File size: 3,124 Bytes
f45e98c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Statistical primitives for the evaluation experiments.

Inferential layer: paired significance (Wilcoxon signed-rank), cluster-aware bootstrap
CIs, Benjamini-Hochberg FDR, and AUC (+ bootstrap CI on AUC differences for the ablation).
"""

from __future__ import annotations

from collections import defaultdict
from collections.abc import Callable, Sequence

import numpy as np
from scipy import stats as sps


def auc(pos: Sequence[float], neg: Sequence[float]) -> float:
    """AUC = P(random pos > random neg), via Mann-Whitney U (ties = 0.5)."""
    pos = np.asarray(pos, float)
    neg = np.asarray(neg, float)
    if len(pos) == 0 or len(neg) == 0:
        return float("nan")
    ranks = sps.rankdata(np.concatenate([pos, neg]))
    u = ranks[: len(pos)].sum() - len(pos) * (len(pos) + 1) / 2
    return float(u / (len(pos) * len(neg)))


def wilcoxon_p(deltas: Sequence[float], alternative: str = "greater") -> float:
    """Wilcoxon signed-rank p-value on paired deltas (drops zeros)."""
    d = np.asarray(deltas, float)
    d = d[d != 0]
    if len(d) < 1:
        return float("nan")
    try:
        return float(sps.wilcoxon(d, alternative=alternative).pvalue)
    except ValueError:
        return float("nan")


def cohens_d_paired(deltas: Sequence[float]) -> float:
    d = np.asarray(deltas, float)
    sd = d.std(ddof=0)
    return float(d.mean() / sd) if sd > 0 else float("nan")


def bh_fdr(pvals: Sequence[float]) -> np.ndarray:
    """Benjamini-Hochberg adjusted p-values."""
    p = np.asarray(pvals, float)
    n = len(p)
    order = np.argsort(p)
    ranked = p[order] * n / np.arange(1, n + 1)
    ranked = np.minimum.accumulate(ranked[::-1])[::-1]
    adj = np.empty(n)
    adj[order] = np.clip(ranked, 0, 1)
    return adj


def cluster_bootstrap_ci(
    records: Sequence[dict],
    statfn: Callable[[list[dict]], float],
    cluster_key: Callable[[dict], str] | None = None,
    n: int = 2000,
    seed: int = 0,
    alpha: float = 0.05,
) -> tuple[float, float]:
    """Percentile CI for `statfn`. If cluster_key is given, resample whole clusters
    (accounts for non-independence within a subcorpus); else resample records."""
    rng = np.random.default_rng(seed)
    recs = list(records)
    boot: list[float] = []
    keys: list[str] = []
    if cluster_key is not None:
        groups: dict[str, list[dict]] = defaultdict(list)
        for r in recs:
            groups[cluster_key(r)].append(r)
        keys = list(groups)
        if len(keys) < 2:  # single cluster → cluster bootstrap is degenerate
            cluster_key = None
    if cluster_key is not None:
        for _ in range(n):
            chosen = rng.integers(0, len(keys), size=len(keys))
            sample: list[dict] = []
            for ci in chosen:
                sample.extend(groups[keys[ci]])
            boot.append(statfn(sample))
    else:
        m = len(recs)
        for _ in range(n):
            idx = rng.integers(0, m, size=m)
            boot.append(statfn([recs[i] for i in idx]))
    lo, hi = np.nanpercentile(boot, [100 * alpha / 2, 100 * (1 - alpha / 2)])
    return float(lo), float(hi)