LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
pfqn_mva.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_PFQN_MVA_H
6#define LINE_API_PFQN_MVA_H
7
8/**
9 * @file
10 * @ingroup api_pfqn
11 * Exact Mean Value Analysis for closed product-form networks
12 * (Reiser and Lavenberg 1980).
13 *
14 * Templated port of matlab/src/api/pfqn/pfqn_mva.m, cross-checked against
15 * mp_pfqn's mva/mva-multi.c for the exact path. The recursion over the
16 * population lattice is
17 *
18 * C(i,r|n) = L(i,r) (mi(i) + Q(i|n - e_r))
19 * X(r|n) = n_r / (Z_r + sum_i C(i,r|n))
20 * Q(i,r|n) = X(r|n) C(i,r|n)
21 *
22 * every operation of which stays in the field of the inputs, so the algorithm
23 * is exact in rational arithmetic with no reformulation.
24 *
25 * Normalizing constant: MATLAB accumulates lG as -sum log X along the lattice
26 * path (0 -> N) that fills one class at a time. Logs do not exist in an exact
27 * field, so the port accumulates the product of the reciprocals instead and
28 * takes the log once at the end, of a value that is still exact. The two agree
29 * to rounding in double.
30 */
31
32#include <cstddef>
33#include <vector>
34
35#include "line/num/number.h"
36#include "line/util/error.h"
38#include "line/util/matrix.h"
40
41namespace line {
42namespace pfqn {
43
44template <class T>
45struct MvaResult {
46 std::vector<T> XN; ///< (R) per-class throughput
47 Matrix<T> QN; ///< (M x R) mean queue length
48 Matrix<T> UN; ///< (M x R) utilization
49 Matrix<T> CN; ///< (M x R) residence time
50 T G; ///< normalizing constant
51 double lG; ///< log of the normalizing constant
52};
53
54/**
55 * @brief Exact Mean Value Analysis for closed product-form networks (Reiser
56 * and Lavenberg 1980).
57 *
58 * @param L (M x R) service demands
59 * @param N (R) population per class
60 * @param Z (K x R) think times, summed over rows; empty for no delay
61 * @param mi (M) additive term of the residence-time recursion
62 * C(i,s)=L(i,s)*(mi[i]+Qarv), 1 for a queueing station; empty for all ones.
63 * THIS IS NOT A SERVER COUNT: mi[i]=c inflates the residence time by c
64 * rather than adding c servers. For multiserver stations call
65 * pfqn_mvams(lambda, L, N, Z, mi, S), which passes S to the load-dependent
66 * recursion with mu(i,n)=min(n,S(i)).
67 *
68 * Standard arrival theorem. For the interlocked-flow correction of Franks (1999),
69 * Ch. 4, Eq. (4.7), call pfqn_mva_ilock instead.
70 */
71template <class T>
72MvaResult<T> pfqn_mva(const Matrix<T>& L, const std::vector<int>& N, const Matrix<T>& Z,
73 const std::vector<int>& mi) {
74 const std::size_t M = L.rows();
75 const std::size_t R = N.size();
76 if (!L.empty() && L.cols() != R)
77 throw InputError("pfqn_mva: demand matrix and population vector disagree on the class count");
78 if (!mi.empty() && mi.size() != M)
79 throw InputError("pfqn_mva: multiplicity vector has the wrong length");
80
81 const T zero = num_traits<T>::from_int(0);
82 const T one = num_traits<T>::from_int(1);
83
84 MvaResult<T> res;
85 res.XN.assign(R, zero);
86 res.QN = Matrix<T>(M, R, zero);
87 res.UN = Matrix<T>(M, R, zero);
88 res.CN = Matrix<T>(M, R, zero);
89 res.G = one;
90 res.lG = 0.0;
91
92 bool anyPositive = false;
93 for (int v : N) {
94 if (v < 0) throw InputError("pfqn_mva: negative population");
95 if (v > 0) anyPositive = true;
96 }
97 if (!anyPositive || M == 0) return res; // empty closed population: nothing to compute
98
99 std::vector<T> Zsum(R, zero);
100 if (!Z.empty()) {
101 if (Z.cols() != R) throw InputError("pfqn_mva: Z and N disagree on the class count");
102 for (std::size_t k = 0; k < Z.rows(); ++k)
103 for (std::size_t r = 0; r < R; ++r) Zsum[r] += Z(k, r);
104 }
105
106 std::vector<T> multi(M, one);
107 for (std::size_t i = 0; i < mi.size(); ++i) multi[i] = num_traits<T>::from_int(mi[i]);
108
109 const std::vector<std::size_t> prods = plane_sizes(N);
110 const std::size_t total = population_count(N);
111
112 // lattice indexing rationale: see _kb/03-api-layer.md (cpp port notes: pfqn)
113 std::vector<T> Q(total * M, zero);
114
115 std::vector<int> n(R, 0);
116 bool more = true;
117 std::size_t visited = 0;
118 while (more) {
119 // Wall-clock budget, read every 1024 populations. A recursion cut short
120 // holds the metrics of a smaller population only, which is no answer to
121 // this one, so it raises instead of returning an interim result.
122 if ((++visited & 1023u) == 0)
123 util::timeout_check("Exact MVA (use an approximate method or raise the budget)");
124 int npop = 0;
125 for (int v : n) npop += v;
126 if (npop > 0) {
127 const std::size_t idx = pop_index(n, prods);
128 for (std::size_t s = 0; s < R; ++s) {
129 // empty-class zero-population-row rationale: see _kb/03-api-layer.md (cpp port notes: pfqn)
130 const std::size_t idx_1s = n[s] > 0 ? idx - prods[s] : 0;
131 T ctot = Zsum[s];
132 for (std::size_t i = 0; i < M; ++i) {
133 const T qarv = Q[idx_1s * M + i];
134 res.CN(i, s) = L(i, s) * (multi[i] + qarv);
135 ctot += res.CN(i, s);
136 }
137 // a class with no jobs in this population has no rate, whatever its
138 // demands: a chain of zero population and zero demand is not degenerate
139 if (ctot == zero && n[s] > 0) throw NumericError(ErrorKind{"Degenerate"}, "pfqn_mva: zero total residence time");
140 res.XN[s] = n[s] > 0 ? num_traits<T>::from_int(n[s]) / ctot : zero;
141 for (std::size_t i = 0; i < M; ++i) {
142 res.QN(i, s) = res.XN[s] * res.CN(i, s);
143 Q[idx * M + i] += res.QN(i, s);
144 }
145 }
146
147 // normalizing-constant accumulation rationale: see _kb/03-api-layer.md (cpp port notes: pfqn)
148 long last_nnz = -1;
149 for (long r = static_cast<long>(R) - 1; r >= 0; --r)
150 if (n[r] != 0) {
151 last_nnz = r;
152 break;
153 }
154 if (last_nnz >= 0) {
155 bool prefixFull = true;
156 for (long r = 0; r < last_nnz; ++r)
157 if (n[r] != N[r]) {
158 prefixFull = false;
159 break;
160 }
161 bool suffixEmpty = true;
162 for (std::size_t r = static_cast<std::size_t>(last_nnz) + 1; r < R; ++r)
163 if (n[r] != 0) {
164 suffixEmpty = false;
165 break;
166 }
167 if (prefixFull && suffixEmpty) {
168 const T& x = res.XN[static_cast<std::size_t>(last_nnz)];
169 if (x == zero) throw NumericError(ErrorKind{"Degenerate"}, "pfqn_mva: zero throughput on the G path");
170 res.G /= x;
171 }
172 }
173 }
174 more = next_pop(n, N);
175 }
176
177 for (std::size_t i = 0; i < M; ++i)
178 for (std::size_t r = 0; r < R; ++r) res.UN(i, r) = res.XN[r] * L(i, r);
179
181 return res;
182}
183
184/**
185 * Exact MVA recursion carrying the interlocked-flow correction.
186 *
187 * The correction replaces the arrival theorem term Q(n-1_s,i) by a per-class weighted
188 * sum, so the recursion has to carry per-class queue lengths that pfqn_mva does not
189 * need. Closed single-server models only.
190 *
191 * The discount splits each class's queue at the in-service component, as lqns
192 * MVA::queueOnly_adjusted does: the queue-only part max(ILw*Qc-Uc, 0) is floored at
193 * zero, and the in-service part is discounted on its own as ILw*Uc. Flooring the whole
194 * term at Uc instead cancelled the correction wherever a class holds one customer
195 * (Qc == Uc), i.e. every task-layer chain (BUGS.md BUG-103).
196 * sum_s XN[s]*L(i,s) <= mi[i] is asserted nowhere.
197 *
198 * @param L (M x R) service demands
199 * @param N (R) population per class
200 * @param Z (K x R) think times, summed over rows; empty for no delay
201 * @param mi (M) additive term of the residence-time recursion
202 * C(i,s)=L(i,s)*(mi[i]+Qarv), 1 for a queueing station; empty for all ones.
203 * THIS IS NOT A SERVER COUNT: mi[i]=c inflates the residence time by c
204 * rather than adding c servers. For multiserver stations call
205 * pfqn_mvams(lambda, L, N, Z, mi, S), which passes S to the load-dependent
206 * recursion with mu(i,n)=min(n,S(i)).
207 * @param IL (R x R) interlock matrix of Franks (1999), Eq. (4.7): IL(r,s) is the
208 * share of the class-s queue that a class-r arrival cannot see, because that
209 * work was itself caused by the class-r request.
210 * Required. The model is outside product form under it, so G and lG are not
211 * meaningful and come back as one and zero.
212 */
213template <class T>
214MvaResult<T> pfqn_mva_ilock(const Matrix<T>& L, const std::vector<int>& N, const Matrix<T>& Z,
215 const std::vector<int>& mi, const Matrix<T>& IL) {
216 const std::size_t M = L.rows();
217 const std::size_t R = N.size();
218 if (!L.empty() && L.cols() != R)
219 throw InputError("pfqn_mva_ilock: demand matrix and population vector disagree on the class count");
220 if (!mi.empty() && mi.size() != M)
221 throw InputError("pfqn_mva_ilock: multiplicity vector has the wrong length");
222
223 const T zero = num_traits<T>::from_int(0);
224 const T one = num_traits<T>::from_int(1);
225
226 MvaResult<T> res;
227 res.XN.assign(R, zero);
228 res.QN = Matrix<T>(M, R, zero);
229 res.UN = Matrix<T>(M, R, zero);
230 res.CN = Matrix<T>(M, R, zero);
231 res.G = one;
232 res.lG = 0.0;
233
234 bool anyPositive = false;
235 for (int v : N) {
236 if (v < 0) throw InputError("pfqn_mva_ilock: negative population");
237 if (v > 0) anyPositive = true;
238 }
239 if (!anyPositive || M == 0) return res; // empty closed population: nothing to compute
240
241 std::vector<T> Zsum(R, zero);
242 if (!Z.empty()) {
243 if (Z.cols() != R) throw InputError("pfqn_mva_ilock: Z and N disagree on the class count");
244 for (std::size_t k = 0; k < Z.rows(); ++k)
245 for (std::size_t r = 0; r < R; ++r) Zsum[r] += Z(k, r);
246 }
247
248 std::vector<T> multi(M, one);
249 for (std::size_t i = 0; i < mi.size(); ++i) multi[i] = num_traits<T>::from_int(mi[i]);
250
251 if (IL.empty())
252 throw InputError("pfqn_mva_ilock: an interlock matrix is required; use pfqn_mva for the standard arrival theorem");
253 Matrix<T> ILw;
254 {
255 if (IL.rows() != R || IL.cols() != R)
256 throw InputError("pfqn_mva_ilock: the interlock matrix must be nclasses x nclasses");
257 ILw = Matrix<T>(R, R, zero);
258 for (std::size_t r = 0; r < R; ++r)
259 for (std::size_t s = 0; s < R; ++s) {
260 T w = (r == s) ? one : T(one - IL(r, s));
261 if (w < zero) w = zero;
262 if (w > one) w = one;
263 ILw(r, s) = w;
264 }
265 }
266
267 const std::vector<std::size_t> prods = plane_sizes(N);
268 const std::size_t total = population_count(N);
269
270 // lattice indexing rationale: see _kb/03-api-layer.md (cpp port notes: pfqn)
271 std::vector<T> Q(total * M, zero);
272 // per-class queue lengths, needed by the interlock
273 std::vector<T> Qc(total * M * R, zero);
274 // per-class in-service component, where the interlock splits each queue
275 std::vector<T> Uc(total * M * R, zero);
276
277 std::vector<int> n(R, 0);
278 bool more = true;
279 std::size_t visited = 0;
280 while (more) {
281 // Wall-clock budget, read every 1024 populations. A recursion cut short
282 // holds the metrics of a smaller population only, which is no answer to
283 // this one, so it raises instead of returning an interim result.
284 if ((++visited & 1023u) == 0)
285 util::timeout_check("Exact MVA (use an approximate method or raise the budget)");
286 int npop = 0;
287 for (int v : n) npop += v;
288 if (npop > 0) {
289 const std::size_t idx = pop_index(n, prods);
290 // Arrival-instant queues seen at this level, in full and discounted, as lqns
291 // MVA::queueOnly_adjusted splits them: the queue-only part max(ILw*Qc-Uc, 0)
292 // floored at zero plus the in-service part ILw*Uc.
293 Matrix<T> qfull(M, R, zero), qdisc(M, R, zero);
294 for (std::size_t s = 0; s < R; ++s) {
295 // empty-class zero-population-row rationale: see _kb/03-api-layer.md (cpp port notes: pfqn)
296 const std::size_t idx_1s = n[s] > 0 ? idx - prods[s] : 0;
297 for (std::size_t i = 0; i < M; ++i)
298 for (std::size_t r = 0; r < R; ++r) {
299 const T qc = Qc[(idx_1s * M + i) * R + r];
300 const T inSvc = Uc[(idx_1s * M + i) * R + r];
301 const T wait = T(ILw(s, r) * qc - inSvc);
302 qfull(i, s) += qc;
303 qdisc(i, s) += T((wait > zero ? wait : zero) + ILw(s, r) * inSvc);
304 }
305 }
306 // THE DISCOUNT MAY NOT TAKE A STATION PAST ITS CAPACITY. Two classes that each
307 // remove the other's interlocked share, in service included, break Little's law
308 // at the station: two single-thread tasks on one PS processor reported Util 1.02,
309 // a throughput above the demand bound lqsim sits on (BUGS.md BUG-107). The full
310 // discount is kept where feasible, else the largest feasible fraction of it.
311 auto level = [&](const T& theta, std::vector<T>& X, Matrix<T>& C) -> bool {
312 for (std::size_t s = 0; s < R; ++s) {
313 T ctot = Zsum[s];
314 for (std::size_t i = 0; i < M; ++i) {
315 C(i, s) = L(i, s) * (multi[i] + qfull(i, s) - theta * (qfull(i, s) - qdisc(i, s)));
316 ctot += C(i, s);
317 }
318 if (ctot == zero)
319 throw NumericError(ErrorKind{"Degenerate"}, "pfqn_mva_ilock: zero total residence time");
320 X[s] = num_traits<T>::from_int(n[s]) / ctot;
321 }
322 for (std::size_t i = 0; i < M; ++i) {
323 T u = zero;
324 for (std::size_t s = 0; s < R; ++s) u += X[s] * L(i, s);
325 if (num_traits<T>::to_double(u) > num_traits<T>::to_double(multi[i]) * (1.0 + 1e-12))
326 return false;
327 }
328 return true;
329 };
330 std::vector<T> Xl(R, zero);
331 Matrix<T> Cl(M, R, zero);
332 if (!level(one, Xl, Cl)) {
333 double lo = 0.0, hi = 1.0;
334 for (int it = 0; it < 60; ++it) {
335 const double mid = 0.5 * (lo + hi);
336 if (level(num_traits<T>::from_double(mid), Xl, Cl)) lo = mid;
337 else hi = mid;
338 }
339 level(num_traits<T>::from_double(lo), Xl, Cl);
340 }
341 for (std::size_t s = 0; s < R; ++s) {
342 res.XN[s] = Xl[s];
343 for (std::size_t i = 0; i < M; ++i) {
344 res.CN(i, s) = Cl(i, s);
345 res.QN(i, s) = res.XN[s] * res.CN(i, s);
346 Q[idx * M + i] += res.QN(i, s);
347 Qc[(idx * M + i) * R + s] = res.QN(i, s);
348 Uc[(idx * M + i) * R + s] = res.XN[s] * L(i, s);
349 }
350 }
351
352 // the interlock leaves the model outside product form, so G is never
353 // accumulated and res.G/res.lG keep their neutral initial values
354 }
355 more = next_pop(n, N);
356 }
357
358 for (std::size_t i = 0; i < M; ++i)
359 for (std::size_t r = 0; r < R; ++r) res.UN(i, r) = res.XN[r] * L(i, r);
360
362 return res;
363}
364
365template <class T>
366MvaResult<T> pfqn_mva(const Matrix<T>& L, const std::vector<int>& N, const Matrix<T>& Z) {
367 return pfqn_mva(L, N, Z, std::vector<int>());
368}
369
370template <class T>
371MvaResult<T> pfqn_mva(const Matrix<T>& L, const std::vector<int>& N) {
372 return pfqn_mva(L, N, Matrix<T>(), std::vector<int>());
373}
374
375} // namespace pfqn
376} // namespace line
377
378#endif // LINE_API_PFQN_MVA_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
bool empty() const
Definition matrix.h:92
NumericError(const std::string &what)
Definition error.h:112
The exception types the port throws.
options.timeout: one wall-clock budget per top-level solve, on a per-THREAD deadline stack.
Dense matrix and non-owning view.
MvaResult< T > pfqn_mva(const Matrix< T > &L, const std::vector< int > &N, const Matrix< T > &Z, const std::vector< int > &mi)
Exact Mean Value Analysis for closed product-form networks (Reiser and Lavenberg 1980).
Definition pfqn_mva.h:72
MvaResult< T > pfqn_mva_ilock(const Matrix< T > &L, const std::vector< int > &N, const Matrix< T > &Z, const std::vector< int > &mi, const Matrix< T > &IL)
Exact MVA recursion carrying the interlocked-flow correction.
Definition pfqn_mva.h:214
void timeout_check(const char *where)
The raising checkpoint, for a computation with no valid partial result: throws LINE:numerical:Timeout...
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
std::size_t population_count(const std::vector< int > &N)
Number of population vectors n with 0 <= n <= N.
Definition population.h:38
std::vector< std::size_t > plane_sizes(const std::vector< int > &N)
Mixed-radix plane sizes: prods[r] = prod_{s<r} (N[s]+1).
Definition population.h:27
bool next_pop(std::vector< int > &n, const std::vector< int > &N)
Advance n to the next population vector in the lattice 0 <= n <= N, odometer order with the last clas...
Definition population.h:56
std::size_t pop_index(const std::vector< int > &n, const std::vector< std::size_t > &prods)
Index of n in the lattice, 0-based (MATLAB hashpop is 1-based).
Definition population.h:45
Number-type abstraction for the templated API port.
Population-vector enumeration and combinatorics.
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
std::vector< T > XN
(R) per-class throughput
Definition pfqn_mva.h:46
Matrix< T > QN
(M x R) mean queue length
Definition pfqn_mva.h:47
double lG
log of the normalizing constant
Definition pfqn_mva.h:51
Matrix< T > CN
(M x R) residence time
Definition pfqn_mva.h:49
T G
normalizing constant
Definition pfqn_mva.h:50
Matrix< T > UN
(M x R) utilization
Definition pfqn_mva.h:48