5#ifndef LINE_LANG_LAL_BUILDER_H
6#define LINE_LANG_LAL_BUILDER_H
76typedef std::vector<std::pair<std::string, Matrix<double>>>
NamedMatrices;
80typedef std::map<std::string, long>
Vars;
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");
90 for (std::size_t k = 0; k < m.
size(); ++k)
91 if (!std::isfinite(m[k]))
return false;
96 for (std::size_t k = 0; k < m.
size(); ++k)
97 if (m[k] != 0)
return true;
103 for (std::size_t k = 0; k < m.
size(); ++k) r = std::max(r, std::fabs(m[k]));
108inline double tiny_scale() {
return std::numeric_limits<double>::min(); }
113 for (std::size_t k = 0; k < r.
size(); ++k) r[k] *= f;
118inline bool is_probability(
const std::vector<double>& p, std::size_t n) {
119 if (p.size() != n)
return false;
122 if (!std::isfinite(x) || x < 0)
return false;
125 return std::fabs(s - 1.0) <= 1e-12;
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;
147inline bool metzler_abscissa_below(
const Matrix<double>& T,
double s) {
148 const std::size_t n = T.
rows();
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);
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));
178 for (std::size_t j = 0; j < n; ++j) r += T(i, j);
179 rowmax = std::max(rowmax, r);
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))
190 return 0.5 * (lo + hi);
194inline std::string valuation_name(
const std::vector<long>& v) {
196 for (std::size_t i = 0; i < v.size(); ++i) s += (i ?
", " :
"") + std::to_string(v[i]);
197 if (v.size() == 1) s +=
",";
221 template <class N, typename std::enable_if<std::is_arithmetic<N>::value,
int>::type = 0>
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,
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,
237 std::optional<CommandValue>
rate;
251 std::function<bool(
const Vars&)> guard;
252 std::function<
Vars(
const Vars&)> update;
259 std::vector<std::string> states;
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;
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;
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");
304 static Agent with_vars(
const std::string&
name,
const std::vector<std::pair<std::string, std::vector<long>>>& vars,
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");
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;
327 for (
const auto& v : vars) a.d_->initial_vars.push_back(
initial.at(v.first));
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; }
336 const std::optional<QueueInfo>&
queue_info()
const {
return d_->queue_info; }
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) {
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);
357 double weight = 1.0) {
361 return add(source,
action, 0.0, std::move(weight), target,
Role::Passive, 0, std::nullopt);
370 double weight = 1.0,
int priority = 0,
const std::optional<std::string>& label = std::nullopt) {
374 int priority = 0,
const std::optional<std::string>& label = std::nullopt) {
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)];
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) {
400 v.push_back(it == p.end() ? 0.0 : it->second);
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");
429 d_->commands.push_back(c);
435 const std::string& label = std::string()) {
442 o.
guard = std::move(guard);
443 o.
update = std::move(update);
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) {
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) +
"]";
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);
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.");
480 if (d_->queue_info && d_->queue_template && d_->transitions == *d_->queue_template)
496 friend class detail::Records;
497 std::shared_ptr<detail::AgentData> d_;
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())
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");
516 t.
value = fn ? 0.0 : value;
519 if (label) t.
label.push_back(*label);
520 t.
fn = std::move(fn);
521 d_->transitions.push_back(t);
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) {
531 for (std::size_t i = 0; i < names.size(); ++i) v[names[i]] = state[i];
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;
540 std::vector<long> source, target;
541 const detail::Command* cmd;
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");
559 for (
const auto& kv : changes) nxt[kv.first] = kv.second;
560 if (!in_domain(nxt))
continue;
563 for (
const std::string& n : names) r.target.push_back(nxt.at(n));
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)
574 ": rates and weights must be finite and nonnegative");
575 if (val == 0)
continue;
578 r.value = c.value.constant;
581 if (!seen.count(r.target)) {
582 seen[r.target] =
states.size();
583 states.push_back(r.target);
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) {
593 t.
source = detail::valuation_name(r.source);
594 t.action = r.cmd->action;
595 t.role = r.cmd->role;
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);
601 rec.transitions.push_back(t);
603 rec.var_names = names;
615 detail::identifier(
name,
"action name");
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);
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");
668 const std::string&
name()
const {
return name_; }
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);
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());
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()) {
692 for (
const std::string& n : common) list += (list.empty() ?
"'" :
", '") + n +
"'";
693 throw value_error(
"nested composition repeats part names: [" + list +
"]");
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);
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())
730 " is already in the composition; give a distinct prefix");
731 for (
const Agent& a : agents_)
732 if (a.name() == 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);
758 if (!fn)
throw value_error(
"a reward is a callable of the joint-state view");
759 set_reward_(
name, std::move(fn));
766 for (
const auto& p : embedded_) p->
refresh();
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)};
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);
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)};
799 return synchronize(active, passives, std::vector<NodeRef>());
802 return synchronize(active, std::vector<ActionRef>{passive});
806 return synchronize(active, std::vector<ActionRef>(), std::vector<NodeRef>{node});
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");
815 if (!owns(p.agent))
throw value_error(
"Synchronization endpoints must belong to the composition");
820 std::vector<std::string> agent_names{s.
active.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());
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);
833 if (used_active.count(p)) reused =
true;
834 if (reused)
throw value_error(
"An endpoint can participate in only one synchronization");
837 std::vector<Sync> trial = syncs_;
839 model_checked(&trial,
nullptr);
848 if (passives.empty())
throw value_error(
"Synchronization requires at least one passive endpoint");
850 if (!owns(p.agent))
throw value_error(
"Synchronization endpoints must belong to the composition");
855 std::vector<ExtSync> trial = ext_syncs_;
857 model_checked(
nullptr, &trial);
858 ext_syncs_.push_back(x);
862 return synchronize(active, std::vector<ActionRef>{passive});
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");
876 if (!owns(r.agent))
throw value_error(
"Synchronization endpoints must belong to the composition");
878 if (!owns(r.agent))
throw value_error(
"Synchronization endpoints must belong to the composition");
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());
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());
897 if (used.count(e))
throw value_error(
"An endpoint can participate in only one synchronization");
901 min_syncs_.push_back(s);
907 if (agents_.empty() && embedded_.empty())
throw value_error(
"Composition requires one or more agents");
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());
915 if (names.size() != agents_.size())
throw value_error(
"Agent names must be unique within a composition");
917 for (
const auto& part : embedded_) {
918 std::set<std::string> injected;
921 if (p.first == part->name() && p.second.index) injected.insert(*p.second.index);
922 part->set_injected(injected);
924 for (
const auto& part : embedded_) {
926 r.
name = part->name();
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_; }
956 std::ifstream in(path, std::ios::binary);
958 std::ostringstream os;
975 friend struct detail::Lowering;
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_;
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);
991 rewards_.push_back(std::make_pair(
name, std::move(fn)));
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");
997 if (embedded_.size() > 1)
throw value_error(
"several embedded models: give part=<prefix>");
998 return embedded_.front();
1000 for (
const auto& p : embedded_)
1001 if (p->name() == *part)
return p;
1002 throw value_error(
"no embedded model named " + *part);
1006 void model_checked(
const std::vector<Sync>*
syncs,
const std::vector<ExtSync>*
ext_syncs)
const {
1010 }
catch (
const InputError& exc) {
1011 if (std::string(exc.what()).find(
"Unconnected passive action") == std::string::npos)
throw;
1015 bool owns(
const Agent& a)
const {
1016 for (
const Agent& b : agents_)
1017 if (b.same(a))
return true;
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) {
1026 if (t.role != role) bad =
true;
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;
1045 while (pos < source.size()) {
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) ||
1050 throw value_error(
"Unexpected character at line " + std::to_string(line_of(pos)) +
": '" +
1051 std::string(1, source[pos]) +
"'");
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));
1062 auto has = [&](
const std::string& n) {
return model.has_agent(n); };
1064 const std::string kind = take();
1065 if (kind ==
"param") {
1066 const std::string name = this->name();
1068 const double value = number();
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();
1076 std::vector<std::string> states{this->name()};
1077 while (peek_is(
",")) {
1079 states.push_back(this->name());
1083 std::optional<std::vector<double>> distribution;
1084 std::string initial;
1088 distribution = std::vector<double>();
1090 distribution->push_back(to_float(take()));
1091 if (!peek_is(
","))
break;
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) {
1103 initial = states[first];
1105 initial = this->name();
1108 std::vector<Transition> transitions;
1109 while (!peek_is(
"}")) {
1111 t.source = this->name();
1114 t.action = this->name();
1116 const std::string role = take();
1117 if (role ==
"rate") {
1121 }
else if (role ==
"passive") {
1130 }
else if (role ==
"immediate") {
1134 while (peek_is(
",")) {
1136 const std::string key = take();
1138 if (key ==
"weight") {
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");
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");
1153 throw value_error(
"Unknown immediate attribute '" + key +
"'");
1157 throw value_error(
"Unknown action role '" + role +
"'");
1161 t.target = this->name();
1163 transitions.push_back(t);
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);
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") {
1181 while (!peek_is(
"}")) {
1182 const std::string k = take();
1183 if (k ==
"synchronize_min") {
1185 s.active.push_back(endpoint());
1186 while (peek_is(
",")) {
1188 s.active.push_back(endpoint());
1190 if (peek_is(
"->")) {
1192 s.passive.push_back(endpoint());
1193 while (peek_is(
",")) {
1195 s.passive.push_back(endpoint());
1199 model.min_syncs.push_back(s);
1202 if (k !=
"synchronize")
throw value_error(
"Unknown synchronization '" + k +
"'");
1204 s.active = endpoint();
1206 s.passive.push_back(endpoint());
1207 while (peek_is(
",")) {
1209 s.passive.push_back(endpoint());
1212 model.syncs.push_back(s);
1216 throw value_error(
"Unknown declaration '" + kind +
"'");
1224 std::vector<std::pair<std::string, int>> tokens_;
1226 std::map<std::string, double> params_;
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; }
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 '" +
1242 std::string name() {
1243 const std::string v = take();
1244 if (!is_identifier(v))
throw value_error(
"Expected identifier, got '" + v +
"'");
1249 static std::optional<double> try_float(
const std::string& s) {
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(
"");
1257 std::size_t used = 0;
1258 const double v = std::stod(t, &used);
1259 if (used == t.size())
return v;
1262 return std::nullopt;
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 +
"'");
1272 const std::string v = take();
1274 const auto f = try_float(v);
1278 auto it = params_.find(v);
1279 if (it == params_.end())
throw value_error(
"Unknown parameter '" + v +
"'");
1282 if (!std::isfinite(n) || n <= 0)
throw value_error(
"Rates and weights must be finite and positive");
1287 const std::string a = name();
1296inline Model parse(
const std::string& source) {
return detail::Parser(source).parse(); }
1300 std::vector<Agent>
agents;
1302 auto find = [&](
const std::string& n) ->
const Agent& {
1304 if (a.name() == n)
return a;
1309 std::vector<ActionRef> ps;
1310 for (
const Endpoint& p : s.
passive) ps.push_back(find(p.first).action(p.second));
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));
A finite-state agent with active, weighted passive and immediate transitions (handle semantics).
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...
bool same(const Agent &o) const
Agent & command(const std::string &action, const CommandOptions &o)
Add a guarded command to a typed-variable agent (command).
bool unbounded_queue() const
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.
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)
const std::vector< std::string > & states() const
static Agent from_record(const AgentRecord &value)
Rebuild a builder agent from a parsed record (as Composition.from_string does).
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.
const std::vector< Transition > & transitions() const
Agent & passive(const std::string &source, const std::string &action, const std::string &target, ValueFn weight)
Agent & setInitialDistribution(const std::map< std::string, double > &p)
static std::vector< Agent > array(const Agent &prototype, long n)
n copies of prototype named <name>_0 ... <name>_{n-1}, labels suffixed [i] (Agent....
ActionRef action(const std::string &name) const
Reference an existing action (a transition or a command) for synchronisation.
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).
const std::string & name() const
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,...
AgentRecord record() const
The immutable record (_record); a typed-variable agent is expanded from its initial valuation.
const std::optional< QueueInfo > & queue_info() const
Agent & set_initial_distribution(const std::vector< double > &p)
Start the agent from a law over its states, a vector in state order.
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.
Agent(const std::string &name, const std::vector< std::string > &states, const std::string &initial)
const std::optional< std::vector< double > > & initial_distribution() const
const std::string & initial() const
Agent & setInitialDistribution(const std::vector< double > &p)
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.
A collection of agents and embedded LINE models with atomic synchronisations (Composition).
Composition(const std::string &name)
Composition & setReward(const std::string &name, RewardFn fn)
Declare a state reward fn(view), read back with getAvgReward().
const std::vector< Sync > & syncs() const
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).
Composition(const std::string &name, const std::vector< Agent > &agents)
const std::vector< std::pair< std::string, RewardFn > > & rewards() const
Composition & add(const Agent &agent)
Add a hand-declared agent.
Composition & add(const Composition &model)
Nest a composition: its agents, embedded models, synchronisations, hidden labels and rewards join thi...
static Composition from_file(const std::string &path)
Load a .lal declaration from a UTF-8 file (from_file).
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.
Composition & synchronize(const ActionRef &active, const std::vector< ActionRef > &passives)
Synchronise one active action with one or more hand passive actions.
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).
Composition(const std::vector< Agent > &agents)
std::optional< std::vector< std::size_t > > source_sync
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.
Composition & set_reward(const std::string &name, RewardFn fn)
Composition & add_part(std::shared_ptr< EmbeddedPart > part)
Add an embedded part built elsewhere (embed_part).
Composition & hide(const ActionSpec &action)
Make actions internal (hide): they still occur, but leave the action tables.
Model model(const std::vector< Sync > *syncs=nullptr, const std::vector< ExtSync > *ext_syncs=nullptr) const
The current model snapshot (_model).
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...
const std::vector< ExtSync > & ext_syncs() const
Composition & refresh()
Re-read every embedded LINE model after it was changed.
const std::string & name() const
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 ...
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.
const std::set< std::string > & hidden() const
Composition & synchronize(const NodeRef &active, const ActionRef &passive)
Compiled get_struct() const
Finite CTMC states, generator and labelled event matrices (get_struct).
Composition(const char *name)
Composition & synchronize(const ActionRef &active, const ActionRef &passive)
const std::vector< Agent > & agents() const
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
std::vector< std::string > source_event_order
const std::vector< MinSync > & min_syncs() const
Composition(std::initializer_list< Agent > agents)
const std::vector< std::shared_ptr< EmbeddedPart > > & embedded() const
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 ...
Read-only view of a joint state, for functional rates and rewards (StateView).
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.
const char * role_name(Role r)
std::vector< std::pair< std::string, double > > NamedWeights
Model parse(const std::string &source)
Parse a .lal source into a validated model record (core.parse).
Role
Transition role: active (rate), passive (weight) or immediate (weight, zero time).
std::function< double(const StateView &)> RewardFn
A state reward: a function of the joint-state view (Composition::setReward).
std::pair< std::string, std::string > Endpoint
(agent, action).
std::function< double(const StateView &)> ValueFn
A functional rate or weight: a function of the joint-state view.
std::map< std::string, long > Vars
The valuation of the typed variables of an agent (v in a guard, update or rate).
std::string endpoint_repr(const Endpoint &e)
Python's repr of an endpoint tuple, ('agent', 'action').
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...
InputError value_error(const std::string &what)
LINE:input:Unspecified, the C++ spelling of the Python ValueError raised throughout LAL.
void validate_model(const Model &model, bool allow_unbounded=false)
Validate the common agent model used by both frontends (validate_model).
std::vector< std::pair< std::string, Matrix< double > > > NamedMatrices
EventType
The events a state can undergo, with the values of MATLAB EventType.
Conservation laws of a layered queueing network, enumerated from its structure.
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).
Keyword arguments of Composition::add for an embedded LINE model.
std::string prefix
Names the embedded part; required when two parts would share node names.
std::optional< double > cutoff
Bounds open classes as SolverCTMC's cutoff does.
The immutable agent record (core.Agent).
std::optional< std::vector< double > > initial_distribution
std::vector< Transition > transitions
std::vector< std::string > states
std::optional< QueueInfo > queue_info
std::shared_ptr< EmbeddedPart > embedded
An embedded LINE model, whose states are global state indices; null for a hand agent.
std::optional< long > unbounded_initial
bool discrete
A discrete-time agent (an embedded MarkovChain).
Keyword arguments of Agent::command.
std::function< Vars(const Vars &)> update
The variables the command changes; an empty function changes none.
std::optional< CommandValue > weight
role Passive or Immediate: default 1
std::optional< CommandValue > rate
role Active: required
std::function< bool(const Vars &)> guard
A rate or weight of a guarded command: a number, a function f(v) of the agent's own variables,...
std::function< double(const Vars &, const StateView &)> joint
std::function< double(const Vars &)> local
The compiled finite CTMC (core.Compiled).
Hand passives that join every event of an embedded part carrying a key matching pattern.
std::vector< Endpoint > passive
The lowering of a minimum-rate synchronisation (_lower_minimum).
A minimum-rate synchronisation: at least two active endpoints and optional passive ones.
std::vector< Endpoint > passive
std::vector< Endpoint > active
A composition snapshot (core.Model): agents in declaration order plus synchronisations.
std::vector< MinSync > min_syncs
std::vector< std::pair< std::string, RewardFn > > rewards
declared state rewards, in order
std::vector< Sync > syncs
std::vector< ExtSync > ext_syncs
std::vector< AgentRecord > agents
std::set< std::string > hidden
labels removed from the action tables
Key of an embedded node action: (node, EventType, class | mode).
An action of a node of an embedded LINE model (NodeRef): key is the (node, EventType,...
An ordinary synchronisation: one active endpoint, hand passives and injected node arrivals.
std::vector< std::pair< std::string, NodeEvent > > node_passive
(embedded part, ARV key): the hand action injects an arrival at that node.
std::vector< Endpoint > passive
One labelled local transition source --(action, value)--> target.
std::vector< std::string > label
A user-supplied chain: a MarkovProcess when discrete is false, else a MarkovChain.
The intermediate model, and the second stage that flattens it.