LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
solver_env.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_H
6#define LINE_SOLVERS_ENV_SOLVER_ENV_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * SolverENV: a queueing network in a random environment.
12 *
13 * Port of `matlab/src/solvers/@@SolverENV/SolverENV.m` driving
14 * `solver_env_meanfield_analyzer.m`, the default (and historical) coupling.
15 *
16 * THE FIXED POINT, in one paragraph. Each stage is solved TRANSIENTLY, not in
17 * steady state, because a stage does not last long enough to reach one -- the
18 * environment switches first. What the network carries across a switch is its
19 * queue lengths, so stage e must be started from the mean queue lengths it is
20 * ENTERED with, and those are the exit queue lengths of whichever stage
21 * preceded it. That is a fixed point over the entry vectors, and the iteration
22 * below is a Picard iteration on it:
23 *
24 * Qentry[e] = sum_h probOrig(h, e) * reset_{h->e}( Qexit[h][e] )
25 *
26 * where Qexit[h][e] is the transient of stage h AVERAGED OVER WHEN the h -> e
27 * switch happens -- the increments of that transition's CDF are the weights.
28 * The environment-averaged answer at the end weights each stage's transient
29 * over its own HOLDING time CDF instead (any exit, not a particular one), and
30 * blends the stages by their stationary probabilities probEnv.
31 *
32 * WHY THE WEIGHTS ARE CDF INCREMENTS AND NOT A DENSITY. The transient comes
33 * back on a grid, so the reference integrates the metric against the measure
34 * the transition induces on that same grid: w_j = F(t_j) - F(t_{j-1}), with
35 * w_1 = 0, normalized by their sum. That is a Riemann-Stieltjes sum, and it
36 * needs no density -- which matters, because a deterministic transition has
37 * none.
38 *
39 * THE MEAN-FIELD COLLAPSE is the approximation, and it is worth naming: only
40 * the MARGINAL MEAN queue lengths cross a switch, so any correlation between
41 * stations at the moment of the switch is discarded.
42 * `solver_env_statevec_analyzer.m` carries the whole joint distribution
43 * instead; it is ported in `solver_env_statevec.h`, as a separate class with a
44 * CTMC stage solver, and `env_dispatch.h` chooses between the two the way
45 * `SolverENV.init` does. `method = "statevec"` is refused HERE by name rather
46 * than silently served by the mean-field coupling.
47 *
48 * A LAYERED STAGE IS THE SAME FIXED POINT WITH A DIFFERENT STAGE SOLVER. When
49 * a stage holds a `lqn::LqnStruct` rather than a flat network, its transient
50 * comes from a `SolverLN` over the stage's own layers instead of from one fluid
51 * integration, and the (station, class) view the coupling blends over is the
52 * BLOCK-DIAGONAL UNION of those layers -- `LayeredNetwork.layerBlocks` in the
53 * reference, `SolverLN::layer_blocks` here. Nothing else changes: the same
54 * marginal mean queue lengths cross a switch, split into per-layer blocks on
55 * the way in (`SolverLN::init_from_marginal`) and reassembled on the way out.
56 * The one thing to know about the handoff is that it must be replayed AFTER the
57 * layered fixed point and BEFORE the layer transients, because the fixed point
58 * resets its layers as it converges; `run_layer_transient` is where that
59 * happens, and a warm start installed anywhere earlier is silently inert.
60 *
61 * WHAT IS PORTED, and what is refused by name:
62 * ported `meanfield` (the default), `smp` (the mean-field coupling on the
63 * exact SEMI-MARKOV environment: arcs of any law, competing or kernel,
64 * probEnv and probOrig from the embedded jump chain and the mean
65 * holding times of Environment::init, and each exit averaged over the
66 * cumulative incidence of its own destination -- see `dest_resolved`),
67 * `statedep` (state-dependent environment rates,
68 * `resetEnvRates`), stochastic and deterministic sojourn,
69 * per-transition reset policies including the named `keep`/`clear`
70 * of a node breakdown, fluid stages, CTMC stages, and LayeredNetwork
71 * stages over fluid layers
72 * refused `statevec`/`blend` (this class is the mean-field coupling; use
73 * env::solver_env for them), `avg`/`dec` (the closed-form fast/slow
74 * limits of `solveEnvLimit`, ported as env::SolverEnvLimit and
75 * likewise reached through env::solver_env). The cache
76 * aggregation of `aggregateCacheMeanfield_` is not in this class
77 * but is ported on top of it, in solver_env_meanfield.h
78 * (`aggregate_cache_meanfield`, over `solver_fld_cacheqn_tran`).
79 */
80
81#include <algorithm>
82#include <cmath>
83#include <cstddef>
84#include <limits>
85#include <memory>
86#include <string>
87#include <vector>
88
102#include "line/util/error.h"
103#include "line/util/matrix.h"
104
105namespace line {
106namespace env {
107
108/**
109 * `LnOptions` as a LAYERED environment stage is solved with.
110 *
111 * Only the layer engine differs from the SolverLN default, and it differs
112 * because the mean-field coupling has no use for a stage it cannot integrate:
113 * see `EnvOptions::lqn`.
114 */
117 o.layer_solver = "fluid";
118 return o;
119}
120
121/** Options of SolverENV. Defaults are `Solver.defaultOptions`. */
123 int iter_max = 100;
124 double iter_tol = 1e-4;
125 /**
126 * Which solver runs each FLAT stage: `fluid` (the fluid transient), `ctmc`
127 * (the enumerated chain), `mva` or `nc`. A LAYERED stage is run by SolverLN
128 * whatever this says, and its own layer engine is named by
129 * `lqn.layer_solver`; asking for `ctmc` alongside a layered stage is refused
130 * rather than reinterpreted, since an LQN has no single generator to
131 * enumerate.
132 *
133 * `mva` and `nc` are the ensemble the reference builds with
134 * `SolverENV(env, @SolverMVA)` / `@SolverNC`. Neither has a transient, so,
135 * as `SolverENV.methodRefusal` rules, they serve the closed-form limits
136 * `avg` and `dec` (`SolverEnvLimit`, at `stage_mva` / `stage_nc`) and the
137 * mean-field family refuses them by name.
138 */
139 std::string stage_solver = "fluid";
140 /** Options of an `mva` stage solver, `SolverMVA(model, options)`. */
142 /** Options of an `nc` stage solver, `SolverNC(model, options)`. */
144 /** The inter-stage coupling: `meanfield` is the reference's default. */
145 std::string method = "meanfield";
146 /** `options.sojourn`: `stochastic` (default) or `deterministic`. */
147 std::string sojourn = "stochastic";
148 /** Options handed to each stage solver. */
150 /**
151 * `options.cutoff` of a CTMC stage, read only when `stage_solver` is ctmc.
152 * An open stage needs one; a closed one enumerates its own population.
153 */
154 double stage_cutoff = -1.0;
155 /**
156 * `options.stiff` of a CTMC stage, read only when `stage_solver` is ctmc.
157 * False integrates each stage transient with the reference's ode23 (RelTol
158 * 1e-3) instead of the stiff integrator, which moves the coupled answer.
159 */
160 bool stage_stiff = true;
161 /** `options.timespan(2)` of the inner solver: the transient horizon. */
162 double timespan_end = 100.0;
163 /**
164 * Method `occupation`: SolverENV's OWN `options.timespan`, [t0, t1]. The
165 * horizon is t1 - t0 when both are finite and unbounded otherwise, which is
166 * the default ([Inf, Inf], as `SolverOptions('ENV')` sets it). Distinct from
167 * `timespan_end`, the inner solvers' transient horizon of the couplings.
168 */
169 double env_timespan_start = std::numeric_limits<double>::infinity();
170 double env_timespan_end = std::numeric_limits<double>::infinity();
171 /**
172 * Method `occupation`: `options.config.env_init`, the initial probability
173 * of each stage. Empty means the first stage, as the reference defaults.
174 */
175 std::vector<double> env_init;
176 /**
177 * Points on a UNIFORM transient grid, used only where `stage_grid` declines
178 * to build one (a stage whose holding time is the disabled 1 x 1 zero pair).
179 *
180 * It used to be the accuracy knob of the whole method, because the exit
181 * metrics are a Riemann-Stieltjes sum over whatever grid the stage was
182 * integrated on and a uniform grid resolves the HORIZON rather than the
183 * sojourn. Since 2026-08-11 each stage is integrated on the grid the
184 * sojourn asks for -- 90% of the points under `5*E[S]` -- so the answer no
185 * longer moves with this: on renv_node_breakdown the horizon may be 100 or
186 * 1000 and Server QLen is 0.458854 or 0.459191.
187 */
188 std::size_t tran_points = 1001;
189 /**
190 * Options of the `SolverLN` that runs a LAYERED stage.
191 *
192 * The reference names the stage solver by handing SolverENV a FACTORY --
193 * `ENV(env, @(m) LN(m, @(mm) FLD(mm), 'timespan', [0 T]))` -- and this field
194 * is that factory's argument list, because a C++ template cannot take a
195 * MATLAB function handle. `timespan_end`, `tran_points` and `tran_grid` are
196 * OVERWRITTEN by the environment for every stage: the horizon and the grid
197 * the exit average is summed on belong to the coupling, not to a stage.
198 *
199 * `layer_solver` defaults to `fluid` here where `LnOptions` alone defaults
200 * to `mva`, and the difference is not a preference: the coupling carries
201 * queue lengths across a switch and therefore needs each stage's
202 * TRANSIENT, which only the fluid layer engine produces. A caller who names
203 * another engine is refused by `init`, not quietly served the fluid one.
204 */
206};
207
208/** What SolverENV reports. */
210 /** Environment-averaged metrics, (nstations x nclasses). */
212 /** Per-stage, sojourn-averaged metrics. */
213 std::vector<Matrix<double>> QExit, UExit, TExit;
214 /** The entry queue lengths the fixed point converged to. */
215 std::vector<Matrix<double>> Qentry;
216 /**
217 * `meancov` only: the environment-wide queue-length COVARIANCE over the
218 * (station, class) pairs, (M*K)-by-(M*K) and indexed `ir = r*M + i`, and its
219 * diagonal reshaped to (nstations x nclasses). Empty under every other
220 * coupling, which carries a first moment alone.
221 */
223 int iterations = 0;
224 bool converged = false;
225};
226
227namespace detail {
228
229/**
230 * `maxpe(approx, exact)`: max |1 - approx/exact| over the entries where exact
231 * is nonzero, which is what the reference's convergence test compares.
232 */
233inline double env_maxpe(const std::vector<double>& approx, const std::vector<double>& exact) {
234 double worst = -1.0;
235 for (std::size_t i = 0; i < approx.size() && i < exact.size(); ++i) {
236 if (exact[i] == 0.0) continue;
237 const double e = std::fabs(1.0 - approx[i] / exact[i]);
238 if (e > worst) worst = e;
239 }
240 return worst; // negative means "no comparable entry", the reference's empty
241}
242
243/** Linear interpolation of a transient metric at `d`, clamped to the grid. */
244inline double env_det_eval(const std::vector<double>& t, const std::vector<double>& metric,
245 double d) {
246 if (t.empty()) return 0.0;
247 d = std::max(t.front(), std::min(d, t.back()));
248 for (std::size_t j = 1; j < t.size(); ++j) {
249 if (d <= t[j]) {
250 const double dt = t[j] - t[j - 1];
251 if (!(dt > 0.0)) return metric[j];
252 const double a = (d - t[j - 1]) / dt;
253 return metric[j - 1] * (1.0 - a) + metric[j] * a;
254 }
255 }
256 return metric.back();
257}
258
259/**
260 * Time average of a transient metric over [t.front(), d], d clamped to the grid
261 * as in `env_det_eval`: the REPORTED value of a stage with a deterministic
262 * sojourn, where `env_det_eval` is the exit value the handoff reads.
263 */
264inline double env_det_avg(const std::vector<double>& t, const std::vector<double>& metric,
265 double d) {
266 if (t.empty()) return 0.0;
267 d = std::max(t.front(), std::min(d, t.back()));
268 if (!(d > t.front())) return metric.front();
269 double s = 0.0;
270 for (std::size_t j = 1; j < t.size() && t[j - 1] < d; ++j) {
271 const double hi = std::min(t[j], d);
272 const double dt = t[j] - t[j - 1];
273 const double mhi = (dt > 0.0 && hi < t[j])
274 ? metric[j - 1] + (metric[j] - metric[j - 1]) * (hi - t[j - 1]) / dt
275 : metric[j];
276 s += 0.5 * (hi - t[j - 1]) * (metric[j - 1] + mhi);
277 }
278 return s / (d - t.front());
279}
280
281} // namespace detail
282
283/**
284 * The environment solver.
285 *
286 * `envObj` must already carry a model per stage; `init()` is called here, as
287 * `SolverENV.init` does.
288 */
289template <class T>
291public:
292 SolverEnv(Environment<T>& e, const EnvOptions& o) : envObj(e), opt(o) { init(); }
293
295 const std::size_t E = envObj.nstages();
296 EnvSolution out;
297 out.QN = Matrix<double>(M, K, 0.0);
298 out.UN = Matrix<double>(M, K, 0.0);
299 out.TN = Matrix<double>(M, K, 0.0);
300
301 pre();
302 std::vector<std::vector<double>> qfirst_prev(E), qfirst_curr(E);
303 int it = 0;
304 for (it = 1; it <= opt.iter_max; ++it) {
305 for (std::size_t e = 0; e < E; ++e) analyze(e);
306 // The reference's convergence test compares the FIRST point of the
307 // transient -- the entry queue length -- across iterations.
308 qfirst_prev = qfirst_curr;
309 qfirst_curr.assign(E, std::vector<double>());
310 for (std::size_t e = 0; e < E; ++e) {
311 qfirst_curr[e].reserve(M * K);
312 for (std::size_t i = 0; i < M; ++i)
313 for (std::size_t r = 0; r < K; ++r) qfirst_curr[e].push_back(tranQ[e][i][r][0]);
314 }
315 bool conv = it > 1;
316 if (conv)
317 for (std::size_t e = 0; e < E && conv; ++e) {
318 const double d = detail::env_maxpe(qfirst_curr[e], qfirst_prev[e]);
319 if (d < 0.0) continue; // nothing comparable, treated as converged
320 if (!std::isfinite(d) || d >= opt.iter_tol) conv = false;
321 }
322 post();
323 if (conv) {
324 out.converged = true;
325 break;
326 }
327 }
328 out.iterations = std::min(it, opt.iter_max);
329 finish(out);
330 return out;
331 }
332
333private:
334 void init() {
335 // MVA and NC stages are a valid ensemble with no transient, which the
336 // reference's `methodRefusal` turns away from the mean-field family with
337 // this sentence; the closed-form limits are where they run.
338 if (opt.stage_solver == "mva" || opt.stage_solver == "nc")
339 throw UnsupportedError(ErrorKind{"Structure"}, // init's LINE:unsupported:Structure
340 "SolverENV: the mean-field environment coupling integrates each stage over its "
341 "sojourn, so it needs transient averages from the stage solver, which " +
342 std::string(opt.stage_solver == "mva" ? "SolverMVA" : "SolverNC") +
343 " (stage 1) does not produce. Use a fluid or CTMC stage solver, or method='dec' "
344 "or 'avg'.");
345 if (opt.stage_solver != "fluid" && opt.stage_solver != "ctmc")
346 throw UnsupportedError(ErrorKind{"Option"},
347 "SolverENV: stage solver '" + opt.stage_solver +
348 "' is not available; the environment coupling needs a TRANSIENT stage solve and "
349 "only the fluid analyzer and the enumerated CTMC provide one in this port");
350 ctmc_stages = (opt.stage_solver == "ctmc");
351 if (opt.method == "statevec")
352 throw UnsupportedError(ErrorKind{"Method"},
353 "SolverENV: the state-vector analyzer (solver_env_statevec_analyzer.m) carries the "
354 "full joint distribution across a switch, which THIS class does not: it is the "
355 "mean-field coupling and carries the marginal means. The state-vector coupling is "
356 "ported as env::SolverEnvStatevec, with its own options and its CTMC stage solver; "
357 "reach it through env::solver_env (env_dispatch.h), which is the analyzer "
358 "selection of SolverENV.init");
359 if (opt.method == "avg" || opt.method == "dec" || opt.method == "occupation")
360 throw UnsupportedError(ErrorKind{"Method"},
361 "SolverENV: the closed-form fast/slow environment limits (SolverENV.solveEnvLimit) "
362 "and the occupation weighting (SolverENV.solveEnvOccupation) "
363 "replace this fixed point rather than configure it -- neither carries anything "
364 "across a switch. They are ported as env::SolverEnvLimit, with their own result "
365 "type; reach them through env::solver_env (env_dispatch.h), which is the method "
366 "dispatch of SolverENV.runAnalyzer");
367 // `smp` selects no analyzer of its own: it runs the mean-field one on the
368 // semi-Markov stage probabilities Environment::init computes, and resolves
369 // each exit by destination (`dest_resolved`).
370 smp = (opt.method == "smp");
371 statedep = (opt.method == "statedep");
372 // "default" IS the reference's spelling of this coupling: SolverENV.m
373 // installs solver_env_meanfield_analyzer for every method that is not
374 // statevec, and its listValidMethods leads with 'default'. Only the CLI
375 // normalised it away, so a caller constructing SolverEnv directly with
376 // the reference's own name was refused. "blend" is a third spelling of
377 // it since 2026-09-13, when that name was repointed here from the
378 // state-vector coupling, and this whitelist is why it has to be named:
379 // falling past the statevec branch reaches the mean-field analyzer, but
380 // an unlisted name is refused before it gets there.
381 if (opt.method != "meanfield" && opt.method != "default" && opt.method != "mean"
382 && opt.method != "meancov" && opt.method != "blend" && opt.method != "blending"
383 && opt.method != "smp"
384 && !statedep)
385 throw UnsupportedError(ErrorKind{"Method"}, "SolverENV: unknown method '" + opt.method + "'");
386 // 'meancov' IS THIS COUPLING, carrying a COVARIANCE beside the mean: the
387 // propagation is the mean-field one and only the object crossing a switch
388 // is richer, so it is a flag here rather than an analyzer of its own.
389 meancov = (opt.method == "meancov");
390 // THE STAGE METHOD IS THE CALLER'S, as it is in the reference, where a
391 // stage is an ordinary SolverFluid the caller constructed: `kp` integrates
392 // the Ko-Pender fluid AND diffusion limits, and is the only route in this
393 // port that carries a second moment along a stage trajectory. Every other
394 // fluid method integrates the closing drift, which carries a first moment
395 // alone; `meancov` over such stages keeps the TIMING variance of the
396 // sojourn and the spread of the per-origin means, and nothing of the
397 // within-stage spread, exactly as the reference does for a stage solver
398 // that reports none.
399 {
400 std::string sm = opt.stage.method;
401 if (sm.size() > 4 && sm.compare(0, 4, "fld.") == 0) sm = sm.substr(4);
402 kp_stages = (!ctmc_stages && sm == "kp");
403 // `dae` is the OTHER route that carries a second moment along a stage
404 // trajectory: it integrates the linear-noise covariance beside the
405 // min-normal mean, and unlike `kp` its DRIFT reads that covariance, so
406 // a stage restarting at Sigma(0) = 0 gets the mean wrong as well as
407 // the variance. It needs a stage route of its own: `solver_fluid_transient`
408 // integrates the CLOSING drift whatever the method name says (only
409 // `solver_fluid_run_transient` dispatches, and it takes no output grid),
410 // so a `dae` stage sent there would be answered by a different method,
411 // report no covariance at all, and drop `init_qcov` in silence.
412 dae_stages = (!ctmc_stages && !kp_stages && sm == "dae");
413 }
414 // A CTMC STAGE IS NOT REFUSED under `meancov`: it takes a lattice STATE
415 // rather than a distribution, so the carried covariance simply does not
416 // seed it, which is what the reference does too. The coupling then keeps
417 // the timing variance of the sojourn and the spread of the per-origin
418 // means, and reports both.
419 if (!(opt.timespan_end > 0.0) || !std::isfinite(opt.timespan_end))
420 throw InputError(
421 "SolverENV: the stage transient needs a finite positive horizon, "
422 "options.timespan(2); the mean-field coupling integrates each stage's "
423 "TRAJECTORY against the holding-time CDF and has nothing to integrate over an "
424 "infinite one");
425 if (opt.tran_points < 2)
426 throw InputError("SolverENV: the transient grid needs at least two points");
427 if (!std::is_same<T, double>::value)
428 throw UnsupportedError(ErrorKind{"Arithmetic"},
429 "SolverENV: a fluid stage integrates its drift with LSODA, which is double only; "
430 "rerun with --arith double");
431
432 // `methodRefusal`: only 'smp' reads a stage's holding time off its arc
433 // CDFs; every other coupling needs the (D0,D1) race of its transitions.
434 envObj.require_declared();
435 envObj.refuse_semi_markov(opt.method);
436 if (smp && envObj.is_semi_markov() && opt.stage_solver == "fluid" &&
437 !envObj.has_lqn_stages()) {
438 const qn::NetworkStruct<T>& sn1 = envObj.stage(0).model;
439 for (std::size_t ind = 0; ind < sn1.nodes.size(); ++ind)
440 if (sn1.nodes[ind].nodetype == lang::NodeType::Cache)
441 throw UnsupportedError(ErrorKind{"Structure"},
442 "SolverENV: The mean-field cache fixed point integrates each stage's "
443 "holding time as a phase process inside the cache drift, which a "
444 "semi-Markov stage (a non-Markovian or kernel transition) does not have. "
445 "Fit the transitions to phase-type laws, or use a non-fluid stage solver.");
446 }
447 envObj.refuse_absorbing(opt.method);
448 envObj.init();
449 const std::size_t E = envObj.nstages();
450 build_lqn_stages();
451 for (std::size_t e = 1; e < E; ++e)
452 if (envObj.is_lqn(0) && envObj.is_lqn(e) && lnsolv[e]->nlayers() != lnsolv[0]->nlayers())
453 throw UnsupportedError(ErrorKind{"Method"},
454 "Stages 1 and " + std::to_string(e + 1) + " are layered networks whose layers "
455 "differ (a zero-capacity element removes the layers only a trapped reference task "
456 "reaches), and method '" + opt.method + "' couples the stages layer by layer. Use "
457 "method 'occupation'.");
458 M = stage_M(0);
459 K = stage_K(0);
460 for (std::size_t e = 1; e < E; ++e)
461 if (stage_M(e) != M || stage_K(e) != K)
462 throw InputError(
463 "SolverENV: every stage must have the same stations and classes; the metrics "
464 "are blended entrywise across them. A LAYERED stage counts the block-diagonal "
465 "union of the layers SolverLN builds for it, which is what layerBlocks "
466 "reports, so two layered stages agree exactly when they have the same layer "
467 "shape -- not merely the same LQN element count");
468 entry.assign(E, Matrix<double>(M, K, 0.0));
469 centry.assign(E, Matrix<double>(M * K, M * K, 0.0));
470 tranC.assign(E, std::vector<Matrix<double>>());
471 tranT.assign(E, std::vector<double>());
472 tranQ.assign(E, std::vector<std::vector<std::vector<double>>>());
473 tranU.assign(E, std::vector<std::vector<std::vector<double>>>());
474 tranTp.assign(E, std::vector<std::vector<std::vector<double>>>());
475 steady.assign(E, StageSteady());
476 steady_asked.assign(E, 0);
477 det_sojourn = (opt.sojourn == "deterministic");
478 dvals.assign(E, 0.0);
479 refresh_sojourn_means();
480 if (statedep) {
481 bool any = false;
482 for (std::size_t e = 0; e < E; ++e)
483 for (std::size_t h = 0; h < E; ++h)
484 if (envObj.arc(e, h).enabled && envObj.arc(e, h).reset_rates) any = true;
485 if (!any)
486 throw InputError(
487 "SolverENV: method 'statedep' updates each environment transition from the "
488 "state its stage is left in, and no arc carries a rate reset "
489 "(Environment::set_env_rate_reset, resetEnvRatesFun in the reference); the "
490 "run would be the mean-field fixed point under a different name");
491 }
492 }
493
494 // ---- layered (LayeredNetwork) stages ---------------------------------
495
496 /**
497 * Build one persistent `SolverLN` per LAYERED stage.
498 *
499 * ONE SOLVER FOR THE WHOLE RUN, not one per sweep, and that is the
500 * reference's arrangement too (`self.solvers{e}` outlives the iteration).
501 * It matters twice over: the layer ensemble is what carries the aggregate
502 * (station, class) SHAPE this coupling blends over, and it has to be known
503 * before any stage is solved; and the layered fixed point is solved ONCE,
504 * because a steady solve ignores the state it is started from -- only the
505 * transient reads it -- so re-running it every environment sweep would
506 * recompute the same numbers.
507 */
508 void build_lqn_stages() {
509 const std::size_t E = envObj.nstages();
510 lnsolv.assign(E, std::shared_ptr<ln::SolverLN<T>>());
511 lnblk.assign(E, ln::LnLayerBlocks());
512 if (!envObj.has_lqn_stages()) return;
513 if (ctmc_stages)
514 throw UnsupportedError(ErrorKind{"LayeredNetwork"},
515 "SolverENV: a LayeredNetwork stage is solved by SolverLN over its layers, not by "
516 "an enumerated CTMC over one stage generator -- an LQN has no single generator to "
517 "enumerate. Leave stage_solver at 'fluid', which names the engine each LAYER is "
518 "integrated with (EnvOptions::lqn.layer_solver)");
519 if (opt.lqn.layer_solver != "fluid")
520 throw UnsupportedError(ErrorKind{"LayeredNetwork"},
521 "SolverENV: a LayeredNetwork stage is carried across an environment switch by its "
522 "queue lengths, so the coupling needs the stage's TRANSIENT; among the layer "
523 "engines only the fluid one produces one, and this ensemble asks for '" +
524 opt.lqn.layer_solver + "' layers (EnvOptions::lqn.layer_solver)");
525 for (std::size_t e = 0; e < E; ++e) {
526 if (!envObj.is_lqn(e)) continue;
527 ln::LnOptions lo = opt.lqn;
528 // THE HORIZON AND THE GRID BELONG TO THE COUPLING. A stage lasts as
529 // long as the environment lets it, and the exit average is summed
530 // against the holding-time CDF, so neither is a property of the LQN
531 // and a caller's value for either would silently change what the
532 // Stieltjes sum integrates over. `tran_grid` is installed per sweep
533 // by `lqn_stage_transient`, since a state-dependent method may move
534 // the holding time between sweeps.
535 lo.timespan_end = opt.timespan_end;
536 lo.tran_points = opt.tran_points;
537 lo.tran_grid.clear();
538 lnsolv[e] = std::make_shared<ln::SolverLN<T>>(envObj.stage(e).lqn_model, lo);
539 lnblk[e] = lnsolv[e]->layer_blocks();
540 }
541 }
542
543 /** Stations of stage `e`: its own, or the block-diagonal union of its layers. */
544 std::size_t stage_M(std::size_t e) const {
545 return envObj.is_lqn(e) ? lnblk[e].M : envObj.stage(e).model.nstations;
546 }
547
548 /** Classes of stage `e`: its own, or the block-diagonal union of its layers. */
549 std::size_t stage_K(std::size_t e) const {
550 return envObj.is_lqn(e) ? lnblk[e].K : envObj.stage(e).model.nclasses;
551 }
552
553 /**
554 * One LAYERED stage's transient, assembled block-diagonally into the same
555 * `tranT`/`tranQ`/`tranU`/`tranTp` the flat path fills.
556 *
557 * `seed` says whether the fixed point has an entry vector yet, exactly as it
558 * does on the CTMC path: `pre()` runs before it has one, and warm-starting
559 * from an all-zero matrix would empty every closed layer rather than leave
560 * it on its default state.
561 *
562 * THE OFF-DIAGONAL BLOCKS ARE ZERO AND ARE ALLOCATED ANYWAY. They pair a
563 * station of one layer with a class of another and stand for nothing, which
564 * is why the reference leaves them as empty cells; here they must still be
565 * present and sized, because the convergence test reads the FIRST point of
566 * every (station, class) series and an absent series has no first point.
567 * Zero series contribute nothing to the blend and are skipped by `maxpe`,
568 * which ignores an exact value of zero -- so the two ports agree on the
569 * numbers as well as on the shape.
570 */
571 void lqn_stage_transient(std::size_t e, bool seed) {
572 ln::SolverLN<T>& s = *lnsolv[e];
573 s.init_from_marginal(seed ? entry[e] : Matrix<double>());
574 s.set_tran_grid(stage_grid(e));
575 const ln::LnTranSolution tr = s.get_tran_avg();
576 const ln::LnLayerBlocks& b = lnblk[e];
577
578 // Every layer was integrated on the same grid -- one horizon, one
579 // out_grid -- so layer one's is the stage's time base.
580 tranT[e].clear();
581 if (!tr.layers.empty()) tranT[e] = tr.layers[0].t;
582 const std::size_t P = std::max<std::size_t>(tranT[e].size(), 1);
583 tranQ[e].assign(M, std::vector<std::vector<double>>(K, std::vector<double>(P, 0.0)));
584 tranU[e].assign(M, std::vector<std::vector<double>>(K, std::vector<double>(P, 0.0)));
585 tranTp[e].assign(M, std::vector<std::vector<double>>(K, std::vector<double>(P, 0.0)));
586 if (tranT[e].empty()) return;
587
588 // `b` and the blocks were both derived from the SAME layer ensemble --
589 // it is built once, in SolverLN's constructor, and never resized -- so
590 // `msz`/`ksz` are the exact extents of each block and the offsets tile
591 // the aggregate exactly. Nothing here is a bounds guard.
592 for (std::size_t l = 0; l < tr.layers.size(); ++l) {
593 const ln::LnTranLayer& L = tr.layers[l];
594 for (std::size_t i = 0; i < b.msz[l]; ++i)
595 for (std::size_t r = 0; r < b.ksz[l]; ++r) {
596 const std::size_t row = b.roff[l] + i, col = b.coff[l] + r;
597 copy_series(L.QN[i][r], tranQ[e][row][col]);
598 copy_series(L.UN[i][r], tranU[e][row][col]);
599 copy_series(L.TN[i][r], tranTp[e][row][col]);
600 }
601 }
602 }
603
604 /**
605 * Copy a layer series onto the stage grid.
606 *
607 * The two lengths agree by construction -- every layer was integrated on the
608 * grid this stage's time base came from -- and the loop is written over
609 * whichever is shorter so that a layer whose integration was cut short
610 * leaves the tail at zero rather than reading past its own trajectory.
611 */
612 static void copy_series(const std::vector<double>& src, std::vector<double>& dst) {
613 for (std::size_t j = 0; j < dst.size() && j < src.size(); ++j) dst[j] = src[j];
614 }
615
616 /** The mean holding times the deterministic sojourn evaluates at. */
617 void refresh_sojourn_means() {
618 if (!det_sojourn) return;
619 for (std::size_t e = 0; e < envObj.nstages(); ++e)
620 dvals[e] = envObj.hold_time_mean(e);
621 }
622
623 /**
624 * `pre_`: seed every stage from its own solve at the first iteration, so
625 * the fixed point starts somewhere the model could be.
626 *
627 * Which solve is the reference's branch on the STAGE horizon: a finite one
628 * takes the LAST POINT of the stage transient, and only an infinite one --
629 * which this coupling refuses in `init`, since it has no transient to
630 * integrate -- takes the steady state. The distinction is not cosmetic on a
631 * stage that is unstable on its own -- a broken server offered more than it
632 * can serve -- where the steady state is whatever the integrator's own
633 * horizon happened to reach and is far from the transient at
634 * `timespan_end`. The seed only moves by the drift per environment cycle,
635 * so a seed off by a factor of ten costs iterations proportionally.
636 */
637 void pre() {
638 const std::size_t E = envObj.nstages();
639 for (std::size_t e = 0; e < E; ++e) {
640 if (envObj.is_lqn(e)) {
641 // The layered seed is the reference's own: the LAST POINT of the
642 // stage transient run from the layers' default state, which for
643 // a finite horizon is what `pre_` takes for every stage solver.
644 lqn_stage_transient(e, false);
645 if (tranT[e].empty()) continue;
646 const std::size_t last = tranT[e].size() - 1;
647 for (std::size_t i = 0; i < M; ++i)
648 for (std::size_t r = 0; r < K; ++r) entry[e](i, r) = tranQ[e][i][r][last];
649 continue;
650 }
651 if (ctmc_stages) {
652 // A CTMC stage has no "seed from nowhere" solve to run: it
653 // starts from the model's OWN initial state, which is what
654 // `initDefault` put there, so the first sweep enters at that
655 // state's queue lengths rather than at zero.
656 const ctmc::CtmcTransient<T> tr = ctmc_stage_transient(e, false, std::vector<double>());
657 if (tr.t.empty()) continue;
658 for (std::size_t i = 0; i < M; ++i)
659 for (std::size_t r = 0; r < K; ++r)
660 entry[e](i, r) = num_traits<T>::to_double(tr.QNt[i][r].back());
661 continue;
662 }
663 if (kp_stages) {
664 kp_stage_transient(e, false);
665 if (tranT[e].empty()) continue;
666 const std::size_t last = tranT[e].size() - 1;
667 for (std::size_t i = 0; i < M; ++i)
668 for (std::size_t r = 0; r < K; ++r) entry[e](i, r) = tranQ[e][i][r][last];
669 continue;
670 }
671 fluid::FluidOptions fo = opt.stage;
672 fo.init_sol.clear();
673 // THE SAME METHOD AS `analyze`: the entry vector this seeds the fixed
674 // point with is read off a stage trajectory, so taking it from the
675 // closing drift and then iterating with `dae` would start the loop at
676 // another method's answer.
677 const std::vector<fluid::FluidTranPoint> tr =
678 dae_stages ? fluid::solver_fluid_dae_transient(envObj.stage(e).model, fo,
679 opt.timespan_end, opt.tran_points)
680 : fluid::solver_fluid_transient(envObj.stage(e).model, fo,
681 opt.timespan_end, opt.tran_points);
682 if (tr.empty()) continue;
683 for (std::size_t i = 0; i < M; ++i)
684 for (std::size_t r = 0; r < K; ++r) entry[e](i, r) = tr.back().QN(i, r);
685 }
686 }
687
688 /** `analyze_`: the transient of one stage from its entry queue lengths. */
689 void analyze(std::size_t e) {
690 if (envObj.is_lqn(e)) {
691 lqn_stage_transient(e, true);
692 return;
693 }
694 tranT[e].clear();
695 tranC[e].clear();
696 tranQ[e].assign(M, std::vector<std::vector<double>>(K));
697 tranU[e].assign(M, std::vector<std::vector<double>>(K));
698 tranTp[e].assign(M, std::vector<std::vector<double>>(K));
699 if (ctmc_stages) {
700 // THE REFINED GRID, and it was MEASURED against the alternative.
701 // The reference forms its Stieltjes sum on whatever points ode23
702 // stopped at, so reporting on those looks like the faithful choice;
703 // on renv_threestages_repairmen it is the worse one -- Queue1 QLen
704 // 0.8344 against the reference's 0.83053, where the refined grid
705 // gives 0.83092. The refined grid puts 90% of its points under
706 // 5*E[S], which is where the holding-time CDF puts its mass, so it
707 // resolves the integrand rather than the trajectory. The residual
708 // 4.7e-4 is what is left of this quadrature difference.
709 const ctmc::CtmcTransient<T> tr = ctmc_stage_transient(e, true, stage_grid(e));
710 for (std::size_t j = 0; j < tr.t.size(); ++j) {
711 tranT[e].push_back(num_traits<T>::to_double(tr.t[j]));
712 for (std::size_t i = 0; i < M; ++i)
713 for (std::size_t r = 0; r < K; ++r) {
714 tranQ[e][i][r].push_back(num_traits<T>::to_double(tr.QNt[i][r][j]));
715 tranU[e][i][r].push_back(num_traits<T>::to_double(tr.UNt[i][r][j]));
716 tranTp[e][i][r].push_back(num_traits<T>::to_double(tr.TNt[i][r][j]));
717 }
718 }
719 return;
720 }
721 const qn::NetworkStruct<T>& sn = envObj.stage(e).model;
722 if (kp_stages) {
723 kp_stage_transient(e, true);
724 return;
725 }
726 fluid::FluidOptions fo = opt.stage;
727 fo.init_sol = initsol_from_marginal(sn, entry[e]);
728 // A `dae` stage takes the entry covariance as well as the entry mean, and
729 // gives its own back. Only that method reads `init_qcov`: offering it to a
730 // closing stage would be dropped in silence, which is the failure this
731 // predicate exists to avoid.
732 if (meancov && dae_stages) fo.init_qcov = centry[e];
733 const std::vector<fluid::FluidTranPoint> tr =
734 dae_stages ? fluid::solver_fluid_dae_transient(sn, fo, opt.timespan_end,
735 opt.tran_points, stage_grid(e))
736 : fluid::solver_fluid_transient(sn, fo, opt.timespan_end,
737 opt.tran_points, stage_grid(e));
738 for (const fluid::FluidTranPoint& p : tr) {
739 tranT[e].push_back(p.t);
740 for (std::size_t i = 0; i < M; ++i)
741 for (std::size_t r = 0; r < K; ++r) {
742 tranQ[e][i][r].push_back(p.QN(i, r));
743 tranU[e][i][r].push_back(p.UN(i, r));
744 tranTp[e][i][r].push_back(p.TN(i, r));
745 }
746 if (meancov && dae_stages && p.QCov.rows() == M * K) tranC[e].push_back(p.QCov);
747 }
748 // ALL OR NOTHING: `exit_cov` reads tranC[e] only when it has one matrix per
749 // point, so a run where some points carried a covariance and others did not
750 // must contribute none rather than a ragged series.
751 if (tranC[e].size() != tranT[e].size()) tranC[e].clear();
752 }
753
754 /**
755 * One stage's transient under the KO-PENDER limits, mean AND covariance.
756 *
757 * THE ONLY STAGE ROUTE THAT CARRIES A SECOND MOMENT in this port: the
758 * closing drift integrates a first moment alone, so a `meancov` run over
759 * closing stages keeps the TIMING variance of the sojourn and nothing of the
760 * within-stage spread. `kp` integrates both on one grid, which is why the
761 * covariance is read off the same solve as the mean rather than asked for
762 * again. Selected by `EnvOptions::stage.method`, so a caller asks for the
763 * limit by name exactly as a standalone fluid solve does.
764 *
765 * `seed` says whether the fixed point has an entry vector yet, as on the
766 * layered and CTMC paths: `pre()` runs before it has one, and seeding from
767 * an all-zero mean and covariance would start every stage empty rather than
768 * at this method's own stationary arrival phase.
769 */
770 void kp_stage_transient(std::size_t e, bool seed) {
771 tranT[e].clear();
772 tranC[e].clear();
773 const qn::NetworkStruct<T>& sn = envObj.stage(e).model;
774 fluid::FluidOptions fo = opt.stage;
775 fo.method = "kp";
776 fo.init_sol.clear();
777 fo.timespan_end = opt.timespan_end;
778 if (seed) {
779 fo.init_qlen = entry[e];
780 if (meancov) fo.init_qcov = centry[e];
781 }
782 fluid::FluidKpTransient tr;
783 fluid::solver_fluid_kp_core(sn, fo, &tr, stage_grid(e));
784 tranT[e] = tr.t;
785 const std::size_t P = tr.t.size();
786 tranQ[e].assign(M, std::vector<std::vector<double>>(K, std::vector<double>(P, 0.0)));
787 tranU[e].assign(M, std::vector<std::vector<double>>(K, std::vector<double>(P, 0.0)));
788 tranTp[e].assign(M, std::vector<std::vector<double>>(K, std::vector<double>(P, 0.0)));
789 // Mean and covariance come off the SAME integration, on the same grid, so
790 // the two moments this coupling carries need no interpolation onto one
791 // another and the covariance costs nothing beyond the aggregation.
792 for (std::size_t n = 0; n < P; ++n)
793 for (std::size_t i = 0; i < M; ++i)
794 for (std::size_t r = 0; r < K; ++r) {
795 tranQ[e][i][r][n] = tr.QN[n](i, r);
796 tranU[e][i][r][n] = tr.UN[n](i, r);
797 tranTp[e][i][r][n] = tr.TN[n](i, r);
798 }
799 if (meancov) tranC[e] = tr.QCov;
800 }
801
802 /**
803 * One stage's transient under an ENUMERATED CTMC, from its entry marginal.
804 *
805 * THE MARGINAL IS ROUNDED HERE and is not for a fluid stage, which is the
806 * reference's own split (`roundMarginalForDiscreteSolver` runs for every
807 * stage solver except SolverFluid): a chain has no state holding 1.7 jobs,
808 * so the fixed point's continuous iterate has to be placed on the lattice
809 * before it can be a state at all. The rounding conserves each closed
810 * class's population, so the placed state is one the chain actually
811 * contains.
812 *
813 * The state is written onto a COPY of the stage struct as its one-row
814 * declared state space, which is the same channel `setState` reaches
815 * `solver_ctmc_transient_analyzer` through -- so this seeds the stage
816 * exactly as a caller would, rather than through a private door.
817 */
818 ctmc::CtmcTransient<T> ctmc_stage_transient(std::size_t e, bool seed,
819 const std::vector<double>& grid) const {
820 qn::NetworkStruct<T> sn = envObj.stage(e).model;
821 // `seed` is explicit and not inferred from the arguments: `pre()` runs
822 // BEFORE the fixed point has an entry vector, and its all-zero matrix
823 // would place every job nowhere -- a state the chain does not have.
824 if (seed) seed_ctmc_state(sn, entry[e]);
825 std::vector<T> g;
826 g.reserve(grid.size());
827 for (std::size_t j = 0; j < grid.size(); ++j) g.push_back(num_traits<T>::from_double(grid[j]));
829 sn, ctmc_stage_options(), num_traits<T>::from_int(0),
830 num_traits<T>::from_double(opt.timespan_end), g);
831 }
832
833 /** The CTMC options a stage is solved with; the cutoff is the caller's. */
834 ctmc::CtmcOptions ctmc_stage_options() const {
835 ctmc::CtmcOptions co;
836 co.cutoff = opt.stage_cutoff;
837 co.stiff = opt.stage_stiff;
838 return co;
839 }
840
841 /**
842 * Write the rounded entry marginal onto `sn` as its declared state.
843 *
844 * A row that the encoding cannot realize leaves the station alone, so the
845 * analyzer falls back to that station's default marking rather than being
846 * handed a state the chain does not contain -- an error the coupling could
847 * not act on, where the default is at least a state of the same model.
848 */
849 void seed_ctmc_state(qn::NetworkStruct<T>& sn, const Matrix<double>& Q) const {
850 if (Q.empty()) return;
851 const std::vector<std::vector<std::size_t>> nir = round_marginal(sn, Q);
852 for (std::size_t i = 0; i < sn.nstations && i < nir.size(); ++i) {
853 const std::size_t ind = sn.station_to_node[i]; // 1-based node index
854 // A SOURCE'S STATE IS NOT A FUNCTION OF ITS QUEUE LENGTH: `State.fromMarginal`'s EXT
855 // branch ignores n and seeds every generated class in phase one, which is the default
856 // row. Built from the zero marginal it is all-zero, a state the chain does not contain.
857 if (sn.stations[i].nodetype == lang::NodeType::Source) continue;
858 std::vector<std::size_t> ph(sn.nclasses, 1);
859 for (std::size_t r = 0; r < sn.nclasses; ++r) ph[r] = sn.phasessz_of(i + 1, r + 1);
860 std::vector<T> row;
861 if (!qn::from_marginal_node_first(sn, ind, nir[i], ph, row))
862 continue;
863 Matrix<T> space(1, row.size());
864 for (std::size_t c = 0; c < row.size(); ++c) space(0, c) = row[c];
865 sn.statespace[ind] = space;
866 sn.stateprior[ind] = std::vector<T>(1, num_traits<T>::from_int(1));
867 }
868 }
869
870 /**
871 * `roundMarginalForDiscreteSolver`: the continuous per-class marginal on the
872 * integer lattice, conserving each CLOSED class's population.
873 *
874 * Rounding entrywise does not conserve it -- three stations holding 0.5 jobs
875 * of a one-job class round to 0, 0, 0 and the class disappears from the
876 * chain -- so the residual is handed to the stations with the largest
877 * fractional parts, which is the reference's own rule.
878 */
879 std::vector<std::vector<std::size_t>> round_marginal(const qn::NetworkStruct<T>& sn,
880 const Matrix<double>& Q) const {
881 std::vector<std::vector<std::size_t>> n(sn.nstations, std::vector<std::size_t>(sn.nclasses, 0));
882 for (std::size_t r = 0; r < sn.nclasses; ++r) {
883 const double pop = sn.classes[r].population;
884 std::vector<double> frac(sn.nstations, 0.0);
885 long placed = 0;
886 for (std::size_t i = 0; i < sn.nstations; ++i) {
887 const double q = (i < Q.rows() && r < Q.cols()) ? std::max(0.0, Q(i, r)) : 0.0;
888 const double fl = std::floor(q);
889 n[i][r] = static_cast<std::size_t>(fl);
890 frac[i] = q - fl;
891 placed += static_cast<long>(fl);
892 }
893 if (!std::isfinite(pop)) continue; // an open class has no population to conserve
894 long want = static_cast<long>(std::llround(pop));
895 while (placed < want) {
896 std::size_t best = 0;
897 double bv = -1.0;
898 for (std::size_t i = 0; i < sn.nstations; ++i)
899 if (frac[i] > bv) { bv = frac[i]; best = i; }
900 ++n[best][r];
901 frac[best] = -1.0;
902 ++placed;
903 if (bv < 0.0) break; // nowhere left to place; the loop would not terminate
904 }
905 while (placed > want) {
906 std::size_t best = 0;
907 double bv = 2.0;
908 bool any = false;
909 for (std::size_t i = 0; i < sn.nstations; ++i)
910 if (n[i][r] > 0 && frac[i] < bv) { bv = frac[i]; best = i; any = true; }
911 if (!any) break;
912 --n[best][r];
913 frac[best] = 2.0;
914 --placed;
915 }
916 }
917 return n;
918 }
919
920 /** One stage's steady tables, in the (station, class) space of the blend. */
921 struct StageSteady {
922 Matrix<double> QN, UN, TN;
923 };
924
925 /**
926 * The stage's own STEADY tables, which are the exit value of every metric
927 * its transient carries no trajectory for.
928 *
929 * A METRIC WITH NO TRAJECTORY IS NOT A METRIC WORTH ZERO. A stage solver
930 * advances the quantities its integration actually carries; what it leaves
931 * out it holds CONSTANT over the stage, so the value at the exit instant is
932 * that constant whatever the sojourn was. `post()` and `finish()` used to
933 * skip such a stage outright and blend the zeros, reporting a stage whose
934 * metrics never move as ABSENT rather than as constant. That is the defect
935 * `stageSteady_` closes in the reference (`solver_env_meanfield_analyzer.m`)
936 * and `stageSteady`/`_stage_steady` close in the JAR and native python.
937 *
938 * THE HORIZON IS PUT ASIDE FOR THE ASK, and here it is not a refusal to
939 * dodge but a DIFFERENT ANSWER to avoid. The reference's `getAvg` rejects a
940 * finite `options.timespan` by name; `solver_fluid` instead ACCEPTS one and
941 * quietly stops its window iteration there, disarming both the fixed-point
942 * and the geometric-tail tests. Asked with the stage horizon still on the
943 * options it would hand back the state at `t = timespan_end` -- the very
944 * transient this seed exists to complement -- instead of the constant.
945 *
946 * THE ASK GOES TO THE ENGINE THAT PRODUCED THE TRAJECTORY, branch for branch
947 * with `analyze`: the closing drift's own fixed point for a closing stage
948 * (`solver_fluid_transient` integrates that drift whatever the method name
949 * says), `kp` and `dae` through their own steady entries, and the enumerated
950 * chain's stationary law for a CTMC stage. A seed taken from another closure
951 * would not be the constant the trajectory holds.
952 *
953 * A LAYERED STAGE IS NOT ASKED, exactly as the JAR's `stageSteadyAsk`
954 * refuses a non-`Network` stage by name: `SolverLN`'s steady table is over
955 * the LQN's OWN nodes -- hosts, tasks, entries, activities -- and not over
956 * the block-diagonal (station, class) aggregate this coupling blends in, so
957 * a leading-block copy would read LQN node k as class k. Its transient is
958 * already assembled in the right layout by `lqn_stage_transient`, and every
959 * cell it owns carries one.
960 *
961 * ASKED ONCE PER STAGE, AND ONLY WHERE IT IS READ. The stage networks do not
962 * change across sweeps -- `statedep` rewrites the environment arcs, not the
963 * models -- so the constants are the same every time; and a stage whose
964 * trajectory IS readable has every cell of the seed overwritten from it, so
965 * asking then would cost a steady solve per sweep to be discarded. That is
966 * this port's form of the reference's "read `result` first".
967 */
968 const StageSteady& stage_steady(std::size_t e) {
969 if (steady_asked[e]) return steady[e];
970 steady_asked[e] = 1;
971 StageSteady& out = steady[e];
972 out.QN = Matrix<double>(M, K, 0.0);
973 out.UN = Matrix<double>(M, K, 0.0);
974 out.TN = Matrix<double>(M, K, 0.0);
975 if (envObj.is_lqn(e)) return out;
976 const qn::NetworkStruct<T>& sn = envObj.stage(e).model;
977 if (ctmc_stages) {
978 const ctmc::CtmcAvg<T> a = ctmc::solver_ctmc_analyzer(sn, ctmc_stage_options()).avg;
979 copy_finite(a.QN, out.QN);
980 copy_finite(a.UN, out.UN);
981 copy_finite(a.TN, out.TN);
982 return out;
983 }
984 fluid::FluidOptions fo = opt.stage;
985 // NOTHING CARRIED IN: the constant is what the stage holds on its own,
986 // and the entry vector the handoff computes is the transient's business.
987 fo.init_sol.clear();
988 fo.init_qlen = Matrix<double>();
989 fo.init_qcov = Matrix<double>();
990 fo.timespan_end = std::numeric_limits<double>::infinity();
991 fluid::FluidSolution s;
992 if (kp_stages) {
993 fo.method = "kp";
994 s = fluid::solver_fluid_kp<T>(sn, fo);
995 } else if (dae_stages) {
996 fo.method = "dae";
997 s = fluid::solver_fluid_dae<T>(sn, fo);
998 } else {
999 fo.method = "closing";
1000 s = fluid::solver_fluid<T>(sn, fo);
1001 }
1002 copy_finite(s.QN, out.QN);
1003 copy_finite(s.UN, out.UN);
1004 copy_finite(s.TN, out.TN);
1005 return out;
1006 }
1007
1008 /**
1009 * Copy `src` onto `dst`, leaving every non-finite entry at zero: a NaN is
1010 * ABSENT, not a number, and must not enter the probEnv blend.
1011 *
1012 * The two shapes agree by construction -- `init` refuses an environment
1013 * whose stages differ in stations or classes, and a flat stage's own tables
1014 * are (nstations, nclasses) -- so this is a copy and not a fit.
1015 */
1016 template <class S>
1017 static void copy_finite(const Matrix<S>& src, Matrix<double>& dst) {
1018 for (std::size_t i = 0; i < dst.rows(); ++i)
1019 for (std::size_t r = 0; r < dst.cols(); ++r) {
1020 const double v = num_traits<S>::to_double(src(i, r));
1021 if (std::isfinite(v)) dst(i, r) = v;
1022 }
1023 }
1024
1025 /**
1026 * The exit tables of stage `e`: its transient averaged over the sojourn on
1027 * the cells that carry one, and its steady constants on the cells that do
1028 * not. `want_all` asks for U and T beside Q, which only a state-dependent
1029 * rate reads in `post()` and which `finish()` always reports.
1030 *
1031 * THE WEIGHT IS THE STAGE SOJOURN, NOT THE e -> h CLOCK, and the reference
1032 * says so where it builds it: competing exponentials leave the exit TIME
1033 * independent of which destination won, so the exit average does not depend
1034 * on h at all -- h enters only through the reset applied on the way in.
1035 * Weighting by `proc[e][h]` instead read the transient over the mean of ONE
1036 * risk rather than of their minimum: on renv_twostages_repairmen, whose
1037 * Stage2 competes a 0.5 self arc with a 0.5 arc back, that is a mean of 2
1038 * against the sojourn's 1, and it reported Queue1 QLen 0.55882 against
1039 * MATLAB's 0.55550 with the two stations' throughputs 1.4% apart in a closed
1040 * cycle that admits one throughput.
1041 *
1042 * A TRAJECTORY THE COUPLING CANNOT AVERAGE IS NOT AN ANSWER OF ZERO. Two
1043 * cases reach `stage_steady` rather than a blend: a stage that reported no
1044 * transient at all, and one whose sojourn puts NO MASS on the grid, which is
1045 * this port's form of the reference's single-point transient (`tR = 1`, the
1046 * table `cdf_weights` can form no increment over). Both mean the same thing
1047 * -- nothing moved that the exit instant could be read off -- and the stage's
1048 * own constant is the exit value in both.
1049 */
1050 void stage_exit(std::size_t e, bool want_all, Matrix<double>& Qe, Matrix<double>& Ue,
1051 Matrix<double>& Te, bool report = false) {
1052 std::vector<double> w;
1053 double wsum = 0.0;
1054 if (!tranT[e].empty() && !det_sojourn) {
1055 w = cdf_weights(e, tranT[e]);
1056 for (double v : w) wsum += v;
1057 if (report && wsum > 0.0) {
1058 // finish() REPORTS the time average over the sojourn, not the
1059 // exit value post() hands on; see `sojourn_avg_weights`.
1060 w = sojourn_avg_weights(e, tranT[e]);
1061 wsum = 0.0;
1062 for (double v : w) wsum += v;
1063 }
1064 }
1065 if (tranT[e].empty() || (!det_sojourn && !(wsum > 0.0))) {
1066 const StageSteady& st = stage_steady(e);
1067 Qe = st.QN;
1068 if (want_all) {
1069 Ue = st.UN;
1070 Te = st.TN;
1071 }
1072 return;
1073 }
1074 for (std::size_t i = 0; i < M; ++i)
1075 for (std::size_t r = 0; r < K; ++r) {
1076 if (det_sojourn) {
1077 // Deterministic sojourn: the exit metrics are the transient
1078 // read at t = d_e, the reported ones its average over [0,d_e].
1079 if (report) {
1080 Qe(i, r) = detail::env_det_avg(tranT[e], tranQ[e][i][r], dvals[e]);
1081 if (!want_all) continue;
1082 Ue(i, r) = detail::env_det_avg(tranT[e], tranU[e][i][r], dvals[e]);
1083 Te(i, r) = detail::env_det_avg(tranT[e], tranTp[e][i][r], dvals[e]);
1084 continue;
1085 }
1086 Qe(i, r) = detail::env_det_eval(tranT[e], tranQ[e][i][r], dvals[e]);
1087 if (!want_all) continue;
1088 Ue(i, r) = detail::env_det_eval(tranT[e], tranU[e][i][r], dvals[e]);
1089 Te(i, r) = detail::env_det_eval(tranT[e], tranTp[e][i][r], dvals[e]);
1090 continue;
1091 }
1092 Qe(i, r) = weighted(tranQ[e][i][r], w, wsum);
1093 if (!want_all) continue;
1094 Ue(i, r) = weighted(tranU[e][i][r], w, wsum);
1095 Te(i, r) = weighted(tranTp[e][i][r], w, wsum);
1096 }
1097 }
1098
1099 /**
1100 * `post_`: average each stage's transient over WHEN it hands over to each
1101 * destination, then re-seed every stage from its predecessors.
1102 */
1103 void post() {
1104 const std::size_t E = envObj.nstages();
1105 std::vector<std::vector<Matrix<double>>> Qexit(
1106 E, std::vector<Matrix<double>>(E, Matrix<double>(M, K, 0.0)));
1107 // The other two exit metrics are read only by a state-dependent rate,
1108 // which is given all three; without one they are never looked at, and
1109 // the reference computes them in the same loop regardless.
1110 std::vector<std::vector<Matrix<double>>> Uexit, Texit;
1111 if (statedep) {
1112 Uexit.assign(E, std::vector<Matrix<double>>(E, Matrix<double>(M, K, 0.0)));
1113 Texit.assign(E, std::vector<Matrix<double>>(E, Matrix<double>(M, K, 0.0)));
1114 }
1115 for (std::size_t e = 0; e < E; ++e) {
1116 // Seeded with the stage's own steady state rather than skipped: a
1117 // metric its transient carries no trajectory for is one it holds
1118 // CONSTANT, and calling that zero is what reported an open cache
1119 // model's Q, U and T as identically zero. see `stage_steady`
1120 Matrix<double> Qd(M, K, 0.0), Ud(M, K, 0.0), Td(M, K, 0.0);
1121 stage_exit(e, statedep, Qd, Ud, Td);
1122 for (std::size_t h = 0; h < E; ++h) {
1123 Qexit[e][h] = Qd;
1124 if (!statedep) continue;
1125 Uexit[e][h] = Ud;
1126 Texit[e][h] = Td;
1127 }
1128 if (dest_resolved(e)) exit_by_destination(e, Qexit, Uexit, Texit);
1129 }
1130
1131 // 'meancov' carries a COVARIANCE beside the mean, and it is taken over the
1132 // same sojourn weights the exit mean uses -- independent of the
1133 // destination, exactly as Qexit is, since competing exponentials leave the
1134 // exit time independent of where the switch goes.
1135 const std::size_t n2 = M * K;
1136 std::vector<Matrix<double>> Cexit;
1137 if (meancov) {
1138 Cexit.assign(E, Matrix<double>(n2, n2, 0.0));
1139 for (std::size_t e = 0; e < E; ++e)
1140 if (!tranT[e].empty()) Cexit[e] = stage_exit_cov(e);
1141 }
1142
1143 for (std::size_t e = 0; e < E; ++e) {
1144 if (tranT[e].empty()) continue;
1145 Matrix<double> Qe(M, K, 0.0);
1146 std::vector<double> ment(meancov ? n2 : 0, 0.0);
1147 Matrix<double> sent(meancov ? n2 : 0, meancov ? n2 : 0, 0.0);
1148 for (std::size_t h = 0; h < E; ++h) {
1149 const double p = envObj.prob_orig(h, e);
1150 if (!(p > 0.0)) continue;
1151 const ResetMarginal& f = envObj.arc(h, e).reset;
1152 const Matrix<double> reset = f ? f(Qexit[h][e]) : Qexit[h][e];
1153 if (reset.rows() != M || reset.cols() != K)
1154 throw InputError(
1155 "SolverENV: a reset policy returned a matrix of the wrong shape");
1156 for (std::size_t i = 0; i < M; ++i)
1157 for (std::size_t r = 0; r < K; ++r) Qe(i, r) += p * reset(i, r);
1158 if (!meancov) continue;
1159 // The reset is an arbitrary map on the means, so the covariance
1160 // crosses it by the delta method. The MIXTURE over origins is then
1161 // taken on the SECOND MOMENT, not on the covariances: a convex
1162 // combination of the C_h alone drops the spread of the per-origin
1163 // means, which is most of the variance when the stages differ.
1164 const Matrix<double> R = reset_jacobian(f, Qexit[h][e]);
1165 const Matrix<double> Ch = congruence(R, Cexit[h]);
1166 for (std::size_t a = 0; a < n2; ++a) {
1167 const double ma = reset(a % M, a / M);
1168 ment[a] += p * ma;
1169 for (std::size_t b = 0; b < n2; ++b)
1170 sent(a, b) += p * (Ch(a, b) + ma * reset(b % M, b / M));
1171 }
1172 }
1173 entry[e] = Qe;
1174 if (!meancov) continue;
1175 Matrix<double> Ce(n2, n2, 0.0);
1176 for (std::size_t a = 0; a < n2; ++a)
1177 for (std::size_t b = 0; b < n2; ++b)
1178 Ce(a, b) = 0.5 * ((sent(a, b) - ment[a] * ment[b]) +
1179 (sent(b, a) - ment[b] * ment[a]));
1180 centry[e] = Ce;
1181 }
1182
1183 // The state-dependent rates come AFTER the entry update, as they do in
1184 // the reference: the entries just computed used the probOrig of the
1185 // environment as it was during this iteration, and rewriting the arcs
1186 // first would blend them with weights from an environment the stage
1187 // transients were never solved under.
1188 if (!statedep) return;
1189 bool touched = false;
1190 for (std::size_t e = 0; e < E; ++e)
1191 for (std::size_t h = 0; h < E; ++h) {
1192 const EnvArc<T>& a = envObj.arc(e, h);
1193 if (!a.enabled || !a.reset_rates) continue;
1194 envObj.set_transition_dist(e, h,
1195 a.reset_rates(a.dist, Qexit[e][h], Uexit[e][h],
1196 Texit[e][h]));
1197 touched = true;
1198 }
1199 if (!touched) return;
1200 // Everything the analyzer integrates against -- the marked transition
1201 // processes, the superposed holding times, probEnv and probOrig -- is
1202 // derived from the arc distributions, so the environment is rebuilt
1203 // whole rather than patched.
1204 envObj.init();
1205 refresh_sojourn_means();
1206 }
1207
1208 /**
1209 * `finish_`: average each stage over its own holding time and blend the
1210 * stages by their stationary probabilities.
1211 */
1212 void finish(EnvSolution& out) {
1213 const std::size_t E = envObj.nstages();
1214 out.QExit.assign(E, Matrix<double>(M, K, 0.0));
1215 out.UExit.assign(E, Matrix<double>(M, K, 0.0));
1216 out.TExit.assign(E, Matrix<double>(M, K, 0.0));
1217 for (std::size_t e = 0; e < E; ++e)
1218 // Seeded with the stage's own steady state rather than skipped, for
1219 // the reason `post()` is: a metric with no trajectory is a constant
1220 // and not a zero, and here the zeros would be what the run REPORTS.
1221 // see `stage_steady`
1222 stage_exit(e, true, out.QExit[e], out.UExit[e], out.TExit[e], true);
1223 for (std::size_t e = 0; e < E; ++e) {
1224 const double p = envObj.prob_env[e];
1225 for (std::size_t i = 0; i < M; ++i)
1226 for (std::size_t r = 0; r < K; ++r) {
1227 out.QN(i, r) += p * out.QExit[e](i, r);
1228 out.UN(i, r) += p * out.UExit[e](i, r);
1229 out.TN(i, r) += p * out.TExit[e](i, r);
1230 }
1231 }
1232 out.Qentry = entry;
1233 if (!meancov) return;
1234 // 'meancov' also REPORTS the second moment, mixed over the stages by the
1235 // same law of total variance the handoff uses. The term
1236 // sum_e p_e (m_e - m)(m_e - m)' is what the environment itself
1237 // contributes: two stages with identical within-stage variance but
1238 // different means still leave the queue length varying, and averaging the
1239 // per-stage covariances alone would report none of it.
1240 const std::size_t n = M * K;
1241 std::vector<double> mval(n, 0.0);
1242 Matrix<double> sval(n, n, 0.0);
1243 for (std::size_t e = 0; e < E; ++e) {
1244 const double p = envObj.prob_env[e];
1245 if (!(p > 0.0) || tranT[e].empty()) continue;
1246 const Matrix<double> Ce = stage_exit_cov(e);
1247 for (std::size_t a = 0; a < n; ++a) {
1248 const double ma = out.QExit[e](a % M, a / M);
1249 mval[a] += p * ma;
1250 for (std::size_t b = 0; b < n; ++b)
1251 sval(a, b) += p * (Ce(a, b) + ma * out.QExit[e](b % M, b / M));
1252 }
1253 }
1254 out.QCov = Matrix<double>(n, n, 0.0);
1255 out.QVar = Matrix<double>(M, K, 0.0);
1256 for (std::size_t a = 0; a < n; ++a) {
1257 for (std::size_t b = 0; b < n; ++b)
1258 out.QCov(a, b) = 0.5 * ((sval(a, b) - mval[a] * mval[b]) +
1259 (sval(b, a) - mval[b] * mval[a]));
1260 out.QVar(a % M, a / M) = std::max(0.0, out.QCov(a, a));
1261 }
1262 }
1263
1264 /**
1265 * The grid an exit average is summed on, refined where the SOJOURN WEIGHT
1266 * CANNOT SEE the integrator's own grid.
1267 *
1268 * The exit metric is `sum_k m(t_k) * [F(t_k) - F(t_{k-1})]` over the ODE
1269 * solver's OUTPUT grid, and that grid is chosen for the horizon rather than
1270 * for the sojourn: a stage integrated over [0,1e3] and read through an
1271 * Exp(1) clock puts almost every point where the weight is zero, so the
1272 * answer becomes an artifact of step placement.
1273 *
1274 * The grid is rebuilt UNCONDITIONALLY -- 90% of the points under `5*E[S]`
1275 * and the rest across the tail -- rather than only when the solver's own
1276 * grid looks too coarse. A "50 points inside the support is enough" escape
1277 * (native python's, before this) stops wherever the integrator's steps
1278 * happened to fall and does not converge: on renv_node_breakdown the sum
1279 * runs 0.462260, 0.460580, 0.459704, 0.459272, 0.459138, 0.459122 as the
1280 * point count goes 500 to 5e4, and this engine on a 1e5-point uniform grid
1281 * answers 0.459171. Rebuilding always is also what makes the four codebases
1282 * sum the SAME points, which is the property parity needs.
1283 */
1284 static constexpr std::size_t kCdfInterp = 5000;
1285
1286 static std::vector<double> refine_grid(double mean_hold, bool disabled,
1287 const std::vector<double>& t) {
1288 if (t.size() < 2) return t;
1289 // A DISABLED ARC is the 1 x 1 zero pair, and `map_mean` refuses it by
1290 // name ("zero arrival rate") rather than returning an infinity. Its
1291 // weights are identically zero, so the grid it would be summed on
1292 // cannot matter; leave it alone, exactly as cdf_weights does.
1293 if (disabled) return t;
1294 const double t0 = t.front();
1295 const double tend = t.back();
1296 double mean_sojourn = mean_hold;
1297 if (!(mean_sojourn > 0.0) || !std::isfinite(mean_sojourn))
1298 mean_sojourn = (tend - t0) / 10.0;
1299 double tcdf = std::min(tend, 5.0 * mean_sojourn);
1300 if (tcdf <= t0) tcdf = tend;
1301 const std::size_t ndense = static_cast<std::size_t>(0.9 * kCdfInterp);
1302 const std::size_t ntail = kCdfInterp - ndense;
1303 const bool with_tail = tcdf < tend && ntail > 1;
1304 std::vector<double> fine;
1305 fine.reserve(with_tail ? ndense + ntail : ndense);
1306 for (std::size_t k = 0; k < ndense; ++k)
1307 fine.push_back(t0 + (tcdf - t0) * static_cast<double>(k) /
1308 static_cast<double>(ndense - 1));
1309 if (with_tail)
1310 for (std::size_t k = 1; k <= ntail; ++k)
1311 fine.push_back(tcdf + (tend - tcdf) * static_cast<double>(k) /
1312 static_cast<double>(ntail));
1313 return fine;
1314 }
1315
1316 /**
1317 * The OUTPUT GRID stage `e` is integrated on: the refined one, so the exit
1318 * average is summed over points the trajectory was actually evaluated at.
1319 *
1320 * Interpolating instead cannot recover resolution the trajectory never had
1321 * -- over [0,1e3] a uniform 1001-point grid carries SIX samples below
1322 * `5*E[S]` for an `Exp(1)` sojourn, and a piecewise-linear reading of six
1323 * samples is still six samples' worth of information; it reported a
1324 * throughput of 0.8099 for a source admitting 0.8. LSODA takes an arbitrary
1325 * increasing output vector, so the points are simply asked for.
1326 *
1327 * The scale is the HOLDING time, which is the sojourn regardless of which
1328 * destination fires (competing exponentials), so one grid serves post()'s
1329 * per-destination weights and finish()'s holding-time ones alike.
1330 */
1331 std::vector<double> stage_grid(std::size_t e) const {
1332 std::vector<double> ends(2);
1333 ends[0] = 0.0;
1334 ends[1] = opt.timespan_end;
1335 const std::vector<double> g =
1336 refine_grid(hold_disabled(e) ? 0.0 : envObj.hold_time_mean(e), hold_disabled(e), ends);
1337 // A disabled holding time leaves `refine_grid` with nothing to say; fall
1338 // back to the uniform grid the option asks for.
1339 if (g.size() < 3) return std::vector<double>();
1340 return g;
1341 }
1342
1343 /**
1344 * The covariance of the station-class queue lengths at the instant stage `e`
1345 * is left, by the law of total variance over the random sojourn T:
1346 *
1347 * Cov[Q(T)] = E_T[Cov(Q(t)|t)] + Cov_T[E(Q(t)|t)]
1348 * = sum_n w_n (C(t_n) + m(t_n) m(t_n)')/sum(w) - m_exit m_exit'
1349 *
1350 * with the SAME weights the exit mean uses, so the two are consistent by
1351 * construction. `C(t)` is the within-stage covariance the stage solver
1352 * integrated and is absent -- hence zero -- for a stage carrying a first
1353 * moment only; the timing term survives regardless. A deterministic sojourn
1354 * contributes no timing variance, so the answer is `C(d)` alone.
1355 */
1356 Matrix<double> stage_exit_cov(std::size_t e) const {
1357 const std::size_t n = M * K;
1358 Matrix<double> C(n, n, 0.0);
1359 const std::vector<double>& t = tranT[e];
1360 if (t.size() < 2) return C;
1361 const bool have_c = tranC[e].size() == t.size();
1362 if (det_sojourn) {
1363 if (!have_c) return C;
1364 // Clamped to the stage's own grid rather than extrapolated: linear
1365 // extrapolation of a covariance can leave the positive semidefinite
1366 // cone, while a convex combination of two members stays inside it.
1367 double d = std::max(t.front(), std::min(dvals[e], t.back()));
1368 std::size_t j = t.size() - 1;
1369 for (std::size_t k = 1; k < t.size(); ++k)
1370 if (d <= t[k]) {
1371 j = k;
1372 break;
1373 }
1374 const double dt = t[j] - t[j - 1];
1375 const double a = (dt > 0.0) ? (d - t[j - 1]) / dt : 0.0;
1376 for (std::size_t p = 0; p < n; ++p)
1377 for (std::size_t q = 0; q < n; ++q)
1378 C(p, q) = (1.0 - a) * tranC[e][j - 1](p, q) + a * tranC[e][j](p, q);
1379 return C;
1380 }
1381 const std::vector<double> w = cdf_weights(e, t);
1382 double wsum = 0.0;
1383 for (double v : w) wsum += v;
1384 if (!(wsum > 0.0)) return C;
1385 std::vector<double> mexit(n, 0.0);
1386 for (std::size_t a = 0; a < n; ++a)
1387 mexit[a] = weighted(tranQ[e][a % M][a / M], w, wsum);
1388 for (std::size_t a = 0; a < n; ++a) {
1389 const std::vector<double>& qa = tranQ[e][a % M][a / M];
1390 for (std::size_t b = 0; b < n; ++b) {
1391 const std::vector<double>& qb = tranQ[e][b % M][b / M];
1392 double acc = 0.0;
1393 for (std::size_t k = 0; k < w.size() && k < qa.size() && k < qb.size(); ++k)
1394 acc += w[k] * qa[k] * qb[k];
1395 if (have_c)
1396 for (std::size_t k = 0; k < w.size(); ++k) acc += w[k] * tranC[e][k](a, b);
1397 C(a, b) = acc / wsum - mexit[a] * mexit[b];
1398 }
1399 }
1400 for (std::size_t a = 0; a < n; ++a)
1401 for (std::size_t b = a + 1; b < n; ++b) {
1402 const double v = 0.5 * (C(a, b) + C(b, a)); // drop the rounding asymmetry
1403 C(a, b) = v;
1404 C(b, a) = v;
1405 }
1406 return C;
1407 }
1408
1409 /**
1410 * The Jacobian of a reset policy at the exit mean, so a covariance can cross
1411 * the switch as `R C R'`.
1412 *
1413 * A reset policy is an arbitrary map on the (station x class) mean queue
1414 * lengths, and there is no general way to push a second moment through one.
1415 * The delta method is the first-order image, which is the order the whole
1416 * mean-field coupling works to. The two NAMED policies are linear and R is
1417 * then EXACT: the identity for `keep`, zero for `clear`. Linear indexing is
1418 * column-major, `ir = r*M + i`, the same index space as the covariance.
1419 */
1420 Matrix<double> reset_jacobian(const ResetMarginal& f, const Matrix<double>& qexit) const {
1421 const std::size_t n = M * K;
1422 Matrix<double> R(n, n, 0.0);
1423 if (!f) { // the identity map: no reset on this arc
1424 for (std::size_t a = 0; a < n; ++a) R(a, a) = 1.0;
1425 return R;
1426 }
1427 const Matrix<double> base = f(qexit);
1428 if (base.rows() != M || base.cols() != K) return R;
1429 double scale = 1.0;
1430 for (std::size_t i = 0; i < M; ++i)
1431 for (std::size_t r = 0; r < K; ++r) scale = std::max(scale, std::fabs(qexit(i, r)));
1432 const double step = 1e-6 * scale;
1433 for (std::size_t j = 0; j < n; ++j) {
1434 Matrix<double> qp = qexit;
1435 qp(j % M, j / M) += step;
1436 const Matrix<double> pert = f(qp);
1437 if (pert.rows() != M || pert.cols() != K) continue;
1438 for (std::size_t a = 0; a < n; ++a)
1439 R(a, j) = (pert(a % M, a / M) - base(a % M, a / M)) / step;
1440 }
1441 return R;
1442 }
1443
1444 /** The congruence `R C R'`, the image of a covariance under a linear map. */
1445 static Matrix<double> congruence(const Matrix<double>& R, const Matrix<double>& C) {
1446 const std::size_t n = R.rows();
1447 Matrix<double> RC(n, n, 0.0), out(n, n, 0.0);
1448 for (std::size_t a = 0; a < n; ++a)
1449 for (std::size_t b = 0; b < n; ++b) {
1450 double acc = 0.0;
1451 for (std::size_t c = 0; c < n; ++c) acc += R(a, c) * C(c, b);
1452 RC(a, b) = acc;
1453 }
1454 for (std::size_t a = 0; a < n; ++a)
1455 for (std::size_t b = 0; b < n; ++b) {
1456 double acc = 0.0;
1457 for (std::size_t c = 0; c < n; ++c) acc += RC(a, c) * R(b, c);
1458 out(a, b) = acc;
1459 }
1460 return out;
1461 }
1462
1463 /**
1464 * True when stage e's holding time is the disabled 1 x 1 zero pair, whose
1465 * CDF is identically zero. A semi-Markov stage never is: it has arcs.
1466 */
1467 bool hold_disabled(std::size_t e) const {
1468 if (envObj.hold_time_is_semi_markov(e)) return false;
1469 const mam::Map<double> m = envObj.hold_time[e].map();
1470 for (std::size_t a = 0; a < m.D1.rows(); ++a)
1471 for (std::size_t b = 0; b < m.D1.cols(); ++b)
1472 if (m.D1(a, b) != 0.0) return false;
1473 return true;
1474 }
1475
1476 /**
1477 * The Stieltjes weights of stage e's holding time over the transient grid,
1478 * through `Environment::hold_time_cdf` (`Environment.holdTimeCdf`): the MAP
1479 * for a Markovian stage, the arc race or kernel mixture for a semi-Markov one.
1480 */
1481 std::vector<double> cdf_weights(std::size_t e, const std::vector<double>& t) const {
1482 std::vector<double> w(t.size(), 0.0);
1483 if (t.size() < 2) return w;
1484 if (hold_disabled(e)) return w;
1485 const std::vector<double> F = envObj.hold_time_cdf(e, t);
1486 for (std::size_t j = 1; j < t.size(); ++j) w[j] = F[j] - F[j - 1];
1487 return w;
1488 }
1489
1490 /**
1491 * `sojournAvgWeights_`: trapezoid weights of the survival 1 - F(t) of stage
1492 * e's holding time over the grid t. finish() REPORTS each stage by the time
1493 * average of its transient over the sojourn, int m(t)(1 - F(t))dt / E[H]
1494 * (renewal reward), because prob_env, which blends the stages, is the
1495 * fraction of TIME spent in each. The exit value int m dF that post() hands
1496 * on equals it only for an exponential holding time: on renv3, whose middle
1497 * stage holds for an Erlang(2), reporting the exit values put the Delay
1498 * throughput at 2.715 against the Queue's 2.75 in a closed cycle.
1499 */
1500 std::vector<double> sojourn_avg_weights(std::size_t e, const std::vector<double>& t) const {
1501 std::vector<double> W(t.size(), 0.0);
1502 if (t.size() < 2) return W;
1503 const std::vector<double> F = envObj.hold_time_cdf(e, t);
1504 for (std::size_t j = 1; j < t.size(); ++j) {
1505 const double h = 0.5 * (t[j] - t[j - 1]);
1506 W[j - 1] += h * (1.0 - F[j - 1]);
1507 W[j] += h * (1.0 - F[j]);
1508 }
1509 return W;
1510 }
1511
1512 /**
1513 * `destResolved_`: whether stage e's exit has to be averaged per destination.
1514 *
1515 * Only under 'smp', and only where the exit time depends on the destination:
1516 * a stage with two or more successors whose transitions are not all
1517 * competing exponentials. With competing exponentials the race leaves the
1518 * exit time independent of where the switch goes, and the destination-free
1519 * average is exact. A deterministic sojourn reads every exit at d_e and is
1520 * not resolved, as the reference's branch for it returns first.
1521 */
1522 bool dest_resolved(std::size_t e) const {
1523 if (!smp || det_sojourn) return false;
1524 const std::size_t E = envObj.nstages();
1525 std::size_t nsucc = 0;
1526 for (std::size_t h = 0; h < E; ++h)
1527 if (envObj.pemb(e, h) > 0.0) ++nsucc;
1528 if (nsucc < 2) return false;
1529 if (envObj.is_kernel_stage(e)) return true;
1530 std::vector<lang::Distrib<T>> arcs;
1531 std::vector<double> probs;
1532 envObj.stage_arcs(e, arcs, probs);
1533 for (const lang::Distrib<T>& a : arcs)
1534 if (!a.disabled && a.type != lang::ProcessType::EXP) return true;
1535 return false;
1536 }
1537
1538 /**
1539 * `exitByDestination_`: exit metrics of stage e for each destination h,
1540 * averaged over the cumulative incidence CIF_eh of `mc::smp_stage_cif`
1541 * rather than over the holding-time CDF. In a semi-Markov stage a switch to
1542 * h happens at the times the e -> h transition wins, so the state it hands
1543 * over is the transient read at those times. The weights of all
1544 * destinations add up to the holding-time weight, so the probEmb-mixture of
1545 * these exits is the destination-free average. A destination with no
1546 * trajectory or no weight keeps the stage's steady state. U and T are
1547 * resolved only where they are read, by a state-dependent rate.
1548 */
1549 void exit_by_destination(std::size_t e, std::vector<std::vector<Matrix<double>>>& Qexit,
1550 std::vector<std::vector<Matrix<double>>>& Uexit,
1551 std::vector<std::vector<Matrix<double>>>& Texit) {
1552 const std::size_t E = envObj.nstages();
1553 const StageSteady& st = stage_steady(e);
1554 for (std::size_t h = 0; h < E; ++h) {
1555 Qexit[e][h] = st.QN;
1556 if (!statedep) continue;
1557 Uexit[e][h] = st.UN;
1558 Texit[e][h] = st.TN;
1559 }
1560 if (tranT[e].empty()) return;
1561 std::vector<lang::Distrib<T>> arcs;
1562 std::vector<double> probs;
1563 envObj.stage_arcs(e, arcs, probs);
1564 const mc::SmpStageCif c = mc::smp_stage_cif(arcs, probs, tranT[e]);
1565 const std::size_t nt = tranT[e].size();
1566 for (std::size_t h = 0; h < E; ++h) {
1567 if (!(envObj.pemb(e, h) > 0.0)) continue;
1568 std::vector<double> w(nt, 0.0);
1569 double wsum = 0.0;
1570 bool nan = false;
1571 for (std::size_t j = 1; j < nt; ++j) {
1572 w[j] = c.C(h, j) - c.C(h, j - 1);
1573 if (std::isnan(w[j])) nan = true;
1574 wsum += w[j];
1575 }
1576 if (nan || !(wsum > 0.0)) continue;
1577 for (std::size_t i = 0; i < M; ++i)
1578 for (std::size_t r = 0; r < K; ++r) {
1579 Qexit[e][h](i, r) = weighted(tranQ[e][i][r], w, wsum);
1580 if (!statedep) continue;
1581 Uexit[e][h](i, r) = weighted(tranU[e][i][r], w, wsum);
1582 Texit[e][h](i, r) = weighted(tranTp[e][i][r], w, wsum);
1583 }
1584 }
1585 }
1586
1587 static double weighted(const std::vector<double>& v, const std::vector<double>& w,
1588 double wsum) {
1589 double s = 0.0;
1590 for (std::size_t j = 0; j < v.size() && j < w.size(); ++j) s += v[j] * w[j];
1591 return s / wsum;
1592 }
1593
1594 /**
1595 * `initFromMarginal` for a fluid stage: the mean queue length of every
1596 * (station, class) enters in PHASE ONE.
1597 *
1598 * The reference does NOT round this for a fluid stage
1599 * (`roundMarginalForDiscreteSolver` is skipped when the stage solver is
1600 * SolverFluid), because a fluid state is continuous -- rounding it would
1601 * quantize the very quantity the fixed point is iterating on.
1602 */
1603 std::vector<double> initsol_from_marginal(const qn::NetworkStruct<T>& sn,
1604 const Matrix<double>& Q) const {
1605 const fluid::FluidLayout L = fluid::fluid_layout(sn);
1606 std::vector<double> y(L.nstates, 0.0);
1607 for (std::size_t i = 0; i < sn.nstations && i < Q.rows(); ++i)
1608 for (std::size_t r = 0; r < sn.nclasses && r < Q.cols(); ++r) {
1609 if (!L.enabled[i][r]) continue;
1610 y[L.qidx[i][r]] = std::max(0.0, Q(i, r));
1611 }
1612 return y;
1613 }
1614
1615 Environment<T>& envObj;
1616 EnvOptions opt;
1617 std::size_t M = 0, K = 0;
1618 bool det_sojourn = false;
1619 bool statedep = false; ///< `method = "statedep"`: the arcs are rewritten each sweep
1620 bool smp = false; ///< `method = "smp"`: exits resolved by destination
1621 bool ctmc_stages = false; ///< `stage_solver = "ctmc"`: enumerate each stage's chain
1622 bool meancov = false; ///< `method = "meancov"`: a covariance crosses beside the mean
1623 bool kp_stages = false; ///< `stage.method = "kp"`: the Ko-Pender limits run each stage
1624 bool dae_stages = false; ///< `stage.method = "dae"`: the linear-noise DAE runs each stage
1625 std::vector<double> dvals;
1626 std::vector<Matrix<double>> entry; ///< per-stage entry queue lengths
1627 /**
1628 * `meancov` only: per-stage entry COVARIANCE over the (station, class)
1629 * pairs, the companion of `entry`, and the WITHIN-STAGE covariance the stage
1630 * solver integrated, one matrix per point of `tranT`. `tranC[e]` is empty
1631 * for a stage solver carrying a first moment only, and the coupling then
1632 * keeps the timing variance of the sojourn alone.
1633 */
1634 std::vector<Matrix<double>> centry;
1635 std::vector<std::vector<Matrix<double>>> tranC;
1636 std::vector<std::vector<double>> tranT;
1637 std::vector<std::vector<std::vector<std::vector<double>>>> tranQ, tranU, tranTp;
1638 /**
1639 * Per stage, its steady tables and whether they have been asked for: the
1640 * exit value of every metric its transient carries no trajectory for. Asked
1641 * at most once per run and only where one is read; see `stage_steady`.
1642 */
1643 std::vector<StageSteady> steady;
1644 std::vector<char> steady_asked;
1645 /** Per LAYERED stage, the SolverLN that runs it; null for a flat stage. */
1646 std::vector<std::shared_ptr<ln::SolverLN<T>>> lnsolv;
1647 /** Per LAYERED stage, where each of its layers sits in the aggregate view. */
1648 std::vector<ln::LnLayerBlocks> lnblk;
1649};
1650
1651} // namespace env
1652} // namespace line
1653
1654#endif // LINE_SOLVERS_ENV_SOLVER_ENV_H
InputError(const std::string &what)
Definition error.h:105
UnsupportedError(const std::string &what)
Definition error.h:119
SolverEnv(Environment< T > &e, const EnvOptions &o)
Definition solver_env.h:292
EnvSolution solve()
Definition solver_env.h:294
Equilibrium distribution of a discrete-time Markov chain, and stochastic complementation.
A random environment: a port of matlab/src/lang/Environment.m, restricted to what SolverENV reads out...
The exception types the port throws.
The min-normal closure as a DIFFERENTIAL-ALGEBRAIC system: solver_fluid_dae.m.
Port of solver_fluid_kp.m: the fluid AND diffusion limits of the (MAP_t/Ph_t/inf)^N network of Y.
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.
The option and result types every MVA analyzer shares.
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....
CtmcTransient< T > solver_ctmc_transient_analyzer(const NetworkStruct< T > &sn_arg, const CtmcOptions &opt, const T &t0, const T &t1, const std::vector< T > &grid=std::vector< T >())
Port of solver_ctmc_transient_analyzer.m.
std::function< Matrix< double >(const Matrix< double > &)> ResetMarginal
The reset policy of a transition, resetFun in the reference.
Definition environment.h:98
ln::LnOptions env_default_lqn_options()
LnOptions as a LAYERED environment stage is solved with.
Definition solver_env.h:115
FluidSolution solver_fluid_kp(const qn::NetworkStruct< T > &sn, const FluidOptions &opt)
Port of solver_fluid_kp.m: the steady table at the horizon.
Definition fluid_kp.h:1055
FluidLayout fluid_layout(const qn::NetworkStruct< T > &sn)
Port of the layout half of solver_fluid_odes.m.
Definition fluid_odes.h:282
FluidSolution solver_fluid_dae(const qn::NetworkStruct< T > &sn, const FluidOptions &opt, const FluidDaeOptions &dopt_in=FluidDaeOptions())
solver_fluid_dae.m: the min-normal closure solved as one system.
Definition fluid_dae.h:2153
std::vector< FluidTranPoint > solver_fluid_transient(const qn::NetworkStruct< T > &sn, const FluidOptions &opt, double t_end, std::size_t points=101, const std::vector< double > &out_grid=std::vector< double >())
Port of @@SolverFLD/getTranAvg: the metrics along the trajectory, not just at the fixed point.
FluidSolution solver_fluid(const qn::NetworkStruct< T > &sn_in, const FluidOptions &opt, qn::NetworkStruct< T > *sn_out=nullptr)
Port of solver_fluid_analyzer.m: dispatch on the method, refit the non-exponential FCFS stations the ...
std::vector< FluidTranPoint > solver_fluid_dae_transient(const qn::NetworkStruct< T > &sn, const FluidOptions &opt, double t_end, std::size_t points=101, const std::vector< double > &out_grid=std::vector< double >(), const FluidDaeOptions &dopt_in=FluidDaeOptions())
@@SolverFLD/getTranAvg for the DAE route: the metrics ALONG the trajectory.
Definition fluid_dae.h:2611
FluidSolution solver_fluid_kp_core(const qn::NetworkStruct< T > &sn, const FluidOptions &opt, FluidKpTransient *tran, const std::vector< double > &out_grid=std::vector< double >())
The Ko-Pender solve, returning both the steady table and the covariance trajectory so that neither ha...
Definition fluid_kp.h:314
SmpStageCif smp_stage_cif(const std::vector< lang::Distrib< T > > &arcs, const std::vector< double > &probs, const std::vector< double > &t)
CIF and holding-time CDF of a stage at the ascending instants t.
bool from_marginal_node_first(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< std::size_t > &n, const std::vector< std::size_t > &phases, std::vector< T > &out)
The FIRST row from_marginal_node emits, BUILT rather than enumerated.
Definition state.h:2887
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
Controls and result shape shared by the normalizing-constant analyzers.
A queueing network and its refreshed NetworkStruct.
Cumulative incidence functions of one semi-Markov stage.
Port of solver_ctmc_transient_analyzer.m: the time-dependent counterpart of solver_ctmc_analyzer,...
SolverFluid: the closing method, a port of solver_fluid.m, solver_fluid_iteration....
SolverLN: layered decomposition of a layered queueing network.
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
Options of SolverENV.
Definition solver_env.h:122
std::string method
The inter-stage coupling: meanfield is the reference's default.
Definition solver_env.h:145
std::vector< double > env_init
Method occupation: options.config.env_init, the initial probability of each stage.
Definition solver_env.h:175
std::string stage_solver
Which solver runs each FLAT stage: fluid (the fluid transient), ctmc (the enumerated chain),...
Definition solver_env.h:139
bool stage_stiff
options.stiff of a CTMC stage, read only when stage_solver is ctmc.
Definition solver_env.h:160
std::string sojourn
options.sojourn: stochastic (default) or deterministic.
Definition solver_env.h:147
fluid::FluidOptions stage
Options handed to each stage solver.
Definition solver_env.h:149
double stage_cutoff
options.cutoff of a CTMC stage, read only when stage_solver is ctmc.
Definition solver_env.h:154
double timespan_end
options.timespan(2) of the inner solver: the transient horizon.
Definition solver_env.h:162
double env_timespan_start
Method occupation: SolverENV's OWN options.timespan, [t0, t1].
Definition solver_env.h:169
ln::LnOptions lqn
Options of the SolverLN that runs a LAYERED stage.
Definition solver_env.h:205
nc::NcSolverOptions stage_nc
Options of an nc stage solver, SolverNC(model, options).
Definition solver_env.h:143
mva::MvaOptions stage_mva
Options of an mva stage solver, SolverMVA(model, options).
Definition solver_env.h:141
std::size_t tran_points
Points on a UNIFORM transient grid, used only where stage_grid declines to build one (a stage whose h...
Definition solver_env.h:188
What SolverENV reports.
Definition solver_env.h:209
Matrix< double > UN
Definition solver_env.h:211
std::vector< Matrix< double > > Qentry
The entry queue lengths the fixed point converged to.
Definition solver_env.h:215
Matrix< double > QCov
meancov only: the environment-wide queue-length COVARIANCE over the (station, class) pairs,...
Definition solver_env.h:222
Matrix< double > TN
Definition solver_env.h:211
Matrix< double > QN
Environment-averaged metrics, (nstations x nclasses).
Definition solver_env.h:211
Matrix< double > QVar
Definition solver_env.h:222
std::vector< Matrix< double > > TExit
Definition solver_env.h:213
std::vector< Matrix< double > > UExit
Definition solver_env.h:213
std::vector< Matrix< double > > QExit
Per-stage, sojourn-averaged metrics.
Definition solver_env.h:213
Controls, defaulting to SolverOptions('Fluid') in the reference.
Options of SolverLN.
Definition solver_ln.h:275
std::string layer_solver
Which solver runs each layer: mva, nc, fluid, ssa, mam, ctmc, ldes (the native in-process LDES engine...
Definition solver_ln.h:318
The options SolverMVA reads.
Definition mva_types.h:32
Controls, defaulting to SolverOptions('NC') in the reference.
Definition nc_types.h:35