LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
qsys_bmapphnn_retrial.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_QSYS_QSYS_BMAPPHNN_RETRIAL_H
6#define LINE_API_QSYS_QSYS_BMAPPHNN_RETRIAL_H
7
8/**
9 * @file
10 * @ingroup api_qsys
11 * The BMAP/PH/N/N bufferless retrial queue with flexible retrial admission
12 * control.
13 *
14 * Templated port of matlab/src/api/qsys/qsys_bmapphnn_retrial.m, which
15 * implements Dudin et al., "Analysis of BMAP/PH/N-Type Queueing System with
16 * Flexible Retrials Admission Control", Mathematics 2025, 13(9), 1434.
17 *
18 * THE MODEL. N servers and no waiting room. Arrivals come in batches from a
19 * BMAP (D0, D1, ..., DK) on V states; a batch that finds fewer than its size
20 * free servers fills what it can and the excess either joins the orbit, with
21 * probability 1 - p, or is lost, with probability p. Service is PH (beta, S)
22 * on M phases, so the server-side state with n busy servers is the multiset of
23 * their phases, of which there are T_n = C(n+M-1, M-1); the level of the
24 * generator is the orbit population and each level carries V * sum_n T_n
25 * states. Each orbiting customer retries at rate alpha and abandons at rate
26 * gamma, and a retrial SUCCEEDS only while n <= R(nu), which is the admission
27 * control: above the threshold the retrial finds the system closed and the
28 * customer stays in orbit.
29 *
30 * THE STATE SPACE IS A LEVEL-DEPENDENT QBD and the reference does not solve it
31 * as one: it truncates the orbit at a finite level, assembles the whole
32 * generator densely, and solves pi Q = 0 with the last column replaced by the
33 * normalization. This port does the same, so that the two agree, including on
34 * the truncation. See the two reference defects below, which are both about
35 * that truncation.
36 *
37 * WHAT THE PORT CHANGES, AND WHY IT DOES NOT CHANGE THE ANSWER. The reference
38 * rebuilds B, B_bar, Gamma and B_tilde inside buildGeneratorLevel, i.e. once
39 * per (i, j) block pair, although none of them depends on i or j; on the
40 * default truncation that is over a hundred rebuilds of the same matrices.
41 * They are hoisted here. The generator entries are identical.
42 *
43 * REFERENCE DEFECTS in qsys_bmapphnn_retrial.m:
44 *
45 * 1. AN UNSTABLE ORBIT CAN RETURN A FINITE, PLAUSIBLE-LOOKING ANSWER. The
46 * truncated chain is always positive recurrent and pi is renormalized, so
47 * divergence appears as a number. With R = 0 a retrial succeeds only when
48 * the system is empty, so the orbit is unstable even at rho = 2/3:
49 * qsys_bmapphnn_retrial({-2,2}, 1, -1, 3, 0.5, 0, 0, 0, 'MaxLevel', L)
50 * gives L_orbit 94.5, 194.0, ..., 1593.5 for L = 100, 200, ..., 1600, with
51 * the top-level mass stuck near 0.18. A fixed MaxLevel never warns; the
52 * adaptive default below fails to converge, so the reference warns and the
53 * port reports converged = false.
54 * 2. THE STARTING TRUNCATION LEVEL IGNORES EVERY ORBIT PARAMETER:
55 * max(100, ceil(50/(1 - min(rho, 0.99)))) with rho = lambda b1 / N depends
56 * on neither alpha nor gamma nor the blocking probability. With
57 * alpha = 0.02 it is 150, and MaxLevel 100 gives L_orbit 57.5935191 against
58 * the converged 57.73566168. The reference and this port therefore double
59 * the level until the relative orbit-truncation error (truncError, the
60 * top-level mass times the level over the mean orbit length) falls under
61 * TailTolerance, or the next generator would exceed MaxDim. A fixed maxLevel
62 * disables the refinement. The port also returns topLevelMass as a direct
63 * diagnostic, and supports RetrialPolicy.CONSTANT and the MaxBlockSize cap.
64 *
65 * 3. THE DOCUMENTED MEANING OF R DOES NOT MATCH THE CODE. The header of the
66 * .m file says "When n > R(nu), arriving customers go to orbit", but R
67 * enters the generator only through computeGamma and computeBbar, both of
68 * which act on RETRIALS from the orbit. A fresh arrival always takes a
69 * free server if there is one, whatever R is. The code is consistent with
70 * the paper's "flexible retrials admission control"; the docstring is not.
71 *
72 * 4. computeC's first branch builds a (T_n x 1) zero column, a shape that
73 * cannot be a valid block, and the caller silently discards it through a
74 * size test (size(C_nk, 2) == T(N+1)). It also assigns the same zero
75 * matrix twice under an if that cannot change it. Harmless, and the port
76 * simply does not create the malformed shape.
77 *
78 * ARITHMETIC. Nothing here needs a transcendental function: the generator is a
79 * rational expression in the inputs and the solution is one linear solve, so
80 * the header is instantiable at T = Rational and the exact instantiation
81 * returns the stationary law of the TRUNCATED chain exactly. That is worth
82 * having for a small truncation, where it makes the generator itself
83 * checkable, and impractical for the default one, where the dense solve is
84 * hundreds of dimensions wide.
85 */
86
87#include <cmath>
88#include <cstddef>
89#include <limits>
90#include <string>
91#include <vector>
92
95#include "line/num/number.h"
96#include "line/util/error.h"
97#include "line/util/linalg.h"
98#include "line/util/lu.h"
99#include "line/util/matrix.h"
100
101namespace line {
102namespace qsys {
103
104// RetrialPolicy lives in qsys_retrial_policy.h, shared with the M/G/1/1 and
105// stability retrial functions.
106
107/** Options of qsys_bmapphnn_retrial (the name-value pairs of the .m file). */
109 /**
110 * Fixed orbit truncation level ('MaxLevel'); 0 selects the reference's
111 * adaptive choice, which doubles the level until the mass retained at the
112 * top level contributes less than tailTolerance of the mean orbit length.
113 */
114 std::size_t maxLevel = 0;
115 /** 'RetrialPolicy'. */
117 /** 'Tolerance' (parsed by the reference and, like there, not consumed). */
118 double tolerance = 1e-10;
119 /** 'TailTolerance': relative orbit-truncation error target. */
120 double tailTolerance = 1e-6;
121 /** 'MaxDim': cap on the total generator dimension of the refinement. */
122 double maxDim = 2e5;
123 /** 'MaxBlockSize': cap on the per-level block size V*d; exceeding it is an error. */
124 double maxBlockSize = 5000;
125};
126
127/** Result of qsys_bmapphnn_retrial. */
128template <class T>
130 T L_orbit; ///< mean number of customers in orbit
131 T N_server; ///< mean number of busy servers
132 T L_system; ///< L_orbit + N_server
133 T utilization; ///< N_server / N
134 T throughput; ///< N_server / b1
135 T P_idle; ///< probability that every server is idle
136 T P_empty_orbit; ///< probability that the orbit is empty
137 T P_empty_system; ///< probability that the system is empty
138 Matrix<T> pi; ///< stationary law, (truncLevel + 1) x (V d)
139 std::size_t truncLevel; ///< truncation level used
140 T truncError; ///< relative orbit-truncation error estimate at truncLevel
141 T topLevelMass; ///< mass at the highest retained level; see defect 2
142 bool clipped; ///< a negative probability had to be clipped to zero
143 /**
144 * The adaptive refinement reached tailTolerance (always true for a fixed
145 * maxLevel). False stands for the reference's line_warning that the orbit
146 * measures are underestimated at the dimension cap maxDim.
147 */
149};
150
151namespace detail {
152
153/**
154 * Weak compositions of n into M parts in the reference's reverse
155 * lexicographic order (generateCompositions in the .m file). The order matters:
156 * it fixes the index of every server-phase multiset.
157 */
158inline std::vector<std::vector<int>> retrial_compositions(int n, int M) {
159 std::vector<std::vector<int>> out;
160 if (M <= 0) return out;
161 if (M == 1) {
162 out.push_back(std::vector<int>(1, n));
163 return out;
164 }
165 for (int m1 = n; m1 >= 0; --m1) {
166 const std::vector<std::vector<int>> sub = retrial_compositions(n - m1, M - 1);
167 for (std::size_t s = 0; s < sub.size(); ++s) {
168 std::vector<int> row;
169 row.reserve(static_cast<std::size_t>(M));
170 row.push_back(m1);
171 row.insert(row.end(), sub[s].begin(), sub[s].end());
172 out.push_back(row);
173 }
174 }
175 return out;
176}
177
178/** Index of a composition in the reverse-lexicographic list, or -1. */
179inline int retrial_find(const std::vector<std::vector<int>>& comps, const std::vector<int>& key) {
180 for (std::size_t j = 0; j < comps.size(); ++j)
181 if (comps[j] == key) return static_cast<int>(j);
182 return -1;
183}
184
185/** Everything the block builders need, assembled once. */
186template <class T>
187struct RetrialCtx {
188 std::vector<Matrix<T>> D; ///< D0 ... DK
189 std::vector<T> beta;
190 Matrix<T> S;
191 std::vector<T> S0;
192 int M = 0, N = 0, V = 0, K = 0;
193 std::size_t d = 0;
194 std::vector<std::size_t> Tn; ///< T_n, n = 0..N
195 std::vector<long> R; ///< admission threshold per BMAP state
196 T alpha, gamma, p;
197 std::vector<std::vector<std::vector<int>>> comps; ///< comps[n]
198};
199
200/** Starting index of the states with n busy servers, 0-based. */
201template <class T>
202std::size_t retrial_offset(const RetrialCtx<T>& c, int n) {
203 std::size_t off = 0;
204 for (int i = 0; i < n; ++i) off += c.Tn[static_cast<std::size_t>(i)];
205 return off;
206}
207
208/** L_n: service completions, T_n x T_{n-1}. */
209template <class T>
210Matrix<T> retrial_L(const RetrialCtx<T>& c, int n) {
211 const T zero = num_traits<T>::from_int(0);
212 if (n == 0) return Matrix<T>();
213 Matrix<T> L(c.Tn[static_cast<std::size_t>(n)], c.Tn[static_cast<std::size_t>(n - 1)], zero);
214 const std::vector<std::vector<int>>& cn = c.comps[static_cast<std::size_t>(n)];
215 const std::vector<std::vector<int>>& cm = c.comps[static_cast<std::size_t>(n - 1)];
216 for (std::size_t i = 0; i < cn.size(); ++i)
217 for (int l = 0; l < c.M; ++l) {
218 if (cn[i][static_cast<std::size_t>(l)] <= 0) continue;
219 std::vector<int> mp = cn[i];
220 --mp[static_cast<std::size_t>(l)];
221 const int j = retrial_find(cm, mp);
222 if (j >= 0)
223 L(i, static_cast<std::size_t>(j)) +=
224 num_traits<T>::from_int(cn[i][static_cast<std::size_t>(l)]) *
225 c.S0[static_cast<std::size_t>(l)];
226 }
227 return L;
228}
229
230/** A_n: service phase changes, T_n x T_n. */
231template <class T>
232Matrix<T> retrial_A(const RetrialCtx<T>& c, int n) {
233 const T zero = num_traits<T>::from_int(0);
234 if (n == 0) return Matrix<T>(1, 1, zero);
235 Matrix<T> A(c.Tn[static_cast<std::size_t>(n)], c.Tn[static_cast<std::size_t>(n)], zero);
236 const std::vector<std::vector<int>>& cn = c.comps[static_cast<std::size_t>(n)];
237 for (std::size_t i = 0; i < cn.size(); ++i)
238 for (int l = 0; l < c.M; ++l) {
239 if (cn[i][static_cast<std::size_t>(l)] <= 0) continue;
240 for (int lp = 0; lp < c.M; ++lp) {
241 if (lp == l) continue;
242 if (!(c.S(static_cast<std::size_t>(l), static_cast<std::size_t>(lp)) > zero))
243 continue;
244 std::vector<int> mp = cn[i];
245 --mp[static_cast<std::size_t>(l)];
246 ++mp[static_cast<std::size_t>(lp)];
247 const int j = retrial_find(cn, mp);
248 if (j >= 0)
249 A(i, static_cast<std::size_t>(j)) +=
250 num_traits<T>::from_int(cn[i][static_cast<std::size_t>(l)]) *
251 c.S(static_cast<std::size_t>(l), static_cast<std::size_t>(lp));
252 }
253 }
254 return A;
255}
256
257/** P_n: a new customer enters service, T_n x T_{n+1}. */
258template <class T>
259Matrix<T> retrial_P(const RetrialCtx<T>& c, int n) {
260 const T zero = num_traits<T>::from_int(0);
261 if (n >= c.N) return Matrix<T>();
262 Matrix<T> P(c.Tn[static_cast<std::size_t>(n)], c.Tn[static_cast<std::size_t>(n + 1)], zero);
263 const std::vector<std::vector<int>>& cn = c.comps[static_cast<std::size_t>(n)];
264 const std::vector<std::vector<int>>& cp = c.comps[static_cast<std::size_t>(n + 1)];
265 for (std::size_t i = 0; i < cn.size(); ++i)
266 for (int l = 0; l < c.M; ++l) {
267 if (!(c.beta[static_cast<std::size_t>(l)] > zero)) continue;
268 std::vector<int> mp = cn[i];
269 ++mp[static_cast<std::size_t>(l)];
270 const int j = retrial_find(cp, mp);
271 if (j >= 0)
272 P(i, static_cast<std::size_t>(j)) += c.beta[static_cast<std::size_t>(l)];
273 }
274 return P;
275}
276
277/** Delta_n: total exit rate of each server-phase multiset, diagonal T_n. */
278template <class T>
279Matrix<T> retrial_Delta(const RetrialCtx<T>& c, int n) {
280 const T zero = num_traits<T>::from_int(0);
281 if (n == 0) return Matrix<T>(1, 1, zero);
282 Matrix<T> D(c.Tn[static_cast<std::size_t>(n)], c.Tn[static_cast<std::size_t>(n)], zero);
283 const std::vector<std::vector<int>>& cn = c.comps[static_cast<std::size_t>(n)];
284 for (std::size_t i = 0; i < cn.size(); ++i) {
285 T total = zero;
286 for (int l = 0; l < c.M; ++l)
287 total += num_traits<T>::from_int(cn[i][static_cast<std::size_t>(l)]) *
288 T(-c.S(static_cast<std::size_t>(l), static_cast<std::size_t>(l)));
289 D(i, i) = total;
290 }
291 return D;
292}
293
294/** Gamma^(nu): the indicator of n > R(nu), diagonal d. */
295template <class T>
296Matrix<T> retrial_Gamma(const RetrialCtx<T>& c, int nu) {
297 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
298 Matrix<T> G(c.d, c.d, zero);
299 std::size_t off = 0;
300 for (int n = 0; n <= c.N; ++n) {
301 const std::size_t width = c.Tn[static_cast<std::size_t>(n)];
302 if (static_cast<long>(n) > c.R[static_cast<std::size_t>(nu)])
303 for (std::size_t t = 0; t < width; ++t) G(off + t, off + t) = one;
304 off += width;
305 }
306 return G;
307}
308
309/** The scalar of G_{n,n}^{(nu,nu')}: batch losses when the batch cannot fit. */
310template <class T>
311T retrial_G_scalar(const RetrialCtx<T>& c, int n, int nu, int nuPrime) {
312 const T zero = num_traits<T>::from_int(0);
313 if (n <= c.N - c.K) return zero;
314 T total = zero;
315 for (int k = c.N - n + 1; k <= c.K; ++k)
316 if (k >= 1)
317 total += c.D[static_cast<std::size_t>(k)](static_cast<std::size_t>(nu),
318 static_cast<std::size_t>(nuPrime));
319 return T(c.p * total);
320}
321
322/**
323 * The product P_n P_{n+1} ... P_{n+k-1}, which places k arriving customers
324 * into service starting from n busy servers.
325 */
326template <class T>
327Matrix<T> retrial_Pprod(const RetrialCtx<T>& c, const std::vector<Matrix<T>>& P, int n, int upto) {
328 Matrix<T> prod = eye<T>(c.Tn[static_cast<std::size_t>(n)]);
329 for (int j = n; j < upto; ++j)
330 if (j < c.N) prod = matmul(prod, P[static_cast<std::size_t>(j)]);
331 return prod;
332}
333
334/** B^(nu): the within-level block for a BMAP state that does not change. */
335template <class T>
336Matrix<T> retrial_B(const RetrialCtx<T>& c, const std::vector<Matrix<T>>& L,
337 const std::vector<Matrix<T>>& A, const std::vector<Matrix<T>>& P,
338 const std::vector<Matrix<T>>& Delta, int nu) {
339 const T zero = num_traits<T>::from_int(0);
340 Matrix<T> B(c.d, c.d, zero);
341 for (int n = 0; n <= c.N; ++n) {
342 const std::size_t rs = retrial_offset(c, n);
343 const std::size_t w = c.Tn[static_cast<std::size_t>(n)];
344 const T g = retrial_G_scalar(c, n, nu, nu);
345 if (n == 0) {
346 B(rs, rs) = g;
347 } else {
348 for (std::size_t a = 0; a < w; ++a)
349 for (std::size_t b = 0; b < w; ++b)
350 B(rs + a, rs + b) = A[static_cast<std::size_t>(n)](a, b) +
351 Delta[static_cast<std::size_t>(n)](a, b) +
352 (a == b ? g : zero);
353 }
354 if (n >= 1) {
355 const std::size_t cs = retrial_offset(c, n - 1);
356 for (std::size_t a = 0; a < w; ++a)
357 for (std::size_t b = 0; b < c.Tn[static_cast<std::size_t>(n - 1)]; ++b)
358 B(rs + a, cs + b) = L[static_cast<std::size_t>(n)](a, b);
359 }
360 for (int k = 1; k <= c.K; ++k) {
361 if (n + k > c.N) continue;
362 const std::size_t cs = retrial_offset(c, n + k);
363 const T dk = c.D[static_cast<std::size_t>(k)](static_cast<std::size_t>(nu),
364 static_cast<std::size_t>(nu));
365 const Matrix<T> pp = retrial_Pprod(c, P, n, n + k);
366 for (std::size_t a = 0; a < w; ++a)
367 for (std::size_t b = 0; b < c.Tn[static_cast<std::size_t>(n + k)]; ++b)
368 B(rs + a, cs + b) = dk * pp(a, b);
369 }
370 }
371 return B;
372}
373
374/** B_bar^(nu): a successful retrial, valid only while n <= R(nu). */
375template <class T>
376Matrix<T> retrial_Bbar(const RetrialCtx<T>& c, const std::vector<Matrix<T>>& P, int nu) {
377 const T zero = num_traits<T>::from_int(0);
378 Matrix<T> B(c.d, c.d, zero);
379 const long cap = c.R[static_cast<std::size_t>(nu)] < static_cast<long>(c.N - 1)
380 ? c.R[static_cast<std::size_t>(nu)]
381 : static_cast<long>(c.N - 1);
382 for (long n = 0; n <= cap; ++n) {
383 const std::size_t rs = retrial_offset(c, static_cast<int>(n));
384 const std::size_t cs = retrial_offset(c, static_cast<int>(n) + 1);
385 const Matrix<T>& Pn = P[static_cast<std::size_t>(n)];
386 for (std::size_t a = 0; a < Pn.rows(); ++a)
387 for (std::size_t b = 0; b < Pn.cols(); ++b) B(rs + a, cs + b) = Pn(a, b);
388 }
389 return B;
390}
391
392/** B_tilde^(nu,nu'): the within-level block when the BMAP state changes. */
393template <class T>
394Matrix<T> retrial_Btilde(const RetrialCtx<T>& c, const std::vector<Matrix<T>>& P, int nu,
395 int nuPrime) {
396 const T zero = num_traits<T>::from_int(0);
397 Matrix<T> B(c.d, c.d, zero);
398 for (int n = 0; n <= c.N; ++n) {
399 const std::size_t rs = retrial_offset(c, n);
400 const std::size_t w = c.Tn[static_cast<std::size_t>(n)];
401 const T g = retrial_G_scalar(c, n, nu, nuPrime);
402 for (std::size_t a = 0; a < w; ++a) B(rs + a, rs + a) = g;
403 for (int k = 1; k <= c.K; ++k) {
404 if (n + k > c.N) continue;
405 const std::size_t cs = retrial_offset(c, n + k);
406 const T dk = c.D[static_cast<std::size_t>(k)](static_cast<std::size_t>(nu),
407 static_cast<std::size_t>(nuPrime));
408 const Matrix<T> pp = retrial_Pprod(c, P, n, n + k);
409 for (std::size_t a = 0; a < w; ++a)
410 for (std::size_t b = 0; b < c.Tn[static_cast<std::size_t>(n + k)]; ++b)
411 B(rs + a, cs + b) = dk * pp(a, b);
412 }
413 }
414 return B;
415}
416
417/**
418 * C_{n,k}^(nu,nu'): a batch that overflows the free servers sends k customers
419 * to the orbit and leaves all N servers busy. Returns an empty matrix when the
420 * block does not exist, in place of the reference's malformed zero column.
421 */
422template <class T>
423Matrix<T> retrial_C(const RetrialCtx<T>& c, const std::vector<Matrix<T>>& P, int n, int k, int nu,
424 int nuPrime) {
425 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
426 if (n < c.N - c.K + k) return Matrix<T>();
427 if (n < c.N) {
428 const int batch = c.N - n + k;
429 if (batch < 1 || batch > c.K) return Matrix<T>();
430 const T db = c.D[static_cast<std::size_t>(batch)](static_cast<std::size_t>(nu),
431 static_cast<std::size_t>(nuPrime));
432 Matrix<T> pp = retrial_Pprod(c, P, n, c.N);
433 for (std::size_t a = 0; a < pp.rows(); ++a)
434 for (std::size_t b = 0; b < pp.cols(); ++b) pp(a, b) = T(one - c.p) * db * pp(a, b);
435 return pp;
436 }
437 if (k < 1 || k > c.K) return Matrix<T>();
438 const T dk = c.D[static_cast<std::size_t>(k)](static_cast<std::size_t>(nu),
439 static_cast<std::size_t>(nuPrime));
440 Matrix<T> out(c.Tn[static_cast<std::size_t>(c.N)], c.Tn[static_cast<std::size_t>(c.N)], zero);
441 for (std::size_t a = 0; a < out.rows(); ++a) out(a, a) = T(one - c.p) * dk;
442 return out;
443}
444
445} // namespace detail
446
447/**
448 * The BMAP/PH/N/N bufferless retrial queue.
449 *
450 * @param D the BMAP as {D0, D1, ..., DK}, each V x V
451 * @param beta PH service entry vector, length M
452 * @param S PH service sub-generator, M x M
453 * @param N number of servers, which is also the capacity
454 * @param alpha retrial rate per orbiting customer
455 * @param gamma abandonment rate per orbiting customer
456 * @param p probability that an overflowing batch is lost rather than
457 * joining the orbit
458 * @param R admission threshold per BMAP state; a single entry is broadcast
459 * @param opt truncation level
460 */
461template <class T>
463 const std::vector<T>& beta, const Matrix<T>& S,
464 int N, const T& alpha, const T& gamma, const T& p,
465 const std::vector<long>& R,
467 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
468 if (D.size() < 2) throw InputError("qsys_bmapphnn_retrial: the BMAP needs D0 and at least D1");
469 if (N < 1) throw InputError("qsys_bmapphnn_retrial: at least one server is required");
470 const int V = static_cast<int>(D[0].rows());
471 if (V < 1) throw InputError("qsys_bmapphnn_retrial: empty BMAP");
472 for (std::size_t k = 0; k < D.size(); ++k)
473 if (D[k].rows() != static_cast<std::size_t>(V) || D[k].cols() != static_cast<std::size_t>(V))
474 throw InputError("qsys_bmapphnn_retrial: every BMAP matrix must be V x V");
475 const int M = static_cast<int>(S.rows());
476 if (M < 1 || S.cols() != static_cast<std::size_t>(M) ||
477 beta.size() != static_cast<std::size_t>(M))
478 throw InputError("qsys_bmapphnn_retrial: the PH service is malformed");
479 if (R.empty()) throw InputError("qsys_bmapphnn_retrial: no admission threshold given");
480
481 // validateRetrialInputs: reject anything that is not a well-formed BMAP/PH
482 // pair before any large allocation, as the reference does.
483 {
484 const double fineTol = lang::GlobalConstants::FineTol;
485 const double sqrtFineTol = std::sqrt(fineTol);
486 Matrix<T> DsumV(static_cast<std::size_t>(V), static_cast<std::size_t>(V), zero);
487 for (std::size_t k = 0; k < D.size(); ++k)
488 for (std::size_t i = 0; i < D[k].rows(); ++i)
489 for (std::size_t j = 0; j < D[k].cols(); ++j) {
490 const double v = num_traits<T>::to_double(D[k](i, j));
491 if (!std::isfinite(v))
492 throw InputError("qsys_bmapphnn_retrial: BMAP matrix D{" +
493 std::to_string(k + 1) +
494 "} contains NaN or Inf entries. The arrival process is "
495 "disabled or not phase-type representable.");
496 if (k >= 1 && v < -fineTol)
497 throw InputError("qsys_bmapphnn_retrial: BMAP arrival matrix D{" +
498 std::to_string(k + 1) + "} must be non-negative.");
499 DsumV(i, j) += D[k](i, j);
500 }
501 for (std::size_t i = 0; i < D[0].rows(); ++i) {
502 if (num_traits<T>::to_double(D[0](i, i)) > fineTol)
503 throw InputError("qsys_bmapphnn_retrial: BMAP matrix D0 must have non-positive "
504 "diagonal entries.");
505 T rs = zero;
506 for (std::size_t j = 0; j < DsumV.cols(); ++j) rs += DsumV(i, j);
507 if (std::fabs(num_traits<T>::to_double(rs)) > sqrtFineTol)
508 throw InputError("qsys_bmapphnn_retrial: BMAP matrices are inconsistent: sum_k D_k "
509 "must have zero row sums.");
510 }
511 T betaSum = zero;
512 for (std::size_t i = 0; i < beta.size(); ++i) {
513 const double v = num_traits<T>::to_double(beta[i]);
514 if (!std::isfinite(v))
515 throw InputError("qsys_bmapphnn_retrial: Phase-type service vector beta is empty or "
516 "contains NaN/Inf. The service distribution is disabled or not "
517 "phase-type representable.");
518 if (v < -fineTol)
519 throw InputError("qsys_bmapphnn_retrial: Phase-type service vector beta must be "
520 "non-negative and sum to one.");
521 betaSum += beta[i];
522 }
523 if (std::fabs(num_traits<T>::to_double(betaSum) - 1.0) > sqrtFineTol)
524 throw InputError("qsys_bmapphnn_retrial: Phase-type service vector beta must be "
525 "non-negative and sum to one.");
526 for (std::size_t i = 0; i < S.rows(); ++i) {
527 T rs = zero;
528 for (std::size_t j = 0; j < S.cols(); ++j) {
529 if (!std::isfinite(num_traits<T>::to_double(S(i, j))))
530 throw InputError("qsys_bmapphnn_retrial: Phase-type service subgenerator S "
531 "contains NaN or Inf entries. The service distribution is "
532 "disabled or not phase-type representable.");
533 rs += S(i, j);
534 }
535 if (!(S(i, i) < zero))
536 throw InputError("qsys_bmapphnn_retrial: Phase-type service subgenerator S must "
537 "have strictly negative diagonal entries.");
538 if (num_traits<T>::to_double(T(-rs)) < -fineTol)
539 throw InputError("qsys_bmapphnn_retrial: Phase-type service subgenerator S must "
540 "have non-negative exit rates.");
541 }
542 const double ad = num_traits<T>::to_double(alpha), gd = num_traits<T>::to_double(gamma),
544 if (!std::isfinite(ad) || ad < 0.0)
545 throw InputError("qsys_bmapphnn_retrial: Retrial rate alpha must be a finite "
546 "non-negative scalar.");
547 if (!std::isfinite(gd) || gd < 0.0)
548 throw InputError("qsys_bmapphnn_retrial: Orbit impatience rate gamma must be a finite "
549 "non-negative scalar.");
550 if (!std::isfinite(pd) || pd < 0.0 || pd > 1.0)
551 throw InputError("qsys_bmapphnn_retrial: Batch rejection probability p must lie in "
552 "[0,1].");
553 for (std::size_t i = 0; i < R.size(); ++i)
554 if (R[i] < 0 || R[i] > static_cast<long>(N))
555 throw InputError("qsys_bmapphnn_retrial: Admission threshold R must lie in [0," +
556 std::to_string(N) + "].");
557 }
558
559 detail::RetrialCtx<T> c;
560 c.D = D;
561 c.beta = beta;
562 c.S = S;
563 c.M = M;
564 c.N = N;
565 c.V = V;
566 c.K = static_cast<int>(D.size()) - 1;
567 c.alpha = alpha;
568 c.gamma = gamma;
569 c.p = p;
570 c.R.assign(static_cast<std::size_t>(V), R[0]);
571 if (R.size() > 1) {
572 if (R.size() != static_cast<std::size_t>(V))
573 throw InputError("qsys_bmapphnn_retrial: R must be a scalar or one entry per BMAP "
574 "state");
575 c.R = R;
576 }
577
578 // S0 = -S e, the absorption rates
579 c.S0.assign(static_cast<std::size_t>(M), zero);
580 for (int i = 0; i < M; ++i) {
581 T s = zero;
582 for (int j = 0; j < M; ++j)
583 s += S(static_cast<std::size_t>(i), static_cast<std::size_t>(j));
584 c.S0[static_cast<std::size_t>(i)] = -s;
585 }
586
587 // T_n = C(n + M - 1, M - 1), and the compositions that index those states
588 c.Tn.assign(static_cast<std::size_t>(N) + 1, 0);
589 c.comps.resize(static_cast<std::size_t>(N) + 1);
590 c.d = 0;
591 for (int n = 0; n <= N; ++n) {
592 c.comps[static_cast<std::size_t>(n)] = detail::retrial_compositions(n, M);
593 c.Tn[static_cast<std::size_t>(n)] = c.comps[static_cast<std::size_t>(n)].size();
594 c.d += c.Tn[static_cast<std::size_t>(n)];
595 }
596
597 // mean arrival rate and mean service time, for rho and the throughput
598 Matrix<T> Dsum(static_cast<std::size_t>(V), static_cast<std::size_t>(V), zero);
599 Matrix<T> DkSum(static_cast<std::size_t>(V), static_cast<std::size_t>(V), zero);
600 for (std::size_t k = 0; k < D.size(); ++k)
601 for (std::size_t i = 0; i < Dsum.rows(); ++i)
602 for (std::size_t j = 0; j < Dsum.cols(); ++j) {
603 Dsum(i, j) += D[k](i, j);
604 if (k >= 1)
605 DkSum(i, j) += num_traits<T>::from_int(static_cast<long>(k)) * D[k](i, j);
606 }
607 // theta Dsum = 0, sum theta = 1, by replacing the last equation
608 Matrix<T> A = Dsum.transpose();
609 for (std::size_t j = 0; j < A.cols(); ++j) A(A.rows() - 1, j) = one;
610 std::vector<T> rhs(A.rows(), zero);
611 rhs[A.rows() - 1] = one;
612 const std::vector<T> theta = solve(A, rhs);
613 T lambda = zero;
614 for (std::size_t i = 0; i < theta.size(); ++i)
615 for (std::size_t j = 0; j < DkSum.cols(); ++j) lambda += theta[i] * DkSum(i, j);
616
617 Matrix<T> negS = S;
618 for (std::size_t i = 0; i < negS.rows(); ++i)
619 for (std::size_t j = 0; j < negS.cols(); ++j) negS(i, j) = -negS(i, j);
620 const std::vector<T> tau = mulvec(inverse(negS), ones<T>(static_cast<std::size_t>(M)));
621 T b1 = zero;
622 for (int i = 0; i < M; ++i) b1 += beta[static_cast<std::size_t>(i)] * tau[static_cast<std::size_t>(i)];
623 if (!(b1 > zero)) throw InputError("qsys_bmapphnn_retrial: the mean service time must be positive");
624
625 const std::size_t Vd = static_cast<std::size_t>(V) * c.d;
626
627 // A level block of size Vd is dense and is built once per level, so an
628 // oversized block must be rejected rather than attempted ('MaxBlockSize').
629 if (static_cast<double>(Vd) > opt.maxBlockSize)
630 throw InputError("qsys_bmapphnn_retrial: Per-level block size V*d = " + std::to_string(Vd) +
631 " exceeds MaxBlockSize = " +
632 std::to_string(static_cast<long long>(std::llround(opt.maxBlockSize))) +
633 ". The service distribution has " + std::to_string(M) +
634 " phases and the station has " + std::to_string(N) +
635 " servers, which yields " + std::to_string(c.d) +
636 " service configurations. Reduce the phase-type order (e.g. fit the "
637 "service distribution with fewer phases), reduce the number of servers, "
638 "or raise maxBlockSize if the memory cost is acceptable.");
639
640 // Blocks that do not depend on the level, built once (the reference
641 // rebuilds them per block pair).
642 std::vector<Matrix<T>> L(static_cast<std::size_t>(N) + 1), Am(static_cast<std::size_t>(N) + 1),
643 P(static_cast<std::size_t>(N) + 1), Delta(static_cast<std::size_t>(N) + 1);
644 for (int n = 0; n <= N; ++n) {
645 L[static_cast<std::size_t>(n)] = detail::retrial_L(c, n);
646 Am[static_cast<std::size_t>(n)] = detail::retrial_A(c, n);
647 P[static_cast<std::size_t>(n)] = detail::retrial_P(c, n);
648 Delta[static_cast<std::size_t>(n)] = detail::retrial_Delta(c, n);
649 }
650 std::vector<Matrix<T>> B(static_cast<std::size_t>(V)), Bbar(static_cast<std::size_t>(V)),
651 Gam(static_cast<std::size_t>(V));
652 for (int nu = 0; nu < V; ++nu) {
653 B[static_cast<std::size_t>(nu)] = detail::retrial_B(c, L, Am, P, Delta, nu);
654 Bbar[static_cast<std::size_t>(nu)] = detail::retrial_Bbar(c, P, nu);
655 Gam[static_cast<std::size_t>(nu)] = detail::retrial_Gamma(c, nu);
656 }
657 std::vector<std::vector<Matrix<T>>> Btilde(
658 static_cast<std::size_t>(V), std::vector<Matrix<T>>(static_cast<std::size_t>(V)));
659 for (int nu = 0; nu < V; ++nu)
660 for (int nup = 0; nup < V; ++nup)
661 if (nu != nup) Btilde[static_cast<std::size_t>(nu)][static_cast<std::size_t>(nup)] =
662 detail::retrial_Btilde(c, P, nu, nup);
663
664 bool clipped = false;
665
666 // solveAtLevel: build the level-truncated generator and solve pi Q = 0,
667 // pi e = 1; returns pi reshaped to (truncLevel + 1) x Vd. The impatience
668 // terms scale with the orbit size i; the retrial terms with the policy
669 // weight: i under LINEAR, one whenever the orbit is non-empty under CONSTANT.
670 auto solveAtLevel = [&](std::size_t truncLevel) -> Matrix<T> {
671 const std::size_t total = (truncLevel + 1) * Vd;
672 Matrix<T> Q(total, total, zero);
673
674 for (std::size_t i = 0; i <= truncLevel; ++i) {
675 const T iT = num_traits<T>::from_int(static_cast<long>(i));
676 const T wT = opt.retrialPolicy == RetrialPolicy::CONSTANT ? (i >= 1 ? one : zero) : iT;
677 // diagonal block
678 for (int nu = 0; nu < V; ++nu) {
679 const std::size_t rs = i * Vd + static_cast<std::size_t>(nu) * c.d;
680 for (int nup = 0; nup < V; ++nup) {
681 const std::size_t cs = i * Vd + static_cast<std::size_t>(nup) * c.d;
682 const T d0 = D[0](static_cast<std::size_t>(nu), static_cast<std::size_t>(nup));
683 if (nu == nup) {
684 for (std::size_t a = 0; a < c.d; ++a)
685 for (std::size_t b = 0; b < c.d; ++b) {
686 T v = B[static_cast<std::size_t>(nu)](a, b) +
687 wT * alpha * Gam[static_cast<std::size_t>(nu)](a, b);
688 if (a == b) v += d0 - iT * gamma - wT * alpha;
689 Q(rs + a, cs + b) = v;
690 }
691 } else {
692 const Matrix<T>& bt =
693 Btilde[static_cast<std::size_t>(nu)][static_cast<std::size_t>(nup)];
694 for (std::size_t a = 0; a < c.d; ++a)
695 for (std::size_t b = 0; b < c.d; ++b)
696 Q(rs + a, cs + b) = bt(a, b) + (a == b ? d0 : zero);
697 }
698 }
699 }
700 // subdiagonal block: abandonment and successful retrials
701 if (i >= 1) {
702 for (int nu = 0; nu < V; ++nu) {
703 const std::size_t rs = i * Vd + static_cast<std::size_t>(nu) * c.d;
704 const std::size_t cs = (i - 1) * Vd + static_cast<std::size_t>(nu) * c.d;
705 for (std::size_t a = 0; a < c.d; ++a)
706 for (std::size_t b = 0; b < c.d; ++b) {
707 T v = wT * alpha * Bbar[static_cast<std::size_t>(nu)](a, b);
708 if (a == b) v += iT * gamma;
709 Q(rs + a, cs + b) = v;
710 }
711 }
712 }
713 // superdiagonal blocks: batches that overflow into the orbit
714 for (int k = 1; k <= c.K; ++k) {
715 const std::size_t j = i + static_cast<std::size_t>(k);
716 if (j > truncLevel) break;
717 for (int nu = 0; nu < V; ++nu) {
718 const std::size_t rs = i * Vd + static_cast<std::size_t>(nu) * c.d;
719 for (int nup = 0; nup < V; ++nup) {
720 const std::size_t cs = j * Vd + static_cast<std::size_t>(nup) * c.d;
721 const std::size_t ncol = detail::retrial_offset(c, N);
722 for (int n = 0; n <= N; ++n) {
723 const Matrix<T> Cnk = detail::retrial_C(c, P, n, k, nu, nup);
724 if (Cnk.rows() == 0) continue;
725 if (Cnk.cols() != c.Tn[static_cast<std::size_t>(N)]) continue;
726 const std::size_t nrow = detail::retrial_offset(c, n);
727 for (std::size_t a = 0; a < Cnk.rows(); ++a)
728 for (std::size_t b = 0; b < Cnk.cols(); ++b)
729 Q(rs + nrow + a, cs + ncol + b) += Cnk(a, b);
730 }
731 }
732 }
733 }
734 }
735
736 // conservative diagonal, as the reference does after assembly
737 for (std::size_t i = 0; i < total; ++i) {
738 T s = zero;
739 for (std::size_t j = 0; j < total; ++j) s += Q(i, j);
740 Q(i, i) = Q(i, i) - s;
741 }
742
743 // pi Q = 0 with the last column carrying the normalization
744 for (std::size_t i = 0; i < total; ++i) Q(i, total - 1) = one;
745 Matrix<T> QT = Q.transpose();
746 std::vector<T> rhs2(total, zero);
747 rhs2[total - 1] = one;
748 std::vector<T> pi = solve(QT, rhs2);
749
750 // Handle numerical issues: the reference warns below -1e-8, clips every
751 // negative entry and renormalizes.
752 const T warnTol = num_traits<T>::from_double(-1e-8);
753 T mass = zero;
754 for (std::size_t i = 0; i < total; ++i) {
755 if (pi[i] < warnTol) clipped = true;
756 if (pi[i] < zero) pi[i] = zero;
757 mass += pi[i];
758 }
759 if (!(mass > zero)) throw NumericError(ErrorKind{"Degenerate"}, "qsys_bmapphnn_retrial: the solution has no mass");
760 Matrix<T> pim(truncLevel + 1, Vd);
761 for (std::size_t i = 0; i <= truncLevel; ++i)
762 for (std::size_t j = 0; j < Vd; ++j) pim(i, j) = pi[i * Vd + j] / mass;
763 return pim;
764 };
765
766 // orbitTruncationError: relative contribution the truncated tail would add
767 // to the mean orbit length, bounded by the mass sitting at the top level.
768 auto orbitTruncationError = [&](const Matrix<T>& pim, std::size_t truncLevel) -> T {
769 T lorbit = zero, top = zero;
770 for (std::size_t i = 0; i <= truncLevel; ++i) {
771 T lv = zero;
772 for (std::size_t j = 0; j < Vd; ++j) lv += pim(i, j);
773 lorbit += num_traits<T>::from_int(static_cast<long>(i)) * lv;
774 if (i == truncLevel) top = lv;
775 }
776 const T realmin = num_traits<T>::from_double(std::numeric_limits<double>::min());
777 const T denom = lorbit > realmin ? lorbit : realmin;
778 return T(num_traits<T>::from_int(static_cast<long>(truncLevel)) * top / denom);
779 };
780
781 // Truncation level: fixed when given, else the reference's starting formula
782 // followed by the doubling refinement against tailTolerance under maxDim.
783 std::size_t truncLevel = opt.maxLevel;
784 Matrix<T> pim;
785 T truncError = zero;
786 bool converged = true;
787 if (truncLevel > 0) {
788 pim = solveAtLevel(truncLevel);
789 truncError = orbitTruncationError(pim, truncLevel);
790 } else {
791 const double rho = num_traits<T>::to_double(T(lambda * b1)) / static_cast<double>(N);
792 const double capped = rho < 0.99 ? rho : 0.99;
793 const double lv = std::ceil(50.0 / (1.0 - capped));
794 truncLevel = lv > 100.0 ? static_cast<std::size_t>(lv) : static_cast<std::size_t>(100);
795 converged = false;
796 while (true) {
797 pim = solveAtLevel(truncLevel);
798 truncError = orbitTruncationError(pim, truncLevel);
799 if (num_traits<T>::to_double(truncError) <= opt.tailTolerance) {
800 converged = true;
801 break;
802 }
803 const std::size_t nextLevel = 2 * truncLevel;
804 if (static_cast<double>(nextLevel + 1) * static_cast<double>(Vd) > opt.maxDim) break;
805 truncLevel = nextLevel;
806 }
807 // !converged stands for the reference's line_warning: orbit measures
808 // are underestimated; raise maxDim or set maxLevel explicitly.
809 }
810
812 r.clipped = clipped;
813 r.converged = converged;
814 r.pi = pim;
815
816 r.L_orbit = zero;
817 for (std::size_t i = 1; i <= truncLevel; ++i) {
818 T lv = zero;
819 for (std::size_t j = 0; j < Vd; ++j) lv += r.pi(i, j);
820 r.L_orbit += num_traits<T>::from_int(static_cast<long>(i)) * lv;
821 }
822 r.N_server = zero;
823 r.P_idle = zero;
824 for (std::size_t i = 0; i <= truncLevel; ++i)
825 for (int nu = 0; nu < V; ++nu) {
826 const std::size_t base = static_cast<std::size_t>(nu) * c.d;
827 for (int n = 0; n <= N; ++n) {
828 const std::size_t off = base + detail::retrial_offset(c, n);
829 for (std::size_t t = 0; t < c.Tn[static_cast<std::size_t>(n)]; ++t)
830 r.N_server += num_traits<T>::from_int(n) * r.pi(i, off + t);
831 }
832 r.P_idle += r.pi(i, base);
833 }
834 r.P_empty_orbit = zero;
835 for (std::size_t j = 0; j < Vd; ++j) r.P_empty_orbit += r.pi(0, j);
836 r.P_empty_system = zero;
837 for (int nu = 0; nu < V; ++nu) r.P_empty_system += r.pi(0, static_cast<std::size_t>(nu) * c.d);
838 r.topLevelMass = zero;
839 for (std::size_t j = 0; j < Vd; ++j) r.topLevelMass += r.pi(truncLevel, j);
840
841 r.L_system = T(r.L_orbit + r.N_server);
843 r.throughput = T(r.N_server / b1);
844 r.truncLevel = truncLevel;
845 r.truncError = truncError;
846 return r;
847}
848
849/** qsys_bmapphnn_retrial with the reference's automatic truncation level. */
850template <class T>
852 const std::vector<T>& beta, const Matrix<T>& S,
853 int N, const T& alpha, const T& gamma, const T& p,
854 long R) {
855 return qsys_bmapphnn_retrial(D, beta, S, N, alpha, gamma, p, std::vector<long>(1, R),
857}
858
859} // namespace qsys
860} // namespace line
861
862#endif // LINE_API_QSYS_QSYS_BMAPPHNN_RETRIAL_H
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 size() const
Definition matrix.h:91
std::size_t cols() const
Definition matrix.h:90
std::size_t rows() const
Definition matrix.h:89
Matrix transpose() const
Definition matrix.h:110
NumericError(const std::string &what)
Definition error.h:112
The exception types the port throws.
Enumerations and the minimal distribution descriptor shared by the model layer of the C++ port.
Dense linear algebra over the templated number type: products, identity, inverse, and powers.
LU factorization with partial pivoting, templated on the number type.
Dense matrix and non-owning view.
RetrialPolicy
Retrial admission policy (RetrialPolicy in MATLAB).
@ CONSTANT
the orbit retries at rate alpha whenever it is non-empty
@ LINEAR
each orbiting customer retries at rate alpha (orbit rate i*alpha)
BmapPhNnRetrialResult< T > qsys_bmapphnn_retrial(const std::vector< Matrix< T > > &D, const std::vector< T > &beta, const Matrix< T > &S, int N, const T &alpha, const T &gamma, const T &p, const std::vector< long > &R, const BmapPhNnRetrialOptions &opt)
The BMAP/PH/N/N bufferless retrial queue.
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
Matrix< T > inverse(const Matrix< T > &A)
Inverse by LU with one factorization and n back substitutions.
Definition linalg.h:72
Matrix< T > matmul(const Matrix< T > &A, const Matrix< T > &B)
Matrix product A B.
Definition linalg.h:36
std::vector< T > mulvec(const Matrix< T > &A, const std::vector< T > &v)
Matrix times column vector, A v.
Definition linalg.h:62
std::vector< T > solve(const Matrix< T > &A, const std::vector< T > &b)
Convenience: solve Ax = b, leaving A and b untouched.
Definition lu.h:158
std::vector< T > ones(std::size_t n)
Column vector of ones, the ubiquitous e in MAP algebra.
Definition linalg.h:104
Matrix< T > eye(std::size_t n)
Identity of order n.
Definition linalg.h:28
Number-type abstraction for the templated API port.
The retrial policy shared by the qsys retrial functions (MATLAB RetrialPolicy).
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
static constexpr double FineTol
Definition lang_types.h:823
Options of qsys_bmapphnn_retrial (the name-value pairs of the .m file).
double tolerance
'Tolerance' (parsed by the reference and, like there, not consumed).
std::size_t maxLevel
Fixed orbit truncation level ('MaxLevel'); 0 selects the reference's adaptive choice,...
double maxDim
'MaxDim': cap on the total generator dimension of the refinement.
double tailTolerance
'TailTolerance': relative orbit-truncation error target.
RetrialPolicy retrialPolicy
'RetrialPolicy'.
double maxBlockSize
'MaxBlockSize': cap on the per-level block size V*d; exceeding it is an error.
Result of qsys_bmapphnn_retrial.
bool converged
The adaptive refinement reached tailTolerance (always true for a fixed maxLevel).
T P_empty_orbit
probability that the orbit is empty
T L_orbit
mean number of customers in orbit
std::size_t truncLevel
truncation level used
T P_idle
probability that every server is idle
T truncError
relative orbit-truncation error estimate at truncLevel
Matrix< T > pi
stationary law, (truncLevel + 1) x (V d)
T topLevelMass
mass at the highest retained level; see defect 2
T P_empty_system
probability that the system is empty
T N_server
mean number of busy servers
bool clipped
a negative probability had to be clipped to zero