File size: 15,395 Bytes
0a3f650
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
"""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