File size: 13,626 Bytes
314ecfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Counterfactual 'visibility-aware creep' replay for a single recorded collision.

The ego follows its recorded path geometry but with a new speed profile: from the start point it creeps at
<= v_cap and, being memoryless, starts braking `tau` seconds after any corner of the other actor's box enters
the 110 deg front-camera FOV. The other actor replays its recorded trajectory (constant-velocity
extrapolation after the real impact). If it was at rest and started moving after the start point, its
launch is re-timed to the moment the simulated ego reaches the position the real ego had at launch
(scenario actors are triggered by ego proximity).
"""
import json
import math

import numpy as np

from failure_report import CAM_BACK, EGO_EXTENT, HALF_FOV, corners, interp_state

DT = 0.02


def _axes(c):
    return [(c[1][0] - c[0][0], c[1][1] - c[0][1]), (c[2][0] - c[0][0], c[2][1] - c[0][1])]


def boxes_overlap(a, b):
    for axis in _axes(a) + _axes(b):
        pa = [p[0] * axis[0] + p[1] * axis[1] for p in a]
        pb = [p[0] * axis[0] + p[1] * axis[1] for p in b]
        if max(pa) < min(pb) or max(pb) < min(pa):
            return False
    return True


def box(x, y, yaw, ext):
    # corners() order: (-x,-y), (-x,+y), (+x,-y), (+x,+y) -> reorder to a polygon for SAT axes
    c = corners(x, y, yaw, ext)
    return [c[0], c[1], c[3], c[2]]


def visible(ego, oth, ext):
    ex, ey, eyaw = ego
    c, s = math.cos(math.radians(eyaw)), math.sin(math.radians(eyaw))
    cx, cy = ex - CAM_BACK * c, ey - CAM_BACK * s
    for px, py in corners(*oth, ext):
        lx = (px - cx) * c + (py - cy) * s
        ly = -(px - cx) * s + (py - cy) * c
        if lx > 0 and abs(math.atan2(ly, lx)) < HALF_FOV:
            return True
    return False


class Path:
    def __init__(self, hero, t0, t1, extend=15.0):
        seg = hero[(hero[:, 0] >= t0) & (hero[:, 0] <= t1)]
        pts = [seg[0]]
        for r in seg[1:]:
            if math.hypot(r[1] - pts[-1][1], r[2] - pts[-1][2]) > 0.05:
                pts.append(r)
        pts = np.array(pts)
        yaw = math.radians(pts[-1][3])
        ext = np.array([[0, pts[-1][1] + k * math.cos(yaw), pts[-1][2] + k * math.sin(yaw), pts[-1][3], 0]
                        for k in np.arange(0.5, extend, 0.5)])
        self.p = np.vstack([pts, ext]) if len(ext) else pts
        d = np.hypot(np.diff(self.p[:, 1]), np.diff(self.p[:, 2]))
        self.s = np.concatenate([[0], np.cumsum(d)])
        self.s_impact = self.s[len(pts) - 1]
        self.t_of_s = (pts[:, 0], self.s[: len(pts)])

    def pose(self, s):
        s = float(np.clip(s, 0, self.s[-1]))
        x = np.interp(s, self.s, self.p[:, 1])
        y = np.interp(s, self.s, self.p[:, 2])
        yaw = np.degrees(np.unwrap(np.radians(self.p[:, 3])))
        return x, y, float(np.interp(s, self.s, yaw))

    def s_at_time(self, t):
        return float(np.interp(t, *self.t_of_s))


def other_pose_fn(tr, t_c):
    pre = tr[tr[:, 0] <= t_c - 0.1]
    last, prev = pre[-1], pre[max(0, len(pre) - 6)]
    dt = max(last[0] - prev[0], 1e-3)
    vx, vy = (last[1] - prev[1]) / dt, (last[2] - prev[2]) / dt

    def f(t):
        if t <= last[0]:
            return interp_state(pre, max(t, pre[0, 0]))
        return last[1] + vx * (t - last[0]), last[2] + vy * (t - last[0]), last[3]

    return f, last[0]


def bystander_index(d, other_id, extents):
    """Map 0.1 s time keys -> list of (box params) for every recorded actor except the collision partner."""
    actors = json.loads(str(d["actors"]))
    idx = {}
    for t, aid, x, y, yaw in d["others"]:
        if aid == other_id:
            continue
        ext = extents.get(actors.get(str(int(aid)), ""), (2.4, 1.0))
        idx.setdefault(int(round(t * 10)), []).append((int(aid), x, y, yaw, ext))
    return idx


def simulate(d, t_c, other_id, ext_other, t_start, v0, v_cap=3.0, a_acc=2.0, a_brake=6.0, tau=0.5,
             replay_actual=False, horizon=15.0, bystanders=None):
    """tau=None means a blind creep (never brakes); `bystanders` from bystander_index() adds overlap
    checks against all other recorded actors (replayed on the original clock)."""
    hero = d["hero"]
    others = d["others"]
    tr = others[others[:, 1] == other_id][:, [0, 2, 3, 4]]
    path = Path(hero, t_start, t_c)
    opose, t_last = other_pose_fn(tr, t_c)
    # Detect a triggered launch: at rest at t_start, moving later.
    spd = np.hypot(np.diff(tr[:, 1]), np.diff(tr[:, 2])) / np.maximum(np.diff(tr[:, 0]), 1e-3)
    moving = np.where((tr[1:, 0] > t_start) & (spd > 0.5))[0]
    at_rest_start = len(tr) > 1 and tr[0, 0] <= t_start and np.all(spd[(tr[1:, 0] <= t_start) & (tr[1:, 0] > t_start - 1.0)] < 0.3)
    t_launch = float(tr[moving[0] + 1, 0]) if (len(moving) and at_rest_start) else None
    s_launch = path.s_at_time(t_launch) if t_launch is not None else None

    s, v, t = 0.0, v0, 0.0
    t_trig, t_seen, braking = None, None, False
    first_seen = None
    min_gap = None
    while t < horizon:
        if replay_actual:
            s = path.s_at_time(t_start + t) if t_start + t <= t_c else path.s_impact
        ego = path.pose(s)
        if t_launch is not None:
            if t_trig is None and s >= s_launch:
                t_trig = t
            t_o = t_launch + (t - t_trig) if t_trig is not None else t_launch - 1e-3
        else:
            t_o = t_start + t
        oth = opose(t_o)
        if t_seen is None and visible(ego, oth, ext_other):
            t_seen = t
            first_seen = t if first_seen is None else first_seen
        ego_box = box(*ego, EGO_EXTENT)
        if boxes_overlap(ego_box, box(*oth, ext_other)):
            return {"outcome": "collision", "triggered": t_launch is not None, "t": round(t, 2), "t_seen": first_seen, "s": round(s, 1),
                    "s_impact": round(path.s_impact, 1)}
        if bystanders is not None and t_start + t < t_c + 3.0:
            for aid, bx, by, byaw, bext in bystanders.get(int(round((t_start + t) * 10)), []):
                if abs(bx - ego[0]) < 8 and abs(by - ego[1]) < 8 and boxes_overlap(ego_box, box(bx, by, byaw, bext)):
                    return {"outcome": "collision_with_other", "triggered": t_launch is not None, "other_id": aid, "t": round(t, 2),
                            "t_seen": first_seen}
        gap = math.hypot(ego[0] - oth[0], ego[1] - oth[1])
        min_gap = gap if min_gap is None else min(min_gap, gap)
        # Done once the other actor's motion has run past the extrapolation window, or we cleared the impact point.
        if t_o > t_last + 5.0 or (s > path.s_impact + 8.0):
            return {"outcome": "safe", "triggered": t_launch is not None, "t_seen": first_seen, "min_centre_gap": round(min_gap, 1)}
        if not replay_actual:
            if tau is not None and t_seen is not None and t >= t_seen + tau:
                braking = True
            if braking:
                v = max(0.0, v - a_brake * DT)
                # Resume once the other actor is no longer visible and has moved away.
                if v == 0.0 and gap > 12.0 and not visible(ego, oth, ext_other):
                    braking, t_seen = False, None
            elif v > v_cap:
                v = max(v_cap, v - 3.0 * DT)
            else:
                v = min(v_cap, v + a_acc * DT)
            s += v * DT
        t += DT
    return {"outcome": "timeout", "min_centre_gap": round(min_gap or -1, 1)}


def _bystander_tracks(d, other_id, extents):
    actors = json.loads(str(d["actors"]))
    others = d["others"]
    tracks = {}
    for aid in np.unique(others[:, 1]):
        if aid == other_id:
            continue
        tr = others[others[:, 1] == aid][:, [0, 2, 3, 4]]
        tracks[int(aid)] = (tr, extents.get(actors.get(str(int(aid)), ""), (2.4, 1.0)))
    return tracks


def _track_pose(tr, t):
    if t < tr[0, 0] or t > tr[-1, 0]:
        return None
    return interp_state(tr, t)


def simulate_reactive(d, t_c, other_id, ext_other, t_start, v0, extents, v_cap=3.0, a_acc=2.0, a_brake=6.0,
                      tau=0.5, t_pred=3.0, horizon=40.0, v_release=None, release_after=(4.0, 1.0)):
    """Creep at <= v_cap and yield to every actor currently in the front-camera FOV whose constant-velocity
    prediction (from its last 0.5 s of motion, no future knowledge) overlaps the ego's creep path within
    t_pred seconds. Braking/resuming acts on the threat state from `tau` seconds earlier. Bystanders are
    replayed on the recorded clock until the recording ends; the partner is extrapolated beyond that.
    Note flow actors switch to reactive driving after any crash, so post-impact bystander motion is optimistic.
    v_release: once the ego has crept release_after[0] m and seen no threat for release_after[1] s, the cap
    is raised to v_release (threat checks stay active)."""
    hero, others = d["hero"], d["others"]
    tr = others[others[:, 1] == other_id][:, [0, 2, 3, 4]]
    path = Path(hero, t_start, t_c)
    opose, t_last = other_pose_fn(tr, t_c)
    spd = np.hypot(np.diff(tr[:, 1]), np.diff(tr[:, 2])) / np.maximum(np.diff(tr[:, 0]), 1e-3)
    moving = np.where((tr[1:, 0] > t_start) & (spd > 0.5))[0]
    at_rest_start = len(tr) > 1 and tr[0, 0] <= t_start and np.all(spd[(tr[1:, 0] <= t_start) & (tr[1:, 0] > t_start - 1.0)] < 0.3)
    t_launch = float(tr[moving[0] + 1, 0]) if (len(moving) and at_rest_start) else None
    s_launch = path.s_at_time(t_launch) if t_launch is not None else None
    tracks = _bystander_tracks(d, other_id, extents)
    rec_end = float(hero[-1, 0])
    ego_ext = (EGO_EXTENT[0] + 0.5, EGO_EXTENT[1] + 0.3)

    s, v, t = 0.0, v0, 0.0
    cap = v_cap
    t_trig = None
    threat_hist = []  # (t, threat)
    braking = False
    first_threat, n_threat_actors = None, set()
    while t < horizon:
        ego = path.pose(s)
        if t_launch is not None:
            if t_trig is None and s >= s_launch:
                t_trig = t
            t_o = t_launch + (t - t_trig) if t_trig is not None else t_launch - 1e-3
            partner = lambda tt: opose(t_launch + (tt - t_trig) if t_trig is not None else t_launch - 1e-3)
        else:
            t_o = t_start + t
            partner = lambda tt: opose(t_start + tt)
        oth = opose(t_o)
        ego_box = box(*ego, EGO_EXTENT)
        if boxes_overlap(ego_box, box(*oth, ext_other)):
            return {"outcome": "collision", "triggered": t_launch is not None, "t": round(t, 2), "s": round(s, 1),
                    "s_impact": round(path.s_impact, 1), "first_threat": first_threat}
        tw = t_start + t
        live = []
        for aid, (btr, bext) in (tracks.items() if tw <= rec_end else ()):
            p = _track_pose(btr, tw)
            if p is None or abs(p[0] - ego[0]) > 40 or abs(p[1] - ego[1]) > 40:
                continue
            live.append((aid, p, btr, bext))
            if abs(p[0] - ego[0]) < 8 and abs(p[1] - ego[1]) < 8 and boxes_overlap(ego_box, box(*p, bext)):
                return {"outcome": "collision_with_other", "triggered": t_launch is not None, "with_id": aid,
                        "t": round(t, 2), "first_threat": first_threat}
        info = {"triggered": t_launch is not None, "first_threat": first_threat, "t": round(t, 2),
                "threat_actors": sorted(map(str, n_threat_actors)), "s": round(s, 1), "s_impact": round(path.s_impact, 1)}
        if s > path.s_impact + 8.0:
            return {"outcome": "passed" if tw <= rec_end else "passed_after_recording", **info}
        if tw > rec_end and t_o > t_last + 5.0:
            # Partner extrapolated well past the impact; recorded traffic ended without a conflict.
            return {"outcome": "partner_avoided", **info}

        if int(round(t / DT)) % 5 == 0:
            cand = [("partner", oth, partner(t - 0.5), ext_other)]
            for aid, p, btr, bext in live:
                q = _track_pose(btr, tw - 0.5)
                cand.append((aid, p, q if q is not None else p, bext))
            threat = False
            v_plan = max(v, cap)
            for aid, p, q, ext in cand:
                if not visible(ego, p, ext):
                    continue
                vx, vy = (p[0] - q[0]) / 0.5, (p[1] - q[1]) / 0.5
                for k in np.arange(0.0, t_pred + 1e-6, 0.2):
                    ek = path.pose(s + v_plan * k)
                    if abs(p[0] + vx * k - ek[0]) > 10 or abs(p[1] + vy * k - ek[1]) > 10:
                        continue
                    if boxes_overlap(box(*ek, ego_ext), box(p[0] + vx * k, p[1] + vy * k, p[2], ext)):
                        threat = True
                        n_threat_actors.add(aid)
                        break
                if threat:
                    break
            if threat and first_threat is None:
                first_threat = round(t, 2)
            threat_hist.append((t, threat))
        delayed = [th for tt, th in threat_hist if tt <= t - (tau or 0.0)]
        braking = bool(delayed[-1]) if delayed else False
        if v_release is not None and cap == v_cap and s >= release_after[0]:
            recent = [th for tt, th in threat_hist if tt >= t - release_after[1]]
            if len(recent) >= int(release_after[1] / 0.1) and not any(recent):
                cap = v_release
        if braking:
            v = max(0.0, v - a_brake * DT)
        elif v > cap:
            v = max(cap, v - 3.0 * DT)
        else:
            v = min(cap, v + a_acc * DT)
        s += v * DT
        t += DT
    return {"outcome": "stuck", "first_threat": first_threat, "s": round(s, 1), "s_impact": round(path.s_impact, 1),
            "threat_actors": sorted(map(str, n_threat_actors))}