File size: 7,801 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 | #!/usr/bin/env python3
"""Helpers that build episode configs from the runner defaults (runner/default_config.json).
Episode files must carry the explicit latency block that these helpers produce (the runner itself keeps "no latency
default" so every episode is self-describing).
from default_episode import load_default, latency_for, recovery_episode, nominal_episode, draw_placement
* recovery_episode() takes a rigid `placement` {'heading': rad, 'x0': m, 'y0': m} applied to BOTH the straight
reference and the initial pose (placement is a per-scenario nuisance factor shared by all controllers);
nominal_episode() takes an optional placement that turns the released CSV into a `csv_transformed` reference
(randomized full-path runs). With placement=None the configs use the canonical +x frame at the origin.
* recovery_episode() and nominal_episode() take an optional `control_start_s` (default: default_config
'control_start_s' = 0.0). The horizon is extended by the same amount, so every controller has the horizon H
measured from control start (the runner measures ST from control start).
* recovery_episode(..., horizon_s=H) overrides the recovery horizon (e.g. 40 s for the main TR table B01, scored
offline at H = 15/25/40 s); the horizon is still extended by control_start_s. Combine with
termination={'stop_on_divergence': False} to run every recovery episode to its full horizon.
* controller_spec(d, controller_id) returns (controller, controller_params) for a registered controller id
(default_config.json 'controller_registry'; e.g. 'nnhd_x1.75').
"""
import json
import math
import os
HERE = os.path.dirname(os.path.abspath(__file__))
DEFAULT_PATH = os.path.join(HERE, 'default_config.json')
def load_default(path=DEFAULT_PATH):
import hashlib
with open(path, 'rb') as f:
raw = f.read()
d = json.loads(raw)
d['_sha256'] = hashlib.sha256(raw).hexdigest()
return d
def compute_delay_for(d, controller, controller_params=None):
table = d['latency']['compute_delay_s_by_controller']
if controller in table:
return table[controller]
if controller == 'plugin:wrapped_released' and controller_params and controller_params.get('base') in table:
return table[controller_params['base']]
return table['plugin_default']
def latency_for(d, controller, controller_params=None, phase_s=0.0, model=None):
"""Explicit latency block for one episode. model=None -> runner default; 'ideal' -> no latency."""
lat = d['latency']
if (model or lat['model']) == 'ideal':
return {'model': 'ideal'}
P = lat['controller_period_s']
if not (0.0 <= phase_s < P):
raise ValueError(f'phase {phase_s} outside [0, {P})')
return {'model': 'ros_emulated', 'controller_period_s': P, 'controller_phase_s': round(phase_s, 3),
'compute_delay_s': compute_delay_for(d, controller, controller_params), 'state_delay_s': lat['state_delay_s'],
'state_rate_hz': lat['state_rate_hz'], 'driver_rate_hz': lat['driver_rate_hz']}
def controller_spec(d, controller_id):
"""(controller, controller_params or None) for a registered controller id (default_config 'controller_registry').
The params are copied, so callers cannot modify the runner default."""
reg = d['controller_registry']['ids']
if controller_id not in reg:
raise KeyError(f'unknown controller id {controller_id!r}; registered: {sorted(reg)}')
e = reg[controller_id]
params = e.get('controller_params')
return e['controller'], (json.loads(json.dumps(params)) if params else None)
def draw_placement(d, rng):
"""One rigid placement from the nuisance distribution (3 draws, in this order: heading, x0, y0)."""
p = d['placement']
h = float(rng.uniform(p['heading_rad'][0], p['heading_rad'][1]))
x0 = float(rng.uniform(p['origin_box_m'][0], p['origin_box_m'][1]))
y0 = float(rng.uniform(p['origin_box_m'][0], p['origin_box_m'][1]))
return {'heading': h, 'x0': x0, 'y0': y0}
def _place(placement, x, y, yaw):
if not placement:
return x, y, yaw
c, s = math.cos(placement['heading']), math.sin(placement['heading'])
return (placement['x0'] + c * x - s * y, placement['y0'] + s * x + c * y, yaw + placement['heading'])
def _control_start(d, control_start_s):
c0 = d['control_start_s'] if control_start_s is None else float(control_start_s)
if c0 < 0 or abs(c0 * 1000 - round(c0 * 1000)) > 1e-9:
raise ValueError(f'control_start_s {c0} must be a non-negative multiple of 1 ms')
return round(c0, 3)
def recovery_episode(d, episode_id, scenario_id, controller, e_m, phi_rad, phase_s, controller_params=None,
perturbation=None, termination=None, model=None, tags=None, placement=None, control_start_s=None,
horizon_s=None):
"""Paper geometry in the path frame: straight reference along the path-frame +x axis; vehicle displaced
laterally by e (positive = left of the path, path-frame +y) and misaligned by phi (CCW positive), at rest.
The pose is given in default_config 'recovery.initial_pose_frame'. `placement` rigidly moves reference and pose."""
r = d['recovery']
ref = dict(r['reference'])
if placement:
ref.update({'x0': placement['x0'], 'y0': placement['y0'], 'heading': placement['heading']})
x, y, yaw = _place(placement, r['start_x_m'], float(e_m), float(phi_rad))
c0 = _control_start(d, control_start_s)
ep = {'episode_id': episode_id, 'scenario_id': scenario_id, 'controller': controller,
'reference': ref,
'initial_pose': {'x': x, 'y': y, 'yaw': yaw, 'frame': r['initial_pose_frame']},
'horizon_s': round((r['horizon_s'] if horizon_s is None else float(horizon_s)) + c0, 3), 'control_start_s': c0,
'latency': latency_for(d, controller, controller_params, phase_s, model),
'termination': dict(r['termination'], **(termination or {})),
'mpc_osqp_adaptive_rho_interval': d['mpc_osqp_adaptive_rho_interval'],
'tags': dict(tags or {}, default_config_sha256=d.get('_sha256'), e_m=float(e_m), phi_rad=float(phi_rad),
placement=placement)}
if controller_params:
ep['controller_params'] = controller_params
if perturbation:
ep['perturbation'] = perturbation
return ep
def nominal_episode(d, episode_id, path_key, controller, phase_s=0.0, controller_params=None, initial_pose=None,
perturbation=None, model=None, tags=None, placement=None, scenario_id=None, control_start_s=None):
n = d['nominal']
p = n['paths'][path_key]
pose = dict(initial_pose or n['initial_pose'])
if placement:
ref = {'type': 'csv_transformed', 'name': p['reference'], 'dx': placement['x0'], 'dy': placement['y0'],
'rotate': placement['heading']}
pose['x'], pose['y'], pose['yaw'] = _place(placement, pose['x'], pose['y'], pose['yaw'])
else:
ref = {'type': 'released_csv', 'name': p['reference']}
c0 = _control_start(d, control_start_s)
ep = {'episode_id': episode_id, 'scenario_id': scenario_id or f'nominal_{path_key}', 'controller': controller,
'reference': ref,
'initial_pose': pose, 'horizon_s': round(p['horizon_s'] + c0, 3),
'control_start_s': c0,
'latency': latency_for(d, controller, controller_params, phase_s, model),
'termination': dict(n['termination']),
'mpc_osqp_adaptive_rho_interval': d['mpc_osqp_adaptive_rho_interval'],
'tags': dict(tags or {}, default_config_sha256=d.get('_sha256'), placement=placement)}
if controller_params:
ep['controller_params'] = controller_params
if perturbation:
ep['perturbation'] = perturbation
return ep
|