5#ifndef LINE_LANG_DISTRIBUTION_H
6#define LINE_LANG_DISTRIBUTION_H
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);
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");
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");
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()))
115 "dist_to_map: a LogLogistic with shape <= 1 has an infinite mean");
132 for (
const T& x : d.
trace) {
137 return mam::aph_fit(T(m1 / n), T(m2 / n), T(m3 / n)).aph;
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");
201 if (s == zero)
return one;
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");
217 auto g = [&a, &b, &s](
const T& u) -> T {
219 const double w = std::max(1.0 - uv, std::numeric_limits<double>::min());
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");
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");
260 "dist_lst: the transform of a Uniform evaluates exp, which exact arithmetic "
261 "has no representation for; use the double or real backend");
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");
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");
302 auto g = [&alpha, &k, &s, &tiny, &one](
const T& u) -> T {
304 const T uu = u > tiny ? u : tiny;
310 const T val = qsys::detail::num_integral<T>(g, zero, one,
313 return T(alpha * val);
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");
326 const double upper = a * std::pow(-std::log(1e-10), 1.0 / r);
328 const double dx = upper / n;
330 for (
int i = 1; i <= n; ++i) {
331 const double x = i * dx;
333 (r / a) * std::pow(x / a, r - 1.0) * std::exp(-std::pow(x / a, r));
334 acc += std::exp(-sv * x) * pdf;
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");
348 const double upper = std::exp(mu + 5.0 * sg);
350 const double dx = upper / n;
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;
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");
382 const std::size_t n = m.
D0.rows();
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));
387 std::vector<T> rhs(n, zero);
388 for (std::size_t i = 0; i < n; ++i) {
390 for (std::size_t j = 0; j < n; ++j) acc += m.
D0(i, j);
394 std::vector<T> x = rhs;
395 for (std::size_t col = 0; col < n; ++col) {
396 std::size_t best = col;
398 for (std::size_t r = col + 1; r < n; ++r) {
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]);
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]);
419 for (std::size_t i = 0; i < n; ++i) out += pie[i] * T(x[i] / A(i, i));
427T
dist_cdf(
const Distrib<T>& d,
const T& x);
453 "dist_lst at a complex argument requires transcendental arithmetic");
462 if (std::abs(s) == 0.0)
return std::complex<double>(1.0, 0.0);
466 return std::complex<double>(1.0, 0.0);
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);
476 auto re = [&](
const double& u) ->
double {
477 return u > 0.0 ? std::exp(-s * q(u)).real() : 1.0;
479 auto im = [&](
const double& u) ->
double {
480 return u > 0.0 ? std::exp(-s * q(u)).imag() : 0.0;
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);
487 std::complex<double> acc(0.0, 0.0);
489 return acc /
static_cast<double>(d.
trace.size());
496 return (std::exp(-s * a) - std::exp(-s * b)) / (s * (b - a));
501 return std::exp(-mu * s + sg * sg * s * s / 2.0);
506 return std::pow(std::complex<double>(1.0, 0.0) + s * scale, -shape);
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) {
523 for (std::size_t j = 0; j < n; ++j) {
525 A[i][j] = (i == j ? s : std::complex<double>(0.0, 0.0)) - d0;
528 x[i] = std::complex<double>(-exit, 0.0);
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; }
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)
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];
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];
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];
557 const std::size_t n_grid = 2400;
559 double hi = mean * 60.0;
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);
568 for (std::size_t i = 0; i < n_grid; ++i) {
569 const double right =
static_cast<double>(i + 1) * step;
571 const double w = cur - prev;
573 if (w == 0.0)
continue;
575 acc += w * std::exp(-s * ((
static_cast<double>(i) + 0.5) * step));
577 return mass > 0.0 ? acc / mass : std::complex<double>(1.0, 0.0);
590 if (k == 0)
return one;
598 for (
unsigned i = 0; i < k; ++i) v = T(v * d.
mean);
604 T pa = one, pb = one;
605 for (
unsigned i = 0; i <= k; ++i) {
616 throw NumericError(
ErrorKind{
"Overflow"},
"dist_moment: the Pareto moment of this order is infinite");
618 for (
unsigned i = 0; i < k; ++i) ps = T(ps * scale);
619 return T(alpha * ps / (alpha - m));
624 for (
const T& x : d.
trace) {
626 for (
unsigned i = 0; i < k; ++i) v = T(v * x);
634 "dist_moment: the moments of a Gamma are values of the gamma function, which "
635 "exact arithmetic has no representation for");
640 std::pow(scale,
static_cast<double>(k)));
646 "dist_moment: the moments of a Weibull are values of the gamma function, "
647 "which exact arithmetic has no representation for");
652 std::tgamma(1.0 + k / r));
658 "dist_moment: the moments of a LogLogistic are values of sin, which exact "
659 "arithmetic has no representation for");
664 if (
static_cast<double>(k) >= r)
666 const double b =
static_cast<double>(k) * 3.14159265358979323846 / r;
679 "dist_moment: the moments of a Defective law are infinite");
685 "dist_moment: the moments of a Lognormal are values of exp, which exact "
686 "arithmetic has no representation for");
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 +
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)");
751 return x < d.
params[0] ? zero : one;
754 if (x <= a)
return zero;
755 if (x >= b)
return one;
756 return T((x - a) / (b - a));
761 "dist_cdf: the Gaussian CDF is a value of erf, which exact arithmetic has no "
762 "representation for");
769 (sg * std::sqrt(2.0)))));
773 if (x < zero)
return zero;
779 if (x < zero)
return zero;
784 "dist_cdf: the LogLogistic CDF is a real power, which exact arithmetic has no "
785 "representation for");
789 if (!(xv > 0.0))
return zero;
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;
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");
812 if (!(x > zero))
return zero;
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);
836 (1.0 - p) * (1.0 - std::exp(-m2 * xv)));
841 if (xv <= scale)
return zero;
858 0.5 * std::erfc(-(std::log(xv) - mu) / (sg * std::sqrt(2.0))));
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);
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));
891 if (!(p > zero) || !(p < one))
892 throw InputError(
"dist_quantile: p must lie strictly between 0 and 1");
904 if (!(p > p0))
return zero;
908 const T q = T(one - d.
params[0]);
914 "dist_quantile: this quantile of a Defective law is infinite");
922 const int max_expand = 200;
931 lo = T(d.
mean - step);
932 hi = T(d.
mean + step);
934 for (; j < max_expand; ++j) {
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);
941 if (j == max_expand)
throw NumericError(
ErrorKind{
"NonConvergence"},
"dist_quantile: failed to bracket the quantile");
944 for (; i < max_expand; ++i) {
948 if (i == max_expand)
throw NumericError(
ErrorKind{
"NonConvergence"},
"dist_quantile: failed to bracket the quantile");
951 for (
int k = 0; k < 200; ++k) {
952 const T mid = T((lo + hi) / two);
957 const T scale = hi > one ? hi : one;
958 if (T(hi - lo) <= T(tol * scale))
break;
960 return T((lo + hi) / two);
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());
987 for (std::size_t i = 0; i < d.
trace.size(); ++i) {
988 acc = T(acc + d.
trace[i]);
989 epochs.push_back(acc);
1012 const std::string& method =
"leemis", std::size_t num_segments = 100,
1013 bool cyclic =
false) {
1014 if (method ==
"leemis") {
1018 if (method ==
"powerlaw") {
1020 if (num_segments < 1)
1021 throw InputError(
"dist_fit_nhpp: num_segments must be a positive integer");
1024 std::vector<T> bp(num_segments + 1), rt(num_segments);
1025 for (std::size_t k = 0; k <= num_segments; ++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]);
1035 throw InputError(
"dist_fit_nhpp: method must be 'leemis' or 'powerlaw'");
Minimal-order acyclic phase-type fit of the first three moments (matlab/lib/kpctoolbox/aph/aph_fit....
NumericError(const std::string &what)
UnsupportedError(const std::string &what)
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...
Dense matrix and non-owning view.
NhppKsResult< Tv > infer_nhpp_ks(const std::vector< Tv > ×, 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 > ×, 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 > ×, 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...
@ LOGLOGISTIC
Three reliability laws of Trivedi and Bobbio, "Reliability andAvailability Engineering" (2017),...
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,...
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 > ×, 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.
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.
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).
T map_scv(const Map< T > &m)
Squared coefficient of variation.
T map_moment(const Map< T > &m, unsigned k)
Raw moment of order k of the inter-arrival time: k!
Conservation laws of a layered queueing network, enumerated from its structure.
Matrix< T > expm(const Matrix< T > &A)
Matrix exponential exp(A).
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....
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.
std::shared_ptr< Distrib< T > > inner
The wrapped law of a MassAtOrigin or a Defective, null otherwise.
std::vector< T > params
Constructor arguments, in MATLAB getParam order.
std::vector< T > trace
Replayer / Trace samples; empty for every other type.
static constexpr double FineTol
static constexpr double CoarseTol
A MAP as the pair of matrices (D0, D1).