LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
solver_env_statevec.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_SOLVERS_ENV_SOLVER_ENV_STATEVEC_H
6#define LINE_SOLVERS_ENV_SOLVER_ENV_STATEVEC_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * SolverENV, `method = "statevec"`: a port of
12 * `matlab/src/solvers/ENV/solver_env_statevec_analyzer.m`.
13 *
14 * WHAT IT DOES DIFFERENTLY FROM THE MEAN-FIELD COUPLING. `solver_env.h` carries
15 * only the MARGINAL MEAN queue lengths across an environment switch, so any
16 * correlation between stations at the moment of the switch is thrown away. This
17 * analyzer carries the whole JOINT distribution instead: each stage is an
18 * explicitly enumerated CTMC, and what crosses a switch is the full state
19 * probability vector. The two agree exactly when the marginal collapse happens
20 * to be lossless and diverge when it is not, which is the entire reason the
21 * reference keeps both.
22 *
23 * THE FIXED POINT, and it is the same shape as the mean-field one. For stage e
24 * with generator Q_e and entry distribution pi_enter[e], propagate the transient
25 * pi(t) = pi_enter[e] exp(Q_e t) over the stage's time span, then read off
26 * pi_exit[e][h] the distribution AT the e -> h switch, the expectation of
27 * pi(t) under the e -> h transition time,
28 * pi_timeavg[e] the distribution at the END of the sojourn, under the
29 * superposed holding time,
30 * and chain the entries as
31 * pi_enter[e] = sum_h prob_orig(h, e) reset_{h->e}( pi_exit[h][e] ),
32 * renormalized, iterated to an L1 fixed point. The blend at the end weights each
33 * stage's pi_timeavg by prob_env and maps it to means.
34 *
35 * THREE SOJOURN REGIMES, and only the third one integrates anything. When every
36 * outgoing transition of a stage is exponential the exit distribution equals the
37 * time-average and both are the RESOLVENT s pi_0 (sI - Q)^{-1}, a single linear
38 * solve with no quadrature -- so that regime stays exact even in rational
39 * arithmetic. A deterministic sojourn is uniformization at one point. Only a
40 * general phase-type sojourn needs the adaptive transient, and that branch is
41 * gated below.
42 *
43 * WHY THIS FILE DOES NOT DECODE MARGINALS ITSELF. There is a recorded defect
44 * here: `_kb/06-solver-catalog.md`, "ENV state-vector Util had drifted from the
45 * CTMC analyzer". MATLAB, Java and Python each grew a THIRD copy of the
46 * state-to-means reduction beside `solver_ctmc_analyzer`, all three drifted
47 * identically in the lld/cd branch, and no parity check saw it because they
48 * drifted together -- Util was overstated by 44% on a closed lld model. The
49 * reduction here is therefore `ctmc::solver_ctmc_avg_from_pi`, the same function
50 * the CTMC analyzer calls, invoked on the same `CtmcResult`. Nothing about the
51 * discipline, the load dependence or the loss guards is re-derived.
52 *
53 * THE ORACLE THAT NEEDS NO EXTERNAL REFERENCE, named in that same entry: an
54 * environment whose stages are IDENTICAL cannot change anything the network
55 * does, so this solver must reproduce the plain SolverCTMC solution of that one
56 * model. It does so EXACTLY here, not approximately, because the stationary
57 * distribution is a fixed point of all three sojourn regimes: pi Q = 0 makes the
58 * resolvent, the uniformized time-average and the transient all return pi
59 * unchanged, and `pre()` seeds from pi.
60 *
61 * WHAT IS PORTED, and what is refused by name:
62 * ported the CTMC backend, all three sojourn regimes, per-transition state
63 * reset policies, the cache hit/miss blend of `aggregateCacheBlend_`
64 * ported both stage backends -- the enumerated CTMC and the MAM/LDQBD one
65 * (`solver_mam_ldqbd` + `solver_mam_ldqbd_flatten`, reduced by
66 * `solver_mam_ldqbd_avg`) -- all three sojourn regimes, per-transition
67 * state reset policies, the cache hit/miss blend of
68 * `aggregateCacheBlend_`
69 * refused an infinite inner-solver timespan
70 *
71 * THE TWO BACKENDS DIFFER IN WHAT A STATE IS, and everything downstream of that
72 * is shared. A CTMC stage's state is an enumerated row of `sn.space`; a MAM
73 * stage's is a (level, phase) pair of the flattened QBD, with no marginal to
74 * decode and no cache content in it. So the propagation, the fixed point and the
75 * reset policies are backend-agnostic -- they act on a probability vector and a
76 * generator -- while the two ENDS are not: `pre()` builds the generator
77 * differently and `finish()` reduces it differently
78 * (`solver_ctmc_avg_from_pi` against `solver_mam_ldqbd_avg`).
79 */
80
81#include <algorithm>
82#include <cmath>
83#include <cstddef>
84#include <functional>
85#include <limits>
86#include <map>
87#include <string>
88#include <vector>
89
96#include "line/num/number.h"
101#include "line/util/error.h"
102#include "line/util/lu.h"
103#include "line/util/matrix.h"
104
105namespace line {
106namespace env {
107
108/**
109 * `resetStateFun{h,e}` of the reference: the state distribution of stage h at
110 * the h -> e switch, mapped onto the state space of stage e.
111 *
112 * This is NOT `ResetMarginal`, which acts on the (nstations x nclasses) mean
113 * queue lengths the mean-field coupling carries. The two coexist because the
114 * couplings carry different objects, and a policy expressed on means has no
115 * canonical lift to a joint distribution.
116 */
117template <class T>
118using ResetStateVec = std::function<std::vector<T>(const std::vector<T>&)>;
119
120/** Options of the state-vector coupling. */
121template <class T>
123 int iter_max = 100;
124 double iter_tol = 1e-4;
125 /**
126 * Which solver runs each stage: `"ctmc"`, the enumerated chain, or `"mam"`,
127 * which flattens a level-dependent QBD into a generator over its
128 * level/phase states. The MAM backend only accepts what `solver_mam_ldqbd`
129 * accepts -- one class and either Delay+Queue or Source+Queue -- and it
130 * carries NO cache state, so the hit/miss blend is skipped there, as the
131 * reference skips it.
132 */
133 std::string stage_solver = "ctmc";
134 /**
135 * `cutoff` handed to `solver_mam_ldqbd` for an OPEN stage, which is where
136 * the level count comes from; a closed stage takes its population instead
137 * and ignores this.
138 */
139 std::size_t mam_cutoff = 10;
140 /** `options.sojourn`: `stochastic` (default) or `deterministic`. */
141 std::string sojourn = "stochastic";
142 /** Options handed to each stage's SolverCTMC. */
144 /**
145 * `options.timespan` of the inner solver. The end DEFAULTS TO INFINITY so
146 * that a caller who never set one is refused by name rather than served a
147 * silently invented horizon -- the reference's own check, and the reason
148 * `CTMC(model,'timespan',[0,T])` is spelled out in its error message.
149 *
150 * SET IT TO A FEW MEAN HOLDING TIMES, NOT TO A LARGE SAFE NUMBER. Only the
151 * general phase-type branch reads it, and that branch integrates with
152 * `ctmc_transient`, i.e. with ode23, whose maximum step is one tenth of the
153 * span. An explicit Runge-Kutta pair is unstable once that step exceeds the
154 * chain's fastest time scale, and the local error estimate CANNOT see it:
155 * near an equilibrium the estimate vanishes with the derivative, so every
156 * oversized step is accepted and roundoff is amplified instead. On the
157 * three-job closed model of `test_env_statevec.cpp` (max |Q_ii| = 4) a span
158 * of 5 reproduces the stationary law to the last bit while a span of 50
159 * drifts to an L1 error of 7e-4. The holding-time CDF has decayed long
160 * before the horizon anyway, so a longer one buys nothing.
161 */
162 double timespan_start = 0.0;
163 double timespan_end = std::numeric_limits<double>::infinity();
164 /** Per-stage override of `timespan_end`, or empty for the global one. */
165 std::vector<double> stage_timespan_end;
166 /** `resetStateFun[h][e]`; an empty entry, or an empty table, is identity. */
167 std::vector<std::vector<ResetStateVec<T>>> reset_state;
168};
169
170/** What the state-vector coupling reports. */
171template <class T>
173 /** Environment-averaged metrics, (nstations x nclasses). */
175 /** Per-stage, sojourn-averaged metrics. */
176 std::vector<Matrix<T>> QStage, UStage, TStage;
177 /** The entry distributions the fixed point converged to, per stage. */
178 std::vector<std::vector<T>> pi_enter;
179 /** The sojourn-end distributions the blend was taken over, per stage. */
180 std::vector<std::vector<T>> pi_timeavg;
181 /**
182 * `aggregateCacheBlend_`: environment-blended hit and miss probabilities,
183 * keyed by the 1-based node index of each Cache. The reference writes these
184 * onto the stage-one node objects with `setResultHitProb`; a struct-level
185 * port has no node object to write to, so they are reported here instead.
186 * An entry is NaN for a class the cache never serves.
187 */
188 std::map<std::size_t, std::vector<T>> hit_prob, miss_prob;
189 int iterations = 0;
190 bool converged = false;
191};
192
193/**
194 * The state-vector environment solver.
195 *
196 * `envObj` must already carry a model per stage; `init()` is called here, as
197 * `SolverENV.init` does.
198 */
199template <class T>
201public:
202 SolverEnvStatevec(Environment<T>& e, const EnvStatevecOptions<T>& o) : envObj(e), opt(o) {
203 init();
204 }
205
207 const std::size_t E = envObj.nstages();
209
210 pre();
211 int it = 0;
212 for (it = 1; it <= opt.iter_max; ++it) {
213 for (std::size_t e = 0; e < E; ++e) analyze(e);
214 post();
215 if (converged()) {
216 out.converged = true;
217 break;
218 }
219 }
220 out.iterations = std::min(it, opt.iter_max);
221 finish(out);
222 return out;
223 }
224
225private:
226 void init() {
227 mam_backend = (opt.stage_solver == "mam");
228 if (!mam_backend && opt.stage_solver != "ctmc")
229 throw UnsupportedError(
230 "SolverENV statevec: stage solver '" + opt.stage_solver +
231 "' is not available; the state-vector coupling needs an EXPLICIT generator over a "
232 "state space it can propagate a distribution across, which SolverCTMC exposes by "
233 "enumeration and SolverMAM by flattening its level-dependent QBD blocks");
234 if (opt.sojourn != "stochastic" && opt.sojourn != "deterministic")
235 throw InputError("SolverENV statevec: unknown sojourn '" + opt.sojourn + "'");
236
237 // A LAYERED STAGE HAS NO SINGLE GENERATOR to propagate a distribution
238 // across -- an LQN decomposes into one network per layer, and the joint
239 // law over the union of them is not what any layer solver produces. The
240 // reference refuses it in the same place and for the same reason
241 // (`@@SolverENV/SolverENV.m`, where `method` selects the state-vector
242 // analyzer), so this is its error and not a limit of this port.
243 envObj.reject_lqn_stages(
244 "SolverENV statevec",
245 "the state-vector coupling propagates a joint distribution over ONE stage "
246 "generator, which a layered model does not have -- it decomposes into a network "
247 "per layer");
248 envObj.init();
249 const std::size_t E = envObj.nstages();
250 M = envObj.stage(0).model.nstations;
251 K = envObj.stage(0).model.nclasses;
252 for (std::size_t e = 1; e < E; ++e)
253 if (envObj.stage(e).model.nstations != M || envObj.stage(e).model.nclasses != K)
254 throw InputError(
255 "SolverENV statevec: every stage must have the same stations and classes; the "
256 "metrics are blended entrywise across them");
257
258 // The reference checks the horizon PER STAGE and names the stage that
259 // is missing one, because each stage carries its own inner solver.
260 tspan_end.assign(E, opt.timespan_end);
261 for (std::size_t e = 0; e < E; ++e) {
262 if (e < opt.stage_timespan_end.size()) tspan_end[e] = opt.stage_timespan_end[e];
263 if (!std::isfinite(tspan_end[e]) || !(tspan_end[e] > opt.timespan_start))
264 throw InputError(
265 "SolverENV statevec: the statevec analyzer requires a finite inner-solver "
266 "timespan for stage " +
267 std::to_string(e + 1) + ", e.g. CTMC(model,'timespan',[0,T])");
268 }
269
270 det_sojourn = (opt.sojourn == "deterministic");
271 stages.assign(E, ctmc::CtmcSolution<T>());
272 mam_ld.assign(E, mam::LdqbdBlocks<T>());
273 mam_flat.assign(E, mam::LdqbdFlat<T>());
274 pi_enter.assign(E, std::vector<T>());
275 pi_enter_prev.assign(E, std::vector<T>());
276 pi_exit.assign(E, std::vector<std::vector<T>>());
277 pi_timeavg.assign(E, std::vector<T>());
278 dvals.assign(E, 0.0);
279 if (det_sojourn)
280 for (std::size_t e = 0; e < E; ++e)
281 dvals[e] = std::max(mam::map_mean(envObj.hold_time[e].map()),
282 std::numeric_limits<double>::epsilon());
283 }
284
285 /**
286 * `pre_`: build each stage's chain once and warm-start its entry
287 * distribution from that stage's own stationary law, which is a valid
288 * probability vector over its state space whatever the environment does.
289 *
290 * THE CHAIN COMES FROM THE ANALYZER, not from a bare `solver_ctmc` call as
291 * the reference's `pre_` makes. The analyzer restricts a reducible generator
292 * to the weakly connected component of the model's initial state; solving
293 * the unrestricted generator instead spreads mass over states the model can
294 * never occupy. That restriction is also what makes the identical-stage
295 * oracle hold EXACTLY rather than up to the mass on unreachable states.
296 */
297 void pre() {
298 const std::size_t E = envObj.nstages();
299 for (std::size_t e = 0; e < E; ++e) {
300 if (mam_backend) {
301 // The MAM backend has no enumerated space: the stage is a
302 // level-dependent QBD, and flattening its blocks is what turns
303 // it into something a distribution can be propagated across.
304 // `Nlev` is finite by construction here -- the closed population,
305 // or the open truncation `cutoff` -- so the flat matrix exists.
306 mam::MamOptions mo;
307 mo.method = "default";
308 mo.cutoff = opt.mam_cutoff;
309 mam_ld[e] = mam::solver_mam_ldqbd(envObj.stage(e).model, mo).ld;
310 mam_flat[e] = mam::solver_mam_ldqbd_flatten(mam_ld[e]);
311 } else {
312 stages[e] = ctmc::solver_ctmc_analyzer(envObj.stage(e).model, opt.stage);
313 }
314 }
315 seed_entry_distributions();
316 pi_enter_prev = pi_enter;
317 }
318
319 /**
320 * Warm start. A stage's OWN stationary law is not a usable seed: a stage
321 * that is individually unstable or critical (arrival rate >= its own
322 * service rate) has no stationary law at all, and the reducible solver then
323 * returns the stationary law of the TRUNCATED generator, which piles mass
324 * against the truncation wall and whose mean grows linearly with the cutoff
325 * -- for a critical M/M/1 truncated at N it is uniform, with mean N/2.
326 *
327 * The fixed point chained in `post` is EXACT: it is the stationary equation
328 * of the joint (queue,stage) chain, phi_e = (sum_h phi_h q_he)(s_e I-Q_e)^-1.
329 * It does contract to the right answer from that seed, but the number of
330 * sweeps it needs grows with the cutoff, so at a finite `iter_max` the
331 * reported result drifts FURTHER from the truth as the cutoff is RAISED --
332 * the natural response to a suspect number makes it worse.
333 *
334 * Seed instead from the environment-averaged generator sum_e prob_env[e]*Q_e,
335 * positive recurrent exactly when the model is stable on average, which is
336 * the regime in which the answer exists at all; its stationary law is
337 * therefore cutoff-independent. Averaging needs one common state space, so
338 * when the stages differ in size fall back to the per-stage law, which is
339 * the best available and no worse than before.
340 */
341 void seed_entry_distributions() {
342 const std::size_t E = envObj.nstages();
343
344 // The per-stage law, which is what the seed falls back to and also what
345 // selects the recurrent class below. THE CHAIN COMES FROM THE ANALYZER,
346 // not from a bare solve: the analyzer restricts a reducible generator to
347 // the weakly connected component of the model's initial state AND uses
348 // that state to pick among the BSCCs that survive, so `stages[e].pi` is
349 // not reproducible from `gen(e)` alone. Re-deriving it here is what
350 // would spread mass over states the model can never occupy.
351 std::vector<std::vector<T>> own(E);
352 for (std::size_t e = 0; e < E; ++e) {
353 // The MAM backend has no analyzer law, and the REDUCIBLE solver:
354 // the flat generator of a truncated open QBD need not be irreducible.
355 own[e] = mam_backend ? normalized(mc::ctmc_solve_reducible(mam_flat[e].Q).pi)
356 : normalized(stages[e].pi);
357 }
358
359 bool sameSpace = E > 1;
360 for (std::size_t e = 1; e < E && sameSpace; ++e)
361 sameSpace = (state_count(e) == state_count(0));
362
363 std::vector<T> shared;
364 if (sameSpace) {
365 std::vector<double> w(E, 1.0 / static_cast<double>(E));
366 double wsum = 0.0;
367 bool usable = envObj.prob_env.size() == E;
368 for (std::size_t e = 0; e < E && usable; ++e) {
369 if (!std::isfinite(envObj.prob_env[e]) || envObj.prob_env[e] < 0.0) usable = false;
370 else wsum += envObj.prob_env[e];
371 }
372 // Stage probabilities unavailable or degenerate: weight stages equally.
373 if (usable && wsum > 0.0)
374 for (std::size_t e = 0; e < E; ++e) w[e] = envObj.prob_env[e] / wsum;
375
376 const std::size_t n = state_count(0);
377 Matrix<T> Qbar(n, n, num_traits<T>::from_double(0.0));
378 for (std::size_t e = 0; e < E; ++e) {
379 const Matrix<T>& Qe = gen(e);
380 const T we = num_traits<T>::from_double(w[e]);
381 for (std::size_t i = 0; i < n; ++i)
382 for (std::size_t j = 0; j < n; ++j) Qbar(i, j) += we * Qe(i, j);
383 }
384 // Seeded with the blended per-stage law so the recurrent class the
385 // ANALYZER chose is the one carried forward. This is also what keeps
386 // the identical-stage oracle EXACT: with equal stages Qbar == Q_0 and
387 // pi0 == pi, pi is already stationary for Q_0, so the solve returns
388 // it unchanged and the fixed point is still reached at sweep one.
389 std::vector<T> pi0(n, num_traits<T>::from_double(0.0));
390 for (std::size_t e = 0; e < E; ++e) {
391 const T we = num_traits<T>::from_double(w[e]);
392 for (std::size_t i = 0; i < n; ++i) pi0[i] += we * own[e][i];
393 }
394 shared = normalized(mc::ctmc_solve_reducible(Qbar, pi0).pi);
395 }
396
397 for (std::size_t e = 0; e < E; ++e) {
398 pi_enter[e] = shared.empty() ? own[e] : shared;
399 }
400 }
401
402 /** The stage's generator, whichever backend built it. */
403 const Matrix<T>& gen(std::size_t e) const {
404 return mam_backend ? mam_flat[e].Q : stages[e].chain.Q;
405 }
406
407 /** The size of the stage's state space, whichever backend built it. */
408 std::size_t state_count(std::size_t e) const {
409 return mam_backend ? mam_flat[e].levelOf.size() : stages[e].chain.space.size();
410 }
411
412 /**
413 * `analyze_`: propagate the entry distribution of stage e through its
414 * sojourn, recording where it lands at each destination and at the end.
415 */
416 void analyze(std::size_t e) {
417 const std::size_t E = envObj.nstages();
418 const Matrix<T>& Q = gen(e);
419 const std::vector<T> pi0 = pi_enter[e];
420
421 if (det_sojourn) {
422 // A deterministic sojourn has no CDF to integrate against: the exit
423 // is pi0 exp(Q d) and the blend is the exact time-average over
424 // [0, d], both from uniformization, and both the same toward every
425 // destination since the switch instant does not depend on where it
426 // goes.
427 std::vector<T> avg, ex;
428 time_average(pi0, Q, dvals[e], avg, ex);
429 pi_exit[e].assign(E, std::vector<T>());
430 for (std::size_t h = 0; h < E; ++h)
431 if (envObj.arc(e, h).enabled) pi_exit[e][h] = ex;
432 pi_timeavg[e] = avg;
433 return;
434 }
435
436 double s_e = 0.0;
437 if (exp_sojourn(e, s_e)) {
438 // Every outgoing transition exponential: the memorylessness makes
439 // the distribution at the switch equal to the time-average, and both
440 // are the resolvent s pi0 (sI - Q)^{-1}. One linear solve, no
441 // quadrature, and no dependence on the horizon at all.
442 const std::vector<T> res = resolvent(pi0, Q, s_e);
443 pi_exit[e].assign(E, std::vector<T>());
444 for (std::size_t h = 0; h < E; ++h)
445 if (envObj.arc(e, h).enabled) pi_exit[e][h] = res;
446 pi_timeavg[e] = res;
447 return;
448 }
449
450 // General phase-type sojourn: the transient on the integrator's own
451 // adaptive grid, averaged against the transition and holding-time CDFs.
452 if constexpr (!num_traits<T>::has_transcendental) {
453 throw UnsupportedError(
454 "SolverENV statevec: a non-exponential environment sojourn needs the transient "
455 "pi0 exp(Qt) from ctmc_transient, which is an adaptive approximation governed by "
456 "a tolerance and has no exact value in rational arithmetic; rerun with "
457 "--arith double, or use exponential transitions, whose resolvent is exact");
458 } else {
459 const mc::TransientResult<T> tr =
460 mc::ctmc_transient(Q, pi0, num_traits<T>::from_double(opt.timespan_start),
461 num_traits<T>::from_double(tspan_end[e]));
462 std::vector<double> t(tr.t.size());
463 for (std::size_t j = 0; j < tr.t.size(); ++j) t[j] = num_traits<T>::to_double(tr.t[j]);
464
465 pi_exit[e].assign(E, std::vector<T>());
466 for (std::size_t h = 0; h < E; ++h)
467 pi_exit[e][h] = stieltjes(tr.pi, cdf_weights(envObj.proc[e][h].map(), t));
468
469 const std::vector<T> avg =
470 stieltjes(tr.pi, cdf_weights(envObj.hold_time[e].map(), t));
471 if (!avg.empty()) {
472 pi_timeavg[e] = avg;
473 } else {
474 // Degenerate holding time on this grid: fall back to the
475 // terminal distribution, as the reference does.
476 const std::size_t last = tr.pi.rows() - 1, n = tr.pi.cols();
477 std::vector<T> tail(n);
478 for (std::size_t j = 0; j < n; ++j) tail[j] = tr.pi(last, j);
479 pi_timeavg[e] = tail;
480 }
481 }
482 }
483
484 /**
485 * `post_`: chain the entry distributions, carrying each stage's exit
486 * distributions into the stages they feed, weighted by prob_orig.
487 */
488 void post() {
489 const std::size_t E = envObj.nstages();
490 pi_enter_prev = pi_enter;
491 std::vector<std::vector<T>> next(E);
492
493 for (std::size_t e = 0; e < E; ++e) {
494 const std::size_t n = state_count(e);
495 std::vector<T> acc(n, num_traits<T>::from_int(0));
496 double wsum = 0.0;
497 for (std::size_t h = 0; h < E; ++h) {
498 const double po = envObj.prob_orig(h, e);
499 if (!(po > 0.0)) continue;
500 if (pi_exit[h].size() <= e || pi_exit[h][e].empty()) continue;
501 const std::vector<T> pex = reset_apply(h, e, pi_exit[h][e]);
502 if (pex.size() != n)
503 throw InputError(
504 "SolverENV statevec: reset_state[" + std::to_string(h) + "][" +
505 std::to_string(e) + "] returned a " + std::to_string(pex.size()) +
506 "-element vector but stage " + std::to_string(e + 1) + " has " +
507 std::to_string(n) +
508 " states; supply a reset that maps the state space of stage " +
509 std::to_string(h + 1) + " onto that of stage " + std::to_string(e + 1));
510 const T w = num_traits<T>::from_double(po);
511 for (std::size_t s = 0; s < n; ++s) acc[s] += T(w * pex[s]);
512 wsum += po;
513 }
514 if (wsum > 0.0) {
515 const T w = num_traits<T>::from_double(wsum);
516 for (std::size_t s = 0; s < n; ++s) acc[s] = T(acc[s] / w);
517 } else {
518 acc = pi_enter[e]; // no inflow this cycle: retain the estimate
519 }
520 next[e] = normalized(acc);
521 }
522 pi_enter = next;
523 }
524
525 /**
526 * `converged_`: the max L1 change of any entry distribution over a full
527 * cycle. It is the DISTRIBUTIONS that are compared and not the means,
528 * because two different joint laws can share every marginal mean.
529 */
530 bool converged() const {
531 const std::size_t E = envObj.nstages();
532 double l1 = 0.0;
533 for (std::size_t e = 0; e < E; ++e) {
534 const std::vector<T>& a = pi_enter[e];
535 const std::vector<T>& b = pi_enter_prev[e];
536 if (a.empty() || b.empty() || a.size() != b.size()) return false;
537 double d = 0.0;
538 for (std::size_t s = 0; s < a.size(); ++s)
539 d += std::fabs(num_traits<T>::to_double(a[s]) - num_traits<T>::to_double(b[s]));
540 l1 = std::max(l1, d);
541 }
542 if (!std::isfinite(l1)) return false;
543 return l1 < opt.iter_tol;
544 }
545
546 /**
547 * `finish_`: map each stage's sojourn-end distribution to means with the
548 * CTMC analyzer's own reduction, and blend by prob_env.
549 */
550 void finish(EnvStatevecSolution<T>& out) {
551 const std::size_t E = envObj.nstages();
552 const T zero = num_traits<T>::from_int(0);
553 out.QN = Matrix<T>(M, K, zero);
554 out.UN = Matrix<T>(M, K, zero);
555 out.TN = Matrix<T>(M, K, zero);
556 out.QStage.assign(E, Matrix<T>(M, K, zero));
557 out.UStage.assign(E, Matrix<T>(M, K, zero));
558 out.TStage.assign(E, Matrix<T>(M, K, zero));
559
560 for (std::size_t e = 0; e < E; ++e) {
561 if (pi_timeavg[e].empty()) continue;
562 Matrix<T> QNe, UNe, TNe;
563 if (mam_backend) {
564 // The LD-QBD reduction reports one column, the model being
565 // single-class by construction; K is 1 here for the same reason.
566 const mam::LdqbdAvg<T> a =
567 mam::solver_mam_ldqbd_avg(mam_ld[e], pi_timeavg[e], mam_flat[e].levelOf);
568 QNe = a.QN;
569 UNe = a.UN;
570 TNe = a.TN;
571 } else {
572 const ctmc::CtmcAvg<T> a = ctmc::solver_ctmc_avg_from_pi(
573 envObj.stage(e).model, stages[e].chain, pi_timeavg[e]);
574 QNe = a.QN;
575 UNe = a.UN;
576 TNe = a.TN;
577 }
578 out.QStage[e] = QNe;
579 out.UStage[e] = UNe;
580 out.TStage[e] = TNe;
581 const T p = num_traits<T>::from_double(envObj.prob_env[e]);
582 for (std::size_t i = 0; i < M; ++i)
583 for (std::size_t r = 0; r < K && r < QNe.cols(); ++r) {
584 out.QN(i, r) += T(p * QNe(i, r));
585 out.UN(i, r) += T(p * UNe(i, r));
586 out.TN(i, r) += T(p * TNe(i, r));
587 }
588 }
589 out.pi_enter = pi_enter;
590 out.pi_timeavg = pi_timeavg;
591 cache_blend(out);
592 }
593
594 /**
595 * `aggregateCacheBlend_`: hit and miss probabilities as the ratio of the
596 * environment-blended hit and miss THROUGHPUTS.
597 *
598 * The ratio has to be taken after the blend and not before it: a per-stage
599 * ratio weighted by prob_env would be an average of ratios, which is not
600 * the ratio the environment actually exhibits unless every stage carries
601 * the same total rate.
602 */
603 void cache_blend(EnvStatevecSolution<T>& out) const {
604 // A MAM stage's state is a (level, phase) pair of the flattened QBD: it
605 // carries no cache content and no departure-rate table to read hit and
606 // miss throughputs off, so there is nothing to blend. The reference
607 // returns here for the same reason.
608 if (mam_backend) return;
609 const std::size_t E = envObj.nstages();
610 const qn::NetworkStruct<T>& sn1 = envObj.stage(0).model;
611 const T zero = num_traits<T>::from_int(0);
612
613 for (const auto& kv : sn1.nodeparam) {
614 const std::size_t ind = kv.first;
615 const std::size_t isf = sn1.stateful_index(ind);
616 if (isf == 0) continue;
617 std::vector<T> hitT(K, zero), missT(K, zero);
618 for (std::size_t e = 0; e < E; ++e) {
619 if (pi_timeavg[e].empty()) continue;
620 const std::vector<T> pv = normalized(pi_timeavg[e]);
621 const qn::NetworkStruct<T>& sne = envObj.stage(e).model;
622 const auto it = sne.nodeparam.find(ind);
623 if (it == sne.nodeparam.end()) continue;
624 const qn::CacheParam<T>& np = it->second;
625 const T w = num_traits<T>::from_double(envObj.prob_env[e]);
626 const auto& dr = stages[e].chain.dep_rates;
627 for (std::size_t k = 0; k < K && k < np.hitclass.size(); ++k) {
628 const std::size_t hc = np.hitclass[k];
629 const std::size_t mc = k < np.missclass.size() ? np.missclass[k] : 0;
630 if (hc == 0 || mc == 0) continue;
631 for (std::size_t s = 0; s < pv.size(); ++s) {
632 hitT[k] += T(w * pv[s] * dr[s][isf - 1][hc - 1]);
633 missT[k] += T(w * pv[s] * dr[s][isf - 1][mc - 1]);
634 }
635 }
636 }
637 const T nan = num_traits<T>::from_double(std::numeric_limits<double>::quiet_NaN());
638 std::vector<T> hp(K, nan), mp(K, nan);
639 for (std::size_t k = 0; k < K; ++k) {
640 const T tot = T(hitT[k] + missT[k]);
641 if (num_traits<T>::to_double(tot) > 0) {
642 hp[k] = T(hitT[k] / tot);
643 mp[k] = T(missT[k] / tot);
644 }
645 }
646 out.hit_prob[ind] = hp;
647 out.miss_prob[ind] = mp;
648 }
649 }
650
651 // ---- the three sojourn regimes ---------------------------------------
652
653 /** True when every enabled transition out of e is exponential; `s` is their total rate. */
654 bool exp_sojourn(std::size_t e, double& s) const {
655 const std::size_t E = envObj.nstages();
656 s = 0.0;
657 bool any = false;
658 for (std::size_t h = 0; h < E; ++h) {
659 const EnvArc<T>& a = envObj.arc(e, h);
660 if (!a.enabled) continue;
661 if (a.dist.type != lang::ProcessType::EXP) return false;
662 s += num_traits<T>::to_double(a.dist.D1(0, 0));
663 any = true;
664 }
665 return any && s > 0.0;
666 }
667
668 /** `s pi0 (sI - Q)^{-1}`, solved as `(sI - Q)^T x = s pi0` on the columns. */
669 static std::vector<T> resolvent(const std::vector<T>& pi0, const Matrix<T>& Q, double s) {
670 const std::size_t n = Q.rows();
671 const T sT = num_traits<T>::from_double(s);
672 Matrix<T> A(n, n, num_traits<T>::from_int(0));
673 for (std::size_t i = 0; i < n; ++i)
674 for (std::size_t j = 0; j < n; ++j)
675 A(j, i) = T((i == j ? sT : num_traits<T>::from_int(0)) - Q(i, j));
676 std::vector<T> b(n);
677 for (std::size_t i = 0; i < n; ++i) b[i] = T(sT * pi0[i]);
678 return line::solve(A, b);
679 }
680
681 /** `ctmc_timeaverage` at the mean holding time, gated on transcendentals. */
682 static void time_average(const std::vector<T>& pi0, const Matrix<T>& Q, double d,
683 std::vector<T>& avg, std::vector<T>& ex) {
684 if constexpr (!num_traits<T>::has_transcendental) {
685 throw UnsupportedError(
686 "SolverENV statevec: a deterministic sojourn needs ctmc_timeaverage, whose "
687 "uniformization carries Poisson weights exp(-qt) that are not rational; rerun "
688 "with --arith double");
689 } else {
690 const mc::TimeAverageResult<T> r =
691 mc::ctmc_timeaverage(pi0, Q, num_traits<T>::from_double(d));
692 avg = r.piTimeAvg;
693 ex = r.piExit;
694 }
695 }
696
697 /**
698 * The Stieltjes weights of a transition over the transient grid, w_j =
699 * F(t_j) - F(t_{j-1}) with w_1 = 0.
700 *
701 * NO DENSITY IS INVOLVED, deliberately: the increments of the CDF are the
702 * measure the transition induces on this grid, and a deterministic
703 * transition has increments but no density.
704 */
705 static std::vector<double> cdf_weights(const mam::Map<double>& m,
706 const std::vector<double>& t) {
707 std::vector<double> w(t.size(), 0.0);
708 if (t.size() < 2) return w;
709 // A disabled arc is the 1 x 1 zero pair, whose CDF is identically zero.
710 bool all_zero = true;
711 for (std::size_t a = 0; a < m.D1.rows() && all_zero; ++a)
712 for (std::size_t b = 0; b < m.D1.cols() && all_zero; ++b)
713 if (m.D1(a, b) != 0.0) all_zero = false;
714 if (all_zero) return w;
715 const std::vector<double> F = mam::map_cdf(m, t);
716 for (std::size_t j = 1; j < t.size(); ++j) w[j] = F[j] - F[j - 1];
717 return w;
718 }
719
720 /** `(w' * pit) / sum(w)`; empty when the weights carry no mass or a NaN. */
721 static std::vector<T> stieltjes(const Matrix<T>& pit, const std::vector<double>& w) {
722 double sw = 0.0;
723 for (double v : w) {
724 if (std::isnan(v)) return std::vector<T>();
725 sw += v;
726 }
727 if (!(sw > 0.0)) return std::vector<T>();
728 const std::size_t n = pit.cols();
729 std::vector<T> out(n, num_traits<T>::from_int(0));
730 for (std::size_t j = 0; j < w.size() && j < pit.rows(); ++j) {
731 if (w[j] == 0.0) continue;
732 const T wj = num_traits<T>::from_double(w[j] / sw);
733 for (std::size_t s = 0; s < n; ++s) out[s] += T(wj * pit(j, s));
734 }
735 return out;
736 }
737
738 // ---- small helpers ----------------------------------------------------
739
740 std::vector<T> reset_apply(std::size_t h, std::size_t e, const std::vector<T>& p) const {
741 if (h < opt.reset_state.size() && e < opt.reset_state[h].size() && opt.reset_state[h][e])
742 return opt.reset_state[h][e](p);
743 return p;
744 }
745
746 /** Clamp the numerical dust below zero and renormalize to a distribution. */
747 static std::vector<T> normalized(const std::vector<T>& p) {
748 const T zero = num_traits<T>::from_int(0);
749 std::vector<T> q = p;
750 T tot = zero;
751 for (std::size_t s = 0; s < q.size(); ++s) {
752 if (num_traits<T>::to_double(q[s]) < 0) q[s] = zero;
753 tot += q[s];
754 }
755 if (num_traits<T>::to_double(tot) > 0)
756 for (std::size_t s = 0; s < q.size(); ++s) q[s] = T(q[s] / tot);
757 return q;
758 }
759
760 Environment<T>& envObj;
761 EnvStatevecOptions<T> opt;
762 std::size_t M = 0, K = 0;
763 bool det_sojourn = false;
764 std::vector<double> dvals, tspan_end;
765 std::vector<ctmc::CtmcSolution<T>> stages;
766 bool mam_backend = false;
767 std::vector<mam::LdqbdBlocks<T>> mam_ld;
768 std::vector<mam::LdqbdFlat<T>> mam_flat;
769 std::vector<std::vector<T>> pi_enter, pi_enter_prev, pi_timeavg;
770 std::vector<std::vector<std::vector<T>>> pi_exit; ///< pi_exit[e][h]
771};
772
773/** Solve in one call, for a caller with no use for the solver object. */
774template <class T>
778
779} // namespace env
780} // namespace line
781
782#endif // LINE_SOLVERS_ENV_SOLVER_ENV_STATEVEC_H
InputError(const std::string &what)
Definition error.h:39
UnsupportedError(const std::string &what)
Definition error.h:51
SolverEnvStatevec(Environment< T > &e, const EnvStatevecOptions< T > &o)
EnvStatevecSolution< T > solve()
Limiting distribution of a CTMC whose generator may be reducible.
Transient distribution of a CTMC over a time interval, by integrating the forward equations d pi/dt =...
Transient distribution of a CTMC by uniformization (Jensen's method), and the time-averaged distribut...
A random environment: a port of matlab/src/lang/Environment.m, restricted to what SolverENV reads out...
The exception types the port throws.
LU factorization with partial pivoting, templated on the number type.
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.
CtmcAvg< T > solver_ctmc_avg_from_pi(const NetworkStruct< T > &sn, const CtmcResult< T > &r, const std::vector< T > &pivec)
Port of solver_ctmc_avg_from_pi: map a state distribution to mean metrics.
CtmcSolution< T > solver_ctmc_analyzer(const NetworkStruct< T > &sn_in, const CtmcOptions &opt)
Port of solver_ctmc_analyzer.m plus the fork-join wrapper of @@SolverCTMC/runAnalyzer....
EnvStatevecSolution< T > solver_env_statevec(Environment< T > &e, const EnvStatevecOptions< T > &o)
Solve in one call, for a caller with no use for the solver object.
std::function< std::vector< T >(const std::vector< T > &)> ResetStateVec
resetStateFun{h,e} of the reference: the state distribution of stage h at the h -> e switch,...
LdqbdSolution< T > solver_mam_ldqbd(const qn::NetworkStruct< T > &L, const MamOptions &opt)
Port of solver_mam_ldqbd.m.
T map_mean(const Map< T > &m)
Mean inter-arrival time, 1/lambda.
Definition map_moment.h:101
LdqbdFlat< T > solver_mam_ldqbd_flatten(const LdqbdBlocks< T > &ld)
Port of solver_mam_ldqbd_flatten.m.
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
LdqbdAvg< T > solver_mam_ldqbd_avg(const LdqbdBlocks< T > &ld, const std::vector< T > &piflat_in, const std::vector< std::size_t > &levelOf)
Port of solver_mam_ldqbd_avg.m: map a distribution over the flat state space to means.
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.
TimeAverageResult< T > ctmc_timeaverage(const std::vector< T > &pi0, const Matrix< T > &Q, const T &t, double tol=1e-12, long maxiter=-1)
Time-averaged distribution (1/t) int_0^t pi(u) du, plus pi(t) itself.
TransientResult< T > ctmc_transient(const Matrix< T > &Q, const std::vector< T > &pi0, const T &t0, const T &t1, double rtol=1e-3, double atol=1e-6)
Transient distribution of a CTMC over a time interval, by integrating the forward equations d pi/dt =...
std::vector< T > solve(const Matrix< T > &A, const std::vector< T > &b)
Convenience: solve Ax = b, leaving A and b untouched.
Definition lu.h:158
A queueing network and its refreshed NetworkStruct.
Number-type abstraction for the templated API port.
Port of solver_ctmc.m: the infinitesimal generator of a queueing network, assembled from the enumerat...
Port of solver_ctmc_analyzer.m and the parts of @@SolverCTMC/runAnalyzer.m that surround one solve: t...
The two reductions that let an LD-QBD stand in for an enumerated CTMC.
The SolverCTMC knobs this port honours.
Everything one CTMC solve produces.
Options of the state-vector coupling.
std::string sojourn
options.sojourn: stochastic (default) or deterministic.
ctmc::CtmcOptions stage
Options handed to each stage's SolverCTMC.
std::vector< double > stage_timespan_end
Per-stage override of timespan_end, or empty for the global one.
std::vector< std::vector< ResetStateVec< T > > > reset_state
resetStateFun[h][e]; an empty entry, or an empty table, is identity.
std::string stage_solver
Which solver runs each stage: "ctmc", the enumerated chain, or "mam", which flattens a level-dependen...
double timespan_start
options.timespan of the inner solver.
std::size_t mam_cutoff
cutoff handed to solver_mam_ldqbd for an OPEN stage, which is where the level count comes from; a clo...
What the state-vector coupling reports.
std::vector< Matrix< T > > QStage
Per-stage, sojourn-averaged metrics.
std::vector< Matrix< T > > UStage
std::map< std::size_t, std::vector< T > > hit_prob
aggregateCacheBlend_: environment-blended hit and miss probabilities, keyed by the 1-based node index...
std::map< std::size_t, std::vector< T > > miss_prob
std::vector< Matrix< T > > TStage
Matrix< T > QN
Environment-averaged metrics, (nstations x nclasses).
std::vector< std::vector< T > > pi_enter
The entry distributions the fixed point converged to, per stage.
std::vector< std::vector< T > > pi_timeavg
The sojourn-end distributions the blend was taken over, per stage.
The LD-QBD blocks and parameters, the reference's optional eighth output.
The flat generator of an LD-QBD, with the level each flat state belongs to.