LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
records.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_RECORDS_H
10#define LINE_LANG_LAL_RECORDS_H
11
12/**
13 * @file
14 * @ingroup line_lang
15 * LINE Agent Language (LAL): private record constructors of LAL agents (not
16 * part of the public API). Port of python/line_solver/lal/_records.py.
17 *
18 * LAL agents are declared action by action, or obtained by embedding LINE
19 * model objects. These constructors build the same finite agents for LAL's own
20 * internal use: SolverMAM's lowering of embedded Queue and Source nodes into
21 * the level and source agents its recognizers read (mam_lowering.h), the
22 * synthetic marked stream that its traffic fitting substitutes for a source
23 * (mam_reduced.h), and the embedding of MarkovProcess, MarkovChain and
24 * Workflow objects (embed.h). They were public `Agent` factories until
25 * 2026-11-15.
26 */
27
28#include <cmath>
29#include <optional>
30#include <set>
31#include <string>
32#include <vector>
33
39
40namespace line {
41namespace lal {
42namespace detail {
43
44/** Keyword arguments of `Records::queue`. `capacity = nullopt` declares an unbounded queue. */
45struct QueueOptions {
46 std::optional<long> capacity;
47 std::optional<double> service_rate;
48 std::vector<std::string> arrivals;
49 std::optional<NamedWeights> departures;
50 long servers = 1;
51 long initial = 0;
52 std::optional<std::string> service_input;
53 std::optional<std::vector<std::string>> service_inputs;
54 std::optional<std::string> service_phase;
55};
56
57inline bool all_close(const Matrix<double>& a, const Matrix<double>& b, double rtol, double atol) {
58 if (a.rows() != b.rows() || a.cols() != b.cols()) return false;
59 for (std::size_t k = 0; k < a.size(); ++k)
60 if (!(std::abs(a[k] - b[k]) <= atol + rtol * std::abs(b[k]))) return false;
61 return true;
62}
63
64/** The private constructors (`_Records`); a friend of `Agent`. */
65class Records {
66 public:
67 /**
68 * A single-class queue; `capacity = nullopt` is unbounded (`_Records.queue`).
69 * `arrivals` names separate passive inputs; `departures` maps active output
70 * names to fixed routing probabilities summing to one. A full queue
71 * disables its inputs. For an external service clock, leave
72 * `service_rate` unset and give `service_input(s)` and, if needed,
73 * `service_phase`; this mode has one server.
74 */
75 static Agent queue(const std::string& name, const QueueOptions& o) {
76 const bool unbounded = !o.capacity.has_value();
77 long capacity = 0, servers = o.servers, initial = o.initial;
78 std::optional<long> unbounded_initial;
79 if (unbounded) {
80 if (servers < 1) throw value_error("servers must be an integer >= 1");
81 if (servers > 1000) throw value_error("an unbounded queue supports at most 1000 servers");
82 capacity = servers + 1;
83 if (initial < 0) throw value_error("initial must be an integer >= 0");
84 unbounded_initial = initial;
85 initial = std::min(initial, capacity);
86 } else {
87 capacity = *o.capacity;
88 }
89 if (capacity < 1) throw value_error("capacity must be an integer >= 1");
90 if (servers < 1) throw value_error("servers must be an integer >= 1");
91 if (initial < 0) throw value_error("initial must be an integer >= 0");
92 if (initial > capacity) throw value_error("initial cannot exceed capacity");
93 if (o.service_inputs && o.service_input) throw value_error("specify service_input or service_inputs, not both");
94 std::vector<std::string> service_inputs;
95 if (o.service_inputs) {
96 service_inputs = *o.service_inputs;
97 if (service_inputs.empty()) throw value_error("service_inputs must be nonempty");
98 } else if (o.service_input) {
99 service_inputs.push_back(*o.service_input);
100 }
101 double service_rate = 0.0;
102 if (service_inputs.empty()) {
103 if (o.service_phase) throw value_error("service_phase requires service_input");
104 if (!o.service_rate || !std::isfinite(*o.service_rate) || *o.service_rate <= 0)
105 throw value_error("service_rate must be finite and positive");
106 service_rate = *o.service_rate;
107 } else if (o.service_rate || o.departures || servers != 1) {
108 throw value_error("passive service requires service_rate=None, no departures and one server");
109 }
110 const std::vector<std::string>& arrivals = o.arrivals;
111 {
112 std::set<std::string> u(arrivals.begin(), arrivals.end());
113 if (u.size() != arrivals.size()) throw value_error("arrivals must contain distinct action names");
114 }
115 for (const std::string& l : arrivals) identifier(l, "arrival action");
116 NamedWeights departures;
117 if (o.departures) departures = *o.departures;
118 else if (service_inputs.empty()) departures.push_back({"departure", 1.0});
119 if (service_inputs.empty() && departures.empty())
120 throw value_error("departures must map action names to routing probabilities");
122 for (const auto& kv : departures) {
123 identifier(kv.first, "departure action");
124 if (!std::isfinite(kv.second) || kv.second <= 0)
125 throw value_error("routing probabilities must be finite and positive");
126 for (const auto& r : routes)
127 if (r.first == kv.first) throw value_error("Duplicate departure " + kv.first);
128 routes.push_back(kv);
129 }
130 std::vector<std::string> passive_service = service_inputs;
131 if (o.service_phase) passive_service.push_back(*o.service_phase);
132 for (const std::string& l : passive_service) identifier(l, "service action");
133 {
134 std::set<std::string> ps(passive_service.begin(), passive_service.end());
135 bool clash = ps.size() != passive_service.size();
136 for (const std::string& a : arrivals) {
137 if (ps.count(a)) clash = true;
138 for (const auto& r : routes)
139 if (r.first == a) clash = true;
140 }
141 if (clash) throw value_error("arrival and departure action names must be distinct");
142 }
143 if (service_inputs.empty()) {
144 double s = 0.0;
145 for (const auto& r : routes) s += r.second;
146 if (!(std::fabs(s - 1.0) <= 1e-12)) throw value_error("routing probabilities must sum to one");
147 }
148 std::vector<std::string> states;
149 for (long n = 0; n <= capacity; ++n) states.push_back("n_" + std::to_string(n));
150 Agent agent(name, states, states[static_cast<std::size_t>(initial)]);
151 for (long n = 0; n < capacity; ++n)
152 for (const std::string& l : arrivals) agent.passive(states[n], l, states[n + 1]);
153 for (long n = 1; n <= capacity; ++n) {
154 if (!service_inputs.empty()) {
155 for (const std::string& a : service_inputs) agent.passive(states[n], a, states[n - 1]);
156 if (o.service_phase) agent.passive(states[n], *o.service_phase, states[n]);
157 }
158 for (const auto& r : routes)
159 agent.active(states[n], r.first, static_cast<double>(std::min(n, servers)) * service_rate * r.second,
160 states[n - 1]);
161 }
162 QueueInfo qi;
163 if (!unbounded) qi.capacity = capacity;
164 qi.servers = servers;
165 qi.arrivals = arrivals;
166 for (const auto& r : routes) qi.departures.push_back(r.first);
167 qi.service_input = o.service_input;
168 qi.service_inputs = service_inputs;
169 qi.service_phase = o.service_phase;
170 if (service_inputs.empty()) qi.service_rate = service_rate;
171 qi.routes = routes;
172 agent.d_->queue_info = qi;
173 agent.d_->queue_template = agent.d_->transitions;
174 if (unbounded) {
175 agent.d_->unbounded_queue = true;
176 agent.d_->unbounded_initial = unbounded_initial;
177 agent.d_->unbounded_template = agent.d_->transitions;
178 }
179 return agent;
180 }
181
182 /**
183 * Append transitions to a queue agent and keep it recognized as the queue
184 * it was built as (the full-queue loss self-events of the MAM lowering).
185 */
186 static void extend_queue(Agent& agent, const std::vector<Transition>& extra) {
187 agent.d_->transitions.insert(agent.d_->transitions.end(), extra.begin(), extra.end());
188 if (agent.d_->queue_template) agent.d_->queue_template = agent.d_->transitions;
189 if (agent.d_->unbounded_template) agent.d_->unbounded_template = agent.d_->transitions;
190 }
191
192 /** Append one prepared transition (any role, labels or priority) without the public checks. */
193 static void add_transition(Agent& agent, const Transition& t) { agent.d_->transitions.push_back(t); }
194
195 /** Replace the transition list. */
196 static void set_transitions(Agent& agent, const std::vector<Transition>& ts) { agent.d_->transitions = ts; }
197
198 /** Set the initial law over the states without the public checks (the embedding's uniform start). */
199 static void set_initial_distribution(Agent& agent, const std::vector<double>& p) {
200 agent.d_->initial_distribution = p;
201 }
202
203 /** Mark an agent discrete-time (an embedded MarkovChain). */
204 static void set_discrete(Agent& agent, bool discrete) { agent.d_->discrete = discrete; }
205
206 /** A finite agent from an MMAP and its named mark matrices (`_Records.mmap`). */
207 static Agent mmap(const std::string& name, const Matrix<double>& D0, const NamedMatrices& marks,
208 std::size_t initial = 0) {
209 return mmap_impl(name, D0, marks, initial, nullptr);
210 }
211 /** MMAP agent with an initial probability vector. */
212 static Agent mmap(const std::string& name, const Matrix<double>& D0, const NamedMatrices& marks,
213 const std::vector<double>& initial) {
214 return mmap_impl(name, D0, marks, 0, &initial);
215 }
216
217 /** Two independent Poisson inputs paired through bounded unmatched buffers (`buffered_join`). */
218 static Agent buffered_join(const std::string& name, double left_rate, double right_rate, long capacity,
219 const std::string& output = "complete") {
220 if (!std::isfinite(left_rate) || !std::isfinite(right_rate) || left_rate <= 0 || right_rate <= 0)
221 throw value_error("input rates must be finite and positive");
222 mam::Map<double> l{Matrix<double>{{-left_rate}}, Matrix<double>{{left_rate}}};
223 mam::Map<double> r{Matrix<double>{{-right_rate}}, Matrix<double>{{right_rate}}};
224 return buffered_map_join(name, l, r, capacity, output);
225 }
226
227 /** Pair two MAP streams, freezing a whole input at its full buffer (`buffered_map_join`). */
228 static Agent buffered_map_join(const std::string& name, const mam::Map<double>& left,
229 const mam::Map<double>& right, long capacity,
230 const std::string& output = "complete") {
231 if (capacity < 1) throw value_error("capacity must be a positive integer");
232 const double order = static_cast<double>(left.D0.rows()) * right.D0.rows() * (2.0 * capacity + 1);
233 if (order > 512) throw value_error("buffered MAP join exceeds 512 phases");
234 mmap("_LeftValidation", left.D0, {{"arrival", left.D1}});
235 mmap("_RightValidation", right.D0, {{"arrival", right.D1}});
236 mam::Mmap<double> a{left.D0, left.D1, {left.D1}};
237 mam::Mmap<double> b{right.D0, right.D1, {right.D1}};
238 const mam::Mmap<double> m = mam::mmap_max(a, b, static_cast<unsigned>(capacity));
239 return mmap(name, m.D0, {{output, m.D1}});
240 }
241
242 /** Pair two MMAP streams, marking each completion by its later arrival (`buffered_mmap_join`). */
243 static Agent buffered_mmap_join(const std::string& name, const mam::Mmap<double>& left,
244 const mam::Mmap<double>& right, long capacity,
245 const std::vector<std::string>& labels) {
246 if (capacity < 1) throw value_error("capacity must be a positive integer");
247 if (left.Dc.empty() || left.Dc.size() != right.Dc.size())
248 throw value_error("inputs must be M3A lists with matching mark counts");
249 {
250 std::set<std::string> u(labels.begin(), labels.end());
251 if (labels.size() != left.Dc.size() || u.size() != labels.size())
252 throw value_error("labels must contain one distinct name per mark");
253 }
254 const double order = static_cast<double>(left.D0.rows()) * right.D0.rows() * (2.0 * capacity + 1);
255 if (order > 512) throw value_error("buffered MMAP join exceeds 512 phases");
256 for (const mam::Mmap<double>* v : {&left, &right}) {
257 NamedMatrices marks;
258 for (std::size_t k = 0; k < labels.size(); ++k) marks.push_back({labels[k], v->Dc[k]});
259 mmap("_JoinValidation", v->D0, marks);
260 Matrix<double> s(v->D0.rows(), v->D0.cols(), 0.0);
261 for (const Matrix<double>& m : v->Dc)
262 for (std::size_t k = 0; k < s.size(); ++k) s[k] += m[k];
263 bool close = v->D1.rows() == s.rows() && v->D1.cols() == s.cols();
264 for (std::size_t k = 0; close && k < s.size(); ++k)
265 if (!(std::fabs(v->D1[k] - s[k]) <= 1e-12 + 1e-12 * std::fabs(s[k]))) close = false;
266 if (!close) throw value_error("the aggregate mark matrix must equal the sum of the mark matrices");
267 }
268 const mam::Mmap<double> m = mam::mmap_max(left, right, static_cast<unsigned>(capacity));
269 NamedMatrices marks;
270 for (std::size_t k = 0; k < labels.size(); ++k) marks.push_back({labels[k], m.Dc[k]});
271 return mmap(name, m.D0, marks);
272 }
273
274 /** A PH service clock (`ph_service`) with one completion action. */
275 static Agent ph_service(const std::string& name, const std::vector<double>& alpha, const Matrix<double>& T,
276 const std::string& completion = "complete") {
277 return ph_service(name, alpha, T, NamedWeights{{completion, 1.0}});
278 }
279 /** PH service clock with a routing-probability map of completion actions. */
280 static Agent ph_service(const std::string& name, const std::vector<double>& alpha, const Matrix<double>& T,
281 const NamedWeights& completion) {
282 const std::size_t n = alpha.size();
283 bool ok = n > 0 && T.rows() == n && T.cols() == n && all_finite(T);
284 double asum = 0.0;
285 for (double a : alpha) {
286 if (!std::isfinite(a) || a < 0) ok = false;
287 asum += a;
288 }
289 if (!ok || !(std::fabs(asum - 1.0) <= 1e-12))
290 throw value_error("alpha and T must define a finite PH distribution");
291 std::vector<double> exit_rates(n, 0.0);
292 bool bad = false;
293 // Relative to the largest rate, so a slow but valid PH is accepted.
294 const double tscale = std::max(tiny_scale(), max_abs(T));
295 for (std::size_t i = 0; i < n; ++i) {
296 double s = 0.0;
297 for (std::size_t j = 0; j < n; ++j) {
298 s += T(i, j);
299 if (i != j && T(i, j) < 0) bad = true;
300 }
301 if (T(i, i) >= 0) bad = true;
302 exit_rates[i] = -s;
303 if (exit_rates[i] < -1e-12 * tscale) bad = true;
304 }
305 if (bad || !metzler_abscissa_below(scaled_copy(T, 1.0 / tscale), -1e-12))
306 throw value_error("T must be a transient PH subgenerator");
307 for (double& e : exit_rates) e = std::max(e, 0.0);
308 if (completion.empty())
309 throw value_error("completion must be an action name or routing-probability mapping");
310 double psum = 0.0;
311 for (const auto& kv : completion) {
312 identifier(kv.first, "completion action");
313 if (!std::isfinite(kv.second) || kv.second <= 0)
314 throw value_error("completion routing probabilities must be finite and positive");
315 psum += kv.second;
316 }
317 if (!(std::fabs(psum - 1.0) <= 1e-12))
318 throw value_error("completion routing probabilities must sum to one");
319 NamedMatrices marks;
320 for (const auto& kv : completion) {
321 Matrix<double> b(n, n, 0.0);
322 for (std::size_t i = 0; i < n; ++i)
323 for (std::size_t j = 0; j < n; ++j) b(i, j) = exit_rates[i] * alpha[j] * kv.second;
324 marks.push_back({kv.first, b});
325 }
326 return mmap(name, T, marks, alpha);
327 }
328
329 /** From a stationary marked MAP in M3A form (`from_marked_map`); only the per-mark blocks are used. */
330 static Agent from_marked_map(const std::string& name, const mam::Mmap<double>& process,
331 const std::vector<std::string>& labels, std::size_t initial = 0) {
332 return mmap(name, process.D0, marked_blocks(process, labels), initial);
333 }
334 static Agent from_marked_map(const std::string& name, const mam::Mmap<double>& process,
335 const std::vector<std::string>& labels, const std::vector<double>& initial) {
336 return mmap(name, process.D0, marked_blocks(process, labels), initial);
337 }
338
339 /** From a stationary MAP, including MMPP2 (`from_map`). */
340 static Agent from_map(const std::string& name, const mam::Map<double>& process,
341 const std::string& action = "arrival", std::size_t initial = 0) {
342 return mmap(name, process.D0, {{action, process.D1}}, initial);
343 }
344 static Agent from_map(const std::string& name, const mam::Map<double>& process, const std::string& action,
345 const std::vector<double>& initial) {
346 return mmap(name, process.D0, {{action, process.D1}}, initial);
347 }
348
349 /** One finite agent from a CTMC generator and optional event filters (`from_generator`). */
350 static Agent from_generator(const std::string& name, const Matrix<double>& generator,
351 const NamedMatrices& events = NamedMatrices(), std::size_t initial = 0) {
352 return generator_impl(name, generator, events, initial, nullptr);
353 }
354 static Agent from_generator(const std::string& name, const Matrix<double>& generator,
355 const NamedMatrices& events, const std::vector<double>& initial) {
356 return generator_impl(name, generator, events, 0, &initial);
357 }
358
359 /**
360 * One stationary MAP/MMAP process of a LINE network struct
361 * (`from_network_process`). `station` and `jobclass` are zero-based. A
362 * marked source must be imported from its first-mark carrier with one
363 * label per mark; with no labels a MAP is labelled `arrival`.
364 */
365 static Agent from_network_process(const std::string& name, const qn::NetworkStruct<double>& sn,
366 std::size_t station, std::size_t jobclass,
367 const std::optional<std::vector<std::string>>& labels = std::nullopt,
368 std::size_t initial = 0) {
369 if (station >= sn.nstations || jobclass >= sn.nclasses || station >= sn.service.size() ||
370 jobclass >= sn.service[station].size())
371 throw value_error("station or jobclass is absent from the network struct");
372 const lang::Distrib<double>& d = sn.service[station][jobclass];
373 const lang::ProcessType kind = d.type;
374 const bool marked = kind == lang::ProcessType::MMAP || kind == lang::ProcessType::MPH;
375 if (kind != lang::ProcessType::MAP && kind != lang::ProcessType::MMPP2 && !marked)
376 throw value_error(std::string("unsupported network process type ") + lang::process_to_text(kind) +
377 "; expected stationary MAP or MMAP");
378 if (!d.has_map() || d.D1.rows() == 0)
379 throw value_error("network process has no stationary matrix representation");
380 if (marked) {
381 if (sn.markidx_of(station + 1, jobclass + 1) > 1)
382 throw value_error("import a marked source from its first-mark carrier");
383 const std::vector<Matrix<double>>& blocks = d.Dmark;
384 bool ok = !blocks.empty();
385 if (ok) {
386 Matrix<double> total(d.D1.rows(), d.D1.cols(), 0.0);
387 for (const Matrix<double>& b : blocks) {
388 if (b.rows() != total.rows() || b.cols() != total.cols()) {
389 ok = false;
390 break;
391 }
392 for (std::size_t k = 0; k < b.size(); ++k) total[k] += b[k];
393 }
394 ok = ok && all_close(d.D1, total, 1e-12, 1e-12);
395 }
396 if (!ok) throw value_error("invalid M3A aggregate or missing mark matrices");
397 if (!labels) throw value_error("labels must contain one distinct name per mark");
398 const std::set<std::string> unique(labels->begin(), labels->end());
399 if (labels->size() != blocks.size() || unique.size() != labels->size())
400 throw value_error("labels must contain one distinct name per mark");
401 NamedMatrices marks;
402 for (std::size_t k = 0; k < blocks.size(); ++k) marks.push_back({(*labels)[k], blocks[k]});
403 return mmap(name, d.D0, marks, initial);
404 }
405 const std::vector<std::string> l = labels ? *labels : std::vector<std::string>{"arrival"};
406 if (l.size() != 1) throw value_error("a MAP requires exactly one action label");
407 return mmap(name, d.D0, NamedMatrices{{l[0], d.D1}}, initial);
408 }
409
410 private:
411 static NamedMatrices marked_blocks(const mam::Mmap<double>& process, const std::vector<std::string>& labels) {
412 std::set<std::string> u(labels.begin(), labels.end());
413 if (labels.size() != process.Dc.size() || u.size() != labels.size())
414 throw value_error("labels must contain one distinct name per mark");
415 NamedMatrices marks;
416 for (std::size_t k = 0; k < labels.size(); ++k) marks.push_back({labels[k], process.Dc[k]});
417 return marks;
418 }
419
420 static Agent mmap_impl(const std::string& name, const Matrix<double>& d0, const NamedMatrices& marks,
421 std::size_t initial, const std::vector<double>* initial_vec) {
422 if (d0.rows() == 0 || d0.rows() != d0.cols()) throw value_error("D0 must be a nonempty square matrix");
423 if (!all_finite(d0)) throw value_error("D0 must be finite");
424 const std::size_t n = d0.rows();
425 std::size_t initial_index = initial;
426 if (!initial_vec) {
427 if (initial >= n) throw value_error("initial must be a valid zero-based phase index");
428 } else {
429 if (!is_probability(*initial_vec, n)) throw value_error("initial must be a valid probability vector");
430 initial_index = first_positive(*initial_vec);
431 }
432 if (marks.empty()) throw value_error("marks must be a nonempty mapping of names to matrices");
433 Matrix<double> off = d0;
434 for (std::size_t i = 0; i < n; ++i) off(i, i) = 0.0;
435 for (std::size_t i = 0; i < n; ++i)
436 for (std::size_t j = 0; j < n; ++j)
437 if (off(i, j) < 0 || d0(i, i) > 0)
438 throw value_error("D0 requires nonnegative off-diagonals and nonpositive diagonals");
439 std::set<std::string> seen;
440 Matrix<double> total = d0;
441 for (const auto& kv : marks) {
442 identifier(kv.first, "mark name");
443 if (kv.first == "_phase") throw value_error("mark name _phase is reserved for internal phase changes");
444 if (!seen.insert(kv.first).second) throw value_error("Duplicate mark " + kv.first);
445 const Matrix<double>& b = kv.second;
446 bool ok = b.rows() == n && b.cols() == n && all_finite(b);
447 for (std::size_t k = 0; ok && k < b.size(); ++k)
448 if (b[k] < 0) ok = false;
449 if (!ok) throw value_error("mark " + kv.first + " must be a finite nonnegative matrix of D0 order");
450 for (std::size_t k = 0; k < b.size(); ++k) total[k] += b[k];
451 }
452 const double scale = std::max({tiny_scale(), max_abs(total), max_abs(d0)});
453 for (std::size_t i = 0; i < n; ++i) {
454 double s = 0.0;
455 for (std::size_t j = 0; j < n; ++j) s += total(i, j);
456 if (!(std::fabs(s) <= 1e-12 * scale)) throw value_error("D0 plus mark matrices must have zero row sums");
457 }
458 std::vector<std::string> states;
459 for (std::size_t i = 0; i < n; ++i) states.push_back("phase_" + std::to_string(i));
460 Agent agent(name, states, states[initial_index]);
461 if (initial_vec) agent.d_->initial_distribution = *initial_vec;
462 for (std::size_t i = 0; i < n; ++i)
463 for (std::size_t j = 0; j < n; ++j)
464 if (off(i, j) != 0) agent.active(states[i], "_phase", off(i, j), states[j]);
465 for (const auto& kv : marks) {
466 if (!any_nonzero(kv.second)) {
467 // an all-zero mark keeps its label as a zero-rate placeholder
468 Transition t;
469 t.source = states[0];
470 t.action = kv.first;
471 t.role = Role::Active;
472 t.value = 0.0;
473 t.target = states[0];
474 agent.d_->transitions.push_back(t);
475 }
476 for (std::size_t i = 0; i < n; ++i)
477 for (std::size_t j = 0; j < n; ++j)
478 if (kv.second(i, j) != 0) agent.active(states[i], kv.first, kv.second(i, j), states[j]);
479 }
480 return agent;
481 }
482
483 static Agent generator_impl(const std::string& name, const Matrix<double>& q, const NamedMatrices& events,
484 std::size_t initial, const std::vector<double>* initial_vec) {
485 if (q.rows() == 0 || q.rows() != q.cols() || !all_finite(q))
486 throw value_error("generator must be a finite nonempty square matrix");
487 const std::size_t n = q.rows();
488 const double tolerance = 1e-12 * std::max(tiny_scale(), max_abs(q));
489 Matrix<double> off = q;
490 for (std::size_t i = 0; i < n; ++i) off(i, i) = 0.0;
491 for (std::size_t i = 0; i < n; ++i) {
492 double s = 0.0;
493 for (std::size_t j = 0; j < n; ++j) {
494 s += q(i, j);
495 if (off(i, j) < -tolerance)
496 throw value_error("generator must have nonnegative off-diagonals and zero row sums");
497 }
498 if (q(i, i) > tolerance || std::fabs(s) > tolerance)
499 throw value_error("generator must have nonnegative off-diagonals and zero row sums");
500 }
501 for (std::size_t k = 0; k < off.size(); ++k) off[k] = std::max(off[k], 0.0);
502 NamedMatrices blocks;
503 std::set<std::string> seen;
504 Matrix<double> labelled(n, n, 0.0);
505 for (const auto& kv : events) {
506 identifier(kv.first, "action name");
507 if (kv.first == "_internal") throw value_error("action name _internal is reserved");
508 if (!seen.insert(kv.first).second) throw value_error("Duplicate event " + kv.first);
509 const Matrix<double>& b = kv.second;
510 bool ok = b.rows() == n && b.cols() == n && all_finite(b);
511 for (std::size_t k = 0; ok && k < b.size(); ++k)
512 if (b[k] < 0) ok = false;
513 if (!ok) throw value_error("event " + kv.first + " must be a finite nonnegative matrix of generator order");
514 blocks.push_back(kv);
515 for (std::size_t k = 0; k < b.size(); ++k) labelled[k] += b[k];
516 }
517 for (std::size_t i = 0; i < n; ++i) labelled(i, i) = 0.0;
518 Matrix<double> remainder(n, n, 0.0);
519 for (std::size_t k = 0; k < off.size(); ++k) {
520 remainder[k] = off[k] - labelled[k];
521 if (remainder[k] < -tolerance) throw value_error("event filters exceed the generator; filters may overlap");
522 remainder[k] = std::max(remainder[k], 0.0);
523 }
524 std::vector<std::string> states;
525 for (std::size_t i = 0; i < n; ++i) states.push_back("state_" + std::to_string(i));
526 std::size_t initial_index = initial;
527 if (!initial_vec) {
528 if (initial >= n) throw value_error("initial must be a valid zero-based state index");
529 } else {
530 if (!is_probability(*initial_vec, n)) throw value_error("initial must be a valid probability vector");
531 initial_index = first_positive(*initial_vec);
532 }
533 Agent agent(name, states, states[initial_index]);
534 if (initial_vec) agent.d_->initial_distribution = *initial_vec;
535 if (any_nonzero(remainder)) blocks.push_back({"_internal", remainder});
536 for (const auto& kv : blocks) {
537 if (!any_nonzero(kv.second)) {
538 Transition t;
539 t.source = states[0];
540 t.action = kv.first;
541 t.role = Role::Active;
542 t.value = 0.0;
543 t.target = states[0];
544 agent.d_->transitions.push_back(t);
545 }
546 for (std::size_t i = 0; i < n; ++i)
547 for (std::size_t j = 0; j < n; ++j)
548 if (kv.second(i, j) != 0) agent.active(states[i], kv.first, kv.second(i, j), states[j]);
549 }
550 return agent;
551 }
552};
553
554} // namespace detail
555} // namespace lal
556} // namespace line
557
558#endif // LINE_LANG_LAL_RECORDS_H
LINE Agent Language (LAL): programmatic construction of finite agents and their composition,...
Enumerations and the minimal distribution descriptor shared by the model layer of the C++ port.
Maximum of two independent MAPs, and its marked k-stage generalization.
Markovian arrival process descriptors: stationary vectors, rate, moments, autocorrelation and the ind...
Marked MAP (MMAP) algebra: per-class rates, class probabilities, superposition, normalization and sca...
std::vector< Route > routes(const qn::NetworkStruct< T > &sn)
Definition code_gen.h:246
Definition ag.h:49
std::vector< std::pair< std::string, double > > NamedWeights
Definition builder.h:77
InputError value_error(const std::string &what)
LINE:input:Unspecified, the C++ spelling of the Python ValueError raised throughout LAL.
Definition core.h:85
std::vector< std::pair< std::string, Matrix< double > > > NamedMatrices
Definition builder.h:76
Mmap< T > mmap_max(const Mmap< T > &a, const Mmap< T > &b, unsigned k)
MMAP of the maximum over k synchronization rounds of two independent MMAPs.
Definition map_max.h:88
double max_abs(const Vec &a)
Definition spn_ispn.h:139
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
A queueing network and its refreshed NetworkStruct.
A MAP as the pair of matrices (D0, D1).
Definition map_moment.h:53
An MMAP: the underlying MAP plus the per-class arrival matrices.
Definition mmap_lambda.h:45