pragmastat 14.0.1

Pragmastat: Pragmatic Statistical Toolkit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
//! PairwiseMargin function for computing confidence bound margins
//!
//! Determines how many extreme pairwise differences to exclude when constructing bounds
//! based on the distribution of dominance statistics.

use crate::assumptions::{AssumptionError, Subject};

const MAX_EXACT_SIZE: usize = 400;
const MAX_ACCEPTABLE_BINOM_N: usize = 62;

/// PairwiseMargin determines how many extreme pairwise differences to exclude
/// when constructing bounds based on the distribution of dominance statistics.
/// Uses exact calculation for small samples (n+m <= 400) and Edgeworth
/// approximation for larger samples.
///
/// # Arguments
///
/// * `n` - Sample size of first sample (must be positive)
/// * `m` - Sample size of second sample (must be positive)
/// * `misrate` - Misclassification rate (must be in [0, 1])
///
/// # Returns
///
/// Integer representing the total margin split between lower and upper tails,
/// or an error if inputs are invalid.
///
/// # Errors
///
/// Returns an error if n == 0, m == 0, or misrate is outside [0, 1] or is NaN.
pub fn pairwise_margin(n: usize, m: usize, misrate: f64) -> Result<u64, AssumptionError> {
    if n == 0 {
        return Err(AssumptionError::domain(Subject::X));
    }
    if m == 0 {
        return Err(AssumptionError::domain(Subject::Y));
    }
    if misrate.is_nan() || !(0.0..=1.0).contains(&misrate) {
        return Err(AssumptionError::domain(Subject::Misrate));
    }

    let min_misrate = crate::min_misrate::min_achievable_misrate_two_sample(n, m)?;
    if misrate < min_misrate {
        return Err(AssumptionError::domain(Subject::Misrate));
    }

    if n + m <= MAX_EXACT_SIZE {
        Ok(pairwise_margin_exact(n, m, misrate))
    } else {
        Ok(pairwise_margin_approx(n, m, misrate))
    }
}

/// Uses the exact distribution based on Loeffler's recurrence
fn pairwise_margin_exact(n: usize, m: usize, misrate: f64) -> u64 {
    pairwise_margin_exact_raw(n, m, misrate / 2.0) as u64 * 2
}

/// Uses Edgeworth approximation for large samples
fn pairwise_margin_approx(n: usize, m: usize, misrate: f64) -> u64 {
    pairwise_margin_approx_raw(n, m, misrate / 2.0) * 2
}

/// Inversed implementation of Andreas Löffler's (1982)
/// "Über eine Partition der nat. Zahlen und ihre Anwendung beim U-Test"
fn pairwise_margin_exact_raw(n: usize, m: usize, p: f64) -> usize {
    let total = if n + m < MAX_ACCEPTABLE_BINOM_N {
        binomial_coefficient(n + m, m)
    } else {
        binomial_coefficient_float(n + m, m)
    };

    let capacity = n * m + 1;
    let mut pmf = Vec::with_capacity(capacity);
    pmf.push(1.0); // pmf[0] = 1
    let mut sigma = Vec::with_capacity(capacity);
    sigma.push(0.0); // sigma[0] is unused

    let mut u: usize = 0;
    let mut cdf = 1.0 / total;

    if cdf >= p {
        return 0;
    }

    loop {
        u += 1;

        // Ensure sigma has entry for u
        if sigma.len() <= u {
            let mut value = 0;
            for d in 1..=n {
                if u.is_multiple_of(d) && u >= d {
                    value += d as i64;
                }
            }
            for d in (m + 1)..=(m + n) {
                if u.is_multiple_of(d) && u >= d {
                    value -= d as i64;
                }
            }
            sigma.push(value as f64);
        }

        // Compute pmf[u] using Loeffler recurrence
        let mut sum = 0.0;
        for i in 0..u {
            sum = f64::mul_add(pmf[i], sigma[u - i], sum);
        }
        sum /= u as f64;
        pmf.push(sum);

        cdf += sum / total;
        if cdf >= p {
            return u;
        }
        if sum == 0.0 {
            break;
        }
    }

    pmf.len() - 1
}

/// Inverse Edgeworth Approximation
fn pairwise_margin_approx_raw(n: usize, m: usize, misrate: f64) -> u64 {
    let mut a: u64 = 0;
    let mut b: u64 = n as u64 * m as u64;
    while a < b - 1 {
        let c = u64::midpoint(a, b);
        let p = edgeworth_cdf(n, m, c);
        if p < misrate {
            a = c;
        } else {
            b = c;
        }
    }

    if edgeworth_cdf(n, m, b) < misrate {
        b
    } else {
        a
    }
}

/// Computes the CDF using Edgeworth expansion
fn edgeworth_cdf(n: usize, m: usize, u: u64) -> f64 {
    let n_f64 = n as f64;
    let m_f64 = m as f64;
    let u_f64 = u as f64;

    let mu = (n_f64 * m_f64) / 2.0;
    let su = ((n_f64 * m_f64 * (n_f64 + m_f64 + 1.0)) / 12.0).sqrt();
    // -0.5 continuity correction: computing P(U ≥ u) for a right-tail discrete CDF
    let z = (u_f64 - mu - 0.5) / su;

    // Standard normal PDF and CDF
    let phi = (-z * z / 2.0).exp() / (2.0 * std::f64::consts::PI).sqrt();
    let big_phi = crate::gauss_cdf::gauss_cdf(z);

    // Pre-compute powers of n and m for efficiency
    let n2 = n_f64 * n_f64;
    let n3 = n2 * n_f64;
    let n4 = n2 * n2;
    let m2 = m_f64 * m_f64;
    let m3 = m2 * m_f64;
    let m4 = m2 * m2;

    // Compute moments
    let mu2 = (n_f64 * m_f64 * (n_f64 + m_f64 + 1.0)) / 12.0;
    let mu4 = (n_f64
        * m_f64
        * (n_f64 + m_f64 + 1.0)
        * (5.0 * m_f64 * n_f64 * (m_f64 + n_f64) - 2.0 * (m2 + n2) + 3.0 * m_f64 * n_f64
            - 2.0 * (n_f64 + m_f64)))
        / 240.0;

    let mu6 = (n_f64
        * m_f64
        * (n_f64 + m_f64 + 1.0)
        * (35.0 * m2 * n2 * (m2 + n2) + 70.0 * m3 * n3
            - 42.0 * m_f64 * n_f64 * (m3 + n3)
            - 14.0 * m2 * n2 * (n_f64 + m_f64)
            + 16.0 * (n4 + m4)
            - 52.0 * n_f64 * m_f64 * (n2 + m2)
            - 43.0 * n2 * m2
            + 32.0 * (m3 + n3)
            + 14.0 * m_f64 * n_f64 * (n_f64 + m_f64)
            + 8.0 * (n2 + m2)
            + 16.0 * n_f64 * m_f64
            - 8.0 * (n_f64 + m_f64)))
        / 4032.0;

    // Pre-compute powers of mu2 and related terms
    let mu2_2 = mu2 * mu2;
    let mu2_3 = mu2_2 * mu2;
    let mu4_mu2_2 = mu4 / mu2_2;

    // Factorial constants: 4! = 24, 6! = 720, 8! = 40320
    let e3 = (mu4_mu2_2 - 3.0) / 24.0;
    let e5 = (mu6 / mu2_3 - 15.0 * mu4_mu2_2 + 30.0) / 720.0;
    let e7 = 35.0 * (mu4_mu2_2 - 3.0) * (mu4_mu2_2 - 3.0) / 40320.0;

    // Pre-compute powers of z for Hermite polynomials
    let z2 = z * z;
    let z3 = z2 * z;
    let z5 = z3 * z2;
    let z7 = z5 * z2;

    // Hermite polynomial derivatives: f_n = -phi * H_n(z)
    let f3 = -phi * (z3 - 3.0 * z);
    let f5 = -phi * (z5 - 10.0 * z3 + 15.0 * z);
    let f7 = -phi * (z7 - 21.0 * z5 + 105.0 * z3 - 105.0 * z);

    // Edgeworth expansion
    let edgeworth = big_phi + e3 * f3 + e5 * f5 + e7 * f7;

    // Clamp to [0, 1]
    edgeworth.clamp(0.0, 1.0)
}

/// Computes binomial coefficient C(n, k) using integer arithmetic
fn binomial_coefficient(n: usize, k: usize) -> f64 {
    if k > n {
        return 0.0;
    }
    if k == 0 || k == n {
        return 1.0;
    }

    let k = k.min(n - k); // Take advantage of symmetry
    let mut result = 1u128;

    for i in 0..k {
        result = result * (n - i) as u128 / (i + 1) as u128;
    }

    result as f64
}

/// Computes binomial coefficient using floating-point logarithms for large values
fn binomial_coefficient_float(n: usize, k: usize) -> f64 {
    if k > n {
        return 0.0;
    }
    if k == 0 || k == n {
        return 1.0;
    }

    let k = k.min(n - k); // Take advantage of symmetry

    // Use log-factorial function: C(n, k) = exp(log(n!) - log(k!) - log((n-k)!))
    let log_result = log_factorial(n) - log_factorial(k) - log_factorial(n - k);
    log_result.exp()
}

/// Computes the natural logarithm of n!
fn log_factorial(n: usize) -> f64 {
    if n == 0 || n == 1 {
        return 0.0;
    }

    let x = (n + 1) as f64; // n! = Gamma(n+1)

    if x < 1e-5 {
        return 0.0;
    }

    // DONT TOUCH: Stirling's approximation is inaccurate for small x.
    // Use Gamma recurrence: Gamma(x) = Gamma(x+k) / (x*(x+1)*...*(x+k-1))
    // These branches appear unreachable in current usage (n+m >= 65), but
    // are retained for correctness if the function is used in other contexts.
    if x < 1.0 {
        return stirling_approx_log(x + 3.0) - (x * (x + 1.0) * (x + 2.0)).ln();
    }
    if x < 2.0 {
        return stirling_approx_log(x + 2.0) - (x * (x + 1.0)).ln();
    }
    if x < 3.0 {
        return stirling_approx_log(x + 1.0) - x.ln();
    }

    stirling_approx_log(x)
}

/// Stirling's approximation with Bernoulli correction
fn stirling_approx_log(x: f64) -> f64 {
    let mut result = x * x.ln() - x + (2.0 * std::f64::consts::PI / x).ln() / 2.0;

    // Bernoulli correction series
    const B2: f64 = 1.0 / 6.0;
    const B4: f64 = -1.0 / 30.0;
    const B6: f64 = 1.0 / 42.0;
    const B8: f64 = -1.0 / 30.0;
    const B10: f64 = 5.0 / 66.0;

    let x2 = x * x;
    let x3 = x2 * x;
    let x5 = x3 * x2;
    let x7 = x5 * x2;
    let x9 = x7 * x2;

    result +=
        B2 / (2.0 * x) + B4 / (12.0 * x3) + B6 / (30.0 * x5) + B8 / (56.0 * x7) + B10 / (90.0 * x9);

    result
}

#[cfg(test)]
mod tests {
    use super::pairwise_margin;
    use serde::Deserialize;
    use std::fs;
    use std::path::PathBuf;

    #[derive(Debug, Deserialize)]
    struct Input {
        n: usize,
        m: usize,
        misrate: f64,
    }

    #[derive(Debug, Deserialize)]
    struct TestCase {
        input: Input,
        output: Option<u64>,
        expected_error: Option<serde_json::Value>,
    }

    fn repo_root() -> PathBuf {
        PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .unwrap()
            .parent()
            .unwrap()
            .to_path_buf()
    }

    #[test]
    fn reference() {
        let test_data_dir = repo_root().join("tests").join("pairwise-margin");
        assert!(
            test_data_dir.exists(),
            "Test data directory not found: {test_data_dir:?}"
        );

        let json_files: Vec<_> = fs::read_dir(&test_data_dir)
            .unwrap()
            .filter_map(|entry| {
                let path = entry.unwrap().path();
                if path.extension()?.to_str()? == "json" {
                    Some(path)
                } else {
                    None
                }
            })
            .collect();

        assert!(
            !json_files.is_empty(),
            "No JSON test files found in {test_data_dir:?}"
        );

        let mut failures = Vec::new();

        for json_file in &json_files {
            let content = fs::read_to_string(json_file).unwrap();
            let test_case: TestCase = serde_json::from_str(&content).unwrap();
            let file_name = json_file.file_name().unwrap();

            if let Some(ref expected_error) = test_case.expected_error {
                let result = pairwise_margin(
                    test_case.input.n,
                    test_case.input.m,
                    test_case.input.misrate,
                );
                match result {
                    Ok(_) => failures.push(format!("{file_name:?}: expected error, got Ok")),
                    Err(err) => {
                        if let Some(expected_id) = expected_error.get("id").and_then(|v| v.as_str())
                        {
                            if err.violation().id.as_str() != expected_id {
                                failures.push(format!(
                                    "{file_name:?}: expected violation id {expected_id}, got {}",
                                    err.violation().id.as_str()
                                ));
                            }
                        }
                    }
                }
                continue;
            }

            let actual_output = match pairwise_margin(
                test_case.input.n,
                test_case.input.m,
                test_case.input.misrate,
            ) {
                Ok(val) => val,
                Err(e) => {
                    failures.push(format!("{file_name:?}: unexpected error {e:?}"));
                    continue;
                }
            };
            let expected_output = test_case.output.expect("Test case must have output");

            if actual_output != expected_output {
                failures.push(format!(
                    "{file_name:?}: expected {expected_output}, got {actual_output}"
                ));
            }
        }

        assert!(
            failures.is_empty(),
            "Failed tests:\n{}",
            failures.join("\n")
        );
    }

    use crate::assumptions::{AssumptionId, Subject};

    #[test]
    fn zero_n() {
        let result = pairwise_margin(0, 10, 0.05);
        assert!(result.is_err());
        let v = result.unwrap_err().violation();
        assert_eq!(v.id, AssumptionId::Domain);
        assert_eq!(v.subject, Subject::X);
    }

    #[test]
    fn zero_m() {
        let result = pairwise_margin(10, 0, 0.05);
        assert!(result.is_err());
        let v = result.unwrap_err().violation();
        assert_eq!(v.id, AssumptionId::Domain);
        assert_eq!(v.subject, Subject::Y);
    }

    #[test]
    fn negative_misrate() {
        let result = pairwise_margin(10, 10, -0.1);
        assert!(result.is_err());
        let v = result.unwrap_err().violation();
        assert_eq!(v.id, AssumptionId::Domain);
        assert_eq!(v.subject, Subject::Misrate);
    }

    #[test]
    fn misrate_greater_than_one() {
        let result = pairwise_margin(10, 10, 1.5);
        assert!(result.is_err());
        let v = result.unwrap_err().violation();
        assert_eq!(v.id, AssumptionId::Domain);
        assert_eq!(v.subject, Subject::Misrate);
    }

    #[test]
    fn nan_misrate() {
        let result = pairwise_margin(10, 10, f64::NAN);
        assert!(result.is_err());
        let v = result.unwrap_err().violation();
        assert_eq!(v.id, AssumptionId::Domain);
        assert_eq!(v.subject, Subject::Misrate);
    }

    #[test]
    fn misrate_below_min() {
        // n=2, m=2: min_misrate = 2/C(4,2) = 1/3 ≈ 0.333
        let result = pairwise_margin(2, 2, 0.05);
        assert!(result.is_err());
        let v = result.unwrap_err().violation();
        assert_eq!(v.id, AssumptionId::Domain);
        assert_eq!(v.subject, Subject::Misrate);
    }
}