LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
qsys_mg1_sjf.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_SJF_H
6#define LINE_API_QSYS_QSYS_MG1_SJF_H
7
8/**
9 * @file
10 * @ingroup api_qsys
11 * M/G/1 with non-preemptive shortest-job-first scheduling: per-class mean
12 * response times.
13 *
14 * Port of matlab/src/api/qsys/qsys_mg1_sjf.m. A job of size x waits
15 *
16 * W(x) = (lambda E[S^2]/2) / (1 - rho(x))^2, rho(x) = lambda int_0^x t f(t) dt,
17 *
18 * (Phipps, 1956), and the class mean averages W(x) over the class's size law.
19 * Each class's size law is the reference's two-moment fit (exponential,
20 * balanced-means H2 above cs = 1, an Erlang mixture below), and both integrals
21 * are the reference's trapezoidal rules on the same uniform grid, so the
22 * numbers agree with MATLAB to rounding.
23 *
24 * ARITHMETIC: double, as the reference.
25 */
26
27#include <algorithm>
28#include <cmath>
29#include <cstddef>
30#include <limits>
31#include <vector>
32
35#include "line/util/error.h"
36
37namespace line {
38namespace qsys {
39
40namespace sjfdetail {
41
42/** The reference's sjf_fit: exponential, H2 or Erlang mixture by cs^2. */
43struct SjfFit {
44 int type = 0; // 0 exp, 1 h2, 2 erlmix
45 double rate = 0, p = 0, r1 = 0, r2 = 0, rate_min = 0, rate_max = 0;
46 int k = 0;
47};
48
49inline SjfFit sjf_fit(double mu, double cs) {
50 SjfFit f;
51 const double mean_x = 1.0 / mu;
52 const double c2 = cs * cs;
53 if (std::fabs(c2 - 1.0) < 1e-9) {
54 f.type = 0;
55 f.rate = f.rate_min = f.rate_max = mu;
56 } else if (c2 > 1.0) {
57 const double pr = 0.5 * (1.0 + std::sqrt((c2 - 1.0) / (c2 + 1.0)));
58 f.type = 1;
59 f.p = pr;
60 f.r1 = 2.0 * pr * mu;
61 f.r2 = 2.0 * (1.0 - pr) * mu;
62 f.rate_min = std::min(f.r1, f.r2);
63 f.rate_max = std::max(f.r1, f.r2);
64 } else {
65 const int k = static_cast<int>(std::ceil(1.0 / c2));
66 const double pr = (1.0 / (1.0 + c2)) * (k * c2 - std::sqrt(k * (1.0 + c2) - static_cast<double>(k) * k * c2));
67 f.type = 2;
68 f.k = k;
69 f.p = pr;
70 f.rate = f.rate_min = f.rate_max = (k - pr) / mean_x;
71 }
72 return f;
73}
74
75/** Erlang(n, rate) density at x, in the reference's log-Poisson form. */
76inline double erlang_pdf(int n, double rate, double x) {
77 if (n <= 0) return 0.0;
78 const double t = rate * x;
79 const int m = n - 1;
80 double logp;
81 if (t <= 0.0) logp = (m == 0) ? 0.0 : -std::numeric_limits<double>::infinity();
82 else logp = m * std::log(t) - t - std::lgamma(m + 1.0);
83 return rate * std::exp(logp);
84}
85
86inline double sjf_pdf(const SjfFit& f, double x) {
87 switch (f.type) {
88 case 0: return f.rate * std::exp(-f.rate * x);
89 case 1: return f.p * f.r1 * std::exp(-f.r1 * x) + (1.0 - f.p) * f.r2 * std::exp(-f.r2 * x);
90 default: return f.p * erlang_pdf(f.k - 1, f.rate, x) + (1.0 - f.p) * erlang_pdf(f.k, f.rate, x);
91 }
92}
93
94} // namespace sjfdetail
95
96/** MATLAB's [W, rho_total, res] outputs. */
98 std::vector<double> W; ///< per-class mean response time
99 double rhohat = 0; ///< Q/(1+Q), MATLAB's rho_total
100 QsysRes res; ///< meanSojournTime, meanWaitingTime, meanQueueLength, utilization, conservationResidual, analyzer
101};
102
103/**
104 * @brief M/G/1 non-preemptive SJF.
105 *
106 * @param lambda per-class arrival rates
107 * @param mu per-class service rates
108 * @param cs per-class coefficients of variation of the service time
109 */
110inline Mg1SjfResult qsys_mg1_sjf(const std::vector<double>& lambda, const std::vector<double>& mu,
111 const std::vector<double>& cs) {
112 using namespace sjfdetail;
113 const std::size_t K = lambda.size();
114 if (mu.size() != K || cs.size() != K)
115 throw InputError(ErrorKind("Argument"), "qsys_mg1_sjf: lambda, mu and cs must have the same length");
116 for (std::size_t r = 0; r < K; ++r)
117 if (!(lambda[r] > 0.0) || !(mu[r] > 0.0) || !(cs[r] >= 0.0))
118 throw InputError(ErrorKind("Argument"), "qsys_mg1_sjf: lambda and mu must be positive, cs non-negative");
119 double lambda_total = 0.0, rho_util = 0.0, lES2 = 0.0;
120 for (std::size_t r = 0; r < K; ++r) {
121 lambda_total += lambda[r];
122 rho_util += lambda[r] / mu[r];
123 lES2 += lambda[r] * (1.0 + cs[r] * cs[r]) / (mu[r] * mu[r]);
124 }
125 if (rho_util >= 1.0) resdetail::throw_unstable("qsys_mg1_sjf", "rho", rho_util);
126 bool any_det = false;
127 for (std::size_t r = 0; r < K; ++r) any_det = any_det || cs[r] == 0.0;
128 if (any_det) {
129 // A deterministic class puts an atom in the size law, which the grid
130 // below cannot carry (the Tijms fit needs cs > 0, and the trapezoid
131 // rule smears the jump of rho(x)). Use the exact quadrature over the
132 // same two-moment laws plus the point mass, with rho-(x) and rho+(x)
133 // at an atom (equal sizes served FCFS, Cobham), as MATLAB does.
134 const std::vector<double> Wqd = sizequad::solve(lambda, mu, cs, sizequad::Mode::SJF);
135 const std::vector<double> xW = sizequad::solve(lambda, mu, cs, sizequad::Mode::SJFX);
136 Mg1SjfResult od;
137 std::vector<double> Qd(K);
138 od.W.assign(K, 0.0);
139 double Qs = 0.0, sx = 0.0;
140 for (std::size_t r = 0; r < K; ++r) {
141 od.W[r] = Wqd[r] + 1.0 / mu[r];
142 Qd[r] = lambda[r] * od.W[r];
143 Qs += Qd[r];
144 sx += lambda[r] * xW[r];
145 }
146 od.rhohat = Qs / (1.0 + Qs);
147 od.res.set("meanSojournTime", od.W);
148 od.res.set("meanWaitingTime", Wqd);
149 od.res.set("meanQueueLength", Qd);
150 od.res.set("utilization", rho_util);
151 od.res.set("conservationResidual", sx - rho_util * lES2 / (2.0 * (1.0 - rho_util)));
152 od.res.analyzer = "exact:M/G/1-SJF";
153 return od;
154 }
155 std::vector<SjfFit> fits(K);
156 double rate_min = std::numeric_limits<double>::infinity(), rate_max = 0.0;
157 for (std::size_t r = 0; r < K; ++r) {
158 fits[r] = sjf_fit(mu[r], cs[r]);
159 rate_min = std::min(rate_min, fits[r].rate_min);
160 rate_max = std::max(rate_max, fits[r].rate_max);
161 }
162 double xmax = 40.0 / rate_min;
163 for (std::size_t r = 0; r < K; ++r) {
164 if (fits[r].type != 2) continue;
165 // An Erlang-k phase rate does not bound the law, whose mass sits
166 // near k/rate: also cover k + 15 sqrt(k) phases, or the grid ends
167 // before the mean once k > 40 (cs < 0.16 gave W ~ 0).
168 xmax = std::max(xmax, (fits[r].k + 15.0 * std::sqrt(static_cast<double>(fits[r].k))) / fits[r].rate);
169 }
170 const long N = std::min(2000000L, std::max(20000L, static_cast<long>(std::ceil(200.0 * rate_max / rate_min))));
171 const std::size_t np = static_cast<std::size_t>(N) + 1;
172 std::vector<double> x(np), fmix(np, 0.0);
173 // linspace(0, xmax, N+1), as MATLAB computes it
174 for (std::size_t i = 0; i < np; ++i) x[i] = xmax * static_cast<double>(i) / static_cast<double>(N);
175 x[np - 1] = xmax;
176 std::vector<std::vector<double>> pdf(K, std::vector<double>(np));
177 for (std::size_t r = 0; r < K; ++r) {
178 const double p = lambda[r] / lambda_total;
179 for (std::size_t i = 0; i < np; ++i) {
180 pdf[r][i] = sjf_pdf(fits[r], x[i]);
181 fmix[i] += p * pdf[r][i];
182 }
183 }
184 // rho_x = lambda_total * cumtrapz(x, x .* fmix)
185 std::vector<double> Wx(np);
186 double cum = 0.0;
187 for (std::size_t i = 0; i < np; ++i) {
188 if (i > 0) cum += 0.5 * (x[i] - x[i - 1]) * (x[i] * fmix[i] + x[i - 1] * fmix[i - 1]);
189 const double denom = std::max(1.0 - lambda_total * cum, 1e-12);
190 Wx[i] = (lES2 / 2.0) / (denom * denom);
191 }
192 auto trapz = [&](const std::vector<double>& y) {
193 double s = 0.0;
194 for (std::size_t i = 1; i < np; ++i) s += 0.5 * (x[i] - x[i - 1]) * (y[i] + y[i - 1]);
195 return s;
196 };
197 Mg1SjfResult out;
198 std::vector<double> Wq(K), Qi(K), y(np);
199 out.W.assign(K, 0.0);
200 double Q = 0.0;
201 for (std::size_t r = 0; r < K; ++r) {
202 for (std::size_t i = 0; i < np; ++i) y[i] = Wx[i] * pdf[r][i];
203 Wq[r] = trapz(y);
204 out.W[r] = Wq[r] + 1.0 / mu[r];
205 Qi[r] = lambda[r] * out.W[r];
206 Q += Qi[r];
207 }
208 out.rhohat = Q / (1.0 + Q);
209 for (std::size_t i = 0; i < np; ++i) y[i] = x[i] * fmix[i] * Wx[i];
210 out.res.set("meanSojournTime", out.W);
211 out.res.set("meanWaitingTime", Wq);
212 out.res.set("meanQueueLength", Qi);
213 out.res.set("utilization", rho_util);
214 out.res.set("conservationResidual", lambda_total * trapz(y) - rho_util * lES2 / (2.0 * (1.0 - rho_util)));
215 out.res.analyzer = "exact:M/G/1-SJF";
216 return out;
217}
218
219} // namespace qsys
220} // namespace line
221
222#endif // LINE_API_QSYS_QSYS_MG1_SJF_H
InputError(const std::string &what)
Definition error.h:105
The exception types the port throws.
void throw_unstable(const char *fn, const char *what, double v)
A LINE:input:Unstable refusal "fn: unstable system: <what> = %g >= 1".
Definition qsys_res.h:213
std::vector< double > solve(const std::vector< double > &lambda, const std::vector< double > &mu, const std::vector< double > &cs, Mode mode)
double erlang_pdf(int n, double rate, double x)
Erlang(n, rate) density at x, in the reference's log-Poisson form.
SjfFit sjf_fit(double mu, double cs)
double sjf_pdf(const SjfFit &f, double x)
Mg1SjfResult qsys_mg1_sjf(const std::vector< double > &lambda, const std::vector< double > &mu, const std::vector< double > &cs)
M/G/1 non-preemptive SJF.
QsysResT< double > QsysRes
Definition qsys_res.h:96
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
The res struct the exact queueing-system functions return, and the numeric helpers those functions sh...
Per-class mean response time of an M/G/1 queue under FB, PSJF or SRPT for general job sizes.
ErrorKind(std::string n)
Definition error.h:39
MATLAB's [W, rho_total, res] outputs.
QsysRes res
meanSojournTime, meanWaitingTime, meanQueueLength, utilization, conservationResidual,...
double rhohat
Q/(1+Q), MATLAB's rho_total.
std::vector< double > W
per-class mean response time
std::string analyzer
Definition qsys_res.h:59
void set(const std::string &name, const T &v)
Sets (or overwrites) a scalar field.
Definition qsys_res.h:62
The reference's sjf_fit: exponential, H2 or Erlang mixture by cs^2.