LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
solver_nc_cdf.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_NC_SOLVER_NC_CDF_H
6#define LINE_SOLVERS_NC_SOLVER_NC_CDF_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * Port of `@@SolverNC/getCdfRespT.m`, and of its two aliases `getSjrnT` and
12 * `sjrnT`.
13 *
14 * WHAT IT ADDS OVER THE AVERAGE TABLE. `getAvg` reports E[R]; this reports the
15 * whole law Pr[R <= t], which is what a percentile or a service-level target
16 * needs. The two are not interchangeable: a product-form response time is not
17 * exponential, so E[R] does not determine its tail.
18 *
19 * TWO KINDS OF STATION, TWO DIFFERENT LAWS. At an FCFS queue the sojourn time
20 * is the tagged-job passage time through a closed network and comes from
21 * `pfqn_stdf` (exact) or `pfqn_stdf_heur` (the `rd` heuristic). At a delay
22 * station there is no queueing at all, so the sojourn time IS the service time
23 * and the law is the distribution's own CDF, taken through `map_cdf`. The
24 * reference computes both and returns them in one station-indexed table.
25 *
26 * WHY THE TIME GRID IS WHAT IT IS. The reference builds
27 * `logspace(log10 T - 2, log10 T + 1, 100)`, where T is sum(N) times the mean
28 * service time (averaged over the classes a station serves) at the slowest FCFS
29 * station, or a Delay's longest mean service time when that is longer. It is
30 * reproduced exactly, because the grid is part of the answer -- the CDF is
31 * reported AT these points. The former `logspace(0, 2 log10 T, 100)` started
32 * at t = 1 whatever the scale, so a fast system was at CDF ~ 1 on its first
33 * point; for T < 1 it ran DOWN to T^2 and at T = 1 it collapsed to a hundred
34 * identical points. See `_kb/06-solver-catalog.md` (NC, getCdfRespT).
35 *
36 * ORDER-INDEPENDENT MODELS (`nc_is_oi_model`) are intercepted first: an open
37 * one goes to `solver_oi_open_cdfrespt`, a closed or mixed one is refused
38 * (UnsupportedError, kind "Analysis"), as in the reference. Every other
39 * fully open model goes to `solver_nc_open_cdfrespt` (exact per-visit laws of
40 * an open product-form network, or a refusal by name).
41 *
42 * REFUSED, as the reference refuses it: a model with no FCFS station. MATLAB
43 * warns and returns an empty cell array, which reads as a completed analysis
44 * with no data; this throws instead.
45 *
46 * ARITHMETIC. `pfqn_stdf` and `map_cdf` are transcendental, and the grid itself
47 * is a `logspace`, so a non-transcendental backend is refused by name.
48 */
49
50#include <algorithm>
51#include <cmath>
52#include <cstddef>
53#include <string>
54#include <vector>
55
66#include "line/util/error.h"
67#include "line/util/matrix.h"
68
69namespace line {
70namespace nc {
71
72/**
73 * The response-time distributions, station by class.
74 *
75 * `RD[i][r]` is a two-column matrix whose first column is F(t) and whose second
76 * is t, which is the shape `setDistribResults` stores in the reference. An
77 * empty entry means the station-class pair has no law (a Queue that is not
78 * FCFS, or a class the station does not serve).
79 */
80template <class T>
82 std::vector<std::vector<Matrix<T>>> RD;
83 std::vector<T> tset; ///< the shared evaluation grid
84 /**
85 * Non-empty when the reference WARNS AND RETURNS EMPTY rather than
86 * computing: today only "applies only to FCFS nodes". `RD` is then empty,
87 * which a caller can test by size -- unlike the zero table the
88 * normalizing-constant path returns when a method declines a model.
89 */
90 std::string warning;
91};
92
93/**
94 * Port of `@@SolverNC/getCdfRespT.m`.
95 *
96 * @param sn the refreshed struct
97 * @param opt solver controls; `opt.cdf_algorithm` selects 'exact' or 'rd'
98 */
99template <class T>
102 if constexpr (!num_traits<T>::has_transcendental) {
103 (void)sn;
104 (void)opt;
105 throw UnsupportedError(ErrorKind{"Arithmetic"},
106 "solver_nc_cdf_respt: the sojourn-time law is evaluated on a logarithmic time grid "
107 "and inverts a generating function; it needs transcendental arithmetic");
108 } else {
109 const T zero = num_traits<T>::from_int(0);
110 const std::size_t M = sn.nstations, R = sn.nclasses;
111
112 // Order-independent models take their own route, as `getCdfRespT.m`
113 // since Phase 3 of the OI work: an open OI network has exact per-visit
114 // laws (solver_oi_open_cdfrespt, Gardner-Righter for nested
115 // collaborative pools); a closed or mixed one has no known
116 // response-time law, and the FCFS tagged-job passage below would
117 // silently treat its OI stations as something they are not. The
118 // config algorithm ('exact'/'rd') selects between passage-time
119 // inversions and is not read on this route.
120 if (nc_is_oi_model(sn)) {
121 for (const qn::JobClass& c : sn.classes)
122 if (!std::isinf(c.population))
123 throw UnsupportedError(ErrorKind{"Analysis"},
124 "getCdfRespT has no exact law for a closed or mixed network with "
125 "order-independent stations; use SolverCTMC, SolverSSA or SolverLDES for "
126 "this model.");
128 out.RD = oi.RD;
129 out.tset = oi.tset;
130 return out;
131 }
132 // Every other open network takes the open product-form route
133 // (`solver_nc_open_cdfrespt.m`): exact per-visit laws at FCFS and INF
134 // stations, and at single-server PS and LCFS-PR stations that no route
135 // feeds back to; anything outside product form is refused by name
136 // there. The tagged-job passage below is defined on a closed network.
137 {
138 bool allOpen = true;
139 for (const qn::JobClass& c : sn.classes)
140 if (!std::isinf(c.population)) allOpen = false;
141 if (allOpen) {
143 out.RD = op.RD;
144 out.tset = op.tset;
145 return out;
146 }
147 }
148
149 if (opt.cdf_algorithm != "exact" && opt.cdf_algorithm != "rd")
150 throw UnsupportedError(ErrorKind{"Option"}, "solver_nc_cdf_respt: config.algorithm '" + opt.cdf_algorithm +
151 "' is unsupported; use 'exact' (pfqn_stdf) or 'rd' "
152 "(pfqn_stdf_heur)");
153
154 // The reference indexes fcfsNodes into the rows of the NON-DELAY
155 // stations and fcfsNodeIds into all stations; both are kept, because
156 // pfqn_stdf is given the queueing rows only while the result is
157 // reported against the full station list.
158 std::vector<std::size_t> fcfsStations, delayStations;
159 for (std::size_t i = 0; i < M; ++i) {
160 if (sn.stations[i].sched == qn::SchedStrategy::INF) {
161 delayStations.push_back(i + 1);
162 } else if (sn.stations[i].sched == qn::SchedStrategy::FCFS) {
163 fcfsStations.push_back(i + 1);
164 }
165 }
166 if (fcfsStations.empty()) {
167 // ALIGNED TO MATLAB (the empty-result ruling of 2026-07-25, register
168 // row N1 in a second shape). `getCdfRespT.m:44-45` warns
169 // "getCdfRespT applies only to FCFS nodes" and RETURNS with RD = {},
170 // never calling setDistribResults. This returns the same empty
171 // result rather than throwing. It is less lossy than N1's zero
172 // table: a caller can detect an empty result by SIZE, where a table
173 // of zeros is indistinguishable from a model that holds no jobs.
174 out.warning = "getCdfRespT applies only to FCFS nodes.";
175 return out;
176 }
177 for (double n : sn.njobs())
178 if (!std::isfinite(n))
179 throw UnsupportedError(ErrorKind{"OpenClass"},
180 "solver_nc_cdf_respt: the tagged-job sojourn-time law is defined on a CLOSED "
181 "network; this model has an open class");
182
184
185 // The FCFS stations in the index space of the NON-DELAY stations, which
186 // is `fcfsNodes` in the reference and is what pfqn_stdf wants: the rows
187 // of D are the Queue nodes, and on a closed model the non-delay
188 // stations are exactly those.
189 std::vector<std::size_t> fcfsNonDelayPos;
190 {
191 std::size_t pos = 0;
192 for (std::size_t i = 0; i < M; ++i) {
193 if (sn.stations[i].sched == qn::SchedStrategy::INF) continue;
194 ++pos;
195 if (sn.stations[i].sched == qn::SchedStrategy::FCFS) fcfsNonDelayPos.push_back(pos);
196 }
197 }
198
199 // T is the time scale of a sojourn, as `getCdfRespT.m` computes it since
200 // 2026-10-16: sum(N) times the mean (over the classes the station serves)
201 // of 1/rate, at the slowest FCFS station; a Delay's own longest mean
202 // service when that is longer, since its CDF is reported on the same
203 // grid. MATLAB reads a disabled pair as NaN: `mean(...,2,'omitnan')`
204 // skips it and `max` ignores a row that is NaN throughout.
205 double Nsum = 0.0;
206 for (double n : sn.njobs()) Nsum += n;
207 double Tmax = 0.0;
208 bool anyRow = false;
209 for (std::size_t ist : fcfsStations) {
210 double acc = 0.0;
211 std::size_t cnt = 0;
212 for (std::size_t r = 0; r < R; ++r) {
213 if (sn.disabled[ist - 1][r]) continue;
214 acc += 1.0 / num_traits<T>::to_double(sn.rates(ist - 1, r));
215 ++cnt;
216 }
217 if (cnt == 0) continue;
218 const double v = Nsum * acc / static_cast<double>(cnt);
219 if (!anyRow || v > Tmax) Tmax = v;
220 anyRow = true;
221 }
222 for (std::size_t ist : delayStations)
223 for (std::size_t r = 0; r < R; ++r) {
224 if (sn.disabled[ist - 1][r]) continue;
225 const double v = 1.0 / num_traits<T>::to_double(sn.rates(ist - 1, r));
226 if (!anyRow || v > Tmax) Tmax = v;
227 anyRow = true;
228 }
229 if (!anyRow || !(Tmax > 0.0) || !std::isfinite(Tmax))
230 throw NumericError(ErrorKind{"Degenerate"},
231 "solver_nc_cdf_respt: the time grid has no scale; every FCFS station's service "
232 "rate is undefined or non-positive");
233
234 // logspace(log10(T)-2, log10(T)+1, 100): two decades below T, one above.
235 const std::size_t npts = 100;
236 const double lo = std::log10(Tmax) - 2.0;
237 out.tset.assign(npts, zero);
238 for (std::size_t j = 0; j < npts; ++j) {
239 const double e = lo + 3.0 * static_cast<double>(j) / static_cast<double>(npts - 1);
240 out.tset[j] = num_traits<T>::from_double(std::pow(10.0, e));
241 }
242
243 // pfqn_stdf wants the FCFS stations as 0-based indices into the ROWS OF
244 // D, which are the Queue nodes. On a closed model the non-delay
245 // stations ARE the queues, so the reference's `fcfsNodes` is already in
246 // that space and only needs rebasing to zero.
247 std::vector<std::size_t> fcfsRows;
248 for (std::size_t pos : fcfsNonDelayPos) {
249 if (pos > pf.queue_stations.size())
250 throw UnsupportedError(ErrorKind{"SchedStrategy_FCFS"},
251 "solver_nc_cdf_respt: an FCFS station has no row in the product-form demand "
252 "matrix; the model has a non-Queue, non-Delay station between them");
253 fcfsRows.push_back(pos - 1);
254 }
255 Matrix<T> rates(pf.queue_stations.size(), R, zero);
256 for (std::size_t i = 0; i < pf.queue_stations.size(); ++i)
257 for (std::size_t r = 0; r < R; ++r)
258 if (!sn.disabled[pf.queue_stations[i] - 1][r])
259 rates(i, r) = sn.rates(pf.queue_stations[i] - 1, r);
260
261 std::vector<int> N(R, 0);
262 for (std::size_t r = 0; r < R; ++r)
263 N[r] = static_cast<int>(std::llround(pf.N[r]));
264
265 // pfqn_stdf takes integer server counts; an infinite one cannot appear
266 // here because every row of D is a Queue node.
267 std::vector<int> S(pf.S.size(), 1);
268 for (std::size_t i = 0; i < pf.S.size(); ++i) {
269 if (!std::isfinite(pf.S[i]))
270 throw UnsupportedError(ErrorKind{"DelayStation"},
271 "solver_nc_cdf_respt: a queueing station has infinitely many servers, which "
272 "the tagged-job passage time cannot represent");
273 S[i] = static_cast<int>(std::llround(pf.S[i]));
274 }
275 const pfqn::StdfResult<T> sd =
276 opt.cdf_algorithm == "exact"
277 ? pfqn::pfqn_stdf(pf.D, N, pf.Z, S, fcfsRows, rates, out.tset)
278 : pfqn::pfqn_stdf_heur(pf.D, N, pf.Z, S, fcfsRows, rates, out.tset);
279
280 out.RD.assign(M, std::vector<Matrix<T>>(R));
281 for (std::size_t i = 0; i < fcfsStations.size() && i < sd.RD.size(); ++i)
282 for (std::size_t r = 0; r < R && r < sd.RD[i].size(); ++r)
283 out.RD[fcfsStations[i] - 1][r] = sd.RD[i][r];
284
285 // A delay station queues for nothing, so its sojourn law is the service
286 // distribution itself.
287 for (std::size_t ist : delayStations)
288 for (std::size_t r = 0; r < R; ++r) {
289 if (sn.disabled[ist - 1][r]) continue;
290 const std::vector<T> F = mam::map_cdf(
291 lang::dist_to_map(sn.service[ist - 1][r]), out.tset);
292 Matrix<T> A(npts, 2, zero);
293 for (std::size_t j = 0; j < npts; ++j) {
294 A(j, 0) = F[j];
295 A(j, 1) = out.tset[j];
296 }
297 out.RD[ist - 1][r] = A;
298 }
299 return out;
300 }
301}
302
303/** Port of `@@SolverNC/getSjrnT.m`: an alias of getCdfRespT. */
304template <class T>
308
309} // namespace nc
310} // namespace line
311
312#endif // LINE_SOLVERS_NC_SOLVER_NC_CDF_H
NumericError(const std::string &what)
Definition error.h:112
UnsupportedError(const std::string &what)
Definition error.h:119
A network plus its refreshed NetworkStruct.
What refreshProcessRepresentations and refreshLST compute FROM a distribution: the (D0,...
The exception types the port throws.
Cumulative distribution of the inter-arrival time of a MAP.
Dense matrix and non-owning view.
mam::Map< T > dist_to_map(const Distrib< T > &d)
The (D0,D1) pair that reaches sn.proc.
std::vector< T > map_cdf(const Map< T > &m, const std::vector< T > &points)
Cumulative distribution of the inter-arrival time at the given points.
Definition map_cdf.h:63
bool nc_is_oi_model(const qn::NetworkStruct< T > &sn)
Port of nc_is_oi_model.m: a closed, open or mixed network with at least one OI station and nothing bu...
CdfRespTResult< T > solver_nc_sjrnt(const qn::NetworkStruct< T > &sn, const NcSolverOptions &opt)
Port of @@SolverNC/getSjrnT.m: an alias of getCdfRespT.
CdfRespTResult< T > solver_nc_cdf_respt(const qn::NetworkStruct< T > &sn, const NcSolverOptions &opt)
Port of @@SolverNC/getCdfRespT.m.
OiOpenCdfRespT< T > solver_oi_open_cdfrespt(const qn::NetworkStruct< T > &sn, double tol)
Port of solver_oi_open_cdfrespt.m.
PfParams< T > sn_get_product_form_params(const qn::NetworkStruct< T > &sn)
Port of sn_get_product_form_params.
OiOpenCdfRespT< T > solver_nc_open_cdfrespt(const qn::NetworkStruct< T > &sn)
Port of solver_nc_open_cdfrespt.m.
StdfResult< T > pfqn_stdf(const Matrix< T > &L, const std::vector< int > &N, const Matrix< T > &Z, const std::vector< int > &S, const std::vector< std::size_t > &fcfsNodes, const Matrix< T > &rates, const std::vector< T > &tset)
Sojourn-time distribution at the listed FCFS stations.
Definition pfqn_stdf.h:322
StdfResult< T > pfqn_stdf_heur(const Matrix< T > &L, const std::vector< int > &N, const Matrix< T > &Z, const std::vector< int > &S, const std::vector< std::size_t > &fcfsNodes, const Matrix< T > &rates, const std::vector< T > &tset)
Heuristic sojourn-time distribution at the listed FCFS stations.
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
Controls and result shape shared by the normalizing-constant analyzers.
A queueing network and its refreshed NetworkStruct.
Sojourn-time distribution at multiserver FCFS stations of a closed product-form network (J.
Heuristic sojourn-time distribution at multiserver FCFS stations, a variant of J.
Port of matlab/src/api/sn/sn_get_product_form_params.m: the CLASS-level product-form parameters.
Order-independent (OI) and pass-and-swap (P&S) normalizing-constant analysis.
Per-visit response-time distributions of an OPEN product-form (BCMP / Jackson) network with no order-...
Per-visit response-time distributions of an OPEN network of order-independent (OI) and BCMP stations:...
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
The response-time distributions, station by class.
std::vector< std::vector< Matrix< T > > > RD
std::string warning
Non-empty when the reference WARNS AND RETURNS EMPTY rather than computing: today only "applies only ...
std::vector< T > tset
the shared evaluation grid
Controls, defaulting to SolverOptions('NC') in the reference.
Definition nc_types.h:35
Return value of solver_oi_open_cdfrespt: RD{ist,r} = [F(t) t] and the shared grid.
std::vector< std::vector< Matrix< T > > > RD
The [lambda,D,N,Z,mu,S,V] of the reference.
Result of pfqn_stdf / pfqn_stdf_heur, mirroring the MATLAB cell array RD.
Definition pfqn_stdf.h:97
std::vector< std::vector< Matrix< T > > > RD
Definition pfqn_stdf.h:98
One job class of the network.
double population
infinite for an open class