File size: 12,548 Bytes
b5fb851
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
372
373
374
"""
Extensible RL interface for robotics environments.

This module provides the canonical observation and action interfaces
that work across different robot embodiments (manipulators, mobile robots,
navigation agents, etc.).

Key classes:
- Observation: Extensible observation with proprio dict, camera images, and extras
- Action: Extensible action with continuous and discrete channels

Conventional keys:
- ProprioKeys: Standard proprioceptive channel names
- ActionKeys: Standard action channel names
"""

from __future__ import annotations

import base64
from typing import Any

import numpy as np
from pydantic import BaseModel, ConfigDict, Field, field_validator

# =============================================================================
# Conventional Key Names
# =============================================================================


class ProprioKeys:
    """
    Conventional proprioceptive channel names.

    These are suggestions - environments can use any keys they want.
    Using these conventions improves interoperability between environments.
    """

    # End-effector state (single arm)
    EE_POS = "ee_pos"  # [x, y, z] meters
    EE_QUAT = "ee_quat"  # [x, y, z, w] quaternion
    EE_VEL_LIN = "ee_vel_lin"  # [vx, vy, vz] m/s
    EE_VEL_ANG = "ee_vel_ang"  # [wx, wy, wz] rad/s

    # Gripper
    GRIPPER = "gripper"  # [state] 0=open, 1=closed
    # or [f1, f2, ...] for multi-finger

    # Joint state
    JOINT_POS = "joint_pos"  # [j1, j2, ..., jN] radians
    JOINT_VEL = "joint_vel"  # [j1, j2, ..., jN] rad/s
    JOINT_TORQUE = "joint_torque"  # [t1, t2, ..., tN] Nm

    # Mobile base
    BASE_POS = "base_pos"  # [x, y, z] meters
    BASE_QUAT = "base_quat"  # [x, y, z, w] quaternion
    BASE_HEADING = "base_heading"  # [theta] radians (2D heading)
    BASE_VEL = "base_vel"  # [vx, vy, vtheta] or [vx, vy, vz, wx, wy, wz]

    # Dual arm (prefix with left_/right_)
    LEFT_EE_POS = "left_ee_pos"
    LEFT_EE_QUAT = "left_ee_quat"
    LEFT_GRIPPER = "left_gripper"
    RIGHT_EE_POS = "right_ee_pos"
    RIGHT_EE_QUAT = "right_ee_quat"
    RIGHT_GRIPPER = "right_gripper"

    # Sensing
    FORCE = "force"  # [fx, fy, fz] Newtons
    TORQUE = "torque"  # [tx, ty, tz] Nm
    IMU_ACC = "imu_acc"  # [ax, ay, az] m/s^2
    IMU_GYRO = "imu_gyro"  # [wx, wy, wz] rad/s


class ActionKeys:
    """Conventional action channel names."""

    # Cartesian control
    EE_TWIST = "ee_twist"  # [vx, vy, vz, wx, wy, wz] normalized
    EE_POS_TARGET = "ee_pos_target"  # [x, y, z] position target

    # Gripper
    GRIPPER = "gripper"  # [cmd] 0=open, 1=closed

    # Joint control
    JOINT_VEL = "joint_vel"  # [j1, j2, ..., jN] normalized
    JOINT_POS_TARGET = "joint_pos_target"  # [j1, ..., jN] position targets

    # Mobile base
    BASE_VEL = "base_vel"  # [vx, vy, vtheta] normalized

    # Dual arm
    LEFT_TWIST = "left_twist"
    LEFT_GRIPPER = "left_gripper"
    RIGHT_TWIST = "right_twist"
    RIGHT_GRIPPER = "right_gripper"


# =============================================================================
# Image Encoding/Decoding
# =============================================================================


def _encode_image(img: np.ndarray) -> dict[str, Any]:
    """Encode image as base64 with metadata for efficient serialization."""
    return {
        "data": base64.b64encode(img.tobytes()).decode("ascii"),
        "shape": list(img.shape),
        "dtype": str(img.dtype),
    }


def _decode_image(encoded: dict[str, Any] | list) -> np.ndarray:
    """Decode image from base64 or nested list format."""
    if isinstance(encoded, list):
        # Legacy nested list format
        return np.array(encoded, dtype=np.uint8)
    # Base64 encoded format
    data = base64.b64decode(encoded["data"])
    shape = tuple(encoded["shape"])
    dtype = np.dtype(encoded["dtype"])
    return np.frombuffer(data, dtype=dtype).reshape(shape)


# =============================================================================
# Observation Class
# =============================================================================


class Observation(BaseModel):
    """
    Extensible observation for any robot embodiment.

    Structure:
    - `rgb`: Camera images (keyed by camera name)
    - `depth`: Depth images (keyed by camera name)
    - `proprio`: Proprioceptive channels (keyed by channel name)
    - `cam_intrinsics`: Camera intrinsics matrices (keyed by camera name)
    - `cam_extrinsics`: Camera extrinsics matrices (keyed by camera name)
    - `extra`: Arbitrary additional data

    Examples:
        # Single-arm manipulator
        obs = Observation(
            rgb={"wrist": img},
            proprio={
                "ee_pos": [0.4, 0.0, 0.2],
                "ee_quat": [0, 0, 0, 1],
                "gripper": [0.5],
            },
        )

        # Navigation agent
        obs = Observation(
            rgb={"ego": img},
            proprio={
                "base_pos": [1.2, 0.0, 3.4],
                "base_heading": [1.57],
            },
            extra={"task_prompt": "Pick up the apple."},
        )
    """

    model_config = ConfigDict(extra="forbid")

    rgb: dict[str, dict | list] = Field(default_factory=dict)
    depth: dict[str, dict | list] = Field(default_factory=dict)
    proprio: dict[str, list[float]] = Field(default_factory=dict)
    cam_intrinsics: dict[str, list[list[float]]] = Field(default_factory=dict)
    cam_extrinsics: dict[str, list[list[float]]] = Field(default_factory=dict)
    extra: dict[str, Any] = Field(default_factory=dict)

    @field_validator("rgb", "depth", mode="before")
    @classmethod
    def _coerce_images(cls, value: Any) -> dict[str, Any]:
        if value is None:
            return {}
        if isinstance(value, dict):
            result = {}
            for k, v in value.items():
                if isinstance(v, np.ndarray):
                    result[k] = _encode_image(v)
                else:
                    result[k] = v
            return result
        return value

    @field_validator("proprio", mode="before")
    @classmethod
    def _coerce_proprio(cls, value: Any) -> dict[str, list[float]]:
        if value is None:
            return {}
        result = {}
        for k, v in value.items():
            if isinstance(v, np.ndarray):
                result[k] = v.tolist()
            elif isinstance(v, (int, float)):
                result[k] = [float(v)]
            else:
                result[k] = list(v)
        return result

    def get_image(self, camera: str) -> np.ndarray | None:
        """Get decoded RGB image for a camera."""
        if camera not in self.rgb:
            return None
        return _decode_image(self.rgb[camera])

    def get_depth(self, camera: str) -> np.ndarray | None:
        """Get decoded depth image for a camera."""
        if camera not in self.depth:
            return None
        return _decode_image(self.depth[camera])

    @property
    def images(self) -> dict[str, np.ndarray]:
        """Get all RGB images as numpy arrays."""
        return {name: _decode_image(data) for name, data in self.rgb.items()}

    def get_proprio(self, key: str) -> np.ndarray | None:
        """Get a proprioceptive channel as numpy array."""
        if key not in self.proprio:
            return None
        return np.array(self.proprio[key], dtype=np.float32)

    def proprio_array(self, keys: list[str] | None = None) -> np.ndarray:
        """
        Concatenate proprio channels into flat array.

        Args:
            keys: Channel names to include (default: all, sorted alphabetically)
        """
        if keys is None:
            keys = sorted(self.proprio.keys())
        arrays = [self.proprio[k] for k in keys if k in self.proprio]
        if not arrays:
            return np.array([], dtype=np.float32)
        return np.concatenate(arrays).astype(np.float32)

    def to_payload(self, include_images: bool = True) -> dict[str, Any]:
        """Serialize for network transport."""
        data = self.model_dump(mode="python")
        if not include_images:
            data["rgb"] = {}
            data["depth"] = {}
        return data


# =============================================================================
# Action Class
# =============================================================================


class Action(BaseModel):
    """
    Extensible action for any robot embodiment.

    Structure:
    - `continuous`: Continuous control channels (normalized to [-1, 1] or [0, 1])
    - `discrete`: Discrete action selections
    - `extra`: Arbitrary additional data

    Examples:
        # Manipulator action
        action = Action(continuous={
            "ee_twist": [0.1, 0, 0, 0, 0, 0],
            "gripper": [1.0],
        })

        # Navigation action
        action = Action(
            discrete={"nav": 0},  # 0=forward
            continuous={"gripper": [0.8]},
        )
    """

    model_config = ConfigDict(extra="forbid")

    continuous: dict[str, list[float]] = Field(default_factory=dict)
    discrete: dict[str, int] = Field(default_factory=dict)
    extra: dict[str, Any] = Field(default_factory=dict)

    @field_validator("continuous", mode="before")
    @classmethod
    def _coerce_continuous(cls, value: Any) -> dict[str, list[float]]:
        if value is None:
            return {}
        result = {}
        for k, v in value.items():
            if isinstance(v, np.ndarray):
                result[k] = v.tolist()
            elif isinstance(v, (int, float)):
                result[k] = [float(v)]
            else:
                result[k] = list(v)
        return result

    def get_continuous(self, key: str) -> np.ndarray | None:
        """Get a continuous channel as numpy array."""
        if key not in self.continuous:
            return None
        return np.array(self.continuous[key], dtype=np.float32)

    def continuous_array(self, keys: list[str] | None = None) -> np.ndarray:
        """Concatenate continuous channels into flat array."""
        if keys is None:
            keys = sorted(self.continuous.keys())
        arrays = [self.continuous[k] for k in keys if k in self.continuous]
        if not arrays:
            return np.array([], dtype=np.float32)
        return np.concatenate(arrays).astype(np.float32)

    @classmethod
    def from_array(cls, array: Any, schema: dict[str, int]) -> Action:
        """
        Construct from flat array given a schema.

        Args:
            array: Flat numpy array of action values
            schema: Mapping of channel names to sizes, e.g. {"ee_twist": 6, "gripper": 1}
        """
        arr = np.asarray(array, dtype=np.float32).flatten()
        continuous: dict[str, list[float]] = {}
        idx = 0
        for key, size in schema.items():
            continuous[key] = arr[idx : idx + size].tolist()
            idx += size
        return cls(continuous=continuous)

    def to_array(self, keys: list[str] | None = None) -> np.ndarray:
        """Convert to flat array for backward compatibility."""
        return self.continuous_array(keys)


# =============================================================================
# Helper Functions
# =============================================================================


def coerce_action(action: Any, schema: dict[str, int] | None = None) -> Action:
    """
    Coerce various formats to Action.

    Args:
        action: Action in any supported format (Action, dict, or array)
        schema: For array inputs, mapping of channel names to sizes
    """
    if isinstance(action, Action):
        return action
    if isinstance(action, dict):
        return Action.model_validate(action)
    if isinstance(action, np.ndarray) or hasattr(action, "__iter__"):
        if schema is None:
            # Default schema for backward compatibility with 7-element actions
            schema = {ActionKeys.EE_TWIST: 6, ActionKeys.GRIPPER: 1}
        return Action.from_array(np.asarray(action), schema)
    raise TypeError(f"Cannot coerce {type(action)} to Action")


def normalize_quaternion(quat: np.ndarray) -> np.ndarray:
    """Normalize a quaternion to unit length."""
    norm = np.linalg.norm(quat)
    if norm <= 0:
        return np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float32)
    return (quat / norm).astype(np.float32)


class Step(BaseModel):
    """A step containing observation and action (for trajectories)."""

    model_config = ConfigDict(extra="forbid")

    obs: Observation
    action: Action