libqe-stats 0.1.2
QE C++ library
Loading...
Searching...
No Matches
inference.hpp
Go to the documentation of this file.
1#pragma once
2#include "metrics.hpp"
3#include <cmath>
4#include <stdexcept>
5#include <vector>
6
7namespace qestats {
8
9// ── Hypergeometric CDF ────────────────────────────────────────────────────────
10// P(X <= q) where X ~ Hypergeometric(N, K, n)
11// K = number of successes in population
12// N - K = failures in population
13// n = sample size
14//
15// Computed in log-space to avoid overflow. Equivalent to R's phyper(q,K,N-K,n).
16
17inline double phyper(int q, int K, int N_minus_K, int n) {
18 if (q < 0) return 0.0;
19 const int N = K + N_minus_K;
20 if (n > N || K < 0 || N_minus_K < 0) return 0.0;
21
22 // log of C(a, b)
23 auto lnchoose = [](int a, int b) -> double {
24 if (b < 0 || b > a) return -1e300;
25 if (b == 0 || b == a) return 0.0;
26 return std::lgamma(a + 1) - std::lgamma(b + 1) - std::lgamma(a - b + 1);
27 };
28
29 const double log_denom = lnchoose(N, n);
30 double sum = 0.0;
31 const int hi = std::min(q, std::min(K, n));
32 for (int k = std::max(0, n - N_minus_K); k <= hi; ++k) {
33 double log_num = lnchoose(K, k) + lnchoose(N_minus_K, n - k);
34 sum += std::exp(log_num - log_denom);
35 }
36 return std::min(sum, 1.0);
37}
38
39// ── Hypergeometric confidence interval for proportion ─────────────────────────
40// Estimates CI for the proportion of positives in a population.
41// R equivalent: hyper_range(n_pos, n, N, alpha)
42// n_pos = positives in sample
43// n = sample size
44// N = population size
45// alpha = significance level
46
47inline Interval hyper_range(int n_pos, int n, int N, double alpha = 0.05) {
48 if (n_pos < 0 || n_pos > n || n > N || alpha <= 0 || alpha >= 1)
49 throw std::domain_error("hyper_range: invalid input parameters");
50
51 const int n_neg = n - n_pos;
52 int M_lower = n_neg;
53 int M_upper = N - n_pos;
54
55 // Shrink M_lower upward until phyper tail >= alpha/2
56 {
57 double p_lower = phyper(n_pos, N - M_lower, M_lower, n);
58 if (p_lower < alpha / 2) {
59 int left = M_lower, right = M_upper;
60 while (right - left > 2) {
61 M_lower = (left + right + 1) / 2;
62 double p = phyper(n_pos - 1, N - M_lower, M_lower, n);
63 if (p < alpha / 2) left = M_lower;
64 else right = M_lower;
65 }
66 M_lower = left;
67 }
68 }
69
70 // Shrink M_upper downward until upper tail >= alpha/2
71 {
72 double p_upper = 1.0 - phyper(n_pos, N - M_upper, M_upper, n);
73 if (p_upper < alpha / 2) {
74 int left = M_lower, right = M_upper;
75 while (right - left > 2) {
76 M_upper = (left + right + 1) / 2;
77 double p = 1.0 - phyper(n_pos - 1, N - M_upper, M_upper, n);
78 if (p < alpha / 2) right = M_upper;
79 else left = M_upper;
80 }
81 M_upper = right;
82 }
83 }
84
85 return {
86 1.0 - static_cast<double>(M_upper) / N,
87 (n > 0) ? static_cast<double>(n_pos) / n : 0.0,
88 1.0 - static_cast<double>(M_lower) / N
89 };
90}
91
92// ── Perfect sampling: proportion ──────────────────────────────────────────────
93// Minimum sample size n such that if all items in the sample satisfy the
94// property, H0: x <= x0 is rejected at level alpha.
95// Returns {n, power, cost}; n = -1 on invalid input.
96
97struct PsResult {
98 int n = -1;
99 double power = 0;
100 double cost = 0;
101};
102
103inline PsResult ps_proportion(double x0, double x1 = 0,
104 int N = 0, int allowed_errors = 0,
105 double alpha = 0.05) {
106 if (alpha < 0.001 || alpha > 0.1) return {};
107 if (x0 < 0.5 || x0 >= 1.0) return {};
108
109 const int a = allowed_errors;
110 if (N <= 0) N = 1000000;
111 const int K = static_cast<int>(std::ceil(x0 * N));
112 if (K == N) return {N, 1.0, 1.0};
113 if (a >= static_cast<int>(K * (1.0 - x0))) return {};
114
115 // Binary search for min n: P(X >= n - a | K, N-K, n) <= alpha
116 // i.e. 1 - phyper(n-1-a, K, N-K, n) <= alpha
117 int left = a, right = K;
118 double p = 1.0;
119 while (left < right - 1) {
120 int n = (left + right + 1) / 2;
121 p = 1.0 - phyper(n - 1 - a, K, N - K, n);
122 if (p > alpha) left = n;
123 else right = n;
124 }
125 const int n_out = right;
126
127 if (x1 <= x0 || x1 >= 1.0) x1 = (x0 + 1.0) / 2.0;
128 const double K1 = x1 * N;
129 const int K1i = static_cast<int>(K1);
130 const double power = 1.0 - phyper(n_out - 1 - a, K1i, N - K1i, n_out);
131 return {n_out, power, static_cast<double>(n_out) / power};
132}
133
134// ── Perfect sampling: kappa ───────────────────────────────────────────────────
135// Derives the maximum achievable accuracy for (baserate, kappa) via range(),
136// then delegates to ps_proportion.
137// Declared here; implemented after derivation.hpp is included in qestats.hpp.
138// Forward declaration only — see qestats.hpp for the full definition.
139
140// ── ps_est_proportion ────────────────────────────────────────────────────────
141// Given a perfect sample of size n, estimate the minimum proportion of
142// positives in the population.
143
144inline double ps_est_proportion(int n, int N = 0, int allowed_errors = 0,
145 double alpha = 0.05) {
146 if (alpha < 0.001 || alpha > 0.1) return -1;
147 const int a = allowed_errors;
148 if (a >= n) return -1;
149 if (N <= 0) N = 1000000;
150 if (n < 1 || n >= N) return -1;
151
152 int left = 1, right = N;
153 double x = 0;
154 while (right - left > 1) {
155 int K = (left + right + 1) / 2;
156 double p = 1.0 - phyper(n - 1 - a, K, N - K, n);
157 x = static_cast<double>(K) / N;
158 if (p < alpha) left = K;
159 else right = K;
160 }
161 return x;
162}
163
164// ── ps_est_kappa ──────────────────────────────────────────────────────────────
165// Given a perfect sample of size n, estimate the minimum kappa achievable.
166// Declared here; depends on range() from derivation.hpp — implemented in
167// comparison.hpp after derivation.hpp is included.
168// Forward-declared below; full definition is in comparison.hpp.
169
170// ── metrics_range ─────────────────────────────────────────────────────────────
171// Estimates CI for precision, recall, accuracy, FDR, FOR, and kappa given a
172// sampled confusion matrix (raw counts) and population size N.
173// Returns a vector of MetricRangeRow in the same order as R's metrics_range().
174
175inline std::vector<MetricRangeRow>
176metrics_range(double tp, double fp, double fn, double tn,
177 int N, double baserate, double alpha = 0.05) {
178 // Helper: derive metrics from (baserate, FDR, FOR)
179 auto metrics_from_bFF = [](double b, double FDR, double FOR) -> Metrics {
180 const double fp_ = FDR * b;
181 const double tp_ = b - fp_;
182 const double fn_ = FOR * (1.0 - b);
183 const double tn_ = 1.0 - fp_ - tp_ - fn_;
184 return metrics_from_cm({tp_, fp_, fn_, tn_});
185 };
186
187 // Precision CI via hyper_range (full alpha)
188 Interval prec = hyper_range(static_cast<int>(tp),
189 static_cast<int>(tp + fp), N, alpha);
190 Interval FDR_ci = {1.0 - prec.upper, 1.0 - prec.mean, 1.0 - prec.lower};
191
192 // FOR CI: tn / (fn + tn) via hyper_range, then invert
193 Interval one_minus_FOR = hyper_range(static_cast<int>(tn),
194 static_cast<int>(fn + tn), N, alpha);
195 Interval FOR_ci = {1.0 - one_minus_FOR.upper,
196 1.0 - one_minus_FOR.mean,
197 1.0 - one_minus_FOR.lower};
198
199 // Derive recall, accuracy, kappa at lower/mean/upper FDR+FOR extremes
200 Metrics lower_m = metrics_from_bFF(baserate, FDR_ci.upper, FOR_ci.upper);
201 Metrics mean_m = metrics_from_bFF(baserate, FDR_ci.mean, FOR_ci.mean);
202 Metrics upper_m = metrics_from_bFF(baserate, FDR_ci.lower, FOR_ci.lower);
203
204 return {
205 {"precision", prec.lower, prec.mean, prec.upper},
206 {"recall", lower_m.recall, mean_m.recall, upper_m.recall},
207 {"accuracy", lower_m.accuracy, mean_m.accuracy, upper_m.accuracy},
208 {"FDR", FDR_ci.lower, FDR_ci.mean, FDR_ci.upper},
209 {"FOR", FOR_ci.lower, FOR_ci.mean, FOR_ci.upper},
210 {"kappa", lower_m.kappa, mean_m.kappa, upper_m.kappa},
211 };
212}
213
214} // namespace qestats
Definition comparison.hpp:12
std::vector< MetricRangeRow > metrics_range(double tp, double fp, double fn, double tn, int N, double baserate, double alpha=0.05)
Definition inference.hpp:176
PsResult ps_proportion(double x0, double x1=0, int N=0, int allowed_errors=0, double alpha=0.05)
Definition inference.hpp:103
double ps_est_proportion(int n, int N=0, int allowed_errors=0, double alpha=0.05)
Definition inference.hpp:144
Metrics metrics_from_cm(const ConfusionMatrix &cm)
Definition metrics.hpp:81
Interval hyper_range(int n_pos, int n, int N, double alpha=0.05)
Definition inference.hpp:47
double phyper(int q, int K, int N_minus_K, int n)
Definition inference.hpp:17
Definition metrics.hpp:50
double mean
Definition metrics.hpp:52
double upper
Definition metrics.hpp:53
double lower
Definition metrics.hpp:51
Definition metrics.hpp:29
double accuracy
Definition metrics.hpp:37
double kappa
Definition metrics.hpp:40
double recall
Definition metrics.hpp:36
Definition inference.hpp:97
double power
Definition inference.hpp:99
double cost
Definition inference.hpp:100
int n
Definition inference.hpp:98