"""Held-out analysis on goal set B (Sim2Sim). Fixed together with the TR design (fixed_design.py) before any held-out run. Usage: python analyze_confirm.py --set B --rom-dir results/rom_B_confirm16 --chrono-dir results/chrono_B_confirm16 --primary confirm --secondary confirm16 --out results/confirm_analysis.json [--label held-out] (--set A with set-A directories of the fixed-design conditions runs the same code on exploration data.) Primary test: on the primary pool (12 held-out policies), delta tau = tau_b(PRIMARY_TR, Chrono) - tau_b(nominal ROM, Chrono) > 0, with the lower end of the 95 % paired goal-bootstrap interval > 0 (5000 replicates, stratified by goal range). Everything else is secondary and is reported whatever the result. """ import argparse import json import numpy as np import fixed_design as design import rankstats as rs from common import HORIZON_S from run_rom import POOLS B_REPS, B_SEED = 5000, 20261105 def load_rom(rom_dir, name): d = np.load(f'{rom_dir}/{name}.npz') return list(d['policies']), list(d['goal_ids']), rs.bounded(d['time_s'].astype(np.float64), d['success']), d['success'], d['time_s'] def load_chrono(chrono_dir, policies, goal_ids): rows = [json.loads(l) for l in open(f'{chrono_dir}/episodes.jsonl')] if any(r.get('status') == 'runtime_error' for r in rows): raise RuntimeError('Chrono runtime errors present') look = {(r['policy'], r['goal_id']): r for r in rows} miss = [(p, g) for p in policies for g in goal_ids if (p, g) not in look] if miss: raise RuntimeError(f'{len(miss)} Chrono episodes missing') S = np.array([[look[(p, g)]['success'] for g in goal_ids] for p in policies])[:, :, None] t = np.round(np.array([[look[(p, g)]['time_s'] if look[(p, g)]['success'] else np.nan for g in goal_ids] for p in policies], dtype=np.float64), 1)[:, :, None] return rs.bounded(t, S), S, t def auc(score_bad_high, label): """Probability that a random positive (label 1) has a higher score than a random negative; ties 0.5.""" pos, neg = score_bad_high[..., label == 1], score_bad_high[..., label == 0] if pos.shape[-1] == 0 or neg.shape[-1] == 0: return np.full(score_bad_high.shape[:-1], np.nan) gt = (pos[..., :, None] > neg[..., None, :]).mean((-1, -2)) eq = (pos[..., :, None] == neg[..., None, :]).mean((-1, -2)) return gt + 0.5 * eq def analyze_pool(pool, all_pols, rom, chrono, grange, boot, sub_boot): idx = [all_pols.index(p) for p in pool] Tc, Sc, tc = (x[idx] for x in chrono) out = dict(policies=pool, chrono=rs.summarize_method(Tc, Sc, pool, grange, boot), conditions={}) Rc = rs.per_goal_ranks(Tc) R = {} for n, (T, S, t) in rom.items(): T, S, t = T[idx], S[idx], t[idx] R[n] = rs.per_goal_ranks(T) c = dict(rom=rs.summarize_method(T, S, pool, grange, boot)) # gap magnitude: mean successful time ROM vs Chrono on units where both succeed (per policy) both = S.all(2) & Sc[:, :, 0] ratio = {} for i, p in enumerate(pool): if both[i].any(): ratio[p] = float(np.nanmean(tc[i, both[i], 0]) / np.nanmean(np.where(S[i, both[i]], t[i, both[i]], np.nan))) c['chrono_over_rom_time_ratio'] = ratio out['conditions'][n] = c subsets = {'all': np.arange(len(grange)), 'id': np.flatnonzero(grange == 'id'), 'ood': np.flatnonzero(grange == 'ood')} for sub, gi in subsets.items(): b = boot if sub == 'all' else sub_boot[sub] res, taus = rs.compare_to_truth({n: R[n][:, gi] for n in R}, Rc[:, gi], b) for n in R: v = res[n] d = taus[n] - taus[design.BASELINE] v['delta_tau_vs_nominal'] = v['kendall_tau_b'] - res[design.BASELINE]['kendall_tau_b'] v['delta_tau_ci95'] = rs.ci(d) v['bootstrap_frac_delta_le_0'] = float(np.mean(d[np.isfinite(d)] <= 0)) out['conditions'][n].setdefault('vs_chrono', {})[sub] = v for n in R: out['conditions'][n]['pair_agreement_vs_nominal'] = rs.pair_agreement(R[n], R[design.BASELINE], Rc, pool) # sensitivity: agreement of each condition's order with the primary TR order prim = R[design.PRIMARY_TR] for n in R: tb = rs.kendall_tau_b(R[n][:, boot].mean(2).T, prim[:, boot].mean(2).T) out['conditions'][n]['tau_vs_primary_tr'] = dict(value=float(rs.kendall_tau_b(R[n].mean(1), prim.mean(1))), ci95=rs.ci(tb)) # hidden-failure screening: Chrono success < 0.5 on this goal set csr = Sc[:, :, 0].mean(1) label = (csr < 0.5).astype(int) out['hidden_failure'] = dict(definition='Chrono success rate < 0.5 on this goal set; score = mean rank (higher = worse)', policies=[p for p, l in zip(pool, label) if l], nominal_success_of_these={p: out['conditions'][design.BASELINE]['rom']['success_rate']['all'][p] for p, l in zip(pool, label) if l}, auc={}) for n in R: mr_b = R[n][:, boot].mean(2).T out['hidden_failure']['auc'][n] = dict(value=float(auc(R[n].mean(1), label)), ci95=rs.ci(auc(mr_b, label))) return out def main(): ap = argparse.ArgumentParser() ap.add_argument('--set', required=True) ap.add_argument('--rom-dir', required=True) ap.add_argument('--chrono-dir', required=True) ap.add_argument('--primary', required=True, help='pool name in run_rom.POOLS, or comma list') ap.add_argument('--secondary', default='') ap.add_argument('--out', required=True) ap.add_argument('--label', default='held-out') a = ap.parse_args() goals = json.load(open(f'{a.rom_dir}/goals.json')) gids = [g['goal_id'] for g in goals] grange = np.array([g['goal_range'] for g in goals]) pools = {'primary': POOLS.get(a.primary, a.primary.split(','))} if a.secondary: pools['secondary'] = POOLS.get(a.secondary, a.secondary.split(',')) rom = {} all_pols = None for n in design.CONDITIONS: pols, gi, T, S, t = load_rom(a.rom_dir, n) assert gi == gids and (all_pols is None or pols == all_pols) all_pols = pols rom[n] = (T, S, t.astype(np.float64)) chrono = load_chrono(a.chrono_dir, all_pols, gids) boot = rs.boot_indices(grange, B_REPS, B_SEED) sub_boot = {s: rs.boot_indices(grange[grange == s], B_REPS, B_SEED + i + 1) for i, s in enumerate(['id', 'ood'])} out = dict(label=a.label, sim2sim=True, goal_set=a.set, goals=len(gids), goals_by_range={s: int((grange == s).sum()) for s in ['id', 'ood']}, horizon_s=HORIZON_S, primary_tr=design.PRIMARY_TR, baseline=design.BASELINE, conditions_spec={n: dict(trials=k, spec={p: list(v) for p, v in s.items()}) for n, (k, s) in design.CONDITIONS.items()}, bootstrap=dict(replicates=B_REPS, seed=B_SEED, unit='goal, stratified by range, paired across methods'), pools={}) for name, pool in pools.items(): out['pools'][name] = analyze_pool(pool, all_pols, rom, chrono, grange, boot, sub_boot) v = out['pools']['primary']['conditions'][design.PRIMARY_TR]['vs_chrono']['all'] out['primary_test'] = dict(statement='delta tau_b (primary TR minus nominal ROM, vs Chrono) > 0 with 95 % CI lower end > 0, primary pool, all goals', delta_tau=v['delta_tau_vs_nominal'], ci95=v['delta_tau_ci95'], supported=bool(v['delta_tau_ci95'][0] > 0)) json.dump(out, open(a.out, 'w'), indent=1) for name, P in out['pools'].items(): print(f'== pool {name} ({len(P["policies"])} policies), goal set {a.set}, {a.label}') print(f"{'condition':16s} {'tau':>6s} {'CI95':>15s} {'dtau':>6s} {'dCI95':>16s} {'tauID':>6s} {'tauOOD':>6s} {'AUC':>5s} {'res':>4s} {'vsTR':>5s}") for n, c in P['conditions'].items(): vv = c['vs_chrono'] print(f"{n:16s} {vv['all']['kendall_tau_b']:6.3f} {str(np.round(vv['all']['kendall_ci95'], 3)):>15s} {vv['all']['delta_tau_vs_nominal']:+6.3f} " f"{str(np.round(vv['all']['delta_tau_ci95'], 3)):>16s} {vv['id']['kendall_tau_b']:6.3f} {vv['ood']['kendall_tau_b']:6.3f} " f"{P['hidden_failure']['auc'][n]['value']:5.2f} {c['rom']['resolved_pairs']:4d} {c['tau_vs_primary_tr']['value']:5.2f}") print('Chrono resolved pairs', P['chrono']['resolved_pairs'], 'of', len(P['chrono']['pairs']), '| hidden failures', P['hidden_failure']['policies']) print('primary test', out['primary_test']) if __name__ == '__main__': main()