File size: 5,515 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
"""Write results/exploration_report.md and results/exploration_tau_table.json: every ROM condition tried on
goal set A versus Chrono (exploration, Sim2Sim)."""
import json

import numpy as np

import rankstats as rs
import variants as V
from analyze import load_chrono, load_rom
from common import RESULTS

B = 2000
goals = json.loads((RESULTS / 'rom_A_explore/goals.json').read_text())
gids = [g['goal_id'] for g in goals]
gr = np.array([g['goal_range'] for g in goals])
pols, _, _, _ = load_rom('A', 'explore', 'nominal')
Tc, Sc = load_chrono('A', 'explore', pols, gids)
boot = rs.boot_indices(gr, B, 20261104)
sub_boot = {s: rs.boot_indices(gr[gr == s], B, 20261104 + 7 + i) for i, s in enumerate(['id', 'ood'])}
pools = {'all16': list(range(16)), 'new12': [i for i, p in enumerate(pols) if p not in ('rel1', 'rel2', 'rel3', 'rel4')]}
names = list(V.EXPLORE)
data = {n: load_rom('A', 'explore', n) for n in names}


def spec_text(n):
    K, spec = V.EXPLORE[n]
    if not spec:
        return 'none (training ROM)'
    parts = []
    for k, d in spec.items():
        if d[0] == 'const':
            parts.append(f'{k}={d[1]:g}')
        elif d[0] == 'normal':
            parts.append(f'{k}~N({d[1]:g},{d[2]:g})')
        elif d[0] == 'choice':
            parts.append(f'{k} in {{{",".join(f"{x:g}" for x in d[1])}}}')
        else:
            parts.append(f'{k}~{"LogU" if d[0] == "loguniform" else "U"}({d[1]:.3g},{d[2]:.3g})')
    return '; '.join(parts)


res = {}
for pname, idx in pools.items():
    Rc = rs.per_goal_ranks(Tc[idx])
    R = {n: rs.per_goal_ranks(data[n][2][idx]) for n in names}
    out = {}
    for sub, gi in {'all': np.arange(len(gids)), 'id': np.flatnonzero(gr == 'id'), 'ood': np.flatnonzero(gr == 'ood')}.items():
        b = boot if sub == 'all' else sub_boot[sub]
        r, taus = rs.compare_to_truth({n: R[n][:, gi] for n in names}, Rc[:, gi], b)
        for n in names:
            o = out.setdefault(n, {})
            o[sub] = r[n]['kendall_tau_b']
            if sub == 'all':
                o['ci'] = r[n]['kendall_ci95']
                o['d'] = r[n]['kendall_tau_b'] - r['nominal']['kendall_tau_b']
                o['dci'] = rs.ci(taus[n] - taus['nominal'])
                o['sr'] = float(data[n][3][idx].mean())
    res[pname] = out

L = ['# Case 2 exploration on goal set A (Sim2Sim)', '',
     'Generated by `report_explore.py` from `results/rom_A_explore/*.npz` and `results/chrono_A_explore/episodes.jsonl`.',
     'Goal set A: 50 ID (10-20 m) + 50 OOD (20-40 m) goals. Pools: all 16 (released 1-4 + 12 new) and the 12 new policies.',
     'Kendall tau-b of the ROM mean-rank order with the Chrono mean-rank order; 95 % goal-bootstrap ranges (2000 replicates,',
     'stratified by goal range, paired). Delta = tau(condition) - tau(nominal ROM). These numbers were used to choose',
     'the TR design that was then fixed for the held-out evaluation on goal set B. They are optimistic for the chosen',
     'condition (selection among all rows); the held-out evaluation tests the choice on new policies and goals.',
     "Condition 'paper_tr' is the noise-only TR (action and powertrain noise).", '',
     'Parameter units: sig_* = sd of additive noise on normalized throttle/steering per 0.1 s step; steer_rate = max change',
     'of normalized steering per 0.1 s step; delay and hold in 0.1 s steps; wheelbase in m; vmax in m/s; tau0 in N m;',
     'omega0 in rad/s; yaw0, g_rot in rad; obs_pos_sig in m; gx_scale = goal-radius factor. K = trials per goal.', '',
     '| Condition | Perturbation (per trial) | K | ROM success, 16 | tau, 16 (95 % range) | Delta, 16 (95 % range) | tau ID, 16 | tau OOD, 16 | tau, new 12 (95 % range) | Delta, new 12 (95 % range) |',
     '|---|---|---:|---:|---|---|---:|---:|---|---|']
f = lambda x: f'{x:.2f}'
for n in sorted(names, key=lambda n: -res['all16'][n]['all']):
    a, b = res['all16'][n], res['new12'][n]
    L.append(f"| {n} | {spec_text(n)} | {V.EXPLORE[n][0]} | {a['sr']:.2f} | {f(a['all'])} ({f(a['ci'][0])} to {f(a['ci'][1])}) | "
             f"{a['d']:+.2f} ({a['dci'][0]:+.2f} to {a['dci'][1]:+.2f}) | {f(a['id'])} | {f(a['ood'])} | "
             f"{f(b['all'])} ({f(b['ci'][0])} to {f(b['ci'][1])}) | {b['d']:+.2f} ({b['dci'][0]:+.2f} to {b['dci'][1]:+.2f}) |")
# per-policy table
an = json.loads((RESULTS / 'analysis_A_explore.json').read_text())
ch = an['chrono']
L += ['', '## Per policy, goal set A (exploration)', '',
      'Mean rank among 16 policies (1 = best). Success = share of goals (ROM TR: share of goal-trials).', '',
      '| Policy | Chrono success ID | Chrono success OOD | Chrono mean rank | Nominal ROM success | Nominal ROM mean rank | Rate-limit TR (rate_rand_paper) success | Rate-limit TR mean rank | Noise-only TR (paper_tr) mean rank |',
      '|---|---:|---:|---:|---:|---:|---:|---:|---:|']
for p in sorted(pols, key=lambda p: ch['mean_rank'][p]):
    c = an['conditions']
    L.append(f"| {p} | {ch['success_rate']['id'][p]:.2f} | {ch['success_rate']['ood'][p]:.2f} | {ch['mean_rank'][p]:.2f} | "
             f"{c['nominal']['rom']['success_rate']['all'][p]:.2f} | {c['nominal']['rom']['mean_rank'][p]:.2f} | "
             f"{c['rate_rand_paper']['rom']['success_rate']['all'][p]:.2f} | {c['rate_rand_paper']['rom']['mean_rank'][p]:.2f} | "
             f"{c['paper_tr']['rom']['mean_rank'][p]:.2f} |")
(RESULTS / 'exploration_report.md').write_text('\n'.join(L) + '\n')
json.dump(res, open(RESULTS / 'exploration_tau_table.json', 'w'), indent=1)
print('\n'.join(L[:60]))