Download code/case2/report_confirm.py from harryzhang1018/TestRandomization: direct link, hf CLI and curl.
- Browser
- Download file 7.93 kB
-
https://huggingface.co/datasets/harryzhang1018/TestRandomization/resolve/main/code/case2/report_confirm.py
- Command line
-
hf download hf://datasets/harryzhang1018/TestRandomization/code/case2/report_confirm.py
-
curl -L -o report_confirm.py https://huggingface.co/datasets/harryzhang1018/TestRandomization/resolve/main/code/case2/report_confirm.py
7.93 kB
| """Write results/heldout_report.md from results/confirm_analysis.json (output of analyze_confirm.py). Sim2Sim.""" | |
| import json | |
| import sys | |
| import numpy as np | |
| import fixed_design as design | |
| from common import BASE, RESULTS | |
| # optional: analysis json, behavior json, output md (defaults = goal-set-B held-out files) | |
| args = sys.argv[1:] + [None] * 3 | |
| A = json.loads(open(args[0] or RESULTS / 'confirm_analysis.json').read()) | |
| beh = json.loads(open(args[1] or RESULTS / 'behavior_B_confirm16.json').read()) | |
| OUT_MD = args[2] or RESULTS / 'heldout_report.md' | |
| reg = json.loads((BASE / 'policies/registry.json').read_text()) | |
| f2 = lambda x: f'{x:.2f}' | |
| rng = lambda c: 'n/a' if c[0] is None else f'{c[0]:.2f} to {c[1]:.2f}' | |
| srng = lambda c: f'{c[0]:+.2f} to {c[1]:+.2f}' | |
| def spec_text(spec): | |
| if not spec: | |
| return 'none (training ROM)' | |
| out = [] | |
| for k, d in spec.items(): | |
| if d[0] == 'const': | |
| out.append(f'{k} = {d[1]:g}') | |
| elif d[0] == 'normal': | |
| out.append(f'{k} ~ N({d[1]:g}, {d[2]:g})') | |
| elif d[0] == 'choice': | |
| out.append(f'{k} in {{{", ".join(f"{x:g}" for x in d[1])}}}') | |
| else: | |
| out.append(f'{k} ~ {"LogU" if d[0] == "loguniform" else "U"}({d[1]:g}, {d[2]:g})') | |
| return '; '.join(out) | |
| L = ['# Case 2 held-out evaluation on goal set B (Sim2Sim)', '', | |
| 'Generated by `report_confirm.py` from `results/confirm_analysis.json` (output of `analyze_confirm.py`).', | |
| f"Goal set B: {A['goals_by_range']['id']} ID (10-20 m) + {A['goals_by_range']['ood']} OOD (20-40 m) goals, never used before the TR design was fixed.", | |
| 'Primary pool: 12 held-out PPO policies (seeds 2001-2004). Secondary pool: the 12 + released checkpoints 1-4.', | |
| "Condition 'paper_tr' is the noise-only TR (action and powertrain noise).", | |
| f"Bootstrap: {A['bootstrap']['replicates']} goal resamples, stratified by range, paired across methods. Ranges are 95 % percentile ranges.", '', | |
| f"**Primary test: delta tau = {A['primary_test']['delta_tau']:+.3f} (95 % range {srng(A['primary_test']['ci95'])}); met = {A['primary_test']['supported']}.**", ''] | |
| for pname in A['pools']: | |
| P = A['pools'][pname] | |
| L += [f"## Agreement with Chrono, {pname} pool ({len(P['policies'])} policies)", '', | |
| '| Condition | tau, all goals (95 % range) | Delta tau vs nominal (95 % range) | tau ID | tau OOD | Spearman | AUC for Chrono success < 0.5 (95 % range) | Resolved pairs | tau with primary TR order |', | |
| '|---|---|---|---:|---:|---:|---|---:|---:|'] | |
| for n, c in P['conditions'].items(): | |
| v = c['vs_chrono'] | |
| au = P['hidden_failure']['auc'][n] | |
| L.append(f"| {n}{' (primary)' if n == design.PRIMARY_TR else ''} | {f2(v['all']['kendall_tau_b'])} ({rng(v['all']['kendall_ci95'])}) | " | |
| f"{v['all']['delta_tau_vs_nominal']:+.2f} ({srng(v['all']['delta_tau_ci95'])}) | {f2(v['id']['kendall_tau_b'])} | {f2(v['ood']['kendall_tau_b'])} | " | |
| f"{f2(v['all']['spearman'])} | {f2(au['value'])} ({rng(au['ci95'])}) | {c['rom']['resolved_pairs']}/{len(c['rom']['pairs'])} | {f2(c['tau_vs_primary_tr']['value'])} |") | |
| ch = P['chrono'] | |
| L += ['', f"Chrono resolved pairs: {ch['resolved_pairs']}/{len(ch['pairs'])}. Chrono success < 0.5: {', '.join(P['hidden_failure']['policies']) or 'none'}.", ''] | |
| pa = P['conditions'][design.PRIMARY_TR]['pair_agreement_vs_nominal'] | |
| L += [f"Pairs ordered as Chrono orders them: primary TR {pa['method_correct']}/{pa['pairs']}, nominal ROM {pa['base_correct']}/{pa['pairs']}. " | |
| f"On the {pa['discordant']} pairs where the two disagree, Chrono supports the TR on {pa['discordant_method_correct']} and nominal ROM on {pa['discordant_base_correct']}.", ''] | |
| # per-policy table | |
| nom = P['conditions'][design.BASELINE]['rom'] | |
| tr = P['conditions'][design.PRIMARY_TR]['rom'] | |
| L += [f'### Per policy, {pname} pool (mean rank: 1 = best of {len(P["policies"])})', '', | |
| '| Policy | Training config | Seed | Mean step change of steering (nominal ROM) | Chrono success ID | Chrono success OOD | Chrono mean rank | Nominal ROM success ID / OOD | Nominal ROM mean rank | TR success ID / OOD | TR mean rank |', | |
| '|---|---|---:|---:|---:|---:|---:|---|---:|---|---:|'] | |
| for p in sorted(P['policies'], key=lambda p: ch['mean_rank'][p]): | |
| cfg = reg[p]['config'] if p in reg else 'released (one PPO run)' | |
| seed = reg[p]['seed'] if p in reg else '-' | |
| L.append(f"| {p} | {cfg} | {seed} | {beh[p]['mean_abs_steer_change']:.3f} | {f2(ch['success_rate']['id'][p])} | {f2(ch['success_rate']['ood'][p])} | " | |
| f"{ch['mean_rank'][p]:.2f} | {f2(nom['success_rate']['id'][p])} / {f2(nom['success_rate']['ood'][p])} | {nom['mean_rank'][p]:.2f} | " | |
| f"{f2(tr['success_rate']['id'][p])} / {f2(tr['success_rate']['ood'][p])} | {tr['mean_rank'][p]:.2f} |") | |
| L += ['', 'Order by mean rank:', '', | |
| f"- Chrono: {' > '.join(ch['order'])}", | |
| f"- Nominal ROM: {' > '.join(nom['order'])}", | |
| f"- Primary TR: {' > '.join(tr['order'])}", ''] | |
| rat = P['conditions'][design.BASELINE]['chrono_over_rom_time_ratio'] | |
| if rat: | |
| vals = np.array(list(rat.values())) | |
| L += [f"Gap magnitude: Chrono time / nominal ROM time on goals both reach = {vals.min():.2f} to {vals.max():.2f} (median {np.median(vals):.2f}) across policies.", ''] | |
| L += ['## Conditions and perturbation magnitudes', '', | |
| 'Units: action noise sd in normalized units (throttle range 0.2-0.5, steering range -1 to 1), per 0.1 s step; tau0 in N m; omega0 in rad/s;', | |
| 'steer_rate = largest change of normalized steering per 0.1 s step (Chrono loop: 0.1); delay and hold in 0.1 s steps; wheelbase in m.', '', | |
| '| Condition | Role | Perturbation (one draw per trial; noise each step) | Trials per goal |', '|---|---|---|---:|'] | |
| roles = {'nominal': 'baseline', design.PRIMARY_TR: 'primary TR', 'paper_tr': 'secondary (noise-only TR)'} | |
| for n, c in A['conditions_spec'].items(): | |
| L.append(f"| {n} | {roles.get(n, 'secondary')} | {spec_text(c['spec'])} | {c['trials']} |") | |
| PH = RESULTS / 'posthoc_confirm.json' | |
| if args[0] is None and PH.exists(): | |
| ph = json.loads(PH.read_text()) | |
| L += ['', '## Post hoc summaries (not part of the fixed primary test, no new simulation; `posthoc_confirm.py`)', ''] | |
| for pname, o in ph['pools'].items(): | |
| L += [f'### {pname} pool', '', '| Condition | tau(primary TR) - tau(condition) (95 % range) | Chrono-resolved pairs: same direction | opposite direction | unresolved |', | |
| '|---|---|---:|---:|---:|'] | |
| for n, v in o['pair_resolution_vs_chrono'].items(): | |
| d = o['delta_tau_primary_tr_minus'].get(n) | |
| dt = '-' if d is None else f"{d['value']:+.2f} ({srng(d['ci95'])})" | |
| L.append(f"| {n} | {dt} | {v['same_direction']}/{v['chrono_resolved']} | {v['opposite_direction']} | {v['unresolved']} |") | |
| c = o['chatter_vs_chrono_success'] | |
| L += ['', f"Steering chatter (mean step change in nominal ROM) versus Chrono success, Spearman across policies: " | |
| f"ID {c['id']['spearman']:+.2f} (p = {c['id']['p_value']:.3f}), OOD {c['ood']['spearman']:+.2f} (p = {c['ood']['p_value']:.3f}), " | |
| f"all {c['all']['spearman']:+.2f} (p = {c['all']['p_value']:.3f}).", ''] | |
| sec = A['pools'][list(A['pools'])[-1]] | |
| csr = sec['chrono']['success_rate']['all'] | |
| low = ', '.join(f'{p} at {csr[p]:.2f}' for p in sorted(sec['policies'], key=lambda p: csr[p])[:2]) | |
| L += ['## Notes', '', | |
| '- Hidden-failure screening (Chrono success < 0.5) is not evaluable on set B: no policy had Chrono success below 0.5 ' | |
| f'(lowest: {low}).', | |
| '- `report_confirm.py` and `posthoc_confirm.py` only format or summarize the outputs of `analyze_confirm.py`; they run no simulation.'] | |
| open(OUT_MD, 'w').write('\n'.join(L) + '\n') | |
| print('\n'.join(L)) | |