LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
solver_ln.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_LN_SOLVER_LN_H
6#define LINE_SOLVERS_LN_SOLVER_LN_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * SolverLN: layered decomposition of a layered queueing network.
12 *
13 * Port of the matlab/src/solvers/LN SolverLN class folder -- construct, buildLayers,
14 * buildLayersRecursive, init, initInterlock, converged, analyze, post,
15 * updateMetrics, updatePopulations, updateThinkTimes, updateLayers,
16 * updateRoutingProbabilities, getEntryServiceMatrix and getEnsembleAvg --
17 * driven by the EnsembleSolver iteration in @@EnsembleSolver/iterate.m.
18 *
19 * The method is a Picard iteration over a fixed point. Each processor and each
20 * software task becomes a closed queueing network (a "layer") in which the
21 * element is the server and its callers are the customers; solving all layers
22 * gives new residence times, which become the service times of the calls one
23 * level up and the think times of the callers one level down, and the layers
24 * are re-solved until the queue lengths stop moving.
25 *
26 * WHAT IS IMPLEMENTED. Every path a plain layered model takes is here:
27 * synchronous calls, entry selection by throughput ratio, multi-entry tasks,
28 * reference tasks with think time, infinite-server tasks and processors,
29 * server replication, AND-forks and AND-joins, and the LQNS V5 interlock
30 * analysis. Forwarding is solved too: construct() runs the
31 * lqn_fwd_rendezvous rewrite of lqn_helpers.h (:306), which flattens every
32 * forwarding chain into caller-side pseudo rendezvous arcs, so nothing below
33 * this point needs a forwarding case. Asynchronous calls and entry open
34 * arrivals are solved by giving the layer its own Source/Sink pair and an
35 * open chain (build_layer's async_here/open_entries construction, roughly
36 * :622-668). Cache tasks and item entries are solved by a Cache node placed
37 * in the host layer, with the hit and miss branches switching class at the
38 * server (build_layer's iscachelayer path, :591-616 and the read walk at
39 * :883-908). Setup tasks with a setup time are solved by charging the cold
40 * start to the ENTRY, at the probability the thread was found powered down
41 * (setup_charge, added to entry_servt and to the caller's think time); no layer
42 * station carries a SetupDelayOffParam. Admission constraints are solved by a Region on
43 * the server station, which forces that layer's fixed point through
44 * SolverCTMC rather than MVA or fluid (:1051-1096, dispatch at :1753-1760).
45 * reject_unsupported() (:433) is kept but empty: every construct the
46 * reference LQN model can carry is now accounted for here. A few narrower
47 * combinations remain unsupported and are refused where they are discovered
48 * instead of up front: a fork sharing a layer with an open stream (:492-496),
49 * a fork's fixed point outside layer_solver 'mva' (:1723-1728), and a fluid
50 * layer or an AND-join's order-statistic fit under a non-double/non-real
51 * arithmetic backend (:120-126, :2198-2201).
52 *
53 * WHAT ELSE THIS CLASS ANSWERS, beyond the mean-value table. `options.method`
54 * selects between three DIFFERENT questions rather than three routes to one:
55 * `default` is the mean-based update; `moment3` is updateMetricsMomentBased,
56 * which fits an APH to each layer's response-time CDF and convolves along the
57 * entry's activity sequence, so it additionally reports a per-entry response
58 * time DISTRIBUTION through get_cdf_respt(); `mw.upper` / `mw.lower` report
59 * Majumdar-Woodside robust box bounds and never solve a layer at all.
60 * get_tran_avg() is the layered transient, decoupled (demands frozen at the
61 * fixed point) or coupled (waveform relaxation over time-varying demands
62 * injected through the fluid rate schedule). get_sensitivity_table() delegates
63 * to each layer's own sensitivity table; every derivative in it is a partial
64 * WITHIN its layer, not a total derivative of the layered model.
65 *
66 * THE LAYER ENGINE is `layer_solver`: `mva`, `nc`, `fluid`, `ssa`, `mam`,
67 * `ctmc`, `ldes` or `jmt`, the C++ spelling of the reference's solver FACTORY. They converge to
68 * DIFFERENT fixed points, because each feeds different demands back into the next outer sweep.
69 * `ssa`, `ldes` and `jmt` are noisy, so the deterministic convergence test is replaced by
70 * LnStochController (Robbins-Monro relaxation, Polyak-Ruppert reporting);
71 * running them under the deterministic test would simply reach iter_max.
72 *
73 * PHASE-2 ACTIVITIES ARE SOLVED, not refused. `servt` keeps both phases, so the
74 * server's utilization is unchanged, while `residt` carries the CALLER's view:
75 * phase 1 in full plus the phase-2 time the caller is actually overtaken by,
76 * with the overtaking probability from lqn_analyzers.h's
77 * lqn_overtake_prob_markov. Every phase-2 branch below is gated on `has_phase2`
78 * and is inert on a single-phase model.
79 *
80 * ARITHMETIC. All model quantities are T. Iteration counters, populations,
81 * multiplicities and the convergence tolerances are double, matching the
82 * reference: they are properties of the algorithm and of the model's integer
83 * structure, not quantities whose precision is under study.
84 */
85
87#include <algorithm>
88#include <cctype>
89#include <cmath>
90#include <functional>
91#include <iostream>
92#include <limits>
93#include <map>
94#include <memory>
95#include <set>
96#include <string>
97#include <type_traits>
98#include <vector>
99
104#include "line/api/lqn/lqn_mol.h"
107#include "line/api/mam/aph_fit.h"
120#include "line/api/lqn/lqn_ph.h"
134#include "line/util/error.h"
135#include "line/util/expm.h"
136#include "line/util/linalg.h"
137#include "line/util/matrix.h"
139
140namespace line {
141namespace ln {
142
143using lang::CallType;
144using lang::Distrib;
145using lang::GlobalConstants;
147using lang::LqnElement;
148using lang::NodeType;
152using lqn::LqnCallGroup;
153using lqn::LqnStruct;
154
155/** One (station, class) rate trajectory injected into a layer's closing ODE. */
157
158namespace detail {
159
160/**
161 * Run the fluid analyzer on one layer and write its metrics into the shape the
162 * MVA layer path returns.
163 *
164 * Overloaded rather than gated: LSODA is double-only, so the template below is
165 * what any other backend resolves to, and it refuses by name instead of failing
166 * to compile inside a branch that could never run.
167 */
168inline void ln_fluid_solve(const qn::NetworkStruct<double>& L, const fluid::FluidOptions& fo,
170 // THE RUNNER, NOT THE SWITCH. `solver_fluid` is the ungated port of
171 // solver_fluid_analyzer.m and cannot reach `minnormal`, `rmf`, `mnrefined` or
172 // `kp` at all; `solver_fluid_run_analyzer` is the port of runAnalyzer's resolution,
173 // which is what `LN(model, @(m) Fluid(m))` runs in the reference. Calling
174 // the switch here silently ran the FIRST-ORDER `matrix` method in every
175 // layer: on lqn_basic that reported T3's residence as its bare demand
176 // (0.02 against MATLAB's 0.0206615) because the hard min charges no
177 // queueing below the server count, and the LN table then disagreed with
178 // MATLAB by 3.3% on a metric neither codebase flagged.
180 for (std::size_t i = 0; i < L.nstations; ++i)
181 for (std::size_t r = 0; r < L.nclasses; ++r) {
182 out.Q(i, r) = s.QN(i, r);
183 out.U(i, r) = s.UN(i, r);
184 out.R(i, r) = s.RN(i, r);
185 out.Tp(i, r) = s.TN(i, r);
186 }
187 for (std::size_t r = 0; r < L.nclasses && r < s.XN.size(); ++r) {
188 out.X[r] = s.XN[r];
189 out.C[r] = s.CN[r];
190 }
191 out.method = s.method;
192 out.iter = static_cast<int>(s.iters);
193}
194template <class T>
195void ln_fluid_solve(const qn::NetworkStruct<T>&, const fluid::FluidOptions&,
197 throw UnsupportedError(ErrorKind{"Arithmetic"},
198 "SolverLN: a fluid layer integrates its drift with LSODA, whose coefficients assume "
199 "double precision; rerun with --arith double or use layer_solver 'mva'");
200}
201
202/**
203 * The response-time CDF of every (station, class) of one layer, which is what
204 * `SolverFluid(ensemble{e}).getCdfRespT` returns in the reference.
205 *
206 * The layer is integrated once to its fixed point and the converged state is
207 * the marking the passage starts from, so the law reported is the STATIONARY
208 * response time and not the one seen from an arbitrary initial condition. That
209 * is `options.init_sol = odeStateVec` in `@@SolverFLD/getCdfRespT`.
210 *
211 * A pair the class never visits comes back as the degenerate curve at zero,
212 * which `fluid_passage_time` already returns; the moment extraction above reads
213 * it as a mean of zero and the caller drops the term, as MATLAB's
214 * `m1 > CoarseTol` test does.
215 */
216inline std::vector<std::vector<fluid::FluidPassage>> ln_fluid_cdf_respt(
218 fluid::FluidOptions o = fo;
219 // THE RUNNER, as in ln_fluid_solve: @SolverFLD/getCdfRespT takes the fixed
220 // point and its closure variance from the RESOLVED method. The first-order
221 // switch charges no queueing below the server count, so on a single-server
222 // PS host at 0.88 jobs it returned the bare Exp(1) demand as the activity's
223 // law (mean 1.001 against MATLAB's 1.546) and the entry 8.09 against 8.637.
224 // With the runner the randomLQN model of test_ln_methods.cpp reads E:e0
225 // 2.2752 against MATLAB's 2.2750 (once MATLAB's APH.evalCDF stopped hanging).
227 std::vector<std::vector<fluid::FluidPassage>> out(
228 L.nstations, std::vector<fluid::FluidPassage>(L.nclasses));
229 for (std::size_t i = 1; i <= L.nstations; ++i) {
230 if (L.stations[i - 1].nodetype == qn::NodeType::Source) continue;
231 for (std::size_t r = 1; r <= L.nclasses; ++r) {
232 if (L.disabled[i - 1][r - 1]) continue;
233 out[i - 1][r - 1] = fluid::fluid_passage_time(L, s.xvec, i, r, o.tol, 201, s.closure);
234 }
235 }
236 return out;
237}
238template <class T>
239std::vector<std::vector<fluid::FluidPassage>> ln_fluid_cdf_respt(const qn::NetworkStruct<T>&,
240 const fluid::FluidOptions&) {
241 throw UnsupportedError(ErrorKind{"Arithmetic"},
242 "SolverLN: the response-time CDF a layer contributes to the 'moment3' update is a fluid "
243 "passage time, integrated by LSODA in double precision; rerun with --arith double");
244}
245
246/**
247 * One layer's transient trajectory, the `getTranAvg` of a layer.
248 *
249 * `out_grid` REPLACES the uniform grid, and it is not a convenience: SolverENV
250 * sums a layered stage's exit average against the environment's holding-time
251 * CDF, so the trajectory has to be evaluated where that CDF puts its mass
252 * rather than where the horizon happens to spread points. It also makes every
253 * layer of one stage report on the SAME grid, which is what lets the layers be
254 * assembled into one block-diagonal transient with a single time base.
255 */
256inline std::vector<fluid::FluidTranPoint> ln_fluid_transient(
257 const qn::NetworkStruct<double>& L, const fluid::FluidOptions& fo, double t_end,
258 std::size_t points, const std::vector<double>& out_grid = std::vector<double>()) {
259 return fluid::solver_fluid_transient(L, fo, t_end, points, out_grid);
260}
261template <class T>
262std::vector<fluid::FluidTranPoint> ln_fluid_transient(const qn::NetworkStruct<T>&,
263 const fluid::FluidOptions&, double,
264 std::size_t,
265 const std::vector<double>& =
266 std::vector<double>()) {
267 throw UnsupportedError(ErrorKind{"Arithmetic"},
268 "SolverLN: the layered transient integrates each layer's drift with LSODA, which is "
269 "double precision by construction; rerun with --arith double");
270}
271
272} // namespace detail
273
274/** Options of SolverLN. Defaults are SolverOptions('LN'). */
275struct LnOptions {
276 int iter_max = 200;
277 double iter_tol = 5e-3;
278 double tol = 1e-4;
279 bool interlocking = true;
280 /**
281 * `options.config.interlock_method`: how the interlock is TRACKED once
282 * `interlocking` is on. `ilrate` is the post-hoc rate discount of
283 * update_populations (the default and the historical method); `refpath`
284 * merges the callers that are the same reference customers into ONE client
285 * chain running down the reference path, replacing the discount; `none`
286 * applies no correction. A request refpath cannot carry DOWNGRADES to
287 * `ilrate`, see ln_interlock_method.
288 */
289 std::string interlock_method = "ilrate";
290 /** `options.config.interlock_maxpaths`: refpath refuses a layer carrying more routes into it. */
291 double interlock_maxpaths = 32.0;
292 /**
293 * `options.config.interlock_refpath_scope`: `merging` transforms only the
294 * layers where two or more callers descend from one reference task; `all`
295 * also those with a lone caller below a reference task.
296 */
297 std::string interlock_refpath_scope = "merging";
298 std::string relax = "fixed";
299 double relax_factor = 0.5;
300 /** Options handed to each layer solver; SolverMVA defaults. */
302 /**
303 * Which solver runs each layer: `mva`, `nc`, `fluid`, `ssa`, `mam`, `ctmc`,
304 * `ldes` (the native in-process LDES engine) or `jmt` (JSIM, as a subprocess).
305 *
306 * The reference names this by passing a solver FACTORY,
307 * `LN(model, @(m) Fluid(m, opt))`, so the choice is per-ensemble and not
308 * per-layer; this field is the same choice under a name, because a C++
309 * template cannot take a MATLAB function handle.
310 *
311 * THEY DO NOT CONVERGE TO THE SAME PLACE. Each engine feeds different
312 * service demands back into the next outer iteration, so the ensembles
313 * reach different fixed points rather than the same one by different
314 * routes. `ssa` in particular is a NOISY layer solver: the deterministic
315 * convergence test cannot terminate against its standard error, so it is
316 * driven with `LnStochController` (lqn_analyzers.h) instead.
317 */
318 std::string layer_solver = "mva";
319 /** Options handed to each layer when `layer_solver` is `fluid`. */
321 /** Options handed to each layer when `layer_solver` is `nc`. */
323 /** Options handed to each layer when `layer_solver` is `ssa`. */
325 /** Options handed to each layer when `layer_solver` is `mam` (SolverMAM's own default method). */
327 /**
328 * Options handed to each layer when `layer_solver` is `ctmc`, and to a
329 * Region layer, which goes to CTMC whatever the layer solver is.
330 */
332 /**
333 * Options handed to each layer when `layer_solver` is `ldes`. `seed` is the BASE of the
334 * reference's Robbins-Monro schedule: layer e (1-based) of iteration it runs at
335 * `seed + (it-1)*nlayers + e`, as SolverLN.pre does for every stochastic layer.
336 */
338 /** Options handed to each layer when `layer_solver` is `jmt` (JSIM); `seed` as for `layer_ldes`. */
340 /**
341 * `options.method`, which selects WHAT is reported and not merely how:
342 *
343 * `default` the mean-based update (updateMetricsDefault)
344 * `moment3` the APH moment-based update (updateMetricsMomentBased),
345 * which additionally produces a per-entry response-time
346 * distribution, `get_cdf_respt()`
347 * `mw.upper` Majumdar-Woodside robust box bounds INSTEAD of a fixed
348 * `mw.lower` point: no layer is ever solved, and every metric the
349 * bound does not define is reported as undefined
350 */
351 std::string method = "default";
352 /**
353 * `options.config.ln_transient`: how the per-layer transients are coupled.
354 * `decoupled` freezes the inter-layer demands at the converged fixed point;
355 * `coupled` reconciles them by waveform relaxation. Iteration 0 of the
356 * coupled relaxation IS the decoupled answer.
357 */
358 std::string ln_transient = "coupled";
359 /** `options.config.ln_transient_iter_max` and `..._tol` of the relaxation. */
361 double ln_transient_tol = 1e-2;
362 /**
363 * `options.config.ln_transient_channels`: which inter-layer coupling is
364 * injected, `both`, `thinkt` (client delay only) or `callservt`
365 * (synchronous-call service only). Used to isolate each channel's share of
366 * the coupled transient.
367 */
368 std::string ln_transient_channels = "both";
369 /** `options.timespan(2)`: the transient horizon; infinite means none is set. */
370 double timespan_end = std::numeric_limits<double>::infinity();
371 /** Output points per layer trajectory, and the relaxation's own grid size. */
372 std::size_t tran_points = 101;
373 /**
374 * An EXPLICIT output grid for the layered transient, replacing the uniform
375 * `tran_points` one when it is not empty.
376 *
377 * SolverENV is what asks for it: a layered stage's exit metric is a
378 * Riemann-Stieltjes sum against the environment's holding-time CDF, and a
379 * uniform grid over the horizon resolves the horizon rather than the
380 * sojourn. Interpolating afterwards cannot recover resolution the
381 * trajectory never had, so the points are asked for instead --
382 * `SolverEnv::stage_grid` builds them and `set_tran_grid` installs them.
383 * The grid must be increasing and start at zero; LSODA takes it as given.
384 */
385 std::vector<double> tran_grid;
386 /**
387 * `options.config.lld`: a smooth queue-dependent rate multiplier per
388 * station, `{processor or task name: expression in n}`, read by
389 * method='nlp' and by warmstart='nlp' only. See lqn_export_nlp.h.
390 */
391 std::map<std::string, ::line::lqn::NlpLld> lld;
392 /** `options.config.nlp_alpha`: sharpness of the softmin standing in for min(n, m). */
393 double nlp_alpha = 20.0;
394 /** `options.config.nlp_warm`: the warm-start sweeps the program's Newton ladder begins from. */
395 int nlp_warm = 0;
396 /** `options.config.nlp_maxiter`: budget of the descent the root-find falls back to. */
397 int nlp_maxiter = 3000;
398 /** `options.config.nlp_fork`: 'refuse' an AND-fork block, or price it at E[max] of exponentials ('exp'). */
399 std::string nlp_fork = "refuse";
400 /**
401 * `options.config.warmstart`: empty for a cold start, or 'nlp' / 'mol' to
402 * seed a LAYERED method's fixed point with the QD-AMVA program's solution or
403 * the Method of Layers'. Refused with method='nlp', which runs no iteration.
404 */
405 std::string warmstart;
406 /** `options.config.mol_iter_max`, `mol_iter_tol`, `mol_relax_factor`: lqn_mol's own settings for warmstart='mol'. */
407 std::size_t mol_iter_max = 200;
408 double mol_iter_tol = 1e-6;
409 double mol_relax_factor = 0.5;
410};
411
412/** Per-layer results of one iteration, the [QN,UN,RN,TN,AN,WN] of getAvg. */
413template <class T>
416};
417
418/** The LQN-level answer, indexed by element 1..nidx. */
419template <class T>
421 std::vector<T> QN, UN, RN, TN, AN, WN;
423 int iterations = 0;
424 bool converged = false;
425 /**
426 * True when the numbers are a BOUND (`method` = `mw.upper` / `mw.lower`)
427 * rather than the fixed point. A bound defines throughput and processor
428 * utilization and nothing else, so the other four measures come back
429 * undefined; reporting zeros there would be a claim.
430 */
431 bool is_bound = false;
432 /** A warning the analysis raised, verbatim, empty when it raised none (method='nlp' off a root). */
433 std::string warning;
434};
435
436/** A CDF sampled on a grid, the [F, t] pair MATLAB's evalCDF returns. */
437struct LnCdf {
438 std::vector<double> t, cdf;
439 bool empty() const { return t.empty(); }
440};
441
442/**
443 * One layer's block of the layered transient.
444 *
445 * The reference assembles the layers into one BLOCK-DIAGONAL cell array whose
446 * off-diagonal blocks are empty, so the blocks themselves carry the whole
447 * answer; keeping them apart also keeps each layer's own time grid, which the
448 * block-diagonal form has nowhere to put.
449 */
451 std::vector<double> t; ///< the output grid, shared by every series below
452 /// [station][class][point]
453 std::vector<std::vector<std::vector<double>>> QN, UN, TN;
454};
455
456/**
457 * `LayeredNetwork.layerBlocks`: where each layer's block sits in the aggregate.
458 *
459 * An LQN has no stations and classes of its own -- SolverLN builds them, one
460 * network per layer -- so the flat (station, class) view a caller like
461 * SolverENV needs is the BLOCK-DIAGONAL UNION of the layer networks, in layer
462 * order. `roff[e]`/`coff[e]` are layer e's 0-based row/column offset in that
463 * union and `msz[e]`/`ksz[e]` its size; `M`/`K` are the totals.
464 *
465 * The off-diagonal blocks pair a station of one layer with a class of another
466 * and stand for nothing at all. The reference leaves them as EMPTY cells; this
467 * port fills them with zeros, which is what the reference's consumers make of
468 * an empty cell (`tranTimeBase_` returns nothing and the metric stays 0).
469 */
471 std::vector<std::size_t> roff, coff, msz, ksz;
472 std::size_t M = 0, K = 0;
473};
474
475/** The layered transient: one block per layer, plus how it was produced. */
477 std::vector<LnTranLayer> layers;
478 std::string mode; ///< "coupled" or "decoupled"
479 long iterations = 0; ///< waveform-relaxation sweeps; 0 when decoupled
480 double gap = 0.0; ///< final sup-norm trajectory change, coupled only
481};
482
483/** getSensitivityTable of the ensemble: the layer tables under a Layer column. */
484template <class T>
486 struct Row {
487 std::string layer, station, jobclass;
489 };
490 std::vector<Row> rows;
491 /** Per layer, the branch that layer took; empty for a layer with no solver. */
492 std::vector<std::string> layer_methods;
493 /** The summary label: the common branch, or "mixed" when they differ. */
494 std::string method;
495 /** Per layer, the analytic Jacobian where that layer produced one. */
496 std::vector<sens::SensTable<T>> layer_tables;
497};
498
499/**
500 * Overtaking probability at a server entry, defined in lqn_analyzers.h.
501 *
502 * DECLARED, not included: lqn_analyzers.h needs LayerResult and SolverLN
503 * complete (LnStochController holds a vector of the first and two refusals take
504 * the second), so it must be parsed AFTER this class. The definition arrives
505 * through the include at the foot of this file, which is why the declaration
506 * has to stand here -- an unqualified call from a member function would
507 * otherwise find nothing, LqnStruct's associated namespace being line::lqn.
508 */
509template <class T>
510T lqn_overtake_prob_markov(const LqnStruct<T>& lqn, const std::vector<T>& servt,
511 const std::vector<T>& callresidt, const std::vector<T>& tput,
512 std::size_t eidx, const T& xj);
513
514/** `options.config.stochiter_*` of SolverOptions.m, with its defaults. */
516 long burnin = 5; ///< Picard iterations before the step decay starts
517 double a0 = 1.0; ///< Robbins-Monro step immediately after burn-in
518 double alpha = 0.6; ///< step decay exponent, in (0.5, 1]
519 long conseq = 3; ///< consecutive sub-tolerance iterations required to stop
520 double iter_tol = 5e-3;
521 /** Relaxation in force during burn-in, i.e. whatever init left in place. */
522 double relax_burnin = 1.0;
523};
524
525/**
526 * The Robbins-Monro / Polyak-Ruppert controller, defined in lqn_analyzers.h.
527 *
528 * DECLARED HERE, not included: same mutual dependence as above. `iterate` holds
529 * one through a shared_ptr rather than by value so that this class stays
530 * complete without it -- a by-value member would need the definition at the
531 * point the class template is instantiated, and the definition arrives at the
532 * foot of this file.
533 *
534 * ITS CONFIG CANNOT BE DEFERRED THE SAME WAY. `iterate` names LnStochConfig by
535 * value, and that name does not depend on T, so it is looked up and required
536 * COMPLETE when the template is parsed rather than when it is instantiated --
537 * the shared_ptr trick only defers the class template beside it.
538 */
539template <class T>
541
542template <class T>
543class SolverLN {
544public:
545 /**
546 * Port of `SolverLN.listValidMethods`.
547 *
548 * Each name states the LAYERING and the ENCODING; `ln_requested_method`
549 * normalises the alias spellings ("ph", "cs", "srvncs", "flatcs",
550 * "squashed", "squashed.ph") onto these, and they are left out here to keep
551 * the list unambiguous, exactly as the reference does.
552 */
553 static std::vector<std::string> list_valid_methods() {
554 // the names and their order are this solver's row of the method registry (doc/line-methods.json)
555 return ::line::method_registry::methods("LN");
556 }
557
558 SolverLN(const LqnStruct<T>& lqn_in, const LnOptions& options) : lqn(lqn_in), opt(options) {
559 // A LAYER SOLVER NEVER NARRATES, the same invariant the MATLAB, JAR and
560 // python ports stamp on each constructed layer solver. The fixed point
561 // runs every layer once per iteration, so a layer left at the caller's
562 // verbosity would print its own banner nlayers*iter_max times and bury
563 // the layered narration the caller actually asked for. `ssa` is the one
564 // layer engine here carrying a verbosity knob of its own; the level is
565 // forced rather than trusted so a library caller cannot set it.
566 // SolverLN's own reporting is unaffected.
567 opt.layer_ssa.verbose = false;
568 // interlock_method itself is validated by ln_interlock_method, where it is resolved
569 for (char& ch : opt.interlock_refpath_scope)
570 ch = char(std::tolower(static_cast<unsigned char>(ch)));
571 if (opt.interlock_refpath_scope != "merging" && opt.interlock_refpath_scope != "all")
572 throw InputError("Unknown config.interlock_refpath_scope '" +
573 opt.interlock_refpath_scope + "', use 'merging' or 'all'.");
574 if (std::isnan(opt.interlock_maxpaths) || opt.interlock_maxpaths < 0.0)
575 throw InputError("config.interlock_maxpaths must be a non-negative number.");
576 validate_nlp_options();
577 construct();
578 }
579
580 /** True once init() seeded the iterate from config.warmstart; converged() then drops iter_min. */
581 bool warmstarted() const { return warmstarted_; }
582 /** method='nlp': the program's solution, clipped at zero, in the program's variable order. */
583 const std::vector<double>& nlp_solution() const { return nlp_solution_; }
584 /** method='nlp': the program's objective at nlp_solution(). */
585 double nlp_objective() const { return nlp_objective_; }
586
587 /**
588 * The QD-AMVA program of this model under the solver's nlp options, the
589 * program method='nlp' roots and warmstart='nlp' seeds from.
590 */
593 o.lld = opt.lld;
594 o.alpha = opt.nlp_alpha;
595 o.fork = opt.nlp_fork;
596 return ::line::lqn::lqn_nlp_program(lqn, o);
597 }
598
599 /** Port of getEnsembleAvg: run the iteration and aggregate onto LQN elements. */
601 // getAvgTable.m:611-624 answers the two bound requests WITHOUT running
602 // the fixed point at all: a box bound is a statement about the model,
603 // not about an iterate, so solving first and discarding the answer would
604 // only cost time and invite the two to be confused.
605 if (opt.method == "mw.upper" || opt.method == "mw.lower") return box_bounds();
606 // method='nlp' builds no layers and runs no fixed point: the model is one program
607 if (lnmethod == "nlp") return nlp_analyzer();
608 // with every reference task trapped at a zero-capacity element there is nothing to layer
609 if (!zerocap.live) return trapped_overlay(aggregate());
610 iterate();
611 // the layers of "srvn.ph" carry one class per caller task, so the
612 // per-element results are rebuilt analytically -- see aggregate_ph
613 return trapped_overlay(is_ph_encoding() ? aggregate_ph() : aggregate());
614 }
615
616 /**
617 * Nested blocking of the reference tasks trapped at a zero-capacity element
618 * (ln_zero_capacity): every element on a blocked call path holds the requests
619 * stuck below it and never completes one. A processor keeps its undefined
620 * queue length. Port of trappedOverlay in @SolverLN/getEnsembleAvg.m.
621 */
623 if (!zerocap.any_trapped()) return s;
624 const T inf = num_traits<T>::from_double(std::numeric_limits<double>::infinity());
625 for (std::size_t idx = 1; idx <= lqn.nidx; ++idx) {
626 if (!zerocap.onroute[idx]) continue;
627 const T held = num_traits<T>::from_double(zerocap.held[idx]);
628 switch (lqn.type[idx]) {
629 case LqnElement::TASK:
630 // a task the live part also reaches keeps its own requests and rate
631 if (ignore[idx] || !s.defined_Q[idx]) s.QN[idx] = Tzero();
632 s.QN[idx] = T(s.QN[idx] + held);
633 s.defined_Q[idx] = true;
634 if (ignore[idx] && !lqn.isref[idx]) {
635 s.WN[idx] = inf;
636 s.defined_W[idx] = true;
637 }
638 break;
639 case LqnElement::ENTRY:
640 case LqnElement::ACTIVITY:
641 s.QN[idx] = held;
642 s.RN[idx] = inf;
643 s.TN[idx] = Tzero();
644 s.defined_Q[idx] = s.defined_R[idx] = s.defined_T[idx] = true;
645 if (lqn.type[idx] == LqnElement::ACTIVITY) {
646 s.WN[idx] = inf;
647 s.defined_W[idx] = true;
648 }
649 break;
650 default:
651 break;
652 }
653 }
654 return s;
655 }
656
657 /**
658 * Port of @@SolverLN/getCdfRespT: the per-entry response-time distribution.
659 *
660 * ONLY THE `moment3` METHOD PRODUCES ONE. The reference reacts to an empty
661 * table by re-running getAvg under method='moment3' and restoring the
662 * caller's method afterwards, and so does this: the distribution is the
663 * whole point of that method, and the mean-based update has no distribution
664 * to report, not a coarser one.
665 *
666 * Indexed by entry NUMBER 1..nentries, as the reference's
667 * `entrycdfrespt{eidx - (nhosts+ntasks)}` is.
668 */
669 std::vector<LnCdf> get_cdf_respt() {
670 if (lnmethod == "nlp")
671 throw UnsupportedError(ErrorKind{"Analysis"},
672 "method='nlp' solves for means only and builds no layers, so there is no response-time "
673 "distribution to report. Use method='moment3' for getCdfRespT.");
674 if (lqn.nentries == 0) return entrycdfrespt;
675 if (entrycdfrespt.size() <= lqn.nentries || entrycdfrespt[1].empty()) {
676 // The distribution pass reads the ROUTING encoding of the activity
677 // graph, which srvn.ph layers do not carry: re-running the iteration
678 // over them would reconstruct the wrong topology rather than a
679 // coarser answer, and returning the empty table would report no
680 // distribution at all. Refuse by name, as the reference does
681 // (@SolverLN/getCdfRespT).
682 if (is_ph_encoding())
683 throw UnsupportedError(ErrorKind{"Method"},
684 "getCdfRespT needs the routing encoding of the activity graph, which "
685 "method='srvn.ph' does not build. Rebuild the solver with "
686 "method='srvn.cs' or method='moment3'.");
687 // BOTH the option and the RESOLVED method have to move. update_metrics
688 // dispatches on `lnmethod`, which build_layers resolved once, so
689 // flipping `opt.method` alone leaves the mean-based update in place and
690 // the table empty -- which is what this getter did between the alias
691 // landing and 2026-08-11. The routing layers already built serve
692 // moment3 unchanged, so only the update pass changes.
693 const std::string saved = opt.method;
694 const std::string saved_resolved = lnmethod;
695 opt.method = "moment3";
696 lnmethod = "moment3";
697 iterate();
698 aggregate();
699 opt.method = saved;
700 lnmethod = saved_resolved;
701 }
702 return entrycdfrespt;
703 }
704
705 /**
706 * Port of @@SolverLN/getTranAvg: the block-diagonal aggregate transient.
707 *
708 * `opt.ln_transient` selects the coupling; both modes return the same
709 * layout, and iteration 0 of the coupled relaxation IS the decoupled
710 * answer.
711 */
713 if (lnmethod == "nlp")
714 throw UnsupportedError(ErrorKind{"Analysis"},
715 "method='nlp' states the steady state as one program and builds no layers, so there is "
716 "no layer transient to integrate. Use a layered method ('srvn.cs', 'flat.cs') for getTranAvg.");
717 if (opt.ln_transient == "decoupled") return tran_avg_decoupled();
718 if (opt.ln_transient == "coupled") return tran_avg_coupled();
719 throw InputError("SolverLN: unknown ln_transient mode '" + opt.ln_transient +
720 "' (use 'coupled' or 'decoupled')");
721 }
722
723 /**
724 * Port of @@SolverLN/getSensitivityTable: solve the ensemble, then
725 * concatenate each layer solver's own table under a leading Layer column.
726 *
727 * WHAT THESE DERIVATIVES MEAN, and the reference is emphatic about it: each
728 * entry is a partial derivative WITHIN ITS LAYER, taken with the layer
729 * parameters the fixed point produced held fixed. Perturbing a host demand
730 * moves the think times, populations and demands of every other layer
731 * through the fixed-point map, and that indirect term is NOT included. The
732 * table attributes a bottleneck inside a layer; it does not predict the
733 * effect of a parameter change on the solved layered model.
734 */
736 // the derivatives are each layer solver's own, and an empty table would read as "none here"
737 if (lnmethod == "nlp")
738 throw UnsupportedError(ErrorKind{"Analysis"},
739 "method='nlp' states the model as one program and builds no layers, so there are no "
740 "per-layer sensitivities to report. Use a layered method ('srvn', 'srvn.ph', 'flat.cs') "
741 "for getSensitivityTable.");
742 if (results.empty()) iterate();
743 LnSensTable<T> out;
744 out.layer_methods.assign(ensemble.size(), std::string());
745 out.layer_tables.resize(ensemble.size());
746 for (std::size_t e = 0; e < ensemble.size(); ++e) {
747 sens::SensOptions so = sopt;
748 so.simulation = layer_solver_is_stochastic();
749 so.replicate = [this](std::size_t k, std::size_t n) {
750 this->sens_rep_k = k;
751 this->sens_rep_n = n;
752 };
753 const bool exact_available =
754 opt.layer_solver == "mva" || opt.layer_solver == "nc";
756 ensemble[e], so, exact_available && !fj_tr[e].active(),
757 [this, e]() { return this->solve_layer(e); });
758 out.layer_methods[e] = t.method;
759 for (const sens::SensRow<T>& r : t.rows) {
760 typename LnSensTable<T>::Row row;
761 row.layer = ensemble[e].name;
762 row.station = r.station;
763 row.jobclass = r.jobclass;
764 row.dTput = r.dTput;
765 row.dRespT = r.dRespT;
766 row.dQLen = r.dQLen;
767 row.dUtil = r.dUtil;
768 out.rows.push_back(row);
769 }
770 out.layer_tables[e] = t;
771 }
772 // One branch label per layer, plus a summary that is `mixed` when the
773 // layers did not all take the same branch.
774 for (const std::string& m : out.layer_methods) {
775 if (m.empty()) continue;
776 if (out.method.empty()) out.method = m;
777 else if (out.method != m) out.method = "mixed";
778 }
779 return out;
780 }
781
782 /**
783 * Majumdar-Woodside robust box bounds, reported in the shape of a solution.
784 *
785 * `mw.upper` reports the upper bound of both throughput and processor
786 * utilization, `mw.lower` the lower bound of both. Everything the bound
787 * does not define -- queue length, response time, residence time, arrival
788 * rate -- is left UNDEFINED rather than zeroed.
789 */
791 const bool upper = opt.method != "mw.lower";
792 // Fully qualified: the member `lqn` shadows the namespace of the same
793 // name inside this class, so an unqualified `lqn::` would not compile.
794 const ::line::lqn::LqnBoxBounds<T> b = ::line::lqn::lqn_boxbounds(lqn);
796 const std::size_t N = lqn.nidx;
797 auto blank = [&](std::vector<T>& v, std::vector<bool>& d) {
798 v.assign(N + 1, Tzero());
799 d.assign(N + 1, false);
800 };
801 blank(s.QN, s.defined_Q);
802 blank(s.UN, s.defined_U);
803 blank(s.RN, s.defined_R);
804 blank(s.TN, s.defined_T);
805 blank(s.AN, s.defined_A);
806 blank(s.WN, s.defined_W);
807 for (std::size_t i = 1; i <= N; ++i) {
808 if (b.defined_T[i]) {
809 s.TN[i] = upper ? b.TN_up[i] : b.TN_lo[i];
810 s.defined_T[i] = true;
811 }
812 if (b.defined_U[i]) {
813 s.UN[i] = upper ? b.UN_up[i] : b.UN_lo[i];
814 s.defined_U[i] = true;
815 }
816 }
817 s.iterations = 0;
818 s.converged = true; // a bound needs no fixed point to have converged to
819 s.is_bound = true;
820 return s;
821 }
822
823 std::size_t nlayers() const { return ensemble.size(); }
824 const std::vector<qn::Layer<T>>& layers() const { return ensemble; }
825
826 /**
827 * Port of `LayeredNetwork.layerBlocks`: the block-diagonal layout of the
828 * layers in the aggregate (station x class) view.
829 *
830 * Available as soon as the solver is constructed -- `build_layers` runs in
831 * the constructor -- which is what lets SolverENV compare the shapes of its
832 * stages before solving any of them.
833 */
836 const std::size_t E = ensemble.size();
837 b.roff.assign(E, 0);
838 b.coff.assign(E, 0);
839 b.msz.assign(E, 0);
840 b.ksz.assign(E, 0);
841 for (std::size_t e = 0; e < E; ++e) {
842 b.roff[e] = b.M;
843 b.coff[e] = b.K;
844 b.msz[e] = ensemble[e].nstations;
845 b.ksz[e] = ensemble[e].nclasses;
846 b.M += b.msz[e];
847 b.K += b.ksz[e];
848 }
849 return b;
850 }
851
852 /**
853 * Port of `getBlockAvg`: the layers' own STEADY averages, in the
854 * block-diagonal layout of `layer_blocks` (each off-block cell 0).
855 *
856 * This is not `get_ensemble_avg`, whose answer is indexed by LQN element and
857 * carries no station or class meaning. It reads the last iterate of the
858 * fixed point and does NOT run it, so `get_ensemble_avg` must have run. A
859 * non-finite cell is an ABSENT station-class pair and is returned as 0.
860 */
861 void get_block_avg(Matrix<T>& QN, Matrix<T>& UN, Matrix<T>& TN) const {
862 if (results.empty() || results.back().size() < ensemble.size())
863 throw InputError("SolverLN::get_block_avg reads the layer averages of the last fixed-point "
864 "iterate; call get_ensemble_avg first");
865 const LnLayerBlocks b = layer_blocks();
866 const T zero = num_traits<T>::from_double(0.0);
867 QN = Matrix<T>(b.M, b.K, zero);
868 UN = Matrix<T>(b.M, b.K, zero);
869 TN = Matrix<T>(b.M, b.K, zero);
870 auto put = [&](Matrix<T>& D, const Matrix<T>& S, std::size_t e) {
871 for (std::size_t i = 0; i < b.msz[e] && i < S.rows(); ++i)
872 for (std::size_t r = 0; r < b.ksz[e] && r < S.cols(); ++r)
873 if (std::isfinite(num_traits<T>::to_double(S(i, r))))
874 D(b.roff[e] + i, b.coff[e] + r) = S(i, r);
875 };
876 for (std::size_t e = 0; e < ensemble.size(); ++e) {
877 const LayerResult<T>& r = results.back()[e];
878 put(QN, r.QN, e);
879 put(UN, r.UN, e);
880 put(TN, r.TN, e);
881 }
882 }
883
884 /**
885 * Port of `LayeredNetwork.initFromMarginal`: split an aggregate (M x K)
886 * mean queue-length matrix into per-layer blocks and warm-start each layer
887 * from its own.
888 *
889 * WHY THIS IS RECORDED AND NOT APPLIED HERE, which is the trap the JAR and
890 * python ports both hit: the layered fixed point RESETS its layers as it
891 * converges, so a warm start installed before the solve does not survive
892 * it. The blocks are therefore kept and replayed by `run_layer_transient`,
893 * i.e. after the fixed point and immediately before each layer's transient
894 * -- the steady solve ignores an initial state, the transient does not.
895 *
896 * THE BLOCK IS NOT ROUNDED. The reference rounds a replayed block onto the
897 * integer lattice for every layer engine EXCEPT the fluid one, and the
898 * layered transient exists only over fluid layers (`require_transient_ready`
899 * refuses the rest), so the branch that would round has no reachable case
900 * here. Rounding a fluid state would quantize the very quantity SolverENV's
901 * fixed point is iterating on.
902 *
903 * An empty matrix clears the warm start, so a caller can put the layers
904 * back on their default initial state without rebuilding the solver.
905 */
907 const std::size_t E = ensemble.size();
908 layer_tran_init.assign(E, std::vector<double>());
909 if (n.empty()) return;
910 const LnLayerBlocks b = layer_blocks();
911 if (n.rows() != b.M || n.cols() != b.K)
912 throw InputError(
913 "SolverLN::init_from_marginal: the marginal is " + std::to_string(n.rows()) + "x" +
914 std::to_string(n.cols()) + " where the block-diagonal union of the layers is " +
915 std::to_string(b.M) + "x" + std::to_string(b.K) +
916 "; the aggregate view is layerBlocks', not the LQN element count");
917 for (std::size_t e = 0; e < E; ++e) {
918 const qn::Layer<T>& L = ensemble[e];
920 std::vector<double> y(lay.nstates, 0.0);
921 bool any = false;
922 for (std::size_t i = 0; i < L.nstations && i < b.msz[e]; ++i)
923 for (std::size_t r = 0; r < L.nclasses && r < b.ksz[e]; ++r) {
924 if (!lay.enabled[i][r]) continue;
925 const double q = std::max(0.0, n(b.roff[e] + i, b.coff[e] + r));
926 y[lay.qidx[i][r]] = q;
927 if (q > 0.0) any = true;
928 }
929 // An all-zero block is NOT a warm start: it is the absence of one,
930 // and installing it would empty a closed layer whose population the
931 // fixed point conserves. The reference reaches the same place by
932 // never calling initFromMarginal before the first stage solve.
933 if (any) layer_tran_init[e] = y;
934 }
935 }
936
937 /** Install the explicit output grid of the layered transient; see `LnOptions::tran_grid`. */
938 void set_tran_grid(const std::vector<double>& g) { opt.tran_grid = g; }
939
940 /** Diagnostic access to the per-iteration layer results, for the regression. */
941 const std::vector<std::vector<LayerResult<T>>>& iteration_results() const { return results; }
942 const std::vector<T>& state_servt() const { return servt; }
943 const std::vector<T>& state_residt() const { return residt; }
944 const std::vector<T>& state_tput() const { return tput; }
945 const std::vector<T>& state_thinkt() const { return thinkt; }
946 const std::vector<T>& state_callservt() const { return callservt; }
947 const std::vector<T>& state_callresidt() const { return callresidt; }
948 const std::vector<Distrib<T>>& state_servtproc() const { return servtproc; }
949 const std::vector<Distrib<T>>& state_thinktproc() const { return thinktproc; }
950 const std::vector<Distrib<T>>& state_callservtproc() const { return callservtproc; }
951 const std::vector<T>& state_util() const { return util; }
952 /** Per iteration, the layer-summed max queue-length change the convergence test reads (index 0 unused). */
953 const std::vector<double>& state_maxitererr() const { return maxitererr; }
954 /** The method the layers were built for: "srvn.ph", "srvn.cs" or "moment3". */
955 const std::string& state_lnmethod() const { return lnmethod; }
956 /**
957 * The interlock tracking method this run USES: "ilrate", "refpath" or
958 * "none". Recorded by build_layers and, when no layer merged a reference
959 * chain, demoted from "refpath" to "ilrate" at the end of construct.
960 */
961 const std::string& state_interlock_method() const { return interlockMethod; }
962 /** Per reference-path stage key, the stage mean the last iteration installed. */
963 const std::vector<double>& state_refpath_stages() const { return refpath_stage_prev; }
964
965 /**
966 * Port of SolverLN.interlockMethodFor: the method a solve would use, asked
967 * through the same query build_layers asks. Like the reference it does not
968 * see the construct-time demotion of a refpath that merged nothing; that
969 * recorded answer is state_interlock_method().
970 */
972 return ln_interlock_method(lqn, opt.interlock_method, opt.interlocking, lnmethod);
973 }
974
975private:
976 // state
979
980 std::vector<qn::Layer<T>> ensemble; ///< compacted, layer e is ensemble[e]
981 std::vector<long> idxhash; ///< (nidx+1) element -> layer index, -1 if none
982 std::vector<bool> ignore; ///< (nidx+1) element in a component with no ref task
983 LnZeroCapacity zerocap; ///< reference tasks trapped at a zero-capacity element
984
985 // update maps, rows of [layerElement, elementOrCall, node, class]
986 struct UpdRow {
987 std::size_t idx, aidx, node, cls;
988 };
989 std::vector<UpdRow> servt_map, thinkt_map, call_map, actthinkt_map;
990 /**
991 * Source arrival of an async call class, `aidx` holding the call index.
992 *
993 * Kept apart from call_map because the two update different things about
994 * the same class: call_map carries the SERVICE at the server replicas,
995 * this one the arrival RATE at the Source, which is the caller activity's
996 * throughput and so moves with the fixed point. Entry open arrivals have
997 * no row here at all -- theirs is exogenous and never reseeded.
998 */
999 std::vector<UpdRow> arv_call_map;
1000 /** [idx, tidx_caller, eidx, nodefrom, nodeto, classfrom, classto] */
1001 struct RouteRow {
1002 std::size_t idx, tidx_caller, eidx, nodefrom, nodeto, cfrom, cto;
1003 };
1004 std::vector<RouteRow> route_map;
1005 std::vector<std::size_t> unique_route_idx;
1006 std::vector<std::size_t> route_reset, svc_reset;
1007
1008 /** The interlock tracking method in force, resolved once by build_layers. */
1009 std::string interlockMethod = "ilrate";
1010 /**
1011 * Reference-path stage rows, refpath_classes_updmap of the reference:
1012 * [idx, node, class] name the stage, `kind` 1 = residt(elem), 2 =
1013 * callresidt(elem)/entryvisits(fromentry), 3 = threadWait(elem), each term
1014 * multiplied by `sign`.
1015 */
1016 struct RefPathRow {
1017 std::size_t idx, node, cls;
1018 int kind;
1019 std::size_t elem;
1020 double sign;
1021 std::size_t fromentry;
1022 };
1023 std::vector<RefPathRow> refpath_map;
1024 /** Unique (idx, node, class) of refpath_map, sorted, and each row's key. */
1025 std::vector<std::array<std::size_t, 3>> refpath_keys;
1026 std::vector<std::size_t> refpath_group;
1027 /** Per key, the previous iteration's stage mean; NaN until the first update. */
1028 std::vector<double> refpath_stage_prev;
1029 std::vector<T> refpath_stage_prev_v;
1030 /**
1031 * Per layer ELEMENT, the per-class normalising TASK class (1-based, 0 = use
1032 * the chain's reference class), attribute.normclass of the reference. Only
1033 * the refpath layers fill it; see ln_layer_refcell.
1034 */
1035 std::map<std::size_t, std::vector<std::size_t>> layer_normclass;
1036 /** Invocations of an entry per invocation of its task; starts at 1. */
1037 std::vector<T> entryvisits;
1038
1039 Matrix<double> njobs; ///< (NT+1 x NT+1) population of caller tidx in layer idx
1040
1041 // per-element metric state
1042 std::vector<T> servt, residt, tput, util, thinkt;
1043 std::vector<T> callservt, callresidt;
1044 /**
1045 * Phase-2 state, the reference's hasPhase2 / servt_ph1 / servt_ph2 /
1046 * prOvertake. The split is of `servt` and exists only while `has_phase2`;
1047 * `prOvertake` is indexed by entry NUMBER 1..nentries, as the reference
1048 * indexes it, not by element index.
1049 */
1050 bool has_phase2 = false;
1051 std::vector<T> servt_ph1, servt_ph2, prOvertake;
1052 /** Last entry service and its phase-2 part, resolve_entry_service -> overtaking split. */
1053 std::vector<T> entry_servt_last, entry_servt_ph2;
1054 std::vector<T> join_tail; // straggler time after a quorum join replies, a phase-2 tail
1055 /** Tasks whose own layer was collapsed to one representative replica. */
1056 std::set<std::size_t> single_replica_tasks;
1057 /**
1058 * Replicated tasks whose host layer holds ALL their replicas in one class (the
1059 * host has fewer replicas than the task, or is shared unevenly), mapped to that
1060 * layer's server replicas: the client row read there is already the total over
1061 * the task's replicas, one server station holds 1/nreplicas of it (BUG-110).
1062 */
1063 std::map<std::size_t, std::size_t> host_all_replica_tasks;
1064 std::vector<Distrib<T>> servtproc, thinkproc, thinktproc, tputproc, callservtproc;
1065 /**
1066 * `moment3` state: the response-time CDF of each activity (by element) and
1067 * of each call, the fitted per-entry law and the CDF read off it. All empty
1068 * under the default method, which never forms a distribution at all.
1069 */
1070 std::vector<fluid::FluidPassage> servtcdf, callservtcdf;
1071 std::vector<LnCdf> entrycdfrespt;
1072 std::vector<mam::AphPair<T>> entryproc;
1073 /** Per layer, the response-time CDFs of the converged pass; a lazy cache. */
1074 std::vector<std::vector<std::vector<fluid::FluidPassage>>> cdf_repo;
1075 std::vector<double> servt_prev, residt_prev, tput_prev, thinkt_prev;
1076 std::vector<double> callservt_prev, callresidt_prev;
1077 std::vector<T> servt_prev_v, residt_prev_v, tput_prev_v, thinkt_prev_v, callservt_prev_v;
1078 Matrix<T> servtmatrix; ///< (nidx+ncalls) x (nidx+ncalls) entry reachability
1079
1080 // interlock tables
1081 Matrix<T> il_all, il_ph1;
1082 std::vector<std::vector<std::size_t>> il_common_entries, il_src_all, il_src_ph2;
1083 /**
1084 * Per-layer interlock matrix of Franks (1999), Eq. (4.7), CLASS-indexed. A host layer
1085 * whose engine carries the correction inside its own MVA takes the matrix instead of
1086 * having its residence times scaled after the fact; empty for every other layer.
1087 */
1088 std::vector<std::vector<std::vector<double>>> layer_interlock;
1089 std::vector<double> il_num_sources;
1090
1091 std::vector<std::vector<LayerResult<T>>> results; ///< [iteration][layer]
1092 /** The outer iteration analyze() is running, 1-based; 0 before the first sweep. Seeds stochastic layers. */
1093 long cur_it = 0;
1094 /**
1095 * Replication of the tuned sensitivity branch (sens::SensOptions::replicate):
1096 * pair index k (0 = off) and number of pairs. While k > 0 a stochastic layer
1097 * runs with seed + k - 1 and samples / npairs.
1098 */
1099 std::size_t sens_rep_k = 0, sens_rep_n = 0;
1100 /**
1101 * The newest iterate as the layers returned it, before `converged` folded the moving
1102 * average into it. MATLAB averages a copy (iterate.m keeps its own raw history and
1103 * hands it back to self.results every pass), so the window, the error test and the
1104 * averaged servt in updateMetricsDefault all read RAW past iterates; this puts the raw
1105 * values back once the iterate is no longer the newest.
1106 */
1107 std::vector<LayerResult<T>> results_raw_last;
1108 bool results_raw_valid = false;
1109 std::vector<Matrix<T>> layer_init_sol;
1110 /**
1111 * Per layer, the ODE state `init_from_marginal` recorded, replayed by
1112 * `run_layer_transient`. Empty for a layer with no warm start.
1113 */
1114 std::vector<std::vector<double>> layer_tran_init;
1115 /**
1116 * Per layer, the fork-join transform SolverMVA solves instead of the layer
1117 * itself (inactive for a layer with no fork), and the auxiliary arrival
1118 * rates its fixed point iterates on. See fj_mmt.h.
1119 *
1120 * `fj_lambda` is the `self.fjForkLambda` of the reference and is deliberately
1121 * NOT reset between outer iterations: the transform is rebuilt cold on every
1122 * outer pass but the iterate it converged to last time is a far better
1123 * starting point than FineTol, and the reference warm-starts it the same way
1124 * (options.config.fj_warmstart, true by default).
1125 */
1126 std::vector<mva::FjMmt<T>> fj_tr;
1127 std::vector<std::vector<T>> fj_lambda;
1128 double relax_omega = 1.0;
1129 /** Live only while a NOISY layer engine is in force; null otherwise. */
1130 std::shared_ptr<LnStochController<T>> stoch_ctl;
1131 long averagingstart = -1;
1132 bool hasconverged = false;
1133 /** init() seeded the iterate from config.warmstart, so converged() drops iter_min from its stop test. */
1134 bool warmstarted_ = false;
1135 /** method='nlp': the program's root (clipped at zero) and its objective there. */
1136 std::vector<double> nlp_solution_;
1137 double nlp_objective_ = std::numeric_limits<double>::quiet_NaN();
1138 /** method='moment3': true once the distribution pass has formed the entry laws. */
1139 bool moment_pass_done = false;
1140 std::vector<double> maxitererr;
1141 int iterations_done = 0;
1142 bool did_converge = false;
1143
1144 std::size_t NT() const { return lqn.tshift + lqn.ntasks; }
1145
1146 static T Tzero() { return num_traits<T>::from_int(0); }
1147 static T Tone() { return num_traits<T>::from_int(1); }
1148 static double dbl(const T& x) { return num_traits<T>::to_double(x); }
1149
1150 // -----------------------------------------------------------------------
1151 // construct
1152 // -----------------------------------------------------------------------
1153 void construct() {
1154 // Forwarding rewrite, SolverLN.m:162-164: flatten every forwarding
1155 // chain into caller-side pseudo rendezvous calls BEFORE anything else
1156 // reads lqn, so build_layers/detect_phase2/reject_unsupported all see
1157 // plain rendezvous arcs. The raw FWD calls survive in the struct but
1158 // must not contribute blocking after this point (lqn_helpers.h).
1159 lqn_fwd_rendezvous(lqn);
1160 reject_unsupported();
1161 detect_phase2();
1162
1163 const std::size_t N = lqn.nidx;
1164 ignore.assign(N + 1, false);
1165 // weakly connected components of graph + graph'; a component with no
1166 // reference task is unreachable and its elements are ignored
1167 std::vector<long> comp(N + 1, -1);
1168 long ncomp = 0;
1169 for (std::size_t v = 1; v <= N; ++v) {
1170 if (comp[v] >= 0) continue;
1171 std::vector<std::size_t> stack{v};
1172 comp[v] = ncomp;
1173 while (!stack.empty()) {
1174 const std::size_t u = stack.back();
1175 stack.pop_back();
1176 for (std::size_t w : lqn.graph.succ(u))
1177 if (comp[w] < 0) {
1178 comp[w] = ncomp;
1179 stack.push_back(w);
1180 }
1181 for (std::size_t w : lqn.graph.pred(u))
1182 if (comp[w] < 0) {
1183 comp[w] = ncomp;
1184 stack.push_back(w);
1185 }
1186 }
1187 ++ncomp;
1188 }
1189 if (ncomp > 1) {
1190 std::vector<bool> has_ref(ncomp, false);
1191 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
1192 const std::size_t tidx = lqn.tshift + t;
1193 if (lqn.sched[tidx] == SchedStrategy::REF) has_ref[comp[tidx]] = true;
1194 }
1195 for (std::size_t v = 1; v <= N; ++v)
1196 if (!has_ref[comp[v]]) ignore[v] = true;
1197 }
1198 // A reference task trapped at a zero-capacity processor or task is answered
1199 // structurally; the elements only it reaches are dropped from the layers
1200 zerocap = ln_zero_capacity(lqn);
1201 if (!zerocap.reason.empty()) throw UnsupportedError(ErrorKind{"Structure"}, zerocap.reason);
1202 if (zerocap.any_trapped()) {
1203 if (ln_requested_method(opt.method) == "nlp")
1204 throw UnsupportedError(ErrorKind{"Method"},
1205 "method='nlp' cannot solve a model whose reference task is trapped at a "
1206 "zero-capacity element; use a layered method.");
1207 if (num_traits<T>::is_exact)
1208 throw UnsupportedError(ErrorKind{"Structure"},
1209 "A reference task trapped at a zero-capacity element has infinite response "
1210 "times, which exact arithmetic cannot represent; solve it in double precision.");
1211 }
1212 for (std::size_t v = 1; v <= N; ++v)
1213 if (zerocap.ignore[v]) ignore[v] = true;
1214 if (zerocap.any_trapped()) {
1215 // size the thread pools as if the trapped reference tasks were absent
1216 std::vector<double> liveMult = lqn.mult;
1217 for (std::size_t i = 1; i < liveMult.size(); ++i)
1218 if (zerocap.trapped[i]) liveMult[i] = 0.0;
1219 lqn.maxmult = lqn::lqn_sustainable_mult(lqn, liveMult);
1220 }
1221
1222 servtproc.assign(N + 1, Distrib<T>::disabled_dist());
1223 thinkproc.assign(N + 1, Distrib<T>::disabled_dist());
1224 thinktproc.assign(N + 1, Distrib<T>::disabled_dist());
1225 tputproc.assign(N + 1, Distrib<T>::disabled_dist());
1226 for (std::size_t i = 1; i <= N; ++i) {
1227 servtproc[i] = lqn.hostdem[i];
1228 thinkproc[i] = lqn.think[i];
1229 }
1230 callservtproc.assign(lqn.ncalls + 1, Distrib<T>::disabled_dist());
1231 for (std::size_t c = 1; c <= lqn.ncalls; ++c)
1232 callservtproc[c] = lqn.hostdem[lqn.callpair_dst[c]];
1233
1234 // Invocations of an entry per invocation of its task, filled by
1235 // resolve_entry_service; 1 because iteration 1 runs before any measurement
1236 entryvisits.assign(N + 1, Tone());
1237 refpath_map.clear();
1238 layer_normclass.clear();
1239
1240 njobs = Matrix<double>(NT() + 1, NT() + 1, 0.0);
1241 // method 'nlp' solves the model as ONE program and never decomposes it:
1242 // everything above is bookkeeping the analyzer reads (`ignore`), and
1243 // everything below is layer machinery no one would solve. Nor is there
1244 // when every reference task is trapped at a zero-capacity element.
1245 if (ln_requested_method(opt.method) == "nlp" || !zerocap.live) {
1246 if (zerocap.live) lnmethod = "nlp";
1247 return;
1248 }
1249 build_layers();
1250
1251 // layers whose routing or service must be re-derived after an update
1252 std::vector<bool> rr(NT() + 1, false), sr(NT() + 1, false);
1253 for (const RouteRow& r : route_map) rr[r.idx] = true;
1254 for (const UpdRow& r : thinkt_map) sr[r.idx] = true;
1255 for (const UpdRow& r : call_map) sr[r.idx] = true;
1256 // refpath REMOVES the think-time row of every merged caller and the
1257 // client-side call row of every re-expanded descent, so a layer whose only
1258 // per-iteration change was one of those would otherwise never be
1259 // refresh_rates()'d and would freeze at its build-time seed. Its stage
1260 // rows put it back.
1261 for (const RefPathRow& r : refpath_map) sr[r.idx] = true;
1262 // a moved arrival rate reweights the Sink closure, which only
1263 // refresh_chains rebuilds, so these layers need the routing reset
1264 for (const UpdRow& r : arv_call_map) rr[r.idx] = true;
1265 for (std::size_t i = 1; i <= NT(); ++i) {
1266 if (rr[i] && idxhash[i] >= 0) route_reset.push_back(std::size_t(idxhash[i]));
1267 if (sr[i] && idxhash[i] >= 0) svc_reset.push_back(std::size_t(idxhash[i]));
1268 }
1269 std::sort(route_reset.begin(), route_reset.end());
1270 route_reset.erase(std::unique(route_reset.begin(), route_reset.end()), route_reset.end());
1271 std::sort(svc_reset.begin(), svc_reset.end());
1272 svc_reset.erase(std::unique(svc_reset.begin(), svc_reset.end()), svc_reset.end());
1273
1274 // The reference-path stage keys, unique((idx, node, class), 'rows').
1275 refpath_keys.clear();
1276 refpath_group.clear();
1277 for (const RefPathRow& r : refpath_map) refpath_keys.push_back({r.idx, r.node, r.cls});
1278 std::sort(refpath_keys.begin(), refpath_keys.end());
1279 refpath_keys.erase(std::unique(refpath_keys.begin(), refpath_keys.end()),
1280 refpath_keys.end());
1281 for (const RefPathRow& r : refpath_map) {
1282 const std::array<std::size_t, 3> key{r.idx, r.node, r.cls};
1283 refpath_group.push_back(std::size_t(
1284 std::lower_bound(refpath_keys.begin(), refpath_keys.end(), key) -
1285 refpath_keys.begin()));
1286 }
1287 if (refpath_map.empty() && interlockMethod == "refpath") {
1288 // Not one layer merged a reference chain, so the build is the one
1289 // 'none' produces, and so would the solve be: post() suppresses the
1290 // rate discount whenever the method is 'refpath'. Switching a
1291 // correction off and declining to replace it is strictly worse than
1292 // either method alone, so the method is demoted here, before init()
1293 // decides whether to build the interlock tables.
1294 interlockMethod = "ilrate";
1295 }
1296 refpath_stage_prev.assign(refpath_keys.size(), std::numeric_limits<double>::quiet_NaN());
1297 refpath_stage_prev_v.assign(refpath_keys.size(), Tzero());
1298 }
1299
1300 /** Reject, by name, every construct this port does not implement. */
1301 // Phase-2 detection, SolverLN.m:165-173. Deliberately NOT inside
1302 // reject_unsupported: that method is const because it only refuses, and
1303 // detection sets state. Marking the flag mutable would have compiled and
1304 // left a validator that silently mutates the solver.
1305 void detect_phase2() {
1306 has_phase2 = false;
1307 for (std::size_t a = 1; a <= lqn.nacts; ++a)
1308 if (lqn.actphase[a] > 1) has_phase2 = true;
1309 // A quorum join replies after k of its n branches, but the n-k stragglers still run on
1310 // the thread, which stays busy after the reply as in a second phase (ln_has_quorum_tail.m).
1311 // The layer's Join waits for ALL branches; the caller's quorum wait comes back via residt.
1312 for (std::size_t aidx = 1; aidx <= lqn.nidx && aidx < lqn.actquorum.size(); ++aidx) {
1313 if (lqn.actquorum[aidx] < 1) continue;
1314 std::size_t nbranches = 0;
1315 for (std::size_t tail = 1; tail <= lqn.nidx; ++tail) {
1316 if (tail == aidx || lqn.actpretype[tail] != PrecedenceType::PRE_AND) continue;
1317 for (std::size_t sx : lqn.graph.succ(tail))
1318 if (sx == aidx) ++nbranches;
1319 }
1320 if (lqn.actquorum[aidx] < nbranches) has_phase2 = true;
1321 }
1322 }
1323
1324 /**
1325 * True when `eidx` is the destination of a raw forwarding call.
1326 *
1327 * buildLayersRecursive.m:186-192 keeps this test even though
1328 * lqn_fwd_rendezvous has already run, and so must this port:
1329 * the rewrite walks chains out of SYNC calls only, so an entry whose
1330 * forwarder is reached asynchronously gets no pseudo arc and would
1331 * otherwise be dropped from the layer along with all of its work.
1332 */
1333 bool is_fwd_target(std::size_t eidx) const {
1334 for (std::size_t c = 1; c <= lqn.ncalls; ++c)
1335 if (lqn.calltype[c] == CallType::FWD && lqn.callpair_dst[c] == eidx) return true;
1336 return false;
1337 }
1338
1339 /**
1340 * Total exogenous rate into the entries of task `tidx`, zero unless the arrival is
1341 * the ONLY way in.
1342 *
1343 * A task nobody calls has no task layer, so update_think_times never sets its
1344 * surrogate delay and its caller class cycles against an Immediate one. Carrying the
1345 * arrival as an open stream ON TOP of that unthrottled chain loads the host twice:
1346 * lqn_open_arrival read the processor at 0.68 where lqns, lqsim and LDES all give
1347 * 0.32. The chain is the representation that honours the thread pool, so build_layer
1348 * drops the stream for these tasks and update_think_times closes the chain on this
1349 * rate, as the reference does for a forwarding target. With a caller or a forwarding
1350 * source the stream needs a class of its own and this returns 0.
1351 */
1352 double open_arrival_rate_of(std::size_t tidx) const {
1353 if (lqn.isref[tidx]) return 0.0;
1354 for (std::size_t e : lqn.entriesof[tidx])
1355 if (lqn.issynccaller.any_col(e) || lqn.isasynccaller.any_col(e) || is_fwd_target(e))
1356 return 0.0;
1357 double rate = 0.0;
1358 for (std::size_t e : lqn.entriesof[tidx]) {
1359 if (!lqn.has_arrival[e]) continue;
1360 const double m = dbl(lqn.arrival[e].mean);
1361 if (std::isfinite(m) && m > GlobalConstants::FineTol) rate += 1.0 / m;
1362 }
1363 return rate;
1364 }
1365
1366 /**
1367 * Residence time of the synchronous calls the activities `acts` make. A thread of a
1368 * chain closed on a known rate cycles through these calls as well as its host
1369 * demand, so its think time must leave room for them; leaving them out throttled
1370 * the chain below the rate it is closed on: lqns 0.1 against LN 0.0870 for an open
1371 * stream into an entry with one call (BUG-103).
1372 */
1373 T sync_call_residt_of(const std::vector<std::size_t>& acts) const {
1374 T total = Tzero();
1375 for (std::size_t aidx : acts)
1376 for (std::size_t cidx : lqn.callsof[aidx])
1377 if (lqn.calltype[cidx] == CallType::SYNC && cidx < callresidt.size() &&
1378 std::isfinite(dbl(callresidt[cidx])))
1379 total += callresidt[cidx];
1380 return total;
1381 }
1382
1383 /** sync_call_residt_of per arriving request of `tidx`, by each entry's arrival share. */
1384 T open_arrival_call_residt(std::size_t tidx, double arvrate) const {
1385 T total = Tzero();
1386 if (!(arvrate > 0.0)) return total;
1387 for (std::size_t e : lqn.entriesof[tidx]) {
1388 if (!lqn.has_arrival[e]) continue;
1389 const double m = dbl(lqn.arrival[e].mean);
1390 if (std::isfinite(m) && m > GlobalConstants::FineTol)
1391 total += T(num_traits<T>::from_double(1.0 / m / arvrate) *
1392 sync_call_residt_of(lqn.actsof[e]));
1393 }
1394 return total;
1395 }
1396
1397 /** True when layer `e` carries a Cache node. */
1398 bool has_cache_node(std::size_t e) const {
1399 for (std::size_t n = 0; n < ensemble[e].nodes.size(); ++n)
1400 if (ensemble[e].nodes[n].nodetype == NodeType::Cache) return true;
1401 return false;
1402 }
1403
1404 /** True when `aidx` is an activity bound to an entry nobody calls synchronously. */
1405 bool async_only_activity(std::size_t aidx) const {
1406 if (aidx <= lqn.ashift || aidx > lqn.ashift + lqn.nacts) return false;
1407 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
1408 const std::size_t eidx = lqn.eshift + e;
1409 if (lqn.graph.get(eidx, aidx) == Tzero()) continue;
1410 return lqn.isasynccaller.any_col(eidx) && !lqn.issynccaller.any_col(eidx);
1411 }
1412 return false;
1413 }
1414
1415 /**
1416 * Reject, by name, every construct this port does not implement.
1417 *
1418 * NOTHING IS LEFT. Forwarding, asynchronous calls, entry open arrivals,
1419 * admission constraints, cache tasks and setup tasks are each solved.
1420 * The method is kept rather than deleted because it is the place a new
1421 * refusal belongs, and because a layer-build refusal must be raised HERE,
1422 * before construct() has read anything out of the struct, rather than
1423 * halfway through building a layer.
1424 */
1425 void reject_unsupported() const {}
1426
1427 /**
1428 * The interlock tracking method, resolved ONCE for the encoding just chosen,
1429 * for the same reason lnmethod is: what update_populations and init_interlock
1430 * do can never disagree with what was built into the layers.
1431 */
1432 void resolve_interlock_method() {
1433 const LnInterlockChoice ch =
1434 ln_interlock_method(lqn, opt.interlock_method, opt.interlocking, lnmethod);
1435 interlockMethod = ch.method;
1436 if (!ch.why.empty()) std::cerr << "[LINE] Warning: " << ch.why << "\n";
1437 }
1438
1439 // -----------------------------------------------------------------------
1440 // buildLayers
1441 // -----------------------------------------------------------------------
1442 void build_layers() {
1443 // Method resolution. A method name carries both the LAYERING and the
1444 // ENCODING: "srvn.ph" replaces the routing encoding of the activity graph
1445 // by a composed phase-type server law, "srvn" is the alias that takes it
1446 // where it can serve the model and "srvn.cs" otherwise. The choice is
1447 // made ONCE, here, and every later dispatch reads lnmethod.
1448 // See _kb/06-solver-catalog.md (LN section).
1449 const std::string requested = ln_requested_method(opt.method);
1450 assert_call_groups(requested == "flat.cs");
1451 if (requested == "flat.cs") {
1452 lnmethod = "flat.cs";
1453 resolve_interlock_method();
1454 build_flat_layer();
1455 return;
1456 }
1457 if (requested == "flat.ph") {
1458 // the squashed layering with the composed law: ONE submodel holding
1459 // every server, and a caller visiting each of them once per
1460 // invocation. The feature gate is the srvn.ph one plus the refusals a
1461 // single submodel carries -- see ph_flat_server_set.
1462 ph_laws_ready = false;
1463 lnmethod = "flat.ph";
1464 assert_warmstart_encoding();
1465 build_layers_ph(true);
1466 return;
1467 }
1468 if (requested == "srvn.ph" || requested == "srvn") {
1469 ph_laws_ready = false;
1470 // srvn.ph switches the interlock correction off; see has_interlock
1471 if (requested == "srvn.ph" || (!has_interlock() && probe_srvn_ph())) {
1472 lnmethod = "srvn.ph";
1473 assert_warmstart_encoding();
1474 build_layers_ph();
1475 return;
1476 }
1477 }
1478 lnmethod = (requested == "moment3") ? "moment3" : "srvn.cs";
1479 resolve_interlock_method();
1480 std::vector<qn::Layer<T>> raw(NT() + 1);
1481 std::vector<bool> present(NT() + 1, false);
1482
1483 for (std::size_t hidx = 1; hidx <= lqn.nhosts; ++hidx) {
1484 if (ignore[hidx]) continue;
1485 std::vector<std::size_t> hcallers; // a task only a trapped reference task reaches is dropped
1486 for (std::size_t c : lqn.tasksof[hidx])
1487 if (!ignore[c]) hcallers.push_back(c);
1488 build_layer(raw[hidx], {hidx}, hcallers, true, false);
1489 present[hidx] = true;
1490 }
1491 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
1492 const std::size_t tidx = lqn.tshift + t;
1493 if (ignore[tidx] || lqn.isref[tidx]) continue;
1494 bool any_caller = lqn.iscaller.any_row(tidx) || lqn.iscaller.any_col(tidx);
1495 if (!any_caller) continue;
1496 // tasks that call some entry of tidx
1497 std::vector<std::size_t> callers;
1498 for (std::size_t ct = 1; ct <= lqn.ntasks; ++ct) {
1499 const std::size_t c = lqn.tshift + ct;
1500 if (ignore[c]) continue;
1501 bool calls = false;
1502 for (std::size_t e : lqn.entriesof[tidx])
1503 if (lqn.iscaller.get(c, e)) calls = true;
1504 if (calls) callers.push_back(c);
1505 }
1506 if (callers.empty()) continue;
1507 build_layer(raw[tidx], {tidx}, callers, false, false);
1508 present[tidx] = true;
1509 }
1510
1511 idxhash.assign(lqn.nidx + 1, -1);
1512 long next = 0;
1513 for (std::size_t i = 1; i <= NT(); ++i)
1514 if (present[i]) {
1515 idxhash[i] = next++;
1516 ensemble.push_back(std::move(raw[i]));
1517 }
1518 layer_init_sol.assign(ensemble.size(), Matrix<T>());
1519 build_fork_views();
1520 }
1521
1522 /**
1523 * Reject a routed call group under any layering or layer solver that cannot
1524 * carry it.
1525 *
1526 * Two conditions, and both are refusals rather than degradations. The
1527 * squashed layering is needed because under `srvn` each target lives in a
1528 * submodel of its own and is replaced, in the caller's submodel, by a
1529 * surrogate delay -- no node ever has arcs to more than one of them, so
1530 * there is nothing to dispatch among. A layer solver that resolves the
1531 * strategy from the STATE is needed because `refresh_routing` expands
1532 * RROBIN and JSQ into a uniform probability split for the matrix solvers,
1533 * and returning that split under a round-robin label misreports a
1534 * deterministic policy as a coin. In this port `ssa`, `ldes` and `jmt`
1535 * resolve them, the simulators of the reference's CTMC/SSA/LDES/JMT list.
1536 */
1537 void assert_call_groups(bool flat) const {
1538 if (lqn.callgroups.empty()) return;
1539 if (!flat)
1540 throw UnsupportedError(ErrorKind{"CallGroup"},
1541 "Call groups routed by a routing strategy require the squashed layering; use "
1542 "method='flat'. Under srvn the targets never share a submodel, so the dispatch "
1543 "order cannot be represented.");
1544 if (!layer_solver_is_stochastic())
1545 throw UnsupportedError(ErrorKind{"CallGroup"},
1546 "Routed call groups need a layer solver that resolves the strategy from the "
1547 "state; set layer_solver='ssa', 'ldes' or 'jmt'. MVA, NC and FLD read the routing matrix, into "
1548 "which refresh_routing has expanded the strategy as a uniform split, and would "
1549 "return that split under a round-robin or JSQ label.");
1550 }
1551
1552 /**
1553 * The processors and called tasks that become stations of the flat layer.
1554 *
1555 * Squashing is refused rather than approximated where an element carries
1556 * state that only a submodel of its own can hold: a REPLICATED element
1557 * would need one station per copy inside a layer whose routing addresses it
1558 * once, a CACHE task needs the Cache node in the host layer its reads queue
1559 * at, and a SETUP task's delay-off belongs to the station that powers down.
1560 */
1561 std::vector<std::size_t> flat_server_set() const {
1562 std::vector<std::size_t> servers;
1563 for (std::size_t i = 1; i <= NT(); ++i) {
1564 if (lqn.repl[i] > 1.0)
1565 throw UnsupportedError(ErrorKind{"Replication"},
1566 "Flat layering does not support replicated processors or tasks, use the "
1567 "default 'srvn' layering.");
1568 if (lqn.iscache[i])
1569 throw UnsupportedError(ErrorKind{"CacheTask"},
1570 "Flat layering does not support cache tasks, use the default 'srvn' "
1571 "layering.");
1572 if (lqn.hassetup[i])
1573 throw UnsupportedError(ErrorKind{"SetupDelayOff"},
1574 "Flat layering does not support setup tasks, use the default 'srvn' "
1575 "layering.");
1576 }
1577 for (std::size_t hidx = 1; hidx <= lqn.nhosts; ++hidx)
1578 if (!ignore[hidx] && !lqn.tasksof[hidx].empty()) servers.push_back(hidx);
1579 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
1580 const std::size_t tidx = lqn.tshift + t;
1581 if (ignore[tidx] || lqn.isref[tidx]) continue;
1582 if (!lqn.iscaller.any_row(tidx) && !lqn.iscaller.any_col(tidx)) continue;
1583 bool has_task_caller = false;
1584 for (std::size_t eidx : lqn.entriesof[tidx])
1585 for (std::size_t c = 1; c <= lqn.ntasks; ++c)
1586 if (lqn.iscaller.get(lqn.tshift + c, eidx)) has_task_caller = true;
1587 if (has_task_caller) servers.push_back(tidx);
1588 }
1589 if (servers.empty())
1590 throw InputError(
1591 "Flat layering found no server: the model has no processor with tasks.");
1592 return servers;
1593 }
1594
1595 /**
1596 * Build the single squashed layer holding every processor and called task.
1597 *
1598 * Every served element resolves to layer 0, which is at once the host layer
1599 * and the task layer, so a consumer that walks `idxhash` finds the same
1600 * network for a processor and for a task and must read the station off
1601 * `server_idx_of` rather than off `serverIdx`.
1602 */
1603 void build_flat_layer() {
1604 const std::vector<std::size_t> flat_servers = flat_server_set();
1605 std::vector<std::size_t> flat_callers;
1606 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
1607 const std::size_t tidx = lqn.tshift + t;
1608 if (!ignore[tidx]) flat_callers.push_back(tidx);
1609 }
1610 qn::Layer<T> layer;
1611 build_layer(layer, flat_servers, flat_callers, false, true);
1612 ensemble.clear();
1613 ensemble.push_back(std::move(layer));
1614 idxhash.assign(lqn.nidx + 1, -1);
1615 for (std::size_t s : flat_servers) idxhash[s] = 0;
1616 layer_init_sol.assign(ensemble.size(), Matrix<T>());
1617 build_fork_views();
1618 }
1619
1620 /**
1621 * Build, for every layer that has a fork, the transformed model SolverMVA
1622 * actually solves, and seed its auxiliary arrival rates.
1623 */
1624 void build_fork_views() {
1625 fj_tr.assign(ensemble.size(), mva::FjMmt<T>());
1626 fj_lambda.assign(ensemble.size(), {});
1627 for (std::size_t e = 0; e < ensemble.size(); ++e) {
1628 if (!ensemble[e].has_fork()) continue;
1629 // fj_mmt mints its own Source/Sink pair and would silently overwrite
1630 // sourceIdx/sinkNode, detaching the open stream already routed there.
1631 // NOT a parity gap: the reference does not solve this combination
1632 // either, it fails inside the layer solve with "Arrays have
1633 // incompatible sizes" (checked 2026-07-29 on a fork+async model).
1634 // Refusing by name is the better answer, so this stays.
1635 if (ensemble[e].sourceIdx != 0)
1636 throw UnsupportedError(ErrorKind{"Fork"},
1637 "SolverLN: layer '" + ensemble[e].name +
1638 "' carries both an AND fork and an open stream (an async call or an entry "
1639 "arrival); the fork-join transform needs a Source of its own");
1640 fj_tr[e] = mva::fj_mmt(ensemble[e]);
1641 fj_lambda[e].assign(fj_tr[e].V.classes.size() + 1,
1642 num_traits<T>::from_double(GlobalConstants::FineTol));
1643 }
1644 }
1645
1646 /**
1647 * Port of matlab/src/lang/layered/lqn_dep_layer_handle.m: lift a
1648 * per-operand rate handle onto the classes of a layer station.
1649 *
1650 * COLS[j] lists the layer classes (0-based) through which operand j occupies
1651 * the station; CHAINCOLS is the same list in the CHAIN index space, filled
1652 * once refresh_chains has run. Solvers evaluate the handle in either space
1653 * -- CTMC and the exact recursions pass a per-class vector, the AMVA and NC
1654 * chain recursions a per-chain one -- so the handle reads the LENGTH of what
1655 * it is given to decide, aggregates the operand populations in that space,
1656 * and answers a vector of the same length, since the caller indexes the
1657 * answer with the index it passed in. An index belonging to no operand keeps
1658 * the neutral scaling 1.
1659 */
1660 static lang::CdScaling<T> layer_dep_handle(
1661 const lang::CdScaling<T>& f, const std::vector<std::vector<std::size_t>>& cols,
1662 const std::shared_ptr<std::vector<std::vector<std::size_t>>>& chaincols, std::size_t R) {
1663 return [f, cols, chaincols, R](const std::vector<T>& n) -> std::vector<T> {
1664 const std::size_t L = n.size();
1665 const std::vector<std::vector<std::size_t>>& use =
1666 (L == R || chaincols->empty()) ? cols : *chaincols;
1667 std::vector<T> nop(use.size(), num_traits<T>::from_int(0));
1668 for (std::size_t j = 0; j < use.size(); ++j)
1669 for (std::size_t k = 0; k < use[j].size(); ++k)
1670 if (use[j][k] < L) nop[j] = T(nop[j] + n[use[j][k]]);
1671 const std::vector<T> w = f(nop);
1672 std::vector<T> v(L, num_traits<T>::from_int(1));
1673 if (w.empty()) return v;
1674 for (std::size_t j = 0; j < use.size(); ++j) {
1675 const T wj = w[j < w.size() ? j : w.size() - 1];
1676 for (std::size_t k = 0; k < use[j].size(); ++k)
1677 if (use[j][k] < L) v[use[j][k]] = wj;
1678 }
1679 return v;
1680 };
1681 }
1682
1683 /** Spread a per-operand peak rate onto the layer classes. Twin of layerPeak. */
1684 static std::vector<T> layer_peak(const std::vector<T>& peakPerOperand,
1685 const std::vector<std::vector<std::size_t>>& cols,
1686 std::size_t R) {
1687 std::vector<T> peak(R, num_traits<T>::from_int(1));
1688 if (peakPerOperand.empty()) return peak;
1689 for (std::size_t j = 0; j < cols.size(); ++j) {
1690 const T pj = peakPerOperand[j < peakPerOperand.size() ? j : peakPerOperand.size() - 1];
1691 for (std::size_t k = 0; k < cols[j].size(); ++k)
1692 if (cols[j][k] < R) peak[cols[j][k]] = pj;
1693 }
1694 return peak;
1695 }
1696
1697 /**
1698 * Give every class of a host layer the priority of the task that owns it.
1699 *
1700 * Applies to each processor in idxSet that schedules by priority (HOL, 'pri', ...).
1701 * lqns serves a LARGER task priority first while a class priority of 0 is the highest,
1702 * so the class priority is max(prio on the host) - prio(task). A layer solver with a
1703 * priority arm (MVA, CTMC, ...) then applies it. Without this every class tied at 0
1704 * and a priority processor ran as FCFS. Port of MATLAB ln_host_task_priorities.m.
1705 */
1706 void apply_host_task_priorities(qn::Layer<T>& m, const std::vector<std::size_t>& idxSet) const {
1707 using qn::SchedStrategy;
1708 auto is_prio = [](SchedStrategy s) {
1709 return s == SchedStrategy::HOL || s == SchedStrategy::FCFSPRPRIO ||
1710 s == SchedStrategy::FCFSPIPRIO || s == SchedStrategy::LCFSPRIO ||
1711 s == SchedStrategy::LCFSPRPRIO || s == SchedStrategy::LCFSPIPRIO ||
1712 s == SchedStrategy::PSPRIO || s == SchedStrategy::DPSPRIO ||
1713 s == SchedStrategy::GPSPRIO;
1714 };
1715 const std::size_t R = m.classes.size();
1716 std::vector<std::size_t> owner(R + 1, 0); // 1-based class -> owning task, 0 = none
1717 auto own = [&](std::size_t k, std::size_t t) {
1718 if (k >= 1 && k <= R && owner[k] == 0) owner[k] = t;
1719 };
1720 for (const auto& a : m.attr_tasks) own(a.first, a.second);
1721 for (const auto& a : m.attr_entries) own(a.first, lqn.parent[a.second]);
1722 for (const auto& a : m.attr_activities) own(a.first, lqn.parent[a.second]);
1723 for (const auto& a : m.attr_calls) own(a[0], lqn.parent[a[2]]);
1724 for (std::size_t s : idxSet) {
1725 if (s < 1 || s > lqn.nhosts || !is_prio(lqn.sched[s])) continue;
1726 int pmax = 0;
1727 for (std::size_t t = lqn.tshift + 1; t <= lqn.tshift + lqn.ntasks; ++t)
1728 if (lqn.parent[t] == s) pmax = std::max(pmax, lqn.prio[t]);
1729 for (std::size_t k = 1; k <= R; ++k)
1730 if (owner[k] != 0 && lqn.parent[owner[k]] == s)
1731 m.classes[k - 1].prio = pmax - lqn.prio[owner[k]];
1732 }
1733 }
1734
1735 /**
1736 * Port of buildLayersRecursive.
1737 *
1738 * The layer holds a client Delay carrying the callers' think times and the
1739 * time they spend elsewhere, and `nreplicas` copies of the server station.
1740 * A class is created for every task, entry, activity and call that the
1741 * callers' activity graphs reach, and the graph traversal lays down the
1742 * routing that moves a job between those classes.
1743 */
1744 void build_layer(qn::Layer<T>& m, const std::vector<std::size_t>& idxSet,
1745 const std::vector<std::size_t>& callers, bool ishostlayer, bool flat) {
1746 const T one = Tone();
1747 // The layer key: the model name, the ensemble slot and the column every
1748 // update map is written under. Under `srvn` it is the layer's only
1749 // served element; under `flat` it is the first of them.
1750 const std::size_t idx = idxSet[0];
1751 m.name = flat ? lqn.hashnames[idx] + ".Flat" : lqn.hashnames[idx];
1752 m.flat = flat;
1753
1754 const double rawrepl = lqn.repl[idx];
1755 std::size_t nreplicas = 1;
1756 if (!flat && rawrepl > 1.0 && !callers.empty()) {
1757 // A replicated server is pooled into ONE station instead of one per
1758 // replica when every caller already addresses all of its replicas:
1759 // on a host layer that is the callers replicating in step with it,
1760 // on a task layer it is a declared fan-out covering every replica.
1761 // With no fan-out declared the lookup is 0 < rawrepl and the layer
1762 // materialises the replicas, which is the reference's answer too.
1763 bool reduce = true;
1764 if (ishostlayer) {
1765 for (std::size_t c : callers)
1766 if (lqn.repl[c] != rawrepl) reduce = false;
1767 } else {
1768 for (std::size_t c : callers)
1769 if (lqn.fanout_at(c, idx) < rawrepl) reduce = false;
1770 }
1771 nreplicas = reduce ? 1 : static_cast<std::size_t>(std::llround(rawrepl));
1772 if (reduce && !ishostlayer) single_replica_tasks.insert(idx);
1773 }
1774 const bool reduce_fanout = (nreplicas == 1 && rawrepl > 1.0 && !callers.empty());
1775 const std::vector<double>& mult = lqn.maxmult;
1776
1777 // A client Delay exists unless the layer is a task layer reached only
1778 // by asynchronous callers, which this port refuses upstream.
1779 m.clientIdx = m.add_station(qn::Station<T>{"Clients", NodeType::Delay, SchedStrategy::INF,
1780 std::numeric_limits<double>::infinity(), false, 0});
1781 const std::size_t clientNode = m.node_of_station(m.clientIdx);
1782 m.serverIdx = m.clientIdx + 1;
1783 // One station (times its replicas) per SERVED ELEMENT of this layer.
1784 // Under `srvn` that is one element and `srv[idx] == server`; under
1785 // `flat` every processor and called task of the model is here.
1786 std::vector<std::vector<std::size_t>> srv(lqn.nidx + 1);
1787 std::vector<std::vector<std::size_t>> srvnode(lqn.nidx + 1);
1788 m.server_idx_of.assign(lqn.nidx + 1, 0);
1789 for (std::size_t sidx : idxSet) {
1790 const bool sishost = sidx <= lqn.nhosts;
1791 srv[sidx].resize(nreplicas);
1792 for (std::size_t r = 0; r < nreplicas; ++r) {
1793 qn::Station<T> st;
1794 st.name = r == 0 ? lqn.hashnames[sidx]
1795 : lqn.hashnames[sidx] + "." + std::to_string(r + 1);
1796 // inf-scheduled Queue as Delay node rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_ln.h)
1797 st.nodetype =
1798 lqn.sched[sidx] == SchedStrategy::INF ? NodeType::Delay : NodeType::Queue;
1799 st.sched = lqn.sched[sidx];
1800 // setNumberOfServers no-op rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_ln.h)
1801 st.nservers = lqn.sched[sidx] == SchedStrategy::INF
1802 ? std::numeric_limits<double>::infinity()
1803 : mult[sidx];
1804 st.attr_ishost = flat ? sishost : ishostlayer;
1805 st.attr_idx = sidx;
1806 srv[sidx][r] = m.add_station(st);
1807 srvnode[sidx].push_back(m.node_of_station(srv[sidx][r]));
1808 }
1809 m.server_idx_of[sidx] = srv[sidx][0];
1810 if (sishost)
1811 m.host_stations.push_back(srv[sidx][0]);
1812 else
1813 m.task_stations.push_back(srv[sidx][0]);
1814 }
1815 // the layer's own server, the sole server under `srvn`
1816 const std::vector<std::size_t>& server = srv[idx];
1817 const std::vector<std::size_t>& serverNode = srvnode[idx];
1818
1819 /** Stations of ELEM when it is served in this layer, empty otherwise. */
1820 auto servers_for = [&](std::size_t elem) -> const std::vector<std::size_t>& {
1821 static const std::vector<std::size_t> none;
1822 if (elem >= 1 && elem <= lqn.nidx && !srv[elem].empty()) return srv[elem];
1823 return none;
1824 };
1825 auto server_nodes_for = [&](std::size_t elem) -> const std::vector<std::size_t>& {
1826 static const std::vector<std::size_t> none;
1827 if (elem >= 1 && elem <= lqn.nidx && !srvnode[elem].empty()) return srvnode[elem];
1828 return none;
1829 };
1830 /** True when the processor of task TIDX is a server of this layer. */
1831 auto host_is_server = [&](std::size_t tidx_) {
1832 return !servers_for(lqn.parent[tidx_]).empty();
1833 };
1834 /** True when TIDX calls an entry served by this layer. */
1835 auto is_layer_client = [&](std::size_t tidx_) {
1836 for (std::size_t s : idxSet)
1837 for (std::size_t e : lqn.entriesof[s])
1838 if (lqn.issynccaller.get(tidx_, e)) return true;
1839 return false;
1840 };
1841 /** Declare a class at every server station of this layer. */
1842 auto set_all_servers = [&](std::size_t cl, const Distrib<T>& d) {
1843 for (std::size_t s : idxSet)
1844 for (std::size_t st : srv[s]) m.set_service(st, cl, d);
1845 };
1846
1847 // Routed call groups, resolved from target ENTRIES to the call indices
1848 // that reach them: a group is ONE dispatch with n destinations, so its
1849 // members share a call class and a dispatch class that holds the job at
1850 // the client while the target is picked (callGroupsByCidx in
1851 // buildLayersRecursive.m).
1852 std::vector<std::size_t> group_of_call(lqn.ncalls + 1, 0);
1853 std::vector<std::vector<std::size_t>> group_members(lqn.callgroups.size() + 1);
1854 for (std::size_t g = 0; g < lqn.callgroups.size(); ++g) {
1855 const LqnCallGroup& grp = lqn.callgroups[g];
1856 for (std::size_t tgt : grp.targets)
1857 for (std::size_t cidx : lqn.callsof[grp.caller])
1858 if (lqn.callpair_dst[cidx] == tgt && lqn.calltype[cidx] == CallType::SYNC &&
1859 group_of_call[cidx] == 0) {
1860 group_of_call[cidx] = g + 1;
1861 group_members[g + 1].push_back(cidx);
1862 break;
1863 }
1864 }
1865 // per group: the Router node, the dispatch class and the group class
1866 std::vector<std::size_t> grp_router(lqn.callgroups.size() + 1, 0);
1867 std::vector<std::size_t> grp_dispatch(lqn.callgroups.size() + 1, 0);
1868 std::vector<std::size_t> grp_class(lqn.callgroups.size() + 1, 0);
1869 // (router node, dispatch class, group) triples whose strategy is
1870 // installed once the routing is written
1871 std::vector<std::array<std::size_t, 3>> routed_group_sites;
1872
1873 // Fork/Router/Join construction rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_ln.h)
1874 std::vector<std::size_t> acts_in_caller;
1875 for (std::size_t c : callers)
1876 for (std::size_t a : lqn.actsof[c]) acts_in_caller.push_back(a);
1877 bool hasfork = false, hasjoin = false;
1878 std::size_t maxfanout = 1;
1879 for (std::size_t a : acts_in_caller) {
1880 if (lqn.actposttype[a] == PrecedenceType::POST_AND) hasfork = true;
1881 if (lqn.actpretype[a] == PrecedenceType::PRE_AND) hasjoin = true;
1882 std::size_t nand = 0;
1883 for (std::size_t sx : lqn.graph.succ(a))
1884 if (lqn.actposttype[sx] == PrecedenceType::POST_AND) ++nand;
1885 if (nand > maxfanout) maxfanout = nand;
1886 }
1887 std::size_t forkNode = 0, joinNode = 0, joinStation = 0;
1888 std::vector<std::size_t> forkRouter;
1889 if (hasfork) {
1890 forkNode = m.add_node("Fork_PostAnd", NodeType::Fork, false);
1891 for (std::size_t f = 1; f <= maxfanout; ++f)
1892 forkRouter.push_back(
1893 m.add_node("Fork_PostAnd_" + std::to_string(f), NodeType::Router, true));
1894 }
1895 if (hasjoin) {
1896 qn::Station<T> js;
1897 js.name = "Join_PreAnd";
1898 js.nodetype = NodeType::Join;
1899 js.sched = SchedStrategy::INF;
1900 js.nservers = std::numeric_limits<double>::infinity();
1901 js.attr_ishost = false;
1902 js.attr_idx = 0;
1903 joinStation = m.add_station(js);
1904 joinNode = m.node_of_station(joinStation);
1905 if (forkNode) m.fj.emplace_back(forkNode, joinNode);
1906 }
1907 // A CACHE LAYER is a HOST layer all of whose callers are cache tasks,
1908 // buildLayersRecursive.m:88. The Cache node lives here and not in the
1909 // cache task's own layer: the item lookup is what the task DOES on its
1910 // processor, so the hit and miss branches have to queue at the same
1911 // server the read arrived at.
1912 bool iscachelayer = !flat && ishostlayer && !callers.empty();
1913 for (std::size_t c : callers)
1914 if (!lqn.iscache[c]) iscachelayer = false;
1915 // A SETUP NO LONGER CHANGES HOW A LAYER IS BUILT (buildLayersRecursive.m,
1916 // 2026-08-11). Wiring the setup/delay-off onto the server station routed
1917 // the layer through the open M/G/1-with-setup QBD, which reads the idle
1918 // period off the Poisson rate 1/X and so powers the thread down far more
1919 // often than a CLOSED layer does -- 12.67% below LDES on lqn_setup -- and
1920 // it charged the restart to the ACTIVITY, where it is not host demand.
1921 // The cold start is charged to the ENTRY instead, with the probability
1922 // that the thread was really found down: see setup_charge().
1923 std::size_t cacheNode = 0;
1924 qn::CacheParam<T> cachepar;
1925 if (iscachelayer) {
1926 const std::size_t ct = callers[0];
1927 cachepar.nitems = lqn.nitems[ct];
1928 cachepar.itemcap = lqn.itemcap[ct];
1929 cachepar.replacestrat = lqn.replacestrat[ct];
1930 cacheNode = m.add_node(lqn.hashnames[ct], NodeType::Cache, true);
1931 }
1932
1933 // The open streams this layer carries, decided BEFORE the Source is
1934 // added: m.serverIdx is the client index plus one and replica r is
1935 // m.serverIdx + r, so a station inserted between them would silently
1936 // renumber the servers. Source and Sink therefore come last.
1937 // An async call is declared only in the layer whose server owns the
1938 // called entry, which is serversFor(parent(dst)) in the reference
1939 // (buildLayersRecursive.m:327) and the same test route_sync_call uses.
1940 std::vector<std::size_t> async_here;
1941 for (std::size_t c : callers)
1942 for (std::size_t aidx : lqn.actsof[c])
1943 for (std::size_t cidx : lqn.callsof[aidx])
1944 if (lqn.calltype[cidx] == CallType::ASYNC &&
1945 !servers_for(lqn.parent[lqn.callpair_dst[cidx]]).empty())
1946 async_here.push_back(cidx);
1947 std::vector<std::size_t> open_entries;
1948 for (std::size_t c : callers) {
1949 // An arrival that is the only way into the task is carried by the caller
1950 // CHAIN, not by a stream: that task has no task layer, so nothing ever sets
1951 // its surrogate delay, and a chain cycling against an Immediate one plus a
1952 // stream loads the host twice -- lqn_open_arrival's processor read 0.68
1953 // against 0.32 from lqns, lqsim and LDES. update_think_times closes the
1954 // chain on the known rate instead, as it does for a forwarding target.
1955 if (open_arrival_rate_of(c) > GlobalConstants::FineTol) continue;
1956 for (std::size_t eidx : lqn.entriesof[c])
1957 if (lqn.has_arrival[eidx]) open_entries.push_back(eidx);
1958 }
1959
1960 std::size_t sourceStation = 0, sourceNode = 0, sinkNode = 0;
1961 if (!async_here.empty() || !open_entries.empty()) {
1962 qn::Station<T> src;
1963 src.name = "Source";
1964 src.nodetype = NodeType::Source;
1965 // EXT keeps solver_mva out of both infSET and qSET: the Source is lambda, not a queue
1966 src.sched = SchedStrategy::EXT;
1967 src.nservers = 1.0;
1968 src.attr_ishost = false;
1969 src.attr_idx = 0;
1970 sourceStation = m.add_station(src);
1971 sourceNode = m.node_of_station(sourceStation);
1972 sinkNode = m.add_node("Sink", NodeType::Sink, false);
1973 m.sourceIdx = sourceStation;
1974 m.sinkNode = sinkNode;
1975 }
1976
1977 /** The stack of entry classes at the forks currently open. */
1978 std::vector<std::size_t> forkClassStack;
1979
1980 // class index of each LQN element and each call, 0 when absent
1981 std::vector<std::size_t> cls(lqn.nidx + 1, 0);
1982 std::vector<std::size_t> callcls(lqn.ncalls + 1, 0);
1983 // `<call>.Aux`, present only for a call whose mean count differs from the
1984 // replica count; 0 elsewhere. See the routing in route_sync_call.
1985 std::vector<std::size_t> auxcallcls(lqn.ncalls + 1, 0);
1986
1987 // A caller carries a closed class when its own PROCESSOR is served here
1988 // and something drives it (it is a reference task, is called, is a
1989 // forwarding target or takes an arrival), or when it calls an entry
1990 // served here. Under `srvn` the first disjunct is exactly the host
1991 // layer and the second exactly the task layer, so this reduces to the
1992 // two-branch test it replaces (buildLayersRecursive.m:217).
1993 auto caller_needs_class = [&](std::size_t tidx_caller) {
1994 if (host_is_server(tidx_caller)) {
1995 if (lqn.isref[tidx_caller]) return true;
1996 for (std::size_t e : lqn.entriesof[tidx_caller])
1997 if (lqn.issynccaller.any_col(e) || lqn.isasynccaller.any_col(e) ||
1998 is_fwd_target(e) || lqn.has_arrival[e])
1999 return true;
2000 }
2001 return is_layer_client(tidx_caller);
2002 };
2003 auto caller_acts_visible = [&](std::size_t tidx_caller) {
2004 return host_is_server(tidx_caller) || is_layer_client(tidx_caller);
2005 };
2006 /**
2007 * The population caller TIDX_ contributes to this layer WITHOUT a
2008 * refpath merge, including the infinite-server fallbacks. Shared by the
2009 * first pass, which also records it in njobs, and by resolve_ref_path,
2010 * which compares it against the chain population before any class exists.
2011 */
2012 auto caller_pool = [&](std::size_t tidx_) -> double {
2013 // representative-replica scaling rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_ln.h)
2014 const bool single_replica = reduce_fanout || single_replica_tasks.count(tidx_) > 0;
2015 if (ishostlayer && !single_replica && lqn.repl[tidx_] > 1.0)
2016 host_all_replica_tasks[tidx_] = nreplicas;
2017 if (njobs(tidx_, idx) != 0.0) return njobs(tidx_, idx);
2018 double nj = single_replica ? mult[tidx_] : mult[tidx_] * lqn.repl[tidx_];
2019 if (std::isinf(nj)) {
2020 double s = 0.0;
2021 for (std::size_t c = 1; c <= NT(); ++c)
2022 if (lqn.taskgraph.get(c, tidx_) != Tzero()) s += mult[c];
2023 nj = s;
2024 if (std::isinf(nj)) {
2025 double s2 = 0.0;
2026 for (std::size_t c = 1; c <= NT(); ++c)
2027 if (std::isfinite(mult[c])) s2 += mult[c] * lqn.repl[c];
2028 nj = std::min(s2, 1000.0);
2029 }
2030 }
2031 return nj;
2032 };
2033
2034 // ---- reference-path interlocking (interlock_method = 'refpath') -------
2035 // This layer's client is then not one population per caller but ONE
2036 // chain running from the reference task down through every caller it
2037 // reaches, so two callers that are the same REF customers arriving by
2038 // two routes stop being counted as two. The tables say which callers are
2039 // merged (rp_spliced), which sync calls stop being a surrogate delay and
2040 // become an explicit descent (rp_expand), and which entries above or
2041 // between the callers become hop stages on the client Delay (rp_hop).
2042 // See lqn_ref_routes and _kb/06-solver-catalog.md (LN section).
2043 bool rp_on = false;
2044 std::vector<bool> rp_member(lqn.nidx + 1, false); // task: a caller merged into a chain
2045 std::vector<bool> rp_spliced(lqn.nidx + 1, false); // task: merged AND not the chain head
2046 std::vector<bool> rp_hop(lqn.nidx + 1, false); // entry: a stage of the path
2047 std::vector<bool> rp_expand(lqn.ncalls + 1, false); // call: re-expanded, not a delay
2048 std::vector<std::size_t> rp_child_task(lqn.ncalls + 1, 0); // callee task, when a member
2049 std::vector<std::size_t> rp_child_entry(lqn.ncalls + 1, 0); // callee entry, when a hop
2050 std::vector<T> rp_ret_share(lqn.ncalls + 1, Tzero()); // share of the callee's return
2051 std::vector<T> rp_call_mean(lqn.ncalls + 1, Tzero()); // invocations per execution
2052 std::vector<std::vector<std::size_t>> rp_hop_children(lqn.nidx + 1); // descent order
2053 std::vector<double> rp_hop_seed(lqn.nidx + 1, 0.0); // build-time stage mean
2054 std::vector<std::vector<std::size_t>> rp_member_inbound(lqn.nidx + 1);
2055 std::vector<std::vector<std::size_t>> rp_hop_inbound(lqn.nidx + 1);
2056 std::vector<std::vector<std::size_t>> rp_group_roots;
2057 std::vector<std::size_t> rp_group_reftask;
2058 std::vector<bool> rp_group_head_is_caller;
2059 // classes minted for the path, 0 when absent
2060 std::vector<std::size_t> rp_ref_stage;
2061 std::vector<std::size_t> rp_hop_cls(lqn.nidx + 1, 0), rp_hop_ret(lqn.nidx + 1, 0),
2062 rp_ret_cls(lqn.nidx + 1, 0);
2063 std::vector<std::size_t> rp_gate(lqn.ncalls + 1, 0), rp_aux(lqn.ncalls + 1, 0),
2064 rp_resume(lqn.ncalls + 1, 0);
2065
2066 /** Build-time seed of a hop stage: the entry's own host demand. */
2067 auto host_demand_of_entry = [&](std::size_t eidx_) {
2068 double d = 0.0;
2069 for (std::size_t a_ : lqn.actsof[eidx_]) {
2070 if (lqn.hostdem[a_].disabled) continue;
2071 const double m_ = dbl(lqn.hostdem[a_].mean);
2072 if (std::isfinite(m_)) d += m_;
2073 }
2074 return d;
2075 };
2076 const auto in_idxset = [&](std::size_t t_) {
2077 return std::find(idxSet.begin(), idxSet.end(), t_) != idxSet.end();
2078 };
2079
2080 // Port of resolveRefPath: a pure query over lqn plus the layer's own
2081 // server set, run before any class exists because the first pass needs
2082 // the answer to size the caller populations.
2083 [&]() {
2084 if (interlockMethod != "refpath" || flat || iscachelayer || hasfork || hasjoin) return;
2085 // a Fork flattens every positive alpha in the visit solve; a replicated
2086 // element carries a per-replica njobs convention a shared chain breaks
2087 if (reduce_fanout || nreplicas > 1) return;
2088 for (std::size_t t_ : callers)
2089 if (lqn.repl[t_] > 1.0 || single_replica_tasks.count(t_) > 0) return;
2090 const lqn::LqnRefRoutes<T> R =
2091 lqn::lqn_ref_routes(lqn, callers, opt.interlock_maxpaths, idxSet);
2092 if (!R.why.empty()) {
2093 // named, because the discontinuity is otherwise invisible
2094 std::cerr << "[LINE] Warning: layer '" << lqn.hashnames[idx]
2095 << "' falls back to the 'ilrate' interlock method: " << R.why
2096 << ".\n";
2097 return;
2098 }
2099 std::vector<std::size_t> keep;
2100 for (std::size_t g_ = 0; g_ < R.groups.size(); ++g_) {
2101 const lqn::LqnRefGroup<T>& G = R.groups[g_];
2102 bool wanted = G.members.size() >= 2;
2103 // a lone caller below a reference task: no merge, but the path
2104 // above it becomes explicit instead of a fitted idle time
2105 if (!wanted && opt.interlock_refpath_scope == "all" && !G.head_is_caller &&
2106 !G.members.empty())
2107 wanted = true;
2108 if (!wanted) continue;
2109 // The merge only pays when the chain population it installs is
2110 // STRICTLY below the caller pools it replaces; otherwise the
2111 // group stays on 'ilrate' (17-external-interlock).
2112 double pool = 0.0;
2113 for (std::size_t t_ : G.members) pool += caller_pool(t_);
2114 const double chainPop = mult[G.reftask] * lqn.repl[G.reftask];
2115 if (!(pool > chainPop)) continue;
2116 keep.push_back(g_);
2117 }
2118 if (keep.empty()) return;
2119 // Stage the whole decision, then commit: a refusal found on the
2120 // second group must not leave the first one half-applied.
2121 std::vector<bool> sMember(lqn.nidx + 1, false), sSpliced(lqn.nidx + 1, false),
2122 sHop(lqn.nidx + 1, false), sExpand(lqn.ncalls + 1, false);
2123 std::vector<std::size_t> sChildTask(lqn.ncalls + 1, 0),
2124 sChildEntry(lqn.ncalls + 1, 0);
2125 std::vector<T> sRetShare(lqn.ncalls + 1, Tzero()), sCallMean(lqn.ncalls + 1, Tzero());
2126 std::vector<std::vector<std::size_t>> sHopChildren(lqn.nidx + 1),
2127 sMemberInbound(lqn.nidx + 1), sHopInbound(lqn.nidx + 1);
2128 std::vector<double> sHopSeed(lqn.nidx + 1, 0.0);
2129 std::vector<std::vector<std::size_t>> sRoots;
2130 std::vector<std::size_t> sRefTask;
2131 std::vector<bool> sHeadIsCaller;
2132 for (std::size_t g_ : keep) {
2133 const lqn::LqnRefGroup<T>& G = R.groups[g_];
2134 const std::size_t nE = G.entries.size();
2135 // does this DAG node lead to a caller? reverse topological order
2136 std::vector<bool> leads(G.ismember.begin(), G.ismember.end());
2137 for (std::size_t i_ = nE; i_-- > 0;)
2138 for (const lqn::LqnRefCall<T>& c_ : G.calls)
2139 if (c_.from == i_ && leads[c_.to]) leads[i_] = true;
2140 for (std::size_t t_ : G.members)
2141 if (!caller_needs_class(t_)) return; // no client class to enter
2142 if (G.head_is_caller && !caller_needs_class(G.reftask)) return;
2143 // an infinite reference pool has no chain population
2144 if (!G.head_is_caller && !std::isfinite(lqn.maxmult[G.reftask])) return;
2145 for (std::size_t i_ = 0; i_ < nE; ++i_) {
2146 if (!leads[i_] || G.ismember[i_]) continue;
2147 // a hop served by this layer's own station would be in two places
2148 if (in_idxset(G.etask[i_]) || lqn.repl[G.etask[i_]] > 1.0) return;
2149 }
2150 for (const lqn::LqnRefCall<T>& c_ : G.calls) {
2151 if (!leads[c_.to]) continue;
2152 if (in_idxset(G.etask[c_.to])) return; // callee served by this layer
2153 }
2154 // commit this group into the staging tables
2155 const std::size_t head = G.reftask;
2156 for (std::size_t t_ : G.members) {
2157 sMember[t_] = true;
2158 sSpliced[t_] = !(G.head_is_caller && t_ == head);
2159 }
2160 std::vector<T> inTotMember(lqn.nidx + 1, Tzero()), inTotHop(lqn.nidx + 1, Tzero());
2161 for (const lqn::LqnRefCall<T>& c_ : G.calls) {
2162 if (!leads[c_.to]) continue;
2163 const std::size_t cidx_ = c_.cidx;
2164 const std::size_t fromEidx = G.entries[c_.from];
2165 sExpand[cidx_] = true;
2166 sCallMean[cidx_] = lqn.callproc_mean[cidx_];
2167 sHopChildren[fromEidx].push_back(cidx_);
2168 if (G.ismember[c_.to]) {
2169 const std::size_t tv = G.etask[c_.to];
2170 sChildTask[cidx_] = tv;
2171 sMemberInbound[tv].push_back(cidx_);
2172 inTotMember[tv] = T(inTotMember[tv] + c_.vcall);
2173 } else {
2174 const std::size_t ev = G.entries[c_.to];
2175 sChildEntry[cidx_] = ev;
2176 sHopInbound[ev].push_back(cidx_);
2177 inTotHop[ev] = T(inTotHop[ev] + c_.vcall);
2178 }
2179 sRetShare[cidx_] = c_.vcall; // normalised below
2180 }
2181 for (const lqn::LqnRefCall<T>& c_ : G.calls) {
2182 const std::size_t cidx_ = c_.cidx;
2183 if (!sExpand[cidx_]) continue;
2184 const T tot = sChildTask[cidx_] > 0 ? inTotMember[sChildTask[cidx_]]
2185 : inTotHop[sChildEntry[cidx_]];
2186 sRetShare[cidx_] = dbl(tot) > GlobalConstants::FineTol
2187 ? T(sRetShare[cidx_] / tot)
2188 : Tzero();
2189 }
2190 for (std::size_t i_ = 0; i_ < nE; ++i_)
2191 if (leads[i_] && !G.ismember[i_]) {
2192 const std::size_t ev = G.entries[i_];
2193 sHop[ev] = true;
2194 sHopSeed[ev] = host_demand_of_entry(ev);
2195 }
2196 if (!G.head_is_caller) {
2197 // EVERY entry of the reference task becomes a stage, not only
2198 // those reaching this layer, or the 1/nentries split would
2199 // shrink its denominator and over-drive the chain
2200 for (std::size_t ev : lqn.entriesof[G.reftask])
2201 if (!sHop[ev]) {
2202 sHop[ev] = true;
2203 sHopSeed[ev] = host_demand_of_entry(ev);
2204 }
2205 }
2206 sRoots.push_back(lqn.entriesof[head]);
2207 sRefTask.push_back(head);
2208 sHeadIsCaller.push_back(G.head_is_caller);
2209 }
2210 rp_member = sMember;
2211 rp_spliced = sSpliced;
2212 rp_hop = sHop;
2213 rp_expand = sExpand;
2214 rp_child_task = sChildTask;
2215 rp_child_entry = sChildEntry;
2216 rp_ret_share = sRetShare;
2217 rp_call_mean = sCallMean;
2218 rp_hop_children = sHopChildren;
2219 rp_hop_seed = sHopSeed;
2220 rp_member_inbound = sMemberInbound;
2221 rp_hop_inbound = sHopInbound;
2222 rp_group_roots = sRoots;
2223 rp_group_reftask = sRefTask;
2224 rp_group_head_is_caller = sHeadIsCaller;
2225 rp_on = true;
2226 }();
2227
2228 // ---- first pass: create the classes --------------------------------
2229 for (std::size_t tidx_caller : callers) {
2230 if (caller_needs_class(tidx_caller)) {
2231 double nj = njobs(tidx_caller, idx);
2232 if (nj == 0.0) {
2233 nj = caller_pool(tidx_caller);
2234 njobs(tidx_caller, idx) = nj;
2235 }
2236 // A caller merged into a reference chain brings NO population of
2237 // its own: the customers are the reference task's. Only the CLASS
2238 // is zeroed; njobs still records the pool for update_think_times.
2239 const bool rp_spliced_here = rp_on && rp_spliced[tidx_caller];
2240 qn::JobClass jc;
2241 jc.name = lqn.hashnames[tidx_caller];
2242 jc.type = JobClassType::CLOSED;
2243 jc.population = rp_spliced_here ? 0.0 : nj;
2244 jc.refstat = m.clientIdx;
2245 jc.completes = false;
2246 // ONE reference class per chain: a merged caller yields it to the
2247 // chain head and is normalised through layer_normclass instead
2248 jc.is_ref_class = !rp_spliced_here;
2249 jc.attr_kind = int(LqnElement::TASK);
2250 jc.attr_idx = tidx_caller;
2251 cls[tidx_caller] = m.add_class(jc);
2252 m.attr_tasks.emplace_back(cls[tidx_caller], tidx_caller);
2253 if (lqn.isref[tidx_caller]) {
2254 m.set_service(m.clientIdx, cls[tidx_caller], thinkproc[tidx_caller]);
2255 } else if (rp_spliced_here) {
2256 // the path above this caller is explicit now, so there is no
2257 // idle time left to fit and no update-map row to refresh it
2258 m.set_service(m.clientIdx, cls[tidx_caller], Distrib<T>::immediate());
2259 } else {
2260 // a served task's declared think time is not a per-request
2261 // delay, so the seed carries none either; update_think_times
2262 // replaces this from the first iteration on
2263 m.set_service(m.clientIdx, cls[tidx_caller], Distrib<T>::immediate());
2264 thinkt_map.push_back({idx, tidx_caller, m.clientIdx, cls[tidx_caller]});
2265 }
2266
2267 for (std::size_t eidx : lqn.entriesof[tidx_caller]) {
2268 qn::JobClass ec;
2269 ec.name = lqn.hashnames[eidx];
2270 ec.type = JobClassType::CLOSED;
2271 ec.population = 0.0;
2272 ec.refstat = m.clientIdx;
2273 ec.completes = false;
2274 ec.attr_kind = int(LqnElement::ENTRY);
2275 ec.attr_idx = eidx;
2276 cls[eidx] = m.add_class(ec);
2277 m.attr_entries.emplace_back(cls[eidx], eidx);
2278 m.set_service(m.clientIdx, cls[eidx], Distrib<T>::immediate());
2279 }
2280 }
2281
2282 for (std::size_t aidx : lqn.actsof[tidx_caller]) {
2283 if (caller_acts_visible(tidx_caller)) {
2284 qn::JobClass ac;
2285 ac.name = lqn.hashnames[aidx];
2286 ac.type = JobClassType::CLOSED;
2287 ac.population = 0.0;
2288 ac.refstat = m.clientIdx;
2289 ac.completes = false;
2290 ac.attr_kind = int(LqnElement::ACTIVITY);
2291 ac.attr_idx = aidx;
2292 cls[aidx] = m.add_class(ac);
2293 m.attr_activities.emplace_back(cls[aidx], aidx);
2294 // The host demand is served at the processor's own station
2295 // when this layer holds it; everywhere else the activity is
2296 // a surrogate delay at the client.
2297 const std::size_t hidx = lqn.parent[lqn.parent[aidx]];
2298 if (servers_for(hidx).empty())
2299 m.set_service(m.clientIdx, cls[aidx], servtproc[aidx]);
2300 }
2301 for (std::size_t cidx : lqn.callsof[aidx]) {
2302 if (lqn.calltype[cidx] == CallType::ASYNC) {
2303 // An async call is a stream, not a visit: the caller does
2304 // not block, so it carries no closed class and instead
2305 // drives an open chain of its own out of the Source.
2306 const std::size_t adst = lqn.parent[lqn.callpair_dst[cidx]];
2307 if (servers_for(adst).empty()) continue;
2308 qn::JobClass oc;
2309 oc.name = lqn.callhashnames[cidx];
2310 oc.type = JobClassType::OPEN;
2311 oc.population = std::numeric_limits<double>::infinity();
2312 oc.refstat = sourceStation;
2313 oc.completes = false;
2314 oc.is_ref_class = false;
2315 oc.attr_kind = int(LqnElement::CALL);
2316 oc.attr_idx = cidx;
2317 callcls[cidx] = m.add_class(oc);
2318 m.attr_calls.push_back({callcls[cidx], cidx, lqn.callpair_src[cidx],
2319 lqn.callpair_dst[cidx]});
2320 // A NEGLIGIBLE seed, not the reference's Immediate. The
2321 // rate is replaced from the caller's throughput on the
2322 // first post(), but apply_sink_closure weights the
2323 // Sink->Source arcs by it in between, and Immediate is
2324 // rate 1/0: the closed classes sharing the closure then
2325 // get NaN visits. fj_mmt seeds its own open classes the
2326 // same way, for the same reason.
2327 m.set_service(sourceStation, callcls[cidx],
2329 num_traits<T>::from_double(GlobalConstants::FineTol)));
2330 T minRespTA = Tzero();
2331 for (std::size_t ta : lqn.actsof[adst]) minRespTA += lqn.hostdem[ta].mean;
2332 for (std::size_t st : servers_for(adst)) {
2333 m.set_service(st, callcls[cidx], Distrib<T>::exp_mean(minRespTA));
2334 call_map.push_back({idx, cidx, st, callcls[cidx]});
2335 }
2336 arv_call_map.push_back({idx, cidx, sourceStation, callcls[cidx]});
2337 continue;
2338 }
2339 if (lqn.calltype[cidx] != CallType::SYNC) continue;
2340 const std::size_t gid = group_of_call[cidx];
2341 if (gid != 0) {
2342 // ONE dispatch with n destinations. The members SHARE the
2343 // dispatch class, which is both the class the strategy
2344 // routes and the class that visits the targets: the hop
2345 // must not switch class, because a state-dependent
2346 // routing function is evaluated at zero off the class
2347 // diagonal. The class switch goes on the return arc
2348 // instead, into a group class the job continues in.
2349 if (grp_dispatch[gid] == 0) {
2350 // The strategy is a property of a NODE and routes
2351 // over that node's links, not over one class's arcs,
2352 // so a dedicated Router whose only links are the
2353 // group's targets is the only place where the choice
2354 // is exactly the group's.
2355 const std::string tag =
2356 lqn.hashnames[aidx] + ".Dispatch" + std::to_string(gid);
2357 grp_router[gid] = m.add_node(tag + ".Router", NodeType::Router, true);
2358 qn::JobClass dc;
2359 dc.name = tag;
2360 dc.type = JobClassType::CLOSED;
2361 dc.population = 0.0;
2362 dc.refstat = m.clientIdx;
2363 dc.completes = false;
2364 dc.attr_kind = int(LqnElement::CALL);
2365 dc.attr_idx = cidx;
2366 grp_dispatch[gid] = m.add_class(dc);
2367 m.set_service(m.clientIdx, grp_dispatch[gid], Distrib<T>::immediate());
2368 qn::JobClass gc;
2369 gc.name = lqn.callhashnames[cidx] + ".Group" + std::to_string(gid);
2370 gc.type = JobClassType::CLOSED;
2371 gc.population = 0.0;
2372 gc.refstat = m.clientIdx;
2373 gc.completes = false;
2374 gc.attr_kind = int(LqnElement::CALL);
2375 gc.attr_idx = cidx;
2376 grp_class[gid] = m.add_class(gc);
2377 m.set_service(m.clientIdx, grp_class[gid], Distrib<T>::immediate());
2378 routed_group_sites.push_back(
2379 {grp_router[gid], grp_dispatch[gid], gid});
2380 }
2381 callcls[cidx] = grp_dispatch[gid];
2382 m.attr_calls.push_back({callcls[cidx], cidx, lqn.callpair_src[cidx],
2383 lqn.callpair_dst[cidx]});
2384 for (std::size_t st2 : servers_for(lqn.parent[lqn.callpair_dst[cidx]]))
2385 m.set_service(st2, callcls[cidx], callservtproc[cidx]);
2386 continue;
2387 }
2388 qn::JobClass cc;
2389 cc.name = lqn.callhashnames[cidx];
2390 cc.type = JobClassType::CLOSED;
2391 cc.population = 0.0;
2392 cc.refstat = m.clientIdx;
2393 cc.completes = false;
2394 cc.attr_kind = int(LqnElement::CALL);
2395 cc.attr_idx = cidx;
2396 callcls[cidx] = m.add_class(cc);
2397 m.attr_calls.push_back({callcls[cidx], cidx, lqn.callpair_src[cidx],
2398 lqn.callpair_dst[cidx]});
2399 // An upper bound on the server's response, replaced at the
2400 // first iteration by the measured one. The station seeded is
2401 // the CALLEE's under `flat` and the layer's own under
2402 // `srvn`, where the latter also seeds calls that leave the
2403 // layer -- a phantom rate on a class with no visits here,
2404 // kept because removing it moves the fixed point (see
2405 // seedCallService in buildLayersRecursive.m).
2406 const std::size_t seedidx = flat ? lqn.parent[lqn.callpair_dst[cidx]] : idx;
2407 T minRespT = Tzero();
2408 for (std::size_t ta : lqn.actsof[seedidx]) minRespT += lqn.hostdem[ta].mean;
2409 for (std::size_t st : servers_for(seedidx))
2410 m.set_service(st, callcls[cidx], Distrib<T>::exp_mean(minRespT));
2411 // .Aux class rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_ln.h)
2412 if (lqn.callproc_mean[cidx] !=
2413 num_traits<T>::from_double(double(nreplicas))) {
2414 qn::JobClass xc;
2415 xc.name = lqn.callhashnames[cidx] + ".Aux";
2416 xc.type = JobClassType::CLOSED;
2417 xc.population = 0.0;
2418 xc.refstat = m.clientIdx;
2419 xc.completes = false;
2420 xc.attr_kind = int(LqnElement::CALL);
2421 xc.attr_idx = cidx;
2422 auxcallcls[cidx] = m.add_class(xc);
2423 m.set_service(m.clientIdx, auxcallcls[cidx], Distrib<T>::immediate());
2424 }
2425 }
2426 }
2427 }
2428
2429 // ---- reference-path classes (buildRefPathClasses) ------------------
2430 // Minted with the caller classes. A descent issued from a caller's own
2431 // activity graph REUSES the call classes that already exist as its gate
2432 // and its geometric auxiliary: fresh ones would leave those two with no
2433 // inbound arc at all.
2434 auto rp_class = [&](const std::string& nm, double pop, std::size_t attr) {
2435 qn::JobClass rc;
2436 rc.name = nm;
2437 rc.type = JobClassType::CLOSED;
2438 rc.population = pop;
2439 rc.refstat = m.clientIdx;
2440 rc.completes = false;
2441 rc.is_ref_class = false;
2442 rc.attr_kind = -1;
2443 rc.attr_idx = attr;
2444 const std::size_t k_ = m.add_class(rc);
2445 m.set_service(m.clientIdx, k_, Distrib<T>::immediate());
2446 return k_;
2447 };
2448 if (rp_on) {
2449 for (std::size_t g_ = 0; g_ < rp_group_reftask.size(); ++g_) {
2450 if (rp_group_head_is_caller[g_]) {
2451 rp_ref_stage.push_back(0); // the caller class IS the head
2452 continue;
2453 }
2454 const std::size_t rt = rp_group_reftask[g_];
2455 const std::size_t k_ =
2456 rp_class(lqn.hashnames[rt] + ".RefPath", mult[rt] * lqn.repl[rt], rt);
2457 m.classes[k_ - 1].is_ref_class = true;
2458 m.set_service(m.clientIdx, k_, thinkproc[rt]);
2459 rp_ref_stage.push_back(k_);
2460 }
2461 for (std::size_t ev = 1; ev <= lqn.nidx; ++ev) {
2462 if (!rp_hop[ev]) continue;
2463 const std::size_t k_ = rp_class(lqn.hashnames[ev] + ".RefHop", 0.0, ev);
2464 if (rp_hop_seed[ev] > GlobalConstants::FineTol)
2465 m.set_service(m.clientIdx, k_,
2466 Distrib<T>::exp_mean(num_traits<T>::from_double(rp_hop_seed[ev])));
2467 rp_hop_cls[ev] = k_;
2468 // the entry's own residence, MINUS the descents re-expanded below
2469 // it, PLUS the wait its task's threads queue for
2470 refpath_map.push_back({idx, m.clientIdx, k_, 1, ev, 1.0, 0});
2471 for (std::size_t c_ : rp_hop_children[ev])
2472 refpath_map.push_back({idx, m.clientIdx, k_, 2, c_, -1.0, ev});
2473 refpath_map.push_back({idx, m.clientIdx, k_, 3, lqn.parent[ev], 1.0, 0});
2474 rp_hop_ret[ev] = rp_class(lqn.hashnames[ev] + ".RefHopRet", 0.0, ev);
2475 }
2476 for (std::size_t tv = 1; tv <= lqn.nidx; ++tv)
2477 if (rp_spliced[tv]) rp_ret_cls[tv] = rp_class(lqn.hashnames[tv] + ".RefRet", 0.0, tv);
2478 for (std::size_t cidx_ = 1; cidx_ <= lqn.ncalls; ++cidx_) {
2479 if (!rp_expand[cidx_]) continue;
2480 if (callcls[cidx_] != 0) {
2481 rp_gate[cidx_] = callcls[cidx_];
2482 m.set_service(m.clientIdx, rp_gate[cidx_], Distrib<T>::immediate());
2483 if (auxcallcls[cidx_] != 0) rp_aux[cidx_] = auxcallcls[cidx_];
2484 } else {
2485 rp_gate[cidx_] = rp_class(lqn.callhashnames[cidx_] + ".RefGate", 0.0, cidx_);
2486 if (rp_call_mean[cidx_] != Tone())
2487 rp_aux[cidx_] =
2488 rp_class(lqn.callhashnames[cidx_] + ".RefGate.Aux", 0.0, cidx_);
2489 }
2490 // A MEMBER entered through this gate has its subgraph explicit
2491 // here; the one cost it does not show is the wait for one of its
2492 // own threads, which lives in its own task layer.
2493 if (rp_child_task[cidx_] > 0)
2494 refpath_map.push_back(
2495 {idx, m.clientIdx, rp_gate[cidx_], 3, rp_child_task[cidx_], 1.0, 0});
2496 rp_resume[cidx_] = rp_class(lqn.callhashnames[cidx_] + ".RefResume", 0.0, cidx_);
2497 }
2498 }
2499
2500 // ---- second pass: routing out of the entries -------------------------
2501 struct Ctx {
2502 std::size_t curclass;
2503 int jobpos; // 1 = at the client, 2 = at a server replica, 3 = at the Cache
2504 // The nodes the job stands at when jobpos is atServer. Under `srvn`
2505 // these are always the layer's own server replicas; under `flat`
2506 // they are whichever element's stations the last hop landed on, so
2507 // the position has to be carried rather than assumed.
2508 std::vector<std::size_t> curnodes;
2509 };
2510 const int atClient = 1, atServer = 2, atCache = 3;
2511 std::vector<int> jobposkey(lqn.nidx + 1, atClient);
2512 std::vector<std::size_t> curclasskey(lqn.nidx + 1, 0);
2513 std::vector<std::vector<std::size_t>> curnodeskey(lqn.nidx + 1);
2514
2515 // Port of routeRefPathDescent: one explicit descent into the callee of
2516 // CIDX_, replacing the surrogate delay that would charge its whole
2517 // residence at the client. The multiplicity is a geometric loop per
2518 // edge, never one flat loop of the product, and the m < 1 branch is not
2519 // optional: 1 - 1/m goes negative below one.
2520 auto rp_descent = [&](std::size_t cidx_, Ctx st) -> Ctx {
2521 const std::size_t gate = rp_gate[cidx_], res = rp_resume[cidx_], aux = rp_aux[cidx_];
2522 const T m_ = rp_call_mean[cidx_];
2523 const std::size_t enter = rp_child_task[cidx_] > 0 ? cls[rp_child_task[cidx_]]
2524 : rp_hop_cls[rp_child_entry[cidx_]];
2525 if (st.jobpos == atClient)
2526 m.set_route(st.curclass, gate, clientNode, clientNode, Tone());
2527 else
2528 for (std::size_t nd : st.curnodes) m.set_route(st.curclass, gate, nd, clientNode, Tone());
2529 std::size_t cont;
2530 if (m_ == Tone()) {
2531 m.set_route(gate, enter, clientNode, clientNode, Tone());
2532 cont = res;
2533 } else if (m_ > Tone()) {
2534 m.set_route(gate, enter, clientNode, clientNode, Tone());
2535 m.set_route(res, enter, clientNode, clientNode, T(Tone() - Tone() / m_));
2536 m.set_route(res, aux, clientNode, clientNode, T(Tone() / m_));
2537 cont = aux;
2538 } else {
2539 m.set_route(gate, enter, clientNode, clientNode, m_);
2540 m.set_route(gate, aux, clientNode, clientNode, T(Tone() - m_));
2541 m.set_route(res, aux, clientNode, clientNode, Tone());
2542 cont = aux;
2543 }
2544 st.jobpos = atClient;
2545 st.curnodes.clear();
2546 st.curclass = cont;
2547 return st;
2548 };
2549
2550 std::function<Ctx(std::size_t, std::size_t, Ctx)> recur =
2551 [&](std::size_t tidx_caller, std::size_t aidx, Ctx st) -> Ctx {
2552 jobposkey[aidx] = st.jobpos;
2553 curclasskey[aidx] = st.curclass;
2554 curnodeskey[aidx] = st.curnodes;
2555 const std::vector<std::size_t> nexts = lqn.graph.succ(aidx);
2556 std::size_t lastEntryClass = st.curclass;
2557 // fork pre-state save/restore rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_ln.h)
2558 bool next_is_fork = false;
2559 for (std::size_t sx : nexts)
2560 if (lqn.actposttype[sx] == PrecedenceType::POST_AND) next_is_fork = true;
2561 const Ctx preFork = st;
2562 std::vector<std::size_t> andSuccs;
2563 for (std::size_t sx : nexts)
2564 if (lqn.actposttype[sx] == PrecedenceType::POST_AND) andSuccs.push_back(sx);
2565
2566 for (std::size_t k = 0; k < nexts.size(); ++k) {
2567 const std::size_t nextaidx = nexts[k];
2568 if (next_is_fork) st = preFork;
2569 bool isLoop = lqn.graph.get(aidx, nextaidx) != lqn.dag.get(aidx, nextaidx);
2570 if (lqn.parent[aidx] != lqn.parent[nextaidx]) {
2571 // a call to an entry of another task
2572 std::size_t cidx = 0;
2573 for (std::size_t c : lqn.callsof[aidx])
2574 if (lqn.callpair_dst[c] == nextaidx) cidx = c;
2575 if (cidx == 0) continue;
2576 // FWD lays down no routing: its work is already carried by the pseudo SYNC arc
2577 if (lqn.calltype[cidx] != CallType::SYNC) continue;
2578 const std::size_t gid = group_of_call[cidx];
2579 if (gid != 0) {
2580 // The whole group is routed once, at its FIRST member;
2581 // the others are the same dispatch and lay down nothing.
2582 if (group_members[gid].empty() || group_members[gid][0] != cidx) continue;
2583 // The job is switched into the dispatch class while still
2584 // at the client, so (client, dispatch) carries exactly
2585 // the n arcs the strategy chooses among. The 1/n split
2586 // laid down here is the probabilistic reading a solver
2587 // without state-dependent routing would see; the
2588 // declared strategy replaces it below.
2589 std::vector<std::size_t> tnode2, tstat2, tcall2;
2590 for (std::size_t mc : group_members[gid]) {
2591 const std::size_t tt = lqn.parent[lqn.callpair_dst[mc]];
2592 if (servers_for(tt).empty()) continue;
2593 tnode2.push_back(server_nodes_for(tt)[0]);
2594 tstat2.push_back(servers_for(tt)[0]);
2595 tcall2.push_back(mc);
2596 }
2597 if (tnode2.size() < 2) continue; // not enough of it is here
2598 const std::size_t fromNode2 =
2599 st.jobpos == atClient ? clientNode : st.curnodes[0];
2600 const std::size_t dc = grp_dispatch[gid], gc = grp_class[gid];
2601 m.set_route(st.curclass, dc, fromNode2, grp_router[gid], Tone());
2602 const T share2 =
2603 T(Tone() / num_traits<T>::from_int(int(tnode2.size())));
2604 for (std::size_t d = 0; d < tnode2.size(); ++d) {
2605 m.set_route(dc, dc, grp_router[gid], tnode2[d], share2);
2606 m.set_route(dc, gc, tnode2[d], clientNode, Tone());
2607 m.set_service(tstat2[d], dc, callservtproc[tcall2[d]]);
2608 call_map.push_back({idx, tcall2[d], tstat2[d], dc});
2609 }
2610 st.curclass = gc;
2611 st.jobpos = atClient;
2612 st.curnodes.clear();
2613 continue;
2614 }
2615 if (rp_on && rp_expand[cidx]) {
2616 // the callee is on the reference path into this layer: the
2617 // customer descends into it rather than waiting a delay out
2618 st = rp_descent(cidx, st);
2619 continue;
2620 }
2621 const std::size_t ctgt = lqn.parent[lqn.callpair_dst[cidx]];
2622 st = route_sync_call(m, idx, cidx, st, server_nodes_for(ctgt),
2623 servers_for(ctgt), callcls, auxcallcls, clientNode,
2624 atClient, atServer, flat);
2625 continue;
2626 }
2627 // a successor inside the same task
2628 bool any_entry_succ = false;
2629 for (std::size_t sx : nexts)
2630 if (sx > lqn.eshift && sx <= lqn.eshift + lqn.nentries) any_entry_succ = true;
2631 if (!any_entry_succ) {
2632 st.jobpos = jobposkey[aidx];
2633 st.curclass = curclasskey[aidx];
2634 st.curnodes = curnodeskey[aidx];
2635 } else {
2636 if (k > 0 && nexts[k - 1] > lqn.eshift && nexts[k - 1] <= lqn.eshift + lqn.nentries)
2637 lastEntryClass = st.curclass;
2638 st.jobpos = atClient;
2639 st.curclass = lastEntryClass;
2640 st.curnodes.clear();
2641 }
2642 const T w = lqn.graph.get(aidx, nextaidx);
2643
2644 // THE CACHE READ, buildLayersRecursive.m:743-765. `aidx` is the
2645 // item entry and `nextaidx` the activity bound to it: the job
2646 // goes from the client to the Cache node, which decides the hit
2647 // or the miss and switches the class accordingly, so the read
2648 // class itself is never served anywhere and the branch classes
2649 // pick the work up at the server.
2650 if (iscachelayer && lqn.nitems[aidx] > 0 && cls[nextaidx] != 0) {
2651 const std::size_t readcls = cls[nextaidx];
2652 m.set_route(st.curclass, readcls, clientNode, cacheNode, w);
2653 if (cachepar.pread.size() < m.classes.size())
2654 cachepar.pread.resize(m.classes.size());
2655 cachepar.pread[readcls - 1] = lqn.itemproc[aidx];
2656 const std::vector<std::size_t> hm = lqn.graph.succ(nextaidx);
2657 if (hm.size() != 2)
2658 throw InputError("SolverLN: the cache read '" + lqn.names[nextaidx] +
2659 "' needs exactly one hit and one miss successor");
2660 if (cachepar.hitclass.size() < m.classes.size()) {
2661 cachepar.hitclass.resize(m.classes.size(), 0);
2662 cachepar.missclass.resize(m.classes.size(), 0);
2663 }
2664 cachepar.hitclass[readcls - 1] = cls[hm[0]];
2665 cachepar.missclass[readcls - 1] = cls[hm[1]];
2666 st.jobpos = atCache;
2667 st.curclass = readcls;
2668 st.curnodes.clear();
2669 st = recur(tidx_caller, nextaidx, st);
2670 continue;
2671 }
2672
2673 const bool is_and_join_tail = lqn.actpretype[aidx] == PrecedenceType::PRE_AND;
2674 // the branch index of this successor among the fork's outputs
2675 std::size_t fbranch = 0;
2676 if (next_is_fork)
2677 for (std::size_t q = 0; q < andSuccs.size(); ++q)
2678 if (andSuccs[q] == nextaidx) fbranch = q + 1;
2679
2680 // Where the successor's HOST DEMAND is served: at the station of
2681 // its own processor when this layer holds it, at the client
2682 // otherwise. Under `srvn` that is the host layer's own server
2683 // and nothing else, so this reduces to the `ishostlayer` test
2684 // it replaces.
2685 const std::size_t hidxOf = lqn.parent[lqn.parent[nextaidx]];
2686 const std::vector<std::size_t>& actStations = servers_for(hidxOf);
2687 const std::vector<std::size_t>& actNodes = server_nodes_for(hidxOf);
2688 const bool actAtServer = !actStations.empty();
2689 const std::size_t from = st.jobpos == atClient ? clientNode
2690 : st.jobpos == atCache ? cacheNode
2691 : st.curnodes[0];
2692 // the node a job continues to after this successor is served
2693 // Routes INTO the replica stations share the probability among them,
2694 // as the reference's routing does (BUG-110); a route from replica r
2695 // to replica r is not split.
2696 const T split = actAtServer ? T(Tone() / num_traits<T>::from_double(double(nreplicas)))
2697 : Tone();
2698 const bool oneToOne = st.jobpos != atClient && st.jobpos != atCache &&
2699 st.curnodes.size() == nreplicas;
2700 for (std::size_t r = 0; r < nreplicas; ++r) {
2701 const std::size_t fromNode =
2702 st.jobpos == atClient ? clientNode
2703 : st.jobpos == atCache ? cacheNode
2704 : st.curnodes[std::min(r, st.curnodes.size() - 1)];
2705 const std::size_t toNode = actAtServer ? actNodes[r] : clientNode;
2706 if (next_is_fork && fbranch > 0) {
2707 m.set_route(st.curclass, st.curclass, fromNode, forkNode, Tone());
2708 if (r == 0) forkClassStack.push_back(st.curclass);
2709 m.set_route(st.curclass, st.curclass, forkNode, forkRouter[fbranch - 1],
2710 Tone());
2711 m.set_route(st.curclass, cls[nextaidx], forkRouter[fbranch - 1], toNode,
2712 T(Tone() * split));
2713 } else if (is_and_join_tail) {
2714 // rejoin the class the branch was forked from, then
2715 // leave the Join in the successor's class
2716 if (forkClassStack.empty())
2717 throw InputError("SolverLN: an AND join has no matching fork in '" +
2718 lqn.names[aidx] + "'");
2719 const std::size_t forkClass = forkClassStack.back();
2720 if (r + 1 == nreplicas) forkClassStack.pop_back();
2721 m.set_route(st.curclass, forkClass, fromNode, joinNode, Tone());
2722 m.set_route(forkClass, cls[nextaidx], joinNode, toNode, T(Tone() * split));
2723 } else {
2724 // replica r stays on replica r; a job arriving from one node
2725 // spreads over the replicas (BUG-110)
2726 m.set_route(st.curclass, cls[nextaidx], fromNode, toNode,
2727 oneToOne ? w : T(w * split));
2728 }
2729 if (actAtServer)
2730 m.set_service(actStations[r], cls[nextaidx], lqn.hostdem[nextaidx]);
2731 }
2732 (void)from;
2733 if (actAtServer) {
2734 st.jobpos = atServer;
2735 st.curclass = cls[nextaidx];
2736 st.curnodes = actNodes;
2737 servt_map.push_back({idx, nextaidx, actStations[0], cls[nextaidx]});
2738 } else {
2739 st.jobpos = atClient;
2740 st.curclass = cls[nextaidx];
2741 st.curnodes.clear();
2742 m.set_service(m.clientIdx, cls[nextaidx], servtproc[nextaidx]);
2743 thinkt_map.push_back({idx, nextaidx, m.clientIdx, cls[nextaidx]});
2744 }
2745 if (aidx != nextaidx && !isLoop) {
2746 st = recur(tidx_caller, nextaidx, st);
2747 // close the branch with a reply back to the caller's class; a
2748 // merged caller replies to its OWN return class instead, which
2749 // hands the customer back to whichever descent invoked it
2750 const std::size_t reply =
2751 (rp_on && rp_spliced[tidx_caller]) ? rp_ret_cls[tidx_caller]
2752 : cls[tidx_caller];
2753 if (st.jobpos == atClient) {
2754 m.set_route(st.curclass, reply, clientNode, clientNode, Tone());
2755 } else {
2756 for (std::size_t nd : st.curnodes)
2757 m.set_route(st.curclass, reply, nd, clientNode, Tone());
2758 }
2759 // .Aux completion-guard rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_ln.h)
2760 if (!is_aux_class(m.classes[st.curclass - 1].name))
2761 m.classes[st.curclass - 1].completes = true;
2762 }
2763 }
2764 return st;
2765 };
2766
2767 for (std::size_t tidx_caller : callers) {
2768 if (!caller_needs_class(tidx_caller)) continue;
2769 const std::vector<std::size_t>& ents = lqn.entriesof[tidx_caller];
2770 const T share = T(Tone() / num_traits<T>::from_int(int(ents.size())));
2771 for (std::size_t eidx : ents) {
2772 m.set_route(cls[tidx_caller], cls[eidx], clientNode, clientNode, share);
2773 if (ents.size() > 1)
2774 route_map.push_back({idx, tidx_caller, eidx, m.clientIdx, m.clientIdx,
2775 cls[tidx_caller], cls[eidx]});
2776 Ctx st{cls[eidx], atClient, {}};
2777 recur(tidx_caller, eidx, st);
2778 }
2779 }
2780
2781 // ---- reference-path arcs no activity graph of this layer writes ------
2782 // routeRefPath: the reference stage, the hop stages and every callee's
2783 // return split.
2784 if (rp_on) {
2785 for (std::size_t g_ = 0; g_ < rp_group_reftask.size(); ++g_) {
2786 if (rp_group_head_is_caller[g_]) continue; // its own graph carries the descent
2787 std::vector<std::size_t> roots;
2788 for (std::size_t r_ : rp_group_roots[g_])
2789 if (rp_hop[r_]) roots.push_back(r_);
2790 if (roots.empty()) continue;
2791 // the REF task picks among its entries: a PROBABILISTIC split
2792 const T share = T(Tone() / num_traits<T>::from_int(int(roots.size())));
2793 for (std::size_t r_ : roots) {
2794 m.set_route(rp_ref_stage[g_], rp_hop_cls[r_], clientNode, clientNode, share);
2795 m.set_route(rp_hop_ret[r_], rp_ref_stage[g_], clientNode, clientNode, Tone());
2796 }
2797 }
2798 // the descents below a hop are a SERIES: one cycle traverses all of them
2799 for (std::size_t ev = 1; ev <= lqn.nidx; ++ev) {
2800 if (!rp_hop[ev]) continue;
2801 Ctx cur{rp_hop_cls[ev], atClient, {}};
2802 for (std::size_t c_ : rp_hop_children[ev]) cur = rp_descent(c_, cur);
2803 m.set_route(cur.curclass, rp_hop_ret[ev], clientNode, clientNode, Tone());
2804 }
2805 // Return arcs, split by the share of the callee's invocations each
2806 // descent contributes: v(p_i)*m_i, exact rather than a heuristic.
2807 for (std::size_t tv = 1; tv <= lqn.nidx; ++tv) {
2808 if (!rp_spliced[tv]) continue;
2809 for (std::size_t c_ : rp_member_inbound[tv])
2810 if (rp_ret_share[c_] > Tzero())
2811 m.set_route(rp_ret_cls[tv], rp_resume[c_], clientNode, clientNode,
2812 rp_ret_share[c_]);
2813 }
2814 for (std::size_t ev = 1; ev <= lqn.nidx; ++ev) {
2815 if (!rp_hop[ev]) continue;
2816 for (std::size_t c_ : rp_hop_inbound[ev])
2817 if (rp_ret_share[c_] > Tzero())
2818 m.set_route(rp_hop_ret[ev], rp_resume[c_], clientNode, clientNode,
2819 rp_ret_share[c_]);
2820 }
2821 }
2822
2823 // ---- open streams, laid down AFTER the activity-graph walk ----------
2824 // buildLayersRecursive.m:473 puts the entry-arrival routing here for the
2825 // same reason: the walk above rewrites whole rows of P and would erase
2826 // an arc written before it. Both kinds route Source -> server -> Sink
2827 // within one class, so they never join a closed class in a chain --
2828 // refresh_chains would reject that, the two carrying different refstats.
2829 if (sourceStation != 0) {
2830 const T nrep = num_traits<T>::from_int(int(nreplicas));
2831 for (std::size_t cidx : async_here) {
2832 const std::size_t oc = callcls[cidx];
2833 if (oc == 0) continue;
2834 // the stream enters the CALLEE's station, which under `srvn` is
2835 // this layer's own server and under `flat` one among many
2836 const std::vector<std::size_t>& anode =
2837 server_nodes_for(lqn.parent[lqn.callpair_dst[cidx]]);
2838 const T callmean = lqn.callproc_mean[cidx];
2839 if (callmean < Tone()) {
2840 // fewer than one call per firing: a single Bernoulli pass
2841 m.set_route(oc, oc, sourceNode, sinkNode, T(Tone() - callmean));
2842 for (std::size_t r = 0; r < anode.size(); ++r) {
2843 m.set_route(oc, oc, sourceNode, anode[r], T(callmean / nrep));
2844 m.set_route(oc, oc, anode[r], sinkNode, Tone());
2845 }
2846 } else {
2847 // callmean visits in expectation, as a geometric self-loop
2848 const T p = T(Tone() / callmean);
2849 for (std::size_t r = 0; r < anode.size(); ++r) {
2850 m.set_route(oc, oc, sourceNode, anode[r], T(Tone() / nrep));
2851 for (std::size_t q = 0; q < anode.size(); ++q)
2852 m.set_route(oc, oc, anode[r], anode[q], T((Tone() - p) / nrep));
2853 m.set_route(oc, oc, anode[r], sinkNode, p);
2854 }
2855 }
2856 }
2857 for (std::size_t eidx : open_entries) {
2858 qn::JobClass eo;
2859 eo.name = lqn.hashnames[eidx] + "_Open";
2860 eo.type = JobClassType::OPEN;
2861 eo.population = std::numeric_limits<double>::infinity();
2862 eo.refstat = sourceStation;
2863 eo.completes = false;
2864 eo.is_ref_class = false;
2865 eo.attr_kind = int(LqnElement::ENTRY);
2866 eo.attr_idx = eidx;
2867 const std::size_t ec = m.add_class(eo);
2868 // the arrival is exogenous and fixed, so it is never reseeded
2869 m.set_service(sourceStation, ec, lqn.arrival[eidx]);
2870 // entries are Immediate; the work is the activity bound to them
2871 std::size_t bound = 0;
2872 for (std::size_t sx : lqn.graph.succ(eidx))
2873 if (bound == 0 && sx > lqn.ashift) bound = sx;
2874 const Distrib<T>& svc = bound != 0 ? servtproc[bound] : servtproc[eidx];
2875 // the arrival enters the processor of the entry's task under
2876 // host layering, and the task's own station under `flat`
2877 const std::vector<std::size_t>& ostat =
2878 flat ? servers_for(lqn.parent[eidx]) : server;
2879 const std::vector<std::size_t>& onode =
2880 flat ? server_nodes_for(lqn.parent[eidx]) : serverNode;
2881 for (std::size_t r = 0; r < ostat.size(); ++r) {
2882 m.set_service(ostat[r], ec, svc);
2883 m.set_route(ec, ec, sourceNode, onode[r], T(Tone() / nrep));
2884 m.set_route(ec, ec, onode[r], sinkNode, Tone());
2885 }
2886 }
2887 }
2888
2889 // ---- admission constraint on the server station ---------------------
2890 // buildLayersRecursive.m:596-625. The constraint is stated over LQN
2891 // elements and has to be re-expressed in the layer's own classes: a
2892 // task occupies its host through the classes of its ACTIVITIES, an
2893 // entry is occupied by the classes of the CALLS that target it. The
2894 // columns are summed into the class, never assigned, because several
2895 // classes can stand for one column.
2896 // Rows of the admission constraint, in the layer's own classes: the
2897 // declared lincon first, then the refpath pool rows.
2898 std::vector<std::vector<T>> Arows;
2899 std::vector<T> brows;
2900 if (idx < lqn.lincon_A.size() && lqn.lincon_A[idx].rows() > 0) {
2901 const Matrix<T>& Aelem = lqn.lincon_A[idx];
2902 Matrix<T> Alayer(Aelem.rows(), m.classes.size(), Tzero());
2903 const std::vector<std::size_t>& constrained =
2904 ishostlayer ? lqn.tasksof[idx] : lqn.entriesof[idx];
2905 for (std::size_t j = 0; j < constrained.size() && j < Aelem.cols(); ++j) {
2906 std::vector<std::size_t> layerClasses;
2907 if (ishostlayer) {
2908 for (std::size_t a : lqn.actsof[constrained[j]])
2909 if (cls[a] != 0) layerClasses.push_back(cls[a]);
2910 } else {
2911 for (std::size_t c = 1; c <= lqn.ncalls; ++c)
2912 if (lqn.callpair_dst[c] == constrained[j] && callcls[c] != 0)
2913 layerClasses.push_back(callcls[c]);
2914 }
2915 for (std::size_t k = 0; k < layerClasses.size(); ++k)
2916 for (std::size_t rr = 0; rr < Aelem.rows(); ++rr)
2917 Alayer(rr, layerClasses[k] - 1) =
2918 T(Alayer(rr, layerClasses[k] - 1) + Aelem(rr, j));
2919 }
2920 for (std::size_t rr = 0; rr < Alayer.rows(); ++rr) {
2921 std::vector<T> row(m.classes.size(), Tzero());
2922 for (std::size_t k = 0; k < m.classes.size(); ++k) row[k] = Alayer(rr, k);
2923 Arows.push_back(row);
2924 brows.push_back(lqn.lincon_b[idx][rr]);
2925 }
2926 }
2927 // A merged caller no longer carries its thread pool as a population, so
2928 // the pool is declared as an admission bound on the server instead, BUT
2929 // ONLY WHEN THE LAYER SOLVER CAN HONOUR ONE. Under the default MVA layer
2930 // solver the pool's other carrier, the thread-acquisition wait charged
2931 // at every descent gate and hop stage, carries it alone; emitting the
2932 // region there anyway would change which engine solves the layer.
2933 if (rp_on && layer_solver_declares_region()) {
2934 std::vector<std::size_t> srvEntries;
2935 for (std::size_t sidx : idxSet)
2936 for (std::size_t e : lqn.entriesof[sidx]) srvEntries.push_back(e);
2937 for (std::size_t tv = 1; tv <= lqn.nidx; ++tv) {
2938 if (!rp_spliced[tv]) continue;
2939 const double cap = lqn.maxmult[tv];
2940 if (!std::isfinite(cap) || cap <= 0.0) continue;
2941 std::vector<T> row(m.classes.size(), Tzero());
2942 bool anyc = false;
2943 if (ishostlayer) {
2944 // a task occupies the host through the classes of its activities
2945 for (std::size_t a_ : lqn.actsof[tv])
2946 if (cls[a_] != 0) {
2947 row[cls[a_] - 1] = Tone();
2948 anyc = true;
2949 }
2950 } else {
2951 // a task occupies the server through the calls it makes into it
2952 for (std::size_t a_ : lqn.actsof[tv])
2953 for (std::size_t c_ : lqn.callsof[a_])
2954 if (std::find(srvEntries.begin(), srvEntries.end(),
2955 lqn.callpair_dst[c_]) != srvEntries.end() &&
2956 callcls[c_] != 0) {
2957 row[callcls[c_] - 1] = Tone();
2958 anyc = true;
2959 }
2960 }
2961 if (anyc) {
2962 Arows.push_back(row);
2963 brows.push_back(num_traits<T>::from_double(cap));
2964 }
2965 }
2966 }
2967 {
2968 bool any = false;
2969 for (const std::vector<T>& row : Arows)
2970 for (const T& v : row)
2971 if (v != Tzero()) any = true;
2972 if (any) {
2973 Matrix<T> Alayer(Arows.size(), m.classes.size(), Tzero());
2974 for (std::size_t rr = 0; rr < Arows.size(); ++rr)
2975 for (std::size_t k = 0; k < m.classes.size(); ++k) Alayer(rr, k) = Arows[rr][k];
2976 // ONE region over every replica, not one each: the constraint
2977 // models a passive resource of the server as a whole (a
2978 // semaphore, a connection pool), so the replicas share tokens.
2979 typename qn::NetworkStruct<T>::Region rg;
2980 const std::size_t M = m.stations.size(), K = m.classes.size();
2981 rg.cap.assign(M, std::vector<double>(K + 1, -1.0));
2982 rg.maxmem.assign(M, -1.0);
2983 rg.members.assign(M, false);
2984 rg.rule.assign(K, lang::DropStrategy::WAITQ);
2985 rg.weight.assign(K, Tone());
2986 rg.size.assign(K, Tone());
2987 for (std::size_t r = 0; r < nreplicas; ++r) rg.members[server[r] - 1] = true;
2988 rg.lincon_A = Alayer;
2989 rg.lincon_b = brows;
2990 m.regions.push_back(rg);
2991 }
2992 }
2993
2994 // The Cache node's parameters are only complete once the walk has seen
2995 // every read: pread, hitclass and missclass are all per READ CLASS, and
2996 // the classes are created as the activity graph is traversed.
2997 if (cacheNode != 0) {
2998 cachepar.pread.resize(m.classes.size());
2999 cachepar.hitclass.resize(m.classes.size(), 0);
3000 cachepar.missclass.resize(m.classes.size(), 0);
3001 m.nodeparam[cacheNode] = cachepar;
3002 }
3003
3004 // The declared dispatch replaces the probabilistic split on the router,
3005 // and ONLY on the (router, dispatch class) pair whose arcs are exactly
3006 // the group's targets. The split stays in P underneath, which is what
3007 // `refresh_routing` re-expands for anything that reads a matrix; the SSA
3008 // engine walks the arcs itself and honours the strategy.
3009 for (const std::array<std::size_t, 3>& site : routed_group_sites) {
3010 qn::NodeDef& nd = m.nodes[site[0] - 1];
3011 if (nd.routing.size() < m.classes.size())
3012 nd.routing.resize(m.classes.size(), RoutingStrategy::PROB);
3013 nd.routing[site[1] - 1] = lqn.callgroups[site[2] - 1].strategy;
3014 }
3015
3016 // ---- queue-dependent service rates on the server station ------------
3017 // buildLayersRecursive.m:700-762. Declared over the server's OPERANDS
3018 // (the tasks of a host, the entries of a task) and re-expressed in the
3019 // layer's own classes, on the same mapping the admission constraint
3020 // uses above. The handles are evaluated in two index spaces -- CTMC and
3021 // the exact recursions pass a per-class vector, the AMVA and NC chain
3022 // recursions a per-chain one -- so each carries both column lists and
3023 // picks by the length of what it is handed. The chain list is only known
3024 // after refresh_chains, hence the shared slot filled just below.
3025 std::vector<std::pair<std::shared_ptr<std::vector<std::vector<std::size_t>>>,
3026 std::vector<std::vector<std::size_t>>>> deferred_chaincols;
3027 for (std::size_t sidx : idxSet) {
3028 const bool hasld = sidx < lqn.lldscaling.size() && !lqn.lldscaling[sidx].empty();
3029 const bool hascd = sidx < lqn.cdscaling.size() && bool(lqn.cdscaling[sidx]);
3030 const bool hasjd = sidx < lqn.jdscaling.size() && bool(lqn.jdscaling[sidx]);
3031 const bool haspools = sidx < lqn.pools.size() && !lqn.pools[sidx].empty();
3032 if (!(hasld || hascd || hasjd || haspools)) continue;
3033 const bool sishost = sidx <= lqn.nhosts;
3034 const std::vector<std::size_t>& operandIdx =
3035 sishost ? lqn.tasksof[sidx] : lqn.entriesof[sidx];
3036 std::vector<std::vector<std::size_t>> cols(operandIdx.size());
3037 for (std::size_t j = 0; j < operandIdx.size(); ++j) {
3038 if (sishost) {
3039 for (std::size_t a : lqn.actsof[operandIdx[j]])
3040 if (cls[a] != 0) cols[j].push_back(cls[a] - 1);
3041 } else {
3042 for (std::size_t c = 1; c <= lqn.ncalls; ++c)
3043 if (lqn.callpair_dst[c] == operandIdx[j] && callcls[c] != 0)
3044 cols[j].push_back(callcls[c] - 1);
3045 }
3046 }
3047 const std::size_t R = m.classes.size();
3048 std::shared_ptr<std::vector<std::vector<std::size_t>>> chaincols =
3049 std::make_shared<std::vector<std::vector<std::size_t>>>();
3050 deferred_chaincols.push_back(std::make_pair(chaincols, cols));
3051 for (std::size_t r = 0; r < nreplicas; ++r) {
3052 // The scalings are written straight onto the Station, as the
3053 // region block above writes m.regions: a Layer is a
3054 // NetworkStruct, not the NetworkBuilder that carries the
3055 // set_*_dependence helpers.
3056 qn::Station<T>& stn = m.stations[srv[sidx][r] - 1];
3057 if (hasld) stn.lldscaling = lqn.lldscaling[sidx];
3058 if (hascd) {
3059 // beta_{i,r} is product form only while an operand maps to a
3060 // single class; where it aggregates several, the same
3061 // scaling is emitted as a joint dependence, numerically
3062 // identical but no longer exact.
3063 bool one_class_each = true;
3064 for (std::size_t j = 0; j < cols.size(); ++j)
3065 if (cols[j].size() > 1) one_class_each = false;
3066 const lang::CdScaling<T> h =
3067 layer_dep_handle(lqn.cdscaling[sidx], cols, chaincols, R);
3068 const std::vector<T> pk = layer_peak(lqn.cdscalingpeak[sidx], cols, R);
3069 if (one_class_each) {
3070 stn.cdscaling = h;
3071 stn.cdscalingpeak = pk;
3072 } else {
3073 stn.jdscaling = h;
3074 stn.jdscalingpeak = pk;
3075 }
3076 }
3077 if (hasjd) {
3078 stn.jdscaling = layer_dep_handle(lqn.jdscaling[sidx], cols, chaincols, R);
3079 stn.jdscalingpeak = layer_peak(lqn.jdscalingpeak[sidx], cols, R);
3080 }
3081 if (haspools) {
3082 // A compatibility declaration IS a rate law: the pools clear
3083 // the activated-server rate of api::sn_compat_rate, order
3084 // independent at every integer state. sn_compat_scaling
3085 // normalises it against the rate the SAME population would
3086 // get under full compatibility, so eta isolates the
3087 // compatibility GRAPH and a fully-compatible pool is the
3088 // neutral eta == 1; the low-occupancy loss stays with the
3089 // solver's own multiserver term.
3090 const lqn::ServerPools<T>& pl = lqn.pools[sidx];
3091 const Matrix<T> compat = pl.compat;
3092 const std::vector<double> counts = pl.counts;
3093 const std::vector<T> rates = pl.rates;
3094 lang::CdScaling<T> etaPool = [compat, counts,
3095 rates](const std::vector<T>& nop) {
3096 return std::vector<T>(
3097 1, api::sn_compat_scaling(compat, counts, rates, nop));
3098 };
3099 stn.jdscaling = layer_dep_handle(etaPool, cols, chaincols, R);
3100 stn.jdscalingpeak = layer_peak(
3101 std::vector<T>(cols.size(), num_traits<T>::from_int(1)), cols, R);
3102 }
3103 }
3104 }
3105
3106 if (rp_on) {
3107 // Per-class normalisation task, read by layer_refclass. A merged chain
3108 // holds more than one caller and only ONE reference class, so without
3109 // this every merged caller's residence would come out scaled by the
3110 // product of the call multiplicities along the path.
3111 std::vector<std::size_t> nc(m.classes.size(), 0);
3112 for (std::size_t tv = 1; tv <= lqn.nidx; ++tv) {
3113 if (!rp_member[tv] || cls[tv] == 0) continue;
3114 const std::size_t own = cls[tv];
3115 std::vector<std::size_t> owned{cls[tv]};
3116 for (std::size_t e_ : lqn.entriesof[tv]) owned.push_back(cls[e_]);
3117 for (std::size_t a_ : lqn.actsof[tv]) {
3118 owned.push_back(cls[a_]);
3119 for (std::size_t c_ : lqn.callsof[a_]) {
3120 owned.push_back(callcls[c_]);
3121 owned.push_back(auxcallcls[c_]);
3122 }
3123 }
3124 // an open class (an async call) has no chain reference rate of its own
3125 for (std::size_t q_ : owned)
3126 if (q_ != 0 && m.classes[q_ - 1].type == JobClassType::CLOSED) nc[q_ - 1] = own;
3127 }
3128 layer_normclass[idx] = nc;
3129 ref_path_audit(m, idx, callers, caller_needs_class, rp_spliced, rp_member, rp_hop,
3130 rp_expand, rp_group_head_is_caller, rp_ref_stage, rp_hop_cls,
3131 rp_hop_ret, rp_ret_cls, rp_gate, rp_aux, rp_resume, cls);
3132 }
3133
3134 // a priority-scheduling processor orders its callers by task priority
3135 apply_host_task_priorities(m, idxSet);
3136 m.refresh_chains();
3137 // The chain columns of every handle emitted above, now that the chains
3138 // exist. The slots are shared with the handles, so filling them here
3139 // reaches every replica without rebuilding a single lambda.
3140 for (std::size_t d = 0; d < deferred_chaincols.size(); ++d) {
3141 const std::vector<std::vector<std::size_t>>& cols = deferred_chaincols[d].second;
3142 std::vector<std::vector<std::size_t>>& out = *deferred_chaincols[d].first;
3143 out.assign(cols.size(), std::vector<std::size_t>());
3144 for (std::size_t j = 0; j < cols.size(); ++j) {
3145 for (std::size_t k = 0; k < cols[j].size(); ++k)
3146 for (std::size_t cc = 0; cc < m.chains.size(); ++cc)
3147 if (cols[j][k] < m.chains[cc].size() && m.chains[cc][cols[j][k]]) {
3148 bool seen = false;
3149 for (std::size_t q = 0; q < out[j].size(); ++q)
3150 if (out[j][q] == cc) seen = true;
3151 if (!seen) out[j].push_back(cc);
3152 }
3153 }
3154 }
3155 // A layer holding a POST_AND fork is a fork-join model like any other,
3156 // and the reference builds it as a `Network`, so buildLayers's
3157 // `getStruct()` runs the MMT node-visit pass on it: layer P:P2 of
3158 // lqn_workflows reports a Join visit of 4.3333, not the 1 the routing
3159 // solve leaves. THE LATER `refresh_chains()` CALLS DO NOT REPEAT IT, and
3160 // that is the reference's behaviour rather than an oversight here:
3161 // SolverLN.m re-runs `refreshChains()` alone after a routing reset,
3162 // which recomputes the visits WITHOUT the pass.
3164 }
3165
3166 /**
3167 * Port of layerSolverDeclaresRegion: true when the layer solver's feature
3168 * set covers an admission constraint. Asked while a layer is being built, so
3169 * it reads the solver CLASS's feature set, as the reference does: NC, FLD
3170 * and SSA declare Region, MVA does not.
3171 */
3172 bool layer_solver_declares_region() const {
3173 // SolverCTMC, SolverLDES and SolverJMT declare Region in the reference's feature set; SolverMAM does not.
3174 return opt.layer_solver == "nc" || opt.layer_solver == "fluid" || opt.layer_solver == "ssa" ||
3175 opt.layer_solver == "ctmc" || opt.layer_solver == "ldes" || opt.layer_solver == "jmt";
3176 }
3177
3178 /** True when the layer engine is a simulator, i.e. `isStochastic()` of the reference's layer solver. */
3179 bool layer_solver_is_stochastic() const {
3180 return opt.layer_solver == "ssa" || opt.layer_solver == "ldes" || opt.layer_solver == "jmt";
3181 }
3182
3183 /**
3184 * The seed SolverLN.pre gives stochastic layer e (0-based here) in Robbins-Monro mode:
3185 * `seed + (it-1)*nlayers + e`, with e 1-based there. `cur_it` is the outer iteration
3186 * analyze() is running; a solve outside the sweep (sensitivity, transient) reuses the last.
3187 */
3188 long layer_seed(long base, std::size_t e) const {
3189 const long it = cur_it > 0 ? cur_it : 1;
3190 return base + (it - 1) * static_cast<long>(ensemble.size()) + static_cast<long>(e) + 1 +
3191 sens_rep_offset();
3192 }
3193
3194 /** Seed offset k - 1 of the tuned sensitivity replication k, 0 outside it. */
3195 long sens_rep_offset() const {
3196 return sens_rep_k > 0 ? static_cast<long>(sens_rep_k) - 1 : 0;
3197 }
3198
3199 /** A layer's sample budget, split over the pairs of a tuned sensitivity sweep. */
3200 template <class S>
3201 S sens_rep_samples(S samples) const {
3202 if (sens_rep_k == 0 || sens_rep_n == 0) return samples;
3203 const double v = std::ceil(static_cast<double>(samples) / static_cast<double>(sens_rep_n));
3204 return static_cast<S>(v < 1.0 ? 1.0 : v);
3205 }
3206
3207 /**
3208 * Port of refPathAudit. Only the classes refpath wrote are checked: every
3209 * row they leave a node by must sum to one with no negative entry, and the
3210 * layer must carry exactly one reference class per chain it built, which is
3211 * what refresh_chains requires. Warnings, as in the reference.
3212 */
3213 template <class NeedsClass>
3214 void ref_path_audit(const qn::Layer<T>& m, std::size_t idx,
3215 const std::vector<std::size_t>& callers, const NeedsClass& needs_class,
3216 const std::vector<bool>& spliced, const std::vector<bool>& member,
3217 const std::vector<bool>& hop, const std::vector<bool>& expand,
3218 const std::vector<bool>& head_is_caller,
3219 const std::vector<std::size_t>& ref_stage,
3220 const std::vector<std::size_t>& hop_cls,
3221 const std::vector<std::size_t>& hop_ret,
3222 const std::vector<std::size_t>& ret_cls,
3223 const std::vector<std::size_t>& gate, const std::vector<std::size_t>& aux,
3224 const std::vector<std::size_t>& resume,
3225 const std::vector<std::size_t>& cls) const {
3226 std::set<std::size_t> watch;
3227 for (std::size_t k : ref_stage)
3228 if (k) watch.insert(k);
3229 for (std::size_t e = 1; e < hop.size(); ++e)
3230 if (hop[e]) {
3231 if (hop_cls[e]) watch.insert(hop_cls[e]);
3232 if (hop_ret[e]) watch.insert(hop_ret[e]);
3233 }
3234 for (std::size_t t = 1; t < member.size(); ++t)
3235 if (member[t]) {
3236 if (ret_cls[t]) watch.insert(ret_cls[t]);
3237 if (cls[t]) watch.insert(cls[t]);
3238 }
3239 for (std::size_t c = 1; c < expand.size(); ++c)
3240 if (expand[c]) {
3241 if (gate[c]) watch.insert(gate[c]);
3242 if (aux[c]) watch.insert(aux[c]);
3243 if (resume[c]) watch.insert(resume[c]);
3244 }
3245 const std::size_t I = m.nodes.size();
3246 for (std::size_t r : watch) {
3247 for (std::size_t n = 1; n <= I; ++n) {
3248 double tot = 0.0;
3249 bool neg = false;
3250 for (const auto& kv : m.P) {
3251 if (kv.first.first != r || n > kv.second.rows()) continue;
3252 for (std::size_t j = 0; j < kv.second.cols(); ++j) {
3253 const double v = dbl(kv.second(n - 1, j));
3254 if (v < -GlobalConstants::FineTol) neg = true;
3255 tot += v;
3256 }
3257 }
3258 if (neg)
3259 std::cerr << "[LINE] Warning: refpath layer '" << lqn.hashnames[idx]
3260 << "': class '" << m.classes[r - 1].name << "' routes out of node "
3261 << n << " with a negative probability.\n";
3262 if (tot > GlobalConstants::FineTol && std::fabs(tot - 1.0) > 1e-6)
3263 std::cerr << "[LINE] Warning: refpath layer '" << lqn.hashnames[idx]
3264 << "': class '" << m.classes[r - 1].name << "' leaves node " << n
3265 << " with total probability " << tot << ".\n";
3266 }
3267 }
3268 std::size_t nref = 0;
3269 for (const qn::JobClass& jc : m.classes)
3270 if (jc.is_ref_class) ++nref;
3271 std::size_t expect = 0;
3272 for (bool h : head_is_caller)
3273 if (!h) ++expect;
3274 for (std::size_t t : callers)
3275 if (!spliced[t] && needs_class(t)) ++expect;
3276 if (nref != expect)
3277 std::cerr << "[LINE] Warning: refpath layer '" << lqn.hashnames[idx] << "' declares "
3278 << nref << " reference classes where " << expect
3279 << " were built; a chain holding two makes refresh_chains throw.\n";
3280 }
3281
3282 /**
3283 * Port of routeSynchCall (buildLayersRecursive.m).
3284 *
3285 * A synchronous call is made `callmean` times per visit to the calling
3286 * activity, against `nreplicas` server replicas. The branch is chosen by
3287 * callmean ALONE, against 1 and never against nreplicas: a Bernoulli pass
3288 * carries at most one call, more than one needs the geometric loop through
3289 * the `<call>.Aux` class, and the replicas only SPLIT each probability by
3290 * ntgt -- they never relax that bound (buildLayersRecursive.m:1028-1051).
3291 * Comparing against nreplicas instead agrees with the reference only at
3292 * nreplicas == 1; on lqn_sockshop's replicated P2_1 it put a callmean of 1
3293 * on the < branch and doubled T1's throughput and P2_1's utilization.
3294 *
3295 * A second class is needed because a self-loop on the call class would also
3296 * re-enter its service. Which of the two carries the call time depends on
3297 * the direction:
3298 *
3299 * callmean < 1 the mean count is folded into the DEMAND
3300 * (callservt = callmean * W), so the call class must
3301 * be visited exactly once or the time is discounted
3302 * twice; .Aux absorbs the remaining branch.
3303 * callmean > 1 the call class is re-entered, and .Aux is the
3304 * return path that closes the loop with probability
3305 * 1/callmean, giving a mean of callmean visits.
3306 *
3307 * The four cases below are (job at client / at server) x (call targets an
3308 * entry of THIS layer's server / of some other task).
3309 */
3310 struct CtxPair {
3311 std::size_t curclass;
3312 int jobpos;
3313 };
3314
3315 /** The `<call>.Aux` suffix, which is how the reference identifies them too. */
3316 static bool is_aux_class(const std::string& name) {
3317 return name.size() >= 4 && name.compare(name.size() - 4, 4, ".Aux") == 0;
3318 }
3319 template <class Ctx>
3320 Ctx route_sync_call(qn::Layer<T>& m, std::size_t idx, std::size_t cidx, Ctx st,
3321 const std::vector<std::size_t>& tnode,
3322 const std::vector<std::size_t>& tstat,
3323 const std::vector<std::size_t>& callcls,
3324 const std::vector<std::size_t>& auxcallcls, std::size_t clientNode,
3325 int atClient, int atServer, bool flat) {
3326 const T one = Tone();
3327 // The callee's stations in THIS layer, empty when it is served
3328 // elsewhere: under `srvn` that is the layer's own server or nothing,
3329 // under `flat` it is whichever of the many servers the call targets.
3330 const std::size_t ntgt = tnode.size();
3331 const bool to_this_server = ntgt > 0;
3332 const T nrep = num_traits<T>::from_int(int(ntgt > 0 ? ntgt : 1));
3333 const T share = T(one / nrep);
3334 const T callmean = lqn.callproc_mean[cidx];
3335 const std::size_t cc = callcls[cidx];
3336 const std::size_t ax = auxcallcls[cidx];
3337 const bool below = callmean < one;
3338 const bool above = callmean > one;
3339 if (st.jobpos == atClient) {
3340 if (to_this_server) {
3341 if (below) {
3342 m.set_route(st.curclass, ax, clientNode, clientNode, T(one - callmean));
3343 for (std::size_t r = 0; r < ntgt; ++r) {
3344 m.set_route(st.curclass, cc, clientNode, tnode[r], T(callmean / nrep));
3345 m.set_route(cc, cc, tnode[r], clientNode, one);
3346 }
3347 // keeps .Aux attached to the routing graph; carries no time
3348 m.set_route(ax, cc, clientNode, clientNode, one);
3349 } else if (above) {
3350 for (std::size_t r = 0; r < ntgt; ++r) {
3351 m.set_route(st.curclass, cc, clientNode, tnode[r], share);
3352 m.set_route(cc, ax, tnode[r], clientNode, one);
3353 m.set_route(ax, cc, clientNode, tnode[r], T((one - one / callmean) / nrep));
3354 }
3355 m.set_route(ax, cc, clientNode, clientNode, T(one / callmean));
3356 } else {
3357 for (std::size_t r = 0; r < ntgt; ++r) {
3358 m.set_route(st.curclass, cc, clientNode, tnode[r], share);
3359 m.set_route(cc, cc, tnode[r], clientNode, one);
3360 }
3361 }
3362 for (std::size_t r = 0; r < ntgt; ++r) {
3363 m.set_service(tstat[r], cc, callservtproc[cidx]);
3364 call_map.push_back({idx, cidx, tstat[r], cc});
3365 }
3366 m.set_service(m.clientIdx, cc, Distrib<T>::immediate());
3367 st.jobpos = atClient;
3368 st.curnodes.clear();
3369 st.curclass = cc;
3370 } else {
3371 m.set_route(st.curclass, cc, clientNode, clientNode, one);
3372 if (below || above) {
3373 m.set_route(cc, ax, clientNode, clientNode, one);
3374 st.curclass = ax;
3375 } else {
3376 st.curclass = cc;
3377 }
3378 st.jobpos = atClient;
3379 st.curnodes.clear();
3380 m.set_service(m.clientIdx, cc, callservtproc[cidx]);
3381 call_map.push_back({idx, cidx, m.clientIdx, cc});
3382 }
3383 } else {
3384 // the node the job stands at, one per replica of wherever it landed
3385 auto fromNode = [&](std::size_t r) {
3386 return st.curnodes[std::min(r, st.curnodes.size() - 1)];
3387 };
3388 if (to_this_server) {
3389 if (below) {
3390 // The skip and the call merge back in the CALL class at the
3391 // client, exactly as in the atClient branch above. Routing
3392 // the skip into the call class instead and leaving in .Aux
3393 // gives .Aux no inbound arc at all, so its chain has no
3394 // reference class (buildLayersRecursive.m:1100-1118). This
3395 // port did that until 2026-08-11 and the arm is the same
3396 // under both layerings, as it is in the reference.
3397 for (std::size_t r = 0; r < ntgt; ++r) {
3398 m.set_route(st.curclass, ax, fromNode(r), clientNode, T(one - callmean));
3399 m.set_route(st.curclass, cc, fromNode(r), tnode[r], T(callmean / nrep));
3400 m.set_route(cc, cc, tnode[r], clientNode, one);
3401 }
3402 m.set_route(ax, cc, clientNode, clientNode, one);
3403 m.set_service(m.clientIdx, cc, Distrib<T>::immediate());
3404 st.jobpos = atClient;
3405 st.curnodes.clear();
3406 st.curclass = cc;
3407 } else if (above) {
3408 if (flat) {
3409 // the geometric repeat transits the client between
3410 // visits; a self-loop would merge them into one
3411 for (std::size_t r = 0; r < ntgt; ++r) {
3412 m.set_route(st.curclass, cc, fromNode(r), tnode[r], one);
3413 m.set_route(cc, ax, tnode[r], clientNode, one);
3414 m.set_route(ax, cc, clientNode, tnode[r],
3415 T((one - one / callmean) / nrep));
3416 }
3417 m.set_route(ax, cc, clientNode, clientNode, T(one / callmean));
3418 m.set_service(m.clientIdx, cc, Distrib<T>::immediate());
3419 st.curclass = cc;
3420 } else {
3421 for (std::size_t r = 0; r < ntgt; ++r) {
3422 m.set_route(st.curclass, cc, fromNode(r), tnode[r], one);
3423 m.set_route(cc, cc, tnode[r], tnode[r], T(one - one / callmean));
3424 m.set_route(cc, ax, tnode[r], clientNode, T(one / callmean));
3425 }
3426 st.curclass = ax;
3427 }
3428 st.jobpos = atClient;
3429 st.curnodes.clear();
3430 } else {
3431 for (std::size_t r = 0; r < ntgt; ++r)
3432 m.set_route(st.curclass, cc, fromNode(r), tnode[r], one);
3433 if (flat) {
3434 // the reply returns the job to the client, which is
3435 // where the successor restoration expects it
3436 for (std::size_t r = 0; r < ntgt; ++r)
3437 m.set_route(cc, cc, tnode[r], clientNode, one);
3438 m.set_service(m.clientIdx, cc, Distrib<T>::immediate());
3439 st.jobpos = atClient;
3440 st.curnodes.clear();
3441 } else {
3442 st.jobpos = atServer;
3443 st.curnodes = tnode;
3444 }
3445 st.curclass = cc;
3446 }
3447 for (std::size_t r = 0; r < ntgt; ++r) {
3448 m.set_service(tstat[r], cc, callservtproc[cidx]);
3449 call_map.push_back({idx, cidx, tstat[r], cc});
3450 }
3451 } else {
3452 for (std::size_t nd : st.curnodes)
3453 m.set_route(st.curclass, cc, nd, clientNode, one);
3454 if (below || above) {
3455 m.set_route(cc, ax, clientNode, clientNode, one);
3456 st.curclass = ax;
3457 } else {
3458 st.curclass = cc;
3459 }
3460 st.jobpos = atClient;
3461 st.curnodes.clear();
3462 m.set_service(m.clientIdx, cc, callservtproc[cidx]);
3463 call_map.push_back({idx, cidx, m.clientIdx, cc});
3464 }
3465 }
3466 return st;
3467 }
3468
3469 // -----------------------------------------------------------------------
3470 // getEntryServiceMatrix
3471 // -----------------------------------------------------------------------
3472
3473 /**
3474 * Reachability of activities and calls from each entry, as a 0/1 matrix over
3475 * the combined element-and-call index space. Multiplying it by
3476 * [residt; callresidt] sums an entry's whole service into one number.
3477 */
3478 void build_entry_service_matrix() {
3479 const std::size_t dim = lqn.nidx + lqn.ncalls;
3480 servtmatrix = Matrix<T>(dim + 1, dim + 1, Tzero());
3481 std::function<void(std::size_t, std::size_t)> rec = [&](std::size_t aidx, std::size_t eidx) {
3482 for (std::size_t nextaidx : lqn.graph.succ(aidx)) {
3483 const bool isLoop = lqn.graph.get(aidx, nextaidx) != lqn.dag.get(aidx, nextaidx);
3484 if (lqn.parent[aidx] != lqn.parent[nextaidx]) {
3485 for (std::size_t cidx : lqn.callsof[aidx])
3486 if (lqn.calltype[cidx] == CallType::SYNC)
3487 servtmatrix(eidx, lqn.nidx + cidx) = Tone();
3488 } else if (nextaidx != aidx && !isLoop) {
3489 servtmatrix(eidx, nextaidx) = Tone();
3490 rec(nextaidx, eidx);
3491 }
3492 }
3493 };
3494 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
3495 const std::size_t eidx = lqn.eshift + e;
3496 rec(eidx, eidx);
3497 }
3498 }
3499
3500 // -----------------------------------------------------------------------
3501 // initInterlock
3502 // -----------------------------------------------------------------------
3503
3504 /** Port of initInterlock: the LQNS V5 static interlock analysis. */
3505 /**
3506 * True when the interlock correction would act on this model: some server has
3507 * interlocked sources (il_num_sources > 0 with common parent entries). The tables
3508 * only read lqn, so they are built here when absent. Read by the 'srvn' alias:
3509 * srvn.ph builds no call classes and switches the correction off, which reported the
3510 * uncorrected answer on an interlocked model (10-interlock 0.2236 against lqns's
3511 * 0.25), so the alias takes srvn.cs there. Port of SolverLN.hasInterlock.
3512 */
3513 bool has_interlock() {
3514 if (!opt.interlocking) return false;
3515 if (il_num_sources.empty()) init_interlock();
3516 for (std::size_t s = 0; s < il_num_sources.size(); ++s)
3517 if (il_num_sources[s] > 0.0 && s < il_common_entries.size() &&
3518 !il_common_entries[s].empty())
3519 return true;
3520 return false;
3521 }
3522
3523 void init_interlock() {
3524 const std::size_t NE = lqn.nentries;
3525 il_all = Matrix<T>(NE + 1, NE + 1, Tzero());
3526 il_ph1 = Matrix<T>(NE + 1, NE + 1, Tzero());
3527
3528 std::function<void(std::size_t, std::size_t, T, T, std::vector<bool>&, int)> trace =
3529 [&](std::size_t eidx, std::size_t root_e, T pall, T pph1, std::vector<bool>& visited,
3530 int depth) {
3531 if (eidx <= lqn.eshift || eidx > lqn.eshift + NE) return;
3532 const std::size_t e = eidx - lqn.eshift;
3533 if (visited[e]) return;
3534 visited[e] = true;
3535 il_all(root_e, e) = T(il_all(root_e, e) + pall);
3536 il_ph1(root_e, e) = T(il_ph1(root_e, e) + pph1);
3537 for (std::size_t aidx : lqn.actsof[eidx]) {
3538 if (aidx <= lqn.ashift || aidx > lqn.ashift + lqn.nacts) continue;
3539 const std::size_t a = aidx - lqn.ashift;
3540 if (depth > 0 && lqn.actphase[a] > 1) continue;
3541 const bool is_ph1 = lqn.actphase[a] <= 1;
3542 for (std::size_t cidx : lqn.callsof[aidx]) {
3543 if (lqn.calltype[cidx] != CallType::SYNC) continue;
3544 if (!(lqn.callproc_mean[cidx] > Tzero())) continue;
3545 const std::size_t dst = lqn.callpair_dst[cidx];
3546 if (dst <= lqn.eshift || dst > lqn.eshift + NE) continue;
3547 trace(dst, root_e, T(pall * lqn.callproc_mean[cidx]),
3548 is_ph1 ? T(pph1 * lqn.callproc_mean[cidx]) : Tzero(), visited,
3549 depth + 1);
3550 }
3551 }
3552 visited[e] = false;
3553 };
3554 for (std::size_t e = 1; e <= NE; ++e) {
3555 std::vector<bool> visited(NE + 1, false);
3556 trace(lqn.eshift + e, e, Tone(), Tone(), visited, 0);
3557 }
3558
3559 il_common_entries.assign(NT() + 1, {});
3560 il_src_all.assign(NT() + 1, {});
3561 il_src_ph2.assign(NT() + 1, {});
3562 il_num_sources.assign(NT() + 1, 0.0);
3563
3564 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
3565 const std::size_t tidx = lqn.tshift + t;
3566 if (lqn.isref[tidx] || lqn.sched[tidx] == SchedStrategy::INF) continue;
3567 interlock_for_server(tidx);
3568 }
3569 for (std::size_t h = 1; h <= lqn.nhosts; ++h) {
3570 if (lqn.sched[h] == SchedStrategy::INF) continue;
3571 interlock_for_server(h);
3572 }
3573 }
3574
3575 std::vector<std::size_t> server_entry_nums(std::size_t serverIdx) const {
3576 std::vector<std::size_t> out;
3577 if (serverIdx <= lqn.nhosts) {
3578 for (std::size_t tidx : lqn.tasksof[serverIdx])
3579 for (std::size_t se : lqn.entriesof[tidx]) out.push_back(se - lqn.eshift);
3580 } else {
3581 for (std::size_t se : lqn.entriesof[serverIdx]) out.push_back(se - lqn.eshift);
3582 }
3583 return out;
3584 }
3585
3586 std::vector<std::size_t> client_tasks(std::size_t serverIdx) const {
3587 std::vector<std::size_t> out;
3588 if (serverIdx <= lqn.nhosts) return lqn.tasksof[serverIdx];
3589 for (std::size_t se : lqn.entriesof[serverIdx])
3590 for (std::size_t ci : lqn.iscaller.col(se))
3591 if (ci > lqn.tshift && ci <= NT()) out.push_back(ci);
3592 std::sort(out.begin(), out.end());
3593 out.erase(std::unique(out.begin(), out.end()), out.end());
3594 return out;
3595 }
3596
3597 std::vector<std::size_t> call_dst_tasks(std::size_t src_eidx, std::size_t target_e) const {
3598 std::vector<std::size_t> out;
3599 for (std::size_t aidx : lqn.actsof[src_eidx]) {
3600 if (aidx <= lqn.ashift || aidx > lqn.ashift + lqn.nacts) continue;
3601 for (std::size_t cidx : lqn.callsof[aidx]) {
3602 if (lqn.calltype[cidx] != CallType::SYNC) continue;
3603 const std::size_t dst = lqn.callpair_dst[cidx];
3604 const std::size_t de = dst - lqn.eshift;
3605 if (de >= 1 && de <= lqn.nentries && il_all(de, target_e) > Tzero())
3606 out.push_back(lqn.parent[dst]);
3607 }
3608 }
3609 std::sort(out.begin(), out.end());
3610 out.erase(std::unique(out.begin(), out.end()), out.end());
3611 return out;
3612 }
3613
3614 bool is_branch_point(std::size_t srcX, std::size_t entryA, std::size_t srcY,
3615 std::size_t entryB) const {
3616 const std::size_t taskA = lqn.parent[entryA], taskB = lqn.parent[entryB];
3617 const std::size_t taskX = lqn.parent[srcX];
3618 if (taskX == taskA && taskX == taskB) return false;
3619 if (srcX == entryA || srcY == entryB) return true;
3620 const std::vector<std::size_t> dx = call_dst_tasks(srcX, entryA - lqn.eshift);
3621 const std::vector<std::size_t> dy = call_dst_tasks(srcY, entryB - lqn.eshift);
3622 for (std::size_t a : dx)
3623 for (std::size_t b : dy)
3624 if (a != b) return true;
3625 return false;
3626 }
3627
3628 void trace_to_server(std::size_t eidx, std::size_t serverIdx, std::vector<bool>& visited,
3629 std::vector<std::size_t>& itasks, bool isHead) const {
3630 if (eidx <= lqn.eshift || eidx > lqn.eshift + lqn.nentries) return;
3631 const std::size_t e = eidx - lqn.eshift;
3632 if (visited[e]) return;
3633 const std::size_t owner = lqn.parent[eidx];
3634 if (owner == serverIdx) return;
3635 if (serverIdx <= lqn.nhosts && lqn.parent[owner] == serverIdx) return;
3636 visited[e] = true;
3637 bool found = false;
3638 const std::vector<std::size_t> sen = server_entry_nums(serverIdx);
3639 for (std::size_t aidx : lqn.actsof[eidx]) {
3640 if (aidx <= lqn.ashift || aidx > lqn.ashift + lqn.nacts) continue;
3641 for (std::size_t cidx : lqn.callsof[aidx]) {
3642 if (lqn.calltype[cidx] != CallType::SYNC) continue;
3643 const std::size_t dst = lqn.callpair_dst[cidx];
3644 const std::size_t dtask = lqn.parent[dst];
3645 bool reaches = dtask == serverIdx ||
3646 (serverIdx <= lqn.nhosts && lqn.parent[dtask] == serverIdx);
3647 if (!reaches) {
3648 const std::size_t de = dst - lqn.eshift;
3649 for (std::size_t sn : sen)
3650 if (il_all(de, sn) > Tzero()) reaches = true;
3651 }
3652 if (reaches) {
3653 trace_to_server(dst, serverIdx, visited, itasks, false);
3654 found = true;
3655 }
3656 }
3657 }
3658 if (found && !isHead) {
3659 itasks.push_back(owner);
3660 std::sort(itasks.begin(), itasks.end());
3661 itasks.erase(std::unique(itasks.begin(), itasks.end()), itasks.end());
3662 }
3663 visited[e] = false;
3664 }
3665
3666 void interlock_for_server(std::size_t serverIdx) {
3667 const std::vector<std::size_t> sen = server_entry_nums(serverIdx);
3668 if (sen.empty()) return;
3669 const std::vector<std::size_t> cts = client_tasks(serverIdx);
3670 if (cts.empty()) return;
3671
3672 std::vector<std::pair<std::size_t, std::size_t>> pairs; // (task, entry number)
3673 for (std::size_t ct : cts)
3674 for (std::size_t ce : lqn.entriesof[ct]) {
3675 const std::size_t cen = ce - lqn.eshift;
3676 if (cen < 1 || cen > lqn.nentries) continue;
3677 for (std::size_t se : sen)
3678 if (il_all(cen, se) > Tzero()) {
3679 pairs.emplace_back(ct, cen);
3680 break;
3681 }
3682 }
3683 if (pairs.size() < 2) return;
3684
3685 // A client entry that reaches the server only from its own phase 2 has REPLIED by then, so a
3686 // parent above it runs concurrently with that request and can meet it at the server: that branch
3687 // is not interlocked. The tracer in init_interlock cuts a nested phase 2 for the same reason.
3688 std::vector<bool> reach_ph1(lqn.nentries + 1, false);
3689 for (const auto& p : pairs)
3690 for (std::size_t se : sen)
3691 if (il_ph1(p.second, se) > Tzero()) {
3692 reach_ph1[p.second] = true;
3693 break;
3694 }
3695
3696 std::vector<std::size_t> common;
3697 for (std::size_t i = 0; i < pairs.size(); ++i)
3698 for (std::size_t j = i + 1; j < pairs.size(); ++j) {
3699 if (pairs[i].first == pairs[j].first) continue;
3700 const std::size_t eA = pairs[i].second, eC = pairs[j].second;
3701 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
3702 const std::size_t tidx = lqn.tshift + t;
3703 for (std::size_t ex : lqn.entriesof[tidx])
3704 for (std::size_t ey : lqn.entriesof[tidx]) {
3705 const std::size_t xn = ex - lqn.eshift, yn = ey - lqn.eshift;
3706 if (xn < 1 || yn < 1 || xn > lqn.nentries || yn > lqn.nentries) continue;
3707 if (il_all(xn, eA) > Tzero() && il_all(yn, eC) > Tzero() &&
3708 (reach_ph1[eA] || xn == eA) && (reach_ph1[eC] || yn == eC) &&
3709 is_branch_point(ex, eA + lqn.eshift, ey, eC + lqn.eshift))
3710 common.push_back(ex);
3711 }
3712 }
3713 }
3714 std::sort(common.begin(), common.end());
3715 common.erase(std::unique(common.begin(), common.end()), common.end());
3716 if (common.empty()) return;
3717
3718 std::vector<std::size_t> interlocked;
3719 for (std::size_t ce : common) {
3720 std::vector<bool> visited(lqn.nentries + 1, false);
3721 std::vector<std::size_t> it;
3722 trace_to_server(ce, serverIdx, visited, it, true);
3723 for (std::size_t x : it) interlocked.push_back(x);
3724 }
3725 std::sort(interlocked.begin(), interlocked.end());
3726 interlocked.erase(std::unique(interlocked.begin(), interlocked.end()), interlocked.end());
3727
3728 std::vector<std::size_t> src_all;
3729 for (std::size_t ce : common) src_all.push_back(lqn.parent[ce]);
3730 std::sort(src_all.begin(), src_all.end());
3731 src_all.erase(std::unique(src_all.begin(), src_all.end()), src_all.end());
3732 {
3733 std::vector<std::size_t> diff;
3734 for (std::size_t x : src_all)
3735 if (!std::binary_search(interlocked.begin(), interlocked.end(), x)) diff.push_back(x);
3736 src_all = diff;
3737 }
3738
3739 // Left empty on purpose, and NOT because phase 2 is unsupported: the
3740 // reference computes ph2SrcTasks (initInterlock.m:230-262) and never
3741 // reads it, and its phase-2 source count is behind `if false`
3742 // (initInterlock.m:288-304). Filling it would change no number.
3743 std::vector<std::size_t> src_ph2;
3744 for (std::size_t it : interlocked)
3745 for (std::size_t ie : lqn.entriesof[it])
3746 for (std::size_t ci : lqn.iscaller.col(ie))
3747 if (ci > lqn.tshift && ci <= NT() &&
3748 !std::binary_search(interlocked.begin(), interlocked.end(), ci))
3749 src_all.push_back(ci);
3750 std::sort(src_all.begin(), src_all.end());
3751 src_all.erase(std::unique(src_all.begin(), src_all.end()), src_all.end());
3752
3753 double nsrc = 0.0;
3754 for (std::size_t st : src_all) nsrc += lqn.mult[st];
3755
3756 il_common_entries[serverIdx] = common;
3757 il_src_all[serverIdx] = src_all;
3758 il_src_ph2[serverIdx] = src_ph2;
3759 il_num_sources[serverIdx] = nsrc;
3760 }
3761
3762 // -----------------------------------------------------------------------
3763 // init and the outer iteration
3764 // -----------------------------------------------------------------------
3765 void init() {
3766 const std::size_t N = lqn.nidx;
3767 tput.assign(N + 1, Tzero());
3768 util.assign(N + 1, Tzero());
3769 servt.assign(N + 1, Tzero());
3770 residt.assign(N + 1, Tzero());
3771 thinkt.assign(N + 1, Tzero());
3772 callservt.assign(lqn.ncalls + 1, Tzero());
3773 callresidt.assign(lqn.ncalls + 1, Tzero());
3774 tputproc.assign(N + 1, Distrib<T>::disabled_dist());
3775 servt_ph1.assign(N + 1, Tzero());
3776 servt_ph2.assign(N + 1, Tzero());
3777 prOvertake.assign(lqn.nentries + 1, Tzero());
3778 build_entry_service_matrix();
3779
3780 relax_omega = (opt.relax == "fixed" || opt.relax == "adaptive") ? opt.relax_factor : 1.0;
3781
3782 servt_prev.assign(N + 1, std::numeric_limits<double>::quiet_NaN());
3783 residt_prev.assign(N + 1, std::numeric_limits<double>::quiet_NaN());
3784 tput_prev.assign(N + 1, std::numeric_limits<double>::quiet_NaN());
3785 thinkt_prev.assign(N + 1, std::numeric_limits<double>::quiet_NaN());
3786 callservt_prev.assign(lqn.ncalls + 1, std::numeric_limits<double>::quiet_NaN());
3787 callresidt_prev.assign(lqn.ncalls + 1, std::numeric_limits<double>::quiet_NaN());
3788 servt_prev_v.assign(N + 1, Tzero());
3789 residt_prev_v.assign(N + 1, Tzero());
3790 tput_prev_v.assign(N + 1, Tzero());
3791 thinkt_prev_v.assign(N + 1, Tzero());
3792 callservt_prev_v.assign(lqn.ncalls + 1, Tzero());
3793
3794 unique_route_idx.clear();
3795 for (const RouteRow& r : route_map) unique_route_idx.push_back(r.idx);
3796 std::sort(unique_route_idx.begin(), unique_route_idx.end());
3797 unique_route_idx.erase(std::unique(unique_route_idx.begin(), unique_route_idx.end()),
3798 unique_route_idx.end());
3799
3800 // only 'ilrate' reads the interlock tables, and their static analysis is costly
3801 if (interlockMethod == "ilrate") init_interlock();
3802
3803 maxitererr.assign(opt.iter_max + 2, 0.0);
3804 results_raw_last.clear();
3805 results_raw_valid = false;
3806 averagingstart = -1;
3807 hasconverged = false;
3808 moment_pass_done = false;
3809 results.clear();
3810
3811 servtcdf.assign(N + 1, fluid::FluidPassage());
3812 callservtcdf.assign(lqn.ncalls + 1, fluid::FluidPassage());
3813 entrycdfrespt.assign(lqn.nentries + 1, LnCdf());
3814 entryproc.assign(lqn.nentries + 1, mam::AphPair<T>());
3815 cdf_repo.assign(ensemble.size(), std::vector<std::vector<fluid::FluidPassage>>());
3816
3817 // warmstart replaces the starting point, and comes LAST so it wins over
3818 // everything above that writes the iterate
3819 warmstarted_ = false;
3820 if (opt.warmstart == "nlp") {
3821 nlp_warm_start();
3822 } else if (opt.warmstart == "mol") {
3823 mol_warm_start();
3824 }
3825 }
3826
3827 /**
3828 * The Picard iteration, with the stochastic controller in place of the
3829 * deterministic test when the layer engine is a simulator.
3830 *
3831 * The two tests are NOT interchangeable and cannot both run: `converged`
3832 * folds a moving average into `results` in place, which is exactly what the
3833 * Polyak-Ruppert average would then be taken of a second time. Whichever
3834 * test is in force therefore owns the results.
3835 */
3836 void iterate() {
3837 init();
3838 const bool stoch = layer_solver_is_stochastic();
3839 if (stoch) {
3840 LnStochConfig cfg;
3841 cfg.iter_tol = opt.iter_tol;
3842 cfg.relax_burnin = relax_omega;
3843 stoch_ctl = std::make_shared<LnStochController<T>>(cfg);
3844 }
3845 int it = 0;
3846 // converged(0), converged(1), ..., converged(n), as iterate.m calls it: the last
3847 // iterate is tested (and averaged) even when the loop stops on iter_max
3848 bool done = !stoch && converged(it);
3849 while (!done && it < opt.iter_max) {
3850 if (results_raw_valid) {
3851 results.back() = results_raw_last;
3852 results_raw_valid = false;
3853 }
3854 ++it;
3855 results.emplace_back(ensemble.size());
3856 for (std::size_t e = 0; e < ensemble.size(); ++e) analyze(it, e);
3857 post(it);
3858 if (stoch) {
3859 std::vector<double> jobs(ensemble.size(), 0.0);
3860 for (std::size_t e = 0; e < ensemble.size(); ++e)
3861 jobs[e] = ensemble[e].total_jobs();
3862 const bool stop = stoch_ctl->update(it, results.back(), jobs, servt, residt);
3863 // The step this sets is the one the NEXT updateMetrics applies,
3864 // which is why it is read back here and not before the sweep.
3865 relax_omega = stoch_ctl->relax_omega();
3866 if (stop) {
3867 did_converge = true;
3868 hasconverged = true;
3869 break;
3870 }
3871 } else {
3872 done = converged(it);
3873 }
3874 }
3875 iterations_done = it;
3876 // finish(): in Robbins-Monro mode report the averaged iterate, not the
3877 // last (noisy) one.
3878 if (stoch && stoch_ctl && stoch_ctl->averaging_count() > 0) {
3879 const std::vector<LayerResult<T>>& avg = stoch_ctl->averaged_results();
3880 for (std::size_t e = 0; e < results.back().size() && e < avg.size(); ++e)
3881 results.back()[e] = avg[e];
3882 servt = stoch_ctl->averaged_servt();
3883 residt = stoch_ctl->averaged_residt();
3884 }
3885 }
3886
3887 /**
3888 * Port of the filterMetric helper inside @@NetworkSolver/getAvg.m.
3889 *
3890 * This is not cosmetic post-processing: it is where a raw solver matrix
3891 * becomes the result the rest of LINE consumes, and three of its rules
3892 * change numbers that SolverLN then iterates on.
3893 *
3894 * 1. a (station, class) pair the class never visits is zeroed, whether
3895 * because its service is disabled or because its visit ratio is zero;
3896 * 2. anything below FineTol is snapped to zero;
3897 * 3. the caller's zeroMask is applied -- and for the queue length and the
3898 * utilization that mask is `RN < 10*FineTol`, which zeroes both
3899 * wherever the response time is immediate.
3900 *
3901 * Rule 3 is the one that matters most here. Every LQN entry, task and call
3902 * class is served by an Immediate distribution somewhere, whose response
3903 * time is 1e-8, so without it a layer reports the Immediate classes' share
3904 * of the population as real queue length and the LN think-time update reads
3905 * a task utilization that MATLAB reports as zero.
3906 */
3907 Matrix<T> filter_metric(const qn::Layer<T>& L, const Matrix<T>& metric,
3908 const std::vector<std::vector<bool>>* zero_mask) const {
3909 const std::size_t M = L.nstations, K = L.nclasses;
3910 Matrix<T> out(M, K, Tzero());
3911 for (std::size_t i = 0; i < M; ++i)
3912 for (std::size_t k = 0; k < K; ++k)
3913 if (!L.disabled[i][k]) out(i, k) = metric(i, k);
3914 if (zero_mask)
3915 for (std::size_t i = 0; i < M; ++i)
3916 for (std::size_t k = 0; k < K; ++k)
3917 if ((*zero_mask)[i][k]) out(i, k) = Tzero();
3918 for (std::size_t i = 0; i < M; ++i)
3919 for (std::size_t k = 0; k < K; ++k)
3920 if (dbl(out(i, k)) < GlobalConstants::FineTol) out(i, k) = Tzero();
3921 for (std::size_t k = 0; k < K; ++k) {
3922 std::size_t c = L.nchains;
3923 for (std::size_t cc = 0; cc < L.nchains; ++cc)
3924 if (L.chains[cc][k]) c = cc;
3925 if (c == L.nchains) continue;
3926 for (std::size_t i = 0; i < M; ++i)
3927 if (L.visits[c](L.stateful_of_station(i + 1) - 1, k) == Tzero())
3928 out(i, k) = Tzero();
3929 }
3930 return out;
3931 }
3932
3933 /**
3934 * Solve one layer with CTMC and report it in the shape the MVA path returns:
3935 * the reference's `LN(model, @(m) CTMC(m))`, and the engine a layer carrying
3936 * a Region is forced onto whatever the layer solver is.
3937 *
3938 * `qn::Layer<T>` derives from NetworkStruct, so the layer goes to the
3939 * analyzer as it stands; the generator needs the routing matrix, which the
3940 * layer does not build until asked (see solve_layer_fluid). A layer is a
3941 * closed network of the LQN's own small populations, so its state space is
3942 * finite without a cutoff; how large it grows is this engine's real limit.
3943 * A fork layer is refused, as under NC and SSA.
3944 */
3945 mva::MvaSolution<T> solve_layer_ctmc(std::size_t e) {
3946 refuse_fork_layer(e);
3947 qn::Layer<T>& L = ensemble[e];
3948 L.refresh_rt();
3949 // The capacities the WAITQ generator reads to bound each station's
3950 // marginal are filled by solve_layer, for every engine; the routing
3951 // matrix is not, because only this path and the fluid one need it.
3952 const ctmc::CtmcOptions& co = opt.layer_ctmc;
3953 // _run_any, not _run: the plain generator implements DROP only, and a
3954 // region built from an LQN admission constraint carries the WAITQ
3955 // default, whose per-region token FIFO lives in the waitq generator.
3956 const mva::AvgResult<T> a = ctmc::solver_ctmc_run_analyzer_any(L, co);
3957 mva::MvaSolution<T> out;
3958 out.method = "ctmc";
3959 out.iter = 1;
3960 out.Q = a.QN;
3961 out.U = a.UN;
3962 out.R = a.RN;
3963 out.Tp = a.TN;
3964 out.C = a.CN;
3965 out.X = a.XN;
3966 return out;
3967 }
3968
3969 /**
3970 * Solve one layer with SolverMAM, the reference's `LN(model, @(m) MAM(m))`.
3971 *
3972 * The layer goes through the full `mam_dispatch` ladder under
3973 * `opt.layer_mam`, whose method is SolverMAM's own `default` unless the
3974 * caller set one, exactly as the factory builds a default SolverMAM. On a
3975 * closed layer that resolves to the `dec.source` decomposition; MAM is a
3976 * deterministic engine, so the ordinary convergence test stays in force. A
3977 * fork layer is refused, as under NC and SSA.
3978 */
3979 mva::MvaSolution<T> solve_layer_mam(std::size_t e) {
3980 refuse_fork_layer(e);
3981 qn::Layer<T>& L = ensemble[e];
3982 L.refresh_rt();
3983 L.refresh_capacity();
3984 mva::MvaSolution<T> out = mam::mam_dispatch(L, opt.layer_mam).sol;
3985 out.method = "mam";
3986 return out;
3987 }
3988
3989 /** A fork layer's fixed point is driven by MVA in this port; any other engine refuses it by name. */
3990 void refuse_fork_layer(std::size_t e) const {
3991 if (fj_tr[e].active())
3992 throw UnsupportedError(ErrorKind{"Fork"},
3993 "SolverLN: layer '" + ensemble[e].name +
3994 "' carries a fork, whose fixed point is driven by MVA in this port; solve this "
3995 "model with layer_solver 'mva'");
3996 }
3997
3998 /**
3999 * Solve one layer with SolverNC, the reference's `LN(model, @(m) NC(m))`.
4000 *
4001 * This is the layer engine the Java CLI's bare `ln` token selects, against
4002 * `ln.mva` for the MVA one. NC evaluates the normalizing constant rather
4003 * than the MVA recursion, so on a product-form layer it is the SAME answer
4004 * reached exactly instead of through the AMVA approximation -- and on a
4005 * layer that is not product form the two differ, which is the whole reason
4006 * the token exists.
4007 */
4008 mva::MvaSolution<T> solve_layer_nc(std::size_t e) {
4009 if (fj_tr[e].active())
4010 throw UnsupportedError(ErrorKind{"Fork"},
4011 "SolverLN: layer '" + ensemble[e].name +
4012 "' carries a fork, whose fixed point is driven by MVA in this port; solve this "
4013 "model with layer_solver 'mva'");
4014 qn::Layer<T>& L = ensemble[e];
4015 L.refresh_rt();
4016 // `solver_nc_solve`, NOT `nc_dispatch`: the latter is the INNER network
4017 // solve, the one the caching-queueing decomposition itself calls as its
4018 // `netfun`, and it carries no cache branch at all. The three cache gates
4019 // live in `solver_nc_solve` (solver_nc_runner.h), which is the true
4020 // counterpart of `mva_dispatch` on the branch below. Routed here, a
4021 // cache layer never reached `solver_nc_cacheqn_analyzer` and its Cache
4022 // node was solved as ordinary routing, so the hit/miss split came back
4023 // as the probability `link()` offered -- an even 1/2, independent of
4024 // capacity, item count and replacement strategy, with no warning.
4025 // `.sol` alone is taken, exactly as the MVA branch takes it: the layer
4026 // reads the split off its own station throughputs, and the auxiliary
4027 // `refreshed_struct` both dispatchers also return is unused on either.
4028 mva::MvaSolution<T> out = nc::solver_nc_solve(L, opt.layer_nc).sol;
4029 out.method = "nc";
4030 return out;
4031 }
4032
4033 /**
4034 * Solve one layer by simulation, the reference's `LN(model, @(m) SSA(m))`.
4035 *
4036 * THE LAYER RESULTS ARE THEN NOISY, and the deterministic convergence test
4037 * cannot terminate against noise: its successive-difference error is
4038 * bounded below by the standard error of the estimates. `iterate` therefore
4039 * switches to `LnStochController` whenever this engine is selected, so the
4040 * relaxation decays as Robbins-Monro and the reported iterate is the
4041 * Polyak-Ruppert average. Selecting this engine and keeping the
4042 * deterministic test would simply run to iter_max.
4043 */
4044 mva::MvaSolution<T> solve_layer_ssa(std::size_t e) {
4045 if (fj_tr[e].active())
4046 throw UnsupportedError(ErrorKind{"Fork"},
4047 "SolverLN: layer '" + ensemble[e].name +
4048 "' carries a fork, whose fixed point is driven by MVA in this port; solve this "
4049 "model with layer_solver 'mva'");
4050 qn::Layer<T>& L = ensemble[e];
4051 L.refresh_rt();
4052 ssa::SsaOptions so = opt.layer_ssa;
4053 so.seed = static_cast<unsigned long>(static_cast<long>(so.seed) + sens_rep_offset());
4054 so.samples = sens_rep_samples(so.samples);
4055 const ssa::SsaSolution s = ssa::solver_ssa(L, so);
4056 mva::MvaSolution<T> out;
4057 out.method = "ssa";
4058 out.iter = 1;
4059 out.Q = Matrix<T>(L.nstations, L.nclasses, Tzero());
4060 out.U = Matrix<T>(L.nstations, L.nclasses, Tzero());
4061 out.R = Matrix<T>(L.nstations, L.nclasses, Tzero());
4062 out.Tp = Matrix<T>(L.nstations, L.nclasses, Tzero());
4063 for (std::size_t i = 0; i < L.nstations; ++i)
4064 for (std::size_t r = 0; r < L.nclasses; ++r) {
4065 out.Q(i, r) = num_traits<T>::from_double(s.QN(i, r));
4066 out.U(i, r) = num_traits<T>::from_double(s.UN(i, r));
4067 out.R(i, r) = num_traits<T>::from_double(s.RN(i, r));
4068 out.Tp(i, r) = num_traits<T>::from_double(s.TN(i, r));
4069 }
4070 out.C.assign(L.nclasses, Tzero());
4071 out.X.assign(L.nclasses, Tzero());
4072 for (std::size_t r = 0; r < L.nclasses && r < s.XN.size(); ++r) {
4073 out.X[r] = num_traits<T>::from_double(s.XN[r]);
4074 out.C[r] = num_traits<T>::from_double(s.CN[r]);
4075 }
4076 return out;
4077 }
4078
4079 /**
4080 * Solve one layer with the native LDES engine, the reference's `LN(model, @(m) LDES(m))`.
4081 *
4082 * IN PROCESS, not through `solver_ldes`'s subprocess client: the layer is a
4083 * NetworkStruct this port built itself, so there is no model.json whose
4084 * bytes would have to be forwarded losslessly, and one process per layer per
4085 * iteration would dominate the run. The engine is the one `common/ldes`
4086 * runs (ldes_engine.h). Noisy like `ssa`, so `iterate` runs the stochastic
4087 * controller; each solve gets the Robbins-Monro seed of SolverLN.pre. A
4088 * fork layer is refused, as under NC and SSA.
4089 */
4090 mva::MvaSolution<T> solve_layer_ldes(std::size_t e) {
4091 refuse_fork_layer(e);
4092 qn::Layer<T>& L = ensemble[e];
4093 // The engine samples in double precision (its fork and clock state are
4094 // double), so a higher arithmetic has nothing to carry: refuse it.
4095 if constexpr (!std::is_same<T, double>::value) {
4096 throw UnsupportedError(ErrorKind{"Arithmetic"},
4097 "SolverLN: the ldes layer engine simulates in double precision; "
4098 "rerun with --arith double");
4099 } else {
4100 L.refresh_rt();
4101 ldes::LdesOptions lo = opt.layer_ldes;
4102 lo.seed = layer_seed(opt.layer_ldes.seed, e);
4103 lo.samples = sens_rep_samples(lo.samples);
4104 if (lo.events > 0) lo.events = sens_rep_samples(lo.events);
4105 const ldes::LdesResult s = ldes::ldes_engine_solve(L, lo);
4106 mva::MvaSolution<T> out = sim_layer_solution(L, s.QN, s.UN, s.RN, s.TN, "ldes");
4107 for (std::size_t r = 0; r < L.nclasses && r < s.XN.cols(); ++r) {
4108 out.X[r] = s.XN(0, r);
4109 out.C[r] = s.CN(0, r);
4110 }
4111 return out;
4112 }
4113 }
4114
4115 /**
4116 * Solve one layer with JSIM, the reference's `LN(model, @(m) JMT(m))`.
4117 *
4118 * One JMT subprocess per layer per iteration, exactly as the reference's
4119 * factory runs one. A layer carrying immediate feedback is refused up front
4120 * with the reference's own sentence (assertLayerSolverSupportsModel):
4121 * JSIM re-queues a job the layer means to keep in service. Seeded and
4122 * driven as `ldes` is; a fork layer is refused, as under NC and SSA.
4123 */
4124 mva::MvaSolution<T> solve_layer_jmt(std::size_t e) {
4125 refuse_fork_layer(e);
4126 qn::Layer<T>& L = ensemble[e];
4127 for (std::size_t i = 0; i < L.immfeed.size(); ++i)
4128 for (std::size_t r = 0; r < L.immfeed[i].size(); ++r)
4129 if (L.immfeed[i][r])
4130 throw UnsupportedError(ErrorKind{"Structure"},
4131 "SolverJMT cannot solve LN layer " + std::to_string(e + 1) +
4132 ": the layer carries immediate feedback (sn.immfeed), which SolverJMT does "
4133 "not support, so LN would fail at the first iteration. Use the default layer "
4134 "factory (MVA/NC) or another layer solver that supports immediate feedback.");
4135 L.refresh_rt();
4136 jmt::JmtOptions jo = opt.layer_jmt;
4137 jo.seed = layer_seed(opt.layer_jmt.seed, e);
4138 jo.samples = sens_rep_samples(jo.samples);
4139 jo.verbose = false;
4140 const jmt::JmtResult<T> s = jmt::solver_jmt_run_analyzer(L, jo);
4141 Matrix<double> Q(L.nstations, L.nclasses, 0.0), U = Q, R = Q, X = Q;
4142 for (std::size_t i = 0; i < L.nstations; ++i)
4143 for (std::size_t r = 0; r < L.nclasses; ++r) {
4144 Q(i, r) = num_traits<T>::to_double(s.avg.QN(i, r));
4145 U(i, r) = num_traits<T>::to_double(s.avg.UN(i, r));
4146 R(i, r) = num_traits<T>::to_double(s.avg.RN(i, r));
4147 X(i, r) = num_traits<T>::to_double(s.avg.TN(i, r));
4148 }
4149 mva::MvaSolution<T> out = sim_layer_solution(L, Q, U, R, X, "jmt");
4150 for (std::size_t r = 0; r < L.nclasses; ++r) {
4151 if (r < s.avg.XN.size()) out.X[r] = s.avg.XN[r];
4152 if (r < s.avg.CN.size()) out.C[r] = s.avg.CN[r];
4153 }
4154 return out;
4155 }
4156
4157 /** A simulator's station tables (the first nstations rows) in the shape the MVA path returns. */
4158 static mva::MvaSolution<T> sim_layer_solution(const qn::Layer<T>& L, const Matrix<double>& Q,
4159 const Matrix<double>& U, const Matrix<double>& R,
4160 const Matrix<double>& X, const char* method) {
4161 mva::MvaSolution<T> out;
4162 out.method = method;
4163 out.iter = 1;
4164 out.Q = Matrix<T>(L.nstations, L.nclasses, Tzero());
4165 out.U = Matrix<T>(L.nstations, L.nclasses, Tzero());
4166 out.R = Matrix<T>(L.nstations, L.nclasses, Tzero());
4167 out.Tp = Matrix<T>(L.nstations, L.nclasses, Tzero());
4168 for (std::size_t i = 0; i < L.nstations; ++i)
4169 for (std::size_t r = 0; r < L.nclasses; ++r) {
4170 out.Q(i, r) = num_traits<T>::from_double(Q(i, r));
4171 out.U(i, r) = num_traits<T>::from_double(U(i, r));
4172 out.R(i, r) = num_traits<T>::from_double(R(i, r));
4173 out.Tp(i, r) = num_traits<T>::from_double(X(i, r));
4174 }
4175 out.C.assign(L.nclasses, Tzero());
4176 out.X.assign(L.nclasses, Tzero());
4177 return out;
4178 }
4179
4180 /**
4181 * Run one layer through the fluid analyzer instead of MVA.
4182 *
4183 * WHAT MAKES THIS SOUND AT ALL. The layer handed to a solver is an ordinary
4184 * closed queueing network -- the layering has already replaced every call
4185 * by a class with a service demand -- so any NetworkSolver can solve it,
4186 * and the reference says exactly that by taking a solver factory. The outer
4187 * Picard iteration only ever reads [QN, UN, RN, TN] back, so the fluid
4188 * result maps onto the same shape MVA returns.
4189 *
4190 * WHAT CHANGES, and it is not nothing: the fluid limit is exact only as the
4191 * populations grow, so on a layer of a few jobs it is a genuinely different
4192 * approximation, not a slower route to the same fixed point. It also feeds
4193 * DIFFERENT service demands back into the next outer iteration, so the two
4194 * ensembles converge to different fixed points rather than to the same one
4195 * by different paths.
4196 *
4197 * REFUSED BY NAME: a non-double backend (LSODA is double-only, see
4198 * solver_fluid.h) and a fork layer (`fj_fixed_point` supplies MVA as its
4199 * inner solve, and the auxiliary near-zero-rate open classes it introduces
4200 * are not something the fluid drift represents).
4201 */
4202 mva::MvaSolution<T> solve_layer_fluid(std::size_t e) {
4203 if (fj_tr[e].active())
4204 throw UnsupportedError(ErrorKind{"Fork"},
4205 "SolverLN: layer '" + std::to_string(e) +
4206 "' carries a fork, whose fixed point is driven by MVA in this port; solve this "
4207 "model with layer_solver 'mva'");
4208 qn::Layer<T>& L = ensemble[e];
4209 // THE LAYER HAS NO ROUTING MATRIX UNTIL IT IS ASKED FOR ONE. `buildLayers`
4210 // records the wiring with set_route and then calls refresh_chains, which
4211 // reads P directly and computes the VISITS; MVA needs nothing else, so
4212 // `rt` stays empty. Both fluid methods route through `sn.rt` instead, and
4213 // an empty one is not an error anywhere -- it is read as "no transition
4214 // exists", the drift decays to zero and every metric comes back 0. It is
4215 // rebuilt on every solve because update_routing_probabilities can change
4216 // the wiring between outer iterations.
4217 L.refresh_rt();
4218 mva::MvaSolution<T> out;
4219 out.method = "fluid";
4220 out.iter = 1;
4221 out.Q = Matrix<T>(L.nstations, L.nclasses, Tzero());
4222 out.U = Matrix<T>(L.nstations, L.nclasses, Tzero());
4223 out.R = Matrix<T>(L.nstations, L.nclasses, Tzero());
4224 out.Tp = Matrix<T>(L.nstations, L.nclasses, Tzero());
4225 out.C.assign(L.nclasses, Tzero());
4226 out.X.assign(L.nclasses, Tzero());
4227 detail::ln_fluid_solve(L, opt.layer_fluid, out);
4228 return out;
4229 }
4230
4231 /**
4232 * Solve one layer, running the fork-join fixed point when it has a fork.
4233 *
4234 * The driver itself is shared (fj_driver.h); the layer path supplies
4235 * solver_mva_analyzer as the inner solve. The auxiliary arrival rates
4236 * fj_lambda are warm-started across outer iterations, per the reference.
4237 *
4238 * `default` becomes `amva` on a fork layer, which is what mvaDispatch.m does
4239 * for any model whose BASE has a fork: the transformed layer is mixed with
4240 * auxiliary near-zero-rate open classes, and the exact mixed MVA the default
4241 * ladder would otherwise pick degenerates on them.
4242 */
4243 mva::MvaSolution<T> solve_layer(std::size_t e) {
4244 // BEFORE ANY ENGINE, AND FOR EVERY ONE OF THEM. `build_layer` stops at
4245 // refresh_chains, so a layer reaches this point with `cap` and
4246 // `classcap` still EMPTY, while the reference hands SolverMVA a struct
4247 // that refreshCapacity has already filled. Every consumer of Kendall's
4248 // K -- `buffer_size`, and through it `has_blocking` and the BCMP gate
4249 // `has_product_form` -- indexes those vectors by station, so an empty
4250 // one is an out-of-range read and not a permissive default. It is
4251 // recomputed on each solve because the layer's class populations move
4252 // between outer iterations, and the buffers are derived from them.
4253 ensemble[e].refresh_capacity();
4254 // A layer carrying an admission constraint goes to CTMC whatever the
4255 // layer solver is, as adaptiveSolverFactory does (SolverLN.m:1047-1089):
4256 // MVA and the fluid path both refuse a Region by name, so leaving the
4257 // layer on them would refuse a model the reference solves. The
4258 // reference then falls back to LDES and SSA; neither is reachable here
4259 // (there is no cpp LDES, and cpp SSA refuses regions), so CTMC is the
4260 // only path and its state-space bound is this port's real limit.
4261 // An explicit LDES or JMT factory keeps the layer: both declare Region,
4262 // so the reference's assertLayerSolverSupportsModel admits them as given.
4263 if (!ensemble[e].regions.empty() && opt.layer_solver != "ldes" && opt.layer_solver != "jmt")
4264 return solve_layer_ctmc(e);
4265 // A setup no longer forces the MAM decomposition on the layer
4266 // (SolverLN.m, 2026-08-11): the cold start is charged to the entry by
4267 // setup_charge(), not wired into the station, so the layer is an
4268 // ordinary one and the user's own layer solver serves it.
4269 // A cache layer is dispatched to the integrated caching-queueing
4270 // analyzer, which reads the NODE routing to find what lies downstream
4271 // of the cache. The layer carries none until asked, and it has to be
4272 // rebuilt every pass because entry selection can move it. EVERY layer
4273 // engine below must reach that analyzer, not just the MVA one: this
4274 // refresh runs for all of them, and a branch that then hands the
4275 // rebuilt routing to a solver with no cache gate reports the offered
4276 // hit/miss split instead of the converged one.
4277 if (has_cache_node(e)) ensemble[e].refresh_rt();
4278 if (opt.layer_solver == "fluid") return solve_layer_fluid(e);
4279 if (opt.layer_solver == "nc") return solve_layer_nc(e);
4280 if (opt.layer_solver == "ssa") return solve_layer_ssa(e);
4281 if (opt.layer_solver == "mam") return solve_layer_mam(e);
4282 if (opt.layer_solver == "ctmc") return solve_layer_ctmc(e);
4283 if (opt.layer_solver == "ldes") return solve_layer_ldes(e);
4284 if (opt.layer_solver == "jmt") return solve_layer_jmt(e);
4285 if (opt.layer_solver != "mva")
4286 throw UnsupportedError(ErrorKind{"Option"}, "SolverLN: layer_solver '" + opt.layer_solver +
4287 "' is not available; use 'mva', 'nc', 'fluid', 'ssa', 'mam', 'ctmc', "
4288 "'ldes' or 'jmt'");
4289 // Route each layer through the full mva_dispatch ladder, as MATLAB's
4290 // SolverLN does by handing every layer to SolverMVA.runAnalyzer: a plain
4291 // closed layer still lands on branch 13 (solver_mva_analyzer), but a
4292 // layer carrying load- or class-dependent scaling now reaches
4293 // solver_mvald_analyzer, matching the reference rather than silently
4294 // running the flat AMVA.
4295 mva::MvaOptions eopt = opt.layer;
4296 if (e < layer_interlock.size()) eopt.interlock = layer_interlock[e];
4297 if (!fj_tr[e].active())
4298 return mva::mva_dispatch(ensemble[e], eopt, layer_init_sol[e]).sol;
4299 mva::MvaOptions lopt = eopt;
4300 if (lopt.method == "default") lopt.method = "amva";
4301 return mva::fj_fixed_point(
4302 ensemble[e], fj_tr[e], fj_lambda[e], eopt,
4303 [&lopt](qn::NetworkStruct<T>& V) {
4304 return mva::mva_dispatch(V, lopt, Matrix<T>()).sol;
4305 });
4306 }
4307
4308 void analyze(int it, std::size_t e) {
4309 qn::Layer<T>& L = ensemble[e];
4310 cur_it = it;
4311 const mva::MvaSolution<T> s = solve_layer(e);
4312 LayerResult<T>& r = results[it - 1][e];
4313 r.RN = filter_metric(L, s.R, nullptr);
4314 std::vector<std::vector<bool>> zmask(L.nstations, std::vector<bool>(L.nclasses, false));
4315 for (std::size_t i = 0; i < L.nstations; ++i)
4316 for (std::size_t k = 0; k < L.nclasses; ++k)
4317 zmask[i][k] = dbl(r.RN(i, k)) < 10.0 * GlobalConstants::FineTol;
4318 r.QN = filter_metric(L, s.Q, &zmask);
4319 r.UN = filter_metric(L, s.U, &zmask);
4320 r.TN = filter_metric(L, s.Tp, nullptr);
4321 r.WN = residence_from_response(L, r.RN);
4322 // warm start the next solve of this layer from the chain-aggregated
4323 // queue lengths, as the reference does for SolverMVA layers
4324 // A fork layer is exempt: the reference guards this on the result having
4325 // the LAYER's station count, and the transformed model reports one more
4326 // row (its Source), so the hint is never installed there. A fluid layer
4327 // is exempt too, and for the reference's own reason: `analyze` guards
4328 // the warm start on `strcmp(self.solvers{e}.name, 'SolverMVA')`, because
4329 // init_sol means a queue-length vector to AMVA and a full ODE state
4330 // vector to the fluid solver -- the two are not interchangeable.
4331 if (!fj_tr[e].active() && opt.layer_solver == "mva") {
4332 Matrix<T> Qch(L.nstations, L.nchains, Tzero());
4333 for (std::size_t c = 0; c < L.nchains; ++c)
4334 for (std::size_t i = 0; i < L.nstations; ++i) {
4335 T s2 = Tzero();
4336 for (std::size_t k : L.inchain[c]) s2 += s.Q(i, k - 1);
4337 Qch(i, c) = s2;
4338 }
4339 layer_init_sol[e] = Qch;
4340 }
4341 }
4342
4343 /** Port of sn_get_residt_from_respt: response time scaled by the visit ratio. */
4344 Matrix<T> residence_from_response(const qn::Layer<T>& L, const Matrix<T>& RN) const {
4345 Matrix<T> V(L.nstations, L.nclasses, Tzero());
4346 for (std::size_t c = 0; c < L.nchains; ++c)
4347 for (std::size_t i = 0; i < L.nstations; ++i) {
4348 const std::size_t sf = L.stateful_of_station(i + 1) - 1;
4349 for (std::size_t k = 0; k < L.nclasses; ++k)
4350 V(i, k) = T(V(i, k) + L.visits[c](sf, k));
4351 }
4352 Matrix<T> WN(L.nstations, L.nclasses, Tzero());
4353 for (std::size_t i = 0; i < L.nstations; ++i)
4354 for (std::size_t k = 0; k < L.nclasses; ++k) {
4355 if (L.disabled[i][k]) continue;
4356 if (!(RN(i, k) > Tzero())) continue;
4357 if (dbl(RN(i, k)) < GlobalConstants::FineTol) {
4358 WN(i, k) = RN(i, k);
4359 continue;
4360 }
4361 std::size_t c = 0;
4362 for (std::size_t cc = 0; cc < L.nchains; ++cc)
4363 if (L.chains[cc][k]) c = cc;
4364 const std::size_t rstat = L.classes[k].refstat;
4365 T den = Tzero();
4366 if (L.refclass[c] > 0) {
4367 den = V(rstat - 1, L.refclass[c] - 1);
4368 } else {
4369 for (std::size_t kk : L.inchain[c]) den += V(rstat - 1, kk - 1);
4370 }
4371 if (den == Tzero()) continue;
4372 WN(i, k) = T(RN(i, k) * V(i, k) / den);
4373 }
4374 for (std::size_t i = 0; i < L.nstations; ++i)
4375 for (std::size_t k = 0; k < L.nclasses; ++k)
4376 if (dbl(WN(i, k)) < 10.0 * GlobalConstants::FineTol) WN(i, k) = Tzero();
4377 return WN;
4378 }
4379
4380 void post(int it) {
4381 update_metrics(it);
4382 // Under 'refpath' the merged client chain performs the interlocking
4383 // structurally, and the discount as well would deflate the same wait twice
4384 if (interlockMethod == "ilrate") update_populations(it);
4385 update_think_times(it);
4386 update_layers(it);
4387 update_routing_probabilities(it);
4388 for (std::size_t e : route_reset) {
4389 ensemble[e].refresh_chains();
4390 layer_init_sol[e] = Matrix<T>();
4391 }
4392 // moment3 needs no refreshProcesses here: this port keeps the service
4393 // DISTRIBUTION on the layer and refresh_rates re-reads it, so there is no
4394 // second representation to fall out of step, unlike sn.proc in MATLAB.
4395 for (std::size_t e : svc_reset) ensemble[e].refresh_rates();
4396 }
4397
4398 /** Port of converged.m: moving average of the layer results plus the test. */
4399 bool converged(int it) {
4400 const std::size_t E = ensemble.size();
4401 const int iter_min = std::max<int>(2 * int(E), int(std::ceil(opt.iter_max / 4.0)));
4402 const int wnd_size = std::max(5, int(std::ceil(iter_min / 5.0)));
4403
4404 if (it >= iter_min && int(results.size()) >= wnd_size) {
4405 results_raw_last = results.back();
4406 results_raw_valid = true;
4407 const T w = T(Tone() / num_traits<T>::from_int(wnd_size));
4408 for (std::size_t e = 0; e < E; ++e) {
4409 LayerResult<T>& cur = results[results.size() - 1][e];
4410 auto scale = [&](Matrix<T>& A) {
4411 for (std::size_t i = 0; i < A.rows(); ++i)
4412 for (std::size_t j = 0; j < A.cols(); ++j) A(i, j) = T(A(i, j) * w);
4413 };
4414 Matrix<T> Q = cur.QN, U = cur.UN, R = cur.RN, Tp = cur.TN, W = cur.WN;
4415 scale(Q); scale(U); scale(R); scale(Tp); scale(W);
4416 for (int k = 1; k < wnd_size; ++k) {
4417 const LayerResult<T>& old = results[results.size() - 1 - k][e];
4418 auto add = [&](Matrix<T>& A, const Matrix<T>& B) {
4419 for (std::size_t i = 0; i < A.rows(); ++i)
4420 for (std::size_t j = 0; j < A.cols(); ++j) A(i, j) = T(A(i, j) + B(i, j) * w);
4421 };
4422 add(Q, old.QN); add(U, old.UN); add(R, old.RN); add(Tp, old.TN); add(W, old.WN);
4423 }
4424 cur.QN = Q; cur.UN = U; cur.RN = R; cur.TN = Tp; cur.WN = W;
4425 }
4426 }
4427
4428 if (it > 1) {
4429 double err = 0.0;
4430 for (std::size_t e = 0; e < E; ++e) {
4431 const Matrix<T>& Q = results[results.size() - 1][e].QN;
4432 const Matrix<T>& Q1 = results[results.size() - 2][e].QN;
4433 const double Njobs = ensemble[e].total_jobs();
4434 if (!(Njobs > 0.0)) continue;
4435 double mx = 0.0;
4436 for (std::size_t i = 0; i < Q.rows(); ++i)
4437 for (std::size_t j = 0; j < Q.cols(); ++j)
4438 mx = std::max(mx, std::fabs(dbl(Q(i, j)) - dbl(Q1(i, j))));
4439 err += mx / Njobs;
4440 }
4441 maxitererr[it] = err;
4443 static_cast<long>(it),
4444 "layer iteration %zu: max queue-length change %.3e (tolerance %.3e)",
4445 static_cast<std::size_t>(it), err, opt.iter_tol);
4446 if (it == iter_min) {
4447 line::util::LineConsole::step("started averaging the iterates to aid convergence");
4448 averagingstart = it;
4449 }
4450 }
4451
4452 // ITER_MIN DOES NOT FLOOR THE STOP TEST OF A WARM-STARTED RUN: the floor keeps a cold iterate from
4453 // reading its early plateau as convergence, and a seeded one starts past it. It still sizes the
4454 // averaging window above, so both arms iterate the same map. Three computed errors are still needed.
4455 const int stop_floor = warmstarted_ ? 3 : iter_min;
4456 if (it > stop_floor && maxitererr[it] < opt.iter_tol && maxitererr[it - 1] < opt.iter_tol &&
4457 maxitererr[it - 2] < opt.iter_tol) {
4458 if (!hasconverged) {
4459 hasconverged = true;
4460 } else {
4461 did_converge = true;
4462 return true;
4463 }
4464 } else {
4465 hasconverged = false;
4466 }
4467 return false;
4468 }
4469
4470 // -----------------------------------------------------------------------
4471 // updateMetrics
4472 // -----------------------------------------------------------------------
4473 /** Port of updateMetrics.m: the method selects which update runs. */
4474 // -----------------------------------------------------------------------
4475 // Method "srvn.ph": the activity graph of an entry as a phase-type server law
4476 //
4477 // Each layer is a two-station cycle, a client Delay plus the server, with
4478 // one closed class per caller task. The sequencing the default method
4479 // encodes as routing -- a class per entry, per activity and per call, plus
4480 // Fork, Join, Router and ClassSwitch nodes -- is composed instead into a
4481 // single phase-type service law per (layer, caller), by the exact
4482 // series-parallel reduction of Workflow. The layer therefore carries only
4483 // the client/server back-and-forth, and the activity graph survives as a
4484 // distribution.
4485 //
4486 // Port of the MATLAB @SolverLN/buildLayersPH.m, updateLayersPH.m,
4487 // updateMetricsPH.m, updateThinkTimesPH.m, phComposeEntryLaws.m and
4488 // getEnsembleAvgPH.m, of the JAR jline.solvers.ln.SolverLNPH and of the
4489 // Python line_solver.solvers.solver_ln.solver_ln_ph. See
4490 // _kb/06-solver-catalog.md (LN section) for the layering taxonomy.
4491 // -----------------------------------------------------------------------
4492
4493 /**
4494 * The method the layers were actually BUILT for: "srvn.ph", "srvn.cs",
4495 * "flat.cs", "flat.ph" or "moment3". Resolved once in build_layers, because
4496 * the alias "srvn" may fall back; every dispatch reads this and not
4497 * opt.method, so a reconstruction can never disagree with the layers it is
4498 * reading.
4499 */
4500 std::string lnmethod;
4501 /** True once ph_init_laws has composed the per-entry workflows. */
4502 bool ph_laws_ready = false;
4503
4504 /**
4505 * Normalise a method name onto one the solver dispatches on. A method name
4506 * carries TWO decisions: the LAYERING, which fixes what a submodel is, and
4507 * the ENCODING, which fixes how an activity graph is written into it.
4508 *
4509 * "srvn.cs" encodes the activity graph as ROUTING, "srvn.ph" as a composed
4510 * phase-type server law, "srvn" is the alias that takes "srvn.ph" where it
4511 * can serve the model and "srvn.cs" otherwise, "flat.cs" squashes every
4512 * server into one submodel with the routing encoding, "flat.ph" squashes
4513 * them with the composed one ("flat" is the alias of "flat.cs" and resolves
4514 * unconditionally rather than probing "flat.ph", because a model is squashed
4515 * in order to express what only the routing encoding carries), and "moment3"
4516 * is the three-moment distribution pass over the routing layers. "default"
4517 * is the srvn alias; an unrecognised method name takes "srvn.cs".
4518 */
4519 static std::string ln_requested_method(const std::string& method) {
4520 std::string m;
4521 for (char c : method) m += static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
4522 if (m.empty() || m == "srvn" || m == "default" || m == "auto") return "srvn";
4523 if (m == "srvn.ph" || m == "ph") return "srvn.ph";
4524 if (m == "srvn.cs" || m == "srvncs" || m == "cs") return "srvn.cs";
4525 if (m == "flat.cs" || m == "flatcs" || m == "flat" || m == "squashed") return "flat.cs";
4526 if (m == "flat.ph" || m == "flatph" || m == "squashed.ph") return "flat.ph";
4527 if (m == "moment3") return "moment3";
4528 // 'nlp' names NO layering: the whole model is one program over the QD-AMVA laws
4529 if (m == "nlp" || m == "qdamva" || m == "qd-amva") return "nlp";
4530 // An unrecognised token takes the routing encoding, which is what every
4531 // name other than "moment3" resolved to before the alias existed.
4532 return "srvn.cs";
4533 }
4534
4535 /**
4536 * Refuse a warm start the composed phase-type layers cannot take: both seeds
4537 * solve for means, so there is no phase distribution in either to start them from.
4538 */
4539 void assert_warmstart_encoding() const {
4540 if (!is_ph_encoding() || opt.warmstart.empty()) return;
4541 throw InputError("config['warmstart']='" + opt.warmstart + "' cannot seed method='" + lnmethod +
4542 "': its layers carry a COMPOSED PHASE-TYPE service law and the seed solves for "
4543 "means, so there is no phase distribution to start it from. Use method='srvn.cs' "
4544 "for the same layering under the routing encoding, which those means do "
4545 "parameterize.");
4546 }
4547
4548 /**
4549 * config.warmstart and the nlp keys, validated before anything is built.
4550 * The program and lqn_mol are double precision by construction, so another
4551 * arithmetic is refused rather than handed a double answer under its name.
4552 */
4553 void validate_nlp_options() const {
4554 const bool nlp = ln_requested_method(opt.method) == "nlp";
4555 if (!opt.warmstart.empty()) {
4556 if (opt.warmstart != "nlp" && opt.warmstart != "mol")
4557 throw InputError("config['warmstart'] takes 'nlp', 'mol' or None, got '" + opt.warmstart +
4558 "'. 'nlp' seeds the layered fixed point with the QD-AMVA program's solution "
4559 "and 'mol' with the Method of Layers'; None starts it from the model's own "
4560 "host demands.");
4561 if (nlp)
4562 throw InputError("config['warmstart']='" + opt.warmstart +
4563 "' is a starting point for a LAYERED method, and method='nlp' runs no "
4564 "iteration to start. Drop one of the two.");
4565 }
4566 if ((nlp || !opt.warmstart.empty()) && !std::is_same<T, double>::value)
4567 throw UnsupportedError(ErrorKind{"Arithmetic"},
4568 std::string(nlp ? "SolverLN: method='nlp'" : "SolverLN: config.warmstart") +
4569 " roots a double-precision program, so it has no exact answer to give; rerun with "
4570 "--arith double");
4571 }
4572
4573 /** The double value of v as T. */
4574 static T fromd(double v) { return num_traits<T>::from_double(v); }
4575
4576 /** The program's root under the solver's nlp options, and the program itself; python ns['solve']. */
4577 std::vector<double> nlp_root(::line::lqn::NlpProgram& P) const {
4578 P = nlp_program();
4579 std::vector<double> x = P.solve(opt.nlp_warm, opt.nlp_maxiter).x;
4580 for (double& v : x) v = std::max(v, 0.0);
4581 return x;
4582 }
4583
4584 /** The share of its host an activity holds: busy servers at a delay, a busy fraction otherwise. */
4585 static std::vector<double> nlp_act_util(const ::line::lqn::NlpProgram& P, const std::vector<double>& Xa) {
4586 std::vector<double> u(P.NA, 0.0);
4587 for (std::size_t a = 0; a < P.NA; ++a) {
4588 const std::size_t h = P.task_host[P.act_task[a]];
4589 const double busy = P.act_demand[a] * Xa[a];
4590 u[a] = P.host_delay[h] ? busy : busy / P.host_maxmult[h];
4591 }
4592 return u;
4593 }
4594
4595 /**
4596 * method='nlp', python solver_ln_nlp_analyzer: root the program and place its
4597 * blocks on the LQN index space. A processor reports Util only, a task Tput,
4598 * QLen, Util and ResidT, an entry Tput, RespT, QLen and Util, an activity all
4599 * but ArvR; what stays undefined is what the layered path leaves undefined.
4600 */
4601 LnSolution<T> nlp_analyzer() {
4602 using P_ = ::line::lqn::NlpProgram;
4603 P_ P;
4604 const std::vector<double> x = nlp_root(P);
4605 const double obj = P.objective(x);
4606 nlp_solution_ = x;
4607 nlp_objective_ = obj;
4608 hasconverged = P.solved(x);
4609 did_converge = hasconverged;
4610
4611 LnSolution<T> s;
4612 const std::size_t N = lqn.nidx;
4613 auto blank = [&](std::vector<T>& v, std::vector<bool>& d) {
4614 v.assign(N + 1, Tzero());
4615 d.assign(N + 1, false);
4616 };
4617 blank(s.QN, s.defined_Q);
4618 blank(s.UN, s.defined_U);
4619 blank(s.RN, s.defined_R);
4620 blank(s.TN, s.defined_T);
4621 blank(s.AN, s.defined_A);
4622 blank(s.WN, s.defined_W);
4623 auto put = [&](std::vector<T>& v, std::vector<bool>& d, std::size_t i, double val) {
4624 v[i] = fromd(val);
4625 d[i] = true;
4626 };
4627 const std::vector<double> Xe = P.block(x, P_::XE), Xa = P.block(x, P_::XA), W = P.block(x, P_::W),
4628 S = P.block(x, P_::S), R = P.block(x, P_::R);
4629 const std::vector<double> util_a = nlp_act_util(P, Xa);
4630 for (std::size_t a = 0; a < P.NA; ++a) {
4631 double resp = W[a];
4632 for (std::size_t c : P.calls_of_act[a]) resp += P.call_mean[c] * R[c];
4633 const std::size_t aidx = lqn.ashift + a + 1;
4634 put(s.TN, s.defined_T, aidx, Xa[a]);
4635 put(s.RN, s.defined_R, aidx, resp);
4636 put(s.QN, s.defined_Q, aidx, Xa[a] * resp);
4637 put(s.UN, s.defined_U, aidx, util_a[a]);
4638 put(s.WN, s.defined_W, aidx, P.act_visits[a] * W[a]);
4639 }
4640 for (std::size_t e = 0; e < P.NE; ++e) {
4641 const std::size_t eidx = lqn.eshift + e + 1;
4642 double u = 0.0;
4643 for (std::size_t a = 0; a < P.NA; ++a)
4644 if (P.act_entry[a] == e) u += util_a[a];
4645 put(s.TN, s.defined_T, eidx, Xe[e]);
4646 put(s.RN, s.defined_R, eidx, S[e]);
4647 put(s.QN, s.defined_Q, eidx, Xe[e] * S[e]);
4648 put(s.UN, s.defined_U, eidx, u);
4649 }
4650 for (std::size_t t = 0; t < P.NT; ++t) {
4651 double tn = 0.0, qn = 0.0, un = 0.0, wn = 0.0;
4652 for (std::size_t e = 0; e < P.NE; ++e)
4653 if (P.entry_task[e] == t) {
4654 tn += Xe[e];
4655 qn += Xe[e] * S[e];
4656 }
4657 for (std::size_t a = 0; a < P.NA; ++a)
4658 if (P.act_task[a] == t) {
4659 un += util_a[a];
4660 wn += P.act_visits[a] * W[a];
4661 }
4662 const std::size_t tidx = lqn.tshift + t + 1;
4663 put(s.TN, s.defined_T, tidx, tn);
4664 put(s.QN, s.defined_Q, tidx, qn);
4665 put(s.UN, s.defined_U, tidx, un);
4666 put(s.WN, s.defined_W, tidx, wn);
4667 }
4668 for (std::size_t h = 0; h < P.NH; ++h) {
4669 double un = 0.0;
4670 for (std::size_t a : P.acts_of_host[h]) un += util_a[a];
4671 put(s.UN, s.defined_U, lqn.hshift + h + 1, un);
4672 }
4673 for (std::size_t i = 1; i <= N; ++i)
4674 if (ignore[i]) {
4675 put(s.QN, s.defined_Q, i, 0.0);
4676 put(s.UN, s.defined_U, i, 0.0);
4677 put(s.RN, s.defined_R, i, 0.0);
4678 put(s.TN, s.defined_T, i, 0.0);
4679 put(s.AN, s.defined_A, i, 0.0);
4680 put(s.WN, s.defined_W, i, 0.0);
4681 }
4682 s.iterations = 0;
4683 s.converged = hasconverged;
4684 if (!hasconverged)
4685 s.warning = "method='nlp' did not reach a root of the QD-AMVA laws (objective " +
4686 ::line::lqn::nlp_detail::fmt("%.3e", obj) + " over " + std::to_string(P.NRES) +
4687 " residuals); the reported means satisfy the linear relations but not every congestion "
4688 "law. solve() already escalated the warm start to 100 sweeps, so raise "
4689 "config['nlp_warm'] past that to start it further along.";
4690 return s;
4691 }
4692
4693 /** The surrogate client delay law of update_think_times, at a given busy-thread count. */
4694 void seed_think_time(std::size_t tidx, double X, double busy, double z, bool inf, double mult) {
4695 double nj = 0.0;
4696 for (std::size_t c = 1; c <= NT(); ++c) nj = std::max(nj, njobs(tidx, c));
4697 const double val = inf ? (nj - busy) / X - z : nj * std::fabs(1.0 - busy / mult) / X - z;
4698 const double th = std::max(GlobalConstants::Zero, std::max(0.0, val) + setup_charge(tidx));
4699 thinkt[tidx] = fromd(th);
4700 if (th + z > 0) thinktproc[tidx] = Distrib<T>::exp_mean(fromd(th + z));
4701 }
4702
4703 /** Fit the seeded means as exponential laws, as both python seeds do. */
4704 void seed_processes() {
4705 for (std::size_t i = 1; i <= lqn.nidx; ++i)
4706 if (dbl(servt[i]) > 0) servtproc[i] = Distrib<T>::exp_mean(servt[i]);
4707 for (std::size_t c = 1; c <= lqn.ncalls; ++c)
4708 if (dbl(callservt[c]) > 0) callservtproc[c] = Distrib<T>::exp_mean(callservt[c]);
4709 }
4710
4711 /** Carry the seeded laws into the layers, the tail of post() without an iteration's results. */
4712 void seed_layers() {
4713 update_layers(0);
4714 for (std::size_t e : svc_reset) ensemble[e].refresh_rates();
4715 warmstarted_ = true;
4716 }
4717
4718 /**
4719 * warmstart='nlp', python ln_nlp_warm_start: seed the LAYERED iterate with
4720 * the program's service, residence, throughput and surrogate delays. The
4721 * iteration then runs normally and converges to its own fixed point.
4722 */
4723 void nlp_warm_start() {
4724 using P_ = ::line::lqn::NlpProgram;
4725 P_ P;
4726 const std::vector<double> x = nlp_root(P);
4727 const std::vector<double> Xe = P.block(x, P_::XE), Xa = P.block(x, P_::XA), W = P.block(x, P_::W),
4728 S = P.block(x, P_::S), R = P.block(x, P_::R), BC = P.block(x, P_::BC),
4729 BR = P.block(x, P_::BR);
4730 const std::vector<double> util_a = nlp_act_util(P, Xa);
4731 for (std::size_t a = 0; a < P.NA; ++a) {
4732 const std::size_t idx = lqn.ashift + a + 1;
4733 double st = W[a];
4734 for (std::size_t c : P.calls_of_act[a]) st += P.call_mean[c] * R[c];
4735 servt[idx] = fromd(st);
4736 residt[idx] = fromd(P.act_visits[a] * W[a]);
4737 tput[idx] = fromd(Xa[a]);
4738 util[idx] = fromd(util_a[a]);
4739 }
4740 for (std::size_t e = 0; e < P.NE; ++e) {
4741 const std::size_t idx = lqn.eshift + e + 1;
4742 servt[idx] = residt[idx] = fromd(S[e]);
4743 tput[idx] = fromd(Xe[e]);
4744 }
4745 for (std::size_t t = 0; t < P.NT; ++t) {
4746 double x_t = 0.0;
4747 for (std::size_t e = 0; e < P.NE; ++e)
4748 if (P.entry_task[e] == t) x_t += Xe[e];
4749 tput[lqn.tshift + t + 1] = fromd(x_t);
4750 }
4751 for (std::size_t c = 0; c < P.NC; ++c) {
4752 callservt[c + 1] = fromd(R[c]);
4753 callresidt[c + 1] = fromd(P.call_mean[c] * R[c]);
4754 }
4755 seed_processes();
4756 // the surrogate delays: BC(c) is call c's hold on its callee, BR(r) the threads of reference task r held
4757 for (std::size_t t = 0; t < P.NT; ++t) {
4758 const std::size_t idx = lqn.tshift + t + 1;
4759 const double X = dbl(tput[idx]);
4760 if (X <= GlobalConstants::Zero) continue;
4761 const auto r = std::find(P.ref_tasks.begin(), P.ref_tasks.end(), t);
4762 double busy = 0.0;
4763 if (r != P.ref_tasks.end()) {
4764 busy = BR[std::size_t(r - P.ref_tasks.begin())];
4765 } else {
4766 for (std::size_t c : P.calls_into_task[t]) busy += BC[c];
4767 }
4768 const double mult = P.task_mult[t];
4769 seed_think_time(idx, X, busy, P.task_think[t],
4770 lqn.sched[idx] == SchedStrategy::INF || std::isinf(mult), mult);
4771 }
4772 seed_layers();
4773 }
4774
4775 /**
4776 * warmstart='mol', python ln_mol_warm_start: seed the LAYERED iterate with
4777 * lqn_mol's converged state. lqn_mol serves entry-only models, so each
4778 * entry's single activity takes the entry's whole execution.
4779 */
4780 void mol_warm_start() {
4781 if constexpr (num_traits<T>::has_transcendental) {
4782 ::line::lqn::LqnMolOptions mo;
4783 mo.iter_max = opt.mol_iter_max;
4784 mo.iter_tol = opt.mol_iter_tol;
4785 mo.relax_factor = opt.mol_relax_factor;
4786 const ::line::lqn::LqnMolResult<T> m = ::line::lqn::lqn_mol(lqn, mo);
4787 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
4788 const std::size_t eidx = lqn.eshift + e;
4789 const std::size_t aidx = lqn.actsof[eidx].at(0);
4790 servt[eidx] = residt[eidx] = m.info.servt[eidx];
4791 tput[eidx] = m.TN[eidx];
4792 servt[aidx] = m.info.servt[eidx];
4793 residt[aidx] = m.info.residt[eidx];
4794 tput[aidx] = m.TN[eidx];
4795 util[aidx] = m.UN[eidx];
4796 }
4797 for (std::size_t t = 1; t <= lqn.ntasks; ++t) tput[lqn.tshift + t] = m.TN[lqn.tshift + t];
4798 for (std::size_t c = 1; c <= lqn.ncalls; ++c) {
4799 double y = dbl(lqn.callproc_mean[c]);
4800 if (std::isnan(y)) y = 0.0;
4801 callservt[c] = m.info.callservt[c];
4802 callresidt[c] = T(fromd(y) * m.info.callservt[c]);
4803 }
4804 seed_processes();
4805 // lqn_mol's own thinkt is a submodel's Z, so SolverLN's law is applied to its busy threads instead
4806 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
4807 const std::size_t tidx = lqn.tshift + t;
4808 const double X = dbl(m.TN[tidx]);
4809 if (X <= GlobalConstants::Zero) continue;
4810 double z = 0.0;
4811 if (tidx < lqn.think.size() && !lqn.think[tidx].disabled) {
4812 z = dbl(lqn.think[tidx].mean);
4813 if (!std::isfinite(z) || z < 0.0) z = 0.0;
4814 }
4815 double mult = tidx < lqn.mult.size() ? lqn.mult[tidx] : 1.0;
4816 if (mult == 0.0) mult = 1.0;
4817 seed_think_time(tidx, X, dbl(m.QN[tidx]), z,
4818 lqn.sched[tidx] == SchedStrategy::INF || !std::isfinite(mult),
4819 std::max(1.0, mult));
4820 }
4821 seed_layers();
4822 } else {
4823 // validate_nlp_options refuses this arithmetic before anything is built
4824 throw UnsupportedError(ErrorKind{"Arithmetic"},
4825 "SolverLN: config.warmstart='mol' needs transcendental arithmetic; rerun with --arith double");
4826 }
4827 }
4828
4829 /** True when the layers are the collapsed phase-type ones of "srvn.ph". */
4830 bool is_srvn_ph() const { return lnmethod == "srvn.ph"; }
4831
4832 /**
4833 * True when the layers carry the COMPOSED phase-type server law rather than
4834 * the routing encoding of the activity graph, under either layering. The
4835 * encoding, not the layering, decides which update and reconstruction passes
4836 * run, so every such dispatch asks this and not for one method name.
4837 */
4838 bool is_ph_encoding() const { return lnmethod == "srvn.ph" || lnmethod == "flat.ph"; }
4839
4840 /** True under the flat (squashed) layering, whichever encoding it carries. */
4841 bool is_flat_layering() const { return lnmethod == "flat.cs" || lnmethod == "flat.ph"; }
4842
4843 /**
4844 * Station of layer L that stands for LQN element ELEM, falling back to the
4845 * layer's own server when ELEM is not a server there. Under "srvn" the
4846 * fallback is the answer for every element; under "flat.cs" it is the map
4847 * that tells the many servers of one layer apart.
4848 */
4849 static std::size_t station_idx_of(const qn::Layer<T>& L, std::size_t elem) {
4850 if (elem >= 1 && elem < L.server_idx_of.size() && L.server_idx_of[elem] != 0)
4851 return L.server_idx_of[elem];
4852 return L.serverIdx;
4853 }
4854
4855 /**
4856 * Station of layer L that class K (0-based) is served at: the PROCESSOR of
4857 * an activity, the CALLED TASK of a call, the layer's own server otherwise.
4858 */
4859 std::size_t station_idx_of_class(const qn::Layer<T>& L, std::size_t k) const {
4860 const int kind = L.classes[k].attr_kind;
4861 const std::size_t a = L.classes[k].attr_idx;
4862 if (kind == int(LqnElement::ACTIVITY))
4863 return station_idx_of(L, lqn.parent[lqn.parent[a]]);
4864 if (kind == int(LqnElement::CALL))
4865 return station_idx_of(L, lqn.parent[lqn.callpair_dst[a]]);
4866 return L.serverIdx;
4867 }
4868
4869 /**
4870 * Answer whether "srvn.ph" can serve this model, without disturbing the
4871 * solver.
4872 *
4873 * Both the feature gate and the series-parallel reduction can refuse, and
4874 * the second only finds out by composing the per-entry workflows -- work the
4875 * build then reuses, since those laws do not depend on the iterate.
4876 */
4877 bool probe_srvn_ph() {
4878 try {
4879 ph_assert_supported();
4880 ph_init_laws();
4881 ph_laws_ready = true;
4882 return true;
4883 } catch (const std::exception&) {
4884 ph_laws_ready = false;
4885 return false;
4886 }
4887 }
4888
4889 /** One two-station layer, and the caller classes that cycle through it. */
4890 struct PHLayer {
4891 std::size_t idx = 0;
4892 bool ishost = false;
4893 std::vector<std::size_t> callers;
4894 /** 1-based class index of each caller task, 0 when absent. */
4895 std::vector<std::size_t> class_of_caller;
4896 std::size_t nreplicas = 1;
4897 /** 1-based station indices of the server replicas. */
4898 std::vector<std::size_t> qstations;
4899 /** Mean of the law each class is currently served with, by class index. */
4900 std::vector<T> svcmean_by_class;
4901 /** (class index, entry index) or (class index, -call index). */
4902 std::vector<std::pair<std::size_t, long>> open_arrivals;
4903 /**
4904 * Closed population of the MODEL this server sits in. Under "flat.ph"
4905 * that is every caller of the single network, not only the callers of
4906 * this one station, so it is recorded here rather than recomputed.
4907 */
4908 double npop = 0.0;
4909 };
4910
4911 // per-entry workflows and their composed laws
4912 std::vector<workflow::Workflow<T>> ph_wf, ph_wfhost;
4913 std::vector<std::unordered_map<std::size_t, T>> ph_execs;
4914 std::vector<bool> ph_has_wf;
4915 std::vector<workflow::PhLaw<T>> ph_hostlaw, ph_entrylaw;
4916 std::vector<T> ph_hostmean, ph_entrymean, ph_entryscv;
4917 std::vector<T> ph_share, ph_overlap, ph_setupshare, ph_xdemand;
4918 Matrix<T> ph_ncalls, ph_calltime;
4919 std::vector<T> ph_procresid, ph_actthinkt, ph_calltotal;
4920 std::vector<T> ph_procsave; ///< overlap an AND fork saves on the processor
4921 Matrix<T> ph_callsave; ///< [caller task, called task] overlap saved on a callee
4922 std::vector<PHLayer> ph_layers; ///< by element index, empty where absent
4923 std::vector<bool> ph_has_layer;
4924
4925 /** Mean of an activity's own think time, 0 when it declares none. */
4926 T act_think_time(std::size_t aidx) const {
4927 if (aidx >= lqn.actthink.size() || lqn.actthink[aidx].disabled) return Tzero();
4928 const double m = dbl(lqn.actthink[aidx].mean);
4929 if (!std::isfinite(m) || m <= GlobalConstants::FineTol) return Tzero();
4930 return lqn.actthink[aidx].mean;
4931 }
4932
4933 /** SetupTask cold-start charge per task, as last computed by setup_charge(tidx, S). */
4934 std::unordered_map<std::size_t, double> setupcharge;
4935
4936 /**
4937 * Mean extra time one request of task TIDX spends because threads power
4938 * down, 0 when it declares no setup.
4939 *
4940 * A SetupTask powers a thread down when its delay-off countdown expires while
4941 * it is idle, and a request that finds no warm thread waits for a setup. The
4942 * task's thread pool is therefore an M/M/k queue with setup and delayed-off
4943 * servers (Gandhi, Harchol-Balter and Adan, Performance Evaluation 67(11),
4944 * 2010), with k the multiplicity and the admission rules of the LDES engine,
4945 * and it is solved EXACTLY by mam::qbd_setupdelayoff_mmk, at the callers'
4946 * population N and complementary delay Z = (N - Q)/X of the layer where TIDX
4947 * is the server (or at its arrival rate X when a visiting class is open), and
4948 * at the base service time S of a request, i.e. the entry service before any
4949 * charge. The layer serves the pool as a plain M/M/k, so the charge is the
4950 * EQUIVALENT extra service,
4951 *
4952 * charge = S' - S, with R_M/M/k(S') = QN/X (setup, delay-off),
4953 *
4954 * S' found by bisection. Subtracting the two response times instead counted
4955 * the queueing behind a setup twice, once in the chain and again in the
4956 * layer, and ran the one-thread model of test_ln_setup 5.6% below LDES. The
4957 * result is continuous in the load and exact at any thread count; it
4958 * replaces a closure that assumed max(1, b) hot threads at offered load b,
4959 * which dropped the charge to zero above one busy thread and oscillated at
4960 * the kink (BUG-78).
4961 *
4962 * Called with S, it computes the charge from the current layer solution and
4963 * stores it, as the metric update does once per iteration; called with NaN,
4964 * it returns the stored value, so every consumer of one iteration charges
4965 * the same cold start. Before anything has been computed the thread is down
4966 * when the first request arrives, and the charge is the setup mean. Twin of
4967 * MATLAB lqn_setup_charge.m, the JAR SolverLN.setupCharge and the Python
4968 * SolverLN._setup_charge.
4969 */
4970 double setup_charge(std::size_t tidx, double S = std::numeric_limits<double>::quiet_NaN()) {
4971 if (tidx >= lqn.hassetup.size() || !lqn.hassetup[tidx]) return 0.0;
4972 const double s = tidx < lqn.setuptime.size() && !lqn.setuptime[tidx].disabled
4973 ? dbl(lqn.setuptime[tidx].mean) : 0.0;
4974 const double d = tidx < lqn.delayofftime.size() && !lqn.delayofftime[tidx].disabled
4975 ? dbl(lqn.delayofftime[tidx].mean) : 0.0;
4976 if (!(s > GlobalConstants::FineTol) || !(d > GlobalConstants::FineTol)) return 0.0;
4977 const double mult = lqn.mult[tidx];
4978 if (!std::isfinite(mult) || mult <= 0.0) return 0.0;
4979 if (std::isnan(S)) {
4980 const auto it = setupcharge.find(tidx);
4981 return it == setupcharge.end() ? s : it->second;
4982 }
4983 const double c = setup_charge_exact(tidx, static_cast<int>(std::llround(mult)), S, s, d);
4984 setupcharge[tidx] = c;
4985 return c;
4986 }
4987
4988 /** The charge of setup_charge from the layer where TIDX is the server. */
4989 double setup_charge_exact(std::size_t tidx, int k, double S, double s, double d) const {
4990 // nothing has arrived yet, so the thread is down when the first does
4991 if (!(S > GlobalConstants::FineTol) || tidx >= idxhash.size() || idxhash[tidx] < 0
4992 || results.empty() || std::size_t(idxhash[tidx]) >= results.back().size())
4993 return s;
4994 const std::size_t e = std::size_t(idxhash[tidx]);
4995 const qn::Layer<T>& L = ensemble[e];
4996 const LayerResult<T>& r = results.back()[e];
4997 if (r.TN.rows() == 0 || r.QN.rows() == 0) return s;
4998 const std::size_t ts = station_idx_of(L, tidx) - 1;
4999 // per replica: the layer's station is one representative replica
5000 double X = 0.0, Q = 0.0;
5001 for (std::size_t c = 0; c < L.nclasses && c < r.TN.cols(); ++c) {
5002 const double tn = dbl(r.TN(ts, c)), qn = dbl(r.QN(ts, c));
5003 if (!std::isnan(tn)) X += tn;
5004 if (!std::isnan(qn)) Q += qn;
5005 }
5006 if (!std::isfinite(X) || X <= GlobalConstants::FineTol) return s;
5007 // N is the population of every CHAIN that visits the station: under
5008 // 'srvn.cs' a caller's jobs sit in a class of the chain other than the
5009 // one served here
5010 double N = 0.0;
5011 bool isopen = false;
5012 for (std::size_t ch = 0; ch < L.inchain.size(); ++ch) {
5013 bool visits = false;
5014 double pop = 0.0;
5015 for (std::size_t c1 : L.inchain[ch]) {
5016 if (c1 < 1 || c1 > L.nclasses || c1 > r.TN.cols()) continue;
5017 if (dbl(r.TN(ts, c1 - 1)) > 0.0) visits = true;
5018 pop += L.classes[c1 - 1].population;
5019 }
5020 if (!visits) continue;
5021 if (std::isfinite(pop)) N += pop;
5022 else isopen = true;
5023 }
5024 const double mu = 1.0 / S;
5025 auto scv_of = [](const std::vector<Distrib<T>>& procs, std::size_t i) {
5026 if (i >= procs.size() || procs[i].disabled) return 1.0;
5027 const double v = dbl(procs[i].scv);
5028 return (std::isfinite(v) && v > 0.0) ? v : 1.0;
5029 };
5030 const double ascv = scv_of(lqn.setuptime, tidx);
5031 const double bscv = scv_of(lqn.delayofftime, tidx);
5032 // the layer serves the pool as a plain M/M/k, so the charge is what that
5033 // station needs on top of S to answer in the setup pool's response time
5034 if (isopen || N <= 0.0) {
5035 if (X >= k * mu) return 0.0; // a saturated pool never idles, so no thread powers down
5036 const mam::SetupDelayoffMMk<double> res = mam::qbd_setupdelayoff_mmk<double>(
5037 k, std::numeric_limits<double>::infinity(), X, mu, 1.0 / s, ascv, 1.0 / d, bscv);
5038 if (!(res.XN > GlobalConstants::FineTol)) return s;
5039 return mmk_equiv_service([&](double Sp) { return mmk_open_resp(k, X, 1.0 / Sp); }, S,
5040 res.QN / res.XN, k / X) - S;
5041 }
5042 const int pop = static_cast<int>(std::llround(N));
5043 const double Z = std::max((pop - std::min(Q, double(pop))) / X, GlobalConstants::FineTol);
5044 const mam::SetupDelayoffMMk<double> res =
5045 mam::qbd_setupdelayoff_mmk<double>(k, pop, Z, mu, 1.0 / s, ascv, 1.0 / d, bscv);
5046 if (!(res.XN > GlobalConstants::FineTol)) return s;
5047 return mmk_equiv_service([&](double Sp) { return mmk_closed_resp(k, pop, Z, 1.0 / Sp); }, S,
5048 res.QN / res.XN, res.QN / res.XN) - S;
5049 }
5050
5051 /**
5052 * Service time S' >= S at which the M/M/k response time RESP(S') equals Rs,
5053 * found by bisection on [S, hi]; S itself when the pool already answers in Rs.
5054 */
5055 template <class F>
5056 static double mmk_equiv_service(const F& resp, double S, double Rs, double hi) {
5057 double lo = S;
5058 if (resp(lo) >= Rs) return S;
5059 for (int it = 0; it < 200; ++it) {
5060 const double mid = 0.5 * (lo + hi);
5061 if (resp(mid) < Rs) lo = mid;
5062 else hi = mid;
5063 if (hi - lo <= 1e-12 * hi) break;
5064 }
5065 return 0.5 * (lo + hi);
5066 }
5067
5068 /**
5069 * Mean response time of an M/M/k station visited by N customers that spend
5070 * a mean Z elsewhere: the birth-death chain of the machine-repairman model.
5071 */
5072 static double mmk_closed_resp(int k, int N, double Z, double mu) {
5073 std::vector<double> p(std::size_t(N) + 1, 0.0);
5074 p[0] = 1.0;
5075 for (int n = 1; n <= N; ++n) {
5076 p[n] = p[n - 1] * ((N - n + 1) / Z) / (std::min(n, k) * mu);
5077 if (p[n] > 1e250)
5078 for (int i = 0; i <= n; ++i) p[i] /= p[n];
5079 }
5080 double tot = 0.0, Qs = 0.0, Xs = 0.0;
5081 for (int n = 0; n <= N; ++n) tot += p[n];
5082 for (int n = 0; n <= N; ++n) {
5083 Qs += n * p[n] / tot;
5084 Xs += (N - n) / Z * p[n] / tot;
5085 }
5086 return Qs / Xs;
5087 }
5088
5089 /** Mean response time of an open M/M/k queue (Erlang C). */
5090 static double mmk_open_resp(int k, double lam, double mu) {
5091 const double a = lam / mu, rho = a / k;
5092 double term = 1.0, acc = 1.0;
5093 for (int i = 1; i < k; ++i) {
5094 term *= a / i;
5095 acc += term;
5096 }
5097 const double tk = term * a / k;
5098 const double C = tk / (1.0 - rho) / (acc + tk / (1.0 - rho));
5099 return 1.0 / mu + C / (k * mu - lam);
5100 }
5101
5102 /**
5103 * Probability that a request for entry EIDX finds its task's thread off.
5104 * ONE closure for both methods: setup_charge returns p*s, so p is that over
5105 * s, evaluated at M1, the mean of the composed entry law before any setup.
5106 * It also answers p = 1 during construction, before the first layer solve.
5107 */
5108 double ph_setup_prob(std::size_t eidx, double m1) {
5109 const std::size_t tidx = lqn.parent[eidx];
5110 if (tidx >= lqn.hassetup.size() || !lqn.hassetup[tidx]) return 0.0;
5111 const double s = tidx < lqn.setuptime.size() && !lqn.setuptime[tidx].disabled
5112 ? dbl(lqn.setuptime[tidx].mean) : 0.0;
5113 const double d = tidx < lqn.delayofftime.size() && !lqn.delayofftime[tidx].disabled
5114 ? dbl(lqn.delayofftime[tidx].mean) : 0.0;
5115 if (!(s > GlobalConstants::FineTol) || !(d > GlobalConstants::FineTol)) return 0.0;
5116 return std::min(1.0, std::max(0.0, setup_charge(tidx, m1) / s));
5117 }
5118
5119 /** Divisor that scales a processor utilization into [0,1]. */
5120 double ph_host_servers(std::size_t hidx) const {
5121 if (lqn.sched[hidx] == SchedStrategy::INF) return 1.0;
5122 const double m = lqn.maxmult[hidx];
5123 return (std::isfinite(m) && m > 0.0) ? m : 1.0;
5124 }
5125
5126 /** True when any task calls entry EIDX, synchronously or not. */
5127 bool ph_any_caller_of(std::size_t eidx) const {
5128 return lqn.issynccaller.any_col(eidx) || lqn.isasynccaller.any_col(eidx);
5129 }
5130
5131 /**
5132 * True when an entry arrival is the ONLY way requests reach task TIDX.
5133 * "srvn.ph" refuses forwarding calls outright, so sync/async callers are the
5134 * whole test.
5135 */
5136 bool ph_open_arrival_only(std::size_t tidx) const {
5137 if (lqn.isref[tidx]) return false;
5138 for (std::size_t eidx : lqn.entriesof[tidx])
5139 if (ph_any_caller_of(eidx)) return false;
5140 for (std::size_t eidx : lqn.entriesof[tidx])
5141 if (lqn.has_arrival[eidx]) return true;
5142 return false;
5143 }
5144
5145 /** Asynchronous calls whose target entry belongs to TIDX. */
5146 std::vector<std::size_t> ph_async_calls_into(std::size_t tidx) const {
5147 std::vector<std::size_t> out;
5148 for (std::size_t cidx = 1; cidx <= lqn.ncalls; ++cidx) {
5149 if (lqn.calltype[cidx] != CallType::ASYNC) continue;
5150 for (std::size_t e : lqn.entriesof[tidx])
5151 if (lqn.callpair_dst[cidx] == e) { out.push_back(cidx); break; }
5152 }
5153 return out;
5154 }
5155
5156 /**
5157 * True when the per-layer "srvn.ph" builder gives task TIDX a task layer: the
5158 * same test the build loop applies, so an entry arrival moved off the host
5159 * layer always lands on a layer that is built.
5160 */
5161 bool ph_has_task_layer(std::size_t tidx) const {
5162 if (ignore[tidx] || lqn.isref[tidx]) return false;
5163 for (std::size_t ct = 1; ct <= lqn.ntasks; ++ct) {
5164 const std::size_t c = lqn.tshift + ct;
5165 if (c == tidx || ignore[c]) continue;
5166 for (std::size_t e : lqn.entriesof[tidx])
5167 if (lqn.issynccaller.get(c, e)) return true;
5168 }
5169 return !ph_async_calls_into(tidx).empty();
5170 }
5171
5172 /**
5173 * Features the collapsed layer cannot represent are refused by name rather
5174 * than silently degraded.
5175 */
5176 void ph_assert_supported(bool flat = false) const {
5177 // The list is a property of the ENCODING, so it is the same under either
5178 // layering; what the squashing adds on top is refused in ph_flat_server_set.
5179 const std::string mname = flat ? "flat.ph" : "srvn.ph";
5180 // PHASE 2 IS ASKED HERE AND NOWHERE ELSE. `has_phase2` is built during
5181 // layering rather than being a property of the model, so the report twin
5182 // below cannot ask it; every other rule is shared with it.
5183 if (has_phase2)
5184 throw UnsupportedError(ErrorKind{"Activity"},
5185 "method='" + mname + "' does not support second-phase activities: the composed "
5186 "entry law has no reply point. Use method='default'.");
5187 // ONE RULE LIST, TWO CALLERS: this throws what `ph_method_refusal`
5188 // returns, in the same order, so the run and a report cannot say
5189 // different things about one model. The squashing rules it also carries
5190 // for `flat.ph` are the ones `ph_flat_server_set` raises, which runs
5191 // before this on that path, so the message a caller sees is unchanged.
5192 const std::string why = ph_method_refusal(mname);
5193 if (!why.empty()) throw UnsupportedError(ErrorKind{"Model"}, why);
5194 }
5195
5196 /**
5197 * The same rules as a SENTENCE, so a report can withdraw a method it cannot run.
5198 *
5199 * ONE RULE LIST, TWO CALLERS. `ph_assert_supported` above answers the run
5200 * path by throwing; nothing answered the report, and `list_valid_methods`
5201 * returns the same eight names for every model, so every layered model was
5202 * offered every encoding and `srvn.ph`/`flat.ph` then threw on contact.
5203 *
5204 * PHASE 2 IS DELIBERATELY ABSENT. `has_phase2` is built during layering
5205 * rather than being a property of the model, so a gate cannot ask it without
5206 * doing the layering it is meant to precede; the run path still refuses it.
5207 *
5208 * @param method the concrete method name
5209 * @return empty string when the method can encode this model, else the reason
5210 */
5211 std::string ph_method_refusal(const std::string& method) const {
5212 if (method != "srvn.ph" && method != "flat.ph") return std::string();
5213 // The squashing refusals, `flat.ph` only: each carries PER-LAYER state
5214 // that one submodel cannot hold (ph_flat_server_set).
5215 if (method == "flat.ph") {
5216 for (std::size_t i = 1; i <= NT(); ++i) {
5217 if (lqn.repl[i] > 1.0)
5218 return "method='flat.ph' does not support replicated processors or tasks, "
5219 "whose replicas need a submodel each. Use method='srvn.ph'.";
5220 if (lqn.hassetup[i])
5221 return "method='flat.ph' does not support setup tasks, whose powered-down "
5222 "threads are per-layer state. Use method='srvn.ph'.";
5223 }
5224 }
5225 for (std::size_t cidx = 1; cidx <= lqn.ncalls; ++cidx)
5226 if (lqn.calltype[cidx] == CallType::FWD)
5227 return "method='" + method +
5228 "' does not support forwarding calls, whose target is not part of the "
5229 "caller's activity graph. Use method='default'.";
5230 for (std::size_t i = 1; i < lqn.iscache.size(); ++i)
5231 if (lqn.iscache[i])
5232 return "method='" + method +
5233 "' does not support cache tasks. Use method='default'.";
5234 for (std::size_t i = 1; i < lqn.hassetup.size(); ++i) {
5235 if (!lqn.hassetup[i]) continue;
5236 if (lqn.sched[i] == SchedStrategy::INF || !std::isfinite(lqn.mult[i]))
5237 return "method='" + method + "': task '" + lqn.names[i] +
5238 "' declares a setup time on an infinite-server task, which holds no "
5239 "thread to power down; give it a finite multiplicity.";
5240 }
5241 for (std::size_t i = 0; i < lqn.lincon_A.size(); ++i)
5242 if (lqn.lincon_A[i].rows() > 0)
5243 return "method='" + method +
5244 "' does not support admission constraints on a layer station. "
5245 "Use method='default'.";
5246 for (std::size_t i = 1; i < lqn.lldscaling.size(); ++i) {
5247 const char* fname = nullptr;
5248 if (!lqn.lldscaling[i].empty()) fname = "a load dependence";
5249 else if (lqn.cdscaling[i]) fname = "a class dependence";
5250 else if (lqn.jdscaling[i]) fname = "a joint dependence";
5251 else if (!lqn.pools[i].empty()) fname = "server pools";
5252 if (fname != nullptr)
5253 return "method='" + method +
5254 "' does not support queue-dependent service rates on a layer station ('" +
5255 lqn.names[i] + "' declares " + fname + "). Use method='srvn.cs'.";
5256 }
5257 return std::string();
5258 }
5259
5260 /** Build the per-entry workflows and the iteration-invariant processor law. */
5261 void ph_init_laws() {
5262 const std::size_t N = lqn.nidx;
5263 ph_wf.assign(N + 1, workflow::Workflow<T>("empty"));
5264 ph_wfhost.assign(N + 1, workflow::Workflow<T>("empty"));
5265 ph_execs.assign(N + 1, {});
5266 ph_has_wf.assign(N + 1, false);
5267 ph_hostlaw.assign(N + 1, workflow::PhLaw<T>());
5268 ph_entrylaw.assign(N + 1, workflow::PhLaw<T>());
5269 ph_hostmean.assign(N + 1, Tzero());
5270 ph_entrymean.assign(N + 1, Tzero());
5271 ph_entryscv.assign(N + 1, Tone());
5272 ph_share.assign(N + 1, Tzero());
5273 ph_overlap.assign(N + 1, Tone());
5274 ph_setupshare.assign(N + 1, Tzero());
5275 ph_xdemand.assign(N + 1, Tzero());
5276 ph_ncalls = Matrix<T>(N + 1, N + 1, Tzero());
5277 ph_calltime = Matrix<T>(N + 1, N + 1, Tzero());
5278 ph_procresid.assign(N + 1, Tzero());
5279 ph_actthinkt.assign(N + 1, Tzero());
5280 ph_calltotal.assign(N + 1, Tzero());
5281 ph_procsave.assign(N + 1, Tzero());
5282 ph_callsave = Matrix<T>(N + 1, N + 1, Tzero());
5283 ph_layers.assign(NT() + 1, PHLayer());
5284 ph_has_layer.assign(NT() + 1, false);
5285
5286 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
5287 const std::size_t eidx = lqn.eshift + e;
5288 const std::size_t tidx = lqn.parent[eidx];
5289 if (ignore[tidx]) continue;
5290 api::lqn::EntryWorkflow<T> ew = api::lqn::entry_workflow(lqn, eidx, true);
5291 ph_wf[eidx] = std::move(ew.wf);
5292 ph_execs[eidx] = ew.execs;
5293 ph_has_wf[eidx] = true;
5294 api::lqn::EntryWorkflow<T> eh = api::lqn::entry_workflow(lqn, eidx, false);
5295 ph_wfhost[eidx] = std::move(eh.wf);
5296 // the processor sees the WORK of concurrent branches, not their
5297 // elapsed time, so the host law serialises an AND fork
5298 ph_hostlaw[eidx] = api::lqn::serial_law(ph_wfhost[eidx]);
5299 ph_hostmean[eidx] =
5300 api::lqn::ph_moments(ph_hostlaw[eidx].alpha, ph_hostlaw[eidx].S).first;
5301 }
5302
5303 // until the first iteration reports throughputs, a task splits its
5304 // requests evenly over its entries
5305 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
5306 const std::size_t tidx = lqn.tshift + t;
5307 const std::size_t n = lqn.entriesof[tidx].size();
5308 if (n == 0) continue;
5309 for (std::size_t eidx : lqn.entriesof[tidx])
5310 ph_share[eidx] = num_traits<T>::from_double(1.0 / double(n));
5311 }
5312 }
5313
5314 /**
5315 * Law of the total time one execution of the issuing activity spends in call
5316 * CIDX: the geometric compound, of mean callproc_mean, of the response law
5317 * of the called entry. The response law is fitted to the response time
5318 * reported by the callee's layer and to the SCV of the callee's own composed
5319 * law, so no extra solver output is needed.
5320 */
5321 Distrib<T> ph_call_burst_law(std::size_t cidx) const {
5322 const double m = dbl(lqn.callproc_mean[cidx]);
5323 const std::size_t eidx = lqn.callpair_dst[cidx];
5325 const T R = T(callservt[cidx] / lqn.callproc_mean[cidx]);
5326 double scvd = dbl(ph_entryscv[eidx]);
5327 if (!std::isfinite(scvd) || scvd <= GlobalConstants::FineTol) scvd = 1.0;
5328 const T Rf = dbl(R) > GlobalConstants::FineTol
5329 ? R : num_traits<T>::from_double(GlobalConstants::FineTol);
5330 const Distrib<T> base = lang::aph_fit_mean_scv(Rf, num_traits<T>::from_double(scvd));
5331 const workflow::PhLaw<T> body = api::lqn::ph_law_of(base);
5332 const workflow::PhLaw<T> loop =
5333 workflow::Workflow<T>::compose_loop_geometric(body, lqn.callproc_mean[cidx]);
5334 return Distrib<T>::phase_type(loop.alpha, loop.S,
5336 }
5337
5338 /**
5339 * Station law of a composed workflow. A geometric loop over a body of two or
5340 * more phases closes a cycle in the phase graph, and a cyclic generator is a
5341 * PH and not an APH: no layer solver declares PH, so such a law is reduced
5342 * to the APH with the SAME first two moments. AMVA and NC read exactly those
5343 * two, so the reduction is lossless for them and is a two-moment fit for the
5344 * phase-aware layer solvers.
5345 */
5346 Distrib<T> ph_station_law(const workflow::PhLaw<T>& law) const {
5348 return Distrib<T>::phase_type(law.alpha, law.S, true);
5349 const std::pair<T, T> mm = api::lqn::ph_moments(law.alpha, law.S);
5350 return lang::aph_fit_mean_scv(mm.first, mm.second);
5351 }
5352
5353 /** The law of a single immediate phase, the empty-composition answer. */
5354 static workflow::PhLaw<T> ph_immediate_law() {
5355 workflow::PhLaw<T> out;
5356 out.alpha.assign(1, Tone());
5357 out.S = Matrix<T>(1, 1, num_traits<T>::from_double(-GlobalConstants::Immediate));
5358 return out;
5359 }
5360
5361 /** True when an activity of entry EIDX opens an AND fork, the only place the branches can overlap. */
5362 bool ph_has_and_fork(std::size_t eidx) const {
5363 for (std::size_t aidx : lqn.actsof[eidx])
5364 if (aidx < lqn.actposttype.size() && lqn.actposttype[aidx] == PrecedenceType::POST_AND) return true;
5365 return false;
5366 }
5367
5368 /**
5369 * True when the processor of entry EIDX's task serves one job at a time, so the
5370 * branches of an AND fork cannot run on it concurrently. Declared multiplicity,
5371 * not maxmult: maxmult caps a host by its tasks' threads, and a fork adds threads.
5372 */
5373 bool ph_single_server_host(std::size_t eidx) const {
5374 const std::size_t hidx = lqn.parent[lqn.parent[eidx]];
5375 if (lqn.sched[hidx] == SchedStrategy::INF) return false;
5376 const double m = lqn.mult[hidx];
5377 return std::isfinite(m) && m <= 1.0;
5378 }
5379
5380 /**
5381 * Servers of the processor of entry EIDX's task, i.e. how many activities of
5382 * one entry it can serve at once: infinite for an INF host or an unbounded
5383 * multiplicity. Declared multiplicity, as in ph_single_server_host.
5384 */
5385 double ph_entry_host_servers(std::size_t eidx) const {
5386 const std::size_t hidx = lqn.parent[lqn.parent[eidx]];
5387 if (lqn.sched[hidx] == SchedStrategy::INF) return std::numeric_limits<double>::infinity();
5388 const double m = lqn.mult[hidx];
5389 if (!std::isfinite(m)) return std::numeric_limits<double>::infinity();
5390 return std::max(m, 1.0);
5391 }
5392
5393 /**
5394 * Recompose the entry service laws from the current fixed-point iterate.
5395 *
5396 * The composed mean is NOT the sum of the leaf means when the graph forks:
5397 * the branches of an AND fork overlap, and the entry finishes with the last
5398 * of them. The ratio of the two, the overlap factor, is what the caller-side
5399 * aggregates are scaled by, so that the pieces of a cycle still add up to
5400 * the cycle.
5401 */
5402 void ph_compose_entry_laws() {
5403 const std::size_t N = lqn.nidx;
5404 std::vector<T> entry_setup_share(N + 1, Tzero());
5405 ph_overlap.assign(N + 1, Tone());
5406 std::vector<bool> hostserial(N + 1, false);
5407
5408 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
5409 const std::size_t eidx = lqn.eshift + e;
5410 if (!ph_has_wf[eidx]) continue;
5411 workflow::Workflow<T>& w = ph_wf[eidx];
5412 const std::unordered_map<std::size_t, T>& ex = ph_execs[eidx];
5413 T entrysum = Tzero(), procsum = Tzero(), pres = Tzero();
5414 for (std::size_t aidx : lqn.actsof[eidx]) {
5415 T m = T(residt[aidx] + act_think_time(aidx));
5416 const T xa = ex.at(aidx);
5417 procsum += T(xa * m);
5418 pres += T(xa * residt[aidx]);
5419 const double md = dbl(m);
5420 w.set_activity_demand_mean(
5421 lqn.names[aidx],
5423 ? m : num_traits<T>::from_double(GlobalConstants::FineTol));
5424 for (std::size_t cidx : lqn.callsof[aidx]) {
5425 if (lqn.calltype[cidx] != CallType::SYNC) continue;
5426 w.set_activity_demand(lqn.callhashnames[cidx], ph_call_burst_law(cidx));
5427 m = T(m + callservt[cidx]);
5428 }
5429 entrysum += T(xa * m);
5430 }
5431 workflow::PhLaw<T> law = api::lqn::ph_law_of(w.refresh_ph());
5432 std::pair<T, T> mm = api::lqn::ph_moments(law.alpha, law.S);
5433 T m1 = mm.first, scv = mm.second;
5434 // All activities of an entry run on ONE processor, so the branches of
5435 // an AND fork cannot overlap the processor residence they request
5436 // beyond what its servers can serve at once: with c servers the entry
5437 // takes at least procsum/c, and an infinite-server host bounds
5438 // nothing. The composed maximum is a lower bound on the entry service
5439 // time only above that. Where it falls below, the law is rescaled in
5440 // time to it, which keeps its shape, its SCV and its order. Charging
5441 // the full procsum on an INF host serialised the branches the host
5442 // runs side by side (test_ln_fork_openarrival: entry 1.0 against the
5443 // exact 0.8286).
5444 const double hservers = ph_entry_host_servers(eidx);
5445 if (std::isfinite(hservers)) {
5446 const T procfloor = T(procsum / num_traits<T>::from_double(hservers));
5447 if (dbl(procfloor) > dbl(m1) + GlobalConstants::FineTol) {
5448 const T f = T(m1 / procfloor);
5449 for (std::size_t i = 0; i < law.S.rows(); ++i)
5450 for (std::size_t j = 0; j < law.S.cols(); ++j) law.S(i, j) = T(law.S(i, j) * f);
5451 m1 = procfloor;
5452 }
5453 }
5454 // On a SINGLE-SERVER host that bound is not enough: the branches queue for
5455 // the one server, so their host demand is not overlapped at all and only the
5456 // rest of the entry is. The law is stretched in time by the overlap the host
5457 // lost, and every layer then charges the host serially (see the aggregates).
5458 if (ph_has_and_fork(eidx) && ph_single_server_host(eidx)) {
5459 hostserial[eidx] = true;
5460 if (dbl(entrysum) > GlobalConstants::FineTol) {
5461 const T add = T((Tone() - num_traits<T>::from_double(
5462 std::min(1.0, dbl(m1) / dbl(entrysum)))) * pres);
5463 if (dbl(add) > GlobalConstants::FineTol) {
5464 const T f = T(m1 / (m1 + add));
5465 for (std::size_t i = 0; i < law.S.rows(); ++i)
5466 for (std::size_t j = 0; j < law.S.cols(); ++j) law.S(i, j) = T(law.S(i, j) * f);
5467 m1 = T(m1 + add);
5468 }
5469 }
5470 }
5471 // A SetupTask powers a thread down when it goes idle, so a request may
5472 // find it off and pay a cold start before the entry runs at all. The
5473 // setup is not part of the activity graph and never enters the
5474 // series-parallel reduction: it is prefixed to the composed law
5475 // afterwards as the mixture p*(setup THEN entry) + (1-p)*entry, which
5476 // is again phase-type.
5477 const double p = ph_setup_prob(eidx, dbl(m1));
5478 if (p > GlobalConstants::FineTol) {
5479 const std::size_t tidx = lqn.parent[eidx];
5480 const double sm = dbl(lqn.setuptime[tidx].mean);
5481 double sscv = dbl(lqn.setuptime[tidx].scv);
5482 if (!std::isfinite(sscv) || sscv <= GlobalConstants::FineTol) sscv = 1.0;
5483 if (std::isfinite(sm) && sm > GlobalConstants::FineTol) {
5484 const workflow::PhLaw<T> sl = api::lqn::ph_law_of(lang::aph_fit_mean_scv(
5485 num_traits<T>::from_double(sm), num_traits<T>::from_double(sscv)));
5486 std::vector<workflow::PhLaw<T>> mix;
5487 mix.push_back(workflow::Workflow<T>::compose_serial(sl, law));
5488 mix.push_back(law);
5489 std::vector<T> probs;
5490 probs.push_back(num_traits<T>::from_double(p));
5491 probs.push_back(num_traits<T>::from_double(1.0 - p));
5493 mm = api::lqn::ph_moments(law.alpha, law.S);
5494 m1 = mm.first;
5495 scv = mm.second;
5496 // The share of the entry law that is cold start and not work.
5497 // The surrogate-delay closure measures a thread's cycle in
5498 // WORK, so it must not read a station utilization this has
5499 // inflated -- see update_think_times_ph.
5500 const double denom = std::max(dbl(m1), GlobalConstants::FineTol);
5501 entry_setup_share[eidx] = num_traits<T>::from_double(p * sm / denom);
5502 }
5503 }
5504 ph_entrylaw[eidx] = law;
5505 ph_entrymean[eidx] = m1;
5506 ph_entryscv[eidx] = scv;
5507 if (hostserial[eidx]) {
5508 // only the non-host part of the entry overlaps: pres + r*(entrysum-pres) = m1
5509 const double rest = dbl(entrysum) - dbl(pres);
5510 if (rest > GlobalConstants::FineTol) {
5511 const double r = std::min(1.0, std::max(0.0, (dbl(m1) - dbl(pres)) / rest));
5512 ph_overlap[eidx] = num_traits<T>::from_double(r);
5513 }
5514 } else if (dbl(entrysum) > GlobalConstants::FineTol) {
5515 const double r = std::min(1.0, dbl(m1) / dbl(entrysum));
5516 ph_overlap[eidx] = num_traits<T>::from_double(r);
5517 }
5518 }
5519
5520 // Per task, the share-weighted fraction of its station service that is
5521 // cold start rather than work.
5522 ph_setupshare.assign(N + 1, Tzero());
5523 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
5524 const std::size_t tidx = lqn.tshift + t;
5525 if (ignore[tidx]) continue;
5526 for (std::size_t eidx : lqn.entriesof[tidx])
5527 ph_setupshare[tidx] = T(ph_setupshare[tidx] + ph_share[eidx] * entry_setup_share[eidx]);
5528 }
5529
5530 // Expected number of calls per invocation, and the caller-side aggregates
5531 ph_ncalls = Matrix<T>(N + 1, N + 1, Tzero());
5532 ph_calltime = Matrix<T>(N + 1, N + 1, Tzero());
5533 ph_procresid.assign(N + 1, Tzero());
5534 ph_actthinkt.assign(N + 1, Tzero());
5535 ph_calltotal.assign(N + 1, Tzero());
5536 // The overlap SAVED on the processor and on each callee: a station charges its
5537 // demand in full, serial, so the layer holding it must take the saving back out
5538 // of the delay, or that layer's cycle is the serial sum and not the composed law.
5539 // Only an entry with an AND fork can save anything, so only those carry it: a
5540 // ratio of 1-eps elsewhere would subtract eps*calltime and cancel, see ph_delay_mean.
5541 ph_procsave.assign(N + 1, Tzero());
5542 ph_callsave = Matrix<T>(N + 1, N + 1, Tzero());
5543 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
5544 const std::size_t tidx = lqn.tshift + t;
5545 if (ignore[tidx]) continue;
5546 for (std::size_t eidx : lqn.entriesof[tidx]) {
5547 if (!ph_has_wf[eidx]) continue;
5548 const T w = ph_share[eidx];
5549 if (!(dbl(w) > 0.0)) continue;
5550 const std::unordered_map<std::size_t, T>& ex = ph_execs[eidx];
5551 const T r = ph_overlap[eidx];
5552 const T sv = ph_has_and_fork(eidx) ? T(Tone() - r) : Tzero();
5553 // a single-server host is charged serially, so it neither overlaps nor saves
5554 const T rp = hostserial[eidx] ? Tone() : r;
5555 const T svp = hostserial[eidx] ? Tzero() : sv;
5556 for (std::size_t aidx : lqn.actsof[eidx]) {
5557 const T xa = ex.at(aidx);
5558 ph_procresid[tidx] = T(ph_procresid[tidx] + w * rp * xa * residt[aidx]);
5559 ph_procsave[tidx] = T(ph_procsave[tidx] + w * svp * xa * residt[aidx]);
5560 ph_actthinkt[tidx] = T(ph_actthinkt[tidx] + w * r * xa * act_think_time(aidx));
5561 for (std::size_t cidx : lqn.callsof[aidx]) {
5562 if (lqn.calltype[cidx] != CallType::SYNC) continue;
5563 const std::size_t tgte = lqn.callpair_dst[cidx];
5564 const std::size_t tgtt = lqn.parent[tgte];
5565 // the COUNT of calls does not change with the overlap,
5566 // only the time the caller is held by them
5567 ph_ncalls(tidx, tgte) =
5568 T(ph_ncalls(tidx, tgte) + w * xa * lqn.callproc_mean[cidx]);
5569 ph_calltime(tidx, tgtt) =
5570 T(ph_calltime(tidx, tgtt) + w * r * xa * callservt[cidx]);
5571 ph_calltotal[tidx] = T(ph_calltotal[tidx] + w * r * xa * callservt[cidx]);
5572 ph_callsave(tidx, tgtt) =
5573 T(ph_callsave(tidx, tgtt) + w * sv * xa * callservt[cidx]);
5574 }
5575 }
5576 }
5577 }
5578 }
5579
5580 /** Build the ensemble under method "srvn.ph". */
5581 void build_layers_ph(bool flat = false) {
5582 if (!ph_laws_ready) ph_assert_supported(flat);
5583 // The interlock correction rewrites the populations of the call classes,
5584 // which this method does not create: its callers reach the server in one
5585 // class each
5586 opt.interlocking = false;
5587 interlockMethod = "none";
5588
5589 // A preceding probe has already composed the per-entry workflows; they do
5590 // not depend on the iterate, so they are not rebuilt here.
5591 if (!ph_laws_ready) ph_init_laws();
5592
5593 // Seed the fixed point with the static demands, then compose the laws
5594 const std::size_t N = lqn.nidx;
5595 residt.assign(N + 1, Tzero());
5596 servt.assign(N + 1, Tzero());
5597 callservt.assign(lqn.ncalls + 1, Tzero());
5598 callresidt.assign(lqn.ncalls + 1, Tzero());
5599 for (std::size_t aidx = lqn.ashift + 1; aidx <= lqn.ashift + lqn.nacts; ++aidx)
5600 residt[aidx] = lqn.hostdem[aidx].disabled ? Tzero() : lqn.hostdem[aidx].mean;
5601 for (std::size_t cidx = 1; cidx <= lqn.ncalls; ++cidx) {
5602 if (lqn.calltype[cidx] != CallType::SYNC && lqn.calltype[cidx] != CallType::ASYNC)
5603 continue;
5604 const std::size_t eidx = lqn.callpair_dst[cidx];
5605 callservt[cidx] = T(lqn.callproc_mean[cidx] * ph_hostmean[eidx]);
5606 callresidt[cidx] = callservt[cidx];
5607 }
5608 ph_compose_entry_laws();
5609
5610 if (flat) {
5611 // ONE subnetwork holding every processor and every called task
5612 build_ph_flat_layer();
5613 tput.assign(N + 1, Tzero());
5614 util.assign(N + 1, Tzero());
5615 thinkt.assign(N + 1, Tzero());
5616 update_layers_ph(0);
5617 for (qn::Layer<T>& e : ensemble) e.refresh_chains();
5618 return;
5619 }
5620
5621 std::vector<qn::Layer<T>> raw(NT() + 1);
5622 std::vector<bool> present(NT() + 1, false);
5623
5624 for (std::size_t hidx = 1; hidx <= lqn.nhosts; ++hidx) {
5625 if (ignore[hidx]) continue;
5626 std::vector<std::size_t> callers;
5627 for (std::size_t tidx : lqn.tasksof[hidx]) {
5628 if (ignore[tidx]) continue;
5629 if (lqn.isref[tidx]) { callers.push_back(tidx); continue; }
5630 for (std::size_t eidx : lqn.entriesof[tidx])
5631 if (ph_any_caller_of(eidx) || lqn.has_arrival[eidx]) {
5632 callers.push_back(tidx);
5633 break;
5634 }
5635 }
5636 if (callers.empty()) continue;
5637 build_layer_ph(raw[hidx], hidx, callers, true);
5638 present[hidx] = true;
5639 }
5640 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
5641 const std::size_t tidx = lqn.tshift + t;
5642 if (ignore[tidx] || lqn.isref[tidx]) continue;
5643 std::vector<std::size_t> callers;
5644 for (std::size_t ct = 1; ct <= lqn.ntasks; ++ct) {
5645 const std::size_t c = lqn.tshift + ct;
5646 if (c == tidx || ignore[c]) continue;
5647 for (std::size_t e : lqn.entriesof[tidx])
5648 if (lqn.issynccaller.get(c, e)) { callers.push_back(c); break; }
5649 }
5650 if (callers.empty() && ph_async_calls_into(tidx).empty()) continue;
5651 build_layer_ph(raw[tidx], tidx, callers, false);
5652 present[tidx] = true;
5653 }
5654
5655 idxhash.assign(lqn.nidx + 1, -1);
5656 long next = 0;
5657 for (std::size_t i = 1; i <= NT(); ++i)
5658 if (present[i]) {
5659 idxhash[i] = next++;
5660 ensemble.push_back(std::move(raw[i]));
5661 }
5662 layer_init_sol.assign(ensemble.size(), Matrix<T>());
5663 build_fork_views();
5664
5665 // install the initial laws, so that iteration 1 sees the seeded demands
5666 // rather than the placeholders the stations were created with
5667 tput.assign(N + 1, Tzero());
5668 util.assign(N + 1, Tzero());
5669 thinkt.assign(N + 1, Tzero());
5670 update_layers_ph(0);
5671 // update_layers_ph only rebuilds rt; the cached rates still hold the build-time
5672 // placeholders (an async Source seeded Immediate, rate 1e8, saturates iteration 1)
5673 // until post() refreshes them, so refresh here as MATLAB's setService invalidation does
5674 for (qn::Layer<T>& e : ensemble) e.refresh_chains();
5675 }
5676
5677 /**
5678 * Build the ONE layer of method "flat.ph": a client delay plus a station for
5679 * every processor and every called task.
5680 *
5681 * A caller task is one closed class, and it visits each server it uses ONCE
5682 * per invocation, carrying there the composed law of the demand it places on
5683 * that server -- the same law method "srvn.ph" installs in the server's own
5684 * layer. What changes is that the servers now contend inside one network
5685 * instead of seeing each other through surrogate delays, so the client delay
5686 * keeps only the think times and whatever of the cycle this model does not
5687 * hold. That is the whole difference between the two encodings of the PH
5688 * composition, and it is why the reconstruction passes are shared verbatim.
5689 */
5690 void build_ph_flat_layer() {
5691 const std::vector<std::size_t> servers = ph_flat_server_set();
5692 const std::size_t nsrv = servers.size();
5693
5694 qn::Layer<T> m;
5695 m.name = "FlatPH";
5696 m.clientIdx = m.add_station(qn::Station<T>{
5697 "Clients", NodeType::Delay, SchedStrategy::INF,
5698 std::numeric_limits<double>::infinity(), false, 0});
5699 const std::size_t clientNode = m.node_of_station(m.clientIdx);
5700 m.server_idx_of.assign(lqn.nidx + 1, 0);
5701
5702 std::vector<std::size_t> station_of(lqn.nidx + 1, 0);
5703 std::vector<std::size_t> serverNode(nsrv, 0);
5704 std::vector<std::size_t> srvStation(nsrv, 0);
5705 for (std::size_t si = 0; si < nsrv; ++si) {
5706 const std::size_t idx = servers[si];
5707 const bool ishost = idx <= lqn.nhosts;
5708 qn::Station<T> st;
5709 st.name = lqn.hashnames[idx];
5710 st.nodetype = lqn.sched[idx] == SchedStrategy::INF ? NodeType::Delay : NodeType::Queue;
5711 st.sched = lqn.sched[idx];
5712 st.nservers = lqn.sched[idx] == SchedStrategy::INF
5713 ? std::numeric_limits<double>::infinity()
5714 : lqn.maxmult[idx];
5715 st.attr_ishost = ishost;
5716 st.attr_idx = idx;
5717 const std::size_t s = m.add_station(st);
5718 srvStation[si] = s;
5719 station_of[idx] = s;
5720 serverNode[si] = m.node_of_station(s);
5721 m.server_idx_of[idx] = s;
5722 if (ishost)
5723 m.host_stations.push_back(s);
5724 else
5725 m.task_stations.push_back(s);
5726 }
5727 // the scalar fallback of the station lookup, which no served element reaches
5728 m.serverIdx = station_of[servers[0]];
5729 m.flat = true;
5730
5731 // Callers of each server, and the union of them, which becomes the class set
5732 std::vector<std::vector<std::size_t>> callers_of(lqn.nidx + 1);
5733 std::vector<std::size_t> all_callers;
5734 for (std::size_t si = 0; si < nsrv; ++si) {
5735 const std::size_t idx = servers[si];
5736 std::vector<std::size_t> cs;
5737 if (idx <= lqn.nhosts) {
5738 for (std::size_t tidx : lqn.tasksof[idx]) {
5739 if (ignore[tidx]) continue;
5740 if (lqn.isref[tidx]) { cs.push_back(tidx); continue; }
5741 for (std::size_t eidx : lqn.entriesof[tidx])
5742 if (ph_any_caller_of(eidx) || lqn.has_arrival[eidx]) {
5743 cs.push_back(tidx);
5744 break;
5745 }
5746 }
5747 } else {
5748 for (std::size_t ct = 1; ct <= lqn.ntasks; ++ct) {
5749 const std::size_t c = lqn.tshift + ct;
5750 if (c == idx || ignore[c]) continue;
5751 for (std::size_t e : lqn.entriesof[idx])
5752 if (lqn.issynccaller.get(c, e)) { cs.push_back(c); break; }
5753 }
5754 }
5755 callers_of[idx] = cs;
5756 for (std::size_t c : cs)
5757 if (std::find(all_callers.begin(), all_callers.end(), c) == all_callers.end())
5758 all_callers.push_back(c);
5759 }
5760 std::sort(all_callers.begin(), all_callers.end());
5761
5762 // One closed class per caller task
5763 std::vector<std::size_t> class_of_caller(lqn.nidx + 1, 0);
5764 double npop = 0.0;
5765 for (std::size_t c : all_callers) {
5766 // ph_flat_server_set has refused every replicated element, so the
5767 // per-replica reduction the srvn builder makes is the identity here
5768 double nj = lqn.maxmult[c];
5769 if (std::isinf(nj)) {
5770 double sacc = 0.0;
5771 for (std::size_t k = 1; k <= NT(); ++k)
5772 if (lqn.taskgraph.get(k, c) != Tzero()) sacc += lqn.maxmult[k];
5773 nj = sacc;
5774 if (std::isinf(nj) || nj == 0.0) {
5775 double s2 = 0.0;
5776 for (std::size_t k = 1; k <= NT(); ++k)
5777 if (std::isfinite(lqn.maxmult[k])) s2 += lqn.maxmult[k];
5778 nj = std::min(s2, 1000.0);
5779 }
5780 }
5781 qn::JobClass jc;
5782 jc.name = lqn.hashnames[c];
5783 jc.type = JobClassType::CLOSED;
5784 jc.population = nj;
5785 jc.refstat = m.clientIdx;
5786 jc.is_ref_class = true;
5787 jc.attr_kind = int(LqnElement::TASK);
5788 jc.attr_idx = c;
5789 const std::size_t k = m.add_class(jc);
5790 class_of_caller[c] = k;
5791 m.attr_tasks.emplace_back(k, c);
5792 npop += nj;
5793 const double zt = dbl(ref_think_time(c));
5794 m.set_service(m.clientIdx, k,
5795 Distrib<T>::exp_mean(num_traits<T>::from_double(
5796 std::max(zt, GlobalConstants::FineTol))));
5797 // A station this caller never reaches must say so with a DISABLED law,
5798 // not with a tiny placeholder. An FCFS station carries ONE service law
5799 // across its classes, so a placeholder is not inert there: it is mixed
5800 // into the multiserver correction and invents waiting where there is
5801 // none. Under "srvn.ph" the question never arises, since every class of
5802 // a layer visits that layer's single server.
5803 for (std::size_t si = 0; si < nsrv; ++si)
5804 m.set_service(srvStation[si], k, Distrib<T>::disabled_dist());
5805 for (std::size_t si = 0; si < nsrv; ++si) {
5806 const std::size_t idx = servers[si];
5807 const std::vector<std::size_t>& cs = callers_of[idx];
5808 if (std::find(cs.begin(), cs.end(), c) == cs.end()) continue;
5809 m.set_service(srvStation[si], k,
5811 num_traits<T>::from_double(GlobalConstants::FineTol)));
5812 njobs(c, idx) = nj;
5813 thinkt_map.push_back({idx, c, m.clientIdx, k});
5814 servt_map.push_back({idx, c, station_of[idx], k});
5815 }
5816 }
5817
5818 // Open classes: entry arrivals on a processor station, async calls on a task one
5819 std::vector<std::vector<std::pair<std::size_t, long>>> open_of(lqn.nidx + 1);
5820 std::size_t sourceStation = 0, sinkNode = 0;
5821 for (std::size_t si = 0; si < nsrv; ++si) {
5822 const std::size_t hidx = servers[si];
5823 if (hidx > lqn.nhosts) continue;
5824 for (std::size_t c : callers_of[hidx]) {
5825 // A task no other task calls has no task station, so the think-time
5826 // closure never gives its caller class a surrogate delay: the class
5827 // cycles against an Immediate one and an open stream on top of it
5828 // doubles the load. The chain is the representation that honours the
5829 // thread pool, so it is kept and closed on the arrival rate instead.
5830 if (ph_open_arrival_only(c)) continue;
5831 for (std::size_t eidx : lqn.entriesof[c]) {
5832 if (!lqn.has_arrival[eidx]) continue;
5833 if (sourceStation == 0) {
5834 sourceStation = m.add_station(qn::Station<T>{
5835 "Source", NodeType::Source, SchedStrategy::EXT,
5836 std::numeric_limits<double>::infinity(), false, 0});
5837 m.sourceIdx = sourceStation;
5838 sinkNode = m.add_node("Sink", NodeType::Sink, false);
5839 m.sinkNode = sinkNode;
5840 }
5841 qn::JobClass oc;
5842 oc.name = lqn.hashnames[eidx] + ".Open";
5843 oc.type = JobClassType::OPEN;
5844 oc.population = std::numeric_limits<double>::infinity();
5845 oc.refstat = sourceStation;
5846 oc.attr_kind = int(LqnElement::ENTRY);
5847 oc.attr_idx = eidx;
5848 const std::size_t k = m.add_class(oc);
5849 m.set_service(sourceStation, k, lqn.arrival[eidx]);
5850 // disabled, not a placeholder, at every station this stream misses
5851 for (std::size_t s2 = 0; s2 < nsrv; ++s2)
5852 m.set_service(srvStation[s2], k, Distrib<T>::disabled_dist());
5853 const double hm = std::max(dbl(ph_hostmean[eidx]), GlobalConstants::FineTol);
5854 m.set_service(srvStation[si], k,
5855 Distrib<T>::exp_mean(num_traits<T>::from_double(hm)));
5856 open_of[hidx].emplace_back(k, long(eidx));
5857 m.attr_entries.emplace_back(k, eidx);
5858 }
5859 }
5860 }
5861 for (std::size_t si = 0; si < nsrv; ++si) {
5862 const std::size_t tidx = servers[si];
5863 if (tidx <= lqn.nhosts) continue;
5864 for (std::size_t cidx : ph_async_calls_into(tidx)) {
5865 if (sourceStation == 0) {
5866 sourceStation = m.add_station(qn::Station<T>{
5867 "Source", NodeType::Source, SchedStrategy::EXT,
5868 std::numeric_limits<double>::infinity(), false, 0});
5869 m.sourceIdx = sourceStation;
5870 sinkNode = m.add_node("Sink", NodeType::Sink, false);
5871 m.sinkNode = sinkNode;
5872 }
5873 const std::size_t eidx = lqn.callpair_dst[cidx];
5874 qn::JobClass oc;
5875 oc.name = lqn.callhashnames[cidx];
5876 oc.type = JobClassType::OPEN;
5877 oc.population = std::numeric_limits<double>::infinity();
5878 oc.refstat = sourceStation;
5879 oc.attr_kind = int(LqnElement::CALL);
5880 oc.attr_idx = cidx;
5881 const std::size_t k = m.add_class(oc);
5882 m.set_service(sourceStation, k, Distrib<T>::immediate());
5883 // disabled, not a placeholder, at every station this stream misses
5884 for (std::size_t s2 = 0; s2 < nsrv; ++s2)
5885 m.set_service(srvStation[s2], k, Distrib<T>::disabled_dist());
5886 const double em = std::max(dbl(ph_entrymean[eidx]), GlobalConstants::FineTol);
5887 m.set_service(srvStation[si], k,
5888 Distrib<T>::exp_mean(num_traits<T>::from_double(em)));
5889 open_of[tidx].emplace_back(k, -long(cidx));
5890 m.attr_calls.push_back({k, cidx, lqn.callpair_src[cidx], eidx});
5891 arv_call_map.push_back({tidx, cidx, sourceStation, k});
5892 call_map.push_back({tidx, cidx, station_of[tidx], k});
5893 }
5894 }
5895
5896 // Routing: one visit per server the caller uses, in server order. The
5897 // number of calls is carried by the service law, not by a visit ratio, so
5898 // no arc ever moves.
5899 for (std::size_t c : all_callers) {
5900 const std::size_t k = class_of_caller[c];
5901 std::size_t prev = clientNode;
5902 bool visited = false;
5903 for (std::size_t si = 0; si < nsrv; ++si) {
5904 const std::vector<std::size_t>& cs = callers_of[servers[si]];
5905 if (std::find(cs.begin(), cs.end(), c) == cs.end()) continue;
5906 m.set_route(k, k, prev, serverNode[si], Tone());
5907 prev = serverNode[si];
5908 visited = true;
5909 }
5910 if (visited) m.set_route(k, k, prev, clientNode, Tone());
5911 }
5912 if (sourceStation != 0) {
5913 const std::size_t srcNode = m.node_of_station(sourceStation);
5914 for (std::size_t si = 0; si < nsrv; ++si)
5915 for (const auto& oa : open_of[servers[si]]) {
5916 m.set_route(oa.first, oa.first, srcNode, serverNode[si], Tone());
5917 m.set_route(oa.first, oa.first, serverNode[si], sinkNode, Tone());
5918 }
5919 }
5920 apply_host_task_priorities(m, servers);
5921 m.refresh_chains();
5922
5923 idxhash.assign(lqn.nidx + 1, -1);
5924 for (std::size_t idx : servers) idxhash[idx] = 0;
5925 ensemble.clear();
5926 ensemble.push_back(std::move(m));
5927 layer_init_sol.assign(ensemble.size(), Matrix<T>());
5928 build_fork_views();
5929
5930 const std::size_t nclasses = ensemble[0].classes.size();
5931 for (std::size_t idx : servers) {
5932 PHLayer L;
5933 L.idx = idx;
5934 L.ishost = idx <= lqn.nhosts;
5935 L.callers = callers_of[idx];
5936 L.class_of_caller = class_of_caller;
5937 L.nreplicas = 1;
5938 L.qstations.assign(1, station_of[idx]);
5939 L.svcmean_by_class.assign(nclasses + 1, Tzero());
5940 L.open_arrivals = open_of[idx];
5941 L.npop = npop < 1.0 ? 1.0 : npop;
5942 ph_layers[idx] = L;
5943 ph_has_layer[idx] = true;
5944 }
5945 }
5946
5947 /**
5948 * Processors and called tasks that become stations of the flat layer.
5949 *
5950 * The set is the elements the srvn builder would have given a layer of their
5951 * own, so "flat.ph" and "srvn.ph" place the SAME stations and differ only in
5952 * how many networks hold them. The refusals are those of flat_server_set,
5953 * since they are properties of the squashing and not of the encoding: each of
5954 * these carries per-layer state that one submodel cannot hold.
5955 */
5956 std::vector<std::size_t> ph_flat_server_set() const {
5957 for (std::size_t i = 1; i <= NT(); ++i) {
5958 if (lqn.repl[i] > 1.0)
5959 throw UnsupportedError(ErrorKind{"Replication"},
5960 "method='flat.ph' does not support replicated processors or tasks, whose "
5961 "replicas need a submodel each. Use method='srvn.ph'.");
5962 if (lqn.iscache[i])
5963 throw UnsupportedError(ErrorKind{"CacheTask"},
5964 "method='flat.ph' does not support cache tasks. Use method='default'.");
5965 if (lqn.hassetup[i])
5966 throw UnsupportedError(ErrorKind{"SetupDelayOff"},
5967 "method='flat.ph' does not support setup tasks, whose powered-down threads "
5968 "are per-layer state. Use method='srvn.ph'.");
5969 }
5970 std::vector<std::size_t> servers;
5971 for (std::size_t hidx = 1; hidx <= lqn.nhosts; ++hidx) {
5972 if (ignore[hidx] || lqn.tasksof[hidx].empty()) continue;
5973 bool any = false;
5974 for (std::size_t tidx : lqn.tasksof[hidx]) {
5975 if (ignore[tidx]) continue;
5976 if (lqn.isref[tidx]) { any = true; break; }
5977 for (std::size_t eidx : lqn.entriesof[tidx])
5978 if (ph_any_caller_of(eidx) || lqn.has_arrival[eidx]) { any = true; break; }
5979 if (any) break;
5980 }
5981 if (any) servers.push_back(hidx);
5982 }
5983 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
5984 const std::size_t tidx = lqn.tshift + t;
5985 if (ignore[tidx] || lqn.isref[tidx]) continue;
5986 bool has_caller = false;
5987 for (std::size_t ct = 1; ct <= lqn.ntasks && !has_caller; ++ct) {
5988 const std::size_t c = lqn.tshift + ct;
5989 if (c == tidx || ignore[c]) continue;
5990 for (std::size_t e : lqn.entriesof[tidx])
5991 if (lqn.issynccaller.get(c, e)) { has_caller = true; break; }
5992 }
5993 if (!has_caller && ph_async_calls_into(tidx).empty()) continue;
5994 servers.push_back(tidx);
5995 }
5996 if (servers.empty())
5997 throw InputError(
5998 "method='flat.ph' found no server: the model has no processor with tasks.");
5999 return servers;
6000 }
6001
6002 /** Build the two-station layer of server element IDX. */
6003 void build_layer_ph(qn::Layer<T>& m, std::size_t idx,
6004 const std::vector<std::size_t>& callers, bool ishost) {
6005 m.name = lqn.hashnames[idx];
6006
6007 // Replicas of the server station, with the same fan-out reduction as the
6008 // default builder: a caller that reaches every replica sees one
6009 // representative
6010 const double rawrepl = lqn.repl[idx];
6011 std::size_t nreplicas = 1;
6012 if (rawrepl > 1.0 && !callers.empty()) {
6013 bool reduce = true;
6014 if (ishost) {
6015 for (std::size_t c : callers)
6016 if (lqn.repl[c] != rawrepl) reduce = false;
6017 } else {
6018 for (std::size_t c : callers)
6019 if (lqn.fanout_at(c, idx) < rawrepl) reduce = false;
6020 }
6021 nreplicas = reduce ? 1 : static_cast<std::size_t>(std::llround(rawrepl));
6022 if (reduce && !ishost) single_replica_tasks.insert(idx);
6023 }
6024 const bool reduce_fanout = (nreplicas == 1 && rawrepl > 1.0 && !callers.empty());
6025
6026 m.clientIdx = m.add_station(qn::Station<T>{
6027 "Clients", NodeType::Delay, SchedStrategy::INF,
6028 std::numeric_limits<double>::infinity(), false, 0});
6029 const std::size_t clientNode = m.node_of_station(m.clientIdx);
6030 m.serverIdx = m.clientIdx + 1;
6031 PHLayer L;
6032 L.idx = idx;
6033 L.ishost = ishost;
6034 L.callers = callers;
6035 L.nreplicas = nreplicas;
6036 L.class_of_caller.assign(lqn.nidx + 1, 0);
6037 std::vector<std::size_t> serverNode(nreplicas);
6038 for (std::size_t r = 0; r < nreplicas; ++r) {
6039 qn::Station<T> st;
6040 st.name = r == 0 ? lqn.hashnames[idx] : lqn.hashnames[idx] + "." + std::to_string(r + 1);
6041 st.nodetype = lqn.sched[idx] == SchedStrategy::INF ? NodeType::Delay : NodeType::Queue;
6042 st.sched = lqn.sched[idx];
6043 st.nservers = lqn.sched[idx] == SchedStrategy::INF
6044 ? std::numeric_limits<double>::infinity()
6045 : lqn.maxmult[idx];
6046 st.attr_ishost = ishost;
6047 st.attr_idx = idx;
6048 const std::size_t s = m.add_station(st);
6049 L.qstations.push_back(s);
6050 serverNode[r] = m.node_of_station(s);
6051 }
6052
6053 // --- closed class per caller task
6054 for (std::size_t c : callers) {
6055 double nj = njobs(c, idx);
6056 if (nj == 0.0) {
6057 const bool caller_single_replica =
6058 reduce_fanout || single_replica_tasks.count(c) > 0;
6059 nj = caller_single_replica ? lqn.maxmult[c] : lqn.maxmult[c] * lqn.repl[c];
6060 if (std::isinf(nj)) {
6061 double s = 0.0;
6062 for (std::size_t k = 1; k <= NT(); ++k)
6063 if (lqn.taskgraph.get(k, c) != Tzero()) s += lqn.maxmult[k];
6064 nj = s;
6065 if (std::isinf(nj) || nj == 0.0) {
6066 double s2 = 0.0;
6067 for (std::size_t k = 1; k <= NT(); ++k)
6068 if (std::isfinite(lqn.maxmult[k])) s2 += lqn.maxmult[k] * lqn.repl[k];
6069 nj = std::min(s2, 1000.0);
6070 }
6071 }
6072 njobs(c, idx) = nj;
6073 }
6074 qn::JobClass jc;
6075 jc.name = lqn.hashnames[c];
6076 jc.type = JobClassType::CLOSED;
6077 jc.population = nj;
6078 jc.refstat = m.clientIdx;
6079 jc.is_ref_class = true;
6080 jc.attr_kind = int(LqnElement::TASK);
6081 jc.attr_idx = c;
6082 const std::size_t k = m.add_class(jc);
6083 L.class_of_caller[c] = k;
6084 m.attr_tasks.emplace_back(k, c);
6085 const double zt = dbl(ref_think_time(c));
6086 m.set_service(m.clientIdx, k,
6087 Distrib<T>::exp_mean(num_traits<T>::from_double(
6088 std::max(zt, GlobalConstants::FineTol))));
6089 for (std::size_t s : L.qstations)
6090 m.set_service(s, k, Distrib<T>::exp_mean(
6091 num_traits<T>::from_double(GlobalConstants::FineTol)));
6092 // every layer must be refreshed after a law change: post() resets the
6093 // layers named by the think-time map
6094 thinkt_map.push_back({idx, c, m.clientIdx, k});
6095 servt_map.push_back({idx, c, L.qstations[0], k});
6096 }
6097
6098 // --- open classes: entry arrivals and async calls on the task layer of
6099 // their target; an entry arrival falls back on the host layer only when its
6100 // task has no task layer at all
6101 std::size_t sourceStation = 0, sinkNode = 0;
6102 if (ishost) {
6103 for (std::size_t c : callers) {
6104 // A task no other task calls has no task layer, so
6105 // update_think_times_ph never gives its caller class a surrogate
6106 // delay: the class cycles against an Immediate one and an open
6107 // stream on top of it doubles the load. The chain is the
6108 // representation that honours the thread pool, so it is kept and
6109 // closed on the arrival rate instead.
6110 if (ph_open_arrival_only(c)) continue;
6111 // A task that HAS a task layer takes its entry arrivals there, where
6112 // an open request holds one of the task's threads for the whole
6113 // entry (host residence plus calls) exactly as a sync request does.
6114 // Served here instead, the request only ever met the processor and
6115 // never queued for a thread (test_ln_fork_openarrival: OE 0.1109
6116 // against an arrival rate of 0.1).
6117 if (ph_has_task_layer(c)) continue;
6118 for (std::size_t eidx : lqn.entriesof[c]) {
6119 if (!lqn.has_arrival[eidx]) continue;
6120 if (sourceStation == 0) {
6121 sourceStation = m.add_station(qn::Station<T>{
6122 "Source", NodeType::Source, SchedStrategy::EXT,
6123 std::numeric_limits<double>::infinity(), false, 0});
6124 m.sourceIdx = sourceStation;
6125 sinkNode = m.add_node("Sink", NodeType::Sink, false);
6126 m.sinkNode = sinkNode;
6127 }
6128 qn::JobClass oc;
6129 oc.name = lqn.hashnames[eidx] + ".Open";
6130 oc.type = JobClassType::OPEN;
6131 oc.population = std::numeric_limits<double>::infinity();
6132 oc.refstat = sourceStation;
6133 oc.attr_kind = int(LqnElement::ENTRY);
6134 oc.attr_idx = eidx;
6135 const std::size_t k = m.add_class(oc);
6136 m.set_service(sourceStation, k, lqn.arrival[eidx]);
6137 for (std::size_t s : L.qstations) {
6138 const double hm = std::max(dbl(ph_hostmean[eidx]), GlobalConstants::FineTol);
6139 m.set_service(s, k, Distrib<T>::exp_mean(num_traits<T>::from_double(hm)));
6140 }
6141 L.open_arrivals.emplace_back(k, long(eidx));
6142 m.attr_entries.emplace_back(k, eidx);
6143 }
6144 }
6145 } else {
6146 // entry arrivals of this task: an open stream that holds a thread for
6147 // the composed entry law (host residence plus calls), refreshed with
6148 // that law in update_layers_ph; its arrival process stays static
6149 for (std::size_t eidx : lqn.entriesof[idx]) {
6150 if (!lqn.has_arrival[eidx]) continue;
6151 if (sourceStation == 0) {
6152 sourceStation = m.add_station(qn::Station<T>{
6153 "Source", NodeType::Source, SchedStrategy::EXT,
6154 std::numeric_limits<double>::infinity(), false, 0});
6155 m.sourceIdx = sourceStation;
6156 sinkNode = m.add_node("Sink", NodeType::Sink, false);
6157 m.sinkNode = sinkNode;
6158 }
6159 qn::JobClass oc;
6160 oc.name = lqn.hashnames[eidx] + ".Open";
6161 oc.type = JobClassType::OPEN;
6162 oc.population = std::numeric_limits<double>::infinity();
6163 oc.refstat = sourceStation;
6164 oc.attr_kind = int(LqnElement::ENTRY);
6165 oc.attr_idx = eidx;
6166 const std::size_t k = m.add_class(oc);
6167 m.set_service(sourceStation, k, lqn.arrival[eidx]);
6168 for (std::size_t s : L.qstations) {
6169 const double em = std::max(dbl(ph_entrymean[eidx]), GlobalConstants::FineTol);
6170 m.set_service(s, k, Distrib<T>::exp_mean(num_traits<T>::from_double(em)));
6171 }
6172 L.open_arrivals.emplace_back(k, long(eidx));
6173 m.attr_entries.emplace_back(k, eidx);
6174 }
6175 for (std::size_t cidx : ph_async_calls_into(idx)) {
6176 if (sourceStation == 0) {
6177 sourceStation = m.add_station(qn::Station<T>{
6178 "Source", NodeType::Source, SchedStrategy::EXT,
6179 std::numeric_limits<double>::infinity(), false, 0});
6180 m.sourceIdx = sourceStation;
6181 sinkNode = m.add_node("Sink", NodeType::Sink, false);
6182 m.sinkNode = sinkNode;
6183 }
6184 const std::size_t eidx = lqn.callpair_dst[cidx];
6185 qn::JobClass oc;
6186 oc.name = lqn.callhashnames[cidx];
6187 oc.type = JobClassType::OPEN;
6188 oc.population = std::numeric_limits<double>::infinity();
6189 oc.refstat = sourceStation;
6190 oc.attr_kind = int(LqnElement::CALL);
6191 oc.attr_idx = cidx;
6192 const std::size_t k = m.add_class(oc);
6193 m.set_service(sourceStation, k, Distrib<T>::immediate());
6194 for (std::size_t s : L.qstations) {
6195 const double em = std::max(dbl(ph_entrymean[eidx]), GlobalConstants::FineTol);
6196 m.set_service(s, k, Distrib<T>::exp_mean(num_traits<T>::from_double(em)));
6197 }
6198 L.open_arrivals.emplace_back(k, -long(cidx));
6199 m.attr_calls.push_back({k, cidx, lqn.callpair_src[cidx], eidx});
6200 arv_call_map.push_back({idx, cidx, sourceStation, k});
6201 call_map.push_back({idx, cidx, L.qstations[0], k});
6202 }
6203 }
6204
6205 // Routing: one visit to the server per client cycle. The number of calls
6206 // is carried by the service law, not by a visit ratio, so no arc changes
6207 const T share = num_traits<T>::from_double(1.0 / double(nreplicas));
6208 for (std::size_t c : callers) {
6209 const std::size_t k = L.class_of_caller[c];
6210 for (std::size_t r = 0; r < nreplicas; ++r) {
6211 m.set_route(k, k, clientNode, serverNode[r], share);
6212 m.set_route(k, k, serverNode[r], clientNode, Tone());
6213 }
6214 }
6215 for (const auto& oa : L.open_arrivals) {
6216 const std::size_t k = oa.first;
6217 const std::size_t srcNode = m.node_of_station(sourceStation);
6218 for (std::size_t r = 0; r < nreplicas; ++r) {
6219 m.set_route(k, k, srcNode, serverNode[r], share);
6220 m.set_route(k, k, serverNode[r], sinkNode, Tone());
6221 }
6222 }
6223 L.svcmean_by_class.assign(m.classes.size() + 1, Tzero());
6224 double np = 0.0;
6225 for (std::size_t c : callers) {
6226 const double v = njobs(c, idx);
6227 if (std::isfinite(v) && v > 0.0) np += v;
6228 }
6229 L.npop = np < 1.0 ? 1.0 : np;
6230 apply_host_task_priorities(m, std::vector<std::size_t>{idx});
6231 m.refresh_chains();
6232 ph_layers[idx] = L;
6233 ph_has_layer[idx] = true;
6234 }
6235
6236 /** Law of the demand caller C places on the server of layer IDX per invocation. */
6237 workflow::PhLaw<T> ph_service_law(std::size_t idx, bool ishost, std::size_t c) const {
6238 if (ishost) {
6239 // mixture over the entries of C, weighted by their share of its requests
6240 std::vector<workflow::PhLaw<T>> laws;
6241 std::vector<T> probs;
6242 double tot = 0.0;
6243 for (std::size_t eidx : lqn.entriesof[c]) {
6244 if (ph_hostlaw[eidx].S.rows() == 0 || !(dbl(ph_share[eidx]) > 0.0)) continue;
6245 laws.push_back(ph_hostlaw[eidx]);
6246 probs.push_back(ph_share[eidx]);
6247 tot += dbl(ph_share[eidx]);
6248 }
6249 if (laws.empty()) return ph_immediate_law();
6250 for (T& p : probs) p = T(p / num_traits<T>::from_double(tot));
6251 return workflow::Workflow<T>::compose_mixture(laws, probs);
6252 }
6253 // task layer: the total demand is the sum, over the entries of the
6254 // server, of a geometric compound of the entry law of mean equal to the
6255 // number of calls
6256 bool started = false;
6257 workflow::PhLaw<T> out;
6258 for (std::size_t eidx : lqn.entriesof[idx]) {
6259 const T n = ph_ncalls(c, eidx);
6260 if (dbl(n) <= GlobalConstants::FineTol || ph_entrylaw[eidx].S.rows() == 0) continue;
6261 const workflow::PhLaw<T> lp =
6263 out = started ? workflow::Workflow<T>::compose_serial(out, lp) : lp;
6264 started = true;
6265 }
6266 if (!started) return ph_immediate_law();
6267 return out;
6268 }
6269
6270 /**
6271 * Mean time a thread of caller C spends away from the server of layer IDX per
6272 * invocation: idle, plus whatever of its cycle the layer does not hold.
6273 */
6274 T ph_delay_mean(std::size_t idx, std::size_t c) const {
6275 // ONE closure for both layerings. Under "srvn.ph" the model holds a single
6276 // server, so a host layer charges the whole call burst to the delay and a
6277 // task layer charges the caller's processor plus every other callee. Under
6278 // "flat.ph" the model holds every server, and only the think times are
6279 // left. Every term is SUMMED in rather than obtained by subtracting from a
6280 // total: that subtraction cancels catastrophically once a call time is
6281 // large, the think time falls below the ULP of the call time, and the layer
6282 // then sees a client delay of zero, saturates, and the fixed point runs
6283 // away.
6284 T z = T(thinkt[c] + ref_think_time(c));
6285 if (!std::isfinite(dbl(z)) || dbl(z) < 0.0) z = Tzero();
6286 z = T(z + ph_actthinkt[c]);
6287 const std::size_t hidx = lqn.parent[c];
6288 // A station held here charges its demand SERIAL, while the cycle holds it only
6289 // at the overlap ratio of the AND forks it sits in, so the saving comes back out
6290 // of the delay. Every layer then cycles in z + the composed entry mean, and flow
6291 // balances across the call (lqn_workflows, _kb/06-solver-catalog.md).
6292 if (!ph_served_here(idx, hidx)) z = T(z + ph_procresid[c]);
6293 else z = T(z - ph_procsave[c]);
6294 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
6295 const std::size_t tidx = lqn.tshift + t;
6296 if (!ph_served_here(idx, tidx)) z = T(z + ph_calltime(c, tidx));
6297 else z = T(z - ph_callsave(c, tidx));
6298 }
6299 if (!std::isfinite(dbl(z)) || dbl(z) < 0.0)
6300 z = num_traits<T>::from_double(GlobalConstants::FineTol);
6301 return z;
6302 }
6303
6304 /**
6305 * True when LQN element ELEM is a station of the same model that holds server
6306 * IDX. Under "srvn.ph" that is ELEM == IDX, since each server has a layer of
6307 * its own; under "flat.ph" it is every server of the one network.
6308 */
6309 bool ph_served_here(std::size_t idx, std::size_t elem) const {
6310 if (elem < 1 || elem >= idxhash.size() || idx < 1 || idx >= idxhash.size())
6311 return false;
6312 return idxhash[elem] >= 0 && idxhash[elem] == idxhash[idx];
6313 }
6314
6315 /**
6316 * Push the composed laws into the layers.
6317 *
6318 * A layer of this method carries no routing that depends on the iterate: the
6319 * number of calls a caller makes is folded into its service law rather than
6320 * into a visit ratio, so only two laws move per (layer, class) -- the
6321 * phase-type service law at the server and the mean of the surrogate delay
6322 * at the client.
6323 */
6324 void update_layers_ph(int) {
6325 for (std::size_t idx = 1; idx <= NT(); ++idx) {
6326 if (idxhash[idx] < 0 || !ph_has_layer[idx]) continue;
6327 PHLayer& L = ph_layers[idx];
6328 qn::Layer<T>& m = ensemble[std::size_t(idxhash[idx])];
6329 for (std::size_t c : L.callers) {
6330 const std::size_t k = L.class_of_caller[c];
6331 const workflow::PhLaw<T> sl = ph_service_law(idx, L.ishost, c);
6332 L.svcmean_by_class[k] = api::lqn::ph_moments(sl.alpha, sl.S).first;
6333 const Distrib<T> law = ph_station_law(sl);
6334 for (std::size_t s : L.qstations) m.set_service(s, k, law);
6335 const double zd = std::max(dbl(ph_delay_mean(idx, c)),
6337 m.set_service(m.clientIdx, k,
6338 Distrib<T>::exp_mean(num_traits<T>::from_double(zd)));
6339 }
6340 for (const auto& oa : L.open_arrivals) {
6341 const std::size_t k = oa.first;
6342 if (oa.second > 0 && L.ishost) {
6343 // entry arrival of a task with no task layer: the processor
6344 // demand law of the entry is static
6345 L.svcmean_by_class[k] = ph_hostmean[std::size_t(oa.second)];
6346 continue;
6347 }
6348 if (oa.second > 0) {
6349 // entry arrival on its task layer: it holds a thread for the
6350 // composed entry law, which moves with the call response times;
6351 // the arrival process is the model's own and is not touched
6352 const std::size_t eo = std::size_t(oa.second);
6353 L.svcmean_by_class[k] = ph_entrymean[eo];
6354 const Distrib<T> elaw = ph_station_law(ph_entrylaw[eo]);
6355 for (std::size_t s : L.qstations) m.set_service(s, k, elaw);
6356 continue;
6357 }
6358 const std::size_t cidx = std::size_t(-oa.second);
6359 const std::size_t eidx = lqn.callpair_dst[cidx];
6360 L.svcmean_by_class[k] = ph_entrymean[eidx];
6361 const Distrib<T> law = ph_station_law(ph_entrylaw[eidx]);
6362 for (std::size_t s : L.qstations) m.set_service(s, k, law);
6363 const std::size_t aidx = lqn.callpair_src[cidx];
6364 double rate = dbl(tput[aidx]) * dbl(lqn.callproc_mean[cidx]);
6365 if (!std::isfinite(rate) || rate <= GlobalConstants::FineTol)
6367 m.set_service(m.sourceIdx, k,
6368 Distrib<T>::exp_rate(num_traits<T>::from_double(rate)));
6369 }
6370 m.refresh_rt();
6371 }
6372 }
6373
6374 /**
6375 * Residence time per visit, by Little from the queue length rather than from
6376 * the reported RN. A layer that saturates can come back from AMVA with an RN
6377 * no closed model can produce, and a reconstruction that trusts it feeds the
6378 * impossible value straight back into the call response times.
6379 */
6380 static T ph_residence(const T& Q, const T& X, const T& RN) {
6381 const double q = num_traits<T>::to_double(Q), x = num_traits<T>::to_double(X);
6382 if (std::isfinite(q) && q >= 0.0 && std::isfinite(x) && x > GlobalConstants::FineTol)
6383 return T(Q / X);
6384 return RN;
6385 }
6386
6387 /**
6388 * Ratio of a residence time to the mean of the law it was measured against,
6389 * bounded above by the layer population: a job can wait behind at most every
6390 * other job in a closed layer.
6391 */
6392 static T ph_inflation_of(const T& R, const T& S, double npop) {
6393 double f = 1.0;
6394 const double s = num_traits<T>::to_double(S), r = num_traits<T>::to_double(R);
6395 if (s > GlobalConstants::FineTol && std::isfinite(r) && r > 0.0) f = r / s;
6396 if (!std::isfinite(f) || f < 1.0) f = 1.0;
6397 if (std::isfinite(npop) && npop >= 1.0 && f > npop) f = npop;
6398 return num_traits<T>::from_double(f);
6399 }
6400
6401 /** Total closed population of a layer, i.e. how many jobs a job can queue behind. */
6402 double ph_layer_pop(const PHLayer& L, std::size_t idx) const {
6403 // A server that also takes an OPEN stream has no such bound: a job can
6404 // queue behind any number of open jobs, so capping the inflation at the
6405 // closed population would erase exactly the wait the open stream causes.
6406 if (!L.open_arrivals.empty()) return std::numeric_limits<double>::infinity();
6407 // Under "flat.ph" this is every caller of the single network and not only
6408 // the callers of this one station, so it is taken from the layer record.
6409 if (L.npop >= 1.0) return L.npop;
6410 double n = 0.0;
6411 for (std::size_t c : L.callers) {
6412 const double v = njobs(c, idx);
6413 if (std::isfinite(v) && v > 0.0) n += v;
6414 }
6415 return n < 1.0 ? 1.0 : n;
6416 }
6417
6418 /**
6419 * Reconstruct the LQN metrics.
6420 *
6421 * A layer of this method reports one row per caller task, not one per entry,
6422 * activity and call, so the per-element quantities the rest of SolverLN reads
6423 * -- servt, residt, callservt, callresidt, tput -- are recovered analytically
6424 * from the series-parallel weights of the entry workflows.
6425 *
6426 * The split is conservative by construction. A station reports a residence
6427 * time R per visit against a service law of mean S, so the queueing inflation
6428 * R/S is attributed to every leaf of that visit in proportion to its own
6429 * mean: the pieces sum back to R exactly.
6430 */
6431 void update_metrics_ph(int it) {
6432 const std::size_t N = lqn.nidx;
6433 servt.assign(N + 1, Tzero());
6434 residt.assign(N + 1, Tzero());
6435 callservt.assign(lqn.ncalls + 1, Tzero());
6436 callresidt.assign(lqn.ncalls + 1, Tzero());
6437
6438 std::vector<T> inflNum(N + 1, Tzero()), inflDen(N + 1, Tzero());
6439 std::vector<T> taskTput(N + 1, Tzero()), openTput(N + 1, Tzero());
6440
6441 // Host layers: the queueing inflation of the processor demand
6442 for (std::size_t hidx = 1; hidx <= lqn.nhosts; ++hidx) {
6443 if (idxhash[hidx] < 0 || !ph_has_layer[hidx]) continue;
6444 const PHLayer& L = ph_layers[hidx];
6445 const LayerResult<T>& res = results.back()[std::size_t(idxhash[hidx])];
6446 const double npop = ph_layer_pop(L, hidx);
6447 for (std::size_t c : L.callers) {
6448 const std::size_t k = L.class_of_caller[c];
6449 T X = Tzero(), Q = Tzero();
6450 for (std::size_t s : L.qstations) {
6451 X = T(X + res.TN(s - 1, k - 1));
6452 Q = T(Q + res.QN(s - 1, k - 1));
6453 }
6454 const T R = ph_residence(Q, X, res.RN(L.qstations[0] - 1, k - 1));
6455 const T f = ph_inflation_of(R, L.svcmean_by_class[k], npop);
6456 if (!std::isfinite(dbl(X)) || dbl(X) < 0.0) X = Tzero();
6457 // TOTAL over the replicas. The processor layer of a replicated
6458 // element models ONE representative replica, so X is one replica's
6459 // rate and the element's own rate is REPL times it. The matching
6460 // per-replica quantity is ph_xdemand, which the think-time closure
6461 // divides down for the same reason.
6462 // A host with fewer replicas than C holds ALL of C's threads in the
6463 // one class, so X is already the total (BUG-110).
6464 double rc = lqn.repl[c];
6465 if (rc > 1.0 && njobs(c, hidx) >= lqn.maxmult[c] * rc) rc = 1.0;
6466 taskTput[c] = T(taskTput[c] + num_traits<T>::from_double(rc) * X);
6467 for (std::size_t eidx : lqn.entriesof[c]) {
6468 const T sh = dbl(ph_share[eidx]) > 0.0 ? ph_share[eidx] : Tzero();
6469 const T w = T(sh * X);
6470 inflNum[eidx] = T(inflNum[eidx] + w * f);
6471 inflDen[eidx] = T(inflDen[eidx] + w);
6472 }
6473 }
6474 for (const auto& oa : L.open_arrivals) {
6475 if (oa.second <= 0) continue; // an async call is served in the task layer
6476 const std::size_t k = oa.first;
6477 const std::size_t eidx = std::size_t(oa.second);
6478 T X = Tzero(), Q = Tzero();
6479 for (std::size_t s : L.qstations) {
6480 X = T(X + res.TN(s - 1, k - 1));
6481 Q = T(Q + res.QN(s - 1, k - 1));
6482 }
6483 if (!std::isfinite(dbl(X)) || dbl(X) <= 0.0) continue;
6484 const T f = ph_inflation_of(ph_residence(Q, X, res.RN(L.qstations[0] - 1, k - 1)),
6485 L.svcmean_by_class[k], npop);
6486 inflNum[eidx] = T(inflNum[eidx] + X * f);
6487 inflDen[eidx] = T(inflDen[eidx] + X);
6488 openTput[eidx] = T(openTput[eidx] + X);
6489 taskTput[lqn.parent[eidx]] = T(taskTput[lqn.parent[eidx]] + X);
6490 }
6491 }
6492
6493 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
6494 const std::size_t eidx = lqn.eshift + e;
6495 double f = 1.0;
6496 if (dbl(inflDen[eidx]) > GlobalConstants::FineTol)
6497 f = dbl(inflNum[eidx]) / dbl(inflDen[eidx]);
6498 if (!std::isfinite(f) || f < 1.0) f = 1.0; // a residence cannot fall below its demand
6499 const T fv = num_traits<T>::from_double(f);
6500 for (std::size_t aidx : lqn.actsof[eidx])
6501 residt[aidx] = T(fv * (lqn.hostdem[aidx].disabled ? Tzero()
6502 : lqn.hostdem[aidx].mean));
6503 }
6504
6505 // Task layers: the response time of every call
6506 std::vector<T> relw(N + 1, Tzero());
6507 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
6508 const std::size_t tidx = lqn.tshift + t;
6509 if (idxhash[tidx] < 0 || !ph_has_layer[tidx]) continue;
6510 const PHLayer& L = ph_layers[tidx];
6511 const LayerResult<T>& res = results.back()[std::size_t(idxhash[tidx])];
6512 const double npop = ph_layer_pop(L, tidx);
6513 for (std::size_t c : L.callers) {
6514 const std::size_t k = L.class_of_caller[c];
6515 T X = Tzero(), Q = Tzero();
6516 for (std::size_t s : L.qstations) {
6517 X = T(X + res.TN(s - 1, k - 1));
6518 Q = T(Q + res.QN(s - 1, k - 1));
6519 }
6520 if (!std::isfinite(dbl(X)) || dbl(X) < 0.0) X = Tzero();
6521 const T g = ph_inflation_of(ph_residence(Q, X, res.RN(L.qstations[0] - 1, k - 1)),
6522 L.svcmean_by_class[k], npop);
6523 for (std::size_t cidx = 1; cidx <= lqn.ncalls; ++cidx) {
6524 if (lqn.calltype[cidx] != CallType::SYNC) continue;
6525 if (lqn.parent[lqn.callpair_src[cidx]] != c) continue;
6526 if (lqn.parent[lqn.callpair_dst[cidx]] != tidx) continue;
6527 const std::size_t eidx = lqn.callpair_dst[cidx];
6528 callservt[cidx] = T(lqn.callproc_mean[cidx] * g * ph_entrymean[eidx]);
6529 callresidt[cidx] = callservt[cidx];
6530 }
6531 for (std::size_t eidx : lqn.entriesof[tidx])
6532 relw[eidx] = T(relw[eidx] + X * ph_ncalls(c, eidx));
6533 }
6534 for (const auto& oa : L.open_arrivals) {
6535 if (oa.second == 0) continue;
6536 const std::size_t k = oa.first;
6537 if (oa.second > 0) {
6538 // entry arrival served on its task layer: its rate enters the
6539 // entry shares and the thread-cycle demand that closes the
6540 // processor layer, whose thread chain then carries it, so it is
6541 // NOT added to taskTput, which that chain already reports
6542 T Xo = Tzero();
6543 for (std::size_t s : L.qstations) Xo = T(Xo + res.TN(s - 1, k - 1));
6544 if (std::isfinite(dbl(Xo)) && dbl(Xo) > 0.0)
6545 openTput[std::size_t(oa.second)] = T(openTput[std::size_t(oa.second)] + Xo);
6546 continue;
6547 }
6548 const std::size_t cidx = std::size_t(-oa.second);
6549 const std::size_t eidx = lqn.callpair_dst[cidx];
6550 T X = Tzero();
6551 for (std::size_t s : L.qstations) X = T(X + res.TN(s - 1, k - 1));
6552 const T R = res.RN(L.qstations[0] - 1, k - 1);
6553 if (std::isfinite(dbl(R)) && dbl(R) > 0.0) {
6554 callservt[cidx] = T(R * lqn.callproc_mean[cidx]);
6555 callresidt[cidx] = callservt[cidx];
6556 }
6557 if (std::isfinite(dbl(X)) && dbl(X) > 0.0) relw[eidx] = T(relw[eidx] + X);
6558 }
6559 }
6560
6561 // Entry shares and throughputs
6562 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
6563 const std::size_t tidx = lqn.tshift + t;
6564 const std::vector<std::size_t>& entries = lqn.entriesof[tidx];
6565 if (entries.empty()) continue;
6566 // How the requests SPLIT over the entries is a flow-balance question,
6567 // and is answered at the task layer: a caller class reaches that server
6568 // once per invocation of the caller, carrying its whole call burst in
6569 // its service law, so the station rate counts caller cycles and the
6570 // per-entry rate is that rate times the calls the caller makes.
6571 T tot = Tzero();
6572 for (std::size_t eidx : entries) tot = T(tot + relw[eidx] + openTput[eidx]);
6573 if (dbl(tot) > GlobalConstants::FineTol) {
6574 for (std::size_t eidx : entries)
6575 ph_share[eidx] = T((relw[eidx] + openTput[eidx]) / tot);
6576 } else {
6577 for (std::size_t eidx : entries)
6578 ph_share[eidx] = num_traits<T>::from_double(1.0 / double(entries.size()));
6579 }
6580 // HOW MANY requests the task completes is a different question, and the
6581 // flow-balance total does not answer it: that total is what the callers
6582 // DEMAND, not what the task's threads can deliver. A thread cycles
6583 // through its host demand AND then through the task think time, and only
6584 // the processor layer of the task carries both, so the rate is read there.
6585 tput[tidx] = dbl(taskTput[tidx]) > GlobalConstants::FineTol ? taskTput[tidx] : tot;
6586 for (std::size_t eidx : entries) tput[eidx] = T(tput[tidx] * ph_share[eidx]);
6587 // The DEMAND is kept apart because it, and not the rate just reported,
6588 // is what closes the surrogate delay: normalising the think time by a
6589 // rate the same think time produced makes the processor layer
6590 // self-referential. PER REPLICA, because the thread count it is paired
6591 // with there is per replica.
6592 const T nrep = num_traits<T>::from_double(std::max(1.0, lqn.repl[tidx]));
6593 ph_xdemand[tidx] = dbl(tot) > GlobalConstants::FineTol ? T(tot / nrep)
6594 : T(tput[tidx] / nrep);
6595 }
6596
6597 // Recovery, under-relaxation, and the derived per-element quantities
6598 for (std::size_t aidx = lqn.ashift + 1; aidx <= lqn.ashift + lqn.nacts; ++aidx) {
6599 T v = residt[aidx];
6600 if (!std::isfinite(dbl(v)) && it > 1 && !std::isnan(residt_prev[aidx]))
6601 v = residt_prev_v[aidx];
6602 if (relax_omega < 1.0 && it > 1 && !std::isnan(residt_prev[aidx])) {
6603 const T om = num_traits<T>::from_double(relax_omega);
6604 const T om1 = num_traits<T>::from_double(1.0 - relax_omega);
6605 v = T(om * v + om1 * residt_prev_v[aidx]);
6606 }
6607 residt[aidx] = v;
6608 residt_prev[aidx] = dbl(v);
6609 residt_prev_v[aidx] = v;
6610 }
6611 for (std::size_t cidx = 1; cidx <= lqn.ncalls; ++cidx) {
6612 T v = callservt[cidx];
6613 if (!std::isfinite(dbl(v)))
6614 v = (it > 1 && std::isfinite(callservt_prev[cidx])) ? callservt_prev_v[cidx]
6615 : Tzero();
6616 if (relax_omega < 1.0 && it > 1 && !std::isnan(callservt_prev[cidx])) {
6617 const T om = num_traits<T>::from_double(relax_omega);
6618 const T om1 = num_traits<T>::from_double(1.0 - relax_omega);
6619 v = T(om * v + om1 * callservt_prev_v[cidx]);
6620 }
6621 callservt[cidx] = v;
6622 callresidt[cidx] = v;
6623 callservt_prev[cidx] = dbl(v);
6624 callresidt_prev[cidx] = dbl(v);
6625 callservt_prev_v[cidx] = v;
6626 if (dbl(v) > 0.0) callservtproc[cidx] = Distrib<T>::exp_mean(v);
6627 }
6628
6629 // Recompose the entry laws from the iterate just computed. The entry
6630 // service time is then the mean of the COMPOSED law and not the sum of the
6631 // parts: the branches of an AND fork overlap, so an entry that forks
6632 // finishes with the last of its branches and is not charged their sum.
6633 ph_compose_entry_laws();
6634
6635 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
6636 const std::size_t eidx = lqn.eshift + e;
6637 if (!ph_has_wf[eidx]) continue;
6638 const std::unordered_map<std::size_t, T>& ex = ph_execs[eidx];
6639 for (std::size_t aidx : lqn.actsof[eidx]) {
6640 T sa = T(residt[aidx] + act_think_time(aidx));
6641 for (std::size_t cidx : lqn.callsof[aidx])
6642 if (lqn.calltype[cidx] == CallType::SYNC) sa = T(sa + callservt[cidx]);
6643 servt[aidx] = sa;
6644 servt_prev[aidx] = dbl(sa);
6645 servt_prev_v[aidx] = sa;
6646 tput[aidx] = T(tput[eidx] * ex.at(aidx));
6647 tput_prev[aidx] = dbl(tput[aidx]);
6648 tput_prev_v[aidx] = tput[aidx];
6649 // exp_rate admits a null rate, but a never-called activity has no arrivals: disabled says so, as the python twin does.
6650 tputproc[aidx] = dbl(tput[aidx]) > 0.0 ? Distrib<T>::exp_rate(tput[aidx])
6651 : Distrib<T>::disabled_dist();
6652 if (dbl(sa) > 0.0) servtproc[aidx] = Distrib<T>::exp_mean(sa);
6653 }
6654 servt[eidx] = ph_entrymean[eidx];
6655 residt[eidx] = ph_entrymean[eidx];
6656 if (dbl(servt[eidx]) > 0.0) servtproc[eidx] = Distrib<T>::exp_mean(servt[eidx]);
6657 }
6658 }
6659
6660 /**
6661 * Busy fraction of a task's threads, read from its own layer (ln_thread_busy_fraction.m).
6662 *
6663 * The think-time closure Z = njobs*(1-U)/X conserves throughput across a call only when
6664 * njobs*U is the mean number of HELD threads, sum_r T_r*S_r over c servers with S_r the
6665 * nominal service mean at the task station. Without a rate dependence that is the reported
6666 * Util. A load-, class- or joint-dependent station (server pools lower to the joint form)
6667 * reports Util normalized by its declared peak instead, so a 5-thread task with
6668 * class-dependence peak [2 1] read U = 1.35 and flow balance broke (T0 1.43412 against
6669 * E1/E2 1.94888). For such a station the fraction is computed from the definition; an
6670 * infinite server, or one with no dependence, returns the plain row sum; `skipnan` keeps
6671 * the srvn.ph closure's habit of dropping NaN entries from that sum.
6672 */
6673 T thread_busy_fraction(const qn::Layer<T>& L, std::size_t ts, const LayerResult<T>& r,
6674 bool skipnan) const {
6675 const qn::Station<T>& st = L.stations[ts - 1];
6676 const double c = st.nservers;
6677 const bool hasdep = !st.lldscaling.empty() || bool(st.cdscaling) || bool(st.jdscaling);
6678 T u = Tzero();
6679 if (!hasdep || std::isinf(c) || c <= 0.0) {
6680 for (std::size_t k = 0; k < L.nclasses; ++k) {
6681 const T v = r.UN(ts - 1, k);
6682 if (!skipnan || !std::isnan(dbl(v))) u = T(u + v);
6683 }
6684 return u;
6685 }
6686 for (std::size_t k = 0; k < L.nclasses; ++k) {
6687 const T x = r.TN(ts - 1, k);
6688 if (std::isnan(dbl(x)) || !(dbl(x) > 0.0)) continue;
6689 const Distrib<T>& d = L.service[ts - 1][k];
6690 if (d.disabled) continue;
6691 if (std::isfinite(dbl(d.mean))) u = T(u + x * d.mean);
6692 }
6693 return T(u / num_traits<T>::from_double(c));
6694 }
6695
6696 /**
6697 * Surrogate delay of every caller.
6698 *
6699 * Same closure as update_think_times -- a thread of the task is idle for
6700 * whatever of its cycle the task's own station does not hold -- but the rate
6701 * it is normalised by is the INVOCATION rate of the task and not the
6702 * throughput of its station. Under this method a caller class reaches the
6703 * server once per invocation of the caller, carrying its whole call burst in
6704 * its service law, so the station rate counts caller cycles rather than calls
6705 * and the two differ by the mean number of calls.
6706 */
6707 void update_think_times_ph(int it) {
6708 thinktproc.assign(lqn.nidx + 1, Distrib<T>::disabled_dist());
6709 const T floorv = num_traits<T>::from_double(GlobalConstants::Zero);
6710 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
6711 const std::size_t tidx = lqn.tshift + t;
6712 if (ignore[tidx]) continue;
6713 const T ztask = ref_think_time(tidx);
6714 if (idxhash[tidx] < 0) {
6715 // A task no other task calls but whose entries carry an arrival
6716 // still has a cycle: its threads are driven by the stream.
6717 // build_layers_ph drops the open class for it precisely so this
6718 // closure can set the rate.
6719 const double arvrate = open_arrival_rate_of(tidx);
6720 if (arvrate > GlobalConstants::FineTol) {
6721 double nja = lqn.maxmult[tidx];
6722 if (!std::isfinite(nja) || nja <= 0.0) {
6723 nja = 0.0;
6724 for (std::size_t c = 1; c <= NT(); ++c) nja = std::max(nja, njobs(tidx, c));
6725 }
6726 T hres = Tzero();
6727 const std::size_t hidx = lqn.parent[tidx];
6728 if (hidx >= 1 && hidx < idxhash.size() && idxhash[hidx] >= 0 &&
6729 ph_has_layer[hidx] && ph_layers[hidx].class_of_caller[tidx] > 0) {
6730 const PHLayer& HL = ph_layers[hidx];
6731 const LayerResult<T>& hr = results.back()[std::size_t(idxhash[hidx])];
6732 const T rr = hr.RN(HL.qstations[0] - 1, HL.class_of_caller[tidx] - 1);
6733 if (!std::isnan(dbl(rr))) hres = rr;
6734 }
6735 hres += open_arrival_call_residt(tidx, arvrate);
6736 T za = T(num_traits<T>::from_double(nja / arvrate) - hres - ztask);
6737 if (za < floorv) za = floorv;
6738 if (relax_omega < 1.0 && it > 1 && !std::isnan(thinkt_prev[tidx])) {
6739 const T om = num_traits<T>::from_double(relax_omega);
6740 const T om1 = num_traits<T>::from_double(1.0 - relax_omega);
6741 za = T(om * za + om1 * thinkt_prev_v[tidx]);
6742 }
6743 tput[tidx] = num_traits<T>::from_double(arvrate);
6744 thinkt[tidx] = za;
6745 thinkt_prev[tidx] = dbl(za);
6746 thinkt_prev_v[tidx] = za;
6747 thinktproc[tidx] = Distrib<T>::exp_mean(T(za + ztask));
6748 continue;
6749 }
6750 // a reference task, or one no other task calls: it has no station
6751 // of its own, so its only delay is the think time the user declared
6752 thinkt[tidx] = num_traits<T>::from_double(GlobalConstants::FineTol);
6753 thinktproc[tidx] = Distrib<T>::immediate();
6754 continue;
6755 }
6756 const PHLayer& L = ph_layers[tidx];
6757 const qn::Layer<T>& m = ensemble[std::size_t(idxhash[tidx])];
6758 const LayerResult<T>& r = results.back()[std::size_t(idxhash[tidx])];
6759 // the thread busy fraction, not a dependent station's peak-normalized Util
6760 T U = thread_busy_fraction(m, L.qstations[0], r, true);
6761 util[tidx] = U;
6762 // The closure below measures a thread's cycle in WORK: it is idle for
6763 // whatever of the cycle its station does not hold it working. A
6764 // SetupTask's station service also carries a cold start, which is time
6765 // the thread is unavailable but is not work, so it is taken back out of
6766 // U before the closure reads it. Zero for every task without a setup.
6767 if (dbl(ph_setupshare[tidx]) > 0.0)
6768 U = T(U * (Tone() - ph_setupshare[tidx]));
6769 // the rate the CALLERS ask of the task, not the rate its processor
6770 // layer reported: the latter is itself a function of this think time
6771 T X = ph_xdemand[tidx];
6772 if (!(dbl(X) > GlobalConstants::FineTol)) X = tput[tidx];
6773 // The thread pool of ONE replica, the convention ph_xdemand is kept in
6774 double nj = lqn.maxmult[tidx];
6775 if (!std::isfinite(nj) || nj <= 0.0) {
6776 nj = 0.0;
6777 for (std::size_t c = 1; c <= NT(); ++c) nj = std::max(nj, njobs(tidx, c));
6778 }
6779 T z;
6780 if (dbl(X) > GlobalConstants::FineTol) {
6781 if (lqn.sched[tidx] == SchedStrategy::INF) {
6782 // an infinite server reports a mean number of busy threads
6783 z = T((num_traits<T>::from_double(nj) - U) / X - ztask);
6784 } else {
6785 const T om = U > Tone() ? T(U - Tone()) : T(Tone() - U);
6786 z = T(num_traits<T>::from_double(nj) * om / X - ztask);
6787 }
6788 } else {
6789 z = thinkt[tidx];
6790 }
6791 if (z < floorv) z = floorv;
6792 if (it > 1 && !std::isnan(thinkt_prev[tidx]) && !std::isfinite(dbl(z)))
6793 z = thinkt_prev_v[tidx];
6794 if (relax_omega < 1.0 && it > 1 && !std::isnan(thinkt_prev[tidx])) {
6795 const T om = num_traits<T>::from_double(relax_omega);
6796 const T om1 = num_traits<T>::from_double(1.0 - relax_omega);
6797 z = T(om * z + om1 * thinkt_prev_v[tidx]);
6798 }
6799 thinkt[tidx] = z;
6800 thinkt_prev[tidx] = dbl(z);
6801 thinkt_prev_v[tidx] = z;
6802 thinktproc[tidx] = Distrib<T>::exp_mean(T(z + ztask));
6803 }
6804 }
6805
6806 /**
6807 * LQN-level results of method "srvn.ph".
6808 *
6809 * The layers report per caller task, so every entry, activity and call figure
6810 * is rebuilt from the converged fixed point rather than read off a class row,
6811 * in the layout aggregate() returns: QN carries the entry and task
6812 * utilizations, UN the processor utilizations, RN the response times and WN
6813 * the residence times.
6814 */
6815 LnSolution<T> aggregate_ph() {
6816 const std::size_t N = lqn.nidx;
6817 LnSolution<T> out;
6818 out.QN.assign(N + 1, Tzero());
6819 out.UN.assign(N + 1, Tzero());
6820 out.RN.assign(N + 1, Tzero());
6821 out.TN.assign(N + 1, Tzero());
6822 out.AN.assign(N + 1, Tzero());
6823 out.WN.assign(N + 1, Tzero());
6824 out.defined_Q.assign(N + 1, false);
6825 out.defined_U.assign(N + 1, false);
6826 out.defined_R.assign(N + 1, false);
6827 out.defined_T.assign(N + 1, false);
6828 out.defined_A.assign(N + 1, false);
6829 out.defined_W.assign(N + 1, false);
6830 out.iterations = iterations_done;
6831 out.converged = did_converge;
6832
6833 std::vector<T> PN(N + 1, Tzero()), UT(N + 1, Tzero());
6834 std::vector<bool> hasPN(N + 1, false), hasUT(N + 1, false);
6835
6836 for (std::size_t a = 1; a <= lqn.nacts; ++a) {
6837 const std::size_t aidx = lqn.ashift + a;
6838 const std::size_t tidx = lqn.parent[aidx];
6839 if (ignore[tidx]) continue;
6840 const std::size_t hidx = lqn.parent[tidx];
6841 out.TN[aidx] = tput[aidx];
6842 out.defined_T[aidx] = true;
6843 out.RN[aidx] = servt[aidx];
6844 out.defined_R[aidx] = true;
6845 UT[aidx] = T(tput[aidx] * servt[aidx]);
6846 hasUT[aidx] = true;
6847 // LINE scales the utilization of a queueing station into [0,1] whatever
6848 // its multiplicity, and reports a mean number of busy servers at an
6849 // infinite server: the processor share of an activity follows the same
6850 // convention
6851 const T hd = lqn.hostdem[aidx].disabled ? Tzero() : lqn.hostdem[aidx].mean;
6852 PN[aidx] = T(tput[aidx] * hd / num_traits<T>::from_double(ph_host_servers(hidx)));
6853 hasPN[aidx] = true;
6854 PN[hidx] = T(PN[hidx] + PN[aidx]);
6855 hasPN[hidx] = true;
6856 }
6857
6858 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
6859 const std::size_t eidx = lqn.eshift + e;
6860 const std::size_t tidx = lqn.parent[eidx];
6861 if (ignore[tidx]) continue;
6862 out.TN[eidx] = tput[eidx];
6863 out.defined_T[eidx] = true;
6864 out.RN[eidx] = servt[eidx];
6865 out.defined_R[eidx] = true;
6866 UT[eidx] = T(tput[eidx] * servt[eidx]);
6867 hasUT[eidx] = true;
6868 for (std::size_t aidx : lqn.actsof[eidx]) {
6869 PN[eidx] = T(PN[eidx] + PN[aidx]);
6870 hasPN[eidx] = true;
6871 }
6872 // ResidT is reported per visit to the TASK, not per execution of the
6873 // activity: an activity of this entry runs EXECS times per invocation,
6874 // and the entry takes SHARE of the task's invocations. RespT stays per
6875 // execution.
6876 if (ph_has_wf[eidx]) {
6877 const std::unordered_map<std::size_t, T>& ex = ph_execs[eidx];
6878 for (std::size_t aidx : lqn.actsof[eidx]) {
6879 out.WN[aidx] = T(ph_share[eidx] * ex.at(aidx) * residt[aidx]);
6880 out.defined_W[aidx] = true;
6881 }
6882 }
6883 UT[tidx] = T(UT[tidx] + UT[eidx]);
6884 hasUT[tidx] = true;
6885 }
6886
6887 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
6888 const std::size_t tidx = lqn.tshift + t;
6889 if (ignore[tidx]) continue;
6890 out.TN[tidx] = tput[tidx];
6891 out.defined_T[tidx] = true;
6892 T w = Tzero();
6893 bool anyw = false;
6894 for (std::size_t aidx : lqn.actsof[tidx]) {
6895 PN[tidx] = T(PN[tidx] + PN[aidx]);
6896 hasPN[tidx] = true;
6897 if (out.defined_W[aidx]) { w = T(w + out.WN[aidx]); anyw = true; }
6898 }
6899 if (anyw) { out.WN[tidx] = w; out.defined_W[tidx] = true; }
6900 }
6901
6902 for (std::size_t hidx = 1; hidx <= lqn.nhosts; ++hidx)
6903 out.defined_T[hidx] = false; // kept undefined for consistency with LQNS
6904
6905 for (std::size_t idx = 1; idx <= N; ++idx) {
6906 out.QN[idx] = UT[idx];
6907 out.defined_Q[idx] = hasUT[idx];
6908 out.UN[idx] = PN[idx];
6909 out.defined_U[idx] = hasPN[idx];
6910 // Idle, not undefined -- the same rule aggregate() applies, and for the
6911 // same reason: an unreachable element reports zero for the measures its
6912 // kind HAS and leaves the ones it never has undefined, so that the
6913 // table's NaN mask survives a disconnected component.
6914 if (ignore[idx]) {
6915 out.UN[idx] = Tzero(); // every kind reports a utilization
6916 out.defined_U[idx] = true;
6917 out.defined_A[idx] = false; // nothing reports an arrival rate on an LQN
6918 const bool host = lqn.type[idx] == LqnElement::HOST;
6919 const bool task = lqn.type[idx] == LqnElement::TASK;
6920 const bool entry = lqn.type[idx] == LqnElement::ENTRY;
6921 out.QN[idx] = Tzero();
6922 out.defined_Q[idx] = !host;
6923 out.RN[idx] = Tzero();
6924 out.defined_R[idx] = !host && !task;
6925 out.WN[idx] = Tzero();
6926 out.defined_W[idx] = !host && !entry;
6927 out.TN[idx] = Tzero();
6928 out.defined_T[idx] = !host;
6929 }
6930 }
6931 return out;
6932 }
6933
6934 void update_metrics(int it) {
6935 if (is_ph_encoding()) {
6936 update_metrics_ph(it);
6937 return;
6938 }
6939 if (lnmethod == "moment3") {
6940 update_metrics_moment_based(it);
6941 return;
6942 }
6943 update_metrics_default(it);
6944 }
6945
6946 /**
6947 * Port of ln_layer_refcell: the 1-based class whose throughput at its
6948 * refstat normalises a residence of class K (0-based) in the layer of
6949 * element IDX, 0 when there is none. A chain merged by refpath holds more
6950 * than one caller task and only ONE reference class, so the per-caller rate
6951 * is read through the layer's normclass; everywhere else it is the chain's
6952 * reference class, which is what normclass would have named anyway.
6953 */
6954 std::size_t layer_refclass(std::size_t idx, const qn::Layer<T>& L, std::size_t k) const {
6955 const auto it = layer_normclass.find(idx);
6956 if (it != layer_normclass.end() && k < it->second.size() && it->second[k] > 0)
6957 return it->second[k];
6958 std::size_t c = 0;
6959 for (std::size_t cc = 0; cc < L.nchains; ++cc)
6960 if (L.chains[cc][k]) c = cc;
6961 return L.refclass[c];
6962 }
6963
6964 void update_metrics_default(int it) {
6965 const std::size_t N = lqn.nidx;
6966 servt.assign(N + 1, Tzero());
6967 residt.assign(N + 1, Tzero());
6968 const int iter_min = std::min(30, int(std::ceil(opt.iter_max / 4.0)));
6969 const bool averaging = averagingstart >= 0 && it >= iter_min;
6970 const int wnd = averaging ? int(it - averagingstart + 1) : 1;
6971
6972 for (const UpdRow& row : servt_map) {
6973 const std::size_t e = std::size_t(idxhash[row.idx]);
6974 const qn::Layer<T>& L = ensemble[e];
6975 const std::size_t k = row.cls - 1;
6976 const std::size_t refclass_c = layer_refclass(row.idx, L, k);
6977 const std::size_t refstat_k = L.classes[k].refstat;
6978
6979 T sv = Tzero(), rs = Tzero(), tp = Tzero();
6980 const T wT = T(Tone() / num_traits<T>::from_int(wnd));
6981 for (int w = 0; w < wnd; ++w) {
6982 const LayerResult<T>& r = results[results.size() - 1 - w][e];
6983 sv += r.RN(row.node - 1, k) * wT;
6984 const T TN_ref = (refclass_c > 0 && refstat_k > 0) ? r.TN(refstat_k - 1, refclass_c - 1) : Tzero();
6985 if (dbl(TN_ref) > GlobalConstants::FineTol)
6986 rs += r.QN(row.node - 1, k) / TN_ref * wT;
6987 else
6988 rs += r.WN(row.node - 1, k) * wT;
6989 tp += r.TN(row.node - 1, k) * wT;
6990 }
6991 servt[row.aidx] = sv;
6992 residt[row.aidx] = rs;
6993 tput[row.aidx] = tp;
6994
6995 // A host layer holding every replica of the task spreads its class evenly
6996 // over the host's identical replica stations, and what was read is one of
6997 // them: the residence and rate are the sum over all (BUG-110)
6998 if (lqn.parent[lqn.parent[row.aidx]] == row.idx) {
6999 const auto hr = host_all_replica_tasks.find(lqn.parent[row.aidx]);
7000 if (hr != host_all_replica_tasks.end() && hr->second > 1) {
7001 const T h = num_traits<T>::from_double(double(hr->second));
7002 residt[row.aidx] = T(h * residt[row.aidx]);
7003 tput[row.aidx] = T(h * tput[row.aidx]);
7004 }
7005 }
7006
7007 // an activity think time is in series with the host demand
7008 const Distrib<T>& at = lqn.actthink[row.aidx];
7009 if (!at.disabled && dbl(at.mean) > GlobalConstants::FineTol) {
7010 servt[row.aidx] = T(servt[row.aidx] + at.mean);
7011 residt[row.aidx] = T(residt[row.aidx] + at.mean);
7012 }
7013
7014 // An activity of an async-only entry takes RN, the response per
7015 // visit, and not the visit-weighted residence: entry selection
7016 // routes the task to each of its entries with a share, and there is
7017 // no caller-side visit ratio here to divide that share back out
7018 // (the sync branch below does exactly that). updateMetricsDefault.m:63-77.
7019 if (async_only_activity(row.aidx)) residt[row.aidx] = servt[row.aidx];
7020
7021 if (relax_omega < 1.0 && it > 1) {
7022 const T om = num_traits<T>::from_double(relax_omega);
7023 const T om1 = num_traits<T>::from_double(1.0 - relax_omega);
7024 if (!std::isnan(servt_prev[row.aidx]))
7025 servt[row.aidx] = T(om * servt[row.aidx] + om1 * servt_prev_v[row.aidx]);
7026 if (!std::isnan(residt_prev[row.aidx]))
7027 residt[row.aidx] = T(om * residt[row.aidx] + om1 * residt_prev_v[row.aidx]);
7028 if (!std::isnan(tput_prev[row.aidx]))
7029 tput[row.aidx] = T(om * tput[row.aidx] + om1 * tput_prev_v[row.aidx]);
7030 }
7031 servt_prev[row.aidx] = dbl(servt[row.aidx]);
7032 residt_prev[row.aidx] = dbl(residt[row.aidx]);
7033 tput_prev[row.aidx] = dbl(tput[row.aidx]);
7034 servt_prev_v[row.aidx] = servt[row.aidx];
7035 residt_prev_v[row.aidx] = residt[row.aidx];
7036 tput_prev_v[row.aidx] = tput[row.aidx];
7037
7038 if (servt[row.aidx] > Tzero() && dbl(servt[row.aidx]) <= 1e10)
7039 servtproc[row.aidx] = Distrib<T>::exp_mean(servt[row.aidx]);
7040 tputproc[row.aidx] = Distrib<T>::exp_rate(tput[row.aidx]);
7041 }
7042
7043 // The phase split of servt, updateMetricsDefault.m:120-151. It is
7044 // recomputed from scratch each iteration because servt is; the
7045 // overtaking probability it feeds is computed later, once the entry
7046 // throughputs exist.
7047 if (has_phase2) {
7048 servt_ph1.assign(N + 1, Tzero());
7049 servt_ph2.assign(N + 1, Tzero());
7050 for (std::size_t a = 1; a <= lqn.nacts; ++a) {
7051 const std::size_t aidx = lqn.ashift + a;
7052 if (lqn.actphase[a] == 1)
7053 servt_ph1[aidx] = servt[aidx];
7054 else
7055 servt_ph2[aidx] = servt[aidx];
7056 }
7057 // the ENTRY split is taken once the entry service exists, below: summing the
7058 // activities' own servt left out the synchronous calls each phase makes
7059 }
7060
7061 // throughput of the activities that appear only as client-side classes
7062 for (const UpdRow& row : thinkt_map) {
7063 if (!tputproc[row.aidx].disabled) continue;
7064 const std::size_t e = std::size_t(idxhash[row.idx]);
7065 T tp = Tzero();
7066 const T wT = T(Tone() / num_traits<T>::from_int(wnd));
7067 for (int w = 0; w < wnd; ++w)
7068 tp += results[results.size() - 1 - w][e].TN(row.node - 1, row.cls - 1) * wT;
7069 tput[row.aidx] = tp;
7070 tputproc[row.aidx] = Distrib<T>::exp_rate(tp);
7071 }
7072
7073 // call service and residence times
7074 callservt.assign(lqn.ncalls + 1, Tzero());
7075 callresidt.assign(lqn.ncalls + 1, Tzero());
7076 // A call into a replicated callee registers ONE ROW PER REPLICA STATION, each
7077 // rewriting the same entry, so a Little residence read off one station keeps one
7078 // replica's share. The replicas are symmetric, so the whole call is that share
7079 // times the number of DISTINCT stations (rows would also count a call reached from
7080 // several graph positions). Without it 51-replication's B1 read a response time of
7081 // 44.2 against the reference's 99.9 (BUG-103; updateMetricsDefault.m callRowsPerLayer).
7082 std::vector<std::size_t> call_rows(call_map.size(), 1);
7083 for (std::size_t q = 0; q < call_map.size(); ++q) {
7084 std::vector<std::size_t> st;
7085 for (const UpdRow& o : call_map)
7086 if (o.idx == call_map[q].idx && o.aidx == call_map[q].aidx && o.node > 1 &&
7087 std::find(st.begin(), st.end(), o.node) == st.end())
7088 st.push_back(o.node);
7089 call_rows[q] = std::max<std::size_t>(1, st.size());
7090 }
7091 for (std::size_t q = 0; q < call_map.size(); ++q) {
7092 const UpdRow& row = call_map[q];
7093 if (row.node <= 1) continue; // a client-side call class contributes none
7094 const std::size_t e = std::size_t(idxhash[row.idx]);
7095 const LayerResult<T>& r = results.back()[e];
7096 callservt[row.aidx] =
7097 T(r.RN(row.node - 1, row.cls - 1) * lqn.callproc_mean[row.aidx]);
7098 // Normalise per chain-reference visit, as residt does. WN divides by the
7099 // class's own reference rate when the layer is open (an INF client task),
7100 // which is per-ENTRY visit, and the entry rescaling in
7101 // resolve_entry_service would then charge the call once per entry.
7102 {
7103 const qn::Layer<T>& L = ensemble[e];
7104 const std::size_t k = row.cls - 1;
7105 const std::size_t refclass_c = layer_refclass(row.idx, L, k);
7106 const std::size_t refstat_k = L.classes[k].refstat;
7107 const T TN_ref = (refclass_c > 0 && refstat_k > 0) ? r.TN(refstat_k - 1, refclass_c - 1) : Tzero();
7108 callresidt[row.aidx] = dbl(TN_ref) > GlobalConstants::FineTol
7109 ? T(num_traits<T>::from_int(int(call_rows[q])) *
7110 r.QN(row.node - 1, k) / TN_ref)
7111 : r.WN(row.node - 1, k);
7112 }
7113 const T rw = region_wait(e, row.cls);
7114 if (rw > Tzero()) {
7115 callservt[row.aidx] = T(callservt[row.aidx] + rw);
7116 callresidt[row.aidx] = T(callresidt[row.aidx] + rw);
7117 }
7118 if (relax_omega < 1.0 && it > 1 && !std::isnan(callservt_prev[row.aidx])) {
7119 const T om = num_traits<T>::from_double(relax_omega);
7120 const T om1 = num_traits<T>::from_double(1.0 - relax_omega);
7121 callservt[row.aidx] =
7122 T(om * callservt[row.aidx] + om1 * callservt_prev_v[row.aidx]);
7123 }
7124 callservt_prev[row.aidx] = dbl(callservt[row.aidx]);
7125 callservt_prev_v[row.aidx] = callservt[row.aidx];
7126 callresidt_prev[row.aidx] = dbl(callresidt[row.aidx]);
7127 }
7128
7129 resolve_entry_service();
7130
7131 // The overtaking correction, updateMetricsDefault.m:313-351. It runs
7132 // HERE and not with the split above because it needs the entry
7133 // throughput resolve_entry_service has just produced.
7134 //
7135 // servt keeps both phases -- the server IS busy through phase 2, so the
7136 // utilization is unchanged -- while residt becomes the CALLER's view:
7137 // phase 1 in full, phase 2 only when the caller is actually overtaken.
7138 if (has_phase2) {
7139 // Entry phase split: the phase-2 share of the entry service, calls included,
7140 // scaled onto servt as resolve_entry_service scaled the total
7141 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
7142 const std::size_t eidx = lqn.eshift + e;
7143 servt_ph2[eidx] = (eidx < entry_servt_last.size() && entry_servt_last[eidx] > Tzero())
7144 ? T(entry_servt_ph2[eidx] * servt[eidx] / entry_servt_last[eidx])
7145 : Tzero();
7146 servt_ph1[eidx] = T(servt[eidx] - servt_ph2[eidx]);
7147 }
7148 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
7149 const std::size_t eidx = lqn.eshift + e;
7150 const std::size_t tidx = lqn.parent[eidx];
7151 if (!(dbl(servt_ph2[eidx]) > GlobalConstants::FineTol)) continue;
7152 if (lqn.isref[tidx] || !lqn.issynccaller.any_col(eidx)) {
7153 residt[eidx] = servt[eidx];
7154 continue;
7155 }
7156 T entry_tput = Tzero();
7157 if (dbl(tput[eidx]) > GlobalConstants::FineTol)
7158 entry_tput = tput[eidx];
7159 else if (dbl(tput[tidx]) > GlobalConstants::FineTol)
7160 entry_tput = tput[tidx];
7161 prOvertake[e] =
7162 dbl(entry_tput) > GlobalConstants::FineTol
7163 ? lqn_overtake_prob_markov(lqn, servt, callresidt, tput, eidx,
7164 servt_ph2[eidx])
7165 : Tzero();
7166 residt[eidx] = T(servt_ph1[eidx] + prOvertake[e] * servt_ph2[eidx]);
7167 }
7168 }
7169
7170 for (const UpdRow& row : call_map) {
7171 if (row.node <= 1) continue;
7172 const std::size_t eidx = lqn.callpair_dst[row.aidx];
7173 if (servt[eidx] > Tzero()) servtproc[eidx] = Distrib<T>::exp_mean(servt[eidx]);
7174 }
7175 for (const UpdRow& row : call_map) {
7176 if (row.node <= 1) continue;
7177 const std::size_t eidx = lqn.callpair_dst[row.aidx];
7178 if (it == 1) {
7179 callservt[row.aidx] = servt[eidx];
7180 callservtproc[row.aidx] = servtproc[eidx];
7181 } else if (callservt[row.aidx] > Tzero()) {
7182 callservtproc[row.aidx] = Distrib<T>::exp_mean(callservt[row.aidx]);
7183 }
7184 }
7185
7186 // What a synchronous CALLER waits for at a phase-2 target is residt,
7187 // not servt (updateMetricsDefault.m:384-400): the loop just above set it
7188 // from the target's full service, which would charge the caller for
7189 // phase 2 it never waits through. Under srvn layering the callee's layer
7190 // already serves residt (update_layers), so the response read from it is
7191 // residt plus the callee's queueing and must stand after the first pass:
7192 // overriding it with a residt computed before update_populations charges
7193 // the caller a value the callee no longer serves (BUGS.md BUG-103).
7194 if (has_phase2 && (is_flat_layering() || it == 1)) {
7195 for (std::size_t cidx = 1; cidx <= lqn.ncalls; ++cidx) {
7196 if (lqn.calltype[cidx] != CallType::SYNC) continue;
7197 const std::size_t target = lqn.callpair_dst[cidx];
7198 if (target <= lqn.eshift || target > lqn.eshift + lqn.nentries) continue;
7199 if (!(dbl(servt_ph2[target]) > GlobalConstants::FineTol)) continue;
7200 const T eff = residt[target]; // servt_ph1 + prOvertake * servt_ph2
7201 if (!(eff > Tzero())) continue;
7202 const T w = T(eff * lqn.callproc_mean[cidx]);
7203 callservt[cidx] = w;
7204 callresidt[cidx] = w;
7205 callservtproc[cidx] = Distrib<T>::exp_mean(w);
7206 }
7207 }
7208 }
7209
7210 // -----------------------------------------------------------------------
7211 // updateMetricsMomentBased, the `moment3` method
7212 // -----------------------------------------------------------------------
7213
7214 /**
7215 * The moments of an empirical CDF, MATLAB's `EmpiricalCDF.getMoments`.
7216 *
7217 * READ EXACTLY AS THE REFERENCE READS IT, and the reading is not the
7218 * obvious one: the weight of a bin is the CDF INCREMENT and its abscissa is
7219 * the MIDPOINT of the two t values, so this is a midpoint quadrature of
7220 * integral x^k dF and not a sum over grid points. Reading the grid as a pmf
7221 * at the right endpoint instead inflates every moment; that exact mistake
7222 * cost a wrong entry mean in the Python port (see _kb/06-solver-catalog.md).
7223 */
7224 static void cdf_moments(const fluid::FluidPassage& c, double& m1, double& m2, double& m3) {
7225 m1 = m2 = m3 = 0.0;
7226 for (std::size_t i = 0; i + 1 < c.t.size(); ++i) {
7227 const double x = 0.5 * (c.t[i + 1] + c.t[i]);
7228 const double w = c.cdf[i + 1] - c.cdf[i];
7229 m1 += x * w;
7230 m2 += x * x * w;
7231 m3 += x * x * x * w;
7232 }
7233 }
7234
7235 /** The per-layer response-time CDFs, computed once and cached. */
7236 const std::vector<std::vector<fluid::FluidPassage>>& layer_cdf(std::size_t e) {
7237 if (cdf_repo[e].empty()) {
7238 // THE LAYER HAS NO ROUTING MATRIX UNTIL IT IS ASKED FOR ONE, and the
7239 // fluid drift is built from `sn.rt` alone: without this the ODE has
7240 // no transitions, the state decays to zero, every passage reports the
7241 // degenerate curve at the origin and every entry ends up with an
7242 // empty convolution and a service time of zero. Same reason as in
7243 // solve_layer_fluid, and the failure is silent in both.
7244 ensemble[e].refresh_rt();
7245 try {
7246 cdf_repo[e] = detail::ln_fluid_cdf_respt(ensemble[e], opt.layer_fluid);
7247 } catch (const std::exception&) {
7248 // The reference falls back to the LAYER's own solver when the
7249 // fluid passage fails, and for the MVA-family layers that is
7250 // the base-class exponential law with the layer's mean -- so
7251 // the fallback here is that law over the last solved averages,
7252 // rather than an empty repo that silently collapses every
7253 // entry law to its bare host demand.
7254 cdf_repo[e] = layer_cdf_exp_fallback(e);
7255 }
7256 }
7257 return cdf_repo[e];
7258 }
7259
7260 /** The base-class exponential CDF over layer e's last solved mean response
7261 * times, the reference's fallback route when the fluid passage fails. */
7262 std::vector<std::vector<fluid::FluidPassage>> layer_cdf_exp_fallback(std::size_t e) {
7263 const qn::NetworkStruct<T>& L = ensemble[e];
7264 std::vector<std::vector<fluid::FluidPassage>> out(
7265 L.nstations, std::vector<fluid::FluidPassage>(L.nclasses));
7266 if (results.empty() || e >= results.back().size()) return out;
7267 const Matrix<T>& RN = results.back()[e].RN;
7268 const std::size_t npts = 100;
7269 for (std::size_t i = 0; i < L.nstations; ++i) {
7270 if (L.stations[i].nodetype == qn::NodeType::Source) continue;
7271 for (std::size_t r = 0; r < L.nclasses; ++r) {
7272 if (L.disabled[i][r]) continue;
7273 const double rn = (i < static_cast<std::size_t>(RN.rows()) &&
7274 r < static_cast<std::size_t>(RN.cols()))
7275 ? dbl(RN(i, r))
7276 : 0.0;
7277 if (!(std::isfinite(rn) && rn > 0.0)) continue;
7278 fluid::FluidPassage& cell = out[i][r];
7279 cell.t.reserve(npts);
7280 cell.cdf.reserve(npts);
7281 for (std::size_t j = 0; j < npts; ++j) {
7282 const double q =
7283 0.001 + (0.999 - 0.001) * static_cast<double>(j) / (npts - 1);
7284 cell.cdf.push_back(q);
7285 cell.t.push_back(-std::log(1.0 - q) * rn);
7286 }
7287 }
7288 }
7289 return out;
7290 }
7291
7292 /**
7293 * task_tput / entry_tput at the host layer of `eidx`.
7294 *
7295 * This is what renormalises a residence time from "one visit to the TASK",
7296 * which is how the layer reports it, to "one visit to the ENTRY", which is
7297 * what an entry metric means. It exists as a helper because applying it
7298 * TWICE is a real and silent failure mode: `moment3` once summed per-visit
7299 * response times and then applied this ratio on top, inflating every entry
7300 * service time by the entries-per-task ratio.
7301 *
7302 * `state` is 0 when the entry's layers are ignored (nothing is assigned at
7303 * all), 1 when it has no synchronous caller (no ratio exists) and 2 when
7304 * `ratio` is set.
7305 */
7306 int entry_visit_ratio(std::size_t eidx, T& ratio) const {
7307 const std::size_t tidx = lqn.parent[eidx];
7308 const std::size_t hidx = lqn.parent[tidx];
7309 if (ignore[tidx] || ignore[hidx] || idxhash[hidx] < 0) return 0;
7310 if (!lqn.issynccaller.any_col(eidx)) return 1;
7311 const std::size_t hl = std::size_t(idxhash[hidx]);
7312 const qn::Layer<T>& L = ensemble[hl];
7313 const LayerResult<T>& r = results.back()[hl];
7314 T task_tput = Tzero(), entry_tput = Tzero();
7315 for (const auto& kv : L.attr_tasks)
7316 if (kv.second == tidx) task_tput += r.TN(L.clientIdx - 1, kv.first - 1);
7317 for (const auto& kv : L.attr_entries)
7318 if (kv.second == eidx) entry_tput += r.TN(L.clientIdx - 1, kv.first - 1);
7319 const T floor = num_traits<T>::from_double(GlobalConstants::Zero);
7320 ratio = T(task_tput / (entry_tput > floor ? entry_tput : floor));
7321 return 2;
7322 }
7323
7324 /** (I - servtmatrix)^-1, the reference's `inv(eye - servtmatrix)`. */
7325 Matrix<T> entry_service_resolvent() const {
7326 const std::size_t dim = lqn.nidx + lqn.ncalls;
7327 Matrix<T> A(dim + 1, dim + 1, Tzero());
7328 for (std::size_t i = 0; i <= dim; ++i) {
7329 A(i, i) = Tone();
7330 for (std::size_t j = 0; j <= dim; ++j) A(i, j) = T(A(i, j) - servtmatrix(i, j));
7331 }
7332 return ::line::inverse(A);
7333 }
7334
7335 /**
7336 * Port of @@SolverLN/updateMetricsMomentBased.m, the `moment3` method.
7337 *
7338 * WHAT IT DOES DIFFERENTLY from the default update. The default feeds MEANS
7339 * between the layers. This fits an APH to the response-time CDF of every
7340 * activity and every call a layer reports, convolves those fits along the
7341 * entry's activity sequence, and reads the entry's law off the convolution:
7342 * a mean AND a distribution, which is what `get_cdf_respt` returns.
7343 *
7344 * TWO PASSES, not one. While the ensemble is still moving (`!hasconverged`)
7345 * the update is mean-based -- forming a CDF per layer per iteration would
7346 * cost a fluid integration per layer per iteration and would be fitting
7347 * noise anyway -- and the distribution is formed ONCE, on the converged
7348 * ensemble. The reference splits it exactly here.
7349 *
7350 * THE NORMALISATION TRAP. Both passes build the entry service from
7351 * RESIDENCE times, which are normalised to one visit to the TASK, and then
7352 * apply the task/entry throughput ratio, which converts that to one visit
7353 * to the ENTRY. Summing per-visit RESPONSE times and applying the ratio as
7354 * well applies the normalisation twice and inflates every multi-entry task
7355 * by its entries-per-task ratio. That was a live defect in all three
7356 * reference codebases until 2026-07-31.
7357 */
7358 void update_metrics_moment_based(int it) {
7359 const std::size_t N = lqn.nidx;
7360 servt.assign(N + 1, Tzero());
7361 residt.assign(N + 1, Tzero());
7362 callservt.assign(lqn.ncalls + 1, Tzero());
7363 callresidt.assign(lqn.ncalls + 1, Tzero());
7364
7365 // ---- what every activity's layer reports, common to both passes ----
7366 for (const UpdRow& row : servt_map) {
7367 const std::size_t e = std::size_t(idxhash[row.idx]);
7368 const qn::Layer<T>& L = ensemble[e];
7369 const LayerResult<T>& r = results.back()[e];
7370 const std::size_t k = row.cls - 1;
7371 std::size_t c = 0;
7372 for (std::size_t cc = 0; cc < L.nchains; ++cc)
7373 if (L.chains[cc][k]) c = cc;
7374 const std::size_t refclass_c = L.refclass[c];
7375 const std::size_t refstat_k = L.classes[k].refstat;
7376 const T TN_ref = (refclass_c > 0 && refstat_k > 0) ? r.TN(refstat_k - 1, refclass_c - 1) : Tzero();
7377
7378 tput[row.aidx] = r.TN(row.node - 1, k);
7379 residt[row.aidx] = dbl(TN_ref) > GlobalConstants::FineTol
7380 ? T(r.QN(row.node - 1, k) / TN_ref)
7381 : r.WN(row.node - 1, k);
7382 if (!hasconverged) {
7383 servt[row.aidx] = r.RN(row.node - 1, k);
7384 servtproc[row.aidx] = Distrib<T>::exp_mean(servt[row.aidx]);
7385 const Distrib<T>& at = lqn.actthink[row.aidx];
7386 if (!at.disabled && dbl(at.mean) > GlobalConstants::FineTol) {
7387 servt[row.aidx] = T(servt[row.aidx] + at.mean);
7388 residt[row.aidx] = T(residt[row.aidx] + at.mean);
7389 servtproc[row.aidx] = Distrib<T>::exp_mean(servt[row.aidx]);
7390 }
7391 // An activity of an async-only entry takes the per-visit
7392 // response, for the same reason as in the default update.
7393 if (async_only_activity(row.aidx)) residt[row.aidx] = servt[row.aidx];
7394 } else {
7395 servtcdf[row.aidx] = layer_cdf(e)[row.node - 1][k];
7396 }
7397 }
7398
7399 for (const UpdRow& row : call_map) {
7400 if (row.node <= 1) continue; // a client-side call class contributes none
7401 const std::size_t e = std::size_t(idxhash[row.idx]);
7402 const LayerResult<T>& r = results.back()[e];
7403 callresidt[row.aidx] = r.WN(row.node - 1, row.cls - 1);
7404 if (!hasconverged)
7405 callservt[row.aidx] =
7406 T(r.RN(row.node - 1, row.cls - 1) * lqn.callproc_mean[row.aidx]);
7407 else
7408 callservtcdf[row.aidx] = layer_cdf(e)[row.node - 1][row.cls - 1];
7409 }
7410
7411 if (!hasconverged)
7412 moment3_means_pass(it);
7413 else
7414 moment3_distribution_pass(it);
7415 }
7416
7417 /** The mean-based pass of moment3, run while the ensemble is still moving. */
7418 void moment3_means_pass(int it) {
7419 const std::size_t dim = lqn.nidx + lqn.ncalls;
7420 std::vector<T> x(dim + 1, Tzero());
7421 for (std::size_t i = 1; i <= lqn.nidx; ++i) x[i] = residt[i];
7422 for (std::size_t c = 1; c <= lqn.ncalls; ++c) x[lqn.nidx + c] = callresidt[c];
7423
7424 // entry_servt = (I - servtmatrix) \ [residt; callresidt]
7425 const Matrix<T> Rinv = entry_service_resolvent();
7426 std::vector<T> entry_servt(dim + 1, Tzero());
7427 for (std::size_t i = 1; i <= dim; ++i) {
7428 T s = Tzero();
7429 for (std::size_t j = 1; j <= dim; ++j)
7430 if (Rinv(i, j) != Tzero()) s += Rinv(i, j) * x[j];
7431 entry_servt[i] = s;
7432 }
7433 for (std::size_t i = 1; i <= lqn.eshift; ++i) entry_servt[i] = Tzero();
7434
7435 // NO forwarding propagation here. `lqn_fwd_rendezvous` has already
7436 // reconnected every forwarding chain reachable from a synchronous call to
7437 // the client that issued the rendezvous (Franks 1999, Sec. 3.3.1), so the
7438 // forwarded service is in the caller's chain before this runs; charging it
7439 // again inflated the caller by exactly the forwarded entry's mean. An
7440 // asynchronous call into a chain is left untouched there by design -- a
7441 // send-no-reply does not block -- so it must not accumulate the forwarded
7442 // service either. See BUGS.md BUG-91.
7443
7444 for (std::size_t e = 1; e <= lqn.nentries; ++e)
7445 servt[lqn.eshift + e] = entry_servt[lqn.eshift + e];
7446
7447 // entry_residt = servtmatrix * [residt; callresidt]
7448 std::vector<T> entry_residt(dim + 1, Tzero());
7449 for (std::size_t i = lqn.eshift + 1; i <= lqn.eshift + lqn.nentries; ++i) {
7450 T s = Tzero();
7451 for (std::size_t j = 1; j <= dim; ++j)
7452 if (servtmatrix(i, j) != Tzero()) s += servtmatrix(i, j) * x[j];
7453 entry_residt[i] = s;
7454 }
7455
7456 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
7457 const std::size_t eidx = lqn.eshift + e;
7458 T ratio = Tone();
7459 const int state = entry_visit_ratio(eidx, ratio);
7460 if (state == 0) continue;
7461 if (state == 1) {
7462 residt[eidx] = entry_residt[eidx];
7463 continue;
7464 }
7465 servt[eidx] = T(entry_servt[eidx] * ratio);
7466 residt[eidx] = T(entry_residt[eidx] * ratio);
7467 }
7468
7469 for (const UpdRow& row : call_map) {
7470 if (row.node <= 1) continue;
7471 const std::size_t eidx = lqn.callpair_dst[row.aidx];
7472 if (servt[eidx] > Tzero()) servtproc[eidx] = Distrib<T>::exp_mean(servt[eidx]);
7473 }
7474 for (const UpdRow& row : call_map) {
7475 if (row.node <= 1) continue;
7476 const std::size_t eidx = lqn.callpair_dst[row.aidx];
7477 if (it == 1) {
7478 // A response time is per visit, so the number of calls is 1 here.
7479 callservt[row.aidx] = servt[eidx];
7480 callservtproc[row.aidx] = servtproc[eidx];
7481 } else if (callservt[row.aidx] > Tzero()) {
7482 callservtproc[row.aidx] = Distrib<T>::exp_mean(callservt[row.aidx]);
7483 }
7484 }
7485 }
7486
7487 /**
7488 * The distribution pass of moment3, run once on the converged ensemble.
7489 *
7490 * Every term reachable from an entry is fitted to an APH from the first
7491 * three moments of its response-time CDF, repeated as many times as the
7492 * entry-service matrix says it is visited, and the whole sequence is
7493 * convolved. A FRACTIONAL repetition count -- a call made 1.5 times on
7494 * average -- is realised as a branch between the fitted law and a point
7495 * mass at zero, which is the reference's `aph_simplify(..., pattern 3)`.
7496 */
7497 void moment3_distribution_pass(int it) {
7498 if constexpr (!num_traits<T>::has_transcendental) {
7499 throw UnsupportedError(ErrorKind{"Arithmetic"},
7500 "SolverLN: the 'moment3' method fits an APH to a response-time CDF, which needs "
7501 "square roots and a matrix exponential; rerun with --arith double or real");
7502 } else {
7503 const std::size_t dim = lqn.nidx + lqn.ncalls;
7504 const Matrix<T> Rinv = entry_service_resolvent();
7505
7506 // The point mass at zero the fractional branch mixes against.
7507 mam::AphPair<T> zero_law;
7508 zero_law.alpha.push_back(Tone());
7509 zero_law.S = Matrix<T>(1, 1, num_traits<T>::from_double(-GlobalConstants::Immediate));
7510
7511 for (std::size_t en = 1; en <= lqn.nentries; ++en) {
7512 const std::size_t eidx = lqn.eshift + en;
7513 std::vector<mam::AphPair<T>> seq;
7514 for (std::size_t fitidx = 1; fitidx <= dim; ++fitidx) {
7515 if (!(Rinv(eidx, fitidx) > Tzero())) continue;
7516 // Entries themselves are dropped: the entry's own service is
7517 // what is being assembled, and a host or task index carries
7518 // no response-time law of its own.
7519 if (fitidx <= lqn.eshift + lqn.nentries) continue;
7520 const bool is_call = fitidx > lqn.nidx;
7521 const fluid::FluidPassage& curve =
7522 is_call ? callservtcdf[fitidx - lqn.nidx] : servtcdf[fitidx];
7523 double m1 = 0.0, m2 = 0.0, m3 = 0.0;
7524 cdf_moments(curve, m1, m2, m3);
7525
7526 // An activity think time is in series with the host demand,
7527 // so its raw moments convolve with the measured ones.
7528 if (!is_call && !lqn.actthink[fitidx].disabled &&
7529 dbl(lqn.actthink[fitidx].mean) > GlobalConstants::FineTol) {
7530 const Distrib<T>& zt = lqn.actthink[fitidx];
7531 const double t1 = dbl(lang::dist_moment(zt, 1));
7532 const double t2 = dbl(lang::dist_moment(zt, 2));
7533 const double t3 = dbl(lang::dist_moment(zt, 3));
7534 m3 = m3 + 3.0 * m2 * t1 + 3.0 * m1 * t2 + t3;
7535 m2 = m2 + 2.0 * m1 * t1 + t2;
7536 m1 = m1 + t1;
7537 }
7538
7539 // CoarseTol and not FineTol: an Immediate activity has a
7540 // near-zero mean whose APH fit has rates of order 1e8, and
7541 // the matrix exponential of the convolution then does not
7542 // terminate. The reference skips those terms outright.
7543 if (!(m1 > GlobalConstants::CoarseTol)) continue;
7544
7545 const mam::AphFitResult<T> fit = mam::aph_fit(
7546 num_traits<T>::from_double(m1), num_traits<T>::from_double(m2),
7547 num_traits<T>::from_double(m3), 10u,
7548 num_traits<T>::from_double(GlobalConstants::FineTol));
7549 const mam::AphPair<T> law = aph_pair_of_map(fit.aph);
7550
7551 double reps = dbl(Rinv(eidx, fitidx));
7552 // servtmatrix carries 1.0 for a call; the mean NUMBER of
7553 // calls is what says how many times its law is convolved.
7554 if (is_call) reps *= dbl(lqn.callproc_mean[fitidx - lqn.nidx]);
7555 const long whole = static_cast<long>(std::floor(reps));
7556 const double frac = reps - static_cast<double>(whole);
7557 for (long q = 0; q < whole; ++q) seq.push_back(law);
7558 if (frac > 0.0)
7559 seq.push_back(mam::aph_simplify(law, zero_law,
7560 num_traits<T>::from_double(frac),
7561 num_traits<T>::from_double(1.0 - frac),
7563
7564 if (is_call) {
7565 const std::size_t cidx = fitidx - lqn.nidx;
7566 callservt[cidx] = num_traits<T>::from_double(m1);
7567 callservtproc[cidx] = Distrib<T>::exp_mean(callservt[cidx]);
7568 } else {
7569 servt[fitidx] = num_traits<T>::from_double(m1);
7570 servtproc[fitidx] = Distrib<T>::exp_mean(servt[fitidx]);
7571 }
7572 }
7573
7574 if (seq.empty()) {
7575 servt[eidx] = Tzero();
7576 continue;
7577 }
7578 const mam::AphPair<T> entry_law = mam::aph_convseq(seq);
7579 entryproc[en] = entry_law;
7580 servt[eidx] = Distrib<T>::ph_moment(entry_law.alpha, entry_law.S, 1);
7581 servtproc[eidx] = Distrib<T>::exp_mean(servt[eidx]);
7582 entrycdfrespt[en] = aph_eval_cdf(entry_law);
7583 }
7584
7585 // NO forwarding propagation here, for the reason given at the
7586 // entry_servt assembly above. See BUGS.md BUG-91.
7587
7588 // entry_residt = servtmatrix * [residt; callresidt], then the same
7589 // task/entry renormalisation the mean pass applies.
7590 std::vector<T> x(dim + 1, Tzero());
7591 for (std::size_t i = 1; i <= lqn.nidx; ++i) x[i] = residt[i];
7592 for (std::size_t c = 1; c <= lqn.ncalls; ++c) x[lqn.nidx + c] = callresidt[c];
7593 for (std::size_t en = 1; en <= lqn.nentries; ++en) {
7594 const std::size_t eidx = lqn.eshift + en;
7595 T s = Tzero();
7596 for (std::size_t j = 1; j <= dim; ++j)
7597 if (servtmatrix(eidx, j) != Tzero()) s += servtmatrix(eidx, j) * x[j];
7598 T ratio = Tone();
7599 const int state = entry_visit_ratio(eidx, ratio);
7600 if (state == 0) continue;
7601 residt[eidx] = state == 2 ? T(s * ratio) : s;
7602 }
7603
7604 if (it == 1)
7605 for (const UpdRow& row : call_map) {
7606 if (row.node <= 1) continue;
7607 const std::size_t eidx = lqn.callpair_dst[row.aidx];
7608 callservt[row.aidx] = servt[eidx];
7609 callservtproc[row.aidx] = Distrib<T>::exp_mean(servt[eidx]);
7610 }
7611
7612 // The entry servt is now the MEAN OF AN APH CONVOLUTION, not a sum
7613 // of residence times, which the interlock rescale in
7614 // `update_populations` has to know. See BUGS.md BUG-97.
7615 moment_pass_done = true;
7616 }
7617 }
7618
7619 /**
7620 * (alpha, S) of an APH handed back by aph_fit as a (D0, D1) pair.
7621 *
7622 * D1(i,j) = (-D0 e)_i alpha_j by construction, so alpha is any row of D1
7623 * divided by that row's exit rate; the first row with a positive exit rate
7624 * is taken. It is not recovered from the stationary phase distribution,
7625 * which is a different vector and would silently refit the law.
7626 */
7627 static mam::AphPair<T> aph_pair_of_map(const mam::Map<T>& m) {
7628 mam::AphPair<T> out;
7629 const std::size_t n = m.D0.rows();
7630 out.S = m.D0;
7631 out.alpha.assign(n, Tzero());
7632 for (std::size_t i = 0; i < n; ++i) {
7633 T rowsum = Tzero();
7634 for (std::size_t j = 0; j < n; ++j) rowsum += m.D1(i, j);
7635 if (!(dbl(rowsum) > GlobalConstants::Zero)) continue;
7636 for (std::size_t j = 0; j < n; ++j) out.alpha[j] = T(m.D1(i, j) / rowsum);
7637 return out;
7638 }
7639 // No phase can absorb: the law is degenerate, so it enters phase one and
7640 // stays there, which is what a zero alpha would NOT say.
7641 out.alpha[0] = Tone();
7642 return out;
7643 }
7644
7645 /**
7646 * F(t) = 1 - alpha exp(S t) e on the reference's grid, `APH.evalCDF` with
7647 * no argument: 500 points over [0, mean + 10 sigma].
7648 */
7649 static LnCdf aph_eval_cdf(const mam::AphPair<T>& law) {
7650 LnCdf out;
7651 const double m1 = dbl(Distrib<T>::ph_moment(law.alpha, law.S, 1));
7652 const double m2 = dbl(Distrib<T>::ph_moment(law.alpha, law.S, 2));
7653 const double var = m2 - m1 * m1;
7654 const double sigma = var > 0.0 ? std::sqrt(var) : 0.0;
7655 const double tmax = m1 + 10.0 * sigma;
7656 const std::size_t P = 500;
7657 out.t.resize(P);
7658 out.cdf.resize(P);
7659 for (std::size_t k = 0; k < P; ++k) {
7660 const double t = tmax * static_cast<double>(k) / static_cast<double>(P - 1);
7661 out.t[k] = t;
7662 Matrix<T> St(law.S.rows(), law.S.cols(), Tzero());
7663 for (std::size_t i = 0; i < law.S.rows(); ++i)
7664 for (std::size_t j = 0; j < law.S.cols(); ++j)
7665 St(i, j) = T(law.S(i, j) * num_traits<T>::from_double(t));
7666 const Matrix<T> E = ::line::expm(St);
7667 T surv = Tzero();
7668 for (std::size_t i = 0; i < E.rows(); ++i)
7669 for (std::size_t j = 0; j < E.cols(); ++j) surv += law.alpha[i] * E(i, j);
7670 out.cdf[k] = 1.0 - dbl(surv);
7671 }
7672 return out;
7673 }
7674
7675 /**
7676 * The AND-join completion times, and how much they undercut the serial sum.
7677 *
7678 * The branches of an AND fork run concurrently, so the time to clear the
7679 * join is the k-th smallest of the branch completion times, k being the
7680 * quorum. The entry-service reachability matrix cannot express that -- it
7681 * charges every activity of every branch to the entry, i.e. it serialises
7682 * them -- so the difference is recorded per join and applied as a
7683 * correction to any entry that reaches it.
7684 *
7685 * Branch times are taken as exponential, so the variance is the square of
7686 * the mean; that is the reference's assumption, not an approximation added
7687 * here.
7688 */
7689 std::vector<T> join_excess() {
7690 std::vector<T> excess(lqn.nidx + 1, Tzero());
7691 join_tail.assign(lqn.nidx + 1, Tzero());
7692 std::vector<std::size_t> joined;
7693 for (std::size_t tail = 1; tail <= lqn.nidx; ++tail) {
7694 if (lqn.actpretype[tail] != PrecedenceType::PRE_AND) continue;
7695 for (std::size_t sx : lqn.graph.succ(tail))
7696 if (sx > lqn.ashift && sx <= lqn.ashift + lqn.nacts) joined.push_back(sx);
7697 }
7698 std::sort(joined.begin(), joined.end());
7699 joined.erase(std::unique(joined.begin(), joined.end()), joined.end());
7700 if (joined.empty()) return excess;
7701
7702 fj::LqnBranchView<T> view;
7703 view.graph = Matrix<T>(lqn.nidx, lqn.nidx, Tzero());
7704 for (std::size_t i = 1; i <= lqn.nidx; ++i)
7705 for (const auto& e : lqn.graph.row[i]) view.graph(i - 1, e.first - 1) = e.second;
7706 view.ashift = lqn.ashift;
7707 view.nacts = lqn.nacts;
7708 view.actposttype.assign(lqn.nidx, 0);
7709 for (std::size_t i = 1; i <= lqn.nidx; ++i)
7710 view.actposttype[i - 1] = static_cast<int>(lqn.actposttype[i]);
7711
7712 for (std::size_t aidx : joined) {
7713 const std::vector<std::vector<std::size_t>> branches =
7714 fj::fj_branch_members(view, aidx);
7715 if (branches.empty()) continue;
7716 std::vector<T> means;
7717 for (const auto& br : branches) {
7718 T s = Tzero();
7719 for (std::size_t a : br) {
7720 s += residt[a];
7721 // A branch activity with an Immediate host demand does all its work
7722 // in a rendezvous, so residt alone leaves this correction inert.
7723 if (a < lqn.callsof.size())
7724 for (std::size_t cidx : lqn.callsof[a])
7725 if (cidx < lqn.calltype.size() && lqn.calltype[cidx] == CallType::SYNC
7726 && cidx < callresidt.size())
7727 s += callresidt[cidx];
7728 }
7729 means.push_back(s);
7730 }
7731 if (means.size() == 1) continue; // a single branch cannot overlap
7732 std::size_t quorum = means.size();
7733 if (lqn.actquorum[aidx] >= 1 && lqn.actquorum[aidx] <= means.size())
7734 quorum = lqn.actquorum[aidx];
7735 std::vector<T> vars;
7736 for (const T& m2 : means) vars.push_back(T(m2 * m2));
7737 T serial = Tzero();
7738 for (const T& m2 : means) serial += m2;
7739 if constexpr (num_traits<T>::has_transcendental) {
7740 const fj::FJQuorumMomentsResult<T> q = fj::fj_quorum_moments(means, vars, quorum);
7741 excess[aidx] = T(q.m - serial);
7742 if (quorum < means.size()) {
7743 // The n-k stragglers still hold the thread until the LAST branch ends.
7744 const fj::FJQuorumMomentsResult<T> all = fj::fj_quorum_moments(means, vars, means.size());
7745 if (all.m > q.m) join_tail[aidx] = T(all.m - q.m);
7746 }
7747 } else {
7748 throw UnsupportedError(ErrorKind{"Arithmetic"},
7749 "SolverLN: the AND-join completion time is a k-th order statistic fitted "
7750 "through a three-point distribution, which needs a square root; use the "
7751 "double or real backend for a model with an AND join");
7752 }
7753 }
7754 return excess;
7755 }
7756
7757 /** The block that turns activity residence times into entry service times. */
7758 void resolve_entry_service() {
7759 const std::size_t dim = lqn.nidx + lqn.ncalls;
7760 std::vector<T> x(dim + 1, Tzero());
7761 for (std::size_t i = 1; i <= lqn.nidx; ++i) x[i] = residt[i];
7762 for (std::size_t c = 1; c <= lqn.ncalls; ++c) x[lqn.nidx + c] = callresidt[c];
7763 std::vector<T> entry_servt(dim + 1, Tzero());
7764 for (std::size_t i = 1; i <= dim; ++i) {
7765 T s = Tzero();
7766 for (std::size_t j = 1; j <= dim; ++j)
7767 if (servtmatrix(i, j) != Tzero()) s += servtmatrix(i, j) * x[j];
7768 entry_servt[i] = s;
7769 }
7770
7771 // replace each reachable join's serialised branch sum by its concurrent
7772 // completion time
7773 const std::vector<T> excess = join_excess();
7774 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
7775 const std::size_t eidx = lqn.eshift + e;
7776 for (std::size_t aidx = 1; aidx <= lqn.nidx; ++aidx) {
7777 if (excess[aidx] == Tzero()) continue;
7778 if (servtmatrix(eidx, aidx) > Tzero())
7779 entry_servt[eidx] = T(entry_servt[eidx] + excess[aidx]);
7780 }
7781 if (entry_servt[eidx] < Tzero()) entry_servt[eidx] = Tzero();
7782 // The quorum tail lengthens the thread's holding time but not the caller's wait
7783 for (std::size_t aidx = 1; aidx <= lqn.nidx; ++aidx)
7784 if (join_tail[aidx] > Tzero() && servtmatrix(eidx, aidx) > Tzero())
7785 entry_servt[eidx] = T(entry_servt[eidx] + join_tail[aidx]);
7786 }
7787
7788 // A SetupTask's cold start is charged HERE, to the entry. It is not host
7789 // demand, so it belongs to no activity's residence -- reporting it there
7790 // put RespT(A2) at 1.29479 against 0.333178 from LDES on lqn_setup, the
7791 // bare demand. The charge is computed ONCE per task from the base service
7792 // of a request, the sum of its entries' services before any charge, and
7793 // ph_setup_prob reads the same closure (updateMetricsDefault.m,
7794 // lqn_setup_charge.m).
7795 std::unordered_map<std::size_t, double> charge_su;
7796 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
7797 const std::size_t tidx = lqn.parent[lqn.eshift + e];
7798 if (charge_su.count(tidx)) continue;
7799 double S = 0.0;
7800 for (std::size_t e2 = 1; e2 <= lqn.nentries; ++e2)
7801 if (lqn.parent[lqn.eshift + e2] == tidx) S += dbl(entry_servt[lqn.eshift + e2]);
7802 charge_su[tidx] = setup_charge(tidx, S);
7803 }
7804 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
7805 const std::size_t eidx = lqn.eshift + e;
7806 const double c = charge_su[lqn.parent[eidx]];
7807 if (c != 0.0)
7808 entry_servt[eidx] = T(entry_servt[eidx] + num_traits<T>::from_double(c));
7809 }
7810
7811 // The phase-2 part of each entry's service: phase-2 activities and the calls they
7812 // make, through the same reachability. The overtaking block splits servt with it.
7813 if (has_phase2) {
7814 std::vector<T> x2(dim + 1, Tzero());
7815 for (std::size_t a = 1; a <= lqn.nacts; ++a)
7816 if (lqn.actphase[a] > 1) x2[lqn.ashift + a] = x[lqn.ashift + a];
7817 for (std::size_t c = 1; c <= lqn.ncalls; ++c) {
7818 const std::size_t src = lqn.callpair_src[c];
7819 if (src > lqn.ashift && src <= lqn.ashift + lqn.nacts && lqn.actphase[src - lqn.ashift] > 1)
7820 x2[lqn.nidx + c] = x[lqn.nidx + c];
7821 }
7822 entry_servt_ph2.assign(dim + 1, Tzero());
7823 for (std::size_t i = lqn.eshift + 1; i <= dim; ++i) {
7824 T s2 = Tzero();
7825 for (std::size_t j = 1; j <= dim; ++j)
7826 if (servtmatrix(i, j) != Tzero()) s2 += servtmatrix(i, j) * x2[j];
7827 entry_servt_ph2[i] = s2;
7828 }
7829 // and the quorum tail is all phase 2, see join_excess
7830 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
7831 const std::size_t eidx = lqn.eshift + e;
7832 for (std::size_t aidx = 1; aidx <= lqn.nidx; ++aidx)
7833 if (join_tail[aidx] > Tzero() && servtmatrix(eidx, aidx) > Tzero())
7834 entry_servt_ph2[eidx] = T(entry_servt_ph2[eidx] + join_tail[aidx]);
7835 }
7836 entry_servt_last = entry_servt;
7837 }
7838
7839 // ResidT is normalised so the TASK has one visit; the entries need one
7840 // visit each, hence the throughput ratio below
7841 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
7842 const std::size_t eidx = lqn.eshift + e;
7843 const std::size_t tidx = lqn.parent[eidx];
7844 const std::size_t hidx = lqn.parent[tidx];
7845 if (ignore[tidx] || ignore[hidx]) continue;
7846 if (idxhash[hidx] < 0) continue;
7847 const bool has_sync = lqn.issynccaller.any_col(eidx);
7848 if (!has_sync) {
7849 servt[eidx] = entry_servt[eidx];
7850 residt[eidx] = entry_servt[eidx];
7851 continue;
7852 }
7853 const std::size_t hl = std::size_t(idxhash[hidx]);
7854 const qn::Layer<T>& L = ensemble[hl];
7855 const LayerResult<T>& r = results.back()[hl];
7856 T task_tput = Tzero(), entry_tput = Tzero();
7857 for (const auto& kv : L.attr_tasks)
7858 if (kv.second == tidx) task_tput += r.TN(L.clientIdx - 1, kv.first - 1);
7859 for (const auto& kv : L.attr_entries)
7860 if (kv.second == eidx) entry_tput += r.TN(L.clientIdx - 1, kv.first - 1);
7861 if (dbl(entry_tput) > GlobalConstants::Zero) {
7862 servt[eidx] = T(entry_servt[eidx] * task_tput / entry_tput);
7863 residt[eidx] = servt[eidx];
7864 // the same ratio the other way round, the entry's invocations per
7865 // task invocation, which a refpath hop stage converts its call terms by
7866 if (dbl(task_tput) > GlobalConstants::Zero)
7867 entryvisits[eidx] = T(entry_tput / task_tput);
7868 } else {
7869 servt[eidx] = entry_servt[eidx];
7870 residt[eidx] = entry_servt[eidx];
7871 }
7872 }
7873 }
7874
7875 // -----------------------------------------------------------------------
7876 // updatePopulations (interlock correction)
7877 // -----------------------------------------------------------------------
7878 /**
7879 * True when the layer engine applies Eq. (4.7) inside its own MVA. A layer whose MVA path
7880 * has no interlock term would be moved to another algorithm by the matrix alone: exact
7881 * multiserver MVA would become AMVA, the product-form kernels would become the
7882 * load-dependent forward step. That swap is worth far more than the correction it carries,
7883 * and on a layer sitting near a bifurcation it turns the LN iteration into a limit cycle.
7884 * Such a layer keeps the residt scaling instead.
7885 */
7886 bool layer_takes_interlock(std::size_t e) const {
7887 return opt.layer_solver == "mva" && e < ensemble.size() &&
7888 mva::mva_carries_interlock(ensemble[e], opt.layer);
7889 }
7890
7891 /**
7892 * Class-level interlock matrix of one host layer. IL[r][s] is the share of the class-s
7893 * queue that a class-r arrival must not see at the host. It is kept CLASS-indexed, not
7894 * chain-indexed, so that a later chain refresh cannot leave it stale: the analyzer
7895 * aggregates it to chains against the struct it is about to solve. Two classes are
7896 * interlocked only if BOTH their tasks are, which is the 0/1 relation ir_mkj of Eq. (5);
7897 * the diagonal stays zero, since a request always sees its own class in full. The entry
7898 * is the Eq. (5) product Pr(IL_ms)*IR_ms*IR_mr, asymmetric in (r,s) because Pr(IL) is
7899 * taken from the QUEUED class s, so that the layer's ILw(r,s) = 1-IL(r,s) is the
7900 * lower-level adjustment rate r_lower. An empty result keeps the layer on the plain MVA
7901 * path.
7902 */
7903 std::vector<std::vector<double>> build_layer_interlock(std::size_t e,
7904 const std::vector<std::size_t>& hts,
7905 const std::vector<T>& prIL,
7906 const std::vector<T>& PrIL) const {
7907 const qn::Layer<T>& L = ensemble[e];
7908 const std::size_t R = L.nclasses;
7909 std::vector<double> cls_ir(R, 0.0); // IR
7910 std::vector<double> cls_pr(R, 0.0); // Pr(IL)
7911 auto stamp = [&](std::size_t classIdx, std::size_t tidx) {
7912 if (classIdx < 1 || classIdx > R) return;
7913 for (std::size_t i = 0; i < hts.size(); ++i)
7914 if (hts[i] == tidx) {
7915 cls_ir[classIdx - 1] = dbl(prIL[i]);
7916 cls_pr[classIdx - 1] = dbl(PrIL[i]);
7917 }
7918 };
7919 for (const auto& a : L.attr_tasks) stamp(a.first, a.second);
7920 for (const auto& a : L.attr_entries) stamp(a.first, lqn.parent[a.second]);
7921 for (const auto& a : L.attr_activities) stamp(a.first, lqn.parent[a.second]);
7922 for (const auto& a : L.attr_calls) stamp(a[0], lqn.parent[a[2]]);
7923
7924 std::vector<std::vector<double>> IL(R, std::vector<double>(R, 0.0));
7925 bool any = false;
7926 for (std::size_t r = 0; r < R; ++r) {
7927 if (!(cls_ir[r] > GlobalConstants::FineTol)) continue;
7928 for (std::size_t sIl = 0; sIl < R; ++sIl) {
7929 if (sIl == r || !(cls_ir[sIl] > GlobalConstants::FineTol)) continue;
7930 IL[r][sIl] = cls_pr[sIl] * cls_ir[sIl] * cls_ir[r];
7931 if (IL[r][sIl] > GlobalConstants::FineTol) any = true;
7932 }
7933 }
7934 return any ? IL : std::vector<std::vector<double>>();
7935 }
7936
7937 /**
7938 * Interlock probability for one (client, server) pair, as {IR, Pr(IL)} of Li and Franks,
7939 * "An improved interlocking correction for decomposition of layered queueing networks",
7940 * CCECE 2015, Eqs. (3) and (4). isProcessorHost selects the m' rule of lqns
7941 * Interlock::ilrate_pril_flow: at a PROCESSOR the common-source population is doubled
7942 * above 3 customers and squared at or below it, which is what turns m = 4 into the
7943 * pril = 1/8 its trace reports. The two factors are multiplied into the Eq. (5) rate by
7944 * build_layer_interlock, so neither carries the source count on its own -- that lives in
7945 * m'. This replaces the superseded (n_s-1)/n_s discount of Franks (1999), Eq. (4.7).
7946 */
7947 std::pair<T, T> interlock_prob(std::size_t client_tidx, std::size_t server_idx,
7948 bool isProcessorHost) const {
7949 const std::vector<std::size_t>& common = il_common_entries[server_idx];
7950 const double nsrc = il_num_sources[server_idx];
7951 if (nsrc == 0.0 || common.empty()) return std::make_pair(Tzero(), Tzero());
7952 const std::vector<std::size_t>& allsrc = il_src_all[server_idx];
7953 T sum_flow = Tzero();
7954 T sum_pril = Tzero();
7955 for (std::size_t ce : common) {
7956 const std::size_t srcTask = lqn.parent[ce];
7957 const std::size_t cen = ce - lqn.eshift;
7958 // population of this common source, in customer copies
7959 double m_src = lqn.mult[srcTask];
7960 if (!std::isfinite(m_src) || m_src < 1.0) m_src = 1.0;
7961 double m_eff = m_src;
7962 if (isProcessorHost) m_eff = (m_src > 3.0) ? (m_src + m_src) : (m_src * m_src);
7963 for (std::size_t dst : lqn.entriesof[client_tidx]) {
7964 const std::size_t dn = dst - lqn.eshift;
7965 if (dn < 1 || dn > lqn.nentries) continue;
7966 if (!(il_all(cen, dn) > Tzero())) continue;
7967 T ce_tput = tput[ce];
7968 if (!(dbl(ce_tput) > GlobalConstants::FineTol) && !lqn.actsof[ce].empty())
7969 ce_tput = tput[lqn.actsof[ce][0]];
7970 if (!(dbl(ce_tput) > GlobalConstants::FineTol)) ce_tput = tput[srcTask];
7971 if (!(dbl(ce_tput) > GlobalConstants::FineTol)) continue;
7972 // phase-2 entries are refused upstream, so every source is all-phase
7973 if (std::find(allsrc.begin(), allsrc.end(), srcTask) != allsrc.end()) {
7974 const T contrib = T(ce_tput * il_all(cen, dn));
7975 sum_flow += contrib;
7976 sum_pril += T(contrib / num_traits<T>::from_double(m_eff));
7977 }
7978 }
7979 }
7980 T client_tput = tput[client_tidx];
7981 if (!(dbl(client_tput) > GlobalConstants::FineTol)) {
7982 for (std::size_t e : lqn.entriesof[client_tidx]) {
7983 T et = tput[e];
7984 if (!(dbl(et) > GlobalConstants::FineTol) && !lqn.actsof[e].empty())
7985 et = tput[lqn.actsof[e][0]];
7986 client_tput = T(client_tput + et);
7987 }
7988 }
7989 if (!(dbl(client_tput) > GlobalConstants::FineTol))
7990 return std::make_pair(Tzero(), Tzero());
7991 const T flow = sum_flow < client_tput ? sum_flow : client_tput;
7992 T IR = T(flow / client_tput);
7993 if (IR > Tone()) IR = Tone();
7994 if (dbl(IR) < 0.0) IR = Tzero();
7995 T pr = Tzero();
7996 if (dbl(sum_flow) > GlobalConstants::FineTol) pr = T(sum_pril / sum_flow);
7997 if (pr > Tone()) pr = Tone();
7998 if (dbl(pr) < 0.0) pr = Tzero();
7999 return std::make_pair(IR, pr);
8000 }
8001
8002 void update_populations(int) {
8003 const std::vector<T> residt_orig = residt;
8004 const std::vector<T> callresidt_orig = callresidt;
8005 bool adjusted = false;
8006
8007 // Every layer starts the pass without a matrix, so a server that stops being
8008 // interlocked does not keep the previous iteration's correction alive.
8009 layer_interlock.assign(ensemble.size(), {});
8010
8011 // Pass 0: a TASK layer whose MVA carries Eq. (4.7) takes the interlock as a class
8012 // matrix, as a host layer does below. Correcting its calls after the solve (pass 1)
8013 // shortens the callers' residence while the layer's own throughput keeps the full
8014 // waiting, so the server's throughput stops matching the sum of its callers'
8015 // (BUGS.md BUG-103).
8016 std::vector<bool> il_in_layer(lqn.nidx + 1, false);
8017 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
8018 const std::size_t server_tidx = lqn.tshift + t;
8019 if (server_tidx >= il_common_entries.size() || il_common_entries[server_tidx].empty()) continue;
8020 if (!(idxhash[server_tidx] >= 0) || !layer_takes_interlock(std::size_t(idxhash[server_tidx])))
8021 continue;
8022 const std::size_t e = std::size_t(idxhash[server_tidx]);
8023 std::vector<std::size_t> cts;
8024 for (std::size_t cidx = 1; cidx <= lqn.ncalls; ++cidx) {
8025 if (lqn.calltype[cidx] != CallType::SYNC) continue;
8026 if (lqn.parent[lqn.callpair_dst[cidx]] != server_tidx) continue;
8027 const std::size_t ctidx = lqn.parent[lqn.callpair_src[cidx]];
8028 if (std::find(cts.begin(), cts.end(), ctidx) == cts.end()) cts.push_back(ctidx);
8029 }
8030 std::vector<T> prIL(cts.size(), Tzero()), PrIL(cts.size(), Tzero());
8031 for (std::size_t i = 0; i < cts.size(); ++i) {
8032 const std::pair<T, T> ilp = interlock_prob(cts[i], server_tidx, false);
8033 prIL[i] = ilp.first;
8034 PrIL[i] = ilp.second;
8035 }
8036 il_in_layer[server_tidx] = true;
8037 layer_interlock[e] = build_layer_interlock(e, cts, prIL, PrIL);
8038 }
8039
8040 for (std::size_t cidx = 1; cidx <= lqn.ncalls; ++cidx) {
8041 if (lqn.calltype[cidx] != CallType::SYNC) continue;
8042 const std::size_t dst = lqn.callpair_dst[cidx];
8043 const std::size_t server_tidx = lqn.parent[dst];
8044 std::size_t server = 0;
8045 if (server_tidx <= NT() && !il_common_entries[server_tidx].empty()) {
8046 server = server_tidx;
8047 } else if (server_tidx > lqn.tshift) {
8048 const std::size_t h = lqn.parent[server_tidx];
8049 if (h >= 1 && h <= NT() && !il_common_entries[h].empty()) server = h;
8050 }
8051 if (server == 0 || il_in_layer[server]) continue;
8052 // A HOST whose layer carries Eq. (4.7) in its own MVA (Pass 2 hands it the matrix)
8053 // has already discounted the processor queueing this call's residence reads, so
8054 // scaling the call again removes the same waiting twice and shortens the caller's
8055 // cycle while the callee's layer keeps the full wait: flow stopped balancing across
8056 // the call, above the demand bound lqsim sits on (BUGS.md BUG-107).
8057 if (server <= lqn.nhosts && idxhash[server] >= 0 &&
8058 layer_takes_interlock(std::size_t(idxhash[server])))
8059 continue;
8060 const std::size_t client_tidx = lqn.parent[lqn.callpair_src[cidx]];
8061 // This path serves a TASK, not a processor, so the m' rule of Li/lqns leaves the
8062 // source population alone; the product IR*Pr(IL) reproduces the scalar this
8063 // branch used before.
8064 const std::pair<T, T> ilp = interlock_prob(client_tidx, server, false);
8065 const T prIL = T(ilp.first * ilp.second);
8066 if (!(dbl(prIL) > GlobalConstants::FineTol)) continue;
8067 const T S = servt[dst];
8068 const T cm = lqn.callproc_mean[cidx];
8069 if (!(cm > Tzero()) || !(callservt[cidx] > Tzero())) continue;
8070 const T RN = T(callservt[cidx] / cm);
8071 const T W = RN > S ? T(RN - S) : Tzero();
8072 if (!(dbl(W) > GlobalConstants::FineTol)) continue;
8073 const T RN_adj = T(S + (Tone() - prIL) * W);
8074 const T scale = T(RN_adj / RN);
8075 callservt[cidx] = T(callservt[cidx] * scale);
8076 callresidt[cidx] = T(callresidt[cidx] * scale);
8077 if (callservt[cidx] > Tzero())
8078 callservtproc[cidx] = Distrib<T>::exp_mean(callservt[cidx]);
8079 adjusted = true;
8080 }
8081
8082 for (std::size_t h = 1; h <= lqn.nhosts; ++h) {
8083 if (il_common_entries[h].empty()) continue;
8084 const std::vector<std::size_t>& hts = lqn.tasksof[h];
8085 std::vector<T> prIL(hts.size(), Tzero()), PrIL(hts.size(), Tzero()),
8086 tutil(hts.size(), Tzero());
8087 for (std::size_t i = 0; i < hts.size(); ++i) {
8088 // The host of a task layer is a PROCESSOR, which is what selects the m' rule.
8089 const std::pair<T, T> ilp = interlock_prob(hts[i], h, true);
8090 prIL[i] = ilp.first;
8091 PrIL[i] = ilp.second;
8092 for (std::size_t e : lqn.entriesof[hts[i]])
8093 for (std::size_t a : lqn.actsof[e]) tutil[i] += tput[a] * lqn.hostdem[a].mean;
8094 }
8095 T Utot = Tzero(), Uil = Tzero();
8096 for (std::size_t i = 0; i < hts.size(); ++i) {
8097 Utot += tutil[i];
8098 if (dbl(prIL[i]) > GlobalConstants::FineTol) Uil += tutil[i];
8099 }
8100 if (!(dbl(Utot) > GlobalConstants::FineTol) || !(dbl(Uil) > GlobalConstants::FineTol))
8101 continue;
8102 const T frac = T(Uil / Utot);
8103
8104 // When the layer engine carries Eq. (4.7) inside its own MVA, the interlock goes
8105 // to the layer as a class-level matrix and the residence times are left
8106 // untouched. Scaling them here as well would remove the same waiting twice, and
8107 // would still leave the layer's own THROUGHPUT uncorrected, which is what breaks
8108 // flow balance across a call: the reported task rate then comes from a cycle time
8109 // the correction has already shortened elsewhere.
8110 if (idxhash[h] >= 0 && layer_takes_interlock(std::size_t(idxhash[h]))) {
8111 const std::size_t e = std::size_t(idxhash[h]);
8112 layer_interlock[e] = build_layer_interlock(e, hts, prIL, PrIL);
8113 continue;
8114 }
8115
8116 for (std::size_t i = 0; i < hts.size(); ++i) {
8117 if (!(dbl(prIL[i]) > GlobalConstants::FineTol)) continue;
8118 // Weight by the share of host utilization that is interlocked. The rate
8119 // is the SAME Eq. (5) product IR*Pr(IL) that pass 1 applies to a call and
8120 // that build_layer_interlock puts in the layer matrix -- IR alone is a
8121 // flow SHARE, ~1 whenever a layer has a single common source, and using
8122 // it here removed the whole processor queueing rather than the
8123 // interlocked part of it, which broke flow balance across a call.
8124 const T eff = T(prIL[i] * PrIL[i] * frac);
8125 for (std::size_t e : lqn.entriesof[hts[i]])
8126 for (std::size_t a : lqn.actsof[e]) {
8127 // D is per VISIT and residt per CYCLE (visits times response): take the
8128 // waiting from the per-visit servt and apply the cut as a ratio, as pass 1
8129 // does for a call. Subtracting D from residt dropped a loop's visit count.
8130 const T D = lqn.hostdem[a].mean;
8131 const T R = servt[a];
8132 if (D > Tzero() && dbl(R - D) > GlobalConstants::FineTol) {
8133 residt[a] = T(residt[a] * (D + (Tone() - eff) * (R - D)) / R);
8134 adjusted = true;
8135 }
8136 }
8137 }
8138 }
8139
8140 if (!adjusted) return;
8141 const std::size_t dim = lqn.nidx + lqn.ncalls;
8142 auto esum = [&](const std::vector<T>& rs, const std::vector<T>& cr, std::size_t i) {
8143 T s = Tzero();
8144 for (std::size_t j = 1; j <= dim; ++j) {
8145 if (servtmatrix(i, j) == Tzero()) continue;
8146 s += servtmatrix(i, j) * (j <= lqn.nidx ? rs[j] : cr[j - lqn.nidx]);
8147 }
8148 return s;
8149 };
8150 // The split update_metrics uses: phase-2 activities and the calls they make. A
8151 // correction landing in phase 2 must not shrink phase 1, and the caller-visible
8152 // residt is rebuilt from the two parts rather than scaled with the whole entry
8153 // (BUGS.md BUG-103).
8154 std::vector<bool> isph2(dim + 1, false);
8155 if (has_phase2) {
8156 for (std::size_t a = 1; a <= lqn.nacts; ++a)
8157 if (lqn.actphase[a] > 1) isph2[lqn.ashift + a] = true;
8158 for (std::size_t c = 1; c <= lqn.ncalls; ++c) {
8159 const std::size_t src = lqn.callpair_src[c];
8160 if (src > lqn.ashift && src <= lqn.ashift + lqn.nacts && lqn.actphase[src - lqn.ashift] > 1)
8161 isph2[lqn.nidx + c] = true;
8162 }
8163 }
8164 auto esum2 = [&](const std::vector<T>& rs, const std::vector<T>& cr, std::size_t i) {
8165 T s = Tzero();
8166 for (std::size_t j = 1; j <= dim; ++j) {
8167 if (!isph2[j] || servtmatrix(i, j) == Tzero()) continue;
8168 s += servtmatrix(i, j) * (j <= lqn.nidx ? rs[j] : cr[j - lqn.nidx]);
8169 }
8170 return s;
8171 };
8172 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
8173 const std::size_t eidx = lqn.eshift + e;
8174 const T oldv = esum(residt_orig, callresidt_orig, eidx);
8175 if (!(dbl(oldv) > GlobalConstants::FineTol)) continue;
8176 const T ratio = T(esum(residt, callresidt, eidx) / oldv);
8177 if (has_phase2 && !moment_pass_done && dbl(servt_ph2[eidx]) > GlobalConstants::FineTol) {
8178 const T old2 = esum2(residt_orig, callresidt_orig, eidx);
8179 const T new2 = esum2(residt, callresidt, eidx);
8180 const T old1 = T(oldv - old2);
8181 const T new1 = T(esum(residt, callresidt, eidx) - new2);
8182 const T r1 = dbl(old1) > GlobalConstants::FineTol ? T(new1 / old1) : Tone();
8183 const T r2 = dbl(old2) > GlobalConstants::FineTol ? T(new2 / old2) : Tone();
8184 servt_ph1[eidx] = T(servt_ph1[eidx] * r1);
8185 servt_ph2[eidx] = T(servt_ph2[eidx] * r2);
8186 servt[eidx] = T(servt_ph1[eidx] + servt_ph2[eidx]);
8187 if (servt[eidx] > Tzero()) servtproc[eidx] = Distrib<T>::exp_mean(servt[eidx]);
8188 // residt as update_metrics builds it: the full servt for a reference task or an
8189 // entry with no synchronous caller, else phase 1 plus the overtaken share of phase 2
8190 const std::size_t tidx = lqn.parent[eidx];
8191 if (lqn.isref[tidx] || !lqn.issynccaller.any_col(eidx))
8192 residt[eidx] = servt[eidx];
8193 else
8194 residt[eidx] = T(servt_ph1[eidx] + prOvertake[e] * servt_ph2[eidx]);
8195 continue;
8196 }
8197 // The entry servt is rescaled only when it was itself assembled from
8198 // these residence times, which is the mean-based path. After the
8199 // moment3 distribution pass it is the mean of an APH convolution of
8200 // the activities' own response laws, and a ratio of residence-time
8201 // sums is not a correction to it: applying it multiplied the entry
8202 // law by the entry's visit ratio and reported a service time BELOW
8203 // that of the single activity the entry contains. The residence
8204 // times keep their correction either way. See BUGS.md BUG-97.
8205 if (!moment_pass_done) {
8206 servt[eidx] = T(servt[eidx] * ratio);
8207 if (servt[eidx] > Tzero()) servtproc[eidx] = Distrib<T>::exp_mean(servt[eidx]);
8208 }
8209 residt[eidx] = T(residt[eidx] * ratio);
8210 }
8211 }
8212
8213 // -----------------------------------------------------------------------
8214 // Declared think time of a task as it enters the thread cycle: the value for
8215 // a REFERENCE task, zero for any other.
8216 //
8217 // A think time is an attribute of the closed customer population a reference
8218 // task stands for, and it is what separates one request of that population
8219 // from the next. On a served task it has no such meaning, and charging it
8220 // per request throttles the task: lqn_basic's T3 has 25 threads and a
8221 // declared think time of 4, and reading it as a per-request delay caps it at
8222 // 25/(4+0.02) = 6.219 completions per second. Three independent oracles put
8223 // the rate at five calls per caller request instead -- lqsim 66.5, LDES
8224 // 66.955, lqns 75.6. See _kb/06-solver-catalog.md (LN section).
8225 T ref_think_time(std::size_t tidx) const {
8226 if (tidx >= lqn.isref.size() || !lqn.isref[tidx]) return Tzero();
8227 if (lqn.think[tidx].disabled) return Tzero();
8228 return lqn.think[tidx].mean;
8229 }
8230
8231 // updateThinkTimes
8232 // -----------------------------------------------------------------------
8233 /**
8234 * Mean time per request that a thread of task TIDX stays busy after replying, i.e. servt - residt
8235 * averaged over its phase-2 entries by their throughput (phase2Tail in updateThinkTimes.m).
8236 */
8237 T phase2_tail(std::size_t tidx) const {
8238 T tail = Tzero();
8239 if (!has_phase2) return tail;
8240 T wtot = Tzero();
8241 const T fine = num_traits<T>::from_double(GlobalConstants::FineTol);
8242 for (std::size_t eidx : lqn.entriesof[tidx]) {
8243 if (servt_ph2[eidx] <= fine) continue;
8244 T w = tput[eidx];
8245 if (w <= fine) w = Tone();
8246 const T d = T(servt[eidx] - residt[eidx]);
8247 tail += T(w * (d > Tzero() ? d : Tzero()));
8248 wtot += w;
8249 }
8250 if (wtot > fine) tail = T(tail / wtot);
8251 return tail;
8252 }
8253
8254 void update_think_times(int it) {
8255 // Under "srvn.ph" a caller reaches the server once per invocation, so the
8256 // station rate is not the task's invocation rate
8257 if (is_ph_encoding()) {
8258 update_think_times_ph(it);
8259 return;
8260 }
8261 thinktproc.assign(lqn.nidx + 1, Distrib<T>::disabled_dist());
8262 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
8263 const std::size_t tidx = lqn.tshift + t;
8264 // only a REFERENCE task's think time is a per-request delay
8265 const T ztask = ref_think_time(tidx);
8266 if (idxhash[tidx] < 0) {
8267 // A task reached only by an entry arrival still has a cycle: its threads
8268 // are driven by the stream. build_layer drops the open class for it so
8269 // the chain can be closed on the known rate here.
8270 const double arvrate = open_arrival_rate_of(tidx);
8271 if (arvrate > GlobalConstants::FineTol) {
8272 double nja = 0.0;
8273 for (std::size_t c = 1; c <= NT(); ++c) nja = std::max(nja, njobs(tidx, c));
8274 if (!(nja > 0.0)) nja = lqn.maxmult[tidx];
8275 T hres = Tzero();
8276 for (std::size_t eidx : lqn.entriesof[tidx]) {
8277 for (std::size_t aidx : lqn.actsof[eidx])
8278 if (!std::isnan(dbl(residt[aidx]))) hres += residt[aidx];
8279 hres += sync_call_residt_of(lqn.actsof[eidx]);
8280 }
8281 const T floora = num_traits<T>::from_double(GlobalConstants::Zero);
8282 T za = T(num_traits<T>::from_double(nja / arvrate) - hres - ztask);
8283 if (za < floora) za = floora;
8284 if (relax_omega < 1.0 && it > 1 && !std::isnan(thinkt_prev[tidx])) {
8285 const T om = num_traits<T>::from_double(relax_omega);
8286 const T om1 = num_traits<T>::from_double(1.0 - relax_omega);
8287 za = T(om * za + om1 * thinkt_prev_v[tidx]);
8288 }
8289 tput[tidx] = num_traits<T>::from_double(arvrate);
8290 thinkt[tidx] = za;
8291 thinkt_prev[tidx] = dbl(za);
8292 thinkt_prev_v[tidx] = za;
8293 thinktproc[tidx] = Distrib<T>::exp_mean(T(za + ztask));
8294 continue;
8295 }
8296 thinkt[tidx] = num_traits<T>::from_double(GlobalConstants::FineTol);
8297 thinktproc[tidx] = Distrib<T>::immediate();
8298 continue;
8299 }
8300 const std::size_t e = std::size_t(idxhash[tidx]);
8301 const qn::Layer<T>& L = ensemble[e];
8302 const LayerResult<T>& r = results.back()[e];
8303 double nj = 0.0;
8304 for (std::size_t c = 1; c <= NT(); ++c) nj = std::max(nj, njobs(tidx, c));
8305 // the task's OWN station, which under `flat.cs` is one of many
8306 const std::size_t ts = station_idx_of(L, tidx);
8307 T tp = Tzero();
8308 for (std::size_t k = 0; k < L.nclasses; ++k) tp += r.TN(ts - 1, k);
8309 tput[tidx] = T(num_traits<T>::from_double(lqn.repl[tidx]) * tp);
8310 // the thread busy fraction, not a dependent station's peak-normalized Util
8311 util[tidx] = thread_busy_fraction(L, ts, r, false);
8312 // The closure is a cycle of ONE replica's threads, so both sides are per replica: the rate is the
8313 // total divided back down, and the pool is maxmult, since njobs keeps whichever convention the
8314 // caller's layer used. Inert at repl 1 (updateThinkTimes.m).
8315 const double nrep = std::max(1.0, lqn.repl[tidx]);
8316 const T xcyc = T(tput[tidx] / num_traits<T>::from_double(nrep));
8317 if (nrep > 1.0 && std::isfinite(lqn.maxmult[tidx]) && lqn.maxmult[tidx] > 0.0) nj = lqn.maxmult[tidx];
8318 T raw;
8319 if (lqn.sched[tidx] == SchedStrategy::INF) {
8320 // an infinite server reports utilization as a mean job count
8321 raw = xcyc == Tzero()
8322 ? Tzero()
8323 : T((num_traits<T>::from_double(nj) - util[tidx]) / xcyc - ztask);
8324 } else {
8325 const T om = util[tidx] > Tone() ? T(util[tidx] - Tone()) : T(Tone() - util[tidx]);
8326 raw = xcyc == Tzero()
8327 ? Tzero()
8328 : T(num_traits<T>::from_double(nj) * om / xcyc - ztask);
8329 }
8330 const T floorv = num_traits<T>::from_double(GlobalConstants::Zero);
8331 thinkt[tidx] = raw < floorv ? floorv : raw;
8332
8333 // Phase-2 tail: the entry replies after phase 1, so the station serves the caller for residt while the
8334 // thread stays busy for servt. What is left is busy time, not think time (updateThinkTimes.m).
8335 if (lnmethod != "flat.cs") {
8336 const T lessz = T(thinkt[tidx] - phase2_tail(tidx));
8337 thinkt[tidx] = lessz < floorv ? floorv : lessz;
8338 }
8339
8340 // The cold start goes the OTHER way from the phase-2 tail. A caller
8341 // class cycles as delay plus station service, and the station serves
8342 // only the host demand: the charge is on the ENTRY, not on any
8343 // activity's demand, so the station never sees it and the delay has
8344 // to carry it. Without this the callee layer cycles faster than its
8345 // callers drive it -- 0.529412 against 0.5 on lqn_setup, with the
8346 // caller conserved and the callee not. Zero for a task with no setup
8347 // (updateThinkTimes.m).
8348 {
8349 const double c = setup_charge(tidx);
8350 if (c != 0.0) {
8351 const T withc = T(thinkt[tidx] + num_traits<T>::from_double(c));
8352 thinkt[tidx] = withc < floorv ? floorv : withc;
8353 }
8354 }
8355
8356 if (relax_omega < 1.0 && it > 1 && !std::isnan(thinkt_prev[tidx])) {
8357 const double rawd = dbl(thinkt[tidx]);
8358 if (thinkt_prev[tidx] > 10.0 * rawd && rawd > GlobalConstants::FineTol) {
8359 thinkt_prev[tidx] = rawd;
8360 thinkt_prev_v[tidx] = thinkt[tidx];
8361 }
8362 const T om = num_traits<T>::from_double(relax_omega);
8363 const T om1 = num_traits<T>::from_double(1.0 - relax_omega);
8364 thinkt[tidx] = T(om * thinkt[tidx] + om1 * thinkt_prev_v[tidx]);
8365 }
8366 thinkt_prev[tidx] = dbl(thinkt[tidx]);
8367 thinkt_prev_v[tidx] = thinkt[tidx];
8368 thinktproc[tidx] = Distrib<T>::exp_mean(T(thinkt[tidx] + ztask));
8369 }
8370 }
8371
8372 // -----------------------------------------------------------------------
8373 // updateLayers and updateRoutingProbabilities
8374 // -----------------------------------------------------------------------
8375 void update_layers(int it) {
8376 // Under "srvn.ph" the layer classes are one per caller task and their laws
8377 // are composed, not read off the update maps
8378 if (is_ph_encoding()) {
8379 update_layers_ph(it);
8380 return;
8381 }
8382 const bool elevator = (it % 2) == 1;
8383 const std::size_t nt = thinkt_map.size();
8384 for (std::size_t r = 0; r < nt; ++r) {
8385 const UpdRow& row = thinkt_map[elevator ? nt - 1 - r : r];
8386 qn::Layer<T>& L = ensemble[std::size_t(idxhash[row.idx])];
8387 if (row.aidx <= NT() && opt.interlocking &&
8388 L.classes[row.cls - 1].type == JobClassType::CLOSED)
8389 L.classes[row.cls - 1].population = njobs(row.aidx, row.idx);
8390 if (row.node == L.clientIdx) {
8391 if (lqn.type[row.aidx] == LqnElement::TASK) {
8392 if (lqn.sched[row.aidx] != SchedStrategy::REF) {
8393 if (!thinktproc[row.aidx].disabled)
8394 L.set_service(row.node, row.cls, thinktproc[row.aidx]);
8395 } else {
8396 L.set_service(row.node, row.cls, servtproc[row.aidx]);
8397 }
8398 } else {
8399 L.set_service(row.node, row.cls, servtproc[row.aidx]);
8400 }
8401 } else {
8402 L.set_service(row.node, row.cls, servtproc[row.aidx]);
8403 }
8404 }
8405 const std::size_t nc = call_map.size();
8406 for (std::size_t r = 0; r < nc; ++r) {
8407 const UpdRow& row = call_map[elevator ? nc - 1 - r : r];
8408 qn::Layer<T>& L = ensemble[std::size_t(idxhash[row.idx])];
8409 if (row.node == L.clientIdx) {
8410 L.set_service(row.node, row.cls, callservtproc[row.aidx]);
8411 } else {
8412 const std::size_t eidx = lqn.callpair_dst[row.aidx];
8413 // A phase-2 entry replies before phase 2 runs, so the caller is held for residt, not servt; charging
8414 // servt here while the caller's layer charges residt breaks flow conservation across the call.
8415 // Flat layering shares one model between caller and callee and takes no correction (updateLayers.m).
8416 if (has_phase2 && lnmethod != "flat.cs" && dbl(servt_ph2[eidx]) > GlobalConstants::FineTol)
8417 L.set_service(row.node, row.cls, Distrib<T>::exp_mean(residt[eidx]));
8418 else
8419 L.set_service(row.node, row.cls, servtproc[eidx]);
8420 }
8421 }
8422 // Async arrival rate: the caller activity fires at its own throughput,
8423 // and every firing releases callmean jobs into this layer's Source.
8424 // updateLayers.m:63-73 replays the same map; the geometric self-loop in
8425 // build_layer already accounts for callmean, so the rate is the bare
8426 // activity throughput, not scaled by it.
8427 //
8428 // The reference-path stage means go first, after the think times:
8429 // residt, callresidt, util and tput are all fresh by now.
8430 if (interlockMethod == "refpath") update_ref_path_stages(it);
8431 for (const UpdRow& row : arv_call_map) {
8432 qn::Layer<T>& L = ensemble[std::size_t(idxhash[row.idx])];
8433 const Distrib<T>& d = tputproc[lqn.callpair_src[row.aidx]];
8434 if (!d.disabled) L.set_service(row.node, row.cls, d);
8435 }
8436 }
8437
8438 /**
8439 * Port of updateRefPathStages: recompute every reference-path stage mean.
8440 *
8441 * A HOP stage stands for an entry whose task has no activity graph in the
8442 * layer: residt(e), minus callresidt(c)/entryvisits(e) for each descent the
8443 * chain re-expands below it, plus the wait W for one of its task's threads.
8444 * A GATE into a MEMBER charges W(callee task) alone, since everything else
8445 * the member owns is explicit in the layer. W is taken in the POPULATION
8446 * domain, never as the difference of two nearly equal response times.
8447 */
8448 void update_ref_path_stages(int it) {
8449 if (refpath_map.empty()) return;
8450 const std::size_t nkeys = refpath_keys.size();
8451 std::vector<T> stage(nkeys, Tzero());
8452 for (std::size_t r = 0; r < refpath_map.size(); ++r) {
8453 const RefPathRow& row = refpath_map[r];
8454 T term = Tzero();
8455 switch (row.kind) {
8456 case 1: // the entry's own residence, per entry invocation
8457 term = residt[row.elem];
8458 break;
8459 case 2: { // a re-expanded descent, converted to the entry scale
8460 T v = Tone();
8461 if (row.fromentry >= 1 && dbl(entryvisits[row.fromentry]) > GlobalConstants::FineTol)
8462 v = entryvisits[row.fromentry];
8463 term = T(callresidt[row.elem] / v);
8464 break;
8465 }
8466 case 3: // the thread-acquisition wait of the task
8467 term = thread_wait(row.elem);
8468 break;
8469 }
8470 if (!std::isfinite(dbl(term))) term = Tzero();
8471 stage[refpath_group[r]] = T(stage[refpath_group[r]] + term * num_traits<T>::from_double(row.sign));
8472 }
8473 const double omega = relax_omega;
8474 for (std::size_t k = 0; k < nkeys; ++k) {
8475 if (stage[k] < Tzero()) stage[k] = Tzero();
8476 // the think-time schedule, including the escape from a divergent iterate
8477 if (omega < 1.0 && it > 1 && !std::isnan(refpath_stage_prev[k])) {
8478 T prevS = refpath_stage_prev_v[k];
8479 if (dbl(prevS) > 10.0 * dbl(stage[k]) && dbl(stage[k]) > GlobalConstants::FineTol)
8480 prevS = stage[k];
8481 stage[k] = T(num_traits<T>::from_double(omega) * stage[k] +
8482 num_traits<T>::from_double(1.0 - omega) * prevS);
8483 }
8484 refpath_stage_prev[k] = dbl(stage[k]);
8485 refpath_stage_prev_v[k] = stage[k];
8486 qn::Layer<T>& L = ensemble[std::size_t(idxhash[refpath_keys[k][0]])];
8487 // exp_mean(0) is an infinite rate, which the visit solve reads as a
8488 // disabled pair and drops from the chain
8489 if (dbl(stage[k]) > GlobalConstants::FineTol)
8490 L.set_service(refpath_keys[k][1], refpath_keys[k][2], Distrib<T>::exp_mean(stage[k]));
8491 else
8492 L.set_service(refpath_keys[k][1], refpath_keys[k][2], Distrib<T>::immediate());
8493 }
8494 }
8495
8496 /**
8497 * Mean time a request queues for a thread of task TIDX, read from TIDX's own
8498 * layer in the population domain, max(0, Q - m*U)/X. An infinite or
8499 * unbounded pool never queues.
8500 */
8501 T thread_wait(std::size_t tidx) const {
8502 if (tidx < 1 || tidx > lqn.nidx) return Tzero();
8503 if (lqn.sched[tidx] == SchedStrategy::INF || !std::isfinite(lqn.maxmult[tidx])) return Tzero();
8504 if (idxhash[tidx] < 0 || results.empty()) return Tzero();
8505 const std::size_t e = std::size_t(idxhash[tidx]);
8506 const qn::Layer<T>& L = ensemble[e];
8507 const LayerResult<T>& r = results.back()[e];
8508 const std::size_t ks = station_idx_of(L, tidx);
8509 T Qtot = Tzero();
8510 for (std::size_t c = 0; c < L.nclasses; ++c) Qtot += r.QN(ks - 1, c);
8511 const T Btot = T(num_traits<T>::from_double(lqn.maxmult[tidx]) * util[tidx]);
8512 const T Xtot = T(tput[tidx] / num_traits<T>::from_double(std::max(1.0, lqn.repl[tidx])));
8513 if (!(dbl(Xtot) > GlobalConstants::FineTol)) return Tzero();
8514 T d = T(Qtot - Btot);
8515 const T z = num_traits<T>::from_double(GlobalConstants::Zero);
8516 if (d < z) d = z;
8517 return T(d / Xtot);
8518 }
8519
8520 /**
8521 * Time a job of `cls`'s CHAIN spends blocked at this layer's region.
8522 *
8523 * A job held by an admission constraint is at no station at all, so its
8524 * wait is structurally absent from the RN and WN the layer reports back and
8525 * the caller and the callee end up disagreeing on throughput -- the fixed
8526 * point still converges, it just converges to the wrong place.
8527 *
8528 * Recovered by Little over the CHAIN, never per class: a job switches class
8529 * along the activity graph, so a call class carries population 0 and a
8530 * per-class deficit comes out negative and silently does nothing.
8531 * Zero for a layer with no region, which is every layer in a plain model.
8532 */
8533 T region_wait(std::size_t e, std::size_t cls) const {
8534 const qn::Layer<T>& L = ensemble[e];
8535 if (L.regions.empty() || results.empty()) return Tzero();
8536 const LayerResult<T>& r = results.back()[e];
8537 const std::size_t k = cls - 1;
8538 std::size_t c = L.nchains;
8539 for (std::size_t cc = 0; cc < L.nchains; ++cc)
8540 if (L.chains[cc][k]) c = cc;
8541 if (c == L.nchains) return Tzero();
8542
8543 // the station the region is stated over, which under `flat.cs` is one
8544 // among many and under `srvn` is the layer's own server
8545 std::size_t rs = L.serverIdx;
8546 for (std::size_t i = 0; i < L.regions[0].members.size(); ++i)
8547 if (L.regions[0].members[i]) { rs = i + 1; break; }
8548
8549 double pop = 0.0;
8550 T inside = Tzero(), tput_srv = Tzero();
8551 for (std::size_t j = 0; j < L.nclasses; ++j) {
8552 if (!L.chains[c][j]) continue;
8553 const double p = L.classes[j].population;
8554 if (!std::isfinite(p)) return Tzero(); // an open chain has no population to close on
8555 pop += p;
8556 for (std::size_t i = 0; i < L.nstations; ++i) inside += r.QN(i, j);
8557 tput_srv += r.TN(rs - 1, j);
8558 }
8559 const T deficit = T(num_traits<T>::from_double(pop) - inside);
8560 if (!(deficit > Tzero()) || !(tput_srv > Tzero())) return Tzero();
8561 return T(deficit / tput_srv);
8562 }
8563
8564 /** Port of updateRoutingProbabilities: entry selection by throughput ratio. */
8565 void update_routing_probabilities(int) {
8566 for (std::size_t u = 0; u < unique_route_idx.size(); ++u) {
8567 // the reference always takes the reversed order here: its `mod(it,0)`
8568 // guard is NaN, which MATLAB reads as false
8569 const std::size_t idx = unique_route_idx[unique_route_idx.size() - 1 - u];
8570 qn::Layer<T>& L = ensemble[std::size_t(idxhash[idx])];
8571 bool updated = false;
8572 for (const RouteRow& r : route_map) {
8573 if (r.idx != idx) continue;
8574 if (idxhash[r.tidx_caller] < 0) continue;
8575 const std::size_t cl = std::size_t(idxhash[r.tidx_caller]);
8576 const qn::Layer<T>& CL = ensemble[cl];
8577 const LayerResult<T>& cr = results.back()[cl];
8578 // the CALLER's own station, and for a call class the station of
8579 // the entry it targets; the two coincide under `srvn`
8580 const std::size_t cs = station_idx_of(CL, r.tidx_caller);
8581 T Xtot = Tzero();
8582 for (std::size_t k = 0; k < CL.nclasses; ++k) Xtot += cr.TN(cs - 1, k);
8583 if (!(Xtot > Tzero())) continue;
8584 T entry_tput = Tzero();
8585 for (const auto& a : CL.attr_calls)
8586 if (a[3] == r.eidx)
8587 entry_tput += cr.TN(station_idx_of(CL, lqn.parent[a[3]]) - 1, a[0] - 1);
8588 L.set_route(r.cfrom, r.cto, r.nodefrom, r.nodeto, T(entry_tput / Xtot));
8589 updated = true;
8590 }
8591 if (updated) L.refresh_chains();
8592 }
8593 }
8594
8595 // -----------------------------------------------------------------------
8596 // getTranAvg: getTranAvgDecoupled and getTranAvgCoupled
8597 // -----------------------------------------------------------------------
8598
8599 /**
8600 * What a layered transient needs before it can mean anything.
8601 *
8602 * A FLUID ENSEMBLE IS REQUIRED, and not as an implementation shortcut: the
8603 * reference reaches the layer transient through `self.solvers{e}.getTranAvg`,
8604 * which only a transient-capable layer solver has, and the coupled mode
8605 * injects its time-varying demands through the fluid rate schedule
8606 * specifically. An MVA layer has no trajectory to report and no place to
8607 * receive an injection, so an ensemble built on one is refused here rather
8608 * than silently answered with its steady state repeated over a grid.
8609 */
8610 void require_transient_ready() const {
8611 if (opt.layer_solver != "fluid")
8612 throw UnsupportedError(ErrorKind{"Analysis"},
8613 "SolverLN: the layered transient is the transient OF EACH LAYER, which only the "
8614 "fluid layer solver has; rebuild the ensemble with layer_solver 'fluid'");
8615 }
8616
8617 /** True when the caller named a horizon; otherwise each layer picks its own. */
8618 bool has_finite_horizon() const {
8619 return std::isfinite(opt.timespan_end) && opt.timespan_end > 0.0;
8620 }
8621
8622 /** One layer's trajectory, resampled onto the shared grid. */
8623 struct TranTraj {
8624 std::vector<std::vector<std::vector<double>>> Q, U, Tp, R; ///< [station][class][point]
8625 };
8626
8627 /**
8628 * Run one layer's transient, optionally with an injected rate schedule, and
8629 * return both the reportable block and the trajectory the relaxation reads.
8630 */
8631 void run_layer_transient(std::size_t e, const std::vector<FluidRateSched>& sched,
8632 LnTranLayer& block, TranTraj& traj) {
8633 qn::Layer<T>& L = ensemble[e];
8634 L.refresh_rt();
8635 fluid::FluidOptions fo = opt.layer_fluid;
8636 fo.rate_sched = sched;
8637 // THE WARM START IS REPLAYED HERE, and this is the only place it can be:
8638 // `converged` resets every layer the first time the fixed point settles,
8639 // so a state installed before the solve is gone by now. The steady solve
8640 // ignores an initial state and the transient does not, which is why
8641 // replaying it after the one and before the other loses nothing.
8642 if (e < layer_tran_init.size() && !layer_tran_init[e].empty())
8643 fo.init_sol = layer_tran_init[e];
8644 // No horizon named: this layer picks its own, by the analyzer's own rule
8645 // (thirty mean events of its slowest transition). That is what the
8646 // reference's decoupled path does -- each layer's SolverFluid chooses --
8647 // and it is why an unset timespan is a valid request rather than an error.
8648 const double t_end =
8649 has_finite_horizon() ? opt.timespan_end : fluid::fluid_default_horizon(L, fo);
8650 const std::vector<fluid::FluidTranPoint> pts =
8651 detail::ln_fluid_transient(L, fo, t_end, opt.tran_points, opt.tran_grid);
8652 const std::size_t M = L.nstations, K = L.nclasses, P = pts.size();
8653 block.t.resize(P);
8654 auto alloc = [&](std::vector<std::vector<std::vector<double>>>& A) {
8655 A.assign(M, std::vector<std::vector<double>>(K, std::vector<double>(P, 0.0)));
8656 };
8657 alloc(block.QN);
8658 alloc(block.UN);
8659 alloc(block.TN);
8660 alloc(traj.Q);
8661 alloc(traj.U);
8662 alloc(traj.Tp);
8663 alloc(traj.R);
8664 for (std::size_t p = 0; p < P; ++p) {
8665 block.t[p] = pts[p].t;
8666 for (std::size_t i = 0; i < M; ++i)
8667 for (std::size_t r = 0; r < K; ++r) {
8668 const double q = pts[p].QN(i, r), u = pts[p].UN(i, r), x = pts[p].TN(i, r);
8669 block.QN[i][r][p] = q;
8670 block.UN[i][r][p] = u;
8671 block.TN[i][r][p] = x;
8672 traj.Q[i][r][p] = q;
8673 traj.U[i][r][p] = u;
8674 traj.Tp[i][r][p] = x;
8675 // Residence by Little, which is how the relaxation reads a
8676 // callee's response time off a layer trajectory.
8677 traj.R[i][r][p] = q / std::max(x, GlobalConstants::FineTol);
8678 }
8679 }
8680 }
8681
8682 /**
8683 * Port of getTranAvgDecoupled: freeze the inter-layer demands at the
8684 * converged fixed point and run each layer's transient in isolation.
8685 */
8686 LnTranSolution tran_avg_decoupled() {
8687 require_transient_ready();
8688 if (results.empty()) iterate();
8689 LnTranSolution out;
8690 out.mode = "decoupled";
8691 out.layers.resize(ensemble.size());
8692 for (std::size_t e = 0; e < ensemble.size(); ++e) {
8693 TranTraj tj;
8694 run_layer_transient(e, std::vector<FluidRateSched>(), out.layers[e], tj);
8695 }
8696 return out;
8697 }
8698
8699 /**
8700 * Port of getTranAvgCoupled: reconcile the per-layer transients by waveform
8701 * relaxation, so the layer populations and the inter-layer demands co-evolve
8702 * in model time.
8703 *
8704 * Each layer's fluid transient is driven by TIME-VARYING inter-layer demand
8705 * trajectories taken from the other layers' latest transients, and the loop
8706 * repeats until the trajectories stop moving in sup-norm. Iteration 0 uses
8707 * the frozen equilibrium demands, so it reproduces the decoupled answer
8708 * exactly; at convergence every layer relaxes to its own fixed point, so the
8709 * endpoint equals getAvg.
8710 *
8711 * TWO CHANNELS ARE COUPLED, the task think times (the client delay) and the
8712 * synchronous-call service demands (the caller's client station). Both are
8713 * dominant inter-layer couplings; the intra-layer host service stays at its
8714 * equilibrium value, as in the reference.
8715 */
8716 LnTranSolution tran_avg_coupled() {
8717 require_transient_ready();
8718 // Waveform relaxation reconciles the layers on ONE shared grid, so it
8719 // needs a horizon the layers agree on. With none named there is nothing
8720 // to co-evolve over, and the reference defers to the decoupled path
8721 // rather than inventing one; so does this.
8722 if (!has_finite_horizon()) return tran_avg_decoupled();
8723 if (results.empty()) iterate();
8724 const std::size_t E = ensemble.size();
8725
8726 LnTranSolution out;
8727 out.mode = "coupled";
8728 out.layers.resize(E);
8729 std::vector<TranTraj> traj(E), prev(E);
8730 for (std::size_t e = 0; e < E; ++e)
8731 run_layer_transient(e, std::vector<FluidRateSched>(), out.layers[e], traj[e]);
8732 const std::vector<double> tgrid = out.layers.empty() ? std::vector<double>() : out.layers[0].t;
8733
8734 for (long iter = 1; iter <= opt.ln_transient_iter_max; ++iter) {
8735 prev = traj;
8736 const std::vector<std::vector<FluidRateSched>> sched =
8737 build_rate_sched(recompute_demand(traj, tgrid), tgrid);
8738 for (std::size_t e = 0; e < E; ++e)
8739 run_layer_transient(e, sched[e], out.layers[e], traj[e]);
8740 double gap = 0.0;
8741 for (std::size_t e = 0; e < E; ++e)
8742 for (std::size_t i = 0; i < traj[e].Q.size(); ++i)
8743 for (std::size_t r = 0; r < traj[e].Q[i].size(); ++r)
8744 for (std::size_t p = 0; p < traj[e].Q[i][r].size(); ++p)
8745 gap = std::max(gap, std::fabs(traj[e].Q[i][r][p] - prev[e].Q[i][r][p]));
8746 out.iterations = iter;
8747 out.gap = gap;
8748 if (gap < opt.ln_transient_tol) break;
8749 }
8750 return out;
8751 }
8752
8753 /** The two coupled demand channels, as trajectories on the shared grid. */
8754 struct TranDemand {
8755 std::map<std::size_t, std::vector<double>> thinkt; ///< by task element index
8756 std::map<std::size_t, std::vector<double>> callservt; ///< by call index
8757 };
8758
8759 /**
8760 * Recompute the inter-layer demands pointwise in t, mirroring the SCALAR
8761 * updateThinkTimes and updateMetricsDefault formulas.
8762 *
8763 * They are the same formulas, evaluated at each point of the grid instead of
8764 * at the fixed point: that is what makes the endpoint of the relaxation the
8765 * steady-state answer rather than something near it.
8766 */
8767 TranDemand recompute_demand(const std::vector<TranTraj>& traj,
8768 const std::vector<double>& tgrid) const {
8769 TranDemand out;
8770 const std::size_t ng = tgrid.size();
8771
8772 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
8773 const std::size_t tidx = lqn.tshift + t;
8774 if (idxhash[tidx] < 0 || lqn.isref[tidx]) continue;
8775 const std::size_t e = std::size_t(idxhash[tidx]);
8776 const qn::Layer<T>& L = ensemble[e];
8777 const std::size_t s = station_idx_of(L, tidx) - 1;
8778 double nj = 0.0;
8779 for (std::size_t c = 1; c <= NT(); ++c) nj = std::max(nj, njobs(tidx, c));
8780 // same closure as update_think_times, so the same gate
8781 const double userthink = dbl(ref_think_time(tidx));
8782 std::vector<double> tk(ng, 0.0);
8783 for (std::size_t p = 0; p < ng; ++p) {
8784 double U = 0.0, X = 0.0;
8785 for (std::size_t r = 0; r < L.nclasses; ++r) {
8786 U += traj[e].U[s][r][p];
8787 X += traj[e].Tp[s][r][p];
8788 }
8789 const double Xs = std::max(X, GlobalConstants::FineTol);
8790 double v = lqn.sched[tidx] == SchedStrategy::INF
8791 ? (nj - U) / Xs - userthink
8792 : nj * std::fabs(1.0 - U) / Xs - userthink;
8794 tk[p] = v + userthink; // total mean, user think included
8795 }
8796 out.thinkt[tidx] = tk;
8797 }
8798
8799 for (std::size_t cidx = 1; cidx <= lqn.ncalls; ++cidx) {
8800 if (lqn.calltype[cidx] != CallType::SYNC) continue;
8801 const std::size_t eidx = lqn.callpair_dst[cidx];
8802 const std::size_t tidx = lqn.parent[eidx];
8803 if (tidx > NT() || idxhash[tidx] < 0) continue;
8804 const std::size_t e = std::size_t(idxhash[tidx]);
8805 const qn::Layer<T>& L = ensemble[e];
8806 const std::size_t s = station_idx_of(L, tidx) - 1;
8807 std::vector<double> Rc(ng, 0.0);
8808 bool any = false;
8809 for (std::size_t r = 0; r < L.nclasses; ++r) {
8810 if (L.classes[r].attr_kind != int(LqnElement::ENTRY)) continue;
8811 if (L.classes[r].attr_idx != eidx) continue;
8812 any = true;
8813 for (std::size_t p = 0; p < ng; ++p) Rc[p] += traj[e].R[s][r][p];
8814 }
8815 if (!any) {
8816 // No entry class of its own in this layer: the entry's work is
8817 // carried by its activities, so their residence is the answer.
8818 for (std::size_t r = 0; r < L.nclasses; ++r)
8819 for (std::size_t p = 0; p < ng; ++p) Rc[p] += traj[e].R[s][r][p];
8820 }
8821 const double cm = dbl(lqn.callproc_mean[cidx]);
8822 for (std::size_t p = 0; p < ng; ++p) Rc[p] *= cm;
8823 out.callservt[cidx] = Rc;
8824 }
8825 return out;
8826 }
8827
8828 /**
8829 * Map the demand trajectories onto per-layer rate schedules, through the
8830 * SAME update maps that place the scalar setService calls.
8831 *
8832 * The injected schedule MODULATES the layer's equilibrium rate by the ratio
8833 * of the transient demand to its steady-state value: passing rate = 1/d(t)
8834 * with nominal = 1/d(end) makes solver_fluid_ratemult's multiplier
8835 * d(end)/d(t), which is exactly 1 at the horizon end. That is what makes the
8836 * layer relax to its UNMODIFIED fixed point regardless of any small mismatch
8837 * between the fluid residence Q/T and the scalar equilibrium demand.
8838 */
8839 std::vector<std::vector<FluidRateSched>> build_rate_sched(
8840 const TranDemand& demand, const std::vector<double>& tgrid) const {
8841 std::vector<std::vector<FluidRateSched>> out(ensemble.size());
8842 const bool want_think =
8843 opt.ln_transient_channels == "both" || opt.ln_transient_channels == "thinkt";
8844 const bool want_call =
8845 opt.ln_transient_channels == "both" || opt.ln_transient_channels == "callservt";
8846
8847 auto add = [&](std::size_t e, std::size_t station, std::size_t cls,
8848 const std::vector<double>& d) {
8849 if (d.empty()) return;
8850 const double dend = d.back();
8851 if (!(dend > GlobalConstants::FineTol)) return; // degenerate steady state
8852 // Bound the transient demand to a physical band around its
8853 // steady-state value: an early-transient throughput near zero sends
8854 // the reciprocal to infinity and the integrator with it.
8855 const double cap = 20.0;
8857 s.station = station;
8858 s.cls = cls;
8859 s.tgrid = tgrid;
8860 s.rates.resize(d.size());
8861 for (std::size_t p = 0; p < d.size(); ++p) {
8862 const double v = std::min(std::max(d[p], dend / cap), dend * cap);
8863 s.rates[p] = 1.0 / v;
8864 }
8865 s.nominal = 1.0 / dend;
8866 out[e].push_back(s);
8867 };
8868
8869 if (want_think)
8870 for (const UpdRow& row : thinkt_map) {
8871 if (idxhash[row.idx] < 0) continue;
8872 const std::size_t e = std::size_t(idxhash[row.idx]);
8873 if (row.node != ensemble[e].clientIdx) continue;
8874 if (lqn.type[row.aidx] != LqnElement::TASK) continue;
8875 if (lqn.sched[row.aidx] == SchedStrategy::REF) continue;
8876 const auto it = demand.thinkt.find(row.aidx);
8877 if (it == demand.thinkt.end()) continue;
8878 add(e, row.node, row.cls, it->second);
8879 }
8880 if (want_call)
8881 for (const UpdRow& row : call_map) {
8882 if (idxhash[row.idx] < 0) continue;
8883 const std::size_t e = std::size_t(idxhash[row.idx]);
8884 if (row.node != ensemble[e].clientIdx) continue;
8885 const auto it = demand.callservt.find(row.aidx);
8886 if (it == demand.callservt.end()) continue;
8887 add(e, row.node, row.cls, it->second);
8888 }
8889 return out;
8890 }
8891
8892 /// First activity bound to entry EIDX, or 0 when it has none.
8893 std::size_t bound_activity_of(std::size_t eidx) const {
8894 for (std::size_t sx : lqn.graph.succ(eidx))
8895 if (sx > lqn.ashift) return sx;
8896 return 0;
8897 }
8898
8899 // -----------------------------------------------------------------------
8900 // getEnsembleAvg
8901 // -----------------------------------------------------------------------
8902 LnSolution<T> aggregate() {
8903 const std::size_t N = lqn.nidx;
8904 LnSolution<T> s;
8905 auto mk = [&](std::vector<T>& v, std::vector<bool>& d) {
8906 v.assign(N + 1, Tzero());
8907 d.assign(N + 1, false);
8908 };
8909 std::vector<T> QN, UN, RN, TN, PN, SN, WN, AN;
8910 std::vector<bool> dQ, dU, dR, dT, dP, dS, dW, dA;
8911 mk(QN, dQ); mk(UN, dU); mk(RN, dR); mk(TN, dT);
8912 mk(PN, dP); mk(SN, dS); mk(WN, dW); mk(AN, dA);
8913 std::vector<bool> wn_done(N + 1, false);
8914
8915 for (std::size_t e = 0; e < ensemble.size(); ++e) {
8916 const qn::Layer<T>& L = ensemble[e];
8917 const LayerResult<T>& r = results.back()[e];
8918 const std::size_t clientIdx = L.clientIdx;
8919 // The processors this layer serves: one under `srvn` (and only when
8920 // it is a host layer), every one of them under `flat.cs`. Each is
8921 // charged with the activities that actually run on it, which is
8922 // vacuous under `srvn` because a host layer holds no others.
8923 const bool has_host_server = !L.host_stations.empty();
8924 for (std::size_t hs : L.host_stations) {
8925 const std::size_t hidx = L.stations[hs - 1].attr_idx;
8926 dT[hidx] = true;
8927 TN[hidx] = Tzero();
8928 dP[hidx] = true;
8929 PN[hidx] = Tzero();
8930 for (std::size_t k = 0; k < L.nclasses; ++k) {
8931 if (L.classes[k].completes) {
8932 T t = clientIdx > 0 ? r.TN(clientIdx - 1, k) : Tzero();
8933 const T ts = r.TN(hs - 1, k);
8934 TN[hidx] = T(TN[hidx] + (t > ts ? t : ts));
8935 }
8936 if (L.classes[k].attr_kind == int(LqnElement::ACTIVITY)) {
8937 // the activity does not run on this processor
8938 if (station_idx_of_class(L, k) != hs) continue;
8939 const std::size_t aidx = L.classes[k].attr_idx;
8940 const std::size_t tidx = lqn.parent[aidx];
8941 dP[aidx] = true;
8942 dP[tidx] = true;
8943 PN[aidx] = T(PN[aidx] + r.UN(hs - 1, k));
8944 PN[tidx] = T(PN[tidx] + r.UN(hs - 1, k));
8945 PN[hidx] = T(PN[hidx] + r.UN(hs - 1, k));
8946 } else if (L.classes[k].attr_kind == int(LqnElement::ENTRY)
8947 && L.classes[k].type == JobClassType::OPEN) {
8948 // an entry's own open stream is served here for its bound
8949 // activity's demand, so its busy time belongs to that activity,
8950 // its task and this processor like any other
8951 if (station_idx_of_class(L, k) != hs) continue;
8952 const std::size_t eidx = L.classes[k].attr_idx;
8953 const std::size_t tidx = lqn.parent[eidx];
8954 const std::size_t aidx = bound_activity_of(eidx);
8955 const T uo = r.UN(hs - 1, k);
8956 if (aidx != 0) {
8957 dP[aidx] = true;
8958 PN[aidx] = T(PN[aidx] + uo);
8959 }
8960 dP[tidx] = true;
8961 PN[tidx] = T(PN[tidx] + uo);
8962 PN[hidx] = T(PN[hidx] + uo);
8963 }
8964 }
8965 dT[hidx] = false; // NaN in the reference, for consistency with LQNS
8966 }
8967
8968 for (std::size_t k = 0; k < L.nclasses; ++k) {
8969 const int kind = L.classes[k].attr_kind;
8970 // the station this class is actually served at, which under
8971 // `flat.cs` is the processor of an activity or the called task
8972 // of a call rather than the one server the layer used to have
8973 const std::size_t serverIdx = station_idx_of_class(L, k);
8974 if (kind == int(LqnElement::TASK)) {
8975 const std::size_t tidx = L.classes[k].attr_idx;
8976 if (has_host_server && !dT[tidx]) {
8977 dT[tidx] = true;
8978 TN[tidx] = r.TN(clientIdx - 1, k);
8979 }
8980 } else if (kind == int(LqnElement::ENTRY) && L.classes[k].type == JobClassType::OPEN) {
8981 // the entry's own open stream, on top of what its callers send: it
8982 // rides a class of its own in the host layer, so its rate adds to the
8983 // entry, its task and its bound activity
8984 const std::size_t eidx = L.classes[k].attr_idx;
8985 const T to = r.TN(L.classes[k].refstat - 1, k);
8986 for (std::size_t idx : {eidx, lqn.parent[eidx], bound_activity_of(eidx)}) {
8987 if (idx == 0) continue;
8988 dT[idx] = true;
8989 TN[idx] = T(TN[idx] + to);
8990 }
8991 } else if (kind == int(LqnElement::ENTRY)) {
8992 const std::size_t eidx = L.classes[k].attr_idx;
8993 dS[eidx] = true;
8994 // getEnsembleAvg.m:84-92: a phase-2 entry reports the
8995 // CALLER's view, which is what residt now holds.
8996 SN[eidx] = (has_phase2 && dbl(servt_ph2[eidx]) > GlobalConstants::FineTol)
8997 ? residt[eidx]
8998 : servt[eidx];
8999 if (has_host_server && !dT[eidx]) {
9000 dT[eidx] = true;
9001 TN[eidx] = r.TN(clientIdx - 1, k);
9002 }
9003 } else if (kind == int(LqnElement::CALL)) {
9004 const std::size_t cidx = L.classes[k].attr_idx;
9005 const std::size_t aidx = lqn.callpair_src[cidx];
9006 if (lqn.calltype[cidx] == CallType::SYNC) {
9007 dS[aidx] = true;
9008 SN[aidx] = T(SN[aidx] + r.RN(serverIdx - 1, k) * lqn.callproc_mean[cidx]);
9009 }
9010 dQ[aidx] = true;
9011 QN[aidx] = T(QN[aidx] + r.QN(serverIdx - 1, k));
9012 } else if (kind == int(LqnElement::ACTIVITY)) {
9013 const std::size_t aidx = L.classes[k].attr_idx;
9014 const std::size_t tidx = lqn.parent[aidx];
9015 dQ[tidx] = true;
9016 QN[tidx] = T(QN[tidx] + r.QN(serverIdx - 1, k));
9017 dT[aidx] = true;
9018 dQ[aidx] = true;
9019 TN[aidx] = T(TN[aidx] + r.TN(serverIdx - 1, k));
9020 dS[aidx] = true;
9021 SN[aidx] = T(SN[aidx] + r.RN(serverIdx - 1, k));
9022 dR[aidx] = true;
9023 RN[aidx] = T(RN[aidx] + r.RN(serverIdx - 1, k));
9024 dW[aidx] = true;
9025 dW[tidx] = true;
9026 WN[aidx] = residt[aidx];
9027 if (!wn_done[aidx]) {
9028 WN[tidx] = T(WN[tidx] + residt[aidx]);
9029 wn_done[aidx] = true;
9030 }
9031 QN[aidx] = T(QN[aidx] + r.QN(serverIdx - 1, k));
9032 }
9033 }
9034 }
9035
9036 // A replicated element is solved as ONE representative replica; report it as the
9037 // TOTAL over its copies (TN and busy time scaled by repl, response times per
9038 // request). Mirrors MATLAB getEnsembleAvg; inert when nothing is replicated.
9039 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
9040 const std::size_t tidx = lqn.tshift + t;
9041 const double nrep = lqn.repl[tidx];
9042 if (!(nrep > 1.0)) continue;
9043 std::vector<std::size_t> scaleIdx{tidx};
9044 scaleIdx.insert(scaleIdx.end(), lqn.entriesof[tidx].begin(), lqn.entriesof[tidx].end());
9045 scaleIdx.insert(scaleIdx.end(), lqn.actsof[tidx].begin(), lqn.actsof[tidx].end());
9046 // read from a host layer that held every replica (BUG-110): the client row
9047 // is already the total, a server station holds one host replica's share
9048 const auto hr = host_all_replica_tasks.find(tidx);
9049 const bool hall = hr != host_all_replica_tasks.end();
9050 const T pscale = num_traits<T>::from_double(hall ? double(hr->second) : nrep);
9051 for (std::size_t idx : scaleIdx) {
9052 const bool isact = std::find(lqn.actsof[tidx].begin(), lqn.actsof[tidx].end(), idx) !=
9053 lqn.actsof[tidx].end();
9054 const T tscale = !hall ? num_traits<T>::from_double(nrep)
9055 : isact ? pscale : Tone();
9056 if (dT[idx]) TN[idx] = T(tscale * TN[idx]);
9057 if (dP[idx]) PN[idx] = T(pscale * PN[idx]);
9058 }
9059 }
9060 for (std::size_t hidx = 1; hidx <= lqn.nhosts; ++hidx)
9061 if (lqn.repl[hidx] > 1.0 && dP[hidx]) PN[hidx] = T(num_traits<T>::from_double(lqn.repl[hidx]) * PN[hidx]);
9062
9063 // A routing fork is solved in the host layer and the called task is
9064 // solved again in its task layer. Use the task-layer request rate for
9065 // the task, entries, and fork branches so the reported cycle is flow
9066 // balanced rather than the independent host-layer class cycle.
9067 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
9068 const std::size_t tidx = lqn.tshift + t;
9069 bool has_fork = false;
9070 for (std::size_t aidx : lqn.actsof[tidx]) {
9071 if (lqn.actposttype[aidx] == PrecedenceType::POST_AND) {
9072 has_fork = true;
9073 break;
9074 }
9075 }
9076 if (!has_fork || !dT[tidx] || !(dbl(TN[tidx]) > GlobalConstants::FineTol)) continue;
9077 const T task_tput = tput[tidx];
9078 if (!(dbl(task_tput) > GlobalConstants::FineTol) || !std::isfinite(dbl(task_tput))) continue;
9079 const T flow_scale = T(task_tput / TN[tidx]);
9080 if (!(dbl(flow_scale) > 0.0) || !std::isfinite(dbl(flow_scale))) continue;
9081 std::vector<std::size_t> scale_idx{tidx};
9082 scale_idx.insert(scale_idx.end(), lqn.entriesof[tidx].begin(), lqn.entriesof[tidx].end());
9083 scale_idx.insert(scale_idx.end(), lqn.actsof[tidx].begin(), lqn.actsof[tidx].end());
9084 for (std::size_t idx : scale_idx)
9085 if (dT[idx]) TN[idx] = T(flow_scale * TN[idx]);
9086 }
9087
9088 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
9089 const std::size_t eidx = lqn.eshift + e;
9090 const std::size_t tidx = lqn.parent[eidx];
9091 dU[tidx] = true;
9092 dU[eidx] = true;
9093 // getEnsembleAvg.m:186-198: the server is busy through BOTH phases,
9094 // so the utilization is the full service time and not SN, which for
9095 // a phase-2 entry has been cut down to the caller's view above.
9096 UN[eidx] = (has_phase2 && dbl(servt_ph2[eidx]) > GlobalConstants::FineTol)
9097 ? T(TN[eidx] * (servt_ph1[eidx] + servt_ph2[eidx]))
9098 : T(TN[eidx] * SN[eidx]);
9099 T ps = Tzero();
9100 bool any = false;
9101 for (std::size_t a : lqn.actsof[eidx])
9102 if (dP[a]) {
9103 ps += PN[a];
9104 any = true;
9105 }
9106 if (!lqn.actsof[eidx].empty()) {
9107 dP[eidx] = true;
9108 PN[eidx] = any ? ps : Tzero();
9109 }
9110 for (std::size_t a : lqn.actsof[tidx]) {
9111 dU[a] = true;
9112 UN[a] = T(TN[a] * SN[a]);
9113 }
9114 UN[tidx] = T(UN[tidx] + UN[eidx]);
9115 }
9116
9117 // AN IGNORED ELEMENT IS IDLE, NOT UNDEFINED, and the two are different cells.
9118 // Its component holds no reference task, so nothing reaches it and every
9119 // measure it HAS is zero -- but the measures its kind never has stay
9120 // undefined, exactly as they do for a reachable element. A flat zero over
9121 // all six columns broke the table's NaN mask (a processor with a queue
9122 // length of 0, an arrival rate reported where no solver reports one), and
9123 // the mask is part of the answer: see _kb/06-solver-catalog.md. The
9124 // relabelling below reports Q from U, U from P and R from S, so QN and RN
9125 // are dead here and are not written.
9126 for (std::size_t i = 1; i <= N; ++i)
9127 if (ignore[i]) {
9128 PN[i] = Tzero(); // every kind reports a utilization
9129 dP[i] = true;
9130 dA[i] = false; // nothing reports an arrival rate on an LQN
9131 const bool host = lqn.type[i] == LqnElement::HOST;
9132 const bool task = lqn.type[i] == LqnElement::TASK;
9133 const bool entry = lqn.type[i] == LqnElement::ENTRY;
9134 UN[i] = Tzero();
9135 dU[i] = !host;
9136 SN[i] = Tzero();
9137 dS[i] = !host && !task;
9138 WN[i] = Tzero();
9139 dW[i] = !host && !entry;
9140 TN[i] = Tzero();
9141 dT[i] = !host;
9142 }
9143
9144 // the reference's final relabelling: Q <- U, U <- P, R <- S
9145 s.QN = UN; s.defined_Q = dU;
9146 s.UN = PN; s.defined_U = dP;
9147 s.RN = SN; s.defined_R = dS;
9148 s.TN = TN; s.defined_T = dT;
9149 s.AN = AN; s.defined_A = dA;
9150 s.WN = WN; s.defined_W = dW;
9151 s.iterations = iterations_done;
9152 s.converged = did_converge;
9153 return s;
9154 }
9155};
9156
9157} // namespace ln
9158} // namespace line
9159
9160// Deliberately at the FOOT of the file: lqn_analyzers.h needs LayerResult and
9161// SolverLN complete, and this file needs its lqn_overtake_prob_markov, so the
9162// two are mutually dependent. Either include order works -- whichever header a
9163// translation unit names first, the other is fully parsed before the templates
9164// above are instantiated -- and the forward declaration near the top of this
9165// file is what makes the call inside update_metrics resolve.
9167
9168#endif // LINE_SOLVERS_LN_SOLVER_LN_H
Convolution of a sequence of matrix-exponential laws.
Minimal-order acyclic phase-type fit of the first three moments (matlab/lib/kpctoolbox/aph/aph_fit....
Composition of two matrix-exponential distributions given in (alpha, T) form.
Malformed or inconsistent input (dimensions, negative populations, ...): LINE:input:<kind>.
Definition error.h:103
InputError(const std::string &what)
Definition error.h:105
std::size_t cols() const
Definition matrix.h:90
std::size_t rows() const
Definition matrix.h:89
bool empty() const
Definition matrix.h:92
UnsupportedError(const std::string &what)
Definition error.h:119
Convergence controller for an ensemble whose layers are solved by a NOISY method (simulation,...
const std::vector< double > & state_refpath_stages() const
Per reference-path stage key, the stage mean the last iteration installed.
Definition solver_ln.h:963
const std::string & state_interlock_method() const
The interlock tracking method this run USES: "ilrate", "refpath" or "none".
Definition solver_ln.h:961
LnSolution< T > box_bounds()
Majumdar-Woodside robust box bounds, reported in the shape of a solution.
Definition solver_ln.h:790
LnLayerBlocks layer_blocks() const
Port of LayeredNetwork.layerBlocks: the block-diagonal layout of the layers in the aggregate (station...
Definition solver_ln.h:834
LnSolution< T > trapped_overlay(LnSolution< T > s) const
Nested blocking of the reference tasks trapped at a zero-capacity element (ln_zero_capacity): every e...
Definition solver_ln.h:622
const std::vector< std::vector< LayerResult< T > > > & iteration_results() const
Diagnostic access to the per-iteration layer results, for the regression.
Definition solver_ln.h:941
LnInterlockChoice interlock_method_for() const
Port of SolverLN.interlockMethodFor: the method a solve would use, asked through the same query build...
Definition solver_ln.h:971
const std::vector< T > & state_util() const
Definition solver_ln.h:951
SolverLN(const LqnStruct< T > &lqn_in, const LnOptions &options)
Definition solver_ln.h:558
LnSensTable< T > get_sensitivity_table(const sens::SensOptions &sopt)
Port of @SolverLN/getSensitivityTable: solve the ensemble, then concatenate each layer solver's own t...
Definition solver_ln.h:735
LnTranSolution get_tran_avg()
Port of @SolverLN/getTranAvg: the block-diagonal aggregate transient.
Definition solver_ln.h:712
const std::vector< T > & state_thinkt() const
Definition solver_ln.h:945
double nlp_objective() const
method='nlp': the program's objective at nlp_solution().
Definition solver_ln.h:585
std::size_t nlayers() const
Definition solver_ln.h:823
void get_block_avg(Matrix< T > &QN, Matrix< T > &UN, Matrix< T > &TN) const
Port of getBlockAvg: the layers' own STEADY averages, in the block-diagonal layout of layer_blocks (e...
Definition solver_ln.h:861
const std::vector< Distrib< T > > & state_callservtproc() const
Definition solver_ln.h:950
std::vector< LnCdf > get_cdf_respt()
Port of @SolverLN/getCdfRespT: the per-entry response-time distribution.
Definition solver_ln.h:669
const std::vector< T > & state_callresidt() const
Definition solver_ln.h:947
::line::lqn::NlpProgram nlp_program() const
The QD-AMVA program of this model under the solver's nlp options, the program method='nlp' roots and ...
Definition solver_ln.h:591
const std::vector< double > & state_maxitererr() const
Per iteration, the layer-summed max queue-length change the convergence test reads (index 0 unused).
Definition solver_ln.h:953
const std::string & state_lnmethod() const
The method the layers were built for: "srvn.ph", "srvn.cs" or "moment3".
Definition solver_ln.h:955
bool warmstarted() const
True once init() seeded the iterate from config.warmstart; converged() then drops iter_min.
Definition solver_ln.h:581
const std::vector< T > & state_tput() const
Definition solver_ln.h:944
void set_tran_grid(const std::vector< double > &g)
Install the explicit output grid of the layered transient; see LnOptions::tran_grid.
Definition solver_ln.h:938
const std::vector< T > & state_servt() const
Definition solver_ln.h:942
static std::vector< std::string > list_valid_methods()
Port of SolverLN.listValidMethods.
Definition solver_ln.h:553
const std::vector< Distrib< T > > & state_servtproc() const
Definition solver_ln.h:948
const std::vector< Distrib< T > > & state_thinktproc() const
Definition solver_ln.h:949
LnSolution< T > get_ensemble_avg()
Port of getEnsembleAvg: run the iteration and aggregate onto LQN elements.
Definition solver_ln.h:600
const std::vector< double > & nlp_solution() const
method='nlp': the program's solution, clipped at zero, in the program's variable order.
Definition solver_ln.h:583
const std::vector< T > & state_callservt() const
Definition solver_ln.h:946
const std::vector< qn::Layer< T > > & layers() const
Definition solver_ln.h:824
const std::vector< T > & state_residt() const
Definition solver_ln.h:943
void init_from_marginal(const Matrix< double > &n)
Port of LayeredNetwork.initFromMarginal: split an aggregate (M x K) mean queue-length matrix into per...
Definition solver_ln.h:906
The program of one layered model.
A layer network: everything a NetworkStruct holds, plus the LQN back-mapping.
Definition qn_layer.h:52
A network plus its refreshed NetworkStruct.
std::vector< std::vector< bool > > disabled
std::vector< Station< T > > stations
stations[k-1] is the k-th station
static void iter(long k, const char *fmt,...)
Report iteration k of the current loop.
static void step(const char *fmt,...)
Write one progress line.
static bool is_acyclic_generator(const Matrix< T > &S)
True when the phase graph of S has no cycle.
Definition workflow.h:699
static PhLaw< T > compose_loop_geometric(const PhLaw< T > &body, const T &count)
Geometric repetition of a phase-type law, the POST_LOOP semantics.
Definition workflow.h:627
static PhLaw< T > compose_serial(const PhLaw< T > &a, const PhLaw< T > &b)
Serial composition: the second law starts when the first absorbs.
Definition workflow.h:505
static PhLaw< T > compose_mixture(const std::vector< PhLaw< T > > &laws, const std::vector< T > &probs)
Probabilistic mixture: a block-diagonal generator whose initial vector picks branch i with probabilit...
Definition workflow.h:590
What refreshProcessRepresentations and refreshLST compute FROM a distribution: the (D0,...
The exception types the port throws.
Matrix exponential by scaling and squaring with a diagonal Pade approximant.
Activities belonging to each branch of an AND-join.
The fork-join fixed point that drives one inner MVA solve.
The fork-join transform SolverMVA applies before solving a layer that contains a Fork.
Mean and variance of a k-of-n (quorum) join completion time, from the mean and variance of each branc...
Response-time distribution by tagged fluid: a port of solver_fluid_passage_time.m,...
The fluid solver's outermost entry point: @@SolverFLD/runAnalyzer.m's method resolution over solver_f...
The NATIVE LDES discrete-event engine.
Dense linear algebra over the templated number type: products, identity, inverse, and powers.
Running progress log of a LINE solver run (the "solver console").
Reference tasks trapped at a zero-capacity element of a layered network.
The @SolverLN methods that solver_ln.h does not carry.
Majumdar-Woodside robust box bounds on the throughput of a layered network.
A layered queueing network as ONE nonlinear program: linear constraints over the flows,...
Standalone LQN routines that SolverLN needs but does not contain.
Method of Layers on the SRVN decomposition of a layered queueing network whose entries carry no activ...
Phase-type composition of an LQN activity graph, the machinery behind SolverLN method 'srvn....
.lqnx -> LqnStruct, a port of matlab/src/lang/layered/@LayeredNetwork/parseXML.m followed by ....
Synchronous call DAG carrying reference-task customers into a layer.
LayeredNetworkStruct, the flattened description of a layered queueing network.
Port of solver_mam_analyzer.m: one inner solve, choosing the analyzer that fits the model and the req...
Dense matrix and non-owning view.
The method names of each solver, in listing order.
Port of @@SolverMVA/mvaDispatch.m: one inner solve, choosing the analyzer that fits the model.
EntryWorkflow< T > entry_workflow(const ::line::lqn::LqnStruct< T > &lqn, std::size_t eidx, bool with_calls)
Activity graph of LQN entry EIDX as a Workflow.
Definition lqn_ph.h:104
PhLaw< T > ph_law_of(const Distrib< T > &d)
The (alpha, S) pair of a phase-type Distrib, the form the composition rules take.
Definition lqn_ph.h:52
PhLaw< T > serial_law(Workflow< T > &wf)
Composed law of a workflow in which the branches of an AND fork are SERIAL rather than concurrent,...
Definition lqn_ph.h:241
std::pair< T, T > ph_moments(const std::vector< T > &alpha, const Matrix< T > &S)
First two moments of a phase-type law without building a Distrib, which is what the layered fixed poi...
Definition lqn_ph.h:258
void sn_fj_nodevisits_mmt(qn::NetworkStruct< T > &sn)
Rewrite sn.nodevisits with the MMT correction.
T sn_compat_scaling(const Matrix< T > &compat, const std::vector< double > &counts, const std::vector< T > &rates, const std::vector< T > &n)
Rate scaling eta(n) a compatibility declaration imposes on its station.
mva::AvgResult< T > solver_ctmc_run_analyzer_any(const NetworkStruct< T > &sn, const CtmcOptions &opt)
Solve on whichever path applies and format, mirroring solver_ctmc_run_analyzer.
std::vector< std::vector< std::size_t > > fj_branch_members(const LqnBranchView< T > &lqn, std::size_t joinaidx)
Branch membership of an AND-join.
FJQuorumMomentsResult< T > fj_quorum_moments(const std::vector< T > &branchMeans, const std::vector< T > &branchVars, std::size_t k)
Mean and variance of a k-of-n (quorum) join completion time, from the mean and variance of each branc...
double fluid_default_horizon(const qn::NetworkStruct< T > &sn, const FluidOptions &opt)
The horizon a transient runs to when the caller gives none.
FluidLayout fluid_layout(const qn::NetworkStruct< T > &sn)
Port of the layout half of solver_fluid_odes.m.
Definition fluid_odes.h:282
std::vector< FluidTranPoint > solver_fluid_transient(const qn::NetworkStruct< T > &sn, const FluidOptions &opt, double t_end, std::size_t points=101, const std::vector< double > &out_grid=std::vector< double >())
Port of @@SolverFLD/getTranAvg: the metrics along the trajectory, not just at the fixed point.
FluidSolution solver_fluid_run_analyzer(const qn::NetworkStruct< T > &sn, const FluidOptions &opt, qn::NetworkStruct< T > *sn_out=nullptr, qn::NetworkStruct< T > *refreshed_out=nullptr, solvers::CacheMetrics< T > *cache_out=nullptr, const qn::NetworkStruct< T > *gate_sn=nullptr)
Port of @@SolverFLD/runAnalyzer.m: resolve the method, route to the function the reference routes to,...
FluidPassage fluid_passage_time(const qn::NetworkStruct< T > &sn, const std::vector< double > &x_steady, std::size_t ist, std::size_t cls, double tol=1e-4, std::size_t points=201, const FluidClosure &closure=FluidClosure())
Response-time CDF at station ist for class cls, both 1-based.
JmtResult< T > solver_jmt_run_analyzer(const qn::NetworkStruct< T > &sn, const JmtOptions &opt_in)
Port of @@SolverJMT/runAnalyzer.m, the jsim and jmva arms.
SchedStrategy
Scheduling disciplines, with the values of MATLAB SchedStrategy.
Definition lang_types.h:194
PrecedenceType
Activity precedence kinds, with the values of MATLAB ActivityPrecedenceType.
Definition lang_types.h:511
LqnElement
LQN element kinds, with the values of MATLAB LayeredNetworkElement.
Definition lang_types.h:505
RoutingStrategy
Routing strategies, with the values of MATLAB RoutingStrategy.
Definition lang_types.h:430
CallType
Call kinds, with the values of MATLAB CallType.
Definition lang_types.h:508
Distrib< T > aph_fit_mean_scv(const T &mean, const T &scv)
APH.fitMeanAndSCV(MEAN, SCV), through mam::aph_fit_mean_scv.
JobClassType
Job class kinds, with the values of MATLAB JobClassType.
Definition lang_types.h:388
std::function< std::vector< T >(const std::vector< T > &)> CdScaling
A class-dependent scaling map, sn.cdscaling.
Definition lang_types.h:794
NodeType
Node kinds, with the values of MATLAB NodeType.
Definition lang_types.h:345
T dist_moment(const Distrib< T > &d, unsigned k)
The k-th raw moment.
LdesResult ldes_engine_solve(const qn::NetworkStruct< T > &sn, const LdesOptions &o)
Simulate sn, over independent REPLICATIONS when options.replications > 1.
void lqn_fwd_rendezvous(LqnStruct< T > &lqn)
Replace every forwarding chain reachable from a synchronous call by caller-side pseudo rendezvous cal...
Definition lqn_helpers.h:77
LnZeroCapacity ln_zero_capacity(const lqn::LqnStruct< T > &lqn)
Port of ln_zero_capacity.m; see the file header.
T lqn_overtake_prob_markov(const LqnStruct< T > &lqn, const std::vector< T > &servt, const std::vector< T > &callresidt, const std::vector< T > &tput, std::size_t eidx, const T &xj)
Overtaking probability at a server entry, through the LQNS phased-server chain rather than the reduce...
LnInterlockChoice ln_interlock_method(const LqnStruct< T > &lqn, const std::string &requested, bool interlocking, const std::string &lnmethod)
Port of matlab/src/solvers/LN/ln_interlock_method.m, asked as a query.
fluid::FluidOptions::RateSched FluidRateSched
One (station, class) rate trajectory injected into a layer's closing ODE.
Definition solver_ln.h:156
bool is_prio(SchedStrategy s)
Definition lqn_focus.h:116
double z(double v)
Definition lqn_focus.h:261
std::string elem(const LqnStruct< T > &lqn, std::size_t idx)
double tot(const std::vector< double > &pops)
std::string fmt(const char *f, double v)
std::string attr(const char *name, const Val &v)
InputError err(const std::string &msg, int line=-1)
Definition srvn_reader.h:97
std::string name(const Element *el, const std::string &key="name")
LqnRefRoutes< T > lqn_ref_routes(const LqnStruct< T > &lqn, const std::vector< std::size_t > &callers, double maxpaths=32.0, const std::vector< std::size_t > &server_set={})
Resolve the reference routes into the layer whose callers are CALLERS.
LqnMolResult< T > lqn_mol(const LqnStruct< T > &lsn, const LqnMolOptions &options=LqnMolOptions())
Method of Layers on the SRVN decomposition of a layered queueing network whose entries carry no activ...
Definition lqn_mol.h:209
LqnBoxBounds< T > lqn_boxbounds(const LqnStruct< T > &lqn)
Evaluate the box bounds of lqn.
std::vector< double > lqn_sustainable_mult(const LqnStruct< T > &l, const std::vector< double > &mult)
Sustainable multiplicity (lsn_max_multiplicity) of every host and task of l under the declared multip...
Definition lqn_reader.h:451
MamSolution< T > mam_dispatch(const qn::NetworkStruct< T > &L, const MamOptions &opt_in)
The ladder.
AphPair< T > aph_convseq(const std::vector< AphPair< T > > &seq)
Convolve the sequence, i.e.
Definition aph_convseq.h:37
AphPair< T > aph_simplify(const AphPair< T > &d1, const AphPair< T > &d2, const T &p1, const T &p2, AphPattern pattern)
Compose two matrix-exponential laws, as aph_simplify.m does.
SetupDelayoffMMk< T > qbd_setupdelayoff_mmk(int k, double N, const T &arv, const T &mu, const T &alpharate, const T &alphascv, const T &betarate, const T &betascv)
Mean number present and throughput of a k-SERVER queue whose servers each pay a setup when woken from...
AphFitResult< T > aph_fit(const T &e1, const T &e2, const T &e3, unsigned nmax, const T &tol)
Fit an APH(n) with n <= nmax to the raw moments e1, e2, e3.
Definition aph_fit.h:176
double var(const std::vector< double > &x)
Sample variance with the n - 1 denominator.
MvaSolution< T > fj_fixed_point(const qn::NetworkStruct< T > &L, FjMmt< T > &tr, std::vector< T > &lam, const MvaOptions &opt, InnerSolve inner, std::string *warning=nullptr)
Drive the fork-join fixed point of a transformed model to convergence.
Definition fj_driver.h:512
FjMmt< T > fj_mmt(const qn::NetworkStruct< T > &L)
Build the transformed layer.
Definition fj_mmt.h:444
bool mva_carries_interlock(const qn::NetworkStruct< T > &L, const MvaOptions &opt)
True when the MVA path this model already dispatches to carries a class-level interlock matrix (Frank...
DispatchResult< T > mva_dispatch(const qn::NetworkStruct< T > &L, const MvaOptions &opt, const Matrix< T > &init_sol)
The ladder itself.
NcSolution< T > solver_nc_solve(const qn::NetworkStruct< T > &L_in, const NcSolverOptions &opt_in)
The gates, the multiserver conversion and the dispatch of @@SolverNC/runAnalyzer.m,...
std::vector< T > expand(const std::vector< T > &v, std::size_t K, const char *name, const T &def)
A scalar broadcast to K entries, or a K-vector left as it is.
SensTable< T > solver_sensitivity_table(qn::NetworkStruct< T > &sn, const SensOptions &opt, bool exact_available, const std::function< mva::MvaSolution< T >()> &solve)
Build the sensitivity table of sn under solve.
void put(Matrix< double > &A, std::size_t r0, std::size_t c0, const Matrix< double > &S)
A(r0:, c0:) = S.
Definition mg1.h:927
double expect(const Vec &r, const std::string &what, const Mat &x, const std::vector< std::vector< std::size_t > > &lv, int K, int Ktop, const Vec &c1, const Vec &c2, double tol)
Definition spn_ispn.h:512
Mat mult(const Mat &A, const Mat &B)
Definition spn_ispn.h:173
SsaSolution solver_ssa(const qn::NetworkStruct< T > &sn, const SsaOptions &opt, std::vector< SsaCacheRatio > *cache=nullptr)
std::vector< Frame > & stack()
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
Matrix< T > expm(const Matrix< T > &A)
Matrix exponential exp(A).
Definition expm.h:141
Port of solver_nc_analyzer.m, solver_ncld_analyzer.m and @@SolverNC/ncDispatch.m: one inner solve,...
Multi-server queue with setup and delayed-off servers.
One SolverLN layer: a NetworkStruct plus the LQN annotations that say which element of the layered mo...
Total service rate of a station served by heterogeneous server pools with a class-compatibility graph...
Post-MMT node visits of a fork-join model.
Port of solver_ctmc_fcr_waitq.m: the reachability-built generator of a model whose finite capacity re...
SolverFluid: the closing method, a port of solver_fluid.m, solver_fluid_iteration....
Port of SolverJMT, the Java Modelling Tools client.
SolverMVA over a SolverLN layer.
The SolverNC class surface: @@SolverNC/runAnalyzer.m and the gates around it.
Performance sensitivities with respect to service rates.
The SolverSSA entry surface: a port of @@SolverSSA/runAnalyzer.m's method whitelist,...
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
The SolverCTMC knobs this port honours.
Where each (station, class) block sits in the state vector.
Definition fluid_odes.h:86
std::vector< std::vector< std::size_t > > qidx
0-based first index of (i,r)
Definition fluid_odes.h:88
std::size_t nstates
length of the state vector
Definition fluid_odes.h:87
std::vector< std::vector< bool > > enabled
whether (i,r) is served at all
Definition fluid_odes.h:90
options.config.rate_sched: explicit per-(station, class) rate trajectories, the third source solver_f...
Controls, defaulting to SolverOptions('Fluid') in the reference.
double tol
absolute and relative tolerance handed to the integrator
What the analyzer returns, in the same shape as the MVA solver's result.
std::vector< double > XN
std::vector< double > xvec
the converged fluid state
std::vector< double > CN
The options of one JMT solve, SolverOptions('JMT') restricted to what is read.
Definition solver_jmt.h:123
The knobs of one LDES run.
static Distrib exp_rate(const T &r)
static Distrib phase_type(const std::vector< T > &alpha, const Matrix< T > &A, bool acyclic)
PH / APH given by (alpha, A): D0 = A and D1 = (-A e) alpha.
static Distrib disabled_dist()
static T ph_moment(const std::vector< T > &alpha, const Matrix< T > &A, unsigned k)
The k-th raw moment of a phase-type (alpha, A): k!
static Distrib immediate()
The point mass at zero.
static Distrib exp_mean(const T &m)
static constexpr double Immediate
Rate of an Immediate distribution; its mean is 1/Immediate = 1e-8.
Definition lang_types.h:829
static constexpr double FineTol
Definition lang_types.h:823
static constexpr double Zero
Definition lang_types.h:825
static constexpr double CoarseTol
Definition lang_types.h:824
Per-layer results of one iteration, the [QN,UN,RN,TN,AN,WN] of getAvg.
Definition solver_ln.h:414
A CDF sampled on a grid, the [F, t] pair MATLAB's evalCDF returns.
Definition solver_ln.h:437
bool empty() const
Definition solver_ln.h:439
std::vector< double > t
Definition solver_ln.h:438
std::vector< double > cdf
Definition solver_ln.h:438
The interlock tracking method a run will use, and why it differs from the request.
LayeredNetwork.layerBlocks: where each layer's block sits in the aggregate.
Definition solver_ln.h:470
std::vector< std::size_t > msz
Definition solver_ln.h:471
std::vector< std::size_t > roff
Definition solver_ln.h:471
std::vector< std::size_t > coff
Definition solver_ln.h:471
std::vector< std::size_t > ksz
Definition solver_ln.h:471
Options of SolverLN.
Definition solver_ln.h:275
ldes::LdesOptions layer_ldes
Options handed to each layer when layer_solver is ldes.
Definition solver_ln.h:337
std::size_t tran_points
Output points per layer trajectory, and the relaxation's own grid size.
Definition solver_ln.h:372
std::vector< double > tran_grid
An EXPLICIT output grid for the layered transient, replacing the uniform tran_points one when it is n...
Definition solver_ln.h:385
std::string relax
Definition solver_ln.h:298
std::string nlp_fork
options.config.nlp_fork: 'refuse' an AND-fork block, or price it at E[max] of exponentials ('exp').
Definition solver_ln.h:399
fluid::FluidOptions layer_fluid
Options handed to each layer when layer_solver is fluid.
Definition solver_ln.h:320
std::string layer_solver
Which solver runs each layer: mva, nc, fluid, ssa, mam, ctmc, ldes (the native in-process LDES engine...
Definition solver_ln.h:318
std::string interlock_method
options.config.interlock_method: how the interlock is TRACKED once interlocking is on.
Definition solver_ln.h:289
int nlp_warm
options.config.nlp_warm: the warm-start sweeps the program's Newton ladder begins from.
Definition solver_ln.h:395
std::size_t mol_iter_max
options.config.mol_iter_max, mol_iter_tol, mol_relax_factor: lqn_mol's own settings for warmstart='mo...
Definition solver_ln.h:407
mva::MvaOptions layer
Options handed to each layer solver; SolverMVA defaults.
Definition solver_ln.h:301
std::string method
options.method, which selects WHAT is reported and not merely how:
Definition solver_ln.h:351
ssa::SsaOptions layer_ssa
Options handed to each layer when layer_solver is ssa.
Definition solver_ln.h:324
std::string ln_transient_channels
options.config.ln_transient_channels: which inter-layer coupling is injected, both,...
Definition solver_ln.h:368
mam::MamOptions layer_mam
Options handed to each layer when layer_solver is mam (SolverMAM's own default method).
Definition solver_ln.h:326
double interlock_maxpaths
options.config.interlock_maxpaths: refpath refuses a layer carrying more routes into it.
Definition solver_ln.h:291
std::string ln_transient
options.config.ln_transient: how the per-layer transients are coupled.
Definition solver_ln.h:358
int nlp_maxiter
options.config.nlp_maxiter: budget of the descent the root-find falls back to.
Definition solver_ln.h:397
nc::NcSolverOptions layer_nc
Options handed to each layer when layer_solver is nc.
Definition solver_ln.h:322
std::string warmstart
options.config.warmstart: empty for a cold start, or 'nlp' / 'mol' to seed a LAYERED method's fixed p...
Definition solver_ln.h:405
std::string interlock_refpath_scope
options.config.interlock_refpath_scope: merging transforms only the layers where two or more callers ...
Definition solver_ln.h:297
ctmc::CtmcOptions layer_ctmc
Options handed to each layer when layer_solver is ctmc, and to a Region layer, which goes to CTMC wha...
Definition solver_ln.h:331
double timespan_end
options.timespan(2): the transient horizon; infinite means none is set.
Definition solver_ln.h:370
long ln_transient_iter_max
options.config.ln_transient_iter_max and ..._tol of the relaxation.
Definition solver_ln.h:360
jmt::JmtOptions layer_jmt
Options handed to each layer when layer_solver is jmt (JSIM); seed as for layer_ldes.
Definition solver_ln.h:339
std::map< std::string, ::line::lqn::NlpLld > lld
options.config.lld: a smooth queue-dependent rate multiplier per station, {processor or task name: ex...
Definition solver_ln.h:391
double nlp_alpha
options.config.nlp_alpha: sharpness of the softmin standing in for min(n, m).
Definition solver_ln.h:393
getSensitivityTable of the ensemble: the layer tables under a Layer column.
Definition solver_ln.h:485
std::vector< std::string > layer_methods
Per layer, the branch that layer took; empty for a layer with no solver.
Definition solver_ln.h:492
std::vector< sens::SensTable< T > > layer_tables
Per layer, the analytic Jacobian where that layer produced one.
Definition solver_ln.h:496
std::vector< Row > rows
Definition solver_ln.h:490
std::string method
The summary label: the common branch, or "mixed" when they differ.
Definition solver_ln.h:494
The LQN-level answer, indexed by element 1..nidx.
Definition solver_ln.h:420
std::vector< T > WN
Definition solver_ln.h:421
std::vector< bool > defined_W
Definition solver_ln.h:422
std::vector< bool > defined_U
Definition solver_ln.h:422
std::string warning
A warning the analysis raised, verbatim, empty when it raised none (method='nlp' off a root).
Definition solver_ln.h:433
std::vector< T > QN
Definition solver_ln.h:421
std::vector< bool > defined_R
Definition solver_ln.h:422
std::vector< T > RN
Definition solver_ln.h:421
std::vector< T > AN
Definition solver_ln.h:421
std::vector< bool > defined_Q
Definition solver_ln.h:422
bool is_bound
True when the numbers are a BOUND (method = mw.upper / mw.lower) rather than the fixed point.
Definition solver_ln.h:431
std::vector< bool > defined_A
Definition solver_ln.h:422
std::vector< T > UN
Definition solver_ln.h:421
std::vector< bool > defined_T
Definition solver_ln.h:422
std::vector< T > TN
Definition solver_ln.h:421
options.config.stochiter_* of SolverOptions.m, with its defaults.
Definition solver_ln.h:515
double a0
Robbins-Monro step immediately after burn-in.
Definition solver_ln.h:517
long conseq
consecutive sub-tolerance iterations required to stop
Definition solver_ln.h:519
long burnin
Picard iterations before the step decay starts.
Definition solver_ln.h:516
double alpha
step decay exponent, in (0.5, 1]
Definition solver_ln.h:518
double relax_burnin
Relaxation in force during burn-in, i.e.
Definition solver_ln.h:522
One layer's block of the layered transient.
Definition solver_ln.h:450
std::vector< std::vector< std::vector< double > > > QN
[station][class][point]
Definition solver_ln.h:453
std::vector< double > t
the output grid, shared by every series below
Definition solver_ln.h:451
std::vector< std::vector< std::vector< double > > > UN
Definition solver_ln.h:453
std::vector< std::vector< std::vector< double > > > TN
Definition solver_ln.h:453
The layered transient: one block per layer, plus how it was produced.
Definition solver_ln.h:476
std::string mode
"coupled" or "decoupled"
Definition solver_ln.h:478
long iterations
waveform-relaxation sweeps; 0 when decoupled
Definition solver_ln.h:479
double gap
final sup-norm trajectory change, coupled only
Definition solver_ln.h:480
std::vector< LnTranLayer > layers
Definition solver_ln.h:477
The structural answer of ln_zero_capacity; see the file header.
std::vector< std::size_t > targets
absolute entry indices, in declaration order
Definition lqn_struct.h:203
std::size_t caller
absolute index of the dispatching activity
Definition lqn_struct.h:201
std::size_t iter_max
Definition lqn_mol.h:92
Options of the program: python export_nlp(lld=, alpha=, fork=).
double alpha
softmin sharpness
std::string fork
'refuse' or 'exp'
std::map< std::string, NlpLld > lld
station name -> multiplier
The options SolverMAM reads.
Definition mam_types.h:30
The options SolverMVA reads.
Definition mva_types.h:32
Class-level results, the [Q,U,R,T,C,X] of the MATLAB analyzers.
Definition mva_types.h:97
std::vector< T > X
Definition mva_types.h:99
std::vector< T > C
Definition mva_types.h:99
Controls, defaulting to SolverOptions('NC') in the reference.
Definition nc_types.h:35
The name-value contract of getSensitivityTable.
std::function< void(std::size_t, std::size_t)> replicate
Replication hook of the tuned simulator central branch: (k, npairs) before a solve of pair k,...
bool simulation
True when the callback is a simulator, which widens the default step.
One (station, class) row of the table.
What the table carries, plus the branch that produced it.
std::vector< SensRow< T > > rows
std::string method
"exact" or "fd", the branch actually taken
Controls, defaulting to SolverOptions('SSA') in the reference.
Definition ssa_types.h:71