5#ifndef LINE_LANG_LAL_CTMC_H
6#define LINE_LANG_LAL_CTMC_H
51 nlohmann::json
extra = nlohmann::json::object();
68 std::vector<StateRow>
rows;
70 std::size_t
size()
const {
return rows.size(); }
72 double probability(
const std::string& agent,
const std::string& state)
const {
74 if (r.agent == agent && r.state == state)
return r.probability;
75 throw value_error(
"No state row " + agent +
"." + state);
80 std::vector<ActionRow>
rows;
82 std::size_t
size()
const {
return rows.size(); }
86 if (r.action == action)
return r.throughput;
105 std::vector<std::vector<std::size_t>>
states;
110 std::vector<std::pair<std::string, double>>
rewards;
119inline std::vector<int> strong_components(
const std::vector<std::vector<std::size_t>>& adj,
int& count) {
120 const std::size_t n = adj.size();
121 std::vector<int> index(n, -1), low(n, 0), comp(n, -1);
122 std::vector<char> on(n, 0);
123 std::vector<std::size_t> stack;
126 for (std::size_t s = 0; s < n; ++s) {
127 if (index[s] != -1)
continue;
128 std::vector<std::pair<std::size_t, std::size_t>> call{{s, 0}};
129 index[s] = low[s] = next++;
132 while (!call.empty()) {
133 const std::size_t v = call.back().first;
134 std::size_t& it = call.back().second;
135 if (it < adj[v].size()) {
136 const std::size_t w = adj[v][it++];
137 if (index[w] == -1) {
138 index[w] = low[w] = next++;
141 call.push_back({w, 0});
143 low[v] = std::min(low[v], index[w]);
146 if (low[v] == index[v]) {
148 const std::size_t w = stack.back();
158 const std::size_t u = call.back().first;
159 low[u] = std::min(low[u], low[v]);
168 const std::vector<std::size_t>& c) {
170 for (std::size_t i = 0; i < r.size(); ++i)
171 for (std::size_t j = 0; j < c.size(); ++j) out(i, j) = q(r[i], c[j]);
184 const std::vector<double>& probs) {
186 for (std::size_t a = 0; a < snapshot.
agents.size(); ++a) {
189 std::vector<double> m(agent.
states.size(), 0.0);
190 for (std::size_t i = 0; i < states.size(); ++i) m[states[i][a]] += probs[i];
191 for (std::size_t s = 0; s < agent.
states.size(); ++s) t.
rows.push_back({agent.name, agent.states[s], m[s]});
195 const std::string prefix = emb.
prefix().empty() ? std::string() : emb.
prefix() +
".";
197 std::map<std::size_t, double> marg;
198 for (std::size_t i = 0; i < states.size(); ++i) marg[emb.
stage_of(states[i][a])] += probs[i];
199 const std::vector<std::string> names = emb.
stage_names();
200 for (
const auto& kv : marg)
201 t.
rows.push_back({prefix +
"Env", kv.first < names.size() ? names[kv.first] : std::to_string(kv.first),
205 std::vector<std::string> order;
206 std::map<std::string, double> marg;
207 for (std::size_t i = 0; i < states.size(); ++i) {
209 if (!marg.count(label)) order.push_back(label);
210 marg[label] += probs[i];
212 for (
const std::string& label : order) t.
rows.push_back({prefix + node.first, label, marg[label]});
225 const std::vector<std::vector<std::size_t>>& states,
226 const std::vector<double>& probs) {
227 std::vector<std::pair<std::string, double>> out;
228 for (
const auto& r : snapshot.
rewards) {
230 for (std::size_t i = 0; i < states.size(); ++i)
231 if (probs[i] != 0) v += probs[i] * r.second(
StateView(snapshot, states[i]));
232 out.push_back(std::make_pair(r.first, v));
239 const Model* snapshot =
nullptr) {
241 for (std::size_t k = 0; k < compiled.
labels.size(); ++k) {
242 if (snapshot && is_hidden(*snapshot, compiled.
labels[k]))
continue;
245 for (std::size_t i = 0; i < E.
rows(); ++i) {
247 for (std::size_t j = 0; j < E.
cols(); ++j) s += E(i, j);
273 const std::size_t N = compiled.
states.size();
274 std::set<std::size_t> seen;
275 for (std::size_t i = 0; i < N; ++i)
277 std::vector<std::size_t> pending(seen.begin(), seen.end());
278 for (std::size_t p = 0; p < pending.size(); ++p) {
279 const std::size_t i = pending[p];
280 for (std::size_t j = 0; j < N; ++j)
281 if (q(i, j) > 0 && !seen.count(j)) {
283 pending.push_back(j);
286 const std::vector<std::size_t> reachable(seen.begin(), seen.end());
287 const std::size_t R = reachable.size();
289 std::vector<std::vector<std::size_t>> adj(R);
290 for (std::size_t i = 0; i < R; ++i)
291 for (std::size_t j = 0; j < R; ++j)
292 if (i != j && qr(i, j) != 0) adj[i].push_back(j);
294 const std::vector<int> labels = detail::strong_components(adj, count);
298 std::vector<std::vector<std::size_t>> members(
static_cast<std::size_t
>(count));
299 for (std::size_t i = 0; i < R; ++i) members[static_cast<std::size_t>(labels[i])].push_back(i);
300 std::vector<std::vector<std::size_t>> closed;
301 for (
const auto& m : members) {
303 for (std::size_t i : m)
304 for (std::size_t j : adj[i])
305 if (labels[j] != labels[i] && qr(i, j) > 0) out =
true;
306 if (!out) closed.push_back(m);
308 std::sort(closed.begin(), closed.end());
309 std::vector<char> recurrent(R, 0);
310 for (
const auto& m : closed)
311 for (std::size_t i : m) recurrent[i] = 1;
312 std::vector<std::size_t> transient;
313 for (std::size_t i = 0; i < R; ++i)
314 if (!recurrent[i]) transient.push_back(i);
315 std::vector<double> w0(R);
318 std::vector<std::size_t> piv;
319 if (!transient.empty()) {
320 lu = detail::submatrix(qr, transient, transient);
321 for (std::size_t k = 0; k < lu.size(); ++k) lu[k] = -lu[k];
324 std::vector<double> probs(N, 0.0);
325 for (
const auto& m : closed) {
327 for (std::size_t i : m) weight += w0[i];
328 if (!transient.empty()) {
329 std::vector<double> flow(transient.size(), 0.0);
330 for (std::size_t t = 0; t < transient.size(); ++t)
331 for (std::size_t i : m) flow[t] += qr(transient[t], i);
333 for (std::size_t t = 0; t < transient.size(); ++t) weight += w0[transient[t]] * flow[t];
335 std::vector<std::size_t> rec;
336 for (std::size_t i : m) rec.push_back(reachable[i]);
337 const std::vector<double> pc =
mc::ctmc_solve(detail::submatrix(q, rec, rec));
338 for (std::size_t k = 0; k < rec.size(); ++k) probs[rec[k]] = weight * pc[k];
370 const std::vector<AgentRecord>& agents = snapshot.
agents;
371 const std::size_t K = agents.size();
372 std::vector<int> init(K);
373 for (std::size_t i = 0; i < K; ++i) {
376 std::size_t nz = 0, first = 0;
379 if (nz == 0) first = s;
383 init[i] =
static_cast<int>(first);
388 std::map<Endpoint, std::vector<Endpoint>> sync;
391 std::vector<std::size_t> lev;
392 std::vector<Matrix<double>> W;
395 std::vector<DenseEvent> events;
396 for (std::size_t i = 0; i < K; ++i) {
398 std::vector<std::string> actions;
401 actions.push_back(t.
action);
402 for (
const std::string& action : actions) {
403 const std::size_t n = agent.
states.size();
410 ev.W.push_back(active);
411 ev.label = agent.
name +
"." + action;
413 if (it != sync.end()) {
414 for (
const Endpoint& p : it->second) {
415 const std::size_t j = snapshot.
index_of(p.first);
417 const std::size_t m = other.
states.size();
422 for (std::size_t r = 0; r < m; ++r) {
424 for (std::size_t c = 0; c < m; ++c) s += block(r, c);
425 for (std::size_t c = 0; c < m; ++c) block(r, c) = s > 0 ? block(r, c) / s : 0.0;
428 ev.W.push_back(block);
431 events.push_back(std::move(ev));
436 std::size_t expanded = 0;
437 auto successors = [&](
const std::vector<int>& state,
bool check) -> std::vector<std::vector<int>> {
440 if (expanded > max_states)
442 "LAL MDD reachability exceeds " + std::to_string(max_states) +
" states.");
444 std::set<std::vector<int>> result;
445 for (
const DenseEvent& ev : events) {
446 std::vector<std::vector<int>> local;
448 for (std::size_t t = 0; t < ev.lev.size(); ++t) {
451 const std::size_t row =
static_cast<std::size_t
>(state[ev.lev[t]]);
452 for (std::size_t c = 0; c < b.
cols(); ++c)
453 if (b(row, c) > 0) nz.push_back(
static_cast<int>(c));
454 if (nz.empty()) empty =
true;
458 std::vector<std::size_t> idx(local.size(), 0);
460 std::vector<int> target = state;
461 for (std::size_t t = 0; t < local.size(); ++t) target[ev.lev[t]] = local[t][idx[t]];
462 result.insert(target);
463 std::size_t d = local.size();
471 if (++idx[d] < local[d].size())
break;
477 return std::vector<std::vector<int>>(result.begin(), result.end());
479 std::vector<int> domain(K);
480 for (std::size_t i = 0; i < K; ++i) domain[i] = static_cast<int>(agents[i].states.size());
482 mdd::mdd_reachset(domain, init, [&](
const std::vector<int>& s) {
return successors(s,
true); });
483 const std::vector<std::vector<int>> states = diagram.
enumerate();
484 std::map<std::vector<int>, std::size_t> lookup;
485 for (std::size_t i = 0; i < states.size(); ++i) lookup[states[i]] = i;
486 std::vector<std::vector<std::size_t>> adj(states.size());
487 std::size_t edges = 0;
488 for (std::size_t i = 0; i < states.size(); ++i)
489 for (
const std::vector<int>& target : successors(states[i],
false)) {
490 adj[i].push_back(lookup.at(target));
491 if (++edges > 1000000)
495 detail::strong_components(adj, ncomp);
502 for (
const DenseEvent& ev : events) {
504 e.
a = ev.lev.front();
509 for (std::size_t r = 0; r < w.
rows(); ++r)
510 for (std::size_t c = 0; c < w.
cols(); ++c) b.
add(r, c, w(r, c));
513 desc.
events.push_back(std::move(e));
517 for (std::size_t i = 0; i < K; ++i) {
518 const std::size_t k = K - 1 - i;
519 std::vector<double> marginal(agents[i].states.size(), 0.0);
520 for (std::size_t r = 0; r < out.
mcd.
Mrows[k].size(); ++r)
521 marginal[
static_cast<std::size_t
>(out.
mcd.
Mrows[k][r].second)] += out.
mcd.
pik[k][r];
522 for (std::size_t j = 0; j < agents[i].states.size(); ++j)
523 out.
table.
rows.push_back({agents[i].name, agents[i].states[j], marginal[j]});
UnsupportedError(const std::string &what)
An embedded LINE model seen by the LAL core (Python's EmbeddedNetwork / EmbeddedEnvironment duck type...
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 std::size_t stage_of(std::size_t)
The stage of global state s (Environment only).
virtual bool has_stages()
True for an embedded Environment, whose stage is an agent of its own.
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).
Raised when finite-state compilation exceeds a configured resource limit.
StateView(const Model &model, const std::vector< std::size_t > &state)
The diagram: insert / member / index / enumerate / cardinality.
MddStruct to_struct() const
Export the diagram as plain arrays for downstream algorithms.
std::vector< std::vector< int > > enumerate() const
All stored states as rows, in index() order.
Incremental triplet builder; duplicate entries are accumulated.
Builder & add(std::size_t i, std::size_t j, const T &value)
Accumulate value into entry (i,j).
MddLocalMatrix< T > build() const
LINE Agent Language (LAL): the finite-agent model record, its validation, the joint-state event kerne...
Steady-state distribution of a continuous-time Markov chain.
LU factorization with partial pivoting, templated on the number type.
Quasi-reduced ordered Multi-valued Decision Diagram.
Miner-Ciardo-Donatelli approximate stationary analysis.
Reachability set generation into a decision diagram.
The rate side of the decision-diagram domain: local matrices, events, the Kronecker descriptor,...
std::pair< std::string, std::string > Endpoint
(agent, action).
bool has_discrete(const Model &model)
True when any agent of the model is discrete-time.
MddSolution solve_mdd(const Model &snapshot, std::size_t max_states=100000)
MDD aggregation for finite active/passive compositions (solve_mdd).
std::vector< std::pair< std::string, double > > reward_values(const Model &snapshot, const std::vector< std::vector< std::size_t > > &states, const std::vector< double > &probs)
Stationary expectation of every declared reward (reward_values).
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...
StateTable agent_state_rows(const Model &snapshot, const std::vector< std::vector< std::size_t > > &states, const std::vector< double > &probs)
Marginal state probabilities of every agent (agent_state_rows): one row per local state of a hand age...
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).
ActionTable action_table(const Compiled &compiled, const std::vector< double > &probs, const Model *snapshot=nullptr)
Labelled event throughputs probs @ rowsum(event), hidden labels left out.
Result solve_composition(const Model &snapshot, std::size_t max_states=0, std::size_t max_dense_bytes=kDefaultMaxDenseBytes)
Solve a finite composition, respecting its initial state if reducible (solve_composition).
StateTable marginal_table(const Model &snapshot, const Compiled &compiled, const std::vector< double > &probs)
Agent-state marginals of a joint probability vector, in the Python row order.
static const std::size_t kDefaultMaxDenseBytes
Default dense-storage budget of the CTMC path: 256 MiB.
std::vector< T > ctmc_solve(const Matrix< T > &Qin, const std::string &linsolver=std::string())
Steady-state distribution of a continuous-time Markov chain.
MDD mdd_reachset(const std::vector< int > &domain, const std::vector< int > &init, const MddNextState &nextfun)
Generate and store the reachability set into a quasi-reduced ordered MDD.
MddMcdResult< T > mdd_mcd(const MddStruct &mdds, const MddDescriptor< T > &desc, const MddMcdOptions &options=MddMcdOptions())
Approximate stationary measures by decision-diagram-guided aggregation.
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).
One row of an action table: Action, Throughput.
std::vector< ActionRow > rows
double throughput(const std::string &action) const
Throughput of one action label; throws when absent.
The immutable agent record (core.Agent).
std::optional< std::vector< double > > initial_distribution
std::vector< Transition > transitions
std::vector< std::string > states
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.
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< double > initial_distribution
std::vector< Matrix< double > > events
one rate matrix per label
std::vector< std::vector< std::size_t > > states
joint states as local indices
Matrix< double > generator
The output of solve_mdd: the marginal table and the MCD aggregation.
mdd::MddMcdResult< double > mcd
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::size_t index_of(const std::string &name) const
std::vector< AgentRecord > agents
The result container shared by the LAL solver paths (LALCTMCResult, the AG decomposition results,...
std::vector< double > probabilities
joint probabilities (CTMC)
std::optional< Compiled > compiled
nlohmann::json diagnostics
std::vector< std::vector< std::size_t > > states
joint states (CTMC)
std::optional< std::string > fallback_reason
std::vector< std::pair< std::string, double > > rewards
Stationary expectations of the rewards declared with Composition::setReward, in order.
One row of a state table: Agent, State, Probability.
double probability(const std::string &agent, const std::string &state) const
Probability of one agent state; throws when absent.
std::vector< StateRow > rows
An ordinary synchronisation: one active endpoint, hand passives and injected node arrivals.
std::vector< Endpoint > passive
The attrs of a LAL result table.
nlohmann::json extra
remaining Python attrs
std::optional< std::string > fallback_reason
std::optional< bool > exact
One labelled local transition source --(action, value)--> target.
Kronecker rate descriptor of a structured model, the input of mdd_mcd.
std::vector< int > domain
Local domain per level.
std::vector< int > init
Initial local index per level.
std::vector< MddEvent< T > > events
The events of the descriptor.
std::size_t K
Number of levels, i.e.
One event of the Kronecker rate descriptor.
std::size_t b
Station (or mode) the event arrives at, 0-based; equals a for an internal event.
std::size_t a
Station (or transition node) the event departs from, 0-based.
std::vector< MddLocalMatrix< T > > W
Local matrices at the levels named by lev.
std::vector< std::size_t > lev
Levels the event touches, as 0-based level indices, aligned with W.
Result of the Miner-Ciardo-Donatelli level aggregation.
std::vector< std::vector< T > > pik
pik[k] is the level-k stationary vector over M_k, in paper orientation.
std::vector< std::vector< std::pair< int, int > > > Mrows
Mrows[k][r] = {node id, local value} of row r of M_k.