LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
distribution.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_DISTRIBUTION_H
6#define LINE_LANG_DISTRIBUTION_H
7
8/**
9 * @file
10 * @ingroup line_lang
11 * What `refreshProcessRepresentations` and `refreshLST` compute FROM a
12 * distribution: the (D0,D1) pair that reaches `sn.proc`, the arrival-phase
13 * vector `sn.pie`, and the Laplace-Stieltjes transform `sn.lst`.
14 *
15 * These are free functions rather than members of `Distrib` because they need
16 * the api layer -- the stationary vector of a MAP is a linear solve
17 * (`api/mam/map_moment.h`), the Erlang approximation of a non-Markovian
18 * distribution is `map_erlang`, and the Replayer's is an APH fit -- and the
19 * model layer would otherwise depend on the api layer wholesale.
20 *
21 * WHERE THE REFERENCE IS BUG-FOR-BUG REPRODUCED, deliberately. The Weibull and
22 * Lognormal transforms in MATLAB are 1000-point RIGHT-ENDPOINT Riemann sums
23 * over a truncated interval, not converged quadrature: they are biased low by
24 * the tail they drop and by the O(dx) rule. Their values enter M/G/1 waiting
25 * times, so replacing them with an accurate integral would move numbers this
26 * port is supposed to match. The Pareto transform, by contrast, IS converged in
27 * the reference (adaptive Gauss-Kronrod at RelTol 1e-12 over the substitution
28 * u = k/x), and is reproduced as such with the ported `num_integral`.
29 */
30
31#include <cmath>
32#include <complex>
33#include <cstddef>
34#include <string>
35#include <vector>
36
46#include "line/num/number.h"
47#include "line/util/error.h"
48#include "line/util/expm.h"
49#include "line/util/matrix.h"
50
51namespace line {
52namespace lang {
53
54/**
55 * The number of Erlang phases `convertToMAP` picks for a non-Markovian
56 * distribution: 20 when the SCV is below CoarseTol (a Det, or near one), and
57 * otherwise ceil(1/SCV) capped at 100.
58 *
59 * The cap is what makes the approximation one-sided: a Pareto of SCV 64 gets a
60 * single phase (an exponential), so the approximation matches the mean and NOT
61 * the SCV whenever the SCV exceeds 1. That is the reference's behaviour and the
62 * reason `sn.scv` is read from the distribution rather than from `sn.proc`.
63 */
64inline unsigned convert_to_map_phases(double scv) {
65 if (scv < GlobalConstants::CoarseTol) return 20;
66 const double n = std::ceil(1.0 / scv);
67 const double capped = n < 1.0 ? 1.0 : (n > 100.0 ? 100.0 : n);
68 return static_cast<unsigned>(capped);
69}
70
71/**
72 * The refusal every lowering of a `Prior` shares.
73 *
74 * A Prior is a set of models, not one law, so there is no (D0,D1), no transform
75 * and no moment of it that a solver could integrate: substituting any single
76 * alternative would answer for a model the caller did not describe, and
77 * collapsing the set to its mixture would answer for a model nobody described.
78 * SolverUQ is the one consumer, and it replaces the Prior before the design
79 * point is solved.
80 */
81inline void reject_prior(const char* who) {
82 throw UnsupportedError(ErrorKind{"Prior"}, std::string(who) +
83 ": the distribution is a Prior, which is a weighted set of alternative "
84 "MODELS rather than one law; solve the model with SolverUQ, which "
85 "replaces each Prior by one alternative per design point");
86}
87
88/**
89 * The (D0,D1) pair that reaches `sn.proc`.
90 *
91 * A type that carries its own representation returns it unchanged. Det,
92 * Uniform, Pareto, Gamma, Weibull and Lognormal are replaced by the Erlang
93 * approximation of `convertToMAP`; a Replayer is fitted by `aph_fit`, which is
94 * what MATLAB's `Replayer.fitAPH` does before taking getProcess.
95 */
96template <class T>
98 if (d.is_prior()) reject_prior("dist_to_map");
99 if (d.disabled) throw InputError("dist_to_map: the distribution is disabled");
100 if (d.type == ProcessType::NORMAL)
101 throw UnsupportedError(ErrorKind{"Normal"},
102 "dist_to_map: a Normal puts mass below zero, so it is not the law of any duration and "
103 "has no Markovian representation. The default arm of this function would hand back the "
104 "Erlang fit of its mean, which is a positive law with the same mean and nothing else "
105 "in common; refusing instead. A Normal reaches this port only as the parameter density "
106 "of a continuous Prior");
108 throw InputError(ErrorKind{"Argument"},
109 "dist_to_map: a Defective law is infinite with probability pInf, so its mean is Inf "
110 "and it has no Markovian representation. Use it as a lifetime or failure law, or "
111 "MassAtOrigin for an atom at zero");
113 std::numeric_limits<double>::infinity()))
114 throw InputError(ErrorKind{"Argument"},
115 "dist_to_map: a LogLogistic with shape <= 1 has an infinite mean");
116 if (d.has_map()) {
117 mam::Map<T> m;
118 m.D0 = d.D0;
119 m.D1 = d.D1;
120 return m;
121 }
122 if (d.type == ProcessType::REPLAYER) {
123 // MATLAB fits an APH to the trace's first three moments. The fit is
124 // Bobbio-Horvath-Telek, which needs roots and exponentials, so it is
125 // gated: without the guard the static_assert inside aph_fit fires for
126 // EVERY exact-arithmetic caller of dist_to_map, trace or not, because
127 // the branch is instantiated whether or not it is taken.
128 if constexpr (num_traits<T>::has_transcendental) {
129 const T n = num_traits<T>::from_int(static_cast<long>(d.trace.size()));
132 for (const T& x : d.trace) {
133 m1 += x;
134 m2 += T(x * x);
135 m3 += T(x * x * x);
136 }
137 return mam::aph_fit(T(m1 / n), T(m2 / n), T(m3 / n)).aph;
138 } else {
139 throw UnsupportedError(ErrorKind{"Arithmetic"},
140 "dist_to_map: fitting a Replayer trace to an acyclic phase-type needs "
141 "transcendental arithmetic, which exact rational arithmetic does not provide; "
142 "solve in double or Real<n>, or replace the trace by a fitted distribution");
143 }
144 }
146}
147
148/** `sn.pie`: the phase distribution seen by an arriving job. */
149template <class T>
150std::vector<T> dist_pie(const Distrib<T>& d) {
151 return mam::map_pie(dist_to_map(d));
152}
153
154/**
155 * Fill in the first two moments of a distribution given by its matrices.
156 *
157 * `Distrib::map_dist` cannot compute them -- they need the stationary vector --
158 * so a MAP built directly from (D0,D1) leaves mean and scv at their defaults
159 * until this runs. Every builder call that installs such a distribution passes
160 * through here.
161 */
162template <class T>
164 if (d.disabled || !d.has_map()) return;
165 // An Erlang is only ever built by `Distrib::erlang`, which already stores
166 // MATLAB's closed forms (Erlang.getMean = r/alpha, getSCV = 1/r). The
167 // matrix route below lands one ulp away (Erlang(10,3): 0.30000000000000004
168 // against 0.3), and sn.rates = 1/mean inherits it; see
169 // _kb/06-solver-catalog.md (MAM closed FCFS exit) for what one ulp can cost.
170 if (d.type == ProcessType::ERLANG) return;
171 if (d.type == ProcessType::DMAP) {
173 return;
174 }
175 mam::Map<T> m;
176 m.D0 = d.D0;
177 m.D1 = d.D1;
178 d.mean = mam::map_mean(m);
179 d.scv = mam::map_scv(m);
180}
181
182/**
183 * `sn.lst`: the Laplace-Stieltjes transform E[exp(-sX)].
184 *
185 * The phase-type families evaluate the closed form pie (sI - D0)^-1 (-D0) e;
186 * for a MAP that is the transform of its stationary interarrival time, which is
187 * the quantity the M/G/1 analyzers want.
188 */
189template <class T>
190T dist_lst(const Distrib<T>& d, const T& s) {
191 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
192 if (d.is_prior()) reject_prior("dist_lst");
193 if (d.disabled) throw InputError("dist_lst: the distribution is disabled");
194 // The wrappers combine the transform of the law they wrap. They come before
195 // the s = 0 shortcut: a Defective has L(0) = 1 - pInf, its finite mass.
197 const T p0 = d.params[0];
198 return T(p0 + (one - p0) * dist_lst(*d.inner, s));
199 }
200 if (d.type == ProcessType::DEFECTIVE) return T((one - d.params[0]) * dist_lst(*d.inner, s));
201 if (s == zero) return one;
202
203 switch (d.type) {
205 return one;
207 if constexpr (!num_traits<T>::has_transcendental) {
208 throw UnsupportedError(ErrorKind{"Arithmetic"},
209 "dist_lst: the transform of a LogLogistic is a numerical integral, which exact "
210 "arithmetic has no representation for; use the double or real backend");
211 } else {
212 // MATLAB `LogLogistic.evalLST`: the quantile substitution
213 // x = alpha (u/(1-u))^(1/beta) maps the transform onto [0,1],
214 // where the integrand is bounded by 1, so the power-law tail
215 // needs no truncation.
216 const T a = d.params[0], b = d.params[1];
217 auto g = [&a, &b, &s](const T& u) -> T {
218 const double uv = num_traits<T>::to_double(u);
219 const double w = std::max(1.0 - uv, std::numeric_limits<double>::min());
220 if (!(uv > 0.0)) return num_traits<T>::from_int(1);
221 const double x = num_traits<T>::to_double(a) *
222 std::pow(uv / w, 1.0 / num_traits<T>::to_double(b));
224 };
225 return qsys::detail::num_integral<T>(g, zero, one, num_traits<T>::from_double(1e-12),
226 num_traits<T>::from_double(1e-15), 50);
227 }
228 }
230 // The EMPIRICAL transform mean(exp(-s x)) over the trace, which is
231 // what MATLAB `Replayer.evalLST` and the JAR/python twins return.
232 // Falling through to the phase-type arm would transform the APH fit
233 // of the first three moments instead, i.e. a different law: on
234 // gallery_replayerm1 that moves the G/M/1 caudal root from 0.332835
235 // to 0.332887 and QLen by 1e-4 relative.
236 if constexpr (!num_traits<T>::has_transcendental) {
237 throw UnsupportedError(ErrorKind{"Arithmetic"},
238 "dist_lst: the transform of a Replayer trace is a mean of exp, which exact "
239 "arithmetic has no representation for; use the double or real backend");
240 } else {
241 const double sv = num_traits<T>::to_double(s);
242 double acc = 0.0;
243 for (const T& x : d.trace) acc += std::exp(-sv * num_traits<T>::to_double(x));
244 return num_traits<T>::from_double(acc / static_cast<double>(d.trace.size()));
245 }
246 }
247 case ProcessType::DET: {
248 if constexpr (!num_traits<T>::has_transcendental) {
249 throw UnsupportedError(ErrorKind{"Arithmetic"},
250 "dist_lst: the transform of a Det is exp(-s m), which exact arithmetic has "
251 "no representation for; use the double or real backend");
252 } else {
255 }
256 }
258 if constexpr (!num_traits<T>::has_transcendental) {
259 throw UnsupportedError(ErrorKind{"Arithmetic"},
260 "dist_lst: the transform of a Uniform evaluates exp, which exact arithmetic "
261 "has no representation for; use the double or real backend");
262 } else {
263 const double a = num_traits<T>::to_double(d.params[0]);
264 const double b = num_traits<T>::to_double(d.params[1]);
265 const double sv = num_traits<T>::to_double(s);
266 return num_traits<T>::from_double((std::exp(-sv * a) - std::exp(-sv * b)) /
267 (sv * (b - a)));
268 }
269 }
270 case ProcessType::NORMAL: {
271 if constexpr (!num_traits<T>::has_transcendental) {
272 throw UnsupportedError(ErrorKind{"Arithmetic"},
273 "dist_lst: the transform of a Normal is a value of exp, which exact arithmetic "
274 "has no representation for; use the double or real backend");
275 } else {
276 // exp(-mu s + sigma^2 s^2 / 2), the Laplace-Stieltjes transform.
277 //
278 // ONE DELIBERATE DIVERGENCE, and it is a defect on the other
279 // side: `Normal.m:96-106` returns exp(+mu s + sigma^2 s^2 / 2),
280 // which is the MGF at +s and not E[exp(-sX)] at all -- its own
281 // comment says "the moment-generating function evaluated at -s",
282 // which that expression is also not. Nothing reads it: a Normal
283 // is never a service process, so no analyzer reaches this arm,
284 // and reproducing the sign would put a wrong transform in the
285 // one place a future caller would trust. Recorded in BUGS.md.
286 const double mu = num_traits<T>::to_double(d.params[0]);
287 const double sg = num_traits<T>::to_double(d.params[1]);
288 const double sv = num_traits<T>::to_double(s);
289 return num_traits<T>::from_double(std::exp(-mu * sv + sg * sg * sv * sv / 2.0));
290 }
291 }
292 case ProcessType::PARETO: {
293 if constexpr (!num_traits<T>::has_transcendental) {
294 throw UnsupportedError(ErrorKind{"Arithmetic"},
295 "dist_lst: the transform of a Pareto is an integral of exp, which exact "
296 "arithmetic has no representation for; use the double or real backend");
297 } else {
298 // alpha * int_0^1 u^(alpha-1) exp(-s k / u) du, the substitution
299 // x = k/u the reference uses to stay accurate as s -> 0.
300 const T alpha = d.params[0], k = d.params[1];
301 const T tiny = num_traits<T>::from_double(1e-300);
302 auto g = [&alpha, &k, &s, &tiny, &one](const T& u) -> T {
303 if (!(u > num_traits<T>::from_int(0))) return num_traits<T>::from_int(0);
304 const T uu = u > tiny ? u : tiny;
305 const double e = std::exp(-num_traits<T>::to_double(T(s * k / uu)));
306 const double p = std::pow(num_traits<T>::to_double(u),
307 num_traits<T>::to_double(T(alpha - one)));
308 return num_traits<T>::from_double(p * e);
309 };
310 const T val = qsys::detail::num_integral<T>(g, zero, one,
312 num_traits<T>::from_double(1e-300), 50);
313 return T(alpha * val);
314 }
315 }
317 if constexpr (!num_traits<T>::has_transcendental) {
318 throw UnsupportedError(ErrorKind{"Arithmetic"},
319 "dist_lst: the transform of a Weibull is a numerical integral, which exact "
320 "arithmetic has no representation for; use the double or real backend");
321 } else {
322 // The reference's 1000-panel right-endpoint sum, reproduced.
323 const double a = num_traits<T>::to_double(d.params[0]);
324 const double r = num_traits<T>::to_double(d.params[1]);
325 const double sv = num_traits<T>::to_double(s);
326 const double upper = a * std::pow(-std::log(1e-10), 1.0 / r);
327 const int n = 1000;
328 const double dx = upper / n;
329 double acc = 0.0;
330 for (int i = 1; i <= n; ++i) {
331 const double x = i * dx;
332 const double pdf =
333 (r / a) * std::pow(x / a, r - 1.0) * std::exp(-std::pow(x / a, r));
334 acc += std::exp(-sv * x) * pdf;
335 }
336 return num_traits<T>::from_double(acc * dx);
337 }
338 }
340 if constexpr (!num_traits<T>::has_transcendental) {
341 throw UnsupportedError(ErrorKind{"Arithmetic"},
342 "dist_lst: the transform of a Lognormal is a numerical integral, which exact "
343 "arithmetic has no representation for; use the double or real backend");
344 } else {
345 const double mu = num_traits<T>::to_double(d.params[0]);
346 const double sg = num_traits<T>::to_double(d.params[1]);
347 const double sv = num_traits<T>::to_double(s);
348 const double upper = std::exp(mu + 5.0 * sg);
349 const int n = 1000;
350 const double dx = upper / n;
351 double acc = 0.0;
352 for (int i = 1; i <= n; ++i) {
353 const double x = i * dx;
354 const double lx = std::log(x);
355 const double pdf = std::exp(-(lx - mu) * (lx - mu) / (2.0 * sg * sg)) /
356 (x * sg * std::sqrt(2.0 * M_PI));
357 acc += std::exp(-sv * x) * pdf;
358 }
359 return num_traits<T>::from_double(acc * dx);
360 }
361 }
362 case ProcessType::GAMMA: {
363 if constexpr (!num_traits<T>::has_transcendental) {
364 throw UnsupportedError(ErrorKind{"Arithmetic"},
365 "dist_lst: the transform of a Gamma is (1 + s theta)^-k, which exact "
366 "arithmetic has no representation for; use the double or real backend");
367 } else {
368 const double shape = num_traits<T>::to_double(d.params[0]);
369 const double scale = num_traits<T>::to_double(d.params[1]);
371 std::pow(1.0 + num_traits<T>::to_double(s) * scale, -shape));
372 }
373 }
374 default:
375 break;
376 }
377
378 // Phase-type / MAP families: pie (sI - D0)^-1 (-D0) e, a rational function
379 // of s and therefore exact wherever the arithmetic is.
380 const mam::Map<T> m = dist_to_map(d);
381 const std::vector<T> pie = mam::map_pie(m);
382 const std::size_t n = m.D0.rows();
383 Matrix<T> A(n, n, zero);
384 for (std::size_t i = 0; i < n; ++i)
385 for (std::size_t j = 0; j < n; ++j) A(i, j) = T((i == j ? s : zero) - m.D0(i, j));
386 // rhs = (-D0) e, the exit-rate vector
387 std::vector<T> rhs(n, zero);
388 for (std::size_t i = 0; i < n; ++i) {
389 T acc = zero;
390 for (std::size_t j = 0; j < n; ++j) acc += m.D0(i, j);
391 rhs[i] = T(-acc);
392 }
393 // Solve A x = rhs by Gaussian elimination with partial pivoting.
394 std::vector<T> x = rhs;
395 for (std::size_t col = 0; col < n; ++col) {
396 std::size_t best = col;
397 double bv = std::fabs(num_traits<T>::to_double(A(col, col)));
398 for (std::size_t r = col + 1; r < n; ++r) {
399 const double v = std::fabs(num_traits<T>::to_double(A(r, col)));
400 if (v > bv) {
401 bv = v;
402 best = r;
403 }
404 }
405 if (best != col) {
406 for (std::size_t j = 0; j < n; ++j) std::swap(A(col, j), A(best, j));
407 std::swap(x[col], x[best]);
408 }
409 if (A(col, col) == zero) throw NumericError(ErrorKind{"Singular"}, "dist_lst: singular transform matrix");
410 for (std::size_t r = 0; r < n; ++r) {
411 if (r == col) continue;
412 const T f = T(A(r, col) / A(col, col));
413 if (f == zero) continue;
414 for (std::size_t j = 0; j < n; ++j) A(r, j) = T(A(r, j) - f * A(col, j));
415 x[r] = T(x[r] - f * x[col]);
416 }
417 }
418 T out = zero;
419 for (std::size_t i = 0; i < n; ++i) out += pie[i] * T(x[i] / A(i, i));
420 return out;
421}
422
423// Forward declarations: the complex transform below reaches the CDF and the raw
424// moments, both defined further down, and a dependent call would resolve only by
425// ADL at instantiation.
426template <class T>
427T dist_cdf(const Distrib<T>& d, const T& x);
428template <class T>
429T dist_moment(const Distrib<T>& d, unsigned k);
430
431/**
432 * `sn.lst` at a COMPLEX argument, E[exp(-sX)] with s off the real axis.
433 *
434 * WHY A SECOND OVERLOAD. A transform is evaluated off the real axis by anything
435 * that inverts it or locates its roots: the Abate-Whitt Euler sum walks the line
436 * Re(s) = A/(2t), and a matrix transform int exp(Ut) dF(t) is read off the
437 * spectrum of U, which is complex in general. `dist_lst(d, s)` above is
438 * templated on the arithmetic type T and returns T, so it cannot answer either;
439 * this twin fixes the argument and the result at std::complex<double>, since a
440 * complex transform is meaningless without transcendental arithmetic anyway.
441 * Parity note: the JAR carries the same capability by widening `sn.lst` to
442 * SerializableFunction<Complex, Complex>, MATLAB by its own closed forms, and
443 * python by Distribution.evalLST accepting a complex argument.
444 *
445 * THE TIERS mirror the real overload exactly: a closed form where the family has
446 * one, the phase-type solve where the law is Markovian, and the CDF-increment
447 * sum otherwise -- the last being a proper measure for ANY law, including one
448 * with an atom and one with no density.
449 */
450template <class T>
451std::complex<double> dist_lst(const Distrib<T>& d, const std::complex<double>& s) {
453 "dist_lst at a complex argument requires transcendental arithmetic");
454 if (d.is_prior()) reject_prior("dist_lst");
455 if (d.disabled) throw InputError("dist_lst: the distribution is disabled");
457 const double p0 = num_traits<T>::to_double(d.params[0]);
458 return p0 + (1.0 - p0) * dist_lst(*d.inner, s);
459 }
461 return (1.0 - num_traits<T>::to_double(d.params[0])) * dist_lst(*d.inner, s);
462 if (std::abs(s) == 0.0) return std::complex<double>(1.0, 0.0);
463
464 switch (d.type) {
466 return std::complex<double>(1.0, 0.0);
468 // The real overload's quantile substitution, real and imaginary
469 // parts integrated separately over [0,1].
470 const double a = num_traits<T>::to_double(d.params[0]);
471 const double b = num_traits<T>::to_double(d.params[1]);
472 auto q = [a, b](double u) {
473 const double w = std::max(1.0 - u, std::numeric_limits<double>::min());
474 return a * std::pow(u / w, 1.0 / b);
475 };
476 auto re = [&](const double& u) -> double {
477 return u > 0.0 ? std::exp(-s * q(u)).real() : 1.0;
478 };
479 auto im = [&](const double& u) -> double {
480 return u > 0.0 ? std::exp(-s * q(u)).imag() : 0.0;
481 };
482 const double r = qsys::detail::num_integral<double>(re, 0.0, 1.0, 1e-12, 1e-15, 50);
483 const double i = qsys::detail::num_integral<double>(im, 0.0, 1.0, 1e-12, 1e-15, 50);
484 return std::complex<double>(r, i);
485 }
487 std::complex<double> acc(0.0, 0.0);
488 for (const T& x : d.trace) acc += std::exp(-s * num_traits<T>::to_double(x));
489 return acc / static_cast<double>(d.trace.size());
490 }
491 case ProcessType::DET:
492 return std::exp(-s * num_traits<T>::to_double(d.mean));
494 const double a = num_traits<T>::to_double(d.params[0]);
495 const double b = num_traits<T>::to_double(d.params[1]);
496 return (std::exp(-s * a) - std::exp(-s * b)) / (s * (b - a));
497 }
498 case ProcessType::NORMAL: {
499 const double mu = num_traits<T>::to_double(d.params[0]);
500 const double sg = num_traits<T>::to_double(d.params[1]);
501 return std::exp(-mu * s + sg * sg * s * s / 2.0);
502 }
503 case ProcessType::GAMMA: {
504 const double shape = num_traits<T>::to_double(d.params[0]);
505 const double scale = num_traits<T>::to_double(d.params[1]);
506 return std::pow(std::complex<double>(1.0, 0.0) + s * scale, -shape);
507 }
508 default:
509 break;
510 }
511
512 if (process_is_markovian(d.type)) {
513 // pie (sI - D0)^-1 (-D0) e, the same rational function as the real
514 // overload, continued to the complex plane.
515 const mam::Map<T> m = dist_to_map(d);
516 const std::vector<T> pie = mam::map_pie(m);
517 const std::size_t n = m.D0.rows();
518 std::vector<std::vector<std::complex<double> > > A(
519 n, std::vector<std::complex<double> >(n, std::complex<double>(0.0, 0.0)));
520 std::vector<std::complex<double> > x(n, std::complex<double>(0.0, 0.0));
521 for (std::size_t i = 0; i < n; ++i) {
522 double exit = 0.0;
523 for (std::size_t j = 0; j < n; ++j) {
524 const double d0 = num_traits<T>::to_double(m.D0(i, j));
525 A[i][j] = (i == j ? s : std::complex<double>(0.0, 0.0)) - d0;
526 exit += d0;
527 }
528 x[i] = std::complex<double>(-exit, 0.0);
529 }
530 for (std::size_t col = 0; col < n; ++col) {
531 std::size_t piv = col;
532 double bv = std::abs(A[col][col]);
533 for (std::size_t r = col + 1; r < n; ++r) {
534 if (std::abs(A[r][col]) > bv) { bv = std::abs(A[r][col]); piv = r; }
535 }
536 if (piv != col) { std::swap(A[piv], A[col]); std::swap(x[piv], x[col]); }
537 if (std::abs(A[col][col]) == 0.0)
538 throw NumericError(ErrorKind{"Singular"}, "dist_lst: singular transform matrix");
539 for (std::size_t r = col + 1; r < n; ++r) {
540 const std::complex<double> f = A[r][col] / A[col][col];
541 for (std::size_t c = col; c < n; ++c) A[r][c] -= f * A[col][c];
542 x[r] -= f * x[col];
543 }
544 }
545 for (std::size_t row = n; row-- > 0;) {
546 std::complex<double> acc = x[row];
547 for (std::size_t c = row + 1; c < n; ++c) acc -= A[row][c] * x[c];
548 x[row] = acc / A[row][row];
549 }
550 std::complex<double> out(0.0, 0.0);
551 for (std::size_t i = 0; i < n; ++i) out += num_traits<T>::to_double(pie[i]) * x[i];
552 return out;
553 }
554
555 // Riemann-Stieltjes sum with true CDF increments, renormalized for the cut
556 // tail, so the result is still a transform.
557 const std::size_t n_grid = 2400;
558 const double mean = num_traits<T>::to_double(dist_moment(d, 1u));
559 double hi = mean * 60.0;
560 const double m2 = num_traits<T>::to_double(dist_moment(d, 2u));
561 const double var = m2 - mean * mean;
562 if (std::isfinite(var) && var > 0.0) hi = std::max(hi, mean + 12.0 * std::sqrt(var));
563 if (!std::isfinite(hi) || hi <= 0.0) return std::complex<double>(1.0, 0.0);
564 const double step = hi / static_cast<double>(n_grid);
565 std::complex<double> acc(0.0, 0.0);
566 double mass = 0.0;
568 for (std::size_t i = 0; i < n_grid; ++i) {
569 const double right = static_cast<double>(i + 1) * step;
570 const double cur = num_traits<T>::to_double(dist_cdf(d, num_traits<T>::from_double(right)));
571 const double w = cur - prev;
572 prev = cur;
573 if (w == 0.0) continue;
574 mass += w;
575 acc += w * std::exp(-s * ((static_cast<double>(i) + 0.5) * step));
576 }
577 return mass > 0.0 ? acc / mass : std::complex<double>(1.0, 0.0);
578}
579
580/**
581 * The k-th raw moment.
582 *
583 * The closed-form families are evaluated from their parameters, as the MATLAB
584 * classes do, rather than from the Erlang approximation of `sn.proc`: the
585 * approximation matches only the mean once the SCV exceeds 1.
586 */
587template <class T>
588T dist_moment(const Distrib<T>& d, unsigned k) {
589 const T one = num_traits<T>::from_int(1);
590 if (k == 0) return one;
591 if (d.is_prior()) reject_prior("dist_moment");
592 if (d.disabled) throw InputError("dist_moment: the distribution is disabled");
593 switch (d.type) {
595 return num_traits<T>::from_int(0);
596 case ProcessType::DET: {
597 T v = one;
598 for (unsigned i = 0; i < k; ++i) v = T(v * d.mean);
599 return v;
600 }
602 // (b^(k+1) - a^(k+1)) / ((k+1)(b-a))
603 const T a = d.params[0], b = d.params[1];
604 T pa = one, pb = one;
605 for (unsigned i = 0; i <= k; ++i) {
606 pa = T(pa * a);
607 pb = T(pb * b);
608 }
609 return T((pb - pa) / (num_traits<T>::from_int(static_cast<long>(k) + 1) * (b - a)));
610 }
611 case ProcessType::PARETO: {
612 // alpha k^m / (alpha - m), finite only for m < alpha
613 const T alpha = d.params[0], scale = d.params[1];
614 const T m = num_traits<T>::from_int(static_cast<long>(k));
615 if (!(alpha > m))
616 throw NumericError(ErrorKind{"Overflow"}, "dist_moment: the Pareto moment of this order is infinite");
617 T ps = one;
618 for (unsigned i = 0; i < k; ++i) ps = T(ps * scale);
619 return T(alpha * ps / (alpha - m));
620 }
622 const T n = num_traits<T>::from_int(static_cast<long>(d.trace.size()));
623 T acc = num_traits<T>::from_int(0);
624 for (const T& x : d.trace) {
625 T v = one;
626 for (unsigned i = 0; i < k; ++i) v = T(v * x);
627 acc += v;
628 }
629 return T(acc / n);
630 }
631 case ProcessType::GAMMA: {
632 if constexpr (!num_traits<T>::has_transcendental) {
633 throw UnsupportedError(ErrorKind{"Arithmetic"},
634 "dist_moment: the moments of a Gamma are values of the gamma function, which "
635 "exact arithmetic has no representation for");
636 } else {
637 const double shape = num_traits<T>::to_double(d.params[0]);
638 const double scale = num_traits<T>::to_double(d.params[1]);
639 return num_traits<T>::from_double(std::tgamma(shape + k) / std::tgamma(shape) *
640 std::pow(scale, static_cast<double>(k)));
641 }
642 }
644 if constexpr (!num_traits<T>::has_transcendental) {
645 throw UnsupportedError(ErrorKind{"Arithmetic"},
646 "dist_moment: the moments of a Weibull are values of the gamma function, "
647 "which exact arithmetic has no representation for");
648 } else {
649 const double a = num_traits<T>::to_double(d.params[0]);
650 const double r = num_traits<T>::to_double(d.params[1]);
651 return num_traits<T>::from_double(std::pow(a, static_cast<double>(k)) *
652 std::tgamma(1.0 + k / r));
653 }
654 }
656 if constexpr (!num_traits<T>::has_transcendental) {
657 throw UnsupportedError(ErrorKind{"Arithmetic"},
658 "dist_moment: the moments of a LogLogistic are values of sin, which exact "
659 "arithmetic has no representation for");
660 } else {
661 // alpha^k b/sin(b), b = k pi/beta; Inf when k >= beta, as MATLAB.
662 const double a = num_traits<T>::to_double(d.params[0]);
663 const double r = num_traits<T>::to_double(d.params[1]);
664 if (static_cast<double>(k) >= r)
665 return num_traits<T>::from_double(std::numeric_limits<double>::infinity());
666 const double b = static_cast<double>(k) * 3.14159265358979323846 / r;
667 return num_traits<T>::from_double(std::pow(a, static_cast<double>(k)) * b / std::sin(b));
668 }
669 }
671 // E[X^k] = (1 - p0) E[Y^k] for k >= 1.
672 return T((one - d.params[0]) * dist_moment(*d.inner, k));
674 if (num_traits<T>::to_double(d.params[0]) > 0.0) {
676 return num_traits<T>::from_double(std::numeric_limits<double>::infinity());
677 else
678 throw UnsupportedError(ErrorKind{"Arithmetic"},
679 "dist_moment: the moments of a Defective law are infinite");
680 }
681 return dist_moment(*d.inner, k);
683 if constexpr (!num_traits<T>::has_transcendental) {
684 throw UnsupportedError(ErrorKind{"Arithmetic"},
685 "dist_moment: the moments of a Lognormal are values of exp, which exact "
686 "arithmetic has no representation for");
687 } else {
688 const double mu = num_traits<T>::to_double(d.params[0]);
689 const double sg = num_traits<T>::to_double(d.params[1]);
690 return num_traits<T>::from_double(std::exp(k * mu + k * k * sg * sg / 2.0));
691 }
692 }
693 case ProcessType::NORMAL: {
694 // The raw moments from the recurrence m_k = mu m_{k-1} + (k-1)
695 // sigma^2 m_{k-2}, which is exact in any arithmetic and needs no
696 // double factorial: m_1 = mu and m_2 = mu^2 + sigma^2 seed it.
697 const T mu = d.params[0], sg = d.params[1];
698 T prev2 = one, prev1 = mu;
699 if (k == 1) return prev1;
700 for (unsigned i = 2; i <= k; ++i) {
701 const T next = T(mu * prev1 +
702 num_traits<T>::from_int(static_cast<long>(i) - 1) * sg * sg *
703 prev2);
704 prev2 = prev1;
705 prev1 = next;
706 }
707 return prev1;
708 }
709 default:
710 break;
711 }
712 return mam::map_moment(dist_to_map(d), k);
713}
714
715/**
716 * F(x) = P{X <= x}, MATLAB's `Distribution.evalCDF`.
717 *
718 * WHY IT EXISTS AT ALL in a port whose solvers read moments and transforms: it
719 * is the only thing `Prior.discretize` needs. The quadrature design of SolverUQ
720 * places its nodes at the conditional medians of equal-mass strata of the
721 * parameter density, which is an inverse CDF and nothing else, so a parameter
722 * law of any family can be discretized with no per-family quantile.
723 *
724 * PER FAMILY, from the closed form the reference's own class uses -- the Erlang
725 * from its Poisson sum, the Gamma from the regularized incomplete gamma, the
726 * Pareto from `gpcdf` reduced to 1 - (k/x)^alpha -- rather than from the Erlang
727 * approximation of `dist_to_map`, for the same reason `dist_moment` does: the
728 * approximation matches only the mean once the SCV exceeds one. The phase-type
729 * and MAP families fall through to 1 - pie exp(D0 x) e, which is `map_cdf`.
730 *
731 * ONE DELIBERATE DIVERGENCE FROM THE REFERENCE, and it is a defect on the other
732 * side: `Uniform.evalCDF` in MATLAB returns the constant DENSITY 1/(b-a) inside
733 * the support and 0 above it, so it is neither a CDF nor monotone. Reproducing
734 * that would make the bisection below fail to bracket rather than return a
735 * matching wrong number, and no ported quantity reads it, so the correct
736 * (x-a)/(b-a) is computed here. Recorded in BUGS.md.
737 */
738template <class T>
739T dist_cdf(const Distrib<T>& d, const T& x) {
740 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
741 if (d.is_prior())
742 throw UnsupportedError(ErrorKind{"Prior"},
743 "dist_cdf: a Prior's law is the mixture over its alternatives, which lives with the "
744 "Prior; call prior_cdf (lang/prior.h)");
745 if (d.disabled) throw InputError("dist_cdf: the distribution is disabled");
746 switch (d.type) {
748 // Immediate.evalCDF returns 1 everywhere, the point mass at zero.
749 return one;
750 case ProcessType::DET:
751 return x < d.params[0] ? zero : one;
753 const T a = d.params[0], b = d.params[1];
754 if (x <= a) return zero;
755 if (x >= b) return one;
756 return T((x - a) / (b - a));
757 }
758 case ProcessType::NORMAL: {
759 if constexpr (!num_traits<T>::has_transcendental) {
760 throw UnsupportedError(ErrorKind{"Arithmetic"},
761 "dist_cdf: the Gaussian CDF is a value of erf, which exact arithmetic has no "
762 "representation for");
763 } else {
764 // 0.5 (1 + erf((x - mu) / (sigma sqrt 2))), `Normal.m:87-95`.
765 const double mu = num_traits<T>::to_double(d.params[0]);
766 const double sg = num_traits<T>::to_double(d.params[1]);
768 0.5 * (1.0 + std::erf((num_traits<T>::to_double(x) - mu) /
769 (sg * std::sqrt(2.0)))));
770 }
771 }
773 if (x < zero) return zero;
774 const T p0 = d.params[0];
775 return T(p0 + (one - p0) * dist_cdf(*d.inner, x));
776 }
778 // Tends to 1 - pInf as x -> Inf.
779 if (x < zero) return zero;
780 return T((one - d.params[0]) * dist_cdf(*d.inner, x));
782 if constexpr (!num_traits<T>::has_transcendental) {
783 throw UnsupportedError(ErrorKind{"Arithmetic"},
784 "dist_cdf: the LogLogistic CDF is a real power, which exact arithmetic has no "
785 "representation for");
786 } else {
787 // z/(1+z), z = (x/alpha)^beta.
788 const double xv = num_traits<T>::to_double(x);
789 if (!(xv > 0.0)) return zero;
790 const double z = std::pow(xv / num_traits<T>::to_double(d.params[0]),
792 return num_traits<T>::from_double(std::isinf(z) ? 1.0 : z / (1.0 + z));
793 }
794 }
796 // The empirical CDF of the trace: the fraction of samples <= x.
797 if (d.trace.empty()) throw InputError("dist_cdf: the Replayer carries no samples");
798 std::size_t below = 0;
799 for (const T& v : d.trace)
800 if (!(v > x)) ++below;
801 return T(num_traits<T>::from_int(static_cast<long>(below)) /
802 num_traits<T>::from_int(static_cast<long>(d.trace.size())));
803 }
804 default:
805 break;
806 }
807 if constexpr (!num_traits<T>::has_transcendental) {
808 throw UnsupportedError(ErrorKind{"Arithmetic"},
809 "dist_cdf: the law of this family is an exponential, which exact arithmetic has no "
810 "representation for; use the double or real backend");
811 } else {
812 if (!(x > zero)) return zero;
813 const double xv = num_traits<T>::to_double(x);
814 switch (d.type) {
815 case ProcessType::EXP: {
816 const double lam = num_traits<T>::to_double(d.params[0]);
817 return num_traits<T>::from_double(1.0 - std::exp(-lam * xv));
818 }
819 case ProcessType::ERLANG: {
820 // 1 - sum_{j<r} exp(-alpha x) (alpha x)^j / j!, the reference's form.
821 const double alpha = num_traits<T>::to_double(d.params[0]);
822 const long r = std::lround(num_traits<T>::to_double(d.params[1]));
823 const double z = alpha * xv;
824 double term = std::exp(-z), acc = term;
825 for (long j = 1; j < r; ++j) {
826 term *= z / static_cast<double>(j);
827 acc += term;
828 }
829 return num_traits<T>::from_double(1.0 - acc);
830 }
832 const double p = num_traits<T>::to_double(d.params[0]);
833 const double m1 = num_traits<T>::to_double(d.params[1]);
834 const double m2 = num_traits<T>::to_double(d.params[2]);
835 return num_traits<T>::from_double(p * (1.0 - std::exp(-m1 * xv)) +
836 (1.0 - p) * (1.0 - std::exp(-m2 * xv)));
837 }
838 case ProcessType::PARETO: {
839 const double alpha = num_traits<T>::to_double(d.params[0]);
840 const double scale = num_traits<T>::to_double(d.params[1]);
841 if (xv <= scale) return zero;
842 return num_traits<T>::from_double(1.0 - std::pow(scale / xv, alpha));
843 }
844 case ProcessType::GAMMA: {
845 const double shape = num_traits<T>::to_double(d.params[0]);
846 const double scale = num_traits<T>::to_double(d.params[1]);
847 return num_traits<T>::from_double(mam::gammainc_lower(shape, xv / scale));
848 }
850 const double a = num_traits<T>::to_double(d.params[0]);
851 const double r = num_traits<T>::to_double(d.params[1]);
852 return num_traits<T>::from_double(1.0 - std::exp(-std::pow(xv / a, r)));
853 }
855 const double mu = num_traits<T>::to_double(d.params[0]);
856 const double sg = num_traits<T>::to_double(d.params[1]);
858 0.5 * std::erfc(-(std::log(xv) - mu) / (sg * std::sqrt(2.0))));
859 }
860 default:
861 break;
862 }
863 // The phase-type and MAP families: map_cdf, 1 - pie exp(D0 x) e.
864 const mam::Map<T> m = dist_to_map(d);
865 const std::vector<T> pie = mam::map_pie(m);
866 Matrix<T> A(m.D0.rows(), m.D0.cols(), zero);
867 for (std::size_t i = 0; i < A.rows(); ++i)
868 for (std::size_t j = 0; j < A.cols(); ++j) A(i, j) = T(m.D0(i, j) * x);
869 const Matrix<T> E = expm(A);
870 T acc = zero;
871 for (std::size_t i = 0; i < E.rows(); ++i)
872 for (std::size_t j = 0; j < E.cols(); ++j) acc += T(pie[i] * E(i, j));
873 return T(one - acc);
874 }
875}
876
877/**
878 * The p-quantile, by bisection on `dist_cdf`.
879 *
880 * Port of `Prior.quantile`: bracketing starts at the mean and doubles outward,
881 * which terminates for any law with a finite mean, and the search then halves
882 * 200 times or until the bracket is within FineTol of its own width. Using only
883 * the CDF is what makes it applicable to every family at once, which is the
884 * reason `Prior.discretize` is written in probability space rather than in
885 * parameter space.
886 */
887template <class T>
888T dist_quantile(const Distrib<T>& d, const T& p) {
889 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
890 const T two = num_traits<T>::from_int(2);
891 if (!(p > zero) || !(p < one))
892 throw InputError("dist_quantile: p must lie strictly between 0 and 1");
894 if constexpr (num_traits<T>::has_transcendental) {
895 // Closed form alpha (p/(1-p))^(1/beta): the mean may be infinite,
896 // which the bracketing below cannot start from.
897 const double pv = num_traits<T>::to_double(p);
899 std::pow(pv / (1.0 - pv), 1.0 / num_traits<T>::to_double(d.params[1])));
900 }
901 }
903 const T p0 = d.params[0];
904 if (!(p > p0)) return zero;
905 return dist_quantile(*d.inner, T((p - p0) / (one - p0)));
906 }
907 if (d.type == ProcessType::DEFECTIVE) {
908 const T q = T(one - d.params[0]);
909 if (!(p < q)) {
911 return num_traits<T>::from_double(std::numeric_limits<double>::infinity());
912 else
913 throw UnsupportedError(ErrorKind{"Arithmetic"},
914 "dist_quantile: this quantile of a Defective law is infinite");
915 }
916 return dist_quantile(*d.inner, T(p / q));
917 }
918 T lo = zero;
920 ? d.mean
922 const int max_expand = 200;
923 // A law with mass BELOW ZERO needs the lower end walked down as well. Every
924 // ProcessType family but one is a duration and starts at 0, which is why the
925 // bracket did; a Normal parameter density does not, and leaving lo at 0
926 // would have returned a non-negative "quantile" for any p under F(0) -- a
927 // wrong stratum median for `Prior.discretize`, with no diagnostic.
928 if (d.type == ProcessType::NORMAL) {
929 // Walk both ends out from the mean in doubling multiples of sigma.
930 T step = d.params.size() > 1 ? d.params[1] : one;
931 lo = T(d.mean - step);
932 hi = T(d.mean + step);
933 int j = 0;
934 for (; j < max_expand; ++j) {
935 const bool low_ok = dist_cdf(d, lo) <= p, high_ok = dist_cdf(d, hi) >= p;
936 if (low_ok && high_ok) break;
937 step = T(step * two);
938 if (!low_ok) lo = T(d.mean - step);
939 if (!high_ok) hi = T(d.mean + step);
940 }
941 if (j == max_expand) throw NumericError(ErrorKind{"NonConvergence"}, "dist_quantile: failed to bracket the quantile");
942 } else {
943 int i = 0;
944 for (; i < max_expand; ++i) {
945 if (dist_cdf(d, hi) >= p) break;
946 hi = T(hi * two);
947 }
948 if (i == max_expand) throw NumericError(ErrorKind{"NonConvergence"}, "dist_quantile: failed to bracket the quantile");
949 }
951 for (int k = 0; k < 200; ++k) {
952 const T mid = T((lo + hi) / two);
953 if (dist_cdf(d, mid) < p)
954 lo = mid;
955 else
956 hi = mid;
957 const T scale = hi > one ? hi : one;
958 if (T(hi - lo) <= T(tol * scale)) break;
959 }
960 return T((lo + hi) / two);
961}
962
963/**
964 * Port of `Replayer.isNHPP`: test whether a trace is a sample path of a
965 * NON-HOMOGENEOUS POISSON process, by the conditional-uniform KS test with the
966 * Lewis refinement (`infer_nhpp_ks`).
967 *
968 * WHY THE QUESTION IS WORTH ASKING. A Replayer is used wherever a measured
969 * stream is fed to a solver, and every analytical method that consumes it as an
970 * arrival process assumes SOMETHING about its dependence structure. This test
971 * says whether the Poisson assumption -- independent increments, whatever the
972 * rate does with time -- survives contact with the data, which is the
973 * assumption a time-varying analysis (`mtginf`, `mol`, `tvms`) rests on. A
974 * small p-value says the stream is not Poisson at any rate function, so those
975 * methods are answering a different process.
976 *
977 * The trace holds INTER-ARRIVAL times, so the arrival epochs are their
978 * cumulative sum and the horizon is the last of them.
979 */
980template <class T>
982 if (d.trace.size() < 2)
983 throw InputError("dist_is_nhpp: the trace needs at least two inter-arrival times to test");
984 std::vector<T> epochs;
985 epochs.reserve(d.trace.size());
986 T acc = num_traits<T>::from_int(0);
987 for (std::size_t i = 0; i < d.trace.size(); ++i) {
988 acc = T(acc + d.trace[i]);
989 epochs.push_back(acc);
990 }
991 return infer::infer_nhpp_ks<T>(epochs, epochs.back());
992}
993
994/**
995 * Port of `NHPP.fit`: fit an NHPP to ONE sample path of arrival EPOCHS observed
996 * on [0, horizon], returned as a Distrib usable as a Source arrival.
997 *
998 * "leemis" returns the piecewise-linear integrated rate estimator of Leemis
999 * (1991) exactly: its rate is constant on every gap between consecutive
1000 * arrivals, so the schedule has the knots [0, times, T] as breakpoints and
1001 * N/((N+1) gap) as rates. "powerlaw" fits Lambda(t) = (a t)^b by maximum
1002 * likelihood and returns the schedule on `num_segments` equal segments whose
1003 * rates match the fitted Lambda exactly at every breakpoint.
1004 *
1005 * Only the RATE is identified by one path: Nelson and Leemis (2020) show that
1006 * whether the process is Poisson at all cannot be tested from it. To see how
1007 * much a conclusion leans on the Poisson assumption, rerun with an NNPP of the
1008 * same rate and a dispersion ratio swept around 1.
1009 */
1010template <class T>
1011Distrib<T> dist_fit_nhpp(const std::vector<T>& times, const T& horizon,
1012 const std::string& method = "leemis", std::size_t num_segments = 100,
1013 bool cyclic = false) {
1014 if (method == "leemis") {
1015 const infer::NhppLeemisResult<T> est = infer::infer_nhpp_leemis<T>(times, horizon);
1016 return Distrib<T>::nhpp(est.knots, est.rates, cyclic);
1017 }
1018 if (method == "powerlaw") {
1019 using std::pow;
1020 if (num_segments < 1)
1021 throw InputError("dist_fit_nhpp: num_segments must be a positive integer");
1023 const T K = num_traits<T>::from_int(static_cast<long>(num_segments));
1024 std::vector<T> bp(num_segments + 1), rt(num_segments);
1025 for (std::size_t k = 0; k <= num_segments; ++k)
1026 bp[k] = num_traits<T>::from_int(static_cast<long>(k)) * (horizon / K);
1027 bp[num_segments] = horizon;
1028 for (std::size_t k = 0; k < num_segments; ++k) {
1029 const T lo = pow(est.scale * bp[k], est.shape);
1030 const T hi = pow(est.scale * bp[k + 1], est.shape);
1031 rt[k] = (hi - lo) / (bp[k + 1] - bp[k]);
1032 }
1033 return Distrib<T>::nhpp(bp, rt, cyclic);
1034 }
1035 throw InputError("dist_fit_nhpp: method must be 'leemis' or 'powerlaw'");
1036}
1037
1038} // namespace lang
1039} // namespace line
1040
1041#endif // LINE_LANG_DISTRIBUTION_H
Minimal-order acyclic phase-type fit of the first three moments (matlab/lib/kpctoolbox/aph/aph_fit....
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
NumericError(const std::string &what)
Definition error.h:112
UnsupportedError(const std::string &what)
Definition error.h:119
Equilibrium distribution of a discrete-time Markov chain, and stochastic complementation.
The exception types the port throws.
Matrix exponential by scaling and squaring with a diagonal Pade approximant.
Fitting a nonstationary Poisson process from ONE observed sequence of arrival times.
Kolmogorov-Smirnov tests for a non-homogeneous Poisson arrival process.
Enumerations and the minimal distribution descriptor shared by the model layer of the C++ port.
Transient distribution of a level-independent-in-the-tail QBD by an adaptive Taylor series (libQBD QB...
Markovian arrival process descriptors: stationary vectors, rate, moments, autocorrelation and the ind...
MAP constructors and structural transformations.
Dense matrix and non-owning view.
NhppKsResult< Tv > infer_nhpp_ks(const std::vector< Tv > &times, const Tv &T, const std::function< Tv(const Tv &)> &cumRate=std::function< Tv(const Tv &)>(), NhppKsMethod method=NhppKsMethod::Lewis, const Tv &T0=num_traits< Tv >::from_int(0))
Kolmogorov-Smirnov tests for a non-homogeneous Poisson arrival process.
NhppPowerLawResult< T > infer_nhpp_powerlaw(const std::vector< T > &times, const T &horizon, double alpha=0.05)
Maximum likelihood power-law NHPP fit, Lambda(t) = (a t)^b, from one sample path, with observed-infor...
NhppLeemisResult< T > infer_nhpp_leemis(const std::vector< T > &times, const T &horizon, const std::vector< T > &tq=std::vector< T >(), double alpha=0.05)
Nonparametric integrated-rate estimate of an NHPP from one sample path: the step-function estimator w...
mam::Map< T > dist_to_map(const Distrib< T > &d)
The (D0,D1) pair that reaches sn.proc.
T dist_quantile(const Distrib< T > &d, const T &p)
The p-quantile, by bisection on dist_cdf.
infer::NhppKsResult< T > dist_is_nhpp(const Distrib< T > &d)
Port of Replayer.isNHPP: test whether a trace is a sample path of a NON-HOMOGENEOUS POISSON process,...
T dist_lst(const Distrib< T > &d, const T &s)
sn.lst: the Laplace-Stieltjes transform E[exp(-sX)].
unsigned convert_to_map_phases(double scv)
The number of Erlang phases convertToMAP picks for a non-Markovian distribution: 20 when the SCV is b...
T dist_cdf(const Distrib< T > &d, const T &x)
F(x) = P{X <= x}, MATLAB's Distribution.evalCDF.
std::vector< T > dist_pie(const Distrib< T > &d)
sn.pie: the phase distribution seen by an arriving job.
@ NORMAL
A Gaussian, and the ONE family whose value is not MATLAB's, because MATLAB has none to copy: ProcessT...
Definition lang_types.h:650
@ LOGLOGISTIC
Three reliability laws of Trivedi and Bobbio, "Reliability andAvailability Engineering" (2017),...
Definition lang_types.h:622
void dmap_refresh_moments(Distrib< T > &d)
The first two moments of a DISCRETE-time MAP, from its own law.
bool process_is_markovian(ProcessType p)
ProcessType.isMarkovian: true when sn.proc carries an exact matrix representation of the law,...
Definition lang_types.h:713
void dist_refresh_moments(Distrib< T > &d)
Fill in the first two moments of a distribution given by its matrices.
void reject_prior(const char *who)
The refusal every lowering of a Prior shares.
Distrib< T > dist_fit_nhpp(const std::vector< T > &times, const T &horizon, const std::string &method="leemis", std::size_t num_segments=100, bool cyclic=false)
Port of NHPP.fit: fit an NHPP to ONE sample path of arrival EPOCHS observed on [0,...
T dist_moment(const Distrib< T > &d, unsigned k)
The k-th raw moment.
double gammainc_lower(double a, double x)
Regularized lower incomplete gamma P(a, x), MATLAB's gammainc(x, a, 'lower').
T map_mean(const Map< T > &m)
Mean inter-arrival time, 1/lambda.
Definition map_moment.h:101
AphFitResult< T > aph_fit(const T &e1, const T &e2, const T &e3, unsigned nmax, const T &tol)
Fit an APH(n) with n <= nmax to the raw moments e1, e2, e3.
Definition aph_fit.h:176
Map< T > map_erlang(const T &mean, unsigned k)
Erlang-k renewal MAP with the given mean (map_erlang.m).
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
T map_scv(const Map< T > &m)
Squared coefficient of variation.
Definition map_moment.h:140
T map_moment(const Map< T > &m, unsigned k)
Raw moment of order k of the inter-arrival time: k!
Definition map_moment.h:118
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
Matrix< T > expm(const Matrix< T > &A)
Matrix exponential exp(A).
Definition expm.h:141
Number-type abstraction for the templated API port.
Adaptive quadrature for the qsys functions whose MATLAB originals call integral(),...
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
Outcome of the KS test.
Outcome of infer_nhpp_leemis.
std::vector< T > knots
breakpoints [0, times, T], length N+2
std::vector< T > rates
piecewise-constant rate on each gap, length N+1
Outcome of infer_nhpp_powerlaw.
T shape
the power-law shape b
T scale
the power-law scale a
static Distrib nhpp(const std::vector< T > &breakpoints, const std::vector< T > &rates, bool cyclic)
NHPP(breakpoints, rates, cyclic): a MAPt of ORDER ONE, which is what an inhomogeneous Poisson process...
bool has_map() const
True when the type carries a (D0,D1) pair of its own.
Matrix< T > D0
The (D0,D1) pair when the type carries one directly.
Definition lang_types.h:921
std::shared_ptr< Distrib< T > > inner
The wrapped law of a MassAtOrigin or a Defective, null otherwise.
Definition lang_types.h:951
std::vector< T > params
Constructor arguments, in MATLAB getParam order.
Definition lang_types.h:894
std::vector< T > trace
Replayer / Trace samples; empty for every other type.
Definition lang_types.h:896
bool is_prior() const
Definition lang_types.h:961
static constexpr double FineTol
Definition lang_types.h:823
static constexpr double CoarseTol
Definition lang_types.h:824
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