LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
builder.h
Go to the documentation of this file.
1/*
2 * Copyright (c) 2012-2026, QORE Lab, Imperial College London
3 * All rights reserved.
4 */
5#ifndef LINE_LANG_LAL_BUILDER_H
6#define LINE_LANG_LAL_BUILDER_H
7
8/**
9 * @file
10 * @ingroup line_lang
11 * LINE Agent Language (LAL): programmatic construction of finite agents and
12 * their composition, plus the `.lal` text parser.
13 *
14 * Port of python/line_solver/lal/builder.py and the Parser of core.py.
15 * `Agent` is a HANDLE (shared ownership) so that, as in Python, an agent added
16 * to a Composition can still be modified and the change is seen by the next
17 * `get_struct()`; `ActionRef` compares agents by identity.
18 *
19 * An agent is declared action by action: by named states with `active`,
20 * `passive` and `immediate`, or by typed variables (`Agent::with_vars`) with
21 * guarded `command`s. A Composition holds such agents and EMBEDDED LINE models
22 * (`add`): a Network, Environment, LayeredNetwork (LQN2QN), MarkovProcess,
23 * MarkovChain or Workflow, each node of a network being an agent whose
24 * actions are named `Node.EVENT[class]` (`action`). The embedding itself lives
25 * in embed.h, which this header includes at its foot.
26 *
27 * The family factories of earlier releases (queue, MMAP, PH service, MAP and
28 * generator agents, LINE-object adapters) are not public any more; LAL's own
29 * matrix-analytic lowering builds those agents through `detail::Records`
30 * (records.h).
31 */
32
33#include <cmath>
34#include <fstream>
35#include <functional>
36#include <limits>
37#include <map>
38#include <memory>
39#include <optional>
40#include <regex>
41#include <set>
42#include <sstream>
43#include <stdexcept>
44#include <string>
45#include <type_traits>
46#include <utility>
47#include <vector>
48
49#include "line/lang/lal/core.h"
51#include "line/util/lu.h"
52
53namespace line {
54
55namespace env {
56template <class T>
57class Environment;
58}
59namespace lqn {
60template <class T>
61struct LqnModel;
62}
63namespace lang {
64namespace processes {
65template <class T>
66struct MarkovChainModel;
67}
68} // namespace lang
69namespace workflow {
70template <class T>
71class Workflow;
72}
73
74namespace lal {
75
76typedef std::vector<std::pair<std::string, Matrix<double>>> NamedMatrices;
77typedef std::vector<std::pair<std::string, double>> NamedWeights;
78
79/** The valuation of the typed variables of an agent (`v` in a guard, update or rate). */
80typedef std::map<std::string, long> Vars;
81
82namespace detail {
83
84inline const std::string& identifier(const std::string& value, const std::string& kind) {
85 if (!is_identifier(value)) throw value_error(kind + " must be a valid LAL identifier");
86 return value;
87}
88
89inline bool all_finite(const Matrix<double>& m) {
90 for (std::size_t k = 0; k < m.size(); ++k)
91 if (!std::isfinite(m[k])) return false;
92 return true;
93}
94
95inline bool any_nonzero(const Matrix<double>& m) {
96 for (std::size_t k = 0; k < m.size(); ++k)
97 if (m[k] != 0) return true;
98 return false;
99}
100
101inline double max_abs(const Matrix<double>& m) {
102 double r = 0.0;
103 for (std::size_t k = 0; k < m.size(); ++k) r = std::max(r, std::fabs(m[k]));
104 return r;
105}
106
107/** Smallest positive normal double: the floor of a relative tolerance scale. */
108inline double tiny_scale() { return std::numeric_limits<double>::min(); }
109
110/** A copy of m multiplied by f. */
111inline Matrix<double> scaled_copy(const Matrix<double>& m, double f) {
112 Matrix<double> r = m;
113 for (std::size_t k = 0; k < r.size(); ++k) r[k] *= f;
114 return r;
115}
116
117/** A valid probability vector of length n (finite, nonnegative, sum 1 within 1e-12). */
118inline bool is_probability(const std::vector<double>& p, std::size_t n) {
119 if (p.size() != n) return false;
120 double s = 0.0;
121 for (double x : p) {
122 if (!std::isfinite(x) || x < 0) return false;
123 s += x;
124 }
125 return std::fabs(s - 1.0) <= 1e-12;
126}
127
128inline std::size_t first_positive(const std::vector<double>& p) {
129 for (std::size_t i = 0; i < p.size(); ++i)
130 if (p[i] > 0) return i;
131 return 0;
132}
133
134/**
135 * Whether every eigenvalue of a Metzler matrix T (nonnegative off-diagonal)
136 * has real part strictly below s, i.e. whether its spectral abscissa is < s.
137 *
138 * sI - T is a Z-matrix, and a Z-matrix is a nonsingular M-matrix exactly when
139 * all its leading principal minors are positive (Berman and Plemmons, Thm
140 * 6.2.3), which is exactly when Gaussian elimination WITHOUT pivoting meets
141 * only positive pivots. sI - T is a nonsingular M-matrix exactly when every
142 * eigenvalue of T has real part below s. The test is finite and exact up to
143 * rounding, and holds for a REDUCIBLE T: a power iteration does not, since its
144 * Collatz-Wielandt bounds need not meet on a reducible matrix (the block
145 * [[-1,1,0],[1,-1,0],[0,0,-5]] has abscissa 0 but was read as transient).
146 */
147inline bool metzler_abscissa_below(const Matrix<double>& T, double s) {
148 const std::size_t n = T.rows();
149 Matrix<double> A(n, n, 0.0);
150 for (std::size_t i = 0; i < n; ++i)
151 for (std::size_t j = 0; j < n; ++j) A(i, j) = (i == j ? s : 0.0) - T(i, j);
152 for (std::size_t k = 0; k < n; ++k) {
153 const double p = A(k, k);
154 if (!(p > 0.0)) return false;
155 for (std::size_t i = k + 1; i < n; ++i) {
156 const double l = A(i, k) / p;
157 if (l == 0.0) continue;
158 for (std::size_t j = k + 1; j < n; ++j) A(i, j) -= l * A(k, j);
159 }
160 }
161 return true;
162}
163
164/**
165 * Spectral abscissa of a Metzler matrix T, the real Perron root of T + cI
166 * shifted back. It lies between max_i T(i,i) and the largest row sum, and is
167 * found by bisection on `metzler_abscissa_below`, so it is right for a
168 * reducible T as well. A DECISION against a threshold should call
169 * `metzler_abscissa_below` directly rather than compare this value.
170 */
171inline double metzler_abscissa(const Matrix<double>& T) {
172 const std::size_t n = T.rows();
173 if (n == 0) return -std::numeric_limits<double>::infinity();
174 double lo = -std::numeric_limits<double>::infinity(), rowmax = -std::numeric_limits<double>::infinity();
175 for (std::size_t i = 0; i < n; ++i) {
176 lo = std::max(lo, T(i, i));
177 double r = 0.0;
178 for (std::size_t j = 0; j < n; ++j) r += T(i, j);
179 rowmax = std::max(rowmax, r);
180 }
181 double hi = std::max(rowmax, lo) + 1.0 + std::fabs(rowmax);
182 for (int it = 0; it < 400; ++it) {
183 if (hi - lo <= 1e-15 * std::max(1.0, std::max(std::fabs(lo), std::fabs(hi)))) break;
184 const double mid = 0.5 * (lo + hi);
185 if (metzler_abscissa_below(T, mid))
186 hi = mid;
187 else
188 lo = mid;
189 }
190 return 0.5 * (lo + hi);
191}
192
193/** Python's `str(tuple)` of a typed-variable valuation: `(0,)`, `(0, 1)`. */
194inline std::string valuation_name(const std::vector<long>& v) {
195 std::string s = "(";
196 for (std::size_t i = 0; i < v.size(); ++i) s += (i ? ", " : "") + std::to_string(v[i]);
197 if (v.size() == 1) s += ",";
198 return s + ")";
199}
200
201class Records;
202struct Lowering;
203
204} // namespace detail
205
206class Agent;
207
208/** A named action belonging to a particular agent instance. */
209struct ActionRef;
210
211/**
212 * A rate or weight of a guarded command: a number, a function `f(v)` of the
213 * agent's own variables, or a function `f(v, view)` that also reads other
214 * agents through the joint-state view (a functional rate).
215 */
217 double constant = 0.0;
218 std::function<double(const Vars&)> local;
219 std::function<double(const Vars&, const StateView&)> joint;
220
221 template <class N, typename std::enable_if<std::is_arithmetic<N>::value, int>::type = 0>
222 CommandValue(N v) : constant(static_cast<double>(v)) {}
223 template <class F, typename std::enable_if<!std::is_arithmetic<F>::value &&
224 std::is_invocable_r<double, F, const Vars&, const StateView&>::value,
225 int>::type = 0>
226 CommandValue(F f) : joint(std::move(f)) {}
227 template <class F, typename std::enable_if<!std::is_arithmetic<F>::value &&
228 !std::is_invocable_r<double, F, const Vars&, const StateView&>::value &&
229 std::is_invocable_r<double, F, const Vars&>::value,
230 int>::type = 0>
231 CommandValue(F f) : local(std::move(f)) {}
232};
233
234/** Keyword arguments of `Agent::command`. */
237 std::optional<CommandValue> rate; ///< role Active: required
238 std::optional<CommandValue> weight; ///< role Passive or Immediate: default 1
239 std::function<bool(const Vars&)> guard;
240 /** The variables the command changes; an empty function changes none. */
241 std::function<Vars(const Vars&)> update;
242 int priority = 0;
243 std::string label;
244};
245
246namespace detail {
247struct Command {
248 std::string action;
249 Role role = Role::Active;
250 CommandValue value = CommandValue(1.0);
251 std::function<bool(const Vars&)> guard;
252 std::function<Vars(const Vars&)> update;
253 int priority = 0;
254 std::string label;
255};
256
257struct AgentData {
258 std::string name;
259 std::vector<std::string> states;
260 std::string initial;
261 std::optional<std::vector<double>> initial_distribution;
262 std::vector<Transition> transitions;
263 std::optional<QueueInfo> queue_info;
264 std::optional<std::vector<Transition>> queue_template;
265 bool unbounded_queue = false;
266 std::optional<long> unbounded_initial;
267 std::optional<std::vector<Transition>> unbounded_template;
268 bool discrete = false;
269 /** Typed-variable declaration: domains in declaration order, the initial valuation and the commands. */
270 bool has_vars = false;
271 std::vector<std::pair<std::string, std::vector<long>>> vars;
272 std::vector<long> initial_vars;
273 std::vector<Command> commands;
274};
275} // namespace detail
276
277/**
278 * A finite-state agent with active, weighted passive and immediate transitions
279 * (handle semantics).
280 *
281 * Declare its states by name (`Agent(name, states, initial)`) and add
282 * transitions with `active`/`passive`/`immediate`, or declare typed variables
283 * (`Agent::with_vars`) and add guarded `command`s; the local state is then the
284 * tuple of variable values, enumerated from the initial valuation.
285 */
286class Agent {
287 public:
288 Agent(const std::string& name, const std::vector<std::string>& states, const std::string& initial)
289 : d_(std::make_shared<detail::AgentData>()) {
290 d_->name = detail::identifier(name, "agent name");
291 for (const std::string& s : states) d_->states.push_back(detail::identifier(s, "state name"));
292 std::set<std::string> u(d_->states.begin(), d_->states.end());
293 if (d_->states.empty() || u.size() != d_->states.size())
294 throw value_error("states must be nonempty and unique");
295 if (!u.count(initial)) throw value_error("initial state must belong to the agent");
296 d_->initial = initial;
297 }
298
299 /**
300 * A typed-variable agent (`Agent(name, vars={...}, initial={...})`): `vars`
301 * maps each variable, in order, to its finite domain of distinct values;
302 * `initial` gives every variable a value in its domain.
303 */
304 static Agent with_vars(const std::string& name, const std::vector<std::pair<std::string, std::vector<long>>>& vars,
305 const Vars& initial) {
306 Agent a;
307 a.d_ = std::make_shared<detail::AgentData>();
308 a.d_->name = detail::identifier(name, "agent name");
309 if (vars.empty()) throw value_error("vars must map variable names to finite domains");
310 std::set<std::string> names;
311 for (const auto& v : vars) {
312 detail::identifier(v.first, "variable name");
313 const std::set<long> u(v.second.begin(), v.second.end());
314 if (v.second.empty() || u.size() != v.second.size())
315 throw value_error("variable " + v.first + " needs a nonempty domain of distinct values");
316 if (!names.insert(v.first).second)
317 throw value_error("variable " + v.first + " needs a nonempty domain of distinct values");
318 }
319 std::set<std::string> given;
320 for (const auto& kv : initial) given.insert(kv.first);
321 if (given != names) throw value_error("initial must give a value to every variable");
322 for (const auto& v : vars)
323 if (std::find(v.second.begin(), v.second.end(), initial.at(v.first)) == v.second.end())
324 throw value_error("initial value of " + v.first + " is outside its domain");
325 a.d_->has_vars = true;
326 a.d_->vars = vars;
327 for (const auto& v : vars) a.d_->initial_vars.push_back(initial.at(v.first));
328 return a;
329 }
330
331 const std::string& name() const { return d_->name; }
332 const std::vector<std::string>& states() const { return d_->states; }
333 const std::string& initial() const { return d_->initial; }
334 const std::vector<Transition>& transitions() const { return d_->transitions; }
335 const std::optional<std::vector<double>>& initial_distribution() const { return d_->initial_distribution; }
336 const std::optional<QueueInfo>& queue_info() const { return d_->queue_info; }
337 bool unbounded_queue() const { return d_->unbounded_queue; }
338 bool has_vars() const { return d_->has_vars; }
339 bool same(const Agent& o) const { return d_ == o.d_; }
340
341 /**
342 * Add a timed action at `rate`. `priority` orders the timed actions of
343 * this agent: an action is disabled while one of the same agent with a
344 * higher priority is enabled. `label` (nonempty) aliases the event label.
345 */
346 Agent& active(const std::string& source, const std::string& action, double rate, const std::string& target,
347 const std::optional<std::string>& label = std::nullopt, int priority = 0) {
348 return add(source, action, rate, ValueFn(), target, Role::Active, priority, label);
349 }
350 /** A timed action whose rate is a function of the joint state. */
351 Agent& active(const std::string& source, const std::string& action, ValueFn rate, const std::string& target,
352 const std::optional<std::string>& label = std::nullopt, int priority = 0) {
353 return add(source, action, 0.0, std::move(rate), target, Role::Active, priority, label);
354 }
355 /** Add a passive reaction, chosen in proportion to `weight` among the enabled ones. */
356 Agent& passive(const std::string& source, const std::string& action, const std::string& target,
357 double weight = 1.0) {
358 return add(source, action, weight, ValueFn(), target, Role::Passive, 0, std::nullopt);
359 }
360 Agent& passive(const std::string& source, const std::string& action, const std::string& target, ValueFn weight) {
361 return add(source, action, 0.0, std::move(weight), target, Role::Passive, 0, std::nullopt);
362 }
363 /**
364 * Add a zero-time action. Immediate actions have maximal progress: in a
365 * state where any is enabled, only those of the highest `priority` fire,
366 * chosen in proportion to `weight`, and timed actions wait. The vanishing
367 * states this creates are eliminated by the solvers.
368 */
369 Agent& immediate(const std::string& source, const std::string& action, const std::string& target,
370 double weight = 1.0, int priority = 0, const std::optional<std::string>& label = std::nullopt) {
371 return add(source, action, weight, ValueFn(), target, Role::Immediate, priority, label);
372 }
373 Agent& immediate(const std::string& source, const std::string& action, const std::string& target, ValueFn weight,
374 int priority = 0, const std::optional<std::string>& label = std::nullopt) {
375 return add(source, action, 0.0, std::move(weight), target, Role::Immediate, priority, label);
376 }
377
378 /** Reference an existing action (a transition or a command) for synchronisation. */
379 ActionRef action(const std::string& name) const;
380
381 /** Start the agent from a law over its states, a vector in state order. */
382 Agent& set_initial_distribution(const std::vector<double>& p) {
383 if (d_->has_vars) throw value_error("a typed-variable agent starts from its initial valuation");
384 if (!detail::is_probability(p, d_->states.size()))
385 throw value_error("the initial distribution of " + d_->name +
386 " must be a probability vector over its states");
387 d_->initial_distribution = p;
388 d_->initial = d_->states[detail::first_positive(p)];
389 return *this;
390 }
391 /** Start the agent from a law over its states, by state name (missing states have probability 0). */
392 Agent& set_initial_distribution(const std::map<std::string, double>& p) {
393 if (d_->has_vars) throw value_error("a typed-variable agent starts from its initial valuation");
394 for (const auto& kv : p)
395 if (std::find(d_->states.begin(), d_->states.end(), kv.first) == d_->states.end())
396 throw value_error("unknown state in the initial distribution of " + d_->name);
397 std::vector<double> v;
398 for (const std::string& s : d_->states) {
399 auto it = p.find(s);
400 v.push_back(it == p.end() ? 0.0 : it->second);
401 }
402 return set_initial_distribution(v);
403 }
404 Agent& setInitialDistribution(const std::vector<double>& p) { return set_initial_distribution(p); }
405 Agent& setInitialDistribution(const std::map<std::string, double>& p) { return set_initial_distribution(p); }
406
407 /**
408 * Add a guarded command to a typed-variable agent (`command`). `guard(v)`
409 * and `update(v)` take the agent's variables; `update` returns the
410 * variables it changes. A command is disabled where its guard is false or
411 * its update leaves a domain.
412 */
413 Agent& command(const std::string& action, const CommandOptions& o) {
414 if (!d_->has_vars) throw value_error("command() applies to agents declared with vars; use active/passive/immediate");
415 detail::identifier(action, "action name");
416 detail::Command c;
417 c.action = action;
418 c.role = o.role;
419 if (o.role == Role::Active) {
420 if (!o.rate) throw value_error("an active command needs a rate");
421 c.value = *o.rate;
422 } else {
423 c.value = o.weight ? *o.weight : CommandValue(1.0);
424 }
425 c.guard = o.guard;
426 c.update = o.update;
427 c.priority = o.priority;
428 c.label = o.label;
429 d_->commands.push_back(c);
430 return *this;
431 }
432 /** `command(action, rate, guard, update[, role, priority, label])`; for a non-active role `value` is the weight. */
433 Agent& command(const std::string& action, const CommandValue& value, std::function<bool(const Vars&)> guard,
434 std::function<Vars(const Vars&)> update, Role role = Role::Active, int priority = 0,
435 const std::string& label = std::string()) {
437 o.role = role;
438 if (role == Role::Active)
439 o.rate = value;
440 else
441 o.weight = value;
442 o.guard = std::move(guard);
443 o.update = std::move(update);
444 o.priority = priority;
445 o.label = label;
446 return command(action, o);
447 }
448
449 /** `n` copies of `prototype` named `<name>_0` ... `<name>_{n-1}`, labels suffixed `[i]` (`Agent.array`). */
450 static std::vector<Agent> array(const Agent& prototype, long n) {
451 if (n < 1) throw value_error("n must be a positive integer");
452 std::vector<Agent> copies;
453 for (long i = 0; i < n; ++i) {
454 Agent clone;
455 clone.d_ = std::make_shared<detail::AgentData>(*prototype.d_);
456 clone.d_->name = detail::identifier(prototype.name() + "_" + std::to_string(i), "agent name");
457 const std::string suffix = "[" + std::to_string(i) + "]";
458 for (Transition& t : clone.d_->transitions)
459 for (std::string& l : t.label) l += suffix;
460 for (detail::Command& c : clone.d_->commands)
461 if (!c.label.empty()) c.label += suffix;
462 copies.push_back(clone);
463 }
464 return copies;
465 }
466
467 /** The immutable record (`_record`); a typed-variable agent is expanded from its initial valuation. */
469 if (d_->has_vars) return expand_vars();
470 if (d_->unbounded_queue && d_->unbounded_template && d_->transitions != *d_->unbounded_template)
471 throw value_error("Unbounded queue transitions cannot be modified directly.");
472 AgentRecord r;
473 r.name = d_->name;
474 r.states = d_->states;
475 r.initial = d_->initial;
476 r.transitions = d_->transitions;
477 r.initial_distribution = d_->initial_distribution;
478 r.unbounded_queue = d_->unbounded_queue;
479 r.unbounded_initial = d_->unbounded_initial;
480 if (d_->queue_info && d_->queue_template && d_->transitions == *d_->queue_template)
481 r.queue_info = d_->queue_info;
482 r.discrete = d_->discrete;
483 return r;
484 }
485
486 /** Rebuild a builder agent from a parsed record (as Composition.from_string does). */
487 static Agent from_record(const AgentRecord& value) {
488 Agent agent(value.name, value.states, value.initial);
489 agent.d_->transitions = value.transitions;
490 agent.d_->initial_distribution = value.initial_distribution;
491 return agent;
492 }
493
494 private:
495 friend class Composition;
496 friend class detail::Records;
497 std::shared_ptr<detail::AgentData> d_;
498
499 Agent() {}
500
501 Agent& add(const std::string& source, const std::string& action, double value, ValueFn fn,
502 const std::string& target, Role role, int priority, const std::optional<std::string>& label) {
503 if (d_->has_vars) throw value_error("Unknown state in " + d_->name);
504 detail::identifier(action, "action name");
505 if (std::find(d_->states.begin(), d_->states.end(), source) == d_->states.end() ||
506 std::find(d_->states.begin(), d_->states.end(), target) == d_->states.end())
507 throw value_error("Unknown state in " + d_->name);
508 // no label is the default `agent.action`; an EMPTY label is refused (builder.py `_add`)
509 if (label && label->empty()) throw value_error("an action label must be a nonempty string");
510 if (!fn && (!std::isfinite(value) || value <= 0))
511 throw value_error("Rates and weights must be finite and positive");
512 Transition t;
513 t.source = source;
514 t.action = action;
515 t.role = role;
516 t.value = fn ? 0.0 : value;
517 t.target = target;
518 t.priority = priority;
519 if (label) t.label.push_back(*label);
520 t.fn = std::move(fn);
521 d_->transitions.push_back(t);
522 return *this;
523 }
524
525 /** Enumerate the reachable valuations and expand commands into transitions (`_expand_vars`). */
526 AgentRecord expand_vars() const {
527 std::vector<std::string> names;
528 for (const auto& v : d_->vars) names.push_back(v.first);
529 auto as_vars = [&](const std::vector<long>& state) {
530 Vars v;
531 for (std::size_t i = 0; i < names.size(); ++i) v[names[i]] = state[i];
532 return v;
533 };
534 auto in_domain = [&](const Vars& v) {
535 for (const auto& d : d_->vars)
536 if (std::find(d.second.begin(), d.second.end(), v.at(d.first)) == d.second.end()) return false;
537 return true;
538 };
539 struct Raw {
540 std::vector<long> source, target;
541 const detail::Command* cmd;
542 double value;
543 ValueFn fn;
544 };
545 std::vector<std::vector<long>> states{d_->initial_vars};
546 std::map<std::vector<long>, std::size_t> seen{{d_->initial_vars, 0}};
547 std::vector<Raw> raw;
548 for (std::size_t k = 0; k < states.size(); ++k) {
549 const std::vector<long> state = states[k];
550 const Vars v = as_vars(state);
551 for (const detail::Command& c : d_->commands) {
552 if (c.guard && !c.guard(v)) continue;
553 Vars changes = c.update ? c.update(v) : Vars();
554 for (const auto& kv : changes)
555 if (!v.count(kv.first))
556 throw value_error("the update of " + d_->name + "." + c.action +
557 " must return a dict of its variables");
558 Vars nxt = v;
559 for (const auto& kv : changes) nxt[kv.first] = kv.second;
560 if (!in_domain(nxt)) continue;
561 Raw r;
562 r.source = state;
563 for (const std::string& n : names) r.target.push_back(nxt.at(n));
564 r.cmd = &c;
565 r.value = 0.0;
566 if (c.value.joint) {
567 const std::function<double(const Vars&, const StateView&)> f = c.value.joint;
568 const Vars local = v;
569 r.fn = [f, local](const StateView& view) { return f(local, view); };
570 } else if (c.value.local) {
571 const double val = c.value.local(v);
572 if (!std::isfinite(val) || val < 0)
573 throw value_error(d_->name + "." + c.action +
574 ": rates and weights must be finite and nonnegative");
575 if (val == 0) continue;
576 r.value = val;
577 } else {
578 r.value = c.value.constant;
579 }
580 raw.push_back(r);
581 if (!seen.count(r.target)) {
582 seen[r.target] = states.size();
583 states.push_back(r.target);
584 }
585 }
586 }
587 AgentRecord rec;
588 rec.name = d_->name;
589 for (const auto& s : states) rec.states.push_back(detail::valuation_name(s));
590 rec.initial = detail::valuation_name(d_->initial_vars);
591 for (const Raw& r : raw) {
592 Transition t;
593 t.source = detail::valuation_name(r.source);
594 t.action = r.cmd->action;
595 t.role = r.cmd->role;
596 t.value = r.value;
597 t.target = detail::valuation_name(r.target);
598 t.priority = r.cmd->priority;
599 if (!r.cmd->label.empty()) t.label.push_back(r.cmd->label);
600 t.fn = r.fn;
601 rec.transitions.push_back(t);
602 }
603 rec.var_names = names;
604 rec.var_values = states;
605 return rec;
606 }
607};
608
609struct ActionRef {
611 std::string name;
612};
613
614inline ActionRef Agent::action(const std::string& name) const {
615 detail::identifier(name, "action name");
616 bool any = false;
617 for (const Transition& t : d_->transitions)
618 if (t.action == name) any = true;
619 for (const detail::Command& c : d_->commands)
620 if (c.action == name) any = true;
621 if (!any) throw value_error("Unknown action " + d_->name + "." + name);
622 return ActionRef{*this, name};
623}
624
625/**
626 * An action of a node of an embedded LINE model (`NodeRef`): `key` is the
627 * `(node, EventType, class | mode)` key, `part` the name of the embedded part
628 * that owns the node.
629 */
630struct NodeRef {
631 std::string part;
633};
634
635/** Keyword arguments of `Composition::add` for an embedded LINE model. */
637 /** Names the embedded part; required when two parts would share node names. */
638 std::string prefix;
639 /** Bounds open classes as SolverCTMC's cutoff does. */
640 std::optional<double> cutoff;
641};
642
643struct ActionSpec;
644
645Model parse(const std::string& source);
646
647/**
648 * A collection of agents and embedded LINE models with atomic
649 * synchronisations (`Composition`). Changes to agents are reflected on the
650 * next `get_struct()`; an embedded model is re-read after `refresh()`.
651 *
652 * An embedded LINE model is held by reference when added as a `qn::Network`
653 * lvalue (so `refresh()` sees later edits), and must outlive the composition.
654 */
656 public:
657 Composition() : Composition(std::string("LAL"), std::vector<Agent>()) {}
658 explicit Composition(const std::string& name) : Composition(name, std::vector<Agent>()) {}
659 explicit Composition(const char* name) : Composition(std::string(name), std::vector<Agent>()) {}
660 explicit Composition(const std::vector<Agent>& agents) : Composition(std::string("LAL"), agents) {}
661 Composition(const std::string& name, const std::vector<Agent>& agents) : name_(name), agents_(agents) {
662 std::set<std::string> names;
663 for (const Agent& a : agents) names.insert(a.name());
664 if (names.size() != agents.size()) throw value_error("Agent names must be unique within a composition");
665 }
666 Composition(std::initializer_list<Agent> agents) : Composition(std::vector<Agent>(agents)) {}
667
668 const std::string& name() const { return name_; }
669
670 /** Add a hand-declared agent. */
671 Composition& add(const Agent& agent) {
672 for (const Agent& a : agents_)
673 if (a.name() == agent.name()) throw value_error("Agent names must be unique within a composition");
674 for (const auto& p : embedded_)
675 if (p->name() == agent.name()) throw value_error("Agent names must be unique within a composition");
676 agents_.push_back(agent);
677 return *this;
678 }
679
680 /** Nest a composition: its agents, embedded models, synchronisations, hidden labels and rewards join this one. */
682 std::set<std::string> names, theirs;
683 for (const Agent& a : agents_) names.insert(a.name());
684 for (const auto& p : embedded_) names.insert(p->name());
685 for (const Agent& a : model.agents_) theirs.insert(a.name());
686 for (const auto& p : model.embedded_) theirs.insert(p->name());
687 std::vector<std::string> common;
688 for (const std::string& n : names)
689 if (theirs.count(n)) common.push_back(n);
690 if (!common.empty()) {
691 std::string list;
692 for (const std::string& n : common) list += (list.empty() ? "'" : ", '") + n + "'";
693 throw value_error("nested composition repeats part names: [" + list + "]");
694 }
695 bool unprefixed = false;
696 for (const auto& p : embedded_) unprefixed = unprefixed || p->prefix().empty();
697 for (const auto& p : model.embedded_) unprefixed = unprefixed || p->prefix().empty();
698 if (!embedded_.empty() && !model.embedded_.empty() && unprefixed)
699 throw value_error("several embedded models need distinct prefix= values");
700 agents_.insert(agents_.end(), model.agents_.begin(), model.agents_.end());
701 embedded_.insert(embedded_.end(), model.embedded_.begin(), model.embedded_.end());
702 syncs_.insert(syncs_.end(), model.syncs_.begin(), model.syncs_.end());
703 min_syncs_.insert(min_syncs_.end(), model.min_syncs_.begin(), model.min_syncs_.end());
704 ext_syncs_.insert(ext_syncs_.end(), model.ext_syncs_.begin(), model.ext_syncs_.end());
705 hidden_.insert(model.hidden_.begin(), model.hidden_.end());
706 for (const auto& r : model.rewards_) set_reward_(r.first, r.second);
707 return *this;
708 }
709
710 /** Embed a LINE Network held by reference: each node becomes an agent (defined in embed.h). */
712 /** Embed a LINE Network the composition shares ownership of (defined in embed.h). */
713 Composition& add(std::shared_ptr<qn::Network<double>> network, const AddOptions& o = AddOptions());
714 /** Embed a LINE Environment: a stage agent plus its stage networks (defined in embed.h). */
715 Composition& add(const env::Environment<double>& environment, const AddOptions& o = AddOptions());
716 /** Embed a LayeredNetwork through LINE's own LQN2QN translation (defined in embed.h). */
717 Composition& add(const lqn::LqnModel<double>& layered, const AddOptions& o = AddOptions());
718 /** Embed a MarkovProcess (one agent) or a MarkovChain (one discrete-time agent) (defined in embed.h). */
720 /** Embed a Workflow as one renewal agent labelled by activity (defined in embed.h). */
722
723 /** Add an embedded part built elsewhere (`embed_part`). */
724 Composition& add_part(std::shared_ptr<EmbeddedPart> part) {
725 detail::identifier(part->name(),
726 "embedded model name (give prefix= when the model name is not an identifier)");
727 for (const auto& p : embedded_)
728 if (p->name() == part->name())
729 throw value_error("a part named " + part->name() +
730 " is already in the composition; give a distinct prefix");
731 for (const Agent& a : agents_)
732 if (a.name() == part->name())
733 throw value_error("a part named " + part->name() +
734 " is already in the composition; give a distinct prefix");
735 if (!embedded_.empty() && part->prefix().empty())
736 throw value_error("several embedded models need distinct prefix= values");
737 for (const auto& p : embedded_)
738 if (p->prefix().empty()) throw value_error("several embedded models need distinct prefix= values");
739 embedded_.push_back(part);
740 return *this;
741 }
742
743 /**
744 * Make actions internal (`hide`): they still occur, but leave the action
745 * tables. Each action is named as in `getAvgAct`; an open class or a
746 * trailing `[*]` hides the whole family (defined in tables.h).
747 */
749 Composition& hide(const std::vector<ActionSpec>& actions);
750
751 /**
752 * Declare a state reward `fn(view)`, read back with `getAvgReward()`.
753 * `view[agent]` is an agent's local state; `view.node(part, node)` the
754 * state row of a node of an embedded LINE model.
755 */
756 Composition& setReward(const std::string& name, RewardFn fn) {
757 if (name.empty()) throw value_error("a reward needs a nonempty name");
758 if (!fn) throw value_error("a reward is a callable of the joint-state view");
759 set_reward_(name, std::move(fn));
760 return *this;
761 }
762 Composition& set_reward(const std::string& name, RewardFn fn) { return setReward(name, std::move(fn)); }
763
764 /** Re-read every embedded LINE model after it was changed. */
766 for (const auto& p : embedded_) p->refresh();
767 return *this;
768 }
769
770 /**
771 * A node action of an embedded LINE model (`action`): `node` and
772 * `jobclass` are names, `mode` a Petri-net mode for ENABLE/FIRE. Leaving
773 * the class out matches every class; `part` selects the embedded part when
774 * there are several.
775 */
776 NodeRef action(const std::string& node, lang::EventType event,
777 const std::optional<std::string>& jobclass = std::nullopt,
778 const std::optional<std::string>& mode = std::nullopt,
779 const std::optional<std::string>& part = std::nullopt) const {
780 const std::shared_ptr<EmbeddedPart> p = part_of(part);
781 return NodeRef{p->name(), p->resolve(node, event, jobclass, mode)};
782 }
783 NodeRef action(const char* node, lang::EventType event, const std::optional<std::string>& jobclass = std::nullopt,
784 const std::optional<std::string>& mode = std::nullopt,
785 const std::optional<std::string>& part = std::nullopt) const {
786 return action(std::string(node), event, jobclass, mode, part);
787 }
788 /** The same by 1-based node and class indices of the embedded network (class 0: every class). */
789 NodeRef action(std::size_t node, lang::EventType event, std::size_t jobclass = 0,
790 const std::optional<std::string>& part = std::nullopt) const {
791 const std::shared_ptr<EmbeddedPart> p = part_of(part);
792 const std::optional<std::string> cls =
793 jobclass == 0 ? std::optional<std::string>() : std::optional<std::string>(p->class_name(jobclass));
794 return NodeRef{p->name(), p->resolve(p->node_name(node), event, cls, std::nullopt)};
795 }
796
797 /** Synchronise one active action with one or more hand passive actions. */
798 Composition& synchronize(const ActionRef& active, const std::vector<ActionRef>& passives) {
799 return synchronize(active, passives, std::vector<NodeRef>());
800 }
801 Composition& synchronize(const ActionRef& active, const ActionRef& passive) {
802 return synchronize(active, std::vector<ActionRef>{passive});
803 }
804 /** The hand action injects an arrival of an open class at a node of an embedded network. */
805 Composition& synchronize(const ActionRef& active, const NodeRef& node) {
806 return synchronize(active, std::vector<ActionRef>(), std::vector<NodeRef>{node});
807 }
808 /** One active action with hand passives and injected node arrivals. */
809 Composition& synchronize(const ActionRef& active, const std::vector<ActionRef>& passives,
810 const std::vector<NodeRef>& nodes) {
811 if (passives.empty() && nodes.empty())
812 throw value_error("Synchronization requires at least one passive endpoint");
813 if (!owns(active.agent)) throw value_error("Synchronization endpoints must belong to the composition");
814 for (const ActionRef& p : passives)
815 if (!owns(p.agent)) throw value_error("Synchronization endpoints must belong to the composition");
816 Sync s;
817 s.active = Endpoint(active.agent.name(), active.name);
818 for (const ActionRef& p : passives) s.passive.push_back(Endpoint(p.agent.name(), p.name));
819 for (const NodeRef& n : nodes) s.node_passive.push_back(std::make_pair(n.part, n.key));
820 std::vector<std::string> agent_names{s.active.first};
821 for (const Endpoint& p : s.passive) agent_names.push_back(p.first);
822 for (const auto& p : s.node_passive) agent_names.push_back(p.first);
823 if (std::set<std::string>(agent_names.begin(), agent_names.end()).size() != agent_names.size())
824 throw value_error("Synchronization requires distinct agents");
825 std::set<Endpoint> used_active, used_passive;
826 for (const Sync& x : syncs_) {
827 used_active.insert(x.active);
828 used_passive.insert(x.passive.begin(), x.passive.end());
829 }
830 for (const MinSync& x : min_syncs_) used_active.insert(x.active.begin(), x.active.end());
831 bool reused = used_active.count(s.active) || used_passive.count(s.active);
832 for (const Endpoint& p : s.passive)
833 if (used_active.count(p)) reused = true;
834 if (reused) throw value_error("An endpoint can participate in only one synchronization");
835 // validate_model checks roles; other passive actions may be connected
836 // later, so the unconnected-passive rule waits for the full composition
837 std::vector<Sync> trial = syncs_;
838 trial.push_back(s);
839 model_checked(&trial, nullptr);
840 syncs_.push_back(s);
841 return *this;
842 }
843 /**
844 * Hand passives join every network event that carries the node key, and
845 * block it while they are disabled (`synchronize(node action, passives)`).
846 */
847 Composition& synchronize(const NodeRef& active, const std::vector<ActionRef>& passives) {
848 if (passives.empty()) throw value_error("Synchronization requires at least one passive endpoint");
849 for (const ActionRef& p : passives)
850 if (!owns(p.agent)) throw value_error("Synchronization endpoints must belong to the composition");
851 ExtSync x;
852 x.agent = active.part;
853 x.pattern = active.key;
854 for (const ActionRef& p : passives) x.passive.push_back(Endpoint(p.agent.name(), p.name));
855 std::vector<ExtSync> trial = ext_syncs_;
856 trial.push_back(x);
857 model_checked(nullptr, &trial);
858 ext_syncs_.push_back(x);
859 return *this;
860 }
861 Composition& synchronize(const NodeRef& active, const ActionRef& passive) {
862 return synchronize(active, std::vector<ActionRef>{passive});
863 }
864
865 /**
866 * Synchronise active actions at the minimum enabled total rate. Each
867 * participant's enabled transition is sampled proportionally to its local
868 * rate or passive weight; any disabled participant blocks the event, and
869 * the first active action names it.
870 */
871 Composition& synchronize_min(const std::vector<ActionRef>& actives,
872 const std::vector<ActionRef>& passives = std::vector<ActionRef>()) {
873 if (actives.size() < 2)
874 throw value_error("minimum synchronization requires at least two active action references");
875 for (const ActionRef& r : actives)
876 if (!owns(r.agent)) throw value_error("Synchronization endpoints must belong to the composition");
877 for (const ActionRef& r : passives)
878 if (!owns(r.agent)) throw value_error("Synchronization endpoints must belong to the composition");
879 MinSync s;
880 for (const ActionRef& r : actives) s.active.push_back(Endpoint(r.agent.name(), r.name));
881 for (const ActionRef& r : passives) s.passive.push_back(Endpoint(r.agent.name(), r.name));
882 std::vector<Endpoint> endpoints = s.active;
883 endpoints.insert(endpoints.end(), s.passive.begin(), s.passive.end());
884 std::set<std::string> ag;
885 for (const Endpoint& e : endpoints) ag.insert(e.first);
886 if (ag.size() != endpoints.size()) throw value_error("Synchronization requires distinct agents");
887 std::set<Endpoint> used;
888 for (const Sync& x : syncs_) {
889 used.insert(x.active);
890 used.insert(x.passive.begin(), x.passive.end());
891 }
892 for (const MinSync& x : min_syncs_) {
893 used.insert(x.active.begin(), x.active.end());
894 used.insert(x.passive.begin(), x.passive.end());
895 }
896 for (const Endpoint& e : endpoints)
897 if (used.count(e)) throw value_error("An endpoint can participate in only one synchronization");
898 const Model candidate = model();
899 for (const Endpoint& e : s.active) check_role(candidate, e, Role::Active);
900 for (const Endpoint& e : s.passive) check_role(candidate, e, Role::Passive);
901 min_syncs_.push_back(s);
902 return *this;
903 }
904
905 /** The current model snapshot (`_model`). */
906 Model model(const std::vector<Sync>* syncs = nullptr, const std::vector<ExtSync>* ext_syncs = nullptr) const {
907 if (agents_.empty() && embedded_.empty()) throw value_error("Composition requires one or more agents");
908 Model m;
909 std::set<std::string> names;
910 for (const Agent& a : agents_) {
911 detail::identifier(a.name(), "agent name");
912 names.insert(a.name());
913 m.agents.push_back(a.record());
914 }
915 if (names.size() != agents_.size()) throw value_error("Agent names must be unique within a composition");
916 m.syncs = syncs ? *syncs : syncs_;
917 for (const auto& part : embedded_) {
918 std::set<std::string> injected;
919 for (const Sync& s : m.syncs)
920 for (const auto& p : s.node_passive)
921 if (p.first == part->name() && p.second.index) injected.insert(*p.second.index);
922 part->set_injected(injected);
923 }
924 for (const auto& part : embedded_) {
925 AgentRecord r;
926 r.name = part->name();
927 r.embedded = part;
928 m.agents.push_back(r);
929 }
930 m.min_syncs = min_syncs_;
931 m.ext_syncs = ext_syncs ? *ext_syncs : ext_syncs_;
932 m.hidden = hidden_;
933 m.rewards = rewards_;
934 return m;
935 }
936
937 /** Finite CTMC states, generator and labelled event matrices (`get_struct`). */
939 const Model m = model();
941 return compile_model(m);
942 }
943
944 const std::vector<Agent>& agents() const { return agents_; }
945 const std::vector<std::shared_ptr<EmbeddedPart>>& embedded() const { return embedded_; }
946 const std::vector<Sync>& syncs() const { return syncs_; }
947 const std::vector<MinSync>& min_syncs() const { return min_syncs_; }
948 const std::vector<ExtSync>& ext_syncs() const { return ext_syncs_; }
949 const std::set<std::string>& hidden() const { return hidden_; }
950 const std::vector<std::pair<std::string, RewardFn>>& rewards() const { return rewards_; }
951
952 /** Parse a `.lal` declaration into a programmatic composition (`from_string`). */
953 static Composition from_string(const std::string& source);
954 /** Load a `.lal` declaration from a UTF-8 file (`from_file`). */
955 static Composition from_file(const std::string& path) {
956 std::ifstream in(path, std::ios::binary);
957 if (!in) throw value_error("Cannot read " + path);
958 std::ostringstream os;
959 os << in.rdbuf();
960 return from_string(os.str());
961 }
962
963 /**
964 * Provenance of a composition built over a flattened LINE CTMC: set by the
965 * caller that builds one (the test helper twin of `network_ctmc`). The
966 * solvers read `source_truncated`: a truncated import is not exact.
967 */
968 std::optional<Matrix<double>> source_state_space;
969 std::vector<std::string> source_event_order;
970 std::optional<std::vector<std::size_t>> source_sync;
971 bool source_truncated = false;
972
973 private:
974 friend struct ActionSpec;
975 friend struct detail::Lowering;
976 std::string name_;
977 std::vector<Agent> agents_;
978 std::vector<std::shared_ptr<EmbeddedPart>> embedded_;
979 std::vector<Sync> syncs_;
980 std::vector<MinSync> min_syncs_;
981 std::vector<ExtSync> ext_syncs_;
982 std::set<std::string> hidden_;
983 std::vector<std::pair<std::string, RewardFn>> rewards_;
984
985 void set_reward_(const std::string& name, RewardFn fn) {
986 for (auto& r : rewards_)
987 if (r.first == name) {
988 r.second = std::move(fn);
989 return;
990 }
991 rewards_.push_back(std::make_pair(name, std::move(fn)));
992 }
993
994 std::shared_ptr<EmbeddedPart> part_of(const std::optional<std::string>& part) const {
995 if (embedded_.empty()) throw value_error("the composition embeds no LINE model");
996 if (!part) {
997 if (embedded_.size() > 1) throw value_error("several embedded models: give part=<prefix>");
998 return embedded_.front();
999 }
1000 for (const auto& p : embedded_)
1001 if (p->name() == *part) return p;
1002 throw value_error("no embedded model named " + *part);
1003 }
1004
1005 /** A trial snapshot validated as `_model(syncs=..., ext_syncs=...)` does: an unconnected passive may wait. */
1006 void model_checked(const std::vector<Sync>* syncs, const std::vector<ExtSync>* ext_syncs) const {
1007 const Model m = model(syncs, ext_syncs);
1008 try {
1009 validate_model(m, true);
1010 } catch (const InputError& exc) {
1011 if (std::string(exc.what()).find("Unconnected passive action") == std::string::npos) throw;
1012 }
1013 }
1014
1015 bool owns(const Agent& a) const {
1016 for (const Agent& b : agents_)
1017 if (b.same(a)) return true;
1018 return false;
1019 }
1020
1021 static void check_role(const Model& m, const Endpoint& ep, Role role) {
1022 bool any = false, bad = false;
1023 for (const Transition& t : m.agent(ep.first).transitions)
1024 if (t.action == ep.second) {
1025 any = true;
1026 if (t.role != role) bad = true;
1027 }
1028 if (!any || bad)
1029 throw value_error(endpoint_repr(ep) + " must have only " + role_name(role) + " transitions");
1030 }
1031};
1032
1033namespace detail {
1034
1035/** The `.lal` tokenizer and recursive-descent parser (`core.Parser`). */
1036class Parser {
1037 public:
1038 explicit Parser(const std::string& source) {
1039 static const std::regex token(
1040 R"(\s+|#[^\n]*|->|-?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|[A-Za-z_][A-Za-z_0-9]*|[{}\‍[\‍]():;,=.<>])");
1041 std::size_t pos = 0;
1042 auto line_of = [&](std::size_t p) {
1043 return static_cast<int>(std::count(source.begin(), source.begin() + static_cast<long>(p), '\n')) + 1;
1044 };
1045 while (pos < source.size()) {
1046 std::smatch m;
1047 const auto begin = source.begin() + static_cast<long>(pos);
1048 if (!std::regex_search(begin, source.end(), m, token, std::regex_constants::match_continuous) ||
1049 m.length(0) == 0) {
1050 throw value_error("Unexpected character at line " + std::to_string(line_of(pos)) + ": '" +
1051 std::string(1, source[pos]) + "'");
1052 }
1053 const std::string s = m.str(0);
1054 const bool space = std::all_of(s.begin(), s.end(), [](char c) { return std::isspace(static_cast<unsigned char>(c)); });
1055 if (!space && s[0] != '#') tokens_.push_back({s, line_of(pos)});
1056 pos += static_cast<std::size_t>(m.length(0));
1057 }
1058 }
1059
1060 Model parse() {
1061 Model model;
1062 auto has = [&](const std::string& n) { return model.has_agent(n); };
1063 while (peek()) {
1064 const std::string kind = take();
1065 if (kind == "param") {
1066 const std::string name = this->name();
1067 take("=");
1068 const double value = number();
1069 take(";");
1070 if (params_.count(name)) throw value_error("Duplicate parameter " + name);
1071 params_[name] = value;
1072 } else if (kind == "agent") {
1073 const std::string name = this->name();
1074 take("{");
1075 take("state");
1076 std::vector<std::string> states{this->name()};
1077 while (peek_is(",")) {
1078 take(",");
1079 states.push_back(this->name());
1080 }
1081 take(";");
1082 take("initial");
1083 std::optional<std::vector<double>> distribution;
1084 std::string initial;
1085 if (peek_is("[")) {
1086 // initial [p_0, ..., p_n]: a distribution over the declared states, in order
1087 take("[");
1088 distribution = std::vector<double>();
1089 while (true) {
1090 distribution->push_back(to_float(take()));
1091 if (!peek_is(",")) break;
1092 take(",");
1093 }
1094 take("]");
1095 if (distribution->size() != states.size())
1096 throw value_error("initial distribution of " + name + " needs one probability per state");
1097 std::size_t first = 0;
1098 for (std::size_t i = 0; i < distribution->size(); ++i)
1099 if ((*distribution)[i] > 0) {
1100 first = i;
1101 break;
1102 }
1103 initial = states[first];
1104 } else {
1105 initial = this->name();
1106 }
1107 take(";");
1108 std::vector<Transition> transitions;
1109 while (!peek_is("}")) {
1110 Transition t;
1111 t.source = this->name();
1112 take(":");
1113 take("(");
1114 t.action = this->name();
1115 take(",");
1116 const std::string role = take();
1117 if (role == "rate") {
1118 take("=");
1119 t.value = number();
1120 t.role = Role::Active;
1121 } else if (role == "passive") {
1122 t.value = 1.0;
1123 t.role = Role::Passive;
1124 if (peek_is(",")) {
1125 take(",");
1126 take("weight");
1127 take("=");
1128 t.value = number();
1129 }
1130 } else if (role == "immediate") {
1131 // s: (a, immediate[, weight = w][, priority = p]) -> t;
1132 t.value = 1.0;
1133 t.role = Role::Immediate;
1134 while (peek_is(",")) {
1135 take(",");
1136 const std::string key = take();
1137 take("=");
1138 if (key == "weight") {
1139 t.value = number();
1140 } else if (key == "priority") {
1141 const std::string raw = take();
1142 static const std::regex integer(R"(-?\d+)");
1143 if (!std::regex_match(raw, integer)) throw value_error("priority must be an integer");
1144 // Python's int is unbounded; an int priority is not, so a literal
1145 // past its range is the parser's input error at its line
1146 try {
1147 t.priority = std::stoi(raw);
1148 } catch (const std::out_of_range&) {
1149 throw value_error("Line " + std::to_string(tokens_[i_ - 1].second) +
1150 ": priority " + raw + " is out of range");
1151 }
1152 } else {
1153 throw value_error("Unknown immediate attribute '" + key + "'");
1154 }
1155 }
1156 } else {
1157 throw value_error("Unknown action role '" + role + "'");
1158 }
1159 take(")");
1160 take("->");
1161 t.target = this->name();
1162 take(";");
1163 transitions.push_back(t);
1164 }
1165 take("}");
1166 if (has(name)) throw value_error("Duplicate agent " + name);
1167 std::set<std::string> u(states.begin(), states.end());
1168 if (u.size() != states.size() || !u.count(initial))
1169 throw value_error("Invalid states or initial state in " + name);
1170 for (const Transition& t : transitions)
1171 if (!u.count(t.source) || !u.count(t.target)) throw value_error("Unknown state in " + name);
1172 AgentRecord rec;
1173 rec.name = name;
1174 rec.states = states;
1175 rec.initial = initial;
1176 rec.transitions = transitions;
1177 rec.initial_distribution = distribution;
1178 model.agents.push_back(rec);
1179 } else if (kind == "system") {
1180 take("{");
1181 while (!peek_is("}")) {
1182 const std::string k = take();
1183 if (k == "synchronize_min") {
1184 MinSync s;
1185 s.active.push_back(endpoint());
1186 while (peek_is(",")) {
1187 take(",");
1188 s.active.push_back(endpoint());
1189 }
1190 if (peek_is("->")) {
1191 take("->");
1192 s.passive.push_back(endpoint());
1193 while (peek_is(",")) {
1194 take(",");
1195 s.passive.push_back(endpoint());
1196 }
1197 }
1198 take(";");
1199 model.min_syncs.push_back(s);
1200 continue;
1201 }
1202 if (k != "synchronize") throw value_error("Unknown synchronization '" + k + "'");
1203 Sync s;
1204 s.active = endpoint();
1205 take("->");
1206 s.passive.push_back(endpoint());
1207 while (peek_is(",")) {
1208 take(",");
1209 s.passive.push_back(endpoint());
1210 }
1211 take(";");
1212 model.syncs.push_back(s);
1213 }
1214 take("}");
1215 } else {
1216 throw value_error("Unknown declaration '" + kind + "'");
1217 }
1218 }
1219 validate_model(model, true);
1220 return model;
1221 }
1222
1223 private:
1224 std::vector<std::pair<std::string, int>> tokens_;
1225 std::size_t i_ = 0;
1226 std::map<std::string, double> params_;
1227
1228 const std::string* peek() const { return i_ < tokens_.size() ? &tokens_[i_].first : nullptr; }
1229 bool peek_is(const std::string& s) const { return peek() && *peek() == s; }
1230
1231 std::string take(const std::string& expected = std::string()) {
1232 if (i_ == tokens_.size())
1233 throw value_error("Unexpected end of input; expected " + (expected.empty() ? std::string("token") : expected));
1234 const auto& tok = tokens_[i_];
1235 if (!expected.empty() && tok.first != expected)
1236 throw value_error("Line " + std::to_string(tok.second) + ": expected '" + expected + "', got '" +
1237 tok.first + "'");
1238 ++i_;
1239 return tok.first;
1240 }
1241
1242 std::string name() {
1243 const std::string v = take();
1244 if (!is_identifier(v)) throw value_error("Expected identifier, got '" + v + "'");
1245 return v;
1246 }
1247
1248 /** Python float(): a full numeric literal (or inf/nan spellings), else nullopt. */
1249 static std::optional<double> try_float(const std::string& s) {
1250 std::string t = s;
1251 std::string low;
1252 for (char c : t) low += static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
1253 if (low == "inf" || low == "infinity" || low == "+inf") return HUGE_VAL;
1254 if (low == "-inf" || low == "-infinity") return -HUGE_VAL;
1255 if (low == "nan") return std::nan("");
1256 try {
1257 std::size_t used = 0;
1258 const double v = std::stod(t, &used);
1259 if (used == t.size()) return v;
1260 } catch (...) {
1261 }
1262 return std::nullopt;
1263 }
1264
1265 static double to_float(const std::string& s) {
1266 const auto v = try_float(s);
1267 if (!v) throw value_error("could not convert string to float: '" + s + "'");
1268 return *v;
1269 }
1270
1271 double number() {
1272 const std::string v = take();
1273 double n;
1274 const auto f = try_float(v);
1275 if (f) {
1276 n = *f;
1277 } else {
1278 auto it = params_.find(v);
1279 if (it == params_.end()) throw value_error("Unknown parameter '" + v + "'");
1280 n = it->second;
1281 }
1282 if (!std::isfinite(n) || n <= 0) throw value_error("Rates and weights must be finite and positive");
1283 return n;
1284 }
1285
1286 Endpoint endpoint() {
1287 const std::string a = name();
1288 take(".");
1289 return Endpoint(a, name());
1290 }
1291};
1292
1293} // namespace detail
1294
1295/** Parse a `.lal` source into a validated model record (`core.parse`). */
1296inline Model parse(const std::string& source) { return detail::Parser(source).parse(); }
1297
1298inline Composition Composition::from_string(const std::string& source) {
1299 const Model record = parse(source);
1300 std::vector<Agent> agents;
1301 for (const AgentRecord& r : record.agents) agents.push_back(Agent::from_record(r));
1302 auto find = [&](const std::string& n) -> const Agent& {
1303 for (const Agent& a : agents)
1304 if (a.name() == n) return a;
1305 throw value_error("Unknown agent " + n);
1306 };
1307 Composition result(agents);
1308 for (const Sync& s : record.syncs) {
1309 std::vector<ActionRef> ps;
1310 for (const Endpoint& p : s.passive) ps.push_back(find(p.first).action(p.second));
1311 result.synchronize(find(s.active.first).action(s.active.second), ps);
1312 }
1313 for (const MinSync& s : record.min_syncs) {
1314 std::vector<ActionRef> as, ps;
1315 for (const Endpoint& p : s.active) as.push_back(find(p.first).action(p.second));
1316 for (const Endpoint& p : s.passive) ps.push_back(find(p.first).action(p.second));
1317 result.synchronize_min(as, ps);
1318 }
1319 return result;
1320}
1321
1322} // namespace lal
1323} // namespace line
1324
1325#include "line/lang/lal/records.h"
1326#include "line/lang/lal/tables.h"
1327#include "line/lang/lal/embed.h"
1328
1329#endif // LINE_LANG_LAL_BUILDER_H
std::size_t size() const
Definition matrix.h:91
std::size_t rows() const
Definition matrix.h:89
A finite-state agent with active, weighted passive and immediate transitions (handle semantics).
Definition builder.h:286
Agent & command(const std::string &action, const CommandValue &value, std::function< bool(const Vars &)> guard, std::function< Vars(const Vars &)> update, Role role=Role::Active, int priority=0, const std::string &label=std::string())
command(action, rate, guard, update[, role, priority, label]); for a non-active role value is the wei...
Definition builder.h:433
bool same(const Agent &o) const
Definition builder.h:339
Agent & command(const std::string &action, const CommandOptions &o)
Add a guarded command to a typed-variable agent (command).
Definition builder.h:413
bool unbounded_queue() const
Definition builder.h:337
Agent & immediate(const std::string &source, const std::string &action, const std::string &target, double weight=1.0, int priority=0, const std::optional< std::string > &label=std::nullopt)
Add a zero-time action.
Definition builder.h:369
Agent & immediate(const std::string &source, const std::string &action, const std::string &target, ValueFn weight, int priority=0, const std::optional< std::string > &label=std::nullopt)
Definition builder.h:373
const std::vector< std::string > & states() const
Definition builder.h:332
static Agent from_record(const AgentRecord &value)
Rebuild a builder agent from a parsed record (as Composition.from_string does).
Definition builder.h:487
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::vector< Transition > & transitions() const
Definition builder.h:334
Agent & passive(const std::string &source, const std::string &action, const std::string &target, ValueFn weight)
Definition builder.h:360
Agent & setInitialDistribution(const std::map< std::string, double > &p)
Definition builder.h:405
static std::vector< Agent > array(const Agent &prototype, long n)
n copies of prototype named <name>_0 ... <name>_{n-1}, labels suffixed [i] (Agent....
Definition builder.h:450
ActionRef action(const std::string &name) const
Reference an existing action (a transition or a command) for synchronisation.
Definition builder.h:614
friend class Composition
Definition builder.h:495
Agent & set_initial_distribution(const std::map< std::string, double > &p)
Start the agent from a law over its states, by state name (missing states have probability 0).
Definition builder.h:392
const std::string & name() const
Definition builder.h:331
static Agent with_vars(const std::string &name, const std::vector< std::pair< std::string, std::vector< long > > > &vars, const Vars &initial)
A typed-variable agent (Agent(name, vars={...}, initial={...})): vars maps each variable,...
Definition builder.h:304
AgentRecord record() const
The immutable record (_record); a typed-variable agent is expanded from its initial valuation.
Definition builder.h:468
const std::optional< QueueInfo > & queue_info() const
Definition builder.h:336
Agent & set_initial_distribution(const std::vector< double > &p)
Start the agent from a law over its states, a vector in state order.
Definition builder.h:382
Agent & passive(const std::string &source, const std::string &action, const std::string &target, double weight=1.0)
Add a passive reaction, chosen in proportion to weight among the enabled ones.
Definition builder.h:356
bool has_vars() const
Definition builder.h:338
Agent(const std::string &name, const std::vector< std::string > &states, const std::string &initial)
Definition builder.h:288
const std::optional< std::vector< double > > & initial_distribution() const
Definition builder.h:335
const std::string & initial() const
Definition builder.h:333
Agent & setInitialDistribution(const std::vector< double > &p)
Definition builder.h:404
Agent & active(const std::string &source, const std::string &action, ValueFn rate, const std::string &target, const std::optional< std::string > &label=std::nullopt, int priority=0)
A timed action whose rate is a function of the joint state.
Definition builder.h:351
A collection of agents and embedded LINE models with atomic synchronisations (Composition).
Definition builder.h:655
Composition(const std::string &name)
Definition builder.h:658
Composition & setReward(const std::string &name, RewardFn fn)
Declare a state reward fn(view), read back with getAvgReward().
Definition builder.h:756
const std::vector< Sync > & syncs() const
Definition builder.h:946
Composition & hide(const std::vector< ActionSpec > &actions)
static Composition from_string(const std::string &source)
Parse a .lal declaration into a programmatic composition (from_string).
Definition builder.h:1298
Composition(const std::string &name, const std::vector< Agent > &agents)
Definition builder.h:661
const std::vector< std::pair< std::string, RewardFn > > & rewards() const
Definition builder.h:950
Composition & add(const Agent &agent)
Add a hand-declared agent.
Definition builder.h:671
Composition & add(const Composition &model)
Nest a composition: its agents, embedded models, synchronisations, hidden labels and rewards join thi...
Definition builder.h:681
static Composition from_file(const std::string &path)
Load a .lal declaration from a UTF-8 file (from_file).
Definition builder.h:955
Composition & synchronize(const ActionRef &active, const std::vector< ActionRef > &passives, const std::vector< NodeRef > &nodes)
One active action with hand passives and injected node arrivals.
Definition builder.h:809
Composition & synchronize(const ActionRef &active, const std::vector< ActionRef > &passives)
Synchronise one active action with one or more hand passive actions.
Definition builder.h:798
NodeRef action(std::size_t node, lang::EventType event, std::size_t jobclass=0, const std::optional< std::string > &part=std::nullopt) const
The same by 1-based node and class indices of the embedded network (class 0: every class).
Definition builder.h:789
Composition(const std::vector< Agent > &agents)
Definition builder.h:660
std::optional< std::vector< std::size_t > > source_sync
Definition builder.h:970
Composition & synchronize(const ActionRef &active, const NodeRef &node)
The hand action injects an arrival of an open class at a node of an embedded network.
Definition builder.h:805
Composition & set_reward(const std::string &name, RewardFn fn)
Definition builder.h:762
Composition & add_part(std::shared_ptr< EmbeddedPart > part)
Add an embedded part built elsewhere (embed_part).
Definition builder.h:724
Composition & hide(const ActionSpec &action)
Make actions internal (hide): they still occur, but leave the action tables.
friend struct ActionSpec
Definition builder.h:974
Model model(const std::vector< Sync > *syncs=nullptr, const std::vector< ExtSync > *ext_syncs=nullptr) const
The current model snapshot (_model).
Definition builder.h:906
Composition & synchronize(const NodeRef &active, const std::vector< ActionRef > &passives)
Hand passives join every network event that carries the node key, and block it while they are disable...
Definition builder.h:847
const std::vector< ExtSync > & ext_syncs() const
Definition builder.h:948
Composition & refresh()
Re-read every embedded LINE model after it was changed.
Definition builder.h:765
const std::string & name() const
Definition builder.h:668
NodeRef action(const std::string &node, lang::EventType event, const std::optional< std::string > &jobclass=std::nullopt, const std::optional< std::string > &mode=std::nullopt, const std::optional< std::string > &part=std::nullopt) const
A node action of an embedded LINE model (action): node and jobclass are names, mode a Petri-net mode ...
Definition builder.h:776
Composition & synchronize_min(const std::vector< ActionRef > &actives, const std::vector< ActionRef > &passives=std::vector< ActionRef >())
Synchronise active actions at the minimum enabled total rate.
Definition builder.h:871
const std::set< std::string > & hidden() const
Definition builder.h:949
Composition & synchronize(const NodeRef &active, const ActionRef &passive)
Definition builder.h:861
Compiled get_struct() const
Finite CTMC states, generator and labelled event matrices (get_struct).
Definition builder.h:938
Composition(const char *name)
Definition builder.h:659
Composition & synchronize(const ActionRef &active, const ActionRef &passive)
Definition builder.h:801
const std::vector< Agent > & agents() const
Definition builder.h:944
NodeRef action(const char *node, lang::EventType event, const std::optional< std::string > &jobclass=std::nullopt, const std::optional< std::string > &mode=std::nullopt, const std::optional< std::string > &part=std::nullopt) const
Definition builder.h:783
std::vector< std::string > source_event_order
Definition builder.h:969
const std::vector< MinSync > & min_syncs() const
Definition builder.h:947
Composition(std::initializer_list< Agent > agents)
Definition builder.h:666
const std::vector< std::shared_ptr< EmbeddedPart > > & embedded() const
Definition builder.h:945
std::optional< Matrix< double > > source_state_space
Provenance of a composition built over a flattened LINE CTMC: set by the caller that builds one (the ...
Definition builder.h:968
Read-only view of a joint state, for functional rates and rewards (StateView).
Definition core.h:345
A queueing network under construction.
LINE Agent Language (LAL): the finite-agent model record, its validation, the joint-state event kerne...
LINE Agent Language (LAL): embedding of LINE model objects into a LAL composition.
LU factorization with partial pivoting, templated on the number type.
Definition ag.h:49
const char * role_name(Role r)
Definition core.h:90
std::vector< std::pair< std::string, double > > NamedWeights
Definition builder.h:77
Model parse(const std::string &source)
Parse a .lal source into a validated model record (core.parse).
Definition builder.h:1296
Role
Transition role: active (rate), passive (weight) or immediate (weight, zero time).
Definition core.h:88
std::function< double(const StateView &)> RewardFn
A state reward: a function of the joint-state view (Composition::setReward).
Definition core.h:100
std::pair< std::string, std::string > Endpoint
(agent, action).
Definition core.h:139
std::function< double(const StateView &)> ValueFn
A functional rate or weight: a function of the joint-state view.
Definition core.h:97
std::map< std::string, long > Vars
The valuation of the typed variables of an agent (v in a guard, update or rate).
Definition builder.h:80
std::string endpoint_repr(const Endpoint &e)
Python's repr of an endpoint tuple, ('agent', 'action').
Definition core.h:144
Compiled compile_model(const Model &model, const CompileOptions &opt=CompileOptions())
Compile the Cartesian (or, with reachable_only, the reachable) finite state space and its event matri...
Definition core.h:1262
InputError value_error(const std::string &what)
LINE:input:Unspecified, the C++ spelling of the Python ValueError raised throughout LAL.
Definition core.h:85
void validate_model(const Model &model, bool allow_unbounded=false)
Validate the common agent model used by both frontends (validate_model).
Definition core.h:550
std::vector< std::pair< std::string, Matrix< double > > > NamedMatrices
Definition builder.h:76
EventType
The events a state can undergo, with the values of MATLAB EventType.
Definition lang_types.h:116
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,...
LINE Agent Language (LAL): private record constructors of LAL agents (not part of the public API).
std::string name
Definition builder.h:611
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
The immutable agent record (core.Agent).
Definition core.h:284
std::string name
Definition core.h:285
std::optional< std::vector< double > > initial_distribution
Definition core.h:289
std::string initial
Definition core.h:287
std::vector< Transition > transitions
Definition core.h:288
std::vector< std::string > states
Definition core.h:286
std::optional< QueueInfo > queue_info
Definition core.h:292
std::shared_ptr< EmbeddedPart > embedded
An embedded LINE model, whose states are global state indices; null for a hand agent.
Definition core.h:294
std::optional< long > unbounded_initial
Definition core.h:291
bool discrete
A discrete-time agent (an embedded MarkovChain).
Definition core.h:296
Keyword arguments of Agent::command.
Definition builder.h:235
std::function< Vars(const Vars &)> update
The variables the command changes; an empty function changes none.
Definition builder.h:241
std::optional< CommandValue > weight
role Passive or Immediate: default 1
Definition builder.h:238
std::optional< CommandValue > rate
role Active: required
Definition builder.h:237
std::function< bool(const Vars &)> guard
Definition builder.h:239
A rate or weight of a guarded command: a number, a function f(v) of the agent's own variables,...
Definition builder.h:216
std::function< double(const Vars &, const StateView &)> joint
Definition builder.h:219
std::function< double(const Vars &)> local
Definition builder.h:218
The compiled finite CTMC (core.Compiled).
Definition core.h:396
Hand passives that join every event of an embedded part carrying a key matching pattern.
Definition core.h:264
NodeEvent pattern
Definition core.h:266
std::vector< Endpoint > passive
Definition core.h:267
std::string agent
Definition core.h:265
The lowering of a minimum-rate synchronisation (_lower_minimum).
Definition ag.h:224
A minimum-rate synchronisation: at least two active endpoints and optional passive ones.
Definition core.h:258
std::vector< Endpoint > passive
Definition core.h:260
std::vector< Endpoint > active
Definition core.h:259
A composition snapshot (core.Model): agents in declaration order plus synchronisations.
Definition core.h:310
std::vector< MinSync > min_syncs
Definition core.h:313
std::vector< std::pair< std::string, RewardFn > > rewards
declared state rewards, in order
Definition core.h:316
std::vector< Sync > syncs
Definition core.h:312
std::vector< ExtSync > ext_syncs
Definition core.h:314
std::vector< AgentRecord > agents
Definition core.h:311
std::set< std::string > hidden
labels removed from the action tables
Definition core.h:315
Key of an embedded node action: (node, EventType, class | mode).
Definition core.h:153
An action of a node of an embedded LINE model (NodeRef): key is the (node, EventType,...
Definition builder.h:630
NodeEvent key
Definition builder.h:632
std::string part
Definition builder.h:631
An ordinary synchronisation: one active endpoint, hand passives and injected node arrivals.
Definition core.h:250
Endpoint active
Definition core.h:251
std::vector< std::pair< std::string, NodeEvent > > node_passive
(embedded part, ARV key): the hand action injects an arrival at that node.
Definition core.h:254
std::vector< Endpoint > passive
Definition core.h:252
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
std::string source
Definition core.h:112
std::string action
Definition core.h:113
A user-supplied chain: a MarkovProcess when discrete is false, else a MarkovChain.
The intermediate model, and the second stage that flattens it.
Definition lqn_reader.h:411