LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
infer_nhpp_fit.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_API_INFER_NHPP_FIT_H
6#define LINE_API_INFER_NHPP_FIT_H
7
8/**
9 * @file
10 * @ingroup api_infer
11 * Fitting a nonstationary Poisson process from ONE observed sequence of
12 * arrival times.
13 *
14 * Templated port of matlab/src/api/infer/infer_nhpp_leemis.m and
15 * infer_nhpp_powerlaw.m, cross-checked against
16 * jar/src/main/java/jline/api/infer/InferNhppFit.java.
17 *
18 * TWO NONPARAMETRIC ESTIMATORS. The step-function estimator Lambdabar(t) counts
19 * the arrivals in (0,t]. It is unbiased for Lambda(t) and, a Poisson count
20 * having its mean as variance, carries the approximate pointwise interval
21 * Lambdabar(t) -/+ z sqrt(Lambdabar(t)), whose width grows with t: from one
22 * path the count by time t is the only information about Lambda(t), so the
23 * estimate is NOT consistent as T grows. For simulation the piecewise-linear
24 * estimator of Leemis (1991) interpolates it,
25 * Lambdahat(t) = iN/(N+1) + N(t-T_i)/((N+1)(T_{i+1}-T_i)),
26 * whose derivative is constant on each gap between arrivals: exactly an NHPP
27 * schedule (see lang::dist_fit_nhpp).
28 *
29 * THE POWER LAW. Lambda(t) = (a t)^b has the closed-form maximum likelihood
30 * estimator b = N/(N ln T - sum ln T_i), a = N^(1/b)/T, and the inverse of the
31 * observed information matrix gives Wald intervals.
32 *
33 * ARITHMETIC. sqrt, log and pow: transcendental only.
34 *
35 * Reference: B. L. Nelson, L. M. Leemis (2020). The ease of fitting but
36 * futility of testing a nonstationary Poisson process from one sample path.
37 * Proc. Winter Simulation Conference, 266-276; L. M. Leemis (1991).
38 * Nonparametric estimation of the cumulative intensity function for a
39 * nonhomogeneous Poisson process. Management Science 37(7), 886-900.
40 */
41
42#include <algorithm>
43#include <cmath>
44#include <cstddef>
45#include <string>
46#include <vector>
47
49#include "line/num/number.h"
50#include "line/util/error.h"
51
52namespace line {
53namespace infer {
54
55/** Outcome of infer_nhpp_leemis. */
56template <class T>
58 std::size_t n = 0; ///< number of arrivals N
59 T horizon; ///< the observation horizon
60 std::vector<T> knots; ///< breakpoints [0, times, T], length N+2
61 std::vector<T> knotValues; ///< piecewise-linear estimate at the knots
62 std::vector<T> rates; ///< piecewise-constant rate on each gap, length N+1
63 std::vector<T> tq; ///< query points
64 std::vector<T> cumRate; ///< piecewise-linear estimate at tq
65 std::vector<T> step; ///< step-function estimate at tq
66 std::vector<T> lower; ///< lower pointwise bound at tq, floored at zero
67 std::vector<T> upper; ///< upper pointwise bound at tq
68};
69
70/** Outcome of infer_nhpp_powerlaw. */
71template <class T>
73 std::size_t n = 0; ///< number of arrivals N
74 T horizon; ///< the observation horizon
75 T scale; ///< the power-law scale a
76 T shape; ///< the power-law shape b
77 T loglik; ///< maximised log-likelihood
78 T info[2][2]; ///< observed information, order (a, b)
79 T cov[2][2]; ///< its inverse
80 T se[2]; ///< standard errors of (a, b)
81 T scaleCI[2]; ///< Wald interval for a
82 T shapeCI[2]; ///< Wald interval for b
83};
84
85namespace detail {
86
87/** The knots [0, sorted times, T], checked to be strictly increasing. */
88template <class T>
89std::vector<T> nhpp_fit_knots(const std::vector<T>& times, const T& horizon, const char* caller) {
90 const T zero = num_traits<T>::from_int(0);
91 if (!(horizon > zero) || !std::isfinite(num_traits<T>::to_double(horizon)))
92 throw InputError(std::string(caller) + ": the horizon T must be a positive finite scalar");
93 if (times.empty())
94 throw InputError(std::string(caller) + ": at least one arrival is needed to estimate the rate");
95 std::vector<T> t = times;
96 std::sort(t.begin(), t.end());
97 if (!(t.front() > zero) || t.back() > horizon)
98 throw InputError(std::string(caller) + ": the arrival times must lie in (0,T]");
99 std::vector<T> k;
100 k.reserve(t.size() + 2);
101 k.push_back(zero);
102 k.insert(k.end(), t.begin(), t.end());
103 k.push_back(horizon);
104 for (std::size_t i = 1; i < k.size(); ++i)
105 if (!(k[i] > k[i - 1]))
106 throw InputError(std::string(caller) +
107 ": the arrival times must be distinct and strictly below T: a tie "
108 "gives the piecewise-linear estimator a jump that no finite rate "
109 "carries");
110 return k;
111}
112
113/** Number of entries of the sorted range [first, last) that are <= x. */
114template <class T, class It>
115std::size_t nhpp_fit_upper(It first, It last, const T& x) {
116 return static_cast<std::size_t>(std::upper_bound(first, last, x) - first);
117}
118
119} // namespace detail
120
121/**
122 * @brief Nonparametric integrated-rate estimate of an NHPP from one sample
123 * path: the step-function estimator with its pointwise interval and
124 * the piecewise-linear estimator of Leemis (1991).
125 *
126 * @param times distinct arrival epochs in (0,T]
127 * @param horizon the observation horizon T
128 * @param tq query points in [0,T]; the knots [0, times, T] when empty
129 * @param alpha significance level of the pointwise interval
130 */
131template <class T>
132NhppLeemisResult<T> infer_nhpp_leemis(const std::vector<T>& times, const T& horizon,
133 const std::vector<T>& tq = std::vector<T>(),
134 double alpha = 0.05) {
135 static_assert(num_traits<T>::has_transcendental, "infer_nhpp_leemis needs sqrt for the interval");
136 using std::sqrt;
137 const std::vector<T> k = detail::nhpp_fit_knots(times, horizon, "infer_nhpp_leemis");
138 const std::size_t n = k.size() - 2;
139 if (!(alpha > 0.0 && alpha < 1.0))
140 throw InputError("infer_nhpp_leemis: alpha must lie in (0,1)");
141 const T zero = num_traits<T>::from_int(0);
142 const T nT = num_traits<T>::from_int(static_cast<long>(n));
143 const T n1 = num_traits<T>::from_int(static_cast<long>(n + 1));
144
146 r.n = n;
147 r.horizon = horizon;
148 r.knots = k;
149 r.knotValues.resize(n + 2);
150 for (std::size_t i = 0; i <= n; ++i)
151 r.knotValues[i] = num_traits<T>::from_int(static_cast<long>(i)) * nT / n1;
152 r.knotValues[n + 1] = nT;
153 r.rates.resize(n + 1);
154 for (std::size_t i = 0; i <= n; ++i) r.rates[i] = nT / (n1 * (k[i + 1] - k[i]));
155
156 if (tq.empty()) {
157 r.tq = k;
158 } else {
159 r.tq = tq;
160 for (const T& x : r.tq)
161 if (x < zero || x > horizon)
162 throw InputError("infer_nhpp_leemis: the query points must lie in [0,T]");
163 }
164 const T z = num_traits<T>::from_double(line::sim::sim_norminv(1.0 - alpha / 2.0));
165 const std::size_t m = r.tq.size();
166 r.cumRate.resize(m);
167 r.step.resize(m);
168 r.lower.resize(m);
169 r.upper.resize(m);
170 for (std::size_t j = 0; j < m; ++j) {
171 const T& q = r.tq[j];
172 // Bin of q, with q == T in the last (right-closed) bin.
173 std::size_t idx = detail::nhpp_fit_upper(k.begin(), k.end(), q);
174 idx = idx == 0 ? 0 : idx - 1;
175 if (idx > n) idx = n;
176 r.cumRate[j] = r.knotValues[idx] + r.rates[idx] * (q - k[idx]);
177 const std::size_t s = detail::nhpp_fit_upper(k.begin() + 1, k.end() - 1, q);
178 const T sT = num_traits<T>::from_int(static_cast<long>(s));
179 const T half = z * sqrt(sT);
180 r.step[j] = sT;
181 const T lo = sT - half;
182 r.lower[j] = lo > zero ? lo : zero;
183 r.upper[j] = sT + half;
184 }
185 return r;
186}
187
188/**
189 * @brief Maximum likelihood power-law NHPP fit, Lambda(t) = (a t)^b, from one
190 * sample path, with observed-information Wald intervals.
191 *
192 * @param times arrival epochs in (0,T]
193 * @param horizon the observation horizon T
194 * @param alpha significance level of the Wald intervals
195 */
196template <class T>
197NhppPowerLawResult<T> infer_nhpp_powerlaw(const std::vector<T>& times, const T& horizon,
198 double alpha = 0.05) {
199 static_assert(num_traits<T>::has_transcendental, "infer_nhpp_powerlaw needs log and pow");
200 using std::log;
201 using std::pow;
202 using std::sqrt;
203 if (!(alpha > 0.0 && alpha < 1.0))
204 throw InputError("infer_nhpp_powerlaw: alpha must lie in (0,1)");
205 const T zero = num_traits<T>::from_int(0);
206 const T one = num_traits<T>::from_int(1);
207 if (!(horizon > zero) || !std::isfinite(num_traits<T>::to_double(horizon)))
208 throw InputError("infer_nhpp_powerlaw: the horizon T must be a positive finite scalar");
209 if (times.empty())
210 throw InputError("infer_nhpp_powerlaw: at least one arrival is needed to fit the power law");
211 const std::size_t n = times.size();
212 const T nT = num_traits<T>::from_int(static_cast<long>(n));
213 T sumLog = zero;
214 for (const T& x : times) {
215 if (!(x > zero) || x > horizon)
216 throw InputError("infer_nhpp_powerlaw: the arrival times must lie in (0,T]");
217 sumLog += log(x);
218 }
219 const T denom = nT * log(horizon) - sumLog;
220 if (!(denom > zero))
221 throw InputError("infer_nhpp_powerlaw: every arrival is at T, so the power-law shape is unbounded");
222 const T b = nT / denom;
223 const T a = pow(nT, one / b) / horizon;
224 const T aT = a * horizon;
225 const T L = pow(aT, b);
226 const T lnaT = log(aT);
227 const T two = num_traits<T>::from_int(2);
228
230 r.n = n;
231 r.horizon = horizon;
232 r.scale = a;
233 r.shape = b;
234 r.loglik = nT * b * log(a) + nT * log(b) + (b - one) * sumLog - L;
235 // Negated second derivatives of ln L, Nelson and Leemis (2020) Section 3.2.
236 const T Tb = pow(horizon, b);
237 const T iaa = nT * b / (a * a) + b * (b - one) * pow(a, b - two) * Tb;
238 const T iab = -nT / a + pow(a, b - one) * Tb * (one + b * lnaT);
239 const T ibb = nT / (b * b) + L * lnaT * lnaT;
240 const T det = iaa * ibb - iab * iab;
241 r.info[0][0] = iaa;
242 r.info[0][1] = iab;
243 r.info[1][0] = iab;
244 r.info[1][1] = ibb;
245 r.cov[0][0] = ibb / det;
246 r.cov[0][1] = -iab / det;
247 r.cov[1][0] = -iab / det;
248 r.cov[1][1] = iaa / det;
249 r.se[0] = sqrt(r.cov[0][0]);
250 r.se[1] = sqrt(r.cov[1][1]);
251 const T z = num_traits<T>::from_double(line::sim::sim_norminv(1.0 - alpha / 2.0));
252 r.scaleCI[0] = a - z * r.se[0];
253 r.scaleCI[1] = a + z * r.se[0];
254 r.shapeCI[0] = b - z * r.se[1];
255 r.shapeCI[1] = b + z * r.se[1];
256 return r;
257}
258
259} // namespace infer
260} // namespace line
261
262#endif // LINE_API_INFER_NHPP_FIT_H
InputError(const std::string &what)
Definition error.h:105
The exception types the port throws.
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...
double sim_norminv(double p)
Standard normal quantile function.
Definition sim_dist.h:62
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
Number-type abstraction for the templated API port.
Normal and Student t quantiles used by the output-analysis routines.
Outcome of infer_nhpp_leemis.
std::vector< T > tq
query points
std::vector< T > knots
breakpoints [0, times, T], length N+2
T horizon
the observation horizon
std::vector< T > rates
piecewise-constant rate on each gap, length N+1
std::size_t n
number of arrivals N
std::vector< T > knotValues
piecewise-linear estimate at the knots
std::vector< T > cumRate
piecewise-linear estimate at tq
std::vector< T > upper
upper pointwise bound at tq
std::vector< T > step
step-function estimate at tq
std::vector< T > lower
lower pointwise bound at tq, floored at zero
Outcome of infer_nhpp_powerlaw.
T shape
the power-law shape b
T se[2]
standard errors of (a, b)
T scaleCI[2]
Wald interval for a.
T horizon
the observation horizon
T info[2][2]
observed information, order (a, b)
T shapeCI[2]
Wald interval for b.
T scale
the power-law scale a
T loglik
maximised log-likelihood
std::size_t n
number of arrivals N