libqe-stats 0.1.3-dev.9005
QE C++ library
Loading...
Searching...
No Matches
comparison.hpp
Go to the documentation of this file.
1#pragma once
2#include "metrics.hpp"
3#include "inference.hpp"
4#include "derivation.hpp"
5#include <algorithm>
6#include <cmath>
7#include <random>
8#include <stdexcept>
9#include <string>
10#include <vector>
11
12namespace qestats {
13
14// ── Bootstrap result ──────────────────────────────────────────────────────────
15
18 // Per-metric standard errors and CI (parallel to METRIC_NAMES order)
19 struct MetricStat {
20 std::string name;
21 double se = 0;
22 double ci_lo = 0;
23 double ci_hi = 0;
24 };
25 std::vector<MetricStat> stats;
26};
27
28// Metric names in canonical order matching qestats R output.
29inline const std::vector<std::string>& metric_names() {
30 static const std::vector<std::string> v = {
31 "b1","b2","precision","recall","accuracy","FDR","FOR","kappa"
32 };
33 return v;
34}
35
36// ── bootstrap_metrics ─────────────────────────────────────────────────────────
37// cm: raw confusion matrix (TP, FP, FN, TN counts — not proportions)
38// n_sample: resample size
39// n_set: population size (0 = infinite)
40// n_bootstrap: number of bootstrap replicates
41// conf_level: confidence level (e.g. 0.95)
42
43inline BootstrapResult
44bootstrap_metrics(const ConfusionMatrix& cm, int n_sample,
45 const std::vector<std::string>& metrics = {},
46 int n_set = 0, int n_bootstrap = 1000,
47 double conf_level = 0.95) {
48 const auto& all = metric_names();
49 const auto& chosen = metrics.empty() ? all : metrics;
50
51 double n1 = cm.tp, n2 = cm.fp, n3 = cm.fn, n4 = cm.tn;
52 double n0 = n1 + n2 + n3 + n4;
53 if (n0 <= 0 || n1 < 0 || n2 < 0 || n3 < 0 || n4 < 0)
54 throw std::domain_error("bootstrap_metrics: invalid confusion matrix");
55
56 BootstrapResult result;
57 result.original = calculate_metrics(n1, n2, n3, n4);
58
59 // Scale to population if requested
60 if (n_set > 0) {
61 double r = static_cast<double>(n_set) / n0;
62 if (r > 1) {
63 n1 = std::ceil(n1 * r); n2 = std::ceil(n2 * r);
64 n3 = std::ceil(n3 * r); n4 = std::ceil(n4 * r);
65 } else {
66 n1 = std::floor(n1 * r); n2 = std::floor(n2 * r);
67 n3 = std::floor(n3 * r); n4 = std::floor(n4 * r);
68 }
69 double tot = n1 + n2 + n3 + n4;
70 if (n_sample > tot) n_sample = static_cast<int>(tot);
71 }
72 const double n_total = n1 + n2 + n3 + n4;
73 const bool with_replacement = (n_set == 0);
74
75 // Build population index vector [0..n_total)
76 const int N = static_cast<int>(n_total);
77 const int c1 = static_cast<int>(n1);
78 const int c2 = static_cast<int>(n2);
79 const int c3 = static_cast<int>(n3);
80
81 std::mt19937 rng(42); // fixed seed for reproducibility
82
83 // Collect bootstrap replicates
84 std::vector<std::vector<double>> samples(chosen.size());
85
86 for (int b = 0; b < n_bootstrap; ++b) {
87 std::vector<int> idx(n_sample);
88 if (with_replacement) {
89 std::uniform_int_distribution<int> dist(0, N - 1);
90 for (int& x : idx) x = dist(rng);
91 } else {
92 // sample without replacement
93 std::vector<int> pool(N);
94 std::iota(pool.begin(), pool.end(), 0);
95 std::shuffle(pool.begin(), pool.end(), rng);
96 for (int i = 0; i < n_sample; ++i) idx[i] = pool[i];
97 }
98 int b1_ = 0, b2_ = 0, b3_ = 0, b4_ = 0;
99 for (int x : idx) {
100 if (x < c1) ++b1_;
101 else if (x < c1+c2) ++b2_;
102 else if (x < c1+c2+c3) ++b3_;
103 else ++b4_;
104 }
105 Metrics bm = calculate_metrics(b1_, b2_, b3_, b4_);
106 for (std::size_t i = 0; i < chosen.size(); ++i)
107 samples[i].push_back(get_metric(bm, chosen[i]));
108 }
109
110 const double alpha = 1.0 - conf_level;
111 for (std::size_t i = 0; i < chosen.size(); ++i) {
112 auto& s = samples[i];
113 double mean = 0; for (double x : s) mean += x; mean /= s.size();
114 double var = 0; for (double x : s) var += (x-mean)*(x-mean);
115 double se = std::sqrt(var / (s.size() - 1));
116
117 std::sort(s.begin(), s.end());
118 int lo_idx = std::max(0, static_cast<int>(std::floor(alpha/2 * s.size())));
119 int hi_idx = std::min(static_cast<int>(s.size())-1,
120 static_cast<int>(std::ceil((1.0-alpha/2) * s.size())));
121 result.stats.push_back({chosen[i], se, s[lo_idx], s[hi_idx]});
122 }
123 return result;
124}
125
126// ── Welch t-test helper ───────────────────────────────────────────────────────
127
129 double t_stat = 0;
130 double df = 0;
131 double p_value = 1;
132};
133
134inline TTestResult welch_t(double m1, double m2,
135 double s1, double s2,
136 int n1, int n2,
137 double tol = 1e-9) {
138 if (std::abs(m1 - m2) < tol) return {0, 1, 1.0};
139 if (std::abs(s1) < tol && std::abs(s2) < tol)
140 return {0, 1, (std::abs(m1-m2) < tol) ? 1.0 : 0.0};
141
142 const double t = (m1 - m2) / std::sqrt(s1*s1 + s2*s2);
143 const double num = (s1*s1 + s2*s2) * (s1*s1 + s2*s2);
144 const double den = s1*s1*s1*s1/(n1-1) + s2*s2*s2*s2/(n2-1);
145 const double df = (den > 0) ? num/den : 1.0;
146
147 // Two-sided p-value via regularised incomplete beta (approx via normal for large df)
148 // For production accuracy use a proper t-distribution CDF; for now use
149 // normal approximation which is good for df > 30.
150 double p;
151 if (df > 30) {
152 // Standard normal approximation
153 double z = std::abs(t);
154 p = 2.0 * (0.5 * std::erfc(z / std::sqrt(2.0)));
155 } else {
156 // Abramowitz & Stegun approximation to t CDF
157 double x = df / (df + t*t);
158 // regularized incomplete beta I_x(df/2, 1/2) via continued fraction (simple approximation)
159 // Good enough for n_bootstrap >= 30; exact implementation would need boost or a special function
160 double z = std::abs(t);
161 double a_s = df / 2.0, b_s = 0.5;
162 // Use the normal approximation as a safe fallback
163 p = 2.0 * (0.5 * std::erfc(z / std::sqrt(2.0)));
164 }
165 return {t, df, p};
166}
167
168// ── p_diff ────────────────────────────────────────────────────────────────────
169// p-value for a metric difference between two groups using bootstrap Welch t.
170
171inline double p_diff(const ConfusionMatrix& cm1, const ConfusionMatrix& cm2,
172 int n_sample, const std::string& metric,
173 int n_set = 0, int n_bootstrap = 1000, double alpha = 0.05) {
174 const double n1 = cm1.tp + cm1.fp + cm1.fn + cm1.tn;
175 const double n2 = cm2.tp + cm2.fp + cm2.fn + cm2.tn;
176 const double n0 = n1 + n2;
177 if (n_sample <= 0) n_sample = static_cast<int>(n0);
178 const double r = static_cast<double>(n_sample) / n0;
179 const int ns1 = std::max(1, static_cast<int>(std::floor(n1 * (r < 1 ? 1 : r))));
180 const int ns2 = std::max(1, static_cast<int>(std::floor(n2 * (r < 1 ? 1 : r))));
181 const int nset1 = (n_set > 0) ? static_cast<int>(std::floor(n_set * n1 / n0)) : 0;
182 const int nset2 = (n_set > 0) ? static_cast<int>(std::floor(n_set * n2 / n0)) : 0;
183
184 auto r1 = bootstrap_metrics(cm1, ns1, {metric}, nset1, n_bootstrap, 1.0-alpha);
185 auto r2 = bootstrap_metrics(cm2, ns2, {metric}, nset2, n_bootstrap, 1.0-alpha);
186
187 const double m1v = get_metric(r1.original, metric);
188 const double m2v = get_metric(r2.original, metric);
189 const double se1 = r1.stats.empty() ? 0 : r1.stats[0].se;
190 const double se2 = r2.stats.empty() ? 0 : r2.stats[0].se;
191
192 return welch_t(m1v, m2v, se1, se2, n_bootstrap, n_bootstrap).p_value;
193}
194
195// ── n_diff ────────────────────────────────────────────────────────────────────
196// Minimum n at which two groups show a significant metric difference.
197
198inline int n_diff(const ConfusionMatrix& cm1, const ConfusionMatrix& cm2,
199 const std::string& metric, int n_set = 0,
200 int n_bootstrap = 1000, double alpha = 0.05) {
201 const int n1 = static_cast<int>(cm1.tp+cm1.fp+cm1.fn+cm1.tn);
202 const int n2 = static_cast<int>(cm2.tp+cm2.fp+cm2.fn+cm2.tn);
203 int n = n1 + n2;
204
205 double p0 = p_diff(cm1, cm2, n, metric, n_set, n_bootstrap, alpha);
206 if (p0 < alpha) return n;
207
208 int left = n, right = n_set > 0 ? n_set : n;
209 if (n_set <= 0) {
210 while (p0 >= alpha) {
211 left = right;
212 right *= 2;
213 p0 = p_diff(cm1, cm2, right, metric, n_set, n_bootstrap, alpha);
214 }
215 } else {
216 double p1 = p_diff(cm1, cm2, n_set, metric, n_set, n_bootstrap, alpha);
217 if (p1 >= alpha) return n_set;
218 }
219
220 while (right - left > 1) {
221 int mid = (left + right + 1) / 2;
222 p0 = p_diff(cm1, cm2, mid, metric, n_set, n_bootstrap, alpha);
223 if (p0 >= alpha) left = mid;
224 else right = mid;
225 }
226 return (left + right + 1) / 2;
227}
228
229// ── N_Diff2 ───────────────────────────────────────────────────────────────────
230// Minimum n at which CI intervals for two groups no longer overlap by > d.
231
232inline double interval_overlap(const MetricRange& r1, const MetricRange& r2) {
233 double span = std::min(r1.max - r1.min, r2.max - r2.min);
234 if (span <= 0) return 0.0;
235 double overlap = std::min(r1.max, r2.max) - std::max(r1.min, r2.min);
236 return (overlap <= 0) ? 0.0 : overlap / span;
237}
238
239// range_est: hyper-based CI for a metric given raw counts + population N
241 const std::string& metric, int N, double alpha = 0.05) {
242 const int tp = static_cast<int>(cm.tp), fp = static_cast<int>(cm.fp);
243 const int fn = static_cast<int>(cm.fn), tn = static_cast<int>(cm.tn);
244 auto prec_ci = hyper_range(tp, tp+fp, N, alpha);
245 auto for_ci = hyper_range(fn, fn+tn, N, alpha); // FOR = fn/(fn+tn)
246 double b1 = static_cast<double>(tp+fp) / (tp+fp+fn+tn);
247
248 auto eval_m = [&](double fdr, double for_v) -> double {
249 Metrics m = derive_from_rates(b1, fdr, for_v);
250 return get_metric(m, metric);
251 };
252
253 // Precision = 1 - FDR; CI is [lo, hi] for precision → FDR is [1-hi, 1-lo]
254 double fdr_lo = 1.0 - prec_ci.upper, fdr_hi = 1.0 - prec_ci.lower;
255 double for_lo = for_ci.lower, for_hi = for_ci.upper;
256
257 double v_lo = eval_m(fdr_hi, for_hi); // worst case
258 double v_hi = eval_m(fdr_lo, for_lo); // best case
259 if (v_lo > v_hi) std::swap(v_lo, v_hi);
260 return {v_lo, v_hi};
261}
262
263inline int N_Diff2(const ConfusionMatrix& cm1, const ConfusionMatrix& cm2,
264 const std::string& metric, int N, double d = 0.1,
265 double alpha = 0.05) {
266 const double n1 = cm1.tp+cm1.fp+cm1.fn+cm1.tn;
267 const double n2 = cm2.tp+cm2.fp+cm2.fn+cm2.tn;
268 const int n = static_cast<int>(n1 + n2);
269
270 auto scale = [](const ConfusionMatrix& cm, double r) -> ConfusionMatrix {
271 return {std::floor(cm.tp*r), std::floor(cm.fp*r),
272 std::floor(cm.fn*r), std::floor(cm.tn*r)};
273 };
274
275 auto check_overlap = [&](double x) -> bool {
276 auto s1 = scale(cm1, x); auto s2 = scale(cm2, x);
277 auto r1 = range_est(s1, metric, N, alpha);
278 auto r2 = range_est(s2, metric, N, alpha);
279 return interval_overlap(r1, r2) >= d;
280 };
281
282 if (!check_overlap(1.0)) return n; // already separable
283
284 const double x_max = static_cast<double>(N) / n;
285 if (check_overlap(x_max)) return N; // never separable at population size
286
287 double left = 1.0, right = x_max;
288 while (right - left > 1.0 / n) {
289 double mid = (left + right) / 2.0;
290 if (check_overlap(mid)) left = mid;
291 else right = mid;
292 }
293 return static_cast<int>(std::ceil(n * (left + right) / 2.0));
294}
295
296// ── ps_est_kappa ──────────────────────────────────────────────────────────────
297// Given a perfect sample of size n and a baserate, estimate the minimum kappa.
298
299inline double ps_est_kappa(int n, double baserate, int N = 0,
300 int allowed_errors = 0, double alpha = 0.05) {
301 double accuracy = ps_est_proportion(n, N, allowed_errors, alpha);
302 if (accuracy < 0) return -1;
303 MetricRange kappa_range = range("baserate", baserate, "accuracy", accuracy, "kappa");
304 return kappa_range.min;
305}
306
307// ── ps_kappa ─────────────────────────────────────────────────────────────────
308// Perfect sample size for kappa test — delegates to ps_proportion via
309// max accuracy from range(baserate, kappa).
310
311inline PsResult ps_kappa(double kappa0, double baserate,
312 double kappa1 = 0, int N = 0,
313 int allowed_errors = 0, double alpha = 0.05) {
314 if (alpha < 0.001 || alpha > 0.1) return {};
315 if (kappa0 <= 0 || kappa0 >= 1) return {};
316
317 MetricRange acc_range = range("baserate", baserate, "kappa", kappa0, "accuracy");
318 return ps_proportion(acc_range.max, kappa1, N, allowed_errors, alpha);
319}
320
321} // namespace qestats
Definition comparison.hpp:12
int n_diff(const ConfusionMatrix &cm1, const ConfusionMatrix &cm2, const std::string &metric, int n_set=0, int n_bootstrap=1000, double alpha=0.05)
Definition comparison.hpp:198
MetricRange range_est(const ConfusionMatrix &cm, const std::string &metric, int N, double alpha=0.05)
Definition comparison.hpp:240
MetricRange range(const std::string &name1, double val1, const std::string &name2, double val2, const std::string &target)
Definition derivation.hpp:442
PsResult ps_proportion(double x0, double x1=0, int N=0, int allowed_errors=0, double alpha=0.05)
Definition inference.hpp:103
int N_Diff2(const ConfusionMatrix &cm1, const ConfusionMatrix &cm2, const std::string &metric, int N, double d=0.1, double alpha=0.05)
Definition comparison.hpp:263
double interval_overlap(const MetricRange &r1, const MetricRange &r2)
Definition comparison.hpp:232
double ps_est_proportion(int n, int N=0, int allowed_errors=0, double alpha=0.05)
Definition inference.hpp:144
double p_diff(const ConfusionMatrix &cm1, const ConfusionMatrix &cm2, int n_sample, const std::string &metric, int n_set=0, int n_bootstrap=1000, double alpha=0.05)
Definition comparison.hpp:171
Metrics calculate_metrics(double tp, double fp, double fn, double tn)
Definition metrics.hpp:100
Interval hyper_range(int n_pos, int n, int N, double alpha=0.05)
Definition inference.hpp:47
TTestResult welch_t(double m1, double m2, double s1, double s2, int n1, int n2, double tol=1e-9)
Definition comparison.hpp:134
Metrics derive_from_rates(double b1, double fdr, double for_)
Definition derivation.hpp:603
PsResult ps_kappa(double kappa0, double baserate, double kappa1=0, int N=0, int allowed_errors=0, double alpha=0.05)
Definition comparison.hpp:311
BootstrapResult bootstrap_metrics(const ConfusionMatrix &cm, int n_sample, const std::vector< std::string > &metrics={}, int n_set=0, int n_bootstrap=1000, double conf_level=0.95)
Definition comparison.hpp:44
double get_metric(const Metrics &m, const std::string &name)
Definition metrics.hpp:107
const std::vector< std::string > & metric_names()
Definition comparison.hpp:29
double ps_est_kappa(int n, double baserate, int N=0, int allowed_errors=0, double alpha=0.05)
Definition comparison.hpp:299
Definition comparison.hpp:19
double se
Definition comparison.hpp:21
double ci_hi
Definition comparison.hpp:23
std::string name
Definition comparison.hpp:20
double ci_lo
Definition comparison.hpp:22
Definition comparison.hpp:16
std::vector< MetricStat > stats
Definition comparison.hpp:25
Metrics original
Definition comparison.hpp:17
Definition metrics.hpp:24
double fp
Definition metrics.hpp:25
double fn
Definition metrics.hpp:25
double tp
Definition metrics.hpp:25
double tn
Definition metrics.hpp:25
Definition metrics.hpp:44
double max
Definition metrics.hpp:46
double min
Definition metrics.hpp:45
Definition metrics.hpp:29
Definition inference.hpp:97
Definition comparison.hpp:128
double df
Definition comparison.hpp:130
double t_stat
Definition comparison.hpp:129
double p_value
Definition comparison.hpp:131