libqe 0.2.5
QE C++ library
Loading...
Searching...
No Matches
stats.hpp
Go to the documentation of this file.
1
10#ifndef LIBQE_STATS_HPP
11#define LIBQE_STATS_HPP
12
13#include <armadillo>
14#include <algorithm>
15#include <cmath>
16#include <limits>
17#include <stdexcept>
18#include <vector>
19
20namespace qe {
21
22// ---------------------------------------------------------------------------
25// ---------------------------------------------------------------------------
26
35inline arma::mat center_points(arma::mat values) {
36 return values.each_row() - arma::mean(values);
37}
38
40
42
43// ---------------------------------------------------------------------------
44// Normal quantile (probit) — pure C++, no R dependency
45// Rational approximation by Peter Acklam; max abs error < 1.15e-9.
46// Used by libena's ena_correlation() (rENA) so it doesn't need Rcpp::qnorm.
47// ---------------------------------------------------------------------------
48
49inline double normal_quantile(double p) {
50 static const double a[] = {
51 -3.969683028665376e+01, 2.209460984245205e+02,
52 -2.759285104469687e+02, 1.383577518672690e+02,
53 -3.066479806614716e+01, 2.506628277459239e+00
54 };
55 static const double b[] = {
56 -5.447609879822406e+01, 1.615858368580409e+02,
57 -1.556989798598866e+02, 6.680131188771972e+01,
58 -1.328068155288572e+01
59 };
60 static const double c[] = {
61 -7.784894002430293e-03, -3.223964580411365e-01,
62 -2.400758277161838e+00, -2.549732539343734e+00,
63 4.374664141464968e+00, 2.938163982698783e+00
64 };
65 static const double d[] = {
66 7.784695709041462e-03, 3.224671290700398e-01,
67 2.445134137142996e+00, 3.754408661907416e+00
68 };
69 const double p_low = 0.02425;
70 const double p_high = 1.0 - p_low;
71 double q, r;
72 if (p < p_low) {
73 q = std::sqrt(-2.0 * std::log(p));
74 return (((((c[0]*q+c[1])*q+c[2])*q+c[3])*q+c[4])*q+c[5]) /
75 ((((d[0]*q+d[1])*q+d[2])*q+d[3])*q+1.0);
76 } else if (p <= p_high) {
77 q = p - 0.5; r = q * q;
78 return (((((a[0]*r+a[1])*r+a[2])*r+a[3])*r+a[4])*r+a[5])*q /
79 (((((b[0]*r+b[1])*r+b[2])*r+b[3])*r+b[4])*r+1.0);
80 } else {
81 q = std::sqrt(-2.0 * std::log(1.0 - p));
82 return -(((((c[0]*q+c[1])*q+c[2])*q+c[3])*q+c[4])*q+c[5]) /
83 ((((d[0]*q+d[1])*q+d[2])*q+d[3])*q+1.0);
84 }
85}
86
87// ---------------------------------------------------------------------------
88// Internal helpers: regularized incomplete beta + t-distribution quantile
89// ---------------------------------------------------------------------------
90//
91// These live in qe::detail so they don't pollute the public qe namespace.
92// They are used by mean_ci() and are not part of the public API.
93
94namespace detail {
95
96// Lentz continued-fraction evaluation for the regularized incomplete beta.
97// Ported from Numerical Recipes in C, §6.4.
98inline double betacf(double a, double b, double x) {
99 const int MAXIT = 200;
100 const double EPS = std::numeric_limits<double>::epsilon();
101 const double FPMIN = std::numeric_limits<double>::min() / EPS;
102 double qab = a + b, qap = a + 1.0, qam = a - 1.0;
103 double c = 1.0;
104 double d = 1.0 - qab * x / qap;
105 if (std::abs(d) < FPMIN) d = FPMIN;
106 d = 1.0 / d;
107 double h = d;
108 for (int m = 1; m <= MAXIT; ++m) {
109 const int m2 = 2 * m;
110 // even step
111 double aa = static_cast<double>(m) * (b - static_cast<double>(m)) * x
112 / ((qam + m2) * (a + m2));
113 d = 1.0 + aa * d; if (std::abs(d) < FPMIN) d = FPMIN;
114 c = 1.0 + aa / c; if (std::abs(c) < FPMIN) c = FPMIN;
115 d = 1.0 / d; h *= d * c;
116 // odd step
117 aa = -(a + static_cast<double>(m)) * (qab + static_cast<double>(m)) * x
118 / ((a + m2) * (qap + m2));
119 d = 1.0 + aa * d; if (std::abs(d) < FPMIN) d = FPMIN;
120 c = 1.0 + aa / c; if (std::abs(c) < FPMIN) c = FPMIN;
121 d = 1.0 / d;
122 const double del = d * c;
123 h *= del;
124 if (std::abs(del - 1.0) <= EPS) break;
125 }
126 return h;
127}
128
129// Regularized incomplete beta I_x(a, b).
130inline double betai(double a, double b, double x) {
131 if (x <= 0.0) return 0.0;
132 if (x >= 1.0) return 1.0;
133 const double lbab = std::lgamma(a + b) - std::lgamma(a) - std::lgamma(b);
134 const double bt = std::exp(lbab + a * std::log(x) + b * std::log(1.0 - x));
135 if (x < (a + 1.0) / (a + b + 2.0))
136 return bt * betacf(a, b, x) / a;
137 return 1.0 - bt * betacf(b, a, 1.0 - x) / b;
138}
139
140// Quantile function (inverse CDF) for the t-distribution with `df` degrees
141// of freedom. Uses the relation:
142//
143// P(T ≤ t | df) = 1 - I_x(df/2, 1/2) / 2, x = df / (df + t^2)
144//
145// Inverted via Newton–Raphson on I_x with bisection fallback; normal-quantile
146// plus one Cornish–Fisher correction term provides the starting guess.
147inline double t_quantile(double p, double df) {
148 const double INF = std::numeric_limits<double>::infinity();
149 if (p <= 0.0) return -INF;
150 if (p >= 1.0) return INF;
151 if (p == 0.5) return 0.0;
152 if (df <= 0.0) return INF; // df = 0 → t-distribution undefined → treat as ∞
153
154 // Work with pp > 0.5 for numerical stability; negate at the end if needed.
155 const bool flip = (p < 0.5);
156 const double pp = flip ? 1.0 - p : p;
157 const double a = 0.5 * df;
158 const double bv = 0.5;
159
160 // We need x in (0,1) such that I_x(a, bv) = 2*(1-pp).
161 const double target = 2.0 * (1.0 - pp);
162
163 // Initial guess via normal quantile + single Cornish–Fisher correction.
164 const double z = normal_quantile(pp);
165 const double t0 = z + (z * z * z + z) / (4.0 * df);
166 double x = df / (df + t0 * t0);
167 x = std::max(1e-12, std::min(1.0 - 1e-12, x));
168
169 // Newton–Raphson with a bisection bracket.
170 // f(x) = I_x(a,bv) - target; f'(x) = x^(a-1)*(1-x)^(bv-1) / B(a,bv)
171 const double lbab = std::lgamma(a + bv) - std::lgamma(a) - std::lgamma(bv);
172 double xlo = 0.0, xhi = 1.0;
173 for (int iter = 0; iter < 100; ++iter) {
174 const double fx = betai(a, bv, x) - target;
175 // betai is increasing in x, so fx < 0 → x too small → raise lower bound
176 if (fx < 0.0) xlo = x; else xhi = x;
177
178 // Derivative: may underflow near boundaries — fall back to bisection.
179 const double log_fpx = lbab + (a - 1.0) * std::log(x)
180 + (bv - 1.0) * std::log(1.0 - x);
181 const double fpx = (log_fpx > -700.0) ? std::exp(log_fpx) : 0.0;
182
183 double x_new;
184 if (fpx > 0.0) {
185 x_new = x - fx / fpx;
186 if (x_new <= xlo || x_new >= xhi)
187 x_new = 0.5 * (xlo + xhi);
188 } else {
189 x_new = 0.5 * (xlo + xhi);
190 }
191
192 if (std::abs(x_new - x) < 1e-13 * x) break;
193 x = x_new;
194 }
195
196 const double t_val = std::sqrt(df * (1.0 - x) / x);
197 return flip ? -t_val : t_val;
198}
199
200// ---------------------------------------------------------------------------
201// IQR helper — matches R's quantile(type = 7) (Hyndman–Fan #7), which is
202// identical to numpy's np.percentile(method="linear").
203//
204// For a sorted n-element vector and probability p:
205// h = (n - 1) * p
206// lo = floor(h), frac = h - lo
207// Q(p) = sorted[lo] * (1 - frac) + sorted[lo+1] * frac
208// ---------------------------------------------------------------------------
209
210inline double quantile_type7(const arma::vec& sorted, double p) {
211 const int n = static_cast<int>(sorted.n_elem);
212 if (n == 0) return std::numeric_limits<double>::quiet_NaN();
213 if (n == 1) return sorted[0];
214 const double h = (n - 1) * p;
215 const int lo = static_cast<int>(std::floor(h));
216 const double frac = h - lo;
217 if (lo + 1 >= n) return sorted[n - 1]; // guard: p == 1.0
218 return sorted[lo] * (1.0 - frac) + sorted[lo + 1] * frac;
219}
220
221// Interquartile range for a column vector — uses the same type-7 quantile as R.
222inline double iqr(const arma::vec& col) {
223 const arma::vec s = arma::sort(col);
224 return quantile_type7(s, 0.75) - quantile_type7(s, 0.25);
225}
226
227} // namespace detail
228
230
231// ---------------------------------------------------------------------------
234// ---------------------------------------------------------------------------
235
251inline arma::mat mean_ci(const arma::mat& points, double conf_level = 0.95) {
252 const int n = static_cast<int>(points.n_rows);
253 const int n_dims = static_cast<int>(points.n_cols);
254
255 arma::mat out(n_dims, 3);
256 out.fill(std::numeric_limits<double>::quiet_NaN());
257
258 if (n == 0) return out;
259
260 const double df = static_cast<double>(n - 1);
261 const double t_crit = detail::t_quantile(1.0 - (1.0 - conf_level) / 2.0, df);
262 const double INF = std::numeric_limits<double>::infinity();
263
264 for (int d = 0; d < n_dims; ++d) {
265 const arma::vec col = points.col(d);
266 const double mu = arma::mean(col);
267 out(d, 0) = mu;
268 if (n == 1) {
269 // t_crit = Inf and se = 0 would give NaN; explicitly set ±Inf
270 out(d, 1) = -INF;
271 out(d, 2) = INF;
272 } else {
273 const double se = arma::stddev(col) / std::sqrt(static_cast<double>(n));
274 out(d, 1) = mu - t_crit * se;
275 out(d, 2) = mu + t_crit * se;
276 }
277 }
278 return out;
279}
280
305inline arma::mat outlier_ci(const arma::mat& points, double iqr_factor = 1.5) {
306 const int n_dims = static_cast<int>(points.n_cols);
307 arma::mat out(n_dims, 2, arma::fill::zeros);
308
309 if (points.n_rows == 0) {
310 out.fill(std::numeric_limits<double>::quiet_NaN());
311 return out;
312 }
313
314 for (int d = 0; d < n_dims; ++d) {
315 const double half_width = iqr_factor * detail::iqr(points.col(d));
316 out(d, 0) = -half_width;
317 out(d, 1) = half_width;
318 }
319 return out;
320}
321
323
324// ---------------------------------------------------------------------------
327// ---------------------------------------------------------------------------
328
347 int n1;
348 int n2;
349
350 // Parametric
351 arma::vec t;
352 arma::vec df;
353 arma::vec pvalue_t;
354 arma::vec cohens_d;
355 arma::mat means;
356 arma::mat sds;
357
358 // Non-parametric
359 arma::vec U;
360 arma::vec pvalue_u;
361 arma::vec effect_r;
362 arma::mat medians;
363};
364
366namespace detail {
367
368// Two-tailed p-value for a Welch t-statistic.
369// Uses the relation P(T≤t|df) = 1 − I_x(df/2, 1/2)/2, x = df/(df+t²).
370inline double t_test_pvalue(double t_stat, double df) {
371 if (!std::isfinite(t_stat) || df <= 0.0)
372 return std::numeric_limits<double>::quiet_NaN();
373 const double x = df / (df + t_stat * t_stat);
374 return betai(df / 2.0, 0.5, x); // == 2 * P(T_df > |t_stat|)
375}
376
377// Wilcoxon rank-sum U (= R's W for group 1) and two-tailed p-value.
378// Normal approximation with tie correction and continuity correction,
379// matching R's wilcox.test(..., exact=FALSE, correct=TRUE).
380struct WilcoxResult { double U; double p; };
381
382inline WilcoxResult wilcox_ranksum(const arma::vec& g1, const arma::vec& g2) {
383 const int n1 = static_cast<int>(g1.n_elem);
384 const int n2 = static_cast<int>(g2.n_elem);
385 const int n = n1 + n2;
386 const double NaN = std::numeric_limits<double>::quiet_NaN();
387
388 if (n1 == 0 || n2 == 0) return {NaN, NaN};
389
390 // Merge both groups into a single array, tagging each element's origin.
391 arma::vec vals(n);
392 std::vector<int> grp(n);
393 for (int i = 0; i < n1; ++i) { vals[i] = g1[i]; grp[i] = 0; }
394 for (int i = 0; i < n2; ++i) { vals[n1 + i] = g2[i]; grp[n1 + i] = 1; }
395
396 arma::uvec ord = arma::sort_index(vals);
397
398 // Assign average ranks for tied values; accumulate tie correction T = Σ(t³−t).
399 arma::vec rnk(n);
400 double T_ties = 0.0;
401 arma::uword i = 0;
402 while (i < static_cast<arma::uword>(n)) {
403 arma::uword j = i;
404 while (j + 1 < static_cast<arma::uword>(n) &&
405 vals[ord[j + 1]] == vals[ord[j]])
406 ++j;
407 const double avg = 0.5 * (static_cast<double>(i) + static_cast<double>(j)) + 1.0;
408 for (arma::uword k = i; k <= j; ++k) rnk[ord[k]] = avg;
409 const double t = static_cast<double>(j - i + 1);
410 T_ties += t * (t * t - 1.0); // t³ − t
411 i = j + 1;
412 }
413
414 // W = rank-sum for group 1; U = W − n1*(n1+1)/2 (R's wilcox.test statistic).
415 double W = 0.0;
416 for (int k = 0; k < n; ++k)
417 if (grp[k] == 0) W += rnk[k];
418 const double U = W - static_cast<double>(n1) * (n1 + 1) / 2.0;
419
420 // Normal approximation: Var[U] = n1·n2/12 · ((n+1) − T_ties/(n·(n−1)))
421 const double mu_U = static_cast<double>(n1) * n2 / 2.0;
422 const double tie_adj = (n > 1) ? T_ties / (static_cast<double>(n) * (n - 1)) : 0.0;
423 double var_U = static_cast<double>(n1) * n2 / 12.0
424 * (static_cast<double>(n + 1) - tie_adj);
425 if (var_U < 0.0) var_U = 0.0;
426
427 double p;
428 if (var_U == 0.0) {
429 p = (U == mu_U) ? 1.0 : 0.0;
430 } else {
431 // Continuity correction: |U − mu| − 0.5
432 double z = (std::abs(U - mu_U) - 0.5) / std::sqrt(var_U);
433 if (z < 0.0) z = 0.0;
434 p = std::erfc(z / std::sqrt(2.0)); // = 2*(1−Φ(z))
435 p = std::min(p, 1.0);
436 }
437
438 return {U, p};
439}
440
441} // namespace detail (group stats helpers)
443
476inline GroupStats group_stats(const arma::mat& g1, const arma::mat& g2) {
477 const int n1 = static_cast<int>(g1.n_rows);
478 const int n2 = static_cast<int>(g2.n_rows);
479 const int n_dims = static_cast<int>(g1.n_cols);
480 const double NaN = std::numeric_limits<double>::quiet_NaN();
481
482 GroupStats out;
483 out.n1 = n1;
484 out.n2 = n2;
485
486 out.t = arma::vec(n_dims); out.t.fill(NaN);
487 out.df = arma::vec(n_dims); out.df.fill(NaN);
488 out.pvalue_t = arma::vec(n_dims); out.pvalue_t.fill(NaN);
489 out.cohens_d = arma::vec(n_dims); out.cohens_d.fill(NaN);
490 out.means = arma::mat(2, n_dims); out.means.fill(NaN);
491 out.sds = arma::mat(2, n_dims); out.sds.fill(NaN);
492 out.U = arma::vec(n_dims); out.U.fill(NaN);
493 out.pvalue_u = arma::vec(n_dims); out.pvalue_u.fill(NaN);
494 out.effect_r = arma::vec(n_dims); out.effect_r.fill(NaN);
495 out.medians = arma::mat(2, n_dims); out.medians.fill(NaN);
496
497 if (n1 == 0 || n2 == 0) return out;
498
499 for (int d = 0; d < n_dims; ++d) {
500 const arma::vec c1 = g1.col(d);
501 const arma::vec c2 = g2.col(d);
502
503 // ── Means and medians ───────────────────────────────────────────────
504 const double m1 = arma::mean(c1);
505 const double m2 = arma::mean(c2);
506 out.means(0, d) = m1;
507 out.means(1, d) = m2;
508 out.medians(0, d) = arma::median(c1);
509 out.medians(1, d) = arma::median(c2);
510
511 // ── Standard deviations (ddof = 1, matching R's sd()) ───────────────
512 const double s1 = (n1 > 1) ? arma::stddev(c1) : NaN;
513 const double s2 = (n2 > 1) ? arma::stddev(c2) : NaN;
514 out.sds(0, d) = s1;
515 out.sds(1, d) = s2;
516
517 // ── Welch two-sample t-test ──────────────────────────────────────────
518 if (n1 > 1 && n2 > 1 && std::isfinite(s1) && std::isfinite(s2)) {
519 const double v1n = s1 * s1 / n1;
520 const double v2n = s2 * s2 / n2;
521 const double se = std::sqrt(v1n + v2n);
522 if (se > 0.0) {
523 const double t_stat = (m1 - m2) / se;
524 const double df_val = (v1n + v2n) * (v1n + v2n)
525 / (v1n * v1n / (n1 - 1) + v2n * v2n / (n2 - 1));
526 out.t(d) = t_stat;
527 out.df(d) = df_val;
528 out.pvalue_t(d) = detail::t_test_pvalue(t_stat, df_val);
529 }
530 }
531
532 // ── Cohen's d (pooled SD) ────────────────────────────────────────────
533 if (n1 + n2 > 2 && std::isfinite(s1) && std::isfinite(s2)) {
534 const double pooled_var = ((n1 - 1) * s1 * s1 + (n2 - 1) * s2 * s2)
535 / (n1 + n2 - 2);
536 const double pooled_sd = std::sqrt(pooled_var);
537 out.cohens_d(d) = (pooled_sd > 0.0) ? (m1 - m2) / pooled_sd : 0.0;
538 }
539
540 // ── Wilcoxon rank-sum ────────────────────────────────────────────────
541 const detail::WilcoxResult wr = detail::wilcox_ranksum(c1, c2);
542 out.U(d) = wr.U;
543 out.pvalue_u(d) = wr.p;
544 if (std::isfinite(wr.U))
545 out.effect_r(d) = 1.0 - 2.0 * wr.U / (static_cast<double>(n1) * n2);
546 }
547
548 return out;
549}
550
552
553} // namespace qe
554
555#endif // LIBQE_STATS_HPP
Definition adjacency.hpp:16
GroupStats group_stats(const arma::mat &g1, const arma::mat &g2)
Compute per-dimension two-group comparison statistics.
Definition stats.hpp:476
arma::mat mean_ci(const arma::mat &points, double conf_level=0.95)
Student-t confidence interval for the mean of a group of ENA unit points.
Definition stats.hpp:251
arma::mat center_points(arma::mat values)
Subtract column means so that every dimension is centred at the origin.
Definition stats.hpp:35
arma::mat outlier_ci(const arma::mat &points, double iqr_factor=1.5)
Tukey-fence outlier interval for a group of ENA unit points.
Definition stats.hpp:305
Per-dimension statistics from a two-group comparison.
Definition stats.hpp:346
arma::mat medians
2 × n_dims: medians; row 0 = group1, row 1 = group2.
Definition stats.hpp:362
int n2
Sample size of group 2.
Definition stats.hpp:348
int n1
Sample size of group 1.
Definition stats.hpp:347
arma::vec pvalue_u
Two-tailed p-values (normal approx, tie + continuity correction).
Definition stats.hpp:360
arma::vec U
Wilcoxon rank-sum U for group 1 (= R's W statistic).
Definition stats.hpp:359
arma::vec t
Welch two-sample t-statistics.
Definition stats.hpp:351
arma::vec cohens_d
Cohen's d (pooled-SD formula, group1 − group2).
Definition stats.hpp:354
arma::vec pvalue_t
Two-tailed p-values from the Welch t-test.
Definition stats.hpp:353
arma::vec df
Welch–Satterthwaite degrees of freedom.
Definition stats.hpp:352
arma::mat means
2 × n_dims: means; row 0 = group1, row 1 = group2.
Definition stats.hpp:355
arma::mat sds
2 × n_dims: sample standard deviations.
Definition stats.hpp:356
arma::vec effect_r
Rank-biserial effect: 1 − 2·U / (n1·n2).
Definition stats.hpp:361