File size: 3,833 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
"""Measured observations shared by all policy variants; no simulator labels."""

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


class ObservationConfig(BaseModel, frozen=True):
    model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
    points: PositiveInt = 256
    """Total points, split equally between visible role colors and context."""


def as_numpy(value):
    if hasattr(value, "detach"):
        return value.detach().cpu().numpy()
    return np.asarray(value)


def sample_points(points: np.ndarray, count: int) -> np.ndarray:
    if len(points) == 0:
        return np.zeros((count, 6), dtype=np.float32)
    # Deterministic sampling; independent of labels, episode seed, and test set.
    indices = np.linspace(0, len(points) - 1, count).astype(np.int64)
    return points[indices].astype(np.float32)


def cloud_from_rgbd(obs: dict) -> tuple[np.ndarray, np.ndarray]:
    """Unproject millimeter optical depth using calibrated CV cameras."""
    coordinates, colors = [], []
    for name, view in obs["sensor_data"].items():
        depth = as_numpy(view["depth"]).squeeze().astype(np.float32) / 1000
        rgb = as_numpy(view["rgb"]).reshape(-1, 3)
        height, width = depth.shape
        v, u = np.mgrid[:height, :width]
        pixels = np.stack([u + 0.5, v + 0.5, np.ones_like(u)], axis=-1).reshape(-1, 3)
        params = obs["sensor_param"][name]
        intrinsic = as_numpy(params["intrinsic_cv"]).reshape(3, 3)
        extrinsic = as_numpy(params["extrinsic_cv"]).reshape(3, 4)
        camera_xyz = (pixels @ np.linalg.inv(intrinsic).T) * depth.reshape(-1, 1)
        world_xyz = (camera_xyz - extrinsic[:, 3]) @ extrinsic[:, :3]
        coordinates.append(np.c_[world_xyz, depth.reshape(-1) > 0].astype(np.float32))
        colors.append(rgb)
    return np.concatenate(coordinates), np.concatenate(colors)


def encode_observation(obs: dict, config: ObservationConfig) -> dict[str, np.ndarray]:
    """Only camera point XYZ/RGB, joint positions/velocities and measured TCP pose."""
    if obs.get("sensor_data") and "depth" in next(iter(obs["sensor_data"].values())):
        xyzw, raw_rgb = cloud_from_rgbd(obs)
    else:
        xyzw = as_numpy(obs["pointcloud"]["xyzw"]).reshape(-1, 4)
        raw_rgb = as_numpy(obs["pointcloud"]["rgb"]).reshape(-1, 3)
    rgb = raw_rgb.astype(np.float32) / 255
    tcp = as_numpy(obs["extra"]["tcp_pose"]).reshape(-1, 7)[0]
    qpos = as_numpy(obs["agent"]["qpos"]).reshape(-1, 9)[0]
    qvel = as_numpy(obs["agent"]["qvel"]).reshape(-1, 9)[0]
    valid = (xyzw[:, 3] > 0) & np.isfinite(xyzw).all(axis=1)
    xyz = xyzw[:, :3]
    valid &= (xyz[:, 2] > 0.005) & (xyz[:, 2] < 0.6)
    valid &= (abs(xyz[:, 0]) < 0.5) & (abs(xyz[:, 1]) < 0.5)
    xyz, rgb = xyz[valid], rgb[valid]
    source = (
        (rgb[:, 0] > 0.25)
        & (rgb[:, 0] > 1.8 * rgb[:, 1])
        & (rgb[:, 0] > 1.8 * rgb[:, 2])
    )
    target = (
        (rgb[:, 1] > 0.25)
        & (rgb[:, 1] > 1.8 * rgb[:, 0])
        & (rgb[:, 1] > 1.8 * rgb[:, 2])
    )
    target_center = xyz[target].mean(axis=0) if target.any() else np.zeros(3)
    points = np.concatenate([(xyz - tcp[:3]) / 0.3, rgb], axis=1)
    role_count = config.points // 4
    selected = np.concatenate(
        [
            sample_points(points[source], role_count),
            sample_points(points[target], role_count),
            sample_points(points, config.points - 2 * role_count),
        ]
    )
    state = np.concatenate([qpos, qvel, tcp, target_center, [float(target.any())]])
    return {
        "points": selected,
        "state": state.astype(np.float32),
        "tcp": tcp.astype(np.float32),
        "target": np.asarray(target_center, dtype=np.float32),
        "counts": np.array([len(xyzw), len(xyz), int(source.sum()), int(target.sum())]),
    }