LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
solver_ctmc_analyzer.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_CTMC_SOLVER_CTMC_ANALYZER_H
6#define LINE_SOLVERS_CTMC_SOLVER_CTMC_ANALYZER_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * Port of `solver_ctmc_analyzer.m` and the parts of `@@SolverCTMC/runAnalyzer.m`
12 * that surround one solve: the method gate, the open-model CUTOFF, the state
13 * space and synchronization construction, the stationary solve with its
14 * reducible-generator handling, and the mapping onto the AvgTable columns.
15 *
16 * WHAT THE CUTOFF IS, AND WHY IT IS NOT A TOLERANCE. A closed class carries its
17 * own population, so its lattice is finite. An open class does not, so the
18 * chain is infinite and the reference TRUNCATES it at `options.cutoff` jobs per
19 * class. The answer is therefore the exact stationary law of a DIFFERENT chain,
20 * one the truncation defined, and it converges to the model's only as the
21 * cutoff grows. That is why the reference prints a warning on every open model
22 * and why the banner here reports the cutoff it used: a CTMC number for an open
23 * model is not a number without it.
24 *
25 * REDUCIBILITY. `space_generator` enumerates every state the ENCODING admits,
26 * and the dynamics need not reach all of them; the generator is then reducible
27 * and pi is not unique. The reference resolves this by keeping the weakly
28 * connected component of the INITIAL state, and falling back to the largest
29 * component when the initial state is not in the space at all. Solving the whole
30 * generator instead -- which is what `ctmc_solve` does on its own, splitting
31 * per component and renormalizing -- spreads mass over states the model can
32 * never occupy and moves every reported mean.
33 */
34
36#include <algorithm>
37#include <cmath>
38#include <cstddef>
39#include <limits>
40#include <map>
41#include <string>
42#include <vector>
43
50#include "line/lang/qn/fj_tag.h"
55#include "line/lang/qn/state.h"
64#include "line/util/error.h"
65#include "line/util/matrix.h"
66
67namespace line {
68namespace ctmc {
69
70/**
71 * `SolverOptions.m:107`: the per-class state-space cutoff SolverCTMC defaults an
72 * open or mixed model to. It is a SOLVER default, not a fallback computed from
73 * the model, and the reference's `ceil(6000^(1/(M*K)))` is reached only from an
74 * explicitly infinite request. See `resolve_cutoff`.
75 */
76constexpr std::size_t CTMC_DEFAULT_CUTOFF = 10;
77
78/**
79 * One entry of `options.config.rate_sched`: the rate of (station, class)
80 * follows the piecewise-linear schedule (tgrid, rates) over a transient.
81 *
82 * `station` and `cls` are 1-based, as in the MATLAB struct. The multiplier the
83 * generator is scaled by is rate(t) / nominal, where a NaN nominal means the
84 * model's own rate at that (station, class), which is the reference default.
85 * Outside [tgrid.front(), tgrid.back()] the schedule holds its end values.
86 */
88 std::size_t station = 0;
89 std::size_t cls = 0;
90 std::vector<double> tgrid;
91 std::vector<double> rates;
92 double nominal = std::numeric_limits<double>::quiet_NaN();
93};
94
95/**
96 * The SolverCTMC knobs this port honours.
97 *
98 * `cutoff` is per-class when `cutoff_vec` is given and uniform otherwise; a
99 * negative `cutoff` means "not given" and takes the reference's solver default
100 * `CTMC_DEFAULT_CUTOFF`, while an infinite one takes its automatic value,
101 * `ceil(6000^(1/(M*K)))`.
102 */
104 std::string method = "default";
105 /**
106 * Keep the per-synchronization EVENT FILTRATION alongside Q.
107 *
108 * Off by default because it costs one n x n matrix per synchronization,
109 * which on a model with many routing pairs dwarfs the generator itself. The
110 * response-time CDF needs it, since splitting Q on one event cannot be done
111 * after the contributions have been summed.
112 */
113 bool keep_filtration = false;
114 double cutoff = -1.0; ///< < 0 = not given
115 std::vector<std::size_t> cutoff_vec; ///< per-class override, or empty
116 /**
117 * `options.cutoff` AS A (station x class) MATRIX, or empty.
118 *
119 * The reference accepts a matrix wherever a model needs a different
120 * truncation per station -- oqn_cs_routing writes `[1,1,0;3,3,0;0,0,3]`,
121 * which bounds each queue only in the classes it actually serves. Reducing
122 * that to its per-class maximum enumerates a far larger chain and answers a
123 * different model, so it is carried whole and applied per station in
124 * `space_capacity_c`.
125 */
126 std::vector<std::vector<std::size_t>> cutoff_mat;
127 std::size_t state_max = 3000000; ///< refuse a space larger than this
128 /// `options.force`: downgrade the memory pre-gate's refusal to a warning.
129 bool force = false;
130 /// `options.memorySafetyFraction`: share of available memory a solve may target.
132 /**
133 * `options.config.nonmkvorder`: the phase budget `sn_nonmarkov_toph` spends
134 * on a non-Markovian service law. The reference default is 20, and it is a
135 * real cost here -- every phase multiplies the state space.
136 */
137 std::size_t nonmkv_order = 20;
138 /**
139 * `options.timestep`: the FIXED OUTPUT STEP of a transient analysis.
140 *
141 * <= 0 means adaptive, which is the reference's default and its `[]`. It
142 * changes WHERE the solution is reported and not how it is computed: the
143 * integrator takes the same steps either way, and the grid points are read
144 * off its interpolant. A caller comparing two transients needs the second,
145 * because two adaptive solves land on different time vectors.
146 */
147 double timestep = -1.0;
148 /**
149 * `options.config.transient_method`: "ode" (the default) integrates the
150 * forward equation, "fau" marches fast adaptive uniformization
151 * (`mc::ctmc_fau`) over the output grid.
152 *
153 * It is a config key rather than a value of `method` because it changes no
154 * stationary answer -- it is the transient path only -- and because the
155 * reference's valid-method list is enumerated by its sanity harness, which
156 * then wants a recorded baseline per method.
157 */
158 std::string transient_method = "ode";
159 /**
160 * `options.config.fau_epsilon`: total probability mass the whole grid may
161 * discard under "fau". It is divided by the number of steps, each step
162 * removing mass and none putting any back, so the accumulated defect stays
163 * below it.
164 */
165 double fau_epsilon = 1e-6;
166 /// `options.config.fau_delta`: occupancy below which a state is dropped.
167 double fau_delta = 1e-12;
168 /// `options.config.fau_ngrid`: output grid size when `timestep` is unset.
169 std::size_t fau_ngrid = 100;
170 /**
171 * `options.config.rate_sched`: the TIME-INHOMOGENEOUS transient. Empty means
172 * the constant-rate generator. Transient path only; the stationary solve
173 * ignores it, as the reference's does.
174 */
175 std::vector<CtmcRateSched> rate_sched;
176 /// `options.config.ctmc_tv_ngrid`: uniform grid size of the rate_sched propagator.
177 std::size_t ctmc_tv_ngrid = 100;
178 /**
179 * `options.config.chain_aggregation`: solve the CHAIN-AGGREGATED model.
180 *
181 * The state space grows with the per-class populations, so collapsing every
182 * chain onto a single class is the standard way to make an otherwise
183 * intractable multiclass model solvable: `api::sn_aggregate_chains` builds
184 * the collapsed model and `mva::sn_deaggregate_chain_results` maps the
185 * chain-level metrics back through alpha. EXACT on a product-form model, an
186 * approximation otherwise, since one aggregate service law replaces the
187 * per-class ones. Off by default: a caller who needs the exact multiclass
188 * answer must pay the state space, not discover the trade after the fact.
189 */
190 bool chain_aggregation = false;
191
192 /**
193 * `options.config.transform='lc'`: solve by LOAD CONCEALMENT.
194 *
195 * Birman-Kogan Algorithm 2 as a model transformation: each chain is solved
196 * on its own against the residual capacity the others leave it, with the
197 * single-chain subproblem a real struct this analyzer solves. Distinct from
198 * the `pfqn_bklc` KERNEL, which sweeps a demand matrix and stays the fast
199 * path; see `tr::transform_solve_lc`.
200 */
201 bool load_concealment = false;
202
203 /** Sweep cap for an iterated transformation; the kernel's own default. */
204 std::size_t transform_iter_max = 1000;
205 /**
206 * `options.config.fes_stations`: 1-BASED station indices to collapse into a
207 * flow-equivalent server before the chain is enumerated. Empty by default.
208 *
209 * The collapsed stations' own metrics are recovered by conditioning on the
210 * FES population, so the table still names every station of the model the
211 * caller built; see `solver_ctmc_fes_aggregation`.
212 */
213 std::vector<std::size_t> fes_stations;
214};
215
216/**
217 * Everything one CTMC solve produces.
218 *
219 * `chain` is the generator RESTRICTED to the component that was kept, together
220 * with the state space and the per-state arrival and departure rates on it. The
221 * rates are carried rather than recomputed because Q has already summed every
222 * synchronization's contribution into one entry, and a per-class rate cannot be
223 * recovered from that sum afterwards.
224 */
225template <class T>
228 std::vector<T> pi; ///< stationary distribution over chain.space
230 std::vector<std::size_t> cutoff; ///< the per-class cutoff actually used
231 std::string actualmethod = "default";
232 /**
233 * `fjclassmap` when the model was fork-join, empty otherwise: the ORIGINAL
234 * class of each auxiliary sibling class of the AUGMENTED struct that `chain`
235 * and `pi` are indexed by. `avg` is already folded back onto the original
236 * classes, so this is what relates the two index spaces.
237 */
238 std::vector<std::size_t> fjclassmap;
239 /**
240 * What the chain says about the model's Cache nodes: exact, since the hit
241 * and miss shares are read off the stationary law rather than approximated.
242 * Empty on a model with no Cache.
243 */
245 /** Set when the chain is a reducible mixture solved from an invented seed. */
246 std::string warning;
247};
248
249/**
250 * Port of `SolverCTMC.listValidMethods`.
251 *
252 * `exact` is an explicit ALIAS for the default state-space path: it pins the
253 * intent at the call site so an example or test cannot be re-baselined by a
254 * later change of what `default` selects. It must stay behaviourally identical
255 * to `default` -- nothing below branches on the name -- and that equivalence is
256 * the point of the alias.
257 *
258 * `mdd` never builds the explicit generator, so it is served by
259 * `solver_ctmc_mdd_analyzer` and returns before this file's state-space
260 * machinery is reached; it appears here only because this is the list the gate
261 * below is read against. The perfect sampler `cftp` / `cftp.approx` is a
262 * SolverNC method (`nc/solver_nc_cftp.h`) and is an unknown name here.
263 */
264inline std::vector<std::string> list_valid_methods() {
265 return {"default", "exact", "mdd"};
266}
267
268/** True for a method whose analyzer is not the explicit-generator one. */
269inline bool is_stateless_method(const std::string& method) {
270 return method == "mdd";
271}
272
273/**
274 * Port of `runAnalyzerChecks`' method gate.
275 *
276 * `mdd` IS refused here, because reaching THIS analyzer with that name means
277 * the caller routed a generator-free method into the generator path: the answer
278 * would be the enumerated one under a reported method that never ran. Its own
279 * entry point does not call this gate.
280 */
281inline void check_method(const std::string& method) {
282 const std::vector<std::string> valid = list_valid_methods();
283 if (std::find(valid.begin(), valid.end(), method) == valid.end())
284 throw UnsupportedError("SolverCTMC: the '" + method +
285 "' method is unsupported by this solver");
286 if (is_stateless_method(method))
287 throw UnsupportedError("SolverCTMC: the '" + method +
288 "' method does not enumerate a state space and is served by its "
289 "own analyzer, not by solver_ctmc_analyzer");
290}
291
292/**
293 * Refuse the constructs this port generates a chain for but does not MODEL.
294 *
295 * WHY A GATE AND NOT A TODO. A construct this port generates a chain for but does
296 * not MODEL comes back as a complete, plausible AvgTable computed from a chain
297 * that is not the model's, and a caller has no way to tell. Where the reference
298 * declares the construct supported, silence here would show two different answers
299 * with no indication which is wrong.
300 *
301 * As of this change the list is empty of structural gaps: fork-join goes through
302 * `fj_tag`, class and joint dependence through `cd_factor`, and BAS through the
303 * blocked marker. What remains are the DECLARATION defects below -- a dependence
304 * handle with no peak -- plus the refusals stated by name elsewhere
305 * (`getSymbolicGenerator`, a matrix-exponential `getProb`, `getCdfRespT` on an
306 * open model, and every region rule but DROP and WAITQ).
307 */
308template <class T>
310 // Server breakdowns are MODELLED (2026-09-23): `refresh_local_vars` reserves
311 // the trailing status column, `append_local_vars` enumerates it, and
312 // `after_event_station` fires FAILURE and REPAIR against it and suspends or
313 // degrades service while it is down, as `State.afterEventStation` does.
314 // Class dependence requires a DECLARED peak, and unlike the handle itself
315 // the peak cannot be derived: `cd_factor` scales the generator correctly
316 // without it, but the utilization column would then silently fall back to the
317 // busy-server probability, which at a station whose beta emulates extra
318 // servers is not a utilization. `getLimitedClassDependencePeak` makes it
319 // mandatory in the reference, so a missing peak is a model defect.
320 for (std::size_t i = 0; i < sn.stations.size(); ++i) {
321 if (sn.stations[i].cdscaling && sn.stations[i].cdscalingpeak.empty())
322 throw InputError(
323 "SolverCTMC: station '" + sn.stations[i].name +
324 "' declares class-dependent service without a peak rate. Utilization at a "
325 "class-dependent station is reported as T/mu/peak, so pass the peak to "
326 "setClassDependence");
327 if (sn.stations[i].jdscaling && sn.stations[i].jdscalingpeak.empty())
328 throw InputError(
329 "SolverCTMC: station '" + sn.stations[i].name +
330 "' declares joint-dependent service without a peak rate; pass the peak to "
331 "setJointDependence");
332 }
333 // BAS / BBS / RSRD are SOLVED, not refused, and the two tiers are the
334 // reference's, not a shortcut here:
335 //
336 // BAS gets the blocked marker. `refresh_bas_blocking` reserves the column,
337 // the generator emits the become-blocked edge, the departure handler clears
338 // it at 1e7 and `solver_ctmc_avg_from_pi` moves the held job to its
339 // destination. The chain is exact.
340 //
341 // BBS and RSRD get the DISABLED DEPARTURE only -- `arrival_is_lost` returns
342 // false, so the completion that would move the job is simply not generated
343 // until room frees. `declaresBlockedMarker` tests BAS alone, so the
344 // reference does the same and does not distinguish repetitive service from
345 // a random redraw of the destination. The server freezes with the job in
346 // it, which is the right occupancy but not the right sample path for RSRD.
347 //
348 // `solver_ctmc_waitq` still refuses all three on ITS path: the WAITQ
349 // generator augments the state with a per-region token FIFO and would have to
350 // carry the marker through that augmentation as well.
351}
352
353namespace analyzer_detail {
354
355/**
356 * The per-class cutoff of `@@SolverCTMC/runAnalyzer.m`.
357 *
358 * A closed class never consults it; an open one takes the caller's value.
359 *
360 * THE DEFAULT IS 10, NOT THE 6000-STATE BUDGET. `SolverOptions.m:107` sets
361 * `options.cutoff = 10` for SolverCTMC, so `runAnalyzer`'s
362 * `ceil(6000^(1/(M*K)))` fallback is reached only when the caller explicitly
363 * asks for an INFINITE cutoff, which is the one value the truncation cannot
364 * honour. Taking the fallback as the default instead put this port one lattice
365 * step below the reference on every open model and the answers differed in the
366 * third digit with nothing to show for it: on the Exp(0.5) -> three-FCFS-queue
367 * tandem the budget gives 9 and QLen at Q1 came out 0.9437940 against the
368 * reference's 0.9446411, while cutoff 10 reproduces it to every digit.
369 */
370template <class T>
371std::vector<std::size_t> resolve_cutoff(const NetworkStruct<T>& sn, const CtmcOptions& opt) {
372 const std::size_t M = sn.nstations, K = sn.nclasses;
373 std::vector<std::size_t> cut(K, 0);
374 bool any_open = false;
375 for (std::size_t k = 0; k < K; ++k)
376 if (!std::isfinite(sn.njobs()[k])) any_open = true;
377 if (!any_open) return cut;
378
379 if (!opt.cutoff_mat.empty()) {
380 // `spaceGenerator.m`: the LATTICE height of an open class is the largest
381 // bound any station grants it, `max(capacityc(:,r))`; the per-station
382 // entries then bound each node individually.
383 if (opt.cutoff_mat.size() != M)
384 throw InputError("SolverCTMC: the cutoff matrix must have one row per station");
385 for (std::size_t k = 0; k < K; ++k) {
386 if (std::isfinite(sn.njobs()[k])) continue;
387 for (std::size_t i = 0; i < M; ++i) {
388 if (opt.cutoff_mat[i].size() != K)
389 throw InputError(
390 "SolverCTMC: the cutoff matrix must have one column per class");
391 cut[k] = std::max(cut[k], opt.cutoff_mat[i][k]);
392 }
393 }
394 return cut;
395 }
396 if (!opt.cutoff_vec.empty()) {
397 if (opt.cutoff_vec.size() != K)
398 throw InputError("SolverCTMC: the per-class cutoff must have one entry per class");
399 return opt.cutoff_vec;
400 }
401 std::size_t c;
402 if (opt.cutoff > 0 && std::isfinite(opt.cutoff)) {
403 c = static_cast<std::size_t>(opt.cutoff);
404 } else if (opt.cutoff < 0) {
406 } else {
407 const double e = 1.0 / static_cast<double>(M * K);
408 c = static_cast<std::size_t>(std::ceil(std::pow(6000.0, e)));
409 if (c < 1) c = 1;
410 }
411 for (std::size_t k = 0; k < K; ++k)
412 if (!std::isfinite(sn.njobs()[k])) cut[k] = c;
413 return cut;
414}
415
416/**
417 * Port of the `maxPending` rule of `State.spaceGeneratorNodes`.
418 *
419 * Block B of a delayed-hit cache counts the secondary requests merged onto an
420 * in-flight fetch, and an EXACT solver has to enumerate it, so it needs a
421 * truncation level: the closed population bounds it where there is one, the
422 * state-space cutoff where the model is open. `after_event_cache` reads the same
423 * field and REFUSES a merge past the level rather than landing in a state the
424 * enumeration does not hold -- which is why the two must be set together.
425 *
426 * @return false when no cache carries a retrieval system, leaving `out` untouched
427 */
428template <class T>
429bool set_retrieval_truncation(const NetworkStruct<T>& sn, const std::vector<std::size_t>& cutoff,
430 NetworkStruct<T>& out) {
431 bool any = false;
432 for (typename std::map<std::size_t, qn::CacheParam<T>>::const_iterator ci =
433 sn.nodeparam.begin();
434 ci != sn.nodeparam.end(); ++ci)
435 if (ci->second.retrieval_capacity > 0 && !ci->second.retrieval_classes.empty()) any = true;
436 if (!any) return false;
437 long lvl = 0;
438 if (sn.nclosedjobs() > 0) {
439 lvl = static_cast<long>(sn.nclosedjobs()) - 1;
440 } else {
441 std::size_t mx = 0;
442 for (std::size_t k = 0; k < cutoff.size(); ++k) mx = std::max(mx, cutoff[k]);
443 lvl = static_cast<long>(mx) - 1;
444 }
445 if (lvl < 0) lvl = 0;
446 out = sn;
447 for (typename std::map<std::size_t, qn::CacheParam<T>>::iterator ci = out.nodeparam.begin();
448 ci != out.nodeparam.end(); ++ci)
449 if (ci->second.retrieval_capacity > 0) ci->second.max_pending_retrieval = lvl;
450 return true;
451}
452
453/**
454 * Port of `solver_ctmc.m:47-62`: a G-network SIGNAL NEVER RESIDES at a station,
455 * so its per-class capacity there is zero. A REPLY signal is exempt -- it
456 * completes a synchronous call and queues like an ordinary job.
457 *
458 * WHY THE LATTICE CANNOT DISCOVER THIS ON ITS OWN, and why leaving it undiscovered
459 * is not merely slow. `space_generator` walks every marginal admitted by
460 * `classcap` and, at an FCFS-family station, enumerates the ORDERED buffer of each
461 * one, so an uncapped signal class multiplies the buffer alphabet: a cutoff of c
462 * over two classes gives on the order of 2^c sequences where the model has c+1
463 * states. Every one of them is unreachable -- the arrival handler annihilates the
464 * signal instead of seating it -- so the answer is right and only the cost is
465 * wrong, which is exactly what makes it dangerous: it is invisible in the results.
466 *
467 * IT ALSO REPAIRS THE MEMORY GATE, which is the part that turns this from a
468 * slowdown into a kill. `ctmc_state_space_logsize` already drops signal classes
469 * from its buffered set (ctmc_state_space_logsize.h:176), so without this the gate
470 * sizes the SMALL space and clears a generation of the large one. Measured on the
471 * `test_ctmc_signal_util` G-network at the cutoff of 30 its tests ask for, the
472 * unfixed enumeration was OOM-killed at 43.6 GB resident.
473 *
474 * @return false when the model declares no annihilating signal, leaving `out` untouched
475 */
476template <class T>
477bool annihilate_signal_capacity(const NetworkStruct<T>& sn, NetworkStruct<T>& out) {
478 std::vector<bool> annihilated(sn.nclasses, false);
479 bool any = false;
480 for (std::size_t k = 0; k < sn.nclasses && k < sn.issignal.size(); ++k) {
481 if (!sn.issignal[k]) continue;
482 if (k < sn.signaltype.size() && sn.signaltype[k] == lang::SignalType::REPLY) continue;
483 annihilated[k] = true;
484 any = true;
485 }
486 if (!any) return false;
487 out = sn;
488 for (std::size_t i = 0; i < out.stations.size() && i < out.classcap.size(); ++i) {
489 // The Source is where a signal is BORN, so its capacity there is what the
490 // arrival stream is drawn from and must not be zeroed.
491 if (out.stations[i].sched == SchedStrategy::EXT) continue;
492 for (std::size_t k = 0; k < annihilated.size() && k < out.classcap[i].size(); ++k)
493 if (annihilated[k]) out.classcap[i][k] = 0.0;
494 }
495 return true;
496}
497
498/**
499 * Port of the cache write-back of `solver_ctmc_analyzer.m:333-450`.
500 *
501 * WHAT A CACHE'S HIT AND MISS SHARES ARE, ON A CHAIN. A read leaves the cache in
502 * its configured hit class or its miss class and in no other, so the two
503 * departure rates of those classes at the cache node ARE the hit and the miss
504 * flows, and normalizing by their sum gives the shares. Nothing here reads the
505 * routing matrix, whose cache entries `refresh_routing` resolved to a uniform
506 * split that is not the answer.
507 *
508 * THE DELAYED HIT IS A TRANSITION REWARD, NOT A STATE REWARD, and that is the
509 * whole reason this is not two lines. A merged secondary request departs in the
510 * HIT class, so the hit-class rate above is (true hits + delayed hits) and
511 * something has to split it. A fetch of item i completes on exactly the
512 * transitions that clear block A bit i, and each such transition releases the
513 * block-B count of item i, so the delayed rate is the pi-weighted sum of
514 * (count held) x (rate out on those transitions). The alternative identity
515 * lambda_i * phi_i is only PASTA-exact and would be wrong on a closed model.
516 *
517 * `phi` and `d1` are ordinary state rewards of the same two blocks and give the
518 * per-item DelayedHitQLen columns.
519 *
520 * `latency` is Little's law over the retrieval sub-system,
521 *
522 * Z_k = (sum_i phi_{i,k} + sum_i d_{i,k}) / (miss_k + delayed_k)
523 *
524 * the requests the sub-system holds over the rate at which they enter it. The
525 * numerator is the primary request of every in-flight fetch, counted as the network
526 * population of that read class's retrieval classes (block A is indexed by item alone
527 * and cannot be split when two read classes share a cache, whereas the retrieval
528 * classes are per (item, read class) pair), plus the secondary requests merged onto
529 * those fetches. Both terms and the delayed rate are exact rewards of this chain, so
530 * Z_k is exact up to the state space cutoff, which truncates block B and so approaches
531 * the exact value from below.
532 */
533template <class T>
534solvers::CacheMetrics<T> cache_metrics(const NetworkStruct<T>& sn, const CtmcResult<T>& r,
535 const std::vector<T>& pi, const Matrix<T>& QN) {
536 solvers::CacheMetrics<T> out =
537 solvers::cache_metrics_of(sn, std::vector<T>(), std::vector<T>(), std::vector<T>(),
538 std::vector<T>(), Matrix<T>(), Matrix<T>(), std::vector<T>());
539 if (out.caches.empty() || r.space.empty()) return out;
540 const std::size_t K = sn.nclasses, ns = r.space.size();
541 const double dnan = std::numeric_limits<double>::quiet_NaN();
542
543 for (std::size_t c = 0; c < out.caches.size(); ++c) {
544 solvers::CacheNodeMetrics<T>& m = out.caches[c];
545 const std::size_t isf = sn.stateful_index(m.node);
546 if (isf == 0) continue;
547 const qn::CacheParam<T>& cp = sn.nodeparam.find(m.node)->second;
548
549 std::vector<double> tn(K, 0.0);
550 for (std::size_t s = 0; s < ns && s < pi.size(); ++s) {
551 const double p = num_traits<T>::to_double(pi[s]);
552 if (p == 0) continue;
553 if (isf - 1 >= r.dep_rates[s].size()) continue;
554 for (std::size_t k = 0; k < K && k < r.dep_rates[s][isf - 1].size(); ++k)
555 tn[k] += p * num_traits<T>::to_double(r.dep_rates[s][isf - 1][k]);
556 }
557
558 const std::size_t n = cp.nitems;
559 std::size_t tcc = 0;
560 for (std::size_t l = 0; l < cp.itemcap.size(); ++l)
561 if (cp.itemcap[l] > 0) tcc += static_cast<std::size_t>(cp.itemcap[l]);
562 std::vector<std::size_t> rcl, rci, rco;
563 if (cp.retrieval_capacity > 0) qn::cache_retrieval_class_map(cp, rcl, rci, rco);
564 const std::size_t lvw = r.space[0].local[isf - 1].size();
565 const bool retr = !rcl.empty() && lvw >= tcc + n + rcl.size();
566 std::vector<double> drate(K, 0.0), dclass(K, 0.0), inflight(K, 0.0);
567
568 // TIME-STATIONARY per-item occupancy of each list. The contents block of the
569 // local vector holds the item index resident in each cache position, so
570 // P(item i is held by list l) is a state reward of pi. This is the
571 // TIME-WEIGHTED law, the counterpart of the EMBEDDED (per-request) one the
572 // NC/MVA cache algorithms return; the two coincide only under PASTA.
573 // The local row is [per-class counts | contents | block A | block B], so the
574 // contents block sits at the offset the trailing retrieval blocks leave.
575 const std::size_t tail = cp.retrieval_capacity > 0 ? n + rcl.size() : 0;
576 if (n > 0 && tcc > 0 && lvw >= tcc + tail) {
577 const std::size_t coff = lvw - (tcc + tail);
578 const std::size_t h = cp.itemcap.size();
579 Matrix<T> ip(n, h + 1);
580 std::vector<double> acc(n * h, 0.0);
581 std::vector<char> present(n, 0);
582 for (std::size_t s = 0; s < ns && s < pi.size(); ++s) {
583 const double p = num_traits<T>::to_double(pi[s]);
584 if (p == 0) continue;
585 const std::vector<T>& lv = r.space[s].local[isf - 1];
586 std::size_t off = coff;
587 for (std::size_t l = 0; l < h; ++l) {
588 const std::size_t cap =
589 cp.itemcap[l] > 0 ? static_cast<std::size_t>(cp.itemcap[l]) : 0;
590 std::fill(present.begin(), present.end(), 0);
591 for (std::size_t q = 0; q < cap; ++q) {
592 const long it = static_cast<long>(num_traits<T>::to_double(lv[off + q]));
593 if (it >= 1 && static_cast<std::size_t>(it) <= n)
594 present[static_cast<std::size_t>(it) - 1] = 1;
595 }
596 for (std::size_t i = 0; i < n; ++i)
597 if (present[i]) acc[i * h + l] += p;
598 off += cap;
599 }
600 }
601 for (std::size_t i = 0; i < n; ++i) {
602 double miss = 1.0;
603 for (std::size_t l = 0; l < h; ++l) {
604 const double v = acc[i * h + l];
605 ip(i, l + 1) = num_traits<T>::from_double(v);
606 miss -= v;
607 }
608 ip(i, 0) = num_traits<T>::from_double(miss);
609 }
610 m.itemprob = ip;
611 }
612
613 if (retr) {
614 const std::size_t aoff = lvw - (n + rcl.size()), boff = aoff + n;
615 std::vector<double> phi(n, 0.0), d1(n, 0.0);
616 for (std::size_t s = 0; s < ns && s < pi.size(); ++s) {
617 const double p = num_traits<T>::to_double(pi[s]);
618 if (p == 0) continue;
619 const std::vector<T>& lv = r.space[s].local[isf - 1];
620 for (std::size_t i = 0; i < n; ++i)
621 if (num_traits<T>::to_double(lv[aoff + i]) != 0) phi[i] += p;
622 for (std::size_t j = 0; j < rcl.size(); ++j)
623 d1[rci[j] - 1] += p * num_traits<T>::to_double(lv[boff + j]);
624 }
625 m.delayedhitqlen.assign(n, num_traits<T>::from_int(0));
626 m.delayedhitqlenfull.assign(n, num_traits<T>::from_int(0));
627 for (std::size_t i = 0; i < n; ++i) {
628 m.delayedhitqlen[i] = num_traits<T>::from_double(d1[i]);
629 m.delayedhitqlenfull[i] = num_traits<T>::from_double(d1[i] + phi[i]);
630 }
631 for (std::size_t s = 0; s < ns && s < pi.size(); ++s) {
632 const double p = num_traits<T>::to_double(pi[s]);
633 if (p == 0) continue;
634 const std::vector<T>& lv = r.space[s].local[isf - 1];
635 for (std::size_t j = 0; j < rcl.size(); ++j) {
636 const std::size_t i = rci[j] - 1;
637 const double held = num_traits<T>::to_double(lv[boff + j]);
638 if (held <= 0 || num_traits<T>::to_double(lv[aoff + i]) == 0) continue;
639 double completes = 0.0;
640 for (std::size_t b = 0; b < ns; ++b) {
641 if (b == s) continue;
642 const double q = num_traits<T>::to_double(r.Q(s, b));
643 if (q == 0) continue;
644 if (num_traits<T>::to_double(r.space[b].local[isf - 1][aoff + i]) == 0)
645 completes += q;
646 }
647 if (rco[j] - 1 < K) drate[rco[j] - 1] += p * held * completes;
648 }
649 }
650 // The two populations the retrieval sub-system holds, split by the
651 // originating (reading) class, for the expected latency below.
652 for (std::size_t s = 0; s < ns && s < pi.size(); ++s) {
653 const double p = num_traits<T>::to_double(pi[s]);
654 if (p == 0) continue;
655 const std::vector<T>& lv = r.space[s].local[isf - 1];
656 for (std::size_t j = 0; j < rcl.size(); ++j)
657 if (rco[j] - 1 < K)
658 dclass[rco[j] - 1] += p * num_traits<T>::to_double(lv[boff + j]);
659 }
660 for (std::size_t k = 0; k < K; ++k)
661 for (std::size_t i = 0; i < cp.retrieval_classes.size(); ++i) {
662 if (k >= cp.retrieval_classes[i].size()) continue;
663 const std::size_t rc = cp.retrieval_classes[i][k];
664 if (rc == 0 || rc > static_cast<std::size_t>(QN.cols())) continue;
665 for (std::size_t st = 0; st < static_cast<std::size_t>(QN.rows()); ++st)
666 inflight[k] += num_traits<T>::to_double(QN(st, rc - 1));
667 }
668 }
669
670 m.hitprob.assign(K, num_traits<T>::from_double(dnan));
671 m.missprob.assign(K, num_traits<T>::from_double(dnan));
672 if (retr) m.delayedprob.assign(K, num_traits<T>::from_double(dnan));
673 for (std::size_t k = 0; k < K; ++k) {
674 if (k >= cp.hitclass.size() || k >= cp.missclass.size()) continue;
675 const std::size_t h = cp.hitclass[k], mi = cp.missclass[k];
676 if (h == 0 || mi == 0 || h > K || mi > K) continue;
677 const double denom = tn[h - 1] + tn[mi - 1];
678 if (denom <= 0) continue;
679 // Capped at the hit-class flow: the two are the same measurement of
680 // the same transitions, and a floating-point excess would report a
681 // negative true-hit share rather than a zero one.
682 const double d = retr ? std::min(drate[k], tn[h - 1]) : 0.0;
683 m.hitprob[k] = num_traits<T>::from_double((tn[h - 1] - d) / denom);
684 m.missprob[k] = num_traits<T>::from_double(tn[mi - 1] / denom);
685 if (retr) m.delayedprob[k] = num_traits<T>::from_double(d / denom);
686 if (retr && cp.retrieval_queues.find(k) != cp.retrieval_queues.end() &&
687 !cp.retrieval_queues.find(k)->second.empty()) {
688 if (m.latency.empty()) m.latency.assign(K, num_traits<T>::from_double(dnan));
689 const double enter = d + tn[mi - 1];
690 if (enter > GlobalConstants::Zero)
691 m.latency[k] = num_traits<T>::from_double((inflight[k] + dclass[k]) / enter);
692 }
693 }
694 }
695 return out;
696}
697
698/**
699 * Strip the reference's leading infinite-population column from a DECLARED
700 * Source row, so a state written by MATLAB, the JAR or native python names a
701 * row this port's enumerated space actually holds.
702 *
703 * The reference writes a Source as `[Inf | one phase block per class]` --
704 * `[Inf 1 0 0 0 0 0]` for a Source generating the first of six classes -- and
705 * this port's `from_marginal_core`, which the state-space walk runs, writes the
706 * phase blocks alone. The two therefore differ by exactly one column, and an
707 * untranslated row is one wider than every row of the space, so no lookup can
708 * match it and the padding rule cannot help: it left-pads a NARROW candidate
709 * and refuses a wide one. `rewardModel_mm1k` came back from its M2C row as
710 * `solver_ctmc_transient_analyzer: the initial state is not contained in the
711 * state space` while the JAR and native-python rows, each reading its own
712 * encoding, passed.
713 *
714 * The phase block is KEPT rather than rebuilt: a Source with a MAP arrival has
715 * several rows in its local space and which one the model declared is the
716 * caller's statement, not a detail to regenerate.
717 */
718template <class T>
719void strip_reference_source_column(const NetworkStruct<T>& sn, std::size_t ind,
720 std::vector<T>& row) {
721 const std::size_t ist = sn.nodes[ind - 1].station;
722 if (ist == 0 || ist > sn.stations.size()) return;
723 if (sn.stations[ist - 1].nodetype != NodeType::Source &&
724 sn.stations[ist - 1].sched != SchedStrategy::EXT)
725 return;
726 std::size_t w = 0;
727 for (std::size_t r = 0; r < sn.nclasses; ++r) w += sn.phasessz_of(ist, r + 1);
728 // Width is the discriminator rather than the leading value: an exact
729 // arithmetic has no infinity, so the reference's marker arrives as the
730 // MaxInt clamp `to_marginal` uses and cannot be tested for.
731 if (row.size() == w + 1) row.erase(row.begin());
732}
733
734/**
735 * The model's default initial state: every closed class's jobs at its reference
736 * station, everything else empty, which is `Network.initDefault`.
737 *
738 * The first row `from_marginal_node` emits for that marginal is taken. It is
739 * used for two things -- seeding the reachable walk, and choosing a connected
740 * component -- and for both any row with the right marginal serves, since rows
741 * sharing a marginal are mutually reachable by construction.
742 *
743 * @return false when some node admits no state at all for that marginal
744 */
745template <class T>
746bool default_init_state(const NetworkStruct<T>& sn, NetState<T>& init) {
747 const std::size_t R = sn.nclasses;
748 const std::vector<std::size_t>& sfn = sn.stateful_nodes;
749 init.local.assign(sfn.size(), std::vector<T>());
750 for (std::size_t f = 0; f < sfn.size(); ++f) {
751 const std::size_t ind = sfn[f];
752 // A DECLARED STATE WINS OVER THE DEFAULT MARKING, which is the whole
753 // point of declaring one: `setState` is used precisely to move the jobs
754 // off their reference stations, and rebuilding the default here would
755 // answer `getProbSysAggr` for a state the caller did not name. The pair
756 // (statespace, stateprior) is what the writers emit and the reader
757 // stores; the FIRST row is the state when the prior is the trivial one,
758 // and a genuine distribution over several rows is not a single initial
759 // state at all, so only the one-row case is taken.
760 const typename std::map<std::size_t, Matrix<T>>::const_iterator sp =
761 sn.statespace.find(ind);
762 if (sp != sn.statespace.end() && sp->second.rows() == 1 && sp->second.cols() > 0) {
763 std::vector<T> row(sp->second.cols());
764 for (std::size_t c = 0; c < sp->second.cols(); ++c) row[c] = sp->second(0, c);
765 strip_reference_source_column(sn, ind, row);
766 // A ROW OF EXACTLY ONE ENTRY PER CLASS IS A MARGINAL, NOT AN
767 // ENCODED ROW, and the two differ wherever a class is DISABLED at
768 // the station. The reference keeps a column for every class
769 // (`sn.phases` is 1 at a class it does not serve), while this port
770 // drops the block outright (`phases_of` is 0), so a Delay serving
771 // one of three classes has a width-3 row there and a width-1 row
772 // here, LEFT-PADDED to the encoding width. Installing the
773 // reference's row verbatim then puts the jobs in another class's
774 // block: on tut06_cache_lru_zipf the single client job landed where
775 // nothing could serve it and the sample path deadlocked at once,
776 // which is what a state nobody can leave looks like. Rebuilding it
777 // through `from_marginal_node_first` is the same construction the
778 // default branch below uses, so the two agree by construction.
779 std::vector<std::size_t> marg(R, 0), mph(R, 1);
780 const std::size_t mist = sn.nodes[ind - 1].station;
781 bool rebuilt = false;
782 if (row.size() == R && mist != 0) {
783 for (std::size_t r = 0; r < R; ++r) {
784 const double v = num_traits<T>::to_double(row[r]);
785 marg[r] = v > 0.0 ? static_cast<std::size_t>(v + 0.5) : 0;
786 mph[r] = sn.phasessz_of(mist, r + 1);
787 }
788 std::vector<T> built;
789 if (from_marginal_node_first(sn, ind, marg, mph, built) && !built.empty()) {
790 init.local[f] = built;
791 rebuilt = true;
792 }
793 }
794 if (!rebuilt) init.local[f] = row;
795 continue;
796 }
797 const std::size_t ist = sn.nodes[ind - 1].station;
798 std::vector<std::size_t> nmarg(R, 0), ph(R, 1);
799 if (ist != 0) {
800 for (std::size_t r = 0; r < R; ++r) ph[r] = sn.phasessz_of(ist, r + 1);
801 if (sn.stations[ist - 1].nodetype == NodeType::Source) {
802 // The infinite reservoir: one job per class in service, and only
803 // for the classes the Source generates -- the same guard
804 // `space_generator` needs. Without it this returns false on any
805 // model with a downstream-only class, the initial state is
806 // reported as absent, and the reducible-component selection
807 // silently falls back to "largest component": a plausible answer
808 // for the wrong chain.
809 for (std::size_t r = 0; r < R; ++r)
810 if (!sn.disabled[ist - 1][r]) nmarg[r] = 1;
811 } else {
812 for (std::size_t r = 0; r < R; ++r) {
813 const double nj = sn.njobs()[r];
814 if (std::isfinite(nj) && sn.classes[r].refstat == ist)
815 nmarg[r] = static_cast<std::size_t>(nj);
816 }
817 // A PLACE'S DECLARED MARKING IS THE INITIAL STATE, and it is not
818 // derivable from a class population: an OPEN class has none, so
819 // every Place of an open SPN started empty however many tokens
820 // the model put there. On `spn_open_sevenplaces` that dropped
821 // P1's two tokens and P5's one; T4 needs a P5 token to fire, so
822 // the marking never moved past P3 and the chain reported Tput 0
823 // with P3 pinned at the cutoff. `state_initial_occupancy` is the
824 // same accessor `space_capacity_c` sizes the lattice with, so the
825 // two agree on what the model declared.
826 for (std::size_t r = 0; r < R; ++r) {
827 const std::size_t m0 = qn::state_initial_occupancy(sn, ind, r);
828 if (m0 > nmarg[r]) nmarg[r] = m0;
829 }
830 }
831 }
832 if (!from_marginal_node_first(sn, ind, nmarg, ph, init.local[f])) return false;
833 }
834 return true;
835}
836
837/** The index in `space` of the default initial state, or npos. */
838template <class T>
839std::size_t init_state_index(const NetworkStruct<T>& sn, const std::vector<NetState<T>>& space) {
840 const std::size_t npos = static_cast<std::size_t>(-1);
841 if (space.empty()) return npos;
842 NetState<T> init;
843 if (!default_init_state(sn, init)) return npos;
844 for (std::size_t f = 0; f < init.local.size(); ++f) {
845 // Every state of a node carries the node's widest row, left-padded with
846 // zeros; a candidate built at the natural width would never match.
847 const std::size_t w = space[0].local[f].size();
848 if (init.local[f].size() > w) return npos;
849 if (init.local[f].size() < w)
850 init.local[f].insert(init.local[f].begin(), w - init.local[f].size(),
851 num_traits<T>::from_int(0));
852 }
853 const std::vector<double> key = ctmc_detail::state_key(init);
854 for (std::size_t s = 0; s < space.size(); ++s)
855 if (ctmc_detail::state_key(space[s]) == key) return s;
856 return npos;
857}
858
859/**
860 * The initial DISTRIBUTION over `space`: the product of the declared per-node
861 * priors, or a point mass on the default initial state where none is declared.
862 *
863 * Port of the initial-state loop of `@@SolverCTMC/runAnalyzer.m`, which walks
864 * the cartesian product of the per-node state spaces, weights each combination
865 * by the product of its per-node priors, integrates the forward equation once
866 * per combination and SUMS the trajectories with those weights. Every quantity
867 * the transient analyzer reports is linear in pi(t), and pi(t) is linear in
868 * pi(0), so seeding the mixture and integrating ONCE gives the same answer at a
869 * fraction of the cost -- and on ONE time grid, where the reference has to
870 * interpolate its separate adaptive grids onto their union to add them.
871 *
872 * A combination the enumerated space does not contain is an error rather than a
873 * dropped term: it means the declared space and the reachable one disagree, and
874 * renormalizing over what is left would answer for a different prior.
875 *
876 * @return false when a node admits no state at all, as `default_init_state` does
877 */
878template <class T>
879bool init_state_distribution(const NetworkStruct<T>& sn, const std::vector<NetState<T>>& space,
880 std::vector<T>& pi0) {
881 const std::size_t npos = static_cast<std::size_t>(-1);
882 pi0.assign(space.size(), num_traits<T>::from_int(0));
883 if (space.empty()) return false;
884 NetState<T> base;
885 if (!default_init_state(sn, base)) return false;
886 const std::vector<std::size_t>& sfn = sn.stateful_nodes;
887
888 // Per stateful node: the rows it may start in and their probabilities. A
889 // node with no declared prior contributes its default row alone.
890 std::vector<std::vector<std::vector<T>>> rows(sfn.size());
891 std::vector<std::vector<double>> wts(sfn.size());
892 for (std::size_t f = 0; f < sfn.size(); ++f) {
893 const typename std::map<std::size_t, Matrix<T>>::const_iterator ss =
894 sn.statespace.find(sfn[f]);
895 const typename std::map<std::size_t, std::vector<T>>::const_iterator sp =
896 sn.stateprior.find(sfn[f]);
897 if (ss == sn.statespace.end() || sp == sn.stateprior.end() || ss->second.rows() == 0 ||
898 ss->second.rows() != sp->second.size()) {
899 rows[f].push_back(base.local[f]);
900 wts[f].push_back(1.0);
901 continue;
902 }
903 for (std::size_t r = 0; r < ss->second.rows(); ++r) {
904 const double w = num_traits<T>::to_double(sp->second[r]);
905 if (!(w > 0.0)) continue; // a zero-probability row is not a state to visit
906 std::vector<T> row(ss->second.cols());
907 for (std::size_t c = 0; c < ss->second.cols(); ++c) row[c] = ss->second(r, c);
908 strip_reference_source_column(sn, sfn[f], row);
909 rows[f].push_back(row);
910 wts[f].push_back(w);
911 }
912 if (rows[f].empty()) return false;
913 }
914
915 std::vector<std::size_t> pick(sfn.size(), 0);
916 double total = 0.0;
917 for (;;) {
918 NetState<T> cand = base;
919 double w = 1.0;
920 for (std::size_t f = 0; f < sfn.size(); ++f) {
921 cand.local[f] = rows[f][pick[f]];
922 w *= wts[f][pick[f]];
923 // Every state of a node carries the node's widest row, left-padded
924 // with zeros; a candidate at the natural width would never match.
925 const std::size_t wd = space[0].local[f].size();
926 if (cand.local[f].size() > wd) return false;
927 if (cand.local[f].size() < wd)
928 cand.local[f].insert(cand.local[f].begin(), wd - cand.local[f].size(),
929 num_traits<T>::from_int(0));
930 }
931 std::size_t idx = npos;
932 const std::vector<double> key = ctmc_detail::state_key(cand);
933 for (std::size_t s = 0; s < space.size() && idx == npos; ++s)
934 if (ctmc_detail::state_key(space[s]) == key) idx = s;
935 if (idx == npos) return false;
936 pi0[idx] = T(pi0[idx] + num_traits<T>::from_double(w));
937 total += w;
938
939 std::size_t f = 0;
940 for (; f < sfn.size(); ++f) {
941 if (++pick[f] < rows[f].size()) break;
942 pick[f] = 0;
943 }
944 if (f == sfn.size()) break;
945 }
946 if (!(total > 0.0)) return false;
947 // The declared priors are per node and need not multiply to one; the
948 // reference sums the weighted trajectories without renormalizing, so a
949 // prior that already sums to one is unchanged and one that does not is
950 // reported as the reference reports it.
951 return true;
952}
953
954/** Weakly connected components of the generator, as a per-state label. */
955template <class T>
956std::vector<std::size_t> weak_components(const Matrix<T>& Q, std::size_t& ncomp) {
957 const std::size_t n = Q.rows();
958 const std::size_t npos = static_cast<std::size_t>(-1);
959 std::vector<std::size_t> comp(n, npos);
960 ncomp = 0;
961 for (std::size_t s = 0; s < n; ++s) {
962 if (comp[s] != npos) continue;
963 std::vector<std::size_t> stack{s};
964 comp[s] = ncomp;
965 while (!stack.empty()) {
966 const std::size_t u = stack.back();
967 stack.pop_back();
968 for (std::size_t v = 0; v < n; ++v) {
969 if (comp[v] != npos) continue;
970 // The DIAGONAL is minus the row sum and is nonzero at almost
971 // every state, so it must not be read as an edge to itself.
972 if (v == u) continue;
973 if (num_traits<T>::to_double(Q(u, v)) != 0 ||
974 num_traits<T>::to_double(Q(v, u)) != 0) {
975 comp[v] = comp[u];
976 stack.push_back(v);
977 }
978 }
979 }
980 ++ncomp;
981 }
982 return comp;
983}
984
985/** Restrict a CtmcResult to a subset of its states, keeping their order. */
986template <class T>
987CtmcResult<T> restrict_to(const CtmcResult<T>& r, const std::vector<std::size_t>& wset) {
988 CtmcResult<T> out;
989 out.Q = Matrix<T>(wset.size(), wset.size(), num_traits<T>::from_int(0));
990 for (std::size_t a = 0; a < wset.size(); ++a)
991 for (std::size_t b = 0; b < wset.size(); ++b) out.Q(a, b) = r.Q(wset[a], wset[b]);
992 out.space.reserve(wset.size());
993 out.arv_rates.reserve(wset.size());
994 out.dep_rates.reserve(wset.size());
995 for (std::size_t a = 0; a < wset.size(); ++a) {
996 out.space.push_back(r.space[wset[a]]);
997 out.arv_rates.push_back(r.arv_rates[wset[a]]);
998 out.dep_rates.push_back(r.dep_rates[wset[a]]);
999 }
1000 // The filtration is indexed by the SAME rows as Q, so it has to be
1001 // restricted with it or every CDF built from it would index the wrong
1002 // states. Its diagonal is NOT rebuilt: a filtration entry is a rate the
1003 // event contributed, not a generator, and it has no diagonal to speak of.
1004 out.filt.reserve(r.filt.size());
1005 for (std::size_t f = 0; f < r.filt.size(); ++f) {
1006 Matrix<T> F(wset.size(), wset.size(), num_traits<T>::from_int(0));
1007 for (std::size_t a = 0; a < wset.size(); ++a)
1008 for (std::size_t b = 0; b < wset.size(); ++b) F(a, b) = r.filt[f](wset[a], wset[b]);
1009 out.filt.push_back(F);
1010 }
1011 // The submatrix of a generator is not a generator: the rates that left the
1012 // component have to come off the diagonal, or the rows no longer sum to zero
1013 // and the stationary solve is of a matrix that is not a chain.
1014 make_infgen(out.Q);
1015 return out;
1016}
1017
1018} // namespace analyzer_detail
1019
1020/**
1021 * Build the chain of ONE struct, solve it, reduce it.
1022 *
1023 * The state space is the FULL encoding space, as the reference's
1024 * `options.config.state_space_gen` default of 'default' asks for, so the
1025 * reducible handling below is on the normal path and not an edge case. Two
1026 * exceptions force the reachable walk instead: a global synchronization (an SPN)
1027 * and a fork firing list.
1028 *
1029 * Split out of `solver_ctmc_analyzer` so that the fork-join wrapper can run it on
1030 * the AUGMENTED struct without the gates firing twice.
1031 */
1032template <class T>
1034 const std::vector<qn::FjSync<T>>& fjsync) {
1035 CtmcSolution<T> out;
1036 out.cutoff = analyzer_detail::resolve_cutoff(sn_in, opt);
1037 // A delayed-hit cache is enumerated under a declared merge truncation, and
1038 // the events are held to the same one; every other model walks `sn_in`.
1039 NetworkStruct<T> sn_trunc;
1040 const bool retr = analyzer_detail::set_retrieval_truncation(sn_in, out.cutoff, sn_trunc);
1041 const NetworkStruct<T>& sn_r = retr ? sn_trunc : sn_in;
1042 // A signal class holds no place in a station's buffer, and saying so BEFORE
1043 // the memory gate is what keeps the gate's estimate and the generator's
1044 // enumeration measuring the same space; see `annihilate_signal_capacity`.
1045 NetworkStruct<T> sn_sig;
1046 const bool sig = analyzer_detail::annihilate_signal_capacity(sn_r, sn_sig);
1047 const NetworkStruct<T>& sn = sig ? sn_sig : sn_r;
1048
1049 // THE MEMORY PRE-GATE, `@SolverCTMC/runAnalyzer.m:150-164`. It runs BEFORE
1050 // any generation because `state_max` is enforced inside the generator loop,
1051 // so on its own it enumerates up to three million states before refusing --
1052 // and three million is a fixed count that knows nothing about how much
1053 // memory this host actually has. `mdd` never reaches here;
1054 // see the exemption note in ctmc_memory_gate.h, which is load-bearing.
1055 {
1056 mc::CtmcSizeOptions szopt;
1057 szopt.cutoff = opt.cutoff;
1058 const double log_nstates = mc::ctmc_state_space_logsize(sn, szopt);
1059 const mc::CtmcGateResult gate =
1060 mc::ctmc_memory_gate(log_nstates, opt.force, opt.memory_safety_fraction);
1061 if (!gate.ok) throw UnsupportedError(gate.message + " Stopping SolverCTMC.");
1062 }
1063
1064 const std::vector<Sync<T>> sync = refresh_sync(sn);
1065 const std::vector<qn::GlobalSync<T>> gsync = refresh_global_sync(sn);
1066
1067 // AN SPN NEEDS THE REACHABLE WALK, not the lattice enumeration. A firing
1068 // does not conserve the per-chain population, and a Transition's state is
1069 // per-MODE, so no population marginal produces the states in which a mode is
1070 // firing: `from_marginal_node` emits only the all-idle row. Enumerating the
1071 // lattice therefore yields a space every ENABLE lands outside of, and the
1072 // generator comes out empty. The reference forces
1073 // `options.config.state_space_gen = 'reachable'` for exactly this class of
1074 // model; the condition here is the presence of a global synchronization,
1075 // which is the same set.
1076 // A FORK FIRING LIST forces the same choice as an SPN, for the same reason:
1077 // the lattice enumeration walks the per-chain population, and a firing does
1078 // not conserve it -- one parent becomes B siblings in classes the lattice
1079 // gives population 0. The reference sets
1080 // `options.config.state_space_gen = 'reachable'` on every fork-join model.
1081 std::vector<NetState<T>> space;
1082 if (!gsync.empty() || !fjsync.empty()) {
1083 NetState<T> init;
1084 if (!analyzer_detail::default_init_state(sn, init))
1085 throw UnsupportedError(
1086 "SolverCTMC: the model's initial marking admits no state; check the Place "
1087 "populations against the class reference stations");
1088 // THE CUTOFF TRAVELS WITH THE WALK, or an open model never terminates:
1089 // the Source keeps producing and the walk runs to `state_max` instead of
1090 // answering. It is the same bound the lattice arm below applies.
1091 space = reachable_space_generator(sn, init, sync, gsync, opt.state_max, fjsync,
1092 out.cutoff, opt.cutoff_mat);
1093 } else {
1094 space = space_generator(sn, out.cutoff, opt.state_max, opt.cutoff_mat);
1095 }
1096 if (space.empty())
1097 throw UnsupportedError(
1098 "SolverCTMC: the state space is empty; no state satisfies the model's capacities");
1099 // A DROP region censors the chain: the states it forbids are simply never
1100 // occupied, so removing them and letting `make_infgen` re-close the rows IS
1101 // the censored chain. WAITQ and the blocking rules augment the state
1102 // instead and are refused by name inside.
1103 space = ctmc_filter_regions(sn, space);
1104 CtmcResult<T> r = solver_ctmc(sn, space, sync, gsync, opt.keep_filtration, fjsync);
1105 // ELIMINATE THE VANISHING STATES, `solver_ctmc.m:812`. Until this ran the
1106 // port returned the UNREDUCED chain: a Router or Fork pass-through, a firable
1107 // Join and an immediate SPN mode all kept their GlobalConstants::Immediate
1108 // row, so `-a states` and `-a gen` reported a state space the other three
1109 // codebases had already complemented away -- six states against four on
1110 // `fj_tiny_closed`, the two extras carrying 6.1e-09 of the mass each. `-a avg`
1111 // agreed to the digits printed for exactly that reason, which is why the gap
1112 // stayed invisible unless the chain itself was asked for.
1114
1115 const std::size_t npos = static_cast<std::size_t>(-1);
1116 // The initial state is looked up in the REDUCED space: the enumeration index
1117 // no longer addresses the same rows once the vanishing ones are gone.
1118 std::size_t init = analyzer_detail::init_state_index(sn, r.space);
1119
1120 std::size_t ncomp = 0;
1121 const std::vector<std::size_t> comp = analyzer_detail::weak_components(r.Q, ncomp);
1122 if (ncomp > 1) {
1123 std::size_t pick;
1124 if (init != npos) {
1125 pick = comp[init];
1126 } else {
1127 // The initial state is not representable in this space -- an SPN
1128 // whose ENABLE states were folded away, for one -- so the reference
1129 // keeps the largest component instead of failing.
1130 std::vector<std::size_t> sizes(ncomp, 0);
1131 for (std::size_t s = 0; s < comp.size(); ++s) ++sizes[comp[s]];
1132 pick = static_cast<std::size_t>(
1133 std::max_element(sizes.begin(), sizes.end()) - sizes.begin());
1134 }
1135 std::vector<std::size_t> wset;
1136 for (std::size_t s = 0; s < comp.size(); ++s)
1137 if (comp[s] == pick) wset.push_back(s);
1138 // The seed moves WITH the restriction: keeping the pre-restriction row
1139 // would point the block decomposition at whatever state now sits there.
1140 std::size_t moved = npos;
1141 if (init != npos)
1142 for (std::size_t k = 0; k < wset.size(); ++k)
1143 if (wset[k] == init) {
1144 moved = k;
1145 break;
1146 }
1147 init = moved;
1148 r = analyzer_detail::restrict_to(r, wset);
1149 }
1150
1151 // Every stationary solve goes through the block decomposition, as
1152 // `solver_ctmc_analyzer.m` does: the irreducible case is the degenerate one
1153 // BSCC / no transient states, so no dispatch can disagree with the
1154 // algorithm about whether the chain is reducible. `ctmc_solve` splits a
1155 // reducible generator into WEAK components and renormalizes across them,
1156 // which is not the answer the declared initial state selects.
1157 line::util::LineConsole::step("infinitesimal generator built: %zu states",
1158 static_cast<std::size_t>(r.Q.rows()));
1159 line::util::LineConsole::step("solving for the stationary distribution");
1160 const CtmcStationaryResult<T> st = ctmc_stationary(r.Q, init);
1161 line::util::LineConsole::step("stationary distribution obtained, computing the mean metrics");
1162 out.pi = st.pi;
1163 out.warning = st.warning;
1164 out.avg = solver_ctmc_avg_from_pi(sn, r, out.pi);
1165 out.cache = analyzer_detail::cache_metrics(sn, r, out.pi, out.avg.QN);
1166 out.chain = r;
1167 out.actualmethod = opt.method;
1168 return out;
1169}
1170
1171
1172/**
1173 * Port of `solver_ctmc_analyzer.m` plus the fork-join wrapper of
1174 * `@@SolverCTMC/runAnalyzer.m`.
1175 *
1176 * A fork-join model is solved on the TAG-AUGMENTED copy and the sibling classes
1177 * are folded back at the end. The chain and the stationary vector returned are the
1178 * AUGMENTED ones, as the reference's `result.space` is: they are indexed by a
1179 * class set the caller did not declare, which is why `fjclassmap` comes back with
1180 * them rather than being discarded.
1181 */
1182template <class T>
1184 check_method(opt.method);
1185
1186 // `@@SolverCTMC/runAnalyzer.m:126` converts the non-Markovian service laws
1187 // to a Markovian surrogate on its own copy of the struct. The conversion
1188 // runs before the support check, because what the check must see is the
1189 // struct the generator will actually be built from.
1190 //
1191 // THE PH FIT IS FORCED HERE, where the reference takes its CME default.
1192 // MATLAB's CTMC assembles a RATIONAL generator and can carry a matrix
1193 // exponential; this port assembles an ordinary one, and an ME's D0 has
1194 // off-diagonal entries that are not rates, so the chain it builds is not a
1195 // Markov chain. Measured on a closed Delay + Gamma(4, 0.5) FCFS model with
1196 // two jobs: the CME fit gives Util 1.075 -- IMPOSSIBLE for one server --
1197 // and a throughput of 0.538 at the delay against 0.400 at the queue, i.e.
1198 // flow that does not balance around a cycle. The PH fit gives Util 0.950,
1199 // balanced throughput 0.475 and QLen 1.525, against MATLAB's 0.954, 0.477
1200 // and 1.523.
1201 //
1202 // The residual 0.4% IS the divergence from the reference, and it is the
1203 // price of the honest fit: MATLAB matches two moments exactly with its ME
1204 // (scv 0.25) where the Bernstein PH lands at scv 0.323. Closing it needs
1205 // the CTMC to handle a rational generator, which is a separate change.
1206 NetworkStruct<T> converted;
1207 const NetworkStruct<T>* snp = &sn_in;
1208 if constexpr (num_traits<T>::has_transcendental) {
1209 if (api::sn_has_nonmarkov(sn_in, false)) {
1210 converted = sn_in;
1212 no.order = opt.nonmkv_order;
1213 no.phfit = api::PhFit::Ph;
1214 api::sn_nonmarkov_toph(converted, no);
1215 snp = &converted;
1216 }
1217 }
1218 const NetworkStruct<T>& sn = *snp;
1219
1221 // runAnalyzerChecks' universal feature gate, AFTER ctmc_check_support so the
1222 // declaration-defect messages, which the declared set also withholds, still
1223 // win over the gate's generic one.
1224 qn::feature_gate("SolverCTMC", qn::ctmc_feature_set(opt.method), sn);
1225
1226 if (!tr::has_fork_join(sn))
1227 return solve_struct(sn, opt, std::vector<qn::FjSync<T>>());
1228
1229 const qn::FjTagged<T> fjt = qn::fj_tag(sn);
1230 CtmcSolution<T> out = solve_struct(fjt.V, opt, fjt.fjsync);
1231 tr::fj_foldback(sn, out.avg, fjt.fjclassmap, fjt.korig);
1232 out.fjclassmap = fjt.fjclassmap;
1233 return out;
1234}
1235
1236/**
1237 * Port of `@@SolverCTMC/runAnalyzer.m`'s result assembly: solve, then apply the
1238 * metric filter `@@NetworkSolver/getAvg` puts between the analyzer and the
1239 * caller, so the table is the same shape SolverMVA and SolverNC print.
1240 *
1241 * The response-time mask the product-form runners apply -- drop a metric whose
1242 * response time is below the tolerance -- is NOT applied here. A CTMC reports
1243 * what the chain does, and a station a class genuinely visits with a tiny
1244 * response time is a real measurement rather than a numerical artefact of a
1245 * fixed point that did not converge there.
1246 */
1247template <class T>
1249 const std::string& method) {
1250 const std::size_t M = sn.nstations, K = sn.nclasses;
1251
1252 std::vector<std::vector<bool>> srcmask(M, std::vector<bool>(K, false));
1253 for (std::size_t i = 0; i < M; ++i)
1254 if (sn.stations[i].nodetype == NodeType::Source)
1255 for (std::size_t k = 0; k < K; ++k) srcmask[i][k] = true;
1256
1257 // A PLACE IS MEASURED IN TOKENS and the analyzer counts FIRING EVENTS: an
1258 // arc of multiplicity 2 moves two tokens per firing, and an IMMEDIATE mode
1259 // moves them in zero time, which is not a timed event and so is counted by
1260 // no analyzer here or in the reference. `sn_pn_avg_rates` recovers the mode
1261 // firing rates from the flow-balance equations and rewrites the Place rows
1262 // of TN and RN, exactly where `@SolverCTMC/runAnalyzer.m:126` and `:266` do
1263 // it -- on the RAW table, before the filter, and on the ORIGINAL struct,
1264 // since `solver_ctmc_analyzer_any` folds a fork-join tagging back before
1265 // returning. A model with no Place is returned untouched. AN follows below
1266 // from the repaired TN, as `AN = sn_get_arvr_from_tput(sn, TN)` does there.
1267 const api::SnPnAvgRates<T> pn =
1268 api::sn_pn_avg_rates(sn, d.avg.QN, d.avg.TN, Matrix<T>(), d.avg.RN);
1269
1271 o.QN = mva::filter_metric(sn, d.avg.QN, mva::MetricKind::QLen, nullptr);
1272 o.UN = mva::filter_metric(sn, d.avg.UN, mva::MetricKind::Util, nullptr);
1274 o.TN = mva::filter_metric(sn, pn.TN, mva::MetricKind::Tput, nullptr);
1276 mva::MetricKind::ResidT, nullptr);
1278 &srcmask);
1279 o.CN = d.avg.CN;
1280 o.XN = d.avg.XN;
1281 o.cache = d.cache;
1282 o.method = method;
1284 o.iter = 1;
1285 return o;
1286}
1287
1288template <class T>
1289mva::AvgResult<T> solver_ctmc_run_analyzer(const NetworkStruct<T>& sn, const CtmcOptions& opt);
1290
1291/**
1292 * Solve the CHAIN-AGGREGATED model and map its metrics back to the classes.
1293 *
1294 * `api::sn_aggregate_chains` collapses every chain onto a single class, class
1295 * switching disappearing with it, and `mva::sn_deaggregate_chain_results` maps
1296 * chain-level metrics back through alpha, the per-station share of the chain's
1297 * visits each class carries. Both transforms existed in all four codebases with
1298 * no solver consumer; this is that consumer.
1299 *
1300 * WHAT IS TRADED. Exactness on a non-product-form model: one aggregate service
1301 * law, fitted to the alpha-weighted first two moments, replaces the per-class
1302 * ones. On a product-form model the chain IS the unit MVA and convolution
1303 * already solve in, so the answer is exact and the state space is the smaller
1304 * one.
1305 */
1306template <class T>
1308 const CtmcOptions& opt) {
1309 // Driven by tr::transform_solve_chains, so the aggregate is solved through
1310 // an inner-solve seam rather than a hard-wired call to this analyzer.
1311 // Clearing the flag states that the aggregate must not be re-aggregated,
1312 // rather than relying on the caller's nchains < nclasses guard to decline.
1313 CtmcOptions sub = opt;
1314 sub.chain_aggregation = false;
1316 sn,
1317 [&sub](const NetworkStruct<T>& subsn) { return solver_ctmc_run_analyzer(subsn, sub); },
1318 opt.method);
1319}
1320
1321/**
1322 * Solve by LOAD CONCEALMENT, the iterated transformation.
1323 *
1324 * `tr::transform_solve_lc` sweeps the chains in Gauss-Seidel order, solving each
1325 * concealed single-chain struct with THIS analyzer. Clearing the flag on the
1326 * inner options states that a subproblem must not be concealed again, rather
1327 * than relying on its one-chain shape to decline.
1328 */
1329template <class T>
1331 const CtmcOptions& opt) {
1332 CtmcOptions sub = opt;
1333 sub.load_concealment = false;
1335 sn,
1336 [&sub](const NetworkStruct<T>& subsn) { return solver_ctmc_run_analyzer(subsn, sub); },
1337 opt.method, opt.transform_iter_max);
1338}
1339
1340/**
1341 * Solve with a station subset replaced by a FLOW-EQUIVALENT SERVER, then
1342 * recover the collapsed stations' own metrics by conditioning.
1343 *
1344 * `api::fes_aggregate` has existed in all four codebases with no solver
1345 * consumer at all: it was exercised by examples and tests only, so nothing in
1346 * the solver stack depended on it. Flow-equivalent aggregation is the standard
1347 * route to HIERARCHICAL DECOMPOSITION -- a subnetwork is solved in isolation
1348 * and enters the outer chain as a single load-dependent station, which is what
1349 * makes an otherwise intractable state space tractable.
1350 *
1351 * The reduced model answers for the surviving stations directly. For a
1352 * collapsed station the answer is the Chandy-Herzog-Woo conditional sum
1353 * E[Q_i] = sum_n P(N_fes = n) * Q_i(n), with P read off the reduced chain's
1354 * stationary law and Q_i(n) from the isolated subnetwork
1355 * (`fes::fes_compute_metrics`). Throughput needs no conditioning: flow is fixed
1356 * by the routing and an exact reduction leaves the chain throughput unchanged.
1357 *
1358 * EXACT when the collapsed subnetwork is product-form, which is the condition
1359 * `fes_aggregate` already imposes; an approximation otherwise, and the
1360 * state-space saving is the reason to accept that.
1361 */
1362template <class T>
1364 const CtmcOptions& opt) {
1365 const std::size_t M = sn.nstations, K = sn.nclasses;
1366 const std::vector<std::size_t>& subset = opt.fes_stations;
1367 if (subset.size() < 2)
1368 throw InputError(
1369 "options.config.fes_stations must name at least two stations: collapsing one "
1370 "station into a flow-equivalent server saves nothing.");
1371 if (subset.size() >= M)
1372 throw InputError(
1373 "options.config.fes_stations names every station: there is no complement left "
1374 "to solve.");
1375 for (std::size_t i : subset)
1376 if (i < 1 || i > M)
1377 throw InputError("options.config.fes_stations must be 1-based station indices in 1.." +
1378 std::to_string(M) + ".");
1379
1381 const fes::FesDeaggInfo<T>& info = agg.deagg;
1382 const NetworkStruct<T>& snRed = agg.model.get_struct();
1383
1384 CtmcOptions sub = opt;
1385 sub.fes_stations.clear();
1386 const CtmcSolution<T> red = solver_ctmc_analyzer(snRed, sub);
1387 const mva::AvgResult<T> redAvg = solver_ctmc_avg_table(snRed, red, sub.method);
1388
1389 // P(N_fes = n). The aggregate state space carries K columns per STATION, at
1390 // (ist-1)*K + k, so the FES's block is the one at its station index.
1391 const Matrix<T> SSq = ctmc_state_space_aggr(snRed, red.chain.space);
1392 const std::size_t fesIst = snRed.nodes[info.fesNode - 1].station;
1393 std::size_t tableSize = 1;
1394 for (int c : info.cutoffs) tableSize *= static_cast<std::size_t>(c + 1);
1395 std::vector<double> Pn(tableSize, 0.0);
1396 for (std::size_t r = 0; r < SSq.rows(); ++r) {
1397 std::vector<int> nvec(K, 0);
1398 for (std::size_t k = 0; k < K; ++k)
1399 nvec[k] = static_cast<int>(
1400 std::llround(num_traits<T>::to_double(SSq(r, (fesIst - 1) * K + k))));
1401 Pn[fes::ljd_linearize(nvec, info.cutoffs) - 1] +=
1402 r < red.pi.size() ? num_traits<T>::to_double(red.pi[r]) : 0.0;
1403 }
1404
1407
1408 const T zero = num_traits<T>::from_int(0);
1410 out.QN = Matrix<T>(M, K, zero);
1411 out.UN = Matrix<T>(M, K, zero);
1412 out.RN = Matrix<T>(M, K, zero);
1413 out.TN = Matrix<T>(M, K, zero);
1414
1415 for (std::size_t a = 0; a < info.complementIndices.size(); ++a) {
1416 const std::size_t i = info.complementIndices[a] - 1;
1417 for (std::size_t k = 0; k < K; ++k) {
1418 out.QN(i, k) = redAvg.QN(a, k);
1419 out.UN(i, k) = redAvg.UN(a, k);
1420 out.TN(i, k) = redAvg.TN(a, k);
1421 }
1422 }
1423
1424 const std::size_t Msub = info.subsetIndices.size();
1425 Matrix<T> Qsub(Msub, K, zero), Usub(Msub, K, zero);
1426 for (std::size_t idx = 0; idx < tableSize; ++idx) {
1427 if (!(Pn[idx] > 0.0)) continue;
1428 const T w = num_traits<T>::from_double(Pn[idx]);
1429 for (std::size_t a = 0; a < Msub && a < cm.QN[idx].rows(); ++a)
1430 for (std::size_t k = 0; k < K; ++k) {
1431 Qsub(a, k) += T(w * cm.QN[idx](a, k));
1432 Usub(a, k) += T(w * cm.UN[idx](a, k));
1433 }
1434 }
1435 for (std::size_t a = 0; a < Msub; ++a) {
1436 const std::size_t i = info.subsetIndices[a] - 1;
1437 for (std::size_t k = 0; k < K; ++k) {
1438 out.QN(i, k) = Qsub(a, k);
1439 out.UN(i, k) = Usub(a, k);
1440 // Flow through a station is fixed by the routing, so it is the FES's
1441 // throughput scaled by the ratio of ORIGINAL visit ratios.
1442 T ratio = zero;
1443 for (std::size_t c = 0; c < sn.nchains; ++c) {
1444 const std::size_t isf = sn.stateful_of_station(i + 1) - 1;
1445 const std::size_t isfFes = snRed.stateful_of_station(fesIst) - 1;
1446 if (isf < sn.visits[c].rows() && isfFes < snRed.visits[c].rows() &&
1447 snRed.visits[c](isfFes, k) > zero)
1448 ratio += T(sn.visits[c](isf, k) / snRed.visits[c](isfFes, k));
1449 }
1450 out.TN(i, k) = T(redAvg.TN(fesIst - 1, k) * ratio);
1451 }
1452 }
1453
1454 out.CN.assign(K, zero);
1455 out.XN = redAvg.XN;
1456 for (std::size_t i = 0; i < M; ++i)
1457 for (std::size_t k = 0; k < K; ++k) {
1458 if (out.TN(i, k) > zero) out.RN(i, k) = T(out.QN(i, k) / out.TN(i, k));
1459 out.CN[k] += out.RN(i, k);
1460 }
1461 out.AN = mva::sn_get_arvr_from_tput(sn, out.TN);
1463 out.method = opt.method;
1464 out.actualmethod = opt.method + "/fes";
1465 return out;
1466}
1467
1468/** Solve and format in one call, for a caller with no use for the chain. */
1469template <class T>
1471 // Chain aggregation, opt-in and only where the transform is not the identity.
1472 if (opt.load_concealment) return solver_ctmc_load_concealment(sn, opt);
1473 if (opt.chain_aggregation && sn.nchains < sn.nclasses)
1475 // Flow-equivalent server aggregation, opt-in.
1476 if (!opt.fes_stations.empty()) return solver_ctmc_fes_aggregation(sn, opt);
1478}
1479
1480} // namespace ctmc
1481} // namespace line
1482
1483#endif // LINE_SOLVERS_CTMC_SOLVER_CTMC_ANALYZER_H
What a solver observed about the Cache nodes of a model.
InputError(const std::string &what)
Definition error.h:39
std::size_t rows() const
Definition matrix.h:89
UnsupportedError(const std::string &what)
Definition error.h:51
A network plus its refreshed NetworkStruct.
std::size_t stateful_of_station(std::size_t st) const
std::vector< NodeDef > nodes
every node, in creation order
std::vector< Matrix< T > > visits
(nchains) each (nstateful x nclasses)
static void step(const char *fmt,...)
Write one progress line.
Host-aware memory pre-gate for SolverCTMC.
Steady-state distribution of a continuous-time Markov chain.
Worst-case log-size of the CTMC state space induced by a NetworkStruct.
Port of matlab/src/solvers/CTMC/ctmc_stationary.m: the single entry point for the stationary distribu...
The exception types the port throws.
Flow-equivalent-server aggregation: replace a station subset by one station.
Per-station metrics of the ISOLATED subnetwork at every population state, the companion of fes_comput...
Port of matlab/src/api/fj/sn_fj_validate.m and matlab/src/io/@@ModelAdapter/fjtag....
Fork-join TAG AUGMENTATION: the fold-back half of the transform/lift pair that CTMC and SSA share.
Running progress log of a LINE solver run (the "solver console").
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...
SnPnAvgRates< T > sn_pn_avg_rates(const qn::NetworkStruct< T > &sn, const Matrix< T > &QN, const Matrix< T > &TN, const Matrix< T > &AN, const Matrix< T > &RN)
Port of sn_pn_avg_rates: rewrite the place rows of TN, AN and RN so that they agree with the recovere...
@ 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.
mva::AvgResult< T > solver_ctmc_fes_aggregation(const NetworkStruct< T > &sn, const CtmcOptions &opt)
Solve with a station subset replaced by a FLOW-EQUIVALENT SERVER, then recover the collapsed stations...
void ctmc_eliminate_vanishing(CtmcResult< T > &res)
Port of the "now remove immediate transitions" block of solver_ctmc.m (:812-870): eliminate the vanis...
mva::AvgResult< T > solver_ctmc_chain_aggregation(const NetworkStruct< T > &sn, const CtmcOptions &opt)
Solve the CHAIN-AGGREGATED model and map its metrics back to the classes.
void check_method(const std::string &method)
Port of runAnalyzerChecks' method gate.
std::vector< std::string > list_valid_methods()
Port of SolverCTMC.listValidMethods.
void ctmc_check_support(const NetworkStruct< T > &sn)
Refuse the constructs this port generates a chain for but does not MODEL.
void make_infgen(Matrix< T > &Q)
Port of ctmc_makeinfgen: turn an off-diagonal rate matrix into a generator.
mva::AvgResult< T > solver_ctmc_avg_table(const NetworkStruct< T > &sn, const CtmcSolution< T > &d, const std::string &method)
Port of @@SolverCTMC/runAnalyzer.m's result assembly: solve, then apply the metric filter @@NetworkSo...
CtmcAvg< T > solver_ctmc_avg_from_pi(const NetworkStruct< T > &sn, const CtmcResult< T > &r, const std::vector< T > &pivec, bool stationary=true)
Port of solver_ctmc_avg_from_pi: map a state distribution to mean metrics.
mva::AvgResult< T > solver_ctmc_load_concealment(const NetworkStruct< T > &sn, const CtmcOptions &opt)
Solve by LOAD CONCEALMENT, the iterated transformation.
std::vector< NetState< T > > ctmc_filter_regions(const NetworkStruct< T > &sn, const std::vector< NetState< T > > &space)
The states of space a DROP region admits, in their original order.
CtmcResult< T > solver_ctmc(const NetworkStruct< T > &sn, const std::vector< NetState< T > > &space, const std::vector< Sync< T > > &sync, const std::vector< qn::GlobalSync< T > > &gsync=std::vector< qn::GlobalSync< T > >(), bool want_filtration=false, const std::vector< qn::FjSync< T > > &fjsync=std::vector< qn::FjSync< T > >())
Port of the generator assembly of solver_ctmc.m.
CtmcSolution< T > solve_struct(const NetworkStruct< T > &sn_in, const CtmcOptions &opt, const std::vector< qn::FjSync< T > > &fjsync)
Build the chain of ONE struct, solve it, reduce it.
CtmcSolution< T > solver_ctmc_analyzer(const NetworkStruct< T > &sn_in, const CtmcOptions &opt)
Port of solver_ctmc_analyzer.m plus the fork-join wrapper of @@SolverCTMC/runAnalyzer....
mva::AvgResult< T > solver_ctmc_run_analyzer(const NetworkStruct< T > &sn, const CtmcOptions &opt)
Solve and format in one call, for a caller with no use for the chain.
CtmcStationaryResult< T > ctmc_stationary(const Matrix< T > &Q, std::size_t init_index=static_cast< std::size_t >(-1))
constexpr std::size_t CTMC_DEFAULT_CUTOFF
SolverOptions.m:107: the per-class state-space cutoff SolverCTMC defaults an open or mixed model to.
bool is_stateless_method(const std::string &method)
True for a method whose analyzer is not the explicit-generator one.
Matrix< T > ctmc_state_space_aggr(const NetworkStruct< T > &sn, const std::vector< NetState< T > > &space)
Port of StateSpaceAggr: the per-(station, class) job counts of every state, as an (nstates x nstation...
std::vector< NetState< T > > reachable_space_generator(const NetworkStruct< T > &sn, const NetState< T > &init, const std::vector< Sync< T > > &sync, const std::vector< qn::GlobalSync< T > > &gsync=std::vector< qn::GlobalSync< T > >(), std::size_t maxst=3000000, const std::vector< qn::FjSync< T > > &fjsync=std::vector< qn::FjSync< T > >(), const std::vector< std::size_t > &cutoff=std::vector< std::size_t >(), const std::vector< std::vector< std::size_t > > &cutoff_mat=std::vector< std::vector< std::size_t > >())
Port of State.reachableSpaceGenerator: the states reachable from init.
std::size_t ljd_linearize(const std::vector< int > &nvec, const std::vector< int > &cutoffs)
Linearized index of a per-class population vector, for Limited Joint Dependence (LJD) tables.
FesConditionalMetrics< T > fes_compute_metrics(const Matrix< T > &L, const std::vector< int > &mi, const std::vector< bool > &isDelay, const std::vector< int > &cutoffs)
Per-station metrics of the ISOLATED subnetwork at every population state, the companion of fes_comput...
FesAggregateResult< T > fes_aggregate(const qn::NetworkStruct< T > &sn, const std::vector< std::size_t > &subsetIndices, const FesOptions &options=FesOptions())
Flow-equivalent-server aggregation: replace a station subset by one station.
@ REPLY
completes a synchronous call, releasing a held server
Definition lang_types.h:168
constexpr double CTMC_DEFAULT_SAFETY_FRACTION
Fraction of available memory the solver may target.
CtmcGateResult ctmc_memory_gate(double log_nstates, bool force=false, double safety_fraction=CTMC_DEFAULT_SAFETY_FRACTION)
Decide whether a state space of log-size log_nstates can be solved here.
double ctmc_state_space_logsize(const qn::NetworkStruct< T > &sn, const CtmcSizeOptions &opt=CtmcSizeOptions())
Worst-case log state-space size of sn.
Matrix< T > sn_get_residt_from_respt(const qn::NetworkStruct< T > &L, const Matrix< T > &RN)
Port of sn_get_residt_from_respt: the per-JOB residence time.
Matrix< T > filter_metric(const qn::NetworkStruct< T > &L, const Matrix< T > &metric, MetricKind kind, const std::vector< std::vector< bool > > *zero_mask)
Port of filterMetric: what @@NetworkSolver/getAvg does between the analyzer and the caller.
Matrix< T > sn_get_arvr_from_tput(const qn::NetworkStruct< T > &L, const Matrix< T > &TN)
void cache_retrieval_class_map(const CacheParam< T > &cp, std::vector< std::size_t > &rc_list, std::vector< std::size_t > &rc_items, std::vector< std::size_t > &rc_orig)
Port of State.cacheRetrievalClassMap: the canonical order of a cache's retrieval classes,...
bool from_marginal_node_first(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< std::size_t > &n, const std::vector< std::size_t > &phases, std::vector< T > &out)
The FIRST row from_marginal_node emits, BUILT rather than enumerated.
Definition state.h:2022
std::size_t state_initial_occupancy(const NetworkStruct< T > &sn, std::size_t ind, std::size_t r)
Port of State.initialOccupancy: the class-r jobs node ind holds in the DECLARED initial state,...
Definition state.h:2171
FeatureSet ctmc_feature_set(const std::string &method)
SolverCTMC.getFeatureSet, the reference's 104 MATLAB names in full.
void feature_gate(const std::string &solver, const FeatureSet &declared, const NetworkStruct< T > &sn, const std::string &requested_method="", const std::string &resolved_method="")
runAnalyzerChecks: refuse a model the solver does not declare, by name.
FjTagged< T > fj_tag(const NetworkStruct< T > &sn)
Port of ModelAdapter.fjtag.
Definition fj_tag.h:302
CacheMetrics< T > cache_metrics_of(const qn::NetworkStruct< T > &sn, const std::vector< T > &hitprob, const std::vector< T > &missprob, const std::vector< T > &delayedprob, const std::vector< T > &latency, const Matrix< T > &hitproblist, const Matrix< T > &itemprob, const std::vector< T > &listcost)
Assemble CacheMetrics from what a cache analyzer returned.
mva::AvgResult< T > transform_solve_lc(const qn::NetworkStruct< T > &sn, InnerSolve inner_solve, const std::string &method, std::size_t iter_max=1000)
LOAD CONCEALMENT (Birman-Kogan Algorithm 2) as a transformation, and the first ITERATED one.
void fj_foldback(const qn::NetworkStruct< T > &sn, Avg &a, const std::vector< std::size_t > &fjclassmap, std::size_t korig)
Reduce the augmented metrics onto the original classes.
mva::AvgResult< T > transform_solve_chains(const qn::NetworkStruct< T > &sn, InnerSolve inner_solve, const std::string &method)
Chain aggregation: collapse every chain onto a single class, solve, and map the chain metrics back on...
bool has_fork_join(const qn::NetworkStruct< T > &sn)
Whether the model needs the tag augmentation at all.
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:52
A queueing network and its refreshed NetworkStruct.
Collapse every chain onto one class, port of ModelAdapter.aggregateChains.
Replace every non-Markovian service and firing law by a Markovian surrogate.
Ports of matlab/src/api/sn/sn_pn_firing_rates.m and sn_pn_avg_rates.m.
Port of solver_ctmc.m: the infinitesimal generator of a queueing network, assembled from the enumerat...
Finite Capacity Regions in SolverCTMC: the DROP rule, as a filter on the enumerated state space,...
The DECLARED side of the gate: one feature set per solver.
The SolverMVA class surface: @@SolverMVA/runAnalyzer.m and the gates around it.
Port of the MATLAB +State package: the encoding that turns a station's state row into marginal job co...
Port of the event half of MATLAB's +State package: the successor states an event produces at one node...
options.config.nonmkv and friends.
std::size_t order
nonmkvorder, the phase budget
PhFit phfit
which surrogate family
What sn_pn_avg_rates rewrites in place; empty tables are left empty.
The mean performance metrics a stationary vector maps to.
The SolverCTMC knobs this port honours.
bool force
options.force: downgrade the memory pre-gate's refusal to a warning.
double memory_safety_fraction
options.memorySafetyFraction: share of available memory a solve may target.
std::vector< std::size_t > cutoff_vec
per-class override, or empty
std::size_t nonmkv_order
options.config.nonmkvorder: the phase budget sn_nonmarkov_toph spends on a non-Markovian service law.
bool load_concealment
options.config.transform='lc': solve by LOAD CONCEALMENT.
std::size_t transform_iter_max
Sweep cap for an iterated transformation; the kernel's own default.
std::vector< std::vector< std::size_t > > cutoff_mat
options.cutoff AS A (station x class) MATRIX, or empty.
std::vector< std::size_t > fes_stations
options.config.fes_stations: 1-BASED station indices to collapse into a flow-equivalent server before...
std::size_t state_max
refuse a space larger than this
double fau_delta
options.config.fau_delta: occupancy below which a state is dropped.
double cutoff
< 0 = not given
double timestep
options.timestep: the FIXED OUTPUT STEP of a transient analysis.
std::string transient_method
options.config.transient_method: "ode" (the default) integrates the forward equation,...
std::size_t fau_ngrid
options.config.fau_ngrid: output grid size when timestep is unset.
std::vector< CtmcRateSched > rate_sched
options.config.rate_sched: the TIME-INHOMOGENEOUS transient.
bool chain_aggregation
options.config.chain_aggregation: solve the CHAIN-AGGREGATED model.
std::size_t ctmc_tv_ngrid
options.config.ctmc_tv_ngrid: uniform grid size of the rate_sched propagator.
double fau_epsilon
options.config.fau_epsilon: total probability mass the whole grid may discard under "fau".
bool keep_filtration
Keep the per-synchronization EVENT FILTRATION alongside Q.
One entry of options.config.rate_sched: the rate of (station, class) follows the piecewise-linear sch...
std::vector< double > rates
std::vector< double > tgrid
The generator, the state space it is indexed by, and the event rates.
Definition solver_ctmc.h:57
std::vector< NetState< T > > space
row i of Q is space[i]
Definition solver_ctmc.h:59
Matrix< T > Q
(n x n) infinitesimal generator
Definition solver_ctmc.h:58
Everything one CTMC solve produces.
std::string warning
Set when the chain is a reducible mixture solved from an invented seed.
std::vector< std::size_t > cutoff
the per-class cutoff actually used
solvers::CacheMetrics< T > cache
What the chain says about the model's Cache nodes: exact, since the hit and miss shares are read off ...
std::vector< std::size_t > fjclassmap
fjclassmap when the model was fork-join, empty otherwise: the ORIGINAL class of each auxiliary siblin...
std::vector< T > pi
stationary distribution over chain.space
std::vector< T > pi
stationary distribution, length N
std::string warning
Empty unless the chain is an UNSEEDED reducible mixture.
static constexpr double Zero
Definition lang_types.h:762
What fes_aggregate returns.
The per-population tables the conditional sum is taken over.
std::vector< Matrix< T > > QN
Indexed by the 0-based linearized population state; each (M_sub x K).
std::vector< Matrix< T > > UN
Indexed by the 0-based linearized population state; each (M_sub x K).
Everything needed to map an FES result back onto the original model.
Matrix< T > isolatedDemands
(M_sub x K)
std::vector< std::size_t > subsetIndices
1-based, as given
std::vector< std::size_t > complementIndices
1-based
std::vector< bool > isolatedIsDelay
std::vector< int > isolatedServers
std::size_t fesNode
1-based node index of the FES in the new model
std::vector< int > cutoffs
The gate verdict, plus the message the caller reports either way.
Options the estimator reads; only the cutoff matters.
double cutoff
< 0 or non-finite = not given, take the solver default
The metrics getAvg returns, after filtering.
Matrix< T > TN
throughput
Matrix< T > RN
response time, per visit
Matrix< T > UN
utilization
Matrix< T > WN
residence time, per job
std::string method
the method asked for
std::string actualmethod
the algorithm that ran
Matrix< T > QN
queue length
std::vector< T > CN
system response time per class
std::vector< T > XN
system throughput per class
solvers::CacheMetrics< T > cache
What the cache branches observed, EMPTY on a model with no Cache node and on every solver that does n...
Matrix< T > AN
arrival rate
One fork firing synchronization: sn.fjsync{k}.
The augmented struct and everything needed to read its results back.
Definition fj_tag.h:71
std::vector< FjSync< T > > fjsync
Definition fj_tag.h:76
NetworkStruct< T > V
Definition fj_tag.h:72
std::size_t korig
Definition fj_tag.h:78
std::vector< std::size_t > fjclassmap
fjclassmap[a-1] is the ORIGINAL class of auxiliary class a, 0 for originals.
Definition fj_tag.h:74
One network state: the per-stateful-node local rows it is composed of.
Definition state.h:2157
Every Cache node of the model, in node order; empty on a model with none.
Solver-agnostic driver of a model TRANSFORMATION, the sibling of solvers/mva/fj_driver....