File size: 30,273 Bytes
602054e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
"""Bench test fixture FT-2: load a board under test, run the test, unload it, with an SO-101.

Builds the `gauntlet.Task` the acceptance run uses, including the fixture logic (`Fixture`): connector latches,
the test button and lamps, and the connector load cells. Read-only: the acceptance run checks this file's hash
and uses its own copy.
"""
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")
TIMESTEP = 0.002

# ---- Fit (diametral clearance of both receptacles, one value per board lot) ----
CLEARANCE_RANGE = (0.0003, 0.0010)
NOMINAL_CLEARANCE = 0.0006

# ---- DC barrel plug (5.5 mm barrel) and jack ----
DC_BARREL_R = 0.00275
DC_BARREL_END = 0.0225          # barrel tip, plug frame (+x = barrel direction, origin = housing centre)
DC_PLUG_MASS = 0.012
DC_BORE_START, DC_BORE_END, DC_CHAMFER = -0.0115, -0.0008, 0.0008   # jack frame, +x out of the mouth
DC_CONTACT_X = -0.0080          # centre-pin spring contact (plate) at rest
DC_JACK_POS = (0.0, 0.047, 0.0071)   # board frame: mouth 2 mm past the board's +y edge, axis 5.5 mm over the board
DC_SPRING_K, DC_SPRING_F0 = 500.0, 2.0

# ---- 2-pin keyed header (plug housing 10 x 7 mm, key rib and latch on the +y face) ----
HDR_PLUG_MASS = 0.006
RIB_HALF_W, RIB_PROUD = 0.0012, 0.0009
LATCH_PIVOT_Z, LATCH_REST, LATCH_RANGE, LATCH_K = 0.011, 0.15, 0.20, 0.04
SHROUD_POS = (0.006, -0.020, 0.0016)  # board frame, on the board top
SHROUD_WALL_H, SHROUD_CHAMFER = 0.007, 0.001
HDR_CONTACT_Z = 0.003
HDR_SPRING_K, HDR_SPRING_F0 = 250.0, 1.2
CONTACT_TRAVEL = 0.003
SEAT_FRAC = 0.60                # spring contact pushed this far through its travel = seated

# ---- Board, nest, button ----
BOARD_HALF = (0.035, 0.045)
BOARD_MASS = 0.07
NEST_XY = (0.215, 0.0)
NEST_HALF = (0.065, 0.040)
PIN_A, PIN_B = (-0.028, -0.034), (0.028, 0.034)
BUTTON_XY = (-0.050, 0.020)
BUTTON_TRAVEL, BUTTON_K, BUTTON_F0 = 0.003, 300.0, 2.5
BUTTON_TRIP = 0.002
LIFT_LIMIT_M = 0.001            # board off its pins by more than this = lifted

# ---- Parking ----
DC_PAD_XY = (0.205, 0.130)
HOLDER_XY = (0.165, -0.115)
TARGETS_XY = ((0.33, -0.16), (0.33, 0.0), (0.33, 0.16))   # white registration discs on the duct cover
TARGET_R = 0.006
# ---- Touch-off probes (bench datum switches) ----
PROBE_XY = ((0.105, 0.065), (0.115, -0.030), (0.270, -0.100))
PROBE_TOP = 0.021                      # plunger cap top at rest (bench frame)
PROBE_TRAVEL, PROBE_K, PROBE_F0 = 0.004, 150.0, 0.5
PROBE_TRIP = 0.001                     # switch closes once the plunger is pushed down this far
HOLDER_HALF = (0.013, 0.011)          # parking socket block, outer half size
HOLDER_FLOOR, HOLDER_TOP = 0.002, 0.008
POCKET_X = 0.00515                     # pocket half length (plug half 5.0 mm): a snug parking fit
POCKET_Y = (-0.00365, 0.00455)         # pocket y span (plug -3.5 mm face, +4.4 mm over the key rib)
HOLDER_YAW_PUBLIC, HOLDER_YAW_LIMIT = 20.0, 25.0


def holder_geoms():
  """Parking socket: floor and four walls around a pocket, frame at the pocket's plug origin on the bench."""
  hx, hy = HOLDER_HALF
  hz = 0.5 * (HOLDER_TOP - HOLDER_FLOOR)
  zc = HOLDER_FLOOR + hz
  y0, y1 = POCKET_Y
  return [
      ("floor", (0.0, 0.0, HOLDER_FLOOR / 2), (hx, hy, HOLDER_FLOOR / 2)),
      ("wall_mx", (-(POCKET_X + hx) / 2, 0.0, zc), ((hx - POCKET_X) / 2, hy, hz)),
      ("wall_px", ((POCKET_X + hx) / 2, 0.0, zc), ((hx - POCKET_X) / 2, hy, hz)),
      ("wall_my", (0.0, (y0 - hy) / 2, zc), (POCKET_X, (hy + y0) / 2, hz)),
      ("wall_py", (0.0, (y1 + hy) / 2, zc), (POCKET_X, (hy - y1) / 2, hz)),
  ]

# ---- Cables ----
DC_ANCHOR = (0.22, 0.25, 0.02)
HDR_ANCHOR = (0.22, -0.25, 0.02)
DC_CABLE_SLACK, HDR_CABLE_SLACK = 0.150, 0.270
CABLE_K_NOMINAL = 20.0
CABLE_K_RANGE = (7.5, 41.25)

# ---- Camera ----
OVERHEAD_POS = (0.22, 0.0, 0.62)
OVERHEAD_FOVY = 40


def _quat_from_axes(ax, ay, az):
  R = np.column_stack([ax, ay, az]).astype(float)
  q = np.zeros(4)
  mujoco.mju_mat2Quat(q, R.reshape(-1))
  return q


def dc_bore_geoms(c: float):
  """(name, pos, quat, half sizes) of the jack's bore staves for diametral clearance c (jack frame)."""
  rb = DC_BARREL_R + c / 2
  t = 0.001
  n = 8
  w = (rb + t) * math.tan(math.pi / n) + 0.0002
  out = []
  L = DC_BORE_END - DC_BORE_START
  xc = (DC_BORE_END + DC_BORE_START) / 2
  for k in range(n):
    a = 2 * math.pi * k / n + math.pi / n
    rad = np.array([0.0, math.cos(a), math.sin(a)])
    tan = np.array([0.0, -math.sin(a), math.cos(a)])
    ax = np.array([1.0, 0.0, 0.0])
    out.append((f"bore{k}", ax * xc + rad * (rb + t / 2), _quat_from_axes(ax, rad, tan), (L / 2, t / 2, w)))
    # 45 deg lead-in: face from (x=-ch, r=rb) to (x=0, r=rb+ch)
    ch = DC_CHAMFER
    fdir = (ax + rad) / math.sqrt(2)          # along the face, outward and toward the mouth
    nrm = (rad - ax) / math.sqrt(2)           # into the material
    mid = ax * (-ch / 2) + rad * (rb + ch / 2)
    out.append((f"lead{k}", mid + nrm * (t / 2), _quat_from_axes(fdir, nrm, tan), (ch * 0.75, t / 2, w + ch)))
  return out


def shroud_geoms(c: float):
  """(name, pos, quat, half sizes) of the header shroud walls and lead-ins for diametral clearance c."""
  a, b = 0.005 + c / 2, 0.0035 + c / 2
  t, h, ch = 0.001, SHROUD_WALL_H, SHROUD_CHAMFER
  s = RIB_HALF_W + c / 2 + 0.0002          # key slot half width in the +y wall
  out = []
  ez = np.array([0.0, 0.0, 1.0])

  def wall(name, centre_xy, along, outward, half_len, inner):
    """A straight wall segment and its 45 deg lead-in. along/outward: unit xy vectors; inner = distance of the
    inner face from the shroud axis along `outward`."""
    along = np.array([*along, 0.0]); outward = np.array([*outward, 0.0])
    cxy = np.array([*centre_xy, 0.0])
    out.append((name, cxy + outward * (inner + t / 2) + ez * (h / 2), _quat_from_axes(along, outward, np.cross(along, outward)),
                (half_len, t / 2, h / 2)))
    fdir = (outward + ez) / math.sqrt(2)
    nrm = (outward - ez) / math.sqrt(2)
    mid = cxy + outward * (inner + ch / 2) + ez * (h + ch / 2)
    out.append((name + "_lead", mid + nrm * (t / 2), _quat_from_axes(along, fdir, np.cross(along, fdir)),
                (half_len, ch * 0.75, t / 2)))

  wall("wall_my", (0.0, 0.0), (1, 0), (0, -1), a + t, b)
  wall("wall_px", (0.0, 0.0), (0, 1), (1, 0), b, a)
  wall("wall_mx", (0.0, 0.0), (0, 1), (-1, 0), b, a)
  seg = (a + t - s) / 2
  wall("wall_py_r", ((s + a + t) / 2, 0.0), (1, 0), (0, 1), seg, b)
  wall("wall_py_l", (-(s + a + t) / 2, 0.0), (1, 0), (0, 1), seg, b)
  return out


# ---- Limits (fixture spec) ----
DC_PUSH_MAX_N = 12.0            # axial push on the DC plug while it is in the jack
HDR_PUSH_MAX_N = 10.0           # axial push on the header plug while it is in the shroud
DC_SIDE_MAX_N = 5.0             # force across the connector axis while engaged
HDR_SIDE_MAX_N = 4.0
SQUEEZE_MAX_N = 25.0            # either plug housing
HDR_PULL_MAX_N = 15.0           # pulling a latched header harder than this breaks the latch
DC_RETENTION_RANGE = (2.5, 3.5)
TEST_S_RANGE = (1.5, 3.0)
HOLD_TICKS = 3                  # a load counts when held over 3 control ticks (60 ms)
LATCH_ENGAGE, LATCH_RELEASE = 0.10, 0.06

HOME = {"robot/shoulder_pan": 0.0, "robot/shoulder_lift": -1.6, "robot/elbow_flex": -1.45,
        "robot/wrist_flex": 1.0, "robot/wrist_roll": 0.0, "robot/gripper": 0.2}

# ---- Layout ranges: public draws (in_range) and the documented cell limits (outside band reaches them) ----
NEST_DXY_PUBLIC, NEST_DXY_LIMIT = 0.015, 0.019
NEST_YAW_PUBLIC, NEST_YAW_LIMIT = 6.0, 7.5
SHROUD_REVS = {"A": -0.012, "B": 0.0, "C": 0.012}      # header position along the board (board x) per revision
SHROUD_X_LIMIT = (-0.012, 0.012)
DC_START_PUBLIC = ((0.180, 0.230), (0.110, 0.150), (-120.0, -60.0))   # x, y, yaw deg of the plug (final)
DC_START_LIMIT = ((0.174, 0.236), (0.105, 0.155), (-127.5, -52.5))
HOLDER_PUBLIC = ((0.150, 0.190), (-0.130, -0.095))
HOLDER_LIMIT = ((0.145, 0.195), (-0.135, -0.090))
CABLE_K_PUBLIC, CABLE_K_LIMIT = (10.0, 35.0), (7.5, 41.25)
CLEAR_PUBLIC, CLEAR_LIMIT = (0.0004, 0.0009), (0.0003, 0.0010)

EPISODE: dict = {}   # written by `setup`, read by the fixture process and the grading functions below


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


BAND_ORDER = ("in_range", "in_between", "in_range", "outside")
BAND_SHIFT = {"T0": 0, "T1": 3, "T2": 2, "T3": 1, "T4": 0}


def band_of(idx: int, tier: str = "T0") -> str:
  """Placement band of episode `idx` of a tier: in_range, in_between, in_range, outside in turn, the cycle shifted
  per tier so that short runs of every tier still see all three bands (about half / a quarter / a quarter)."""
  return BAND_ORDER[(idx + BAND_SHIFT.get(tier, 0)) % 4]


def _draw(rng, pub, lim, band):
  """One value: inside the public range, or (outside band) in the margin between it and the limit."""
  if band != "outside":
    return float(rng.uniform(*pub))
  lo_w, hi_w = pub[0] - lim[0], lim[1] - pub[1]
  u = float(rng.uniform(0, lo_w + hi_w))
  return lim[0] + u if u < lo_w else pub[1] + (u - lo_w)


def setup(m: mujoco.MjModel, d: mujoco.MjData, rng: np.random.Generator, p=None) -> None:
  """Lays out the cycle: fixture pose, board revision, fit, cable stiffness, plug start poses."""
  tier = getattr(p, "tier", "T0")
  band = EPISODE.get("force_band") or band_of(int(getattr(p, "idx", 0)), tier)
  # fixture nest pose
  if band == "outside":
    dx = _draw(rng, (-NEST_DXY_PUBLIC, NEST_DXY_PUBLIC), (-NEST_DXY_LIMIT, NEST_DXY_LIMIT), band)
    dy = _draw(rng, (-NEST_DXY_PUBLIC, NEST_DXY_PUBLIC), (-NEST_DXY_LIMIT, NEST_DXY_LIMIT), band)
    yaw = _draw(rng, (-NEST_YAW_PUBLIC, NEST_YAW_PUBLIC), (-NEST_YAW_LIMIT, NEST_YAW_LIMIT), band)
  else:
    dx, dy = rng.uniform(-NEST_DXY_PUBLIC, NEST_DXY_PUBLIC, 2)
    yaw = float(rng.uniform(-NEST_YAW_PUBLIC, NEST_YAW_PUBLIC))
  nest = m.body("nest").id
  m.body_pos[nest, :2] = np.array(NEST_XY) + (dx, dy)
  m.body_quat[nest] = _quat_z(math.radians(yaw))
  # board revision: header position along the board
  if band == "in_between":
    sx = float(rng.uniform(*SHROUD_X_LIMIT))
    rev = "engineering sample"
  else:
    rev = "ABC"[int(rng.integers(3))]
    sx = SHROUD_REVS[rev]
  sh = m.body("hdr_shroud").id
  m.body_pos[sh] = (sx + SHROUD_POS[0], SHROUD_POS[1], SHROUD_POS[2])
  # fit
  c = _draw(rng, CLEAR_PUBLIC, CLEAR_LIMIT, band)
  for name, pos, quat, size in dc_bore_geoms(c):
    g = m.geom("dc_" + name).id
    m.geom_pos[g], m.geom_quat[g] = pos, quat
  for name, pos, quat, size in shroud_geoms(c):
    g = m.geom("hdr_" + name).id
    m.geom_pos[g], m.geom_quat[g] = pos, quat
  # cables
  k_cable = _draw(rng, CABLE_K_PUBLIC, CABLE_K_LIMIT, band)
  for t in ("dc_cable", "hdr_cable"):
    m.tendon_stiffness[m.tendon(t).id] = k_cable
  # DC plug start pose (final, after the tier's offset of the target)
  off = np.zeros(2) if p is None else np.asarray(p.target_xy_m, float)
  oyaw = 0.0 if p is None else float(p.target_yaw_deg)
  lim = DC_START_LIMIT if band == "outside" else DC_START_PUBLIC
  x = _draw(rng, DC_START_PUBLIC[0], DC_START_LIMIT[0], band)
  y = _draw(rng, DC_START_PUBLIC[1], DC_START_LIMIT[1], band)
  pyaw = _draw(rng, DC_START_PUBLIC[2], DC_START_LIMIT[2], band)
  adr = m.jnt_qposadr[m.joint("dc_plug").id]
  d.qpos[adr:adr + 3] = (x - off[0], y - off[1], 0.0045)
  d.qpos[adr + 3:adr + 7] = _quat_z(math.radians(pyaw - oyaw))
  # header parking cup (the gauntlet's support body; its tier offset is added later) and plug yaw
  doff = np.zeros(2) if p is None else np.asarray(p.dest_xy_m, float)
  hx = _draw(rng, HOLDER_PUBLIC[0], HOLDER_LIMIT[0], band)
  hy = _draw(rng, HOLDER_PUBLIC[1], HOLDER_LIMIT[1], band)
  hyaw = _draw(rng, (-HOLDER_YAW_PUBLIC, HOLDER_YAW_PUBLIC), (-HOLDER_YAW_LIMIT, HOLDER_YAW_LIMIT), band)
  hb = m.body("holder").id
  m.body_pos[hb, :2] = (hx - doff[0], hy - doff[1])
  m.body_quat[hb] = _quat_z(math.radians(hyaw))
  adr = m.jnt_qposadr[m.joint("hdr_plug").id]
  d.qpos[adr:adr + 3] = (hx, hy, HOLDER_FLOOR)
  d.qpos[adr + 3:adr + 7] = _quat_z(math.radians(hyaw))
  force_band = EPISODE.get("force_band")       # run_gauntlet.py --band: kept for every cycle of the run
  EPISODE.clear()
  if force_band:
    EPISODE["force_band"] = force_band
  EPISODE.update(band=band, tier=tier, clearance=c, cable_k=k_cable, revision=rev, shroud_x=sx,
                 nest=(float(m.body_pos[nest, 0]), float(m.body_pos[nest, 1]), yaw),
                 dc_retention=float(rng.uniform(*DC_RETENTION_RANGE)), test_s=float(rng.uniform(*TEST_S_RANGE)))
  mujoco.mj_forward(m, d)


# ---------------------------------------------------------------------------------------------- fixture process
def _rel_pose(d, b1, b2):
  """Pose of body b2 in the frame of body b1 (pos, quat)."""
  R1 = d.xmat[b1].reshape(3, 3)
  pos = R1.T @ (d.xpos[b2] - d.xpos[b1])
  q1inv = np.zeros(4); mujoco.mju_negQuat(q1inv, d.xquat[b1])
  q = np.zeros(4); mujoco.mju_mulQuat(q, q1inv, d.xquat[b2])
  return pos, q


class Fixture:
  """Connector latches, connector load cells, test button and lamps (privileged, once per control tick)."""

  def __init__(self, m: mujoco.MjModel, d: mujoco.MjData, p, dt: float):
    self.m, self.dt = m, dt
    self.ep = EPISODE
    self.tier = getattr(p, "tier", "T0")
    self.dc = m.body("dc_plug").id
    self.hdr = m.body("hdr_plug").id
    self.jack = m.body("dc_jack").id
    self.shroud = m.body("hdr_shroud").id
    self.board = m.body("board").id
    self.nest = m.body("nest").id
    self.q_dc_contact = m.jnt_qposadr[m.joint("dc_contact").id]
    self.q_hdr_contact = m.jnt_qposadr[m.joint("hdr_contact").id]
    self.q_latch = m.jnt_qposadr[m.joint("hdr_latch").id]
    self.q_lift = m.jnt_qposadr[m.joint("board_lift").id]
    self.q_button = m.jnt_qposadr[m.joint("button").id]
    self.q_probe = [m.jnt_qposadr[m.joint(f"probe_{k}").id] for k in range(len(PROBE_XY))]
    self.probe = [False] * len(PROBE_XY)
    self.eq_dc = m.equality("dc_lock").id
    self.eq_hdr = m.equality("hdr_lock").id
    self.tip_site = m.site("dc_tip").id
    self.jaws = (m.body("robot/gripper").id, m.body("robot/moving_jaw_so101_v1").id)
    self.holding = False                                 # a plug between both jaws (for the T4 grasp trigger)
    rb = [b for b in range(m.nbody) if (m.body(b).name or "").startswith("robot/")]
    self.robot_geom = np.isin(m.geom_bodyid, rb)
    self.plug_of_geom = np.full(m.ngeom, -1)
    self.plug_of_geom[m.geom_bodyid == self.dc] = 0
    self.plug_of_geom[(m.geom_bodyid == self.hdr) | (m.geom_bodyid == m.body("hdr_latch").id)] = 1
    self.lamp_pass = m.geom("lamp_pass").id
    self.lamp_fail = m.geom("lamp_fail").id
    self.f6 = np.zeros(6)
    self.hist = collections.deque(maxlen=HOLD_TICKS)     # per tick: (force on dc (3), force on hdr (3), squeeze (2))
    self.dc_locked = self.hdr_locked = False
    self.dc_ever = self.hdr_ever = None                  # first time each plug latched
    self.lamp = "off"
    self.results: list[tuple[float, str]] = []
    self.test_end = None
    self.button_down = False
    self.presses = 0
    self.max_lift = 0.0
    self.lift_hit = None
    self.peak = dict(dc_push=0.0, hdr_push=0.0, dc_side=0.0, hdr_side=0.0, squeeze=0.0, hdr_pull=0.0)
    self.hits: dict[str, float] = {}
    self.events: list = []
    self.dc_out_t = self.hdr_out_t = None
    self.held_at_end = False
    self.park_since = None
    m.eq_data[self.eq_dc, 10] = 1.0
    m.eq_data[self.eq_hdr, 10] = 1.0
    d.eq_active[self.eq_dc] = d.eq_active[self.eq_hdr] = False
    EPISODE["proc"] = self
    EPISODE["_md"] = (m, d)

  # -- readings
  def robot_forces(self, m, d):
    """Net force the robot puts on each plug (world, contact normal + friction), and the squeeze on each: the
    larger of the two jaws' summed force vectors on it (as the gauntlet's grasp force)."""
    out = np.zeros((2, 3)); sq = np.zeros(2)
    n = d.ncon
    if n == 0:
      self.holding = False
      return out, sq
    g1 = np.asarray(d.contact.geom1[:n]); g2 = np.asarray(d.contact.geom2[:n])
    r1, r2 = self.robot_geom[g1], self.robot_geom[g2]
    p1, p2 = self.plug_of_geom[g1], self.plug_of_geom[g2]
    per_body: dict = {}
    for i in np.nonzero((r1 & (p2 >= 0)) | (r2 & (p1 >= 0)))[0]:
      mujoco.mj_contactForce(m, d, int(i), self.f6)
      fr = np.asarray(d.contact.frame[i]).reshape(3, 3)
      f_w = fr.T @ self.f6[:3]               # force on geom2 from geom1 (world)
      if r1[i]:
        plug, f_on, rb = int(p2[i]), f_w, int(m.geom_bodyid[g1[i]])
      else:
        plug, f_on, rb = int(p1[i]), -f_w, int(m.geom_bodyid[g2[i]])
      out[plug] += f_on
      per_body[(plug, rb)] = per_body.get((plug, rb), 0.0) + f_on
    for (plug, _), v in per_body.items():
      sq[plug] = max(sq[plug], float(np.linalg.norm(v)))
    self.holding = any(all((k, j) in per_body for j in self.jaws) for k in (0, 1))
    return out, sq

  def dc_axis(self, d):
    """(mouth position, outward unit axis) of the jack."""
    return d.xpos[self.jack].copy(), d.xmat[self.jack].reshape(3, 3)[:, 0].copy()

  def dc_depth(self, d):
    """How far the barrel tip is inside the jack mouth (m, > 0 inside)."""
    o, ax = self.dc_axis(d)
    rel = d.site_xpos[self.tip_site] - o
    lat = np.linalg.norm(rel - (rel @ ax) * ax)
    return -float(rel @ ax), float(lat)

  def hdr_depth(self, d):
    """How far the plug bottom is below the shroud top (m, > 0 inside) and its lateral offset."""
    R = d.xmat[self.shroud].reshape(3, 3)
    rel = R.T @ (d.xpos[self.hdr] - d.xpos[self.shroud])
    return float(SHROUD_WALL_H + SHROUD_CHAMFER - rel[2]), float(np.hypot(rel[0], rel[1]))

  def dc_seated(self, d):
    return d.qpos[self.q_dc_contact] <= -SEAT_FRAC * CONTACT_TRAVEL

  def hdr_seated(self, d):
    return d.qpos[self.q_hdr_contact] <= -SEAT_FRAC * CONTACT_TRAVEL

  def _lock(self, m, d, eq, b1, b2):
    pos, q = _rel_pose(d, b1, b2)
    m.eq_data[eq, 0:3] = 0.0
    m.eq_data[eq, 3:6] = pos
    m.eq_data[eq, 6:10] = q
    d.eq_active[eq] = True

  def _hit(self, name, t):
    if name not in self.hits:
      self.hits[name] = round(t, 2)
      self.events.append((round(t, 2), "violation", name))

  # -- per control tick
  def tick(self, m, d, disturbance_time=None):
    t = float(d.time)
    f, sq = self.robot_forces(m, d)
    self.hist.append((f, sq))
    held = len(self.hist) == HOLD_TICKS
    # loads held over 60 ms: per component the smallest magnitude over the window
    o, ax = self.dc_axis(d)
    dc_in, dc_lat = self.dc_depth(d)
    h_in, h_lat = self.hdr_depth(d)
    dc_clear = dc_in < -0.002 or dc_lat > 0.006       # plug fully out of its receptacle
    h_clear = h_in < -0.002 or h_lat > 0.008
    hz = d.xmat[self.shroud].reshape(3, 3)[:, 2]
    if held:
      fs = np.array([h[0] for h in self.hist]); sqs = np.array([h[1] for h in self.hist])
      squeeze = float(np.min(sqs, axis=0).max())
      self.peak["squeeze"] = max(self.peak["squeeze"], squeeze)
      if squeeze > SQUEEZE_MAX_N:
        self._hit("plug_crushed", t)
      if self.dc_locked or (dc_in > 0.0005 and dc_lat < 0.004):
        push = np.min(fs[:, 0] @ (-ax))
        side = np.min(np.linalg.norm(fs[:, 0] - np.outer(fs[:, 0] @ ax, ax), axis=1))
        self.peak["dc_push"] = max(self.peak["dc_push"], float(push))
        self.peak["dc_side"] = max(self.peak["dc_side"], float(side))
        if push > DC_PUSH_MAX_N:
          self._hit("dc_overload", t)
        if side > DC_SIDE_MAX_N:
          self._hit("dc_side_load", t)
      if self.hdr_locked or (h_in > 0.0005 and h_lat < 0.006):
        push = np.min(fs[:, 1] @ (-hz))
        pull = np.min(fs[:, 1] @ hz)
        side = np.min(np.linalg.norm(fs[:, 1] - np.outer(fs[:, 1] @ hz, hz), axis=1))
        self.peak["hdr_push"] = max(self.peak["hdr_push"], float(push))
        self.peak["hdr_side"] = max(self.peak["hdr_side"], float(side))
        self.peak["hdr_pull"] = max(self.peak["hdr_pull"], float(pull))
        if push > HDR_PUSH_MAX_N:
          self._hit("hdr_overload", t)
        if side > HDR_SIDE_MAX_N:
          self._hit("hdr_side_load", t)
        if self.hdr_locked and pull > HDR_PULL_MAX_N:
          self._hit("hdr_latch_broken", t)
          d.eq_active[self.eq_hdr] = False
          self.hdr_locked = False
    # board on its pins
    lift = float(d.qpos[self.q_lift])
    self.max_lift = max(self.max_lift, lift)
    if lift > LIFT_LIMIT_M:
      self._hit("board_lifted", t)
    # DC jack: seats on the spring contact's end, holds until pulled out past the retention force
    if not self.dc_locked:
      if self.dc_seated(d):
        self._lock(m, d, self.eq_dc, self.jack, self.dc)
        self.dc_locked = True
        if self.dc_ever is None:
          self.dc_ever = t
        self.events.append((round(t, 2), "dc", "latched"))
    elif held:
      pull = float(np.mean(np.array([h[0][0] for h in self.hist]) @ ax))
      if pull > self.ep["dc_retention"]:
        d.eq_active[self.eq_dc] = False
        self.dc_locked = False
        self.events.append((round(t, 2), "dc", "released"))
    # header: the latch catches when the plug is seated and the tab is free; pressing the tab frees it
    lat = float(d.qpos[self.q_latch])
    if not self.hdr_locked:
      if self.hdr_seated(d) and lat > LATCH_ENGAGE:
        self._lock(m, d, self.eq_hdr, self.shroud, self.hdr)
        self.hdr_locked = True
        if self.hdr_ever is None:
          self.hdr_ever = t
        self.events.append((round(t, 2), "hdr", "latched"))
    elif lat < LATCH_RELEASE:
      d.eq_active[self.eq_hdr] = False
      self.hdr_locked = False
      self.events.append((round(t, 2), "hdr", "released"))
    # touch-off probe switches
    self.probe = [bool(d.qpos[q] <= -PROBE_TRIP) for q in self.q_probe]
    # test button and lamps
    down = d.qpos[self.q_button] <= -BUTTON_TRIP
    if down and not self.button_down:
      self.presses += 1
      if self.lamp != "testing":
        if self.dc_locked and self.hdr_locked and lift <= LIFT_LIMIT_M:
          self.lamp, self.test_end = "testing", t + self.ep["test_s"]
          self.events.append((round(t, 2), "test", "started"))
        else:
          self._result(m, t, "fail")
    self.button_down = down
    if self.lamp == "testing":
      if not (self.dc_locked and self.hdr_locked) or lift > LIFT_LIMIT_M:
        self._result(m, t, "fail")
      elif t >= self.test_end:
        self._result(m, t, "pass")
    # unplugged after the test: plug fully out of its receptacle
    if self.dc_out_t is None and self.dc_ever is not None and not self.dc_locked and dc_clear:
      self.dc_out_t = t
    if self.dc_out_t is not None and (self.dc_locked or not dc_clear):
      self.dc_out_t = None
    if self.hdr_out_t is None and self.hdr_ever is not None and not self.hdr_locked and h_clear:
      self.hdr_out_t = t
    if self.hdr_out_t is not None and (self.hdr_locked or not h_clear):
      self.hdr_out_t = None
    # parked: both out, on the bench clear of the nest, not held
    self.held_at_end = bool(sq.max() > 0.0)
    npose = np.concatenate([d.xpos[self.nest], d.xquat[self.nest]])
    park = (self.dc_out_t is not None and self.hdr_out_t is not None and not self.held_at_end
            and all(d.xpos[b][2] < 0.03 and not _in_nest(d.xpos[b], npose) for b in (self.dc, self.hdr)))
    if park and self.park_since is None:
      self.park_since = t
    elif not park:
      self.park_since = None

  @property
  def done_t(self):
    return self.park_since

  @property
  def n_done(self) -> int:
    """Stages done so far (as `stage_states` counts them, park as soon as both plugs lie parked)."""
    passed = bool(self.results) and self.results[0][1] == "pass"
    t_pass = self.results[0][0] if passed else None
    return int(sum((self.dc_ever is not None, self.hdr_ever is not None, passed,
                    passed and self.dc_out_t is not None and self.dc_out_t > t_pass,
                    passed and self.hdr_out_t is not None and self.hdr_out_t > t_pass,
                    passed and self.park_since is not None)))

  def _result(self, m, t, res):
    self.lamp = res
    self.test_end = None
    self.results.append((round(t, 2), res))
    self.events.append((round(t, 2), "test", res))
    m.geom_rgba[self.lamp_pass] = (0.1, 0.95, 0.2, 1) if res == "pass" else (0.05, 0.25, 0.05, 1)
    m.geom_rgba[self.lamp_fail] = (1.0, 0.1, 0.1, 1) if res == "fail" else (0.25, 0.05, 0.05, 1)

  def io(self) -> dict:
    return {"lamp": self.lamp, "power": bool(self.dc_locked), "tests": len(self.results), "probe": list(self.probe)}


def make_process(m, d, p, dt):
  return Fixture(m, d, p, dt)


# ---------------------------------------------------------------------------------------------- grading
STAGES = ("dc_insert", "hdr_insert", "test", "dc_unplug", "hdr_unplug", "park")


def _in_nest(pose, nest_pose, margin=0.010):
  """True if a position lies over the nest footprint grown by `margin`."""
  q = nest_pose[3:7]
  yaw = math.atan2(2 * (q[0] * q[3] + q[1] * q[2]), 1 - 2 * (q[2] ** 2 + q[3] ** 2))
  c, s = math.cos(yaw), math.sin(yaw)
  rel = np.asarray(pose[:2]) - np.asarray(nest_pose[:2])
  loc = np.array([c * rel[0] + s * rel[1], -s * rel[0] + c * rel[1]])
  return abs(loc[0]) < NEST_HALF[0] + margin and abs(loc[1]) < max(NEST_HALF[1], BOARD_HALF[1]) + 0.004 + margin


def stage_states(pe) -> list[tuple[str, bool, str]]:
  """Ordered (stage, done, reason) for the cycle as it stands at the end of the episode."""
  fx = EPISODE.get("proc")
  if fx is None:
    return [(s, False, "not started") for s in STAGES]
  first = fx.results[0][1] if fx.results else None
  passed = first == "pass"
  out = []
  out.append(("dc_insert", fx.dc_ever is not None, "" if fx.dc_ever is not None else "insert"))
  out.append(("hdr_insert", fx.hdr_ever is not None, "" if fx.hdr_ever is not None else "insert"))
  out.append(("test", passed, "" if passed else ("test failed" if first == "fail" else "not run")))
  dc_out = passed and fx.dc_out_t is not None and fx.dc_out_t > fx.results[0][0]
  hdr_out = passed and fx.hdr_out_t is not None and fx.hdr_out_t > fx.results[0][0]
  out.append(("dc_unplug", dc_out, "" if dc_out else ("mechanism" if passed else "test")))
  out.append(("hdr_unplug", hdr_out, "" if hdr_out else ("mechanism" if passed else "test")))
  park_ok, why = False, "unplug"
  if dc_out and hdr_out:
    ok = []
    for b in ("dc_plug", "hdr_plug"):
      ok.append(pe[b][2] < 0.03 and not _in_nest(pe[b], pe["nest"]))
    park_ok = all(ok) and not fx.held_at_end
    why = "" if park_ok else ("still held" if fx.held_at_end else "not on the bench")
  out.append(("park", park_ok, why))
  return out


def success(pe, p0) -> bool:
  return all(done for _, done, _ in stage_states(pe))


def progress(pe, p0) -> float:
  st = stage_states(pe)
  return sum(done for _, done, _ in st) / len(st)


def audit(watch, f, poses, body_names, settle_start, dt):
  """Fixture limits as violations; per-stage results and loads as metrics."""
  fx = EPISODE["proc"]
  idx = {n: i for i, n in enumerate(body_names)}
  pe = {n: poses[-1][i] for n, i in idx.items()}
  v = list(fx.hits)
  st = stage_states(pe)
  metrics = {"stages": [{"name": n, "done": bool(dn), "reason": r} for n, dn, r in st],
             "progress": round(sum(dn for _, dn, _ in st) / len(st), 4),
             "results": fx.results, "max_lift_mm": round(1000 * fx.max_lift, 3),
             "peaks_n": {k: round(float(x), 2) for k, x in fx.peak.items()},
             "violation_t": dict(fx.hits), "events": fx.events[-40:],
             "band": EPISODE.get("band"), "clearance_mm": round(1000 * EPISODE.get("clearance", 0.0), 3),
             "cable_k": round(EPISODE.get("cable_k", 0.0), 1), "revision": EPISODE.get("revision")}
  done_t = fx.done_t
  first_pass = fx.results[0][0] if fx.results and fx.results[0][1] == "pass" else None
  metrics["stage_t"] = {"dc_insert": fx.dc_ever, "hdr_insert": fx.hdr_ever, "test": first_pass,
                        "dc_unplug": fx.dc_out_t, "hdr_unplug": fx.hdr_out_t, "park": done_t}
  if all(dn for _, dn, _ in st):
    metrics["cycle_s"] = round(done_t, 2) if done_t is not None else None
    if done_t is not None and done_t > CYCLE_S:
      v.append("cycle_late")
  metrics["cycle_budget_s"] = CYCLE_S
  metrics["fault_setup_s"] = FAULT_SETUP_S
  return v, metrics


CYCLE_S = 100.0
FAULT_SETUP_S = 30.0       # set-up allowance before stages fall due on a fault cycle (scoring.fault_cycle_score)
FAULT_ONSET_MIN_S = 52.0   # no fault starts earlier: past FAULT_SETUP_S + CYCLE_S / 6, so a stage is always due

TASK = G.Task(
    task_id="ft2_fixture_loading",
    scene_xml=SCENE,
    target_body="dc_plug",
    support_body="holder",
    bystander_bodies=(),
    success=success,
    progress=progress,
    robot_pattern=r"^robot/",
    pad_pattern=r"^robot/(gripper|moving_jaw_so101_v1)$",
    gripper_actuators=("robot/gripper",),
    observed_bodies=(),
    control_dt_s=0.02,
    episode_s=120.0,
    perception_hz=5.0, camera_trigger=True,
    perception_noise_m=(0.0, 0.0),
    home_qpos=HOME,
    safety=G.SafetyLimits(max_grasp_force_n=SQUEEZE_MAX_N, drop_z_tol_m=None),
    setup=setup,
    cameras=(("overhead", 480, 360, False), ("robot/wrist_cam", 240, 180, False)),
    audit=audit,
    audit_quality=("cycle_late",),
    process=make_process,
    # T4 faults are timed by the work: "arm_motion" starts 52-82 s after the arm first moves, "grasp" after 0.2-9 s
    # of holding a plug counted from 52 s on, so waiting does not bring a fault on. No fault starts before
    # FAULT_ONSET_MIN_S; the abort must come within 20 s of the onset. Fault cycles are scored against the cycle
    # pace (scoring.fault_cycle_score).
    fault_triggers=("arm_motion", "grasp"),
    fault_delay_s={"arm_motion": (52.0, 82.0), "grasp": (0.2, 9.0)},
    fault_min_onset_s=FAULT_ONSET_MIN_S,
    fault_abort_s=20.0,
)


def make_task(scene_xml: str | None = None) -> G.Task:
  """The task, optionally pointed at another copy of the scene."""
  import dataclasses
  return TASK if scene_xml is None else dataclasses.replace(TASK, scene_xml=scene_xml)