LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
ctmc_blocks.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_LANG_QN_CTMC_BLOCKS_H
6#define LINE_LANG_QN_CTMC_BLOCKS_H
7
8/**
9 * @file
10 * @ingroup line_lang
11 * The station blocks SolverCTMC appends to a station's local state for three
12 * features the population lattice cannot carry on its own, ports of the native
13 * python `api/state/setup_delayoff.py`, `retrial_attempts.py` and
14 * `server_parallelism.py`:
15 *
16 * - SETUP AND DELAY-OFF (`Queue.setDelayOff`): every server is ACTIVE, OFF, in
17 * SETUP or in DELAYOFF. The station row ends with the server counts
18 * `[off, setup(r,k)..., delayoff(r,k)...]` over the classes r and the phases
19 * k of their setup and delay-off laws; ACTIVE is the remainder of the server
20 * count. All servers start ACTIVE (a zero block).
21 * - RETRIAL WITH A FINITE NUMBER OF ATTEMPTS (`Queue.setRetrial(..., maxAttempts)`):
22 * the orbit (the class tokens of the buffer) is split over attempt levels,
23 * `n[a]` = orbiting jobs that have failed `a` retries, `sum_a n[a]` = orbit.
24 * - SERVER PARALLELISM (`Queue.setServerParallelism`): a class-r job holds
25 * `n_r` of the `c` servers for its whole service. No block: the ordinary FCFS
26 * row carries it, but idle servers may sit next to waiting jobs, so the
27 * state space is generated by reachability.
28 *
29 * WHERE THE BLOCK LIVES. The reference takes the shared node-block column of
30 * `sn.nvars` (python column 2R) and reads the block as the last columns of the
31 * row. This port's node block is followed by the REPLY counters, so the block
32 * gets a column of its own instead: `nvars[ind-1][3R+1]`, one past the
33 * reference's `3R+1` columns. It exists only on the copy SolverCTMC solves
34 * (`ctmc_station_blocks`), which is what ACTIVATES the block: every other
35 * solver, and SolverCTMC on a model without these features, sees `nvars` rows
36 * of the usual width and none of the handlers below. Every slicer that takes
37 * `nvars_of` clear of the right-hand end already takes the block with it.
38 *
39 * The block must TRAIL the row, so it is refused together with the two other
40 * trailing constructs, the breakdown status and the true-BAS held-job block.
41 */
42
43#include <cmath>
44#include <cstddef>
45#include <map>
46#include <string>
47#include <vector>
48
52#include "line/util/error.h"
53
54namespace line {
55namespace qn {
56
57/** The 0-based `nvars` column that holds the CTMC station block's width. */
58template <class T>
59std::size_t ctmc_tail_col(const NetworkStruct<T>& sn) {
60 return 3 * sn.nclasses + 1;
61}
62
63/** Width of the CTMC station block of node `ind` (1-based), 0 when it has none. */
64template <class T>
65std::size_t ctmc_tail_width(const NetworkStruct<T>& sn, std::size_t ind) {
66 if (ind == 0 || ind > sn.nvars.size()) return 0;
67 const std::size_t c = ctmc_tail_col(sn);
68 return sn.nvars[ind - 1].size() > c ? sn.nvars[ind - 1][c] : 0;
69}
70
71/** One setup or delay-off law in phase-type form, and its offset in the block. */
72template <class T>
73struct SetupLaw {
74 std::vector<T> alpha; ///< initial phase vector
75 Matrix<T> S; ///< sub-generator (D0)
76 std::vector<T> exit; ///< exit rates -S e
77 std::size_t off = 0; ///< offset of phase 0 inside the block
78};
79
80/** The setup/delay-off layout of one station (python `setup_info`). */
81template <class T>
82struct SetupInfo {
83 bool valid = false;
84 std::size_t ist = 0; ///< 1-based station
85 std::size_t c = 0; ///< server count
86 std::size_t width = 0; ///< 1 + setup phases + delay-off phases
87 std::map<std::size_t, SetupLaw<T>> setup; ///< keyed by 1-based class
88 std::map<std::size_t, SetupLaw<T>> delay; ///< keyed by 1-based class
89};
90
91namespace blocks_detail {
92
93/**
94 * The laws a server-state block takes, python `_ph`: every CONTINUOUS family
95 * with a (D0, initial vector) representation -- the renewal phase-type ones, a
96 * MAP or MMPP2 (its interval law, entered at the embedded vector `map_pie`, as
97 * the reference's `getInitProb`), and the matrix-exponential ME and RAP. The
98 * marked and batch families (MMAP, MPH, BMAP) have no single interval law and
99 * the reference fails on them; a DMAP is discrete-time, so its D0 is not a
100 * rate matrix (the reference reads it as one as a delay-off, and fails on it as
101 * a setup). All of those are refused here, as is every non-Markovian law.
102 */
104 using lang::ProcessType;
105 return p == ProcessType::EXP || p == ProcessType::ERLANG || p == ProcessType::HYPEREXP ||
106 p == ProcessType::PH || p == ProcessType::APH || p == ProcessType::COXIAN ||
107 p == ProcessType::COX2 || p == ProcessType::MAP || p == ProcessType::MMPP2 ||
108 p == ProcessType::ME || p == ProcessType::RAP;
109}
110
111template <class T>
112SetupLaw<T> phase_law(const lang::Distrib<T>& d, const std::string& what, const std::string& node,
113 const std::string& cls) {
114 if (d.disabled || !is_phase_type(d.type) || d.D0.rows() == 0 || d.D1.rows() != d.D0.rows())
115 throw UnsupportedError(ErrorKind{"SetupDelayOff"},
116 "SolverCTMC needs a Markovian " + what + " law at " + node + " for class " + cls +
117 "; " + lang::process_to_text(d.type) + " has no phase-type form. Use SolverLDES.");
118 SetupLaw<T> law;
119 law.S = d.D0;
120 const std::size_t n = d.D0.rows();
121 law.exit.assign(n, num_traits<T>::from_int(0));
122 for (std::size_t k = 0; k < n; ++k) {
124 for (std::size_t j = 0; j < n; ++j) s += d.D0(k, j);
125 law.exit[k] = T(-s);
126 }
127 mam::Map<T> m;
128 m.D0 = d.D0;
129 m.D1 = d.D1;
130 law.alpha = mam::map_pie(m);
131 return law;
132}
133
134} // namespace blocks_detail
135
136/**
137 * The setup/delay-off layout of node `ind` as the model declares it, whether or
138 * not the block is active. `valid` is false when the station declares no pair.
139 * A class takes part when it declares BOTH laws, as in the reference.
140 */
141template <class T>
143 SetupInfo<T> info;
144 if (ind == 0 || ind > sn.nodes.size()) return info;
145 const std::size_t ist = sn.nodes[ind - 1].station;
146 if (ist == 0) return info;
147 const typename std::map<std::size_t, SetupDelayOffParam<T>>::const_iterator it =
148 sn.setupparam.find(ist);
149 if (it == sn.setupparam.end()) return info;
150 const SetupDelayOffParam<T>& sp = it->second;
151 const std::size_t R = sn.nclasses;
152 std::vector<std::size_t> cls;
153 for (std::size_t r = 1; r <= R; ++r)
154 if (r <= sp.setup.size() && !sp.setup[r - 1].disabled && r <= sp.delayoff.size() &&
155 !sp.delayoff[r - 1].disabled)
156 cls.push_back(r);
157 if (cls.empty()) return info;
158 const std::string& node = sn.nodes[ind - 1].name;
159 std::size_t off = 1;
160 for (std::size_t x = 0; x < cls.size(); ++x) {
161 SetupLaw<T> law = blocks_detail::phase_law(sp.setup[cls[x] - 1], "setup", node,
162 sn.classes[cls[x] - 1].name);
163 law.off = off;
164 off += law.S.rows();
165 info.setup[cls[x]] = law;
166 }
167 for (std::size_t x = 0; x < cls.size(); ++x) {
168 SetupLaw<T> law = blocks_detail::phase_law(sp.delayoff[cls[x] - 1], "delay-off", node,
169 sn.classes[cls[x] - 1].name);
170 law.off = off;
171 off += law.S.rows();
172 info.delay[cls[x]] = law;
173 }
174 const double c = sn.stations[ist - 1].nservers;
175 info.ist = ist;
176 info.c = std::isfinite(c) && c > 0 ? static_cast<std::size_t>(c + 0.5) : 0;
177 info.width = off;
178 info.valid = true;
179 return info;
180}
181
182/** The ACTIVE setup/delay-off block of node `ind`: the layout, when SolverCTMC appended it. */
183template <class T>
184SetupInfo<T> setup_info(const NetworkStruct<T>& sn, std::size_t ind) {
185 const std::size_t w = ctmc_tail_width(sn, ind);
186 if (w == 0) return SetupInfo<T>();
187 SetupInfo<T> info = setup_layout(sn, ind);
188 if (!info.valid || info.width != w) return SetupInfo<T>();
189 return info;
190}
191
192/** A finite-attempt retrial station (python `attempts_info`). */
194 bool valid = false;
195 std::size_t ist = 0; ///< 1-based station
196 std::size_t cls = 0; ///< 1-based retrial class
197 std::size_t M = 0; ///< maxAttempts, the number of attempt levels
198};
199
200/** The finite-attempt retrial of node `ind` as the model declares it, active or not. */
201template <class T>
204 if (ind == 0 || ind > sn.nodes.size()) return a;
205 const std::size_t ist = sn.nodes[ind - 1].station;
206 if (ist == 0) return a;
207 const typename std::map<std::size_t, RetrialParam<T>>::const_iterator it =
208 sn.retrialparam.find(ist);
209 if (it == sn.retrialparam.end()) return a;
210 const RetrialParam<T>& rp = it->second;
211 for (std::size_t r = 0; r < rp.retrial_proc.size() && r < sn.nclasses; ++r)
212 if (!rp.retrial_proc[r].disabled && r < rp.max_attempts.size() && rp.max_attempts[r] > 0) {
213 a.valid = true;
214 a.ist = ist;
215 a.cls = r + 1;
216 a.M = static_cast<std::size_t>(rp.max_attempts[r]);
217 return a;
218 }
219 return a;
220}
221
222/** The ACTIVE attempt block of node `ind`: the layout, when SolverCTMC appended it. */
223template <class T>
225 const std::size_t w = ctmc_tail_width(sn, ind);
226 if (w == 0) return AttemptsLayout();
227 if (sn.setupparam.count(sn.nodes[ind - 1].station)) return AttemptsLayout();
228 const AttemptsLayout a = attempts_layout(sn, ind);
229 if (!a.valid || a.M != w) return AttemptsLayout();
230 return a;
231}
232
233/**
234 * Every vector of `parts` nonnegative integers summing to `total`, in the order
235 * of python `compositions`: the first part runs from `total` down to 0, so the
236 * all-at-level-0 vector comes first.
237 */
238inline void attempt_compositions(std::size_t total, std::size_t parts,
239 std::vector<std::vector<std::size_t>>& out,
240 std::vector<std::size_t> head = std::vector<std::size_t>()) {
241 if (parts <= 1) {
242 head.push_back(total);
243 out.push_back(head);
244 return;
245 }
246 for (std::size_t first = total + 1; first-- > 0;) {
247 std::vector<std::size_t> h = head;
248 h.push_back(first);
249 attempt_compositions(total - first, parts - 1, out, h);
250 }
251}
252
253/**
254 * Per-class server degrees `n_r` (all >= 1) of node `ind`, or empty when every
255 * class seizes one server (python `parallelism_of`).
256 */
257template <class T>
258std::vector<double> parallelism_of(const NetworkStruct<T>& sn, std::size_t ind) {
259 if (ind == 0 || ind > sn.nodes.size()) return std::vector<double>();
260 const std::size_t ist = sn.nodes[ind - 1].station;
261 if (ist == 0) return std::vector<double>();
262 const std::vector<std::size_t>& sp = sn.stations[ist - 1].server_parallelism;
263 std::vector<double> par(sn.nclasses, 1.0);
264 bool any = false;
265 for (std::size_t r = 0; r < sp.size() && r < sn.nclasses; ++r) {
266 par[r] = sp[r] > 1 ? static_cast<double>(sp[r]) : 1.0;
267 if (sp[r] > 1) any = true;
268 }
269 return any ? par : std::vector<double>();
270}
271
272/**
273 * Prepare the copy SolverCTMC solves: validate the setup/delay-off, finite-attempt
274 * and server-parallelism stations, and give each setup or attempt station its
275 * block column (python `ctmc_setup`, `ctmc_retrial_attempts`, `ctmc_parallelism`).
276 *
277 * The attempt-level refusals that do not depend on the layout (a closed class,
278 * the CONSTANT policy, non-persistent customers, orbital search) are the state
279 * supports gate's, `state_impatience_unsupported`, as in the reference.
280 *
281 * @param reachable set true when some station holds waiting jobs next to idle
282 * servers (setup or parallelism), which only the reachable walk enumerates
283 * @return true when `out` was written (some station gained a block)
284 */
285template <class T>
286bool ctmc_station_blocks(const NetworkStruct<T>& in, NetworkStruct<T>& out, bool& reachable) {
287 reachable = false;
288 const std::size_t R = in.nclasses;
289 const std::size_t col = ctmc_tail_col(in);
290 std::map<std::size_t, std::size_t> width; // node -> block width
291 for (std::size_t ind = 1; ind <= in.nodes.size(); ++ind) {
292 const std::size_t ist = in.nodes[ind - 1].station;
293 if (ist == 0) continue;
294 const Station<T>& st = in.stations[ist - 1];
295 const std::string& node = in.nodes[ind - 1].name;
296 const double c = st.nservers;
297
298 // ---- setup and delay-off
299 const SetupInfo<T> si = setup_layout(in, ind);
300 if (si.valid) {
301 if (st.sched != SchedStrategy::FCFS)
302 throw UnsupportedError(ErrorKind{"SetupDelayOff"},
303 "SolverCTMC serves setup and delay-off only under FCFS; " + node + " is " +
304 lang::sched_to_text(st.sched) + ". Use SolverLDES.");
305 if (!std::isfinite(c))
306 throw UnsupportedError(ErrorKind{"SetupDelayOff"},
307 "Setup and delay-off need a finite number of servers at " + node + ".");
308 // every class the station serves needs both laws: the setup an arrival
309 // starts and the delay-off a departure starts are those of its own class.
310 // A REPLY answering a call held here needs no law of its own: it brings
311 // back the server its call held, and that server follows the CALLING
312 // class's delay-off law (`blocks_events::setup_departure_variants`).
313 std::vector<bool> isreply(R, false);
314 if (in.replyblock.size() >= ind)
315 for (std::size_t r = 1; r <= R && r <= in.syncreply.size(); ++r) {
316 const std::size_t s = in.syncreply[r - 1];
317 if (s >= 1 && s <= R && in.replyblock[ind - 1].size() >= r &&
318 in.replyblock[ind - 1][r - 1])
319 isreply[s - 1] = true;
320 }
321 for (std::size_t r = 1; r <= R; ++r) {
322 const bool served = !in.disabled[ist - 1][r - 1] &&
323 !in.service[ist - 1][r - 1].disabled &&
324 in.service[ist - 1][r - 1].D0.rows() > 0;
325 if (served && !si.setup.count(r) && !isreply[r - 1])
326 throw UnsupportedError(ErrorKind{"SetupDelayOff"},
327 "Class " + in.classes[r - 1].name + " is served at " + node +
328 " without a setup and delay-off law, while other classes have one; "
329 "SolverCTMC needs one per served class.");
330 }
331 std::string clash;
332 if (in.has_breakdown_node(ind))
333 clash = "server breakdowns";
334 else if (ind <= in.isbasblocking.size() && in.isbasblocking[ind - 1])
335 clash = "true BAS blocking";
336 else if (!in.ctmcpool.empty() && in.ctmcpool.count(ind))
337 clash = "heterogeneous server pools";
338 else {
339 const typename std::map<std::size_t, RetrialParam<T>>::const_iterator rit =
340 in.retrialparam.find(ist);
341 if (rit != in.retrialparam.end())
342 for (std::size_t r = 0; r < rit->second.retrial_proc.size(); ++r)
343 if (!rit->second.retrial_proc[r].disabled) clash = "retrials";
344 if (clash.empty())
345 for (std::size_t r = 1; r <= R; ++r) {
346 const lang::ProcessType pt = in.procid(ist, r);
348 in.mapc_of(ist, r) != nullptr)
349 clash = "a non-renewal (MAP) service";
350 }
351 }
352 if (!clash.empty())
353 throw UnsupportedError(ErrorKind{"SetupDelayOff"},
354 "SolverCTMC does not combine setup and delay-off with " + clash + " at " +
355 node + ". Use SolverLDES.");
356 width[ind] = si.width;
357 reachable = true;
358 }
359
360 // ---- retrial with a finite number of attempts
361 const AttemptsLayout al = attempts_layout(in, ind);
362 if (al.valid && !si.valid) {
363 // The attempt counters trail the row, and so do the breakdown status
364 // and the held-job block, whose handlers read the LAST columns.
365 if (in.has_breakdown_node(ind) ||
366 (ind <= in.isbasblocking.size() && in.isbasblocking[ind - 1]))
367 throw UnsupportedError(ErrorKind{"Retrial"},
368 "SolverCTMC does not combine a finite maxAttempts with " +
369 std::string(in.has_breakdown_node(ind) ? "server breakdowns"
370 : "true BAS blocking") +
371 " at " + node + ": both keep a trailing block in the station state. Use "
372 "SolverLDES.");
373 width[ind] = al.M;
374 }
375
376 // ---- server parallelism
377 const std::vector<double> par = parallelism_of(in, ind);
378 if (!par.empty()) {
379 if (st.sched != SchedStrategy::FCFS)
380 throw UnsupportedError(ErrorKind{"ServerParallelism"},
381 "SolverCTMC serves server parallelism only under FCFS; " + node + " is " +
382 lang::sched_to_text(st.sched) + ". Use SolverLDES.");
383 if (!std::isfinite(c))
384 throw UnsupportedError(ErrorKind{"ServerParallelism"},
385 "Server parallelism needs a finite number of servers at " + node + ".");
386 for (std::size_t r = 0; r < par.size(); ++r)
387 if (par[r] > c)
388 throw UnsupportedError(ErrorKind{"ServerParallelism"},
389 "A class at " + node + " seizes more servers than the " +
390 std::to_string(static_cast<long>(c)) + " it has.");
391 if (si.valid)
392 throw UnsupportedError(ErrorKind{"ServerParallelism"},
393 "SolverCTMC does not combine server parallelism with setup and delay-off at " +
394 node + ". Use SolverLDES.");
395 reachable = true;
396 }
397 }
398 if (width.empty()) return false;
399 out = in;
400 for (std::map<std::size_t, std::size_t>::const_iterator it = width.begin(); it != width.end();
401 ++it) {
402 std::vector<std::size_t>& nv = out.nvars[it->first - 1];
403 if (nv.size() <= col) nv.resize(col + 1, 0);
404 nv[col] = it->second;
405 }
406 return true;
407}
408
409} // namespace qn
410} // namespace line
411
412#endif // LINE_LANG_QN_CTMC_BLOCKS_H
UnsupportedError(const std::string &what)
Definition error.h:119
A network plus its refreshed NetworkStruct.
std::vector< std::vector< std::size_t > > nvars
sn.nvars, (nnodes x 3R+1): the LOCAL VARIABLE columns each node appends to its state,...
The exception types the port throws.
Enumerations and the minimal distribution descriptor shared by the model layer of the C++ port.
Markovian arrival process descriptors: stationary vectors, rate, moments, autocorrelation and the ind...
ProcessType
Distribution kinds, with the values of MATLAB ProcessType.
Definition lang_types.h:524
const char * sched_to_text(SchedStrategy s)
Definition lang_types.h:248
const char * process_to_text(ProcessType p)
The MATLAB ProcessType name, as sn.procid prints it.
Definition lang_types.h:655
std::vector< T > map_pie(const Map< T > &m)
Phase distribution seen by an arriving job, pie = pi D1 / (pi D1 e).
Definition map_moment.h:89
SetupLaw< T > phase_law(const lang::Distrib< T > &d, const std::string &what, const std::string &node, const std::string &cls)
bool is_phase_type(lang::ProcessType p)
The laws a server-state block takes, python _ph: every CONTINUOUS family with a (D0,...
SetupInfo< T > setup_info(const NetworkStruct< T > &sn, std::size_t ind)
The ACTIVE setup/delay-off block of node ind: the layout, when SolverCTMC appended it.
void attempt_compositions(std::size_t total, std::size_t parts, std::vector< std::vector< std::size_t > > &out, std::vector< std::size_t > head=std::vector< std::size_t >())
Every vector of parts nonnegative integers summing to total, in the order of python compositions: the...
AttemptsLayout attempts_layout(const NetworkStruct< T > &sn, std::size_t ind)
The finite-attempt retrial of node ind as the model declares it, active or not.
SetupInfo< T > setup_layout(const NetworkStruct< T > &sn, std::size_t ind)
The setup/delay-off layout of node ind as the model declares it, whether or not the block is active.
bool ctmc_station_blocks(const NetworkStruct< T > &in, NetworkStruct< T > &out, bool &reachable)
Prepare the copy SolverCTMC solves: validate the setup/delay-off, finite-attempt and server-paralleli...
std::size_t ctmc_tail_col(const NetworkStruct< T > &sn)
The 0-based nvars column that holds the CTMC station block's width.
Definition ctmc_blocks.h:59
std::vector< double > parallelism_of(const NetworkStruct< T > &sn, std::size_t ind)
Per-class server degrees n_r (all >= 1) of node ind, or empty when every class seizes one server (pyt...
AttemptsLayout attempts_info(const NetworkStruct< T > &sn, std::size_t ind)
The ACTIVE attempt block of node ind: the layout, when SolverCTMC appended it.
std::size_t ctmc_tail_width(const NetworkStruct< T > &sn, std::size_t ind)
Width of the CTMC station block of node ind (1-based), 0 when it has none.
Definition ctmc_blocks.h:65
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
A queueing network and its refreshed NetworkStruct.
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
Matrix< T > D0
The (D0,D1) pair when the type carries one directly.
Definition lang_types.h:921
A MAP as the pair of matrices (D0, D1).
Definition map_moment.h:53
Matrix< T > D1
Definition map_moment.h:55
Matrix< T > D0
Definition map_moment.h:54
A finite-attempt retrial station (python attempts_info).
std::size_t M
maxAttempts, the number of attempt levels
std::size_t ist
1-based station
std::size_t cls
1-based retrial class
The parameters of a retrial station: MATLAB sn.retrialProc and friends.
std::vector< int > max_attempts
0 = unbounded
std::vector< lang::Distrib< T > > retrial_proc
retrial_proc[r] is the class-r retrial process; empty = not a retrial class.
Setup and delay-off of a station that powers down when it falls idle.
std::vector< lang::Distrib< T > > setup
per class, disabled = not declared
std::vector< lang::Distrib< T > > delayoff
per class
The setup/delay-off layout of one station (python setup_info).
Definition ctmc_blocks.h:82
std::map< std::size_t, SetupLaw< T > > setup
keyed by 1-based class
Definition ctmc_blocks.h:87
std::map< std::size_t, SetupLaw< T > > delay
keyed by 1-based class
Definition ctmc_blocks.h:88
std::size_t ist
1-based station
Definition ctmc_blocks.h:84
std::size_t c
server count
Definition ctmc_blocks.h:85
std::size_t width
1 + setup phases + delay-off phases
Definition ctmc_blocks.h:86
One setup or delay-off law in phase-type form, and its offset in the block.
Definition ctmc_blocks.h:73
Matrix< T > S
sub-generator (D0)
Definition ctmc_blocks.h:75
std::vector< T > exit
exit rates -S e
Definition ctmc_blocks.h:76
std::vector< T > alpha
initial phase vector
Definition ctmc_blocks.h:74
std::size_t off
offset of phase 0 inside the block
Definition ctmc_blocks.h:77
One station of the network.
SchedStrategy sched
double nservers
may be infinite (a Delay, or an inf-scheduled task)