File size: 5,504 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
"""Observed TCP feedback for world-frame position/6D-orientation keypose commands."""

from typing import Any

import torch
from mani_skill.utils.geometry.rotation_conversions import (
    axis_angle_to_matrix,
    matrix_to_axis_angle,
    matrix_to_euler_angles,
    quaternion_to_matrix,
)
from pydantic import BaseModel, ConfigDict, PositiveFloat

from lim.action_encoding import ROTATION_SCALE, matrix_to_sixd, sixd_to_matrix


class KeyposeControlConfig(BaseModel, frozen=True):
    model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
    max_translation_m: PositiveFloat = 0.01
    """Maximum requested Cartesian displacement per 20 Hz control step."""
    max_rotation_rad: PositiveFloat = 0.05
    """Maximum requested SO(3) angle per control step, before controller decoding."""
    position_tolerance_m: PositiveFloat = 0.003
    """Measured TCP distance required before accepting the target gripper command."""
    rotation_tolerance_rad: PositiveFloat = 0.05
    """Measured angular distance required before accepting the target gripper command."""


def encode_keypose(pose, gripper):
    """Input xyz,wxyz; output world xyz, continuous6D rotation, continuous gripper."""
    if pose.shape[-1] != 7 or not torch.isfinite(pose).all():
        raise ValueError("Expected finite world xyz,wxyz poses")
    q = pose[..., 3:]
    if not torch.allclose(q.norm(dim=-1), torch.ones_like(q[..., 0]), atol=1e-4):
        raise ValueError("Keypose quaternions must be unit length")
    return torch.cat(
        [pose[..., :3], matrix_to_sixd(quaternion_to_matrix(q)), gripper[..., None]], -1
    )


def keypose_error(current, target):
    if current.shape[-1] != 7 or target.shape[-1] != 10:
        raise ValueError("Expected observed TCP7 and target10")
    if not torch.isfinite(current).all() or not torch.isfinite(target).all():
        raise ValueError("Nonfinite observed TCP or keypose target")
    delta = target[..., :3] - current[..., :3]
    rotation = sixd_to_matrix(target[..., 3:9]) @ quaternion_to_matrix(
        current[..., 3:]
    ).transpose(-1, -2)
    vector = matrix_to_axis_angle(rotation)
    return delta, vector


def keypose_command(current, target, previous_gripper, config: KeyposeControlConfig):
    """Pure observed-state controller; audited Panda root axes coincide with world."""
    delta, rotation = keypose_error(current, target)
    position_error = delta.norm(dim=-1)
    rotation_error = rotation.norm(dim=-1)
    reached = (position_error <= config.position_tolerance_m) & (
        rotation_error <= config.rotation_tolerance_rad
    )
    translation = (
        delta
        * (config.max_translation_m / position_error.clamp_min(1e-8)).clamp(max=1)[
            ..., None
        ]
    )
    vector = (
        rotation
        * (config.max_rotation_rad / rotation_error.clamp_min(1e-8)).clamp(max=1)[
            ..., None
        ]
    )
    # Euler exists ONLY at the installed low-level controller boundary. Targets
    # and SO(3) error/interpolation never learn or interpolate Euler coordinates.
    angles = (
        matrix_to_euler_angles(axis_angle_to_matrix(vector), "XYZ") / ROTATION_SCALE
    )
    angles = angles / angles.norm(dim=-1, keepdim=True).clamp(min=1)
    gripper = torch.where(reached, target[..., -1].clamp(-1, 1), previous_gripper)
    command = torch.cat(
        [(translation / 0.1).clamp(-1, 1), angles, gripper[..., None]], -1
    )
    return command, reached, position_error, rotation_error


class KeyposeEnvConfig(BaseModel, frozen=True):
    model_config = ConfigDict(
        arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
    )
    env: Any
    """Physical vector environment exposing full state25 observations."""
    control: KeyposeControlConfig = KeyposeControlConfig()
    """Pure keypose tracking and gripper synchronization settings."""


class KeyposeEnv:
    def __init__(self, config: KeyposeEnvConfig):
        import gymnasium as gym
        import numpy as np

        self.config = config
        self.current = None
        self.gripper = None
        self.action_space = gym.spaces.Box(
            -np.inf, np.inf, (config.env.num_envs, 10), dtype=np.float32
        )
        self.single_action_space = gym.spaces.Box(
            -np.inf, np.inf, (10,), dtype=np.float32
        )

    def __getattr__(self, name):
        return getattr(self.config.env, name)

    def remember(self, obs, reset=None):
        state = torch.as_tensor(obs["state"], dtype=torch.float32)
        if state.shape[-1] != 25:
            raise ValueError("Expected audited qpos9,qvel9,TCP7 state layout")
        self.current = state[:, 18:25].clone()
        # Panda PDJointPosMimicController maps [-1,1] to [-.01,.04] m.
        measured = ((state[:, 7:9].mean(-1) + 0.01) / 0.05 * 2 - 1).clamp(-1, 1)
        if reset is None:
            self.gripper = measured
        else:
            self.gripper = torch.where(torch.as_tensor(reset), measured, self.gripper)

    def reset(self, *args, **kwargs):
        obs, info = self.config.env.reset(*args, **kwargs)
        self.remember(obs)
        return obs, info

    def step(self, target):
        command, _, _, _ = keypose_command(
            self.current, torch.as_tensor(target), self.gripper, self.config.control
        )
        self.gripper = command[:, -1].clone()
        result = self.config.env.step(command.numpy())
        self.remember(result[0], result[2] | result[3])
        return result