LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
autocov.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_TRACE_AUTOCOV_H
6#define LINE_API_TRACE_AUTOCOV_H
7
8/**
9 * @file
10 * @ingroup api_trace
11 * Sample autocovariance sequence of a trace, lags 0 .. n-2.
12 *
13 * Templated port of matlab/lib/kpctoolbox/contrib/autocov.m, cross-checked
14 * against the private autocov() of
15 * jar/src/main/java/jline/api/trace/Trace_var.java (identical formula; the
16 * MATLAB implementation evaluates it by FFT, which is the same quantity up to
17 * rounding but is not usable in exact arithmetic, so this port evaluates the
18 * defining sum directly).
19 *
20 * acv(p) = 1/(n-p) sum_{i=1}^{n-p} (S_i - Sbar)(S_{i+p} - Sbar)
21 *
22 * The lag-0 term is therefore the POPULATION variance (denominator n), not
23 * MATLAB's var: the header comment of autocov.m claiming acv(1) = var(X) is
24 * wrong by the factor n/(n-1). See trace_var.h.
25 *
26 * ARITHMETIC: sums, products and divisions, exact in Rational.
27 */
28
29#include <cstddef>
30#include <vector>
31
34#include "line/num/number.h"
35#include "line/util/error.h"
36
37namespace line {
38namespace trace {
39
40/**
41 * @brief Sample autocovariance sequence of a trace, lags 0 .. n-2.
42 *
43 * @return acv[0..n-2], acv[p] the lag-p sample autocovariance.
44 */
45template <class T>
46std::vector<T> autocov(const std::vector<T>& S) {
47 detail::require_nonempty(S, "autocov");
48 const std::size_t n = S.size();
49 if (n < 2) throw InputError("autocov: the trace must have at least two samples");
50 const T mu = trace_mean(S);
51 std::vector<T> X(n);
52 for (std::size_t i = 0; i < n; ++i) X[i] = S[i] - mu;
53
54 std::vector<T> acv(n - 1, num_traits<T>::from_int(0));
55 for (std::size_t p = 0; p + 1 < n; ++p) {
57 for (std::size_t i = 0; i + p < n; ++i) s += X[i] * X[i + p];
58 acv[p] = s / num_traits<T>::from_int(static_cast<long>(n - p));
59 }
60 return acv;
61}
62
63} // namespace trace
64} // namespace line
65
66#endif // LINE_API_TRACE_AUTOCOV_H
InputError(const std::string &what)
Definition error.h:39
The exception types the port throws.
T trace_mean(const std::vector< T > &S)
(1/n) sum_i S(i).
Definition trace_mean.h:31
std::vector< T > autocov(const std::vector< T > &S)
Sample autocovariance sequence of a trace, lags 0 .
Definition autocov.h:46
Number-type abstraction for the templated API port.
Sample mean of a trace.
Shared declarations for the empirical trace statistics domain.