Download code/case1/analysis/baseline_orders.py from harryzhang1018/TestRandomization: direct link, hf CLI and curl.
- Browser
- Download file 5.85 kB
-
https://huggingface.co/datasets/harryzhang1018/TestRandomization/resolve/main/code/case1/analysis/baseline_orders.py
- Command line
-
hf download hf://datasets/harryzhang1018/TestRandomization/code/case1/analysis/baseline_orders.py
-
curl -L -o baseline_orders.py https://huggingface.co/datasets/harryzhang1018/TestRandomization/resolve/main/code/case1/analysis/baseline_orders.py
5.85 kB
| #!/usr/bin/env python3 | |
| """Case 1 baseline orders for Table IV: nominal simulation and Monte Carlo evaluation on the deployment paths. | |
| For each path P1-P3 and metric (lateral, heading) a baseline predicts the controller order by ascending run MAE: | |
| * M-NOM: one nominal Chrono run per path and controller (batch B03, tag nominal_role = primary, controller phase 0); | |
| * NOM-archived-2024: the nominal simulation logs of Tables II-III (physical/physical_runs.py -> nominal_sim_runs.csv); | |
| * RF-A: Monte Carlo, start pose jittered within the spread of the physical starts, random controller phase, | |
| 20 runs per path and controller (batch B04); score = mean run MAE over the 20 runs; | |
| * RF-B: as RF-A plus actuation delay 0.10 s, steering bias 0.013 and pose noise 0.02 m / 0.01 rad (batch B05). | |
| Runs of the Monte Carlo batches are paired by scenario_id; a scenario that lacks a controller (or has a non-finite | |
| MAE) is dropped for every controller. NN-HD column: ctrl_label nnhdx175 for P1/P2, nnhdx150 for P3. Order ties keep | |
| the label order MPC, NN-MPC, PID, NN-HD (stable sort). | |
| Usage: python baseline_orders.py PER_START_DIR NOMINAL_SIM_RUNS_CSV OUT_JSON | |
| PER_START_DIR contains B03_nominal/, B04_rf_a/, B05_rf_b/ with fullpath_part*.csv.gz (extract stage). | |
| """ | |
| import csv | |
| import glob | |
| import gzip | |
| import json | |
| import os | |
| import sys | |
| import numpy as np | |
| csv.field_size_limit(1 << 24) | |
| LABELS = ['mpc', 'nnmpc', 'pid', 'nnhd'] | |
| PATHS = ['P1', 'P2', 'P3'] | |
| METRICS = ['lateral', 'heading'] | |
| METRIC_COL = {'lateral': 'mae_lat_m', 'heading': 'mae_head_rad'} | |
| MATCHED = {'P1': ['mpc', 'nnmpc', 'pid', 'nnhdx175'], 'P2': ['mpc', 'nnmpc', 'pid', 'nnhdx175'], | |
| 'P3': ['mpc', 'nnmpc', 'pid', 'nnhdx150']} | |
| DESC = {'M-NOM': 'nominal Chrono simulation, one run per path and controller (B03, phase 0)', | |
| 'NOM-archived-2024': 'nominal simulation logs of Tables II-III (one run per path and controller)', | |
| 'RF-A': 'Monte Carlo, start jitter and random phase, 20 runs per path and controller (B04)', | |
| 'RF-B': 'Monte Carlo, start jitter, random phase and disturbances, 20 runs per path and controller (B05)'} | |
| def fnum(v): | |
| return float(v) if v != '' else np.nan | |
| def load_fullpath(d, batch_dir): | |
| rows = [] | |
| for f in sorted(glob.glob(os.path.join(d, batch_dir, 'fullpath_part*.csv.gz'))): | |
| with gzip.open(f, 'rt', newline='') as fh: | |
| rows += [r for r in csv.DictReader(fh) if r['kind'] == 'fullpath'] | |
| return rows | |
| def ordering(scores): | |
| """LABELS sorted by ascending score (stable; ties keep input order).""" | |
| return [LABELS[i] for i in np.argsort(np.asarray(scores, dtype=float), kind='stable')] | |
| def nominal(rows): | |
| out = {} | |
| for p, labels in MATCHED.items(): | |
| for m in METRICS: | |
| vals = [] | |
| for lab in labels: | |
| sel = [r for r in rows if r['path_key'] == p and r['ctrl_label'] == lab] | |
| vals.append(fnum(sel[0][METRIC_COL[m]]) if len(sel) == 1 else np.nan) | |
| out[(p, m)] = np.array(vals) | |
| return out | |
| def monte_carlo(rows): | |
| out, n_sets = {}, {} | |
| for p, labels in MATCHED.items(): | |
| sub = [r for r in rows if r['path_key'] == p] | |
| for m in METRICS: | |
| cell = {} | |
| for r in sub: | |
| if r['ctrl_label'] in labels: | |
| key = (r['scenario_id'], r['ctrl_label']) | |
| if key in cell: | |
| raise RuntimeError(f'duplicate row for {key}') | |
| cell[key] = fnum(r[METRIC_COL[m]]) | |
| scens = sorted({s for s, _ in cell}) | |
| complete = [s for s in scens if all((s, l) in cell for l in labels)] | |
| complete = [s for s in complete if all(np.isfinite(cell[(s, l)]) for l in labels)] | |
| M = np.array([[cell[(s, l)] for l in labels] for s in complete], float).reshape(len(complete), len(labels)) | |
| out[(p, m)] = M.mean(0) | |
| n_sets[p] = len(complete) | |
| return out, n_sets | |
| def main(): | |
| d, nom_csv, out_json = sys.argv[1:4] | |
| preds, info = {}, {} | |
| b03 = [r for r in load_fullpath(d, 'B03_nominal') if r['tag_batch'] == 'B03' and r['tag_nominal_role'] == 'primary'] | |
| preds['M-NOM'] = nominal(b03) | |
| arch = {} | |
| for r in csv.DictReader(open(nom_csv)): | |
| c = {'MPC': 'mpc', 'NN-MPC': 'nnmpc', 'PID': 'pid', 'NN-HD': 'nnhd'}[r['controller']] | |
| arch.setdefault(r['path'], {}).setdefault('lateral', [None] * 4)[LABELS.index(c)] = float(r['run_mae_lateral_m']) | |
| arch[r['path']].setdefault('heading', [None] * 4)[LABELS.index(c)] = float(r['run_mae_heading_rad']) | |
| preds['NOM-archived-2024'] = {(p, m): np.array(arch[p][m], float) for p in PATHS for m in METRICS} | |
| for arm, bdir, tag in (('RF-A', 'B04_rf_a', 'B04'), ('RF-B', 'B05_rf_b', 'B05')): | |
| preds[arm], info[arm] = monte_carlo([r for r in load_fullpath(d, bdir) if r['tag_batch'] == tag]) | |
| res = {'_doc': 'Baseline predicted orders per path and metric (ascending run MAE). predicted_scores are in the ' | |
| 'order MPC, NN-MPC, PID, NN-HD (P1/P2: nnhdx175, P3: nnhdx150 for the Chrono batches).'} | |
| for name, pr in preds.items(): | |
| res[name] = {'description': DESC[name]} | |
| if name in info: | |
| res[name]['n_runs_per_controller'] = info[name] | |
| for p in PATHS: | |
| for m in METRICS: | |
| pt = pr[(p, m)] | |
| if not np.all(np.isfinite(pt)): | |
| raise RuntimeError(f'{name} {p} {m}: missing runs') | |
| res[name][f'{p}_{m}'] = {'predicted_ordering': ordering(pt), 'predicted_scores': [float(v) for v in pt]} | |
| json.dump(res, open(out_json, 'w'), indent=1) | |
| for name in preds: | |
| print(name, {t: '>'.join(v['predicted_ordering']) for t, v in res[name].items() if isinstance(v, dict) and 'predicted_ordering' in v}) | |
| if __name__ == '__main__': | |
| main() | |