File size: 14,794 Bytes
3e56913
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""FOV-limited object memory ("object bank") shared by training-label generation and the eval agent.

An object enters the bank when it is inside the front camera's field of view, within range and not
occluded (BEV ray test against the other boxes). While visible its state is the ground-truth state;
once it leaves the view it is propagated with constant velocity in the world frame until it has been
unseen for too long or has drifted too far away. Every frame the bank is rendered into a fixed-size
table of per-object rows in the current ego frame (x forward, y right, CARLA convention).

The same class runs offline over SimLingo logs (scripts/build_object_bank.py) and online in the
Bench2Drive agent on privileged CARLA state (team_code/oracle_objects.py); only the observation source
differs.
"""
from dataclasses import dataclass
from typing import List, Optional

import numpy as np

CLASS_CAR, CLASS_WALKER, CLASS_STATIC = 0, 1, 2
NUM_CLASSES = 3

# raw row layout written to the bank files
RAW_X, RAW_Y, RAW_YAW, RAW_SPEED, RAW_LENGTH, RAW_WIDTH, RAW_CLASS, RAW_VISIBLE, RAW_UNSEEN, RAW_AGE = range(10)
RAW_DIM = 10
# model features: x, y, cos, sin, speed, length, width, class one-hot (3), visible, t_unseen, t_age
FEAT_DIM = 13

RELATION_IGNORE, RELATION_FOLLOW, RELATION_YIELD = 0, 1, 2
RELATION_NAMES = ("ignore", "follow", "yield")
RELATION_PAD = -100

POSITION_SCALE = 50.0
SPEED_SCALE = 20.0
EXTENT_SCALE = 5.0
TIME_SCALE = 10.0

DEFAULT_BANK = dict(max_objects=32, max_range=50.0, max_unseen_s=10.0, max_keep_distance=80.0,
                    max_behind_distance=20.0, fov_deg=110.0, camera_x=-1.5, camera_z=2.0)


@dataclass
class Observation:
    obj_id: Optional[int]  # None for id-less static objects (matched by position)
    cls: int
    world_xy: np.ndarray  # (2,)
    world_yaw: float  # radians, CARLA world frame
    speed: float  # m/s along the heading
    length: float  # half extent along the heading
    width: float  # half extent across
    height: float = 0.75  # half extent up (occlusion test)


def normalize_angle(angle):
    return (angle + np.pi) % (2 * np.pi) - np.pi


def ego_pose_from_matrix(ego_matrix):
    """(x, y, yaw) of the CARLA 4x4 transform matrix."""
    m = np.asarray(ego_matrix, dtype=np.float64)
    return m[0, 3], m[1, 3], float(np.arctan2(m[1, 0], m[0, 0]))


def world_to_ego(points_xy, ego_xy, ego_yaw):
    c, s = np.cos(ego_yaw), np.sin(ego_yaw)
    d = np.asarray(points_xy, dtype=np.float64).reshape(-1, 2) - np.asarray(ego_xy, dtype=np.float64)
    return np.stack((c * d[:, 0] + s * d[:, 1], -s * d[:, 0] + c * d[:, 1]), axis=-1)


def ego_to_world(points_xy, ego_xy, ego_yaw):
    c, s = np.cos(ego_yaw), np.sin(ego_yaw)
    p = np.asarray(points_xy, dtype=np.float64).reshape(-1, 2)
    return np.stack((c * p[:, 0] - s * p[:, 1], s * p[:, 0] + c * p[:, 1]), axis=-1) + np.asarray(ego_xy)


def _segments_hit_boxes(seg_start, seg_ends, box_xy, box_yaw, half_l, half_w):
    """2D segment / oriented-box tests. seg_ends [K, 2], boxes [M]; returns [M, K] bool."""
    c, s = np.cos(box_yaw), np.sin(box_yaw)
    # world -> box frame rotation rows: [M, 2, 2]
    rot = np.stack((np.stack((c, s), -1), np.stack((-s, c), -1)), 1)
    p0 = np.einsum("mij,mj->mi", rot, np.asarray(seg_start) - box_xy)  # [M, 2]
    p1 = np.einsum("mij,mkj->mki", rot, np.asarray(seg_ends)[None] - box_xy[:, None])  # [M, K, 2]
    d = p1 - p0[:, None]
    half = np.stack((half_l, half_w), -1)[:, None]  # [M, 1, 2]
    parallel = np.abs(d) < 1e-9
    inside = np.abs(p0)[:, None] <= half
    hits = (~parallel | inside).all(-1)
    safe_d = np.where(parallel, 1.0, d)
    t1 = (-half - p0[:, None]) / safe_d
    t2 = (half - p0[:, None]) / safe_d
    lo = np.where(parallel, 0.0, np.minimum(t1, t2)).max(-1)
    hi = np.where(parallel, 1.0, np.maximum(t1, t2)).min(-1)
    return hits & (np.maximum(lo, 0.0) <= np.minimum(hi, 1.0))


def visible_mask(rel_xy, rel_yaw, half_l, half_w, half_h, max_range, fov_deg, camera_x, camera_z=2.0):
    """Which objects (ego-frame boxes) the front camera can see.

    In the field of view, within range, and the ray from the camera to the object's top edge is not
    blocked (in BEV) by a closer box that is tall enough to reach that ray.
    """
    rel_xy = np.asarray(rel_xy, dtype=np.float64).reshape(-1, 2)
    n = len(rel_xy)
    if n == 0:
        return np.zeros(0, dtype=bool)
    rel_yaw = np.asarray(rel_yaw, dtype=np.float64)
    half_l = np.asarray(half_l, dtype=np.float64)
    half_w = np.asarray(half_w, dtype=np.float64)
    top = 2.0 * np.asarray(half_h, dtype=np.float64)
    cam = np.array([camera_x, 0.0])
    d = rel_xy - cam
    dist = np.hypot(d[:, 0], d[:, 1])
    angle = np.degrees(np.arctan2(d[:, 1], d[:, 0]))
    # the box edge nearest to the camera decides the range check
    half_diag = np.hypot(half_l, half_w)
    in_view = (d[:, 0] > 0.5) & (np.abs(angle) < fov_deg / 2.0) & (dist - half_diag <= max_range)
    out = in_view.copy()
    for i in np.flatnonzero(in_view):
        closer = np.flatnonzero(dist < dist[i] - 1e-6)
        if len(closer) == 0:
            continue
        # height of the camera->top-of-target ray where it passes each closer box
        ray_height = camera_z + (top[i] - camera_z) * dist[closer] / dist[i]
        closer = closer[top[closer] > ray_height]
        if len(closer) == 0:
            continue
        # rays to the centre and to the two silhouette edges (perpendicular to the viewing ray)
        u = d[i] / max(dist[i], 1e-6)
        perp = np.array([-u[1], u[0]]) * (0.9 * min(half_l[i], half_w[i]))
        ends = np.stack((rel_xy[i], rel_xy[i] + perp, rel_xy[i] - perp))
        hits = _segments_hit_boxes(cam, ends, rel_xy[closer], rel_yaw[closer], half_l[closer], half_w[closer])
        out[i] = not hits.any(0).all()
    return out


class _Track:
    __slots__ = ("obj_id", "cls", "world_xy", "world_yaw", "speed", "length", "width", "height",
                 "last_seen", "first_seen")

    def __init__(self, obj_id, obs: Observation, t):
        self.obj_id = obj_id
        self.first_seen = t
        self.update(obs, t)

    def update(self, obs: Observation, t):
        self.cls = obs.cls
        self.world_xy = np.asarray(obs.world_xy, dtype=np.float64)
        self.world_yaw = float(obs.world_yaw)
        self.speed = float(obs.speed)
        self.length = float(obs.length)
        self.width = float(obs.width)
        self.height = float(obs.height)
        self.last_seen = t

    def propagated_xy(self, t):
        dt = max(t - self.last_seen, 0.0)
        return self.world_xy + dt * self.speed * np.array([np.cos(self.world_yaw), np.sin(self.world_yaw)])


class ObjectBank:
    def __init__(self, max_objects=32, max_range=50.0, max_unseen_s=10.0, max_keep_distance=80.0,
                 max_behind_distance=20.0, fov_deg=110.0, camera_x=-1.5, camera_z=2.0,
                 static_match_distance=1.0):
        self.max_objects = int(max_objects)
        self.max_range = float(max_range)
        self.max_unseen_s = float(max_unseen_s)
        self.max_keep_distance = float(max_keep_distance)
        self.max_behind_distance = float(max_behind_distance)
        self.fov_deg = float(fov_deg)
        self.camera_x = float(camera_x)
        self.camera_z = float(camera_z)
        self.static_match_distance = float(static_match_distance)
        self.reset()

    def reset(self):
        self.tracks = {}
        self._next_pseudo_id = -1

    def _match_idless(self, obs: Observation):
        best, best_d = None, self.static_match_distance
        for tid, tr in self.tracks.items():
            if tid >= 0 or tr.cls != obs.cls:
                continue
            d = float(np.hypot(*(tr.world_xy - obs.world_xy)))
            if d < best_d:
                best, best_d = tid, d
        if best is None:
            best = self._next_pseudo_id
            self._next_pseudo_id -= 1
        return best

    def step(self, t, ego_matrix, observations: List[Observation]):
        """Ingest this frame's observations and render the bank.

        Returns raw rows [max_objects, RAW_DIM] float32 (zero padded), ids [max_objects] int64
        (0 for padding) and the number of valid rows.
        """
        ego_xy = np.array(ego_pose_from_matrix(ego_matrix)[:2])
        ego_yaw = ego_pose_from_matrix(ego_matrix)[2]
        if observations:
            world = np.stack([o.world_xy for o in observations])
            rel = world_to_ego(world, ego_xy, ego_yaw)
            rel_yaw = np.array([normalize_angle(o.world_yaw - ego_yaw) for o in observations])
            half_l = np.array([o.length for o in observations])
            half_w = np.array([o.width for o in observations])
            half_h = np.array([o.height for o in observations])
            vis = visible_mask(rel, rel_yaw, half_l, half_w, half_h, self.max_range, self.fov_deg,
                               self.camera_x, self.camera_z)
            for obs, seen in zip(observations, vis):
                if not seen:
                    continue
                obj_id = obs.obj_id if obs.obj_id is not None else self._match_idless(obs)
                if obj_id in self.tracks:
                    self.tracks[obj_id].update(obs, t)
                else:
                    self.tracks[obj_id] = _Track(obj_id, obs, t)
        # prune and render
        rows = []
        for tid in list(self.tracks):
            tr = self.tracks[tid]
            unseen = t - tr.last_seen
            if unseen > self.max_unseen_s:
                del self.tracks[tid]
                continue
            rel = world_to_ego(tr.propagated_xy(t), ego_xy, ego_yaw)[0]
            dist = float(np.hypot(rel[0] - self.camera_x, rel[1]))
            if dist > self.max_keep_distance or rel[0] < -self.max_behind_distance:
                del self.tracks[tid]
                continue
            rows.append((dist, tid, rel, tr, unseen))
        rows.sort(key=lambda r: r[0])
        raw = np.zeros((self.max_objects, RAW_DIM), dtype=np.float32)
        ids = np.zeros(self.max_objects, dtype=np.int64)
        count = min(len(rows), self.max_objects)
        for k, (dist, tid, rel, tr, unseen) in enumerate(rows[:count]):
            raw[k, RAW_X] = rel[0]
            raw[k, RAW_Y] = rel[1]
            raw[k, RAW_YAW] = normalize_angle(tr.world_yaw - ego_yaw)
            raw[k, RAW_SPEED] = tr.speed
            raw[k, RAW_LENGTH] = tr.length
            raw[k, RAW_WIDTH] = tr.width
            raw[k, RAW_CLASS] = tr.cls
            raw[k, RAW_VISIBLE] = 1.0 if unseen <= 1e-6 else 0.0
            raw[k, RAW_UNSEEN] = unseen
            raw[k, RAW_AGE] = t - tr.first_seen
            ids[k] = tid
        return raw, ids, count


def augment_raw(raw, aug_translation=0.0, aug_rotation=0.0):
    """Apply the camera-shift augmentation (metres right, degrees) used for waypoints/routes."""
    if aug_translation == 0.0 and aug_rotation == 0.0:
        return raw
    out = np.array(raw, dtype=np.float32, copy=True)
    a = np.deg2rad(aug_rotation)
    c, s = np.cos(a), np.sin(a)
    x = out[:, RAW_X]
    y = out[:, RAW_Y] - aug_translation
    out[:, RAW_X] = c * x + s * y
    out[:, RAW_Y] = -s * x + c * y
    out[:, RAW_YAW] = normalize_angle(out[:, RAW_YAW] - a)
    return out


def raw_to_features(raw):
    """[N, RAW_DIM] -> [N, FEAT_DIM] float32 model features (padding rows stay all-zero)."""
    raw = np.asarray(raw, dtype=np.float32)
    feats = np.zeros((raw.shape[0], FEAT_DIM), dtype=np.float32)
    valid = (raw != 0).any(axis=1)
    feats[:, 0] = raw[:, RAW_X] / POSITION_SCALE
    feats[:, 1] = raw[:, RAW_Y] / POSITION_SCALE
    feats[:, 2] = np.cos(raw[:, RAW_YAW]) * valid
    feats[:, 3] = np.sin(raw[:, RAW_YAW]) * valid
    feats[:, 4] = raw[:, RAW_SPEED] / SPEED_SCALE
    feats[:, 5] = raw[:, RAW_LENGTH] / EXTENT_SCALE
    feats[:, 6] = raw[:, RAW_WIDTH] / EXTENT_SCALE
    cls = np.clip(raw[:, RAW_CLASS].astype(np.int64), 0, NUM_CLASSES - 1)
    feats[np.arange(len(raw)), 7 + cls] = valid.astype(np.float32)
    feats[:, 10] = raw[:, RAW_VISIBLE]
    feats[:, 11] = np.minimum(raw[:, RAW_UNSEEN], TIME_SCALE) / TIME_SCALE
    feats[:, 12] = np.minimum(raw[:, RAW_AGE], TIME_SCALE) / TIME_SCALE
    return feats


def observations_from_simlingo_boxes(boxes, ego_matrix):
    """Convert one SimLingo boxes/*.json.gz frame into bank observations (world frame)."""
    ego_x, ego_y, ego_yaw = ego_pose_from_matrix(ego_matrix)
    observations = []
    for box in boxes:
        cls_name = box.get("class")
        if cls_name == "car":
            cls = CLASS_CAR
        elif cls_name == "walker":
            cls = CLASS_WALKER
        elif cls_name in ("static_car", "static", "static_trafficwarning"):
            cls = CLASS_STATIC
        else:
            continue
        if "position" not in box or "extent" not in box:
            continue
        rel = np.asarray(box["position"][:2], dtype=np.float64)
        if not np.isfinite(rel).all():
            continue
        world_xy = ego_to_world(rel, (ego_x, ego_y), ego_yaw)[0]
        world_yaw = normalize_angle(float(box.get("yaw", 0.0)) + ego_yaw)
        speed = float(box.get("speed", 0.0) or 0.0) if cls != CLASS_STATIC else 0.0
        extent = box["extent"]
        observations.append(Observation(
            obj_id=int(box["id"]) if box.get("id") is not None else None,
            cls=cls, world_xy=world_xy, world_yaw=world_yaw, speed=max(speed, 0.0),
            length=max(float(extent[0]), 0.1), width=max(float(extent[1]), 0.1),
            height=max(float(extent[2]), 0.05) if len(extent) > 2 else 0.75))
    return observations


def relation_labels(ids, count, measurement):
    """Per-object relation label from the PDM-Lite expert's bookkeeping in measurements/*.json.gz."""
    labels = np.full(len(ids), RELATION_PAD, dtype=np.int64)
    labels[:count] = RELATION_IGNORE
    yield_ids = set()
    if measurement.get("vehicle_hazard") and measurement.get("vehicle_affecting_id") is not None:
        yield_ids.add(int(measurement["vehicle_affecting_id"]))
    if measurement.get("walker_hazard") and measurement.get("walker_affecting_id") is not None:
        yield_ids.add(int(measurement["walker_affecting_id"]))
    follow_id = None
    reduced_id = measurement.get("speed_reduced_by_obj_id")
    reduced_type = str(measurement.get("speed_reduced_by_obj_type") or "")
    if reduced_id is not None:
        if reduced_type.startswith("walker"):
            yield_ids.add(int(reduced_id))
        elif reduced_type.startswith("vehicle"):
            follow_id = int(reduced_id)
    for k in range(count):
        if ids[k] in yield_ids:
            labels[k] = RELATION_YIELD
        elif follow_id is not None and ids[k] == follow_id:
            labels[k] = RELATION_FOLLOW
    return labels