Download code/case2/analyze.py from harryzhang1018/TestRandomization: direct link, hf CLI and curl.
- Browser
- Download file 5.18 kB
-
https://huggingface.co/datasets/harryzhang1018/TestRandomization/resolve/main/code/case2/analyze.py
- Command line
-
hf download hf://datasets/harryzhang1018/TestRandomization/code/case2/analyze.py
-
curl -L -o analyze.py https://huggingface.co/datasets/harryzhang1018/TestRandomization/resolve/main/code/case2/analyze.py
5.18 kB
| """Compare ROM conditions (nominal, TR variants) with Chrono truth on one goal set and pool. Sim2Sim. | |
| Usage: python analyze.py --set A --pool explore [--variants all] [--boot 2000] [--label exploratory] | |
| Reads results/rom_<set>_<pool>/<variant>.npz and results/chrono_<set>_<pool>/episodes.jsonl. | |
| Writes results/analysis_<set>_<pool>.json. | |
| """ | |
| import argparse | |
| import json | |
| import numpy as np | |
| import rankstats as rs | |
| from common import RESULTS, HORIZON_S | |
| def load_rom(set_name, pool, variant): | |
| d = np.load(RESULTS / f'rom_{set_name}_{pool}' / f'{variant}.npz') | |
| T = rs.bounded(d['time_s'].astype(np.float64), d['success']) | |
| return list(d['policies']), list(d['goal_ids']), T, d['success'] | |
| def load_chrono(set_name, pool, policies, goal_ids): | |
| rows = [json.loads(l) for l in open(RESULTS / f'chrono_{set_name}_{pool}' / 'episodes.jsonl')] | |
| errors = [r for r in rows if r.get('status') == 'runtime_error'] | |
| if errors: | |
| raise RuntimeError(f'{len(errors)} Chrono runtime errors; rerun before analysis') | |
| look = {(r['policy'], r['goal_id']): r for r in rows} | |
| missing = [(p, g) for p in policies for g in goal_ids if (p, g) not in look] | |
| if missing: | |
| raise RuntimeError(f'{len(missing)} Chrono episodes missing, first {missing[:3]}') | |
| S = np.array([[look[(p, g)]['success'] for g in goal_ids] for p in policies])[:, :, None] | |
| t = 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)[:, :, None] | |
| # Chrono times are control-step times; round to 0.1 s so that float noise does not break ties | |
| t = np.round(t, 1) | |
| return rs.bounded(t, S), S | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument('--set', required=True) | |
| ap.add_argument('--pool', required=True) | |
| ap.add_argument('--variants', default='all') | |
| ap.add_argument('--boot', type=int, default=2000) | |
| ap.add_argument('--label', default='exploratory') | |
| ap.add_argument('--baseline', default='nominal') | |
| a = ap.parse_args() | |
| rom_dir = RESULTS / f'rom_{a.set}_{a.pool}' | |
| names = sorted(p.stem for p in rom_dir.glob('*.npz')) if a.variants == 'all' else a.variants.split(',') | |
| goals = json.loads((rom_dir / 'goals.json').read_text()) | |
| goal_ids = [g['goal_id'] for g in goals] | |
| grange = np.array([g['goal_range'] for g in goals]) | |
| policies, gids, _, _ = load_rom(a.set, a.pool, a.baseline) | |
| assert gids == goal_ids | |
| Tc, Sc = load_chrono(a.set, a.pool, policies, goal_ids) | |
| boot = rs.boot_indices(grange, a.boot, seed=20261104) | |
| out = dict(label=a.label, sim2sim=True, goal_set=a.set, pool=a.pool, policies=policies, goals=len(goal_ids), | |
| horizon_s=HORIZON_S, bootstrap=dict(replicates=a.boot, seed=20261104, unit='goal, stratified by goal range, paired across methods'), | |
| chrono=rs.summarize_method(Tc, Sc, policies, grange, boot), conditions={}) | |
| Rc = rs.per_goal_ranks(Tc) | |
| subsets = {'all': np.arange(len(goal_ids)), 'id': np.flatnonzero(grange == 'id'), 'ood': np.flatnonzero(grange == 'ood')} | |
| Rm = {} | |
| for n in names: | |
| pol, gi, T, S = load_rom(a.set, a.pool, n) | |
| assert pol == policies and gi == goal_ids | |
| Rm[n] = rs.per_goal_ranks(T) | |
| out['conditions'][n] = dict(rom=rs.summarize_method(T, S, policies, grange, boot)) | |
| for sub, idx in subsets.items(): | |
| b_rel = boot if sub == 'all' else rs.boot_indices(grange[idx], a.boot, seed=20261104 + len(sub)) # indices into idx | |
| res, taus = rs.compare_to_truth({n: Rm[n][:, idx] for n in names}, Rc[:, idx], b_rel) | |
| for n in names: | |
| c = out['conditions'][n] | |
| c.setdefault('vs_chrono', {})[sub] = res[n] | |
| if a.baseline in taus: | |
| d = taus[n] - taus[a.baseline] | |
| c['vs_chrono'][sub]['delta_tau_vs_baseline'] = float(res[n]['kendall_tau_b'] - res[a.baseline]['kendall_tau_b']) | |
| c['vs_chrono'][sub]['delta_tau_ci95'] = rs.ci(d) | |
| c['vs_chrono'][sub]['p_delta_le_0'] = float(np.mean(d[np.isfinite(d)] <= 0)) | |
| if sub == 'all': | |
| c['pair_agreement_vs_baseline'] = rs.pair_agreement(Rm[n], Rm[a.baseline], Rc, policies) | |
| path = RESULTS / f'analysis_{a.set}_{a.pool}.json' | |
| path.write_text(json.dumps(out, indent=1) + '\n') | |
| # console table | |
| print(f"{'condition':18s} {'tau_all':>8s} {'CI95':>16s} {'dtau':>7s} {'dCI95':>16s} {'tau_ID':>7s} {'tau_OOD':>7s} pairs ok/disc") | |
| for n in sorted(names, key=lambda n: -out['conditions'][n]['vs_chrono']['all']['kendall_tau_b']): | |
| v = out['conditions'][n]['vs_chrono'] | |
| pa = out['conditions'][n]['pair_agreement_vs_baseline'] | |
| print(f"{n:18s} {v['all']['kendall_tau_b']:8.3f} {str([round(x, 3) for x in v['all']['kendall_ci95']]):>16s} " | |
| f"{v['all'].get('delta_tau_vs_baseline', 0):7.3f} {str([round(x, 3) for x in v['all'].get('delta_tau_ci95', [0, 0])]):>16s} " | |
| f"{v['id']['kendall_tau_b']:7.3f} {v['ood']['kendall_tau_b']:7.3f} {pa['method_correct']}/{pa['pairs']} disc {pa['discordant_method_correct']}:{pa['discordant_base_correct']}") | |
| if __name__ == '__main__': | |
| main() | |