LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
environment.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_QN_ENVIRONMENT_H
6#define LINE_LANG_QN_ENVIRONMENT_H
7
8/**
9 * @file
10 * @ingroup line_lang
11 * A random environment: a port of `matlab/src/lang/Environment.m`, restricted
12 * to what `SolverENV` reads out of it.
13 *
14 * WHAT IT MODELS. A queueing network whose PARAMETERS change over time because
15 * the world around it does: a server that breaks down and is repaired, a
16 * workload that has a day phase and a night phase, a system that degrades and
17 * is reset. Each of those is a STAGE, holding its own complete network, and the
18 * environment is a semi-Markov process over the stages. The point is that the
19 * network never restarts empty at a switch -- the jobs in it at the moment of
20 * the switch are carried into the next stage, which is what couples the stages
21 * and what makes this more than solving each stage separately.
22 *
23 * THE HOLDING TIME IS A COMPETING RISK, and this is the part worth reading the
24 * reference for. Every enabled transition e -> h has its own distribution, and
25 * they all run at once: the stage ends when the FIRST of them fires, and which
26 * one fired decides the next stage. `init()` therefore superposes the outgoing
27 * transitions of e by a Kronecker sum into a single marked process
28 * `hold_time[e]`, whose per-mark rates give the embedded jump chain `Pemb`.
29 * The collapse that follows -- each block's row sums moved into its FIRST
30 * column -- is the reference's, and it makes the superposed process restart in
31 * phase one after every jump, i.e. renewal at each stage entry.
32 *
33 * WHAT init() PRODUCES, and what the solver consumes:
34 * proc[e][h] the e -> h transition process, whose CDF weights the stage
35 * transient when computing the metrics AT a switch to h
36 * hold_time[e] the superposed holding time of stage e, whose CDF weights the
37 * transient when computing the metrics OVER the whole stage
38 * prob_env[e] the stationary probability of being in stage e
39 * prob_orig prob_orig(h, e) = P(the previous stage was h | now entering e)
40 *
41 * A SEMI-MARKOV STAGE has no such MAP form: a stage with a non-Markovian arc
42 * (Det, Gamma, Weibull, ...) or with KERNEL arcs (`add_kernel_transition`, a
43 * jump probability and a conditional sojourn law per arc). `init()` then reads
44 * its embedded jump row and mean holding time off the arc CDFs by
45 * `mc::smp_stage_quad`, leaves `hold_time[e]` and `proc[e][h]` as the disabled
46 * pair, and `hold_time_cdf` / `hold_time_mean` evaluate the holding-time law
47 * from the arcs. Only SolverENV method `smp` solves such an environment.
48 *
49 * A DISABLED transition is the 1 x 1 zero pair, exactly as in the reference:
50 * krons(A, 0) leaves A unchanged, so a disabled arc costs nothing and needs no
51 * special case anywhere below.
52 *
53 * NODE BREAKDOWNS are the one stage pattern the reference gives a name to
54 * (`addNodeBreakdown` / `addNodeRepair` / `addNodeFailureRepair`): the UP stage
55 * holds the base network, the DOWN_<node> stage holds the same network with one
56 * node's service replaced by its degraded distribution, and the two arcs
57 * between them are the time to failure and the time to repair. It is a macro
58 * over `set_stage` and `add_transition` and nothing more, EXCEPT for the pair of
59 * queue-length reset policies it attaches, which are the only part of a
60 * breakdown that the expanded stages cannot express -- hence `NodeFailure`,
61 * which records them beside the stages so an environment read back from
62 * `model.json` is the same model it was written from.
63 */
64
65#include <cctype>
66#include <cmath>
67#include <cstddef>
68#include <cstdio>
69#include <functional>
70#include <limits>
71#include <string>
72#include <vector>
73
83#include "line/lang/prior.h"
85#include "line/util/error.h"
86#include "line/util/matrix.h"
87
88namespace line {
89namespace env {
90
91/**
92 * The reset policy of a transition, `resetFun` in the reference.
93 *
94 * It maps the mean queue lengths at the moment of the switch onto the mean
95 * queue lengths the next stage starts from. Identity means the jobs are simply
96 * carried over; zero means the buffer is flushed on the switch.
97 */
98using ResetMarginal = std::function<Matrix<double>(const Matrix<double>&)>;
99
100/**
101 * The two NAMED reset policies of `Environment.resolveResetPolicy`, which are
102 * the only ones the JSON interchange can carry (a function handle is written as
103 * `custom` and warned about by both writers, never reloaded).
104 *
105 * `keep` resolves to the EMPTY function rather than to an explicit identity,
106 * because empty is how this port spells identity everywhere a reset is read:
107 * `SolverEnv::post` skips the call, and the compression's macro-arc fold
108 * compares resets only by whether one is PRESENT, so an explicit identity on
109 * one arc and nothing on another would be refused as a disagreement although
110 * the two mean the same thing.
111 */
112inline ResetMarginal env_reset_policy(const std::string& name) {
113 std::string low;
114 low.reserve(name.size());
115 for (std::size_t i = 0; i < name.size(); ++i)
116 low.push_back(static_cast<char>(std::tolower(static_cast<unsigned char>(name[i]))));
117 if (low == "keep") return ResetMarginal();
118 if (low == "clear")
119 return [](const Matrix<double>& q) { return Matrix<double>(q.rows(), q.cols(), 0.0); };
120 throw InputError("Environment: unknown reset policy '" + name +
121 "'. The serializable policies are 'keep' (carry the queue lengths across "
122 "the switch) and 'clear' (empty the queues); a custom policy is a function "
123 "and is installed through add_transition, not by name");
124}
125
126/**
127 * `Environment.nodeFailures{k}`: the declarative record of one node breakdown.
128 *
129 * The expanded stages and transitions already carry the STRUCTURE of a
130 * breakdown; what only this record carries is the pair of reset policies, which
131 * decide what the next stage starts from and therefore change the numbers. It
132 * is kept on the environment for the same reason the reference keeps it: so an
133 * environment read from `model.json` in its expanded form can be given back its
134 * policies, and so it serializes out again as the same model.
135 */
136template <class T>
138 std::string node; ///< the node that breaks down
139 lang::Distrib<T> breakdown; ///< time to failure, the UP -> DOWN transition
140 lang::Distrib<T> down_service; ///< the node's service while it is down
141 lang::Distrib<T> repair; ///< time to repair, the DOWN -> UP transition
142 bool has_repair = false; ///< false for a breakdown with no repair arc
143 std::string breakdown_reset = "keep";
144 std::string repair_reset; ///< empty when there is no repair
145};
146
147/**
148 * One stage: a name, a category, and the model in force while it lasts.
149 *
150 * THE MODEL IS ONE OF TWO KINDS, and which one is the stage's own property
151 * rather than the environment's: a flat `qn::NetworkStruct`, or a
152 * `lqn::LqnStruct` -- a LayeredNetwork, whose stations and classes are those of
153 * the LAYERS SolverLN builds out of it. The reference draws no distinction at
154 * this level either (`Environment.addStage` stores whatever model it is handed
155 * and `SolverENV` branches on its class), and the two fields are kept apart
156 * rather than unified because nothing about them is shared below the name: a
157 * flat stage is integrated directly, a layered one through a whole fixed point
158 * over its layers.
159 *
160 * `has_model` and `has_lqn` are mutually exclusive; `set_stage` and
161 * `set_lqn_stage` each clear the other, so a stage re-declared as the other
162 * kind cannot leave a stale twin behind for a later consumer to read.
163 */
164template <class T>
165struct EnvStage {
166 std::string name;
167 std::string type; ///< the stage category, informational only
169 bool has_model = false;
170 /** The layered model, when this stage holds a LayeredNetwork. */
172 bool has_lqn = false;
173 /** True when the stage carries a model of either kind. */
174 bool declared() const { return has_model || has_lqn; }
175};
176
177/**
178 * `resetEnvRatesFun` in the reference: the state-dependent environment rate.
179 *
180 * It is given the arc's CURRENT transition distribution and the exit metrics of
181 * the stage the arc leaves -- mean queue lengths, utilizations and throughputs,
182 * averaged over when that arc fires -- and returns the distribution the arc
183 * should carry next. It is what makes the environment process depend on the
184 * network it modulates, and `method = "statedep"` is what applies it.
185 */
186template <class T>
188 std::function<lang::Distrib<T>(const lang::Distrib<T>&, const Matrix<double>&,
189 const Matrix<double>&, const Matrix<double>&)>;
190
191/**
192 * `resetStateFun{e,h}` of the reference: the state distribution of stage e at
193 * the e -> h switch, mapped onto the state space of stage h.
194 *
195 * This is NOT `ResetMarginal`, which acts on the (nstations x nclasses) mean
196 * queue lengths the mean-field coupling carries. The two coexist because the
197 * couplings carry different objects, and a policy expressed on means has no
198 * canonical lift to a joint distribution. The vectors are indexed by the
199 * TANGIBLE states of each stage's enumerated CTMC, in LINE's order; SolverENV
200 * method `statevec` reads it, and so does the LAL embedding of an Environment.
201 */
202template <class T>
203using ResetStateVec = std::function<std::vector<T>(const std::vector<T>&)>;
204
205/** One arc of the environment process. */
206template <class T>
207struct EnvArc {
208 bool enabled = false;
209 lang::Distrib<T> dist; ///< the e -> h transition time
210 ResetMarginal reset; ///< empty means the identity
211 ResetEnvRates<T> reset_rates; ///< empty means the rate does not depend on the state
212 ResetStateVec<T> reset_state; ///< `resetStateFun{e,h}`; empty means the identity
213};
214
215/**
216 * The DOWN stage network of `addNodeBreakdown`: the base network with ONE
217 * node's service replaced by its degraded distribution, for EVERY class.
218 *
219 * Every class, and not only the ones that were enabled there, is what the
220 * reference does (`for c = 1:length(classes), nodes{nodeIdx}.setService(...)`),
221 * so a class that was disabled at the node while it was up is served at the
222 * degraded rate while it is down. The whole refresh chain is rerun afterwards
223 * because `rates`, `scv` and the chain-derived tables are all read off the
224 * service table; editing the table alone would leave the struct describing the
225 * UP stage and the solver reading the DOWN one.
226 */
227template <class T>
229 const std::string& node_name,
230 const lang::Distrib<T>& down_service) {
232 std::size_t node = 0;
233 for (std::size_t i = 0; i < sn.nodes.size(); ++i)
234 if (sn.nodes[i].name == node_name) {
235 node = i + 1;
236 break;
237 }
238 if (node == 0)
239 throw InputError("Environment: node '" + node_name +
240 "' is not in the base model, so it has no service to degrade");
241 const std::size_t ist = sn.nodes[node - 1].station;
242 if (ist == 0)
243 throw InputError("Environment: node '" + node_name +
244 "' is not a station and carries no service distribution, so it cannot "
245 "break down into a degraded service");
246 lang::Distrib<T> d = down_service;
247 if (d.is_prior())
249 else
251 for (std::size_t r = 1; r <= sn.classes.size(); ++r) sn.set_service(ist, r, d);
252 sn.refresh_struct();
253 return sn;
254}
255
256template <class T>
258public:
259 Environment(const std::string& nm, std::size_t nstages)
260 : name_(nm), stages_(nstages), arcs_(nstages, std::vector<EnvArc<T>>(nstages)),
261 kernel_prob_(nstages, nstages, std::numeric_limits<double>::quiet_NaN()) {
262 if (nstages == 0) throw InputError("Environment: a random environment needs a stage");
263 }
264
265 std::size_t nstages() const { return stages_.size(); }
266 const std::string& name() const { return name_; }
267
268 /** `addStage`: name the stage and give it its network. */
269 void set_stage(std::size_t e, const std::string& nm, const std::string& type,
270 const qn::NetworkStruct<T>& model) {
271 check(e);
272 stages_[e].name = nm;
273 stages_[e].type = type;
274 stages_[e].model = model;
275 stages_[e].has_model = true;
276 stages_[e].has_lqn = false;
277 stages_[e].lqn_model = lqn::LqnStruct<T>();
278 }
279
280 /**
281 * `addStage` with a LayeredNetwork: the stage holds a LAYERED model.
282 *
283 * The environment itself does nothing with the difference -- probEnv,
284 * probOrig and the holding times are read off the ARCS and never off a
285 * stage model -- so the whole content of this overload is that the stage
286 * records which kind of model it carries and `SolverEnv` runs the matching
287 * stage solver. What the two kinds must still agree on is the (station,
288 * class) SHAPE of the metrics being blended, and for a layered stage that
289 * shape is the block-diagonal union of its layers; `SolverEnv::init` is
290 * where the shapes are compared, because only there is a SolverLN built and
291 * the layer blocks known.
292 */
293 void set_lqn_stage(std::size_t e, const std::string& nm, const std::string& type,
294 const lqn::LqnStruct<T>& model) {
295 check(e);
296 // compare LQN elements, not layers: a zero-capacity stage drops the layers
297 // only its trapped reference tasks reach (SolverLN, ln_zero_capacity)
298 for (std::size_t h = 0; h < stages_.size(); ++h)
299 if (h != e && stages_[h].has_lqn &&
300 (stages_[h].lqn_model.nidx != model.nidx || stages_[h].lqn_model.tshift != model.tshift))
301 throw InputError(ErrorKind{"Model"},
302 "Unsupported feature. Random environment stages must map to layered networks "
303 "with the same hosts, tasks, entries and activities.");
304 stages_[e].name = nm;
305 stages_[e].type = type;
306 stages_[e].lqn_model = model;
307 stages_[e].has_lqn = true;
308 stages_[e].has_model = false;
309 stages_[e].model = qn::NetworkStruct<T>();
310 }
311
312 /** True when stage `e` holds a LayeredNetwork rather than a flat network. */
313 bool is_lqn(std::size_t e) const {
314 check(e);
315 return stages_[e].has_lqn;
316 }
317
318 /** True when ANY stage holds a LayeredNetwork. */
319 bool has_lqn_stages() const {
320 for (std::size_t e = 0; e < stages_.size(); ++e)
321 if (stages_[e].has_lqn) return true;
322 return false;
323 }
324
325 /**
326 * Refuse an environment carrying a LayeredNetwork stage, by name.
327 *
328 * Shared by every consumer that reads `stage(e).model` directly -- the
329 * state-vector coupling, the closed-form limits, the compression -- so that
330 * each says the same thing about the same gap rather than reading an EMPTY
331 * NetworkStruct and reporting a confident answer about a model that is not
332 * there. `who` names the caller and `why` says what about it needs a flat
333 * stage.
334 */
335 void reject_lqn_stages(const std::string& who, const std::string& why) const {
336 for (std::size_t e = 0; e < stages_.size(); ++e)
337 if (stages_[e].has_lqn)
338 throw UnsupportedError(ErrorKind{"LayeredNetwork"},
339 who + ": stage " + std::to_string(e + 1) + " ('" + stages_[e].name +
340 "') holds a LayeredNetwork, and " + why +
341 ". The mean-field coupling (method 'default' / 'meanfield') is the one that "
342 "solves a layered stage, through SolverLN");
343 }
344
345 /**
346 * `addTransition`: enable e -> h with a distribution and a reset policy.
347 *
348 * A COMPETING arc: `d` is a latent clock started on entry to the stage, and
349 * the first of the stage's clocks to ring picks the destination. Any law is
350 * accepted; a non-Markovian one makes the environment semi-Markov, which
351 * only SolverENV method `smp` solves.
352 */
353 void add_transition(std::size_t e, std::size_t h, const lang::Distrib<T>& d,
354 const ResetMarginal& reset = ResetMarginal()) {
355 check(e);
356 check(h);
357 arcs_[e][h].enabled = true;
358 arcs_[e][h].dist = d;
359 arcs_[e][h].reset = reset;
360 kernel_prob_(e, h) = std::numeric_limits<double>::quiet_NaN();
361 }
362
363 /**
364 * `addKernelTransition`: a KERNEL arc of Q(e,h,t) = prob * F(t).
365 *
366 * On entry to e the next stage is h with probability `prob`, and the sojourn
367 * is then distributed as `d`: the sojourn-time parameterization (Approach I
368 * of Asanjarani et al.), beside `add_transition`'s competing clocks (Approach
369 * II). A stage's arcs must be all kernel or all competing, and the
370 * probabilities of a kernel stage must sum to one (`stage_arcs`). Only
371 * SolverENV method `smp` solves an environment with kernel arcs.
372 */
373 void add_kernel_transition(std::size_t e, std::size_t h, double prob,
374 const lang::Distrib<T>& d,
375 const ResetMarginal& reset = ResetMarginal()) {
376 if (!(prob > 0.0 && prob <= 1.0))
377 throw InputError("Environment: the probability of a kernel transition must be a "
378 "scalar in (0,1].");
379 add_transition(e, h, d, reset);
380 kernel_prob_(e, h) = prob;
381 }
382
383 /** `kernelProb(e,h)`: the kernel arc's probability, NaN for a competing arc or none. */
384 double kernel_prob(std::size_t e, std::size_t h) const {
385 check(e);
386 check(h);
387 return kernel_prob_(e, h);
388 }
389
390 /** `isKernelStage`: true if stage e's arcs are kernel arcs. */
391 bool is_kernel_stage(std::size_t e) const {
392 check(e);
393 for (std::size_t h = 0; h < stages_.size(); ++h)
394 if (!std::isnan(kernel_prob_(e, h))) return true;
395 return false;
396 }
397
398 /**
399 * `isSemiMarkovStage`: true if stage e's holding time has no Markovian (MAP)
400 * form, i.e. it has kernel arcs or a competing arc whose law is not
401 * Markovian (the reference's `isa(arc, 'Markovian')`).
402 */
403 bool is_semi_markov_stage(std::size_t e) const {
404 if (is_kernel_stage(e)) return true;
405 for (std::size_t h = 0; h < stages_.size(); ++h) {
406 const EnvArc<T>& a = arcs_[e][h];
407 if (a.enabled && !a.dist.disabled && !arc_is_markovian(a.dist)) return true;
408 }
409 return false;
410 }
411
412 /**
413 * `isAbsorbingStage`: true if stage e has no outgoing transition, so once
414 * entered the environment stays there with an infinite holding time. A
415 * self arc does not count as a way out.
416 */
417 bool is_absorbing_stage(std::size_t e) const {
418 check(e);
419 if (is_kernel_stage(e)) return false;
420 for (std::size_t h = 0; h < stages_.size(); ++h)
421 if (h != e && arcs_[e][h].enabled && !arcs_[e][h].dist.disabled) return false;
422 return true;
423 }
424
425 /**
426 * Refuse a stage with no model. Runs ahead of the structural refusals, since
427 * an undeclared stage also has no arcs and would otherwise be reported as absorbing.
428 */
429 void require_declared() const {
430 for (std::size_t e = 0; e < stages_.size(); ++e)
431 if (!stages_[e].declared())
432 throw InputError("Environment: stage " + std::to_string(e + 1) + " has no model");
433 }
434
435 /** True if some stage is absorbing, i.e. `init()` left probEnv empty. */
436 bool is_absorbing() const {
437 for (std::size_t e = 0; e < stages_.size(); ++e)
438 if (is_absorbing_stage(e)) return true;
439 return false;
440 }
441
442 /**
443 * Refuse an absorbing environment for a coupling that reads probEnv: its
444 * limit depends on the initial stage, so it has no single steady state.
445 */
446 void refuse_absorbing(const std::string& method) const {
447 for (std::size_t e = 0; e < stages_.size(); ++e)
448 if (is_absorbing_stage(e))
449 throw UnsupportedError(ErrorKind{"Structure"},
450 "Stage " + std::to_string(e + 1) + " ('" + stages_[e].name +
451 "') has no outgoing transition, so the environment is absorbing and has no "
452 "single steady state: its limit depends on the initial stage. Method '" +
453 method + "' reads the stationary stage probabilities; use method "
454 "'occupation', with options.config.env_init naming the initial stage law.");
455 }
456
457 /** `isSemiMarkov`: true if any stage is semi-Markov. */
458 bool is_semi_markov() const {
459 for (std::size_t e = 0; e < stages_.size(); ++e)
460 if (is_semi_markov_stage(e)) return true;
461 return false;
462 }
463
464 /**
465 * `getStageArcs`: the transitions out of stage e in the form
466 * `mc::smp_stage_cif` takes. `arcs[h]` is the law of e -> h, DISABLED where
467 * there is none (and for h == e), and `probs` is empty for competing arcs or
468 * holds the kernel probabilities, validated as the reference does.
469 */
470 void stage_arcs(std::size_t e, std::vector<lang::Distrib<T>>& arcs,
471 std::vector<double>& probs) const {
472 check(e);
473 const std::size_t E = stages_.size();
474 arcs.assign(E, lang::Distrib<T>());
475 for (std::size_t h = 0; h < E; ++h)
476 if (h != e && arcs_[e][h].enabled && !arcs_[e][h].dist.disabled)
477 arcs[h] = arcs_[e][h].dist;
478 probs.clear();
479 if (!is_kernel_stage(e)) return;
480 probs.assign(E, 0.0);
481 double tot = 0.0;
482 for (std::size_t h = 0; h < E; ++h) {
483 if (!arcs[h].disabled) {
484 if (std::isnan(kernel_prob_(e, h)))
485 throw InputError("Environment: stage " + std::to_string(e + 1) +
486 " mixes kernel and competing transitions (the one to stage " +
487 std::to_string(h + 1) +
488 " was added by addTransition). Declare all of a stage's "
489 "transitions with addKernelTransition, or none.");
490 probs[h] = kernel_prob_(e, h);
491 tot += probs[h];
492 } else if (!std::isnan(kernel_prob_(e, h))) {
493 throw InputError("Environment: the kernel transition " + std::to_string(e + 1) +
494 "->" + std::to_string(h + 1) + " has no law.");
495 }
496 }
497 if (std::fabs(tot - 1.0) > 1e-8) {
498 char buf[64];
499 std::snprintf(buf, sizeof buf, "%.12g", tot);
500 throw InputError("Environment: the kernel probabilities out of stage " +
501 std::to_string(e + 1) + " sum to " + buf + ", not 1.");
502 }
503 }
504
505 /**
506 * The `methodRefusal` rule for every coupling but `smp`: refuse a kernel
507 * stage, or a competing arc that is not Markovian, with the reference's
508 * sentences. Those couplings read each stage's holding time as a (D0,D1)
509 * race of its transitions, which neither has.
510 */
511 void refuse_semi_markov(const std::string& method) const {
512 if (method == "smp") return;
513 const std::size_t E = stages_.size();
514 for (std::size_t e = 0; e < E; ++e) {
515 if (is_kernel_stage(e))
516 throw UnsupportedError(ErrorKind{"Structure"},
517 "Stage " + std::to_string(e + 1) +
518 " has kernel transitions (addKernelTransition), which only method 'smp' of "
519 "SolverENV solves: the other couplings read each stage's holding time as a "
520 "Markovian (D0,D1) race of its transitions.");
521 for (std::size_t h = 0; h < E; ++h) {
522 const EnvArc<T>& a = arcs_[e][h];
523 if (!a.enabled || a.dist.disabled || arc_is_markovian(a.dist)) continue;
524 throw UnsupportedError(ErrorKind{"Structure"},
525 "The distribution of the environment transition from stage " +
526 std::to_string(e + 1) + " to " + std::to_string(h + 1) + " is a " +
527 lang::process_to_text(a.dist.type) + ", which is not Markovian: method '" +
528 method +
529 "' reads every arc as a (D0,D1) process to build the holding-time laws. Use "
530 "method 'smp', which solves the semi-Markov environment, or fit the arc to a "
531 "phase-type law, e.g. APH.fitMeanAndSCV.");
532 }
533 }
534 }
535
536 const EnvStage<T>& stage(std::size_t e) const {
537 check(e);
538 return stages_[e];
539 }
540 const EnvArc<T>& arc(std::size_t e, std::size_t h) const {
541 check(e);
542 check(h);
543 return arcs_[e][h];
544 }
545
546 /**
547 * `resetEnvRatesFun{e,h}`: make the e -> h transition depend on the state
548 * the stage is left in. Only `method = "statedep"` reads it.
549 */
550 void set_env_rate_reset(std::size_t e, std::size_t h, const ResetEnvRates<T>& f) {
551 check(e);
552 check(h);
553 if (!arcs_[e][h].enabled)
554 throw InputError("Environment: no transition " + stages_[e].name + " -> " +
555 stages_[h].name +
556 " is declared, so its rate cannot be made state dependent");
557 arcs_[e][h].reset_rates = f;
558 }
559
560 /**
561 * `resetStateFun{e,h}`: map the exit state-probability vector of stage e
562 * onto the entry vector of stage h at the e -> h switch (the seventh
563 * argument of the reference's `addTransition`). `method = "statevec"`
564 * reads it, as does the LAL embedding of this environment; an empty
565 * function restores the identity.
566 */
567 void set_state_reset(std::size_t e, std::size_t h, const ResetStateVec<T>& f) {
568 check(e);
569 check(h);
570 if (!arcs_[e][h].enabled)
571 throw InputError("Environment: no transition " + stages_[e].name + " -> " +
572 stages_[h].name +
573 " is declared, so it cannot be given a state reset policy");
574 arcs_[e][h].reset_state = f;
575 }
576
577 /**
578 * Replace the distribution of an arc that is already declared.
579 *
580 * This is what the state-dependent method writes back each iteration; every
581 * other caller declares the arc once through `add_transition`. `init()` must
582 * be rerun afterwards, because the superposed holding times and the stage
583 * probabilities are all derived from these distributions.
584 */
585 void set_transition_dist(std::size_t e, std::size_t h, const lang::Distrib<T>& d) {
586 check(e);
587 check(h);
588 if (!arcs_[e][h].enabled)
589 throw InputError("Environment: no transition " + stages_[e].name + " -> " +
590 stages_[h].name + " is declared, so its distribution cannot be set");
591 arcs_[e][h].dist = d;
592 }
593
594 /** The index of the stage called `nm`, or `nstages()` when there is none. */
595 std::size_t find_stage(const std::string& nm) const {
596 for (std::size_t e = 0; e < stages_.size(); ++e)
597 if (stages_[e].has_model && stages_[e].name == nm) return e;
598 return stages_.size();
599 }
600
601 /**
602 * Install a reset policy on an arc that is already declared.
603 *
604 * The arc must exist: a reset on a disabled arc is a policy for a switch
605 * the environment cannot make, and it would sit there reporting nothing.
606 * The reference reaches this through `setBreakdownResetPolicy`, which
607 * likewise errors when the stages it names are absent.
608 */
609 void set_reset(std::size_t e, std::size_t h, const ResetMarginal& reset) {
610 check(e);
611 check(h);
612 if (!arcs_[e][h].enabled)
613 throw InputError("Environment: no transition " + stages_[e].name + " -> " +
614 stages_[h].name +
615 " is declared, so it cannot be given a reset policy");
616 arcs_[e][h].reset = reset;
617 }
618
619 // ---- node breakdown and repair ---------------------------------------
620
621 /** `nodeFailures`, the declarative record of the breakdowns declared here. */
622 const std::vector<NodeFailure<T>>& node_failures() const { return node_failures_; }
623
624 /** `findNodeFailure`: the descriptor for `nm`, or `node_failures().size()`. */
625 std::size_t find_node_failure(const std::string& nm) const {
626 for (std::size_t i = 0; i < node_failures_.size(); ++i)
627 if (node_failures_[i].node == nm) return i;
628 return node_failures_.size();
629 }
630
631 /** The name `addNodeBreakdown` gives the stage in which `nm` is down. */
632 static std::string down_stage_name(const std::string& nm) { return "DOWN_" + nm; }
633
634 /**
635 * Port of `addNodeBreakdown`, on a FIXED stage count.
636 *
637 * The reference grows its stage graph as breakdowns are declared; this
638 * environment is sized at construction, exactly as `set_stage` is, so the
639 * caller says which slot is UP and which is the DOWN stage of this node.
640 * Everything else is the reference's: the UP stage holds the base model and
641 * is named `UP`, the DOWN stage holds the degraded copy and is named
642 * `DOWN_<node>`, and the UP -> DOWN arc carries the breakdown time and the
643 * breakdown reset policy.
644 */
645 void add_node_breakdown(std::size_t up, std::size_t down, const qn::NetworkStruct<T>& base,
646 const std::string& node_name, const lang::Distrib<T>& breakdown,
647 const lang::Distrib<T>& down_service,
648 const std::string& reset_policy = "keep") {
649 check(up);
650 check(down);
651 if (up == down)
652 throw InputError("Environment: the UP and DOWN stages of node '" + node_name +
653 "' must be different stages");
654 if (!stages_[up].has_model) set_stage(up, "UP", "operational", base);
655 set_stage(down, down_stage_name(node_name), "failed",
656 env_degraded_model(base, node_name, down_service));
657 add_transition(up, down, breakdown, env_reset_policy(reset_policy));
658
660 nf.node = node_name;
661 nf.breakdown = breakdown;
662 nf.down_service = down_service;
663 nf.breakdown_reset = reset_policy;
664 record_node_failure(nf);
665 }
666
667 /** Port of `addNodeRepair`: the DOWN_<node> -> UP arc and its policy. */
668 void add_node_repair(const std::string& node_name, const lang::Distrib<T>& repair,
669 const std::string& reset_policy = "keep") {
670 const std::size_t down = find_stage(down_stage_name(node_name));
671 const std::size_t up = find_stage("UP");
672 if (down == stages_.size())
673 throw InputError("Environment: stage '" + down_stage_name(node_name) +
674 "' is not defined; declare the breakdown of node '" + node_name +
675 "' before its repair");
676 if (up == stages_.size())
677 throw InputError("Environment: no UP stage is defined, so node '" + node_name +
678 "' has nothing to be repaired into");
679 add_transition(down, up, repair, env_reset_policy(reset_policy));
680
681 const std::size_t idx = find_node_failure(node_name);
682 if (idx == node_failures_.size())
683 throw InputError("Environment: no breakdown is recorded for node '" + node_name +
684 "', so its repair would describe a failure that was never declared");
685 node_failures_[idx].repair = repair;
686 node_failures_[idx].has_repair = true;
687 node_failures_[idx].repair_reset = reset_policy;
688 }
689
690 /** `addNodeFailureRepair`: the two calls above, in order. */
691 void add_node_failure_repair(std::size_t up, std::size_t down,
692 const qn::NetworkStruct<T>& base, const std::string& node_name,
693 const lang::Distrib<T>& breakdown, const lang::Distrib<T>& repair,
694 const lang::Distrib<T>& down_service,
695 const std::string& breakdown_reset = "keep",
696 const std::string& repair_reset = "keep") {
697 add_node_breakdown(up, down, base, node_name, breakdown, down_service, breakdown_reset);
698 add_node_repair(node_name, repair, repair_reset);
699 }
700
701 /**
702 * Port of `registerNodeFailure`: attach a breakdown descriptor, and its
703 * reset policies, to stages that ALREADY exist.
704 *
705 * This is the read path of an environment saved in its expanded form: the
706 * `UP` and `DOWN_<node>` stages and their two arcs came off the wire, and
707 * the only thing the wire could not carry is the pair of policies, which is
708 * what this installs.
709 */
710 void register_node_failure(const std::string& node_name, const lang::Distrib<T>& breakdown,
711 const lang::Distrib<T>& down_service, bool has_repair,
712 const lang::Distrib<T>& repair,
713 const std::string& breakdown_reset,
714 const std::string& repair_reset) {
715 const std::size_t up = find_stage("UP");
716 const std::size_t down = find_stage(down_stage_name(node_name));
717 if (up == stages_.size())
718 throw InputError("Environment: cannot register a node failure on '" + node_name +
719 "': no UP stage is defined in this environment");
720 if (down == stages_.size())
721 throw InputError("Environment: cannot register a node failure on '" + node_name +
722 "': no '" + down_stage_name(node_name) +
723 "' stage is defined in this environment");
724 set_reset(up, down, env_reset_policy(breakdown_reset));
725
727 nf.node = node_name;
728 nf.breakdown = breakdown;
729 nf.down_service = down_service;
730 nf.breakdown_reset = breakdown_reset;
731 if (has_repair) {
732 set_reset(down, up, env_reset_policy(repair_reset));
733 nf.repair = repair;
734 nf.has_repair = true;
735 nf.repair_reset = repair_reset;
736 }
737 record_node_failure(nf);
738 }
739
740 /**
741 * Port of `Environment.init()`.
742 *
743 * Superpose the outgoing transitions of each stage, read the embedded jump
744 * chain off the per-destination rates, and solve the resulting semi-Markov
745 * process for its stationary stage probabilities. A semi-Markov stage takes
746 * its jump row and mean holding time from `mc::smp_stage_quad` instead, and
747 * keeps its arcs so `hold_time_cdf` can evaluate the law.
748 *
749 * An ABSORBING stage (`is_absorbing_stage`, no outgoing arc) gets an
750 * infinite mean holding time, a zero embedded row and rate 0. The
751 * environment then has no single steady state, so probEnv and probOrig are
752 * left EMPTY; method 'occupation' reads the embedded chain instead.
753 */
754 void init() {
755 const std::size_t E = stages_.size();
757
758 // proc[e][h], the transition process, as an MMAP marked by destination.
759 // A semi-Markov stage has no MAP form, so its arcs are the disabled pair.
760 sm_stage_.assign(E, 0);
761 sm_arcs_.assign(E, std::vector<lang::Distrib<T>>());
762 sm_probs_.assign(E, std::vector<double>());
763 for (std::size_t e = 0; e < E; ++e) sm_stage_[e] = is_semi_markov_stage(e) ? 1 : 0;
764 proc.assign(E, std::vector<mam::Mmap<double>>(E));
765 for (std::size_t e = 0; e < E; ++e)
766 for (std::size_t h = 0; h < E; ++h)
767 proc[e][h] = sm_stage_[e] ? disabled_mmap(E) : arc_mmap(e, h, E);
768
769 hold_time.assign(E, mam::Mmap<double>());
770 hold_mean.assign(E, 0.0);
771 Matrix<double> Pemb(E, E, 0.0);
772 std::vector<double> lambda(E, 0.0);
773 for (std::size_t e = 0; e < E; ++e) {
774 if (is_absorbing_stage(e)) {
775 // No exit: the stage is never left, so it has no jump law and an
776 // infinite mean holding time (lambda[e] = 0, its Pemb row zero).
777 hold_time[e] = disabled_mmap(E);
778 hold_mean[e] = std::numeric_limits<double>::infinity();
779 continue;
780 }
781 if (sm_stage_[e]) {
782 // The embedded jump probabilities and the mean holding time come
783 // from quadrature on the arc CDFs.
784 stage_arcs(e, sm_arcs_[e], sm_probs_[e]);
785 const mc::SmpStageQuad q = mc::smp_stage_quad(sm_arcs_[e], sm_probs_[e]);
786 for (std::size_t h = 0; h < E; ++h) Pemb(e, h) = q.P[h];
787 hold_mean[e] = q.m;
788 hold_time[e] = disabled_mmap(E);
789 lambda[e] = (q.m > 0.0) ? 1.0 / q.m : 0.0;
790 continue;
791 }
792 // The reference seeds the superposition with the SELF transition
793 // and folds in every other destination.
794 mam::Mmap<double> ht = proc[e][e];
795 for (std::size_t h = 0; h < E; ++h) {
796 if (h == e) continue;
797 ht = superpose_collapsed(ht, proc[e][h]);
798 }
799 hold_time[e] = ht;
800 const std::vector<double> cl = mam::mmap_count_lambda(ht);
801 double tot = 0.0;
802 for (double v : cl) tot += v;
803 if (tot > 0.0)
804 for (std::size_t h = 0; h < E; ++h) Pemb(e, h) = cl[h] / tot;
805 const double m = mam::map_mean(ht.map());
806 hold_mean[e] = m;
807 lambda[e] = (m > 0.0) ? 1.0 / m : 0.0;
808 }
809
810 pemb = Pemb;
811 rate = lambda;
812 bool all_positive = true;
813 for (double v : lambda)
814 if (!(v > 0.0)) all_positive = false;
815 if (!all_positive) {
816 // An absorbing environment has no single steady state: its limit
817 // depends on the initial stage, so it is left to the solver
818 // (SolverENV method 'occupation').
819 prob_env.clear();
821 return;
822 }
823
824 // A = -lambda_e (I - Pemb): the generator of the semi-Markov process
825 // observed at its jumps, whose stationary law is the stage probability.
826 Matrix<double> A(E, E, 0.0);
827 for (std::size_t e = 0; e < E; ++e)
828 for (std::size_t h = 0; h < E; ++h)
829 A(e, h) = -lambda[e] * ((e == h ? 1.0 : 0.0) - Pemb(e, h));
831
832 prob_orig = Matrix<double>(E, E, 0.0);
833 for (std::size_t e = 0; e < E; ++e) {
834 for (std::size_t h = 0; h < E; ++h)
835 prob_orig(h, e) = prob_env[h] * lambda[h] * Pemb(h, e);
836 if (prob_env[e] > 0.0) {
837 double s = 0.0;
838 for (std::size_t h = 0; h < E; ++h) s += prob_orig(h, e);
839 if (s > 0.0)
840 for (std::size_t h = 0; h < E; ++h) prob_orig(h, e) /= s;
841 }
842 }
843 }
844
845 /**
846 * `getReliabilityTable`: MTTF, MTTR, MTBF and availability of an
847 * environment built out of node breakdowns.
848 *
849 * It reads the UP and DOWN_* stages BY NAME, as the reference does, so it
850 * applies to a breakdown environment and to nothing else; a stage set that
851 * carries no such names is refused rather than answered about.
852 *
853 * The four are not independent readings of the same thing. MTTF is the
854 * COMPETING-RISK mean of the arcs out of UP, i.e. one over the SUM of the
855 * breakdown rates, so a second failing node shortens it. MTTR is the mean
856 * repair time weighted by the CONDITIONAL probability of being in each DOWN
857 * stage given that the system is down. Availability is read off probEnv and
858 * not from MTTF/(MTTF+MTTR): the two agree for a Markovian environment and
859 * the stationary law is the one that stays right when the arcs are not.
860 */
861 struct Reliability {
862 double mttf = 0.0; ///< mean time to failure, UP -> any DOWN
863 double mttr = 0.0; ///< mean time to repair, DOWN -> UP
864 double mtbf = 0.0; ///< MTTF + MTTR
865 double availability = 0.0; ///< stationary probability of being UP
866 };
867
869 if (prob_env.empty())
870 throw InputError(
871 "Environment: reliability metrics are read from probEnv; call init() first");
872 const std::size_t E = stages_.size();
873 const std::size_t up = find_stage("UP");
874 if (up == E)
875 throw InputError(
876 "Environment: no UP stage, so there is nothing for a breakdown to leave; "
877 "reliability metrics apply to an environment built with add_node_breakdown");
878 std::vector<std::size_t> down;
879 for (std::size_t e = 0; e < E; ++e)
880 if (stages_[e].name.compare(0, 5, "DOWN_") == 0) down.push_back(e);
881 if (down.empty())
882 throw InputError(
883 "Environment: no DOWN_<node> stage, so no node breaks down; reliability metrics "
884 "apply to an environment built with add_node_breakdown");
885
886 double lambda_total = 0.0;
887 for (std::size_t h : down)
888 if (arcs_[up][h].enabled) lambda_total += arc_rate(up, h);
889 if (!(lambda_total > 0.0))
890 throw InputError(
891 "Environment: no UP -> DOWN transition, so the system never fails and its mean "
892 "time to failure is not a number");
893
894 std::vector<double> mu, p;
895 for (std::size_t e : down)
896 if (arcs_[e][up].enabled) {
897 mu.push_back(is_semi_markov_stage(e) ? 1.0 / hold_mean[e] : arc_rate(e, up));
898 p.push_back(prob_env[e]);
899 }
900 if (mu.empty())
901 throw InputError(
902 "Environment: no DOWN -> UP transition, so the system is never repaired and its "
903 "mean time to repair is not a number");
904
905 Reliability r;
906 r.mttf = 1.0 / lambda_total;
907 // A semi-Markov UP stage has no rates to add: the time to failure is its holding time.
908 if (is_semi_markov_stage(up)) r.mttf = hold_mean[up];
909 double ptot = 0.0;
910 for (double v : p) ptot += v;
911 r.mttr = 0.0;
912 for (std::size_t i = 0; i < mu.size(); ++i)
913 r.mttr += (ptot > 0.0 ? p[i] / ptot : 1.0 / static_cast<double>(mu.size())) / mu[i];
914 r.mtbf = r.mttf + r.mttr;
915 double pup = prob_env[up], pdown = 0.0;
916 for (std::size_t e : down) pdown += prob_env[e];
917 r.availability = (pup + pdown > 0.0) ? pup / (pup + pdown) : 0.0;
918 return r;
919 }
920
921 /**
922 * `getStageTable`: one row per stage. The reference's HoldT column holds the
923 * MAP or the semi-Markov arc struct; here it is the mean holding time and
924 * whether the stage is semi-Markov, which is what a reader of the table uses.
925 */
926 struct StageRow {
927 std::size_t stage = 0; ///< 1-based, as the reference prints it
928 std::string name;
929 std::string type;
930 double prob = 0.0; ///< probEnv
931 double hold_mean = 0.0; ///< holdMean
932 bool semi_markov = false;
933 };
934
935 std::vector<StageRow> stage_table() const {
936 if (prob_env.empty())
937 throw InputError("Environment: the stage table reads probEnv; call init() first");
938 std::vector<StageRow> rows(stages_.size());
939 for (std::size_t e = 0; e < stages_.size(); ++e) {
940 rows[e].stage = e + 1;
941 rows[e].name = stages_[e].name;
942 rows[e].type = stages_[e].type;
943 rows[e].prob = prob_env[e];
944 rows[e].hold_mean = hold_mean[e];
945 rows[e].semi_markov = hold_time_is_semi_markov(e);
946 }
947 return rows;
948 }
949
950 /**
951 * `printStageTable`, as text: the stages with their networks, then every
952 * enabled arc in (from, to) order, a competing one by its rate and a kernel
953 * one by its probability, sojourn family and mean. A layered stage reports
954 * its task and entry counts, having no node or class count of its own.
955 */
956 std::string stage_table_text() const {
957 std::string s = "Stage Table:\n============\n";
958 char buf[512];
959 for (std::size_t e = 0; e < stages_.size(); ++e) {
960 const EnvStage<T>& st = stages_[e];
961 std::snprintf(buf, sizeof buf, "Stage %zu: %s (Type: %s)\n", e + 1, st.name.c_str(), st.type.c_str());
962 s += buf;
963 if (st.has_model) {
964 std::snprintf(buf, sizeof buf, " - Network: %s\n - Nodes: %zu\n - Classes: %zu\n",
965 st.model.name.c_str(), st.model.nodes.size(), st.model.nclasses);
966 s += buf;
967 } else if (st.has_lqn) {
968 std::snprintf(buf, sizeof buf, " - Layered network: %zu tasks, %zu entries\n",
969 st.lqn_model.ntasks, st.lqn_model.nentries);
970 s += buf;
971 }
972 }
973 std::string tr;
974 for (std::size_t e = 0; e < stages_.size(); ++e)
975 for (std::size_t h = 0; h < stages_.size(); ++h) {
976 const EnvArc<T>& a = arcs_[e][h];
977 if (!a.enabled || a.dist.disabled) continue;
978 const double m = num_traits<T>::to_double(a.dist.mean);
979 if (is_kernel_stage(e))
980 std::snprintf(buf, sizeof buf, " %s -> %s: prob = %.4f, sojourn %s, mean = %.4f\n",
981 stages_[e].name.c_str(), stages_[h].name.c_str(), kernel_prob_(e, h),
982 lang::process_to_text(a.dist.type), m);
983 else
984 std::snprintf(buf, sizeof buf, " %s -> %s: rate = %.4f\n", stages_[e].name.c_str(),
985 stages_[h].name.c_str(), 1.0 / m);
986 tr += buf;
987 }
988 if (!tr.empty()) s += "\nTransitions:\n" + tr;
989 return s;
990 }
991
992 /** `printStageTable`: writes `stage_table_text()` to `out`. */
993 void print_stage_table(std::FILE* out = stdout) const {
994 std::fputs(stage_table_text().c_str(), out);
995 }
996
997 /**
998 * `Environment.holdTimeCdf(holdTime{e}, t)`: the holding-time CDF of stage e
999 * at the instants `t`, from the MAP for a Markovian stage and from the arc
1000 * race or kernel mixture (`mc::smp_stage_cif`) for a semi-Markov one.
1001 */
1002 std::vector<double> hold_time_cdf(std::size_t e, const std::vector<double>& t) const {
1003 check(e);
1004 if (e >= sm_stage_.size())
1005 throw InputError("Environment: the holding-time law is built by init(); call it first");
1006 if (sm_stage_[e]) return mc::smp_stage_cif(sm_arcs_[e], sm_probs_[e], t).Fhold;
1007 return mam::map_cdf(hold_time[e].map(), t);
1008 }
1009
1010 /** `Environment.holdTimeMean(holdTime{e})`: the mean holding time of stage e. */
1011 double hold_time_mean(std::size_t e) const {
1012 check(e);
1013 if (e >= hold_mean.size())
1014 throw InputError("Environment: the holding-time law is built by init(); call it first");
1015 return hold_mean[e];
1016 }
1017
1018 /** True when init() built stage e as a semi-Markov stage (no MAP holding time). */
1019 bool hold_time_is_semi_markov(std::size_t e) const {
1020 check(e);
1021 return e < sm_stage_.size() && sm_stage_[e];
1022 }
1023
1024 // ---- what init() produced --------------------------------------------
1025 std::vector<std::vector<mam::Mmap<double>>> proc; ///< proc[e][h]; disabled for a semi-Markov stage
1026 std::vector<mam::Mmap<double>> hold_time; ///< holdTime[e]; disabled for a semi-Markov stage
1027 std::vector<double> hold_mean; ///< holdMean
1028 std::vector<double> prob_env; ///< probEnv
1029 Matrix<double> prob_orig; ///< probOrig(h, e)
1030 Matrix<double> pemb; ///< probEmb, the embedded jump chain
1031 std::vector<double> rate; ///< 1/E[holding time]
1032
1033private:
1034 /** `isa(arc, 'Markovian')`: a family with a (D0,D1) form that carries one. */
1035 static bool arc_is_markovian(const lang::Distrib<T>& d) {
1036 return lang::process_is_markovian(d.type) && d.has_map();
1037 }
1038
1039 /** The 1 x 1 zero pair a disabled arc is. */
1040 static mam::Mmap<double> disabled_mmap(std::size_t E) {
1042 m.D0 = Matrix<double>(1, 1, 0.0);
1043 m.D1 = Matrix<double>(1, 1, 0.0);
1044 m.Dc.assign(E, Matrix<double>(1, 1, 0.0));
1045 return m;
1046 }
1047
1048 void check(std::size_t e) const {
1049 if (e >= stages_.size()) throw InputError("Environment: stage index out of range");
1050 }
1051
1052 /** `1 / env{e,h}.getMean()`: the arc rate the reliability reading uses. */
1053 double arc_rate(std::size_t e, std::size_t h) const {
1054 const double m = num_traits<T>::to_double(arcs_[e][h].dist.mean);
1055 if (!(m > 0.0))
1056 throw InputError("Environment: the transition " + stages_[e].name + " -> " +
1057 stages_[h].name +
1058 " has no positive mean, so it carries no rate to report");
1059 return 1.0 / m;
1060 }
1061
1062 /** Record a descriptor, replacing the one this node already had. */
1063 void record_node_failure(const NodeFailure<T>& nf) {
1064 const std::size_t idx = find_node_failure(nf.node);
1065 if (idx < node_failures_.size())
1066 node_failures_[idx] = nf;
1067 else
1068 node_failures_.push_back(nf);
1069 }
1070
1071 /**
1072 * `emmap{e}{h}`: the arc's process marked by destination -- its D1 in slot
1073 * h and zero in every other slot. A disabled arc is the 1 x 1 zero pair.
1074 */
1075 mam::Mmap<double> arc_mmap(std::size_t e, std::size_t h, std::size_t E) const {
1076 mam::Mmap<double> m;
1077 if (!arcs_[e][h].enabled) {
1078 m.D0 = Matrix<double>(1, 1, 0.0);
1079 m.D1 = Matrix<double>(1, 1, 0.0);
1080 m.Dc.assign(E, Matrix<double>(1, 1, 0.0));
1081 return m;
1082 }
1083 const lang::Distrib<T>& d = arcs_[e][h].dist;
1084 const std::size_t n = d.D0.rows();
1085 if (n == 0)
1086 throw InputError("Environment: the transition distribution has no representation");
1087 m.D0 = Matrix<double>(n, n, 0.0);
1088 m.D1 = Matrix<double>(n, n, 0.0);
1089 for (std::size_t a = 0; a < n; ++a)
1090 for (std::size_t b = 0; b < n; ++b) {
1091 m.D0(a, b) = num_traits<T>::to_double(d.D0(a, b));
1092 m.D1(a, b) = num_traits<T>::to_double(d.D1(a, b));
1093 }
1094 m.Dc.assign(E, Matrix<double>(n, n, 0.0));
1095 m.Dc[h] = m.D1;
1096 return m;
1097 }
1098
1099 /**
1100 * One fold of the reference's superposition loop: Kronecker-sum the blocks,
1101 * then move each block's row sums into its FIRST column.
1102 *
1103 * The collapse is what makes the superposed holding time RENEW at every
1104 * jump: without it the phase surviving from the losing risks would carry
1105 * into the next stage, which is not the semi-Markov model the solver then
1106 * solves.
1107 */
1108 static mam::Mmap<double> superpose_collapsed(const mam::Mmap<double>& a,
1109 const mam::Mmap<double>& b) {
1110 mam::Mmap<double> s;
1111 s.D0 = mam::krons(a.D0, b.D0);
1112 s.D1 = collapse(mam::krons(a.D1, b.D1));
1113 s.Dc.reserve(a.Dc.size());
1114 for (std::size_t c = 0; c < a.Dc.size(); ++c)
1115 s.Dc.push_back(collapse(mam::krons(a.Dc[c], b.Dc[c])));
1116 return mam::mmap_normalize(s);
1117 }
1118
1119 /** Row sums into column one, the rest zeroed. */
1120 static Matrix<double> collapse(const Matrix<double>& X) {
1121 Matrix<double> Y(X.rows(), X.cols(), 0.0);
1122 for (std::size_t i = 0; i < X.rows(); ++i) {
1123 double s = 0.0;
1124 for (std::size_t j = 0; j < X.cols(); ++j) s += X(i, j);
1125 Y(i, 0) = s;
1126 }
1127 return Y;
1128 }
1129
1130 std::string name_;
1131 std::vector<EnvStage<T>> stages_;
1132 std::vector<std::vector<EnvArc<T>>> arcs_;
1133 std::vector<NodeFailure<T>> node_failures_;
1134 Matrix<double> kernel_prob_; ///< kernelProb, NaN for a competing arc or none
1135 std::vector<char> sm_stage_; ///< per stage, whether init() built it semi-Markov
1136 std::vector<std::vector<lang::Distrib<T>>> sm_arcs_; ///< a semi-Markov stage's arcs
1137 std::vector<std::vector<double>> sm_probs_; ///< and its kernel probabilities
1138};
1139
1140} // namespace env
1141} // namespace line
1142
1143#endif // LINE_LANG_QN_ENVIRONMENT_H
InputError(const std::string &what)
Definition error.h:105
UnsupportedError(const std::string &what)
Definition error.h:119
const std::string & name() const
void set_env_rate_reset(std::size_t e, std::size_t h, const ResetEnvRates< T > &f)
resetEnvRatesFun{e,h}: make the e -> h transition depend on the state the stage is left in.
void register_node_failure(const std::string &node_name, const lang::Distrib< T > &breakdown, const lang::Distrib< T > &down_service, bool has_repair, const lang::Distrib< T > &repair, const std::string &breakdown_reset, const std::string &repair_reset)
Port of registerNodeFailure: attach a breakdown descriptor, and its reset policies,...
const std::vector< NodeFailure< T > > & node_failures() const
nodeFailures, the declarative record of the breakdowns declared here.
void init()
Port of Environment.init().
std::vector< double > rate
1/E[holding time]
void require_declared() const
Refuse a stage with no model.
Environment(const std::string &nm, std::size_t nstages)
void print_stage_table(std::FILE *out=stdout) const
printStageTable: writes stage_table_text() to out.
void add_node_breakdown(std::size_t up, std::size_t down, const qn::NetworkStruct< T > &base, const std::string &node_name, const lang::Distrib< T > &breakdown, const lang::Distrib< T > &down_service, const std::string &reset_policy="keep")
Port of addNodeBreakdown, on a FIXED stage count.
std::vector< double > hold_time_cdf(std::size_t e, const std::vector< double > &t) const
Environment.holdTimeCdf(holdTime{e}, t): the holding-time CDF of stage e at the instants t,...
bool is_semi_markov_stage(std::size_t e) const
isSemiMarkovStage: true if stage e's holding time has no Markovian (MAP) form, i.e.
bool hold_time_is_semi_markov(std::size_t e) const
True when init() built stage e as a semi-Markov stage (no MAP holding time).
void refuse_absorbing(const std::string &method) const
Refuse an absorbing environment for a coupling that reads probEnv: its limit depends on the initial s...
const EnvStage< T > & stage(std::size_t e) const
double kernel_prob(std::size_t e, std::size_t h) const
kernelProb(e,h): the kernel arc's probability, NaN for a competing arc or none.
Matrix< double > prob_orig
probOrig(h, e)
bool is_semi_markov() const
isSemiMarkov: true if any stage is semi-Markov.
std::vector< std::vector< mam::Mmap< double > > > proc
proc[e][h]; disabled for a semi-Markov stage
void add_node_failure_repair(std::size_t up, std::size_t down, const qn::NetworkStruct< T > &base, const std::string &node_name, const lang::Distrib< T > &breakdown, const lang::Distrib< T > &repair, const lang::Distrib< T > &down_service, const std::string &breakdown_reset="keep", const std::string &repair_reset="keep")
addNodeFailureRepair: the two calls above, in order.
void stage_arcs(std::size_t e, std::vector< lang::Distrib< T > > &arcs, std::vector< double > &probs) const
getStageArcs: the transitions out of stage e in the form mc::smp_stage_cif takes.
std::vector< StageRow > stage_table() const
void set_transition_dist(std::size_t e, std::size_t h, const lang::Distrib< T > &d)
Replace the distribution of an arc that is already declared.
void set_lqn_stage(std::size_t e, const std::string &nm, const std::string &type, const lqn::LqnStruct< T > &model)
addStage with a LayeredNetwork: the stage holds a LAYERED model.
bool is_absorbing_stage(std::size_t e) const
isAbsorbingStage: true if stage e has no outgoing transition, so once entered the environment stays t...
std::size_t find_stage(const std::string &nm) const
The index of the stage called nm, or nstages() when there is none.
Reliability reliability() const
std::size_t nstages() const
static std::string down_stage_name(const std::string &nm)
The name addNodeBreakdown gives the stage in which nm is down.
std::vector< mam::Mmap< double > > hold_time
holdTime[e]; disabled for a semi-Markov stage
void add_kernel_transition(std::size_t e, std::size_t h, double prob, const lang::Distrib< T > &d, const ResetMarginal &reset=ResetMarginal())
addKernelTransition: a KERNEL arc of Q(e,h,t) = prob * F(t).
bool is_kernel_stage(std::size_t e) const
isKernelStage: true if stage e's arcs are kernel arcs.
void set_reset(std::size_t e, std::size_t h, const ResetMarginal &reset)
Install a reset policy on an arc that is already declared.
std::string stage_table_text() const
printStageTable, as text: the stages with their networks, then every enabled arc in (from,...
std::size_t find_node_failure(const std::string &nm) const
findNodeFailure: the descriptor for nm, or node_failures().size().
void set_state_reset(std::size_t e, std::size_t h, const ResetStateVec< T > &f)
resetStateFun{e,h}: map the exit state-probability vector of stage e onto the entry vector of stage h...
void reject_lqn_stages(const std::string &who, const std::string &why) const
Refuse an environment carrying a LayeredNetwork stage, by name.
bool is_absorbing() const
True if some stage is absorbing, i.e.
double hold_time_mean(std::size_t e) const
Environment.holdTimeMean(holdTime{e}): the mean holding time of stage e.
void set_stage(std::size_t e, const std::string &nm, const std::string &type, const qn::NetworkStruct< T > &model)
addStage: name the stage and give it its network.
bool has_lqn_stages() const
True when ANY stage holds a LayeredNetwork.
Matrix< double > pemb
probEmb, the embedded jump chain
std::vector< double > hold_mean
holdMean
const EnvArc< T > & arc(std::size_t e, std::size_t h) const
void refuse_semi_markov(const std::string &method) const
The methodRefusal rule for every coupling but smp: refuse a kernel stage, or a competing arc that is ...
bool is_lqn(std::size_t e) const
True when stage e holds a LayeredNetwork rather than a flat network.
void add_node_repair(const std::string &node_name, const lang::Distrib< T > &repair, const std::string &reset_policy="keep")
Port of addNodeRepair: the DOWN_<node> -> UP arc and its policy.
void add_transition(std::size_t e, std::size_t h, const lang::Distrib< T > &d, const ResetMarginal &reset=ResetMarginal())
addTransition: enable e -> h with a distribution and a reset policy.
std::vector< double > prob_env
probEnv
A network plus its refreshed NetworkStruct.
Courtois decomposition of a nearly completely decomposable (NCD) CTMC.
What refreshProcessRepresentations and refreshLST compute FROM a distribution: the (D0,...
The exception types the port throws.
Enumerations and the minimal distribution descriptor shared by the model layer of the C++ port.
LayeredNetworkStruct, the flattened description of a layered queueing network.
Cumulative distribution of the inter-arrival time of a MAP.
Markovian arrival process descriptors: stationary vectors, rate, moments, autocorrelation and the ind...
Dense matrix and non-owning view.
Marked MAP (MMAP) algebra: per-class rates, class probabilities, superposition, normalization and sca...
std::function< Matrix< double >(const Matrix< double > &)> ResetMarginal
The reset policy of a transition, resetFun in the reference.
Definition environment.h:98
qn::NetworkStruct< T > env_degraded_model(const qn::NetworkStruct< T > &base, const std::string &node_name, const lang::Distrib< T > &down_service)
The DOWN stage network of addNodeBreakdown: the base network with ONE node's service replaced by its ...
std::function< lang::Distrib< T >(const lang::Distrib< T > &, const Matrix< double > &, const Matrix< double > &, const Matrix< double > &)> ResetEnvRates
resetEnvRatesFun in the reference: the state-dependent environment rate.
std::function< std::vector< T >(const std::vector< T > &)> ResetStateVec
resetStateFun{e,h} of the reference: the state distribution of stage e at the e -> h switch,...
ResetMarginal env_reset_policy(const std::string &name)
The two NAMED reset policies of Environment.resolveResetPolicy, which are the only ones the JSON inte...
void prior_refresh_moments(Distrib< T > &d)
Write the mixture moments onto a Prior, the counterpart of dist_refresh_moments for the Markovian fam...
Definition prior.h:346
const char * process_to_text(ProcessType p)
The MATLAB ProcessType name, as sn.procid prints it.
Definition lang_types.h:655
bool process_is_markovian(ProcessType p)
ProcessType.isMarkovian: true when sn.proc carries an exact matrix representation of the law,...
Definition lang_types.h:713
void dist_refresh_moments(Distrib< T > &d)
Fill in the first two moments of a distribution given by its matrices.
Mmap< T > mmap_normalize(const Mmap< T > &in)
Clamp negative off-diagonal and per-class entries to zero and rebuild D1 and the diagonal of D0 from ...
Matrix< T > krons(const Matrix< T > &A, const Matrix< T > &B)
Kronecker sum, MATLAB's krons: kron(A, I_nb) + kron(I_na, B).
Definition mmap_lambda.h:71
T map_mean(const Map< T > &m)
Mean inter-arrival time, 1/lambda.
Definition map_moment.h:101
std::vector< T > map_cdf(const Map< T > &m, const std::vector< T > &points)
Cumulative distribution of the inter-arrival time at the given points.
Definition map_cdf.h:63
std::vector< T > mmap_count_lambda(const Mmap< T > &m)
Per-class arrival rates, lambda_c = theta D1^(c) e.
ReducibleResult< T > ctmc_solve_reducible(const Matrix< T > &Q, const std::vector< T > &pi0, double zeroColTol=1e-12)
Limiting distribution of a CTMC whose generator may be reducible.
SmpStageQuad smp_stage_quad(const std::vector< lang::Distrib< T > > &arcs, const std::vector< double > &probs)
SmpStageCif smp_stage_cif(const std::vector< lang::Distrib< T > > &arcs, const std::vector< double > &probs, const std::vector< double > &t)
CIF and holding-time CDF of a stage at the ascending instants t.
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
A queueing network and its refreshed NetworkStruct.
Prior: parameter uncertainty as a weighted set of alternative models.
Cumulative incidence functions of one semi-Markov stage.
Embedded jump probabilities and mean holding time of a semi-Markov stage.
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
std::string name
Definition error.h:38
One arc of the environment process.
lang::Distrib< T > dist
the e -> h transition time
ResetStateVec< T > reset_state
resetStateFun{e,h}; empty means the identity
ResetMarginal reset
empty means the identity
ResetEnvRates< T > reset_rates
empty means the rate does not depend on the state
One stage: a name, a category, and the model in force while it lasts.
std::string type
the stage category, informational only
lqn::LqnStruct< T > lqn_model
The layered model, when this stage holds a LayeredNetwork.
bool declared() const
True when the stage carries a model of either kind.
qn::NetworkStruct< T > model
getReliabilityTable: MTTF, MTTR, MTBF and availability of an environment built out of node breakdowns...
double mttr
mean time to repair, DOWN -> UP
double availability
stationary probability of being UP
double mttf
mean time to failure, UP -> any DOWN
getStageTable: one row per stage.
std::size_t stage
1-based, as the reference prints it
Environment.nodeFailures{k}: the declarative record of one node breakdown.
std::string repair_reset
empty when there is no repair
std::string breakdown_reset
std::string node
the node that breaks down
lang::Distrib< T > down_service
the node's service while it is down
bool has_repair
false for a breakdown with no repair arc
lang::Distrib< T > breakdown
time to failure, the UP -> DOWN transition
lang::Distrib< T > repair
time to repair, the DOWN -> UP transition
bool has_map() const
True when the type carries a (D0,D1) pair of its own.
Matrix< T > D0
The (D0,D1) pair when the type carries one directly.
Definition lang_types.h:921
bool is_prior() const
Definition lang_types.h:961
An MMAP: the underlying MAP plus the per-class arrival matrices.
Definition mmap_lambda.h:45
Map< T > map() const
Definition mmap_lambda.h:52
Matrix< T > D0
Definition mmap_lambda.h:46
Matrix< T > D1
Definition mmap_lambda.h:47
std::vector< Matrix< T > > Dc
per-class matrices, sum_c Dc = D1
Definition mmap_lambda.h:48
std::vector< double > Fhold
What smp_stage_quad returns.
std::vector< double > P
the embedded jump probabilities, one per arc
double m
the mean holding time