File size: 27,324 Bytes
e3be6f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
"""Fruit-prep station FP-2: pack fruit into the transfer tub, pour it into the mixing bowl, park the tub, with an
I2RT YAM.

Builds the `gauntlet.Task` the acceptance run uses, including the station's own rules (`Station`): fruit squeeze,
spills, the mixing bowl, the tub. Read-only: the acceptance run checks this file's hash and uses its own copy.
Lengths in metres, forces in newtons, world frame = robot base frame as built.
"""
from __future__ import annotations

import collections
import math
import os
import sys

import mujoco
import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "gauntlet"))
import gauntlet as G  # noqa: E402

SCENE = os.path.join(HERE, "scene.xml")
FRUITS = tuple(f"fruit_{k}" for k in range(6))

# ---- Fruit (CELL_SHEET.md) ----
# shape, colour, size range: sphere radius, or ellipsoid (long semi-axis, short semi-axes)
KINDS = {
    "peach":       dict(shape="sphere", rgba=(0.98, 0.64, 0.52, 1.0), r=(0.026, 0.031)),
    "red apple":   dict(shape="sphere", rgba=(0.74, 0.08, 0.10, 1.0), r=(0.027, 0.031)),
    "green apple": dict(shape="sphere", rgba=(0.47, 0.74, 0.20, 1.0), r=(0.026, 0.030)),
    "orange":      dict(shape="sphere", rgba=(0.97, 0.50, 0.05, 1.0), r=(0.025, 0.030)),
    "plum":        dict(shape="ellipsoid", rgba=(0.38, 0.10, 0.36, 1.0), a=(0.026, 0.030), b=(0.021, 0.024)),
    "lemon":       dict(shape="ellipsoid", rgba=(0.96, 0.85, 0.18, 1.0), a=(0.032, 0.036), b=(0.024, 0.027)),
    "kiwi":        dict(shape="ellipsoid", rgba=(0.48, 0.34, 0.18, 1.0), a=(0.029, 0.033), b=(0.022, 0.025)),
}
FIRM = tuple(k for k in KINDS if k != "peach")
DENSITY = (800.0, 950.0)            # kg/m^3
FRICTION = (0.5, 0.9)               # fruit skin
SOFT_N = 8.0                        # the peach bruises above this squeeze per pad (held 60 ms)
FIRM_N = 25.0                       # any other fruit is marked above this squeeze per pad (held 60 ms)
PIECES = (4, 6)

# ---- Fixtures and vessels (scene.xml) ----
CRATE_IN = (0.135, 0.092)           # crate inside half sizes (x along the crate's own axis)
CRATE_FLOOR, CRATE_WALL_H = 0.008, 0.045
CRATE_OUT = (0.143, 0.100)
TUB_R_IN, TUB_R_TOP, TUB_H, TUB_FLOOR = 0.062, 0.078, 0.100, 0.008   # inner radius at the floor and at the rim
TUB_R_OUT, TUB_R_BASE = 0.084, 0.068  # outside radius at the rim and at the base
TUB_GRIP = (-0.096, 0.0, 0.060)     # centre of the grip block in the tub frame (handle on the -x side)
TUB_REACH = 0.104                   # handle tip from the tub axis
HANDLE_ROOM_M = 0.060               # free bench around the approach to the handle (gripper fingers open)
BOWL_FLOOR_H, BOWL_TOP_R, BOWL_TOP_Z, BOWL_OUT = 0.010, 0.118, 0.080, 0.124
MAT_HALF, MAT_TOP = 0.090, 0.005

# ---- Station rules ----
BOWL_SHIFT_M = 0.010                # the mixing bowl may not be moved more than this
TUB_ON_MAT_M = MAT_HALF - TUB_R_BASE + 0.004   # tub axis within this of the mat centre (each mat axis): base on the mat
TUB_UPRIGHT_DEG = 8.0
POUR_TILT_DEG = 45.0                # a fruit that leaves the tub while the tub is tilted past this was poured
BUDGET_BASE_S, BUDGET_PER_PIECE_S = 75.0, 10.0
FAULT_GRACE_S = 35.0                # set-up allowance of the fault-batch score (harness.fault_episode_score)
EPISODE_S = 145.0

# ---- Layout (public ranges; the acceptance run also uses the in-between and outside bands) ----
CRATE_MOUNTS = ((0.205, 0.285, math.radians(-38.0)), (0.125, 0.315, math.radians(-22.0)))   # x, y, yaw
MAT_MOUNTS = ((0.135, -0.375, math.radians(-70.0)), (0.035, -0.395, math.radians(-85.0)))
TUB_X, TUB_Y = (0.33, 0.40), (-0.03, 0.07)
TUB_BEARING_DEG = 30.0              # handle direction: within this of pointing at the arm base
BOWL_X, BOWL_Y = (0.31, 0.39), (-0.27, -0.17)
CLEARANCE_M = 0.015                 # between any two of crate, tub (with handle), bowl, mat
FRUIT_GAP_M = 0.012                 # between neighbouring fruit in the crate
FRUIT_WALL_M = 0.018                # between fruit and the crate walls (the liner's raised edge keeps them off)
LIMITS_NOTE = "outside band: ranges widened by 25 %, mounts extrapolated by up to 25 % of their spacing"

# Placement band of the next episode: "in_range" (the public runner), "in_between" or "outside" (acceptance run).
BAND = "in_range"

HOME = {"robot/joint1": 0.0, "robot/joint2": 1.20, "robot/joint3": 1.15, "robot/joint4": -1.25,
        "robot/joint5": 0.0, "robot/joint6": 0.0, "robot/left_finger": 0.040, "robot/right_finger": 0.040}

EPISODE: dict = {}


# ---------------------------------------------------------------------------------------------- helpers
def _rz(a):
  c, s = math.cos(a), math.sin(a)
  return np.array([[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]])


def _qz(a):
  return np.array([math.cos(a / 2), 0.0, 0.0, math.sin(a / 2)])


def tilt_deg(q) -> float:
  return math.degrees(math.acos(float(np.clip(1 - 2 * (q[1] ** 2 + q[2] ** 2), -1.0, 1.0))))


def _widen(lo, hi, band, rng):
  w = hi - lo
  if band == "outside":
    return float(rng.uniform(hi, hi + 0.25 * w)) if rng.random() < 0.5 else float(rng.uniform(lo - 0.25 * w, lo))
  return float(rng.uniform(lo, hi))


def _range(lo, hi, band, rng, p_out=0.5):
  """A draw from the public range; in the 'outside' band, from the 25 % margins with probability p_out."""
  if band == "outside" and rng.random() < p_out:
    return _widen(lo, hi, band, rng)
  return float(rng.uniform(lo, hi))


def _mount(mounts, band, rng):
  a, b = np.array(mounts[0]), np.array(mounts[1])
  if band == "in_between":
    t = float(rng.uniform(0.25, 0.75))
  elif band == "outside":
    t = float(rng.uniform(1.0, 1.25)) if rng.random() < 0.5 else float(rng.uniform(-0.25, 0.0))
  else:
    t = float(rng.integers(2))
  return a + t * (b - a)


def _rect_pts(cx, cy, yaw, hx, hy, n=6):
  r = _rz(yaw)[:2, :2]
  pts = []
  for u in np.linspace(-1, 1, n):
    for v in (-1, 1):
      pts.append(r @ np.array([u * hx, v * hy]) + (cx, cy))
      pts.append(r @ np.array([v * hx, u * hy]) + (cx, cy))
  return np.array(pts)


def _dist_pt_rect(p, cx, cy, yaw, hx, hy):
  r = _rz(yaw)[:2, :2]
  loc = r.T @ (np.asarray(p) - (cx, cy))
  dx, dy = max(abs(loc[0]) - hx, 0.0), max(abs(loc[1]) - hy, 0.0)
  return math.hypot(dx, dy)


def _rects_clear(a, b, gap):
  """Two rotated rectangles (cx, cy, yaw, hx, hy) at least `gap` apart (sampled edges)."""
  return (min(_dist_pt_rect(p, *b) for p in _rect_pts(*a)) >= gap and
          min(_dist_pt_rect(p, *a) for p in _rect_pts(*b)) >= gap)


def fruit_extent(f):
  """(radius in plan, half height) of a fruit lying at rest."""
  if f["shape"] == "sphere":
    return f["r"], f["r"]
  return f["a"], f["b"]


# ---------------------------------------------------------------------------------------------- episode plan
def plan(rng: np.random.Generator, band: str) -> dict:
  ep = {"band": band}
  n = int(rng.integers(PIECES[0], PIECES[1] + 1))
  kinds = ["peach"] + [FIRM[int(i)] for i in rng.integers(len(FIRM), size=n - 1)]
  fruit = []
  for k, kind in enumerate(kinds):
    spec = KINDS[kind]
    f = {"body": FRUITS[k], "kind": kind, "shape": spec["shape"]}
    if spec["shape"] == "sphere":
      f["r"] = _range(*spec["r"], band, rng)
      vol = 4.0 / 3.0 * math.pi * f["r"] ** 3
    else:
      f["a"] = _range(*spec["a"], band, rng)
      f["b"] = min(_range(*spec["b"], band, rng), f["a"] - 0.003)
      vol = 4.0 / 3.0 * math.pi * f["a"] * f["b"] ** 2
    f["mass"] = vol * float(rng.uniform(*DENSITY))
    f["friction"] = _range(*FRICTION, band, rng)
    fruit.append(f)
  ep["fruit"] = fruit
  ep["n"] = n
  for _ in range(4000):
    crate = _mount(CRATE_MOUNTS, band, rng)
    mat = _mount(MAT_MOUNTS, band, rng)
    tub = np.array([_range(*TUB_X, band, rng, 0.7), _range(*TUB_Y, band, rng, 0.7)])
    bear = TUB_BEARING_DEG * (float(rng.choice([-1, 1])) * float(rng.uniform(1.0, 1.25))
                              if band == "outside" and rng.random() < 0.5 else float(rng.uniform(-1, 1)))
    tub_yaw = math.atan2(tub[1], tub[0]) + math.radians(bear)     # tub +x points from the handle to the axis
    bowl = np.array([_range(*BOWL_X, band, rng, 0.7), _range(*BOWL_Y, band, rng, 0.7)])
    rects = {"crate": (crate[0], crate[1], crate[2], CRATE_OUT[0], CRATE_OUT[1]),
             "mat": (mat[0], mat[1], mat[2], MAT_HALF, MAT_HALF)}
    circles = {"tub": (tub, TUB_R_OUT), "bowl": (bowl, BOWL_OUT)}
    handle = tub + TUB_REACH * np.array([-math.cos(tub_yaw), -math.sin(tub_yaw)])
    ok = math.dist(tub, bowl) >= TUB_R_OUT + BOWL_OUT + CLEARANCE_M
    ok = ok and math.dist(handle, bowl) >= BOWL_OUT + CLEARANCE_M
    for (c, r) in circles.values():
      ok = ok and all(_dist_pt_rect(c, *rc) >= r + CLEARANCE_M for rc in rects.values())
    ok = ok and all(_dist_pt_rect(handle, *rc) >= CLEARANCE_M for rc in rects.values())
    # the handle faces open bench: room for a gripper to come in along the handle
    out = np.array([-math.cos(tub_yaw), -math.sin(tub_yaw)])
    for t in (0.0, 0.05, 0.10):
      pt = handle + t * out
      ok = ok and all(_dist_pt_rect(pt, *rc) >= HANDLE_ROOM_M for rc in rects.values())
      ok = ok and math.dist(pt, bowl) >= BOWL_OUT + HANDLE_ROOM_M
    ok = ok and _rects_clear(rects["crate"], rects["mat"], CLEARANCE_M)
    if ok:
      break
  else:  # pragma: no cover
    raise RuntimeError("no layout")
  ep.update(crate=tuple(float(x) for x in crate), mat=tuple(float(x) for x in mat),
            tub=(float(tub[0]), float(tub[1]), float(tub_yaw)), bearing_deg=bear,
            bowl=(float(bowl[0]), float(bowl[1])))
  # fruit in the crate (crate frame): a 3 x 2 grid of bays, one piece per bay, jittered inside its bay
  ix, iy = CRATE_IN
  cw, ch = 2 * ix / 3, 2 * iy / 2
  bays = rng.permutation(6)[:n]
  for f, bay in zip(fruit, bays):
    ext, _h = fruit_extent(f)
    cxb = -ix + cw * (bay % 3 + 0.5)
    cyb = -iy + ch * (bay // 3 + 0.5)
    # jitter inside the bay: half the fruit gap from an inner bay edge, the wall gap from a crate wall
    def span(c, half, lim):
      lo = (-lim + FRUIT_WALL_M) if c - half < -lim + 1e-9 else (c - half + FRUIT_GAP_M / 2)
      hi = (lim - FRUIT_WALL_M) if c + half > lim - 1e-9 else (c + half - FRUIT_GAP_M / 2)
      lo, hi = lo + ext, hi - ext
      return (lo, hi) if lo <= hi else ((lo + hi) / 2, (lo + hi) / 2)
    xs, ys = span(cxb, cw / 2, ix), span(cyb, ch / 2, iy)
    f["crate_xy"] = (float(rng.uniform(*xs)), float(rng.uniform(*ys)))
    f["yaw"] = float(rng.uniform(0, 2 * math.pi))
  ep["budget_s"] = BUDGET_BASE_S + BUDGET_PER_PIECE_S * n
  return ep


def _place_fixed(m, name, x, y, yaw):
  b = m.body(name).id
  m.body_pos[b] = (x, y, 0.0)
  m.body_quat[b] = _qz(yaw)


def _set_free(m, d, name, pos, quat):
  adr = m.jnt_qposadr[m.body_jntadr[m.body(name).id]]
  d.qpos[adr:adr + 3] = pos
  d.qpos[adr + 3:adr + 7] = quat


def setup(m: mujoco.MjModel, d: mujoco.MjData, rng: np.random.Generator, pspec=None) -> None:
  """Lays out the station for one episode. The tier's placement offsets of the peach and the bowl (applied by the
  gauntlet after this) are taken out here, so every layout stays inside the documented limits."""
  ep = plan(rng, BAND)
  EPISODE.clear()
  EPISODE.update(ep)
  _place_fixed(m, "crate", *ep["crate"])
  _place_fixed(m, "mat", *ep["mat"])
  tx, ty, tyaw = ep["tub"]
  _set_free(m, d, "tub", (tx, ty, 0.0005), _qz(tyaw))
  bx, by = ep["bowl"]
  boff = np.array(pspec.dest_xy_m[:2]) if pspec is not None else np.zeros(2)
  _set_free(m, d, "bowl", (bx - boff[0], by - boff[1], 0.0005), (1, 0, 0, 0))
  cx, cy, cyaw = ep["crate"]
  rc = _rz(cyaw)
  for k, name in enumerate(FRUITS):
    b = m.body(name).id
    gs, ge = m.geom(f"{name}_sphere").id, m.geom(f"{name}_ellipsoid").id
    if k >= ep["n"]:
      m.body_gravcomp[b] = 1.0
      for g in (gs, ge):
        m.geom_contype[g] = m.geom_conaffinity[g] = 0
        m.geom_rgba[g] = (0, 0, 0, 0)
        m.geom_matid[g] = -1
      _set_free(m, d, name, (-0.6 - 0.08 * k, 0.9, -0.5), (1, 0, 0, 0))
      continue
    f = ep["fruit"][k]
    on, off = (gs, ge) if f["shape"] == "sphere" else (ge, gs)
    m.geom_contype[off] = m.geom_conaffinity[off] = 0
    m.geom_rgba[off] = (0, 0, 0, 0)
    m.geom_matid[off] = -1
    m.geom_matid[on] = -1
    m.geom_rgba[on] = KINDS[f["kind"]]["rgba"]
    m.geom_friction[on, 0] = f["friction"]
    if f["shape"] == "sphere":
      r = f["r"]
      m.geom_size[on] = (r, 0.0, 0.0)
      rb = r
      inertia = np.full(3, 0.4 * f["mass"] * r * r)
      h = r
    else:
      a, bb = f["a"], f["b"]
      m.geom_size[on] = (a, bb, bb)
      rb = a
      inertia = np.array([0.4 * f["mass"] * bb * bb, 0.2 * f["mass"] * (a * a + bb * bb), 0.2 * f["mass"] * (a * a + bb * bb)])
      h = bb
    m.geom_rbound[on] = rb
    m.geom_aabb[on] = (0.0, 0.0, 0.0, *m.geom_size[on][:3]) if f["shape"] == "ellipsoid" else (0.0, 0.0, 0.0, r, r, r)
    m.body_mass[b] = f["mass"]
    m.body_inertia[b] = inertia
    m.body_ipos[b] = 0.0
    m.body_iquat[b] = (1.0, 0.0, 0.0, 0.0)
    pw = rc @ np.array([f["crate_xy"][0], f["crate_xy"][1], 0.0]) + np.array([cx, cy, CRATE_FLOOR + h + 0.0005])
    yaw = f["yaw"]
    if k == 0 and pspec is not None:
      pw[:2] -= np.array(pspec.target_xy_m[:2])
      yaw -= math.radians(pspec.target_yaw_deg)
    _set_free(m, d, name, pw, _qz(yaw))
  mujoco.mj_forward(m, d)


# ---------------------------------------------------------------------------------------------- station process
class Station:
  """Fruit squeeze, spills, the bowl and the tub, checked once per control tick (privileged)."""

  def __init__(self, m: mujoco.MjModel, d: mujoco.MjData, pspec, dt: float):
    self.m, self.dt = m, dt
    self.ep = EPISODE
    self.n = self.ep["n"]
    self.fruit = self.ep["fruit"]
    self.fb = np.array([m.body(f["body"]).id for f in self.fruit])
    self.ext = [fruit_extent(f) for f in self.fruit]
    self.tub, self.bowl = m.body("tub").id, m.body("bowl").id
    self.crate, self.mat = m.body("crate").id, m.body("mat").id
    self.pads = [m.body("robot/left_pad").id, m.body("robot/right_pad").id]
    self.robot = np.array([(m.body(b).name or "").startswith("robot/") for b in range(m.nbody)])
    self.pad_of = np.full(m.nbody, -1)
    for i, b in enumerate(self.pads):
      self.pad_of[b] = i
    self.fruit_of = np.full(m.nbody, -1)
    for i, b in enumerate(self.fb):
      self.fruit_of[b] = i
    self.bench = m.geom("bench").id
    self.bowl0 = None
    self.squeeze = collections.deque(maxlen=3)
    self.max_squeeze = np.zeros(self.n)
    self.max_squeeze_t = [None] * self.n
    self.was_in_tub = np.zeros(self.n, bool)
    self.packed_t = [None] * self.n
    self.poured = np.zeros(self.n, bool)
    self.spilled_t = [None] * self.n
    self.mat_since = None
    self.viol: dict[str, float] = {}
    self.events: list = []
    self.max_bowl_shift = 0.0
    self.tub_lifted_t = None
    self.final = {}
    # work record for the fault-episode score (harness.fault_episode_score); no effect on physics or the stages
    self.holding = False              # both pads on one piece, or both on the tub
    self.held_s = 0.0
    self.n_stages = 2 * self.n + 1
    self.n_done = 0                   # stages met at this tick (packed, poured and in the bowl, parked in time)
    self.reach_t: list = []           # time each count of stages met was first reached
    # no fault starts before one stage is due at budget pace: grace + budget / n
    self.fault_floor_s = FAULT_GRACE_S + self.ep["budget_s"] / self.n_stages
    EPISODE["proc"] = self

  # -- geometry
  def _frame(self, d, b):
    return d.xpos[b].copy(), d.xmat[b].reshape(3, 3).copy()

  def in_tub(self, d, k):
    p, r = self._frame(d, self.tub)
    loc = r.T @ (d.xpos[self.fb[k]] - p)
    r_in = TUB_R_IN + (TUB_R_TOP - TUB_R_IN) * min(max(loc[2], 0.0), TUB_H) / TUB_H
    return math.hypot(loc[0], loc[1]) < r_in and -0.005 < loc[2] < TUB_H + 0.025

  def in_bowl(self, d, k):
    p, r = self._frame(d, self.bowl)
    loc = r.T @ (d.xpos[self.fb[k]] - p)
    return math.hypot(loc[0], loc[1]) < BOWL_TOP_R and 0.0 < loc[2] < BOWL_TOP_Z + 0.01

  def in_crate(self, d, k):
    p, r = self._frame(d, self.crate)
    loc = r.T @ (d.xpos[self.fb[k]] - p)
    return abs(loc[0]) < CRATE_IN[0] and abs(loc[1]) < CRATE_IN[1] and loc[2] < CRATE_WALL_H + 0.01

  def tub_tilt(self, d):
    return tilt_deg(d.xquat[self.tub])

  def _contacts(self, m, d):
    """(per fruit per pad normal force, robot touching tub, robot touching each fruit, fruit touching bench, per pad
    normal force on the tub)."""
    pf = np.zeros((self.n, 2))
    pt = np.zeros(2)
    tub_touch = False
    ftouch = np.zeros(self.n, bool)
    fbench = np.zeros(self.n, bool)
    nc = d.ncon
    if nc == 0:
      return pf, tub_touch, ftouch, fbench, pt
    g1 = np.asarray(d.contact.geom1[:nc]); g2 = np.asarray(d.contact.geom2[:nc])
    b1, b2 = m.geom_bodyid[g1], m.geom_bodyid[g2]
    adr = np.asarray(d.contact.efc_address[:nc])
    for i in range(nc):
      x, y = int(b1[i]), int(b2[i])
      rx, ry = self.robot[x], self.robot[y]
      if rx or ry:
        other = y if rx else x
        rob = x if rx else y
        if other == self.tub:
          tub_touch = True
          pk = self.pad_of[rob]
          if pk >= 0 and adr[i] >= 0:
            pt[pk] += abs(float(d.efc_force[adr[i]]))
        fk = self.fruit_of[other]
        if fk >= 0:
          ftouch[fk] = True
          pk = self.pad_of[rob]
          if pk >= 0 and adr[i] >= 0:
            pf[fk, pk] += abs(float(d.efc_force[adr[i]]))
      elif int(g1[i]) == self.bench or int(g2[i]) == self.bench:
        fk = self.fruit_of[y if int(g1[i]) == self.bench else x]
        if fk >= 0:
          fbench[fk] = True
    return pf, tub_touch, ftouch, fbench, pt

  def _violate(self, name, t, info=""):
    if name not in self.viol:
      self.viol[name] = t
      self.events.append((round(t, 2), name, info))

  # -- per control tick
  def tick(self, m, d, disturbance_time=None):
    t = float(d.time)
    if self.bowl0 is None:
      self.bowl0 = d.xpos[self.bowl, :2].copy()
      self.tub0 = d.xpos[self.tub].copy()
    pf, tub_touch, ftouch, fbench, pt = self._contacts(m, d)
    self.holding = bool(np.any(np.all(pf > 0.5, axis=1)) or np.all(pt > 0.5))
    if self.holding:
      self.held_s += self.dt
    self.squeeze.append(pf.max(axis=1))
    held = np.min(np.array(self.squeeze), axis=0) if len(self.squeeze) == 3 else np.zeros(self.n)
    for k in range(self.n):
      if held[k] > self.max_squeeze[k]:
        self.max_squeeze_t[k] = round(t, 2)
    self.max_squeeze = np.maximum(self.max_squeeze, held)
    for k in range(self.n):
      lim = SOFT_N if self.fruit[k]["kind"] == "peach" else FIRM_N
      if held[k] > lim:
        self._violate("bruised" if self.fruit[k]["kind"] == "peach" else "squeezed", t,
                      f"{self.fruit[k]['body']} {held[k]:.1f} N")
    tilt = self.tub_tilt(d)
    tub_z = float(d.xpos[self.tub, 2])
    if self.tub_lifted_t is None and tub_z > self.tub0[2] + 0.02:
      self.tub_lifted_t = t
    # the tub may not fall over or off the bench
    if (tilt > 60.0 and not tub_touch) or tub_z < -0.03:
      self._violate("tub_dropped", t, f"tilt {tilt:.0f} deg")
    shift = float(np.linalg.norm(d.xpos[self.bowl, :2] - self.bowl0))
    self.max_bowl_shift = max(self.max_bowl_shift, shift)
    if shift > BOWL_SHIFT_M:
      self._violate("bowl_moved", t, f"{1000 * shift:.0f} mm")
    tub_resting = tub_z < self.tub0[2] + 0.004 and tilt < TUB_UPRIGHT_DEG and not tub_touch
    for k in range(self.n):
      inside = self.in_tub(d, k)
      v = np.zeros(6)
      mujoco.mj_objectVelocity(m, d, mujoco.mjtObj.mjOBJ_BODY, int(self.fb[k]), v, 0)
      still = float(np.linalg.norm(v[3:])) < 0.03
      if inside and still and tub_resting and not ftouch[k] and self.packed_t[k] is None:
        self.packed_t[k] = t
        self.events.append((round(t, 2), self.fruit[k]["body"], "packed"))
      if self.was_in_tub[k] and not inside and tilt > POUR_TILT_DEG and self.packed_t[k] is not None:
        self.poured[k] = True
      self.was_in_tub[k] = inside
      # a fruit on the bench, or under it, has been spilt (the crate, the tub and the bowl stand on the bench)
      if self.spilled_t[k] is None and (fbench[k] or float(d.xpos[self.fb[k], 2]) < -0.02):
        self.spilled_t[k] = t
        self._violate("spill", t, self.fruit[k]["body"])
    # tub parked on the mat: since when (start of its final stay)
    p, r = self._frame(d, self.mat)
    loc = r.T @ (d.xpos[self.tub] - p)
    on_mat = (abs(loc[0]) <= TUB_ON_MAT_M and abs(loc[1]) <= TUB_ON_MAT_M and abs(loc[2] - MAT_TOP) < 0.004
              and tilt < TUB_UPRIGHT_DEG and not tub_touch)
    if on_mat and self.mat_since is None:
      self.mat_since = t
    elif not on_mat:
      self.mat_since = None
    self._last = dict(tub_touch=tub_touch, ftouch=ftouch.copy(), on_mat=on_mat, loc=loc, tilt=tilt)
    self._d = d
    # stages met at this tick, as `stages` would judge them now
    ok = [self.packed_t[k] is not None and self.max_squeeze[k] <= (SOFT_N if self.fruit[k]["kind"] == "peach" else FIRM_N)
          for k in range(self.n)]
    poured = [ok[k] and self.poured[k] and self.spilled_t[k] is None and not ftouch[k] and self.in_bowl(d, k)
              for k in range(self.n)]
    in_tub_any = any(self.was_in_tub)
    # the park counts only for a tub that has been poured from (an empty tub carried to the mat is no stage)
    parked = (self.mat_since is not None and not in_tub_any and any(self.poured)
              and self.mat_since <= self.ep["budget_s"])
    self.n_done = int(sum(ok) + sum(poured) + parked)
    while len(self.reach_t) < self.n_done:
      self.reach_t.append(round(t, 2))

  def io(self) -> dict:
    return {"pieces": int(self.n), "budget_s": float(self.ep["budget_s"]), "soft": "peach",
            "soft_limit_n": SOFT_N, "firm_limit_n": FIRM_N}

  # -- verdicts
  def stages(self):
    d = self._d
    out = []
    budget = self.ep["budget_s"]
    last = self._last
    in_bowl = [self.in_bowl(d, k) for k in range(self.n)]
    in_tub = [self.in_tub(d, k) for k in range(self.n)]
    in_crate = [self.in_crate(d, k) for k in range(self.n)]
    bad_squeeze = [self.max_squeeze[k] > (SOFT_N if self.fruit[k]["kind"] == "peach" else FIRM_N) for k in range(self.n)]
    for k in range(self.n):
      name = self.fruit[k]["body"]
      ok = self.packed_t[k] is not None and not bad_squeeze[k]
      reason = ""
      if not ok:
        reason = ("force" if bad_squeeze[k] else "grasp" if in_crate[k] else
                  "transport")
      out.append({"name": f"pack:{name}", "skill": "pack", "done": bool(ok), "t": self.packed_t[k] if ok else None,
                  "reason": reason, "kind": self.fruit[k]["kind"]})
    for k in range(self.n):
      name = self.fruit[k]["body"]
      ok = (self.packed_t[k] is not None and not bad_squeeze[k] and in_bowl[k] and self.poured[k]
            and self.spilled_t[k] is None and not last["ftouch"][k])
      reason = ""
      if not ok:
        reason = ("force" if bad_squeeze[k] else "transport" if self.packed_t[k] is None else
                  "pour" if (in_tub[k] or not in_bowl[k] or not self.poured[k]) else "grasp")
      out.append({"name": f"pour:{name}", "skill": "pour", "done": bool(ok), "t": None, "reason": reason})
    empty = not any(in_tub)
    mat_ok = self.mat_since is not None and empty and any(self.poured)
    late = mat_ok and self.mat_since > budget
    reason = ""
    if not mat_ok:
      reason = ("pour" if self.mat_since is not None and (not empty or not any(self.poured)) else
                ("grasp" if last["tub_touch"] else "transport"))
    elif late:
      reason = "timeout"
    out.append({"name": "park:tub", "skill": "park", "done": bool(mat_ok and not late),
                "t": self.mat_since if mat_ok else None, "reason": reason})
    # pour stages are timed by the park (the job is done once the empty tub is parked)
    for s in out:
      if s["skill"] == "pour" and s["done"]:
        s["t"] = self.mat_since if self.mat_since is not None else budget
    self.final = {"tub_on_mat_mm": [round(1000 * float(x), 1) for x in last["loc"][:2]],
                  "tub_tilt_deg": round(float(last["tilt"]), 1),
                  "in_bowl": in_bowl, "in_tub": in_tub, "in_crate": in_crate}
    return out

  def all_done(self):
    return all(s["done"] for s in self.stages())


def success(pe, p0) -> bool:
  proc = EPISODE.get("proc")
  return bool(proc is not None and proc.all_done())


def progress(pe, p0) -> float:
  proc = EPISODE.get("proc")
  if proc is None:
    return 0.0
  st = proc.stages()
  return sum(1 for s in st if s["done"]) / max(1, len(st))


def audit(watch, f, poses, body_names, settle_start, dt, proc=None):
  """The station's own limits (bruise, squeeze, spill, bowl moved, tub dropped) as safety violations, and the
  stage record as metrics."""
  if proc is None:
    return [], {}
  st = proc.stages()
  park = [s for s in st if s["skill"] == "park"][0]
  metrics = {
      "stages": st, "violation_times": {k: round(v, 3) for k, v in proc.viol.items()},
      "n_pieces": proc.n, "budget_s": proc.ep["budget_s"], "band": proc.ep["band"],
      "cycle_time_s": round(park["t"], 3) if (park["t"] is not None and all(s["done"] for s in st)) else None,
      "max_squeeze_n": [round(float(x), 1) for x in proc.max_squeeze], "max_squeeze_t": proc.max_squeeze_t,
      "bowl_shift_mm": round(1000 * proc.max_bowl_shift, 1),
      "kinds": [f["kind"] for f in proc.fruit], "events": proc.events[-40:], "final": proc.final,
      "n_stages": proc.n_stages, "time_limit_s": proc.ep["budget_s"],     # pace for harness.fault_episode_score
      "fault_grace_s": FAULT_GRACE_S, "fault_floor_s": round(proc.fault_floor_s, 3),
      "stages_met_t": proc.reach_t, "held_s": round(proc.held_s, 2),
  }
  return list(proc.viol), metrics


TASK = G.Task(
    task_id="fp2_fruit_prep",
    scene_xml=SCENE,
    target_body="fruit_0",
    support_body="bowl",
    bystander_bodies=(),
    success=success,
    progress=progress,
    pad_pattern=r"^robot/(left_pad|right_pad)$",
    gripper_actuators=("robot/gripper",),
    observed_bodies=("crate", "mat"),
    control_dt_s=0.02,
    episode_s=EPISODE_S,
    perception_hz=2.0,
    perception_noise_m=(0.001, 0.002),
    home_qpos=HOME,
    safety=G.SafetyLimits(max_grasp_force_n=35.0, max_contact_force_n=60.0, drop_z_tol_m=None),
    setup=setup,
    cameras=(("overhead", 256, 192, True), ("robot/wrist_cam", 128, 96, False)),
    audit=audit,
    process=Station,
    disturb_speed={"push": 0.3, "knockout": 0.3},
    # T4 faults start only with something in the jaws: the trigger arms when both pads first hold one piece or the
    # tub, and the delay counts held time only (0.2-50 s), so the fault lands anywhere from the first pick to the
    # park and waiting for it does not bring it. No fault starts before Station.fault_floor_s (35 s + budget / n),
    # when one stage is due; a fault due earlier starts at the first held tick after it. A fault batch is scored against budget pace
    # (harness.fault_episode_score). No abort deadline: a dead gripper holding its setpoint shows only once the
    # gripper command changes (for a held tub, at the release).
    fault_triggers=("grasp", "grasp"),
    fault_delay_s={"grasp": (0.2, 50.0)},
)