Download code/case1/runner/art_runner/physics.py from harryzhang1018/TestRandomization: direct link, hf CLI and curl.
- Browser
- Download file 4.96 kB
-
https://huggingface.co/datasets/harryzhang1018/TestRandomization/resolve/main/code/case1/runner/art_runner/physics.py
- Command line
-
hf download hf://datasets/harryzhang1018/TestRandomization/code/case1/runner/art_runner/physics.py
-
curl -L -o physics.py https://huggingface.co/datasets/harryzhang1018/TestRandomization/resolve/main/code/case1/runner/art_runner/physics.py
4.96 kB
| """Client for the art_lockstep physics server (NEW CODE). | |
| One server process == one episode == one freshly constructed Chrono system, | |
| ARTcar and RigidTerrain. Communication is strictly request/response over | |
| pipes, so results never depend on wall-clock timing. | |
| """ | |
| import os | |
| import select | |
| import subprocess | |
| import time | |
| STATE_FIELDS = ('step time cog_x cog_y cog_z q_e0 q_e1 q_e2 q_e3 vel_x vel_y vel_z wloc_x wloc_y wloc_z ' | |
| 'ref_x ref_y ref_z applied_steer applied_thr applied_brake drv_steer drv_thr drv_brake ' | |
| 'veh_speed finite step_wall_s').split() | |
| DEFAULT_BINARY = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'build', 'art_lockstep') | |
| class PhysicsError(RuntimeError): | |
| """Infrastructure failure of the physics server (crash, timeout, message format).""" | |
| class PhysicsServer: | |
| def __init__(self, x, y, yaw, binary=DEFAULT_BINARY, terrain_json=None, waypoint_boxes=None, | |
| replicate_vis=False, timeout_s=120.0, stderr_path=None): | |
| self.timeout_s = timeout_s | |
| args = [binary, '--x', repr(float(x)), '--y', repr(float(y)), '--yaw', repr(float(yaw))] | |
| if terrain_json: | |
| args += ['--terrain-json', terrain_json] | |
| if waypoint_boxes: | |
| args += ['--waypoint-boxes', waypoint_boxes] | |
| if replicate_vis: | |
| args += ['--replicate-vis', '1'] | |
| self.args = args | |
| self.extra_output = [] | |
| t0 = time.perf_counter() | |
| self._stderr = open(stderr_path, 'w') if stderr_path else subprocess.DEVNULL | |
| env = dict(os.environ) | |
| env.setdefault('OMP_NUM_THREADS', '1') | |
| self.proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self._stderr, | |
| bufsize=0, env=env) | |
| self._buf = b'' | |
| ready = self._read_until(b'READY') | |
| self.ready_line = ready | |
| self.server_init_s = float(ready.split()[1].split('=')[1]) | |
| self.state = self._parse_state(self._read_until(b'X ')) | |
| self.spawn_to_ready_s = time.perf_counter() - t0 | |
| self.step_calls = 0 | |
| # -- low level --------------------------------------------------------- | |
| def _readline(self): | |
| deadline = time.monotonic() + self.timeout_s | |
| while b'\n' not in self._buf: | |
| remaining = deadline - time.monotonic() | |
| if remaining <= 0: | |
| raise PhysicsError(f'physics server timeout after {self.timeout_s}s') | |
| r, _, _ = select.select([self.proc.stdout], [], [], remaining) | |
| if not r: | |
| continue | |
| chunk = os.read(self.proc.stdout.fileno(), 1 << 16) | |
| if not chunk: | |
| raise PhysicsError(f'physics server exited (code {self.proc.poll()})') | |
| self._buf += chunk | |
| line, self._buf = self._buf.split(b'\n', 1) | |
| return line.decode() | |
| def _read_until(self, prefix): | |
| while True: | |
| line = self._readline() | |
| if line.startswith(prefix.decode()): | |
| return line | |
| if line.startswith('ART_LOCKSTEP_FATAL'): | |
| raise PhysicsError(line) | |
| self.extra_output.append(line) # e.g. Chrono GetLog() text | |
| def _send(self, text): | |
| try: | |
| os.write(self.proc.stdin.fileno(), text.encode()) | |
| except (BrokenPipeError, OSError) as e: | |
| raise PhysicsError(f'physics server pipe error: {e}') | |
| def _parse_state(line): | |
| parts = line.split()[1:] | |
| if len(parts) != len(STATE_FIELDS): | |
| raise PhysicsError(f'bad state line ({len(parts)} fields): {line[:200]}') | |
| st = {} | |
| for k, v in zip(STATE_FIELDS, parts): | |
| st[k] = float(v) | |
| st['step'] = int(parts[0]) | |
| st['finite'] = int(parts[STATE_FIELDS.index('finite')]) | |
| return st | |
| # -- API ---------------------------------------------------------------- | |
| def step(self, n): | |
| if n <= 0: | |
| raise ValueError('step count must be positive') | |
| self._send(f'S {int(n)}\n') | |
| self.state = self._parse_state(self._read_until(b'X ')) | |
| self.step_calls += 1 | |
| if not self.state['finite']: | |
| raise PhysicsError(f"non-finite physics state at step {self.state['step']}") | |
| return self.state | |
| def set_inputs(self, steering, throttle, braking): | |
| self._send(f'U {float(steering)!r} {float(throttle)!r} {float(braking)!r}\n') | |
| parts = self._read_until(b'OK').split() | |
| return float(parts[1]), float(parts[2]), float(parts[3]) | |
| def close(self): | |
| if self.proc.poll() is None: | |
| try: | |
| self._send('Q\n') | |
| self.proc.wait(timeout=10) | |
| except Exception: | |
| self.proc.kill() | |
| self.proc.wait() | |
| if self._stderr not in (None, subprocess.DEVNULL): | |
| self._stderr.close() | |
| return self.proc.returncode | |