"""Read-only diagnostics around the existing keypose execution boundary.""" import json from pathlib import Path import numpy as np import torch from pydantic import BaseModel, ConfigDict from lim.keypose_control import KeyposeEnv, keypose_command class KeyposeTraceConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) env: KeyposeEnv """Unmodified observed-state keypose executor.""" path: Path """New JSONL file of pre-action diagnostics, one row per scene and step.""" seed_start: int """First seed in the recorder's consecutive synchronous episode batches.""" class KeyposeTraceEnv: def __init__(self, config: KeyposeTraceConfig): self.config = config self.stream = config.path.open("x") self.batch = 0 self.step_index = 0 def __getattr__(self, name): return getattr(self.config.env, name) def step(self, target): env = self.config.env target_tensor = torch.as_tensor(target) command, reached, position_error, rotation_error = keypose_command( env.current, target_tensor, env.gripper, env.config.control ) values = { "target": target_tensor, "tcp_before": env.current, "previous_gripper": env.gripper, "recomputed_command": command, "reached": reached, "position_error_m": position_error, "rotation_error_rad": rotation_error, } values = {k: v.detach().cpu().tolist() for k, v in values.items()} result = env.step(target) done = np.asarray(result[2]) | np.asarray(result[3]) if done.any() and not done.all(): raise ValueError("Keypose trace requires synchronous episode batches") for slot in range(env.num_envs): row = {key: value[slot] for key, value in values.items()} row.update( seed=self.config.seed_start + self.batch * env.num_envs + slot, step=self.step_index, done=bool(done[slot]), ) self.stream.write(json.dumps(row, allow_nan=False) + "\n") self.step_index += 1 if done.all(): self.batch += 1 self.step_index = 0 self.stream.flush() return result def finish(self): self.stream.close()