LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
solver_mam_dt.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_SOLVERS_MAM_SOLVER_MAM_DT_H
6#define LINE_SOLVERS_MAM_SOLVER_MAM_DT_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * Port of `solver_mam_dt.m`: discrete-time (slotted) analysis of an open
12 * network whose interarrival and service laws all live on the slot lattice.
13 *
14 * A single queueing station is solved EXACTLY by the Q-MAM discrete-time
15 * queues, `q_dt_ph_ph_1` when both laws are renewal discrete phase-type and
16 * `q_dt_map_map_1` when either side is a D-MAP. Several stations are solved by
17 * a discrete-time parametric decomposition, which is an approximation: the
18 * departure process is truncated at a finite level and compressed back to a
19 * bounded phase dimension, and correlations between the streams entering a
20 * station are not preserved.
21 *
22 * Time is measured in slots internally and converted back on exit, so Q and U
23 * are dimensionless, T is per time unit and R is in time units.
24 *
25 * Convention: late arrival system with delayed access (LAS-DA), matching the
26 * Q-MAM discrete-time queues and the LDES slotted engine. `A_1 = kron(C1,D0)`
27 * is the claim that a job arriving at the end of a slot is not served in it.
28 *
29 * ARITHMETIC: field with transcendentals. The queue solve iterates to a
30 * tolerance, so the analyzer stands down under exact arithmetic exactly as the
31 * MAP/MAP/1 fast path does.
32 */
33
34#include <algorithm>
35#include <cmath>
36#include <cstddef>
37#include <numeric>
38#include <string>
39#include <vector>
40
41#include "line/api/mam/dtime.h"
47#include "line/util/error.h"
48
49namespace line {
50namespace mam {
51
52namespace dt_detail {
53
54/** Rejects the model features the discrete-time path cannot represent. */
55template <class T>
56void assert_scope(const qn::NetworkStruct<T>& sn) {
58 if (!api::sn_is_open_model(sn))
59 throw UnsupportedError(ErrorKind{"ClosedClass"},
60 "SolverMAM: the discrete-time path supports open models only. A closed slotted model "
61 "needs a level-dependent discrete chain, which the Q-MAM discrete-time catalogue does "
62 "not cover.");
63 if (sn.nclasses > 1)
64 throw UnsupportedError(
65 "SolverMAM: the discrete-time path supports one class only. Independent per-class "
66 "lattice sources fire in the same slot with positive probability, and a batch of "
67 "simultaneous arrivals of different classes is not an MMAP[K], which is what "
68 "Q_DT_MMAPK_PHK_1 consumes.");
69 for (std::size_t ist = 0; ist < sn.nstations; ++ist) {
70 const SchedStrategy sched = sn.stations[ist].sched;
71 if (sched == SchedStrategy::EXT) continue;
72 if (sched != SchedStrategy::FCFS)
73 throw UnsupportedError(ErrorKind{"SchedStrategy"},
74 "SolverMAM: the discrete-time path supports FCFS single-server stations and the "
75 "Source only.");
76 if (sn.stations[ist].nservers > 1)
77 throw UnsupportedError(ErrorKind{"MultiServer"},
78 "SolverMAM: the discrete-time path models one server per station; a slotted "
79 "multiserver queue needs the level-dependent boundary of Geo/Geo/c.");
80 }
81}
82
83/**
84 * A DMAP stepping once per time unit, re-expressed on a lattice of m slots per
85 * unit. Each phase i becomes a chain of m sub-phases: the first m-1 advance
86 * deterministically and the last carries the original one-step transition (D0
87 * or D1) into the first sub-phase of the target phase, so an interval of k time
88 * units becomes exactly k*m slots and no event is gained or lost. m = 1 returns
89 * the DMAP unchanged.
90 */
91template <class T>
92Dmap<T> dmap_stretch(const Dmap<T>& D, std::size_t m) {
93 if (m <= 1) return D;
94 const T zero = num_traits<T>::from_int(0);
95 const T one = num_traits<T>::from_int(1);
96 const std::size_t n = D.D0.rows();
97 Dmap<T> out;
98 out.D0 = Matrix<T>(n * m, n * m, zero);
99 out.D1 = Matrix<T>(n * m, n * m, zero);
100 for (std::size_t i = 0; i < n; ++i) {
101 const std::size_t base = i * m;
102 for (std::size_t s = 0; s + 1 < m; ++s) out.D0(base + s, base + s + 1) = one;
103 for (std::size_t j = 0; j < n; ++j) {
104 out.D0(base + m - 1, j * m) = D.D0(i, j);
105 out.D1(base + m - 1, j * m) = D.D1(i, j);
106 }
107 }
108 return out;
109}
110
111/**
112 * Coarsest lattice g*d holding every law: g is the gcd of the per-law slot
113 * counts, 1/d for the laws stepping in whole time units and v/d for Det(v).
114 */
115template <class T>
116double coarsest_slot(const qn::NetworkStruct<T>& sn, double slot_length) {
117 using lang::ProcessType;
118 long g = 0;
119 for (std::size_t ist = 0; ist < sn.nstations; ++ist)
120 for (std::size_t r = 0; r < sn.nclasses; ++r) {
121 const ProcessType pt = sn.procid(ist + 1, r + 1);
122 const double rate = num_traits<T>::to_double(sn.rates(ist, r));
123 if (pt == ProcessType::DISABLED || pt == ProcessType::NONE || sn.disabled[ist][r] ||
124 !std::isfinite(rate) || rate <= 0)
125 continue;
126 const long k = pt == ProcessType::DET ? std::lround(1.0 / (rate * slot_length))
127 : std::lround(1.0 / slot_length);
128 g = std::gcd(g, k);
129 }
130 return g > 1 ? slot_length * static_cast<double>(g) : slot_length;
131}
132
133/**
134 * Discrete-time law of a station, expressed in slots.
135 *
136 * The slot length is the lattice unit, never a rescaling of the law: a
137 * Geometric(p) is the same law here as in every other solver. sn_is_discrete_time
138 * has already checked that each law lies on {d,2d,...}, so Geometric,
139 * DiscreteUniform and DMAP, which step in whole time units, are built on the
140 * unit lattice and stretched by the integral number of slots per unit, and a
141 * Det is built directly from its integral slot count.
142 */
143template <class T>
144Dmap<T> station_law(const qn::NetworkStruct<T>& sn, std::size_t ist, std::size_t r,
145 double slot_length) {
146 using lang::ProcessType;
147 const ProcessType pt = sn.procid(ist + 1, r + 1);
148 const double mean_time = 1.0 / num_traits<T>::to_double(sn.rates(ist, r));
149 const std::size_t unit_slots = static_cast<std::size_t>(std::lround(1.0 / slot_length));
150 if (pt == ProcessType::DMAP) {
151 // the (D0,D1) pair survives verbatim in the struct: it already has MAP shape
152 Dmap<T> d;
153 d.D0 = sn.service[ist][r].D0;
154 d.D1 = sn.service[ist][r].D1;
155 return dmap_stretch(d, unit_slots);
156 }
157 if (pt == ProcessType::DET)
158 return dph_to_dmap(
159 dph_from_dist<T>(pt, num_traits<T>::from_double(mean_time / slot_length), sn.scv(ist, r)));
160 return dmap_stretch(
161 dph_to_dmap(dph_from_dist<T>(pt, num_traits<T>::from_double(mean_time), sn.scv(ist, r))),
162 unit_slots);
163}
164
165/** Exact single-station analysis through the Q-MAM discrete-time queues. */
166template <class T>
167std::vector<T> solve_single_station(const Dmap<T>& arv, const Dmap<T>& svc,
168 std::size_t max_num_comp) {
169 if (dmap_is_renewal(arv) && dmap_is_renewal(svc))
170 return q_dt_ph_ph_1(dmap_to_dph(arv), dmap_to_dph(svc), max_num_comp);
171 return q_dt_map_map_1(arv, svc, max_num_comp);
172}
173
174/**
175 * Station-to-station routing probabilities, source first and sink stripped.
176 *
177 * The Sink feeds back into the Source to keep the routing matrix stochastic; an
178 * open traffic equation must not see that edge. Routers and class switches
179 * carry no service, so their transit is censored into (I - Pnn)^-1.
180 */
181template <class T>
182Matrix<T> routing(const qn::NetworkStruct<T>& sn, std::size_t source_idx,
183 const std::vector<std::size_t>& queue_idx) {
184 using lang::NodeType;
185 const T zero = num_traits<T>::from_int(0);
186 const std::size_t I = sn.nof_nodes(), K = sn.nclasses;
187 Matrix<T> Pn(I, I, zero);
188 for (std::size_t a = 0; a < I; ++a)
189 for (std::size_t b = 0; b < I; ++b) Pn(a, b) = sn.rtnodes(a * K, b * K);
190
191 std::vector<std::size_t> sink_nodes;
192 for (std::size_t ind = 0; ind < I; ++ind)
193 if (sn.nodes[ind].nodetype == NodeType::Sink) {
194 sink_nodes.push_back(ind);
195 for (std::size_t b = 0; b < I; ++b) Pn(ind, b) = zero;
196 }
197
198 std::vector<std::size_t> station_nodes;
199 station_nodes.push_back(sn.station_to_node[source_idx] - 1);
200 for (std::size_t idx = 0; idx < queue_idx.size(); ++idx)
201 station_nodes.push_back(sn.station_to_node[queue_idx[idx]] - 1);
202
203 std::vector<std::size_t> inter_nodes;
204 for (std::size_t ind = 0; ind < I; ++ind) {
205 const bool is_station =
206 std::find(station_nodes.begin(), station_nodes.end(), ind) != station_nodes.end();
207 const bool is_sink = std::find(sink_nodes.begin(), sink_nodes.end(), ind) != sink_nodes.end();
208 if (!is_station && !is_sink) inter_nodes.push_back(ind);
209 }
210
211 auto sub = [&](const std::vector<std::size_t>& rows, const std::vector<std::size_t>& cols) {
212 Matrix<T> out(rows.size(), cols.size(), zero);
213 for (std::size_t a = 0; a < rows.size(); ++a)
214 for (std::size_t b = 0; b < cols.size(); ++b) out(a, b) = Pn(rows[a], cols[b]);
215 return out;
216 };
217
218 const std::size_t ns = station_nodes.size();
219 Matrix<T> full = sub(station_nodes, station_nodes);
220 if (!inter_nodes.empty()) {
221 Matrix<T> Psn = sub(station_nodes, inter_nodes);
222 Matrix<T> Pnn = sub(inter_nodes, inter_nodes);
223 Matrix<T> Pns = sub(inter_nodes, station_nodes);
224 Matrix<T> Inn = detail::dt_eye<T>(inter_nodes.size());
225 Matrix<T> inv = detail::dt_left_solve(detail::dt_sub(Inn, Pnn), Inn);
226 full = detail::dt_add(full, detail::dt_mul(detail::dt_mul(Psn, inv), Pns));
227 }
228 // column 0 is the Source, which receives nothing
229 Matrix<T> P(ns, ns - 1, zero);
230 for (std::size_t a = 0; a < ns; ++a)
231 for (std::size_t b = 1; b < ns; ++b) P(a, b - 1) = full(a, b);
232 return P;
233}
234
235/** Arrival stream of a queue: source share plus thinned upstream departures. */
236template <class T>
237DBatch<T> arrivals(const DBatch<T>& src, const std::vector<DBatch<T>>& dep, const Matrix<T>& P,
238 std::size_t idx, std::size_t space_max) {
239 DBatch<T> arv;
240 bool have = false;
241 if (num_traits<T>::to_double(P(0, idx)) > 0) {
242 arv = dmap_thin(src, P(0, idx));
243 have = true;
244 }
245 for (std::size_t j = 0; j < dep.size(); ++j) {
246 const T p = P(1 + j, idx);
247 if (num_traits<T>::to_double(p) <= 0) continue;
248 DBatch<T> contrib = dmap_thin(dep[j], p);
249 if (!have) {
250 arv = contrib;
251 have = true;
252 } else {
253 arv = dmap_super(arv, contrib);
254 arv = dmap_compress_batch(arv, space_max);
255 }
256 }
257 if (!have)
258 throw InputError(
259 "SolverMAM: a queue receives no arrivals in the discrete-time routing matrix.");
260 return arv;
261}
262
263/** Total visit ratio of a station across the chains. */
264template <class T>
265T visit_ratio(const qn::NetworkStruct<T>& sn, std::size_t ist) {
266 T v = num_traits<T>::from_int(0);
267 for (std::size_t c = 0; c < sn.visits.size(); ++c) {
268 const Matrix<T>& vm = sn.visits[c];
269 if (ist >= vm.rows()) continue;
270 for (std::size_t r = 0; r < vm.cols(); ++r) v = v + vm(ist, r);
271 }
272 return v;
273}
274
275} // namespace dt_detail
276
277/**
278 * Discrete-time analysis of `sn`, returning the same metric tuple as every
279 * other MAM analyzer. `slot_length` is the slot in model time units.
280 */
281template <class T>
283 double slot_length) {
285 const T zero = num_traits<T>::from_int(0);
286 dt_detail::assert_scope(sn);
287
288 const std::size_t M = sn.nstations, K = sn.nclasses;
289 // Solve on the coarsest lattice every law lies on. No event can fall between
290 // its points, so the sample path is the same, and stretching every law by a
291 // common factor would only make the joint chain periodic (and reducible).
292 slot_length = dt_detail::coarsest_slot(sn, slot_length);
293 std::vector<Dmap<T>> law(M);
294 for (std::size_t ist = 0; ist < M; ++ist) law[ist] = dt_detail::station_law(sn, ist, 0, slot_length);
295
296 std::size_t source_idx = M;
297 std::vector<std::size_t> queue_idx;
298 for (std::size_t ist = 0; ist < M; ++ist) {
299 if (sn.stations[ist].sched == SchedStrategy::EXT)
300 source_idx = ist;
301 else
302 queue_idx.push_back(ist);
303 }
304 if (source_idx == M)
305 throw UnsupportedError(ErrorKind{"ClosedClass"}, "SolverMAM: the discrete-time path requires an open model with a Source.");
306
307 const std::size_t nq = queue_idx.size();
308 std::vector<T> QN(nq, zero), UN(nq, zero), TN(nq, zero);
309 std::string method;
310 int totiter = 1;
311
312 DBatch<T> src_batch;
313 src_batch.push_back(law[source_idx].D0);
314 src_batch.push_back(law[source_idx].D1);
315 const T lambda_slot = dmap_lambda_batch(src_batch);
316
317 if (nq == 1) {
318 const std::vector<T> ql =
319 dt_detail::solve_single_station(law[source_idx], law[queue_idx[0]], 1000);
320 for (std::size_t i = 0; i < ql.size(); ++i)
321 QN[0] = QN[0] + num_traits<T>::from_int(static_cast<int>(i)) * ql[i];
322 UN[0] = num_traits<T>::from_int(1) - ql[0];
323 TN[0] = lambda_slot;
324 method = "dt.qmam";
325 } else {
326 // Initial departure streams: Bernoulli of the exact station throughput,
327 // the slotted counterpart of seeding a decomposition with Poisson streams
328 Matrix<T> P = dt_detail::routing(sn, source_idx, queue_idx);
329 std::vector<DBatch<T>> dep(nq);
330 for (std::size_t idx = 0; idx < nq; ++idx) {
331 const T p = lambda_slot * dt_detail::visit_ratio(sn, queue_idx[idx]);
332 DBatch<T> b;
333 b.push_back(Matrix<T>(1, 1, num_traits<T>::from_int(1) - p));
334 b.push_back(Matrix<T>(1, 1, p));
335 dep[idx] = b;
336 }
337
338 std::vector<T> QNprev(nq, zero), QNprev2(nq, zero), UNprev(nq, zero), TNprev(nq, zero);
339 const int iter_max = opt.iter_max > 0 ? opt.iter_max : 100;
340 const double iter_tol = opt.tol > 0 ? opt.tol : 1e-3;
341 auto max_rel = [&](const std::vector<T>& a, const std::vector<T>& b) {
342 double worst = 0;
343 for (std::size_t i = 0; i < a.size(); ++i) {
344 const double d = std::max(std::abs(num_traits<T>::to_double(b[i])), 1e-14);
345 worst = std::max(worst, std::abs(num_traits<T>::to_double(a[i] - b[i])) / d);
346 }
347 return worst;
348 };
349
350 for (int it = 1; it <= iter_max; ++it) {
351 totiter = it;
352 for (std::size_t idx = 0; idx < nq; ++idx) {
353 DBatch<T> arv = dt_detail::arrivals(src_batch, dep, P, idx, opt.space_max);
354 DtQueueResult<T> r = mg1_dt_queue(arv, law[queue_idx[idx]], 1000, true);
355 QN[idx] = r.QN;
356 UN[idx] = r.UN;
357 TN[idx] = r.TN;
358 DBatch<T> d;
359 d.push_back(r.dep.D0);
360 d.push_back(r.dep.D1);
361 dep[idx] = dmap_compress_batch(d, opt.space_max);
362 }
363 if (it > 1 && max_rel(QN, QNprev) < iter_tol) break;
364 if (it > 2 && max_rel(QN, QNprev2) < iter_tol) {
365 // Feedback loops settle into a period-two cycle rather than a
366 // point: re-solving a station with the departure process it just
367 // produced moves it back. The cycle amplitude sits far below the
368 // error of the decomposition itself, so the midpoint is reported
369 // instead of burning iter_max sweeps on an orbit that will not close.
370 const T half = num_traits<T>::from_double(0.5);
371 for (std::size_t idx = 0; idx < nq; ++idx) {
372 QN[idx] = (QN[idx] + QNprev[idx]) * half;
373 UN[idx] = (UN[idx] + UNprev[idx]) * half;
374 TN[idx] = (TN[idx] + TNprev[idx]) * half;
375 }
376 break;
377 }
378 QNprev2 = QNprev;
379 QNprev = QN;
380 UNprev = UN;
381 TNprev = TN;
382 }
383 method = "dt.dec";
384 }
385
386 MamSolution<T> out;
387 mva::MvaSolution<T>& s = out.sol;
388 s.Q = Matrix<T>(M, K, zero);
389 s.U = Matrix<T>(M, K, zero);
390 s.R = Matrix<T>(M, K, zero);
391 s.Tp = Matrix<T>(M, K, zero);
392 s.C.assign(K, zero);
393 s.X.assign(K, zero);
394
395 const T slot = num_traits<T>::from_double(slot_length);
396 for (std::size_t idx = 0; idx < nq; ++idx) {
397 const std::size_t ist = queue_idx[idx];
398 s.Q(ist, 0) = QN[idx];
399 s.U(ist, 0) = UN[idx];
400 s.Tp(ist, 0) = TN[idx] / slot;
401 if (num_traits<T>::to_double(TN[idx]) > 0) s.R(ist, 0) = QN[idx] / TN[idx] * slot;
402 }
403 const T lambda = lambda_slot / slot;
404 s.Tp(source_idx, 0) = lambda;
405 s.X[0] = lambda;
406 T qtot = zero;
407 for (std::size_t idx = 0; idx < nq; ++idx) qtot = qtot + QN[idx];
408 s.C[0] = qtot / lambda;
409 s.iter = totiter;
410 out.actualmethod = method;
411 return out;
412}
413
414} // namespace mam
415} // namespace line
416
417#endif // LINE_SOLVERS_MAM_SOLVER_MAM_DT_H
InputError(const std::string &what)
Definition error.h:105
UnsupportedError(const std::string &what)
Definition error.h:119
A network plus its refreshed NetworkStruct.
Discrete-time (slotted) matrix-analytic primitives and queues.
The exception types the port throws.
Enumerations and the minimal distribution descriptor shared by the model layer of the C++ port.
The option and result types SolverMAM shares with its analyzers.
bool sn_is_open_model(const qn::NetworkStruct< T > &sn)
all(isinf(sn.njobs)): EVERY class is open, which a mixed model fails.
SchedStrategy
Scheduling disciplines, with the values of MATLAB SchedStrategy.
Definition lang_types.h:194
ProcessType
Distribution kinds, with the values of MATLAB ProcessType.
Definition lang_types.h:524
NodeType
Node kinds, with the values of MATLAB NodeType.
Definition lang_types.h:345
DBatch< T > dmap_compress_batch(const DBatch< T > &A, std::size_t max_order)
Order reduction of a BATCH stream.
Definition dtime.h:712
std::vector< T > q_dt_map_map_1(const Dmap< T > &arv, const Dmap< T > &svc, std::size_t max_num_comp=1000)
Queue length distribution of a discrete-time D-MAP/D-MAP/1/FCFS queue, the queue-length half of Q_DT_...
Definition dtime.h:956
std::vector< Matrix< T > > DBatch
A discrete batch arrival stream, entry k carrying the slots with k events.
Definition dtime.h:67
T dmap_lambda_batch(const DBatch< T > &A)
Mean number of EVENTS per slot, pi sum_k k A_k e.
Definition dtime.h:280
std::vector< T > q_dt_ph_ph_1(const Dph< T > &arv, const Dph< T > &svc, std::size_t max_num_comp=1000)
Queue length of a discrete-time DPH/DPH/1/FCFS queue, via the D-MAP route.
Definition dtime.h:1037
DtQueueResult< T > mg1_dt_queue(const DBatch< T > &arv, const Dmap< T > &svc, std::size_t max_num_comp=1000, bool want_departure=false)
Discrete-time single-server queue with batch D-MAP arrivals, DBMAP/D-MAP/1.
Definition dtime.h:1067
Dph< T > dph_from_dist(lang::ProcessType type, const T &mean_slots, const T &scv)
Exact discrete phase-type representation of a lattice-valued law.
Definition dtime.h:160
Dmap< T > dph_to_dmap(const Dph< T > &d)
Renewal D-MAP (A, a alpha) of a discrete phase-type law.
Definition dtime.h:219
MamSolution< T > solver_mam_dt(const qn::NetworkStruct< T > &sn, const MamOptions &opt, double slot_length)
Discrete-time analysis of sn, returning the same metric tuple as every other MAM analyzer.
Dph< T > dmap_to_dph(const Dmap< T > &d)
Discrete phase-type law underlying a renewal D-MAP.
Definition dtime.h:257
DBatch< T > dmap_super(const DBatch< T > &A, const DBatch< T > &B)
Superposition, E_k = sum_{i+j=k} kron(A_i, B_j).
Definition dtime.h:303
bool dmap_is_renewal(const Dmap< T > &d)
True when D1 has rank one, i.e.
Definition dtime.h:236
DBatch< T > dmap_thin(const DBatch< T > &A, const T &p)
Bernoulli thinning, B_k = sum_{n>=k} C(n,k) p^k (1-p)^(n-k) A_n.
Definition dtime.h:323
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
A queueing network and its refreshed NetworkStruct.
Port of matlab/src/api/sn/sn_is_discrete_time.m.
Ports of the sn_has_* / sn_is_* predicate family of matlab/src/api/sn.
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
Outcome of a slotted station solve.
Definition dtime.h:1044
The options SolverMAM reads.
Definition mam_types.h:30
What the MAM dispatch returns: the metrics plus the algorithm that ran.
Definition mam_types.h:211
std::string actualmethod
The concrete algorithm, as the reference's actualmethod.
Definition mam_types.h:214
mva::MvaSolution< T > sol
Definition mam_types.h:212
Class-level results, the [Q,U,R,T,C,X] of the MATLAB analyzers.
Definition mva_types.h:97
std::vector< T > X
Definition mva_types.h:99
std::vector< T > C
Definition mva_types.h:99