5#ifndef LINE_LANG_LAL_SOLVERS_H
6#define LINE_LANG_LAL_SOLVERS_H
53inline std::string lower(std::string s) {
54 for (
char& c : s) c =
static_cast<char>(std::tolower(
static_cast<unsigned char>(c)));
58inline std::string strip_prefix(
const std::string& s,
const std::string& p) {
59 return s.compare(0, p.size(), p) == 0 ? s.substr(p.size()) : s;
62inline std::string network_metric_refusal(
const std::string& caller) {
63 return caller +
" requires queueing-network station and class metrics; "
64 "a general LAL composition provides state and action tables instead.";
73 std::optional<std::pair<double, double>>
timespan;
75 nlohmann::json
config = nlohmann::json::object();
77 std::string
key()
const {
106 const std::string m = detail::lower(method);
107 if (m ==
"default" || m ==
"exact")
return {
true, std::nullopt};
109 const Model snapshot = model_->model();
111 if (!features.empty())
112 return {
false, std::string(
"LAL MDD supports timed hand-declared agents only; the composition uses ") +
113 detail::join_sorted(features) +
" actions."};
115 return {
false, std::string(
"LAL MDD does not support minimum-rate synchronization.")};
121 if (nz != 1)
return {
false, std::string(
"LAL MDD requires deterministic initial states.")};
123 return {
true, std::nullopt};
125 return {
false, std::string(
"LAL compositions support exact finite CTMC enumeration and restricted MDD aggregation.")};
134 "LAL SolverCTMC does not support timespan, init_sol or config options; "
135 "use the composition initial distribution and getTranProbSys(t).");
136 const Model snapshot = model_->model();
137 const bool truncated = model_->source_truncated;
138 std::optional<std::string> fallback_reason;
139 std::optional<Result> solved;
140 if (method !=
"mdd") {
142 solved = solve_(snapshot);
144 if (method !=
"default" || exc.
id() !=
"LINE:unsupported:StateSpace")
throw;
146 fallback_reason = exc.what();
151 if (method ==
"mdd") {
153 const bool exact =
mdd.mcd.no_aggregation && !truncated;
154 mdd.table.attrs.method =
"mdd";
155 mdd.table.attrs.exact = exact;
156 mdd.table.attrs.truncated = truncated;
157 mdd.table.attrs.fallback_reason = fallback_reason;
158 mdd.table.attrs.extra[
"approximation"] =
159 exact ? nlohmann::json(
nullptr) : nlohmann::json(
"MDD level aggregation");
160 result_.state_table =
mdd.table;
161 result_.method =
"mdd";
162 result_.exact = exact;
163 result_.truncated = truncated;
164 result_.mdd = std::move(
mdd.mcd);
169 a->exact = !truncated;
170 a->truncated = truncated;
178 result_.compiled = std::move(r.
compiled);
179 result_.method =
"ctmc";
180 result_.exact = !truncated;
181 result_.truncated = truncated;
187 void reset() { signature_.reset(); }
192 const State& r = ensure_();
193 if (r.method ==
"mdd")
195 return *r.action_table;
208 const std::optional<std::string>& jobclass = std::nullopt,
209 const std::optional<std::string>& mode = std::nullopt) {
210 return getAvgAct(ActionSpec::key(node, event, jobclass, mode));
213 return getAvgAct(ActionSpec::key(node, event, jobclass));
216 std::vector<double>
getActAvg(
const std::vector<ActionSpec>& actions) {
217 std::vector<double> out;
218 for (
const ActionSpec& a : actions) out.push_back(
getAvgAct(a));
225 std::pair<std::vector<double>, std::vector<std::string>>
getAvgReward() {
226 const State& r = ensure_();
228 std::pair<std::vector<double>, std::vector<std::string>> out;
229 for (
const auto& kv : r.rewards) {
230 out.first.push_back(kv.second);
231 out.second.push_back(kv.first);
238 const State& r = ensure_();
239 if (r.method ==
"mdd")
241 "MDD aggregation does not return a joint stationary distribution.");
246 const State& r = ensure_();
247 if (r.method ==
"mdd")
249 return r.compiled->generator;
253 std::pair<Matrix<double>, std::vector<Matrix<double>>>
getGenerator() {
255 return {q, ensure_().compiled->events};
259 const State& r = ensure_();
261 return r.compiled->labels;
268 std::pair<std::vector<std::vector<std::string>>, std::vector<std::vector<std::string>>>
getStateSpace() {
269 const State& r = ensure_();
270 if (r.method ==
"mdd")
272 std::vector<std::vector<std::string>> space;
273 for (std::size_t i = 0; i < r.space.size(); ++i) space.push_back(r.compiled->state_names(i));
274 std::vector<std::vector<std::string>> local(r.compiled->agent_names.size());
275 for (
const auto& row : space)
276 for (std::size_t a = 0; a < row.size(); ++a) local[a].push_back(row[a]);
277 return {space, local};
282 if (!std::isfinite(t) || t < 0)
284 const State& r = ensure_();
285 if (r.method ==
"mdd")
289 if (std::fabs(t - std::round(t)) > 1e-12)
291 "a discrete-time composition advances one step per unit of time, so getTranProbSys "
292 "requires a nonnegative integer number of steps.");
294 std::vector<double> p = r.compiled->initial_distribution;
295 const long steps =
static_cast<long>(std::llround(t));
296 for (
long k = 0; k < steps; ++k) {
297 std::vector<double> next(p.size(), 0.0);
298 for (std::size_t i = 0; i < p.size(); ++i) {
299 if (p[i] == 0)
continue;
300 for (std::size_t j = 0; j < p.size(); ++j) next[j] += p[i] * (Q(i, j) + (i == j ? 1.0 : 0.0));
307 for (std::size_t k = 0; k < qt.
size(); ++k) qt[k] *= t;
309 const std::vector<double>& p0 = r.compiled->initial_distribution;
310 std::vector<double> out(p0.size(), 0.0);
311 for (std::size_t i = 0; i < p0.size(); ++i)
312 for (std::size_t j = 0; j < p0.size(); ++j) out[j] += p0[i] * e(i, j);
318 const State& r = ensure_();
337 bool truncated =
false;
340 std::vector<double> pi;
341 std::vector<std::vector<std::size_t>> space;
342 std::optional<Compiled> compiled;
343 std::optional<mdd::MddMcdResult<double>>
mdd;
344 std::vector<std::pair<std::string, double>> rewards;
345 bool discrete =
false;
350 std::optional<std::string> signature_;
356 std::string key_()
const {
359 const State& ensure_() {
360 if (!signature_ || *signature_ != key_())
runAnalyzer();
372 std::pair<double, double>
timespan{0.0, std::numeric_limits<double>::infinity()};
373 nlohmann::json
config = nlohmann::json::object();
377 double timeout = std::numeric_limits<double>::infinity();
378 double cutoff = std::numeric_limits<double>::infinity();
381 std::ostringstream os;
384 <<
',' << detail::repr_double(
timespan.second) <<
'|' <<
config.dump() <<
'|'
386 << detail::repr_double(
timeout) <<
'|' << detail::repr_double(
cutoff);
409 static std::vector<std::string>
listValidMethods() { return ::line::method_registry::methods(
"SSA"); }
413 const std::string m = detail::strip_prefix(detail::lower(method),
"ssa.");
414 const Model snapshot = model_->model();
416 return {
false, std::string(
"SolverSSA simulates continuous time; a discrete-time composition (MarkovChain) "
417 "has no holding times to sample.")};
420 if (!features.empty())
421 return {
false,
"the next-reaction method supports timed hand-declared agents only; the composition "
422 "uses " + detail::join_sorted(features) +
" actions (use serial)."};
424 if (m ==
"default" || m ==
"serial" || m ==
"ssa" || m ==
"nrm")
return {
true, std::nullopt};
425 return {
false, std::string(
"LAL compositions support serial SSA and NRM only.")};
435 "LAL SSA does not yet support finite timespan, config, timestep, "
436 "path recording, timeout or cutoff options.");
437 const Model snapshot = model_->model();
440 const std::string m = detail::strip_prefix(detail::lower(
options.
method),
"ssa.");
442 const bool truncated = model_->source_truncated;
446 a->truncated = truncated;
447 a->extra[
"statistical"] =
true;
449 a->extra[
"events"] = r.
events;
452 a->extra[
"warmupfrac"] = warmupfrac;
454 result_ = std::move(r);
459 void reset() { signature_.reset(); }
482 const std::optional<std::string>& jobclass = std::nullopt,
483 const std::optional<std::string>& mode = std::nullopt) {
484 return getAvgAct(ActionSpec::key(node, event, jobclass, mode));
487 return getAvgAct(ActionSpec::key(node, event, jobclass));
490 std::vector<double>
getActAvg(
const std::vector<ActionSpec>& actions) {
491 std::vector<double> out;
492 for (
const ActionSpec& a : actions) out.push_back(
getAvgAct(a));
497 std::pair<std::vector<double>, std::vector<std::string>>
getAvgReward() {
499 std::pair<std::vector<double>, std::vector<std::string>> out;
500 for (
const auto& kv : r.
rewards) {
501 out.first.push_back(kv.second);
502 out.second.push_back(kv.first);
523 "use the LAL state and action tables.");
532 std::optional<std::string> signature_;
534 std::string key_()
const {
537 const SSAResult& ensure_() {
538 if (!signature_ || *signature_ != key_())
runAnalyzer();
LINE Agent Language (LAL): programmatic construction of finite agents and their composition,...
const std::string & id() const noexcept
The full identifier, e.g.
A refusal: the feature, method or analysis is not covered: LINE:unsupported:<kind>.
UnsupportedError(const std::string &what)
A collection of agents and embedded LINE models with atomic synchronisations (Composition).
Model model(const std::vector< Sync > *syncs=nullptr, const std::vector< ExtSync > *ext_syncs=nullptr) const
The current model snapshot (_model).
SolverCTMC & runAnalyzer()
SolverCTMC(const Composition &model, CTMCOptions options=CTMCOptions())
The solver REFERENCES model, as Python's re-reads self.model on every query: a later edit (an added a...
double getAvgAct(const std::string &node, lang::EventType event, const std::optional< std::string > &jobclass=std::nullopt, const std::optional< std::string > &mode=std::nullopt)
std::vector< std::string > getEventLabels()
static bool supports(const Composition &)
ActionTable getActTable()
std::pair< std::vector< double >, std::vector< std::string > > getAvgReward()
The rewards declared with Composition::setReward, on the stationary law: (R, names).
std::function< Result(const Model &, std::size_t)> ctmc_backend
Test seam: replaces the explicit CTMC call (Python tests monkeypatch it).
std::pair< Matrix< double >, std::vector< Matrix< double > > > getGenerator()
The generator and the event filters, in getEventLabels order.
ActionTable getActionTable()
std::vector< double > getActAvg(const std::vector< ActionSpec > &actions)
Throughputs of several actions, each named as in getAvgAct.
SolverCTMC(const Composition &&, CTMCOptions=CTMCOptions())=delete
std::pair< bool, std::optional< std::string > > supportsModelMethod(const std::string &method) const
double get_avg_act(const ActionSpec &action)
std::vector< double > getProbSys()
Joint stationary distribution in getStateSpace order (MATLAB getProbSys).
double getAvgAct(const ActionSpec &action)
Throughput of one LAL action (getAvgAct): named by label, by agent.action("x"), by composition....
std::vector< double > get_act_avg(const std::vector< ActionSpec > &actions)
Matrix< double > getInfGen()
std::pair< std::vector< std::vector< std::string > >, std::vector< std::vector< std::string > > > getStateSpace()
Joint state names, one row per state and one column per agent, plus the per-agent columns (Python ret...
std::vector< double > getTranProbSys(double t)
Transient joint distribution pi0 exp(Q t).
double getAvgAct(std::size_t node, lang::EventType event, std::size_t jobclass=0)
const mdd::MddMcdResult< double > & getMDDResult()
MDD aggregation details (Python's _result.mdd); throws unless the method run was mdd.
std::string getResultMethod()
LINE Agent Language (LAL): the result tables every LAL solver returns, the exact finite CTMC analysis...
Matrix exponential by scaling and squaring with a diagonal Pade approximant.
The method names of each solver, in listing order.
std::string signature(const Model &m)
A deterministic text signature of a model snapshot (Python's repr(model)), used by the solvers to cac...
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).
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).
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).
std::set< std::string > model_features(const Model &model)
Features of a model that only the extended kernel interprets (model_features).
static const std::size_t kDefaultMaxDenseBytes
Default dense-storage budget of the CTMC path: 256 MiB.
EventType
The events a state can undergo, with the values of MATLAB EventType.
Conservation laws of a layered queueing network, enumerated from its structure.
Matrix< T > expm(const Matrix< T > &A)
Matrix exponential exp(A).
LINE Agent Language (LAL): on-demand Gillespie simulation of a finite composition (lal/ssa....
The immutable agent record (core.Agent).
std::optional< std::vector< double > > initial_distribution
Options of the LAL arm of SolverCTMC.
std::optional< std::vector< double > > init_sol
refused when set
nlohmann::json config
refused when nonempty
std::optional< std::pair< double, double > > timespan
refused when set
std::size_t ctmc_max_states
hard cap on enumerated global states
The output of solve_mdd: the marginal table and the MCD aggregation.
A composition snapshot (core.Model): agents in declaration order plus synchronisations.
std::vector< MinSync > min_syncs
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
std::vector< std::vector< std::size_t > > states
joint states (CTMC)
std::vector< std::pair< std::string, double > > rewards
Stationary expectations of the rewards declared with Composition::setReward, in order.
Options of the LAL arm of SolverSSA.
long samples
deprecated alias of events
std::optional< long > events
event budget; overrides samples
std::optional< double > warmupfrac
std::pair< double, double > timespan
std::optional< double > timestep
The SSA result (LALSSAResult).
double duration
measured time; +inf when absorbed
long events
measured events (after warm-up)
std::vector< std::pair< std::string, double > > rewards
Estimates of the rewards declared with Composition::setReward, in order.
The attrs of a LAL result table.
Result of the Miner-Ciardo-Donatelli level aggregation.