File size: 8,652 Bytes
3f5bffe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
528e4d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f5bffe
 
 
 
 
 
 
 
 
528e4d0
 
 
 
3f5bffe
 
 
 
 
 
 
 
 
 
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
"""Turn raw job JSON into the numbers behind each claim.

Usage: python analyze.py <claim> <results.json> [more.json ...]
"""

from __future__ import annotations

import glob
import json
import sys

import numpy as np


def load(paths):
    out = []
    for p in paths:
        for f in sorted(glob.glob(p)):
            with open(f) as fh:
                out.append(json.load(fh))
    return out


# --------------------------------------------------------------------------
# Claim 1 / Claim 5: from the ablation records
# --------------------------------------------------------------------------


def claim1(paths):
    """Proposition 1: the standard (EIG) utility choice is suboptimal w.r.t. the
    Lagrangian utility that accounts for the drifter's future trajectory.

    The paper's formal proof (App. D) is a one-line argmax argument giving only
    the weak inequality LU(x^S) <= LU(x*). Here we measure whether the gap is
    real and how big it is, using the ground-truth field to define LU = B(.;true).
    """
    recs = [r for d in load(paths) for r in d["records"]]
    rows = []
    for r in recs:
        u_true = np.array(r["u_true"])
        u_eig = np.array(r["u_eig"])
        u_ball = np.array(r["u"]).mean(0)
        i_eig, i_ball, i_star = u_eig.argmax(), u_ball.argmax(), u_true.argmax()
        rows.append({
            "t": r["t"],
            "LU_star": u_true[i_star],
            "LU_eig": u_true[i_eig],
            "LU_ballast": u_true[i_ball],
            "LU_mean": u_true.mean(),  # uniform policy
            "strict": bool(u_true[i_eig] < u_true[i_star] - 1e-9),
            "eig_is_argmax": bool(i_eig == i_star),
        })
    out = {}
    for t in sorted(set(r["t"] for r in rows)):
        sub = [r for r in rows if r["t"] == t]
        gap_eig = np.array([(r["LU_star"] - r["LU_eig"]) / abs(r["LU_star"]) * 100 for r in sub])
        gap_bal = np.array([(r["LU_star"] - r["LU_ballast"]) / abs(r["LU_star"]) * 100 for r in sub])
        gap_uni = np.array([(r["LU_star"] - r["LU_mean"]) / abs(r["LU_star"]) * 100 for r in sub])
        out[t] = {
            "n": len(sub),
            "pct_strictly_suboptimal": 100 * np.mean([r["strict"] for r in sub]),
            "gap_eig_pct": [gap_eig.mean(), 2 * gap_eig.std() / np.sqrt(len(sub))],
            "gap_ballast_pct": [gap_bal.mean(), 2 * gap_bal.std() / np.sqrt(len(sub))],
            "gap_unif_pct": [gap_uni.mean(), 2 * gap_uni.std() / np.sqrt(len(sub))],
        }
    return out


def claim5(paths):
    """Sec. 5.1 / G.1: percentage utility gap vs J, and the J at which it drops
    below 1%.

        Gap_MC(J)   = B(s*; inf) - B(s*_J; inf),  approximated with J=200
        Gap_Full(J) = B(s*_true; true) - B(s*_J; true)
    """
    recs = [r for d in load(paths) for r in d["records"]]
    ts = sorted(set(r["t"] for r in recs))
    out = {}
    for t in ts:
        sub = [r for r in recs if r["t"] == t]
        Jmax = np.array(sub[0]["u"]).shape[0]
        Js = np.arange(1, Jmax + 1)
        mc = np.zeros((len(sub), Jmax))
        full = np.zeros((len(sub), Jmax))
        eig_mc, eig_full, uni_mc, uni_full = [], [], [], []
        for i, r in enumerate(sub):
            u = np.array(r["u"])  # (Jmax, N)
            u_true = np.array(r["u_true"])
            u_eig = np.array(r["u_eig"])
            B_inf = u.mean(0)  # B(.; inf) approximated by J=200
            s_star = B_inf.argmax()
            s_true = u_true.argmax()
            run = np.cumsum(u, axis=0) / Js[:, None]  # B(.; J) for each J
            sJ = run.argmax(axis=1)  # s*_J
            mc[i] = (B_inf[s_star] - B_inf[sJ]) / abs(B_inf[s_star]) * 100
            full[i] = (u_true[s_true] - u_true[sJ]) / abs(u_true[s_true]) * 100
            ie = u_eig.argmax()
            eig_mc.append((B_inf[s_star] - B_inf[ie]) / abs(B_inf[s_star]) * 100)
            eig_full.append((u_true[s_true] - u_true[ie]) / abs(u_true[s_true]) * 100)
            uni_mc.append((B_inf[s_star] - B_inf.mean()) / abs(B_inf[s_star]) * 100)
            uni_full.append((u_true[s_true] - u_true.mean()) / abs(u_true[s_true]) * 100)

        def band(a):
            return a.mean(0), 2 * a.std(0) / np.sqrt(a.shape[0])

        m_mc, s_mc = band(mc)
        m_fu, s_fu = band(full)
        below = np.where(m_mc < 1.0)[0]
        out[t] = {
            "n_reps": len(sub),
            "J": Js.tolist(),
            "gap_mc_mean": m_mc.tolist(), "gap_mc_se2": s_mc.tolist(),
            "gap_full_mean": m_fu.tolist(), "gap_full_se2": s_fu.tolist(),
            "J_at_1pct_mc": int(Js[below[0]]) if len(below) else None,
            "eig_gap_mc": float(np.mean(eig_mc)), "eig_gap_full": float(np.mean(eig_full)),
            "unif_gap_mc": float(np.mean(uni_mc)), "unif_gap_full": float(np.mean(uni_full)),
            "gap_at_J20_mc": float(m_mc[19]), "gap_at_J20_full": float(m_fu[19]),
        }
    return out


# --------------------------------------------------------------------------
# Claims 3 / 4: policy comparison
# --------------------------------------------------------------------------

POLICY_ORDER = ["unif", "sobol", "dist_sep", "eig", "ballast_opt", "ballast_true"]


def claim34(paths):
    from ballast.experiment import iso_performance

    res = [r for d in load(paths) for r in d["results"]]
    seeds = sorted(set(r["seed"] for r in res))
    pols = [p for p in POLICY_ORDER if any(r["policy"] == p for r in res)]
    by = {(r["seed"], r["policy"]): np.array(r["errors"]) for r in res}
    n_dep = len(next(iter(by.values())))

    # runs where every policy completed
    good = [s for s in seeds if all((s, p) in by for p in pols)]
    E = {p: np.stack([by[(s, p)] for s in good]) for p in pols}  # (n_runs, n_dep)

    # --- average policy rank per iteration (1 = best)
    stack = np.stack([E[p] for p in pols])  # (n_pol, n_runs, n_dep)
    order = stack.argsort(axis=0).argsort(axis=0) + 1
    rank_mean = order.mean(axis=1)  # (n_pol, n_dep)
    rank_se2 = 2 * order.std(axis=1) / np.sqrt(len(good))

    # --- iso-performance vs UNIF
    iso = {}
    for p in pols:
        v = np.stack([iso_performance(E[p][i], E["unif"][i]) for i in range(len(good))])
        iso[p] = {
            "mean": np.nanmean(v, axis=0).tolist(),
            "se2": (2 * np.nanstd(v, axis=0) / np.sqrt(len(good))).tolist(),
            "final": float(np.nanmean(v[:, -1])),
            "final_se2": float(2 * np.nanstd(v[:, -1]) / np.sqrt(len(good))),
        }
    n_policy_chosen = n_dep - 1  # the first drifter is placed uniformly at random

    # The paper defines iso-performance as "averaged over each iteration's
    # results" (Sec. 5.2) and reports the saving as a single number ("save about
    # 3 drifters ~16%"). We therefore headline the mean over deployment
    # iterations, which matches the paper's Claim-3 number almost exactly (3.4 vs
    # 3). The final-iteration value ("drifters needed to match uniform's *final*
    # accuracy") is a different, larger statistic and is kept as a secondary read.
    iso_avg = {p: float(np.nanmean(iso[p]["mean"])) for p in pols}
    iso_avg_se2 = {
        p: float(2 * np.nanstd([np.nanmean(
            [iso_performance(E[p][i], E["unif"][i])]) for i in range(len(good))])
            / np.sqrt(len(good)))
        for p in pols
    }
    # per-run averaged-over-iterations, for a correct standard error
    iso_avg_runs = {
        p: np.array([np.nanmean(iso_performance(E[p][i], E["unif"][i]))
                     for i in range(len(good))])
        for p in pols
    }
    iso_avg = {p: float(np.nanmean(iso_avg_runs[p])) for p in pols}
    iso_avg_se2 = {p: float(2 * np.nanstd(iso_avg_runs[p]) / np.sqrt(len(good)))
                   for p in pols}
    return {
        "n_runs": len(good),
        "policies": pols,
        "n_deploy": n_dep,
        "rank_mean": rank_mean.tolist(),
        "rank_se2": rank_se2.tolist(),
        "err_mean": {p: E[p].mean(0).tolist() for p in pols},
        "err_se2": {p: (2 * E[p].std(0) / np.sqrt(len(good))).tolist() for p in pols},
        "iso": iso,
        "iso_avg": iso_avg,  # paper's metric: averaged over iterations
        "iso_avg_se2": iso_avg_se2,
        "savings_pct_avg": {p: 100 * iso_avg[p] / n_policy_chosen for p in pols},
        "savings_pct_final": {p: 100 * iso[p]["final"] / n_policy_chosen for p in pols},
        "n_obs_mean": {
            p: float(np.mean([r["n_obs"] for r in res if r["policy"] == p])) for p in pols
        },
    }


if __name__ == "__main__":
    which, paths = sys.argv[1], sys.argv[2:]
    fn = {"claim1": claim1, "claim5": claim5, "claim34": claim34}[which]
    print(json.dumps(fn(paths), indent=2, default=float))