LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
ssa.h
Go to the documentation of this file.
1/*
2 * Copyright (c) 2012-2026, QORE Lab, Imperial College London
3 * All rights reserved.
4 */
5#ifndef LINE_LANG_LAL_SSA_H
6#define LINE_LANG_LAL_SSA_H
7
8/**
9 * @file
10 * @ingroup line_lang
11 * LINE Agent Language (LAL): on-demand Gillespie simulation of a finite
12 * composition (`lal/ssa.py`). Both the serial direct method and the next
13 * reaction method walk the event kernel without building the joint state
14 * space.
15 *
16 * The random stream is std::mt19937_64 seeded with `seed`; the Python path
17 * draws from numpy's PCG64, so the two agree in distribution, not sample path.
18 */
19
20#include <cmath>
21#include <limits>
22#include <map>
23#include <queue>
24#include <random>
25#include <set>
26#include <string>
27#include <tuple>
28#include <vector>
29
30#include "line/lang/lal/ctmc.h"
31
32namespace line {
33namespace lal {
34
35/** The SSA result (`LALSSAResult`). */
36struct SSAResult {
39 long events = 0; ///< measured events (after warm-up)
40 double duration = 0; ///< measured time; +inf when absorbed
41 bool absorbed = false;
42 std::string method = "ssa";
43 /** Estimates of the rewards declared with `Composition::setReward`, in order. */
44 std::vector<std::pair<std::string, double>> rewards;
45};
46
47namespace detail {
48
49class SsaRng {
50 public:
51 explicit SsaRng(unsigned long long seed) : gen_(seed) {}
52 double uniform() { return std::generate_canonical<double, 53>(gen_); }
53 /** Exponential with the given mean (numpy's `exponential(scale)`). */
54 double exponential(double scale) { return -std::log1p(-uniform()) * scale; }
55 std::size_t choice(const std::vector<double>& p) {
56 const double u = uniform();
57 double c = 0.0;
58 for (std::size_t i = 0; i < p.size(); ++i) {
59 c += p[i];
60 if (u < c) return i;
61 }
62 for (std::size_t i = p.size(); i-- > 0;)
63 if (p[i] > 0) return i;
64 return p.size() - 1;
65 }
66
67 private:
68 std::mt19937_64 gen_;
69};
70
71using LocalDelta = std::vector<std::pair<std::size_t, std::size_t>>;
72
73struct Step {
74 std::vector<std::size_t> previous;
75 std::vector<std::size_t> target;
76 std::size_t label;
77 double duration;
78};
79
80/**
81 * Agents whose state each event reads (`_dependencies`): the agent named by
82 * the label's prefix, plus every partner of the synchronisation keyed by its
83 * active endpoint `agent.action`.
84 */
85inline std::vector<std::set<std::string>> ssa_dependencies(const Model& snapshot, const EventKernel& kernel) {
86 std::vector<std::set<std::string>> deps(kernel.labels.size());
87 for (std::size_t k = 0; k < kernel.labels.size(); ++k)
88 deps[k].insert(kernel.labels[k].substr(0, kernel.labels[k].find('.')));
89 for (const Sync& s : snapshot.syncs) {
90 const std::size_t k = kernel.label_index(endpoint_label(s.active));
91 for (const Endpoint& p : s.passive) deps[k].insert(p.first);
92 }
93 for (const MinSync& s : snapshot.min_syncs) {
94 const std::size_t k = kernel.label_index(endpoint_label(s.active.front()));
95 for (const Endpoint& e : s.active) deps[k].insert(e.first);
96 for (const Endpoint& e : s.passive) deps[k].insert(e.first);
97 }
98 return deps;
99}
100
101/** Consecutive zero-time firings after which an immediate cycle is reported. */
102static const long kImmediateCycleLimit = 1000000;
103
104/**
105 * Serial simulation of compositions with immediate, functional or embedded
106 * actions (`_simulate_extended`). Immediate events fire in zero time with
107 * maximal progress and priorities, as in `compile_model`; their firings are
108 * counted in the throughputs but take no time. Embedded LINE models contribute
109 * their own events.
110 */
111inline SSAResult simulate_extended(const Model& snapshot, long events, unsigned long long seed, double warmupfrac,
112 const std::string& method) {
113 if (has_discrete(snapshot))
114 throw UnsupportedError(ErrorKind("Model"),
115 "SolverSSA simulates continuous time; a discrete-time composition (MarkovChain) has no "
116 "holding times to sample.");
117 if (method != "ssa")
118 throw UnsupportedError(ErrorKind("Method"),
119 "the next-reaction method (nrm) supports timed hand-declared agents only; use the "
120 "serial method for immediate, functional or embedded actions.");
121 const Events kernel(snapshot);
122 SsaRng rng(seed);
123 const std::vector<AgentRecord>& agents = snapshot.agents;
124 const std::size_t K = agents.size();
125 std::vector<std::size_t> state(K);
126 for (std::size_t i = 0; i < K; ++i)
127 state[i] = agents[i].embedded ? agents[i].embedded->initial()
128 : agents[i].initial_distribution ? rng.choice(*agents[i].initial_distribution)
129 : agents[i].state_index(agents[i].initial);
130 std::vector<std::pair<std::size_t, EmbeddedPart*>> vanishing_parts;
131 for (std::size_t i = 0; i < K; ++i)
132 if (agents[i].embedded && agents[i].embedded->has_vanishing())
133 vanishing_parts.push_back({i, agents[i].embedded.get()});
134 const long warmup = static_cast<long>(static_cast<double>(events) * warmupfrac);
135 std::map<std::vector<std::size_t>, double> occupied;
136 std::vector<long> counts(kernel.labels.size(), 0);
137 double elapsed = 0.0;
138 long measured = 0, zero_run = 0;
139 bool absorbed = false;
140 for (long step = 0; step < events; ++step) {
141 std::vector<Event> evs;
142 for (Event& e : kernel.outgoing(state))
143 if (e.rate > 0) evs.push_back(std::move(e));
144 if (evs.empty()) {
145 absorbed = true;
146 break;
147 }
148 bool immediate = false;
149 for (const Event& e : evs) immediate = immediate || e.immediate;
150 bool vanishing = immediate;
151 for (const auto& vp : vanishing_parts) vanishing = vanishing || vp.second->is_vanishing(state[vp.first]);
152 if (vanishing) evs = selected(evs);
153 double total = 0.0;
154 for (const Event& e : evs) total += e.rate;
155 if (!std::isfinite(total)) throw value_error("Total enabled event rate must be finite");
156 const double duration = immediate ? 0.0 : rng.exponential(1.0 / total);
157 zero_run = immediate ? zero_run + 1 : 0;
158 if (zero_run > kImmediateCycleLimit)
159 throw UnsupportedError(ErrorKind("Model"),
160 "the immediate actions form a cycle that never returns to a tangible state.");
161 const double draw = rng.uniform() * total;
162 double cumulative = 0.0;
163 const Event* chosen = &evs.back();
164 for (const Event& e : evs) {
165 cumulative += e.rate;
166 if (draw < cumulative) {
167 chosen = &e;
168 break;
169 }
170 }
171 if (step >= warmup) {
172 occupied[state] += duration;
173 elapsed += duration;
174 for (std::size_t l : chosen->labels) counts[l] += 1;
175 ++measured;
176 }
177 state = chosen->target;
178 }
179 const double inf = std::numeric_limits<double>::infinity();
180 if (absorbed) {
181 occupied.clear();
182 occupied[state] = 1.0;
183 std::fill(counts.begin(), counts.end(), 0);
184 elapsed = inf;
185 }
186 if (!absorbed && elapsed <= 0) throw value_error("SSA produced no positive measurement time");
187 std::vector<std::vector<std::size_t>> states;
188 std::vector<double> weights;
189 for (const auto& kv : occupied) {
190 states.push_back(kv.first);
191 weights.push_back(absorbed ? kv.second : kv.second / elapsed);
192 }
193 SSAResult r;
194 r.state_table = agent_state_rows(snapshot, states, weights);
195 for (std::size_t k = 0; k < kernel.labels.size(); ++k)
196 if (!is_hidden(snapshot, kernel.labels[k]))
197 r.action_table.rows.push_back(
198 {kernel.labels[k], absorbed ? 0.0 : static_cast<double>(counts[k]) / elapsed});
199 r.events = measured;
200 r.duration = elapsed;
201 r.absorbed = absorbed;
202 r.method = method;
203 r.rewards = reward_values(snapshot, states, weights);
204 return r;
205}
206
207} // namespace detail
208
209/**
210 * Simulate event races without constructing the joint state space
211 * (`simulate`). `method` is "ssa" (serial direct method) or "nrm".
212 */
213inline SSAResult simulate(const Model& snapshot, long events, unsigned long long seed, double warmupfrac = 0.0,
214 const std::string& method = "ssa") {
215 if (events <= 0) throw value_error("SSA event budget must be a positive integer");
216 if (!std::isfinite(warmupfrac) || !(warmupfrac >= 0 && warmupfrac < 1))
217 throw value_error("warmupfrac must be in [0, 1)");
218 if (!model_features(snapshot).empty() || has_discrete(snapshot))
219 return detail::simulate_extended(snapshot, events, seed, warmupfrac, method);
220 if (method != "ssa" && method != "nrm") throw value_error("Unknown LAL SSA method");
221 const EventKernel kernel(snapshot);
222 const std::size_t L = kernel.labels.size();
223 detail::SsaRng rng(seed);
224 const std::vector<AgentRecord>& agents = snapshot.agents;
225 const std::size_t K = agents.size();
226 std::vector<std::size_t> state(K);
227 for (std::size_t i = 0; i < K; ++i)
228 state[i] = agents[i].initial_distribution ? rng.choice(*agents[i].initial_distribution)
229 : agents[i].state_index(agents[i].initial);
230 const long warmup = static_cast<long>(static_cast<double>(events) * warmupfrac);
231 std::map<std::vector<std::size_t>, double> occupied;
232 std::vector<long> counts(L, 0);
233 double elapsed = 0.0;
234 long measured = 0;
235 long steps = 0;
236 auto record = [&](const detail::Step& s) {
237 if (steps >= warmup) {
238 occupied[s.previous] += s.duration;
239 elapsed += s.duration;
240 counts[s.label] += 1;
241 ++measured;
242 }
243 ++steps;
244 state = s.target;
245 };
246 const double inf = std::numeric_limits<double>::infinity();
247 if (method == "ssa") {
248 std::vector<std::size_t> current = state;
249 for (long e = 0; e < events; ++e) {
250 std::vector<Move> moves;
251 for (Move& m : kernel.outgoing(current))
252 if (m.rate > 0) moves.push_back(std::move(m));
253 double total = 0.0;
254 for (const Move& m : moves) total += m.rate;
255 if (!std::isfinite(total)) throw value_error("Total enabled event rate must be finite");
256 if (total == 0) break;
257 const double duration = rng.exponential(1.0 / total);
258 const double choice = rng.uniform() * total;
259 double cumulative = 0.0;
260 const Move* pick = &moves.back();
261 for (const Move& m : moves) {
262 cumulative += m.rate;
263 if (choice < cumulative) {
264 pick = &m;
265 break;
266 }
267 }
268 record(detail::Step{current, pick->target, pick->label, duration});
269 current = pick->target;
270 }
271 } else {
272 // Next-reaction clocks with dependency-based updates. Each move is
273 // cached as the local updates it makes, never as a joint target: an
274 // event is refreshed only when an agent it reads changes, so a cached
275 // joint target would restore stale states of other agents.
276 const std::vector<std::set<std::string>> deps = detail::ssa_dependencies(snapshot, kernel);
277 std::vector<long> versions(L, 0);
278 std::vector<double> rates(L, 0.0), scheduled(L, inf);
279 using Entry = std::tuple<double, long, std::size_t>;
280 std::priority_queue<Entry, std::vector<Entry>, std::greater<Entry>> heap;
281 std::vector<std::vector<std::pair<detail::LocalDelta, double>>> groups(L);
282 double time = 0.0;
283 auto alternatives = [&](const std::vector<std::size_t>& current, const std::vector<bool>* selected) {
284 for (std::size_t k = 0; k < L; ++k)
285 if (!selected || (*selected)[k]) groups[k].clear();
286 for (const Move& m : kernel.outgoing(current, selected)) {
287 if (!(m.rate > 0)) continue;
288 detail::LocalDelta delta;
289 for (std::size_t i = 0; i < K; ++i)
290 if (current[i] != m.target[i]) delta.push_back({i, m.target[i]});
291 groups[m.label].push_back({delta, m.rate});
292 }
293 };
294 auto update = [&](std::size_t k, double new_rate, bool fired) {
295 const double old_rate = rates[k], old_time = scheduled[k];
296 if (!std::isfinite(new_rate)) throw value_error("Total enabled event rate must be finite");
297 double new_time;
298 if (new_rate == 0)
299 new_time = inf;
300 else if (fired || old_rate == 0)
301 new_time = time + rng.exponential(1.0 / new_rate);
302 else
303 new_time = time + (old_rate / new_rate) * std::max(0.0, old_time - time);
304 rates[k] = new_rate;
305 scheduled[k] = new_time;
306 versions[k] += 1;
307 if (std::isfinite(new_time)) heap.push(Entry(new_time, versions[k], k));
308 };
309 auto total_of = [&](std::size_t k) {
310 double s = 0.0;
311 for (const auto& g : groups[k]) s += g.second;
312 return s;
313 };
314 std::vector<std::size_t> current = state;
315 alternatives(current, nullptr);
316 for (std::size_t k = 0; k < L; ++k) update(k, total_of(k), false);
317 for (long e = 0; e < events; ++e) {
318 while (!heap.empty() && std::get<1>(heap.top()) != versions[std::get<2>(heap.top())]) heap.pop();
319 if (heap.empty()) break;
320 const Entry top = heap.top();
321 heap.pop();
322 const std::size_t label = std::get<2>(top);
323 const double duration = std::get<0>(top) - time;
324 time = std::get<0>(top);
325 const auto& options = groups[label];
326 const double draw = rng.uniform() * rates[label];
327 double cumulative = 0.0;
328 detail::LocalDelta delta = options.back().first;
329 for (const auto& o : options) {
330 cumulative += o.second;
331 if (draw < cumulative) {
332 delta = o.first;
333 break;
334 }
335 }
336 const std::vector<std::size_t> previous = current;
337 for (const auto& d : delta) current[d.first] = d.second;
338 record(detail::Step{previous, current, label, duration});
339 std::set<std::string> changed;
340 for (std::size_t i = 0; i < K; ++i)
341 if (previous[i] != current[i]) changed.insert(agents[i].name);
342 std::vector<bool> affected(L, false);
343 for (std::size_t k = 0; k < L; ++k) {
344 if (k == label) {
345 affected[k] = true;
346 continue;
347 }
348 for (const std::string& n : deps[k])
349 if (changed.count(n)) {
350 affected[k] = true;
351 break;
352 }
353 }
354 alternatives(current, &affected);
355 for (std::size_t k = 0; k < L; ++k)
356 if (affected[k]) update(k, total_of(k), k == label);
357 if (heap.size() > std::max<std::size_t>(100, 4 * L)) {
358 std::priority_queue<Entry, std::vector<Entry>, std::greater<Entry>> fresh;
359 for (std::size_t k = 0; k < L; ++k)
360 if (std::isfinite(scheduled[k])) fresh.push(Entry(scheduled[k], versions[k], k));
361 heap.swap(fresh);
362 }
363 }
364 }
365 bool absorbed = false;
366 if (steps < events) {
367 // The limiting occupation is the reached absorbing state; every
368 // preceding event has zero long-run throughput.
369 occupied.clear();
370 occupied[state] = 1.0;
371 std::fill(counts.begin(), counts.end(), 0);
372 elapsed = inf;
373 absorbed = true;
374 }
375 if (!absorbed && elapsed <= 0) throw value_error("SSA produced no positive measurement time");
376 SSAResult r;
377 for (std::size_t i = 0; i < K; ++i)
378 for (std::size_t s = 0; s < agents[i].states.size(); ++s) {
379 double p = 0.0;
380 for (const auto& kv : occupied)
381 if (kv.first[i] == s) p += absorbed ? kv.second : kv.second / elapsed;
382 r.state_table.rows.push_back({agents[i].name, agents[i].states[s], p});
383 }
384 for (std::size_t k = 0; k < L; ++k)
385 if (!is_hidden(snapshot, kernel.labels[k]))
386 r.action_table.rows.push_back(
387 {kernel.labels[k], absorbed ? 0.0 : static_cast<double>(counts[k]) / elapsed});
388 r.events = measured;
389 r.duration = elapsed;
390 r.absorbed = absorbed;
391 r.method = method;
392 std::vector<std::vector<std::size_t>> visited;
393 std::vector<double> weights;
394 for (const auto& kv : occupied) {
395 visited.push_back(kv.first);
396 weights.push_back(absorbed ? kv.second : kv.second / elapsed);
397 }
398 r.rewards = reward_values(snapshot, visited, weights);
399 return r;
400}
401
402} // namespace lal
403} // namespace line
404
405#endif // LINE_LANG_LAL_SSA_H
UnsupportedError(const std::string &what)
Definition error.h:119
The legacy timed event kernel (event_kernel): the ordered event labels and a lazy joint-state transit...
Definition core.h:1065
std::vector< std::string > labels
Definition core.h:1071
std::vector< Move > outgoing(const std::vector< std::size_t > &state, const std::vector< bool > *include=nullptr) const
Outgoing moves of state.
Definition core.h:1079
LINE Agent Language (LAL): the result tables every LAL solver returns, the exact finite CTMC analysis...
Definition ag.h:49
SSAResult simulate(const Model &snapshot, long events, unsigned long long seed, double warmupfrac=0.0, const std::string &method="ssa")
Simulate event races without constructing the joint state space (simulate).
Definition ssa.h:213
std::pair< std::string, std::string > Endpoint
(agent, action).
Definition core.h:139
bool has_discrete(const Model &model)
True when any agent of the model is discrete-time.
Definition core.h:543
std::vector< Event > selected(const std::vector< Event > &events)
Apply maximal progress and immediate priorities to the enabled events (selected).
Definition core.h:746
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).
Definition ctmc.h:224
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...
Definition ctmc.h:183
InputError value_error(const std::string &what)
LINE:input:Unspecified, the C++ spelling of the Python ValueError raised throughout LAL.
Definition core.h:85
std::string endpoint_label(const Endpoint &e)
Definition core.h:141
std::set< std::string > model_features(const Model &model)
Features of a model that only the extended kernel interprets (model_features).
Definition core.h:525
Matrix< double > events(const LdesSamplePath &sp, long node0)
The event rows of node node0 (0-based), or of every node when it is negative.
double elapsed(const Frame &f)
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
ErrorKind(std::string n)
Definition error.h:39
std::vector< ActionRow > rows
Definition ctmc.h:80
A composition snapshot (core.Model): agents in declaration order plus synchronisations.
Definition core.h:310
std::vector< AgentRecord > agents
Definition core.h:311
One outgoing joint-state move of the legacy event kernel.
Definition core.h:1050
The SSA result (LALSSAResult).
Definition ssa.h:36
ActionTable action_table
Definition ssa.h:38
StateTable state_table
Definition ssa.h:37
double duration
measured time; +inf when absorbed
Definition ssa.h:40
long events
measured events (after warm-up)
Definition ssa.h:39
std::vector< std::pair< std::string, double > > rewards
Estimates of the rewards declared with Composition::setReward, in order.
Definition ssa.h:44
std::string method
Definition ssa.h:42
std::vector< StateRow > rows
Definition ctmc.h:68