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 <functional>
40#include <limits>
41#include <map>
42#include <memory>
43#include <string>
44#include <type_traits>
45#include <vector>
46
53#include "line/lang/qn/fj_tag.h"
58#include "line/lang/qn/state.h"
69#include "line/util/error.h"
70#include "line/util/matrix.h"
72
73namespace line {
74namespace ctmc {
75
76/**
77 * `SolverOptions.m:107`: the per-class state-space cutoff SolverCTMC defaults an
78 * open or mixed model to. It is a SOLVER default, not a fallback computed from
79 * the model, and the reference's `ceil(6000^(1/(M*K)))` is reached only from an
80 * explicitly infinite request. See `resolve_cutoff`.
81 */
82constexpr std::size_t CTMC_DEFAULT_CUTOFF = 10;
83
84/**
85 * One entry of `options.config.rate_sched`: the rate of (station, class)
86 * follows the piecewise-linear schedule (tgrid, rates) over a transient.
87 *
88 * `station` and `cls` are 1-based, as in the MATLAB struct. The multiplier the
89 * generator is scaled by is rate(t) / nominal, where a NaN nominal means the
90 * model's own rate at that (station, class), which is the reference default.
91 * Outside [tgrid.front(), tgrid.back()] the schedule holds its end values.
92 */
94 std::size_t station = 0;
95 std::size_t cls = 0;
96 std::vector<double> tgrid;
97 std::vector<double> rates;
98 double nominal = std::numeric_limits<double>::quiet_NaN();
99};
100
101/**
102 * The SolverCTMC knobs this port honours.
103 *
104 * `cutoff` is per-class when `cutoff_vec` is given and uniform otherwise; a
105 * negative `cutoff` means "not given" and takes the reference's solver default
106 * `CTMC_DEFAULT_CUTOFF`, while an infinite one takes its automatic value,
107 * `ceil(6000^(1/(M*K)))`.
108 */
110 std::string method = "default";
111 /**
112 * Keep the per-synchronization EVENT FILTRATION alongside Q.
113 *
114 * Off by default because it costs one n x n matrix per synchronization,
115 * which on a model with many routing pairs dwarfs the generator itself. The
116 * response-time CDF needs it, since splitting Q on one event cannot be done
117 * after the contributions have been summed.
118 */
119 bool keep_filtration = false;
120 double cutoff = -1.0; ///< < 0 = not given
121 std::vector<std::size_t> cutoff_vec; ///< per-class override, or empty
122 /**
123 * The internal collect sink of the LAL Network embedding (python
124 * `SolverCTMC._lal_collect`). Not an `options.config` key, so it has no
125 * schema row: `line::lal::EmbeddedNetwork` sets it on its own options. When
126 * set, the chain's per-event arcs are collected after the vanishing-row
127 * purge and, with `stop`, the solve returns before the complement.
128 */
129 std::shared_ptr<LalCollect> lal_collect;
130 /**
131 * `options.cutoff` AS A (station x class) MATRIX, or empty.
132 *
133 * The reference accepts a matrix wherever a model needs a different
134 * truncation per station -- oqn_cs_routing writes `[1,1,0;3,3,0;0,0,3]`,
135 * which bounds each queue only in the classes it actually serves. Reducing
136 * that to its per-class maximum enumerates a far larger chain and answers a
137 * different model, so it is carried whole and applied per station in
138 * `space_capacity_c`.
139 */
140 std::vector<std::vector<std::size_t>> cutoff_mat;
141 std::size_t state_max = 3000000; ///< refuse a space larger than this
142 /// `options.force`: downgrade the memory pre-gate's refusal to a warning.
143 bool force = false;
144 /// `options.memorySafetyFraction`: share of available memory a solve may target.
146 /**
147 * `options.config.nonmkvorder`: the phase budget `sn_nonmarkov_toph` spends
148 * on a non-Markovian service law. The reference default is 20, and it is a
149 * real cost here -- every phase multiplies the state space.
150 */
151 std::size_t nonmkv_order = 20;
152 /**
153 * `options.config.nonmkv`: 'bernstein' (default) runs `sn_nonmarkov_toph`,
154 * 'none' skips it; any other name is refused (`api::nonmkv_enabled`).
155 */
156 std::string nonmkv = "bernstein";
157 /**
158 * `options.timestep`: the FIXED OUTPUT STEP of a transient analysis.
159 *
160 * <= 0 means adaptive, which is the reference's default and its `[]`. It
161 * changes WHERE the solution is reported and not how it is computed: the
162 * integrator takes the same steps either way, and the grid points are read
163 * off its interpolant. A caller comparing two transients needs the second,
164 * because two adaptive solves land on different time vectors.
165 */
166 double timestep = -1.0;
167 /**
168 * `options.stiff`, which `SolverOptions` defaults to TRUE and the transient passes to
169 * `ctmc_transient` as `useStiff`, so the reference's 'ode' transient is ode15s. An
170 * immediate transition (rate 1e8) makes the explicit ode23 pair take ~4e7 steps per unit
171 * time, so false is only usable on a chain without one.
172 */
173 bool stiff = true;
174 /**
175 * `options.config.transient_method`: "ode" (the default) integrates the
176 * forward equation, "fau" marches fast adaptive uniformization
177 * (`mc::ctmc_fau`) over the output grid.
178 *
179 * It is a config key rather than a value of `method` because it changes no
180 * stationary answer -- it is the transient path only -- and because the
181 * reference's valid-method list is enumerated by its sanity harness, which
182 * then wants a recorded baseline per method.
183 */
184 std::string transient_method = "ode";
185 /**
186 * `options.config.fau_epsilon`: total probability mass the whole grid may
187 * discard under "fau". It is divided by the number of steps, each step
188 * removing mass and none putting any back, so the accumulated defect stays
189 * below it.
190 */
191 double fau_epsilon = 1e-6;
192 /// `options.config.fau_delta`: occupancy below which a state is dropped.
193 double fau_delta = 1e-12;
194 /// `options.config.fau_ngrid`: output grid size when `timestep` is unset.
195 std::size_t fau_ngrid = 100;
196 /**
197 * `options.config.rate_sched`: the TIME-INHOMOGENEOUS transient. Empty means
198 * the constant-rate generator. Transient path only; the stationary solve
199 * ignores it, as the reference's does.
200 */
201 std::vector<CtmcRateSched> rate_sched;
202 /// `options.config.ctmc_tv_ngrid`: uniform grid size of the rate_sched propagator.
203 std::size_t ctmc_tv_ngrid = 100;
204 /**
205 * `options.config.chain_aggregation`: solve the CHAIN-AGGREGATED model.
206 *
207 * The state space grows with the per-class populations, so collapsing every
208 * chain onto a single class is the standard way to make an otherwise
209 * intractable multiclass model solvable: `api::sn_aggregate_chains` builds
210 * the collapsed model and `mva::sn_deaggregate_chain_results` maps the
211 * chain-level metrics back through alpha. EXACT on a product-form model, an
212 * approximation otherwise, since one aggregate service law replaces the
213 * per-class ones. Off by default: a caller who needs the exact multiclass
214 * answer must pay the state space, not discover the trade after the fact.
215 */
216 bool chain_aggregation = false;
217
218 /**
219 * `options.config.transform='lc'`: solve by LOAD CONCEALMENT.
220 *
221 * Birman-Kogan Algorithm 2 as a model transformation: each chain is solved
222 * on its own against the residual capacity the others leave it, with the
223 * single-chain subproblem a real struct this analyzer solves. Distinct from
224 * the `pfqn_bklc` KERNEL, which sweeps a demand matrix and stays the fast
225 * path; see `tr::transform_solve_lc`.
226 */
227 bool load_concealment = false;
228
229 /** Sweep cap for an iterated transformation; the kernel's own default. */
230 std::size_t transform_iter_max = 1000;
231 /**
232 * `options.config.fes_stations`: 1-BASED station indices to collapse into a
233 * flow-equivalent server before the chain is enumerated. Empty by default.
234 *
235 * The collapsed stations' own metrics are recovered by conditioning on the
236 * FES population, so the table still names every station of the model the
237 * caller built; see `solver_ctmc_fes_aggregation`.
238 */
239 std::vector<std::size_t> fes_stations;
240 /**
241 * `options.config.fes_solver`: how the collapsed subnetwork is solved,
242 * 'mva' (default, product form), or 'ctmc', 'ssa', 'jmt' or 'ldes', which
243 * solve it as built so a non-product-form subsystem enters the FES with its
244 * own rates and conditional queue lengths (Lazowska et al. 1984, 8.5).
245 */
246 std::string fes_solver = "mva";
247 /** `options.seed`, passed to a simulating `fes_solver`. */
248 long seed = 23000;
249};
250
251/**
252 * Everything one CTMC solve produces.
253 *
254 * `chain` is the generator RESTRICTED to the component that was kept, together
255 * with the state space and the per-state arrival and departure rates on it. The
256 * rates are carried rather than recomputed because Q has already summed every
257 * synchronization's contribution into one entry, and a per-class rate cannot be
258 * recovered from that sum afterwards.
259 */
260template <class T>
263 std::vector<T> pi; ///< stationary distribution over chain.space
265 std::vector<std::size_t> cutoff; ///< the per-class cutoff actually used
266 std::string actualmethod = "default";
267 /**
268 * `fjclassmap` when the model was fork-join, empty otherwise: the ORIGINAL
269 * class of each auxiliary sibling class of the AUGMENTED struct that `chain`
270 * and `pi` are indexed by. `avg` is already folded back onto the original
271 * classes, so this is what relates the two index spaces.
272 */
273 std::vector<std::size_t> fjclassmap;
274 /**
275 * The struct the chain was built on, when it differs from the caller's in its
276 * state LAYOUT: set when heterogeneous server pools or a MAP service in pair form were
277 * rewritten (`ctmc_pools`, `ctmc_mapc`), so every reader decoding `chain.space` must
278 * use it. Null otherwise.
279 */
280 std::shared_ptr<const NetworkStruct<T>> solved_sn;
281 /**
282 * What the chain says about the model's Cache nodes: exact, since the hit
283 * and miss shares are read off the stationary law rather than approximated.
284 * Empty on a model with no Cache.
285 */
287 /** Set when the chain is a reducible mixture solved from an invented seed. */
288 std::string warning;
289};
290
291/**
292 * A caller-supplied STATIONARY SOLVER, the optional third argument of
293 * `solver_ctmc_analyzer.m` (`stationaryFcn(InfGen, StateSpace, StateSpaceAggr,
294 * sn)`). It receives the generator exactly as the default path would solve it
295 * (vanishing states eliminated, restricted to the weak component of the initial
296 * state), the state of every row, the per-(station, class) job counts of every
297 * row (`ctmc_state_space_aggr`, column `(ist-1)*K + k`) and the struct the
298 * chain was built on, and returns a stationary vector over those rows. Only the
299 * solve is replaced: the clamp, the renormalization and every metric are the
300 * shared extraction of `solver_ctmc_avg_from_pi`. SolverMAM 'censor'
301 * (`solver_mam_censor.h`) is the caller.
302 */
303template <class T>
304using CtmcStationaryHook = std::function<std::vector<T>(
305 const Matrix<T>& Q, const std::vector<NetState<T>>& space, const Matrix<T>& space_aggr,
306 const NetworkStruct<T>& sn)>;
307
308/**
309 * Port of `SolverCTMC.listValidMethods`.
310 *
311 * `exact` is an explicit ALIAS for the default state-space path: it pins the
312 * intent at the call site so an example or test cannot be re-baselined by a
313 * later change of what `default` selects. It must stay behaviourally identical
314 * to `default` -- nothing below branches on the name -- and that equivalence is
315 * the point of the alias.
316 *
317 * `mdd` never builds the explicit generator, so it is served by
318 * `solver_ctmc_mdd_analyzer` and returns before this file's state-space
319 * machinery is reached; it appears here only because this is the list the gate
320 * below is read against. The perfect sampler `cftp` / `cftp.approx` is a
321 * SolverNC method (`nc/solver_nc_cftp.h`) and is an unknown name here.
322 */
323inline std::vector<std::string> list_valid_methods() {
324 // the names and their order are this solver's row of the method registry (doc/line-methods.json)
325 return ::line::method_registry::methods("CTMC");
326}
327
328/** True for a method whose analyzer is not the explicit-generator one. */
329inline bool is_stateless_method(const std::string& method) {
330 return method == "mdd";
331}
332
333/**
334 * Port of `runAnalyzerChecks`' method gate.
335 *
336 * `mdd` IS refused here, because reaching THIS analyzer with that name means
337 * the caller routed a generator-free method into the generator path: the answer
338 * would be the enumerated one under a reported method that never ran. Its own
339 * entry point does not call this gate.
340 */
341inline void check_method(const std::string& method) {
342 const std::vector<std::string> valid = list_valid_methods();
343 // `unsupportedMethodReason` (SolverCTMC.m): the QRF reduction bounds are SolverBA's now.
344 if (method.compare(0, 3, "qrf") == 0)
345 throw UnsupportedError(ErrorKind{"Method"}, "SolverCTMC: the QRF reduction bounds (method '" +
346 method + "') moved to SolverBA. Use SolverBA with method '" + method +
347 "' (or the 'qr'/'lr' aliases).");
348 if (std::find(valid.begin(), valid.end(), method) == valid.end())
349 throw UnsupportedError(ErrorKind{"Method"}, "SolverCTMC: the '" + method +
350 "' method is unsupported by this solver");
351 if (is_stateless_method(method))
352 throw UnsupportedError(ErrorKind{"Method"}, "SolverCTMC: the '" + method +
353 "' method does not enumerate a state space and is served by its "
354 "own analyzer, not by solver_ctmc_analyzer");
355}
356
357/**
358 * Refuse the constructs this port generates a chain for but does not MODEL.
359 *
360 * WHY A GATE AND NOT A TODO. A construct this port generates a chain for but does
361 * not MODEL comes back as a complete, plausible AvgTable computed from a chain
362 * that is not the model's, and a caller has no way to tell. Where the reference
363 * declares the construct supported, silence here would show two different answers
364 * with no indication which is wrong.
365 *
366 * As of this change the list is empty of structural gaps: fork-join goes through
367 * `fj_tag`, class and joint dependence through `cd_factor`, and BAS through the
368 * blocked marker. What remains are the DECLARATION defects below -- a dependence
369 * handle with no peak -- plus the refusals stated by name elsewhere
370 * (`getSymbolicGenerator`, a matrix-exponential `getProb`, `getCdfRespT` on an
371 * open model, and every region rule but DROP and WAITQ).
372 */
373template <class T>
375 // config.nonmkv='none' leaves a Gamma, Weibull, Det, ... as the refresh built
376 // it, with no phase-type matrices; the generator reads D0/D1 and would index an
377 // empty matrix, so the law is refused by its FeatureSet name instead.
378 for (std::size_t ist = 0; ist < sn.nstations; ++ist)
379 for (std::size_t r = 0; r < sn.nclasses; ++r) {
380 if (ist < sn.disabled.size() && r < sn.disabled[ist].size() && sn.disabled[ist][r])
381 continue;
382 const lang::Distrib<T>& d = sn.service[ist][r];
383 if (d.disabled || d.is_prior() || d.has_map()) continue;
384 if (api::detail::nonmkv_is_markovian(d.type) || api::detail::nonmkv_is_scheduled(d.type))
385 continue;
386 const std::string nm = qn::feature_name(qn::feature_of_process(d.type));
387 throw UnsupportedError(ErrorKind{nm},
388 "SolverCTMC: config.nonmkv='none' leaves the " + nm + " service of class '" +
389 sn.classes[r].name + "' at station '" + sn.stations[ist].name +
390 "' without a phase-type representation, which a CTMC cannot carry; use "
391 "nonmkv='bernstein' or declare a phase-type law");
392 }
393 for (typename std::map<std::size_t, qn::TransitionParam<T>>::const_iterator it =
394 sn.transparam.begin();
395 it != sn.transparam.end(); ++it)
396 for (std::size_t m = 0; m < it->second.firingproc.size(); ++m) {
397 if (api::detail::nonmkv_firing_ready(it->second, m)) continue;
398 const lang::Distrib<T>& d = it->second.firingproc[m];
399 if (d.disabled || d.is_prior()) continue;
400 if (api::detail::nonmkv_is_markovian(d.type) || api::detail::nonmkv_is_scheduled(d.type))
401 continue;
402 const std::string nm = qn::feature_name(qn::feature_of_process(d.type));
403 throw UnsupportedError(ErrorKind{nm},
404 "SolverCTMC: config.nonmkv='none' leaves the " + nm + " firing law of mode " +
405 std::to_string(m + 1) + " of a transition without a phase-type representation, "
406 "which a CTMC cannot carry; use nonmkv='bernstein' or declare a phase-type law");
407 }
408}
409
410template <class T>
412 const std::string impatience = qn::state_impatience_unsupported(sn, "SolverCTMC");
413 if (!impatience.empty()) throw UnsupportedError(ErrorKind{"Impatience"}, impatience);
414 // A BMAP is declared for its ARRIVAL use: a Source emitting batches, which
415 // `batch_arrival_arcs` expands. As a SERVICE it is a bulk server (BMSP),
416 // completing several jobs per firing, which the state machinery does not
417 // represent (python solver_ctmc_state_supports).
418 bool bmap_source = false;
419 for (std::size_t ist = 0; ist < sn.stations.size() && ist < sn.service.size(); ++ist)
420 for (std::size_t r = 0; r < sn.service[ist].size(); ++r) {
421 if (sn.service[ist][r].type != lang::ProcessType::BMAP) continue;
422 if (sn.stations[ist].nodetype == lang::NodeType::Source) {
423 bmap_source = true;
424 continue;
425 }
426 throw UnsupportedError(ErrorKind{"Structure"},
427 "SolverCTMC does not model a BMAP service (a bulk server completing a batch per firing) at " +
428 sn.stations[ist].name + ". Use SolverLDES.");
429 }
430 // Only the lattice generator lands a batch. The WAITQ walk emits one job per
431 // Source epoch, a DROP region censors the space the batch builder lands in
432 // (a batch that overflows the region would vanish rather than lose its
433 // excess jobs one by one), and the reachable walk a fork-join model or a
434 // Petri net forces discovers states one arrival at a time. Refused by name
435 // rather than answered as a model whose batches collapse to one job.
436 // Setup/delay-off and server parallelism are walked by reachability too.
437 bool reach_blocks = false;
438 for (std::size_t ind = 1; bmap_source && ind <= sn.nodes.size() && !reach_blocks; ++ind)
439 reach_blocks = (sn.nodes[ind - 1].station != 0 && sn.setupparam.count(sn.nodes[ind - 1].station)) ||
440 !qn::parallelism_of(sn, ind).empty();
441 if (bmap_source && (!sn.regions.empty() || sn.has_fork() || !sn.fj.empty() || !sn.transparam.empty() ||
442 reach_blocks))
443 throw UnsupportedError(ErrorKind{"BMAP"},
444 "SolverCTMC does not combine BMAP (batch) arrivals with a finite capacity region, fork-join, "
445 "Petri-net transitions, setup/delay-off or server parallelism: those generators admit one "
446 "arriving job per transition. Use SolverLDES.");
447 // Server breakdowns are MODELLED (2026-09-23): `refresh_local_vars` reserves
448 // the trailing status column, `append_local_vars` enumerates it, and
449 // `after_event_station` fires FAILURE and REPAIR against it and suspends or
450 // degrades service while it is down, as `State.afterEventStation` does.
451 // Class dependence requires a DECLARED peak, and unlike the handle itself
452 // the peak cannot be derived: `cd_factor` scales the generator correctly
453 // without it, but the utilization column would then silently fall back to the
454 // busy-server probability, which at a station whose beta emulates extra
455 // servers is not a utilization. `getLimitedClassDependencePeak` makes it
456 // mandatory in the reference, so a missing peak is a model defect.
457 for (std::size_t i = 0; i < sn.stations.size(); ++i) {
458 if (sn.stations[i].cdscaling && sn.stations[i].cdscalingpeak.empty())
459 throw InputError(
460 "SolverCTMC: station '" + sn.stations[i].name +
461 "' declares class-dependent service without a peak rate. Utilization at a "
462 "class-dependent station is reported as T/mu/peak, so pass the peak to "
463 "setClassDependence");
464 if (sn.stations[i].jdscaling && sn.stations[i].jdscalingpeak.empty())
465 throw InputError(
466 "SolverCTMC: station '" + sn.stations[i].name +
467 "' declares joint-dependent service without a peak rate; pass the peak to "
468 "setJointDependence");
469 }
470 // BAS / BBS / RSRD are SOLVED, not refused, and the two tiers are the
471 // reference's, not a shortcut here:
472 //
473 // BAS gets the held-job block, one counter per target code (BUG-110).
474 // `refresh_bas_blocking` sizes it, the generator emits the become-blocked
475 // edge (one more job held for that target), splits each departure into the
476 // 1e7 transfer of a held job and a fresh completion scaled by the free
477 // share of the class in service, and `solver_ctmc_avg_from_pi` moves each
478 // held job to its destination. The chain is exact.
479 //
480 // BBS and RSRD get the DISABLED DEPARTURE only -- `arrival_is_lost` returns
481 // false, so the completion that would move the job is simply not generated
482 // until room frees. `declaresBlockedMarker` tests BAS alone, so the
483 // reference does the same and does not distinguish repetitive service from
484 // a random redraw of the destination. The server freezes with the job in
485 // it, which is the right occupancy but not the right sample path for RSRD.
486 //
487 // `solver_ctmc_waitq` still refuses all three on ITS path: the WAITQ
488 // generator augments the state with a per-region token FIFO and would have to
489 // carry the marker through that augmentation as well.
490}
491
492namespace analyzer_detail {
493
494/**
495 * The tag pool `fj_tag` truncates an open chain's (or a quorum join's)
496 * fork-join section at: the largest finite cutoff, as python passes
497 * `int(max finite options.cutoff)`. An unset cutoff is the solver default
498 * (`CTMC_DEFAULT_CUTOFF`, python's options.cutoff = 10); an infinite one gives
499 * 0, i.e. no truncation, and the open chain is refused.
500 */
501inline std::size_t fj_tag_pool(const CtmcOptions& opt) {
502 std::size_t pool = 0;
503 if (opt.cutoff > 0 && std::isfinite(opt.cutoff)) pool = static_cast<std::size_t>(opt.cutoff);
504 else if (opt.cutoff < 0 && opt.cutoff_vec.empty() && opt.cutoff_mat.empty()) pool = CTMC_DEFAULT_CUTOFF;
505 for (std::size_t k = 0; k < opt.cutoff_vec.size(); ++k) pool = std::max(pool, opt.cutoff_vec[k]);
506 for (std::size_t i = 0; i < opt.cutoff_mat.size(); ++i)
507 for (std::size_t k = 0; k < opt.cutoff_mat[i].size(); ++k) pool = std::max(pool, opt.cutoff_mat[i][k]);
508 return pool;
509}
510
511/**
512 * The per-class cutoff of `@@SolverCTMC/runAnalyzer.m`.
513 *
514 * A closed class never consults it; an open one takes the caller's value.
515 *
516 * THE DEFAULT IS 10, NOT THE 6000-STATE BUDGET. `SolverOptions.m:107` sets
517 * `options.cutoff = 10` for SolverCTMC, so `runAnalyzer`'s
518 * `ceil(6000^(1/(M*K)))` fallback is reached only when the caller explicitly
519 * asks for an INFINITE cutoff, which is the one value the truncation cannot
520 * honour. Taking the fallback as the default instead put this port one lattice
521 * step below the reference on every open model and the answers differed in the
522 * third digit with nothing to show for it: on the Exp(0.5) -> three-FCFS-queue
523 * tandem the budget gives 9 and QLen at Q1 came out 0.9437940 against the
524 * reference's 0.9446411, while cutoff 10 reproduces it to every digit.
525 */
526template <class T>
527std::vector<std::size_t> resolve_cutoff(const NetworkStruct<T>& sn, const CtmcOptions& opt) {
528 const std::size_t M = sn.nstations, K = sn.nclasses;
529 std::vector<std::size_t> cut(K, 0);
530 bool any_open = false;
531 for (std::size_t k = 0; k < K; ++k)
532 if (!std::isfinite(sn.njobs()[k])) any_open = true;
533 if (!any_open) return cut;
534
535 if (!opt.cutoff_mat.empty()) {
536 // `spaceGenerator.m`: the LATTICE height of an open class is the largest
537 // bound any station grants it, `max(capacityc(:,r))`; the per-station
538 // entries then bound each node individually.
539 if (opt.cutoff_mat.size() != M)
540 throw InputError("SolverCTMC: the cutoff matrix must have one row per station");
541 for (std::size_t k = 0; k < K; ++k) {
542 if (std::isfinite(sn.njobs()[k])) continue;
543 for (std::size_t i = 0; i < M; ++i) {
544 if (opt.cutoff_mat[i].size() != K)
545 throw InputError(
546 "SolverCTMC: the cutoff matrix must have one column per class");
547 cut[k] = std::max(cut[k], opt.cutoff_mat[i][k]);
548 }
549 }
550 return cut;
551 }
552 if (!opt.cutoff_vec.empty()) {
553 if (opt.cutoff_vec.size() != K)
554 throw InputError("SolverCTMC: the per-class cutoff must have one entry per class");
555 return opt.cutoff_vec;
556 }
557 std::size_t c;
558 if (opt.cutoff > 0 && std::isfinite(opt.cutoff)) {
559 c = static_cast<std::size_t>(opt.cutoff);
560 } else if (opt.cutoff < 0) {
562 } else {
563 const double e = 1.0 / static_cast<double>(M * K);
564 c = static_cast<std::size_t>(std::ceil(std::pow(6000.0, e)));
565 if (c < 1) c = 1;
566 }
567 for (std::size_t k = 0; k < K; ++k)
568 if (!std::isfinite(sn.njobs()[k])) cut[k] = c;
569 return cut;
570}
571
572/**
573 * Port of the `maxPending` rule of `State.spaceGeneratorNodes`.
574 *
575 * Block B of a delayed-hit cache counts the secondary requests merged onto an
576 * in-flight fetch, and an EXACT solver has to enumerate it, so it needs a
577 * truncation level: the closed population bounds it where there is one, the
578 * state-space cutoff where the model is open. `after_event_cache` reads the same
579 * field and REFUSES a merge past the level rather than landing in a state the
580 * enumeration does not hold -- which is why the two must be set together.
581 *
582 * @return false when no cache carries a retrieval system, leaving `out` untouched
583 */
584template <class T>
585bool set_retrieval_truncation(const NetworkStruct<T>& sn, const std::vector<std::size_t>& cutoff,
586 NetworkStruct<T>& out) {
587 bool any = false;
588 for (typename std::map<std::size_t, qn::CacheParam<T>>::const_iterator ci =
589 sn.nodeparam.begin();
590 ci != sn.nodeparam.end(); ++ci)
591 if (ci->second.retrieval_capacity > 0 && !ci->second.retrieval_classes.empty()) any = true;
592 if (!any) return false;
593 long lvl = 0;
594 if (sn.nclosedjobs() > 0) {
595 lvl = static_cast<long>(sn.nclosedjobs()) - 1;
596 } else {
597 std::size_t mx = 0;
598 for (std::size_t k = 0; k < cutoff.size(); ++k) mx = std::max(mx, cutoff[k]);
599 lvl = static_cast<long>(mx) - 1;
600 }
601 if (lvl < 0) lvl = 0;
602 out = sn;
603 for (typename std::map<std::size_t, qn::CacheParam<T>>::iterator ci = out.nodeparam.begin();
604 ci != out.nodeparam.end(); ++ci)
605 if (ci->second.retrieval_capacity > 0) ci->second.max_pending_retrieval = lvl;
606 return true;
607}
608
609/**
610 * Port of `solver_ctmc.m:47-62`: a G-network SIGNAL NEVER RESIDES at a station,
611 * so its per-class capacity there is zero. A REPLY signal is exempt -- it
612 * completes a synchronous call and queues like an ordinary job.
613 *
614 * WHY THE LATTICE CANNOT DISCOVER THIS ON ITS OWN, and why leaving it undiscovered
615 * is not merely slow. `space_generator` walks every marginal admitted by
616 * `classcap` and, at an FCFS-family station, enumerates the ORDERED buffer of each
617 * one, so an uncapped signal class multiplies the buffer alphabet: a cutoff of c
618 * over two classes gives on the order of 2^c sequences where the model has c+1
619 * states. Every one of them is unreachable -- the arrival handler annihilates the
620 * signal instead of seating it -- so the answer is right and only the cost is
621 * wrong, which is exactly what makes it dangerous: it is invisible in the results.
622 *
623 * IT ALSO REPAIRS THE MEMORY GATE, which is the part that turns this from a
624 * slowdown into a kill. `ctmc_state_space_logsize` already drops signal classes
625 * from its buffered set (ctmc_state_space_logsize.h:176), so without this the gate
626 * sizes the SMALL space and clears a generation of the large one. Measured on the
627 * `test_ctmc_signal_util` G-network at the cutoff of 30 its tests ask for, the
628 * unfixed enumeration was OOM-killed at 43.6 GB resident.
629 *
630 * @return false when the model declares no annihilating signal, leaving `out` untouched
631 */
632template <class T>
633bool annihilate_signal_capacity(const NetworkStruct<T>& sn, NetworkStruct<T>& out) {
634 std::vector<bool> annihilated(sn.nclasses, false);
635 bool any = false;
636 for (std::size_t k = 0; k < sn.nclasses && k < sn.issignal.size(); ++k) {
637 if (!sn.issignal[k]) continue;
638 if (k < sn.signaltype.size() && sn.signaltype[k] == lang::SignalType::REPLY) continue;
639 annihilated[k] = true;
640 any = true;
641 }
642 if (!any) return false;
643 out = sn;
644 for (std::size_t i = 0; i < out.stations.size() && i < out.classcap.size(); ++i) {
645 // The Source is where a signal is BORN, so its capacity there is what the
646 // arrival stream is drawn from and must not be zeroed.
647 if (out.stations[i].sched == SchedStrategy::EXT) continue;
648 for (std::size_t k = 0; k < annihilated.size() && k < out.classcap[i].size(); ++k)
649 if (annihilated[k]) out.classcap[i][k] = 0.0;
650 }
651 return true;
652}
653
654/**
655 * Port of the cache write-back of `solver_ctmc_analyzer.m:333-450`.
656 *
657 * WHAT A CACHE'S HIT AND MISS SHARES ARE, ON A CHAIN. A read leaves the cache in
658 * its configured hit class or its miss class and in no other, so the two
659 * departure rates of those classes at the cache node ARE the hit and the miss
660 * flows, and normalizing by their sum gives the shares. Nothing here reads the
661 * routing matrix, whose cache entries `refresh_routing` resolved to a uniform
662 * split that is not the answer.
663 *
664 * THE DELAYED HIT IS A TRANSITION REWARD, NOT A STATE REWARD, and that is the
665 * whole reason this is not two lines. A merged secondary request departs in the
666 * HIT class, so the hit-class rate above is (true hits + delayed hits) and
667 * something has to split it. A fetch of item i completes on exactly the
668 * transitions that clear block A bit i, and each such transition releases the
669 * block-B count of item i, so the delayed rate is the pi-weighted sum of
670 * (count held) x (rate out on those transitions). The alternative identity
671 * lambda_i * phi_i is only PASTA-exact and would be wrong on a closed model.
672 *
673 * `phi` and `d1` are ordinary state rewards of the same two blocks and give the
674 * per-item DelayedHitQLen columns.
675 *
676 * `latency` is the paper's eq. (latency tot), the mean wait over ALL read requests,
677 *
678 * Z_k = (sum_i phi_{i,k} + sum_i d_{i,k}) / (hit_k + delayed_k + miss_k)
679 *
680 * the requests the retrieval sub-system holds over the TOTAL read rate of class k
681 * at the cache (a hit waits zero), i.e. the hit-class plus miss-class departure
682 * rate, since delayed hits depart in the hit class. The
683 * numerator is the primary request of every in-flight fetch, counted as the network
684 * population of that read class's retrieval classes (block A is indexed by item alone
685 * and cannot be split when two read classes share a cache, whereas the retrieval
686 * classes are per (item, read class) pair), plus the secondary requests merged onto
687 * those fetches. Both terms and the delayed rate are exact rewards of this chain, so
688 * Z_k is exact up to the state space cutoff, which truncates block B and so approaches
689 * the exact value from below.
690 */
691template <class T>
692solvers::CacheMetrics<T> cache_metrics(const NetworkStruct<T>& sn, const CtmcResult<T>& r,
693 const std::vector<T>& pi, const Matrix<T>& QN) {
694 solvers::CacheMetrics<T> out =
695 solvers::cache_metrics_of(sn, std::vector<T>(), std::vector<T>(), std::vector<T>(),
696 std::vector<T>(), Matrix<T>(), Matrix<T>(), std::vector<T>());
697 if (out.caches.empty() || r.space.empty()) return out;
698 const std::size_t K = sn.nclasses, ns = r.space.size();
699 const double dnan = std::numeric_limits<double>::quiet_NaN();
700
701 for (std::size_t c = 0; c < out.caches.size(); ++c) {
702 solvers::CacheNodeMetrics<T>& m = out.caches[c];
703 const std::size_t isf = sn.stateful_index(m.node);
704 if (isf == 0) continue;
705 const qn::CacheParam<T>& cp = sn.nodeparam.find(m.node)->second;
706
707 std::vector<double> tn(K, 0.0);
708 for (std::size_t s = 0; s < ns && s < pi.size(); ++s) {
709 const double p = num_traits<T>::to_double(pi[s]);
710 if (p == 0) continue;
711 if (isf - 1 >= r.dep_rates[s].size()) continue;
712 for (std::size_t k = 0; k < K && k < r.dep_rates[s][isf - 1].size(); ++k)
713 tn[k] += p * num_traits<T>::to_double(r.dep_rates[s][isf - 1][k]);
714 }
715
716 const std::size_t n = cp.nitems;
717 std::size_t tcc = 0;
718 for (std::size_t l = 0; l < cp.itemcap.size(); ++l)
719 if (cp.itemcap[l] > 0) tcc += static_cast<std::size_t>(cp.itemcap[l]);
720 std::vector<std::size_t> rcl, rci, rco;
721 if (cp.retrieval_capacity > 0) qn::cache_retrieval_class_map(cp, rcl, rci, rco);
722 const std::size_t lvw = r.space[0].local[isf - 1].size();
723 const bool retr = !rcl.empty() && lvw >= tcc + n + rcl.size();
724 std::vector<double> drate(K, 0.0), dclass(K, 0.0), inflight(K, 0.0);
725
726 // TIME-STATIONARY per-item occupancy of each list. The contents block of the
727 // local vector holds the item index resident in each cache position, so
728 // P(item i is held by list l) is a state reward of pi. This is the
729 // TIME-WEIGHTED law, the counterpart of the EMBEDDED (per-request) one the
730 // NC/MVA cache algorithms return; the two coincide only under PASTA.
731 // The local row is [per-class counts | contents | block A | block B], so the
732 // contents block sits at the offset the trailing retrieval blocks leave.
733 const std::size_t tail = cp.retrieval_capacity > 0 ? n + rcl.size() : 0;
734 if (n > 0 && tcc > 0 && lvw >= tcc + tail) {
735 const std::size_t coff = lvw - (tcc + tail);
736 const std::size_t h = cp.itemcap.size();
737 Matrix<T> ip(n, h + 1);
738 std::vector<double> acc(n * h, 0.0);
739 std::vector<char> present(n, 0);
740 for (std::size_t s = 0; s < ns && s < pi.size(); ++s) {
741 const double p = num_traits<T>::to_double(pi[s]);
742 if (p == 0) continue;
743 const std::vector<T>& lv = r.space[s].local[isf - 1];
744 std::size_t off = coff;
745 for (std::size_t l = 0; l < h; ++l) {
746 const std::size_t cap =
747 cp.itemcap[l] > 0 ? static_cast<std::size_t>(cp.itemcap[l]) : 0;
748 std::fill(present.begin(), present.end(), 0);
749 for (std::size_t q = 0; q < cap; ++q) {
750 const long it = static_cast<long>(num_traits<T>::to_double(lv[off + q]));
751 if (it >= 1 && static_cast<std::size_t>(it) <= n)
752 present[static_cast<std::size_t>(it) - 1] = 1;
753 }
754 for (std::size_t i = 0; i < n; ++i)
755 if (present[i]) acc[i * h + l] += p;
756 off += cap;
757 }
758 }
759 for (std::size_t i = 0; i < n; ++i) {
760 double miss = 1.0;
761 for (std::size_t l = 0; l < h; ++l) {
762 const double v = acc[i * h + l];
763 ip(i, l + 1) = num_traits<T>::from_double(v);
764 miss -= v;
765 }
766 ip(i, 0) = num_traits<T>::from_double(miss);
767 }
768 m.itemprob = ip;
769 }
770
771 if (retr) {
772 const std::size_t aoff = lvw - (n + rcl.size()), boff = aoff + n;
773 std::vector<double> phi(n, 0.0), d1(n, 0.0);
774 for (std::size_t s = 0; s < ns && s < pi.size(); ++s) {
775 const double p = num_traits<T>::to_double(pi[s]);
776 if (p == 0) continue;
777 const std::vector<T>& lv = r.space[s].local[isf - 1];
778 for (std::size_t i = 0; i < n; ++i)
779 if (num_traits<T>::to_double(lv[aoff + i]) != 0) phi[i] += p;
780 for (std::size_t j = 0; j < rcl.size(); ++j)
781 d1[rci[j] - 1] += p * num_traits<T>::to_double(lv[boff + j]);
782 }
783 m.delayedhitqlen.assign(n, num_traits<T>::from_int(0));
784 m.delayedhitqlenfull.assign(n, num_traits<T>::from_int(0));
785 for (std::size_t i = 0; i < n; ++i) {
786 m.delayedhitqlen[i] = num_traits<T>::from_double(d1[i]);
787 m.delayedhitqlenfull[i] = num_traits<T>::from_double(d1[i] + phi[i]);
788 }
789 for (std::size_t s = 0; s < ns && s < pi.size(); ++s) {
790 const double p = num_traits<T>::to_double(pi[s]);
791 if (p == 0) continue;
792 const std::vector<T>& lv = r.space[s].local[isf - 1];
793 for (std::size_t j = 0; j < rcl.size(); ++j) {
794 const std::size_t i = rci[j] - 1;
795 const double held = num_traits<T>::to_double(lv[boff + j]);
796 if (held <= 0 || num_traits<T>::to_double(lv[aoff + i]) == 0) continue;
797 double completes = 0.0;
798 for (std::size_t b = 0; b < ns; ++b) {
799 if (b == s) continue;
800 const double q = num_traits<T>::to_double(r.Q(s, b));
801 if (q == 0) continue;
802 if (num_traits<T>::to_double(r.space[b].local[isf - 1][aoff + i]) == 0)
803 completes += q;
804 }
805 if (rco[j] - 1 < K) drate[rco[j] - 1] += p * held * completes;
806 }
807 }
808 // The two populations the retrieval sub-system holds, split by the
809 // originating (reading) class, for the expected latency below.
810 for (std::size_t s = 0; s < ns && s < pi.size(); ++s) {
811 const double p = num_traits<T>::to_double(pi[s]);
812 if (p == 0) continue;
813 const std::vector<T>& lv = r.space[s].local[isf - 1];
814 for (std::size_t j = 0; j < rcl.size(); ++j)
815 if (rco[j] - 1 < K)
816 dclass[rco[j] - 1] += p * num_traits<T>::to_double(lv[boff + j]);
817 }
818 for (std::size_t k = 0; k < K; ++k)
819 for (std::size_t i = 0; i < cp.retrieval_classes.size(); ++i) {
820 if (k >= cp.retrieval_classes[i].size()) continue;
821 const std::size_t rc = cp.retrieval_classes[i][k];
822 if (rc == 0 || rc > static_cast<std::size_t>(QN.cols())) continue;
823 for (std::size_t st = 0; st < static_cast<std::size_t>(QN.rows()); ++st)
824 inflight[k] += num_traits<T>::to_double(QN(st, rc - 1));
825 }
826 }
827
828 m.hitprob.assign(K, num_traits<T>::from_double(dnan));
829 m.missprob.assign(K, num_traits<T>::from_double(dnan));
830 if (retr) m.delayedprob.assign(K, num_traits<T>::from_double(dnan));
831 for (std::size_t k = 0; k < K; ++k) {
832 if (k >= cp.hitclass.size() || k >= cp.missclass.size()) continue;
833 const std::size_t h = cp.hitclass[k], mi = cp.missclass[k];
834 if (h == 0 || mi == 0 || h > K || mi > K) continue;
835 const double denom = tn[h - 1] + tn[mi - 1];
836 if (denom <= 0) continue;
837 // Capped at the hit-class flow: the two are the same measurement of
838 // the same transitions, and a floating-point excess would report a
839 // negative true-hit share rather than a zero one.
840 const double d = retr ? std::min(drate[k], tn[h - 1]) : 0.0;
841 m.hitprob[k] = num_traits<T>::from_double((tn[h - 1] - d) / denom);
842 m.missprob[k] = num_traits<T>::from_double(tn[mi - 1] / denom);
843 if (retr) m.delayedprob[k] = num_traits<T>::from_double(d / denom);
844 if (retr && cp.retrieval_queues.find(k) != cp.retrieval_queues.end() &&
845 !cp.retrieval_queues.find(k)->second.empty()) {
846 if (m.latency.empty()) m.latency.assign(K, num_traits<T>::from_double(dnan));
847 // all reads of class k: the hit class carries the true and the delayed hits
848 m.latency[k] = num_traits<T>::from_double((inflight[k] + dclass[k]) / denom);
849 }
850 }
851 }
852 return out;
853}
854
855/**
856 * `cache_delayed_hit_rate`: the exact delayed-hit rate of a retrieval-aware cache, per
857 * originating class, as a TRANSITION reward over the solved chain `r` weighted by `pi`.
858 *
859 * A fetch of item i completes on exactly the transitions that clear block A bit i, and
860 * each releases the block-B counts of item i as delayed hits. `ind` is the 1-based
861 * node index of the cache. All zeros when the cache has no retrieval sub-system.
862 * The same reward `cache_metrics` takes above, exposed for the environment blend,
863 * which solves the same generators one stage at a time.
864 */
865template <class T>
866std::vector<double> cache_delayed_hit_rate(const NetworkStruct<T>& sn, std::size_t ind,
867 const CtmcResult<T>& r, const std::vector<T>& pi) {
868 const std::size_t K = sn.nclasses;
869 std::vector<double> drate(K, 0.0);
870 const std::size_t isf = sn.stateful_index(ind);
871 if (isf == 0 || r.space.empty()) return drate;
872 const auto it = sn.nodeparam.find(ind);
873 if (it == sn.nodeparam.end() || sn.nodes[ind - 1].nodetype != lang::NodeType::Cache)
874 return drate;
875 const qn::CacheParam<T>& cp = it->second;
876 if (!(cp.retrieval_capacity > 0)) return drate;
877 std::vector<std::size_t> rcl, rci, rco;
878 qn::cache_retrieval_class_map(cp, rcl, rci, rco);
879 if (rcl.empty()) return drate;
880 const std::size_t n = cp.nitems, ns = r.space.size();
881 std::size_t tcc = 0;
882 for (std::size_t l = 0; l < cp.itemcap.size(); ++l)
883 if (cp.itemcap[l] > 0) tcc += static_cast<std::size_t>(cp.itemcap[l]);
884 const std::size_t lvw = r.space[0].local[isf - 1].size();
885 if (lvw < tcc + n + rcl.size()) return drate;
886 const std::size_t aoff = lvw - (n + rcl.size()), boff = aoff + n;
887 for (std::size_t s = 0; s < ns && s < pi.size(); ++s) {
888 const double p = num_traits<T>::to_double(pi[s]);
889 if (p == 0) continue;
890 const std::vector<T>& lv = r.space[s].local[isf - 1];
891 for (std::size_t j = 0; j < rcl.size(); ++j) {
892 const std::size_t i = rci[j] - 1;
893 const double held = num_traits<T>::to_double(lv[boff + j]);
894 if (held <= 0 || num_traits<T>::to_double(lv[aoff + i]) == 0) continue;
895 double completes = 0.0;
896 for (std::size_t b = 0; b < ns; ++b) {
897 if (b == s) continue;
898 const double q = num_traits<T>::to_double(r.Q(s, b));
899 if (q == 0) continue;
900 if (num_traits<T>::to_double(r.space[b].local[isf - 1][aoff + i]) == 0)
901 completes += q;
902 }
903 if (rco[j] - 1 < K) drate[rco[j] - 1] += p * held * completes;
904 }
905 }
906 return drate;
907}
908
909/**
910 * Strip the reference's leading infinite-population column from a DECLARED
911 * Source row, so a state written by MATLAB, the JAR or native python names a
912 * row this port's enumerated space actually holds.
913 *
914 * The reference writes a Source as `[Inf | one phase block per class]` --
915 * `[Inf 1 0 0 0 0 0]` for a Source generating the first of six classes -- and
916 * this port's `from_marginal_core`, which the state-space walk runs, writes the
917 * phase blocks alone. The two therefore differ by exactly one column, and an
918 * untranslated row is one wider than every row of the space, so no lookup can
919 * match it and the padding rule cannot help: it left-pads a NARROW candidate
920 * and refuses a wide one. `rewardModel_mm1k` came back from its M2C row as
921 * `solver_ctmc_transient_analyzer: the initial state is not contained in the
922 * state space` while the JAR and native-python rows, each reading its own
923 * encoding, passed.
924 *
925 * The phase block is KEPT rather than rebuilt: a Source with a MAP arrival has
926 * several rows in its local space and which one the model declared is the
927 * caller's statement, not a detail to regenerate.
928 */
929template <class T>
930void strip_reference_source_column(const NetworkStruct<T>& sn, std::size_t ind,
931 std::vector<T>& row) {
932 const std::size_t ist = sn.nodes[ind - 1].station;
933 if (ist == 0 || ist > sn.stations.size()) return;
934 if (sn.stations[ist - 1].nodetype != NodeType::Source &&
935 sn.stations[ist - 1].sched != SchedStrategy::EXT)
936 return;
937 std::size_t w = 0;
938 for (std::size_t r = 0; r < sn.nclasses; ++r) w += sn.phasessz_of(ist, r + 1);
939 // Width is the discriminator rather than the leading value: an exact
940 // arithmetic has no infinity, so the reference's marker arrives as the
941 // MaxInt clamp `to_marginal` uses and cannot be tested for.
942 if (row.size() == w + 1) row.erase(row.begin());
943}
944
945/**
946 * The model's default initial state: every closed class's jobs at its reference
947 * station, everything else empty, which is `Network.initDefault`.
948 *
949 * The first row `from_marginal_node` emits for that marginal is taken. It is
950 * used for two things -- seeding the reachable walk, and choosing a connected
951 * component -- and for both any row with the right marginal serves, since rows
952 * sharing a marginal are mutually reachable by construction.
953 *
954 * @return false when some node admits no state at all for that marginal
955 */
956template <class T>
957bool default_init_state(const NetworkStruct<T>& sn, NetState<T>& init) {
958 const std::size_t R = sn.nclasses;
959 const std::vector<std::size_t>& sfn = sn.stateful_nodes;
960 init.local.assign(sfn.size(), std::vector<T>());
961 for (std::size_t f = 0; f < sfn.size(); ++f) {
962 const std::size_t ind = sfn[f];
963 // A DECLARED STATE WINS OVER THE DEFAULT MARKING, which is the whole
964 // point of declaring one: `setState` is used precisely to move the jobs
965 // off their reference stations, and rebuilding the default here would
966 // answer `getProbSysAggr` for a state the caller did not name. The pair
967 // (statespace, stateprior) is what the writers emit and the reader
968 // stores; the FIRST row is the state when the prior is the trivial one,
969 // and a genuine distribution over several rows is not a single initial
970 // state at all, so only the one-row case is taken.
971 const typename std::map<std::size_t, Matrix<T>>::const_iterator sp =
972 sn.statespace.find(ind);
973 if (sp != sn.statespace.end() && sp->second.rows() == 1 && sp->second.cols() > 0) {
974 std::vector<T> row(sp->second.cols());
975 for (std::size_t c = 0; c < sp->second.cols(); ++c) row[c] = sp->second(0, c);
976 strip_reference_source_column(sn, ind, row);
977 // A ROW OF EXACTLY ONE ENTRY PER CLASS IS A MARGINAL, NOT AN
978 // ENCODED ROW, and the two differ wherever a class is DISABLED at
979 // the station. The reference keeps a column for every class
980 // (`sn.phases` is 1 at a class it does not serve), while this port
981 // drops the block outright (`phases_of` is 0), so a Delay serving
982 // one of three classes has a width-3 row there and a width-1 row
983 // here, LEFT-PADDED to the encoding width. Installing the
984 // reference's row verbatim then puts the jobs in another class's
985 // block: on tut06_cache_lru_zipf the single client job landed where
986 // nothing could serve it and the sample path deadlocked at once,
987 // which is what a state nobody can leave looks like. Rebuilding it
988 // through `from_marginal_node_first` is the same construction the
989 // default branch below uses, so the two agree by construction.
990 std::vector<std::size_t> marg(R, 0), mph(R, 1);
991 const std::size_t mist = sn.nodes[ind - 1].station;
992 bool rebuilt = false;
993 if (row.size() == R && mist != 0) {
994 for (std::size_t r = 0; r < R; ++r) {
995 const double v = num_traits<T>::to_double(row[r]);
996 marg[r] = v > 0.0 ? static_cast<std::size_t>(v + 0.5) : 0;
997 mph[r] = sn.phasessz_of(mist, r + 1);
998 }
999 std::vector<T> built;
1000 if (from_marginal_node_first(sn, ind, marg, mph, built) && !built.empty()) {
1001 init.local[f] = built;
1002 rebuilt = true;
1003 }
1004 }
1005 if (!rebuilt) init.local[f] = row;
1006 continue;
1007 }
1008 const std::size_t ist = sn.nodes[ind - 1].station;
1009 std::vector<std::size_t> nmarg(R, 0), ph(R, 1);
1010 if (ist != 0) {
1011 for (std::size_t r = 0; r < R; ++r) ph[r] = sn.phasessz_of(ist, r + 1);
1012 if (sn.stations[ist - 1].nodetype == NodeType::Source) {
1013 // The infinite reservoir: one job per class in service, and only
1014 // for the classes the Source generates -- the same guard
1015 // `space_generator` needs. Without it this returns false on any
1016 // model with a downstream-only class, the initial state is
1017 // reported as absent, and the reducible-component selection
1018 // silently falls back to "largest component": a plausible answer
1019 // for the wrong chain.
1020 for (std::size_t r = 0; r < R; ++r)
1021 if (!sn.disabled[ist - 1][r]) nmarg[r] = 1;
1022 } else {
1023 for (std::size_t r = 0; r < R; ++r) {
1024 const double nj = sn.njobs()[r];
1025 if (std::isfinite(nj) && sn.classes[r].refstat == ist)
1026 nmarg[r] = static_cast<std::size_t>(nj);
1027 }
1028 // A PLACE'S DECLARED MARKING IS THE INITIAL STATE, and it is not
1029 // derivable from a class population: an OPEN class has none, so
1030 // every Place of an open SPN started empty however many tokens
1031 // the model put there. On `spn_open_sevenplaces` that dropped
1032 // P1's two tokens and P5's one; T4 needs a P5 token to fire, so
1033 // the marking never moved past P3 and the chain reported Tput 0
1034 // with P3 pinned at the cutoff. `state_initial_occupancy` is the
1035 // same accessor `space_capacity_c` sizes the lattice with, so the
1036 // two agree on what the model declared.
1037 // A DECLARED marking REPLACES the population a closed class puts at its
1038 // reference Place, as `Place.setState` overrides `initDefault` in the
1039 // reference and as `solver_ssa_nrm_spn` reads it. Taking the larger of the
1040 // two put all N tokens of a net that spreads them over its places at the
1041 // reference Place AS WELL, so the walk explored a different net.
1042 const bool declared = sn.initmarking.find(ind) != sn.initmarking.end();
1043 for (std::size_t r = 0; r < R; ++r) {
1044 const std::size_t m0 = qn::state_initial_occupancy(sn, ind, r);
1045 if (declared || m0 > nmarg[r]) nmarg[r] = m0;
1046 }
1047 }
1048 }
1049 if (!from_marginal_node_first(sn, ind, nmarg, ph, init.local[f])) return false;
1050 }
1051 return true;
1052}
1053
1054/** The index in `space` of the default initial state, or npos. */
1055template <class T>
1056std::size_t init_state_index(const NetworkStruct<T>& sn, const std::vector<NetState<T>>& space) {
1057 const std::size_t npos = static_cast<std::size_t>(-1);
1058 if (space.empty()) return npos;
1059 NetState<T> init;
1060 if (!default_init_state(sn, init)) return npos;
1061 for (std::size_t f = 0; f < init.local.size(); ++f) {
1062 // Every state of a node carries the node's widest row, left-padded with
1063 // zeros; a candidate built at the natural width would never match.
1064 const std::size_t w = space[0].local[f].size();
1065 if (init.local[f].size() > w) return npos;
1066 if (init.local[f].size() < w)
1067 init.local[f].insert(init.local[f].begin(), w - init.local[f].size(),
1068 num_traits<T>::from_int(0));
1069 }
1070 const std::vector<double> key = ctmc_detail::state_key(init);
1071 for (std::size_t s = 0; s < space.size(); ++s)
1072 if (ctmc_detail::state_key(space[s]) == key) return s;
1073 return npos;
1074}
1075
1076/**
1077 * The initial DISTRIBUTION over `space`: the product of the declared per-node
1078 * priors, or a point mass on the default initial state where none is declared.
1079 *
1080 * Port of the initial-state loop of `@@SolverCTMC/runAnalyzer.m`, which walks
1081 * the cartesian product of the per-node state spaces, weights each combination
1082 * by the product of its per-node priors, integrates the forward equation once
1083 * per combination and SUMS the trajectories with those weights. Every quantity
1084 * the transient analyzer reports is linear in pi(t), and pi(t) is linear in
1085 * pi(0), so seeding the mixture and integrating ONCE gives the same answer at a
1086 * fraction of the cost -- and on ONE time grid, where the reference has to
1087 * interpolate its separate adaptive grids onto their union to add them.
1088 *
1089 * A combination the enumerated space does not contain is an error rather than a
1090 * dropped term: it means the declared space and the reachable one disagree, and
1091 * renormalizing over what is left would answer for a different prior.
1092 *
1093 * @return false when a node admits no state at all, as `default_init_state` does
1094 */
1095template <class T>
1096bool init_state_distribution(const NetworkStruct<T>& sn, const std::vector<NetState<T>>& space,
1097 std::vector<T>& pi0) {
1098 const std::size_t npos = static_cast<std::size_t>(-1);
1099 pi0.assign(space.size(), num_traits<T>::from_int(0));
1100 if (space.empty()) return false;
1101 NetState<T> base;
1102 if (!default_init_state(sn, base)) return false;
1103 const std::vector<std::size_t>& sfn = sn.stateful_nodes;
1104
1105 // Per stateful node: the rows it may start in and their probabilities. A
1106 // node with no declared prior contributes its default row alone.
1107 std::vector<std::vector<std::vector<T>>> rows(sfn.size());
1108 std::vector<std::vector<double>> wts(sfn.size());
1109 for (std::size_t f = 0; f < sfn.size(); ++f) {
1110 const typename std::map<std::size_t, Matrix<T>>::const_iterator ss =
1111 sn.statespace.find(sfn[f]);
1112 const typename std::map<std::size_t, std::vector<T>>::const_iterator sp =
1113 sn.stateprior.find(sfn[f]);
1114 if (ss == sn.statespace.end() || sp == sn.stateprior.end() || ss->second.rows() == 0 ||
1115 ss->second.rows() != sp->second.size()) {
1116 rows[f].push_back(base.local[f]);
1117 wts[f].push_back(1.0);
1118 continue;
1119 }
1120 for (std::size_t r = 0; r < ss->second.rows(); ++r) {
1121 const double w = num_traits<T>::to_double(sp->second[r]);
1122 if (!(w > 0.0)) continue; // a zero-probability row is not a state to visit
1123 std::vector<T> row(ss->second.cols());
1124 for (std::size_t c = 0; c < ss->second.cols(); ++c) row[c] = ss->second(r, c);
1125 strip_reference_source_column(sn, sfn[f], row);
1126 rows[f].push_back(row);
1127 wts[f].push_back(w);
1128 }
1129 if (rows[f].empty()) return false;
1130 }
1131
1132 std::vector<std::size_t> pick(sfn.size(), 0);
1133 double total = 0.0;
1134 for (;;) {
1135 NetState<T> cand = base;
1136 double w = 1.0;
1137 for (std::size_t f = 0; f < sfn.size(); ++f) {
1138 cand.local[f] = rows[f][pick[f]];
1139 w *= wts[f][pick[f]];
1140 // Every state of a node carries the node's widest row, left-padded
1141 // with zeros; a candidate at the natural width would never match.
1142 const std::size_t wd = space[0].local[f].size();
1143 if (cand.local[f].size() > wd) return false;
1144 if (cand.local[f].size() < wd)
1145 cand.local[f].insert(cand.local[f].begin(), wd - cand.local[f].size(),
1146 num_traits<T>::from_int(0));
1147 }
1148 std::size_t idx = npos;
1149 const std::vector<double> key = ctmc_detail::state_key(cand);
1150 for (std::size_t s = 0; s < space.size() && idx == npos; ++s)
1151 if (ctmc_detail::state_key(space[s]) == key) idx = s;
1152 if (idx == npos) return false;
1153 pi0[idx] = T(pi0[idx] + num_traits<T>::from_double(w));
1154 total += w;
1155
1156 std::size_t f = 0;
1157 for (; f < sfn.size(); ++f) {
1158 if (++pick[f] < rows[f].size()) break;
1159 pick[f] = 0;
1160 }
1161 if (f == sfn.size()) break;
1162 }
1163 if (!(total > 0.0)) return false;
1164 // The declared priors are per node and need not multiply to one; the
1165 // reference sums the weighted trajectories without renormalizing, so a
1166 // prior that already sums to one is unchanged and one that does not is
1167 // reported as the reference reports it.
1168 return true;
1169}
1170
1171/** Weakly connected components of the generator, as a per-state label. */
1172template <class T>
1173std::vector<std::size_t> weak_components(const Matrix<T>& Q, std::size_t& ncomp) {
1174 const std::size_t n = Q.rows();
1175 const std::size_t npos = static_cast<std::size_t>(-1);
1176 std::vector<std::size_t> comp(n, npos);
1177 ncomp = 0;
1178 for (std::size_t s = 0; s < n; ++s) {
1179 if (comp[s] != npos) continue;
1180 std::vector<std::size_t> stack{s};
1181 comp[s] = ncomp;
1182 while (!stack.empty()) {
1183 const std::size_t u = stack.back();
1184 stack.pop_back();
1185 for (std::size_t v = 0; v < n; ++v) {
1186 if (comp[v] != npos) continue;
1187 // The DIAGONAL is minus the row sum and is nonzero at almost
1188 // every state, so it must not be read as an edge to itself.
1189 if (v == u) continue;
1190 if (num_traits<T>::to_double(Q(u, v)) != 0 ||
1191 num_traits<T>::to_double(Q(v, u)) != 0) {
1192 comp[v] = comp[u];
1193 stack.push_back(v);
1194 }
1195 }
1196 }
1197 ++ncomp;
1198 }
1199 return comp;
1200}
1201
1202/** Restrict a CtmcResult to a subset of its states, keeping their order. */
1203template <class T>
1204CtmcResult<T> restrict_to(const CtmcResult<T>& r, const std::vector<std::size_t>& wset) {
1205 CtmcResult<T> out;
1206 out.Q = Matrix<T>(wset.size(), wset.size(), num_traits<T>::from_int(0));
1207 for (std::size_t a = 0; a < wset.size(); ++a)
1208 for (std::size_t b = 0; b < wset.size(); ++b) out.Q(a, b) = r.Q(wset[a], wset[b]);
1209 out.space.reserve(wset.size());
1210 out.arv_rates.reserve(wset.size());
1211 out.dep_rates.reserve(wset.size());
1212 for (std::size_t a = 0; a < wset.size(); ++a) {
1213 out.space.push_back(r.space[wset[a]]);
1214 out.arv_rates.push_back(r.arv_rates[wset[a]]);
1215 out.dep_rates.push_back(r.dep_rates[wset[a]]);
1216 }
1217 // The filtration is indexed by the SAME rows as Q, so it has to be
1218 // restricted with it or every CDF built from it would index the wrong
1219 // states. Its diagonal is NOT rebuilt: a filtration entry is a rate the
1220 // event contributed, not a generator, and it has no diagonal to speak of.
1221 out.filt.reserve(r.filt.size());
1222 for (std::size_t f = 0; f < r.filt.size(); ++f) {
1223 Matrix<T> F(wset.size(), wset.size(), num_traits<T>::from_int(0));
1224 for (std::size_t a = 0; a < wset.size(); ++a)
1225 for (std::size_t b = 0; b < wset.size(); ++b) F(a, b) = r.filt[f](wset[a], wset[b]);
1226 out.filt.push_back(F);
1227 }
1228 // The submatrix of a generator is not a generator: the rates that left the
1229 // component have to come off the diagonal, or the rows no longer sum to zero
1230 // and the stationary solve is of a matrix that is not a chain.
1231 make_infgen(out.Q);
1232 return out;
1233}
1234
1235} // namespace analyzer_detail
1236
1237/**
1238 * Build the chain of ONE struct, solve it, reduce it.
1239 *
1240 * The state space is the FULL encoding space, as the reference's
1241 * `options.config.state_space_gen` default of 'default' asks for, so the
1242 * reducible handling below is on the normal path and not an edge case. Two
1243 * exceptions force the reachable walk instead: a global synchronization (an SPN)
1244 * and a fork firing list.
1245 *
1246 * Split out of `solver_ctmc_analyzer` so that the fork-join wrapper can run it on
1247 * the AUGMENTED struct without the gates firing twice.
1248 */
1249template <class T>
1251 const std::vector<qn::FjSync<T>>& fjsync,
1252 const CtmcStationaryHook<T>& stationary = CtmcStationaryHook<T>()) {
1253 CtmcSolution<T> out;
1254 // Heterogeneous server pools are rewritten into exact per-pool phase blocks
1255 // (`solver_ctmc_pools`); everything below enumerates and solves the rewritten copy.
1256 NetworkStruct<T> sn_pool;
1257 const bool pooled = ctmc_pools(sn_arg, sn_pool);
1258 const NetworkStruct<T>& sn_pl = pooled ? sn_pool : sn_arg;
1259 // A MAP service at an FCFS station runs in pair form, the carried-phase law of JMT and
1260 // LDES (`solver_ctmc_mapc`); it widens the server block, so readers need the copy too.
1261 NetworkStruct<T> sn_mapc;
1262 const bool mapc = ctmc_mapc(sn_pl, sn_mapc);
1263 const NetworkStruct<T>& sn_mp = mapc ? sn_mapc : sn_pl;
1264 // Setup/delay-off and finite-attempt stations carry a block of their own at
1265 // the end of the station row, and setup or server parallelism lets jobs wait
1266 // next to idle servers, which only the reachable walk enumerates
1267 // (qn::ctmc_station_blocks, python `_ctmc_sync_space`).
1268 NetworkStruct<T> sn_blk;
1269 bool blk_reach = false;
1270 const bool blk = qn::ctmc_station_blocks(sn_mp, sn_blk, blk_reach);
1271 const NetworkStruct<T>& sn_in = blk ? sn_blk : sn_mp;
1272 if (pooled || mapc || blk) out.solved_sn = std::make_shared<const NetworkStruct<T>>(sn_in);
1273 out.cutoff = analyzer_detail::resolve_cutoff(sn_in, opt);
1274 // A delayed-hit cache is enumerated under a declared merge truncation, and
1275 // the events are held to the same one; every other model walks `sn_in`.
1276 NetworkStruct<T> sn_trunc;
1277 const bool retr = analyzer_detail::set_retrieval_truncation(sn_in, out.cutoff, sn_trunc);
1278 const NetworkStruct<T>& sn_r = retr ? sn_trunc : sn_in;
1279 // A signal class holds no place in a station's buffer, and saying so BEFORE
1280 // the memory gate is what keeps the gate's estimate and the generator's
1281 // enumeration measuring the same space; see `annihilate_signal_capacity`.
1282 NetworkStruct<T> sn_sig;
1283 const bool sig = analyzer_detail::annihilate_signal_capacity(sn_r, sn_sig);
1284 const NetworkStruct<T>& sn = sig ? sn_sig : sn_r;
1285
1286 // THE MEMORY PRE-GATE, `@SolverCTMC/runAnalyzer.m:150-164`. It runs BEFORE
1287 // any generation because `state_max` is enforced inside the generator loop,
1288 // so on its own it enumerates up to three million states before refusing --
1289 // and three million is a fixed count that knows nothing about how much
1290 // memory this host actually has. `mdd` never reaches here;
1291 // see the exemption note in ctmc_memory_gate.h, which is load-bearing.
1292 {
1293 mc::CtmcSizeOptions szopt;
1294 szopt.cutoff = opt.cutoff;
1295 const double log_nstates = mc::ctmc_state_space_logsize(sn, szopt);
1296 const mc::CtmcGateResult gate =
1297 mc::ctmc_memory_gate(log_nstates, opt.force, opt.memory_safety_fraction);
1298 if (!gate.ok) throw UnsupportedError(ErrorKind{"StateSpace"}, gate.message + " Stopping SolverCTMC.");
1299 }
1300
1301 const std::vector<Sync<T>> sync = refresh_sync(sn);
1302 const std::vector<qn::GlobalSync<T>> gsync = refresh_global_sync(sn);
1303
1304 // AN SPN NEEDS THE REACHABLE WALK, not the lattice enumeration. A firing
1305 // does not conserve the per-chain population, and a Transition's state is
1306 // per-MODE, so no population marginal produces the states in which a mode is
1307 // firing: `from_marginal_node` emits only the all-idle row. Enumerating the
1308 // lattice therefore yields a space every ENABLE lands outside of, and the
1309 // generator comes out empty. The reference forces
1310 // `options.config.state_space_gen = 'reachable'` for exactly this class of
1311 // model; the condition here is the presence of a global synchronization,
1312 // which is the same set.
1313 // A FORK FIRING LIST forces the same choice as an SPN, for the same reason:
1314 // the lattice enumeration walks the per-chain population, and a firing does
1315 // not conserve it -- one parent becomes B siblings in classes the lattice
1316 // gives population 0. The reference sets
1317 // `options.config.state_space_gen = 'reachable'` on every fork-join model.
1318 std::vector<NetState<T>> space;
1319 if (!gsync.empty() || !fjsync.empty() || blk_reach) {
1320 NetState<T> init;
1321 if (!analyzer_detail::default_init_state(sn, init))
1322 throw UnsupportedError(ErrorKind{"Model"},
1323 "SolverCTMC: the model's initial marking admits no state; check the Place "
1324 "populations against the class reference stations");
1325 // THE CUTOFF TRAVELS WITH THE WALK, or an open model never terminates:
1326 // the Source keeps producing and the walk runs to `state_max` instead of
1327 // answering. It is the same bound the lattice arm below applies.
1328 space = reachable_space_generator(sn, init, sync, gsync, opt.state_max, fjsync,
1329 out.cutoff, opt.cutoff_mat);
1330 } else {
1331 space = space_generator(sn, out.cutoff, opt.state_max, opt.cutoff_mat);
1332 }
1333 if (space.empty())
1334 throw UnsupportedError(ErrorKind{"Model"},
1335 "SolverCTMC: the state space is empty; no state satisfies the model's capacities");
1336 // A DROP region censors the chain: the states it forbids are simply never
1337 // occupied, so removing them and letting `make_infgen` re-close the rows IS
1338 // the censored chain. WAITQ and the blocking rules augment the state
1339 // instead and are refused by name inside.
1340 space = ctmc_filter_regions(sn, space);
1341 CtmcResult<T> r = solver_ctmc(sn, space, sync, gsync, opt.keep_filtration, fjsync,
1342 std::is_same<T, double>::value ? opt.lal_collect.get() : nullptr);
1343 if constexpr (std::is_same<T, double>::value) {
1344 if (opt.lal_collect) {
1345 LalCollect& c = *opt.lal_collect;
1346 c.sn = std::make_shared<const NetworkStruct<double>>(sn);
1347 c.space = r.space;
1348 c.buf.clear();
1349 c.sync = sync;
1350 c.gsync = gsync;
1351 c.fjsync = fjsync;
1352 c.initial_index = analyzer_detail::init_state_index(sn, r.space);
1353 c.filled = true;
1354 if (c.stop) return out;
1355 }
1356 }
1357 // ELIMINATE THE VANISHING STATES, `solver_ctmc.m:812`. Until this ran the
1358 // port returned the UNREDUCED chain: a Router or Fork pass-through, a firable
1359 // Join and an immediate SPN mode all kept their GlobalConstants::Immediate
1360 // row, so `-a states` and `-a gen` reported a state space the other three
1361 // codebases had already complemented away -- six states against four on
1362 // `fj_tiny_closed`, the two extras carrying 6.1e-09 of the mass each. `-a avg`
1363 // agreed to the digits printed for exactly that reason, which is why the gap
1364 // stayed invisible unless the chain itself was asked for.
1366
1367 const std::size_t npos = static_cast<std::size_t>(-1);
1368 // The initial state is looked up in the REDUCED space: the enumeration index
1369 // no longer addresses the same rows once the vanishing ones are gone.
1370 std::size_t init = analyzer_detail::init_state_index(sn, r.space);
1371
1372 std::size_t ncomp = 0;
1373 const std::vector<std::size_t> comp = analyzer_detail::weak_components(r.Q, ncomp);
1374 if (ncomp > 1) {
1375 std::size_t pick;
1376 if (init != npos) {
1377 pick = comp[init];
1378 } else {
1379 // The initial state is not representable in this space -- an SPN
1380 // whose ENABLE states were folded away, for one -- so the reference
1381 // keeps the largest component instead of failing.
1382 std::vector<std::size_t> sizes(ncomp, 0);
1383 for (std::size_t s = 0; s < comp.size(); ++s) ++sizes[comp[s]];
1384 pick = static_cast<std::size_t>(
1385 std::max_element(sizes.begin(), sizes.end()) - sizes.begin());
1386 }
1387 std::vector<std::size_t> wset;
1388 for (std::size_t s = 0; s < comp.size(); ++s)
1389 if (comp[s] == pick) wset.push_back(s);
1390 // The seed moves WITH the restriction: keeping the pre-restriction row
1391 // would point the block decomposition at whatever state now sits there.
1392 std::size_t moved = npos;
1393 if (init != npos)
1394 for (std::size_t k = 0; k < wset.size(); ++k)
1395 if (wset[k] == init) {
1396 moved = k;
1397 break;
1398 }
1399 init = moved;
1400 r = analyzer_detail::restrict_to(r, wset);
1401 }
1402
1403 // Every stationary solve goes through the block decomposition, as
1404 // `solver_ctmc_analyzer.m` does: the irreducible case is the degenerate one
1405 // BSCC / no transient states, so no dispatch can disagree with the
1406 // algorithm about whether the chain is reducible. `ctmc_solve` splits a
1407 // reducible generator into WEAK components and renormalizes across them,
1408 // which is not the answer the declared initial state selects.
1409 line::util::LineConsole::step("infinitesimal generator built: %zu states",
1410 static_cast<std::size_t>(r.Q.rows()));
1411 if (stationary) {
1412 // A caller-supplied solver over the same chain (SolverMAM 'censor'); the
1413 // metric extraction below is shared, clamp and renormalization included.
1415 "solving for the stationary distribution (caller-supplied solver)");
1416 out.pi = stationary(r.Q, r.space, ctmc_state_space_aggr(sn, r.space), sn);
1417 if (out.pi.size() != r.Q.rows())
1418 throw NumericError("SolverCTMC: the caller-supplied stationary solver returned " +
1419 std::to_string(out.pi.size()) + " entries for " +
1420 std::to_string(r.Q.rows()) + " states");
1421 } else {
1422 line::util::LineConsole::step("solving for the stationary distribution");
1423 const CtmcStationaryResult<T> st = ctmc_stationary(r.Q, init);
1424 out.pi = st.pi;
1425 out.warning = st.warning;
1426 }
1427 line::util::LineConsole::step("stationary distribution obtained, computing the mean metrics");
1428 out.avg = solver_ctmc_avg_from_pi(sn, r, out.pi);
1429 out.cache = analyzer_detail::cache_metrics(sn, r, out.pi, out.avg.QN);
1430 out.chain = r;
1431 out.actualmethod = opt.method;
1432 return out;
1433}
1434
1435
1436/**
1437 * Port of `solver_ctmc_analyzer.m` plus the fork-join wrapper of
1438 * `@@SolverCTMC/runAnalyzer.m`.
1439 *
1440 * A fork-join model is solved on the TAG-AUGMENTED copy and the sibling classes
1441 * are folded back at the end. The chain and the stationary vector returned are the
1442 * AUGMENTED ones, as the reference's `result.space` is: they are indexed by a
1443 * class set the caller did not declare, which is why `fjclassmap` comes back with
1444 * them rather than being discarded.
1445 *
1446 * `stationary`, when given, replaces the stationary solve and nothing else (see
1447 * `CtmcStationaryHook`). Its caller is another solver that reaches this analyzer
1448 * below SolverCTMC's own run checks, as `solver_mam_censor.m` calls
1449 * `solver_ctmc_analyzer.m` directly, so SolverCTMC's feature gate is then left
1450 * to that caller's (SolverMAM's 'censor' featset has already been applied); the
1451 * method check and the declaration checks of `ctmc_check_support` still run.
1452 */
1453template <class T>
1455 const CtmcStationaryHook<T>& stationary =
1457 check_method(opt.method);
1458
1459 // `@@SolverCTMC/runAnalyzer.m:126` converts the non-Markovian service laws
1460 // to a Markovian surrogate on its own copy of the struct. The conversion
1461 // runs before the support check, because what the check must see is the
1462 // struct the generator will actually be built from.
1463 //
1464 // THE FIT IS THE REFERENCE'S CME DEFAULT (`phfit = 'cme'`): below SCV 1 the
1465 // surrogate is a concentrated matrix exponential matching two moments
1466 // exactly, tagged ME, and the generator then carries its signed entries
1467 // (`ctmc_all_phasetype` turns the clamp off). Forcing the Bernstein PH here
1468 // instead left M/Gamma/1 and M/Uniform/1 2% away from MATLAB, the JAR and
1469 // native Python (RespT 2.18638 against 2.14569 at rho 0.7, cutoff 5).
1470 NetworkStruct<T> converted;
1471 const NetworkStruct<T>* snp = &sn_in;
1472 if constexpr (num_traits<T>::has_transcendental) {
1473 if (api::nonmkv_enabled(opt.nonmkv) && api::sn_has_nonmarkov(sn_in, false)) {
1474 converted = sn_in;
1476 no.order = opt.nonmkv_order;
1477 api::sn_nonmarkov_toph(converted, no);
1478 snp = &converted;
1479 }
1480 }
1481 if (!api::nonmkv_enabled(opt.nonmkv)) ctmc_refuse_nonmarkov(*snp);
1482 const NetworkStruct<T>& sn = *snp;
1483
1485 // runAnalyzerChecks' universal feature gate, AFTER ctmc_check_support so the
1486 // declaration-defect messages, which the declared set also withholds, still
1487 // win over the gate's generic one.
1488 if (!stationary) qn::feature_gate("SolverCTMC", qn::ctmc_feature_set(opt.method), sn);
1489
1490 if (!tr::has_fork_join(sn))
1491 return solve_struct(sn, opt, std::vector<qn::FjSync<T>>(), stationary);
1492
1493 // An open chain through a Fork, and a quorum join, are truncated at the
1494 // cutoff: that many fork-join jobs in progress at once (`fj_tag`).
1495 const qn::FjTagged<T> fjt = qn::fj_tag(sn, analyzer_detail::fj_tag_pool(opt));
1496 CtmcSolution<T> out = solve_struct(fjt.V, opt, fjt.fjsync, stationary);
1497 // the LAL embedding stops at the collected arcs, before any metric
1498 if (opt.lal_collect && opt.lal_collect->filled && opt.lal_collect->stop) return out;
1499 tr::fj_foldback(sn, out.avg, fjt.fjclassmap, fjt.korig);
1500 out.fjclassmap = fjt.fjclassmap;
1501 return out;
1502}
1503
1504/**
1505 * Port of `@@SolverCTMC/runAnalyzer.m`'s result assembly: solve, then apply the
1506 * metric filter `@@NetworkSolver/getAvg` puts between the analyzer and the
1507 * caller, so the table is the same shape SolverMVA and SolverNC print.
1508 *
1509 * The response-time mask the product-form runners apply -- drop a metric whose
1510 * response time is below the tolerance -- is NOT applied here. A CTMC reports
1511 * what the chain does, and a station a class genuinely visits with a tiny
1512 * response time is a real measurement rather than a numerical artefact of a
1513 * fixed point that did not converge there.
1514 */
1515template <class T>
1517 const std::string& method) {
1518 const std::size_t M = sn.nstations, K = sn.nclasses;
1519
1520 std::vector<std::vector<bool>> srcmask(M, std::vector<bool>(K, false));
1521 for (std::size_t i = 0; i < M; ++i)
1522 if (sn.stations[i].nodetype == NodeType::Source)
1523 for (std::size_t k = 0; k < K; ++k) srcmask[i][k] = true;
1524
1525 // A PLACE IS MEASURED IN TOKENS and the analyzer counts FIRING EVENTS: an
1526 // arc of multiplicity 2 moves two tokens per firing, and an IMMEDIATE mode
1527 // moves them in zero time, which is not a timed event and so is counted by
1528 // no analyzer here or in the reference. `sn_pn_avg_rates` recovers the mode
1529 // firing rates from the flow-balance equations and rewrites the Place rows
1530 // of TN and RN, exactly where `@SolverCTMC/runAnalyzer.m:126` and `:266` do
1531 // it -- on the RAW table, before the filter, and on the ORIGINAL struct,
1532 // since `solver_ctmc_analyzer_any` folds a fork-join tagging back before
1533 // returning. A model with no Place is returned untouched. AN follows below
1534 // from the repaired TN, as `AN = sn_get_arvr_from_tput(sn, TN)` does there.
1535 const api::SnPnAvgRates<T> pn =
1536 api::sn_pn_avg_rates(sn, d.avg.QN, d.avg.TN, Matrix<T>(), d.avg.RN);
1537
1539 o.QN = mva::filter_metric(sn, d.avg.QN, mva::MetricKind::QLen, nullptr);
1540 o.UN = mva::filter_metric(sn, d.avg.UN, mva::MetricKind::Util, nullptr);
1542 o.TN = mva::filter_metric(sn, pn.TN, mva::MetricKind::Tput, nullptr);
1544 mva::MetricKind::ResidT, nullptr);
1546 &srcmask);
1547 o.CN = d.avg.CN;
1548 o.XN = d.avg.XN;
1549 o.cache = d.cache;
1550 o.method = method;
1552 o.iter = 1;
1553 return o;
1554}
1555
1556template <class T>
1557mva::AvgResult<T> solver_ctmc_run_analyzer(const NetworkStruct<T>& sn, const CtmcOptions& opt);
1558
1559/**
1560 * Solve the CHAIN-AGGREGATED model and map its metrics back to the classes.
1561 *
1562 * `api::sn_aggregate_chains` collapses every chain onto a single class, class
1563 * switching disappearing with it, and `mva::sn_deaggregate_chain_results` maps
1564 * chain-level metrics back through alpha, the per-station share of the chain's
1565 * visits each class carries. Both transforms existed in all four codebases with
1566 * no solver consumer; this is that consumer.
1567 *
1568 * WHAT IS TRADED. Exactness on a non-product-form model: one aggregate service
1569 * law, fitted to the alpha-weighted first two moments, replaces the per-class
1570 * ones. On a product-form model the chain IS the unit MVA and convolution
1571 * already solve in, so the answer is exact and the state space is the smaller
1572 * one.
1573 */
1574template <class T>
1576 const CtmcOptions& opt) {
1577 // Driven by tr::transform_solve_chains, so the aggregate is solved through
1578 // an inner-solve seam rather than a hard-wired call to this analyzer.
1579 // Clearing the flag states that the aggregate must not be re-aggregated,
1580 // rather than relying on the caller's nchains < nclasses guard to decline.
1581 CtmcOptions sub = opt;
1582 sub.chain_aggregation = false;
1584 sn,
1585 [&sub](const NetworkStruct<T>& subsn) { return solver_ctmc_run_analyzer(subsn, sub); },
1586 opt.method);
1587}
1588
1589/**
1590 * Solve by LOAD CONCEALMENT, the iterated transformation.
1591 *
1592 * `tr::transform_solve_lc` sweeps the chains in Gauss-Seidel order, solving each
1593 * concealed single-chain struct with THIS analyzer. Clearing the flag on the
1594 * inner options states that a subproblem must not be concealed again, rather
1595 * than relying on its one-chain shape to decline.
1596 */
1597template <class T>
1599 const CtmcOptions& opt) {
1600 CtmcOptions sub = opt;
1601 sub.load_concealment = false;
1603 sn,
1604 [&sub](const NetworkStruct<T>& subsn) { return solver_ctmc_run_analyzer(subsn, sub); },
1605 opt.method, opt.transform_iter_max);
1606}
1607
1608/**
1609 * Solve with a station subset replaced by a FLOW-EQUIVALENT SERVER, then
1610 * recover the collapsed stations' own metrics by conditioning.
1611 *
1612 * `api::fes_aggregate` has existed in all four codebases with no solver
1613 * consumer at all: it was exercised by examples and tests only, so nothing in
1614 * the solver stack depended on it. Flow-equivalent aggregation is the standard
1615 * route to HIERARCHICAL DECOMPOSITION -- a subnetwork is solved in isolation
1616 * and enters the outer chain as a single load-dependent station, which is what
1617 * makes an otherwise intractable state space tractable.
1618 *
1619 * The reduced model answers for the surviving stations directly. For a
1620 * collapsed station the answer is the Chandy-Herzog-Woo conditional sum
1621 * E[Q_i] = sum_n P(N_fes = n) * Q_i(n), with P read off the reduced chain's
1622 * stationary law and Q_i(n) from the isolated subnetwork
1623 * (`fes::fes_compute_metrics`). Throughput needs no conditioning: flow is fixed
1624 * by the routing and an exact reduction leaves the chain throughput unchanged.
1625 *
1626 * EXACT when the collapsed subnetwork is product-form, which is the condition
1627 * `fes_aggregate` already imposes; an approximation otherwise, and the
1628 * state-space saving is the reason to accept that.
1629 */
1630template <class T>
1632 const CtmcOptions& opt) {
1633 const std::size_t M = sn.nstations, K = sn.nclasses;
1634 const std::vector<std::size_t>& subset = opt.fes_stations;
1635 if (subset.size() < 2)
1636 throw InputError(
1637 "options.config.fes_stations must name at least two stations: collapsing one "
1638 "station into a flow-equivalent server saves nothing.");
1639 if (subset.size() >= M)
1640 throw InputError(
1641 "options.config.fes_stations names every station: there is no complement left "
1642 "to solve.");
1643 for (std::size_t i : subset)
1644 if (i < 1 || i > M)
1645 throw InputError("options.config.fes_stations must be 1-based station indices in 1.." +
1646 std::to_string(M) + ".");
1647
1648 fes::FesOptions fesopts;
1649 if (!opt.fes_solver.empty()) {
1650 fesopts.solver = opt.fes_solver;
1651 fesopts.seed = opt.seed;
1652 }
1653 fes::FesAggregateResult<T> agg = fes::fes_aggregate(sn, subset, fesopts);
1654 const fes::FesDeaggInfo<T>& info = agg.deagg;
1655 const NetworkStruct<T>& snRed = agg.model.get_struct();
1656
1657 CtmcOptions sub = opt;
1658 sub.fes_stations.clear();
1659 const CtmcSolution<T> red = solver_ctmc_analyzer(snRed, sub);
1660 const mva::AvgResult<T> redAvg = solver_ctmc_avg_table(snRed, red, sub.method);
1661
1662 // P(N_fes = n). The aggregate state space carries K columns per STATION, at
1663 // (ist-1)*K + k, so the FES's block is the one at its station index.
1664 const Matrix<T> SSq = ctmc_state_space_aggr(snRed, red.chain.space);
1665 const std::size_t fesIst = snRed.nodes[info.fesNode - 1].station;
1666 std::size_t tableSize = 1;
1667 for (int c : info.cutoffs) tableSize *= static_cast<std::size_t>(c + 1);
1668 std::vector<double> Pn(tableSize, 0.0);
1669 for (std::size_t r = 0; r < SSq.rows(); ++r) {
1670 std::vector<int> nvec(K, 0);
1671 for (std::size_t k = 0; k < K; ++k)
1672 nvec[k] = static_cast<int>(
1673 std::llround(num_traits<T>::to_double(SSq(r, (fesIst - 1) * K + k))));
1674 Pn[fes::ljd_linearize(nvec, info.cutoffs) - 1] +=
1675 r < red.pi.size() ? num_traits<T>::to_double(red.pi[r]) : 0.0;
1676 }
1677
1678 // The isolated subnetwork's metrics at every population it can hold: from
1679 // the solve that produced the FES rates when it was not the product-form
1680 // one, so the conditional sum and the rates describe the same subnetwork.
1682 if (!info.isolatedQtable.empty()) {
1683 cm.QN = info.isolatedQtable;
1684 cm.UN = info.isolatedUtable;
1685 } else {
1687 info.isolatedIsDelay, info.cutoffs);
1688 }
1689
1690 const T zero = num_traits<T>::from_int(0);
1692 out.QN = Matrix<T>(M, K, zero);
1693 out.UN = Matrix<T>(M, K, zero);
1694 out.RN = Matrix<T>(M, K, zero);
1695 out.TN = Matrix<T>(M, K, zero);
1696
1697 for (std::size_t a = 0; a < info.complementIndices.size(); ++a) {
1698 const std::size_t i = info.complementIndices[a] - 1;
1699 for (std::size_t k = 0; k < K; ++k) {
1700 out.QN(i, k) = redAvg.QN(a, k);
1701 out.UN(i, k) = redAvg.UN(a, k);
1702 out.TN(i, k) = redAvg.TN(a, k);
1703 }
1704 }
1705
1706 const std::size_t Msub = info.subsetIndices.size();
1707 Matrix<T> Qsub(Msub, K, zero), Usub(Msub, K, zero);
1708 for (std::size_t idx = 0; idx < tableSize; ++idx) {
1709 if (!(Pn[idx] > 0.0)) continue;
1710 const T w = num_traits<T>::from_double(Pn[idx]);
1711 for (std::size_t a = 0; a < Msub && a < cm.QN[idx].rows(); ++a)
1712 for (std::size_t k = 0; k < K; ++k) {
1713 Qsub(a, k) += T(w * cm.QN[idx](a, k));
1714 Usub(a, k) += T(w * cm.UN[idx](a, k));
1715 }
1716 }
1717 for (std::size_t a = 0; a < Msub; ++a) {
1718 const std::size_t i = info.subsetIndices[a] - 1;
1719 for (std::size_t k = 0; k < K; ++k) {
1720 out.QN(i, k) = Qsub(a, k);
1721 out.UN(i, k) = Usub(a, k);
1722 // Flow through a station is fixed by the routing, so it is the FES's
1723 // throughput scaled by the ratio of ORIGINAL visit ratios.
1724 T ratio = zero;
1725 for (std::size_t c = 0; c < sn.nchains; ++c) {
1726 const std::size_t isf = sn.stateful_of_station(i + 1) - 1;
1727 const std::size_t isfFes = snRed.stateful_of_station(fesIst) - 1;
1728 if (isf < sn.visits[c].rows() && isfFes < snRed.visits[c].rows() &&
1729 snRed.visits[c](isfFes, k) > zero)
1730 ratio += T(sn.visits[c](isf, k) / snRed.visits[c](isfFes, k));
1731 }
1732 out.TN(i, k) = T(redAvg.TN(fesIst - 1, k) * ratio);
1733 }
1734 }
1735
1736 out.CN.assign(K, zero);
1737 out.XN = redAvg.XN;
1738 for (std::size_t i = 0; i < M; ++i)
1739 for (std::size_t k = 0; k < K; ++k) {
1740 if (out.TN(i, k) > zero) out.RN(i, k) = T(out.QN(i, k) / out.TN(i, k));
1741 out.CN[k] += out.RN(i, k);
1742 }
1743 out.AN = mva::sn_get_arvr_from_tput(sn, out.TN);
1745 out.method = opt.method;
1746 out.actualmethod = opt.method + "/fes";
1747 return out;
1748}
1749
1750/** Solve and format in one call, for a caller with no use for the chain. */
1751template <class T>
1753 // Chain aggregation, opt-in and only where the transform is not the identity.
1754 if (opt.load_concealment) return solver_ctmc_load_concealment(sn, opt);
1755 if (opt.chain_aggregation && sn.nchains < sn.nclasses)
1757 // Flow-equivalent server aggregation, opt-in.
1758 if (!opt.fes_stations.empty()) return solver_ctmc_fes_aggregation(sn, opt);
1760}
1761
1762} // namespace ctmc
1763} // namespace line
1764
1765// fes_aggregate.h skips the definition of fes::fes_solved_tables while this
1766// header is being read, since it calls the analyzer above; it is complete now.
1768
1769#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:105
std::size_t rows() const
Definition matrix.h:89
NumericError(const std::string &what)
Definition error.h:112
UnsupportedError(const std::string &what)
Definition error.h:119
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...
FES rates from a non-product-form solve of the isolated subnetwork.
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.
The method names of each solver, in listing order.
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.
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...
void sn_nonmarkov_toph(qn::NetworkStruct< T > &sn, const NonmarkovOptions &opts=NonmarkovOptions())
Replace every non-Markovian service and firing law by a Markovian surrogate.
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 > >(), LalCollect *collect=nullptr)
Port of the generator assembly of solver_ctmc.m.
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...
bool ctmc_pools(const qn::NetworkStruct< T > &in, qn::NetworkStruct< T > &out)
Rewrite a copy of in into out when it has pooled stations; false, leaving out untouched,...
CtmcSolution< T > solver_ctmc_analyzer(const NetworkStruct< T > &sn_in, const CtmcOptions &opt, const CtmcStationaryHook< T > &stationary=CtmcStationaryHook< T >())
Port of solver_ctmc_analyzer.m plus the fork-join wrapper of @@SolverCTMC/runAnalyzer....
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)
bool ctmc_mapc(const qn::NetworkStruct< T > &in, qn::NetworkStruct< T > &out)
Rewrite a copy of in into out when it has a MAP service at an FCFS station; false,...
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.
std::function< std::vector< T >( const Matrix< T > &Q, const std::vector< NetState< T > > &space, const Matrix< T > &space_aggr, const NetworkStruct< T > &sn)> CtmcStationaryHook
A caller-supplied STATIONARY SOLVER, the optional third argument of solver_ctmc_analyzer....
CtmcSolution< T > solve_struct(const NetworkStruct< T > &sn_arg, const CtmcOptions &opt, const std::vector< qn::FjSync< T > > &fjsync, const CtmcStationaryHook< T > &stationary=CtmcStationaryHook< T >())
Build the chain of ONE struct, solve it, reduce it.
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.
void ctmc_refuse_nonmarkov(const NetworkStruct< T > &sn)
Refuse the constructs this port generates a chain for but does not MODEL.
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:181
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, bool verbose=false)
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)
Port of sn_get_arvr_from_tput: the arrival rate each station sees, from the throughputs and the class...
std::string state_impatience_unsupported(const NetworkStruct< T > &sn, const std::string &solver)
Port of solver_ctmc_state_supports.m: the impatience laws the state machinery cannot serve,...
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:2887
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:3036
Feature feature_of_process(ProcessType p)
The feature name of a distribution, MATLAB serviceProcess{r}{3}.name.
FeatureSet ctmc_feature_set(const std::string &method)
SolverCTMC.getFeatureSet, the reference's 104 MATLAB names in full.
bool ctmc_station_blocks(const NetworkStruct< T > &in, NetworkStruct< T > &out, bool &reachable)
Prepare the copy SolverCTMC solves: validate the setup/delay-off, finite-attempt and server-paralleli...
FjTagged< T > fj_tag(const NetworkStruct< T > &sn, std::size_t tag_pool=0)
Port of ModelAdapter.fjtag.
Definition fj_tag.h:321
std::vector< double > parallelism_of(const NetworkStruct< T > &sn, std::size_t ind)
Per-class server degrees n_r (all >= 1) of node ind, or empty when every class seizes one server (pyt...
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.
const char * feature_name(Feature f)
The canonical registry name, byte for byte the MATLAB field name.
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.
std::vector< Frame > & stack()
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
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,...
Port of solver_ctmc_mapc.m: the pair form of a MAP (and MMPP2) service at an FCFS station,...
Port of solver_ctmc_pools.m: rewrite every heterogeneous-server station (Queue.addServerType) into th...
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...
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
options.config.nonmkv and friends.
std::size_t order
nonmkvorder, the phase budget
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.
long seed
options.seed, passed to a simulating fes_solver.
bool stiff
options.stiff, which SolverOptions defaults to TRUE and the transient passes to ctmc_transient as use...
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
std::string fes_solver
options.config.fes_solver: how the collapsed subnetwork is solved, 'mva' (default,...
std::shared_ptr< LalCollect > lal_collect
The internal collect sink of the LAL Network embedding (python SolverCTMC._lal_collect).
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 nonmkv
options.config.nonmkv: 'bernstein' (default) runs sn_nonmarkov_toph, 'none' skips it; any other name ...
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:64
std::vector< NetState< T > > space
row i of Q is space[i]
Definition solver_ctmc.h:66
Matrix< T > Q
(n x n) infinitesimal generator
Definition solver_ctmc.h:65
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::shared_ptr< const NetworkStruct< T > > solved_sn
The struct the chain was built on, when it differs from the caller's in its state LAYOUT: set when he...
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.
The internal collect sink of the LAL embedding (python options.collect).
std::vector< qn::Sync< double > > sync
std::size_t initial_index
std::shared_ptr< const qn::NetworkStruct< double > > sn
std::vector< std::vector< std::vector< std::size_t > > > buf
The region FIFOs of each state, per region (WaitqState::buf), when the chain is the WAITQ region walk...
std::vector< qn::FjSync< double > > fjsync
std::vector< qn::GlobalSync< double > > gsync
std::vector< qn::NetState< double > > space
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< Matrix< T > > isolatedQtable
Per 0-based linearized population state, the (M_sub x K) mean queue lengths and utilizations of the i...
std::vector< Matrix< T > > isolatedUtable
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
options of the reference.
std::string solver
options.solver: how the isolated subnetwork is solved.
long seed
options.solverOptions.seed for the 'ssa', 'jmt' and 'ldes' solves.
bool has_map() const
True when the type carries a (D0,D1) pair of its own.
bool is_prior() const
Definition lang_types.h:961
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:72
std::vector< FjSync< T > > fjsync
Definition fj_tag.h:77
NetworkStruct< T > V
Definition fj_tag.h:73
std::size_t korig
Definition fj_tag.h:79
std::vector< std::size_t > fjclassmap
fjclassmap[a-1] is the ORIGINAL class of auxiliary class a, 0 for originals.
Definition fj_tag.h:75
One network state: the per-stateful-node local rows it is composed of.
Definition state.h:3022
The parameters of a Transition node: MATLAB sn.nodeparam{ind} for an SPN transition,...
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....