File size: 14,378 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
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
250
251
252
253
254
255
256
"""Case 1 (ART) analysis under the per-start rank rule: Tables I, IV and V, sensitivity, physical pair tests.

TR logs (Chrono digital twin): B01 (S2, 400 starts, logged 40 s), B06 (S0/S1/S3/S4, 200 starts each), B07 (S2 starts
with the channel conditions D1a-D5, 200 starts each); per-start metrics from the extract stage. Physical reference
(Sim2Real): physical_runs.csv, mean of the per-run MAEs (5 runs per path and controller). NN-HD column of the TR
order: ctrl_label nnhdx175 for Path 1-2 targets and nnhdx150 for Path 3 targets. Baseline orders (nominal
simulation, Monte Carlo RF-A/RF-B, nominal simulation of Tables II-III) from baseline_orders.json.

Usage: python case1_rank_analysis.py <per_start_dir> <physical_runs.csv> <baseline_orders.json> <out_dir>
"""
import csv, glob, gzip, itertools, json, math, sys
import numpy as np

PER_START, PHYS_CSV, BASE_JSON, OUT = sys.argv[1:5]
RNG = np.random.default_rng(20261105)
B = 2000
BASE = ('mpc', 'nnmpc', 'pid')
LBL = {'mpc': 'MPC', 'nnmpc': 'NN-MPC', 'pid': 'PID', 'nnhd': 'NN-HD'}
ITEMS = ('mpc', 'nnmpc', 'pid', 'nnhd')
TARGETS = ('P1_lateral', 'P1_heading', 'P2_lateral', 'P2_heading', 'P3_lateral', 'P3_heading')
GAIN = {'P1': 'nnhdx175', 'P2': 'nnhdx175', 'P3': 'nnhdx150'}


def load(batch, col_fn):
    """scenario key -> {ctrl_label: row}"""
    d = {}
    for f in glob.glob(f'{PER_START}/{batch}/recovery_part*.csv.gz'):
        for r in csv.DictReader(gzip.open(f, 'rt')):
            d.setdefault((r['tag_family'], r['tag_condition'], r['scenario_id']), {})[r['ctrl_label']] = r
    return d


B01, B06, B07 = load('B01_main_tr', None), load('B06_severity_shape', None), load('B07_dist_recovery', None)


def times(d, fam, cond, L='L010', Hd='H010', H=25.0, gain='nnhdx175', ids=None):
    """N x 4 array of first tube-entry times (capped at H), columns ITEMS; NN-HD column uses `gain`."""
    col = f'T{25 if H <= 25 else 40}_trk100_{L}{Hd}_first'
    rows, keys = [], []
    for (f, c, sid), v in sorted(d.items()):
        if f != fam or c != cond or not all(k in v for k in BASE + (gain,)):
            continue
        if ids is not None and sid not in ids:
            continue
        rows.append([min(float(v[k][col]), H) for k in BASE + (gain,)]); keys.append(sid)
    return np.array(rows), keys


def ranks(T):
    """per-start ranks with shared ties (1 = fastest)"""
    less = (T[:, None, :] < T[:, :, None]).sum(2)
    eq = (T[:, None, :] == T[:, :, None]).sum(2) - 1
    return 1 + less + eq / 2.0


def order_of(score):  # ITEMS sorted by ascending score
    return [ITEMS[i] for i in np.argsort(score, kind='stable')]


def tau(a, b):
    pa = {c: i for i, c in enumerate(a)}; pb = {c: i for i, c in enumerate(b)}
    s = sum(np.sign((pa[x] - pa[y]) * (pb[x] - pb[y])) for x, y in itertools.combinations(ITEMS, 2))
    return s / 6.0


def summary(T, H):
    R = ranks(T); n = len(T)
    fail = (T >= H)
    ok = ~fail.any(1)
    rank_pct = {}
    for j, c in enumerate(ITEMS):
        cnt = np.zeros(4)
        for row_t in T:
            lo = 1 + (row_t < row_t[j]).sum(); k = (row_t == row_t[j]).sum()
            cnt[lo - 1:lo - 1 + k] += 1.0 / k
        rank_pct[LBL[c]] = [round(100 * x / n, 1) for x in cnt]
    win = {}
    for i, j in itertools.combinations(range(4), 2):
        w = (T[:, i] < T[:, j]) + 0.5 * (T[:, i] == T[:, j])
        bs = [w[RNG.integers(0, n, n)].mean() for _ in range(B)]
        win[f'{LBL[ITEMS[i]]} beats {LBL[ITEMS[j]]}'] = [round(w.mean(), 3), [round(float(np.percentile(bs, 2.5)), 3), round(float(np.percentile(bs, 97.5)), 3)]]
    return {'n': n, 'order': [LBL[c] for c in order_of(R.mean(0))],
            'mean_rank': {LBL[c]: round(float(R.mean(0)[j]), 2) for j, c in enumerate(ITEMS)},
            'rank_pct': rank_pct,
            'fail_pct': {LBL[c]: round(100 * float(fail[:, j].mean()), 1) for j, c in enumerate(ITEMS)},
            'n_all_recover': int(ok.sum()),
            'mean_st_all_recover': {LBL[c]: round(float(T[ok, j].mean()), 2) for j, c in enumerate(ITEMS)},
            'pairwise_win_rate_ci95': win}


# ---------------- physical reference ----------------
phys = {}
for r in csv.DictReader(open(PHYS_CSV)):
    c = {'MPC': 'mpc', 'NN-MPC': 'nnmpc', 'PID': 'pid', 'NN-HD': 'nnhd'}[r['controller']]
    phys.setdefault(f"{r['path']}_lateral", {}).setdefault(c, []).append(float(r['run_mae_lateral_m']))
    phys.setdefault(f"{r['path']}_heading", {}).setdefault(c, []).append(float(r['run_mae_heading_rad']))
phys = {t: {c: np.array(v) for c, v in phys[t].items()} for t in TARGETS}
phys_order = {t: order_of(np.array([phys[t][c].mean() for c in ITEMS])) for t in TARGETS}


def phys_boot():
    return {t: order_of(np.array([RNG.choice(phys[t][c], len(phys[t][c])).mean() for c in ITEMS])) for t in TARGETS}


def perm_p(a, b):  # exact two-sided permutation test on the difference of means
    x = np.concatenate([a, b]); n = len(a); obs = abs(a.mean() - b.mean()); cnt = tot = 0
    for idx in itertools.combinations(range(len(x)), n):
        m = np.zeros(len(x), bool); m[list(idx)] = True
        cnt += abs(x[m].mean() - x[~m].mean()) >= obs - 1e-12; tot += 1
    return cnt / tot


phys_tests = {}
for t in TARGETS:
    rows = []
    for a, b in itertools.combinations(ITEMS, 2):
        rows.append({'pair': f'{LBL[a]} vs {LBL[b]}', 'mean_a': round(float(phys[t][a].mean()), 4),
                     'mean_b': round(float(phys[t][b].mean()), 4), 'p_perm': round(perm_p(phys[t][a], phys[t][b]), 4)})
    ps = sorted(range(len(rows)), key=lambda i: rows[i]['p_perm']); run = 0.0
    for k, i in enumerate(ps):  # Holm step-down adjustment across the 6 pairs of this target
        run = max(run, min(1.0, (len(rows) - k) * rows[i]['p_perm'])); rows[i]['p_holm'] = round(run, 4)
    phys_tests[t] = rows

# ---------------- methods: TR (rank rule) and baselines ----------------
TS2 = {g: times(B01, 'S2', 'none', H=25.0, gain=g)[0] for g in ('nnhdx175', 'nnhdx150')}
RS2 = {g: ranks(T) for g, T in TS2.items()}
tr_order = {t: order_of(RS2[GAIN[t[:2]]].mean(0)) for t in TARGETS}
base = json.load(open(BASE_JSON))
methods = {'TR (rank rule, S2)': tr_order}
for m, name in (('M-NOM', 'Nominal simulation'), ('NOM-archived-2024', 'Nominal simulation (2024 archive)'),
                ('RF-A', 'Monte Carlo, start jitter (RF-A)'), ('RF-B', 'Monte Carlo, jitter + disturbances (RF-B)')):
    methods[name] = {t: base[m][t]['predicted_ordering'] for t in TARGETS}

boot_phys = [phys_boot() for _ in range(B)]
n = len(RS2['nnhdx175'])
boot_tr = []
for _ in range(B):
    idx = RNG.integers(0, n, n)
    boot_tr.append({t: order_of(RS2[GAIN[t[:2]]][idx].mean(0)) for t in TARGETS})


def ci(v):
    return [round(float(np.percentile(v, 2.5)), 2), round(float(np.percentile(v, 97.5)), 2)]


compare = {}
for name, ords in methods.items():
    taus = {t: tau(ords[t], phys_order[t]) for t in TARGETS}
    bt = {t: [tau((boot_tr[b][t] if name.startswith('TR') else ords[t]), boot_phys[b][t]) for b in range(B)] for t in TARGETS}
    bmean = [np.mean([bt[t][b] for t in TARGETS]) for b in range(B)]
    sel = {t: ords[t][0] for t in TARGETS}
    regret = {t: round(float(phys[t][sel[t]].mean() / min(phys[t][c].mean() for c in ITEMS)), 2) for t in TARGETS}
    # concordance on physically resolved pairs (Holm-adjusted permutation p < 0.05)
    conc = tot = 0
    for t in TARGETS:
        for r_ in phys_tests[t]:
            if r_['p_holm'] < 0.05:
                a, b = (next(k for k in ITEMS if LBL[k] == s) for s in r_['pair'].split(' vs '))
                pa = ords[t].index(a) < ords[t].index(b); pp = phys_order[t].index(a) < phys_order[t].index(b)
                conc += pa == pp; tot += 1
    compare[name] = {'order': {t: [LBL[c] for c in ords[t]] for t in TARGETS},
                     'tau': {t: round(taus[t], 2) for t in TARGETS}, 'tau_ci95': {t: ci(bt[t]) for t in TARGETS},
                     'mean_tau': round(float(np.mean(list(taus.values()))), 2), 'mean_tau_ci95': ci(bmean),
                     'exact_order_matches': int(sum(v == 1 for v in taus.values())),
                     'best_selected': int(sum(sel[t] == phys_order[t][0] for t in TARGETS)),
                     'selected_error_ratio_to_best': regret,
                     'resolved_pairs_correct': [conc, tot]}
# paired difference TR - nominal in mean tau
bt_tr = [np.mean([tau(boot_tr[b][t], boot_phys[b][t]) for t in TARGETS]) for b in range(B)]
bt_nom = [np.mean([tau(methods['Nominal simulation'][t], boot_phys[b][t]) for t in TARGETS]) for b in range(B)]
d = np.array(bt_tr) - np.array(bt_nom)
compare_delta = {'TR minus nominal, mean tau': round(compare['TR (rank rule, S2)']['mean_tau'] - compare['Nominal simulation']['mean_tau'], 2),
                 'ci95': ci(d)}
# same for the nominal simulation of Tables II-III (the paper's nominal baseline; no new random draws)
NOM_T = 'Nominal simulation (2024 archive)'
bt_nom_t = [np.mean([tau(methods[NOM_T][t], boot_phys[b][t]) for t in TARGETS]) for b in range(B)]
d_t = np.array(bt_tr) - np.array(bt_nom_t)
pt_t = np.mean([tau(tr_order[t], phys_order[t]) for t in TARGETS]) - np.mean([tau(methods[NOM_T][t], phys_order[t]) for t in TARGETS])
compare_delta_tables = {'TR minus nominal (Tables II-III), mean tau': round(float(pt_t), 2), 'ci95': ci(d_t),
                        'min': round(float(d_t.min()), 2), 'share_of_replicates_gt_0': float(np.mean(d_t > 0))}


def mean_tau(R_by_gain):
    return round(float(np.mean([tau(order_of(R_by_gain[GAIN[t[:2]]].mean(0)), phys_order[t]) for t in TARGETS])), 2)


# ---------------- Table I offset sweep ----------------
sweep = []
for fam, d_, H in (('S0', B06, 25.0), ('S1', B06, 25.0), ('S2', B01, 25.0), ('S3', B06, 25.0), ('S4', B06, 25.0)):
    T = {g: times(d_, fam, 'none', H=H, gain=g)[0] for g in ('nnhdx175', 'nnhdx150')}
    s = summary(T['nnhdx175'], H); s['range'] = fam
    s['mean_tau_vs_physical'] = mean_tau({g: ranks(v) for g, v in T.items()})
    sweep.append(s)

# ---------------- tube and horizon sensitivity (S2) ----------------
tube = []
for L in ('L005', 'L010', 'L020'):
    for Hd in ('H005', 'H010', 'H020'):
        for H in (15.0, 25.0, 40.0):
            T = {g: times(B01, 'S2', 'none', L, Hd, H, g)[0] for g in ('nnhdx175', 'nnhdx150')}
            R = ranks(T['nnhdx175'])
            tube.append({'tube_lat_m': int(L[1:]) / 100, 'tube_head_rad': int(Hd[1:]) / 100, 'H_s': H,
                         'order': [LBL[c] for c in order_of(R.mean(0))],
                         'mpc_first_pct': round(100 * float((R[:, 0] == 1).mean()), 1),
                         'fail_pct': {LBL[c]: round(100 * float((T['nnhdx175'][:, j] >= H).mean()), 1) for j, c in enumerate(ITEMS)},
                         'mean_tau_vs_physical': mean_tau({g: ranks(v) for g, v in T.items()})})

# ---------------- number of trials ----------------
R = RS2['nnhdx175']; full = order_of(R.mean(0)); nsens = []
for N in (10, 25, 50, 100, 200, 400):
    same = top = 0
    for _ in range(B):
        idx = RNG.choice(n, N, replace=False); o = order_of(R[idx].mean(0))
        same += o == full; top += o[0] == 'mpc'
    nsens.append({'N': N, 'p_same_order_as_400': round(same / B, 3), 'p_mpc_first': round(top / B, 3)})
mr = np.sort(R.mean(0)); gap = float(np.min(np.diff(mr)))
hoeff = {'loss': 'per-start rank, bounded in [1, 4] (B = 3)', 'K': 4, 'alpha': 0.05,
         'smallest_adjacent_mean_rank_gap_at_N400': round(gap, 3),
         'n_bound': int(math.ceil(2 * 9 / gap ** 2 * math.log(2 * 4 / 0.05)))}

# ---------------- ablation by channel (B07, CRN starts of B01) ----------------
CH = {'D1a': 'actuation: +0.10 s delay', 'D1b': 'actuation: +0.20 s delay', 'D2a': 'actuation: steering bias 0.013',
      'D2b': 'actuation: steering bias 0.026', 'D3a': 'observation: pose noise 0.02 m / 0.01 rad',
      'D3b': 'observation: pose noise 0.05 m / 0.03 rad', 'D4a': 'plant: friction 0.6', 'D4b': 'plant: friction 0.4',
      'D5': 'combined D1a + D2a + D3a'}
abl = []
ids = None
for cond, desc in CH.items():
    T = {g: times(B07, 'S2', cond, H=25.0, gain=g) for g in ('nnhdx175', 'nnhdx150')}
    keys = {k.split('_', 1)[1] for k in T['nnhdx175'][1]}
    T0 = {g: times(B01, 'S2', 'none', H=25.0, gain=g, ids=keys)[0] for g in ('nnhdx175', 'nnhdx150')}
    s = summary(T['nnhdx175'][0], 25.0)
    abl.append({'condition': cond, 'channel': desc, 'n': s['n'], 'order': s['order'], 'mean_rank': s['mean_rank'],
                'fail_pct': s['fail_pct'], 'mpc_first_pct': s['rank_pct']['MPC'][0],
                'mean_tau_vs_physical': mean_tau({g: ranks(v[0]) for g, v in T.items()}),
                'same_starts_no_disturbance': {'order': [LBL[c] for c in order_of(ranks(T0['nnhdx175']).mean(0))],
                                               'mean_tau_vs_physical': mean_tau({g: ranks(v) for g, v in T0.items()})}})

# MPC failures by start pose: see mpc_failures/d3_range.py (all 29 divergences start beyond the cost ridge).
res = {'label': 'Case 1 analysis. TR rows: Chrono digital-twin recovery tests; physical reference: archived physical runs (Sim2Real). Rule: per-start rank.',
       'physical_order': {t: [LBL[c] for c in o] for t, o in phys_order.items()},
       'physical_pairwise_tests': phys_tests, 'method_comparison': compare, 'tr_minus_nominal': compare_delta, 'tr_minus_nominal_tables_II_III': compare_delta_tables,
       'offset_sweep': sweep, 'tube_horizon_sensitivity': tube, 'trial_number_sensitivity': nsens,
       'hoeffding': hoeff, 'ablation_by_channel': abl, 'bootstrap_B': B}
json.dump(res, open(f'{OUT}/case1_rank_analysis.json', 'w'), indent=1)
print(json.dumps({k: res[k] for k in ('physical_order', 'tr_minus_nominal', 'tr_minus_nominal_tables_II_III', 'hoeffding')}, indent=1))
for name, v in compare.items():
    print(name, v['mean_tau'], v['mean_tau_ci95'], 'exact', v['exact_order_matches'], 'best', v['best_selected'], 'pairs', v['resolved_pairs_correct'], v['selected_error_ratio_to_best'])
for s in sweep:
    print(s['range'], s['n'], '>'.join(s['order']), 'fail', s['fail_pct'], 'tau', s['mean_tau_vs_physical'], 'MPC1st', s['rank_pct']['MPC'][0])
for s in tube:
    print(s['tube_lat_m'], s['tube_head_rad'], s['H_s'], '>'.join(s['order']), s['mpc_first_pct'], s['mean_tau_vs_physical'])
print(nsens)
for a in abl:
    print(a['condition'], a['channel'], '>'.join(a['order']), a['mpc_first_pct'], a['fail_pct'], a['mean_tau_vs_physical'], a['same_starts_no_disturbance'])