File size: 3,426 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
"""AWE-style waypoint selection on dense controller targets.

Shi et al. (CoRL 2023) choose the fewest waypoints such that linear
interpolation between consecutive waypoints stays within a distance threshold
of every intermediate state, by dynamic programming. Here the states are the
dense controller target positions of one demonstration; gripper command
changes are forced waypoints so no interpolated segment spans a gripper event.
"""

from itertools import pairwise

import numpy as np


def segment_error(points: np.ndarray, start: int, end: int) -> float:
    """Largest distance from points[start+1:end] to the segment start->end."""
    if end - start < 2:
        return 0.0
    a, b = points[start], points[end]
    inner = points[start + 1 : end]
    direction = b - a
    length = float(direction @ direction)
    if length == 0.0:
        return float(np.linalg.norm(inner - a, axis=1).max())
    t = np.clip((inner - a) @ direction / length, 0.0, 1.0)
    return float(np.linalg.norm(inner - (a + t[:, None] * direction), axis=1).max())


def _piece(points, start, end, threshold):
    """Fewest waypoints in (start, end] covering points[start..end]."""
    cost = {start: 0}
    previous = {}
    for i in range(start + 1, end + 1):
        best = None
        for j in range(i - 1, start - 1, -1):
            if j not in cost or segment_error(points, j, i) > threshold:
                continue
            if best is None or cost[j] + 1 < best[0]:
                best = (cost[j] + 1, j)
        # Adjacent points are always a valid segment, so best exists.
        cost[i], previous[i] = best
    chosen, i = [], end
    while i != start:
        chosen.append(i)
        i = previous[i]
    return sorted(chosen)


def select_waypoints(positions, threshold: float, gripper=None) -> np.ndarray:
    """Waypoint indices into positions (n x d), always including n-1.

    Index 0 is the start anchor, not a waypoint. Where the gripper command
    changes between i-1 and i, both i-1 and i are forced waypoints.
    """
    points = np.asarray(positions, dtype=np.float64)
    if points.ndim != 2 or len(points) < 1 or not np.isfinite(points).all():
        raise ValueError("Expected a finite n x d position array")
    if threshold <= 0:
        raise ValueError("Waypoint threshold must be positive")
    n = len(points)
    anchors = {0, n - 1}
    if gripper is not None:
        command = np.asarray(gripper)
        if command.shape != (n,):
            raise ValueError("Gripper commands must align with positions")
        for i in np.flatnonzero(command[1:] != command[:-1]) + 1:
            anchors.update((int(i) - 1, int(i)))
    anchors = sorted(anchors)
    if n == 1:
        return np.array([0], dtype=np.int64)
    chosen = set(anchors[1:])
    for start, end in pairwise(anchors):
        chosen.update(_piece(points, start, end, threshold))
    return np.array(sorted(chosen), dtype=np.int64)


def next_waypoint(length: int, waypoints) -> np.ndarray:
    """For each action time t, the first waypoint strictly after t (last maps to itself)."""
    points = np.asarray(waypoints, dtype=np.int64)
    if len(points) == 0 or points[-1] != length - 1 or np.any(np.diff(points) <= 0):
        raise ValueError("Waypoints must be increasing and end at the last action")
    index = np.searchsorted(points, np.arange(length), side="right")
    return points[np.minimum(index, len(points) - 1)]