File size: 18,408 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 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 | #!/usr/bin/env python3
"""Episode-list generator for the Case 1 (ART) batches used in the paper: B01, B03, B04, B05, B06, B07.
Builds the scenario tables with common random numbers (CRN) and writes one episode list per batch
(<out>/<batch dir>/episodes.json), using the runner's own builders (../default_episode.py: recovery_episode,
nominal_episode, draw_placement, latency_for) and the runner defaults (../default_config.json). No physics is run.
B01 main TR table: S2 rows 0-399 x 6 controllers (V6), control from t = 0, logged 40 s, run to the full horizon
B03 nominal runs on Paths 1-3 x V6 x controller phases {0, 20, 40, 60, 80} ms (phase 0 = nominal_role primary)
B04 Monte Carlo (RF-A): 3 paths x 20 runs x V5; start jitter dx, dy ~ U[-0.2, 0.2] m, dyaw ~ U[-0.067, 0.067] rad,
random phase and placement
B05 RF-B: the B04 runs plus condition D5 (actuation delay 0.10 s, steering bias 0.013, pose noise 0.02 m / 0.01 rad)
B06 offset ranges / shapes: 9 families (S0, S1, S3, S4, LATS1, LATS2, HEADS1, HEADS2, BETAS2) x rows 0-199 x V5,
25 s; CRN-mapped from the S2 table rows 0-199 (S2 itself = B01 rows 0-199)
B07 channel conditions D1a-D5 on the S2 rows 0-199 x V5, 25 s
V6 = MPC, NN-MPC, PID, NN-HD x1.75, NN-HD x1.5, NN-HD x1.0; V5 = V6 without NN-HD x1.0.
Seeds: numpy.random.default_rng(numpy.random.SeedSequence(seed)) with
[20261019, 2, 1] main S2 table, N = 400 (B01, B06 and B07 via CRN mapping)
[20261019, 2, 2] full-path Monte Carlo table, 3 paths x 20 (B04, B05)
[20261019, 2, 3] B04/B05 longitudinal start jitter u_dx, one draw per Monte Carlo row
Draw order per main row: u_side, u_E, u_Phi, phase_ms (integers 0..P_ms-1), placement heading, x0, y0
(default_episode.draw_placement), obs_noise seed (integers 0..2**31-2), u_bias (bias sign). Every row draws every
field, whatever the batch uses. Per Monte Carlo row: u_e, u_phi, phase_ms, placement (3), obs_noise seed, u_bias;
and u_dx from the separate stream [20261019, 2, 3].
The generated configs equal the released episode_config.json files of the simulation-log archives, except
tags.default_config_sha256 (see ../default_config.json, _doc).
Usage: python3 generate_lists.py [--out-root DIR]
"""
import argparse
import copy
import csv
import hashlib
import json
import math
import os
import sys
import numpy as np
HERE = os.path.dirname(os.path.abspath(__file__))
RUNNER = os.path.dirname(HERE)
sys.path.insert(0, RUNNER)
import default_episode as DE # noqa: E402
MASTER = 20261019
SEEDS = {'main_s2': [MASTER, 2, 1], 'rf': [MASTER, 2, 2], 'rf_dx': [MASTER, 2, 3]}
N_MAIN, N_S200, R_MAX = 400, 200, 20
RFA_PRIMARY = {'dxy_m': 0.2, 'dyaw_rad': 0.067} # Monte Carlo start jitter (spread of the physical starts)
RFA_WIDE = {'e_m': 0.25, 'phi_rad': 0.37} # jit_* columns of the Monte Carlo table (not used by B04/B05)
PATHS = ('P1', 'P2', 'P3')
NOMINAL_PHASES_MS = (0, 20, 40, 60, 80) # phase 0 (nominal run) + phase band
MAIN_HORIZON_S = 40.0 # B01: logged to 40 s; scored at H = 15 / 25 / 40 s
S200_HORIZON_S = 25.0 # B06, B07
NOISE_DOC = {'std_x': 0.02, 'std_y': 0.02, 'std_yaw': 0.01}
NOISE_EXP = {'std_x': 0.05, 'std_y': 0.05, 'std_yaw': 0.03}
STEERING_BIAS_JSON = os.path.join(HERE, 'steering_bias.json')
LISTS_VERSION = 'v1'
# Controller variants (labels used in episode ids and tags): (controller, controller_params, ctrl_desc)
SPECS = {
'mpc': ('mpc', None, 'MPC'),
'nnmpc': ('nnmpc', None, 'NN-MPC'),
'pid': ('pid', None, 'PID'),
'nnhdx175': ('plugin:wrapped_released', {'base': 'nnhd', 'steering_scale': 1.75},
'NN-HD, steering gain x1.75 (configuration of the Path 1-2 physical runs)'),
'nnhdx150': ('plugin:wrapped_released', {'base': 'nnhd', 'steering_scale': 1.5},
'NN-HD, steering gain x1.5 (configuration of the Path 3 physical runs)'),
'nnhdx100': ('nnhd', None, 'NN-HD, steering gain x1.0'),
}
V6 = ['mpc', 'nnmpc', 'pid', 'nnhdx175', 'nnhdx150', 'nnhdx100']
V5 = V6[:5]
# Channel conditions. 'bias': 'doc' | '2x' (levels from steering_bias.json); noise: NOISE_DOC | NOISE_EXP.
DIST = {
'D1a': {'delay': 0.10, 'label': 'extra actuation delay +0.10 s'},
'D1b': {'delay': 0.20, 'label': 'extra actuation delay +0.20 s'},
'D2a': {'bias': 'doc', 'label': 'steering bias 0.013'},
'D2b': {'bias': '2x', 'label': 'steering bias 0.026 (2 x D2a)'},
'D3a': {'noise': NOISE_DOC, 'label': 'observation noise sigma_xy 0.02 m, sigma_yaw 0.01 rad'},
'D3b': {'noise': NOISE_EXP, 'label': 'observation noise sigma_xy 0.05 m, sigma_yaw 0.03 rad'},
'D4a': {'friction': 0.6, 'label': 'friction mu 0.6'},
'D4b': {'friction': 0.4, 'label': 'friction mu 0.4'},
'D5': {'delay': 0.10, 'bias': 'doc', 'noise': NOISE_DOC, 'label': 'combined: D1a + D2a + D3a'},
}
DIST_ORDER = ['D1a', 'D1b', 'D2a', 'D2b', 'D3a', 'D3b', 'D4a', 'D4b', 'D5']
# Offset families, CRN-mapped from the first 200 rows of the main table.
PI = math.pi
def beta33_inv(u):
"""Inverse CDF of Beta(3, 3): F(x) = 10x^3 - 15x^4 + 6x^5, by 200-step bisection (deterministic)."""
lo, hi = 0.0, 1.0
for _ in range(200):
mid = 0.5 * (lo + hi)
if 10 * mid ** 3 - 15 * mid ** 4 + 6 * mid ** 5 < u:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)
def _head_only(u, phimax):
s = 1.0 if u >= 0.5 else -1.0
return 0.0, s * (0.10 + (phimax - 0.10) * abs(2.0 * u - 1.0))
FAMILIES = {
'S0': ('near-reference: e ~ U[-0.25, 0.25] m, phi ~ U[-0.37, 0.37] rad',
lambda r: (r['side'] * 0.25 * r['u_E'], -0.37 + 0.74 * r['u_Phi'])),
'S1': ('intermediate: |E| ~ U[0.5, 1.5] m, Phi ~ U[-pi/6, pi/6]',
lambda r: (r['side'] * (0.5 + 1.0 * r['u_E']), -PI / 6 + (PI / 3) * r['u_Phi'])),
'S2': ('main range: |E| ~ U[1.5, 2.5] m, Phi ~ U[-pi/4, pi/4]',
lambda r: (r['side'] * (1.5 + 1.0 * r['u_E']), -PI / 4 + (PI / 2) * r['u_Phi'])),
'S3': ('E ~ U[-2.12, 2.12] m, Phi ~ U[-pi/4, pi/4]',
lambda r: (r['side'] * 2.12 * r['u_E'], -PI / 4 + (PI / 2) * r['u_Phi'])),
'S4': ('severe: |E| ~ U[2.5, 3.5] m, Phi ~ U[-pi/3, pi/3]',
lambda r: (r['side'] * (2.5 + 1.0 * r['u_E']), -PI / 3 + (2 * PI / 3) * r['u_Phi'])),
'LATS1': ('lateral-only at S1: |E| ~ U[0.5, 1.5] m, Phi = 0', lambda r: (r['side'] * (0.5 + r['u_E']), 0.0)),
'LATS2': ('lateral-only at S2: |E| ~ U[1.5, 2.5] m, Phi = 0', lambda r: (r['side'] * (1.5 + r['u_E']), 0.0)),
'HEADS1': ('heading-only at S1: E = 0, |Phi| ~ U[0.10, pi/6] with random sign (start outside the tube)',
lambda r: _head_only(r['u_Phi'], PI / 6)),
'HEADS2': ('heading-only at S2: E = 0, |Phi| ~ U[0.10, pi/4] with random sign (start outside the tube)',
lambda r: _head_only(r['u_Phi'], PI / 4)),
'BETAS2': ('central shape on the S2 support: |E| = 1.5 + B1, Phi = (pi/4)(2 B2 - 1), B1, B2 ~ Beta(3, 3)',
lambda r: (r['side'] * (1.5 + beta33_inv(r['u_E'])), (PI / 4) * (2.0 * beta33_inv(r['u_Phi']) - 1.0))),
}
B06_FAMILIES = ['S0', 'S1', 'S3', 'S4', 'LATS1', 'LATS2', 'HEADS1', 'HEADS2', 'BETAS2']
BATCH_DIRS = {'B01': 'B01_main_tr', 'B03': 'B03_nominal', 'B04': 'B04_rf_a', 'B05': 'B05_rf_b',
'B06': 'B06_severity_shape', 'B07': 'B07_dist_recovery'}
def sha256_file(p):
with open(p, 'rb') as f:
return hashlib.sha256(f.read()).hexdigest()
def rng_for(key):
return np.random.default_rng(np.random.SeedSequence(SEEDS[key]))
# ---------------------------------------------------------------------------------------------------------------
# Scenario tables
# ---------------------------------------------------------------------------------------------------------------
def scenario_rows(d, key, n, prefix):
rng = rng_for(key)
p_ms = int(round(d['latency']['controller_period_s'] * 1000))
rows = []
for i in range(n):
u_side, u_E, u_Phi = float(rng.random()), float(rng.random()), float(rng.random())
phase_ms = int(rng.integers(0, p_ms))
pl = DE.draw_placement(d, rng)
noise_seed = int(rng.integers(0, 2 ** 31 - 1))
u_bias = float(rng.random())
rows.append({'row': i, 'scenario_id': f'{prefix}_r{i:03d}', 'side': 1 if u_side < 0.5 else -1,
'u_side': u_side, 'u_E': u_E, 'u_Phi': u_Phi, 'phase_ms': phase_ms,
'pl_heading': pl['heading'], 'pl_x0': pl['x0'], 'pl_y0': pl['y0'],
'noise_seed': noise_seed, 'u_bias': u_bias, 'bias_sign': 1 if u_bias < 0.5 else -1})
return rows
def rf_rows(d):
"""Monte Carlo rows. The jit_* columns map u_e, u_phi to a lateral/yaw jitter that B04/B05 do not use; the start
jitter of B04/B05 (prim_*) maps u_dx, u_e, u_phi to dx, dy, dyaw."""
rng = rng_for('rf')
rng_dx = rng_for('rf_dx')
p_ms = int(round(d['latency']['controller_period_s'] * 1000))
a, w = RFA_PRIMARY, RFA_WIDE
rows = []
for pk in PATHS:
for r in range(R_MAX):
u_e, u_phi = float(rng.random()), float(rng.random())
phase_ms = int(rng.integers(0, p_ms))
pl = DE.draw_placement(d, rng)
noise_seed = int(rng.integers(0, 2 ** 31 - 1))
u_bias = float(rng.random())
u_dx = float(rng_dx.random())
rows.append({'path': pk, 'rep': r, 'scenario_id': f'rf_{pk}_r{r:02d}', 'u_e': u_e, 'u_phi': u_phi,
'jit_e_m': -w['e_m'] + 2 * w['e_m'] * u_e, 'jit_phi_rad': -w['phi_rad'] + 2 * w['phi_rad'] * u_phi,
'phase_ms': phase_ms,
'pl_heading': pl['heading'], 'pl_x0': pl['x0'], 'pl_y0': pl['y0'],
'noise_seed': noise_seed, 'u_bias': u_bias, 'bias_sign': 1 if u_bias < 0.5 else -1,
'u_dx': u_dx, 'prim_dx_m': -a['dxy_m'] + 2 * a['dxy_m'] * u_dx,
'prim_dy_m': -a['dxy_m'] + 2 * a['dxy_m'] * u_e,
'prim_dyaw_rad': -a['dyaw_rad'] + 2 * a['dyaw_rad'] * u_phi})
return rows
def placement_of(row):
return {'heading': row['pl_heading'], 'x0': row['pl_x0'], 'y0': row['pl_y0']}
# ---------------------------------------------------------------------------------------------------------------
# Episode builders
# ---------------------------------------------------------------------------------------------------------------
class Ctx:
def __init__(self, d, bias):
self.d = d
self.bias = bias # {'doc': D2a, '2x': D2b}
self.registry = (d.get('controller_registry') or {}).get('ids') or {}
def spec(self, label):
ctrl, par, desc = SPECS[label]
par = copy.deepcopy(par)
reg_ids = [k for k, v in self.registry.items()
if v.get('controller') == ctrl and (v.get('controller_params') or None) == (par or None)]
return ctrl, par, desc, reg_ids
def base_tags(batch, label, desc, reg_ids, extra):
t = {'batch': batch, 'lists_version': LISTS_VERSION, 'ctrl_label': label, 'ctrl_desc': desc}
if reg_ids:
t['controller_registry_ids'] = reg_ids
t.update(extra)
return t
def pert_for(ctx, cond, row):
if cond is None:
return None
c = DIST[cond]
p = {}
if 'delay' in c:
p['actuation_delay_s'] = c['delay']
if 'bias' in c:
p['steering_bias'] = round(row['bias_sign'] * ctx.bias[c['bias']], 6)
if 'noise' in c:
p['obs_noise'] = dict(c['noise'], seed=row['noise_seed'])
if 'friction' in c:
p['friction'] = c['friction']
return p
def rec_ep(ctx, batch, sid, label, e, phi, row, horizon, extra, cond=None):
ctrl, par, desc, reg = ctx.spec(label)
phase_ms = row['phase_ms']
tags = base_tags(batch, label, desc, reg, dict(extra, row=row['row'], phase_ms=phase_ms, condition=cond or 'none'))
return DE.recovery_episode(ctx.d, f'{batch.lower()}_{sid}_{label}', sid, ctrl, e, phi, phase_ms / 1000.0,
controller_params=par, perturbation=pert_for(ctx, cond, row),
termination={'stop_on_divergence': False}, tags=tags,
placement=placement_of(row), horizon_s=horizon)
def fp_ep(ctx, batch, sid, label, pk, phase_ms, extra, pose=None, placement=None, cond=None, row=None):
ctrl, par, desc, reg = ctx.spec(label)
tags = base_tags(batch, label, desc, reg, dict(extra, path=pk, phase_ms=phase_ms, condition=cond or 'none'))
return DE.nominal_episode(ctx.d, f'{batch.lower()}_{sid}_{label}', pk, ctrl, phase_ms / 1000.0,
controller_params=par, initial_pose=pose, perturbation=pert_for(ctx, cond, row),
tags=tags, placement=placement, scenario_id=sid)
def rf_pose(row):
"""Jitter around the default start pose (chassis_ref (0, 0, 0), before the placement): x = dx, y = dy (default body
axes), yaw = dyaw. Returns (pose, local jitter)."""
loc = {'dx_m': row['prim_dx_m'], 'dy_m': row['prim_dy_m'], 'dyaw_rad': row['prim_dyaw_rad']}
return {'x': loc['dx_m'], 'y': loc['dy_m'], 'yaw': loc['dyaw_rad'], 'frame': 'chassis_ref'}, loc
# ---------------------------------------------------------------------------------------------------------------
# Batches
# ---------------------------------------------------------------------------------------------------------------
def b01(ctx, main):
eps = []
for r in main:
e, phi = FAMILIES['S2'][1](r)
for lab in V6:
eps.append(rec_ep(ctx, 'B01', r['scenario_id'], lab, e, phi, r, MAIN_HORIZON_S,
{'family': 'S2', 'table_seed': SEEDS['main_s2']}))
return eps
def b03(ctx):
eps = []
for pk in PATHS:
for ph in NOMINAL_PHASES_MS:
for lab in V6:
eps.append(fp_ep(ctx, 'B03', f'nom_{pk}_ph{ph:03d}', lab, pk, ph,
{'nominal_role': 'primary' if ph == 0 else 'phase band'}))
return eps
def rf_batch(ctx, rf, batch, labels, cond):
eps = []
for r in rf:
pose, local = rf_pose(r)
for lab in labels:
sid = r['scenario_id'] if cond is None else f"{cond}_{r['scenario_id']}"
arm = 'RF-A' if cond is None else ('RF-B' if cond == 'D5' else 'RF-A + ' + cond)
extra = {'rep': r['rep'], 'table_seed': SEEDS['rf'], 'rf_arm': arm, 'rf_jitter': 'primary',
'rf_jitter_local': local, 'rf_jitter_dx_seed': SEEDS['rf_dx']}
eps.append(fp_ep(ctx, batch, sid, lab, r['path'], r['phase_ms'], extra,
pose=pose, placement=placement_of(r), cond=cond, row=r))
return eps
def b06(ctx, main):
eps = []
for fam in B06_FAMILIES:
for r in main[:N_S200]:
e, phi = FAMILIES[fam][1](r)
sid = f"{fam}_r{r['row']:03d}"
for lab in V5:
eps.append(rec_ep(ctx, 'B06', sid, lab, e, phi, r, S200_HORIZON_S,
{'family': fam, 'crn_source': r['scenario_id'], 'table_seed': SEEDS['main_s2']}))
return eps
def b07(ctx, main):
eps = []
for cond in DIST_ORDER:
for r in main[:N_S200]:
e, phi = FAMILIES['S2'][1](r)
sid = f"{cond}_{r['scenario_id']}"
for lab in V5:
eps.append(rec_ep(ctx, 'B07', sid, lab, e, phi, r, S200_HORIZON_S,
{'family': 'S2', 'crn_source': r['scenario_id'], 'table_seed': SEEDS['main_s2']},
cond=cond))
return eps
# ---------------------------------------------------------------------------------------------------------------
def write_json(path, obj):
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, 'w') as f:
json.dump(obj, f, indent=1, sort_keys=False)
f.write('\n')
def write_csv(path, rows):
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, 'w', newline='') as f:
w = csv.DictWriter(f, fieldnames=list(rows[0]))
w.writeheader()
for r in rows:
w.writerow(r)
def load_bias():
sb = json.load(open(STEERING_BIAS_JSON))
return {'doc': float(sb['result']['D2a_documented_level_cmd_units']),
'2x': float(sb['result']['D2b_exploratory_level_cmd_units'])}
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--out-root', default=os.path.join(HERE, 'lists'))
a = ap.parse_args()
d = DE.load_default()
bias = load_bias()
ctx = Ctx(d, bias)
main_rows = scenario_rows(d, 'main_s2', N_MAIN, 's2m')
rf = rf_rows(d)
out = os.path.abspath(a.out_root)
batches = {'B01': b01(ctx, main_rows), 'B03': b03(ctx),
'B04': rf_batch(ctx, rf, 'B04', V5, None),
'B05': rf_batch(ctx, rf, 'B05', V5, 'D5'),
'B06': b06(ctx, main_rows), 'B07': b07(ctx, main_rows)}
for b, eps in batches.items():
write_json(os.path.join(out, BATCH_DIRS[b], 'episodes.json'), eps)
# scenario tables
tdir = os.path.join(out, 'tables')
write_csv(os.path.join(tdir, 'main_s2_table.csv'),
[dict(r, e_m=FAMILIES['S2'][1](r)[0], phi_rad=FAMILIES['S2'][1](r)[1]) for r in main_rows])
write_csv(os.path.join(tdir, 'rf_table.csv'), rf)
fam_rows = []
for fam in ['S2'] + B06_FAMILIES:
for r in main_rows[:N_S200]:
e, phi = FAMILIES[fam][1](r)
fam_rows.append({'family': fam, 'row': r['row'], 'crn_source': r['scenario_id'], 'e_m': e, 'phi_rad': phi,
'phase_ms': r['phase_ms'], 'description': FAMILIES[fam][0]})
write_csv(os.path.join(tdir, 'family_table.csv'), fam_rows)
meta = {'lists_version': LISTS_VERSION, 'seeds': SEEDS, 'steering_bias': {'D2a': bias['doc'], 'D2b': bias['2x']},
'default_config_sha256_in_episodes': d['_sha256'], 'numpy': np.__version__, 'python': sys.version.split()[0],
'controller_specs': {k: {'controller': v[0], 'controller_params': v[1], 'desc': v[2]} for k, v in SPECS.items()},
'episodes': {b: len(e) for b, e in batches.items()}}
write_json(os.path.join(out, 'generation_meta.json'), meta)
for b, eps in batches.items():
print(b, BATCH_DIRS[b], len(eps))
if __name__ == '__main__':
main()
|