LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
qsys_mg1_srpt.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_SRPT_H
6#define LINE_API_QSYS_QSYS_MG1_SRPT_H
7
8/**
9 * @file
10 * @ingroup api_qsys
11 * M/G/1 under SRPT (shortest remaining processing time), by the
12 * Schrage-Miller formula.
13 *
14 * Templated port of matlab/src/api/qsys/qsys_mg1_srpt.m, cross-checked against
15 * jar/src/main/java/jline/api/qsys/Qsys_mg1_srpt.java.
16 *
17 * For a job of size x, with f the mixture size density and Fbar its tail,
18 *
19 * rho(x) = lambda int_0^x t f(t) dt
20 * m2(x) = int_0^x t^2 f(t) dt
21 * E[W(x)] = lambda (m2(x) + x^2 Fbar(x)) / (2 (1-rho(x))^2)
22 * E[R(x)] = int_0^x dt/(1-rho(t))
23 * E[T(x)] = E[W(x)] + E[R(x)]
24 *
25 * and the class mean is int_0^inf E[T(x)] f_r(x) dx. Because E[T(x)] depends
26 * on the size alone -- SRPT is size-based, not class-based -- that integral is
27 * exact given the size laws.
28 *
29 * Each class is matched to (mean 1/mu_r, scv cs_r^2) by an exponential when
30 * cs_r = 1, a balanced-means two-phase hyperexponential when cs_r > 1, and a
31 * Tijms mixture of Erlang-(k-1)/Erlang-k when cs_r < 1. A class with cs_r = 0
32 * is a point mass, and any such class sends the call to the exact quadrature
33 * of qsys_sizequad.h (Mode::SRPT), since the size law then has an atom. The integrals are
34 * evaluated by cumulative trapezoid quadrature on the same fixed grid MATLAB
35 * builds: 40 e-foldings of the slowest phase, and at least 20000 points, or
36 * 200 per unit of phase-rate spread. That grid, not the formula, sets the
37 * accuracy -- the trapezoid rule on a uniform grid of N points is O(N^-2), so
38 * the reference itself carries an error of order 1e-6 relative, and the port
39 * matches it point for point rather than integrating better.
40 *
41 * ARITHMETIC. exp, log and the trapezoid rule make this transcendental.
42 */
43
44#include <algorithm>
45#include <cmath>
46#include <cstddef>
47#include <vector>
48
53#include "line/num/number.h"
54#include "line/util/error.h"
55
56namespace line {
57namespace qsys {
58
59namespace detail {
60
61/** Job-size law matched to a mean and an SCV, as in MATLAB's local srpt_fit. */
62template <class T>
63struct SrptFit {
64 enum Kind { EXPONENTIAL, HYPEREXP2, ERLANG_MIX } kind = EXPONENTIAL;
65 T rate; ///< EXPONENTIAL and ERLANG_MIX
66 T p; ///< branch probability for HYPEREXP2 and ERLANG_MIX
67 T r1, r2; ///< HYPEREXP2 phase rates
68 unsigned k = 0; ///< ERLANG_MIX larger shape
69 T rate_min, rate_max;
70};
71
72template <class T>
73SrptFit<T> srpt_fit(const T& mu, const T& cs) {
74 const T one = num_traits<T>::from_int(1);
75 const T two = num_traits<T>::from_int(2);
76 const T half = num_traits<T>::from_rational(1, 2);
77 const T c2 = cs * cs;
78 SrptFit<T> f;
79 if (num_abs(T(c2 - one)) < T(num_traits<T>::from_double(1e-9))) {
80 f.kind = SrptFit<T>::EXPONENTIAL;
81 f.rate = mu;
82 f.rate_min = mu;
83 f.rate_max = mu;
84 } else if (c2 > one) {
85 const T pr = half * (one + num_sqrt(T((c2 - one) / (c2 + one))));
86 f.kind = SrptFit<T>::HYPEREXP2;
87 f.p = pr;
88 f.r1 = two * pr * mu;
89 f.r2 = two * (one - pr) * mu;
90 f.rate_min = num_min(f.r1, f.r2);
91 f.rate_max = f.r1 < f.r2 ? f.r2 : f.r1;
92 } else {
93 const double inv = 1.0 / num_traits<T>::to_double(c2);
94 const unsigned k = static_cast<unsigned>(std::ceil(inv));
95 const T kt = num_traits<T>::from_int(static_cast<long>(k));
96 const T pr = (one / (one + c2)) * (kt * c2 - num_sqrt(T(kt * (one + c2) - kt * kt * c2)));
97 f.kind = SrptFit<T>::ERLANG_MIX;
98 f.k = k;
99 f.p = pr;
100 f.rate = (kt - pr) * mu; // mean_x = 1/mu, so (k-p)/mean_x = (k-p) mu
101 f.rate_min = f.rate;
102 f.rate_max = f.rate;
103 }
104 return f;
105}
106
107/** log(m!) by summation, standing in for MATLAB's gammaln(m+1). */
108template <class T>
109T log_factorial(unsigned m) {
110 T s = num_traits<T>::from_int(0);
111 for (unsigned j = 2; j <= m; ++j) {
112 using std::log;
113 s += log(num_traits<T>::from_int(static_cast<long>(j)));
114 }
115 return s;
116}
117
118/** Erlang-n density with the given rate, in log space as in MATLAB. */
119template <class T>
120T erlang_pdf(unsigned n, const T& rate, const T& x) {
121 const T zero = num_traits<T>::from_int(0);
122 if (n == 0) return zero;
123 const T t = rate * x;
124 const unsigned m = n - 1;
125 if (t <= zero) return m == 0 ? rate : zero;
126 using std::log;
127 const T logp = num_traits<T>::from_int(static_cast<long>(m)) * log(t) - t - log_factorial<T>(m);
128 return rate * num_exp(logp);
129}
130
131/** Erlang-n complementary CDF, the upper Poisson tail, in log space. */
132template <class T>
133T erlang_tail(unsigned n, const T& rate, const T& x) {
134 const T zero = num_traits<T>::from_int(0);
135 if (n == 0) return zero;
136 const T t = rate * x;
137 if (t <= zero) return num_traits<T>::from_int(1);
138 using std::log;
139 T y = zero;
140 const T logt = log(t);
141 for (unsigned j = 0; j < n; ++j)
142 y += num_exp(T(num_traits<T>::from_int(static_cast<long>(j)) * logt - t -
143 log_factorial<T>(j)));
144 return y;
145}
146
147template <class T>
148T srpt_pdf(const SrptFit<T>& f, const T& x) {
149 const T one = num_traits<T>::from_int(1);
150 switch (f.kind) {
151 case SrptFit<T>::EXPONENTIAL:
152 return f.rate * num_exp(T(-f.rate * x));
153 case SrptFit<T>::HYPEREXP2:
154 return f.p * f.r1 * num_exp(T(-f.r1 * x)) +
155 (one - f.p) * f.r2 * num_exp(T(-f.r2 * x));
156 default:
157 return f.p * erlang_pdf(f.k - 1, f.rate, x) +
158 (one - f.p) * erlang_pdf(f.k, f.rate, x);
159 }
160}
161
162template <class T>
163T srpt_tail(const SrptFit<T>& f, const T& x) {
164 const T one = num_traits<T>::from_int(1);
165 switch (f.kind) {
166 case SrptFit<T>::EXPONENTIAL:
167 return num_exp(T(-f.rate * x));
168 case SrptFit<T>::HYPEREXP2:
169 return f.p * num_exp(T(-f.r1 * x)) + (one - f.p) * num_exp(T(-f.r2 * x));
170 default:
171 return f.p * erlang_tail(f.k - 1, f.rate, x) +
172 (one - f.p) * erlang_tail(f.k, f.rate, x);
173 }
174}
175
176} // namespace detail
177
178/**
179 * @brief M/G/1 under SRPT (shortest remaining processing time), by the
180 * Schrage-Miller formula.
181 *
182 * @param lambda per-class arrival rates
183 * @param mu per-class service rates
184 * @param cs per-class coefficients of variation of the service time
185 */
186template <class T>
187Mg1DisciplineResult<T> qsys_mg1_srpt(const std::vector<T>& lambda, const std::vector<T>& mu,
188 const std::vector<T>& cs) {
190 "qsys_mg1_srpt requires transcendental arithmetic");
191 detail::mg1_discipline_check("qsys_mg1_srpt", lambda, mu, cs);
192 const std::size_t K = lambda.size();
193 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
194 const T two = num_traits<T>::from_int(2);
195
196 T lambda_total = zero;
197 for (const T& v : lambda) lambda_total += v;
198 std::vector<T> p(K);
199 for (std::size_t i = 0; i < K; ++i) p[i] = lambda[i] / lambda_total;
200
201 bool any_det = false;
202 for (const T& c : cs) any_det = any_det || num_traits<T>::to_double(c) == 0.0;
203 if (any_det) {
204 // A deterministic class puts an atom in the size law, which the grid
205 // below cannot carry (the Tijms fit needs cs > 0, and the trapezoid
206 // rule smears the jump of rho(x)). Use the exact quadrature over the
207 // same two-moment laws plus the point mass, with rho-(x) and rho+(x)
208 // at an atom (equal sizes served FCFS), as MATLAB does; in double.
209 std::vector<double> l(K), m(K), c(K);
210 for (std::size_t i = 0; i < K; ++i) {
211 l[i] = num_traits<T>::to_double(lambda[i]);
212 m[i] = num_traits<T>::to_double(mu[i]);
213 c[i] = num_traits<T>::to_double(cs[i]);
214 }
215 const std::vector<double> Wd = sizequad::solve(l, m, c, sizequad::Mode::SRPT);
217 rd.W.assign(K, zero);
218 for (std::size_t k = 0; k < K; ++k) rd.W[k] = T(num_traits<T>::from_double(Wd[k]));
219 rd.rhohat = detail::mg1_discipline_rhohat(lambda, rd.W);
220 return rd;
221 }
222
223 std::vector<detail::SrptFit<T>> fits;
224 fits.reserve(K);
225 T rate_min = zero, rate_max = zero;
226 for (std::size_t r = 0; r < K; ++r) {
227 fits.push_back(detail::srpt_fit(mu[r], cs[r]));
228 if (r == 0 || fits[r].rate_min < rate_min) rate_min = fits[r].rate_min;
229 if (r == 0 || fits[r].rate_max > rate_max) rate_max = fits[r].rate_max;
230 }
231 if (rate_min <= zero) throw NumericError(ErrorKind{"Degenerate"}, "qsys_mg1_srpt: degenerate phase rate");
232
233 // Grid: 40 e-foldings of the slowest phase, 200 points per rate ratio.
234 T xmax = num_traits<T>::from_int(40) / rate_min;
235 for (std::size_t r = 0; r < K; ++r) {
236 if (fits[r].kind != detail::SrptFit<T>::ERLANG_MIX) continue;
237 // An Erlang-k phase rate does not bound the law, whose mass sits
238 // near k/rate: also cover k + 15 sqrt(k) phases, or the grid ends
239 // before the mean once k > 40 (cs < 0.16 gave W ~ 0).
240 const double kd = static_cast<double>(fits[r].k);
241 const T xr = num_traits<T>::from_double(kd + 15.0 * std::sqrt(kd)) / fits[r].rate;
242 if (xr > xmax) xmax = xr;
243 }
244 const double ratio = num_traits<T>::to_double(rate_max) / num_traits<T>::to_double(rate_min);
245 std::size_t N = static_cast<std::size_t>(std::ceil(200.0 * ratio));
246 if (N < 20000u) N = 20000u;
247 if (N > 2000000u) N = 2000000u;
248
249 std::vector<T> x(N + 1), fmix(N + 1, zero), Fbar(N + 1, zero);
250 for (std::size_t i = 0; i <= N; ++i)
251 x[i] = xmax * num_traits<T>::from_int(static_cast<long>(i)) /
252 num_traits<T>::from_int(static_cast<long>(N));
253 for (std::size_t r = 0; r < K; ++r)
254 for (std::size_t i = 0; i <= N; ++i) {
255 fmix[i] += p[r] * detail::srpt_pdf(fits[r], x[i]);
256 Fbar[i] += p[r] * detail::srpt_tail(fits[r], x[i]);
257 }
258
259 std::vector<T> xf(N + 1), x2f(N + 1);
260 for (std::size_t i = 0; i <= N; ++i) {
261 xf[i] = x[i] * fmix[i];
262 x2f[i] = x[i] * x[i] * fmix[i];
263 }
264 std::vector<T> rho_x = detail::num_cumtrapz(x, xf);
265 for (T& v : rho_x) v *= lambda_total;
266 const std::vector<T> m2_x = detail::num_cumtrapz(x, x2f);
267
268 // Guard the (1-rho(x)) factors; rho(x) -> rho < 1 as x -> inf.
269 const T floor_ = T(num_traits<T>::from_double(1e-12));
270 std::vector<T> denom(N + 1), invden(N + 1), ET(N + 1);
271 for (std::size_t i = 0; i <= N; ++i) {
272 const T d = one - rho_x[i];
273 denom[i] = d > floor_ ? d : floor_;
274 invden[i] = one / denom[i];
275 }
276 const std::vector<T> Res = detail::num_cumtrapz(x, invden);
277 for (std::size_t i = 0; i <= N; ++i)
278 ET[i] = lambda_total * (m2_x[i] + x[i] * x[i] * Fbar[i]) / (two * denom[i] * denom[i]) +
279 Res[i];
280
282 r.W.assign(K, zero);
283 std::vector<T> integrand(N + 1);
284 for (std::size_t c = 0; c < K; ++c) {
285 for (std::size_t i = 0; i <= N; ++i) integrand[i] = ET[i] * detail::srpt_pdf(fits[c], x[i]);
286 r.W[c] = detail::num_trapz(x, integrand);
287 }
288 r.rhohat = detail::mg1_discipline_rhohat(lambda, r.W);
289 return r;
290}
291
292} // namespace qsys
293} // namespace line
294
295#endif // LINE_API_QSYS_QSYS_MG1_SRPT_H
NumericError(const std::string &what)
Definition error.h:112
The exception types the port throws.
std::vector< double > solve(const std::vector< double > &lambda, const std::vector< double > &mu, const std::vector< double > &cs, Mode mode)
Mg1DisciplineResult< T > qsys_mg1_srpt(const std::vector< T > &lambda, const std::vector< T > &mu, const std::vector< T > &cs)
M/G/1 under SRPT (shortest remaining processing time), by the Schrage-Miller formula.
Mat inv(const Mat &A)
Definition spn_ispn.h:253
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
T num_abs(const T &v)
Definition number.h:184
Number-type abstraction for the templated API port.
M/G/1 under SETF (shortest elapsed time first), the non-preemptive counterpart of FB/LAS.
Adaptive quadrature for the qsys functions whose MATLAB originals call integral(),...
Per-class mean response time of an M/G/1 queue under FB, PSJF or SRPT for general job sizes.
Shared return type and arithmetic helpers for the templated qsys port.
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
std::vector< T > W
per-class mean response time
T rhohat
Q/(1+Q) with Q = sum_k lambda_k W_k.