5#ifndef LINE_LANG_LAL_CORE_H
6#define LINE_LANG_LAL_CORE_H
66#include <unordered_map>
139typedef std::pair<std::string, std::string>
Endpoint;
160 std::string out =
model.empty() ? std::string() :
model +
".";
201 virtual const std::string&
name()
const = 0;
203 virtual const std::string&
prefix()
const = 0;
207 virtual const std::vector<NodeEvent>&
labels() = 0;
209 virtual std::vector<EmbeddedArc>
outgoing(std::size_t s) = 0;
215 virtual std::vector<std::pair<std::size_t, double>>
inject(std::size_t s,
const NodeEvent& key) = 0;
220 const std::optional<std::string>& mode) = 0;
230 virtual std::vector<std::pair<std::string, std::size_t>>
node_states() = 0;
234 virtual std::vector<double>
node_row(std::size_t s,
const std::string& node) = 0;
236 virtual double node_jobs(std::size_t s,
const std::string& node,
const std::string& jobclass) = 0;
240 virtual std::size_t
stage_of(std::size_t) {
return 0; }
242 virtual std::vector<std::string>
stage_names() {
return std::vector<std::string>(); }
280 std::vector<std::pair<std::string, double>>
routes;
303 for (std::size_t i = 0; i <
states.size(); ++i)
304 if (
states[i] == s)
return i;
305 return static_cast<std::size_t
>(-1);
316 std::vector<std::pair<std::string, RewardFn>>
rewards;
318 std::size_t
index_of(
const std::string& name)
const {
319 for (std::size_t i = 0; i <
agents.size(); ++i)
320 if (
agents[i].name == name)
return i;
321 return static_cast<std::size_t
>(-1);
323 bool has_agent(
const std::string& name)
const {
return index_of(name) !=
static_cast<std::size_t
>(-1); }
325 const std::size_t i =
index_of(name);
326 if (i ==
static_cast<std::size_t
>(-1))
throw value_error(
"Unknown agent " + name);
330 const std::size_t i =
index_of(name);
331 if (i ==
static_cast<std::size_t
>(-1))
throw value_error(
"Unknown agent " + name);
349 bool contains(
const std::string& agent)
const {
return model_->has_agent(agent); }
352 const std::size_t a = position(agent);
354 if (rec.
embedded)
return std::to_string((*state_)[a]);
355 return rec.
states[(*state_)[a]];
358 std::size_t
index(
const std::string& agent)
const {
return (*state_)[position(agent)]; }
360 long var(
const std::string& agent,
const std::string& variable)
const {
361 const std::size_t a = position(agent);
363 for (std::size_t k = 0; k < rec.
var_names.size(); ++k)
365 throw value_error(
"agent " + agent +
" has no variable " + variable);
368 std::vector<double>
node(
const std::string& agent,
const std::string&
node)
const {
369 const std::size_t a = position(agent);
375 double jobs(
const std::string& agent,
const std::string&
node,
const std::string& jobclass = std::string())
const {
376 const std::size_t a = position(agent);
379 return rec.
embedded->node_jobs((*state_)[a],
node, jobclass);
383 const std::vector<std::size_t>&
state()
const {
return *state_; }
386 std::size_t position(
const std::string& agent)
const {
387 const std::size_t a = model_->
index_of(agent);
388 if (a ==
static_cast<std::size_t
>(-1))
throw value_error(
"Unknown agent " + agent);
392 const std::vector<std::size_t>* state_;
397 std::vector<std::vector<std::size_t>>
states;
409 std::vector<std::string> out;
410 for (std::size_t a = 0; a <
states[i].size(); ++a)
416 for (std::size_t k = 0; k <
labels.size(); ++k)
424inline bool is_identifier(
const std::string& v) {
425 if (v.empty())
return false;
426 auto alpha = [](
char c) {
return (c >=
'A' && c <=
'Z') || (c >=
'a' && c <=
'z') || c ==
'_'; };
427 if (!alpha(v[0]))
return false;
429 if (!alpha(c) && !(c >=
'0' && c <=
'9'))
return false;
433inline std::string repr_double(
double x) {
434 std::ostringstream os;
440inline bool contains(
const std::vector<Endpoint>& v,
const Endpoint& e) {
441 return std::find(v.begin(), v.end(), e) != v.end();
444inline std::string join_sorted(
const std::set<std::string>& s) {
446 for (
const std::string& x : s) out += (out.empty() ?
"" :
", ") + x;
459 return t.
label.empty() ? std::vector<std::string>{agent +
"." + t.
action} : t.
label;
473 std::ostringstream os;
476 os <<
"A[" << a.
name <<
"|";
478 os <<
"E:" << a.
embedded->name() <<
":" <<
static_cast<const void*
>(a.
embedded.get()) <<
"]";
481 for (
const std::string& s : a.
states) os << s <<
",";
486 os <<
"fn<" << t.
fn.target_type().name() <<
">";
490 for (
const std::string& l : t.
label) os <<
":" << l;
504 for (
const auto& p : s.
node_passive) os <<
"," << p.first <<
":" << p.second.label();
515 os <<
"X[" << s.agent <<
":" << s.pattern.label();
519 for (
const std::string& h : m.
hidden) os <<
"H[" << h <<
"]";
520 for (
const auto& r : m.
rewards) os <<
"R[" << r.first <<
":" << r.second.target_type().name() <<
"]";
526 std::set<std::string> features;
529 features.insert(
"embedded");
534 if (t.
fn) features.insert(
"functional");
538 if (!model.
ext_syncs.empty()) features.insert(
"embedded");
551 const std::vector<AgentRecord>& agents = model.
agents;
552 if (agents.empty())
throw value_error(
"At least one agent is required");
554 std::set<std::string> names;
556 if (!names.insert(a.name).second)
throw value_error(
"Invalid states or initial state in " + a.name);
559 const std::string& name = agent.name;
560 if (agent.embedded) {
561 if (name != agent.embedded->name())
throw value_error(
"Invalid embedded agent name " + name);
564 if (agent.unbounded_queue && !allow_unbounded)
566 "This method requires finite agents; the composition contains an unbounded queue.");
567 std::set<std::string> uniq(agent.states.begin(), agent.states.end());
568 if (agent.states.empty() || uniq.size() != agent.states.size() || !uniq.count(agent.initial))
569 throw value_error(
"Invalid states or initial state in " + name);
570 if (agent.initial_distribution) {
571 const std::vector<double>& p = *agent.initial_distribution;
572 bool ok = p.size() == agent.states.size();
575 if (!std::isfinite(x) || x < 0) ok =
false;
578 if (!ok || !(std::fabs(
sum - 1.0) <= 1e-12))
throw value_error(
"Invalid initial distribution in " + name);
580 for (
const Transition& t : agent.transitions) {
586 "Rates must be finite and nonnegative; passive and immediate weights must be positive");
590 auto roles = [&](
const Endpoint& ep) -> std::optional<std::set<Role>> {
592 if (a.
embedded)
return std::nullopt;
601 "a discrete-time agent (MarkovChain) must be the only part of its composition: "
602 "LINE has no composition of DTMCs.");
604 std::set<Endpoint> used_active, used_passive;
606 std::vector<std::string> agent_names{s.
active.first};
608 for (
const auto& p : s.
node_passive) agent_names.push_back(p.first);
609 const std::set<std::string> distinct(agent_names.begin(), agent_names.end());
610 bool unknown =
false;
611 for (
const std::string& n : agent_names)
613 if ((s.
passive.empty() && s.
node_passive.empty()) || unknown || distinct.size() != agent_names.size())
614 throw value_error(
"Synchronization requires distinct known agents");
615 bool reused = used_active.count(s.
active) || used_passive.count(s.
active);
617 if (used_active.count(p)) reused =
true;
618 if (reused)
throw value_error(
"An endpoint can participate in only one synchronization");
619 used_active.insert(s.
active);
621 const std::optional<std::set<Role>> r = roles(s.
active);
624 ": an embedded node action cannot drive a hand-agent synchronization; synchronize the "
625 "node key with hand passives instead");
626 bool only_active = !r->empty() && r->size() == 1;
631 const std::optional<std::set<Role>> rb = roles(b);
633 if (rb->empty() || *rb != std::set<Role>{Role::Passive})
639 throw value_error(
"('" + b.first +
"', " + b.second.label() +
") must have only passive transitions");
640 part.
embedded->check_injection(b.second);
644 std::vector<Endpoint> endpoints = s.
active;
645 endpoints.insert(endpoints.end(), s.
passive.begin(), s.
passive.end());
646 if (s.
active.size() < 2)
throw value_error(
"minimum synchronization requires at least two active endpoints");
647 const std::set<Endpoint> eps(endpoints.begin(), endpoints.end());
648 bool reused = eps.size() != endpoints.size();
650 if (used_active.count(e) || used_passive.count(e)) reused =
true;
651 if (reused)
throw value_error(
"An endpoint can participate in only one synchronization");
652 std::set<std::string> agents_in;
653 bool unknown =
false;
654 for (
const Endpoint& e : endpoints) {
655 if (!model.
has_agent(e.first)) unknown =
true;
656 agents_in.insert(e.first);
658 if (unknown || agents_in.size() != endpoints.size())
659 throw value_error(
"Synchronization requires distinct known agents");
663 "synchronize_min cannot take an embedded node action: it would retime LINE's "
668 bool any =
false, bad =
false;
670 if (t.action == ep.second) {
672 if (t.role != role) bad =
true;
683 std::set<std::string> names{x.
agent};
684 bool unknown =
false;
686 if (!model.
has_agent(p.first)) unknown =
true;
687 names.insert(p.first);
689 if (x.
passive.empty() || unknown || names.size() != x.
passive.size() + 1)
690 throw value_error(
"Synchronization requires distinct known agents");
692 const std::optional<std::set<Role>> rb = roles(b);
699 if (agent.embedded)
continue;
708 std::set<Endpoint> min_members, min_heads;
711 min_heads.insert(s.
active.front());
713 std::vector<std::string> labels;
714 std::set<std::string> seen;
715 auto add = [&](
const std::string& l) {
716 if (seen.insert(l).second) labels.push_back(l);
723 if (p.second.model == agent.
embedded->prefix()) add(p.second.label());
729 if (min_members.count(ep) && !min_heads.count(ep))
continue;
746inline std::vector<Event>
selected(
const std::vector<Event>& events) {
748 int top = std::numeric_limits<int>::min();
749 for (
const Event& e : events)
752 top = std::max(top, e.priority);
754 if (!any)
return events;
755 std::vector<Event> out;
756 for (
const Event& e : events)
757 if (e.immediate && e.priority == top) out.push_back(e);
775 for (std::size_t k = 0; k <
labels.size(); ++k) label_index_[
labels[k]] = k;
780 for (std::size_t a = 0; a < n; ++a) {
782 if (
ag.embedded)
continue;
783 local_[a].assign(
ag.states.size(), {});
784 tlabels_[a].resize(
ag.transitions.size());
785 for (std::size_t k = 0; k <
ag.transitions.size(); ++k) {
787 local_[a][
ag.state_index(t.
source)].push_back(k);
790 bool member =
false, head =
false;
792 if (detail::contains(s.
active, ep)) member =
true;
793 if (s.
active.front() == ep) head =
true;
795 if (member && !head)
continue;
796 for (
const std::string& l :
transition_labels(
ag.name, t)) tlabels_[a][k].push_back(index_of(l));
813 std::vector<PassiveRef> refs;
814 std::vector<std::size_t> extra;
816 for (
const auto& p : s.node_passive) {
817 refs.push_back(PassiveRef{
model.
index_of(p.first), std::string(),
true, p.second});
818 extra.push_back(index_of(p.second.label()));
821 sync_labels_[s.
active] = extra;
824 std::vector<PassiveRef> refs;
833 auto it = label_index_.find(label);
834 if (it == label_index_.end())
throw value_error(
"Unknown event label " + label);
841 std::vector<Event>
outgoing(
const std::vector<std::size_t>& state)
const {
842 std::vector<Event> out;
844 const std::size_t n = model_.agents.size();
845 for (std::size_t ai = 0; ai < n; ++ai) {
850 std::vector<PassiveRef> partners;
851 for (
const auto& join : ext_[ai]) {
854 if (emb.
matches(k, join.first)) hit =
true;
855 if (hit) partners.insert(partners.end(), join.second.begin(), join.second.end());
857 std::vector<std::size_t> keys;
858 for (
const NodeEvent& k : arc.keys) keys.push_back(index_of(k.
label()));
859 const std::vector<std::vector<Choice>> sets = passive_choices(state, view, partners);
860 product(sets, [&](
const std::vector<const Choice*>& choice) {
863 e.
target[ai] = arc.target;
865 for (
const Choice* c : choice) {
866 e.
target[c->agent] = c->target;
870 e.
rate = arc.rate * prob;
873 out.push_back(std::move(e));
878 std::vector<std::pair<int, std::vector<Event>>> timed;
879 for (std::size_t k : local_[ai][state[ai]]) {
883 if (min_members_.count(endpoint))
continue;
885 if (!(rate > 0))
continue;
887 std::vector<std::size_t> tl = tlabels_[ai][k];
888 std::vector<std::vector<Choice>> sets;
889 auto sit = sync_.find(endpoint);
890 if (sit != sync_.end()) {
891 sets = passive_choices(state, view, sit->second);
892 const std::vector<std::size_t>& extra = sync_labels_.at(endpoint);
893 tl.insert(tl.end(), extra.begin(), extra.end());
895 std::vector<Event> evs;
896 product(sets, [&](
const std::vector<const Choice*>& choice) {
901 for (
const Choice* c : choice) {
902 e.
target[c->agent] = c->target;
906 e.
rate = rate * prob;
909 evs.push_back(std::move(e));
912 for (
Event& e : evs) out.push_back(std::move(e));
913 }
else if (!evs.empty()) {
914 timed.push_back(std::make_pair(t.
priority, std::move(evs)));
920 if (!timed.empty()) {
921 int top = timed.front().first;
922 for (
const auto& p : timed) top = std::max(top, p.first);
923 for (
auto& p : timed)
925 for (
Event& e : p.second) out.push_back(std::move(e));
928 for (std::size_t m = 0; m < model_.min_syncs.size(); ++m) {
929 const MinSync& s = model_.min_syncs[m];
930 std::vector<std::vector<Choice>> choices;
931 std::vector<double> totals;
932 std::vector<Endpoint> all = s.
active;
935 const std::size_t pi = model_.index_of(e.first);
938 choices.push_back(candidates(pi, e.second, role, state[pi], view, &total));
941 const double rate = *std::min_element(totals.begin(), totals.end());
942 if (rate == 0)
continue;
943 product(choices, [&](
const std::vector<const Choice*>& choice) {
947 for (
const Choice* c : choice) {
948 e.
target[c->agent] = c->target;
951 e.
labels = std::vector<std::size_t>{min_label_[m]};
952 e.
rate = rate * prob;
953 out.push_back(std::move(e));
972 std::size_t index_of(
const std::string& label)
const {
973 auto it = label_index_.find(label);
974 if (it == label_index_.end())
979 std::vector<Choice> candidates(std::size_t pi,
const std::string& action,
Role role, std::size_t local,
980 const StateView& view,
double* total_out =
nullptr)
const {
981 const AgentRecord& other = model_.agents[pi];
982 std::vector<std::pair<const Transition*, double>> cand;
984 for (std::size_t k : local_[pi][local]) {
986 if (p.role != role || p.action != action)
continue;
989 cand.push_back(std::make_pair(&p, w));
993 if (total_out) *total_out = total;
994 std::vector<Choice> out;
995 if (total == 0)
return out;
996 for (
const auto& c : cand) out.push_back(Choice{pi, other.state_index(c.first->target), c.second / total});
1000 std::vector<std::vector<Choice>> passive_choices(
const std::vector<std::size_t>& state,
const StateView& view,
1001 const std::vector<PassiveRef>& partners)
const {
1002 std::vector<std::vector<Choice>> out;
1003 for (
const PassiveRef& p : partners) {
1004 const AgentRecord& other = model_.agents[p.agent];
1006 std::vector<Choice> c;
1007 for (
const auto& r : other.embedded->inject(state[p.agent], p.key))
1008 c.push_back(Choice{p.agent, r.first, r.second});
1012 out.push_back(candidates(p.agent, p.action,
Role::Passive, state[p.agent], view));
1019 static void product(
const std::vector<std::vector<Choice>>& sets, F&& f) {
1020 for (
const auto& s : sets)
1021 if (s.empty())
return;
1022 std::vector<std::size_t> idx(sets.size(), 0);
1023 std::vector<const Choice*> pick(sets.size());
1025 for (std::size_t i = 0; i < sets.size(); ++i) pick[i] = &sets[i][idx[i]];
1027 if (sets.empty())
return;
1028 std::size_t d = sets.size();
1031 if (++idx[d] < sets[d].size())
break;
1038 const Model& model_;
1039 std::map<std::string, std::size_t> label_index_;
1040 std::vector<std::vector<std::vector<std::size_t>>> local_;
1041 std::vector<std::vector<std::vector<std::size_t>>> tlabels_;
1042 std::map<Endpoint, std::vector<PassiveRef>> sync_;
1043 std::map<Endpoint, std::vector<std::size_t>> sync_labels_;
1044 std::set<Endpoint> min_members_;
1045 std::vector<std::size_t> min_label_;
1046 std::vector<std::vector<std::pair<NodeEvent, std::vector<PassiveRef>>>> ext_;
1073 std::size_t
label_index(
const std::string& label)
const {
return events_.label_index(label); }
1079 std::vector<Move>
outgoing(
const std::vector<std::size_t>& state,
1080 const std::vector<bool>* include =
nullptr)
const {
1081 std::vector<Move> out;
1082 for (
Event& e : events_.outgoing(state)) {
1083 const std::size_t lab = e.labels.front();
1084 if (include && !(*include)[lab])
continue;
1086 m.
target = std::move(e.target);
1089 out.push_back(std::move(m));
1099 std::set<std::string> refused;
1100 for (
const std::string& f : features)
1101 if (f ==
"immediate" || f ==
"embedded" || f ==
"multilabel") refused.insert(f);
1102 if (!refused.empty())
1104 "this LAL method supports only timed hand-declared agents; the composition uses " +
1105 detail::join_sorted(refused) +
" actions.");
1109 const Model& model_;
1122inline std::size_t isqrt(std::size_t v) {
1123 std::size_t r =
static_cast<std::size_t
>(std::sqrt(
static_cast<double>(v)));
1124 while (r * r > v) --r;
1125 while ((r + 1) * (r + 1) <= v) ++r;
1130 std::size_t operator()(
const std::vector<std::size_t>& v)
const {
1131 std::size_t h = 1469598103934665603ULL;
1132 for (std::size_t x : v) {
1133 h ^= x + 0x9e3779b97f4a7c15ULL + (h << 6) + (h >> 2);
1148inline void complement(Compiled& c,
const Matrix<double>& allrates,
const std::vector<bool>& vanish) {
1149 const std::size_t n = c.states.size();
1150 std::vector<std::size_t> T, V;
1151 for (std::size_t i = 0; i < n; ++i) (vanish[i] ? V : T).push_back(i);
1154 "every reachable state is vanishing: the immediate actions never let time advance.");
1155 const std::size_t nt = T.size(), nv = V.size();
1156 Matrix<double> off = allrates;
1157 for (std::size_t i = 0; i < n; ++i) off(i, i) = 0.0;
1159 Matrix<double> A(nv, nv, 0.0), At(nv, nv, 0.0);
1160 for (std::size_t a = 0; a < nv; ++a) {
1162 for (std::size_t j = 0; j < n; ++j) out += off(V[a], j);
1163 for (std::size_t b = 0; b < nv; ++b) A(a, b) = -off(V[a], V[b]);
1166 for (std::size_t a = 0; a < nv; ++a)
1167 for (std::size_t b = 0; b < nv; ++b) At(b, a) = A(a, b);
1168 Matrix<double> absorb(nv, nt, 0.0), entry(nt, nv, 0.0);
1171 std::vector<std::size_t> piv =
lu_factor(A);
1172 std::vector<std::size_t> pivt =
lu_factor(At);
1173 for (std::size_t t = 0; t < nt; ++t) {
1174 std::vector<double> b(nv);
1175 for (std::size_t a = 0; a < nv; ++a) b[a] = off(V[a], T[t]);
1177 for (std::size_t a = 0; a < nv; ++a) absorb(a, t) = b[a];
1179 for (std::size_t t = 0; t < nt; ++t) {
1180 std::vector<double> b(nv);
1181 for (std::size_t a = 0; a < nv; ++a) b[a] = off(T[t], V[a]);
1183 for (std::size_t a = 0; a < nv; ++a) entry(t, a) = b[a];
1185 }
catch (
const NumericError&) {
1188 for (std::size_t a = 0; ok && a < nv; ++a) {
1190 for (std::size_t t = 0; t < nt; ++t) s += absorb(a, t);
1191 if (!std::isfinite(s) || std::fabs(s - 1.0) > 1e-8 + 1e-5 * 1.0) ok =
false;
1195 "the immediate actions form a cycle that never returns to a tangible state.");
1196 auto restrict = [&](
const Matrix<double>& r) {
1197 Matrix<double> out(nt, nt, 0.0);
1199 Matrix<double> rva(nv, nt, 0.0);
1200 for (std::size_t a = 0; a < nv; ++a)
1201 for (std::size_t b = 0; b < nv; ++b) {
1202 const double x = r(V[a], V[b]);
1203 if (x == 0)
continue;
1204 for (std::size_t t = 0; t < nt; ++t) rva(a, t) += x * absorb(b, t);
1206 for (std::size_t i = 0; i < nt; ++i)
1207 for (std::size_t j = 0; j < nt; ++j) {
1208 double v = r(T[i], T[j]);
1209 for (std::size_t a = 0; a < nv; ++a) {
1210 v += r(T[i], V[a]) * absorb(a, j);
1211 v += entry(i, a) * (r(V[a], T[j]) + rva(a, j));
1217 Matrix<double> q(nt, nt, 0.0);
1218 for (std::size_t i = 0; i < nt; ++i)
1219 for (std::size_t j = 0; j < nt; ++j) {
1220 double v = off(T[i], T[j]);
1221 for (std::size_t a = 0; a < nv; ++a) v += off(T[i], V[a]) * absorb(a, j);
1224 for (std::size_t i = 0; i < nt; ++i) {
1227 for (std::size_t j = 0; j < nt; ++j) s += q(i, j);
1230 for (Matrix<double>& E : c.events) E = restrict(E);
1231 std::vector<double> p0(nt, 0.0);
1232 for (std::size_t t = 0; t < nt; ++t) {
1233 p0[t] = c.initial_distribution[T[t]];
1234 for (std::size_t a = 0; a < nv; ++a) p0[t] += c.initial_distribution[V[a]] * absorb(a, t);
1236 std::vector<std::vector<std::size_t>> tangible;
1237 for (std::size_t t : T) tangible.push_back(c.states[t]);
1238 std::size_t init = 0;
1239 for (std::size_t t = 0; t < nt; ++t)
1244 c.states = std::move(tangible);
1245 c.generator = std::move(q);
1246 c.initial_distribution = std::move(p0);
1248 c.vanishing_eliminated = nv;
1264 const Events kernel(model);
1265 const std::vector<std::string>& labels = kernel.
labels;
1267 const bool reachable_only =
opt.reachable_only || features.count(
"embedded");
1268 std::size_t max_states =
opt.max_states;
1269 std::string limit_note;
1270 if (reachable_only &&
opt.max_dense_bytes > 0) {
1271 const std::size_t cap = std::max<std::size_t>(
1272 1, detail::isqrt(
opt.max_dense_bytes / (8 * (labels.size() + 4))));
1273 if (max_states == 0 || cap < max_states) {
1275 limit_note =
" (set by the dense matrix storage limit of " + std::to_string(
opt.max_dense_bytes) +
1279 const std::size_t n = model.
agents.size();
1280 std::vector<std::vector<std::pair<std::size_t, double>>> choices(n);
1281 double support = 1.0;
1282 for (std::size_t a = 0; a < n; ++a) {
1285 choices[a].push_back({agent.
embedded->initial(), 1.0});
1289 for (std::size_t s = 0; s < agent.
states.size(); ++s)
1292 support *=
static_cast<double>(choices[a].size());
1294 if (reachable_only && max_states > 0 && support >
static_cast<double>(max_states))
1296 std::to_string(max_states) + limit_note);
1297 std::vector<std::pair<std::vector<std::size_t>,
double>> initial_states;
1299 std::vector<std::size_t> idx(n, 0);
1301 for (
const auto& c : choices)
1302 if (c.empty()) done =
true;
1304 std::vector<std::size_t> st(n);
1306 for (std::size_t a = 0; a < n; ++a) {
1307 st[a] = choices[a][idx[a]].first;
1308 p *= choices[a][idx[a]].second;
1310 initial_states.push_back({st, p});
1318 if (++idx[d] < choices[d].size())
break;
1323 std::vector<std::pair<std::size_t, EmbeddedPart*>> vanishing_parts;
1324 for (std::size_t a = 0; a < n; ++a)
1325 if (model.
agents[a].embedded && model.
agents[a].embedded->has_vanishing())
1326 vanishing_parts.push_back({a, model.
agents[a].embedded.get()});
1327 auto enabled = [&](
const std::vector<std::size_t>& state,
bool& is_vanishing) {
1328 std::vector<Event> evs;
1330 if (e.rate > 0) evs.push_back(std::move(e));
1331 is_vanishing =
false;
1332 for (
const Event& e : evs)
1333 if (e.immediate) is_vanishing =
true;
1334 for (
const auto& vp : vanishing_parts)
1335 if (vp.second->is_vanishing(state[vp.first])) is_vanishing =
true;
1336 return is_vanishing ?
selected(evs) : evs;
1340 std::unordered_map<std::vector<std::size_t>, std::size_t, detail::StateHash> lookup;
1341 std::vector<std::vector<Event>> out;
1342 std::vector<bool> vanish;
1343 if (reachable_only) {
1344 if (max_states > 0 && initial_states.size() > max_states)
1345 throw StateSpaceLimitError(
"reachable state space exceeds limit " + std::to_string(max_states) +
1347 for (
const auto& is : initial_states) {
1348 if (!lookup.count(is.first)) lookup[is.first] = c.
states.size();
1349 c.
states.push_back(is.first);
1351 for (std::size_t i = 0; i < c.
states.size(); ++i) {
1352 const std::vector<std::size_t> state = c.
states[i];
1354 std::vector<Event> evs = enabled(state, v);
1355 for (
const Event& e : evs) {
1356 if (!lookup.count(e.target)) {
1357 if (max_states > 0 && c.
states.size() >= max_states)
1359 std::to_string(max_states) + limit_note);
1360 lookup[e.target] = c.
states.size();
1361 c.
states.push_back(e.target);
1364 out.push_back(std::move(evs));
1365 vanish.push_back(v);
1368 std::vector<std::size_t> idx(n, 0);
1370 lookup[idx] = c.
states.size();
1380 if (++idx[d] < model.
agents[d].states.size())
break;
1385 for (std::size_t i = 0; i < c.
states.size(); ++i) {
1387 out.push_back(enabled(c.
states[i], v));
1388 vanish.push_back(v);
1391 const std::size_t N = c.
states.size();
1392 const double estimate =
static_cast<double>(N) *
static_cast<double>(N) * 8.0 * (labels.size() + 4);
1393 if (
opt.max_dense_bytes > 0 && estimate >
static_cast<double>(
opt.max_dense_bytes)) {
1394 std::ostringstream os;
1396 os <<
"estimated dense matrix storage is " <<
static_cast<unsigned long long>(estimate)
1397 <<
" bytes; limit is " <<
opt.max_dense_bytes;
1401 for (
const auto& is : initial_states) c.
initial_distribution[lookup.at(is.first)] += is.second;
1402 c.
initial = lookup.at(initial_states.front().first);
1407 for (std::size_t i = 0; i < N; ++i)
1408 for (
const Event& e : out[i]) {
1409 const std::size_t j = lookup.at(e.target);
1410 allrates(i, j) += e.rate;
1411 for (std::size_t l : e.labels) c.
events[l](i, j) += e.rate;
1417 bool any_vanishing =
false;
1418 for (
bool v : vanish) any_vanishing = any_vanishing || v;
1419 if (!any_vanishing) {
1421 for (std::size_t i = 0; i < N; ++i) {
1424 for (std::size_t j = 0; j < N; ++j) s += c.
generator(i, j);
1429 detail::complement(c, allrates, vanish);
InternalError(const std::string &what)
One CTMC state as a state-set predicate sees it, the reference's RewardState: the AGGREGATE row of st...
UnsupportedError(const std::string &what)
An embedded LINE model seen by the LAL core (Python's EmbeddedNetwork / EmbeddedEnvironment duck type...
virtual NodeEvent resolve(const std::string &node, lang::EventType event, const std::optional< std::string > &jobclass, const std::optional< std::string > &mode)=0
The key of a node action, validated against the model's names.
virtual double node_jobs(std::size_t s, const std::string &node, const std::string &jobclass)=0
Jobs at a station in global state s: the total, or those of class jobclass when nonempty.
virtual bool has_vanishing()=0
True when the embedded model has any vanishing state.
virtual std::size_t initial()=0
The global index of the initial state.
virtual const std::string & prefix() const =0
The embedding prefix, empty when none was given.
virtual std::vector< std::pair< std::string, std::size_t > > node_states()=0
[(node name, isf)] of the stateful node agents (isf is 1-based).
virtual void check_injection(const NodeEvent &key)=0
Refuse a key that a hand agent cannot drive.
virtual void refresh()=0
Re-read the embedded model on next use.
virtual void set_injected(const std::set< std::string > &)
Record the classes hand agents inject (names); a change invalidates the enumeration.
virtual bool is_vanishing(std::size_t s)=0
True when s is a vanishing state of the embedded model.
virtual std::string class_name(std::size_t cls)=0
Name of the 1-based class index of the model.
virtual std::vector< double > node_row(std::size_t s, const std::string &node)=0
The state row of a stateful node in global state s.
virtual std::vector< std::pair< std::size_t, double > > inject(std::size_t s, const NodeEvent &key)=0
Passive response to an injected arrival: [(target, probability)]; empty blocks it.
virtual std::size_t stage_of(std::size_t)
The stage of global state s (Environment only).
virtual bool matches(const NodeEvent &key, const NodeEvent &pattern) const
True when key is pattern, or pattern leaves the index open.
virtual std::string node_name(std::size_t node)=0
Name of the 1-based node index of the model.
virtual bool has_stages()
True for an embedded Environment, whose stage is an agent of its own.
virtual const std::vector< NodeEvent > & labels()=0
Every node key an arc carries, in first-seen order.
virtual const std::string & name() const =0
The part name (the prefix, or the model name).
virtual std::vector< EmbeddedArc > outgoing(std::size_t s)=0
Arcs leaving global state s.
virtual std::string node_state_label(std::size_t s, std::size_t isf)=0
The state row of stateful node isf in global state s, as [v1 v2 ...].
virtual std::vector< std::string > stage_names()
The stage names (Environment only).
std::size_t label_index(const std::string &label) const
std::vector< std::string > labels
std::vector< Move > outgoing(const std::vector< std::size_t > &state, const std::vector< bool > *include=nullptr) const
Outgoing moves of state.
EventKernel(const Model &model)
const Model & model() const
The extended event kernel (events): the ordered labels and the enabled events of a joint state,...
Events(const Model &model)
std::size_t label_index(const std::string &label) const
std::vector< std::string > labels
std::vector< Event > outgoing(const std::vector< std::size_t > &state) const
The enabled events of state (zero-rate events are kept out).
const Model & model() const
StateSpaceLimitError(const std::string &what)
Read-only view of a joint state, for functional rates and rewards (StateView).
std::size_t index(const std::string &agent) const
StateView(const Model &model, const std::vector< std::size_t > &state)
std::vector< double > node(const std::string &agent, const std::string &node) const
const Model & model() const
bool contains(const std::string &agent) const
const std::vector< std::size_t > & state() const
std::string operator[](const std::string &agent) const
long var(const std::string &agent, const std::string &variable) const
double jobs(const std::string &agent, const std::string &node, const std::string &jobclass=std::string()) const
The exception types the port throws.
Enumerations and the minimal distribution descriptor shared by the model layer of the C++ port.
LU factorization with partial pivoting, templated on the number type.
Dense matrix and non-owning view.
const char * role_name(Role r)
std::string signature(const Model &m)
A deterministic text signature of a model snapshot (Python's repr(model)), used by the solvers to cac...
double transition_value(const Transition &t, const StateView &view)
The value of a transition in a joint state (_value).
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::string endpoint_repr(const Endpoint &e)
Python's repr of an endpoint tuple, ('agent', 'action').
std::vector< std::string > transition_labels(const std::string &agent, const Transition &t)
All labels of a transition: a multi-label transition credits one firing to each.
bool has_discrete(const Model &model)
True when any agent of the model is discrete-time.
std::vector< std::string > event_labels(const Model &model)
Ordered event labels: hand active/immediate labels, then embedded node keys (event_labels).
std::vector< Event > selected(const std::vector< Event > &events)
Apply maximal progress and immediate priorities to the enabled events (selected).
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::string endpoint_label(const Endpoint &e)
bool node_event_matches(const NodeEvent &key, const NodeEvent &pattern)
True when key is pattern, or pattern leaves the index open.
std::set< std::string > model_features(const Model &model)
Features of a model that only the extended kernel interprets (model_features).
std::string transition_label(const std::string &agent, const Transition &t)
Primary label of a transition (its first label when it carries several).
EventType
The events a state can undergo, with the values of MATLAB EventType.
@ LOCAL
dummy event, no state change outside the node
const char * event_to_text(EventType e)
Conservation laws of a layered queueing network, enumerated from its structure.
void lu_solve(const Matrix< T > &LU, const std::vector< std::size_t > &piv, std::vector< T > &b)
Solve LUx = Pb in place on b, using the factors from lu_factor.
std::vector< std::size_t > lu_factor(Matrix< T > &A)
In-place LU of A (n x n).
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
The immutable agent record (core.Agent).
std::optional< std::vector< double > > initial_distribution
std::vector< Transition > transitions
std::vector< std::vector< long > > var_values
std::vector< std::string > var_names
Typed-variable agents: the variable names, and the valuation of each local state.
std::vector< std::string > states
std::optional< QueueInfo > queue_info
std::size_t state_index(const std::string &s) const
Zero-based index of a local state, or npos.
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).
Options of compile_model.
std::size_t max_dense_bytes
The compiled finite CTMC (core.Compiled).
std::vector< std::string > labels
event labels, in order
std::vector< std::vector< std::string > > agent_states
empty for an embedded agent
std::vector< double > initial_distribution
const Matrix< double > & event(const std::string &label) const
The rate matrix of a label; throws for an unknown label.
std::size_t vanishing_eliminated
std::vector< std::string > state_names(std::size_t i) const
The Python tuple of state names for joint state i (an embedded agent shows its global index).
std::vector< Matrix< double > > events
one rate matrix per label
std::vector< std::string > agent_names
std::vector< std::vector< std::size_t > > states
joint states as local indices
Matrix< double > generator
One arc of an embedded model: (target, keys, rate, immediate) (an immediate arc carries a weight).
std::vector< NodeEvent > keys
One enabled joint event: successor, label indices, rate (weight if immediate), priority (Event).
std::vector< std::size_t > labels
indices into Events::labels
std::vector< std::size_t > target
Hand passives that join every event of an embedded part carrying a key matching pattern.
std::vector< Endpoint > passive
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
bool has_agent(const std::string &name) const
std::vector< std::pair< std::string, RewardFn > > rewards
declared state rewards, in order
std::vector< Sync > syncs
std::vector< ExtSync > ext_syncs
std::size_t index_of(const std::string &name) const
std::vector< AgentRecord > agents
AgentRecord & agent(const std::string &name)
const AgentRecord & agent(const std::string &name) const
std::set< std::string > hidden
labels removed from the action tables
One outgoing joint-state move of the legacy event kernel.
std::vector< std::size_t > target
std::size_t label
index into EventKernel::labels
Key of an embedded node action: (node, EventType, class | mode).
std::optional< std::string > index
bool operator!=(const NodeEvent &o) const
bool operator==(const NodeEvent &o) const
bool operator<(const NodeEvent &o) const
std::string label() const
Structured queue declaration retained while a queue agent is unmodified (queue_info).
std::optional< long > capacity
nullopt: unbounded
std::optional< std::string > service_phase
std::vector< std::string > service_inputs
std::optional< double > service_rate
nullopt: passive service
std::vector< std::string > departures
std::optional< std::string > service_input
std::vector< std::pair< std::string, double > > routes
std::vector< std::string > arrivals
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
bool tuple_label
The label is a TUPLE (python Transition.label given as a tuple), which marks a multi-label event even...
bool operator==(const Transition &o) const
Value equality; two functional values compare equal by kind only (a std::function has no identity).
bool operator!=(const Transition &o) const