LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
pfqn_oi_mixed.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_API_PFQN_PFQN_OI_MIXED_H
6#define LINE_API_PFQN_PFQN_OI_MIXED_H
7
8/**
9 * @file
10 * @ingroup api_pfqn
11 * Closed-lattice station tables of an order-independent (OI) station visited by
12 * CLOSED and OPEN classes, with the open classes summed out exactly.
13 *
14 * Templated port of matlab/src/api/pfqn/pfqn_oi_mixed.m. Class r is closed when
15 * N(r) is finite and open when N(r) = Inf. For each closed count vector c
16 * (0 <= c <= N on the closed classes) the routine returns
17 *
18 * W(c) = sum_o Phi(c, o) * prod_r lambda_r^{n_r},
19 * H_r(c) = sum_o n_r Phi(c, o) * prod_r lambda_r^{n_r},
20 * S_r(c) = sum_o Xi_r(c, o) * prod_r lambda_r^{n_r},
21 *
22 * where o runs over ALL open count vectors, n = (c, o), Phi is the OI balance
23 * function (pfqn_ncoi) and Xi_r its in-service weight (pfqn_oi_insvc). LAMBDA is
24 * the visit ratio of a closed class and the offered traffic lambda_r * V_ir of
25 * an open class. W is the station's factor in the closed-chain convolution of a
26 * MIXED product-form network (OI queues are quasi-reversible, Berezner, Kriel,
27 * Krzesinski 1995); H and S give the per-class mean and in-service weights. With
28 * no closed class the lattice is the single point c = 0 and E[n_r] = H_r/W,
29 * E[sir_r] = S_r/W are the open station's means (pfqn_oi_open).
30 *
31 * SATURATION RECURSION. With tau_r the per-class cutoffs of the OPEN classes,
32 * mu(c, o) = mu(c, min(o, tau)) for every closed c <= N, the open coordinates
33 * collapse into macrostates (m_r = tau_r stands for every o_r >= tau_r) while
34 * the closed coordinates stay exact. With den(m) = mu(m) - sum_{r open, m_r =
35 * tau_r} lambda_r,
36 *
37 * G(m) den(m) = sum_{r: m_r>0} lambda_r G(m - e_r)
38 * H_j(m) den(m) = sum_{r: m_r>0} lambda_r H_j(m - e_r)
39 * + lambda_j 1{m_j>0} (1{j open, m_j = tau_j} G(m) + G(m - e_j))
40 * S_j(m) den(m) = sum_{r: m_r>0} lambda_r S_j(m - e_r)
41 * + lambda_j 1{m_j>0} 1{mu(m) > mu(m - e_j)} G(m - e_j)
42 *
43 * and W, H, S are the sums of G, H, S over the open macrostates at each c. A
44 * reachable macrostate with den(m) <= 0 makes its open series diverge: the
45 * station is unstable (stable = false). With every cutoff 1 and no closed class
46 * this is the Bonald-Comte-Mathieu (2017) class-subset recursion.
47 *
48 * NON-SATURATING RATES. When the open coordinates do not saturate within
49 * `taumax`, the rate is frozen at a uniform open cutoff T and T is doubled until
50 * the tables move by less than `tol` (relative); `method` is then "oi.trunc",
51 * and the run fails by name past `maxstates` macrostates.
52 *
53 * UNSTABLE STATION. The reference fills W, H and S with Inf; this port leaves
54 * them at zero and reports stable = false, because infinity has no
55 * representation under exact arithmetic. Every caller tests `stable` first.
56 *
57 * ARITHMETIC. The recursion is additions, multiplications and divisions, so it
58 * runs in any field; the saturation and convergence tests are tolerance tests
59 * and are taken in double, as the reference takes them.
60 */
61
62#include <algorithm>
63#include <cmath>
64#include <cstddef>
65#include <functional>
66#include <limits>
67#include <sstream>
68#include <string>
69#include <vector>
70
71#include "line/num/number.h"
72#include "line/util/error.h"
73#include "line/util/matrix.h"
74
75namespace line {
76namespace pfqn {
77
78/** The tuning fields of pfqn_oi_mixed / pfqn_oi_open (OPTIONS in the reference). */
80 double tol = 1e-8; ///< relative tolerance of the 'oi.trunc' branch
81 int taumax = 64; ///< per-class cutoff search limit
82 double maxstates = 2e6; ///< macrostate budget of the cutoff search and 'oi.trunc'
83};
84
85/** Return value of pfqn_oi_mixed, mirroring [W, H, S, stable, tau, method]. */
86template <class T>
88 std::vector<T> W; ///< (prod(Nc+1)) column-major table over the closed lattice
89 Matrix<T> H; ///< (prod(Nc+1) x R) per-class mean weights
90 Matrix<T> S; ///< (prod(Nc+1) x R) per-class in-service weights
91 bool stable = true; ///< false when some reachable macrostate has den(m) <= 0
92 std::vector<int> tau; ///< (R) open cutoffs used (0 for closed and idle classes)
93 std::string method = "oi"; ///< "oi" (exact) or "oi.trunc"
94};
95
96namespace detail {
97
98/** The per-class count vector of a 0-based linear index over `dims` (column-major). */
99inline std::vector<int> oi_mixed_sub(std::size_t li, const std::vector<std::size_t>& dims) {
100 std::vector<int> m(dims.size(), 0);
101 for (std::size_t j = 0; j < dims.size(); ++j) {
102 m[j] = static_cast<int>(li % dims[j]);
103 li /= dims[j];
104 }
105 return m;
106}
107
108/** prod(dims) in double, so an oversize box is detected before it overflows. */
109inline double oi_mixed_box(const std::vector<std::size_t>& dims) {
110 double p = 1.0;
111 for (std::size_t d : dims) p *= static_cast<double>(d);
112 return p;
113}
114
115/**
116 * The cutoff search, as `oi_cutoffs`: smallest open cutoffs tau with
117 * f(m + e_r) == f(m) whenever m_r = tau_r, over the box (open 0..tau, closed
118 * 0..cap). Closed classes are never searched. `bounded` is false when a cutoff
119 * would exceed `taumax` or the box `maxstates`; tau is then the last admissible
120 * value.
121 */
122template <class T>
123std::vector<int> oi_mixed_cutoffs(const std::function<T(const std::vector<int>&)>& fAt,
124 const std::vector<bool>& openA, const std::vector<int>& capA,
125 int taumax, double maxstates, bool& bounded) {
126 const std::size_t K = openA.size();
127 const double tolr = 1e-9;
128 std::vector<int> tau(K, 0);
129 bool any_open = false;
130 for (std::size_t j = 0; j < K; ++j)
131 if (openA[j]) {
132 tau[j] = 1;
133 any_open = true;
134 }
135 bounded = true;
136 const auto box_of = [&](const std::vector<int>& t) {
137 double p = 1.0;
138 for (std::size_t j = 0; j < K; ++j)
139 p *= openA[j] ? static_cast<double>(t[j] + 1) : static_cast<double>(capA[j] + 1);
140 return p;
141 };
142 bool changed = any_open;
143 while (changed) {
144 changed = false;
145 for (std::size_t r = 0; r < K; ++r) {
146 if (!openA[r]) continue;
147 std::vector<std::size_t> lim(K, 1);
148 for (std::size_t j = 0; j < K; ++j)
149 lim[j] = openA[j] ? static_cast<std::size_t>(tau[j] + 1)
150 : static_cast<std::size_t>(capA[j] + 1);
151 lim[r] = 1;
152 std::size_t total = 1;
153 for (std::size_t j = 0; j < K; ++j) total *= lim[j];
154 bool sat = true;
155 for (std::size_t li = 0; li < total && sat; ++li) {
156 std::vector<int> m(K, 0);
157 std::size_t rem = li;
158 for (std::size_t j = 0; j < K; ++j) {
159 if (j == r) {
160 m[j] = tau[r];
161 } else {
162 m[j] = static_cast<int>(rem % lim[j]);
163 rem /= lim[j];
164 }
165 }
166 std::vector<int> mp = m;
167 ++mp[r];
168 const double a = num_traits<T>::to_double(fAt(m));
169 const double b = num_traits<T>::to_double(fAt(mp));
170 if (std::fabs(b - a) > tolr * std::max(1.0, std::fabs(a))) sat = false;
171 }
172 if (!sat) {
173 ++tau[r];
174 changed = true;
175 if (tau[r] > taumax || box_of(tau) > maxstates) {
176 bounded = false;
177 --tau[r];
178 return tau;
179 }
180 }
181 }
182 }
183 return tau;
184}
185
186/** Macro tables of the saturation recursion over one box, as `oi_macro`. */
187template <class T>
188struct OiMacroTables {
189 std::vector<T> G;
190 Matrix<T> H, S;
191 bool stable = true;
192};
193
194/**
195 * The saturation recursion over the box (open 0..tau, closed 0..cap), as
196 * `oi_macro`. States are visited in increasing total count; within one total
197 * the order is the column-major one, as MATLAB's stable sort leaves it.
198 */
199template <class T>
200OiMacroTables<T> oi_mixed_macro(const std::vector<T>& lam,
201 const std::function<T(const std::vector<int>&)>& mu,
202 const std::vector<int>& tau, const std::vector<bool>& openA,
203 const std::vector<int>& capA) {
204 const T zero = num_traits<T>::from_int(0);
205 const std::size_t R = lam.size();
206 std::vector<std::size_t> dims(R), strides(R, 1);
207 for (std::size_t r = 0; r < R; ++r)
208 dims[r] = openA[r] ? static_cast<std::size_t>(tau[r] + 1)
209 : static_cast<std::size_t>(capA[r] + 1);
210 for (std::size_t r = 1; r < R; ++r) strides[r] = strides[r - 1] * dims[r - 1];
211 std::size_t ngrid = 1;
212 for (std::size_t d : dims) ngrid *= d;
213 std::vector<std::vector<int>> counts(ngrid);
214 std::vector<int> tot(ngrid, 0);
215 for (std::size_t k = 0; k < ngrid; ++k) {
216 counts[k] = oi_mixed_sub(k, dims);
217 for (int v : counts[k]) tot[k] += v;
218 }
219 std::vector<std::size_t> ord(ngrid);
220 for (std::size_t k = 0; k < ngrid; ++k) ord[k] = k;
221 std::stable_sort(ord.begin(), ord.end(),
222 [&tot](std::size_t a, std::size_t b) { return tot[a] < tot[b]; });
223
224 OiMacroTables<T> out;
225 out.G.assign(ngrid, zero);
226 out.H = Matrix<T>(ngrid, R, zero);
227 out.S = Matrix<T>(ngrid, R, zero);
228 std::vector<T> muv(ngrid, zero);
229 out.G[0] = num_traits<T>::from_int(1);
230 for (std::size_t kk = 1; kk < ngrid; ++kk) {
231 const std::size_t k = ord[kk];
232 const std::vector<int>& m = counts[k];
233 muv[k] = mu(m);
234 std::vector<bool> satm(R, false);
235 T lamsat = zero;
236 T numG = zero;
237 for (std::size_t r = 0; r < R; ++r) {
238 if (m[r] <= 0) continue;
239 satm[r] = openA[r] && (m[r] == tau[r]);
240 if (satm[r]) lamsat += lam[r];
241 numG += T(lam[r] * out.G[k - strides[r]]);
242 }
243 const T den = T(muv[k] - lamsat);
244 if (!(numG > zero)) continue; // unreachable macrostate (all predecessors weightless)
245 const double dden = num_traits<T>::to_double(den);
246 if (dden <= 0.0 || !std::isfinite(dden)) {
247 bool anysat = false;
248 for (std::size_t r = 0; r < R; ++r)
249 if (satm[r]) anysat = true;
250 if (anysat) {
251 out.stable = false; // an open series diverges
252 return out;
253 }
254 continue; // zero rate at a finite closed state: weightless
255 }
256 out.G[k] = T(numG / den);
257 const double dmuk = num_traits<T>::to_double(muv[k]);
258 for (std::size_t j = 0; j < R; ++j) {
259 T hj = zero, sj = zero;
260 for (std::size_t r = 0; r < R; ++r) {
261 if (m[r] <= 0) continue;
262 hj += T(lam[r] * out.H(k - strides[r], j));
263 sj += T(lam[r] * out.S(k - strides[r], j));
264 }
265 if (m[j] > 0) {
266 const std::size_t kj = k - strides[j];
267 if (satm[j]) hj += T(lam[j] * out.G[k]);
268 hj += T(lam[j] * out.G[kj]);
269 if (dmuk - num_traits<T>::to_double(muv[kj]) > 1e-12 * std::max(1.0, std::fabs(dmuk)))
270 sj += T(lam[j] * out.G[kj]);
271 }
272 out.H(k, j) = T(hj / den);
273 out.S(k, j) = T(sj / den);
274 }
275 }
276 return out;
277}
278
279/**
280 * Sum the macro tables over the open coordinates, indexed by the closed counts in
281 * the closed-lattice order of the caller, as `oi_marginalize`.
282 */
283template <class T>
284void oi_mixed_marginalize(const OiMacroTables<T>& mt, const std::vector<int>& tau,
285 const std::vector<bool>& openA, const std::vector<int>& capA,
286 const std::vector<std::size_t>& act,
287 const std::vector<std::size_t>& closedIdx,
288 const std::vector<std::size_t>& dimsC, std::size_t R,
289 OiMixedResult<T>& res) {
290 const T zero = num_traits<T>::from_int(0);
291 const std::size_t Ra = tau.size();
292 std::vector<std::size_t> dims(Ra);
293 for (std::size_t a = 0; a < Ra; ++a)
294 dims[a] = openA[a] ? static_cast<std::size_t>(tau[a] + 1)
295 : static_cast<std::size_t>(capA[a] + 1);
296 std::size_t ngrid = 1;
297 for (std::size_t d : dims) ngrid *= d;
298 std::size_t ncl = 1;
299 for (std::size_t d : dimsC) ncl *= d;
300 std::vector<std::size_t> stridesC(dimsC.size(), 1);
301 for (std::size_t a = 1; a < dimsC.size(); ++a) stridesC[a] = stridesC[a - 1] * dimsC[a - 1];
302 res.W.assign(ncl, zero);
303 res.H = Matrix<T>(ncl, R, zero);
304 res.S = Matrix<T>(ncl, R, zero);
305 std::vector<std::size_t> posC(Ra, 0);
306 for (std::size_t a = 0; a < Ra; ++a)
307 if (!openA[a])
308 for (std::size_t q = 0; q < closedIdx.size(); ++q)
309 if (closedIdx[q] == act[a]) posC[a] = q;
310 for (std::size_t k = 0; k < ngrid; ++k) {
311 bool any = !(mt.G[k] == zero);
312 for (std::size_t a = 0; a < Ra && !any; ++a)
313 if (!(mt.H(k, a) == zero) || !(mt.S(k, a) == zero)) any = true;
314 if (!any) continue;
315 std::size_t li = k, lc = 0;
316 for (std::size_t a = 0; a < Ra; ++a) {
317 const std::size_t ma = li % dims[a];
318 li /= dims[a];
319 if (!openA[a]) lc += ma * stridesC[posC[a]];
320 }
321 res.W[lc] += mt.G[k];
322 for (std::size_t a = 0; a < Ra; ++a) {
323 res.H(lc, act[a]) += mt.H(k, a);
324 res.S(lc, act[a]) += mt.S(k, a);
325 }
326 }
327}
328
329} // namespace detail
330
331/**
332 * @brief Closed-lattice station tables of an OI station with open classes summed out.
333 *
334 * @param lambda (R) closed visit ratios / open offered traffic (>= 0)
335 * @param N (R) closed populations, +Inf for an open class
336 * @param mu total service rate mu(n) on the per-class count vector (R)
337 * @param opt tol, taumax, maxstates
338 */
339template <class T>
340OiMixedResult<T> pfqn_oi_mixed(const std::vector<T>& lambda, const std::vector<double>& N,
341 const std::function<T(const std::vector<int>&)>& mu,
342 const OiMixedOptions& opt = OiMixedOptions()) {
343 if (!mu)
344 throw InputError(ErrorKind{"Argument"},
345 "pfqn_oi_mixed: mu must be a function mu(n) on the per-class count vector.");
346 const std::size_t R = lambda.size();
347 if (N.size() != R)
348 throw InputError(ErrorKind{"Argument"},
349 "pfqn_oi_mixed: lambda and N must have the same number of classes.");
350 for (std::size_t r = 0; r < R; ++r) {
351 const double l = num_traits<T>::to_double(lambda[r]);
352 if (!std::isfinite(l) || l < 0.0)
353 throw InputError(ErrorKind{"Argument"},
354 "pfqn_oi_mixed: lambda must be finite and nonnegative.");
355 }
356 const T zero = num_traits<T>::from_int(0);
357 std::vector<bool> isOpen(R, false);
358 std::vector<int> Nc(R, 0);
359 std::vector<std::size_t> closedIdx, dimsC;
360 for (std::size_t r = 0; r < R; ++r) {
361 isOpen[r] = std::isinf(N[r]);
362 if (!isOpen[r]) {
363 Nc[r] = static_cast<int>(std::llround(N[r]));
364 closedIdx.push_back(r);
365 dimsC.push_back(static_cast<std::size_t>(Nc[r]) + 1);
366 }
367 }
368 std::size_t ncl = 1;
369 for (std::size_t d : dimsC) ncl *= d;
370
371 // classes that ever hold a job: closed with N>0 and lambda>0, open with lambda>0
372 std::vector<std::size_t> act;
373 for (std::size_t r = 0; r < R; ++r)
374 if (lambda[r] > zero && (isOpen[r] || Nc[r] > 0)) act.push_back(r);
375
377 res.W.assign(ncl, zero);
378 res.H = Matrix<T>(ncl, R, zero);
379 res.S = Matrix<T>(ncl, R, zero);
380 res.tau.assign(R, 0);
381 if (act.empty()) {
382 res.W[0] = num_traits<T>::from_int(1); // only the empty station is reachable
383 return res;
384 }
385 const std::size_t Ra = act.size();
386 std::vector<T> lamA(Ra);
387 std::vector<bool> openA(Ra);
388 std::vector<int> capA(Ra);
389 for (std::size_t a = 0; a < Ra; ++a) {
390 lamA[a] = lambda[act[a]];
391 openA[a] = isOpen[act[a]];
392 capA[a] = Nc[act[a]];
393 }
394 // the rate on the active coordinates, sanitized: a non-finite or negative
395 // rate reads as zero, the reference's `oi_rate_san`
396 const std::function<T(const std::vector<int>&)> muA = [mu, act, R](const std::vector<int>& na) {
397 std::vector<int> n(R, 0);
398 for (std::size_t a = 0; a < act.size(); ++a) n[act[a]] = na[a];
399 const T v = mu(n);
400 const double d = num_traits<T>::to_double(v);
401 if (!std::isfinite(d) || d < 0.0) return num_traits<T>::from_int(0);
402 return v;
403 };
404
405 bool bounded = true;
406 std::vector<int> tauA = detail::oi_mixed_cutoffs<T>(muA, openA, capA, opt.taumax,
407 opt.maxstates, bounded);
408 if (!bounded) {
409 res.method = "oi.trunc";
410 int Tc = 2;
411 for (std::size_t a = 0; a < Ra; ++a)
412 if (openA[a]) Tc = std::max(Tc, tauA[a]);
413 bool havePrev = false;
414 std::vector<T> prevW;
415 Matrix<T> prevH;
416 std::vector<int> tauT;
417 while (true) {
418 tauT = tauA;
419 std::vector<std::size_t> dimsT(Ra);
420 for (std::size_t a = 0; a < Ra; ++a) {
421 if (openA[a]) tauT[a] = Tc;
422 dimsT[a] = openA[a] ? static_cast<std::size_t>(Tc + 1)
423 : static_cast<std::size_t>(capA[a] + 1);
424 }
425 if (detail::oi_mixed_box(dimsT) > opt.maxstates) {
426 std::ostringstream os;
427 os << "pfqn_oi_mixed: the order-independent rate does not saturate in the open "
428 "classes and the truncated macrostate box (cutoff "
429 << Tc << ") exceeds maxstates = " << opt.maxstates
430 << " before the tables settled to tol = " << opt.tol
431 << "; give the station a saturating rate.";
432 throw NumericError(ErrorKind{"NonConvergence"}, os.str());
433 }
434 const std::vector<int> tauF = tauT;
435 const std::vector<bool> openF = openA;
436 const std::function<T(const std::vector<int>&)> muT =
437 [muA, tauF, openF](const std::vector<int>& na) {
438 std::vector<int> n = na;
439 for (std::size_t a = 0; a < n.size(); ++a)
440 if (openF[a]) n[a] = std::min(n[a], tauF[a]);
441 return muA(n);
442 };
443 const detail::OiMacroTables<T> mt = detail::oi_mixed_macro<T>(lamA, muT, tauT, openA, capA);
444 res.stable = mt.stable;
445 if (mt.stable) {
447 detail::oi_mixed_marginalize<T>(mt, tauT, openA, capA, act, closedIdx, dimsC, R, cur);
448 if (havePrev) {
449 double dW = 0.0, dH = 0.0;
450 for (std::size_t i = 0; i < ncl; ++i) {
451 const double wn = num_traits<T>::to_double(cur.W[i]);
452 const double wp = num_traits<T>::to_double(prevW[i]);
453 dW = std::max(dW, std::fabs(wn - wp) / std::max(std::fabs(wn), 1e-300));
454 for (std::size_t r = 0; r < R; ++r) {
455 const double hn = num_traits<T>::to_double(cur.H(i, r));
456 const double hp = num_traits<T>::to_double(prevH(i, r));
457 dH = std::max(dH, std::fabs(hn - hp) / std::max(std::fabs(hn), 1e-300));
458 }
459 }
460 if (dW < opt.tol && dH < opt.tol) {
461 res.W = cur.W;
462 res.H = cur.H;
463 res.S = cur.S;
464 break;
465 }
466 }
467 prevW = cur.W;
468 prevH = cur.H;
469 havePrev = true;
470 }
471 Tc *= 2;
472 }
473 tauA = tauT;
474 } else {
475 const detail::OiMacroTables<T> mt = detail::oi_mixed_macro<T>(lamA, muA, tauA, openA, capA);
476 res.stable = mt.stable;
477 if (mt.stable) detail::oi_mixed_marginalize<T>(mt, tauA, openA, capA, act, closedIdx, dimsC, R, res);
478 }
479 if (!res.stable) {
480 res.W.assign(ncl, zero);
481 res.H = Matrix<T>(ncl, R, zero);
482 res.S = Matrix<T>(ncl, R, zero);
483 }
484 for (std::size_t a = 0; a < Ra; ++a)
485 if (openA[a]) res.tau[act[a]] = tauA[a];
486 return res;
487}
488
489} // namespace pfqn
490} // namespace line
491
492#endif // LINE_API_PFQN_PFQN_OI_MIXED_H
InputError(const std::string &what)
Definition error.h:105
NumericError(const std::string &what)
Definition error.h:112
The exception types the port throws.
Dense matrix and non-owning view.
double tot(const std::vector< double > &pops)
OiMixedResult< T > pfqn_oi_mixed(const std::vector< T > &lambda, const std::vector< double > &N, const std::function< T(const std::vector< int > &)> &mu, const OiMixedOptions &opt=OiMixedOptions())
Closed-lattice station tables of an OI station with open classes summed out.
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
Number-type abstraction for the templated API port.
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
The tuning fields of pfqn_oi_mixed / pfqn_oi_open (OPTIONS in the reference).
double maxstates
macrostate budget of the cutoff search and 'oi.trunc'
int taumax
per-class cutoff search limit
double tol
relative tolerance of the 'oi.trunc' branch
Return value of pfqn_oi_mixed, mirroring [W, H, S, stable, tau, method].
std::vector< int > tau
(R) open cutoffs used (0 for closed and idle classes)
Matrix< T > S
(prod(Nc+1) x R) per-class in-service weights
std::vector< T > W
(prod(Nc+1)) column-major table over the closed lattice
std::string method
"oi" (exact) or "oi.trunc"
bool stable
false when some reachable macrostate has den(m) <= 0
Matrix< T > H
(prod(Nc+1) x R) per-class mean weights