Download code/case1/runner/art_runner/config.py from harryzhang1018/TestRandomization: direct link, hf CLI and curl.
- Browser
- Download file 12.7 kB
-
https://huggingface.co/datasets/harryzhang1018/TestRandomization/resolve/main/code/case1/runner/art_runner/config.py
- Command line
-
hf download hf://datasets/harryzhang1018/TestRandomization/code/case1/runner/art_runner/config.py
-
curl -L -o config.py https://huggingface.co/datasets/harryzhang1018/TestRandomization/resolve/main/code/case1/runner/art_runner/config.py
12.7 kB
| """Episode configuration: validation, defaults, canonical hash (NEW CODE). | |
| The authoritative schema is runner/schemas/episode_config.schema.json; this | |
| module implements the same rules without third-party dependencies. Unknown | |
| keys are rejected so that typos cannot silently fall back to defaults. | |
| """ | |
| import copy | |
| import hashlib | |
| import json | |
| import math | |
| import re | |
| DT = 1e-3 | |
| SCHEMA_VERSION = 'tr-c1-episode/1' | |
| RELEASED = ('mpc', 'nnmpc', 'pid', 'nnhd') | |
| DEFAULT_PERTURBATION = { | |
| 'steering_bias': 0.0, | |
| 'actuation_delay_s': 0.0, | |
| 'friction': None, | |
| 'obs_noise': {'seed': 0, 'std_x': 0.0, 'std_y': 0.0, 'std_yaw': 0.0}, | |
| } | |
| DEFAULT_TERMINATION = { | |
| 'type': 'fixed_horizon', | |
| 'tube_lat_m': 0.1, | |
| 'tube_head_rad': 0.1, | |
| 'divergence_dist_m': 5.0, | |
| 'divergence_hold_s': 2.0, | |
| 'stop_on_divergence': True, | |
| 'completion_margin_s': 0.0, | |
| } | |
| ROS_DEFAULTS = {'controller_period_s': 0.1, 'state_rate_hz': 25.0, 'driver_rate_hz': 10.0, 'state_delay_s': 0.0} | |
| TOP_KEYS = {'schema', 'episode_id', 'scenario_id', 'controller', 'controller_params', 'reference', 'initial_pose', | |
| 'horizon_s', 'control_start_s', 'latency', 'perturbation', 'termination', 'on_controller_failure', | |
| 'replicate_waypoint_boxes', 'replicate_visual_setters', 'tags', 'mpc_osqp_adaptive_rho_interval'} | |
| DEFAULT_OSQP_ADAPTIVE_RHO_INTERVAL = 25 | |
| class ConfigError(ValueError): | |
| pass | |
| # Parameters and DEFAULTS of | |
| # every plug-in. config.normalize rejects an unknown plug-in name, an unknown parameter (typos cannot silently fall | |
| # back to a default) and a non-finite / out-of-range value. normalize() does NOT write the defaults into the config | |
| # (configs written before this revision keep their canonical hash); the plug-in applies them and the episode summary | |
| # records them as `controller_params_effective`. Kinds: num = finite number, pos = finite > 0, nonneg = finite >= 0, | |
| # bool, released = one of RELEASED. REQUIRED = no default. | |
| REQUIRED = object() | |
| PLUGIN_PARAM_SPECS = { | |
| 'replica_pid': {}, | |
| # pure pursuit / Stanley: P speed loop throttle = clip(throttle_ff + k_v * (v_ref - v), 0, 1) | |
| 'pure_pursuit': {'lookahead_m': ('pos', 1.0), 'wheelbase_m': ('pos', 0.5), 'k_v': ('num', 1.0), | |
| 'throttle_ff': ('num', 0.0)}, | |
| 'stanley': {'k': ('num', 1.0), 'softening': ('nonneg', 0.5), 'k_v': ('num', 1.0), 'throttle_ff': ('num', 0.0)}, | |
| 'wrapped_released': {'base': ('released', REQUIRED), 'steering_scale': ('num', 1.0), 'shared_speed': ('bool', False), | |
| 'kp_speed': ('num', 1.0), 'throttle_bias': ('num', 0.0)}, | |
| 'mpc_n5': {}, | |
| } | |
| def plugin_effective_params(name, params): | |
| """Validate plug-in parameters against PLUGIN_PARAM_SPECS and return them with the defaults filled in.""" | |
| if name not in PLUGIN_PARAM_SPECS: | |
| raise ConfigError(f'unknown plug-in {name!r}; known plug-ins: {sorted(PLUGIN_PARAM_SPECS)}') | |
| spec = PLUGIN_PARAM_SPECS[name] | |
| if spec is None: # test-only registrations (fault-injection checks) skip validation | |
| return dict(params or {}) | |
| params = dict(params or {}) | |
| _check_keys(params, spec, f'controller_params of plugin:{name}') | |
| out = {} | |
| for k, (kind, default) in spec.items(): | |
| if k not in params: | |
| if default is REQUIRED: | |
| raise ConfigError(f'plugin:{name} requires controller_params.{k}') | |
| out[k] = default | |
| continue | |
| v = params[k] | |
| if kind == 'bool': | |
| if not isinstance(v, bool): | |
| raise ConfigError(f'plugin:{name} {k} must be true/false') | |
| elif kind == 'released': | |
| if v not in RELEASED: | |
| raise ConfigError(f'plugin:{name} {k} must be one of {RELEASED}') | |
| else: | |
| _num(params, k, lo=None) | |
| if kind == 'pos' and not v > 0: | |
| raise ConfigError(f'plugin:{name} {k} must be > 0') | |
| if kind == 'nonneg' and v < 0: | |
| raise ConfigError(f'plugin:{name} {k} must be >= 0') | |
| out[k] = v | |
| return out | |
| def _num(d, k, lo=None, hi=None, required=True, default=None): | |
| if k not in d: | |
| if required: | |
| raise ConfigError(f'missing {k}') | |
| return default | |
| v = d[k] | |
| if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v): | |
| raise ConfigError(f'{k} must be a finite number, got {v!r}') | |
| if lo is not None and v < lo: | |
| raise ConfigError(f'{k}={v} < {lo}') | |
| if hi is not None and v > hi: | |
| raise ConfigError(f'{k}={v} > {hi}') | |
| return float(v) | |
| def _check_keys(d, allowed, where): | |
| extra = set(d) - set(allowed) | |
| if extra: | |
| raise ConfigError(f'unknown keys in {where}: {sorted(extra)}') | |
| def to_steps(seconds, name): | |
| n = seconds / DT | |
| r = int(round(n)) | |
| if abs(n - r) > 1e-6: | |
| raise ConfigError(f'{name}={seconds} s is not a multiple of the 1 ms physics step') | |
| return r | |
| def normalize(cfg): | |
| if not isinstance(cfg, dict): | |
| raise ConfigError('episode config must be an object') | |
| c = copy.deepcopy(cfg) | |
| _check_keys(c, TOP_KEYS, 'episode') | |
| c['schema'] = c.get('schema', SCHEMA_VERSION) | |
| if c['schema'] != SCHEMA_VERSION: | |
| raise ConfigError(f"schema {c['schema']} != {SCHEMA_VERSION}") | |
| for k in ('episode_id', 'scenario_id'): | |
| if not isinstance(c.get(k), str) or not re.fullmatch(r'[A-Za-z0-9_.\-]{1,160}', c[k]): | |
| raise ConfigError(f'{k} must match [A-Za-z0-9_.-]{{1,160}}') | |
| ctrl = c.get('controller') | |
| if not isinstance(ctrl, str) or not (ctrl in RELEASED or ctrl.startswith('plugin:')): | |
| raise ConfigError(f'controller must be one of {RELEASED} or plugin:<name>') | |
| c['controller_params'] = c.get('controller_params', {}) | |
| if ctrl in RELEASED and c['controller_params']: | |
| raise ConfigError('released controllers take no controller_params (unmodified)') | |
| if ctrl.startswith('plugin:'): | |
| if not isinstance(c['controller_params'], dict): | |
| raise ConfigError('controller_params must be an object') | |
| plugin_effective_params(ctrl.split(':', 1)[1], c['controller_params']) # validation only | |
| ref = c.get('reference') | |
| if not isinstance(ref, dict) or ref.get('type') not in ('released_csv', 'csv_transformed', 'straight', 'array'): | |
| raise ConfigError('reference.type must be released_csv|csv_transformed|straight|array') | |
| allowed_ref = {'released_csv': {'type', 'name'}, 'csv_transformed': {'type', 'name', 'dx', 'dy', 'rotate'}, | |
| 'straight': {'type', 'x0', 'y0', 'heading', 's_start', 's_end', 'spacing', 'v_ref'}, | |
| 'array': {'type', 'points'}}[ref['type']] | |
| _check_keys(ref, allowed_ref, 'reference') | |
| if ref['type'] in ('released_csv', 'csv_transformed') and not re.fullmatch(r'[A-Za-z0-9_]+', str(ref.get('name'))): | |
| raise ConfigError('reference.name must be a released waypoint stem') | |
| pose = c.get('initial_pose') | |
| if not isinstance(pose, dict): | |
| raise ConfigError('initial_pose required') | |
| _check_keys(pose, {'x', 'y', 'yaw', 'frame'}, 'initial_pose') | |
| for k in ('x', 'y', 'yaw'): | |
| _num(pose, k) | |
| pose['frame'] = pose.get('frame', 'chassis_ref') | |
| if pose['frame'] not in ('chassis_ref', 'cog'): | |
| raise ConfigError('initial_pose.frame must be chassis_ref|cog') | |
| _num(c, 'horizon_s', lo=0.001, hi=3600) | |
| to_steps(c['horizon_s'], 'horizon_s') | |
| c['control_start_s'] = _num(c, 'control_start_s', lo=0, required=False, default=0.0) | |
| to_steps(c['control_start_s'], 'control_start_s') | |
| lat = c.get('latency') | |
| if not isinstance(lat, dict) or lat.get('model') not in ('ideal', 'ros_emulated'): | |
| raise ConfigError('latency.model must be given explicitly: ideal|ros_emulated (no campaign default)') | |
| if lat['model'] == 'ideal': | |
| _check_keys(lat, {'model', 'controller_period_s'}, 'latency') | |
| lat['controller_period_s'] = _num(lat, 'controller_period_s', lo=0.001, required=False, default=0.1) | |
| to_steps(lat['controller_period_s'], 'controller_period_s') | |
| else: | |
| _check_keys(lat, {'model', 'controller_phase_s', 'compute_delay_s', 'state_delay_s', 'controller_period_s', | |
| 'state_rate_hz', 'driver_rate_hz'}, 'latency') | |
| for k in ('controller_phase_s', 'compute_delay_s'): | |
| _num(lat, k, lo=0) # required: calibrated by the ROS-reference agent | |
| to_steps(lat[k], k) | |
| for k, v in ROS_DEFAULTS.items(): | |
| lat[k] = _num(lat, k, lo=0, required=False, default=v) | |
| to_steps(lat['state_delay_s'], 'state_delay_s') | |
| to_steps(lat['controller_period_s'], 'controller_period_s') | |
| pert = copy.deepcopy(DEFAULT_PERTURBATION) | |
| user_p = c.get('perturbation', {}) | |
| _check_keys(user_p, set(DEFAULT_PERTURBATION), 'perturbation') | |
| for k in ('steering_bias', 'actuation_delay_s'): | |
| if k in user_p: | |
| pert[k] = _num(user_p, k, lo=-1 if k == 'steering_bias' else 0, hi=1 if k == 'steering_bias' else 10) | |
| to_steps(pert['actuation_delay_s'], 'actuation_delay_s') | |
| if user_p.get('friction') is not None: | |
| pert['friction'] = _num(user_p, 'friction', lo=0.0, hi=2.0) | |
| if 'obs_noise' in user_p: | |
| on = user_p['obs_noise'] | |
| _check_keys(on, {'seed', 'std_x', 'std_y', 'std_yaw'}, 'perturbation.obs_noise') | |
| for k in ('std_x', 'std_y', 'std_yaw'): | |
| if k in on: | |
| pert['obs_noise'][k] = _num(on, k, lo=0) | |
| if 'seed' in on: | |
| if not isinstance(on['seed'], int) or isinstance(on['seed'], bool) or on['seed'] < 0: | |
| raise ConfigError('obs_noise.seed must be a non-negative integer') | |
| pert['obs_noise']['seed'] = on['seed'] | |
| c['perturbation'] = pert | |
| term = copy.deepcopy(DEFAULT_TERMINATION) | |
| user_t = c.get('termination', {}) | |
| _check_keys(user_t, set(DEFAULT_TERMINATION), 'termination') | |
| if 'type' in user_t: | |
| if user_t['type'] not in ('fixed_horizon', 'path_completion'): | |
| raise ConfigError('termination.type must be fixed_horizon|path_completion') | |
| term['type'] = user_t['type'] | |
| for k in ('tube_lat_m', 'tube_head_rad', 'divergence_dist_m', 'divergence_hold_s', 'completion_margin_s'): | |
| if k in user_t: | |
| term[k] = _num(user_t, k, lo=0) | |
| if 'stop_on_divergence' in user_t: | |
| term['stop_on_divergence'] = bool(user_t['stop_on_divergence']) | |
| to_steps(term['divergence_hold_s'], 'divergence_hold_s') | |
| to_steps(term['completion_margin_s'], 'completion_margin_s') | |
| c['termination'] = term | |
| c['on_controller_failure'] = c.get('on_controller_failure', 'hold_last_command') | |
| if c['on_controller_failure'] not in ('hold_last_command', 'terminate'): | |
| raise ConfigError('on_controller_failure must be hold_last_command|terminate') | |
| # The released MPC leaves OSQP's adaptive_rho_interval at 0 ("automatic"), which OSQP 0.6 resolves from | |
| # WALL-CLOCK time (first iteration count at which solve time > 0.4 x setup time, rounded to a multiple of | |
| # check_termination=25). Under CPU load this changes solutions within the solver tolerance. 25 is the value | |
| # that reproduces every archived nominal-sim MPC command exactly (checked by replay); | |
| # null keeps the released time-based behaviour (NOT deterministic). | |
| v = c.get('mpc_osqp_adaptive_rho_interval', DEFAULT_OSQP_ADAPTIVE_RHO_INTERVAL) | |
| if v is not None and (not isinstance(v, int) or isinstance(v, bool) or v <= 0): | |
| raise ConfigError('mpc_osqp_adaptive_rho_interval must be a positive integer or null') | |
| c['mpc_osqp_adaptive_rho_interval'] = v | |
| c['replicate_waypoint_boxes'] = bool(c.get('replicate_waypoint_boxes', False)) | |
| c['replicate_visual_setters'] = bool(c.get('replicate_visual_setters', False)) | |
| c['tags'] = c.get('tags', {}) | |
| return c | |
| def config_hash(normalized): | |
| blob = json.dumps(normalized, sort_keys=True, separators=(',', ':'), allow_nan=False) | |
| return hashlib.sha256(blob.encode()).hexdigest() | |
| def load_episode_list(path): | |
| with open(path) as f: | |
| data = json.load(f) | |
| if isinstance(data, dict): | |
| data = data.get('episodes') | |
| if not isinstance(data, list) or not data: | |
| raise ConfigError('episode file must be a non-empty list or {"episodes": [...]}') | |
| out, seen = [], set() | |
| for i, cfg in enumerate(data): | |
| try: | |
| n = normalize(cfg) | |
| except ConfigError as e: | |
| raise ConfigError(f'episode #{i} ({cfg.get("episode_id") if isinstance(cfg, dict) else "?"}): {e}') | |
| if n['episode_id'] in seen: | |
| raise ConfigError(f"duplicate episode_id {n['episode_id']}") | |
| seen.add(n['episode_id']) | |
| out.append(n) | |
| return out | |