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], read off
25 * pi_exit[e][h] the distribution AT the e -> h switch,
26 * pi_timeavg[e] the distribution averaged over the sojourn,
27 * and chain the entries as
28 * pi_enter[e] = sum_h prob_orig(h, e) reset_{h->e}( pi_exit[h][e] ),
29 * renormalized, iterated to an L1 fixed point. The blend at the end weights each
30 * stage's pi_timeavg by prob_env and maps it to means.
31 *
32 * THREE SOJOURN REGIMES, none of which integrates anything. When every outgoing
33 * transition of a stage is exponential the exit distribution equals the
34 * time-average and both are the RESOLVENT s pi_0 (sI - Q)^{-1}. A deterministic
35 * sojourn is uniformization at one point. A general phase-type sojourn is solved
36 * IN CLOSED FORM on the product of the stage chain and the stage's holding-time
37 * MMAP H = {D0h, D1h, Dc[h]}: with alpha = map_pie(H),
38 * x = (pi_0 (x) alpha) (-(Q (+) D0h))^{-1}, state-major index i*p + j,
39 * the time-average is the normalized row sums of X and the exit toward h the
40 * normalized X Dc[h] 1. It is one linear solve, exact in rational arithmetic,
41 * and needs NO inner-solver horizon: before 2026-11-15 this branch integrated
42 * the transient with ode23 over a caller-supplied `timespan_end` and refused an
43 * infinite one, which is why `default` could not resolve here.
44 *
45 * WHY THIS FILE DOES NOT DECODE MARGINALS ITSELF. There is a recorded defect
46 * here: `_kb/06-solver-catalog.md`, "ENV state-vector Util had drifted from the
47 * CTMC analyzer". MATLAB, Java and Python each grew a THIRD copy of the
48 * state-to-means reduction beside `solver_ctmc_analyzer`, all three drifted
49 * identically in the lld/cd branch, and no parity check saw it because they
50 * drifted together -- Util was overstated by 44% on a closed lld model. The
51 * reduction here is therefore `ctmc::solver_ctmc_avg_from_pi`, the same function
52 * the CTMC analyzer calls, invoked on the same `CtmcResult`. Nothing about the
53 * discipline, the load dependence or the loss guards is re-derived.
54 *
55 * THE ORACLE THAT NEEDS NO EXTERNAL REFERENCE, named in that same entry: an
56 * environment whose stages are IDENTICAL cannot change anything the network
57 * does, so this solver must reproduce the plain SolverCTMC solution of that one
58 * model. It does so EXACTLY here, not approximately, because the stationary
59 * distribution is a fixed point of all three sojourn regimes: pi Q = 0 makes the
60 * resolvent, the uniformized time-average and the product-chain solve all return pi
61 * unchanged, and `pre()` seeds from pi.
62 *
63 * WHAT IS PORTED, and what is refused by name:
64 * ported the CTMC backend, all three sojourn regimes, per-transition state
65 * reset policies, the cache hit/miss blend of `aggregateCacheBlend_`
66 * ported both stage backends -- the enumerated CTMC and the MAM/LDQBD one
67 * (`solver_mam_ldqbd` + `solver_mam_ldqbd_flatten`, reduced by
68 * `solver_mam_ldqbd_avg`) -- all three sojourn regimes, per-transition
69 * state reset policies, the cache hit/miss blend of
70 * `aggregateCacheBlend_`, with its exact delayed-hit split on a
71 * retrieval-aware cache (CTMC backend, `ctmc::cache_delayed_hit_rate`)
72 * refused a semi-Markov or absorbing stage (no holding-time MMAP to
73 * couple against)
74 *
75 * THE TWO BACKENDS DIFFER IN WHAT A STATE IS, and everything downstream of that
76 * is shared. A CTMC stage's state is an enumerated row of `sn.space`; a MAM
77 * stage's is a (level, phase) pair of the flattened QBD, with no marginal to
78 * decode and no cache content in it. So the propagation, the fixed point and the
79 * reset policies are backend-agnostic -- they act on a probability vector and a
80 * generator -- while the two ENDS are not: `pre()` builds the generator
81 * differently and `finish()` reduces it differently
82 * (`solver_ctmc_avg_from_pi` against `solver_mam_ldqbd_avg`).
83 */
84
85#include <algorithm>
86#include <cmath>
87#include <cstddef>
88#include <functional>
89#include <limits>
90#include <map>
91#include <string>
92#include <vector>
93
99#include "line/num/number.h"
105#include "line/util/error.h"
106#include "line/util/lu.h"
107#include "line/util/matrix.h"
108
109namespace line {
110namespace env {
111
112// `ResetStateVec`, the `resetStateFun` type, is declared with the Environment
113// (line/lang/qn/environment.h), which carries it per arc as `EnvArc::reset_state`.
114
115/** Options of the state-vector coupling. */
116template <class T>
118 int iter_max = 100;
119 double iter_tol = 1e-4;
120 /**
121 * Which solver runs each stage: `"ctmc"`, the enumerated chain, or `"mam"`,
122 * which flattens a level-dependent QBD into a generator over its
123 * level/phase states. The MAM backend only accepts what `solver_mam_ldqbd`
124 * accepts -- one class and either Delay+Queue or Source+Queue -- and it
125 * carries NO cache state, so the hit/miss blend is skipped there, as the
126 * reference skips it.
127 */
128 std::string stage_solver = "ctmc";
129 /**
130 * `cutoff` handed to `solver_mam_ldqbd` for an OPEN stage, which is where
131 * the level count comes from; a closed stage takes its population instead
132 * and ignores this.
133 */
134 std::size_t mam_cutoff = 10;
135 /** `options.sojourn`: `stochastic` (default) or `deterministic`. */
136 std::string sojourn = "stochastic";
137 /** Options handed to each stage's SolverCTMC. */
139 /**
140 * `resetStateFun[h][e]`, an OVERRIDE of the environment's own: a non-empty
141 * entry here is applied in place of `envObj.arc(h, e).reset_state`. An
142 * empty entry, or an empty table, defers to the arc, whose empty function
143 * is the identity.
144 */
145 std::vector<std::vector<ResetStateVec<T>>> reset_state;
146};
147
148/** What the state-vector coupling reports. */
149template <class T>
151 /** Environment-averaged metrics, (nstations x nclasses). */
153 /** Per-stage, sojourn-averaged metrics. */
154 std::vector<Matrix<T>> QStage, UStage, TStage;
155 /** The entry distributions the fixed point converged to, per stage. */
156 std::vector<std::vector<T>> pi_enter;
157 /** The sojourn-end distributions the blend was taken over, per stage. */
158 std::vector<std::vector<T>> pi_timeavg;
159 /**
160 * `aggregateCacheBlend_`: the environment-blended cache surface. The
161 * reference writes it onto the stage-one node objects with
162 * `setResultHitProb`; a struct-level port has no node object to write to,
163 * so it is reported here instead, and a class the cache never serves stays
164 * NaN rather than reading as "never hits".
165 *
166 * KEYED BY NAME, in `CacheMetrics`' one shape rather than the node-index
167 * map this used to be: the mean-field coupling and the closed-form limits
168 * report the same surface, and indexing a cache result by position is what
169 * once made a host write it onto a Sink (see `cache_metrics.h`).
170 */
172 int iterations = 0;
173 bool converged = false;
174};
175
176/**
177 * The state-vector environment solver.
178 *
179 * `envObj` must already carry a model per stage; `init()` is called here, as
180 * `SolverENV.init` does.
181 */
182template <class T>
184public:
185 SolverEnvStatevec(Environment<T>& e, const EnvStatevecOptions<T>& o) : envObj(e), opt(o) {
186 init();
187 }
188
190 const std::size_t E = envObj.nstages();
192
193 pre();
194 int it = 0;
195 for (it = 1; it <= opt.iter_max; ++it) {
196 for (std::size_t e = 0; e < E; ++e) analyze(e);
197 post();
198 if (converged()) {
199 out.converged = true;
200 break;
201 }
202 }
203 out.iterations = std::min(it, opt.iter_max);
204 finish(out);
205 return out;
206 }
207
208private:
209 void init() {
210 mam_backend = (opt.stage_solver == "mam");
211 if (!mam_backend && opt.stage_solver != "ctmc")
212 throw UnsupportedError(ErrorKind{"Option"},
213 "SolverENV statevec: stage solver '" + opt.stage_solver +
214 "' is not available; the state-vector coupling needs an EXPLICIT generator over a "
215 "state space it can propagate a distribution across, which SolverCTMC exposes by "
216 "enumeration and SolverMAM by flattening its level-dependent QBD blocks");
217 if (opt.sojourn != "stochastic" && opt.sojourn != "deterministic")
218 throw InputError("SolverENV statevec: unknown sojourn '" + opt.sojourn + "'");
219
220 // A LAYERED STAGE HAS NO SINGLE GENERATOR to propagate a distribution
221 // across -- an LQN decomposes into one network per layer, and the joint
222 // law over the union of them is not what any layer solver produces. The
223 // reference refuses it in the same place and for the same reason
224 // (`@@SolverENV/SolverENV.m`, where `method` selects the state-vector
225 // analyzer), so this is its error and not a limit of this port.
226 envObj.reject_lqn_stages(
227 "SolverENV statevec",
228 "the state-vector coupling propagates a joint distribution over ONE stage "
229 "generator, which a layered model does not have -- it decomposes into a network "
230 "per layer");
231 envObj.refuse_semi_markov("statevec");
232 envObj.refuse_absorbing("statevec");
233 envObj.init();
234 const std::size_t E = envObj.nstages();
235 M = envObj.stage(0).model.nstations;
236 K = envObj.stage(0).model.nclasses;
237 for (std::size_t e = 1; e < E; ++e)
238 if (envObj.stage(e).model.nstations != M || envObj.stage(e).model.nclasses != K)
239 throw InputError(
240 "SolverENV statevec: every stage must have the same stations and classes; the "
241 "metrics are blended entrywise across them");
242
243 det_sojourn = (opt.sojourn == "deterministic");
244 stages.assign(E, ctmc::CtmcSolution<T>());
245 mam_ld.assign(E, mam::LdqbdBlocks<T>());
246 mam_flat.assign(E, mam::LdqbdFlat<T>());
247 pi_enter.assign(E, std::vector<T>());
248 pi_enter_prev.assign(E, std::vector<T>());
249 pi_exit.assign(E, std::vector<std::vector<T>>());
250 pi_timeavg.assign(E, std::vector<T>());
251 dvals.assign(E, 0.0);
252 if (det_sojourn)
253 for (std::size_t e = 0; e < E; ++e)
254 dvals[e] = std::max(envObj.hold_time_mean(e),
255 std::numeric_limits<double>::epsilon());
256 }
257
258 /**
259 * `pre_`: build each stage's chain once and warm-start its entry
260 * distribution from that stage's own stationary law, which is a valid
261 * probability vector over its state space whatever the environment does.
262 *
263 * THE CHAIN COMES FROM THE ANALYZER, not from a bare `solver_ctmc` call as
264 * the reference's `pre_` makes. The analyzer restricts a reducible generator
265 * to the weakly connected component of the model's initial state; solving
266 * the unrestricted generator instead spreads mass over states the model can
267 * never occupy. That restriction is also what makes the identical-stage
268 * oracle hold EXACTLY rather than up to the mass on unreachable states.
269 */
270 void pre() {
271 const std::size_t E = envObj.nstages();
272 for (std::size_t e = 0; e < E; ++e) {
273 if (mam_backend) {
274 // The MAM backend has no enumerated space: the stage is a
275 // level-dependent QBD, and flattening its blocks is what turns
276 // it into something a distribution can be propagated across.
277 // `Nlev` is finite by construction here -- the closed population,
278 // or the open truncation `cutoff` -- so the flat matrix exists.
279 mam::MamOptions mo;
280 mo.method = "default";
281 mo.cutoff = opt.mam_cutoff;
282 mam_ld[e] = mam::solver_mam_ldqbd(envObj.stage(e).model, mo).ld;
283 mam_flat[e] = mam::solver_mam_ldqbd_flatten(mam_ld[e]);
284 } else {
285 stages[e] = ctmc::solver_ctmc_analyzer(envObj.stage(e).model, opt.stage);
286 }
287 }
288 seed_entry_distributions();
289 pi_enter_prev = pi_enter;
290 }
291
292 /**
293 * Warm start. A stage's OWN stationary law is not a usable seed: a stage
294 * that is individually unstable or critical (arrival rate >= its own
295 * service rate) has no stationary law at all, and the reducible solver then
296 * returns the stationary law of the TRUNCATED generator, which piles mass
297 * against the truncation wall and whose mean grows linearly with the cutoff
298 * -- for a critical M/M/1 truncated at N it is uniform, with mean N/2.
299 *
300 * The fixed point chained in `post` is EXACT: it is the stationary equation
301 * of the joint (queue,stage) chain, phi_e = (sum_h phi_h q_he)(s_e I-Q_e)^-1.
302 * It does contract to the right answer from that seed, but the number of
303 * sweeps it needs grows with the cutoff, so at a finite `iter_max` the
304 * reported result drifts FURTHER from the truth as the cutoff is RAISED --
305 * the natural response to a suspect number makes it worse.
306 *
307 * Seed instead from the environment-averaged generator sum_e prob_env[e]*Q_e,
308 * positive recurrent exactly when the model is stable on average, which is
309 * the regime in which the answer exists at all; its stationary law is
310 * therefore cutoff-independent. Averaging needs one common state space, so
311 * when the stages differ in size fall back to the per-stage law, which is
312 * the best available and no worse than before.
313 */
314 void seed_entry_distributions() {
315 const std::size_t E = envObj.nstages();
316
317 // The per-stage law, which is what the seed falls back to and also what
318 // selects the recurrent class below. THE CHAIN COMES FROM THE ANALYZER,
319 // not from a bare solve: the analyzer restricts a reducible generator to
320 // the weakly connected component of the model's initial state AND uses
321 // that state to pick among the BSCCs that survive, so `stages[e].pi` is
322 // not reproducible from `gen(e)` alone. Re-deriving it here is what
323 // would spread mass over states the model can never occupy.
324 std::vector<std::vector<T>> own(E);
325 for (std::size_t e = 0; e < E; ++e) {
326 // The MAM backend has no analyzer law, and the REDUCIBLE solver:
327 // the flat generator of a truncated open QBD need not be irreducible.
328 own[e] = mam_backend ? normalized(mc::ctmc_solve_reducible(mam_flat[e].Q).pi)
329 : normalized(stages[e].pi);
330 }
331
332 bool sameSpace = E > 1;
333 for (std::size_t e = 1; e < E && sameSpace; ++e)
334 sameSpace = (state_count(e) == state_count(0));
335
336 std::vector<T> shared;
337 if (sameSpace) {
338 std::vector<double> w(E, 1.0 / static_cast<double>(E));
339 double wsum = 0.0;
340 bool usable = envObj.prob_env.size() == E;
341 for (std::size_t e = 0; e < E && usable; ++e) {
342 if (!std::isfinite(envObj.prob_env[e]) || envObj.prob_env[e] < 0.0) usable = false;
343 else wsum += envObj.prob_env[e];
344 }
345 // Stage probabilities unavailable or degenerate: weight stages equally.
346 if (usable && wsum > 0.0)
347 for (std::size_t e = 0; e < E; ++e) w[e] = envObj.prob_env[e] / wsum;
348
349 const std::size_t n = state_count(0);
350 Matrix<T> Qbar(n, n, num_traits<T>::from_double(0.0));
351 for (std::size_t e = 0; e < E; ++e) {
352 const Matrix<T>& Qe = gen(e);
353 const T we = num_traits<T>::from_double(w[e]);
354 for (std::size_t i = 0; i < n; ++i)
355 for (std::size_t j = 0; j < n; ++j) Qbar(i, j) += we * Qe(i, j);
356 }
357 // Seeded with the blended per-stage law so the recurrent class the
358 // ANALYZER chose is the one carried forward. This is also what keeps
359 // the identical-stage oracle EXACT: with equal stages Qbar == Q_0 and
360 // pi0 == pi, pi is already stationary for Q_0, so the solve returns
361 // it unchanged and the fixed point is still reached at sweep one.
362 std::vector<T> pi0(n, num_traits<T>::from_double(0.0));
363 for (std::size_t e = 0; e < E; ++e) {
364 const T we = num_traits<T>::from_double(w[e]);
365 for (std::size_t i = 0; i < n; ++i) pi0[i] += we * own[e][i];
366 }
367 shared = normalized(mc::ctmc_solve_reducible(Qbar, pi0).pi);
368 }
369
370 for (std::size_t e = 0; e < E; ++e) {
371 pi_enter[e] = shared.empty() ? own[e] : shared;
372 }
373 }
374
375 /** The stage's generator, whichever backend built it. */
376 const Matrix<T>& gen(std::size_t e) const {
377 return mam_backend ? mam_flat[e].Q : stages[e].chain.Q;
378 }
379
380 /** The size of the stage's state space, whichever backend built it. */
381 std::size_t state_count(std::size_t e) const {
382 return mam_backend ? mam_flat[e].levelOf.size() : stages[e].chain.space.size();
383 }
384
385 /**
386 * `analyze_`: propagate the entry distribution of stage e through its
387 * sojourn, recording where it lands at each destination and at the end.
388 */
389 void analyze(std::size_t e) {
390 const std::size_t E = envObj.nstages();
391 const Matrix<T>& Q = gen(e);
392 const std::vector<T> pi0 = pi_enter[e];
393
394 if (det_sojourn) {
395 // A deterministic sojourn has no CDF to integrate against: the exit
396 // is pi0 exp(Q d) and the blend is the exact time-average over
397 // [0, d], both from uniformization, and both the same toward every
398 // destination since the switch instant does not depend on where it
399 // goes.
400 std::vector<T> avg, ex;
401 time_average(pi0, Q, dvals[e], avg, ex);
402 pi_exit[e].assign(E, std::vector<T>());
403 for (std::size_t h = 0; h < E; ++h)
404 if (envObj.arc(e, h).enabled) pi_exit[e][h] = ex;
405 pi_timeavg[e] = avg;
406 return;
407 }
408
409 double s_e = 0.0;
410 if (exp_sojourn(e, s_e)) {
411 // Every outgoing transition exponential: the memorylessness makes
412 // the distribution at the switch equal to the time-average, and both
413 // are the resolvent s pi0 (sI - Q)^{-1}. One linear solve, no
414 // quadrature, and no dependence on the horizon at all.
415 const std::vector<T> res = resolvent(pi0, Q, s_e);
416 pi_exit[e].assign(E, std::vector<T>());
417 for (std::size_t h = 0; h < E; ++h)
418 if (envObj.arc(e, h).enabled) pi_exit[e][h] = res;
419 pi_timeavg[e] = res;
420 return;
421 }
422
423 // General phase-type sojourn, in closed form. The stage state and the
424 // holding-time MMAP H = {D0h, D1h, Dc[h]} (mark h = the switch to h)
425 // evolve jointly on Q (+) D0h until the sojourn ends, so with
426 // alpha = map_pie(H) the expected occupation of that product chain is
427 // x = (pi0 (x) alpha) (-(Q (+) D0h))^{-1}. Its row sums over the holding
428 // phases are the time average over the sojourn, and the mass absorbed
429 // through mark h is X * (Dc[h] * 1), the exit law toward h. One linear
430 // solve, no horizon and no quadrature, so it is exact in any arithmetic.
431 sojourn_closed_form(e, pi0, Q);
432 }
433
434 /**
435 * `post_`: chain the entry distributions, carrying each stage's exit
436 * distributions into the stages they feed, weighted by prob_orig.
437 */
438 void post() {
439 const std::size_t E = envObj.nstages();
440 pi_enter_prev = pi_enter;
441 std::vector<std::vector<T>> next(E);
442
443 for (std::size_t e = 0; e < E; ++e) {
444 const std::size_t n = state_count(e);
445 std::vector<T> acc(n, num_traits<T>::from_int(0));
446 double wsum = 0.0;
447 for (std::size_t h = 0; h < E; ++h) {
448 const double po = envObj.prob_orig(h, e);
449 if (!(po > 0.0)) continue;
450 if (pi_exit[h].size() <= e || pi_exit[h][e].empty()) continue;
451 const std::vector<T> pex = reset_apply(h, e, pi_exit[h][e]);
452 if (pex.size() != n)
453 throw InputError(
454 "SolverENV statevec: resetStateFun[" + std::to_string(h) + "][" +
455 std::to_string(e) + "] returned a " + std::to_string(pex.size()) +
456 "-element vector but stage " + std::to_string(e + 1) + " has " +
457 std::to_string(n) +
458 " states; supply a reset that maps the state space of stage " +
459 std::to_string(h + 1) + " onto that of stage " + std::to_string(e + 1));
460 const T w = num_traits<T>::from_double(po);
461 for (std::size_t s = 0; s < n; ++s) acc[s] += T(w * pex[s]);
462 wsum += po;
463 }
464 if (wsum > 0.0) {
465 const T w = num_traits<T>::from_double(wsum);
466 for (std::size_t s = 0; s < n; ++s) acc[s] = T(acc[s] / w);
467 } else {
468 acc = pi_enter[e]; // no inflow this cycle: retain the estimate
469 }
470 next[e] = normalized(acc);
471 }
472 pi_enter = next;
473 }
474
475 /**
476 * `converged_`: the max L1 change of any entry distribution over a full
477 * cycle. It is the DISTRIBUTIONS that are compared and not the means,
478 * because two different joint laws can share every marginal mean.
479 */
480 bool converged() const {
481 const std::size_t E = envObj.nstages();
482 double l1 = 0.0;
483 for (std::size_t e = 0; e < E; ++e) {
484 const std::vector<T>& a = pi_enter[e];
485 const std::vector<T>& b = pi_enter_prev[e];
486 if (a.empty() || b.empty() || a.size() != b.size()) return false;
487 double d = 0.0;
488 for (std::size_t s = 0; s < a.size(); ++s)
489 d += std::fabs(num_traits<T>::to_double(a[s]) - num_traits<T>::to_double(b[s]));
490 l1 = std::max(l1, d);
491 }
492 if (!std::isfinite(l1)) return false;
493 return l1 < opt.iter_tol;
494 }
495
496 /**
497 * `finish_`: map each stage's sojourn-end distribution to means with the
498 * CTMC analyzer's own reduction, and blend by prob_env.
499 */
500 void finish(EnvStatevecSolution<T>& out) {
501 const std::size_t E = envObj.nstages();
502 const T zero = num_traits<T>::from_int(0);
503 out.QN = Matrix<T>(M, K, zero);
504 out.UN = Matrix<T>(M, K, zero);
505 out.TN = Matrix<T>(M, K, zero);
506 out.QStage.assign(E, Matrix<T>(M, K, zero));
507 out.UStage.assign(E, Matrix<T>(M, K, zero));
508 out.TStage.assign(E, Matrix<T>(M, K, zero));
509
510 for (std::size_t e = 0; e < E; ++e) {
511 if (pi_timeavg[e].empty()) continue;
512 Matrix<T> QNe, UNe, TNe;
513 if (mam_backend) {
514 // The LD-QBD reduction reports one column, the model being
515 // single-class by construction; K is 1 here for the same reason.
516 const mam::LdqbdAvg<T> a =
517 mam::solver_mam_ldqbd_avg(mam_ld[e], pi_timeavg[e], mam_flat[e].levelOf);
518 QNe = a.QN;
519 UNe = a.UN;
520 TNe = a.TN;
521 } else {
522 // stationary=false: pi_timeavg is a SOJOURN-AVERAGED TRANSIENT
523 // law, so the arrival-rate utilization reading does not balance
524 // the departure-rate one and max() of the two biases upward.
525 const ctmc::CtmcAvg<T> a = ctmc::solver_ctmc_avg_from_pi(
526 envObj.stage(e).model, stages[e].chain, pi_timeavg[e], false);
527 QNe = a.QN;
528 UNe = a.UN;
529 TNe = a.TN;
530 }
531 out.QStage[e] = QNe;
532 out.UStage[e] = UNe;
533 out.TStage[e] = TNe;
534 const T p = num_traits<T>::from_double(envObj.prob_env[e]);
535 for (std::size_t i = 0; i < M; ++i)
536 for (std::size_t r = 0; r < K && r < QNe.cols(); ++r) {
537 out.QN(i, r) += T(p * QNe(i, r));
538 out.UN(i, r) += T(p * UNe(i, r));
539 out.TN(i, r) += T(p * TNe(i, r));
540 }
541 }
542 out.pi_enter = pi_enter;
543 out.pi_timeavg = pi_timeavg;
544 cache_blend(out);
545 }
546
547 /**
548 * `aggregateCacheBlend_`: hit and miss probabilities as the ratio of the
549 * environment-blended hit and miss THROUGHPUTS.
550 *
551 * The ratio has to be taken after the blend and not before it: a per-stage
552 * ratio weighted by prob_env would be an average of ratios, which is not
553 * the ratio the environment actually exhibits unless every stage carries
554 * the same total rate.
555 */
556 void cache_blend(EnvStatevecSolution<T>& out) const {
557 // A MAM stage's state is a (level, phase) pair of the flattened QBD: it
558 // carries no cache content and no departure-rate table to read hit and
559 // miss throughputs off, so there is nothing to blend. The reference
560 // returns here for the same reason.
561 if (mam_backend) return;
562 const std::size_t E = envObj.nstages();
563 const qn::NetworkStruct<T>& sn1 = envObj.stage(0).model;
564 const T zero = num_traits<T>::from_int(0);
565
566 out.cache = solvers::cache_metrics_of(sn1, std::vector<T>(), std::vector<T>(),
567 std::vector<T>(), std::vector<T>(), Matrix<T>(),
568 Matrix<T>(), std::vector<T>());
569 for (std::size_t c = 0; c < out.cache.caches.size(); ++c) {
570 const std::size_t ind = out.cache.caches[c].node;
571 const std::size_t isf = sn1.stateful_index(ind);
572 if (isf == 0) continue;
573 std::vector<T> hitT(K, zero), missT(K, zero), dhitT(K, zero);
574 bool any_delayed = false;
575 for (std::size_t e = 0; e < E; ++e) {
576 if (pi_timeavg[e].empty()) continue;
577 const std::vector<T> pv = normalized(pi_timeavg[e]);
578 const qn::NetworkStruct<T>& sne = envObj.stage(e).model;
579 const auto it = sne.nodeparam.find(ind);
580 if (it == sne.nodeparam.end()) continue;
581 const qn::CacheParam<T>& np = it->second;
582 const T w = num_traits<T>::from_double(envObj.prob_env[e]);
583 const auto& dr = stages[e].chain.dep_rates;
584 // Delayed hits depart in the HIT class, so the hit-class departure rate is (true
585 // hits + delayed hits) and the exact transition reward splits it.
586 const std::vector<double> drate =
587 ctmc::analyzer_detail::cache_delayed_hit_rate(sne, ind, stages[e].chain, pv);
588 for (std::size_t k = 0; k < K && k < np.hitclass.size(); ++k) {
589 const std::size_t hc = np.hitclass[k];
590 const std::size_t mc = k < np.missclass.size() ? np.missclass[k] : 0;
591 if (hc == 0 || mc == 0) continue;
592 T hit_rate = zero, miss_rate = zero;
593 for (std::size_t s = 0; s < pv.size(); ++s) {
594 hit_rate += T(pv[s] * dr[s][isf - 1][hc - 1]);
595 miss_rate += T(pv[s] * dr[s][isf - 1][mc - 1]);
596 }
597 T dk = zero;
598 if (k < drate.size())
599 dk = num_traits<T>::from_double(
600 std::min(drate[k], num_traits<T>::to_double(hit_rate)));
601 if (num_traits<T>::to_double(dk) > 0) any_delayed = true;
602 hitT[k] += T(w * T(hit_rate - dk));
603 dhitT[k] += T(w * dk);
604 missT[k] += T(w * miss_rate);
605 }
606 }
607 const T nan = num_traits<T>::from_double(std::numeric_limits<double>::quiet_NaN());
608 std::vector<T> hp(K, nan), mp(K, nan), dp(K, nan);
609 for (std::size_t k = 0; k < K; ++k) {
610 const T tot = T(hitT[k] + missT[k] + dhitT[k]);
611 if (num_traits<T>::to_double(tot) > 0) {
612 hp[k] = T(hitT[k] / tot);
613 mp[k] = T(missT[k] / tot);
614 dp[k] = T(dhitT[k] / tot);
615 }
616 }
617 out.cache.caches[c].hitprob = hp;
618 out.cache.caches[c].missprob = mp;
619 if (any_delayed) out.cache.caches[c].delayedprob = dp;
620 }
621 }
622
623 // ---- the three sojourn regimes ---------------------------------------
624
625 /** True when every enabled transition out of e is exponential; `s` is their total rate. */
626 bool exp_sojourn(std::size_t e, double& s) const {
627 const std::size_t E = envObj.nstages();
628 s = 0.0;
629 bool any = false;
630 for (std::size_t h = 0; h < E; ++h) {
631 const EnvArc<T>& a = envObj.arc(e, h);
632 if (!a.enabled) continue;
633 if (a.dist.type != lang::ProcessType::EXP) return false;
634 s += num_traits<T>::to_double(a.dist.D1(0, 0));
635 any = true;
636 }
637 return any && s > 0.0;
638 }
639
640 /** `s pi0 (sI - Q)^{-1}`, solved as `(sI - Q)^T x = s pi0` on the columns. */
641 static std::vector<T> resolvent(const std::vector<T>& pi0, const Matrix<T>& Q, double s) {
642 const std::size_t n = Q.rows();
643 const T sT = num_traits<T>::from_double(s);
644 Matrix<T> A(n, n, num_traits<T>::from_int(0));
645 for (std::size_t i = 0; i < n; ++i)
646 for (std::size_t j = 0; j < n; ++j)
647 A(j, i) = T((i == j ? sT : num_traits<T>::from_int(0)) - Q(i, j));
648 std::vector<T> b(n);
649 for (std::size_t i = 0; i < n; ++i) b[i] = T(sT * pi0[i]);
650 return line::solve(A, b);
651 }
652
653 /**
654 * The general Markovian sojourn of stage e: time average and per-destination
655 * exit laws from one solve on the product of the stage chain and the
656 * holding-time MMAP, `x (-(Q (+) D0h)) = pi0 (x) alpha`, state-major index
657 * `i * p + j`. Mirrors `solver_env_statevec_analyzer.m`.
658 */
659 void sojourn_closed_form(std::size_t e, const std::vector<T>& pi0, const Matrix<T>& Q) {
660 const std::size_t E = envObj.nstages();
661 const mam::Mmap<double>& H = envObj.hold_time[e];
662 const std::size_t p = H.D0.rows(), d = Q.rows(), n = d * p;
663 const std::vector<double> alpha = mam::map_pie(H.map());
664 const T zero = num_traits<T>::from_int(0);
665 // A^T with A = -(Q (x) I_p + I_d (x) D0h), so that A^T x^T = (pi0 (x) alpha)^T.
666 Matrix<T> At(n, n, zero);
667 for (std::size_t i = 0; i < d; ++i)
668 for (std::size_t k = 0; k < d; ++k) {
669 if (Q(i, k) == zero) continue;
670 for (std::size_t j = 0; j < p; ++j) At(k * p + j, i * p + j) -= Q(i, k);
671 }
672 for (std::size_t i = 0; i < d; ++i)
673 for (std::size_t j = 0; j < p; ++j)
674 for (std::size_t l = 0; l < p; ++l)
675 if (H.D0(j, l) != 0.0)
676 At(i * p + l, i * p + j) -= num_traits<T>::from_double(H.D0(j, l));
677 std::vector<T> b(n);
678 for (std::size_t i = 0; i < d; ++i)
679 for (std::size_t j = 0; j < p; ++j) b[i * p + j] = T(pi0[i] * num_traits<T>::from_double(alpha[j]));
680 const std::vector<T> x = line::solve(At, b);
681
682 std::vector<T> avg(d, zero);
683 for (std::size_t i = 0; i < d; ++i)
684 for (std::size_t j = 0; j < p; ++j) avg[i] += x[i * p + j];
685 pi_timeavg[e] = normalized(avg);
686
687 pi_exit[e].assign(E, std::vector<T>());
688 for (std::size_t h = 0; h < E; ++h) {
689 if (!envObj.arc(e, h).enabled || h >= H.Dc.size()) continue;
690 std::vector<double> rate(p, 0.0); // Dc[h] * 1
691 for (std::size_t j = 0; j < p; ++j)
692 for (std::size_t l = 0; l < H.Dc[h].cols(); ++l) rate[j] += H.Dc[h](j, l);
693 std::vector<T> ex(d, zero);
694 double mass = 0.0;
695 for (std::size_t i = 0; i < d; ++i) {
696 for (std::size_t j = 0; j < p; ++j)
697 if (rate[j] != 0.0) ex[i] += T(x[i * p + j] * num_traits<T>::from_double(rate[j]));
698 mass += num_traits<T>::to_double(ex[i]);
699 }
700 if (mass > 0.0) pi_exit[e][h] = normalized(ex);
701 }
702 }
703
704 /** `ctmc_timeaverage` at the mean holding time, gated on transcendentals. */
705 static void time_average(const std::vector<T>& pi0, const Matrix<T>& Q, double d,
706 std::vector<T>& avg, std::vector<T>& ex) {
707 if constexpr (!num_traits<T>::has_transcendental) {
708 throw UnsupportedError(ErrorKind{"Arithmetic"},
709 "SolverENV statevec: a deterministic sojourn needs ctmc_timeaverage, whose "
710 "uniformization carries Poisson weights exp(-qt) that are not rational; rerun "
711 "with --arith double");
712 } else {
713 const mc::TimeAverageResult<T> r =
714 mc::ctmc_timeaverage(pi0, Q, num_traits<T>::from_double(d));
715 avg = r.piTimeAvg;
716 ex = r.piExit;
717 }
718 }
719
720 // ---- small helpers ----------------------------------------------------
721
722 std::vector<T> reset_apply(std::size_t h, std::size_t e, const std::vector<T>& p) const {
723 if (h < opt.reset_state.size() && e < opt.reset_state[h].size() && opt.reset_state[h][e])
724 return opt.reset_state[h][e](p);
725 const ResetStateVec<T>& f = envObj.arc(h, e).reset_state;
726 if (f) return f(p);
727 return p;
728 }
729
730 /** Clamp the numerical dust below zero and renormalize to a distribution. */
731 static std::vector<T> normalized(const std::vector<T>& p) {
732 const T zero = num_traits<T>::from_int(0);
733 std::vector<T> q = p;
734 T tot = zero;
735 for (std::size_t s = 0; s < q.size(); ++s) {
736 if (num_traits<T>::to_double(q[s]) < 0) q[s] = zero;
737 tot += q[s];
738 }
739 if (num_traits<T>::to_double(tot) > 0)
740 for (std::size_t s = 0; s < q.size(); ++s) q[s] = T(q[s] / tot);
741 return q;
742 }
743
744 Environment<T>& envObj;
745 EnvStatevecOptions<T> opt;
746 std::size_t M = 0, K = 0;
747 bool det_sojourn = false;
748 std::vector<double> dvals;
749 std::vector<ctmc::CtmcSolution<T>> stages;
750 bool mam_backend = false;
751 std::vector<mam::LdqbdBlocks<T>> mam_ld;
752 std::vector<mam::LdqbdFlat<T>> mam_flat;
753 std::vector<std::vector<T>> pi_enter, pi_enter_prev, pi_timeavg;
754 std::vector<std::vector<std::vector<T>>> pi_exit; ///< pi_exit[e][h]
755};
756
757/** Solve in one call, for a caller with no use for the solver object. */
758template <class T>
762
763} // namespace env
764} // namespace line
765
766#endif // LINE_SOLVERS_ENV_SOLVER_ENV_STATEVEC_H
What a solver observed about the Cache nodes of a model.
InputError(const std::string &what)
Definition error.h:105
UnsupportedError(const std::string &what)
Definition error.h:119
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 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.
CtmcSolution< T > solver_ctmc_analyzer(const NetworkStruct< T > &sn_in, const CtmcOptions &opt, const CtmcStationaryHook< T > &stationary=CtmcStationaryHook< T >())
Port of solver_ctmc_analyzer.m plus the fork-join wrapper of @@SolverCTMC/runAnalyzer....
CtmcAvg< T > solver_ctmc_avg_from_pi(const NetworkStruct< T > &sn, const CtmcResult< T > &r, const std::vector< T > &pivec, bool stationary=true)
Port of solver_ctmc_avg_from_pi: map a state distribution to mean metrics.
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{e,h} of the reference: the state distribution of stage e at the e -> h switch,...
double tot(const std::vector< double > &pops)
LdqbdSolution< T > solver_mam_ldqbd(const qn::NetworkStruct< T > &L, const MamOptions &opt)
Port of solver_mam_ldqbd.m.
LdqbdFlat< T > solver_mam_ldqbd_flatten(const LdqbdBlocks< T > &ld)
Port of solver_mam_ldqbd_flatten.m.
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.
std::vector< T > map_pie(const Map< T > &m)
Phase distribution seen by an arriving job, pie = pi D1 / (pi D1 e).
Definition map_moment.h:89
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.
CacheMetrics< T > cache_metrics_of(const qn::NetworkStruct< T > &sn, const std::vector< T > &hitprob, const std::vector< T > &missprob, const std::vector< T > &delayedprob, const std::vector< T > &latency, const Matrix< T > &hitproblist, const Matrix< T > &itemprob, const std::vector< T > &listcost)
Assemble CacheMetrics from what a cache analyzer returned.
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
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 <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
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< std::vector< ResetStateVec< T > > > reset_state
resetStateFun[h][e], an OVERRIDE of the environment's own: a non-empty entry here is applied in place...
std::string stage_solver
Which solver runs each stage: "ctmc", the enumerated chain, or "mam", which flattens a level-dependen...
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
solvers::CacheMetrics< T > cache
aggregateCacheBlend_: the environment-blended cache surface.
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.
Every Cache node of the model, in node order; empty on a model with none.