LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
fes_solved_tables.h
Go to the documentation of this file.
1/**
2 * @file fes_solved_tables.h
3 * @brief FES rates from a non-product-form solve of the isolated subnetwork.
4 *
5 * Port of the local functions `fes_solved_tables`, `fes_isolated_network` and
6 * `fes_check_copyable` of MATLAB `@ModelAdapter/aggregateFES.m`.
7 *
8 * The subset is rebuilt as a closed network with its original stations (so a
9 * priority or a non-exponential FCFS station keeps the behaviour that breaks
10 * product form) and the stochastic-complement routing, and solved once per
11 * population state by `options.solver`. The rate is reported per unit visit
12 * with the normalisation `fes_build_isolated` applies to the demands (visits
13 * relative to the first subset station), so it is interchangeable with the
14 * 'mva' table and the Norton escape factor applies to it unchanged.
15 *
16 * This header is the DEFINITION of `fes::fes_solved_tables`, declared in
17 * `fes_aggregate.h`. It needs the CTMC analyzer, which is itself a client of
18 * `fes_aggregate.h`; see the include notes there.
19 *
20 * Copyright (c) 2012-2026, Imperial College London
21 * All rights reserved.
22 */
23
24// Its SSA and LDES clients reach `solver_ctmc_waitq.h`, which includes the CTMC
25// analyzer before its own declarations: read from inside that header, this one
26// would see an empty waitq. It is then skipped (its guard left undefined) and
27// `solver_ctmc_waitq.h` includes it from its bottom, once complete; a function
28// template only needs its definition somewhere in the translation unit.
29#if defined(LINE_SOLVERS_CTMC_SOLVER_CTMC_WAITQ_H) && !defined(LINE_SOLVERS_CTMC_SOLVER_CTMC_WAITQ_DONE)
30#elif !defined(LINE_API_FES_FES_SOLVED_TABLES_H)
31#define LINE_API_FES_FES_SOLVED_TABLES_H
32
33#include <cmath>
34#include <cstddef>
35#include <cstdio>
36#include <string>
37#include <vector>
38
49#include "line/util/error.h"
50#include "line/util/matrix.h"
51
52namespace line {
53namespace fes {
54
55namespace detail {
56
57/**
58 * `fes_check_copyable`: refuse a station whose behaviour the isolated rebuild
59 * would not reproduce. Dropping the feature would give the FES the rates of a
60 * different subnetwork, so it is refused by name instead.
61 *
62 * @param ist 1-based station index in `sn`
63 */
64template <class T>
65void fes_check_copyable(const qn::NetworkStruct<T>& sn, std::size_t ist) {
66 const qn::Station<T>& st = sn.stations[ist - 1];
67 const std::size_t K = sn.nclasses;
68 std::string bad;
69 bool par = false;
70 for (std::size_t p : st.server_parallelism) par = par || p > 1;
71 bool feedback = false;
72 for (bool f : st.immfeed) feedback = feedback || f;
73 if (st.sched == lang::SchedStrategy::POLLING) {
74 bad = "polling";
75 } else if (st.svc_rate_fun) {
76 bad = "a pass-and-swap service rate function";
77 } else if (!st.server_types.empty()) {
78 bad = "heterogeneous servers";
79 } else if (par) {
80 bad = "server parallelism";
81 } else if (feedback) {
82 bad = "immediate feedback";
83 } else if (sn.breakdownparam.find(ist) != sn.breakdownparam.end()) {
84 bad = "breakdowns";
85 } else {
86 const auto rit = sn.retrialparam.find(ist);
87 const auto sit = sn.setupparam.find(ist);
88 for (std::size_t k = 0; k < K && bad.empty(); ++k) {
89 const bool patience =
90 (k < st.impatience.size() && st.impatience[k] != lang::ImpatienceType::NONE) ||
91 (k < st.patience.size() && !st.patience[k].disabled);
92 const bool balking =
93 k < st.balking.size() && st.balking[k].strategy != lang::BalkingStrategy::NONE;
94 const bool retrial = rit != sn.retrialparam.end() &&
95 k < rit->second.retrial_proc.size() &&
96 !rit->second.retrial_proc[k].disabled;
97 if (patience || balking || retrial)
98 bad = "impatience, balking or retrial";
99 else if (sit != sn.setupparam.end() && k < sit->second.setup.size() &&
100 !sit->second.setup[k].disabled)
101 bad = "setup times";
102 }
103 }
104 if (!bad.empty())
105 throw UnsupportedError(ErrorKind{"Structure"},
106 "Station " + st.name + " has " + bad +
107 ", which the isolated subnetwork rebuilt for options.solver "
108 "does not carry; aggregate it with a measured "
109 "options.throughputTable instead.");
110}
111
112/**
113 * `fes_isolated_network`: the subset as a closed network holding population
114 * `nvec`. Every class is kept (a class with no job here has population zero),
115 * so class indices, and with them any class- or joint-dependent rate handle,
116 * carry over unchanged.
117 */
118template <class T>
119qn::NetworkStruct<T> fes_isolated_network(const qn::NetworkStruct<T>& sn,
120 const std::vector<std::size_t>& subsetIndices,
121 const std::vector<Matrix<T>>& Pk, const Matrix<T>& visits,
122 const std::vector<int>& nvec) {
123 const std::size_t K = sn.nclasses;
124 const std::size_t M_sub = subsetIndices.size();
125 qn::Network<T> iso(sn.name + "_FESsub");
126 std::vector<std::size_t> nodes(M_sub, 0);
127 for (std::size_t a = 0; a < M_sub; ++a) {
128 const std::size_t ist = subsetIndices[a];
129 fes_check_copyable(sn, ist);
130 const qn::Station<T>& st = sn.stations[ist - 1];
131 if (st.nodetype == lang::NodeType::Delay && st.sched == lang::SchedStrategy::INF) {
132 nodes[a] = iso.add_delay(st.name);
133 } else if (st.nodetype == lang::NodeType::Queue || st.nodetype == lang::NodeType::Delay) {
134 nodes[a] = iso.add_queue(st.name, st.sched);
135 if (!std::isinf(st.nservers)) iso.set_number_of_servers(nodes[a], st.nservers);
136 if (std::isfinite(st.cap)) iso.set_capacity(nodes[a], st.cap);
137 } else {
138 throw UnsupportedError(ErrorKind{"Node"},
139 "Unsupported station type at station " + st.name + ".");
140 }
141 }
142 std::vector<std::size_t> isoClasses(K, 0);
143 for (std::size_t k = 0; k < K; ++k) {
144 // the first station with the largest visit ratio, as MATLAB's max
145 std::size_t ref = 0;
146 for (std::size_t a = 1; a < M_sub; ++a)
147 if (visits(a, k) > visits(ref, k)) ref = a;
148 isoClasses[k] = iso.add_closed_class(sn.classes[k].name, static_cast<double>(nvec[k]),
149 nodes[ref], sn.classes[k].prio);
150 }
151 for (std::size_t a = 0; a < M_sub; ++a) {
152 const std::size_t ist = subsetIndices[a];
153 const qn::Station<T>& st = sn.stations[ist - 1];
154 const bool isDelayNode = st.nodetype == lang::NodeType::Delay && st.sched == lang::SchedStrategy::INF;
155 for (std::size_t k = 0; k < K; ++k) {
156 const bool have = ist - 1 < sn.service.size() && k < sn.service[ist - 1].size();
157 if (!have || sn.service[ist - 1][k].disabled) {
158 iso.set_service(nodes[a], isoClasses[k], lang::Distrib<T>::disabled_dist());
159 continue;
160 }
161 iso.set_service(nodes[a], isoClasses[k], sn.service[ist - 1][k]);
162 // the DPS / GPS weight, or the SEPT / LEPT rank, of a queue
163 if (!isDelayNode && k < st.schedparam.size() &&
164 st.schedparam[k] > num_traits<T>::from_int(0))
165 iso.set_sched_param(nodes[a], isoClasses[k], st.schedparam[k]);
166 }
167 if (!st.lldscaling.empty()) iso.set_limited_load_dependence(nodes[a], st.lldscaling);
168 if (st.cdscaling) iso.set_class_dependence(nodes[a], st.cdscaling, st.cdscalingpeak);
169 if (st.jdscaling) iso.set_joint_dependence(nodes[a], st.jdscaling, st.jdscalingpeak);
170 }
171 qn::RoutingMatrix<T> P = iso.init_routing_matrix();
172 for (std::size_t k = 0; k < K; ++k)
173 for (std::size_t a = 0; a < M_sub; ++a)
174 for (std::size_t b = 0; b < M_sub; ++b)
175 if (Pk[k](a, b) != num_traits<T>::from_int(0))
176 P.set(isoClasses[k], isoClasses[k], nodes[a], nodes[b], Pk[k](a, b));
177 iso.link(P);
178 return iso.get_struct();
179}
180
181/** The (M_sub x K) Q, U and T of one isolated solve, as doubles. */
182struct FesIsoAvg {
183 Matrix<double> Q, U, T;
184};
185
186template <class T>
187Matrix<double> fes_to_double(const Matrix<T>& A) {
188 Matrix<double> B(A.rows(), A.cols(), 0.0);
189 for (std::size_t i = 0; i < A.rows(); ++i)
190 for (std::size_t j = 0; j < A.cols(); ++j) B(i, j) = num_traits<T>::to_double(A(i, j));
191 return B;
192}
193
194template <class T>
195FesIsoAvg fes_solve_isolated(const qn::NetworkStruct<T>& isoSn, const FesOptions& options) {
196 FesIsoAvg r;
197 if (options.solver == "ctmc") {
198 ctmc::CtmcOptions o;
199 o.seed = options.seed;
200 const mva::AvgResult<T> a = ctmc::solver_ctmc_run_analyzer(isoSn, o);
201 r.Q = fes_to_double(a.QN);
202 r.U = fes_to_double(a.UN);
203 r.T = fes_to_double(a.TN);
204 } else if (options.solver == "ssa") {
205 ssa::SsaOptions o;
206 o.seed = static_cast<unsigned long>(options.seed);
207 o.verbose = false;
208 // unqualified: found by argument-dependent lookup at instantiation,
209 // where the SSA dispatcher is complete whatever the include order
210 const ssa::SsaSolution a = solver_ssa(isoSn, o);
211 r.Q = a.QN;
212 r.U = a.UN;
213 r.T = a.TN;
214 } else if (options.solver == "jmt") {
215 jmt::JmtOptions o;
216 o.seed = options.seed;
217 o.verbose = false;
218 const jmt::JmtResult<T> a = jmt::solver_jmt_run_analyzer(isoSn, o);
219 r.Q = fes_to_double(a.avg.QN);
220 r.U = fes_to_double(a.avg.UN);
221 r.T = fes_to_double(a.avg.TN);
222 } else if (options.solver == "ldes") {
223 ldes::LdesOptions o;
224 o.seed = options.seed;
225 const ldes::LdesResult a = ldes::ldes_engine_solve(isoSn, o);
226 r.Q = a.QN;
227 r.U = a.UN;
228 r.T = a.TN;
229 } else {
230 throw InputError(ErrorKind{"Option"},
231 "aggregateFES: options.solver '" + options.solver +
232 "' is not supported: use 'mva', 'ctmc', 'ssa', 'jmt' or 'ldes'.");
233 }
234 return r;
235}
236
237} // namespace detail
238
239template <class T>
241 const std::vector<std::size_t>& subsetIndices,
242 const std::vector<Matrix<T>>& Pk, const Matrix<T>& visits,
243 const std::vector<int>& cutoffs, const FesOptions& options) {
244 const T zero = num_traits<T>::from_int(0);
245 const std::size_t K = cutoffs.size();
246 const std::size_t M_sub = subsetIndices.size();
247 std::size_t tableSize = 1;
248 for (int c : cutoffs) tableSize *= static_cast<std::size_t>(c + 1);
249 // visits relative to the first subset station, as fes_build_isolated
250 // normalises the demands
251 std::vector<double> vnormSum(K, 0.0);
252 for (std::size_t k = 0; k < K; ++k) {
253 const double v1 = num_traits<T>::to_double(visits(0, k));
254 for (std::size_t a = 0; a < M_sub; ++a) {
255 const double v = num_traits<T>::to_double(visits(a, k));
256 vnormSum[k] += v1 > 0.0 ? v / v1 : v;
257 }
258 }
260 out.scalingTable.assign(K, std::vector<T>(tableSize, zero));
261 out.Qtab.assign(tableSize, Matrix<T>(M_sub, K, zero));
262 out.Utab.assign(tableSize, Matrix<T>(M_sub, K, zero));
263 for (std::size_t idx = 0; idx < tableSize; ++idx) {
264 const std::vector<int> nvec = ljd_delinearize(idx + 1, cutoffs);
265 int tot = 0;
266 for (int n : nvec) tot += n;
267 if (tot == 0) continue; // an empty subnetwork holds nothing and serves nothing
268 const qn::NetworkStruct<T> isoSn =
269 detail::fes_isolated_network(sn, subsetIndices, Pk, visits, nvec);
270 const detail::FesIsoAvg a = detail::fes_solve_isolated(isoSn, options);
271 auto fin = [](const Matrix<double>& A, std::size_t i, std::size_t k) {
272 if (i >= A.rows() || k >= A.cols()) return 0.0;
273 return std::isfinite(A(i, k)) ? A(i, k) : 0.0;
274 };
275 std::vector<double> tsum(K, 0.0);
276 for (std::size_t i = 0; i < M_sub; ++i)
277 for (std::size_t k = 0; k < K; ++k) {
278 out.Qtab[idx](i, k) = num_traits<T>::from_double(fin(a.Q, i, k));
279 out.Utab[idx](i, k) = num_traits<T>::from_double(fin(a.U, i, k));
280 tsum[k] += fin(a.T, i, k);
281 }
282 for (std::size_t k = 0; k < K; ++k)
283 if (nvec[k] > 0 && vnormSum[k] > 0.0)
284 out.scalingTable[k][idx] = num_traits<T>::from_double(tsum[k] / vnormSum[k]);
285 if (options.verbose) {
286 std::string ns = "[", xs = "[";
287 for (std::size_t k = 0; k < K; ++k) {
288 char buf[64];
289 std::snprintf(buf, sizeof(buf), "%.4g",
291 ns += (k ? " " : "") + std::to_string(nvec[k]);
292 xs += (k ? " " : "") + std::string(buf);
293 }
294 std::printf("FES %s solve at population %s]: X = %s]\n", options.solver.c_str(),
295 ns.c_str(), xs.c_str());
296 }
297 }
298 return out;
299}
300
301} // namespace fes
302} // namespace line
303
304#endif // LINE_API_FES_FES_SOLVED_TABLES_H (deferred while solver_ctmc_waitq.h is open)
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
UnsupportedError(const std::string &what)
Definition error.h:119
A network plus its refreshed NetworkStruct.
The exception types the port throws.
Flow-equivalent-server aggregation: replace a station subset by one station.
The NATIVE LDES discrete-event engine.
The option and result records of SolverLDES, the discrete-event simulator.
Linearized index of a per-class population vector, for Limited Joint Dependence (LJD) tables.
Dense matrix and non-owning view.
mva::AvgResult< T > solver_ctmc_run_analyzer(const NetworkStruct< T > &sn, const CtmcOptions &opt)
Solve and format in one call, for a caller with no use for the chain.
std::vector< int > ljd_delinearize(std::size_t idx, const std::vector< int > &cutoffs)
Inverse of ljd_linearize: the population vector behind an index.
FesSolvedTables< T > fes_solved_tables(const qn::NetworkStruct< T > &sn, const std::vector< std::size_t > &subsetIndices, const std::vector< Matrix< T > > &Pk, const Matrix< T > &visits, const std::vector< int > &cutoffs, const FesOptions &options)
fes_solved_tables of aggregateFES.m: the FES rates from a solve of the isolated subnetwork by options...
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.
LdesResult ldes_engine_solve(const qn::NetworkStruct< T > &sn, const LdesOptions &o)
Simulate sn, over independent REPLICATIONS when options.replications > 1.
SsaSolution solver_ssa(const qn::NetworkStruct< T > &sn, const SsaOptions &opt, std::vector< SsaCacheRatio > *cache=nullptr)
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
The Network constructor API: Queue, Delay, Source, Sink, Router, ClassSwitch, Cache,...
A queueing network and its refreshed NetworkStruct.
Port of solver_ctmc_analyzer.m and the parts of @@SolverCTMC/runAnalyzer.m that surround one solve: t...
Port of SolverJMT, the Java Modelling Tools client.
The SolverSSA entry surface: a port of @@SolverSSA/runAnalyzer.m's method whitelist,...
Controls, results and the random source of SolverSSA.
options of the reference.
std::string solver
options.solver: how the isolated subnetwork is solved.
What a non-product-form solve of the isolated subnetwork returns: FES rates and conditional metrics.
std::vector< Matrix< T > > Qtab
std::vector< Matrix< T > > Utab
per 0-based state, (M_sub x K)
std::vector< std::vector< T > > scalingTable
per class, linearized on the lattice
static Distrib disabled_dist()