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