File size: 5,664 Bytes
0c3dd1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Per-scenario rank rule (the same rule as Case 1), pairwise win rates, Kendall tau and goal bootstrap. Sim2Sim.

Times: array T[policy, goal, trial] in seconds, failure = HORIZON (40 s), so failures rank last and tie.
Rank rule: per (goal, trial) fractional ranks by time (1 = fastest, ties share the mean rank).
Policy score = mean rank, first over the trials of a goal, then over goals (equal goal weight).
Order = ascending mean rank. Win rate P(p beats q) = mean of 1[T_p < T_q] + 0.5 * 1[T_p == T_q].
Bootstrap resamples goals (stratified by goal range), keeps all trials of a goal, and is paired across
methods (the same goal indices for ROM methods and Chrono).
"""
import numpy as np
from scipy.stats import rankdata

from common import HORIZON_S


def bounded(times, success):
    t = np.where(success, times, HORIZON_S)
    return np.minimum(np.nan_to_num(t, nan=HORIZON_S), HORIZON_S)


def per_goal_ranks(T):
    """T[p, g, k] -> per-goal mean rank R[p, g] (fractional ranks within each (g, k))."""
    P, G, K = T.shape
    r = rankdata(T.reshape(P, -1), axis=0, method='average').reshape(P, G, K)
    return r.mean(2)


def per_goal_wins(T):
    """W[p, q, g] = mean over trials of P(T_p < T_q) with ties 0.5."""
    lt = (T[:, None] < T[None, :]).astype(np.float64)
    eq = (T[:, None] == T[None, :]).astype(np.float64)
    return (lt + 0.5 * eq).mean(3)


def kendall_tau_b(a, b):
    """Kendall tau-b between score vectors a[..., n] and b[..., n] (lower score = better; only sign matters)."""
    i, j = np.triu_indices(a.shape[-1], 1)
    sa = np.sign(a[..., i] - a[..., j])
    sb = np.sign(b[..., i] - b[..., j])
    n0 = len(i)
    n1 = (sa == 0).sum(-1)
    n2 = (sb == 0).sum(-1)
    den = np.sqrt((n0 - n1) * (n0 - n2).astype(np.float64))
    with np.errstate(invalid='ignore', divide='ignore'):
        return np.where(den > 0, (sa * sb).sum(-1) / den, np.nan)


def spearman(a, b):
    ra = rankdata(a, axis=-1)
    rb = rankdata(b, axis=-1)
    ra = ra - ra.mean(-1, keepdims=True)
    rb = rb - rb.mean(-1, keepdims=True)
    with np.errstate(invalid='ignore', divide='ignore'):
        return (ra * rb).sum(-1) / np.sqrt((ra ** 2).sum(-1) * (rb ** 2).sum(-1))


def boot_indices(strata, B, seed):
    """strata: array of stratum labels per goal. Returns (B, G) resampled goal indices, stratified."""
    rng = np.random.default_rng(seed)
    strata = np.asarray(strata)
    cols = []
    for s in np.unique(strata):
        idx = np.flatnonzero(strata == s)
        cols.append(idx[rng.integers(0, len(idx), (B, len(idx)))])
    return np.concatenate(cols, 1)


def ci(x, lo=2.5, hi=97.5):
    x = np.asarray(x, dtype=np.float64)
    x = x[np.isfinite(x)]
    return [float(np.percentile(x, lo)), float(np.percentile(x, hi))] if len(x) else [None, None]


def summarize_method(T, success, policies, goal_range, boot=None):
    """Success by range, mean rank, order, resolved pairs. T and success are [p, g, k]."""
    R = per_goal_ranks(T)
    mr = R.mean(1)
    order = [policies[i] for i in np.argsort(mr, kind='stable')]
    out = dict(mean_rank={p: float(mr[i]) for i, p in enumerate(policies)}, order=order)
    gr = np.asarray(goal_range)
    out['success_rate'] = {rng: {p: float(success[i][gr == rng].mean()) for i, p in enumerate(policies)}
                           for rng in sorted(set(gr))}
    out['success_rate']['all'] = {p: float(success[i].mean()) for i, p in enumerate(policies)}
    # mean time over goals (and trials) where every policy succeeds
    allok = success.all(0)
    out['common_success_units'] = int(allok.sum())
    out['mean_time_common_success'] = {p: (float(T[i][allok].mean()) if allok.any() else None) for i, p in enumerate(policies)}
    if boot is not None:
        W = per_goal_wins(T)
        w = W.mean(2)
        wb = W[:, :, boot].mean(3)  # [p, q, B]
        pairs = []
        for a in range(len(policies)):
            for b in range(a + 1, len(policies)):
                lo, hi = ci(wb[a, b])
                pairs.append(dict(a=policies[a], b=policies[b], win_a=float(w[a, b]), ci95=[lo, hi],
                                  resolved=bool(lo > 0.5 or hi < 0.5)))
        out['pairs'] = pairs
        out['resolved_pairs'] = int(sum(p['resolved'] for p in pairs))
        mrb = R[:, boot].mean(2).T  # [B, p]
        out['mean_rank_ci95'] = {p: ci(mrb[:, i]) for i, p in enumerate(policies)}
    return out


def compare_to_truth(methods, truth, boot):
    """methods: dict name -> per-goal mean ranks R[p, g]; truth: R[p, g] (Chrono). Paired goal bootstrap."""
    t_mr = truth.mean(1)
    t_b = truth[:, boot].mean(2).T
    res = {}
    taus_b = {}
    for name, R in methods.items():
        mr = R.mean(1)
        rb = R[:, boot].mean(2).T
        tb = kendall_tau_b(rb, t_b)
        taus_b[name] = tb
        res[name] = dict(kendall_tau_b=float(kendall_tau_b(mr, t_mr)), kendall_ci95=ci(tb),
                         spearman=float(spearman(mr, t_mr)), spearman_ci95=ci(spearman(rb, t_b)))
    return res, taus_b


def pair_agreement(R_method, R_base, R_truth, policies):
    """Pairs where method and base disagree on order: how many does each get right relative to truth."""
    a, b, t = R_method.mean(1), R_base.mean(1), R_truth.mean(1)
    i, j = np.triu_indices(len(policies), 1)
    sm, sb, st = np.sign(a[i] - a[j]), np.sign(b[i] - b[j]), np.sign(t[i] - t[j])
    disc = (sm != sb)
    return dict(pairs=int(len(i)), method_correct=int((sm == st).sum()), base_correct=int((sb == st).sum()),
                discordant=int(disc.sum()), discordant_method_correct=int((disc & (sm == st)).sum()),
                discordant_base_correct=int((disc & (sb == st)).sum()))