LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
qsys_mg1_ps.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_MG1_PS_H
6#define LINE_API_QSYS_QSYS_MG1_PS_H
7
8/**
9 * @file
10 * @ingroup api_qsys
11 * Sojourn-time distribution of the M/G/1 processor-sharing queue.
12 *
13 * Port of matlab/src/api/qsys/qsys_mg1_ps.m (twins `Qsys_mg1_ps.java`,
14 * `python/line_solver/api/qsys/mg1ps.py`). MATLAB is the reference.
15 *
16 * Jobs arrive Poisson at rate lambda at one egalitarian processor-sharing
17 * server whose service requirement has LST bhat(tau) and mean m1. Writing V(x)
18 * for the sojourn of a tagged job of requirement x and rho = lambda m1 < 1, Ott
19 * (1984) and Yashkov (1983) give
20 *
21 * E[exp(-s V(x))] = (1 - rho) / D(s,x),
22 *
23 * D(s,x) being the inverse Laplace transform, evaluated at x, of
24 *
25 * f(tau;s) = [ (1-rho) tau^2 - (1-rho) lambda (1-bhat(tau)) tau
26 * + s rho tau - s lambda (1-bhat(tau)) ]
27 * / [ tau^2 (tau - s - lambda (1-bhat(tau))) ].
28 *
29 * The transform is exact but IMPLICIT: f has to be inverted in tau. For
30 * phase-type service f is a proper rational function of tau, the double pole at
31 * the origin cancels, and D(s,x) comes out in closed form as a finite sum of
32 * residues -- so the M/PH/1-PS queue, hence every service law that can be
33 * fitted phase-type, is exactly solvable. For a transform supplied as a
34 * callback, f is inverted numerically on a Bromwich contour placed to the right
35 * of the dominant singularity tau*(s), the unique root of
36 * tau = s + lambda (1 - bhat(tau)) in the right half plane, which the fixed
37 * point of that equation reaches at geometric rate rho.
38 *
39 * THE CONDITIONAL SOJOURN IS ATOMIC ON THE LATTICE t = (k+1) x, and that is not
40 * a numerical artifact. Processor sharing gives every job in the system the
41 * same service rate, so if the k jobs present on arrival all outlive the tagged
42 * job and nothing arrives, the sojourn is exactly (k+1) x. The k = 0 atom,
43 * (1-rho) exp(-lambda x), is the probability of finding the system empty and
44 * sharing it with nobody, and it is the only one that stays exact for general
45 * service. It is removed before inverting in s; the remaining atoms make the
46 * conditional CDF JUMP and leave no density, so the density is reported as NaN
47 * on the lattice rather than as the finite garbage a smooth inversion returns
48 * there.
49 *
50 * TWO SUBSTITUTIONS FOR MATLAB, both self-contained rather than approximate:
51 *
52 * 1. `roots(P)` is computed by Durand-Kerner rather than by the eigenvalues of
53 * the companion matrix, so this header does not require LAPACK. The
54 * polynomial has degree n+1 in the phase count, which is small, and the
55 * iteration converges to machine precision on it; the roots are a SET, and
56 * the residue sum that consumes them does not depend on their order. The
57 * same routine supplies `eig(T)` for the quadrature range, as the roots of
58 * the characteristic polynomial det(tau I - T) that Faddeev-LeVerrier
59 * already produces.
60 * 2. The Golub-Welsch call behind the panelled quadrature is the tree's own
61 * `gauss_legendre`, which computes the same Legendre nodes by Newton. The
62 * reference notes that the rule is fixed so that every codebase shares it;
63 * the nodes agree to machine precision, so they do.
64 *
65 * ARITHMETIC: double. The inversion, the root finding and the contour are all
66 * inherently floating point, and the reference's own tolerances are absolute in
67 * double.
68 */
69
70#include <algorithm>
71#include <cmath>
72#include <complex>
73#include <cstddef>
74#include <functional>
75#include <limits>
76#include <memory>
77#include <vector>
78
81#include "line/num/number.h"
82#include "line/util/error.h"
83#include "line/util/expm.h"
84#include "line/util/lu.h"
85#include "line/util/matrix.h"
86
87namespace line {
88namespace qsys {
89
90using Cplx = std::complex<double>;
91
92/** Options of `qsys_mg1_ps`, mirroring the reference's name-value pairs. */
94 std::vector<double> x; ///< service requirements to condition on
95 std::vector<double> s; ///< transform arguments to tabulate the LST at
96 std::vector<double> t; ///< times to evaluate the sojourn distribution at
97 std::size_t nterms = 41; ///< function evaluations per numerical inversion, ODD
98 /** Service density, needed to remove the conditioning on a callback path. */
99 std::function<double(double)> pdf;
100 /**
101 * Initial vector of the TAGGED job's requirement, PH(tagAlpha, T), on the
102 * phase-type path only (empty: alpha). The arrival stream still mixes
103 * requirements as PH(alpha, T), which fixes rho and V(x); the unconditional
104 * outputs remove the conditioning against the tagged law, and m1/m2 are its
105 * moments. A multiclass Poisson stream at one PS server is this queue with
106 * alpha the rate-weighted mix of the class blocks, and one class's block as
107 * tagAlpha gives that class's exact law.
108 */
109 std::vector<double> tagAlpha;
110};
111
112/** Everything `qsys_mg1_ps` returns. */
114 double rho = 0.0;
115 double m1 = 0.0;
116 double m2 = std::numeric_limits<double>::quiet_NaN();
117 std::function<Cplx(Cplx, double)> lstCond; ///< (s,x) -> E[exp(-s V(x))]
118 std::function<Cplx(Cplx, double)> lstExcess; ///< (s,x) -> E[exp(-s (V(x)-x))]
119 std::function<Cplx(Cplx)> lstUncond; ///< s -> E[exp(-s V)]
120 std::function<Cplx(Cplx)> dominantRoot; ///< s -> tau*(s)
121 std::vector<double> x, s, t;
122 Matrix<double> lstCondVal; ///< (|x| x |s|)
123 std::vector<double> lstUncondVal;
124 std::vector<double> atomCond; ///< (1-rho) exp(-lambda x), at t = x
125 double atomUncond = 0.0; ///< (1-rho) bhat(lambda)
126 std::vector<double> meanCond, m2Cond, varCond;
127 double meanUncond = 0.0;
128 double m2Uncond = std::numeric_limits<double>::quiet_NaN();
129 double varUncond = std::numeric_limits<double>::quiet_NaN();
130 Matrix<double> pdfCond, cdfCond; ///< (|x| x |t|)
131 std::vector<double> pdfUncond, cdfUncond;
132};
133
134namespace mg1psdetail {
135
136/** Polynomial product, highest degree first, as MATLAB's `conv`. */
137inline std::vector<double> conv(const std::vector<double>& a, const std::vector<double>& b) {
138 if (a.empty() || b.empty()) return std::vector<double>();
139 std::vector<double> c(a.size() + b.size() - 1, 0.0);
140 for (std::size_t i = 0; i < a.size(); ++i)
141 for (std::size_t j = 0; j < b.size(); ++j) c[i + j] += a[i] * b[j];
142 return c;
143}
144
145/** Horner evaluation of a polynomial given highest degree first. */
146template <class C, class U>
147U polyval(const std::vector<C>& p, const U& z) {
148 U v = U(0.0);
149 for (std::size_t i = 0; i < p.size(); ++i) v = v * z + U(p[i]);
150 return v;
151}
152
153/** Derivative of a polynomial given highest degree first. */
154inline std::vector<double> polyder(const std::vector<double>& p) {
155 if (p.size() <= 1) return std::vector<double>(1, 0.0);
156 const std::size_t n = p.size() - 1;
157 std::vector<double> d(n, 0.0);
158 for (std::size_t i = 0; i < n; ++i) d[i] = p[i] * static_cast<double>(n - i);
159 return d;
160}
161
162/**
163 * Roots of a polynomial by Durand-Kerner.
164 *
165 * MATLAB uses the companion-matrix eigenvalues; this is LAPACK-free and exact
166 * to machine precision at the degrees involved (one more than the phase count).
167 * The roots are a SET and every consumer here is symmetric in them.
168 */
169inline std::vector<Cplx> poly_roots(const std::vector<double>& p_in) {
170 std::vector<double> p = p_in;
171 // Strip leading zeros: they are not roots, they are a lower degree.
172 std::size_t lead = 0;
173 while (lead + 1 < p.size() && p[lead] == 0.0) ++lead;
174 p.erase(p.begin(), p.begin() + static_cast<long>(lead));
175 if (p.size() <= 1) return std::vector<Cplx>();
176 const std::size_t n = p.size() - 1;
177 std::vector<double> mon(p.size());
178 for (std::size_t i = 0; i < p.size(); ++i) mon[i] = p[i] / p[0];
179
180 // The classic spiral start, off the real axis so a real polynomial's
181 // iterates do not collapse onto it.
182 std::vector<Cplx> r(n);
183 const Cplx seed(0.4, 0.9);
184 Cplx pw(1.0, 0.0);
185 for (std::size_t i = 0; i < n; ++i) {
186 r[i] = pw;
187 pw *= seed;
188 }
189 for (int it = 0; it < 1000; ++it) {
190 double move = 0.0;
191 for (std::size_t i = 0; i < n; ++i) {
192 Cplx den(1.0, 0.0);
193 for (std::size_t j = 0; j < n; ++j)
194 if (j != i) den *= (r[i] - r[j]);
195 if (std::abs(den) < 1e-300) continue;
196 const Cplx step = polyval(mon, r[i]) / den;
197 r[i] -= step;
198 move = std::max(move, std::abs(step));
199 }
200 if (move < 1e-14) break;
201 }
202 return r;
203}
204
205/**
206 * Matrix exponential of a COMPLEX matrix, by scaling and squaring with a
207 * Taylor series.
208 *
209 * `util/expm.h` is templated on `num_traits`, which has no complex
210 * instantiation, so the repeated-pole branch below needs its own. Scaling to a
211 * norm under 1/2 makes the truncated series converge to machine precision in
212 * around twenty terms, and the squaring recovers the full argument.
213 */
214inline Matrix<Cplx> expm_cplx(const Matrix<Cplx>& A) {
215 const std::size_t n = A.rows();
216 double nrm = 0.0;
217 for (std::size_t i = 0; i < n; ++i) {
218 double row = 0.0;
219 for (std::size_t j = 0; j < n; ++j) row += std::abs(A(i, j));
220 nrm = std::max(nrm, row);
221 }
222 int sq = 0;
223 while (nrm > 0.5) {
224 nrm /= 2.0;
225 ++sq;
226 }
227 const double sc = std::pow(2.0, -static_cast<double>(sq));
228 Matrix<Cplx> B(n, n, Cplx(0.0, 0.0)), E(n, n, Cplx(0.0, 0.0)), Tk(n, n, Cplx(0.0, 0.0));
229 for (std::size_t i = 0; i < n; ++i) {
230 E(i, i) = Cplx(1.0, 0.0);
231 Tk(i, i) = Cplx(1.0, 0.0);
232 for (std::size_t j = 0; j < n; ++j) B(i, j) = A(i, j) * sc;
233 }
234 for (int k = 1; k <= 30; ++k) {
235 Matrix<Cplx> P(n, n, Cplx(0.0, 0.0));
236 for (std::size_t i = 0; i < n; ++i)
237 for (std::size_t j = 0; j < n; ++j) {
238 Cplx acc(0.0, 0.0);
239 for (std::size_t l = 0; l < n; ++l) acc += Tk(i, l) * B(l, j);
240 P(i, j) = acc / static_cast<double>(k);
241 }
242 Tk = P;
243 for (std::size_t i = 0; i < n; ++i)
244 for (std::size_t j = 0; j < n; ++j) E(i, j) += Tk(i, j);
245 }
246 for (int t = 0; t < sq; ++t) {
247 Matrix<Cplx> P(n, n, Cplx(0.0, 0.0));
248 for (std::size_t i = 0; i < n; ++i)
249 for (std::size_t j = 0; j < n; ++j) {
250 Cplx acc(0.0, 0.0);
251 for (std::size_t l = 0; l < n; ++l) acc += E(i, l) * E(l, j);
252 P(i, j) = acc;
253 }
254 E = P;
255 }
256 return E;
257}
258
259/**
260 * Abate-Whitt Euler inversion, symmetrized so that a complex-valued time
261 * function is handled as well as a real-valued one. The nodes and weights are
262 * the shared `lti::euler_get_alpha` / `lti::euler_get_omega`; only the
263 * symmetrized sum (F(beta) + F(conj beta))/2, in place of Re F(beta), is
264 * specific here.
265 */
266template <class Fn>
267Cplx ilt(Fn fun, double t, std::size_t nterms) {
268 const std::size_t n = 2 * ((nterms - 1) / 2) + 1;
269 const std::vector<Cplx> beta = lti::euler_get_alpha(n);
270 const std::vector<Cplx> eta = lti::euler_get_omega(n);
271 Cplx g(0.0, 0.0);
272 for (std::size_t k = 0; k < n; ++k) {
273 const Cplx bj = beta[k] / t;
274 g += 0.5 * eta[k] * (fun(bj) + fun(std::conj(bj)));
275 }
276 return g / t;
277}
278
279/**
280 * The panelled Gauss-Legendre rule the reference uses to remove the
281 * conditioning: eight panels growing geometrically toward ymax, so that both
282 * ends of an exponentially decaying density are resolved, times a 32-point rule.
283 * The rule is FIXED, so it is the same in every codebase.
284 */
285inline void quad_nodes(double ymax, std::vector<double>* y, std::vector<double>* w,
286 std::size_t npanel = 8, std::size_t ng = 32) {
287 y->clear();
288 w->clear();
289 std::vector<double> edges;
290 edges.push_back(0.0);
291 for (long k = -static_cast<long>(npanel); k <= 0; ++k)
292 edges.push_back(ymax * std::pow(2.0, static_cast<double>(k)));
293 for (std::size_t k = 0; k + 1 < edges.size(); ++k) {
294 std::vector<double> xg, wg;
295 pfqn::detail::gauss_legendre<double>(ng, edges[k], edges[k + 1], xg, wg);
296 for (std::size_t i = 0; i < xg.size(); ++i) {
297 y->push_back(xg[i]);
298 w->push_back(wg[i]);
299 }
300 }
301}
302
303/**
304 * Second moment from the transform's curvature at the origin.
305 *
306 * The stencil is ONE-SIDED so the transform is never sampled at a negative
307 * argument, where it need not converge; the step is scaled by the conditional
308 * mean but capped by the unconditional one so it stays finite as x -> 0; and
309 * Richardson extrapolation over h and h/2 removes the leading truncation.
310 */
311template <class Fn>
312double second_moment(Fn lst, double meanref, double meanscale) {
313 if (!(meanref > 0.0)) return 0.0;
314 const double h = std::min(1e-2 / meanref, 1.0 / meanscale);
315 auto d2 = [&lst](double hh) {
316 double f[6];
317 for (int j = 0; j < 6; ++j) f[j] = std::real(lst(Cplx(static_cast<double>(j) * hh, 0.0)));
318 return (45.0 * f[0] - 154.0 * f[1] + 214.0 * f[2] - 156.0 * f[3] + 61.0 * f[4] -
319 10.0 * f[5]) /
320 (12.0 * hh * hh);
321 };
322 return (16.0 * d2(h / 2.0) - d2(h)) / 15.0;
323}
324
325/**
326 * Everything downstream of D(s,x): the transforms, the grids, the moments and
327 * the inversions, shared by the phase-type and the transform-handle forms.
328 *
329 * @param bhat service LST
330 * @param denom (s, x, &scale) -> val with D(s,x) = exp(scale x) val
331 * @param bpdf service density, empty when unavailable (hasPdf false)
332 * @param ymax range of the panelled quadrature removing the conditioning
333 * @param isPH phase-type path: the time grid is admissible
334 */
335inline Mg1PsResult mg1ps_finish(double lambda, double rho, double m1, double m2,
336 const std::function<Cplx(const Cplx&)>& bhat,
337 const std::function<Cplx(const Cplx&)>& bhatTag,
338 const std::function<Cplx(const Cplx&, double, double*)>& denom,
339 const std::function<double(double)>& bpdf, double ymax, bool isPH,
340 const Mg1PsOptions& opt) {
341 const bool hasPdf = static_cast<bool>(bpdf);
342 const double nan = std::numeric_limits<double>::quiet_NaN();
343
344 Mg1PsResult res;
345 res.rho = rho;
346 res.m1 = m1;
347 res.m2 = m2;
348 res.meanUncond = m1 / (1.0 - rho);
349 res.atomUncond = (1.0 - rho) * bhatTag(Cplx(lambda, 0.0)).real();
350
351 auto lst_cond = [denom, rho](const Cplx& s, double x, bool excess) {
352 if (x == 0.0) return Cplx(1.0, 0.0);
353 double scale = 0.0;
354 const Cplx val = denom(s, x, &scale);
355 const Cplx expo = (excess ? s : Cplx(0.0, 0.0)) - Cplx(scale, 0.0);
356 return Cplx(1.0 - rho, 0.0) * std::exp(expo * x) / val;
357 };
358 res.lstCond = [lst_cond](Cplx s, double x) { return lst_cond(s, x, false); };
359 res.lstExcess = [lst_cond](Cplx s, double x) { return lst_cond(s, x, true); };
360 res.dominantRoot = [lambda, bhat, rho](Cplx s) {
361 Cplx tau = s;
362 const int maxit = std::max(200, static_cast<int>(std::ceil(
363 3.0 * std::log(1e-15) / std::log(std::max(rho, 1e-3)))));
364 for (int it = 0; it < maxit; ++it) {
365 const Cplx nx = s + Cplx(lambda, 0.0) * (Cplx(1.0, 0.0) - bhat(tau));
366 if (std::abs(nx - tau) <= 1e-14 * std::max(1.0, std::abs(nx))) return nx;
367 tau = nx;
368 }
369 throw InputError("qsys_mg1_ps: the dominant root iteration did not converge");
370 };
371
372 // The quadrature that removes the conditioning. The nodes do not move with
373 // s, so the service density is sampled once.
374 std::vector<double> yq, wq, bq;
375 quad_nodes(ymax, &yq, &wq);
376 if (hasPdf) {
377 bq.resize(yq.size());
378 for (std::size_t k = 0; k < yq.size(); ++k) bq[k] = bpdf(yq[k]);
379 }
380 res.lstUncond = [lst_cond, yq, wq, bq](Cplx s) {
381 if (bq.empty())
382 throw InputError("qsys_mg1_ps: the service density is required to remove the "
383 "conditioning, pass it as the pdf option");
384 Cplx v(0.0, 0.0);
385 for (std::size_t k = 0; k < yq.size(); ++k)
386 v += wq[k] * bq[k] * lst_cond(s, yq[k], false);
387 return v;
388 };
389
390 res.x = opt.x;
391 res.s = opt.s;
392 res.t = opt.t;
393 res.lstCondVal = Matrix<double>(res.x.size(), res.s.size(), 0.0);
394 for (std::size_t i = 0; i < res.x.size(); ++i)
395 for (std::size_t j = 0; j < res.s.size(); ++j)
396 res.lstCondVal(i, j) = res.lstCond(Cplx(res.s[j], 0.0), res.x[i]).real();
397 res.lstUncondVal.assign(res.s.size(), nan);
398 if (hasPdf)
399 for (std::size_t j = 0; j < res.s.size(); ++j)
400 res.lstUncondVal[j] = res.lstUncond(Cplx(res.s[j], 0.0)).real();
401
402 res.atomCond.assign(res.x.size(), 0.0);
403 res.meanCond.assign(res.x.size(), 0.0);
404 res.m2Cond.assign(res.x.size(), 0.0);
405 res.varCond.assign(res.x.size(), 0.0);
406 for (std::size_t i = 0; i < res.x.size(); ++i) {
407 res.atomCond[i] = (1.0 - rho) * std::exp(-lambda * res.x[i]);
408 res.meanCond[i] = res.x[i] / (1.0 - rho);
409 const double xi = res.x[i];
410 res.m2Cond[i] = second_moment([&res, xi](Cplx u) { return res.lstCond(u, xi); },
411 res.meanCond[i], res.meanUncond);
412 res.varCond[i] = res.m2Cond[i] - res.meanCond[i] * res.meanCond[i];
413 }
414
415 // The unconditional second moment is integrated from the conditional one,
416 // which is far better conditioned than differentiating the quadrature that
417 // removed the conditioning.
418 res.m2Uncond = nan;
419 res.varUncond = nan;
420 if (hasPdf) {
421 double m2u = 0.0;
422 for (std::size_t k = 0; k < yq.size(); ++k) {
423 const double yk = yq[k];
424 m2u += wq[k] * bq[k] *
425 second_moment([&res, yk](Cplx u) { return res.lstCond(u, yk); },
426 yk / (1.0 - rho), res.meanUncond);
427 }
428 res.m2Uncond = m2u;
429 res.varUncond = m2u - res.meanUncond * res.meanUncond;
430 }
431
432 if (!res.t.empty() && !isPH)
433 throw InputError("qsys_mg1_ps: the sojourn time distribution needs phase-type service, "
434 "since inverting a numerically inverted transform is unstable in double "
435 "precision; with a transform handle only the LST and its moments are "
436 "available");
437 res.pdfCond = Matrix<double>(res.x.size(), res.t.size(), 0.0);
438 res.cdfCond = Matrix<double>(res.x.size(), res.t.size(), 0.0);
439 for (std::size_t i = 0; i < res.x.size(); ++i) {
440 const double atom = res.atomCond[i], xi = res.x[i];
441 // V(x) >= x with an atom at x, so what is inverted is the EXCESS
442 // V(x)-x net of its atom.
443 auto gpdf = [&res, xi, atom](Cplx u) { return res.lstExcess(u, xi) - Cplx(atom, 0.0); };
444 auto gcdf = [gpdf](Cplx u) { return gpdf(u) / u; };
445 for (std::size_t j = 0; j < res.t.size(); ++j) {
446 const double tj = res.t[j];
447 if (tj < xi) continue;
448 if (tj == xi) {
449 res.cdfCond(i, j) = atom;
450 continue;
451 }
452 res.cdfCond(i, j) = ilt(gcdf, tj - xi, opt.nterms).real() + atom;
453 const double ratio = tj / xi;
454 if (std::fabs(ratio - std::floor(ratio + 0.5)) < 1e-9)
455 res.pdfCond(i, j) = std::numeric_limits<double>::quiet_NaN();
456 else
457 res.pdfCond(i, j) = ilt(gpdf, tj - xi, opt.nterms).real();
458 }
459 }
460
461 res.pdfUncond.assign(res.t.size(), nan);
462 res.cdfUncond.assign(res.t.size(), nan);
463 if (hasPdf)
464 for (std::size_t j = 0; j < res.t.size(); ++j) {
465 if (res.t[j] <= 0.0) {
466 res.pdfUncond[j] = 0.0;
467 res.cdfUncond[j] = 0.0;
468 continue;
469 }
470 res.pdfUncond[j] = ilt(res.lstUncond, res.t[j], opt.nterms).real();
471 res.cdfUncond[j] =
472 ilt([&res](Cplx u) { return res.lstUncond(u) / u; }, res.t[j], opt.nterms).real();
473 }
474 return res;
475}
476
477} // namespace mg1psdetail
478
479/**
480 * @brief Sojourn-time distribution of the M/G/1 processor-sharing queue.
481 *
482 * @param lambda arrival rate, finite and positive
483 * @param alpha phase-type initial probability vector
484 * @param Tmat phase-type subgenerator
485 * @param opt grids and tuning
486 */
487inline Mg1PsResult qsys_mg1_ps(double lambda, const std::vector<double>& alpha,
488 const Matrix<double>& Tmat, const Mg1PsOptions& opt) {
489 using namespace mg1psdetail;
490 if (!(lambda > 0.0) || !std::isfinite(lambda))
491 throw InputError("qsys_mg1_ps: lambda must be a finite positive scalar");
492 if (opt.nterms % 2 == 0 || opt.nterms < 11)
493 throw InputError("qsys_mg1_ps: nterms must be an odd integer of at least 11");
494
495 const std::size_t n = alpha.size();
496 if (n == 0 || Tmat.rows() != n || Tmat.cols() != n)
497 throw InputError("qsys_mg1_ps: T must be n x n to match alpha");
498 double asum = 0.0;
499 for (std::size_t i = 0; i < n; ++i) {
500 if (alpha[i] < -1e-12) throw InputError("qsys_mg1_ps: alpha must be a probability vector");
501 asum += alpha[i];
502 }
503 if (std::fabs(asum - 1.0) > 1e-8)
504 throw InputError("qsys_mg1_ps: alpha must be a probability vector");
505 std::vector<double> exitrate(n, 0.0);
506 for (std::size_t i = 0; i < n; ++i) {
507 double row = 0.0;
508 for (std::size_t j = 0; j < n; ++j) row += Tmat(i, j);
509 exitrate[i] = -row;
510 if (exitrate[i] < -1e-10 || Tmat(i, i) >= 0.0)
511 throw InputError("qsys_mg1_ps: T must be a proper phase-type subgenerator");
512 }
513
514 // Moments, by solving with (-T) rather than forming its inverse.
515 Matrix<double> negT(n, n, 0.0);
516 for (std::size_t i = 0; i < n; ++i)
517 for (std::size_t j = 0; j < n; ++j) negT(i, j) = -Tmat(i, j);
518 const std::vector<double> ones(n, 1.0);
519 const std::vector<double> u1 = solve(negT, ones);
520 const std::vector<double> u2 = solve(negT, u1);
521 double m1 = 0.0, m2 = 0.0;
522 for (std::size_t i = 0; i < n; ++i) {
523 m1 += alpha[i] * u1[i];
524 m2 += 2.0 * alpha[i] * u2[i];
525 }
526 const double rho = lambda * m1;
527 if (rho >= 1.0)
528 throw InputError("qsys_mg1_ps: the system is unstable, the utilization is at least one");
529 // The arrival mix fixes the load and the denominator; a tagged job of a
530 // different requirement law only changes what the conditioning is removed
531 // against.
532 const double m1mix = m1;
533 const bool tagged = !opt.tagAlpha.empty();
534 const std::vector<double>& talpha = tagged ? opt.tagAlpha : alpha;
535 if (tagged) {
536 if (talpha.size() != n)
537 throw InputError("qsys_mg1_ps: tagAlpha must have n entries to match T");
538 double tsum = 0.0;
539 for (std::size_t i = 0; i < n; ++i) {
540 if (talpha[i] < -1e-12)
541 throw InputError("qsys_mg1_ps: tagAlpha must be a probability vector");
542 tsum += talpha[i];
543 }
544 if (std::fabs(tsum - 1.0) > 1e-8)
545 throw InputError("qsys_mg1_ps: tagAlpha must be a probability vector");
546 if (opt.pdf)
547 throw InputError("qsys_mg1_ps: pass either tagAlpha or pdf, not both");
548 m1 = 0.0;
549 m2 = 0.0;
550 for (std::size_t i = 0; i < n; ++i) {
551 m1 += talpha[i] * u1[i];
552 m2 += 2.0 * talpha[i] * u2[i];
553 }
554 }
555
556 // Faddeev-LeVerrier gives det(tau I - T) and the adjugate in one sweep, so
557 // bhat(tau) = nb(tau)/db(tau) as polynomials of degree n-1 and n.
558 std::vector<double> db(n + 1, 0.0), nb(n, 0.0), nbt(n, 0.0);
559 db[0] = 1.0;
560 Matrix<double> Mk(n, n, 0.0);
561 for (std::size_t i = 0; i < n; ++i) Mk(i, i) = 1.0;
562 for (std::size_t k = 1; k <= n; ++k) {
563 double v = 0.0, vt = 0.0;
564 for (std::size_t i = 0; i < n; ++i) {
565 double row = 0.0;
566 for (std::size_t j = 0; j < n; ++j) row += Mk(i, j) * exitrate[j];
567 v += alpha[i] * row;
568 vt += talpha[i] * row;
569 }
570 nb[k - 1] = v;
571 nbt[k - 1] = vt;
572 Matrix<double> TM(n, n, 0.0);
573 for (std::size_t i = 0; i < n; ++i)
574 for (std::size_t j = 0; j < n; ++j) {
575 double acc = 0.0;
576 for (std::size_t l = 0; l < n; ++l) acc += Tmat(i, l) * Mk(l, j);
577 TM(i, j) = acc;
578 }
579 double tr = 0.0;
580 for (std::size_t i = 0; i < n; ++i) tr += TM(i, i);
581 db[k] = -tr / static_cast<double>(k);
582 Mk = TM;
583 for (std::size_t i = 0; i < n; ++i) Mk(i, i) += db[k];
584 }
585
586 auto bhat = [db, nb](const Cplx& tau) { return polyval(nb, tau) / polyval(db, tau); };
587 // the tagged requirement shares det(tau I - T) and differs in the numerator
588 auto bhat_tag = [db, nbt](const Cplx& tau) { return polyval(nbt, tau) / polyval(db, tau); };
589 auto bpdf = [&Tmat, &talpha, &exitrate, n](double y) {
590 Matrix<double> E = Tmat;
591 for (std::size_t i = 0; i < n; ++i)
592 for (std::size_t j = 0; j < n; ++j) E(i, j) = Tmat(i, j) * y;
593 const Matrix<double> Ey = expm(E);
594 double v = 0.0;
595 for (std::size_t i = 0; i < n; ++i) {
596 double row = 0.0;
597 for (std::size_t j = 0; j < n; ++j) row += Ey(i, j) * exitrate[j];
598 v += talpha[i] * row;
599 }
600 return v;
601 };
602
603 // D(s,x) = exp(scale x) val, exactly, from the residues of f(tau;s), whose
604 // double pole at the origin cancels. The scale is carried separately so
605 // that neither factor overflows at large s.
606 // Everything but the last step depends on s alone: the roots of P, their
607 // residues and the scale. The quadrature that removes the conditioning
608 // asks for D(s,x) at every node with the same s, so they are solved once
609 // per s and reused across x, as the reference does by vectorizing over x.
610 struct DenomPrep {
611 bool valid = false;
612 Cplx s;
613 std::vector<Cplx> Pc, Ahat, r, coef;
614 double scale = 0.0;
615 bool simple = false;
616 };
617 auto prep = std::make_shared<DenomPrep>();
618 auto denom = [db, nb, n, lambda, rho, prep](const Cplx& s, double x, double* scale_out) {
619 if (!prep->valid || prep->s != s) {
620 std::vector<double> dm(db.size(), 0.0);
621 dm[0] = db[0];
622 for (std::size_t i = 1; i < db.size(); ++i) dm[i] = db[i] - nb[i - 1];
623
624 // These carry s, so they are complex; the polynomial helpers are
625 // written over a scalar type for exactly that reason.
626 std::vector<Cplx> Pc, Ac;
627 {
628 std::vector<Cplx> lin;
629 lin.push_back(Cplx(1.0, 0.0));
630 lin.push_back(-(s + Cplx(lambda, 0.0)));
631 std::vector<Cplx> dbz(db.size());
632 for (std::size_t i = 0; i < db.size(); ++i) dbz[i] = Cplx(db[i], 0.0);
633 Pc.assign(lin.size() + dbz.size() - 1, Cplx(0.0, 0.0));
634 for (std::size_t i = 0; i < lin.size(); ++i)
635 for (std::size_t j = 0; j < dbz.size(); ++j) Pc[i + j] += lin[i] * dbz[j];
636 // + [0, 0, lambda*nb]
637 for (std::size_t i = 0; i < nb.size(); ++i)
638 Pc[Pc.size() - nb.size() + i] += Cplx(lambda * nb[i], 0.0);
639
640 std::vector<Cplx> q1;
641 q1.push_back(Cplx(1.0 - rho, 0.0));
642 q1.push_back(s * Cplx(rho, 0.0));
643 q1.push_back(Cplx(0.0, 0.0));
644 std::vector<Cplx> t1(q1.size() + dbz.size() - 1, Cplx(0.0, 0.0));
645 for (std::size_t i = 0; i < q1.size(); ++i)
646 for (std::size_t j = 0; j < dbz.size(); ++j) t1[i + j] += q1[i] * dbz[j];
647
648 std::vector<Cplx> q2;
649 q2.push_back(Cplx(1.0 - rho, 0.0));
650 q2.push_back(s);
651 std::vector<Cplx> ldm(dm.size());
652 for (std::size_t i = 0; i < dm.size(); ++i) ldm[i] = Cplx(lambda * dm[i], 0.0);
653 std::vector<Cplx> t2(q2.size() + ldm.size() - 1, Cplx(0.0, 0.0));
654 for (std::size_t i = 0; i < q2.size(); ++i)
655 for (std::size_t j = 0; j < ldm.size(); ++j) t2[i + j] += q2[i] * ldm[j];
656
657 Ac.assign(t1.size(), Cplx(0.0, 0.0));
658 for (std::size_t i = 0; i < t1.size(); ++i) Ac[i] = t1[i];
659 for (std::size_t i = 0; i < t2.size(); ++i) Ac[Ac.size() - t2.size() + i] -= t2[i];
660 }
661 // The double pole at the origin must cancel: the two lowest
662 // coefficients of A are what would survive it.
663 double nrmA = 0.0;
664 for (std::size_t i = 0; i < Ac.size(); ++i) nrmA = std::max(nrmA, std::abs(Ac[i]));
665 const double tailA = std::abs(Ac[Ac.size() - 2]) + std::abs(Ac[Ac.size() - 1]);
666 if (tailA > 1e-6 * std::max(1.0, nrmA))
667 throw InputError("qsys_mg1_ps: the double pole at the origin did not cancel");
668 // `A(1:n+1)` in the reference: the first n+1 of the n+3 coefficients.
669 // The two dropped ones are the cancelled double pole, checked just
670 // above; taking n+2 instead silently keeps half of it and the LST comes
671 // back above one.
672 std::vector<Cplx> Ahat(Ac.begin(), Ac.begin() + static_cast<long>(n + 1));
673
674 // Durand-Kerner over the complex coefficients of P.
675 std::vector<Cplx> r;
676 {
677 std::vector<Cplx> mon(Pc.size());
678 for (std::size_t i = 0; i < Pc.size(); ++i) mon[i] = Pc[i] / Pc[0];
679 const std::size_t deg = mon.size() - 1;
680 r.assign(deg, Cplx(0.0, 0.0));
681 const Cplx seed(0.4, 0.9);
682 Cplx pw(1.0, 0.0);
683 for (std::size_t i = 0; i < deg; ++i) {
684 r[i] = pw;
685 pw *= seed;
686 }
687 for (int it = 0; it < 2000; ++it) {
688 double move = 0.0;
689 for (std::size_t i = 0; i < deg; ++i) {
690 Cplx den(1.0, 0.0);
691 for (std::size_t j = 0; j < deg; ++j)
692 if (j != i) den *= (r[i] - r[j]);
693 if (std::abs(den) < 1e-300) continue;
694 const Cplx step = polyval(mon, r[i]) / den;
695 r[i] -= step;
696 move = std::max(move, std::abs(step));
697 }
698 if (move < 1e-14) break;
699 }
700 }
701 double scale = -std::numeric_limits<double>::infinity();
702 for (std::size_t i = 0; i < r.size(); ++i) scale = std::max(scale, r[i].real());
703
704 double maxr = 0.0, minsep = std::numeric_limits<double>::infinity();
705 for (std::size_t i = 0; i < r.size(); ++i) maxr = std::max(maxr, std::abs(r[i]));
706 for (std::size_t i = 0; i < r.size(); ++i)
707 for (std::size_t j = 0; j < r.size(); ++j)
708 if (i != j) minsep = std::min(minsep, std::abs(r[i] - r[j]));
709 prep->simple = r.size() >= 2 && minsep > 1e-7 * std::max(1.0, maxr);
710 prep->coef.clear();
711 if (prep->simple) {
712 std::vector<Cplx> dP(Pc.size() - 1, Cplx(0.0, 0.0));
713 for (std::size_t i = 0; i + 1 < Pc.size(); ++i)
714 dP[i] = Pc[i] * static_cast<double>(Pc.size() - 1 - i);
715 for (std::size_t i = 0; i < r.size(); ++i) prep->coef.push_back(polyval(Ahat, r[i]) / polyval(dP, r[i]));
716 }
717 prep->Pc = Pc;
718 prep->Ahat = Ahat;
719 prep->r = r;
720 prep->scale = scale;
721 prep->s = s;
722 prep->valid = true;
723 }
724 const double scale = prep->scale;
725 const std::vector<Cplx>& Pc = prep->Pc;
726 const std::vector<Cplx>& Ahat = prep->Ahat;
727 const std::vector<Cplx>& r = prep->r;
728 *scale_out = scale;
729 if (prep->simple) {
730 Cplx val(0.0, 0.0);
731 for (std::size_t i = 0; i < r.size(); ++i) val += std::exp((r[i] - Cplx(scale, 0.0)) * x) * prep->coef[i];
732 return val;
733 }
734 // Repeated poles: the companion realization of Ahat/P, exactly as the
735 // reference falls back to. A residue sum is undefined there; the
736 // matrix exponential is not.
737 const std::size_t d = Pc.size() - 1;
738 Matrix<Cplx> Acomp(d, d, Cplx(0.0, 0.0));
739 for (std::size_t j = 0; j < d; ++j) Acomp(0, j) = -Pc[j + 1] / Pc[0];
740 for (std::size_t i = 1; i < d; ++i) Acomp(i, i - 1) = Cplx(1.0, 0.0);
741 for (std::size_t i = 0; i < d; ++i) Acomp(i, i) -= Cplx(scale, 0.0);
742 Matrix<Cplx> Ax(d, d, Cplx(0.0, 0.0));
743 for (std::size_t i = 0; i < d; ++i)
744 for (std::size_t j = 0; j < d; ++j) Ax(i, j) = Acomp(i, j) * x;
745 const Matrix<Cplx> E = expm_cplx(Ax);
746 Cplx val(0.0, 0.0);
747 for (std::size_t j = 0; j < d && j < Ahat.size(); ++j) val += (Ahat[j] / Pc[0]) * E(j, 0);
748 return val;
749 };
750
751 // ymax for the quadrature that removes the conditioning: the reference's
752 // max(40 m1, 40 / min(-real(eig(T)))). The eigenvalues of T are the roots
753 // of det(tau I - T) = db(tau), which Faddeev-LeVerrier has just produced,
754 // so they come from the same Durand-Kerner the residue sum uses.
755 double mineig = std::numeric_limits<double>::infinity();
756 {
757 const std::vector<Cplx> ev = poly_roots(db);
758 for (std::size_t i = 0; i < ev.size(); ++i) mineig = std::min(mineig, -ev[i].real());
759 if (ev.empty() || !std::isfinite(mineig))
760 for (std::size_t i = 0; i < n; ++i) mineig = std::min(mineig, -Tmat(i, i));
761 }
762 const double ymax = std::max(40.0 * std::max(m1, m1mix), 40.0 / std::max(mineig, 1e-12));
763
764 std::function<Cplx(const Cplx&, double, double*)> denom_fn = denom;
765 std::function<Cplx(const Cplx&)> bhat_fn = bhat;
766 std::function<Cplx(const Cplx&)> bhat_tag_fn = bhat_tag;
767 std::function<double(double)> bpdf_fn = opt.pdf ? opt.pdf : std::function<double(double)>(bpdf);
768 return mg1psdetail::mg1ps_finish(lambda, rho, m1, m2, bhat_fn, bhat_tag_fn, denom_fn, bpdf_fn, ymax, true,
769 opt);
770}
771
772/**
773 * @brief Sojourn-time distribution of the M/G/1-PS queue for a service law
774 * given by its Laplace-Stieltjes transform, the reference's second form
775 * `qsys_mg1_ps(lambda, bhat, m1, ...)`.
776 *
777 * f(tau; s) is inverted in tau numerically on a Bromwich contour placed
778 * 0.25 (1-rho)/m1 to the right of the dominant root tau*(s). The service
779 * density `opt.pdf` is needed to remove the conditioning (lstUncond,
780 * lstUncondVal, m2Uncond, varUncond are NaN or unavailable without it), m2 is
781 * NaN, and a time grid `opt.t` is refused, as in the reference: inverting a
782 * numerically inverted transform is unstable in double precision.
783 *
784 * @param lambda arrival rate, finite and positive
785 * @param bhat service LST, accepting complex arguments
786 * @param m1 mean service time
787 * @param opt grids and tuning
788 */
789inline Mg1PsResult qsys_mg1_ps(double lambda, const std::function<Cplx(const Cplx&)>& bhat,
790 double m1, const Mg1PsOptions& opt) {
791 using namespace mg1psdetail;
792 if (!(lambda > 0.0) || !std::isfinite(lambda))
793 throw InputError("qsys_mg1_ps: lambda must be a finite positive scalar");
794 if (opt.nterms % 2 == 0 || opt.nterms < 11)
795 throw InputError("qsys_mg1_ps: nterms must be an odd integer of at least 11");
796 if (!bhat) throw InputError("qsys_mg1_ps: the service transform handle is empty");
797 if (!std::isfinite(m1) || m1 <= 0.0)
798 throw InputError("qsys_mg1_ps: the mean service time must be a finite positive scalar");
799 const double rho = lambda * m1;
800 if (rho >= 1.0)
801 throw InputError("qsys_mg1_ps: the system is unstable, the utilization is at least one");
802 if (!opt.t.empty())
803 throw InputError("qsys_mg1_ps: the sojourn time distribution needs phase-type service, "
804 "since inverting a numerically inverted transform is unstable in double "
805 "precision; with a transform handle only the LST and its moments are "
806 "available");
807
808 // the dominant root tau*(s), the reference's local_root
809 auto rootfun = [lambda, bhat, rho](const Cplx& s) {
810 Cplx tau = s;
811 const int maxit = std::max(200, static_cast<int>(std::ceil(
812 3.0 * std::log(1e-15) / std::log(std::max(rho, 1e-3)))));
813 for (int it = 0; it < maxit; ++it) {
814 const Cplx nx = s + Cplx(lambda, 0.0) * (Cplx(1.0, 0.0) - bhat(tau));
815 if (std::abs(nx - tau) <= 1e-14 * std::max(1.0, std::abs(nx))) return nx;
816 tau = nx;
817 }
818 throw InputError("qsys_mg1_ps: the dominant root iteration did not converge");
819 };
820 const double shift = 0.25 * (1.0 - rho) / m1;
821 const std::size_t nterms = opt.nterms;
822 // D(s,x) for a general service transform: f(tau;s) inverted in tau on a
823 // contour just to the right of the dominant singularity (local_denom_gen)
824 std::function<Cplx(const Cplx&, double, double*)> denom =
825 [lambda, rho, bhat, rootfun, shift, nterms](const Cplx& s, double x, double* scale_out) {
826 const double scale = rootfun(s).real() + shift;
827 *scale_out = scale;
828 auto f = [&](const Cplx& u) {
829 const Cplx tau = u + Cplx(scale, 0.0);
830 const Cplx bh = bhat(tau);
831 const Cplx one_m_bh = Cplx(1.0, 0.0) - bh;
832 const Cplx num = Cplx(1.0 - rho, 0.0) * tau * tau -
833 Cplx((1.0 - rho) * lambda, 0.0) * one_m_bh * tau +
834 s * Cplx(rho, 0.0) * tau - s * Cplx(lambda, 0.0) * one_m_bh;
835 return num / (tau * tau * (tau - s - Cplx(lambda, 0.0) * one_m_bh));
836 };
837 return ilt(f, x, nterms);
838 };
839 if (!opt.tagAlpha.empty())
840 throw InputError("qsys_mg1_ps: tagAlpha needs phase-type service");
841 const double ymax = 60.0 * m1;
842 return mg1ps_finish(lambda, rho, m1, std::numeric_limits<double>::quiet_NaN(), bhat, bhat, denom,
843 opt.pdf, ymax, false, opt);
844}
845
846} // namespace qsys
847} // namespace line
848
849#endif // LINE_API_QSYS_QSYS_MG1_PS_H
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
The exception types the port throws.
Matrix exponential by scaling and squaring with a diagonal Pade approximant.
Numerical inversion of a Laplace transform: Euler, Talbot, Gaver-Stehfest.
LU factorization with partial pivoting, templated on the number type.
Dense matrix and non-owning view.
std::vector< Cplx > euler_get_omega(std::size_t n)
Euler weights: eta, alternating in sign, scaled by 10^((n-1)/6).
std::vector< Cplx > euler_get_alpha(std::size_t n)
Euler nodes: a vertical line at Re = (n-1) log(10) / 6.
Mg1PsResult qsys_mg1_ps(double lambda, const std::vector< double > &alpha, const Matrix< double > &Tmat, const Mg1PsOptions &opt)
Sojourn-time distribution of the M/G/1 processor-sharing queue.
std::complex< double > Cplx
Definition qsys_mg1_ps.h:90
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
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 > expm(const Matrix< T > &A)
Matrix exponential exp(A).
Definition expm.h:141
Number-type abstraction for the templated API port.
Shared scalar machinery for the integration / asymptotic members of the pfqn family (pfqn_le,...
Options of qsys_mg1_ps, mirroring the reference's name-value pairs.
Definition qsys_mg1_ps.h:93
std::function< double(double)> pdf
Service density, needed to remove the conditioning on a callback path.
Definition qsys_mg1_ps.h:99
std::vector< double > tagAlpha
Initial vector of the TAGGED job's requirement, PH(tagAlpha, T), on the phase-type path only (empty: ...
std::vector< double > s
transform arguments to tabulate the LST at
Definition qsys_mg1_ps.h:95
std::vector< double > t
times to evaluate the sojourn distribution at
Definition qsys_mg1_ps.h:96
std::size_t nterms
function evaluations per numerical inversion, ODD
Definition qsys_mg1_ps.h:97
std::vector< double > x
service requirements to condition on
Definition qsys_mg1_ps.h:94
Everything qsys_mg1_ps returns.
Matrix< double > lstCondVal
(|x| x |s|)
std::function< Cplx(Cplx)> lstUncond
s -> E[exp(-s V)]
std::vector< double > lstUncondVal
std::vector< double > meanCond
double atomUncond
(1-rho) bhat(lambda)
Matrix< double > cdfCond
(|x| x |t|)
std::function< Cplx(Cplx, double)> lstCond
(s,x) -> E[exp(-s V(x))]
std::function< Cplx(Cplx, double)> lstExcess
(s,x) -> E[exp(-s (V(x)-x))]
std::vector< double > cdfUncond
std::vector< double > m2Cond
std::vector< double > s
std::vector< double > varCond
std::vector< double > pdfUncond
std::vector< double > x
std::function< Cplx(Cplx)> dominantRoot
s -> tau*(s)
Matrix< double > pdfCond
std::vector< double > t
std::vector< double > atomCond
(1-rho) exp(-lambda x), at t = x