LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
solver_fluid.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_FLUID_SOLVER_FLUID_H
6#define LINE_SOLVERS_FLUID_SOLVER_FLUID_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * SolverFluid: the `closing` method, a port of `solver_fluid.m`,
12 * `solver_fluid_iteration.m` and `solver_fluid_closing.m`.
13 *
14 * WHAT THE SOLVER DOES. The fluid approximation replaces the integer queue
15 * lengths of the CTMC with real-valued masses and follows their mean drift.
16 * The drift is built in `fluid_odes.h`; this file integrates it and turns the
17 * end state into the usual Q/U/R/T/C/X table.
18 *
19 * WHY THE INTEGRATION IS AN ITERATION RATHER THAN ONE LONG SOLVE. The steady
20 * state is the drift's fixed point, and how long it takes to get there is set
21 * by the SLOWEST rate in the model. The reference integrates to
22 * 10*iter/min(rate) on iteration `iter`, restarting from the previous end
23 * state: each pass buys another ten mean events of the slowest transition. A
24 * single solve to a guessed horizon either stops short on a stiff model or
25 * wastes most of its steps on one that settled early.
26 *
27 * A NOTE ON THE CONVERGENCE TEST. `movedMassRatio` is the mass moved over ONE
28 * window, and for a mode relaxing at rate r it underestimates the distance
29 * still to go by (1-exp(-r*window)). On M/M/1 at rho = 0.9 with `minnormal` the
30 * fixed point is Q = 7.021524680 and stopping at `iter_tol = 1e-4` lands on
31 * 7.014672, out by 0.1%. Both `solver_fluid_iteration.m` and this port
32 * therefore ran every one of their `iter_max` passes, which is what made a
33 * fluid solve cost a fixed 150 windows however close it started to the answer.
34 * The fix is to stop on what the ratio DROPS: summing the geometric tail,
35 * ratio*rho/(1-rho) with rho read off the iteration itself, bounds the distance
36 * left rather than the distance just travelled, and needs no rate to stand in
37 * for the slowest system mode -- when one does, as a bare drift norm must, the
38 * stop lands 3% short. `earlystop` (default true, `options.config.fluid_earlystop`)
39 * selects it; `iter_tol > 0` remains the caller's own cruder trade. A FINITE
40 * `timespan_end` is a transient request and is exempt from both: it integrates
41 * to its end time even once the state has settled.
42 *
43 * THE PRICE OF RUNNING EVERY PASS is this port's own, and it is small: LSODA is
44 * restarted once per pass, so at the default `tol = 1e-4` its error accumulates
45 * on a state that is already at the fixed point. On Delay(Z=1) -> PS(c=2), N=6,
46 * whose `closing` fixed point is exactly (2,4) and which the reference returns
47 * to nine digits, this port is right to 1e-8 by pass 8 and 7e-6 by pass 200.
48 * `tol = 1e-6` removes it, at the cost of a different trajectory row count.
49 *
50 * DOUBLE ONLY. The drift is integrated by LSODA, whose coefficients assume
51 * `double` (see `util/lsoda.h`), so a non-`double` backend is refused BY NAME
52 * rather than silently narrowed.
53 */
54
55#include <algorithm>
56#include <cmath>
57#include <cstddef>
58#include <limits>
59#include <string>
60#include <vector>
61
67#include "line/lang/qn/state.h"
82#include "line/util/error.h"
84#include "line/util/lsoda.h"
85#include "line/util/matrix.h"
86
87namespace line {
88namespace fluid {
89
90/** Controls, defaulting to `SolverOptions('Fluid')` in the reference. */
92 std::string method = "default";
93 double tol = 1e-4; ///< absolute and relative tolerance handed to the integrator
94 double iter_tol = 0.0; ///< >0 stops early when the moved-mass ratio falls below it; 0 runs to iter_max, as the reference does
95 bool earlystop = true; ///< `options.config.fluid_earlystop`: stop on the geometric tail of the window iteration
96 std::size_t iter_max = 200; ///< cap on outer integrations
97 /**
98 * `options.config.nonmkvorder`: the phase budget `sn_nonmarkov_toph` spends
99 * on a non-Markovian service law. The fluid path always takes the PH fit,
100 * so this is the Bernstein order.
101 */
102 std::size_t nonmkv_order = 20;
103 /**
104 * `options.config.nonmkv`: 'bernstein' (default) runs `sn_nonmarkov_toph`,
105 * 'none' skips it; any other name is refused (`api::nonmkv_enabled`).
106 */
107 std::string nonmkv = "bernstein";
108 double timespan_end = std::numeric_limits<double>::infinity();
109 std::vector<double> init_sol; ///< initial state; empty selects the default below
110 /**
111 * `options.config.tbi_cells`: an explicit partition for method `tbi`, as
112 * disjoint 0-BASED station index sets covering every station once. Empty
113 * leaves the grouping to `tbi_partition`, which agglomerates on routing
114 * coupling towards `tbi_cellsize` stations per cell
115 * (`options.config.tbi_cellsize`).
116 */
117 std::vector<std::vector<std::size_t>> tbi_cells;
118 std::size_t tbi_cellsize = 5;
119 /**
120 * `options.config.kp_init_sol`: the `kp` method's initial state, in the
121 * KO-PENDER layout -- one offset counter walking the stations in order, an
122 * arrival-phase block at each EXT station-class and a service-phase block at
123 * every other, with no mass returning to the source.
124 *
125 * NOT `init_sol`, which is laid out for the CLOSING state vector: the two
126 * can have the same length on the same model, so sharing one field lets a
127 * closing-layout seed be consumed here, silently zeroing the source phase
128 * mass and with it the whole network. Empty selects the stationary arrival
129 * phase; a wrong-sized seed is refused rather than ignored.
130 */
131 std::vector<double> kp_init_sol;
132 /**
133 * `options.config.init_cov`: the `kp` method's initial covariance Sigma(0),
134 * dim-by-dim in the same layout as `kp_init_sol`.
135 *
136 * A caller that carries a DISTRIBUTION across a handoff supplies the second
137 * moment beside the mean, so the next stage does not restart from a point
138 * mass it never had. Empty keeps the default diag(theta) - theta theta' of
139 * the initial arrival phase.
140 */
142 /**
143 * `options.config.init_qlen`: the `kp` method's initial state over
144 * (station, class) PAIRS, M-by-K, rather than over its own phase layout.
145 *
146 * The layout-free spelling of `kp_init_sol`, for a caller that has a mean
147 * queue length per station and class and does not know how this method
148 * numbers phases -- SolverENV's `meancov` coupling is the case it exists
149 * for. The lift is the multinomial one: a block's mass is split over its
150 * phases by the service entry vector pie. Mutually exclusive with
151 * `kp_init_sol`/`init_cov`, which are the same initial condition in the
152 * other spelling.
153 */
155 /**
156 * `options.config.init_qcov`: the companion covariance of `init_qlen`, over
157 * the station-class pairs, (M*K)-by-(M*K) and indexed `ir = r*M + i`.
158 *
159 * Lifted to the phase layout beside the mean: the diagonal block carries
160 * `C(ir,ir) pie pie'` plus the MULTINOMIAL term `m_ir (diag(pie) - pie pie')`,
161 * which is the variance of splitting a known total over the phases. Dropping
162 * that term asserts every job's phase is known once the total is.
163 *
164 * READ BY `kp` AND BY `dae`. `dae` takes it WITHOUT `init_qlen`: its mean
165 * already arrives through `init_sol` and the seed trajectory, so only the
166 * second moment is missing, and `fluid_dae_lift_qcov` takes the block masses
167 * and phase split from the stage's own initial state. Above
168 * `FluidDaeOptions::maxcov`, and under a finite-capacity cap, the variance is
169 * held and a seed cannot be used, which is REFUSED rather than dropped.
170 */
172 double softmin_alpha = 20.0; ///< sharpness of the 'softmin' smoothing
173 double pstar = 20.0; ///< exponent of the 'pnorm' smoothing
174 /**
175 * Opt in to the p-norm under `matrix`/`default` too, which is what
176 * `options.config.pstar` does in MATLAB, the JAR and native Python. The
177 * exponent above is a default, not a request, so it cannot serve as the
178 * flag: leaving it at 20 must keep the hard min() under `matrix`.
179 */
180 bool pstar_set = false;
181 /**
182 * `options.config.fork_join`: which fork-join arm the fixed point takes,
183 * 'default'/'mmt'/'fjt' or 'ht'. Carried here so that a fluid solve of a
184 * fork-join model selects the same transform an MVA or NC solve of it
185 * would; see the `has_fork` branch of fluid_runner.h.
186 */
187 std::string fork_join = "default";
188 double timestep = 0.01; ///< 'diffusion' Euler-Maruyama step
189 unsigned long seed = 23000; ///< 'diffusion' RNG seed
190 /**
191 * `options.stiff`: integrate the closing family with the explicit stiff arm
192 * of `fluid_stiff.h` rather than with LSODA.
193 *
194 * THE DEFAULT IS FALSE WHERE THE REFERENCE'S IS TRUE, and that is not a
195 * downgrade. `options.stiff = true` selects ode15s, a variable-order BDF
196 * code; LSODA is a variable-order Adams/BDF code that switches to BDF on
197 * its own stiffness detector, so the reference's default arm is the one
198 * already taken here. Setting this selects the four-stage Rosenbrock
199 * method, which is the family ode23s belongs to -- the reference's OTHER
200 * arm -- so the flag names the integrator that is actually different.
201 */
202 bool stiff = false;
203 /**
204 * `options.config.hide_immediate`: fold the Immediate-rate transitions into
205 * the timed ones by stochastic complementation before integrating. Off in
206 * the reference too, which reaches `ode_eliminate_immediate` only when the
207 * caller asks for it.
208 */
209 bool hide_immediate = true;
210 /**
211 * `options.config.aoi_preemption`: the preemption (bufferless) or
212 * replacement (single buffer) probability of the AoI branch of `mfq`.
213 * Negative selects the value the scheduling policy implies.
214 */
215 double aoi_preemption = -1.0;
216 /**
217 * `options.config.moment_sigma2` and `options.config.moment_cov`: the second
218 * moment the drift's non-linear terms are closed with.
219 *
220 * A CALLER DOES NOT SET THIS. `solver_fluid_moments` does, once per sweep of
221 * its outer fixed point, and it is on the options because the mean solve is
222 * the ORDINARY closing integration -- the closure has to reach the drift
223 * without a second entry point that could drift from the first.
224 */
226 /**
227 * `options.config.moment_maxstate`: the largest phase-resolved state the
228 * moment-closure methods will build a covariance over. The Lyapunov solve is
229 * cubic in it, so this is a refusal threshold and not a tuning knob; it also
230 * decides whether `default` resolves to `minnormal` at all.
231 */
232 std::size_t moment_maxstate = 200;
233 /**
234 * `options.config.dae_maxstate` and `options.config.dae_maxcov`: the DAE
235 * route's own two refusal thresholds, on the simultaneous solve and on the
236 * covariance it integrates alongside the mean.
237 *
238 * ZERO MEANS NOT SET, and that is what makes them options rather than a
239 * second copy of the defaults: the route reads them off `FluidDaeOptions`,
240 * whose own values a caller may pin directly, and `fluid_dae_options` lets
241 * an explicit pin stand wherever the options are silent. A user reaching
242 * for the knob writes the option, as in the other three codebases; a test
243 * pinning one writes the struct.
244 */
245 std::size_t dae_maxstate = 0;
246 std::size_t dae_maxcov = 0;
247 /**
248 * `options.config.fluid_boundary`: how the Petri `dae` route reports a fluid place level held at a bound,
249 * `reflect` (the bound itself) or `diffusion` (the mean of a reflected Brownian motion with the unthrottled
250 * drift and the linear-noise variance rate of the net inflow). Read only by an FSPN; line-cli
251 * `--fluid-boundary`.
252 */
253 std::string fluid_boundary = "reflect";
254 /**
255 * `options.config.highvar`: which non-exponential FCFS correction the
256 * analyzer's outer refit loop applies, `interp` (the WSC 2020 diffusion
257 * interpolation) or `default`/`none`/`hvmva` (no rescaling, so the loop
258 * converges after one sweep).
259 *
260 * THE DEFAULT IS `default`, i.e. NO rescaling, because that is what
261 * `SolverOptions.m:127` sets for FLD -- NC is the solver that defaults to
262 * `interp`. The refit loop still runs: with no rescaling it refits each FCFS
263 * station to a Coxian at its own mean and SCV, which is an identity on a
264 * declared Coxian and a two-moment reduction on anything else, and it
265 * converges in two sweeps because `eta` is constant. See fluid_nonexp.h.
266 */
267 std::string highvar = "default";
268 /**
269 * `options.config.rate_traj = {tgrid, Mmat}`: a caller-supplied per-EVENT
270 * multiplier, which is what the coupled LN layer transient injects.
271 * `Mmat` must have one row per event of the closing ODE.
272 */
274 /**
275 * `options.config.nhpp_sched`: the (station, class) pairs whose SOURCE
276 * carries a non-homogeneous intensity, which the drift is to follow exactly
277 * rather than at its time average.
278 *
279 * IT IS A LIST AND NOT A FLAG, and that is the reference's design. A model
280 * can declare an NHPP and still be solved at the nominal -- that is what
281 * `solver_fluid.m` does for a steady-state request -- so the schedule enters
282 * the drift only when a caller asks for it, which in the reference is
283 * `@@SolverFLD/getTranAvg` through `local_detect_nhpp`. `fluid_detect_nhpp`
284 * below is that detector; a caller that wants the nominal simply does not
285 * call it.
286 */
287 std::vector<std::pair<std::size_t, std::size_t> > nhpp_sched; ///< 1-based (station, class)
288 /**
289 * `options.config.rate_sched`: explicit per-(station, class) rate
290 * trajectories, the third source `solver_fluid_ratemult` composes. Used by
291 * the coupled LN layer transient to inject time-varying inter-layer demand
292 * through the same station-class -> event expansion the NHPP path uses.
293 */
294 struct RateSched {
295 std::size_t station = 0; ///< 1-based
296 std::size_t cls = 0; ///< 1-based
297 std::vector<double> tgrid;
298 std::vector<double> rates;
299 /** The nominal baked into rate_base; <= 0 selects `Mu{i}{c}(1)`. */
300 double nominal = -1.0;
301 };
302 std::vector<RateSched> rate_sched;
303};
304
305/**
306 * The second-order results of the moment-closure methods, i.e. what
307 * `@@SolverFLD/getMoments` returns.
308 *
309 * EMPTY FOR EVERY FIRST-ORDER METHOD, which compute no second moment at all --
310 * `has_moments` on the solution says which. Reporting zeros instead would be a
311 * variance of zero, which is a claim and not an absence.
312 */
314 Matrix<double> Sigma; ///< state-level covariance, on range(D)
315 Matrix<double> QVar, QStd; ///< per station and class queue-length variance
316 std::vector<double> sigma2; ///< per-station population variance
317 std::vector<double> refinement; ///< the 1/N correction, `mnrefined` only
318 std::size_t outer_iters = 0;
319 /// state coordinates of each (station,class): `Sigma` is indexed by SERVICE
320 /// PHASE, so reading a per-class population off it needs this map
321 std::vector<std::vector<std::vector<std::size_t>>> class_block;
322};
323
324/**
325 * One point of a transient trajectory: the metrics at time `t`.
326 *
327 * `getTranAvg` in the reference returns QNt/UNt/TNt as (station x class) cell
328 * arrays of time series; this carries the same information sampled at a grid,
329 * which is what a caller plots or integrates.
330 */
332 double t = 0.0;
334 /**
335 * Per-(station,class) queue-length VARIANCE at this instant, empty where the
336 * method carries no second moment along the trajectory. Only the `dae`
337 * route fills it, and only below `FluidDaeOptions::maxcov`: the moment
338 * closures evaluate their whole transient at the single stationary variance,
339 * so a per-point variance would be the same number repeated.
340 */
342 /**
343 * The same second moment as a FULL (M*K)-by-(M*K) covariance, indexed
344 * `ir = r*M + i`, empty wherever `QVar` is. `QVar` is its diagonal reshaped;
345 * the off-diagonal entries carry the cross-station and cross-class terms a
346 * per-pair variance drops, which is what a coupling carrying a distribution
347 * across a handoff needs -- SolverEnv's `meancov` is the case it exists for.
348 */
350};
351
352/** What the analyzer returns, in the same shape as the MVA solver's result. */
355 std::vector<double> CN, XN;
356 std::vector<double> xvec; ///< the converged fluid state
357 std::size_t iters = 0;
358 /**
359 * `iter` of `solver_fluid_analyzer.m`: the FCFS non-exponential refit sweeps.
360 * Zero when the model has no FCFS station or the method does not refit, which
361 * is the reference's own "the loop was never entered".
362 */
363 std::size_t refit_sweeps = 0;
364 std::string method = "closing";
365 /**
366 * The reference's line_warning text, verbatim, empty when it did not warn.
367 * Set only by the fork-join fixed point today (fluid_fork_join_run).
368 */
369 std::string warning;
370 /**
371 * `result.solverSpecific.aoiResults`: set only by the AoI branch of `mfq`,
372 * where the age laws, and not QN/RN, are the answer.
373 */
374 bool has_aoi = false;
376 /**
377 * `result.solverSpecific.moments`: set only by `minnormal` and `mnrefined`.
378 * `closure` is the variance those methods converged to, kept so that a
379 * transient asked for afterwards integrates the SAME Gaussian drift the
380 * steady-state table was read from rather than the first-order one.
381 */
382 bool has_moments = false;
385 /** `self.result.FJ`, set by the fork-join arm (fluid_fork_join_run); empty otherwise. */
387};
388
389namespace detail {
390
391/**
392 * Port of `solver_fluid_initsol.m`: THE initial condition of every fluid
393 * integration, and the only one in this port.
394 *
395 * IT IS NOT THE `y0` OF `solver_fluid.m`. That vector -- the even spread of a
396 * closed population over the stations that serve its class -- is the
397 * reference's `ydefault`, reached only when the integrator rejects the real
398 * initial point. `solver_fluid_analyzer.m:25-27` fills `options.init_sol` with
399 * `solver_fluid_initsol` BEFORE the method switch, so the even spread is never
400 * what a solve starts from.
401 *
402 * WHAT `solver_fluid_initsol` ACTUALLY RETURNS, and why it is this short.
403 * It decodes `sn.state`, which for any model that did not call setState is what
404 * `Network.initDefault` wrote through `State.fromMarginalAndStarted`. That
405 * encoder puts every job it starts in PHASE ONE
406 * (`init = spaceClosedSingle(K(r),0); init(1) = si(r)`), never enumerating the
407 * phase assignment. Outside a Source the decode then gives phase one
408 * `nir(r) - sum_{k>=2} kir(r,k)`, and with every kir(r,k>=2) zero that is the
409 * whole per-station population back again. So the round trip through the
410 * encoder is an identity, and what is left of `solver_fluid_initsol` is the
411 * PLACEMENT `initDefault` computed, written into the phase-one entries.
412 *
413 * An open class instead holds the unit job pool at its Source, which is
414 * `init(1) = 1` in the encoder's EXT branch, and nothing anywhere else.
415 *
416 * THE PLACEMENT IS `initDefault`'s AND NOT "ALL OF IT AT THE REFERENCE
417 * STATION". The reference station takes as much of the population as its
418 * `classcap`/`cap` allows and SPILLS the excess onto the remaining stations in
419 * ascending order, erroring when it never fits. On a model with no explicit
420 * capacity the two coincide -- `refreshCapacity` gives every station the
421 * population of the chains that reach it -- but `setCapacity(k)` below the
422 * population makes them different vectors, and then the ODE would be started
423 * from a point the model is never in.
424 */
425template <class T>
426std::vector<std::vector<double>> fluid_initsol_placement(const qn::NetworkStruct<T>& sn,
427 const FluidLayout& L) {
428 const std::size_t M = sn.nstations, K = sn.nclasses;
429 const double inf = std::numeric_limits<double>::infinity();
430 std::vector<std::vector<double>> nplace(M, std::vector<double>(K, 0.0));
431 std::vector<double> totplace(M, 0.0);
432 // An unrefreshed struct carries no capacity table, which is the reference's
433 // Inf default and not a zero buffer.
434 const bool has_cap = sn.cap.size() == M && sn.classcap.size() == M;
435
436 for (std::size_t r = 0; r < K; ++r) {
437 const double pop = sn.classes[r].population;
438 if (!std::isfinite(pop)) continue;
439 // The reference station first, then every other station in ascending
440 // order: `[refist, setdiff(1:M, refist)]`.
441 std::vector<std::size_t> order;
442 const std::size_t rs = sn.classes[r].refstat;
443 if (rs >= 1 && rs <= M) order.push_back(rs - 1);
444 for (std::size_t i = 0; i < M; ++i)
445 if (order.empty() || i != order[0]) order.push_back(i);
446
447 // A Place takes the WHOLE population and never spills, capacity or not
448 // (`initDefault.m:24-28`). It carries no fluid coordinates, so the class
449 // then contributes nothing to the state vector -- which is also what the
450 // reference's decode does, since a Place has NaN rates and
451 // `solver_fluid_initsol.m:29,39` appends a column only for a rated class.
452 if (rs >= 1 && rs <= M && sn.stations[rs - 1].nodetype == lang::NodeType::Place) {
453 nplace[rs - 1][r] = pop;
454 totplace[rs - 1] += pop;
455 continue;
456 }
457
458 double remaining = pop;
459 for (std::size_t oi = 0; oi < order.size() && remaining > 0.0; ++oi) {
460 const std::size_t j = order[oi];
461 // A Source is the reservoir of the open classes, not a holding place
462 // for a closed population; a Place belongs to the Petri net encoding
463 // and has no fluid coordinates at all.
464 if (sn.stations[j].sched == lang::SchedStrategy::EXT) continue;
465 if (sn.stations[j].nodetype == lang::NodeType::Place) continue;
466 // A pair with no fluid block would otherwise take its mass through
467 // `qidx` into the NEXT block, since a disabled pair's index is the
468 // following pair's start.
469 if (!L.enabled[j][r]) continue;
470 const double ccap = (has_cap && sn.classcap[j].size() > r) ? sn.classcap[j][r] : inf;
471 const double scap = has_cap ? sn.cap[j] : inf;
472 const double avail = std::min(ccap - nplace[j][r], scap - totplace[j]);
473 const double take = std::min(remaining, std::max(0.0, avail));
474 nplace[j][r] += take;
475 totplace[j] += take;
476 remaining -= take;
477 }
478 if (remaining > 0.0)
479 throw InputError("solver_fluid_initsol: cannot place the population of class '" +
480 sn.classes[r].name +
481 "': the total capacity of the stations that serve it is insufficient");
482 }
483 return nplace;
484}
485
486/**
487 * The DECLARED initial condition, or false when the model declares none.
488 *
489 * `solver_fluid_initsol.m` decodes `sn.state{isf}`, which is whatever
490 * `setState` or `initFromMarginal` left there and only falls back to
491 * `initDefault`'s placement when nothing was set. This port used to recompute
492 * that placement unconditionally, so `initFromMarginal([0 0; 4 1])` integrated
493 * from the DEFAULT marking instead -- the right answer to a different model, and
494 * invisible in a long horizon because every initial condition of a closed model
495 * converges to the same stationary point.
496 *
497 * PHASE ONE IS NOT ASSUMED HERE, unlike in the default placement. A declared
498 * state carries `kir(r,k)`, jobs in service in phase k, so the reference writes
499 * `nir(r) - sum_{k>=2} kir(r,k)` into phase one and `kir(r,k)` into the rest; an
500 * `initFromMarginalAndStarted` state has jobs past phase one and folding them
501 * forward would start the integration with a different amount of work in flight.
502 *
503 * A Source is the EXT branch: it holds no fluid population of its own, and its
504 * per-phase entries are the reference's `kir` there too.
505 *
506 * WHICH ROW OF `statespace` IS THE STATE: THE FIRST ONE CARRYING PRIOR MASS.
507 * The pair on the wire is the node's WHOLE local space with a prior over its
508 * rows, not a one-row state -- a model saved after `initDefault` sends eight
509 * rows for a 3-server FCFS queue, with the prior a point mass on row 0. The
510 * reference does not read that pair at all: `solver_fluid_initsol.m` decodes
511 * `sn.state{isf}`, the single CURRENT state, and every writer emits that state
512 * as row 0 of the space it sends (the invariant `state.h` states for
513 * `default_init_state`).
514 *
515 * A PRIOR OVER SEVERAL ROWS DOES NOT CHANGE THE ANSWER, and must not. The fluid
516 * limit is not linear in the initial distribution -- the ODE from the mean of
517 * two states is not the mean of the two ODEs -- so there is nothing to average;
518 * the reference simply keeps integrating from `sn.state`, which `setStatePrior`
519 * does not touch. Declining the mixture and falling back to `initDefault`'s
520 * placement instead answered `init_state_fcfs_nonexp`'s Prior 3 with the
521 * DEFAULT marking (0.175046 for a reference 0.175821) while its Prior 2, the
522 * same state under a point-mass prior, was right.
523 *
524 * THE FALLBACK IS PER STATION, as `sn_declared_marginal`'s is. A station whose
525 * row is absent, undecodable or a mixture keeps `initDefault`'s placement while
526 * its neighbours keep their declared rows; an all-or-nothing rule zeroed the
527 * whole vector the moment ONE station declared and another did not, which on
528 * `init_state_fcfs_nonexp` emptied the network and reported QLen 0.
529 */
530template <class T>
531bool fluid_declared_initsol(const qn::NetworkStruct<T>& sn, const FluidLayout& L,
532 const std::vector<std::vector<double>>& nplace,
533 std::vector<double>& y0) {
534 const std::size_t M = sn.nstations, K = sn.nclasses;
535 bool any = false;
536 std::vector<double> out(L.nstates, 0.0);
537 for (std::size_t i = 0; i < M; ++i) {
538 const std::size_t ind = sn.node_of_station(i + 1);
539 const bool ext = sn.stations[i].sched == lang::SchedStrategy::EXT;
540 const typename std::map<std::size_t, Matrix<T>>::const_iterator ss =
541 sn.statespace.find(ind);
542 const typename std::map<std::size_t, std::vector<T>>::const_iterator sp =
543 sn.stateprior.find(ind);
544 std::size_t pick = static_cast<std::size_t>(-1);
545 if (ss != sn.statespace.end() && sp != sn.stateprior.end() && ss->second.cols() > 0 &&
546 ss->second.rows() == sp->second.size()) {
547 for (std::size_t r = 0; r < ss->second.rows() && pick == static_cast<std::size_t>(-1);
548 ++r)
549 if (num_traits<T>::to_double(sp->second[r]) > 0.0) pick = r;
550 }
551 qn::Marginal<T> m;
552 bool decoded = false;
553 if (pick != static_cast<std::size_t>(-1)) {
554 std::vector<T> row(ss->second.cols());
555 for (std::size_t c = 0; c < ss->second.cols(); ++c) row[c] = ss->second(pick, c);
556 std::vector<std::size_t> ph(K, 1), shift(K, 0);
557 std::size_t w = 0;
558 for (std::size_t r = 0; r < K; ++r) {
559 ph[r] = sn.phasessz_of(i + 1, r + 1);
560 shift[r] = w;
561 w += ph[r];
562 }
563 try {
564 m = qn::to_marginal(sn, i + 1, row, ph, shift, sn.nvars_of(ind));
565 decoded = m.nir.size() == K && m.kir.size() == K;
566 } catch (const Error&) {
567 decoded = false; // a row the encoding cannot decode is not a state
568 }
569 }
570 for (std::size_t r = 0; r < K; ++r) {
571 if (!L.enabled[i][r]) continue;
572 if (!decoded) {
573 // This station keeps `initDefault`'s placement, all of it in
574 // phase one, which is where that encoder starts every job.
575 if (!ext && nplace[i][r] > 0.0) out[L.qidx[i][r]] = nplace[i][r];
576 if (ext && !std::isfinite(sn.classes[r].population)) out[L.qidx[i][r]] = 1.0;
577 continue;
578 }
579 const std::size_t np = L.kic[i][r];
580 for (std::size_t k = 0; k < np; ++k) {
581 double v = 0.0;
582 if (k < m.kir[r].size()) v = num_traits<T>::to_double(m.kir[r][k]);
583 if (k == 0 && !ext) {
584 // Phase one absorbs the waiting buffer: `nir - sum_{k>=2} kir`.
585 double served = 0.0;
586 for (std::size_t j = 1; j < m.kir[r].size(); ++j)
587 served += num_traits<T>::to_double(m.kir[r][j]);
588 v = num_traits<T>::to_double(m.nir[r]) - served;
589 }
590 // A Source reports nir = +Inf by the EXT sentinel; only its
591 // per-phase counts are a quantity, and those are finite.
592 if (!std::isfinite(v)) v = 0.0;
593 out[L.qidx[i][r] + k] = v;
594 }
595 any = true;
596 }
597 }
598 if (!any) return false;
599 y0.swap(out);
600 return true;
601}
602
603/** The initial condition itself: the declared state, else the placement above. */
604template <class T>
605std::vector<double> fluid_default_initsol(const qn::NetworkStruct<T>& sn, const FluidLayout& L) {
606 const std::size_t M = sn.nstations, K = sn.nclasses;
607 std::vector<double> y0(L.nstates, 0.0);
608 const std::vector<std::vector<double>> nplace = fluid_initsol_placement(sn, L);
609 if (fluid_declared_initsol(sn, L, nplace, y0)) return y0;
610 for (std::size_t r = 0; r < K; ++r) {
611 if (std::isfinite(sn.classes[r].population)) {
612 // Phase one of a block gets `nir - sum_{k>=2} kir`, and every job
613 // `initDefault` starts is in phase one, so that is the whole of the
614 // station's share of the population.
615 // The enabled guard is load-bearing for a Place: it holds a
616 // placement but no fluid block, and a disabled pair's `qidx` is the
617 // NEXT pair's start, so writing it would corrupt a neighbour.
618 for (std::size_t i = 0; i < M; ++i)
619 if (L.enabled[i][r] && nplace[i][r] > 0.0) y0[L.qidx[i][r]] = nplace[i][r];
620 } else {
621 // An open class holds the unit job pool at its source.
622 for (std::size_t i = 0; i < M; ++i)
623 if (L.enabled[i][r] && sn.stations[i].sched == lang::SchedStrategy::EXT)
624 y0[L.qidx[i][r]] = 1.0;
625 }
626 }
627 return y0;
628}
629
630} // namespace detail
631
632namespace detail {
633
634/**
635 * Snap numerical dust to zero, as `filterMetric` does with
636 * `outData(outData < FineTol) = 0`.
637 *
638 * A station a class never reaches still accumulates a few 1e-15 of mass from
639 * the integrator, and printing that as a queue length claims a presence the
640 * model does not have. The reference clears it, so a fluid table can be
641 * compared with an exact one without every unvisited cell reading as a
642 * mismatch.
643 */
644inline void fluid_snap_fine(Matrix<double>& m) {
645 for (std::size_t i = 0; i < m.rows(); ++i)
646 for (std::size_t j = 0; j < m.cols(); ++j)
647 if (std::fabs(m(i, j)) < lang::GlobalConstants::FineTol) m(i, j) = 0.0;
648}
649
650/**
651 * Snap the whole result set, then clear the response time wherever the
652 * throughput went with it.
653 *
654 * RespT is a RATIO of two dusty quantities, so it does not look small even
655 * when both of its operands do: 3e-15 over 3e-15 is 1, which would report a
656 * unit response time at a station the class never visits. Zeroing it with its
657 * throughput is what keeps the row consistent.
658 */
659inline void fluid_snap_all(Matrix<double>& q, Matrix<double>& u, Matrix<double>& r,
660 Matrix<double>& t) {
661 fluid_snap_fine(q);
662 fluid_snap_fine(u);
663 fluid_snap_fine(t);
664 fluid_snap_fine(r);
665 for (std::size_t i = 0; i < r.rows(); ++i)
666 for (std::size_t j = 0; j < r.cols(); ++j)
667 if (t(i, j) == 0.0 && q(i, j) == 0.0) r(i, j) = 0.0;
668}
669
670/**
671 * Mark the (station, class) pairs the model actually routes a job into, read
672 * off the per-chain visit ratios `sn.visits`.
673 *
674 * A fluid result cannot decide that question from the SIZE of QN or TN. Both
675 * carry a decaying remnant of the initial state, spread over pairs the class
676 * never reaches, and the remnant is whatever the integrator left behind when it
677 * stopped: measured at QN = 1.3e-12 and TN = 1.3e-13 on an older (no BMI2/ADX) host for
678 * `test_CQN_Cox_CS_7`, i.e. ABOVE `GlobalConstants::Zero`, so a threshold on
679 * them divides one remnant by the other and reports the station's own service
680 * time, 10.0000086, as a response time. The visit ratios come from the routing
681 * solve instead, where an unrouted pair is zero to the last bits (2.7e-17
682 * there). `visits` is indexed by STATEFUL node, hence `stateful_of_station`.
683 *
684 * A struct carrying no visit information decides nothing and every pair is
685 * reported visited. Mirrors `fluid_visited_pairs.m`.
686 */
687template <class T>
688std::vector<char> fluid_visited_pairs(const qn::NetworkStruct<T>& sn, std::size_t M, std::size_t K) {
689 std::vector<char> visited(M * K, 0);
690 bool have = false;
691 std::size_t max_cols = 0;
692 for (std::size_t c = 0; c < sn.visits.size(); ++c) {
693 const Matrix<T>& Vc = sn.visits[c];
694 if (Vc.rows() == 0 || Vc.cols() == 0) continue;
695 have = true;
696 max_cols = std::max(max_cols, Vc.cols());
697 for (std::size_t i = 0; i < M; ++i) {
698 const std::size_t isf = sn.stateful_of_station(i + 1);
699 if (isf == 0 || isf > Vc.rows()) {
700 for (std::size_t r = 0; r < K; ++r) visited[i * K + r] = 1;
701 continue;
702 }
703 for (std::size_t r = 0; r < K && r < Vc.cols(); ++r)
704 if (std::fabs(num_traits<T>::to_double(Vc(isf - 1, r))) >
706 visited[i * K + r] = 1;
707 }
708 }
709 if (!have) {
710 std::fill(visited.begin(), visited.end(), static_cast<char>(1));
711 } else {
712 // A class NO visit matrix reaches is not evidence of a non-visit, only of a
713 // struct whose visits were refreshed against fewer classes.
714 for (std::size_t i = 0; i < M; ++i)
715 for (std::size_t r = max_cols; r < K; ++r) visited[i * K + r] = 1;
716 }
717 return visited;
718}
719
720/**
721 * The analyzer-level correction `solver_fluid_analyzer.m:206-262` applies to
722 * EVERY method branch, after the switch.
723 *
724 * The per-method solvers report a utilization read straight off the fluid
725 * state: `sum(Xservice/mu)/S`, the server time the drift assigns to the class.
726 * That quantity is not a utilization -- it can exceed both 1 and the class's
727 * own mean population, because the drift's share is an instantaneous rate and
728 * not an occupancy. The reference restates it as the smallest of three
729 * quantities that each bound it from above: unity, the mean population per
730 * server, and the pre-correction total rescaled by the class's share of
731 * TN/rate, the share computed from the TRUE service rates rather than from the
732 * drift's approximation of them.
733 *
734 * Omitting this was worth 111% on `cqn_scheduling_dps`: DPS Queue2/Class2 read
735 * 0.2249 (its share of a saturated server) where the reference reports 0.1066
736 * (its mean population, which is the binding bound). Both were internally
737 * consistent, which is why it survived: the uncorrected value satisfies
738 * `U = X E[S]` exactly, and only disagrees with the reference.
739 *
740 * MATLAB's `min` over a vector SKIPS NaN, so a class whose rate is zero
741 * (0/0 in the share) must not poison the minimum; the NaN term is dropped, not
742 * propagated.
743 */
744template <class T>
745void fluid_analyzer_correct(const qn::NetworkStruct<T>& sn, const Matrix<double>& Q,
746 Matrix<double>& U, Matrix<double>& R, const Matrix<double>& T_) {
747 const std::size_t M = Q.rows(), K = Q.cols();
748 // A class the model never routes here has no response time, and QN alone
749 // does not say so -- see fluid_visited_pairs.
750 const std::vector<char> visited = fluid_visited_pairs(sn, M, K);
751 const Matrix<double> U0 = U;
752 for (std::size_t i = 0; i < M; ++i) {
753 double u0sum = 0.0, share_den = 0.0;
754 for (std::size_t r = 0; r < K; ++r) {
755 if (!(Q(i, r) > 0.0) || !visited[i * K + r]) continue;
756 u0sum += U0(i, r);
757 const double rate = num_traits<T>::to_double(sn.rates(i, r));
758 if (rate != 0.0) share_den += T_(i, r) / rate;
759 }
760 // A load-dependent station clears alpha(n) times the nominal work, so the
761 // bound that divides by its capacity has to divide by the PEAK scaling:
762 // Seff = max(c_i, max_n alpha_i(n)), the same T*S/peak convention
763 // `solver_ctmc_avg_from_pi` applies. Without load dependence Seff == c and
764 // every expression below is unchanged.
765 double c = sn.stations[i].nservers;
766 for (std::size_t k = 0; k < sn.stations[i].lldscaling.size(); ++k)
767 c = std::max(c, num_traits<T>::to_double(sn.stations[i].lldscaling[k]));
768 const bool is_delay = sn.stations[i].sched == lang::SchedStrategy::INF;
769 for (std::size_t r = 0; r < K; ++r) {
770 if (!(Q(i, r) > 0.0) || !visited[i * K + r]) {
771 U(i, r) = 0.0;
772 R(i, r) = 0.0;
773 continue;
774 }
775 if (is_delay) {
776 U(i, r) = Q(i, r);
777 continue;
778 }
779 double best = 1.0;
780 if (std::isfinite(c) && c > 0.0) best = std::min(best, Q(i, r) / c);
781 const double rate = num_traits<T>::to_double(sn.rates(i, r));
782 if (rate != 0.0 && share_den != 0.0)
783 best = std::min(best, u0sum * (T_(i, r) / rate) / share_den);
784 U(i, r) = best;
785 if (T_(i, r) != 0.0) R(i, r) = Q(i, r) / T_(i, r);
786 }
787 }
788 for (std::size_t i = 0; i < M; ++i)
789 for (std::size_t r = 0; r < K; ++r) {
790 if (std::isnan(U(i, r))) U(i, r) = 0.0;
791 if (std::isnan(R(i, r))) R(i, r) = 0.0;
792 }
793}
794
795} // namespace detail
796
797
798/**
799 * Read Q/U/R/T off ONE fluid state, for the closing family.
800 *
801 * Factored out because the transient needs exactly this at every point of the
802 * trajectory, and a second copy would drift from the steady-state one. `m` is
803 * the resolved method name: only `statedep` changes the rules here, and it does
804 * so at FCFS stations (see the mean-service-time share below).
805 */
806template <class T>
808 const std::string& m, const std::vector<double>& xs, Matrix<double>& Q,
810 const std::size_t M = sn.nstations, K = sn.nclasses;
811 const FluidLayout& L = sys.layout;
812 Q = Matrix<double>(M, K, 0.0);
813 U = Matrix<double>(M, K, 0.0);
814 R = Matrix<double>(M, K, 0.0);
815 T_ = Matrix<double>(M, K, 0.0);
816 // Queue length is the mass of the (station, class) block.
817 for (std::size_t i = 0; i < M; ++i)
818 for (std::size_t r = 0; r < K; ++r) {
819 double q = 0.0;
820 for (std::size_t k = 0; k < L.kic[i][r]; ++k) q += xs[L.qidx[i][r] + k];
821 Q(i, r) = q;
822 }
823
824 // Throughput, and the per-phase service mass the utilization is read from.
825 std::vector<std::vector<std::vector<double>>> xservice(M, std::vector<std::vector<double>>(K));
826 for (std::size_t i = 0; i < M; ++i) {
827 const lang::SchedStrategy sc = sn.stations[i].sched;
828 double xi = 0.0;
829 for (std::size_t r = 0; r < K; ++r) xi += Q(i, r);
830 double wxi = 0.0;
831 for (std::size_t r = 0; r < K; ++r)
832 wxi += (r < sn.stations[i].schedparam.size()
833 ? num_traits<T>::to_double(sn.stations[i].schedparam[r])
834 : 1.0) *
835 Q(i, r);
836 const double c = sn.stations[i].nservers;
837 // The capacity term psi(n) = min(n,c)*alpha(n), and not the bare min: a
838 // load-dependent station clears alpha(n) times the nominal work, so the
839 // bare min would drop the scaling from Tput and Util while the ODE applied
840 // it. With no load dependence `sys.lld[i]` is empty and this IS min(xi,c).
841 const double served = fluid_capacity_closure(xi, c, 0.0, sys.lld[i], false).h;
842
843 // `statedep` shares an FCFS server by MEAN SERVICE TIME, not by head
844 // count: a class that occupies a server for longer draws a larger share.
845 // `solver_fluid_closing.m` applies that weighting for this method only,
846 // and additionally overrides TN with sum(Xservice) -- i.e. WITHOUT the
847 // completion probability phi that every other branch carries.
848 const bool fcfs_statedep = (m == "statedep") && (sc == lang::SchedStrategy::FCFS);
849 std::vector<double> wmean(K, 0.0);
851 if (fcfs_statedep) {
852 for (std::size_t r = 0; r < K; ++r) {
853 if (!L.enabled[i][r]) continue;
855 const std::size_t nn = sn.service[i][r].D0.rows();
856 mp.D0 = Matrix<double>(nn, nn, 0.0);
857 mp.D1 = Matrix<double>(nn, nn, 0.0);
858 for (std::size_t a = 0; a < nn; ++a)
859 for (std::size_t bb = 0; bb < nn; ++bb) {
860 mp.D0(a, bb) = num_traits<T>::to_double(sn.service[i][r].D0(a, bb));
861 mp.D1(a, bb) = num_traits<T>::to_double(sn.service[i][r].D1(a, bb));
862 }
863 wmean[r] = mam::map_mean(mp);
864 wni += wmean[r] * Q(i, r);
865 }
866 }
867
868 for (std::size_t r = 0; r < K; ++r) {
869 xservice[i][r].assign(L.kic[i][r], 0.0);
870 if (!L.enabled[i][r]) continue;
871 std::vector<double> mu, phi;
872 detail::fluid_mu_phi(sn.service[i][r], mu, phi);
873 const std::size_t b = L.qidx[i][r], n = L.kic[i][r];
874 double tn = 0.0;
875 if (fcfs_statedep) {
876 for (std::size_t k = 0; k < n; ++k)
877 xservice[i][r][k] = xs[b + k] * mu[k] * wmean[r] / wni * served;
878 double s2 = 0.0;
879 for (std::size_t k = 0; k < n; ++k) s2 += xservice[i][r][k];
880 T_(i, r) = s2; // the reference's sum(Xservice) override
881 continue;
882 }
883 for (std::size_t k = 0; k < n; ++k) {
884 double mass = xs[b + k];
885 switch (sc) {
887 // The source holds unit mass: phase one carries the rest.
888 if (k == 0) {
889 double rest = 0.0;
890 for (std::size_t p = 1; p < n; ++p) rest += xs[b + p];
891 mass = 1.0 - rest;
892 }
893 tn += mass * mu[k] * phi[k];
894 xservice[i][r][k] = mass * mu[k];
895 break;
897 tn += mass * mu[k] * phi[k];
898 xservice[i][r][k] = mass * mu[k];
899 break;
901 const double w = r < sn.stations[i].schedparam.size()
902 ? num_traits<T>::to_double(sn.stations[i].schedparam[r])
903 : 1.0;
904 if (wxi > 0.0) {
905 tn += mass * mu[k] * phi[k] * w / wxi * served;
906 xservice[i][r][k] = mass * mu[k] * w / wxi * served;
907 }
908 break;
909 }
910 default: // PS, FCFS, SIRO and the rest share the servers
911 if (xi > 0.0) {
912 tn += mass * mu[k] * phi[k] / xi * served;
913 xservice[i][r][k] = mass * mu[k] / xi * served;
914 }
915 break;
916 }
917 }
918 T_(i, r) = tn;
919 }
920 }
921
922 // Utilization: the service mass divided by the phase rate is the time a
923 // server spends on it; a delay reports the queue length itself.
924 for (std::size_t i = 0; i < M; ++i) {
925 const bool is_delay = sn.stations[i].sched == lang::SchedStrategy::INF;
926 for (std::size_t r = 0; r < K; ++r) {
927 if (!L.enabled[i][r]) continue;
928 std::vector<double> mu, phi;
929 detail::fluid_mu_phi(sn.service[i][r], mu, phi);
930 double u = 0.0;
931 for (std::size_t k = 0; k < xservice[i][r].size(); ++k)
932 if (xservice[i][r][k] > 0.0 && mu[k] > 0.0) u += xservice[i][r][k] / mu[k];
933 // Divided by the PEAK scaling, Seff = max(c, max_n alpha(n)), which is
934 // c itself without load dependence.
935 double c = sn.stations[i].nservers;
936 for (std::size_t k = 0; k < sys.lld[i].size(); ++k) c = std::max(c, sys.lld[i][k]);
937 U(i, r) = (is_delay || !std::isfinite(c) || c <= 0.0) ? u : u / c;
938 }
939 }
940
941 // Response time by Little's law, which the reference also applies here.
942 for (std::size_t i = 0; i < M; ++i)
943 for (std::size_t r = 0; r < K; ++r)
944 if (T_(i, r) > 0.0) R(i, r) = Q(i, r) / T_(i, r);
945
946 // A Source and a Sink report no queue length, utilization or response
947 // time: `getAvgHandles` disables those three metric kinds there, which is
948 // the same rule the MVA runner's `filter_metric` applies. The fluid state
949 // does carry mass at an EXT source -- the unit job pool the drift needs --
950 // and reporting it would show a queue that does not exist. Throughput is
951 // kept, since that is the arrival rate.
952 for (std::size_t i = 0; i < M; ++i) {
953 const qn::NodeType nt = sn.stations[i].nodetype;
954 if (nt != qn::NodeType::Source && nt != qn::NodeType::Sink) continue;
955 for (std::size_t r = 0; r < K; ++r) {
956 Q(i, r) = 0.0;
957 U(i, r) = 0.0;
958 R(i, r) = 0.0;
959 }
960 }
961
962 detail::fluid_snap_all(Q, U, R, T_);
963}
964
965namespace detail {
966
967// ---------------------------------------------------------------------------
968// `solver_fluid_ratemult.m`: the time-varying per-event rate multiplier.
969// ---------------------------------------------------------------------------
970/**
971 * `local_nhpp_steps`: a step-faithful (time, rate) sampling of a
972 * piecewise-constant intensity over [t0, thi].
973 *
974 * Each segment contributes TWO samples, at its start and just before its end,
975 * so that the clamped-linear `fluid_interpcols` reproduces a STEP rather than a
976 * ramp between segment values. Sampling once per segment would interpolate
977 * across the whole segment and integrate an intensity the model never has.
978 */
979inline void fluid_nhpp_steps(const std::vector<double>& bp, const std::vector<double>& seg_rate,
980 bool cyclic, double t0, double thi, std::vector<double>& seg_t,
981 std::vector<double>& seg_r) {
982 seg_t.clear();
983 seg_r.clear();
984 if (bp.size() < 2 || seg_rate.empty() || !(thi > t0)) return;
985 const double period = bp.back() - bp.front();
986 std::vector<double> bounds;
987 bounds.push_back(t0);
988 if (cyclic && period > 0.0) {
989 const long kmax = static_cast<long>(std::ceil((thi - t0) / period)) + 2;
990 for (long k = -1; k <= kmax; ++k)
991 for (std::size_t a = 0; a < bp.size(); ++a)
992 bounds.push_back(bp[a] + static_cast<double>(k) * period);
993 } else {
994 for (std::size_t a = 0; a < bp.size(); ++a) bounds.push_back(bp[a]);
995 }
996 bounds.push_back(thi);
997 std::sort(bounds.begin(), bounds.end());
998 bounds.erase(std::remove_if(bounds.begin(), bounds.end(),
999 [&](double v) { return v < t0 || v > thi; }),
1000 bounds.end());
1001 bounds.erase(std::unique(bounds.begin(), bounds.end()), bounds.end());
1002 if (bounds.size() < 2) return;
1003
1004 // The rate in force on a segment, read at its MIDPOINT so a boundary never
1005 // decides which segment is sampled.
1006 const auto rate_at = [&](double t) -> double {
1007 double offset = t - bp.front();
1008 if (cyclic) {
1009 if (period > 0.0) {
1010 offset = std::fmod(offset, period);
1011 if (offset < 0.0) offset += period;
1012 } else {
1013 offset = 0.0;
1014 }
1015 } else if (offset < 0.0 || offset >= period) {
1016 return 0.0; // zero past a non-cyclic horizon, as the reference
1017 }
1018 const double pos = bp.front() + offset;
1019 std::size_t idx = seg_rate.size() - 1;
1020 for (std::size_t k = 1; k < bp.size(); ++k)
1021 if (pos < bp[k]) {
1022 idx = k - 1;
1023 break;
1024 }
1025 return idx < seg_rate.size() ? seg_rate[idx] : 0.0;
1026 };
1027
1028 const double neps = std::max(1e-9, 1e-6 * (thi - t0));
1029 for (std::size_t k = 0; k + 1 < bounds.size(); ++k) {
1030 const double a = bounds[k], b = bounds[k + 1];
1031 const double r = rate_at(0.5 * (a + b));
1032 seg_t.push_back(a);
1033 seg_r.push_back(r);
1034 seg_t.push_back(std::max(a + neps, b - neps));
1035 seg_r.push_back(r);
1036 }
1037}
1038
1039/** `local_merge`: elementwise product of two multipliers on the union grid. */
1040inline FluidRateMult fluid_ratemult_merge(const FluidRateMult& a, const FluidRateMult& b,
1041 std::size_t nevents) {
1042 if (a.empty()) return b;
1043 if (b.empty()) return a;
1044 std::vector<double> tg = a.tgrid;
1045 tg.insert(tg.end(), b.tgrid.begin(), b.tgrid.end());
1046 std::sort(tg.begin(), tg.end());
1047 tg.erase(std::unique(tg.begin(), tg.end()), tg.end());
1048 FluidRateMult out;
1049 out.tgrid = tg;
1050 out.Mmat = Matrix<double>(nevents, tg.size(), 1.0);
1051 std::vector<double> ca, cb;
1052 for (std::size_t j = 0; j < tg.size(); ++j) {
1053 fluid_interpcols(a.tgrid, a.Mmat, tg[j], ca);
1054 fluid_interpcols(b.tgrid, b.Mmat, tg[j], cb);
1055 for (std::size_t e = 0; e < nevents; ++e) {
1056 const double va = e < ca.size() ? ca[e] : 1.0;
1057 const double vb = e < cb.size() ? cb[e] : 1.0;
1058 out.Mmat(e, j) = va * vb;
1059 }
1060 }
1061 return out;
1062}
1063
1064/**
1065 * Whether the OPTIONS make the drift non-autonomous.
1066 *
1067 * This is a property of what the caller asked for, not of the model: the same
1068 * model is autonomous at its nominal and time-varying under `nhpp_sched`. It is
1069 * what `fluid_minnormal_applicable.m:99` consults to steer `default` away from
1070 * the moment closures, and what `fluid_moment_terms.m:114` raises on when one
1071 * was asked for by name.
1072 */
1073inline bool fluid_has_time_varying_rates(const FluidOptions& opt) {
1074 return !opt.rate_traj.empty() || !opt.nhpp_sched.empty() || !opt.rate_sched.empty();
1075}
1076
1077/** The events sourced at (station i, class c), both 0-based. */
1078inline std::vector<std::size_t> fluid_events_of(const FluidOdeSystem& sys, std::size_t i,
1079 std::size_t c) {
1080 std::vector<std::size_t> rows;
1081 const std::size_t lo = sys.layout.qidx[i][c];
1082 const std::size_t hi = lo + sys.layout.kic[i][c];
1083 for (std::size_t e = 0; e < sys.events.size(); ++e)
1084 if (sys.events[e].event_idx >= lo && sys.events[e].event_idx < hi) rows.push_back(e);
1085 return rows;
1086}
1087
1088/** One (station, class) trajectory expanded onto the event rows. */
1089inline FluidRateMult fluid_ratemult_rows(const FluidOdeSystem& sys, std::size_t i, std::size_t c,
1090 const std::vector<double>& seg_t,
1091 const std::vector<double>& seg_r, double nominal) {
1092 FluidRateMult out;
1093 if (seg_t.empty() || !(nominal > 0.0)) return out;
1094 const std::vector<std::size_t> rows = fluid_events_of(sys, i, c);
1095 if (rows.empty()) return out;
1096 out.tgrid = seg_t;
1097 out.Mmat = Matrix<double>(sys.events.size(), seg_t.size(), 1.0);
1098 for (std::size_t j = 0; j < seg_t.size(); ++j)
1099 for (std::size_t e : rows) out.Mmat(e, j) = seg_r[j] / nominal;
1100 return out;
1101}
1102
1103/**
1104 * Port of `solver_fluid_ratemult.m`: compose the three time-varying sources into
1105 * one per-event multiplier, or return an empty one when none is configured.
1106 *
1107 * REFERENCE SCALE MISMATCH, reproduced deliberately. The nominal the multiplier
1108 * divides by is `Mu{i}{c}(1)`, the FIRST PHASE RATE of the process, while the
1109 * numerator is `getRateAt(t)`, which for a MAPt is `map_lambda` of the segment,
1110 * i.e. a STATIONARY ARRIVAL rate. The two coincide for an NHPP, where the
1111 * process has one phase and the phase rate IS the arrival rate, and that is the
1112 * case the reference documents and uses. For a multi-phase MAPt they are
1113 * different quantities and the multiplier is off by their ratio. Ported as
1114 * written, because parity is the contract; flagged here and in
1115 * `_kb/06-solver-catalog.md` rather than silently corrected.
1116 */
1117template <class T>
1118FluidRateMult fluid_ratemult(const qn::NetworkStruct<T>& sn, const FluidOdeSystem& sys,
1119 const FluidOptions& opt) {
1120 const std::size_t nev = sys.events.size();
1121 FluidRateMult out;
1122 if (!opt.rate_traj.empty()) {
1123 if (opt.rate_traj.Mmat.rows() != nev)
1124 throw InputError("solver_fluid_ratemult: rate_traj has " +
1125 std::to_string(opt.rate_traj.Mmat.rows()) +
1126 " rows but the closing ODE has " + std::to_string(nev) + " events");
1127 out = opt.rate_traj;
1128 }
1129
1130 // The horizon a (possibly cyclic) schedule is expanded over. An unbounded
1131 // timespan takes a few periods, so a cycle is REPRESENTED rather than
1132 // clamped after its first segment.
1133 double t0 = 0.0;
1134 const double tend = opt.timespan_end;
1135
1136 FluidRateMult nh;
1137 for (std::size_t a = 0; a < opt.nhpp_sched.size(); ++a) {
1138 const std::size_t i = opt.nhpp_sched[a].first - 1, c = opt.nhpp_sched[a].second - 1;
1139 if (i >= sn.nstations || c >= sn.nclasses) continue;
1140 if (!sys.layout.enabled[i][c]) continue;
1141 const lang::Distrib<T>& d = sn.service[i][c];
1142 if (!d.has_schedule()) continue;
1143 const std::vector<T> mu = d.mu_vec();
1144 if (mu.empty()) continue;
1145 const double nominal = num_traits<T>::to_double(mu[0]);
1146 if (!(nominal > 0.0)) continue;
1147
1148 std::vector<double> bp, seg_r;
1149 for (std::size_t k = 0; k < d.sched_bp.size(); ++k)
1150 bp.push_back(num_traits<T>::to_double(d.sched_bp[k]));
1151 // `getRateAt`: the stationary arrival rate of the segment's pair, which
1152 // for a one-phase process is that phase's rate.
1153 for (std::size_t k = 0; k < d.sched_D0.size(); ++k) {
1154 mam::Map<T> m;
1155 m.D0 = d.sched_D0[k];
1156 m.D1 = d.sched_D1[k];
1157 seg_r.push_back(num_traits<T>::to_double(mam::map_lambda(m)));
1158 }
1159 const double period = bp.empty() ? 0.0 : bp.back() - bp.front();
1160 double thi = tend;
1161 if (!std::isfinite(thi))
1162 thi = (std::isfinite(period) && period > 0.0) ? t0 + 3.0 * period : t0 + 1.0;
1163 std::vector<double> seg_t, seg_v;
1164 fluid_nhpp_steps(bp, seg_r, d.sched_cyclic, t0, thi, seg_t, seg_v);
1165 nh = fluid_ratemult_merge(nh, fluid_ratemult_rows(sys, i, c, seg_t, seg_v, nominal), nev);
1166 }
1167
1168 FluidRateMult rs;
1169 for (std::size_t a = 0; a < opt.rate_sched.size(); ++a) {
1170 const FluidOptions::RateSched& e = opt.rate_sched[a];
1171 const std::size_t i = e.station - 1, c = e.cls - 1;
1172 if (i >= sn.nstations || c >= sn.nclasses) continue;
1173 if (!sys.layout.enabled[i][c]) continue;
1174 if (e.tgrid.size() != e.rates.size() || e.tgrid.empty())
1175 throw InputError("solver_fluid_ratemult: rate_sched tgrid and rates must be "
1176 "non-empty and of equal length");
1177 double nominal = e.nominal;
1178 if (!(nominal > 0.0)) {
1179 const std::vector<T> mu = sn.service[i][c].mu_vec();
1180 if (mu.empty()) continue;
1181 nominal = num_traits<T>::to_double(mu[0]);
1182 }
1183 if (!(nominal > 0.0)) continue;
1184 rs = fluid_ratemult_merge(rs, fluid_ratemult_rows(sys, i, c, e.tgrid, e.rates, nominal),
1185 nev);
1186 }
1187
1188 out = fluid_ratemult_merge(out, nh, nev);
1189 out = fluid_ratemult_merge(out, rs, nev);
1190 return out;
1191}
1192
1193/**
1194 * `slowrate` of the reference: the smallest phase rate among the service
1195 * processes the layout enables, which is what sets every integration horizon
1196 * here. Finite rates above `tol` only, falling back to 1 when the model has
1197 * none, exactly as `solver_fluid.m` does.
1198 */
1199template <class T>
1200double fluid_slow_rate(const qn::NetworkStruct<T>& sn, const FluidLayout& L, double tol) {
1201 double min_rate = std::numeric_limits<double>::infinity();
1202 for (std::size_t i = 0; i < sn.nstations; ++i)
1203 for (std::size_t r = 0; r < sn.nclasses; ++r) {
1204 if (!L.enabled[i][r]) continue;
1205 const lang::Distrib<T>& d = sn.service[i][r];
1206 for (std::size_t k = 0; k < d.D0.rows(); ++k) {
1207 const double mu = -num_traits<T>::to_double(d.D0(k, k));
1208 if (mu > tol && std::isfinite(mu)) min_rate = std::min(min_rate, mu);
1209 }
1210 }
1211 return std::isfinite(min_rate) ? min_rate : 1.0;
1212}
1213
1214/**
1215 * The method switch of `solver_fluid_analyzer.m`, without its trailing
1216 * correction. Kept separate so the correction below runs on EVERY branch, as
1217 * it does in the reference; folding it into each branch's exit would repeat it
1218 * six times and let one path drift.
1219 *
1220 * Refuses by name anything the port does not cover, rather than returning a
1221 * number computed by the wrong model.
1222 */
1223template <class T>
1224FluidSolution fluid_dispatch(const qn::NetworkStruct<T>& sn, const FluidOptions& opt) {
1225 if (!std::is_same<T, double>::value)
1226 throw UnsupportedError(ErrorKind{"Arithmetic"},
1227 "solver_fluid: the fluid solver integrates its drift with LSODA, whose coefficients "
1228 "assume double precision; rerun with --arith double");
1229 // `fluid.<name>` is the same method under its qualified spelling.
1230 std::string m = opt.method;
1231 if (m.compare(0, 4, "fld.") == 0) m = m.substr(4);
1233 bool statedep_family = false;
1234 // `solver_fluid_analyzer.m` routes default, matrix AND pnorm to
1235 // solver_fluid_matrix -- `ode_pnorm.m` is never reached under the name
1236 // `pnorm`, so pnorm here means "the matrix method with p-norm smoothing".
1237 // `@@SolverFLD/runAnalyzer.m` resolves the method BEFORE the analyzer sees
1238 // it, and the resolution depends on the model, not just the name:
1239 // a Cache -> rmf
1240 // a DPS station -> closing (the matrix method cannot express DPS)
1241 // otherwise -> matrix
1242 // and `matrix`/`pnorm` asked for EXPLICITLY on a DPS model is an error, not
1243 // a silent downgrade. Without this gate the C++ ran matrix on a DPS model
1244 // and redistributed the population differently from every other codebase.
1245 bool has_dps = false, has_cache = false;
1246 for (const auto& st : sn.stations)
1247 if (st.sched == lang::SchedStrategy::DPS) has_dps = true;
1248 for (const qn::NodeDef& nd : sn.nodes)
1249 if (nd.nodetype == qn::NodeType::Cache) has_cache = true;
1250 if ((m == "matrix" || m == "pnorm") && has_dps)
1251 throw UnsupportedError(ErrorKind{"SchedStrategy_DPS"},
1252 "solver_fluid: the matrix method does not support DPS scheduling; use method "
1253 "'closing' (which is what 'default' selects on a DPS model)");
1254 if (m == "default") {
1255 if (has_cache)
1256 throw UnsupportedError(ErrorKind{"Cache"},
1257 "solver_fluid: a Cache model resolves to the 'rmf' fluid method, which is ported "
1258 "in fluid_cacheqn.h and reached through solver_fluid_run_analyzer (fluid_runner.h); this "
1259 "function is solver_fluid_analyzer alone and cannot call it without a cyclic "
1260 "include");
1261 if (has_dps) m = "closing";
1262 }
1263 const bool matrix_family = (m == "default" || m == "matrix" || m == "pnorm");
1264 if (m == "statedep") {
1265 statedep_family = true;
1266 sd_kind = StateDepKind::StateDep;
1267 } else if (m == "softmin") {
1268 statedep_family = true;
1269 sd_kind = StateDepKind::SoftMin;
1270 } else if (!(matrix_family || m == "closing" || m == "tbi" || m == "diffusion" || m == "mfq")) {
1271 throw UnsupportedError(ErrorKind{"Method"}, "solver_fluid: the '" + opt.method +
1272 "' fluid method is not solved here; available are 'closing', "
1273 "'statedep', 'softmin', 'pnorm', 'matrix', 'tbi', 'diffusion' and "
1274 "'mfq', while 'rmf', 'minnormal', 'mnrefined', 'dae' and 'kp' are "
1275 "reached through solver_fluid_run_analyzer (fluid_runner.h), which is the "
1276 "port of runAnalyzer's resolution");
1277 }
1278
1279 const std::size_t M = sn.nstations, K = sn.nclasses;
1280 FluidOdeSystem sys = fluid_ode_system(sn);
1281 // The moment closure travels on the options, so it reaches the drift through
1282 // the SAME system the metrics are read from; `solver_fluid_moments` is the
1283 // only caller that fills it and an empty one is the first-order drift.
1284 sys.closure = opt.closure;
1285 // `solver_fluid_odes.m:127-134`: the time-varying rate multiplier is built
1286 // once, beside the drift it scales, and an empty one leaves the autonomous
1287 // closure exactly as it was.
1288 sys.ratemult = detail::fluid_ratemult(sn, sys, opt);
1289 const FluidLayout& L = sys.layout;
1290 if (L.nstates == 0)
1291 throw InputError("solver_fluid: no station serves any class, so the drift is empty");
1292
1293 // ---- the slowest rate sets the integration horizon --------------------
1294 const double min_rate = fluid_slow_rate(sn, L, opt.tol);
1295
1296 // ---- integrate, restarting from the previous end state ----------------
1297 std::vector<double> x = opt.init_sol.empty() ? detail::fluid_default_initsol(sn, L) : opt.init_sol;
1298 if (x.size() != L.nstates)
1299 throw InputError("solver_fluid: init_sol has " + std::to_string(x.size()) +
1300 " entries but the fluid state has " + std::to_string(L.nstates));
1301
1302 // ---- the exact single Markov-modulated fluid queue --------------------
1303 if (m == "mfq") {
1304 // `solver_fluid_analyzer.m` tries the AoI topology FIRST, because it is
1305 // the more specific one: a capacity-1 or capacity-2 single queue is
1306 // also a single queue, and the age laws are what that model is for.
1307 const AoiTopology atop = aoi_is_aoi(sn);
1308 if (atop.ok) {
1309 const FluidAoiResult ar = fluid_aoi(sn, atop, opt.aoi_preemption);
1310 FluidSolution out;
1311 out.iters = 1;
1312 out.method = "mfq";
1313 out.has_aoi = true;
1314 out.aoi = ar.age;
1315 out.QN = Matrix<double>(M, K, 0.0);
1316 out.UN = Matrix<double>(M, K, 0.0);
1317 out.RN = Matrix<double>(M, K, 0.0);
1318 out.TN = Matrix<double>(M, K, 0.0);
1319 out.XN.assign(K, 0.0);
1320 out.CN.assign(K, 0.0);
1321 for (std::size_t r = 0; r < K; ++r) {
1322 out.QN(atop.queue, r) = ar.QN[r];
1323 out.UN(atop.queue, r) = ar.UN[r];
1324 out.RN(atop.queue, r) = ar.RN[r];
1325 out.TN(atop.queue, r) = ar.TN[r];
1326 // the source offers lambda; the queue delivers TN <= lambda
1327 out.TN(atop.source, r) = (r == atop.cls) ? ar.lambda : 0.0;
1328 out.XN[r] = out.TN(atop.source, r); // TN at the reference station, as MATLAB
1329 out.CN[r] = ar.RN[r];
1330 }
1331 return out;
1332 }
1333
1334 // `fluid_mfq_admits` is the ONE predicate deciding the shape, shared with
1335 // `fluid_resolve_method`: off it the reference warns "MFQ not
1336 // applicable" and re-enters the matrix method, and so does this port.
1337 // This port has no line_warning channel (see mva_dispatch.h), so the
1338 // substitution is visible in `method`, which reports "matrix".
1339 if (!fluid_mfq_admits(sn).ok) {
1340 FluidOptions mopt = opt;
1341 mopt.method = "matrix";
1342 return fluid_dispatch(sn, mopt);
1343 }
1344 const MfqTopology top = mfq_is_single_queue(sn);
1345 // Distinct priorities among the open classes send the model to the
1346 // fluid PRIORITY queue instead of the single fluid-fluid queue.
1347 bool mixed_prio = false;
1348 if (top.ok)
1349 for (std::size_t j = 1; j < top.open_classes.size(); ++j)
1350 if (sn.classes[top.open_classes[j]].prio != sn.classes[top.open_classes[0]].prio)
1351 mixed_prio = true;
1352 if (mixed_prio) {
1353 const MfqPrioResult pr = fluid_mfq_prio(sn, top, opt.tol);
1354 if (pr.fallback) {
1355 // The reference warns and runs the matrix method instead.
1356 FluidOptions fb = opt;
1357 fb.method = "matrix";
1358 return solver_fluid(sn, fb);
1359 }
1360 FluidSolution out;
1361 out.iters = 1;
1362 out.method = "mfq";
1363 out.QN = Matrix<double>(M, K, 0.0);
1364 out.UN = Matrix<double>(M, K, 0.0);
1365 out.RN = Matrix<double>(M, K, 0.0);
1366 out.TN = Matrix<double>(M, K, 0.0);
1367 out.XN.assign(K, 0.0);
1368 out.CN.assign(K, 0.0);
1369 for (std::size_t r = 0; r < K; ++r) {
1370 out.QN(top.queue, r) = pr.QN[r];
1371 out.TN(top.queue, r) = pr.TN[r];
1372 out.TN(top.source, r) = pr.TN[r];
1373 out.XN[r] = pr.TN[r];
1374 }
1375 // RAW metrics, as solver_mfq_prio.m returns them: the analyzer's
1376 // post-processing (UN capped by the fluid level and shared by load,
1377 // RN = QN/TN, UN = QN at an INF station) is fluid_analyzer_correct,
1378 // which solver_fluid applies to every dispatch. Applying it here too
1379 // corrected twice: the second pass summed the CAPPED UN of the first
1380 // and cut every other class's share (0.127 for 0.22 on a 3-class model).
1381 const bool inf = sn.stations[top.queue].sched == lang::SchedStrategy::INF;
1382 for (std::size_t r = 0; r < K; ++r) {
1383 out.UN(top.queue, r) = pr.UN[r];
1384 out.RN(top.queue, r) = pr.RN[r];
1385 if (pr.QN[r] > 0.0) out.CN[r] = inf ? pr.RN[r] : pr.QN[r] / pr.TN[r];
1386 }
1387 return out;
1388 }
1389 // Admitted by the reference's node-level test but not by the stricter
1390 // station-level topology this solver builds (a Delay beside the queue, a
1391 // closed class): the matrix method answers, as it always did here.
1392 if (!top.ok) {
1393 FluidOptions mopt = opt;
1394 mopt.method = "matrix";
1395 return fluid_dispatch(sn, mopt);
1396 }
1397 const MfqResult r = fluid_mfq(sn, top, opt.tol);
1398 FluidSolution out;
1399 out.iters = 1; // solved, not iterated
1400 out.method = "mfq";
1401 out.QN = Matrix<double>(M, K, 0.0);
1402 out.UN = Matrix<double>(M, K, 0.0);
1403 out.RN = Matrix<double>(M, K, 0.0);
1404 out.TN = Matrix<double>(M, K, 0.0);
1405 out.QN(top.queue, top.cls) = r.QN;
1406 out.UN(top.queue, top.cls) = r.UN;
1407 out.RN(top.queue, top.cls) = r.RN;
1408 out.TN(top.queue, top.cls) = r.TN;
1409 out.TN(top.source, top.cls) = r.TN; // the Source reports its arrivals
1410 out.XN.assign(K, 0.0);
1411 out.CN.assign(K, 0.0);
1412 out.XN[top.cls] = r.TN;
1413 out.CN[top.cls] = r.RN;
1414 return out;
1415 }
1416
1417 // ---- the diffusion approximation: a stochastic trajectory -------------
1418 if (m == "diffusion") {
1419 DiffusionOptions dopt;
1420 // the horizon is timespan_end, never iter_max: see fluid_diffusion.h
1421 if (std::isfinite(opt.timespan_end) && opt.timestep > 0.0)
1422 dopt.steps = std::max<std::size_t>(2, static_cast<std::size_t>(std::ceil(opt.timespan_end / opt.timestep)));
1423 dopt.dt = opt.timestep;
1424 dopt.seed = opt.seed;
1425 const DiffusionResult dr = fluid_diffusion(sn, dopt);
1426 FluidSolution out;
1427 out.iters = 1; // a single trajectory
1428 out.method = "diffusion";
1429 out.QN = dr.QN;
1430 out.UN = dr.UN;
1431 out.RN = dr.RN;
1432 out.TN = dr.TN;
1433 detail::fluid_snap_all(out.QN, out.UN, out.RN, out.TN);
1434 out.XN.assign(K, 0.0);
1435 out.CN.assign(K, 0.0);
1436 for (std::size_t r = 0; r < K; ++r) {
1437 const std::size_t rs = sn.classes[r].refstat;
1438 if (rs >= 1 && rs <= M) out.XN[r] = out.TN(rs - 1, r);
1439 double q = 0.0;
1440 for (std::size_t i = 0; i < M; ++i) q += out.QN(i, r);
1441 if (out.XN[r] > 0.0) out.CN[r] = q / out.XN[r];
1442 }
1443 return out;
1444 }
1445
1446 LsodaOptions lopt;
1447 lopt.rtol = opt.tol;
1448 lopt.atol = opt.tol;
1449
1450 // ---- the matrix method: one generator, one integration ----------------
1451 if (matrix_family) {
1452 // `pnorm` is the matrix method with the smoothing switched on; plain
1453 // `matrix`/`default` leave pstar at zero, which selects the hard min,
1454 // unless the caller asked for the smoothing explicitly.
1455 const double ps = (m == "pnorm" || opt.pstar_set) ? opt.pstar : 0.0;
1456 const FluidMatrixSystem ms = fluid_matrix_system(sn, x, ps);
1457 const std::function<void(double, const double*, double*)> mdrift = fluid_matrix_drift(ms);
1458 const double t1 =
1459 std::min(opt.timespan_end,
1460 10.0 * static_cast<double>(opt.iter_max) / ms.min_rate);
1461 std::vector<double> xm = fluid_integrate_leg(mdrift, 0.0, t1, ms.x0, lopt);
1462 for (double& v : xm)
1463 if (v < 0.0) v = 0.0;
1464
1465 // DEGENERATE DRIFT: re-integrate with a closed saturation term, do not
1466 // touch the answer that came back. min(E[n], c) is FLAT above the server
1467 // count, so a network of saturated stations has a CONTINUUM of fixed
1468 // points and this method returns whichever one the integrator stopped at
1469 // -- [9 1] against an exact [5 5] on two identical saturated stations in
1470 // a closed cycle, and [8 2] with two servers each. The repair is applied
1471 // to the DRIFT, not to the point: the same trajectory is integrated again
1472 // with E[min(n, c)] in place of min(E[n], c), which is strictly
1473 // increasing and so isolates one fixed point.
1474 //
1475 // WHY A CLOSURE AND NOT A SMOOTHED min: any smoothing sharp enough to
1476 // stay faithful to min away from the kink is numerically FLAT far from
1477 // it. The Boltzmann softmin at alpha = 20 carries a restoring force of
1478 // exp(-160) at the [9 1] point, and the p-norm trades the two off
1479 // directly (pstar = 2 recovers [5 5], pstar = 128 gives [8.94 1.06]).
1480 // The closure escapes the trade-off because its slope comes from the
1481 // VARIANCE of the marginal rather than from a smoothing width.
1482 //
1483 // Only a model that is ACTUALLY degenerate pays for it, so a well-posed
1484 // model integrates once and is unchanged.
1485 FluidMatrixSystem msr = ms;
1486 if (ps <= 0.0 && fluid_matrix_degenerate(ms, mdrift, xm, K)) {
1487 msr.var_closure = true;
1488 const std::function<void(double, const double*, double*)> cdrift =
1489 fluid_matrix_drift(msr);
1490 std::vector<double> xc = fluid_integrate_leg(cdrift, 0.0, t1, ms.x0, lopt);
1491 bool finite = xc.size() == xm.size();
1492 for (std::size_t a = 0; finite && a < xc.size(); ++a)
1493 if (!std::isfinite(xc[a])) finite = false;
1494 if (finite) {
1495 for (double& v : xc)
1496 if (v < 0.0) v = 0.0;
1497 xm = xc;
1498 } else {
1499 // A failed repair leaves the unrepaired answer standing rather
1500 // than turning a wrong number into no number.
1501 msr.var_closure = false;
1502 }
1503 }
1504
1505 // The same share the drift used, smoothed, closed or neither
1506 std::vector<double> theta(ms.nstates, 0.0);
1507 detail::fluid_matrix_theta(msr, xm.data(), theta);
1508
1509 FluidSolution out;
1510 out.iters = 1; // a single integration, unlike the closing iteration
1511 out.method = (m == "pnorm") ? "pnorm" : "matrix";
1512 out.xvec = xm;
1513 out.QN = Matrix<double>(M, K, 0.0);
1514 out.UN = Matrix<double>(M, K, 0.0);
1515 out.RN = Matrix<double>(M, K, 0.0);
1516 out.TN = Matrix<double>(M, K, 0.0);
1517 for (std::size_t i = 0; i < M; ++i)
1518 for (std::size_t r = 0; r < K; ++r) {
1519 double q = 0.0, u = 0.0, t = 0.0;
1520 for (std::size_t a = 0; a < ms.nstates; ++a) {
1521 q += ms.sqc(i * K + r, a) * xm[a];
1522 u += ms.suc(i * K + r, a) * theta[a];
1523 t += ms.stc(i * K + r, a) * theta[a];
1524 }
1525 out.QN(i, r) = q;
1526 // An infinite server reports the queue length itself as its
1527 // utilization -- there is no capacity to divide by. The SUC map
1528 // carries 1/S with S substituted by the closed population, so
1529 // the delay rows have to be restated here, exactly as
1530 // `solver_fluid.m` does for its UNt.
1531 out.UN(i, r) =
1532 (sn.stations[i].sched == lang::SchedStrategy::INF ||
1533 !std::isfinite(sn.stations[i].nservers))
1534 ? q
1535 : u;
1536 out.TN(i, r) = t;
1537 // Little's law, as the reference -- but TN is zero only to the
1538 // integrator's accuracy, so a class that never visits leaves a
1539 // residue in q and t alike and a strict > 0 test divides one by
1540 // the other. See solver_fluid_analyzer.m.
1541 if (t > lang::GlobalConstants::Zero) out.RN(i, r) = q / t;
1542 }
1543 // A Source reports arrivals only. Its states are held at zero with
1544 // theta = 0, so STC*theta gives it no throughput at all; the reference
1545 // still shows the arrival rate there, so it is restated from the rates
1546 // that were injected into the downstream queues.
1547 for (std::size_t i = 0; i < M; ++i) {
1548 const qn::NodeType nt = sn.stations[i].nodetype;
1549 if (nt != qn::NodeType::Source && nt != qn::NodeType::Sink) continue;
1550 for (std::size_t r = 0; r < K; ++r) {
1551 out.QN(i, r) = 0.0;
1552 out.UN(i, r) = 0.0;
1553 out.RN(i, r) = 0.0;
1554 if (nt == qn::NodeType::Source && ms.src_arrival.rows() == M)
1555 out.TN(i, r) = ms.src_arrival(i, r);
1556 }
1557 }
1558 detail::fluid_snap_all(out.QN, out.UN, out.RN, out.TN);
1559 out.XN.assign(K, 0.0);
1560 out.CN.assign(K, 0.0);
1561 for (std::size_t r = 0; r < K; ++r) {
1562 const std::size_t rs = sn.classes[r].refstat;
1563 if (rs >= 1 && rs <= M) out.XN[r] = out.TN(rs - 1, r);
1564 double q = 0.0;
1565 for (std::size_t i = 0; i < M; ++i) q += out.QN(i, r);
1566 if (out.XN[r] > 0.0) out.CN[r] = q / out.XN[r];
1567 }
1568 return out;
1569 }
1570
1571 // THE PASS LOOP BELOW RESTARTS THE INTEGRATOR ONCE PER PASS, so its local
1572 // error is paid iter_max times over and lands on a state that is already at
1573 // the fixed point. At the nominal tol = 1e-4 that accumulated to 3.3e-4 on
1574 // oqn_basic -- Queue1 QLen 0.10023962 where MATLAB, the JAR and native
1575 // Python all return 0.10020646880565 -- which reads as a DIFFERENT fluid
1576 // fixed point and is nothing of the kind: the same run at 1e-6 reproduces
1577 // the reference to the last digit. So the integrator runs at tol/iter_max
1578 // while `opt.tol` stays what the caller asked of the FIXED POINT, which is
1579 // the quantity that tolerance names. The single-integration matrix family
1580 // above is exempt because nothing is restarted there, and so is
1581 // `solver_fluid_transient` below, which integrates one grid in one call.
1582 lopt.rtol = lopt.atol =
1583 opt.tol / std::max<double>(1.0, static_cast<double>(opt.iter_max));
1584
1585 // `ode_eliminate_immediate` is applied to the CLOSING drift only, which is
1586 // the `otherwise` arm of `solver_fluid_odes.m` where the reference applies
1587 // it: the state-dependent drifts are not a jump/rate system and `tbi`
1588 // partitions the unreduced one.
1589 FluidOdeSystem dsys = sys;
1590 FluidImmediateResult imm_result;
1591 if (fluid_hide_immediate(sn, opt) && !statedep_family) {
1592 imm_result = fluid_eliminate_immediate(sn, sys);
1593 if (imm_result.eliminated) {
1594 dsys = imm_result.sys;
1595 // A complemented coordinate receives no transitions at all, so mass left
1596 // there would sit stranded rather than be integrated. It is PROJECTED, not
1597 // zeroed: those are jobs, and a cold start puts none there but a warm start
1598 // from an earlier LN iterate does.
1599 std::vector<double> xp(x.size(), 0.0);
1600 for (std::size_t f = 0; f < x.size() && f < imm_result.absorb.rows(); ++f)
1601 for (std::size_t sidx = 0; sidx < x.size() && sidx < imm_result.absorb.cols();
1602 ++sidx)
1603 xp[sidx] += x[f] * imm_result.absorb(f, sidx);
1604 for (std::size_t a = 0; a < x.size(); ++a) x[a] = xp[a];
1605 }
1606 }
1607
1608 const std::function<void(double, const double*, double*)> drift =
1609 statedep_family ? fluid_drift_statedep(fluid_statedep_system(sn, sd_kind, opt.softmin_alpha,
1610 opt.pstar))
1611 : fluid_drift(dsys);
1612
1613 const std::vector<std::vector<std::size_t>> tbi_cells =
1614 (m != "tbi") ? std::vector<std::vector<std::size_t>>()
1615 : opt.tbi_cells.empty() ? tbi_partition(sn, opt.tbi_cellsize)
1616 : tbi_check_partition(sn, opt.tbi_cells);
1617 // Early stop on the GEOMETRIC TAIL of the window iteration; see the header.
1618 // The residual cannot go below the integrator's own error, so a request for
1619 // less than `tol` asks for something unobservable.
1620 const double drift_tol = std::max(opt.iter_tol, opt.tol);
1621 const double drift_safety = 0.01; // headroom, since rho is estimated
1622 const double min_horizon = 10.0 / min_rate;
1623 double moved_prev = std::numeric_limits<double>::infinity();
1624 std::vector<double> rho_hist(3, std::numeric_limits<double>::quiet_NaN());
1625 int drift_below = 0;
1626 std::vector<double> drift_buf(x.size(), 0.0);
1627
1628 double t0 = 0.0;
1629 std::size_t iter = 0;
1630 for (; iter < opt.iter_max; ++iter) {
1631 // Wall-clock budget (options.timeout), read after the first window, as
1632 // `solver_fluid_iteration.m`: the last integrated state is the interim one.
1633 if (iter > 0 && util::timeout_exceeded()) break;
1634 const double horizon = 10.0 * static_cast<double>(iter + 1) / min_rate;
1635 const double t1 = std::min(opt.timespan_end, horizon);
1636 if (!(t1 > t0)) break;
1637 const std::vector<double> prev = x;
1638 // A FIXED POINT ENDS THE WINDOW IN CLOSED FORM, and this is what keeps a
1639 // window that has already converged from becoming a window that never
1640 // returns. Armed only for an AUTONOMOUS drift, so f(x*) = 0 means
1641 // x(t) = x* for every later t and the rest of the span is known exactly
1642 // rather than integrated.
1643 //
1644 // THE THRESHOLD IS ROUND-OFF, NOT `drift_tol`. That tolerance (1e-4 by
1645 // default) says "converged to what the caller asked for", and a state
1646 // that merely satisfies it is still moving -- cutting the window there
1647 // was measured to shift results by 1.8e-5 in the Python twin. A
1648 // normalized residual below GlobalConstants::Zero is the stronger claim
1649 // that the drift is zero to double precision, which is what makes
1650 // skipping the remaining span exact instead of approximate.
1651 //
1652 // WHY THE WINDOW DOES NOT END ON ITS OWN. A stiff step controller handed
1653 // a state it is already at cannot pick a step: on the LN layer of
1654 // test_LQN_13 the Python twin advanced t by 0.011 in 20000 steps from a
1655 // state with |f| = 1.5e-16, and covered the whole 1000-unit span in 60
1656 // steps once that state was nudged 1e-6 off the equilibrium. That layer
1657 // carries an Immediate() coordinate -- an eigenvalue of exactly
1658 // -GlobalConstants::Immediate = -1e8 that the immediate elimination did
1659 // not fold out -- so the controller is pinned near 1/1e8 while the
1660 // window runs to 10*iter/min_rate. 272 windows took 3.0 s between them
1661 // and the 273rd had not returned after 143 s.
1662 // A FINITE timespan is a transient request, which must reach its end time
1663 // rather than stop at the fixed point -- the same gate the geometric-tail
1664 // test below carries.
1665 const bool fp_armed = opt.earlystop && !std::isfinite(opt.timespan_end)
1666 && !fluid_has_time_varying_rates(opt);
1667 if (fp_armed) {
1668 drift(t0, x.data(), drift_buf.data());
1669 double dn = 0.0, dtot = 0.0;
1670 for (std::size_t i = 0; i < x.size(); ++i) {
1671 dn += std::fabs(drift_buf[i]);
1672 dtot += x[i];
1673 }
1674 if (dtot > 0.0 && dn / 2.0 / dtot / min_rate < lang::GlobalConstants::Zero) {
1675 t0 = t1;
1676 ++iter;
1677 break;
1678 }
1679 }
1680 // THE TEST ABOVE IS TAKEN ONCE, at the window's first instant. A window
1681 // that reaches the fixed point AFTER its first step is the same stall
1682 // entered one step later, and nothing above catches it, so the SAME test
1683 // rides on the integrator as a per-accepted-step stop. That is where
1684 // MATLAB's OutputFcn chain and the native-Python step loop take it, so
1685 // the four codebases stop on one condition at one place. `lsoda.h`
1686 // reproduces the output grid through `LsodaStepper` when this is set and
1687 // is untouched when it is not.
1688 // NOT ON THE TBI ARM. `tbi_advance` integrates one CELL at a time, on a
1689 // state vector holding only that cell's entries, while `drift` is the
1690 // WHOLE model's: handing it a cell-local vector reads and writes past
1691 // the end of both buffers. MATLAB arms the guard in
1692 // `solver_fluid_iteration.m` and Java in
1693 // `ClosingAndStateDepMethodsAnalyzer`, neither of which is the tbi arm,
1694 // so leaving tbi unarmed is also what keeps the four codebases aligned.
1695 // A stop test for tbi would have to be built from the CELL's drift,
1696 // inside `tbi_advance`, where the two state spaces agree.
1697 lopt.step_stop = {};
1698 if (fp_armed && m != "tbi") {
1699 const double fp_rate = min_rate;
1700 lopt.step_stop = [&drift, fp_rate](double tt, const std::vector<double>& yy) {
1701 if (yy.empty() || !(fp_rate > 0.0)) return false;
1702 std::vector<double> dy(yy.size(), 0.0);
1703 drift(tt, yy.data(), dy.data());
1704 double dn = 0.0, dtot = 0.0;
1705 for (std::size_t i = 0; i < yy.size(); ++i) {
1706 dn += std::fabs(dy[i]);
1707 dtot += yy[i];
1708 }
1709 return dtot > 0.0 && dn / 2.0 / dtot / fp_rate < lang::GlobalConstants::Zero;
1710 };
1711 }
1712 if (m == "tbi") {
1713 // Same drift, decomposed over cells; see fluid_tbi.h.
1714 x = tbi_advance(sys, tbi_cells, x, t0, t1, TbiOptions(), lopt);
1715 } else if (opt.stiff) {
1716 // `ode_solve_stiff.m`: same leg, same tolerances, implicit method
1717 // -- and the same per-restart tightening, since this arm is one leg
1718 // of the very loop that pays the local error iter_max times.
1719 FluidStiffOptions sopt;
1720 sopt.rtol = lopt.rtol;
1721 sopt.atol = lopt.atol;
1722 // The stiff arm is the Rosenbrock method, not LSODA, so it carries
1723 // the stop itself: this is the arm the settling windows run on.
1724 if (lopt.step_stop) {
1725 const std::function<bool(double, const std::vector<double>&)> ss_stop =
1726 lopt.step_stop;
1727 sopt.step_stop = [ss_stop](const double& tt, const std::vector<double>& yy) {
1728 return ss_stop(tt, yy);
1729 };
1730 }
1731 const OdeSolution<double> ss = fluid_ode_solve_stiff(drift, t0, t1, x, sopt);
1732 x = ss.final_state();
1733 } else {
1734 x = fluid_integrate_leg(drift, t0, t1, x, lopt);
1735 }
1736 // The drift conserves mass but the integrator need not, to the last
1737 // digit; a small negative mass is noise, so it is clamped rather than
1738 // allowed to feed back as a negative rate.
1739 for (double& v : x)
1740 if (v < 0.0) v = 0.0;
1741 // THAT CLAMP IS ALSO WHERE A DIVERGENCE HIDES. Under the moment closure
1742 // the drift can leave the simplex, and clamping the result turns a state
1743 // that is not a solution into one that merely looks like it settled --
1744 // every later window then integrates from it. The population of a closed
1745 // class is conserved EXACTLY by the drift, so a deviation is a
1746 // divergence and nothing else; raise the error the fallback ladder in
1747 // fluid_runner.h already catches, so 'dae' and then 'matrix'/'closing'
1748 // answer the model. Gated on gaussian() so the first-order pass, which
1749 // IS the ladder's own fallback, keeps identical behaviour.
1750 if (opt.closure.gaussian()) {
1751 const int bad = fluid_conservation_violation(sn, sys.layout, x);
1752 if (bad >= 0) {
1754 "The moment-closure drift left the model: closed chain " +
1755 std::to_string(bad) + " moved more than " +
1756 std::to_string(static_cast<int>(100 * kFluidConservationTol)) +
1757 "% of a population the drift conserves exactly, by t = " +
1758 std::to_string(t1) +
1759 ", so the excursion is a divergence rather than a solution. "
1760 "Falling back to a first-order closure.");
1761 }
1762 }
1763 t0 = t1;
1764
1765 double moved = 0.0, total = 0.0;
1766 for (std::size_t i = 0; i < x.size(); ++i) {
1767 moved += std::fabs(x[i] - prev[i]);
1768 total += prev[i];
1769 }
1770 const double ratio = (total > 0.0) ? moved / 2.0 / total : 0.0;
1771 // A FINITE timespan is a transient request, which must reach its end
1772 // time rather than stop at the fixed point; see the header.
1773 //
1774 // iter_tol = 0, the default, never fires here: the reference runs every
1775 // one of its iter_max passes and this port now does too.
1776 if (opt.iter_tol > 0.0 && ratio < opt.iter_tol && !std::isfinite(opt.timespan_end)) {
1777 ++iter;
1778 break;
1779 }
1780 // THE TERMINATION TEST. `ratio` alone is the mass moved over ONE window
1781 // and drops the geometric tail behind it; summing that tail,
1782 // ratio*rho/(1-rho), is what the header says it is missing. rho comes
1783 // from the iteration itself, so no rate has to stand in for the slowest
1784 // system mode -- when one does, the stop lands 3% short. The drift, zero
1785 // AT a fixed point, is an independent second bound. Both must hold on
1786 // two consecutive windows, past the slowest relaxation time.
1787 if (opt.earlystop && iter > 0 && !std::isfinite(opt.timespan_end) && t1 >= min_horizon) {
1788 rho_hist[iter % rho_hist.size()] =
1789 ratio / std::max(moved_prev, lang::GlobalConstants::Zero);
1790 double rho = 0.0;
1791 for (double v : rho_hist)
1792 if (std::isfinite(v) && v > rho) rho = v;
1793 drift(t1, x.data(), drift_buf.data());
1794 double dn = 0.0, dtot = 0.0;
1795 for (std::size_t i = 0; i < x.size(); ++i) {
1796 dn += std::fabs(drift_buf[i]);
1797 dtot += x[i];
1798 }
1799 const double drift_displ = (dtot > 0.0) ? dn / 2.0 / dtot / min_rate : 0.0;
1800 // a non-contracting iteration has no tail to sum: it is not converging
1801 //
1802 // THE 1e-6 GATE IS NOT AN OVERSIGHT, even though it sits below the
1803 // integrator's own tol. Relaxing it to "the moved mass reached the
1804 // integrator floor, so trust the drift residual alone" was TRIED and
1805 // REVERTED: it stops the M/M/1 rho = 0.9 minnormal solve at 7.018088
1806 // against the 7.021524680 all four codebases agree on, and it truncates
1807 // the statedep response-time trajectory to t = 60 instead of its 2000.
1808 // The accuracy of this loop comes from running the windows, so the stop
1809 // has to stay conservative. It is also not what makes a solve hang: see
1810 // _kb/06-solver-catalog.md, where the minnormal closure diverges outright
1811 // on a bounded multiserver station.
1812 if (rho < 1.0 && ratio * rho / (1.0 - rho) < drift_safety * drift_tol
1813 && drift_displ < drift_tol) {
1814 if (++drift_below >= 2) {
1815 ++iter;
1816 break;
1817 }
1818 } else {
1819 drift_below = 0;
1820 }
1821 }
1822 moved_prev = ratio;
1823 if (t1 >= opt.timespan_end) {
1824 ++iter;
1825 break;
1826 }
1827 }
1828
1829 // ---- read the metrics off the converged state -------------------------
1830 FluidSolution out;
1831 out.iters = iter;
1832 out.method = (statedep_family || m == "tbi") ? m : std::string("closing");
1833 out.xvec = x;
1834 out.QN = Matrix<double>(M, K, 0.0);
1835 out.UN = Matrix<double>(M, K, 0.0);
1836 out.RN = Matrix<double>(M, K, 0.0);
1837 out.TN = Matrix<double>(M, K, 0.0);
1838
1839 fluid_closing_metrics(sn, sys, m, x, out.QN, out.UN, out.RN, out.TN);
1840
1841 // THE COMPLETIONS AN ELIMINATED COORDINATE MAKES ARE NOT LOST. The metrics
1842 // above read throughputs off the STATE, as x_f * mu_f * phi_f summed over
1843 // phases, and an eliminated coordinate holds no mass there -- so its
1844 // completions, which are FINITE because mu_f is InfRate, would silently
1845 // vanish and the station would stop balancing against its neighbours. Their
1846 // total rate is exactly what `emap` carries: the composed event that replaced
1847 // the inflow stands for the original completion too.
1848 if (imm_result.eliminated) {
1849 const FluidLayout& LL = sys.layout;
1850 std::vector<std::size_t> cs(LL.nstates, 0), cc(LL.nstates, 0);
1851 for (std::size_t i = 0; i < M; ++i)
1852 for (std::size_t r = 0; r < K; ++r)
1853 for (std::size_t k = 0; k < LL.kic[i][r]; ++k) {
1854 cs[LL.qidx[i][r] + k] = i;
1855 cc[LL.qidx[i][r] + k] = r;
1856 }
1857 std::vector<bool> kept(LL.nstates, false);
1858 for (std::size_t a = 0; a < imm_result.state_map.size(); ++a)
1859 kept[imm_result.state_map[a]] = true;
1860 std::vector<double> rr(x.begin(), x.end());
1861 fluid_rates_closing(dsys, x.data(), rr);
1862 for (std::size_t o = 0; o < sys.n_departures && o < sys.events.size(); ++o) {
1863 const std::size_t c = sys.events[o].event_idx;
1864 if (c >= LL.nstates || kept[c]) continue;
1865 double extra = 0.0;
1866 for (std::size_t e = 0; e < rr.size() && e < imm_result.emap.rows(); ++e)
1867 extra += imm_result.emap(e, o) * rr[e];
1868 out.TN(cs[c], cc[c]) += extra;
1869 }
1870 for (std::size_t i = 0; i < M; ++i)
1871 for (std::size_t r = 0; r < K; ++r)
1872 if (out.TN(i, r) > lang::GlobalConstants::Zero)
1873 out.RN(i, r) = out.QN(i, r) / out.TN(i, r);
1874 }
1875 detail::fluid_snap_all(out.QN, out.UN, out.RN, out.TN);
1876
1877 // System throughput and response time, per chain reference station.
1878 out.XN.assign(K, 0.0);
1879 out.CN.assign(K, 0.0);
1880 for (std::size_t r = 0; r < K; ++r) {
1881 const std::size_t rs = sn.classes[r].refstat;
1882 if (rs >= 1 && rs <= M) out.XN[r] = out.TN(rs - 1, r);
1883 double q = 0.0;
1884 for (std::size_t i = 0; i < M; ++i) q += out.QN(i, r);
1885 if (out.XN[r] > 0.0) out.CN[r] = q / out.XN[r];
1886 }
1887 return out;
1888}
1889
1890// ---------------------------------------------------------------------------
1891// The FCFS non-exponential refit loop of `solver_fluid_analyzer.m:100-197`.
1892// ---------------------------------------------------------------------------
1893/*
1894 * WHAT IT CORRECTS. The fluid drift of an FCFS station is the drift of a
1895 * PROCESSOR-SHARING station: a continuous mass has no queueing order to
1896 * respect, so every class in the buffer is served in proportion to its mass.
1897 * That is exact for exponential service, where the residual is memoryless and
1898 * the order does not matter, and wrong for anything else -- the whole point of
1899 * FCFS is that a long job blocks the ones behind it. The reference therefore
1900 * does not integrate an FCFS station at its declared service process. It runs
1901 * the mean-field solve, reads the resulting utilizations back into
1902 * `npfqn_nonexp_approx`, which rescales each FCFS station's service time by the
1903 * WSC 2020 diffusion interpolation, refits a COXIAN to that rescaled mean at the
1904 * station's ORIGINAL SCV, and integrates again. The loop closes on `eta`, the
1905 * M/G/1 decay rate the interpolation is built from.
1906 *
1907 * WHY THE FIT IS A COXIAN AND NOT A RATE CHANGE. `npfqn_nonexp_approx` returns a
1908 * scaled MEAN only. Writing that mean back as a one-phase exponential would
1909 * discard the SCV, which is the quantity that made the station non-product-form
1910 * in the first place; `Coxian.fitMeanAndSCV(1/rate, SCV)` keeps both moments and
1911 * changes the station's PHASE COUNT, which is why the layout, the initial
1912 * condition and the drift are all rebuilt inside the loop.
1913 *
1914 * THE SCV AND THE RATES ARE THE DECLARED ONES, EVERY SWEEP. `SCV = sn.scv` and
1915 * `rates0 = sn.rates` are read once, before the loop. Re-reading the SCV from
1916 * the refitted process would feed the fit its own output -- the Coxian written
1917 * in sweep n has, by construction, the SCV that was asked for -- so the sequence
1918 * would freeze at the first fit instead of converging to the interpolation's
1919 * fixed point. For the same reason the utilization fed back is `TN ./ rates0`
1920 * and not `TN ./ rates`, and `sn.rates` is never reassigned inside the loop.
1921 *
1922 * WHERE THE STATE HANDLING WENT. The reference re-encodes `sn.state` through
1923 * `State.toMarginal` / `State.fromMarginalAndStarted` whenever the phase count
1924 * changes, because `solver_fluid_initsol.m` DECODES that state to build the
1925 * initial condition. `fluid_default_initsol` is the closed form of that round
1926 * trip (see fluid_closing.h): it writes the `initDefault` placement into the
1927 * phase-one entries directly and never reads `sn.state`. The re-encoding is
1928 * therefore an identity here, and rebuilding the initial condition after a phase
1929 * change is the whole of its observable effect -- which is done.
1930 */
1931/**
1932 * The methods whose FCFS drift is the PS drift, and which the reference
1933 * therefore refits.
1934 *
1935 * The reference's second switch lists `matrix`, `closing`, `tbi`, `minnormal`,
1936 * `mnrefined` and `dae`, and NOT `statedep`, `softmin`, `pnorm`, `diffusion`,
1937 * `mfq`, `rmf` or `kp`. The state-dependent family already carries a min()-based
1938 * capacity term, so its FCFS drift is not the PS one and refitting it would
1939 * correct a correction; `statedep` is commented in the reference as needing a
1940 * single iteration, and that comment is the contract. The rest are different
1941 * solvers, not different closures of the same drift.
1942 *
1943 * `dae` refits because it IS the min-normal closure -- same drift, same rate
1944 * factors, solved simultaneously instead of by substitution -- so the phase
1945 * count its answer depends on is refitted on the same schedule `minnormal` uses.
1946 */
1947inline bool fluid_method_refits_fcfs(const std::string& method) {
1948 std::string m = method;
1949 if (m.size() > 4 && m.compare(0, 4, "fld.") == 0) m = m.substr(4);
1950 return m == "matrix" || m == "closing" || m == "tbi" || m == "minnormal" || m == "mnrefined" ||
1951 m == "dae";
1952}
1953
1954/** `cellsum(sn.visits)` at station level; the reference's `V` argument. */
1955template <class T>
1956Matrix<T> fluid_station_visits(const qn::NetworkStruct<T>& sn) {
1957 const T zero = num_traits<T>::from_int(0);
1958 Matrix<T> V(sn.nstations, sn.nclasses, zero);
1959 for (std::size_t c = 0; c < sn.nchains; ++c)
1960 for (std::size_t i = 0; i < sn.nstations; ++i) {
1961 const std::size_t sf = sn.stateful_of_station(i + 1);
1962 for (std::size_t k = 0; k < sn.nclasses; ++k)
1963 V(i, k) = T(V(i, k) + sn.visits[c](sf - 1, k));
1964 }
1965 return V;
1966}
1967
1968/**
1969 * MATLAB's max(abs(1 - eta ./ eta_1)) over a vector that MAY contain NaN.
1970 *
1971 * `max` SKIPS NaN in MATLAB, and an all-NaN vector makes the comparison
1972 * `[] > tol` false, i.e. the loop stops. A 0/0 entry -- a station whose decay
1973 * rate was zero on both sweeps -- must therefore not read as "not converged",
1974 * which is what a straight `std::max` over NaN would produce.
1975 */
1976inline double fluid_eta_gap(const std::vector<double>& eta, const std::vector<double>& eta_1) {
1977 double best = -std::numeric_limits<double>::infinity();
1978 bool any = false;
1979 for (std::size_t i = 0; i < eta.size(); ++i) {
1980 const double g = std::fabs(1.0 - eta[i] / eta_1[i]);
1981 if (std::isnan(g)) continue;
1982 any = true;
1983 best = std::max(best, g);
1984 }
1985 return any ? best : 0.0;
1986}
1987
1988/** Elementwise reciprocal of A, with the reference's two sentinels for the
1989 * degenerate entries. */
1990template <class T>
1991Matrix<T> fluid_reciprocal_guarded(const Matrix<T>& A) {
1992 const T one = num_traits<T>::from_int(1);
1993 Matrix<T> B(A.rows(), A.cols(), num_traits<T>::from_int(0));
1994 for (std::size_t i = 0; i < A.rows(); ++i)
1995 for (std::size_t r = 0; r < A.cols(); ++r) {
1996 const double a = num_traits<T>::to_double(A(i, r));
1997 if (std::isnan(a))
1998 B(i, r) = num_traits<T>::from_double(lang::GlobalConstants::FineTol);
1999 else if (a == 0.0 || std::isinf(1.0 / a))
2000 // A zero rate gives Inf, which the reference replaces by
2001 // GlobalConstants.Immediate = 1e8 -- a very LARGE service time,
2002 // not a vanishing one. That reads backwards and is what
2003 // `solver_fluid_analyzer.m:107-109` does; the pairs it applies to
2004 // carry no utilization, so the interpolation then leaves them alone.
2005 B(i, r) = num_traits<T>::from_double(lang::GlobalConstants::Immediate);
2006 else
2007 B(i, r) = T(one / A(i, r));
2008 }
2009 return B;
2010}
2011
2012/**
2013 * Refit every FCFS station of `sn` to the rescaled service time at its declared
2014 * SCV, returning true when any station's PHASE COUNT changed.
2015 *
2016 * A phase change invalidates the fluid layout, so the caller must rebuild the
2017 * initial condition rather than carry the previous state vector across.
2018 */
2019template <class T>
2020bool fluid_refit_fcfs_stations(qn::NetworkStruct<T>& sn, const Matrix<T>& rates,
2021 const Matrix<T>& SCV,
2022 std::vector<std::vector<std::size_t>>& phases) {
2023 const T zero = num_traits<T>::from_int(0);
2024 const T one = num_traits<T>::from_int(1);
2025 const std::size_t M = sn.nstations, K = sn.nclasses;
2026 bool changed = false;
2027 for (std::size_t i = 0; i < M; ++i) {
2028 if (sn.stations[i].sched != lang::SchedStrategy::FCFS) continue;
2029 for (std::size_t r = 0; r < K; ++r) {
2030 if (!(rates(i, r) > zero) || !(SCV(i, r) > zero)) continue;
2031 const pfqn::MarieCoxFit<T> cx = pfqn::marie_cox_fit(T(one / rates(i, r)), SCV(i, r));
2032 // `refresh_rates` is deliberately NOT called: the reference never
2033 // assigns `sn.rates` inside the loop, and every consumer below the
2034 // switch (the correction, the next sweep's rho) reads the DECLARED
2035 // rate. Only the process representation the drift is built from moves.
2036 sn.service[i][r] = lang::Distrib<T>::coxian(cx.mu, cx.phi);
2037 if (cx.mu.size() != phases[i][r]) changed = true;
2038 phases[i][r] = cx.mu.size();
2039 }
2040 }
2041 return changed;
2042}
2043
2044/**
2045 * The loop. `seed` is the first integration, which the caller has already run at
2046 * the model's declared service processes, and `solve` re-integrates the refitted
2047 * struct by the SAME method -- UNCORRECTED, because the analyzer applies its
2048 * correction once, after the loop.
2049 *
2050 * Returns the uncorrected table of the final integration, and `iters` is that
2051 * integration's own pass count.
2052 *
2053 * `iters` IS NOT ACCUMULATED ACROSS THE SWEEPS, and that is the reference's
2054 * split rather than a simplification. `solver_fluid_analyzer.m` returns `iter`,
2055 * the number of REFIT sweeps, and keeps the summed integration count in
2056 * `outer_iters`, which it uses for runtime accounting only. This port's `iters`
2057 * has always meant "passes of the integration the reported table came from", so
2058 * summing the discarded sweeps into it would change what the field means for
2059 * every model, refitting or not. The sweep count is reported separately below.
2060 */
2061template <class T, class Solve>
2062FluidSolution fluid_fcfs_nonexp_refit(const qn::NetworkStruct<T>& sn0, const FluidOptions& opt,
2063 const FluidSolution& seed, Solve solve,
2064 qn::NetworkStruct<T>* sn_out = nullptr) {
2065 const std::size_t M = sn0.nstations, K = sn0.nclasses;
2066 // `result.solverSpecific.sn` of the reference: the struct the reported
2067 // solution was integrated on. It is the input one until the loop refits a
2068 // service process, and a caller that reads the state vector afterwards --
2069 // the passage time does -- needs the refitted one, whose phase counts the
2070 // vector is laid out by.
2071 if (sn_out) *sn_out = sn0;
2072 if (!fluid_method_refits_fcfs(opt.method)) return seed;
2073 bool any_fcfs = false;
2074 for (std::size_t i = 0; i < M; ++i)
2075 if (sn0.stations[i].sched == lang::SchedStrategy::FCFS) any_fcfs = true;
2076 if (!any_fcfs) return seed;
2077
2078 const T zero = num_traits<T>::from_int(0);
2079 const T one = num_traits<T>::from_int(1);
2080 const Matrix<T>& rates0 = sn0.rates;
2081 const Matrix<T>& SCV = sn0.scv;
2082 const Matrix<T> V = fluid_station_visits(sn0);
2083 const Matrix<T> ST0 = fluid_reciprocal_guarded(rates0);
2084
2085 std::vector<bool> isFCFS(M, false);
2086 std::vector<T> nservers(M, one), gamma(M, zero);
2087 for (std::size_t i = 0; i < M; ++i) {
2088 isFCFS[i] = sn0.stations[i].sched == lang::SchedStrategy::FCFS;
2089 nservers[i] = num_traits<T>::from_double(sn0.stations[i].nservers);
2090 }
2091
2092 qn::NetworkStruct<T> sn = sn0;
2093 std::vector<std::vector<std::size_t>> phases(M, std::vector<std::size_t>(K, 0));
2094 for (std::size_t i = 0; i < M; ++i)
2095 for (std::size_t r = 0; r < K; ++r) phases[i][r] = sn0.service[i][r].D0.rows();
2096
2097 FluidSolution cur = seed;
2098 std::vector<double> eta(M, std::numeric_limits<double>::infinity()), eta_1(M, 0.0);
2099 std::size_t iter = 0;
2100
2101 while (fluid_eta_gap(eta, eta_1) > lang::GlobalConstants::CoarseTol && iter <= opt.iter_max) {
2102 // Wall-clock budget (options.timeout): the last completed pass is the
2103 // interim solution.
2104 if (iter > 0 && util::timeout_exceeded()) break;
2105 ++iter;
2106 eta_1 = eta;
2107
2108 Matrix<T> U(M, K, zero), TN(M, K, zero);
2109 for (std::size_t i = 0; i < M; ++i)
2110 for (std::size_t r = 0; r < K; ++r) {
2111 TN(i, r) = num_traits<T>::from_double(cur.TN(i, r));
2112 if (rates0(i, r) > zero) U(i, r) = T(TN(i, r) / rates0(i, r));
2113 }
2114
2115 const npfqn::NonexpApproxResult<T> na = npfqn::npfqn_nonexp_approx(
2116 opt.highvar, isFCFS, rates0, ST0, V, SCV, TN, U, gamma, nservers);
2117 gamma = na.gamma;
2118 for (std::size_t i = 0; i < M; ++i) eta[i] = num_traits<T>::to_double(na.eta[i]);
2119
2120 const Matrix<T> rates = fluid_reciprocal_guarded(na.ST);
2121 const bool phase_change = fluid_refit_fcfs_stations(sn, rates, SCV, phases);
2122
2123 FluidOptions o = opt;
2124 const std::vector<double> fresh = fluid_default_initsol(sn, fluid_layout(sn));
2125 o.init_sol = (!phase_change && cur.xvec.size() == fresh.size()) ? cur.xvec : fresh;
2126 cur = solve(sn, o);
2127 }
2128
2129 // The reference re-solves once more from the CLEAN initial condition, so the
2130 // reported table is the drift of the converged service processes started
2131 // where the model says the system starts, not where the last sweep left off.
2132 FluidOptions o = opt;
2133 o.init_sol = fluid_default_initsol(sn, fluid_layout(sn));
2134 FluidSolution out = solve(sn, o);
2135 out.refit_sweeps = iter;
2136 if (sn_out) *sn_out = sn;
2137 return out;
2138}
2139
2140} // namespace detail
2141
2142
2143/**
2144 * Port of `solver_fluid_analyzer.m`: dispatch on the method, refit the
2145 * non-exponential FCFS stations the reference refits, then apply the
2146 * utilization and response-time correction it applies to whatever the branch
2147 * returned.
2148 */
2149template <class T>
2151 qn::NetworkStruct<T>* sn_out = nullptr) {
2152 // `@@SolverFLD/runAnalyzer.m:25` converts the non-Markovian service laws
2153 // first, and FORCES phfit = 'ph': the ODEs read mu*phi as a flow between
2154 // phases, and a matrix exponential has no such flow -- its off-diagonal
2155 // entries are not rates. The default two-moment CME would give a better
2156 // moment match and a meaningless drift.
2157 qn::NetworkStruct<T> converted;
2158 const qn::NetworkStruct<T>* snp = &sn_in;
2159 if constexpr (num_traits<T>::has_transcendental) {
2160 if (api::nonmkv_enabled(opt.nonmkv) && api::sn_has_nonmarkov(sn_in, false)) {
2161 converted = sn_in;
2163 no.order = opt.nonmkv_order;
2164 no.phfit = api::PhFit::Ph;
2165 api::sn_nonmarkov_toph(converted, no);
2166 snp = &converted;
2167 }
2168 }
2169 const qn::NetworkStruct<T>& sn = *snp;
2170
2171 FluidSolution out = detail::fluid_dispatch(sn, opt);
2172 out = detail::fluid_fcfs_nonexp_refit(
2173 sn, opt, out,
2174 [](const qn::NetworkStruct<T>& s, const FluidOptions& o) { return detail::fluid_dispatch(s, o); },
2175 sn_out);
2176 detail::fluid_analyzer_correct(sn, out.QN, out.UN, out.RN, out.TN);
2177 detail::fluid_snap_all(out.QN, out.UN, out.RN, out.TN);
2178 return out;
2179}
2180
2181
2182/**
2183 * Port of `local_detect_nhpp` in `@@SolverFLD/getTranAvg.m`: the (station, class)
2184 * pairs whose SOURCE carries a rate schedule, 1-based.
2185 *
2186 * A CALLER OPTS IN, and that is the reference's split rather than a convenience.
2187 * `getTranAvg` calls this and puts the result on the options; a steady-state
2188 * request does not, and is answered at the time-averaged nominal. Both are
2189 * legitimate readings of the same model, so the decision belongs to the entry
2190 * point and not to the drift builder.
2191 *
2192 * The reference tests `ismethod(proc,'getRateSchedule')`, which NHPP, MAPt and
2193 * PHt all answer; here that is `Distrib::has_schedule()`, the same three.
2194 */
2195template <class T>
2196std::vector<std::pair<std::size_t, std::size_t> > fluid_detect_nhpp(
2197 const qn::NetworkStruct<T>& sn) {
2198 std::vector<std::pair<std::size_t, std::size_t> > out;
2199 for (std::size_t i = 0; i < sn.nstations; ++i) {
2200 if (sn.stations[i].sched != lang::SchedStrategy::EXT) continue;
2201 for (std::size_t r = 0; r < sn.nclasses; ++r)
2202 if (!sn.disabled[i][r] && sn.service[i][r].has_schedule())
2203 out.push_back(std::make_pair(i + 1, r + 1));
2204 }
2205 return out;
2206}
2207
2208/**
2209 * Port of `@@SolverFLD/getTranAvg`: the metrics along the trajectory, not just
2210 * at the fixed point.
2211 *
2212 * The reference forces the method to `closing` for a transient (matrix and the
2213 * smoothed variants are steady-state devices), and so does this. The drift is
2214 * integrated once over [0, t_end] with the output grid handed to LSODA, and
2215 * every point is passed through the SAME extraction the steady state uses, so
2216 * the last point of a long enough run reproduces `solver_fluid` exactly.
2217 *
2218 * A transient is only meaningful from a KNOWN starting state, so the default
2219 * initial condition is used unless the caller supplies `init_sol`.
2220 *
2221 * THE RATE SCHEDULE IS DETECTED HERE, as `getTranAvg.m:76` detects it: a
2222 * transient of a model with a non-homogeneous source follows the intensity
2223 * exactly rather than its time average. A caller that has already filled
2224 * `opt.nhpp_sched` keeps its own list, so the nominal can still be asked for.
2225 *
2226 * `out_grid` REPLACES the uniform grid when a caller needs the trajectory at
2227 * points of its own choosing. It exists because interpolating a trajectory
2228 * cannot recover resolution it never had: SolverENV sums an exit average
2229 * against a sojourn CDF, and over a horizon of 1e3 read through an Exp(1) clock
2230 * a uniform 1001-point grid carries six samples where the whole weight lives.
2231 * LSODA takes an arbitrary increasing output vector, so asking for the points
2232 * that matter costs nothing and removes the interpolation entirely.
2233 */
2234template <class T>
2235std::vector<FluidTranPoint> solver_fluid_transient(const qn::NetworkStruct<T>& sn,
2236 const FluidOptions& opt, double t_end,
2237 std::size_t points = 101,
2238 const std::vector<double>& out_grid =
2239 std::vector<double>()) {
2240 if (!std::is_same<T, double>::value)
2241 throw UnsupportedError(ErrorKind{"Arithmetic"},
2242 "solver_fluid_transient: the fluid drift is integrated by LSODA, which is double "
2243 "precision by construction; rerun with --arith double");
2244 if (!(t_end > 0.0)) throw InputError("solver_fluid_transient: t_end must be positive");
2245 if (points < 2) throw InputError("solver_fluid_transient: need at least two output points");
2246
2247 FluidOptions o = opt;
2248 if (o.nhpp_sched.empty()) o.nhpp_sched = fluid_detect_nhpp(sn);
2250 sys.ratemult = detail::fluid_ratemult(sn, sys, o);
2251 const FluidLayout& L = sys.layout;
2252 if (L.nstates == 0)
2253 throw InputError("solver_fluid_transient: no station serves any class");
2254
2255 std::vector<double> y0 =
2256 o.init_sol.empty() ? detail::fluid_default_initsol(sn, L) : o.init_sol;
2257 if (y0.size() != L.nstates)
2258 throw InputError("solver_fluid_transient: init_sol has the wrong length");
2259
2260 std::vector<double> grid = out_grid;
2261 if (grid.empty()) {
2262 grid.resize(points);
2263 for (std::size_t j = 0; j < points; ++j)
2264 grid[j] = t_end * static_cast<double>(j) / static_cast<double>(points - 1);
2265 }
2266
2267 LsodaOptions lopt;
2268 lopt.rtol = o.tol;
2269 lopt.atol = o.tol;
2270 const std::function<void(double, const double*, double*)> tdrift = fluid_drift(sys);
2271 const LsodaSolution sol = fluid_integrate_grid(tdrift, y0, grid, lopt);
2272
2273 std::vector<FluidTranPoint> out;
2274 out.reserve(sol.y.size());
2275 for (std::size_t j = 0; j < sol.y.size(); ++j) {
2276 std::vector<double> xs = sol.y[j];
2277 for (double& v : xs)
2278 if (v < 0.0) v = 0.0;
2279 FluidTranPoint pt;
2280 pt.t = sol.t[j];
2282 fluid_closing_metrics(sn, sys, std::string("closing"), xs, pt.QN, pt.UN, R, pt.TN);
2283 detail::fluid_snap_all(pt.QN, pt.UN, R, pt.TN);
2284 out.push_back(pt);
2285 }
2286 return out;
2287}
2288
2289/**
2290 * The horizon a transient runs to when the caller gives none.
2291 *
2292 * FACTORED OUT OF `solver_fluid_tran_avg` because `dae` has a transient of its
2293 * own (fluid_dae.h) and must reach it by the SAME rule: a horizon rule that two
2294 * methods each computed for themselves is a horizon rule that can differ
2295 * between them, and then two trajectories of one model are read at different
2296 * times for no stated reason.
2297 *
2298 * `options.timespan` defaults to [0, Inf] and the reference does NOT integrate
2299 * to infinity for it. The rule lives in `@NetworkSolver/getTranAvg.m`, not in
2300 * the fluid analyzer: an unspecified end time becomes `30/minrate` with
2301 * `minrate = min(sn.rates(isfinite(sn.rates)))`, i.e. thirty mean events of the
2302 * SLOWEST RATE IN sn.rates -- arrival rates included, since the source's rate
2303 * sits in that same table. That is not the analyzer's own horizon-extension
2304 * rule (ten mean events of the slowest transition per pass), which governs how
2305 * far `solver_fluid` integrates while hunting the fixed point and is invisible
2306 * to the getter. A caller that sets `timespan_end` is integrated over exactly
2307 * that instead.
2308 *
2309 * MATLAB drops NaN (its disabled marker) through `isfinite`; the port carries a
2310 * separate `disabled` flag and stores zero, so the zero is skipped by the flag.
2311 */
2312template <class T>
2314 if (std::isfinite(opt.timespan_end) && opt.timespan_end > 0.0) return opt.timespan_end;
2315 double min_rate = std::numeric_limits<double>::infinity();
2316 for (std::size_t i = 0; i < sn.nstations; ++i)
2317 for (std::size_t r = 0; r < sn.nclasses; ++r) {
2318 if (sn.disabled[i][r]) continue;
2319 const double rate = num_traits<T>::to_double(sn.rates(i, r));
2320 if (std::isfinite(rate) && rate > opt.tol) min_rate = std::min(min_rate, rate);
2321 }
2322 if (!std::isfinite(min_rate)) min_rate = 1.0;
2323 return 30.0 / min_rate;
2324}
2325
2326/**
2327 * `getTranAvg` on the first-order closing drift, over that horizon.
2328 *
2329 * THE METHOD IS NOT CONSULTED, as it is not in the reference: matrix, pnorm and
2330 * the smoothed variants are steady-state devices with no trajectory of their
2331 * own, so `getTranAvg.m` substitutes `closing` for them and warns. `dae` is the
2332 * exception the reference itself makes, and `solver_fluid_run_transient`
2333 * (fluid_runner.h) is where that routing lives -- it cannot live here, because
2334 * this header is below fluid_dae.h in the include order.
2335 */
2336template <class T>
2337std::vector<FluidTranPoint> solver_fluid_tran_avg(const qn::NetworkStruct<T>& sn,
2338 const FluidOptions& opt,
2339 std::size_t points = 101) {
2341}
2342
2343/**
2344 * The Jacobian of the fluid drift at a state, by central differences.
2345 *
2346 * The reference's `getJacobian` builds this SYMBOLICALLY and hands the
2347 * expression to a SAGE backend over HTTP; there is no symbolic engine here, so
2348 * this is the numerical counterpart. It is what the symbolic form is used for
2349 * in practice -- local stability of the fixed point, through the eigenvalues of
2350 * J -- and it needs no external service.
2351 */
2352template <class T>
2353Matrix<double> fluid_jacobian(const qn::NetworkStruct<T>& sn, const std::vector<double>& x) {
2354 const FluidOdeSystem sys = fluid_ode_system(sn);
2355 const std::size_t n = sys.layout.nstates;
2356 if (x.size() != n) throw InputError("fluid_jacobian: the state has the wrong length");
2357 const std::function<void(double, const double*, double*)> f = fluid_drift(sys);
2358 Matrix<double> J(n, n, 0.0);
2359 std::vector<double> xp(x), xm(x), fp(n, 0.0), fm(n, 0.0);
2360 for (std::size_t j = 0; j < n; ++j) {
2361 // A step scaled to the component, floored so a zero entry still moves.
2362 const double h = 1e-6 * std::max(1.0, std::fabs(x[j]));
2363 xp = x;
2364 xm = x;
2365 xp[j] += h;
2366 xm[j] -= h;
2367 f(0.0, xp.data(), fp.data());
2368 f(0.0, xm.data(), fm.data());
2369 for (std::size_t i = 0; i < n; ++i) J(i, j) = (fp[i] - fm[i]) / (2.0 * h);
2370 }
2371 return J;
2372}
2373
2374
2375/**
2376 * The joint probability of the per-class populations at station `i` (0-based)
2377 * under the linear noise approximation solved by the moment closure, the
2378 * `local_gaussian_cell` of the reference `@@SolverFLD/getProbAggr`.
2379 *
2380 * The state coordinates of class r at the station are `moments.class_block[i][r]`
2381 * (one per service phase), so the class population is their sum: its mean is the
2382 * reported `QN(i,r)` and the class-to-class covariance is the sum of the
2383 * corresponding block of `moments.Sigma`. The integer count n is then read off
2384 * the continuous law as the unit cell [n-1/2, n+1/2], with the two ends extended
2385 * to infinity at the boundaries of the state space, so that the mass the normal
2386 * puts on negative populations lands on the empty station and the mass above a
2387 * closed population lands on the full one. Those cells tile the state space, so
2388 * the probabilities sum to one over the reachable states.
2389 */
2390template <class T>
2392 std::size_t i, const std::vector<double>& nir,
2393 double* logp_out = nullptr) {
2394 const std::size_t K = sn.nclasses;
2395 const std::vector<std::vector<std::size_t>>& cb = sol.moments.class_block[i];
2396
2397 std::vector<std::size_t> idx;
2398 std::vector<double> m, a, b;
2399 for (std::size_t r = 0; r < K; ++r) {
2400 if (cb[r].empty()) {
2401 // the class has no service process here, so it has no coordinate:
2402 // any positive count is impossible rather than improbable
2403 if (nir[r] > 0.0) {
2404 if (logp_out) *logp_out = -std::numeric_limits<double>::infinity();
2405 return 0.0;
2406 }
2407 continue;
2408 }
2409 idx.push_back(r);
2410 m.push_back(sol.QN(i, r));
2411 a.push_back(nir[r] <= 0.0 ? -std::numeric_limits<double>::infinity() : nir[r] - 0.5);
2412 const double pop = sn.classes[r].population;
2413 b.push_back((std::isfinite(pop) && nir[r] >= pop) ? std::numeric_limits<double>::infinity()
2414 : nir[r] + 0.5);
2415 }
2416
2417 if (idx.empty()) {
2418 if (logp_out) *logp_out = 0.0;
2419 return 1.0;
2420 }
2421
2422 const std::size_t nr = idx.size();
2423 Matrix<double> C(nr, nr, 0.0);
2424 for (std::size_t u = 0; u < nr; ++u)
2425 for (std::size_t v = u; v < nr; ++v) {
2426 double acc = 0.0;
2427 for (std::size_t p = 0; p < cb[idx[u]].size(); ++p)
2428 for (std::size_t q = 0; q < cb[idx[v]].size(); ++q)
2429 acc += sol.moments.Sigma(cb[idx[u]][p], cb[idx[v]][q]);
2430 C(u, v) = acc;
2431 C(v, u) = acc;
2432 }
2433
2434 const double p = fluid_mvn_rectangle(m, C, a, b);
2435 if (logp_out) *logp_out = p > 0.0 ? std::log(p) : -std::numeric_limits<double>::infinity();
2436 return p;
2437}
2438
2439/**
2440 * Port of `@@SolverFLD/getProbAggr`: the probability that station `ist` holds
2441 * the marginal population of the model's default state.
2442 *
2443 * The fluid solver has no state space, so the probability is FITTED to the
2444 * mean queue lengths it does produce: a binomial for each closed class
2445 * (Schmidt) and, for the open ones, the BCMP marginal -- Poisson at an
2446 * infinite server, multinomial-geometric at a queue. The two contributions are
2447 * ADDED in log space, which is what lets a mixed model be evaluated at all;
2448 * the MVA port's version picks one branch because its callers are never mixed.
2449 *
2450 * `ist` is 1-based, as in the reference.
2451 */
2452template <class T>
2453double fluid_prob_aggr(const qn::NetworkStruct<T>& sn, const FluidSolution& sol, std::size_t ist,
2454 double* logp_out = nullptr) {
2455 const std::size_t M = sn.nstations, K = sn.nclasses;
2456 if (ist == 0 || ist > M)
2457 throw InputError("fluid_prob_aggr: station number exceeds the number of stations");
2458 const std::size_t i = ist - 1;
2459
2460 // The marginal of the DEFAULT state: a closed class sits at its reference
2461 // station, an open one holds nothing. This is what `State.toMarginal`
2462 // returns for the state the model starts in.
2463 std::vector<double> nir(K, 0.0);
2464 for (std::size_t r = 0; r < K; ++r) {
2465 const double pop = sn.classes[r].population;
2466 if (std::isfinite(pop) && sn.classes[r].refstat == ist) nir[r] = pop;
2467 }
2468
2469 double logp = 0.0;
2470 bool minus_inf = false;
2471 const lang::SchedStrategy sc = sn.stations[i].sched;
2472
2473 // The moment closure supplies the JOINT law of the per-class populations, so
2474 // the answer is the probability its multivariate normal assigns to the unit
2475 // cell around the state, correlation between the classes included. Three
2476 // exclusions, each structural rather than defensive:
2477 // - a Source coordinate is a normalisation constant, not a population, and
2478 // `fluid_moment_terms` projects it out of the covariance;
2479 // - an OPEN class already has an EXACT first-order answer here (the BCMP
2480 // marginal below), and a normal approximation of it would only lose: on
2481 // M/M/1 at rho = 0.5 the cell returns 0.391 for the empty queue against
2482 // an exact 0.500;
2483 // - without moments there is no second moment anywhere in FLD.
2484 if (sol.has_moments && !sol.moments.class_block.empty() && sc != lang::SchedStrategy::EXT) {
2485 bool open_here = false;
2486 for (std::size_t r = 0; r < K; ++r)
2487 if (!sol.moments.class_block[i][r].empty() && !std::isfinite(sn.classes[r].population))
2488 open_here = true;
2489 if (!open_here)
2490 return fluid_prob_aggr_gaussian(sn, sol, i, nir, logp_out);
2491 }
2492
2493 // ---- open classes ------------------------------------------------------
2494 bool any_open = false;
2495 for (std::size_t r = 0; r < K; ++r)
2496 if (!std::isfinite(sn.classes[r].population)) any_open = true;
2497 if (any_open && sc == lang::SchedStrategy::INF) {
2498 for (std::size_t r = 0; r < K; ++r) {
2499 if (std::isfinite(sn.classes[r].population)) continue;
2500 const double q = sol.QN(i, r);
2501 if (q > 0.0)
2502 logp += nir[r] * std::log(q) - q - std::lgamma(nir[r] + 1.0);
2503 else if (nir[r] > 0.0)
2504 minus_inf = true;
2505 }
2506 } else if (any_open && sc != lang::SchedStrategy::EXT) {
2507 double rho_total = 0.0, n_total = 0.0;
2508 for (std::size_t r = 0; r < K; ++r) {
2509 if (std::isfinite(sn.classes[r].population)) continue;
2510 rho_total += sol.UN(i, r);
2511 n_total += nir[r];
2512 }
2513 if (rho_total < 1.0) {
2514 logp += std::log(1.0 - rho_total) + std::lgamma(n_total + 1.0);
2515 for (std::size_t r = 0; r < K; ++r) {
2516 if (std::isfinite(sn.classes[r].population) || !(nir[r] > 0.0)) continue;
2517 const double rho_r = sol.UN(i, r);
2518 if (rho_r > 0.0)
2519 logp += nir[r] * std::log(rho_r) - std::lgamma(nir[r] + 1.0);
2520 else
2521 minus_inf = true;
2522 }
2523 } else {
2524 minus_inf = true; // a saturated station has no stationary marginal
2525 }
2526 }
2527
2528 // ---- closed classes: the Schmidt binomial ------------------------------
2529 for (std::size_t r = 0; r < K; ++r) {
2530 const double N = sn.classes[r].population;
2531 if (!std::isfinite(N)) continue;
2532 const double q = sol.QN(i, r);
2533 const double p = (N > 0.0) ? q / N : 0.0;
2534 // nchoosekln(N, nir)
2535 logp += std::lgamma(N + 1.0) - std::lgamma(nir[r] + 1.0) - std::lgamma(N - nir[r] + 1.0);
2536 if (p > 0.0) {
2537 logp += nir[r] * std::log(p);
2538 } else if (nir[r] > 0.0) {
2539 minus_inf = true;
2540 }
2541 if (p < 1.0) {
2542 logp += (N - nir[r]) * std::log(1.0 - p);
2543 } else if (N - nir[r] > 0.0) {
2544 minus_inf = true;
2545 }
2546 }
2547
2548 if (minus_inf) {
2549 if (logp_out) *logp_out = -std::numeric_limits<double>::infinity();
2550 return 0.0;
2551 }
2552 if (logp_out) *logp_out = logp;
2553 return std::exp(logp);
2554}
2555
2556} // namespace fluid
2557} // namespace line
2558
2559#endif // LINE_SOLVERS_FLUID_SOLVER_FLUID_H
2560
InputError(const std::string &what)
Definition error.h:105
UnsupportedError(const std::string &what)
Definition error.h:119
FluidNonHyperbolicError(const std::string &what)
A network plus its refreshed NetworkStruct.
std::size_t nvars_of(std::size_t ind) const
Total local-variable width of node ind (1-based).
std::vector< JobClass > classes
std::size_t phasessz_of(std::size_t ist, std::size_t r) const
The exception types the port throws.
Fork-join section metrics: FJQLen, FJRespT and FJTput of every Fork/Join pair.
Age of Information by Markovian fluid queues: a port of solver_mfq_aoi.m (identical to solver_fluid_a...
Detects a moment-closure trajectory that has left the model.
The diffusion method: a port of solver_fluid_diffusion.m.
The matrix fluid method: a port of solver_fluid_matrix.m, the formulation of Ruuskanen,...
The mfq method: a port of solver_mfq.m and the single-queue gate fluid_is_single_queue....
Port of fluid_mfq_admits.m and fluid_is_single_queue.m: can the mfq fluid method (and its alias aoi) ...
The priority branch of the mfq method: a port of solver_mfq_prio.m.
Port of fluid_mvn_rectangle.m: the rectangle probability P(a <= Y <= b) for Y ~ Normal(m,...
The one exception the fluid fallback ladder catches.
The fluid drift: a port of solver_fluid_odes.m and the ode_jumps_new / ode_rate_base / ode_rates_clos...
The state-dependent fluid drifts: ports of ode_statedep.m, ode_softmin.m and ode_pnorm....
Port of ode_eliminate_immediate.m, eliminate_immediate_matrix.m and ode_solve_stiff....
The tbi method: a port of solver_fluid_tbi_iteration.m and tbi_partition.m.
options.timeout: one wall-clock budget per top-level solve, on a per-THREAD deadline stack.
LSODA: the LINE-facing wrapper over the vendored solver in third_party/lsoda.hpp.
Markovian arrival process descriptors: stationary vectors, rate, moments, autocorrelation and the ind...
Dense matrix and non-owning view.
bool sn_has_nonmarkov(const qn::NetworkStruct< T > &sn, bool preserve_det=false)
Whether any law in the struct would be replaced, so a caller can skip copying the struct when there i...
bool nonmkv_enabled(const std::string &method)
Resolve options.config.nonmkv to NonmarkovOptions::enabled.
@ Ph
Bernstein density fit: a genuine phase-type, shape-carrying.
void sn_nonmarkov_toph(qn::NetworkStruct< T > &sn, const NonmarkovOptions &opts=NonmarkovOptions())
Replace every non-Markovian service and firing law by a Markovian surrogate.
double fluid_default_horizon(const qn::NetworkStruct< T > &sn, const FluidOptions &opt)
The horizon a transient runs to when the caller gives none.
FluidMfqAdmits fluid_mfq_admits(const qn::NetworkStruct< T > &sn)
Port of fluid_mfq_admits.m.
std::vector< std::pair< std::size_t, std::size_t > > fluid_detect_nhpp(const qn::NetworkStruct< T > &sn)
Port of local_detect_nhpp in @@SolverFLD/getTranAvg.m: the (station, class) pairs whose SOURCE carrie...
FluidLayout fluid_layout(const qn::NetworkStruct< T > &sn)
Port of the layout half of solver_fluid_odes.m.
Definition fluid_odes.h:282
constexpr double kFluidConservationTol
Relative population drift that counts as having left the model.
std::vector< double > fluid_integrate_leg(const std::function< void(double, const double *, double *)> &f, double t0, double t1, const std::vector< double > &y0, const LsodaOptions &lopt)
One integration leg, with the reference's retry on a failed solve.
bool fluid_matrix_degenerate(const FluidMatrixSystem &s, const std::function< void(double, const double *, double *)> &drift, const std::vector< double > &x, std::size_t K)
Is the returned point one of a CONTINUUM of fixed points?
FluidMatrixSystem fluid_matrix_system(const qn::NetworkStruct< T > &sn, const std::vector< double > &init_sol, double pstar)
Assemble the matrix-form drift of sn.
void fluid_closing_metrics(const qn::NetworkStruct< T > &sn, const FluidOdeSystem &sys, const std::string &m, const std::vector< double > &xs, Matrix< double > &Q, Matrix< double > &U, Matrix< double > &R, Matrix< double > &T_)
Read Q/U/R/T off ONE fluid state, for the closing family.
ClosureValue fluid_capacity_closure(double n, double c, double s2, const std::vector< double > &lldrow, bool is_inf)
Port of fluid_capacity_closure.m: E[psi(X)] and its derivative, where psi(n) = min(n,...
double fluid_prob_aggr(const qn::NetworkStruct< T > &sn, const FluidSolution &sol, std::size_t ist, double *logp_out=nullptr)
Port of @@SolverFLD/getProbAggr: the probability that station ist holds the marginal population of th...
AoiTopology aoi_is_aoi(const qn::NetworkStruct< T > &sn)
Port of aoi_is_aoi.m.
Definition fluid_aoi.h:106
StateDepKind
Which smoothing the drift applies at a saturated station.
double fluid_mvn_rectangle(const std::vector< double > &m, const Matrix< double > &C, const std::vector< double > &a, const std::vector< double > &b, std::size_t npoints=FLUID_MVN_POINTS)
P(a <= Y <= b) for Y ~ Normal(m, C).
DiffusionResult fluid_diffusion(const qn::NetworkStruct< T > &sn, const DiffusionOptions &opt)
Run the diffusion approximation of sn.
std::function< void(double, const double *, double *)> fluid_drift_statedep(const FluidStateDepSystem &s)
The drift dx/dt for the state-dependent family.
std::vector< std::vector< std::size_t > > tbi_check_partition(const qn::NetworkStruct< T > &sn, const std::vector< std::vector< std::size_t > > &cells)
The options.config.tbi_cells branch of tbi_partition.m: an explicit partition, returned as given once...
Definition fluid_tbi.h:86
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.
FluidStateDepSystem fluid_statedep_system(const qn::NetworkStruct< T > &sn, StateDepKind kind, double alpha=20.0, double pstar=20.0)
Assemble what the state-dependent drifts need from sn.
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 ...
MfqTopology mfq_is_single_queue(const qn::NetworkStruct< T > &sn)
Port of fluid_is_single_queue.m: the model must be one open class flowing Source -> Queue -> Sink and...
Definition fluid_mfq.h:67
std::vector< FluidTranPoint > solver_fluid_tran_avg(const qn::NetworkStruct< T > &sn, const FluidOptions &opt, std::size_t points=101)
getTranAvg on the first-order closing drift, over that horizon.
LsodaSolution fluid_integrate_grid(const std::function< void(double, const double *, double *)> &f, const std::vector< double > &y0, const std::vector< double > &grid, const LsodaOptions &lopt)
The same retry over a whole output grid, for the callers that ask LSODA for a trajectory rather than ...
FluidJacobian fluid_jacobian(const FluidSymSystem &sys, const FluidSymbolicOptions &opt=FluidSymbolicOptions())
Jacobian, drift and equilibria of the mean-field vector field.
int fluid_conservation_violation(const qn::NetworkStruct< T > &sn, const FluidLayout &L, const std::vector< double > &x, double tol=kFluidConservationTol)
The closed chain whose conserved population has drifted past tol, or -1.
MfqResult fluid_mfq(const qn::NetworkStruct< T > &sn, const MfqTopology &top, double tol)
Solve the single fluid queue of sn.
Definition fluid_mfq.h:144
double fluid_prob_aggr_gaussian(const qn::NetworkStruct< T > &sn, const FluidSolution &sol, std::size_t i, const std::vector< double > &nir, double *logp_out=nullptr)
The joint probability of the per-class populations at station i (0-based) under the linear noise appr...
FluidOdeSystem fluid_ode_system(const qn::NetworkStruct< T > &sn)
Build the drift of sn: the port of ode_jumps_new and ode_rate_base fused into one pass.
Definition fluid_odes.h:322
std::function< void(double, const double *, double *)> fluid_drift(const FluidOdeSystem &sys)
The drift dx/dt, ready to hand to the integrator.
Definition fluid_odes.h:657
std::vector< std::vector< std::size_t > > tbi_partition(const qn::NetworkStruct< T > &sn, std::size_t cellsize=5)
Port of tbi_partition.m: stations grouped by routing coupling.
Definition fluid_tbi.h:103
std::vector< double > tbi_advance(const FluidOdeSystem &sys, const std::vector< std::vector< std::size_t > > &cells, const std::vector< double > &y0, double t0, double t1, const TbiOptions &topt, const LsodaOptions &lopt)
Advance the state over [t0, t1] by time-based iteration.
Definition fluid_tbi.h:189
void fluid_interpcols(const std::vector< double > &tg, const Matrix< double > &B, double tt, std::vector< double > &out)
Port of fluid_interpcols.m: clamped piecewise-linear interpolation of the columns of B at a scalar ti...
Definition fluid_odes.h:170
void fluid_rates_closing(const FluidOdeSystem &sys, const double *x, std::vector< double > &g)
The reference's ode_rates_closing name, kept for the first-order callers.
Definition fluid_odes.h:646
std::function< void(double, const double *, double *)> fluid_matrix_drift(const FluidMatrixSystem &s)
The drift dx/dt = W' theta(x) + A_lambda.
MfqPrioResult fluid_mfq_prio(const qn::NetworkStruct< T > &sn, const MfqTopology &top, double tol)
Solve the single priority fluid queue of sn.
FluidImmediateResult fluid_eliminate_immediate(const FluidOdeSystem &sys, double imm_tol=fluid_immediate_transition_tol())
Stochastic complementation of the INSTANTANEOUS coordinates of a fluid drift, the twin of ode_elimina...
bool fluid_hide_immediate(const qn::NetworkStruct< T > &sn, const Opt &opt)
Whether this model's fluid drift is built on the stochastic complement of its INSTANTANEOUS coordinat...
OdeSolution< double > fluid_ode_solve_stiff(const std::function< void(double, const double *, double *)> &f, double t0, double t1, const std::vector< double > &y0, const FluidStiffOptions &opt=FluidStiffOptions())
Port of ode_solve_stiff.m.
FluidAoiResult fluid_aoi(const qn::NetworkStruct< T > &sn, const AoiTopology &top, double preempt_override)
Port of solver_mfq_aoi.m.
Definition fluid_aoi.h:795
SchedStrategy
Scheduling disciplines, with the values of MATLAB SchedStrategy.
Definition lang_types.h:194
NodeType
Node kinds, with the values of MATLAB NodeType.
Definition lang_types.h:345
T map_mean(const Map< T > &m)
Mean inter-arrival time, 1/lambda.
Definition map_moment.h:101
T map_lambda(const Map< T > &m)
Stationary arrival rate, lambda = pi D1 e.
Definition map_moment.h:79
NonexpApproxResult< T > npfqn_nonexp_approx(const std::string &method, const std::vector< bool > &isFCFS, const Matrix< T > &rates, const Matrix< T > &ST, const Matrix< T > &V, const Matrix< T > &SCV, const Matrix< T > &Tput, const Matrix< T > &U, const std::vector< T > &gamma, const std::vector< T > &nservers)
Handler for non-exponential service and arrival processes in AMVA and NC.
MarieCoxFit< T > marie_cox_fit(const T &mean, const T &scv)
Closed-form Coxian fit of a mean and an SCV (matlab/src/lang/processes/Coxian.m, fitMeanAndSCV),...
Definition pfqn_marie.h:120
Marginal< T > to_marginal(const NetworkStruct< T > &sn, std::size_t ist, const std::vector< T > &state_i, const std::vector< std::size_t > &phasesz, const std::vector< std::size_t > &phaseshift, std::size_t nvar=0)
Port of State.toMarginal for a STATION, one state row at a time.
Definition state.h:139
bool timeout_exceeded()
The checkpoint: true when the innermost budget has run out, marking it tripped.
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
std::vector< T > solve(const Matrix< T > &A, const std::vector< T > &b)
Convenience: solve Ax = b, leaving A and b untouched.
Definition lu.h:158
A queueing network and its refreshed NetworkStruct.
Handler for non-exponential service and arrival processes in AMVA and NC.
Marie's iterative aggregation-decomposition for closed networks with FCFS general (Coxian) service.
Replace every non-Markovian service and firing law by a Markovian surrogate.
Port of the MATLAB +State package: the encoding that turns a station's state row into marginal job co...
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
Integration controls.
Definition lsoda.h:64
double atol
absolute tolerance, applied to every component
Definition lsoda.h:66
double rtol
relative tolerance, applied to every component
Definition lsoda.h:65
Result of an integration, mirroring OdeSolution in ode.h.
Definition lsoda.h:126
std::vector< std::vector< double > > y
y[i] is the state at t[i]
Definition lsoda.h:128
std::vector< double > t
output times, t[0] = t_eval[0]
Definition lsoda.h:127
options.config.nonmkv and friends.
std::size_t order
nonmkvorder, the phase budget
PhFit phfit
which surrogate family
Both age laws of one system, with the policy parameter that produced them.
Definition fluid_aoi.h:267
The second moment the drift closes its non-linear terms with, i.e.
Definition fluid_odes.h:123
Where each (station, class) block sits in the state vector.
Definition fluid_odes.h:86
std::vector< std::vector< std::size_t > > qidx
0-based first index of (i,r)
Definition fluid_odes.h:88
std::size_t nstates
length of the state vector
Definition fluid_odes.h:87
std::vector< std::vector< bool > > enabled
whether (i,r) is served at all
Definition fluid_odes.h:90
std::vector< std::vector< std::size_t > > kic
phases held by (i,r); 0 when disabled
Definition fluid_odes.h:89
The second-order results of the moment-closure methods, i.e.
std::vector< std::vector< std::vector< std::size_t > > > class_block
state coordinates of each (station,class): Sigma is indexed by SERVICE PHASE, so reading a per-class ...
Matrix< double > Sigma
state-level covariance, on range(D)
Matrix< double > QStd
per station and class queue-length variance
std::vector< double > refinement
the 1/N correction, mnrefined only
std::vector< double > sigma2
per-station population variance
The assembled drift: the layout, the events, and the per-station schedule.
Definition fluid_odes.h:195
FluidRateMult ratemult
solver_fluid_ratemult's multiplier; empty is the autonomous drift.
Definition fluid_odes.h:220
std::vector< std::vector< double > > lld
sn.lldscaling(i,:) per station, EMPTY when the station has none or when every entry is one – the refe...
Definition fluid_odes.h:216
options.config.rate_sched: explicit per-(station, class) rate trajectories, the third source solver_f...
double nominal
The nominal baked into rate_base; <= 0 selects Mu{i}{c}(1).
Controls, defaulting to SolverOptions('Fluid') in the reference.
FluidClosure closure
options.config.moment_sigma2 and options.config.moment_cov: the second moment the drift's non-linear ...
std::vector< std::pair< std::size_t, std::size_t > > nhpp_sched
options.config.nhpp_sched: the (station, class) pairs whose SOURCE carries a non-homogeneous intensit...
std::vector< double > init_sol
initial state; empty selects the default below
double softmin_alpha
sharpness of the 'softmin' smoothing
std::string fork_join
options.config.fork_join: which fork-join arm the fixed point takes, 'default'/'mmt'/'fjt' or 'ht'.
std::vector< RateSched > rate_sched
std::string highvar
options.config.highvar: which non-exponential FCFS correction the analyzer's outer refit loop applies...
std::size_t nonmkv_order
options.config.nonmkvorder: the phase budget sn_nonmarkov_toph spends on a non-Markovian service law.
std::size_t dae_maxstate
options.config.dae_maxstate and options.config.dae_maxcov: the DAE route's own two refusal thresholds...
std::vector< double > kp_init_sol
options.config.kp_init_sol: the kp method's initial state, in the KO-PENDER layout – one offset count...
double pstar
exponent of the 'pnorm' smoothing
FluidRateMult rate_traj
options.config.rate_traj = {tgrid, Mmat}: a caller-supplied per-EVENT multiplier, which is what the c...
unsigned long seed
'diffusion' RNG seed
bool earlystop
options.config.fluid_earlystop: stop on the geometric tail of the window iteration
double iter_tol
>0 stops early when the moved-mass ratio falls below it; 0 runs to iter_max, as the reference does
double timestep
'diffusion' Euler-Maruyama step
double tol
absolute and relative tolerance handed to the integrator
bool hide_immediate
options.config.hide_immediate: fold the Immediate-rate transitions into the timed ones by stochastic ...
std::string fluid_boundary
options.config.fluid_boundary: how the Petri dae route reports a fluid place level held at a bound,...
std::string nonmkv
options.config.nonmkv: 'bernstein' (default) runs sn_nonmarkov_toph, 'none' skips it; any other name ...
double aoi_preemption
options.config.aoi_preemption: the preemption (bufferless) or replacement (single buffer) probability...
Matrix< double > init_qcov
options.config.init_qcov: the companion covariance of init_qlen, over the station-class pairs,...
std::size_t iter_max
cap on outer integrations
std::vector< std::vector< std::size_t > > tbi_cells
options.config.tbi_cells: an explicit partition for method tbi, as disjoint 0-BASED station index set...
Matrix< double > init_qlen
options.config.init_qlen: the kp method's initial state over (station, class) PAIRS,...
bool pstar_set
Opt in to the p-norm under matrix/default too, which is what options.config.pstar does in MATLAB,...
bool stiff
options.stiff: integrate the closing family with the explicit stiff arm of fluid_stiff....
Matrix< double > init_cov
options.config.init_cov: the kp method's initial covariance Sigma(0), dim-by-dim in the same layout a...
std::size_t moment_maxstate
options.config.moment_maxstate: the largest phase-resolved state the moment-closure methods will buil...
Port of solver_fluid_ratemult.m's output: a per-event MULTIPLIER on a time grid, evaluated by fluid_i...
Definition fluid_odes.h:155
What the analyzer returns, in the same shape as the MVA solver's result.
bool has_moments
result.solverSpecific.moments: set only by minnormal and mnrefined.
std::vector< double > XN
bool has_aoi
result.solverSpecific.aoiResults: set only by the AoI branch of mfq, where the age laws,...
FluidMomentReport moments
std::string warning
The reference's line_warning text, verbatim, empty when it did not warn.
std::vector< double > xvec
the converged fluid state
solvers::FjMetrics< double > fj
self.result.FJ, set by the fork-join arm (fluid_fork_join_run); empty otherwise.
std::vector< double > CN
std::size_t refit_sweeps
iter of solver_fluid_analyzer.m: the FCFS non-exponential refit sweeps.
One point of a transient trajectory: the metrics at time t.
Matrix< double > QCov
The same second moment as a FULL (M*K)-by-(M*K) covariance, indexed ir = r*M + i, empty wherever QVar...
Matrix< double > QVar
Per-(station,class) queue-length VARIANCE at this instant, empty where the method carries no second m...
static Distrib coxian(const std::vector< T > &mu, const std::vector< T > &phi)
Coxian(mu, phi): phase i completes with probability phi(i) and otherwise moves to phase i+1.
static constexpr double Immediate
Rate of an Immediate distribution; its mean is 1/Immediate = 1e-8.
Definition lang_types.h:829
static constexpr double FineTol
Definition lang_types.h:823
static constexpr double Zero
Definition lang_types.h:825
static constexpr double CoarseTol
Definition lang_types.h:824
A MAP as the pair of matrices (D0, D1).
Definition map_moment.h:53
Matrix< T > D1
Definition map_moment.h:55
Matrix< T > D0
Definition map_moment.h:54
self.result.FJ: one row per Fork/Join pair, one column per class.
Definition fj_metrics.h:43