LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
trace_skew.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_TRACE_SKEW_H
6#define LINE_API_TRACE_TRACE_SKEW_H
7
8/**
9 * @file
10 * @ingroup api_trace
11 * Bias-corrected sample skewness (MATLAB's skewness(S,0), equivalently the
12 * G1 estimator).
13 *
14 * Templated port of matlab/lib/kpctoolbox/trace/trace_skew.m, cross-checked
15 * against jar/src/main/java/jline/api/trace/TraceSkew.java, which delegates
16 * to Apache Commons Math's Skewness. The two are algebraically IDENTICAL:
17 * Apache computes n/((n-1)(n-2)) * sum d^3 / s^3 with s the n-1 standard
18 * deviation, MATLAB computes m3/m2^{3/2} * sqrt((n-1)/n) * n/(n-2), and both
19 * reduce to
20 *
21 * G1 = sqrt(n(n-1)) / (n-2) * m3 / m2^{3/2}, m_k = (1/n) sum (x-xbar)^k.
22 *
23 * That closed form is what is evaluated here, so the result is symmetric in
24 * the two references rather than favouring one rounding order.
25 *
26 * ARITHMETIC: a 3/2 power of the second central moment.
27 * static_assert(num_traits<T>::has_transcendental)
28 */
29
30#include <cstddef>
31#include <vector>
32
35#include "line/num/number.h"
36#include "line/util/error.h"
37
38namespace line {
39namespace trace {
40
41/**
42 * @brief Bias-corrected sample skewness (MATLAB's skewness(S,0), equivalently
43 * the G1 estimator).
44 *
45 * @param S the trace, at least 3 samples.
46 */
47template <class T>
48T trace_skew(const std::vector<T>& S) {
50 "trace_skew requires transcendental arithmetic");
51 detail::require_nonempty(S, "trace_skew");
52 const long n = static_cast<long>(S.size());
53 if (n < 3) throw InputError("trace_skew: the skewness needs at least three samples");
54 const T mu = trace_mean(S);
56 for (std::size_t i = 0; i < S.size(); ++i) {
57 const T d = S[i] - mu;
58 m2 += d * d;
59 m3 += d * d * d;
60 }
61 const T nt = num_traits<T>::from_int(n);
62 m2 /= nt;
63 m3 /= nt;
64 if (m2 == num_traits<T>::from_int(0))
65 throw NumericError("trace_skew: the trace is constant, the skewness is undefined");
66 const T corr = detail::num_sqrt(T(nt * num_traits<T>::from_int(n - 1))) / num_traits<T>::from_int(n - 2);
67 return corr * m3 / (m2 * detail::num_sqrt(m2));
68}
69
70} // namespace trace
71} // namespace line
72
73#endif // LINE_API_TRACE_TRACE_SKEW_H
InputError(const std::string &what)
Definition error.h:39
NumericError(const std::string &what)
Definition error.h:45
The exception types the port throws.
T trace_skew(const std::vector< T > &S)
Bias-corrected sample skewness (MATLAB's skewness(S,0), equivalently the G1 estimator).
Definition trace_skew.h:48
T trace_mean(const std::vector< T > &S)
(1/n) sum_i S(i).
Definition trace_mean.h:31
Number-type abstraction for the templated API port.
Sample mean of a trace.
Shared declarations for the empirical trace statistics domain.