File size: 9,327 Bytes
0dd5490
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Tests for src.decode. Run with `python -m pytest tests` or `python tests/test_decode.py`."""
import itertools
import math
import sys
from pathlib import Path

import numpy as np

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from src.decode import (best_subset, decode_all, decode_arrays,  # noqa: E402
                        expected_f05_topk, threshold_decode)
from src.metric import f05_entity  # noqa: E402


# ---------------------------------------------------------------------------
# helpers: independent reference implementations
# ---------------------------------------------------------------------------
def _pb_pmf(p):
    pmf = np.array([1.0])
    for x in p:
        pmf = np.convolve(pmf, [1.0 - x, x])
    return pmf


def _expected_naive(p):
    """O(m^3) prefix x suffix double sum, straight from the definition."""
    p = np.sort(np.asarray(p, float))[::-1]
    m = len(p)
    out = np.zeros(m + 1)
    out[0] = np.prod(1 - p)
    for k in range(1, m + 1):
        pre, suf = _pb_pmf(p[:k]), _pb_pmf(p[k:])
        for a in range(1, k + 1):
            for b in range(len(suf)):
                out[k] += pre[a] * suf[b] * 1.25 * (a / k) * (a / (a + b)) / (0.25 * a / k + a / (a + b))
    return out


def _expected_enumerate(p):
    """Exact expectation by enumerating all 2^m label vectors, scored with src.metric."""
    p = np.sort(np.asarray(p, float))[::-1]
    m = len(p)
    out = np.zeros(m + 1)
    for y in itertools.product([0, 1], repeat=m):
        w = np.prod([pi if yi else 1 - pi for pi, yi in zip(p, y)])
        true = {i for i in range(m) if y[i]}
        for k in range(m + 1):
            out[k] += w * f05_entity(set(range(k)), true)
    return out


def _crossover(p1=0.95, lo=0.0, hi=None, iters=60):
    """Smallest p2 at which predicting both beats predicting only the first."""
    hi = p1 if hi is None else hi
    assert best_subset([p1, lo])[0] == 1 and best_subset([p1, hi])[0] == 2
    for _ in range(iters):
        mid = 0.5 * (lo + hi)
        if best_subset([p1, mid])[0] == 2:
            hi = mid
        else:
            lo = mid
    return 0.5 * (lo + hi)


# ---------------------------------------------------------------------------
# (a) single candidate: include iff p > 0.5
# ---------------------------------------------------------------------------
def test_single_candidate():
    assert best_subset(np.array([0.49]))[0] == 0
    assert best_subset(np.array([0.51]))[0] == 1
    k, v = best_subset(np.array([0.49]))
    assert math.isclose(v, 0.51)
    k, v = best_subset(np.array([0.51]))
    assert math.isclose(v, 0.51)
    assert best_subset(np.array([0.5]))[0] == 0      # tie -> prefer the smaller set
    assert best_subset(np.array([]))[0] == 0
    assert best_subset(np.array([]))[1] == 1.0


# ---------------------------------------------------------------------------
# (b) second-candidate crossover with p1 = 0.95
# ---------------------------------------------------------------------------
def test_two_candidate_crossover():
    x = _crossover(0.95)
    # closed form: E1 = p1 (1 - p2/6), E2 = 5/9 (p1 + p2 - 2 p1 p2) + p1 p2
    p1 = 0.95
    analytic = (p1 - 5 / 9 * p1) / (5 / 9 * (1 - 2 * p1) + p1 + p1 / 6)
    print(f"  p2 crossover at p1=0.95: {x:.6f} (closed form {analytic:.6f})")
    assert 0.65 < x < 0.72
    assert abs(x - analytic) < 1e-9


# ---------------------------------------------------------------------------
# (c) Monte Carlo agreement, and exact agreement with brute force
# ---------------------------------------------------------------------------
def test_monte_carlo_matches_dp():
    rng = np.random.default_rng(12345)
    n_draws = 200_000
    worst = 0.0
    for trial in range(16):
        m = int(rng.integers(1, 9))
        if trial % 3 == 0:
            p = rng.random(m)
        elif trial % 3 == 1:
            p = rng.beta(0.5, 0.5, m)
        else:
            p = rng.beta(0.4, 3.0, m)
        p = np.sort(p)[::-1]
        dp = expected_f05_topk(p)
        y = rng.random((n_draws, m)) < p                # independent labels
        n = y.sum(axis=1)
        tp = np.cumsum(y, axis=1)
        mc = np.empty(m + 1)
        mc[0] = (n == 0).mean()
        for k in range(1, m + 1):
            t = tp[:, k - 1]
            mc[k] = np.where(t > 0, 5.0 * t / (4.0 * k + n), 0.0).mean()
        err = np.abs(mc - dp).max()
        worst = max(worst, err)
        assert err < 0.005, (p, mc, dp)
    print(f"  max |MC - DP| over 16 vectors: {worst:.5f}")


def test_exact_vs_enumeration_and_naive():
    rng = np.random.default_rng(7)
    for m in range(1, 9):
        p = rng.random(m)
        dp = expected_f05_topk(p)
        assert np.allclose(dp, _expected_enumerate(p), atol=1e-12, rtol=0)
        assert np.allclose(dp, _expected_naive(p), atol=1e-12, rtol=0)
    # large m against the O(m^3) reference
    for m in (30, 60):
        p = np.concatenate([rng.beta(5, 1, 3), rng.beta(0.3, 6, m - 3)])
        dp = expected_f05_topk(p)
        assert np.allclose(dp, _expected_naive(p), atol=1e-12, rtol=0)
        assert (dp >= -1e-15).all() and (dp <= 1 + 1e-12).all()


def test_input_order_irrelevant_and_edge_probs():
    p = np.array([0.1, 0.9, 0.0, 1.0, 0.3])
    assert np.allclose(expected_f05_topk(p), expected_f05_topk(p[::-1]))
    k, v = best_subset(np.array([1.0, 1.0, 0.0]))
    assert k == 2 and math.isclose(v, 1.0)
    assert best_subset(np.array([np.nan, 0.2]))[0] == 0


def test_min_prob_and_max_k():
    p = np.array([0.99, 0.97, 0.96, 0.95])
    assert best_subset(p)[0] == 4
    assert best_subset(p, max_k=2)[0] == 2
    assert best_subset(p, min_prob=0.965)[0] == 2
    E = expected_f05_topk(p)
    assert math.isclose(best_subset(p, max_k=2)[1], E[:3].max())
    assert best_subset(np.array([0.6]), min_prob=0.7)[0] == 0


def test_threshold_decode():
    p = np.array([0.2, 0.5, 0.51, 0.9])
    assert threshold_decode(p, 0.5).tolist() == [False, False, True, True]


# ---------------------------------------------------------------------------
# (d) decode_all agrees with best_subset per entity
# ---------------------------------------------------------------------------
def _synthetic(n_ent=3000, max_m=60, seed=3):
    rng = np.random.default_rng(seed)
    m = rng.integers(1, max_m + 1, size=n_ent)
    ids = np.array([f"S1-{i:06d}" for i in range(n_ent)], dtype=object)
    s1 = np.repeat(ids, m)
    N = int(m.sum())
    p = np.where(rng.random(N) < 0.08, rng.beta(4, 1, N), rng.beta(0.4, 4, N))
    perm = rng.permutation(N)                          # rows not grouped by entity
    return s1[perm], p[perm]


def _check_against_best_subset(s1, p, out, **kw):
    by_ent = {}
    for i, sid in enumerate(s1.tolist()):
        by_ent.setdefault(sid, []).append(i)
    assert set(out) == set(by_ent)
    for sid, rows in by_ent.items():
        rows = np.array(rows)
        k, _ = best_subset(p[rows], **kw)
        top = rows[np.argsort(-p[rows], kind="stable")[:k]]
        assert sorted(out[sid]) == sorted(top.tolist()), sid


def test_decode_all_matches_best_subset():
    s1, p = _synthetic()
    assert len(p) > 50_000                             # large enough to use the pool
    out_mp = decode_all(s1, p, n_jobs=2)
    out_1 = decode_all(s1, p, n_jobs=1)
    assert out_mp == out_1
    _check_against_best_subset(s1, p, out_mp)
    # expected values agree too
    r = decode_arrays(s1, p, n_jobs=1)
    for e in range(0, len(r.entity_ids), 97):
        rows = np.flatnonzero(s1 == r.entity_ids[e])
        k, v = best_subset(p[rows])
        assert k == r.k[e] and math.isclose(v, r.expected_f05[e], rel_tol=1e-12)


def test_decode_all_caps_and_threshold():
    s1, p = _synthetic(n_ent=800, seed=11)
    out = decode_all(s1, p, n_jobs=1, max_k=2, min_prob=0.3)
    _check_against_best_subset(s1, p, out, max_k=2, min_prob=0.3)
    out_t = decode_all(s1, p, n_jobs=1, method="threshold", threshold=0.4)
    mask = threshold_decode(p, 0.4)
    assert sorted(i for v in out_t.values() for i in v) == np.flatnonzero(mask).tolist()


def test_decode_frame_roundtrip():
    import pandas as pd
    from src.decode import decode_frame, pred_dict_from_frame
    from src.metric import macro_f05
    df = pd.DataFrame({
        "source1_entity_id": ["a", "a", "b", "c", "c", "c"],
        "candidate_entity_id": ["x1", "x2", "y1", "z1", "z2", "z3"],
        "prob": [0.9, 0.2, 0.3, 0.97, 0.96, 0.1],
    })
    fr = decode_frame(df, n_jobs=1)
    pred = pred_dict_from_frame(fr)
    assert pred == {"a": {"x1"}, "b": set(), "c": {"z1", "z2"}}
    assert fr.set_index("source1_entity_id").loc["c", "matched_entity_ids"] == ["z1", "z2"]
    truth = {"a": {"x1"}, "b": set(), "c": {"z1", "z2"}, "d": set()}
    assert macro_f05(pred, truth) == 1.0


def _run_all():
    mod = sys.modules[__name__]
    names = [n for n in dir(mod) if n.startswith("test_") and callable(getattr(mod, n))]
    failed = 0
    for n in names:
        try:
            getattr(mod, n)()
            print(f"PASS {n}")
        except Exception as e:  # noqa: BLE001
            failed += 1
            import traceback
            traceback.print_exc()
            print(f"FAIL {n}: {type(e).__name__}: {e}")
    print(f"{len(names) - failed}/{len(names)} passed")
    return failed


if __name__ == "__main__":
    raise SystemExit(1 if _run_all() else 0)