File size: 9,573 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
"""Measured gripper completion and a CPU SAPIEN feedback adapter."""

from collections import defaultdict
from typing import Any

import numpy as np
from pydantic import BaseModel, ConfigDict, PositiveFloat, PositiveInt


class GripperCompletionConfig(BaseModel, frozen=True):
    model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
    position_tolerance_m: PositiveFloat = 0.001
    """Maximum absolute position error of each finger for target completion."""
    velocity_tolerance_m_s: PositiveFloat = 0.005
    """Maximum absolute velocity of either finger for stable completion."""
    stable_steps: PositiveInt = 3
    """Consecutive post-action feedback samples required for the same condition."""
    timeout_steps: PositiveInt = 40
    """Maximum actual gripper control steps; timeout is not completion."""
    minimum_contact_force_n: PositiveFloat = 0.5
    """Per-finger force threshold for bilateral contact against one external body."""
    detect_arrest: bool = False
    """Recognise a driven-but-frozen finger as arrested instead of waiting out the
    timeout. The original contract only exits a BLOCKED CLOSING, because
    closing_against_object requires position > target; a blocked opening has no
    exit and its finite-difference velocity reads ~0 while the joint is still
    driven. Default false preserves every previously scored run."""
    arrest_encoder_tolerance_m: PositiveFloat = 0.0001
    """Maximum encoder displacement per step still counted as frozen."""
    arrest_drive_velocity_m_s: PositiveFloat = 0.05
    """Minimum instantaneous joint velocity proving the drive is still pushing."""
    arrest_steps: PositiveInt = 5
    """Consecutive frozen-but-driven samples required to declare an arrest."""


class GripperMeasurement(BaseModel, frozen=True):
    model_config = ConfigDict(
        extra="forbid", use_attribute_docstrings=True, allow_inf_nan=False
    )
    positions_m: tuple[float, float]
    """Measured positions of the two finger joints."""
    velocities_m_s: tuple[float, float]
    """Measured encoder displacement over the last physical control interval."""
    targets_m: tuple[float, float]
    """Command mapped to physical joint coordinates and clipped to joint limits."""
    bilateral_contact: bool
    """Both finger inner sides currently contact the same external body."""
    contact_forces_n: tuple[float, float] = (0.0, 0.0)
    """Force components along the inner-finger normals for the accepted pair."""
    joint_velocities_m_s: tuple[float, float] = (0.0, 0.0)
    """Instantaneous simulator joint velocities, logged separately for diagnosis."""


class GripperCompletion:
    def __init__(self, config: GripperCompletionConfig):
        self.config = config
        self.steps = 0
        self.streak = 0
        self.arrested_streak = 0
        self.condition = None
        self.status = "running"

    def update(self, measured: GripperMeasurement):
        if self.status != "running":
            raise RuntimeError("Completion monitor already ended")
        self.steps += 1
        position = np.asarray(measured.positions_m)
        target = np.asarray(measured.targets_m)
        error = np.abs(position - target)
        stationary = (
            max(abs(v) for v in measured.velocities_m_s)
            <= self.config.velocity_tolerance_m_s
        )
        at_target = bool(np.all(error <= self.config.position_tolerance_m))
        # Contact can complete a closing command, never a blocked opening.
        closing_against_object = bool(
            np.all(position >= target - self.config.position_tolerance_m)
            and np.any(position > target + self.config.position_tolerance_m)
        )
        condition = None
        if stationary:
            if at_target:
                condition = "target_reached"
            elif closing_against_object and measured.bilateral_contact:
                condition = "contact_stable"
        self.streak = (
            self.streak + 1
            if condition is not None and condition == self.condition
            else int(condition is not None)
        )
        self.condition = condition
        # Frozen encoder while the drive still pushes: the finger is held by
        # something. Never reported as completion, since the command was not met.
        frozen = (
            max(abs(v) for v in measured.velocities_m_s)
            <= self.config.arrest_encoder_tolerance_m
        )
        driven = (
            max(abs(v) for v in measured.joint_velocities_m_s)
            >= self.config.arrest_drive_velocity_m_s
        )
        arrested = bool(frozen and driven and not at_target)
        self.arrested_streak = self.arrested_streak + 1 if arrested else 0
        if self.streak >= self.config.stable_steps:
            self.status = "complete"
        elif (
            self.config.detect_arrest
            and self.arrested_streak >= self.config.arrest_steps
        ):
            self.status = "arrested"
        elif self.steps >= self.config.timeout_steps:
            self.status = "timeout"
        return {
            **measured.model_dump(mode="json"),
            "position_error_m": error.tolist(),
            "stationary": stationary,
            "condition": condition,
            "stable_steps": self.streak,
            "arrested": arrested,
            "arrested_steps": self.arrested_streak,
            "elapsed_steps": self.steps,
            "status": self.status,
        }


class FeedbackReaderConfig(BaseModel, frozen=True):
    model_config = ConfigDict(
        arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
    )
    env: Any
    """One CPU Panda physical environment exposing encoders and contact impulses."""
    completion: GripperCompletionConfig = GripperCompletionConfig()
    """Contact-force threshold shared with the completion contract."""


class PandaGripperFeedback:
    def __init__(self, config: FeedbackReaderConfig):
        self.config = config
        base = config.env.unwrapped
        if base.gpu_sim_enabled or base.num_envs != 1:
            raise ValueError("Feedback adapter requires a single CPU environment")
        self.robot = base.agent.robot
        self.fingers = (base.agent.finger1_link, base.agent.finger2_link)
        self.finger_entities = tuple(f._bodies[0].entity for f in self.fingers)
        self.robot_entities = {
            link._bodies[0].entity for link in self.robot.get_links()
        }
        self.controller = base.agent.controller.controllers["gripper"]
        if (
            self.controller.config.use_delta
            or not self.controller.config.normalize_action
        ):
            raise ValueError("Expected normalized absolute gripper commands")
        self.joint_indices = [
            self.robot.active_joints_map[name].active_index[0].item()
            for name in base.agent.gripper_joint_names
        ]
        self.limits = self.robot.get_qlimits()[0, self.joint_indices].cpu().numpy()
        self.previous_positions = (
            self.robot.get_qpos()[0, self.joint_indices].cpu().numpy().copy()
        )

    def read(self, command):
        base = self.config.env.unwrapped
        # Backend contact adapter: no cube identity, task success, or geometry is
        # used. Contact against arbitrary external bodies is tactile-style input.
        forces = defaultdict(lambda: np.zeros((2, 3)))
        for contact in base.scene.get_contacts():
            entities = [body.entity for body in contact.bodies]
            for finger, entity in enumerate(self.finger_entities):
                if entity not in entities:
                    continue
                index = entities.index(entity)
                other = entities[1 - index]
                if other in self.robot_entities:
                    continue
                impulse = np.sum([point.impulse for point in contact.points], axis=0)
                forces[other][finger] += (
                    impulse * (1 if index == 0 else -1) / base.scene.px.timestep
                )
        directions = np.stack(
            [
                self.fingers[0].pose.to_transformation_matrix()[0, :3, 1].cpu().numpy(),
                -self.fingers[1]
                .pose.to_transformation_matrix()[0, :3, 1]
                .cpu()
                .numpy(),
            ]
        )
        bilateral = False
        magnitudes = np.zeros(2)
        for pair in forces.values():
            normal_forces = (pair * directions).sum(axis=1)
            if np.all(normal_forces >= self.config.completion.minimum_contact_force_n):
                bilateral = True
                magnitudes = normal_forces
                break
        lower, upper = self.controller.config.lower, self.controller.config.upper
        requested = (float(np.clip(command, -1, 1)) + 1) / 2 * (upper - lower) + lower
        targets = np.clip(np.full(2, requested), self.limits[:, 0], self.limits[:, 1])
        positions = self.robot.get_qpos()[0, self.joint_indices].cpu().numpy().copy()
        velocity = (positions - self.previous_positions) / base.control_timestep
        self.previous_positions = positions
        return GripperMeasurement(
            positions_m=tuple(positions),
            velocities_m_s=tuple(velocity),
            joint_velocities_m_s=tuple(
                self.robot.get_qvel()[0, self.joint_indices].cpu().tolist()
            ),
            targets_m=tuple(targets),
            bilateral_contact=bilateral,
            contact_forces_n=tuple(magnitudes),
        )