Skip to main content

lib_jsl_statistics/
contingency.rs

1//! Effect sizes for contingency tables (SciPy's `odds_ratio`, `relative_risk` and
2//! `contingency.association`), with confidence intervals.
3//!
4//! See the book entry [Multivariate distributions and further tests](https://jwkunz.github.io/lib_jsl/book/statistics/multivariate-tests.html#effect-sizes-for-contingency-tables).
5
6use crate::hypothesis_tests::Alternative;
7use lib_jsl_core::ErrorsJSL;
8use lib_jsl_special_functions::gamma::ln_gamma;
9use lib_jsl_special_functions::normal_quantile as nq;
10
11/// The standard normal quantile.
12fn normal_quantile(p: f64) -> f64 {
13    nq(p, 0.0, 1.0)
14}
15
16fn ln_choose(n: f64, k: f64) -> f64 {
17    ln_gamma(n + 1.0) - ln_gamma(k + 1.0) - ln_gamma(n - k + 1.0)
18}
19
20/// Fisher's noncentral hypergeometric distribution of `x = table[0][0]` given the margins:
21/// `P(x) ∝ C(n, x) C(M − n, N − x) ωˣ` on `max(0, N − M + n) ≤ x ≤ min(n, N)`.
22struct FisherNcHypergeom {
23    lo: u64,
24    hi: u64,
25    log_base: Vec<f64>,
26}
27
28impl FisherNcHypergeom {
29    fn new(m: u64, n: u64, nn: u64) -> Self {
30        let lo = nn.saturating_sub(m - n);
31        let hi = n.min(nn);
32        let log_base = (lo..=hi).map(|x| ln_choose(n as f64, x as f64) + ln_choose((m - n) as f64, (nn - x) as f64)).collect();
33        FisherNcHypergeom { lo, hi, log_base }
34    }
35    /// The probabilities for odds ratio `ω`, normalised in logarithms.
36    fn probs(&self, omega: f64) -> Vec<f64> {
37        let lw = omega.ln();
38        let logs: Vec<f64> = self.log_base.iter().enumerate().map(|(i, b)| b + (self.lo + i as u64) as f64 * lw).collect();
39        let top = logs.iter().copied().fold(f64::NEG_INFINITY, f64::max);
40        let w: Vec<f64> = logs.iter().map(|l| (l - top).exp()).collect();
41        let s: f64 = w.iter().sum();
42        w.iter().map(|v| v / s).collect()
43    }
44    fn mean(&self, omega: f64) -> f64 {
45        self.probs(omega).iter().enumerate().map(|(i, p)| (self.lo + i as u64) as f64 * p).sum()
46    }
47    /// `P(X ≤ x)`.
48    fn cdf(&self, x: i64, omega: f64) -> f64 {
49        if x < self.lo as i64 {
50            return 0.0;
51        }
52        self.probs(omega).iter().take((x - self.lo as i64 + 1) as usize).sum::<f64>().min(1.0)
53    }
54    /// `P(X > x)`, summed directly.
55    fn sf(&self, x: i64, omega: f64) -> f64 {
56        let start = (x + 1 - self.lo as i64).max(0) as usize;
57        self.probs(omega).iter().skip(start).sum::<f64>().min(1.0)
58    }
59}
60
61/// Brent's root finder on a bracket (as SciPy's `brentq`, with absolute tolerance `xtol` and
62/// relative tolerance 4ε).
63fn brentq(f: impl Fn(f64) -> f64, mut a: f64, mut b: f64, xtol: f64) -> f64 {
64    let (mut fa, mut fb) = (f(a), f(b));
65    if fa == 0.0 {
66        return a;
67    }
68    if fb == 0.0 {
69        return b;
70    }
71    let (mut c, mut fc) = (a, fa);
72    let (mut d, mut e) = (b - a, b - a);
73    for _ in 0..200 {
74        if fb.signum() == fc.signum() {
75            c = a;
76            fc = fa;
77            d = b - a;
78            e = d;
79        }
80        if fc.abs() < fb.abs() {
81            a = b;
82            b = c;
83            c = a;
84            fa = fb;
85            fb = fc;
86            fc = fa;
87        }
88        let tol = 2.0 * 4.0 * f64::EPSILON * b.abs() + 0.5 * xtol;
89        let m = 0.5 * (c - b);
90        if m.abs() <= tol || fb == 0.0 {
91            return b;
92        }
93        if e.abs() >= tol && fa.abs() > fb.abs() {
94            let s = fb / fa;
95            let (p, q) = if a == c {
96                (2.0 * m * s, 1.0 - s)
97            } else {
98                let q0 = fa / fc;
99                let r = fb / fc;
100                (s * (2.0 * m * q0 * (q0 - r) - (b - a) * (r - 1.0)), (q0 - 1.0) * (r - 1.0) * (s - 1.0))
101            };
102            let (p, q) = if p > 0.0 { (p, -q) } else { (-p, q) };
103            if 2.0 * p < (3.0 * m * q - (tol * q).abs()).min((e * q).abs()) {
104                e = d;
105                d = p / q;
106            } else {
107                d = m;
108                e = m;
109            }
110        } else {
111            d = m;
112            e = m;
113        }
114        a = b;
115        fa = fb;
116        b += if d.abs() > tol { d } else { tol.copysign(m) };
117        fb = f(b);
118    }
119    b
120}
121
122/// SciPy's `_solve`: the root in `(0, ∞)` of an increasing or decreasing function, bracketed by
123/// halving or doubling from 1.
124fn solve_positive(f: impl Fn(f64) -> f64) -> f64 {
125    let v = f(1.0);
126    if v == 0.0 {
127        return 1.0;
128    }
129    let (lo, hi) = if v > 0.0 {
130        let mut nc = 0.5;
131        while f(nc) > 0.0 {
132            nc /= 2.0;
133        }
134        (nc, 2.0 * nc)
135    } else {
136        let mut nc = 2.0;
137        while f(nc) < 0.0 {
138            nc *= 2.0;
139        }
140        (nc / 2.0, nc)
141    };
142    brentq(f, lo, hi, 1e-13)
143}
144
145/// Which odds ratio [`odds_ratio`] estimates (SciPy's `kind`).
146#[derive(Clone, Copy, Debug, PartialEq, Eq)]
147#[non_exhaustive]
148pub enum OddsRatioKind {
149    /// The conditional maximum-likelihood estimate, given the margins (SciPy's default).
150    Conditional,
151    /// The sample odds ratio `ad/(bc)`.
152    Sample,
153}
154
155/// The result of [`odds_ratio`].
156#[derive(Clone, Copy, Debug)]
157#[non_exhaustive]
158pub struct OddsRatioResult {
159    pub statistic: f64,
160    pub kind: OddsRatioKind,
161    table: [[u64; 2]; 2],
162}
163
164// ANCHOR: odds_ratio
165/// The odds ratio of a 2 × 2 table `[[a, b], [c, d]]` (SciPy's `odds_ratio`). The conditional
166/// estimate solves `E_ω[X] = a` for the odds ratio `ω` of Fisher's noncentral hypergeometric
167/// distribution of `X = table[0][0]` given all margins; its confidence limits invert that
168/// distribution's tails (the exact interval that matches Fisher's exact test). The sample odds
169/// ratio is `ad/(bc)`, with Woolf's interval `exp(log OR ± z √(1/a + 1/b + 1/c + 1/d))`.
170pub fn odds_ratio(table: [[u64; 2]; 2], kind: OddsRatioKind) -> OddsRatioResult {
171    let [[a, b], [c, d]] = table;
172    let statistic = if a + b == 0 || c + d == 0 || a + c == 0 || b + d == 0 {
173        f64::NAN
174    } else {
175        match kind {
176            OddsRatioKind::Sample => sample_odds_ratio(&table),
177            OddsRatioKind::Conditional => {
178                let h = FisherNcHypergeom::new(a + b + c + d, a + b, a + c);
179                if a == h.lo {
180                    0.0
181                } else if a == h.hi {
182                    f64::INFINITY
183                } else {
184                    solve_positive(|nc| h.mean(nc) - a as f64)
185                }
186            }
187        }
188    };
189    OddsRatioResult { statistic, kind, table }
190}
191// ANCHOR_END: odds_ratio
192
193fn sample_odds_ratio(t: &[[u64; 2]; 2]) -> f64 {
194    let [[a, b], [c, d]] = *t;
195    if c > 0 && b > 0 {
196        (a * d) as f64 / (c * b) as f64
197    } else if a == 0 || d == 0 {
198        f64::NAN
199    } else {
200        f64::INFINITY
201    }
202}
203
204impl OddsRatioResult {
205    /// The confidence interval for the odds ratio (SciPy's `confidence_interval`).
206    pub fn confidence_interval(&self, confidence_level: f64, alternative: Alternative) -> Result<(f64, f64), ErrorsJSL> {
207        if !(0.0..=1.0).contains(&confidence_level) {
208            return Err(ErrorsJSL::InvalidInputRange("the confidence level must lie in [0, 1]"));
209        }
210        let [[a, b], [c, d]] = self.table;
211        if self.statistic.is_nan() && (a + b == 0 || c + d == 0 || a + c == 0 || b + d == 0) {
212            return Ok((f64::NAN, f64::NAN));
213        }
214        Ok(match self.kind {
215            OddsRatioKind::Sample => {
216                let or = sample_odds_ratio(&self.table);
217                let log_or = or.ln();
218                let se = (1.0 / a as f64 + 1.0 / b as f64 + 1.0 / c as f64 + 1.0 / d as f64).sqrt();
219                match alternative {
220                    Alternative::Less => (0.0, (log_or + normal_quantile(confidence_level) * se).exp()),
221                    Alternative::Greater => ((log_or - normal_quantile(confidence_level) * se).exp(), f64::INFINITY),
222                    Alternative::TwoSided => {
223                        let z = normal_quantile(0.5 * confidence_level + 0.5);
224                        ((log_or - z * se).exp(), (log_or + z * se).exp())
225                    }
226                }
227            }
228            OddsRatioKind::Conditional => {
229                let h = FisherNcHypergeom::new(a + b + c + d, a + b, a + c);
230                let or = sample_odds_ratio(&self.table);
231                let x = a as i64;
232                let upper = |alpha: f64| if or == f64::INFINITY { f64::INFINITY } else { solve_positive(|nc| alpha - h.cdf(x, nc)) };
233                let lower = |alpha: f64| if or == 0.0 { 0.0 } else { solve_positive(|nc| h.sf(x - 1, nc) - alpha) };
234                match alternative {
235                    Alternative::TwoSided => {
236                        let alpha = 0.5 * (1.0 - confidence_level);
237                        (lower(alpha), upper(alpha))
238                    }
239                    Alternative::Less => (0.0, upper(1.0 - confidence_level)),
240                    Alternative::Greater => (lower(1.0 - confidence_level), f64::INFINITY),
241                }
242            }
243        })
244    }
245}
246
247/// The result of [`relative_risk`].
248#[derive(Clone, Copy, Debug)]
249#[non_exhaustive]
250pub struct RelativeRiskResult {
251    pub relative_risk: f64,
252    counts: (u64, u64, u64, u64),
253}
254
255/// The relative risk `(a/n₁)/(c/n₂)` of `a` cases among `n₁` exposed and `c` among `n₂` controls
256/// (SciPy's `relative_risk`).
257pub fn relative_risk(exposed_cases: u64, exposed_total: u64, control_cases: u64, control_total: u64) -> Result<RelativeRiskResult, ErrorsJSL> {
258    if exposed_total == 0 || control_total == 0 || exposed_cases > exposed_total || control_cases > control_total {
259        return Err(ErrorsJSL::InvalidInputRange("relative_risk: need 0 ≤ cases ≤ total and totals ≥ 1"));
260    }
261    let rr = match (exposed_cases, control_cases) {
262        (0, 0) => f64::NAN,
263        (0, _) => 0.0,
264        (_, 0) => f64::INFINITY,
265        _ => (exposed_cases as f64 / exposed_total as f64) / (control_cases as f64 / control_total as f64),
266    };
267    Ok(RelativeRiskResult { relative_risk: rr, counts: (exposed_cases, exposed_total, control_cases, control_total) })
268}
269
270impl RelativeRiskResult {
271    /// Katz's interval `RR exp(±z √(1/a − 1/n₁ + 1/c − 1/n₂))`.
272    pub fn confidence_interval(&self, confidence_level: f64) -> Result<(f64, f64), ErrorsJSL> {
273        if !(0.0..=1.0).contains(&confidence_level) {
274            return Err(ErrorsJSL::InvalidInputRange("the confidence level must lie in [0, 1]"));
275        }
276        let (a, n1, c, n2) = self.counts;
277        Ok(match (a, c) {
278            (0, 0) => (f64::NAN, f64::NAN),
279            (0, _) => (0.0, f64::NAN),
280            (_, 0) => (f64::NAN, f64::INFINITY),
281            _ => {
282                let z = normal_quantile(1.0 - (1.0 - confidence_level) / 2.0);
283                let se = (1.0 / a as f64 - 1.0 / n1 as f64 + 1.0 / c as f64 - 1.0 / n2 as f64).sqrt();
284                (self.relative_risk * (-z * se).exp(), self.relative_risk * (z * se).exp())
285            }
286        })
287    }
288}
289
290/// A measure of association for an `r × c` table (SciPy's `association`'s `method`).
291#[derive(Clone, Copy, Debug, PartialEq, Eq)]
292#[non_exhaustive]
293pub enum AssociationMethod {
294    /// Cramér's V, `√(φ² / min(r − 1, c − 1))`.
295    Cramer,
296    /// Tschuprow's T, `√(φ² / √((r − 1)(c − 1)))`.
297    Tschuprow,
298    /// Pearson's contingency coefficient, `√(φ² / (1 + φ²))`.
299    Pearson,
300}
301
302/// The strength of association between the two variables of a contingency table (SciPy's
303/// `contingency.association`), from `φ² = χ²/N` without continuity correction: 0 for
304/// independence, 1 (for Cramér's V and Tschuprow's T on square tables) for perfect association.
305pub fn association(table: &[Vec<u64>], method: AssociationMethod) -> Result<f64, ErrorsJSL> {
306    let r = table.len();
307    let c = table.first().map_or(0, |row| row.len());
308    if r < 2 || c < 2 || table.iter().any(|row| row.len() != c) {
309        return Err(ErrorsJSL::InvalidInputRange("association: need a rectangular table with at least 2 × 2 cells"));
310    }
311    let total: f64 = table.iter().flatten().map(|&v| v as f64).sum();
312    let rows: Vec<f64> = table.iter().map(|row| row.iter().map(|&v| v as f64).sum()).collect();
313    let cols: Vec<f64> = (0..c).map(|j| table.iter().map(|row| row[j] as f64).sum()).collect();
314    if rows.iter().chain(&cols).any(|&s| s == 0.0) {
315        return Err(ErrorsJSL::InvalidInputRange("association: a row or column sums to zero"));
316    }
317    let mut chi2 = 0.0;
318    for i in 0..r {
319        for j in 0..c {
320            let e = rows[i] * cols[j] / total;
321            chi2 += (table[i][j] as f64 - e).powi(2) / e;
322        }
323    }
324    let phi2 = chi2 / total;
325    let (rf, cf) = (r as f64, c as f64);
326    Ok(match method {
327        AssociationMethod::Cramer => (phi2 / (cf - 1.0).min(rf - 1.0)).sqrt(),
328        AssociationMethod::Tschuprow => (phi2 / ((rf - 1.0) * (cf - 1.0)).sqrt()).sqrt(),
329        AssociationMethod::Pearson => (phi2 / (1.0 + phi2)).sqrt(),
330    })
331}
332
333#[cfg(test)]
334mod tests {
335    use super::*;
336
337    #[test]
338    fn effect_sizes() {
339        let t = [[12, 5], [3, 15]];
340        assert!((odds_ratio(t, OddsRatioKind::Sample).statistic - 12.0).abs() < 1e-15);
341        let c = odds_ratio(t, OddsRatioKind::Conditional);
342        // The conditional MLE is shrunk towards 1 relative to the sample odds ratio.
343        assert!(c.statistic > 1.0 && c.statistic < 12.0);
344        let (lo, hi) = c.confidence_interval(0.95, Alternative::TwoSided).unwrap();
345        assert!(lo < c.statistic && c.statistic < hi);
346        assert_eq!(odds_ratio([[0, 6], [5, 9]], OddsRatioKind::Conditional).statistic, 0.0);
347        let rr = relative_risk(10, 100, 5, 100).unwrap();
348        assert!((rr.relative_risk - 2.0).abs() < 1e-15);
349        // A perfectly associated square table.
350        let perfect = vec![vec![10, 0, 0], vec![0, 7, 0], vec![0, 0, 4]];
351        assert!((association(&perfect, AssociationMethod::Cramer).unwrap() - 1.0).abs() < 1e-15);
352        let independent = vec![vec![10, 20], vec![30, 60]];
353        assert!(association(&independent, AssociationMethod::Cramer).unwrap() < 1e-15);
354    }
355}