LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
qsys_mmck.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_MMCK_H
6#define LINE_API_QSYS_QSYS_MMCK_H
7
8/**
9 * @file
10 * @ingroup api_qsys
11 * Exact analysis of the M/M/c/K queue (truncated Erlang form).
12 *
13 * Templated port of matlab/src/api/qsys/qsys_mmck.m, cross-checked against
14 * jar/src/main/java/jline/api/qsys/Qsys_mmck.java.
15 *
16 * a = lambda/mu, rho = a/c
17 * p_n = a^n/n! p_0 0 <= n <= c
18 * p_n = a^c/c! rho^(n-c) p_0 c <= n <= K
19 * p_0 = 1 / [ sum_{n<c} a^n/n! + (a^c/c!) sum_{n=0}^{K-c} rho^n ]
20 *
21 * All exponents are integers and the normalization is a finite sum, so the
22 * whole computation stays in the field of the inputs and is exact for
23 * T = Rational. The exact instantiation is not academic here: MATLAB builds
24 * the unnormalized vector as a^n/n! and warns about overflow, which is the
25 * failure mode for large a and K; in rational arithmetic the intermediate
26 * magnitudes are irrelevant.
27 *
28 * Unlike the unbounded M/M/c, no stability condition is needed: a finite
29 * capacity makes every load admissible, rho >= 1 included.
30 */
31
32#include <cstddef>
33#include <vector>
34
37#include "line/num/number.h"
38#include "line/util/error.h"
39
40namespace line {
41namespace qsys {
42
43template <class T>
44struct MmckResult {
45 T meanQueueLength; ///< L, mean number in system
46 T meanQueueLengthQ; ///< Lq, mean number waiting
47 T meanWaitingTime; ///< Wq = Lq/lambda_eff
48 T meanSojournTime; ///< W = L /lambda_eff
49 T utilization; ///< per-server utilization lambda_eff/(c mu)
50 T throughput; ///< lambda_eff = lambda (1 - p_K)
51 T lossProbability; ///< p_K
52 std::vector<T> queueLengthDist; ///< p_0 ... p_K
53 T varQueueLength; ///< variance of the number in system
54 std::vector<T> arrivalDist; ///< Pi_n = p_n/(1-p_K), n = 0..K-1, seen by admitted arrivals
55 T probWait; ///< P(an admitted arrival waits)
56 T condMeanWaitingTime; ///< E[W | W > 0], 0 when no arrival waits
57 T varWaitingTime; ///< Var[W] from the Erlang(m, c mu) mixture
58 T varSojournTime; ///< Var[W] + 1/mu^2
59};
60
61/**
62 * @brief Exact analysis of the M/M/c/K queue (truncated Erlang form).
63 *
64 * @param lambda Poisson arrival rate
65 * @param mu exponential service rate of one server
66 * @param c number of servers, c >= 1
67 * @param K system capacity, K >= c
68 */
69template <class T>
70MmckResult<T> qsys_mmck(const T& lambda, const T& mu, unsigned c, unsigned K) {
71 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
72 if (lambda <= zero) throw InputError("qsys_mmck: lambda must be a positive real scalar");
73 if (mu <= zero) throw InputError("qsys_mmck: mu must be a positive real scalar");
74 if (c < 1) throw InputError("qsys_mmck: c must be a positive integer");
75 if (K < c) throw InputError("qsys_mmck: K must be an integer >= c");
76
77 const T a = lambda / mu;
78 const T rho = a / num_traits<T>::from_int(static_cast<long>(c));
79
80 std::vector<T> p(K + 1, zero);
81 for (unsigned n = 0; n < c; ++n) p[n] = num_pow_int(a, n) / num_factorial<T>(n);
82 const T ac_over_cfact = num_pow_int(a, c) / num_factorial<T>(c);
83 for (unsigned n = c; n <= K; ++n) p[n] = ac_over_cfact * num_pow_int(rho, n - c);
84
85 T S = zero;
86 for (const T& v : p) S += v;
87 if (S <= zero) throw NumericError(ErrorKind{"Degenerate"}, "qsys_mmck: stationary distribution failed to normalize");
88 for (T& v : p) v /= S;
89
91 r.queueLengthDist = p;
92 T L = zero, Lq = zero;
93 for (unsigned n = 0; n <= K; ++n) {
94 L += num_traits<T>::from_int(static_cast<long>(n)) * p[n];
95 if (n > c) Lq += num_traits<T>::from_int(static_cast<long>(n - c)) * p[n];
96 }
97 r.meanQueueLength = L;
98 r.meanQueueLengthQ = Lq;
99 r.lossProbability = p[K];
100 const T lambdaEff = lambda * (one - p[K]);
101 r.throughput = lambdaEff;
102 r.utilization = lambdaEff / (num_traits<T>::from_int(static_cast<long>(c)) * mu);
103 if (lambdaEff > zero) {
104 r.meanWaitingTime = Lq / lambdaEff;
105 r.meanSojournTime = L / lambdaEff;
106 } else {
107 r.meanWaitingTime = zero;
108 r.meanSojournTime = zero;
109 }
110 T EN2 = zero;
111 for (unsigned n = 0; n <= K; ++n) EN2 += num_traits<T>::from_int(static_cast<long>(n) * n) * p[n];
112 r.varQueueLength = EN2 - L * L;
113 r.arrivalDist.resize(K);
114 for (unsigned n = 0; n < K; ++n) r.arrivalDist[n] = p[n] / (one - p[K]);
115 // an admitted arrival finding nw >= c jobs waits Erlang(nw-c+1, c mu)
116 const T theta = num_traits<T>::from_int(static_cast<long>(c)) * mu;
117 T probWait = zero, EW2 = zero;
118 for (unsigned nw = c; nw + 1 <= K; ++nw) {
119 const long m = static_cast<long>(nw - c + 1);
120 probWait += r.arrivalDist[nw];
121 EW2 += r.arrivalDist[nw] * num_traits<T>::from_int(m * (m + 1));
122 }
123 EW2 /= theta * theta;
124 r.probWait = probWait;
125 r.condMeanWaitingTime = probWait > zero ? T(r.meanWaitingTime / probWait) : zero;
127 r.varSojournTime = r.varWaitingTime + one / (mu * mu);
128 return r;
129}
130
131/**
132 * @brief The distributional part of qsys_mmck: waiting/sojourn CDFs and percentiles.
133 *
134 * Port of the tPoints/percentiles options of matlab/src/api/qsys/qsys_mmck.m.
135 * An arriving (admitted) job sees the arrival law Pi; one that finds m-1 jobs
136 * waiting waits an Erlang(m, c mu) time, and its sojourn adds an Exp(mu)
137 * service. Returns a `QsysRes` holding the `tPoints`, `waitingTimeCdf`,
138 * `sojournTimeCdf`, `percentiles`, `waitingTimePercentile` and
139 * `sojournTimePercentile` fields the options call for, and `analyzer`.
140 */
141inline QsysRes qsys_mmck_dist(double lambda, double mu, unsigned c, unsigned K,
142 const QsysResOptions& o = QsysResOptions()) {
143 using namespace resdetail;
144 const MmckResult<double> r = qsys_mmck(lambda, mu, c, K);
145 const std::vector<double> Pi = r.arrivalDist;
146 std::vector<double> Piw, m;
147 for (unsigned nw = c; nw + 1 <= K; ++nw) {
148 Piw.push_back(Pi[nw]);
149 m.push_back(static_cast<double>(nw - c + 1));
150 }
151 const double theta = c * mu;
152 const std::function<double(double)> Wccdf = [Piw, m, theta](double t) {
153 if (t < 0.0) return 1.0;
154 double v = 0.0;
155 for (std::size_t i = 0; i < m.size(); ++i) v += Piw[i] * gammainc_upper(theta * t, m[i]);
156 return v;
157 };
158 const std::function<double(double)> Tccdf = [Pi, Piw, m, theta, mu, c](double t) {
159 if (t < 0.0) return 1.0;
160 double s0 = 0.0;
161 for (std::size_t i = 0; i < std::min<std::size_t>(c, Pi.size()); ++i) s0 += Pi[i];
162 double v = s0 * std::exp(-mu * t);
163 if (m.empty()) return v;
164 if (c == 1) {
165 for (std::size_t i = 0; i < m.size(); ++i) v += Piw[i] * gammainc_upper(mu * t, m[i] + 1.0);
166 } else {
167 const double d = theta - mu;
168 for (std::size_t i = 0; i < m.size(); ++i) {
169 const double lower = gammainc_lower(d * t, m[i]);
170 const double cross =
171 lower > 0.0 ? std::exp(m[i] * std::log(theta / d) - mu * t + std::log(lower)) : 0.0;
172 v += Piw[i] * (gammainc_upper(theta * t, m[i]) + cross);
173 }
174 }
175 return v;
176 };
177 QsysRes res;
178 if (!o.tPoints.empty()) {
179 res.set("tPoints", o.tPoints);
180 res.set("waitingTimeCdf", cdf_of(Wccdf, o.tPoints));
181 res.set("sojournTimeCdf", cdf_of(Tccdf, o.tPoints));
182 }
183 if (!o.percentiles.empty()) {
184 for (double p : o.percentiles)
185 if (p <= 0.0 || p >= 100.0) throw Error("qsys_mmck: percentiles must lie in (0, 100)");
186 const double hiT = (K + 50.0) / std::min(mu, theta);
187 res.set("percentiles", o.percentiles);
188 res.set("waitingTimePercentile", pct_of(Wccdf, o.percentiles, hiT));
189 res.set("sojournTimePercentile", pct_of(Tccdf, o.percentiles, hiT));
190 }
191 res.analyzer = "exact:M/M/" + std::to_string(c) + "/" + std::to_string(K);
192 return res;
193}
194
195} // namespace qsys
196} // namespace line
197
198#endif // LINE_API_QSYS_QSYS_MMCK_H
Error(const std::string &what)
Definition error.h:75
InputError(const std::string &what)
Definition error.h:105
NumericError(const std::string &what)
Definition error.h:112
The exception types the port throws.
MmckResult< T > qsys_mmck(const T &lambda, const T &mu, unsigned c, unsigned K)
Exact analysis of the M/M/c/K queue (truncated Erlang form).
Definition qsys_mmck.h:70
QsysResT< double > QsysRes
Definition qsys_res.h:96
QsysRes qsys_mmck_dist(double lambda, double mu, unsigned c, unsigned K, const QsysResOptions &o=QsysResOptions())
The distributional part of qsys_mmck: waiting/sojourn CDFs and percentiles.
Definition qsys_mmck.h:141
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
T num_factorial(unsigned n)
Factorial as a value of T.
Definition number.h:196
T num_pow_int(const T &base, unsigned e)
Integer power, valid in any field (no transcendental requirement).
Definition number.h:204
Number-type abstraction for the templated API port.
The res struct the exact queueing-system functions return, and the numeric helpers those functions sh...
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 > queueLengthDist
p_0 ... p_K
Definition qsys_mmck.h:52
T meanWaitingTime
Wq = Lq/lambda_eff.
Definition qsys_mmck.h:47
T meanQueueLengthQ
Lq, mean number waiting.
Definition qsys_mmck.h:46
T varWaitingTime
Var[W] from the Erlang(m, c mu) mixture.
Definition qsys_mmck.h:57
std::vector< T > arrivalDist
Pi_n = p_n/(1-p_K), n = 0..K-1, seen by admitted arrivals.
Definition qsys_mmck.h:54
T varSojournTime
Var[W] + 1/mu^2.
Definition qsys_mmck.h:58
T meanQueueLength
L, mean number in system.
Definition qsys_mmck.h:45
T utilization
per-server utilization lambda_eff/(c mu)
Definition qsys_mmck.h:49
T varQueueLength
variance of the number in system
Definition qsys_mmck.h:53
T probWait
P(an admitted arrival waits).
Definition qsys_mmck.h:55
T meanSojournTime
W = L /lambda_eff.
Definition qsys_mmck.h:48
T throughput
lambda_eff = lambda (1 - p_K)
Definition qsys_mmck.h:50
T condMeanWaitingTime
E[W | W > 0], 0 when no arrival waits.
Definition qsys_mmck.h:56
The name-value options shared by the exact functions: tPoints, percentiles and nmax (a negative nmax ...
Definition qsys_res.h:102
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