"""Latch a predicted world pose through its path and measured gripper completion.""" from collections import deque from typing import Any import numpy as np import torch from pydantic import ( BaseModel, ConfigDict, NonNegativeInt, PositiveFloat, model_validator, ) from lim.gripper_feedback import ( GripperCompletion, GripperCompletionConfig, GripperMeasurement, ) from lim.keypose_control import KeyposeControlConfig, keypose_error class PlannerConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) env: Any """Single physical Panda environment; only robot state is used by planning.""" joint_velocity_scale: PositiveFloat = 0.9 """Multiplier on MPLib's robot joint velocity limits, matching the expert.""" joint_acceleration_scale: PositiveFloat = 0.9 """Multiplier on joint acceleration limits, matching the expert.""" class MplibKeyposePlanner: def __init__(self, config: PlannerConfig): from mani_skill.examples.motionplanning.panda.motionplanner import ( PandaArmMotionPlanningSolver, ) self.config = config self.last_status = "not_planned" self.solver = PandaArmMotionPlanningSolver( config.env, debug=False, vis=False, base_pose=config.env.unwrapped.agent.robot.pose, visualize_target_grasp_pose=False, print_env_info=False, joint_vel_limits=config.joint_velocity_scale, joint_acc_limits=config.joint_acceleration_scale, ) def plan(self, target): import sapien from mani_skill.utils.geometry.rotation_conversions import matrix_to_quaternion from lim.action_encoding import sixd_to_matrix target = torch.as_tensor(target, dtype=torch.float32) if target.shape != (10,) or not torch.isfinite(target).all(): raise ValueError("Expected a finite world keypose10") quaternion = matrix_to_quaternion(sixd_to_matrix(target[3:9])).numpy() pose = sapien.Pose(target[:3].numpy(), quaternion) # Same screw planner and native retry as collection. No object geometry, # expert phase, grasp labels, extra obstacles or fallback goals supplied. result = self.solver.move_to_pose_with_screw(pose, dry_run=True) if isinstance(result, int): self.last_status = "native_planning_failed" return None position = np.asarray(result["position"], dtype=np.float32) if position.ndim == 2 and position.shape == (0, 7): # Native TOPP can sample zero points when duration < one control # interval. There is no trajectory to execute; record a failed plan. self.last_status = "native_empty_trajectory" return None if ( position.ndim != 2 or position.shape[1] != 7 or len(position) == 0 or not np.isfinite(position).all() ): raise ValueError("Invalid planned joint trajectory") self.last_status = "Success" return result class PlannedExecutorConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) control: KeyposeControlConfig = KeyposeControlConfig() """Original pose tolerances for diagnostics only; they do not block completion.""" gripper_completion: GripperCompletionConfig = GripperCompletionConfig() """Measured finger target/contact stability required before querying again.""" initial_gripper: float = 1.0 """Measured initial finger position mapped to the continuous command range.""" resume_after_incomplete: bool = False """Return to prediction after a gripper timeout or arrest instead of ending the episode. The original contract has no path back from gripper_timeout, so a single unmet gripper command freezes the remaining budget with zero further queries. Default false preserves every previously scored run.""" carry_gripper_feedback: bool = False """Reuse fresh stable feedback from the motion only when the next gripper command is exactly the same executed float32 command after clipping. A changed command retains the original post-path feedback protocol.""" motion_replan_steps: NonNegativeInt = 0 """Actual motion steps between fresh target/plan attempts; zero keeps full paths.""" @model_validator(mode="after") def check_motion_replan(self): if self.motion_replan_steps and ( self.resume_after_incomplete or self.carry_gripper_feedback ): raise ValueError("Motion replanning requires isolated completion semantics") return self class PlannedKeyposeExecutor: def __init__(self, config: PlannedExecutorConfig): self.config = config self.gripper = float(config.initial_gripper) self.phase = "ready" self.target = None self.path = None self.index = 0 self.completion = None # Cumulative, because resuming clears the phase that used to record it. self.gripper_timeouts = 0 self.gripper_arrests = 0 self.gripper_feedback_carried = 0 self.motion_feedback = deque(maxlen=config.gripper_completion.stable_steps) self.motion_observed_steps = 0 self.motion_command = None self.completed_target = None self.completed_target_query = None self.completed_goals = 0 self.active_query = None self.goal_id = 0 self.path_revision = 0 self.accepted_paths = 0 self.replan_attempts = 0 self.replan_failures = 0 self.goal_replan_attempts = 0 self.motion_steps_since_attempt = 0 self.goal_motion_steps = 0 self.total_motion_steps = 0 self._motion_step_pending = False @property def needs_prediction(self): return self.phase == "ready" @property def needs_motion_replan(self): return bool( self.config.motion_replan_steps and self.phase == "trajectory" and self.index < len(self.path) and not self._motion_step_pending and self.motion_steps_since_attempt >= self.config.motion_replan_steps ) @staticmethod def _checked_target(target): target = torch.as_tensor(target, dtype=torch.float32).clone() if target.shape != (10,) or not torch.isfinite(target).all(): raise ValueError("Expected a finite world keypose10") return target @staticmethod def _checked_path(path): path = np.asarray(path, dtype=np.float32).copy() if ( path.ndim != 2 or path.shape[1] != 7 or not len(path) or not np.isfinite(path).all() ): raise ValueError("Expected a nonempty finite N x 7 planned trajectory") return path def begin(self, target, path, current_qpos, *, source_query=None): if not self.needs_prediction: raise RuntimeError("Cannot replace an unfinished keypose trajectory") self.target = self._checked_target(target) self.active_query = source_query self.goal_id += 1 self.path_revision = 0 self.goal_replan_attempts = 0 self.motion_steps_since_attempt = 0 self.goal_motion_steps = 0 self._motion_step_pending = False self.index = 0 self.completion = None self.motion_feedback.clear() self.motion_observed_steps = 0 self.motion_command = None if path is None: self.path = np.asarray(current_qpos, dtype=np.float32)[None, :7].copy() self.phase = "planning_failed" else: self.path = self._checked_path(path) self.accepted_paths += 1 self.phase = "trajectory" def replace_motion_plan(self, target, path, *, source_query): """Resolve one due dry-run attempt without completing the active goal. None means planner failure: preserve target/path/index/gripper and only reset the retry interval. Invalid numeric output raises before mutation. """ if not self.needs_motion_replan: raise RuntimeError("Motion replanning requires a due unfinished trajectory") candidate = self._checked_target(target) candidate_path = None if path is None else self._checked_path(path) self.replan_attempts += 1 self.goal_replan_attempts += 1 self.motion_steps_since_attempt = 0 if candidate_path is None: self.replan_failures += 1 return False self.target, self.path = candidate, candidate_path self.active_query = source_query self.index = 0 self.path_revision += 1 self.accepted_paths += 1 return True def observe_motion_step(self): """Acknowledge env.step, never an inference call or merely built command.""" if not self.config.motion_replan_steps or not self._motion_step_pending: raise RuntimeError( "Motion accounting requires one executed pending command" ) self._motion_step_pending = False self.motion_steps_since_attempt += 1 self.goal_motion_steps += 1 self.total_motion_steps += 1 def _publish_completed_target(self): self.completed_target = self.target.clone() self.completed_target_query = self.active_query self.completed_goals += 1 def command(self, current_tcp): if self.needs_prediction: raise RuntimeError("Predict before requesting the next command") if self.config.motion_replan_steps and self._motion_step_pending: raise RuntimeError( "Acknowledge the physical motion step before a new command" ) delta, rotation = keypose_error(torch.as_tensor(current_tcp), self.target) position_error, rotation_error = float(delta.norm()), float(rotation.norm()) reached = ( position_error <= self.config.control.position_tolerance_m and rotation_error <= self.config.control.rotation_tolerance_rad ) if self.phase == "path_complete": self.phase = "gripper" self.gripper = float(self.target[-1].clamp(-1, 1)) self.completion = GripperCompletion(self.config.gripper_completion) phase = self.phase index = self.index if phase == "trajectory" else len(self.path) - 1 command = np.r_[self.path[index], self.gripper].astype(np.float32) if phase == "trajectory": self._motion_step_pending = bool(self.config.motion_replan_steps) self.motion_command = float(command[-1]) self.index += 1 if self.index == len(self.path): self.phase = "path_complete" return command, { "phase": phase, "path_index": index, "path_length": len(self.path), "reached": reached, "position_error_m": position_error, "rotation_error_rad": rotation_error, } def begin_gripper(self, target, current_qpos, *, source_query=None): """Execute a predicted gripper event while holding the measured arm. No trajectory step or pose correction precedes the command. Feedback and timeout semantics are exactly the same as the ordinary post-path phase. """ self.begin( target, np.asarray(current_qpos)[None, :7], current_qpos, source_query=source_query, ) self.phase = "gripper" self.gripper = float(self.target[-1].clamp(-1, 1)) self.completion = GripperCompletion(self.config.gripper_completion) def observe_motion_gripper(self, measured: GripperMeasurement): """Observe one executed path step, without ever interrupting its trajectory. Replay the most recent stability window through the existing predicate. A fresh monitor makes a previously complete window revocable when contact is lost; it never calls update() on an already ended completion monitor. Motion timeout/arrest cannot prematurely stop the remaining arm path. """ if not self.config.carry_gripper_feedback: raise RuntimeError("Motion feedback carry is not enabled") if self.phase not in ("trajectory", "path_complete") or ( self.motion_observed_steps != self.index - 1 ): raise RuntimeError("Motion feedback requires one newly executed path step") self.motion_observed_steps += 1 if self.motion_feedback and ( self.motion_feedback[-1].targets_m != measured.targets_m ): self.motion_feedback.clear() self.motion_feedback.append(measured) completion_config = self.config.gripper_completion monitor = GripperCompletion( completion_config.model_copy( update={ "timeout_steps": max( completion_config.timeout_steps, completion_config.stable_steps ), "detect_arrest": False, } ) ) for sample in self.motion_feedback: row = monitor.update(sample) # Compare the actual actuator command values, not gripper sign, measured # finger opening, or a tolerance that could erase a real command change. requested = float(np.float32(float(self.target[-1].clamp(-1, 1)))) unchanged = requested == self.motion_command carried = ( self.phase == "path_complete" and unchanged and row["status"] == "complete" ) if carried: self._publish_completed_target() self.phase = "ready" self.gripper_feedback_carried += 1 return { **row, "window_samples": len(self.motion_feedback), "motion_steps_observed": self.motion_observed_steps, "motion_gripper_command": self.motion_command, "target_gripper_command": requested, "same_gripper_command": unchanged, "carried_to_path_completion": carried, } def observe_gripper(self, measured: GripperMeasurement): """Consume feedback ONLY after a physical gripper command has executed.""" if self.phase != "gripper": raise RuntimeError("Gripper feedback requires an executed gripper step") row = self.completion.update(measured) if row["status"] == "complete": self._publish_completed_target() self.phase = "ready" elif row["status"] in ("timeout", "arrested"): if row["status"] == "timeout": self.gripper_timeouts += 1 else: self.gripper_arrests += 1 # Resuming records the unmet command and keeps the loop alive; it never # claims the gripper reached its target. self.phase = ( "ready" if self.config.resume_after_incomplete else f"gripper_{row['status']}" ) return row