File size: 11,155 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
#!/usr/bin/env python3
"""Case 1 physical runs and nominal simulations: per-run MAE (Tables II-III) and per-run start metadata.

Input: the folder TestingData of https://github.com/uwsbel/sbel-reproducibility/tree/master/2024/PathFollowingSim2real
(sub-folders rd_path = Path 1, syn_path = Path 2, lot17 = Path 3; five physical runs per policy and path, and one
nominal simulation log sim_<policy>.csv per policy and path) and the reference waypoints of the Docker image
(path_iros_1.csv, path_iros_2.csv, lot17_sinsquare.csv; copied to data/waypoints/).

Error definition (each logged sample): nearest reference waypoint (zero lookahead); lateral error = body-frame lateral
component of the displacement to that waypoint; heading error = wrapped difference between waypoint heading and
vehicle heading. Run MAE = mean of the absolute errors over all logged samples (no trimming or filtering).
Pose columns: nine-column logs (0, 1, 2); fourteen-column logs (Path 3 NN-MPC and NN-HD physical runs) (2, 3, 10).
The derived start quantities (initial pose, initial errors, motion onset, stale-pose fraction, pose outliers,
stationary segments) are proxies computed from the logged samples; the logs carry no timestamps.

Outputs (OUT_DIR):
  physical_runs.csv      60 physical runs (rounded as in the released table)
  nominal_sim_runs.csv   12 nominal simulation runs (full precision)
  tables_II_III.json     per path and policy: mean and sample SD (ddof = 1) of the five run MAEs, nominal sim MAE
  tables_II_III.tex      the rows of Tables II (lateral, m) and III (heading, rad)
  physical_pair_bootstrap.json  per path and metric: mean MAE difference of each controller pair and its 95 % run
                         bootstrap interval (20000 replicates, seed 20261019)
  physical_summary.json  start spread of the physical runs (max start distance, max |initial lateral error|)

Usage: python physical_runs.py TESTING_DATA_DIR WAYPOINTS_DIR OUT_DIR
"""
import csv
import glob
import hashlib
import itertools
import json
import math
import os
import sys

import numpy as np

PATHS = {'rd_path': 'path_iros_1', 'syn_path': 'path_iros_2', 'lot17': 'lot17_sinsquare'}
PATH_KEY = {'rd_path': 'P1', 'syn_path': 'P2', 'lot17': 'P3'}
POLICY = {'mpc': 'MPC', 'nn_mpc': 'NN-MPC', 'pid': 'PID', 'nn_mc': 'NN-HD', 'mpc_bb': 'NN-MPC', 'mc_bb': 'NN-HD'}
CTRL_ORDER = ['MPC', 'NN-MPC', 'PID', 'NN-HD']
N_BOOT, BOOT_SEED = 20000, 20261019


def sha(p):
    return hashlib.sha256(open(p, 'rb').read()).hexdigest()


def wrap(a):
    return np.arctan2(np.sin(a), np.cos(a))


def errors(x, y, th, ref, lookahead=0.0):
    ax, ay = x + np.cos(th) * lookahead, y + np.sin(th) * lookahead
    idx = ((ax[:, None] - ref[None, :, 0]) ** 2 + (ay[:, None] - ref[None, :, 1]) ** 2).argmin(1)
    dx, dy = ref[idx, 0] - x, ref[idx, 1] - y
    return -np.sin(th) * dx + np.cos(th) * dy, wrap(ref[idx, 2] - th), idx


def runs_of(mask):
    out, start = [], None
    for i, m in enumerate(mask):
        if m and start is None:
            start = i
        if not m and start is not None:
            out.append((start, i - 1)); start = None
    if start is not None:
        out.append((start, len(mask) - 1))
    return out


def analyse(f, ref, data):
    a = np.loadtxt(f, delimiter=',')
    cols = (0, 1, 2) if a.shape[1] == 9 else (2, 3, 10)
    x, y, th = a[:, cols[0]], a[:, cols[1]], a[:, cols[2]]
    lat, head, idx = errors(x, y, th, ref)
    step = np.r_[0.0, np.hypot(np.diff(x), np.diff(y))]
    moving = np.where(step > 0.01)[0]
    onset = int(moving[0]) if len(moving) else None
    # isolated outliers: sample far from both neighbours while neighbours are close to each other
    out_rows = []
    for t in range(1, len(a) - 1):
        d_prev = np.hypot(x[t] - x[t - 1], y[t] - y[t - 1]); d_next = np.hypot(x[t + 1] - x[t], y[t + 1] - y[t])
        d_skip = np.hypot(x[t + 1] - x[t - 1], y[t + 1] - y[t - 1])
        if d_prev > 0.5 and d_next > 0.5 and d_skip < 0.5:
            out_rows.append(t)
    big_steps = [int(t) for t in np.where(step > 0.5)[0] if t not in out_rows and t - 1 not in out_rows]
    stationary = [(s, e) for s, e in runs_of(step < 0.01) if onset is not None and s > onset and e - s + 1 >= 20 and e < len(a) - 1]
    n_ref = len(ref)
    return dict(
        file=os.path.relpath(f, data), sha256=sha(f), columns=a.shape[1], rows=len(a),
        initial_pose=[float(x[0]), float(y[0]), float(th[0])],
        initial_zero_lookahead_lateral_m=float(lat[0]), initial_heading_error_rad=float(head[0]),
        initial_nearest_waypoint=int(idx[0]),
        motion_onset_row=onset,
        stale_pose_fraction=float(np.mean(step[1:] < 1e-9)),
        max_progress_waypoint_fraction=float(idx.max() / (n_ref - 1)),
        isolated_pose_outlier_rows=out_rows,
        other_pose_steps_gt_0p5m_rows=big_steps,
        stationary_segments_after_onset_ge_2s=[[int(s), int(e)] for s, e in stationary],
        max_abs_lateral_m=float(np.abs(lat).max()),
        mae=np.abs(np.column_stack((lat, head))).mean(axis=0).tolist())


def main():
    data, wp, out = sys.argv[1:4]
    os.makedirs(out, exist_ok=True)
    runs = []
    for folder, stem in PATHS.items():
        ref = np.loadtxt(os.path.join(wp, stem + '.csv'), delimiter=',')
        for f in sorted(glob.glob(os.path.join(data, folder, '*.csv'))):
            name = os.path.basename(f)[:-4]
            pol = name[4:] if name.startswith('sim_') else name.rsplit('_', 1)[0]
            r = analyse(f, ref, data)
            r.update(path=folder, policy=POLICY[pol], kind='nominal_sim' if name.startswith('sim_') else 'physical')
            runs.append(r)

    phys = [r for r in runs if r['kind'] == 'physical']
    assert len(phys) == 60
    rows = []
    for r in sorted(phys, key=lambda r: (PATH_KEY[r['path']], CTRL_ORDER.index(r['policy']), r['file'])):
        run_idx = int(os.path.splitext(os.path.basename(r['file']))[0].split('_')[-1])
        rows.append({
            'path': PATH_KEY[r['path']], 'controller': r['policy'], 'run': run_idx, 'log_file': 'TestingData/' + r['file'],
            'log_sha256': r['sha256'], 'log_columns': r['columns'], 'rows': r['rows'],
            'start_distance_from_local_origin_m': round(math.hypot(*r['initial_pose'][:2]), 4),
            'start_yaw_local_frame_rad': round(r['initial_pose'][2], 4),
            'initial_lateral_error_m': round(r['initial_zero_lookahead_lateral_m'], 4),
            'initial_heading_error_rad': round(r['initial_heading_error_rad'], 4),
            'initial_nearest_waypoint': r['initial_nearest_waypoint'],
            'motion_onset_row': r['motion_onset_row'],
            'max_progress_waypoint_fraction': round(r['max_progress_waypoint_fraction'], 4),
            'stale_pose_fraction': round(r['stale_pose_fraction'], 4),
            'pose_steps_gt_0p5m': len(r['other_pose_steps_gt_0p5m_rows']),
            'isolated_pose_outliers': len(r['isolated_pose_outlier_rows']),
            'stationary_segments_ge_2s_after_onset': len(r['stationary_segments_after_onset_ge_2s']),
            'run_mae_lateral_m': round(r['mae'][0], 5), 'run_mae_heading_rad': round(r['mae'][1], 5),
            'max_abs_lateral_error_m': round(r['max_abs_lateral_m'], 3),
        })
    with open(os.path.join(out, 'physical_runs.csv'), 'w', newline='') as f:
        w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
        w.writeheader()
        w.writerows(rows)

    nom = sorted([r for r in runs if r['kind'] == 'nominal_sim'], key=lambda r: (PATH_KEY[r['path']], CTRL_ORDER.index(r['policy'])))
    assert len(nom) == 12
    with open(os.path.join(out, 'nominal_sim_runs.csv'), 'w', newline='') as f:
        w = csv.writer(f)
        w.writerow(['path', 'controller', 'log_file', 'log_sha256', 'log_columns', 'rows', 'run_mae_lateral_m', 'run_mae_heading_rad'])
        for r in nom:
            w.writerow([PATH_KEY[r['path']], r['policy'], 'TestingData/' + r['file'], r['sha256'], r['columns'], r['rows'],
                        repr(r['mae'][0]), repr(r['mae'][1])])

    # Tables II-III: mean and sample SD (ddof = 1) of the five run MAEs (full precision); one nominal simulation run
    tab = {}
    for folder in PATHS:
        p = PATH_KEY[folder]
        for c in CTRL_ORDER:
            v = np.array([r['mae'] for r in phys if r['path'] == folder and r['policy'] == c])
            s = next(r for r in nom if r['path'] == folder and r['policy'] == c)
            tab[f'{p}|{c}'] = {'n_runs': len(v), 'real_mean': v.mean(axis=0).tolist(), 'real_sd': v.std(axis=0, ddof=1).tolist(),
                               'nominal_sim': s['mae']}
    json.dump({'metrics': ['lateral_m', 'heading_rad'], 'cells': tab}, open(os.path.join(out, 'tables_II_III.json'), 'w'), indent=1)
    lines = []
    for mi, (name, unit) in enumerate((('Table II: lateral error', 'm'), ('Table III: heading error', 'rad'))):
        lines += [f'% {name} ({unit}); columns Path 1, Path 2, Path 3', r'Policy & Path 1 & Path 2 & Path 3 \\']
        for c in CTRL_ORDER:
            cells = [tab[f'{p}|{c}'] for p in ('P1', 'P2', 'P3')]
            lines.append(f'{c}-Sim & ' + ' & '.join(f"${x['nominal_sim'][mi]:.3f}$" for x in cells) + r' \\')
            lines.append(f'{c}-Real & ' + ' & '.join(f"${x['real_mean'][mi]:.3f}\\pm{x['real_sd'][mi]:.3f}$" for x in cells) + r' \\')
        lines.append('')
    open(os.path.join(out, 'tables_II_III.tex'), 'w').write('\n'.join(lines))

    # Run bootstrap of the mean-MAE difference of each controller pair: resample the five runs of each controller
    # independently (with replacement), 20000 replicates, seed 20261019; one draw array per path (Paths 1, 2, 3 in
    # this order), shared by both metrics.
    rng = np.random.default_rng(BOOT_SEED)
    pairs = {}
    for folder in PATHS:
        p = PATH_KEY[folder]
        run_mae = np.array([[r['mae'] for r in phys if r['path'] == folder and r['policy'] == c] for c in CTRL_ORDER])
        draws = rng.integers(0, 5, size=(4, N_BOOT, 5))
        for mi, m in enumerate(('lateral', 'heading')):
            v = run_mae[:, :, mi]
            boot = np.stack([v[k][draws[k]].mean(axis=1) for k in range(4)], axis=1)
            point = v.mean(axis=1)
            pairs[f'{p}_{m}'] = [{'pair': f'{CTRL_ORDER[a]} - {CTRL_ORDER[b]}', 'mean_difference': float(point[a] - point[b]),
                                  'bootstrap_95': np.quantile(boot[:, a] - boot[:, b], [.025, .975]).tolist()}
                                 for a, b in itertools.combinations(range(4), 2)]
    json.dump({'replicates': N_BOOT, 'seed': BOOT_SEED, 'pairs': pairs},
              open(os.path.join(out, 'physical_pair_bootstrap.json'), 'w'), indent=1)

    summ = {'n_physical_runs': len(phys), 'n_nominal_sim_runs': len(nom),
            'max_start_distance_from_local_origin_m': round(max(math.hypot(*r['initial_pose'][:2]) for r in phys), 4),
            'max_abs_initial_lateral_error_m': round(max(abs(r['initial_zero_lookahead_lateral_m']) for r in phys), 4)}
    json.dump(summ, open(os.path.join(out, 'physical_summary.json'), 'w'), indent=1)
    print(json.dumps(summ))
    print('\n'.join(lines))


if __name__ == '__main__':
    main()