Skip to content

The first exam for code agents in the physical world: frozen robot tasks from many benchmark suites, each answered with a program and verified in a separate sandbox. Runs on Harbor.

LIBERO-MAX: image 0.1.1 pins OpenBLAS's Zen kernels so frozen instances rebuild on Intel Xeon 8488C (+1 more) (#107, #106)

Kangrui Wanga97b5c131a3d
diff --git a/docs/benchmarks/libero-max.md b/docs/benchmarks/libero-max.md
index d4d2593741..8a353c7820 100644
--- a/docs/benchmarks/libero-max.md
+++ b/docs/benchmarks/libero-max.md
@@ -9,7 +9,7 @@ tasks, each with one online event, in both modes: 64 cases, 128 tasks.
| upstream | LIBERO-MAX @ `a1e3cef` (benchmark 3.0.0; event runtime and case parameters); LIBERO-PRO @ `2b910b5` (MIT; LIBERO package and assets), task data `zhouxueyang/LIBERO-Pro` @ `c86fc3b` (CC-BY-4.0); robosuite 1.4.0, MuJoCo 3.2.6 |
| tasks | `tasks/libero-max-<suite>-<task>-<event>-iNN-privileged` and `...-standard` |
| metadata | `simulator = "robosuite"`, `robot = "franka-panda"`, `family = "libero-max/<suite>/<event>"`, `oracle = "full"` |
-| image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` (`images/libero-max/`), 3.5 GB, CPU only |
+| image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` (`images/libero-max/`; `sha256:0e5b5e15aaeb761e4b66772a351f4195392fa638572d47bec5d924305c89aa99`), 3.5 GB, CPU only; x86-64 with AVX-512 (see Host CPUs) |
| standard client | the shared client base and pins of `scripts/eai_standard/`; `rcb_client.py`, `rcb1.py` and the standard `grade.py` are byte copies of main's (HumanoidBench / VLABench); `rcb_service.py` is too, plus one hook (3 lines): `verify()` may return `extra`, merged into the verdict, which LIBERO-MAX uses to record `event_fired` / `event_step` (live) and `replay_event_fired` / `replay_event_step` in `final.json` (evidence only, never part of the success rule; a candidate to upstream to the shared service) |
| generator | `scripts/libero-max/` (`select_cases.py` → `cases.json`, `freeze.sh` → `frozen/`, `generate.py` → `tasks/`, `generate.py --check`) |
@@ -36,6 +36,26 @@ tasks, each with one online event, in both modes: 64 cases, 128 tasks.
camera_view_angle variant) did not rebuild bit-exactly a second time in the same process. `lmx_tool` therefore
refuses a second Session in one process (loudly, with the reason), and every verification replay and replay video
runs in a fresh process (privileged grader, standard service).
+- **Host CPUs.** The start state is bit-exact only with the numeric kernels it was frozen with, because robosuite's OSC
+ controller and LIBERO's code run on numpy and scipy. Two parts of the stack choose kernels by CPU at run time:
+ - **OpenBLAS.** numpy 1.22.4 and scipy 1.10.1 bundle OpenBLAS 0.3.18, which picks its kernels per CPU: Zen on the
+ reference AMD Ryzen 9 7950X, but its generic Prescott (SSE3) kernels on the AWS hosts' Intel Xeon Platinum 8488C
+ (Sapphire Rapids), a CPU it does not know. With image 0.1.0 none of the 64 instances rebuilt there (the Session
+ refused with a hash mismatch), and 3 references replayed to a failure. Image 0.1.1 sets `OPENBLAS_CORETYPE=Zen`
+ (AVX2 + FMA kernels; a build-time check asserts both libraries use them). Forcing Prescott on the 7950X reproduces the
+ mismatch, and forcing Zen on the 8488C removes it.
+ - **numpy's own SIMD loops.** numpy dispatches its math loops at run time, and the frozen hashes use its AVX-512
+ loops. Both reference CPUs dispatch the same targets (up to `AVX512_ICL`). With those loops switched off
+ (`NPY_DISABLE_CPU_FEATURES`, standing in for an AVX2-only CPU), 3 of 6 sampled instances differ. A real AVX2-only
+ CPU, an AWS AMD EPYC 7R13 (Zen 3, the rcb-gpu hosts), rebuilt only 10 of the first 24 instances checked with 0.1.1.
+ So run LIBERO-MAX on hosts that dispatch like the two reference CPUs (`AVX512_ICL`: Intel Ice Lake or newer Xeon,
+ AMD Zen 4 or newer), and check any other host type with `rebuild_check.sh`.
+ - **Exact or nothing.** There is no tolerance. On a host whose kernels differ, every Session refuses, loudly, and the
+ error names the kernels in use (`lmx_tool.numerics()`).
+ - Why no tolerance: a state off by rounding grows over a contact-rich episode. With 0.1.0 on the 8488C, 3 of the 64
+ reference trajectories failed even though their events fired at the recorded steps.
+ - Before using a new host type, run `bash scripts/libero-max/rebuild_check.sh [parallel]`: every instance's start
+ hash, plus its reference replayed to the recorded final hash, event step and success.
- **Event.** LIBERO-MAX's frozen change and trigger: the first control step at which the gripper is within the case's
distance (0.18 m) of the trigger object (LIBERO-MAX's `distance_to_entity`), the change is applied once by
LIBERO-MAX's backend (objects or fixtures moved, objects parked off-scene at reset brought in, camera pose and field
@@ -80,6 +100,7 @@ bash scripts/libero-max/freeze.sh candidates.json frozen-candidates 8 # ~2
python3 scripts/libero-max/select_cases.py pick candidates.json frozen-candidates scripts/libero-max/cases.json
bash scripts/libero-max/freeze.sh # the chosen cases -> scripts/libero-max/frozen/
python3 scripts/libero-max/generate.py && python3 scripts/libero-max/generate.py --check
+bash scripts/libero-max/rebuild_check.sh 8 # per host type: 64/64 rebuild bit-exactly
cd tasks && harbor add --scan . && cd .. && bash ci_checks/run_all.sh
```
@@ -93,6 +114,9 @@ cd tasks && harbor add --scan . && cd .. && bash ci_checks/run_all.sh
| `harbor run -a nop` | 4/4 privileged and 4/4 standard reward 0 |
| scripted cheat attempts (patched tooling and success check, forged reward files, `sitecustomize.py`, tampered instance copy; hidden endpoints, wrong action type and `dt`, NaN rows, forged `final.json`), on the first 48-case revision (graders and service unchanged since; the tool only gained `state()["articulations"]`) | privileged 0, standard 0; hidden endpoints 404, malformed submits 400 |
| `generate.py --check`, `task_conventions.py --check`, `ci_checks/run_all.sh` | clean; no LIBERO-MAX warnings |
+| `rebuild_check.sh` (start hash; reference replayed to the recorded final hash, event step and success), 64 instances | 0.1.0 on Intel Xeon 8488C (AWS rcb-cpu): 0/64, OpenBLAS Prescott kernels, 3 references fail; 0.1.1 on the 8488C: 64/64; 0.1.1 on AMD 7950X: 64/64 |
+| `rebuild_check.sh`, 0.1.1, AWS AMD EPYC 7R13 (Zen 3, no AVX-512) | 10 of the first 24 instances rebuild: numpy's AVX-512 loops are missing (OpenBLAS runs Zen); not a supported host |
+| kernel probes on the 7950X, 6 instances (one per 11 in sorted order) | OpenBLAS Prescott forced: 0/6; Haswell forced: 6/6; Zen with numpy's AVX-512 loops off: 3/6 |
Measured on the reference machine (AMD Ryzen 9 7950X): about 20 ms of physics per control step, about 70 ms per
256×256 camera image (OSMesa); a privileged oracle trial takes 2–3 min, most of it the verifier's two fresh replays.
diff --git a/docs/benchmarks/roboolympics.md b/docs/benchmarks/roboolympics.md
new file mode 100644
index 0000000000..49634c64c5
--- /dev/null
+++ b/docs/benchmarks/roboolympics.md
@@ -0,0 +1,101 @@
+# RoboOlympics (standard-realtime)
+
+Three real-time sports from [RoboOlympics](https://github.com/CHIGUI0/roboolympics) (by CHIGUI0; MIT): one robot
+against the sport's scripted opponent, seen only through cameras. The world runs on its own clock at 1/S of real speed
+while the agent thinks, so the agent plays with a program of its own and fixes it during the match. Standard-realtime
+mode only, on `eai-standard/2.3` (PROTOCOL §4b), with the per-benchmark exceptions below.
+
+| | |
+|---|---|
+| upstream | RoboOlympics, branch `upstream-export` at `596d551a` (core 0.2.13; the repository is private): the sports' simulators, referees, scripted opponents, action layers and reference players, copied unchanged into `scripts/roboolympics/shared/` (one change: `renderers/presentation/assets.py` reads the players' meshes from `RO_LOD_DIR`) |
+| simulator | MuJoCo 3.3.7 on CPU, OSMesa rendering; bit-exact replay |
+| tasks | 3: `tasks/roboolympics-<sport>-<format>-i00-standard-realtime` (no privileged or standard twin) |
+| protocol | `eai-standard/2.3`: HumanoidBench's 2.3 layer (`rcb_realtime.py`, `rcb_service.py`, `rcb1.py`, `rcb_client.py`) unchanged, plus the RoboOlympics adapter `scripts/roboolympics/shared/sim/rcb_olympics.py` |
+| image | `ghcr.io/mll-lab-nu/eai-olympiad:0.2.0` (`images/olympiad/`; public): the simulator stack and the players' visual meshes |
+| generator | `scripts/roboolympics/gen_tasks.py render` / `check` (CI: `ci_checks/check-generated-tasks.sh`) from `tasks.toml`, `sports.toml`, `templates/`, `shared/`, `oracle/` |
+| oracle | full: the sport's RoboOlympics reference player (camera images, the proprio columns and `/spec` only) through the agent's own client (`scripts/roboolympics/oracle/oracle_play.py`) |
+| agent budget | 7200 s (uniform; a match plus its breaks takes 5-60 min of wall time at S = 10) |
+
+## Tasks
+| task | sport, rules | robot, commands | instance |
+|---|---|---|---|
+| `roboolympics-tabletennis-match-i00-standard-realtime` | table tennis, ITTF Laws (deviations in the instruction): one game to 5 points; the opponent serves recorded real serves (DeepMind), you receive | Franka Panda with a paddle; `stroke` (the blade's state at contact; the service plans the swing), `rest` | seed 101, opponent level 1 of 4 |
+| `roboolympics-badminton-match-i00-standard-realtime` | singles badminton, BWF Laws: first to 5 points, rally scoring, the players serve | Franka Panda with a racket on an x-y sliding base; `stroke` (the racket head's state at contact, planned during a 4-step lead), `toss`, `rest` | seed 101, opponent level 1 of 2 |
+| `roboolympics-airhockey-match-i00-standard-realtime` | air hockey, USAA rules: one game to 7 goals, 0.35 m goal mouth, a 120 s play cap | KUKA iiwa 14 with a mallet; `mallet` (the mallet's target in your half, a row per control step; Cartesian path and torque control in the sim), `stop` | seed 101, opponent level 1 of 4 |
+
+Every task also has `ready` (end a break early). The agent sees two cameras (table tennis, badminton: 480 x 360; air
+hockey: one 320 x 240) and, as proprio columns, its own robot and the referee's information (score, the ball's clock,
+what it heard, the serve); never the ball's or the opponent's state, nor the seed.
+
+## How RoboOlympics maps onto eai-standard/2.3
+- **Clock.** One control step of the service is one 10 ms control step of the match (`Match.step()`). The match starts
+ paused; its clock starts at the agent's first `submit` or `get_obs(seconds > 0)` and then runs one step every
+ 0.01 × S s of wall time, whatever the agent does, until the match is over (`rcb_realtime.py`, unchanged).
+- **Commands.** A `/submit` row is one of the sport's own commands (its RoboOlympics action layer at the task's level).
+ It takes effect at the control step it is planned for: there the action layer parses it, plans it from that step's
+ state and lowers it to a low-level command, which `Match.apply()` installs before the step runs (RoboOlympics'
+ realtime effect boundary). Out-of-range values are clipped (`meta.clipped`); a command the rules refuse at its step
+ (a toss when it is not the agent's serve) changes nothing and is counted (`commands_refused`).
+- **Breaks between points.** RoboOlympics froze the world after every unit until the agent sent a review. Here the
+ clock never stops: after every unit (a point, a rally) the match stands still for **12 s of game time (120 s of wall
+ time at S = 10)** while the clock runs on (control steps, wall time, the agent's plan), nothing moves and nothing
+ scores; play resumes by itself when the break is over, or at the step of the agent's `ready` row (its review goes in
+ `submit`'s `note`, recorded in `calls.jsonl`). A break is part of the game's logic, like a break between points in a
+ real match, not a protocol feature: it needs no protocol exception. Commands planned inside a break are dropped. The
+ play-time rules (air hockey's 120 s cap, the seven-second rule) count play only, as before.
+- **Record and grading.** A sim row is `[command id, ready]`: the id of the low-level command that took effect at that
+ step (-1: none) and the agent's `ready`. The commands are in `/data/commands.jsonl`, written before the row that names
+ them, so the journal (`trajectory_live.f64`) and that table are the whole record. Finalize replays it in a fresh
+ process (`rcb_olympics.py replay`): `success` = live success (a finished match the agent won) ∧ replay success ∧
+ deterministic (the replay ends in the live state). `match.json` is the replay's summary (score, breaks, commands);
+ `tests/grade.py` grades `final.json` only. A crash resumes the same match from the journal (bit-exact), paused;
+ past `RCB_MAX_RESUMES` it is an infrastructure failure (`infra_error = 1`).
+- **Timing.** The service renders the images and plans the strokes on its own thread between control steps; a long
+ plan (badminton) makes it run late and catch up (`max_lag_s`, `stalls` in `final.json`), never changes what happens
+ in the match.
+
+## Per-benchmark exceptions (owner, 2026-10-08; PROTOCOL §4b)
+| | PROTOCOL §4b | RoboOlympics | why |
+|---|---|---|---|
+| slowdown S | `RCB_SLOWDOWN` default 1 | default **10**, overridable | RoboOlympics' official slowdown of all three sports: a model call takes seconds and a rally is over in a few, so at S = 1 play would be reflexes, not reasoning. Results state S; S ≠ 1 is reported separately anyway (§4b, §5) |
+| privileged twin | `<base>-privileged` shares the instance | none | the sports measure play from camera images against an opponent; there is no trajectory deliverable to hand in. CI exempts `roboolympics-*` explicitly (`ci_checks/check-instance-copies.sh`, `scripts/task_conventions.py` `NO_TWIN`) |
+
+The reset budget is §4b's default, 0: one match is one episode. Everything else is `eai-standard/2.3` as specified.
+
+## Run
+```bash
+MODES=standard-realtime scripts/run_agent_batch.sh <batch> roboolympics-tabletennis-match-i00 \
+ roboolympics-badminton-match-i00 roboolympics-airhockey-match-i00
+```
+Docker, CPU only. Per trial the sim takes up to 6 CPUs and 8 GB (air hockey 4 CPUs), the agent container 2 CPUs and
+4 GB. Run real-time tasks where the host is not overloaded: the service's lag behind its clock is reported
+(`max_lag_s`, `stalls`). The agent reaches the sim through Harbor's egress-control namespace (`allowlist`: the model
+APIs only); with public egress `main` could not reach `localhost:8000`.
+
+## Image
+`images/olympiad/`: MuJoCo 3.3.7, numpy, imageio, PyOpenGL, Pillow, OSMesa, and since 0.2.0 the players' visual meshes
+at `/opt/roboolympics/lod` (`RO_LOD_DIR`): the 25k level of detail of MuJoCo Menagerie's `franka_emika_panda` and
+`kuka_iiwa_14` (Apache-2.0, licences next to them). `images/olympiad/prepare_assets.sh` rebuilds them from Menagerie's
+pinned commit with RoboOlympics' `lod.py` (bit-identical) and checks them against `lod.json`; every task's renderer
+checks them again (sha256 per file) before drawing. No task code and no solution is in the image.
+
+## Evidence
+Harbor 0.23.0, S = 10, CPU only, on a shared 32-core host (load 30-70), image 0.2.0, the tasks as merged (PR #106):
+
+| task | oracle | match (game time) | trial wall | `max_lag_s`, stalls | nop |
+|---|---|---|---|---|---|
+| table tennis | 1: won 5:2 | 22.4 s, 6 breaks (each ended by `ready`) | 289 s | 0.32, 0 | 0 (the match never starts) |
+| badminton | 1: won 7:5 | 229 s, 11 breaks | 2432 s | 0.45, 1 | 0 |
+| air hockey | 1: won 3:2 at the 120 s play cap | 120 s, 7 breaks | 1297 s | 0.16, 1 | 0 |
+
+Every replay was deterministic. Badminton's reference player is the weakest of the three: its matches are close
+(this loop also won 6:4 locally; an earlier version of the loop, which re-planned its stroke at every step, lost 3:5).
+
+## Attribution
+- RoboOlympics (simulators, referees, opponents, reference players): CHIGUI0 and contributors, MIT.
+- Table-tennis serves (`sport/sim/serves_pool.json`): recorded real serves from Google DeepMind's
+ competitive robot table tennis data, licensed under CC-BY-4.0 (https://creativecommons.org/licenses/by/4.0/);
+ the table, ball and contact model follow DeepMind's `competitive_robot_table_tennis` (Apache-2.0).
+- Air-hockey table and arm models: AirHockeyChallenge (MIT; `sport/scene/UPSTREAM_LICENSE` and `ORIGIN.md`).
+- Robot models: MuJoCo Menagerie's Franka Emika Panda (Apache-2.0) and KUKA LBR iiwa 14 (BSD-3-Clause, from Drake's
+ iiwa14 description); the licences ship with the meshes in the image and in `renderers/presentation/`.
diff --git a/images/libero-max/Dockerfile b/images/libero-max/Dockerfile
index a03d561deb..d45b733d54 100644
--- a/images/libero-max/Dockerfile
+++ b/images/libero-max/Dockerfile
@@ -7,8 +7,13 @@
# manifests, results and figures, every .git, and the Hugging Face client used to fetch the task data (last layers).
# Build from the repository root (the COPY names images/libero-max/...): see docs/benchmarks/libero-max.md.
FROM docker.io/library/python:3.10.18-slim-bookworm@sha256:445b9efb2c047a7ccdb30d293fd6b1aa0f62a55062dc2b69051df91e10848749
+# OPENBLAS_CORETYPE=Zen (0.1.1): the frozen start-state hashes depend on OpenBLAS's kernels (robosuite's OSC controller
+# and LIBERO run on numpy/scipy). The OpenBLAS 0.3.18 that numpy 1.22.4 and scipy 1.10.1 bundle picks them per CPU
+# (Zen on the reference AMD 7950X, its generic Prescott kernels on an Intel Xeon 8488C, which it does not know), so
+# the same instance rebuilt differently there. Pinned to the kernels the instances were frozen with (AVX2 + FMA).
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 PIP_DISABLE_PIP_VERSION_CHECK=1 \
- MUJOCO_GL=osmesa PYOPENGL_PLATFORM=osmesa OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1
+ MUJOCO_GL=osmesa PYOPENGL_PLATFORM=osmesa OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1 \
+ OPENBLAS_CORETYPE=Zen
RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends libosmesa6 libgl1 libglib2.0-0 \
libmagickwand-6.q16-6 libexpat1 libfontconfig1 git && rm -rf /var/lib/apt/lists/*
COPY images/libero-max/requirements.txt /tmp/requirements.txt
@@ -38,4 +43,10 @@ RUN test -z "$(find /opt -name '*.hdf5' -o -name '.git' -o -name 'download_utils
&& test ! -e /opt/libero-max/scripts && test ! -e /opt/libero-max/benchmark \
&& python -c "import importlib.util as u; assert u.find_spec('huggingface_hub') is None" \
&& python -c "import mujoco, robosuite, torch; from libero.libero import benchmark; from libero_max.cosmos_integration import CosmosInterventionEnv; print('ok', mujoco.__version__, robosuite.__version__)"
+# Both bundled OpenBLAS builds run their Zen kernels (OPENBLAS_CORETYPE above), whatever CPU builds the image.
+RUN python -c 'import ctypes, numpy, scipy.linalg; scipy.linalg.inv(numpy.eye(2)); \
+ libs = {x.split()[-1] for x in open("/proc/self/maps") if "libopenblas" in x}; \
+ fns = [getattr(ctypes.CDLL(p), "openblas_get_corename64_" if "openblas64" in p else "openblas_get_corename") for p in libs]; \
+ [setattr(f, "restype", ctypes.c_char_p) for f in fns]; cores = sorted(f().decode() for f in fns); \
+ print("openblas", cores); assert len(cores) == 2 and set(cores) == {"Zen"}, cores'
WORKDIR /app
diff --git a/images/libero-max/VERSION b/images/libero-max/VERSION
index 6e8bf73aa5..17e51c385e 100644
--- a/images/libero-max/VERSION
+++ b/images/libero-max/VERSION
@@ -1 +1 @@
-0.1.0
+0.1.1
diff --git a/images/olympiad/.build-context-self b/images/olympiad/.build-context-self
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/images/olympiad/.gitignore b/images/olympiad/.gitignore
new file mode 100644
index 0000000000..a441ead0dc
--- /dev/null
+++ b/images/olympiad/.gitignore
@@ -0,0 +1 @@
+ro_lod/
diff --git a/images/olympiad/Dockerfile b/images/olympiad/Dockerfile
new file mode 100644
index 0000000000..ffa55071ba
--- /dev/null
+++ b/images/olympiad/Dockerfile
@@ -0,0 +1,17 @@
+# eai-olympiad: the RoboOlympics sports' simulator stack: MuJoCo 3.3.7 on CPU (bit-exact replay) with OSMesa rendering;
+# no GPU. One image for every RoboOlympics task's `sim` service; each task mounts its own code at /srv
+# (docker-compose: ./sim:/srv:ro). The agent containers and verifiers use the standard client image instead.
+# Since 0.2.0 it also holds the players' visual meshes (PROTOCOL §2.1: a base image holds the simulator and its assets):
+# the 25k level of detail of MuJoCo Menagerie's Franka Panda and KUKA iiwa 14 (Apache-2.0, licences next to them) at
+# /opt/roboolympics/lod (RO_LOD_DIR), which the tasks' renderers/presentation verifies against its lod.json (sha256 per
+# file). Build: images/olympiad/prepare_assets.sh (writes ro_lod/ here), then scripts/build_images.sh.
+FROM docker.io/library/python:3.12.11-slim-bookworm@sha256:519591d6871b7bc437060736b9f7456b8731f1499a57e22e6c285135ae657bf7
+ENV DEBIAN_FRONTEND=noninteractive PIP_NO_CACHE_DIR=1 PYTHONDONTWRITEBYTECODE=1 MUJOCO_GL=osmesa PYOPENGL_PLATFORM=osmesa \
+ OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1 NUMEXPR_NUM_THREADS=1 RO_LOD_DIR=/opt/roboolympics/lod
+COPY requirements.txt /opt/eai-olympiad/requirements.txt
+RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends libosmesa6 libgl1 \
+ && pip install -r /opt/eai-olympiad/requirements.txt && pip check \
+ && rm -rf /var/lib/apt/lists/*
+RUN python -c "import mujoco, numpy, imageio, OpenGL, PIL; print('mujoco', mujoco.__version__)"
+COPY ro_lod /opt/roboolympics/lod
+WORKDIR /srv
diff --git a/images/olympiad/VERSION b/images/olympiad/VERSION
new file mode 100644
index 0000000000..0ea3a944b3
--- /dev/null
+++ b/images/olympiad/VERSION
@@ -0,0 +1 @@
+0.2.0
diff --git a/images/olympiad/lod.py b/images/olympiad/lod.py
new file mode 100644
index 0000000000..6a6fcac72b
--- /dev/null
+++ b/images/olympiad/lod.py
@@ -0,0 +1,118 @@
+"""Levels of detail of the presentation models (players' images, renderer rule 6): a model's visual meshes decimated
+to a triangle budget, so that a sport can draw its players' images with fine meshes on the CPU at a small cost and
+bundle them into its simulator directory (a few MB instead of 30).
+
+ python3 -m renderers.presentation.lod build MODEL LEVEL e.g. build franka_emika_panda 25k
+
+reads the model's verified upstream files from the asset cache (assets.py fetch first), decimates every visual mesh by
+the same ratio (quadric error metrics; meshes under MIN_FACES keep at least MIN_FACES triangles), writes
+renderers/presentation/lod/<LEVEL>/<model path>/... (OBJ or binary STL as upstream, vertices and faces only: MuJoCo computes the normals) plus a
+copy of the model's MJCF file, and records every file's sha256 in lod.json. The levels are committed (derived works of
+the upstream files, same licence: LICENSE.<model>); renders read them like the upstream files (assets.model_xml with
+meshes=LEVEL), verified by sha256. Building needs `pip install trimesh==5.1.1 fast-simplification==0.2.0` (a developer
+step, never run by a match); a rebuild with these versions reproduces the files.
+"""
+from __future__ import annotations
+
+import json
+import re
+import shutil
+import sys
+from pathlib import Path
+
+from . import assets
+
+MIN_FACES = 64
+TOOLS = {"trimesh": "5.1.1", "fast-simplification": "0.2.0"}
+
+
+def target_of(level: str) -> int:
+ m = re.fullmatch(r"(\d+)k", level)
+ if not m:
+ raise ValueError(f"a level is <N>k (N thousand triangles per model), not {level!r}")
+ return int(m.group(1)) * 1000
+
+
+def build(name: str, level: str, log=print) -> dict:
+ import numpy as np
+ import trimesh
+ import fast_simplification as fs
+ from . import model_parts
+ target = target_of(level)
+ xml = assets.model_xml(name) # the verified upstream files
+ src = xml.parent
+ parts = model_parts(xml)
+ _, mod = assets._find(name)
+ out_base = assets.HERE / "lod" / level
+ model_dir = out_base / Path(mod["xml"]).parent
+ if model_dir.exists():
+ shutil.rmtree(model_dir)
+ model_dir.mkdir(parents=True)
+ rel_xml = mod["xml"]
+ shutil.copyfile(xml, out_base / rel_xml)
+ meshes = {}
+ for mn, me in parts["meshes"].items():
+ t = trimesh.load(src / me["file"], force="mesh", process=False)
+ t.merge_vertices(merge_tex=True, merge_norm=True)
+ meshes[mn] = (me["file"], t)
+ total = sum(len(t.faces) for _, t in meshes.values())
+ ratio = min(1.0, target / total)
+ n_out, written = 0, {rel_xml: None}
+ for mn, (f, t) in sorted(meshes.items()):
+ nf = len(t.faces)
+ keep = max(MIN_FACES, int(round(nf * ratio)))
+ if keep < nf:
+ v, fc = fs.simplify(np.asarray(t.vertices, np.float32), np.asarray(t.faces, np.int32),
+ target_reduction=1 - keep / nf)
+ t = trimesh.Trimesh(v, fc, process=False)
+ n_out += len(t.faces)
+ rel = str(Path(rel_xml).parent / f)
+ dst = out_base / rel
+ dst.parent.mkdir(parents=True, exist_ok=True)
+ if dst.suffix.lower() == ".obj":
+ dst.write_text(_obj(t))
+ elif dst.suffix.lower() == ".stl":
+ dst.write_bytes(_stl(t))
+ else:
+ raise ValueError(f"{rel}: only OBJ and STL meshes are decimated (got {dst.suffix})")
+ written[rel] = None
+ shas = {p: assets._sha(out_base / p) for p in sorted(written)}
+ man = assets.lods() or {"name": "lod", "note": __doc__.split("\n\n")[0].replace("\n", " "), "models": {}}
+ man["tools"] = TOOLS
+ man["models"].setdefault(name, {})[level] = {
+ "source": f"menagerie@{assets._find(name)[0]['commit']}", "target_triangles": target,
+ "source_triangles": total, "triangles": n_out, "files": shas}
+ (assets.HERE / assets.LOD_MANIFEST).write_text(json.dumps(man, indent=1, sort_keys=True) + "\n")
+ size = sum((out_base / p).stat().st_size for p in shas)
+ log(f"{name} {level}: {total} -> {n_out} triangles, {len(shas)} files, {size / 1e6:.2f} MB in {model_dir}")
+ return man["models"][name][level]
+
+
+def _obj(t) -> str:
+ """Vertices and triangles only, fixed precision (the same bytes for the same mesh)."""
+ import numpy as np
+ v = np.asarray(t.vertices, float)
+ f = np.asarray(t.faces, int) + 1
+ return ("".join(f"v {a:.6f} {b:.6f} {c:.6f}\n" for a, b, c in v)
+ + "".join(f"f {a} {b} {c}\n" for a, b, c in f))
+
+
+def _stl(t) -> bytes:
+ """Binary STL (zero normals: MuJoCo computes them), the same bytes for the same mesh."""
+ import numpy as np
+ tri = np.asarray(t.vertices, np.float32)[np.asarray(t.faces, int)] # (n, 3, 3)
+ rec = np.zeros(len(tri), dtype=[("n", "<f4", 3), ("v", "<f4", (3, 3)), ("a", "<u2")])
+ rec["v"] = tri
+ return b"\0" * 80 + np.uint32(len(tri)).astype("<u4").tobytes() + rec.tobytes()
+
+
+def main(argv) -> int:
+ if len(argv) != 3 or argv[0] != "build":
+ print(__doc__)
+ return 2
+ build(argv[1], argv[2])
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/images/olympiad/prepare_assets.sh b/images/olympiad/prepare_assets.sh
new file mode 100755
index 0000000000..b74d490898
--- /dev/null
+++ b/images/olympiad/prepare_assets.sh
@@ -0,0 +1,32 @@
+#!/bin/bash
+# Assemble the players' visual meshes for the eai-olympiad image (build context images/olympiad, tree ro_lod/, not
+# committed): the "25k" level of detail of MuJoCo Menagerie's franka_emika_panda and kuka_iiwa_14 (commit f054586a,
+# Apache-2.0; renderers/presentation/menagerie.json), decimated by RoboOlympics' lod.py with its pinned tools
+# (images/olympiad/lod.py; trimesh 5.1.1, fast-simplification 0.2.0; the rebuild is bit-identical) and checked file by file against the
+# sha256 in lod.json, the same manifest every task's simulator verifies them against at run time (RO_LOD_DIR).
+# Needs Docker and network access to GitHub raw and PyPI. Then: scripts/build_images.sh (or docker build here).
+set -euo pipefail
+HERE=$(cd "$(dirname "$0")" && pwd); ROOT=$(cd "$HERE/../.." && pwd); OUT=$HERE/ro_lod; TMP=$(mktemp -d)
+cp -r "$ROOT/scripts/roboolympics/shared/sim/renderers" "$TMP/renderers"
+cp "$HERE/lod.py" "$TMP/renderers/presentation/lod.py" # RoboOlympics renderers/presentation/lod.py, unchanged
+cat > "$TMP/build.sh" <<'SH'
+set -e
+pip install -q --root-user-action=ignore numpy==2.2.6 trimesh==5.1.1 fast-simplification==0.2.0 mujoco==3.3.7
+python -m renderers.presentation.assets fetch franka_emika_panda kuka_iiwa_14
+python -m renderers.presentation.lod build franka_emika_panda 25k
+python -m renderers.presentation.lod build kuka_iiwa_14 25k
+python - <<'PY'
+import sys
+from renderers.presentation import assets
+bad = [m for m in ("franka_emika_panda", "kuka_iiwa_14") if assets.missing(m, "25k", assets.HERE / "lod" / "25k")]
+sys.exit(f"not the files lod.json pins: {bad}" if bad else 0)
+PY
+SH
+docker run --rm -v "$TMP":/w -w /w -e RO_ASSET_CACHE=/w/cache -e HOST_ID="$(id -u):$(id -g)" \
+ docker.io/library/python:3.12.11-slim-bookworm@sha256:519591d6871b7bc437060736b9f7456b8731f1499a57e22e6c285135ae657bf7 \
+ sh -c 'sh /w/build.sh; rc=$?; chown -R "$HOST_ID" /w; exit $rc'
+rm -rf "$OUT"; mkdir -p "$OUT"
+cp -r "$TMP/renderers/presentation/lod/25k" "$OUT/25k"
+cp "$ROOT/scripts/roboolympics/shared/sim/renderers/presentation/LICENSE.franka_emika_panda" \
+ "$ROOT/scripts/roboolympics/shared/sim/renderers/presentation/LICENSE.kuka_iiwa_14" "$OUT/"
+rm -rf "$TMP"; du -sh "$OUT"
diff --git a/images/olympiad/requirements.txt b/images/olympiad/requirements.txt
new file mode 100644
index 0000000000..ba178c36cc
--- /dev/null
+++ b/images/olympiad/requirements.txt
@@ -0,0 +1,7 @@
+# eai-olympiad: the sim service's Python stack (pinned). MuJoCo 3.3.7 (CPU physics, bit-exact replay), osmesa rendering.
+mujoco==3.3.7
+numpy==2.2.6
+imageio==2.37.0
+imageio-ffmpeg==0.6.0
+PyOpenGL==3.1.10
+pillow==11.3.0
diff --git a/scripts/libero-max/rebuild_check.py b/scripts/libero-max/rebuild_check.py
new file mode 100644
index 0000000000..8c860d3060
--- /dev/null
+++ b/scripts/libero-max/rebuild_check.py
@@ -0,0 +1,37 @@
+"""Rebuild one frozen LIBERO-MAX case on this host and compare it with what freeze.sh recorded (runs in the
+eai-libero-max image, one process per case, see rebuild_check.sh).
+
+ python rebuild_check.py <frozen/<case_id> dir>
+
+Prints one JSON line: whether the start state rebuilt bit-exactly (`initial_ok`, the check every Session makes) and
+whether the reference trajectory (oracle.npy) replays to the recorded final state, event step and success
+(`final_ok`), plus the numeric kernels in use (lmx_tool.numerics()).
+"""
+
+import json
+import sys
+import time
+from pathlib import Path
+
+import numpy as np
+
+sys.path.insert(0, str(Path(__file__).resolve().parent / "shared"))
+import lmx_tool # noqa: E402
+
+d = Path(sys.argv[1])
+t0 = time.time()
+inst = lmx_tool.load_instance(d / "instance.json")
+live = json.loads((d / "report.json").read_text())["live"]
+s = lmx_tool.Session(inst, check=False)
+r = s.replay(np.load(d / "oracle.npy"))
+out = {
+ "case_id": d.name,
+ "initial_ok": s.initial_state_sha == inst["initial_state_sha"],
+ "final_ok": r["state_sha"] == live["state_sha"] and r["event_step"] == live["event_step"] and r["success"],
+ "success": r["success"],
+ "event_step": r["event_step"],
+ "initial_state_sha": s.initial_state_sha[:12],
+ "numerics": lmx_tool.numerics(),
+ "wall_s": round(time.time() - t0, 1),
+}
+print(json.dumps(out))
diff --git a/scripts/libero-max/rebuild_check.sh b/scripts/libero-max/rebuild_check.sh
new file mode 100755
index 0000000000..5b61f666c2
--- /dev/null
+++ b/scripts/libero-max/rebuild_check.sh
@@ -0,0 +1,24 @@
+#!/usr/bin/env bash
+# Check that this host rebuilds every frozen LIBERO-MAX instance bit-exactly and replays every reference to its recorded
+# final state (run it once per new host type: the frozen hashes depend on the CPU's numeric kernels, see
+# docs/benchmarks/libero-max.md). One fresh container per case, in the eai-libero-max image, without network.
+# bash scripts/libero-max/rebuild_check.sh [parallel] [out.jsonl] # exit 1 unless every case matches
+set -euo pipefail
+here="$(cd "$(dirname "$0")" && pwd)"
+root="$(cd "$here/../.." && pwd)"
+jobs="${1:-4}"
+out="$(realpath -m "${2:-rebuild_check.jsonl}")"
+image="ghcr.io/mll-lab-nu/eai-libero-max:$(cat "$root/images/libero-max/VERSION")"
+ls "$here/frozen" |
+ xargs -P "$jobs" -I{} docker run --rm --network none -u "$(id -u):$(id -g)" --tmpfs /tmp:exec,mode=1777 -e HOME=/tmp \
+ -v "$here:/work:ro" -w /work -e PYTHONPATH=/work/shared:/opt/libero-max/overlay:/opt/libero-max/src \
+ "$image" sh -c 'python rebuild_check.py frozen/{} 2>/dev/null | grep "^{" || echo "{\"case_id\": \"{}\", \"error\": true}"' >"$out"
+python3 - "$out" <<'PY'
+import collections, json, sys
+rs = [json.loads(l) for l in open(sys.argv[1])]
+bad = [r["case_id"] for r in rs if not (r.get("initial_ok") and r.get("final_ok"))]
+kern = collections.Counter(json.dumps(r.get("numerics"), sort_keys=True) for r in rs)
+print(f"{len(rs) - len(bad)}/{len(rs)} cases rebuild bit-exactly and replay their reference; numerics: {dict(kern)}")
+print("\n".join(f" differs: {c}" for c in bad))
+sys.exit(1 if bad or not rs else 0)
+PY
diff --git a/scripts/libero-max/shared/lmx_tool.py b/scripts/libero-max/shared/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/scripts/libero-max/shared/lmx_tool.py
+++ b/scripts/libero-max/shared/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/scripts/libero-max/templates/README.md b/scripts/libero-max/templates/README.md
index 0e4632c2e4..e3dfea7815 100644
--- a/scripts/libero-max/templates/README.md
+++ b/scripts/libero-max/templates/README.md
@@ -37,3 +37,11 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `{{image}}`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/scripts/libero-max/templates/standard/README.md b/scripts/libero-max/templates/standard/README.md
index c41650f53f..a7968bb11d 100644
--- a/scripts/libero-max/templates/standard/README.md
+++ b/scripts/libero-max/templates/standard/README.md
@@ -28,3 +28,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = {{pos_scale}} m, {{rot_scale}} rad per control step) and gripper |
| Episode cap | {{std_cap}} control steps ({{robot_seconds}} s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/scripts/roboolympics/gen_tasks.py b/scripts/roboolympics/gen_tasks.py
new file mode 100644
index 0000000000..95cd923a1b
--- /dev/null
+++ b/scripts/roboolympics/gen_tasks.py
@@ -0,0 +1,251 @@
+#!/usr/bin/env python3
+"""RoboOlympics task generator (docs/benchmarks/roboolympics.md): renders tasks/roboolympics-*-standard-realtime from
+tasks.toml, sports.toml, templates/ and shared/.
+
+ python3 scripts/roboolympics/gen_tasks.py render [NAME ...] write the task directories
+ python3 scripts/roboolympics/gen_tasks.py check exit 1 if tasks/ differs from a fresh render (CI:
+ ci_checks/check-generated-tasks.sh)
+
+A task directory is:
+ environment/sim/ the sidecar (mounted at /srv): the eai-standard/2.3 layer, copied unchanged from HumanoidBench
+ (scripts/humanoidbench/shared/realtime/rcb_realtime.py, shared/standard/rcb_service.py, rcb1.py),
+ the RoboOlympics adapter and its entry point (shared/sim/rcb_olympics.py, server.py), the
+ RoboOlympics core and renderers it needs (shared/sim/core, shared/sim/renderers) and the sport
+ (shared/sports/<sport>/ as sport/, without its built-in players and its own grader); the players'
+ visual meshes are in the eai-olympiad image (RO_LOD_DIR), checked against lod.json
+ environment/ the agent's image: the client (scripts/humanoidbench/shared/realtime/rcb_client.py, rcb1.py) and
+ the client pins (scripts/eai_standard/client-requirements.txt)
+ tests/ the verifier (shared/tests/grade.py)
+ solution/ the oracle: oracle/oracle_play.py and the sport's builtin_players.py
+Standard library only (CI runs `check` without the simulator); every file is copied or filled from a template, then
+scripts/task_conventions.py normalizes the task.
+"""
+from __future__ import annotations
+
+import ast
+import filecmp
+import json
+import re
+import shutil
+import sys
+import tempfile
+import textwrap
+import tomllib
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+ROOT = HERE.parent.parent
+TASKS_DIR = ROOT / "tasks"
+SHARED = HERE / "shared"
+TEMPLATES = HERE / "templates"
+HB = ROOT / "scripts" / "humanoidbench" / "shared"
+CLIENT = ROOT / "scripts" / "eai_standard"
+CLIENT_ENV = dict(l.split("=", 1) for l in (CLIENT / "client.env").read_text().splitlines() if "=" in l and not l.startswith("#"))
+CLIENT_IMAGE = CLIENT_ENV["CLIENT_IMAGE"].strip()
+CLIENT_REQUIREMENTS = CLIENT / CLIENT_ENV.get("CLIENT_REQUIREMENTS", "client-requirements.txt").strip()
+LAYER = {"rcb_realtime.py": HB / "realtime" / "rcb_realtime.py", "rcb_service.py": HB / "standard" / "rcb_service.py",
+ "rcb1.py": HB / "standard" / "rcb1.py"}
+# the sport's files that stay out of the simulator: its built-in players (the oracle's, in solution/), RoboOlympics'
+# own grader, and table tennis' duel and low level (these tasks play format match at the high level)
+NOT_IN_SIM = {"builtin_players.py", "grade.py", "duel.py", "workers.py", "ipc.py", "robot_model.py", "seat",
+ "tt_duel.xml"}
+# the agent reaches the model APIs only (scripts/set_agent_egress.py HOSTS; the same list as every allowlist task)
+HOSTS = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com",
+ "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com"]
+REVIEW_PR = 106 # the pull request that adds the tasks (their oracle evidence)
+
+
+def load() -> tuple[dict, list[dict], dict]:
+ cfg = tomllib.loads((HERE / "tasks.toml").read_text())
+ return cfg["defaults"], cfg["tasks"], tomllib.loads((HERE / "sports.toml").read_text())
+
+
+def adapter_facts() -> dict:
+ """From shared/sim/rcb_olympics.py, without importing it (it needs numpy): BREAK_S and, per sport profile, the
+ sport.toml [spec] entries it drops (they describe RoboOlympics' own interface) and the literal ones it adds."""
+ tree = ast.parse((SHARED / "sim" / "rcb_olympics.py").read_text())
+ out = {"profiles": {}}
+ for node in tree.body:
+ if isinstance(node, ast.Assign) and getattr(node.targets[0], "id", None) == "BREAK_S":
+ out["break_s"] = ast.literal_eval(node.value)
+ if isinstance(node, ast.ClassDef):
+ p = {}
+ for st in node.body:
+ if isinstance(st, ast.Assign) and getattr(st.targets[0], "id", None) in ("drop", "rules"):
+ try:
+ p[st.targets[0].id] = ast.literal_eval(st.value)
+ except ValueError:
+ pass
+ out["profiles"][node.name] = p
+ if isinstance(node, ast.Assign) and getattr(node.targets[0], "id", None) == "PROFILES":
+ out["names"] = {k.value: v.id for k, v in zip(node.value.keys, node.value.values)}
+ return out
+
+
+def fill(template: str, ctx: dict) -> str:
+ missing: list[str] = []
+
+ def one(m: re.Match) -> str:
+ if m.group(1) not in ctx:
+ missing.append(m.group(1))
+ return m.group(0)
+ return str(ctx[m.group(1)])
+ out = re.sub(r"\{\{(\w+)\}\}", one, template)
+ if missing:
+ raise KeyError(f"template placeholders with no value: {sorted(set(missing))}")
+ return out
+
+
+def flow(text: str) -> str:
+ """One paragraph per blank-line-separated block (the TOML texts are wrapped at ~120 columns)."""
+ return "\n\n".join(" ".join(p.split()) for p in text.strip().split("\n\n"))
+
+
+RULES_NOTE = ("The rule texts come from RoboOlympics' `sport.toml`. Where they name RoboOlympics' own interface "
+ "(`{'type': 'act', ...}`, `{'type': 'toss', ...}`, `{'type': 'none'}`, `{'type': 'target', ...}`, "
+ "`state.*`, `game spec`, `/spec`), read: your `stroke`, `toss`, `rest`, `mallet` and `stop` rows, the "
+ "proprio columns and `spec()`; where they say the world freezes for reviews, read: the break.\n")
+
+
+def rules_md(sport_toml: dict, facts: dict, profile: str) -> str:
+ """The rules from the sport's sport.toml: [spec] (without the entries about RoboOlympics' own interface, with the
+ adapter's replacements), the tiebreaks and the deviations from the rulebook."""
+ p = facts["profiles"].get(profile, {})
+ spec = {k: v for k, v in (sport_toml.get("spec") or {}).items() if k not in set(p.get("drop", ()))}
+ spec.update({k: v for k, v in p.get("rules", {}).items() if isinstance(v, str)})
+ lines = [RULES_NOTE] + [f"- `{k}`: {' '.join(str(v).split())}" for k, v in spec.items()]
+ tb = (sport_toml.get("tiebreaks") or {}).get("text")
+ if tb:
+ lines.append(f"- Winner: {' '.join(tb.split())}")
+ rb = sport_toml.get("rulebook") or {}
+ if rb.get("name"):
+ lines.append(f"- Rulebook: {rb['name']}" + (f", {rb['version']}" if rb.get("version") else ""))
+ for d in sport_toml.get("deviations") or []:
+ lines.append(f"- Deviation {d['id']} ({d['rule']}): {' '.join(d['text'].split())}")
+ return "\n".join(lines)
+
+
+def context(t: dict, defaults: dict, sports: dict, facts: dict) -> dict:
+ s = sports[t["sport"]]
+ sport_toml = tomllib.loads((SHARED / "sports" / t["sport"] / "sport.toml").read_text())
+ slowdown = int(defaults["slowdown"])
+ break_s = float(facts["break_s"])
+ actions = re.findall(r"^\| `(\w+)` \|", s["actions"], re.M)
+ return {
+ **{k: t[k] for k in ("name", "sport", "source", "family", "robot", "format", "action_level", "seed", "level",
+ "sim_cpus")},
+ "title": s["title"], "title_lower": s["title"].lower(), "unit": s["unit"],
+ "ball": {"tabletennis": "ball", "badminton": "shuttle", "airhockey": "puck"}[t["sport"]],
+ "intro": flow(s["intro"]), "intro_line": " ".join(s["intro"].split()),
+ "task_text": s["task_text"], "episode_text": s["episode_text"],
+ "actions": s["actions"].strip(), "action_list": ", ".join(f"`{a}`" for a in actions),
+ "first_action": actions[0], "proprio": flow(s["proprio"]), "cameras": flow(s["cameras"]), "tip": flow(s["tip"]),
+ "robot_text": s["robot"], "rules": rules_md(sport_toml, facts, facts["names"][t["sport"]]),
+ "refused_example": {"tabletennis": "a stroke whose contact time has already passed",
+ "badminton": "a toss when it is not your serve",
+ "airhockey": "a mallet target while the match stands still"}[t["sport"]],
+ "revision": sport_toml["sport"]["revision"], "slowdown": slowdown,
+ "wall_s_per_step": f"{0.01 * slowdown:g}", "break_s": f"{break_s:g}", "break_wall_s": f"{break_s * slowdown:g}",
+ "agent_timeout_sec": int(defaults["agent_timeout_sec"]), "image": defaults["image"],
+ "client_image": CLIENT_IMAGE, "allowed_hosts": json.dumps(HOSTS), "upstream": defaults["upstream"],
+ "review_pr": REVIEW_PR,
+ }
+
+
+def write(out: Path, rel: str, text: str) -> None:
+ p = out / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(text.rstrip("\n") + "\n")
+ if rel.endswith(".sh"):
+ p.chmod(0o755)
+
+
+def copy_tree(src: Path, dst: Path, skip=frozenset()) -> None:
+ for f in sorted(src.rglob("*")):
+ rel = f.relative_to(src)
+ if "__pycache__" in rel.parts or any(part in skip for part in rel.parts) or not f.is_file():
+ continue
+ (dst / rel).parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(f, dst / rel)
+
+
+def render(t: dict, defaults: dict, sports: dict, facts: dict, tasks_dir: Path = TASKS_DIR) -> Path:
+ sys.path.insert(0, str(ROOT / "scripts"))
+ from task_conventions import normalize
+ ctx = context(t, defaults, sports, facts)
+ out = tasks_dir / t["name"]
+ if out.exists():
+ shutil.rmtree(out)
+ tpl = lambda name: fill((TEMPLATES / name).read_text(), ctx) # noqa: E731
+ write(out, "task.toml", tpl("task.toml"))
+ write(out, "instruction.md", tpl("instruction.md"))
+ write(out, "README.md", tpl("README.md"))
+ write(out, "environment/docker-compose.yaml", tpl("docker-compose.yaml"))
+ write(out, "environment/Dockerfile", tpl("Dockerfile"))
+ write(out, "tests/Dockerfile", tpl("tests.Dockerfile"))
+ write(out, "tests/test.sh", tpl("test.sh"))
+ write(out, "solution/solve.sh", tpl("solve.sh"))
+ sim = out / "environment" / "sim"
+ copy_tree(SHARED / "sim", sim)
+ for name, src in LAYER.items():
+ shutil.copyfile(src, sim / name)
+ copy_tree(SHARED / "sports" / t["sport"], sim / "sport", skip=NOT_IN_SIM)
+ shutil.copyfile(HB / "realtime" / "rcb_client.py", out / "environment" / "rcb_client.py")
+ shutil.copyfile(HB / "standard" / "rcb1.py", out / "environment" / "rcb1.py")
+ shutil.copyfile(CLIENT_REQUIREMENTS, out / "environment" / "client-requirements.txt")
+ shutil.copyfile(SHARED / "tests" / "grade.py", out / "tests" / "grade.py")
+ shutil.copyfile(HERE / "oracle" / "oracle_play.py", out / "solution" / "oracle_play.py")
+ shutil.copyfile(SHARED / "sports" / t["sport"] / "builtin_players.py", out / "solution" / "builtin_players.py")
+ normalize(out)
+ return out
+
+
+def cmd_render(names: list[str]) -> int:
+ defaults, tasks, sports = load()
+ facts = adapter_facts()
+ for t in tasks:
+ if not names or t["name"] in names:
+ print("rendered", render(t, defaults, sports, facts).relative_to(ROOT))
+ return 0
+
+
+def _diff(c: filecmp.dircmp, prefix: str) -> list[str]:
+ out = [f"tasks/{prefix}/{x}: differs from its render" for x in c.diff_files]
+ out += [f"tasks/{prefix}/{x}: not rendered" for x in c.left_only] + [f"tasks/{prefix}/{x}: missing" for x in c.right_only]
+ for sub, sc in c.subdirs.items():
+ out += _diff(sc, f"{prefix}/{sub}")
+ return out
+
+
+def cmd_check() -> int:
+ """tasks/ must be what render writes from today's sources, with no stale roboolympics-* directory."""
+ defaults, tasks, sports = load()
+ facts = adapter_facts()
+ failed: list[str] = []
+ with tempfile.TemporaryDirectory() as tmp:
+ rendered = {render(t, defaults, sports, facts, Path(tmp)).name for t in tasks}
+ for name in sorted(rendered):
+ if not (TASKS_DIR / name).is_dir():
+ failed.append(f"tasks/{name}: missing")
+ continue
+ failed += _diff(filecmp.dircmp(TASKS_DIR / name, Path(tmp) / name, ignore=["__pycache__"]), name)
+ for f in sorted((Path(tmp) / name).rglob("*")): # filecmp ignores modes: test.sh, solve.sh
+ g = TASKS_DIR / name / f.relative_to(Path(tmp) / name)
+ if f.is_file() and g.is_file() and (f.stat().st_mode & 0o111) != (g.stat().st_mode & 0o111):
+ failed.append(f"tasks/{name}/{f.relative_to(Path(tmp) / name)}: executable bit differs")
+ failed += [f"tasks/{p.name}: no longer rendered" for p in sorted(TASKS_DIR.glob("roboolympics-*"))
+ if p.name not in rendered]
+ print("\n".join(f"FAIL {x}" for x in failed) or f"check: {len(rendered)} task dirs are what render writes")
+ return 1 if failed else 0
+
+
+def main(argv: list[str]) -> int:
+ if not argv or argv[0] not in ("render", "check"):
+ print(textwrap.dedent(__doc__).strip().splitlines()[2:4][0])
+ print("usage: gen_tasks.py render [NAME ...] | check")
+ return 2
+ return cmd_render(argv[1:]) if argv[0] == "render" else cmd_check()
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/scripts/roboolympics/oracle/oracle_play.py b/scripts/roboolympics/oracle/oracle_play.py
new file mode 100644
index 0000000000..0f36ecd9a3
--- /dev/null
+++ b/scripts/roboolympics/oracle/oracle_play.py
@@ -0,0 +1,236 @@
+"""Harbor oracle: the sport's RoboOlympics reference player (builtin_players.Reference, next to this file: camera images
+and the documented facts only) driven through the agent's own client (rcb_client.py, eai-standard/2.3).
+
+The reference players were written for RoboOlympics' realtime interface: each step they get a `view` -- the state
+(score, the ball's clock, what was heard, the robot's own body) and a tiled PNG of the newest camera frames -- and
+return an act body or nothing. This loop builds that view from /observe (a short watch: the frames and one proprio row
+per frame), turns the act into a /submit row of the task's action type, and sends `ready` (with the player's review as
+the note) once per break. Nothing here reads simulator state the agent could not read.
+
+Timing (table tennis, badminton): the players also have an in-process mode in which an act takes effect exactly at the
+observed step. 2.3's `at` makes that exact over HTTP too: the loop picks the control step its command will take effect
+at (a margin of LEAD_STEPS after the step it estimates is running now), hands the player the view as of that step (the
+step and the times relative to it shifted accordingly; images and frame steps are absolute), and submits the command
+with `at` = that step. Host load then delays the command's arrival, never its effect.
+"""
+from __future__ import annotations
+
+import base64
+import io
+import math
+import os
+import sys
+import time
+
+import numpy as np
+from PIL import Image
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import builtin_players as bp # noqa: E402
+from rcb_client import EpisodeOver, Robot # noqa: E402
+
+NAN = float("nan")
+LEAD_STEPS = 5 # control steps between "now" (estimated) and a command's planned effect: 0.5 s of wall
+ # time at S = 10 for the player's own computation and the request
+
+
+def num(x):
+ return None if x is None or (isinstance(x, float) and math.isnan(x)) else x
+
+
+def png_b64(rows: list) -> tuple[str, list]:
+ """rows of tiles (one row per camera) -> base64 PNG and the tile list."""
+ sheet = np.concatenate([np.concatenate(r, axis=1) for r in rows], axis=0)
+ buf = io.BytesIO()
+ Image.fromarray(np.ascontiguousarray(sheet[..., :3])).save(buf, format="PNG", compress_level=1)
+ return base64.b64encode(buf.getvalue()).decode(), []
+
+
+class Bridge:
+ def __init__(self):
+ self.r = Robot()
+ self.spec = self.r.spec()
+ self.sport = self.spec["sport"]
+ self.layout = self.spec["proprio_layout"]
+ self.dt = float(self.spec["control_dt"])
+ self.period = float(self.spec["timing"]["wall_s_per_control_step"])
+ self.cams = list(self.spec["cameras"])
+ rules = self.spec.get("rules") or {}
+ cams = []
+ for name in self.cams:
+ c = dict(self.spec["cameras"][name], name=name)
+ if self.sport == "airhockey":
+ c.update(width=c["hw"][1], height=c["hw"][0])
+ cams.append(c)
+ self.exact = self.sport in ("tabletennis", "badminton") # the in-process timing mode (module docstring)
+ ref = {"cameras": cams, "action_level": self.spec["match"]["action_level"],
+ "timing": {"period_s": None if self.exact else self.period}, **rules}
+ self.player = bp.Reference(ref, "A", 0)
+ self.reviewed_break = None
+ self.n_obs = 0
+ self.hist: list = [] # (match step, proprio row, {cam: image}) of recent observations
+ self.spacing = {"tabletennis": 4, "badminton": 6}.get(self.sport, 1) # 40 / 60 ms, as RoboOlympics' views
+ self.running = False
+ # how often the loop looks (control steps): badminton at RoboOlympics' own client cadence (an observation, then
+ # `wait 0.05`): a player that re-plans its stroke at every step keeps the arm from ever finishing a swing
+ self.every = {"badminton": 5}.get(self.sport, 1)
+ # badminton: a command waits `lead_steps` after its step (stroke_pending_effect_step shows it then); before
+ # that it is still in the service's plan, which the proprio does not show: the loop marks it pending itself
+ self.lead = int(((self.spec.get("rules") or {}).get("act") or {}).get("lead_steps", 0))
+ self.pending_until = -1
+
+ # ------------------------------------------------------------------ one view
+ def rows(self, res) -> list[dict]:
+ P = np.asarray(res.proprio, float).reshape(-1, len(self.layout))
+ return [dict(zip(self.layout, map(float, row))) for row in P]
+
+ def state(self, p: dict, shift: int = 0) -> dict:
+ """The player's state as of `shift` control steps after the proprio row p (relative times shifted)."""
+ p = dict(p)
+ for k in ("t_since_played",):
+ if k in p and not math.isnan(p[k]):
+ p[k] += shift * self.dt
+ for k in ("serve_opens_in_s", "serve_deadline_in_s", "stroke_contact_in_s"):
+ if k in p and not math.isnan(p[k]):
+ p[k] -= shift * self.dt
+ if "serve_opens_in_s" in p and not math.isnan(p["serve_opens_in_s"]):
+ p["serve_opens_in_s"] = max(0.0, p["serve_opens_in_s"])
+ st = {"step": int(p["match_step"]) + shift, "world": "frozen" if p["break"] > 0.5 else "running",
+ "done": p["finished"] > 0.5}
+ if self.sport == "tabletennis":
+ heard = [{"event": ev, "t": p[f"heard_{k}_t"]} for k, ev in
+ (("opp_bounce", "bounce on the opponent's half"), ("own_bounce", "bounce on your half"),
+ ("net", "net"), ("paddle", "paddle"), ("robot", "robot"), ("floor", "floor"))
+ if not math.isnan(p[f"heard_{k}_t"])]
+ st.update(point=int(p["point"]), ball="serve" if p["ball_is_serve"] > 0.5 else "opponent's return",
+ t_since_played=p["t_since_played"], ball_in_play=p["ball_in_play"] > 0.5, heard=heard,
+ ball_state="coming to you" if p["ball_coming"] > 0.5 else
+ "going to the opponent" if p["ball_going"] > 0.5 else "dead")
+ elif self.sport == "badminton":
+ phase = {0: "waiting", 1: "open", 2: "tossed", 3: "done"}.get(int(p["serve_phase"]) if not
+ math.isnan(p["serve_phase"]) else -1)
+ sv = {"phase": phase, "court": "right" if p["serve_court_right"] > 0.5 else "left",
+ "opens_in_s": num(p["serve_opens_in_s"]), "deadline_in_s": num(p["serve_deadline_in_s"])}
+ if not math.isnan(p["serve_tossed_at_step"]):
+ sv["tossed_at_step"] = int(p["serve_tossed_at_step"])
+ notes = "; ".join(n for n, k in (("head speed limited", "stroke_head_speed_limited"),
+ ("pose not delivered", "stroke_pose_not_delivered")) if p[k] > 0.5)
+ st.update(point=int(p["point"]), score={"you": int(p["score_you"]), "opponent": int(p["score_opponent"])},
+ you_serve=p["you_serve"] > 0.5, serve=sv, robot_base_xy=[p["base_x"], p["base_y"]],
+ t_since_played=num(p["t_since_played"]),
+ ball_state="coming to you" if p["ball_coming"] > 0.5 else
+ "going to the opponent" if p["ball_going"] > 0.5 else
+ "tossed: yours to hit (your serve)" if p["ball_tossed"] > 0.5 else
+ "not yet served" if p["ball_not_served"] > 0.5 else "dead")
+ if p["stroke_active"] > 0.5:
+ st["command"] = {"contact_in_s": p["stroke_contact_in_s"], "stroke": notes}
+ if not math.isnan(p["stroke_pending_effect_step"]):
+ st["pending_commands"] = [{"takes_effect_at_step": int(p["stroke_pending_effect_step"])}]
+ else:
+ st.update(rally=int(p["rally"]), t_play=p["t_play"],
+ own={"mallet_xyz": [p["mallet_x"], p["mallet_y"], p["mallet_z"]]})
+ return st
+
+ def observe(self):
+ """Air hockey: watch 0.05 s (the players' cadence) and take the last image. Table tennis, badminton: the
+ current images at once (the clock is started by a short watch first), kept in a history from which the view
+ takes four frames about SPACING control steps apart, newest last, as RoboOlympics' observation did."""
+ if self.sport == "airhockey":
+ res = self.r.get_obs(cameras=self.cams, seconds=0.05, video="none")
+ return res, self.rows(res), {c: res.last[c][None] for c in self.cams}
+ res = self.r.get_obs(cameras=self.cams, seconds=0 if self.running else 0.05, video="frames")
+ self.running = True
+ rows = self.rows(res)
+ k = int(rows[-1]["match_step"])
+ if not self.hist or self.hist[-1][0] != k:
+ self.hist.append((k, rows[-1], {c: res.frames[c][-1] for c in self.cams}))
+ self.hist = self.hist[-40:]
+ sel, last = [], None
+ for k, row, fr in reversed(self.hist):
+ if last is None or last - k >= self.spacing:
+ sel.append((k, row, fr))
+ last = k
+ if len(sel) == 4:
+ break
+ sel.reverse()
+ return res, [r for _, r, _ in sel], {c: np.stack([fr[c] for _, _, fr in sel]) for c in self.cams}
+
+ def view(self, res, rows, frames, shift: int = 0) -> tuple[dict, dict, dict]:
+ now = rows[-1]
+ st = self.state(now, shift)
+ n = min(len(rows), min(len(f) for f in frames.values()))
+ rows, frames = rows[-n:], {c: f[-n:] for c, f in frames.items()}
+ self.n_obs += 1
+ ob = {"view_steps": [int(p["match_step"]) for p in rows],
+ "view_sim_times": [round(p["match_step"] * self.dt, 4) for p in rows]}
+ if not self.exact:
+ ob.update(obs_id=self.n_obs, obs_age_wall_s=0.0, render_wall_s=0.0)
+ if self.sport == "airhockey":
+ img = frames[self.cams[0]][-1]
+ ob["image_png_b64"], _ = png_b64([[img]])
+ ob["tiles"] = [{"camera": self.cams[0], "x": 0, "y": 0, "width": img.shape[1], "height": img.shape[0]}]
+ else:
+ ob["image_png_b64"], _ = png_b64([[f for f in frames[c]] for c in self.cams])
+ return st, ob, now
+
+ # ------------------------------------------------------------------ one action
+ def send(self, body: dict, at=None) -> None:
+ t = body.get("type")
+ if t == "act":
+ row = [body["t"], *body["pos"], *body["normal"], *body["vel"]]
+ self.r.submit("stroke", [row], at=at)
+ elif t == "toss":
+ self.r.submit("toss", [[*body["pos"], float(body.get("height", 0.0))]], at=at)
+ elif t == "target":
+ self.r.submit("mallet", [[body["x"], body["y"]]], at=at)
+ elif t == "none":
+ self.r.submit("stop" if self.sport == "airhockey" else "rest", [[0.0]], at=at)
+
+ def run(self) -> dict:
+ t_last = 0.0
+ while True:
+ time.sleep(max(0.0, t_last + self.every * self.period - time.monotonic())) # one view per `every` steps
+ t_last = time.monotonic()
+ try:
+ res, rows, frames = self.observe()
+ except EpisodeOver:
+ break
+ t_reply = time.monotonic()
+ if res.meta.get("done"):
+ break
+ at = shift = None
+ if self.exact: # the step the command will take effect at, and the view as of then
+ at = math.ceil(res.meta["control_steps"] + 0.5) + LEAD_STEPS
+ at = max(at, math.ceil(res.meta["control_steps"] + (time.monotonic() - t_reply) / self.period)
+ + LEAD_STEPS)
+ shift = at - int(res.meta["control_steps"])
+ st, ob, now = self.view(res, rows, frames, shift or 0)
+ if st["world"] == "frozen":
+ key = int(now["match_step"]) # the match stands still in a break: one key per break
+ if key != self.reviewed_break:
+ self.reviewed_break = key
+ f = getattr(self.player, "review", None)
+ why, plan = f(now) if f else ("played as planned", "same plan")
+ try:
+ self.r.submit("ready", [[1.0]], note=f"WHY: {why} PLAN: {plan}"[:200])
+ except EpisodeOver:
+ break
+ continue
+ if self.sport == "badminton" and res.meta["control_steps"] <= self.pending_until:
+ st["pending_commands"] = [{"takes_effect_at_step": int(now["match_step"]) + self.pending_until
+ - int(res.meta["control_steps"]) + 1}]
+ body = self.player.act({"state": st, "observation": ob})
+ if body:
+ if at is not None:
+ self.pending_until = at + self.lead
+ try:
+ self.send(body, at)
+ except EpisodeOver:
+ break
+ return self.r.status()
+
+
+if __name__ == "__main__":
+ t0 = time.time()
+ out = Bridge().run()
+ print({"status": out, "wall_s": round(time.time() - t0, 1)})
diff --git a/scripts/roboolympics/shared/sim/core/README.md b/scripts/roboolympics/shared/sim/core/README.md
new file mode 100644
index 0000000000..6d80cefa51
--- /dev/null
+++ b/scripts/roboolympics/shared/sim/core/README.md
@@ -0,0 +1,18 @@
+# core/
+
+The match core (docs/framework_zh.md §5): it hosts every match under one set of rules and never names a sport or a
+harness. Version: `VERSION` in `__init__.py` (bump on every change; every sport's golden replay must still pass).
+
+| File | Contract / job |
+|---|---|
+| `sport.py` | ② the sport interface: `MatchConfig` (seats, sides, format, modes, renderer), `Phase`, `Refused`, `MatchBase` (the optional hooks and their defaults), `ActionLayer` / `LowLayer` / `SchemaLayer`, `check_command`; request validation (core 0.2.11): `check_body` (every request), `check_action` + `parse_action` (every act: any exception while reading an action is the player's 400, never a technical failure) |
+| `http.py`, `client.py`, `game.py` | ① the player protocol: the HTTP envelope (`/<seat>/<endpoint>`, limits), the client loop of built-in players, the generic `game` CLI |
+| `realtime.py`, `turn.py`, `service.py` | flow: `eai-standard-realtime/1.0` (slowdown, freeze and review, act pipeline, delayed effects, entities) and `eai-standard-turn/1.0` (turns, chess clocks, reviews); what both share (seats and sides, observations, team channel, retirement, final.json) |
+| `episode.py` | ③ the match record: `episode.jsonl` and the fresh-process replay (`python -m core.episode PLUGIN DIR`) |
+| `outcome.py`, `grading.py` | judgement: the no-draw chain, N-side ranking, solo scoring; the verifier (validity, reward fields, no-code audit hookup) |
+| `observe.py`, `channel.py`, `rng.py`, `spec.py` | the observation whitelist and camera tiles (through `renderers/`), the reply images of an action (`Match.reply_views`, core 0.2.8: snapshotted under the lock, drawn off it by the same camera worker, attached to the reply as `observation`), the team channel, random streams by name, sport.toml |
+| `seats.py`, `metering/` | per-seat counters, locks and chess clocks; the metering hookup (`think_clock.py`, `api_errors.py`: byte-identical copies); player modes (`PLAYER_MODE_<seat>`): `model` (metered by the seat's proxy, required for validity), `oracle` (exempt), `unmetered` (core 0.2.13: the runner meters the model itself, e.g. a plain Harbor with native agents; no proxy, no meter required) |
+| `spectator.py` | the broadcast log (`broadcast.jsonl`, the legacy writer copied as `spectator/broadcast_log.py`) and the replay video (`replay.mp4`, a fresh-process replay drawn by the spectator renderer); never read back |
+| final.json compatibility | `service.py` `COMPAT`: the sport's fields are lifted to the top level (unless a core field has the name) and `score` is set, so the Season-1 readers work; the sport fields also stay under `sport_fields` |
+| `workers.py`, `serve.py`, `launch.py` | worker processes (plan, render, camera), the service entry point, the launcher (one metering proxy per seat, none for an unmetered seat) |
+| `local.py`, `testkit.py`, `tests/` | in-process matches of built-in players, the generic test suite of every sport, the core's own tests |
diff --git a/scripts/roboolympics/shared/sim/core/__init__.py b/scripts/roboolympics/shared/sim/core/__init__.py
new file mode 100644
index 0000000000..fd44c1d84c
--- /dev/null
+++ b/scripts/roboolympics/shared/sim/core/__init__.py
@@ -0,0 +1,8 @@
+"""RoboOlympics match core (docs/framework_zh.md §5): hosts every match under one set of rules.
+
+Flow (clock, slowdown, freeze and review, seats and turns), rules (formats, modes), records (episode log, replay,
+metering) and judgement (outcome, validity). It names no sport and no harness (ci_checks/check-core-purity.sh), computes
+no physics, and changes only in its own commits with a version bump (VERSION) and every sport's golden replay passing.
+"""
+VERSION = "0.2.13"
+PROTOCOLS = {"realtime": "eai-standard-realtime/1.0", "turn": "eai-standard-turn/1.0"}
diff --git a/scripts/roboolympics/shared/sim/core/observe.py b/scripts/roboolympics/shared/sim/core/observe.py
new file mode 100644
index 0000000000..94b46fc9b3
--- /dev/null
+++ b/scripts/roboolympics/shared/sim/core/observe.py
@@ -0,0 +1,154 @@
+"""Observations (sport rule 1, docs/framework_zh.md §9): what a seat gets is the camera images, its own body and the
+referee's information, and nothing else. The sport declares the fields of Match.observe() in sport.toml
+([observation] fields); a field outside that whitelist is never delivered and is a technical error of the match.
+
+The camera images: Match.cameras(seat, query) returns camera definitions, the task's renderer (renderers/, chosen by
+the task parameter `renderer`) draws them from the sport's scene and Match.render_state(), and the core lays the
+images out as tiles of one PNG (left to right, `columns` per row), described in the reply (`tiles`).
+
+Reply images (core 0.2.8): Match.reply_views(seat, cmd, info) right after an action -> reply_job() snapshots the
+frames under the lock -> CameraWorker.draw_job() draws them off the lock (the same renderer, scene and worker as the
+observation) -> one PNG of tiles, each tile also naming its frame (`frame`, `label`) when there are several.
+
+The scene of the players' images (core 0.2.9, renderer rule 6): Sport.scene(cfg), or the presentation scene the sport
+declares for its players (sports/<sport>/presentation/presentation.toml `players`, bundled into the simulator by the
+generator; renderers/presentation.players_scene): the same kinematics, finer visual meshes. Any other presentation
+scene is refused (spectators only)."""
+from __future__ import annotations
+
+import copy
+import struct
+import zlib
+from pathlib import Path
+
+import numpy as np
+
+
+class WhitelistError(Exception):
+ pass
+
+
+def filter_fields(obs: dict, allowed: set[str] | None) -> tuple[dict, list[str]]:
+ """(the whitelisted part of obs, the names that were not allowed)."""
+ if allowed is None:
+ return obs, []
+ bad = sorted(k for k in obs if k not in allowed)
+ return {k: v for k, v in obs.items() if k in allowed}, bad
+
+
+def png(img: np.ndarray) -> bytes:
+ """A minimal RGB8 PNG encoder (no imaging library needed in the sim)."""
+ img = np.ascontiguousarray(img, dtype=np.uint8)
+ h, w = img.shape[:2]
+ raw = b"".join(b"\x00" + img[y].tobytes() for y in range(h))
+
+ def chunk(tag, data):
+ return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
+
+ return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0))
+ + chunk(b"IDAT", zlib.compress(raw, 6)) + chunk(b"IEND", b""))
+
+
+def reply_job(m, spec: dict | None, columns: int) -> dict | None:
+ """Under the lock: Match.reply_views()'s answer -> a self-contained draw job (deep copies: the match may move on
+ while the job is drawn off the lock). A frame without a state gets render_state() now."""
+ if not spec or not spec.get("frames"):
+ return None
+ order = spec.get("order", "frame")
+ if order not in ("frame", "camera"):
+ raise ValueError(f"reply_views: order must be 'frame' or 'camera', not {order!r}")
+ now = None
+ frames = []
+ for f in spec["frames"]:
+ st = f.get("state")
+ if st is None:
+ now = m.render_state() if now is None else now
+ st = now
+ cams = list(f.get("cameras") or [])
+ if not cams:
+ raise ValueError("reply_views: every frame needs at least one camera")
+ frames.append({"state": st, "cams": cams, "label": f.get("label")})
+ return copy.deepcopy({"frames": frames, "order": order, "columns": int(spec.get("columns") or columns),
+ "note": spec.get("note")})
+
+
+def compose(images: list[np.ndarray], names: list[str], columns: int = 2) -> tuple[np.ndarray, list[dict]]:
+ """Tiles left to right, `columns` per row, each at its own size; -> (sheet, [{camera, x, y, width, height}])."""
+ rows = [list(range(i, min(i + columns, len(images)))) for i in range(0, len(images), columns)]
+ widths = [sum(images[j].shape[1] for j in r) for r in rows]
+ heights = [max(images[j].shape[0] for j in r) for r in rows]
+ sheet = np.zeros((sum(heights), max(widths), 3), np.uint8)
+ tiles, y = [], 0
+ for r, hgt in zip(rows, heights):
+ x = 0
+ for j in r:
+ h, w = images[j].shape[:2]
+ sheet[y:y + h, x:x + w] = images[j][..., :3]
+ tiles.append({"camera": names[j], "x": x, "y": y, "width": w, "height": h})
+ x += w
+ y += hgt
+ return sheet, tiles
+
+
+def players_scene(sport, plugin: str, cfg):
+ """The scene of the players' images: the sport's presentation scene when it declares `players`, else
+ Sport.scene(cfg)."""
+ scene = sport.scene(cfg)
+ d = Path(plugin).resolve().parent
+ if not (d / "presentation" / "presentation.toml").is_file():
+ return scene
+ from renderers import presentation
+ return presentation.players_scene(d, scene)
+
+
+class CameraWorker:
+ """Draws a seat's camera definitions with the task's renderer (in-process or inside a render worker process)."""
+
+ def __init__(self, scene, renderer_name: str | None):
+ import renderers
+ if getattr(scene, "match", None) is not None and not getattr(scene, "players", False):
+ raise ValueError("the players' images are drawn from the match scene (Sport.scene) or the presentation "
+ "scene the sport declares for them; any other presentation scene is for spectators only "
+ "(renderer rule 6)")
+ self.name = renderer_name or renderers.DEFAULT
+ self.renderer = renderers.load(self.name)(scene)
+
+ def draw(self, state: dict, cams: list[dict], columns: int = 2) -> dict:
+ from renderers.base import CameraDef
+ defs = [CameraDef.from_dict(c) for c in cams]
+ images = self.renderer.render(state, defs)
+ sheet, tiles = compose(images, [c.name for c in defs], columns)
+ return {"png": png(sheet), "tiles": tiles, "renderer": self.name}
+
+ def draw_frames(self, job: dict) -> dict:
+ """A reply job (reply_job()): every frame's cameras drawn from that frame's state, laid out frame after
+ frame or camera after camera; a tile names its camera, and its frame (index, label) when there are several."""
+ from renderers.base import CameraDef
+ frames = job["frames"]
+ drawn = [] # per frame: [(name, image)]
+ for f in frames:
+ defs = [CameraDef.from_dict(c) for c in f["cams"]]
+ drawn.append(list(zip([c.name for c in defs], self.renderer.render(f["state"], defs))))
+ cells = [] # (frame index, camera name, image)
+ if job.get("order") == "camera":
+ for j in range(max(len(d) for d in drawn)):
+ cells += [(i, d[j][0], d[j][1]) for i, d in enumerate(drawn) if j < len(d)]
+ else:
+ cells = [(i, name, img) for i, d in enumerate(drawn) for name, img in d]
+ sheet, tiles = compose([c[2] for c in cells], [c[1] for c in cells], int(job.get("columns", 2)))
+ many = len(frames) > 1
+ for t, (i, _, _) in zip(tiles, cells):
+ if many:
+ t["frame"] = i
+ if frames[i].get("label"):
+ t["label"] = frames[i]["label"]
+ out = {"png": png(sheet), "tiles": tiles, "renderer": self.name}
+ if job.get("note"):
+ out["note"] = job["note"]
+ return out
+
+ def draw_job(self, job: dict) -> dict:
+ """Any job of the core's camera worker: a reply job (frames) or an observation (state + cameras)."""
+ if "frames" in job:
+ return self.draw_frames(job)
+ return self.draw(job["state"], job["cams"], job.get("columns", 2))
diff --git a/scripts/roboolympics/shared/sim/core/outcome.py b/scripts/roboolympics/shared/sim/core/outcome.py
new file mode 100644
index 0000000000..11916961f2
--- /dev/null
+++ b/scripts/roboolympics/shared/sim/core/outcome.py
@@ -0,0 +1,50 @@
+"""The no-draw decision chain (docs/framework_zh.md §5): a forfeit (a core decision: review or clock time, abandonment,
+or a side that never started, "no_show"; sides that retired before it rank last, the last to retire first), then the
+sport's tiebreaks in order (rulebook result -> rulebook tiebreak -> capped extra play -> last resort; the last one must
+decide). A match with more than two sides is decided by the sport's classification (Match.ranking, best first). A solo
+match (single format without an opponent: tiebreaks() == []) has no winner; its result is the score against the
+success line. A match that did not finish has no winner."""
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+from .sport import FINISHED
+
+
+@dataclass
+class Outcome:
+ winner: str | None
+ decided_by: str
+ scores: dict
+ ranking: list = field(default_factory=list)
+ solo: bool = False
+
+
+def decide(match, forfeit_seat: str | None = None, why: str | None = None, sides=("A", "B"),
+ side_of=lambda s: s, retired=()) -> Outcome:
+ scores = match.scores()
+ sides = list(sides)
+ rules = match.tiebreaks()
+ solo = len(sides) == 1 and not rules
+ if forfeit_seat is not None:
+ lost = side_of(forfeit_seat)
+ others = [s for s in sides if s != lost and s not in retired]
+ if len(others) == 1:
+ return Outcome(others[0], f"forfeit:{why}", scores, others + [lost] + list(reversed(retired)))
+ if not others and len(sides) == 1: # a single player who forfeits loses (to the line or the opponent)
+ return Outcome(None, f"forfeit:{why}", scores, [], solo)
+ if match.phase().state != FINISHED:
+ return Outcome(None, "unfinished", scores, [], solo)
+ if solo:
+ return Outcome(None, "score", scores, list(sides), True)
+ if len(sides) > 2:
+ ranking = list(match.ranking() or [])
+ if sorted(ranking) != sorted(sides):
+ raise RuntimeError("a match of more than two sides must rank every side (Match.ranking)")
+ return Outcome(ranking[0], "ranking", scores, ranking)
+ for name, rule in rules:
+ w = rule(match)
+ if w is not None:
+ rest = [s for s in sides if s != w]
+ return Outcome(w, name, scores, [w] + rest)
+ raise RuntimeError("a finished match must be decided by its last tiebreak (no draws)")
diff --git a/scripts/roboolympics/shared/sim/core/spec.py b/scripts/roboolympics/shared/sim/core/spec.py
new file mode 100644
index 0000000000..9cc5599b5c
--- /dev/null
+++ b/scripts/roboolympics/shared/sim/core/spec.py
@@ -0,0 +1,20 @@
+"""The sport's declarations (sport.toml next to its plugin.py, docs/framework_zh.md §4.2): data, read by the core
+(observation whitelist, team channel, success line, timing), the generator, the checks and the documentation."""
+from __future__ import annotations
+
+import os
+import tomllib
+from pathlib import Path
+
+
+def load(plugin_path: str | os.PathLike) -> dict:
+ p = Path(plugin_path)
+ p = p / "sport.toml" if p.is_dir() else p.with_name("sport.toml")
+ if not p.exists():
+ return {}
+ return tomllib.loads(p.read_text())
+
+
+def whitelist(decl: dict) -> set[str] | None:
+ fields = (decl.get("observation") or {}).get("fields")
+ return set(fields) if fields is not None else None
diff --git a/scripts/roboolympics/shared/sim/core/sport.py b/scripts/roboolympics/shared/sim/core/sport.py
new file mode 100644
index 0000000000..a60647ec26
--- /dev/null
+++ b/scripts/roboolympics/shared/sim/core/sport.py
@@ -0,0 +1,455 @@
+"""Contract ② (docs/framework_zh.md §4.2): the one interface between the core and a sport (sports/<sport>/).
+
+A sport's plugin module exports SPORT. The core calls only the functions below and never names a sport; a sport never
+imports another sport. A sport answers four questions, one group of functions each (10 required):
+
+ world Sport.build(cfg) -> Match Match.step() -> events Match.state_digest() -> hex
+ actions Match.schema(seat) Match.apply(seat, low_cmd) -> info
+ optional high-level plugin: Sport.action_layer(level) -> ActionLayer whose lower() turns a high-level
+ command into a low-level one (the episode log holds LOW-LEVEL commands only)
+ referee Match.phase() -> Phase Match.scores() -> {side: n} Match.tiebreaks() -> [(name, rule)]
+ optional: to_move(), forfeit(), resume(), retire(), ranking()
+ observation Match.observe(seat, query) -> dict (own body + referee information, whitelisted in sport.toml)
+ Match.cameras(seat, query) -> [camera definitions] (drawn by the task's renderer, renderers/)
+
+Optional hooks have defaults in MatchBase; none of them is required by every sport, and the core never branches on a
+sport. Stage-0 hooks (all optional): sides != seats (MatchConfig.sides, Match.entities: one act in flight per entity),
+N sides with a classification (Match.ranking) and in-match retirement (Match.retire), a delayed effect
+(ActionLayer.delay_steps), observation parameters (the `query` of observe/cameras), a team channel (core/channel.py,
+declared in sport.toml) and a scored single format without an opponent (tiebreaks() == []).
+
+Reply images (core 0.2.8, optional): Match.reply_views(seat, cmd, info) names the cameras (and optionally a short
+strip of frames) that show the result of an action; the core snapshots them under the lock right after the action
+took effect, draws them off the lock with the task's renderer (the path of the observation images) and attaches them
+to the action's reply as `observation` (image_png_b64 + tiles, as /observe). In the turn protocol the core also tells
+the sport whose review is due (Match.awaiting_review), so that a sport serving images only on turn can hold them
+back from the other seats while the actor reviews.
+
+Presentation (core 0.2.4, optional, spectators only): sports/<sport>/presentation/presentation.toml dresses the scene
+of Sport.scene(cfg) for spectator renderers (renderers/presentation; e.g. fine visual meshes on a robot's bodies,
+same kinematics). It is not part of the simulator directory and never reaches the players' images, unless the sport
+declares `players` there (core 0.2.9): then the generator bundles it (and the models' files) into the simulator and
+the players' images are drawn from it (core/observe.players_scene; a sport drawing its own images uses
+renderers.players_model).
+"""
+from __future__ import annotations
+
+import hashlib
+import json
+import math
+from dataclasses import asdict, dataclass, field, fields
+from typing import Any, Callable, Protocol
+
+
+@dataclass(frozen=True)
+class MatchConfig:
+ sport: str
+ format: str # single | duel | team | multi (the sport declares which it supports)
+ seats: tuple[str, ...] # e.g. ("A", "B"); the HTTP addresses /<seat>/<endpoint>
+ seed: int
+ first: str | None = None # the side that starts (serves / throws first; the rules say what that means)
+ slowdown: float | None = None # realtime only
+ level: int | None = None # scripted opponent level (single)
+ action_level: str = "high" # high | low
+ play: str = "program" # program | direct
+ params: dict = field(default_factory=dict)
+ sides: dict | None = None # seat -> side; default: every seat is its own side
+ renderer: str | None = None # the renderer of the players' images (renderers/; None = the default)
+
+ def side_of(self, seat: str) -> str:
+ return (self.sides or {}).get(seat, seat)
+
+ def side_list(self) -> list[str]:
+ out: list[str] = []
+ for s in self.seats:
+ if self.side_of(s) not in out:
+ out.append(self.side_of(s))
+ return out
+
+ def seats_of(self, side: str) -> list[str]:
+ return [s for s in self.seats if self.side_of(s) == side]
+
+ def to_json(self) -> dict:
+ d = asdict(self)
+ d["seats"] = list(self.seats)
+ return d
+
+ @staticmethod
+ def from_json(d: dict) -> "MatchConfig":
+ known = {f.name for f in fields(MatchConfig)}
+ return MatchConfig(**{**{k: v for k, v in d.items() if k in known}, "seats": tuple(d["seats"])})
+
+
+PLAYING, UNIT_OVER, FINISHED = "playing", "unit_over", "finished"
+
+
+@dataclass
+class Phase:
+ state: str # PLAYING | UNIT_OVER | FINISHED
+ review: tuple[str, ...] = () # seats that review before play resumes (realtime: usually all seats)
+ reason: str = ""
+
+
+class Refused(Exception):
+ """An action the core must refuse: HTTP `code` (400 bad body, 409 wrong time) with `message`."""
+
+ def __init__(self, message: str, code: int = 400):
+ super().__init__(message)
+ self.code = code
+ self.cause = "" # parse_action: the hidden exception (logs only)
+
+
+Tiebreak = tuple[str, Callable[["Match"], "str | None"]] # (name, rule) -> winning side or None (undecided)
+
+
+class Match(Protocol):
+ k: int # [R] control steps (realtime) / actions (turn) so far
+ dt: float # [R realtime] control step, seconds
+
+ # world
+ def step(self) -> list[dict]: ... # [R realtime] advance one control step; events
+ def state_digest(self) -> str: ... # [R] hex digest of everything that affects the score
+ # actions
+ def schema(self, seat: str) -> dict: ... # [R] the low-level command types and ranges (/spec)
+ def apply(self, seat: str, cmd: dict) -> dict: ... # [R] a LOW-LEVEL command takes effect now; info
+ # referee
+ def phase(self) -> Phase: ... # [R]
+ def scores(self) -> dict[str, float]: ... # [R] by side (informational: tiebreaks decide)
+ def tiebreaks(self) -> list[Tiebreak]: ... # [R] rulebook -> extra play -> last resort; [] = solo
+ # observation
+ def observe(self, seat: str, query: dict | None = None) -> dict: ... # [R] own body + referee information
+ def cameras(self, seat: str, query: dict | None = None) -> list[dict]: ... # [R] camera definitions (renderers/)
+
+
+class MatchBase:
+ """Defaults of every optional hook (a sport subclasses this and overrides what it needs)."""
+ k = 0
+ dt = 0.0
+ awaiting_review = None # turn protocol, set by the core: the seat whose review
+ # is due now (None: nobody's); never part of the digest
+
+ # referee
+ def resume(self) -> None: # leaving a review: frozen-time work (next serve ...)
+ pass
+
+ def to_move(self): # turn protocol: the seat whose turn it is
+ return None
+
+ def forfeit(self, seat, why) -> bool: # record a core decision inside the world (True)
+ return False
+
+ def retire(self, side, why) -> bool: # N sides: True = the match goes on without `side`
+ return False
+
+ def ranking(self): # N sides: the classification, best first
+ return None
+
+ def unit(self) -> int: # index of the current unit (acts of an old unit drop)
+ return 0
+
+ # actions
+ def schema(self, seat) -> dict:
+ return {}
+
+ def entities(self, seat) -> tuple[str, ...]: # what a seat commands; one act in flight per entity
+ return ()
+
+ # observation
+ def cameras(self, seat, query=None) -> list[dict]:
+ return []
+
+ def render_state(self) -> dict: # what a renderer needs to draw the scene now
+ return {}
+
+ def camera_job(self, seat): # a sport that draws its own images: (job, meta)
+ return None, {}
+
+ def reply_views(self, seat, cmd, info) -> dict | None:
+ """The images of an action's result for its reply (core 0.2.8), or None. Called under the lock right after
+ Match.apply(seat, cmd) returned `info` (realtime: only for an act without a delayed effect); it must not change
+ the match, and what it returns must follow from the match state and (seat, cmd, info) alone, so that a replay
+ can draw the same images (python -m core.episode PLUGIN DIR --reply N).
+ {"frames": [{"cameras": [camera definitions, as cameras()],
+ "state": render state (optional; default: render_state() now),
+ "label": short text (optional, e.g. "-200 ms"; shown in the tiles)}, ...],
+ "order": "frame" (default: frame after frame) | "camera" (camera after camera: one strip per camera),
+ "columns": tiles per row (default: sport.toml [observation] columns),
+ "note": one line for the player (optional)}
+ Drawn like the observation images: the task's renderer, the match scene (never a presentation scene),
+ sport.toml [observation] frame_budget_ms for the whole reply image."""
+ return None
+
+ def final_fields(self) -> dict: # sport fields for final.json
+ return {}
+
+ def broadcast_frame(self): # spectator frame (never read back)
+ return None
+
+
+class ActionLayer(Protocol):
+ level: str # "high" | "low"
+ worker: str | None # Sport worker kind that runs prepare(), or None
+ delay_steps: int # realtime: the effect is delay_steps after lowering
+
+ def parse(self, seat: str, body: dict, match: Match, ctx: dict) -> dict: ...
+ # validate a request body (raise Refused); ctx = core facts at the request (e.g. both chess clocks), which the
+ # plugin may copy into the command so that replay sees them
+ def snapshot(self, seat: str, cmd: dict, match: Match, ordinal: int) -> Any: ... # under the lock, for prepare
+ def prepare(self, job: Any) -> Any: ... # off the lock (in `worker` if set); expensive planning
+ def lower(self, seat: str, cmd: dict, prepared: Any, match: Match) -> tuple[dict, dict]: ...
+ # at the effect boundary, cheap: -> (low-level command for Match.apply, info for the reply)
+ def reply(self, seat: str, cmd: dict, info: dict, match: Match) -> dict: ...
+
+
+class LowLayer:
+ """The identity layer: the request body, validated by `validate(seat, body, match, ctx) -> cmd`, is the command."""
+ level = "low"
+ worker = None
+ delay_steps = 0
+
+ def __init__(self, validate):
+ self._validate = validate
+
+ def schema(self, match, seat): # what /spec shows of this layer's commands
+ return match.schema(seat)
+
+ def parse(self, seat, body, match, ctx):
+ return self._validate(seat, body, match, ctx)
+
+ def snapshot(self, seat, cmd, match, ordinal):
+ return None
+
+ def prepare(self, job):
+ return None
+
+ def lower(self, seat, cmd, prepared, match):
+ return cmd, {}
+
+ def reply(self, seat, cmd, info, match):
+ return info
+
+
+def check_command(schema: dict, body: dict) -> dict:
+ """Validate a request body against a Match.schema() and return the clean command (raises Refused).
+
+ schema = {TYPE: {FIELD: {"type": "number"|"integer"|"boolean"|"enum"|"vector", "min", "max", "values", "len",
+ "unit", "doc", "default"}}}; the command is {"type": TYPE, FIELD: value, ...}."""
+ if not isinstance(body, dict):
+ raise Refused("the action must be a JSON object")
+ kind = body.get("type")
+ if kind not in schema:
+ raise Refused(f"unknown action type {kind!r}; one of {sorted(schema)}")
+ out: dict = {"type": kind}
+ spec = schema[kind]
+ extra = sorted(set(body) - set(spec) - {"type", "entity"})
+ if extra:
+ raise Refused(f"unknown field(s) {extra} for {kind}")
+ for name, f in spec.items():
+ if name not in body:
+ if "default" in f:
+ out[name] = f["default"]
+ continue
+ raise Refused(f"{kind} needs {name}")
+ out[name] = _value(name, f, body[name])
+ if "entity" in body:
+ out["entity"] = str(body["entity"])
+ return out
+
+
+def _value(name, f, v):
+ t = f.get("type", "number")
+ if t == "boolean":
+ if not isinstance(v, bool):
+ raise Refused(f"{name} must be true or false")
+ return v
+ if t == "enum":
+ if v not in f["values"]:
+ raise Refused(f"{name} must be one of {f['values']}")
+ return v
+ if t == "vector":
+ if not isinstance(v, list) or len(v) != f["len"]:
+ raise Refused(f"{name} must be a list of {f['len']} numbers")
+ return [_number(f"{name}[{i}]", f, x) for i, x in enumerate(v)]
+ x = _number(name, f, v)
+ if t == "integer":
+ if x != int(x):
+ raise Refused(f"{name} must be an integer")
+ return int(x)
+ return x
+
+
+def _number(name, f, v):
+ if isinstance(v, bool) or not isinstance(v, (int, float)) or (isinstance(v, int) and v.bit_length() > 60) or \
+ not math.isfinite(v):
+ raise Refused(f"{name} must be a finite number")
+ lo, hi = f.get("min", -math.inf), f.get("max", math.inf)
+ if not lo <= v <= hi:
+ raise Refused(f"{name} must be in [{lo}, {hi}]")
+ return round(float(v), f.get("digits", 6))
+
+
+# ------------------------------------------------------------------ request validation (core 0.2.11)
+# Every request body is checked before an endpoint reads it (check_body), and every act body against the action
+# layer's published schema before the layer parses it (check_action). A body that fails, or that makes the layer's
+# parse raise ANY exception, is the player's own error: refused (HTTP 400, counted), never a technical failure.
+BODY_MAX_DEPTH = 10 # nesting of lists / objects (the body object is depth 1)
+BODY_MAX_ITEMS = 4096 # elements of one list, keys of one object
+BODY_MAX_STR = 8192 # characters of one string (keys included)
+BODY_MAX_ABS = 1e15 # |number|: no action of any sport needs more (and a huge integer overflows a float)
+TYPE_MAX_STR = 64 # characters of the action type
+
+
+def check_body(value, depth: int = 1) -> None:
+ """Generic sanity of a decoded JSON request body (raises Refused): finite, bounded numbers; bounded strings, list
+ lengths and nesting."""
+ if depth > BODY_MAX_DEPTH:
+ raise Refused(f"the request is nested deeper than {BODY_MAX_DEPTH} levels")
+ if value is None or isinstance(value, bool):
+ return
+ if isinstance(value, str):
+ if len(value) > BODY_MAX_STR:
+ raise Refused(f"strings are limited to {BODY_MAX_STR} characters")
+ return
+ if isinstance(value, int):
+ if value.bit_length() > 60 or abs(value) > BODY_MAX_ABS:
+ raise Refused(f"numbers are limited to +-{BODY_MAX_ABS:g}")
+ return
+ if isinstance(value, float):
+ if not math.isfinite(value) or abs(value) > BODY_MAX_ABS:
+ raise Refused(f"numbers must be finite and within +-{BODY_MAX_ABS:g}")
+ return
+ if isinstance(value, (list, dict)):
+ if len(value) > BODY_MAX_ITEMS:
+ raise Refused(f"lists and objects are limited to {BODY_MAX_ITEMS} items")
+ for k in value if isinstance(value, dict) else ():
+ if not isinstance(k, str) or len(k) > BODY_MAX_STR:
+ raise Refused("object keys must be strings")
+ for x in value.values() if isinstance(value, dict) else value:
+ check_body(x, depth + 1)
+ return
+ raise Refused("unsupported JSON value")
+
+
+def _is_num(v) -> bool:
+ return not isinstance(v, bool) and isinstance(v, (int, float))
+
+
+def _lens(spec_len) -> set | None:
+ """A field's declared length: an int, or a text such as "1 or 2" (None: not declared)."""
+ if isinstance(spec_len, int) and not isinstance(spec_len, bool):
+ return {spec_len}
+ if isinstance(spec_len, str):
+ return {int(x) for x in spec_len.replace(",", " ").split() if x.isdigit()} or None
+ return None
+
+
+def _check_field(kind: str, name: str, f, v) -> None:
+ """The shape of one declared field (ranges and meaning stay with the layer's parse)."""
+ if not isinstance(f, dict):
+ return
+ t, where = f.get("type", "number"), f"{kind}.{name}"
+ if t in ("number", "integer"):
+ if not _is_num(v):
+ raise Refused(f"{where} must be a number")
+ elif t == "boolean":
+ if not isinstance(v, bool):
+ raise Refused(f"{where} must be true or false")
+ elif t == "enum":
+ if isinstance(v, (list, dict)):
+ raise Refused(f"{where} must be one of {f.get('values')}")
+ elif t == "vector":
+ lens = _lens(f.get("len"))
+ if not isinstance(v, list) or (lens and len(v) not in lens) or not all(_is_num(x) for x in v):
+ raise Refused(f"{where} must be a list of {f.get('len', 'some')} numbers")
+ elif t == "rows":
+ lens, top = _lens(f.get("len")), f.get("max_rows")
+ if not isinstance(v, list) or (isinstance(top, int) and len(v) > top) or not all(
+ isinstance(r, list) and (not lens or len(r) in lens) and all(_is_num(x) for x in r) for r in v):
+ raise Refused(f"{where} must be a list of rows of {f.get('len', 'some')} numbers"
+ + (f", at most {top} rows" if isinstance(top, int) else ""))
+ elif t == "list":
+ if not isinstance(v, list):
+ raise Refused(f"{where} must be a list")
+ elif t == "object":
+ if not isinstance(v, dict):
+ raise Refused(f"{where} must be an object")
+ keys = f.get("keys")
+ if isinstance(keys, (list, tuple)) and set(v) - set(keys):
+ raise Refused(f"{where}: unknown key(s) {sorted(set(v) - set(keys))[:8]}; the keys are {list(keys)}")
+
+
+def check_action(schema, body) -> None:
+ """An act body against the action layer's published schema, before the layer parses it (raises Refused). The
+ type, if given, must be a short string; for a type the schema names, each declared field that is present must
+ have its shape (number, boolean, scalar enum value, vector / rows lengths, list, object keys). Unknown types and
+ fields, ranges and defaults stay with the layer's parse (a layer may take an implicit type)."""
+ if not isinstance(body, dict):
+ raise Refused("the action must be a JSON object")
+ kind = body.get("type")
+ if kind is not None and (not isinstance(kind, str) or len(kind) > TYPE_MAX_STR):
+ raise Refused(f"type must be a string of at most {TYPE_MAX_STR} characters")
+ spec = schema.get(kind) if isinstance(schema, dict) and kind is not None else None
+ if isinstance(spec, dict):
+ for name, f in spec.items():
+ if name in body:
+ _check_field(kind, name, f, body[name])
+
+
+def parse_action(layer, seat: str, body, match, ctx: dict):
+ """What the core runs for every act (and core.local for built-in players): check_body, check_action against the
+ layer's schema (what /spec shows), then layer.parse. ANY exception on the way is the player's own error: Refused
+ (HTTP 400); a malformed action never ends a match as a technical failure. The exception's text is not shown to
+ the player; the caller may log it (`Refused.cause`)."""
+ try:
+ check_body(body)
+ check_action(layer.schema(match, seat) if hasattr(layer, "schema") else {}, body)
+ return layer.parse(seat, body, match, ctx)
+ except Refused:
+ raise
+ except Exception as exc: # noqa: BLE001
+ err = Refused("invalid action: the action layer could not read it (see /spec for the command schema)")
+ err.cause = f"{type(exc).__name__}: {str(exc)[:200]}"
+ raise err from exc
+
+
+class SchemaLayer(LowLayer):
+ """The default low level: the body is checked against Match.schema(seat); `ctx_keys` copies core facts (e.g. the
+ chess clocks) into the command so that the replay sees them."""
+
+ def __init__(self, ctx_keys: tuple[str, ...] = ()):
+ super().__init__(None)
+ self.ctx_keys = ctx_keys
+
+ def parse(self, seat, body, match, ctx):
+ cmd = check_command(match.schema(seat), body)
+ ents = tuple(match.entities(seat))
+ if ents and cmd.get("entity", ents[0]) not in ents:
+ raise Refused(f"entity must be one of {list(ents)}")
+ if ents:
+ cmd.setdefault("entity", ents[0])
+ for k in self.ctx_keys:
+ cmd[k] = ctx.get(k)
+ return cmd
+
+
+class Sport(Protocol):
+ name: str
+ protocol: str # "realtime" | "turn"
+ revision: str # bump on any change that alters play
+ source_dirs: list[str] # whose files enter source_sha (the plugin dir; the core adds itself)
+
+ def build(self, cfg: MatchConfig) -> Match: ...
+ def action_layer(self, level: str) -> ActionLayer: ...
+ def spec(self, cfg: MatchConfig, seat: str, match: Match) -> dict: ...
+ # optional: the scene for renderers, worker processes (render / plan), built-in players
+ def scene(self, cfg: MatchConfig): ... # renderers.base.Scene (needed when cameras() is used);
+ # the MATCH scene: the base of the presentation scene
+ # (sports/<s>/presentation) and the players' images
+ # unless that declares `players`
+ def worker_init(self, kind: str, seat: str, cfg: MatchConfig) -> Any: ...
+ def worker_call(self, obj: Any, kind: str, job: Any) -> dict: ...
+ def players(self) -> dict: ... # {name: factory(spec, seat, seed) -> built-in player}
+
+
+def sha_json(value) -> str:
+ return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"), default=float).encode()).hexdigest()
diff --git a/scripts/roboolympics/shared/sim/rcb_olympics.py b/scripts/roboolympics/shared/sim/rcb_olympics.py
new file mode 100644
index 0000000000..f62893059e
--- /dev/null
+++ b/scripts/roboolympics/shared/sim/rcb_olympics.py
@@ -0,0 +1,723 @@
+"""RoboOlympics sports behind eai-standard/2.3 (docs/PROTOCOL.md §4b; docs/benchmarks/roboolympics.md): the adapter
+that puts one RoboOlympics match (a sport plugin under sport/, core/sport.py's contract ②) behind rcb_service's `Sim`
+contract. The protocol itself -- the endpoints, RCB1, the realtime clock and its plan, budgets, evidence, crash
+recovery, finalize -- is rcb_realtime.py + rcb_service.py, unchanged (copied from HumanoidBench's 2.3 layer).
+
+The world. One control step of the service is one control step of the match (Match.step(), 10 ms of game time), with
+one exception, the break: when a unit ends (a point, a rally) the match stands still for BREAK_S of game time -- the
+clock keeps running (the service's control steps go on at 1/S of real speed, the agent's plan is consumed), nothing
+moves, nothing scores -- and play resumes by itself when the break is over, or at the agent's `ready` row, whichever
+comes first. Like a break in a real match: the time passes, the game does not.
+
+Actions. The agent's rows are the sport's own commands (the RoboOlympics action layer of the task's level), one row per
+command: table tennis and badminton (high level) `stroke` (the paddle's / racket's state at contact, t seconds after
+the command takes effect; the service plans the swing), badminton's `toss` (the serve), `rest` (back to the ready
+pose), air hockey (low level) `mallet` (the mallet's target, a row per control step, interpolable) and `stop`; every
+sport `ready`. A command takes effect at the control step its row is planned for: the sport's action layer parses it
+there, plans it from the state of that step and lowers it to a low-level command (core/sport.py ActionLayer.lower),
+which Match.apply() installs before the step runs -- the RoboOlympics realtime service's effect boundary. A row the
+sport refuses at that moment (e.g. a toss when it is not your serve) changes nothing and is counted in proprio.
+
+The journal. A sim row is [command id, ready]: the id of the low-level command that took effect at that step (-1:
+none), and 1 when the step carries the agent's ready. The low-level commands themselves are kept in
+DATA/commands.jsonl (one JSON line per id, written before the row that names it), so the journal plus that table is the
+whole record: a replay re-applies exactly the commands the live match applied, at their steps, and never plans again.
+The match is bit-exact (the RoboOlympics sports' golden replays), so a crash resumes by replaying the journal and a
+fresh-process replay decides the verdict (`success` = a finished match the agent won).
+"""
+from __future__ import annotations
+
+import hashlib
+import importlib.util
+import json
+import math
+import os
+import subprocess
+import sys
+import tempfile
+
+import numpy as np
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+if HERE not in sys.path:
+ sys.path.insert(0, HERE)
+
+from core import spec as spec_mod # noqa: E402
+from core.outcome import decide # noqa: E402
+from core.sport import FINISHED, UNIT_OVER, MatchConfig, Refused, parse_action # noqa: E402
+
+BREAK_S = 12.0 # game seconds of the break after every unit (120 s of wall time at S = 10)
+NAN = float("nan")
+READY_DOC = ("end the break now (between units only; ignored during play): play resumes at the next control step "
+ "(the row's value is ignored; put your review in submit's note)")
+
+
+def load_plugin(path: str):
+ """The sport's plugin module at `path` (its directory first on sys.path, so its simulator modules import); its
+ SPORT is the sport."""
+ path = os.path.abspath(path)
+ if os.path.dirname(path) not in sys.path:
+ sys.path.insert(0, os.path.dirname(path))
+ spec = importlib.util.spec_from_file_location("ro_plugin", path)
+ mod = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(mod)
+ return mod
+
+
+def _f(x, default=NAN) -> float:
+ try:
+ return float(x)
+ except (TypeError, ValueError):
+ return default
+
+
+def _json(x):
+ """JSON-exact Python values: what DATA/commands.jsonl holds, so the live match applies what a replay reads back."""
+ return json.loads(json.dumps(x, default=lambda o: o.tolist() if hasattr(o, "tolist") else float(o)))
+
+
+def _clip_box(row, i, lo, hi, name, out, k):
+ v = float(row[i])
+ c = min(max(v, lo), hi)
+ if c != v:
+ out.append({"row": k, "index": i, "reason": f"{name} clipped to [{lo:g}, {hi:g}]"})
+ row[i] = c
+
+
+def _clip_norm(row, sl, cap, name, out, k):
+ v = np.asarray(row[sl], float)
+ n = float(np.linalg.norm(v))
+ if n > cap:
+ row[sl] = v * (cap / n)
+ out.append({"row": k, "index": sl.start, "reason": f"|{name}| = {n:.3f} scaled to {cap:g}"})
+
+
+def _heard(o: dict, names: dict) -> list:
+ """The first time of each heard event (seconds on the current ball's clock), NaN if not heard."""
+ out = []
+ for key in names.values():
+ out.append(next((_f(h.get("t")) for h in o.get("heard") or [] if h.get("event") == key), NAN))
+ return out
+
+
+def _last_point(points, you="you") -> float:
+ if not points:
+ return NAN
+ w = points[-1].get("winner")
+ return 1.0 if w == you else 0.0 if w in (None, "let") else -1.0
+
+
+# ================================================================================================ per-sport profiles
+class _Profile:
+ """What differs between the sports: the agent's action types (as rows), their limits, the proprio columns, the
+ cameras and how they are drawn."""
+ types: dict = {}
+ interp: tuple = ()
+ cams: dict = {}
+ drop: tuple = () # sport.toml [spec] / Sport.spec() entries about RoboOlympics' own interface
+ rules: dict = {} # ... and what replaces them here
+
+ def __init__(self, sim):
+ self.sim = sim
+
+ def body(self, typ, row): # an agent row -> the sport's act body (None: nothing new)
+ raise NotImplementedError
+
+ def clip(self, typ, rows):
+ return rows, []
+
+ def command(self, typ):
+ """The row a gap in the plan is filled with (rcb_realtime: a submit whose `at` lies ahead holds "the target in
+ force" until then; a row is also interpolated from it): for a command that is not a target, zeros, which
+ to_sim reads as no command. No agent row is all zeros after clip() (Olympics.clip)."""
+ return np.zeros(int(self.types[typ]["dim"]))
+
+ def proprio(self) -> list:
+ raise NotImplementedError
+
+ def images(self, cams) -> dict:
+ raise NotImplementedError
+
+
+def _stroke_type(what, t_max, box, extra=""):
+ return {"dim": 10, "layout": ["t", "x", "y", "z", "nx", "ny", "nz", "vx", "vy", "vz"],
+ "units": "s, m, unit-free normal, m/s (your frame)",
+ "limits": {"t": [0.0, t_max], **box, "normal": "non-zero", "speed_max": 8.0},
+ "semantics": (f"the {what}'s state at contact t seconds after the command takes effect: centre x y z, face "
+ f"normal nx ny nz (pointing where the ball should go), velocity vx vy vz; it replaces the "
+ f"stroke under way; the service plans the swing (IK, joint speed limits) and the robot goes "
+ f"back to its ready pose after it. Out-of-range values are clipped (meta.clipped){extra}"),
+ "interpolable": False}
+
+
+class TableTennis(_Profile):
+ types = {
+ "stroke": _stroke_type("paddle blade", 2.5, {"x": [-1.2, 1.2], "y": [-2.5, -0.5], "z": [0.0, 1.2]},
+ "; the delivered state scatters by about 4 mm, 0.6 degrees and 2 %"),
+ "rest": {"dim": 1, "layout": ["unused"], "interpolable": False,
+ "semantics": "cancel the stroke under way: the arm returns to its ready pose (the value is ignored)"},
+ "ready": {"dim": 1, "layout": ["unused"], "interpolable": False, "semantics": READY_DOC}}
+ drop = ("duel", "observation", "action_high", "action_low", "real_time", "scatter_and_seed")
+ rules = {"scatter": "the serves, the opponent's returns and your strokes' execution scatter are drawn from the "
+ "task's frozen seed (never shown)"}
+ HEARD = {"opp_bounce": "bounce on the opponent's half", "own_bounce": "bounce on your half", "net": "net",
+ "paddle": "paddle", "robot": "robot", "floor": "floor"}
+ layout = (["score_you", "score_opponent", "point", "ball_is_serve", "t_since_played", "serve_in_s",
+ "ball_in_play", "ball_coming", "ball_going"]
+ + [f"heard_{k}_t" for k in HEARD]
+ + [f"q{i}" for i in range(1, 8)] + ["paddle_x", "paddle_y", "paddle_z", "paddle_nx", "paddle_ny", "paddle_nz"]
+ + ["stroke_active", "stroke_contact_in_s", "stroke_speed_scale", "stroke_blade_error_m",
+ "stroke_normal_error_deg", "stroke_ik_residual", "last_point_won"])
+
+ def __init__(self, sim):
+ super().__init__(sim)
+ import match
+ self.cams = {c["name"]: dict(c, fovy_deg=45.0, hw=[360, 480], focal_px=434.6, principal_point_px=[240, 180])
+ for c in match.Match.CAM_INFO}
+ self.view = None
+
+ def body(self, typ, row):
+ if typ == "rest":
+ return {"type": "none"}
+ r = [float(x) for x in row]
+ return {"type": "act", "t": r[0], "pos": r[1:4], "normal": r[4:7], "vel": r[7:10]}
+
+ def clip(self, typ, rows):
+ out = []
+ if typ != "stroke":
+ return rows, out
+ rows = np.array(rows, dtype=np.float64)
+ for k, row in enumerate(rows):
+ _clip_box(row, 0, 0.01, 2.5, "t", out, k)
+ for i, (lo, hi) in zip((1, 2, 3), ((-1.2, 1.2), (-2.5, -0.5), (0.0, 1.2))):
+ _clip_box(row, i, lo, hi, "xyz"[i - 1], out, k)
+ if np.linalg.norm(row[4:7]) < 1e-6:
+ row[4:7] = [0.0, 1.0, 0.0]
+ out.append({"row": k, "index": 4, "reason": "a zero normal replaced by (0, 1, 0)"})
+ _clip_norm(row, slice(7, 10), 8.0, "vel", out, k)
+ return rows, out
+
+ def proprio(self):
+ m = self.sim.m
+ o = m.observe(self.sim.seat)
+ R = m.R
+ bs = o.get("ball_state")
+ cmd = o.get("command")
+ la = getattr(R, "_last_act", None) or {}
+ active = isinstance(cmd, dict)
+ return ([_f(o["score"]["you"]), _f(o["score"]["opponent"]), _f(o.get("point")),
+ 1.0 if o.get("ball") == "serve" else 0.0, _f(o.get("t_since_played")), _f(o.get("serve_in_s"), 0.0),
+ float(bool(o.get("ball_in_play"))), float(bs == "coming to you"), float(bs == "going to the opponent")]
+ + _heard(o, self.HEARD) + [_f(x) for x in o["q"]] + [_f(x) for x in o["paddle_pos"]]
+ + [_f(x) for x in o["paddle_normal"]]
+ + [float(active), _f(cmd.get("contact_in_s")) if active else NAN,
+ _f(la.get("speed_scale")) if active else NAN, _f(la.get("blade_error_m")) if active else NAN,
+ _f(la.get("normal_error_deg")) if active else NAN, _f(la.get("ik_residual")) if active else NAN,
+ _last_point(R.points)])
+
+ def images(self, cams):
+ if self.view is None:
+ self.view = self.sim.mod.MatchView()
+ import match
+ R = self.sim.m.R
+ names = list(self.cams)
+ q, ox = R.s.d.qpos.copy(), R.opp_x()
+ text = f"k={R.k} t={R.t_since_launch():.2f}s"
+ return {c: self.view.tile(names.index(c), q, text, lambda scn, o=ox: match.Match._extra_geoms(None, scn, o), ox)
+ for c in cams}
+
+
+class Badminton(_Profile):
+ types = {
+ "stroke": _stroke_type("racket head", 5.0, {"x": [-3.4, 3.4], "y": [-7.5, -0.3], "z": [0.2, 3.0]},
+ "; it takes effect spec.rules.act.lead_steps control steps after its row's step (the "
+ "planning time), and t counts from then; a stroke or toss sent before the previous one "
+ "took effect is refused"),
+ "toss": {"dim": 4, "layout": ["x", "y", "z", "height"], "units": "m (your frame)", "interpolable": False,
+ "limits": {"z": [0.5, 1.8], "height": [0.0, 0.5], "y_max": -0.5, "reach_from_base": 1.0},
+ "semantics": ("your serve: the shuttle appears at x y z (from rest, or rising `height` straight up) "
+ "when the command takes effect (the same lead as a stroke); only the server, once per "
+ "serve, from the step the receiver is ready (proprio serve_phase = 1, open); then hit "
+ "it with a stroke (which may be sent before the toss)")},
+ "rest": {"dim": 1, "layout": ["unused"], "interpolable": False,
+ "semantics": "cancel the stroke under way: the robot returns to its ready pose, the base home"},
+ "ready": {"dim": 1, "layout": ["unused"], "interpolable": False, "semantics": READY_DOC}}
+ drop = ("duel", "observation", "lowlevel", "act")
+ PHASES = {"waiting": 0.0, "open": 1.0, "tossed": 2.0, "done": 3.0}
+ layout = (["score_you", "score_opponent", "point", "you_serve", "serve_court_right", "serve_phase",
+ "serve_opens_in_s", "serve_deadline_in_s", "serve_tossed_at_step", "ball_kind", "t_since_played",
+ "ball_in_play", "ball_not_served", "ball_tossed", "ball_coming", "ball_going",
+ "base_x", "base_y"] + [f"q{i}" for i in range(1, 8)]
+ + ["racket_x", "racket_y", "racket_z", "racket_nx", "racket_ny", "racket_nz",
+ "stroke_active", "stroke_contact_in_s", "stroke_traj_steps_left", "stroke_pending_effect_step",
+ "stroke_head_speed_limited", "stroke_pose_not_delivered", "last_point_won"])
+
+ def __init__(self, sim):
+ super().__init__(sim)
+ import bm
+ FOCAL_PX = sim.mod.FOCAL_PX
+ self.TOSS_Z, self.TOSS_H = tuple(bm.TOSS_Z), float(bm.TOSS_H_MAX)
+ self.types = dict(self.types)
+ self.types["toss"] = dict(self.types["toss"], limits={"z": list(bm.TOSS_Z), "height": [0.0, bm.TOSS_H_MAX],
+ "y_max": -0.5, "reach_from_base": bm.TOSS_REACH})
+ lead = sim.mod.lead_steps(sim.cfg.slowdown)
+ self.rules = {"act": {"lead_steps": lead, "lead_game_s": round(lead * bm.CONTROL_DT, 4),
+ "rule": (f"a stroke, a toss or a rest takes effect {lead} control steps after the step "
+ "its row is planned for (the stroke is planned meanwhile; proprio "
+ "stroke_pending_effect_step shows it); a stroke's t counts from that effect "
+ "step; another stroke, toss or rest planned before then is refused")},
+ "serve": {"command": ("a `toss` row: the shuttle appears at x y z when the command takes effect "
+ "(the same lead as a stroke) and rises `height` straight up (0: released "
+ "from rest); then hit it with a stroke (it may be sent before the toss)"),
+ "phases": ("proprio serve_phase: 0 waiting (the receiver is getting ready), 1 open "
+ "(toss now), 2 tossed, 3 done")}}
+ w, h = bm.Match.TILE
+ self.cams = {c["name"]: dict(c, fovy_deg=45.0, hw=[h, w], focal_px=FOCAL_PX, principal_point_px=[w / 2, h / 2])
+ for c in bm.Match.cam_info()}
+ self.view = None
+
+ def body(self, typ, row):
+ r = [float(x) for x in row]
+ if typ == "rest":
+ return {"type": "none"}
+ if typ == "toss":
+ return {"type": "toss", "pos": r[0:3], "height": r[3]}
+ return {"type": "act", "t": r[0], "pos": r[1:4], "normal": r[4:7], "vel": r[7:10]}
+
+ def clip(self, typ, rows):
+ out = []
+ rows = np.array(rows, dtype=np.float64)
+ if typ == "stroke":
+ for k, row in enumerate(rows):
+ _clip_box(row, 0, 0.01, 5.0, "t", out, k)
+ for i, (lo, hi) in zip((1, 2, 3), ((-3.4, 3.4), (-7.5, -0.3), (0.2, 3.0))):
+ _clip_box(row, i, lo, hi, "xyz"[i - 1], out, k)
+ if np.linalg.norm(row[4:7]) < 1e-6:
+ row[4:7] = [0.0, 1.0, 0.0]
+ out.append({"row": k, "index": 4, "reason": "a zero normal replaced by (0, 1, 0)"})
+ _clip_norm(row, slice(7, 10), 8.0, "vel", out, k)
+ elif typ == "toss":
+ for k, row in enumerate(rows):
+ _clip_box(row, 1, -7.5, -0.5, "y", out, k)
+ _clip_box(row, 2, self.TOSS_Z[0], self.TOSS_Z[1], "z", out, k)
+ _clip_box(row, 3, 0.0, self.TOSS_H, "height", out, k)
+ return rows, out
+
+ def proprio(self):
+ m = self.sim.m
+ o = m.observe(self.sim.seat)
+ sv = o.get("serve") or {}
+ bs = str(o.get("ball_state") or "")
+ cmd = o.get("command")
+ active = isinstance(cmd, dict) and "contact_in_s" in cmd
+ notes = str(cmd.get("stroke") or "") if active else ""
+ pend = o.get("pending_commands") or []
+ kind = {"serve": 0.0, "your serve": 1.0}.get(o.get("ball"), 2.0)
+ return ([_f(o["score"]["you"]), _f(o["score"]["opponent"]), _f(o.get("point")), float(bool(o.get("you_serve"))),
+ float(sv.get("court") == "right"), self.PHASES.get(sv.get("phase"), NAN), _f(sv.get("opens_in_s")),
+ _f(sv.get("deadline_in_s")), _f(sv.get("tossed_at_step")), kind, _f(o.get("t_since_played")),
+ float(bool(o.get("ball_in_play"))), float(bs == "not yet served"), float(bs.startswith("tossed")),
+ float(bs == "coming to you"), float(bs == "going to the opponent")]
+ + [_f(x) for x in o["robot_base_xy"]] + [_f(x) for x in o["q_arm"]] + [_f(x) for x in o["racket_pos"]]
+ + [_f(x) for x in o["racket_normal"]]
+ + [float(active), _f(cmd.get("contact_in_s")) if active else NAN,
+ _f(cmd.get("traj_steps_left"), 0.0) if isinstance(cmd, dict) else 0.0,
+ _f(pend[0].get("takes_effect_at_step")) if pend else NAN,
+ float("head speed limited" in notes), float("pose not delivered" in notes),
+ _last_point(m.g.points)])
+
+ def images(self, cams):
+ if self.view is None:
+ self.view = self.sim.mod.Views(True, "A")
+ g = self.sim.m.g
+ sn = {"qpos": g.s.d.qpos.copy(), "sh": tuple(float(x) for x in g.s.sh_p),
+ "shv": tuple(float(x) for x in g.s.sh_v), "opp": [float(x) for x in g.opp_xy()],
+ "k": int(g.k), "t": float(g.t_since_launch())}
+ names = list(self.cams)
+ return {c: self.view.tile(names.index(c), sn) for c in cams}
+
+
+class AirHockey(_Profile):
+ types = {
+ "mallet": {"dim": 2, "layout": ["x", "y"], "units": "m (the table frame)", "interpolable": True,
+ "semantics": ("the mallet centre's target; the robot drives the mallet there along a speed- and "
+ "acceleration-limited path (spec.sport.mallet_path) and holds it until replaced; "
+ "own half only: a target outside the workspace (spec.sport.workspace) is moved to "
+ "its nearest point (meta.clipped)")},
+ "stop": {"dim": 1, "layout": ["unused"], "interpolable": False,
+ "semantics": "the mallet stops where it is (its target becomes its position)"},
+ "ready": {"dim": 1, "layout": ["unused"], "interpolable": False, "semantics": READY_DOC}}
+ interp = ("mallet",)
+ drop = ("real_time", "action", "observation")
+ rules = {"review": ("every goal, foul or dead puck ends the rally: both mallets return home, the break follows "
+ "(spec.break), then the next rally starts")}
+ HOW = {"goal": 1.0, "seven_second_foul": 2.0, "dead_puck": 3.0, "time_cap": 4.0}
+ layout = (["score_you", "score_opponent", "rally", "t_play", "play_time_left_s",
+ "mallet_x", "mallet_y", "mallet_z", "target_x", "target_y"]
+ + [f"q{i}" for i in range(1, 8)] + ["q_striker1", "q_striker2"]
+ + [f"qd{i}" for i in range(1, 8)] + ["qd_striker1", "qd_striker2"]
+ + ["last_rally_how", "last_rally_scored", "last_rally_fouled", "last_rally_next_puck"])
+
+ def __init__(self, sim):
+ super().__init__(sim)
+ from renderers.base import CameraDef
+ self.P = sim.mod
+ self.camdefs = [CameraDef.from_dict(c) for c in sim.m.cameras(sim.seat)]
+ self.cams = {c.name: dict(c.to_dict(), **c.intrinsics(), hw=[c.height, c.width]) for c in self.camdefs}
+ self.renderer = None
+
+ def body(self, typ, row):
+ h = self.sim.m.h
+ if typ == "stop":
+ return {"type": "none"}
+ x, y = float(row[0]), float(row[1])
+ cur = h.commands.get(self.sim.seat) if isinstance(h.commands, dict) else None
+ if cur is not None and abs(float(cur[0]) - x) < 1e-9 and abs(float(cur[1]) - y) < 1e-9:
+ return None # the target in force: nothing new
+ return {"type": "target", "x": x, "y": y}
+
+ def clip(self, typ, rows):
+ out = []
+ rows = np.array(rows, dtype=np.float64)
+ if typ != "mallet":
+ return rows, out
+ H = self.P.H
+ for k, row in enumerate(rows):
+ w = H.workspace(self.sim.seat, row)
+ if not H.in_workspace(self.sim.seat, w, eps=0.0): # the box-then-radial clip may land a hair outside
+ w = H.workspace(self.sim.seat, [w[0] * 0.999999, w[1] * 0.999999])
+ w = [round(float(w[0]), 6), round(float(w[1]), 6)]
+ if abs(w[0] - row[0]) > 1e-9 or abs(w[1] - row[1]) > 1e-9:
+ out.append({"row": k, "index": 0, "reason": "outside the mallet workspace: moved to its nearest point"})
+ row[0], row[1] = w
+ return rows, out
+
+ def command(self, typ):
+ if typ == "mallet":
+ h = self.sim.m.h
+ return np.asarray(h.commands[self.sim.seat], np.float64)
+ return super().command(typ)
+
+ def proprio(self):
+ m = self.sim.m
+ o = m.observe(self.sim.seat)
+ h = m.h
+ sc = h.scores()
+ last = h.results[-1] if h.results else None
+ side = lambda s: NAN if last is None else (1.0 if s == "A" else -1.0 if s == "B" else 0.0) # noqa: E731
+ return ([_f(sc["A"]["points"]), _f(sc["B"]["points"]), _f(o["rally"]), _f(o["t_play"]),
+ _f(o["play_time_left_s"])] + [_f(x) for x in o["own"]["mallet_xyz"]]
+ + [_f(x) for x in o["own"]["command"]] + [_f(x) for x in o["own"]["joint_position"]]
+ + [_f(x) for x in o["own"]["joint_velocity"]]
+ + [NAN if last is None else self.HOW.get(last["how"], 5.0), side(last and last["winner"]),
+ side(last and last["guilty"]), side(last and last["next"])])
+
+ def images(self, cams):
+ if self.renderer is None:
+ import renderers
+ from core.observe import players_scene
+ sim = self.sim
+ self.renderer = renderers.load(sim.cfg.renderer or renderers.DEFAULT)(
+ players_scene(sim.sport, sim.plugin, sim.cfg))
+ imgs = self.renderer.render(self.sim.m.render_state(), self.camdefs)
+ return {c.name: img for c, img in zip(self.camdefs, imgs) if c.name in cams}
+
+
+PROFILES = {"tabletennis": TableTennis, "badminton": Badminton, "airhockey": AirHockey}
+
+
+# ================================================================================================ the Sim contract
+class Olympics:
+ """One RoboOlympics match against the scripted opponent (seat A) behind rcb_service.Sim (module docstring)."""
+
+ raw_dim = 2 # [command id (-1: none), ready]
+ depth_cameras: tuple = ()
+
+ def __init__(self, plugin: str, cfg: MatchConfig, data: str | None = None, task_text: str = "",
+ episode_text: str = "", break_s: float = BREAK_S):
+ self.plugin, self.cfg, self.data = os.path.abspath(plugin), cfg, data
+ self.mod = load_plugin(self.plugin)
+ self.sport = self.mod.SPORT
+ self.decl = spec_mod.load(self.plugin)
+ self.seat = cfg.seats[0]
+ self.task_text, self.episode_text = task_text, episode_text
+ self.commands: list = []
+ self.cmd_path = os.path.join(data, "commands.jsonl") if data else None
+ if self.cmd_path and os.path.exists(self.cmd_path): # a resumed service: the table so far
+ with open(self.cmd_path) as f:
+ for line in f:
+ try:
+ rec = json.loads(line)
+ except ValueError:
+ break # a line cut by a crash: no journal row names it
+ if rec.get("id") == len(self.commands):
+ self.commands.append(rec["low"])
+ self._new_match()
+ self.control_dt = float(self.m.dt)
+ self.break_steps = max(1, int(round(break_s / self.control_dt)))
+ self.max_control_steps = 10 ** 8 # no step cap: the match ends by its rules, else the wall clock
+ self.profile = PROFILES[self.sport.name](self)
+ self.cameras = tuple(self.profile.cams)
+ self.proprio_layout = (["match_step", "break", "break_left_s", "finished"] + list(self.profile.layout)
+ + ["commands_applied", "commands_refused", "last_refused_step"])
+
+ def _new_match(self):
+ self.m = self.sport.build(self.cfg)
+ self.layer = self.sport.action_layer(self.cfg.action_level)
+ self.steps = 0 # control steps of this episode, breaks included
+ self.in_break, self.break_left, self.breaks = False, 0, []
+ self.finished = self.won = False
+ self.applied = self.refused = self.dropped = 0
+ self.last_refused = -1
+
+ # ------------------------------------------------------------------ facts
+ def spec(self) -> dict:
+ sport = dict(self.decl.get("spec") or {}) # as RoboOlympics' public_spec: sport.toml, then Sport.spec()
+ sport.update(self.sport.spec(self.cfg, self.seat, self.m))
+ for k in ("calls", "image", "image_layout", "cameras", "action_interface") + tuple(self.profile.drop):
+ sport.pop(k, None)
+ for k, v in self.profile.rules.items():
+ sport[k] = {**sport[k], **v} if isinstance(v, dict) and isinstance(sport.get(k), dict) else v
+ if (self.decl.get("tiebreaks") or {}).get("text"):
+ sport["tiebreaks"] = self.decl["tiebreaks"]["text"]
+ types = {k: {kk: vv for kk, vv in v.items() if kk != "interpolable"} for k, v in self.profile.types.items()}
+ s = self.decl.get("sport") or {}
+ return {"simulator": "RoboOlympics on MuJoCo 3.3.7 (CPU)", "sport": s.get("name", self.sport.name),
+ "title": s.get("title"), "revision": self.sport.revision, "robot": sport.pop("robot", None),
+ "task_text": self.task_text, "episode": self.episode_text,
+ "match": {"format": self.cfg.format, "opponent_level": self.cfg.level, "action_level":
+ self.cfg.action_level, "you": self.seat},
+ "action_types": types, "cameras": self.profile.cams, "rules": sport,
+ "break": {"game_s": self.break_steps * self.control_dt, "control_steps": self.break_steps,
+ "rule": ("after every unit (a point, a rally) the match stands still for this much game "
+ "time: the clock runs on (control steps, wall time, your plan), nothing moves and "
+ "nothing scores; play resumes by itself at the end of the break, or at the control "
+ "step of your `ready` row. proprio: break (1 during it), break_left_s")},
+ "proprio_notes": ("one row per frame, columns proprio_layout; NaN = not applicable now; match_step = "
+ "the match's own control step (it stands still in a break; meta.control_steps "
+ "counts every step); times in game seconds; positions in your frame")}
+
+ def interpolable(self, typ: str) -> bool:
+ return typ in self.profile.interp
+
+ # ------------------------------------------------------------------ observation
+ def images(self, cameras, depth):
+ return self.profile.images(list(cameras)), {}
+
+ def proprio(self) -> np.ndarray:
+ own = [float(self.m.k), float(self.in_break), self.break_left * self.control_dt if self.in_break else 0.0,
+ float(self.finished)]
+ return np.asarray(own + self.profile.proprio() + [float(self.applied), float(self.refused),
+ float(self.last_refused)], np.float32)
+
+ # ------------------------------------------------------------------ actions
+ def clip(self, typ, rows):
+ """The profile's limits; a one-value command (rest, stop, ready: the value is ignored) becomes 1, so that no
+ agent row is all zeros, the gap filler's row (command())."""
+ try:
+ if int(self.profile.types.get(typ, {}).get("dim", 0)) == 1 and typ not in self.profile.interp:
+ return np.ones((len(rows), 1)), []
+ return self.profile.clip(typ, rows)
+ except Exception as exc: # noqa: BLE001 -- clip must never fail a request that passed the checks
+ return np.asarray(rows, np.float64), [{"row": 0, "index": 0, "reason": f"unchecked: {exc!r}"[:200]}]
+
+ def command(self, typ):
+ try:
+ return self.profile.command(typ)
+ except Exception: # noqa: BLE001
+ return np.zeros(int(self.profile.types.get(typ, {"dim": 1})["dim"]))
+
+ def hold(self):
+ return "hold", np.zeros(1)
+
+ def to_sim(self, typ, row) -> np.ndarray:
+ """At the step the row is planned for (rcb_service._step, right before step()): the row as a sim row. A
+ command is parsed, planned and lowered here, from this step's state, and enters the command table. An all-zero
+ row of a command type is no command: a gap the service filled with command() (clip() leaves no agent row so)."""
+ if typ not in self.profile.interp and not np.any(np.asarray(row, dtype=np.float64)):
+ return np.array([-1.0, 0.0])
+ if typ == "ready":
+ return np.array([-1.0, 1.0])
+ if typ not in self.profile.types or self.finished:
+ return np.array([-1.0, 0.0])
+ if self.in_break:
+ self.dropped += 1
+ return np.array([-1.0, 0.0])
+ body = self.profile.body(typ, row)
+ if body is None:
+ return np.array([-1.0, 0.0])
+ rec = {"id": len(self.commands), "step": self.steps, "match_k": int(self.m.k), "type": typ,
+ "row": [float(x) for x in row]}
+ try:
+ cmd = parse_action(self.layer, self.seat, body, self.m, {})
+ job = self.layer.snapshot(self.seat, cmd, self.m, self.applied + self.refused + 1)
+ prepared = self.layer.prepare(job) if job is not None else None
+ low, info = self.layer.lower(self.seat, cmd, prepared, self.m)
+ except Refused as exc:
+ self.refused += 1
+ self.last_refused = int(self.m.k)
+ self._log({**rec, "id": None, "refused": str(exc)[:300]})
+ return np.array([-1.0, 0.0])
+ rec.update(low=_json(low), info=_json(info))
+ self.commands.append(rec["low"])
+ self._log(rec)
+ return np.array([float(rec["id"]), 0.0])
+
+ def _log(self, rec):
+ if self.cmd_path:
+ with open(self.cmd_path, "a") as f:
+ f.write(json.dumps(rec, default=float) + "\n")
+ f.flush()
+
+ def step(self, row) -> tuple[bool, bool, dict]:
+ cid, ready = int(round(float(row[0]))), float(row[1]) > 0.5
+ self.steps += 1
+ if self.finished:
+ return True, self.won, {}
+ if self.in_break:
+ if ready or self.break_left <= 1:
+ self.in_break = False
+ self.breaks[-1].update(end=self.steps, by="ready" if ready else "time")
+ self.m.resume()
+ else:
+ self.break_left -= 1
+ return False, False, {}
+ if cid >= 0:
+ info = self.m.apply(self.seat, self.commands[cid]) or {}
+ if isinstance(info, dict) and "rejected" in info:
+ self.refused += 1
+ self.last_refused = int(self.m.k)
+ else:
+ self.applied += 1
+ self.m.step()
+ ph = self.m.phase()
+ if ph.state == FINISHED:
+ self.finished = True
+ out = decide(self.m, None, None, self.cfg.side_list(), self.cfg.side_of)
+ self.won = out.winner == self.cfg.side_of(self.seat)
+ return True, self.won, {}
+ if ph.state == UNIT_OVER:
+ self.in_break, self.break_left = True, self.break_steps
+ self.breaks.append({"start": self.steps, "match_k": int(self.m.k), "reason": ph.reason})
+ return False, False, {}
+
+ # ------------------------------------------------------------------ episode
+ def reset(self) -> None:
+ self._new_match()
+ self.profile = PROFILES[self.sport.name](self)
+
+ def state_sha(self) -> str:
+ own = json.dumps([self.steps, self.in_break, self.break_left, self.finished, self.won], sort_keys=True)
+ return hashlib.sha256((self.m.state_digest() + own).encode()).hexdigest()
+
+ def summary(self) -> dict:
+ out = decide(self.m, None, None, self.cfg.side_list(), self.cfg.side_of)
+ scores = self.m.scores()
+ you = self.cfg.side_of(self.seat)
+ them = [s for s in scores if s != you]
+ return {"sport": self.sport.name, "revision": self.sport.revision, "finished": self.finished,
+ "won": bool(self.finished and out.winner == you), "winner": out.winner, "decided_by": out.decided_by,
+ "scores": scores, "points_for": scores.get(you), "points_against": scores.get(them[0]) if them else None,
+ "match_steps": int(self.m.k), "control_steps": self.steps, "breaks": self.breaks,
+ "commands_applied": self.applied, "commands_refused": self.refused,
+ "rows_dropped_in_breaks": self.dropped, "cfg": self.cfg.to_json(), "break_steps": self.break_steps,
+ "sport_fields": _json(self.m.final_fields())}
+
+ # ------------------------------------------------------------------ the record, the replay, the video
+ def save_trajectory(self, rows, path, meta) -> None:
+ np.savez_compressed(path, rows=np.asarray(rows, np.float64).reshape(-1, self.raw_dim),
+ commands=np.array(json.dumps(self.commands)), cfg=np.array(json.dumps(self.cfg.to_json())),
+ break_steps=np.array(self.break_steps), meta=np.array(json.dumps(meta, default=str)),
+ layout=np.array(json.dumps(["command_id", "ready"])))
+
+ def _sub(self, mode: str, rows, out: str) -> dict:
+ """A fresh process (python rcb_olympics.py MODE ...): the replay never shares state with the live match."""
+ fd, tmp = tempfile.mkstemp(suffix=".npz", dir=self.data or None)
+ os.close(fd)
+ try:
+ self.save_trajectory(rows, tmp, {"for": mode})
+ env = dict(os.environ, RO_TASK_TEXT=self.task_text, RO_EPISODE_TEXT=self.episode_text)
+ r = subprocess.run([sys.executable, os.path.abspath(__file__), mode, self.plugin, tmp, out],
+ capture_output=True, text=True, env=env, timeout=3600)
+ if r.returncode:
+ raise RuntimeError(f"{mode} failed: {r.stderr[-1500:]}")
+ return json.loads(r.stdout.strip().splitlines()[-1])
+ finally:
+ os.unlink(tmp)
+
+ def verify(self, rows) -> dict:
+ out = os.path.join(self.data, "match.json") if self.data else os.devnull
+ rep = self._sub("replay", rows, out)
+ return {"success": bool(rep["won"]), "state_sha": rep["state_sha"]}
+
+ def render_video(self, rows, path) -> None:
+ self._sub("video", rows, path)
+
+
+# ================================================================================================ fresh processes
+def _rebuild(plugin: str, npz: str) -> tuple[Olympics, np.ndarray]:
+ z = np.load(npz)
+ cfg = MatchConfig.from_json(json.loads(str(z["cfg"])))
+ sim = Olympics(plugin, cfg, None, os.environ.get("RO_TASK_TEXT", ""), os.environ.get("RO_EPISODE_TEXT", ""))
+ sim.break_steps = int(z["break_steps"])
+ sim.commands = json.loads(str(z["commands"]))
+ return sim, np.asarray(z["rows"], np.float64).reshape(-1, sim.raw_dim)
+
+
+def replay_main(plugin: str, npz: str, out: str) -> dict:
+ sim, rows = _rebuild(plugin, npz)
+ for row in rows:
+ sim.step(row)
+ summary = {**sim.summary(), "state_sha": sim.state_sha()}
+ with open(out, "w") as f:
+ json.dump(summary, f, default=float)
+ return {"won": summary["won"], "state_sha": summary["state_sha"], "scores": summary["scores"]}
+
+
+def video_main(plugin: str, npz: str, out: str, max_frames: int = 1500) -> dict:
+ """The replay for humans: the cameras side by side, one frame every 4 control steps of play (game time at real speed:
+ 25 fps; sparser for a long match, at most about max_frames frames), breaks skipped; the score in the corner.
+ Writes out and out.last.png."""
+ import imageio.v2 as imageio
+ from PIL import Image, ImageDraw
+ sim, rows = _rebuild(plugin, npz)
+ every = max(4, math.ceil(len(rows) / max_frames))
+ cams = list(sim.cameras)
+ w = imageio.get_writer(out, fps=round(1.0 / (every * sim.control_dt)), macro_block_size=8, codec="libx264",
+ output_params=["-pix_fmt", "yuv420p"])
+ last, n = None, 0
+
+ def frame():
+ imgs = sim.images(cams, False)[0]
+ h = max(i.shape[0] for i in imgs.values())
+ row = np.concatenate([np.pad(imgs[c], ((0, h - imgs[c].shape[0]), (0, 0), (0, 0))) for c in cams], axis=1)
+ im = Image.fromarray(np.ascontiguousarray(row[..., :3]))
+ sc = sim.m.scores()
+ ImageDraw.Draw(im).text((8, im.height - 16), " ".join(f"{k} {v}" for k, v in sc.items()), fill=(255, 255, 0))
+ return np.asarray(im)
+
+ try:
+ for i, row in enumerate(rows):
+ was = sim.in_break
+ sim.step(row)
+ if (not was and i % every == 0) or sim.finished:
+ last = frame()
+ w.append_data(last)
+ n += 1
+ if sim.finished:
+ break
+ if last is None:
+ last = frame()
+ w.append_data(last)
+ n += 1
+ finally:
+ w.close()
+ Image.fromarray(last).save((out[:-4] if out.endswith(".mp4") else out) + ".last.png") # replay.last.png
+ return {"frames": n, "every": every}
+
+
+if __name__ == "__main__":
+ mode, plugin_path, npz_path, out_path = sys.argv[1:5]
+ res = replay_main(plugin_path, npz_path, out_path) if mode == "replay" else video_main(plugin_path, npz_path,
+ out_path)
+ print(json.dumps(res, default=float))
diff --git a/scripts/roboolympics/shared/sim/renderers/__init__.py b/scripts/roboolympics/shared/sim/renderers/__init__.py
new file mode 100644
index 0000000000..9a55e841d4
--- /dev/null
+++ b/scripts/roboolympics/shared/sim/renderers/__init__.py
@@ -0,0 +1,40 @@
+"""Renderer plugins (docs/framework_zh.md §3.1): a renderer draws a sport's scene, from its camera definitions, for
+one world state. Sports never import a renderer; the core calls the task's observation renderer (task parameter
+`renderer`, default DEFAULT) and the viewing tools any renderer for re-renders.
+
+ from renderers import load, Scene, CameraDef
+ R = load("mujoco")(Scene.from_file("scene.xml"))
+ images = R.render({"qpos": qpos}, [CameraDef("behind", pos, lookat)])
+"""
+from __future__ import annotations
+
+import importlib
+
+from .base import CameraDef, Renderer, RendererUnavailable, Scene # noqa: F401
+
+DEFAULT = "mujoco"
+REGISTRY = { # name -> (module, realtime, needs_gpu, requires)
+ "mujoco": ("renderers.mujoco", True, False, "mujoco; MUJOCO_GL=osmesa (CPU) or egl (GPU)"),
+ "mujoco-showcase": ("renderers.mujoco_showcase", True, False, "as mujoco"),
+ "cycles": ("renderers.cycles", False, True, "Docker, the rcb-showcase-blender image, an NVIDIA GPU (or device=CPU)"),
+ "isaac": ("renderers.isaac", False, True, "Docker, the Isaac Sim 4.5 image, an NVIDIA RTX GPU"),
+}
+
+
+def load(name: str = DEFAULT):
+ """The Renderer subclass registered under `name`."""
+ if name not in REGISTRY:
+ raise KeyError(f"unknown renderer {name!r}; have {sorted(REGISTRY)}")
+ return importlib.import_module(REGISTRY[name][0]).RENDERER
+
+
+def available() -> dict:
+ return {n: {"realtime": rt, "needs_gpu": gpu, "requires": req} for n, (_, rt, gpu, req) in REGISTRY.items()}
+
+
+def players_model(sport_dir, match: Scene):
+ """For a sport that draws its own images (the renderers' interface for sports): the compiled MjModel of the
+ players' presentation scene its presentation.toml declares (`players`, renderer rule 6; the same kinematics as
+ `match` checked), or None when it declares none (draw the match model). See renderers/presentation."""
+ from .presentation import players_model as _players_model
+ return _players_model(sport_dir, match)
diff --git a/scripts/roboolympics/shared/sim/renderers/base.py b/scripts/roboolympics/shared/sim/renderers/base.py
new file mode 100644
index 0000000000..7cf75e40ba
--- /dev/null
+++ b/scripts/roboolympics/shared/sim/renderers/base.py
@@ -0,0 +1,156 @@
+"""The renderer plugin interface (docs/framework_zh.md §3.1, renderer rules §9): a renderer turns a sport's scene,
+camera definitions and one world state into images. It never changes physics or the match state: it draws on its own
+copy of the model.
+
+ scene = Scene(engine="mujoco", xml=MJCF text, assets={relative path: bytes}, look=None or a presentation look)
+ a presentation scene (renderers/presentation.py, spectators only) also carries `match`, the match scene
+ it dresses: same kinematics, extra visual-only geoms (scene_check.same_kinematics)
+ cameras = [CameraDef(name, pos, lookat, up, fovy_deg, width, height), ...] (what Match.cameras(seat) returns)
+ state = {"qpos": [...], optional "mocap_pos": [...], "mocap_quat": [...]}
+ images = Renderer(scene).render(state, cameras) -> one H x W x 3 uint8 array per camera
+
+The camera model is a pinhole that every renderer must reproduce (CameraDef.project): pixel (u, v) from the image's
+top-left corner, u to the right, v down, vertical field of view fovy_deg. Only numpy is needed here; engines import
+their own libraries inside their backend packages. Never put the renderers/ directory itself on sys.path (its
+`mujoco` backend package would shadow the mujoco library); import it as the package `renderers`.
+"""
+from __future__ import annotations
+
+import math
+from abc import ABC, abstractmethod
+from dataclasses import dataclass, field
+from pathlib import Path
+
+import numpy as np
+
+
+class RendererUnavailable(RuntimeError):
+ """The renderer cannot run here; `requirements` says what it needs (GPU, image, library ...)."""
+
+ def __init__(self, name: str, why: str, requirements: str = ""):
+ super().__init__(f"renderer {name!r} unavailable: {why}" + (f" (requires: {requirements})" if requirements else ""))
+ self.name, self.why, self.requirements = name, why, requirements
+
+
+def _unit(v):
+ v = np.asarray(v, dtype=float)
+ n = np.linalg.norm(v)
+ if not np.isfinite(n) or n < 1e-12:
+ raise ValueError("degenerate camera direction")
+ return v / n
+
+
+@dataclass
+class CameraDef:
+ name: str
+ pos: tuple
+ lookat: tuple
+ up: tuple = (0.0, 0.0, 1.0)
+ fovy_deg: float = 45.0
+ width: int = 320
+ height: int = 240
+
+ def __post_init__(self):
+ self.pos = tuple(float(x) for x in self.pos)
+ self.lookat = tuple(float(x) for x in self.lookat)
+ self.up = tuple(float(x) for x in self.up)
+ self.fovy_deg, self.width, self.height = float(self.fovy_deg), int(self.width), int(self.height)
+ if len(self.pos) != 3 or len(self.lookat) != 3 or len(self.up) != 3:
+ raise ValueError("pos, lookat and up are 3-vectors")
+ if not 0 < self.fovy_deg < 180 or self.width <= 0 or self.height <= 0:
+ raise ValueError("fovy_deg in (0, 180), positive width and height")
+ self.basis() # raises on a degenerate pose
+
+ @staticmethod
+ def from_dict(d: dict) -> "CameraDef":
+ keys = ("name", "pos", "lookat", "up", "fovy_deg", "width", "height")
+ return CameraDef(**{k: d[k] for k in keys if k in d})
+
+ def to_dict(self) -> dict:
+ return {"name": self.name, "pos": list(self.pos), "lookat": list(self.lookat), "up": list(self.up),
+ "fovy_deg": self.fovy_deg, "width": self.width, "height": self.height}
+
+ def focal_px(self) -> float:
+ return (self.height / 2) / math.tan(math.radians(self.fovy_deg) / 2)
+
+ def intrinsics(self) -> dict:
+ return {"focal_px": self.focal_px(), "principal_point_px": [self.width / 2, self.height / 2],
+ "width": self.width, "height": self.height}
+
+ def basis(self):
+ """(right, up, forward) unit vectors in the world frame."""
+ fwd = _unit(np.subtract(self.lookat, self.pos))
+ right = _unit(np.cross(fwd, self.up))
+ up = np.cross(right, fwd)
+ return right, up, fwd
+
+ def project(self, point):
+ """Pixel (u, v) of a world point (u right, v down, from the top-left corner; continuous coordinates, so the
+ centre of pixel column i is u = i + 0.5). None if the point is behind the camera."""
+ right, up, fwd = self.basis()
+ d = np.subtract(point, self.pos)
+ depth = float(d @ fwd)
+ if depth <= 1e-9:
+ return None
+ f = self.focal_px()
+ return (self.width / 2 + f * float(d @ right) / depth, self.height / 2 - f * float(d @ up) / depth)
+
+ def spherical(self):
+ """(lookat, distance, azimuth_deg, elevation_deg): the free-camera form the showcase exporters use."""
+ d = np.subtract(self.lookat, self.pos)
+ dist = float(np.linalg.norm(d))
+ az = math.degrees(math.atan2(d[1], d[0]))
+ el = math.degrees(math.asin(max(-1.0, min(1.0, d[2] / dist))))
+ return list(self.lookat), dist, az, el
+
+
+@dataclass
+class Scene:
+ engine: str = "mujoco" # the physics engine whose scene format `xml` is in
+ xml: str = "" # MJCF text (engine "mujoco")
+ assets: dict = field(default_factory=dict) # {path as referenced by the xml (with meshdir/texturedir): bytes}
+ look: dict | None = None # optional presentation appearance (showcase renderers only)
+ match: "Scene | None" = None # set on a presentation scene only: the match scene it dresses
+ credits: tuple = () # presentation scene: what was added, with its source and licence
+ players: bool = False # a presentation scene the sport declares for its players' images too
+
+ @property
+ def is_presentation(self) -> bool:
+ """A presentation scene (renderers/presentation): drawn for the players' images only when `players` is set
+ (the sport declares it, renderer rule 6), else for spectators only."""
+ return self.match is not None
+
+ @staticmethod
+ def from_file(path, look=None) -> "Scene":
+ """A scene file plus every other file below its directory as an asset (paths relative to that directory)."""
+ p = Path(path)
+ assets = {str(f.relative_to(p.parent)): f.read_bytes() for f in sorted(p.parent.rglob("*"))
+ if f.is_file() and f != p and "__pycache__" not in f.parts}
+ return Scene(engine="mujoco", xml=p.read_text(), assets=assets, look=look)
+
+
+class Renderer(ABC):
+ name: str = ""
+ realtime: bool = True # fast enough for player images (still subject to the task's frame budget)
+ needs_gpu: bool = False
+ label: str | None = None # the tag a re-rendered frame carries ("re-rendered: <engine>"); None = default
+
+ def __init__(self, scene: Scene, **opts):
+ self.scene, self.opts = scene, opts
+
+ @abstractmethod
+ def render(self, state: dict, cameras: list) -> list:
+ """One H x W x 3 uint8 image per camera (CameraDef or its dict form), for the given world state."""
+
+ def close(self):
+ pass
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ self.close()
+
+
+def as_cameras(cameras) -> list:
+ return [c if isinstance(c, CameraDef) else CameraDef.from_dict(c) for c in cameras]
diff --git a/scripts/roboolympics/shared/sim/renderers/mujoco/__init__.py b/scripts/roboolympics/shared/sim/renderers/mujoco/__init__.py
new file mode 100644
index 0000000000..1f52d6a69d
--- /dev/null
+++ b/scripts/roboolympics/shared/sim/renderers/mujoco/__init__.py
@@ -0,0 +1,144 @@
+"""The default renderer: MuJoCo's own rasterizer (CPU with MUJOCO_GL=osmesa, GPU with egl), real time.
+
+The scene is compiled once from its MJCF text with spare world-body cameras added; each CameraDef is drawn by
+setting one spare camera's pose and vertical field of view exactly (cam_pos / cam_quat / cam_fovy), so the picture
+follows CameraDef.project to the pixel. The renderer keeps its own MjModel / MjData: the match's world is never
+touched. A presentation scene (Scene.match set; spectators only) is drawn only when its kinematics equal the match
+scene's (scene_check.same_kinematics); every renderer built on this one inherits the check."""
+from __future__ import annotations
+
+import numpy as np
+
+from ..base import CameraDef, Renderer, RendererUnavailable, Scene, as_cameras
+
+SPARE = "_ro_cam"
+
+
+def camera_quat(cam: CameraDef):
+ """MuJoCo camera frame: x = image right, y = image up, looking along -z."""
+ import mujoco as mj
+ right, up, fwd = cam.basis()
+ R = np.column_stack([right, up, -fwd])
+ q = np.zeros(4)
+ mj.mju_mat2Quat(q, R.reshape(-1))
+ return q
+
+
+def compile_spec(spec, n_cams: int, size):
+ """Add n spare cameras and make the off-screen buffer at least `size` (w, h); returns the compiled model."""
+ g = spec.visual.global_
+ g.offwidth, g.offheight = max(int(g.offwidth), int(size[0])), max(int(g.offheight), int(size[1]))
+ for i in range(n_cams):
+ spec.worldbody.add_camera(name=f"{SPARE}{i}", pos=[0, 0, 0], quat=[1, 0, 0, 0], fovy=45)
+ return spec.compile()
+
+
+def load_spec(scene: Scene):
+ import mujoco as mj
+ if scene.engine != "mujoco":
+ raise RendererUnavailable("mujoco", f"scene engine {scene.engine!r} is not MJCF")
+ return mj.MjSpec.from_string(scene.xml, assets=dict(scene.assets or {}))
+
+
+class MujocoRenderer(Renderer):
+ name = "mujoco"
+ title = "MuJoCo"
+ realtime = True
+ needs_gpu = False
+ label = None # the competition picture: no tag
+
+ def __init__(self, scene: Scene, n_cams: int = 8, size=(640, 480), **opts):
+ super().__init__(scene, **opts)
+ try:
+ import mujoco # noqa: F401
+ except ImportError as exc: # pragma: no cover - the sim images have it
+ raise RendererUnavailable(self.name, "the mujoco Python package is missing", "mujoco") from exc
+ self._n, self._size = int(n_cams), tuple(size)
+ self._build()
+
+ # ---------------------------------------------------------------- model
+ def make_spec(self):
+ """The MjSpec to draw (subclasses change only visual properties)."""
+ return load_spec(self.scene)
+
+ def _build(self):
+ import mujoco as mj
+ self.close()
+ self.m = compile_spec(self.make_spec(), self._n, self._size)
+ if self.scene.match is not None: # a presentation scene: same kinematics as the match scene
+ from ..scene_check import same_kinematics
+ bad = same_kinematics(compile_spec(load_spec(self.scene.match), self._n, self._size), self.m)
+ if bad:
+ raise RuntimeError(f"{self.name}: the presentation scene's kinematics differ from the match scene: "
+ f"{bad[:8]}")
+ self.d = mj.MjData(self.m)
+ self.cam_ids = [self.m.camera(f"{SPARE}{i}").id for i in range(self._n)]
+ self._r = {}
+
+ def _renderer(self, w, h):
+ import mujoco as mj
+ if (w, h) not in self._r:
+ self._r[w, h] = mj.Renderer(self.m, height=h, width=w)
+ return self._r[w, h]
+
+ def set_state(self, state: dict):
+ import mujoco as mj
+ m, d = self.m, self.d
+ q = np.asarray(state.get("qpos", d.qpos), dtype=float)
+ if q.shape != (m.nq,):
+ raise ValueError(f"state qpos has {q.size} values, the scene has nq={m.nq}")
+ d.qpos[:] = q
+ if m.nmocap:
+ if "mocap_pos" in state:
+ d.mocap_pos[:] = np.asarray(state["mocap_pos"], float).reshape(m.nmocap, 3)
+ if "mocap_quat" in state:
+ d.mocap_quat[:] = np.asarray(state["mocap_quat"], float).reshape(m.nmocap, 4)
+ mj.mj_kinematics(m, d)
+ mj.mj_comPos(m, d)
+ mj.mj_camlight(m, d)
+
+ # ---------------------------------------------------------------- drawing
+ def render(self, state: dict, cameras: list) -> list:
+ import mujoco as mj
+ cams = as_cameras(cameras)
+ w_max, h_max = max([c.width for c in cams] + [1]), max([c.height for c in cams] + [1])
+ if len(cams) > self._n or w_max > self.m.vis.global_.offwidth or h_max > self.m.vis.global_.offheight:
+ self._n = max(self._n, len(cams))
+ self._size = (max(self._size[0], w_max), max(self._size[1], h_max))
+ self._build()
+ self.set_state(state)
+ for cam, cid in zip(cams, self.cam_ids):
+ self.m.cam_pos[cid] = cam.pos
+ self.m.cam_quat[cid] = camera_quat(cam)
+ self.m.cam_fovy[cid] = cam.fovy_deg
+ mj.mj_camlight(self.m, self.d) # camera world poses from the new cam_pos / cam_quat
+ self._clip(cams)
+ out = []
+ for cam, cid in zip(cams, self.cam_ids):
+ r = self._renderer(cam.width, cam.height)
+ r.update_scene(self.d, camera=cid)
+ out.append(self.post(np.array(r.render(), dtype=np.uint8, copy=True), cam))
+ return out
+
+ def _clip(self, cams):
+ """MuJoCo clips at zfar * stat.extent: keep every geom of the current state inside every camera's far plane
+ (a small scene seen from afar, or a body far from the scene centre, would otherwise vanish). Visualization
+ only, on our own model copy."""
+ m, d = self.m, self.d
+ ext = max(float(m.stat.extent), 1e-6)
+ pts = np.asarray(d.geom_xpos) if m.ngeom else np.zeros((1, 3))
+ rb = float(np.max(m.geom_rbound)) if m.ngeom else 0.0
+ reach = max(float(np.max(np.linalg.norm(pts - np.asarray(c.pos), axis=1))) for c in cams) + rb
+ if m.vis.map.zfar * ext < 1.05 * reach:
+ m.vis.map.zfar = 1.05 * reach / ext
+
+ def post(self, img, cam):
+ return img
+
+ def close(self):
+ for r in getattr(self, "_r", {}).values():
+ r.close()
+ self._r = {}
+
+
+RENDERER = MujocoRenderer
diff --git a/scripts/roboolympics/shared/sim/renderers/presentation/LICENSE.franka_emika_panda b/scripts/roboolympics/shared/sim/renderers/presentation/LICENSE.franka_emika_panda
new file mode 100644
index 0000000000..d9a10c0d8e
--- /dev/null
+++ b/scripts/roboolympics/shared/sim/renderers/presentation/LICENSE.franka_emika_panda
@@ -0,0 +1,176 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
diff --git a/scripts/roboolympics/shared/sim/renderers/presentation/LICENSE.kuka_iiwa_14 b/scripts/roboolympics/shared/sim/renderers/presentation/LICENSE.kuka_iiwa_14
new file mode 100644
index 0000000000..d4681a468e
--- /dev/null
+++ b/scripts/roboolympics/shared/sim/renderers/presentation/LICENSE.kuka_iiwa_14
@@ -0,0 +1,31 @@
+All components of Drake are licensed under the BSD 3-Clause License
+shown below. Where noted in the source code, some portions may
+be subject to other permissive, non-viral licenses.
+
+Copyright 2012-2022 Robot Locomotion Group @ CSAIL
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+Redistributions of source code must retain the above copyright notice,
+this list of conditions and the following disclaimer. Redistributions
+in binary form must reproduce the above copyright notice, this list of
+conditions and the following disclaimer in the documentation and/or
+other materials provided with the distribution. Neither the name of
+the Massachusetts Institute of Technology nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/scripts/roboolympics/shared/sim/renderers/presentation/__init__.py b/scripts/roboolympics/shared/sim/renderers/presentation/__init__.py
new file mode 100644
index 0000000000..7c589751f7
--- /dev/null
+++ b/scripts/roboolympics/shared/sim/renderers/presentation/__init__.py
@@ -0,0 +1,326 @@
+"""Presentation scenes (docs/framework_zh.md §3.1, renderer rule 6): a sport may dress its match scene for spectators,
+e.g. draw its robot arms with a manufacturer-grade visual model instead of their collision meshes. A presentation
+scene is the match scene plus visual-only geoms on the SAME bodies; nothing that moves or collides changes
+(scene_check.same_kinematics, checked by every renderer before it draws one), so a recorded match replays and
+re-renders with identical body poses. By default it is for spectator renderers only (replay videos, re-renders,
+stills): the players' images use the match scene (core/observe.CameraWorker refuses a presentation scene).
+
+Players' images (core 0.2.9): a sport may declare `players = "<meshes>"` below; then the players' images are drawn
+from the presentation scene too, with the meshes named ("full" = the upstream files, or a level of detail of lod.json,
+e.g. "25k": decimated, a few MB, cheap on the CPU). tools/sportlib.assemble_sim then copies this directory and the
+models' files (verified by sha256, with their licences) into the simulator directory (<sim>/sport/presentation/,
+assets under assets/), so they are part of source_sha and a match needs no cache or network; `players_scene` builds
+that scene (Scene.players set: CameraWorker accepts it, after the same kinematics check), `players_model` compiles it
+for a sport that draws its own images. Changing the declaration changes the players' images: bump the sport's
+revision.
+
+Declaration: sports/<sport>/presentation/presentation.toml (outside the simulator directory: tools/sportlib.NOT_IN_SIM,
+so source_sha, the golden replays and the task directories do not change):
+
+ [presentation]
+ version = 1 # bump on any change of the dressing
+ label = "Franka Panda visual meshes (MuJoCo Menagerie)"
+ [[presentation.robot]]
+ model = "franka_emika_panda" # a model of the asset manifest (renderers/presentation/menagerie.json),
+ # or "./<path>.xml": a (self-authored) model in this directory
+ bodies = '^(?P<pre>[AB]_)?link(?P<n>[0-7])$' # scene bodies to dress (Python regex, full match) ...
+ body = "link{n}" # ... and the model body whose visual geoms each one gets
+ hide = "all" # the dressed bodies' own geoms: "all" (default) | "mesh" | "none"
+ # are hidden (moved to group 3), not removed
+ hide_bodies = '^...$' # optional: hide only in these dressed bodies (default: all of them)
+ colors = { white = [0.92, 0.5, 0.42, 1] } # optional: a model material's colour for this robot (e.g. a side colour)
+ scenes = ["sim/scene/a.xml"] # optional: the match scene files (relative to the sport directory),
+ # for spectator tools when the sport has no Sport.scene()
+ players = "25k" # optional, top level: the players' images use this scene too, with
+ # these meshes ("full" or a level of lod.json); absent = spectators only
+
+The model's visual geoms (contype = conaffinity = 0, group 0..2) are copied, with their meshes, materials and poses
+in the body frame, onto each matching scene body; a body whose parent is dressed too must sit in its parent's frame
+exactly as the model's does (else the declaration names the wrong bodies and dressing fails). The models' files come
+from the asset cache (renderers/presentation/assets.py: pinned commit, sha256 per file; `python3 -m
+renderers.presentation.assets fetch`), never from the repository.
+
+ from renderers.presentation import for_plugin
+ scene = for_plugin("sports/tabletennis/plugin.py", match_scene) # None if the sport declares no presentation
+"""
+from __future__ import annotations
+
+import os
+import re
+import xml.etree.ElementTree as ET
+from pathlib import Path
+
+import numpy as np
+
+from ..base import Scene
+from ..scene_check import VISUAL_PREFIX
+
+DECL = "presentation.toml"
+BUNDLE = "assets" # <sim>/sport/presentation/assets: the models' files bundled into a simulator
+CLASS = "ro_presentation" # the default class of the added geoms (inherits nothing from a robot's childclass)
+HIDDEN_GROUP = "3" # renderers draw groups 0..2; the dressed bodies' own geoms move here
+FRAME_TOL = 1e-6
+
+
+class PresentationUnavailable(RuntimeError):
+ """The sport declares a presentation scene that cannot be built here (e.g. the model assets are not fetched)."""
+
+
+def match_scenes(sport_dir: str | os.PathLike) -> list:
+ """The match scene files a presentation declares (`scenes`), as Scenes; [] if none."""
+ d = Path(sport_dir) / "presentation"
+ if not declared(d):
+ return []
+ return [Scene.from_file(Path(sport_dir) / f) for f in load_decl(d).get("scenes", [])]
+
+
+def directory(plugin: str | os.PathLike) -> Path:
+ return Path(plugin).resolve().parent / "presentation"
+
+
+def declared(d: str | os.PathLike) -> bool:
+ return (Path(d) / DECL).is_file()
+
+
+def load_decl(d: str | os.PathLike) -> dict:
+ import tomllib
+ p = (tomllib.loads((Path(d) / DECL).read_text()).get("presentation") or {})
+ if int(p.get("version", 0)) < 1 or not p.get("robot"):
+ raise ValueError(f"{Path(d) / DECL}: [presentation] needs version >= 1 and at least one [[presentation.robot]]")
+ for r in p["robot"]:
+ for k in ("model", "bodies", "body"):
+ if k not in r:
+ raise ValueError(f"{Path(d) / DECL}: a [[presentation.robot]] needs {k!r}")
+ if r.get("hide", "all") not in ("all", "mesh", "none"):
+ raise ValueError(f"{Path(d) / DECL}: hide is all | mesh | none")
+ pl = p.get("players")
+ if pl is not None and (not isinstance(pl, str) or not (pl == "full" or re.fullmatch(r"\d+k", pl))):
+ raise ValueError(f"{Path(d) / DECL}: players is \"full\" or a level of detail like \"25k\"")
+ return p
+
+
+def players_meshes(d: str | os.PathLike) -> str | None:
+ """The meshes the players' images use ("full" or a level of detail), None = spectators only (the default)."""
+ return load_decl(d).get("players") if declared(d) else None
+
+
+def players_scene(sport_dir: str | os.PathLike, match: Scene) -> Scene:
+ """The scene of the players' images: the presentation scene of `sport_dir` (the sport's directory, or the
+ simulator's sport/) when it declares `players`, else `match` itself."""
+ d = Path(sport_dir) / "presentation"
+ meshes = players_meshes(d)
+ return match if meshes is None else dress(match, d, meshes=meshes, players=True)
+
+
+def players_model(sport_dir: str | os.PathLike, match: Scene):
+ """For a sport that draws its own images: the compiled MjModel of the players' scene, after the same kinematics
+ check against the match scene; None when the sport does not declare `players` (draw the match model)."""
+ sc = players_scene(sport_dir, match)
+ if sc is match:
+ return None
+ import mujoco as mj
+ from ..scene_check import same_kinematics
+ m = mj.MjSpec.from_string(sc.xml, assets=dict(sc.assets or {})).compile()
+ bad = same_kinematics(mj.MjSpec.from_string(match.xml, assets=dict(match.assets or {})).compile(), m)
+ if bad:
+ raise RuntimeError(f"the players' presentation scene's kinematics differ from the match scene: {bad[:8]}")
+ return m
+
+
+def for_plugin(plugin, match: Scene) -> Scene | None:
+ """The presentation scene of the sport whose plugin is `plugin`, dressing `match` (the sport's scene for the same
+ configuration); None when the sport declares none. Raises PresentationUnavailable when it cannot be built. Inside a
+ simulator directory (a bundle, players' presentation) it is the players' scene."""
+ d = directory(plugin)
+ if not declared(d):
+ return None
+ meshes = players_meshes(d)
+ if meshes is not None and (d / BUNDLE).is_dir(): # inside a simulator: only the players' meshes are bundled
+ return dress(match, d, meshes=meshes, players=True)
+ return dress(match, d)
+
+
+# ------------------------------------------------------------------------------------------------ robot models
+def _f(v) -> str:
+ return " ".join(repr(float(x)) for x in np.asarray(v, float).reshape(-1))
+
+
+def _unitq(q):
+ q = np.asarray(q, float)
+ return q / np.linalg.norm(q)
+
+
+def model_parts(xml_path: str | os.PathLike) -> dict:
+ """The visual model of a robot description (parsed by MuJoCo's MJCF parser, nothing compiled or executed):
+ {"bodies": {name: {"parent", "pos", "quat", "geoms": [{"mesh", "material", "rgba", "pos", "quat"}]}},
+ "meshes": {name: {"file" (relative to the description's directory), "scale", "refpos", "refquat"}},
+ "materials": {name: {"rgba", "specular", "shininess", "reflectance", "emission"}}}"""
+ import mujoco as mj
+ xml_path = Path(xml_path)
+ spec = mj.MjSpec.from_file(str(xml_path))
+ meshdir = spec.meshdir or ""
+ meshes = {}
+ for me in spec.meshes:
+ if not me.file:
+ raise ValueError(f"{xml_path.name}: mesh {me.name!r} has no file (only file meshes are supported)")
+ name = me.name or Path(me.file).stem
+ meshes[name] = {"file": os.path.normpath(os.path.join(meshdir, me.file)), "scale": list(me.scale),
+ "refpos": list(me.refpos), "refquat": list(me.refquat)}
+ materials = {mt.name: {"rgba": list(mt.rgba), "specular": float(mt.specular), "shininess": float(mt.shininess),
+ "reflectance": float(mt.reflectance), "emission": float(mt.emission)}
+ for mt in spec.materials}
+ bodies, used = {}, set()
+ for b in spec.bodies:
+ if not b.name or b.name == "world":
+ continue
+ if b.alt.type != mj.mjtOrientation.mjORIENTATION_QUAT:
+ raise ValueError(f"{xml_path.name}: body {b.name} uses an alternative orientation")
+ geoms = []
+ for g in b.geoms:
+ if g.type != mj.mjtGeom.mjGEOM_MESH or g.contype or g.conaffinity or not 0 <= g.group <= 2:
+ continue
+ if g.alt.type != mj.mjtOrientation.mjORIENTATION_QUAT:
+ raise ValueError(f"{xml_path.name}: a visual geom of {b.name} uses an alternative orientation")
+ geoms.append({"mesh": g.meshname, "material": g.material or None, "rgba": list(g.rgba),
+ "pos": list(g.pos), "quat": list(g.quat)})
+ used.add(g.meshname)
+ if g.material:
+ used.add(("mat", g.material))
+ bodies[b.name] = {"parent": b.parent.name if b.parent is not None else "world", "pos": list(b.pos),
+ "quat": list(b.quat), "geoms": geoms}
+ return {"bodies": bodies, "meshes": {n: v for n, v in meshes.items() if n in used},
+ "materials": {n: v for n, v in materials.items() if ("mat", n) in used}}
+
+
+# ------------------------------------------------------------------------------------------------ dressing
+def _meshdir(root) -> str:
+ c = root.find("compiler")
+ if c is None:
+ return ""
+ return c.get("meshdir") or c.get("assetdir") or ""
+
+
+def _asset_key(meshdir: str, file: str) -> str:
+ return os.path.normpath(os.path.join(meshdir, file)) if meshdir else file
+
+
+def _local_frame(el) -> tuple:
+ pos = np.array([float(x) for x in el.get("pos", "0 0 0").split()])
+ if any(el.get(a) is not None for a in ("euler", "axisangle", "xyaxes", "zaxis")):
+ return pos, None
+ return pos, _unitq([float(x) for x in el.get("quat", "1 0 0 0").split()])
+
+
+def dress(match: Scene, d: str | os.PathLike, meshes: str = "full", players: bool = False) -> Scene:
+ """The presentation scene declared in directory `d` for the match scene `match` (see the module docstring), the
+ models with `meshes` ("full" or a level of detail); players: the scene of the players' images (Scene.players).
+ The models' files come from `d`/assets when it exists (a simulator's bundle), else from the cache / lod/."""
+ from . import assets
+ if match.engine != "mujoco":
+ raise PresentationUnavailable(f"presentation scenes need an MJCF scene, not {match.engine!r}")
+ decl = load_decl(d)
+ if players and decl.get("players") is None:
+ raise ValueError(f"{Path(d) / DECL}: the players' images use a presentation scene only when it declares players")
+ bundled = Path(d) / BUNDLE
+ bundle_root = bundled if bundled.is_dir() else None
+ root = ET.fromstring(match.xml)
+ meshdir = _meshdir(root)
+ out_assets = dict(match.assets or {})
+ asset_el = root.find("asset")
+ if asset_el is None:
+ asset_el = ET.Element("asset")
+ root.insert(0, asset_el)
+ default = root.find("default")
+ if default is None:
+ default = ET.Element("default")
+ root.insert(0, default)
+ cls = ET.SubElement(default, "default", {"class": CLASS})
+ ET.SubElement(cls, "geom", {"type": "mesh", "contype": "0", "conaffinity": "0", "group": "2", "mass": "0",
+ "density": "0", "rgba": "0.5 0.5 0.5 1"})
+ parents = {c: p for p in root.iter() for c in p}
+ bodies = {b.get("name"): b for b in root.iter("body") if b.get("name")}
+ credits, n_added, dressed_all, meshes_added = [], 0, set(), set()
+ for ri, rob in enumerate(decl["robot"]):
+ if rob["model"].startswith("./"): # a model shipped in the presentation directory itself
+ xml_file = (Path(d) / rob["model"]).resolve()
+ if Path(d).resolve() not in xml_file.parents:
+ raise ValueError(f"{DECL}: a local model must lie inside the presentation directory")
+ credit = rob.get("credit", f"{rob['model']} (shipped with the sport)")
+ else:
+ xml_file, credit = assets.model_xml(rob["model"], meshes, bundle_root), assets.credit(rob["model"])
+ if meshes != "full":
+ credit += f", visual meshes decimated to level {meshes} (renderers/presentation/lod.json)"
+ parts = model_parts(xml_file)
+ tag = re.sub(r"[^A-Za-z0-9_]", "_", rob["model"])
+ pat = re.compile(rob["bodies"])
+ dressed = {}
+ for name, el in bodies.items():
+ mt = pat.fullmatch(name)
+ if not mt:
+ continue
+ mbody = rob["body"].format(**{k: v or "" for k, v in mt.groupdict().items()})
+ if mbody not in parts["bodies"]:
+ raise ValueError(f"{DECL}: scene body {name} -> {mbody}, which {rob['model']} does not have")
+ dressed[name] = mbody
+ if not dressed:
+ raise ValueError(f"{DECL}: no scene body matches {rob['bodies']!r}")
+ if dressed.keys() & dressed_all:
+ raise ValueError(f"{DECL}: bodies dressed twice: {sorted(dressed.keys() & dressed_all)}")
+ dressed_all |= dressed.keys()
+ for name, mbody in dressed.items(): # the declaration must name bodies in the model's frames
+ par = parents.get(bodies[name])
+ pname = par.get("name") if par is not None and par.tag == "body" else None
+ if pname in dressed and dressed[pname] == parts["bodies"][mbody]["parent"]:
+ pos, quat = _local_frame(bodies[name])
+ mb = parts["bodies"][mbody]
+ if quat is None or np.abs(pos - mb["pos"]).max() > FRAME_TOL or min(
+ np.abs(quat - _unitq(mb["quat"])).max(), np.abs(quat + _unitq(mb["quat"])).max()) > FRAME_TOL:
+ raise ValueError(f"{DECL}: scene body {name} does not sit in its parent's frame as "
+ f"{rob['model']}'s {mbody} does")
+ # assets: the model's meshes and materials, once per robot entry
+ colors = rob.get("colors", {})
+ if set(colors) - set(parts["materials"]) or any(len(v) != 4 for v in colors.values()):
+ raise ValueError(f"{DECL}: colors names materials of {rob['model']} ({sorted(parts['materials'])}), "
+ "each an rgba of 4 numbers")
+ for mname, mat in parts["materials"].items():
+ ET.SubElement(asset_el, "material", {"name": f"ro_{tag}_{ri}_{mname}",
+ "rgba": _f(colors.get(mname, mat["rgba"])),
+ "specular": repr(mat["specular"]),
+ "shininess": repr(mat["shininess"]),
+ "reflectance": repr(mat["reflectance"]),
+ "emission": repr(mat["emission"])})
+ for mname, me in parts["meshes"].items(): # meshes once per model, materials per robot entry
+ if f"ro_{tag}_{mname}" in meshes_added:
+ continue
+ meshes_added.add(f"ro_{tag}_{mname}")
+ rel = f"ro_presentation/{tag}/{me['file']}"
+ attrs = {"name": f"ro_{tag}_{mname}", "file": rel, "scale": _f(me["scale"])}
+ if np.any(np.asarray(me["refpos"]) != 0) or np.any(np.asarray(me["refquat"]) != [1, 0, 0, 0]):
+ attrs.update(refpos=_f(me["refpos"]), refquat=_f(me["refquat"]))
+ ET.SubElement(asset_el, "mesh", attrs)
+ out_assets[_asset_key(meshdir, rel)] = (xml_file.parent / me["file"]).read_bytes()
+ hide = rob.get("hide", "all")
+ hide_pat = re.compile(rob["hide_bodies"]) if rob.get("hide_bodies") else None
+ for name, mbody in dressed.items():
+ body = bodies[name]
+ if hide != "none" and (hide_pat is None or hide_pat.fullmatch(name)):
+ for g in body.findall("geom"):
+ if hide == "all" or g.get("type") == "mesh" or (g.get("mesh") and g.get("type") is None):
+ g.set("group", HIDDEN_GROUP)
+ kids = list(body)
+ at = max([i for i, e in enumerate(kids) if e.tag in ("geom", "inertial", "joint", "freejoint")] + [-1]) + 1
+ for j, g in enumerate(parts["bodies"][mbody]["geoms"]):
+ attrs = {"name": f"{VISUAL_PREFIX}{name}:{j}", "class": CLASS, "mesh": f"ro_{tag}_{g['mesh']}",
+ "pos": _f(g["pos"]), "quat": _f(g["quat"])}
+ if g["material"]:
+ attrs["material"] = f"ro_{tag}_{ri}_{g['material']}"
+ elif not np.allclose(g["rgba"], [0.5, 0.5, 0.5, 1]):
+ attrs["rgba"] = _f(g["rgba"])
+ body.insert(at + j, ET.Element("geom", attrs))
+ n_added += 1
+ credits.append(credit)
+ xml = ET.tostring(root, encoding="unicode")
+ return Scene(engine=match.engine, xml=xml, assets=out_assets, look=match.look, match=match, players=players,
+ credits=tuple(credits) + (f"{decl.get('label', 'presentation scene')} (v{decl['version']}, "
+ f"{n_added} visual geoms" + (", the players' images" if players else "")
+ + ")",))
diff --git a/scripts/roboolympics/shared/sim/renderers/presentation/assets.py b/scripts/roboolympics/shared/sim/renderers/presentation/assets.py
new file mode 100644
index 0000000000..14edb00e1d
--- /dev/null
+++ b/scripts/roboolympics/shared/sim/renderers/presentation/assets.py
@@ -0,0 +1,198 @@
+"""Third-party model files of the presentation scenes, fetched at build time (never committed): every file is pinned
+to one upstream commit and checked against its sha256 in the manifest (menagerie.json, next to this file). The files
+are untrusted data: they are only read (MJCF parsed, meshes loaded by MuJoCo), never executed. Their licences are
+kept next to the manifest (LICENSE.<model>) and credited in NOTICE.
+
+ python3 -m renderers.presentation.assets fetch [MODEL ...] download the missing files (all models by default)
+ python3 -m renderers.presentation.assets verify [MODEL ...] check what is in the cache
+ python3 -m renderers.presentation.assets where print the cache directory
+
+The cache: $RO_ASSET_CACHE, else <repo>/.cache/assets (git-ignored); files at <cache>/<source>/<commit>/<path>.
+Standard library only (python >= 3.8), so the fetch runs on any host; the renderers read the cache inside the image.
+
+Levels of detail (players' images, renderer rule 6): lod.json lists decimated copies of a model's visual meshes
+(renderers/presentation/lod/<level>/<path>, committed: small, derived from the pinned files, licence unchanged; made by
+lod.py), each file pinned by sha256 like the upstream ones. `meshes` = "full" (the upstream files) or a level ("25k").
+A sport whose players' images use its presentation scene gets the model's files bundled into its simulator directory
+(`bundle`, tools/sportlib.assemble_sim): <sim>/sport/presentation/assets/<path>, checked against the same manifests,
+so a match needs neither the cache nor the network.
+"""
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import sys
+import urllib.request
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+MANIFESTS = ("menagerie.json",)
+LOD_MANIFEST = "lod.json"
+FULL = "full"
+_verified: set = set()
+
+
+class _Unavailable(RuntimeError):
+ pass
+
+
+def _err(msg):
+ try:
+ from . import PresentationUnavailable
+ except ImportError: # pragma: no cover - run as a script on a host without numpy
+ return _Unavailable(msg)
+ return PresentationUnavailable(msg)
+
+
+def manifests() -> list:
+ return [json.loads((HERE / m).read_text()) for m in MANIFESTS]
+
+
+def _find(name: str):
+ for man in manifests():
+ if name in man["models"]:
+ return man, man["models"][name]
+ raise KeyError(f"no presentation model {name!r} in {', '.join(MANIFESTS)}")
+
+
+def cache_root() -> Path:
+ env = os.environ.get("RO_ASSET_CACHE")
+ return Path(env) if env else HERE.parents[1] / ".cache" / "assets"
+
+
+def _base(man) -> Path:
+ return cache_root() / man["name"] / man["commit"]
+
+
+def _sha(p: Path) -> str:
+ h = hashlib.sha256()
+ with open(p, "rb") as f:
+ for chunk in iter(lambda: f.read(1 << 20), b""):
+ h.update(chunk)
+ return h.hexdigest()
+
+
+def lods() -> dict:
+ """lod.json: {"models": {model: {level: {"files": {path: sha256}, ...}}}, ...} ({} if absent)."""
+ p = HERE / LOD_MANIFEST
+ return json.loads(p.read_text()) if p.is_file() else {}
+
+
+def files(name: str, meshes: str = FULL) -> dict:
+ """{path: sha256} of model `name` with the given meshes ("full" or a level of lod.json)."""
+ man, mod = _find(name)
+ if meshes == FULL:
+ return dict(mod["files"])
+ lev = (lods().get("models", {}).get(name) or {}).get(meshes)
+ if lev is None:
+ raise KeyError(f"no level of detail {meshes!r} of {name} in {LOD_MANIFEST}")
+ return dict(lev["files"])
+
+
+def source_dir(name: str, meshes: str = FULL) -> Path:
+ """Where the files of `name` with `meshes` live on this checkout: the cache (full) or renderers/presentation/lod."""
+ man, _ = _find(name)
+ return _base(man) if meshes == FULL else lod_root() / meshes
+
+
+def lod_root() -> Path:
+ """The levels of detail: $RO_LOD_DIR (robot_coding_bench: the eai-olympiad image ships them at
+ /opt/roboolympics/lod, verified here against lod.json), else renderers/presentation/lod."""
+ env = os.environ.get("RO_LOD_DIR")
+ return Path(env) if env else HERE / "lod"
+
+
+def missing(name: str, meshes: str = FULL, root: Path | None = None) -> list:
+ """The files of model `name` that are absent (from `root`, default its source_dir) or do not match their sha256."""
+ base = Path(root) if root is not None else source_dir(name, meshes)
+ return [p for p, sha in files(name, meshes).items() if not (base / p).is_file() or _sha(base / p) != sha]
+
+
+def model_xml(name: str, meshes: str = FULL, root: Path | None = None) -> Path:
+ """The model's MJCF file, all its files verified (once per process): from `root` (a simulator's bundle) if given,
+ else from the cache (full meshes) or renderers/presentation/lod (a level of detail)."""
+ _, mod = _find(name)
+ base = Path(root) if root is not None else source_dir(name, meshes)
+ key = (name, meshes, str(base))
+ if key not in _verified:
+ bad = missing(name, meshes, base)
+ if bad:
+ how = (f"python3 -m renderers.presentation.assets fetch {name}" if meshes == FULL and root is None
+ else "regenerate the task (tools/generate.py)" if root is not None
+ else f"python3 -m renderers.presentation.lod build {name} {meshes}")
+ raise _err(f"presentation model {name} ({meshes} meshes): {len(bad)} of {len(files(name, meshes))} files "
+ f"missing or not matching their sha256 in {base} ({how})")
+ _verified.add(key)
+ return base / mod["xml"]
+
+
+def bundle(name: str, meshes: str, dst: Path) -> list:
+ """Copy model `name` with `meshes` (verified) and its licence into the directory `dst` (a simulator's
+ sport/presentation/assets): returns the paths written, relative to dst."""
+ import shutil
+ _, mod = _find(name)
+ src = source_dir(name, meshes)
+ model_xml(name, meshes) # verifies every file
+ out = []
+ for p in sorted(files(name, meshes)):
+ (Path(dst) / p).parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(src / p, Path(dst) / p)
+ out.append(p)
+ lic = mod["license_file"]
+ shutil.copyfile(HERE / lic, Path(dst) / lic)
+ return out + [lic]
+
+
+def credit(name: str) -> str:
+ man, mod = _find(name)
+ return (f"{mod['title']}: {man['title']} ({man['source']}, commit {man['commit'][:12]}, {mod['path']}), "
+ f"{mod['copyright']}, {mod['license']} (renderers/presentation/{mod['license_file']})")
+
+
+def fetch(name: str, log=print) -> int:
+ man, mod = _find(name)
+ base = _base(man)
+ n = 0
+ for p, sha in sorted(mod["files"].items()):
+ dst = base / p
+ if dst.is_file() and _sha(dst) == sha:
+ continue
+ url = man["url"].format(commit=man["commit"], path=p)
+ dst.parent.mkdir(parents=True, exist_ok=True)
+ tmp = dst.with_name(dst.name + ".part")
+ with urllib.request.urlopen(url, timeout=60) as r, open(tmp, "wb") as f:
+ f.write(r.read())
+ got = _sha(tmp)
+ if got != sha:
+ tmp.unlink()
+ raise _err(f"{url}: sha256 {got} != {sha} (manifest); nothing kept")
+ tmp.replace(dst)
+ n += 1
+ log(f"{name}: {len(mod['files'])} files in {base} ({n} downloaded)")
+ return n
+
+
+def main(argv) -> int:
+ cmd, names = (argv[0] if argv else "verify"), argv[1:]
+ if cmd == "where":
+ print(cache_root())
+ return 0
+ names = names or [n for man in manifests() for n in man["models"]]
+ rc = 0
+ for n in names:
+ if cmd == "fetch":
+ fetch(n)
+ elif cmd == "verify":
+ for meshes in [FULL] + sorted(lods().get("models", {}).get(n, {})):
+ bad = missing(n, meshes)
+ print(f"{n} ({meshes}): " + ("ok" if not bad else f"{len(bad)} files missing or changed"))
+ rc |= bool(bad)
+ else:
+ print(__doc__)
+ return 2
+ return rc
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/scripts/roboolympics/shared/sim/renderers/presentation/lod.json b/scripts/roboolympics/shared/sim/renderers/presentation/lod.json
new file mode 100644
index 0000000000..d1eb0f5fcf
--- /dev/null
+++ b/scripts/roboolympics/shared/sim/renderers/presentation/lod.json
@@ -0,0 +1,94 @@
+{
+ "models": {
+ "franka_emika_panda": {
+ "25k": {
+ "files": {
+ "franka_emika_panda/assets/link0_0.obj": "0e6958fd2f69a9c6ec82e59fb3a39689810bcd69180dd865866359b69d0204ba",
+ "franka_emika_panda/assets/link0_1.obj": "5ca2ade591ead9e9d3046468f6d861631b8fcd0434cb6dfbfbc7eb09cbc11c81",
+ "franka_emika_panda/assets/link0_10.obj": "c8daf1be7a5d3d89aa3f0976c6c43afa9d5841697c0ed91edcad8d60a75b1e60",
+ "franka_emika_panda/assets/link0_11.obj": "0ced2c2a707b13a391306d04f9ad9d4318caf2ce924cb242321a1cd9773c3753",
+ "franka_emika_panda/assets/link0_2.obj": "d7d11c50dee70b7d9149805576c85e026d3f4df2df1b824891451f72bce20e1d",
+ "franka_emika_panda/assets/link0_3.obj": "35bad1cdde8a1e6cee4522b22aa4e46d6a06a54bccc3bc966691f96cde0953fa",
+ "franka_emika_panda/assets/link0_4.obj": "ee1d81feeb6591b8a0b4d0e175f7541ffa40725aa6b97d048d289dc5c5517913",
+ "franka_emika_panda/assets/link0_5.obj": "17438838e57292cdc0c18f5417c020ed3290323e50ca4c1b58b07065961bc95c",
+ "franka_emika_panda/assets/link0_7.obj": "2ccf52f5c8b6155fd2764435028b59ad64d23820bb080d9079ba52b939ccee36",
+ "franka_emika_panda/assets/link0_8.obj": "7f895de6ec3ebdd93f5af7c446616da908cf423131dc2c24da50146b32718baa",
+ "franka_emika_panda/assets/link0_9.obj": "8ef4ff7f0676b60a8edf54380b4b696bae3b5a5202e38f7ca64bb3a2f6e0496b",
+ "franka_emika_panda/assets/link1.obj": "89a7387d65a311e92cd39dc65c0f5a7d00a5d342bf670613b87b09da016a82c8",
+ "franka_emika_panda/assets/link2.obj": "b66faa46466a258f1f36250bf4530424eb37b47ae1fcc4dbb114b37a499287a2",
+ "franka_emika_panda/assets/link3_0.obj": "b6124b7a17d85ce218ed739ae1792c4762718e43f135e3633008bc753aebe20f",
+ "franka_emika_panda/assets/link3_1.obj": "6d05236a2bb84117328a7d421f41058ddd9969d5317a5c5a5375da311dc17f30",
+ "franka_emika_panda/assets/link3_2.obj": "4d3f6753c0aa9469486317d5eee5e2ac8b1615b705a78e35335a298a4644cd03",
+ "franka_emika_panda/assets/link3_3.obj": "5afeb0a5722704920fe3930fd56fa30dde7faf1932377e9b5fbaafbf1b6f5030",
+ "franka_emika_panda/assets/link4_0.obj": "ef4c8095c339dbf8e10e727f5361598220833689cd79ac59d10508423934fc93",
+ "franka_emika_panda/assets/link4_1.obj": "7050225b33d23afafac7f597b250e59c7353e3193ecb1098c3708f2f4d561e52",
+ "franka_emika_panda/assets/link4_2.obj": "e084c51cdddb612869d45ae94e31b19a1d011f9c182faff07b1f953ca9e7e6c1",
+ "franka_emika_panda/assets/link4_3.obj": "c5ef5783e41d161269018a4b16446db8e400eb7780527a161e62bf7ed2289e46",
+ "franka_emika_panda/assets/link5_0.obj": "f64a7b7f023bdcaf8d8fac082145d365751c69e9b6bda942c5de3dd3dc8806a4",
+ "franka_emika_panda/assets/link5_1.obj": "8bfc7df033b58c4e7b5f1080dc05da81699ffc237a91b8da9e2a6119cb79b494",
+ "franka_emika_panda/assets/link5_2.obj": "437ee6f13c4d98db88ad75d832aa6bdcb5453db256d5691be1931c4acd935bf9",
+ "franka_emika_panda/assets/link6_0.obj": "9c87e9689cfeacb6b1d2ce305cddcbad463f420584dbd220b2080e3c636b3762",
+ "franka_emika_panda/assets/link6_1.obj": "6445e25a8759385c43f0d5285d50f77eb08f34afe6fbb2d07ddf352c8b3d13b5",
+ "franka_emika_panda/assets/link6_10.obj": "05ec79c4defd0548107dc58f2d7ab26b010a2ca7b7878ed0b282a3540679f620",
+ "franka_emika_panda/assets/link6_11.obj": "96dc648b3382a4b3688d801bb94eb3b6cb1d6e64367e8cae29d2a7c3178324c3",
+ "franka_emika_panda/assets/link6_12.obj": "7b2bea2a736a63661cdae29ef30740a26d08ce43c4a787788907d44d2853413e",
+ "franka_emika_panda/assets/link6_13.obj": "5f6745688f8c3a4172af1689d6a52f320264104414853e72c5a022bdaac77026",
+ "franka_emika_panda/assets/link6_14.obj": "569977e1c13942d0aa84ba42188f5256de447266e1db2e0f46159482791acbc5",
+ "franka_emika_panda/assets/link6_15.obj": "3d201820c51a032ee1e12232b5cb709b20062b8a991d6446a225f6aa8471e486",
+ "franka_emika_panda/assets/link6_16.obj": "ad4f0e691598a70ef3de25b8840d8893b48150dcbb6012a7295cbe706e8de05c",
+ "franka_emika_panda/assets/link6_2.obj": "b6bc873ba1bcbf54af2667d197722f681d82f591173cecb75cad0a67e2b47e3d",
+ "franka_emika_panda/assets/link6_3.obj": "9da48c192b317dde105666470c4898e0ca6ae54cd57f386867de76f3e75f8116",
+ "franka_emika_panda/assets/link6_4.obj": "ed80f9d8e9da1c3252cc375704f80bec5b8263198178db9a4fca72587d9525d2",
+ "franka_emika_panda/assets/link6_5.obj": "68eba154d3031354e6682dea960993b668ce3229fde73d1aaf9456e2978be95e",
+ "franka_emika_panda/assets/link6_6.obj": "c8316be35257df937810664619b67b45820b60dcbd0b219fe7e540bc12e81156",
+ "franka_emika_panda/assets/link6_7.obj": "6bc1c0ce40b6fbf22d37000ffe95255c044a168cd5241a5c56e86bdf5c171f92",
+ "franka_emika_panda/assets/link6_8.obj": "d821b8c3875eca9ad19aa6112a86eb2a0cc0d75ad07349d004c449e85eb00f14",
+ "franka_emika_panda/assets/link6_9.obj": "bd9beb29cdef7b5c6014529f65520245fa83bd8b84c0b57288a9235da2fc94c5",
+ "franka_emika_panda/assets/link7_0.obj": "16a21aac2faf5c012b1b2b2aac5c6170f78caba505a0885fed7c14b3a672899b",
+ "franka_emika_panda/assets/link7_1.obj": "7f5391b3b7104189b38c65d10a8fe213ef6d6443dc05ea7c2c6d7b31fb483ff9",
+ "franka_emika_panda/assets/link7_2.obj": "16e8c340cc6f3c9d2f15760f58892e15d0e668b09b81088a39b3a77929de0721",
+ "franka_emika_panda/assets/link7_3.obj": "47795dd7fc1d3d253313b7b39f94e06036169b3380b2d7486fb51ce53916e04d",
+ "franka_emika_panda/assets/link7_4.obj": "8c3614d6cf07660c5cbfa12edae41bd22a49d4bec9f9c4a2139a00607d1e8f63",
+ "franka_emika_panda/assets/link7_5.obj": "23e7ba2a16fca00e48b6e397d6da49b25af4e5327c6b186217aedcc808f0892f",
+ "franka_emika_panda/assets/link7_6.obj": "40e6a822ade171dcb2ecc6d5d510c9b878505e2af3b497f7e772605fdf2b9c2b",
+ "franka_emika_panda/assets/link7_7.obj": "d70d61a09b7a605a47caf5d5b7225f3d5cce1af1c849b262ab9ea0242c50464b",
+ "franka_emika_panda/panda_nohand.xml": "e7090a5e2384b18a223ef532d98bf914f7f9a6b74dc8bc9f74c8291201074071"
+ },
+ "source": "menagerie@f054586a8e90465d49ee5be15335c4a0c7f57caf",
+ "source_triangles": 126562,
+ "target_triangles": 25000,
+ "triangles": 25568
+ }
+ },
+ "kuka_iiwa_14": {
+ "25k": {
+ "files": {
+ "kuka_iiwa_14/assets/band.obj": "40784c36ec38f8ff2fa804e3c242656b9ed3ae41a33785af33c917de1bbd566f",
+ "kuka_iiwa_14/assets/kuka.obj": "b79762633220dcfae4b45b40d2880a83128e373003f794f0d9a19f4989c92ec7",
+ "kuka_iiwa_14/assets/link_0.obj": "fc2590b0e7ce20e1fa9a5ab4f48259908508c6ad4aeebc4d2ef13e5d22ba23e5",
+ "kuka_iiwa_14/assets/link_1.obj": "81f65e2f348ac6bfdd4968a1440406c9abc9ca6b51de7a404024a08ef46127eb",
+ "kuka_iiwa_14/assets/link_2_grey.obj": "07bc12ae4e6edc159e4123e9a5571a08d03211de8afa503c9cfb74dff51208b2",
+ "kuka_iiwa_14/assets/link_2_orange.obj": "4b151e4dc5689342ad6be614c9114ab3c0668a1aaba25eafc78c8e2e9f7a01f8",
+ "kuka_iiwa_14/assets/link_3.obj": "77be645b049e35bfb1c2bf05d610c95044b39dc17209b4d5e63ded1e4b87832d",
+ "kuka_iiwa_14/assets/link_4_grey.obj": "79f6693b2031e1f24069c56546490d7d1ff6907b3871bd049bba187d4ff0786a",
+ "kuka_iiwa_14/assets/link_4_orange.obj": "2e0613541153884f9a3cc2de654492d7aa563368c6fae335c82109b5def79f4d",
+ "kuka_iiwa_14/assets/link_5.obj": "2f0ee7aeb51dfa86f98954f8673fafdb8c63dfa37618d4e0e76c7db037af267c",
+ "kuka_iiwa_14/assets/link_6_grey.obj": "4eb7481b31d88612b6cc791d8390c3145e367ca87537a2f6763e3c2c2b01dd13",
+ "kuka_iiwa_14/assets/link_6_orange.obj": "450b41e8691e1ccfa427da45d65d4f95c40cd388433fc753c1ab86087d178cdc",
+ "kuka_iiwa_14/assets/link_7.obj": "c35ef794a848268745f3d1e283dbcdb0bf117373110364b62c8405af4275eac1",
+ "kuka_iiwa_14/iiwa14.xml": "ee7e6d796a9f8642de6097f95077281d15f43678dc5285beafeda99b84cf9ef5"
+ },
+ "source": "menagerie@f054586a8e90465d49ee5be15335c4a0c7f57caf",
+ "source_triangles": 73989,
+ "target_triangles": 25000,
+ "triangles": 25141
+ }
+ }
+ },
+ "name": "lod",
+ "note": "Levels of detail of the presentation models (players' images, renderer rule 6): a model's visual meshes decimated to a triangle budget, so that a sport can draw its players' images with fine meshes on the CPU at a small cost and bundle them into its simulator directory (a few MB instead of 30).",
+ "tools": {
+ "fast-simplification": "0.2.0",
+ "trimesh": "5.1.1"
+ }
+}
diff --git a/scripts/roboolympics/shared/sim/renderers/presentation/menagerie.json b/scripts/roboolympics/shared/sim/renderers/presentation/menagerie.json
new file mode 100644
index 0000000000..f20f9bb91f
--- /dev/null
+++ b/scripts/roboolympics/shared/sim/renderers/presentation/menagerie.json
@@ -0,0 +1,135 @@
+{
+ "name": "menagerie",
+ "title": "MuJoCo Menagerie",
+ "source": "https://github.com/google-deepmind/mujoco_menagerie",
+ "commit": "f054586a8e90465d49ee5be15335c4a0c7f57caf",
+ "url": "https://raw.githubusercontent.com/google-deepmind/mujoco_menagerie/{commit}/{path}",
+ "note": "Generated from the pinned commit: per model its MJCF description and the visual meshes of its visual geoms (no collision meshes, textures or scripts). Untrusted data: read only.",
+ "models": {
+ "franka_emika_panda": {
+ "title": "Franka Emika Panda (no hand)",
+ "path": "franka_emika_panda/",
+ "xml": "franka_emika_panda/panda_nohand.xml",
+ "license": "Apache-2.0",
+ "license_file": "LICENSE.franka_emika_panda",
+ "copyright": "MuJoCo Menagerie authors, derived from Franka Emika's franka_ros description",
+ "files": {
+ "franka_emika_panda/assets/link0_0.obj": "6b9f41a4c203540daaeb7a33cc3d0d6c6a32dc8bba187074eeaf97b3e36b3f9c",
+ "franka_emika_panda/assets/link0_1.obj": "57673d2ee2a9db2e10c8986ae57c56a7c39c012b60fd26d7d8549553b664a5ed",
+ "franka_emika_panda/assets/link0_10.obj": "c9198b9d8534d628d097b0f2b239bb30343353182df098ce0d9db6bc13326848",
+ "franka_emika_panda/assets/link0_11.obj": "f0adec78d6677b7799d25121981270e8bfe119b5c18d08a91ee37a54ad75f65c",
+ "franka_emika_panda/assets/link0_2.obj": "1ca435a2a87a9608a146a47955724d43dd7ce10fc3dd3018800aa98f8ba86e05",
+ "franka_emika_panda/assets/link0_3.obj": "3e9c6334d2b3b47944af3458ee5f20519abc20fe7ee23063bb53405ccab28046",
+ "franka_emika_panda/assets/link0_4.obj": "215d25789704936120f119c0bc1cc7f68516dd3f8f1df61457b71acac3873f26",
+ "franka_emika_panda/assets/link0_5.obj": "9361b104e93743045107aa5b15fb1a0835ba9c1f355aae71f56403cf6a9c33f6",
+ "franka_emika_panda/assets/link0_7.obj": "2dc0b8ebbbc80e4c065d71e195adbc384f673438641fac82b07b801b4d2837cb",
+ "franka_emika_panda/assets/link0_8.obj": "3b8c436999db5586b8eb47bed2b0aa7de6993868b2681b4c04246eeac42fdb7a",
+ "franka_emika_panda/assets/link0_9.obj": "45178f97d2b5da6bce11f610212c4ef7d08c73db33a4fc38e1b7f66b93d023f5",
+ "franka_emika_panda/assets/link1.obj": "51091e776b16babdbe2f3849b5c041f921d1f11dd94ac19a0f1c81abf496fbae",
+ "franka_emika_panda/assets/link2.obj": "5c9f8e715de52c3eb71b475de35993b3b96081e02abea9f28c414768877fc59b",
+ "franka_emika_panda/assets/link3_0.obj": "ce2da87f51708e11b189249d41401065dabe89a06e251185a06cef4d5ff27178",
+ "franka_emika_panda/assets/link3_1.obj": "2880b7753a7173f38fa87ee21da4dfc7fa7be46fbe07bac5aef9e128513cb118",
+ "franka_emika_panda/assets/link3_2.obj": "670cff81ae84693769ca4ae658c154cf909d81167e7c8d22b70ea977f2504efa",
+ "franka_emika_panda/assets/link3_3.obj": "30ede0c812efd0e0b767d134a4eae0b84e0fa407bb6325a5a555e0569b3a3ffd",
+ "franka_emika_panda/assets/link4_0.obj": "443bf6d178177cf347951ecf107ccd10ca444e605e375b67304579e5f948806f",
+ "franka_emika_panda/assets/link4_1.obj": "ca935ec7cc8b3f0e86aa079c76b0b3bf593b1e9830bab0fa7131ac51577c74f0",
+ "franka_emika_panda/assets/link4_2.obj": "c89caf26d379c35bb9e191ee2d91d09ab29ecc792b48d8bc10b39e5b38222175",
+ "franka_emika_panda/assets/link4_3.obj": "1495d17f45bdb230cf58b0beef9da4e8c9cfe76a3d2d38da89017efe5e093136",
+ "franka_emika_panda/assets/link5_0.obj": "a3238b8f2af0f2eb66d9fe63dc5d41ac52d5d38507241b5ed10e3cb019ab3e71",
+ "franka_emika_panda/assets/link5_1.obj": "9d994bbf83ec241e301b5197a6846da13f2a4a0582edb2c0f76962c5549649d6",
+ "franka_emika_panda/assets/link5_2.obj": "83b4ffe9f772cd7fe182e98640650eebc899aaf01842656574b0416c90dd40a4",
+ "franka_emika_panda/assets/link6_0.obj": "0504c70ebf1b284ee8faae7dcb896b8830bc672a6552015dd5dbd121fa031fb9",
+ "franka_emika_panda/assets/link6_1.obj": "45f7ca77695198b6d86ec2417ad4e42e6275044f0f96266699ee8e1057757ac1",
+ "franka_emika_panda/assets/link6_10.obj": "365f26c21d10332cab8d8704645cb46930c30b3085956f2d097498c793f24db4",
+ "franka_emika_panda/assets/link6_11.obj": "8ae61e08b3ad064f25bbf03b22e59cc15d65883b5a7ce92711aff29df2493901",
+ "franka_emika_panda/assets/link6_12.obj": "f28d1bfd62b0244ffd19fb35fe9edefdf583d3c9167db944e87185d919e1d021",
+ "franka_emika_panda/assets/link6_13.obj": "0a55fa92dccb261d07200e6565fca4c850fd17f0c1ecf38821c0b97d51796c7d",
+ "franka_emika_panda/assets/link6_14.obj": "750ae3ee4781e62e3a045c662195247b03f6642b05aa93104f08258e5f6eba26",
+ "franka_emika_panda/assets/link6_15.obj": "5999c1c2497a004a7c4bbe034cdf13744f839d85ae7a11b1bc386c48a3e642e6",
+ "franka_emika_panda/assets/link6_16.obj": "551d7a8b37c53e7a152d008b4e36992e5b5abe74a4be18b57ee6319c27def09f",
+ "franka_emika_panda/assets/link6_2.obj": "e54eee4d8232947ee8af65afd5a067e09dac2da6e7e585cb1dccb65496457da0",
+ "franka_emika_panda/assets/link6_3.obj": "d4f6a25ef32fa1fa4734146981994ee760232cb077c80fea6487d78a077c7f27",
+ "franka_emika_panda/assets/link6_4.obj": "be353480fe71d46f7a96f0a3cbb7e112caaf8d88368826f321a36a253c8749b2",
+ "franka_emika_panda/assets/link6_5.obj": "7c87664623c3e1a6cb330db273227a69626dc5e53b4caff1d4ee7911eb3340c6",
+ "franka_emika_panda/assets/link6_6.obj": "8fbc031e0d07b795ebf99115c75223141caaba317cab569159f3d477a7821681",
+ "franka_emika_panda/assets/link6_7.obj": "7dc5ebb799fe281aab27d6e84e7a4efa0a8e42da2369ec83de3ea3f206f62d73",
+ "franka_emika_panda/assets/link6_8.obj": "e3f77381817a341030f9dcc4c4aa7c559f80411b453fd87eb0fefecca82151bf",
+ "franka_emika_panda/assets/link6_9.obj": "25a56ea9b02a03b6cb5a81f31c54f54d0185e1a0b3937c37e4289d896e50215a",
+ "franka_emika_panda/assets/link7_0.obj": "04586b0bde011715cfc22072ac72fe0717eb4d4817bcf665987ce6cd88eb2b93",
+ "franka_emika_panda/assets/link7_1.obj": "c3f72289f394c9d6749a4a327fb11f05b203c37c95032c92f28019b40ebe7e00",
+ "franka_emika_panda/assets/link7_2.obj": "d2faecedb304d0989040d082410378dc949dbbda23bd18c05134f08aae984db5",
+ "franka_emika_panda/assets/link7_3.obj": "b62d87c4d4bdb7b281ed341d347c39dad0e50bf36aed8ac11d050073701d5f70",
+ "franka_emika_panda/assets/link7_4.obj": "cb78ccb61fd4ad6c7bff4c4d2e6cb41e1964a5a3e1a28e67c0c6202371cfc018",
+ "franka_emika_panda/assets/link7_5.obj": "099071d3090b51471ba52f4f90814fd3089f4975d196e4d488117073d0bfe491",
+ "franka_emika_panda/assets/link7_6.obj": "99469e2d95ab74ce0292f2f16954c87a8a7dc16652e62e970fe37c94330a81bb",
+ "franka_emika_panda/assets/link7_7.obj": "426c3db8a19373f3dc73d4bec672e948121b2914c10e2e7b9c7ea80643a19e54",
+ "franka_emika_panda/panda_nohand.xml": "e7090a5e2384b18a223ef532d98bf914f7f9a6b74dc8bc9f74c8291201074071"
+ },
+ "bytes": 32259617,
+ "visual_geoms": 49
+ },
+ "kuka_iiwa_14": {
+ "title": "KUKA LBR iiwa 14",
+ "path": "kuka_iiwa_14/",
+ "xml": "kuka_iiwa_14/iiwa14.xml",
+ "license": "BSD-3-Clause",
+ "license_file": "LICENSE.kuka_iiwa_14",
+ "copyright": "MuJoCo Menagerie authors, derived from the Drake developers' iiwa14 description",
+ "files": {
+ "kuka_iiwa_14/assets/band.obj": "02cf16a93140489da3b05ce6bb30c5498bedaa5e5a77e56850ddbedb8d1ed23e",
+ "kuka_iiwa_14/assets/kuka.obj": "204a82d597d450f2a207731f8e3c17089f2de5a54c0d61feac454e96e325b834",
+ "kuka_iiwa_14/assets/link_0.obj": "6b607f6b5a601874863897ebfbb9821eb0c831c3115bca8350bf7856db6aaeee",
+ "kuka_iiwa_14/assets/link_1.obj": "47a82247b647639c3e1f384ce5b980d374323ca737d6ebc87447667a71981798",
+ "kuka_iiwa_14/assets/link_2_grey.obj": "842b8c3a9148b2fdf9c57ddfd80b595f8251792f94b71276dc9ce9a16674ba1a",
+ "kuka_iiwa_14/assets/link_2_orange.obj": "0d2d8829d89aa888ee04b0d97bed5f215fa0d9fd03d0d4cee2b2e0c8dd3c0124",
+ "kuka_iiwa_14/assets/link_3.obj": "b02d157e8090d82bfb78e7fd4dcd351033e0a5d7bb1937da01e66e7ff91a03a8",
+ "kuka_iiwa_14/assets/link_4_grey.obj": "e4555ea6954fffa40174baee25e6dd1b9efcc3eaf830b6e91d13e2ddc10b414a",
+ "kuka_iiwa_14/assets/link_4_orange.obj": "ef4cf2102e9df98636ff03b82d49d914a6e730b299b0a982d64947f038136cb7",
+ "kuka_iiwa_14/assets/link_5.obj": "f0eef60cddf06e46bd943abcc49ada87510f095f2840bc9c117ed7a2b1a6a787",
+ "kuka_iiwa_14/assets/link_6_grey.obj": "5b5f9883d4fc181c7aa06cb2037debfa4ca857fa0c3a5d55f8fd3e34d38c3100",
+ "kuka_iiwa_14/assets/link_6_orange.obj": "54aa0141e7f48497302f45daf074fd5c69320c620618c12fa76e8841c2a8a9fc",
+ "kuka_iiwa_14/assets/link_7.obj": "7307d0c852715ea234e575a0617ea2d8faf053469e7b823ac0c7c6c4dff36dad",
+ "kuka_iiwa_14/iiwa14.xml": "ee7e6d796a9f8642de6097f95077281d15f43678dc5285beafeda99b84cf9ef5"
+ },
+ "bytes": 5015391,
+ "visual_geoms": 15
+ },
+ "booster_t1": {
+ "title": "Booster T1",
+ "path": "booster_t1/",
+ "xml": "booster_t1/t1.xml",
+ "license": "Apache-2.0",
+ "license_file": "LICENSE.booster_t1",
+ "copyright": "MuJoCo Menagerie authors, derived from Booster Robotics' booster_gym T1 description",
+ "files": {
+ "booster_t1/assets/AL1.stl": "43f5d268152b3c169d34731545ddfa2a510a7e16f209a2a80f8ba9ae0e1a40aa",
+ "booster_t1/assets/AL2.stl": "4bca60adb29c73f701350abd23e8a8d660dc61e87c5163a80157650dd3ad88c3",
+ "booster_t1/assets/AL3.stl": "bfdf5611dfe90f8e02b07b037c36a244f4ce7184b45113371ef46e624fb30854",
+ "booster_t1/assets/AR1.stl": "6dbbd3dab4486600747be9d0e7f8523d67bf00d24d0dc9c23db1766c4d808fcf",
+ "booster_t1/assets/AR2.stl": "0499136785fe1bc0289d9e503e1e0ea48f5a63420a2e45b0fcd9e6b3bcf8f999",
+ "booster_t1/assets/AR3.stl": "92330bd8286fe420fb76949ee4c5d5bdec2e6bb30426acdc4d6fae9257464631",
+ "booster_t1/assets/Ankle_Cross_Left.stl": "e6ec38741838475834c147f2ad18196c0254741e602c2b676f888fd12b5d7981",
+ "booster_t1/assets/Ankle_Cross_Right.stl": "b15d91f0f2470fc4d5634db906a3d7efaf1f700302e6671824494da8faf50308",
+ "booster_t1/assets/H1.stl": "527a2e426db4e3d476a195754764b7f9565a950b809a34e47618f177b139c3f2",
+ "booster_t1/assets/H2.stl": "9cbf4fe83a721c809de65b1f0d0a379314f4523f7e2f8af7f0edc27c2ce385aa",
+ "booster_t1/assets/Hip_Pitch_Left.stl": "7bcb8be569aeb5379cb75a0827d682bc1d73a52a7f515d3aeffece43842c33c9",
+ "booster_t1/assets/Hip_Pitch_Right.stl": "054d579c3c6ccc1f97aaf1461d802dec748ce1bf26c6fdd289283a2d0dbb2032",
+ "booster_t1/assets/Hip_Roll_Left.stl": "72dbd65bdb4e87444c8e538474f631d63bf8c0960922517456b8cf2be9e1d0f0",
+ "booster_t1/assets/Hip_Roll_Right.stl": "d715a7649ea4bf20d7ee17b3a57bae31732e467b9da1053fee2242c90f50980f",
+ "booster_t1/assets/Hip_Yaw_Left.stl": "d588e0467094811e74ae1962fcb0eb669f9b50b74022e96a738bdc8e807e03a7",
+ "booster_t1/assets/Hip_Yaw_Right.stl": "5135f2fd5707364583d283e2fb21845054f3548c224f48e1f0a3d78ed3453497",
+ "booster_t1/assets/Shank_Left.stl": "6ae8dd7f88cb70a4a3cb3972cad4035a76f1604fd73ea66e285da553b3703c40",
+ "booster_t1/assets/Shank_Right.stl": "dc66a8a0e2e31e413884a053e427d9b5007bef4508986587916a638a8a448599",
+ "booster_t1/assets/Trunk.stl": "39d9610b23ef8ac7ea4343231a499f9c485903bede62df9729a2cd1254fede8f",
+ "booster_t1/assets/Waist.stl": "2fe0a9ccfc284beca402e554db38e83022592192afa00f02db13cb374ffe9fbc",
+ "booster_t1/assets/left_foot_link.stl": "82d653e30c0ae2e588c3c539266c9a1fee20e711448e13598f25384c7dc562ca",
+ "booster_t1/assets/left_hand_link.stl": "34df992aed438446481cfa20e78327810cd5cc5ecbb4a6f32ba2bf625462f53d",
+ "booster_t1/assets/right_foot_link.stl": "78440aa4bab7c397b8e507431b44b814e4cb89db0d03455f83ae54e3157cf15b",
+ "booster_t1/assets/right_hand_link.stl": "c5a73e493e17db7611a81785f80c01167f51018271b4042f72fa8d2351d8b0eb",
+ "booster_t1/t1.xml": "78af3f7910e4413894863b6427f44a7daf49e5eb47628e6fe2db775219e346b9"
+ },
+ "bytes": 8445726,
+ "visual_geoms": 24
+ }
+ }
+}
diff --git a/scripts/roboolympics/shared/sim/renderers/scene_check.py b/scripts/roboolympics/shared/sim/renderers/scene_check.py
new file mode 100644
index 0000000000..5713371f35
--- /dev/null
+++ b/scripts/roboolympics/shared/sim/renderers/scene_check.py
@@ -0,0 +1,164 @@
+"""Same scene (renderer rule 2): a non-default renderer draws the default renderer's scene. The geometry, kinematics,
+cameras and the colour a viewer sees of every untextured geom must be identical; a re-textured surface keeps its mean
+colour within TEXTURE_TOL. Only lights, materials (specular, shininess, reflectance, textures with the same mean
+colour) and image quality may differ. The same rule as scripts/olympiad/showcase/looks.same_scene, without the
+sport-specific decor exception (decor is presentation-only and never part of a renderer's player picture).
+
+Same kinematics (renderer rule 6): a presentation scene (renderers/presentation.py, spectators only) may differ from
+the match scene in appearance and by added visual-only geoms, never in bodies, joints, frames, inertias or cameras;
+same_kinematics() checks it before a renderer draws one, pose_diff() compares body poses over recorded states."""
+from __future__ import annotations
+
+import numpy as np
+
+SAME = ("nq", "nv", "nbody", "njnt", "ngeom", "nmesh", "ncam", "nmocap",
+ "body_parentid", "body_pos", "body_quat", "body_mass", "jnt_type", "jnt_qposadr", "jnt_pos", "jnt_axis",
+ "geom_type", "geom_bodyid", "geom_size", "geom_pos", "geom_quat", "geom_group", "geom_dataid",
+ "mesh_vertnum", "mesh_vert", "mesh_face",
+ "cam_mode", "cam_bodyid", "cam_pos", "cam_quat", "cam_fovy")
+DEFAULT_RGBA = (0.5, 0.5, 0.5, 1.0)
+TEXTURE_TOL = 0.02
+MESH = 7 # mjtGeom.mjGEOM_MESH
+
+
+def effective_rgba(m, g):
+ rgba = m.geom_rgba[g]
+ if m.geom_matid[g] >= 0 and np.allclose(rgba, DEFAULT_RGBA):
+ return m.mat_rgba[m.geom_matid[g]]
+ return rgba
+
+
+def _texid(m, g):
+ import mujoco as mj
+ mid = m.geom_matid[g]
+ return int(m.mat_texid[mid, mj.mjtTextureRole.mjTEXROLE_RGB]) if mid >= 0 else -1
+
+
+def _mean_colour(m, g):
+ """Mean drawn colour of a geom (texture mean x material/geom colour), 0..1 RGB."""
+ rgba = np.asarray(effective_rgba(m, g)[:3], float)
+ t = _texid(m, g)
+ if t < 0:
+ return rgba
+ h, w, c = m.tex_height[t], m.tex_width[t], m.tex_nchannel[t]
+ px = m.tex_data[m.tex_adr[t]:m.tex_adr[t] + h * w * c].reshape(-1, c)[:, :3]
+ return rgba * (px.mean(0) / 255.0)
+
+
+SPARE = "_ro_cam" # the renderers' own spare cameras (renderers/mujoco), posed per frame: not scene cameras
+
+
+def _scene_cams(m):
+ return [i for i in range(m.ncam) if not (m.camera(i).name or "").startswith(SPARE)]
+
+
+def same_scene(m0, m1) -> list:
+ """Differences between the default model m0 and the renderer's model m1 (empty list = the same scene)."""
+ bad = []
+ c0, c1 = _scene_cams(m0), _scene_cams(m1)
+ for name in SAME:
+ a, b = np.asarray(getattr(m0, name)), np.asarray(getattr(m1, name))
+ if name.startswith("cam_"):
+ a, b = a[c0], b[c1]
+ elif name == "ncam":
+ a, b = np.asarray(len(c0)), np.asarray(len(c1))
+ if np.shape(a) != np.shape(b) or not np.array_equal(a, b):
+ bad.append(name)
+ if bad:
+ return bad
+ if m0.vis.global_.fovy != m1.vis.global_.fovy:
+ bad.append("vis.global.fovy")
+ for g in range(m0.ngeom):
+ t0, t1 = _texid(m0, g) >= 0, _texid(m1, g) >= 0
+ if not t0 and not t1:
+ if not np.allclose(effective_rgba(m0, g), effective_rgba(m1, g)):
+ bad.append(f"colour of geom {m0.geom(g).name or g}")
+ elif float(np.abs(_mean_colour(m0, g) - _mean_colour(m1, g)).max()) > TEXTURE_TOL:
+ bad.append(f"mean colour of textured geom {m0.geom(g).name or g}")
+ return bad
+
+
+# ------------------------------------------------------------------------------------- presentation scenes (spectators)
+VISUAL_PREFIX = "_vis:" # the name prefix of a presentation scene's added geoms (renderers/presentation.py)
+KINEMATICS = ("nq", "nv", "nu", "nbody", "njnt", "nmocap", "nsite", "qpos0",
+ "body_parentid", "body_rootid", "body_weldid", "body_mocapid", "body_jntnum", "body_jntadr",
+ "body_dofnum", "body_dofadr", "body_pos", "body_quat", "body_ipos", "body_iquat", "body_mass",
+ "body_inertia", "jnt_type", "jnt_bodyid", "jnt_qposadr", "jnt_dofadr", "jnt_pos", "jnt_axis",
+ "jnt_range", "dof_bodyid", "dof_jntid", "dof_armature", "dof_damping", "actuator_trnid",
+ "site_bodyid", "site_pos", "site_quat", "opt.timestep", "opt.gravity")
+MATCH_GEOM = ("geom_type", "geom_bodyid", "geom_size", "geom_pos", "geom_quat", "geom_contype", "geom_conaffinity",
+ "geom_condim", "geom_priority", "geom_friction", "geom_solref", "geom_solimp", "geom_margin", "geom_gap")
+CAMERA = ("cam_mode", "cam_bodyid", "cam_pos", "cam_quat", "cam_fovy")
+
+
+def _arr(m, name):
+ o = m
+ for part in name.split("."):
+ o = getattr(o, part)
+ return np.asarray(o)
+
+
+def visual_geoms(m) -> list:
+ return [g for g in range(m.ngeom) if (m.geom(g).name or "").startswith(VISUAL_PREFIX)]
+
+
+def _mesh_verts(m, g):
+ i = m.geom_dataid[g]
+ return m.mesh_vert[m.mesh_vertadr[i]:m.mesh_vertadr[i] + m.mesh_vertnum[i]]
+
+
+def same_kinematics(m0, m1) -> list:
+ """Differences between the match model m0 and a presentation model m1 (empty list = the same kinematics):
+ every body, joint, dof, frame, inertia, site, mocap body and scene camera is identical; m0's geoms are all in m1,
+ in the same order, with the same geometry, pose and contact properties (only their appearance may change:
+ group, colour, material, e.g. a collision mesh moved to the hidden group 3); every other geom of m1 is an added
+ visual geom (name prefix VISUAL_PREFIX) that never collides (contype = conaffinity = 0) and is drawn (group
+ 0..2). Body masses and inertias being equal, the added geoms carry no mass. So the same qpos puts every body at
+ the same pose in both models: a presentation scene changes only what a spectator sees."""
+ bad = []
+ for name in KINEMATICS:
+ a, b = _arr(m0, name), _arr(m1, name)
+ if a.shape != b.shape or not np.array_equal(a, b):
+ bad.append(name)
+ c0, c1 = _scene_cams(m0), _scene_cams(m1)
+ if len(c0) != len(c1):
+ bad.append("ncam")
+ else:
+ bad += [n for n in CAMERA if not np.array_equal(_arr(m0, n)[c0], _arr(m1, n)[c1])]
+ if bad:
+ return bad
+ extra = visual_geoms(m1)
+ keep = [g for g in range(m1.ngeom) if g not in set(extra)]
+ if len(keep) != m0.ngeom:
+ return [f"{len(keep)} match geoms in the presentation scene for {m0.ngeom}"]
+ bad += [n for n in MATCH_GEOM if not np.array_equal(_arr(m0, n), _arr(m1, n)[keep])]
+ for g0, g1 in enumerate(keep):
+ if (m0.geom(g0).name or "") != (m1.geom(g1).name or ""):
+ bad.append(f"name of geom {g0}")
+ elif m0.geom_dataid[g0] >= 0 and m0.geom_type[g0] == MESH and not np.array_equal(_mesh_verts(m0, g0),
+ _mesh_verts(m1, g1)):
+ bad.append(f"mesh of geom {m0.geom(g0).name or g0}")
+ for g in extra:
+ if m1.geom_contype[g] or m1.geom_conaffinity[g] or not 0 <= m1.geom_group[g] <= 2:
+ bad.append(f"added geom {m1.geom(g).name} collides or is not drawn")
+ return bad
+
+
+def pose_diff(m0, m1, states) -> float:
+ """The largest difference of any body's (and site's) world position or orientation between the two models over
+ the given states ({"qpos", optional "mocap_pos", "mocap_quat"}); 0.0 = bit-identical poses."""
+ import mujoco as mj
+ d0, d1 = mj.MjData(m0), mj.MjData(m1)
+ worst = 0.0
+ for st in states:
+ for m, d in ((m0, d0), (m1, d1)):
+ d.qpos[:] = np.asarray(st["qpos"], float)
+ if m.nmocap and "mocap_pos" in st:
+ d.mocap_pos[:] = np.asarray(st["mocap_pos"], float).reshape(m.nmocap, 3)
+ if m.nmocap and "mocap_quat" in st:
+ d.mocap_quat[:] = np.asarray(st["mocap_quat"], float).reshape(m.nmocap, 4)
+ mj.mj_kinematics(m, d)
+ for a, b in ((d0.xpos, d1.xpos), (d0.xquat, d1.xquat), (d0.xmat, d1.xmat), (d0.site_xpos, d1.site_xpos)):
+ if np.asarray(a).size:
+ worst = max(worst, float(np.abs(np.asarray(a) - np.asarray(b)).max()))
+ return worst
diff --git a/scripts/roboolympics/shared/sim/server.py b/scripts/roboolympics/shared/sim/server.py
new file mode 100644
index 0000000000..5eb03f3410
--- /dev/null
+++ b/scripts/roboolympics/shared/sim/server.py
@@ -0,0 +1,30 @@
+"""eai-standard/2.3 sim service for RoboOlympics: rcb_realtime.py (the sidecar's entry point, `python /srv/rcb_realtime.py`)
+imports this module and calls build(). The sport and its frozen instance come from environment/docker-compose.yaml:
+ RO_PLUGIN the sport's plugin (/srv/sport/plugin.py)
+ RO_FORMAT the sport's format (match: one player against the scripted opponent)
+ RO_SEED the frozen instance's seed (serves, the opponent's returns, the execution scatter)
+ RO_LEVEL the scripted opponent's level
+ RO_ACTION_LEVEL the action level (high: strokes the service plans; low: joint or mallet targets)
+ RO_TASK_TEXT, RO_EPISODE_TEXT one sentence each for /spec
+ RCB_SLOWDOWN the slowdown S (badminton's stroke lead depends on it); RCB_DATA, RCB_RESET_BUDGET,
+ RCB_WALL_CLOCK_S: the service's own (rcb_service.main)
+"""
+from __future__ import annotations
+
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from core.sport import MatchConfig # noqa: E402
+from rcb_olympics import Olympics # noqa: E402
+
+
+def build() -> Olympics:
+ env = os.environ.get
+ plugin = env("RO_PLUGIN", "/srv/sport/plugin.py")
+ sport = os.path.basename(os.path.dirname(os.path.abspath(plugin)))
+ cfg = MatchConfig(sport=env("RO_SPORT", sport), format=env("RO_FORMAT", "match"), seats=("A",),
+ seed=int(env("RO_SEED", "101")), first="A", slowdown=float(env("RCB_SLOWDOWN") or 10),
+ level=int(env("RO_LEVEL", "1")), action_level=env("RO_ACTION_LEVEL", "high"), play="program")
+ return Olympics(plugin, cfg, data=env("RCB_DATA", "/data"), task_text=env("RO_TASK_TEXT", ""),
+ episode_text=env("RO_EPISODE_TEXT", ""))
diff --git a/scripts/roboolympics/shared/sports/airhockey/builtin_players.py b/scripts/roboolympics/shared/sports/airhockey/builtin_players.py
new file mode 100644
index 0000000000..35623d0ced
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/airhockey/builtin_players.py
@@ -0,0 +1,325 @@
+"""airhockey's built-in players (same action interface as a model's program; core/client.py plays them over HTTP).
+
+ Reference the camera-only reference player (rewritten 2026-10-07, review item B13; the legacy camera_player.py
+ rarely scored: 0.05 goals per game against itself). It finds the red puck and the opponent's mallet by
+ colour in its camera image (the camera definition of /spec) and fits the puck's velocity over the recent
+ images. Defence: on the defence line where the puck will cross it (side-rail bounces predicted with the
+ rails' restitution), at the near post when the puck will slide along the end rail towards the mouth,
+ and a puck deep beside the own goal is pushed out from the goal side, never across the mouth. Attack:
+ a puck in the own half is struck hard: wind-up behind it on the chosen line (straight or off a rail, at
+ the part of the goal the opponent's mallet needs longest to reach), then a drive through it towards a
+ target far beyond, so the mallet hits at the path's top speed.
+ Random uniform random targets in the own workspace (generic tests: no draw, whitelist, determinism).
+No simulator import: this file runs in the player's container as the task's oracle (numpy + pillow only)."""
+from __future__ import annotations
+
+import base64
+import io
+import math
+
+import numpy as np
+
+X_NEAR, X_FAR, Y_MAX, REACH, BASE_X = .05, .92, .47, 1.45, 1.51 # the public workspace (game spec: workspace)
+PUCK_R, MALLET_R = .03165, .04815 # game spec: geometry
+CONTACT = PUCK_R + MALLET_R
+END = 1.948 / 2 # the end line (half length)
+RAIL = .519 - PUCK_R # the puck centre's reach across the table (half width - radius)
+MOUTH = .125 - PUCK_R # the puck centre scores within |y| < MOUTH
+E_RAIL = .8 # the rails return about 80 % of the speed across them (spec)
+GUARD = .80 # the defence line (local u)
+WIND = .26 # the wind-up distance behind the puck before a strike
+TOL = .07 # line-up tolerance (rad) before a strike
+MALLET_Z = .005 # the mallet blob's centroid back-projects best onto this height
+
+
+def image_of(view):
+ """The seat's camera tile of the observation as an H x W x 3 float array (None without an image)."""
+ from PIL import Image
+ obs = view.get("observation") or {}
+ if not obs.get("image_png_b64"):
+ return None
+ img = np.asarray(Image.open(io.BytesIO(base64.b64decode(obs["image_png_b64"]))).convert("RGB")).astype(float)
+ tile = next((t for t in obs.get("tiles") or [] if t.get("camera") == "front"), None)
+ if tile:
+ img = img[tile["y"]:tile["y"] + tile["height"], tile["x"]:tile["x"] + tile["width"]]
+ return img
+
+
+def locate(a, cam, seat, what="puck"):
+ """The table-plane position of the puck (red) or of the opponent's mallet top (B green, A blue): the centroid of
+ the colour mask back-projected through the camera definition (pinhole, pixel centres at i + 0.5)."""
+ R, G, B = a[:, :, 0], a[:, :, 1], a[:, :, 2]
+ if what == "puck":
+ mask = (R > 150) & (R > 2.5 * G) & (R > 2.5 * B)
+ elif seat == "A":
+ mask = (G > 100) & (G > 2 * R) & (G > 1.5 * B) # B's green mallet
+ else:
+ mask = (B > 150) & (B > 2 * R) & (B > 1.3 * G) # A's blue mallet
+ rows, cols = np.nonzero(mask)
+ if len(rows) < 3:
+ return None
+ pos, look = np.array(cam["pos"], float), np.array(cam["lookat"], float)
+ fwd = (look - pos) / np.linalg.norm(look - pos)
+ right = np.cross(fwd, np.array(cam.get("up", [0, 0, 1]), float))
+ right /= np.linalg.norm(right)
+ up = np.cross(right, fwd)
+ f = cam["focal_px"]
+ cx, cy = cam["principal_point_px"]
+ ray = fwd + right * ((float(cols.mean()) + .5 - cx) / f) + up * ((cy - float(rows.mean()) - .5) / f)
+ z = .012 if what == "puck" else MALLET_Z # the puck's centre plane / the mallet blob (calibrated)
+ return (pos + ray * ((z - pos[2]) / ray[2]))[:2]
+
+
+def clip(u, v):
+ """Local coordinates (u > 0 into the own half): the nearest workspace point."""
+ u, v = min(max(u, X_NEAR), X_FAR), min(max(v, -Y_MAX), Y_MAX)
+ d = math.hypot(BASE_X - u, v)
+ if d > REACH - 1e-3:
+ u, v = BASE_X - (BASE_X - u) * (REACH - 1e-3) / d, v * (REACH - 1e-3) / d
+ return u, v
+
+
+def inside(u, v):
+ return X_NEAR <= u <= X_FAR and abs(v) <= Y_MAX and math.hypot(BASE_X - u, v) <= REACH
+
+
+def seg_dist(q, a, b):
+ ab = b - a
+ t = float(np.clip((q - a) @ ab / max(1e-9, ab @ ab), 0, 1))
+ return float(np.linalg.norm(q - (a + t * ab)))
+
+
+def cross(p, w, line, bounces=4):
+ """Where (v), after how long (s, at constant speed) and with what velocity across (wv) a puck at p moving with w
+ (local coordinates) crosses u = line, bouncing off the side rails (the speed across a rail scales by E_RAIL);
+ None if it moves away."""
+ pu, pv = float(p[0]), float(p[1])
+ wu, wv = float(w[0]), float(w[1])
+ if (line - pu) * wu <= 1e-9:
+ return None
+ t = 0.
+ for _ in range(bounces + 1):
+ tu = (line - pu) / wu
+ tv = (RAIL - pv) / wv if wv > 1e-9 else ((-RAIL - pv) / wv if wv < -1e-9 else math.inf)
+ if tu <= tv:
+ return pv + wv * tu, t + tu, wv
+ pu, pv, t, wv = pu + wu * tv, pv + wv * tv, t + tv, -E_RAIL * wv
+ return None
+
+
+def shots(p, mouth=MOUTH):
+ """Candidate strikes of a puck at p (local): (unit direction, path points), straight at the other goal or off
+ one side rail (aimed with the rail's restitution), at five points of the goal mouth."""
+ out = []
+ x = END + p[0] # the distance to the other end line along -u
+ for gy in (-.7 * mouth, -.35 * mouth, 0., .35 * mouth, .7 * mouth):
+ out.append((0, gy, np.array([-x, gy - p[1]]), [p, np.array([-END, gy])]))
+ for b in (1, -1):
+ k = ((b * RAIL - p[1]) + (b * RAIL - gy) / E_RAIL) / x
+ if abs(k) < 1e-6:
+ continue
+ x1 = (b * RAIL - p[1]) / k
+ if not 0 < x1 < x:
+ continue
+ out.append((b, gy, np.array([-1., k]), [p, np.array([p[0] - x1, b * RAIL]), np.array([-END, gy])]))
+ return [(b, gy, d / np.linalg.norm(d), path) for b, gy, d, path in out]
+
+
+def defender_time(dist):
+ """Seconds an opponent's mallet needs to move `dist` (a 10 m/s^2 path from rest, plus a reaction)."""
+ return .12 + 2 * math.sqrt(max(dist, 0.) / 10.)
+
+
+def choose(p, opp, speed=1.8, wind=WIND, mouth=MOUTH):
+ """The strike direction for a puck at p: the candidate the opponent's mallet `opp` (local) is least likely to
+ reach in time, among those whose wind-up point behind the puck lies in the workspace."""
+ best = None
+ for b, gy, d, path in shots(p, mouth):
+ w = p - d * wind
+ if not inside(*w):
+ continue
+ if opp is None:
+ score = -.02 * abs(b) + .1 * abs(gy)
+ else:
+ clear, s = 9., 0.
+ for i in range(len(path) - 1):
+ a_, b_ = path[i], path[i + 1]
+ seg = float(np.linalg.norm(b_ - a_))
+ ab = b_ - a_
+ tt = float(np.clip((opp - a_) @ ab / max(1e-9, ab @ ab), 0, 1))
+ dd = float(np.linalg.norm(opp - (a_ + tt * ab)))
+ if dd < clear:
+ clear, s_at = dd, s + tt * seg
+ s += seg
+ t_puck = s_at / (speed * (E_RAIL if b and s_at > float(np.linalg.norm(path[1] - path[0])) else 1.))
+ score = min(defender_time(clear - CONTACT + .01) - t_puck, .3) - .03 * abs(b)
+ if best is None or score > best[0]:
+ best = (score, d)
+ return None if best is None else best[1]
+
+
+class Reference:
+ """Works in local coordinates: u = own * x (own half u > 0, own goal at u = +END), v = y.
+
+ Defence: while the puck is in the other half or coming at the own goal, the mallet stands on the defence line
+ (u = GUARD) where the puck will cross it (the side-rail bounces predicted with the rails' restitution), or, while
+ the puck goes away or rests over there, on the line from the puck to the goal centre. Attack: a puck resting or
+ moving slowly in the own half is struck hard: the mallet winds up WIND behind the puck on the chosen line
+ (choose(): straight or off a rail, where the opponent's mallet has to travel farthest in the time the puck takes),
+ then drives through it towards a target far beyond, so it reaches the path's top speed at the impact."""
+
+ def __init__(self, spec, seat, seed=0):
+ self.seat, self.own = seat, (-1. if seat == "A" else 1.)
+ self.cam = next(c for c in spec["cameras"] if c["name"] == "front")
+ self.mouth = float((spec.get("geometry") or {}).get("goal_width_m", 2 * (MOUTH + PUCK_R))) / 2 - PUCK_R
+ self.rally = None
+ self.reset()
+
+ def reset(self):
+ self.until, self.stroke, self.hist, self.w, self.p, self.t_side = -1., None, [], np.zeros(2), None, None
+ self.deep_stroke = False
+
+ def world(self, u, v):
+ u, v = clip(u, v)
+ return [round(self.own * u, 4), round(v, 4)]
+
+ def track(self, p, t):
+ """The puck's velocity: a straight-line fit over the recent images, restarted at a hit or a rail bounce
+ (an image off the fitted line by more than 1.2 cm)."""
+ if self.hist and t <= self.hist[-1][0] + 1e-6:
+ return
+ if len(self.hist) >= 2:
+ t0, p0 = self.hist[-1]
+ if float(np.linalg.norm(p0 + self.w * (t - t0) - p)) > .012:
+ self.hist = self.hist[-1:]
+ self.hist = (self.hist + [(t, p.copy())])[-5:]
+ if len(self.hist) >= 2:
+ ts = np.array([h[0] for h in self.hist])
+ ps = np.array([h[1] for h in self.hist])
+ tc = ts - ts.mean()
+ self.w = (tc[:, None] * (ps - ps.mean(0))).sum(0) / max(1e-9, float((tc * tc).sum()))
+ else:
+ self.w = np.zeros(2)
+
+ def guard(self, p, w):
+ c = cross(p, w, GUARD) if w[0] > .05 else None
+ e = cross(p, w, END) if w[0] > .05 else None
+ if e is not None and self.mouth - .01 < abs(e[0]) < .34 and e[0] * e[2] < 0 and e[1] < 3.:
+ # it will hit the end rail beside the goal and slide on towards the mouth: block the near post
+ return self.world(X_FAR - .02, float(np.sign(e[0])) * .05)
+ if c is not None and c[1] < 3.:
+ y = c[0]
+ else: # between the puck and the goal centre
+ y = p[1] * (END - GUARD) / max(.2, END - p[0])
+ return self.world(GUARD, float(np.clip(y, -.22, .22)))
+
+ def clear_deep(self, p, w, m, t):
+ """A puck deep beside the own goal: block the near post while it slides towards the goal mouth; else get to
+ its goal side (round the front, never through it) and push it outwards, away from the mouth."""
+ sg = 1. if p[1] >= 0 else -1. # the outer side of the puck
+ if w[1] * sg < -.15 and abs(p[1]) > .1: # sliding along the end rail towards the mouth
+ return self.world(X_FAR, sg * .05)
+ stage = np.array([min(X_FAR, p[0] + .04), p[1] - sg * .075])
+ if float(np.linalg.norm(m - stage)) < .03:
+ q = p - stage
+ self.stroke, self.until = self.world(*(p + q / float(np.linalg.norm(q)) * .25)), t + .3
+ return self.stroke
+ if (m[1] - p[1]) * sg < -.05 and abs(m[0] - p[0]) < .1: # on the goal side: close in
+ return self.world(*stage)
+ beside = np.array([p[0], p[1] - sg * .095])
+ if seg_dist(p, m, beside) > CONTACT + .015:
+ return self.world(*beside)
+ return self.world(p[0] - .13, p[1] - sg * .095) # first in front of the puck
+
+ def decide(self, puck, own_xyz, t, opp=None):
+ m = np.array([self.own * own_xyz[0], own_xyz[1]])
+ if puck is None:
+ if self.p is None or not self.hist or t > self.hist[-1][0] + .25:
+ return self.world(GUARD, 0.)
+ p = self.p + self.w * (t - self.hist[-1][0])
+ else:
+ p = np.array([self.own * puck[0], puck[1]])
+ self.track(p, t)
+ self.p = p
+ w = self.w
+ o = None if opp is None else np.array([self.own * opp[0], opp[1]])
+ if p[0] > PUCK_R: # seven-second clock: time the puck has spent in the own half
+ self.t_side = t if self.t_side is None else self.t_side
+ else:
+ self.t_side = None
+ deep = p[0] > .86 and abs(p[1]) < .26 and w[0] > -.6
+ if t < self.until: # a stroke in progress: drive through until the puck has gone
+ if w[0] < -.4 or p[0] < 0 or (deep and not self.deep_stroke):
+ self.until = -1.
+ else:
+ return self.stroke
+ self.deep_stroke = deep
+ if deep: # deep beside the own goal
+ return self.clear_deep(p + w * .05, w, m, t)
+ if p[0] < -.02 or w[0] > .35 or (w[0] < -.3 and p[0] < .3) or (w[0] > .12 and m[0] < p[0] + .05):
+ return self.guard(p, w) # (also: coming at the goal while the mallet is not behind it)
+ pp = p + w * .1 # where the puck will be when the mallet gets there
+ hurry = self.t_side is not None and t - self.t_side > 4.
+ d, wind = None, WIND
+ for wind in (WIND, .2, .14):
+ d = choose(pp, o, wind=wind, mouth=self.mouth)
+ if d is not None:
+ break
+ if d is None: # no line-up possible (a corner): push it out past the mallet
+ q = pp - m
+ q = q / max(1e-9, float(np.linalg.norm(q)))
+ self.stroke, self.until = self.world(*(pp + q * .25)), t + .3
+ return self.stroke
+ wpt = pp - d * wind
+ rel = pp - m
+ dist = float(np.linalg.norm(rel))
+ tol = TOL * (2.5 if hurry else 1.)
+ if (float(np.linalg.norm(m - wpt)) < .06 or hurry) and CONTACT + .02 < dist < wind + .12 \
+ and float(rel @ d) / dist > math.cos(tol): # lined up: drive through the puck
+ reach = .1
+ for L in (.5, .4, .3, .2):
+ if inside(*(pp + d * L)):
+ reach = L
+ break
+ self.stroke = self.world(*(pp + d * reach))
+ self.until = t + .35
+ return self.stroke
+ if seg_dist(pp, m, wpt) < CONTACT + .03 and float((m - pp) @ d) > -wind + .06:
+ n = np.array([-d[1], d[0]]) # the way to the wind-up point runs through the puck:
+ s = 1. if float(n @ (m - pp)) >= 0 else -1. # first beside it, on the mallet's side
+ q = pp + n * s * .17
+ if not inside(*q):
+ q = pp - d * .12 + n * s * .14
+ if not inside(*q):
+ q = pp - d * .12 - n * s * .14
+ return self.world(*q)
+ return self.world(*wpt)
+
+ def act(self, view):
+ st = view.get("state") or {}
+ if st.get("rally") != self.rally: # a new rally
+ self.rally = st.get("rally")
+ self.reset()
+ img = image_of(view)
+ if img is None or "own" not in st:
+ return None
+ puck = locate(img, self.cam, self.seat)
+ opp = locate(img, self.cam, self.seat, "opponent")
+ x, y = self.decide(puck, st["own"]["mallet_xyz"], float(st.get("t_play", st.get("t_sim", 0.0))), opp)
+ return {"type": "target", "x": x, "y": y}
+
+ def review(self, reply):
+ self.reset()
+ return "A goal, foul or dead puck ended the rally.", "Guard the crossing point; wind up and strike hard at the open side."
+
+
+class Random:
+ def __init__(self, spec, seat, seed=0):
+ self.own = -1. if seat == "A" else 1.
+ self.g = np.random.default_rng(int(seed) * 7919 + 17) # by seed, not by seat
+
+ def act(self, view):
+ if self.g.random() < .2:
+ return {"type": "none"}
+ u, v = clip(float(self.g.uniform(X_NEAR, X_FAR)), float(self.g.uniform(-Y_MAX, Y_MAX)))
+ return {"type": "target", "x": round(self.own * u, 4), "y": round(v, 4)}
diff --git a/scripts/roboolympics/shared/sports/airhockey/grade.py b/scripts/roboolympics/shared/sports/airhockey/grade.py
new file mode 100644
index 0000000000..f352ffbe8c
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/airhockey/grade.py
@@ -0,0 +1,82 @@
+"""airhockey's part of reward.json (the common part is core/grading.py, which runs first; these keys are added after
+it): numbers only, from final.json and, for the legacy metering keys, the sim's artifacts think_usage_<seat>.json in
+RCB_DATA. The keys are the legacy tasks' (scripts/olympiad/airhockey/{match,duel}/tests/grade.py) wherever final.json
+still has the value; README lists what changed and why. official_config replaces the core's value: the legacy rule is
+per format (match: the level's own seeds and the slowdowns 1-20; duel: seeds 1-3 at x10 or x20), which [official]
+cannot express."""
+import json
+import os
+from pathlib import Path
+
+DATA = Path(os.environ.get("RCB_DATA", "/data"))
+OFFICIAL_SEEDS = {1: [101, 111, 121], 2: [202, 212, 222], 3: [303, 313, 323], 4: [404, 414, 424]}
+OFFICIAL_SLOWDOWNS = [1, 2, 5, 10, 20]
+DUEL_SEEDS = [1, 2, 3]
+DUEL_SLOWDOWNS = [10, 20]
+REVISION = 4 # hockey.REVISION airhockey-program-v4 (the simulator and referee)
+METERED = ("requests", "input_tokens", "output_tokens", "rate_limit_retries")
+
+
+def _usage(seat):
+ try:
+ return json.loads((DATA / f"think_usage_{seat}.json").read_text())
+ except (OSError, ValueError):
+ return {}
+
+
+def evaluate(d):
+ f, seats = d.get("sport_fields") or {}, d["cfg"]["seats"]
+ duel = len(seats) == 2
+ reason, errors = d.get("reason"), d.get("errors") or []
+ results = f.get("results") or []
+ table = f.get("scores") or {}
+ normal = reason == "match_over" and bool(f.get("done"))
+ decided = (f.get("decided_by") or "") if normal else ""
+ lag = d.get("sim_lag") or {}
+ run_sim = float(lag.get("run_sim_s") or 0.0)
+ level, seed, slow = int(f.get("level") or 1), int(d.get("seed") or 0), float(d.get("slowdown") or 0.0)
+ official = (seed in DUEL_SEEDS and slow in DUEL_SLOWDOWNS) if duel else \
+ (seed in OFFICIAL_SEEDS.get(level, []) and slow in OFFICIAL_SLOWDOWNS)
+ stats = d.get("seats") or {}
+ out = dict(
+ replay_error=int(not d.get("deterministic") or any(e.get("where") == "replay" for e in errors)),
+ sim_error=int(reason == "technical_error" or any(e.get("where") == "world" for e in errors)),
+ meter_error=int(any((d.get("meter_error") or {}).get(s) for s in seats)),
+ proxy_error=int(any((d.get("proxy_error") or {}).get(s) for s in seats)), timing_invalid=0,
+ official_config=int(official), revision=REVISION, slowdown=slow,
+ first_player_A=int((f.get("first_player") or d.get("first")) == "A"),
+ match_limit=int(normal and decided.startswith("cap")), decided_by_score=int(decided == "score"),
+ decided_by_last_goal=int(decided == "cap_last_goal"), decided_by_territory=int(decided == "cap_territory"),
+ decided_by_first_possession=int(decided == "cap_first_possession"),
+ rallies=len(results), goals=sum(r.get("how") == "goal" for r in results),
+ own_goals=sum(bool(r.get("own_goal")) for r in results),
+ seven_second_fouls=sum(r.get("how") == "seven_second_foul" for r in results),
+ dead_pucks=sum(r.get("how") == "dead_puck" for r in results),
+ n_actions=sum(int((stats.get(s) or {}).get("applied", 0)) for s in seats),
+ n_reviews=len(d.get("reviews") or []), steps=int(d.get("steps") or 0),
+ mallet_contact_steps=int(f.get("mallet_contact_steps", 0)), rail_contact_steps=int(f.get("rail_contact_steps", 0)),
+ late_over_100ms=int(float(lag.get("late_max_s") or 0.0) > 0.1),
+ sim_lag_late_max_s=float(lag.get("late_max_s") or 0.0), sim_lag_late_p99_s=float(lag.get("late_p99_s") or 0.0),
+ sim_effective_slowdown=float(lag.get("run_wall_s") or 0.0) / run_sim if run_sim > 0 else 0.0,
+ sim_run_wall_s=float(lag.get("run_wall_s") or 0.0))
+ if duel:
+ complete = d.get("match_winner") is not None
+ out.update(ready_forfeit=int(reason == "ready_timeout" and complete),
+ start_forfeit=int(reason == "no_show" and complete))
+ for s in seats:
+ row, u = table.get(s) or {}, _usage(s)
+ out[s + "_points"] = int(row.get("points", 0))
+ out[s + "_fouls"] = int(row.get("fouls", 0))
+ for k in METERED:
+ out[f"{s}_metered_{k}"] = int(u.get(k, 0))
+ return out
+ a, b, u = table.get("A") or {}, table.get("B") or {}, _usage("A")
+ out.update(level=level, won=int(bool(d.get("valid_trial")) and d.get("match_winner") == "A"),
+ points_for=int(a.get("points", 0)), points_against=int(b.get("points", 0)), fouls=int(a.get("fouls", 0)),
+ opponent_fouls=int(b.get("fouls", 0)),
+ session_ended=int(reason in ("no_show", "collected", "incomplete", "abandoned") and not f.get("done")),
+ transient_api_errors=int((d.get("transient_api_errors") or {}).get("A", 0)),
+ unrecovered_api_errors=int((d.get("unrecovered_api_errors") or {}).get("A", 0)),
+ metered_requests=int(u.get("requests", 0)), metered_input_tokens=int(u.get("input_tokens", 0)),
+ metered_output_tokens=int(u.get("output_tokens", 0)), rate_limit_retries=int(u.get("rate_limit_retries", 0)))
+ return out
diff --git a/scripts/roboolympics/shared/sports/airhockey/hockey.py b/scripts/roboolympics/shared/sports/airhockey/hockey.py
new file mode 100644
index 0000000000..b1a3a13db3
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/airhockey/hockey.py
@@ -0,0 +1,387 @@
+"""Two physical 7-axis iiwa arms on an air hockey table: fixed-step Cartesian execution and the referee.
+
+Robot dynamics are derived from AirHockeyChallenge (MIT, see scene/). The table is new and mesh-free. The referee
+follows the USAA Official Rules of Air Hockey (sport.toml [rulebook]) with the deviations listed there
+([[deviations]]): one game to 7 points, the seven-second rule (a foul: the puck goes to the opponent), dead-puck
+face-offs, a safety cap on the playing time with a stated last resort (no draws) and a 0.35 m goal mouth (D10).
+"""
+from __future__ import annotations
+
+import hashlib
+import json
+import math
+import os
+from pathlib import Path
+import xml.etree.ElementTree as ET
+
+import mujoco
+import numpy as np
+
+REVISION = 'airhockey-program-v4' # v4 (2026-10-08, review item B13): goal mouth 0.35 m (v3: 0.40 m, v2: 0.25 m)
+DT, PHYSICS_DT = .01, .001 # 10 ms control step (eai-standard-realtime/1.0), 1 kHz physics
+SUBSTEPS = round(DT / PHYSICS_DT)
+POINTS_TO_WIN = 7 # USAA I.1
+SEVEN_S = 7. # USAA I.10: seven seconds to shoot the puck across the centre line
+DEAD_S = 2. # dead puck: out of both robots' reach this long -> face-off
+LINE_S = 7. # dead puck: resting on the centre line this long -> face-off
+CAP_S = 120. # safety cap: at most this much playing time (game seconds) ...
+MAX_RALLIES = 40 # ... and at most this many rallies; then the last resort decides
+CAM_W, CAM_H = 320, 240
+LENGTH, WIDTH = 1.948, 1.038
+GOAL_DEFAULT = .35 # sport.toml deviation D10 (the AirHockeyChallenge table: .25)
+
+
+def goal_width():
+ """The goal mouth (m): GOAL_DEFAULT, or the experiment-only override RO_AIRHOCKEY_GOAL_M (0.2-0.6; the official
+ tasks never set it; plugin.REVISION and final.json record a non-default width)."""
+ v = os.environ.get('RO_AIRHOCKEY_GOAL_M', '').strip()
+ if not v: return GOAL_DEFAULT
+ g = float(v)
+ if not (math.isfinite(g) and .2 <= g <= .6): raise ValueError('RO_AIRHOCKEY_GOAL_M must be within 0.2-0.6 m')
+ return g
+
+
+GOAL = goal_width()
+PUCK_R, MALLET_R = .03165, .04815
+CONTACT = PUCK_R + MALLET_R
+PUCK_DAMPING = '.001' # N s/m on the 10 g puck: the air cushion's drag (about 10 % speed per second)
+BASE_X = 1.51 # robot bases at x = -1.51 (A) and +1.51 (B), y = 0
+REACH = 1.45 # mallet centre at most this far from its robot's base
+X_NEAR, X_FAR, Y_MAX = .05, .92, .47 # mallet centre workspace in its own half: X_NEAR <= |x| <= X_FAR, |y| <= Y_MAX
+HOME_X, SPOT_X = .82, .58 # mallet home and the puck's placement spot (|x|), in the own half
+MAX_SPEED, MAX_ACCEL = 2., 10. # the mallet's Cartesian trajectory limits (m/s, m/s^2)
+LEVELS = { # the scripted opponent (seat B of the single-player game): mallet
+ 1: dict(speed=.4, delay=15, guard=None, gain=0., tol=.25, aim=0., lead=False), # speed cap m/s, reaction delay
+ 2: dict(speed=.6, delay=10, guard=.80, gain=1., tol=.15, aim=0., lead=False), # steps, guard line |x| m, gain
+ 3: dict(speed=1., delay=6, guard=.80, gain=1., tol=.08, aim=.07, lead=False), # on the puck's y, line-up
+ 4: dict(speed=2., delay=3, guard=.80, gain=1., tol=.05, aim=.08, lead=True)} # tolerance rad, aim (y at the
+ # goal), crossing prediction
+SCENE = Path(__file__).with_name('scene')
+OWN = {'A': -1., 'B': 1.} # the sign of x in each seat's own half
+OTHER = {'A': 'B', 'B': 'A'}
+
+
+def source_sha():
+ h = hashlib.sha256(Path(__file__).read_bytes())
+ for f in sorted(SCENE.glob('*.xml')):
+ h.update(f.name.encode()); h.update(f.read_bytes())
+ return h.hexdigest()
+
+
+def scene_xml(seed=101):
+ root = ET.Element('mujoco', model='visual_iiwa_airhockey')
+ ET.SubElement(root, 'compiler', angle='radian', autolimits='true')
+ ET.SubElement(root, 'option', timestep=str(PHYSICS_DT), integrator='implicitfast', cone='elliptic', iterations='40')
+ visual = ET.SubElement(root, 'visual'); ET.SubElement(visual, 'global', offwidth='640', offheight='480')
+ ET.SubElement(visual, 'headlight', ambient='.5 .5 .5', diffuse='.5 .5 .5')
+ world = ET.SubElement(root, 'worldbody')
+ ET.SubElement(world, 'light', pos='0 0 3', dir='0 0 -1', directional='true', castshadow='false')
+ ET.SubElement(world, 'geom', name='table_surface', type='box', pos='0 0 -.045', size='1.07 .61 .045', rgba='.9 .92 .94 1', contype='0', conaffinity='0')
+ ET.SubElement(world, 'geom', name='floor', type='plane', pos='0 0 -.15', size='4 4 .1', rgba='.16 .2 .24 1', contype='0', conaffinity='0')
+ for side in (-1, 1):
+ ET.SubElement(world, 'geom', name=f'wall_side_{side}', type='box', pos=f'0 {side*(WIDTH/2+.025)} .035', size='1.07 .025 .035', rgba='.2 .25 .3 1', friction='0 0 0', solref='.0075 .1', solimp='.99 .999 .001')
+ for end in (-1, 1):
+ half = (WIDTH-GOAL)/4
+ ET.SubElement(world, 'geom', name=f'wall_end_{side}_{end}', type='box', pos=f'{end*(LENGTH/2+.025)} {side*(GOAL/2+half)} .035', size=f'.025 {half} .035', rgba='.2 .25 .3 1', friction='0 0 0', solref='.0075 .1', solimp='.99 .999 .001')
+ # Four public calibration markers outside the puck lane, plus a center line.
+ for i, (x, y) in enumerate([(-.9, -.46), (-.9, .46), (.9, -.46), (.9, .46)]):
+ ET.SubElement(world, 'geom', type='cylinder', pos=f'{x} {y} .001', size='.015 .001', rgba='1 .75 .03 1', contype='0', conaffinity='0')
+ ET.SubElement(world, 'geom', type='box', pos='0 0 .001', size='.002 .5 .001', rgba='.7 .72 .75 1', contype='0', conaffinity='0')
+ base = ET.SubElement(world, 'body', name='puck_base')
+ for name, kind, axis, damping in [('puck_x', 'slide', '1 0 0', PUCK_DAMPING), ('puck_y', 'slide', '0 1 0', PUCK_DAMPING), ('puck_yaw', 'hinge', '0 0 1', '0.000002')]:
+ ET.SubElement(base, 'joint', name=name, type=kind, axis=axis, damping=damping, limited='false')
+ ET.SubElement(base, 'inertial', pos='0 0 0', mass='.01', diaginertia='0.0000025 0.0000025 0.000005')
+ ET.SubElement(base, 'geom', name='puck', type='cylinder', pos='0 0 .012', size=f'{PUCK_R} .01', rgba='.95 .03 .04 1', friction='0 0 0', condim='4', solref='.0075 .1')
+ for seat, pos, axes in [('A', '0 -1.3 2.2', '1 0 0 0 .861 .509'), ('B', '0 1.3 2.2', '-1 0 0 0 -.861 .509')]:
+ ET.SubElement(world, 'camera', name=f'front_{seat}', pos=pos, xyaxes=axes, fovy='48')
+ ET.SubElement(world, 'camera', name='overview', pos='0 -2.3 2.5', xyaxes='1 0 0 0 .736 .677', fovy='55')
+ # Merge upstream robot defaults/world/actuators without any external assets.
+ for i in (1, 2):
+ robot = ET.parse(SCENE/f'iiwa{i}.xml').getroot()
+ for child in robot:
+ if child.tag == 'compiler': continue
+ if child.tag == 'worldbody':
+ for body in child: world.append(body)
+ elif child.tag == 'default':
+ if i == 1: root.append(child) # iiwa1.xml declares the shared classes (vis, robot)
+ elif child.tag == 'actuator':
+ acts = root.find('actuator')
+ if acts is None: acts = ET.SubElement(root, 'actuator')
+ for act in child: acts.append(act)
+ return ET.tostring(root, encoding='unicode')
+
+
+def workspace(seat, xy):
+ """The nearest point of the seat's mallet workspace (own half, X_NEAR <= |x| <= X_FAR, |y| <= Y_MAX, at most
+ REACH from its robot's base) to a point (approximately: box clip, then radial clip towards the base)."""
+ u, v = OWN[seat]*float(xy[0]), float(xy[1])
+ u, v = min(max(u, X_NEAR), X_FAR), min(max(v, -Y_MAX), Y_MAX)
+ d = math.hypot(BASE_X-u, v)
+ if d > REACH:
+ u, v = BASE_X-(BASE_X-u)*REACH/d, v*REACH/d
+ return [OWN[seat]*u, v]
+
+
+def reachable(seat, p):
+ """Whether the seat's mallet can touch a puck centred at p (a mallet centre in the workspace within CONTACT)."""
+ q = workspace(seat, p)
+ return math.hypot(float(p[0])-q[0], float(p[1])-q[1]) <= CONTACT-.005
+
+
+def in_workspace(seat, xy, eps=1e-4):
+ u, v = OWN[seat]*float(xy[0]), float(xy[1])
+ return X_NEAR-eps <= u <= X_FAR+eps and abs(v) <= Y_MAX+eps and math.hypot(BASE_X-u, v) <= REACH+eps
+
+
+def validate_action(body, seat):
+ """None for `none`; else the target [x, y]. Non-finite, wrong half or outside the workspace -> ValueError (400)."""
+ if body.get('type') == 'none': return None
+ if body.get('type', 'target') != 'target': raise ValueError('action type must be target or none')
+ values = [body.get('x'), body.get('y')]
+ if any(type(v) not in (int, float) or not math.isfinite(v) for v in values): raise ValueError('x,y must be finite numbers')
+ if seat not in ('A', 'B'): raise ValueError('unknown seat')
+ if OWN[seat]*values[0] <= 0: raise ValueError('mallet must stay in own half')
+ if not in_workspace(seat, values):
+ raise ValueError(f'target outside the mallet workspace ({X_NEAR} <= |x| <= {X_FAR}, |y| <= {Y_MAX}, '
+ f'at most {REACH} m from the robot base at ({OWN[seat]*BASE_X:+.2f}, 0))')
+ return [float(v) for v in values]
+
+
+class Hockey:
+ def __init__(self, seed=101, level=1, duel=False, first='A'):
+ if level not in (1, 2, 3, 4) or first not in ('A', 'B'): raise ValueError('invalid configuration')
+ self.seed, self.level, self.duel, self.first = seed, level, duel, first
+ self.source_sha = source_sha(); self.model = mujoco.MjModel.from_xml_string(scene_xml())
+ self.data = mujoco.MjData(self.model); self.ik = mujoco.MjData(self.model)
+ self.rng = np.random.default_rng(seed)
+ self.k = 0 # control steps of play (the world's clock; frozen time does not count)
+ self.point_k = 0 # control steps since the current point started
+ self.results = [] # one entry per rally: how it ended (goal, foul, dead puck, time cap)
+ self.done = self.awaiting_review = False
+ self.decided_by = None # 'score' | 'cap_points' | 'cap_last_goal' | 'cap_territory' | 'cap_first_possession'
+ self.rail_contact_steps = self.contact_steps = 0
+ self.half_steps = {'A': 0, 'B': 0} # steps the puck spent wholly in each half (the cap's territory measure)
+ self.ids = {}; self.qadr = {}; self.dadr = {}; self.acts = {}; self.targets = {}
+ for s, n in [('A', 1), ('B', 2)]:
+ names = [f'iiwa_{n}/joint_{j}' for j in range(1, 8)]+[f'iiwa_{n}/striker_joint_{j}' for j in (1, 2)]
+ self.ids[s] = [self.model.joint(name).id for name in names]
+ self.qadr[s] = self.model.jnt_qposadr[self.ids[s]]; self.dadr[s] = self.model.jnt_dofadr[self.ids[s]]
+ self.acts[s] = [self.model.actuator(name).id for name in names]
+ self.ee = {'A': self.model.geom('iiwa_1/ee').id, 'B': self.model.geom('iiwa_2/ee').id}
+ self.mallet_body = {'A': self.model.body('iiwa_1/striker_mallet').id, 'B': self.model.body('iiwa_2/striker_mallet').id}
+ self.puck_geom = self.model.geom('puck').id
+ self.wall_geoms = {i for i in range(self.model.ngeom) if (self.model.geom(i).name or '').startswith('wall_')}
+ self.px = int(self.model.jnt_qposadr[self.model.joint('puck_x').id]); self.py = self.px+1
+ self.pvx = int(self.model.jnt_dofadr[self.model.joint('puck_x').id])
+ mujoco.mj_resetData(self.model, self.data)
+ self.restart(self.first, 'start')
+
+ # ---------------------------------------------------------------- state
+ def position(self, seat): return self.data.geom_xpos[self.ee[seat]].copy()
+
+ def puck(self): return np.array([self.data.qpos[self.px], self.data.qpos[self.py]])
+
+ def puck_velocity(self): return np.array([self.data.qvel[self.pvx], self.data.qvel[self.pvx+1]])
+
+ def restart(self, holder, why):
+ """Play stops: both mallets go back to their home positions (instantly) and the referee places the puck at
+ rest, at the holder's spot in its own half (seeded y), or at the table centre for a face-off (holder None)."""
+ puck = [0., 0.] if holder is None else [OWN[holder]*SPOT_X, round(float(self.rng.uniform(-.18, .18)), 6)]
+ self.data.qvel[:] = 0
+ for s in ('A', 'B'):
+ self.data.qpos[self.qadr[s]] = np.array([0, -.1961, 0, -1.8436, 0, .9704, 0, 0, 0.])
+ self.data.qpos[self.px], self.data.qpos[self.py], self.data.qpos[self.py+1] = puck[0], puck[1], 0.
+ mujoco.mj_forward(self.model, self.data)
+ for s in ('A', 'B'):
+ self.targets[s] = np.array([OWN[s]*HOME_X, 0.])
+ self.data.qpos[self.qadr[s]] = self.solve(s, self.data.qpos[self.qadr[s]].copy(), self.targets[s], 80)
+ self.data.ctrl[:] = 0
+ self.commands = {s: list(self.targets[s]) for s in ('A', 'B')}
+ self.qtarget = {s: self.data.qpos[self.qadr[s]].copy() for s in ('A', 'B')}
+ self.cart_velocity = {s: np.zeros(2) for s in ('A', 'B')}
+ self.side, self.side_steps = holder, 0 # possession: the half the puck is wholly in
+ self.line_steps = self.dead_steps = 0
+ self.last_touch = None
+ self.script = dict(until=-1, target=None, hist=[])
+ self.restart_k, self.restart_why = self.k, why
+ mujoco.mj_forward(self.model, self.data)
+
+ def solve(self, seat, q, target, iterations):
+ adr = self.qadr[seat]; dof = self.dadr[seat]
+ desired = np.diag([-1., 1., -1.]) if seat == 'A' else np.diag([1., -1., -1.])
+ body = self.mallet_body[seat]
+ jp = np.zeros((3, self.model.nv)); jr = np.zeros_like(jp)
+ self.ik.qpos[:] = self.data.qpos
+ ranges = self.model.jnt_range[self.ids[seat]]
+ for _ in range(iterations):
+ self.ik.qpos[adr] = q; mujoco.mj_kinematics(self.model, self.ik); mujoco.mj_comPos(self.model, self.ik)
+ current = self.ik.xmat[body].reshape(3, 3)
+ err = np.r_[np.array([target[0], target[1], .0645])-self.ik.xpos[body],
+ sum(np.cross(current[:, i], desired[:, i]) for i in range(3))*.5]
+ mujoco.mj_jacBody(self.model, self.ik, jp, jr, body)
+ jac = np.vstack([jp[:, dof], jr[:, dof]])
+ delta = [email protected]([email protected]+.001*np.eye(6), err)
+ q = q+np.clip(delta, -.08, .08)
+ q = np.clip(q, ranges[:, 0]+.01, ranges[:, 1]-.01)
+ return q
+
+ def set_command(self, seat, command):
+ if command is None: self.commands[seat] = workspace(seat, self.position(seat)[:2]); return
+ if OWN[seat]*command[0] <= 0: raise ValueError('mallet must stay in own half')
+ self.commands[seat] = list(command)
+
+ # ---------------------------------------------------------------- scripted opponent (single player, seat B)
+ def scripted(self, seat='B'):
+ """Trusted referee-side opponent, from the true puck position `delay` steps ago: guards its goal while the
+ puck is in the other half or coming at it fast, else lines up behind the puck and strikes it at the other
+ goal. Levels differ in mallet speed, reaction delay, how far the guard follows the puck, how precisely it lines
+ up and where it aims (LEVELS)."""
+ lv = LEVELS[self.level]; sg = OWN[seat]; sc = self.script
+ sc['hist'].append(self.puck()); sc['hist'] = sc['hist'][-(lv['delay']+2):]
+ P = sc['hist'][0]; W = (sc['hist'][1]-sc['hist'][0])/DT if len(sc['hist']) > 1 else np.zeros(2)
+ p = np.array([sg*P[0], P[1]]); w = np.array([sg*W[0], W[1]]) # local: u > 0 is the own half
+ m = self.position(seat)[:2]; m = np.array([sg*m[0], m[1]])
+ p = p+w*lv['delay']*DT # now, by its own extrapolation
+ world = lambda u, v: workspace(seat, [sg*u, v])
+ if p[0] < -.02 or w[0] > .15: # guard: at its guard line, following the puck's y (or its crossing)
+ sc['until'] = -1
+ if lv['guard'] is None: # level 1 does not guard: it stays where it is
+ return world(*m)
+ y = p[1]
+ if lv['lead'] and w[0] > .1:
+ y = p[1]+w[1]*(lv['guard']-p[0])/w[0]
+ r = WIDTH/2-PUCK_R; y = (y+r) % (4*r); y = (y if y < 2*r else 4*r-y)-r # rail bounces folded in
+ return world(lv['guard'], float(np.clip(y*lv['gain'], -.42, .42)))
+ if self.k < sc['until']: return sc['target']
+ aim = 0. if not lv['aim'] else (lv['aim'] if p[1] < 0 else -lv['aim']) # the far corner of the goal
+ d = np.array([-1.05, aim])-p; d /= np.linalg.norm(d)
+ rel = p-m; dist = np.linalg.norm(rel)
+ if .12 < dist < .3 and float(rel@d)/dist > math.cos(lv['tol']): # lined up: strike through the puck
+ sc['target'] = world(*(m+rel/dist*(dist+.25))); sc['until'] = self.k+40
+ return sc['target']
+ return world(*(p-d*.18))
+
+ # ---------------------------------------------------------------- one control step
+ def step(self):
+ if self.done or self.awaiting_review: raise RuntimeError('world frozen')
+ if not self.duel: self.set_command('B', self.scripted('B'))
+ qvelocity = {}; qprevious = {}
+ for s in ('A', 'B'):
+ previous_q = self.qtarget[s].copy(); qprevious[s] = previous_q
+ target = np.array(self.commands[s]); delta = target-self.targets[s]
+ vmax = MAX_SPEED if s == 'A' or self.duel else LEVELS[self.level]['speed']
+ accel = 80*delta-18*self.cart_velocity[s]
+ accel *= min(1., MAX_ACCEL/max(1e-9, np.linalg.norm(accel)))
+ self.cart_velocity[s] += accel*DT
+ self.cart_velocity[s] *= min(1., vmax/max(1e-9, np.linalg.norm(self.cart_velocity[s])))
+ self.targets[s] += self.cart_velocity[s]*DT
+ self.qtarget[s] = self.solve(s, self.qtarget[s], self.targets[s], 4)
+ qvelocity[s] = np.clip((self.qtarget[s]-previous_q)/DT, -3., 3.)
+ contact = set()
+ mass = np.zeros((self.model.nv, self.model.nv))
+ for substep in range(SUBSTEPS):
+ mujoco.mj_forward(self.model, self.data)
+ mujoco.mj_fullM(self.model, mass, self.data.qM)
+ for s in ('A', 'B'):
+ q = self.data.qpos[self.qadr[s]]; v = self.data.qvel[self.dadr[s]]
+ reference = qprevious[s]+(self.qtarget[s]-qprevious[s])*(substep+1)/SUBSTEPS
+ acceleration = np.clip(100*(reference-q)+20*(qvelocity[s]-v), -50, 50)
+ torque = mass[np.ix_(self.dadr[s], self.dadr[s])]@acceleration+self.data.qfrc_bias[self.dadr[s]]
+ bounds = self.model.actuator_ctrlrange[self.acts[s]]
+ self.data.ctrl[self.acts[s]] = np.clip(torque, bounds[:, 0], bounds[:, 1])
+ mujoco.mj_step(self.model, self.data)
+ for i in range(self.data.ncon):
+ c = self.data.contact[i]; g = (int(c.geom1), int(c.geom2))
+ if self.puck_geom in g:
+ for s in ('A', 'B'):
+ if self.ee[s] in g: contact.add(s)
+ if g[0] in self.wall_geoms or g[1] in self.wall_geoms: contact.add('wall')
+ self.k += 1; self.point_k += 1
+ for s in ('A', 'B'):
+ if s in contact: self.last_touch = s
+ if contact & {'A', 'B'}: self.contact_steps += 1
+ if 'wall' in contact: self.rail_contact_steps += 1
+ self.referee()
+ return contact
+
+ def referee(self):
+ """After each control step: a goal, a seven-second foul or a dead puck ends the rally; the world then freezes
+ for the review and the next rally starts from the placement the rules give (ready())."""
+ p = self.puck()
+ if abs(p[0]) > LENGTH/2+PUCK_R and abs(p[1]) <= GOAL/2-PUCK_R: # wholly in a goal (USAA I.2, V.1)
+ scorer = 'A' if p[0] > 0 else 'B'
+ return self.end_rally('goal', winner=scorer, next=OTHER[scorer], # the scored-upon serves (I.4)
+ own_goal=self.last_touch == OTHER[scorer])
+ side = 'A' if p[0] < -PUCK_R else ('B' if p[0] > PUCK_R else None) # on the centre line: nobody's (I.11)
+ if side:
+ self.half_steps[side] += 1
+ self.line_steps = 0
+ if side != self.side: self.side, self.side_steps = side, 0
+ self.side_steps += 1
+ else:
+ self.line_steps += 1
+ self.dead_steps = 0 if (reachable('A', p) or reachable('B', p)) else self.dead_steps+1
+ if self.dead_steps*DT >= DEAD_S-1e-9:
+ return self.end_rally('dead_puck', where='out_of_reach', next=None)
+ if self.line_steps*DT >= LINE_S-1e-9:
+ return self.end_rally('dead_puck', where='centre_line', next=None)
+ if side and self.side_steps*DT >= SEVEN_S-1e-9: # a foul: forfeiture of the puck (VI.1)
+ return self.end_rally('seven_second_foul', guilty=side, next=OTHER[side])
+ if self.k*DT >= CAP_S-1e-9:
+ return self.end_rally('time_cap', next=None)
+
+ def end_rally(self, how, winner=None, guilty=None, next=None, **extra):
+ self.results.append(dict(rally=len(self.results)+1, how=how, winner=winner, guilty=guilty,
+ next='faceoff' if next is None else next, k=self.k, steps=self.point_k, **extra))
+ sc = self.scores()
+ if max(sc['A']['points'], sc['B']['points']) >= POINTS_TO_WIN:
+ self.done, self.decided_by = True, 'score'
+ elif how == 'time_cap' or self.k*DT >= CAP_S-1e-9 or len(self.results) >= MAX_RALLIES:
+ self.done, self.decided_by = True, self.cap_decision()
+ else:
+ self.awaiting_review = True
+
+ def cap_decision(self):
+ sc = self.scores(); a, b = sc['A']['points'], sc['B']['points']
+ if a != b: return 'cap_points'
+ if any(r['how'] == 'goal' for r in self.results): return 'cap_last_goal'
+ if self.half_steps['A'] != self.half_steps['B']: return 'cap_territory'
+ return 'cap_first_possession'
+
+ def ready(self):
+ if not self.awaiting_review: raise ValueError('not in review')
+ self.awaiting_review = False; self.point_k = 0
+ nxt = self.results[-1]['next']
+ self.restart(None if nxt == 'faceoff' else nxt, self.results[-1]['how'])
+
+ # ---------------------------------------------------------------- result
+ def scores(self):
+ return {s: dict(points=sum(r['how'] == 'goal' and r['winner'] == s for r in self.results),
+ fouls=sum(r['guilty'] == s for r in self.results)) for s in ('A', 'B')}
+
+ def winner(self):
+ """'A' or 'B' once the game is over (never a draw), else None."""
+ if not self.done: return None
+ sc = self.scores(); a, b = sc['A']['points'], sc['B']['points']
+ if a != b: return 'A' if a > b else 'B'
+ goals = [r for r in self.results if r['how'] == 'goal']
+ if goals: return goals[-1]['winner'] # the winner of the last point
+ if self.half_steps['A'] != self.half_steps['B']: # 0:0: less time with the puck in
+ return 'A' if self.half_steps['A'] < self.half_steps['B'] else 'B' # one's own half (more pressure)
+ return OTHER[self.first] # identical: the player who did not have the first possession
+
+ def digest(self):
+ state = np.empty(mujoco.mj_stateSize(self.model, mujoco.mjtState.mjSTATE_INTEGRATION))
+ mujoco.mj_getState(self.model, self.data, state, mujoco.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha256(state.tobytes())
+ h.update(json.dumps(dict(k=self.k, point_k=self.point_k, results=self.results,
+ commands=self.commands, targets={s: t.tolist() for s, t in self.targets.items()},
+ cart_velocity={s: t.tolist() for s, t in self.cart_velocity.items()},
+ qtarget={s: q.tolist() for s, q in self.qtarget.items()}, side=self.side,
+ side_steps=self.side_steps, line_steps=self.line_steps, dead_steps=self.dead_steps,
+ half_steps=self.half_steps, last_touch=self.last_touch, rng=self.rng.bit_generator.state,
+ script=dict(until=self.script['until'], target=self.script['target'],
+ hist=[x.tolist() for x in self.script['hist']]),
+ contacts=self.contact_steps, rails=self.rail_contact_steps, done=self.done,
+ decided_by=self.decided_by, awaiting_review=self.awaiting_review), sort_keys=True).encode())
+ return h.hexdigest()
diff --git a/scripts/roboolympics/shared/sports/airhockey/plugin.py b/scripts/roboolympics/shared/sports/airhockey/plugin.py
new file mode 100644
index 0000000000..126bbaae02
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/airhockey/plugin.py
@@ -0,0 +1,241 @@
+"""airhockey: robot air hockey after the USAA rules on the v0.2 core (docs/framework_zh.md §4.2). Migrated from the
+legacy tree (scripts/olympiad/airhockey, scripts/olympiad/shared/airhockey/sim) in stage 2; the simulator hockey.py
+(two physically simulated KUKA iiwa arms with mallets, the Cartesian path, IK and torque controller, the puck, the
+referee and the scripted opponent) and its robot files (scene/) are the legacy ones except the goal mouth, 0.35 m
+since revision v4 (sport.toml D10; v3: 0.40 m; the legacy recordings of revision v2 no longer replay, golden/ holds
+native recordings). The four groups of contract ② (core/sport.py):
+
+ world hockey.Hockey: one table, both arms in one MuJoCo world (physics 1 kHz); one control step (10 ms) =
+ Hockey.step(): both arms' Cartesian paths, IK and joint torques, the scripted opponent (format match,
+ seat B inside the world) and the referee after the step
+ actions low only: {"type": "target", x, y} (the mallet's target in the own workspace, hockey.validate_action)
+ or {"type": "none"} (hold where the mallet is) -> Hockey.set_command, at the next control step
+ referee a unit = a rally (a goal, a seven-second foul or a dead puck ends it; the world freezes for the reviews);
+ first to 7 goals, else the safety cap (120 s of play or 40 rallies) and Hockey.winner()'s chain:
+ goals -> the last goal -> territory -> the player who did not have the first possession
+ observation observe = the seat's own arm and mallet and the referee's calls (score, rallies; no puck or opponent
+ coordinate); cameras = the seat's fixed camera above and behind its end (the legacy front_<seat>),
+ drawn by the task's renderer from scene() (hockey.scene_xml) and render_state() (the qpos)
+"""
+from __future__ import annotations
+
+import os
+
+import numpy as np
+
+import hockey as H
+from core.sport import FINISHED, PLAYING, UNIT_OVER, LowLayer, MatchBase, Phase, Refused, check_command
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+REVISION = "airhockey-program-v4+players-25k+core-0.2" + ("" if H.GOAL == H.GOAL_DEFAULT else f"+goal{H.GOAL:g}m") # experiment knob
+NUM = {"type": "number"}
+SCHEMA = {
+ "target": {"x": {**NUM, "min": -H.X_FAR, "max": H.X_FAR, "unit": "m",
+ "doc": f"the mallet centre's target x (world frame); own half only: {H.X_NEAR} <= |x| <= {H.X_FAR}"},
+ "y": {**NUM, "min": -H.Y_MAX, "max": H.Y_MAX, "unit": "m",
+ "doc": f"target y; |y| <= {H.Y_MAX} and at most {H.REACH} m from your robot's base"}},
+ "none": {}}
+TIEBREAKS = ("goals", "last_goal", "territory", "first_possession")
+LEGACY_DECIDED = {"score": "goals", "cap_points": "goals", "cap_last_goal": "last_goal",
+ "cap_territory": "territory", "cap_first_possession": "first_possession"}
+CAM = {"width": H.CAM_W, "height": H.CAM_H, "fovy_deg": 48}
+
+
+def front_camera(seat: str) -> dict:
+ """The legacy fixed camera front_<seat> of hockey.scene_xml (pos, xyaxes) as a camera definition: forward is
+ -(x_axis x y_axis), up the y axis."""
+ pos, x, y = {"A": ((0, -1.3, 2.2), (1, 0, 0), (0, .861, .509)),
+ "B": ((0, 1.3, 2.2), (-1, 0, 0), (0, -.861, .509))}[seat]
+ fwd = -np.cross(x, y)
+ return {"name": "front", "pos": list(map(float, pos)), "lookat": (np.add(pos, fwd)).tolist(),
+ "up": list(map(float, y)), **CAM}
+
+
+def is_single(cfg) -> bool:
+ return len(cfg.seats) == 1
+
+
+class AirHockey(MatchBase):
+ def __init__(self, cfg):
+ self.cfg, self.seats = cfg, tuple(cfg.seats)
+ if self.seats not in (("A",), ("A", "B")):
+ raise ValueError("airhockey: one seat (A, against the scripted opponent) or two (A, B)")
+ self.single = is_single(cfg)
+ level = int(cfg.level or 1) if self.single else 1
+ if level not in H.LEVELS:
+ raise ValueError("level must be 1, 2, 3 or 4")
+ first = cfg.first or "A"
+ if first not in ("A", "B"):
+ raise ValueError("first must be A or B")
+ self.h = H.Hockey(seed=int(cfg.seed), level=level, duel=not self.single, first=first)
+ self.dt = H.DT
+ self.side = {"A": "A", "B": "opponent" if self.single else "B"} # hockey seat -> side of the match
+
+ @property
+ def k(self):
+ return self.h.k
+
+ # ------------------------------------------------------------------ world
+ def step(self):
+ h = self.h
+ n = len(h.results)
+ contact = h.step()
+ events = [{"kind": "contact", "with": sorted(contact)}] if contact else []
+ if len(h.results) > n:
+ events.append({"kind": "rally", **h.results[-1]})
+ return events
+
+ def state_digest(self):
+ """hockey.Hockey.digest(): the full MuJoCo integration state, the controllers, the RNG, the scripted opponent
+ and the referee."""
+ return self.h.digest()
+
+ # ------------------------------------------------------------------ actions
+ def schema(self, seat):
+ return SCHEMA
+
+ def apply(self, seat, cmd):
+ h = self.h
+ if h.done or h.awaiting_review:
+ return {"rejected": "the world is frozen"}
+ h.set_command(seat, None if cmd["type"] == "none" else [cmd["x"], cmd["y"]])
+ return {"command": [round(float(v), 5) for v in h.commands[seat]]}
+
+ # ------------------------------------------------------------------ referee
+ def phase(self):
+ h = self.h
+ if h.done:
+ return Phase(FINISHED, reason="match_over")
+ if h.awaiting_review:
+ return Phase(UNIT_OVER, review=self.seats, reason=h.results[-1]["how"])
+ return Phase(PLAYING)
+
+ def resume(self):
+ self.h.ready()
+
+ def unit(self):
+ return len(self.h.results)
+
+ def scores(self):
+ sc = self.h.scores()
+ return {self.side[s]: sc[s]["points"] for s in ("A", "B")}
+
+ def tiebreaks(self):
+ """Hockey.winner() split into its named steps (USAA I.1 first to 7; the safety cap's chain)."""
+ def goals(m):
+ sc = m.h.scores()
+ a, b = sc["A"]["points"], sc["B"]["points"]
+ return None if a == b else m.side["A" if a > b else "B"]
+
+ def last_goal(m):
+ g = [r for r in m.h.results if r["how"] == "goal"]
+ return m.side[g[-1]["winner"]] if g else None
+
+ def territory(m):
+ hs = m.h.half_steps
+ return None if hs["A"] == hs["B"] else m.side["A" if hs["A"] < hs["B"] else "B"]
+
+ def first_possession(m):
+ return m.side[H.OTHER[m.h.first]]
+ return list(zip(TIEBREAKS, (goals, last_goal, territory, first_possession)))
+
+ # ------------------------------------------------------------------ observation
+ def rally(self, res):
+ sc = {s: sum(r["how"] == "goal" and r["winner"] == s for r in self.h.results[:res["rally"]]) for s in "AB"}
+ return {"rally": res["rally"], "how": res["how"], "scored": res["winner"], "fouled": res["guilty"],
+ "next_puck": res["next"], "score": sc, "t_play": round(res["k"] * H.DT, 2)}
+
+ def observe(self, seat, query=None):
+ h = self.h
+ frozen = h.awaiting_review or h.done
+ return {"rally": len(h.results) + (0 if frozen else 1), "t_play": round(h.k * H.DT, 3),
+ "play_time_left_s": round(max(0.0, H.CAP_S - h.k * H.DT), 3), "score": h.scores(),
+ "own": {"mallet_xyz": [round(float(x), 5) for x in h.position(seat)],
+ "command": [round(float(x), 5) for x in h.commands[seat]],
+ "joint_position": [round(float(x), 5) for x in h.data.qpos[h.qadr[seat]]],
+ "joint_velocity": [round(float(x), 5) for x in h.data.qvel[h.dadr[seat]]]},
+ "rallies": [self.rally(r) for r in h.results],
+ "last_rally": self.rally(h.results[-1]) if h.results else None}
+
+ def cameras(self, seat, query=None):
+ return [front_camera(seat)]
+
+ def render_state(self):
+ return {"qpos": np.asarray(self.h.data.qpos).tolist()}
+
+ def final_fields(self):
+ h = self.h
+ return {"hockey_revision": H.REVISION, "goal_width_m": H.GOAL, "level": h.level, "first_player": h.first, "duel": h.duel,
+ "scores": h.scores(), "results": h.results, "decided_by": h.decided_by,
+ "match_limit": bool(h.decided_by and h.decided_by.startswith("cap")), "done": h.done,
+ "half_steps": dict(h.half_steps), "rail_contact_steps": h.rail_contact_steps,
+ "mallet_contact_steps": h.contact_steps}
+
+
+class TargetLayer(LowLayer):
+ """The only action level: the schema's types and finite numbers (core.sport.check_command), then the legacy
+ hockey.validate_action (own half, the workspace box and the reach; 400 otherwise). A body without a type is a
+ target, as in the legacy `POST /act {"x": X, "y": Y}`."""
+
+ def __init__(self):
+ super().__init__(None)
+
+ def parse(self, seat, body, match, ctx):
+ if isinstance(body, dict) and "type" not in body and "x" in body:
+ body = {"type": "target", **body}
+ cmd = check_command(SCHEMA, body)
+ if "entity" in cmd:
+ raise Refused("the mallet takes no entity")
+ if seat not in match.seats:
+ raise Refused("unknown seat")
+ if cmd["type"] == "target":
+ try:
+ H.validate_action({"type": "target", "x": cmd["x"], "y": cmd["y"]}, seat)
+ except ValueError as exc:
+ raise Refused(str(exc)) from exc
+ return cmd
+
+
+class AirHockeySport:
+ name, protocol, revision, source_dirs, workers = "airhockey", "realtime", REVISION, [HERE], ("render",)
+
+ def build(self, cfg):
+ return AirHockey(cfg)
+
+ def action_layer(self, level):
+ return TargetLayer()
+
+ def scene(self, cfg):
+ from renderers.base import Scene
+ return Scene(xml=H.scene_xml())
+
+ def spec(self, cfg, seat, match):
+ """hockey.py's public constants (no seed): the action workspace, the limits, the geometry and the timing."""
+ h = match.h
+ out = {"match": {"first_player": h.first, "points_to_win": H.POINTS_TO_WIN,
+ **({"opponent_level": h.level, "opponent_seat": "B"} if match.single else {})},
+ "workspace": {"x_abs_m": [H.X_NEAR, H.X_FAR], "y_abs_max_m": H.Y_MAX, "reach_m": H.REACH,
+ "robot_base": {"A": [-H.BASE_X, 0.0], "B": [H.BASE_X, 0.0]}},
+ "mallet_path": {"max_speed_m_s": H.MAX_SPEED, "max_accel_m_s2": H.MAX_ACCEL,
+ "takes_effect": "at the next control step", "hold": "until replaced"},
+ "referee_timing": {"seven_second_rule_s": H.SEVEN_S, "dead_puck_s": H.DEAD_S, "centre_line_s": H.LINE_S,
+ "play_time_cap_s": H.CAP_S, "max_rallies": H.MAX_RALLIES},
+ "geometry": {"length_m": H.LENGTH, "width_m": H.WIDTH, "goal_width_m": H.GOAL,
+ "puck_radius_m": H.PUCK_R, "mallet_radius_m": H.MALLET_R, "puck_plane_z_m": 0.012,
+ "mallet_centre_z_m": 0.0645, "home": {"A": [-H.HOME_X, 0.0], "B": [H.HOME_X, 0.0]},
+ "puck_spot_abs_x_m": H.SPOT_X}}
+ if H.GOAL != H.GOAL_DEFAULT: # the experiment knob RO_AIRHOCKEY_GOAL_M: the rules text follows
+ g = H.GOAL
+ out["table"] = (f"metres, seconds; the table frame: x along the table (seat A's end at x < 0, seat B's at "
+ f"x > 0), y across, z up. Playing surface 1.948 x 1.038 m (|x| <= 0.974, |y| <= 0.519), "
+ f"surrounded by rails; a goal mouth {g:g} m wide (|y| <= {g / 2:g}) in the middle of each "
+ f"end rail; the centre line is x = 0 (experiment setting: this goal width replaces the "
+ f"default {H.GOAL_DEFAULT:g} m)")
+ return out
+
+ def players(self):
+ import builtin_players as bp
+ return {"reference": bp.Reference, "random": bp.Random}
+
+
+SPORT = AirHockeySport()
diff --git a/scripts/roboolympics/shared/sports/airhockey/presentation/presentation.toml b/scripts/roboolympics/shared/sports/airhockey/presentation/presentation.toml
new file mode 100644
index 0000000000..b2ebf396ee
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/airhockey/presentation/presentation.toml
@@ -0,0 +1,17 @@
+# Appearance of air hockey's robots (docs/framework_zh.md §3.1, renderer rule 6; renderers/presentation/__init__.py):
+# the KUKA LBR iiwa 14's visual meshes on the arm's bodies, same kinematics. Since revision airhockey-program-v4 /
+# players-25k the players' images use it too (`players`): tools/sportlib bundles this directory and the 25k level of
+# detail of the meshes (renderers/presentation/lod.json, sha256-pinned, licence kept) into the simulator, and the core's
+# camera worker draws the players' scene (core/observe.players_scene), so they are part of source_sha; spectator
+# re-renders from a checkout use the full meshes.
+[presentation]
+version = 2
+label = "KUKA LBR iiwa 14 visual meshes (MuJoCo Menagerie)"
+players = "25k" # the players' images: the meshes decimated to ~25k triangles per arm
+
+[[presentation.robot]]
+model = "kuka_iiwa_14" # renderers/presentation/menagerie.json (fetched, sha256-pinned)
+bodies = '^iiwa_[12]/(?P<x>base|link)_?(?P<n>[1-7]?)$'
+body = "{x}{n}" # iiwa_1/base -> base, iiwa_1/link_3 -> link3 (the challenge's frames are Menagerie's)
+hide = "all" # the arm's capsules move to the hidden group 3 ...
+hide_bodies = '^iiwa_[12]/(base|link_[1-6])$' # ... but link_7 keeps its capsule: the striker's 0.585 m shaft
diff --git a/scripts/roboolympics/shared/sports/airhockey/scene/ORIGIN.md b/scripts/roboolympics/shared/sports/airhockey/scene/ORIGIN.md
new file mode 100644
index 0000000000..b9b4146c7c
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/airhockey/scene/ORIGIN.md
@@ -0,0 +1 @@
+Robot joint transforms, inertias, limits and motors derived from AirHockeyChallenge/air_hockey_challenge, commit 34729081d4327141dcf560c0fb8274cd4882e82c, qualifying-2025. MIT license retained. Visual meshes replaced by self-authored capsule primitives; no external mesh files. New benchmark table/cameras/referee/controllers are not the official challenge tournament.
diff --git a/scripts/roboolympics/shared/sports/airhockey/scene/UPSTREAM_LICENSE b/scripts/roboolympics/shared/sports/airhockey/scene/UPSTREAM_LICENSE
new file mode 100644
index 0000000000..4cbe8acdef
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/airhockey/scene/UPSTREAM_LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2025 Atalay Donat, Puze Liu, Jonas Guenster, Davide Tateo.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/scripts/roboolympics/shared/sports/airhockey/scene/iiwa1.xml b/scripts/roboolympics/shared/sports/airhockey/scene/iiwa1.xml
new file mode 100644
index 0000000000..94d6709c9f
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/airhockey/scene/iiwa1.xml
@@ -0,0 +1,66 @@
+<mujoco model="iiwa_1">
+ <compiler angle="radian" autolimits="true" />
+
+ <default>
+ <default class="vis">
+ <geom contype="0" conaffinity="0" />
+ </default>
+ <default class="robot">
+ <geom condim="4" solref="0.02 0.3" priority="2" />
+ </default>
+ </default>
+ <worldbody>
+ <body name="iiwa_1/base" pos="-1.51 0 -0.1">
+ <body name="iiwa_1/link_1" pos="0 0 0.1575">
+ <inertial pos="4.007709e-06 -0.033936 0.122467" mass="8.240527" fullinertia="0.021981 0.022182 0.008234 -2.897243e-07 6.3165236e-07 0.003285" />
+ <joint name="iiwa_1/joint_1" pos="0 0 0" axis="0 0 1" range="-2.96706 2.96706" damping="0.33032" frictionloss="0.384477" />
+ <body name="iiwa_1/link_2" pos="0 0 0.2025" quat="0 0 0.707107 0.707107">
+ <inertial pos="0.003402 0.034792 0.046725" mass="6.357896" fullinertia="0.015565 0.005180 0.015484 -4.147301e-06 1.192255e-05 0.002538" />
+ <joint name="iiwa_1/joint_2" pos="0 0 0" axis="0 0 1" range="-2.0944 2.0944" damping="0.21216" frictionloss="0.496333" />
+ <body name="iiwa_1/link_3" pos="0 0.2045 0" quat="0 0 0.707107 0.707107">
+ <inertial pos="-0.001452 0.031526 0.133584" mass="4.042756" fullinertia="0.010914 0.010381 0.003139 -3.540575e-06 -9.059062e-06 -0.002128" />
+ <joint name="iiwa_1/joint_3" pos="0 0 0" axis="0 0 1" range="-2.96706 2.96706" damping="0.1" frictionloss="0.173951" />
+ <body name="iiwa_1/link_4" pos="0 0 0.2155" quat="0.707107 0.707107 0 0">
+ <inertial pos="-0.002527 0.053508 0.037205" mass="3.642249" fullinertia="0.007536 0.002538 0.007206 -5.707028e-06 2.781894e-06 0.001256" />
+ <joint name="iiwa_1/joint_4" pos="0 0 0" axis="0 0 1" range="-2.0944 2.0944" damping="0.219041" frictionloss="0.3751" />
+ <body name="iiwa_1/link_5" pos="0 0.1845 0" quat="0 0 0.707107 0.707107">
+ <inertial pos="0.001855 0.024573 0.080131" mass="2.580896" fullinertia="0.005201 0.004488 0.002242 1.089316e-07 9.035623e-07 -0.001613" />
+ <joint name="iiwa_1/joint_5" pos="0 0 0" axis="0 0 1" range="-2.96706 2.96706" damping="0.185923" frictionloss="0.481099" />
+ <body name="iiwa_1/link_6" pos="0 0 0.2155" quat="0.707107 0.707107 0 0">
+ <inertial pos="-0.001739 -0.001973 -0.002502" mass="2.760564" fullinertia="0.002534 0.001821 0.002393 -1.311766e-06 9.508242e-07 0.000134" />
+ <joint name="iiwa_1/joint_6" pos="0 0 0" axis="0 0 1" range="-2.0944 2.0944" damping="0.1" frictionloss="0.196149" />
+ <body name="iiwa_1/link_7" pos="0 0.081 0" quat="0 0 0.707107 0.707107">
+ <inertial pos="0.000735 0.000387 0.026460" mass="1.285417" fullinertia="0.000151 0.000150 0.000187 -7.223100e-08 2.038333e-06 -3.396830e-07" />
+ <joint name="iiwa_1/joint_7" pos="0 0 0" axis="0 0 1" range="-3.05433 3.05433" damping="0.1" frictionloss="0.299238" armature="0.01" />
+ <body name="iiwa_1/striker_joint_link" pos="0 0 0.585">
+ <inertial pos="0 0 0" mass="0.1" diaginertia="0.001 0.001 0.001" />
+ <body name="iiwa_1/striker_mallet" pos="0 0 0">
+ <inertial pos="0 0 0.0682827" mass="0.283" diaginertia="0.005 0.005 0.005" />
+ <joint name="iiwa_1/striker_joint_1" pos="0 0 0" axis="0 1 0" range="-1.5708 1.5708" damping="0.0" />
+ <joint name="iiwa_1/striker_joint_2" pos="0 0 0" axis="1 0 0" range="-1.5708 1.5708" damping="0.0" />
+ <geom name="iiwa_1/ee" type="cylinder" rgba=".1 .3 .9 1" size="0.04815 0.03" pos="0 0 0.0505" friction="0 0 0" class="robot" />
+ </body>
+ </body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.0 0.585" size=".028" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.081 0.0" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.0 0.2155" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.1845 0.0" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.0 0.2155" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.2045 0.0" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.0 0.2025" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.0 0.1575" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ </worldbody>
+
+
+ <actuator>
+ <motor name="iiwa_1/joint_1" joint="iiwa_1/joint_1" ctrlrange="-320 320" />
+ <motor name="iiwa_1/joint_2" joint="iiwa_1/joint_2" ctrlrange="-320 320" />
+ <motor name="iiwa_1/joint_3" joint="iiwa_1/joint_3" ctrlrange="-176 176" />
+ <motor name="iiwa_1/joint_4" joint="iiwa_1/joint_4" ctrlrange="-176 176" />
+ <motor name="iiwa_1/joint_5" joint="iiwa_1/joint_5" ctrlrange="-110 110" />
+ <motor name="iiwa_1/joint_6" joint="iiwa_1/joint_6" ctrlrange="-40 40" />
+ <motor name="iiwa_1/joint_7" joint="iiwa_1/joint_7" ctrlrange="-40 40" />
+ <motor name="iiwa_1/striker_joint_1" joint="iiwa_1/striker_joint_1" ctrlrange="-10 10" />
+ <motor name="iiwa_1/striker_joint_2" joint="iiwa_1/striker_joint_2" ctrlrange="-10 10" />
+ </actuator>
+</mujoco>
\ No newline at end of file
diff --git a/scripts/roboolympics/shared/sports/airhockey/scene/iiwa2.xml b/scripts/roboolympics/shared/sports/airhockey/scene/iiwa2.xml
new file mode 100644
index 0000000000..295c57a9c5
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/airhockey/scene/iiwa2.xml
@@ -0,0 +1,59 @@
+<mujoco model="iiwa_2">
+ <compiler angle="radian" autolimits="true" />
+
+ <worldbody>
+ <body name="iiwa_2/base" pos="1.51 0 -0.1" quat="0 0 0 1">
+ <body name="iiwa_2/link_1" pos="0 0 0.1575">
+ <inertial pos="4.007709e-06 -0.033936 0.122467" mass="8.240527" fullinertia="0.021981 0.022182 0.008234 -2.897243e-07 6.3165236e-07 0.003285" />
+ <joint name="iiwa_2/joint_1" pos="0 0 0" axis="0 0 1" range="-2.96706 2.96706" damping="0.33032" frictionloss="0.384477" />
+ <body name="iiwa_2/link_2" pos="0 0 0.2025" quat="0 0 0.707107 0.707107">
+ <inertial pos="0.003402 0.034792 0.046725" mass="6.357896" fullinertia="0.015565 0.005180 0.015484 -4.147301e-06 1.192255e-05 0.002538" />
+ <joint name="iiwa_2/joint_2" pos="0 0 0" axis="0 0 1" range="-2.0944 2.0944" damping="0.21216" frictionloss="0.496333" />
+ <body name="iiwa_2/link_3" pos="0 0.2045 0" quat="0 0 0.707107 0.707107">
+ <inertial pos="-0.001452 0.031526 0.133584" mass="4.042756" fullinertia="0.010914 0.010381 0.003139 -3.540575e-06 -9.059062e-06 -0.002128" />
+ <joint name="iiwa_2/joint_3" pos="0 0 0" axis="0 0 1" range="-2.96706 2.96706" damping="0.1" frictionloss="0.173951" />
+ <body name="iiwa_2/link_4" pos="0 0 0.2155" quat="0.707107 0.707107 0 0">
+ <inertial pos="-0.002527 0.053508 0.037205" mass="3.642249" fullinertia="0.007536 0.002538 0.007206 -5.707028e-06 2.781894e-06 0.001256" />
+ <joint name="iiwa_2/joint_4" pos="0 0 0" axis="0 0 1" range="-2.0944 2.0944" damping="0.219041" frictionloss="0.3751" />
+ <body name="iiwa_2/link_5" pos="0 0.1845 0" quat="0 0 0.707107 0.707107">
+ <inertial pos="0.001855 0.024573 0.080131" mass="2.580896" fullinertia="0.005201 0.004488 0.002242 1.089316e-07 9.035623e-07 -0.001613" />
+ <joint name="iiwa_2/joint_5" pos="0 0 0" axis="0 0 1" range="-2.96706 2.96706" damping="0.185923" frictionloss="0.481099" />
+ <body name="iiwa_2/link_6" pos="0 0 0.2155" quat="0.707107 0.707107 0 0">
+ <inertial pos="-0.001739 -0.001973 -0.002502" mass="2.760564" fullinertia="0.002534 0.001821 0.002393 -1.311766e-06 9.508242e-07 0.000134" />
+ <joint name="iiwa_2/joint_6" pos="0 0 0" axis="0 0 1" range="-2.0944 2.0944" damping="0.1" frictionloss="0.196149" />
+ <body name="iiwa_2/link_7" pos="0 0.081 0" quat="0 0 0.707107 0.707107">
+ <inertial pos="0.000735 0.000387 0.026460" mass="1.285417" fullinertia="0.000151 0.000150 0.000187 -7.223100e-08 2.038333e-06 -3.396830e-07" />
+ <joint name="iiwa_2/joint_7" pos="0 0 0" axis="0 0 1" range="-3.05433 3.05433" damping="0.1" frictionloss="0.299238" armature="0.01" />
+ <body name="iiwa_2/striker_joint_link" pos="0 0 0.585">
+ <inertial pos="0 0 0" mass="0.1" diaginertia="0.001 0.001 0.001" />
+ <body name="iiwa_2/striker_mallet" pos="0 0 0">
+ <inertial pos="0 0 0.0682827" mass="0.283" diaginertia="0.005 0.005 0.005" />
+ <joint name="iiwa_2/striker_joint_1" pos="0 0 0" axis="0 1 0" range="-1.5708 1.5708" damping="0.0" />
+ <joint name="iiwa_2/striker_joint_2" pos="0 0 0" axis="1 0 0" range="-1.5708 1.5708" damping="0.0" />
+ <geom name="iiwa_2/ee" type="cylinder" rgba=".05 .65 .2 1" size="0.04815 0.03" pos="0 0 0.0505" friction="0 0 0" class="robot" />
+ </body>
+ </body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.0 0.585" size=".028" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.081 0.0" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.0 0.2155" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.1845 0.0" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.0 0.2155" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.2045 0.0" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.0 0.2025" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.0 0.1575" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ </worldbody>
+
+
+ <actuator>
+ <motor name="iiwa_2/joint_1" joint="iiwa_2/joint_1" ctrlrange="-320 320" />
+ <motor name="iiwa_2/joint_2" joint="iiwa_2/joint_2" ctrlrange="-320 320" />
+ <motor name="iiwa_2/joint_3" joint="iiwa_2/joint_3" ctrlrange="-176 176" />
+ <motor name="iiwa_2/joint_4" joint="iiwa_2/joint_4" ctrlrange="-176 176" />
+ <motor name="iiwa_2/joint_5" joint="iiwa_2/joint_5" ctrlrange="-110 110" />
+ <motor name="iiwa_2/joint_6" joint="iiwa_2/joint_6" ctrlrange="-40 40" />
+ <motor name="iiwa_2/joint_7" joint="iiwa_2/joint_7" ctrlrange="-40 40" />
+ <motor name="iiwa_2/striker_joint_1" joint="iiwa_2/striker_joint_1" ctrlrange="-10 10" />
+ <motor name="iiwa_2/striker_joint_2" joint="iiwa_2/striker_joint_2" ctrlrange="-10 10" />
+ </actuator>
+
+</mujoco>
\ No newline at end of file
diff --git a/scripts/roboolympics/shared/sports/airhockey/sport.toml b/scripts/roboolympics/shared/sports/airhockey/sport.toml
new file mode 100644
index 0000000000..9d2204ae4c
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/airhockey/sport.toml
@@ -0,0 +1,220 @@
+# airhockey: robot air hockey after the USAA rules (docs/framework_zh.md §4.2, §8). Migrated from the legacy tree in
+# stage 2 (scripts/olympiad/airhockey, scripts/olympiad/shared/airhockey/sim); revision v3 (2026-10-07, review item
+# B13) widened the goal mouth to 0.40 m (D10), so the legacy recordings (revision v2) no longer replay and golden/ holds
+# native recordings; revision v4 (2026-10-08) sets it to 0.35 m (a medium width, decided after the goal-width study).
+# The [[tasks]] ids keep the Season-1 task names (airhockey-match-wallclock-program-standard,
+# airhockey-duel-wallclock-program-standard).
+
+[sport]
+name = "airhockey"
+title = "Air hockey"
+summary = "robot air hockey on a physical MuJoCo table: a seven-axis KUKA iiwa arm holding a mallet at each end, the puck sliding on the air cushion, in a continuous world slowed by a factor S; you command your mallet's target in your own half and see the table only through your fixed camera; one game to 7 goals under the USAA rules (seven-second rule, dead-puck face-offs, a safety cap with a stated last resort, a 0.35 m goal mouth); format match: you against a scripted opponent (level 1-4), format duel: two players"
+protocol = "realtime"
+revision = "airhockey-program-v4+players-25k+core-0.2" # plugin.REVISION; bump on any change that alters play (players-25k: the players' images draw the arms with the KUKA iiwa 14's 25k visual meshes)
+physics = "mujoco 3.3.7 (1 kHz physics, 10 ms control): two physically simulated KUKA iiwa arms with passive striker joints (AirHockeyChallenge robot model), a 10 g puck on an air-cushion plane, physical rails and mallets"
+image = "ghcr.io/mll-lab-nu/eai-olympiad:0.1.0"
+status = "sport"
+publish = true
+category = "robotics-sports-arena"
+
+[rulebook]
+name = "USAA (United States Air Hockey Association) Official Rules of Air Hockey, as published by Gold Standard Air Hockey"
+version = "retrieved 2026-10-05"
+url = "https://goldstandardairhockey.com/usaa-official-rules-of-air-hockey/"
+
+[[deviations]]
+id = "D1"
+rule = "I.1, III.1"
+text = "one game to 7 points instead of a match of several games"
+affects_result = true
+[[deviations]]
+id = "D2"
+rule = "- (the rules have no time limit)"
+text = "a safety cap of 120 s of play (frozen time does not count) or 40 rallies; then the player with more goals wins, at equal goals the scorer of the last goal, at 0:0 the player in whose half the puck spent less time, and if that is equal the player who did not have the first possession (the stated last resort: no draws)"
+affects_result = true
+[[deviations]]
+id = "D3"
+rule = "III.1-2"
+text = "the game starts with the puck at rest in the half of the first player (FIRST_PLAYER, the coin toss) instead of a face-off; a face-off places the puck at rest at the table centre with both mallets at home instead of a referee's release"
+affects_result = true
+[[deviations]]
+id = "D4"
+rule = "I.10, VI.1"
+text = "the seven-second rule is a foul with the rulebook's penalty, forfeiture of the puck: the opponent gets it at rest on its spot; a foul gives no point"
+affects_result = true
+[[deviations]]
+id = "D5"
+rule = "IV.6, I.11"
+text = "a dead puck (play suspended) is added for a puck that no mallet can reach for 2 s (the robots' reach) or that touches the centre line for 7 s (I.11 has no limit); it is followed by a face-off"
+affects_result = true
+[[deviations]]
+id = "D6"
+rule = "I.4, I.14-15"
+text = "after every goal (I.4: the player scored upon gets the puck), foul or dead puck both mallets return home and the world freezes for the reviews; the time-outs are not used"
+affects_result = false
+[[deviations]]
+id = "D7"
+rule = "I.8, I.13, VI.6"
+text = "palming, goal-tending and topping cannot occur: only the mallets touch the puck and it stays flat on the table"
+affects_result = false
+[[deviations]]
+id = "D8"
+rule = "I.12, VI.9"
+text = "the mallets cannot cross the centre line: the mallet workspace ends 0.05 m before it (and at 1.45 m from the robot's base), so the players cannot touch each other"
+affects_result = true
+[[deviations]]
+id = "D9"
+rule = "-"
+text = "the players are seven-axis KUKA iiwa arms holding a mallet, commanded by a Cartesian target for the mallet (a smooth path of at most 2 m/s and 10 m/s^2, inverse kinematics and torque-limited motors), not human hands"
+affects_result = false
+[[deviations]]
+id = "D10"
+rule = "II.A.1 (the rules name the sanctioned tables, not their dimensions)"
+text = "the goal mouth is 0.35 m wide (|y| <= 0.175) instead of the 0.25 m of the table model (AirHockeyChallenge, 1.948 x 1.038 m): the arms move the mallet at about 2 m/s, so a shot takes 0.5-1 s to arrive and a defender that follows the puck would cover a 0.25 m mouth almost completely"
+affects_result = true
+
+[formats.match] # one seat against the scripted opponent inside the world (seat B of hockey.py)
+seats = ["A"]
+opponent = true # success = winning a valid game (core/grading.py), as in the legacy task
+levels = [1, 2, 3, 4] # the opponent level (RCB_LEVEL; default 1)
+[formats.duel]
+seats = ["A", "B"]
+first = ["A", "B"] # who has the puck first (FIRST_PLAYER); the runner plays both orders
+
+[modes]
+action_levels = ["low"] # the mallet target is the only level (the legacy interface)
+plays = ["program"]
+
+[timing]
+slowdown = 20 # S (RCB_SLOWDOWN); the legacy default of both tasks (official: match 1-20, duel 10, 20)
+start_timeout_s = 1800 # after the first seat started (duel); format match: from the service start
+ready_timeout_s = 300 # each review (legacy duel: 300 s; the legacy single had no limit)
+
+[actions.cli] # `game target X Y`, `game none`
+low = { target = ["x", "y"], none = [] }
+
+[observation]
+fields = ["rally", "t_play", "play_time_left_s", "score", "own", "rallies", "last_rally"]
+renderer = "mujoco"
+frame_budget_ms = 250 # one 320 x 240 tile (CPU, osmesa)
+columns = 1
+# Since revision airhockey-program-v4+players-25k the arms are drawn with the KUKA LBR iiwa 14's visual meshes
+# (presentation/presentation.toml players = "25k", bundled into the simulator; the core's camera worker draws the
+# players' scene, renderer rule 6). Measured 2026-10-08 (osmesa, host load ~8-10 on 32 cores), median / p95 ms per
+# observation at 1 llvmpipe thread: match scene 8.6 / 17.7, 25k meshes 12.0 / 15.2 (duel 12.1 / 25.0); 2 threads:
+# 6.3 / 9.5 and 8.7 / 16.9
+render_threads = 1 # llvmpipe threads per render process (LP_NUM_THREADS): one tile is cheap
+
+[spec] # the rules (also /spec); the numeric tables come from hockey.py (/spec)
+real_time = "this sport is real time (where the generic text above says otherwise, this line holds): `game wait DT` (POST /wait {\"dt\": DT}, 0 < DT <= 1) lets the world run DT game seconds; `game ready \"WHY\" \"PLAN\"` is due only after each rally, not after each action; acts are never out of turn, one in flight at a time; there is no release point and no execution scatter: your target goes to the mallet's path, the arm's inverse kinematics and its motors"
+robot = "a seven-axis KUKA iiwa arm whose end holds a mallet; seat A plays from the end x < 0, seat B from the end x > 0 (format match: you are A, the scripted opponent is B; `match.opponent_level` in /spec)"
+action = "target: a target for your mallet's centre in table metres (world frame). It must lie in your mallet's workspace (`workspace` in /spec): in your own half, 0.05 <= |x| <= 0.92, |y| <= 0.47, and at most 1.45 m from your robot's base at (-1.51, 0) for seat A, (+1.51, 0) for seat B; a target outside it is refused (HTTP 400). The mallet moves towards the target along a smooth path of at most 2 m/s and 10 m/s^2, driven by the arm's inverse kinematics and torque-limited motors, so it arrives later than the command and may lag when the arm is loaded or hits the puck. A command takes effect at the next 10 ms control step and holds until replaced; none holds the mallet where it is. The service has no puck tracking: aiming, timing and defending are up to you"
+observation = "one 320 x 240 RGB image per observation from your fixed camera above and behind your end of the table (`cameras` in /spec: pose, field of view, focal length; pixel centres at (column + 0.5, row + 0.5)). The puck is red, the mallet of seat A blue, the mallet of seat B green, the arms orange; four yellow markers are at (+-0.9, +-0.46) on the table surface and the centre line is grey. The state gives the score (points and fouls per seat), the time of play, your own mallet position, its command and your arm's joint positions and velocities (`own`), and the rallies that ended (`rallies`, the latest `last_rally`); no puck or opponent coordinates and no seed. Both seats see the game the same way: the two cameras are images of each other turned half a turn about the table centre"
+rally = "a rally starts with the puck at rest in one player's half on a spot at |x| = 0.58 (y varies between -0.18 and 0.18, from the seed), both mallets at home (|x| = 0.82, y = 0); the first rally starts with the puck in the half of `match.first_player`"
+goal = "the puck wholly inside a goal scores 1 point for the other player, whoever touched it last; the player scored upon gets the puck for the next rally"
+seven_second_rule = "if the puck stays wholly in one player's half for 7 s, that player commits a foul: the next rally starts with the puck in the opponent's half; a foul gives no point; the 7 s start again when the puck has wholly entered the other half; while it touches the centre line it is in nobody's half (either player may hit it)"
+dead_puck = "if for 2 s neither mallet can reach the puck (near the centre line at the sides, beyond both workspaces), or the puck touches the centre line for 7 s, the next rally starts with a face-off: the puck at rest at the table centre"
+review = "every goal, foul or dead puck ends the rally: both mallets return home, the world freezes for the reviews, then the next rally starts"
+game = "the first player to score 7 goals wins; the game also ends after 120 s of play (frozen time does not count) or 40 rallies, then the tiebreaks below decide"
+opponent = "format match: the scripted opponent (seat B, in the trusted simulator) guards its goal and strikes the puck at yours from the true puck position a reaction delay ago; levels 1-4 differ in its mallet speed (0.4 / 0.6 / 1 / 2 m/s), reaction delay and defence (level 1 does not guard its goal; level 4 guards the puck's predicted crossing point); it never reads your commands"
+table = "metres, seconds; the table frame: x along the table (seat A's end at x < 0, seat B's at x > 0), y across, z up. Playing surface 1.948 x 1.038 m (|x| <= 0.974, |y| <= 0.519), surrounded by rails; a goal mouth 0.35 m wide (|y| <= 0.175) in the middle of each end rail; the centre line is x = 0"
+puck = "radius 0.03165 m, mass 10 g; it slides flat on the air cushion and slows by about 10 % per second; rails return about 80 % of the puck's speed across them; mallets push it physically (a hit gives the puck up to about 1.3 times the mallet's speed); the puck's top face is at z = 0.022, its centre plane z = 0.012"
+mallet = "radius 0.04815 m, its centre 0.0645 m above the surface; home (-0.82, 0) for A, (0.82, 0) for B; the arm links have no collision geometry"
+cameras_pose = "the camera of seat A at (0, -1.3, 2.2), image right (1, 0, 0), image up (0, 0.861, 0.509), 48 degree vertical field of view; seat B's is the same turned half a turn about the table centre"
+rates = "physics 1000 Hz, control 100 Hz (10 ms steps)"
+
+[tiebreaks]
+order = ["goals", "last_goal", "territory", "first_possession"]
+text = "the first player to score 7 goals wins; at the safety cap (120 s of play or 40 rallies) the player with more goals wins; at equal goals the player who scored the last goal; if nobody has scored, the player in whose half the puck spent less time; last resort (not from the rulebook): the player who did not have the puck first"
+last_resort_in_prompt = true
+
+[[exploits]]
+id = "E1"
+text = "an out-of-range or malformed target (the other half, outside the workspace or the reach, non-finite, unknown fields) is refused (HTTP 400) and changes nothing; acting while the world is frozen is refused (409)"
+test = "test_exploit_bad_and_frozen_actions_are_refused"
+[[exploits]]
+id = "E2"
+text = "stalling with the puck in the own half is a seven-second foul, not a point: the opponent gets the puck"
+test = "test_exploit_stalling_with_the_puck_is_a_foul_not_a_point"
+[[exploits]]
+id = "E3"
+text = "parking the puck where no mallet reaches it is a dead puck after 2 s, followed by a face-off at the centre (which both mallets reach)"
+test = "test_exploit_parking_the_puck_out_of_reach_is_a_dead_puck"
+[[exploits]]
+id = "E4"
+text = "a puck resting on the centre line (nobody's half, no seven-second count) is a dead puck after 7 s"
+test = "test_exploit_centre_line_stall_is_a_dead_puck"
+[[exploits]]
+id = "E5"
+text = "every puck position away from the centre line can be reached by the mallet of its half (no dead zone at the rails)"
+test = "test_exploit_puck_at_the_rails_is_reachable"
+[[exploits]]
+id = "E6"
+text = "parking the mallet in front of the own goal and never playing loses to a player that plays"
+test = "test_exploit_parking_in_front_of_the_goal_loses"
+[[exploits]]
+id = "E7"
+text = "doing nothing loses to the scripted opponent (format match)"
+test = "test_exploit_doing_nothing_loses_to_the_scripted_opponent"
+[[exploits]]
+id = "E8"
+text = "the observation and /spec hold no puck or opponent coordinate and no seed (only the camera image shows the puck)"
+test = "test_exploit_world_state_hidden"
+[[exploits]]
+id = "E9"
+text = "the two robots are identical and point-symmetric through the table centre (geometry, physical parameters, and the puck's path under mirrored commands)"
+test = "test_exploit_mirror_symmetric_robots"
+[[exploits]]
+id = "E10"
+text = "no draws: a game without any play still ends at the cap and every step of the tiebreak chain decides; seven goals end the game at once"
+test = "test_exploit_no_draw_tiebreak_chain"
+
+[players]
+reference = "reference" # Sport.players() names: camera-only, wins the default configuration
+reference_class = "builtin_players:Reference"
+check = ["random"] # policies for the generic tests
+
+[fairness]
+# Two copies of the reference player. Realtime: a wide interval only warns; a reference duel is up to 12000 control
+# steps with two camera images every 5 steps (about 100 s of CPU each), so N is small. Result (README, revision v4):
+# N = 40, first mover 0.0 pp (95% CI +-15.5 pp), seat A -15.0 pp (+-14.8 pp) (no failure; wide: a warning for a
+# realtime sport); 28 of the 40 games decided by goals (26 by the count, 2 by the last goal), 12 by territory (v3 at
+# 0.40 m: 24 and 16; v2: 4 and 36).
+policy = "reference"
+matches_per_order = 20
+max_advantage_pp = 5
+mirror = "statistical" # world-frame observations and actions: a swapped match is not the same view
+
+[check] # tools/check time limits
+stage_timeout_s = 10800 # fairness: 40 reference duels of about 100 s each, over an hour on a shared host
+live_player_timeout_s = 3600 # live: a capped game is 2400 s at x20 plus the reviews
+
+[official] # grade.py applies the legacy rule per format (match: the level's own seeds)
+seeds = [1, 2, 3, 101, 111, 121, 202, 212, 222, 303, 313, 323, 404, 414, 424]
+levels = [1, 2, 3, 4]
+first_any = true
+
+[golden]
+episodes = "golden" # native recordings of revision v4 (tools/golden.py record)
+
+[[tasks]]
+id = "airhockey-match-wallclock-program-standard"
+format = "match"
+action_level = "low"
+[[tasks]]
+id = "airhockey-duel-wallclock-program-standard"
+format = "duel"
+action_level = "low"
+
+[broadcast] # spectators: the replay video's camera (the legacy `overview` camera)
+camera = { name = "broadcast", pos = [0.0, -2.3, 2.5], lookat = [0.0, -1.623, 1.764], up = [0.0, 0.736, 0.677], fovy_deg = 55, width = 640, height = 360 }
+
+[capabilities] # docs/capabilities_zh.md: 2 primary, 1 secondary, 0 none
+a1 = 2 # 3D: the puck and the opponent's mallet only from the oblique camera image
+a2 = 2 # puck dynamics: rail rebounds, air-cushion drag, mallet impacts
+a3 = 2 # execution: an arm with a lagging Cartesian path, IK and torque limits
+a4 = 2 # real time: the puck moves while the program thinks
+b1 = 0
+b2 = 1 # attack vs defence, shots away from the opponent's mallet
+b3 = 0
+physics = ["collision", "friction_rolling"]
diff --git a/scripts/roboolympics/shared/sports/badminton/builtin_players.py b/scripts/roboolympics/shared/sports/badminton/builtin_players.py
new file mode 100644
index 0000000000..569d0eda55
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/badminton/builtin_players.py
@@ -0,0 +1,566 @@
+"""badminton's built-in players (the same action interface as a model's program; core/client.py plays them over HTTP).
+
+ Reference the camera-only reference player of the legacy duel task (scripts/olympiad/badminton/duel/solution/
+ cam_player.py + oracle_play.py; its perception, flight fit and stroke choice unchanged below), for either
+ format and seat: it detects the orange cork in the 8 tiles, triangulates each frame, fits the documented
+ drag model, picks a contact the base can reach and a target (deep corners or short), turns the launch
+ velocity into the racket state with the documented contact law and sends `act` with T counted from the
+ act's effect step; while the shuttle flies it corrects the command when the refined prediction moves the
+ contact, or when the contact step it gets back (state.command) differs from the planned one. Only the
+ images, the state, /spec and the documented physics (the legacy task's privileged /oracle endpoint is
+ gone). Placement: the legacy privileged oracle's rule (oracle_ref.aim_place: a corner away from the
+ opponent, deep if it stands forward, short if it stands back), with the opponent's spot estimated as
+ the point the shuttle was played from (the fitted flight integrated back to its start). A shuttle the
+ fit lands clearly out of its court (0.3 m) is let go, and commands stay within the documented ranges.
+ Its serve (the documented serve rules, /spec serve): it plans a contact at its forehand point at 0.95 m
+ (so the stroke controller keeps the base on its spot), a toss point straight above it from which the
+ shuttle, released from rest (toss height 0), falls to the contact in SERVE_FALL_S, and a high-deep or a
+ short serve into the diagonal service court (a seeded choice per point, the same for either seat); it sends the stroke first (contact
+ SERVE_LEAD_S ahead) and then the toss timed so that the shuttle meets the racket; if the toss took
+ effect at another step than planned, it moves the contact time accordingly.
+ Random occasional random cancels (a check policy).
+No simulator import: this file runs in the player's container as the task's oracle (numpy + Pillow only).
+"""
+from __future__ import annotations
+
+import base64
+import io
+import math
+import random
+import time
+
+import numpy as np
+from PIL import Image
+
+G, K = 9.81, 9.81 / 6.8 ** 2 # gravity; drag K |v| v (terminal speed 6.8 m/s): from /spec
+DT = 0.002 # integration step of the player's own flight model
+STEP = 0.01 # the control step
+NET_TOP, COURT_X, COURT_Y = 1.524, 2.59, 6.70
+TILE_W, TILE_H = 480, 360
+REFINE_M = 0.03 # re-act when the predicted contact moves by more than this
+LAST_REFINE_S = 0.25 # no corrections closer to the contact than this (game seconds)
+OUT_MARGIN = 0.3 # let a shuttle go that the fit lands this far out of your court
+
+
+# ------------------------------------------------------------------------------------------------ cameras
+class Cam:
+ def __init__(self, c: dict):
+ self.pos = np.array(c["position"], float)
+ self.fw = np.array(c["forward"], float)
+ self.fw /= np.linalg.norm(self.fw)
+ self.up = np.array(c["up"], float)
+ self.up /= np.linalg.norm(self.up)
+ self.rt = np.cross(self.fw, self.up)
+ self.f = float(c.get("focal_px", 434.6))
+ pp = c.get("principal_point_px", [240, 180])
+ self.cx, self.cy = float(pp[0]), float(pp[1])
+
+ def ray(self, u, v):
+ d = self.fw + ((u - self.cx) / self.f) * self.rt - ((v - self.cy) / self.f) * self.up
+ return self.pos, d / np.linalg.norm(d)
+
+
+def triangulate(rays):
+ A = np.zeros((3, 3))
+ b = np.zeros(3)
+ for o, d in rays:
+ P = np.eye(3) - np.outer(d, d)
+ A += P
+ b += P @ o
+ X = np.linalg.solve(A, b)
+ res = [np.linalg.norm((np.eye(3) - np.outer(d, d)) @ (X - o)) for o, d in rays]
+ return X, float(np.sqrt(np.mean(np.square(res))))
+
+
+def decode(png: bytes) -> np.ndarray:
+ return np.asarray(Image.open(io.BytesIO(png)).convert("RGB"))
+
+
+def detect_tile(t: np.ndarray):
+ """(u, v) of the orange cork's centroid in a tile, or None."""
+ r = t[..., 0].astype(np.int16)
+ g = t[..., 1].astype(np.int16)
+ b = t[..., 2].astype(np.int16)
+ m = (r > 110) & (g * 100 > 25 * r) & (g * 100 < 72 * r) & (b * 100 < 35 * r)
+ m[:16, :160] = False # the time stamp
+ ys, xs = np.nonzero(m)
+ if len(xs) == 0 or len(xs) > 3000:
+ return None
+ mx, my = np.median(xs), np.median(ys)
+ sel = (np.abs(xs - mx) <= 25) & (np.abs(ys - my) <= 25)
+ if sel.sum() == 0:
+ return None
+ return float(xs[sel].mean()) + 0.5, float(ys[sel].mean()) + 0.5
+
+
+def detect_views(img, cams, times, max_res=0.12):
+ out = []
+ for j, tt in enumerate(times):
+ rays = []
+ for i, c in enumerate(cams):
+ uv = detect_tile(img[i * TILE_H:(i + 1) * TILE_H, j * TILE_W:(j + 1) * TILE_W])
+ if uv is not None:
+ rays.append(c.ray(*uv))
+ if len(rays) == 2:
+ X, res = triangulate(rays)
+ if res < max_res and -0.2 < X[2] < 12.0 and abs(X[0]) < 4.0 and abs(X[1]) < 8.0:
+ out.append((float(tt), X))
+ return out
+
+
+# ------------------------------------------------------------------------------------------------ flight model
+def rollout(p, v, n, dt=DT):
+ """(m, 3) states, integrated n steps (semi-implicit Euler); vectorised over m trajectories."""
+ p = np.array(p, float, ndmin=2)
+ v = np.array(v, float, ndmin=2)
+ P = np.empty((n + 1,) + p.shape)
+ V = np.empty_like(P)
+ P[0] = p
+ V[0] = v
+ for i in range(1, n + 1):
+ s = np.sqrt((v * v).sum(-1, keepdims=True))
+ v = v - (K * s * v + np.array([0.0, 0.0, G])) * dt
+ p = p + v * dt
+ P[i] = p
+ V[i] = v
+ return P, V
+
+
+def positions_at(p, v, t0, times):
+ times = np.asarray(times, float)
+ n = int(math.ceil((times.max() - t0) / DT)) + 1
+ P, _ = rollout(p, v, n)
+ idx = (times - t0) / DT
+ i0 = np.clip(np.floor(idx).astype(int), 0, n - 1)
+ f = (idx - i0)[:, None, None]
+ return P[i0] * (1 - f) + P[i0 + 1] * f # (len(times), m, 3)
+
+
+def fit(obs):
+ """Least-squares (p, v) at the first observation time from [(t, X)] (Gauss-Newton, numerical Jacobian)."""
+ obs = sorted(obs, key=lambda o: o[0])
+ t0 = obs[0][0]
+ ts = np.array([o[0] for o in obs])
+ Xs = np.array([o[1] for o in obs])
+ p = Xs[0].copy()
+ v = (Xs[-1] - Xs[0]) / max(ts[-1] - t0, 0.02) if len(obs) > 1 else np.zeros(3)
+ x = np.r_[p, v]
+ for _ in range(8):
+ eps = np.r_[np.full(3, 1e-3), np.full(3, 1e-3)]
+ X = np.vstack([x] + [x + np.eye(6)[i] * eps[i] for i in range(6)])
+ Pt = positions_at(X[:, :3], X[:, 3:], t0, ts) # (T, 7, 3)
+ r = (Xs - Pt[:, 0]).ravel()
+ J = np.stack([((Pt[:, i + 1] - Pt[:, 0]) / eps[i]).ravel() for i in range(6)], 1)
+ dx = np.linalg.lstsq(J.T @ J + 1e-6 * np.eye(6), J.T @ r, rcond=None)[0]
+ x = x + dx
+ if np.abs(dx).max() < 1e-4:
+ break
+ Pt = positions_at(x[None, :3], x[None, 3:], t0, ts)[:, 0]
+ return t0, x[:3], x[3:], float(np.sqrt(np.mean(np.sum((Xs - Pt) ** 2, 1))))
+
+
+def predict(p, v, t0, t_max=4.0):
+ """Times, positions, velocities until the floor or the net plane below the top."""
+ P, V = rollout(p, v, int(t_max / DT))
+ P, V = P[:, 0], V[:, 0]
+ end = len(P)
+ below = np.nonzero(P[:, 2] <= 0.0)[0]
+ if len(below):
+ end = below[0] + 1
+ cross = np.nonzero((np.sign(P[1:end, 1]) != np.sign(P[:end - 1, 1])) & (P[1:end, 2] < NET_TOP))[0]
+ if len(cross):
+ end = cross[0] + 1
+ return t0 + DT * np.arange(end), P[:end], V[:end]
+
+
+def backtrack(p, v, t, dt=0.001):
+ """The flight integrated backwards for t seconds (the documented model): where the shuttle was t s before (p, v)."""
+ p, v = np.array(p, float), np.array(v, float)
+ for _ in range(int(round(t / dt))):
+ p = p - v * dt
+ v = v + (K * np.linalg.norm(v) * v + np.array([0.0, 0.0, G])) * dt
+ return p
+
+
+# ------------------------------------------------------------------------------------------------ shots
+def solve_launch(p, target, thetas, vmax=45.0, dt=0.003):
+ """Launch velocities from p landing near `target` (xy, opponent's court), clearing the net by 20 cm: one per launch
+ angle that works, in the order given. Planar flights along the heading, vectorised over angle x speed."""
+ p = np.asarray(p, float)
+ d = np.asarray(target, float) - p[:2]
+ H = float(np.linalg.norm(d))
+ hd = d / H
+ th = np.radians(np.asarray(thetas, float))[:, None]
+ sp = np.linspace(2.0, vmax, 120)[None, :]
+ vh = (np.cos(th) * sp).ravel()
+ vz = (np.sin(th) * sp).ravel()
+ h = np.zeros_like(vh)
+ z = np.full_like(vh, p[2])
+ s_net = -p[1] / hd[1] if hd[1] > 1e-9 else np.inf
+ rng_ = np.full(vh.size, np.nan)
+ znet = np.full(vh.size, np.nan)
+ alive = np.ones(vh.size, bool)
+ for _ in range(int(4.0 / dt)):
+ s = np.sqrt(vh * vh + vz * vz)
+ vh = vh - K * s * vh * dt
+ vz = vz - (G + K * s * vz) * dt
+ h1 = h + vh * dt
+ z1 = z + vz * dt
+ cr = alive & (h < s_net) & (h1 >= s_net)
+ znet[cr] = z[cr] + (s_net - h[cr]) / (h1[cr] - h[cr]) * (z1[cr] - z[cr])
+ ld = alive & (z1 <= 0)
+ rng_[ld] = h[ld] + z[ld] / (z[ld] - z1[ld]) * (h1[ld] - h[ld])
+ alive &= ~ld
+ h, z = h1, z1
+ if not alive.any():
+ break
+ R = rng_.reshape(th.shape[0], -1)
+ ZN = znet.reshape(th.shape[0], -1)
+ S = sp[0]
+ out = []
+ for a, tdeg in enumerate(thetas):
+ ok = np.nonzero(np.isfinite(R[a]) & (R[a] >= H))[0]
+ if not len(ok) or ok[0] == 0:
+ continue
+ k = ok[0]
+ f = (H - R[a][k - 1]) / (R[a][k] - R[a][k - 1])
+ v = S[k - 1] + f * (S[k] - S[k - 1])
+ zn = ZN[a][k - 1] + f * (ZN[a][k] - ZN[a][k - 1])
+ if not np.isfinite(zn) or zn < NET_TOP + 0.20:
+ continue
+ c, s_ = math.cos(math.radians(tdeg)), math.sin(math.radians(tdeg))
+ out.append((tdeg, float(v), np.array([hd[0] * c * v, hd[1] * c * v, s_ * v])))
+ return out
+
+
+def racket_state(v_in, v_out):
+ """Contact law: the shuttle leaves along n at 20 (v_head . n) + 0.15 max(0, -v_in . n)."""
+ sp = float(np.linalg.norm(v_out))
+ n = v_out / sp
+ u = max(0.05, (sp - 0.15 * max(0.0, -float(v_in @ n))) / 20.0)
+ return n, u * n
+
+
+def base_time(dist, vmax, amax):
+ a, vm = 0.85 * amax, 0.98 * vmax
+ return 2 * math.sqrt(dist / a) if dist < vm * vm / a else dist / vm + vm / a
+
+
+def stance(p):
+ dz = float(p[2]) - 1.333
+ r = max(0.30, 0.95 - 0.35 * abs(dz))
+ return np.asarray(p[:2], float) - 0.62 * r
+
+
+def choose(ts, P, V, t_now, base_xy, vmax, amax, rng, margin=0.12, opp=None):
+ """Contact (time, position, incoming velocity) and racket state, or None. opp: where the opponent played the
+ shuttle from (x, y in the player's frame), for the placement."""
+ cands = []
+ for i in range(0, len(ts), 5):
+ p = P[i]
+ dt = ts[i] - t_now
+ if dt < 0.22 or not (0.45 <= p[2] <= 2.45 and -7.4 <= p[1] < -0.45 and abs(p[0]) <= 3.3):
+ continue
+ if base_time(float(np.linalg.norm(stance(p) - base_xy)), vmax, amax) <= dt - margin:
+ cands.append(i)
+ if not cands:
+ ok = [i for i in range(0, len(ts), 5) if ts[i] - t_now >= 0.22 and 0.45 <= P[i][2] <= 2.95
+ and -7.4 <= P[i][1] < -0.45 and abs(P[i][0]) <= 3.3]
+ if not ok:
+ return None
+ cands = [ok[-1]]
+ hi = [i for i in cands if 1.7 <= P[i][2] <= 2.45]
+ i = hi[0] if hi else max(cands, key=lambda j: P[j][2])
+ p, v_in = P[i], V[i]
+ if opp is None: # where the opponent is unknown: the legacy random placement
+ deep = rng.random() < 0.65
+ side = 1.0 if rng.random() < 0.5 else -1.0
+ target = np.array([side * 1.8, 5.6]) if deep else np.array([side * 1.5, 2.4])
+ else: # the legacy oracle's placement: a corner away from the opponent,
+ deep = opp[1] < 3.6 # deep if it stands forward, short if it stands back
+ side = -1.0 if opp[0] > 0 else 1.0
+ target = np.array([side * 1.9, 5.9]) if deep else np.array([side * 1.9, 1.6])
+ thetas = DEEP_THETAS if deep else SHORT_THETAS
+ opts = strokes(p, v_in, target, thetas) or strokes(p, v_in, np.array([0.0, 4.5]), (45, 35, 55, 25, 60))
+ if not opts:
+ return None
+ return ts[i], p, v_in, opts, target
+
+
+def strokes(p, v_in, target, thetas, vmax_head=2.2):
+ """Racket states (normal, head velocity) for the shots from p to target, the slowest head first."""
+ out = []
+ for th, sp, v_out in solve_launch(p, target, thetas):
+ n, vel = racket_state(v_in, v_out)
+ if np.linalg.norm(vel) <= vmax_head:
+ out.append((float(np.linalg.norm(vel)), n, vel))
+ return [(n, vel) for _, n, vel in sorted(out, key=lambda o: o[0])]
+
+
+DEEP_THETAS, SHORT_THETAS = (40, 30, 50, 20, 55, 10, 60), (10, 0, 20, -5, 30)
+SERVE_Z = 0.95 # the serve's contact height (below 1.15 m, Law 9.1.6)
+SERVE_FALL_S = 0.35 # from the toss (from rest) to the contact
+SERVE_LEAD_S = 1.0 # the stroke's contact time when it is sent (time to swing from rest)
+SERVE_THETAS = {"high": (50, 45, 55, 40, 60, 35), "short": (20, 14, 26, 10, 32, 6)} # launch angles (deg), in order
+
+
+def fall(t, dt=0.001):
+ """Drop of a shuttle released from rest after t s, and its speed then (the documented model)."""
+ z, v = 0.0, 0.0
+ for _ in range(int(round(t / dt))):
+ v += (G - K * v * v) * dt
+ z += v * dt
+ return z, v
+
+
+def serve_choice(spec_seed, st):
+ """The serve to play: (kind, target xy in your frame). Seeded by the match seed, the point and the score (not the
+ seat), into the receiver's diagonal service court: your right court (state.serve.court) faces its right court,
+ which is on your left (x < 0)."""
+ sc = st.get("score") or {}
+ g = random.Random(f"serve-{int(spec_seed)}-{st.get('point')}-{sc.get('you')}-{sc.get('opponent')}")
+ sgn = -1.0 if (st.get("serve") or {}).get("court") == "right" else 1.0
+ if g.random() < 0.5:
+ return "high", np.array([sgn * g.uniform(0.6, 1.8), g.uniform(5.6, 6.2)])
+ return "short", np.array([sgn * g.uniform(0.4, 1.6), g.uniform(2.25, 2.6)])
+
+
+def serve_plan(base_xy, kind, target):
+ """Contact point, toss point, incoming velocity and the racket states (normal, head velocity) of a serve from
+ the base at base_xy: contact at the forehand point at SERVE_Z (where the stroke controller's stance is the base
+ itself), the shuttle released SERVE_FALL_S of fall above it."""
+ dz = SERVE_Z - 1.333
+ off = 0.62 * max(0.30, 0.95 - 0.35 * abs(dz))
+ pc = np.array([base_xy[0] + off, base_xy[1] + off, SERVE_Z])
+ drop, vf = fall(SERVE_FALL_S)
+ rel = np.array([pc[0], pc[1], SERVE_Z + drop])
+ v_in = np.array([0.0, 0.0, -vf])
+ opts = [] # in the order of the launch angles (a high serve goes high), not by head speed
+ for th, sp, v_out in solve_launch(pc, target, SERVE_THETAS[kind]):
+ n, vel = racket_state(v_in, v_out)
+ if np.linalg.norm(vel) <= 2.2:
+ opts.append((n, vel))
+ return pc, rel, v_in, opts
+
+
+# ------------------------------------------------------------------------------------------------ players
+class Reference:
+ """The legacy play loop (oracle_play.play) as act(view): one command (or None) per call. In-process
+ (core/local.py) the view's step is exact and an act takes effect `lead` steps after it; over HTTP (the
+ observation has an obs_id) the step at which the act arrives is estimated from the wall clock (the newest frame's
+ step and its age give the step and its phase at the reply), and the contact step the service reports back
+ (state.command.contact_in_s) corrects both the act and the estimate."""
+
+ def __init__(self, spec, seat, seed=0):
+ self.high = spec.get("action_level", "high") == "high"
+ self.cams = [Cam(c) for c in spec["cameras"]]
+ self.lead = int(spec["act"]["lead_steps"])
+ self.period = float((spec.get("timing") or {}).get("period_s") or 0.2)
+ base = spec.get("base") or {}
+ self.vmax = float(base.get("max_speed_mps", 6.0))
+ self.amax = float(base.get("max_accel_mps2", 20.0))
+ self.rng = random.Random(f"{seat}-{int(seed)}")
+ self.seed = int(seed)
+ self.srv = None # the serve under way: {point, k_c (contact step), rel (the toss point), released (toss sent)}
+ self.flight, self.obs, self.plan = None, [], None
+ self.k_bias = 0.0 # learned offset of the estimated arrival step (over HTTP)
+ self.sent = None # the last act sent: {k_c (planned contact step), checked}
+
+ def review(self, reply):
+ return "reference player: camera-only, scripted", "reference player: same policy"
+
+ def _now_k(self, st, ob):
+ """The step at which a command sent now arrives (over HTTP: estimated from the newest frame and its age)."""
+ k = float(st.get("step", 0))
+ if "obs_id" in ob:
+ vs, age = ob.get("view_steps") or [], ob.get("obs_age_wall_s")
+ if vs and isinstance(age, (int, float)):
+ k = max(k, float(vs[-1]) + (float(age) + 0.02) / self.period)
+ k += self.k_bias
+ return k
+
+ def serve(self, st, ob):
+ """Your serve: the stroke first, then the toss timed so that the shuttle falls into the racket."""
+ sv = st.get("serve") or {}
+ phase, point = sv.get("phase"), st.get("point")
+ if self.srv is None or self.srv["point"] != point:
+ if phase not in ("waiting", "open"):
+ return None
+ kind, target = serve_choice(self.seed, st)
+ base = np.asarray(st.get("robot_base_xy") or [0.0, -4.0], float)
+ centre = np.array([0.5 * np.sign(target[0]) * COURT_X, 0.5 * (1.98 + COURT_Y)])
+ opts = None
+ for kd in [kind] + [x for x in SERVE_THETAS if x != kind]: # then the other kinds of serve
+ for f in (1.0, 0.75, 0.5, 0.25, 0.0): # no stroke delivers it: a target nearer the court's centre
+ pc, rel, v_in, opts = serve_plan(base, kd, centre + f * (target - centre))
+ if opts:
+ break
+ if opts:
+ kind = kd
+ break
+ if not opts:
+ return None
+ self.srv = {"point": point, "kind": kind, "target": centre + f * (target - centre), "pc": pc, "rel": rel,
+ "opts": opts, "k_c": None,
+ "released": False, "fixed": False}
+ srv = self.srv
+ k_now = self._now_k(st, ob)
+ n_fall = int(round(SERVE_FALL_S / STEP))
+ if phase == "open" and srv["k_c"] is None:
+ k_e = int(math.floor(k_now + 1e-6)) + self.lead
+ n_lead = int(round(SERVE_LEAD_S / STEP))
+ # the toss must take effect once the receiver is ready
+ k_open = int(st.get("step", 0)) + int(round(float(sv.get("opens_in_s") or 0.0) / STEP))
+ if k_e + n_lead - n_fall < k_open:
+ n_lead = k_open - k_e + n_fall
+ if n_lead * STEP > 4.9:
+ return None
+ srv["k_c"] = k_e + n_lead
+ n, vel = srv["opts"][0]
+ return {"type": "act", "t": round(n_lead * STEP, 3), "pos": [round(float(x), 4) for x in srv["pc"]],
+ "normal": [round(float(x), 4) for x in n], "vel": [round(float(x), 4) for x in vel]}
+ c = st.get("command")
+ if isinstance(c, dict) and isinstance(c.get("contact_in_s"), (int, float)) and not srv["released"]:
+ srv["k_c"] = int(st.get("step", 0)) + int(round(c["contact_in_s"] / STEP)) # the reported contact step
+ notes = str(c.get("stroke") or "")
+ k_e = int(math.floor(k_now + 1e-6)) + self.lead
+ if (("pose not delivered" in notes or "head speed limited" in notes) and srv["opts"][1:]
+ and srv["k_c"] - k_e > n_fall + 30 and srv.get("tried") != srv["k_c"]):
+ srv["opts"].pop(0) # the next stroke to the same target, for the same contact step
+ srv["tried"] = srv["k_c"]
+ n, vel = srv["opts"][0]
+ return {"type": "act", "t": round((srv["k_c"] - k_e) * STEP, 3),
+ "pos": [round(float(x), 4) for x in srv["pc"]], "normal": [round(float(x), 4) for x in n],
+ "vel": [round(float(x), 4) for x in vel]}
+ if phase == "open" and not srv["released"] and srv["k_c"] is not None:
+ k_e = int(math.floor(k_now + 1e-6)) + self.lead
+ if k_e >= srv["k_c"] - n_fall - 2: # (in-process the steps line up exactly)
+ srv["released"] = True
+ return {"type": "toss", "pos": [round(float(x), 4) for x in srv["rel"]], "height": 0.0}
+ return None
+ if phase == "tossed" and not srv["fixed"]:
+ srv["fixed"] = True
+ k_rel = sv.get("tossed_at_step")
+ if isinstance(k_rel, int) and k_rel + n_fall != srv["k_c"]:
+ # the toss took effect at another step than planned: move the contact time to meet the shuttle
+ k_e = int(math.floor(k_now + 1e-6)) + self.lead
+ T = (k_rel + n_fall - k_e) * STEP
+ if T > 0.12:
+ n, vel = srv["opts"][0]
+ return {"type": "act", "t": round(T, 3), "pos": [round(float(x), 4) for x in srv["pc"]],
+ "normal": [round(float(x), 4) for x in n], "vel": [round(float(x), 4) for x in vel]}
+ return None
+
+ def act(self, view):
+ st, ob = view.get("state") or {}, view.get("observation") or {}
+ if not self.high or st.get("world") != "running" or st.get("pending_commands"):
+ return None
+ if st.get("you_serve") and (st.get("serve") or {}).get("phase") in ("waiting", "open", "tossed"):
+ return self.serve(st, ob)
+ if st.get("ball_state") != "coming to you" or st.get("t_since_played") is None:
+ self.flight, self.obs, self.plan, self.sent = None, [], None, None
+ return None
+ live = "obs_id" in ob
+ t_entry = time.monotonic()
+ step = int(st.get("step", 0))
+ k_obs = float(step)
+ if live:
+ # the step at the reply, with its phase: the newest frame was taken at its step, obs_age_wall_s ago
+ vs, age = ob.get("view_steps") or [], ob.get("obs_age_wall_s")
+ if vs and isinstance(age, (int, float)):
+ k_obs = max(k_obs, float(vs[-1]) + (float(age) + 0.02) / self.period)
+ else:
+ k_obs += (float(ob.get("render_wall_s") or 0.0) + 0.03) / self.period
+
+ def now_k():
+ return k_obs + ((time.monotonic() - t_entry) / self.period if live else 0.0)
+
+ t_sim = step * STEP
+ t0 = round(t_sim - float(st["t_since_played"]), 3)
+ if self.flight != (st.get("point"), t0):
+ self.flight, self.obs, self.plan, self.sent = (st.get("point"), t0), [], None, None
+ if self.sent is not None and not self.sent["checked"]:
+ c = st.get("command")
+ if isinstance(c, dict) and isinstance(c.get("contact_in_s"), (int, float)):
+ k_true = step + int(round(c["contact_in_s"] / STEP))
+ err = k_true - self.sent["k_c"]
+ self.sent["checked"] = True
+ if live and abs(err) <= 10: # it took effect err steps later than assumed: arrive later next time
+ self.k_bias = max(-5.0, min(5.0, self.k_bias + 0.7 * err))
+ plan = self.plan
+ if plan is not None and not plan.get("skip"):
+ if err != 0:
+ plan["redo"] = True # the act took effect at another step than assumed: send it again
+ # the reply's stroke notes predict the delivery: if the joint speed limits cap the head speed or
+ # the pose is not delivered, take the next (faster-head or other-angle) stroke to the same target
+ notes = str(c.get("stroke") or "")
+ if (("head speed limited" in notes or "pose not delivered" in notes) and plan.get("opts")
+ and plan["t"] - t_sim > 0.3):
+ plan["normal"], plan["vel"] = plan["opts"].pop(0)
+ plan["redo"] = True
+ if "image_png_b64" not in ob:
+ return None
+ img = decode(base64.b64decode(ob["image_png_b64"]))
+ seen = {round(t, 3) for t, _ in self.obs}
+ for t, X in detect_views(img, self.cams, ob.get("view_sim_times") or []):
+ if t > t0 + 0.005 and round(t, 3) not in seen:
+ self.obs.append((t, X))
+ obs = self.obs
+ if len(obs) < 4 or max(t for t, _ in obs) - min(t for t, _ in obs) < 0.05:
+ return None
+ tf, p, v, res = fit(obs)
+ if res > 0.08:
+ self.obs = obs[-4:]
+ return None
+ ts, P, V = predict(p, v, tf)
+ land = P[-1]
+ if land[2] <= 0.05 and (abs(land[0]) > COURT_X + OUT_MARGIN or land[1] < -COURT_Y - OUT_MARGIN):
+ self.plan = {"skip": True} # it lands out of your court: let it go (your point)
+ return None
+ t_now = now_k() * STEP
+ plan = self.plan
+ if plan is None:
+ opp = backtrack(p, v, max(0.0, tf - t0))[:2] # the shuttle where it was played: the opponent's spot
+ c = choose(ts, P, V, t_now + (self.lead + 2) * STEP, np.asarray(st.get("robot_base_xy") or [0.0, -4.0]),
+ self.vmax, self.amax, self.rng, opp=opp)
+ if c is None:
+ self.plan = {"skip": True}
+ return None
+ t_c, pos, v_in, opts, target = c
+ plan = self.plan = dict(t=float(t_c), pos=pos, normal=opts[0][0], vel=opts[0][1], target=target,
+ opts=opts[1:])
+ elif plan.get("skip") or plan["t"] - t_now < LAST_REFINE_S:
+ return None
+ elif plan.pop("redo", False):
+ pass
+ else:
+ i = int(np.argmin(np.abs(ts - plan["t"])))
+ if np.linalg.norm(P[i] - plan["pos"]) < REFINE_M:
+ return None
+ opts = strokes(P[i], V[i], plan["target"], DEEP_THETAS if plan["target"][1] > 4 else SHORT_THETAS)
+ if not opts:
+ return None
+ plan.update(pos=P[i], normal=opts[0][0], vel=opts[0][1], opts=opts[1:])
+ k_e = int(math.floor(now_k() + (self.k_bias if live else 0.0) + 1e-6)) + self.lead
+ T = round(plan["t"] - k_e * STEP, 3)
+ pos = np.asarray(plan["pos"], float)
+ if not (0.03 <= T <= 4.9 and abs(pos[0]) <= 3.35 and -7.45 <= pos[1] <= -0.35 and 0.25 <= pos[2] <= 2.95
+ and np.linalg.norm(plan["vel"]) <= 7.9):
+ return None # outside the act's documented ranges
+ self.sent = {"k_c": k_e + int(round(T / STEP)), "checked": False}
+ return {"type": "act", "t": T, "pos": [round(float(x), 4) for x in plan["pos"]],
+ "normal": [round(float(x), 4) for x in plan["normal"]],
+ "vel": [round(float(x), 4) for x in plan["vel"]]}
+
+
+class Random:
+ """Occasional random cancels (a check policy; seeded by the seed, not the seat)."""
+
+ def __init__(self, spec, seat, seed=0):
+ self.g = np.random.default_rng(int(seed) * 7919 + 17)
+
+ def act(self, view):
+ st = view.get("state") or {}
+ if st.get("world") != "running" or st.get("pending_commands") or self.g.uniform() > 0.05:
+ return None
+ return {"type": "none"}
diff --git a/scripts/roboolympics/shared/sports/badminton/grade.py b/scripts/roboolympics/shared/sports/badminton/grade.py
new file mode 100644
index 0000000000..5149a93b6b
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/badminton/grade.py
@@ -0,0 +1,86 @@
+"""badminton's part of reward.json (the common part is core/grading.py): numbers only, from final.json (and, for the
+metering fields of format match-wallclock, the seat's think_usage_A.json artifact). The keys are the legacy tasks'
+keys where the v0.2 core records the quantity (sports/badminton/README.md lists the differences)."""
+import json
+import os
+from pathlib import Path
+
+
+def usage(seat):
+ try:
+ return json.loads((Path(os.environ.get("RCB_DATA", "/data")) / f"think_usage_{seat}.json").read_text())
+ except (OSError, ValueError):
+ return {}
+
+
+def _lag(d):
+ lag = d.get("sim_lag") or {}
+ sim_s, wall_s = float(lag.get("run_sim_s") or 0.0), float(lag.get("run_wall_s") or 0.0)
+ return lag, sim_s, wall_s
+
+
+def _max(v, scale=1.0):
+ return scale * max([float(x) for x in v or []], default=0.0)
+
+
+def evaluate(d):
+ f, seats = d.get("sport_fields") or {}, d["cfg"]["seats"]
+ if len(seats) == 1:
+ return single(d, f, seats[0])
+ lag, _, _ = _lag(d)
+ out = dict(ready_forfeit=int(d.get("reason") == "ready_timeout" and d.get("match_winner") is not None),
+ timing_invalid=0, steps=int(d.get("steps") or 0), hits=int(f.get("hits") or 0),
+ slowdown=float(d.get("slowdown") or 0.0), first_server_A=int(f.get("first_server") == "A"),
+ lead_steps=int(f.get("lead_steps") or 0), match_limit=int(bool(f.get("match_limit"))),
+ plan_mismatch=int(sum((f.get("plan_mismatch") or {}).values())),
+ sim_lag_max_s=float(lag.get("late_max_s") or 0.0))
+ pts = f.get("points") or []
+ for s in seats:
+ st = d["seats"].get(s, {})
+ out[s + "_points"] = int((f.get("score") or {}).get(s, 0))
+ out[s + "_serves"] = sum(1 for p in pts if p.get("server") == s)
+ out[s + "_service_faults"] = sum(1 for p in pts if p.get("server") == s and p.get("loser") == s
+ and str(p.get("how", "")).startswith("serve_fault:"))
+ for k in ("attempts", "applied", "refused", "dropped", "observations", "rejected_acts"):
+ out[s + "_" + k] = int(st.get(k, 0))
+ for k in ("plan_s", "act_s", "obs_age_s"):
+ out[s + "_" + k + "_max"] = _max(st.get(k))
+ return out
+
+
+def single(d, f, a):
+ st, u = d["seats"].get(a, {}), usage(a)
+ lag, sim_s, wall_s = _lag(d)
+ errs = d.get("errors") or []
+ replay = d.get("replay_scores") or {}
+ det = bool(d.get("deterministic"))
+ return dict(
+ won=int(bool(f.get("won"))),
+ sim_error=int(d.get("reason") == "technical_error" or any(e.get("where") != "replay" for e in errs)),
+ replay_error=int(not det or any(e.get("where") == "replay" for e in errs)),
+ meter_error=int(bool((d.get("meter_error") or {}).get(a))),
+ proxy_error=int(bool((d.get("proxy_error") or {}).get(a))), timing_invalid=0,
+ points_for=int(f.get("points_for") or 0), points_against=int(f.get("points_against") or 0),
+ replay_points_for=int(replay.get(a, -1)), replay_points_against=int(replay.get("opponent", -1)),
+ replay_joint_targets_equal=int(det), finalized=int(bool(d.get("finalized"))), revision=5,
+ our_serves=float(sum(1 for x in f.get("serves") or [] if x.get("server") == "you")),
+ our_service_faults=float(sum(1 for p in f.get("points") or [] if p.get("server") == 0
+ and p.get("winner") == "opponent"
+ and str(p.get("how", "")).startswith("serve_fault:"))),
+ timing_lag_enforced=0, match_limit=int(bool(f.get("match_limit"))),
+ metered_requests=int(u.get("requests", 0)), metered_output_tokens=int(u.get("output_tokens", 0)),
+ metered_input_tokens=int(u.get("input_tokens", 0)), rate_limit_retries=int(u.get("rate_limit_retries", 0)),
+ transient_api_errors=int((d.get("transient_api_errors") or {}).get(a, 0)),
+ unrecovered_api_errors=int((d.get("unrecovered_api_errors") or {}).get(a, 0)),
+ level=float(f.get("level") or 0), slowdown=float(d.get("slowdown") or 0.0),
+ our_shots=float(f.get("our_legs") or 0), good_shots=float(f.get("returns") or 0),
+ n_decisions=float(st.get("applied", 0)), refused_not_model=float(st.get("refused", 0)),
+ dropped_acts=float(st.get("dropped", 0)), rejected_acts=float(st.get("rejected_acts", 0)),
+ n_actions=float(d.get("steps") or 0), sim_steps=float(f.get("physics_steps") or 0),
+ steps=float(d.get("steps") or 0), n_reviews=float(len(d.get("reviews") or [])),
+ n_observe=float(st.get("observations", 0)), n_act=float(st.get("applied", 0)),
+ elapsed_s=float(d.get("elapsed_s") or 0.0), max_lag_s=0.0,
+ sim_lag_late_max_s=float(lag.get("late_max_s") or 0.0), sim_lag_late_p99_s=float(lag.get("late_p99_s") or 0.0),
+ sim_effective_slowdown=round(wall_s / sim_s, 4) if sim_s > 0 else 0.0, sim_run_wall_s=wall_s,
+ plan_ms_max=_max(st.get("plan_s"), 1000.0), plan_lead_steps=float(f.get("plan_lead_steps") or 0),
+ plan_mismatch=float(sum((f.get("plan_mismatch") or {}).values())))
diff --git a/scripts/roboolympics/shared/sports/badminton/plugin.py b/scripts/roboolympics/shared/sports/badminton/plugin.py
new file mode 100644
index 0000000000..a0c82ff87c
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/badminton/plugin.py
@@ -0,0 +1,918 @@
+"""badminton: robot singles badminton in real time (docs/framework_zh.md §4.2). Migrated from the Season-1 tasks
+badminton-match-wallclock-program-standard and badminton-duel-wallclock-program-standard (docs §10 stage 3). The four
+groups of contract ②, on the unchanged legacy simulator (sim/bm.py, sim/bduel.py, sim/wc.py, sim/scene/):
+ world + referee format match-wallclock = bm.Match (seat A against the scripted opponent, levels 1-2, which plays
+ inside the world), format duel-wallclock = bduel.World (seats A and B, mirrored robots); the players
+ serve (BWF Law 9: the rally winner serves; the server tosses the shuttle with `toss`, then hits
+ it below 1.15 m, upwards, into the diagonal service court); step = one 10 ms control step (the
+ legacy services' rt_advance(1) / advance()); a point end freezes the world for the reviews
+ actions low = joint targets: `traj` (a list of 9 joint targets [base_x, base_y, q1..q7], one per control
+ step, followed exactly, then the robot returns to its ready pose and the base to its spot), `none`
+ and `toss` (the shuttle appears at a point, from rest or rising: the server's missing hand);
+ high = the legacy racket command `act` (the racket state at contact T s after the act takes
+ effect), planned in the seat's plan worker by the legacy stroke controller (bm.Match.plan_racket,
+ through the legacy wc.plan_on / bduel.plan_on) on an exact copy of the match (or of the seat's
+ robot) advanced to the act's effect step k0 = request step + lead (the legacy services' lead:
+ ceil(0.4 s / wall time per step)), and lowered to the SAME `traj` command with k0, the planner's
+ state key at k0 and the stroke's hit configuration; `toss` takes effect at k0 too (nothing to
+ plan); the episode holds only `traj`, `none` and `toss`
+ referee phase / scores / tiebreaks (disqualification, then the legacy winner chain in three rules)
+ observation observe = the legacy state (score, what was heard, the robot's own body, its command); camera_job =
+ the legacy 2 cameras x 4 frames (60 ms apart), drawn by the sport itself (the legacy scenes and
+ extra geometry) in the seat's render worker
+"""
+from __future__ import annotations
+
+import copy
+import hashlib
+import itertools
+import json
+import math
+import os
+import struct
+import sys
+import time
+import zlib
+
+import numpy as np
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+SIM = os.path.join(HERE, "sim")
+if SIM not in sys.path:
+ sys.path.insert(0, SIM)
+os.environ.pop("MATCH_SEED", None) # bm.Match reads it at construction; the seed comes from the config only
+
+import bduel as BD # noqa: E402
+import bm as BM # noqa: E402
+import wc as WC # noqa: E402
+
+from core.sport import FINISHED, PLAYING, UNIT_OVER, MatchBase, Phase, Refused # noqa: E402
+
+REVISION = "badminton-wallclock-5+duel-7+core-0.2"
+SEATS2 = ("A", "B")
+OPPONENT = "opponent" # the scripted opponent's side in format match-wallclock (no seat)
+DT = BM.CONTROL_DT
+PLAN_LEAD_S = 0.4 # wall-time budget of an act's stroke planning (legacy WALLCLOCK_PLAN_LEAD_S)
+T_MAX_S = 5.0
+TRAJ_MAX = 600 # joint targets in one low-level traj command
+STROKE_KEYS = ("stroke", "base", "base_goal", "k_hit", "n_swing_steps_available", "n_swing_steps", "ik_residual",
+ "blade_error_m", "normal_error_deg", "speed_scale", "racket_vel_delivered", "T_from_now")
+VEL_LIM = BM.VEL_LIMIT * DT * (1 + 1e-6) + 1e-12
+FOCAL_PX = 434.6 # 45 degree vertical field of view on a 360 px tile
+IMAGE_LAYOUT = ("2 rows x 4 columns of 480 x 360 tiles. Row 1: camera behind and above your base line looking down the "
+ "court; row 2: camera at the side of the court (x < 0 in your frame) looking along +x: your half (y < 0) "
+ "is on the right. Columns: four camera frames 60 ms apart, oldest left; each tile is stamped with its "
+ "control step k and its time t since the shuttle shown was played (view_steps, view_times). The "
+ "shuttle is drawn enlarged: an orange cork (12 cm ball centred on the shuttle's position) with a white "
+ "skirt behind it, cork first along its flight. Yellow marks every 1 m along the outside of the singles "
+ "side lines and behind the base lines.")
+_TOKENS = itertools.count(1)
+
+
+def lead_steps(slowdown) -> int:
+ """Control steps from an act's request to its effect (the legacy services' LEAD_STEPS)."""
+ period = DT * float(slowdown or 20)
+ return max(1, int(math.ceil(PLAN_LEAD_S / period - 1e-9)))
+
+
+def _clean(x):
+ """JSON-exact python values (what the episode log holds and the replay reads back)."""
+ return json.loads(json.dumps(x, default=lambda o: o.tolist() if hasattr(o, "tolist") else float(o)))
+
+
+class Badminton(MatchBase):
+ def __init__(self, cfg):
+ self.cfg = cfg
+ self.single = len(cfg.seats) == 1
+ self.dt = DT
+ self.token = next(_TOKENS)
+ self.review_due = False
+ self.review_hist = None # single: the finished point's last camera frames (display only)
+ self.deferred = {s: None for s in cfg.seats} # a lowered command waiting for its effect step k0
+ self.rejected = {s: 0 for s in cfg.seats}
+ self.mismatch = {s: 0 for s in cfg.seats} # acts re-planned late or planned for another state
+ self.level_ = None
+ if self.single:
+ self.level_ = 1 if cfg.level is None else int(cfg.level)
+ if self.level_ not in BM.LEVELS:
+ raise ValueError(f"opponent level must be one of {sorted(BM.LEVELS)}")
+ self.g = BM.Match(self.level_, lv_override={"seed": int(cfg.seed)})
+ else:
+ self.first = cfg.first if cfg.first in SEATS2 else "A"
+ self._ctx()
+ self.g = BD.World()
+
+ def _ctx(self):
+ """bduel.py keeps the seed and the first server in module globals: set them for this match."""
+ if not self.single:
+ BD.SEED, BD.FIRST_SERVER = int(self.cfg.seed), self.first
+
+ @property
+ def k(self):
+ return self.g.k
+
+ # ------------------------------------------------------------------ robot access
+ def robot(self, seat):
+ """The object that owns the seat's robot and stroke state (bm.Match or bduel.Side)."""
+ return self.g if self.single else self.g.sides[seat]
+
+ def key(self, seat) -> str:
+ """Everything the stroke planner reads, hashed (the legacy services' state key)."""
+ return WC.state_key(self.g) if self.single else self.g.sides[seat].state_key()
+
+ # ------------------------------------------------------------------ world + referee
+ def step(self):
+ self._ctx()
+ for s in self.cfg.seats: # A, then B (the legacy apply_due order)
+ item = self.deferred[s]
+ if item is not None and item["k0"] == self.g.k:
+ self.deferred[s] = None
+ if "rejected" in self._take_effect(s, item):
+ self.rejected[s] += 1
+ g = self.g
+ n0 = len(g.points)
+ if self.single:
+ pre = list(g.hist)
+ g.rt_advance(1)
+ if g.hist and g.hist[-1]["k"] == g.k and "leg_id" not in g.hist[-1]:
+ g.hist[-1]["leg_id"] = len(g.legs) - 1 # display only (the legacy _frame_extras)
+ g.hist[-1]["wall_mono"] = time.monotonic()
+ else:
+ g.advance()
+ if len(g.points) > n0:
+ self.deferred = {s: None for s in self.cfg.seats} # no command carries over to the next point
+ if self.single:
+ self.review_hist = pre or None
+ if not g.done:
+ self.review_due = True
+ return [{"kind": "point", **_clean(g.points[-1])}]
+ return []
+
+ def state_digest(self):
+ if not self.single:
+ return self.g.state_sha()
+ g = self.g # the robot and shuttle state + the referee's record
+ rec = json.dumps({"score": list(g.score), "points": g.points}, sort_keys=True, default=float)
+ return hashlib.sha256((g.s.state_sha() + rec).encode()).hexdigest()
+
+ def capped(self):
+ return bool(self.g.points and self.g.points[-1].get("cap"))
+
+ def phase(self):
+ if self.g.done:
+ return Phase(FINISHED, reason="disqualified" if self.g.disqualified else
+ "match_limit" if self.capped() else "match_over")
+ if self.review_due:
+ return Phase(UNIT_OVER, review=tuple(self.cfg.seats), reason=self.g.points[-1]["how"])
+ return Phase(PLAYING)
+
+ def resume(self):
+ self.review_due = False
+
+ def unit(self):
+ return len(self.g.points)
+
+ def sides(self):
+ return [self.cfg.seats[0], OPPONENT] if self.single else list(SEATS2)
+
+ def scores(self):
+ if self.single:
+ return {self.cfg.seats[0]: int(self.g.score[0]), OPPONENT: int(self.g.score[1])}
+ return {s: int(self.g.score[s]) for s in SEATS2}
+
+ def tiebreaks(self):
+ """The winner chain as three rules: the score (first to 5, from 4-4 by 2, at most 7; at the match limit the
+ player ahead), else the winner of the last point that was not a let, else (last resort, not from the
+ rulebook) the player who received first (format match-wallclock: the opponent, since you serve first)."""
+ def score(m):
+ sc = m.scores()
+ a, b = m.sides()
+ return None if sc[a] == sc[b] else (a if sc[a] > sc[b] else b)
+
+ def last_point(m):
+ names = {"you": m.sides()[0], "opponent": OPPONENT} if m.single else {s: s for s in SEATS2}
+ won = [names[p["winner"]] for p in m.g.points if p.get("winner") in names]
+ return won[-1] if won else None
+
+ def first_receiver(m):
+ return OPPONENT if m.single else BD.OTHER[m.first]
+
+ def disqualification(m): # Law 16.7: the third undue-delay fault disqualifies a player
+ if m.single:
+ return OPPONENT if m.g.disqualified else None
+ return BD.OTHER[m.g.disqualified] if m.g.disqualified else None
+ return [("disqualification", disqualification), ("score", score), ("last_point", last_point),
+ ("first_receiver", first_receiver)]
+
+ def forfeit(self, seat, why):
+ return False # the core decides a forfeit; the world is left as it was
+
+ # ------------------------------------------------------------------ actions (low level)
+ def schema(self, seat):
+ return LOW_SCHEMA
+
+ def apply(self, seat, cmd):
+ self._ctx()
+ typ = cmd.get("type")
+ if typ not in ("traj", "none", "toss"):
+ return {"rejected": f"unknown command {typ!r}"}
+ k0 = cmd.get("k0")
+ if k0 is None or k0 == self.g.k:
+ return self._take_effect(seat, cmd)
+ if k0 < self.g.k:
+ return {"rejected": f"late: planned to take effect at step {k0}, now {self.g.k}"}
+ self.deferred[seat] = dict(cmd)
+ return {"effect_step": int(k0)}
+
+ def _take_effect(self, seat, cmd):
+ """A command takes effect: `toss` puts the shuttle at the given point, from rest or rising (height) (the server only, in its
+ serve window; refused with no change otherwise); `none` cancels the stroke (the legacy rt_clear); a `traj`
+ replaces the stroke under way with exactly the attribute changes of the legacy install (wc.install /
+ bduel.install). A traj is refused (no change) if it breaks a joint range or speed limit, or if the state it was
+ planned for (its key) is not the live one at its effect step."""
+ if cmd["type"] == "toss":
+ try:
+ if self.single:
+ self.g.toss(cmd["pos"], cmd.get("height", 0.0))
+ else:
+ self.g.toss(seat, cmd["pos"], cmd.get("height", 0.0))
+ except ValueError as e:
+ return {"rejected": f"serve: {e}"}
+ return {"tossed_step": int(self.g.k)}
+ if cmd["type"] == "none":
+ if self.single:
+ WC.install(self.g, {"type": "none"})
+ else:
+ BD.install(self.g.sides[seat], {"type": "none"})
+ return {"command": "cleared: the robot returns to the ready pose, the base home"}
+ key = cmd.get("key")
+ if key is not None and key != self.key(seat):
+ self.mismatch[seat] += 1
+ return {"rejected": "the robot's state at the effect step differs from the planned one"}
+ rob = self.robot(seat)
+ cur = np.asarray(rob.s.target, np.float64)
+ q = np.asarray(cmd.get("q") or np.zeros((0, 9)), np.float64).reshape(-1, 9)
+ lo, hi = rob.s.lo, rob.s.hi
+ prev = cur
+ for i, qi in enumerate(q):
+ if not np.all(np.isfinite(qi)) or (qi < lo - 1e-9).any() or (qi > hi + 1e-9).any():
+ return {"rejected": f"joint target {i} outside the joint ranges"}
+ if (np.abs(qi - prev) > VEL_LIM).any():
+ return {"rejected": f"joint target {i} breaks a joint speed limit"}
+ prev = qi
+ if (cmd.get("info") or {}).get("replanned_late_steps"):
+ self.mismatch[seat] += 1
+ q_hit = cmd.get("q_hit")
+ res = {"type": "act", "plan": [x.copy() for x in q], "info": copy.deepcopy(cmd.get("info") or {}),
+ "q_hit": None if q_hit is None else np.asarray(q_hit, np.float64), "ik_seed": None,
+ "swing_last": None}
+ if self.single:
+ WC.install(self.g, res)
+ else:
+ BD.install(self.g.sides[seat], res)
+ return {"took_effect_step": int(self.g.k), "n_targets": int(len(q))}
+
+ # ------------------------------------------------------------------ the serve
+ def serve_state(self, seat) -> dict:
+ """The current point's serve as the seat sees it: whether it serves, the phase (ready: the receiver is getting
+ waiting: the receiver is getting ready; open: the server may toss; tossed; done: the serve was delivered), the
+ steps that bound it, its base (docs/conventions/racket_serve_zh.md)."""
+ g = self.g
+ if self.single:
+ leg = g.leg
+ first = next(x for x in reversed(g.legs) if x["kind"] in ("serve", "our_serve") and x["point"] == leg["point"])
+ server = first["kind"] == "our_serve"
+ right = first["service_court_right"]
+ if server:
+ ready, deadline, rel = first["ready"], first["deadline"], first.get("toss_k")
+ phase = ("waiting" if first["state"] == "held" and g.k < ready else "open" if first["state"] == "held"
+ else "tossed" if first["state"] == "falling" else "done")
+ else:
+ ready = deadline = rel = first["launch"]
+ phase = "waiting" if g.k < ready else "done"
+ base = g.s.d.qpos[g.s.qa[:2]]
+ else:
+ rs = g.rs
+ server = rs["server"] == seat
+ right, ready, deadline, rel = rs["service_court_right"], rs["ready"], rs["deadline"], rs["toss_k"]
+ phase = {"ready": "waiting", "to_serve": "open", "tossed": "tossed"}.get(rs["state"], "done")
+ ph = g.sides[seat].s
+ base = ph.d.qpos[ph.qa[:2]]
+ return {"server": server, "right": right, "phase": phase, "ready_k": ready, "deadline_k": deadline,
+ "toss_k": rel, "base": np.asarray(base, float).copy()}
+
+ def serve_refusal(self, seat, k_eff, pos, height):
+ """Why a toss (at `pos`, rising `height`, effective at step k_eff) is refused now: (message, HTTP code) or None."""
+ sv = self.serve_state(seat)
+ if self.g.done or not sv["server"]:
+ return "it is not your serve", 409
+ if sv["phase"] not in ("waiting", "open"):
+ return "the shuttle was already tossed (one toss per serve)", 409
+ why = BM.toss_problem(pos, height, sv["base"])
+ if why:
+ return why, 400
+ if k_eff < sv["ready_k"]:
+ return (f"the receiver is ready at step {sv['ready_k']}: the toss would take effect at step {k_eff}; "
+ "send it so that it takes effect then or later (state.serve_in_s)"), 409
+ return None
+
+ def _serve_obs(self, seat):
+ g, sv = self.g, self.serve_state(seat)
+ o = {"court": "right" if sv["right"] else "left", "phase": sv["phase"]}
+ if sv["phase"] in ("waiting", "open") and sv["server"]:
+ o["opens_in_s"] = round(max(0.0, (sv["ready_k"] - g.k) * DT), 3)
+ o["deadline_in_s"] = round(max(0.0, (sv["deadline_k"] - g.k) * DT), 3)
+ if sv["toss_k"] is not None and sv["phase"] in ("tossed", "done"):
+ o["tossed_at_step"] = int(sv["toss_k"])
+ return {"you_serve": sv["server"], "you_receive_serve": not sv["server"], "serve": o,
+ "serve_in_s": round(max(0.0, (sv["ready_k"] - g.k) * DT), 3) if sv["phase"] in ("waiting", "open")
+ else None}
+
+ # ------------------------------------------------------------------ observation
+ def observe(self, seat, query=None):
+ g = self.g
+ if self.single:
+ o = self._single_state()
+ leg = g.leg
+ o.update(self._serve_obs(seat))
+ if leg["kind"] == "our_serve" and leg["state"] in ("held", "falling"):
+ o["ball_in_play"] = leg["state"] == "falling"
+ o["ball_state"] = "not yet served" if leg["state"] == "held" else "tossed: yours to hit (your serve)"
+ o["t_since_played"] = None if leg["state"] == "held" else g.t_since_launch()
+ o["heard"] = [] if leg["state"] == "held" else [{"event": "you tossed the shuttle", "t": 0.0}]
+ elif not g.in_play():
+ o["ball_in_play"] = False
+ o["ball_state"] = "not yet served"
+ o["heard"] = []
+ o["t_since_played"] = None
+ else:
+ o["ball_in_play"] = leg["state"] in ("incoming", "to_opp")
+ o["ball_state"] = {"incoming": "coming to you", "to_opp": "going to the opponent",
+ "done": "dead"}.get(leg["state"], leg["state"])
+ if leg["state"] == "to_opp":
+ o["heard"] = o["heard"] + [{"event": "you served" if leg["kind"] == "our_serve" else
+ "you hit the shuttle",
+ "t": round((leg["hit"]["k"] - leg["launch"]) * DT, 3)
+ if "k" in leg.get("hit", {}) else None}]
+ o["last_points"] = [{k: p[k] for k in ("point", "winner", "how", "score")} for p in g.points[-3:]]
+ o["last_shots"] = [{k: r.get(k) for k in ("returned", "summary", "speed_out")} for r in g.results[-3:]]
+ o["opponent_level"] = self.level_
+ else:
+ o = self._duel_state(seat)
+ rob = self.robot(seat)
+ la, active = rob._last_act, rob.plan_j < len(rob.plan)
+ k_hit = la.get("k_hit") if la else None
+ o["command"] = ({"contact_in_s": round((k_hit - g.k) * DT, 3) if k_hit is not None and k_hit >= g.k
+ else "passed",
+ "phase": "approach" if k_hit is not None and g.k < k_hit else "follow_through",
+ "pos": la.get("racket_pos"), "normal": la.get("racket_normal"), "vel": la.get("racket_vel"),
+ "stroke": la.get("stroke")}
+ if active and la else
+ {"traj_steps_left": len(rob.plan) - rob.plan_j} if active else
+ "none (the robot returns to / holds the ready pose, the base to its spot)")
+ it = self.deferred[seat]
+ if it is not None:
+ o["pending_commands"] = [{"type": {"traj": "act"}.get(it["type"], it["type"]),
+ "takes_effect_at_step": int(it["k0"])}]
+ if self.cfg.action_level == "low":
+ o["q_target"] = [float(x) for x in rob.s.target]
+ return o
+
+ def _single_state(self):
+ """bm.Match.decision_observation() without view_times (the frames' times come with the images)."""
+ g = self.g
+ ph, leg = g.s, g.leg
+ heard = [{"event": "the opponent served" if leg["kind"] == "serve" else "the opponent hit the shuttle",
+ "t": 0.0}] if leg["kind"] in ("serve", "return") else []
+ c, n, _ = ph.racket_state()
+ return {"score": {"you": g.score[0], "opponent": g.score[1]}, "point": len(g.points) + 1,
+ "ball": {"serve": "serve", "our_serve": "your serve"}.get(leg["kind"], "opponent's return"),
+ "t_since_played": g.t_since_launch(), "heard": heard,
+ "robot_base_xy": [round(float(x), 3) for x in ph.d.qpos[ph.qa[:2]]],
+ "q_arm": [round(float(x), 4) for x in ph.d.qpos[ph.qa[2:]]],
+ "racket_pos": [round(float(x), 3) for x in c], "racket_normal": [round(float(x), 3) for x in n]}
+
+ def _duel_state(self, side):
+ """The duel's state(side), without the core's fields (phase, world, step, ready ...)."""
+ w = self.g
+ rs, other, me = w.rs, BD.OTHER[side], w.sides[side]
+ ph = me.s
+ c, n, _ = ph.racket_state()
+ st = rs["state"]
+ server = rs["server"] == side
+ if st in ("ready", "to_serve"):
+ ball = "not yet served"
+ elif st == "tossed":
+ ball = "tossed: yours to hit (your serve)" if server else "the opponent tossed the shuttle (serving)"
+ elif st == "live":
+ ball = "coming to you" if rs["expect"] == side else "going to the opponent"
+ else:
+ ball = "dead"
+ heard = []
+ for e in w.events:
+ if e["kind"] == "toss":
+ heard.append({"event": "you tossed the shuttle" if e["side"] == side else
+ "the opponent tossed the shuttle", "t": round((e["k"] - rs["ready"]) * DT, 3)})
+ elif e["kind"] == "hit":
+ first = e["k"] == (rs["serve"] or {}).get("hit_k")
+ what = ("served" if first else "hit the shuttle")
+ heard.append({"event": f"you {what}" if e["side"] == side else f"the opponent {what}",
+ "t": round((e["k"] - rs["ready"]) * DT, 3)})
+ o = {"point": rs["point"] + 1, "score": {"you": w.score[side], "opponent": w.score[other]},
+ "ball_state": ball, "ball_in_play": st in ("tossed", "live"),
+ "t_since_played": round((w.k - rs["played_k"]) * DT, 3) if st in ("tossed", "live", "over") else None,
+ "heard": heard, "robot_base_xy": [round(float(x), 3) for x in ph.d.qpos[ph.qa[:2]]],
+ "q_arm": [round(float(x), 4) for x in ph.d.qpos[ph.qa[2:]]],
+ "racket_pos": [round(float(x), 3) for x in c], "racket_normal": [round(float(x), 3) for x in n],
+ "last_points": [{"point": p["point"], "how": p["how"], "let": p["let"],
+ "winner": "let" if p["winner"] is None else ("you" if p["winner"] == side else
+ "opponent"),
+ "server": "you" if p["server"] == side else "opponent",
+ "score": {"you": p["score"][side], "opponent": p["score"][other]}}
+ for p in w.points[-3:]]}
+ o.update(self._serve_obs(side))
+ return o
+
+ def _snaps(self):
+ """The 4 camera frames 60 ms apart ending at the newest one; during a review the finished point's last frames.
+ Before the first frame of a point: the current state (not stored: observing changes nothing)."""
+ g = self.g
+ if self.single:
+ hist = list(self.review_hist if (self.review_due and self.review_hist) else g.hist)
+ if not hist:
+ hist = [{"k": g.k, "t": g.t_since_launch(), "qpos": g.s.d.qpos.copy(), "sh": g.s.sh_p,
+ "shv": g.s.sh_v, "opp": g.opp_xy().copy(), "leg_id": len(g.legs) - 1}]
+ else:
+ hist = list(g.review_hist or []) if (self.review_due and g.review_hist) else list(g.hist)
+ if not hist:
+ hist = [g.snap()]
+ return [hist[max(0, len(hist) - 1 - b)] for b in reversed(BM.Match.VIEW_BACK)]
+
+ def camera_job(self, seat):
+ snaps = self._snaps()
+ if self.single:
+ frames = [{"qpos": np.asarray(s["qpos"], np.float64).copy(), "sh": tuple(float(x) for x in s["sh"]),
+ "shv": tuple(float(x) for x in s["shv"]), "opp": [float(x) for x in s["opp"]],
+ "k": int(s["k"]), "t": float(s["t"])} for s in snaps]
+ times = [round(float(s["t"]), 3) for s in snaps]
+ legs = [s.get("leg_id") for s in snaps]
+ else:
+ frames = [{"qA": np.asarray(s["qA"], np.float64).copy(), "qB": np.asarray(s["qB"], np.float64).copy(),
+ "sh": tuple(float(x) for x in s["sh"]), "shv": tuple(float(x) for x in s["shv"]),
+ "k": int(s["k"]), "played_k": int(s["played_k"])} for s in snaps]
+ times = [round((s["k"] - s["played_k"]) * DT, 3) for s in snaps]
+ legs = [s.get("flight") for s in snaps]
+ job = {"single": self.single, "side": "A" if self.single else seat, "snaps": frames}
+ meta = {"view_times": times, "view_steps": [int(s["k"]) for s in snaps], "view_leg_ids": legs,
+ "view_sim_times": [round(s["k"] * DT, 4) for s in snaps], "image_layout": IMAGE_LAYOUT,
+ "wall_mono": snaps[-1].get("wall_mono", time.monotonic())}
+ return job, meta
+
+ def final_fields(self):
+ g = self.g
+ lead = lead_steps(self.cfg.slowdown)
+ if self.single:
+ a = self.cfg.seats[0]
+ return {"level": self.level_, "points_for": int(g.score[0]), "points_against": int(g.score[1]),
+ "win_points": BM.WIN_POINTS, "won": bool(g.done and g.winner == 0),
+ "returns": int(sum(r["returned"] for r in g.results)), "our_legs": int(g.n_our_legs),
+ "match_limit": self.capped(), "hits": int(g.hits),
+ "lets": sum(1 for p in g.points if p.get("let")), "points": _clean(g.points),
+ "results": _clean(g.results), "shots": _clean(g.shots), "physics_steps": int(g.s.steps_total),
+ "opponent": _clean([x.get("opp") for x in g.legs if x.get("opp")]),
+ "serves": [{"server": "opponent", "type": x.get("serve")} if x["kind"] == "serve" else
+ {"server": "you", "toss": x.get("toss"), "toss_k": x.get("toss_k"),
+ "contact_z": (x.get("hit") or {}).get("pos", [None] * 3)[2],
+ "speed": (x.get("hit") or {}).get("speed")}
+ for x in g.legs if x.get("kind") in ("serve", "our_serve")],
+ "plan_lead_steps": lead, "rejected_acts": dict(self.rejected), "plan_mismatch": dict(self.mismatch),
+ "seats": {a: {"rejected_acts": self.rejected[a]}}}
+ return {"score": dict(g.score), "points": _clean(g.points), "hits": int(g.hits), "match_limit": self.capped(),
+ "first_server": self.first, "lead_steps": lead, "rejected_acts": dict(self.rejected),
+ "plan_mismatch": dict(self.mismatch),
+ "seats": {s: {"rejected_acts": self.rejected[s]} for s in SEATS2}}
+
+
+# ---------------------------------------------------------------------------------------------- action layers
+NUM = {"type": "number"}
+VEC3 = {"type": "vector", "len": 3}
+NONE = {"none": {}}
+SERVE = {"toss": {"pos": {**VEC3, "unit": "m",
+ "doc": f"your serve's toss (docs/conventions/racket_serve_zh.md): the shuttle appears at this "
+ f"point (your frame) when the command takes effect; {BM.TOSS_Z[0]} <= z <= "
+ f"{BM.TOSS_Z[1]}, within {BM.TOSS_REACH} m (horizontally) of your base, y <= -0.5; "
+ "only the server, once per serve, from the step the receiver is ready (state.serve)"},
+ "height": {**NUM, "min": 0.0, "max": BM.TOSS_H_MAX, "unit": "m", "optional": True,
+ "doc": f"how far it rises straight up from pos (0 <= height <= {BM.TOSS_H_MAX}; default "
+ "0: released from rest)"}}}
+HIGH_SCHEMA = {
+ "act": {"t": {**NUM, "min": 0.0, "max": T_MAX_S, "unit": "s",
+ "doc": "contact T s after the act takes effect (0 < T <= 5)"},
+ "pos": {**VEC3, "unit": "m", "doc": "racket-head centre at contact: |x| <= 3.4, -7.5 <= y <= -0.3, "
+ "0.2 <= z <= 3.0"},
+ "normal": {**VEC3, "doc": "string-face normal at contact (non-zero)"},
+ "vel": {**VEC3, "unit": "m/s", "doc": "racket-head velocity at contact, |vel| <= 8"}},
+ **SERVE, **NONE}
+LOW_SCHEMA = {
+ "traj": {"q": {"type": "list", "doc": f"1-{TRAJ_MAX} joint-target vectors [base_x, base_y, q1..q7], one per 10 ms "
+ "control step from the next step on, followed exactly (then the robot returns "
+ "to its ready pose, the base home); each within the joint ranges and the "
+ "joint speed limits"}},
+ **SERVE, **NONE}
+
+
+def _vec(body, key, n):
+ v = body.get(key)
+ if not isinstance(v, (list, tuple)) or len(v) != n:
+ raise Refused(f"{key} must be a list of {n} numbers")
+ out = []
+ for x in v:
+ if isinstance(x, bool) or not isinstance(x, (int, float)) or not math.isfinite(x):
+ raise Refused(f"{key} must hold {n} finite numbers")
+ out.append(float(x))
+ return out
+
+
+def _common(seat, body, match, allowed, lead=0):
+ if not isinstance(body, dict):
+ raise Refused("the action must be a JSON object")
+ typ = body.get("type")
+ if typ not in allowed:
+ raise Refused(f"unknown action type {typ!r}; one of {sorted(allowed)}")
+ extra = sorted(set(body) - set(allowed[typ]) - {"type"})
+ if extra:
+ raise Refused(f"unknown field(s) {extra} for {typ}")
+ item = match.deferred.get(seat)
+ if item is not None and item["k0"] > match.k:
+ raise Refused(f"your previous act takes effect at step {item['k0']}; send the next command after that", 409)
+ if typ == "none":
+ return {"type": "none"}
+ if typ == "toss":
+ rel = _vec(body, "pos", 3)
+ h = body.get("height", 0.0)
+ if isinstance(h, bool) or not isinstance(h, (int, float)) or not math.isfinite(h):
+ raise Refused("height must be a finite number (0: released from rest)")
+ bad = match.serve_refusal(seat, match.k + lead, rel, float(h))
+ if bad:
+ raise Refused(f"toss refused: {bad[0]}", bad[1])
+ return {"type": "toss", "pos": rel, "height": float(h)}
+ return None
+
+
+class LowLayer:
+ """Low level: joint targets (traj), none and toss, effective at the next control step."""
+ level = "low"
+ worker = None
+ delay_steps = 0
+
+ def schema(self, match, seat):
+ return LOW_SCHEMA
+
+ def parse(self, seat, body, match, ctx):
+ out = _common(seat, body, match, LOW_SCHEMA)
+ if out is not None:
+ return out
+ q = body.get("q")
+ if not isinstance(q, list) or not 1 <= len(q) <= TRAJ_MAX:
+ raise Refused(f"q must be a list of 1 to {TRAJ_MAX} joint-target vectors")
+ return {"type": "traj", "k0": None, "q": [_vec({"q": r}, "q", 9) for r in q]}
+
+ def snapshot(self, seat, cmd, match, ordinal):
+ return None
+
+ def prepare(self, job):
+ return None
+
+ def lower(self, seat, cmd, prepared, match):
+ return cmd, {}
+
+ def reply(self, seat, cmd, info, match):
+ return info
+
+
+def plan_job(job, model) -> dict:
+ """The legacy planner (wc._worker / the duel's workers.plan): restore the exact copy taken at the request step,
+ advance it to the effect step k0 = request step + lead with the command in force, and plan the act there
+ (wc.plan_on / bduel.plan_on: what Match.rt_act at k0 would do). Single: if the point ends on the way, the act
+ is dropped (as in the legacy planner)."""
+ k0 = int(job["k_req"]) + int(job["lead"])
+ out = {"k_effect": k0, "status": "ok"}
+ if job.get("none"):
+ return out
+ t0 = time.monotonic()
+ if job["single"]:
+ m = WC.restore(job["snap"], model)
+ while m.k < k0:
+ n0 = len(m.points)
+ m.rt_advance(1)
+ if len(m.points) > n0 or m.done:
+ out["status"] = "dropped"
+ return out
+ out["key"] = WC.state_key(m)
+ res = WC.plan_on(m, job["dec"])
+ else:
+ side = BD.restore(job["snap"], model)
+ while side.k < k0:
+ side.solo_step()
+ out["key"] = side.state_key()
+ res = BD.plan_on(side, job["dec"])
+ out.update(plan=[np.asarray(q, np.float64) for q in res["plan"]],
+ q_hit=None if res["q_hit"] is None else np.asarray(res["q_hit"], np.float64), info=res["info"],
+ plan_s=time.monotonic() - t0)
+ return out
+
+
+class PlanCtx:
+ """The seat's plan worker: the MjModel the snapshots are restored with."""
+
+ def __init__(self):
+ self.model = BM.Phys().m
+
+ def plan(self, job):
+ return plan_job(job, self.model)
+
+
+class RacketLayer(LowLayer):
+ """High level: the legacy racket command. `act` (and `none`) take effect `lead` control steps after the step at
+ which the request arrives (the legacy act lead); an act is planned in the seat's plan worker from a snapshot of
+ that step and lowered to a low-level traj with its effect step."""
+ level = "high"
+ worker = "plan"
+
+ def __init__(self, lead):
+ self.lead = lead
+ self.ctx = None # an in-process planner for a late act (see lower)
+
+ def schema(self, match, seat):
+ return HIGH_SCHEMA
+
+ def parse(self, seat, body, match, ctx):
+ out = _common(seat, body, match, HIGH_SCHEMA, self.lead)
+ if out is not None:
+ return out
+ T = body.get("t")
+ if isinstance(T, bool) or not isinstance(T, (int, float)) or not math.isfinite(T):
+ raise Refused("t must be a finite number")
+ pos, nrm, vel = _vec(body, "pos", 3), _vec(body, "normal", 3), _vec(body, "vel", 3)
+ if np.linalg.norm(nrm) < 1e-6:
+ raise Refused("normal must be a non-zero vector")
+ if not 0.0 < T <= T_MAX_S:
+ raise Refused(f"t must be in (0, {T_MAX_S}] s from when the act takes effect")
+ if not (abs(pos[0]) <= 3.4 and -7.5 <= pos[1] <= -0.3 and 0.2 <= pos[2] <= 3.0):
+ raise Refused("pos out of range: |x| <= 3.4, -7.5 <= y <= -0.3, 0.2 <= z <= 3.0")
+ if np.linalg.norm(vel) > 8.0:
+ raise Refused("vel too large: |vel| <= 8 m/s")
+ return {"type": "act", "t": float(T), "pos": pos, "normal": nrm, "vel": vel}
+
+ def snapshot(self, seat, cmd, match, ordinal):
+ job = {"single": match.single, "k_req": int(match.k), "lead": self.lead}
+ if cmd["type"] in ("none", "toss"): # nothing to plan: takes effect `lead` steps after the request
+ return dict(job, none=True)
+ match._ctx()
+ snap = WC.snapshot(match.g) if match.single else BD.snapshot(match.g.sides[seat])
+ return dict(job, snap=snap, dec=cmd)
+
+ def prepare(self, job):
+ if job.get("none"):
+ return plan_job(job, None)
+ if self.ctx is None:
+ self.ctx = PlanCtx()
+ return self.ctx.plan(job)
+
+ def lower(self, seat, cmd, prepared, match):
+ k0 = int(prepared["k_effect"])
+ if cmd["type"] == "none":
+ return {"type": "none", "k0": k0}, {"effect_step": k0}
+ if cmd["type"] == "toss":
+ return {"type": "toss", "k0": max(k0, int(match.k)), "pos": cmd["pos"], "height": cmd["height"]}, \
+ {"effect_step": k0}
+ late = match.k - k0
+ if late > 0 and prepared.get("status") == "ok" and cmd["t"] - late * DT > 0:
+ # the plan worker missed the effect step (the legacy service stalled the world until the plan came): plan
+ # again here, from the state now, for an effect now and the same contact time (the world waits)
+ d = dict(cmd, t=round(cmd["t"] - late * DT, 6))
+ job = dict(self.snapshot(seat, d, match, 0), lead=0)
+ prepared = self.prepare(job)
+ prepared["info"]["replanned_late_steps"] = late
+ k0 = int(prepared["k_effect"])
+ if prepared.get("status") != "ok": # the point ends before the effect step: nothing to install
+ return {"type": "traj", "k0": k0, "q": [], "key": "dropped: the point ends before the effect step"}, \
+ {"effect_step": k0, "stroke": {"stroke": "dropped: the point ends before the act takes effect"}}
+ info = _clean({k: v for k, v in prepared["info"].items() if k in STROKE_KEYS + ("replanned_late_steps",)})
+ low = _clean({"type": "traj", "k0": k0, "q": prepared["plan"], "q_hit": prepared["q_hit"],
+ "key": prepared["key"], "info": prepared["info"]})
+ return low, {"stroke": info, "effect_step": k0}
+
+ def reply(self, seat, cmd, info, match):
+ return info
+
+
+# ---------------------------------------------------------------------------------------------- render
+def _players_model(live, scene_file):
+ """The model the cameras draw: the players' presentation scene (presentation/presentation.toml `players`: the
+ Franka Panda's visual meshes on the same bodies, renderer rule 6; same kinematics, checked) with the live model's
+ marker settings, else the live model itself."""
+ from renderers import Scene, players_model
+ fine = players_model(HERE, Scene.from_file(scene_file))
+ if fine is None:
+ return live
+ if fine.nsite == live.nsite:
+ fine.site_pos[:], fine.site_size[:], fine.site_rgba[:] = live.site_pos, live.site_size, live.site_rgba
+ return fine
+
+
+class Views:
+ """The legacy observation images: 2 cameras x 4 frames, each tile stamped `k=.. t=..`, one PNG. Tiles are cached by
+ their content, so a frame shown in several observations is drawn once (same pixels). Since revision wallclock-5 /
+ duel-7 the arms are drawn with the players' presentation scene (the Franka Panda's 25k visual meshes)."""
+
+ def __init__(self, single, side):
+ import mujoco as mj
+ self.mj, self.single = mj, single
+ if single:
+ self.m = _players_model(mj.MjModel.from_xml_path(str(BM.SCENE)), BM.SCENE)
+ w, h = BM.Match.TILE
+ self.r = mj.Renderer(self.m, height=h, width=w)
+ self.rd = mj.MjData(self.m)
+ self.cams = []
+ for lookat, dist, az, el in BM.Match.CAMS:
+ c = mj.MjvCamera()
+ c.lookat[:] = lookat
+ c.distance, c.azimuth, c.elevation = dist, az, el
+ self.cams.append(c)
+ else:
+ self.dr = dr = BD.Renderer(side) # the legacy duel renderer: both robots, the side's own cameras
+ fine = _players_model(dr.m, BD.SCENE2)
+ if fine is not dr.m: # the same joints and qpos addresses (kinematics checked identical)
+ h, w = dr.r.height, dr.r.width
+ dr.r.close()
+ dr.m, dr.d = fine, mj.MjData(fine)
+ dr.r = mj.Renderer(fine, height=h, width=w)
+ self.cams = self.dr.cams
+ self.cache: dict = {}
+
+ def tile(self, ci, sn):
+ from PIL import Image, ImageDraw
+ mj = self.mj
+ if self.single:
+ rd = self.rd
+ rd.qpos[:] = sn["qpos"]
+ rd.mocap_pos[0] = sn["sh"]
+ v = np.asarray(sn["shv"], float)
+ if np.linalg.norm(v) < 1e-6:
+ v = np.array([0.0, 0.0, -1.0])
+ rd.mocap_quat[0] = BM.quat_z_to(v)
+ mj.mj_kinematics(self.m, rd)
+ self.r.update_scene(rd, camera=self.cams[ci])
+ BM.Match._extra_geoms(self.r.scene, np.asarray(sn["opp"], float), sn["sh"])
+ im = Image.fromarray(self.r.render())
+ ImageDraw.Draw(im).text((6, 4), f"k={sn['k']} t={sn['t']:.2f}s", fill=(255, 255, 255))
+ else:
+ dr = self.dr
+ dr.set_state(sn)
+ dr.r.update_scene(dr.d, camera=self.cams[ci])
+ im = Image.fromarray(dr.r.render())
+ t = (sn["k"] - sn["played_k"]) * DT
+ ImageDraw.Draw(im).text((6, 4), f"k={sn['k']} t={t:.2f}s", fill=(255, 255, 255))
+ return np.asarray(im)
+
+ @staticmethod
+ def content_key(ci, sn):
+ h = hashlib.sha1()
+ for name in sorted(sn):
+ v = sn[name]
+ h.update(name.encode())
+ h.update(np.ascontiguousarray(v, np.float64).tobytes() if isinstance(v, (np.ndarray, list, tuple))
+ else repr(v).encode())
+ return ci, h.hexdigest()
+
+ def draw(self, job):
+ rows = []
+ for ci in range(len(self.cams)):
+ tiles = []
+ for sn in job["snaps"]:
+ key = self.content_key(ci, sn)
+ if key not in self.cache:
+ self.cache[key] = self.tile(ci, sn)
+ tiles.append(self.cache[key])
+ rows.append(np.concatenate(tiles, axis=1))
+ if len(self.cache) > 64:
+ for key in list(self.cache)[:len(self.cache) - 48]:
+ del self.cache[key]
+ return png(np.concatenate(rows, axis=0))
+
+
+def png(img: np.ndarray) -> bytes:
+ """RGB8 PNG without row filters, zlib level 1 (the same pixels as the legacy imageio PNG, about 3x faster)."""
+ h, w = img.shape[:2]
+ raw = np.zeros((h, w * 3 + 1), np.uint8)
+ raw[:, 1:] = np.ascontiguousarray(img[..., :3], np.uint8).reshape(h, -1)
+
+ def chunk(tag, data):
+ return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
+ return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0))
+ + chunk(b"IDAT", zlib.compress(raw.tobytes(), 1)) + chunk(b"IEND", b""))
+
+
+_LOCAL_VIEWS: dict = {}
+
+
+class BadmintonSport:
+ name = "badminton"
+ protocol = "realtime"
+ revision = REVISION
+ source_dirs = [HERE]
+ workers = ("plan", "render")
+
+ def __init__(self):
+ self._lead = lead_steps(None)
+
+ def build(self, cfg):
+ self._lead = lead_steps(cfg.slowdown) # the core asks for the action layer right after build()
+ return Badminton(cfg)
+
+ def action_layer(self, level):
+ return RacketLayer(self._lead) if level == "high" else LowLayer()
+
+ def worker_init(self, kind, seat, cfg):
+ if kind == "plan":
+ return PlanCtx()
+ return Views(len(cfg.seats) == 1, seat if len(cfg.seats) > 1 else "A")
+
+ def worker_call(self, obj, kind, job):
+ if kind == "plan":
+ if obj is None:
+ obj = PlanCtx()
+ return obj.plan(job)
+ if obj is None: # in-process (core/local.py): one renderer per (format, side)
+ key = (job["single"], job["side"])
+ if key not in _LOCAL_VIEWS:
+ _LOCAL_VIEWS[key] = Views(*key)
+ obj = _LOCAL_VIEWS[key]
+ return {"png": obj.draw(job)}
+
+ def spec(self, cfg, seat, m):
+ lead = lead_steps(cfg.slowdown)
+ single = len(cfg.seats) == 1
+ out = {
+ "robot": ("franka-panda on a 1.0 m pedestal, base on x-y rails (<= 6 m/s, <= 20 m/s^2) + badminton racket "
+ f"(head centre 0.56 m beyond the flange, string bed radius {BM.R_HEAD} m)"),
+ "base": {"max_speed_mps": BM.BASE_VMAX, "max_accel_mps2": BM.BASE_AMAX, "home_xy": [float(x) for x in BM.HOME],
+ "range": {"x": [float(BM.BASE_LO[0]), float(BM.BASE_HI[0])],
+ "y": [float(BM.BASE_LO[1]), float(BM.BASE_HI[1])]}},
+ "frame": ("your own: x to your right, y towards the opponent, z up; your half y < 0, your base's home "
+ f"{[float(x) for x in BM.HOME]}" + ("" if single else "; the opponent's robot plays from y > 0 (in "
+ "its own frame it sees the game as you do)")),
+ "match": {"win_points": BM.WIN_POINTS, "two_point_lead_from": BM.WIN_POINTS - 1,
+ "cap_points": BM.CAP_POINTS, "max_hits": BM.MAX_HITS, "max_points_played": BM.MAX_POINTS,
+ "scoring": "rally point",
+ **({"opponent_level": m.level_, "first_player": seat, "first_server": seat,
+ "serves": "you serve the first point; then the winner of each rally serves the next point "
+ "(a let: the same server); the opponent serves like you, by the rules"} if single else
+ {"first_player": m.first, "first_server": m.first, "first_server_is_you": m.first == seat,
+ "serves": "match.first_server serves the first point; then the winner of each rally serves "
+ "the next point (a let: the same server)"})},
+ "serve": {"spot_right_court_xy": [float(x) for x in BM.serve_spot(True)],
+ "spot_left_court_xy": [float(x) for x in BM.serve_spot(False)],
+ "courts": "both robots stand in their right service courts when the server's score is even, else "
+ "in their left ones (diagonally opposite); the spot is your base's home for the point",
+ "base_tolerance_m": BM.BASE_TOL, "ready_s": round(BD.READY_STEPS * DT, 3),
+ "window_s": round(BM.SERVE_WINDOW_STEPS * DT, 3), "toss_z_m": list(BM.TOSS_Z),
+ "toss_reach_m": BM.TOSS_REACH, "toss_height_m": [0.0, BM.TOSS_H_MAX], "max_contact_z_m": BM.SERVE_MAX_Z,
+ "command": "{'type': 'toss', 'pos': [x, y, z], 'height': H}: the shuttle appears at the point "
+ "when the command takes effect (the same lead as an act) and rises H straight up "
+ "(0 <= H <= 0.5; 0 or omitted: released from rest); then hit it with an act (it may "
+ "be sent before the toss)",
+ "phases": "serve.phase: waiting (the receiver is getting ready), open (toss now), tossed, done",
+ "faults": "serve faults are recorded as 'serve_fault:<reason>: ...' (reasons: undue_delay, "
+ "missed, too_high, not_upwards, net, out, moved); the receiver's base moving early: "
+ "'receive_fault:moved: ...'"},
+ "act": {"lead_steps": lead, "lead_game_s": round(lead * DT, 4), "T_max_s": T_MAX_S,
+ "rule": (f"an act (and none) takes effect {lead} control steps after the step at which it arrives "
+ "(the stroke is planned meanwhile; the reply gives effect_step, the state shows "
+ "pending_commands, and a command sent before then is refused with HTTP 409); T counts "
+ "from the effect step" if cfg.action_level == "high" else
+ "traj and none take effect at the next control step")},
+ "cameras": [dict(c, fovy_deg=45.0, tile_px=list(BM.Match.TILE), focal_px=FOCAL_PX,
+ principal_point_px=[240, 180], image_right="forward x up") for c in BM.Match.cam_info()],
+ "image": "2 rows (behind, side) x 4 columns (camera frames 60 ms apart, oldest left); tile 480 x 360",
+ "shuttle": {"model": "point mass, gravity 9.81 + quadratic drag: dv/dt = g - K |v| v",
+ "K_per_m": round(BM.K_DRAG, 4), "terminal_speed_mps": BM.V_TERM,
+ "bounce": "none: the rally ends when it reaches the floor"},
+ }
+ if cfg.action_level == "low":
+ rob = m.robot(seat)
+ out["joints"] = {"names": BM.JOINTS, "low": [float(x) for x in rob.s.lo],
+ "high": [float(x) for x in rob.s.hi],
+ "max_step": [float(x) for x in BM.VEL_LIMIT * DT],
+ "ready_pose_arm": [float(x) for x in BM.Q0_ARM],
+ "rule": "each target within [low, high] and within max_step of the previous target "
+ "(the first one: of q_target in the state)"}
+ return out
+
+ def players(self):
+ import builtin_players as bp
+ return {"reference": bp.Reference, "random": bp.Random}
+
+
+SPORT = BadmintonSport()
diff --git a/scripts/roboolympics/shared/sports/badminton/presentation/presentation.toml b/scripts/roboolympics/shared/sports/badminton/presentation/presentation.toml
new file mode 100644
index 0000000000..c219480297
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/badminton/presentation/presentation.toml
@@ -0,0 +1,16 @@
+# Appearance of badminton's robots (docs/framework_zh.md §3.1, renderer rule 6; renderers/presentation/__init__.py):
+# the Franka Panda's visual meshes on the arm's bodies, same kinematics. Since revision wallclock-5 / duel-7 the
+# players' images use it too (`players`): tools/sportlib bundles this directory and the 25k level of detail of the
+# meshes (renderers/presentation/lod.json, sha256-pinned, licence kept) into the simulator, so they are part of
+# source_sha; spectator re-renders from a checkout use the full meshes.
+[presentation]
+version = 2
+label = "Franka Panda visual meshes (MuJoCo Menagerie)"
+players = "25k" # the players' images: the meshes decimated to ~25k triangles per arm
+scenes = ["sim/scene/bm_scene.xml", "sim/scene/bm_duel.xml"] # the match scenes (badminton has no Sport.scene())
+
+[[presentation.robot]]
+model = "franka_emika_panda" # renderers/presentation/menagerie.json (fetched, sha256-pinned)
+bodies = '^link(?P<n>[0-7])(?P<b>_b)?$'
+body = "link{n}"
+hide = "mesh" # the arm's collision meshes move to the hidden group 3
diff --git a/scripts/roboolympics/shared/sports/badminton/sim/bduel.py b/scripts/roboolympics/shared/sports/badminton/sim/bduel.py
new file mode 100644
index 0000000000..df3b2e91ae
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/badminton/sim/bduel.py
@@ -0,0 +1,628 @@
+"""Badminton duel: two robots, two players; rally scoring, first to 5 points, from 4-4 a two-point lead, at most 7.
+
+Robot A (y < 0, facing +y) and robot B (y > 0, facing -y) are identical: the match task's robot (a Franka Panda on a
+sliding base with a racket, bm.py). Each player sees and acts in its OWN frame, the frame of the single-player task
+(its home at (0, -4.0), its half y < 0); B's frame is the world rotated 180 degrees about z: (x, y, z) -> (-x, -y, z).
+
+Physics. MuJoCo contacts are off in the badminton scene and the shuttle is not a MuJoCo body, so the two robots never
+interact physically: each robot runs in its OWN copy of the single-player model (scene/bm_scene.xml, `bm.Phys`), in its
+own frame, stepped in lock-step at 1 ms; the shuttle (bm's point mass with quadratic drag) is integrated once, in the
+world frame (A's frame). At every 1 ms step the racket of the player whose turn it is is tested against the shuttle
+with the match task's contact model (bm.Phys._check_hit), and only while the shuttle is on that player's half. The
+two-robot scene scene/bm_duel.xml only draws the game.
+
+Stroke control. A player's act is the match task's racket-level command, planned by the match task's stroke controller
+(`bm.Match.plan_racket`) on that player's own robot (`Side`). Because each robot's motion depends only on its own
+joint targets, a planner process can advance an exact copy of the robot to the act's effect step and plan there; the
+result is bit-identical to planning in the world thread (`apply_inline`, which the replay uses).
+
+Points (the referee is a deterministic function of the 1 ms flight, evaluated inside every control step, so the
+logged acts replay the match bit-exactly):
+ * ready: both robots at rest in the ready pose at their spots in their service courts (bm.serve_spot: the right
+ courts when the server's score is even, else the left ones; diagonally opposite, BWF 10.1, 9.1.3); FIRST_SERVER
+ serves the first point, then the rally winner (Law 10.3; a let keeps the server). READY_STEPS (1 s) after play
+ resumes the receiver is ready (state to_serve) and the server may toss the shuttle (`toss`: it appears at a point
+ within bm.TOSS_REACH of its base, bm.TOSS_Z high, from rest or rising up to bm.TOSS_H_MAX) within
+ SERVE_WINDOW_STEPS, else a service fault (undue delay; the MAX_DELAY_FAULTS-th disqualifies the player, Law
+ 16.7). Faults are recorded as "serve_fault:<reason>: ..." (docs/conventions/racket_serve_zh.md). The server must
+ hit the tossed shuttle (a miss: fault, 9.1.8) below SERVE_MAX_Z (9.1.6) and upwards (9.1). Both bases stay within BASE_TOL of
+ their spots until the serve is delivered (9.1.4; the mover's fault, both: a let);
+ * the receiver must hit the serve; then the players hit in turn. A racket meets the shuttle only when it is that
+ player's turn and the shuttle is on that player's half; after a hit the hitter's racket no longer touches it;
+ * the shuttle lands (no bounce): in the court of the player whose turn it is (lines in) -> that player loses; out of
+ that court -> the last hitter loses; on the last hitter's own half -> the hitter loses; into the net (below the
+ top, between the posts) -> the hitter loses. An unreturned serve must land in the receiver's diagonal service
+ court (else a service fault: the receiver's point).
+"""
+from __future__ import annotations
+
+import hashlib
+import io
+import json
+import os
+import pickle
+from collections import deque
+from pathlib import Path
+
+import numpy as np
+
+import mujoco as mj
+import bm
+
+# The robot, its base (6 m/s, 20 m/s^2), the scoring (first to 5, two-point lead from 4-4, at most 7), the hit cap and
+# the shot timeout are the match task's (bm.py): the single-player task and the duel play by the same rules.
+from bm import (BASE_VMAX, BASE_AMAX, WIN_POINTS, CAP_POINTS, MAX_HITS, MAX_POINTS, LEG_STEPS) # noqa: E402,F401
+from bm import (CONTROL_DT, SUBSTEPS, PHYS_DT, KP, KD, HOME, NET_TOP, POST_X, R_HEAD, RACKET_GAIN, E_SHUTTLE,
+ OFFCENTRE_LOSS, SHOT_THETAS, SHOT_VMAX, sh_step, solve_shots, in_court)
+from bm import SERVE_MAX_Z, SERVE_WINDOW_STEPS, BASE_TOL, MAX_DELAY_FAULTS, serve_spot, toss_problem, toss_vz # noqa: E402
+
+HERE = Path(__file__).resolve().parent
+SCENE2 = HERE / "scene" / "bm_duel.xml"
+REVISION = "bm-duel-wallclock-6" # 2: base 6 m/s; 3: BWF serve courts, net 1.524 m, win by 2 (cap 7), receiver every point; 4: no draws (cap winner), rules in bm.py; 5: one scatter sequence for both robots; 6: the players serve (BWF Law 9)
+SEED = int(os.environ.get("DUEL_SEED", "1")) # the (shared) execution scatter
+FIRST_SERVER = os.environ.get("FIRST_SERVER", "A") # the side that serves the first point (Law 6: the toss)
+if FIRST_SERVER not in ("A", "B"):
+ raise ValueError("FIRST_SERVER must be A or B")
+SIDES = ("A", "B")
+OTHER = {"A": "B", "B": "A"}
+MIR = np.array([-1.0, -1.0, 1.0])
+READY_STEPS = 100 # 1.0 s from resume until the receiver is ready and the server may toss
+CAM_EVERY = 2
+Q_HOME = np.r_[HOME, bm.Q0_ARM]
+
+
+def mir(v):
+ return np.asarray(v, float) * MIR
+
+
+def to_side(side, v):
+ """World (A's frame) -> the side's own frame (and back: the map is its own inverse)."""
+ return np.asarray(v, float) if side == "A" else mir(v)
+
+
+# ---------------------------------------------------------------------------------------------- one player's robot
+class Side(bm.Match):
+ """One player's robot and stroke controller in its own frame: the match task's `Match` without the shuttle, the
+ opponent and the referee (those live in `World`). Used live, in the planner process (an exact copy) and in the
+ replay."""
+
+ def __init__(self, side: str): # noqa: D107 (bm.Match.__init__ is not called on purpose)
+ self.side = side
+ self.level = 0
+ # the execution scatter: ONE seeded sequence shared by both robots (the n-th act of each robot gets the same
+ # scatter draw, bm.Match.plan_racket), so neither seat nor role picks a luckier stream (as baseball's duel
+ # gives both batters the same pitches); revision 4 drew a stream per role (seed x 10 + 0 for the first
+ # receiver, + 1 for the other), which made the first receiver win 30 of 40 fairness matches
+ self.lv = {"seed": SEED * 10}
+ self.s = bm.Phys()
+ self.s.reset(Q_HOME.copy())
+ self.home = HOME.copy() # the ready target's base goal: the point's spot (go_home)
+ self._twin = None
+ self.plan, self.plan_j = [], 0
+ self.leg = {"launch": 0}
+ self.shots: list = []
+ self._last_act = None
+ self._q_hit_active = None
+ self._ik_seed = None
+ self.n_applied = 0 # acts applied so far (the execution scatter's stream index)
+ self.n_since_reset = 0 # control steps since the robot was last put back at home
+
+ @property
+ def n_our_legs(self): # bm.Match.plan_racket's scatter index: this player's act ordinal
+ return self.n_applied
+
+ def _target_vel(self):
+ a = self.s._actions
+ return (a[-1] - a[-2]) / CONTROL_DT if self.n_since_reset >= 2 and len(a) >= 2 else np.zeros(9)
+
+ def rt_act(self, T, pos, nrm, vel):
+ self.leg = {"launch": self.k} # T counts from now
+ return super().rt_act(T, pos, nrm, vel)
+
+ def go_home(self, spot):
+ """Before a serve: the robot at its spot in its service court (its home for the point) in the ready pose, at
+ rest, no command."""
+ ph = self.s
+ self.home = np.asarray(spot, float).copy()
+ q = np.r_[self.home, bm.Q0_ARM]
+ ph.d.qpos[ph.qa] = q; ph.d.qvel[ph.va] = 0.0
+ mj.mj_forward(ph.m, ph.d)
+ ph.target = q.copy()
+ self.plan, self.plan_j = [], 0
+ self._last_act = None; self._q_hit_active = None
+ self.n_since_reset = 0
+
+ def solo_step(self):
+ """One control step of this robot alone (the planner's copy): the same targets and robot physics as World."""
+ q = np.asarray(self._arm_target(), float)
+ self.s.step(q)
+ self.n_since_reset += 1
+
+ def state_key(self) -> str:
+ """Everything the stroke planner reads, hashed."""
+ ph = self.s
+ h = hashlib.sha256()
+ for a in (ph.d.qpos, ph.d.qvel, ph.d.qacc_warmstart, ph.d.ctrl, np.array([ph.d.time]), ph.target):
+ h.update(np.ascontiguousarray(a, dtype=np.float64).tobytes())
+ h.update(repr((self.k, self.plan_j, len(self.plan), self.n_applied, self.n_since_reset)).encode())
+ h.update(np.ascontiguousarray(self.home, dtype=np.float64).tobytes())
+ if len(ph._actions) >= 2:
+ h.update(np.ascontiguousarray(ph._actions[-2], dtype=np.float64).tobytes())
+ if self._q_hit_active is not None:
+ h.update(np.ascontiguousarray(self._q_hit_active, dtype=np.float64).tobytes())
+ if self.plan_j < len(self.plan):
+ h.update(np.ascontiguousarray(np.asarray(self.plan[self.plan_j:]), dtype=np.float64).tobytes())
+ return h.hexdigest()
+
+
+def plan_on(side: Side, dec: dict) -> dict:
+ """What `apply_inline` would do at the copy's current step, as an installable result."""
+ if dec["type"] == "none":
+ return {"type": "none"}
+ T = float(dec["t"])
+ side.leg = {"launch": side.k}
+ ik_seed = side._q_hit_active if side.plan_j < len(side.plan) else None
+ side._ik_seed = ik_seed
+ plan, info = side.plan_racket(T, dec["pos"], dec["normal"], dec["vel"])
+ q_hit = info.pop("_q_hit", None)
+ info["T_from_now"] = round(T, 4)
+ return {"type": "act", "plan": plan, "q_hit": q_hit, "info": info, "ik_seed": ik_seed,
+ "swing_last": getattr(side, "_swing_last", None)}
+
+
+def install(side: Side, res: dict):
+ """Apply a planned result with exactly the attribute changes of `apply_inline`."""
+ side.n_applied += 1
+ if res["type"] == "none":
+ side.rt_clear()
+ return None
+ side.leg = {"launch": side.k}
+ side._ik_seed = res["ik_seed"]
+ if res["swing_last"] is not None:
+ side._swing_last = res["swing_last"]
+ info = res["info"]
+ if res["plan"]:
+ side.plan, side.plan_j = res["plan"], 0
+ side._q_hit_active = res["q_hit"]
+ side.shots.append({"k": side.k, "leg": side.n_applied - 1, **info})
+ side._last_act = info
+ return info
+
+
+def apply_inline(side: Side, dec: dict):
+ """The reference semantics (also the replay's): plan and apply at the current step."""
+ if dec["type"] == "none":
+ side.n_applied += 1
+ side.rt_clear()
+ return None
+ info = side.rt_act(dec["t"], dec["pos"], dec["normal"], dec["vel"])
+ side.n_applied += 1
+ return info
+
+
+# ---------------------------------------------------------------------------------------------- snapshots
+class _Pickler(pickle.Pickler):
+ def persistent_id(self, obj):
+ return "MODEL" if isinstance(obj, mj.MjModel) else None
+
+
+class _Unpickler(pickle.Unpickler):
+ def __init__(self, f, model):
+ super().__init__(f)
+ self.model = model
+
+ def persistent_load(self, pid):
+ if pid != "MODEL":
+ raise pickle.UnpicklingError(pid)
+ return self.model
+
+
+def snapshot(side: Side) -> bytes:
+ """Exact copy of one robot for planning (not copied: the MjModel, the scratch twin, older joint targets)."""
+ tw = side.__dict__.pop("_twin", None)
+ acts = side.s._actions
+ side.s._actions = acts[-2:]
+ try:
+ f = io.BytesIO()
+ _Pickler(f, protocol=pickle.HIGHEST_PROTOCOL).dump(side)
+ return f.getvalue()
+ finally:
+ side._twin = tw
+ side.s._actions = acts
+
+
+def restore(b: bytes, model) -> Side:
+ side = _Unpickler(io.BytesIO(b), model).load()
+ side._twin = None
+ return side
+
+
+# ---------------------------------------------------------------------------------------------- the world
+class World:
+ def __init__(self):
+ self.sides = {s: Side(s) for s in SIDES}
+ self.k = 0
+ self.sh_p, self.sh_v, self.sh_live = (0.0, 3.0, 1.0), (0.0, 0.0, 0.0), False
+ self.prev = {s: None for s in SIDES}
+ self.events: list[dict] = []
+ self.score = {"A": 0, "B": 0}
+ self.points: list[dict] = []
+ self.hits = 0
+ self.plays = 0 # tosses + hits in the match (a flight's id)
+ self.done = False
+ self.winner = None
+ self.hist: deque = deque(maxlen=16)
+ self.review_hist = None
+ self._pending_point = None
+ self.delay_faults = {"A": 0, "B": 0} # serves not tossed in time (undue delay)
+ self.disqualified = None # the side with MAX_DELAY_FAULTS (Law 16.7): it loses the match
+ self._start_point(0)
+
+ # ------------------------------------------------------------------ points
+ def next_server(self):
+ """FIRST_SERVER serves the first point (Law 6); then the winner of the last rally serves (Law 10.3); after a
+ let the same player serves again (Law 14.3)."""
+ if not self.points:
+ return FIRST_SERVER
+ last = self.points[-1]
+ return last["server"] if last["let"] else last["winner"]
+
+ def receiver(self):
+ return self.rs["receiver"]
+
+ def match_over(self):
+ """First to WIN_POINTS; from 4-4 a two-point lead is needed, capped: the first to CAP_POINTS wins."""
+ hi, lo = max(self.score.values()), min(self.score.values())
+ return (hi >= WIN_POINTS and hi - lo >= 2) or hi >= CAP_POINTS
+
+ def _start_point(self, hold_from):
+ n = len(self.points)
+ srv = self.next_server()
+ recv = OTHER[srv]
+ right = self.score[srv] % 2 == 0 # the server's right court when its score is even (Law 10.1)
+ spot = serve_spot(right) # both robots in their right (left) service courts: diagonal (9.1.3)
+ ready = hold_from + READY_STEPS
+ self.rs = {"point": n, "server": srv, "receiver": recv, "service_court_right": right,
+ "hold_from": hold_from, "ready": ready, "deadline": ready + SERVE_WINDOW_STEPS, "launch": ready,
+ "expect": srv, "last_hitter": None, "played_k": ready, "state": "ready", "flight": self.plays,
+ "hits_in_point": 0, "serve_flight": False, "toss_k": None, "serve": None, "spot": spot.copy()}
+ # the shuttle is held in the server's (missing) free hand, beside its ready pose, until the toss
+ self.sh_p = tuple(float(x) for x in to_side(srv, np.r_[spot + np.array([-0.25, 0.35]), 1.0]))
+ self.sh_v = (0.0, 0.0, 0.0)
+ self.sh_live = False; self.hit_enabled = False
+ self.events = []
+ self.hist.clear()
+ for s in SIDES:
+ self.sides[s].go_home(spot)
+ self.prev[s] = None
+
+ def delivered(self):
+ """The serve of the current point was delivered (hit or faulted)."""
+ return self.rs["state"] not in ("ready", "to_serve", "tossed")
+
+ def toss(self, side, p, h=0.0):
+ """The server's toss: the shuttle appears at p (its own frame) now and rises h straight up (0: from rest).
+ Raises ValueError if not allowed."""
+ rs = self.rs
+ if self.done or side != rs["server"]:
+ raise ValueError("it is not your serve")
+ if rs["state"] == "ready":
+ raise ValueError(f"the receiver is not ready before step {rs['ready']}")
+ if rs["state"] != "to_serve":
+ raise ValueError("the shuttle was already tossed")
+ ph = self.sides[side].s
+ why = toss_problem(p, h, ph.d.qpos[ph.qa[:2]])
+ if why:
+ raise ValueError(why)
+ self.sh_p = tuple(float(x) for x in to_side(side, p)); self.sh_v = (0.0, 0.0, toss_vz(h))
+ self.sh_live = True; self.hit_enabled = True
+ rs.update(state="tossed", toss_k=self.k, played_k=self.k, launch=self.k)
+ rs["serve"] = {"toss": [round(float(x), 4) for x in p], "toss_height": float(h), "toss_k": self.k}
+ self.plays += 1; rs["flight"] = self.plays
+ self.events.append({"kind": "toss", "side": side, "k": self.k})
+
+ def in_play(self):
+ return self.rs["state"] in ("tossed", "live")
+
+ def _end_point(self, loser, how):
+ if self._pending_point is None:
+ self._pending_point = (loser, how)
+
+ def _commit_point(self):
+ loser, how = self._pending_point
+ self._pending_point = None
+ winner = OTHER[loser] if loser is not None else None
+ if winner is not None:
+ self.score[winner] += 1
+ self.review_hist = list(self.hist)
+ self.points.append({"point": len(self.points) + 1, "winner": winner, "loser": loser, "how": how,
+ "score": dict(self.score), "hits": self.rs["hits_in_point"], "step": self.k,
+ "server": self.rs["server"], "receiver": self.rs["receiver"],
+ "court": "right" if self.rs["service_court_right"] else "left",
+ "serve": self.rs["serve"], "let": loser is None})
+ self.rs["state"] = "over"
+ if self.disqualified:
+ self.points[-1]["disqualified"] = self.disqualified
+ self.winner = OTHER[self.disqualified]
+ self.done = True
+ return
+ if self.match_over():
+ self.winner = max(SIDES, key=lambda s: self.score[s])
+ self.done = True
+ return
+ if self.hits >= MAX_HITS or len(self.points) >= MAX_POINTS:
+ # the cap: the leader wins; if level, the winner of the last point (no draws; as in the single task); the
+ # last resort (no point won, not from the rulebook): the player who received first
+ last = next((p["winner"] for p in reversed(self.points) if p["winner"]), OTHER[FIRST_SERVER])
+ sa, sb = self.score["A"], self.score["B"]
+ self.winner = "A" if sa > sb else "B" if sb > sa else last
+ self.points[-1]["cap"] = True
+ self.done = True
+ return
+ self._start_point(self.k)
+
+ # ------------------------------------------------------------------ physics (shared by live and replay)
+ def advance(self):
+ """One control step: both robots follow their commands (the planned stroke, else back to the ready pose)."""
+ if self.done:
+ raise ValueError("the match is over")
+ qs = {s: np.asarray(self.sides[s]._arm_target(), float) for s in SIDES}
+ for s in SIDES:
+ self.sides[s].s.check_target(qs[s])
+ prev_t = {s: self.sides[s].s.target for s in SIDES}
+ qd_des = {s: (qs[s] - prev_t[s]) / CONTROL_DT for s in SIDES}
+ rk = {}
+ for j in range(1, SUBSTEPS + 1):
+ for s in SIDES: # the robot part of bm.Phys.step, per robot in its own model
+ ph = self.sides[s].s
+ m, d = ph.m, ph.d
+ q_des = prev_t[s] + (qs[s] - prev_t[s]) * (j / SUBSTEPS)
+ tau = KP * (q_des - d.qpos[ph.qa]) + KD * (qd_des[s] - d.qvel[ph.va]) + d.qfrc_bias[ph.va]
+ d.ctrl[:] = np.clip(tau, m.actuator_ctrlrange[:, 0], m.actuator_ctrlrange[:, 1])
+ mj.mj_step(m, d)
+ c = d.site_xpos[ph.site].copy(); n = d.site_xmat[ph.site].reshape(3, 3)[:, 0].copy()
+ rk[s] = (to_side(s, c), to_side(s, n))
+ if self.sh_live:
+ e = self.rs["expect"]
+ own_half = self.sh_p[1] < 0 if e == "A" else self.sh_p[1] > 0
+ if self.hit_enabled and own_half and self.prev[e] is not None:
+ self._check_hit(e, *rk[e])
+ for s in SIDES:
+ self.prev[s] = (rk[s][0], rk[s][1], self.sh_p)
+ self._advance_shuttle()
+ else:
+ for s in SIDES:
+ self.prev[s] = (rk[s][0], rk[s][1], self.sh_p)
+ for s in SIDES:
+ ph = self.sides[s].s
+ ph.target = qs[s].copy()
+ ph._actions.append(qs[s].copy())
+ ph.k += 1
+ ph.steps_total += SUBSTEPS
+ self.sides[s].n_since_reset += 1
+ self.k += 1
+ rs = self.rs
+ if rs["state"] == "ready" and self.k >= rs["ready"]:
+ rs["state"] = "to_serve" # the receiver is ready (Law 9.4): the server may toss
+ if self._pending_point is None and rs["state"] != "over":
+ self._referee()
+ if self.k % CAM_EVERY == 0 or self._pending_point is not None:
+ self.hist.append(self.snap())
+ if self._pending_point is not None:
+ self._commit_point()
+
+ def snap(self):
+ return {"k": self.k, "qA": self.sides["A"].s.d.qpos.copy(), "qB": self.sides["B"].s.d.qpos.copy(),
+ "sh": self.sh_p, "shv": self.sh_v, "played_k": self.rs["played_k"], "point": self.rs["point"],
+ "flight": self.rs["flight"], "wall_mono": __import__("time").monotonic()}
+
+ def _check_hit(self, side, c, n):
+ """bm.Phys._check_hit for one racket (world frame)."""
+ cp, npv, sp = self.prev[side]
+ sp = np.array(sp); sh = np.array(self.sh_p)
+ s0 = float((sp - cp) @ npv); s1 = float((sh - c) @ n)
+ if s0 * s1 > 0 or (s0 == 0 and s1 == 0):
+ return
+ f = s0 / (s0 - s1) if s0 != s1 else 0.0
+ pc = cp + f * (c - cp); ps = sp + f * (sh - sp)
+ r = ps - pc
+ off = float(np.linalg.norm(r - (r @ n) * n))
+ if off > R_HEAD:
+ return
+ vr = (c - cp) / PHYS_DT; vs = np.array(self.sh_v)
+ n_out = n if float((vr - vs) @ n) >= 0 else -n
+ u = float(vr @ n_out); vin = float(vs @ n_out)
+ spd = RACKET_GAIN * max(u, 0.0) * (1 - OFFCENTRE_LOSS * (off / R_HEAD) ** 2) + E_SHUTTLE * max(0.0, -vin)
+ v_out = n_out * spd
+ p_new = ps + n_out * 0.002
+ self.sh_p = tuple(float(x) for x in p_new); self.sh_v = tuple(float(x) for x in v_out)
+ rs = self.rs
+ serve = rs["state"] == "tossed" # the server's hit of the tossed shuttle: the serve
+ rs["last_hitter"] = side; rs["expect"] = OTHER[side]; rs["played_k"] = self.k
+ rs["hits_in_point"] += 1; self.hits += 1; self.plays += 1; rs["flight"] = self.plays
+ rs["serve_flight"] = serve
+ self.events.append({"kind": "hit", "side": side, "k": self.k, "pos": [round(float(x), 4) for x in ps],
+ "offcentre": round(off, 4), "racket_speed": round(u, 3), "speed": round(spd, 3),
+ "v_out": [round(float(x), 3) for x in v_out]})
+ if serve:
+ rs["state"] = "live"
+ z = float(ps[2])
+ rs["serve"].update(hit_k=self.k, contact_z=round(z, 4), speed=round(spd, 3),
+ v_out=[round(float(x), 3) for x in to_side(side, v_out)])
+ if z > SERVE_MAX_Z: # Law 9.1.6: the whole shuttle below 1.15 m when hit
+ self._end_point(side, f"serve_fault:too_high: {side} hit the shuttle {z:.2f} m high, above {SERVE_MAX_Z} m "
+ "(Law 9.1.6)")
+ elif float(v_out[2]) <= 0.0: # Law 9.1: the flight upwards from the server's racket
+ self._end_point(side, f"serve_fault:not_upwards: {side}'s serve did not go upwards from the racket (Law 9.1)")
+
+ def _advance_shuttle(self):
+ """bm.Phys._advance_shuttle (world frame)."""
+ p, v = self.sh_p, self.sh_v
+ p1, v1 = sh_step(p, v)
+ if (p[1] > 0) != (p1[1] > 0) and p[1] != p1[1]:
+ f = p[1] / (p[1] - p1[1])
+ z = p[2] + f * (p1[2] - p[2]); x = p[0] + f * (p1[0] - p[0])
+ self.events.append({"kind": "cross", "k": self.k, "x": round(x, 4), "z": round(z, 4),
+ "to": "B" if p1[1] > 0 else "A"})
+ if z < NET_TOP and abs(x) <= POST_X:
+ self.sh_p = (x, 0.0, z); self.sh_v = (0.0, 0.0, 0.0); self.sh_live = False
+ self.events.append({"kind": "net", "k": self.k, "x": round(x, 4), "z": round(z, 4)})
+ return
+ if p1[2] <= 0.0:
+ f = p[2] / (p[2] - p1[2]) if p[2] != p1[2] else 1.0
+ x = p[0] + f * (p1[0] - p[0]); y = p[1] + f * (p1[1] - p[1])
+ self.sh_p = (x, y, 0.0); self.sh_v = (0.0, 0.0, 0.0); self.sh_live = False
+ self.events.append({"kind": "land", "k": self.k, "x": round(x, 4), "y": round(y, 4)})
+ return
+ self.sh_p, self.sh_v = p1, v1
+
+ def _referee(self):
+ rs = self.rs
+ if not self.delivered(): # Law 9.1.4: server and receiver stand still until the serve
+ moved = {}
+ for s in SIDES:
+ ph = self.sides[s].s
+ d = float(np.hypot(*(ph.d.qpos[ph.qa[:2]] - rs["spot"])))
+ if d > BASE_TOL:
+ moved[s] = d
+ if len(moved) == 2:
+ return self._end_point(None, "let: both bases moved before the serve was delivered (Law 14.2.2)")
+ if moved:
+ s, d = next(iter(moved.items()))
+ who = "serve_fault:moved" if s == rs["server"] else "receive_fault:moved"
+ return self._end_point(s, f"{who}: {s}'s base moved {d:.2f} m from its spot before the serve was "
+ "delivered (Law 9.1.4)")
+ srv = rs["server"]
+ if rs["state"] == "to_serve":
+ if self.k >= rs["deadline"]:
+ self.delay_faults[srv] += 1
+ dq = self.delay_faults[srv] >= MAX_DELAY_FAULTS
+ if dq:
+ self.disqualified = srv
+ return self._end_point(srv, f"serve_fault:undue_delay: {srv} did not toss the shuttle within "
+ f"{SERVE_WINDOW_STEPS * CONTROL_DT:.0f} s (undue delay, Law 9.1.1)"
+ + (f"; {srv}'s {MAX_DELAY_FAULTS}rd undue-delay fault disqualifies it "
+ "(Law 16.7)" if dq else ""))
+ return
+ if rs["state"] not in ("tossed", "live"):
+ return
+ exp, hitter = rs["expect"], rs["last_hitter"]
+ ends = [e for e in self.events if e["kind"] in ("net", "land") and e["k"] == self.k - 1]
+ if ends:
+ e = ends[0]
+ if rs["state"] == "tossed": # the tossed shuttle reached the floor: the server missed it
+ return self._end_point(srv, f"serve_fault:missed: {srv} missed the shuttle (Law 9.1.8)")
+ if e["kind"] == "net":
+ if rs["serve_flight"]:
+ return self._end_point(hitter, f"serve_fault:net: {hitter}'s serve hit the net (x={e['x']:.2f}, "
+ f"height {e['z']:.2f} m; Laws 9.1, 13.3.2)")
+ return self._end_point(hitter, f"{hitter}'s shot hit the net (x={e['x']:.2f}, height {e['z']:.2f} m)")
+ x, y = e["x"], e["y"]
+ half = "A" if y < 0 else "B"
+ sign = lambda s: -1 if s == "A" else 1 # in_court's side argument in the world frame
+ if half == hitter:
+ return self._end_point(hitter, f"{hitter}'s shot came down on its own side (x={x:.2f}, y={y:.2f})")
+ if rs["serve_flight"]: # the serve: it must land in the receiver's diagonal service court
+ xr, yr = to_side(exp, [x, y, 0.0])[:2]
+ if bm.in_service_court(xr, yr, rs["service_court_right"]):
+ return self._end_point(exp, f"{hitter}'s serve landed in {exp}'s service court (x={x:.2f}, "
+ f"y={y:.2f}): {exp} did not return it")
+ return self._end_point(hitter, f"serve_fault:out: {hitter}'s serve landed outside {exp}'s service court "
+ f"(x={x:.2f}, y={y:.2f})")
+ if in_court(x, y, sign(exp)):
+ return self._end_point(exp, f"{hitter}'s shot landed in {exp}'s court (x={x:.2f}, y={y:.2f}): {exp} did not return it")
+ return self._end_point(hitter, f"{hitter}'s shot landed out (x={x:.2f}, y={y:.2f})")
+ if self.k - rs["played_k"] > LEG_STEPS:
+ return self._end_point(exp, f"{exp} did not play the shuttle in time")
+
+ # ------------------------------------------------------------------ replay and fingerprints
+ def actions(self):
+ return {s: [q.tolist() for q in self.sides[s].s._actions] for s in SIDES}
+
+ def state_sha(self):
+ h = hashlib.sha256()
+ for s in SIDES:
+ d = self.sides[s].s.d
+ for a in (d.qpos, d.qvel, d.qacc_warmstart, d.ctrl, np.array([d.time])):
+ h.update(np.ascontiguousarray(a, dtype=np.float64).tobytes())
+ h.update(np.array(self.sh_p + self.sh_v, dtype=np.float64).tobytes())
+ h.update(json.dumps(self.points, sort_keys=True).encode())
+ return h.hexdigest()
+
+ def targets_sha(self):
+ return hashlib.sha256(json.dumps(self.actions(), sort_keys=True, separators=(",", ":")).encode()).hexdigest()
+
+
+# ---------------------------------------------------------------------------------------------- rendering
+CAMS = bm.Match.CAMS # behind and side, in the player's own frame (as in the match task)
+VIEW_BACK = bm.Match.VIEW_BACK # 0, 60, 120, 180 ms back
+TILE = bm.Match.TILE
+
+
+class Renderer:
+ """Draws the two-robot scene: the player's two cameras (in its own frame) x 4 frames."""
+
+ def __init__(self, side="A", width=TILE[0], height=TILE[1]):
+ self.m = mj.MjModel.from_xml_path(str(SCENE2))
+ self.d = mj.MjData(self.m)
+ jid = lambda n: self.m.jnt_qposadr[mj.mj_name2id(self.m, mj.mjtObj.mjOBJ_JOINT, n)]
+ self.qa = {"A": np.array([jid(j) for j in bm.JOINTS]), "B": np.array([jid(j + "_b") for j in bm.JOINTS])}
+ self.r = mj.Renderer(self.m, height=height, width=width)
+ self.cams = []
+ for lookat, dist, az, el in CAMS:
+ c = mj.MjvCamera()
+ c.lookat[:] = to_side(side, lookat); c.distance = dist; c.azimuth = az + (0.0 if side == "A" else 180.0)
+ c.elevation = el
+ self.cams.append(c)
+
+ def set_state(self, sn):
+ d = self.d
+ d.qpos[self.qa["A"]] = sn["qA"]; d.qpos[self.qa["B"]] = sn["qB"]
+ d.mocap_pos[0] = sn["sh"]
+ v = np.asarray(sn["shv"], float)
+ if np.linalg.norm(v) < 1e-6:
+ v = np.array([0.0, 0.0, -1.0])
+ d.mocap_quat[0] = bm.quat_z_to(v)
+ mj.mj_kinematics(self.m, d)
+
+ def views(self, snaps) -> bytes:
+ import imageio.v2 as imageio
+ from PIL import Image, ImageDraw
+ rows = []
+ for c in self.cams:
+ tiles = []
+ for sn in snaps:
+ self.set_state(sn)
+ self.r.update_scene(self.d, camera=c)
+ im = Image.fromarray(self.r.render())
+ t = (sn["k"] - sn["played_k"]) * CONTROL_DT
+ ImageDraw.Draw(im).text((6, 4), f"k={sn['k']} t={t:.2f}s", fill=(255, 255, 255))
+ tiles.append(np.asarray(im))
+ rows.append(np.concatenate(tiles, axis=1))
+ buf = io.BytesIO()
+ imageio.imwrite(buf, np.concatenate(rows, axis=0), format="png")
+ return buf.getvalue()
+
+
+def render_video(acts, k_end, out, fps=25, every=2):
+ """Replay video from the logged acts: a high side view of the whole court, 2x slow motion, with the score."""
+ import imageio.v2 as imageio
+ from PIL import Image, ImageDraw
+ w = World()
+ rd = Renderer("A", 640, 360)
+ cam = mj.MjvCamera(); cam.lookat[:] = [0.0, 0.0, 1.0]; cam.distance = 17.0; cam.azimuth = 0.0; cam.elevation = -22.0
+ vw = imageio.get_writer(out, fps=fps, macro_block_size=8)
+ i = 0
+ while w.k < k_end and not w.done:
+ while i < len(acts) and acts[i][0] == w.k:
+ apply_inline(w.sides[acts[i][1]], acts[i][2]); i += 1
+ w.advance()
+ if w.k % every or (w.rs["state"] != "live" and w.k % (3 * every)):
+ continue
+ rd.set_state(w.snap())
+ rd.r.update_scene(rd.d, camera=cam)
+ im = Image.fromarray(rd.r.render())
+ ImageDraw.Draw(im).text((10, 8), f"B (left) {w.score['B']} : {w.score['A']} A (right) point {len(w.points) + 1}",
+ fill=(255, 255, 255))
+ vw.append_data(np.asarray(im))
+ vw.close()
diff --git a/scripts/roboolympics/shared/sports/badminton/sim/bm.py b/scripts/roboolympics/shared/sports/badminton/sim/bm.py
new file mode 100644
index 0000000000..3b313fd3db
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/badminton/sim/bm.py
@@ -0,0 +1,1600 @@
+"""Core of the robot badminton match service (interactive mode): first to 5 (two-point lead from 4-4, at most 7) against a scripted opponent.
+
+World (metres, seconds): floor z = 0, court long axis y, net = the plane y = 0 with its top at 1.524 m. The robot's
+half is y < 0, the opponent's y > 0. Singles court |x| <= 2.59, |y| <= 6.70.
+
+Robot: a Franka Panda arm on a 1.0 m pedestal whose base slides in x and y (a mobile base: 2 prismatic joints, speed
+<= 6 m/s), holding a badminton racket (head centre 0.56 m beyond the flange). One action = 9 absolute joint targets
+[base_x, base_y, q1..q7] held for 10 ms; a PD controller with bias compensation (1 ms physics steps) tracks them;
+target steps are limited to the joint speed limits (base 6 m/s, Franka datasheet for the arm).
+
+Shuttlecock (not a MuJoCo body; integrated here at 1 ms, semi-implicit Euler, pure Python floats, deterministic):
+a point mass under gravity and quadratic drag, dv/dt = g - K |v| v with K = g / V_TERM^2, V_TERM = 6.8 m/s (the
+measured terminal speed of a feather shuttle). A real shuttle flips to fly cork first within a few centimetres of a
+hit; a point mass has no orientation, it is drawn cork first along its velocity. No bounce: when the shuttle reaches
+the floor (z <= 0) the rally is over.
+
+Racket-shuttle contact (a model, not MuJoCo contact): at every 1 ms step the shuttle's centre is tested against the
+racket's string plane; when it crosses the plane within R_HEAD of the head centre, the shuttle leaves along the face
+normal (the side facing the relative motion) at
+ speed = RACKET_GAIN * (racket-head speed along the normal) * (1 - OFFCENTRE_LOSS (r / R_HEAD)^2)
+ + E_SHUTTLE * (incoming speed into the face)
+RACKET_GAIN = 20 stands for the string bed and the wrist snap a Franka does not have (a Franka moves the head at a few
+m/s; a badminton shot needs 15-50 m/s). One hit per shot.
+
+Point flow (all inside Match.step() and the player's commands, so a recorded command sequence replays the whole match
+bit-exactly). You serve the first point; then the winner of the last rally serves (BWF Law 10.3). Both players stand
+at their spots in their service courts (serve_spot, diagonally opposite) before every serve:
+ ready READY_STEPS; the server holds the shuttle.
+ serve the opponent's serve: high and deep, or short (a seeded choice per point, by level), hit at 1.05 m
+ upwards into your diagonal service court. Your serve (leg kind "our_serve"): within SERVE_WINDOW_STEPS you
+ toss the shuttle (toss(), the `toss` command) and hit it below SERVE_MAX_Z, upwards; then it flies
+ to the opponent like any of your shots (it must land in the opponent's diagonal service court).
+ our leg the shuttle comes to us; the model decides the shot (live code: swing / adjust decision points); the
+ robot hits it or not. Our shot is good if the shuttle crosses the net above its top and would land in the
+ opponent's court. The shuttle landing in our court, the net, out = the opponent's point.
+ opp leg the opponent (below) returns it (a new "our leg" starts at its hit) or cannot reach it (our point when it
+ lands in); a shot that would land out it leaves (our fault).
+
+The opponent (LEVELS): a kinematic player on its half, at home (0, 3.8) between rallies. `reaction_s` after our hit it
+predicts the flight perfectly and moves in a straight line towards the best interception point at `chase` m/s; after
+its own shots it walks back home at `recover` m/s. For every point of the flight in its hitting envelope (its half,
+height 0.1-2.7 m) it evaluates
+ pressure = max(max(0, distance - chase * time) / reach, (shuttle speed there - SPEED_FREE) / (max_speed - SPEED_FREE))
+takes the shuttle at the earliest point whose pressure is within 0.05 of the minimum, and there, deterministically:
+pressure > 1 -> it misses (our point); > PRESSURE_WEAK -> a weak lift to the middle of our court; < PRESSURE_PASSIVE ->
+it attacks (a smash from above 1.9 m, else a tight drop or a fast push to a corner, at its widest); otherwise a
+normal return (a seeded clear / drop / drive within the level's width and pace). It sets the shuttle's velocity (an
+impulse; its racket is drawn only) so that the shuttle lands at its target, clears the net by >= 15 cm, and our robot
+can reach the flight from where it stands; an unreachable shot moves towards the centre and becomes gentler.
+Our strokes scatter: the aim is perturbed by a seeded N(0, EXEC_SIGMA[power]) per shot.
+"""
+from __future__ import annotations
+
+import hashlib
+import io
+import json
+import math
+import os
+from collections import deque
+from pathlib import Path
+
+import numpy as np
+
+import mujoco as mj
+
+HERE = Path(__file__).resolve().parent
+SCENE = Path(os.environ.get("RCB_BM_SCENE", HERE / "scene" / "bm_scene.xml"))
+
+CONTROL_DT, SUBSTEPS, PHYS_DT = 0.01, 10, 0.001
+GRAV, V_TERM = 9.81, 6.8
+K_DRAG = GRAV / V_TERM ** 2
+NET_TOP, COURT_X, COURT_Y, POST_X = 1.524, 2.59, 6.70, 3.05 # BWF Law 1.10: net top 1.524 m (at the centre)
+SHORT_SERVICE_Y = 1.98
+R_HEAD, RACKET_GAIN, E_SHUTTLE, OFFCENTRE_LOSS = 0.14, 20.0, 0.15, 0.3
+ARM_VEL = np.array([2.175, 2.175, 2.175, 2.175, 2.61, 2.61, 2.61])
+BASE_VMAX, BASE_AMAX = 6.0, 20.0 # the base moves like a fast badminton player (single and duel; 2026-10-03)
+VEL_LIMIT = np.r_[BASE_VMAX, BASE_VMAX, ARM_VEL]
+KP = np.array([4e4, 4e4, 2400.0, 2400.0, 2400.0, 2400.0, 1000.0, 600.0, 200.0])
+KD = np.array([3e3, 3e3, 100.0, 100.0, 100.0, 100.0, 30.0, 20.0, 6.0])
+JOINTS = ["base_x", "base_y"] + [f"joint{i}" for i in range(1, 8)]
+HOME = np.array([0.0, -4.0]) # the robot's base between shots
+PED_H = 1.0 # link0 height on the pedestal; shoulder at PED_H + 0.333
+Q0_ARM = np.array([0.0, -0.3, 0.0, -1.9, 0.0, 1.9, 0.785]) # ready pose (refined at import by IK, see _ready_pose)
+BASE_LO, BASE_HI = np.array([-3.25, -7.5]), np.array([3.25, -0.5])
+
+WIN_POINTS = 5 # first to 5; from 4-4 a two-point lead is needed; the first to CAP_POINTS wins
+CAP_POINTS = 7
+MAX_HITS = 300 # cap on hits in the match (both sides): the match ends after that point; the leader wins,
+MAX_POINTS = 40 # if level the winner of the last point (no draws; the same in single and duel)
+READY_STEPS = 100 # 1.0 s between points
+LEG_STEPS = 600 # safety: 6 s after a serve or hit without a decision -> the player to hit loses
+CAM_EVERY = 2 # 50 Hz camera snapshots
+SWING_AFTER = 20 # first decision point: 0.2 s after the shuttle was played (serve or opponent's hit)
+ADJUST_BEFORE = 30 # second decision point: 0.3 s before the planned contact
+OPP_HOME = np.array([0.0, 3.8])
+OPP_Z = (0.10, 2.70) # the opponent's hitting envelope (height)
+SPEED_FREE = 12.0
+PRESSURE_WEAK, PRESSURE_PASSIVE = 0.75, 0.35
+EXEC_SIGMA = {"soft": 0.12, "normal": 0.20, "hard": 0.30}
+POWER = ("soft", "normal", "hard")
+AIM_DEFAULT = (0.0, 4.0)
+
+LEVELS = { # defence: reaction, chase / recovery speed, reach, too-fast threshold; attack: width, pace (smash speed);
+ # serve: share of high serves, |x| range of the serve's target, depth range of a short serve (receiver frame)
+ 1: dict(reaction_s=0.30, chase=2.2, recover=1.6, reach=0.95, max_speed=24.0, width=1.4, pace=24.0, seed=101,
+ serve_high=0.7, serve_x=(0.4, 1.6), serve_short_y=(-2.5, -2.8)),
+ 2: dict(reaction_s=0.25, chase=2.6, recover=1.9, reach=1.05, max_speed=28.0, width=1.9, pace=30.0, seed=202,
+ serve_high=0.5, serve_x=(0.25, 2.2), serve_short_y=(-2.2, -2.5)),
+}
+
+# The players' serve (BWF Laws 9-10; 2026-10-07). Before every serve both robots are put in their service courts at
+# their spot (serve_spot: x = +SPOT_X in the right court, -SPOT_X in the left one; own frame), at rest in the ready
+# pose; the spot is the robot's home (the ready target's base goal) for the whole point. READY_STEPS after play
+# resumes the receiver is ready (Law 9.4) and the server may toss the shuttle (docs/conventions/racket_serve_zh.md):
+# it appears at a point the server chooses, within TOSS_REACH (horizontally) of its base and TOSS_Z high, and is
+# released from rest (height 0) or projected straight up to rise at most TOSS_H_MAX (the robot has no free hand: the
+# toss stands for the server's hand letting go of the shuttle, Law 9.1.5: no spin), within SERVE_WINDOW_STEPS (else a
+# fault: undue delay, Law 9.1.1). Then the server must hit it (a miss is a fault, Law 9.1.8) below SERVE_MAX_Z (Law 9.1.6) and upwards (Law
+# 9.1), over the net into the receiver's diagonal service court (Laws 9.1, 10.1). Both bases stay within BASE_TOL of
+# their spots until the serve is delivered (Law 9.1.4; both moving: a let, Law 14.2.2). The rally winner serves next
+# (Law 10.3).
+SPOT_X, SPOT_Y = 0.3, -4.0
+TOSS_REACH, TOSS_Z, TOSS_H_MAX = 1.0, (0.5, 1.8), 0.5
+SERVE_MAX_Z = 1.15
+SERVE_WINDOW_STEPS = 300 # 3 s after the receiver is ready
+BASE_TOL = 0.05
+MAX_DELAY_FAULTS = 3 # the third undue-delay fault of a player disqualifies it (Laws 16.6.1, 16.7)
+
+
+def serve_spot(right: bool) -> np.ndarray:
+ """Where both robots stand before a serve (own frame): in their right service courts when the server's score is
+ even (BWF 10.1), else in their left ones."""
+ return np.array([SPOT_X if right else -SPOT_X, SPOT_Y])
+
+
+def toss_problem(p, h, base) -> str | None:
+ """Why a toss (point p in the own frame, height h) is not allowed for a robot whose base is at `base`, or None."""
+ p = np.asarray(p, float)
+ if p.shape != (3,) or not np.all(np.isfinite(p)):
+ return "the toss point must be 3 finite numbers"
+ if not (isinstance(h, (int, float)) and math.isfinite(h) and 0.0 <= h <= TOSS_H_MAX):
+ return f"the toss height must be 0-{TOSS_H_MAX} m (0: released from rest)"
+ if not TOSS_Z[0] <= p[2] <= TOSS_Z[1]:
+ return f"the toss point must be {TOSS_Z[0]}-{TOSS_Z[1]} m high"
+ d = float(np.hypot(p[0] - base[0], p[1] - base[1]))
+ if d > TOSS_REACH:
+ return f"the toss point must be within {TOSS_REACH} m (horizontally) of your base; it is {d:.2f} m away"
+ if p[1] > -0.5:
+ return "the toss point must be on your half, y <= -0.5"
+ return None
+
+
+def toss_vz(h) -> float:
+ """The upward speed that makes a shuttle rise h metres under gravity and quadratic drag (exact for the continuous
+ model: h = V_TERM^2 / (2 g) ln(1 + vz^2 / V_TERM^2))."""
+ return float(V_TERM * math.sqrt(math.expm1(2.0 * GRAV * float(h) / V_TERM ** 2)))
+
+# launch-angle families (deg) of the opponent's shots, tried in order; max launch speed (m/s)
+SHOT_THETAS = {"clear": (50, 45, 55, 40, 60, 35), "lift": (58, 52, 64, 46), "drop": (5, 0, 10, 15, -5, 20, 25, 30),
+ "drive": (6, 2, 10, 14, -2, 18), "smash": (-14, -10, -18, -6, -22, -2), "push": (28, 32, 24, 36, 20),
+ "serve_high": (55, 50, 60, 45), "serve_short": (22, 26, 18, 30, 34)}
+SHOT_VMAX = {"clear": 60.0, "lift": 50.0, "drop": 25.0, "drive": 34.0, "smash": 45.0, "push": 34.0,
+ "serve_high": 55.0, "serve_short": 14.0}
+OUR_THETAS = (-30, -22, -15, -9, -4, 0, 4, 8, 13, 19, 26, 34, 43, 52, 61)
+OUR_VMAX = 55.0
+
+
+# ---------------------------------------------------------------------- shuttle physics
+def sh_step(p, v):
+ """One 1 ms step of the shuttle (python floats)."""
+ vx, vy, vz = v
+ c = K_DRAG * math.sqrt(vx * vx + vy * vy + vz * vz) * PHYS_DT
+ vx -= c * vx
+ vy -= c * vy
+ vz -= GRAV * PHYS_DT + c * vz
+ return (p[0] + vx * PHYS_DT, p[1] + vy * PHYS_DT, p[2] + vz * PHYS_DT), (vx, vy, vz)
+
+
+def predict(p, v, n_max=6000):
+ """Shuttle-only flight from (p, v): arrays P, V (N, 3) after 1..N steps of 1 ms, until the floor (inclusive) or
+ the net (the step at which it crossed y = 0 below the net top, inclusive)."""
+ p = tuple(float(x) for x in p); v = tuple(float(x) for x in v)
+ P, V = [], []
+ for _ in range(n_max):
+ p1, v1 = sh_step(p, v)
+ if (p[1] > 0) != (p1[1] > 0) and p[1] != p1[1]:
+ f = p[1] / (p[1] - p1[1])
+ z = p[2] + f * (p1[2] - p[2]); x = p[0] + f * (p1[0] - p[0])
+ if z < NET_TOP and abs(x) <= POST_X:
+ P.append(p1); V.append(v1)
+ break
+ P.append(p1); V.append(v1)
+ p, v = p1, v1
+ if p[2] <= 0.0:
+ break
+ return np.array(P), np.array(V)
+
+
+def flight_table(p0, heading, thetas_deg, speeds, dt=0.002, t_max=4.0):
+ """Vectorised planar flights from p0 along `heading` (unit xy) for every (theta, speed): horizontal range at the
+ floor, height when crossing the net plane y = 0 (nan if it never does), flight time. Solver only (2 ms steps);
+ the real flight is the 1 ms 3-D integration."""
+ th = np.deg2rad(np.asarray(thetas_deg, float))[:, None]
+ sp = np.asarray(speeds, float)[None, :]
+ vh = (np.cos(th) * sp).ravel(); vz = (np.sin(th) * sp).ravel()
+ n = vh.size
+ h = np.zeros(n); z = np.full(n, float(p0[2]))
+ s_net = (-p0[1] / heading[1]) if abs(heading[1]) > 1e-9 else np.inf
+ rng_ = np.full(n, np.nan); znet = np.full(n, np.nan); tf = np.full(n, np.nan)
+ alive = np.ones(n, bool)
+ for i in range(int(t_max / dt)):
+ s = np.sqrt(vh * vh + vz * vz)
+ c = K_DRAG * s * dt
+ vh = vh - c * vh; vz = vz - GRAV * dt - c * vz
+ h1 = h + vh * dt; z1 = z + vz * dt
+ cross = alive & (h < s_net) & (h1 >= s_net)
+ if cross.any():
+ f = (s_net - h[cross]) / (h1[cross] - h[cross])
+ znet[cross] = z[cross] + f * (z1[cross] - z[cross])
+ land = alive & (z1 <= 0.0)
+ if land.any():
+ f = z[land] / (z[land] - z1[land])
+ rng_[land] = h[land] + f * (h1[land] - h[land]); tf[land] = (i + f) * dt
+ alive &= ~land
+ h, z = h1, z1
+ if not alive.any():
+ break
+ shp = (len(thetas_deg), len(speeds))
+ return rng_.reshape(shp), znet.reshape(shp), tf.reshape(shp)
+
+
+def solve_shots(p0, target, thetas, vmax, net_margin=0.15, vmin=2.0):
+ """Launch velocities from p0 that land at `target` (xy) and clear the net top by >= net_margin: one per launch
+ angle that works (in the order given). Returns [(theta, speed, v (3,), flight time)]."""
+ p0 = np.asarray(p0, float); target = np.asarray(target, float)
+ d = target - p0[:2]; H = float(np.linalg.norm(d))
+ if H < 1e-6:
+ return []
+ hd = d / H
+ speeds = np.linspace(vmin, vmax, 90)
+ R, ZN, TF = flight_table(p0, hd, thetas, speeds)
+ out = []
+ for i, th in enumerate(thetas):
+ r = R[i]; ok = np.isfinite(r)
+ if not ok.any():
+ continue
+ r_ok = r[ok]; s_ok = speeds[ok]
+ j = np.nonzero(r_ok >= H)[0]
+ if len(j) == 0:
+ continue
+ j = j[0]
+ if j == 0:
+ v = s_ok[0]; f = 0.0; j0 = 0
+ else:
+ f = (H - r_ok[j - 1]) / (r_ok[j] - r_ok[j - 1]); v = s_ok[j - 1] + f * (s_ok[j] - s_ok[j - 1]); j0 = j - 1
+ zn = ZN[i][ok]; tf = TF[i][ok]
+ crosses = (p0[1] > 0) != (target[1] > 0)
+ if crosses:
+ z_net = zn[j0] + f * (zn[min(j, len(zn) - 1)] - zn[j0]) if j > 0 else zn[0]
+ if not np.isfinite(z_net) or z_net < NET_TOP + net_margin:
+ continue
+ t_f = tf[j0] + f * (tf[min(j, len(tf) - 1)] - tf[j0]) if j > 0 else tf[0]
+ thr = math.radians(th)
+ vel = np.array([hd[0] * v * math.cos(thr), hd[1] * v * math.cos(thr), v * math.sin(thr)])
+ out.append((th, float(v), vel, float(t_f)))
+ return out
+
+
+def in_service_court(x, y, right):
+ """The receiver's service court in the receiver's frame (receiver on y < 0, facing +y; singles: between the short
+ service line and the back line; its right court is x >= 0). BWF Laws 9.1 / 10.1: the serve must land in the court
+ diagonally opposite, the receiver's right court when the server's score is even (lines are in)."""
+ return (0.0 <= x <= COURT_X if right else -COURT_X <= x <= 0.0) and -COURT_Y <= y <= -SHORT_SERVICE_Y
+
+
+def serve_plan(seed, n, server_score, base, reachable, lv=None):
+ """The scripted opponent's serve (type, hitting point p0, velocity) in the RECEIVER's frame, from the server's
+ service court into the receiver's diagonal service court (BWF 10.1.1: from the right court when the server's score
+ is even), hit at 1.05 m (below 1.15 m, Law 9.1.6) and upwards (Law 9.1). The server faces -y, so its right court is
+ x < 0. seed: the rng seed list prefix; n: the point's serial number (lets included, for the seeded choice);
+ reachable(p0, v, base): the receiver can meet the flight; lv: the level (share of high serves, target range)."""
+ lv = lv or LEVELS[1]
+ rng = np.random.default_rng(list(seed) + [11, n])
+ u = rng.uniform(-1, 1, 4)
+ right = server_score % 2 == 0
+ sx = -0.45 if right else 0.45 # the server's right court is at x < 0 in the receiver's frame
+ p0 = np.array([sx, 2.3, 1.05])
+ high = (u[0] + 1.0) / 2.0 < lv["serve_high"]
+ typ = "serve_high" if high else "serve_short"
+ side = 1.0 if right else -1.0 # the receiver's diagonal court: x > 0 when the server serves from its right
+ x0, x1 = lv["serve_x"]
+ tx = side * (x0 + (x1 - x0) * (u[1] + 1.0) / 2.0)
+ y0, y1 = lv["serve_short_y"]
+ ty = -5.9 - 0.4 * abs(u[2]) if high else y0 + (y1 - y0) * abs(u[2])
+ v = None
+ for frac in (1.0, 0.6, 0.3):
+ c = solve_shots(p0, (side * max(0.25, abs(tx) * frac), ty), SHOT_THETAS[typ], SHOT_VMAX[typ])
+ c = [x for x in c if reachable(p0, x[2], base)]
+ if c:
+ v = c[0][2]; break
+ if v is None:
+ v = solve_shots(p0, (side * 0.6, -5.5), SHOT_THETAS["serve_high"], 60.0)[0][2]
+ return typ, p0, np.asarray(v, float), right
+
+
+def in_court(x, y, side):
+ """side +1: the opponent's court, -1: ours (lines are in)."""
+ return abs(x) <= COURT_X and (0.0 < side * y <= COURT_Y)
+
+
+def base_goto(b, v, goal):
+ """One control step of the base's go-to generator (bounded speed and acceleration): new (target, velocity)."""
+ e = goal - b; dist = float(np.hypot(e[0], e[1]))
+ sp = float(np.hypot(v[0], v[1]))
+ if dist < 0.004 and sp < 0.15:
+ return goal.copy(), np.zeros(2)
+ vdes = e / max(dist, 1e-9) * min(BASE_VMAX * 0.98, math.sqrt(2 * BASE_AMAX * 0.85 * dist))
+ dv = vdes - v; ndv = float(np.hypot(dv[0], dv[1])); lim = BASE_AMAX * CONTROL_DT
+ if ndv > lim:
+ dv = dv * (lim / ndv)
+ v = v + dv
+ nv = float(np.hypot(v[0], v[1]))
+ if nv > BASE_VMAX * 0.98:
+ v = v * (BASE_VMAX * 0.98 / nv)
+ return np.clip(b + v * CONTROL_DT, BASE_LO, BASE_HI), v
+
+
+def base_time(dist):
+ """Approximate time for the base to travel `dist` from rest to rest."""
+ a, vm = BASE_AMAX * 0.85, BASE_VMAX * 0.98
+ return 2 * math.sqrt(dist / a) if dist < vm * vm / a else dist / vm + vm / a
+
+
+SHOULDER_Z = PED_H + 0.333
+
+
+def stance(p):
+ """Where the base should stand to meet the shuttle at p with a forehand: the contact to the right of and in front
+ of the base, closer in for high and low contacts."""
+ dz = float(p[2]) - SHOULDER_Z
+ r = max(0.30, 0.95 - 0.35 * abs(dz))
+ off = np.array([0.62 * r, 0.62 * r])
+ return np.clip(np.asarray(p[:2], float) - off, BASE_LO, BASE_HI)
+
+
+def quat_z_to(v):
+ """Quaternion rotating the local z axis onto the direction v."""
+ v = np.asarray(v, float); n = np.linalg.norm(v)
+ if n < 1e-9:
+ return np.array([1.0, 0, 0, 0])
+ v = v / n; z = np.array([0.0, 0, 1])
+ c = float(z @ v)
+ if c < -0.999999:
+ return np.array([0.0, 1, 0, 0])
+ ax = np.cross(z, v); s = math.sqrt((1 + c) * 2)
+ return np.array([s / 2, ax[0] / s, ax[1] / s, ax[2] / s])
+
+
+def hermite(q0, v0, q1, v1, T, n):
+ t = np.arange(1, n + 1) * (T / n)
+ s = t / T
+ h00 = 2 * s**3 - 3 * s**2 + 1; h10 = s**3 - 2 * s**2 + s; h01 = -2 * s**3 + 3 * s**2; h11 = s**3 - s**2
+ return h00[:, None] * q0 + h10[:, None] * T * v0 + h01[:, None] * q1 + h11[:, None] * T * v1
+
+
+# ---------------------------------------------------------------------- robot + shuttle physics
+class Phys:
+ """MuJoCo robot (mobile base + Franka + racket), the shuttle integrator and the racket-shuttle contact model."""
+
+ def __init__(self):
+ self.m = mj.MjModel.from_xml_path(str(SCENE))
+ self.d = mj.MjData(self.m)
+ m = self.m
+ jid = [mj.mj_name2id(m, mj.mjtObj.mjOBJ_JOINT, j) for j in JOINTS]
+ self.qa = np.array([m.jnt_qposadr[j] for j in jid]); self.va = np.array([m.jnt_dofadr[j] for j in jid])
+ self.lo = m.jnt_range[jid, 0].copy(); self.hi = m.jnt_range[jid, 1].copy()
+ self.site = mj.mj_name2id(m, mj.mjtObj.mjOBJ_SITE, "racket_center")
+ self.kin = mj.MjData(m)
+ self.steps_total = 0
+
+ def reset(self, q9):
+ m, d = self.m, self.d
+ mj.mj_resetData(m, d)
+ d.qpos[self.qa] = q9
+ mj.mj_forward(m, d)
+ self.target = np.asarray(q9, float).copy()
+ self.k = 0
+ self._actions: list[np.ndarray] = []
+ self.sh_p, self.sh_v, self.sh_live = (0.0, 3.0, 1.0), (0.0, 0.0, 0.0), False
+ self.hit_enabled = False
+ self.events: list[dict] = []
+ self._prev = None
+
+ def copy_from(self, o: "Phys"):
+ d = self.d
+ mj.mj_resetData(self.m, d)
+ d.qpos[:] = o.d.qpos; d.qvel[:] = o.d.qvel; d.qacc_warmstart[:] = o.d.qacc_warmstart; d.time = o.d.time
+ d.ctrl[:] = o.d.ctrl
+ mj.mj_forward(self.m, d)
+ self.target = o.target.copy(); self.k = o.k; self._actions = []
+ self.sh_p, self.sh_v, self.sh_live, self.hit_enabled = o.sh_p, o.sh_v, o.sh_live, o.hit_enabled
+ self.events = []
+ self._prev = None if o._prev is None else (o._prev[0].copy(), o._prev[1].copy(), o._prev[2])
+
+ def check_target(self, q):
+ if q.shape != (9,) or not np.all(np.isfinite(q)):
+ raise ValueError(f"action must be 9 finite joint targets, got {q.shape}")
+ if (q < self.lo - 1e-9).any() or (q > self.hi + 1e-9).any():
+ raise ValueError(f"step {self.k}: joint target outside range: {q}")
+ dq = np.abs(q - self.target)
+ lim = VEL_LIMIT * CONTROL_DT * (1 + 1e-6) + 1e-12
+ if (dq > lim).any():
+ j = int(np.argmax(dq / lim))
+ raise ValueError(f"step {self.k}: joint {JOINTS[j]} target moved {dq[j]:.5f} in one control step "
+ f"(limit {VEL_LIMIT[j] * CONTROL_DT:.5f})")
+
+ def step(self, q):
+ q = np.asarray(q, dtype=np.float64).reshape(-1)
+ self.check_target(q)
+ m, d = self.m, self.d
+ q_prev = self.target
+ qd_des = (q - q_prev) / CONTROL_DT
+ lo, hi = m.actuator_ctrlrange[:, 0], m.actuator_ctrlrange[:, 1]
+ for j in range(1, SUBSTEPS + 1):
+ q_des = q_prev + (q - q_prev) * (j / SUBSTEPS)
+ tau = KP * (q_des - d.qpos[self.qa]) + KD * (qd_des - d.qvel[self.va]) + d.qfrc_bias[self.va]
+ d.ctrl[:] = np.clip(tau, lo, hi)
+ mj.mj_step(m, d)
+ # site pose now = the pose at the start of this step (time t_n), the same time as self.sh_p
+ c = d.site_xpos[self.site].copy(); n = d.site_xmat[self.site].reshape(3, 3)[:, 0].copy()
+ if self.sh_live:
+ if self.hit_enabled and self._prev is not None and self.sh_p[1] < 0: # only on our half (BWF 13.4.2)
+ self._check_hit(c, n)
+ self._prev = (c, n, self.sh_p)
+ self._advance_shuttle()
+ else:
+ self._prev = (c, n, self.sh_p)
+ self.target = q.copy()
+ self._actions.append(q.copy())
+ self.k += 1
+ self.steps_total += SUBSTEPS
+
+ def actions(self) -> np.ndarray:
+ """(N, 9) joint targets applied since the reset."""
+ return np.array(self._actions, dtype=np.float64).reshape(-1, 9)
+
+ def _advance_shuttle(self):
+ p, v = self.sh_p, self.sh_v
+ p1, v1 = sh_step(p, v)
+ if (p[1] > 0) != (p1[1] > 0) and p[1] != p1[1]:
+ f = p[1] / (p[1] - p1[1])
+ z = p[2] + f * (p1[2] - p[2]); x = p[0] + f * (p1[0] - p[0])
+ self.events.append({"kind": "cross", "k": self.k, "x": round(x, 4), "z": round(z, 4),
+ "to": "opp" if p1[1] > 0 else "own"})
+ if z < NET_TOP and abs(x) <= POST_X:
+ self.sh_p = (x, 0.0, z); self.sh_v = (0.0, 0.0, 0.0); self.sh_live = False
+ self.events.append({"kind": "net", "k": self.k, "x": round(x, 4), "z": round(z, 4)})
+ return
+ if p1[2] <= 0.0:
+ f = p[2] / (p[2] - p1[2]) if p[2] != p1[2] else 1.0
+ x = p[0] + f * (p1[0] - p[0]); y = p[1] + f * (p1[1] - p[1])
+ self.sh_p = (x, y, 0.0); self.sh_v = (0.0, 0.0, 0.0); self.sh_live = False
+ self.events.append({"kind": "land", "k": self.k, "x": round(x, 4), "y": round(y, 4)})
+ return
+ self.sh_p, self.sh_v = p1, v1
+
+ def _check_hit(self, c, n):
+ cp, npv, sp = self._prev
+ sp = np.array(sp); sh = np.array(self.sh_p)
+ s0 = float((sp - cp) @ npv); s1 = float((sh - c) @ n)
+ if s0 * s1 > 0 or (s0 == 0 and s1 == 0):
+ return
+ f = s0 / (s0 - s1) if s0 != s1 else 0.0
+ pc = cp + f * (c - cp); ps = sp + f * (sh - sp)
+ r = ps - pc
+ off = float(np.linalg.norm(r - (r @ n) * n))
+ if off > R_HEAD:
+ return
+ vr = (c - cp) / PHYS_DT; vs = np.array(self.sh_v)
+ n_out = n if float((vr - vs) @ n) >= 0 else -n
+ u = float(vr @ n_out); vin = float(vs @ n_out)
+ spd = RACKET_GAIN * max(u, 0.0) * (1 - OFFCENTRE_LOSS * (off / R_HEAD) ** 2) + E_SHUTTLE * max(0.0, -vin)
+ v_out = n_out * spd
+ p_new = ps + n_out * 0.002
+ self.sh_p = tuple(float(x) for x in p_new); self.sh_v = tuple(float(x) for x in v_out)
+ self.hit_enabled = False
+ self.events.append({"kind": "hit", "k": self.k, "pos": [round(float(x), 4) for x in ps],
+ "offcentre": round(off, 4), "racket_speed": round(u, 3), "speed": round(spd, 3),
+ "v_out": [round(float(x), 3) for x in v_out]})
+
+ # kinematics (scratch data; never stepped)
+ def kin_set(self, q9):
+ self.kin.qpos[:] = self.d.qpos
+ self.kin.qpos[self.qa] = q9
+ mj.mj_kinematics(self.m, self.kin)
+ mj.mj_comPos(self.m, self.kin)
+
+ def fk(self, q9):
+ self.kin_set(np.asarray(q9, float))
+ return self.kin.site_xpos[self.site].copy(), self.kin.site_xmat[self.site].reshape(3, 3).copy()
+
+ def jac(self, q9):
+ """(6, 7) racket-centre Jacobian w.r.t. the arm joints."""
+ self.kin_set(np.asarray(q9, float))
+ jp = np.zeros((3, self.m.nv)); jr = np.zeros((3, self.m.nv))
+ mj.mj_jacSite(self.m, self.kin, jp, jr, self.site)
+ return np.vstack([jp[:, self.va[2:]], jr[:, self.va[2:]]])
+
+ def racket_state(self):
+ d = self.d
+ jp = np.zeros((3, self.m.nv)); jr = np.zeros((3, self.m.nv))
+ mj.mj_jacSite(self.m, d, jp, jr, self.site)
+ return (d.site_xpos[self.site].copy(), d.site_xmat[self.site].reshape(3, 3)[:, 0].copy(), jp @ d.qvel)
+
+ def state_sha(self):
+ d = self.d
+ h = hashlib.sha256()
+ for a in (d.qpos, d.qvel, d.qacc_warmstart, d.ctrl, np.array([d.time]), np.array(self.sh_p + self.sh_v)):
+ h.update(np.ascontiguousarray(a, dtype=np.float64).tobytes())
+ h.update(json.dumps(self.events, sort_keys=True).encode())
+ return h.hexdigest()
+
+
+def ik(ph: Phys, pos, normal, base_xy, q_init, iters=150, tol=1e-4):
+ """Damped least squares over the 7 arm joints (base fixed at base_xy): racket centre at pos, face normal along
+ `normal` (rotation about the normal free)."""
+ q = np.r_[base_xy, q_init].astype(float)
+ n_t = np.asarray(normal, float); n_t = n_t / np.linalg.norm(n_t)
+ lo, hi = ph.lo[2:] + 1e-4, ph.hi[2:] - 1e-4
+ err = np.inf
+ for _ in range(iters):
+ p, R = ph.fk(q)
+ n = R[:, 0]
+ e = np.r_[pos - p, np.cross(n, n_t)]
+ err = float(np.linalg.norm(e[:3]) + np.arcsin(min(1.0, np.linalg.norm(e[3:]))))
+ if n @ n_t < 0:
+ e[3:] = np.cross(n, n_t) + 0.5 * np.cross(n, R[:, 1]); err += np.pi / 2
+ if err < tol:
+ break
+ J = ph.jac(q)
+ dq = J.T @ np.linalg.solve(J @ J.T + 1e-3 * np.eye(6), e)
+ nd = float(np.max(np.abs(dq)))
+ if nd > 0.25:
+ dq *= 0.25 / nd
+ q[2:] = np.clip(q[2:] + dq, lo, hi)
+ return q[2:].copy(), err
+
+
+# fixed extra IK start poses (offsets from the ready pose Q0_ARM): arm lowered / raised, turned left / right, wrist
+# turned. Deterministic: the same list every run, so the plan is a pure function of the state (replay is bit-exact).
+IK_SEED_OFFSETS = np.array([
+ [0.0, 0.5, 0.0, 0.6, 0.0, -0.4, 0.0],
+ [0.0, -0.4, 0.0, -0.3, 0.0, 0.4, 0.0],
+ [0.6, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [-0.6, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.3, 0.0, 0.3, 1.2, 0.0, 0.0],
+ [0.0, 0.3, 0.0, 0.3, -1.2, 0.0, 0.0],
+])
+IK_OK = 2e-3 # an IK solution with a residual below this counts as reaching the pose
+
+
+def ik_multi(ph: Phys, pos, normal, base_xy, seeds, q_now):
+ """Deterministic multi-start IK for both string faces: starts from `seeds` (the caller's seed, the current joint
+ targets, the ready pose) and the fixed IK_SEED_OFFSETS poses. Of the solutions that reach the pose
+ (residual < IK_OK) it takes the one nearest to the current joint state in joint-speed terms (the least time at the
+ joint speed limits, max_j |q_j - q_now_j| / ARM_VEL_j), so the swing does not wander into a far, flipped
+ configuration; if none reaches it, the lowest residual. Returns (q, residual, face sign, fallbacks): up
+ to 2 more distinct solutions, next-nearest first, for when the nearest one cannot be swung to in time."""
+ n_t = np.asarray(normal, float); n_t = n_t / np.linalg.norm(n_t)
+ q_now = np.asarray(q_now, float)
+ lo, hi = ph.lo[2:] + 1e-3, ph.hi[2:] - 1e-3
+ starts = []
+ for s in list(seeds) + [Q0_ARM + d for d in IK_SEED_OFFSETS]:
+ s = np.clip(np.asarray(s, float), lo, hi)
+ if not any(np.array_equal(s, t) for t in starts):
+ starts.append(s)
+ cands = []
+ for i, sd in enumerate(starts):
+ for sgn in (1.0, -1.0): # the string bed has two faces (the commanded one first)
+ q, r = ik(ph, pos, sgn * n_t, base_xy, sd)
+ cands.append((float(np.max(np.abs(q - q_now) / ARM_VEL)), r, i, sgn, q))
+ good = sorted((c for c in cands if c[1] < IK_OK), key=lambda c: (round(c[0], 9), c[2], -c[3]))
+ if not good:
+ c = min(cands, key=lambda c: (c[1], c[2]))
+ return c[4], c[1], c[3], []
+ alts = [] # the next-nearest distinct solutions (fallbacks), at most 2
+ for c in good[1:]:
+ if len(alts) < 2 and all(np.max(np.abs(c[4] - o[4])) > 0.2 for o in [good[0]] + alts):
+ alts.append(c)
+ return good[0][4], good[0][1], good[0][3], [(c[4], c[1], c[3]) for c in alts]
+
+
+def swing_score(perr, nerr_deg, verr):
+ """How far a rehearsed swing is from the commanded racket state (m-equivalent: 1 cm ~ 1.7 deg ~ 0.5 m/s)."""
+ return float(perr) + 0.006 * float(nerr_deg) + 0.02 * float(verr)
+
+
+DELIVERY_POS_WARN, DELIVERY_ANG_WARN = 0.03, 5.0 # stroke note when the rehearsed delivery is off by more
+
+
+# ---------------------------------------------------------------------- the match
+class Match:
+ """The match. Live: run_to_decision() / shot() / adjust(). Replay: replay(actions)."""
+
+ # decision cameras: (lookat, distance, azimuth, elevation) of MuJoCo free cameras
+ CAMS = (([0.0, -1.0, 2.8], 13.5, 90.0, -6.0), # behind and above the robot's baseline, looking down the court
+ ([0.0, -1.5, 3.0], 14.0, 0.0, -4.0)) # at the side of the court (x < 0), looking along +x
+ VIEW_BACK = (0, 3, 6, 9) # snapshots back from the latest: 0, 60, 120, 180 ms
+ TILE = (480, 360)
+
+ def __init__(self, level: int = 1, lv_override: dict | None = None):
+ self.level = int(level)
+ self.lv = dict(LEVELS.get(self.level, LEVELS[1]))
+ if lv_override:
+ self.lv.update(lv_override)
+ if os.environ.get("MATCH_SEED"): # other instances of the same level: serves + opponent + scatter
+ self.lv["seed"] = int(os.environ["MATCH_SEED"])
+ self.s = Phys()
+ self.s.reset(np.r_[HOME, Q0_ARM])
+ self._twin = None
+ self.score = [0, 0]
+ self.points: list[dict] = []
+ self.legs: list[dict] = []
+ self.results: list[dict] = []
+ self.shots: list[dict] = []
+ self.hist: deque = deque(maxlen=16)
+ self.done = False
+ self.winner = None # 0 you, 1 the opponent (set when the match ends)
+ self.hits = 0 # hits in the match, both sides (the MAX_HITS cap)
+ self.phase = "swing"
+ self.plan, self.plan_j, self._rec = [], 0, {}
+ self._adj_k = None
+ self.n_our_legs = 0
+ self.delay_faults = 0 # your serves not tossed in time (undue delay)
+ self.disqualified = False # MAX_DELAY_FAULTS reached: you lose the match (Law 16.7)
+ self._start_point(hold_from=0)
+
+ @property
+ def k(self) -> int:
+ return self.s.k
+
+ # ------------------------------------------------------------------ points / legs
+ def next_server(self) -> int:
+ """0 (you) or 1 (the opponent): you serve the first point (Law 6: the toss is fixed in this format); then the
+ winner of the last rally serves (Law 10.3); after a let the same player serves again (Law 14.3)."""
+ if not self.points:
+ return 0
+ last = self.points[-1]
+ if last.get("let"):
+ return last["server"]
+ return 0 if last["winner"] == "you" else 1
+
+ def _start_point(self, hold_from: int):
+ self.hist.clear() # camera history (display only): no frames of the previous point in the next views
+ n = len(self.points)
+ server = self.point_server = self.next_server()
+ right = self.score[server] % 2 == 0 # the server's right court when its score is even (Law 10.1)
+ self.home = serve_spot(right) # both robots in their right (left) courts, diagonally (Law 9.1.3)
+ if server == 1:
+ # the opponent serves from its right court when its own score is even (BWF 10.1.1), diagonally to us
+ typ, p0, v, right = serve_plan([self.lv["seed"]], n, self.score[1], self.home, self._reachable, self.lv)
+ sx = float(p0[0])
+ self.leg = {"kind": "serve", "serve": typ, "point": n, "hold_from": hold_from, "server": 1,
+ "launch": hold_from + READY_STEPS, "state": "incoming", "p0": p0.tolist(),
+ "v0": [float(x) for x in v], "service_court_right": right}
+ # the server stands at its serving spot and walks home from the moment it serves
+ self.opp = {"xy0": np.array([sx, 2.7]), "k0": hold_from + READY_STEPS, "txy": OPP_HOME.copy(),
+ "speed": self.lv["recover"]}
+ else:
+ # you serve: READY_STEPS after play resumes the opponent is ready and you may toss the shuttle
+ ready = hold_from + READY_STEPS
+ self.leg = {"kind": "our_serve", "point": n, "hold_from": hold_from, "server": 0, "launch": ready,
+ "ready": ready, "deadline": ready + SERVE_WINDOW_STEPS, "state": "held",
+ "service_court_right": right}
+ # the opponent receives in its diagonal service court (its right court is x < 0 in your frame) and
+ # stands still until the serve is delivered
+ spot = np.array([-0.45 if right else 0.45, OPP_HOME[1]])
+ self.opp = {"xy0": spot, "k0": hold_from, "txy": spot.copy(), "speed": 0.0}
+ p0 = np.r_[self.home + np.array([-0.25, 0.35]), 1.0] # held in the server's (missing) free hand
+ v = np.zeros(3)
+ self.legs.append(self.leg)
+ self._new_leg()
+ self.s.sh_p = tuple(float(x) for x in p0); self.s.sh_v = tuple(float(x) for x in v); self.s.sh_live = False
+ self._go_home()
+
+ def _go_home(self):
+ """Before every serve: the robot at its spot in its service court (its home for the point) in the ready pose,
+ at rest, no command (as in the duel)."""
+ ph = self.s
+ q = np.r_[self.home, Q0_ARM]
+ ph.d.qpos[ph.qa] = q; ph.d.qvel[ph.va] = 0.0
+ mj.mj_forward(ph.m, ph.d)
+ ph.target = q.copy()
+ self.plan, self.plan_j = [], 0
+ self._last_act = None; self._q_hit_active = None
+ self._since_reset = 0
+
+ def toss(self, p, h=0.0):
+ """Your serve: the shuttle appears at p (your frame) now and rises h straight up (0: from rest). Raises
+ ValueError if not allowed."""
+ leg = self.leg
+ if self.done or leg["kind"] != "our_serve":
+ raise ValueError("it is not your serve")
+ if leg["state"] != "held":
+ raise ValueError("the shuttle was already tossed")
+ if self.k < leg["ready"]:
+ raise ValueError(f"the opponent is not ready before step {leg['ready']}")
+ why = toss_problem(p, h, self.s.d.qpos[self.s.qa[:2]])
+ if why:
+ raise ValueError(why)
+ self.s.sh_p = tuple(float(x) for x in p); self.s.sh_v = (0.0, 0.0, toss_vz(h))
+ self.s.sh_live = True; self.s.hit_enabled = True
+ leg["state"] = "falling"; leg["toss_k"] = self.k; leg["launch"] = self.k
+ leg["toss"] = [round(float(x), 4) for x in p]; leg["toss_height"] = float(h)
+
+ def delivered(self) -> bool:
+ """The serve of the current point was delivered (hit, missed or faulted)."""
+ leg = self.leg
+ if leg["kind"] == "our_serve":
+ return leg["state"] not in ("held", "falling")
+ if leg["kind"] == "serve":
+ return self.k >= leg["launch"]
+ return True
+
+ def _new_leg(self):
+ self.s.events.clear()
+ self.s.hit_enabled = False
+ self._opp_plan_k = None
+
+ def in_play(self) -> bool:
+ return self.k >= self.leg["launch"]
+
+ def t_since_launch(self) -> float:
+ return round((self.k - self.leg["launch"]) * CONTROL_DT, 6)
+
+ # ------------------------------------------------------------------ the opponent
+ def opp_xy(self, k=None) -> np.ndarray:
+ k = self.k if k is None else k
+ o = self.opp
+ dt = max(0.0, (k - o["k0"]) * CONTROL_DT)
+ e = o["txy"] - o["xy0"]; dist = float(np.hypot(e[0], e[1]))
+ if dist < 1e-9:
+ return o["xy0"].copy()
+ return o["xy0"] + e / dist * min(dist, o["speed"] * dt)
+
+ def _opp_plan(self):
+ """`reaction_s` after our hit: predict the flight, choose the interception point, start moving."""
+ leg = self.leg
+ P, V = predict(self.s.sh_p, self.s.sh_v)
+ o = self.opp_xy()
+ last = P[-1]
+ if leg["kind"] == "our_serve": # a serve must land in the opponent's diagonal service court
+ lands_in = bool(last[2] <= 1e-9 and in_service_court(-last[0], -last[1], leg["service_court_right"]))
+ else:
+ lands_in = bool(last[2] <= 1e-9 and in_court(last[0], last[1], +1))
+ leg["opp_x_react"] = [round(float(x), 3) for x in o]
+ if not lands_in:
+ leg["opp_leave"] = True
+ return
+ idx = np.arange(9, len(P), 10)
+ j = (idx + 1) // 10
+ Pc, sp = P[idx], np.linalg.norm(V[idx], axis=1)
+ ok = (Pc[:, 1] > 0.3) & (Pc[:, 2] >= OPP_Z[0]) & (Pc[:, 2] <= OPP_Z[1])
+ if not ok.any():
+ leg["opp_leave"] = True
+ leg["opp_miss"] = "the shuttle never came into the opponent's hitting range"
+ return
+ lv = self.lv
+ dist = np.hypot(Pc[:, 0] - o[0], Pc[:, 1] - o[1])
+ t = j * CONTROL_DT
+ pp = np.maximum(0.0, dist - lv["chase"] * t) / lv["reach"]
+ ps = (sp - SPEED_FREE) / (lv["max_speed"] - SPEED_FREE)
+ pr = np.where(ok, np.maximum(pp, ps), np.inf)
+ pmin = float(pr.min())
+ js = int(np.nonzero(pr <= pmin + 0.05)[0][0])
+ leg["opp_hit_k"] = self.k + int(j[js])
+ leg["opp_pressure"] = round(float(pr[js]), 3)
+ leg["opp_gap"] = round(float(max(0.0, dist[js] - lv["chase"] * t[js])), 3)
+ leg["opp_speed_in"] = round(float(sp[js]), 2)
+ self.opp = {"xy0": o, "k0": self.k, "txy": Pc[js, :2].copy(), "speed": lv["chase"]}
+
+ def _opp_hit(self):
+ leg = self.leg
+ p = np.array(self.s.sh_p)
+ pr = leg["opp_pressure"]
+ rec = {"k": self.k, "pos": [round(float(x), 3) for x in p], "opp_xy": [round(float(x), 3) for x in self.opp_xy()],
+ "pressure": pr, "gap": leg.get("opp_gap"), "speed_in": leg.get("opp_speed_in")}
+ leg["opp"] = rec
+ if pr > 1.0:
+ gap = leg.get("opp_gap", 0.0)
+ why = (f"out of reach: the opponent was {gap:.2f} m short of the shuttle (reach {self.lv['reach']:.2f} m)"
+ if gap > self.lv["reach"] else
+ f"too fast: the shuttle arrived at {leg.get('opp_speed_in'):.1f} m/s (it handles up to "
+ f"{self.lv['max_speed']:.0f} m/s)")
+ leg["opp_miss"] = why; rec["missed"] = why
+ return
+ mode = "weak" if pr > PRESSURE_WEAK else ("attack" if pr < PRESSURE_PASSIVE else "normal")
+ rec["mode"] = mode
+ shot, v, target = self._opp_return(p, mode)
+ rec.update(shot=shot, target=[round(float(x), 3) for x in target], speed=round(float(np.linalg.norm(v)), 2))
+ self._close_our_leg(True, f"good: the opponent played it ({mode} return, a {shot})")
+ self.hits += 1
+ self.s.sh_v = tuple(float(x) for x in v)
+ leg["state"] = "done"
+ self.opp = {"xy0": self.opp_xy(), "k0": self.k, "txy": OPP_HOME.copy(), "speed": self.lv["recover"]}
+ self.leg = {"kind": "return", "shot": shot, "point": len(self.points), "launch": self.k, "state": "incoming",
+ "opp_hit_pos": rec["pos"]}
+ self.legs.append(self.leg)
+ self._new_leg()
+ self.s.hit_enabled = True
+
+ def _opp_return(self, p, mode):
+ lv = self.lv
+ rng = np.random.default_rng([lv["seed"], len(self.points), len(self.legs)])
+ u = rng.uniform(-1, 1, 5)
+ side = 1.0 if u[0] >= 0 else -1.0
+ high = p[2] >= 1.9
+ W = lv["width"]
+ if mode == "weak":
+ plan = [("lift", 0.35 * u[0], -3.9 + 0.4 * u[1], 45.0)]
+ elif mode == "attack":
+ if high:
+ plan = [("smash", side * W, -3.3 + 0.5 * u[1], lv["pace"])]
+ elif u[1] > 0:
+ plan = [("drop", side * W, -1.2, 25.0)]
+ else:
+ plan = [("push", side * W, -6.0, 34.0)]
+ else:
+ x = side * W * abs(u[0]) ** 0.5
+ if high and u[3] > 0.5:
+ plan = [("smash", x, -3.6 + 0.4 * u[1], 0.8 * lv["pace"])]
+ elif u[2] < -0.1:
+ plan = [("clear", x, -5.9 + 0.3 * u[1], 60.0)]
+ elif u[2] < 0.5:
+ plan = [("drop", x, -1.7 + 0.3 * u[1], 25.0)]
+ else:
+ plan = [("drive", x, -4.6 + 0.4 * u[1], 30.0)]
+ base = self.s.d.qpos[self.s.qa[:2]].copy()
+ typ, tx, ty, vmax = plan[0]
+ for frac, t2 in ((1.0, typ), (0.6, typ), (0.3, typ), (0.6, "clear"), (0.0, "clear"), (0.0, "lift")):
+ vm = vmax if t2 == typ else SHOT_VMAX[t2]
+ tyy = ty if t2 == typ else (-5.6 if t2 == "clear" else -4.0)
+ for c in solve_shots(p, (tx * frac, tyy), SHOT_THETAS[t2], vm):
+ if self._reachable(p, c[2], base):
+ return t2, c[2], (tx * frac, tyy)
+ c = solve_shots(p, (0.0, -4.0), SHOT_THETAS["lift"] + (70, 40, 30), 60.0)
+ v = c[0][2] if c else np.array([0.0, -8.0, 12.0])
+ return "lift", v, (0.0, -4.0)
+
+ def _reachable(self, p0, v, base) -> bool:
+ """Our robot can meet this flight: a point 0.5-2.5 m high inside our court, >= 0.55 s after the shot, whose
+ stance the base can reach in time (0.45 s kept for the decision and the swing)."""
+ P, _ = predict(p0, v)
+ if len(P) == 0 or P[-1][2] > 1e-9 or not in_court(P[-1][0], P[-1][1], -1):
+ return False
+ idx = np.arange(549, len(P) - 20, 20)
+ for i in idx:
+ q = P[i]
+ if not (0.5 <= q[2] <= 2.5 and q[1] < -0.5):
+ continue
+ st = stance(q)
+ if base_time(float(np.hypot(*(st - base)))) <= (i + 1) * PHYS_DT - 0.45:
+ return True
+ return False
+
+ # ------------------------------------------------------------------ stepping (shared by live and replay)
+ def step(self, q):
+ self.s.step(q)
+ self._since_reset = getattr(self, "_since_reset", 0) + 1
+ leg = self.leg
+ if leg["kind"] == "serve" and leg["state"] == "incoming" and self.k == leg["launch"]:
+ self.s.sh_live = True; self.s.hit_enabled = True
+ self._referee()
+ if self.k % CAM_EVERY == 0:
+ self.hist.append({"k": self.k, "t": self.t_since_launch(), "qpos": self.s.d.qpos.copy(),
+ "sh": self.s.sh_p, "shv": self.s.sh_v, "opp": self.opp_xy().copy()})
+
+ def _referee(self):
+ if self.done:
+ return
+ leg, s = self.leg, self.s
+ kinds = [e["kind"] for e in s.events]
+ if not self.delivered():
+ moved = float(np.hypot(*(s.d.qpos[s.qa[:2]] - self.home)))
+ if moved > BASE_TOL: # Law 9.1.4: both players stand still until the serve
+ who = "serve_fault:moved" if leg["kind"] == "our_serve" else "receive_fault:moved"
+ self._close_our_leg(False, f"{who}: your base moved {moved:.2f} m from its spot before the serve was "
+ "delivered (Law 9.1.4)")
+ self._end_point(1, self.results[-1]["summary"])
+ return
+ if leg["kind"] == "our_serve" and leg["state"] in ("held", "falling"):
+ if leg["state"] == "held":
+ if self.k >= leg["deadline"]:
+ self.delay_faults += 1
+ dq = self.delay_faults >= MAX_DELAY_FAULTS
+ self.disqualified = dq
+ self._close_our_leg(False, f"serve_fault:undue_delay: you did not toss the shuttle within "
+ f"{SERVE_WINDOW_STEPS * CONTROL_DT:.0f} s (undue delay, Law 9.1.1)"
+ + (f"; your {MAX_DELAY_FAULTS}rd undue-delay fault disqualifies you (Law 16.7)"
+ if dq else ""))
+ self._end_point(1, self.results[-1]["summary"])
+ return
+ if "hit" in kinds:
+ e = next(e for e in s.events if e["kind"] == "hit")
+ leg["hit"] = e; self.hits += 1
+ if e["pos"][2] > SERVE_MAX_Z:
+ self._close_our_leg(False, f"serve_fault:too_high: you hit the shuttle {e['pos'][2]:.2f} m high, above "
+ f"{SERVE_MAX_Z} m (Law 9.1.6)")
+ self._end_point(1, self.results[-1]["summary"])
+ elif e["v_out"][2] <= 0.0:
+ self._close_our_leg(False, "serve_fault:not_upwards: the serve did not go upwards from your racket (Law 9.1)")
+ self._end_point(1, self.results[-1]["summary"])
+ else:
+ leg["state"] = "to_opp"; leg["delivered_k"] = self.k
+ self._opp_plan_k = self.k + int(round(self.lv["reaction_s"] / CONTROL_DT))
+ return
+ if "land" in kinds or self.k - leg["launch"] >= LEG_STEPS:
+ self._close_our_leg(False, "serve_fault:missed: you missed the shuttle (Law 9.1.8)")
+ self._end_point(1, self.results[-1]["summary"])
+ return
+ if leg["state"] == "incoming":
+ if "hit" in kinds:
+ e = next(e for e in s.events if e["kind"] == "hit")
+ leg["hit"] = e; leg["state"] = "to_opp"; self.hits += 1
+ self._opp_plan_k = self.k + int(round(self.lv["reaction_s"] / CONTROL_DT))
+ return
+ if "net" in kinds: # never seen: serves and returns are solved over the net
+ e = next(x for x in s.events if x["kind"] == "net")
+ what = "serve_fault:net: the opponent's serve" if leg["kind"] == "serve" else "the opponent's shot"
+ self._close_our_leg(True, f"{what} hit the net (x={e['x']:.2f}, height {e['z']:.2f} m)")
+ self._end_point(0, self.results[-1]["summary"])
+ return
+ if "land" in kinds:
+ e = next(x for x in s.events if x["kind"] == "land")
+ if leg["kind"] == "serve" and not in_service_court(e["x"], e["y"], leg["service_court_right"]):
+ self._close_our_leg(True, f"serve_fault:out: the opponent's serve landed outside your service court "
+ f"(x={e['x']:.2f}, y={e['y']:.2f})")
+ self._end_point(0, self.results[-1]["summary"])
+ elif in_court(e["x"], e["y"], -1):
+ self._close_our_leg(False, f"missed: the shuttle landed in your court at x={e['x']:.2f}, y={e['y']:.2f}")
+ self._end_point(1, self.results[-1]["summary"])
+ else:
+ self._close_our_leg(True, f"the opponent's shot landed out (x={e['x']:.2f}, y={e['y']:.2f})")
+ self._end_point(0, self.results[-1]["summary"])
+ elif self.in_play() and self.k - leg["launch"] >= LEG_STEPS:
+ self._close_our_leg(False, "missed"); self._end_point(1, "missed")
+ return
+ if leg["state"] == "to_opp":
+ serve = leg["kind"] == "our_serve"
+ if "net" in kinds:
+ e = next(x for x in s.events if x["kind"] == "net")
+ what = "serve_fault:net: your serve" if serve else "fault: your shot"
+ self._close_our_leg(False, f"{what} hit the net (x={e['x']:.2f}, height {e['z']:.2f} m)")
+ self._end_point(1, self.results[-1]["summary"])
+ return
+ if "land" in kinds:
+ e = next(x for x in s.events if x["kind"] == "land")
+ if e["y"] < 0:
+ self._close_our_leg(False, f"fault: your shot came down on your own side (x={e['x']:.2f}, y={e['y']:.2f})")
+ self._end_point(1, self.results[-1]["summary"])
+ elif serve and not in_service_court(-e["x"], -e["y"], leg["service_court_right"]):
+ self._close_our_leg(False, f"serve_fault:out: your serve landed outside the opponent's service court "
+ f"at x={e['x']:.2f}, y={e['y']:.2f} (the opponent let it go)")
+ self._end_point(1, self.results[-1]["summary"])
+ elif serve or in_court(e["x"], e["y"], +1):
+ why = leg.get("opp_miss") or "the opponent could not reach it"
+ self._close_our_leg(True, f"winner: landed in at x={e['x']:.2f}, y={e['y']:.2f} ({why})")
+ self._end_point(0, self.results[-1]["summary"])
+ else:
+ self._close_our_leg(False, f"fault: your shot landed out at x={e['x']:.2f}, y={e['y']:.2f} "
+ "(the opponent let it go)")
+ self._end_point(1, self.results[-1]["summary"])
+ return
+ if self._opp_plan_k is not None and self.k == self._opp_plan_k:
+ self._opp_plan()
+ if leg.get("opp_hit_k") == self.k and "opp_miss" not in leg:
+ self._opp_hit()
+ elif self.k - leg["launch"] >= 3 * LEG_STEPS:
+ self._close_our_leg(False, "?"); self._end_point(1, "timeout")
+
+ def _close_our_leg(self, ok, summary):
+ leg = self.leg
+ if leg.get("closed"):
+ return
+ leg["closed"] = True
+ h = leg.get("hit")
+ res = {"leg": self.n_our_legs, "point": len(self.points), "kind": leg["kind"], "returned": bool(ok),
+ "summary": summary, "hit": int(h is not None), "speed_out": None if h is None else h["speed"],
+ "offcentre": None if h is None else h["offcentre"], "step": self.k}
+ self.results.append(res)
+ self.n_our_legs += 1
+
+ def match_over(self) -> bool:
+ """First to WIN_POINTS; from 4-4 a two-point lead is needed; the first to CAP_POINTS wins."""
+ hi, lo = max(self.score), min(self.score)
+ return (hi >= WIN_POINTS and hi - lo >= 2) or hi >= CAP_POINTS
+
+ def _end_point(self, winner, how: str):
+ """winner 0 (you), 1 (the opponent) or None (a let: the point is replayed)."""
+ if winner is not None:
+ self.score[winner] += 1
+ self.points.append({"point": len(self.points), "winner": None if winner is None else
+ ("you" if winner == 0 else "opponent"), "how": how, "score": list(self.score),
+ "step": self.k, "let": winner is None, "server": self.point_server})
+ self.leg["state"] = "done"
+ if self.disqualified:
+ self.points[-1]["disqualified"] = "you"
+ self.winner = 1
+ self.done = True
+ return
+ if self.match_over():
+ self.winner = 0 if self.score[0] > self.score[1] else 1
+ self.done = True
+ return
+ if getattr(self, "hits", 0) >= MAX_HITS or len(self.points) >= MAX_POINTS:
+ # the cap: the leader wins; if level, the winner of the last point (no draws)
+ last = next((p["winner"] for p in reversed(self.points) if p["winner"]), "opponent")
+ self.winner = (0 if self.score[0] > self.score[1] else 1 if self.score[1] > self.score[0]
+ else 0 if last == "you" else 1)
+ self.points[-1]["cap"] = True
+ self.done = True
+ return
+ self._start_point(hold_from=self.k)
+
+ def replay(self, actions) -> None:
+ for q in actions:
+ self.step(q)
+
+ # ------------------------------------------------------------------ live control
+ def _target_vel(self):
+ a = self.s._actions
+ return (a[-1] - a[-2]) / CONTROL_DT if len(a) >= 2 and getattr(self, "_since_reset", 2) >= 2 else np.zeros(9)
+
+ def _ready_target(self):
+ """Service-driven recovery: the arm back to the ready pose (60 % of its speed limits), the base to its home
+ (the point's spot in its service court, serve_spot)."""
+ tgt = self.s.target
+ lim = ARM_VEL * CONTROL_DT * 0.6
+ arm = tgt[2:] + np.clip(Q0_ARM - tgt[2:], -lim, lim)
+ b, _ = base_goto(tgt[:2], self._target_vel()[:2], self.home)
+ return np.r_[b, arm]
+
+ def _arm_target(self):
+ if self.plan_j < len(self.plan):
+ q = self.plan[self.plan_j]; self.plan_j += 1
+ return q
+ return self._ready_target()
+
+ def decision_due(self) -> bool:
+ leg = self.leg
+ if self.done or leg["state"] != "incoming" or not self.in_play():
+ return False
+ if any(e["kind"] == "hit" for e in self.s.events):
+ return False
+ if self.phase == "swing":
+ return self.k - leg["launch"] >= SWING_AFTER
+ return self._adj_k is not None and self.k >= self._adj_k
+
+ def run_to_decision(self) -> None:
+ self.phase = "swing"
+ while not self.done:
+ if self.decision_due():
+ return
+ self.step(self._arm_target())
+
+ def shot(self, decision: dict, delay_steps: int) -> dict:
+ leg_i = self.n_our_legs
+ rec = {"leg": leg_i, "decision": decision, "delay_steps": int(delay_steps), "k_decision": self.k}
+ for _ in range(delay_steps):
+ if self.leg["state"] != "incoming" or self.done:
+ break
+ self.step(self._arm_target())
+ rec["k_exec"] = self.k
+ self._adj_k = None
+ if decision.get("type") == "swing" and self.leg["state"] == "incoming" and not self.done:
+ self._ik_seed = None
+ if "normal" in decision:
+ self.plan, info = self.plan_racket(float(decision["t"]), decision["pos"], decision["normal"],
+ decision["vel"])
+ else:
+ self.plan, info = self.plan_stroke(float(decision["t"]), np.asarray(decision["pos"], float),
+ np.asarray(decision.get("aim", AIM_DEFAULT), float),
+ decision.get("power", "normal"))
+ self.plan_j = 0
+ rec.update(info)
+ if self.plan and info.get("k_hit") is not None and info["k_hit"] - ADJUST_BEFORE >= self.k + 5:
+ self._adj_k = info["k_hit"] - ADJUST_BEFORE
+ self._rec = rec
+ if decision.get("type") == "swing" and self._adj_k is not None:
+ self.phase = "adjust"
+ while not self.done and self.n_our_legs == leg_i:
+ if self.decision_due():
+ return {"phase": "adjust", **{k: rec[k] for k in rec if k != "decision"}}
+ self.step(self._arm_target())
+ return self._after_leg(rec, leg_i)
+
+ def adjust(self, decision: dict, delay_steps: int) -> dict:
+ rec, leg_i = self._rec, self.n_our_legs
+ rec["adjust"] = decision
+ rec["adjust_delay_steps"] = int(delay_steps)
+ for _ in range(delay_steps):
+ if self.n_our_legs != leg_i or self.done:
+ break
+ self.step(self._arm_target())
+ if decision.get("type") == "adjust" and self.n_our_legs == leg_i and not self.done \
+ and self.leg["state"] == "incoming":
+ self._ik_seed = rec.get("_q_hit")
+ if "normal" in decision:
+ plan, info = self.plan_racket(float(decision["t"]), decision["pos"], decision["normal"], decision["vel"])
+ else:
+ plan, info = self.plan_stroke(float(decision["t"]), np.asarray(decision["pos"], float),
+ np.asarray(decision.get("aim", rec.get("aim", AIM_DEFAULT)), float),
+ decision.get("power", rec.get("power", "normal")))
+ q_hit = info.pop("_q_hit", None)
+ rec["adjust_info"] = info
+ if plan:
+ rec["_q_hit"] = q_hit
+ self.plan, self.plan_j = plan, 0
+ return self._after_leg(rec, leg_i)
+
+ # ------------------------------------------------------------------ real-time protocol (no decision points)
+ def rt_advance(self, n_steps: int):
+ """Run up to n_steps control steps with the current command (the planned stroke, then the return to ready);
+ stops early when a point ends (the command is then dropped). Returns (steps run, points, our results)."""
+ n0, r0, n = len(self.points), len(self.results), 0
+ while n < n_steps and not self.done and len(self.points) == n0:
+ self.step(self._arm_target()); n += 1
+ if len(self.points) > n0:
+ self.plan, self.plan_j = [], 0
+ self._last_act = None
+ return n, self.points[n0:], self.results[r0:]
+
+ def rt_act(self, T, pos, nrm, vel) -> dict:
+ """A new command: the racket state at contact T s from now, planned from the robot's current motion; it
+ replaces the stroke under way (the hit configuration of the replaced stroke seeds the IK)."""
+ t_hit = (self.k - self.leg["launch"]) * CONTROL_DT + float(T)
+ self._ik_seed = getattr(self, "_q_hit_active", None) if self.plan_j < len(self.plan) else None
+ plan, info = self.plan_racket(t_hit, pos, nrm, vel)
+ q_hit = info.pop("_q_hit", None)
+ info["T_from_now"] = round(float(T), 4)
+ if plan:
+ self.plan, self.plan_j = plan, 0
+ self._q_hit_active = q_hit
+ self.shots.append({"k": self.k, "leg": self.n_our_legs, **info})
+ self._last_act = info
+ return info
+
+ def rt_clear(self):
+ self.plan, self.plan_j = [], 0
+ self._last_act = None
+
+ def _after_leg(self, rec, leg_i) -> dict:
+ n0 = len(self.points)
+ while not self.done and self.n_our_legs == leg_i:
+ self.step(self._arm_target())
+ rec.pop("_q_hit", None)
+ self.shots.append(rec)
+ res = dict(self.results[leg_i]) if leg_i < len(self.results) else {"summary": "match over"}
+ self.run_to_decision()
+ res["points_finished"] = self.points[n0:]
+ return res
+
+ # ------------------------------------------------------------------ stroke controller
+ def _twin_phys(self) -> Phys:
+ if self._twin is None:
+ self._twin = Phys()
+ self._twin.reset(self.s.target)
+ return self._twin
+
+ def _base_plan(self, goal, n):
+ """n base targets of the go-to generator from the current base target/velocity towards goal; and the step
+ index at which it has arrived (None if not within n)."""
+ b = self.s.target[:2].copy(); v = self._target_vel()[:2].copy()
+ out, arrived = [], None
+ for i in range(n):
+ b, v = base_goto(b, v, goal)
+ out.append(b.copy())
+ if arrived is None and np.all(b == goal) and not v.any():
+ arrived = i
+ return out, arrived
+
+ def _stroke_for(self, v_in, v_out, p_hit, bxy, seed):
+ ph = self.s
+ sp = float(np.linalg.norm(v_out)); nrm = v_out / sp
+ vin_n = float(v_in @ nrm)
+ u = max(0.05, (sp - E_SHUTTLE * max(0.0, -vin_n)) / RACKET_GAIN)
+ v_p = u * nrm
+ best = None
+ for sgn in (1.0, -1.0):
+ q_h, res = ik(ph, p_hit, sgn * nrm, bxy, seed)
+ if best is None or res < best[1] - 1e-6:
+ best = (q_h, res)
+ q_h, res = best
+ Jp = ph.jac(np.r_[bxy, q_h])[:3]
+ Winv = np.diag(ARM_VEL ** 2)
+ qd_h = Winv @ Jp.T @ np.linalg.solve(Jp @ Winv @ Jp.T + 1e-9 * np.eye(3), v_p)
+ ratio = float(np.max(np.abs(qd_h) / ARM_VEL))
+ return dict(nrm=nrm, v_p=v_p, q_h=q_h, qd_h=qd_h, ik=res, ratio=ratio, v_out=v_out, u=u,
+ p_hit=np.asarray(p_hit, float))
+
+ def plan_stroke(self, t_hit, p_hit, aim, power="normal"):
+ """Swing so that the racket-head centre meets a shuttle centred at p_hit at t_hit (s after it was played)
+ and sends it towards aim. Base: the go-to generator to the forehand stance for p_hit (or as far as it gets
+ 0.05 s before the contact). Shot: the launch velocities that land at aim and clear the net (one per launch
+ angle, the controller's own flight model); power: soft = the slowest, hard = the fastest the arm can swing,
+ normal = the least demanding for the arm. Face normal = the launch direction, head speed from the racket
+ model; IK + a speed-weighted Jacobian inverse give the hit configuration; a cubic swing and follow-through,
+ refined by robot-only rehearsals on a twin; then up to 4 full rehearsals (arm and the real shuttle) correct
+ the aim by the rehearsed landing error. A wrong contact misses in the rehearsal too and is not corrected."""
+ power = power if power in POWER else "normal"
+ info = {"t_hit": t_hit, "p_hit": [float(x) for x in p_hit], "aim": [float(x) for x in aim], "power": power}
+ k_hit = self.leg["launch"] + int(round(t_hit / CONTROL_DT))
+ n_avail = k_hit - self.k
+ info["n_swing_steps_available"] = int(n_avail)
+ info["k_hit"] = None
+ if n_avail < 3:
+ info["stroke"] = "too late: the contact time has already passed"
+ return [], info
+ info["k_hit"] = int(k_hit)
+ # base: stance, or as far as it gets
+ st = stance(p_hit)
+ goal = st
+ b0 = self.s.target[:2].copy()
+ _, arr = self._base_plan(goal, n_avail)
+ if arr is None or arr > n_avail - 5:
+ lo_, hi_ = 0.0, 1.0
+ for _ in range(10):
+ mid = 0.5 * (lo_ + hi_)
+ _, a2 = self._base_plan(b0 + mid * (st - b0), n_avail)
+ if a2 is not None and a2 <= n_avail - 5:
+ lo_ = mid
+ else:
+ hi_ = mid
+ goal = b0 + lo_ * (st - b0)
+ info["base"] = f"could not reach the stance in time: {float(np.linalg.norm(st - goal)):.2f} m short"
+ else:
+ info["base"] = "ok"
+ info["base_goal"] = [round(float(x), 3) for x in goal]
+ base_tg, _ = self._base_plan(goal, n_avail + 40)
+ # incoming shuttle at the contact (the controller's forward model from the true current state)
+ P, V = predict(self.s.sh_p, self.s.sh_v, n_max=int(n_avail * SUBSTEPS))
+ v_in = V[-1] if len(V) else np.zeros(3)
+ rng = np.random.default_rng([self.lv["seed"], 7, self.n_our_legs])
+ aim_n = np.asarray(aim, float) + rng.normal(0.0, EXEC_SIGMA[power], 2)
+ aim_eff = aim_n.copy()
+ seed = getattr(self, "_ik_seed", None)
+ seed = Q0_ARM if seed is None else seed
+ best = None
+ for it in range(4):
+ cands = solve_shots(p_hit, aim_eff, OUR_THETAS, OUR_VMAX, net_margin=0.08)
+ if not cands:
+ info["stroke"] = "no shot from this contact point reaches the aim over the net"
+ if best is None:
+ cands = solve_shots(p_hit, (0.0, 4.0), OUR_THETAS, OUR_VMAX, net_margin=0.08)
+ if not cands:
+ return [], info
+ else:
+ break
+ strokes = [self._stroke_for(v_in, c[2], p_hit, goal, seed) for c in cands]
+ c = self._pick_stroke(strokes, power)
+ tg, sinfo = self._swing(c, goal, base_tg, n_avail)
+ L, spd = self._rehearse(tg)
+ err = None if L is None else float(np.linalg.norm(np.asarray(L) - aim_n))
+ if best is None or (err is not None and (best[2] is None or err < best[2])):
+ best = (tg, sinfo, err, L, spd, c)
+ if L is None or err < 0.08:
+ break
+ aim_eff = aim_eff + (aim_n - np.asarray(L))
+ tg, sinfo, err, L, spd, c = best
+ info.update(sinfo)
+ info["_q_hit"] = c["q_h"]
+ info["rehearsal_landing"] = None if L is None else [round(float(x), 3) for x in L]
+ info["rehearsal_speed"] = None if spd is None else round(float(spd), 2)
+ info.setdefault("stroke", "ok" if L is not None else "the rehearsal missed the shuttle")
+ return tg, info
+
+ RACKET_SCATTER = dict(pos=0.006, ang_deg=0.8, speed=0.03) # execution scatter of the racket state at contact
+
+ def plan_racket(self, t_hit, p_c, nrm, v_p):
+ """Racket-level decision: the player gives the racket state at contact (time t_hit s after the shuttle was
+ played, head centre p_c, string-face normal nrm, head velocity v_p). The controller only makes the robot
+ deliver it: the base to the forehand stance for p_c (or as far as it gets), IK, a speed-weighted Jacobian
+ inverse, a joint-speed-limited cubic swing and robot-only rehearsals that correct the PD lag. It uses no
+ shuttle state and does not aim. The delivered state scatters (seeded, RACKET_SCATTER)."""
+ p_c = np.asarray(p_c, float); nrm = np.asarray(nrm, float); nrm = nrm / np.linalg.norm(nrm)
+ v_p = np.asarray(v_p, float)
+ info = {"t_hit": t_hit, "racket_pos": p_c.round(4).tolist(), "racket_normal": nrm.round(4).tolist(),
+ "racket_vel": v_p.round(3).tolist()}
+ k_hit = self.leg["launch"] + int(round(t_hit / CONTROL_DT))
+ n_avail = k_hit - self.k
+ info["n_swing_steps_available"] = int(n_avail)
+ info["k_hit"] = None
+ if n_avail < 3:
+ info["stroke"] = "too late: the contact time has already passed"
+ return [], info
+ info["k_hit"] = int(k_hit)
+ rng = np.random.default_rng([self.lv["seed"], 13, self.n_our_legs])
+ sc = self.RACKET_SCATTER
+ p_c = p_c + rng.normal(0.0, sc["pos"], 3)
+ axis = np.cross(nrm, rng.normal(0.0, 1.0, 3)); axis /= np.linalg.norm(axis)
+ ang = np.radians(rng.normal(0.0, sc["ang_deg"]))
+ nrm = nrm * np.cos(ang) + np.cross(axis, nrm) * np.sin(ang); nrm /= np.linalg.norm(nrm)
+ v_p = v_p * (1.0 + rng.normal(0.0, sc["speed"]))
+ st = stance(p_c)
+ goal = st
+ b0 = self.s.target[:2].copy()
+ _, arr = self._base_plan(goal, n_avail)
+ if arr is None or arr > n_avail - 5:
+ lo_, hi_ = 0.0, 1.0
+ for _ in range(10):
+ mid = 0.5 * (lo_ + hi_)
+ _, a2 = self._base_plan(b0 + mid * (st - b0), n_avail)
+ if a2 is not None and a2 <= n_avail - 5:
+ lo_ = mid
+ else:
+ hi_ = mid
+ goal = b0 + lo_ * (st - b0)
+ info["base"] = f"could not reach the stance in time: {float(np.linalg.norm(st - goal)):.2f} m short"
+ else:
+ info["base"] = "ok"
+ info["base_goal"] = [round(float(x), 3) for x in goal]
+ base_tg, _ = self._base_plan(goal, n_avail + 40)
+ ph = self.s
+ seed = getattr(self, "_ik_seed", None)
+ q_now = ph.target[2:].copy() # the swing starts from the current joint targets
+ seeds = ([] if seed is None else [seed]) + [q_now, Q0_ARM]
+ q_h, res, sgn, alts = ik_multi(ph, p_c, nrm, goal, seeds, q_now) # deterministic multi-start, nearest first
+ Winv = np.diag(ARM_VEL ** 2)
+ tried = None
+ for q_h, res, _ in [(q_h, res, sgn)] + alts:
+ Jp = ph.jac(np.r_[goal, q_h])[:3]
+ qd_h = Winv @ Jp.T @ np.linalg.solve(Jp @ Winv @ Jp.T + 1e-9 * np.eye(3), v_p)
+ ratio = float(np.max(np.abs(qd_h) / ARM_VEL))
+ c = dict(nrm=nrm, v_p=v_p, q_h=q_h, qd_h=qd_h, ik=res, ratio=ratio, v_out=np.zeros(3), p_hit=p_c)
+ tg, sinfo = self._swing(c, goal, base_tg, n_avail)
+ sc = swing_score(sinfo["blade_error_m"], sinfo["normal_error_deg"],
+ np.linalg.norm(self._swing_last[2] - v_p / sinfo["speed_scale"]))
+ if tried is None or sc < tried[0]:
+ tried = (sc, tg, sinfo, self._swing_last, q_h, res)
+ if sinfo["blade_error_m"] <= DELIVERY_POS_WARN and sinfo["normal_error_deg"] <= DELIVERY_ANG_WARN:
+ break # delivered: the nearest solution that works
+ _, tg, sinfo, self._swing_last, q_h, res = tried
+ for k in ("shot_speed_plan", "launch_dir", "head_speed_plan"):
+ sinfo.pop(k, None)
+ info.update(sinfo)
+ p, n_act, v_act = self._swing_last
+ info["racket_vel_delivered"] = [round(float(x), 3) for x in v_act]
+ info["_q_hit"] = q_h
+ notes = []
+ if res > IK_OK: notes.append(f"pose not reachable exactly (IK residual {res:.3f})")
+ if sinfo["blade_error_m"] > DELIVERY_POS_WARN or sinfo["normal_error_deg"] > DELIVERY_ANG_WARN:
+ notes.append(f"pose not delivered: the rehearsed racket head is {100 * sinfo['blade_error_m']:.1f} cm off "
+ f"and the face {sinfo['normal_error_deg']:.1f} deg off the command at the contact time")
+ if sinfo["speed_scale"] > 1.005: notes.append(f"head speed limited by the joint speed limits (x{1 / sinfo['speed_scale']:.2f})")
+ if sinfo["n_swing_steps"] < 20: notes.append("short swing (little time left)")
+ if info["base"] != "ok": notes.append(info["base"])
+ info["stroke"] = "; ".join(notes) or "ok"
+ return tg, info
+
+ @staticmethod
+ def _pick_stroke(strokes, power):
+ good = ([c for c in strokes if c["ik"] < 2e-3 and c["ratio"] <= 1.0] or [c for c in strokes if c["ik"] < 2e-3]
+ or strokes)
+ if power == "normal":
+ return min(good, key=lambda c: c["ratio"])
+ sp = sorted(good, key=lambda c: float(np.linalg.norm(c["v_out"])))
+ return sp[-1] if power == "hard" else sp[0]
+
+ def _swing(self, c, goal, base_tg, n_avail):
+ """Arm swing (cubic to the hit configuration, follow-through) + base plan; 5 robot-only twin rehearsals
+ correct the hit configuration/velocity for the PD lag, and the best of them (swing_score) is kept."""
+ ph = self.s
+ scale = max(1.0, c["ratio"] / 0.9)
+ q_h, qd_h = c["q_h"].copy(), c["qd_h"] / scale
+ v_p = c["v_p"] / scale
+ q_s = ph.target[2:].copy(); v_s = self._target_vel()[2:]
+ n_sw = int(n_avail)
+ if np.max(np.abs(v_s)) < 1e-6:
+ for n in range(25, int(n_avail) + 1):
+ sw = hermite(q_s, np.zeros(7), q_h, qd_h, n * CONTROL_DT, n)
+ if np.max(np.abs(np.diff(np.vstack([q_s, sw]), axis=0)) / (ARM_VEL * CONTROL_DT)) <= 0.97:
+ n_sw = n
+ break
+ n_sw = int(min(n_sw, n_avail))
+ Winv = np.diag(ARM_VEL ** 2)
+ q_goal, qd_goal = q_h.copy(), qd_h.copy()
+ best = None
+ for it in range(5):
+ tg = self._swing_targets(q_goal, qd_goal, n_avail, n_sw, base_tg)
+ p, n_act, v_act = self._simulate_arm(tg, n_avail)
+ sg = 1.0 if n_act @ c["nrm"] >= 0 else -1.0
+ perr = float(np.linalg.norm(p - c["p_hit"]))
+ nerr = float(np.degrees(np.arccos(np.clip(abs(float(n_act @ c["nrm"])), 0.0, 1.0))))
+ sc = swing_score(perr, nerr, np.linalg.norm(v_act - v_p))
+ if best is None or sc < best[0]: # keep the best of the correction passes, not the last one
+ best = (sc, tg, (p, n_act, v_act), perr, nerr)
+ if it == 4:
+ break
+ J = ph.jac(np.r_[goal, q_goal])
+ e = np.r_[c["p_hit"] - p, np.cross(n_act, sg * c["nrm"])]
+ q_goal = np.clip(q_goal + J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), e),
+ ph.lo[2:] + 1e-4, ph.hi[2:] - 1e-4)
+ Jp = J[:3]
+ qd_goal = qd_goal + Winv @ Jp.T @ np.linalg.solve(Jp @ Winv @ Jp.T + 1e-9 * np.eye(3), v_p - v_act) * 0.7
+ qd_goal = qd_goal / max(1.0, float(np.max(np.abs(qd_goal) / ARM_VEL)))
+ _, tg, self._swing_last, perr, nerr = best
+ info = {"ik_residual": round(float(c["ik"]), 5), "speed_scale": round(scale, 3), "n_swing_steps": n_sw,
+ "blade_error_m": round(perr, 4), "normal_error_deg": round(nerr, 2),
+ "head_speed_plan": round(float(np.linalg.norm(v_p)), 2),
+ "shot_speed_plan": round(float(np.linalg.norm(c["v_out"]) / scale), 2),
+ "launch_dir": [round(float(x), 3) for x in c["nrm"]]}
+ info["stroke"] = "ok" if n_sw >= 20 else "short swing (little time left: slow racket)"
+ return tg, info
+
+ def _swing_targets(self, q_h, qd_h, n_avail, n_sw, base_tg):
+ ph = self.s
+ q_s = ph.target[2:].copy(); v_s = self._target_vel()[2:]
+ pre = np.tile(q_s, (n_avail - n_sw, 1))
+ swing = hermite(q_s, v_s if n_sw == n_avail else np.zeros(7), q_h, qd_h, n_sw * CONTROL_DT, n_sw)
+ n_f = 25
+ follow = hermite(q_h, qd_h, q_h + qd_h * 0.5 * n_f * CONTROL_DT, np.zeros(7), n_f * CONTROL_DT, n_f)
+ out, prev = [], ph.target.copy()
+ lim = VEL_LIMIT * CONTROL_DT * 0.999
+ for i, q in enumerate(np.vstack([pre, swing, follow])):
+ q9 = np.r_[base_tg[min(i, len(base_tg) - 1)], q]
+ q9 = np.clip(q9, ph.lo + 1e-4, ph.hi - 1e-4)
+ q9 = prev + np.clip(q9 - prev, -lim, lim)
+ out.append(q9); prev = q9
+ return out
+
+ def _simulate_arm(self, targets, n):
+ """Robot-only twin rollout from the live robot state: racket (pos, normal, velocity) after n steps."""
+ tw = self._twin_phys()
+ tw.copy_from(self.s)
+ tw.sh_live = False; tw.hit_enabled = False
+ for j in range(n):
+ tw.step(targets[j])
+ mj.mj_forward(tw.m, tw.d)
+ return tw.racket_state()
+
+ def _rehearse(self, targets):
+ """Full twin rehearsal (robot and the real shuttle): landing xy of our shot (shuttle-only prediction after
+ the hit) and its speed off the racket; (None, None) if the racket never meets the shuttle."""
+ tw = self._twin_phys()
+ tw.copy_from(self.s)
+ for j in range(len(targets) + 30):
+ tw.step(targets[j] if j < len(targets) else targets[-1])
+ h = [e for e in tw.events if e["kind"] == "hit"]
+ if h:
+ P, _ = predict(tw.sh_p, tw.sh_v)
+ return (P[-1][:2].tolist() if len(P) else list(tw.sh_p[:2])), h[0]["speed"]
+ if not tw.sh_live:
+ break
+ return None, None
+
+ # ------------------------------------------------------------------ views
+ @staticmethod
+ def cam_pose(lookat, dist, az, el):
+ a, e = math.radians(az), math.radians(el)
+ fwd = np.array([math.cos(e) * math.cos(a), math.cos(e) * math.sin(a), math.sin(e)])
+ up = np.array([-math.sin(e) * math.cos(a), -math.sin(e) * math.sin(a), math.cos(e)])
+ pos = np.asarray(lookat, float) - dist * fwd
+ return pos, fwd, up
+
+ @classmethod
+ def cam_info(cls):
+ out = []
+ for name, c in zip(("behind", "side"), cls.CAMS):
+ pos, fwd, up = cls.cam_pose(*c)
+ out.append({"name": name, "position": [round(float(x), 4) for x in pos],
+ "forward": [round(float(x), 4) for x in fwd], "up": [round(float(x), 4) for x in up]})
+ return out
+
+ def _set_render_state(self, rd, sn):
+ rd.qpos[:] = sn["qpos"]
+ rd.mocap_pos[0] = sn["sh"]
+ v = np.asarray(sn["shv"], float)
+ if np.linalg.norm(v) < 1e-6:
+ v = np.array([0.0, 0.0, -1.0])
+ rd.mocap_quat[0] = quat_z_to(v)
+ mj.mj_kinematics(self.s.m, rd)
+
+ @staticmethod
+ def _extra_geoms(scn, opp_xy, sh=None):
+ def add(typ, size, pos, rgba, mat=np.eye(3)):
+ if scn.ngeom >= scn.maxgeom:
+ return
+ mj.mjv_initGeom(scn.geoms[scn.ngeom], typ, np.asarray(size, float), np.asarray(pos, float),
+ np.asarray(mat, float).ravel(), np.asarray(rgba, np.float32))
+ scn.ngeom += 1
+ ox, oy = float(opp_xy[0]), float(opp_xy[1])
+ add(mj.mjtGeom.mjGEOM_CAPSULE, [0.16, 0.55, 0], [ox, oy, 0.75], [0.35, 0.35, 0.42, 1])
+ add(mj.mjtGeom.mjGEOM_SPHERE, [0.12, 0, 0], [ox, oy, 1.55], [0.85, 0.7, 0.6, 1])
+ # the opponent's racket: red head, reaching towards the shuttle when it is near
+ rp = np.array([ox + 0.45, oy - 0.1, 1.9])
+ if sh is not None:
+ d = np.array(sh) - np.array([ox, oy, 1.2])
+ if np.linalg.norm(d) < 1.6:
+ rp = np.array([ox, oy, 1.2]) + d / max(1e-6, np.linalg.norm(d)) * min(1.2, np.linalg.norm(d))
+ add(mj.mjtGeom.mjGEOM_ELLIPSOID, [0.10, 0.02, 0.13], rp, [0.9, 0.1, 0.1, 1])
+
+ def _renderer(self, w, h):
+ key = (w, h)
+ if getattr(self, "_rkey", None) != key:
+ self._r = mj.Renderer(self.s.m, height=h, width=w)
+ self._rd = mj.MjData(self.s.m)
+ self._rkey = key
+ self._cams = []
+ for lookat, dist, az, el in self.CAMS:
+ c = mj.MjvCamera(); c.lookat[:] = lookat; c.distance = dist; c.azimuth = az; c.elevation = el
+ self._cams.append(c)
+ return self._r, self._rd
+
+ def render_views(self) -> bytes:
+ """PNG: 2 rows (behind camera, side camera) x 4 columns (snapshots 60 ms apart, oldest left), each tile
+ stamped with its time since the shuttle was played."""
+ import imageio.v2 as imageio
+ from PIL import Image, ImageDraw
+ w, h = self.TILE
+ r, rd = self._renderer(w, h)
+ hist = list(self.hist)
+ snaps = [hist[max(0, len(hist) - 1 - b)] for b in reversed(self.VIEW_BACK)]
+ rows = []
+ for c in self._cams:
+ tiles = []
+ for sn in snaps:
+ self._set_render_state(rd, sn)
+ r.update_scene(rd, camera=c)
+ self._extra_geoms(r.scene, sn["opp"], sn["sh"])
+ im = Image.fromarray(r.render())
+ ImageDraw.Draw(im).text((6, 4), f"t={sn['t']:.2f}s", fill=(255, 255, 255))
+ tiles.append(np.asarray(im))
+ rows.append(np.concatenate(tiles, axis=1))
+ buf = io.BytesIO()
+ imageio.imwrite(buf, np.concatenate(rows, axis=0), format="png")
+ return buf.getvalue()
+
+ def view_times(self):
+ hist = list(self.hist)
+ return [hist[max(0, len(hist) - 1 - b)]["t"] for b in reversed(self.VIEW_BACK)]
+
+ def decision_observation(self) -> dict:
+ ph = self.s
+ leg = self.leg
+ heard = []
+ if leg["kind"] == "serve":
+ heard.append({"event": "the opponent served", "t": 0.0})
+ else:
+ heard.append({"event": "the opponent hit the shuttle", "t": 0.0})
+ c, n, _ = ph.racket_state()
+ return {"score": {"you": self.score[0], "opponent": self.score[1]}, "point": len(self.points) + 1,
+ "ball": "serve" if leg["kind"] == "serve" else "opponent's return",
+ "t_since_played": self.t_since_launch(), "heard": heard, "view_times": self.view_times(),
+ "robot_base_xy": [round(float(x), 3) for x in ph.d.qpos[ph.qa[:2]]],
+ "q_arm": [round(float(x), 4) for x in ph.d.qpos[ph.qa[2:]]],
+ "racket_pos": [round(float(x), 3) for x in c], "racket_normal": [round(float(x), 3) for x in n]}
+
+
+def _ready_pose():
+ """Ready pose: racket head up in front of the robot's right shoulder, face towards the net."""
+ global Q0_ARM
+ ph = Phys(); ph.reset(np.r_[HOME, Q0_ARM])
+ q, err = ik(ph, np.r_[HOME + np.array([0.35, 0.45]), SHOULDER_Z + 0.45], np.array([0.0, 1.0, 0.25]), HOME,
+ np.array([0.0, -0.2, 0.0, -1.6, 0.0, 1.6, 0.785]), iters=400)
+ Q0_ARM = np.round(q, 4)
+
+
+_ready_pose()
+
+
+def render_video(actions, level, out, fps=25, every=2):
+ """Replay video: the two decision cameras side by side, 2x slow motion (every `every` control steps at 25 fps),
+ 3x fewer frames while no shuttle is in play."""
+ import imageio.v2 as imageio
+ from PIL import Image, ImageDraw
+ mt = Match(level)
+ r = mj.Renderer(mt.s.m, height=360, width=640)
+ rd = mj.MjData(mt.s.m)
+ cams = []
+ for lookat, dist, az, el in Match.CAMS:
+ c = mj.MjvCamera(); c.lookat[:] = lookat; c.distance = dist; c.azimuth = az; c.elevation = el
+ cams.append(c)
+ w = imageio.get_writer(out, fps=fps, macro_block_size=8)
+ for k, q in enumerate(actions):
+ mt.step(q)
+ live = mt.s.sh_live
+ if k % (every if live else 3 * every):
+ continue
+ sn = {"qpos": mt.s.d.qpos.copy(), "sh": mt.s.sh_p, "shv": mt.s.sh_v}
+ mt._set_render_state(rd, sn)
+ imgs = []
+ for c in cams:
+ r.update_scene(rd, camera=c)
+ mt._extra_geoms(r.scene, mt.opp_xy(), mt.s.sh_p)
+ imgs.append(r.render())
+ im = Image.fromarray(np.concatenate(imgs, axis=1))
+ ImageDraw.Draw(im).text((8, 6), f"robot {mt.score[0]} : {mt.score[1]} opponent (level {level})",
+ fill=(255, 255, 255))
+ w.append_data(np.asarray(im))
+ w.close(); r.close()
diff --git a/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/LICENSE.menagerie-franka b/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/LICENSE.menagerie-franka
new file mode 100644
index 0000000000..d9a10c0d8e
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/LICENSE.menagerie-franka
@@ -0,0 +1,176 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
diff --git a/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link0.stl b/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link0.stl
new file mode 100644
index 0000000000..def070c707
Binary files /dev/null and b/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link0.stl differ
diff --git a/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link1.stl b/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link1.stl
new file mode 100644
index 0000000000..426bcf2d7a
Binary files /dev/null and b/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link1.stl differ
diff --git a/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link2.stl b/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link2.stl
new file mode 100644
index 0000000000..b369f1599a
Binary files /dev/null and b/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link2.stl differ
diff --git a/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link3.stl b/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link3.stl
new file mode 100644
index 0000000000..25162eeedf
Binary files /dev/null and b/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link3.stl differ
diff --git a/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link4.stl b/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link4.stl
new file mode 100644
index 0000000000..76c8c33c3e
Binary files /dev/null and b/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link4.stl differ
diff --git a/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link5_collision_0.obj b/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link5_collision_0.obj
new file mode 100644
index 0000000000..6d6eb5203b
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link5_collision_0.obj
@@ -0,0 +1,188 @@
+v 0.029063642 0.095448048 -0.133538792
+v 0.049877137 -0.013343874 -0.215408068
+v 0.046604998 0.029219000 -0.259000003
+v -0.043494001 0.033698998 -0.259000003
+v -0.030187000 -0.020500001 -0.186547995
+v -0.017736474 -0.052050648 -0.258999242
+v 0.012548444 0.082957777 -0.202027869
+v 0.050364564 0.017247290 -0.214926371
+v 0.020709741 -0.020753554 -0.182012846
+v -0.038214683 0.050463360 -0.167851336
+v 0.045944492 -0.030214707 -0.258999161
+v -0.051997126 -0.017851673 -0.259000003
+v 0.026338819 0.085091480 -0.183646959
+v 0.020922000 0.050882000 -0.259000003
+v 0.045491802 0.013339541 -0.187636452
+v 0.050951000 0.020726001 -0.259000003
+v 0.023551804 0.063747043 -0.133252288
+v -0.013548823 -0.047308172 -0.207602441
+v -0.023108632 0.089348183 -0.175470195
+v 0.028642003 -0.042568484 -0.211525585
+v -0.051912808 0.016682228 -0.233346078
+v 0.021637405 0.093787480 -0.156753967
+v 0.028892799 0.093108394 -0.147202451
+v -0.021765672 0.050517374 -0.259000003
+v 0.029191773 0.046614188 -0.259000003
+v 0.020095230 0.083558674 -0.197022477
+v 0.050294057 0.012853477 -0.210481151
+v 0.041400984 -0.012110881 -0.190499104
+v 0.050274495 0.021321905 -0.223857806
+v 0.050395896 -0.021963709 -0.259000003
+v -0.014053484 -0.016454442 -0.177588961
+v -0.023077204 0.053522191 -0.146035077
+v 0.028830698 0.067305577 -0.135375573
+v -0.038313158 -0.038208997 -0.224413296
+v 0.045422879 -0.030121078 -0.229083894
+v 0.011903144 -0.042590730 -0.199122301
+v 0.012319026 -0.051745998 -0.224350901
+v -0.052457958 0.016511494 -0.258999590
+v -0.046985660 -0.009035359 -0.196875560
+v 0.022625311 0.097598446 -0.133939149
+v 0.012620136 0.087869933 -0.188952639
+v 0.025225283 0.087563533 -0.179602397
+v -0.009634502 0.083175007 -0.202322834
+v -0.024273001 0.085358001 -0.188354000
+v 0.022706000 0.084515996 -0.192412004
+v 0.031834746 0.074158814 -0.139114503
+v 0.050391338 -0.004898283 -0.210560332
+v 0.036850054 -0.028951537 -0.199617216
+v 0.028814057 -0.007357717 -0.177964311
+v 0.007988000 -0.025363000 -0.182107002
+v -0.017462573 -0.033546585 -0.190912689
+v -0.022334082 -0.002848132 -0.172981292
+v -0.030079996 0.053249859 -0.151432391
+v 0.045789921 -0.008346553 -0.194042762
+v 0.037322809 -0.011895567 -0.186316195
+v -0.034569787 -0.042770809 -0.259000003
+v -0.026268487 -0.046990059 -0.224191914
+v 0.033556075 -0.043548766 -0.258998990
+v 0.049874237 -0.022123435 -0.233471659
+v -0.005066666 -0.052041921 -0.219576018
+v 0.016204123 -0.046663484 -0.207808223
+v -0.051942493 -0.005029111 -0.219727096
+v -0.029441908 0.082404274 -0.175896559
+v -0.042174398 -0.025291337 -0.202643498
+f 12 4 3
+f 14 3 4
+f 16 12 3
+f 23 3 13
+f 23 16 3
+f 23 1 16
+f 24 14 4
+f 25 13 3
+f 25 3 14
+f 26 14 7
+f 26 25 14
+f 27 8 1
+f 29 16 1
+f 29 1 8
+f 29 8 16
+f 30 12 16
+f 32 31 17
+f 33 1 17
+f 38 4 12
+f 40 22 19
+f 40 23 22
+f 40 1 23
+f 40 32 17
+f 40 17 1
+f 41 19 22
+f 41 26 7
+f 42 23 13
+f 42 22 23
+f 42 41 22
+f 43 7 14
+f 43 14 24
+f 43 41 7
+f 43 19 41
+f 44 24 4
+f 44 43 24
+f 44 19 43
+f 45 13 25
+f 45 25 26
+f 45 42 13
+f 45 26 41
+f 45 41 42
+f 46 27 1
+f 46 15 27
+f 46 1 33
+f 47 27 15
+f 47 30 16
+f 47 16 8
+f 47 8 27
+f 48 20 35
+f 48 35 2
+f 48 36 20
+f 48 9 36
+f 49 17 9
+f 50 9 17
+f 50 17 31
+f 50 36 9
+f 51 31 5
+f 51 50 31
+f 51 18 36
+f 51 36 50
+f 52 32 5
+f 52 5 31
+f 52 31 32
+f 53 10 39
+f 53 39 5
+f 53 5 32
+f 53 32 40
+f 54 33 28
+f 54 46 33
+f 54 15 46
+f 54 47 15
+f 54 2 47
+f 54 48 2
+f 54 28 48
+f 55 33 17
+f 55 28 33
+f 55 17 49
+f 55 48 28
+f 55 49 9
+f 55 9 48
+f 56 34 12
+f 56 30 6
+f 56 12 30
+f 57 56 6
+f 57 34 56
+f 58 35 20
+f 58 11 35
+f 58 20 37
+f 58 37 6
+f 58 30 11
+f 58 6 30
+f 59 2 35
+f 59 47 2
+f 59 30 47
+f 59 35 11
+f 59 11 30
+f 60 6 37
+f 60 57 6
+f 60 18 57
+f 61 37 20
+f 61 20 36
+f 61 60 37
+f 61 36 18
+f 61 18 60
+f 62 38 12
+f 62 21 38
+f 62 39 10
+f 62 10 21
+f 63 38 21
+f 63 21 10
+f 63 19 44
+f 63 44 4
+f 63 4 38
+f 63 10 53
+f 63 53 40
+f 63 40 19
+f 64 5 39
+f 64 51 5
+f 64 18 51
+f 64 57 18
+f 64 34 57
+f 64 12 34
+f 64 62 12
+f 64 39 62
diff --git a/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link5_collision_1.obj b/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link5_collision_1.obj
new file mode 100644
index 0000000000..2eeeeea170
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link5_collision_1.obj
@@ -0,0 +1,119 @@
+v 0.029605924 0.107695894 -0.057770639
+v 0.028114332 0.082823920 -0.058553905
+v 0.038816102 0.053402838 -0.175505396
+v -0.026856016 0.088084521 -0.175136227
+v -0.030626847 0.107119812 -0.057687294
+v 0.025670733 0.088513946 -0.175229901
+v -0.004989269 0.102164150 -0.123603135
+v -0.038214683 0.050463360 -0.167851336
+v 0.029153411 0.097073936 -0.123627471
+v -0.039514421 0.050433927 -0.176900026
+v -0.009555079 0.106683172 -0.095345165
+v -0.018650687 0.092581494 -0.165880068
+v 0.028410194 0.050382871 -0.151882879
+v -0.025116868 0.079917612 -0.059207257
+v 0.027728461 0.088850155 -0.170468824
+v 0.012301352 0.106583136 -0.090584029
+v -0.033031356 0.072019963 -0.176122603
+v -0.028518812 0.083365915 -0.058497467
+v 0.017236843 0.092763911 -0.165977938
+v -0.013955552 0.101873439 -0.118898329
+v -0.028958102 0.093907525 -0.142630397
+v 0.017254189 0.075705868 -0.064336333
+v -0.014409871 0.075430847 -0.064290830
+v 0.028214046 0.087293870 -0.171111784
+v 0.025659250 0.106544369 -0.076459959
+v 0.003562050 0.106723586 -0.095327997
+v -0.038642138 0.054804181 -0.176806387
+v 0.024373464 0.079432104 -0.059087522
+v 0.021627842 0.092908946 -0.161300197
+v -0.022714762 0.106727072 -0.081193925
+v -0.026651997 0.092292062 -0.156493182
+v -0.028411485 0.090537503 -0.161463618
+v -0.033238728 0.052765384 -0.155973185
+v 0.028928091 0.106502887 -0.067219353
+v 0.003488032 0.101747359 -0.123570031
+v 0.025518961 0.096898989 -0.133035213
+v 0.021620985 0.097180492 -0.137775852
+v -0.029182131 0.097825064 -0.119030284
+v -0.022783418 0.101743257 -0.109443270
+v -0.027976784 0.086163124 -0.175228428
+v -0.029871457 0.106777512 -0.062281333
+f 1 2 3
+f 5 2 1
+f 9 1 3
+f 10 6 3
+f 11 5 1
+f 12 6 4
+f 13 3 2
+f 13 10 3
+f 13 8 10
+f 17 4 6
+f 18 10 8
+f 18 5 10
+f 18 8 14
+f 18 2 5
+f 19 12 7
+f 19 6 12
+f 20 11 7
+f 20 7 12
+f 23 14 8
+f 23 13 22
+f 24 15 9
+f 24 9 3
+f 24 3 6
+f 24 6 15
+f 25 16 1
+f 26 11 1
+f 26 1 16
+f 26 7 11
+f 26 16 19
+f 27 17 6
+f 27 6 10
+f 27 10 5
+f 27 5 21
+f 28 18 14
+f 28 2 18
+f 28 23 22
+f 28 14 23
+f 28 22 13
+f 28 13 2
+f 29 15 6
+f 29 6 19
+f 30 5 11
+f 30 11 20
+f 31 12 4
+f 31 21 30
+f 32 27 21
+f 32 17 27
+f 32 31 4
+f 32 21 31
+f 33 23 8
+f 33 8 13
+f 33 13 23
+f 34 25 1
+f 34 1 9
+f 34 9 25
+f 35 26 19
+f 35 19 7
+f 35 7 26
+f 36 9 15
+f 36 15 29
+f 36 25 9
+f 37 29 19
+f 37 19 16
+f 37 16 25
+f 37 36 29
+f 37 25 36
+f 38 30 21
+f 38 21 5
+f 39 30 20
+f 39 20 12
+f 39 31 30
+f 39 12 31
+f 40 32 4
+f 40 4 17
+f 40 17 32
+f 41 38 5
+f 41 5 30
+f 41 30 38
diff --git a/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link5_collision_2.obj b/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link5_collision_2.obj
new file mode 100644
index 0000000000..6b563bff79
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link5_collision_2.obj
@@ -0,0 +1,188 @@
+v 0.016219155 0.099363113 0.048750773
+v 0.046550363 0.015799999 0.011058674
+v 0.046166659 0.105324245 -0.019041548
+v -0.005436418 0.111465780 -0.067873175
+v -0.043746749 0.015799999 0.019475930
+v 0.032618475 0.015799999 -0.035021468
+v 0.012971462 0.125447286 0.026076443
+v 0.045556378 0.100993129 0.023528159
+v 0.016534659 0.015799999 0.044952921
+v 0.045622136 0.015799999 -0.014505461
+v 0.031590266 0.097675904 -0.057701935
+v -0.026144502 0.015799999 -0.040104519
+v 0.020916727 0.125582876 -0.010159381
+v -0.043170314 0.100482302 0.027956662
+v 0.046145375 0.108191241 0.006346428
+v 0.028387091 0.112218342 0.031375415
+v 0.033002187 0.099171431 0.039965413
+v 0.016412747 0.015799999 -0.044989475
+v 0.036705779 0.015799999 -0.030707024
+v -0.022295018 0.125131249 -0.010109805
+v 0.029605924 0.107695894 -0.057770639
+v -0.013213095 0.112592014 0.039924672
+v -0.017325918 0.015799999 0.044664757
+v -0.047688079 0.104963029 -0.014858533
+v 0.045808408 0.103510400 0.019105049
+v 0.032957420 0.121769349 -0.001719666
+v 0.011885780 0.108060682 0.044095325
+v 0.016109216 0.089384114 0.048719259
+v 0.041214473 0.103236411 0.027403040
+v 0.041650999 0.015799999 0.023706000
+v 0.028114332 0.082823920 -0.058553905
+v -0.017699993 0.015799999 -0.044454039
+v 0.030954458 0.092818151 -0.058089685
+v -0.013656957 0.125189726 -0.019080479
+v 0.020627846 0.125801899 0.015541304
+v 0.008510412 0.111150243 -0.067818128
+v -0.029781181 0.121768239 0.014799138
+v -0.038794729 0.015799999 0.028113908
+v -0.017496539 0.098143056 0.049083962
+v -0.044002704 0.015799999 -0.018961373
+v -0.047333769 0.101445201 0.019313718
+v -0.030626847 0.107119812 -0.057687294
+v 0.046107670 0.108070694 -0.010345774
+v 0.028871230 0.120837663 -0.014381368
+v 0.011692637 0.121507793 0.031446733
+v 0.020178268 0.103656248 0.044326107
+v 0.024954524 0.015799999 0.040826797
+v 0.037099553 0.099607308 0.036020114
+v 0.028145238 0.121197152 0.018754182
+v -0.021927781 0.125344027 0.015252414
+v 0.020917077 0.111451583 -0.057406886
+v 0.012405067 0.125386135 -0.019235931
+v 0.024373464 0.079432104 -0.059087522
+v -0.033976639 0.107508587 0.031219781
+v -0.032505696 0.120513471 -0.010314825
+v -0.026112117 0.015799999 0.040139331
+v -0.008981987 0.108489258 0.044495871
+v -0.005033433 0.070411983 0.049486264
+v -0.047363327 0.103674321 0.015035708
+v -0.033832737 0.116474922 0.018745562
+v -0.047827588 0.074670758 0.002492660
+v -0.028518812 0.083365915 -0.058497467
+v -0.022142435 0.111037086 -0.057352830
+v 0.041463828 0.111761132 -0.014586542
+f 6 2 5
+f 9 5 2
+f 10 3 2
+f 10 2 6
+f 11 3 10
+f 12 6 5
+f 15 2 3
+f 18 6 12
+f 19 10 6
+f 21 3 11
+f 23 5 9
+f 25 8 2
+f 25 2 15
+f 28 17 1
+f 29 8 25
+f 30 9 2
+f 30 2 8
+f 31 6 18
+f 31 19 6
+f 32 18 12
+f 32 4 18
+f 33 11 10
+f 33 10 19
+f 33 19 31
+f 35 13 34
+f 35 26 13
+f 36 21 11
+f 36 11 33
+f 36 33 31
+f 36 18 4
+f 38 14 5
+f 38 5 23
+f 40 12 5
+f 41 5 14
+f 42 40 24
+f 43 26 15
+f 43 15 3
+f 44 26 21
+f 44 21 13
+f 44 13 26
+f 45 16 7
+f 45 7 22
+f 46 17 16
+f 46 45 27
+f 46 16 45
+f 46 27 1
+f 46 1 17
+f 47 28 9
+f 47 17 28
+f 47 9 30
+f 48 8 29
+f 48 30 8
+f 48 47 30
+f 48 17 47
+f 48 29 16
+f 48 16 17
+f 49 29 25
+f 49 16 29
+f 49 25 15
+f 49 15 26
+f 49 26 35
+f 49 35 7
+f 49 7 16
+f 50 7 35
+f 50 37 22
+f 50 22 7
+f 50 35 34
+f 50 34 20
+f 51 13 21
+f 51 21 36
+f 52 34 13
+f 52 51 36
+f 52 13 51
+f 52 36 4
+f 52 4 34
+f 53 36 31
+f 53 31 18
+f 53 18 36
+f 54 22 37
+f 54 39 22
+f 54 14 39
+f 55 42 24
+f 55 50 20
+f 55 37 50
+f 56 38 23
+f 56 23 39
+f 56 39 14
+f 56 14 38
+f 57 22 39
+f 57 45 22
+f 57 27 45
+f 57 39 1
+f 57 1 27
+f 58 28 1
+f 58 1 39
+f 58 9 28
+f 58 39 23
+f 58 23 9
+f 59 55 24
+f 59 37 55
+f 60 41 14
+f 60 59 41
+f 60 37 59
+f 60 54 37
+f 60 14 54
+f 61 40 5
+f 61 5 41
+f 61 24 40
+f 61 59 24
+f 61 41 59
+f 62 12 40
+f 62 40 42
+f 62 32 12
+f 62 42 4
+f 62 4 32
+f 63 34 4
+f 63 4 42
+f 63 20 34
+f 63 55 20
+f 63 42 55
+f 64 43 3
+f 64 3 21
+f 64 21 26
+f 64 26 43
diff --git a/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link6.stl b/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link6.stl
new file mode 100644
index 0000000000..2e9594a873
Binary files /dev/null and b/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link6.stl differ
diff --git a/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link7.stl b/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link7.stl
new file mode 100644
index 0000000000..0532d05750
Binary files /dev/null and b/scripts/roboolympics/shared/sports/badminton/sim/scene/assets/link7.stl differ
diff --git a/scripts/roboolympics/shared/sports/badminton/sim/scene/bm_duel.xml b/scripts/roboolympics/shared/sports/badminton/sim/scene/bm_duel.xml
new file mode 100644
index 0000000000..64d44c831a
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/badminton/sim/scene/bm_duel.xml
@@ -0,0 +1,245 @@
+<!--
+ Robot badminton DUEL scene (render only), generated by scripts/olympiad/badminton/mk_duel_scene.py from
+ bm_scene.xml: robot A as in the match scene; robot B (names *_b, identical) the same robot in
+ a body rotated 180 degrees about z. The physics runs each robot in its own copy of bm_scene.xml (bduel.py).
+-->
+<mujoco model="rcb_badminton_duel">
+ <compiler angle="radian" meshdir="assets" autolimits="true"/>
+ <option integrator="implicitfast" timestep="0.001">
+ <flag contact="disable"/>
+ </option>
+ <size memory="20M"/>
+ <visual>
+ <headlight diffuse=".55 .55 .55" ambient=".25 .25 .25" specular=".2 .2 .2"/>
+ <global offwidth="1280" offheight="720"/>
+ <map znear="0.02" zfar="80"/>
+ </visual>
+ <default>
+ <default class="panda">
+ <joint armature="0.1" damping="1" axis="0 0 1" range="-2.8973 2.8973"/>
+ <geom type="mesh" rgba="0.92 0.93 0.94 1" group="2" contype="0" conaffinity="0"/>
+ <motor ctrlrange="-87 87"/>
+ </default>
+ </default>
+ <asset>
+ <texture type="skybox" builtin="gradient" rgb1=".45 .5 .6" rgb2="0.12 0.12 0.16" width="10" height="10"/>
+ <texture type="2d" name="hall" builtin="checker" rgb1=".30 .30 .34" rgb2=".26 .26 .30" width="300" height="300"/>
+ <material name="hall" texture="hall" texrepeat="10 10"/>
+ <mesh name="link0_c" file="link0.stl"/>
+ <mesh name="link1_c" file="link1.stl"/>
+ <mesh name="link2_c" file="link2.stl"/>
+ <mesh name="link3_c" file="link3.stl"/>
+ <mesh name="link4_c" file="link4.stl"/>
+ <mesh name="link5_c0" file="link5_collision_0.obj"/>
+ <mesh name="link5_c1" file="link5_collision_1.obj"/>
+ <mesh name="link5_c2" file="link5_collision_2.obj"/>
+ <mesh name="link6_c" file="link6.stl"/>
+ <mesh name="link7_c" file="link7.stl"/>
+ </asset>
+ <worldbody>
+ <light pos="0 -3 9" dir="0 0.2 -1" diffuse="0.8 0.8 0.8" specular="0.2 0.2 0.2" castshadow="false"/>
+ <light pos="0 4 9" dir="0 -0.2 -1" diffuse="0.5 0.5 0.5" specular="0.1 0.1 0.1" castshadow="false"/>
+ <geom name="hall_floor" type="plane" size="14 14 0.1" pos="0 0 -0.002" material="hall" contype="0" conaffinity="0"/>
+ <geom name="court" type="box" size="3.35 7.3 0.001" pos="0 0 -0.001" rgba="0.13 0.45 0.30 1" contype="0" conaffinity="0"/>
+ <geom name="side_sL" type="box" size="0.02 6.7 0.001" pos="-2.59 0 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="side_sR" type="box" size="0.02 6.7 0.001" pos="2.59 0 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="side_dL" type="box" size="0.02 6.7 0.001" pos="-3.05 0 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="side_dR" type="box" size="0.02 6.7 0.001" pos="3.05 0 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="base_line-1" type="box" size="3.05 0.02 0.001" pos="0 -6.7 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="short_service-1" type="box" size="3.05 0.02 0.001" pos="0 -1.98 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="centre_line-1" type="box" size="0.02 2.3600000000000003 0.001" pos="0 -4.34 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="base_line1" type="box" size="3.05 0.02 0.001" pos="0 6.7 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="short_service1" type="box" size="3.05 0.02 0.001" pos="0 1.98 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="centre_line1" type="box" size="0.02 2.3600000000000003 0.001" pos="0 4.34 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="mk0" type="box" size="0.1 0.025 0.0015" pos="-2.73 -6 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk1" type="box" size="0.1 0.025 0.0015" pos="2.73 -6 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk2" type="box" size="0.1 0.025 0.0015" pos="-2.73 -5 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk3" type="box" size="0.1 0.025 0.0015" pos="2.73 -5 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk4" type="box" size="0.1 0.025 0.0015" pos="-2.73 -4 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk5" type="box" size="0.1 0.025 0.0015" pos="2.73 -4 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk6" type="box" size="0.1 0.025 0.0015" pos="-2.73 -3 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk7" type="box" size="0.1 0.025 0.0015" pos="2.73 -3 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk8" type="box" size="0.1 0.025 0.0015" pos="-2.73 -2 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk9" type="box" size="0.1 0.025 0.0015" pos="2.73 -2 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk10" type="box" size="0.1 0.025 0.0015" pos="-2.73 -1 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk11" type="box" size="0.1 0.025 0.0015" pos="2.73 -1 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk12" type="box" size="0.1 0.025 0.0015" pos="-2.73 0 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk13" type="box" size="0.1 0.025 0.0015" pos="2.73 0 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk14" type="box" size="0.1 0.025 0.0015" pos="-2.73 1 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk15" type="box" size="0.1 0.025 0.0015" pos="2.73 1 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk16" type="box" size="0.1 0.025 0.0015" pos="-2.73 2 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk17" type="box" size="0.1 0.025 0.0015" pos="2.73 2 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk18" type="box" size="0.1 0.025 0.0015" pos="-2.73 3 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk19" type="box" size="0.1 0.025 0.0015" pos="2.73 3 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk20" type="box" size="0.1 0.025 0.0015" pos="-2.73 4 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk21" type="box" size="0.1 0.025 0.0015" pos="2.73 4 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk22" type="box" size="0.1 0.025 0.0015" pos="-2.73 5 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk23" type="box" size="0.1 0.025 0.0015" pos="2.73 5 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk24" type="box" size="0.1 0.025 0.0015" pos="-2.73 6 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk25" type="box" size="0.1 0.025 0.0015" pos="2.73 6 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk26" type="box" size="0.025 0.1 0.0015" pos="-2 -6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk27" type="box" size="0.025 0.1 0.0015" pos="-2 6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk28" type="box" size="0.025 0.1 0.0015" pos="-1 -6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk29" type="box" size="0.025 0.1 0.0015" pos="-1 6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk30" type="box" size="0.025 0.1 0.0015" pos="1 -6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk31" type="box" size="0.025 0.1 0.0015" pos="1 6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk32" type="box" size="0.025 0.1 0.0015" pos="2 -6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk33" type="box" size="0.025 0.1 0.0015" pos="2 6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <!-- net: 0.76 m deep band whose top is 1.524 m (BWF Law 1.10), posts (1.55 m) at the doubles side lines -->
+ <geom name="net" type="box" size="3.05 0.004 0.38" pos="0 0 1.144" rgba="0.9 0.9 0.9 0.35" contype="0" conaffinity="0"/>
+ <geom name="net_tape" type="box" size="3.05 0.012 0.018" pos="0 0 1.506" rgba="1 1 1 1" contype="0" conaffinity="0"/>
+ <geom name="post_L" type="cylinder" size="0.025 0.775" pos="-3.05 0 0.775" rgba="0.2 0.2 0.2 1" contype="0" conaffinity="0"/>
+ <geom name="post_R" type="cylinder" size="0.025 0.775" pos="3.05 0 0.775" rgba="0.2 0.2 0.2 1" contype="0" conaffinity="0"/>
+
+ <body name="shuttle" mocap="true" pos="0 5 1">
+ <geom name="shuttle_cork" type="sphere" size="0.06" pos="0 0 0" rgba="1.0 0.45 0.05 1" contype="0" conaffinity="0"/>
+ <geom name="shuttle_skirt" type="ellipsoid" size="0.07 0.07 0.11" pos="0 0 -0.11" rgba="1 1 0.92 1" contype="0" conaffinity="0"/>
+ </body>
+
+ <body name="base" pos="0 0 0">
+ <inertial pos="0 0 0.3" mass="40" diaginertia="4 4 2"/>
+ <joint name="base_x" type="slide" axis="1 0 0" range="-3.3 3.3" damping="0"/>
+ <joint name="base_y" type="slide" axis="0 1 0" range="-7.6 -0.4" damping="0"/>
+ <geom name="platform" type="box" size="0.32 0.32 0.06" pos="0 0 0.07" rgba="0.22 0.22 0.26 1" contype="0" conaffinity="0"/>
+ <geom name="pedestal" type="cylinder" size="0.11 0.47" pos="0 0 0.53" rgba="0.3 0.3 0.34 1" contype="0" conaffinity="0"/>
+ <body name="link0" childclass="panda" pos="0 0 1.0" quat="0.7071068 0 0 0.7071068">
+ <inertial mass="0.629769" pos="-0.041018 -0.00014 0.049974"
+ fullinertia="0.00315 0.00388 0.004285 8.2904e-7 0.00015 8.2299e-6"/>
+ <geom name="link0_c" mesh="link0_c"/>
+ <body name="link1" pos="0 0 0.333">
+ <inertial mass="4.970684" pos="0.003875 0.002081 -0.04762"
+ fullinertia="0.70337 0.70661 0.0091170 -0.00013900 0.0067720 0.019169"/>
+ <joint name="joint1"/>
+ <geom name="link1_c" mesh="link1_c"/>
+ <body name="link2" quat="1 -1 0 0">
+ <inertial mass="0.646926" pos="-0.003141 -0.02872 0.003495"
+ fullinertia="0.0079620 2.8110e-2 2.5995e-2 -3.925e-3 1.0254e-2 7.04e-4"/>
+ <joint name="joint2" range="-1.7628 1.7628"/>
+ <geom name="link2_c" mesh="link2_c"/>
+ <body name="link3" pos="0 -0.316 0" quat="1 1 0 0">
+ <joint name="joint3"/>
+ <inertial mass="3.228604" pos="2.7518e-2 3.9252e-2 -6.6502e-2"
+ fullinertia="3.7242e-2 3.6155e-2 1.083e-2 -4.761e-3 -1.1396e-2 -1.2805e-2"/>
+ <geom name="link3_c" mesh="link3_c"/>
+ <body name="link4" pos="0.0825 0 0" quat="1 1 0 0">
+ <inertial mass="3.587895" pos="-5.317e-2 1.04419e-1 2.7454e-2"
+ fullinertia="2.5853e-2 1.9552e-2 2.8323e-2 7.796e-3 -1.332e-3 8.641e-3"/>
+ <joint name="joint4" range="-3.0718 -0.0698"/>
+ <geom name="link4_c" mesh="link4_c"/>
+ <body name="link5" pos="-0.0825 0.384 0" quat="1 -1 0 0">
+ <inertial mass="1.225946" pos="-1.1953e-2 4.1065e-2 -3.8437e-2"
+ fullinertia="3.5549e-2 2.9474e-2 8.627e-3 -2.117e-3 -4.037e-3 2.29e-4"/>
+ <joint name="joint5"/>
+ <geom name="link5_c0" mesh="link5_c0"/>
+ <geom name="link5_c1" mesh="link5_c1"/>
+ <geom name="link5_c2" mesh="link5_c2"/>
+ <body name="link6" quat="1 1 0 0">
+ <inertial mass="1.666555" pos="6.0149e-2 -1.4117e-2 -1.0517e-2"
+ fullinertia="1.964e-3 4.354e-3 5.433e-3 1.09e-4 -1.158e-3 3.41e-4"/>
+ <joint name="joint6" range="-0.0175 3.7525"/>
+ <geom name="link6_c" mesh="link6_c"/>
+ <body name="link7" pos="0.088 0 0" quat="1 1 0 0">
+ <inertial mass="7.35522e-01" pos="1.0517e-2 -4.252e-3 6.1597e-2"
+ fullinertia="1.2516e-2 1.0027e-2 4.815e-3 -4.28e-4 -1.196e-3 -7.41e-4"/>
+ <joint name="joint7"/>
+ <geom name="link7_c" mesh="link7_c"/>
+ <body name="racket" pos="0 0 0.107">
+ <!-- badminton racket: handle + shaft along the flange z axis, oval head; face normal = local +x -->
+ <geom name="racket_handle" type="capsule" fromto="0 0 0 0 0 0.20" size="0.016" mass="0.05" rgba="0.15 0.15 0.18 1" group="2"/>
+ <geom name="racket_shaft" type="capsule" fromto="0 0 0.20 0 0 0.44" size="0.005" mass="0.015" rgba="0.8 0.8 0.85 1" group="2"/>
+ <geom name="racket_frame" type="ellipsoid" pos="0 0 0.56" size="0.006 0.12 0.15" mass="0.02" rgba="0.1 0.3 0.85 1" group="2"/>
+ <geom name="racket_strings" type="ellipsoid" pos="0 0 0.56" size="0.008 0.11 0.14" mass="0.001" rgba="0.95 0.95 0.95 0.55" group="2"/>
+ <site name="racket_center" pos="0 0 0.56" size="0.005" rgba="1 1 1 1" group="4"/>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+
+ </body>
+ <!-- robot B: the same robot in B's frame, (x, y, z) -> (-x, -y, z) -->
+ <body name="side_b" quat="0 0 0 1">
+ <body name="base_b" pos="0 0 0">
+ <inertial pos="0 0 0.3" mass="40" diaginertia="4 4 2"/>
+ <joint name="base_x_b" type="slide" axis="1 0 0" range="-3.3 3.3" damping="0"/>
+ <joint name="base_y_b" type="slide" axis="0 1 0" range="-7.6 -0.4" damping="0"/>
+ <geom name="platform_b" type="box" size="0.32 0.32 0.06" pos="0 0 0.07" rgba="0.22 0.22 0.26 1" contype="0" conaffinity="0"/>
+ <geom name="pedestal_b" type="cylinder" size="0.11 0.47" pos="0 0 0.53" rgba="0.3 0.3 0.34 1" contype="0" conaffinity="0"/>
+ <body name="link0_b" childclass="panda" pos="0 0 1.0" quat="0.7071068 0 0 0.7071068">
+ <inertial mass="0.629769" pos="-0.041018 -0.00014 0.049974"
+ fullinertia="0.00315 0.00388 0.004285 8.2904e-7 0.00015 8.2299e-6"/>
+ <geom name="link0_c_b" mesh="link0_c"/>
+ <body name="link1_b" pos="0 0 0.333">
+ <inertial mass="4.970684" pos="0.003875 0.002081 -0.04762"
+ fullinertia="0.70337 0.70661 0.0091170 -0.00013900 0.0067720 0.019169"/>
+ <joint name="joint1_b"/>
+ <geom name="link1_c_b" mesh="link1_c"/>
+ <body name="link2_b" quat="1 -1 0 0">
+ <inertial mass="0.646926" pos="-0.003141 -0.02872 0.003495"
+ fullinertia="0.0079620 2.8110e-2 2.5995e-2 -3.925e-3 1.0254e-2 7.04e-4"/>
+ <joint name="joint2_b" range="-1.7628 1.7628"/>
+ <geom name="link2_c_b" mesh="link2_c"/>
+ <body name="link3_b" pos="0 -0.316 0" quat="1 1 0 0">
+ <joint name="joint3_b"/>
+ <inertial mass="3.228604" pos="2.7518e-2 3.9252e-2 -6.6502e-2"
+ fullinertia="3.7242e-2 3.6155e-2 1.083e-2 -4.761e-3 -1.1396e-2 -1.2805e-2"/>
+ <geom name="link3_c_b" mesh="link3_c"/>
+ <body name="link4_b" pos="0.0825 0 0" quat="1 1 0 0">
+ <inertial mass="3.587895" pos="-5.317e-2 1.04419e-1 2.7454e-2"
+ fullinertia="2.5853e-2 1.9552e-2 2.8323e-2 7.796e-3 -1.332e-3 8.641e-3"/>
+ <joint name="joint4_b" range="-3.0718 -0.0698"/>
+ <geom name="link4_c_b" mesh="link4_c"/>
+ <body name="link5_b" pos="-0.0825 0.384 0" quat="1 -1 0 0">
+ <inertial mass="1.225946" pos="-1.1953e-2 4.1065e-2 -3.8437e-2"
+ fullinertia="3.5549e-2 2.9474e-2 8.627e-3 -2.117e-3 -4.037e-3 2.29e-4"/>
+ <joint name="joint5_b"/>
+ <geom name="link5_c0_b" mesh="link5_c0"/>
+ <geom name="link5_c1_b" mesh="link5_c1"/>
+ <geom name="link5_c2_b" mesh="link5_c2"/>
+ <body name="link6_b" quat="1 1 0 0">
+ <inertial mass="1.666555" pos="6.0149e-2 -1.4117e-2 -1.0517e-2"
+ fullinertia="1.964e-3 4.354e-3 5.433e-3 1.09e-4 -1.158e-3 3.41e-4"/>
+ <joint name="joint6_b" range="-0.0175 3.7525"/>
+ <geom name="link6_c_b" mesh="link6_c"/>
+ <body name="link7_b" pos="0.088 0 0" quat="1 1 0 0">
+ <inertial mass="7.35522e-01" pos="1.0517e-2 -4.252e-3 6.1597e-2"
+ fullinertia="1.2516e-2 1.0027e-2 4.815e-3 -4.28e-4 -1.196e-3 -7.41e-4"/>
+ <joint name="joint7_b"/>
+ <geom name="link7_c_b" mesh="link7_c"/>
+ <body name="racket_b" pos="0 0 0.107">
+ <!-- badminton racket: handle + shaft along the flange z axis, oval head; face normal = local +x -->
+ <geom name="racket_handle_b" type="capsule" fromto="0 0 0 0 0 0.20" size="0.016" mass="0.05" rgba="0.15 0.15 0.18 1" group="2"/>
+ <geom name="racket_shaft_b" type="capsule" fromto="0 0 0.20 0 0 0.44" size="0.005" mass="0.015" rgba="0.8 0.8 0.85 1" group="2"/>
+ <geom name="racket_frame_b" type="ellipsoid" pos="0 0 0.56" size="0.006 0.12 0.15" mass="0.02" rgba="0.1 0.3 0.85 1" group="2"/>
+ <geom name="racket_strings_b" type="ellipsoid" pos="0 0 0.56" size="0.008 0.11 0.14" mass="0.001" rgba="0.95 0.95 0.95 0.55" group="2"/>
+ <site name="racket_center_b" pos="0 0 0.56" size="0.005" rgba="1 1 1 1" group="4"/>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+
+ </body>
+ </body>
+
+ </worldbody>
+ <actuator>
+ <motor name="motor_bx" joint="base_x" ctrlrange="-1500 1500"/>
+ <motor name="motor_by" joint="base_y" ctrlrange="-1500 1500"/>
+ <motor class="panda" name="motor1" joint="joint1"/>
+ <motor class="panda" name="motor2" joint="joint2"/>
+ <motor class="panda" name="motor3" joint="joint3"/>
+ <motor class="panda" name="motor4" joint="joint4"/>
+ <motor class="panda" name="motor5" joint="joint5" ctrlrange="-12 12"/>
+ <motor class="panda" name="motor6" joint="joint6" ctrlrange="-12 12"/>
+ <motor class="panda" name="motor7" joint="joint7" ctrlrange="-12 12"/>
+ </actuator>
+</mujoco>
diff --git a/scripts/roboolympics/shared/sports/badminton/sim/scene/bm_scene.xml b/scripts/roboolympics/shared/sports/badminton/sim/scene/bm_scene.xml
new file mode 100644
index 0000000000..27e658f778
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/badminton/sim/scene/bm_scene.xml
@@ -0,0 +1,181 @@
+<!--
+ Robot badminton scene for robot_coding_bench (generated; see the task README).
+ * World frame: floor z = 0, the court's long axis is y, the net is the plane y = 0 (top 1.524 m, BWF Law 1.10). The robot's half
+ is y < 0, the opponent's y > 0. Singles court |x| <= 2.59, |y| <= 6.70 (doubles side lines drawn at 3.05).
+ * Robot: a Franka Panda arm (MuJoCo Menagerie panda_nohand, Apache-2.0, assets/LICENSE.menagerie-franka) on a
+ 1.0 m pedestal whose base slides in x and y (two prismatic joints, a mobile base), holding a badminton racket
+ (head centre 0.56 m beyond the flange; face normal = racket local +x).
+ * The shuttlecock is NOT a MuJoCo body: it is integrated by bm.py (point mass, quadratic drag); the mocap body
+ `shuttle` only draws it (cork first along its velocity). MuJoCo contacts are disabled (nothing touches).
+-->
+<mujoco model="rcb_badminton">
+ <compiler angle="radian" meshdir="assets" autolimits="true"/>
+ <option integrator="implicitfast" timestep="0.001">
+ <flag contact="disable"/>
+ </option>
+ <size memory="20M"/>
+ <visual>
+ <headlight diffuse=".55 .55 .55" ambient=".25 .25 .25" specular=".2 .2 .2"/>
+ <global offwidth="1280" offheight="720"/>
+ <map znear="0.02" zfar="80"/>
+ </visual>
+ <default>
+ <default class="panda">
+ <joint armature="0.1" damping="1" axis="0 0 1" range="-2.8973 2.8973"/>
+ <geom type="mesh" rgba="0.92 0.93 0.94 1" group="2" contype="0" conaffinity="0"/>
+ <motor ctrlrange="-87 87"/>
+ </default>
+ </default>
+ <asset>
+ <texture type="skybox" builtin="gradient" rgb1=".45 .5 .6" rgb2="0.12 0.12 0.16" width="10" height="10"/>
+ <texture type="2d" name="hall" builtin="checker" rgb1=".30 .30 .34" rgb2=".26 .26 .30" width="300" height="300"/>
+ <material name="hall" texture="hall" texrepeat="10 10"/>
+ <mesh name="link0_c" file="link0.stl"/>
+ <mesh name="link1_c" file="link1.stl"/>
+ <mesh name="link2_c" file="link2.stl"/>
+ <mesh name="link3_c" file="link3.stl"/>
+ <mesh name="link4_c" file="link4.stl"/>
+ <mesh name="link5_c0" file="link5_collision_0.obj"/>
+ <mesh name="link5_c1" file="link5_collision_1.obj"/>
+ <mesh name="link5_c2" file="link5_collision_2.obj"/>
+ <mesh name="link6_c" file="link6.stl"/>
+ <mesh name="link7_c" file="link7.stl"/>
+ </asset>
+ <worldbody>
+ <light pos="0 -3 9" dir="0 0.2 -1" diffuse="0.8 0.8 0.8" specular="0.2 0.2 0.2" castshadow="false"/>
+ <light pos="0 4 9" dir="0 -0.2 -1" diffuse="0.5 0.5 0.5" specular="0.1 0.1 0.1" castshadow="false"/>
+ <geom name="hall_floor" type="plane" size="14 14 0.1" pos="0 0 -0.002" material="hall" contype="0" conaffinity="0"/>
+ <geom name="court" type="box" size="3.35 7.3 0.001" pos="0 0 -0.001" rgba="0.13 0.45 0.30 1" contype="0" conaffinity="0"/>
+ <geom name="side_sL" type="box" size="0.02 6.7 0.001" pos="-2.59 0 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="side_sR" type="box" size="0.02 6.7 0.001" pos="2.59 0 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="side_dL" type="box" size="0.02 6.7 0.001" pos="-3.05 0 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="side_dR" type="box" size="0.02 6.7 0.001" pos="3.05 0 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="base_line-1" type="box" size="3.05 0.02 0.001" pos="0 -6.7 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="short_service-1" type="box" size="3.05 0.02 0.001" pos="0 -1.98 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="centre_line-1" type="box" size="0.02 2.3600000000000003 0.001" pos="0 -4.34 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="base_line1" type="box" size="3.05 0.02 0.001" pos="0 6.7 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="short_service1" type="box" size="3.05 0.02 0.001" pos="0 1.98 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="centre_line1" type="box" size="0.02 2.3600000000000003 0.001" pos="0 4.34 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="mk0" type="box" size="0.1 0.025 0.0015" pos="-2.73 -6 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk1" type="box" size="0.1 0.025 0.0015" pos="2.73 -6 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk2" type="box" size="0.1 0.025 0.0015" pos="-2.73 -5 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk3" type="box" size="0.1 0.025 0.0015" pos="2.73 -5 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk4" type="box" size="0.1 0.025 0.0015" pos="-2.73 -4 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk5" type="box" size="0.1 0.025 0.0015" pos="2.73 -4 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk6" type="box" size="0.1 0.025 0.0015" pos="-2.73 -3 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk7" type="box" size="0.1 0.025 0.0015" pos="2.73 -3 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk8" type="box" size="0.1 0.025 0.0015" pos="-2.73 -2 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk9" type="box" size="0.1 0.025 0.0015" pos="2.73 -2 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk10" type="box" size="0.1 0.025 0.0015" pos="-2.73 -1 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk11" type="box" size="0.1 0.025 0.0015" pos="2.73 -1 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk12" type="box" size="0.1 0.025 0.0015" pos="-2.73 0 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk13" type="box" size="0.1 0.025 0.0015" pos="2.73 0 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk14" type="box" size="0.1 0.025 0.0015" pos="-2.73 1 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk15" type="box" size="0.1 0.025 0.0015" pos="2.73 1 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk16" type="box" size="0.1 0.025 0.0015" pos="-2.73 2 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk17" type="box" size="0.1 0.025 0.0015" pos="2.73 2 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk18" type="box" size="0.1 0.025 0.0015" pos="-2.73 3 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk19" type="box" size="0.1 0.025 0.0015" pos="2.73 3 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk20" type="box" size="0.1 0.025 0.0015" pos="-2.73 4 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk21" type="box" size="0.1 0.025 0.0015" pos="2.73 4 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk22" type="box" size="0.1 0.025 0.0015" pos="-2.73 5 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk23" type="box" size="0.1 0.025 0.0015" pos="2.73 5 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk24" type="box" size="0.1 0.025 0.0015" pos="-2.73 6 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk25" type="box" size="0.1 0.025 0.0015" pos="2.73 6 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk26" type="box" size="0.025 0.1 0.0015" pos="-2 -6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk27" type="box" size="0.025 0.1 0.0015" pos="-2 6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk28" type="box" size="0.025 0.1 0.0015" pos="-1 -6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk29" type="box" size="0.025 0.1 0.0015" pos="-1 6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk30" type="box" size="0.025 0.1 0.0015" pos="1 -6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk31" type="box" size="0.025 0.1 0.0015" pos="1 6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk32" type="box" size="0.025 0.1 0.0015" pos="2 -6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk33" type="box" size="0.025 0.1 0.0015" pos="2 6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <!-- net: 0.76 m deep band whose top is 1.524 m (BWF Law 1.10), posts (1.55 m) at the doubles side lines -->
+ <geom name="net" type="box" size="3.05 0.004 0.38" pos="0 0 1.144" rgba="0.9 0.9 0.9 0.35" contype="0" conaffinity="0"/>
+ <geom name="net_tape" type="box" size="3.05 0.012 0.018" pos="0 0 1.506" rgba="1 1 1 1" contype="0" conaffinity="0"/>
+ <geom name="post_L" type="cylinder" size="0.025 0.775" pos="-3.05 0 0.775" rgba="0.2 0.2 0.2 1" contype="0" conaffinity="0"/>
+ <geom name="post_R" type="cylinder" size="0.025 0.775" pos="3.05 0 0.775" rgba="0.2 0.2 0.2 1" contype="0" conaffinity="0"/>
+
+ <body name="shuttle" mocap="true" pos="0 5 1">
+ <geom name="shuttle_cork" type="sphere" size="0.06" pos="0 0 0" rgba="1.0 0.45 0.05 1" contype="0" conaffinity="0"/>
+ <geom name="shuttle_skirt" type="ellipsoid" size="0.07 0.07 0.11" pos="0 0 -0.11" rgba="1 1 0.92 1" contype="0" conaffinity="0"/>
+ </body>
+
+ <body name="base" pos="0 0 0">
+ <inertial pos="0 0 0.3" mass="40" diaginertia="4 4 2"/>
+ <joint name="base_x" type="slide" axis="1 0 0" range="-3.3 3.3" damping="0"/>
+ <joint name="base_y" type="slide" axis="0 1 0" range="-7.6 -0.4" damping="0"/>
+ <geom name="platform" type="box" size="0.32 0.32 0.06" pos="0 0 0.07" rgba="0.22 0.22 0.26 1" contype="0" conaffinity="0"/>
+ <geom name="pedestal" type="cylinder" size="0.11 0.47" pos="0 0 0.53" rgba="0.3 0.3 0.34 1" contype="0" conaffinity="0"/>
+ <body name="link0" childclass="panda" pos="0 0 1.0" quat="0.7071068 0 0 0.7071068">
+ <inertial mass="0.629769" pos="-0.041018 -0.00014 0.049974"
+ fullinertia="0.00315 0.00388 0.004285 8.2904e-7 0.00015 8.2299e-6"/>
+ <geom name="link0_c" mesh="link0_c"/>
+ <body name="link1" pos="0 0 0.333">
+ <inertial mass="4.970684" pos="0.003875 0.002081 -0.04762"
+ fullinertia="0.70337 0.70661 0.0091170 -0.00013900 0.0067720 0.019169"/>
+ <joint name="joint1"/>
+ <geom name="link1_c" mesh="link1_c"/>
+ <body name="link2" quat="1 -1 0 0">
+ <inertial mass="0.646926" pos="-0.003141 -0.02872 0.003495"
+ fullinertia="0.0079620 2.8110e-2 2.5995e-2 -3.925e-3 1.0254e-2 7.04e-4"/>
+ <joint name="joint2" range="-1.7628 1.7628"/>
+ <geom name="link2_c" mesh="link2_c"/>
+ <body name="link3" pos="0 -0.316 0" quat="1 1 0 0">
+ <joint name="joint3"/>
+ <inertial mass="3.228604" pos="2.7518e-2 3.9252e-2 -6.6502e-2"
+ fullinertia="3.7242e-2 3.6155e-2 1.083e-2 -4.761e-3 -1.1396e-2 -1.2805e-2"/>
+ <geom name="link3_c" mesh="link3_c"/>
+ <body name="link4" pos="0.0825 0 0" quat="1 1 0 0">
+ <inertial mass="3.587895" pos="-5.317e-2 1.04419e-1 2.7454e-2"
+ fullinertia="2.5853e-2 1.9552e-2 2.8323e-2 7.796e-3 -1.332e-3 8.641e-3"/>
+ <joint name="joint4" range="-3.0718 -0.0698"/>
+ <geom name="link4_c" mesh="link4_c"/>
+ <body name="link5" pos="-0.0825 0.384 0" quat="1 -1 0 0">
+ <inertial mass="1.225946" pos="-1.1953e-2 4.1065e-2 -3.8437e-2"
+ fullinertia="3.5549e-2 2.9474e-2 8.627e-3 -2.117e-3 -4.037e-3 2.29e-4"/>
+ <joint name="joint5"/>
+ <geom name="link5_c0" mesh="link5_c0"/>
+ <geom name="link5_c1" mesh="link5_c1"/>
+ <geom name="link5_c2" mesh="link5_c2"/>
+ <body name="link6" quat="1 1 0 0">
+ <inertial mass="1.666555" pos="6.0149e-2 -1.4117e-2 -1.0517e-2"
+ fullinertia="1.964e-3 4.354e-3 5.433e-3 1.09e-4 -1.158e-3 3.41e-4"/>
+ <joint name="joint6" range="-0.0175 3.7525"/>
+ <geom name="link6_c" mesh="link6_c"/>
+ <body name="link7" pos="0.088 0 0" quat="1 1 0 0">
+ <inertial mass="7.35522e-01" pos="1.0517e-2 -4.252e-3 6.1597e-2"
+ fullinertia="1.2516e-2 1.0027e-2 4.815e-3 -4.28e-4 -1.196e-3 -7.41e-4"/>
+ <joint name="joint7"/>
+ <geom name="link7_c" mesh="link7_c"/>
+ <body name="racket" pos="0 0 0.107">
+ <!-- badminton racket: handle + shaft along the flange z axis, oval head; face normal = local +x -->
+ <geom name="racket_handle" type="capsule" fromto="0 0 0 0 0 0.20" size="0.016" mass="0.05" rgba="0.15 0.15 0.18 1" group="2"/>
+ <geom name="racket_shaft" type="capsule" fromto="0 0 0.20 0 0 0.44" size="0.005" mass="0.015" rgba="0.8 0.8 0.85 1" group="2"/>
+ <geom name="racket_frame" type="ellipsoid" pos="0 0 0.56" size="0.006 0.12 0.15" mass="0.02" rgba="0.1 0.3 0.85 1" group="2"/>
+ <geom name="racket_strings" type="ellipsoid" pos="0 0 0.56" size="0.008 0.11 0.14" mass="0.001" rgba="0.95 0.95 0.95 0.55" group="2"/>
+ <site name="racket_center" pos="0 0 0.56" size="0.005" rgba="1 1 1 1" group="4"/>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+
+ </body>
+ </worldbody>
+ <actuator>
+ <motor name="motor_bx" joint="base_x" ctrlrange="-1500 1500"/>
+ <motor name="motor_by" joint="base_y" ctrlrange="-1500 1500"/>
+ <motor class="panda" name="motor1" joint="joint1"/>
+ <motor class="panda" name="motor2" joint="joint2"/>
+ <motor class="panda" name="motor3" joint="joint3"/>
+ <motor class="panda" name="motor4" joint="joint4"/>
+ <motor class="panda" name="motor5" joint="joint5" ctrlrange="-12 12"/>
+ <motor class="panda" name="motor6" joint="joint6" ctrlrange="-12 12"/>
+ <motor class="panda" name="motor7" joint="joint7" ctrlrange="-12 12"/>
+ </actuator>
+</mujoco>
diff --git a/scripts/roboolympics/shared/sports/badminton/sim/scene/mk_duel_scene.py b/scripts/roboolympics/shared/sports/badminton/sim/scene/mk_duel_scene.py
new file mode 100644
index 0000000000..e9e85bf070
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/badminton/sim/scene/mk_duel_scene.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python3
+"""Write the two-robot badminton scene of the duel's renderer (bm_duel.xml, next to this file) from the match scene.
+
+The duel's physics runs each robot in its own copy of the single-player model (scene/bm_scene.xml; see
+duel/environment/sim/bduel.py); this scene only DRAWS both: robot A as in bm_scene.xml, robot B as a copy of the same
+robot body (every name suffixed `_b`) inside a body rotated 180 degrees about z, so that B's joint values are those of
+B's own frame (x, y, z) -> (-x, -y, z). No actuators are copied (the renderer only sets joint positions).
+
+ python3 sports/badminton/sim/scene/mk_duel_scene.py (then tools/generate.py badminton)
+
+The header written into bm_duel.xml keeps the wording of the legacy script (scripts/olympiad/badminton/), so the
+scene file stays byte-identical to the one the legacy duel recordings were made with.
+"""
+import re
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+SRC = HERE / "bm_scene.xml"
+OUT = HERE / "bm_duel.xml"
+
+
+def robot_block(xml: str) -> str:
+ """The <body name="base"> element (the whole robot), found by balancing <body> tags."""
+ i = xml.index('<body name="base"')
+ depth, j = 0, i
+ for m in re.finditer(r"<body\b[^>]*?(/?)>|</body>", xml[i:]):
+ if m.group(0).startswith("</"):
+ depth -= 1
+ elif not m.group(1):
+ depth += 1
+ if depth == 0:
+ j = i + m.end()
+ break
+ return xml[i:j]
+
+
+def main():
+ xml = SRC.read_text()
+ block = robot_block(xml)
+ copy = re.sub(r'\bname="([^"]+)"', r'name="\1_b"', block)
+ side_b = ('\n <!-- robot B: the same robot in B\'s frame, (x, y, z) -> (-x, -y, z) -->\n'
+ ' <body name="side_b" quat="0 0 0 1">\n ' + copy + '\n </body>\n')
+ out = xml.replace(block, block + side_b)
+ out = out.replace('<mujoco model="rcb_badminton">', '<mujoco model="rcb_badminton_duel">')
+ out = re.sub(r"<!--.*?-->", "", out, count=1, flags=re.S)
+ header = ("<!--\n Robot badminton DUEL scene (render only), generated by scripts/olympiad/badminton/mk_duel_scene.py from\n"
+ " bm_scene.xml: robot A as in the match scene; robot B (names *_b, identical) the same robot in\n"
+ " a body rotated 180 degrees about z. The physics runs each robot in its own copy of bm_scene.xml (bduel.py).\n-->\n")
+ OUT.parent.mkdir(parents=True, exist_ok=True)
+ OUT.write_text(header + out.lstrip())
+ print("wrote", OUT)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/roboolympics/shared/sports/badminton/sim/wc.py b/scripts/roboolympics/shared/sports/badminton/sim/wc.py
new file mode 100644
index 0000000000..eeaa2f50d9
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/badminton/sim/wc.py
@@ -0,0 +1,311 @@
+"""Wall-clock helpers for the badminton match service: exact match snapshots, the stroke-planner process and the
+reference advisor (oracle mode only).
+
+Why a planner process. An `act` is planned by the stroke controller (`bm.Match.plan_racket`: deterministic multi-start
+IK, up to three candidate solutions, five robot-only twin rehearsals each), 0.15-0.26 s of CPU. Done inside the sim
+thread it would stall the world by up to 26 control steps at x1 and 2.6 at x10, beyond the 100 ms completion-lag
+bound. So the service plans OUTSIDE the sim thread and its process, without changing what the plan is:
+
+ * an act queued while the match is at step k_q takes effect at the fixed step k_e = k_q + LEAD_STEPS
+ (LEAD_STEPS = ceil(PLAN_LEAD_S / wall seconds per step), a constant of the task);
+ * at queue time the service pickles the whole match (an exact copy, MjData included; the MjModel is shared by
+ reference) and sends it to the planner process; the planner advances the copy to k_e with the command in force
+ (installing any earlier act that takes effect before k_e, from its own earlier result) and plans the stroke there,
+ exactly as `Match.rt_act` at k_e would;
+ * at k_e the sim thread compares the live state with the planner's state key at k_e and installs the plan (the
+ same attribute changes as `rt_act`). The result is bit-identical to calling `rt_act` at k_e, which is what the
+ fresh-process replay does. A key mismatch (never seen) falls back to `rt_act` in the sim thread and is counted
+ (`plan_mismatch`). If the plan is not back by k_e the sim thread waits for it; the lateness is recorded.
+
+Wire format: length-prefixed pickles over the worker's stdin/stdout (`_send` / `_recv`).
+"""
+from __future__ import annotations
+
+import hashlib
+import io
+import os
+import pickle
+import select
+import struct
+import subprocess
+import sys
+import threading
+import time
+from pathlib import Path
+
+import numpy as np
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+REVISION = "wallclock-4" # 4: the players serve (bm.Match.toss)
+SOURCE_FILES = ("bm.py", "wc.py")
+
+
+def source_sha() -> str:
+ """Fingerprint of everything that decides the match (engine, planning/installation, scene)."""
+ root = Path(HERE)
+ h = hashlib.sha256()
+ names = list(SOURCE_FILES) + [str(p.relative_to(root)) for p in sorted((root / "scene").rglob("*")) if p.is_file()]
+ for name in names:
+ h.update(name.encode()); h.update((root / name).read_bytes())
+ return h.hexdigest()
+
+
+# ---------------------------------------------------------------------------------------------- pipes
+def _send(f, obj, deadline=None) -> None:
+ b = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)
+ packet = struct.pack("<Q", len(b)) + b
+ if deadline is None:
+ view = memoryview(packet)
+ while len(view):
+ n = os.write(f.fileno(), view[:1 << 20])
+ view = view[n:]
+ return
+ offset = 0
+ while offset < len(packet):
+ remaining = deadline - time.monotonic()
+ if remaining <= 0 or not select.select([], [f], [], remaining)[1]:
+ raise TimeoutError("worker request timed out")
+ offset += os.write(f.fileno(), packet[offset:offset + 65536])
+
+
+def _read_exact(f, n, deadline=None):
+ chunks = []
+ while n:
+ if deadline is not None:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0 or not select.select([f], [], [], remaining)[0]:
+ raise TimeoutError("worker response timed out")
+ chunk = os.read(f.fileno(), min(n, 1 << 20))
+ if not chunk:
+ raise EOFError("worker closed its pipe")
+ chunks.append(chunk)
+ n -= len(chunk)
+ return b"".join(chunks)
+
+
+def _recv(f, deadline=None):
+ n = struct.unpack("<Q", _read_exact(f, 8, deadline))[0]
+ return pickle.loads(_read_exact(f, n, deadline))
+
+
+# ---------------------------------------------------------------------------------------------- snapshots
+class _Pickler(pickle.Pickler):
+ def persistent_id(self, obj):
+ import mujoco as mj
+ return "MODEL" if isinstance(obj, mj.MjModel) else None
+
+
+class _Unpickler(pickle.Unpickler):
+ def __init__(self, f, model):
+ super().__init__(f)
+ self.model = model
+
+ def persistent_load(self, pid):
+ if pid != "MODEL":
+ raise pickle.UnpicklingError(pid)
+ return self.model
+
+
+def snapshot(m) -> bytes:
+ """Exact copy of the match state for planning. Not copied: the MjModel (shared by reference), the scratch twin, and
+ the joint-target history except its last two entries (the planner reads only those, for the target velocity)."""
+ tw = m.__dict__.pop("_twin", None)
+ acts = m.s._actions
+ m.s._actions = acts[-2:]
+ try:
+ f = io.BytesIO()
+ _Pickler(f, protocol=pickle.HIGHEST_PROTOCOL).dump(m)
+ return f.getvalue()
+ finally:
+ m._twin = tw
+ m.s._actions = acts
+
+
+def restore(b: bytes, model):
+ m = _Unpickler(io.BytesIO(b), model).load()
+ m._twin = None
+ return m
+
+
+def state_key(m) -> str:
+ """Everything the stroke planner reads, hashed: physics state, command, leg and shot counters."""
+ h = hashlib.sha256()
+ h.update(m.s.state_sha().encode())
+ h.update(repr((m.k, m.plan_j, len(m.plan), m.n_our_legs, len(m.points), len(m.legs), m.leg.get("launch"),
+ m.leg.get("state"), m.done)).encode())
+ h.update(np.ascontiguousarray(m.s.target, dtype=np.float64).tobytes())
+ if len(m.s._actions) >= 2:
+ h.update(np.ascontiguousarray(m.s._actions[-2], dtype=np.float64).tobytes())
+ qa = getattr(m, "_q_hit_active", None)
+ if qa is not None:
+ h.update(np.ascontiguousarray(qa, dtype=np.float64).tobytes())
+ if m.plan_j < len(m.plan):
+ h.update(np.ascontiguousarray(np.asarray(m.plan[m.plan_j:]), dtype=np.float64).tobytes())
+ return h.hexdigest()
+
+
+# ---------------------------------------------------------------------------------------------- plan / install
+def plan_on(m, dec: dict) -> dict:
+ """What `Match.rt_act` / `rt_clear` would do at the current step of m (a copy), as an installable result."""
+ if dec["type"] == "none":
+ return {"type": "none"}
+ import bm
+ T = float(dec["t"])
+ t_hit = (m.k - m.leg["launch"]) * bm.CONTROL_DT + T
+ ik_seed = getattr(m, "_q_hit_active", None) if m.plan_j < len(m.plan) else None
+ m._ik_seed = ik_seed
+ plan, info = m.plan_racket(t_hit, dec["pos"], dec["normal"], dec["vel"])
+ q_hit = info.pop("_q_hit", None)
+ info["T_from_now"] = round(T, 4)
+ return {"type": "act", "plan": plan, "q_hit": q_hit, "info": info, "ik_seed": ik_seed,
+ "swing_last": getattr(m, "_swing_last", None)}
+
+
+def install(m, res: dict) -> dict | None:
+ """Apply a planned result to m with exactly the attribute changes of `Match.rt_act` (or `rt_clear`)."""
+ if res["type"] == "none":
+ m.rt_clear()
+ return None
+ m._ik_seed = res["ik_seed"]
+ if res["swing_last"] is not None:
+ m._swing_last = res["swing_last"]
+ info = res["info"]
+ if res["plan"]:
+ m.plan, m.plan_j = res["plan"], 0
+ m._q_hit_active = res["q_hit"]
+ m.shots.append({"k": m.k, "leg": m.n_our_legs, **info})
+ m._last_act = info
+ return info
+
+
+def apply_inline(m, dec: dict) -> dict | None:
+ """The reference semantics (also the replay's): plan and apply at the current step."""
+ if dec["type"] == "none":
+ m.rt_clear()
+ return None
+ return m.rt_act(dec["t"], dec["pos"], dec["normal"], dec["vel"])
+
+
+# ---------------------------------------------------------------------------------------------- worker process
+def _worker(conn_in, conn_out) -> None:
+ import bm
+ model = bm.Phys().m
+ cache: dict = {} # act_id -> (k_e, result), the planner's earlier results (for later forks)
+ _send(conn_out, "ready")
+ while True:
+ try:
+ job = _recv(conn_in)
+ except EOFError:
+ return
+ t0 = time.monotonic()
+ try:
+ m = restore(job["snap"], model)
+ t1 = time.monotonic()
+ if job["op"] == "plan":
+ k_e = int(job["k_e"])
+ pend = [(cache[i][0], i) for i in job.get("pending", []) if i in cache]
+ applied = set()
+ status = "ok"
+ while True:
+ for ke, i in pend:
+ if ke == m.k and i not in applied and cache[i][1] is not None:
+ install(m, cache[i][1]); applied.add(i)
+ if m.k >= k_e:
+ break
+ n0 = len(m.points)
+ m.rt_advance(1)
+ if len(m.points) > n0 or m.done:
+ status = "dropped"
+ break
+ t2 = time.monotonic()
+ out = {"act_id": job["act_id"], "status": status, "fork_steps": int(m.k - job["k_q"]),
+ "unpickle_ms": round((t1 - t0) * 1e3, 2), "fork_ms": round((t2 - t1) * 1e3, 2)}
+ if status == "ok":
+ out["key"] = state_key(m)
+ res = plan_on(m, job["dec"])
+ out["res"] = res
+ cache[job["act_id"]] = (k_e, res)
+ else:
+ cache[job["act_id"]] = (k_e, None)
+ out["plan_ms"] = round((time.monotonic() - t2) * 1e3, 2)
+ for i in sorted(cache)[:-64]:
+ cache.pop(i)
+ elif job["op"] == "advise":
+ import oracle_ref
+ out = oracle_ref.advise(m)
+ out["unpickle_ms"] = round((t1 - t0) * 1e3, 2)
+ out["advice_ms"] = round((time.monotonic() - t1) * 1e3, 2)
+ else:
+ raise ValueError(f"unknown job {job.get('op')}")
+ out["worker_ms"] = round((time.monotonic() - t0) * 1e3, 2)
+ _send(conn_out, ("ok", out))
+ except Exception as exc: # noqa: BLE001
+ import traceback
+ traceback.print_exc()
+ _send(conn_out, ("error", {"act_id": job.get("act_id"), "error": repr(exc)[:300]}))
+
+
+class Worker:
+ """A planner / advisor child process. `submit` is asynchronous (results arrive through `on_result` from a reader
+ thread); `call` is synchronous (one request at a time)."""
+
+ def __init__(self, name: str, on_result=None):
+ self.name = name
+ self.proc = subprocess.Popen([sys.executable, os.path.abspath(__file__), "worker"], stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE, cwd=HERE, env=dict(os.environ))
+ self.fin, self.fout = self.proc.stdout, self.proc.stdin
+ if _recv(self.fin, time.monotonic() + 120) != "ready":
+ raise RuntimeError(f"{name} worker handshake failed")
+ self.on_result = on_result
+ self.lock = threading.Lock()
+ self.jobs: "list" = []
+ self.cv = threading.Condition()
+ if on_result is not None:
+ threading.Thread(target=self._sender, daemon=True).start()
+ threading.Thread(target=self._reader, daemon=True).start()
+
+ def submit(self, job: dict) -> None:
+ with self.cv:
+ self.jobs.append(job)
+ self.cv.notify()
+
+ def _sender(self):
+ while True:
+ with self.cv:
+ while not self.jobs:
+ self.cv.wait()
+ job = self.jobs.pop(0)
+ try:
+ _send(self.fout, job)
+ except Exception as exc: # noqa: BLE001
+ self.on_result(("error", {"act_id": job.get("act_id"), "error": repr(exc)[:300]}))
+
+ def _reader(self):
+ while True:
+ try:
+ msg = _recv(self.fin)
+ except Exception as exc: # noqa: BLE001
+ self.on_result(("dead", {"error": repr(exc)[:300]}))
+ return
+ self.on_result(msg)
+
+ def call(self, job: dict, timeout_s: float):
+ deadline = time.monotonic() + timeout_s
+ if not self.lock.acquire(timeout=timeout_s):
+ raise TimeoutError(f"{self.name} worker busy")
+ try:
+ _send(self.fout, job, deadline)
+ st, out = _recv(self.fin, deadline)
+ if st != "ok":
+ raise RuntimeError(out.get("error"))
+ return out
+ finally:
+ self.lock.release()
+
+
+if __name__ == "__main__" and sys.argv[1:] == ["worker"]:
+ sys.path.insert(0, HERE)
+ proto_out = os.fdopen(os.dup(1), "wb") # the protocol keeps the real stdout; anything printed goes to stderr
+ os.dup2(2, 1)
+ sys.stdout = sys.stderr
+ _worker(sys.stdin.buffer, proto_out)
diff --git a/scripts/roboolympics/shared/sports/badminton/sport.toml b/scripts/roboolympics/shared/sports/badminton/sport.toml
new file mode 100644
index 0000000000..8be6f85df7
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/badminton/sport.toml
@@ -0,0 +1,200 @@
+# badminton: robot singles badminton in real time (docs/framework_zh.md §4.2, §8). Migrated from the legacy tree in
+# stage 3 (scripts/olympiad/badminton, scripts/olympiad/shared/badminton; sim/bm.py: court, shuttle, robot, stroke
+# controller, scripted opponent, referee; sim/bduel.py: the two-robot match; sim/wc.py: the legacy planner's exact
+# snapshots and plan installation). The physics (shuttle drag, racket contact law, robots) is the legacy one; the
+# serve is not: since 2026-10-07 the players' robots serve by the BWF service laws (D2, D4, D6, D7; README), so the
+# legacy machine-serve recordings no longer apply and were retired from the golden set. The format names keep the
+# legacy task names (badminton-match-wallclock-program-standard, badminton-duel-wallclock-program-standard).
+
+[sport]
+name = "badminton"
+title = "Robot badminton"
+summary = "robot singles badminton on a regulation court in real time (slowed down): a Franka Panda arm with a racket on an x-y sliding base, a point-mass shuttle with high quadratic drag (terminal speed 6.8 m/s) and no bounce, a racket contact law; first to 5 points, rally scoring; the players' robots serve (the rally winner serves next): the server tosses the shuttle (from rest or rising up to 0.5 m) at a point it chooses and hits it underhand, below 1.15 m, into the diagonal service court; format match-wallclock: you against a scripted computer opponent (levels 1-2, `game spec` match.opponent_level), format duel-wallclock: two players"
+protocol = "realtime"
+revision = "badminton-wallclock-5+duel-7+core-0.2" # bump on any change that alters play (4/6: the players serve; 5/7: the players' images draw the arms with the Franka Panda's 25k visual meshes)
+physics = "mujoco (robots, PD-controlled joints at 1 ms) + a point-mass shuttle with quadratic drag integrated at 1 ms (sim/bm.py)"
+image = "ghcr.io/mll-lab-nu/eai-olympiad:0.1.0"
+status = "sport"
+publish = true
+category = "robotics-sports-arena"
+
+[rulebook]
+name = "BWF Laws of Badminton (BWF Statutes, Section 4.1, version 5.0)"
+version = "2025-04-26"
+url = "https://extranet.bwf.sport/docs/document-system/81/1466/1470/Section%204.1%20-%20Laws%20of%20Badminton%20-%2026%20April%202025%20V5.0%20(2)%20.pdf"
+
+[[deviations]]
+id = "D1"
+rule = "7"
+text = "one short game: first to 5 points, from 4-4 a two-point lead is needed, at most 7 (6-6: the next point wins) instead of best of three games to 21 (cap 30); the match also ends after 300 hits (both sides) or 40 points played (lets included): the player ahead wins, at equal points the winner of the last point"
+affects_result = true
+[[deviations]]
+id = "D2"
+rule = "9.1.5-9.1.8"
+text = "the robot has no free hand to hold and drop the shuttle: the server tosses it with the command toss {pos: [x, y, z], height: H} (the common racket-sport toss, docs/conventions/racket_serve_zh.md): when the command takes effect the shuttle appears at that point (0.5-1.8 m high, within 1.0 m horizontally of the server's base, on its half) and is released from rest (H = 0) or projected straight up to rise H (at most 0.5 m; the Laws do not forbid a small toss); until then it is held beside the server. The toss has no spin (a point mass has none, Law 9.1.5). Judged: the server's racket must hit it (a miss is a fault, Law 9.1.8), with the shuttle below 1.15 m at the hit (Law 9.1.6, judged at the shuttle's point: it has no size) and leaving the racket upwards (Law 9.1). Not judged: the racket hitting the base of the shuttle first and moving forwards throughout the service (Laws 9.1.5, 9.1.7)"
+affects_result = true
+[[deviations]]
+id = "D3"
+rule = "13.3-13.4"
+text = "the shuttle is a point mass: a crossing of the net plane below the net top (between the posts) is a fault of the hitter; touching the net or reaching over it is not judged; a racket meets the shuttle only on its own half and only when it is that player's turn (no double hits)"
+affects_result = true
+[[deviations]]
+id = "D4"
+rule = "9.1.3-9.1.4"
+text = "before every serve the referee puts both robots at rest in the ready pose at a fixed spot in their service courts (diagonally opposite: the right courts when the server's score is even, Law 10.1): x = +0.3 (right court) or -0.3 (left court), y = -4.0 in each robot's frame; the spot is the robot's home for the point (where its base returns between strokes). Standing still (Law 9.1.4) is judged on the base: a base more than 5 cm from its spot before the serve is delivered (hit, or faulted) is that player's fault; both at once: a let (Law 14.2.2). The base moves within |x| <= 3.25, -7.5 <= y <= -0.5 at up to 6 m/s and 20 m/s^2"
+affects_result = true
+[[deviations]]
+id = "D5"
+rule = "-"
+text = "the last resort of the no-draw rule (equal points at the match limit and no point won) is not from the rulebook: the player who received first wins (format match-wallclock: the opponent)"
+affects_result = true
+[[deviations]]
+id = "D6"
+rule = "9.1.1, 16.6-16.7"
+text = "undue delay has a fixed limit: the server must toss the shuttle within 3 s after the receiver is ready (1 s after play resumes, Law 9.4), else it is a service fault (the receiver's point); a player's third such fault disqualifies it (it loses the match) instead of the umpire's warning and the referee's discretion (Laws 16.7.1-16.7.2)"
+affects_result = true
+[[deviations]]
+id = "D7"
+rule = "6"
+text = "no toss: format duel-wallclock: the runner plays both orders of the first server (match.first_server); format match-wallclock: you serve the first point"
+affects_result = true
+
+[formats.match-wallclock] # one model seat against the scripted opponent inside the world (bm.Match)
+seats = ["A"]
+opponent = true # success = winning a valid match (core/grading.py), as in the legacy task
+levels = [1, 2] # the opponent level (RCB_LEVEL; default 1)
+[formats.duel-wallclock] # two seats (bduel.World), mirrored: each plays in its own frame
+seats = ["A", "B"]
+first = ["A", "B"] # the first server (Law 6, D7); the runner plays both orders
+
+[modes]
+action_levels = ["high", "low"] # high: the racket command `act` (lowered to joint targets); low: joint targets
+plays = ["program"]
+
+[timing]
+slowdown = 20 # the legacy default (RCB_SLOWDOWN; official 1, 2, 5, 10, 20)
+start_timeout_s = 1800 # the second seat may start up to 30 min after the first (legacy START_TIMEOUT_S)
+ready_timeout_s = 300 # each review after a point (legacy READY_TIMEOUT_S), else the late side loses
+
+[actions.cli] # `game none`; act takes vectors: `game act '{"type": "act", "t": 0.8, ...}'`
+high = { none = [] }
+low = { none = [] }
+
+[observation]
+fields = ["score", "point", "ball", "t_since_played", "heard", "robot_base_xy", "q_arm", "racket_pos", "racket_normal",
+ "ball_in_play", "ball_state", "serve_in_s", "you_receive_serve", "serve", "command", "pending_commands",
+ "last_points", "last_shots", "opponent_level", "q_target", "you_serve"]
+renderer = "mujoco" # the sport draws its own views (the legacy 2 x 4 tiles, MuJoCo; plugin.Views)
+frame_budget_ms = 4000 # one observation, 8 tiles of 480 x 360 (CPU osmesa, a loaded host)
+columns = 4
+# Since wallclock-5 / duel-7 the arms are drawn with the Franka Panda's visual meshes (presentation/
+# presentation.toml players = "25k", bundled into the simulator; renderer rule 6). Measured 2026-10-08 (observations
+# with new tiles, 30 control steps apart, osmesa, 6 CPUs, host load ~8-10 on 32 cores), median / p95 ms per observation
+# at 2 llvmpipe threads: match scene 137 / 171 (duel 142 / 190), 25k meshes 154 / 195 (duel 192 / 220); 1 thread:
+# 223 / 255 (223 / 249) and 254 / 281 (303 / 357)
+render_threads = 2 # llvmpipe threads per render process (LP_NUM_THREADS); one render process per seat
+sim_cpus = 6 # the sim container: 2 seats x 2 render threads + the world, the planners and the core
+
+[spec] # the rule constants (the simulator's values; tests/test_badminton.py checks them)
+match = "first to 5 points (rally scoring); from 4-4 a player must lead by 2, and at 6-6 the next point wins (at most 7); the match also ends after 300 hits (both sides) or 40 points played (replayed lets included): then the player with more points wins, at equal points the player who won the last point"
+play = "there is no bounce: hit the shuttle before it reaches the floor. Your shot is good if your racket meets the shuttle once, on your half, and the shuttle passes over the net and lands in your opponent's singles court (lines are in); after your hit your racket no longer touches it. You lose the point if your shot goes into the net (crosses the net plane below the top), comes down on your own side or lands out, or if a shuttle that is yours to hit lands in your court; an opponent's shot that would land out of your court wins you the point, so you may let it go. Serves (BWF Law 9): the winner of a rally serves the next point (after a let the same server; state.you_serve, state.serve). Before every serve both robots are put at rest in the ready pose at their spots: x = +0.3 in the right service court or -0.3 in the left one, y = -4.0 (your frame); both stand in their right courts when the server's score is even, else in their left ones (diagonally opposite); the spot is your base's home for the point. From 1 s after play resumes (the receiver is ready; state.serve.phase 'open') the server has 3 s to toss the shuttle with {'type':'toss','pos':[X,Y,Z],'height':H}: when the command takes effect (the same lead as an act) the shuttle appears at that point (0.5 <= Z <= 1.8, within 1.0 m horizontally of your base, Y <= -0.5) and is released from rest (H = 0 or omitted) or rises H straight up (0 <= H <= 0.5) before it falls (until then it is held beside the server). Then hit it with your racket (an act, which you may send before the toss): the serve is good if your racket meets the shuttle below 1.15 m, the shuttle leaves the racket upwards, passes over the net and lands in the receiver's diagonally opposite service court (between its short service line and its back line, lines in) or is returned. It is the server's fault (the receiver's point) if it does not toss the shuttle in time (undue delay; the third time disqualifies the player: it loses the match), misses the shuttle, hits it above 1.15 m or not upwards, or the serve hits the net or lands outside that court. Both bases must stay within 5 cm of their spots until the serve is hit (or faulted): a base moving earlier is that player's fault (both at once: a let, replayed)"
+opponent = "format match-wallclock: a scripted computer opponent. You serve the first point; the opponent serves when it won the last rally: from its service court at 1.05 m, upwards, high and deep or short into your diagonal service court, always within your reach (level 1: 70 % high serves, towards the middle of the court; level 2: 50 % high, wider and closer to the short service line); it stands still in its service court while you serve. It never makes an unforced error: it returns every shuttle it can reach, into your court and within your reach; shuttles far from it or fast beat it; level 2 reacts and moves faster and reaches further than level 1"
+world = "metres; your own frame: x to your right, y towards the opponent, z up. Floor z = 0; singles court |x| <= 2.59, |y| <= 6.70 (lines in); the net is the plane y = 0 with its top at z = 1.524 (posts at x = +-3.05); short service lines at |y| = 1.98; the centre line x = 0 divides each half into a right and a left service court. Your half is y < 0"
+robot = "a Franka Panda arm on a 1.0 m pedestal whose base slides on rails (|bx| <= 3.25, -7.5 <= by <= -0.5, up to 6 m/s and 20 m/s^2; home: the point's spot (+-0.3, -4.0), see play); the racket head centre is 0.56 m beyond the flange; the string face is a disc of radius 0.14 m. The racket meets shuttles 0.4-2.5 m above the floor; overhead contacts (1.8-2.5 m) allow the fastest, steepest shots"
+shuttle = "a point mass under gravity (9.81 m/s^2) and quadratic air drag, dv/dt = g - K |v| v with K = 0.212 per metre (terminal speed 6.8 m/s): hit at 40 m/s it slows to about 10 m/s within 0.3 s, and a high shuttle falls almost vertically at close to 6.8 m/s. No spin, no wind, no bounce"
+racket_contact = "the racket meets the shuttle when the shuttle's centre crosses the string plane within 0.14 m of the head centre; the shuttle leaves exactly along the face normal n (the side the head moves towards, relative to the shuttle) at the speed 20 max(0, v_head.n) (1 - 0.3 (r/0.14)^2) + 0.15 max(0, -v_in.n), where v_head is the head velocity, r the contact's distance from the head centre and v_in the shuttle's incoming velocity; the rest of the head and incoming velocity is lost. A head speed along the normal of 0.5 m/s gives about 10 m/s, 2 m/s about 40 m/s; the arm manages up to about 2.4 m/s"
+act = "high level: {'type':'act','t':T,'pos':[PX,PY,PZ],'normal':[NX,NY,NZ],'vel':[VX,VY,VZ]}: the racket's state at contact, T s after the act takes effect: the head centre, the string-face normal and the head velocity (m/s). Limits: 0 < T <= 5, |x| <= 3.4, -7.5 <= y <= -0.3, 0.2 <= z <= 3.0, speed <= 8 m/s. The act takes effect `act.lead_steps` control steps after the step at which it arrives (`game spec`; the stroke is planned meanwhile) and replaces the stroke under way; until then the robot keeps its current command. The controller drives the base to stand for a forehand at the contact point (or as far as it gets in time) and swings the arm under the joint speed limits; it knows nothing about the shuttle. The delivered state scatters by about 6 mm, 0.8 degrees and 3 % (seeded; format duel-wallclock: both robots draw from one sequence, the n-th act of each robot gets the same scatter). {'type':'none'} cancels the stroke (the robot returns to its ready pose, the base to its spot), with the same lead; {'type':'toss','pos':[X,Y,Z],'height':H} tosses the shuttle for your serve (see play), with the same lead"
+lowlevel = "low level: {'type':'traj','q':[[base_x, base_y, q1..q7], ...]}: joint targets, one per 10 ms control step from the next step on (then the robot returns to its ready pose and the base to its spot), each within the joint ranges and speed limits of `game spec` joints; none and serve as above, at the next step"
+observation = "a PNG of 2 rows x 4 columns of 480 x 360 tiles: row 1 a camera behind and above your base line looking down the court, row 2 a camera at the side of the court (x < 0) looking along +x (your half on the right); the columns are frames 60 ms apart, newest on the right, with each frame's step and game time (view_steps, view_sim_times). No shuttle coordinates: the shuttle is drawn enlarged, an orange cork (12 cm ball centred on its position) with a white skirt behind it. `game spec` gives both cameras' poses and intrinsics (pinhole, 45 degree vertical field of view, focal length 434.6 px, principal point at the tile centre). The state gives your robot (robot_base_xy, q_arm, racket_pos, racket_normal), what you heard (tosses, serves and hits, with their times), whether the shuttle is coming to you, and the serve: you_serve, serve.court (right or left), serve.phase (waiting: the receiver is getting ready; open: the server may toss; tossed; done: the serve was delivered), serve.opens_in_s and serve.deadline_in_s for the server, serve.tossed_at_step; a point lost by a service fault says 'serve_fault:<reason>: ...' (undue_delay, missed, too_high, not_upwards, net, out, moved), the receiver's early move 'receive_fault:moved: ...'"
+duel = "format duel-wallclock: another agent controls an identical robot across the net; in each player's frame its own half is y < 0. match.first_server serves the first point; then the winner of each rally serves (both players serve by the same rules, see play)"
+
+[tiebreaks]
+order = ["disqualification", "score", "last_point", "first_receiver"]
+text = "a player disqualified for repeated undue delay (its third serve not tossed in time) loses; else first to 5 points (from 4-4 by 2, at most 7); at the match limit (300 hits or 40 points played) the player with more points; at equal points the player who won the last point that was not a let; then (last resort, not from the rulebook) the player who received first (format match-wallclock: the opponent)"
+last_resort_in_prompt = true
+
+[[exploits]]
+id = "E1"
+text = "an out-of-range, non-finite or malformed command is refused (HTTP 400) and changes nothing"
+test = "test_exploit_bad_commands_are_refused"
+[[exploits]]
+id = "E2"
+text = "low-level joint targets outside the joint ranges or faster than the joint speed limits are refused when they would take effect and change nothing"
+test = "test_exploit_joint_limits"
+[[exploits]]
+id = "E3"
+text = "acts cannot be stacked: a command sent before the previous act took effect is refused (HTTP 409)"
+test = "test_exploit_no_stacked_acts"
+[[exploits]]
+id = "E4"
+text = "the observation holds no shuttle position or velocity and no opponent state (only the images, what was heard and the player's own robot); the legacy privileged /oracle endpoint is gone"
+test = "test_exploit_no_shuttle_state_in_observation"
+[[exploits]]
+id = "E5"
+text = "doing nothing gains nothing: a player who never hits loses the points it receives, and a player who never serves faults on every serve (undue delay): it loses the match"
+test = "test_exploit_idle_loses"
+[[exploits]]
+id = "E6"
+text = "a racket meets the shuttle only on its own half and only on its turn: a robot standing at the net cannot hit the opponent's shot before it crosses, and cannot hit twice"
+test = "test_exploit_no_reach_over_or_double_hit"
+[[exploits]]
+id = "E7"
+text = "the rule constants the players are told (/spec, [spec]) are the simulator's"
+test = "test_exploit_spec_is_the_simulator"
+[[exploits]]
+id = "E8"
+text = "a lowered act replays exactly: the episode holds the low-level joint targets (planned by the legacy stroke controller at the effect step), and a fresh replay reproduces the live state"
+test = "test_exploit_lowered_act_replays"
+[[exploits]]
+id = "E9"
+text = "the serve is judged by the service laws: only the server tosses the shuttle, once per serve, from the step the receiver is ready, within the toss limits (else refused); a miss, a hit above 1.15 m or not upwards, a serve into the net or outside the diagonal service court is the server's fault; a base leaving its spot before the serve is that player's fault; the rally winner serves next from the court of its score's parity"
+test = "test_exploit_serve_rules"
+[[exploits]]
+id = "E10"
+text = "never serving does not pay: a player who wins rallies but never tosses the shuttle is disqualified at its third undue-delay fault and loses, even when ahead on points"
+test = "test_exploit_never_serving_is_disqualified"
+
+[players]
+reference = "reference" # camera-only (the legacy duel's cam_player.py) + a scripted serve: wins the default configuration
+reference_class = "builtin_players:Reference"
+check = [] # the generic tests play the reference only (each match draws thousands of tiles)
+
+[fairness]
+policy = "reference"
+matches_per_order = 20 # N = 40 (the minimum): one in-process duel takes minutes (planning + tiles);
+ # a realtime sport's wide interval only warns
+max_advantage_pp = 5
+mirror = "statistical" # seats are mirrored worlds (one shared scatter sequence; the players serve, the first server alternates)
+
+[official]
+seeds = [1, 2, 3, 101, 111, 121, 202, 212, 222] # duel: 1-3; match: the legacy level seeds (L1 101-121, L2 202-222)
+levels = [1, 2]
+slowdowns = { program = [1, 2, 5, 10, 20] }
+first_any = true
+
+[golden]
+episodes = "golden" # recorded under the player-serve rules; the legacy machine-serve records are retired (README)
+
+[[tasks]]
+format = "match-wallclock"
+action_level = "high"
+id = "badminton-match-wallclock-program-standard" # the legacy task name
+[[tasks]]
+format = "duel-wallclock"
+action_level = "high"
+id = "badminton-duel-wallclock-program-standard" # the legacy task name
+
+[capabilities] # docs/capabilities_zh.md §6
+a1 = 2 # the shuttle's flight only from the camera images (rays, a flight fit)
+a2 = 2 # high drag: the shuttle's flight, the racket contact law
+a3 = 2 # a robot arm on a sliding base, a stroke under joint limits and scatter
+a4 = 2 # real time: the shuttle does not wait; the act lead
+b1 = 1 # the scoring, service (who serves, courts, toss, faults) and fault rules, the match limit
+b2 = 2 # placement against the opponent (deep corners, short), reading its position
+b3 = 0
+physics = ["drag"] # high-drag flight (docs/capabilities_zh.md §6: 高阻力飞行); the shuttle has no
+ # spin and no bounce in this simulator, so spin_bounce is not tested
+
+[check] # tools/check limits: an in-process duel takes 6-15 min (planning + 2 seats' tiles)
+stage_timeout_s = 36000 # stage 2 (~25 in-process matches) and stage 4 (40 duels, serial) take hours
+live_player_timeout_s = 4500 # the live duel at x20 took 1888 s of 3000
diff --git a/scripts/roboolympics/shared/sports/tabletennis/builtin_players.py b/scripts/roboolympics/shared/sports/tabletennis/builtin_players.py
new file mode 100644
index 0000000000..d2e88fec56
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/tabletennis/builtin_players.py
@@ -0,0 +1,663 @@
+"""Table tennis' built-in players (core/client.py plays them over HTTP, core/local.py in-process; the same action
+interface as a model's program). Camera images, the replies and /spec only: no simulator import, no ball state.
+
+ Reference the legacy reference player of Season 1 (scripts/olympiad/tabletennis/*/solution: wc_player.py + arm.py
+ + the oracle loops), one class for every format and action level:
+ perception detect the orange ball in the 8 tiles (2 cameras x 4 frames), triangulate each frame from
+ the two cameras (/spec intrinsics), fit the flight (gravity + quadratic drag, an extra
+ constant acceleration for the unknown spin) and predict the contact after our bounce;
+ shot the paddle state at contact from the contact law, aimed away from the opponent;
+ high level `act` {t, pos, normal, vel} (the service plans the stroke);
+ low level its own arm model from /spec (FK of the documented chain, damped least-squares IK, a
+ joint-speed-limited Hermite swing) streamed as `traj` joint targets, a slew back to the
+ ready pose between balls.
+ Over HTTP it estimates when its act takes effect from the observation's step, the render time and its
+ own latency; in-process (no `timing` in /spec) the act takes effect at the observed step.
+ Idle never acts (the generic tests' check policy: every point ends quickly).
+numpy + Pillow only: this file is also the task's oracle (solution/)."""
+from __future__ import annotations
+
+import base64
+import io
+import math
+import time
+
+import numpy as np
+from PIL import Image
+
+
+# ================================================================================================ perception and shot (wc_player.py)
+G = np.array([0.0, 0.0, -9.81])
+KD = 0.13 # drag: deceleration KD |v| v (instructions: about 0.13)
+E_BOUNCE_Z, E_BOUNCE_XY = 0.96, 0.87
+BALL_R = 0.02
+OFFSET = 0.0275 # blade centre = ball centre - OFFSET * normal (ball radius + half the blade thickness)
+E_PADDLE = 0.96
+TILE_W, TILE_H = 480, 360
+TABLE_X, TABLE_Y = 0.7625, 1.37
+NET_Z = 0.1525
+
+
+# ------------------------------------------------------------------------------------------------ cameras
+class Cam:
+ def __init__(self, c: dict):
+ self.pos = np.array(c["position"], float)
+ self.fw = np.array(c["forward"], float); self.fw /= np.linalg.norm(self.fw)
+ self.up = np.array(c["up"], float); self.up /= np.linalg.norm(self.up)
+ self.rt = np.cross(self.fw, self.up)
+ self.f = float(c.get("focal_px", 434.6))
+ pp = c.get("principal_point_px", [240, 180])
+ self.cx, self.cy = float(pp[0]), float(pp[1])
+
+ def project(self, X):
+ d = np.asarray(X, float) - self.pos
+ z = d @ self.fw
+ return self.cx + self.f * (d @ self.rt) / z, self.cy - self.f * (d @ self.up) / z
+
+ def ray(self, u, v):
+ d = self.fw + ((u - self.cx) / self.f) * self.rt - ((v - self.cy) / self.f) * self.up
+ return self.pos, d / np.linalg.norm(d)
+
+
+def triangulate(rays):
+ """Least-squares point closest to all rays; (point, rms distance to the rays)."""
+ A = np.zeros((3, 3)); b = np.zeros(3)
+ for o, d in rays:
+ P = np.eye(3) - np.outer(d, d)
+ A += P; b += P @ o
+ X = np.linalg.solve(A, b)
+ res = [np.linalg.norm((np.eye(3) - np.outer(d, d)) @ (X - o)) for o, d in rays]
+ return X, float(np.sqrt(np.mean(np.square(res))))
+
+
+# ------------------------------------------------------------------------------------------------ detection
+def decode(png: bytes) -> np.ndarray:
+ return np.asarray(Image.open(io.BytesIO(png)).convert("RGB"))
+
+
+def ball_mask(t: np.ndarray) -> np.ndarray:
+ r = t[..., 0].astype(np.int16); g = t[..., 1].astype(np.int16); b = t[..., 2].astype(np.int16)
+ return (r > 70) & (b * 8 < r) & (g * 100 > 58 * r) & (g * 100 < 82 * r)
+
+
+def detect_tile(t: np.ndarray):
+ """(u, v) of the ball's centroid in a tile, or None."""
+ m = ball_mask(t)
+ m[:16, :70] = False # the time stamp
+ ys, xs = np.nonzero(m)
+ if len(xs) == 0:
+ return None
+ if len(xs) > 400: # far too many: not a ball
+ return None
+ mx, my = np.median(xs), np.median(ys)
+ sel = (np.abs(xs - mx) <= 8) & (np.abs(ys - my) <= 8)
+ if sel.sum() == 0:
+ return None
+ w = t[ys[sel], xs[sel], 0].astype(float)
+ # +0.5: pixel i covers [i, i + 1) in the pinhole model
+ return float(np.average(xs[sel], weights=w)) + 0.5, float(np.average(ys[sel], weights=w)) + 0.5
+
+
+def detect_views(img: np.ndarray, cams: list[Cam], times: list[float], max_res: float = 0.03):
+ """Per frame time: the triangulated ball centre (or nothing). img: 2 rows (cameras) x 4 columns (frames)."""
+ out = []
+ for j, tt in enumerate(times):
+ rays = []
+ for i, c in enumerate(cams):
+ tile = img[i * TILE_H:(i + 1) * TILE_H, j * TILE_W:(j + 1) * TILE_W]
+ uv = detect_tile(tile)
+ if uv is not None:
+ rays.append(c.ray(*uv))
+ if len(rays) == 2:
+ X, res = triangulate(rays)
+ if res < max_res and -0.2 < X[2] < 2.0 and abs(X[1]) < 3.0:
+ out.append((float(tt), X))
+ return out
+
+
+# ------------------------------------------------------------------------------------------------ flight model
+def rollout(p, v, dt, n, bounce=True, a_extra=None):
+ """Explicit integration (semi-implicit Euler) of gravity + drag (+ a constant extra acceleration); the table bounce
+ (restitution) when bounce=True. Returns positions (n+1, 3), velocities (n+1, 3), list of bounce indices."""
+ p = np.array(p, float); v = np.array(v, float)
+ P = np.empty((n + 1, 3)); V = np.empty((n + 1, 3)); P[0] = p; V[0] = v
+ ae = np.zeros(3) if a_extra is None else np.asarray(a_extra, float)
+ bounces = []
+ for i in range(1, n + 1):
+ sp = math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2])
+ a = G - KD * sp * v + ae
+ v = v + a * dt
+ p = p + v * dt
+ if bounce and p[2] < BALL_R and v[2] < 0 and abs(p[0]) <= TABLE_X + 0.01 and abs(p[1]) <= TABLE_Y + 0.01:
+ v = np.array([v[0] * E_BOUNCE_XY, v[1] * E_BOUNCE_XY, -v[2] * E_BOUNCE_Z])
+ p[2] = 2 * BALL_R - p[2]
+ bounces.append(i)
+ P[i] = p; V[i] = v
+ return P, V, bounces
+
+
+def _states_at(p0, v0, t0, times, dt=0.002, a_extra=None):
+ """Positions at `times` (all >= t0, no bounce in between) from the state (p0, v0) at t0."""
+ times = np.asarray(times, float)
+ n = int(math.ceil((times.max() - t0) / dt)) + 1
+ P, _, _ = rollout(p0, v0, dt, n, bounce=False, a_extra=a_extra)
+ idx = (times - t0) / dt
+ i0 = np.clip(np.floor(idx).astype(int), 0, n - 1)
+ f = (idx - i0)[:, None]
+ return P[i0] * (1 - f) + P[i0 + 1] * f
+
+
+def fit_flight(obs, n_iter=6, fit_accel=False, a_fixed=None):
+ """obs: [(t, X)] of one flight segment (no bounce in between). Returns (t0, p0, v0, a_extra, rms) with t0 = the
+ first observation's time, or None. fit_accel: also fit a constant extra acceleration (the Magnus force of the
+ unknown spin) when there are >= 6 points; a_fixed: use this extra acceleration instead."""
+ af = None if a_fixed is None else np.asarray(a_fixed, float)
+ if len(obs) < 2:
+ return None
+ obs = sorted(obs, key=lambda o: o[0])
+ T = np.array([o[0] for o in obs]); X = np.array([o[1] for o in obs])
+ t0 = T[0]
+ if len(obs) == 2:
+ v = (X[1] - X[0]) / (T[1] - T[0]) - 0.5 * G * (T[1] - T[0])
+ return t0, X[0], v, (np.zeros(3) if af is None else af), 0.0
+ # initial guess: quadratic fit per axis
+ A = np.vstack([np.ones_like(T), T - t0, (T - t0) ** 2]).T
+ coef = np.linalg.lstsq(A, X, rcond=None)[0]
+ th = np.r_[coef[0], coef[1], np.zeros(3)]
+ npar = 9 if (fit_accel and af is None and len(obs) >= 6) else 6
+ th = th[:npar]
+ for _ in range(n_iter):
+ def pred(th_):
+ ae = th_[6:9] if npar == 9 else af
+ return _states_at(th_[0:3], th_[3:6], t0, T, a_extra=ae).ravel()
+ r = X.ravel() - pred(th)
+ J = np.zeros((len(r), npar))
+ for c in range(npar):
+ d = np.zeros(npar); d[c] = 1e-4
+ J[:, c] = (pred(th + d) - pred(th)) / 1e-4
+ reg = 1e-6 * np.eye(npar)
+ if npar == 9:
+ reg[6:, 6:] = np.eye(3) * 1e-2 # keep the extra acceleration small unless the data insist
+ step = np.linalg.solve(J.T @ J + reg, J.T @ r)
+ th = th + step
+ if np.linalg.norm(step) < 1e-6:
+ break
+ rms = float(np.sqrt(np.mean((X.ravel() - pred(th)) ** 2)))
+ ae = th[6:9] if npar == 9 else (np.zeros(3) if af is None else af)
+ return t0, th[0:3], th[3:6], ae, rms
+
+
+def predict_contact(t0, p0, v0, a_extra=None, need_bounce=True, t_max=1.6, dt=0.001):
+ """From the state at t0: our bounce (if need_bounce), then the top of the arc after it (or the point where the ball
+ crosses y = -1.38 going down-table, if earlier). Returns (t_contact, p, v) or None."""
+ n = int(t_max / dt)
+ P, V, bounces = rollout(p0, v0, dt, n, bounce=True, a_extra=a_extra)
+ if need_bounce:
+ own = [i for i in bounces if P[i, 1] < 0]
+ if not own:
+ return None
+ i_b = own[0]
+ else:
+ i_b = 0
+ for i in range(i_b + 1, n):
+ if V[i, 2] <= 0 or P[i, 1] < -1.38:
+ return t0 + i * dt, P[i].copy(), V[i].copy()
+ if P[i, 2] < BALL_R:
+ return None
+ return None
+
+
+# ------------------------------------------------------------------------------------------------ stroke
+def landing(p, v, dt=0.004, n=450):
+ """First table contact (x, y) of a free flight after our hit and whether it cleared the net."""
+ P, _, b = rollout(p, v, dt, n, bounce=True)
+ i_net = None
+ for i in range(1, len(P)):
+ if P[i - 1, 1] < 0 <= P[i, 1]:
+ i_net = i
+ if b and i == b[0]:
+ clear = i_net is not None and P[i_net, 2] > NET_Z + BALL_R + 0.03
+ return P[i, :2], clear
+ if P[i, 2] < -0.5:
+ break
+ return None, False
+
+
+def solve_out(p, aim, vy=5.0):
+ """Outgoing ball velocity (vx, vy, vz) from p that lands at `aim` (Newton on vx, vz)."""
+ v = np.array([(aim[0] - p[0]) * vy / max(0.5, aim[1] - p[1]), vy, 1.2])
+ for _ in range(12):
+ L, ok = landing(p, v)
+ if L is None:
+ v[2] += 0.3
+ continue
+ err = L - np.asarray(aim)
+ if np.linalg.norm(err) < 0.01:
+ return v, ok
+ J = np.zeros((2, 2))
+ for c, ix in enumerate((0, 2)):
+ dv = np.zeros(3); dv[ix] = 0.02
+ L2, _ = landing(p, v + dv)
+ if L2 is None:
+ return v, False
+ J[:, c] = (L2 - L) / 0.02
+ try:
+ dx = np.linalg.solve(J, err)
+ except np.linalg.LinAlgError:
+ return v, False
+ dx = np.clip(dx, -1.0, 1.0)
+ v[0] -= dx[0]; v[2] -= dx[1]
+ L, ok = landing(p, v)
+ return v, bool(ok and L is not None and np.linalg.norm(L - np.asarray(aim)) < 0.05)
+
+
+def paddle_for(p_hit, v_in, v_out, tangential=True):
+ """Contact law (instructions): the normal component of the relative velocity reverses with restitution E_PADDLE,
+ the tangential one is kept. With n along (v_out - v_in) the tangential part of the ball is unchanged, so the paddle
+ moves with the ball tangentially and v_p.n = (v_out.n + E v_in.n) / (1 + E)."""
+ dv = v_out - v_in
+ n = dv / np.linalg.norm(dv)
+ vpn = (v_out @ n + E_PADDLE * (v_in @ n)) / (1 + E_PADDLE)
+ v_t = v_in - (v_in @ n) * n
+ v_p = vpn * n + (v_t if tangential else 0.0)
+ p_c = p_hit - OFFSET * n
+ return p_c, n, v_p
+
+
+# ------------------------------------------------------------------------------------------------ the player
+DT = 0.01
+
+
+class Player:
+ """Keeps the frames of the current incoming ball, predicts the contact, decides when to (re-)act.
+
+ update(obs, img, k_req): one observation (its `view_times`, `heard`, `t_since_played`, `step`, `point`, `ball`).
+ decide(k_now): an act dict {"t", "pos", "normal", "vel"} (T from the step k_now) or None.
+ """
+
+ def __init__(self, cams, aim_y=0.85, aim_x=0.45, vys=(5.0, 4.6, 4.2, 3.8, 3.4, 3.0), vp_max=1.4, tangential=True,
+ verbose=False):
+ self.cams = cams
+ self.aim_y, self.aim_x, self.vys, self.vp_max, self.tangential = aim_y, aim_x, tuple(vys), vp_max, tangential
+ self.verbose = verbose
+ self.leg = None
+ self.log = []
+
+ def _new_leg(self, key, obs):
+ self.leg = {"key": key, "frames": {}, "heard": [], "acts": [], "launch": key[2], "kind": obs.get("ball"),
+ "opp_x": None, "done": False, "pred": None}
+
+ def update(self, obs: dict, img, k_req: int):
+ launch = int(round(k_req - float(obs["t_since_played"]) / DT))
+ key = (obs.get("point"), obs.get("ball"), launch)
+ if self.leg is None or self.leg["key"] != key:
+ self._new_leg(key, obs)
+ L = self.leg
+ L["heard"] = obs.get("heard") or []
+ if any(h["event"] in ("paddle", "robot") for h in L["heard"]):
+ L["done"] = True
+ if obs.get("ball_state") != "coming to you":
+ L["done"] = True
+ if img is not None and not L["done"]:
+ # frame times on this ball's clock from the absolute frame steps (a tile's own stamp is relative to the
+ # ball that was current when the frame was taken: right after the opponent's hit, older tiles show our
+ # outgoing ball with that ball's clock)
+ if obs.get("view_steps") is not None:
+ times = [round((k - L["launch"]) * DT, 3) for k in obs["view_steps"]]
+ else:
+ times = obs["view_times"]
+ for t, X in detect_views(img, self.cams, times):
+ if t > 0.005:
+ L["frames"][round(t, 3)] = X
+ return L
+
+ def _bounce_t(self, which):
+ ev = {"opp": "bounce on the opponent's half", "own": "bounce on your half"}[which]
+ ts = [h["t"] for h in self.leg["heard"] if h["event"] == ev]
+ return ts[0] if ts else None
+
+ def predict(self):
+ L = self.leg
+ F = sorted(L["frames"].items())
+ t_own = self._bounce_t("own")
+ if L["kind"] == "serve":
+ t_opp = self._bounce_t("opp")
+ if t_opp is None:
+ return None
+ start = t_opp + 0.005
+ else:
+ start = 0.0
+ A = [(t, X) for t, X in F if start < t and (t_own is None or t < t_own - 0.003)]
+ fa = fit_flight(A, fit_accel=True) if len(A) >= 3 else None
+ if t_own is not None:
+ B = [(t, X) for t, X in F if t > t_own + 0.003]
+ if len(B) >= 3:
+ fb = fit_flight(B, a_fixed=None if fa is None else fa[3])
+ pc = predict_contact(fb[0], fb[1], fb[2], fb[3], need_bounce=False)
+ if pc is not None:
+ return pc + ("post", len(B))
+ if fa is None:
+ return None
+ pc = predict_contact(fa[0], fa[1], fa[2], fa[3], need_bounce=t_own is None)
+ if pc is None:
+ return None
+ return pc + ("pre", len(A))
+
+ def opp_x(self):
+ """Where the opponent is: for a return, where it hit the ball (the first frames of this ball); at a serve it
+ stands at the centre."""
+ L = self.leg
+ if L["kind"] == "serve" or not L["frames"]:
+ return 0.0
+ t, X = min(L["frames"].items())
+ return float(X[0]) if t < 0.2 else 0.0
+
+ def stroke(self, p_hit, v_in, vp_max=None):
+ """Aim away from the opponent; among outgoing speeds (vy = 5.0 ... 3.8 m/s) take the fastest whose paddle
+ speed the arm can deliver (about VP_MAX m/s at the usual contact poses, from the `act` replies)."""
+ ox = self.opp_x()
+ side = -1.0 if ox > 0.05 else (1.0 if ox < -0.05 else (-1.0 if p_hit[0] > 0 else 1.0))
+ aim = np.array([side * self.aim_x, self.aim_y])
+ best = None
+ for vy in self.vys:
+ v_out, ok = solve_out(p_hit, aim, vy)
+ if not ok:
+ continue
+ p_c, n, v_p = paddle_for(p_hit, v_in, v_out, self.tangential)
+ sp = float(np.linalg.norm(v_p))
+ if sp <= (self.vp_max if vp_max is None else vp_max):
+ return p_c, n, v_p, aim
+ if best is None or sp < best[0]:
+ best = (sp, p_c, n, v_p)
+ if best is None:
+ v_out, _ = solve_out(p_hit, aim, self.vys[-1])
+ p_c, n, v_p = paddle_for(p_hit, v_in, v_out, self.tangential)
+ return p_c, n, v_p, aim
+ return best[1], best[2], best[3], aim
+
+ def decide(self, k_now_fn):
+ """k_now_fn(): the current game time in (fractional) control steps, as well as the client can tell; called
+ again after the stroke is computed, so T counts from when the act will reach the service."""
+ L = self.leg
+ if L is None or L["done"]:
+ return None
+ pr = self.predict()
+ if pr is None:
+ return None
+ tc, p, v, phase, nfr = pr
+ L["pred"] = pr
+ t_now = (k_now_fn() - L["launch"]) * DT
+ lead = tc - t_now
+ if lead < 0.04:
+ return None
+ last = L["acts"][-1] if L["acts"] else None
+ cap_changed = last is not None and last.get("vp_cap") != L.get("vp_cap")
+ if last is not None and not cap_changed:
+ dp = float(np.linalg.norm(p - last["p_hit"]))
+ dtc = abs(tc - last["tc"])
+ new_phase = phase == "post" and last["phase"] == "pre"
+ if not new_phase and dp < 0.012 and dtc < 0.006:
+ return None
+ if lead < 0.07 and dp < 0.03 and not new_phase:
+ return None
+ p_c, n, v_p, aim = self.stroke(p, v, L.get("vp_cap", self.vp_max))
+ k_eff = math.floor(k_now_fn()) # the act applies at the start of the step after the current state
+ T = tc - (k_eff - L["launch"]) * DT
+ if T <= 0.02:
+ return None
+ act = {"t": round(float(T), 4), "pos": [round(float(x), 4) for x in p_c],
+ "normal": [round(float(x), 4) for x in n], "vel": [round(float(x), 3) for x in v_p]}
+ L["acts"].append({"tc": tc, "p_hit": p.copy(), "phase": phase, "k_eff": k_eff, "act": act, "nfr": nfr,
+ "aim": aim.tolist(), "vp": float(np.linalg.norm(v_p)), "vp_cap": L.get("vp_cap")})
+ return act
+
+ def on_act_reply(self, stroke: dict | None):
+ """The service says how much of the paddle speed the arm can deliver (speed_scale): cap the next strokes of this
+ ball below that, and re-plan."""
+ L = self.leg
+ if not stroke or L is None or not L["acts"]:
+ return
+ sc = stroke.get("speed_scale") or 1.0
+ if sc > 1.02:
+ cap = 0.95 * L["acts"][-1]["vp"] / sc
+ L["vp_cap"] = round(min(cap, L.get("vp_cap", self.vp_max)), 3)
+
+
+# ================================================================================================ the arm model (arm.py, low level)
+
+
+def quat_mat(q):
+ w, x, y, z = q
+ return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
+ [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
+ [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]])
+
+
+def axis_rot(a, t):
+ a = np.asarray(a, float) / np.linalg.norm(a)
+ K = np.array([[0, -a[2], a[1]], [a[2], 0, -a[0]], [-a[1], a[0], 0]])
+ return np.eye(3) + np.sin(t) * K + (1 - np.cos(t)) * K @ K
+
+
+def hermite(q0, v0, q1, v1, T, n):
+ t = np.arange(1, n + 1) * (T / n)
+ s = t / T
+ h00 = 2 * s**3 - 3 * s**2 + 1; h10 = s**3 - 2 * s**2 + s; h01 = -2 * s**3 + 3 * s**2; h11 = s**3 - s**2
+ return h00[:, None] * q0 + h10[:, None] * T * v0 + h01[:, None] * q1 + h11[:, None] * T * v1
+
+
+class Arm:
+ def __init__(self, spec: dict):
+ kin, lim = spec["kinematics"], spec["limits"]
+ self.chain = [(np.array(b["pos_in_parent"], float), quat_mat(b["quat_in_parent_wxyz"]),
+ None if "joint" not in b else np.array(b["joint_axis_in_body"], float)) for b in kin["chain"]]
+ self.site = np.array(kin["blade_center_in_paddle"], float)
+ self.low = np.array(lim["joint_low_rad"], float)
+ self.high = np.array(lim["joint_high_rad"], float)
+ self.vlim = np.array(lim["joint_speed_limit_rad_s"], float)
+ self.step_lim = np.array(lim["max_target_step_rad"], float)
+ self.q0 = np.array(lim["ready_pose_rad"], float)
+ rng = np.random.default_rng(0)
+ self.starts = [self.q0] + [np.clip(self.q0 + rng.normal(0, .8, 7), self.low + .05, self.high - .05)
+ for _ in range(12)]
+
+ def fk_full(self, q):
+ """(blade centre, paddle rotation (columns: x = face normal), joint axes (7, 3), joint origins (7, 3))."""
+ p, R = np.zeros(3), np.eye(3)
+ axes, origins, j = [], [], 0
+ for pos, Rb, ax in self.chain:
+ p = p + R @ pos
+ R = R @ Rb
+ if ax is not None:
+ axes.append(R @ ax); origins.append(p.copy())
+ R = R @ axis_rot(ax, q[j]); j += 1
+ return p + R @ self.site, R, np.array(axes), np.array(origins)
+
+ def fk(self, q):
+ p, R, _, _ = self.fk_full(q)
+ return p, R
+
+ def jacobian(self, q):
+ p, R, Z, O = self.fk_full(q)
+ Jp = np.cross(Z, p - O).T
+ return np.vstack([Jp, Z.T]), p, R
+
+ def ik(self, pos, normal, q_init, iters=200, tol=1e-4):
+ q = np.array(q_init, float)
+ n_t = np.asarray(normal, float) / np.linalg.norm(normal)
+ err = np.inf
+ for _ in range(iters):
+ J, p, R = self.jacobian(q)
+ n = R[:, 0]
+ e = np.concatenate((pos - p, np.cross(n, n_t)))
+ err = float(np.linalg.norm(e[:3]) + np.arcsin(min(1.0, np.linalg.norm(e[3:]))))
+ if n @ n_t < 0:
+ e[3:] = np.cross(n, n_t) + 0.5 * np.cross(n, R[:, 1]); err += np.pi / 2
+ if err < tol:
+ break
+ q = np.clip(q + J.T @ np.linalg.solve(J @ J.T + 1e-3 * np.eye(6), e), self.low + 1e-4, self.high - 1e-4)
+ return q, err
+
+ def ik_best(self, pos, normal, q_ref):
+ """An accurate branch with little joint travel from q_ref (as the high-level service chooses it)."""
+ def travel(c):
+ return float(np.max(np.abs(c[0] - q_ref) / self.vlim))
+ def rank(c):
+ return (0, travel(c)) if c[1] < 1e-4 else (1, c[1])
+ best = self.ik(pos, normal, q_ref)
+ if best[1] < 1e-4 and travel(best) <= .35:
+ return best
+ for s in self.starts:
+ c = self.ik(pos, normal, s)
+ if rank(c) < rank(best):
+ best = c
+ if best[1] < 1e-4 and travel(best) <= .35:
+ break
+ return best
+
+ def stroke(self, q_s, v_s, n_avail, p_c, nrm, v_p, q_ref=None):
+ """Joint targets for the next n_avail steps + a follow-through, from the target q_s moving at v_s, so that at
+ the end of step n_avail the blade centre is at p_c with face normal nrm and velocity v_p. Returns (rows, info).
+ """
+ nrm = np.asarray(nrm, float) / np.linalg.norm(nrm)
+ q_h, res = self.ik_best(np.asarray(p_c, float), nrm, q_s if q_ref is None else q_ref)
+ J, _, _ = self.jacobian(q_h)
+ Jp = J[:3]
+ W = np.diag(self.vlim ** 2)
+ qd_h = W @ Jp.T @ np.linalg.solve(Jp @ W @ Jp.T, np.asarray(v_p, float))
+ ratio = float(np.max(np.abs(qd_h) / self.vlim))
+ scale = max(1.0, ratio / 0.9)
+ qd_h = qd_h / scale
+ n_sw = n_avail
+ if np.max(np.abs(v_s)) < 1e-6:
+ for n in range(25, n_avail + 1):
+ sw = hermite(q_s, np.zeros(7), q_h, qd_h, n * DT, n)
+ if np.max(np.abs(np.diff(np.vstack([q_s, sw]), axis=0)) / (self.vlim * DT)) <= 0.97:
+ n_sw = n
+ break
+ n_sw = int(min(n_sw, n_avail))
+ pre = np.tile(q_s, (n_avail - n_sw, 1))
+ swing = hermite(q_s, v_s if n_sw == n_avail else np.zeros(7), q_h, qd_h, n_sw * DT, n_sw)
+ n_f = 25
+ follow = hermite(q_h, qd_h, q_h + qd_h * 0.5 * n_f * DT, np.zeros(7), n_f * DT, n_f)
+ rows, prev = [], q_s
+ lim = self.step_lim * 0.995
+ for q in np.vstack([pre, swing, follow]):
+ q = np.clip(q, self.low + 1e-4, self.high - 1e-4)
+ q = prev + np.clip(q - prev, -lim, lim)
+ rows.append(q); prev = q
+ return np.array(rows), {"ik_residual": round(float(res), 5), "speed_scale": round(scale, 3), "n_swing": n_sw}
+
+ def back_to_ready(self, q_s, n=60, frac=0.6):
+ """Speed-limited joint-space return to the ready pose (60 % of the speed limits)."""
+ rows, q = [], np.array(q_s, float)
+ lim = self.step_lim * frac
+ for _ in range(n):
+ q = q + np.clip(self.q0 - q, -lim, lim)
+ rows.append(q.copy())
+ return np.array(rows)
+
+
+# ================================================================================================ the built-in players
+LEAD = 2 # low level: steps between "now" and where a new swing branches off
+MAX_ROWS = 300 # low level: rows per traj command (/spec limits.max_rows_per_command)
+
+
+def _in_range(a):
+ p, v, n = (np.asarray(a[k], float) for k in ("pos", "vel", "normal"))
+ return bool(0 < a["t"] <= 2.5 and abs(p[0]) <= 1.2 and -2.5 <= p[1] <= -0.5 and 0 <= p[2] <= 1.2
+ and np.linalg.norm(v) <= 8 and np.linalg.norm(n) > 1e-6 and np.all(np.isfinite(np.r_[p, v, n])))
+
+
+class Reference:
+ def __init__(self, spec: dict, seat: str, seed: int = 0):
+ self.low = spec.get("action_level") == "low"
+ self.period = (spec.get("timing") or {}).get("period_s") # None in-process (core/local.py)
+ self.P = Player([Cam(c) for c in spec["cameras"]])
+ self.A = Arm(spec) if self.low else None
+ q0 = self.A.q0.copy() if self.low else None
+ self.cmd = {"kind": "hold", "k0": 0, "rows": None, "anchor": (0, q0), "slew": None}
+
+ # ---------------------------------------------------------------- when an act takes effect
+ def _clock(self, st, ob):
+ step, t0 = float(st["step"]), time.monotonic()
+ if self.period is None:
+ return lambda: step # in-process: the act takes effect before this control step
+ # the state is from before the images were drawn; an act takes effect at the control-step boundary after it
+ # arrives, i.e. before step floor(now) runs (+ about 30 ms for the request and, in the duel, the IK)
+ lag = float(ob.get("render_wall_s") or 0.0) + 0.03
+ return lambda: step + (lag + time.monotonic() - t0) / self.period
+
+ # ---------------------------------------------------------------- low level: the command in force
+ def _observe_cmd(self, st):
+ c = self.cmd
+ c["anchor"] = (int(st["step"]) - 1, np.array(st["q_target"], float))
+ now = st.get("command")
+ if now == "hold":
+ c["kind"] = "hold"
+ elif isinstance(now, dict) and now.get("type") == "slew" and c["kind"] == "traj":
+ c["kind"], c["slew"] = "slew", np.array(now["q"], float)
+
+ def _target(self, k):
+ c = self.cmd
+ ka, qa = c["anchor"]
+ if c["kind"] == "traj" and k >= c["k0"]:
+ return c["rows"][min(k - c["k0"], len(c["rows"]) - 1)]
+ if c["kind"] == "slew":
+ q, lim = qa.copy(), self.A.step_lim * 0.6
+ for _ in range(max(0, k - ka)):
+ q = q + np.clip(c["slew"] - q, -lim, lim)
+ return q
+ return qa.copy()
+
+ # ---------------------------------------------------------------- one decision
+ def act(self, view):
+ st, ob = view["state"], view.get("observation") or {}
+ if st.get("world") not in (None, "running"):
+ return None
+ k_now = self._clock(st, ob)
+ incoming = st.get("ball_state") == "coming to you" and bool(st.get("ball_in_play"))
+ if self.low:
+ self._observe_cmd(st)
+ img = None
+ if incoming and ob.get("image_png_b64"):
+ img = decode(base64.b64decode(ob["image_png_b64"]))
+ obs = dict(st, view_steps=ob.get("view_steps"), view_times=ob.get("view_times"))
+ self.P.update(obs, img, int(st["step"]))
+ a = self.P.decide(k_now) if incoming else None
+ if a and not self.low and not _in_range(a): # the act limits (/spec actions): never send a 400
+ a = None
+ if not self.low:
+ return {"type": "act", **a} if a else None
+ if a:
+ k_eff = math.floor(k_now())
+ k_hit, kb = k_eff + int(round(a["t"] / DT)), k_eff + LEAD
+ if k_hit - kb >= 3:
+ q_s = self._target(kb - 1)
+ v_s = (self._target(kb - 1) - self._target(kb - 2)) / DT
+ rows, info = self.A.stroke(q_s, v_s, k_hit - kb, a["pos"], a["normal"], a["vel"])
+ self.P.on_act_reply({"speed_scale": info["speed_scale"]})
+ head = np.array([self._target(k) for k in range(k_eff, kb)]).reshape(-1, 7)
+ rows = np.round(np.vstack([head, rows]), 6)[:MAX_ROWS]
+ self.cmd.update(kind="traj", k0=int(k_eff), rows=rows)
+ return {"type": "traj", "k0": int(k_eff), "q": rows.tolist()}
+ return None
+ k = int(st["step"])
+ c = self.cmd
+ busy = c["kind"] == "traj" and k < c["k0"] + len(c["rows"]) - 1
+ if not incoming and not busy and c["kind"] != "slew" and np.max(np.abs(self._target(k) - self.A.q0)) > 1e-4:
+ q0 = self.A.q0.round(6)
+ c.update(kind="slew", slew=q0)
+ return {"type": "slew", "q": q0.tolist(), "speed": 0.6}
+ return None
+
+ def review(self, reply):
+ return "reference player: scripted", "reference player: same policy"
+
+
+class Idle:
+ def __init__(self, spec: dict, seat: str, seed: int = 0):
+ pass
+
+ def act(self, view):
+ return None
diff --git a/scripts/roboolympics/shared/sports/tabletennis/grade.py b/scripts/roboolympics/shared/sports/tabletennis/grade.py
new file mode 100644
index 0000000000..9f81b835da
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/tabletennis/grade.py
@@ -0,0 +1,129 @@
+"""Table tennis' part of reward.json (the common part is core/grading.py, which runs first; these keys are added after
+it): numbers only, from final.json (and for the legacy metering and no-code fields of the match tasks the sim's
+artifacts think_usage_A.json, think_calls_A.jsonl, direct_gate[_<seat>].jsonl in RCB_DATA). The keys are the legacy
+tasks' keys (scripts/olympiad/tabletennis/{match,duel}/tests/grade.py); README lists what changed and why.
+official_config replaces the core's value: the legacy rule is per format (match: the level's own seeds and the
+program / direct slowdowns; duel: the slowdown only), which [official] cannot express."""
+import importlib.util
+import json
+import os
+from pathlib import Path
+
+DATA = Path(os.environ.get("RCB_DATA", "/data"))
+OFFICIAL_SEEDS = {1: [101, 111, 121], 2: [202, 212, 222], 3: [303, 313, 323], 4: [404, 414, 424]}
+OFFICIAL_SLOWDOWNS = {"match": {"program": [1, 2, 5, 10, 20], "direct": [20, 50, 100]},
+ "duel": {"program": [10, 20], "direct": [20, 50, 100]}}
+LADDER_KEYS = ("points", "balls", "points_touched", "points_active", "points_over_net", "points_landed_in",
+ "points_returned", "points_won", "points_won_expedite", "points_won_rally", "balls_touched",
+ "balls_active", "balls_over_net", "balls_landed_in", "balls_returned")
+EXPEDITE = "(expedite rule)"
+
+
+def _json(name):
+ try:
+ return json.loads((DATA / name).read_text())
+ except (OSError, ValueError):
+ return {}
+
+
+def _gate_blocks(name):
+ p = DATA / name
+ return sum('"ev": "blocked"' in ln for ln in p.read_text().splitlines()) if p.exists() else 0
+
+
+def _audit(seat):
+ """(tool calls, violations) of the players' no-code audit (tests/nocode_audit.py, the same one the core runs)."""
+ p = Path(__file__).resolve().parent / "nocode_audit.py"
+ if not p.exists():
+ return 0, []
+ spec = importlib.util.spec_from_file_location("tt_nocode_audit", p)
+ mod = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(mod)
+ return mod.nocode_audit(DATA / f"think_calls_{seat}.jsonl")
+
+
+def official(d, fmt):
+ try:
+ seed, slow = int(d.get("seed")), float(d.get("slowdown"))
+ except (TypeError, ValueError):
+ return 0
+ ok = slow in OFFICIAL_SLOWDOWNS[fmt].get(d.get("play", "program"), [])
+ if fmt == "match":
+ ok &= seed in OFFICIAL_SEEDS.get(int((d.get("sport_fields") or {}).get("level") or 0), [])
+ return int(ok)
+
+
+def lag(d):
+ s = d.get("sim_lag") or {}
+ run_sim = float(s.get("run_sim_s") or 0.0)
+ return s, (float(s.get("run_wall_s") or 0.0) / run_sim if run_sim > 0 else 0.0)
+
+
+def evaluate(d):
+ f, seats = d.get("sport_fields") or {}, d["cfg"]["seats"]
+ return match(d, f, seats[0]) if len(seats) == 1 else duel(d, f, seats)
+
+
+def duel(d, f, seats):
+ s_lag, _ = lag(d)
+ out = dict(ready_forfeit=int(d.get("reason") == "ready_timeout" and d.get("match_winner") is not None),
+ timing_invalid=0, steps=int(d["steps"]), hits=int(f.get("hits", 0)), slowdown=float(d["slowdown"]),
+ official_config=official(d, "duel"), sim_lag_max_s=float(s_lag.get("late_max_s") or 0.0),
+ net_touches=sum(p.get("net_touches", 0) for p in f.get("points", [])),
+ lets=sum(bool(p.get("let")) for p in f.get("points", [])))
+ for s in seats:
+ st = d["seats"].get(s, {})
+ out[s + "_points"] = int((f.get("score") or {}).get(s, 0))
+ out[s + "_points_expedite"] = sum(p.get("winner") == s and EXPEDITE in str(p.get("how", ""))
+ for p in f.get("points", []))
+ out[s + "_rejected_acts"] = int((f.get("rejected_acts") or {}).get(s, 0))
+ if d.get("play") == "direct":
+ out[s + "_gate_blocks"] = _gate_blocks(f"direct_gate_{s}.jsonl")
+ for k in ("attempts", "applied", "refused", "dropped", "observations"):
+ out[s + "_" + k] = int(st.get(k, 0))
+ for k in ("plan_s", "act_s", "obs_age_s"):
+ out[s + "_" + k + "_max"] = float(max(st.get(k) or [], default=0))
+ return out
+
+
+def match(d, f, a):
+ st, u = d["seats"].get(a, {}), _json(f"think_usage_{a}.json")
+ errs = d.get("errors") or []
+ direct = d.get("play") == "direct"
+ model = (d.get("player_modes") or {}).get(a) == "model"
+ n_tools, bad = _audit(a) if direct else (0, [])
+ forfeit = direct and model and bool(bad)
+ s_lag, eff = lag(d)
+ rep = d.get("replay_scores") or {}
+ lad = f.get("ladder") if isinstance(f.get("ladder"), dict) else {}
+ out = dict(
+ won=int(d.get("match_winner") == a and not forfeit),
+ sim_error=int(d.get("reason") == "technical_error" or any(e.get("where") != "replay" for e in errs)),
+ replay_error=int(not d.get("deterministic") or any(e.get("where") == "replay" for e in errs)),
+ meter_error=int(bool((d.get("meter_error") or {}).get(a))),
+ proxy_error=int(bool((d.get("proxy_error") or {}).get(a))), timing_invalid=0,
+ points_for=int(f.get("points_for", 0)), points_against=int(f.get("points_against", 0)),
+ replay_points_for=int(rep.get(a, -1)), replay_points_against=int(rep.get("opponent", -1)),
+ replay_joint_targets_equal=int(bool(d.get("deterministic"))), finalized=int(bool(d.get("finalized"))),
+ revision=5, timing_lag_enforced=0, rejected_acts=int(f.get("rejected_acts", 0)),
+ nocode_tool_calls=int(n_tools), nocode_violations=len(bad), nocode_forfeit=int(forfeit),
+ gate_blocks=_gate_blocks("direct_gate.jsonl") + _gate_blocks(f"direct_gate_{a}.jsonl"),
+ metered_requests=int(u.get("requests", 0)), metered_output_tokens=int(u.get("output_tokens", 0)),
+ metered_input_tokens=int(u.get("input_tokens", 0)), rate_limit_retries=int(u.get("rate_limit_retries", 0)),
+ transient_api_errors=int((d.get("transient_api_errors") or {}).get(a, 0)),
+ unrecovered_api_errors=int((d.get("unrecovered_api_errors") or {}).get(a, 0)),
+ level=float(f.get("level") or 0), slowdown=float(d.get("slowdown") or 0),
+ our_shots=float(f.get("our_shots", 0)), balls_to_you=float(f.get("our_legs", 0)),
+ good_shots=float(f.get("returns", 0)), n_decisions=float(st.get("applied", 0)),
+ refused_not_model=float(st.get("refused", 0)), dropped_acts=float(st.get("dropped", 0)),
+ n_actions=float(d.get("steps") or 0), sim_steps=float(f.get("physics_steps", 0)),
+ steps=float(d.get("steps") or 0), n_reviews=float(len(d.get("reviews") or [])),
+ n_calls=float(st.get("attempts", 0) + st.get("observations", 0)), n_observe=float(st.get("observations", 0)),
+ n_act=float(st.get("attempts", 0)), elapsed_s=float(d.get("elapsed_s") or 0), max_lag_s=0.0,
+ official_config=official(d, "match"), sim_lag_late_max_s=float(s_lag.get("late_max_s") or 0),
+ sim_lag_late_p99_s=float(s_lag.get("late_p99_s") or 0), sim_effective_slowdown=float(eff),
+ sim_run_wall_s=float(s_lag.get("run_wall_s") or 0))
+ for k in LADDER_KEYS:
+ v = lad.get(k)
+ out["ladder_" + k] = int(v) if isinstance(v, (int, float)) and not isinstance(v, bool) else -1
+ return out
diff --git a/scripts/roboolympics/shared/sports/tabletennis/plugin.py b/scripts/roboolympics/shared/sports/tabletennis/plugin.py
new file mode 100644
index 0000000000..3d601fff71
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/tabletennis/plugin.py
@@ -0,0 +1,589 @@
+"""Table tennis on the v0.2 core (docs/framework_zh.md §4.2): the legacy simulator of Season 1, unchanged (sim/), behind
+contract ②. Two formats, both action levels, both plays:
+
+ world + referee match arm_commands.Core (match.Match: one Franka + paddle against the scripted opponent inside the
+ world; the opponent serves every point; step = Core.rt_advance(1))
+ duel duel.Duel (two arms, a neutral serve machine, the ITTF referee; step = Duel.advance())
+ A point end freezes the world for the reviews (Phase.review); first to 5 (lead by 2 from 4:4, cap 7).
+ actions low the arm command layer: traj / slew / hold joint targets (action_low.validate)
+ high the paddle state at contact (action_high.validate), lowered at the effect boundary to the
+ SAME low-level traj command: match - match.Match.plan_paddle (IK, swing, robot-only rehearsals,
+ seeded scatter) then a slew back to the ready pose; duel - IK off the world lock in the seat's
+ plan worker (workers.prepare), the swing at the boundary (workers.trajectory). The episode
+ holds low-level commands only.
+ observation observe(): own arm, score, heard bounces, the command in force (every position in the seat's own
+ frame); camera_job(): the legacy cameras (behind and beside the seat's robot, 4 frames 40 ms
+ apart), drawn by the sport itself (a frame history is not one renderer state).
+Nothing in sim/ is edited: its seed and first receiver come from the config (duel.py reads them as module constants).
+"""
+from __future__ import annotations
+
+import copy
+import hashlib
+import json
+import os
+import sys
+import time
+from pathlib import Path
+
+import numpy as np
+
+from core.sport import FINISHED, PLAYING, UNIT_OVER, MatchBase, Phase, Refused
+
+HERE = Path(__file__).resolve().parent
+SIM = HERE / "sim"
+if str(SIM) not in sys.path:
+ sys.path.insert(0, str(SIM))
+
+import action_high # noqa: E402
+import action_low # noqa: E402
+import rcb_tt # noqa: E402
+
+DT = rcb_tt.CONTROL_DT
+SEATS = ("A", "B")
+REST_SPEED = action_high.REST # the high level's return to the ready pose (60 % of the limits)
+_INSTALL_KEYS = ("command", "first_row_used", "rows_left")
+IMAGE_LAYOUT = ("2 rows x 4 columns. Row 1: camera behind your robot looking down the table; row 2: camera at the side. "
+ "Columns: four camera frames 40 ms apart, oldest left, latest right; each tile is stamped with its "
+ "control step k and its time t since the current ball was played (observation.view_steps, "
+ "view_times). Yellow marks every 0.25 m along the table edges. Single format: the opponent is the red "
+ "paddle on the far side. The side camera looks along +x: your robot is on the right.")
+
+
+def _duel(cfg):
+ """duel.py reads its seed and first receiver from the environment at import (module constants): set both from the
+ config, also for a module imported by an earlier match of this process."""
+ first = cfg.first or "A"
+ os.environ["DUEL_SEED"], os.environ["FIRST_RECEIVER"] = str(cfg.seed), first
+ import duel
+ duel.SEED, duel.FIRST_RECEIVER = int(cfg.seed), first
+ return duel
+
+
+# ================================================================================================ format "match"
+class TTMatch(MatchBase):
+ """One seat (A) against the scripted opponent (arm_commands.Core)."""
+
+ def __init__(self, cfg):
+ self.cfg, self.level = cfg, int(cfg.level or 1)
+ os.environ["MATCH_SEED"] = str(cfg.seed) # match.Match reads it at construction: serves, opponent, scatter
+ import arm_commands
+ import ladder
+ import levels
+ self.R = arm_commands.Core(self.level, levels.plugin(cfg.action_level))
+ self.contacts = ladder.PaddleContacts(self.R) # read-only (the score ladder's blade speeds)
+ self.dt = DT
+ self.reviewed = 0
+
+ @property
+ def k(self):
+ return self.R.k
+
+ # world + referee
+ def step(self):
+ R = self.R
+ n0, r0 = len(R.points), len(R.results)
+ R.rt_advance(1)
+ self.contacts.after_step(R.k)
+ ev = [{"kind": "shot", **{k: r.get(k) for k in ("returned", "summary")}} for r in R.results[r0:]]
+ return ev + [{"kind": "point", **p} for p in R.points[n0:]]
+
+ def apply(self, seat, cmd):
+ if cmd["type"] == "noop": # a high-level act whose stroke could not be planned
+ return {}
+ return self.R.submit(cmd)
+
+ def phase(self):
+ R = self.R
+ if R.done:
+ return Phase(FINISHED, reason="match_over")
+ if len(R.points) > self.reviewed:
+ return Phase(UNIT_OVER, review=tuple(self.cfg.seats), reason=R.points[-1]["how"])
+ return Phase(PLAYING)
+
+ def resume(self):
+ self.reviewed = len(self.R.points)
+
+ def unit(self):
+ return len(self.R.points)
+
+ def scores(self):
+ return {"A": self.R.score[0], "opponent": self.R.score[1]}
+
+ def tiebreaks(self):
+ return [("game", lambda m: {0: "A", 1: "opponent"}.get(m.R.winner))] # first to 5, lead 2, cap 7; let guard
+
+ def state_digest(self):
+ """The simulator's own state hash (physics + the ball's contact events) and the points (score, how)."""
+ return hashlib.sha256((self.R.s.state_sha() + json.dumps(self.R.points, sort_keys=True)).encode()).hexdigest()
+
+ # observation
+ def observe(self, seat, query=None):
+ R = self.R
+ st, leg = R.s.state(), R.leg
+ heard = [{"event": {"table_opp": "bounce on the opponent's half", "table_own": "bounce on your half",
+ "net": "net"}.get(e["kind"], e["kind"]),
+ "t": round(e["t"] - leg["launch"] * DT, 3)} for e in R.s._events]
+ o = {"score": {"you": R.score[0], "opponent": R.score[1]}, "point": len(R.points) + 1,
+ "ball": "serve" if leg["kind"] == "serve" else "opponent's return", "t_since_played": R.t_since_launch(),
+ "heard": heard, "q": st["q"].round(4).tolist(), "paddle_pos": st["paddle_pos"].round(3).tolist(),
+ "paddle_normal": st["paddle_normal"].round(3).tolist(),
+ "ball_in_play": R.in_play() and leg["state"] in ("incoming", "to_opp", "opp_missed"),
+ "ball_state": {"incoming": "coming to you", "to_opp": "going to the opponent",
+ "opp_missed": "going to the opponent", "done": "dead"}.get(leg["state"], leg["state"]),
+ "points": [{k: p[k] for k in ("point", "winner", "how", "score")} for p in R.points[-2:]],
+ "shots": [{k: r.get(k) for k in ("returned", "summary", "speed_out")} for r in R.results[-2:]]}
+ if not R.in_play():
+ o["serve_in_s"] = round(max(0.0, (leg["launch"] - R.k) * DT), 3)
+ o.update(R.plugin.state(R)) # the command in force (low level: also qd, q_target)
+ return o
+
+ def camera_job(self, seat):
+ R = self.R
+ reviewing = len(R.points) > self.reviewed and not R.done
+ hist = list(R.review_hist if reviewing and hasattr(R, "review_hist") else R.hist)
+ if not hist: # before the first step: the current state (display only)
+ hist = [{"k": R.k, "t": R.t_since_launch(), "qpos": R.s.d.qpos.copy(), "opp_x": R.opp_x(),
+ "leg_id": len(R.legs) - 1, "wall_mono": time.monotonic()}]
+ import match
+ sel = [hist[max(0, len(hist) - 1 - b)] for b in reversed(match.Match.VIEW_BACK)]
+ snaps = [{"qpos": np.asarray(s["qpos"], float).copy(), "t": float(s["t"]), "opp_x": float(s["opp_x"]),
+ "k": int(s["k"])} for s in sel]
+ meta = dict(view_times=[s["t"] for s in sel], view_steps=[s["k"] for s in sel],
+ view_leg_ids=[s.get("leg_id") for s in sel], view_sim_times=[round(s["k"] * DT, 4) for s in sel],
+ wall_mono=sel[-1].get("wall_mono", time.monotonic()), image_layout=IMAGE_LAYOUT)
+ return {"format": "match", "seat": seat, "snaps": snaps}, meta
+
+ def render_state(self):
+ return {"qpos": self.R.s.d.qpos.tolist()}
+
+ def broadcast_frame(self):
+ return {"q": self.R.s.d.qpos.round(5).tolist(), "o": round(self.R.opp_x(), 4)}
+
+ def final_fields(self):
+ import ladder
+ R = self.R
+ return {"level": self.level, "seed": int(R.lv["seed"]), "points_for": R.score[0], "points_against": R.score[1],
+ "win_points": 5, "won": R.winner == 0, "winner_side": {0: "you", 1: "opponent"}.get(R.winner),
+ "returns": int(sum(r["returned"] for r in R.results)), "our_legs": R.n_our_legs,
+ "our_shots": R.n_our_shots, "rejected_acts": R.n_rejected, "physics_steps": int(R.s.sim_steps_total),
+ "points": R.points, "results": R.results, "shots": R.shots, "serves": R.serve_ids,
+ "opponent": [lg.get("opp") for lg in R.legs if lg.get("opp")],
+ "ladder": ladder.ladder(R.points, R.results, contacts=self.contacts.out)}
+
+
+# ================================================================================================ format "duel"
+class TTDuel(MatchBase):
+ def __init__(self, cfg):
+ self.cfg = cfg
+ self.D = D = _duel(cfg)
+ self.g = D.Duel()
+ self.g.rest_ready = cfg.action_level == "high" # the high level returns the arm to the ready pose between strokes
+ self.dt = D.CONTROL_DT
+ self.level = cfg.action_level
+ self.commands = {s: None for s in SEATS} # the high level's stroke in force (shown in the observation)
+
+ @property
+ def k(self):
+ return self.g.k
+
+ def step(self):
+ n = len(self.g.points)
+ self.g.advance()
+ if len(self.g.points) > n:
+ self.commands = {s: None for s in SEATS}
+ return [{"kind": "point", **self.g.points[-1]}]
+ return []
+
+ def apply(self, seat, cmd):
+ return self.g.install(seat, cmd)
+
+ def phase(self):
+ if self.g.done:
+ return Phase(FINISHED, reason="match_over")
+ if self.g.review_due:
+ return Phase(UNIT_OVER, review=SEATS, reason=self.g.points[-1]["how"])
+ return Phase(PLAYING)
+
+ def resume(self):
+ self.g.review_done()
+
+ def unit(self):
+ return self.g.rs["point"]
+
+ def scores(self):
+ return dict(self.g.score)
+
+ def tiebreaks(self):
+ return [("game", lambda m: m.g.winner)] # ITTF game to 5 (lead by 2, cap 7); the let guard inside Duel
+
+ def state_digest(self):
+ return self.g.state_sha()
+
+ def observe(self, seat, query=None):
+ g, D = self.g, self.D
+ other = D.OTHER[seat]
+ p = g.d.site_xpos[g.site_paddle[seat]].copy()
+ normal = g.d.site_xmat[g.site_paddle[seat]].reshape(3, 3)[:, 0].copy()
+ if seat == "B":
+ p, normal = D.mir(p), D.mir(normal)
+ command = copy.deepcopy(self.commands[seat])
+ if command:
+ command["contact_in_s"] = max(0., (command["contact_step"] - g.k) * self.dt)
+ heard = {f"table_{seat}": "bounce on your half", f"table_{other}": "bounce on the opponent's half",
+ f"paddle_{seat}": "paddle", f"paddle_{other}": "opponent hit", f"robot_{seat}": "robot",
+ f"robot_{other}": "opponent arm"}
+ o = dict(point=g.rs["point"] + 1, score=dict(you=g.score[seat], opponent=g.score[other]),
+ ball="serve" if g.rs["last_hitter"] is None else "return",
+ t_since_played=(g.k - g.rs["played_k"]) * self.dt,
+ serve_in_s=max(0., (g.rs["launch"] - g.k) * self.dt), ball_in_play=g.in_play(),
+ ball_state="coming to you" if g.rs["expect"] == seat else "going to opponent",
+ you_receive_serves=g.rs["receiver"] == seat, q=g.d.qpos[g.qadr[seat]].tolist(),
+ paddle_pos=p.tolist(), paddle_normal=normal.tolist(),
+ command=command if self.level == "high" else g.command_state(seat),
+ points=[{k: v for k, v in pt.items() if k != "receiver"} for pt in g.points[-2:]],
+ heard=[dict(event=heard.get(x["kind"], x["kind"]), t=x["t"] - g.rs["played_k"] * self.dt)
+ for x in g.events[-12:] if x["t"] >= g.rs["played_k"] * self.dt - .011])
+ if self.level == "low":
+ o.update(qd=g.d.qvel[g.vadr[seat]].round(4).tolist(), q_target=g.target[seat].round(6).tolist())
+ return o
+
+ def camera_job(self, seat):
+ g = self.g
+ hist = g.review_hist if g.review_due and hasattr(g, "review_hist") else list(g.hist)
+ if not hist:
+ hist = [dict(k=g.k, qpos=g.d.qpos.copy(), played_k=g.rs["played_k"], point=g.rs["point"],
+ wall_mono=time.monotonic())]
+ hist = copy.deepcopy(list(hist))
+ sel = [hist[max(0, len(hist) - 1 - b)] for b in reversed(g.VIEW_BACK)]
+ meta = dict(view_steps=[x["k"] for x in sel], view_points=[x["point"] + 1 for x in sel],
+ view_sim_times=[x["k"] * self.dt for x in sel],
+ view_times=[round((x["k"] - x.get("played_k", g.rs["played_k"])) * self.dt, 3) for x in sel],
+ wall_mono=sel[-1].get("wall_mono", time.monotonic()), image_layout=IMAGE_LAYOUT)
+ return {"format": "duel", "seat": seat, "snapshots": hist, "rs": copy.deepcopy(g.rs)}, meta
+
+ def render_state(self):
+ return {"qpos": self.g.d.qpos.tolist()}
+
+ def broadcast_frame(self):
+ return {"q": self.g.d.qpos.round(5).tolist()}
+
+ def final_fields(self):
+ g = self.g
+ return {"score": dict(g.score), "points": g.points, "hits": g.hits, "rejected_acts": dict(g.rejected),
+ "first_receiver": self.D.FIRST_RECEIVER, "serves": g.serve_ids}
+
+
+# ================================================================================================ action levels
+class _LowShim:
+ """What action_low needs of a simulator (joint ranges, the ready pose), from the duel's model."""
+
+ def __init__(self, g, D):
+ self.s = type("S", (), dict(JOINT_LOW=g.JLOW, JOINT_HIGH=g.JHIGH, inst={"q0": D.Q0}))()
+
+
+def _rows(m):
+ return m.R if isinstance(m, TTMatch) else _LowShim(m.g, m.D)
+
+
+def _vec(n, doc):
+ return {"type": "vector", "len": n, "doc": doc}
+
+
+LOW_SCHEMA = {
+ "traj": {"k0": {"type": "integer", "min": 0, "doc": "control step of the first row"},
+ "q": {"type": "rows", "len": 7, "max_rows": action_low.MAX_ROWS,
+ "doc": "row i = the 7 joint targets (rad) of control step k0 + i; consecutive rows within the "
+ "per-step speed limit (limits.max_target_step_rad)"}},
+ "slew": {"q": _vec(7, "joint goal (rad)"),
+ "speed": {"type": "number", "min": 0.0, "max": 1.0, "default": 1.0,
+ "doc": "fraction of each joint's speed limit, (0, 1]"}},
+ "hold": {}}
+HIGH_SCHEMA = {
+ "act": {"t": {"type": "number", "min": 0.0, "max": 2.5, "unit": "s",
+ "doc": "time from the act's effect until contact, 0 < t <= 2.5"},
+ "pos": _vec(3, "blade centre at contact (m, your frame): |x| <= 1.2, -2.5 <= y <= -0.5, 0 <= z <= 1.2"),
+ "normal": _vec(3, "blade face normal at contact (non-zero)"),
+ "vel": _vec(3, "blade velocity at contact (m/s), |vel| <= 8")},
+ "none": {}}
+
+
+class JointLayer:
+ """Low level: the player's joint-target commands go straight to the arm command layer."""
+ level = "low"
+ worker = None
+ delay_steps = 0
+
+ def schema(self, match, seat):
+ return LOW_SCHEMA
+
+ def parse(self, seat, body, match, ctx):
+ dec = action_low.validate(body if isinstance(body, dict) else {}, _rows(match))
+ if isinstance(dec, str):
+ raise Refused(dec)
+ return dec
+
+ def snapshot(self, seat, cmd, match, ordinal):
+ return None
+
+ def prepare(self, job):
+ return None
+
+ def lower(self, seat, cmd, prepared, match):
+ return cmd, {}
+
+ def reply(self, seat, cmd, info, match):
+ return {"result": info} if isinstance(match, TTMatch) else info
+
+
+class StrokeLayer:
+ """High level: the paddle state at contact, lowered at the effect boundary to a low-level traj command."""
+ level = "high"
+ worker = "plan" # the duel's IK (the match plans at the boundary: no job)
+ delay_steps = 0
+
+ def schema(self, match, seat):
+ return HIGH_SCHEMA
+
+ def parse(self, seat, body, match, ctx):
+ dec = action_high.validate(body if isinstance(body, dict) else {}, None)
+ if isinstance(dec, str):
+ raise Refused(dec)
+ return dec
+
+ def snapshot(self, seat, cmd, match, ordinal):
+ if cmd["type"] == "none" or isinstance(match, TTMatch):
+ return None
+ g = match.g
+ return dict(decision=cmd, point=g.rs["point"], ordinal=ordinal, q=g.d.qpos[g.qadr[seat]].tolist(),
+ target=g.target[seat].tolist())
+
+ def prepare(self, job):
+ raise RuntimeError("runs in the plan worker")
+
+ def lower(self, seat, cmd, prepared, match):
+ if isinstance(match, TTMatch):
+ return self._lower_match(cmd, match.R)
+ g = match.g
+ if cmd["type"] == "none":
+ match.commands[seat] = None
+ return {"type": "hold"}, {}
+ from workers import trajectory
+ prev = g.actions[seat][-2] if (len(g.actions[seat]) >= 2 and
+ np.array_equal(g.target[seat], g.actions[seat][-1])) else g.target[seat]
+ path, info = trajectory(g.target[seat], prev, prepared, cmd["t"], g.JLOW, g.JHIGH)
+ match.commands[seat] = dict(pos=cmd["pos"], normal=cmd["normal"], vel=cmd["vel"],
+ contact_step=g.k + info["contact_steps"])
+ info.update(ik_residual=prepared["ik_residual"], speed_scale=prepared["speed_scale"])
+ return {"type": "traj", "k0": g.k, "q": [q.tolist() for q in path]}, info
+
+ @staticmethod
+ def _lower_match(cmd, R):
+ """= action_high.apply at the effect boundary (the legacy service planned there too), with the plan handed
+ to the arm command layer as a low-level command instead of being submitted directly."""
+ rest = {"type": "slew", "q": [float(x) for x in R.s.inst["q0"]], "speed": REST_SPEED}
+ if cmd["type"] == "none":
+ R._last_act = None
+ R.contact_k = R.k
+ return rest, {"stroke": "cleared: the arm returns to the ready pose"}
+ T = float(cmd["t"])
+ t_hit = (R.k - R.leg["launch"]) * DT + T
+ R._ik_seed = R._planned_hit if R.traj_active() else None
+ plan, info = R.plan_paddle(t_hit, cmd["pos"], cmd["normal"], cmd["vel"])
+ info["T_from_now"] = round(T, 4)
+ R.shots.append({"k": R.k, "leg": R.n_our_legs, **{k: info[k] for k in info if k != "paddle_vel_delivered"}})
+ if not plan:
+ return {"type": "noop"}, info
+ R.contact_k = R.k + info["n_swing_steps_available"]
+ R._last_act = info
+ return {"type": "traj", "k0": R.k, "q": [np.asarray(q, float).tolist() for q in plan], "then": rest}, info
+
+ def reply(self, seat, cmd, info, match):
+ if isinstance(match, TTMatch):
+ return action_high.reply(cmd, info)
+ return {k: v for k, v in info.items() if k not in _INSTALL_KEYS}
+
+
+# ================================================================================================ the cameras
+class _Tiles:
+ """Draws camera tiles exactly as the legacy services did (render_worker.py for the match, Duel.render_views for the
+ duel), with a cache: consecutive observations share most of their frames (a frame every 2 control steps, the 4
+ tiles span 12), and a tile is a pure function of its snapshot, so a cached tile is the same picture."""
+
+ def __init__(self, model, cams):
+ import mujoco as mj
+ self.mj = mj
+ self.m = model
+ self.r = mj.Renderer(self.m, height=360, width=480)
+ self.rd = mj.MjData(self.m)
+ self.cams, self.cache = [], {}
+ for lookat, dist, az, el in cams:
+ c = mj.MjvCamera()
+ c.lookat[:] = lookat
+ c.distance, c.azimuth, c.elevation = dist, az, el
+ self.cams.append(c)
+
+ def tile(self, ci, qpos, text, extra, key):
+ from PIL import Image, ImageDraw
+ key = (ci, key, text, np.asarray(qpos, float).tobytes())
+ if key not in self.cache:
+ mj = self.mj
+ self.rd.qpos[:] = qpos
+ mj.mj_forward(self.m, self.rd)
+ self.r.update_scene(self.rd, camera=self.cams[ci])
+ extra(self.r.scene)
+ im = Image.fromarray(self.r.render())
+ ImageDraw.Draw(im).text((6, 4), text, fill=(255, 255, 255))
+ if len(self.cache) > 96:
+ self.cache.clear()
+ self.cache[key] = np.asarray(im)
+ return self.cache[key]
+
+ def sheet(self, tiles_per_cam):
+ from core.observe import png
+ return png(np.concatenate([np.concatenate(row, axis=1) for row in tiles_per_cam], axis=0))
+
+
+def _players_model(live, scene_file):
+ """The model the cameras draw: the players' presentation scene (presentation/presentation.toml `players`: the
+ Franka Panda's visual meshes on the same bodies, renderer rule 6; same kinematics, checked) with the live model's
+ marker settings, else the live model itself."""
+ from renderers import Scene, players_model
+ fine = players_model(HERE, Scene.from_file(scene_file))
+ if fine is None:
+ return live
+ fine.site_pos[:], fine.site_size[:], fine.site_rgba[:] = live.site_pos, live.site_size, live.site_rgba
+ return fine
+
+
+class MatchView(_Tiles):
+ """The single format's cameras (= the legacy render_worker.py): 2 cameras x 4 frames, 480 x 360 tiles."""
+
+ def __init__(self):
+ import match
+ self.Match = match.Match
+ m = rcb_tt.Session(instance=str(match.INSTANCE), scene=str(match.SCENE)).m # the live match's model
+ super().__init__(_players_model(m, match.SCENE), match.Match.CAMS)
+
+ def draw(self, snaps):
+ return self.sheet([[self.tile(ci, sn["qpos"], f"k={sn['k']} t={sn['t']:.2f}s",
+ lambda scn, o=sn["opp_x"]: self.Match._extra_geoms(None, scn, o), sn["opp_x"])
+ for sn in snaps] for ci in range(len(self.cams))])
+
+
+class DuelView(_Tiles):
+ """A duel seat's cameras (= duel.Duel.render_views): behind and beside the seat's robot, in its own frame."""
+
+ def __init__(self, seat):
+ import duel
+ self.D = duel
+ cams = [(lk if seat == "A" else duel.mir(lk), dist, az if seat == "A" else az + 180.0, el)
+ for lk, dist, az, el in duel.Duel.CAMS]
+ import mujoco as mj
+ super().__init__(_players_model(mj.MjModel.from_xml_path(str(duel.SCENE2)), duel.SCENE2), cams) # = Duel()'s
+
+ def draw(self, snapshots, rs):
+ D, out = self.D, []
+ sel = [snapshots[max(0, len(snapshots) - 1 - b)] for b in reversed(D.Duel.VIEW_BACK)]
+ for ci in range(len(self.cams)):
+ row = []
+ for sn in sel:
+ q = np.array(sn["qpos"], float)
+ pk = sn.get("played_k", rs["played_k"])
+ if sn["k"] <= pk:
+ q[:3] = [0, 0, -10]
+ row.append(self.tile(ci, q, f"k={sn['k']} t={(sn['k'] - pk) * D.CONTROL_DT:.2f}s",
+ lambda scn: D.Duel._extra_geoms(None, scn), pk))
+ out.append(row)
+ return self.sheet(out)
+
+
+_LOCAL: dict = {} # in-process views (core/local.py: no worker processes)
+
+
+# ================================================================================================ the sport
+class TableTennis:
+ name = "tabletennis"
+ protocol = "realtime"
+ revision = "wallclock-6+duel-wallclock-4+core-0.2"
+ source_dirs = [str(HERE)]
+ workers = ("plan", "render")
+
+ def build(self, cfg):
+ return TTDuel(cfg) if len(cfg.seats) > 1 else TTMatch(cfg)
+
+ def action_layer(self, level):
+ return StrokeLayer() if level == "high" else JointLayer()
+
+ def worker_init(self, kind, seat, cfg):
+ duel = len(cfg.seats) > 1
+ if kind == "plan":
+ return _duel(cfg).Planner(seat) if duel else None
+ if duel:
+ _duel(cfg)
+ v = DuelView(seat)
+ else:
+ v = MatchView()
+ v.tile(0, v.rd.qpos.copy(), "", lambda scn: None, "warm-up") # creates the GL context before the handshake
+ v.cache.clear()
+ return v
+
+ def worker_call(self, obj, kind, job):
+ if kind == "plan":
+ from workers import prepare
+ return prepare(obj, job)
+ if obj is None: # in-process (core/local.py)
+ key = (job["format"], job["seat"])
+ if key not in _LOCAL:
+ _LOCAL[key] = MatchView() if job["format"] == "match" else DuelView(job["seat"])
+ obj = _LOCAL[key]
+ if job["format"] == "match":
+ return {"png": obj.draw(job["snaps"])}
+ return {"png": obj.draw(job["snapshots"], job["rs"])}
+
+ def scene(self, cfg):
+ from renderers.base import Scene
+ return Scene.from_file(SIM / "scene" / ("tt_duel.xml" if len(cfg.seats) > 1 else "tt_scene.xml"))
+
+ def players(self):
+ import builtin_players as bp
+ return {"reference": bp.Reference, "idle": bp.Idle}
+
+ def spec(self, cfg, seat, m):
+ import match
+ cams = [dict(c, fovy_deg=45.0, tile_px=[480, 360], focal_px=434.6, principal_point_px=[240, 180],
+ image_right="forward x up") for c in match.Match.CAM_INFO]
+ out = dict(robot="franka-panda + paddle (MuJoCo Menagerie panda_nohand)", cameras=cams,
+ image="2 rows (behind, side) x 4 columns (camera frames 40 ms apart, oldest left); tile 480 x 360",
+ image_layout=IMAGE_LAYOUT,
+ frame="your robot's base is at (0, -1.75, 0) facing +y; your half is y < 0; table top z = 0, "
+ "|x| <= 0.7625, |y| <= 1.37, net at y = 0 (top z = 0.1525); every position you are given "
+ "or send is in this frame",
+ calls={"observe": "{} -> the state + the newest camera frames (observation.image_png_b64)",
+ "act": (action_high.ACT_CALL if cfg.action_level == "high" else action_low.ACT_CALL),
+ "wait": "{'dt': game seconds, 0 < dt <= 1}"})
+ if isinstance(m, TTMatch):
+ out["match"] = dict(win_points=5, win_by=2, cap_points=7, expedite_returns=13, opponent_level=m.level,
+ serves="the opponent serves every point; you always receive",
+ format="first to 5; from 4:4 lead by 2, up to 7 (at 6:6 the next point wins)")
+ else:
+ D = m.D
+ out["match"] = dict(win_points=D.WIN_POINTS, win_by=D.WIN_BY, cap_points=D.CAP_POINTS,
+ expedite_returns=D.EXPEDITE_RETURNS, first_receiver=D.FIRST_RECEIVER,
+ serves="a neutral machine serves recorded real serves; the receiver changes every point",
+ format=f"first to {D.WIN_POINTS}; from {D.WIN_POINTS - 1}:{D.WIN_POINTS - 1} lead by "
+ f"{D.WIN_BY}, up to {D.CAP_POINTS} (at {D.CAP_POINTS - 1}:{D.CAP_POINTS - 1} "
+ "the next point wins); the receiver changes every point")
+ if cfg.action_level == "low":
+ import robot_model
+ mm = m.R.s.m if isinstance(m, TTMatch) else m.g.m # the duel: robot A's chain (= B's, own frame)
+ out.update(action_interface="joint position targets at 100 Hz; no IK or stroke planner (your own frame: "
+ "the same kinematic chain for both duel seats)",
+ kinematics=action_low.kinematics(mm), limits=action_low.limits(_rows(m).s),
+ robot_model={"robot_only_xml": robot_model.robot_only_xml(),
+ "note": "the arm + paddle cut out of the simulator's scene (MJCF; the mesh files "
+ "are MuJoCo Menagerie panda_nohand's); nothing of the world"})
+ return out
+
+
+SPORT = TableTennis()
diff --git a/scripts/roboolympics/shared/sports/tabletennis/presentation/presentation.toml b/scripts/roboolympics/shared/sports/tabletennis/presentation/presentation.toml
new file mode 100644
index 0000000000..b193733953
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/tabletennis/presentation/presentation.toml
@@ -0,0 +1,15 @@
+# Appearance of tabletennis' robots (docs/framework_zh.md §3.1, renderer rule 6; renderers/presentation/__init__.py):
+# the Franka Panda's visual meshes on the arm's bodies, same kinematics. Since revision wallclock-6 / duel-wallclock-4
+# the players' images use it too (`players`): tools/sportlib bundles this directory and the 25k level of detail of the
+# meshes (renderers/presentation/lod.json, sha256-pinned, licence kept) into the simulator, so they are part of
+# source_sha; spectator re-renders from a checkout use the full meshes.
+[presentation]
+version = 2
+label = "Franka Panda visual meshes (MuJoCo Menagerie)"
+players = "25k" # the players' images: the meshes decimated to ~25k triangles per arm
+
+[[presentation.robot]]
+model = "franka_emika_panda" # renderers/presentation/menagerie.json (fetched, sha256-pinned)
+bodies = '^link(?P<n>[0-7])(?P<b>_b)?$'
+body = "link{n}"
+hide = "mesh" # the arm's collision meshes move to the hidden group 3
diff --git a/scripts/roboolympics/shared/sports/tabletennis/robot_model.py b/scripts/roboolympics/shared/sports/tabletennis/robot_model.py
new file mode 100644
index 0000000000..4df3d6f1e3
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/tabletennis/robot_model.py
@@ -0,0 +1,65 @@
+"""The robot's own model for the low-level seat (docs/benchmarks/roboolympics-modes.md §2.3, information boundary):
+`robot_only.xml`, the arm + paddle cut out of the match simulator's scene (sim/scene/tt_scene.xml),
+so it can never drift from the simulated arm. The low action level's /spec carries it (robot_model.robot_only_xml);
+tests/test_tabletennis.py checks that its forward kinematics equal the simulator's and that it holds nothing of the
+world. (The legacy seat image also installed it with MuJoCo under /opt/robot; tools/generate.py has no per-level seat
+files yet.)
+
+Kept: the compiler and physics options, the arm's defaults, its meshes, the body tree from link0 (mount pose in the
+world frame, as `game spec` documents) to the paddle (joints, ranges, armature, damping, masses, inertias, geoms, the
+blade-centre site), the arm's own contact exclusions and its 7 torque motors.
+Dropped: everything that is not the robot - ball, table, net, floor, pedestal, target zone, lights, textures,
+materials, visual settings, the ball-table and ball-paddle contact pairs - and in a duel the other robot.
+"""
+from __future__ import annotations
+
+import copy
+import xml.etree.ElementTree as ET
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+SCENE = HERE / "sim" / "scene" / "tt_scene.xml"
+ROBOT_ROOT = "link0"
+
+HEADER = """
+ The robot's own model (generated from the match simulator's scene by sports/tabletennis/robot_model.py;
+ do not edit): MuJoCo Menagerie Franka Panda (panda_nohand, Apache-2.0, assets/LICENSE.menagerie-franka) with the
+ table-tennis paddle bolted to the flange, mounted in the world frame of the match (base at (0, -1.75, 0), facing +y).
+ It holds the arm only: kinematic tree, joint ranges, armature and damping, masses and inertias, collision meshes,
+ the paddle (blade centre = site paddle_center, face normal = the paddle body's local +x axis) and the 7 torque
+ motors. Nothing of the world is in it: no ball, table, net, floor or opponent. The joint controller that tracks
+ your targets (PD + gravity/Coriolis compensation, 1 kHz) is documented in `game spec` (limits.controller).
+"""
+
+
+def robot_only_xml(scene: Path = SCENE) -> str:
+ src = ET.parse(scene).getroot()
+ out = ET.Element("mujoco", {"model": "franka_paddle_robot_only"})
+ out.append(ET.Comment(HEADER.rstrip() + "\n"))
+ for tag in ("compiler", "option"):
+ el = src.find(tag)
+ if el is not None:
+ out.append(copy.deepcopy(el))
+ out.append(copy.deepcopy(src.find("default")))
+ asset = ET.SubElement(out, "asset")
+ for m in src.find("asset").findall("mesh"):
+ asset.append(copy.deepcopy(m))
+ wb = ET.SubElement(out, "worldbody")
+ robot = [b for b in src.find("worldbody") if b.tag == "body" and b.get("name") == ROBOT_ROOT]
+ assert len(robot) == 1, "the scene must hold exactly one robot rooted at link0"
+ wb.append(copy.deepcopy(robot[0]))
+ robot_bodies = {b.get("name") for b in robot[0].iter("body")}
+ con = ET.SubElement(out, "contact")
+ for el in src.find("contact"):
+ if el.tag == "exclude" and {el.get("body1"), el.get("body2")} <= robot_bodies:
+ con.append(copy.deepcopy(el))
+ out.append(copy.deepcopy(src.find("actuator")))
+ ET.indent(out, space=" ")
+ return ET.tostring(out, encoding="unicode") + "\n"
+
+
+def mesh_files(scene: Path = SCENE) -> list[Path]:
+ """The mesh files robot_only.xml references, plus the Menagerie licence."""
+ src = ET.parse(scene).getroot()
+ d = scene.parent / src.find("compiler").get("meshdir", ".")
+ return [d / m.get("file") for m in src.find("asset").findall("mesh")] + [d / "LICENSE.menagerie-franka"]
diff --git a/scripts/roboolympics/shared/sports/tabletennis/seat/robot_only.xml b/scripts/roboolympics/shared/sports/tabletennis/seat/robot_only.xml
new file mode 100644
index 0000000000..a1b0be279e
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/tabletennis/seat/robot_only.xml
@@ -0,0 +1,94 @@
+<mujoco model="franka_paddle_robot_only">
+ <!--
+ The robot's own model (generated from the match simulator's scene by sports/tabletennis/robot_model.py;
+ do not edit): MuJoCo Menagerie Franka Panda (panda_nohand, Apache-2.0, assets/LICENSE.menagerie-franka) with the
+ table-tennis paddle bolted to the flange, mounted in the world frame of the match (base at (0, -1.75, 0), facing +y).
+ It holds the arm only: kinematic tree, joint ranges, armature and damping, masses and inertias, collision meshes,
+ the paddle (blade centre = site paddle_center, face normal = the paddle body's local +x axis) and the 7 torque
+ motors. Nothing of the world is in it: no ball, table, net, floor or opponent. The joint controller that tracks
+ your targets (PD + gravity/Coriolis compensation, 1 kHz) is documented in `game spec` (limits.controller).
+-->
+ <compiler angle="radian" meshdir="assets" autolimits="true" />
+ <option density="1.225" viscosity="1.8e-5" wind="0 0 0" integrator="implicitfast" timestep="0.001" cone="elliptic" impratio="10" />
+ <default>
+ <default class="panda">
+ <joint armature="0.1" damping="1" axis="0 0 1" range="-2.8973 2.8973" />
+ <geom type="mesh" rgba="0.92 0.93 0.94 1" group="2" />
+ <motor ctrlrange="-87 87" />
+ </default>
+ </default>
+ <asset>
+ <mesh name="link0_c" file="link0.stl" />
+ <mesh name="link1_c" file="link1.stl" />
+ <mesh name="link2_c" file="link2.stl" />
+ <mesh name="link3_c" file="link3.stl" />
+ <mesh name="link4_c" file="link4.stl" />
+ <mesh name="link5_c0" file="link5_collision_0.obj" />
+ <mesh name="link5_c1" file="link5_collision_1.obj" />
+ <mesh name="link5_c2" file="link5_collision_2.obj" />
+ <mesh name="link6_c" file="link6.stl" />
+ <mesh name="link7_c" file="link7.stl" />
+ </asset>
+ <worldbody>
+ <body name="link0" childclass="panda" pos="0 -1.75 0" quat="0.7071068 0 0 0.7071068">
+ <inertial mass="0.629769" pos="-0.041018 -0.00014 0.049974" fullinertia="0.00315 0.00388 0.004285 8.2904e-7 0.00015 8.2299e-6" />
+ <geom name="link0_c" mesh="link0_c" />
+ <body name="link1" pos="0 0 0.333">
+ <inertial mass="4.970684" pos="0.003875 0.002081 -0.04762" fullinertia="0.70337 0.70661 0.0091170 -0.00013900 0.0067720 0.019169" />
+ <joint name="joint1" />
+ <geom name="link1_c" mesh="link1_c" />
+ <body name="link2" quat="1 -1 0 0">
+ <inertial mass="0.646926" pos="-0.003141 -0.02872 0.003495" fullinertia="0.0079620 2.8110e-2 2.5995e-2 -3.925e-3 1.0254e-2 7.04e-4" />
+ <joint name="joint2" range="-1.7628 1.7628" />
+ <geom name="link2_c" mesh="link2_c" />
+ <body name="link3" pos="0 -0.316 0" quat="1 1 0 0">
+ <joint name="joint3" />
+ <inertial mass="3.228604" pos="2.7518e-2 3.9252e-2 -6.6502e-2" fullinertia="3.7242e-2 3.6155e-2 1.083e-2 -4.761e-3 -1.1396e-2 -1.2805e-2" />
+ <geom name="link3_c" mesh="link3_c" />
+ <body name="link4" pos="0.0825 0 0" quat="1 1 0 0">
+ <inertial mass="3.587895" pos="-5.317e-2 1.04419e-1 2.7454e-2" fullinertia="2.5853e-2 1.9552e-2 2.8323e-2 7.796e-3 -1.332e-3 8.641e-3" />
+ <joint name="joint4" range="-3.0718 -0.0698" />
+ <geom name="link4_c" mesh="link4_c" />
+ <body name="link5" pos="-0.0825 0.384 0" quat="1 -1 0 0">
+ <inertial mass="1.225946" pos="-1.1953e-2 4.1065e-2 -3.8437e-2" fullinertia="3.5549e-2 2.9474e-2 8.627e-3 -2.117e-3 -4.037e-3 2.29e-4" />
+ <joint name="joint5" />
+ <geom name="link5_c0" mesh="link5_c0" />
+ <geom name="link5_c1" mesh="link5_c1" />
+ <geom name="link5_c2" mesh="link5_c2" />
+ <body name="link6" quat="1 1 0 0">
+ <inertial mass="1.666555" pos="6.0149e-2 -1.4117e-2 -1.0517e-2" fullinertia="1.964e-3 4.354e-3 5.433e-3 1.09e-4 -1.158e-3 3.41e-4" />
+ <joint name="joint6" range="-0.0175 3.7525" />
+ <geom name="link6_c" mesh="link6_c" />
+ <body name="link7" pos="0.088 0 0" quat="1 1 0 0">
+ <inertial mass="7.35522e-01" pos="1.0517e-2 -4.252e-3 6.1597e-2" fullinertia="1.2516e-2 1.0027e-2 4.815e-3 -4.28e-4 -1.196e-3 -7.41e-4" />
+ <joint name="joint7" />
+ <geom name="link7_c" mesh="link7_c" />
+ <body name="paddle" pos="0 0 0.107">
+ <geom name="paddle_handle" type="capsule" fromto="0 0 0 0 0 0.06" size="0.014" mass="0.05" rgba="0.55 0.35 0.2 1" group="2" />
+ <geom name="paddle_blade" type="box" pos="0 0 0.14" size="0.0075 0.075 0.075" mass="0.09" rgba="0.75 0.08 0.08 1" group="2" />
+ <site name="paddle_center" pos="0 0 0.14" size="0.005" rgba="1 1 1 1" group="4" />
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </worldbody>
+ <contact>
+ <exclude body1="link0" body2="link1" />
+ <exclude body1="link7" body2="paddle" />
+ <exclude body1="link6" body2="paddle" />
+ </contact>
+ <actuator>
+ <motor class="panda" name="motor1" joint="joint1" />
+ <motor class="panda" name="motor2" joint="joint2" />
+ <motor class="panda" name="motor3" joint="joint3" />
+ <motor class="panda" name="motor4" joint="joint4" />
+ <motor class="panda" name="motor5" joint="joint5" ctrlrange="-12 12" />
+ <motor class="panda" name="motor6" joint="joint6" ctrlrange="-12 12" />
+ <motor class="panda" name="motor7" joint="joint7" ctrlrange="-12 12" />
+ </actuator>
+</mujoco>
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/action_high.py b/scripts/roboolympics/shared/sports/tabletennis/sim/action_high.py
new file mode 100644
index 0000000000..ad29366e37
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/tabletennis/sim/action_high.py
@@ -0,0 +1,79 @@
+"""High-level action plugin (action level `high`, the switch on): the player gives the paddle state at contact; the
+plugin plans the stroke with match.Match's planner (IK, a joint-speed-limited swing, rehearsals on a simulator copy,
+seeded execution scatter) and hands the swing to the arm command layer (core.py) as a `traj` command followed by a
+slew back to the ready pose at 60 % of the speed limits. With no stroke under way the arm returns to / holds the ready
+pose. This reproduces the original high-level tasks target for target (scripts/olympiad/tabletennis/test_modes.py).
+"""
+from __future__ import annotations
+
+import numpy as np
+
+from rcb_tt import CONTROL_DT
+
+LEVEL = "high"
+REST = 0.6 # rest command: slew to the ready pose at 60 % of the joint speed limits
+ACT_CALL = "{'type':'act','t':T_from_now,'pos':[x,y,z],'normal':[nx,ny,nz],'vel':[vx,vy,vz]} or {'type':'none'}"
+OBSERVE_CALL = "the newest camera frames (2 x 4), heard bounces, time, your arm and command"
+
+
+def validate(body: dict, core) -> dict | str:
+ if body.get("type") == "none":
+ return {"type": "none"}
+ try:
+ T = float(body["t"]); pos = [float(x) for x in body["pos"]]
+ nrm = [float(x) for x in body["normal"]]; vel = [float(x) for x in body["vel"]]
+ except Exception: # noqa: BLE001
+ return ("act needs T (s from now until contact), pos [x, y, z] (blade centre at contact), normal [nx, ny, nz] "
+ "(blade face normal) and vel [vx, vy, vz] (blade velocity at contact, m/s); or `act none`")
+ if len(pos) != 3 or len(nrm) != 3 or len(vel) != 3 or not np.all(np.isfinite(pos + nrm + vel + [T])):
+ return "pos, normal and vel must have 3 finite numbers each"
+ if np.linalg.norm(nrm) < 1e-6:
+ return "normal must be a non-zero vector"
+ if not (0.0 < T <= 2.5):
+ return "T must be in (0, 2.5] s from now"
+ if not (abs(pos[0]) <= 1.2 and -2.5 <= pos[1] <= -0.5 and 0.0 <= pos[2] <= 1.2):
+ return "pos out of range: |x| <= 1.2, -2.5 <= y <= -0.5, 0 <= z <= 1.2"
+ if np.linalg.norm(vel) > 8.0:
+ return "vel too large: |vel| <= 8 m/s"
+ return {"type": "act", "t": T, "pos": pos, "normal": nrm, "vel": vel}
+
+
+def apply(R, dec: dict) -> dict:
+ if dec["type"] == "none": # cancel: the arm returns to the ready pose
+ R.cmd = R.rest_command()
+ R._last_act = None
+ R.contact_k = R.k
+ return {"stroke": "cleared: the arm returns to the ready pose"}
+ T = float(dec["t"])
+ t_hit = (R.k - R.leg["launch"]) * CONTROL_DT + T
+ R._ik_seed = R._planned_hit if R.traj_active() else None
+ plan, info = R.plan_paddle(t_hit, dec["pos"], dec["normal"], dec["vel"])
+ info["T_from_now"] = round(T, 4)
+ if plan: # the swing, then back to the ready pose
+ res = R.submit({"type": "traj", "k0": R.k, "q": plan, "then": R.rest_command()})
+ assert "command" in res, res # the planner's swing starts at the target in force
+ R.shots.append({"k": R.k, "leg": R.n_our_legs, **{k: info[k] for k in info if k != "paddle_vel_delivered"}})
+ if plan:
+ R.contact_k = R.k + info["n_swing_steps_available"]
+ R._last_act = info
+ return info
+
+
+def reply(dec: dict, info: dict) -> dict:
+ if dec["type"] == "none":
+ return {"command": "cleared: the arm returns to the ready pose"}
+ return {"stroke": {k: info.get(k) for k in ("stroke", "n_swing_steps_available", "n_swing_steps", "ik_residual",
+ "blade_error_m", "normal_error_deg", "speed_scale",
+ "paddle_vel_delivered", "T_from_now")}}
+
+
+def state(R) -> dict:
+ la = getattr(R, "_last_act", None)
+ return {"command": ({"contact_in_s": round(max(0, R.contact_k - R.k) * CONTROL_DT, 3),
+ "phase": "approach" if R.k < R.contact_k else "follow_through", "pos": la.get("paddle_pos"),
+ "normal": la.get("paddle_normal"), "vel": la.get("paddle_vel"), "stroke": la.get("stroke")}
+ if R.traj_active() and la else "none (the arm returns to / holds the ready pose)")}
+
+
+def spec(R) -> dict:
+ return {}
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/action_low.py b/scripts/roboolympics/shared/sports/tabletennis/sim/action_low.py
new file mode 100644
index 0000000000..7cfe8deae9
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/tabletennis/sim/action_low.py
@@ -0,0 +1,130 @@
+"""Low-level action plugin (action level `low`, the high-level switch off): the player's commands go straight to the
+arm command layer (arm_commands.py); nothing plans for it (no IK, no stroke planner, no rehearsal, no return to a ready pose,
+no execution scatter). The robot's own joint controller (PD + gravity/Coriolis compensation at 1 kHz, torque limits;
+rcb_tt.Session.step) tracks the targets. `spec` documents the robot's kinematic chain, limits and controller.
+
+Commands (each replaces the previous one when it takes effect, at the start of the next control step after it
+arrives):
+ traj {"type": "traj", "k0": K0, "q": [[q1..q7], ...]} 1..MAX_ROWS rows; row i is the joint target of control
+ step K0 + i. Passed rows are skipped; before K0 the current target is held; after the last row it is held.
+ Rows must lie in the joint ranges and consecutive rows may differ by at most VEL_LIMIT x 10 ms per joint
+ (HTTP 400). The first row used must be within that limit of the target in force (else rejected, arm_commands.py).
+ slew {"type": "slew", "q": [q1..q7], "speed": F} every joint independently towards q at F x its speed limit.
+ hold {"type": "hold"}
+At the end of a point the command is cleared: the arm holds its targets.
+"""
+from __future__ import annotations
+
+import numpy as np
+
+import mujoco as mj
+from arm_commands import STEP_LIM
+from rcb_tt import KD, KP, TORQUE_LIMIT, VEL_LIMIT
+
+LEVEL = "low"
+REST = None # rest command: hold
+MAX_ROWS = 300 # 3 s of targets per command
+CHAIN = ["link0", "link1", "link2", "link3", "link4", "link5", "link6", "link7", "paddle"]
+ACT_CALL = ("{'type':'traj','k0':K0,'q':[[7 joint targets], ...]} (row i = target of control step K0+i, <= 300 rows) "
+ "| {'type':'slew','q':[7],'speed':F} | {'type':'hold'}")
+OBSERVE_CALL = "the newest camera frames (2 x 4), heard bounces, time, your arm (q, qd, q_target) and command"
+
+
+def validate(body: dict, core) -> dict | str:
+ low, high = core.s.JOINT_LOW, core.s.JOINT_HIGH
+ t = body.get("type")
+ if t == "hold":
+ return {"type": "hold"}
+ if t == "slew":
+ try:
+ q = [float(x) for x in body["q"]]
+ speed = float(body.get("speed", 1.0))
+ except Exception: # noqa: BLE001
+ return "slew needs q: 7 joint angles (rad) and optionally speed in (0, 1]"
+ if len(q) != 7 or not np.all(np.isfinite(q)):
+ return "q must be 7 finite joint angles (rad)"
+ if not (0.0 < speed <= 1.0):
+ return "speed must be in (0, 1] (fraction of each joint's speed limit)"
+ if np.any(np.asarray(q) < low) or np.any(np.asarray(q) > high):
+ return f"q outside the joint ranges: low {np.round(low, 4).tolist()}, high {np.round(high, 4).tolist()}"
+ return {"type": "slew", "q": q, "speed": speed}
+ if t == "traj":
+ try:
+ k0 = body["k0"]
+ if type(k0) is not int:
+ raise TypeError
+ Q = np.asarray(body["q"], dtype=float)
+ except Exception: # noqa: BLE001
+ return "traj needs k0 (an integer control step) and q: a list of rows of 7 joint targets (rad)"
+ if Q.ndim != 2 or Q.shape[1] != 7 or not (1 <= len(Q) <= MAX_ROWS) or not np.all(np.isfinite(Q)):
+ return f"q must be 1..{MAX_ROWS} rows of 7 finite joint targets"
+ if k0 < 0:
+ return "k0 must be >= 0"
+ if np.any(Q < low) or np.any(Q > high):
+ r, j = np.argwhere((Q < low) | (Q > high))[0]
+ return f"row {int(r)}, joint {int(j) + 1}: {Q[r, j]:.5f} outside its range [{low[j]:.4f}, {high[j]:.4f}]"
+ if len(Q) > 1:
+ dq = np.abs(np.diff(Q, axis=0))
+ if (dq > STEP_LIM).any():
+ r, j = np.argwhere(dq > STEP_LIM)[0]
+ return (f"rows {int(r)}->{int(r) + 1}, joint {int(j) + 1}: moves {dq[r, j]:.5f} rad in one 10 ms step "
+ f"(limit {STEP_LIM[j]:.5f} = {VEL_LIMIT[j]} rad/s)")
+ return {"type": "traj", "k0": int(k0), "q": Q.tolist()}
+ return "act type must be traj, slew or hold (this task's action level is low: joint targets)"
+
+
+def apply(R, dec: dict) -> dict:
+ return R.submit(dec)
+
+
+def reply(dec: dict, info: dict) -> dict:
+ return {"result": info}
+
+
+def state(R) -> dict:
+ st = R.s.state()
+ return {"qd": st["qd"].round(4).tolist(), "q_target": st["q_target"].round(6).tolist(),
+ "command": R.command_state()}
+
+
+def kinematics(m: mj.MjModel) -> dict:
+ """The robot's kinematic model (its own body, not world state): the body chain from the world to the paddle."""
+ bodies = []
+ for name in CHAIN:
+ b = mj.mj_name2id(m, mj.mjtObj.mjOBJ_BODY, name)
+ j = [i for i in range(m.njnt) if m.jnt_bodyid[i] == b]
+ e = {"body": name, "pos_in_parent": [round(float(x), 6) for x in m.body_pos[b]],
+ "quat_in_parent_wxyz": [round(float(x), 7) for x in m.body_quat[b]]}
+ if j:
+ e["joint"] = mj.mj_id2name(m, mj.mjtObj.mjOBJ_JOINT, j[0])
+ e["joint_axis_in_body"] = [float(x) for x in m.jnt_axis[j[0]]]
+ e["joint_pos_in_body"] = [float(x) for x in m.jnt_pos[j[0]]]
+ bodies.append(e)
+ site = mj.mj_name2id(m, mj.mjtObj.mjOBJ_SITE, "paddle_center")
+ return {
+ "chain": bodies,
+ "rule": ("world pose of a body = parent pose x translate(pos_in_parent) x rotate(quat_in_parent_wxyz); a body "
+ "with a joint then rotates by the joint angle q about joint_axis_in_body (through joint_pos_in_body). "
+ "The parent of link0 is the world."),
+ "blade_center_in_paddle": [round(float(x), 6) for x in m.site_pos[site]],
+ "blade_normal": "the paddle body's local +x axis (the face normal); the handle runs along its local +z",
+ "blade_half_size_m": [0.0075, 0.075, 0.075],
+ }
+
+
+def limits(s) -> dict:
+ return {"joint_low_rad": [round(float(x), 4) for x in s.JOINT_LOW],
+ "joint_high_rad": [round(float(x), 4) for x in s.JOINT_HIGH],
+ "joint_speed_limit_rad_s": VEL_LIMIT.tolist(), "torque_limit_nm": TORQUE_LIMIT.tolist(),
+ "max_target_step_rad": [round(float(x), 6) for x in STEP_LIM],
+ "controller": {"kp": KP.tolist(), "kd": KD.tolist(),
+ "law": "tau = kp (q_des - q) + kd (qd_des - qd) + gravity/Coriolis compensation, clipped "
+ "at the torque limits, at 1 kHz; q_des interpolates linearly from the previous "
+ "target to the new one over the 10 ms step and qd_des is their difference / 10 ms"},
+ "ready_pose_rad": [round(float(x), 5) for x in s.inst["q0"]],
+ "max_rows_per_command": MAX_ROWS}
+
+
+def spec(R) -> dict:
+ return {"action_interface": "joint position targets at 100 Hz; no IK or stroke planner",
+ "kinematics": kinematics(R.s.m), "limits": limits(R.s)}
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/arm_commands.py b/scripts/roboolympics/shared/sports/tabletennis/sim/arm_commands.py
new file mode 100644
index 0000000000..b5b8320dc7
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/tabletennis/sim/arm_commands.py
@@ -0,0 +1,107 @@
+"""The one table-tennis simulator core of every play mode and action level (docs/benchmarks/roboolympics-modes.md).
+
+Layers, bottom up:
+ physics + referee + opponent rcb_tt.Session, rally.Rally, match.Match (unchanged; Match also holds the stroke
+ planner the high-level plugin uses);
+ arm command layer (this file) the only source of the arm's joint targets: one command at a time -
+ `traj` (joint position targets stamped with absolute control steps, optionally
+ followed by another command), `slew` (every joint towards q at a fraction of its
+ speed limit) or `hold`; a command whose first used target jumps by more than one
+ step's speed limit from the target in force is rejected (the previous one goes on);
+ at the end of a point the command falls back to the level's rest command;
+ action plugin action_low.py (switch off: the player's commands go straight to this layer) or
+ action_high.py (switch on: the paddle state at contact -> IK + stroke planner ->
+ a `traj` command, then a slew back to the ready pose).
+Live service and replay both drive the match only through Core.apply (the plugin) and Core.rt_advance.
+"""
+from __future__ import annotations
+
+import numpy as np
+
+import match
+from rcb_tt import CONTROL_DT, VEL_LIMIT
+
+STEP_LIM = VEL_LIMIT * CONTROL_DT # rad per control step and joint (the arm's speed limits)
+
+
+class Core(match.Match):
+ """match.Match whose arm targets come from the command layer; `plugin` is action_low or action_high."""
+
+ def __init__(self, level: int = 1, plugin=None, lv_override: dict | None = None):
+ super().__init__(level, lv_override)
+ if plugin is None:
+ import action_high as plugin
+ self.plugin = plugin
+ self.n_rejected = 0
+ self.cmd = self.rest_command()
+
+ # ------------------------------------------------------------------ the command layer
+ def rest_command(self):
+ """What the arm does when no command is in force: the plugin's rest (hold, or a slew to the ready pose)."""
+ r = self.plugin.REST
+ return None if r is None else {"type": "slew", "q": np.asarray(self.s.inst["q0"], float), "speed": r}
+
+ def traj_active(self) -> bool:
+ c = self.cmd
+ return c is not None and c["type"] == "traj" and self.k - c["k0"] < len(c["q"])
+
+ def _arm_target(self):
+ c = self.cmd
+ if c is not None and c["type"] == "traj":
+ i = self.k - c["k0"]
+ if i >= len(c["q"]) and c.get("then") is not None:
+ self.cmd = c = c["then"] # e.g. the high level's return to the ready pose
+ elif i < 0:
+ return self.s._target.copy()
+ else:
+ return c["q"][min(i, len(c["q"]) - 1)].copy()
+ tgt = self.s._target
+ if c is None:
+ return tgt.copy()
+ lim = STEP_LIM * c["speed"] # slew
+ return tgt + np.clip(c["q"] - tgt, -lim, lim)
+
+ def submit(self, cmd: dict) -> dict:
+ """At the start of control step self.k: `cmd` (validated) becomes the command in force, or is rejected."""
+ if cmd["type"] == "hold":
+ self.cmd = None
+ return {"command": "hold"}
+ if cmd["type"] == "slew":
+ self.cmd = {"type": "slew", "q": np.asarray(cmd["q"], float), "speed": float(cmd["speed"])}
+ return {"command": "slew"}
+ Q = np.asarray(cmd["q"], float)
+ k0 = int(cmd["k0"])
+ j0 = max(0, self.k - k0)
+ if j0 >= len(Q):
+ self.n_rejected += 1
+ return {"rejected": f"stale: the trajectory's last row was for step {k0 + len(Q) - 1}; this is step {self.k}"}
+ jump = np.abs(Q[j0] - self.s._target)
+ if (jump > STEP_LIM).any():
+ j = int(np.argmax(jump / STEP_LIM))
+ self.n_rejected += 1
+ return {"rejected": f"discontinuous: row {j0} (step {self.k}) moves joint {j + 1} by {jump[j]:.5f} rad from "
+ f"the target in force (limit {STEP_LIM[j]:.5f} per step); the previous command goes on",
+ "first_row_used": j0}
+ self.cmd = {"type": "traj", "q": Q, "k0": k0, "then": cmd.get("then")}
+ return {"command": "traj", "first_row_used": j0, "rows_left": int(len(Q) - j0)}
+
+ def rt_advance(self, n_steps: int):
+ n0 = len(self.points)
+ out = super().rt_advance(n_steps)
+ if len(self.points) > n0:
+ self.cmd = self.rest_command() # a command does not carry over to the next point
+ return out
+
+ def apply(self, dec: dict) -> dict:
+ """A validated player command (live: when it takes effect; replay: at its logged step)."""
+ return self.plugin.apply(self, dec)
+
+ def command_state(self) -> dict | str:
+ c = self.cmd
+ if c is None:
+ return "hold"
+ if c["type"] == "slew":
+ return {"type": "slew", "q": [round(float(x), 5) for x in c["q"]], "speed": c["speed"]}
+ i = self.k - c["k0"]
+ return {"type": "traj", "k0": c["k0"], "rows": int(len(c["q"])),
+ "next_row": int(i), "rows_left": int(max(0, len(c["q"]) - max(i, 0)))}
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/duel.py b/scripts/roboolympics/shared/sports/tabletennis/sim/duel.py
new file mode 100644
index 0000000000..be6a2a1119
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/tabletennis/sim/duel.py
@@ -0,0 +1,570 @@
+"""Table-tennis duel: two robots, two models. One game: first to 5 points; from 4:4 a player must lead by 2, capped at
+7 (at 6:6 the next point wins), i.e. ITTF 2.11.1 scaled down.
+
+Robot A (y < 0, facing +y) and robot B (y > 0, facing -y) are identical Franka + paddle arms in one MuJoCo scene
+(scene/tt_duel.xml, made by mk_scene2.py). Every point starts with a serve machine: a recorded DeepMind serve
+(the match task's pool) towards the receiver, who changes every point (FIRST_RECEIVER receives the first; lets do not
+count); then the two players rally.
+
+Each player sees and acts in its OWN frame, the frame of the single-player tasks (its robot at (0, -1.75, 0) facing
++y, its half y < 0): for B every position is mirrored, (x, y, z) -> (-x, -y, z). So both players get the same
+instruction, the same cameras (behind and beside their robot) and the same shot interface; the shot of either side is
+planned by the match task's stroke controller on a single-robot planning copy in that player's frame (the joint
+spaces of the two robots coincide).
+
+Rules (the referee is a deterministic function of the contact events, evaluated inside every control step, so the
+recorded joint targets of both robots replay the match bit-exactly):
+ - the serve bounces on the server's (machine's) half, then on the receiver's half; the receiver must hit it;
+ - after a hit by P the ball must first touch the table on the other half; the other player must hit it after
+ exactly one bounce on its half;
+ - the player to hit loses the point if it lets the ball bounce twice, hits it before it bounced (volley), misses it
+ (the ball reaches the floor after its bounce), or the ball hits its arm while over or travelling towards its half
+ (obstruction, ITTF 2.10.1.6); the hitter loses the point if its ball touches its own half, the floor, the other
+ robot beyond the end line or beside the table (ITTF 2.10.1.4) or anything else before the other half; a return
+ that touches the net and then the other half is good and play continues (ITTF 2.7.1); a robot whose arm or paddle
+ touches the table, net or floor loses the point; touching the ball twice loses the point;
+ - a machine serve that touches the net, an irregular machine serve, or faults by both players at once are lets;
+ - expedite rule (ITTF 2.15.4, applied from the first point): if the receiver makes 13 good returns in a rally, the
+ receiver wins the point. This bounds every rally (at most 26 hits) and so the match (at most 13 points + lets).
+"""
+from __future__ import annotations
+
+import io
+import json
+import os
+from collections import deque
+from pathlib import Path
+
+import numpy as np
+
+import mujoco as mj
+import match
+import rally
+import rcb_tt
+from rally import BallModel, world_spin # noqa: F401
+from rcb_tt import CONTROL_DT, VEL_LIMIT, KP, KD, SUBSTEPS, MERGE_GAP_S, JOINTS
+
+HERE = Path(__file__).resolve().parent
+SCENE2 = HERE / "scene" / "tt_duel.xml"
+SERVES = match.SERVES
+Q0 = rcb_tt.load_instance(str(rally.INSTANCE))["q0"]
+WIN_POINTS = 5 # first to 5 ...
+WIN_BY = 2 # ... but from 4:4 a player must lead by 2 ...
+CAP_POINTS = 7 # ... up to 7 (at 6:6 the next point wins)
+EXPEDITE_RETURNS = 13 # ITTF 2.15.4: the receiver's 13th good return in a rally wins it the point
+MAX_POINTS_WITH_LETS = 40 # guard: 13 scoring points at most, so this needs 27+ lets; then the player ahead wins,
+ # at a level score the player who won the last point (no draws)
+READY_STEPS = 80
+CAM_EVERY = 2
+DECISION_AFTER_SERVE_BOUNCE = 5
+DECISION_AFTER_HIT = 6
+ADJUST_FRAMES = 3
+DEAD_STEPS = 250 # 2.5 s after the last hit without a decisive event: the player to hit loses
+SEED = int(os.environ.get("DUEL_SEED", "1")) # the serve-machine sequence and both seats' execution scatter
+REVISION = "duel-wallclock-3"
+FIRST_RECEIVER = os.environ.get("FIRST_RECEIVER", "A")
+if FIRST_RECEIVER not in ("A", "B"):
+ raise ValueError("FIRST_RECEIVER must be A or B")
+SIDES = ("A", "B")
+OTHER = {"A": "B", "B": "A"}
+MIR = np.array([-1.0, -1.0, 1.0])
+
+
+def mir(v):
+ return np.asarray(v, float) * MIR
+
+
+def match_winner(score):
+ """The winner ('A' / 'B') of a game with this score, else None: first to WIN_POINTS with a lead of WIN_BY, or the
+ first to CAP_POINTS."""
+ for s in SIDES:
+ a, b = score[s], score[OTHER[s]]
+ if a >= CAP_POINTS or (a >= WIN_POINTS and a - b >= WIN_BY):
+ return s
+ return None
+
+
+class Planner(match.Match):
+ """The match task's stroke controller on a single-robot copy, synced to one side's state in that side's frame."""
+
+ def __init__(self, side: str):
+ self.side = side
+ self.level = 0
+ self.lv = {"seed": SEED + (0 if side == "A" else 1)}
+ self.s = rcb_tt.Session(instance=str(rally.INSTANCE), scene=str(rally.SCENE))
+ self.bm = BallModel()
+ self._twin = None
+ self._ik_seed = None
+ self._planned_hit = None
+ self.n_our_legs = 0
+ self.leg = {"launch": 0}
+
+
+
+class Duel:
+ def __init__(self):
+ m = self.m = mj.MjModel.from_xml_path(str(SCENE2))
+ d = self.d = mj.MjData(m)
+ jid = lambda n: mj.mj_name2id(m, mj.mjtObj.mjOBJ_JOINT, n)
+ self.qadr = {s: np.array([m.jnt_qposadr[jid(j + sfx)] for j in JOINTS]) for s, sfx in (("A", ""), ("B", "_b"))}
+ self.vadr = {s: np.array([m.jnt_dofadr[jid(j + sfx)] for j in JOINTS]) for s, sfx in (("A", ""), ("B", "_b"))}
+ aid = lambda n: mj.mj_name2id(m, mj.mjtObj.mjOBJ_ACTUATOR, n)
+ self.aadr = {s: np.array([aid(f"motor{i}{sfx}") for i in range(1, 8)]) for s, sfx in (("A", ""), ("B", "_b"))}
+ self.lo = m.actuator_ctrlrange[:, 0].copy(); self.hi = m.actuator_ctrlrange[:, 1].copy()
+ self.JLOW = m.jnt_range[[jid(j) for j in JOINTS], 0].copy(); self.JHIGH = m.jnt_range[[jid(j) for j in JOINTS], 1].copy()
+ gid = lambda n: mj.mj_name2id(m, mj.mjtObj.mjOBJ_GEOM, n)
+ self.g_ball, self.g_table, self.g_net, self.g_floor = gid("geom_ball"), gid("geom_table"), gid("geom_net"), gid("floor")
+ self.g_blade = {"A": gid("paddle_blade"), "B": gid("paddle_blade_b")}
+ self.robot_geoms = {s: self._subtree_geoms("link0" + sfx) for s, sfx in (("A", ""), ("B", "_b"))}
+ # Serve fix (2026-09-29): the recorded serves were made for a table with nobody at the serving end. In a duel the
+ # server-side robot stands there, so during the serve (until the ball's bounce on the receiver's half) its geoms
+ # are "ghosts" for the ball: collision bit 2 only, which the table, net and floor also carry (the arm still
+ # collides with them, so the arm-on-table rule holds) but the ball (bit 1) does not.
+ self._ghost_geoms = {s: sorted(set(self.robot_geoms[s]) | {self.g_blade[s]}) for s in SIDES} # the blade is its own body
+ self._mask0 = {g: (int(m.geom_contype[g]), int(m.geom_conaffinity[g])) for s in SIDES for g in self._ghost_geoms[s]}
+ for g in (self.g_table, self.g_net, self.g_floor):
+ m.geom_contype[g] |= 2; m.geom_conaffinity[g] |= 2
+ self.ghost = {s: False for s in SIDES}
+ # the ball-blade contacts are explicit <pair>s (own restitution), which ignore the masks: switch them off by margin
+ self._blade_pairs = {s: [i for i in range(m.npair) if {int(m.pair_geom1[i]), int(m.pair_geom2[i])} == {self.g_ball, self.g_blade[s]}]
+ for s in SIDES}
+ self._pair_margin0 = {i: float(m.pair_margin[i]) for s in SIDES for i in self._blade_pairs[s]}
+ self.site_paddle = {s: mj.mj_name2id(m, mj.mjtObj.mjOBJ_SITE, "paddle_center" + sfx) for s, sfx in (("A", ""), ("B", "_b"))}
+ mj.mj_resetData(m, d)
+ for s in SIDES:
+ d.qpos[self.qadr[s]] = Q0
+ mj.mj_forward(m, d)
+ self.target = {s: Q0.copy() for s in SIDES}
+ self.actions = {s: [] for s in SIDES}
+ self.k = 0
+ self.events: list[dict] = []
+ self._last_touch: dict = {}
+ self.env_touch = {s: 0 for s in SIDES}
+ rng = np.random.default_rng(SEED)
+ self.serve_ids = [int(x) for x in rng.choice(sorted(SERVES), size=2 * CAP_POINTS - 1, replace=False)]
+ self.score = {"A": 0, "B": 0}
+ self.points: list[dict] = []
+ self.hits = 0
+ self.done = False
+ self.winner = None
+ self.hist: deque = deque(maxlen=12)
+ # live control
+ # the arm command layer (docs/benchmarks/roboolympics-modes.md; the duel's form of shared/.../core.py): per side a
+ # row list from the step it was installed (plan / plan_j), else a slew, else the rest command: the high-level
+ # plugin rests by returning to the ready pose (rest_ready, the original behaviour), the low level holds
+ self.plan = {s: [] for s in SIDES}; self.plan_j = {s: 0 for s in SIDES}
+ self.slew = {s: None for s in SIDES}
+ self.rest_ready = True
+ self.rejected = {s: 0 for s in SIDES}
+ self.planners = {} # expensive planners live in separate processes
+ self.decided: dict = {} # (ball id, phase) -> True for decisions already served
+ self.review_due = False # a point just ended: the world waits (static) for both seats' reviews
+ self._start_point(0)
+ self._reset_arms = False
+ mj.mj_forward(m, d)
+
+ def _subtree_geoms(self, root_name):
+ m = self.m
+ root = mj.mj_name2id(m, mj.mjtObj.mjOBJ_BODY, root_name)
+ out = set()
+ for g in range(m.ngeom):
+ b = m.geom_bodyid[g]
+ while b not in (0, root):
+ b = m.body_parentid[b]
+ if b == root:
+ out.add(g)
+ return out
+
+ # ------------------------------------------------------------------ points
+ def _start_point(self, hold_from):
+ n = len(self.points)
+ recv = FIRST_RECEIVER if sum(self.score.values()) % 2 == 0 else OTHER[FIRST_RECEIVER] # every point; lets keep it
+ sid = self.serve_ids[n % len(self.serve_ids)]
+ self.rs = {"point": n, "receiver": recv, "serve": sid, "hold_from": hold_from, "launch": hold_from + READY_STEPS,
+ "expect": recv, "last_hitter": None, "bounces": {"A": 0, "B": 0}, "serve_phase": True,
+ "played_k": hold_from + READY_STEPS, "ball_id": 0, "last_event_k": hold_from + READY_STEPS,
+ "hits_in_point": 0, "receiver_returns": 0, "net_touches": 0, "state": "ready"}
+ self.events = []; self._last_touch = {}; self.frames = []
+ self.hist.clear()
+ self._pending_point = None
+ self._set_ghost(OTHER[recv], True); self._set_ghost(recv, False) # serve fix: server-side robot is a ghost for the ball
+ self._reset_arms = True # serve fix: both players back to the ready pose (applied at the end of step())
+ self._park()
+
+ def _set_ghost(self, side, on):
+ if self.ghost[side] == on:
+ return
+ m = self.m
+ for g in self._ghost_geoms[side]:
+ ct, ca = self._mask0[g]
+ if ct or ca: # visual-only geoms (0/0) stay out of collisions
+ m.geom_contype[g] = 2 if on else ct
+ m.geom_conaffinity[g] = 2 if on else ca
+ for i in self._blade_pairs[side]:
+ m.pair_margin[i] = -10.0 if on else self._pair_margin0[i] # a contact would need 10 m of penetration: never
+ self.ghost[side] = on
+
+ def _serve_state(self):
+ b = SERVES[self.rs["serve"]]
+ p, v, w = np.array(b["pos"]), np.array(b["vel"]), np.array(b["spin"])
+ if self.rs["receiver"] == "B":
+ p, v, w = mir(p), mir(v), mir(w)
+ return p, v, w
+
+ def _park(self):
+ p, v, w = self._serve_state()
+ d = self.d
+ d.qpos[0:3] = p; d.qpos[3:7] = [1, 0, 0, 0]; d.qvel[0:3] = v; d.qvel[3:6] = w
+
+ def in_play(self):
+ return self.k > self.rs["launch"]
+
+ def _end_point(self, loser, how):
+ # Defer resets until the control boundary: never reset a scene mid-substep.
+ if self._pending_point is None:
+ self._pending_point = (loser, how)
+
+ def _commit_point(self):
+ loser, how = self._pending_point
+ winner = OTHER[loser] if loser is not None else None
+ if winner is not None:
+ self.score[winner] += 1
+ self.review_hist = list(self.hist) or [{"k": self.k, "qpos": self.d.qpos.copy(), "played_k": self.rs["played_k"], "point": self.rs["point"]}]
+ self.points.append({"point": len(self.points) + 1, "winner": winner, "loser": loser, "how": how,
+ "score": dict(self.score), "hits": self.rs["hits_in_point"], "step": self.k,
+ "receiver": self.rs["receiver"], "let": loser is None,
+ "net_touches": self.rs["net_touches"]})
+ self.rs["state"] = "over"
+ w = match_winner(self.score)
+ if w is None and len(self.points) >= MAX_POINTS_WITH_LETS: # guard (never reached in practice)
+ a, b = self.score["A"], self.score["B"]
+ w = "A" if a > b else "B" if b > a else next(p["winner"] for p in reversed(self.points) if p["winner"])
+ if w is not None:
+ self.winner = w
+ self.done = True
+ return
+ self._start_point(self.k)
+ self.review_due = True
+
+ # ------------------------------------------------------------------ physics + referee (shared by live and replay)
+ def _check(self, side, q):
+ if q.shape != (7,) or not np.all(np.isfinite(q)):
+ raise ValueError("bad target")
+ if (q < self.JLOW - 1e-9).any() or (q > self.JHIGH + 1e-9).any():
+ raise ValueError(f"{side}: joint target outside range")
+ if (np.abs(q - self.target[side]) > VEL_LIMIT * CONTROL_DT * (1 + 1e-6) + 1e-12).any():
+ raise ValueError(f"{side}: joint speed limit")
+
+ def step(self, qA, qB):
+ qs = {"A": np.asarray(qA, float), "B": np.asarray(qB, float)}
+ for s in SIDES:
+ self._check(s, qs[s])
+ m, d = self.m, self.d
+ if self.rs["state"] == "ready" and self.k >= self.rs["launch"]:
+ self.rs["state"] = "live"
+ prev = {s: self.target[s] for s in SIDES}
+ for j in range(1, SUBSTEPS + 1):
+ for s in SIDES:
+ qd_des = (qs[s] - prev[s]) / CONTROL_DT
+ q_des = prev[s] + (qs[s] - prev[s]) * (j / SUBSTEPS)
+ va = self.vadr[s]
+ tau = KP * (q_des - d.qpos[self.qadr[s]]) + KD * (qd_des - d.qvel[va]) + d.qfrc_bias[va]
+ d.ctrl[self.aadr[s]] = np.clip(tau, self.lo[self.aadr[s]], self.hi[self.aadr[s]])
+ self._v_pre = d.qvel[0:3].copy() # the ball's velocity before this substep (for _towards_half)
+ mj.mj_step(m, d)
+ self._scan()
+ for s in SIDES:
+ self.target[s] = qs[s].copy()
+ self.actions[s].append(qs[s].copy())
+ self.k += 1
+ if self.rs["state"] == "ready" and self.k <= self.rs["launch"]:
+ self._park()
+ elif not self.done and self._pending_point is None:
+ self._referee_time()
+ if self.k % CAM_EVERY == 0 or self._pending_point is not None:
+ self.hist.append({"k": self.k, "qpos": d.qpos.copy(), "played_k": self.rs["played_k"],
+ "point": self.rs["point"], "wall_mono": __import__('time').monotonic()})
+ if self.in_play():
+ self.frames.append(self.k)
+ if self._pending_point is not None:
+ self._commit_point()
+ if getattr(self, "_reset_arms", False):
+ for side in SIDES:
+ d.qpos[self.qadr[side]] = Q0; d.qvel[self.vadr[side]] = 0.0
+ self.target[side] = Q0.copy(); self.plan[side] = []; self.plan_j[side] = 0; self.slew[side] = None
+ mj.mj_forward(m, d)
+ self._reset_arms = False
+
+ def _scan(self):
+ if self.rs["state"] != "live" or self.done or self._pending_point is not None:
+ return
+ d, t = self.d, self.d.time
+ kinds, env_faults = set(), set()
+ for c in d.contact[:d.ncon]:
+ g1, g2 = int(c.geom1), int(c.geom2)
+ if self.g_ball in (g1, g2):
+ other = g2 if g1 == self.g_ball else g1
+ if other == self.g_table:
+ normal_z = float(c.frame[2]) * (1 if g1 == self.g_table else -1)
+ top = normal_z > 1e-6 and abs(c.pos[0]) <= .7635 and abs(c.pos[1]) <= 1.371
+ kind = ("table_A" if c.pos[1] < 0 else "table_B") if top else "table_side"
+ elif other in self.g_blade.values():
+ kind = "paddle_" + next(s for s in SIDES if self.g_blade[s] == other)
+ elif other == self.g_net: kind = "net"
+ elif other == self.g_floor: kind = "floor"
+ else:
+ owners = [s for s in SIDES if other in self.robot_geoms[s]]
+ kind = "robot_" + owners[0] if owners else "other"
+ kinds.add(kind)
+ else:
+ for side in SIDES:
+ own = self.robot_geoms[side] | {self.g_blade[side]}
+ if ((g1 in own and g2 in (self.g_table, self.g_net, self.g_floor)) or
+ (g2 in own and g1 in (self.g_table, self.g_net, self.g_floor))):
+ env_faults.add(side)
+ if env_faults:
+ if len(env_faults) == 2:
+ self._end_point(None, "let: simultaneous arm/table faults")
+ else:
+ side = next(iter(env_faults)); self._end_point(side, f"{side}'s arm or paddle touched table/net/floor")
+ return
+ # Same-substep contacts are processed by category, never by seat priority.
+ new = [kind for kind in kinds if kind not in self._last_touch or t-self._last_touch[kind] > MERGE_GAP_S+1e-9]
+ for kind in kinds: self._last_touch[kind] = t
+ for prefix in ("robot_", "paddle_"):
+ if prefix+"A" in new and prefix+"B" in new:
+ self._end_point(None, "let: simultaneous two-seat ball contact")
+ return
+ priority = lambda k: (0 if k.startswith("robot_") else 1 if k in ("table_A", "table_B") else
+ 2 if k.startswith("paddle_") else 3, k)
+ for kind in sorted(new, key=priority):
+ ev = {"t": round(float(t), 6), "k": self.k, "kind": kind, "pos": d.qpos[:3].tolist()}
+ self.events.append(ev)
+ self._on_event(ev)
+ if self._pending_point is not None: break
+
+ def _on_event(self, ev):
+ rs = self.rs
+ if self.done or rs["state"] != "live":
+ return
+ kind = ev["kind"]
+ rs["last_event_k"] = self.k
+ exp, hitter = rs["expect"], rs["last_hitter"]
+ server_half = OTHER[rs["receiver"]]
+ if kind in ("table_A", "table_B"):
+ half = kind[-1]
+ if rs["serve_phase"] and hitter is None:
+ if half == server_half and rs["bounces"][server_half] == 0 and rs["bounces"][exp] == 0:
+ rs["bounces"][server_half] = 1
+ return
+ if half == exp and rs["bounces"][exp] == 0 and rs["bounces"][server_half] == 1:
+ rs["bounces"][exp] = 1; rs["serve_phase"] = False
+ self._set_ghost(server_half, False) # the serve reached the receiver's half: normal collisions again
+ return
+ # an odd serve (never happens with the pool); replay the point as a let is not needed: receiver's point
+ return self._end_point(None, "let: irregular machine serve")
+ if half == exp:
+ rs["bounces"][exp] += 1
+ if rs["bounces"][exp] >= 2:
+ return self._end_point(exp, f"{exp} let the ball bounce twice")
+ if hitter == rs["receiver"]: # a good return by the receiver
+ rs["receiver_returns"] += 1
+ if rs["receiver_returns"] >= EXPEDITE_RETURNS:
+ return self._end_point(OTHER[hitter], f"{hitter} made {EXPEDITE_RETURNS} good returns as the "
+ "receiver (expedite rule)")
+ return
+ return self._end_point(hitter, f"{hitter}'s shot hit its own half")
+ if kind.startswith("paddle_"):
+ p = kind[-1]
+ if p == exp:
+ if rs["bounces"][exp] != 1:
+ return self._end_point(p, f"{p} hit the ball before it bounced (volley)")
+ rs["last_hitter"] = p; rs["expect"] = OTHER[p]; rs["bounces"] = {"A": 0, "B": 0}
+ rs["played_k"] = self.k; rs["ball_id"] += 1; rs["hits_in_point"] += 1; self.hits += 1
+ self.frames = []
+ return
+ return self._end_point(p, f"{p} touched the ball twice")
+ if kind == "net":
+ if hitter is None:
+ return self._end_point(None, "let: machine serve touched net")
+ rs["net_touches"] += 1 # a return may touch the net (ITTF 2.7.1): play on
+ return
+ if kind.startswith("robot_"):
+ r = kind[-1]
+ if hitter is not None and r == exp and rs["bounces"][r] == 0 and not self._towards_half(r):
+ return self._end_point(hitter, f"{hitter}'s shot went out (it passed {r}'s half and hit {r}'s robot)")
+ return self._end_point(r, f"the ball hit {r}'s non-blade robot part (arm or handle)")
+ # floor / other
+ if hitter is None:
+ return self._end_point(exp, "the serve was not returned")
+ if rs["bounces"][exp] >= 1:
+ return self._end_point(exp, f"{exp} missed the ball")
+ return self._end_point(hitter, f"{hitter}'s shot went out")
+
+ def _towards_half(self, side, horizon_s=0.5):
+ """Whether the ball is over `side`'s half or its straight-line path in the next horizon_s reaches it (in that
+ side's own frame). Ball contact with a robot outside this is not obstruction: the shot was going out."""
+ p, v = self.d.qpos[0:3].copy(), np.array(self._v_pre)
+ if side == "B":
+ p, v = mir(p), mir(v)
+ for t in np.linspace(0.0, horizon_s, 26):
+ x, y = p[0] + v[0] * t, p[1] + v[1] * t
+ if abs(x) <= 0.7625 and -1.37 <= y <= 0.0:
+ return True
+ return False
+
+ def _referee_time(self):
+ rs = self.rs
+ if rs["state"] != "live":
+ return
+ p = self.d.qpos[0:3]
+ out = abs(p[1]) > 3.0 or abs(p[0]) > 2.5 or p[2] < -0.5
+ if out or self.k - rs["last_event_k"] > DEAD_STEPS:
+ exp, hitter = rs["expect"], rs["last_hitter"]
+ if hitter is None or rs["bounces"][exp] >= 1:
+ return self._end_point(exp, f"{exp} missed the ball")
+ return self._end_point(hitter, f"{hitter}'s shot went out")
+
+ def replay(self, qA_list, qB_list):
+ if len(qA_list) != len(qB_list):
+ raise ValueError("seat trajectory lengths differ")
+ for a, b in zip(qA_list, qB_list):
+ if self.done: raise ValueError("trajectory continues after match end")
+ self.step(a, b)
+
+ def state_sha(self):
+ import hashlib
+ h = hashlib.sha256()
+ for a in (self.d.qpos, self.d.qvel, self.d.qacc_warmstart, self.d.ctrl, np.array([self.d.time])):
+ h.update(np.ascontiguousarray(a, dtype=np.float64).tobytes())
+ h.update(json.dumps(self.points, sort_keys=True).encode())
+ return h.hexdigest()
+
+ # ------------------------------------------------------------------ live control
+ def _ready(self, s):
+ tgt = self.target[s]
+ lim = VEL_LIMIT * CONTROL_DT * 0.6
+ return tgt + np.clip(Q0 - tgt, -lim, lim)
+
+ def _arm(self, s):
+ if self.plan_j[s] < len(self.plan[s]):
+ q = self.plan[s][self.plan_j[s]]; self.plan_j[s] += 1
+ return q
+ if self.slew[s] is not None:
+ goal, speed = self.slew[s]
+ lim = VEL_LIMIT * CONTROL_DT * speed
+ return self.target[s] + np.clip(goal - self.target[s], -lim, lim)
+ return self._ready(s) if self.rest_ready else self.target[s].copy()
+
+ def install(self, s, dec):
+ """A validated low-level command (action_low.validate) at the start of the coming control step of side s."""
+ lim = VEL_LIMIT * CONTROL_DT
+ if dec["type"] == "hold":
+ self.plan[s] = []; self.plan_j[s] = 0; self.slew[s] = None
+ return {"command": "hold"}
+ if dec["type"] == "slew":
+ self.plan[s] = []; self.plan_j[s] = 0; self.slew[s] = (np.asarray(dec["q"], float), float(dec["speed"]))
+ return {"command": "slew"}
+ Q = np.asarray(dec["q"], float); k0 = int(dec["k0"]); j0 = max(0, self.k - k0)
+ if j0 >= len(Q):
+ self.rejected[s] += 1
+ return {"rejected": f"stale: the trajectory's last row was for step {k0 + len(Q) - 1}; this is step {self.k}"}
+ jump = np.abs(Q[j0] - self.target[s])
+ if (jump > lim).any():
+ j = int(np.argmax(jump / lim)); self.rejected[s] += 1
+ return {"rejected": f"discontinuous: row {j0} (step {self.k}) moves joint {j + 1} by {jump[j]:.5f} rad from "
+ f"the target in force (limit {lim[j]:.5f} per step); the previous command goes on",
+ "first_row_used": j0}
+ hold = [self.target[s].copy()] * max(0, k0 - self.k) # before K0 the target is held
+ self.plan[s] = hold + [q for q in Q[j0:]]; self.plan_j[s] = 0; self.slew[s] = None
+ return {"command": "traj", "first_row_used": j0, "rows_left": int(len(Q) - j0)}
+
+ def command_state(self, s):
+ if self.plan_j[s] < len(self.plan[s]):
+ return {"type": "traj", "rows_left": len(self.plan[s]) - self.plan_j[s]}
+ if self.slew[s] is not None:
+ return {"type": "slew", "q": [round(float(x), 5) for x in self.slew[s][0]], "speed": self.slew[s][1]}
+ return "hold"
+
+ def advance(self):
+ self.step(self._arm("A"), self._arm("B"))
+
+ def review_done(self):
+ self.review_due = False
+
+ # ------------------------------------------------------------------ observations (in the side's own frame)
+ CAMS = match.Match.CAMS
+ VIEW_BACK = match.Match.VIEW_BACK
+
+ def _extra_geoms(self, scn):
+ def add(size, pos, rgba):
+ if scn.ngeom >= scn.maxgeom:
+ return
+ mj.mjv_initGeom(scn.geoms[scn.ngeom], mj.mjtGeom.mjGEOM_BOX, np.asarray(size, float), np.asarray(pos, float),
+ np.eye(3).ravel(), np.asarray(rgba, np.float32))
+ scn.ngeom += 1
+ for y in np.arange(-1.25, 1.26, 0.25):
+ for x in (-0.7625, 0.7625):
+ add([0.03, 0.006, 0.002], [x, y, 0.002], [1, 0.9, 0.1, 1])
+ for x in np.arange(-0.75, 0.76, 0.25):
+ for y in (-1.37, 1.37):
+ add([0.006, 0.03, 0.002], [x, y, 0.002], [1, 0.9, 0.1, 1])
+
+ def render_views(self, side, width=480, height=360) -> bytes:
+ import imageio.v2 as imageio
+ from PIL import Image, ImageDraw
+ if not hasattr(self, "_renderer"):
+ self._renderer = mj.Renderer(self.m, height=height, width=width)
+ self._rd = mj.MjData(self.m)
+ cams = []
+ for lookat, dist, az, el in self.CAMS:
+ c = mj.MjvCamera()
+ c.lookat[:] = lookat if side == "A" else mir(lookat)
+ c.distance = dist; c.azimuth = az if side == "A" else az + 180.0; c.elevation = el
+ cams.append(c)
+ r, rd = self._renderer, self._rd
+ hist = list(self.hist) or [{"k": self.k, "qpos": self.d.qpos.copy(), "played_k": self.rs["played_k"], "point": self.rs["point"]}]
+ snaps = [hist[max(0, len(hist) - 1 - b)] for b in reversed(self.VIEW_BACK)]
+ rows = []
+ for c in cams:
+ tiles = []
+ for sn in snaps:
+ rd.qpos[:] = sn["qpos"]
+ if sn["k"] <= sn.get("played_k", self.rs["played_k"]): rd.qpos[:3] = [0, 0, -10]
+ mj.mj_forward(self.m, rd)
+ r.update_scene(rd, camera=c)
+ self._extra_geoms(r.scene)
+ im = Image.fromarray(r.render())
+ ImageDraw.Draw(im).text((6, 4), f"k={sn['k']} t={(sn['k'] - sn.get('played_k', self.rs['played_k'])) * CONTROL_DT:.2f}s", fill=(255, 255, 255))
+ tiles.append(np.asarray(im))
+ rows.append(np.concatenate(tiles, axis=1))
+ buf = io.BytesIO()
+ imageio.imwrite(buf, np.concatenate(rows, axis=0), format="png")
+ return buf.getvalue()
+
+
+def render_video(qA, qB, out, names=("A", "B"), fps=25):
+ """Replay video: a side view and a high view of the whole table, 4x slow motion, with the score."""
+ import imageio.v2 as imageio
+ from PIL import Image, ImageDraw
+ du = Duel()
+ r = mj.Renderer(du.m, height=360, width=560)
+ cams = []
+ for lookat, dist, az, el in (([0.0, 0.0, 0.2], 4.6, 0.0, -10.0), ([0.0, 0.0, 0.0], 4.4, 0.0, -55.0)):
+ c = mj.MjvCamera(); c.lookat[:] = lookat; c.distance = dist; c.azimuth = az; c.elevation = el
+ cams.append(c)
+ w = imageio.get_writer(out, fps=fps, macro_block_size=8)
+ for k, (a, b) in enumerate(zip(qA, qB)):
+ du.step(a, b)
+ if du.rs["state"] != "live" and k % 3:
+ continue
+ imgs = []
+ for c in cams:
+ r.update_scene(du.d, camera=c)
+ du._extra_geoms(r.scene)
+ imgs.append(r.render())
+ im = Image.fromarray(np.concatenate(imgs, axis=1))
+ ImageDraw.Draw(im).text((8, 6), f"{names[1]} (left) {du.score['B']} : {du.score['A']} {names[0]} (right)",
+ fill=(255, 255, 255))
+ w.append_data(np.asarray(im))
+ w.close(); r.close()
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/instance.npz b/scripts/roboolympics/shared/sports/tabletennis/sim/instance.npz
new file mode 100644
index 0000000000..a947eff645
Binary files /dev/null and b/scripts/roboolympics/shared/sports/tabletennis/sim/instance.npz differ
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/ipc.py b/scripts/roboolympics/shared/sports/tabletennis/sim/ipc.py
new file mode 100644
index 0000000000..c004cc02f1
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/tabletennis/sim/ipc.py
@@ -0,0 +1,72 @@
+"""Camera rendering in its own PROCESS for the wall-clock server.
+
+MuJoCo's render call holds the Python GIL (measured: up to 50 ms stalls of a 10 ms pacing loop when rendering in a
+thread), so the observe images are drawn in a separate process: it owns its own model copy, MjData, OpenGL (osmesa)
+context and renderer, receives camera-frame snapshots (qpos, time stamp, opponent x) and returns the PNG.
+"""
+from __future__ import annotations
+
+import io
+import os
+import pickle
+import select
+import struct
+import subprocess
+import sys
+import threading
+import time
+
+import numpy as np
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+
+
+def _send(f, obj, deadline=None) -> None:
+ b = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)
+ packet = struct.pack("<Q", len(b)) + b
+ if deadline is None:
+ f.write(packet); f.flush()
+ return
+ offset = 0
+ while offset < len(packet):
+ remaining = deadline - time.monotonic()
+ if remaining <= 0 or not select.select([], [f], [], remaining)[1]:
+ raise TimeoutError("render worker request timed out")
+ # At most PIPE_BUF bytes after writable readiness; never block on a large request.
+ offset += os.write(f.fileno(), packet[offset:offset + 4096])
+
+
+def _read_exact(f, n, deadline=None):
+ chunks = []
+ while n:
+ if deadline is not None:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0 or not select.select([f], [], [], remaining)[0]:
+ raise TimeoutError("render worker response timed out")
+ chunk = os.read(f.fileno(), min(n, 65536))
+ if not chunk:
+ raise EOFError("render worker closed its response pipe")
+ chunks.append(chunk)
+ n -= len(chunk)
+ return b''.join(chunks)
+
+
+def _recv(f, deadline=None):
+ h = _read_exact(f, 8, deadline)
+ n = struct.unpack("<Q", h)[0]
+ if n > 64 * 1024 * 1024:
+ raise ValueError("oversized worker packet")
+ return pickle.loads(_read_exact(f, n, deadline))
+
+
+class _Conn:
+ def __init__(self, fin, fout):
+ self.fin, self.fout = fin, fout
+
+ def send(self, obj, deadline=None):
+ _send(self.fout, obj, deadline)
+
+ def recv(self, deadline=None):
+ return _recv(self.fin, deadline)
+
+
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/ladder.py b/scripts/roboolympics/shared/sports/tabletennis/sim/ladder.py
new file mode 100644
index 0000000000..3113c65f5b
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/tabletennis/sim/ladder.py
@@ -0,0 +1,116 @@
+"""The score ladder (analysis only; it never changes who wins): how far the agent got with each ball and in each point.
+
+ touched the paddle (blade) touched the ball
+ active ... with the blade moving at >= ACTIVE_SPEED at the contact (a swing or a push; a blade held still at the
+ ready pose also meets some serves: the nop player "touches" 2-3 balls of 5 at L1)
+ over_net ... and after that touch the ball first came down beyond the net (y > 0: the opponent's half or the floor
+ behind it; touching the net on the way is allowed)
+ landed_in ... and that first contact was the opponent's half of the table
+ returned ... a good return (also: one own bounce before the hit, one paddle contact, no arm contact with the table)
+ won the point was won; split into `won_expedite` (the agent, always the receiver, made 13 good returns: the
+ expedite rule, ITTF 2.15.4) and `won_rally` (every other won point: the opponent missed or hit out)
+
+Per point a rung counts if any of the agent's balls in that point reached it ("won" counts the point itself; a point
+can be won without a touch, e.g. the opponent's ball passing the agent's half). Lets are not points. Computed from the
+match's own per-ball results (`Match.results`) and points (`Match.points`), live and again in the replay.
+"""
+from __future__ import annotations
+
+RUNGS = ("touched", "active", "over_net", "landed_in", "returned")
+EXPEDITE_TAG = "(expedite rule)" # in a point's `how` when the expedite rule decided it (match.py, duel.py)
+
+
+def by_expedite(p: dict) -> bool:
+ """Whether the expedite rule decided this point (from its `how`; the rules are unchanged, this only reports it)."""
+ return EXPEDITE_TAG in str(p.get("how", ""))
+ACTIVE_SPEED = 0.2 # m/s, blade-centre speed at the paddle contact (a held blade: < 0.01 m/s)
+
+
+def contact_speeds(results: list, contacts: list) -> list:
+ """Per result, the largest blade speed of its paddle contacts. contacts: [(control step, blade speed m/s)] in
+ order; a result's contacts are those after the previous result's close step up to its own (`step`)."""
+ out, prev, i = [], -1, 0
+ for r in results:
+ v = None
+ while i < len(contacts) and contacts[i][0] <= r["step"]:
+ if contacts[i][0] > prev:
+ v = max(v or 0.0, float(contacts[i][1]))
+ i += 1
+ out.append(v)
+ prev = r["step"]
+ return out
+
+
+def ball_rungs(r: dict, speed: float | None = None) -> dict:
+ """The rungs one of the agent's balls (one entry of Match.results) reached; `active` needs the contact speed."""
+ kinds = list(r.get("events") or [])
+ touched = bool(r.get("hit"))
+ post = [k for k in kinds[kinds.index("paddle") + 1:] if k not in ("paddle", "net")] if "paddle" in kinds else []
+ over = touched and bool(post) and float(r.get("landing_y", 0.0)) > 0.0
+ landed = over and post[0] == "table_opp"
+ return {"touched": touched, "active": touched and speed is not None and speed >= ACTIVE_SPEED, "over_net": over,
+ "landed_in": landed, "returned": bool(r.get("returned"))}
+
+
+def ladder(points: list, results: list, me: str = "you", contacts: list | None = None) -> dict:
+ """Counts per match: `points_*` (points that reached the rung) and `balls_*` (the agent's balls that did).
+ contacts: the paddle contacts with the blade speed (replay.py records them); without them `active` is -1."""
+ speeds = contact_speeds(results, contacts) if contacts is not None else [None] * len(results)
+ played = [i for i, p in enumerate(points) if p.get("winner") != "let"]
+ per_point = {i: dict.fromkeys(RUNGS, False) for i in played}
+ balls = dict.fromkeys(RUNGS, 0)
+ for r, v in zip(results, speeds):
+ rg = ball_rungs(r, v)
+ for k in RUNGS:
+ balls[k] += int(rg[k])
+ if r.get("point") in per_point and rg[k]:
+ per_point[r["point"]][k] = True
+ out = {"points": len(played), "balls": len(results)}
+ for k in RUNGS:
+ out["points_" + k] = sum(per_point[i][k] for i in played)
+ out["points_won"] = sum(points[i].get("winner") == me for i in played)
+ out["points_won_expedite"] = sum(points[i].get("winner") == me and by_expedite(points[i]) for i in played)
+ out["points_won_rally"] = out["points_won"] - out["points_won_expedite"]
+ for k in RUNGS:
+ out["balls_" + k] = balls[k]
+ if contacts is None:
+ out["points_active"] = out["balls_active"] = -1
+ out["per_point"] = [{"point": i, **{k: int(per_point[i][k]) for k in RUNGS},
+ "won": int(points[i].get("winner") == me),
+ "expedite": int(points[i].get("winner") == me and by_expedite(points[i]))} for i in played]
+ return out
+
+
+# The flat reward.json fields (tests/grade.py LADDER_KEYS, prefixed `ladder_`; test_modes.py checks they agree).
+REWARD_KEYS = tuple(["points", "balls"] + ["points_" + k for k in RUNGS] + ["points_won", "points_won_expedite", "points_won_rally"] + ["balls_" + k for k in RUNGS])
+
+
+class PaddleContacts:
+ """Records (control step, blade-centre speed) at every new paddle contact of a running match (replay.py calls
+ after_step() after every control step). It also looks when the match closes one of the agent's balls (a contact
+ and the end of the point can fall into the same control step, after which the step's events are cleared).
+ Read-only: it never changes the simulation (the replay's hashes are unchanged)."""
+
+ def __init__(self, match):
+ import numpy as np
+ self.m, self.s, self.out, self._n, self._first = match, match.s, [], 0, None
+ self._v = np.zeros(6)
+ close = match._close_our_leg
+
+ def _close_our_leg(*a, **kw):
+ self.after_step(match.k)
+ return close(*a, **kw)
+ match._close_our_leg = _close_our_leg
+
+ def after_step(self, k: int) -> None:
+ import mujoco as mj
+ import numpy as np
+ ev = self.s._events
+ first = (ev[0]["t"], ev[0]["kind"]) if ev else None # (an object id could be reused after the clear)
+ if first != self._first: # the per-leg event list was cleared (a new leg)
+ self._first, self._n = first, 0
+ n = sum(e["kind"] == "paddle" for e in ev)
+ if n > self._n:
+ mj.mj_objectVelocity(self.s.m, self.s.d, mj.mjtObj.mjOBJ_SITE, self.s._paddle_site, self._v, 0)
+ self.out += [(int(k), round(float(np.linalg.norm(self._v[3:])), 3))] * (n - self._n)
+ self._n = n
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/levels.py b/scripts/roboolympics/shared/sports/tabletennis/sim/levels.py
new file mode 100644
index 0000000000..e68595af64
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/tabletennis/sim/levels.py
@@ -0,0 +1,8 @@
+"""The action-level switch: `high` (the high-level plugin on) or `low` (off: the arm command layer only)."""
+import importlib
+
+
+def plugin(level: str):
+ if level not in ("high", "low"):
+ raise ValueError(f"action level must be high or low, not {level!r}")
+ return importlib.import_module("action_" + level)
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/match.py b/scripts/roboolympics/shared/sports/tabletennis/sim/match.py
new file mode 100644
index 0000000000..deb2cb9b73
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/tabletennis/sim/match.py
@@ -0,0 +1,886 @@
+"""Core of the table-tennis match service (interactive mode): one game against a scripted opponent, with the duel's
+rules: first to 5 points, from 4:4 a lead of 2, at 6:6 the next point wins (7 at most); the expedite rule (the
+receiver's 13th good return in a rally wins it the point, ITTF 2.15.4) bounds every rally. The opponent serves every
+point, so the agent is always the receiver (the duel's receiver rotation cannot apply: the robot cannot serve).
+
+The robot (Franka + paddle, y < 0) plays a scripted opponent on the far side (y > 0). The opponent is part of the
+world, like the physics: a deterministic function of the simulator state, evaluated inside every control step, so a
+recorded sequence of the robot's joint targets replays the whole match bit-exactly (no schedule is needed).
+
+Point flow (all inside step()):
+ ready READY_STEPS control steps; the next serve is held at its launch state, out of play.
+ serve the opponent serves: a recorded DeepMind serve (bounces on its half, crosses the net, bounces on ours).
+ our leg the ball comes to us (a serve, or the opponent's return). The model decides the shot (live code:
+ swing / adjust decision points); the robot hits or not. The leg is judged like the rally task: exactly one
+ own bounce before the hit, one paddle contact, first contact after the hit other than the net = the
+ opponent's half (a return may touch the net, ITTF 2.7.1). A failed leg = the opponent's point. A serve
+ that touches the net is a let (ITTF 2.9.1.1: no point, the next serve; the recorded serves clear the net
+ by >= 3.9 cm, so this does not happen with the pool).
+ opp leg our return bounced on the opponent's half. The opponent (below) either returns it (a new "our leg"
+ starts at its hit) or misses it (our point once the ball is dead).
+
+The opponent (LEVELS): a kinematic paddle on its end line, at the centre when it serves. `reaction_s` after our hit it
+moves towards the (perfectly predicted) ball at `chase`; after each of its shots it walks back towards the centre at
+`recover`. When the ball reaches the top of its bounce on its half (or y = HIT_Y) it evaluates our shot's pressure
+ pressure = max(|ball x - its paddle x| / reach, (our speed off the paddle - SPEED_FREE) / (max_speed - SPEED_FREE))
+and, deterministically: pressure > 1 -> it misses (our point); > PRESSURE_WEAK -> a weak return (slow, central, no
+spin); < PRESSURE_PASSIVE -> it attacks (its widest, fastest ball, full spin); else a normal return (a seeded target
+within the level's width, its pace, top- or backspin plus a sidespin share). It sets the ball's velocity and spin (an
+impulse; it never touches the ball physically) so that the ball lands on our half and its apex after our bounce is in
+the box the reference stroke returns reliably; an unreachable target moves towards the centre and the pace down.
+It never misses except by the rule above.
+Our strokes scatter: the aim is perturbed by a seeded N(0, EXEC_SIGMA[power]) per shot before the stroke is planned.
+"""
+from __future__ import annotations
+
+import io
+import json
+import os
+import time
+from collections import deque
+from pathlib import Path
+
+import numpy as np
+
+import mujoco as mj
+import rally
+import rcb_tt
+from rally import BallModel, world_spin, hermite # noqa: F401
+from rcb_tt import CONTROL_DT, VEL_LIMIT
+
+HERE = Path(__file__).resolve().parent
+SCENE, INSTANCE = rally.SCENE, rally.INSTANCE
+SERVES = {b["id"]: b for b in json.load(open(HERE / "serves_pool.json"))["serves"]}
+REVISION = "wallclock-5"
+WIN_POINTS = 5 # the duel's format (duel.py): first to 5 ...
+WIN_BY = 2 # ... from 4:4 a lead of 2 ...
+CAP_POINTS = 7 # ... at 6:6 the next point wins
+EXPEDITE_RETURNS = 13 # ITTF 2.15.4: the receiver's (our) 13th good return in a rally wins us the point
+MAX_POINTS_WITH_LETS = 40 # guard: 13 scoring points at most, so this needs 27+ lets; then the player ahead wins,
+ # at a level score the player who won the last point
+READY_STEPS = 80 # 0.8 s between points
+LEG_STEPS = 250 # our leg is lost if nothing decisive happens 2.5 s after it started
+CAM_EVERY = 2 # 50 Hz camera frames
+DECISION_AFTER_OPP_BOUNCE = 5 # serve legs: 5th frame (0.1 s) after the serve bounced on the opponent's half
+DECISION_AFTER_OPP_HIT = 6 # return legs: 6th frame (0.12 s) after the opponent's hit
+ADJUST_FRAMES = 3 # second decision point: 3rd frame (0.06 s) after the ball bounced on our half
+HIT_Y = 1.55
+OPP_Y, OPP_Z = 1.75, 0.22 # where the opponent's paddle is drawn
+SHOULDER = np.array([0.0, -1.75, 0.33])
+APEX_X_MAX = 0.30 # the opponent only plays balls whose apex after our bounce is in the box the reference
+ # stroke returns reliably (|x| <= 0.30, -1.38 <= y <= -1.10, 0.25 <= z <= 0.45)
+rcb_tt.HORIZON = 10 ** 7
+OPP_HALF = rally.OPP_HALF
+
+LEVELS = { # defence: reaction, chase / recovery speed, reach, too-fast threshold; attack: width, pace, spin, sidespin share
+ 1: dict(reaction_s=0.27, chase=0.47, recover=0.33, reach=0.27, max_speed=5.4,
+ width=0.15, pace=4.0, spin=10.0, side=0.0, seed=101),
+ 2: dict(reaction_s=0.25, chase=0.50, recover=0.35, reach=0.29, max_speed=5.6,
+ width=0.22, pace=4.4, spin=20.0, side=0.3, seed=202),
+ 3: dict(reaction_s=0.24, chase=0.53, recover=0.37, reach=0.31, max_speed=5.8,
+ width=0.28, pace=4.9, spin=30.0, side=0.6, seed=303),
+ 4: dict(reaction_s=0.22, chase=0.55, recover=0.40, reach=0.33, max_speed=6.0,
+ width=0.30, pace=5.4, spin=40.0, side=1.0, seed=404),
+}
+SPEED_FREE = 3.8 # our shot's speed off the paddle below this puts no pressure on the opponent
+PRESSURE_WEAK = 0.75 # our shot's pressure above this (but <= 1) -> the opponent only manages a weak return
+PRESSURE_PASSIVE = 0.35 # below this the opponent attacks: its widest, fastest ball with its most spin
+EXEC_SIGMA = {"soft": 0.04, "normal": 0.06, "hard": 0.09} # our stroke's landing scatter (m, per axis)
+POWER = ("soft", "normal", "hard")
+
+
+def match_winner(score):
+ """0 (us) / 1 (opponent) if the game is won at this score [us, opponent], else None (same rule as the duel)."""
+ for i in (0, 1):
+ a, b = score[i], score[1 - i]
+ if a >= CAP_POINTS or (a >= WIN_POINTS and a - b >= WIN_BY):
+ return i
+ return None
+
+
+def towards_own_half(p, v, horizon_s=0.5):
+ """Whether a ball at p moving with v is over our half (y < 0) or its straight-line path reaches it within horizon_s:
+ a ball touching a robot outside this is not obstruction, the shot was going out (the duel's rule)."""
+ for t in np.linspace(0.0, horizon_s, 26):
+ x, y = p[0] + v[0] * t, p[1] + v[1] * t
+ if abs(x) <= 0.7625 and -1.37 <= y <= 0.0:
+ return True
+ return False
+
+
+def ball_state(d):
+ return d.qpos[0:3].copy(), d.qvel[0:3].copy(), world_spin(d)
+
+
+class Match(rally.Rally):
+ """The match. Live: run_to_decision() / shot() / adjust(). Replay: replay(actions)."""
+
+ def __init__(self, level: int = 1, lv_override: dict | None = None):
+ self.level = int(level)
+ self.lv = dict(LEVELS.get(self.level, LEVELS[1]))
+ if lv_override:
+ self.lv.update(lv_override)
+ if os.environ.get("MATCH_SEED"): # other instances of the same level: serves + opponent + scatter
+ self.lv["seed"] = int(os.environ["MATCH_SEED"])
+ self.s = rcb_tt.Session(instance=str(INSTANCE), scene=str(SCENE))
+ self.bm = BallModel()
+ self._twin = None
+ self._ik_seed = None
+ self._planned_hit = None
+ rng = np.random.default_rng(self.lv["seed"])
+ ids = sorted(SERVES)
+ self.serve_ids = [int(x) for x in rng.choice(ids, size=2 * CAP_POINTS - 1, replace=False)]
+ self.score = [0, 0] # [robot, opponent]
+ self.points: list[dict] = [] # per point: winner, how, legs
+ self.legs: list[dict] = [] # every leg of the match (ours and the opponent's shots)
+ self.results: list[dict] = [] # our legs' results (rally-style)
+ self.shots: list[dict] = []
+ self.hist: deque = deque(maxlen=12) # recent camera snapshots for the views
+ self.frames: list[dict] = [] # (internal) ball camera frames of the current leg, for timing only
+ self.done = False
+ self.winner = None # 0 us, 1 the opponent (set when the game ends)
+ self.phase = "swing"
+ self.plan, self.plan_j, self._rec = [], 0, {}
+ self.contact_k = 0
+ self.n_our_legs = 0 # every ball that came to us (also the per-leg RNG streams)
+ self.n_our_shots = 0 # our shots: legs in which our paddle touched the ball
+ self.i = 0
+ self._start_point(hold_from=0)
+
+ # ------------------------------------------------------------------ point / leg bookkeeping
+ def _start_point(self, hold_from: int):
+ n = len(self.points)
+ sid = self.serve_ids[n % len(self.serve_ids)]
+ self.point_returns = 0 # our good returns in this rally (expedite rule)
+ self.leg = {"kind": "serve", "serve": sid, "point": n, "hold_from": hold_from,
+ "launch": hold_from + READY_STEPS, "state": "incoming"}
+ self.legs.append(self.leg)
+ b = SERVES[sid]
+ self.opp = {"x0": 0.0, "k0": self.leg["launch"], "tx": 0.0, "plan_k": None, # ready at the centre
+ "speed": self.lv["recover"]}
+ self._new_leg_bookkeeping()
+ self._park()
+
+ def _new_leg_bookkeeping(self):
+ self.frames = []
+ s = self.s
+ s._events.clear(); s._last_touch.clear(); s._robot_table = 0; s._v_out = None
+ self.i = self.n_our_legs
+
+ def _park(self):
+ b = SERVES[self.leg["serve"]]
+ d = self.s.d
+ d.qpos[0:3] = b["pos"]; d.qpos[3:7] = [1, 0, 0, 0]; d.qvel[0:3] = b["vel"]; d.qvel[3:6] = b["spin"]
+
+ def _cur(self) -> dict:
+ return self.leg
+
+ def in_play(self) -> bool:
+ return self.k > self.leg["launch"]
+
+ def t_since_launch(self) -> float:
+ return round((self.k - self.leg["launch"]) * CONTROL_DT, 6)
+
+ # ------------------------------------------------------------------ the opponent
+ def opp_x(self, k=None) -> float:
+ k = self.k if k is None else k
+ o = self.opp
+ dt = max(0.0, (k - o["k0"]) * CONTROL_DT)
+ dx = o["tx"] - o["x0"]
+ step = min(abs(dx), o.get("speed", self.lv["recover"]) * dt)
+ return float(o["x0"] + np.sign(dx) * step)
+
+ def _opp_move(self, tx: float):
+ self.opp = {"x0": self.opp_x(), "k0": self.k, "tx": float(tx), "plan_k": self.opp.get("plan_k"),
+ "speed": self.lv["chase"]}
+
+ def _predict_opp_hit(self):
+ """Where the ball will be when the opponent hits it (ball-only model, true state)."""
+ p, v, w = ball_state(self.s.d)
+ P, V, _, _ = self.bm.rollout(p, v, w, 1500)
+ bounced = False
+ for i in range(1, len(P)):
+ if not bounced and P[i, 1] > 0 and P[i, 2] < 0.03 and V[i, 2] > 0:
+ bounced = True
+ if bounced and (V[i, 2] <= 0 or P[i, 1] >= HIT_Y):
+ return P[i]
+ return P[-1]
+
+ def _opp_return(self, p_hit, mode="normal"):
+ """Opponent's shot from p_hit: (v, w, target, pace). normal: a seeded target within the level's width, its pace
+ and spin (top- or backspin, plus a sidespin share); attack: its widest and fastest ball with full spin; weak:
+ a slow, central, spinless ball (a chance for us). Only balls whose apex after our bounce is in the reliably
+ returnable box are played; otherwise the target moves towards the centre and the pace down."""
+ lv = self.lv
+ rng = np.random.default_rng([lv["seed"], len(self.points), len(self.legs)])
+ u = rng.uniform(-1, 1, 5)
+ if mode == "weak":
+ tx, ty, pace = 0.08 * u[0], -0.6 + 0.1 * u[1], 3.7
+ w = np.zeros(3)
+ else:
+ width = lv["width"] * (1.0 if mode == "attack" else abs(u[0]) ** 0.5)
+ tx = float(np.sign(u[0]) or 1.0) * width
+ ty = -0.6 + 0.15 * u[1]
+ pace = lv["pace"] + (0.5 if mode == "attack" else 0.0)
+ mag = lv["spin"] * (1.0 if mode == "attack" else 0.5 + 0.5 * abs(u[2]))
+ sgn = 1.0 if u[3] > -0.4 else -1.0 # 70 % topspin, 30 % backspin
+ w = np.array([sgn * mag, 0.0, lv["side"] * mag * u[4]])
+ if "explore" in lv: # calibration only: random pace / spin
+ pace = float(rng.uniform(3.6, lv.get("pace_max", 5.0)))
+ sm = lv.get("spin_max", 15.0)
+ w = np.array([float(rng.uniform(-sm, sm)), 0.0, float(rng.uniform(-sm, sm)) * lv.get("side", 0.0)])
+ tx = float(u[0]) * lv["width"]
+ # Search depth as well as width before weakening a nominal shot. Every return is checked.
+ candidates = 0
+ nominal_w = w.copy()
+ for relax in (1.0, .75, .5, 0.0):
+ for dp in (0.0, -.4, .4):
+ for depth in (ty, -.45, -.75, -.3, -.9):
+ candidates += 1
+ target = np.array([tx*relax, depth])
+ speed = max(3.6, pace+dp)
+ spin = nominal_w*relax
+ v = self._solve_shot(p_hit, target, speed, spin)
+ if v is not None and self._reachable(p_hit, v, spin):
+ self._return_search = {"candidates": candidates, "relax": relax,
+ "nominal_pace": pace, "nominal_target_x": tx}
+ return v, spin, target.tolist(), speed
+ raise RuntimeError("opponent solver could not construct a legal reachable return")
+
+ def _solve_shot(self, p0, target, pace, w):
+ """Newton on (vx, vz) with vy = -pace so that the ball-only flight lands at `target` and clears the net."""
+ flight = max(.15, abs(target[1]-p0[1])/pace*1.12)
+ v = np.array([(target[0]-p0[0])/flight, -pace,
+ (rally.BALL_R-p0[2]+.5*9.81*flight**2)/flight])
+ for _ in range(12):
+ L, ok = self._landing(p0, v, w)
+ if L is None:
+ v[2] += 0.4
+ continue
+ err = L - target
+ if np.linalg.norm(err) < 0.01:
+ return v if ok else None
+ J = np.zeros((2, 2))
+ for c, idx in enumerate((0, 2)):
+ dv = np.zeros(3); dv[idx] = 2e-2
+ L2, _ = self._landing(p0, v + dv, w)
+ if L2 is None:
+ return None
+ J[:, c] = (L2 - L) / 2e-2
+ try:
+ dx = np.linalg.lstsq(J, err, rcond=None)[0]
+ except np.linalg.LinAlgError:
+ return None
+ dx = np.clip(dx, -0.8, 0.8)
+ v[0] -= dx[0]; v[2] -= dx[1]
+ return None
+
+ def _landing(self, p0, v, w):
+ """First table contact on our half (interpolated to the ball-radius height) and whether the flight clears
+ the net by >= 3 cm; None if the first contact is anything else."""
+ P, _, _, first = self.bm.rollout(p0, v, w, 1500, stop_at_contact=True)
+ if not first or first[1] != "table_own" or len(P) < 3:
+ return None, False
+ a, b = P[-3], P[-2]
+ z0 = rally.BALL_R
+ f = 0.0 if abs(a[2] - b[2]) < 1e-9 else float(np.clip((a[2] - z0) / (a[2] - b[2]), 0.0, 2.0))
+ L = a[:2] + f * (b[:2] - a[:2])
+ i0 = int(np.argmin(np.abs(P[:, 1])))
+ clear = P[i0, 2] > 0.1525 + 0.02 + 0.03
+ return L, bool(clear)
+
+ def _reachable(self, p0, v, w) -> bool:
+ P, V, _, _ = self.bm.rollout(p0, v, w, 1500)
+ bounced = False
+ for i in range(1, len(P)):
+ if not bounced:
+ if P[i, 2] < 0.03 and V[i, 2] > 0 and P[i, 1] < 0:
+ bounced = True
+ continue
+ if V[i, 2] <= 0:
+ a = P[i]
+ return bool(.17 <= a[2] <= .65 and -1.55 <= a[1] <= -.90 and abs(a[0]) <= .45
+ and np.linalg.norm(a-SHOULDER) <= .82)
+ return False
+
+ # ------------------------------------------------------------------ stepping (shared by live and replay)
+ def step(self, q):
+ self.s.step(q)
+ leg = self.leg
+ if leg["kind"] == "serve" and self.k <= leg["launch"]:
+ self._park()
+ else:
+ self._referee()
+ if self.k % CAM_EVERY == 0:
+ d = self.s.d
+ self.hist.append({"k": self.k, "t": self.t_since_launch(), "qpos": d.qpos.copy(), "opp_x": self.opp_x(),
+ "leg_id": len(self.legs)-1, "wall_mono": time.monotonic()})
+ if self.in_play() and leg["state"] == "incoming":
+ p = d.qpos[0:3]
+ self.frames.append({"t": self.t_since_launch(), "pos": [float(x) for x in p]})
+
+ def _leg_verdict(self):
+ return rcb_tt.judge(self.s._events, OPP_HALF, robot_env_contact=self.s._robot_table)
+
+ def _referee(self):
+ if self.done:
+ return
+ leg, d = self.leg, self.s.d
+ kinds = [e["kind"] for e in self.s._events]
+ p = d.qpos[0:3]
+ dead = any(x in ("floor", "robot", "other") for x in kinds) or p[2] < -0.3 or abs(p[1]) > 2.8 or abs(p[0]) > 2.5
+ if (leg["state"] in ("incoming", "to_opp") and self.opp.get("plan_k") is not None
+ and self.k >= self.opp["plan_k"]):
+ leg["opp_x_react"] = round(self.opp_x(), 3) # the opponent reacts `reaction_s` after our hit
+ self._opp_move(self._predict_opp_hit()[0])
+ self.opp["plan_k"] = None
+ if leg["state"] == "incoming":
+ if leg["kind"] == "serve" and "net" in (kinds[:kinds.index("paddle")] if "paddle" in kinds else kinds):
+ self._end_point(winner=None, how="let: the serve touched the net")
+ return
+ if leg["kind"] == "return" and "robot" in kinds and "paddle" not in kinds and "table_own" not in kinds:
+ e = next(x for x in self.s._events if x["kind"] == "robot")
+ if not towards_own_half(e["pos"], e["vel_pre"]): # as in the duel (ITTF 2.10.1.4 vs 2.10.1.6)
+ self._end_point(winner=0, how="the opponent's shot went out (it passed your half and hit your robot)")
+ return
+ post = kinds[kinds.index("paddle") + 1:] if "paddle" in kinds else []
+ post = [x for x in post if x not in ("paddle", "net")] # a return may touch the net (ITTF 2.7.1)
+ if "paddle" in kinds and self.opp.get("plan_k") is None and "paddle_t" not in leg:
+ ip = next(e for e in self.s._events if e["kind"] == "paddle")
+ leg["paddle_t"] = ip["t"]
+ self.opp["plan_k"] = int(round(ip["t"] / CONTROL_DT)) + int(round(self.lv["reaction_s"] / CONTROL_DT))
+ if post or dead or self.k - leg["launch"] >= LEG_STEPS:
+ v = self._leg_verdict()
+ ok = bool(v["success"]) and not dead
+ self._close_our_leg(v, ok)
+ if ok:
+ self.point_returns += 1
+ if ok and self.point_returns >= EXPEDITE_RETURNS:
+ self._end_point(winner=0, how=f"you made {EXPEDITE_RETURNS} good returns as the receiver "
+ "(expedite rule)")
+ elif ok:
+ leg["state"] = "to_opp"
+ else:
+ self._end_point(winner=1, how=self.results[-1]["summary"])
+ return
+ if leg["state"] == "to_opp":
+ v = d.qvel[0:3]
+ bounced = kinds.count("table_opp") >= 1
+ if bounced and p[1] > 0 and (v[2] <= 0 or p[1] >= HIT_Y) and p[2] > 0.05:
+ self._opp_hit()
+ elif dead or self.k - leg["launch"] >= 2 * LEG_STEPS:
+ self._end_point(winner=0, how=leg.get("opp_miss", "the opponent could not reach the ball"))
+ return
+ if leg["state"] == "opp_missed":
+ if dead or self.k - leg["opp_k"] >= 60:
+ self._end_point(winner=0, how=leg["opp_miss"])
+
+ def _opp_hit(self):
+ d = self.s.d
+ p, v, w = ball_state(d)
+ ox = self.opp_x()
+ vo = self.leg.get("v_out")
+ speed = float(np.linalg.norm(vo)) if vo is not None else float(np.linalg.norm(v)) # our shot's pace off the paddle
+ gap = abs(float(p[0]) - ox)
+ rec = {"k": self.k, "ball_x": round(float(p[0]), 3), "opp_x": round(ox, 3), "gap": round(gap, 3),
+ "speed": round(speed, 3)}
+ self.leg["opp"] = rec
+ rec["t_flight"] = round((self.k - int(round(self.leg.get("paddle_t", 0) / CONTROL_DT))) * CONTROL_DT, 3) if self.leg.get("paddle_t") else None
+ rec["opp_x_at_react"] = self.leg.get("opp_x_react")
+ pressure = max(gap / self.lv["reach"], (speed - SPEED_FREE) / (self.lv["max_speed"] - SPEED_FREE))
+ rec["pressure"] = round(pressure, 3)
+ if pressure > 1.0:
+ why = (f"too wide: the ball passed {gap:.2f} m from the opponent's paddle (its reach {self.lv['reach']:.2f} m)"
+ if gap > self.lv["reach"] else
+ f"too fast: {speed:.1f} m/s off your paddle (it handles up to {self.lv['max_speed']:.1f} m/s)")
+ self.leg["state"] = "opp_missed"; self.leg["opp_miss"] = why; self.leg["opp_k"] = self.k
+ rec["missed"] = why
+ return
+ mode = "weak" if pressure > PRESSURE_WEAK else ("attack" if pressure < PRESSURE_PASSIVE else "normal")
+ rec["mode"] = mode
+ try:
+ vo, wo, target, pace = self._opp_return(p, mode)
+ except RuntimeError: # no legal return from where it met the ball: the opponent misses it
+ why = "the opponent could not play a legal return from where it met the ball"
+ self.leg["state"] = "opp_missed"; self.leg["opp_miss"] = why; self.leg["opp_k"] = self.k
+ rec["missed"] = why
+ return
+ rec.update(target=[round(x, 3) for x in target], pace=pace, spin=[float(x) for x in wo],
+ search=dict(self._return_search))
+ R = np.zeros(9); mj.mju_quat2Mat(R, d.qpos[3:7])
+ d.qvel[0:3] = vo
+ d.qvel[3:6] = R.reshape(3, 3).T @ wo
+ self.leg["state"] = "done"
+ self.opp = {"x0": ox, "k0": self.k, "tx": 0.0, "plan_k": None, "speed": self.lv["recover"]}
+ self.leg = {"kind": "return", "point": len(self.points), "launch": self.k, "state": "incoming",
+ "opp_hit_x": round(float(p[0]), 3)}
+ self.legs.append(self.leg)
+ self._new_leg_bookkeeping()
+
+ def _close_our_leg(self, v, ok):
+ kinds = [e["kind"] for e in self.s._events]
+ vo = self.s._v_out
+ self.leg["v_out"] = None if vo is None else [float(x) for x in vo]
+ res = {"leg": self.n_our_legs, "point": len(self.points), "kind": self.leg["kind"], "returned": ok,
+ "speed_out": None if vo is None else round(float(np.linalg.norm(vo)), 2),
+ "hit": int(v["hit"]), "landing_x": round(float(v["landing_x"]), 3),
+ "landing_y": round(float(v["landing_y"]), 3), "events": kinds, "step": self.k}
+ if ok:
+ res["summary"] = f"returned: landed on the opponent's half at x={v['landing_x']:.2f}, y={v['landing_y']:.2f}"
+ elif not v["hit"]:
+ res["summary"] = "missed: no paddle contact"
+ elif v["robot_env_contact"]:
+ res["summary"] = "fault: the arm or paddle touched the table/net/floor"
+ elif v["n_paddle_contacts"] != 1:
+ res["summary"] = "fault: more than one paddle contact"
+ elif v["own_bounces_before_hit"] != 1:
+ res["summary"] = "fault: hit before the ball bounced on your half (volley)"
+ elif v["landed"]:
+ nxt = kinds[kinds.index("paddle") + 1:]
+ nxt = [x for x in nxt if x not in ("paddle", "net")]
+ where = {"table_own": "your own half", "floor": "the floor (out)"}.get(nxt[0], nxt[0]) if nxt else "?"
+ via = " (after touching the net)" if v["net_touch"] else ""
+ res["summary"] = f"fault: after your hit the ball hit {where}{via} (x={v['landing_x']:.2f}, y={v['landing_y']:.2f})"
+ else:
+ res["summary"] = "fault: after your hit the ball flew out without touching the table"
+ if ok and v["net_touch"]:
+ res["summary"] += " after touching the net"
+ res["net_touch"] = int(v["net_touch"])
+ self.results.append(res)
+ self.n_our_legs += 1
+ self.n_our_shots += int(bool(v["hit"]))
+ res["shot"] = self.n_our_shots if v["hit"] else None
+
+ def _end_point(self, winner: int | None, how: str):
+ if winner is not None: # None: a let (no point scored, the next serve)
+ self.score[winner] += 1
+ self.points.append({"point": len(self.points), "how": how,
+ "winner": "you" if winner == 0 else "opponent" if winner == 1 else "let",
+ "score": list(self.score), "step": self.k, "serve": self.legs[-1].get("serve")
+ if self.legs[-1]["kind"] == "serve" else None})
+ self.review_hist = list(self.hist)
+ self.review_hist.append({"k": self.k, "t": self.t_since_launch(), "qpos": self.s.d.qpos.copy(),
+ "opp_x": self.opp_x(), "leg_id": len(self.legs)-1, "wall_mono": time.monotonic()})
+ self.leg["state"] = "done"
+ w = match_winner(self.score)
+ if w is None and len(self.points) >= MAX_POINTS_WITH_LETS: # guard (never reached in practice)
+ w = (0 if self.score[0] > self.score[1] else 1 if self.score[1] > self.score[0] else
+ next((0 if p["winner"] == "you" else 1) for p in reversed(self.points) if p["winner"] != "let"))
+ if w is not None:
+ self.winner = w
+ self.done = True
+ return
+ self.hist.clear()
+ self._start_point(hold_from=self.k)
+
+ def replay(self, actions) -> None:
+ for q in actions:
+ self.step(q)
+
+ # ------------------------------------------------------------------ live control
+ def _arm_target(self):
+ if self.plan_j < len(self.plan):
+ q = self.plan[self.plan_j]; self.plan_j += 1
+ return q
+ return self._ready_target()
+
+ def decision_due(self) -> bool:
+ leg = self.leg
+ if self.done or leg["state"] != "incoming" or not self.in_play():
+ return False
+ ev = self.s._events
+ if any(e["kind"] == "paddle" for e in ev):
+ return False
+ n_frames = len(self.frames)
+ if self.phase == "swing":
+ if leg["kind"] == "serve":
+ b = [e for e in ev if e["kind"] == "table_opp"]
+ if not b:
+ return False
+ t_b = b[0]["t"] - leg["launch"] * CONTROL_DT
+ return sum(1 for f in self.frames if f["t"] > t_b) >= DECISION_AFTER_OPP_BOUNCE
+ return n_frames >= DECISION_AFTER_OPP_HIT
+ b = [e for e in ev if e["kind"] == "table_own"]
+ if not b:
+ return False
+ t_b = b[0]["t"] - leg["launch"] * CONTROL_DT
+ return sum(1 for f in self.frames if f["t"] > t_b) >= ADJUST_FRAMES
+
+ def run_to_decision(self) -> None:
+ """Advance (arm: rest of the plan, then back to ready) until the next decision point or the match end."""
+ self.phase = "swing"
+ while not self.done:
+ if self.decision_due():
+ return
+ self.step(self._arm_target())
+
+ def shot(self, decision: dict, delay_steps: int) -> dict:
+ leg_i = self.n_our_legs
+ rec = {"leg": leg_i, "decision": decision, "delay_steps": int(delay_steps), "k_decision": self.k}
+ for _ in range(delay_steps):
+ if self.leg["state"] != "incoming" or self.done:
+ break
+ self.step(self._arm_target())
+ rec["k_exec"] = self.k
+ self._ik_seed = None
+ if decision.get("type") == "swing" and self.leg["state"] == "incoming" and not self.done:
+ if "normal" in decision:
+ self.plan, info = self.plan_paddle(float(decision["t"]), decision["pos"], decision["normal"], decision["vel"])
+ else:
+ self.plan, info = self.plan_stroke(float(decision["t"]), np.asarray(decision["pos"], float),
+ np.asarray(decision.get("aim", rally.AIM_DEFAULT), float),
+ decision.get("power", "normal"))
+ self.plan_j = 0
+ rec.update(info)
+ self._rec = rec
+ if decision.get("type") == "swing":
+ self.phase = "adjust"
+ while not self.done and self.n_our_legs == leg_i:
+ if self.decision_due():
+ return {"phase": "adjust", **{k: rec[k] for k in rec if k != "decision"}}
+ self.step(self._arm_target())
+ return self._after_leg(rec, leg_i)
+
+ def adjust(self, decision: dict, delay_steps: int) -> dict:
+ rec, leg_i = self._rec, self.n_our_legs
+ rec["adjust"] = decision
+ rec["adjust_delay_steps"] = int(delay_steps)
+ for _ in range(delay_steps):
+ if self.n_our_legs != leg_i or self.done:
+ break
+ self.step(self._arm_target())
+ self._ik_seed = self._planned_hit
+ if decision.get("type") == "adjust" and self.n_our_legs == leg_i and not self.done and "normal" in decision:
+ plan, info = self.plan_paddle(float(decision["t"]), decision["pos"], decision["normal"], decision["vel"])
+ rec["adjust_info"] = info
+ if plan:
+ self.plan, self.plan_j = plan, 0
+ elif decision.get("type") == "adjust" and self.n_our_legs == leg_i and not self.done:
+ plan, info = self.plan_stroke(float(decision["t"]), np.asarray(decision["pos"], float),
+ np.asarray(decision.get("aim", rec.get("aim", rally.AIM_DEFAULT)), float),
+ decision.get("power", rec.get("power", "normal")))
+ rec["adjust_info"] = info
+ if plan:
+ self.plan, self.plan_j = plan, 0
+ return self._after_leg(rec, leg_i)
+
+ def _after_leg(self, rec, leg_i) -> dict:
+ n0 = len(self.points)
+ while not self.done and self.n_our_legs == leg_i:
+ self.step(self._arm_target())
+ self.shots.append(rec)
+ res = dict(self.results[leg_i]) if leg_i < len(self.results) else {"summary": "match over"}
+ self.run_to_decision()
+ res["points_finished"] = self.points[n0:]
+ return res
+
+ # ------------------------------------------------------------------ stroke controller (rally's, + power)
+ def plan_stroke(self, t_hit, p_hit, aim, power="normal"):
+ """The rally's stroke controller, plus (a) a pace choice and (b) up to 3 full rehearsals of the stroke on a
+ twin simulator from the current state (arm + the real ball): the aim point is corrected by the rehearsed
+ landing error. The rehearsal uses the player's contact time/point as given: a wrong contact misses in the
+ rehearsal too and is not corrected."""
+ self._power = power if power in POWER else "normal"
+ aim = np.asarray(aim, float)
+ rng = np.random.default_rng([self.lv["seed"], 7, self.n_our_legs]) # one draw per shot (adjust reuses it)
+ aim = aim + rng.normal(0.0, EXEC_SIGMA[self._power], 2)
+ aim_eff = aim.copy()
+ seed = self._ik_seed
+ best = None
+ for it in range(4):
+ self._ik_seed = seed
+ tg, info = rally.Rally.plan_stroke(self, t_hit, p_hit, aim_eff)
+ if not tg:
+ return tg, info
+ L, speed = self._rehearse(tg)
+ err = None if L is None else float(np.linalg.norm(np.asarray(L) - aim))
+ if best is None or (err is not None and (best[2] is None or err < best[2])):
+ best = (tg, info, err, L, speed)
+ if L is None or err < 0.04:
+ break
+ aim_eff = aim_eff + (aim - np.asarray(L))
+ tg, info, err, L, speed = best
+ info["power"] = self._power
+ info["rehearsal_landing"] = None if L is None else [round(float(x), 3) for x in L]
+ info["rehearsal_speed"] = None if speed is None else round(float(speed), 2)
+ return tg, info
+
+ def _rehearse(self, targets):
+ """Run `targets` on the twin from the full current state (arm and ball); (landing xy of the first contact
+ after the paddle, outgoing speed) or (None, None) if the paddle never touches the ball."""
+ tw = self._twin_session()
+ m, d = tw.m, tw.d
+ mj.mj_resetData(m, d)
+ d.qpos[:] = self.s.d.qpos; d.qvel[:] = self.s.d.qvel; d.qacc_warmstart[:] = self.s.d.qacc_warmstart
+ d.time = self.s.d.time
+ mj.mj_forward(m, d)
+ tw._target = self.s._target.copy(); tw._k = 0; tw._events = []; tw._last_touch = {}
+ tw._robot_table = 0; tw._v_out = None; tw._actions = []
+ for j in range(len(targets) + 150):
+ tw.step(targets[j] if j < len(targets) else targets[-1])
+ kinds = [e["kind"] for e in tw._events]
+ if "paddle" in kinds:
+ post = [e for e in tw._events[kinds.index("paddle") + 1:] if e["kind"] not in ("paddle", "net")]
+ if post:
+ sp = None if tw._v_out is None else float(np.linalg.norm(tw._v_out))
+ return post[0]["pos"][:2], sp
+ if d.qpos[2] < -0.3:
+ break
+ return None, None
+
+ def _pick_stroke(self, cands):
+ good = ([c for c in cands if c["ik"] < 1e-3 and c["ratio"] <= 1.0] or [c for c in cands if c["ik"] < 1e-3]
+ or cands)
+ power = getattr(self, "_power", "normal")
+ if power == "normal":
+ return min(good, key=lambda c: c["ratio"])
+ sp = sorted(good, key=lambda c: float(np.linalg.norm(c["v_out"])))
+ return sp[-1] if power == "hard" else sp[0]
+
+ # ------------------------------------------------------------------ views
+ CAMS = (([0.0, 0.30, 0.05], 3.6, 72.0, -33.0), # behind and above the robot, looking down the table
+ ([0.0, 0.05, 0.25], 4.0, 0.0, -8.0)) # from the side
+ # world poses of the two cameras as rendered (OpenGL: forward = view direction, image right = forward x up);
+ # pinhole, vertical field of view 45 deg, tiles 480 x 360 px -> focal length 434.6 px, principal point at the centre
+ # (wall-clock tasks: the positions are the centre of MuJoCo's two stereo eye cameras, which is what the mono render
+ # uses; the lock-step tasks' spec gave scene.camera[0], the left eye, 3.4 cm (ipd / 2) to the left: ~4-7 px off)
+ CAM_INFO = [{"name": "behind", "position": [-0.933, -2.5714, 2.0107], "forward": [0.2592, 0.7976, -0.5446],
+ "up": [0.1683, 0.518, 0.8387]},
+ {"name": "side", "position": [-3.9611, 0.05, 0.8067], "forward": [0.9903, 0.0, -0.1392],
+ "up": [0.1392, 0.0, 0.9903]}]
+ VIEW_BACK = (0, 2, 4, 6) # camera frames back from the latest: 0, 40, 80, 120 ms
+
+ def _extra_geoms(self, scn, opp_x):
+ def add(typ, size, pos, rgba, mat=np.eye(3)):
+ if scn.ngeom >= scn.maxgeom:
+ return
+ mj.mjv_initGeom(scn.geoms[scn.ngeom], typ, np.asarray(size, float), np.asarray(pos, float),
+ np.asarray(mat, float).ravel(), np.asarray(rgba, np.float32))
+ scn.ngeom += 1
+ # opponent: red paddle + a grey body behind it
+ add(mj.mjtGeom.mjGEOM_BOX, [0.075, 0.008, 0.075], [opp_x, OPP_Y, OPP_Z], [0.85, 0.1, 0.1, 1])
+ add(mj.mjtGeom.mjGEOM_CAPSULE, [0.14, 0.30, 0], [opp_x, OPP_Y + 0.35, 0.30], [0.35, 0.35, 0.4, 1])
+ # scale marks every 0.25 m along both side edges of the table and along both end lines
+ for y in np.arange(-1.25, 1.26, 0.25):
+ for x in (-0.7625, 0.7625):
+ add(mj.mjtGeom.mjGEOM_BOX, [0.03, 0.006, 0.002], [x, y, 0.002], [1, 0.9, 0.1, 1])
+ for x in np.arange(-0.75, 0.76, 0.25):
+ for y in (-1.37, 1.37):
+ add(mj.mjtGeom.mjGEOM_BOX, [0.006, 0.03, 0.002], [x, y, 0.002], [1, 0.9, 0.1, 1])
+
+ def render_views(self, width=480, height=360) -> bytes:
+ """PNG: 2 rows (behind-the-robot camera, side camera) x 4 columns (oldest -> latest camera frame, 40 ms
+ apart), each tile stamped with its time since the current ball was played."""
+ import imageio.v2 as imageio
+ from PIL import Image, ImageDraw
+ if not hasattr(self, "_renderer"):
+ self._renderer = mj.Renderer(self.s.m, height=height, width=width)
+ self._rd = mj.MjData(self.s.m)
+ self._cams = []
+ for lookat, dist, az, el in self.CAMS:
+ c = mj.MjvCamera(); c.lookat[:] = lookat; c.distance = dist; c.azimuth = az; c.elevation = el
+ self._cams.append(c)
+ r, rd = self._renderer, self._rd
+ hist = list(self.hist)
+ snaps = [hist[max(0, len(hist) - 1 - b)] for b in reversed(self.VIEW_BACK)]
+ rows = []
+ for c in self._cams:
+ tiles = []
+ for sn in snaps:
+ rd.qpos[:] = sn["qpos"]; mj.mj_forward(self.s.m, rd)
+ r.update_scene(rd, camera=c)
+ self._extra_geoms(r.scene, sn["opp_x"])
+ im = Image.fromarray(r.render())
+ ImageDraw.Draw(im).text((6, 4), f"t={sn['t']:.2f}s", fill=(255, 255, 255))
+ tiles.append(np.asarray(im))
+ rows.append(np.concatenate(tiles, axis=1))
+ buf = io.BytesIO()
+ imageio.imwrite(buf, np.concatenate(rows, axis=0), format="png")
+ return buf.getvalue()
+
+ def view_times(self):
+ hist = list(self.hist)
+ return [hist[max(0, len(hist) - 1 - b)]["t"] for b in reversed(self.VIEW_BACK)]
+
+ def decision_observation(self) -> dict:
+ st = self.s.state()
+ leg = self.leg
+ heard = [{"event": {"table_opp": "bounce on the opponent's half", "table_own": "bounce on your half",
+ "net": "net"}.get(e["kind"], e["kind"]),
+ "t": round(e["t"] - leg["launch"] * CONTROL_DT, 3)} for e in self.s._events]
+ return {"score": {"you": self.score[0], "opponent": self.score[1]}, "point": len(self.points) + 1,
+ "ball": "serve" if leg["kind"] == "serve" else "opponent's return",
+ "t_since_played": self.t_since_launch(),
+ "heard": heard, "view_times": self.view_times(),
+ "q": st["q"].round(4).tolist(), "paddle_pos": st["paddle_pos"].round(3).tolist(),
+ "paddle_normal": st["paddle_normal"].round(3).tolist()}
+
+ # ------------------------------------------------------------------ real-time control (observe / act / wait)
+ # The real-time protocol has no decision points: the world advances only through the agent's calls, each of which
+ # first costs its latency (the service decides how many control steps; see server.py). Between calls the arm keeps
+ # executing its current command: the rest of its planned stroke, then the speed-limited return to the ready pose.
+ def rt_advance(self, n_steps: int):
+ """Run up to n_steps control steps with the arm's current command. Stops early when a point ends (the world is
+ then static until the review) or the match is over. Returns (steps run, points finished, our shot results)."""
+ n0, r0, n = len(self.points), len(self.results), 0
+ while n < n_steps and not self.done and len(self.points) == n0:
+ self.step(self._arm_target()); n += 1
+ if len(self.points) > n0:
+ self.plan, self.plan_j = [], 0 # a new point: no stroke carries over; the arm returns to ready
+ return n, self.points[n0:], self.results[r0:]
+
+ def rt_act(self, T: float, pos, nrm, vel) -> dict:
+ """Replace the arm's command: the paddle state at contact T s from now (scheme B, no ball state). The swing is
+ planned from the arm's current state, so a new `act` corrects the one under way."""
+ t_hit = (self.k - self.leg["launch"]) * CONTROL_DT + float(T)
+ self._ik_seed = self._planned_hit if self.plan_j < len(self.plan) else None
+ plan, info = self.plan_paddle(t_hit, pos, nrm, vel)
+ info["T_from_now"] = round(float(T), 4)
+ if plan:
+ self.plan, self.plan_j = plan, 0
+ self.shots.append({"k": self.k, "leg": self.n_our_legs, **{k: info[k] for k in info if k != "paddle_vel_delivered"}})
+ if plan:
+ self.contact_k = self.k + info["n_swing_steps_available"]
+ self._last_act = info
+ return info
+
+ def rt_clear(self) -> None:
+ self.plan, self.plan_j = [], 0
+ self._last_act = None
+ self.contact_k = self.k
+
+ # ------------------------------------------------------------------ paddle-level stroke (scheme B)
+ PADDLE_SCATTER = dict(pos=0.004, ang_deg=0.6, speed=0.02) # execution scatter of the paddle state at contact
+
+ def _ik_best(self, pos, normal, preferred=None):
+ """Choose an accurate branch the arm can reach with little joint travel.
+
+ A precise pose on the far side of a joint's range can take longer than the
+ entire incoming flight. Preserve cheap local solves for nearby commands;
+ otherwise compare deterministic starts using joint-speed-normalized travel.
+ """
+ s = self.s
+ first = preferred if preferred is not None else s.d.qpos[s._qadr]
+ best = self._ik(pos, normal, first)
+ def travel(candidate):
+ return float(np.max(np.abs(candidate[0] - s._target) / VEL_LIMIT))
+ def rank(candidate):
+ return (0, travel(candidate)) if candidate[1] < 1e-4 else (1, candidate[1])
+ if best[1] < 1e-4 and travel(best) <= .35:
+ return best
+ if not hasattr(self, "_ik_starts"):
+ rng = np.random.default_rng(0)
+ q0 = s.inst["q0"]
+ self._ik_starts = [q0] + [np.clip(q0+rng.normal(0, .8, 7), s.JOINT_LOW+.05, s.JOINT_HIGH-.05)
+ for _ in range(12)]
+ for seed in self._ik_starts:
+ if np.array_equal(seed, first):
+ continue
+ candidate = self._ik(pos, normal, seed)
+ if rank(candidate) < rank(best):
+ best = candidate
+ if best[1] < 1e-4 and travel(best) <= .35:
+ break
+ return best
+
+ def plan_paddle(self, t_hit, p_c, nrm, v_p):
+ """Scheme B: the player gives the paddle state at contact (time t_hit s after the ball was played, blade-centre
+ position p_c, blade face normal nrm, blade velocity v_p). The controller only makes the arm deliver it: IK,
+ a speed-weighted Jacobian inverse, a joint-speed-limited cubic swing and robot-only rehearsals (no ball) that
+ correct the PD controller's lag. It uses no ball state and does not aim."""
+ s = self.s
+ p_c = np.asarray(p_c, float); nrm = np.asarray(nrm, float); nrm = nrm / np.linalg.norm(nrm)
+ v_p = np.asarray(v_p, float)
+ info = {"t_hit": t_hit, "paddle_pos": p_c.round(4).tolist(), "paddle_normal": nrm.round(4).tolist(),
+ "paddle_vel": v_p.round(3).tolist()}
+ k_hit = self._cur()["launch"] + int(round(t_hit / CONTROL_DT))
+ n_avail = k_hit - self.k
+ info["n_swing_steps_available"] = int(n_avail)
+ if n_avail < 1:
+ info["stroke"] = "too late: the contact time has already passed"
+ return [], info
+ rng = np.random.default_rng([self.lv["seed"], 11, self.n_our_legs])
+ sc = self.PADDLE_SCATTER
+ p_c = p_c + rng.normal(0.0, sc["pos"], 3)
+ axis = np.cross(nrm, rng.normal(0.0, 1.0, 3)); axis /= np.linalg.norm(axis)
+ ang = np.radians(rng.normal(0.0, sc["ang_deg"]))
+ nrm = nrm * np.cos(ang) + np.cross(axis, nrm) * np.sin(ang); nrm /= np.linalg.norm(nrm)
+ v_p = v_p * (1.0 + rng.normal(0.0, sc["speed"]))
+ q_h, res = self._ik_best(p_c, nrm, self._ik_seed)
+ info["ik_residual"] = round(float(res), 5)
+ Jp = s.jacobian(q_h)[:3]
+ Winv = np.diag(VEL_LIMIT ** 2)
+ qd_h = Winv @ Jp.T @ np.linalg.solve(Jp @ Winv @ Jp.T, v_p)
+ ratio = float(np.max(np.abs(qd_h) / VEL_LIMIT))
+ scale = max(1.0, ratio / 0.9)
+ qd_h = qd_h / scale
+ info["speed_scale"] = round(scale, 3)
+ q_s = s._target.copy(); v_s = self._target_vel()
+ n_sw = int(n_avail)
+ for n in (range(25, int(n_avail) + 1) if np.max(np.abs(v_s)) < 1e-6 else []):
+ sw = hermite(q_s, np.zeros(7), q_h, qd_h, n * CONTROL_DT, n)
+ if np.max(np.abs(np.diff(np.vstack([q_s, sw]), axis=0)) / (VEL_LIMIT * CONTROL_DT)) <= 0.97:
+ n_sw = n
+ break
+ n_sw = int(min(n_sw, n_avail))
+ info["n_swing_steps"] = n_sw
+ q_goal, qd_goal = q_h.copy(), qd_h.copy()
+ self._planned_hit = q_h.copy()
+ best = None
+ for it in range(5):
+ tg = self._swing_targets(q_goal, qd_goal, n_avail, n_sw)
+ p, n_act, v_act = self._simulate_arm(tg, n_avail)
+ angle = float(np.arccos(np.clip(n_act @ nrm, -1, 1)))
+ loss = np.linalg.norm(p-p_c) + .1*angle + .01*np.linalg.norm(v_act-v_p/scale)
+ if best is None or loss < best[0]:
+ best = (loss, tg, p.copy(), n_act.copy(), v_act.copy())
+ # Further rehearsal is unnecessary once delivery is already well
+ # below the declared scatter; avoid holding up the wallclock loop.
+ if (it == 4 or (np.linalg.norm(p-p_c) < .0005 and angle < np.radians(.1)
+ and np.linalg.norm(v_act-v_p/scale) < .005)):
+ break
+ J = s.jacobian(q_goal)
+ e = np.r_[p_c - p, np.cross(n_act, nrm)]
+ q_goal = np.clip(q_goal + J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), e),
+ s.JOINT_LOW + 1e-4, s.JOINT_HIGH - 1e-4)
+ qd_goal = qd_goal + Winv @ Jp.T @ np.linalg.solve(Jp @ Winv @ Jp.T, (v_p / scale) - v_act) * 0.7
+ qd_goal = qd_goal / max(1.0, float(np.max(np.abs(qd_goal) / VEL_LIMIT)))
+ _, tg, p, n_act, v_act = best
+ info["normal_error_deg"] = round(float(np.degrees(np.arccos(np.clip(n_act @ nrm, -1, 1)))), 3)
+ info["blade_error_m"] = round(float(np.linalg.norm(p - p_c)), 4)
+ info["paddle_vel_delivered"] = [round(float(x), 3) for x in v_act]
+ notes = []
+ if info["blade_error_m"] > .03 or info["normal_error_deg"] > 5:
+ notes.append("command not achievable accurately: see blade_error_m / normal_error_deg")
+ if res > 1e-3: notes.append(f"pose not reachable exactly (IK residual {res:.3f})")
+ if scale > 1.0: notes.append(f"paddle speed limited by the joint speed limits (x{1 / scale:.2f})")
+ if n_sw < 20: notes.append("short swing (little time left)")
+ info["stroke"] = "; ".join(notes) or "ok"
+ return tg, info
+
+
+def render_video(actions, level, out, fps=25):
+ """Replay video, the two decision cameras side by side, 4x slow motion (every 3rd frame while no ball is live)."""
+ import imageio.v2 as imageio
+ mt = Match(level)
+ r = mj.Renderer(mt.s.m, height=360, width=560)
+ cams = []
+ for lookat, dist, az, el in Match.CAMS:
+ c = mj.MjvCamera(); c.lookat[:] = lookat; c.distance = dist; c.azimuth = az; c.elevation = el
+ cams.append(c)
+ w = imageio.get_writer(out, fps=fps, macro_block_size=8)
+ from PIL import Image, ImageDraw
+ for k, q in enumerate(actions):
+ mt.step(q)
+ if (not mt.in_play() or mt.leg["state"] == "done") and k % 3:
+ continue
+ imgs = []
+ for c in cams:
+ r.update_scene(mt.s.d, camera=c)
+ mt._extra_geoms(r.scene, mt.opp_x())
+ imgs.append(r.render())
+ im = Image.fromarray(np.concatenate(imgs, axis=1))
+ ImageDraw.Draw(im).text((8, 6), f"you {mt.score[0]} : {mt.score[1]} opponent (level {level})",
+ fill=(255, 255, 255))
+ w.append_data(np.asarray(im))
+ w.close(); r.close()
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/rally.json b/scripts/roboolympics/shared/sports/tabletennis/sim/rally.json
new file mode 100644
index 0000000000..0b9a9f3a1e
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/tabletennis/sim/rally.json
@@ -0,0 +1,100 @@
+{
+ "note": "5 incoming balls (DeepMind serves, CC-BY-4.0), reach-filtered and robust for the reference stroke; selected with numpy seed 2026 (one per hit-x quintile)",
+ "balls": [
+ {
+ "id": 827,
+ "pos": [
+ 0.3060355857000118,
+ 1.4674673460073875,
+ 0.12820465262917263
+ ],
+ "vel": [
+ -1.112151855228876,
+ -5.471515434933733,
+ -2.1092454631890125
+ ],
+ "spin": [
+ -0.35320826583928316,
+ -4.619090418978232,
+ -6.529630599015004
+ ],
+ "source": "DeepMind competitive_robot_table_tennis serves.json id 827"
+ },
+ {
+ "id": 1757,
+ "pos": [
+ -0.21216441586239737,
+ 1.418508513075304,
+ 0.3219075218156344
+ ],
+ "vel": [
+ 0.27465526732770573,
+ -4.462502801964814,
+ -0.8987376693020879
+ ],
+ "spin": [
+ 12.36978943317683,
+ -6.740979501213409,
+ -23.313588111238552
+ ],
+ "source": "DeepMind competitive_robot_table_tennis serves.json id 1757"
+ },
+ {
+ "id": 1598,
+ "pos": [
+ -0.6098590604191972,
+ 1.498004960690973,
+ 0.2866195108684692
+ ],
+ "vel": [
+ 0.8978951239877346,
+ -4.961401750364483,
+ -1.3173997993835385
+ ],
+ "spin": [
+ -0.6843690522592096,
+ -1.650588570147271,
+ -3.1858990293973255
+ ],
+ "source": "DeepMind competitive_robot_table_tennis serves.json id 1598"
+ },
+ {
+ "id": 579,
+ "pos": [
+ -0.3343478406667241,
+ 1.4504041815872282,
+ 0.3109239191740299
+ ],
+ "vel": [
+ 0.7853063428661995,
+ -4.725880944434543,
+ -2.352729350492706
+ ],
+ "spin": [
+ 5.394878666089257,
+ 5.7460033881289005,
+ -2.6452322700214332
+ ],
+ "source": "DeepMind competitive_robot_table_tennis serves.json id 579"
+ },
+ {
+ "id": 2618,
+ "pos": [
+ -0.470465824135137,
+ 1.4562762311376845,
+ 0.18153216758206328
+ ],
+ "vel": [
+ 1.3926624045407625,
+ -5.707174242684581,
+ -2.1689460676131613
+ ],
+ "spin": [
+ 12.004333357799021,
+ -3.2651510124388516,
+ -23.603094304286483
+ ],
+ "source": "DeepMind competitive_robot_table_tennis serves.json id 2618"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/rally.py b/scripts/roboolympics/shared/sports/tabletennis/sim/rally.py
new file mode 100644
index 0000000000..cd3f7ad7a5
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/tabletennis/sim/rally.py
@@ -0,0 +1,570 @@
+"""Core of the table-tennis rally service (interactive mode): the episode, the stroke controller and the views.
+
+An episode = N_BALLS incoming balls (recorded DeepMind serves, `rally.json`), one after another. Per ball:
+ ready READY_STEPS control steps: the service brings the arm back to the ready pose Q0; the next ball is held
+ at its launch state, out of play.
+ launch the ball is released from its recorded state (bounces on the opponent's half, crosses the net).
+ pause at the 5th camera frame after the ball's bounce on the opponent's half the world stops: DECISION POINT.
+ shot the decision (swing: contact time, contact point, aim point; or skip) arrives; first the think delay
+ runs (arm holding the ready pose, ball flying), then the stroke controller plans and executes the swing.
+ outcome the ball's first contact after the paddle, or the ball out of play / 2.5 s after the launch.
+The whole episode is recorded as (applied joint targets, launch schedule) and replays bit-exactly (`replay()`).
+"""
+from __future__ import annotations
+
+import io
+import json
+import os
+import xml.etree.ElementTree as ET
+from pathlib import Path
+
+import numpy as np
+
+import mujoco as mj
+import rcb_tt
+from rcb_tt import CONTROL_DT, VEL_LIMIT
+
+HERE = Path(__file__).resolve().parent
+SCENE = HERE / "scene" / "tt_scene.xml"
+INSTANCE = HERE / "instance.npz"
+BALLS = json.load(open(HERE / "rally.json"))["balls"]
+N_BALLS = len(BALLS)
+READY_STEPS = 60 # 0.6 s between one outcome and the next launch
+BALL_STEPS = 250 # a ball is over at the latest 2.5 s after its launch
+CAM_EVERY = 2 # 50 Hz camera
+NOISE_SIGMA = 0.003
+NOISE_SEED = 314159
+AIM_DEFAULT = (0.0, 0.7)
+ADJUST_FRAMES = 3 # adjust point: 3rd camera frame (0.06 s) after the bounce on our half
+DECISION_FRAMES = 5 # decision point: 5th camera frame (0.1 s) after the bounce on the opponent's half
+AIM_BIAS = np.array([-0.1, -0.28]) # controller calibration: its forward model sends clean contacts ~(0.1, 0.28) m long/right
+BALL_R, HALF_T, E_PADDLE = 0.02, 0.0075, 0.985
+OPP_HALF = dict(table_edges_valid=True, target_center=np.array([0.0, 0.685]), target_half=np.array([0.7625, 0.685]))
+rcb_tt.HORIZON = 10 ** 7 # no episode-level step cap in the tooling; the rally ends itself
+
+
+def world_spin(d) -> np.ndarray:
+ R = np.zeros(9)
+ mj.mju_quat2Mat(R, d.qpos[3:7])
+ return R.reshape(3, 3) @ d.qvel[3:6]
+
+
+def _ball_only_xml(path: Path) -> str:
+ root = ET.parse(path).getroot()
+ wb = root.find("worldbody")
+ for b in list(wb):
+ if b.tag == "body" and b.get("name") == "link0":
+ wb.remove(b)
+ for el in root.findall("actuator"):
+ root.remove(el)
+ con = root.find("contact")
+ for el in list(con):
+ if el.tag == "exclude" or (el.tag == "pair" and el.get("geom2") == "paddle_blade"):
+ con.remove(el)
+ root.find("compiler").set("meshdir", str((path.parent / "assets").resolve()))
+ return ET.tostring(root, encoding="unicode")
+
+
+class BallModel:
+ """Ball-only copy of the scene (same ball / table / net physics): the stroke controller's own forward model."""
+
+ def __init__(self):
+ from mujoco import rollout
+ root = ET.fromstring(_ball_only_xml(SCENE))
+ sensors = ET.SubElement(root, "sensor")
+ for geom in ("geom_table", "geom_net", "floor"):
+ ET.SubElement(sensors, "distance", geom1="geom_ball", geom2=geom, cutoff="10")
+ self.m = mj.MjModel.from_xml_string(ET.tostring(root, encoding="unicode"))
+ self.d = mj.MjData(self.m)
+ self.native = rollout.Rollout()
+
+ def rollout(self, p, v, w_world, n, stop_at_contact=False):
+ # MuJoCo's native loop releases the GIL and avoids thousands of Python transitions.
+ state0 = np.r_[0.0, p, 1.0, 0.0, 0.0, 0.0, v, w_world]
+ states, distances = self.native.rollout(self.m, self.d, state0, nstep=n)
+ st = states[0]
+ P, V = st[:, 1:4].copy(), st[:, 8:11].copy()
+ q, w = st[:, 4:8], st[:, 11:14]
+ # Quaternion rotation of local angular velocity into world coordinates.
+ qw, qv = q[:, :1], q[:, 1:]
+ W = w + 2*np.cross(qv, np.cross(qv, w) + qw*w)
+ hits = np.flatnonzero(np.any(distances[0] <= 0, axis=1))
+ first = None
+ if len(hits):
+ i = int(hits[0]); geom = int(np.argmin(distances[0, i]))
+ kind = "net" if geom == 1 else ("floor" if geom == 2 else
+ ("table_opp" if P[i, 1] > 0 else "table_own"))
+ first = (i, kind, P[i].copy())
+ if stop_at_contact:
+ return P[:i+1], V[:i+1], W[:i+1], first
+ return P, V, W, first
+
+
+def hermite(q0, v0, q1, v1, T, n):
+ t = np.arange(1, n + 1) * (T / n)
+ s = t / T
+ h00 = 2 * s**3 - 3 * s**2 + 1; h10 = s**3 - 2 * s**2 + s; h01 = -2 * s**3 + 3 * s**2; h11 = s**3 - s**2
+ return h00[:, None] * q0 + h10[:, None] * T * v0 + h01[:, None] * q1 + h11[:, None] * T * v1
+
+
+class Rally:
+ """The episode. Live: step() / run_to_decision() / shot(). Replay: replay(actions, schedule)."""
+
+ def __init__(self):
+ self.s = rcb_tt.Session(instance=str(INSTANCE), scene=str(SCENE))
+ self.bm = BallModel()
+ self.schedule: list[dict] = [] # per ball: {"ball", "hold_from", "launch"}
+ self.i = -1 # current ball (index into BALLS), -1 before the first hold
+ self.frames: list[dict] = [] # camera frames of the current ball
+ self.results: list[dict] = [] # per-ball outcome
+ self.shots: list[dict] = [] # per-ball decision record
+ self.done = False
+ self.phase = "swing" # which decision the episode waits for: swing | adjust | done
+ self.plan, self.plan_j, self._rec = [], 0, {}
+ self._twin = None
+ self._ik_seed = None
+ self._schedule_ball(0, 0)
+
+ # ------------------------------------------------------------------ bookkeeping
+ @property
+ def k(self) -> int:
+ return self.s._k
+
+ def _schedule_ball(self, i, hold_from):
+ self.schedule.append({"ball": i, "hold_from": hold_from, "launch": hold_from + READY_STEPS})
+ self.i = i
+ self.frames = []
+ self._park()
+
+ def _cur(self) -> dict:
+ return self.schedule[-1]
+
+ def _park(self):
+ b = BALLS[self.i]
+ d = self.s.d
+ d.qpos[0:3] = b["pos"]; d.qpos[3:7] = [1, 0, 0, 0]; d.qvel[0:3] = b["vel"]; d.qvel[3:6] = b["spin"]
+ s = self.s
+ s._events.clear(); s._last_touch.clear(); s._robot_table = 0; s._v_out = None
+
+ def in_play(self) -> bool:
+ return self.k > self._cur()["launch"]
+
+ def t_since_launch(self) -> float:
+ return round((self.k - self._cur()["launch"]) * CONTROL_DT, 6)
+
+ def ball_outcome_final(self) -> bool:
+ if not self.in_play():
+ return False
+ if self.k - self._cur()["launch"] >= BALL_STEPS:
+ return True
+ kinds = [e["kind"] for e in self.s._events]
+ if "paddle" in kinds and any(x != "paddle" for x in kinds[kinds.index("paddle") + 1:]):
+ return True
+ if any(x in ("floor", "robot", "other") for x in kinds):
+ return True
+ p = self.s.d.qpos
+ return bool(p[2] < -0.3 or p[1] < -2.6)
+
+ # ------------------------------------------------------------------ stepping (shared by live and replay)
+ def step(self, q):
+ self.s.step(q)
+ cur = self._cur()
+ if self.k <= cur["launch"]:
+ self._park() # held out of play until the launch step
+ elif (self.k - cur["launch"]) % CAM_EVERY == 0:
+ p = self.s.d.qpos[0:3]
+ if p[2] > -0.5 and p[1] > -2.6 and abs(p[0]) < 2.0:
+ f = (self.k - cur["launch"]) // CAM_EVERY
+ noise = np.random.default_rng([NOISE_SEED, cur["ball"], f]).normal(0.0, NOISE_SIGMA, 3)
+ self.frames.append({"t": self.t_since_launch(), "pos": [round(float(x), 4) for x in p + noise]})
+
+ def _close_ball(self):
+ v = rcb_tt.judge(self.s._events, OPP_HALF, robot_env_contact=self.s._robot_table)
+ kinds = [e["kind"] for e in self.s._events]
+ ret = bool(v["success"])
+ res = {"ball": self.i, "returned": ret, "hit": int(v["hit"]), "n_paddle_contacts": int(v["n_paddle_contacts"]),
+ "landed_opponent_half": int(v["landed_opponent_half"]), "landing_x": round(float(v["landing_x"]), 4),
+ "landing_y": round(float(v["landing_y"]), 4), "net_touch": int(v["net_touch"]),
+ "robot_env_contact": int(v["robot_env_contact"]), "events": kinds, "step": self.k,
+ "own_bounces_before_hit": int(v["own_bounces_before_hit"])}
+ if ret:
+ res["summary"] = f"returned: landed on the opponent's half at x={v['landing_x']:.2f}, y={v['landing_y']:.2f}"
+ elif not v["hit"]:
+ res["summary"] = "missed: no paddle contact"
+ elif v["robot_env_contact"]:
+ res["summary"] = "fault: the arm or paddle touched the table/net/floor"
+ elif v["n_paddle_contacts"] != 1:
+ res["summary"] = "fault: more than one paddle contact"
+ elif v["own_bounces_before_hit"] != 1:
+ res["summary"] = "fault: hit before the ball bounced on your half (volley)"
+ elif v["landed"]:
+ res["summary"] = (f"fault: first contact after the hit was {kinds[kinds.index('paddle') + 1:][0]} at "
+ f"x={v['landing_x']:.2f}, y={v['landing_y']:.2f}")
+ else:
+ res["summary"] = "fault: the ball did not land"
+ self.results.append(res)
+ return res
+
+ def replay(self, actions, schedule) -> None:
+ """Fresh replay of a recorded episode (same actions and launch schedule). Each ball is judged at the
+ first step its outcome is final, exactly as in the live episode (results in self.results)."""
+ sched = [dict(x) for x in schedule]
+ self.schedule = [sched[0]]; self.i = sched[0]["ball"]; self._park()
+ j, closed = 1, set()
+ for q in actions:
+ if j < len(sched) and self.k == sched[j]["hold_from"]:
+ self.schedule.append(sched[j]); self.i = sched[j]["ball"]; self.frames = []; self._park()
+ j += 1
+ self.step(q)
+ if self.i not in closed and self.ball_outcome_final():
+ self._close_ball(); closed.add(self.i)
+
+ # ------------------------------------------------------------------ live episode
+ def _ready_target(self):
+ """Service-driven return to the ready pose Q0 (speed-limited, 60 % of the joint speed limits)."""
+ tgt = self.s._target
+ lim = VEL_LIMIT * CONTROL_DT * 0.6
+ return tgt + np.clip(self.s.inst["q0"] - tgt, -lim, lim)
+
+ def run_to_decision(self) -> None:
+ """Advance until the current ball reaches its decision point (first camera frame past the net)."""
+ while not self.done:
+ self.step(self._ready_target())
+ if self.in_play() and self._decision_due():
+ return
+ if self.ball_outcome_final(): # (cannot normally happen before the decision point)
+ self._next_ball()
+
+ def _decision_due(self) -> bool:
+ """Decision point: the DECISION_FRAMES-th camera frame after the ball's bounce on the opponent's half
+ (or, if it never bounces there, the first frame past the net)."""
+ ev = [e for e in self.s._events if e["kind"] == "table_opp"]
+ if ev:
+ t_b = ev[0]["t"] - self._cur()["launch"] * CONTROL_DT
+ return sum(1 for f in self.frames if f["t"] > t_b) >= DECISION_FRAMES
+ return bool(self.frames and self.frames[-1]["pos"][1] < 0.0)
+
+ def _next_ball(self):
+ self._close_ball()
+ if self.i + 1 < N_BALLS:
+ self._schedule_ball(self.i + 1, self.k)
+ else:
+ for _ in range(20): # a short tail so the last landing is in the video
+ self.step(self.s._target)
+ self.done = True
+
+ def decision_observation(self) -> dict:
+ st = self.s.state()
+ return {"ball_index": self.i, "n_balls": N_BALLS, "t_since_launch": self.t_since_launch(),
+ "frames": list(self.frames), "q": st["q"].round(4).tolist(),
+ "paddle_pos": st["paddle_pos"].round(4).tolist(), "paddle_normal": st["paddle_normal"].round(4).tolist(),
+ "events": [{"event": e["kind"], "t_since_launch": round(e["t"] - self._cur()["launch"] * CONTROL_DT, 3)}
+ for e in self.s._events],
+ "returns_so_far": sum(r["returned"] for r in self.results), "results_so_far": list(self.results)}
+
+ def _adjust_due(self) -> bool:
+ """Second decision point: the ADJUST_FRAMES-th camera frame after the bounce on our half."""
+ ev = [e for e in self.s._events if e["kind"] == "table_own"]
+ if not ev or any(e["kind"] == "paddle" for e in self.s._events):
+ return False
+ t_b = ev[0]["t"] - self._cur()["launch"] * CONTROL_DT
+ return sum(1 for f in self.frames if f["t"] > t_b) >= ADJUST_FRAMES
+
+ def _run_plan(self, stop_at_adjust: bool) -> bool:
+ """Execute the current plan (then hold) until the ball's outcome (False) or the adjust point (True)."""
+ while not self.ball_outcome_final():
+ self.step(self.plan[self.plan_j] if self.plan_j < len(self.plan) else self.s._target)
+ self.plan_j += 1
+ if stop_at_adjust and self._adjust_due():
+ return True
+ return False
+
+ def _finish_ball(self, rec) -> dict:
+ if self.s._v_out is not None:
+ rec["v_out_actual"] = [round(float(x), 3) for x in self.s._v_out]
+ self.shots.append(rec)
+ self._next_ball()
+ res = dict(self.results[-1]); res.update({k: rec[k] for k in rec if k not in ("decision", "adjust")})
+ self.phase = "done" if self.done else "swing"
+ if not self.done:
+ self.run_to_decision()
+ return res
+
+ def shot(self, decision: dict, delay_steps: int) -> dict:
+ """Decision 1 (swing / skip): think delay (the arm holds its ready pose, the ball flies), then the stroke
+ controller plans and starts the swing; runs to the adjust point (-> {"phase": "adjust"}) or, if there is
+ none, to the ball's outcome and on to the next ball's first decision point (-> the ball's result)."""
+ rec = {"ball": self.i, "decision": decision, "delay_steps": int(delay_steps), "k_decision": self.k}
+ self.plan, self.plan_j = [], 0
+ self._ik_seed = None
+ self._planned_hit = None
+ for _ in range(delay_steps):
+ if self.ball_outcome_final():
+ break
+ self.step(self.s._target)
+ rec["k_exec"] = self.k
+ if decision.get("type") == "swing" and not self.ball_outcome_final():
+ self.plan, info = self.plan_stroke(float(decision["t"]), np.asarray(decision["pos"], float),
+ np.asarray(decision.get("aim", AIM_DEFAULT), float))
+ rec.update(info)
+ self._rec = rec
+ if decision.get("type") == "swing" and self._run_plan(stop_at_adjust=True):
+ self.phase = "adjust"
+ return {"phase": "adjust", "ball": self.i, **{k: rec[k] for k in rec if k != "decision"}}
+ self._run_plan(stop_at_adjust=False)
+ return self._finish_ball(rec)
+
+ def adjust(self, decision: dict, delay_steps: int) -> dict:
+ """Decision 2 (adjust / keep): during the think delay the swing already under way continues; then, for an
+ adjust, the stroke controller re-plans the rest of the swing from the arm's current motion."""
+ rec = self._rec
+ rec["adjust"] = decision
+ rec["adjust_delay_steps"] = int(delay_steps)
+ rec["k_adjust_decision"] = self.k
+ for _ in range(delay_steps):
+ if self.ball_outcome_final():
+ break
+ self.step(self.plan[self.plan_j] if self.plan_j < len(self.plan) else self.s._target)
+ self.plan_j += 1
+ rec["k_adjust_exec"] = self.k
+ self._ik_seed = getattr(self, "_planned_hit", None)
+ if decision.get("type") == "adjust" and not self.ball_outcome_final():
+ plan, info = self.plan_stroke(float(decision["t"]), np.asarray(decision["pos"], float),
+ np.asarray(decision.get("aim", rec.get("aim", AIM_DEFAULT)), float))
+ rec["adjust_info"] = info
+ if plan:
+ self.plan, self.plan_j = plan, 0
+ self._run_plan(stop_at_adjust=False)
+ return self._finish_ball(rec)
+
+ # ------------------------------------------------------------------ stroke controller
+ def _twin_session(self):
+ if self._twin is None:
+ self._twin = rcb_tt.Session(instance=str(INSTANCE), scene=str(SCENE))
+ return self._twin
+
+ def _simulate_arm(self, targets, n):
+ """Robot-only rollout of `targets` from the live arm state; paddle (pos, normal, vel) after n steps."""
+ tw = self._twin_session()
+ m, d = tw.m, tw.d
+ mj.mj_resetData(m, d)
+ d.qpos[tw._qadr] = self.s.d.qpos[self.s._qadr]; d.qvel[tw._vadr] = self.s.d.qvel[self.s._vadr]
+ d.qpos[0:3] = [3.0, 3.0, 5.0]; d.qpos[3:7] = [1, 0, 0, 0]
+ mj.mj_forward(m, d)
+ tw._target = self.s._target.copy(); tw._k = 0; tw._actions = []; tw._events = []; tw._last_touch = {}
+ for j in range(n):
+ d.qpos[0:3] = [3.0, 3.0, 5.0]; d.qvel[0:6] = 0
+ tw.step(targets[j])
+ st = tw.state()
+ return st["paddle_pos"], st["paddle_normal"], st["paddle_vel"]
+
+ def _shoot(self, p0, spin, aim):
+ """Outgoing velocities whose ball-only flight lands at `aim` and clears the net by >= 5 cm (one per launch
+ angle)."""
+ cands = []
+ for vz in (0.5, 1.0, 1.5, 2.0, 2.5, 3.0):
+ v = np.array([aim[0] - p0[0], 5.0, vz])
+ for _ in range(10):
+ P, _, _, first = self.bm.rollout(p0, v, spin, 1500, stop_at_contact=True)
+ L = first[2][:2] if first else np.array([9.0, 9.0])
+ err = L - aim
+ if np.linalg.norm(err) < 0.01:
+ i0 = np.argmin(np.abs(P[:, 1]))
+ if first[1] == "table_opp" and P[i0, 2] > 0.2:
+ cands.append(v.copy())
+ break
+ J = np.zeros((2, 2))
+ for c in range(2):
+ dv = np.zeros(3); dv[c] = 1e-3
+ _, _, _, f2 = self.bm.rollout(p0, v + dv, spin, 1500, stop_at_contact=True)
+ L2 = f2[2][:2] if f2 else np.array([9.0, 9.0])
+ J[:, c] = (L2 - L) / 1e-3
+ try:
+ v[:2] -= np.linalg.lstsq(J, err, rcond=None)[0]
+ except np.linalg.LinAlgError:
+ break
+ return cands or [np.array([aim[0] - p0[0], 5.0, 1.5])]
+
+ def _stroke_for(self, v_in, v_out, p_hit):
+ """Impulse model -> blade normal, contact point, paddle velocity; IK and joint velocity at the hit."""
+ s = self.s
+ dv = v_out - v_in
+ nrm = dv / np.linalg.norm(dv)
+ vpn = np.linalg.norm(dv) / (1 + E_PADDLE) + v_in @ nrm
+ v_p = vpn * nrm + (v_in - (v_in @ nrm) * nrm)
+ p_c = p_hit - nrm * (BALL_R + HALF_T)
+ q_h, res = self._ik(p_c, nrm, self._ik_seed if self._ik_seed is not None else s.inst["q0"])
+ Jp = s.jacobian(q_h)[:3]
+ Winv = np.diag(VEL_LIMIT ** 2)
+ qd_h = Winv @ Jp.T @ np.linalg.solve(Jp @ Winv @ Jp.T, v_p)
+ ratio = float(np.max(np.abs(qd_h) / VEL_LIMIT))
+ return dict(nrm=nrm, v_p=v_p, p_c=p_c, q_h=q_h, qd_h=qd_h, ik=res, ratio=ratio, v_out=v_out)
+
+ def plan_stroke(self, t_hit, p_hit, aim):
+ """Swing so that the blade centre meets a ball centred at `p_hit` at `t_hit` (s after launch) and sends it
+ towards `aim`. The blade angle and speed come from the incoming ball's velocity/spin at that time (the
+ controller's own forward model) and an impulse model of the paddle (normal restitution 0.985 in the paddle frame, no slip); IK + a
+ speed-weighted Jacobian inverse give the hit configuration; a cubic swing (at most 0.35 s) and follow-through,
+ refined by 4 robot-only rehearsals so the lagging PD controller puts the blade where it was planned."""
+ info = {"t_hit": t_hit, "p_hit": [float(x) for x in p_hit], "aim": [float(x) for x in aim]}
+ cur = self._cur()
+ k_hit = cur["launch"] + int(round(t_hit / CONTROL_DT))
+ n_avail = k_hit - self.k
+ info["n_swing_steps_available"] = int(n_avail)
+ if n_avail < 1:
+ info["stroke"] = "too late: the contact time has already passed"
+ return [], info
+ # incoming ball at the contact time, from the ball's current state (forward model)
+ d = self.s.d
+ n_roll = max(1, int(round((k_hit - self.k) * CONTROL_DT / 0.001)))
+ P, V, W, _ = self.bm.rollout(d.qpos[0:3].copy(), d.qvel[0:3].copy(), world_spin(d), n_roll)
+ v_in, w_in = V[-1], W[-1]
+ cands = [self._stroke_for(v_in, v, np.asarray(p_hit, float))
+ for v in self._shoot(np.asarray(p_hit, float), -0.5 * w_in, np.asarray(aim, float) + AIM_BIAS)]
+ c = self._pick_stroke(cands)
+ v_out, nrm, v_p, p_c, q_h, qd_h = c["v_out"], c["nrm"], c["v_p"], c["p_c"], c["q_h"], c["qd_h"]
+ s = self.s
+ info["ik_residual"] = round(float(c["ik"]), 5)
+ Jp = s.jacobian(q_h)[:3]
+ Winv = np.diag(VEL_LIMIT ** 2)
+ scale = max(1.0, c["ratio"] / 0.9)
+ qd_h = qd_h / scale
+ info["speed_scale"] = round(scale, 3)
+ # swing duration: the shortest (>= 0.25 s) whose cubic stays under the speed limits, within the time left
+ q_s = self.s._target.copy()
+ v_s = self._target_vel()
+ n_sw = int(n_avail)
+ for n in (range(25, int(n_avail) + 1) if np.max(np.abs(v_s)) < 1e-6 else []):
+ sw = hermite(q_s, np.zeros(7), q_h, qd_h, n * CONTROL_DT, n)
+ if np.max(np.abs(np.diff(np.vstack([q_s, sw]), axis=0)) / (VEL_LIMIT * CONTROL_DT)) <= 0.97:
+ n_sw = n
+ break
+ n_sw = int(min(n_sw, n_avail))
+ info["n_swing_steps"] = n_sw
+ q_goal, qd_goal = q_h.copy(), qd_h.copy()
+ self._planned_hit = q_h.copy()
+ for it in range(5):
+ tg = self._swing_targets(q_goal, qd_goal, n_avail, n_sw)
+ p, n_act, v_act = self._simulate_arm(tg, n_avail)
+ if it == 4:
+ break
+ J = s.jacobian(q_goal)
+ e = np.r_[p_c - p, np.cross(n_act, nrm)]
+ q_goal = np.clip(q_goal + J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), e),
+ s.JOINT_LOW + 1e-4, s.JOINT_HIGH - 1e-4)
+ qd_goal = qd_goal + Winv @ Jp.T @ np.linalg.solve(Jp @ Winv @ Jp.T, (v_p / scale) - v_act) * 0.7
+ qd_goal = qd_goal / max(1.0, float(np.max(np.abs(qd_goal) / VEL_LIMIT)))
+ info["blade_error_m"] = round(float(np.linalg.norm(p - p_c)), 4)
+ info["n_plan"] = [round(float(x), 4) for x in nrm]; info["v_out_plan"] = [round(float(x), 3) for x in v_out]; info["v_in"] = [round(float(x), 3) for x in v_in]
+ info["paddle_v_plan"] = [round(float(x), 3) for x in v_p / scale]; info["paddle_v_twin"] = [round(float(x), 3) for x in v_act]
+ info["stroke"] = "ok" if n_sw >= 20 else "short swing (little time left: slow paddle)"
+ return tg, info
+
+ def _pick_stroke(self, cands):
+ good = [c for c in cands if c["ik"] < 1e-3] or cands
+ return min(good, key=lambda c: c["ratio"]) # the least demanding stroke
+
+ def _target_vel(self) -> np.ndarray:
+ a = self.s._actions
+ return (a[-1] - a[-2]) / CONTROL_DT if len(a) >= 2 else np.zeros(7)
+
+ def _swing_targets(self, q_h, qd_h, n_avail, n_sw):
+ q_s = self.s._target.copy()
+ v_s = self._target_vel()
+ pre = np.tile(q_s, (n_avail - n_sw, 1))
+ swing = hermite(q_s, v_s if n_sw == n_avail else np.zeros(7), q_h, qd_h, n_sw * CONTROL_DT, n_sw)
+ n_f = 25
+ follow = hermite(q_h, qd_h, q_h + qd_h * 0.5 * n_f * CONTROL_DT, np.zeros(7), n_f * CONTROL_DT, n_f)
+ out, prev = [], q_s
+ lim = VEL_LIMIT * CONTROL_DT * 0.999
+ for q in np.vstack([pre, swing, follow]):
+ q = np.clip(q, self.s.JOINT_LOW + 1e-4, self.s.JOINT_HIGH - 1e-4)
+ q = prev + np.clip(q - prev, -lim, lim)
+ out.append(q); prev = q
+ return out
+
+ def _ik(self, pos, normal, q_init, iters=200, tol=1e-4):
+ s = self.s
+ q = np.array(q_init, float)
+ n_t = normal / np.linalg.norm(normal)
+ err = np.inf
+ jacp = np.zeros((3, s.m.nv)); jacr = np.zeros((3, s.m.nv))
+ damping = 1e-3 * np.eye(6)
+ # These vectors are always length three. Avoid numpy.cross's general
+ # broadcasting machinery inside every iteration of every IK start.
+ def cross(a, b):
+ return np.array([a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]])
+ for _ in range(iters):
+ # FK and the Jacobian use the same q; refresh scratch kinematics once.
+ s._kin_set(q)
+ p = s._kin.site_xpos[s._paddle_site]
+ R = s._kin.site_xmat[s._paddle_site].reshape(3, 3)
+ n = R[:, 0]
+ e = np.concatenate((pos - p, cross(n, n_t)))
+ err = float(np.linalg.norm(e[:3]) + np.arcsin(min(1.0, np.linalg.norm(e[3:]))))
+ if n @ n_t < 0:
+ e[3:] = cross(n, n_t) + 0.5 * cross(n, R[:, 1]); err += np.pi / 2
+ if err < tol:
+ break
+ mj.mj_jacSite(s.m, s._kin, jacp, jacr, s._paddle_site)
+ J = np.vstack([jacp[:, s._vadr], jacr[:, s._vadr]])
+ q = np.clip(q + J.T @ np.linalg.solve(J @ J.T + damping, e), s.JOINT_LOW + 1e-4, s.JOINT_HIGH - 1e-4)
+ return q, err
+
+ # ------------------------------------------------------------------ views
+ def render_views(self, width=480, height=320) -> bytes:
+ """PNG: three camera views side by side (behind the robot, side, top), the camera detections of the
+ current ball drawn as cyan dots (older = darker)."""
+ import imageio.v2 as imageio
+ if not hasattr(self, "_renderer"):
+ self._renderer = mj.Renderer(self.s.m, height=height, width=width)
+ cams = []
+ for lookat, dist, az, el in (([0.0, -0.9, 0.15], 2.4, 60.0, -28.0), ([0.0, -0.3, 0.1], 3.4, 0.0, -10.0),
+ ([0.0, -0.35, 0.0], 3.9, 90.0, -89.0)):
+ c = mj.MjvCamera(); c.lookat[:] = lookat; c.distance = dist; c.azimuth = az; c.elevation = el
+ cams.append(c)
+ self._cams = cams
+ r = self._renderer
+ imgs = []
+ n = len(self.frames)
+ for c in self._cams:
+ r.update_scene(self.s.d, camera=c)
+ for j, fr in enumerate(self.frames):
+ if r.scene.ngeom >= r.scene.maxgeom:
+ break
+ a = 0.35 + 0.65 * (j + 1) / max(1, n)
+ g = r.scene.geoms[r.scene.ngeom]
+ mj.mjv_initGeom(g, mj.mjtGeom.mjGEOM_SPHERE, np.array([0.012, 0, 0]), np.array(fr["pos"], float),
+ np.eye(3).ravel(), np.array([0.1 * a, 0.9 * a, 1.0 * a, 1.0], np.float32))
+ r.scene.ngeom += 1
+ imgs.append(r.render())
+ buf = io.BytesIO()
+ imageio.imwrite(buf, np.concatenate(imgs, axis=1), format="png")
+ return buf.getvalue()
+
+
+def render_video(actions, schedule, out, fps=25):
+ """Replay video, two views, 4x slow motion (frames during the ready phases are skipped every other step)."""
+ import imageio.v2 as imageio
+ rp = Rally()
+ r = mj.Renderer(rp.s.m, height=360, width=640)
+ cams = []
+ for lookat, dist, az, el in (([0.0, -0.4, 0.15], 3.0, 90.0, -14.0), ([0.0, -0.3, 0.1], 3.6, 0.0, -14.0)):
+ c = mj.MjvCamera(); c.lookat[:] = lookat; c.distance = dist; c.azimuth = az; c.elevation = el
+ cams.append(c)
+ w = imageio.get_writer(out, fps=fps, macro_block_size=8)
+ sched = [dict(x) for x in schedule]
+ rp.schedule = [sched[0]]; rp.i = sched[0]["ball"]; rp._park()
+ j = 1
+ for k, q in enumerate(actions):
+ if j < len(sched) and rp.k == sched[j]["hold_from"]:
+ rp.schedule.append(sched[j]); rp.i = sched[j]["ball"]; rp.frames = []; rp._park(); j += 1
+ rp.step(q)
+ if not rp.in_play() and k % 3:
+ continue
+ imgs = []
+ for c in cams:
+ r.update_scene(rp.s.d, camera=c)
+ imgs.append(r.render())
+ w.append_data(np.concatenate(imgs, axis=1))
+ w.close(); r.close()
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/rcb_tt.py b/scripts/roboolympics/shared/sports/tabletennis/sim/rcb_tt.py
new file mode 100644
index 0000000000..53df368e21
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/tabletennis/sim/rcb_tt.py
@@ -0,0 +1,499 @@
+"""
+rcb_tt.py — task-local tooling for the robot table tennis tasks (MuJoCo, Franka Panda with a paddle).
+
+World frame (metres): table top is z = 0, the table's long axis is y, the net is the plane y = 0.
+The robot stands behind the y < 0 end (base at (0, -1.75, 0), facing +y); the opponent half is y > 0.
+
+Control: one action = 7 absolute joint-position targets (rad), held for CONTROL_DT = 10 ms (100 Hz). Inside a
+control step the target is interpolated linearly over the 10 physics steps (1 ms each), and a joint-space
+PD controller with bias (gravity + Coriolis) compensation turns it into joint torques, clipped at the Franka
+torque limits (87 Nm joints 1-4, 12 Nm joints 5-7). The target velocity fed to the D term is the target's
+finite difference. Target limits (checked, a violation raises ValueError / fails the verifier):
+ * every target inside the joint range (JOINT_LOW..JOINT_HIGH),
+ * |target_k - target_{k-1}| <= VEL_LIMIT * CONTROL_DT per joint (Franka joint speed limits);
+ target_{-1} is the instance's initial joint configuration q0.
+An episode lasts HORIZON_S = 2.5 s (250 control steps). A trajectory with fewer than 250 rows holds its last
+target for the rest of the episode.
+
+Python
+------
+ from rcb_tt import Session
+ s = Session() # loads /app/instance.npz (or Session(instance=...))
+ s.reset(); s.step(q_target); s.state(); s.status(); s.actions()
+ s.predict_ball(duration=1.5) # ball-only rollout (no robot) from the current (or a given) ball state
+ s.fk(q) / s.jacobian(q) / s.ik(pos, normal, q_init) # paddle kinematics helpers
+ s.replay(actions) -> status; s.save_trajectory(actions, path)
+
+CLI
+---
+ python rcb_tt.py info
+ python rcb_tt.py replay --traj /app/output/trajectory.npz [--repeat 2]
+ python rcb_tt.py render --traj /app/output/trajectory.npz --out replay.mp4
+"""
+from __future__ import annotations
+
+import argparse
+import copy
+import hashlib
+import json
+import os
+import sys
+import xml.etree.ElementTree as ET
+from pathlib import Path
+
+import numpy as np
+
+import mujoco as mj # rendering backend: MUJOCO_GL (the image sets osmesa = CPU offscreen)
+
+HERE = Path(__file__).resolve().parent
+SCENE_XML = Path(os.environ.get("RCB_TT_SCENE", HERE / "scene" / "tt_scene.xml"))
+DEFAULT_INSTANCE = os.environ.get("RCB_TT_INSTANCE", "/app/instance.npz")
+
+CONTROL_DT = 0.01
+SUBSTEPS = 10 # physics steps per control step (timestep 1 ms)
+HORIZON_S = 2.5
+HORIZON = int(round(HORIZON_S / CONTROL_DT)) # 250 control steps
+VEL_LIMIT = np.array([2.175, 2.175, 2.175, 2.175, 2.61, 2.61, 2.61]) # rad/s (Franka datasheet)
+TORQUE_LIMIT = np.array([87.0, 87.0, 87.0, 87.0, 12.0, 12.0, 12.0]) # Nm
+KP = np.array([2400.0, 2400.0, 2400.0, 2400.0, 1000.0, 600.0, 200.0])
+KD = np.array([100.0, 100.0, 100.0, 100.0, 30.0, 20.0, 6.0])
+MERGE_GAP_S = 0.005 # contacts with the same object closer than this in time count as one
+NET_TOP_Z = 0.1525
+TABLE_HALF_X, TABLE_HALF_Y = 0.7625, 1.37
+
+JOINTS = [f"joint{i}" for i in range(1, 8)]
+
+
+def _robot_geom_ids(m: mj.MjModel) -> set[int]:
+ root = mj.mj_name2id(m, mj.mjtObj.mjOBJ_BODY, "link0")
+ ids = set()
+ for g in range(m.ngeom):
+ b = m.geom_bodyid[g]
+ while b not in (0, root):
+ b = m.body_parentid[b]
+ if b == root:
+ ids.add(g)
+ return ids
+
+
+def _ball_only_xml(path: Path) -> str:
+ """The same scene with the robot removed: used by predict_ball (identical ball/table/net physics)."""
+ tree = ET.parse(path)
+ root = tree.getroot()
+ wb = root.find("worldbody")
+ for b in list(wb):
+ if b.tag == "body" and b.get("name") == "link0":
+ wb.remove(b)
+ for tag in ("actuator",):
+ for el in root.findall(tag):
+ root.remove(el)
+ con = root.find("contact")
+ for el in list(con):
+ if el.tag == "exclude" or (el.tag == "pair" and el.get("geom2") == "paddle_blade"):
+ con.remove(el)
+ root.find("compiler").set("meshdir", str((path.parent / "assets").resolve()))
+ return ET.tostring(root, encoding="unicode")
+
+
+def load_instance(path: str | Path) -> dict:
+ d = np.load(path, allow_pickle=False)
+ return {k: d[k].copy() for k in d.files}
+
+
+class Session:
+ """One simulator (MuJoCo, single thread) for the frozen instance. Unlimited resets."""
+
+ def __init__(self, instance: str | Path | None = None, scene: str | Path | None = None):
+ self.instance_path = str(instance or DEFAULT_INSTANCE)
+ self.inst = load_instance(self.instance_path)
+ self.scene = Path(scene) if scene else SCENE_XML
+ self.m = mj.MjModel.from_xml_path(str(self.scene))
+ self.d = mj.MjData(self.m)
+ m = self.m
+ self._qadr = np.array([m.jnt_qposadr[mj.mj_name2id(m, mj.mjtObj.mjOBJ_JOINT, j)] for j in JOINTS])
+ self._vadr = np.array([m.jnt_dofadr[mj.mj_name2id(m, mj.mjtObj.mjOBJ_JOINT, j)] for j in JOINTS])
+ self.JOINT_LOW = m.jnt_range[[mj.mj_name2id(m, mj.mjtObj.mjOBJ_JOINT, j) for j in JOINTS], 0].copy()
+ self.JOINT_HIGH = m.jnt_range[[mj.mj_name2id(m, mj.mjtObj.mjOBJ_JOINT, j) for j in JOINTS], 1].copy()
+ self._ball_geom = mj.mj_name2id(m, mj.mjtObj.mjOBJ_GEOM, "geom_ball")
+ self._table_geom = mj.mj_name2id(m, mj.mjtObj.mjOBJ_GEOM, "geom_table")
+ self._net_geom = mj.mj_name2id(m, mj.mjtObj.mjOBJ_GEOM, "geom_net")
+ self._floor_geom = mj.mj_name2id(m, mj.mjtObj.mjOBJ_GEOM, "floor")
+ self._blade_geom = mj.mj_name2id(m, mj.mjtObj.mjOBJ_GEOM, "paddle_blade")
+ self._robot_geoms = _robot_geom_ids(m)
+ self._paddle_site = mj.mj_name2id(m, mj.mjtObj.mjOBJ_SITE, "paddle_center")
+ tz = mj.mj_name2id(m, mj.mjtObj.mjOBJ_SITE, "target_zone")
+ m.site_pos[tz, :2] = self.inst["target_center"]
+ m.site_size[tz, :2] = self.inst["target_half"]
+ m.site_rgba[tz, 3] = 0.0 # target-zone visualization is not part of the match
+ self._kin = mj.MjData(m) # scratch data for fk / jacobian / ik (never stepped)
+ self._ball_model = None
+ self.sim_steps_total = 0
+ self.resets = 0
+ self.reset()
+
+ # ------------------------------------------------------------------ episode
+ def reset(self) -> dict:
+ """Back to the frozen initial state (ball in flight, arm at rest at q0, t = 0)."""
+ m, d = self.m, self.d
+ mj.mj_resetData(m, d)
+ d.qpos[0:7] = self.inst["ball_qpos"]
+ d.qvel[0:6] = self.inst["ball_qvel"]
+ d.qpos[self._qadr] = self.inst["q0"]
+ d.ctrl[:] = 0.0
+ mj.mj_forward(m, d)
+ self._target = self.inst["q0"].astype(np.float64).copy()
+ self._actions: list[np.ndarray] = []
+ self._k = 0
+ self._events: list[dict] = [] # contact onsets involving the ball (merged, see MERGE_GAP_S)
+ self._last_touch: dict[str, float] = {}
+ self._robot_table = 0
+ self._robot_contact_names: set[str] = set()
+ self._v_out = None # ball velocity 5 ms after the first paddle contact
+ self.resets += 1
+ return self.state()
+
+ def _check_target(self, q: np.ndarray) -> None:
+ if q.shape != (7,) or not np.all(np.isfinite(q)):
+ raise ValueError(f"action must be 7 finite joint targets, got shape {q.shape}")
+ lo_bad = q < self.JOINT_LOW - 1e-9
+ hi_bad = q > self.JOINT_HIGH + 1e-9
+ if lo_bad.any() or hi_bad.any():
+ raise ValueError(f"step {self._k}: joint target outside range {np.nonzero(lo_bad | hi_bad)[0].tolist()}: {q}")
+ dq = np.abs(q - self._target)
+ lim = VEL_LIMIT * CONTROL_DT * (1 + 1e-6) + 1e-12
+ if (dq > lim).any():
+ j = int(np.argmax(dq / lim))
+ raise ValueError(f"step {self._k}: joint {j + 1} target moved {dq[j]:.5f} rad in one control step "
+ f"(limit {VEL_LIMIT[j] * CONTROL_DT:.5f} = {VEL_LIMIT[j]} rad/s x {CONTROL_DT} s)")
+
+ def step(self, q_target) -> dict:
+ """Apply one action (7 joint targets) for CONTROL_DT = 10 ms. Returns state()."""
+ if self._k >= HORIZON:
+ raise RuntimeError(f"episode is over ({HORIZON} control steps = {HORIZON_S} s); call reset()")
+ q = np.asarray(q_target, dtype=np.float64).reshape(-1)
+ self._check_target(q)
+ m, d = self.m, self.d
+ q_prev = self._target
+ qd_des = (q - q_prev) / CONTROL_DT
+ lo, hi = m.actuator_ctrlrange[:, 0], m.actuator_ctrlrange[:, 1]
+ for j in range(1, SUBSTEPS + 1):
+ q_des = q_prev + (q - q_prev) * (j / SUBSTEPS)
+ tau = KP * (q_des - d.qpos[self._qadr]) + KD * (qd_des - d.qvel[self._vadr]) + d.qfrc_bias[self._vadr]
+ d.ctrl[:] = np.clip(tau, lo, hi)
+ self._v_pre = d.qvel[0:3].copy() # the ball's velocity before this substep (pre-contact)
+ mj.mj_step(m, d)
+ self._scan_contacts()
+ if self._v_out is None and self._events and any(e["kind"] == "paddle" for e in self._events):
+ t_hit = next(e["t"] for e in self._events if e["kind"] == "paddle")
+ if d.time >= t_hit + 0.005 - 1e-9:
+ self._v_out = d.qvel[0:3].copy()
+ self._target = q.copy()
+ self._actions.append(q.copy())
+ self._k += 1
+ self.sim_steps_total += SUBSTEPS
+ return self.state()
+
+ def _scan_contacts(self) -> None:
+ d, t = self.d, self.d.time
+ bg = self._ball_geom
+ for i in range(d.ncon):
+ c = d.contact[i]
+ g1, g2 = int(c.geom1), int(c.geom2)
+ if bg in (g1, g2):
+ other = g2 if g1 == bg else g1
+ if other == self._table_geom:
+ kind = "table_own" if d.qpos[1] < 0 else "table_opp"
+ elif other == self._blade_geom:
+ kind = "paddle"
+ elif other == self._net_geom:
+ kind = "net"
+ elif other == self._floor_geom:
+ kind = "floor"
+ elif other in self._robot_geoms:
+ kind = "robot"
+ else:
+ kind = "other"
+ last = self._last_touch.get(kind)
+ if last is None or t - last > MERGE_GAP_S + 1e-9:
+ # MuJoCo's frame points geom1 -> geom2. Store a stable
+ # surface -> ball convention, independent of geom ordering.
+ normal = c.frame[:3] if g2 == bg else -c.frame[:3]
+ self._events.append(dict(t=round(float(t), 6), kind=kind, pos=d.qpos[0:3].tolist(),
+ vel=d.qvel[0:3].tolist(), vel_pre=self._v_pre.tolist(),
+ contact_pos=c.pos.tolist(),
+ contact_normal=normal.tolist()))
+ self._last_touch[kind] = t
+ else:
+ rob1, rob2 = g1 in self._robot_geoms, g2 in self._robot_geoms
+ if rob1 != rob2: # robot touches the environment (table, net, floor)
+ self._robot_table = 1
+ self._robot_contact_names.add(mj.mj_id2name(self.m, mj.mjtObj.mjOBJ_GEOM, g2 if rob1 else g1) or "?")
+
+ def run_to_end(self) -> dict:
+ """Hold the last target until the episode horizon (what the verifier does after the last action)."""
+ while self._k < HORIZON:
+ self.step(self._target)
+ return self.status()
+
+ # ------------------------------------------------------------------ observation
+ def state(self) -> dict:
+ d = self.d
+ R = d.site_xmat[self._paddle_site].reshape(3, 3)
+ jacp = np.zeros((3, self.m.nv)); jacr = np.zeros((3, self.m.nv))
+ mj.mj_jacSite(self.m, d, jacp, jacr, self._paddle_site)
+ qd = d.qvel[self._vadr]
+ return dict(
+ t=float(d.time), k=self._k,
+ q=d.qpos[self._qadr].copy(), qd=qd.copy(), q_target=self._target.copy(),
+ ball_pos=d.qpos[0:3].copy(), ball_vel=d.qvel[0:3].copy(), ball_spin=d.qvel[3:6].copy(),
+ paddle_pos=d.site_xpos[self._paddle_site].copy(), paddle_R=R.copy(), paddle_normal=R[:, 0].copy(),
+ paddle_vel=jacp[:, self._vadr] @ qd, paddle_angvel=jacr[:, self._vadr] @ qd,
+ events=copy.deepcopy(self._events),
+ )
+
+ def actions(self) -> np.ndarray:
+ """(N, 7) joint targets applied since the last reset."""
+ return np.array(self._actions, dtype=np.float64).reshape(-1, 7)
+
+ def status(self) -> dict:
+ """Judge the episode so far (final only once the ball has landed or the horizon is reached)."""
+ st = judge(self._events, self.inst, robot_env_contact=self._robot_table, t=float(self.d.time), k=self._k)
+ if self._v_out is not None:
+ st["hit_speed_out"] = float(np.linalg.norm(self._v_out))
+ return st
+
+ def state_sha(self) -> str:
+ d = self.d
+ h = hashlib.sha256()
+ for a in (d.qpos, d.qvel, d.act, d.qacc_warmstart, d.ctrl, np.array([d.time])):
+ h.update(np.ascontiguousarray(a, dtype=np.float64).tobytes())
+ h.update(json.dumps(self._events, sort_keys=True).encode())
+ return h.hexdigest()
+
+ # ------------------------------------------------------------------ replay / io
+ def replay(self, actions) -> dict:
+ """Reset, apply `actions` open-loop, hold the last target to the 2.5 s horizon, return status()."""
+ a = np.asarray(actions, dtype=np.float64)
+ if a.ndim != 2 or a.shape[1] != 7 or not (1 <= len(a) <= HORIZON):
+ raise ValueError(f"actions must have shape (N, 7) with 1 <= N <= {HORIZON}, got {a.shape}")
+ self.reset()
+ for q in a:
+ self.step(q)
+ st = self.run_to_end()
+ st["n_actions"] = int(len(a))
+ st["state_sha"] = self.state_sha()
+ return st
+
+ @staticmethod
+ def save_trajectory(actions, path: str = "/app/output/trajectory.npz") -> str:
+ a = np.asarray(actions, dtype=np.float64)
+ if a.ndim != 2 or a.shape[1] != 7:
+ raise ValueError(f"actions must be (N, 7), got {a.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=a, control_dt=np.float64(CONTROL_DT), task=np.str_("tabletennis_return"))
+ return path
+
+ # ------------------------------------------------------------------ helpers (privileged, allowed)
+ def predict_ball(self, pos=None, vel=None, spin=None, duration: float = 1.5) -> dict:
+ """Roll the ball out WITHOUT the robot (same ball/table/net physics, 1 ms steps) from the current ball
+ state or from (pos, vel, spin). Returns t (N,), pos (N,3), vel (N,3), spin (N,3) and the table/net
+ contact onsets. Times are relative to the current sim time. Matches the full sim until the ball
+ touches the robot (up to floating-point differences)."""
+ if self._ball_model is None:
+ self._ball_model = mj.MjModel.from_xml_string(_ball_only_xml(self.scene))
+ self._ball_data = mj.MjData(self._ball_model)
+ bm, bd = self._ball_model, self._ball_data
+ mj.mj_resetData(bm, bd)
+ bd.qpos[0:7] = self.d.qpos[0:7]
+ bd.qvel[0:6] = self.d.qvel[0:6]
+ if pos is not None:
+ bd.qpos[0:3] = pos
+ if vel is not None:
+ bd.qvel[0:3] = vel
+ if spin is not None:
+ bd.qvel[3:6] = spin
+ mj.mj_forward(bm, bd)
+ n = int(round(duration / bm.opt.timestep))
+ P = np.zeros((n, 3)); V = np.zeros((n, 3)); W = np.zeros((n, 3)); T = np.zeros(n)
+ tg = mj.mj_name2id(bm, mj.mjtObj.mjOBJ_GEOM, "geom_table")
+ ng = mj.mj_name2id(bm, mj.mjtObj.mjOBJ_GEOM, "geom_net")
+ fg = mj.mj_name2id(bm, mj.mjtObj.mjOBJ_GEOM, "floor")
+ events, prev = [], set()
+ for i in range(n):
+ mj.mj_step(bm, bd)
+ T[i] = (i + 1) * bm.opt.timestep
+ P[i], V[i], W[i] = bd.qpos[0:3], bd.qvel[0:3], bd.qvel[3:6]
+ cur = set()
+ for c in range(bd.ncon):
+ g = {int(bd.contact[c].geom1), int(bd.contact[c].geom2)}
+ if tg in g:
+ cur.add("table_own" if bd.qpos[1] < 0 else "table_opp")
+ if ng in g:
+ cur.add("net")
+ if fg in g:
+ cur.add("floor")
+ for kind in cur - prev:
+ events.append(dict(t=float(T[i]), kind=kind, pos=P[i].tolist()))
+ prev = cur
+ return dict(t=T, pos=P, vel=V, spin=W, events=events)
+
+ def _kin_set(self, q):
+ self._kin.qpos[:] = self.d.qpos
+ self._kin.qpos[self._qadr] = q
+ mj.mj_kinematics(self.m, self._kin)
+ mj.mj_comPos(self.m, self._kin)
+
+ def fk(self, q) -> tuple[np.ndarray, np.ndarray]:
+ """Paddle blade centre position (3,) and rotation matrix (3,3) for joint config q. Column 0 of the
+ rotation is the blade face normal, column 2 points along the handle (away from the wrist)."""
+ self._kin_set(np.asarray(q, dtype=np.float64))
+ return (self._kin.site_xpos[self._paddle_site].copy(),
+ self._kin.site_xmat[self._paddle_site].reshape(3, 3).copy())
+
+ def jacobian(self, q) -> np.ndarray:
+ """(6, 7) paddle-centre Jacobian [linear; angular] (world frame) at joint config q."""
+ self._kin_set(np.asarray(q, dtype=np.float64))
+ jacp = np.zeros((3, self.m.nv)); jacr = np.zeros((3, self.m.nv))
+ mj.mj_jacSite(self.m, self._kin, jacp, jacr, self._paddle_site)
+ return np.vstack([jacp[:, self._vadr], jacr[:, self._vadr]])
+
+ def ik(self, pos, normal, q_init=None, iters: int = 200, tol: float = 1e-4) -> tuple[np.ndarray, float]:
+ """Damped-least-squares IK for the paddle: blade centre at `pos` with face normal along `normal`
+ (rotation about the normal is free). Joint limits are respected by clipping. Returns (q, residual)
+ where residual = position error (m) + normal error (rad); check it."""
+ q = np.array(self.inst["q0"] if q_init is None else q_init, dtype=np.float64)
+ pos = np.asarray(pos, dtype=np.float64)
+ n_t = np.asarray(normal, dtype=np.float64); n_t = n_t / np.linalg.norm(n_t)
+ err = np.inf
+ for _ in range(iters):
+ p, R = self.fk(q)
+ n = R[:, 0]
+ e = np.r_[pos - p, np.cross(n, n_t)]
+ err = float(np.linalg.norm(e[:3]) + np.arcsin(min(1.0, np.linalg.norm(e[3:]))))
+ if n @ n_t < 0:
+ e[3:] = np.cross(n, n_t) + 0.5 * np.cross(n, R[:, 1]) # flip out of the antipodal solution
+ err += np.pi / 2
+ if err < tol:
+ break
+ J = self.jacobian(q)
+ lam = 1e-3
+ dq = J.T @ np.linalg.solve(J @ J.T + lam * np.eye(6), e)
+ q = np.clip(q + dq, self.JOINT_LOW + 1e-4, self.JOINT_HIGH - 1e-4)
+ return q, err
+
+ # ------------------------------------------------------------------ rendering
+ def render_video(self, actions, out: str, fps: int = 25, every: int = 1, width: int = 640, height: int = 360,
+ slowmo_label: bool = True) -> str:
+ """Replay `actions` and write an mp4 (two views side by side). One frame per `every` control steps
+ (10 ms): fps=25, every=1 is 4x slow motion."""
+ import imageio.v2 as imageio
+ a = np.asarray(actions, dtype=np.float64)
+ r = mj.Renderer(self.m, height=height, width=width)
+ cams = []
+ for lookat, dist, az, el in (([0.0, -0.2, 0.1], 3.6, 0.0, -18.0), ([0.0, 0.0, 0.1], 4.2, -90.0, -22.0)):
+ c = mj.MjvCamera(); c.lookat[:] = lookat; c.distance = dist; c.azimuth = az; c.elevation = el
+ cams.append(c)
+ opt = mj.MjvOption()
+ writer = imageio.get_writer(out, fps=fps, macro_block_size=8)
+
+ def frame():
+ imgs = []
+ for c in cams:
+ r.update_scene(self.d, camera=c, scene_option=opt)
+ imgs.append(r.render())
+ writer.append_data(np.concatenate(imgs, axis=1))
+
+ self.reset(); frame()
+ for k in range(HORIZON):
+ self.step(a[k] if k < len(a) else self._target)
+ if (k + 1) % every == 0:
+ frame()
+ writer.close(); r.close()
+ return out
+
+
+# ---------------------------------------------------------------------- judging
+def judge(events: list[dict], inst: dict, robot_env_contact: int = 0, t: float = 0.0, k: int = 0) -> dict:
+ """Success iff: the ball bounces exactly once on the robot's half and touches nothing else before the hit;
+ exactly one paddle contact; after the hit the ball's first contact other than the net is the table on the
+ opponent half inside the target zone; the robot never touches the table, net or floor.
+ The net is transparent to the judgement (ITTF 2.7.1: a return is good if it touches the opponent's court
+ "directly or after touching the net assembly"); `net_touch` reports it. A serve that touches the net is a let:
+ the caller decides that before calling judge."""
+ center = np.asarray(inst["target_center"], dtype=np.float64)
+ half = np.asarray(inst["target_half"], dtype=np.float64)
+ def top_contact(e):
+ cp, cn = e.get("contact_pos"), e.get("contact_normal")
+ # Top edges have an upward component; vertical sides and the underside
+ # do not. Contact midpoints may lie well below z=0 at higher impact
+ # speeds, so height cannot distinguish top contact from side contact.
+ return bool(cp is not None and cn is not None and cn[2] > 1e-6 and
+ abs(cp[0]) <= .7625 + .001 and abs(cp[1]) <= 1.37 + .001)
+ kinds = [e["kind"] for e in events]
+ out = dict(success=False, hit=0, n_paddle_contacts=kinds.count("paddle"), own_bounces_before_hit=0,
+ bad_contact_before_hit=0, landed=0, landed_opponent_half=0, in_zone=0, landing_error_m=-1.0,
+ landing_x=0.0, landing_y=0.0, net_touch=int("net" in kinds), robot_env_contact=int(robot_env_contact),
+ hit_time=-1.0, hit_speed_out=0.0, t=t, k=k)
+ if "paddle" not in kinds:
+ return out
+ ip = kinds.index("paddle")
+ out["hit"] = 1
+ out["hit_time"] = float(events[ip]["t"])
+ pre = kinds[:ip]
+ edge_rules = bool(inst.get("table_edges_valid"))
+ out["own_bounces_before_hit"] = sum(e["kind"] == "table_own" and (not edge_rules or top_contact(e))
+ for e in events[:ip])
+ out["bad_contact_before_hit"] = int(any(x in ("robot", "floor", "other") for x in pre) or
+ (edge_rules and any(e["kind"] in ("table_own", "table_opp") and not top_contact(e)
+ for e in events[:ip])))
+ post = [e for e in events[ip + 1:] if e["kind"] not in ("paddle", "net")]
+ if post:
+ e = post[0]
+ out["landed"] = 1
+ out["landing_x"], out["landing_y"] = float(e["pos"][0]), float(e["pos"][1])
+ if e["kind"] == "table_opp":
+ out["landed_opponent_half"] = 1
+ err = np.abs(np.array(e["pos"][:2]) - center)
+ if edge_rules:
+ cp = e.get("contact_pos")
+ out["in_zone"] = int(top_contact(e) and cp[1] >= 0)
+ else:
+ out["in_zone"] = int(bool(np.all(err <= half)))
+ out["landing_error_m"] = float(np.linalg.norm(np.array(e["pos"][:2]) - center))
+ out["success"] = bool(out["n_paddle_contacts"] == 1 and out["own_bounces_before_hit"] == 1
+ and not out["bad_contact_before_hit"] and out["landed_opponent_half"] == 1
+ and out["in_zone"] == 1 and not out["robot_env_contact"])
+ return out
+
+
+# ---------------------------------------------------------------------- CLI
+def _main(argv=None) -> int:
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ p = sub.add_parser("info"); p.add_argument("--instance", default=DEFAULT_INSTANCE)
+ p = sub.add_parser("replay"); p.add_argument("--instance", default=DEFAULT_INSTANCE)
+ p.add_argument("--traj", required=True); p.add_argument("--repeat", type=int, default=1)
+ p = sub.add_parser("render"); p.add_argument("--instance", default=DEFAULT_INSTANCE)
+ p.add_argument("--traj", required=True); p.add_argument("--out", default="replay.mp4")
+ a = ap.parse_args(argv)
+ s = Session(instance=a.instance)
+ if a.cmd == "info":
+ inst = {k: (v.tolist() if hasattr(v, "tolist") else v) for k, v in s.inst.items()}
+ print(json.dumps(dict(instance=inst, horizon_s=HORIZON_S, control_dt=CONTROL_DT,
+ joint_low=s.JOINT_LOW.tolist(), joint_high=s.JOINT_HIGH.tolist(),
+ vel_limit=VEL_LIMIT.tolist()), indent=1))
+ return 0
+ acts = np.load(a.traj, allow_pickle=False)["actions"]
+ if a.cmd == "replay":
+ for _ in range(a.repeat):
+ st = s.replay(acts)
+ print(json.dumps({k: v for k, v in st.items()}, default=float))
+ return 0
+ if a.cmd == "render":
+ print(s.render_video(acts, a.out))
+ return 0
+ return 1
+
+
+if __name__ == "__main__":
+ sys.exit(_main())
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/LICENSE.menagerie-franka b/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/LICENSE.menagerie-franka
new file mode 100644
index 0000000000..d9a10c0d8e
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/LICENSE.menagerie-franka
@@ -0,0 +1,176 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link0.stl b/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link0.stl
new file mode 100644
index 0000000000..def070c707
Binary files /dev/null and b/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link0.stl differ
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link1.stl b/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link1.stl
new file mode 100644
index 0000000000..426bcf2d7a
Binary files /dev/null and b/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link1.stl differ
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link2.stl b/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link2.stl
new file mode 100644
index 0000000000..b369f1599a
Binary files /dev/null and b/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link2.stl differ
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link3.stl b/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link3.stl
new file mode 100644
index 0000000000..25162eeedf
Binary files /dev/null and b/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link3.stl differ
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link4.stl b/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link4.stl
new file mode 100644
index 0000000000..76c8c33c3e
Binary files /dev/null and b/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link4.stl differ
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link5_collision_0.obj b/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link5_collision_0.obj
new file mode 100644
index 0000000000..6d6eb5203b
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link5_collision_0.obj
@@ -0,0 +1,188 @@
+v 0.029063642 0.095448048 -0.133538792
+v 0.049877137 -0.013343874 -0.215408068
+v 0.046604998 0.029219000 -0.259000003
+v -0.043494001 0.033698998 -0.259000003
+v -0.030187000 -0.020500001 -0.186547995
+v -0.017736474 -0.052050648 -0.258999242
+v 0.012548444 0.082957777 -0.202027869
+v 0.050364564 0.017247290 -0.214926371
+v 0.020709741 -0.020753554 -0.182012846
+v -0.038214683 0.050463360 -0.167851336
+v 0.045944492 -0.030214707 -0.258999161
+v -0.051997126 -0.017851673 -0.259000003
+v 0.026338819 0.085091480 -0.183646959
+v 0.020922000 0.050882000 -0.259000003
+v 0.045491802 0.013339541 -0.187636452
+v 0.050951000 0.020726001 -0.259000003
+v 0.023551804 0.063747043 -0.133252288
+v -0.013548823 -0.047308172 -0.207602441
+v -0.023108632 0.089348183 -0.175470195
+v 0.028642003 -0.042568484 -0.211525585
+v -0.051912808 0.016682228 -0.233346078
+v 0.021637405 0.093787480 -0.156753967
+v 0.028892799 0.093108394 -0.147202451
+v -0.021765672 0.050517374 -0.259000003
+v 0.029191773 0.046614188 -0.259000003
+v 0.020095230 0.083558674 -0.197022477
+v 0.050294057 0.012853477 -0.210481151
+v 0.041400984 -0.012110881 -0.190499104
+v 0.050274495 0.021321905 -0.223857806
+v 0.050395896 -0.021963709 -0.259000003
+v -0.014053484 -0.016454442 -0.177588961
+v -0.023077204 0.053522191 -0.146035077
+v 0.028830698 0.067305577 -0.135375573
+v -0.038313158 -0.038208997 -0.224413296
+v 0.045422879 -0.030121078 -0.229083894
+v 0.011903144 -0.042590730 -0.199122301
+v 0.012319026 -0.051745998 -0.224350901
+v -0.052457958 0.016511494 -0.258999590
+v -0.046985660 -0.009035359 -0.196875560
+v 0.022625311 0.097598446 -0.133939149
+v 0.012620136 0.087869933 -0.188952639
+v 0.025225283 0.087563533 -0.179602397
+v -0.009634502 0.083175007 -0.202322834
+v -0.024273001 0.085358001 -0.188354000
+v 0.022706000 0.084515996 -0.192412004
+v 0.031834746 0.074158814 -0.139114503
+v 0.050391338 -0.004898283 -0.210560332
+v 0.036850054 -0.028951537 -0.199617216
+v 0.028814057 -0.007357717 -0.177964311
+v 0.007988000 -0.025363000 -0.182107002
+v -0.017462573 -0.033546585 -0.190912689
+v -0.022334082 -0.002848132 -0.172981292
+v -0.030079996 0.053249859 -0.151432391
+v 0.045789921 -0.008346553 -0.194042762
+v 0.037322809 -0.011895567 -0.186316195
+v -0.034569787 -0.042770809 -0.259000003
+v -0.026268487 -0.046990059 -0.224191914
+v 0.033556075 -0.043548766 -0.258998990
+v 0.049874237 -0.022123435 -0.233471659
+v -0.005066666 -0.052041921 -0.219576018
+v 0.016204123 -0.046663484 -0.207808223
+v -0.051942493 -0.005029111 -0.219727096
+v -0.029441908 0.082404274 -0.175896559
+v -0.042174398 -0.025291337 -0.202643498
+f 12 4 3
+f 14 3 4
+f 16 12 3
+f 23 3 13
+f 23 16 3
+f 23 1 16
+f 24 14 4
+f 25 13 3
+f 25 3 14
+f 26 14 7
+f 26 25 14
+f 27 8 1
+f 29 16 1
+f 29 1 8
+f 29 8 16
+f 30 12 16
+f 32 31 17
+f 33 1 17
+f 38 4 12
+f 40 22 19
+f 40 23 22
+f 40 1 23
+f 40 32 17
+f 40 17 1
+f 41 19 22
+f 41 26 7
+f 42 23 13
+f 42 22 23
+f 42 41 22
+f 43 7 14
+f 43 14 24
+f 43 41 7
+f 43 19 41
+f 44 24 4
+f 44 43 24
+f 44 19 43
+f 45 13 25
+f 45 25 26
+f 45 42 13
+f 45 26 41
+f 45 41 42
+f 46 27 1
+f 46 15 27
+f 46 1 33
+f 47 27 15
+f 47 30 16
+f 47 16 8
+f 47 8 27
+f 48 20 35
+f 48 35 2
+f 48 36 20
+f 48 9 36
+f 49 17 9
+f 50 9 17
+f 50 17 31
+f 50 36 9
+f 51 31 5
+f 51 50 31
+f 51 18 36
+f 51 36 50
+f 52 32 5
+f 52 5 31
+f 52 31 32
+f 53 10 39
+f 53 39 5
+f 53 5 32
+f 53 32 40
+f 54 33 28
+f 54 46 33
+f 54 15 46
+f 54 47 15
+f 54 2 47
+f 54 48 2
+f 54 28 48
+f 55 33 17
+f 55 28 33
+f 55 17 49
+f 55 48 28
+f 55 49 9
+f 55 9 48
+f 56 34 12
+f 56 30 6
+f 56 12 30
+f 57 56 6
+f 57 34 56
+f 58 35 20
+f 58 11 35
+f 58 20 37
+f 58 37 6
+f 58 30 11
+f 58 6 30
+f 59 2 35
+f 59 47 2
+f 59 30 47
+f 59 35 11
+f 59 11 30
+f 60 6 37
+f 60 57 6
+f 60 18 57
+f 61 37 20
+f 61 20 36
+f 61 60 37
+f 61 36 18
+f 61 18 60
+f 62 38 12
+f 62 21 38
+f 62 39 10
+f 62 10 21
+f 63 38 21
+f 63 21 10
+f 63 19 44
+f 63 44 4
+f 63 4 38
+f 63 10 53
+f 63 53 40
+f 63 40 19
+f 64 5 39
+f 64 51 5
+f 64 18 51
+f 64 57 18
+f 64 34 57
+f 64 12 34
+f 64 62 12
+f 64 39 62
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link5_collision_1.obj b/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link5_collision_1.obj
new file mode 100644
index 0000000000..2eeeeea170
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link5_collision_1.obj
@@ -0,0 +1,119 @@
+v 0.029605924 0.107695894 -0.057770639
+v 0.028114332 0.082823920 -0.058553905
+v 0.038816102 0.053402838 -0.175505396
+v -0.026856016 0.088084521 -0.175136227
+v -0.030626847 0.107119812 -0.057687294
+v 0.025670733 0.088513946 -0.175229901
+v -0.004989269 0.102164150 -0.123603135
+v -0.038214683 0.050463360 -0.167851336
+v 0.029153411 0.097073936 -0.123627471
+v -0.039514421 0.050433927 -0.176900026
+v -0.009555079 0.106683172 -0.095345165
+v -0.018650687 0.092581494 -0.165880068
+v 0.028410194 0.050382871 -0.151882879
+v -0.025116868 0.079917612 -0.059207257
+v 0.027728461 0.088850155 -0.170468824
+v 0.012301352 0.106583136 -0.090584029
+v -0.033031356 0.072019963 -0.176122603
+v -0.028518812 0.083365915 -0.058497467
+v 0.017236843 0.092763911 -0.165977938
+v -0.013955552 0.101873439 -0.118898329
+v -0.028958102 0.093907525 -0.142630397
+v 0.017254189 0.075705868 -0.064336333
+v -0.014409871 0.075430847 -0.064290830
+v 0.028214046 0.087293870 -0.171111784
+v 0.025659250 0.106544369 -0.076459959
+v 0.003562050 0.106723586 -0.095327997
+v -0.038642138 0.054804181 -0.176806387
+v 0.024373464 0.079432104 -0.059087522
+v 0.021627842 0.092908946 -0.161300197
+v -0.022714762 0.106727072 -0.081193925
+v -0.026651997 0.092292062 -0.156493182
+v -0.028411485 0.090537503 -0.161463618
+v -0.033238728 0.052765384 -0.155973185
+v 0.028928091 0.106502887 -0.067219353
+v 0.003488032 0.101747359 -0.123570031
+v 0.025518961 0.096898989 -0.133035213
+v 0.021620985 0.097180492 -0.137775852
+v -0.029182131 0.097825064 -0.119030284
+v -0.022783418 0.101743257 -0.109443270
+v -0.027976784 0.086163124 -0.175228428
+v -0.029871457 0.106777512 -0.062281333
+f 1 2 3
+f 5 2 1
+f 9 1 3
+f 10 6 3
+f 11 5 1
+f 12 6 4
+f 13 3 2
+f 13 10 3
+f 13 8 10
+f 17 4 6
+f 18 10 8
+f 18 5 10
+f 18 8 14
+f 18 2 5
+f 19 12 7
+f 19 6 12
+f 20 11 7
+f 20 7 12
+f 23 14 8
+f 23 13 22
+f 24 15 9
+f 24 9 3
+f 24 3 6
+f 24 6 15
+f 25 16 1
+f 26 11 1
+f 26 1 16
+f 26 7 11
+f 26 16 19
+f 27 17 6
+f 27 6 10
+f 27 10 5
+f 27 5 21
+f 28 18 14
+f 28 2 18
+f 28 23 22
+f 28 14 23
+f 28 22 13
+f 28 13 2
+f 29 15 6
+f 29 6 19
+f 30 5 11
+f 30 11 20
+f 31 12 4
+f 31 21 30
+f 32 27 21
+f 32 17 27
+f 32 31 4
+f 32 21 31
+f 33 23 8
+f 33 8 13
+f 33 13 23
+f 34 25 1
+f 34 1 9
+f 34 9 25
+f 35 26 19
+f 35 19 7
+f 35 7 26
+f 36 9 15
+f 36 15 29
+f 36 25 9
+f 37 29 19
+f 37 19 16
+f 37 16 25
+f 37 36 29
+f 37 25 36
+f 38 30 21
+f 38 21 5
+f 39 30 20
+f 39 20 12
+f 39 31 30
+f 39 12 31
+f 40 32 4
+f 40 4 17
+f 40 17 32
+f 41 38 5
+f 41 5 30
+f 41 30 38
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link5_collision_2.obj b/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link5_collision_2.obj
new file mode 100644
index 0000000000..6b563bff79
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link5_collision_2.obj
@@ -0,0 +1,188 @@
+v 0.016219155 0.099363113 0.048750773
+v 0.046550363 0.015799999 0.011058674
+v 0.046166659 0.105324245 -0.019041548
+v -0.005436418 0.111465780 -0.067873175
+v -0.043746749 0.015799999 0.019475930
+v 0.032618475 0.015799999 -0.035021468
+v 0.012971462 0.125447286 0.026076443
+v 0.045556378 0.100993129 0.023528159
+v 0.016534659 0.015799999 0.044952921
+v 0.045622136 0.015799999 -0.014505461
+v 0.031590266 0.097675904 -0.057701935
+v -0.026144502 0.015799999 -0.040104519
+v 0.020916727 0.125582876 -0.010159381
+v -0.043170314 0.100482302 0.027956662
+v 0.046145375 0.108191241 0.006346428
+v 0.028387091 0.112218342 0.031375415
+v 0.033002187 0.099171431 0.039965413
+v 0.016412747 0.015799999 -0.044989475
+v 0.036705779 0.015799999 -0.030707024
+v -0.022295018 0.125131249 -0.010109805
+v 0.029605924 0.107695894 -0.057770639
+v -0.013213095 0.112592014 0.039924672
+v -0.017325918 0.015799999 0.044664757
+v -0.047688079 0.104963029 -0.014858533
+v 0.045808408 0.103510400 0.019105049
+v 0.032957420 0.121769349 -0.001719666
+v 0.011885780 0.108060682 0.044095325
+v 0.016109216 0.089384114 0.048719259
+v 0.041214473 0.103236411 0.027403040
+v 0.041650999 0.015799999 0.023706000
+v 0.028114332 0.082823920 -0.058553905
+v -0.017699993 0.015799999 -0.044454039
+v 0.030954458 0.092818151 -0.058089685
+v -0.013656957 0.125189726 -0.019080479
+v 0.020627846 0.125801899 0.015541304
+v 0.008510412 0.111150243 -0.067818128
+v -0.029781181 0.121768239 0.014799138
+v -0.038794729 0.015799999 0.028113908
+v -0.017496539 0.098143056 0.049083962
+v -0.044002704 0.015799999 -0.018961373
+v -0.047333769 0.101445201 0.019313718
+v -0.030626847 0.107119812 -0.057687294
+v 0.046107670 0.108070694 -0.010345774
+v 0.028871230 0.120837663 -0.014381368
+v 0.011692637 0.121507793 0.031446733
+v 0.020178268 0.103656248 0.044326107
+v 0.024954524 0.015799999 0.040826797
+v 0.037099553 0.099607308 0.036020114
+v 0.028145238 0.121197152 0.018754182
+v -0.021927781 0.125344027 0.015252414
+v 0.020917077 0.111451583 -0.057406886
+v 0.012405067 0.125386135 -0.019235931
+v 0.024373464 0.079432104 -0.059087522
+v -0.033976639 0.107508587 0.031219781
+v -0.032505696 0.120513471 -0.010314825
+v -0.026112117 0.015799999 0.040139331
+v -0.008981987 0.108489258 0.044495871
+v -0.005033433 0.070411983 0.049486264
+v -0.047363327 0.103674321 0.015035708
+v -0.033832737 0.116474922 0.018745562
+v -0.047827588 0.074670758 0.002492660
+v -0.028518812 0.083365915 -0.058497467
+v -0.022142435 0.111037086 -0.057352830
+v 0.041463828 0.111761132 -0.014586542
+f 6 2 5
+f 9 5 2
+f 10 3 2
+f 10 2 6
+f 11 3 10
+f 12 6 5
+f 15 2 3
+f 18 6 12
+f 19 10 6
+f 21 3 11
+f 23 5 9
+f 25 8 2
+f 25 2 15
+f 28 17 1
+f 29 8 25
+f 30 9 2
+f 30 2 8
+f 31 6 18
+f 31 19 6
+f 32 18 12
+f 32 4 18
+f 33 11 10
+f 33 10 19
+f 33 19 31
+f 35 13 34
+f 35 26 13
+f 36 21 11
+f 36 11 33
+f 36 33 31
+f 36 18 4
+f 38 14 5
+f 38 5 23
+f 40 12 5
+f 41 5 14
+f 42 40 24
+f 43 26 15
+f 43 15 3
+f 44 26 21
+f 44 21 13
+f 44 13 26
+f 45 16 7
+f 45 7 22
+f 46 17 16
+f 46 45 27
+f 46 16 45
+f 46 27 1
+f 46 1 17
+f 47 28 9
+f 47 17 28
+f 47 9 30
+f 48 8 29
+f 48 30 8
+f 48 47 30
+f 48 17 47
+f 48 29 16
+f 48 16 17
+f 49 29 25
+f 49 16 29
+f 49 25 15
+f 49 15 26
+f 49 26 35
+f 49 35 7
+f 49 7 16
+f 50 7 35
+f 50 37 22
+f 50 22 7
+f 50 35 34
+f 50 34 20
+f 51 13 21
+f 51 21 36
+f 52 34 13
+f 52 51 36
+f 52 13 51
+f 52 36 4
+f 52 4 34
+f 53 36 31
+f 53 31 18
+f 53 18 36
+f 54 22 37
+f 54 39 22
+f 54 14 39
+f 55 42 24
+f 55 50 20
+f 55 37 50
+f 56 38 23
+f 56 23 39
+f 56 39 14
+f 56 14 38
+f 57 22 39
+f 57 45 22
+f 57 27 45
+f 57 39 1
+f 57 1 27
+f 58 28 1
+f 58 1 39
+f 58 9 28
+f 58 39 23
+f 58 23 9
+f 59 55 24
+f 59 37 55
+f 60 41 14
+f 60 59 41
+f 60 37 59
+f 60 54 37
+f 60 14 54
+f 61 40 5
+f 61 5 41
+f 61 24 40
+f 61 59 24
+f 61 41 59
+f 62 12 40
+f 62 40 42
+f 62 32 12
+f 62 42 4
+f 62 4 32
+f 63 34 4
+f 63 4 42
+f 63 20 34
+f 63 55 20
+f 63 42 55
+f 64 43 3
+f 64 3 21
+f 64 21 26
+f 64 26 43
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link6.stl b/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link6.stl
new file mode 100644
index 0000000000..2e9594a873
Binary files /dev/null and b/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link6.stl differ
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link7.stl b/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link7.stl
new file mode 100644
index 0000000000..0532d05750
Binary files /dev/null and b/scripts/roboolympics/shared/sports/tabletennis/sim/scene/assets/link7.stl differ
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/scene/tt_duel.xml b/scripts/roboolympics/shared/sports/tabletennis/sim/scene/tt_duel.xml
new file mode 100644
index 0000000000..c7e5f23888
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/tabletennis/sim/scene/tt_duel.xml
@@ -0,0 +1,190 @@
+<mujoco model="rcb_tabletennis">
+ <compiler angle="radian" meshdir="assets" autolimits="true" />
+ <option density="1.225" viscosity="1.8e-5" wind="0 0 0" integrator="implicitfast" timestep="0.001" cone="elliptic" impratio="10" />
+ <size memory="20M" />
+
+ <visual>
+ <headlight diffuse=".5 .5 .5" specular=".3 .3 .3" />
+ <global offwidth="1280" offheight="720" />
+ </visual>
+
+ <default>
+ <default class="panda">
+ <joint armature="0.1" damping="1" axis="0 0 1" range="-2.8973 2.8973" />
+ <geom type="mesh" rgba="0.92 0.93 0.94 1" group="2" />
+ <motor ctrlrange="-87 87" />
+ </default>
+ </default>
+
+ <asset>
+ <texture type="skybox" builtin="gradient" rgb1=".55 .6 .7" rgb2="0.1 0.1 0.15" width="10" height="10" />
+ <texture type="2d" name="floor" builtin="checker" rgb1=".32 .32 .36" rgb2=".26 .26 .3" width="300" height="300" />
+ <material name="floor" texture="floor" texrepeat="8 8" />
+ <mesh name="link0_c" file="link0.stl" />
+ <mesh name="link1_c" file="link1.stl" />
+ <mesh name="link2_c" file="link2.stl" />
+ <mesh name="link3_c" file="link3.stl" />
+ <mesh name="link4_c" file="link4.stl" />
+ <mesh name="link5_c0" file="link5_collision_0.obj" />
+ <mesh name="link5_c1" file="link5_collision_1.obj" />
+ <mesh name="link5_c2" file="link5_collision_2.obj" />
+ <mesh name="link6_c" file="link6.stl" />
+ <mesh name="link7_c" file="link7.stl" />
+ </asset>
+
+ <worldbody>
+ <light pos="0 0 3" diffuse="0.9 0.9 0.9" specular="0.3 0.3 0.3" castshadow="false" />
+ <geom name="floor" type="plane" size="6 6 0.1" pos="0 0 -0.76" material="floor" />
+
+ <body name="ball" pos="0.0 1.4 0.3">
+ <inertial pos="0 0 0" mass="2.7e-3" diaginertia="0.00000072 0.00000072 0.00000072" />
+ <freejoint name="ball" />
+ <geom name="geom_ball" size=".02" shellinertia="false" fluidcoef="0.235 0.25 0.0 1.0 1.0" group="1" rgba="0.98 0.70 0.015 1" solref="-100000 -0" fluidshape="ellipsoid" />
+ </body>
+
+ <body name="table" pos="0 0 -0.76" quat="0.7071068 0 0 0.7071068">
+ <geom name="geom_table" size="1.37 0.7625 0.02" pos="0 0 0.74" type="box" rgba="0.27 0.51 0.14 1" />
+ <geom name="geom_net" size="0.005 0.915 0.07625" pos="0 0 0.83625" type="box" rgba="1 1 1 0.5" />
+ <geom size="1.371 0.7635 0.02" pos="0 0 0.739" type="box" contype="0" conaffinity="0" group="1" density="0" rgba="0 0 0 1" />
+ <geom size="0.03 0.03 0.36" pos="1.1 0.6 0.36" type="box" contype="0" conaffinity="0" rgba=".2 .2 .2 1" />
+ <geom size="0.03 0.03 0.36" pos="1.1 -0.6 0.36" type="box" contype="0" conaffinity="0" rgba=".2 .2 .2 1" />
+ <geom size="0.03 0.03 0.36" pos="-1.1 0.6 0.36" type="box" contype="0" conaffinity="0" rgba=".2 .2 .2 1" />
+ <geom size="0.03 0.03 0.36" pos="-1.1 -0.6 0.36" type="box" contype="0" conaffinity="0" rgba=".2 .2 .2 1" />
+ </body>
+
+
+ <site name="target_zone" type="box" pos="0 1 0.0005" size="0.2 0.2 0.0005" rgba="1 0.2 0.2 0" />
+
+
+ <geom name="pedestal" type="cylinder" size="0.12 0.38" pos="0 -1.75 -0.38" contype="0" conaffinity="0" rgba=".25 .25 .28 1" />
+
+ <body name="link0" childclass="panda" pos="0 -1.75 0" quat="0.7071068 0 0 0.7071068">
+ <inertial mass="0.629769" pos="-0.041018 -0.00014 0.049974" fullinertia="0.00315 0.00388 0.004285 8.2904e-7 0.00015 8.2299e-6" />
+ <geom name="link0_c" mesh="link0_c" />
+ <body name="link1" pos="0 0 0.333">
+ <inertial mass="4.970684" pos="0.003875 0.002081 -0.04762" fullinertia="0.70337 0.70661 0.0091170 -0.00013900 0.0067720 0.019169" />
+ <joint name="joint1" />
+ <geom name="link1_c" mesh="link1_c" />
+ <body name="link2" quat="1 -1 0 0">
+ <inertial mass="0.646926" pos="-0.003141 -0.02872 0.003495" fullinertia="0.0079620 2.8110e-2 2.5995e-2 -3.925e-3 1.0254e-2 7.04e-4" />
+ <joint name="joint2" range="-1.7628 1.7628" />
+ <geom name="link2_c" mesh="link2_c" />
+ <body name="link3" pos="0 -0.316 0" quat="1 1 0 0">
+ <joint name="joint3" />
+ <inertial mass="3.228604" pos="2.7518e-2 3.9252e-2 -6.6502e-2" fullinertia="3.7242e-2 3.6155e-2 1.083e-2 -4.761e-3 -1.1396e-2 -1.2805e-2" />
+ <geom name="link3_c" mesh="link3_c" />
+ <body name="link4" pos="0.0825 0 0" quat="1 1 0 0">
+ <inertial mass="3.587895" pos="-5.317e-2 1.04419e-1 2.7454e-2" fullinertia="2.5853e-2 1.9552e-2 2.8323e-2 7.796e-3 -1.332e-3 8.641e-3" />
+ <joint name="joint4" range="-3.0718 -0.0698" />
+ <geom name="link4_c" mesh="link4_c" />
+ <body name="link5" pos="-0.0825 0.384 0" quat="1 -1 0 0">
+ <inertial mass="1.225946" pos="-1.1953e-2 4.1065e-2 -3.8437e-2" fullinertia="3.5549e-2 2.9474e-2 8.627e-3 -2.117e-3 -4.037e-3 2.29e-4" />
+ <joint name="joint5" />
+ <geom name="link5_c0" mesh="link5_c0" />
+ <geom name="link5_c1" mesh="link5_c1" />
+ <geom name="link5_c2" mesh="link5_c2" />
+ <body name="link6" quat="1 1 0 0">
+ <inertial mass="1.666555" pos="6.0149e-2 -1.4117e-2 -1.0517e-2" fullinertia="1.964e-3 4.354e-3 5.433e-3 1.09e-4 -1.158e-3 3.41e-4" />
+ <joint name="joint6" range="-0.0175 3.7525" />
+ <geom name="link6_c" mesh="link6_c" />
+ <body name="link7" pos="0.088 0 0" quat="1 1 0 0">
+ <inertial mass="7.35522e-01" pos="1.0517e-2 -4.252e-3 6.1597e-2" fullinertia="1.2516e-2 1.0027e-2 4.815e-3 -4.28e-4 -1.196e-3 -7.41e-4" />
+ <joint name="joint7" />
+ <geom name="link7_c" mesh="link7_c" />
+ <body name="paddle" pos="0 0 0.107">
+
+ <geom name="paddle_handle" type="capsule" fromto="0 0 0 0 0 0.06" size="0.014" mass="0.05" rgba="0.55 0.35 0.2 1" group="2" />
+ <geom name="paddle_blade" type="box" pos="0 0 0.14" size="0.0075 0.075 0.075" mass="0.09" rgba="0.75 0.08 0.08 1" group="2" />
+ <site name="paddle_center" pos="0 0 0.14" size="0.005" rgba="1 1 1 1" group="4" />
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ <body name="link0_b" childclass="panda" pos="0 1.75 0" quat="0.7071068 0 0 -0.7071068">
+ <inertial mass="0.629769" pos="-0.041018 -0.00014 0.049974" fullinertia="0.00315 0.00388 0.004285 8.2904e-7 0.00015 8.2299e-6" />
+ <geom name="link0_c_b" mesh="link0_c" />
+ <body name="link1_b" pos="0 0 0.333">
+ <inertial mass="4.970684" pos="0.003875 0.002081 -0.04762" fullinertia="0.70337 0.70661 0.0091170 -0.00013900 0.0067720 0.019169" />
+ <joint name="joint1_b" />
+ <geom name="link1_c_b" mesh="link1_c" />
+ <body name="link2_b" quat="1 -1 0 0">
+ <inertial mass="0.646926" pos="-0.003141 -0.02872 0.003495" fullinertia="0.0079620 2.8110e-2 2.5995e-2 -3.925e-3 1.0254e-2 7.04e-4" />
+ <joint name="joint2_b" range="-1.7628 1.7628" />
+ <geom name="link2_c_b" mesh="link2_c" />
+ <body name="link3_b" pos="0 -0.316 0" quat="1 1 0 0">
+ <joint name="joint3_b" />
+ <inertial mass="3.228604" pos="2.7518e-2 3.9252e-2 -6.6502e-2" fullinertia="3.7242e-2 3.6155e-2 1.083e-2 -4.761e-3 -1.1396e-2 -1.2805e-2" />
+ <geom name="link3_c_b" mesh="link3_c" />
+ <body name="link4_b" pos="0.0825 0 0" quat="1 1 0 0">
+ <inertial mass="3.587895" pos="-5.317e-2 1.04419e-1 2.7454e-2" fullinertia="2.5853e-2 1.9552e-2 2.8323e-2 7.796e-3 -1.332e-3 8.641e-3" />
+ <joint name="joint4_b" range="-3.0718 -0.0698" />
+ <geom name="link4_c_b" mesh="link4_c" />
+ <body name="link5_b" pos="-0.0825 0.384 0" quat="1 -1 0 0">
+ <inertial mass="1.225946" pos="-1.1953e-2 4.1065e-2 -3.8437e-2" fullinertia="3.5549e-2 2.9474e-2 8.627e-3 -2.117e-3 -4.037e-3 2.29e-4" />
+ <joint name="joint5_b" />
+ <geom name="link5_c0_b" mesh="link5_c0" />
+ <geom name="link5_c1_b" mesh="link5_c1" />
+ <geom name="link5_c2_b" mesh="link5_c2" />
+ <body name="link6_b" quat="1 1 0 0">
+ <inertial mass="1.666555" pos="6.0149e-2 -1.4117e-2 -1.0517e-2" fullinertia="1.964e-3 4.354e-3 5.433e-3 1.09e-4 -1.158e-3 3.41e-4" />
+ <joint name="joint6_b" range="-0.0175 3.7525" />
+ <geom name="link6_c_b" mesh="link6_c" />
+ <body name="link7_b" pos="0.088 0 0" quat="1 1 0 0">
+ <inertial mass="7.35522e-01" pos="1.0517e-2 -4.252e-3 6.1597e-2" fullinertia="1.2516e-2 1.0027e-2 4.815e-3 -4.28e-4 -1.196e-3 -7.41e-4" />
+ <joint name="joint7_b" />
+ <geom name="link7_c_b" mesh="link7_c" />
+ <body name="paddle_b" pos="0 0 0.107">
+
+ <geom name="paddle_handle_b" type="capsule" fromto="0 0 0 0 0 0.06" size="0.014" mass="0.05" rgba="0.55 0.35 0.2 1" group="2" />
+ <geom name="paddle_blade_b" type="box" pos="0 0 0.14" size="0.0075 0.075 0.075" mass="0.09" rgba="0.75 0.08 0.08 1" group="2" />
+ <site name="paddle_center_b" pos="0 0 0.14" size="0.005" rgba="1 1 1 1" group="4" />
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ <geom name="pedestal_b" type="cylinder" size="0.12 0.38" pos="0 1.75 -0.38" contype="0" conaffinity="0" rgba=".25 .25 .28 1" />
+
+ </worldbody>
+
+ <contact>
+ <exclude body1="link0" body2="link1" />
+ <exclude body1="link7" body2="paddle" />
+ <exclude body1="link6" body2="paddle" />
+
+ <pair geom1="geom_ball" geom2="geom_table" solref="-1000000 -17" friction="0.1 0.1 0.005 0.0001 0.0001" solimp="0.98 0.99 0.001 0.5 2" solreffriction="-0.0 -200.0" />
+
+ <pair geom1="geom_ball" geom2="paddle_blade" solref="-600000 -12" friction="0.8 0.8 0.005 0.0001 0.0001" solimp="0.98 0.99 0.001 0.5 2" solreffriction="-0.0 -200.0" />
+ <exclude body1="link0_b" body2="link1_b" />
+ <exclude body1="link7_b" body2="paddle_b" />
+ <exclude body1="link6_b" body2="paddle_b" />
+
+ <pair geom1="geom_ball" geom2="paddle_blade_b" solref="-600000 -12" friction="0.8 0.8 0.005 0.0001 0.0001" solimp="0.98 0.99 0.001 0.5 2" solreffriction="-0.0 -200.0" />
+ </contact>
+
+ <actuator>
+ <motor class="panda" name="motor1" joint="joint1" />
+ <motor class="panda" name="motor2" joint="joint2" />
+ <motor class="panda" name="motor3" joint="joint3" />
+ <motor class="panda" name="motor4" joint="joint4" />
+ <motor class="panda" name="motor5" joint="joint5" ctrlrange="-12 12" />
+ <motor class="panda" name="motor6" joint="joint6" ctrlrange="-12 12" />
+ <motor class="panda" name="motor7" joint="joint7" ctrlrange="-12 12" />
+ <motor class="panda" name="motor1_b" joint="joint1_b" />
+ <motor class="panda" name="motor2_b" joint="joint2_b" />
+ <motor class="panda" name="motor3_b" joint="joint3_b" />
+ <motor class="panda" name="motor4_b" joint="joint4_b" />
+ <motor class="panda" name="motor5_b" joint="joint5_b" ctrlrange="-12 12" />
+ <motor class="panda" name="motor6_b" joint="joint6_b" ctrlrange="-12 12" />
+ <motor class="panda" name="motor7_b" joint="joint7_b" ctrlrange="-12 12" />
+ </actuator>
+</mujoco>
\ No newline at end of file
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/scene/tt_scene.xml b/scripts/roboolympics/shared/sports/tabletennis/sim/scene/tt_scene.xml
new file mode 100644
index 0000000000..0da7de1898
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/tabletennis/sim/scene/tt_scene.xml
@@ -0,0 +1,157 @@
+<!--
+ Robot table tennis scene for robot_coding_bench.
+ * Ball, table, net and the ball-table contact pair: Google DeepMind competitive_robot_table_tennis
+ (system-identified MJCF from ball_states_viz.ipynb, Apache-2.0). World frame: table top at z=0, the long
+ axis is y, the net is the plane y=0. The opponent half is y>0; the robot stands behind the y<0 end.
+ * Arm: MuJoCo Menagerie franka_emika_panda/panda_nohand.xml (Apache-2.0, assets/LICENSE.menagerie-franka),
+ collision meshes only (also used for display), torque (motor) actuators at the Franka torque limits.
+ The joint-space controller (PD + bias compensation) runs in rcb_tt.py at every 1 ms physics step.
+ * Paddle: a 15 x 15 x 1.5 cm box blade on a short handle bolted to the flange instead of the hand.
+ The blade face normal is the paddle's local +x axis; the handle runs along the flange z axis.
+ The ball-paddle contact parameters are hand-picked (not system-identified).
+-->
+<mujoco model="rcb_tabletennis">
+ <compiler angle="radian" meshdir="assets" autolimits="true"/>
+ <option density="1.225" viscosity="1.8e-5" wind="0 0 0" integrator="implicitfast" timestep="0.001"
+ cone="elliptic" impratio="10"/>
+ <size memory="20M"/>
+
+ <visual>
+ <headlight diffuse=".5 .5 .5" specular=".3 .3 .3"/>
+ <global offwidth="1280" offheight="720"/>
+ </visual>
+
+ <default>
+ <default class="panda">
+ <joint armature="0.1" damping="1" axis="0 0 1" range="-2.8973 2.8973"/>
+ <geom type="mesh" rgba="0.92 0.93 0.94 1" group="2"/>
+ <motor ctrlrange="-87 87"/>
+ </default>
+ </default>
+
+ <asset>
+ <texture type="skybox" builtin="gradient" rgb1=".55 .6 .7" rgb2="0.1 0.1 0.15" width="10" height="10"/>
+ <texture type="2d" name="floor" builtin="checker" rgb1=".32 .32 .36" rgb2=".26 .26 .3" width="300" height="300"/>
+ <material name="floor" texture="floor" texrepeat="8 8"/>
+ <mesh name="link0_c" file="link0.stl"/>
+ <mesh name="link1_c" file="link1.stl"/>
+ <mesh name="link2_c" file="link2.stl"/>
+ <mesh name="link3_c" file="link3.stl"/>
+ <mesh name="link4_c" file="link4.stl"/>
+ <mesh name="link5_c0" file="link5_collision_0.obj"/>
+ <mesh name="link5_c1" file="link5_collision_1.obj"/>
+ <mesh name="link5_c2" file="link5_collision_2.obj"/>
+ <mesh name="link6_c" file="link6.stl"/>
+ <mesh name="link7_c" file="link7.stl"/>
+ </asset>
+
+ <worldbody>
+ <light pos="0 -0.5 3" diffuse="0.9 0.9 0.9" specular="0.3 0.3 0.3" castshadow="false"/>
+ <geom name="floor" type="plane" size="6 6 0.1" pos="0 0 -0.76" material="floor"/>
+
+ <body name="ball" pos="0.0 1.4 0.3">
+ <inertial pos="0 0 0" mass="2.7e-3" diaginertia="0.00000072 0.00000072 0.00000072"/>
+ <freejoint name="ball"/>
+ <geom name="geom_ball" size=".02" shellinertia="false" fluidcoef="0.235 0.25 0.0 1.0 1.0" group="1"
+ rgba="0.98 0.70 0.015 1" solref="-100000 -0" fluidshape="ellipsoid"/>
+ </body>
+
+ <body name="table" pos="0 0 -0.76" quat="0.7071068 0 0 0.7071068">
+ <geom name="geom_table" size="1.37 0.7625 0.02" pos="0 0 0.74" type="box" rgba="0.27 0.51 0.14 1"/>
+ <geom name="geom_net" size="0.005 0.915 0.07625" pos="0 0 0.83625" type="box" rgba="1 1 1 0.5"/>
+ <geom size="1.371 0.7635 0.02" pos="0 0 0.739" type="box" contype="0" conaffinity="0" group="1"
+ density="0" rgba="0 0 0 1"/>
+ <geom size="0.03 0.03 0.36" pos="1.1 0.6 0.36" type="box" contype="0" conaffinity="0" rgba=".2 .2 .2 1"/>
+ <geom size="0.03 0.03 0.36" pos="1.1 -0.6 0.36" type="box" contype="0" conaffinity="0" rgba=".2 .2 .2 1"/>
+ <geom size="0.03 0.03 0.36" pos="-1.1 0.6 0.36" type="box" contype="0" conaffinity="0" rgba=".2 .2 .2 1"/>
+ <geom size="0.03 0.03 0.36" pos="-1.1 -0.6 0.36" type="box" contype="0" conaffinity="0" rgba=".2 .2 .2 1"/>
+ </body>
+
+ <!-- visual target zone on the opponent half (the verifier uses the numbers in instance.npz) -->
+ <site name="target_zone" type="box" pos="0 1 0.0005" size="0.2 0.2 0.0005" rgba="1 0.2 0.2 0.45"/>
+
+ <!-- pedestal: visual only -->
+ <geom name="pedestal" type="cylinder" size="0.12 0.38" pos="0 -1.75 -0.38" contype="0" conaffinity="0"
+ rgba=".25 .25 .28 1"/>
+
+ <body name="link0" childclass="panda" pos="0 -1.75 0" quat="0.7071068 0 0 0.7071068">
+ <inertial mass="0.629769" pos="-0.041018 -0.00014 0.049974"
+ fullinertia="0.00315 0.00388 0.004285 8.2904e-7 0.00015 8.2299e-6"/>
+ <geom name="link0_c" mesh="link0_c"/>
+ <body name="link1" pos="0 0 0.333">
+ <inertial mass="4.970684" pos="0.003875 0.002081 -0.04762"
+ fullinertia="0.70337 0.70661 0.0091170 -0.00013900 0.0067720 0.019169"/>
+ <joint name="joint1"/>
+ <geom name="link1_c" mesh="link1_c"/>
+ <body name="link2" quat="1 -1 0 0">
+ <inertial mass="0.646926" pos="-0.003141 -0.02872 0.003495"
+ fullinertia="0.0079620 2.8110e-2 2.5995e-2 -3.925e-3 1.0254e-2 7.04e-4"/>
+ <joint name="joint2" range="-1.7628 1.7628"/>
+ <geom name="link2_c" mesh="link2_c"/>
+ <body name="link3" pos="0 -0.316 0" quat="1 1 0 0">
+ <joint name="joint3"/>
+ <inertial mass="3.228604" pos="2.7518e-2 3.9252e-2 -6.6502e-2"
+ fullinertia="3.7242e-2 3.6155e-2 1.083e-2 -4.761e-3 -1.1396e-2 -1.2805e-2"/>
+ <geom name="link3_c" mesh="link3_c"/>
+ <body name="link4" pos="0.0825 0 0" quat="1 1 0 0">
+ <inertial mass="3.587895" pos="-5.317e-2 1.04419e-1 2.7454e-2"
+ fullinertia="2.5853e-2 1.9552e-2 2.8323e-2 7.796e-3 -1.332e-3 8.641e-3"/>
+ <joint name="joint4" range="-3.0718 -0.0698"/>
+ <geom name="link4_c" mesh="link4_c"/>
+ <body name="link5" pos="-0.0825 0.384 0" quat="1 -1 0 0">
+ <inertial mass="1.225946" pos="-1.1953e-2 4.1065e-2 -3.8437e-2"
+ fullinertia="3.5549e-2 2.9474e-2 8.627e-3 -2.117e-3 -4.037e-3 2.29e-4"/>
+ <joint name="joint5"/>
+ <geom name="link5_c0" mesh="link5_c0"/>
+ <geom name="link5_c1" mesh="link5_c1"/>
+ <geom name="link5_c2" mesh="link5_c2"/>
+ <body name="link6" quat="1 1 0 0">
+ <inertial mass="1.666555" pos="6.0149e-2 -1.4117e-2 -1.0517e-2"
+ fullinertia="1.964e-3 4.354e-3 5.433e-3 1.09e-4 -1.158e-3 3.41e-4"/>
+ <joint name="joint6" range="-0.0175 3.7525"/>
+ <geom name="link6_c" mesh="link6_c"/>
+ <body name="link7" pos="0.088 0 0" quat="1 1 0 0">
+ <inertial mass="7.35522e-01" pos="1.0517e-2 -4.252e-3 6.1597e-2"
+ fullinertia="1.2516e-2 1.0027e-2 4.815e-3 -4.28e-4 -1.196e-3 -7.41e-4"/>
+ <joint name="joint7"/>
+ <geom name="link7_c" mesh="link7_c"/>
+ <body name="paddle" pos="0 0 0.107">
+ <!-- handle along the flange z axis; blade centre 0.14 m beyond the flange -->
+ <geom name="paddle_handle" type="capsule" fromto="0 0 0 0 0 0.06" size="0.014"
+ mass="0.05" rgba="0.55 0.35 0.2 1" group="2"/>
+ <geom name="paddle_blade" type="box" pos="0 0 0.14" size="0.0075 0.075 0.075"
+ mass="0.09" rgba="0.75 0.08 0.08 1" group="2"/>
+ <site name="paddle_center" pos="0 0 0.14" size="0.005" rgba="1 1 1 1" group="4"/>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </worldbody>
+
+ <contact>
+ <exclude body1="link0" body2="link1"/>
+ <exclude body1="link7" body2="paddle"/>
+ <exclude body1="link6" body2="paddle"/>
+ <!-- system-identified ball-table contact (DeepMind) -->
+ <pair geom1="geom_ball" geom2="geom_table" solref="-1000000 -17" friction="0.1 0.1 0.005 0.0001 0.0001"
+ solimp="0.98 0.99 0.001 0.5 2" solreffriction="-0.0 -200.0"/>
+ <!-- ball-paddle contact: hand-picked, NOT system-identified -->
+ <pair geom1="geom_ball" geom2="paddle_blade" solref="-600000 -12" friction="0.8 0.8 0.005 0.0001 0.0001"
+ solimp="0.98 0.99 0.001 0.5 2" solreffriction="-0.0 -200.0"/>
+ </contact>
+
+ <actuator>
+ <motor class="panda" name="motor1" joint="joint1"/>
+ <motor class="panda" name="motor2" joint="joint2"/>
+ <motor class="panda" name="motor3" joint="joint3"/>
+ <motor class="panda" name="motor4" joint="joint4"/>
+ <motor class="panda" name="motor5" joint="joint5" ctrlrange="-12 12"/>
+ <motor class="panda" name="motor6" joint="joint6" ctrlrange="-12 12"/>
+ <motor class="panda" name="motor7" joint="joint7" ctrlrange="-12 12"/>
+ </actuator>
+</mujoco>
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/serves_pool.json b/scripts/roboolympics/shared/sports/tabletennis/sim/serves_pool.json
new file mode 100644
index 0000000000..76569e0835
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/tabletennis/sim/serves_pool.json
@@ -0,0 +1 @@
+{"note": "DeepMind competitive_robot_table_tennis serves.json (CC-BY-4.0): the 109 serves the rally task's stroke controller returns robustly (see tabletennis-rally-interactive README)", "serves": [{"id": 11, "pos": [-0.4049581366048593, 1.4486604589550924, 0.3062632910837785], "vel": [1.0540687388742394, -4.866961343628475, -0.9738064550343261], "spin": [21.723326268467314, 7.826555003862861, -16.343148641254796]}, {"id": 24, "pos": [-0.32775633462433706, 1.2505211863990273, 0.15318614928165003], "vel": [0.21685165997738276, -4.846903311004677, -1.74417390141446], "spin": [-8.470302843515311, 5.974802906253454, 2.22544122554239]}, {"id": 98, "pos": [-0.239689307574105, 1.4175126556604447, 0.16299332678515244], "vel": [0.5408770631283645, -5.8732988912516175, -2.1538360535222045], "spin": [25.148466071415665, -12.322980651175794, -23.531344660791536]}, {"id": 110, "pos": [-0.5768223704206398, 1.4139927402114323, 0.31399513408138247], "vel": [1.247381517760839, -4.310839710568873, -0.5233117398675065], "spin": [3.8602003686804123, 2.0153756161626317, -24.24698699003726]}, {"id": 117, "pos": [0.4621538093247055, 1.2354671003504092, 0.38270532257843964], "vel": [-1.354577004598282, -3.970934399476786, -1.1350348584734755], "spin": [4.505974479522077, -4.165620559951317, 6.897404062739265]}, {"id": 119, "pos": [-0.38513632136491927, 1.4397619670932646, 0.07849106518003968], "vel": [0.3808588557472728, -5.427401884573038, -2.610272723178758], "spin": [-1.1554431023880938, -5.926682793189628, -17.1975634508498]}, {"id": 193, "pos": [0.31964363629133535, 1.3986685623211956, 0.3532919745295203], "vel": [-0.543850139679536, -4.7938639335335615, -0.9041924699248935], "spin": [8.105159001337276, -3.1340466719264275, 9.85122117029645]}, {"id": 194, "pos": [0.06705028714960473, 1.461402600670063, 0.25490866183129945], "vel": [-0.24089958178035534, -4.481258200884452, -2.245424514204765], "spin": [19.291977327021566, -7.505706476658349, -7.656202478577812]}, {"id": 261, "pos": [-0.2680919095017574, 1.4330059515718243, 0.1921022530081258], "vel": [0.17651746877933863, -5.168074822385836, -2.7397793915939195], "spin": [4.777644997301909, -2.4587988699054333, -0.5945738000448773]}, {"id": 273, "pos": [-0.37919349540365205, 1.4292437348394598, 0.20969925175606507], "vel": [0.5081292493844393, -5.144531273889067, -1.8725370084211856], "spin": [0.6670736010404095, 13.859542825234914, -1.735295520860477]}, {"id": 337, "pos": [-0.23222762261603136, 1.4190443358479734, 0.26033008779310185], "vel": [0.23980670349643987, -5.26595903948819, -1.6118596363618145], "spin": [28.037148460519905, -3.028471948611366, -9.45666205823031]}, {"id": 424, "pos": [-0.20573937744572177, 1.4283624624349494, 0.29441235631551066], "vel": [0.2958696709883265, -4.973864037488604, -1.7576077642322923], "spin": [-19.963262845149718, 15.700031965719354, 21.053424374291133]}, {"id": 428, "pos": [0.39185877543202075, 1.4634420795955345, 0.1768245469539992], "vel": [-1.2479586068415625, -5.454738608000466, -1.918446664110609], "spin": [19.222594500057788, -15.6922920219571, -5.9853613704018525]}, {"id": 465, "pos": [0.5516428827217219, 1.4132861096231577, 0.270403030464896], "vel": [-1.9930764902752915, -5.077640450294763, -1.1927146201637715], "spin": [35.607608536135004, -26.121935144166454, 30.41348398307529]}, {"id": 491, "pos": [0.3457104418865123, 1.3988969116435186, 0.2705809043447504], "vel": [-0.44202151764332975, -4.3365730816055175, -2.3118037740386908], "spin": [-16.533820222124966, 5.8936483427768485, -5.235631243170789]}, {"id": 501, "pos": [0.29902607957976185, 1.2873562889814063, 0.3766640814753633], "vel": [-0.7474113957046168, -3.9582688933848953, -0.862508668925518], "spin": [5.964538110259766, -5.98081743335991, 5.507724138666307]}, {"id": 510, "pos": [-0.3828109893813139, 1.416526607659857, 0.3462224343021844], "vel": [1.219255415011712, -4.72377553082806, -0.6343590953422089], "spin": [33.7282324847763, 25.919364605175563, -20.72705882306522]}, {"id": 514, "pos": [-0.13539712243010632, 1.4498183695747962, 0.35802383521022385], "vel": [-0.18393713198692355, -4.662521012827509, -1.801425537646406], "spin": [-5.752446495483427, 14.111004236938125, 13.448834088984288]}, {"id": 539, "pos": [0.44506968865152663, 1.4611718889960748, 0.30621112680889057], "vel": [-1.3309772973021823, -4.307650747226612, -1.8616890567347866], "spin": [-14.328330175559168, 2.669450178013314, -14.270898376295214]}, {"id": 550, "pos": [0.234135592180883, 1.4433793965369843, 0.3869475586448191], "vel": [-0.47580007398912416, -4.420862422913165, -2.2028710959842943], "spin": [-2.8615871578075125, 6.96288428887937, 3.8703287989351627]}, {"id": 552, "pos": [-0.14395418016668207, 1.4229826333860867, 0.31888732693708743], "vel": [0.5067758056048255, -5.09864422025642, -1.609247439530009], "spin": [22.35682798568819, 4.451869963975116, -15.865353187273692]}, {"id": 559, "pos": [0.2871264638269937, 1.2760916193806848, 0.18271958870177732], "vel": [-1.0099153024629999, -4.761876809617584, -1.932722344634323], "spin": [-8.137329192357807, -0.29752252903940324, -2.9025084691583056]}, {"id": 578, "pos": [-0.39970839334328995, 1.423545183051101, 0.18849539675646385], "vel": [0.3278611370728181, -4.847816695561695, -2.0475399124829434], "spin": [15.475560751089873, -21.18846489407994, -22.293078935909257]}, {"id": 579, "pos": [-0.3343478406667241, 1.4504041815872282, 0.3109239191740299], "vel": [0.7853063428661995, -4.725880944434543, -2.352729350492706], "spin": [5.394878666089257, 5.7460033881289005, -2.6452322700214332]}, {"id": 585, "pos": [-0.3872725033864609, 1.4254962241912374, 0.13050359214993934], "vel": [1.0181370057787311, -4.9724707693461205, -2.499696056345045], "spin": [0.9283660717595468, -5.251126185854607, -44.059309084669025]}, {"id": 600, "pos": [-0.31011640587625416, 1.478993608249081, 0.14263871170590653], "vel": [0.6879578002603645, -5.74184064455354, -2.836447424944301], "spin": [13.834892179447017, -6.881318249973792, -9.484570379338285]}, {"id": 633, "pos": [-0.3817098213046743, 1.1880561977397082, 0.15285250086103463], "vel": [-0.06154719954534229, -4.982192996285556, -1.508537050017422], "spin": [16.624313443626892, 2.7405149797099333, 4.081886357446737]}, {"id": 676, "pos": [0.12626788692626156, 1.4440650983331489, 0.30197623145903385], "vel": [-0.8080334508322459, -4.214754814782631, -1.671526507588609], "spin": [-0.5012250468524888, 3.8316085540526137, 24.736488244552724]}, {"id": 695, "pos": [-0.4011534547651849, 1.4498378540123045, 0.31125889979511767], "vel": [0.926377333509501, -4.846918705365502, -1.5325221442114363], "spin": [18.828300637928965, 8.44532773416693, -15.565398641265707]}, {"id": 763, "pos": [0.0952444593817259, 1.4452483980916797, 0.22298557853674306], "vel": [-0.8707816872478126, -5.272072194615711, -1.5664933512353474], "spin": [-11.462618410747313, 31.25968720144166, 11.996136061981671]}, {"id": 827, "pos": [0.3060355857000118, 1.4674673460073875, 0.12820465262917263], "vel": [-1.112151855228876, -5.471515434933733, -2.1092454631890125], "spin": [-0.35320826583928316, -4.619090418978232, -6.529630599015004]}, {"id": 828, "pos": [-0.4526520576254581, 1.2962867267482296, 0.29626608596853043], "vel": [0.7559205101376528, -4.470262428070959, -2.540592210230233], "spin": [-10.680417403757241, 35.26700770911677, -1.8372008617845823]}, {"id": 837, "pos": [0.1519319690858182, 1.4405960375521691, 0.2602364776855966], "vel": [-0.6908944115018857, -4.123072637936164, -2.4780521526261943], "spin": [-1.767409443094369, -24.05089433459393, -14.921775326553922]}, {"id": 847, "pos": [-0.5314931279808703, 1.427454078295705, 0.2878770624720682], "vel": [1.1724840966082195, -5.045365550864894, -1.150500601208381], "spin": [14.400007707204045, -15.255877129651603, -14.026897202550298]}, {"id": 882, "pos": [-0.5512157568545957, 1.4012265053924253, 0.3716314751102631], "vel": [1.2173162973159775, -4.672501739157819, -0.7653332687688074], "spin": [6.904575402351405, 6.307419887850615, -11.529169533850247]}, {"id": 914, "pos": [0.47826321041814357, 1.4574653860095121, 0.2457214591659434], "vel": [-1.3024975098096907, -4.3852695687604575, -2.5573650632547262], "spin": [-0.3377661114238659, -9.027051045984303, 0.4287762138110602]}, {"id": 1066, "pos": [-0.34213889644035556, 1.4107445872125262, 0.36261298317773305], "vel": [0.4920595595952536, -4.543341364848694, -1.4347235566034195], "spin": [2.1655237386264026, -1.3259054196603872, -12.69139467887272]}, {"id": 1088, "pos": [-0.25244494648347293, 1.4382853780032687, 0.28735707529548044], "vel": [0.5828379561784516, -4.8101433858443015, -1.9576675024433483], "spin": [21.12654262023895, 11.604095752063243, -1.1906576636996016]}, {"id": 1149, "pos": [-0.3241917065788105, 1.4255236253414671, 0.22701356431620465], "vel": [0.5797914398854357, -4.8595617899842845, -1.414266417071141], "spin": [-3.781733383642301, -15.31329350103228, -23.35177333577788]}, {"id": 1159, "pos": [-0.29659596184277315, 1.4825826543870906, 0.35297779370616233], "vel": [0.4079343353869322, -4.465705553356311, -2.351000374619085], "spin": [-0.6065151860945768, -0.49406795849030105, -1.1784654294554875]}, {"id": 1190, "pos": [-0.10236539633338974, 1.2827712637008568, 0.3418216146573035], "vel": [0.706776680622113, -4.3998016045192845, -2.393628193058326], "spin": [-12.800702520829173, -14.269076611572741, -4.37651652608102]}, {"id": 1191, "pos": [-0.24627551649087032, 1.4629566159851934, 0.2320677032386983], "vel": [0.6812856890879699, -4.7361782471140375, -3.0362617670442744], "spin": [-7.300519468506536, -6.274066782563657, 14.730487004334437]}, {"id": 1193, "pos": [0.11552979909687829, 1.4109782559628052, 0.4026550276656417], "vel": [-0.7267673645902548, -4.280920775219681, -1.1989364779760898], "spin": [3.5727469048237857, -1.7052352128413508, 9.065267299592312]}, {"id": 1216, "pos": [0.16998329036725243, 1.4448024697139548, 0.25280025346310275], "vel": [-0.4772269814454274, -4.460037882258443, -1.9988787279902716], "spin": [31.987321573940715, -21.40518952732062, -18.50143562406671]}, {"id": 1228, "pos": [-0.2715786619859439, 1.1543840012284887, 0.31738194927374214], "vel": [0.7104263812812404, -3.667011149602738, -2.158531813580238], "spin": [-16.91620632030224, -9.879798546394637, -5.511573118491288]}, {"id": 1258, "pos": [-0.37836355836546826, 1.2625447791344666, 0.1358547118197364], "vel": [-0.10979071028818145, -4.706099237177528, -1.8678369166442645], "spin": [2.484897942623334, -4.87599463433698, 2.585116236807913]}, {"id": 1281, "pos": [-0.5240077991949766, 1.4347345312797715, 0.3866331920830992], "vel": [0.7807733155006649, -4.310324567681965, -2.2548034997137347], "spin": [-2.295515989189582, -3.7907525245093208, -3.2655808052542583]}, {"id": 1286, "pos": [-0.4812020658633066, 1.3542498937207659, 0.2939528350690088], "vel": [1.1682246453834035, -4.368763387061333, -1.13881245860569], "spin": [0.4742897179677393, -9.757425859977367, -28.1590621252726]}, {"id": 1322, "pos": [-0.4613711200042408, 1.4311379119854988, 0.26467415472870603], "vel": [1.113507110452349, -5.0496088496614036, -1.9808026481178513], "spin": [1.4407011961535376, -7.807532214620735, -7.857357490725972]}, {"id": 1364, "pos": [-0.2113559596111618, 1.4237804574844695, 0.1992363701582818], "vel": [0.03571714111178461, -4.88940498967645, -1.8712862615804393], "spin": [0.8617841060123149, 2.461855808903895, 2.4406862238435263]}, {"id": 1402, "pos": [-0.13402118648082215, 1.4334108457853478, 0.3358452140041156], "vel": [-0.0070981437176074556, -4.539762382860411, -1.3975647548678842], "spin": [-19.43489315424744, -10.209803775436994, -6.961326496625412]}, {"id": 1419, "pos": [-0.1424687980998095, 1.4505101592454746, 0.26412753445794135], "vel": [0.5021583593582322, -5.089840972241625, -1.9927637029823944], "spin": [14.751736498831693, -4.415946209883158, -14.558836752795209]}, {"id": 1425, "pos": [-0.17455724066921177, 1.4413841383390333, 0.215107135178888], "vel": [-0.10529541447893435, -5.654573657815397, -1.6125987670901734], "spin": [-17.509183633104367, -80.2902486330937, 50.86243570206514]}, {"id": 1499, "pos": [-0.36382607453051735, 1.4186682280091545, 0.32156091988949953], "vel": [0.9265769838445211, -4.693755075606908, -1.8805071986474655], "spin": [-3.483070412731041, -9.65697958001554, -13.616718647189016]}, {"id": 1514, "pos": [-0.286066250592241, 1.3465448314230573, 0.41853265345793456], "vel": [0.15682282139212225, -4.276617855325889, -1.1868396934047798], "spin": [1.0286325706930666, 0.7790555352924469, -3.1491320515961982]}, {"id": 1534, "pos": [-0.06485967638509445, 1.4511674284683203, 0.2578124173577285], "vel": [-0.01758283807838969, -4.421811132859035, -1.9216400922002153], "spin": [20.94278494733252, -13.186731149491585, -13.01485070301071]}, {"id": 1566, "pos": [-0.2334835359961089, 1.4356474517033955, 0.3829663257634473], "vel": [0.1774085836832497, -4.352025738593028, -2.2043539138332973], "spin": [-8.081554386375776, 1.1479565373421317, 16.560201434754628]}, {"id": 1598, "pos": [-0.6098590604191972, 1.498004960690973, 0.2866195108684692], "vel": [0.8978951239877346, -4.961401750364483, -1.3173997993835385], "spin": [-0.6843690522592096, -1.650588570147271, -3.1858990293973255]}, {"id": 1633, "pos": [-0.6481412607628801, 1.3773110152408532, 0.3270679612145034], "vel": [1.1704851268988705, -4.439963988103589, -1.81766887266196], "spin": [1.4907780754348856, -7.875809196005324, -7.689952963266001]}, {"id": 1672, "pos": [0.04589016267043134, 1.480408436735658, 0.2936485750285157], "vel": [0.13316718243002743, -4.541454740843564, -2.813572147866275], "spin": [0.8478150882030504, 3.269848272684665, 2.5230907809797842]}, {"id": 1678, "pos": [0.0690781159916203, 1.449812554597973, 0.4292443268437318], "vel": [-0.40183696203443986, -4.227021853806545, -1.4010737722710158], "spin": [-1.2297519759413384, -8.576881006211556, 5.65656284613449]}, {"id": 1703, "pos": [0.5759773983395609, 1.4365433310956617, 0.3000045076966916], "vel": [-1.3587940780282133, -4.6054123261694695, -1.3596150467929333], "spin": [-1.7443743225004966, 0.4829481472061006, -10.773623220617822]}, {"id": 1707, "pos": [-0.1563245343370212, 1.4353926361554739, 0.21179580212867846], "vel": [0.623759435514275, -5.713474076502528, -1.5502867529647653], "spin": [-2.598742497249355, -7.845140795915077, -18.96073927998756]}, {"id": 1730, "pos": [-0.3931186673251525, 1.434540639709042, 0.29934741025319533], "vel": [0.8369784102615869, -5.049665646844286, -1.886461119941323], "spin": [6.697695443636102, 10.761941938196944, -1.298852293932447]}, {"id": 1757, "pos": [-0.21216441586239737, 1.418508513075304, 0.3219075218156344], "vel": [0.27465526732770573, -4.462502801964814, -0.8987376693020879], "spin": [12.36978943317683, -6.740979501213409, -23.313588111238552]}, {"id": 1800, "pos": [-0.45368920069082563, 1.4375345891391187, 0.3205575312594913], "vel": [0.5040579262796396, -4.053054763422549, -2.109060379362117], "spin": [1.4241785914356304, 2.195087237066038, 2.2519625178373173]}, {"id": 1825, "pos": [-0.12166145879216621, 1.489059386593448, 0.3273623861389793], "vel": [0.17667259377099995, -4.996354353658553, -2.61830740201127], "spin": [3.7458647832216356, 5.048084122354173, 7.994971154603341]}, {"id": 1900, "pos": [-0.5177639220529926, 1.4685391016517557, 0.27686515243385135], "vel": [1.5695778000260039, -5.427926027871897, -1.514872918387209], "spin": [28.55490089067588, -20.0303915081788, -29.08217302121048]}, {"id": 1939, "pos": [-0.04244879500557531, 1.4413613657285391, 0.2427725403511884], "vel": [0.3080043273045943, -4.758413661046424, -1.7278791594721117], "spin": [-27.194251377134393, -24.547908360562793, -23.823165206319807]}, {"id": 1971, "pos": [0.512422302467441, 1.4014615080852866, 0.4156530903426546], "vel": [-1.18382460046776, -4.0508732812940735, -1.5542803961119827], "spin": [-1.4981317659351197, -0.5942179675340213, 8.600036151627029]}, {"id": 1988, "pos": [0.1722283342657115, 1.448361799057779, 0.3035212106849696], "vel": [-0.5290143303727703, -4.547798288079958, -2.711741871017806], "spin": [-14.694789382604673, 5.429419830546253, 0.28108927089226443]}, {"id": 1991, "pos": [-0.04988101591029433, 1.1899263250768197, 0.16357659385905304], "vel": [-0.6672423703668178, -4.9627149139323405, -1.5301676177201682], "spin": [16.439207731959694, -3.0024177550205366, 3.4059983954873547]}, {"id": 2026, "pos": [0.3044266424038287, 1.468045981235012, 0.18670515813372746], "vel": [-1.0462387910708313, -5.769632436441097, -1.7836712747572698], "spin": [-18.22067907679871, -2.2086269242262246, -2.5089039627472762]}, {"id": 2033, "pos": [-0.34172486264960256, 1.4338184934098408, 0.272067403519489], "vel": [0.9988146067052398, -5.38288402400957, -1.2743198621257728], "spin": [5.07674838935463, -5.827310641258366, -22.690851648913434]}, {"id": 2044, "pos": [-0.4257850835097349, 1.2979614171136091, 0.36077551340390746], "vel": [0.8236652305973449, -4.327174026777351, -1.9933695333728831], "spin": [35.72092107074317, 31.138068954480886, -12.888324484352744]}, {"id": 2061, "pos": [-0.6531966250399616, 1.4692693439809388, 0.2796573863763134], "vel": [0.6899070149462255, -4.519266968379127, -1.939507884160626], "spin": [-12.881273191824645, -42.34301049738489, 28.078188016654767]}, {"id": 2063, "pos": [0.031076001380951155, 1.4469186563722225, 0.2531599363755095], "vel": [-0.5360830827315086, -5.253921174336332, -2.364150636458015], "spin": [-10.94771035110867, 50.28355479593482, 27.827826384242083]}, {"id": 2070, "pos": [0.24491935174483762, 1.4415507121175728, 0.3468021452244696], "vel": [-0.18813661635825463, -4.701893375386033, -2.4502568003938383], "spin": [-17.239060143247304, -2.734022721073727, -1.6623524061012593]}, {"id": 2072, "pos": [-0.32335859338331413, 1.4428513314470184, 0.2636065841851759], "vel": [0.8171380576727789, -4.696183470123974, -1.7519899536081045], "spin": [0.7751500529061292, -13.12128330031004, -9.268205959004485]}, {"id": 2095, "pos": [0.08868019890244752, 1.3982033031702448, 0.1581554366269831], "vel": [-0.26546474125835884, -5.899385042735905, -1.7031282997194157], "spin": [7.134359664969598, 4.988356362817072, 7.799304795857916]}, {"id": 2113, "pos": [0.576357520716982, 1.4748545451614103, 0.4099003518704902], "vel": [-1.0819114474384748, -4.165787849917945, -2.0554312105676473], "spin": [17.053176140981883, -10.551714930376097, -10.600421351423199]}, {"id": 2114, "pos": [-0.49399619857531046, 1.4363813011177058, 0.3663324124950697], "vel": [0.8529583854279472, -5.0970534667214515, -1.220839455831288], "spin": [1.2722706744307772, -0.6134905255222327, -6.475745072872328]}, {"id": 2137, "pos": [-0.4053644161442993, 1.3460774494867933, 0.36298393616002395], "vel": [1.2366110299763742, -4.3647715101438465, -2.2092466124334313], "spin": [6.694496417478496, -12.271677034326698, -8.066652206935723]}, {"id": 2145, "pos": [0.2982530990686171, 1.429517853243929, 0.28587526739543495], "vel": [-0.77959599147891, -5.342097319829765, -1.8165251355835483], "spin": [2.3777276890011723, 19.258287031038336, 31.164364787932023]}, {"id": 2199, "pos": [-0.012451933400186773, 1.4382061507968305, 0.28168164622477826], "vel": [-0.04165616555120048, -5.008015773832297, -1.6961475981614054], "spin": [9.597886050117646, 6.421689212551959, 8.144699201356124]}, {"id": 2217, "pos": [0.23464088486320855, 1.457274904498396, 0.25079849116235187], "vel": [-1.4457413646018369, -4.7849284712001, -1.9563808681453132], "spin": [8.962294262428141, 9.828315170880558, 31.011176179368555]}, {"id": 2224, "pos": [-0.1354386948238012, 1.481206968182418, 0.25790649384099923], "vel": [0.2780593178099566, -4.8111723543884874, -2.5053538870518617], "spin": [-3.209462490737015, 3.1640948728306406, 5.930777861661515]}, {"id": 2249, "pos": [-0.35695342841133004, 1.4432851231709032, 0.25060648485715975], "vel": [0.6090913728368651, -5.526804046440282, -1.8413614419512787], "spin": [-11.379144501999738, -10.57919144100746, -1.215776537381708]}, {"id": 2267, "pos": [-0.4534601456417101, 1.3906491444609772, 0.22236613435770144], "vel": [0.5228705537712461, -5.450438056161476, -1.6883406065227289], "spin": [8.853184786762245, -1.256610891704211, 1.694424866655136]}, {"id": 2271, "pos": [0.05443652134829731, 1.4324654388313534, 0.35871304302811946], "vel": [-0.5049567016088181, -4.016352519312174, -0.800732667943064], "spin": [5.230464776803802, -6.3792638413567015, -11.63531087512327]}, {"id": 2296, "pos": [0.5629832747944347, 1.3975831719757028, 0.16745128832173728], "vel": [-1.6725877758158338, -5.758491360442465, -1.6760310426458471], "spin": [2.0249860949345497, -9.790748292399948, -17.076047218539586]}, {"id": 2302, "pos": [-0.4082344929405746, 1.439063477676491, 0.33904585409309446], "vel": [0.8951505892100406, -4.2733553679788745, -1.6737707309115497], "spin": [18.009978722533287, 2.2575469169714286, -21.21827659584833]}, {"id": 2334, "pos": [0.492937631799761, 1.4393608235103403, 0.16357323357449896], "vel": [-1.3077425546579282, -5.798793752314654, -2.0939879971949074], "spin": [31.98004390342229, -32.817590396377334, -36.74224406215835]}, {"id": 2345, "pos": [-0.3188394859272696, 1.438213568604347, 0.36334806715118073], "vel": [1.1733213053860947, -4.503387279472462, -1.7368508932221973], "spin": [-5.691202364883631, -7.324239493306263, -28.62952609763727]}, {"id": 2353, "pos": [-0.3210157398388675, 1.3826960652878446, 0.3291507909688976], "vel": [0.9210914561879103, -4.5417608223838055, -2.155520609758438], "spin": [-11.081896038509232, 12.219229390173764, -10.672944698476808]}, {"id": 2367, "pos": [-0.560513671641388, 1.4088075199623395, 0.3485842530837476], "vel": [1.3292646634130316, -4.927888966877444, -1.199980041841227], "spin": [11.781552390718439, 3.1279892550557946, -18.555032525703545]}, {"id": 2377, "pos": [-0.30317545915022015, 1.4217605594473486, 0.3306340959878263], "vel": [0.922610690682124, -4.594600953197403, -1.3261711692171276], "spin": [-3.4284368351482017, -6.793316111136656, -26.43863516307784]}, {"id": 2393, "pos": [-0.4086172828345945, 1.4290793266702095, 0.3910144389240547], "vel": [0.5090588491774186, -3.781553873696944, -0.9059826485141945], "spin": [-5.055166829898362, -9.335730972489076, -29.128204500716613]}, {"id": 2425, "pos": [-0.20060495468700196, 1.3334919253552544, 0.38416765347511694], "vel": [0.025292609087780967, -3.8864365801837013, -1.1769216072650412], "spin": [-5.410048078127717, -3.6754303130400405, -6.076306884552507]}, {"id": 2447, "pos": [-0.3484570544497421, 1.4032295327806799, 0.42982027652916405], "vel": [0.41465832486120696, -4.449324901376074, -1.8573351031684906], "spin": [8.78283142373407, 8.21290942013584, -5.490736169717853]}, {"id": 2474, "pos": [-0.27785207814718577, 1.4997375491192224, 0.2295965471133732], "vel": [0.9462395036338209, -5.117948021290964, -2.3904443274054437], "spin": [-5.749180855079036, -4.629866794822625, -8.183908171803177]}, {"id": 2475, "pos": [-0.3960502358050527, 1.4300106493416196, 0.28210103164094796], "vel": [0.8827167576055289, -4.708740796834323, -2.682109697409332], "spin": [11.141550673573963, 7.534739006868594, -3.009926645752371]}, {"id": 2525, "pos": [0.4560408258373585, 1.4243536808370676, 0.262912553268286], "vel": [-0.540824058119839, -5.100761293339064, -2.183867815603693], "spin": [30.29236128296459, -2.5148646479717973, 13.30413467066702]}, {"id": 2550, "pos": [0.14002354196493214, 1.4399703530503334, 0.3731570920122777], "vel": [-0.40024044029979333, -4.5506285693514, -2.0562042772213496], "spin": [-26.419410889560005, 17.23310379916552, 8.793755573145726]}, {"id": 2556, "pos": [-0.5922234165038366, 1.4005635122253106, 0.32643412908645975], "vel": [1.145720551612384, -4.143890849878027, -1.9449776985186542], "spin": [-1.9833882252762494, -9.11573715852647, -12.642217941795762]}, {"id": 2576, "pos": [-0.3652671830861511, 1.4118560950164865, 0.3777035018870971], "vel": [0.14384217958663548, -3.8553232910353135, -0.9281948351573029], "spin": [2.237370805092966, -60.02464510531289, -12.572908651579588]}, {"id": 2618, "pos": [-0.470465824135137, 1.4562762311376845, 0.18153216758206328], "vel": [1.3926624045407625, -5.707174242684581, -2.1689460676131613], "spin": [12.004333357799021, -3.2651510124388516, -23.603094304286483]}, {"id": 2660, "pos": [0.30110698322735324, 1.427693465219787, 0.2238191912318034], "vel": [-0.30275253023008386, -4.970271641804054, -2.342877966391577], "spin": [-3.571656623890767, -9.825332181091039, -20.805032744749653]}, {"id": 2702, "pos": [0.0748104301052215, 1.458625800314788, 0.17038560652947707], "vel": [0.12269544154493864, -5.464210401490957, -2.4665698931424305], "spin": [-0.2712173657895323, -18.05490705721318, -15.061496335855276]}]}
\ No newline at end of file
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sim/workers.py b/scripts/roboolympics/shared/sports/tabletennis/sim/workers.py
new file mode 100644
index 0000000000..001c658f1f
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/tabletennis/sim/workers.py
@@ -0,0 +1,150 @@
+"""Bounded, per-seat planning/render processes. No worker owns the shared world."""
+import os
+import subprocess
+import sys
+import threading
+import time
+from pathlib import Path
+
+import numpy as np
+from ipc import _Conn
+
+HERE = Path(__file__).resolve().parent
+
+
+def affinity(name, all_threads=False):
+ value = os.environ.get(name, "")
+ if value:
+ cpus = set()
+ for part in value.split(','):
+ ends = part.split('-')
+ cpus.update(range(int(ends[0]), int(ends[-1]) + 1))
+ if all_threads:
+ # Mesa can override the inherited mask when it creates native threads.
+ for path in Path('/proc/self/task').iterdir():
+ try: os.sched_setaffinity(int(path.name), cpus)
+ except ProcessLookupError: pass
+ else:
+ os.sched_setaffinity(0, cpus)
+
+
+class ProcessWorker:
+ def __init__(self, kind, side, timeout=30):
+ self.timeout = timeout
+ self.lock = threading.Lock()
+ self.proc = subprocess.Popen([sys.executable, str(Path(__file__).resolve()), kind, side],
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, cwd=HERE)
+ self.conn = _Conn(self.proc.stdout, self.proc.stdin)
+ try:
+ if self.conn.recv(time.monotonic() + timeout) != 'ready':
+ raise RuntimeError('worker startup failed')
+ except Exception:
+ self.close()
+ raise
+
+ def call(self, payload):
+ if not self.lock.acquire(blocking=False):
+ raise BlockingIOError('one request per seat and worker may be in flight')
+ try:
+ deadline = time.monotonic() + self.timeout
+ self.conn.send(payload, deadline)
+ ok, value = self.conn.recv(deadline)
+ if not ok:
+ raise RuntimeError(value)
+ return value
+ except Exception:
+ self.close()
+ raise
+ finally:
+ self.lock.release()
+
+ def close(self):
+ if self.proc.poll() is None:
+ self.proc.terminate()
+ try: self.proc.wait(timeout=1)
+ except subprocess.TimeoutExpired:
+ self.proc.kill(); self.proc.wait(timeout=1)
+ self.proc.stdin.close(); self.proc.stdout.close()
+
+
+def prepare(pl, job):
+ """Prepare a contact configuration. The trajectory start is deliberately NOT baked in."""
+ import duel
+ from rally import VEL_LIMIT
+ dec = job['decision']
+ pl.s.d.qpos[pl.s._qadr] = np.asarray(job['q'], float)
+ pl.s._target = np.asarray(job['target'], float)
+ pos, normal, vel = (np.asarray(dec[k], float) for k in ('pos', 'normal', 'vel'))
+ normal = normal / np.linalg.norm(normal)
+ role = 0 if pl.side == duel.FIRST_RECEIVER else 1
+ rng = np.random.default_rng([duel.SEED, role, job['point'], job['ordinal']])
+ if os.environ.get('DUEL_SCATTER', '1') == '1':
+ pos = pos + rng.normal(0, .004, 3)
+ axis = np.cross(normal, rng.normal(size=3))
+ axis /= max(np.linalg.norm(axis), 1e-12)
+ angle = np.radians(rng.normal(0, .6))
+ normal = normal*np.cos(angle) + np.cross(axis, normal)*np.sin(angle)
+ normal /= np.linalg.norm(normal)
+ vel = vel * (1 + rng.normal(0, .02))
+ q, error = pl._ik_best(pos, normal)
+ jac = pl.s.jacobian(q)[:3]
+ weight = np.diag(VEL_LIMIT**2)
+ qd = weight @ jac.T @ np.linalg.solve(jac @ weight @ jac.T + 1e-8*np.eye(3), vel)
+ scale = max(1., float(np.max(np.abs(qd)/VEL_LIMIT))/.9)
+ return dict(q=q, qd=qd/scale, ik_residual=float(error), speed_scale=scale)
+
+
+def trajectory(target, previous, prepared, T, low, high):
+ """Cheap trajectory construction from the latest command at the effective boundary."""
+ from rally import hermite, CONTROL_DT, VEL_LIMIT
+ start = np.asarray(target, float)
+ speed = (start - np.asarray(previous, float))/CONTROL_DT
+ goal, velocity = prepared['q'], prepared['qd']
+ n = max(1, int(np.ceil(T/CONTROL_DT)))
+ path = hermite(start, speed, goal, velocity, n*CONTROL_DT, n)
+ follow = hermite(goal, velocity, goal + velocity*.125, np.zeros(7), .25, 25)
+ out, prev, clipped = [], start, 0
+ for q in np.concatenate((path, follow)):
+ desired = np.clip(q, low+1e-4, high-1e-4)
+ q = prev + np.clip(desired-prev, -VEL_LIMIT*CONTROL_DT*.999, VEL_LIMIT*CONTROL_DT*.999)
+ clipped += int(np.max(np.abs(q-desired)) > 1e-8)
+ out.append(q); prev = q
+ return out, dict(contact_steps=n, joint_limited_steps=clipped,
+ contact_joint_error=float(np.max(np.abs(out[n-1]-goal))))
+
+
+def main(kind, side):
+ affinity(f'DUEL_{kind.upper()}_{side}_CPUS')
+ import duel
+ if kind == 'plan':
+ obj = duel.Planner(side)
+ elif kind == 'render':
+ obj = duel.Duel()
+ obj.render_views(side) # create Mesa/LLVM threads before the ready handshake
+ else:
+ raise ValueError(kind)
+ affinity(f'DUEL_{kind.upper()}_{side}_CPUS', all_threads=True)
+ proto = os.fdopen(os.dup(1), 'wb')
+ os.dup2(2, 1); sys.stdout = sys.stderr
+ conn = _Conn(sys.stdin.buffer, proto)
+ conn.send('ready')
+ while True:
+ try: job = conn.recv()
+ except EOFError: return
+ try:
+ t0 = time.monotonic()
+ affinity(f'DUEL_{kind.upper()}_{side}_CPUS', all_threads=True)
+ if kind == 'plan':
+ out = prepare(obj, job)
+ else:
+ obj.hist.clear(); obj.hist.extend(job['snapshots'])
+ obj.rs.update(job['rs'])
+ out = dict(png=obj.render_views(side))
+ out['worker_s'] = time.monotonic()-t0
+ conn.send((True, out))
+ except Exception as exc:
+ conn.send((False, repr(exc)))
+
+
+if __name__ == '__main__':
+ main(*sys.argv[1:])
diff --git a/scripts/roboolympics/shared/sports/tabletennis/sport.toml b/scripts/roboolympics/shared/sports/tabletennis/sport.toml
new file mode 100644
index 0000000000..85aa5d580e
--- /dev/null
+++ b/scripts/roboolympics/shared/sports/tabletennis/sport.toml
@@ -0,0 +1,228 @@
+# tabletennis: robot table tennis, real time (docs/framework_zh.md §4.2, §8). Migrated from the legacy tree in stage 2
+# (scripts/olympiad/tabletennis, scripts/olympiad/shared/tabletennis): the simulator (sim/: the physics, the referee,
+# the scripted opponent, the stroke planner, the arm command layer, the duel) is unchanged, so the legacy recordings
+# replay bit-exactly (golden/convert.py). The declarations below are data: the core, tools/generate.py, tools/check
+# and the prompt read them.
+
+[sport]
+name = "tabletennis"
+title = "Table tennis"
+summary = "robot table tennis in a continuous world slowed by a factor S (MuJoCo Franka Panda + paddle, DeepMind ball and table model, recorded real serves), seen only through two cameras of four frames each; one game to 5 points (lead by 2 from 4:4, at 6:6 the next point wins); format match: you against a scripted opponent (level 1-4) that serves every point, format duel: two players and a neutral serve machine, the receiver changing every point"
+protocol = "realtime"
+revision = "wallclock-6+duel-wallclock-4+core-0.2" # bump on any change that alters play (sim/, the rules, the observation)
+physics = "mujoco"
+image = "ghcr.io/mll-lab-nu/eai-olympiad:0.1.0"
+status = "sport"
+publish = true
+category = "robotics-sports-arena"
+
+[rulebook]
+name = "ITTF Laws of Table Tennis (ITTF Statutes 2025, chapter 2)"
+version = "2025 (effective 1 January 2025)"
+url = "https://db.ittf.com/sites/default/files/public/2025-02/ITTF_Statutes_2025_tracked_changes_version.pdf"
+
+[[deviations]]
+id = "D1"
+rule = "ITTF 2.11, 2.12"
+text = "one game to 5 points (from 4:4 a lead of 2 is needed, at 6:6 the next point wins: 7 points at most) instead of a best-of-games match with games to 11"
+affects_result = true
+[[deviations]]
+id = "D2"
+rule = "ITTF 2.6, 2.13"
+text = "the robots cannot toss the ball: format match - the opponent serves every point with recorded real serves and you always receive; format duel - a neutral machine serves recorded real serves and the receiver changes every point (as under the expedite system, 2.13.3, 2.15.3)"
+affects_result = true
+[[deviations]]
+id = "D3"
+rule = "ITTF 2.5.7"
+text = "only the blade can strike the ball: the ball touching the handle or arm loses the point"
+affects_result = true
+[[deviations]]
+id = "D4"
+rule = "ITTF 2.10.1.9-2.10.1.11"
+text = "a robot has no free hand: any contact of the arm or paddle with the table, net or floor loses the point"
+affects_result = true
+[[deviations]]
+id = "D5"
+rule = "ITTF 2.10.1.7"
+text = "any double hit loses the point, deliberate or not"
+affects_result = true
+[[deviations]]
+id = "D6"
+rule = "ITTF 2.15.4"
+text = "the expedite rule applies from the first point: the receiver's 13th good return in a rally wins it the point (this bounds every rally)"
+affects_result = true
+[[deviations]]
+id = "D7"
+rule = "ITTF 2.9.1.1 (let)"
+text = "a serve that touches the net or is irregular is a let; duel: faults by both players at the same instant are a let; the robot that is not receiving is transparent to the serve until it bounces on the receiver's half (the recorded serves were made for an empty serving end)"
+affects_result = true
+[[deviations]]
+id = "D8"
+rule = "- (cost limit, not from the rulebook)"
+text = "if 40 points (lets included) are played the game ends: the player ahead wins; at a level score the player who won the last point (never reached in practice)"
+affects_result = true
+
+[formats.match] # one model seat against the scripted opponent inside the world (match.Match)
+seats = ["A"]
+opponent = true # success = winning a valid match (core/grading.py), as in the legacy task
+levels = [1, 2, 3, 4] # the opponent level (RCB_LEVEL; default 1)
+[formats.duel]
+seats = ["A", "B"]
+first = ["A", "B"] # the first receiver (FIRST_PLAYER); the runner plays both orders
+
+[modes]
+action_levels = ["high", "low"] # high: the paddle state at contact (the stroke planner); low: joint targets
+plays = ["program", "direct"]
+
+[timing]
+slowdown = 20 # the legacy default (RCB_SLOWDOWN); the direct tasks: [[tasks]] slowdown = 50
+start_timeout_s = 1800 # duel: up to 30 minutes to start after the first player
+ready_timeout_s = 300 # each review (after every point), else the side loses
+
+[actions.cli] # the `game` shortcuts per action level (anything else: game act JSON)
+high = { none = [] }
+low = { hold = [] }
+
+[seat] # every task's player image (the legacy tasks' OpenCV)
+pip = ["opencv-python-headless==5.0.0.93"]
+[seat.low] # the low action level's information boundary: the robot's own model + MuJoCo
+files = { "/opt/robot/robot_only.xml" = "seat/robot_only.xml", "/opt/robot/assets" = "sim/scene/assets" }
+pip = ["mujoco==3.3.7", "absl-py==2.5.0", "etils==1.14.0", "fsspec==2026.9.0", "glfw==2.10.2", "PyOpenGL==3.1.10",
+ "typing_extensions==4.16.0", "zipp==4.1.0"] # = the sim image's MuJoCo and its closure (tests check the pin)
+run = ["python -c \"import mujoco; m = mujoco.MjModel.from_xml_path('/opt/robot/robot_only.xml'); assert (m.nbody, m.njnt, m.nu) == (10, 7, 7)\""]
+note = "Your robot's own model is /opt/robot/robot_only.xml (MJCF: the arm and paddle only, nothing of the world; meshes in /opt/robot/assets), with MuJoCo at the simulator's version"
+
+[actions.direct] # direct play: the commands of the `game` MCP tool (players/nocode/game_mcp.py)
+high = [["game act T PX PY PZ NX NY NZ VX VY VZ", "POST /act {\"type\":\"act\",\"t\":T,\"pos\":[PX,PY,PZ],\"normal\":[NX,NY,NZ],\"vel\":[VX,VY,VZ]}", "a paddle command: the blade's state at contact, T s after the command takes effect"],
+ ["game act none", "POST /act {\"type\":\"none\"}", "cancel; the arm returns to its ready pose"]]
+
+[observation]
+fields = ["point", "score", "ball", "t_since_played", "serve_in_s", "ball_in_play", "ball_state", "you_receive_serves",
+ "q", "paddle_pos", "paddle_normal", "command", "qd", "q_target", "points", "shots", "heard"]
+renderer = "mujoco" # the sport draws its own images (camera_job: a 4-frame history); see README
+frame_budget_ms = 1500 # the legacy images (8 tiles 480 x 360, MuJoCo osmesa on CPU): about 0.1-0.2 s per tile, ~1.3 s per observation measured under host load (tiles cached between observations, same pixels)
+columns = 4
+# Since wallclock-6 / duel-wallclock-4 the arms are drawn with the Franka Panda's visual meshes (presentation/
+# presentation.toml players = "25k", bundled into the simulator; renderer rule 6). Measured 2026-10-07 (8 new tiles,
+# osmesa, host load 20-50 on 32 cores), median / p95 ms per observation at 2 llvmpipe threads: match scene 88 / 112,
+# 25k meshes 161 / 182, full meshes 387 / 451 (1 thread: 148, 233, 564)
+render_threads = 2 # llvmpipe threads per render process (LP_NUM_THREADS); one render process per seat
+sim_cpus = 6 # the sim container: 2 seats x 2 render threads + the world, the planners and the core
+
+[spec] # the rule constants and conventions (also in /spec and the prompt)
+game_format = "first to 5 points; from 4:4 a lead of 2 is needed; at 6:6 the next point wins (7 at most)"
+rules = "after exactly one bounce on your half, hit the ball once so that it lands on your opponent's half, directly or after touching the net (the upper table edges count, the vertical sides do not); the same holds for your opponent's returns. You lose the point for a volley, a double hit, two bounces, a miss, a ball that lands on your own half or out, the ball touching your arm or handle while it is over or travelling towards your half, or your arm or paddle touching the table, net or floor. A shot that passes a player's half without touching it is out, even if it then hits that player's robot. A serve that touches the net or is irregular is a let. The receiver's 13th good return in a rally wins it the point (expedite rule). At 40 points played (lets included) the player ahead wins, at a level score the player who won the last point"
+opponent = "format match: the opponent serves every point (you always receive) and returns every ball it can reach; higher levels react faster, reach further and play faster, wider balls with more spin (`match.opponent_level` in game spec)"
+duel = "format duel: a neutral machine serves every point (first on the server's half, then on the receiver's); the receiver changes every point, `match.first_receiver` receives the first; both players get this document and see the game in their own frame"
+world = "metres; your frame: x to your right, y towards the opponent, z up; table top z = 0, |x| <= 0.7625, |y| <= 1.37; net at y = 0, top z = 0.1525; your half y < 0; your robot's base at (0, -1.75, 0) facing +y"
+ball = "radius 0.02 m, orange; gravity 9.81 m/s^2; air drag about 0.13 |v| v; spin bends the flight by a few cm; a bounce keeps about 96 % of the vertical and 87 % of the horizontal speed; a ball takes about 0.6-0.9 s from the opponent to you"
+reach = "the blade can meet a ball whose centre is within about 0.85 m of the shoulder (0, -1.75, 0.33) and above z = 0.12"
+blade = "15 x 15 cm; at contact its centre is 2.75 cm from the ball's centre along the face normal; with n the unit face normal the ball leaves with about v_out = v_paddle - 0.96((v_in - v_paddle).n)n + (v_in - v_paddle) - ((v_in - v_paddle).n)n"
+observation = "observe: one PNG of 2 rows (camera behind your robot, camera at the side) x 4 columns (frames 40 ms apart, newest right) of 480 x 360 tiles, with each frame's control step (observation.view_steps); no ball coordinates; yellow marks every 0.25 m along the table edges; cameras' poses and intrinsics in game spec (pinhole, 45 degree vertical field of view, focal length 434.6 px, principal point at the tile centre)"
+action_high = "high action level: act {type: act, t, pos, normal, vel} = the blade's state at contact t seconds after the command takes effect (centre pos, face normal pointing at the opponent, velocity m/s); limits 0 < t <= 2.5, |x| <= 1.2, -2.5 <= y <= -0.5, 0 <= z <= 1.2, speed <= 8 m/s; it replaces the stroke under way; the service plans the swing (IK, joint speed limits) and the reply predicts how close the arm gets; the delivered state scatters by about 4 mm, 0.6 degrees and 2 %; {type: none} returns the arm to its ready pose"
+action_low = "low action level: joint position targets at 100 Hz, no IK or stroke planner: traj {k0, q: rows of 7 targets} (row i = control step k0 + i, <= 300 rows, consecutive rows within the per-step speed limit, the first row used within that limit of the target in force), slew {q, speed} (every joint towards q at speed x its limit), hold; game spec gives the kinematic chain, limits, the joint controller and the robot's own model (robot_model.robot_only_xml)"
+real_time = "the world runs on its own clock at 1/S of real speed (S = timing.slowdown in game spec); it never waits for you; an act takes effect at the next 10 ms control step after it arrives (the reply's took_effect); one act and one observation per seat in flight; after each point the world freezes until every player has sent game ready WHY PLAN"
+scatter_and_seed = "the serves, the opponent's returns and the execution scatter are drawn from the seed (RCB_SEED / DUEL_SEED)"
+
+[tiebreaks]
+order = ["game"]
+text = "the first player to 5 points with a lead of 2, or the first to 7, wins the game (the match); a let scores no point; if 40 points (lets included) are played, the player ahead wins and at a level score the player who won the last point (last resort, not from the rulebook)"
+last_resort_in_prompt = true
+
+[[exploits]]
+id = "E1"
+text = "an out-of-range, non-finite, too fast or malformed command is refused (HTTP 400) and changes nothing"
+test = "test_exploit_bad_commands_are_refused"
+[[exploits]]
+id = "E2"
+text = "a trajectory whose first row jumps beyond the joint speed limit from the target in force is rejected; the previous command goes on and the simulator never sees the jump"
+test = "test_exploit_discontinuous_start_is_rejected"
+[[exploits]]
+id = "E3"
+text = "the observation holds no ball, opponent or seed state (only the cameras show the ball); /spec holds no seed"
+test = "test_exploit_no_hidden_state"
+[[exploits]]
+id = "E4"
+text = "a player that never moves loses every point (stalling gains nothing)"
+test = "test_exploit_never_moving_loses"
+[[exploits]]
+id = "E5"
+text = "the high action level is the legacy service's planner: the same acts give the same joint targets (no hidden advantage or handicap from the migration)"
+test = "test_exploit_high_level_equals_legacy_planner"
+[[exploits]]
+id = "E6"
+text = "the robot's own model and kinematic chain given at the low level reproduce the simulator's arm and hold nothing of the world"
+test = "test_exploit_robot_model_is_the_simulator_arm"
+[[exploits]]
+id = "E7"
+text = "direct play: a program, a pipe or any tool call other than a literal game command or opening a camera image forfeits the match (players/nocode audit, core grading)"
+test = "test_exploit_nocode_audit_forfeits"
+
+[players]
+reference = "reference" # Sport.players() names: camera-only, wins the default configuration
+reference_class = "builtin_players:Reference"
+check = ["idle"] # the generic tests' check policy (never acts: every point ends quickly)
+
+[fairness]
+policy = "reference" # the camera-only reference on both seats (high level), seeds 1..N, both first receivers
+matches_per_order = 20 # the contract minimum: N = 40 (95% CI about +-15 pp; realtime: a wide CI only warns); an in-process duel takes 15-20 min on the shared host
+max_advantage_pp = 5
+mirror = "statistical" # seat B is the mirrored world: floating-point physics is not bit-symmetric
+
+[official] # grade.py computes official_config with the legacy per-format rule (README)
+seeds = [1, 2, 3, 101, 111, 121, 202, 212, 222, 303, 313, 323, 404, 414, 424]
+levels = [1, 2, 3, 4]
+slowdowns = { program = [1, 2, 5, 10, 20], direct = [20, 50, 100] }
+first_any = true
+
+[golden]
+episodes = "golden" # + the legacy records of the golden-data store, converted by golden/convert.py
+
+[[tasks]]
+id = "tabletennis-match-wallclock-program-standard" # the Season-1 task name
+format = "match"
+action_level = "high"
+play = "program"
+[[tasks]]
+id = "tabletennis-match-wallclock-program-lowlevel-standard" # the Season-1 task name
+format = "match"
+action_level = "low"
+play = "program"
+[[tasks]]
+id = "tabletennis-match-wallclock-direct-standard" # the Season-1 task name
+format = "match"
+action_level = "high"
+play = "direct"
+slowdown = 50 # the legacy direct default (a model call per act); agent budget 10800 s
+[[tasks]]
+id = "tabletennis-duel-wallclock-program-standard" # the Season-1 task name
+format = "duel"
+action_level = "high"
+play = "program"
+[[tasks]]
+id = "tabletennis-duel-wallclock-program-lowlevel-standard" # the Season-1 task name
+format = "duel"
+action_level = "low"
+play = "program"
+[[tasks]]
+id = "tabletennis-duel-wallclock-direct-standard" # the Season-1 task name
+format = "duel"
+action_level = "high"
+play = "direct"
+slowdown = 50
+
+[broadcast] # spectators: the replay video's camera (the whole table from the side, above)
+camera = { name = "broadcast", pos = [4.4, 0.0, 2.2], lookat = [0.0, 0.0, 0.2], fovy_deg = 50, width = 640, height = 360 }
+
+[capabilities] # docs/capabilities_zh.md §6
+a1 = 2 # 3D: the ball only from two cameras (triangulation, the contact point)
+a2 = 2 # dynamics: drag, spin, bounce, the contact law
+a3 = 2 # embodiment: the paddle state (high) or joint targets with its own IK (low)
+a4 = 2 # real time: the world never waits; latency costs game time
+b1 = 1 # rules: the ITTF point rules
+b2 = 2 # strategy: placement away from the opponent, reading its returns
+b3 = 0
+physics = ["spin_bounce"]
+
+[check]
+stage_timeout_s = 10800 # stage 2 (~20 in-process matches) took ~75 min on a loaded shared host (4238 s on main without fine meshes)
diff --git a/scripts/roboolympics/shared/tests/grade.py b/scripts/roboolympics/shared/tests/grade.py
new file mode 100644
index 0000000000..32f4465282
--- /dev/null
+++ b/scripts/roboolympics/shared/tests/grade.py
@@ -0,0 +1,93 @@
+"""Standard-realtime verifier (eai-standard/2.3) for RoboOlympics: grades what the sim service -- which the agent could
+not touch -- wrote.
+
+/data/final.json holds the live match's outcome and the verdict of a fresh-process replay of its record:
+success = live_success (the match finished and the agent won it) AND replay_success (the replay's match too) AND
+deterministic (the replay ends in the live run's state). /data/match.json (the replay's summary: the score, the breaks,
+the commands) only adds information to reward.json; it never decides the verdict.
+Writes /logs/verifier/reward.txt (1/0) and a numeric-only reward.json, and copies the evidence (replay video, last
+frame, the replay's summary, event log) next to them for humans.
+infra_error = 1: no verdict on the agent (the service crashed past its restarts, failed to resume, ended on a simulator
+error, never finished, or failed to finalize; PROTOCOL §4b).
+"""
+import json
+import math
+import os
+import shutil
+import traceback
+
+DATA = os.environ.get("RCB_DATA", "/data")
+LOG = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")
+os.makedirs(LOG, exist_ok=True)
+
+
+def write(ok: bool, out: dict) -> None:
+ with open(os.path.join(LOG, "reward.txt"), "w") as f:
+ f.write("1\n" if ok else "0\n")
+ with open(os.path.join(LOG, "reward.json"), "w") as f:
+ json.dump(out, f)
+ print(json.dumps(out))
+
+
+def num(x, default=0.0) -> float:
+ try:
+ x = float(x)
+ except (TypeError, ValueError):
+ return default
+ return x if math.isfinite(x) else default
+
+
+def match_fields() -> dict:
+ """Information from the replay's summary (numbers only); {} if there is none."""
+ try:
+ with open(os.path.join(DATA, "match.json")) as f:
+ m = json.load(f)
+ except (OSError, ValueError):
+ return {}
+ return {"match_finished": int(bool(m.get("finished"))), "match_won": int(bool(m.get("won"))),
+ "points_for": num(m.get("points_for")), "points_against": num(m.get("points_against")),
+ "match_steps": int(num(m.get("match_steps"))), "breaks": len(m.get("breaks") or []),
+ "breaks_ended_by_ready": sum(1 for b in m.get("breaks") or [] if b.get("by") == "ready"),
+ "commands_applied": int(num(m.get("commands_applied"))),
+ "commands_refused": int(num(m.get("commands_refused")))}
+
+
+def main() -> None:
+ path = os.path.join(DATA, "final.json")
+ if not os.path.exists(path):
+ write(False, {"success": 0, "missing_log": 1, "infra_error": 1, "grader_error": 0})
+ return
+ try:
+ with open(path) as f:
+ d = json.load(f)
+ live, replay, det = (bool(d.get(k)) for k in ("live_success", "replay_success", "deterministic"))
+ failed_finalize = bool(d.get("finalize_error"))
+ unfinished = not d.get("finalized")
+ sim_error = d.get("reason") == "error"
+ infra = bool(d.get("infra_error")) or failed_finalize or unfinished or sim_error
+ ok = live and replay and det and not infra
+ out = {"success": int(ok), "live_success": int(live), "replay_success": int(replay), "deterministic": int(det),
+ "finalized": int(not unfinished), "missing_log": 0, "infra_error": int(infra),
+ "sim_error": int(sim_error), "grader_error": int(failed_finalize),
+ "timeout": int(d.get("reason") == "timeout"),
+ "n_actions": int(num(d.get("n_actions"))), "control_steps": int(num(d.get("control_steps_total"))),
+ "calls": int(num(d.get("calls"))), "rows": int(num(d.get("rows"))),
+ "reset_budget": int(num(d.get("reset_budget"))), "slowdown": num(d.get("slowdown")),
+ "max_lag_s": num(d.get("max_lag_s")), "stalls": int(num(d.get("stalls"))),
+ "late_steps": int(num(d.get("late_steps"))), "sim_startups": int(num(d.get("sim_startups"))),
+ "elapsed_s": num(d.get("elapsed_s")), "video_rendered": int(bool(d.get("video"))), **match_fields()}
+ except Exception: # noqa: BLE001 -- an unreadable final.json is the grader's failure, not the agent's
+ traceback.print_exc()
+ write(False, {"success": 0, "missing_log": 0, "infra_error": 1, "grader_error": 1})
+ return
+ for name in ("replay.mp4", "replay.last.png", "match.json", "episode.jsonl"):
+ try:
+ if os.path.exists(os.path.join(DATA, name)):
+ shutil.copy(os.path.join(DATA, name), os.path.join(LOG, name))
+ except OSError:
+ traceback.print_exc()
+ write(ok, out)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/roboolympics/sports.toml b/scripts/roboolympics/sports.toml
new file mode 100644
index 0000000000..622cfb6a76
--- /dev/null
+++ b/scripts/roboolympics/sports.toml
@@ -0,0 +1,98 @@
+# What gen_tasks.py writes about each sport into its tasks (instruction.md, README.md, /spec's task text). The
+# authoritative interface is the sim service's /spec (shared/sim/rcb_olympics.py: action_types, proprio_layout,
+# cameras, rules): these texts describe it, tests/test_adapter.py checks that the columns and types named here are the
+# service's. The rules themselves come from the sport's sport.toml ([spec], [[deviations]], [tiebreaks]).
+
+[tabletennis]
+title = "Table tennis"
+task_text = "Win a game of table tennis against the scripted opponent: return its serves and shots onto its half."
+episode_text = "Ends when the game is decided (first to 5 points, from 4:4 a lead of 2, at most 7; success: you won), when your time is up (timeout), or on a simulator error."
+intro = """You play robot table tennis (ITTF rules with the deviations below) against a scripted opponent: a MuJoCo Franka
+Panda holding a paddle, at your end of a real-size table, seen only through two cameras. The opponent serves every
+point (recorded real serves) and returns every ball it can reach; you always receive. One game to 5 points."""
+unit = "point"
+robot = "Franka Panda (MuJoCo Menagerie panda_nohand) holding a 15 x 15 cm paddle; its base at (0, -1.75, 0) facing +y"
+actions = """| type | row | what it does |
+|---|---|---|
+| `stroke` | `[t, x, y, z, nx, ny, nz, vx, vy, vz]` | the blade's state at contact, `t` seconds after the command takes effect: centre `x y z` (m), face normal `nx ny nz` (pointing where the ball should go), velocity `vx vy vz` (m/s). The service plans the swing (IK, joint speed limits, rehearsals on its own copy of the arm) from the arm's state at that step, then the arm returns to its ready pose. A new stroke replaces the one under way. Limits: 0 < t <= 2.5, \\|x\\| <= 1.2, -2.5 <= y <= -0.5, 0 <= z <= 1.2, speed <= 8 m/s (clipped, `meta["clipped"]`). The delivered state scatters by about 4 mm, 0.6 degrees and 2 % (from the task's frozen seed) |
+| `rest` | `[0]` | cancel the stroke under way: the arm returns to its ready pose |
+| `ready` | `[0]` | end the break now (see Time) |"""
+proprio = """`match_step`, `break`, `break_left_s`, `finished`; `score_you`, `score_opponent`, `point` (the point being
+played, from 1); the current ball: `ball_is_serve` (1: the opponent's serve, 0: its return), `t_since_played` (seconds
+since the opponent served or hit it; negative while a serve waits), `serve_in_s`, `ball_in_play`, `ball_coming` (coming
+to you), `ball_going` (going to the opponent); what you heard of the current ball, as the time on its clock
+(`t_since_played`) of the first event of each kind, NaN if not heard yet: `heard_opp_bounce_t` (a bounce on the
+opponent's half), `heard_own_bounce_t` (a bounce on your half), `heard_net_t`, `heard_paddle_t` (your paddle),
+`heard_robot_t` (your arm), `heard_floor_t`; your arm: `q1`..`q7` (joint angles, rad), `paddle_x/y/z` (blade centre),
+`paddle_nx/ny/nz` (face normal); the stroke under way: `stroke_active`, `stroke_contact_in_s`, and how well the planner
+can deliver it: `stroke_speed_scale` (> 1: the paddle speed was cut by the joint speed limits), `stroke_blade_error_m`,
+`stroke_normal_error_deg`, `stroke_ik_residual`; `last_point_won` (1 you, -1 the opponent, 0 a let);
+`commands_applied`, `commands_refused`, `last_refused_step`."""
+cameras = """two cameras, 480 x 360 RGB each: `behind` (behind and above your robot, looking down the table) and `side` (at
+the side of the table, looking along +x: your robot is on the right). Pose (`position`, `forward`, `up`), field of view
+(45 degrees vertical), `focal_px` (434.6) and `principal_point_px` in `spec()["cameras"]`; pinhole: u = cx + f x_right /
+depth, v = cy - f y_up / depth. The ball is orange, the opponent is the red paddle; yellow marks every 0.25 m along the
+table edges. Each image is stamped with the match step `k` and the current ball's clock `t`."""
+tip = """A ball takes about 0.6-0.9 s of game time from the opponent to you (6-9 s of wall time at S = 10). Three or more
+frames of the ball (`get_obs(seconds=0.12, video_fps=25, video="frames")` returns four, 40 ms apart, with one proprio
+row each) let you triangulate it with the two cameras and fit its flight."""
+
+[badminton]
+title = "Badminton"
+task_text = "Win a game of singles badminton against the scripted opponent: serve, and return its shots into its court."
+episode_text = "Ends when the game is decided (first to 5 points, from 4-4 by 2, at most 7; or a player disqualified; success: you won), when your time is up (timeout), or on a simulator error."
+intro = """You play robot singles badminton (BWF rules with the deviations below) against a scripted opponent: a MuJoCo
+Franka Panda on a 1 m pedestal whose base slides on rails, holding a racket, seen only through two cameras. Rally
+scoring; you serve the first point, then the winner of each rally serves. One game to 5 points."""
+unit = "point"
+robot = "Franka Panda on a 1.0 m pedestal whose base slides on x-y rails, holding a badminton racket"
+actions = """| type | row | what it does |
+|---|---|---|
+| `stroke` | `[t, x, y, z, nx, ny, nz, vx, vy, vz]` | the racket head's state at contact, `t` seconds after the command takes effect: head centre `x y z` (m), string-face normal `nx ny nz`, head velocity `vx vy vz` (m/s). It takes effect `spec()["rules"]["act"]["lead_steps"]` control steps after its row's step (4 at S = 10: the planning time; `stroke_pending_effect_step` shows it) and `t` counts from then; the service plans the swing and the base's move, then the robot returns to its ready pose and the base home. A stroke, toss or rest planned before the previous one took effect is refused. Limits: 0 < t <= 5, \\|x\\| <= 3.4, -7.5 <= y <= -0.3, 0.2 <= z <= 3.0, speed <= 8 m/s (clipped) |
+| `toss` | `[x, y, z, height]` | your serve's toss: the shuttle appears at `x y z` (your half, y <= -0.5, 0.5-1.8 m high, within 1.0 m of your base horizontally) when the command takes effect (the same lead), from rest or rising `height` (0-0.5 m) straight up. Only the server, once per serve, once the receiver is ready (`serve_phase` 1, open). Then hit it with a stroke (it may be sent before the toss); the serve rules are in `spec()["rules"]["serve"]` |
+| `rest` | `[0]` | cancel the stroke under way (the same lead) |
+| `ready` | `[0]` | end the break now (see Time) |"""
+proprio = """`match_step`, `break`, `break_left_s`, `finished`; `score_you`, `score_opponent`, `point`; the serve:
+`you_serve`, `serve_court_right`, `serve_phase` (0 waiting: the receiver is getting ready, 1 open: toss now, 2 tossed,
+3 done), `serve_opens_in_s`, `serve_deadline_in_s` (toss before it: an undue delay is a fault), `serve_tossed_at_step`;
+the shuttle: `ball_kind` (0 the opponent's serve, 1 your serve, 2 the opponent's return), `t_since_played` (seconds
+since it was played: served, tossed or hit; NaN before), `ball_in_play`, `ball_not_served`, `ball_tossed` (yours to
+hit), `ball_coming`, `ball_going`; your robot: `base_x`, `base_y`, `q1`..`q7`, `racket_x/y/z`, `racket_nx/ny/nz`; the
+stroke under way: `stroke_active`, `stroke_contact_in_s`, `stroke_traj_steps_left`, `stroke_pending_effect_step` (a
+stroke, toss or rest waiting for its effect step, NaN if none), `stroke_head_speed_limited`,
+`stroke_pose_not_delivered` (the planner's notes); `last_point_won`; `commands_applied`, `commands_refused`,
+`last_refused_step`."""
+cameras = """two cameras, 480 x 360 RGB each: `behind` (behind and above your base line, looking down the court) and `side`
+(at the side of the court, x < 0, looking along +x: your half is on the right). Pose, field of view (45 degrees),
+`focal_px` and `principal_point_px` in `spec()["cameras"]`. The shuttle is drawn enlarged: an orange cork (a 12 cm
+ball centred on its position) with a white skirt behind it; yellow marks every 1 m outside the singles side lines and
+behind the base lines. Each image is stamped with the match step `k` and the shuttle's clock `t`."""
+tip = """Four frames 60 ms apart (`get_obs(seconds=0.18, video_fps=17, video="frames")`) with the two cameras let you
+triangulate the shuttle and fit its flight (gravity and quadratic drag, `spec()["rules"]["shuttle"]`)."""
+
+[airhockey]
+title = "Air hockey"
+task_text = "Win a game of air hockey against the scripted opponent: score goals into its goal and defend yours."
+episode_text = "Ends when the game is decided (the first to 7 goals; at the safety cap of 120 s of play or 40 rallies the tiebreaks; success: you won), when your time is up (timeout), or on a simulator error."
+intro = """You play robot air hockey (USAA rules with the deviations below) against a scripted opponent: a MuJoCo KUKA
+iiwa 14 arm holding a mallet at your end of the table (x < 0), seen only through one fixed camera. A rally starts with
+the puck at rest in one player's half; a goal, a seven-second foul or a dead puck ends it. The first to 7 goals wins."""
+unit = "rally"
+robot = "KUKA LBR iiwa 14 holding a mallet (the striker on two passive joints), its base at (-1.51, 0) beside your end"
+actions = """| type | row | what it does |
+|---|---|---|
+| `mallet` | `[x, y]` | the mallet centre's target (m, table frame): the robot drives the mallet there along a speed- and acceleration-limited path (`spec()["rules"]["mallet_path"]`) and holds it until replaced. Own half only: a target outside the workspace (`spec()["rules"]["workspace"]`: 0.05 <= -x <= 0.92, \\|y\\| <= 0.47, at most 1.45 m from your base) is moved to its nearest point (`meta["clipped"]`). Rows may be a chunk `dt` apart with `interpolate="linear"`; a row equal to the target in force changes nothing |
+| `stop` | `[0]` | the mallet stops where it is (its target becomes its position) |
+| `ready` | `[0]` | end the break now (see Time) |"""
+proprio = """`match_step`, `break`, `break_left_s`, `finished`; `score_you`, `score_opponent`, `rally` (the rally being
+played, from 1), `t_play` (seconds of play; breaks do not count), `play_time_left_s` (to the 120 s cap); your mallet:
+`mallet_x/y/z` (its centre), `target_x/y` (the target in force); your arm: `q1`..`q7`, `q_striker1/2` and their
+velocities `qd1`..`qd7`, `qd_striker1/2`; the last rally: `last_rally_how` (1 goal, 2 seven-second foul, 3 dead puck,
+4 time cap), `last_rally_scored` (1 you, -1 the opponent, 0 nobody), `last_rally_fouled` (who committed a foul),
+`last_rally_next_puck` (who gets the puck next, 0 a face-off); `commands_applied`, `commands_refused`,
+`last_refused_step`."""
+cameras = """one camera, `front`, 320 x 240 RGB, fixed above and behind your end of the table (pose, field of view 48
+degrees, `focal_px`, `principal_point_px` in `spec()["cameras"]`). The puck is red; the opponent's mallet is at the
+far end."""
+tip = """The puck moves fast: track it over several consecutive images (`get_obs(seconds=0)` in a loop, each with its
+`t_play`) and move the mallet with a program that runs in the background."""
diff --git a/scripts/roboolympics/tasks.toml b/scripts/roboolympics/tasks.toml
new file mode 100644
index 0000000000..1fb0da76b9
--- /dev/null
+++ b/scripts/roboolympics/tasks.toml
@@ -0,0 +1,54 @@
+# RoboOlympics tasks (docs/benchmarks/roboolympics.md): one player against the sport's scripted opponent, standard-realtime
+# mode only (eai-standard/2.3, PROTOCOL §4b), rendered by gen_tasks.py:
+# python3 scripts/roboolympics/gen_tasks.py render write tasks/roboolympics-*
+# python3 scripts/roboolympics/gen_tasks.py check exit 1 if tasks/ differs from a fresh render (CI)
+# The simulator code under shared/ is RoboOlympics' (github.com/CHIGUI0/roboolympics, private; MIT), taken unchanged from
+# its upstream-export commit below, except renderers/presentation/assets.py (RO_LOD_DIR: the players' meshes come from
+# the eai-olympiad image). The instance is frozen: seed, opponent level and the official slowdown S = 10.
+# sport, source the RoboOlympics sport and the task it was exported from (sport.toml [[tasks]])
+# name roboolympics-<sport>-<format>-i<NN>-standard-realtime (docs/TAXONOMY.md)
+# format the sport's single-player format; action_level: high (strokes the service plans) or low
+# seed, level the frozen instance: the serves, the opponent's returns and the execution scatter; the opponent
+
+[defaults]
+upstream = "CHIGUI0/roboolympics 596d551a862c4236e74aea2beb25654b9783f9a7 (branch upstream-export, core 0.2.13)"
+image = "ghcr.io/mll-lab-nu/eai-olympiad:0.2.0"
+agent_timeout_sec = 7200 # uniform in the benchmark: a match plus its breaks takes 10-60 min of wall time at S = 10
+slowdown = 10 # RoboOlympics' official slowdown (owner, 2026-10-08; PROTOCOL §4b exception)
+instance_tag = "00"
+
+[[tasks]]
+sport = "tabletennis"
+source = "tabletennis-match-wallclock-program-standard"
+name = "roboolympics-tabletennis-match-i00-standard-realtime"
+family = "tabletennis_match"
+robot = "franka-panda"
+format = "match"
+action_level = "high"
+seed = 101
+level = 1
+sim_cpus = 6
+
+[[tasks]]
+sport = "badminton"
+source = "badminton-match-wallclock-program-standard"
+name = "roboolympics-badminton-match-i00-standard-realtime"
+family = "badminton_match"
+robot = "franka-panda"
+format = "match-wallclock"
+action_level = "high"
+seed = 101
+level = 1
+sim_cpus = 6
+
+[[tasks]]
+sport = "airhockey"
+source = "airhockey-match-wallclock-program-standard"
+name = "roboolympics-airhockey-match-i00-standard-realtime"
+family = "airhockey_match"
+robot = "kuka-iiwa14"
+format = "match"
+action_level = "low"
+seed = 101
+level = 1
+sim_cpus = 4
diff --git a/scripts/roboolympics/templates/Dockerfile b/scripts/roboolympics/templates/Dockerfile
new file mode 100644
index 0000000000..61e548780b
--- /dev/null
+++ b/scripts/roboolympics/templates/Dockerfile
@@ -0,0 +1,10 @@
+# Standard-realtime mode: the agent container has no simulator and no RoboOlympics code -- only Python, the client and
+# OpenCV (RoboOlympics' player image).
+FROM {{client_image}}
+COPY client-requirements.txt /tmp/
+RUN pip install --no-cache-dir -r /tmp/client-requirements.txt
+RUN pip install --no-cache-dir -c /tmp/client-requirements.txt opencv-python-headless==5.0.0.93 && pip check
+COPY rcb_client.py rcb1.py /opt/tools/
+ENV PYTHONPATH=/opt/tools
+RUN mkdir -p /app/output
+WORKDIR /app
diff --git a/scripts/roboolympics/templates/README.md b/scripts/roboolympics/templates/README.md
new file mode 100644
index 0000000000..d61c78588c
--- /dev/null
+++ b/scripts/roboolympics/templates/README.md
@@ -0,0 +1,44 @@
+# {{name}}
+
+RoboOlympics {{title_lower}} (`{{source}}`), one match against the scripted opponent (level {{level}}, frozen seed
+{{seed}}), in standard-realtime mode (`eai-standard/2.3`, PROTOCOL §4b): the robot as a service on a clock that does
+not stop. The sport runs in the `sim` sidecar (`environment/docker-compose.yaml`; `environment/sim/rcb_realtime.py`
+runs the clock, `environment/sim/rcb_olympics.py` is the RoboOlympics adapter, `environment/sim/sport/` the sport's
+simulator, referee and opponent), which records every command at the control step it took effect, replays the match in
+a fresh process and renders the replay video; the verifier grades the sidecar's record in a container of its own
+(`tests/Dockerfile`, no network).
+
+| | |
+|---|---|
+| sport | {{intro_line}} |
+| time | S = {{slowdown}} (RoboOlympics' official slowdown; `RCB_SLOWDOWN` overrides it, results under another S are reported separately): one 10 ms control step every {{wall_s_per_step}} s of wall time; the match starts paused and its clock starts at the first `submit` or `get_obs(seconds > 0)`; after every {{unit}} a break of {{break_s}} s of game time ({{break_wall_s}} s of wall time) in which the clock runs on and nothing plays, ended early by the agent's `ready` row |
+| actions | {{action_list}}: the sport's own commands (action level `{{action_level}}`), one per row, effective at the row's control step |
+| observation | camera images and the agent's own robot plus the referee's information as proprio columns; no ball or opponent state, no seed |
+| budget | {{agent_timeout_sec}} s, no reset (one match is the episode), no privileged twin (PROTOCOL §4b exceptions, `docs/benchmarks/roboolympics.md`) |
+| agent API | `environment/rcb_client.py` (the realtime client); `instruction.md` documents the commands, the proprio columns and the cameras |
+
+## Difficulty
+The agent sees the game only through cameras and has no simulator of its own. A {{unit}} is decided in a few seconds of
+game time, faster than a model's turn even at S = {{slowdown}}, so the agent has to write a perception and control
+program (find the {{ball}} in the images, fit its flight, choose and time the command) that plays by itself, and
+improve it between {{unit}}s and during the match. The opponent returns every ball it can reach; level {{level}} of
+the sport's levels.
+
+## Reference solution
+`solution/oracle_play.py` runs the sport's RoboOlympics reference player (`solution/builtin_players.py`: camera images,
+the proprio columns and `/spec` only; perception by colour, triangulation, a fitted flight model, the sport's contact
+law) through the agent's own client; it wins this instance (PR #{{review_pr}}).
+
+## Verification
+`success` = live success (the match finished and the agent won it) ∧ replay success ∧ deterministic (the fresh-process
+replay of the recorded commands ends in the live run's state), computed in the sidecar. The record is
+`trajectory_live.f64` (per control step: the id of the command that took effect, -1 for none, and the `ready` flag) with
+`commands.jsonl` (the commands as the sport's action layer lowered them), so the replay re-applies what the live match
+applied, whatever the timing; `ticks.f64`, `calls.jsonl` and `submitted.f64` record the timing and every call, and
+`final.json` the clock's lag (`max_lag_s`, `stalls`). `match.json` is the replay's summary (score, breaks, commands).
+`tests/grade.py` reads `/data/final.json` and copies the evidence to `/logs/verifier/` (`replay.mp4`). A simulator
+crash or error is an infrastructure failure (`infra_error = 1`), not the agent's (PROTOCOL §4b). `nop` scores 0: the
+match never starts.
+
+Generated by `scripts/roboolympics/gen_tasks.py` from `tasks.toml`, `sports.toml`, `templates/` and `shared/` (the
+RoboOlympics simulator code, {{upstream}}); do not edit by hand.
diff --git a/scripts/roboolympics/templates/docker-compose.yaml b/scripts/roboolympics/templates/docker-compose.yaml
new file mode 100644
index 0000000000..b108038f07
--- /dev/null
+++ b/scripts/roboolympics/templates/docker-compose.yaml
@@ -0,0 +1,35 @@
+# Standard-realtime mode (PROTOCOL §4b): RoboOlympics {{title_lower}} runs in the `sim` sidecar (the agent cannot open it), on
+# its own clock once the match starts (sim/rcb_realtime.py, the adapter sim/rcb_olympics.py); the agent only reaches
+# port 8000. No `expose`/`ports` on sim: under Harbor's egress control it shares main's network namespace
+# (localhost:8000). CPU only: MuJoCo physics and OSMesa rendering (the players' meshes come with the image).
+services:
+ main:
+ depends_on: [sim]
+ sim:
+ image: {{image}}
+ volumes:
+ - ./sim:/srv:ro
+ command: python /srv/rcb_realtime.py
+ restart: on-failure:6 # a crash resumes the same match, paused, never a reset
+ cpus: {{sim_cpus}}
+ mem_limit: 8g
+ pids_limit: 256
+ environment:
+ RO_PLUGIN: /srv/sport/plugin.py
+ RO_SPORT: {{sport}}
+ RO_FORMAT: {{format}}
+ RO_SEED: "{{seed}}"
+ RO_LEVEL: "{{level}}"
+ RO_ACTION_LEVEL: {{action_level}}
+ RO_TASK_TEXT: "{{task_text}}"
+ RO_EPISODE_TEXT: "{{episode_text}}"
+ RCB_WALL_CLOCK_S: "{{agent_timeout_sec}}"
+ # Knobs: ${NAME:-default} takes NAME from the shell that runs harbor. The defaults are the official
+ # configuration; results under other settings are reported separately.
+ RCB_SLOWDOWN: "${RCB_SLOWDOWN:-{{slowdown}}}" # {{slowdown}}: RoboOlympics' official slowdown (PROTOCOL §4b exception); results state S
+ RCB_RESET_BUDGET: "${RCB_RESET_BUDGET:-0}" # 0: one match is one episode (PROTOCOL §4b, the mode's default)
+ MUJOCO_GL: osmesa
+ PYOPENGL_PLATFORM: osmesa
+ LP_NUM_THREADS: "2"
+ OMP_NUM_THREADS: "1"
+ OPENBLAS_NUM_THREADS: "1"
diff --git a/scripts/roboolympics/templates/instruction.md b/scripts/roboolympics/templates/instruction.md
new file mode 100644
index 0000000000..b0b1f166c4
--- /dev/null
+++ b/scripts/roboolympics/templates/instruction.md
@@ -0,0 +1,69 @@
+# {{title}}: a match against a scripted opponent, in real time
+
+{{intro}}
+
+**Your goal: win the match.** The task succeeds if the match finishes and you won it. Keep your scripts, logs and notes
+in `/app/output/`; there is nothing else to hand in: the simulator records the match.
+
+## Time does not stop
+- The world runs at 1/{{slowdown}} of real speed (`spec()["timing"]["slowdown"]` = {{slowdown}}): one 10 ms control
+ step of game time every {{wall_s_per_step}} s of wall time. It never waits for you: while you think, the opponent
+ plays on and your robot keeps executing its last command.
+- The match starts paused. Its clock starts at your first `submit` or `get_obs(seconds > 0)`, and from then on it runs
+ until the match is over. Look at the cameras and read `spec()` first (`get_obs(seconds=0)` does not start the clock).
+- **Breaks.** After every {{unit}} the match stands still for {{break_s}} s of game time ({{break_wall_s}} s of wall time):
+ the clock keeps running, nothing moves and nothing scores, and play resumes by itself at the end of the break. Use it
+ to look at what happened and fix your program. Send a `ready` row to resume earlier (put your review, why you won or
+ lost the {{unit}} and what you change, in `submit`'s `note`). Commands planned for steps inside a break are dropped.
+- You have {{agent_timeout_sec}} s in all. **If your session ends before the match is over, you lose** (success 0); so
+ start the match well before your time runs out and stay until it is over (`meta["done"]`).
+- No reset: one match is the whole episode.
+
+## Write a program
+A model response takes seconds, a {{unit}} only a few seconds of game time, so play with a program of your own: it
+observes, measures in the images, computes its next command and submits it, in a loop, without a new model response
+for each action. Run it in the background, watch its log, and stop, fix and restart it whenever needed (also during the
+match). Use only the camera images, the service's replies and this document: no simulator internals or hidden state.
+
+## Interface
+The client is installed: `from rcb_client import Robot, EpisodeOver` (`/opt/tools/rcb_client.py`, on `PYTHONPATH`;
+its docstring is the reference). Your container has Python 3.12 with numpy, SciPy, Pillow, requests and
+opencv-python-headless; no internet except your model's API.
+
+```python
+r = Robot() # connects to the simulator, waits until it is ready
+spec = r.spec() # the facts: action_types, cameras, proprio_layout, rules, break, timing
+res = r.get_obs(seconds=0) # now, at once: res.last[cam] (H x W x 3 uint8), res.proprio (rows)
+res = r.get_obs(seconds=0.12, video_fps=25, video="frames") # watch 0.12 s of game time: res.frames[cam] (N x H x W x 3)
+r.submit("{{first_action}}", [row]) # a command: answers at once; it takes effect at the next control step
+r.submit("ready", [[0]], note="WHY ... PLAN ...") # during a break: resume now
+```
+
+- `get_obs(cameras=None, seconds=0, video_fps=10, video="frames")`: `seconds=0` returns the current images and one
+ proprio row; `seconds > 0` (at most `spec()["max_watch_s"]`) waits while that much game time runs and returns the
+ frames the cameras saw (one every 1/`video_fps` s) and one proprio row per frame. `cameras=[]`: proprio only.
+- `submit(type, rows, at=None, note="")`: one command per row; the rows become the plan from control step `at` (the
+ next step by default; `meta["control_steps"]` is the next step's number), replacing whatever was planned from there.
+ A row takes effect at its step: the command is checked and planned there, from the state of that step. Rows for
+ steps that are already gone when the request arrives are dropped (`meta["late_steps"]`); out-of-range values are
+ clipped (`meta["clipped"]`); a command the rules refuse at its step (e.g. {{refused_example}}) changes nothing and
+ counts in the proprio column `commands_refused`.
+- `res.meta`: `control_steps`, `sim_time_s`, `time_left_s`, `done`, `reason`, `running`, `lag_s`, and `proprio`
+ (`layout`, `now`). `EpisodeOver` is raised once the match is over.
+
+Your commands (`spec()["action_types"]`):
+
+{{actions}}
+
+Proprioception and the referee's information (`spec()["proprio_layout"]`, one float row per frame; NaN = not
+applicable now; times in game seconds, positions in metres in your frame): {{proprio}}
+
+Cameras: {{cameras}}
+
+{{tip}}
+
+## Rules
+{{rules}}
+
+Your robot: {{robot_text}}. Everything else you need (the frame, the geometry and the rule constants) is in
+`spec()["rules"]`; the physics engine is MuJoCo.
diff --git a/scripts/roboolympics/templates/solve.sh b/scripts/roboolympics/templates/solve.sh
new file mode 100644
index 0000000000..a1680309dd
--- /dev/null
+++ b/scripts/roboolympics/templates/solve.sh
@@ -0,0 +1,5 @@
+#!/bin/bash
+# Oracle: the sport's RoboOlympics reference player (camera images, proprio and /spec only) through the agent's client.
+set -e
+mkdir -p /app/output
+cd /solution && python3 oracle_play.py 2>&1 | tee /app/output/oracle.log
diff --git a/scripts/roboolympics/templates/task.toml b/scripts/roboolympics/templates/task.toml
new file mode 100644
index 0000000000..f49a898bfb
--- /dev/null
+++ b/scripts/roboolympics/templates/task.toml
@@ -0,0 +1,74 @@
+# RoboOlympics {{title}} against the scripted opponent, standard-realtime mode (docs/PROTOCOL.md §4b, docs/benchmarks/roboolympics.md).
+# Generated by scripts/roboolympics/gen_tasks.py from tasks.toml, sports.toml and templates/ -- edit those, not this.
+schema_version = "1.3"
+artifacts = [
+ { source = "/data/final.json", service = "sim" },
+ { source = "/data/match.json", service = "sim" },
+ { source = "/data/episode.jsonl", service = "sim" },
+ { source = "/data/trajectory.npz", service = "sim" },
+ { source = "/data/trajectory_live.f64", service = "sim" },
+ { source = "/data/commands.jsonl", service = "sim" },
+ { source = "/data/replay.mp4", service = "sim" },
+ { source = "/data/replay.last.png", service = "sim" },
+ { source = "/data/ticks.f64", service = "sim" },
+ { source = "/data/calls.jsonl", service = "sim" },
+ { source = "/data/submitted.f64", service = "sim" },
+ { source = "/data/startups.jsonl", service = "sim" },
+ "/app/output/",
+]
+
+[task]
+name = "robot-coding-bench/{{name}}"
+description = "STANDARD-REALTIME MODE (robot as a service on a clock that does not stop, eai-standard/2.3): RoboOlympics {{title_lower}}, one match against a scripted opponent (level {{level}}, frozen seed {{seed}}). The world runs at 1/{{slowdown}} of real speed (S = {{slowdown}}, the benchmark's official slowdown) and never waits: the agent sees only camera images and its own robot through the client, and drives the robot with the sport's commands ({{action_list}}) from a program of its own. Between {{unit}}s a break of {{break_s}} s of game time ({{break_wall_s}} s of wall time) in which the clock runs on and nothing plays; no reset, no privileged state. The sim service records every command at the step it took effect, replays the match in a fresh process and grades it: success = a finished match that the agent won."
+authors = [{ name = "RoboOlympics (CHIGUI0)" }]
+keywords = ["robotics", "roboolympics", "sports", "{{sport}}", "mujoco", "standard-realtime-mode", "vision", "real-time"]
+
+[metadata]
+author_name = "RoboOlympics"
+task_type = "trajectory"
+simulator = "mujoco"
+robot = "{{robot}}"
+family = "{{family}}"
+mode = "standard-realtime"
+protocol = "eai-standard/2.3"
+instance_seed = {{seed}}
+opponent_level = {{level}}
+slowdown = {{slowdown}}
+revision = "{{revision}}"
+play = "program"
+action_level = "{{action_level}}"
+source_task = "roboolympics/{{source}}"
+expert_time_estimate_hours = 0.5
+oracle = "full"
+oracle_evidence = "solution/: the sport's RoboOlympics reference player (camera images, proprio and /spec only) through the agent's client; it wins this instance (PR #{{review_pr}})"
+
+[verifier]
+timeout_sec = 900.0
+environment_mode = "separate"
+network_mode = "no-network"
+
+# The agent's time is up: stop whatever it left running in its container (a program would keep playing).
+[[verifier.collect]]
+service = "main"
+command = "kill -9 -1 2>/dev/null; exit 0"
+timeout_sec = 30
+
+# Then the match ends: SIGUSR1 to the service (re-sent every 30 s, in case it was restarting), which replays and grades it.
+[[verifier.collect]]
+service = "sim"
+command = "for i in $(seq 1 90); do [ -f /data/server.pid ] && break; sleep 2; done; for i in $(seq 1 400); do grep -q '\"finalized\": true' /data/final.json 2>/dev/null && break; [ $((i % 15)) -eq 1 ] && kill -USR1 $(cat /data/server.pid) 2>/dev/null; sleep 2; done; cat /data/final.json"
+timeout_sec = 900
+
+[agent]
+timeout_sec = {{agent_timeout_sec}}
+# The agent reaches the model APIs and the sim (localhost:8000, Harbor's egress control) and nothing else.
+network_mode = "allowlist"
+allowed_hosts = {{allowed_hosts}}
+
+[environment]
+build_timeout_sec = 1200.0
+cpus = 2
+memory_mb = 4096
+
+[verifier.environment]
+build_timeout_sec = 600.0
diff --git a/scripts/roboolympics/templates/test.sh b/scripts/roboolympics/templates/test.sh
new file mode 100644
index 0000000000..75622ada21
--- /dev/null
+++ b/scripts/roboolympics/templates/test.sh
@@ -0,0 +1,5 @@
+#!/bin/bash
+# Verifier (separate sandbox): the sim sidecar's artifacts were uploaded to /data by Harbor.
+mkdir -p /logs/verifier
+rm -rf /logs/verifier/*
+python /tests/grade.py 2> /logs/verifier/grade.log
diff --git a/scripts/roboolympics/templates/tests.Dockerfile b/scripts/roboolympics/templates/tests.Dockerfile
new file mode 100644
index 0000000000..b3fcc46c71
--- /dev/null
+++ b/scripts/roboolympics/templates/tests.Dockerfile
@@ -0,0 +1,4 @@
+# Separate verifier sandbox: grades the sim service's own artifacts; needs nothing but Python.
+FROM {{client_image}}
+COPY test.sh grade.py /tests/
+RUN chmod +x /tests/test.sh
diff --git a/scripts/roboolympics/tests/test_adapter.py b/scripts/roboolympics/tests/test_adapter.py
new file mode 100644
index 0000000000..c856a7968e
--- /dev/null
+++ b/scripts/roboolympics/tests/test_adapter.py
@@ -0,0 +1,151 @@
+"""Tests of the RoboOlympics adapter (shared/sim/rcb_olympics.py) on the rendered tasks; they need the simulator, so they
+run in the eai-olympiad image, one task at a time (the task's sim directory mounted at /srv):
+
+ for t in tasks/roboolympics-*; do docker run --rm -v $PWD/$t/environment/sim:/srv:ro \
+ -v $PWD/scripts/roboolympics:/gen:ro -e TASK=$(basename $t) ghcr.io/mll-lab-nu/eai-olympiad:0.2.0 \
+ python /gen/tests/test_adapter.py; done
+
+ - the interface the instruction documents (sports.toml: the action types, every proprio column) is the service's;
+ - /spec is JSON and clip() keeps any finite row inside the limits without raising;
+ - a session of random commands through to_sim/step (the realtime service's path) replays bit-exactly from its
+ record in a fresh process (verify) and after a simulated crash (a new adapter reading the same commands table);
+ - a break: the match stands still, a `ready` row ends it, otherwise it ends by itself after BREAK_S.
+"""
+from __future__ import annotations
+
+import json
+import os
+import re
+import sys
+import tempfile
+import tomllib
+
+import numpy as np
+
+sys.path.insert(0, "/srv")
+TASK = os.environ["TASK"]
+SPORT = TASK.split("-")[1]
+os.environ.update(RO_SPORT=SPORT, RO_FORMAT={"badminton": "match-wallclock"}.get(SPORT, "match"),
+ RO_ACTION_LEVEL="low" if SPORT == "airhockey" else "high", RCB_SLOWDOWN="10")
+DOCS = tomllib.load(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "sports.toml"), "rb"))[SPORT]
+
+
+def build(data):
+ os.environ["RCB_DATA"] = data
+ import server
+ return server.build()
+
+
+def documented_columns(text: str) -> set[str]:
+ out = set()
+ for stem, a, b in re.findall(r"`([a-z_]+?)(\d+)`\.\.`[a-z_]+?(\d+)`", text): # `q1`..`q7`
+ out.update(f"{stem}{i}" for i in range(int(a), int(b) + 1))
+ for tok in re.findall(r"`([a-z0-9_/.]+)`", text):
+ if "/" in tok: # paddle_x/y/z, q_striker1/2
+ head, *rest = tok.split("/")
+ stem = head[:-len(rest[0])] if head.endswith(tuple("xyz0123456789")) else head
+ out.update([head] + [stem + r for r in rest])
+ else:
+ out.add(tok)
+ return out
+
+
+def test_interface(sim):
+ spec = json.loads(json.dumps(sim.spec()))
+ documented = re.findall(r"^\| `(\w+)` \|", DOCS["actions"], re.M)
+ assert sorted(documented) == sorted(spec["action_types"]), (documented, list(spec["action_types"]))
+ cols = documented_columns(DOCS["proprio"])
+ missing = [c for c in sim.proprio_layout if c not in cols]
+ assert not missing, f"proprio columns the instruction does not name: {missing}"
+ assert len(sim.proprio()) == len(sim.proprio_layout)
+ for typ, t in sim.profile.types.items():
+ rows = np.random.default_rng(0).uniform(-50, 50, (20, int(t["dim"])))
+ out, clipped = sim.clip(typ, rows)
+ assert np.all(np.isfinite(out)) and out.shape == rows.shape, typ
+ for typ in sim.profile.types: # a gap the service fills with command(): no command
+ if typ not in sim.profile.interp:
+ assert list(sim.to_sim(typ, sim.command(typ))) == [-1.0, 0.0], typ
+ assert sim.refused == 0 and not sim.commands
+ print("interface ok:", list(spec["action_types"]), len(sim.proprio_layout), "proprio columns")
+
+
+def random_row(sim, typ, rng):
+ if typ == "stroke":
+ return [rng.uniform(0.2, 1.0), rng.uniform(-0.5, 0.5), rng.uniform(-1.6, -1.0), rng.uniform(0.2, 0.5),
+ 0.0, 1.0, 0.2, 0.0, rng.uniform(0.5, 2.0), 0.5]
+ if typ == "mallet":
+ return [rng.uniform(-0.9, -0.1), rng.uniform(-0.4, 0.4)]
+ if typ == "toss":
+ return [0.3, -3.6, 1.0, 0.0]
+ return [0.0]
+
+
+def session(sim, n, rng, ready_every=None):
+ """Drive the adapter the way rcb_realtime's tick does: one row (a command now and then, else hold) per step."""
+ rows = []
+ types = [t for t in sim.profile.types if t != "ready"]
+ for k in range(n):
+ if ready_every and sim.in_break and rng.random() < 1.0 / ready_every:
+ typ, row = "ready", [1.0]
+ elif rng.random() < (0.3 if SPORT == "airhockey" else 0.02):
+ typ = rng.choice(types)
+ row = random_row(sim, typ, rng)
+ row = sim.clip(typ, np.asarray([row], float))[0][0]
+ else:
+ typ, row = sim.hold()
+ r = sim.to_sim(typ, np.asarray(row, float))
+ rows.append(r)
+ done, _, _ = sim.step(r)
+ if done:
+ break
+ return np.asarray(rows)
+
+
+def test_replay_and_resume():
+ data = tempfile.mkdtemp()
+ sim = build(data)
+ rng = np.random.default_rng(1)
+ rows = session(sim, 2500, rng, ready_every=30)
+ live = sim.state_sha()
+ rep = sim.verify(rows)
+ assert rep["state_sha"] == live, "fresh-process replay differs from the live run"
+ again = build(data) # a crash: a new process reads the same commands table
+ for r in rows:
+ again.step(r)
+ assert again.state_sha() == live, "resume replay differs from the live run"
+ m = json.load(open(os.path.join(data, "match.json")))
+ print(f"replay ok: {len(rows)} steps, {sim.applied} commands applied, {sim.refused} refused, "
+ f"{len(sim.breaks)} breaks, score {m['scores']}")
+
+
+def test_break():
+ sim = build(tempfile.mkdtemp())
+ for _ in range(200000): # hold until the first unit ends
+ sim.step(sim.to_sim(*sim.hold()))
+ if sim.in_break or sim.finished:
+ break
+ assert sim.in_break, "no unit ended"
+ k = sim.m.k
+ for _ in range(10):
+ sim.step(sim.to_sim(*sim.hold()))
+ assert sim.in_break and sim.m.k == k, "the match moved during the break"
+ sim.step(sim.to_sim("ready", np.array([1.0])))
+ assert not sim.in_break and sim.breaks[-1]["by"] == "ready"
+ for _ in range(200000):
+ sim.step(sim.to_sim(*sim.hold()))
+ if sim.in_break or sim.finished:
+ break
+ if sim.in_break:
+ n = 0
+ while sim.in_break:
+ sim.step(sim.to_sim(*sim.hold()))
+ n += 1
+ assert n == sim.break_steps and sim.breaks[-1]["by"] == "time", (n, sim.break_steps)
+ print(f"break ok: {sim.break_steps} steps ({sim.break_steps * sim.control_dt:g} s of game time)")
+
+
+if __name__ == "__main__":
+ test_interface(build(tempfile.mkdtemp()))
+ test_break()
+ test_replay_and_resume()
+ print(TASK, "all tests passed")
diff --git a/tasks/dataset.toml b/tasks/dataset.toml
index a059387484..95e95114fd 100644
--- a/tasks/dataset.toml
+++ b/tasks/dataset.toml
@@ -5315,513 +5315,525 @@ digest = "sha256:1022cf7988317b93b4d805807d7defc24e10be88b1dc29cca357e09ffbe681a
[[tasks]]
name = "robot-coding-bench/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-privileged"
-digest = "sha256:5cbfd803c3c1b06cd1695c2103872ba7e7dba0c40d1cb3a3219c7faad85fd7cc"
+digest = "sha256:ed8aa55b30a1f037459f3739232bd51e081db50e9d06440b6650a860200abe18"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-standard"
-digest = "sha256:7d12a61daec72144dff3cd8ecf8ce4a8ff6286d9797e381b639dd4875e29758a"
+digest = "sha256:06ccc2ac4468c1b1c858178f64c59a2e9ea2d3c1129141e2f6958abdb91adc76"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged"
-digest = "sha256:6484276263a04ef81879130badf5c10a07ad3d13f0fec92aa8bf8a47ddb6d3ff"
+digest = "sha256:0e879d4ff2e627a6e054cd6288f3156bacb540be224b542b651001f8747c40c7"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-standard"
-digest = "sha256:fd1cbd3053ecab52f17597f1c52f4d22407906310aca0d59b97fdf0d51563b02"
+digest = "sha256:0c91649a04cd329df08a10f82d730f53336a5081d4940a857572779ee770f5f0"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-privileged"
-digest = "sha256:85288f8003ca36e4c6f2ca6893013b0e704e4d0b63f87938ff4721c08af355a4"
+digest = "sha256:837db92baff3bb1e724c06577e9c4ee0a1b899be0d885b4f8dbb44d9ac61fda8"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-standard"
-digest = "sha256:6a3d0b4d49c69b1b8f10a1d3fb071ca093eef69678e786940b7efe6d5335be6b"
+digest = "sha256:e3ed4cd5efdada7fdb76068cb2fa482fb8ece975e47afda28d17aeb8fec2dd79"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-privileged"
-digest = "sha256:76d07f7e841fe7036f8209dd9c739aee4ead5e71c2301830c6290ce32155f7aa"
+digest = "sha256:0f7ac4575aee28dcc710bf9b53d7d779c25db994ea9ad3fb127cb489dfd44b94"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-standard"
-digest = "sha256:70a089d53383ebe4ad0a089b01d49ecff569acea1d0aff0ce1c54e1ec31b0e8d"
+digest = "sha256:f6fc68a6f47273b3f31eee465317d89542a0dddd55db3ee430eb9d682be3f858"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-privileged"
-digest = "sha256:47140a02e64bd1ae01c76605cd649c9587f01c190e406b015c33108f2fabb3c0"
+digest = "sha256:213da6a05c1ab23313c6017911fac829df85cc6f865fd328aa61910268d459e6"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-standard"
-digest = "sha256:842e5a682d7e81352cd27a680f64a61bd5efb350af2fd97e362e9a8ddfd4965f"
+digest = "sha256:bdc44a0783a505690388264aca52cfbb1c929881df8a191ff756b3a9152b182f"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-privileged"
-digest = "sha256:a12b38786747813a14fa32f6a84f1eabd36ff466aedb3fdd00a81d28a90df943"
+digest = "sha256:dfbd5bbc0a43b7f6e39754702fd221f69b3e33eed752f29d3322419742376c41"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-standard"
-digest = "sha256:add74467a828da4e31ac0a6c4fcb2c1e84a463dbd4ee87b187b4139c39626a75"
+digest = "sha256:bb398e96e3492d8021015fbbdf716c762a429155ab7469d10fa59c1fd001e374"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-privileged"
-digest = "sha256:0e38210551755fab1f320e34d3202045e890dc088aaab0e519e3e15bd80979e0"
+digest = "sha256:337042bbc00bee929d3592eb0b63c089cdf2f21c9f4141b69336cea24edc73c5"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-standard"
-digest = "sha256:6d973dedcade7d608600e438a026e4ae91e7395754d50aa942ec5180ead3832c"
+digest = "sha256:ea8a51a115f7fc28f614d96dd5d7def8cad0d9ac3efa5b4b40969d72fbd13b23"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-privileged"
-digest = "sha256:f5b88f968278ee4d570f91037684fe071d49fa4c1c5cb85e5ebcb035299e6594"
+digest = "sha256:6227a9e6b6ad79f4d3cb3125dc85f33bf64d5d3831c8bf8b9520767aa7e2a8d3"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-standard"
-digest = "sha256:1a93da98257459180ac2bc11b604ef418951ca843d3200c8dc95f2d5069477b3"
+digest = "sha256:4118e92d78fb84b6fe67e80f88a8a9a7041c9313c215f33b2de3d7884e0b30a6"
[[tasks]]
name = "robot-coding-bench/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-privileged"
-digest = "sha256:241d813b1605dd19b35af585180b7f25a40fbdafa7f7159e4ce8ebfc79e3dd18"
+digest = "sha256:edddf37782f04ada1f0a458875e35963adfd37e5fcff1d3eb5f51e508b0b9b89"
[[tasks]]
name = "robot-coding-bench/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-standard"
-digest = "sha256:72820a9573414fa5c92a6dc80de1fe7acfaa544ba44936d28c604f37e80dea59"
+digest = "sha256:99a3bfc3eebfd1866ed3380cd2cac605e8426e20651d57c29620dcaf46ee6b93"
[[tasks]]
name = "robot-coding-bench/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-privileged"
-digest = "sha256:f9ec0f26c51eb4637c335b42389ecc998b75b39bbf483c59171b2fe7f7e07574"
+digest = "sha256:c244175517c1b158519305b26531d8df634882750dba744a86513784b145ce7c"
[[tasks]]
name = "robot-coding-bench/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-standard"
-digest = "sha256:95e9267dd822450aa61e06a459528b1ad2bfd5c85932509acf3038f22bbcb37b"
+digest = "sha256:d290c1b78ff92e72f325f4716453e98cd49f3e48906c3860706268fe4db6a754"
[[tasks]]
name = "robot-coding-bench/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-privileged"
-digest = "sha256:934ab0a36175b42e123d0b35d7fa9cf892b5d0c14074ff14cc5c4d29fd6b9a51"
+digest = "sha256:8af9f2b062ccf02719d191f0d8980ecfff149f24269ae75e63bf434f861ee5c2"
[[tasks]]
name = "robot-coding-bench/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-standard"
-digest = "sha256:7c364501d66fe877b9f311bb4bcba16c6a4f2847c257e897b9aa2ca63d1b0b66"
+digest = "sha256:e16bb8e51215d66907ab3e4fc82c0266a47ea32689e751fce435ee6194c37517"
[[tasks]]
name = "robot-coding-bench/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-privileged"
-digest = "sha256:de7c71e5f0b73e14eac2155f0d97e8fd83d1f477a9efd19b989e28663f610ec6"
+digest = "sha256:cbc7b0a88f401b6c08402f5c1a5c886acdafa288496ffe67a2cfa302d2dd326e"
[[tasks]]
name = "robot-coding-bench/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-standard"
-digest = "sha256:a8c9704f06d897274d39eb03df60f17bad5af167082b77a573aa4b9c2e7958c4"
+digest = "sha256:ff6544a5f7dfd0ce772d2d527030ebcc368a57881f28c1d9513fd2ac3c1103a1"
[[tasks]]
name = "robot-coding-bench/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-privileged"
-digest = "sha256:e18c8e153f1719506d5464dc7ffee9203b092e7bbc2af410a4b7d428a88fc5d5"
+digest = "sha256:73038178f4f719366024e52c0739e8684aad615842766a343089316e11817268"
[[tasks]]
name = "robot-coding-bench/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-standard"
-digest = "sha256:9a817c6a5c697b85dd68051182e965ee2261d0d90a713800e4c80da024d1f386"
+digest = "sha256:81ac31ba550d635bf8bd9165475effb87390eb6a290824663edc60bb0a91384e"
[[tasks]]
name = "robot-coding-bench/libero-max-object-butter-in-basket-distractor-burst-i00-privileged"
-digest = "sha256:cbda0d999548fae022d6a38005519db74830d69e418869d2b5053b8864810957"
+digest = "sha256:6d4518db37b967215068b5d5b74096886d0d487e099bec130bcd18b5bdbe9cea"
[[tasks]]
name = "robot-coding-bench/libero-max-object-butter-in-basket-distractor-burst-i00-standard"
-digest = "sha256:50d8288496ea9128f4486938eec54281c4256a322c534791db0908014df618f2"
+digest = "sha256:6ce8b80eb1b56f604c3a79a540d730f44f257c0173f4ad6b87cef30a99ea98b2"
[[tasks]]
name = "robot-coding-bench/libero-max-object-butter-in-basket-receptacle-relocation-i00-privileged"
-digest = "sha256:841ec32b940ce9d09561a8d43d5a64ba36f603daa5580da23ad215b4cffce4d5"
+digest = "sha256:32439fd83b7cbf2f275771199555ff8d5059a8a50e60406bc1b8c9a192cac6fb"
[[tasks]]
name = "robot-coding-bench/libero-max-object-butter-in-basket-receptacle-relocation-i00-standard"
-digest = "sha256:bfb78da96775963a6647f4b2b1fb2fc65a8ca2accfed12cdd5b5eb34c524951b"
+digest = "sha256:f35851bb5d9eb130ea42fbacd20661cc4a9bda38797d0a0ce51030c07526bb02"
[[tasks]]
name = "robot-coding-bench/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-privileged"
-digest = "sha256:7e8587b5733982b7ee09304f14a7788cfecd6ef21fe3b90614f50256c2ada3e6"
+digest = "sha256:95c14bf23716eeea91eb54d4f12c36a788282339e653be7d9b0f97ece17838b4"
[[tasks]]
name = "robot-coding-bench/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-standard"
-digest = "sha256:4982c3d2f9ef4ab89d72627f1b52fc2e3be609f2c40e33cab99d6c1161b36be9"
+digest = "sha256:b5443c3b7d53f506cd1b50c06fa9f6b9e2be9c368a4f99f58f05bbf37d033ed8"
[[tasks]]
name = "robot-coding-bench/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-privileged"
-digest = "sha256:7d115fd624cb207d16f63fe8b3d8ca86f274e15960c364423f58583281713feb"
+digest = "sha256:3a40bf1945851fda80a5bffcb88b9e6f85adc93503e5513797bb528f424bde5e"
[[tasks]]
name = "robot-coding-bench/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-standard"
-digest = "sha256:3fc555aeeb2a7983803b6dbb6e435321073d41a75fd619fc652ddae3c5afbab2"
+digest = "sha256:6eba30032bf95d5df9312ccc62e0d8274dbb112ce8e3e8ca78ae627dd0af0705"
[[tasks]]
name = "robot-coding-bench/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-privileged"
-digest = "sha256:cded1d808236340960a0530d5bacb6ac38568770c1c6d82060a6c01b1f45d50c"
+digest = "sha256:55936b3b2ad2c25c8dae02a67e1c5b581a0228be511c7cbf0963dfc303a2108f"
[[tasks]]
name = "robot-coding-bench/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-standard"
-digest = "sha256:368ad66c6d535831d3e6a199bbeb3a294e8e7f2faf030cf45e52fd0a03d11998"
+digest = "sha256:9d8c478bd38b938a29400ec44da2297bf5b565e24dd874e0945368e9939d728c"
[[tasks]]
name = "robot-coding-bench/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-privileged"
-digest = "sha256:3a135e3d1869f2865ef840e0407340d263b83cace1840b187478e1f9aef59b12"
+digest = "sha256:f015c18505eeafcbc3abe8d54b903fcaf5f4eba5458474c6e7a8948de5922ca2"
[[tasks]]
name = "robot-coding-bench/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-standard"
-digest = "sha256:0a004f4c6622c7fe9a12521c39144ba0b9f16bdeec4b2d515d4cac72570a8d02"
+digest = "sha256:691364c8484c76e06de29329d780e030a96385367b967dbd35ff0faaef66aef5"
[[tasks]]
name = "robot-coding-bench/libero-max-object-ketchup-in-basket-distractor-burst-i00-privileged"
-digest = "sha256:6a2cc05a1ae177e137c205d70a0ae1dfab9261575b3cdb91ba96a1941aeeaff1"
+digest = "sha256:a8ebdab6dafaae62ef4d2eaddbe2887211f2b18dd03cdcb56c9817848e04ea69"
[[tasks]]
name = "robot-coding-bench/libero-max-object-ketchup-in-basket-distractor-burst-i00-standard"
-digest = "sha256:306f464cff2559ad8cf183fbd23b9d643fa95197eac123fc856f6607e194037d"
+digest = "sha256:e7b8044e086a63e09a8d4a3ee11ebe8e1e0c52397cdbdd3b431e57829f1ff864"
[[tasks]]
name = "robot-coding-bench/libero-max-object-milk-in-basket-camera-shift-i00-privileged"
-digest = "sha256:b0b4c6b2d3727a1fcf1794cb57288596cebd16b65e6ff27faf0fa01692bb980a"
+digest = "sha256:91df3b3ecb929ec801857c97f42e03b75bb51ba7ed41cadc7100e5fd0dcd41c6"
[[tasks]]
name = "robot-coding-bench/libero-max-object-milk-in-basket-camera-shift-i00-standard"
-digest = "sha256:11ae84371a141984fab1d37938a6f3cb249bdf7c8da4b461bf496a20fe486a16"
+digest = "sha256:e87e8d44f93ede28526282c13b5b7493bcd60163aad59d6bbe79a414088f70c0"
[[tasks]]
name = "robot-coding-bench/libero-max-object-milk-in-basket-distractor-burst-i00-privileged"
-digest = "sha256:a98ac51af507d4f81dbe47c7cd3240eb78d83fe4e9a13aea72ac3a0f6b470d58"
+digest = "sha256:59a457610af2ffab816807e81533a54e6330e40d16fdea7b4bbfe3f0477a21ba"
[[tasks]]
name = "robot-coding-bench/libero-max-object-milk-in-basket-distractor-burst-i00-standard"
-digest = "sha256:49e7c617a9d43203aa8a5422ef324472908bd583cc9fd40e0a8b901b1f891e36"
+digest = "sha256:8c34df1fe9e1d454bb89c72b736399480f3622e65a4b9def6af57081f97af9d3"
[[tasks]]
name = "robot-coding-bench/libero-max-object-milk-in-basket-illumination-switch-i00-privileged"
-digest = "sha256:c21ef65010d5f289f711fe4a0bf9734dcdf63cb5f309162a7d9de867fca815ce"
+digest = "sha256:cd9a728a8bb7466264046f454397125d8b38fb6604ebb0f55532e32a8690b9e7"
[[tasks]]
name = "robot-coding-bench/libero-max-object-milk-in-basket-illumination-switch-i00-standard"
-digest = "sha256:9e13771623ea58d11dea02d2fd83967be56c91d0f570ee4a86afd802b5286837"
+digest = "sha256:fbe3ed9e1dbd391d0f7717099c952315526627ae655498e2df04dce9c39ad8e1"
[[tasks]]
name = "robot-coding-bench/libero-max-object-milk-in-basket-target-relocation-i00-privileged"
-digest = "sha256:e5f9cdbdbefaf71bd782c8c071711f19ff32c6c2166e2330465316ea8f9bf9f7"
+digest = "sha256:d54ad8e86f408aef90653082a641ad15ca199db508bd90262a8895fee41e55cd"
[[tasks]]
name = "robot-coding-bench/libero-max-object-milk-in-basket-target-relocation-i00-standard"
-digest = "sha256:840eff6a33514520adbcfb6b4e626a1c5e7be261fee733396662bfdfba6788cc"
+digest = "sha256:fdfcb8675a07a8abe21e01879c5db107b31d0a09017d4b589eb375b16fc6453c"
[[tasks]]
name = "robot-coding-bench/libero-max-object-orange-juice-in-basket-distractor-burst-i00-privileged"
-digest = "sha256:b5146653931e233a02fe3f97b07ee2f53fb16eafe5e3f351bc35f5cf05f135b8"
+digest = "sha256:57b4b5bf95dd5dafdc5764c0cb09bea9944a6ab023adf12d4abb341ac6aee8d1"
[[tasks]]
name = "robot-coding-bench/libero-max-object-orange-juice-in-basket-distractor-burst-i00-standard"
-digest = "sha256:2cb86b12d04c65e074db9bcf17ed35c5284544d72ee10bc022f7bd3fac505446"
+digest = "sha256:f38df3ea01748cb8f09ea7b6a74ae06afde5b774ac6cbf4b207a579047cabd99"
[[tasks]]
name = "robot-coding-bench/libero-max-object-orange-juice-in-basket-illumination-switch-i00-privileged"
-digest = "sha256:57ffa59f9db20072162848d743c1af59963962e1e671ef5cb6530ab758a6d3a2"
+digest = "sha256:b7b6344745834f4b108bf2f3d0b8aac4c12332d297c31797eeccacb76d1d9ad2"
[[tasks]]
name = "robot-coding-bench/libero-max-object-orange-juice-in-basket-illumination-switch-i00-standard"
-digest = "sha256:a5e0722afcd42aa56cc549ca84211d2d09339e4999efcdead41af6c466df85fd"
+digest = "sha256:5c5560619476730a34873323d2a20f4520a03c3d678853e1bc810ea3670d6f4e"
[[tasks]]
name = "robot-coding-bench/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-privileged"
-digest = "sha256:c4568650d63e5cddbbfe0f839b1d4e48d5ae1d845d88eff6f1d8fd220ae97233"
+digest = "sha256:33e1453a014bcbcb706b941f840a93a98810df693c7f11fe35b64291f695936f"
[[tasks]]
name = "robot-coding-bench/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-standard"
-digest = "sha256:128b8cf0f84ac9f043b4acd20e21dba0fd8bed7ade54798a66ae065940c988de"
+digest = "sha256:3f1d73d394a2a6fb9117d270c853b268a986e7a450f7b6367199453b320fa91e"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-privileged"
-digest = "sha256:44ab65349e12b59358427e4fbd8e2b77c466b5ab3a115c2385a85be8508f93ab"
+digest = "sha256:f2fe5a51f7efa65b3463e74f42728e927e700450c09f3e6c0c990ebebf07e76f"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-standard"
-digest = "sha256:ff40451d40247005bc6db414c8df2ca81af79811e14ceb3a403292ec20a9700b"
+digest = "sha256:1b2fc2c710c90bfe6f43e06be19650d331a039ddd143a24e95c7ccd4084a2349"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-privileged"
-digest = "sha256:633192592005893e232552e3de58208b5f8342c6980440919aa27a697f66732c"
+digest = "sha256:55c4f1457f830d44d516398bdbc05fe768cf84dc4d2ae390d277b071ba7780aa"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-standard"
-digest = "sha256:8aedc8f904b24fe667c74341475d4aec3a44bd42720ec3f80558b9445bf5ea25"
+digest = "sha256:95792f6406122798c4d2a95676ec6b55a1903587571a880e4b0ff7d95f79f094"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-privileged"
-digest = "sha256:8f6642cff05f4a4e0eca95f5bd839faa6b6a40ace6e53e3fb6e1f272cd0622cb"
+digest = "sha256:f17859ec567f413b2332f661e0fccd42265dcfb6a019455f39407ad209d55997"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-standard"
-digest = "sha256:b168200f5a06d6c04285ae7edc56cb1e903decd94a6cceffb0b48269071f3261"
+digest = "sha256:593c59d89535a58b169de1423ea629bb196f669821f2a34cb360a8d78608622f"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-privileged"
-digest = "sha256:c0465e5634680cccd1a698ed0d11cc48e395816ed95cbe0487c44bf22727f40f"
+digest = "sha256:393bef024b3d90b2e60318df34e0f4f2d11aa397e7217bdc4c2edbf1ababaf2d"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-standard"
-digest = "sha256:4ea8c7b1e0185f79800994cdbe3e9c14960113fd4761c5657b046e05832734f4"
+digest = "sha256:82bd7ceb3bc1b614137931d1bf247690d87af03ee9a8082e1185e5e05685962b"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged"
-digest = "sha256:41d1a7de88ea36620a69a2f512f3e2fd3739a72f4e3748ea2d1ea1a62bd93cf2"
+digest = "sha256:cdb0f55c54d68289eac8ad8f7080fe987776d822ab4532a4203921f1ca226fd0"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-standard"
-digest = "sha256:0d502d0a6b79d34170b2b49065a35c74e1490e1285c055db46cc63a4c26868e1"
+digest = "sha256:7ac91232f336a8115b4892564c71ca4016d334898212e627937dd30db922cf23"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-privileged"
-digest = "sha256:260b87c0856b0bbe4e00b78baf1ccff765266d9917b651fcbf4bc96c5f7f8dfb"
+digest = "sha256:fcd1943c7aeeb93c8ca89e4a3eeb6394f05deead2bbc1f118e05c63cd8ae851c"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-standard"
-digest = "sha256:f536c91683ab6399d60321fd7a354b811420afc504950fe4f5dabee536732f0f"
+digest = "sha256:daace03f23da9b1d1366a451e00cda610f5cdf99bd116fa4d8d9bd66f062a259"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-privileged"
-digest = "sha256:322535e602cdffd4566534663a96f7629890edbef542caac110bee60f37a4e26"
+digest = "sha256:dbf597dc614e4c8ae3fb69ef7bc7d4a25134287c86d20926ab3e625588f2ed3d"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-standard"
-digest = "sha256:674d06a618455c0c112fe760f65de9b23590ca8919ca56d12f46f5ba709b55bf"
+digest = "sha256:d2137166b439be240847af164969734e145c98734f8eeebd4b806f8bb71f6bad"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-privileged"
-digest = "sha256:675f391ebc31539affbbc467d11c1711424c073bb5ceeb12be3cd0899608ddf1"
+digest = "sha256:c8c9d578f2bd13ebdc66a0a527327f69afbbf0e7391b4e1132663dfa8828fbe5"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-standard"
-digest = "sha256:0661f6f7c21211110bf89803f7673a9bf0d265f626f887521006c39e9d45fe3d"
+digest = "sha256:74bd6b05cc2bfc47e2f1c3db3ba6b34b135723e2266c3f0433a1d8b44139d077"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-privileged"
-digest = "sha256:a71403c77f1e9ff5575303d5334c8f94c5762176973a45b30858d400df314ace"
+digest = "sha256:f18cb7ec4aa6027bce4f787cd67ac1720f306ce72d15f136e03f6f707a319f82"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-standard"
-digest = "sha256:804c0773e9c970bf7ac71547f700acdea32f88ad42401ca879ffebf26468a8b8"
+digest = "sha256:09f8f743efe76a61d9766de40d804de0e924a7f2e89a6fa17e7059e06f40ce6a"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-privileged"
-digest = "sha256:4058b7b96db777fd5db9eb13bd9e60fe0ec3a3d0932f3821e1aa0d40121f0a19"
+digest = "sha256:ebb626d837a899be4fd03fdfac7709ee7d677a12546d85b7dbae8237b4294183"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-standard"
-digest = "sha256:8c45d677204662e5b36f55556e0a6f0f4d4d891e9a9581f68688459811f76e89"
+digest = "sha256:cb260542d45cfe232a8414cbc6681813061d4fe4ae2b4b2fb70b551e76130075"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-privileged"
-digest = "sha256:9fc077f15a17c8a0edb001283146f74d0818a239a4236d6736981ab8ee7a5fe8"
+digest = "sha256:94f9ccbd2d21bd24be1f42e1c851991c645da216a6e0217116a688a828219d9e"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-standard"
-digest = "sha256:b9471fe504c6ad74896e722c24cd07da934121c89478ed43ce59f97aec2e79f3"
+digest = "sha256:1944a1c8135e4f64b222724f3ea8eac6e0f9ad24221ee889d4f0fb642cf8901a"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-flat-stove-off-visual-theme-switch-i00-privileged"
-digest = "sha256:a51b2a1991e626e1be800522a66b5fe748c0d86b8bc0afe36be57c6acd955deb"
+digest = "sha256:b238b03829bc3c665a1165f5aaac751051ed45c114049fc60dc9add71066db8b"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-flat-stove-off-visual-theme-switch-i00-standard"
-digest = "sha256:ef311370a9e77edceb475f1f53b521c4baa0eb3d963f821000f26453c051af48"
+digest = "sha256:94524a6cdde6c31a9e393cd364f5b71cbe2230906905cc34f90c070318279908"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-flat-stove-on-illumination-switch-i00-privileged"
-digest = "sha256:d71c233d53ba1840672208391896842f3812ed134d61e7422e12eb588143a949"
+digest = "sha256:d04923ff6b6be0ef4c28bbc4ac49c65f664b8c260c72ed336f6f9045ddd44055"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-flat-stove-on-illumination-switch-i00-standard"
-digest = "sha256:907604019058de941b748a0ba850259fc603559f522d6b0cab7e7868bb1aa079"
+digest = "sha256:33a99ea0cb369b33ea669ebbd73b1c9e06a5a2f196d7f66f794893ece75dbe6f"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-flat-stove-on-illumination-switch-i01-privileged"
-digest = "sha256:e9f8bb2596c89c5db20cec641b7c36aa9d7aa5e95ea09b6bd0ff6d0a539fdd7c"
+digest = "sha256:58b05b7a2bce3fdc749addfad914ea25a2f2eabccdfd4b904460a6a4dd9fe6f3"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-flat-stove-on-illumination-switch-i01-standard"
-digest = "sha256:f545f8a169c0e22987f40db5f5a5c85d12fc8b40a2e95205437d83fb6a474a9b"
+digest = "sha256:b613f0342cae3bf0bf7c9ac1db210d9fce483ec3ac2badaba60ff806682aa83a"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-privileged"
-digest = "sha256:fd2466cdb19f6b2d36af56c196b1c6bebcd033c1a8f7cc95d3602428bf41d4a1"
+digest = "sha256:edf337a0f0537f39a52e12ef3fe62dd2bb59f69761c5687c3a5cb41cd1150ad4"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-standard"
-digest = "sha256:8498dbd92833387af6d0ecd712ea699f5fe857fa868185f6176396f2d31dcf72"
+digest = "sha256:d150396e14b0db489b3ff368ee92ff83314fc6e1b70c987bba93725a0bb00640"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-privileged"
-digest = "sha256:5176fe2a45bdc12d1238c6aaaa3e504692e77f5d2cf99c3474128bf28e5b69a4"
+digest = "sha256:ace642d0982db2411c59974daf494c43b4b668d186a1de57b4428578a01d73f0"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-standard"
-digest = "sha256:c7cf1e3587d849d26fc1c787714b9083be95edbe15eebc4f0bf42086f3bfacee"
+digest = "sha256:573ec57a545b04f49b0f3870d5bcf8cfc098331833e8af8715e6be920f5612ff"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-yellow-stove-on-camera-shift-i00-privileged"
-digest = "sha256:9ad4e5693c6018da98fd7d3a90796f52b9e9d15e6fdad8fcedad0a7828e424e3"
+digest = "sha256:8680c85b1a23bb8409ede969e6bb9f3aafe5d7056cae69a035436cd2e46b7eb7"
[[tasks]]
name = "robot-coding-bench/libero-max-goal-yellow-stove-on-camera-shift-i00-standard"
-digest = "sha256:513421909cf249afb3b5edc93ea5894b501e58654858317aa0c449fea313601e"
+digest = "sha256:ee81b019236812b61928d5b7024634026391f8c9c280742c3c8e634c74dde893"
[[tasks]]
name = "robot-coding-bench/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-privileged"
-digest = "sha256:2f2107ef72b6d9e834db25995c0865a8f2dd406838dfea75d10b6bdba84e21f2"
+digest = "sha256:b3a3c3e2770bf84b92ff704ba179f46ed4a8489648844a68387943ba1f3958e2"
[[tasks]]
name = "robot-coding-bench/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-standard"
-digest = "sha256:94d2f82ce4e4aef527ce07b9ed29e18ac81e236454669d3967fd1e9da1be908a"
+digest = "sha256:6e5e8a873509535453c13cc8684fb5d6402c0ae0d446e4c072fa7476f5638bb4"
[[tasks]]
name = "robot-coding-bench/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-privileged"
-digest = "sha256:d8b376349212d7906027c4cad22ee8e9505f5949ed96c29d3f20043c5ae5a56e"
+digest = "sha256:4ec46af09a4d0e7e9170b01270df040b35519c61f4fcea016a4fbec75236f2f0"
[[tasks]]
name = "robot-coding-bench/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-standard"
-digest = "sha256:cba830e90e6a661f62164eafaacfce38c1dc06e1f33918e5513f7bdb9b96c1b9"
+digest = "sha256:cfcb92fc7fc3b634423b64640409adb86f265eb275b763dc8a2bd21a66d8e080"
[[tasks]]
name = "robot-coding-bench/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-privileged"
-digest = "sha256:3fc6f56756c7ab1a48ec5877e4afa9253743da5718752c34ddf81734b7d28839"
+digest = "sha256:dd28a3eeea8e5526fa9480f6f9cef0d899f9fe5607f25f3da6bd325eb6b7d5c9"
[[tasks]]
name = "robot-coding-bench/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-standard"
-digest = "sha256:814da15fe464f27dcfe4caf573bd853d0c3f4e727b86d32d48fc532c179df776"
+digest = "sha256:cbf454701044281d949f972529c80ea46ee0126ced7ea129c7289d7de3626106"
[[tasks]]
name = "robot-coding-bench/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-privileged"
-digest = "sha256:be469dd1ba6402c884a8179ff3971a31bf1e16a7163f48e7618c37931adb08e2"
+digest = "sha256:3a0f16695d9e59abb1b2bd6761c3934103cc22a1eaa0bbc6a4143a56b1dfd685"
[[tasks]]
name = "robot-coding-bench/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-standard"
-digest = "sha256:401c6e65622fb86905d34a2a3c6ad77d81641e319d4305c9a51b2b7f36fb12bf"
+digest = "sha256:8ba03d58b92cf4852e5755fdacd5a03e5e23c74f02f4261c3dfbf9b5767d4bb1"
[[tasks]]
name = "robot-coding-bench/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-privileged"
-digest = "sha256:96e3cfbc85ee61b46b4167d49d37a96b01a97ef0ace03796fc955dbdf904e336"
+digest = "sha256:47dcbfc75d798d31600803d835e10267b8cf52f4eaf4bd9c5c31eb95cd19df7a"
[[tasks]]
name = "robot-coding-bench/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-standard"
-digest = "sha256:f20a84e7feea13ca7c9d324169aa6158186c4993cb800bdd36edc386043aa8b8"
+digest = "sha256:fbdf35e7a420c85b0c0eefe1b529e6276d6b7496349be1237ea8178434687780"
[[tasks]]
name = "robot-coding-bench/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-privileged"
-digest = "sha256:9624f3b6d598874b17bd8fa63bf06dd6c8d3fe40b9204a9620d3db88a782961f"
+digest = "sha256:d87356409466ed506800a32d7ffca9d359dd946f540fe426a68d644cc0ea5157"
[[tasks]]
name = "robot-coding-bench/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-standard"
-digest = "sha256:fca40001001706711d364db742e493f21b25b5064046891e2d7977ae453306d5"
+digest = "sha256:3a8e20b97b01e63786ab25407df1fdd15f2dc565f8790f226be1119959ce0a96"
[[tasks]]
name = "robot-coding-bench/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-privileged"
-digest = "sha256:c6a8fd93593ed42736170f9151a5ff34e76cf35edc8af80f3cc53d48ddfe1ef1"
+digest = "sha256:81dac4c78016764b5581f3aadd1e525782a3c0038eb5d7307a9b367c690c8b2d"
[[tasks]]
name = "robot-coding-bench/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-standard"
-digest = "sha256:8644d3033593ec3f15139c4ffc2830f75c9c94bd3d158b4096310f4986aee5c5"
+digest = "sha256:577c626ee6d2b6fcc4335748adcffca75c58886394199e8ff903085d4c9dc5bb"
[[tasks]]
name = "robot-coding-bench/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-privileged"
-digest = "sha256:b8bf62230e297032c2be675d4b4a4b003a4213f9015d2136e9bb6744b3aede74"
+digest = "sha256:af7607bf201129d0ab7f8fae3c820224061f726c2b1c0a34126435034ec80390"
[[tasks]]
name = "robot-coding-bench/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-standard"
-digest = "sha256:624fc45d476c6acf27ec2dc47fb2cd3aaf5ec7a05f7763bbe5426174b9967afe"
+digest = "sha256:fa653d5e40c34e5031ca9611bbce5349b74e6ee7990e7bcb8635632d670fb5b6"
[[tasks]]
name = "robot-coding-bench/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-privileged"
-digest = "sha256:ed9f82e3729217726f7271333b2ebbda483570b9fa79d74afa0d8d9d776bd237"
+digest = "sha256:9a57de3f29cfc46a32b38c5194cfa2993cc339a04412f26300eca7c22a74c3db"
[[tasks]]
name = "robot-coding-bench/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-standard"
-digest = "sha256:91b6a2844dae35eecafb3be2fe1351004e72ea6ca60d583045bad598894220e6"
+digest = "sha256:3734cb7f6efbbfdd02694e0a23dcff5fde90a8a72fb5f7042a38f0bec6ecf79f"
[[tasks]]
name = "robot-coding-bench/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-privileged"
-digest = "sha256:1617f2e2ce5f06d30b44beb22fa88b29a92ce61daf55a6683e2750c27cf6fc3d"
+digest = "sha256:05adc4c14adcdc709af753fbb33cd57f249f5fdaa77cd1b836700a65221d341a"
[[tasks]]
name = "robot-coding-bench/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-standard"
-digest = "sha256:32a0756fdaec4df890a63d6330300089af5aafb9060693a188e40d9e6f39cb7c"
+digest = "sha256:24fd2c5035b2891ff8671be6f5e8c57c2c3ddecd2a83b86c9249ec3c79e45836"
[[tasks]]
name = "robot-coding-bench/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-privileged"
-digest = "sha256:43bb117b7c284f111f3491ab42a594399b1c72b4dded90c27853d4a29c4a0ccf"
+digest = "sha256:d5d62a5f3aa801f51113759b85c64d6b4c7bcdc89cb8f57960c21c2d4b7a4e47"
[[tasks]]
name = "robot-coding-bench/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-standard"
-digest = "sha256:8abf84b94fa9058ed6833ce69225136573b4acd4509471dad396dc2eb292bae9"
+digest = "sha256:334650a34c835a54d72f88e603eb019f14e5b427c2f07214bbb4e78c219e4af6"
[[tasks]]
name = "robot-coding-bench/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-privileged"
-digest = "sha256:8e71abf33f42458bb814bf0c45d146f788fa8f6ce8215ee1453bd7548493424a"
+digest = "sha256:84e2e1ef4cf52e112d51fd7785ba35806b06bfdd944516edb9a59704a18096f7"
[[tasks]]
name = "robot-coding-bench/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-standard"
-digest = "sha256:36d1b20eeabe676359c64be847040334c61d4d66d1083229dcc95266772a53a4"
+digest = "sha256:9937e4c329b2ca7e9b6a0a3e720d3befa7b3fe05b8385139981a659550bb1c2c"
[[tasks]]
name = "robot-coding-bench/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-privileged"
-digest = "sha256:77d7803be254f6b7213b4b0b8c59eb168ffef1a8b7155b75aa9ef0c492529778"
+digest = "sha256:1fb1d81eb8dc7aed28e48fbfb7eaee6f9748c3997eaad54b8aa52ef1d7cf994a"
[[tasks]]
name = "robot-coding-bench/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-standard"
-digest = "sha256:1a8265c8d393f492005d74df4f9e6560c4a2ea699995482d989cea203b999e21"
+digest = "sha256:b5179e46389b9c5c3cdaffaa3b243c5f8feec239764dc9e508e90d27d7503a7a"
[[tasks]]
name = "robot-coding-bench/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-privileged"
-digest = "sha256:e4f36ae377b54fa86e31d41034a3b7015aecf7a4fd8b3c30c3ad8328db84546d"
+digest = "sha256:ab9880db14107cf32f46247f4e530c4e7ef296037a66cca779b9bef68af121e8"
[[tasks]]
name = "robot-coding-bench/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-standard"
-digest = "sha256:2d5b2111cbfe00f1efd0d98743b0c16413bfe999f60ef1c66a5592c7dcf84059"
+digest = "sha256:2f71f80f8cd333aa385394ed53fcee97313df2f19f723d6e77e162267f80a5fd"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-privileged"
-digest = "sha256:09fa8412fdd37523aba1d4a515e64adcd1bbaeb9151c86aaffda33b0e1f10959"
+digest = "sha256:2efb5efd6bf44f3f3b47106fad271f152f17951113d9f6bed720b5d7f332d80a"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-standard"
-digest = "sha256:ef693d576a2dd27143cf0a952c4b8bad592c4540201c414217aebb957d04761d"
+digest = "sha256:2bdc5530b1eaaf786f22f1e29dc786ae58feecb39c2da09654f47597fe9d41f7"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-privileged"
-digest = "sha256:d680efa7c92876d561cb7453e3bd35557637463c3d056260156fc1d5ec268173"
+digest = "sha256:bae777f8f960194fa2a5ec84a746172705f4eb1b5be4696ef470295afb23fa70"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-standard"
-digest = "sha256:baea9cad15013a98d2d3e0cc11fccedd50eb99c2251e5d7f4a434db3e7e35c0c"
+digest = "sha256:af674b58dc740fa1f19348d4cb6f9f387a84090f10f1fd1b54b29f096eb9d631"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-privileged"
-digest = "sha256:8b7ab0828bf027e201c05388d5996313374e904c9db8d0ec2d90d0082e260f6c"
+digest = "sha256:f99e2eecbfcf1f8942f03305f8d2946b3fe5f090add6eba66a2faeca010251ee"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-standard"
-digest = "sha256:905b2a0cdf9f7b5fb7cd5c8172de5c7d7f63224ee26d5eccd9106b672b7d1d13"
+digest = "sha256:8bb9b4f718a0216410c48fee1b065b15591a8491b192ce991cce17cc3029968e"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-privileged"
-digest = "sha256:736c24215397e476a4f09d9d94905e70df1e158442faf5c0d83f7af3c5793d46"
+digest = "sha256:3aeeb74b4435baa2572599bcf59d314a4386d6ecf798309214b56a37d192ff4e"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-standard"
-digest = "sha256:6e0929edc05f8747a89c970a96a96849406ee7ca2645cfff645bb19a8441035f"
+digest = "sha256:78852ad72a46cb93f43d2815e5cf62566f89dc163616b41d871902c119b28e4c"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-privileged"
-digest = "sha256:629f148e3bfcf78a5f8f9cbc6665cc4071c45de31342ccb8a696ceab01ddf60a"
+digest = "sha256:836a71e7280c9d029ecc5f21454362df35da4218a0c5dca84be61a5883ee5436"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-standard"
-digest = "sha256:571acaf1b683bbf9b627a380cdcae1db8fe3548939da8363bdfafb9203870f69"
+digest = "sha256:fc910e4536cd27787e0937a92f89d041ccb026c8db1f3d68e0d1a125a599a958"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-privileged"
-digest = "sha256:c0c0dcc37143588c296a7b647059f438049d73c6e7a65bb255310618ceef032d"
+digest = "sha256:db85ddcea9dc8166e98d696310bf5a17c44bcf75ee63c1a6983e1b0cd8b140dd"
[[tasks]]
name = "robot-coding-bench/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-standard"
-digest = "sha256:baadf5225c7f4355c657b6827b5ae2391ee315d5e6e7335bfd44fcac5846e556"
+digest = "sha256:146535d4a9b6088a6d4d0fdceced69a4047b095d392440e9afa43524707c2913"
+
+[[tasks]]
+name = "robot-coding-bench/roboolympics-airhockey-match-i00-standard-realtime"
+digest = "sha256:daaa62a3f87d3facf0b3489cf1e08934016f88a988f201d9398b33f1aeded868"
+
+[[tasks]]
+name = "robot-coding-bench/roboolympics-badminton-match-i00-standard-realtime"
+digest = "sha256:28186585dae5dfd7885b56a550b37f96b9854f2387f0052f6d8af7ca407a0c68"
+
+[[tasks]]
+name = "robot-coding-bench/roboolympics-tabletennis-match-i00-standard-realtime"
+digest = "sha256:000794b70e4bed0b3514a33b5ea42d36cd8e9eade15bd6d62cfc3b9caaac3041"
diff --git a/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-privileged/README.md b/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-privileged/README.md
index 34b120c31b..88799e85f0 100644
--- a/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-privileged/README.md
+++ b/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/target_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-initial-pose-position-angle-goal-t03-i09-target_relocation-d0-p195`: a Franka Panda arm at a table, instructed **"Open the top layer of the drawer and put the bowl inside."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-privileged/environment/Dockerfile b/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-privileged/tests/Dockerfile b/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-standard/README.md b/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-standard/README.md
index ae1eccdb3f..c5c2c029bc 100644
--- a/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-standard/README.md
+++ b/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/target_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-initial-pose-position-angle-goal-t03-i09-target_relocation-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Open the top layer of the drawer and put the bowl inside."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-standard/environment/docker-compose.yaml
index eaa492af67..1c79a7be31 100644
--- a/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-goal-akita-black-bowl-in-wooden-cabinet-top-target-relocation-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-privileged/README.md b/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-privileged/README.md
index 6d94b615ef..456517a343 100644
--- a/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-privileged/README.md
+++ b/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/target_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-semantic-goal-t01-i03-target_relocation-d1-p195`: a Franka Panda arm at a table, instructed **"Place the bowl on the stove."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-privileged/environment/Dockerfile b/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-privileged/tests/Dockerfile b/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-standard/README.md b/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-standard/README.md
index 688b8f5fda..6c788cbf85 100644
--- a/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-standard/README.md
+++ b/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/target_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-semantic-goal-t01-i03-target_relocation-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Place the bowl on the stove."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-standard/environment/docker-compose.yaml
index e463624ff5..6173e3e04f 100644
--- a/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-goal-akita-black-bowl-on-flat-stove-cook-target-relocation-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/README.md b/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/README.md
index 88a3c66f71..e9463d10a6 100644
--- a/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/README.md
+++ b/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/receptacle_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-position-goal-t08-i00-receptacle_relocation-d1-p195`: a Franka Panda arm at a table, instructed **"Put the bowl on the plate."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/environment/Dockerfile b/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/tests/Dockerfile b/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-standard/README.md b/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-standard/README.md
index 71ff2d7ac8..1e14e055d7 100644
--- a/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-standard/README.md
+++ b/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/receptacle_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-position-goal-t08-i00-receptacle_relocation-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Put the bowl on the plate."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-standard/environment/docker-compose.yaml
index 81e78d1d60..64be0feabc 100644
--- a/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-goal-akita-black-bowl-on-plate-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-privileged/README.md b/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-privileged/README.md
index 93ced4c766..082d1dc2e5 100644
--- a/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-privileged/README.md
+++ b/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/obstacle_insertion` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-semantic-goal-t04-i02-obstacle_insertion-d0-p195`: a Franka Panda arm at a table, instructed **"Place the bowl on top of the cabinet."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-privileged/environment/Dockerfile b/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-privileged/tests/Dockerfile b/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-standard/README.md b/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-standard/README.md
index ae69d07b36..ffae30371f 100644
--- a/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-standard/README.md
+++ b/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/obstacle_insertion` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-semantic-goal-t04-i02-obstacle_insertion-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Place the bowl on top of the cabinet."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-standard/environment/docker-compose.yaml
index 37d93e14af..7d2b433dc9 100644
--- a/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-goal-akita-black-bowl-on-wooden-cabinet-top-obstacle-insertion-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-privileged/README.md b/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-privileged/README.md
index f716ee24f4..33654e5433 100644
--- a/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-privileged/README.md
+++ b/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/obstacle_insertion` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-position-goal-t06-i06-obstacle_insertion-d1-p195`: a Franka Panda arm at a table, instructed **"Put the cream cheese on the bowl."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-privileged/environment/Dockerfile b/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-privileged/tests/Dockerfile b/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-standard/README.md b/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-standard/README.md
index 90a3be13b1..4103601147 100644
--- a/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-standard/README.md
+++ b/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/obstacle_insertion` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-position-goal-t06-i06-obstacle_insertion-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Put the cream cheese on the bowl."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-standard/environment/docker-compose.yaml
index fbfbb17d8a..72cf250404 100644
--- a/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-goal-cream-cheese-on-akita-black-bowl-obstacle-insertion-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-privileged/README.md b/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-privileged/README.md
index d06418a225..4a034cd151 100644
--- a/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-privileged/README.md
+++ b/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/visual_theme_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-task-goal-t07-i02-visual_theme_switch-d1-p195`: a Franka Panda arm at a table, instructed **"Turn off the stove."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-privileged/environment/Dockerfile b/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-privileged/tests/Dockerfile b/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-standard/README.md b/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-standard/README.md
index ecff66218d..a4559b4664 100644
--- a/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-standard/README.md
+++ b/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/visual_theme_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-task-goal-t07-i02-visual_theme_switch-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Turn off the stove."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-standard/environment/docker-compose.yaml
index 746cc3f24a..ce14a20d78 100644
--- a/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-goal-flat-stove-off-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-privileged/README.md b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-privileged/README.md
index 5ba07892cd..c2f7740853 100644
--- a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-privileged/README.md
+++ b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/illumination_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-semantic-goal-t07-i02-illumination_switch-d0-p195`: a Franka Panda arm at a table, instructed **"Switch on the stove."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-privileged/environment/Dockerfile b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-privileged/tests/Dockerfile b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-standard/README.md b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-standard/README.md
index 78f3548d46..f31a506c13 100644
--- a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-standard/README.md
+++ b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/illumination_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-semantic-goal-t07-i02-illumination_switch-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Switch on the stove."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-standard/environment/docker-compose.yaml
index be9717c4f6..9036647729 100644
--- a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-privileged/README.md b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-privileged/README.md
index f4ce0053e0..a5fc2dce92 100644
--- a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-privileged/README.md
+++ b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/illumination_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-initial-pose-position-angle-goal-t07-i06-illumination_switch-d0-p195`: a Franka Panda arm at a table, instructed **"Turn on the stove."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-privileged/environment/Dockerfile b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-privileged/environment/Dockerfile
+++ b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-privileged/environment/lmx_tool.py b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-privileged/tests/Dockerfile b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-privileged/tests/Dockerfile
+++ b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-privileged/tests/lmx_tool.py b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-standard/README.md b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-standard/README.md
index 7172e35483..db5b0be008 100644
--- a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-standard/README.md
+++ b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/illumination_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-initial-pose-position-angle-goal-t07-i06-illumination_switch-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Turn on the stove."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-standard/environment/docker-compose.yaml b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-standard/environment/docker-compose.yaml
index acda3d0211..406844086e 100644
--- a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-standard/environment/sim/lmx_tool.py b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-goal-flat-stove-on-illumination-switch-i01-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-privileged/README.md b/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-privileged/README.md
index f609e51254..3a7a0df8eb 100644
--- a/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-privileged/README.md
+++ b/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/sensor_noise_onset` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-visual-noise-glare-goal-t07-i08-sensor_noise_onset-d0-p195`: a Franka Panda arm at a table, instructed **"Turn on the stove."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-privileged/environment/Dockerfile b/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-privileged/tests/Dockerfile b/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-standard/README.md b/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-standard/README.md
index c057067b87..091933def1 100644
--- a/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-standard/README.md
+++ b/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/sensor_noise_onset` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-visual-noise-glare-goal-t07-i08-sensor_noise_onset-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Turn on the stove."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-standard/environment/docker-compose.yaml
index acda3d0211..406844086e 100644
--- a/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-goal-flat-stove-on-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-privileged/README.md b/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-privileged/README.md
index 6bf8d3cd30..6768eacd47 100644
--- a/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-privileged/README.md
+++ b/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/receptacle_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-task-goal-t08-i02-receptacle_relocation-d1-p195`: a Franka Panda arm at a table, instructed **"Put the wine bottle on the plate."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-privileged/environment/Dockerfile b/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-privileged/tests/Dockerfile b/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-standard/README.md b/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-standard/README.md
index 3c19b040e4..458947e1db 100644
--- a/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-standard/README.md
+++ b/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/receptacle_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-task-goal-t08-i02-receptacle_relocation-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Put the wine bottle on the plate."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-standard/environment/docker-compose.yaml
index 444ed12914..20ac7f94e3 100644
--- a/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-goal-wine-bottle-on-plate-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-privileged/README.md b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-privileged/README.md
index 8be22ac997..d615b66f3e 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-privileged/README.md
+++ b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/camera_shift` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-view-occlusion-goal-t09-i00-camera_shift-d0-p195`: a Franka Panda arm at a table, instructed **"Put the wine bottle on the rack."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-privileged/environment/Dockerfile b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-privileged/tests/Dockerfile b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-standard/README.md b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-standard/README.md
index 1626929dfa..4fac6bc1d6 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-standard/README.md
+++ b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/camera_shift` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-view-occlusion-goal-t09-i00-camera_shift-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Put the wine bottle on the rack."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-standard/environment/docker-compose.yaml
index fd2ac5e590..c977dd64b0 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-camera-shift-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-privileged/README.md b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-privileged/README.md
index 599f3a8889..7801cc3997 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-privileged/README.md
+++ b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/obstacle_insertion` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-texture-goal-t09-i08-obstacle_insertion-d0-p195`: a Franka Panda arm at a table, instructed **"Put the wine bottle on the rack."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-privileged/environment/Dockerfile b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-privileged/tests/Dockerfile b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-standard/README.md b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-standard/README.md
index 801fbd3ea4..ada4faae20 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-standard/README.md
+++ b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/obstacle_insertion` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-texture-goal-t09-i08-obstacle_insertion-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Put the wine bottle on the rack."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-standard/environment/docker-compose.yaml
index fd2ac5e590..c977dd64b0 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-obstacle-insertion-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-privileged/README.md b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-privileged/README.md
index c96c8147a8..7ba65587c4 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-privileged/README.md
+++ b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/visual_theme_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-view-occlusion-goal-t09-i07-visual_theme_switch-d1-p195`: a Franka Panda arm at a table, instructed **"Put the wine bottle on the rack."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-privileged/environment/Dockerfile b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-privileged/tests/Dockerfile b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-standard/README.md b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-standard/README.md
index 813eadf3f4..a5a2cd1c6f 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-standard/README.md
+++ b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/visual_theme_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-view-occlusion-goal-t09-i07-visual_theme_switch-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Put the wine bottle on the rack."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-standard/environment/docker-compose.yaml
index fd2ac5e590..c977dd64b0 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-goal-wine-bottle-on-wine-rack-top-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-privileged/README.md b/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-privileged/README.md
index 9aea62a961..8db20510b9 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-privileged/README.md
+++ b/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/sensor_noise_onset` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-semantic-goal-t02-i03-sensor_noise_onset-d1-p195`: a Franka Panda arm at a table, instructed **"Place the wine bottle on top of the cabinet."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-privileged/environment/Dockerfile b/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-privileged/tests/Dockerfile b/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-standard/README.md b/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-standard/README.md
index f00dd36786..308a3263ae 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-standard/README.md
+++ b/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/sensor_noise_onset` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-semantic-goal-t02-i03-sensor_noise_onset-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Place the wine bottle on top of the cabinet."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-standard/environment/docker-compose.yaml
index 8fafbe27ce..8a6e97d4d5 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-goal-wine-bottle-on-wooden-cabinet-top-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-privileged/README.md b/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-privileged/README.md
index 8e3ef07ce8..20925eeb65 100644
--- a/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-privileged/README.md
+++ b/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/camera_shift` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-goal-t07-i04-camera_shift-d1-p195`: a Franka Panda arm at a table, instructed **"Turn on the stove."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-privileged/environment/Dockerfile b/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-privileged/tests/Dockerfile b/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-standard/README.md b/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-standard/README.md
index 1c4003ea56..a3767f0d41 100644
--- a/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-standard/README.md
+++ b/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_goal/camera_shift` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-goal-t07-i04-camera_shift-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Turn on the stove."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-standard/environment/docker-compose.yaml
index acda3d0211..406844086e 100644
--- a/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-goal-yellow-stove-on-camera-shift-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-privileged/README.md b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-privileged/README.md
index b362e71fb2..80e6105dd9 100644
--- a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-privileged/README.md
+++ b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/receptacle_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-camera-view-angle-10-t07-i01-receptacle_relocation-d0-p195`: a Franka Panda arm at a table, instructed **"Put both the alphabet soup and the cream cheese box in the basket."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-privileged/environment/Dockerfile b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-privileged/tests/Dockerfile b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-standard/README.md b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-standard/README.md
index 1d16e583bf..24fa5737ac 100644
--- a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-standard/README.md
+++ b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/receptacle_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-camera-view-angle-10-t07-i01-receptacle_relocation-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Put both the alphabet soup and the cream cheese box in the basket."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-standard/environment/docker-compose.yaml
index cc24758785..9ec94ff6e3 100644
--- a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-privileged/README.md b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-privileged/README.md
index ff14a117f5..d70b5eb332 100644
--- a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-privileged/README.md
+++ b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/target_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-camera-view-angle-10-t07-i04-target_relocation-d1-p195`: a Franka Panda arm at a table, instructed **"Put both the alphabet soup and the cream cheese box in the basket."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-privileged/environment/Dockerfile b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-privileged/tests/Dockerfile b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-standard/README.md b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-standard/README.md
index 39017ef688..fff411c66c 100644
--- a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-standard/README.md
+++ b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/target_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-camera-view-angle-10-t07-i04-target_relocation-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Put both the alphabet soup and the cream cheese box in the basket."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-standard/environment/docker-compose.yaml
index cc24758785..9ec94ff6e3 100644
--- a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-long-alphabet-soup-and-cream-cheese-in-basket-target-relocation-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-privileged/README.md b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-privileged/README.md
index 59f42f209f..1a573633e2 100644
--- a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-privileged/README.md
+++ b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/distractor_burst` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-initial-pose-position-angle-10-t00-i01-distractor_burst-d0-p195`: a Franka Panda arm at a table, instructed **"Put both the alphabet soup and the tomato sauce in the basket."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-privileged/environment/Dockerfile b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-privileged/tests/Dockerfile b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-standard/README.md b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-standard/README.md
index 59fda90912..a244f9c4fb 100644
--- a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-standard/README.md
+++ b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/distractor_burst` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-initial-pose-position-angle-10-t00-i01-distractor_burst-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Put both the alphabet soup and the tomato sauce in the basket."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-standard/environment/docker-compose.yaml
index 5ed4404253..22c3940178 100644
--- a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-privileged/README.md b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-privileged/README.md
index da44bf3f1f..ae5b586e30 100644
--- a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-privileged/README.md
+++ b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/receptacle_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-initial-pose-position-angle-10-t00-i02-receptacle_relocation-d0-p195`: a Franka Panda arm at a table, instructed **"Put both the alphabet soup and the tomato sauce in the basket."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-privileged/environment/Dockerfile b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-privileged/tests/Dockerfile b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-standard/README.md b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-standard/README.md
index a593da9c47..2ed5ee4af6 100644
--- a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-standard/README.md
+++ b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/receptacle_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-initial-pose-position-angle-10-t00-i02-receptacle_relocation-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Put both the alphabet soup and the tomato sauce in the basket."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-standard/environment/docker-compose.yaml
index 5ed4404253..22c3940178 100644
--- a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-privileged/README.md b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-privileged/README.md
index 370358fd63..88b5cf2e5d 100644
--- a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-privileged/README.md
+++ b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/sensor_noise_onset` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-texture-10-t00-i02-sensor_noise_onset-d0-p195`: a Franka Panda arm at a table, instructed **"Put both the alphabet soup and the tomato sauce in the basket."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-privileged/environment/Dockerfile b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-privileged/tests/Dockerfile b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-standard/README.md b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-standard/README.md
index c82b3850b5..370ff47f5d 100644
--- a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-standard/README.md
+++ b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/sensor_noise_onset` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-texture-10-t00-i02-sensor_noise_onset-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Put both the alphabet soup and the tomato sauce in the basket."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-standard/environment/docker-compose.yaml
index 5ed4404253..22c3940178 100644
--- a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-long-alphabet-soup-and-tomato-sauce-in-basket-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-privileged/README.md b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-privileged/README.md
index a8fb8af676..be2dd3a27f 100644
--- a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-privileged/README.md
+++ b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/obstacle_insertion` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-10-t03-i02-obstacle_insertion-d0-p195`: a Franka Panda arm at a table, instructed **"Put the black bowl in the bottom drawer of the cabinet and close it."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-privileged/environment/Dockerfile b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-privileged/tests/Dockerfile b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-standard/README.md b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-standard/README.md
index 7b1d62fc83..fe3d3b0d68 100644
--- a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-standard/README.md
+++ b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/obstacle_insertion` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-10-t03-i02-obstacle_insertion-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Put the black bowl in the bottom drawer of the cabinet and close it."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-standard/environment/docker-compose.yaml
index d5d59e55b5..5ff3827105 100644
--- a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-privileged/README.md b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-privileged/README.md
index 81cc14e4db..ec3929f53f 100644
--- a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-privileged/README.md
+++ b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/obstacle_insertion` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-10-t03-i06-obstacle_insertion-d1-p195`: a Franka Panda arm at a table, instructed **"Put the black bowl in the bottom drawer of the cabinet and close it."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-privileged/environment/Dockerfile b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-privileged/environment/Dockerfile
+++ b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-privileged/environment/lmx_tool.py b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-privileged/tests/Dockerfile b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-privileged/tests/Dockerfile
+++ b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-privileged/tests/lmx_tool.py b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-standard/README.md b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-standard/README.md
index eb6e1f77b2..6527ed8371 100644
--- a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-standard/README.md
+++ b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/obstacle_insertion` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-10-t03-i06-obstacle_insertion-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Put the black bowl in the bottom drawer of the cabinet and close it."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-standard/environment/docker-compose.yaml b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-standard/environment/docker-compose.yaml
index d5d59e55b5..5ff3827105 100644
--- a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-standard/environment/sim/lmx_tool.py b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-long-black-bowl-in-wooden-cabinet-bottom-closed-obstacle-insertion-i01-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-privileged/README.md b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-privileged/README.md
index 3090ba6fc5..5b4ea7daec 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-privileged/README.md
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/camera_shift` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-camera-view-angle-10-t04-i08-camera_shift-d1-p195`: a Franka Panda arm at a table, instructed **"Put the white mug on the left plate and put the yellow and white mug on the right plate."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-privileged/environment/Dockerfile b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-privileged/tests/Dockerfile b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-standard/README.md b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-standard/README.md
index 5134d22cce..137d87f797 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-standard/README.md
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/camera_shift` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-camera-view-angle-10-t04-i08-camera_shift-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Put the white mug on the left plate and put the yellow and white mug on the right plate."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-standard/environment/docker-compose.yaml
index 5fa79ecf3b..01526e8c91 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-camera-shift-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-privileged/README.md b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-privileged/README.md
index 777c663ba1..53bc21da35 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-privileged/README.md
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/illumination_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-camera-view-angle-10-t04-i09-illumination_switch-d0-p195`: a Franka Panda arm at a table, instructed **"Put the white mug on the left plate and put the yellow and white mug on the right plate."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-privileged/environment/Dockerfile b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-privileged/tests/Dockerfile b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-standard/README.md b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-standard/README.md
index 5d65cf3ffd..8ee565e607 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-standard/README.md
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/illumination_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-camera-view-angle-10-t04-i09-illumination_switch-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Put the white mug on the left plate and put the yellow and white mug on the right plate."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-standard/environment/docker-compose.yaml
index 5fa79ecf3b..01526e8c91 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-illumination-switch-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-privileged/README.md b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-privileged/README.md
index 9ef7a68a0c..70594d299c 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-privileged/README.md
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/visual_theme_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-position-10-t04-i00-visual_theme_switch-d1-p195`: a Franka Panda arm at a table, instructed **"Put the white mug on the left plate and put the yellow and white mug on the right plate."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-privileged/environment/Dockerfile b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-privileged/tests/Dockerfile b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-standard/README.md b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-standard/README.md
index 39b0f34c08..a4acff8e84 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-standard/README.md
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/visual_theme_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-position-10-t04-i00-visual_theme_switch-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Put the white mug on the left plate and put the yellow and white mug on the right plate."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-standard/environment/docker-compose.yaml
index 5fa79ecf3b..01526e8c91 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-privileged/README.md b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-privileged/README.md
index 38150a58cb..13959d3656 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-privileged/README.md
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/visual_theme_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-semantic-10-t04-i09-visual_theme_switch-d1-p195`: a Franka Panda arm at a table, instructed **"Place white mug on left plate and yellow-white mug on right plate."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-privileged/environment/Dockerfile b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-privileged/environment/Dockerfile
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-privileged/environment/lmx_tool.py b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-privileged/tests/Dockerfile b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-privileged/tests/Dockerfile
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-privileged/tests/lmx_tool.py b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-standard/README.md b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-standard/README.md
index f14d49ad8c..d2235c34cd 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-standard/README.md
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/visual_theme_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-semantic-10-t04-i09-visual_theme_switch-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Place white mug on left plate and yellow-white mug on right plate."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-standard/environment/docker-compose.yaml b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-standard/environment/docker-compose.yaml
index f9640066bf..bf99136547 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-standard/environment/sim/lmx_tool.py b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-long-porcelain-mug-and-white-yellow-mug-on-plate-visual-theme-switch-i01-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-privileged/README.md b/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-privileged/README.md
index e2ade501a3..ba05e35810 100644
--- a/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-privileged/README.md
+++ b/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/sensor_noise_onset` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-10-t06-i09-sensor_noise_onset-d0-p195`: a Franka Panda arm at a table, instructed **"Put the white mug on the plate and put the chocolate pudding to the right of the plate."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-privileged/environment/Dockerfile b/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-privileged/tests/Dockerfile b/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-standard/README.md b/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-standard/README.md
index e9f7a3f418..c7ef64c65d 100644
--- a/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-standard/README.md
+++ b/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/sensor_noise_onset` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-10-t06-i09-sensor_noise_onset-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Put the white mug on the plate and put the chocolate pudding to the right of the plate."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-standard/environment/docker-compose.yaml
index 4b92ee0651..fc335c3e61 100644
--- a/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-long-white-yellow-mug-and-green-chocolate-pudding-on-yellow-plate-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-privileged/README.md b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-privileged/README.md
index 7b92e3d24f..963dc589f4 100644
--- a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-privileged/README.md
+++ b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/camera_shift` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-task-10-t05-i04-camera_shift-d1-p195`: a Franka Panda arm at a table, instructed **"Pick up the cup and place it in the back compartment of the caddy."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-privileged/environment/Dockerfile b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-privileged/tests/Dockerfile b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-standard/README.md b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-standard/README.md
index bf278fed1c..a71048f957 100644
--- a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-standard/README.md
+++ b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/camera_shift` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-task-10-t05-i04-camera_shift-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick up the cup and place it in the back compartment of the caddy."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-standard/environment/docker-compose.yaml
index cdb1bc25cb..4299fb63ed 100644
--- a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-camera-shift-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-privileged/README.md b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-privileged/README.md
index e67b25b312..bf09de3636 100644
--- a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-privileged/README.md
+++ b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/illumination_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-task-10-t05-i00-illumination_switch-d1-p195`: a Franka Panda arm at a table, instructed **"Pick up the cup and place it in the back compartment of the caddy."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-privileged/environment/Dockerfile b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-privileged/tests/Dockerfile b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-standard/README.md b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-standard/README.md
index 67d979fb8e..956fde00fe 100644
--- a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-standard/README.md
+++ b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_10/illumination_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-task-10-t05-i00-illumination_switch-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick up the cup and place it in the back compartment of the caddy."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-standard/environment/docker-compose.yaml
index cdb1bc25cb..4299fb63ed 100644
--- a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-long-white-yellow-mug-in-desk-caddy-back-illumination-switch-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-privileged/README.md b/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-privileged/README.md
index 8d4a1f6d07..388009911f 100644
--- a/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-privileged/README.md
+++ b/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/receptacle_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-texture-object-t00-i08-receptacle_relocation-d0-p195`: a Franka Panda arm at a table, instructed **"Pick the alphabet soup and place it in the basket."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-privileged/environment/Dockerfile b/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-privileged/tests/Dockerfile b/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-standard/README.md b/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-standard/README.md
index c8e8dd8f26..2471976d5a 100644
--- a/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-standard/README.md
+++ b/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/receptacle_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-texture-object-t00-i08-receptacle_relocation-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the alphabet soup and place it in the basket."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-standard/environment/docker-compose.yaml
index 838d9e4edd..49b70a7735 100644
--- a/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-object-alphabet-soup-in-basket-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-privileged/README.md b/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-privileged/README.md
index e2bacb4149..661d233329 100644
--- a/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-privileged/README.md
+++ b/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/target_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-shape-object-t00-i03-target_relocation-d0-p195`: a Franka Panda arm at a table, instructed **"Pick the alphabet soup and place it in the basket."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-privileged/environment/Dockerfile b/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-privileged/tests/Dockerfile b/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-standard/README.md b/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-standard/README.md
index 7928a0480b..3cbf5f8994 100644
--- a/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-standard/README.md
+++ b/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/target_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-shape-object-t00-i03-target_relocation-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the alphabet soup and place it in the basket."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-standard/environment/docker-compose.yaml
index 838d9e4edd..49b70a7735 100644
--- a/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-object-alphabet-soup-in-basket-target-relocation-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-privileged/README.md b/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-privileged/README.md
index 8d1a7edfa2..088de9caf0 100644
--- a/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-privileged/README.md
+++ b/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/visual_theme_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-initial-pose-position-angle-object-t00-i01-visual_theme_switch-d1-p195`: a Franka Panda arm at a table, instructed **"Pick the alphabet soup and place it in the basket."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-privileged/environment/Dockerfile b/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-privileged/tests/Dockerfile b/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-standard/README.md b/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-standard/README.md
index 6b150caf8c..d0c671818a 100644
--- a/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-standard/README.md
+++ b/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/visual_theme_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-initial-pose-position-angle-object-t00-i01-visual_theme_switch-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the alphabet soup and place it in the basket."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-standard/environment/docker-compose.yaml
index 838d9e4edd..49b70a7735 100644
--- a/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-object-alphabet-soup-in-basket-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-privileged/README.md b/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-privileged/README.md
index bd74b1b252..f563a8a260 100644
--- a/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-privileged/README.md
+++ b/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/distractor_burst` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-initial-pose-position-angle-object-t06-i02-distractor_burst-d1-p195`: a Franka Panda arm at a table, instructed **"Pick the butter and place it in the basket."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-privileged/environment/Dockerfile b/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-privileged/tests/Dockerfile b/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-standard/README.md b/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-standard/README.md
index c7cab38f9d..af8a7ca0a7 100644
--- a/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-standard/README.md
+++ b/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/distractor_burst` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-initial-pose-position-angle-object-t06-i02-distractor_burst-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the butter and place it in the basket."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-standard/environment/docker-compose.yaml
index 24a5a2ce64..295546e373 100644
--- a/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-object-butter-in-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-privileged/README.md b/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-privileged/README.md
index cb83efc66a..9973320ae0 100644
--- a/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-privileged/README.md
+++ b/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/receptacle_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-initial-pose-position-angle-object-t06-i08-receptacle_relocation-d0-p195`: a Franka Panda arm at a table, instructed **"Pick the butter and place it in the basket."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-privileged/environment/Dockerfile b/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-privileged/tests/Dockerfile b/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-standard/README.md b/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-standard/README.md
index b8aa302345..fb5e5ac707 100644
--- a/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-standard/README.md
+++ b/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/receptacle_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-initial-pose-position-angle-object-t06-i08-receptacle_relocation-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the butter and place it in the basket."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-standard/environment/docker-compose.yaml
index 24a5a2ce64..295546e373 100644
--- a/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-object-butter-in-basket-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-privileged/README.md b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-privileged/README.md
index 8d643e7ba9..51b9b8de31 100644
--- a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-privileged/README.md
+++ b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/distractor_burst` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-visual-noise-glare-object-t08-i07-distractor_burst-d1-p195`: a Franka Panda arm at a table, instructed **"Pick the chocolate pudding and place it in the basket."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-privileged/environment/Dockerfile b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-privileged/tests/Dockerfile b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-standard/README.md b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-standard/README.md
index 03b7e71b2e..91dff85951 100644
--- a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-standard/README.md
+++ b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/distractor_burst` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-visual-noise-glare-object-t08-i07-distractor_burst-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the chocolate pudding and place it in the basket."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-standard/environment/docker-compose.yaml
index 3445a2e813..18bf3a9b14 100644
--- a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-privileged/README.md b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-privileged/README.md
index 8533a87510..f8cc5c7966 100644
--- a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-privileged/README.md
+++ b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/distractor_burst` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-semantic-object-t08-i09-distractor_burst-d1-p195`: a Franka Panda arm at a table, instructed **"Lift chocolate pudding and put it in basket."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-privileged/environment/Dockerfile b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-privileged/environment/Dockerfile
+++ b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-privileged/environment/lmx_tool.py b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-privileged/tests/Dockerfile b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-privileged/tests/Dockerfile
+++ b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-privileged/tests/lmx_tool.py b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-standard/README.md b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-standard/README.md
index 3c42460a35..72b719e57f 100644
--- a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-standard/README.md
+++ b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/distractor_burst` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-semantic-object-t08-i09-distractor_burst-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Lift chocolate pudding and put it in basket."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-standard/environment/docker-compose.yaml b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-standard/environment/docker-compose.yaml
index d05165eed2..60e557a0da 100644
--- a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-standard/environment/sim/lmx_tool.py b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-object-chocolate-pudding-in-basket-distractor-burst-i01-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-privileged/README.md b/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-privileged/README.md
index 5ddede10ac..838c654d7a 100644
--- a/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-privileged/README.md
+++ b/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/sensor_noise_onset` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-position-object-t08-i02-sensor_noise_onset-d0-p195`: a Franka Panda arm at a table, instructed **"Pick the chocolate pudding and place it in the basket."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-privileged/environment/Dockerfile b/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-privileged/tests/Dockerfile b/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-standard/README.md b/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-standard/README.md
index 7a74d99551..86b975c3dd 100644
--- a/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-standard/README.md
+++ b/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/sensor_noise_onset` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-position-object-t08-i02-sensor_noise_onset-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the chocolate pudding and place it in the basket."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-standard/environment/docker-compose.yaml
index 3445a2e813..18bf3a9b14 100644
--- a/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-object-chocolate-pudding-in-basket-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-privileged/README.md b/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-privileged/README.md
index 19d22a31a2..caa5890b01 100644
--- a/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-privileged/README.md
+++ b/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/visual_theme_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-visual-noise-glare-object-t01-i07-visual_theme_switch-d0-p195`: a Franka Panda arm at a table, instructed **"Pick the cream cheese and place it in the basket."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-privileged/environment/Dockerfile b/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-privileged/tests/Dockerfile b/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-standard/README.md b/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-standard/README.md
index 5f0c72c8f3..73b6631d74 100644
--- a/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-standard/README.md
+++ b/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/visual_theme_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-visual-noise-glare-object-t01-i07-visual_theme_switch-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the cream cheese and place it in the basket."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-standard/environment/docker-compose.yaml
index 7deeb3b25b..3584430ede 100644
--- a/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-object-cream-cheese-in-basket-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-privileged/README.md b/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-privileged/README.md
index 9a04983db3..53d18ad145 100644
--- a/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-privileged/README.md
+++ b/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/distractor_burst` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-object-t03-i05-distractor_burst-d1-p195`: a Franka Panda arm at a table, instructed **"Pick the bbq sauce and place it in the basket."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-privileged/environment/Dockerfile b/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-privileged/tests/Dockerfile b/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-standard/README.md b/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-standard/README.md
index 9ad489a296..369e0a7ebe 100644
--- a/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-standard/README.md
+++ b/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/distractor_burst` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-object-t03-i05-distractor_burst-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the bbq sauce and place it in the basket."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-standard/environment/docker-compose.yaml
index f9d48e0a29..f4e7e41166 100644
--- a/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-object-green-bbq-sauce-in-red-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-privileged/README.md b/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-privileged/README.md
index fd37611000..9bb6a336ed 100644
--- a/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-privileged/README.md
+++ b/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/camera_shift` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-object-t08-i04-camera_shift-d0-p195`: a Franka Panda arm at a table, instructed **"Pick the chocolate pudding and place it in the basket."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-privileged/environment/Dockerfile b/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-privileged/tests/Dockerfile b/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-standard/README.md b/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-standard/README.md
index 125b717225..92fac6c916 100644
--- a/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-standard/README.md
+++ b/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/camera_shift` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-object-t08-i04-camera_shift-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the chocolate pudding and place it in the basket."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-standard/environment/docker-compose.yaml
index 3445a2e813..18bf3a9b14 100644
--- a/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-object-green-chocolate-pudding-in-red-basket-camera-shift-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-privileged/README.md b/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-privileged/README.md
index 7b8e76c8f0..b5ba378528 100644
--- a/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-privileged/README.md
+++ b/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/distractor_burst` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-view-occlusion-object-t04-i05-distractor_burst-d1-p195`: a Franka Panda arm at a table, instructed **"Pick the ketchup and place it in the basket."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-privileged/environment/Dockerfile b/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-privileged/tests/Dockerfile b/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-standard/README.md b/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-standard/README.md
index 0982d53640..b14e2e1d3c 100644
--- a/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-standard/README.md
+++ b/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/distractor_burst` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-view-occlusion-object-t04-i05-distractor_burst-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the ketchup and place it in the basket."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-standard/environment/docker-compose.yaml
index ef2a17ebd8..7d9d12f3c9 100644
--- a/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-object-ketchup-in-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-milk-in-basket-camera-shift-i00-privileged/README.md b/tasks/libero-max-object-milk-in-basket-camera-shift-i00-privileged/README.md
index 0cd1a2ce89..5af830b0c1 100644
--- a/tasks/libero-max-object-milk-in-basket-camera-shift-i00-privileged/README.md
+++ b/tasks/libero-max-object-milk-in-basket-camera-shift-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/camera_shift` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-task-object-t04-i00-camera_shift-d0-p195`: a Franka Panda arm at a table, instructed **"Pick the milk and place it in the basket."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-milk-in-basket-camera-shift-i00-privileged/environment/Dockerfile b/tasks/libero-max-object-milk-in-basket-camera-shift-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-object-milk-in-basket-camera-shift-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-object-milk-in-basket-camera-shift-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-milk-in-basket-camera-shift-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-object-milk-in-basket-camera-shift-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-milk-in-basket-camera-shift-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-object-milk-in-basket-camera-shift-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-milk-in-basket-camera-shift-i00-privileged/tests/Dockerfile b/tasks/libero-max-object-milk-in-basket-camera-shift-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-object-milk-in-basket-camera-shift-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-object-milk-in-basket-camera-shift-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-milk-in-basket-camera-shift-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-object-milk-in-basket-camera-shift-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-milk-in-basket-camera-shift-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-object-milk-in-basket-camera-shift-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-milk-in-basket-camera-shift-i00-standard/README.md b/tasks/libero-max-object-milk-in-basket-camera-shift-i00-standard/README.md
index bb3c7b9dbe..8b037ae5a9 100644
--- a/tasks/libero-max-object-milk-in-basket-camera-shift-i00-standard/README.md
+++ b/tasks/libero-max-object-milk-in-basket-camera-shift-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/camera_shift` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-task-object-t04-i00-camera_shift-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the milk and place it in the basket."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-milk-in-basket-camera-shift-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-object-milk-in-basket-camera-shift-i00-standard/environment/docker-compose.yaml
index 9008f3e358..cb55a396ab 100644
--- a/tasks/libero-max-object-milk-in-basket-camera-shift-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-object-milk-in-basket-camera-shift-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-object-milk-in-basket-camera-shift-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-object-milk-in-basket-camera-shift-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-milk-in-basket-camera-shift-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-object-milk-in-basket-camera-shift-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-privileged/README.md b/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-privileged/README.md
index 685a75a278..315f038fe8 100644
--- a/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-privileged/README.md
+++ b/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/distractor_burst` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-view-occlusion-object-t07-i01-distractor_burst-d0-p195`: a Franka Panda arm at a table, instructed **"Pick the milk and place it in the basket."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-privileged/environment/Dockerfile b/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-privileged/tests/Dockerfile b/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-standard/README.md b/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-standard/README.md
index 261c23ded8..3a04449e7f 100644
--- a/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-standard/README.md
+++ b/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/distractor_burst` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-view-occlusion-object-t07-i01-distractor_burst-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the milk and place it in the basket."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-standard/environment/docker-compose.yaml
index 9008f3e358..cb55a396ab 100644
--- a/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-object-milk-in-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-privileged/README.md b/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-privileged/README.md
index 38d2d02db2..06f70245f5 100644
--- a/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-privileged/README.md
+++ b/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/illumination_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-task-object-t04-i01-illumination_switch-d0-p195`: a Franka Panda arm at a table, instructed **"Pick the milk and place it in the basket."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-privileged/environment/Dockerfile b/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-privileged/tests/Dockerfile b/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-standard/README.md b/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-standard/README.md
index 64b2fb8a25..d66731f3b5 100644
--- a/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-standard/README.md
+++ b/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/illumination_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-task-object-t04-i01-illumination_switch-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the milk and place it in the basket."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-standard/environment/docker-compose.yaml
index 9008f3e358..cb55a396ab 100644
--- a/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-object-milk-in-basket-illumination-switch-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-milk-in-basket-target-relocation-i00-privileged/README.md b/tasks/libero-max-object-milk-in-basket-target-relocation-i00-privileged/README.md
index a66cec3df3..962f8d9f17 100644
--- a/tasks/libero-max-object-milk-in-basket-target-relocation-i00-privileged/README.md
+++ b/tasks/libero-max-object-milk-in-basket-target-relocation-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/target_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-view-occlusion-object-t07-i07-target_relocation-d0-p195`: a Franka Panda arm at a table, instructed **"Pick the milk and place it in the basket."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-milk-in-basket-target-relocation-i00-privileged/environment/Dockerfile b/tasks/libero-max-object-milk-in-basket-target-relocation-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-object-milk-in-basket-target-relocation-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-object-milk-in-basket-target-relocation-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-milk-in-basket-target-relocation-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-object-milk-in-basket-target-relocation-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-milk-in-basket-target-relocation-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-object-milk-in-basket-target-relocation-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-milk-in-basket-target-relocation-i00-privileged/tests/Dockerfile b/tasks/libero-max-object-milk-in-basket-target-relocation-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-object-milk-in-basket-target-relocation-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-object-milk-in-basket-target-relocation-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-milk-in-basket-target-relocation-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-object-milk-in-basket-target-relocation-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-milk-in-basket-target-relocation-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-object-milk-in-basket-target-relocation-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-milk-in-basket-target-relocation-i00-standard/README.md b/tasks/libero-max-object-milk-in-basket-target-relocation-i00-standard/README.md
index 03cc0bc41c..e4213c15fc 100644
--- a/tasks/libero-max-object-milk-in-basket-target-relocation-i00-standard/README.md
+++ b/tasks/libero-max-object-milk-in-basket-target-relocation-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/target_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-view-occlusion-object-t07-i07-target_relocation-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the milk and place it in the basket."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-milk-in-basket-target-relocation-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-object-milk-in-basket-target-relocation-i00-standard/environment/docker-compose.yaml
index 9008f3e358..cb55a396ab 100644
--- a/tasks/libero-max-object-milk-in-basket-target-relocation-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-object-milk-in-basket-target-relocation-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-object-milk-in-basket-target-relocation-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-object-milk-in-basket-target-relocation-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-milk-in-basket-target-relocation-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-object-milk-in-basket-target-relocation-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-privileged/README.md b/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-privileged/README.md
index 056400d046..854a86a4da 100644
--- a/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-privileged/README.md
+++ b/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/distractor_burst` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-shape-object-t09-i04-distractor_burst-d0-p195`: a Franka Panda arm at a table, instructed **"Pick the orange juice and place it in the basket."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-privileged/environment/Dockerfile b/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-privileged/tests/Dockerfile b/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-standard/README.md b/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-standard/README.md
index 97a379bb81..25e1b753dd 100644
--- a/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-standard/README.md
+++ b/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/distractor_burst` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-shape-object-t09-i04-distractor_burst-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the orange juice and place it in the basket."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-standard/environment/docker-compose.yaml
index fcc248ce88..eb6538f094 100644
--- a/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-object-orange-juice-in-basket-distractor-burst-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-privileged/README.md b/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-privileged/README.md
index 9682a2eb7b..b7f8383c0b 100644
--- a/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-privileged/README.md
+++ b/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/illumination_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-texture-object-t09-i05-illumination_switch-d1-p195`: a Franka Panda arm at a table, instructed **"Pick the orange juice and place it in the basket."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-privileged/environment/Dockerfile b/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-privileged/tests/Dockerfile b/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-standard/README.md b/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-standard/README.md
index 205f1d0685..385b9f9a1a 100644
--- a/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-standard/README.md
+++ b/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/illumination_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-texture-object-t09-i05-illumination_switch-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the orange juice and place it in the basket."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-standard/environment/docker-compose.yaml
index fcc248ce88..eb6538f094 100644
--- a/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-object-orange-juice-in-basket-illumination-switch-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-privileged/README.md b/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-privileged/README.md
index f1a73a035b..91ffdd1b0b 100644
--- a/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-privileged/README.md
+++ b/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/sensor_noise_onset` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-position-object-t02-i06-sensor_noise_onset-d0-p195`: a Franka Panda arm at a table, instructed **"Pick the salad dressing and place it in the basket."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-privileged/environment/Dockerfile b/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-privileged/tests/Dockerfile b/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-standard/README.md b/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-standard/README.md
index 8466574dc6..d406891261 100644
--- a/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-standard/README.md
+++ b/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_object/sensor_noise_onset` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-position-object-t02-i06-sensor_noise_onset-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the salad dressing and place it in the basket."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-standard/environment/docker-compose.yaml
index 1c66dac397..9b3b956189 100644
--- a/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-object-salad-dressing-in-basket-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-privileged/README.md b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-privileged/README.md
index 879381a2ec..5e67d4c6cb 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-privileged/README.md
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/camera_shift` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-task-spatial-t03-i03-camera_shift-d1-p195`: a Franka Panda arm at a table, instructed **"Pick the akita black bowl on the top of the cabinet and place it on the plate."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-privileged/environment/Dockerfile b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-privileged/tests/Dockerfile b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-standard/README.md b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-standard/README.md
index 832fabe2f0..5b0647de82 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-standard/README.md
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/camera_shift` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-task-spatial-t03-i03-camera_shift-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the akita black bowl on the top of the cabinet and place it on the plate."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-standard/environment/docker-compose.yaml
index b51a8f2157..7be3d4acdc 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-privileged/README.md b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-privileged/README.md
index e486ee1065..b244ea6301 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-privileged/README.md
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/camera_shift` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-position-spatial-t07-i01-camera_shift-d0-p195`: a Franka Panda arm at a table, instructed **"Pick the akita black bowl on the stove and place it on the plate."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-privileged/environment/Dockerfile b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-privileged/environment/Dockerfile
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-privileged/environment/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-privileged/tests/Dockerfile b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-privileged/tests/Dockerfile
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-privileged/tests/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-standard/README.md b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-standard/README.md
index 1e3674895f..ebdca631fc 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-standard/README.md
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/camera_shift` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-position-spatial-t07-i01-camera_shift-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the akita black bowl on the stove and place it on the plate."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-standard/environment/docker-compose.yaml b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-standard/environment/docker-compose.yaml
index 5de1b8f8a6..73d8f2fa07 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-standard/environment/sim/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-camera-shift-i01-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-privileged/README.md b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-privileged/README.md
index 8c4fbd0758..02a12c1c5e 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-privileged/README.md
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/illumination_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-shape-spatial-t01-i01-illumination_switch-d0-p195`: a Franka Panda arm at a table, instructed **"Pick the akita black bowl next to the ramekin and place it on the plate."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-privileged/environment/Dockerfile b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-privileged/tests/Dockerfile b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-standard/README.md b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-standard/README.md
index cf8fc74ad6..d6eec1f8bf 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-standard/README.md
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/illumination_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-shape-spatial-t01-i01-illumination_switch-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the akita black bowl next to the ramekin and place it on the plate."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-standard/environment/docker-compose.yaml
index 86b10337bf..7ecf48ce3b 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-privileged/README.md b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-privileged/README.md
index b28e58afd3..85f47b963a 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-privileged/README.md
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/illumination_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-semantic-spatial-t05-i06-illumination_switch-d0-p195`: a Franka Panda arm at a table, instructed **"Grab black bowl on ramekin and set it on plate."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-privileged/environment/Dockerfile b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-privileged/environment/Dockerfile
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-privileged/environment/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-privileged/tests/Dockerfile b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-privileged/tests/Dockerfile
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-privileged/tests/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-standard/README.md b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-standard/README.md
index 9f650e80e6..6dce49498a 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-standard/README.md
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/illumination_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-semantic-spatial-t05-i06-illumination_switch-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Grab black bowl on ramekin and set it on plate."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-standard/environment/docker-compose.yaml b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-standard/environment/docker-compose.yaml
index 8961a5392b..e9e3b400a5 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-standard/environment/sim/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-illumination-switch-i01-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-privileged/README.md b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-privileged/README.md
index 5e3596ce10..7a8ed909cc 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-privileged/README.md
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/obstacle_insertion` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-semantic-spatial-t00-i02-obstacle_insertion-d1-p195`: a Franka Panda arm at a table, instructed **"Lift the black bowl between the plate and ramekin and set it on the plate."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-privileged/environment/Dockerfile b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-privileged/tests/Dockerfile b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-standard/README.md b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-standard/README.md
index d3ace28644..1d666622d1 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-standard/README.md
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/obstacle_insertion` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-semantic-spatial-t00-i02-obstacle_insertion-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Lift the black bowl between the plate and ramekin and set it on the plate."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-standard/environment/docker-compose.yaml
index 497cd883c5..f3a9632a15 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-privileged/README.md b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-privileged/README.md
index e1578389bc..34fc8bc606 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-privileged/README.md
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/obstacle_insertion` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-semantic-spatial-t06-i08-obstacle_insertion-d0-p195`: a Franka Panda arm at a table, instructed **"Grab the black bowl beside the cookie box and set it on plate."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-privileged/environment/Dockerfile b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-privileged/environment/Dockerfile
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-privileged/environment/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-privileged/tests/Dockerfile b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-privileged/tests/Dockerfile
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-privileged/tests/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-standard/README.md b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-standard/README.md
index 1d9d9d7bfb..f6c6320526 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-standard/README.md
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/obstacle_insertion` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-semantic-spatial-t06-i08-obstacle_insertion-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Grab the black bowl beside the cookie box and set it on plate."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-standard/environment/docker-compose.yaml b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-standard/environment/docker-compose.yaml
index 48109f5e04..c72fb12f41 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-standard/environment/sim/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-obstacle-insertion-i01-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/README.md b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/README.md
index f939acda40..85a5a37f0a 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/README.md
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/receptacle_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-camera-view-angle-spatial-t09-i06-receptacle_relocation-d1-p195`: a Franka Panda arm at a table, instructed **"Pick the akita black bowl on the wooden cabinet and place it on the plate."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/environment/Dockerfile b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/tests/Dockerfile b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-standard/README.md b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-standard/README.md
index 311142e146..4d0c32d520 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-standard/README.md
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/receptacle_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-camera-view-angle-spatial-t09-i06-receptacle_relocation-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the akita black bowl on the wooden cabinet and place it on the plate."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-standard/environment/docker-compose.yaml
index f2e2c03641..79e9fcdd08 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-privileged/README.md b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-privileged/README.md
index ac9650ba68..631d943bda 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-privileged/README.md
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/receptacle_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-view-occlusion-spatial-t08-i02-receptacle_relocation-d1-p195`: a Franka Panda arm at a table, instructed **"Pick the akita black bowl next to the plate and place it on the plate."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-privileged/environment/Dockerfile b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-privileged/environment/Dockerfile
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-privileged/environment/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-privileged/tests/Dockerfile b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-privileged/tests/Dockerfile
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-privileged/tests/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-standard/README.md b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-standard/README.md
index ad4fb067a6..b27f18f76b 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-standard/README.md
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/receptacle_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-view-occlusion-spatial-t08-i02-receptacle_relocation-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the akita black bowl next to the plate and place it on the plate."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-standard/environment/docker-compose.yaml b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-standard/environment/docker-compose.yaml
index e05ad79598..1cde5bf9aa 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-standard/environment/sim/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-receptacle-relocation-i01-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-privileged/README.md b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-privileged/README.md
index f47c18afcb..82bb72b9d9 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-privileged/README.md
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/sensor_noise_onset` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-visual-noise-glare-spatial-t01-i09-sensor_noise_onset-d1-p195`: a Franka Panda arm at a table, instructed **"Pick the akita black bowl next to the ramekin and place it on the plate."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-privileged/environment/Dockerfile b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-privileged/tests/Dockerfile b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-standard/README.md b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-standard/README.md
index 924e3e272e..d3aa5fae24 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-standard/README.md
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/sensor_noise_onset` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-visual-noise-glare-spatial-t01-i09-sensor_noise_onset-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the akita black bowl next to the ramekin and place it on the plate."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-standard/environment/docker-compose.yaml
index 86b10337bf..7ecf48ce3b 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-privileged/README.md b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-privileged/README.md
index 3bdc5f6880..6be21370a7 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-privileged/README.md
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/sensor_noise_onset` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-initial-pose-position-angle-spatial-t03-i00-sensor_noise_onset-d1-p195`: a Franka Panda arm at a table, instructed **"Pick the akita black bowl on the cookies box and place it on the plate."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-privileged/environment/Dockerfile b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-privileged/environment/Dockerfile
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-privileged/environment/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-privileged/tests/Dockerfile b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-privileged/tests/Dockerfile
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-privileged/tests/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-standard/README.md b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-standard/README.md
index b4aa35dddb..2b15676a72 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-standard/README.md
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/sensor_noise_onset` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-initial-pose-position-angle-spatial-t03-i00-sensor_noise_onset-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the akita black bowl on the cookies box and place it on the plate."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-standard/environment/docker-compose.yaml b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-standard/environment/docker-compose.yaml
index a7c73a6512..d528991985 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-standard/environment/sim/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-sensor-noise-onset-i01-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-privileged/README.md b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-privileged/README.md
index d878ca2bf4..cf2a9d92f4 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-privileged/README.md
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/target_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-initial-pose-position-angle-spatial-t06-i01-target_relocation-d0-p195`: a Franka Panda arm at a table, instructed **"Pick the akita black bowl next to the cookies box and place it on the plate."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-privileged/environment/Dockerfile b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-privileged/tests/Dockerfile b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-standard/README.md b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-standard/README.md
index 1ffc201f54..d08fea63da 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-standard/README.md
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/target_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-initial-pose-position-angle-spatial-t06-i01-target_relocation-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the akita black bowl next to the cookies box and place it on the plate."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-standard/environment/docker-compose.yaml
index 4357ca97b3..cd7ddaaaab 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-privileged/README.md b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-privileged/README.md
index 5c4f3d99d1..e507f3a090 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-privileged/README.md
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/target_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-camera-view-angle-spatial-t06-i03-target_relocation-d0-p195`: a Franka Panda arm at a table, instructed **"Pick the akita black bowl next to the cookies box and place it on the plate."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-privileged/environment/Dockerfile b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-privileged/environment/Dockerfile
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-privileged/environment/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-privileged/tests/Dockerfile b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-privileged/tests/Dockerfile
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-privileged/tests/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-standard/README.md b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-standard/README.md
index a2864911aa..8d3fd1ab94 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-standard/README.md
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/target_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-camera-view-angle-spatial-t06-i03-target_relocation-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the akita black bowl next to the cookies box and place it on the plate."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-standard/environment/docker-compose.yaml b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-standard/environment/docker-compose.yaml
index 4357ca97b3..cd7ddaaaab 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-standard/environment/sim/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-target-relocation-i01-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-privileged/README.md b/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-privileged/README.md
index 29c99f54d3..5651c37510 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-privileged/README.md
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/visual_theme_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-semantic-spatial-t08-i06-visual_theme_switch-d1-p195`: a Franka Panda arm at a table, instructed **"Pick the bowl beside the plate and put it on plate."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-privileged/environment/Dockerfile b/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-privileged/tests/Dockerfile b/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-standard/README.md b/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-standard/README.md
index ce69400225..d812e24bf9 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-standard/README.md
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/visual_theme_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-semantic-spatial-t08-i06-visual_theme_switch-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the bowl beside the plate and put it on plate."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-standard/environment/docker-compose.yaml
index 2ec5efe4d5..bf58747dc8 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-spatial-akita-black-bowl-on-plate-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-privileged/README.md b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-privileged/README.md
index 98084bf76e..13cdbf6bc6 100644
--- a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-privileged/README.md
+++ b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/obstacle_insertion` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-spatial-t00-i08-obstacle_insertion-d1-p195`: a Franka Panda arm at a table, instructed **"Pick the akita black bowl between the plate and the ramekin and place it on the plate."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-privileged/environment/Dockerfile b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-privileged/tests/Dockerfile b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-standard/README.md b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-standard/README.md
index e522a9a2c3..3df566be06 100644
--- a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-standard/README.md
+++ b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/obstacle_insertion` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-spatial-t00-i08-obstacle_insertion-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the akita black bowl between the plate and the ramekin and place it on the plate."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-standard/environment/docker-compose.yaml
index 399fed974f..de46b032aa 100644
--- a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-obstacle-insertion-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-privileged/README.md b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-privileged/README.md
index 73271a888f..d59bf688bc 100644
--- a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-privileged/README.md
+++ b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/target_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-spatial-t00-i09-target_relocation-d0-p195`: a Franka Panda arm at a table, instructed **"Pick the akita black bowl between the plate and the ramekin and place it on the plate."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-privileged/environment/Dockerfile b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-privileged/tests/Dockerfile b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-standard/README.md b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-standard/README.md
index bcec7b345f..cf01fe43de 100644
--- a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-standard/README.md
+++ b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/target_relocation` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-spatial-t00-i09-target_relocation-d0-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the akita black bowl between the plate and the ramekin and place it on the plate."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-standard/environment/docker-compose.yaml
index 399fed974f..de46b032aa 100644
--- a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-target-relocation-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-privileged/README.md b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-privileged/README.md
index 569495deaa..c01398a776 100644
--- a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-privileged/README.md
+++ b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-privileged/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/visual_theme_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-spatial-t02-i01-visual_theme_switch-d1-p195`: a Franka Panda arm at a table, instructed **"Pick the akita black bowl from table center and place it on the plate."**, on a LIBERO-PRO variant
@@ -47,4 +47,12 @@ reward 0; the instance is not solved at the start.
### Provenance
Generated by `scripts/libero-max/generate.py` from `scripts/libero-max/cases.json` (chosen by
-`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0`).
+`scripts/libero-max/select_cases.py`) and `scripts/libero-max/frozen/` (`freeze.sh`, run in `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1`).
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-privileged/environment/Dockerfile b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-privileged/environment/Dockerfile
index e02bf1645d..3791be135c 100644
--- a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-privileged/environment/Dockerfile
+++ b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-privileged/environment/Dockerfile
@@ -1,5 +1,5 @@
# LIBERO-MAX privileged task: the LIBERO-MAX image, the task's tooling and its frozen instance.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY instance.json /app/instance.json
COPY lmx_tool.py /opt/tools/lmx_tool.py
ENV PYTHONPATH=/opt/tools:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-privileged/environment/lmx_tool.py b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-privileged/environment/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-privileged/environment/lmx_tool.py
+++ b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-privileged/environment/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-privileged/tests/Dockerfile b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-privileged/tests/Dockerfile
index 2022f06eef..039880e5b2 100644
--- a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-privileged/tests/Dockerfile
+++ b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-privileged/tests/Dockerfile
@@ -1,6 +1,6 @@
# Separate verifier sandbox: the same image with the verifier's own copies of the tooling and the frozen instance;
# only the declared artifacts (/app/output/) arrive from the agent.
-FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+FROM ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
COPY test.sh grade.py lmx_tool.py instance.json /tests/
RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
ENV PYTHONPATH=/tests:/opt/libero-max/overlay:/opt/libero-max/src
diff --git a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-privileged/tests/lmx_tool.py b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-privileged/tests/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-privileged/tests/lmx_tool.py
+++ b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-privileged/tests/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-standard/README.md b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-standard/README.md
index df91b512a0..9f7521e737 100644
--- a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-standard/README.md
+++ b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-standard/README.md
@@ -9,7 +9,7 @@
| Family / instance | `libero-max/libero_spatial/visual_theme_switch` / seed 195 |
| Oracle | `full` |
| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.0` |
+| Base image | `ghcr.io/mll-lab-nu/eai-libero-max:0.1.1` |
## Task
LIBERO-MAX case `pro-object-spatial-t02-i01-visual_theme_switch-d1-p195` as a robot service: a Franka Panda arm at a table, instructed **"Pick the akita black bowl from table center and place it on the plate."**, on
@@ -39,3 +39,11 @@ is up, or on a simulator error), replays the recorded episode in a fresh process
| Actions | `ee_delta` (7, float64): OSC hand-target delta (1.0 = 0.05 m, 0.5 rad per control step) and gripper |
| Episode cap | 9000 control steps (450 s of robot time; `spec.max_control_steps`, PROTOCOL §4.5 MAY) |
| Resources | 4 CPUs, no GPU (CPU physics, OSMesa rendering) |
+
+### Change Log
+- 2026-10-08: image `eai-libero-max:0.1.1` (`OPENBLAS_CORETYPE=Zen`); the instance, its start-state hash, the reference
+ solution and the pass rule are unchanged, so the task keeps its name. With 0.1.0 the start state did not rebuild on
+ Intel Xeon 8488C hosts (the Session refused with a hash mismatch): the OpenBLAS 0.3.18 bundled with numpy and scipy
+ does not know that CPU and fell back to its generic Prescott kernels, while the instances were frozen with its Zen
+ kernels (AMD 7950X). 0.1.1 pins the Zen kernels; same Python packages and sources. `scripts/libero-max/rebuild_check.sh`
+ (start-state hash and reference replay of all 64 instances): 8488C 0/64 with 0.1.0, 64/64 with 0.1.1; 7950X 64/64.
diff --git a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-standard/environment/docker-compose.yaml b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-standard/environment/docker-compose.yaml
index 1ab1818d2d..7b4c5b752e 100644
--- a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-standard/environment/docker-compose.yaml
+++ b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-standard/environment/docker-compose.yaml
@@ -5,7 +5,7 @@ services:
main:
depends_on: [sim]
sim:
- image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.0
+ image: ghcr.io/mll-lab-nu/eai-libero-max:0.1.1
volumes:
- ./sim:/srv:ro
command: python /srv/server.py
diff --git a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py
index 82fa95636a..10083ab39d 100644
--- a/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py
+++ b/tasks/libero-max-spatial-black-bowl-on-yellow-plate-visual-theme-switch-i00-standard/environment/sim/lmx_tool.py
@@ -92,6 +92,29 @@ def _integration_sha(sim) -> str:
return hashlib.sha256(a.tobytes()).hexdigest()
+def numerics() -> dict:
+ """The CPU-dependent numeric kernels this process uses. The frozen hashes were made with OpenBLAS's Zen kernels
+ (OPENBLAS_CORETYPE=Zen, set in the image: unpinned, OpenBLAS 0.3.18 picks per CPU, e.g. its generic Prescott
+ kernels on Sapphire Rapids) and numpy's AVX-512 math loops, so a CPU without AVX-512 cannot rebuild them."""
+ import ctypes
+
+ out = {"OPENBLAS_CORETYPE": os.environ.get("OPENBLAS_CORETYPE")}
+ try:
+ from numpy.core._multiarray_umath import __cpu_features__ as feats
+
+ out["numpy_avx512_skx"] = bool(feats.get("AVX512_SKX"))
+ with open("/proc/self/maps") as f:
+ libs = sorted({ln.split()[-1] for ln in f if "libopenblas" in ln})
+ for lib in libs:
+ dll = ctypes.CDLL(lib)
+ get = getattr(dll, "openblas_get_corename64_", None) or dll.openblas_get_corename
+ get.restype = ctypes.c_char_p
+ out[Path(lib).name.split("-")[0]] = get().decode()
+ except Exception as exc: # noqa: BLE001 (diagnostics only)
+ out["error"] = repr(exc)[:200]
+ return out
+
+
def build(case: dict):
"""LIBERO-MAX's own path: the LIBERO-PRO task variant, its initial state, the PRO substrate and the event runtime.
Returns (wrapped env, task, robosuite env). Raises if this process already built a simulator."""
@@ -148,8 +171,9 @@ class Session:
self.initial_state_sha = _integration_sha(self.sim)
if check and self.initial_state_sha != self.inst.get("initial_state_sha"):
raise RuntimeError(
- "the frozen instance did not rebuild bit-exactly (different simulator, assets or versions): "
- f"{self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}"
+ "the frozen instance did not rebuild bit-exactly (different simulator, assets, versions or CPU "
+ f"numeric kernels): {self.initial_state_sha[:12]} != {str(self.inst.get('initial_state_sha'))[:12]}; "
+ f"numerics here: {canonical(numerics())} (frozen with OpenBLAS Zen kernels and numpy AVX-512 loops)"
)
self.max_steps = SUITE_MAX_STEPS[self.case["task_suite_name"]]
self.actions: list[np.ndarray] = []
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/README.md b/tasks/roboolympics-airhockey-match-i00-standard-realtime/README.md
new file mode 100644
index 0000000000..9f824afef3
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/README.md
@@ -0,0 +1,57 @@
+# roboolympics-airhockey-match-i00-standard-realtime
+
+| | |
+|---|---|
+| Benchmark | RoboOlympics |
+| Mode | standard-realtime (`eai-standard/2.3`) |
+| Twin | — (none: RoboOlympics is standard-realtime only, PROTOCOL §4b) |
+| Simulator / robot | `mujoco` / `kuka-iiwa14` |
+| Family / instance | `airhockey_match` / seed 101 |
+| Oracle | `full` — solution/: the sport's RoboOlympics reference player (camera images, proprio and /spec only) through the agent's client; it wins this instance (PR #106) |
+| Agent time budget | 7200 s; tokens: protocol default (PROTOCOL §5) |
+| Base image | `ghcr.io/mll-lab-nu/eai-olympiad:0.2.0` |
+
+## Task
+RoboOlympics air hockey (`airhockey-match-wallclock-program-standard`), one match against the scripted opponent (level 1, frozen seed
+101), in standard-realtime mode (`eai-standard/2.3`, PROTOCOL §4b): the robot as a service on a clock that does
+not stop. The sport runs in the `sim` sidecar (`environment/docker-compose.yaml`; `environment/sim/rcb_realtime.py`
+runs the clock, `environment/sim/rcb_olympics.py` is the RoboOlympics adapter, `environment/sim/sport/` the sport's
+simulator, referee and opponent), which records every command at the control step it took effect, replays the match in
+a fresh process and renders the replay video; the verifier grades the sidecar's record in a container of its own
+(`tests/Dockerfile`, no network).
+
+## Difficulty
+The agent sees the game only through cameras and has no simulator of its own. A rally is decided in a few seconds of
+game time, faster than a model's turn even at S = 10, so the agent has to write a perception and control
+program (find the puck in the images, fit its flight, choose and time the command) that plays by itself, and
+improve it between rallys and during the match. The opponent returns every ball it can reach; level 1 of
+the sport's levels.
+
+## Reference solution
+`solution/oracle_play.py` runs the sport's RoboOlympics reference player (`solution/builtin_players.py`: camera images,
+the proprio columns and `/spec` only; perception by colour, triangulation, a fitted flight model, the sport's contact
+law) through the agent's own client; it wins this instance (PR #106).
+
+## Verification
+`success` = live success (the match finished and the agent won it) ∧ replay success ∧ deterministic (the fresh-process
+replay of the recorded commands ends in the live run's state), computed in the sidecar. The record is
+`trajectory_live.f64` (per control step: the id of the command that took effect, -1 for none, and the `ready` flag) with
+`commands.jsonl` (the commands as the sport's action layer lowered them), so the replay re-applies what the live match
+applied, whatever the timing; `ticks.f64`, `calls.jsonl` and `submitted.f64` record the timing and every call, and
+`final.json` the clock's lag (`max_lag_s`, `stalls`). `match.json` is the replay's summary (score, breaks, commands).
+`tests/grade.py` reads `/data/final.json` and copies the evidence to `/logs/verifier/` (`replay.mp4`). A simulator
+crash or error is an infrastructure failure (`infra_error = 1`), not the agent's (PROTOCOL §4b). `nop` scores 0: the
+match never starts.
+
+Generated by `scripts/roboolympics/gen_tasks.py` from `tasks.toml`, `sports.toml`, `templates/` and `shared/` (the
+RoboOlympics simulator code, CHIGUI0/roboolympics 596d551a862c4236e74aea2beb25654b9783f9a7 (branch upstream-export, core 0.2.13)); do not edit by hand.
+
+## Details
+| | |
+|---|---|
+| sport | You play robot air hockey (USAA rules with the deviations below) against a scripted opponent: a MuJoCo KUKA iiwa 14 arm holding a mallet at your end of the table (x < 0), seen only through one fixed camera. A rally starts with the puck at rest in one player's half; a goal, a seven-second foul or a dead puck ends it. The first to 7 goals wins. |
+| time | S = 10 (RoboOlympics' official slowdown; `RCB_SLOWDOWN` overrides it, results under another S are reported separately): one 10 ms control step every 0.1 s of wall time; the match starts paused and its clock starts at the first `submit` or `get_obs(seconds > 0)`; after every rally a break of 12 s of game time (120 s of wall time) in which the clock runs on and nothing plays, ended early by the agent's `ready` row |
+| actions | `mallet`, `stop`, `ready`: the sport's own commands (action level `low`), one per row, effective at the row's control step |
+| observation | camera images and the agent's own robot plus the referee's information as proprio columns; no ball or opponent state, no seed |
+| budget | 7200 s, no reset (one match is the episode), no privileged twin (PROTOCOL §4b exceptions, `docs/benchmarks/roboolympics.md`) |
+| agent API | `environment/rcb_client.py` (the realtime client); `instruction.md` documents the commands, the proprio columns and the cameras |
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/Dockerfile b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/Dockerfile
new file mode 100644
index 0000000000..36d483206f
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/Dockerfile
@@ -0,0 +1,10 @@
+# Standard-realtime mode: the agent container has no simulator and no RoboOlympics code -- only Python, the client and
+# OpenCV (RoboOlympics' player image).
+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f
+COPY client-requirements.txt /tmp/
+RUN pip install --no-cache-dir -r /tmp/client-requirements.txt
+RUN pip install --no-cache-dir -c /tmp/client-requirements.txt opencv-python-headless==5.0.0.93 && pip check
+COPY rcb_client.py rcb1.py /opt/tools/
+ENV PYTHONPATH=/opt/tools
+RUN mkdir -p /app/output
+WORKDIR /app
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/client-requirements.txt b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/client-requirements.txt
new file mode 100644
index 0000000000..8aa73a968f
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/client-requirements.txt
@@ -0,0 +1,11 @@
+# Exact pins for what the standard agent container installs (and a verifier, if it installs anything): the closure of
+# `pip install requests numpy pillow scipy`, the unpinned line of every standard task at 9eb18edf, resolved on
+# 2026-10-01 in CLIENT_IMAGE (client.env: Python 3.12.14, pip 25.0.1). A change here is a shared-files PR.
+certifi==2026.7.22
+charset-normalizer==3.5.2
+idna==3.20
+numpy==2.5.3
+pillow==12.3.0
+requests==2.34.2
+scipy==1.18.1
+urllib3==2.8.0
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/docker-compose.yaml b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/docker-compose.yaml
new file mode 100644
index 0000000000..4e6c017f55
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/docker-compose.yaml
@@ -0,0 +1,35 @@
+# Standard-realtime mode (PROTOCOL §4b): RoboOlympics air hockey runs in the `sim` sidecar (the agent cannot open it), on
+# its own clock once the match starts (sim/rcb_realtime.py, the adapter sim/rcb_olympics.py); the agent only reaches
+# port 8000. No `expose`/`ports` on sim: under Harbor's egress control it shares main's network namespace
+# (localhost:8000). CPU only: MuJoCo physics and OSMesa rendering (the players' meshes come with the image).
+services:
+ main:
+ depends_on: [sim]
+ sim:
+ image: ghcr.io/mll-lab-nu/eai-olympiad:0.2.0
+ volumes:
+ - ./sim:/srv:ro
+ command: python /srv/rcb_realtime.py
+ restart: on-failure:6 # a crash resumes the same match, paused, never a reset
+ cpus: 4
+ mem_limit: 8g
+ pids_limit: 256
+ environment:
+ RO_PLUGIN: /srv/sport/plugin.py
+ RO_SPORT: airhockey
+ RO_FORMAT: match
+ RO_SEED: "101"
+ RO_LEVEL: "1"
+ RO_ACTION_LEVEL: low
+ RO_TASK_TEXT: "Win a game of air hockey against the scripted opponent: score goals into its goal and defend yours."
+ RO_EPISODE_TEXT: "Ends when the game is decided (the first to 7 goals; at the safety cap of 120 s of play or 40 rallies the tiebreaks; success: you won), when your time is up (timeout), or on a simulator error."
+ RCB_WALL_CLOCK_S: "7200"
+ # Knobs: ${NAME:-default} takes NAME from the shell that runs harbor. The defaults are the official
+ # configuration; results under other settings are reported separately.
+ RCB_SLOWDOWN: "${RCB_SLOWDOWN:-10}" # 10: RoboOlympics' official slowdown (PROTOCOL §4b exception); results state S
+ RCB_RESET_BUDGET: "${RCB_RESET_BUDGET:-0}" # 0: one match is one episode (PROTOCOL §4b, the mode's default)
+ MUJOCO_GL: osmesa
+ PYOPENGL_PLATFORM: osmesa
+ LP_NUM_THREADS: "2"
+ OMP_NUM_THREADS: "1"
+ OPENBLAS_NUM_THREADS: "1"
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/rcb1.py b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/rcb1.py
@@ -0,0 +1,83 @@
+"""RCB1 — a tiny binary frame for one JSON header plus N raw blobs (videos, image arrays, depth, proprio).
+
+ frame = b"RCB1" | header_len uint32 LE | header JSON (UTF-8) | blob_0 | blob_1 | ...
+ header = {"v": 1, "meta": {...}, "parts": [{"name", "kind", "len", ...}, ...]} # blobs in the same order
+
+kinds: "mp4" (fps, n), "jpeg", "array" (dtype, shape; C-order raw bytes), "json" (utf-8), "bytes".
+Zero dependencies for bytes/json parts; numpy only when you ask for arrays. Used on both sides (server and client),
+over HTTP bodies (Content-Type: application/x-rcb1) and equally usable over a raw socket. `python -m rcb1 unpack f dir`.
+"""
+from __future__ import annotations
+import json, struct, sys, pathlib
+
+MAGIC = b"RCB1"
+
+
+def encode(meta: dict, parts: list[tuple[str, str, bytes, dict]]) -> bytes:
+ """parts: [(name, kind, blob, extra), ...]; extra carries dtype/shape/fps/n."""
+ hdr_parts = []
+ for name, kind, blob, extra in parts:
+ d = {"name": name, "kind": kind, "len": len(blob)}
+ d.update({k: v for k, v in (extra or {}).items() if v is not None})
+ hdr_parts.append(d)
+ header = json.dumps({"v": 1, "meta": meta, "parts": hdr_parts}, separators=(",", ":")).encode()
+ return b"".join([MAGIC, struct.pack("<I", len(header)), header] + [blob for _, _, blob, _ in parts])
+
+
+def array_part(name: str, arr, extra: dict | None = None) -> tuple[str, str, bytes, dict]:
+ import numpy as np
+ a = np.ascontiguousarray(arr)
+ return (name, "array", a.tobytes(), {"dtype": str(a.dtype), "shape": list(a.shape), **(extra or {})})
+
+
+def decode(buf: bytes, arrays: bool = True) -> tuple[dict, dict]:
+ """-> (meta, parts) where parts[name] = {"kind", ..., "data"}; arrays become numpy arrays when arrays=True."""
+ if buf[:4] != MAGIC:
+ raise ValueError("not an RCB1 frame")
+ n = struct.unpack("<I", buf[4:8])[0]
+ header = json.loads(buf[8:8 + n].decode()); off = 8 + n
+ out = {}
+ for p in header["parts"]:
+ blob = buf[off:off + p["len"]]; off += p["len"]
+ d = dict(p)
+ if p["kind"] == "array" and arrays:
+ import numpy as np
+ d["data"] = np.frombuffer(blob, dtype=np.dtype(p["dtype"])).reshape(p["shape"])
+ elif p["kind"] == "json":
+ d["data"] = json.loads(blob.decode())
+ else:
+ d["data"] = blob
+ out[p["name"]] = d
+ return header.get("meta", {}), out
+
+
+def unpack_to_dir(buf: bytes, out_dir: str) -> list[str]:
+ """Write a frame's parts as files: mp4/jpeg/bytes verbatim, arrays as .npy, meta as meta.json."""
+ import numpy as np
+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)
+ meta, parts = decode(buf, arrays=True); written = []
+ (out / "meta.json").write_text(json.dumps(meta, indent=1)); written.append("meta.json")
+ for name, p in parts.items():
+ safe = name.replace("/", "__")
+ if p["kind"] == "array":
+ f = out / f"{safe}.npy"; np.save(f, p["data"])
+ elif p["kind"] == "mp4":
+ f = out / f"{safe}.mp4"; f.write_bytes(p["data"])
+ elif p["kind"] == "jpeg":
+ f = out / f"{safe}.jpg"; f.write_bytes(p["data"])
+ elif p["kind"] == "json":
+ f = out / f"{safe}.json"; f.write_text(json.dumps(p["data"], indent=1))
+ else:
+ f = out / f"{safe}.bin"; f.write_bytes(p["data"])
+ written.append(f.name)
+ return written
+
+
+if __name__ == "__main__":
+ if len(sys.argv) == 4 and sys.argv[1] == "unpack":
+ print("\n".join(unpack_to_dir(open(sys.argv[2], "rb").read(), sys.argv[3])))
+ elif len(sys.argv) == 3 and sys.argv[1] == "info":
+ meta, parts = decode(open(sys.argv[2], "rb").read(), arrays=False)
+ print(json.dumps(meta, indent=1)); [print(n, {k: v for k, v in p.items() if k != "data"}) for n, p in parts.items()]
+ else:
+ print(__doc__)
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/rcb_client.py b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/rcb_client.py
new file mode 100644
index 0000000000..f2b0559bf9
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/rcb_client.py
@@ -0,0 +1,209 @@
+"""eai-standard/2.3 client (standard-realtime mode): your whole interface to the robot (installed at /opt/tools/rcb_client.py, on
+PYTHONPATH).
+
+ from rcb_client import Robot, EpisodeOver
+ r = Robot() # finds the service (SIM_URL, http://sim:8000, http://localhost:8000), waits until it is ready
+
+TIME DOES NOT STOP (spec()["timing"]). An episode starts paused; its clock starts at its first submit() or
+get_obs(seconds > 0) (again after every reset()) and from then on runs one control step every spec()["control_dt"] x
+spec()["timing"]["slowdown"] seconds of wall time, whether or not you call, until the episode ends. The service keeps a
+plan, one servo-target row per coming control step: submit() writes into it and answers at once; when the plan runs out
+the last target is held. Whatever you do in between -- think, print, run a model -- the robot keeps executing.
+
+Calls (each is one HTTP request; every answer that carries data is an RCB1 frame, decoded into a Result):
+ r.spec() GET /spec, fetched when connecting: the robot's facts. "action_types"
+ ("joint_position": dim, layout (actuator order), lower/upper, range_rad,
+ units, semantics), "control_dt" (0.02 s), "max_control_steps" (the
+ episode), "timing" (realtime, slowdown, max_ahead_steps), "cameras" {name:
+ rgb, depth, hw, fovy_deg, pose, mounted}, "proprio_layout" and "proprio"
+ (joints, axes, positions), "imu", "links" (masses, centres of mass, the
+ feet's boxes), "depth", "budget" {"reset", "wall_clock_s"}, "episode"
+ r.status() GET /status: calls, rows, control_steps, done, reason, elapsed_s, running,
+ planned_steps, lag_s (and episode, resets_left with a reset budget)
+ r.get_obs(cameras=None, seconds=0.0, video_fps=10, include_depth=False, video="frames")
+ POST /observe. seconds=0: the robot now, at once. seconds>0 (at most
+ spec()["max_watch_s"]): waits while that much robot time runs (starting the
+ clock if it is not running) and returns what the cameras saw; it never
+ changes the plan
+ r.submit("joint_position", actions, dt=None, interpolate="linear", at=None, cameras=None, video_fps=10,
+ video="none", include_depth=False, note="")
+ POST /submit: answers at once with the robot as it is now (the rows
+ have not run yet). actions (T, dim): rows dt apart (a multiple of
+ control_dt, the default; T x dt at most spec()["max_chunk_s"]); each step's
+ target is the row (interpolate="hold") or a straight line from the previous
+ row's ("linear", starting from the target in force just before `at`). They
+ become the plan from control step `at` (an episode step number; None = the
+ next step), replacing whatever was planned from `at` on and keeping what is
+ planned before it; at most spec()["timing"]["max_ahead_steps"] ahead. Rows
+ for steps already gone when the request arrives are dropped
+ (meta["late_steps"]). The first submit of an episode starts its clock
+ r.reset(cameras=None, include_depth=False)
+ POST /reset, only when spec()["budget"]["reset"] > 0: abandons the
+ running episode and starts a new one, paused, from the same starting state;
+ only the last episode is graded, and a success ends the trial
+
+cameras=None means every camera in spec()["cameras"]; cameras=[] means no images at all, only proprioception (the
+fastest call: what a controller loop wants). video: "mp4" (one H.264 file per camera), "frames" (the images as arrays),
+"both" or "none" (only the last frame); a submit returns no video (no time passes inside it). include_depth adds depth
+for the cameras that have it.
+
+Result (what get_obs / submit / reset return):
+ res.meta dict: calls, rows, control_steps (steps run in this episode: the next one is this number),
+ sim_time_s, time_s, time_left_s, proprio {"layout", "now"}, done, reason ("success" |
+ "failed" | "timeout" | "error"; None while the episode runs), running, planned_steps,
+ lag_s; per submit: start_step, late_steps, plan_end_step, clipped [{row, index, reason}]
+ (values outside [-1, 1] are clipped, not refused); with a reset budget also episode,
+ resets_left
+ res.last[cam] uint8 H x W x 3: the last frame (unless cameras=[])
+ res.frames[cam] uint8 N x H x W x 3 (get_obs, video="frames"/"both") res.video[cam] mp4 bytes
+ res.depth[cam] float16 N x H x W, metres, 0 = nothing in range (include_depth)
+ res.proprio float32 rows of spec()["proprio_layout"]: one at the call's start, one every 1/video_fps s
+ of a watch, one at its end
+ res.done the episode is over
+ res.save(dir) meta.json, <cam>.mp4, last/<cam>.jpg, frames/<cam>/NNN.jpg, depth_<cam>.npy, proprio.npy
+
+Errors: ValueError -- refused, nothing changed (400: wrong type or shape, NaN, a bad dt or at, too many frames, an
+unknown camera; or a request over 64 MB, refused before it is sent); EpisodeOver -- the episode, or the trial, is over
+(409); RuntimeError -- the service failed (5xx: see spec()["on_service_error"]) or the endpoint does not exist in this
+run (404).
+"""
+from __future__ import annotations
+
+import json
+import os
+import pathlib
+import time
+
+import numpy as np
+import requests
+
+import rcb1
+
+PROTOCOLS = ("eai-standard/2.", "rcb-limited/2.") # any 2.x service, under either name (rcb-limited is the old one)
+MAX_BODY = 64 * 1024 * 1024 # the protocol's request limit: a larger request is refused
+
+
+class EpisodeOver(RuntimeError):
+ pass
+
+
+class Result:
+ """A decoded RCB1 answer: meta, video, frames, last, depth, proprio; save(dir) writes them all out."""
+
+ def __init__(self, meta: dict, parts: dict):
+ self.meta, self.raw = meta, parts
+ self.video, self.frames, self.last, self.depth, self.proprio = {}, {}, {}, {}, None
+ for name, p in parts.items():
+ kind, data = p["kind"], p["data"]
+ if name.startswith("video/") and kind == "mp4":
+ self.video[name[6:]] = data
+ elif name.startswith("frames/"):
+ self.frames[name[7:]] = data
+ elif name.startswith("last/"):
+ self.last[name[5:]] = data
+ elif name.startswith("depth/"):
+ self.depth[name[6:]] = data
+ elif name == "proprio":
+ self.proprio = data
+
+ @property
+ def done(self) -> bool:
+ return bool(self.meta.get("done"))
+
+ def save(self, out_dir: str) -> str:
+ from PIL import Image
+ out = pathlib.Path(out_dir)
+ out.mkdir(parents=True, exist_ok=True)
+ (out / "meta.json").write_text(json.dumps(self.meta, indent=1))
+ for cam, b in self.video.items():
+ (out / f"{cam}.mp4").write_bytes(b)
+ for cam, img in self.last.items():
+ (out / "last").mkdir(exist_ok=True)
+ Image.fromarray(np.ascontiguousarray(img)).save(out / "last" / f"{cam}.jpg", quality=90)
+ for cam, arr in self.frames.items():
+ d = out / "frames" / cam
+ d.mkdir(parents=True, exist_ok=True)
+ for i, f in enumerate(arr):
+ Image.fromarray(np.ascontiguousarray(f)).save(d / f"{i:03d}.jpg", quality=85)
+ for cam, arr in self.depth.items():
+ np.save(out / f"depth_{cam}.npy", arr)
+ if self.proprio is not None:
+ np.save(out / "proprio.npy", self.proprio)
+ return str(out)
+
+
+class Robot:
+ def __init__(self, base: str | None = None, timeout: float = 600.0):
+ candidates = [c for c in (base or os.environ.get("SIM_URL"), "http://sim:8000", "http://localhost:8000") if c]
+ t0, last = time.time(), None
+ while time.time() - t0 < timeout:
+ for b in candidates:
+ try:
+ r = requests.get(b + "/spec", timeout=(5, 60))
+ if r.status_code == 503:
+ last = "warming up"
+ continue
+ r.raise_for_status()
+ self.base, self._spec = b, r.json()
+ if not str(self._spec.get("protocol", "")).startswith(PROTOCOLS):
+ raise RuntimeError(f"not an eai-standard/2.x service: {self._spec.get('protocol')}")
+ return
+ except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e:
+ last = e # not up yet (the scene takes about a minute), or busy
+ time.sleep(2)
+ raise RuntimeError(f"sim service unavailable: {last}")
+
+ def spec(self) -> dict:
+ return self._spec
+
+ def status(self) -> dict:
+ r = requests.get(self.base + "/status", timeout=(5, 60))
+ r.raise_for_status()
+ return r.json()
+
+ def get_obs(self, cameras=None, seconds: float = 0.0, video_fps: int = 10, include_depth: bool = False,
+ video: str = "frames") -> Result:
+ meta = {"cameras": _names(cameras), "seconds": float(seconds), "video_fps": int(video_fps),
+ "include_depth": bool(include_depth), "video": video}
+ return self._post("/observe", meta, [], timeout=900)
+
+ def submit(self, action_type: str, actions, dt: float | None = None, interpolate: str = "linear",
+ at: int | None = None, cameras=None, video_fps: int = 10, video: str = "none",
+ include_depth: bool = False, note: str = "") -> Result:
+ a = np.asarray(actions, dtype=np.float64)
+ if a.ndim == 1:
+ a = a[None, :]
+ if not np.all(np.isfinite(a)):
+ raise ValueError("actions contain NaN or inf")
+ meta = {"type": action_type, "dt": None if dt is None else float(dt), "interpolate": interpolate,
+ "at": None if at is None else int(at), "cameras": _names(cameras), "video_fps": int(video_fps),
+ "video": video,
+ "include_depth": bool(include_depth), "note": note}
+ return self._post("/submit", meta, [rcb1.array_part("actions", a)], timeout=1800)
+
+ def reset(self, cameras=None, include_depth: bool = False) -> Result:
+ return self._post("/reset", {"cameras": _names(cameras), "include_depth": bool(include_depth)}, [], timeout=900)
+
+ def _post(self, path: str, meta: dict, parts: list, timeout: float) -> Result:
+ body = rcb1.encode(meta, parts)
+ if len(body) > MAX_BODY: # the service would close the connection on it unread
+ raise ValueError(f"{path}: {len(body)} bytes, over the protocol's {MAX_BODY}: send fewer rows")
+ r = requests.post(self.base + path, data=body, headers={"Content-Type": "application/x-rcb1"},
+ timeout=(5, timeout))
+ if r.headers.get("Content-Type", "").startswith("application/x-rcb1") and r.status_code == 200:
+ return Result(*rcb1.decode(r.content))
+ try:
+ err = r.json()
+ except ValueError:
+ err = {"error": r.text[:300]}
+ msg = f"{r.status_code} {path}: {err.get('error')}" + (f" ({err['detail']})" if err.get("detail") else "")
+ if r.status_code == 409:
+ raise EpisodeOver(msg + (f"; reason {err['reason']}" if err.get("reason") else "")
+ + (f"; resets_left {err['resets_left']}" if "resets_left" in err else ""))
+ if r.status_code in (400, 413):
+ raise ValueError(msg)
+ raise RuntimeError(msg)
+
+
+def _names(cameras) -> list[str] | None:
+ return None if cameras is None else [cameras] if isinstance(cameras, str) else list(cameras)
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/core/README.md b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/core/README.md
new file mode 100644
index 0000000000..6d80cefa51
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/core/README.md
@@ -0,0 +1,18 @@
+# core/
+
+The match core (docs/framework_zh.md §5): it hosts every match under one set of rules and never names a sport or a
+harness. Version: `VERSION` in `__init__.py` (bump on every change; every sport's golden replay must still pass).
+
+| File | Contract / job |
+|---|---|
+| `sport.py` | ② the sport interface: `MatchConfig` (seats, sides, format, modes, renderer), `Phase`, `Refused`, `MatchBase` (the optional hooks and their defaults), `ActionLayer` / `LowLayer` / `SchemaLayer`, `check_command`; request validation (core 0.2.11): `check_body` (every request), `check_action` + `parse_action` (every act: any exception while reading an action is the player's 400, never a technical failure) |
+| `http.py`, `client.py`, `game.py` | ① the player protocol: the HTTP envelope (`/<seat>/<endpoint>`, limits), the client loop of built-in players, the generic `game` CLI |
+| `realtime.py`, `turn.py`, `service.py` | flow: `eai-standard-realtime/1.0` (slowdown, freeze and review, act pipeline, delayed effects, entities) and `eai-standard-turn/1.0` (turns, chess clocks, reviews); what both share (seats and sides, observations, team channel, retirement, final.json) |
+| `episode.py` | ③ the match record: `episode.jsonl` and the fresh-process replay (`python -m core.episode PLUGIN DIR`) |
+| `outcome.py`, `grading.py` | judgement: the no-draw chain, N-side ranking, solo scoring; the verifier (validity, reward fields, no-code audit hookup) |
+| `observe.py`, `channel.py`, `rng.py`, `spec.py` | the observation whitelist and camera tiles (through `renderers/`), the reply images of an action (`Match.reply_views`, core 0.2.8: snapshotted under the lock, drawn off it by the same camera worker, attached to the reply as `observation`), the team channel, random streams by name, sport.toml |
+| `seats.py`, `metering/` | per-seat counters, locks and chess clocks; the metering hookup (`think_clock.py`, `api_errors.py`: byte-identical copies); player modes (`PLAYER_MODE_<seat>`): `model` (metered by the seat's proxy, required for validity), `oracle` (exempt), `unmetered` (core 0.2.13: the runner meters the model itself, e.g. a plain Harbor with native agents; no proxy, no meter required) |
+| `spectator.py` | the broadcast log (`broadcast.jsonl`, the legacy writer copied as `spectator/broadcast_log.py`) and the replay video (`replay.mp4`, a fresh-process replay drawn by the spectator renderer); never read back |
+| final.json compatibility | `service.py` `COMPAT`: the sport's fields are lifted to the top level (unless a core field has the name) and `score` is set, so the Season-1 readers work; the sport fields also stay under `sport_fields` |
+| `workers.py`, `serve.py`, `launch.py` | worker processes (plan, render, camera), the service entry point, the launcher (one metering proxy per seat, none for an unmetered seat) |
+| `local.py`, `testkit.py`, `tests/` | in-process matches of built-in players, the generic test suite of every sport, the core's own tests |
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/core/__init__.py b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/core/__init__.py
new file mode 100644
index 0000000000..fd44c1d84c
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/core/__init__.py
@@ -0,0 +1,8 @@
+"""RoboOlympics match core (docs/framework_zh.md §5): hosts every match under one set of rules.
+
+Flow (clock, slowdown, freeze and review, seats and turns), rules (formats, modes), records (episode log, replay,
+metering) and judgement (outcome, validity). It names no sport and no harness (ci_checks/check-core-purity.sh), computes
+no physics, and changes only in its own commits with a version bump (VERSION) and every sport's golden replay passing.
+"""
+VERSION = "0.2.13"
+PROTOCOLS = {"realtime": "eai-standard-realtime/1.0", "turn": "eai-standard-turn/1.0"}
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/core/observe.py b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/core/observe.py
new file mode 100644
index 0000000000..94b46fc9b3
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/core/observe.py
@@ -0,0 +1,154 @@
+"""Observations (sport rule 1, docs/framework_zh.md §9): what a seat gets is the camera images, its own body and the
+referee's information, and nothing else. The sport declares the fields of Match.observe() in sport.toml
+([observation] fields); a field outside that whitelist is never delivered and is a technical error of the match.
+
+The camera images: Match.cameras(seat, query) returns camera definitions, the task's renderer (renderers/, chosen by
+the task parameter `renderer`) draws them from the sport's scene and Match.render_state(), and the core lays the
+images out as tiles of one PNG (left to right, `columns` per row), described in the reply (`tiles`).
+
+Reply images (core 0.2.8): Match.reply_views(seat, cmd, info) right after an action -> reply_job() snapshots the
+frames under the lock -> CameraWorker.draw_job() draws them off the lock (the same renderer, scene and worker as the
+observation) -> one PNG of tiles, each tile also naming its frame (`frame`, `label`) when there are several.
+
+The scene of the players' images (core 0.2.9, renderer rule 6): Sport.scene(cfg), or the presentation scene the sport
+declares for its players (sports/<sport>/presentation/presentation.toml `players`, bundled into the simulator by the
+generator; renderers/presentation.players_scene): the same kinematics, finer visual meshes. Any other presentation
+scene is refused (spectators only)."""
+from __future__ import annotations
+
+import copy
+import struct
+import zlib
+from pathlib import Path
+
+import numpy as np
+
+
+class WhitelistError(Exception):
+ pass
+
+
+def filter_fields(obs: dict, allowed: set[str] | None) -> tuple[dict, list[str]]:
+ """(the whitelisted part of obs, the names that were not allowed)."""
+ if allowed is None:
+ return obs, []
+ bad = sorted(k for k in obs if k not in allowed)
+ return {k: v for k, v in obs.items() if k in allowed}, bad
+
+
+def png(img: np.ndarray) -> bytes:
+ """A minimal RGB8 PNG encoder (no imaging library needed in the sim)."""
+ img = np.ascontiguousarray(img, dtype=np.uint8)
+ h, w = img.shape[:2]
+ raw = b"".join(b"\x00" + img[y].tobytes() for y in range(h))
+
+ def chunk(tag, data):
+ return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
+
+ return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0))
+ + chunk(b"IDAT", zlib.compress(raw, 6)) + chunk(b"IEND", b""))
+
+
+def reply_job(m, spec: dict | None, columns: int) -> dict | None:
+ """Under the lock: Match.reply_views()'s answer -> a self-contained draw job (deep copies: the match may move on
+ while the job is drawn off the lock). A frame without a state gets render_state() now."""
+ if not spec or not spec.get("frames"):
+ return None
+ order = spec.get("order", "frame")
+ if order not in ("frame", "camera"):
+ raise ValueError(f"reply_views: order must be 'frame' or 'camera', not {order!r}")
+ now = None
+ frames = []
+ for f in spec["frames"]:
+ st = f.get("state")
+ if st is None:
+ now = m.render_state() if now is None else now
+ st = now
+ cams = list(f.get("cameras") or [])
+ if not cams:
+ raise ValueError("reply_views: every frame needs at least one camera")
+ frames.append({"state": st, "cams": cams, "label": f.get("label")})
+ return copy.deepcopy({"frames": frames, "order": order, "columns": int(spec.get("columns") or columns),
+ "note": spec.get("note")})
+
+
+def compose(images: list[np.ndarray], names: list[str], columns: int = 2) -> tuple[np.ndarray, list[dict]]:
+ """Tiles left to right, `columns` per row, each at its own size; -> (sheet, [{camera, x, y, width, height}])."""
+ rows = [list(range(i, min(i + columns, len(images)))) for i in range(0, len(images), columns)]
+ widths = [sum(images[j].shape[1] for j in r) for r in rows]
+ heights = [max(images[j].shape[0] for j in r) for r in rows]
+ sheet = np.zeros((sum(heights), max(widths), 3), np.uint8)
+ tiles, y = [], 0
+ for r, hgt in zip(rows, heights):
+ x = 0
+ for j in r:
+ h, w = images[j].shape[:2]
+ sheet[y:y + h, x:x + w] = images[j][..., :3]
+ tiles.append({"camera": names[j], "x": x, "y": y, "width": w, "height": h})
+ x += w
+ y += hgt
+ return sheet, tiles
+
+
+def players_scene(sport, plugin: str, cfg):
+ """The scene of the players' images: the sport's presentation scene when it declares `players`, else
+ Sport.scene(cfg)."""
+ scene = sport.scene(cfg)
+ d = Path(plugin).resolve().parent
+ if not (d / "presentation" / "presentation.toml").is_file():
+ return scene
+ from renderers import presentation
+ return presentation.players_scene(d, scene)
+
+
+class CameraWorker:
+ """Draws a seat's camera definitions with the task's renderer (in-process or inside a render worker process)."""
+
+ def __init__(self, scene, renderer_name: str | None):
+ import renderers
+ if getattr(scene, "match", None) is not None and not getattr(scene, "players", False):
+ raise ValueError("the players' images are drawn from the match scene (Sport.scene) or the presentation "
+ "scene the sport declares for them; any other presentation scene is for spectators only "
+ "(renderer rule 6)")
+ self.name = renderer_name or renderers.DEFAULT
+ self.renderer = renderers.load(self.name)(scene)
+
+ def draw(self, state: dict, cams: list[dict], columns: int = 2) -> dict:
+ from renderers.base import CameraDef
+ defs = [CameraDef.from_dict(c) for c in cams]
+ images = self.renderer.render(state, defs)
+ sheet, tiles = compose(images, [c.name for c in defs], columns)
+ return {"png": png(sheet), "tiles": tiles, "renderer": self.name}
+
+ def draw_frames(self, job: dict) -> dict:
+ """A reply job (reply_job()): every frame's cameras drawn from that frame's state, laid out frame after
+ frame or camera after camera; a tile names its camera, and its frame (index, label) when there are several."""
+ from renderers.base import CameraDef
+ frames = job["frames"]
+ drawn = [] # per frame: [(name, image)]
+ for f in frames:
+ defs = [CameraDef.from_dict(c) for c in f["cams"]]
+ drawn.append(list(zip([c.name for c in defs], self.renderer.render(f["state"], defs))))
+ cells = [] # (frame index, camera name, image)
+ if job.get("order") == "camera":
+ for j in range(max(len(d) for d in drawn)):
+ cells += [(i, d[j][0], d[j][1]) for i, d in enumerate(drawn) if j < len(d)]
+ else:
+ cells = [(i, name, img) for i, d in enumerate(drawn) for name, img in d]
+ sheet, tiles = compose([c[2] for c in cells], [c[1] for c in cells], int(job.get("columns", 2)))
+ many = len(frames) > 1
+ for t, (i, _, _) in zip(tiles, cells):
+ if many:
+ t["frame"] = i
+ if frames[i].get("label"):
+ t["label"] = frames[i]["label"]
+ out = {"png": png(sheet), "tiles": tiles, "renderer": self.name}
+ if job.get("note"):
+ out["note"] = job["note"]
+ return out
+
+ def draw_job(self, job: dict) -> dict:
+ """Any job of the core's camera worker: a reply job (frames) or an observation (state + cameras)."""
+ if "frames" in job:
+ return self.draw_frames(job)
+ return self.draw(job["state"], job["cams"], job.get("columns", 2))
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/core/outcome.py b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/core/outcome.py
new file mode 100644
index 0000000000..11916961f2
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/core/outcome.py
@@ -0,0 +1,50 @@
+"""The no-draw decision chain (docs/framework_zh.md §5): a forfeit (a core decision: review or clock time, abandonment,
+or a side that never started, "no_show"; sides that retired before it rank last, the last to retire first), then the
+sport's tiebreaks in order (rulebook result -> rulebook tiebreak -> capped extra play -> last resort; the last one must
+decide). A match with more than two sides is decided by the sport's classification (Match.ranking, best first). A solo
+match (single format without an opponent: tiebreaks() == []) has no winner; its result is the score against the
+success line. A match that did not finish has no winner."""
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+from .sport import FINISHED
+
+
+@dataclass
+class Outcome:
+ winner: str | None
+ decided_by: str
+ scores: dict
+ ranking: list = field(default_factory=list)
+ solo: bool = False
+
+
+def decide(match, forfeit_seat: str | None = None, why: str | None = None, sides=("A", "B"),
+ side_of=lambda s: s, retired=()) -> Outcome:
+ scores = match.scores()
+ sides = list(sides)
+ rules = match.tiebreaks()
+ solo = len(sides) == 1 and not rules
+ if forfeit_seat is not None:
+ lost = side_of(forfeit_seat)
+ others = [s for s in sides if s != lost and s not in retired]
+ if len(others) == 1:
+ return Outcome(others[0], f"forfeit:{why}", scores, others + [lost] + list(reversed(retired)))
+ if not others and len(sides) == 1: # a single player who forfeits loses (to the line or the opponent)
+ return Outcome(None, f"forfeit:{why}", scores, [], solo)
+ if match.phase().state != FINISHED:
+ return Outcome(None, "unfinished", scores, [], solo)
+ if solo:
+ return Outcome(None, "score", scores, list(sides), True)
+ if len(sides) > 2:
+ ranking = list(match.ranking() or [])
+ if sorted(ranking) != sorted(sides):
+ raise RuntimeError("a match of more than two sides must rank every side (Match.ranking)")
+ return Outcome(ranking[0], "ranking", scores, ranking)
+ for name, rule in rules:
+ w = rule(match)
+ if w is not None:
+ rest = [s for s in sides if s != w]
+ return Outcome(w, name, scores, [w] + rest)
+ raise RuntimeError("a finished match must be decided by its last tiebreak (no draws)")
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/core/spec.py b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/core/spec.py
new file mode 100644
index 0000000000..9cc5599b5c
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/core/spec.py
@@ -0,0 +1,20 @@
+"""The sport's declarations (sport.toml next to its plugin.py, docs/framework_zh.md §4.2): data, read by the core
+(observation whitelist, team channel, success line, timing), the generator, the checks and the documentation."""
+from __future__ import annotations
+
+import os
+import tomllib
+from pathlib import Path
+
+
+def load(plugin_path: str | os.PathLike) -> dict:
+ p = Path(plugin_path)
+ p = p / "sport.toml" if p.is_dir() else p.with_name("sport.toml")
+ if not p.exists():
+ return {}
+ return tomllib.loads(p.read_text())
+
+
+def whitelist(decl: dict) -> set[str] | None:
+ fields = (decl.get("observation") or {}).get("fields")
+ return set(fields) if fields is not None else None
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/core/sport.py b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/core/sport.py
new file mode 100644
index 0000000000..a60647ec26
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/core/sport.py
@@ -0,0 +1,455 @@
+"""Contract ② (docs/framework_zh.md §4.2): the one interface between the core and a sport (sports/<sport>/).
+
+A sport's plugin module exports SPORT. The core calls only the functions below and never names a sport; a sport never
+imports another sport. A sport answers four questions, one group of functions each (10 required):
+
+ world Sport.build(cfg) -> Match Match.step() -> events Match.state_digest() -> hex
+ actions Match.schema(seat) Match.apply(seat, low_cmd) -> info
+ optional high-level plugin: Sport.action_layer(level) -> ActionLayer whose lower() turns a high-level
+ command into a low-level one (the episode log holds LOW-LEVEL commands only)
+ referee Match.phase() -> Phase Match.scores() -> {side: n} Match.tiebreaks() -> [(name, rule)]
+ optional: to_move(), forfeit(), resume(), retire(), ranking()
+ observation Match.observe(seat, query) -> dict (own body + referee information, whitelisted in sport.toml)
+ Match.cameras(seat, query) -> [camera definitions] (drawn by the task's renderer, renderers/)
+
+Optional hooks have defaults in MatchBase; none of them is required by every sport, and the core never branches on a
+sport. Stage-0 hooks (all optional): sides != seats (MatchConfig.sides, Match.entities: one act in flight per entity),
+N sides with a classification (Match.ranking) and in-match retirement (Match.retire), a delayed effect
+(ActionLayer.delay_steps), observation parameters (the `query` of observe/cameras), a team channel (core/channel.py,
+declared in sport.toml) and a scored single format without an opponent (tiebreaks() == []).
+
+Reply images (core 0.2.8, optional): Match.reply_views(seat, cmd, info) names the cameras (and optionally a short
+strip of frames) that show the result of an action; the core snapshots them under the lock right after the action
+took effect, draws them off the lock with the task's renderer (the path of the observation images) and attaches them
+to the action's reply as `observation` (image_png_b64 + tiles, as /observe). In the turn protocol the core also tells
+the sport whose review is due (Match.awaiting_review), so that a sport serving images only on turn can hold them
+back from the other seats while the actor reviews.
+
+Presentation (core 0.2.4, optional, spectators only): sports/<sport>/presentation/presentation.toml dresses the scene
+of Sport.scene(cfg) for spectator renderers (renderers/presentation; e.g. fine visual meshes on a robot's bodies,
+same kinematics). It is not part of the simulator directory and never reaches the players' images, unless the sport
+declares `players` there (core 0.2.9): then the generator bundles it (and the models' files) into the simulator and
+the players' images are drawn from it (core/observe.players_scene; a sport drawing its own images uses
+renderers.players_model).
+"""
+from __future__ import annotations
+
+import hashlib
+import json
+import math
+from dataclasses import asdict, dataclass, field, fields
+from typing import Any, Callable, Protocol
+
+
+@dataclass(frozen=True)
+class MatchConfig:
+ sport: str
+ format: str # single | duel | team | multi (the sport declares which it supports)
+ seats: tuple[str, ...] # e.g. ("A", "B"); the HTTP addresses /<seat>/<endpoint>
+ seed: int
+ first: str | None = None # the side that starts (serves / throws first; the rules say what that means)
+ slowdown: float | None = None # realtime only
+ level: int | None = None # scripted opponent level (single)
+ action_level: str = "high" # high | low
+ play: str = "program" # program | direct
+ params: dict = field(default_factory=dict)
+ sides: dict | None = None # seat -> side; default: every seat is its own side
+ renderer: str | None = None # the renderer of the players' images (renderers/; None = the default)
+
+ def side_of(self, seat: str) -> str:
+ return (self.sides or {}).get(seat, seat)
+
+ def side_list(self) -> list[str]:
+ out: list[str] = []
+ for s in self.seats:
+ if self.side_of(s) not in out:
+ out.append(self.side_of(s))
+ return out
+
+ def seats_of(self, side: str) -> list[str]:
+ return [s for s in self.seats if self.side_of(s) == side]
+
+ def to_json(self) -> dict:
+ d = asdict(self)
+ d["seats"] = list(self.seats)
+ return d
+
+ @staticmethod
+ def from_json(d: dict) -> "MatchConfig":
+ known = {f.name for f in fields(MatchConfig)}
+ return MatchConfig(**{**{k: v for k, v in d.items() if k in known}, "seats": tuple(d["seats"])})
+
+
+PLAYING, UNIT_OVER, FINISHED = "playing", "unit_over", "finished"
+
+
+@dataclass
+class Phase:
+ state: str # PLAYING | UNIT_OVER | FINISHED
+ review: tuple[str, ...] = () # seats that review before play resumes (realtime: usually all seats)
+ reason: str = ""
+
+
+class Refused(Exception):
+ """An action the core must refuse: HTTP `code` (400 bad body, 409 wrong time) with `message`."""
+
+ def __init__(self, message: str, code: int = 400):
+ super().__init__(message)
+ self.code = code
+ self.cause = "" # parse_action: the hidden exception (logs only)
+
+
+Tiebreak = tuple[str, Callable[["Match"], "str | None"]] # (name, rule) -> winning side or None (undecided)
+
+
+class Match(Protocol):
+ k: int # [R] control steps (realtime) / actions (turn) so far
+ dt: float # [R realtime] control step, seconds
+
+ # world
+ def step(self) -> list[dict]: ... # [R realtime] advance one control step; events
+ def state_digest(self) -> str: ... # [R] hex digest of everything that affects the score
+ # actions
+ def schema(self, seat: str) -> dict: ... # [R] the low-level command types and ranges (/spec)
+ def apply(self, seat: str, cmd: dict) -> dict: ... # [R] a LOW-LEVEL command takes effect now; info
+ # referee
+ def phase(self) -> Phase: ... # [R]
+ def scores(self) -> dict[str, float]: ... # [R] by side (informational: tiebreaks decide)
+ def tiebreaks(self) -> list[Tiebreak]: ... # [R] rulebook -> extra play -> last resort; [] = solo
+ # observation
+ def observe(self, seat: str, query: dict | None = None) -> dict: ... # [R] own body + referee information
+ def cameras(self, seat: str, query: dict | None = None) -> list[dict]: ... # [R] camera definitions (renderers/)
+
+
+class MatchBase:
+ """Defaults of every optional hook (a sport subclasses this and overrides what it needs)."""
+ k = 0
+ dt = 0.0
+ awaiting_review = None # turn protocol, set by the core: the seat whose review
+ # is due now (None: nobody's); never part of the digest
+
+ # referee
+ def resume(self) -> None: # leaving a review: frozen-time work (next serve ...)
+ pass
+
+ def to_move(self): # turn protocol: the seat whose turn it is
+ return None
+
+ def forfeit(self, seat, why) -> bool: # record a core decision inside the world (True)
+ return False
+
+ def retire(self, side, why) -> bool: # N sides: True = the match goes on without `side`
+ return False
+
+ def ranking(self): # N sides: the classification, best first
+ return None
+
+ def unit(self) -> int: # index of the current unit (acts of an old unit drop)
+ return 0
+
+ # actions
+ def schema(self, seat) -> dict:
+ return {}
+
+ def entities(self, seat) -> tuple[str, ...]: # what a seat commands; one act in flight per entity
+ return ()
+
+ # observation
+ def cameras(self, seat, query=None) -> list[dict]:
+ return []
+
+ def render_state(self) -> dict: # what a renderer needs to draw the scene now
+ return {}
+
+ def camera_job(self, seat): # a sport that draws its own images: (job, meta)
+ return None, {}
+
+ def reply_views(self, seat, cmd, info) -> dict | None:
+ """The images of an action's result for its reply (core 0.2.8), or None. Called under the lock right after
+ Match.apply(seat, cmd) returned `info` (realtime: only for an act without a delayed effect); it must not change
+ the match, and what it returns must follow from the match state and (seat, cmd, info) alone, so that a replay
+ can draw the same images (python -m core.episode PLUGIN DIR --reply N).
+ {"frames": [{"cameras": [camera definitions, as cameras()],
+ "state": render state (optional; default: render_state() now),
+ "label": short text (optional, e.g. "-200 ms"; shown in the tiles)}, ...],
+ "order": "frame" (default: frame after frame) | "camera" (camera after camera: one strip per camera),
+ "columns": tiles per row (default: sport.toml [observation] columns),
+ "note": one line for the player (optional)}
+ Drawn like the observation images: the task's renderer, the match scene (never a presentation scene),
+ sport.toml [observation] frame_budget_ms for the whole reply image."""
+ return None
+
+ def final_fields(self) -> dict: # sport fields for final.json
+ return {}
+
+ def broadcast_frame(self): # spectator frame (never read back)
+ return None
+
+
+class ActionLayer(Protocol):
+ level: str # "high" | "low"
+ worker: str | None # Sport worker kind that runs prepare(), or None
+ delay_steps: int # realtime: the effect is delay_steps after lowering
+
+ def parse(self, seat: str, body: dict, match: Match, ctx: dict) -> dict: ...
+ # validate a request body (raise Refused); ctx = core facts at the request (e.g. both chess clocks), which the
+ # plugin may copy into the command so that replay sees them
+ def snapshot(self, seat: str, cmd: dict, match: Match, ordinal: int) -> Any: ... # under the lock, for prepare
+ def prepare(self, job: Any) -> Any: ... # off the lock (in `worker` if set); expensive planning
+ def lower(self, seat: str, cmd: dict, prepared: Any, match: Match) -> tuple[dict, dict]: ...
+ # at the effect boundary, cheap: -> (low-level command for Match.apply, info for the reply)
+ def reply(self, seat: str, cmd: dict, info: dict, match: Match) -> dict: ...
+
+
+class LowLayer:
+ """The identity layer: the request body, validated by `validate(seat, body, match, ctx) -> cmd`, is the command."""
+ level = "low"
+ worker = None
+ delay_steps = 0
+
+ def __init__(self, validate):
+ self._validate = validate
+
+ def schema(self, match, seat): # what /spec shows of this layer's commands
+ return match.schema(seat)
+
+ def parse(self, seat, body, match, ctx):
+ return self._validate(seat, body, match, ctx)
+
+ def snapshot(self, seat, cmd, match, ordinal):
+ return None
+
+ def prepare(self, job):
+ return None
+
+ def lower(self, seat, cmd, prepared, match):
+ return cmd, {}
+
+ def reply(self, seat, cmd, info, match):
+ return info
+
+
+def check_command(schema: dict, body: dict) -> dict:
+ """Validate a request body against a Match.schema() and return the clean command (raises Refused).
+
+ schema = {TYPE: {FIELD: {"type": "number"|"integer"|"boolean"|"enum"|"vector", "min", "max", "values", "len",
+ "unit", "doc", "default"}}}; the command is {"type": TYPE, FIELD: value, ...}."""
+ if not isinstance(body, dict):
+ raise Refused("the action must be a JSON object")
+ kind = body.get("type")
+ if kind not in schema:
+ raise Refused(f"unknown action type {kind!r}; one of {sorted(schema)}")
+ out: dict = {"type": kind}
+ spec = schema[kind]
+ extra = sorted(set(body) - set(spec) - {"type", "entity"})
+ if extra:
+ raise Refused(f"unknown field(s) {extra} for {kind}")
+ for name, f in spec.items():
+ if name not in body:
+ if "default" in f:
+ out[name] = f["default"]
+ continue
+ raise Refused(f"{kind} needs {name}")
+ out[name] = _value(name, f, body[name])
+ if "entity" in body:
+ out["entity"] = str(body["entity"])
+ return out
+
+
+def _value(name, f, v):
+ t = f.get("type", "number")
+ if t == "boolean":
+ if not isinstance(v, bool):
+ raise Refused(f"{name} must be true or false")
+ return v
+ if t == "enum":
+ if v not in f["values"]:
+ raise Refused(f"{name} must be one of {f['values']}")
+ return v
+ if t == "vector":
+ if not isinstance(v, list) or len(v) != f["len"]:
+ raise Refused(f"{name} must be a list of {f['len']} numbers")
+ return [_number(f"{name}[{i}]", f, x) for i, x in enumerate(v)]
+ x = _number(name, f, v)
+ if t == "integer":
+ if x != int(x):
+ raise Refused(f"{name} must be an integer")
+ return int(x)
+ return x
+
+
+def _number(name, f, v):
+ if isinstance(v, bool) or not isinstance(v, (int, float)) or (isinstance(v, int) and v.bit_length() > 60) or \
+ not math.isfinite(v):
+ raise Refused(f"{name} must be a finite number")
+ lo, hi = f.get("min", -math.inf), f.get("max", math.inf)
+ if not lo <= v <= hi:
+ raise Refused(f"{name} must be in [{lo}, {hi}]")
+ return round(float(v), f.get("digits", 6))
+
+
+# ------------------------------------------------------------------ request validation (core 0.2.11)
+# Every request body is checked before an endpoint reads it (check_body), and every act body against the action
+# layer's published schema before the layer parses it (check_action). A body that fails, or that makes the layer's
+# parse raise ANY exception, is the player's own error: refused (HTTP 400, counted), never a technical failure.
+BODY_MAX_DEPTH = 10 # nesting of lists / objects (the body object is depth 1)
+BODY_MAX_ITEMS = 4096 # elements of one list, keys of one object
+BODY_MAX_STR = 8192 # characters of one string (keys included)
+BODY_MAX_ABS = 1e15 # |number|: no action of any sport needs more (and a huge integer overflows a float)
+TYPE_MAX_STR = 64 # characters of the action type
+
+
+def check_body(value, depth: int = 1) -> None:
+ """Generic sanity of a decoded JSON request body (raises Refused): finite, bounded numbers; bounded strings, list
+ lengths and nesting."""
+ if depth > BODY_MAX_DEPTH:
+ raise Refused(f"the request is nested deeper than {BODY_MAX_DEPTH} levels")
+ if value is None or isinstance(value, bool):
+ return
+ if isinstance(value, str):
+ if len(value) > BODY_MAX_STR:
+ raise Refused(f"strings are limited to {BODY_MAX_STR} characters")
+ return
+ if isinstance(value, int):
+ if value.bit_length() > 60 or abs(value) > BODY_MAX_ABS:
+ raise Refused(f"numbers are limited to +-{BODY_MAX_ABS:g}")
+ return
+ if isinstance(value, float):
+ if not math.isfinite(value) or abs(value) > BODY_MAX_ABS:
+ raise Refused(f"numbers must be finite and within +-{BODY_MAX_ABS:g}")
+ return
+ if isinstance(value, (list, dict)):
+ if len(value) > BODY_MAX_ITEMS:
+ raise Refused(f"lists and objects are limited to {BODY_MAX_ITEMS} items")
+ for k in value if isinstance(value, dict) else ():
+ if not isinstance(k, str) or len(k) > BODY_MAX_STR:
+ raise Refused("object keys must be strings")
+ for x in value.values() if isinstance(value, dict) else value:
+ check_body(x, depth + 1)
+ return
+ raise Refused("unsupported JSON value")
+
+
+def _is_num(v) -> bool:
+ return not isinstance(v, bool) and isinstance(v, (int, float))
+
+
+def _lens(spec_len) -> set | None:
+ """A field's declared length: an int, or a text such as "1 or 2" (None: not declared)."""
+ if isinstance(spec_len, int) and not isinstance(spec_len, bool):
+ return {spec_len}
+ if isinstance(spec_len, str):
+ return {int(x) for x in spec_len.replace(",", " ").split() if x.isdigit()} or None
+ return None
+
+
+def _check_field(kind: str, name: str, f, v) -> None:
+ """The shape of one declared field (ranges and meaning stay with the layer's parse)."""
+ if not isinstance(f, dict):
+ return
+ t, where = f.get("type", "number"), f"{kind}.{name}"
+ if t in ("number", "integer"):
+ if not _is_num(v):
+ raise Refused(f"{where} must be a number")
+ elif t == "boolean":
+ if not isinstance(v, bool):
+ raise Refused(f"{where} must be true or false")
+ elif t == "enum":
+ if isinstance(v, (list, dict)):
+ raise Refused(f"{where} must be one of {f.get('values')}")
+ elif t == "vector":
+ lens = _lens(f.get("len"))
+ if not isinstance(v, list) or (lens and len(v) not in lens) or not all(_is_num(x) for x in v):
+ raise Refused(f"{where} must be a list of {f.get('len', 'some')} numbers")
+ elif t == "rows":
+ lens, top = _lens(f.get("len")), f.get("max_rows")
+ if not isinstance(v, list) or (isinstance(top, int) and len(v) > top) or not all(
+ isinstance(r, list) and (not lens or len(r) in lens) and all(_is_num(x) for x in r) for r in v):
+ raise Refused(f"{where} must be a list of rows of {f.get('len', 'some')} numbers"
+ + (f", at most {top} rows" if isinstance(top, int) else ""))
+ elif t == "list":
+ if not isinstance(v, list):
+ raise Refused(f"{where} must be a list")
+ elif t == "object":
+ if not isinstance(v, dict):
+ raise Refused(f"{where} must be an object")
+ keys = f.get("keys")
+ if isinstance(keys, (list, tuple)) and set(v) - set(keys):
+ raise Refused(f"{where}: unknown key(s) {sorted(set(v) - set(keys))[:8]}; the keys are {list(keys)}")
+
+
+def check_action(schema, body) -> None:
+ """An act body against the action layer's published schema, before the layer parses it (raises Refused). The
+ type, if given, must be a short string; for a type the schema names, each declared field that is present must
+ have its shape (number, boolean, scalar enum value, vector / rows lengths, list, object keys). Unknown types and
+ fields, ranges and defaults stay with the layer's parse (a layer may take an implicit type)."""
+ if not isinstance(body, dict):
+ raise Refused("the action must be a JSON object")
+ kind = body.get("type")
+ if kind is not None and (not isinstance(kind, str) or len(kind) > TYPE_MAX_STR):
+ raise Refused(f"type must be a string of at most {TYPE_MAX_STR} characters")
+ spec = schema.get(kind) if isinstance(schema, dict) and kind is not None else None
+ if isinstance(spec, dict):
+ for name, f in spec.items():
+ if name in body:
+ _check_field(kind, name, f, body[name])
+
+
+def parse_action(layer, seat: str, body, match, ctx: dict):
+ """What the core runs for every act (and core.local for built-in players): check_body, check_action against the
+ layer's schema (what /spec shows), then layer.parse. ANY exception on the way is the player's own error: Refused
+ (HTTP 400); a malformed action never ends a match as a technical failure. The exception's text is not shown to
+ the player; the caller may log it (`Refused.cause`)."""
+ try:
+ check_body(body)
+ check_action(layer.schema(match, seat) if hasattr(layer, "schema") else {}, body)
+ return layer.parse(seat, body, match, ctx)
+ except Refused:
+ raise
+ except Exception as exc: # noqa: BLE001
+ err = Refused("invalid action: the action layer could not read it (see /spec for the command schema)")
+ err.cause = f"{type(exc).__name__}: {str(exc)[:200]}"
+ raise err from exc
+
+
+class SchemaLayer(LowLayer):
+ """The default low level: the body is checked against Match.schema(seat); `ctx_keys` copies core facts (e.g. the
+ chess clocks) into the command so that the replay sees them."""
+
+ def __init__(self, ctx_keys: tuple[str, ...] = ()):
+ super().__init__(None)
+ self.ctx_keys = ctx_keys
+
+ def parse(self, seat, body, match, ctx):
+ cmd = check_command(match.schema(seat), body)
+ ents = tuple(match.entities(seat))
+ if ents and cmd.get("entity", ents[0]) not in ents:
+ raise Refused(f"entity must be one of {list(ents)}")
+ if ents:
+ cmd.setdefault("entity", ents[0])
+ for k in self.ctx_keys:
+ cmd[k] = ctx.get(k)
+ return cmd
+
+
+class Sport(Protocol):
+ name: str
+ protocol: str # "realtime" | "turn"
+ revision: str # bump on any change that alters play
+ source_dirs: list[str] # whose files enter source_sha (the plugin dir; the core adds itself)
+
+ def build(self, cfg: MatchConfig) -> Match: ...
+ def action_layer(self, level: str) -> ActionLayer: ...
+ def spec(self, cfg: MatchConfig, seat: str, match: Match) -> dict: ...
+ # optional: the scene for renderers, worker processes (render / plan), built-in players
+ def scene(self, cfg: MatchConfig): ... # renderers.base.Scene (needed when cameras() is used);
+ # the MATCH scene: the base of the presentation scene
+ # (sports/<s>/presentation) and the players' images
+ # unless that declares `players`
+ def worker_init(self, kind: str, seat: str, cfg: MatchConfig) -> Any: ...
+ def worker_call(self, obj: Any, kind: str, job: Any) -> dict: ...
+ def players(self) -> dict: ... # {name: factory(spec, seat, seed) -> built-in player}
+
+
+def sha_json(value) -> str:
+ return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"), default=float).encode()).hexdigest()
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/rcb1.py b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/rcb1.py
@@ -0,0 +1,83 @@
+"""RCB1 — a tiny binary frame for one JSON header plus N raw blobs (videos, image arrays, depth, proprio).
+
+ frame = b"RCB1" | header_len uint32 LE | header JSON (UTF-8) | blob_0 | blob_1 | ...
+ header = {"v": 1, "meta": {...}, "parts": [{"name", "kind", "len", ...}, ...]} # blobs in the same order
+
+kinds: "mp4" (fps, n), "jpeg", "array" (dtype, shape; C-order raw bytes), "json" (utf-8), "bytes".
+Zero dependencies for bytes/json parts; numpy only when you ask for arrays. Used on both sides (server and client),
+over HTTP bodies (Content-Type: application/x-rcb1) and equally usable over a raw socket. `python -m rcb1 unpack f dir`.
+"""
+from __future__ import annotations
+import json, struct, sys, pathlib
+
+MAGIC = b"RCB1"
+
+
+def encode(meta: dict, parts: list[tuple[str, str, bytes, dict]]) -> bytes:
+ """parts: [(name, kind, blob, extra), ...]; extra carries dtype/shape/fps/n."""
+ hdr_parts = []
+ for name, kind, blob, extra in parts:
+ d = {"name": name, "kind": kind, "len": len(blob)}
+ d.update({k: v for k, v in (extra or {}).items() if v is not None})
+ hdr_parts.append(d)
+ header = json.dumps({"v": 1, "meta": meta, "parts": hdr_parts}, separators=(",", ":")).encode()
+ return b"".join([MAGIC, struct.pack("<I", len(header)), header] + [blob for _, _, blob, _ in parts])
+
+
+def array_part(name: str, arr, extra: dict | None = None) -> tuple[str, str, bytes, dict]:
+ import numpy as np
+ a = np.ascontiguousarray(arr)
+ return (name, "array", a.tobytes(), {"dtype": str(a.dtype), "shape": list(a.shape), **(extra or {})})
+
+
+def decode(buf: bytes, arrays: bool = True) -> tuple[dict, dict]:
+ """-> (meta, parts) where parts[name] = {"kind", ..., "data"}; arrays become numpy arrays when arrays=True."""
+ if buf[:4] != MAGIC:
+ raise ValueError("not an RCB1 frame")
+ n = struct.unpack("<I", buf[4:8])[0]
+ header = json.loads(buf[8:8 + n].decode()); off = 8 + n
+ out = {}
+ for p in header["parts"]:
+ blob = buf[off:off + p["len"]]; off += p["len"]
+ d = dict(p)
+ if p["kind"] == "array" and arrays:
+ import numpy as np
+ d["data"] = np.frombuffer(blob, dtype=np.dtype(p["dtype"])).reshape(p["shape"])
+ elif p["kind"] == "json":
+ d["data"] = json.loads(blob.decode())
+ else:
+ d["data"] = blob
+ out[p["name"]] = d
+ return header.get("meta", {}), out
+
+
+def unpack_to_dir(buf: bytes, out_dir: str) -> list[str]:
+ """Write a frame's parts as files: mp4/jpeg/bytes verbatim, arrays as .npy, meta as meta.json."""
+ import numpy as np
+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)
+ meta, parts = decode(buf, arrays=True); written = []
+ (out / "meta.json").write_text(json.dumps(meta, indent=1)); written.append("meta.json")
+ for name, p in parts.items():
+ safe = name.replace("/", "__")
+ if p["kind"] == "array":
+ f = out / f"{safe}.npy"; np.save(f, p["data"])
+ elif p["kind"] == "mp4":
+ f = out / f"{safe}.mp4"; f.write_bytes(p["data"])
+ elif p["kind"] == "jpeg":
+ f = out / f"{safe}.jpg"; f.write_bytes(p["data"])
+ elif p["kind"] == "json":
+ f = out / f"{safe}.json"; f.write_text(json.dumps(p["data"], indent=1))
+ else:
+ f = out / f"{safe}.bin"; f.write_bytes(p["data"])
+ written.append(f.name)
+ return written
+
+
+if __name__ == "__main__":
+ if len(sys.argv) == 4 and sys.argv[1] == "unpack":
+ print("\n".join(unpack_to_dir(open(sys.argv[2], "rb").read(), sys.argv[3])))
+ elif len(sys.argv) == 3 and sys.argv[1] == "info":
+ meta, parts = decode(open(sys.argv[2], "rb").read(), arrays=False)
+ print(json.dumps(meta, indent=1)); [print(n, {k: v for k, v in p.items() if k != "data"}) for n, p in parts.items()]
+ else:
+ print(__doc__)
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/rcb_olympics.py b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/rcb_olympics.py
new file mode 100644
index 0000000000..f62893059e
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/rcb_olympics.py
@@ -0,0 +1,723 @@
+"""RoboOlympics sports behind eai-standard/2.3 (docs/PROTOCOL.md §4b; docs/benchmarks/roboolympics.md): the adapter
+that puts one RoboOlympics match (a sport plugin under sport/, core/sport.py's contract ②) behind rcb_service's `Sim`
+contract. The protocol itself -- the endpoints, RCB1, the realtime clock and its plan, budgets, evidence, crash
+recovery, finalize -- is rcb_realtime.py + rcb_service.py, unchanged (copied from HumanoidBench's 2.3 layer).
+
+The world. One control step of the service is one control step of the match (Match.step(), 10 ms of game time), with
+one exception, the break: when a unit ends (a point, a rally) the match stands still for BREAK_S of game time -- the
+clock keeps running (the service's control steps go on at 1/S of real speed, the agent's plan is consumed), nothing
+moves, nothing scores -- and play resumes by itself when the break is over, or at the agent's `ready` row, whichever
+comes first. Like a break in a real match: the time passes, the game does not.
+
+Actions. The agent's rows are the sport's own commands (the RoboOlympics action layer of the task's level), one row per
+command: table tennis and badminton (high level) `stroke` (the paddle's / racket's state at contact, t seconds after
+the command takes effect; the service plans the swing), badminton's `toss` (the serve), `rest` (back to the ready
+pose), air hockey (low level) `mallet` (the mallet's target, a row per control step, interpolable) and `stop`; every
+sport `ready`. A command takes effect at the control step its row is planned for: the sport's action layer parses it
+there, plans it from the state of that step and lowers it to a low-level command (core/sport.py ActionLayer.lower),
+which Match.apply() installs before the step runs -- the RoboOlympics realtime service's effect boundary. A row the
+sport refuses at that moment (e.g. a toss when it is not your serve) changes nothing and is counted in proprio.
+
+The journal. A sim row is [command id, ready]: the id of the low-level command that took effect at that step (-1:
+none), and 1 when the step carries the agent's ready. The low-level commands themselves are kept in
+DATA/commands.jsonl (one JSON line per id, written before the row that names it), so the journal plus that table is the
+whole record: a replay re-applies exactly the commands the live match applied, at their steps, and never plans again.
+The match is bit-exact (the RoboOlympics sports' golden replays), so a crash resumes by replaying the journal and a
+fresh-process replay decides the verdict (`success` = a finished match the agent won).
+"""
+from __future__ import annotations
+
+import hashlib
+import importlib.util
+import json
+import math
+import os
+import subprocess
+import sys
+import tempfile
+
+import numpy as np
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+if HERE not in sys.path:
+ sys.path.insert(0, HERE)
+
+from core import spec as spec_mod # noqa: E402
+from core.outcome import decide # noqa: E402
+from core.sport import FINISHED, UNIT_OVER, MatchConfig, Refused, parse_action # noqa: E402
+
+BREAK_S = 12.0 # game seconds of the break after every unit (120 s of wall time at S = 10)
+NAN = float("nan")
+READY_DOC = ("end the break now (between units only; ignored during play): play resumes at the next control step "
+ "(the row's value is ignored; put your review in submit's note)")
+
+
+def load_plugin(path: str):
+ """The sport's plugin module at `path` (its directory first on sys.path, so its simulator modules import); its
+ SPORT is the sport."""
+ path = os.path.abspath(path)
+ if os.path.dirname(path) not in sys.path:
+ sys.path.insert(0, os.path.dirname(path))
+ spec = importlib.util.spec_from_file_location("ro_plugin", path)
+ mod = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(mod)
+ return mod
+
+
+def _f(x, default=NAN) -> float:
+ try:
+ return float(x)
+ except (TypeError, ValueError):
+ return default
+
+
+def _json(x):
+ """JSON-exact Python values: what DATA/commands.jsonl holds, so the live match applies what a replay reads back."""
+ return json.loads(json.dumps(x, default=lambda o: o.tolist() if hasattr(o, "tolist") else float(o)))
+
+
+def _clip_box(row, i, lo, hi, name, out, k):
+ v = float(row[i])
+ c = min(max(v, lo), hi)
+ if c != v:
+ out.append({"row": k, "index": i, "reason": f"{name} clipped to [{lo:g}, {hi:g}]"})
+ row[i] = c
+
+
+def _clip_norm(row, sl, cap, name, out, k):
+ v = np.asarray(row[sl], float)
+ n = float(np.linalg.norm(v))
+ if n > cap:
+ row[sl] = v * (cap / n)
+ out.append({"row": k, "index": sl.start, "reason": f"|{name}| = {n:.3f} scaled to {cap:g}"})
+
+
+def _heard(o: dict, names: dict) -> list:
+ """The first time of each heard event (seconds on the current ball's clock), NaN if not heard."""
+ out = []
+ for key in names.values():
+ out.append(next((_f(h.get("t")) for h in o.get("heard") or [] if h.get("event") == key), NAN))
+ return out
+
+
+def _last_point(points, you="you") -> float:
+ if not points:
+ return NAN
+ w = points[-1].get("winner")
+ return 1.0 if w == you else 0.0 if w in (None, "let") else -1.0
+
+
+# ================================================================================================ per-sport profiles
+class _Profile:
+ """What differs between the sports: the agent's action types (as rows), their limits, the proprio columns, the
+ cameras and how they are drawn."""
+ types: dict = {}
+ interp: tuple = ()
+ cams: dict = {}
+ drop: tuple = () # sport.toml [spec] / Sport.spec() entries about RoboOlympics' own interface
+ rules: dict = {} # ... and what replaces them here
+
+ def __init__(self, sim):
+ self.sim = sim
+
+ def body(self, typ, row): # an agent row -> the sport's act body (None: nothing new)
+ raise NotImplementedError
+
+ def clip(self, typ, rows):
+ return rows, []
+
+ def command(self, typ):
+ """The row a gap in the plan is filled with (rcb_realtime: a submit whose `at` lies ahead holds "the target in
+ force" until then; a row is also interpolated from it): for a command that is not a target, zeros, which
+ to_sim reads as no command. No agent row is all zeros after clip() (Olympics.clip)."""
+ return np.zeros(int(self.types[typ]["dim"]))
+
+ def proprio(self) -> list:
+ raise NotImplementedError
+
+ def images(self, cams) -> dict:
+ raise NotImplementedError
+
+
+def _stroke_type(what, t_max, box, extra=""):
+ return {"dim": 10, "layout": ["t", "x", "y", "z", "nx", "ny", "nz", "vx", "vy", "vz"],
+ "units": "s, m, unit-free normal, m/s (your frame)",
+ "limits": {"t": [0.0, t_max], **box, "normal": "non-zero", "speed_max": 8.0},
+ "semantics": (f"the {what}'s state at contact t seconds after the command takes effect: centre x y z, face "
+ f"normal nx ny nz (pointing where the ball should go), velocity vx vy vz; it replaces the "
+ f"stroke under way; the service plans the swing (IK, joint speed limits) and the robot goes "
+ f"back to its ready pose after it. Out-of-range values are clipped (meta.clipped){extra}"),
+ "interpolable": False}
+
+
+class TableTennis(_Profile):
+ types = {
+ "stroke": _stroke_type("paddle blade", 2.5, {"x": [-1.2, 1.2], "y": [-2.5, -0.5], "z": [0.0, 1.2]},
+ "; the delivered state scatters by about 4 mm, 0.6 degrees and 2 %"),
+ "rest": {"dim": 1, "layout": ["unused"], "interpolable": False,
+ "semantics": "cancel the stroke under way: the arm returns to its ready pose (the value is ignored)"},
+ "ready": {"dim": 1, "layout": ["unused"], "interpolable": False, "semantics": READY_DOC}}
+ drop = ("duel", "observation", "action_high", "action_low", "real_time", "scatter_and_seed")
+ rules = {"scatter": "the serves, the opponent's returns and your strokes' execution scatter are drawn from the "
+ "task's frozen seed (never shown)"}
+ HEARD = {"opp_bounce": "bounce on the opponent's half", "own_bounce": "bounce on your half", "net": "net",
+ "paddle": "paddle", "robot": "robot", "floor": "floor"}
+ layout = (["score_you", "score_opponent", "point", "ball_is_serve", "t_since_played", "serve_in_s",
+ "ball_in_play", "ball_coming", "ball_going"]
+ + [f"heard_{k}_t" for k in HEARD]
+ + [f"q{i}" for i in range(1, 8)] + ["paddle_x", "paddle_y", "paddle_z", "paddle_nx", "paddle_ny", "paddle_nz"]
+ + ["stroke_active", "stroke_contact_in_s", "stroke_speed_scale", "stroke_blade_error_m",
+ "stroke_normal_error_deg", "stroke_ik_residual", "last_point_won"])
+
+ def __init__(self, sim):
+ super().__init__(sim)
+ import match
+ self.cams = {c["name"]: dict(c, fovy_deg=45.0, hw=[360, 480], focal_px=434.6, principal_point_px=[240, 180])
+ for c in match.Match.CAM_INFO}
+ self.view = None
+
+ def body(self, typ, row):
+ if typ == "rest":
+ return {"type": "none"}
+ r = [float(x) for x in row]
+ return {"type": "act", "t": r[0], "pos": r[1:4], "normal": r[4:7], "vel": r[7:10]}
+
+ def clip(self, typ, rows):
+ out = []
+ if typ != "stroke":
+ return rows, out
+ rows = np.array(rows, dtype=np.float64)
+ for k, row in enumerate(rows):
+ _clip_box(row, 0, 0.01, 2.5, "t", out, k)
+ for i, (lo, hi) in zip((1, 2, 3), ((-1.2, 1.2), (-2.5, -0.5), (0.0, 1.2))):
+ _clip_box(row, i, lo, hi, "xyz"[i - 1], out, k)
+ if np.linalg.norm(row[4:7]) < 1e-6:
+ row[4:7] = [0.0, 1.0, 0.0]
+ out.append({"row": k, "index": 4, "reason": "a zero normal replaced by (0, 1, 0)"})
+ _clip_norm(row, slice(7, 10), 8.0, "vel", out, k)
+ return rows, out
+
+ def proprio(self):
+ m = self.sim.m
+ o = m.observe(self.sim.seat)
+ R = m.R
+ bs = o.get("ball_state")
+ cmd = o.get("command")
+ la = getattr(R, "_last_act", None) or {}
+ active = isinstance(cmd, dict)
+ return ([_f(o["score"]["you"]), _f(o["score"]["opponent"]), _f(o.get("point")),
+ 1.0 if o.get("ball") == "serve" else 0.0, _f(o.get("t_since_played")), _f(o.get("serve_in_s"), 0.0),
+ float(bool(o.get("ball_in_play"))), float(bs == "coming to you"), float(bs == "going to the opponent")]
+ + _heard(o, self.HEARD) + [_f(x) for x in o["q"]] + [_f(x) for x in o["paddle_pos"]]
+ + [_f(x) for x in o["paddle_normal"]]
+ + [float(active), _f(cmd.get("contact_in_s")) if active else NAN,
+ _f(la.get("speed_scale")) if active else NAN, _f(la.get("blade_error_m")) if active else NAN,
+ _f(la.get("normal_error_deg")) if active else NAN, _f(la.get("ik_residual")) if active else NAN,
+ _last_point(R.points)])
+
+ def images(self, cams):
+ if self.view is None:
+ self.view = self.sim.mod.MatchView()
+ import match
+ R = self.sim.m.R
+ names = list(self.cams)
+ q, ox = R.s.d.qpos.copy(), R.opp_x()
+ text = f"k={R.k} t={R.t_since_launch():.2f}s"
+ return {c: self.view.tile(names.index(c), q, text, lambda scn, o=ox: match.Match._extra_geoms(None, scn, o), ox)
+ for c in cams}
+
+
+class Badminton(_Profile):
+ types = {
+ "stroke": _stroke_type("racket head", 5.0, {"x": [-3.4, 3.4], "y": [-7.5, -0.3], "z": [0.2, 3.0]},
+ "; it takes effect spec.rules.act.lead_steps control steps after its row's step (the "
+ "planning time), and t counts from then; a stroke or toss sent before the previous one "
+ "took effect is refused"),
+ "toss": {"dim": 4, "layout": ["x", "y", "z", "height"], "units": "m (your frame)", "interpolable": False,
+ "limits": {"z": [0.5, 1.8], "height": [0.0, 0.5], "y_max": -0.5, "reach_from_base": 1.0},
+ "semantics": ("your serve: the shuttle appears at x y z (from rest, or rising `height` straight up) "
+ "when the command takes effect (the same lead as a stroke); only the server, once per "
+ "serve, from the step the receiver is ready (proprio serve_phase = 1, open); then hit "
+ "it with a stroke (which may be sent before the toss)")},
+ "rest": {"dim": 1, "layout": ["unused"], "interpolable": False,
+ "semantics": "cancel the stroke under way: the robot returns to its ready pose, the base home"},
+ "ready": {"dim": 1, "layout": ["unused"], "interpolable": False, "semantics": READY_DOC}}
+ drop = ("duel", "observation", "lowlevel", "act")
+ PHASES = {"waiting": 0.0, "open": 1.0, "tossed": 2.0, "done": 3.0}
+ layout = (["score_you", "score_opponent", "point", "you_serve", "serve_court_right", "serve_phase",
+ "serve_opens_in_s", "serve_deadline_in_s", "serve_tossed_at_step", "ball_kind", "t_since_played",
+ "ball_in_play", "ball_not_served", "ball_tossed", "ball_coming", "ball_going",
+ "base_x", "base_y"] + [f"q{i}" for i in range(1, 8)]
+ + ["racket_x", "racket_y", "racket_z", "racket_nx", "racket_ny", "racket_nz",
+ "stroke_active", "stroke_contact_in_s", "stroke_traj_steps_left", "stroke_pending_effect_step",
+ "stroke_head_speed_limited", "stroke_pose_not_delivered", "last_point_won"])
+
+ def __init__(self, sim):
+ super().__init__(sim)
+ import bm
+ FOCAL_PX = sim.mod.FOCAL_PX
+ self.TOSS_Z, self.TOSS_H = tuple(bm.TOSS_Z), float(bm.TOSS_H_MAX)
+ self.types = dict(self.types)
+ self.types["toss"] = dict(self.types["toss"], limits={"z": list(bm.TOSS_Z), "height": [0.0, bm.TOSS_H_MAX],
+ "y_max": -0.5, "reach_from_base": bm.TOSS_REACH})
+ lead = sim.mod.lead_steps(sim.cfg.slowdown)
+ self.rules = {"act": {"lead_steps": lead, "lead_game_s": round(lead * bm.CONTROL_DT, 4),
+ "rule": (f"a stroke, a toss or a rest takes effect {lead} control steps after the step "
+ "its row is planned for (the stroke is planned meanwhile; proprio "
+ "stroke_pending_effect_step shows it); a stroke's t counts from that effect "
+ "step; another stroke, toss or rest planned before then is refused")},
+ "serve": {"command": ("a `toss` row: the shuttle appears at x y z when the command takes effect "
+ "(the same lead as a stroke) and rises `height` straight up (0: released "
+ "from rest); then hit it with a stroke (it may be sent before the toss)"),
+ "phases": ("proprio serve_phase: 0 waiting (the receiver is getting ready), 1 open "
+ "(toss now), 2 tossed, 3 done")}}
+ w, h = bm.Match.TILE
+ self.cams = {c["name"]: dict(c, fovy_deg=45.0, hw=[h, w], focal_px=FOCAL_PX, principal_point_px=[w / 2, h / 2])
+ for c in bm.Match.cam_info()}
+ self.view = None
+
+ def body(self, typ, row):
+ r = [float(x) for x in row]
+ if typ == "rest":
+ return {"type": "none"}
+ if typ == "toss":
+ return {"type": "toss", "pos": r[0:3], "height": r[3]}
+ return {"type": "act", "t": r[0], "pos": r[1:4], "normal": r[4:7], "vel": r[7:10]}
+
+ def clip(self, typ, rows):
+ out = []
+ rows = np.array(rows, dtype=np.float64)
+ if typ == "stroke":
+ for k, row in enumerate(rows):
+ _clip_box(row, 0, 0.01, 5.0, "t", out, k)
+ for i, (lo, hi) in zip((1, 2, 3), ((-3.4, 3.4), (-7.5, -0.3), (0.2, 3.0))):
+ _clip_box(row, i, lo, hi, "xyz"[i - 1], out, k)
+ if np.linalg.norm(row[4:7]) < 1e-6:
+ row[4:7] = [0.0, 1.0, 0.0]
+ out.append({"row": k, "index": 4, "reason": "a zero normal replaced by (0, 1, 0)"})
+ _clip_norm(row, slice(7, 10), 8.0, "vel", out, k)
+ elif typ == "toss":
+ for k, row in enumerate(rows):
+ _clip_box(row, 1, -7.5, -0.5, "y", out, k)
+ _clip_box(row, 2, self.TOSS_Z[0], self.TOSS_Z[1], "z", out, k)
+ _clip_box(row, 3, 0.0, self.TOSS_H, "height", out, k)
+ return rows, out
+
+ def proprio(self):
+ m = self.sim.m
+ o = m.observe(self.sim.seat)
+ sv = o.get("serve") or {}
+ bs = str(o.get("ball_state") or "")
+ cmd = o.get("command")
+ active = isinstance(cmd, dict) and "contact_in_s" in cmd
+ notes = str(cmd.get("stroke") or "") if active else ""
+ pend = o.get("pending_commands") or []
+ kind = {"serve": 0.0, "your serve": 1.0}.get(o.get("ball"), 2.0)
+ return ([_f(o["score"]["you"]), _f(o["score"]["opponent"]), _f(o.get("point")), float(bool(o.get("you_serve"))),
+ float(sv.get("court") == "right"), self.PHASES.get(sv.get("phase"), NAN), _f(sv.get("opens_in_s")),
+ _f(sv.get("deadline_in_s")), _f(sv.get("tossed_at_step")), kind, _f(o.get("t_since_played")),
+ float(bool(o.get("ball_in_play"))), float(bs == "not yet served"), float(bs.startswith("tossed")),
+ float(bs == "coming to you"), float(bs == "going to the opponent")]
+ + [_f(x) for x in o["robot_base_xy"]] + [_f(x) for x in o["q_arm"]] + [_f(x) for x in o["racket_pos"]]
+ + [_f(x) for x in o["racket_normal"]]
+ + [float(active), _f(cmd.get("contact_in_s")) if active else NAN,
+ _f(cmd.get("traj_steps_left"), 0.0) if isinstance(cmd, dict) else 0.0,
+ _f(pend[0].get("takes_effect_at_step")) if pend else NAN,
+ float("head speed limited" in notes), float("pose not delivered" in notes),
+ _last_point(m.g.points)])
+
+ def images(self, cams):
+ if self.view is None:
+ self.view = self.sim.mod.Views(True, "A")
+ g = self.sim.m.g
+ sn = {"qpos": g.s.d.qpos.copy(), "sh": tuple(float(x) for x in g.s.sh_p),
+ "shv": tuple(float(x) for x in g.s.sh_v), "opp": [float(x) for x in g.opp_xy()],
+ "k": int(g.k), "t": float(g.t_since_launch())}
+ names = list(self.cams)
+ return {c: self.view.tile(names.index(c), sn) for c in cams}
+
+
+class AirHockey(_Profile):
+ types = {
+ "mallet": {"dim": 2, "layout": ["x", "y"], "units": "m (the table frame)", "interpolable": True,
+ "semantics": ("the mallet centre's target; the robot drives the mallet there along a speed- and "
+ "acceleration-limited path (spec.sport.mallet_path) and holds it until replaced; "
+ "own half only: a target outside the workspace (spec.sport.workspace) is moved to "
+ "its nearest point (meta.clipped)")},
+ "stop": {"dim": 1, "layout": ["unused"], "interpolable": False,
+ "semantics": "the mallet stops where it is (its target becomes its position)"},
+ "ready": {"dim": 1, "layout": ["unused"], "interpolable": False, "semantics": READY_DOC}}
+ interp = ("mallet",)
+ drop = ("real_time", "action", "observation")
+ rules = {"review": ("every goal, foul or dead puck ends the rally: both mallets return home, the break follows "
+ "(spec.break), then the next rally starts")}
+ HOW = {"goal": 1.0, "seven_second_foul": 2.0, "dead_puck": 3.0, "time_cap": 4.0}
+ layout = (["score_you", "score_opponent", "rally", "t_play", "play_time_left_s",
+ "mallet_x", "mallet_y", "mallet_z", "target_x", "target_y"]
+ + [f"q{i}" for i in range(1, 8)] + ["q_striker1", "q_striker2"]
+ + [f"qd{i}" for i in range(1, 8)] + ["qd_striker1", "qd_striker2"]
+ + ["last_rally_how", "last_rally_scored", "last_rally_fouled", "last_rally_next_puck"])
+
+ def __init__(self, sim):
+ super().__init__(sim)
+ from renderers.base import CameraDef
+ self.P = sim.mod
+ self.camdefs = [CameraDef.from_dict(c) for c in sim.m.cameras(sim.seat)]
+ self.cams = {c.name: dict(c.to_dict(), **c.intrinsics(), hw=[c.height, c.width]) for c in self.camdefs}
+ self.renderer = None
+
+ def body(self, typ, row):
+ h = self.sim.m.h
+ if typ == "stop":
+ return {"type": "none"}
+ x, y = float(row[0]), float(row[1])
+ cur = h.commands.get(self.sim.seat) if isinstance(h.commands, dict) else None
+ if cur is not None and abs(float(cur[0]) - x) < 1e-9 and abs(float(cur[1]) - y) < 1e-9:
+ return None # the target in force: nothing new
+ return {"type": "target", "x": x, "y": y}
+
+ def clip(self, typ, rows):
+ out = []
+ rows = np.array(rows, dtype=np.float64)
+ if typ != "mallet":
+ return rows, out
+ H = self.P.H
+ for k, row in enumerate(rows):
+ w = H.workspace(self.sim.seat, row)
+ if not H.in_workspace(self.sim.seat, w, eps=0.0): # the box-then-radial clip may land a hair outside
+ w = H.workspace(self.sim.seat, [w[0] * 0.999999, w[1] * 0.999999])
+ w = [round(float(w[0]), 6), round(float(w[1]), 6)]
+ if abs(w[0] - row[0]) > 1e-9 or abs(w[1] - row[1]) > 1e-9:
+ out.append({"row": k, "index": 0, "reason": "outside the mallet workspace: moved to its nearest point"})
+ row[0], row[1] = w
+ return rows, out
+
+ def command(self, typ):
+ if typ == "mallet":
+ h = self.sim.m.h
+ return np.asarray(h.commands[self.sim.seat], np.float64)
+ return super().command(typ)
+
+ def proprio(self):
+ m = self.sim.m
+ o = m.observe(self.sim.seat)
+ h = m.h
+ sc = h.scores()
+ last = h.results[-1] if h.results else None
+ side = lambda s: NAN if last is None else (1.0 if s == "A" else -1.0 if s == "B" else 0.0) # noqa: E731
+ return ([_f(sc["A"]["points"]), _f(sc["B"]["points"]), _f(o["rally"]), _f(o["t_play"]),
+ _f(o["play_time_left_s"])] + [_f(x) for x in o["own"]["mallet_xyz"]]
+ + [_f(x) for x in o["own"]["command"]] + [_f(x) for x in o["own"]["joint_position"]]
+ + [_f(x) for x in o["own"]["joint_velocity"]]
+ + [NAN if last is None else self.HOW.get(last["how"], 5.0), side(last and last["winner"]),
+ side(last and last["guilty"]), side(last and last["next"])])
+
+ def images(self, cams):
+ if self.renderer is None:
+ import renderers
+ from core.observe import players_scene
+ sim = self.sim
+ self.renderer = renderers.load(sim.cfg.renderer or renderers.DEFAULT)(
+ players_scene(sim.sport, sim.plugin, sim.cfg))
+ imgs = self.renderer.render(self.sim.m.render_state(), self.camdefs)
+ return {c.name: img for c, img in zip(self.camdefs, imgs) if c.name in cams}
+
+
+PROFILES = {"tabletennis": TableTennis, "badminton": Badminton, "airhockey": AirHockey}
+
+
+# ================================================================================================ the Sim contract
+class Olympics:
+ """One RoboOlympics match against the scripted opponent (seat A) behind rcb_service.Sim (module docstring)."""
+
+ raw_dim = 2 # [command id (-1: none), ready]
+ depth_cameras: tuple = ()
+
+ def __init__(self, plugin: str, cfg: MatchConfig, data: str | None = None, task_text: str = "",
+ episode_text: str = "", break_s: float = BREAK_S):
+ self.plugin, self.cfg, self.data = os.path.abspath(plugin), cfg, data
+ self.mod = load_plugin(self.plugin)
+ self.sport = self.mod.SPORT
+ self.decl = spec_mod.load(self.plugin)
+ self.seat = cfg.seats[0]
+ self.task_text, self.episode_text = task_text, episode_text
+ self.commands: list = []
+ self.cmd_path = os.path.join(data, "commands.jsonl") if data else None
+ if self.cmd_path and os.path.exists(self.cmd_path): # a resumed service: the table so far
+ with open(self.cmd_path) as f:
+ for line in f:
+ try:
+ rec = json.loads(line)
+ except ValueError:
+ break # a line cut by a crash: no journal row names it
+ if rec.get("id") == len(self.commands):
+ self.commands.append(rec["low"])
+ self._new_match()
+ self.control_dt = float(self.m.dt)
+ self.break_steps = max(1, int(round(break_s / self.control_dt)))
+ self.max_control_steps = 10 ** 8 # no step cap: the match ends by its rules, else the wall clock
+ self.profile = PROFILES[self.sport.name](self)
+ self.cameras = tuple(self.profile.cams)
+ self.proprio_layout = (["match_step", "break", "break_left_s", "finished"] + list(self.profile.layout)
+ + ["commands_applied", "commands_refused", "last_refused_step"])
+
+ def _new_match(self):
+ self.m = self.sport.build(self.cfg)
+ self.layer = self.sport.action_layer(self.cfg.action_level)
+ self.steps = 0 # control steps of this episode, breaks included
+ self.in_break, self.break_left, self.breaks = False, 0, []
+ self.finished = self.won = False
+ self.applied = self.refused = self.dropped = 0
+ self.last_refused = -1
+
+ # ------------------------------------------------------------------ facts
+ def spec(self) -> dict:
+ sport = dict(self.decl.get("spec") or {}) # as RoboOlympics' public_spec: sport.toml, then Sport.spec()
+ sport.update(self.sport.spec(self.cfg, self.seat, self.m))
+ for k in ("calls", "image", "image_layout", "cameras", "action_interface") + tuple(self.profile.drop):
+ sport.pop(k, None)
+ for k, v in self.profile.rules.items():
+ sport[k] = {**sport[k], **v} if isinstance(v, dict) and isinstance(sport.get(k), dict) else v
+ if (self.decl.get("tiebreaks") or {}).get("text"):
+ sport["tiebreaks"] = self.decl["tiebreaks"]["text"]
+ types = {k: {kk: vv for kk, vv in v.items() if kk != "interpolable"} for k, v in self.profile.types.items()}
+ s = self.decl.get("sport") or {}
+ return {"simulator": "RoboOlympics on MuJoCo 3.3.7 (CPU)", "sport": s.get("name", self.sport.name),
+ "title": s.get("title"), "revision": self.sport.revision, "robot": sport.pop("robot", None),
+ "task_text": self.task_text, "episode": self.episode_text,
+ "match": {"format": self.cfg.format, "opponent_level": self.cfg.level, "action_level":
+ self.cfg.action_level, "you": self.seat},
+ "action_types": types, "cameras": self.profile.cams, "rules": sport,
+ "break": {"game_s": self.break_steps * self.control_dt, "control_steps": self.break_steps,
+ "rule": ("after every unit (a point, a rally) the match stands still for this much game "
+ "time: the clock runs on (control steps, wall time, your plan), nothing moves and "
+ "nothing scores; play resumes by itself at the end of the break, or at the control "
+ "step of your `ready` row. proprio: break (1 during it), break_left_s")},
+ "proprio_notes": ("one row per frame, columns proprio_layout; NaN = not applicable now; match_step = "
+ "the match's own control step (it stands still in a break; meta.control_steps "
+ "counts every step); times in game seconds; positions in your frame")}
+
+ def interpolable(self, typ: str) -> bool:
+ return typ in self.profile.interp
+
+ # ------------------------------------------------------------------ observation
+ def images(self, cameras, depth):
+ return self.profile.images(list(cameras)), {}
+
+ def proprio(self) -> np.ndarray:
+ own = [float(self.m.k), float(self.in_break), self.break_left * self.control_dt if self.in_break else 0.0,
+ float(self.finished)]
+ return np.asarray(own + self.profile.proprio() + [float(self.applied), float(self.refused),
+ float(self.last_refused)], np.float32)
+
+ # ------------------------------------------------------------------ actions
+ def clip(self, typ, rows):
+ """The profile's limits; a one-value command (rest, stop, ready: the value is ignored) becomes 1, so that no
+ agent row is all zeros, the gap filler's row (command())."""
+ try:
+ if int(self.profile.types.get(typ, {}).get("dim", 0)) == 1 and typ not in self.profile.interp:
+ return np.ones((len(rows), 1)), []
+ return self.profile.clip(typ, rows)
+ except Exception as exc: # noqa: BLE001 -- clip must never fail a request that passed the checks
+ return np.asarray(rows, np.float64), [{"row": 0, "index": 0, "reason": f"unchecked: {exc!r}"[:200]}]
+
+ def command(self, typ):
+ try:
+ return self.profile.command(typ)
+ except Exception: # noqa: BLE001
+ return np.zeros(int(self.profile.types.get(typ, {"dim": 1})["dim"]))
+
+ def hold(self):
+ return "hold", np.zeros(1)
+
+ def to_sim(self, typ, row) -> np.ndarray:
+ """At the step the row is planned for (rcb_service._step, right before step()): the row as a sim row. A
+ command is parsed, planned and lowered here, from this step's state, and enters the command table. An all-zero
+ row of a command type is no command: a gap the service filled with command() (clip() leaves no agent row so)."""
+ if typ not in self.profile.interp and not np.any(np.asarray(row, dtype=np.float64)):
+ return np.array([-1.0, 0.0])
+ if typ == "ready":
+ return np.array([-1.0, 1.0])
+ if typ not in self.profile.types or self.finished:
+ return np.array([-1.0, 0.0])
+ if self.in_break:
+ self.dropped += 1
+ return np.array([-1.0, 0.0])
+ body = self.profile.body(typ, row)
+ if body is None:
+ return np.array([-1.0, 0.0])
+ rec = {"id": len(self.commands), "step": self.steps, "match_k": int(self.m.k), "type": typ,
+ "row": [float(x) for x in row]}
+ try:
+ cmd = parse_action(self.layer, self.seat, body, self.m, {})
+ job = self.layer.snapshot(self.seat, cmd, self.m, self.applied + self.refused + 1)
+ prepared = self.layer.prepare(job) if job is not None else None
+ low, info = self.layer.lower(self.seat, cmd, prepared, self.m)
+ except Refused as exc:
+ self.refused += 1
+ self.last_refused = int(self.m.k)
+ self._log({**rec, "id": None, "refused": str(exc)[:300]})
+ return np.array([-1.0, 0.0])
+ rec.update(low=_json(low), info=_json(info))
+ self.commands.append(rec["low"])
+ self._log(rec)
+ return np.array([float(rec["id"]), 0.0])
+
+ def _log(self, rec):
+ if self.cmd_path:
+ with open(self.cmd_path, "a") as f:
+ f.write(json.dumps(rec, default=float) + "\n")
+ f.flush()
+
+ def step(self, row) -> tuple[bool, bool, dict]:
+ cid, ready = int(round(float(row[0]))), float(row[1]) > 0.5
+ self.steps += 1
+ if self.finished:
+ return True, self.won, {}
+ if self.in_break:
+ if ready or self.break_left <= 1:
+ self.in_break = False
+ self.breaks[-1].update(end=self.steps, by="ready" if ready else "time")
+ self.m.resume()
+ else:
+ self.break_left -= 1
+ return False, False, {}
+ if cid >= 0:
+ info = self.m.apply(self.seat, self.commands[cid]) or {}
+ if isinstance(info, dict) and "rejected" in info:
+ self.refused += 1
+ self.last_refused = int(self.m.k)
+ else:
+ self.applied += 1
+ self.m.step()
+ ph = self.m.phase()
+ if ph.state == FINISHED:
+ self.finished = True
+ out = decide(self.m, None, None, self.cfg.side_list(), self.cfg.side_of)
+ self.won = out.winner == self.cfg.side_of(self.seat)
+ return True, self.won, {}
+ if ph.state == UNIT_OVER:
+ self.in_break, self.break_left = True, self.break_steps
+ self.breaks.append({"start": self.steps, "match_k": int(self.m.k), "reason": ph.reason})
+ return False, False, {}
+
+ # ------------------------------------------------------------------ episode
+ def reset(self) -> None:
+ self._new_match()
+ self.profile = PROFILES[self.sport.name](self)
+
+ def state_sha(self) -> str:
+ own = json.dumps([self.steps, self.in_break, self.break_left, self.finished, self.won], sort_keys=True)
+ return hashlib.sha256((self.m.state_digest() + own).encode()).hexdigest()
+
+ def summary(self) -> dict:
+ out = decide(self.m, None, None, self.cfg.side_list(), self.cfg.side_of)
+ scores = self.m.scores()
+ you = self.cfg.side_of(self.seat)
+ them = [s for s in scores if s != you]
+ return {"sport": self.sport.name, "revision": self.sport.revision, "finished": self.finished,
+ "won": bool(self.finished and out.winner == you), "winner": out.winner, "decided_by": out.decided_by,
+ "scores": scores, "points_for": scores.get(you), "points_against": scores.get(them[0]) if them else None,
+ "match_steps": int(self.m.k), "control_steps": self.steps, "breaks": self.breaks,
+ "commands_applied": self.applied, "commands_refused": self.refused,
+ "rows_dropped_in_breaks": self.dropped, "cfg": self.cfg.to_json(), "break_steps": self.break_steps,
+ "sport_fields": _json(self.m.final_fields())}
+
+ # ------------------------------------------------------------------ the record, the replay, the video
+ def save_trajectory(self, rows, path, meta) -> None:
+ np.savez_compressed(path, rows=np.asarray(rows, np.float64).reshape(-1, self.raw_dim),
+ commands=np.array(json.dumps(self.commands)), cfg=np.array(json.dumps(self.cfg.to_json())),
+ break_steps=np.array(self.break_steps), meta=np.array(json.dumps(meta, default=str)),
+ layout=np.array(json.dumps(["command_id", "ready"])))
+
+ def _sub(self, mode: str, rows, out: str) -> dict:
+ """A fresh process (python rcb_olympics.py MODE ...): the replay never shares state with the live match."""
+ fd, tmp = tempfile.mkstemp(suffix=".npz", dir=self.data or None)
+ os.close(fd)
+ try:
+ self.save_trajectory(rows, tmp, {"for": mode})
+ env = dict(os.environ, RO_TASK_TEXT=self.task_text, RO_EPISODE_TEXT=self.episode_text)
+ r = subprocess.run([sys.executable, os.path.abspath(__file__), mode, self.plugin, tmp, out],
+ capture_output=True, text=True, env=env, timeout=3600)
+ if r.returncode:
+ raise RuntimeError(f"{mode} failed: {r.stderr[-1500:]}")
+ return json.loads(r.stdout.strip().splitlines()[-1])
+ finally:
+ os.unlink(tmp)
+
+ def verify(self, rows) -> dict:
+ out = os.path.join(self.data, "match.json") if self.data else os.devnull
+ rep = self._sub("replay", rows, out)
+ return {"success": bool(rep["won"]), "state_sha": rep["state_sha"]}
+
+ def render_video(self, rows, path) -> None:
+ self._sub("video", rows, path)
+
+
+# ================================================================================================ fresh processes
+def _rebuild(plugin: str, npz: str) -> tuple[Olympics, np.ndarray]:
+ z = np.load(npz)
+ cfg = MatchConfig.from_json(json.loads(str(z["cfg"])))
+ sim = Olympics(plugin, cfg, None, os.environ.get("RO_TASK_TEXT", ""), os.environ.get("RO_EPISODE_TEXT", ""))
+ sim.break_steps = int(z["break_steps"])
+ sim.commands = json.loads(str(z["commands"]))
+ return sim, np.asarray(z["rows"], np.float64).reshape(-1, sim.raw_dim)
+
+
+def replay_main(plugin: str, npz: str, out: str) -> dict:
+ sim, rows = _rebuild(plugin, npz)
+ for row in rows:
+ sim.step(row)
+ summary = {**sim.summary(), "state_sha": sim.state_sha()}
+ with open(out, "w") as f:
+ json.dump(summary, f, default=float)
+ return {"won": summary["won"], "state_sha": summary["state_sha"], "scores": summary["scores"]}
+
+
+def video_main(plugin: str, npz: str, out: str, max_frames: int = 1500) -> dict:
+ """The replay for humans: the cameras side by side, one frame every 4 control steps of play (game time at real speed:
+ 25 fps; sparser for a long match, at most about max_frames frames), breaks skipped; the score in the corner.
+ Writes out and out.last.png."""
+ import imageio.v2 as imageio
+ from PIL import Image, ImageDraw
+ sim, rows = _rebuild(plugin, npz)
+ every = max(4, math.ceil(len(rows) / max_frames))
+ cams = list(sim.cameras)
+ w = imageio.get_writer(out, fps=round(1.0 / (every * sim.control_dt)), macro_block_size=8, codec="libx264",
+ output_params=["-pix_fmt", "yuv420p"])
+ last, n = None, 0
+
+ def frame():
+ imgs = sim.images(cams, False)[0]
+ h = max(i.shape[0] for i in imgs.values())
+ row = np.concatenate([np.pad(imgs[c], ((0, h - imgs[c].shape[0]), (0, 0), (0, 0))) for c in cams], axis=1)
+ im = Image.fromarray(np.ascontiguousarray(row[..., :3]))
+ sc = sim.m.scores()
+ ImageDraw.Draw(im).text((8, im.height - 16), " ".join(f"{k} {v}" for k, v in sc.items()), fill=(255, 255, 0))
+ return np.asarray(im)
+
+ try:
+ for i, row in enumerate(rows):
+ was = sim.in_break
+ sim.step(row)
+ if (not was and i % every == 0) or sim.finished:
+ last = frame()
+ w.append_data(last)
+ n += 1
+ if sim.finished:
+ break
+ if last is None:
+ last = frame()
+ w.append_data(last)
+ n += 1
+ finally:
+ w.close()
+ Image.fromarray(last).save((out[:-4] if out.endswith(".mp4") else out) + ".last.png") # replay.last.png
+ return {"frames": n, "every": every}
+
+
+if __name__ == "__main__":
+ mode, plugin_path, npz_path, out_path = sys.argv[1:5]
+ res = replay_main(plugin_path, npz_path, out_path) if mode == "replay" else video_main(plugin_path, npz_path,
+ out_path)
+ print(json.dumps(res, default=float))
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/rcb_realtime.py b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/rcb_realtime.py
new file mode 100644
index 0000000000..e23f8cbd2c
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/rcb_realtime.py
@@ -0,0 +1,480 @@
+"""eai-standard/2.3, the standard-realtime mode's protocol: the sim service of HumanoidBench's `-standard-realtime` tasks
+(docs/PROTOCOL.md §4b, docs/LIMITED_MODE_PROTOCOL.md "Standard-realtime mode"; docs/benchmarks/humanoidbench.md). Entry
+point of the sidecar: `python /srv/rcb_realtime.py` (the adapter is server.py's, unchanged). 2.3 is 2.2 plus the realtime
+capability, every 2.2 addition optional: this service is rcb_service's 2.1 service with the capability, and reports
+eai-standard/2.3.
+
+It extends rcb_service.Service: the same endpoints, RCB1 frames, budgets (reset, wall clock), evidence, crash recovery
+and finalize. Only the time model differs. In standard mode time moves only inside calls; here the episode has a clock:
+
+- An episode starts paused, at the frozen start with the servos holding their starting targets. Its clock starts at its
+ first POST /submit or POST /observe with seconds > 0 (again after every reset, and after a crash recovery). From then
+ on one control step runs every control_dt x slowdown seconds of wall time, whether or not the agent sends anything,
+ until the episode ends; the clock stops there.
+- The service keeps a plan: one target row per coming control step. /submit expands its chunk (rows dt apart, `linear`
+ or `hold`, exactly as 2.1 does) into control steps and writes it into the plan from control step `at` (default: the
+ next one), replacing whatever was planned from there on, and answers at once. A chunk that arrives after its `at`
+ loses the rows whose steps are gone (`late_steps`). When the plan runs out the last target is held (zero-order
+ hold): a slow agent's robot keeps its last servo targets.
+- /observe with seconds = 0 answers at once; with seconds > 0 it watches the running episode that long (robot time)
+ and returns what the cameras saw. It never changes the plan.
+- `cameras = []` asks for no images at all (in 2.1 an empty list means every camera): a controller's proprio-only call.
+
+Grading is unchanged: every executed control step's sim row is journaled (trajectory_live.f64) and the graded episode's
+rows are replayed in a fresh simulator at the end. What is graded is the rows the simulator applied, not what was
+submitted, so the replay equals the live run however the timing went. Evidence added (never visible to the agent):
+ticks.f64 (per journal row: wall time, and the call whose chunk gave the row, -1 for a held one), calls.jsonl (one line
+per call; no calls/NNNNNN/ directories: a controller calls 50 times a second) and submitted.f64 (every row as sent:
+call id, then the row). final.json adds realtime, slowdown, max_lag_s, stalls, held_steps and late_steps.
+
+Threads: the simulator and its GL context belong to the main thread, which runs the clock and serves every request in
+between control steps; the HTTP threads only read, queue and encode. A control step that is due runs before any waiting
+request. A service that falls behind (a long render) runs the missed steps back to back, skipping none; more than
+MAX_LAG_S behind, it drops the debt instead (a stall, counted) rather than fast-forward the robot.
+
+A crash resumes the same episode from its last checkpoint (one per second of robot time while the clock runs), paused.
+A simulator crash is an infrastructure failure, never the agent's (PROTOCOL §4b, owner 2026-10-08). No call spans a
+crash here (submit answers at once), so a crash is never put down to the agent's call: past RCB_MAX_RESUMES restarts the
+trial ends `sim_crashed` (infra_error), a failed resume `resume_failed` (infra_error), and a simulator error that ends
+the graded episode (reason "error") sets infra_error in final.json too.
+"""
+from __future__ import annotations
+
+import collections
+import json
+import os
+import queue
+import sys
+import threading
+import time
+import traceback
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from urllib.parse import urlparse
+
+import numpy as np
+
+import rcb_service
+from rcb_service import MAX_BODY, Recorder, Refused, Service, bad_request
+
+PROTOCOL = "eai-standard/2.3" # the standard-realtime mode's protocol (PROTOCOL §4b); rcb_service.py itself serves 2.1
+MAX_LAG_S = 0.5 # behind the clock by more than this: drop the debt (a stall) instead of catching up
+CHECKPOINT_S = 1.0 # robot time between checkpoints while the clock runs (the most a crash loses)
+
+
+class _Job:
+ """One HTTP request, handed from its HTTP thread to the simulator's thread and back."""
+
+ def __init__(self, method: str, path: str, body: bytes, content_length: int | None = None):
+ self.method, self.path, self.body, self.content_length = method, path, body, content_length
+ self.done = threading.Event()
+ self.reply: tuple = () # ("raw", code, ctype, body) | ("rcb1", meta, parts) | ("rec", meta, Recorder)
+
+ def finish(self, *reply) -> None:
+ self.reply = reply
+ self.done.set()
+
+
+class _Watch:
+ """A pending /observe with seconds > 0: completes once its control steps have run (or the episode ended)."""
+
+ def __init__(self, job: _Job, rec: Recorder, start: int, steps: int, cameras: list[str], obs_id: int):
+ self.job, self.rec, self.cameras, self.obs_id = job, rec, cameras, obs_id
+ self.start, self.end = start, start + steps
+
+
+class RealtimeService(Service):
+ """rcb_service.Service with the realtime clock (module docstring)."""
+
+ def __init__(self, sim, *, slowdown: float | None = None, **kw):
+ self.slowdown = float(os.environ.get("RCB_SLOWDOWN") or 1.0) if slowdown is None else float(slowdown)
+ if not self.slowdown > 0:
+ raise ValueError("RCB_SLOWDOWN must be > 0")
+ self.wall_dt = sim.control_dt * self.slowdown
+ self.max_ahead = int(round(float(kw.get("max_chunk_s", 10.0)) / sim.control_dt)) # how far ahead `at` may be
+ self.plan: collections.deque = collections.deque() # (type, row, call id) for each coming control step
+ self.running = False
+ self.anchor_t = self.anchor_n = 0 # the clock: control step anchor_n was due at anchor_t
+ self.watches: list[_Watch] = []
+ self.q: queue.Queue = queue.Queue()
+ self.max_lag = self.lag = 0.0
+ self.stalls = self.held_steps = self.late_steps = 0
+ self._ticks: list[tuple[float, float]] = [] # (wall time, call id) per journal row not yet on disk
+ super().__init__(sim, **kw)
+ self.ticks_path = os.path.join(self.data, "ticks.f64")
+ self.ckpt_every = max(1, int(round(CHECKPOINT_S / sim.control_dt)))
+
+ # ------------------------------------------------------------------ spec, status, evidence
+ def _spec(self) -> dict:
+ spec = super()._spec()
+ spec["protocol"] = PROTOCOL
+ cdt = self.sim.control_dt
+ spec["timing"] = {
+ "realtime": True, "slowdown": self.slowdown, "control_dt": cdt,
+ "wall_s_per_control_step": cdt * self.slowdown,
+ "clock": "an episode starts paused; its clock starts at its first submit or observe with seconds > 0 (also "
+ "after a reset) and then runs one control step every wall_s_per_control_step seconds, whatever "
+ "you do, until the episode ends",
+ "submit": "answers at once: the chunk (rows dt apart, linear or hold) becomes the plan from control step "
+ "`at` (default: the next one), replacing what was planned from there; rows for steps already "
+ "gone are dropped (meta.late_steps); after the plan's last row that target is held",
+ "observe": "seconds = 0: now, at once; seconds > 0: watches the running episode that long and returns what "
+ "the cameras saw; never changes the plan",
+ "max_ahead_steps": self.max_ahead,
+ "no_images": "cameras = [] returns no images, only proprioception (the fastest call)"}
+ return spec
+
+ def _realtime_counters(self) -> dict:
+ return {"running": self.running, "planned_steps": len(self.plan), "lag_s": round(self.lag, 4)}
+
+ def status(self) -> dict:
+ return {**super().status(), **self._realtime_counters()}
+
+ def meta(self) -> dict:
+ return {**super().meta(), **self._realtime_counters()}
+
+ def _timing_record(self) -> dict:
+ return {"protocol": PROTOCOL, "realtime": 1, "slowdown": self.slowdown, "max_lag_s": round(self.max_lag, 4),
+ "stalls": self.stalls, "held_steps": self.held_steps, "late_steps": self.late_steps}
+
+ def _write_final(self) -> None:
+ self.verdict.update(self._timing_record()) # final.json merges the verdict; none of these keys is a verdict's
+ if self.reason == "error": # a simulator error ended the graded episode: infrastructure (§4b)
+ self.verdict["infra_error"] = 1
+ else: # (an episode that erred and was reset away is not graded)
+ self.verdict.pop("infra_error", None)
+ super()._write_final()
+
+ def _checkpoint(self, ev: str, **kw) -> None:
+ if self._ticks: # the tick log first: a crash in between leaves it too long
+ with open(self.ticks_path, "ab") as f:
+ f.write(np.asarray(self._ticks, dtype=np.float64).tobytes())
+ self._ticks = []
+ super()._checkpoint(ev, **kw)
+
+ def _save_call(self, meta: dict, actions: np.ndarray | None) -> None:
+ keep = ("type", "n_rows", "dt", "interpolate", "at", "start_step", "late_steps", "planned_steps", "seconds",
+ "control_steps", "episode", "done", "reason", "n_clipped", "lag_s", "note")
+ line = {"call": self.calls, "ts": time.time(), **{k: meta[k] for k in keep if k in meta}}
+ with open(os.path.join(self.data, "calls.jsonl"), "a") as f:
+ f.write(json.dumps(line) + "\n")
+ if actions is not None:
+ rows = np.concatenate([np.full((len(actions), 1), float(self.calls)), actions], axis=1)
+ with open(os.path.join(self.data, "submitted.f64"), "ab") as f:
+ f.write(np.asarray(rows, dtype=np.float64).tobytes())
+
+ # ------------------------------------------------------------------ start, clock
+ def start(self) -> None:
+ super().start()
+ rows = np.fromfile(self.ticks_path, dtype=np.float64) if os.path.exists(self.ticks_path) else np.zeros(0)
+ n = self.journal_rows
+ if rows.size > 2 * n: # the steps a crash lost from the journal go from the tick log too
+ rows[: 2 * n].tofile(self.ticks_path)
+ elif rows.size < 2 * n: # (an older tick log, short of the journal: pad it as unknown)
+ np.concatenate([rows, np.full(2 * n - rows.size, np.nan)]).tofile(self.ticks_path)
+ self.running = False # a resumed episode waits, paused, for the agent's next call
+
+ def _start_clock(self) -> None:
+ if not self.running and not self.done and not self.stopping:
+ self.running, self.anchor_t, self.anchor_n = True, time.monotonic(), len(self.episode)
+ self.log("clock_start", control_steps=len(self.episode), episode=self.resets + 1)
+
+ def _stop_clock(self, why: str) -> None:
+ if self.running:
+ self.running = False
+ self.log("clock_stop", why=why, control_steps=len(self.episode), max_lag_s=round(self.max_lag, 4))
+ self.plan.clear()
+
+ def _end(self, reason: str) -> None:
+ super()._end(reason)
+ self._stop_clock(reason) # pending watches are completed by whoever ended it, after this
+
+ def due_in(self, now: float) -> float | None:
+ """Seconds until the next control step is due (<= 0: due now); None while the clock is stopped."""
+ if not self.running or self.done or self.stopping:
+ return None
+ return self.anchor_t + (len(self.episode) - self.anchor_n) * self.wall_dt - now
+
+ def tick(self) -> None:
+ """One control step of the clock: the plan's row for it, or the held target."""
+ now = time.monotonic()
+ lag = -(self.due_in(now) or 0.0)
+ if lag > MAX_LAG_S: # far behind: re-anchor rather than rush the robot through the debt
+ self.stalls += 1
+ self.log("stall", behind_s=round(lag, 3), control_steps=len(self.episode))
+ self.anchor_t, self.anchor_n, lag = now, len(self.episode), 0.0
+ self.lag, self.max_lag = max(lag, 0.0), max(self.max_lag, lag)
+ if self.plan:
+ typ, row, src = self.plan.popleft()
+ else:
+ (typ, row), src = self.sim.hold(), -1
+ self.held_steps += 1
+ before = self.journal_rows
+ self._ticks.append((time.time(), float(src)))
+ try:
+ self._step(typ, row)
+ except Exception as exc: # noqa: BLE001 -- it ran and failed: the episode ends, as on hardware
+ traceback.print_exc()
+ if self.journal_rows == before:
+ self._ticks.pop()
+ self.log("error", path="clock", error=repr(exc)[:500])
+ self._end("error")
+ self._release_watches()
+ return
+ for w in list(self.watches):
+ w.rec.step()
+ if self.done or len(self.episode) >= w.end:
+ self._complete_watch(w)
+ if not self.done and len(self.episode) % self.ckpt_every == 0:
+ self._checkpoint("tick")
+
+ # ------------------------------------------------------------------ requests (simulator thread)
+ def dispatch(self, job: _Job) -> None:
+ """Serve one queued request; a watch finishes later, from tick()."""
+ try:
+ self.first_request()
+ path = urlparse(job.path).path
+ if job.method == "GET" and path in ("/spec", "/status"):
+ return job.finish("raw", *self._reply_json(200, self.spec if path == "/spec" else self.status()))
+ routes = {"/submit": self._rt_submit, "/observe": self._rt_observe}
+ if self.reset_budget:
+ routes["/reset"] = self._rt_reset
+ if job.method != "POST" or path not in routes:
+ return job.finish("raw", *self._reply_json(404, {"error": "no such endpoint"}))
+ if (len(job.body) if job.content_length is None else job.content_length) > MAX_BODY:
+ return job.finish("raw", *self._reply_json(413, {"error": f"request body over {MAX_BODY} bytes"}))
+ try:
+ meta, parts = self._decode(job.body)
+ except Exception as exc: # noqa: BLE001 -- any malformed body is the caller's error
+ return job.finish("raw", *self._reply_json(400, {"error": f"malformed body: {exc}"[:300]}))
+ try:
+ routes[path](meta, parts, job)
+ except Refused as exc: # 400 (bad_request), 409: nothing changed
+ job.finish("raw", *self._reply_json(exc.code, exc.body))
+ except Exception as exc: # noqa: BLE001 -- it ran and failed: the episode ends, as on hardware
+ traceback.print_exc()
+ self.log("error", path=path, error=repr(exc)[:500])
+ self._end("error")
+ self._release_watches()
+ if not job.done.is_set():
+ job.finish("raw", *self._reply_json(500, {"error": "simulator error", "detail": repr(exc)[:200]}))
+ except Exception as exc: # noqa: BLE001 -- never leave an HTTP thread waiting forever
+ traceback.print_exc()
+ if not job.done.is_set():
+ job.finish("raw", *self._reply_json(500, {"error": "service error", "detail": repr(exc)[:200]}))
+
+ def _view_rt(self, meta: dict, default_video: str) -> tuple[list[str], int, str, bool]:
+ """2.1's _view, plus cameras = [] for no images."""
+ none = isinstance(meta.get("cameras"), list) and not meta["cameras"]
+ cams, fps, video, depth = self._view(meta, default_video)
+ return ([], fps, "none", False) if none else (cams, fps, video, depth)
+
+ def _planned(self, step: int, nxt: int, typ: str) -> np.ndarray:
+ """The target in force at control step `step` (>= nxt - 1) as things stand: the plan's row for it, else the
+ plan's last row (held), else -- nothing planned, or a step already run -- the current command."""
+ i = step - nxt
+ if i < 0 or not self.plan:
+ return np.asarray(self.sim.command(typ), dtype=np.float64)
+ return np.asarray(self.plan[min(i, len(self.plan) - 1)][1], dtype=np.float64)
+
+ def _rt_submit(self, meta: dict, parts: dict, job: _Job) -> None:
+ if self.done or self.stopping:
+ raise self._conflict()
+ nxt = len(self.episode)
+ with bad_request():
+ typ = meta.get("type")
+ if not isinstance(typ, str) or typ not in self.types:
+ raise ValueError(f"type must be one of {sorted(self.types)}")
+ try:
+ A = np.asarray(parts["actions"]["data"] if "actions" in parts else meta.get("actions"),
+ dtype=np.float64)
+ except (TypeError, ValueError, KeyError):
+ raise ValueError("send the actions as an RCB1 array part `actions` or a JSON list of rows") from None
+ dim = int(self.types[typ]["dim"])
+ if A.ndim != 2 or A.shape[0] < 1 or A.shape[1] != dim:
+ raise ValueError(f"{typ} actions must be (T, {dim}) with T >= 1, got {list(A.shape)}")
+ if not np.all(np.isfinite(A)):
+ raise ValueError("actions contain NaN or inf")
+ cdt = self.sim.control_dt
+ try:
+ dt = cdt if meta.get("dt") is None else float(meta["dt"])
+ except (TypeError, ValueError):
+ raise ValueError("dt must be a number of seconds") from None
+ k = round(dt / cdt) if np.isfinite(dt / cdt) else 0
+ if k < 1 or abs(k * cdt - dt) > 1e-9:
+ raise ValueError(f"dt must be a positive whole multiple of control_dt = {cdt} s (never rounded)")
+ if k > 1 and not self.sim.interpolable(typ):
+ raise ValueError(f"{typ}: one row is one control step, so dt must be control_dt = {cdt} s")
+ if len(A) * k * cdt > self.max_chunk_s + 1e-9:
+ raise ValueError(f"the chunk covers {len(A) * k * cdt:g} s: "
+ f"more than max_chunk_s = {self.max_chunk_s:g}")
+ interp = meta.get("interpolate", "linear")
+ if interp not in ("linear", "hold"):
+ raise ValueError("interpolate must be linear or hold")
+ at = meta.get("at")
+ if at is not None:
+ if isinstance(at, bool) or not isinstance(at, (int, float)) or at != int(at) or at < 0:
+ raise ValueError("at must be a control step of this episode (an integer >= 0), "
+ "or null for the next one")
+ at = int(at)
+ if at - nxt > self.max_ahead:
+ raise ValueError(f"at = {at} is more than max_ahead_steps = {self.max_ahead} control steps ahead "
+ f"of the next one ({nxt})")
+ at = nxt if at is None else at
+ cams, fps, video, depth = self._view_rt(meta, "none")
+ rows, clipped = self.sim.clip(typ, A)
+ prev = self._planned(at - 1, nxt, typ) # linear starts from the target in force just before `at`
+ steps = []
+ for row in rows:
+ for j in range(1, k + 1):
+ steps.append(row if interp == "hold" else prev + (row - prev) * (j / k))
+ prev = row
+ late = max(0, nxt - at)
+ keep = at - nxt if at > nxt else 0
+ self.calls += 1
+ self.rows += len(A)
+ head = list(self.plan)[:keep]
+ if len(head) < keep: # a gap before `at`: the target in force then is held through it
+ fill = self._planned(at - 1, nxt, typ)
+ head += [(typ, fill, -1)] * (keep - len(head))
+ self.plan = collections.deque(head + [(typ, s, self.calls) for s in steps[late:]])
+ self.late_steps += min(late, len(steps))
+ self._start_clock()
+ rec = Recorder(self.sim, cams, fps, depth, "none")
+ rec.start()
+ rec.finish()
+ out = {**self.meta(), "chunk_id": self.calls, "type": typ, "n_rows": int(len(A)), "dt": dt,
+ "interpolate": interp, "at": at, "start_step": max(at, nxt), "late_steps": late,
+ "plan_end_step": nxt + len(self.plan), "clipped": clipped[:200], "n_clipped": len(clipped), "ok": True}
+ self._save_call({**out, "note": str(meta.get("note") or "")[:200]}, A)
+ job.finish("rec", out, rec)
+
+ def _rt_observe(self, meta: dict, parts: dict, job: _Job) -> None:
+ with bad_request():
+ try:
+ seconds = float(meta.get("seconds") or 0.0)
+ except (TypeError, ValueError):
+ raise ValueError("seconds must be a number") from None
+ if not 0.0 <= seconds <= self.max_watch_s:
+ raise ValueError(f"seconds must be in [0, {self.max_watch_s:g}]")
+ cams, fps, video, depth = self._view_rt(meta, "frames")
+ n = int(round(seconds / self.sim.control_dt)) if not (self.done or self.stopping) else 0
+ rec = Recorder(self.sim, cams, fps, depth, video if n or video != "mp4" else "frames") # no time: no video
+ self._frame_budget(rec, n)
+ self.calls += 1
+ rec.start()
+ if not n:
+ rec.finish()
+ out = {**self.meta(), "obs_id": self.calls, "seconds": 0.0, "control_steps_watch": 0, "ok": True}
+ self._save_call(out, None)
+ return job.finish("rec", out, rec)
+ self._start_clock()
+ self.watches.append(_Watch(job, rec, len(self.episode), n, cams, self.calls))
+
+ def _complete_watch(self, w: _Watch) -> None:
+ self.watches.remove(w)
+ w.rec.finish()
+ ran = max(0, min(len(self.episode), w.end) - w.start)
+ out = {**self.meta(), "obs_id": w.obs_id, "seconds": round(ran * self.sim.control_dt, 4),
+ "control_steps_watch": ran, "ok": True}
+ self._save_call(out, None)
+ w.job.finish("rec", out, w.rec)
+
+ def _release_watches(self) -> None:
+ for w in list(self.watches):
+ self._complete_watch(w)
+
+ def _rt_reset(self, meta: dict, parts: dict, job: _Job) -> None:
+ self._release_watches()
+ out, prts = self._reset(meta, parts) # 2.1's reset: checks, abandons the episode, a new one (paused)
+ self._stop_clock("reset")
+ job.finish("rcb1", {**out, **self._realtime_counters()}, prts)
+
+ # ------------------------------------------------------------------ the loop (simulator thread) and HTTP
+ def poll(self) -> None:
+ """After SIGUSR1: end the episode, answer the pending watches, finalize (Service.poll, plus the watches)."""
+ if self.stopping and not self.finalized:
+ if not self.done:
+ self._end("timeout")
+ self._release_watches()
+ self._finalize()
+
+ def loop(self, until: threading.Event | None = None) -> None:
+ """The simulator thread: control steps when due, requests in between, the wrap-up after SIGUSR1."""
+ while until is None or not until.is_set():
+ self.poll()
+ wait = self.due_in(time.monotonic())
+ if wait is not None and wait <= 0:
+ self.tick()
+ continue
+ try:
+ job = self.q.get(timeout=0.25 if wait is None else min(wait, 0.25))
+ except queue.Empty:
+ continue
+ self.dispatch(job)
+
+ def submit_job(self, job: _Job) -> tuple[int, str, bytes]:
+ """From an HTTP thread: queue the request, wait for the simulator thread, encode the answer here."""
+ self.q.put(job)
+ job.done.wait()
+ kind, *rest = job.reply
+ if kind == "raw":
+ return tuple(rest)
+ meta, payload = rest # a Recorder's parts are encoded here, off the simulator's thread
+ return self._reply_rcb1(meta, payload.parts() if kind == "rec" else payload)
+
+ def http_server(self, address: tuple[str, int]) -> ThreadingHTTPServer:
+ svc = self
+
+ class Handler(BaseHTTPRequestHandler):
+ timeout = 120
+
+ def log_message(self, *a):
+ pass
+
+ def _send(self, code: int, ctype: str, body: bytes) -> None:
+ self.send_response(code)
+ self.send_header("Content-Type", ctype)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_GET(self):
+ self._send(*svc.submit_job(_Job("GET", self.path, b"")))
+
+ def do_POST(self):
+ try:
+ n = int(self.headers.get("Content-Length") or 0)
+ except ValueError:
+ return self._send(*svc._reply_json(400, {"error": "bad Content-Length"}))
+ if n > MAX_BODY: # refused unread: drop the connection with it
+ self.close_connection = True
+ return self._send(*svc.submit_job(_Job("POST", self.path, b"", content_length=n)))
+ self._send(*svc.submit_job(_Job("POST", self.path, self.rfile.read(n))))
+
+ class Server(ThreadingHTTPServer):
+ daemon_threads = True
+
+ return Server(address, Handler)
+
+ def serve(self, port: int = 8000) -> None:
+ import signal
+ signal.signal(signal.SIGUSR1, self.on_sigusr1)
+ srv = self.bind(port)
+ threading.Thread(target=srv.serve_forever, name="http", daemon=True).start()
+ print(f"{rcb_service.PROTOCOL} sim service (realtime, slowdown {self.slowdown:g}) ready on :{port}", flush=True)
+ self.loop()
+
+
+def main(build, port: int = 8000) -> None:
+ """rcb_service.main -- the start count, back-off, startup watchdog, resume -- with this service in place of
+ Service (RCB_SLOWDOWN: 1 = real time), and eai-standard/2.3 in everything it logs and writes."""
+ rcb_service.Service = RealtimeService
+ rcb_service.PROTOCOL = PROTOCOL
+ rcb_service.main(build, port)
+
+
+if __name__ == "__main__":
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ import server # noqa: E402 -- the HumanoidBench adapter; picks the GL backend and restores the reward on import
+
+ main(server.build)
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/rcb_service.py b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/rcb_service.py
new file mode 100644
index 0000000000..14c53a477b
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/rcb_service.py
@@ -0,0 +1,759 @@
+"""eai-standard/2.1 sim service: the simulator-agnostic half of a standard-mode sidecar (docs/PROTOCOL.md §4,
+docs/LIMITED_MODE_PROTOCOL.md).
+
+The robot as a service: the agent reaches a simulator it cannot open over HTTP. GET /spec, GET /status, POST /observe
+and POST /submit; POST /reset exists only when the run grants resets (budget.reset > 0); everything else is 404.
+Responses that carry data are RCB1 frames (rcb1.py), never base64. Everything simulator-specific comes in through an
+adapter (the `Sim` contract below), so this file imports no simulator: a sidecar is its benchmark's adapter plus this.
+
+One thread does all of it -- the HTTP requests, the SIGUSR1 wrap-up, the finalize -- because a simulator's GL context
+belongs to the thread that made it (MuJoCo renders black frames from any other).
+
+The episode starts when the service is ready. It ends on success, by the task's own rule ("failed": the robot fell,
+the episode's control steps ran out), on a simulator error ("error"), or at SIGUSR1 ("timeout": the collect hook, once
+the agent's container is gone). With a reset budget, POST /reset abandons the running episode and starts another from
+the frozen instance; only the last episode is graded, and a success ends the trial.
+
+A request is checked in full before anything runs: whatever is wrong with it is a 400 and nothing ran. Once it runs,
+any failure is the simulator's: a 500, and the episode ends ("error").
+
+Evidence under DATA, never visible to the agent:
+ episode.jsonl one line per event; every state the service may resume from is a checkpoint (it carries
+ state_sha and journal_rows)
+ trajectory_live.f64 the journal: every executed control step in the simulator's own action space, float64
+ calls/NNNNNN/ each call's response meta and the actions as sent
+ startups.jsonl one line per process start
+ final.json kept current (written atomically); "finalized": true once the verdict is in
+ trajectory.npz, replay.mp4, replay.last.png the graded episode and its fresh replay
+
+Crash recovery: compose restarts a crashed service (restart: on-failure). It replays the journal up to the last
+checkpoint, checks the state hash, and continues the SAME episode -- never a reset. A call in flight is lost as a
+whole (its caller got an error, not a result, so nothing was learned). More than RCB_MAX_RESUMES restarts since the
+episode began (every process start counts, also one that died building the scene or replaying the journal) end the
+trial: sim_crashed_on_call if every crash happened while serving a call (the agent's failure), else sim_crashed
+(infrastructure, infra_error = 1). A verdict already on disk is never overwritten; a crash while rendering the video
+loses only the video.
+"""
+from __future__ import annotations
+
+import contextlib
+import errno
+import faulthandler
+import json
+import os
+import signal
+import tempfile
+import time
+import traceback
+from http.server import BaseHTTPRequestHandler, HTTPServer
+from typing import Callable
+from urllib.parse import urlparse
+
+import numpy as np
+
+import rcb1
+
+PROTOCOL = "eai-standard/2.1"
+MAX_BODY = 64 * 1024 * 1024 # request bodies above this are refused (413)
+MAX_RESPONSE = 256 * 1024 * 1024 # responses above this drop frames/ and depth/ (meta.degraded says so)
+MAX_VIDEO_FPS = 30
+MAX_FRAMES_PER_CALL = 3000 # images in one response (cameras x frames, depth counted again): bounds memory
+VIDEOS = ("mp4", "frames", "both", "none")
+ON_SERVICE_ERROR = ("if a call fails with a connection error or a 5xx, the service may have crashed and resumed the "
+ "same episode (never a reset): the state is the one after the last call that completed on the "
+ "service, which you may not have received; check GET /status before continuing")
+
+
+class Sim:
+ """The adapter contract, duck-typed (this class only documents it). One object = one frozen scene.
+
+ Rows come in three forms: what the agent sends (an action of one of spec()["action_types"]), the same after
+ clip(), and a "sim row" (to_sim()), the action in the simulator's own space, which step() executes and the
+ journal and the graded trajectory record (raw_dim floats)."""
+ control_dt: float # seconds per control step; a chunk's dt is a whole multiple of it
+ max_control_steps: int # the task's episode length: the episode ends there
+ cameras: tuple[str, ...] # every camera the agent may ask for
+ depth_cameras: tuple[str, ...] # the ones that also give depth
+ proprio_layout: list[str] # the proprio row's columns
+ raw_dim: int # a sim row's width
+
+ def spec(self) -> dict: ... # simulator, robot, task_text, episode, action_types, cameras, robot facts
+ def interpolable(self, type: str) -> bool: ... # may a row of this type span several control steps?
+ def images(self, cameras: list[str], depth: bool) -> tuple[dict, dict]: ... # ({cam: uint8 HxWx3}, {cam: float32 HxW m})
+ def proprio(self) -> np.ndarray: ... # float32, one value per proprio_layout column
+ def clip(self, type: str, rows: np.ndarray) -> tuple[np.ndarray, list]: ... # into the limits; [{row, index, reason}]
+ def to_sim(self, type: str, row: np.ndarray) -> np.ndarray: ... # an agent row -> a sim row
+ def command(self, type: str) -> np.ndarray: ... # the last row executed, exactly as clip() returned it: a chunk
+ # interpolates from it, so a chunk equals its rows sent one by one
+ def hold(self) -> tuple[str, np.ndarray]: ... # the row that holds the last command (/observe with seconds > 0)
+ def step(self, row: np.ndarray) -> tuple[bool, bool, dict]: ... # one control step -> (done, success, info)
+ def reset(self) -> None: ... # back to the frozen instance
+ def state_sha(self) -> str: ...
+ def verify(self, rows: np.ndarray) -> dict: ... # replay in a fresh simulator -> {"success", "state_sha"}
+ def save_trajectory(self, rows: np.ndarray, path: str, meta: dict) -> None: ...
+ def render_video(self, rows: np.ndarray, path: str) -> None: ... # path and path.last.png
+
+
+class GiveUp(Exception):
+ """The service will not run this trial's episode again; final.json says why."""
+
+
+class Refused(Exception):
+ """A request the service turns down with `code` and the JSON `body`; nothing was executed."""
+
+ def __init__(self, code: int, body: dict):
+ super().__init__(body.get("error"))
+ self.code, self.body = code, body
+
+
+def bad_request():
+ """Checking a request, before anything runs: whatever goes wrong here is the request's fault (400)."""
+ try:
+ yield
+ except Refused:
+ raise
+ except Exception as exc: # noqa: BLE001 -- a wrong type, value or shape of any field
+ raise Refused(400, {"error": str(exc)[:300] or type(exc).__name__}) from None
+
+
+def count_start(data: str) -> int:
+ """Record one process start in startups.jsonl; returns how many there have been."""
+ path = os.path.join(data, "startups.jsonl")
+ with open(path, "a") as f:
+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid()}) + "\n")
+ with open(path) as f:
+ return sum(1 for _ in f)
+
+
+def write_json_atomic(path: str, obj: dict) -> None:
+ """Write then rename: the collect hook polling the file never reads half of it."""
+ fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), suffix=".tmp")
+ with os.fdopen(fd, "w") as f:
+ json.dump(obj, f)
+ os.replace(tmp, path)
+
+
+def encode_mp4(frames: np.ndarray, fps: float) -> bytes:
+ import imageio.v2 as imageio
+ fd, path = tempfile.mkstemp(suffix=".mp4")
+ os.close(fd)
+ try:
+ with imageio.get_writer(path, format="FFMPEG", mode="I", fps=fps, codec="libx264", macro_block_size=1,
+ output_params=["-movflags", "+faststart", "-pix_fmt", "yuv420p"]) as w:
+ for f in frames:
+ w.append_data(np.ascontiguousarray(f))
+ with open(path, "rb") as f:
+ return f.read()
+ finally:
+ os.unlink(path)
+
+
+class Recorder:
+ """What one call returns: a proprio row at its start, every `every` control steps (the requested video_fps, rounded to
+ whole control steps) and at its end; with them the cameras' frames when a video or the frames are asked for, else
+ only the last frame (rendering is most of a call's cost)."""
+
+ def __init__(self, sim, cameras: list[str], fps: int, depth: bool, video: str):
+ self.sim, self.cams, self.depth, self.video = sim, cameras, depth, video
+ self.every = max(1, round(1.0 / (sim.control_dt * fps)))
+ self.fps = 1.0 / (self.every * sim.control_dt)
+ self.images = video != "none"
+ self.frames = {c: [] for c in cameras}
+ self.dep = {c: [] for c in cameras}
+ self.prop: list[np.ndarray] = []
+ self.k, self.grabbed_at = 0, None
+
+ def images_per_call(self, steps: int) -> int:
+ per_frame = len(self.cams) + (len(set(self.cams) & set(self.sim.depth_cameras)) if self.depth else 0)
+ return (steps // self.every + 2 if self.images else 1) * per_frame
+
+ def start(self) -> None:
+ self._grab(self.images)
+
+ def step(self) -> None:
+ self.k += 1
+ if self.k % self.every == 0:
+ self._grab(self.images)
+
+ def finish(self) -> None:
+ if self.grabbed_at != self.k:
+ self._grab(self.images)
+ if not self.images:
+ self._grab(True, proprio=False) # the one frame a call without video returns: the last
+
+ def _grab(self, images: bool, proprio: bool = True) -> None:
+ if images:
+ rgb, dep = self.sim.images(self.cams, self.depth)
+ for c in self.cams:
+ self.frames[c].append(rgb[c])
+ if c in dep:
+ self.dep[c].append(dep[c])
+ if proprio:
+ self.prop.append(np.asarray(self.sim.proprio(), np.float32))
+ self.grabbed_at = self.k
+
+ def parts(self) -> list:
+ out = []
+ for c in self.cams:
+ fr = np.stack(self.frames[c])
+ if self.video in ("mp4", "both"):
+ out.append((f"video/{c}", "mp4", encode_mp4(fr, self.fps), {"fps": round(self.fps, 3), "n": int(len(fr))}))
+ if self.video in ("frames", "both"):
+ out.append(rcb1.array_part(f"frames/{c}", fr))
+ out.append(rcb1.array_part(f"last/{c}", fr[-1]))
+ if self.dep[c]:
+ out.append(rcb1.array_part(f"depth/{c}", np.stack(self.dep[c]).astype(np.float16)))
+ out.append(rcb1.array_part("proprio", np.stack(self.prop)))
+ return out
+
+
+class Service:
+ """Episode bookkeeping, evidence and the HTTP endpoints around one `Sim`."""
+
+ def __init__(self, sim, *, data: str = "/data", reset_budget: int = 0, wall_clock_s: float = 3600.0,
+ max_chunk_s: float = 10.0, max_watch_s: float = 30.0, max_frames_per_call: int = MAX_FRAMES_PER_CALL,
+ max_resumes: int = 2):
+ self.sim, self.data = sim, data
+ self.reset_budget, self.wall_clock_s = int(reset_budget), float(wall_clock_s)
+ self.max_chunk_s, self.max_watch_s = float(max_chunk_s), float(max_watch_s)
+ self.max_frames, self.max_resumes = int(max_frames_per_call), int(max_resumes)
+ os.makedirs(os.path.join(data, "calls"), exist_ok=True)
+ self.journal_path = os.path.join(data, "trajectory_live.f64")
+ self.spec = self._spec()
+ self.types = {k: v for k, v in self.spec["action_types"].items() if isinstance(v, dict)}
+ self.calls = self.rows = self.resets = 0
+ self.journal_rows = 0 # control steps executed over the whole trial (the journal's length)
+ self.ep_start = 0 # where the current episode begins in the journal
+ self.episode: list[np.ndarray] = [] # the current episode's sim rows: what finalize grades
+ self.done, self.reason, self.success = False, None, False
+ self.stopping = False # SIGUSR1 seen: the agent is gone
+ self.finalized, self.verdict = False, {}
+ self.t0 = self.t_end = None # the clock starts at the agent's first request
+ self.starts = 1
+ self._unwritten: list[np.ndarray] = [] # sim rows executed since the last checkpoint
+
+ # ------------------------------------------------------------------ spec and status
+ def _spec(self) -> dict:
+ own = self.sim.spec()
+ core = {"protocol": PROTOCOL, "control_dt": self.sim.control_dt, "max_control_steps": self.sim.max_control_steps,
+ "max_chunk_s": self.max_chunk_s, "max_watch_s": self.max_watch_s, "max_video_fps": MAX_VIDEO_FPS,
+ "max_frames_per_call": self.max_frames, "proprio_layout": list(self.sim.proprio_layout),
+ "budget": {"reset": self.reset_budget, "wall_clock_s": self.wall_clock_s},
+ "clock": "time_s and elapsed_s count from your first request to the service; time_left_s is "
+ "budget.wall_clock_s minus time_s",
+ "on_service_error": ON_SERVICE_ERROR}
+ if clash := sorted(set(core) & set(own)):
+ raise ValueError(f"the adapter's spec() must not set {clash}")
+ cams = {c: {"rgb": True, "depth": c in self.sim.depth_cameras, **own["cameras"].get(c, {})}
+ for c in self.sim.cameras}
+ spec = {**core, **own, "cameras": cams}
+ if self.reset_budget:
+ spec["reset"] = ("POST /reset abandons the running episode and starts a new one from the same starting "
+ "state, budget.reset times in all; only the last episode is graded, and a success ends "
+ "the trial")
+ return spec
+
+ def clock(self) -> float:
+ return 0.0 if self.t0 is None else time.time() - self.t0
+
+ def _counters(self) -> dict:
+ out = {"calls": self.calls, "rows": self.rows, "control_steps": len(self.episode), "done": self.done,
+ "reason": self.reason}
+ if self.reset_budget:
+ out.update(episode=self.resets + 1, control_steps_total=self.journal_rows,
+ resets_left=0 if self.success or self.stopping else self.reset_budget - self.resets)
+ return out
+
+ def status(self) -> dict:
+ return {**self._counters(), "elapsed_s": round(self.clock(), 1)}
+
+ def meta(self) -> dict:
+ t = self.clock()
+ return {**self._counters(), "sim_time_s": round(len(self.episode) * self.sim.control_dt, 4),
+ "time_s": round(t, 2), "time_left_s": max(0.0, round(self.wall_clock_s - t, 1)),
+ "proprio": {"layout": list(self.sim.proprio_layout),
+ "now": np.asarray(self.sim.proprio(), np.float32).tolist()}}
+
+ # ------------------------------------------------------------------ evidence
+ def log(self, ev: str, **kw) -> None:
+ with open(os.path.join(self.data, "episode.jsonl"), "a") as f:
+ f.write(json.dumps({"ts": time.time(), "ev": ev, **kw}) + "\n")
+
+ def _events(self) -> list[dict]:
+ try:
+ with open(os.path.join(self.data, "episode.jsonl")) as f:
+ return [json.loads(line) for line in f if line.strip()]
+ except OSError:
+ return []
+
+ def _checkpoint(self, ev: str, **kw) -> None:
+ """Log a state this service may resume from, after appending everything executed since the last one to the
+ journal. Rows of a call that never reaches its checkpoint are lost with it, as the call is."""
+ if self._unwritten:
+ with open(self.journal_path, "ab") as f:
+ f.write(np.asarray(self._unwritten, dtype=np.float64).tobytes())
+ self._unwritten = []
+ self.log(ev, **kw, calls=self.calls, rows=self.rows, resets=self.resets, ep_start=self.ep_start,
+ journal_rows=self.journal_rows, done=self.done, reason=self.reason, success=self.success,
+ state_sha=self.sim.state_sha())
+ self._write_final()
+
+ def _write_final(self) -> None:
+ end = self.t_end or time.time()
+ d = {"protocol": PROTOCOL, "success": False, "live_success": self.success, "done": self.done,
+ "reason": self.reason, "calls": self.calls, "rows": self.rows, "control_steps": len(self.episode),
+ "control_steps_total": self.journal_rows, "episodes": self.resets + 1, "resets": self.resets,
+ "reset_budget": self.reset_budget, "elapsed_s": round(end - self.t0, 1) if self.t0 else 0.0,
+ "sim_startups": self.starts, "finalized": self.finalized, **self.verdict}
+ if "deterministic" in self.verdict:
+ d["success"] = bool(self.success and self.verdict["replay_success"] and self.verdict["deterministic"])
+ write_json_atomic(os.path.join(self.data, "final.json"), d)
+
+ def _save_call(self, meta: dict, actions: np.ndarray | None) -> None:
+ d = os.path.join(self.data, "calls", f"{self.calls:06d}")
+ os.makedirs(d, exist_ok=True)
+ with open(os.path.join(d, "meta.json"), "w") as f:
+ json.dump(meta, f)
+ if actions is not None:
+ np.save(os.path.join(d, "actions.npy"), actions)
+
+ # ------------------------------------------------------------------ start, resume, give up
+ def start(self) -> None:
+ """A fresh episode, or -- after a crash -- the same one again. Raises GiveUp when it must not run again."""
+ try:
+ with open(os.path.join(self.data, "startups.jsonl")) as f:
+ self.starts = max(1, sum(1 for _ in f))
+ except OSError:
+ self.starts = 1
+ ev = self._events()
+ if not any(e["ev"] == "start" for e in ev):
+ open(self.journal_path, "wb").close()
+ self._checkpoint("start", protocol=PROTOCOL, spec=self.spec, startup=self.starts)
+ else:
+ self._resume(ev)
+ with open(os.path.join(self.data, "server.pid"), "w") as f:
+ f.write(str(os.getpid()))
+
+ def _resume(self, ev: list[dict]) -> None:
+ path = os.path.join(self.data, "final.json")
+ try:
+ with open(path) as f:
+ fin = json.load(f)
+ except (OSError, ValueError):
+ fin = {}
+ if fin.get("finalized") or "deterministic" in fin:
+ # Graded already. A verdict that is not finalized: the process died rendering the video, all it lost.
+ if not fin.get("finalized"):
+ write_json_atomic(path, {**fin, "finalized": True, "video": False})
+ self._give_up("restarted after finalize", infra=False)
+ restarts = self.starts - int(next(e for e in ev if e["ev"] == "start")["startup"])
+ last = max(i for i, e in enumerate(ev) if e["ev"] in ("start", "resuming"))
+ in_call = False # did the process that died do so while serving a call?
+ for e in ev[last:]:
+ in_call = {"call_begin": True, "call_end": False}.get(e["ev"], in_call)
+ in_calls = sum(bool(e["crashed_in_call"]) for e in ev if e["ev"] == "resuming") + int(in_call)
+ if restarts > self.max_resumes:
+ agent = in_calls == restarts # every crash happened inside a call: the agent's commands did it
+ self._give_up("sim_crashed_on_call" if agent else "sim_crashed", infra=not agent)
+ self.log("resuming", crashed_in_call=in_call, restart=restarts)
+ cp = [e for e in ev if "state_sha" in e and "journal_rows" in e][-1]
+ n, dim = int(cp["journal_rows"]), int(self.sim.raw_dim)
+ rows = np.fromfile(self.journal_path, dtype=np.float64) if os.path.exists(self.journal_path) else np.zeros(0)
+ if rows.size < n * dim:
+ self._give_up("resume_failed: journal shorter than the log", infra=True)
+ rows = rows[: n * dim].reshape(n, dim)
+ for row in rows[cp["ep_start"]:]:
+ self.sim.step(row)
+ if self.sim.state_sha() != cp["state_sha"]:
+ self._give_up("resume_failed: replayed state differs from the logged one", infra=True)
+ rows.tofile(self.journal_path) # drop the steps of the call that was in flight
+ self.calls, self.rows, self.resets = int(cp["calls"]), int(cp["rows"]), int(cp["resets"])
+ self.ep_start, self.journal_rows = int(cp["ep_start"]), n
+ self.episode = [r.copy() for r in rows[self.ep_start:]]
+ self.done, self.reason, self.success = bool(cp["done"]), cp["reason"], bool(cp["success"])
+ self.t0 = next((e["t0"] for e in ev if e["ev"] == "first_request"), None)
+ if self.done:
+ self.t_end = next((e["ts"] for e in reversed(ev) if e["ev"] == "end"), cp["ts"])
+ self._checkpoint("resumed", downtime_s=round(time.time() - float(ev[-1]["ts"]), 1))
+
+ def _give_up(self, reason: str, infra: bool) -> None:
+ """End the trial without running its episode again: mark it failed (a finalized final.json is kept as it is),
+ leave the PID file for the collect hook, and stop."""
+ self.log("restart_refused", reason=reason)
+ path = os.path.join(self.data, "final.json")
+ try:
+ with open(path) as f:
+ fin = json.load(f)
+ except (OSError, ValueError):
+ fin = {}
+ if not fin.get("finalized"):
+ fin.update({"protocol": PROTOCOL, "success": False, "done": True, "reason": reason, "finalized": True,
+ **({"infra_error": 1} if infra else {})})
+ write_json_atomic(path, fin)
+ with open(os.path.join(self.data, "server.pid"), "w") as f:
+ f.write(str(os.getpid()))
+ raise GiveUp(reason)
+
+ # ------------------------------------------------------------------ requests
+ def first_request(self) -> None:
+ if self.t0 is None:
+ self.t0 = time.time()
+ self.log("first_request", t0=self.t0)
+
+ def handle(self, method: str, path: str, body: bytes = b"", content_length: int | None = None) -> tuple[int, str, bytes]:
+ """One request -> (status, content type, body): the whole HTTP surface, without the HTTP."""
+ self.first_request()
+ path = urlparse(path).path
+ if method == "GET" and path in ("/spec", "/status"):
+ return self._reply_json(200, self.spec if path == "/spec" else self.status())
+ routes = {"/submit": self._submit, "/observe": self._observe}
+ if self.reset_budget:
+ routes["/reset"] = self._reset
+ if method != "POST" or path not in routes:
+ return self._reply_json(404, {"error": "no such endpoint"})
+ if (len(body) if content_length is None else content_length) > MAX_BODY:
+ return self._reply_json(413, {"error": f"request body over {MAX_BODY} bytes"})
+ try:
+ meta, parts = self._decode(body)
+ except Exception as exc: # noqa: BLE001 -- any malformed body is the caller's error
+ return self._reply_json(400, {"error": f"malformed body: {exc}"[:300]})
+ self.log("call_begin", path=path, call=self.calls + 1)
+ try:
+ out, blobs = routes[path](meta, parts)
+ except Refused as exc: # 400 (bad_request), 409: nothing ran
+ return self._reply_json(exc.code, exc.body)
+ except Exception as exc: # noqa: BLE001 -- it ran and failed: the episode ends, as on hardware
+ traceback.print_exc()
+ self.log("error", path=path, error=repr(exc)[:500])
+ self._end("error")
+ return self._reply_json(500, {"error": "simulator error", "detail": repr(exc)[:200]})
+ finally:
+ self.log("call_end", path=path)
+ return self._reply_rcb1(out, blobs)
+
+ @staticmethod
+ def _decode(body: bytes) -> tuple[dict, dict]:
+ if body[:4] == rcb1.MAGIC:
+ meta, parts = rcb1.decode(body)
+ else:
+ meta, parts = json.loads(body or b"{}"), {}
+ if not isinstance(meta, dict):
+ raise ValueError("the body must be a JSON object or an RCB1 frame")
+ return meta, parts
+
+ @staticmethod
+ def _reply_json(code: int, obj: dict) -> tuple[int, str, bytes]:
+ return code, "application/json", json.dumps(obj).encode()
+
+ @staticmethod
+ def _reply_rcb1(meta: dict, parts: list) -> tuple[int, str, bytes]:
+ body = rcb1.encode(meta, parts)
+ if len(body) > MAX_RESPONSE:
+ parts = [p for p in parts if not p[0].startswith(("frames/", "depth/"))]
+ meta = {**meta, "degraded": f"response over {MAX_RESPONSE} bytes: frames/ and depth/ dropped"}
+ body = rcb1.encode(meta, parts)
+ return 200, "application/x-rcb1", body
+
+ def _view(self, meta: dict, default_video: str) -> tuple[list[str], int, str, bool]:
+ cams = meta.get("cameras") or list(self.sim.cameras)
+ if isinstance(cams, str):
+ cams = [c for c in cams.split(",") if c]
+ if not isinstance(cams, list) or (unknown := sorted(set(map(str, cams)) - set(self.sim.cameras))):
+ raise ValueError(f"unknown camera(s) {unknown if isinstance(cams, list) else cams}; "
+ f"the cameras are {list(self.sim.cameras)}")
+ try:
+ fps = int(meta.get("video_fps", 10))
+ except (TypeError, ValueError, OverflowError):
+ raise ValueError("video_fps must be an integer") from None
+ if not 1 <= fps <= MAX_VIDEO_FPS:
+ raise ValueError(f"video_fps must be in [1, {MAX_VIDEO_FPS}]")
+ video = meta.get("video", default_video)
+ if video not in VIDEOS:
+ raise ValueError(f"video must be one of {list(VIDEOS)}")
+ depth = bool(meta.get("include_depth", False))
+ if depth and not set(cams) & set(self.sim.depth_cameras):
+ raise ValueError(f"include_depth: none of {cams} has depth; spec()['cameras'][name]['depth'] says which do")
+ return cams, fps, video, depth
+
+ def _frame_budget(self, rec: Recorder, steps: int) -> None:
+ n = rec.images_per_call(steps)
+ if n > self.max_frames:
+ raise ValueError(f"this call would return {n} images (cameras x frames, depth counted again); the limit is "
+ f"{self.max_frames}: ask for fewer cameras, a lower video_fps or a shorter chunk")
+
+ def _conflict(self) -> Refused:
+ if self.stopping:
+ return Refused(409, {"error": "trial finished: your time is up", "reason": self.reason})
+ body = {"error": "episode finished", "reason": self.reason}
+ if self.reset_budget:
+ body["resets_left"] = 0 if self.success else self.reset_budget - self.resets
+ return Refused(409, body)
+
+ def _step(self, typ: str, row: np.ndarray) -> dict:
+ """One control step: execute, journal, and end the episode if it is over."""
+ sim_row = np.asarray(self.sim.to_sim(typ, row), dtype=np.float64)
+ done, success, info = self.sim.step(sim_row)
+ self._unwritten.append(sim_row)
+ self.journal_rows += 1
+ self.episode.append(sim_row)
+ if success:
+ self._end("success")
+ elif done or len(self.episode) >= self.sim.max_control_steps:
+ self._end("failed")
+ return info
+
+ def _end(self, reason: str) -> None:
+ if self.done:
+ return
+ self.done, self.reason, self.success = True, reason, reason == "success"
+ self.t_end = time.time()
+ try:
+ self._checkpoint("end")
+ except Exception as exc: # noqa: BLE001 -- a broken simulator may not even hash: the end is still logged
+ self.log("end", reason=reason, checkpoint_error=repr(exc)[:300])
+ self._write_final()
+
+ def _submit(self, meta: dict, parts: dict) -> tuple[dict, list]:
+ if self.done or self.stopping:
+ raise self._conflict()
+ with bad_request():
+ typ = meta.get("type")
+ if not isinstance(typ, str) or typ not in self.types:
+ raise ValueError(f"type must be one of {sorted(self.types)}")
+ try:
+ A = np.asarray(parts["actions"]["data"] if "actions" in parts else meta.get("actions"), dtype=np.float64)
+ except (TypeError, ValueError, KeyError):
+ raise ValueError("send the actions as an RCB1 array part `actions` or a JSON list of rows") from None
+ dim = int(self.types[typ]["dim"])
+ if A.ndim != 2 or A.shape[0] < 1 or A.shape[1] != dim:
+ raise ValueError(f"{typ} actions must be (T, {dim}) with T >= 1, got {list(A.shape)}")
+ if not np.all(np.isfinite(A)):
+ raise ValueError("actions contain NaN or inf")
+ cdt = self.sim.control_dt
+ try:
+ dt = cdt if meta.get("dt") is None else float(meta["dt"])
+ except (TypeError, ValueError):
+ raise ValueError("dt must be a number of seconds") from None
+ k = round(dt / cdt) if np.isfinite(dt / cdt) else 0
+ if k < 1 or abs(k * cdt - dt) > 1e-9:
+ raise ValueError(f"dt must be a positive whole multiple of control_dt = {cdt} s (never rounded)")
+ if k > 1 and not self.sim.interpolable(typ):
+ raise ValueError(f"{typ}: one row is one control step, so dt must be control_dt = {cdt} s")
+ if len(A) * k * cdt > self.max_chunk_s + 1e-9:
+ raise ValueError(f"the chunk covers {len(A) * k * cdt:g} s: more than max_chunk_s = {self.max_chunk_s:g}")
+ interp = meta.get("interpolate", "linear")
+ if interp not in ("linear", "hold"):
+ raise ValueError("interpolate must be linear or hold")
+ cams, fps, video, depth = self._view(meta, "mp4")
+ rec = Recorder(self.sim, cams, fps, depth, video)
+ self._frame_budget(rec, len(A) * k)
+ rows, clipped = self.sim.clip(typ, A)
+ before, info, executed, stop = len(self.episode), {}, 0, False
+ prev = np.asarray(self.sim.command(typ), dtype=np.float64)
+ rec.start()
+ for i, row in enumerate(rows):
+ for j in range(1, k + 1):
+ info = self._step(typ, row if interp == "hold" else prev + (row - prev) * (j / k))
+ rec.step()
+ if self.done or self.stopping or info.get("blocked"):
+ stop = True
+ break
+ executed, prev = i + 1, row
+ if stop:
+ break
+ rec.finish()
+ self.calls += 1
+ self.rows += executed
+ out = {**self.meta(), "chunk_id": self.calls, "type": typ, "executed_rows": executed,
+ "control_steps_chunk": len(self.episode) - before, "clipped": clipped[:200], "n_clipped": len(clipped),
+ **info, "ok": True}
+ self._checkpoint("submit", type=typ, n_rows=len(A), dt=dt, interpolate=interp, cameras=cams,
+ note=str(meta.get("note") or "")[:500], executed_rows=executed, n_clipped=len(clipped), **info)
+ self._save_call(out, A)
+ return out, rec.parts()
+
+ def _observe(self, meta: dict, parts: dict) -> tuple[dict, list]:
+ with bad_request():
+ try:
+ seconds = float(meta.get("seconds") or 0.0)
+ except (TypeError, ValueError):
+ raise ValueError("seconds must be a number") from None
+ if not 0.0 <= seconds <= self.max_watch_s:
+ raise ValueError(f"seconds must be in [0, {self.max_watch_s:g}]")
+ cams, fps, video, depth = self._view(meta, "frames")
+ n = int(round(seconds / self.sim.control_dt)) if not (self.done or self.stopping) else 0
+ rec = Recorder(self.sim, cams, fps, depth, video if n or video != "mp4" else "frames") # no time: no video
+ self._frame_budget(rec, n)
+ before = len(self.episode)
+ rec.start()
+ if n:
+ typ, row = self.sim.hold()
+ for _ in range(n):
+ self._step(typ, row)
+ rec.step()
+ if self.done or self.stopping:
+ break
+ rec.finish()
+ self.calls += 1
+ ran = len(self.episode) - before
+ out = {**self.meta(), "obs_id": self.calls, "seconds": round(ran * self.sim.control_dt, 4),
+ "control_steps_watch": ran, "ok": True}
+ self._checkpoint("observe", seconds=out["seconds"], cameras=cams)
+ self._save_call(out, None)
+ return out, rec.parts()
+
+ def _reset(self, meta: dict, parts: dict) -> tuple[dict, list]:
+ if self.success or self.stopping:
+ raise Refused(409, {"error": "trial finished: " + ("an episode succeeded" if self.success else "your time is up"),
+ "reason": self.reason})
+ if self.resets >= self.reset_budget:
+ raise Refused(409, {"error": "reset budget exhausted", "budget": self.reset_budget})
+ with bad_request():
+ cams, fps, video, depth = self._view(meta, "frames")
+ if not self.done:
+ self._end("reset") # the running episode is abandoned
+ self.sim.reset()
+ self.resets += 1
+ self.ep_start, self.episode = self.journal_rows, []
+ self.done, self.reason, self.success, self.t_end = False, None, False, None
+ rec = Recorder(self.sim, cams, fps, depth, "frames" if video == "mp4" else video) # no time: no video
+ rec.start()
+ rec.finish()
+ self.calls += 1
+ out = {**self.meta(), "ok": True}
+ self._checkpoint("reset", cameras=cams)
+ self._save_call(out, None)
+ return out, rec.parts()
+
+ # ------------------------------------------------------------------ the end of the trial
+ def on_sigusr1(self, *_) -> None:
+ """The agent is gone (the [[verifier.collect]] hook). Only a flag: the handler may fire in the middle of a
+ request; a chunk stops at its next control step and poll() wraps up between requests."""
+ self.stopping = True
+
+ def poll(self) -> None:
+ """Between requests (the HTTP loop calls it every 0.5 s): after SIGUSR1, end the episode and finalize."""
+ if self.stopping and not self.finalized:
+ if not self.done:
+ self._end("timeout")
+ self._finalize()
+
+ def _finalize(self) -> None:
+ """The graded episode (every control step since the last reset) as a trajectory, its replay in a fresh
+ simulator (success, and bit-exact agreement with the live run), and a video for humans."""
+ try:
+ rows = np.asarray(self.episode, dtype=np.float64).reshape(-1, self.sim.raw_dim)
+ live_sha = self.sim.state_sha()
+ self.sim.save_trajectory(rows, os.path.join(self.data, "trajectory.npz"),
+ {"source": "standard-mode episode", "protocol": PROTOCOL, "reason": self.reason,
+ "episode": self.resets + 1})
+ rep = self.sim.verify(rows)
+ self.verdict = {"n_actions": int(len(rows)), "replay_success": bool(rep["success"]),
+ "deterministic": rep["state_sha"] == live_sha, "state_sha": live_sha, "video": False}
+ self.log("replay", **self.verdict)
+ self._write_final() # the verdict is on disk before any video is rendered
+ try:
+ self.sim.render_video(rows, os.path.join(self.data, "replay.mp4"))
+ self.verdict["video"] = True
+ except Exception: # noqa: BLE001 -- the video is for humans; it never decides the verdict
+ traceback.print_exc()
+ except Exception as exc: # noqa: BLE001
+ traceback.print_exc()
+ self.log("finalize_error", error=repr(exc)[:500])
+ self.verdict = {"finalize_error": repr(exc)[:300]}
+ self.finalized = True
+ self._write_final()
+
+ # ------------------------------------------------------------------ HTTP
+ def http_server(self, address: tuple[str, int]) -> HTTPServer:
+ svc = self
+
+ class Handler(BaseHTTPRequestHandler):
+ timeout = 120 # a client that stalls mid-request is dropped: one thread serves everyone
+
+ def log_message(self, *a):
+ pass
+
+ def _send(self, code: int, ctype: str, body: bytes) -> None:
+ self.send_response(code)
+ self.send_header("Content-Type", ctype)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_GET(self):
+ self._send(*svc.handle("GET", self.path))
+
+ def do_POST(self):
+ try:
+ n = int(self.headers.get("Content-Length") or 0)
+ except ValueError:
+ return self._send(*svc._reply_json(400, {"error": "bad Content-Length"}))
+ if n > MAX_BODY: # refused unread: drop the connection with it
+ self.close_connection = True
+ return self._send(*svc.handle("POST", self.path, b"", content_length=n))
+ self._send(*svc.handle("POST", self.path, self.rfile.read(n)))
+
+ class Server(HTTPServer):
+ def service_actions(self):
+ svc.poll()
+
+ return Server(address, Handler)
+
+ def bind(self, port: int) -> HTTPServer:
+ """The HTTP server on `port`. Something else may hold the port -- in the network namespace it shares with the
+ agent's container, an agent's process can take it while this service (re)starts -- so wait, not die (a death
+ here would count as a crash); the trial can still end meanwhile (SIGUSR1)."""
+ busy = False
+ while True:
+ try:
+ return self.http_server(("0.0.0.0", port))
+ except OSError as exc:
+ if exc.errno != errno.EADDRINUSE:
+ raise
+ if not busy:
+ busy = True
+ self.log("port_busy", port=port)
+ self.poll()
+ time.sleep(1.0)
+
+ def serve(self, port: int = 8000) -> None:
+ signal.signal(signal.SIGUSR1, self.on_sigusr1)
+ srv = self.bind(port)
+ print(f"{PROTOCOL} sim service ready on :{port}", flush=True)
+ srv.serve_forever()
+
+
+def main(build: Callable[[], Sim], port: int = 8000) -> None:
+ """A sidecar's life: count the start, back off after a failed one, build the scene under a startup watchdog, resume
+ or start the episode, serve. Settings: RCB_DATA (/data), RCB_RESET_BUDGET (0), RCB_WALL_CLOCK_S (3600),
+ RCB_STARTUP_TIMEOUT_S (300), RCB_MAX_RESUMES (2)."""
+ env = os.environ.get
+ data = env("RCB_DATA", "/data")
+ os.makedirs(data, exist_ok=True)
+ starts = count_start(data)
+ # Compose restarts a failed start at once; a scene that failed to build (e.g. the GPU full of other trials) would
+ # meet the same conditions every time, so wait before rebuilding -- only before the episode exists.
+ if starts > 1 and not os.path.exists(os.path.join(data, "episode.jsonl")):
+ time.sleep(min(120, 20 * (starts - 1)))
+ pending: list[int] = []
+ signal.signal(signal.SIGUSR1, lambda *_: pending.append(1)) # its default action would kill the process
+ # A scene build that hangs (no crash, so compose never restarts it) must end the process. Neither a Python thread
+ # (a native hang may hold the GIL) nor SIGALRM's default action (PID 1 ignores it) can; faulthandler's C watchdog
+ # dumps every thread's traceback and exits. Before the scene exists no episode exists: the retry is no reset.
+ faulthandler.dump_traceback_later(float(env("RCB_STARTUP_TIMEOUT_S", "300")), exit=True)
+ sim = build()
+ faulthandler.cancel_dump_traceback_later() # a resume replay may take minutes
+ svc = Service(sim, data=data, reset_budget=int(env("RCB_RESET_BUDGET") or 0),
+ wall_clock_s=float(env("RCB_WALL_CLOCK_S") or 3600), max_resumes=int(env("RCB_MAX_RESUMES") or 2))
+ try:
+ svc.start()
+ except GiveUp as exc:
+ print(f"restart refused: {exc}", flush=True)
+ signal.signal(signal.SIGUSR1, lambda *_: None)
+ while True:
+ time.sleep(3600)
+ if pending:
+ svc.on_sigusr1()
+ svc.serve(port)
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/__init__.py b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/__init__.py
new file mode 100644
index 0000000000..9a55e841d4
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/__init__.py
@@ -0,0 +1,40 @@
+"""Renderer plugins (docs/framework_zh.md §3.1): a renderer draws a sport's scene, from its camera definitions, for
+one world state. Sports never import a renderer; the core calls the task's observation renderer (task parameter
+`renderer`, default DEFAULT) and the viewing tools any renderer for re-renders.
+
+ from renderers import load, Scene, CameraDef
+ R = load("mujoco")(Scene.from_file("scene.xml"))
+ images = R.render({"qpos": qpos}, [CameraDef("behind", pos, lookat)])
+"""
+from __future__ import annotations
+
+import importlib
+
+from .base import CameraDef, Renderer, RendererUnavailable, Scene # noqa: F401
+
+DEFAULT = "mujoco"
+REGISTRY = { # name -> (module, realtime, needs_gpu, requires)
+ "mujoco": ("renderers.mujoco", True, False, "mujoco; MUJOCO_GL=osmesa (CPU) or egl (GPU)"),
+ "mujoco-showcase": ("renderers.mujoco_showcase", True, False, "as mujoco"),
+ "cycles": ("renderers.cycles", False, True, "Docker, the rcb-showcase-blender image, an NVIDIA GPU (or device=CPU)"),
+ "isaac": ("renderers.isaac", False, True, "Docker, the Isaac Sim 4.5 image, an NVIDIA RTX GPU"),
+}
+
+
+def load(name: str = DEFAULT):
+ """The Renderer subclass registered under `name`."""
+ if name not in REGISTRY:
+ raise KeyError(f"unknown renderer {name!r}; have {sorted(REGISTRY)}")
+ return importlib.import_module(REGISTRY[name][0]).RENDERER
+
+
+def available() -> dict:
+ return {n: {"realtime": rt, "needs_gpu": gpu, "requires": req} for n, (_, rt, gpu, req) in REGISTRY.items()}
+
+
+def players_model(sport_dir, match: Scene):
+ """For a sport that draws its own images (the renderers' interface for sports): the compiled MjModel of the
+ players' presentation scene its presentation.toml declares (`players`, renderer rule 6; the same kinematics as
+ `match` checked), or None when it declares none (draw the match model). See renderers/presentation."""
+ from .presentation import players_model as _players_model
+ return _players_model(sport_dir, match)
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/base.py b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/base.py
new file mode 100644
index 0000000000..7cf75e40ba
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/base.py
@@ -0,0 +1,156 @@
+"""The renderer plugin interface (docs/framework_zh.md §3.1, renderer rules §9): a renderer turns a sport's scene,
+camera definitions and one world state into images. It never changes physics or the match state: it draws on its own
+copy of the model.
+
+ scene = Scene(engine="mujoco", xml=MJCF text, assets={relative path: bytes}, look=None or a presentation look)
+ a presentation scene (renderers/presentation.py, spectators only) also carries `match`, the match scene
+ it dresses: same kinematics, extra visual-only geoms (scene_check.same_kinematics)
+ cameras = [CameraDef(name, pos, lookat, up, fovy_deg, width, height), ...] (what Match.cameras(seat) returns)
+ state = {"qpos": [...], optional "mocap_pos": [...], "mocap_quat": [...]}
+ images = Renderer(scene).render(state, cameras) -> one H x W x 3 uint8 array per camera
+
+The camera model is a pinhole that every renderer must reproduce (CameraDef.project): pixel (u, v) from the image's
+top-left corner, u to the right, v down, vertical field of view fovy_deg. Only numpy is needed here; engines import
+their own libraries inside their backend packages. Never put the renderers/ directory itself on sys.path (its
+`mujoco` backend package would shadow the mujoco library); import it as the package `renderers`.
+"""
+from __future__ import annotations
+
+import math
+from abc import ABC, abstractmethod
+from dataclasses import dataclass, field
+from pathlib import Path
+
+import numpy as np
+
+
+class RendererUnavailable(RuntimeError):
+ """The renderer cannot run here; `requirements` says what it needs (GPU, image, library ...)."""
+
+ def __init__(self, name: str, why: str, requirements: str = ""):
+ super().__init__(f"renderer {name!r} unavailable: {why}" + (f" (requires: {requirements})" if requirements else ""))
+ self.name, self.why, self.requirements = name, why, requirements
+
+
+def _unit(v):
+ v = np.asarray(v, dtype=float)
+ n = np.linalg.norm(v)
+ if not np.isfinite(n) or n < 1e-12:
+ raise ValueError("degenerate camera direction")
+ return v / n
+
+
+@dataclass
+class CameraDef:
+ name: str
+ pos: tuple
+ lookat: tuple
+ up: tuple = (0.0, 0.0, 1.0)
+ fovy_deg: float = 45.0
+ width: int = 320
+ height: int = 240
+
+ def __post_init__(self):
+ self.pos = tuple(float(x) for x in self.pos)
+ self.lookat = tuple(float(x) for x in self.lookat)
+ self.up = tuple(float(x) for x in self.up)
+ self.fovy_deg, self.width, self.height = float(self.fovy_deg), int(self.width), int(self.height)
+ if len(self.pos) != 3 or len(self.lookat) != 3 or len(self.up) != 3:
+ raise ValueError("pos, lookat and up are 3-vectors")
+ if not 0 < self.fovy_deg < 180 or self.width <= 0 or self.height <= 0:
+ raise ValueError("fovy_deg in (0, 180), positive width and height")
+ self.basis() # raises on a degenerate pose
+
+ @staticmethod
+ def from_dict(d: dict) -> "CameraDef":
+ keys = ("name", "pos", "lookat", "up", "fovy_deg", "width", "height")
+ return CameraDef(**{k: d[k] for k in keys if k in d})
+
+ def to_dict(self) -> dict:
+ return {"name": self.name, "pos": list(self.pos), "lookat": list(self.lookat), "up": list(self.up),
+ "fovy_deg": self.fovy_deg, "width": self.width, "height": self.height}
+
+ def focal_px(self) -> float:
+ return (self.height / 2) / math.tan(math.radians(self.fovy_deg) / 2)
+
+ def intrinsics(self) -> dict:
+ return {"focal_px": self.focal_px(), "principal_point_px": [self.width / 2, self.height / 2],
+ "width": self.width, "height": self.height}
+
+ def basis(self):
+ """(right, up, forward) unit vectors in the world frame."""
+ fwd = _unit(np.subtract(self.lookat, self.pos))
+ right = _unit(np.cross(fwd, self.up))
+ up = np.cross(right, fwd)
+ return right, up, fwd
+
+ def project(self, point):
+ """Pixel (u, v) of a world point (u right, v down, from the top-left corner; continuous coordinates, so the
+ centre of pixel column i is u = i + 0.5). None if the point is behind the camera."""
+ right, up, fwd = self.basis()
+ d = np.subtract(point, self.pos)
+ depth = float(d @ fwd)
+ if depth <= 1e-9:
+ return None
+ f = self.focal_px()
+ return (self.width / 2 + f * float(d @ right) / depth, self.height / 2 - f * float(d @ up) / depth)
+
+ def spherical(self):
+ """(lookat, distance, azimuth_deg, elevation_deg): the free-camera form the showcase exporters use."""
+ d = np.subtract(self.lookat, self.pos)
+ dist = float(np.linalg.norm(d))
+ az = math.degrees(math.atan2(d[1], d[0]))
+ el = math.degrees(math.asin(max(-1.0, min(1.0, d[2] / dist))))
+ return list(self.lookat), dist, az, el
+
+
+@dataclass
+class Scene:
+ engine: str = "mujoco" # the physics engine whose scene format `xml` is in
+ xml: str = "" # MJCF text (engine "mujoco")
+ assets: dict = field(default_factory=dict) # {path as referenced by the xml (with meshdir/texturedir): bytes}
+ look: dict | None = None # optional presentation appearance (showcase renderers only)
+ match: "Scene | None" = None # set on a presentation scene only: the match scene it dresses
+ credits: tuple = () # presentation scene: what was added, with its source and licence
+ players: bool = False # a presentation scene the sport declares for its players' images too
+
+ @property
+ def is_presentation(self) -> bool:
+ """A presentation scene (renderers/presentation): drawn for the players' images only when `players` is set
+ (the sport declares it, renderer rule 6), else for spectators only."""
+ return self.match is not None
+
+ @staticmethod
+ def from_file(path, look=None) -> "Scene":
+ """A scene file plus every other file below its directory as an asset (paths relative to that directory)."""
+ p = Path(path)
+ assets = {str(f.relative_to(p.parent)): f.read_bytes() for f in sorted(p.parent.rglob("*"))
+ if f.is_file() and f != p and "__pycache__" not in f.parts}
+ return Scene(engine="mujoco", xml=p.read_text(), assets=assets, look=look)
+
+
+class Renderer(ABC):
+ name: str = ""
+ realtime: bool = True # fast enough for player images (still subject to the task's frame budget)
+ needs_gpu: bool = False
+ label: str | None = None # the tag a re-rendered frame carries ("re-rendered: <engine>"); None = default
+
+ def __init__(self, scene: Scene, **opts):
+ self.scene, self.opts = scene, opts
+
+ @abstractmethod
+ def render(self, state: dict, cameras: list) -> list:
+ """One H x W x 3 uint8 image per camera (CameraDef or its dict form), for the given world state."""
+
+ def close(self):
+ pass
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ self.close()
+
+
+def as_cameras(cameras) -> list:
+ return [c if isinstance(c, CameraDef) else CameraDef.from_dict(c) for c in cameras]
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/mujoco/__init__.py b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/mujoco/__init__.py
new file mode 100644
index 0000000000..1f52d6a69d
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/mujoco/__init__.py
@@ -0,0 +1,144 @@
+"""The default renderer: MuJoCo's own rasterizer (CPU with MUJOCO_GL=osmesa, GPU with egl), real time.
+
+The scene is compiled once from its MJCF text with spare world-body cameras added; each CameraDef is drawn by
+setting one spare camera's pose and vertical field of view exactly (cam_pos / cam_quat / cam_fovy), so the picture
+follows CameraDef.project to the pixel. The renderer keeps its own MjModel / MjData: the match's world is never
+touched. A presentation scene (Scene.match set; spectators only) is drawn only when its kinematics equal the match
+scene's (scene_check.same_kinematics); every renderer built on this one inherits the check."""
+from __future__ import annotations
+
+import numpy as np
+
+from ..base import CameraDef, Renderer, RendererUnavailable, Scene, as_cameras
+
+SPARE = "_ro_cam"
+
+
+def camera_quat(cam: CameraDef):
+ """MuJoCo camera frame: x = image right, y = image up, looking along -z."""
+ import mujoco as mj
+ right, up, fwd = cam.basis()
+ R = np.column_stack([right, up, -fwd])
+ q = np.zeros(4)
+ mj.mju_mat2Quat(q, R.reshape(-1))
+ return q
+
+
+def compile_spec(spec, n_cams: int, size):
+ """Add n spare cameras and make the off-screen buffer at least `size` (w, h); returns the compiled model."""
+ g = spec.visual.global_
+ g.offwidth, g.offheight = max(int(g.offwidth), int(size[0])), max(int(g.offheight), int(size[1]))
+ for i in range(n_cams):
+ spec.worldbody.add_camera(name=f"{SPARE}{i}", pos=[0, 0, 0], quat=[1, 0, 0, 0], fovy=45)
+ return spec.compile()
+
+
+def load_spec(scene: Scene):
+ import mujoco as mj
+ if scene.engine != "mujoco":
+ raise RendererUnavailable("mujoco", f"scene engine {scene.engine!r} is not MJCF")
+ return mj.MjSpec.from_string(scene.xml, assets=dict(scene.assets or {}))
+
+
+class MujocoRenderer(Renderer):
+ name = "mujoco"
+ title = "MuJoCo"
+ realtime = True
+ needs_gpu = False
+ label = None # the competition picture: no tag
+
+ def __init__(self, scene: Scene, n_cams: int = 8, size=(640, 480), **opts):
+ super().__init__(scene, **opts)
+ try:
+ import mujoco # noqa: F401
+ except ImportError as exc: # pragma: no cover - the sim images have it
+ raise RendererUnavailable(self.name, "the mujoco Python package is missing", "mujoco") from exc
+ self._n, self._size = int(n_cams), tuple(size)
+ self._build()
+
+ # ---------------------------------------------------------------- model
+ def make_spec(self):
+ """The MjSpec to draw (subclasses change only visual properties)."""
+ return load_spec(self.scene)
+
+ def _build(self):
+ import mujoco as mj
+ self.close()
+ self.m = compile_spec(self.make_spec(), self._n, self._size)
+ if self.scene.match is not None: # a presentation scene: same kinematics as the match scene
+ from ..scene_check import same_kinematics
+ bad = same_kinematics(compile_spec(load_spec(self.scene.match), self._n, self._size), self.m)
+ if bad:
+ raise RuntimeError(f"{self.name}: the presentation scene's kinematics differ from the match scene: "
+ f"{bad[:8]}")
+ self.d = mj.MjData(self.m)
+ self.cam_ids = [self.m.camera(f"{SPARE}{i}").id for i in range(self._n)]
+ self._r = {}
+
+ def _renderer(self, w, h):
+ import mujoco as mj
+ if (w, h) not in self._r:
+ self._r[w, h] = mj.Renderer(self.m, height=h, width=w)
+ return self._r[w, h]
+
+ def set_state(self, state: dict):
+ import mujoco as mj
+ m, d = self.m, self.d
+ q = np.asarray(state.get("qpos", d.qpos), dtype=float)
+ if q.shape != (m.nq,):
+ raise ValueError(f"state qpos has {q.size} values, the scene has nq={m.nq}")
+ d.qpos[:] = q
+ if m.nmocap:
+ if "mocap_pos" in state:
+ d.mocap_pos[:] = np.asarray(state["mocap_pos"], float).reshape(m.nmocap, 3)
+ if "mocap_quat" in state:
+ d.mocap_quat[:] = np.asarray(state["mocap_quat"], float).reshape(m.nmocap, 4)
+ mj.mj_kinematics(m, d)
+ mj.mj_comPos(m, d)
+ mj.mj_camlight(m, d)
+
+ # ---------------------------------------------------------------- drawing
+ def render(self, state: dict, cameras: list) -> list:
+ import mujoco as mj
+ cams = as_cameras(cameras)
+ w_max, h_max = max([c.width for c in cams] + [1]), max([c.height for c in cams] + [1])
+ if len(cams) > self._n or w_max > self.m.vis.global_.offwidth or h_max > self.m.vis.global_.offheight:
+ self._n = max(self._n, len(cams))
+ self._size = (max(self._size[0], w_max), max(self._size[1], h_max))
+ self._build()
+ self.set_state(state)
+ for cam, cid in zip(cams, self.cam_ids):
+ self.m.cam_pos[cid] = cam.pos
+ self.m.cam_quat[cid] = camera_quat(cam)
+ self.m.cam_fovy[cid] = cam.fovy_deg
+ mj.mj_camlight(self.m, self.d) # camera world poses from the new cam_pos / cam_quat
+ self._clip(cams)
+ out = []
+ for cam, cid in zip(cams, self.cam_ids):
+ r = self._renderer(cam.width, cam.height)
+ r.update_scene(self.d, camera=cid)
+ out.append(self.post(np.array(r.render(), dtype=np.uint8, copy=True), cam))
+ return out
+
+ def _clip(self, cams):
+ """MuJoCo clips at zfar * stat.extent: keep every geom of the current state inside every camera's far plane
+ (a small scene seen from afar, or a body far from the scene centre, would otherwise vanish). Visualization
+ only, on our own model copy."""
+ m, d = self.m, self.d
+ ext = max(float(m.stat.extent), 1e-6)
+ pts = np.asarray(d.geom_xpos) if m.ngeom else np.zeros((1, 3))
+ rb = float(np.max(m.geom_rbound)) if m.ngeom else 0.0
+ reach = max(float(np.max(np.linalg.norm(pts - np.asarray(c.pos), axis=1))) for c in cams) + rb
+ if m.vis.map.zfar * ext < 1.05 * reach:
+ m.vis.map.zfar = 1.05 * reach / ext
+
+ def post(self, img, cam):
+ return img
+
+ def close(self):
+ for r in getattr(self, "_r", {}).values():
+ r.close()
+ self._r = {}
+
+
+RENDERER = MujocoRenderer
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/presentation/LICENSE.franka_emika_panda b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/presentation/LICENSE.franka_emika_panda
new file mode 100644
index 0000000000..d9a10c0d8e
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/presentation/LICENSE.franka_emika_panda
@@ -0,0 +1,176 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/presentation/LICENSE.kuka_iiwa_14 b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/presentation/LICENSE.kuka_iiwa_14
new file mode 100644
index 0000000000..d4681a468e
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/presentation/LICENSE.kuka_iiwa_14
@@ -0,0 +1,31 @@
+All components of Drake are licensed under the BSD 3-Clause License
+shown below. Where noted in the source code, some portions may
+be subject to other permissive, non-viral licenses.
+
+Copyright 2012-2022 Robot Locomotion Group @ CSAIL
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+Redistributions of source code must retain the above copyright notice,
+this list of conditions and the following disclaimer. Redistributions
+in binary form must reproduce the above copyright notice, this list of
+conditions and the following disclaimer in the documentation and/or
+other materials provided with the distribution. Neither the name of
+the Massachusetts Institute of Technology nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/presentation/__init__.py b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/presentation/__init__.py
new file mode 100644
index 0000000000..7c589751f7
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/presentation/__init__.py
@@ -0,0 +1,326 @@
+"""Presentation scenes (docs/framework_zh.md §3.1, renderer rule 6): a sport may dress its match scene for spectators,
+e.g. draw its robot arms with a manufacturer-grade visual model instead of their collision meshes. A presentation
+scene is the match scene plus visual-only geoms on the SAME bodies; nothing that moves or collides changes
+(scene_check.same_kinematics, checked by every renderer before it draws one), so a recorded match replays and
+re-renders with identical body poses. By default it is for spectator renderers only (replay videos, re-renders,
+stills): the players' images use the match scene (core/observe.CameraWorker refuses a presentation scene).
+
+Players' images (core 0.2.9): a sport may declare `players = "<meshes>"` below; then the players' images are drawn
+from the presentation scene too, with the meshes named ("full" = the upstream files, or a level of detail of lod.json,
+e.g. "25k": decimated, a few MB, cheap on the CPU). tools/sportlib.assemble_sim then copies this directory and the
+models' files (verified by sha256, with their licences) into the simulator directory (<sim>/sport/presentation/,
+assets under assets/), so they are part of source_sha and a match needs no cache or network; `players_scene` builds
+that scene (Scene.players set: CameraWorker accepts it, after the same kinematics check), `players_model` compiles it
+for a sport that draws its own images. Changing the declaration changes the players' images: bump the sport's
+revision.
+
+Declaration: sports/<sport>/presentation/presentation.toml (outside the simulator directory: tools/sportlib.NOT_IN_SIM,
+so source_sha, the golden replays and the task directories do not change):
+
+ [presentation]
+ version = 1 # bump on any change of the dressing
+ label = "Franka Panda visual meshes (MuJoCo Menagerie)"
+ [[presentation.robot]]
+ model = "franka_emika_panda" # a model of the asset manifest (renderers/presentation/menagerie.json),
+ # or "./<path>.xml": a (self-authored) model in this directory
+ bodies = '^(?P<pre>[AB]_)?link(?P<n>[0-7])$' # scene bodies to dress (Python regex, full match) ...
+ body = "link{n}" # ... and the model body whose visual geoms each one gets
+ hide = "all" # the dressed bodies' own geoms: "all" (default) | "mesh" | "none"
+ # are hidden (moved to group 3), not removed
+ hide_bodies = '^...$' # optional: hide only in these dressed bodies (default: all of them)
+ colors = { white = [0.92, 0.5, 0.42, 1] } # optional: a model material's colour for this robot (e.g. a side colour)
+ scenes = ["sim/scene/a.xml"] # optional: the match scene files (relative to the sport directory),
+ # for spectator tools when the sport has no Sport.scene()
+ players = "25k" # optional, top level: the players' images use this scene too, with
+ # these meshes ("full" or a level of lod.json); absent = spectators only
+
+The model's visual geoms (contype = conaffinity = 0, group 0..2) are copied, with their meshes, materials and poses
+in the body frame, onto each matching scene body; a body whose parent is dressed too must sit in its parent's frame
+exactly as the model's does (else the declaration names the wrong bodies and dressing fails). The models' files come
+from the asset cache (renderers/presentation/assets.py: pinned commit, sha256 per file; `python3 -m
+renderers.presentation.assets fetch`), never from the repository.
+
+ from renderers.presentation import for_plugin
+ scene = for_plugin("sports/tabletennis/plugin.py", match_scene) # None if the sport declares no presentation
+"""
+from __future__ import annotations
+
+import os
+import re
+import xml.etree.ElementTree as ET
+from pathlib import Path
+
+import numpy as np
+
+from ..base import Scene
+from ..scene_check import VISUAL_PREFIX
+
+DECL = "presentation.toml"
+BUNDLE = "assets" # <sim>/sport/presentation/assets: the models' files bundled into a simulator
+CLASS = "ro_presentation" # the default class of the added geoms (inherits nothing from a robot's childclass)
+HIDDEN_GROUP = "3" # renderers draw groups 0..2; the dressed bodies' own geoms move here
+FRAME_TOL = 1e-6
+
+
+class PresentationUnavailable(RuntimeError):
+ """The sport declares a presentation scene that cannot be built here (e.g. the model assets are not fetched)."""
+
+
+def match_scenes(sport_dir: str | os.PathLike) -> list:
+ """The match scene files a presentation declares (`scenes`), as Scenes; [] if none."""
+ d = Path(sport_dir) / "presentation"
+ if not declared(d):
+ return []
+ return [Scene.from_file(Path(sport_dir) / f) for f in load_decl(d).get("scenes", [])]
+
+
+def directory(plugin: str | os.PathLike) -> Path:
+ return Path(plugin).resolve().parent / "presentation"
+
+
+def declared(d: str | os.PathLike) -> bool:
+ return (Path(d) / DECL).is_file()
+
+
+def load_decl(d: str | os.PathLike) -> dict:
+ import tomllib
+ p = (tomllib.loads((Path(d) / DECL).read_text()).get("presentation") or {})
+ if int(p.get("version", 0)) < 1 or not p.get("robot"):
+ raise ValueError(f"{Path(d) / DECL}: [presentation] needs version >= 1 and at least one [[presentation.robot]]")
+ for r in p["robot"]:
+ for k in ("model", "bodies", "body"):
+ if k not in r:
+ raise ValueError(f"{Path(d) / DECL}: a [[presentation.robot]] needs {k!r}")
+ if r.get("hide", "all") not in ("all", "mesh", "none"):
+ raise ValueError(f"{Path(d) / DECL}: hide is all | mesh | none")
+ pl = p.get("players")
+ if pl is not None and (not isinstance(pl, str) or not (pl == "full" or re.fullmatch(r"\d+k", pl))):
+ raise ValueError(f"{Path(d) / DECL}: players is \"full\" or a level of detail like \"25k\"")
+ return p
+
+
+def players_meshes(d: str | os.PathLike) -> str | None:
+ """The meshes the players' images use ("full" or a level of detail), None = spectators only (the default)."""
+ return load_decl(d).get("players") if declared(d) else None
+
+
+def players_scene(sport_dir: str | os.PathLike, match: Scene) -> Scene:
+ """The scene of the players' images: the presentation scene of `sport_dir` (the sport's directory, or the
+ simulator's sport/) when it declares `players`, else `match` itself."""
+ d = Path(sport_dir) / "presentation"
+ meshes = players_meshes(d)
+ return match if meshes is None else dress(match, d, meshes=meshes, players=True)
+
+
+def players_model(sport_dir: str | os.PathLike, match: Scene):
+ """For a sport that draws its own images: the compiled MjModel of the players' scene, after the same kinematics
+ check against the match scene; None when the sport does not declare `players` (draw the match model)."""
+ sc = players_scene(sport_dir, match)
+ if sc is match:
+ return None
+ import mujoco as mj
+ from ..scene_check import same_kinematics
+ m = mj.MjSpec.from_string(sc.xml, assets=dict(sc.assets or {})).compile()
+ bad = same_kinematics(mj.MjSpec.from_string(match.xml, assets=dict(match.assets or {})).compile(), m)
+ if bad:
+ raise RuntimeError(f"the players' presentation scene's kinematics differ from the match scene: {bad[:8]}")
+ return m
+
+
+def for_plugin(plugin, match: Scene) -> Scene | None:
+ """The presentation scene of the sport whose plugin is `plugin`, dressing `match` (the sport's scene for the same
+ configuration); None when the sport declares none. Raises PresentationUnavailable when it cannot be built. Inside a
+ simulator directory (a bundle, players' presentation) it is the players' scene."""
+ d = directory(plugin)
+ if not declared(d):
+ return None
+ meshes = players_meshes(d)
+ if meshes is not None and (d / BUNDLE).is_dir(): # inside a simulator: only the players' meshes are bundled
+ return dress(match, d, meshes=meshes, players=True)
+ return dress(match, d)
+
+
+# ------------------------------------------------------------------------------------------------ robot models
+def _f(v) -> str:
+ return " ".join(repr(float(x)) for x in np.asarray(v, float).reshape(-1))
+
+
+def _unitq(q):
+ q = np.asarray(q, float)
+ return q / np.linalg.norm(q)
+
+
+def model_parts(xml_path: str | os.PathLike) -> dict:
+ """The visual model of a robot description (parsed by MuJoCo's MJCF parser, nothing compiled or executed):
+ {"bodies": {name: {"parent", "pos", "quat", "geoms": [{"mesh", "material", "rgba", "pos", "quat"}]}},
+ "meshes": {name: {"file" (relative to the description's directory), "scale", "refpos", "refquat"}},
+ "materials": {name: {"rgba", "specular", "shininess", "reflectance", "emission"}}}"""
+ import mujoco as mj
+ xml_path = Path(xml_path)
+ spec = mj.MjSpec.from_file(str(xml_path))
+ meshdir = spec.meshdir or ""
+ meshes = {}
+ for me in spec.meshes:
+ if not me.file:
+ raise ValueError(f"{xml_path.name}: mesh {me.name!r} has no file (only file meshes are supported)")
+ name = me.name or Path(me.file).stem
+ meshes[name] = {"file": os.path.normpath(os.path.join(meshdir, me.file)), "scale": list(me.scale),
+ "refpos": list(me.refpos), "refquat": list(me.refquat)}
+ materials = {mt.name: {"rgba": list(mt.rgba), "specular": float(mt.specular), "shininess": float(mt.shininess),
+ "reflectance": float(mt.reflectance), "emission": float(mt.emission)}
+ for mt in spec.materials}
+ bodies, used = {}, set()
+ for b in spec.bodies:
+ if not b.name or b.name == "world":
+ continue
+ if b.alt.type != mj.mjtOrientation.mjORIENTATION_QUAT:
+ raise ValueError(f"{xml_path.name}: body {b.name} uses an alternative orientation")
+ geoms = []
+ for g in b.geoms:
+ if g.type != mj.mjtGeom.mjGEOM_MESH or g.contype or g.conaffinity or not 0 <= g.group <= 2:
+ continue
+ if g.alt.type != mj.mjtOrientation.mjORIENTATION_QUAT:
+ raise ValueError(f"{xml_path.name}: a visual geom of {b.name} uses an alternative orientation")
+ geoms.append({"mesh": g.meshname, "material": g.material or None, "rgba": list(g.rgba),
+ "pos": list(g.pos), "quat": list(g.quat)})
+ used.add(g.meshname)
+ if g.material:
+ used.add(("mat", g.material))
+ bodies[b.name] = {"parent": b.parent.name if b.parent is not None else "world", "pos": list(b.pos),
+ "quat": list(b.quat), "geoms": geoms}
+ return {"bodies": bodies, "meshes": {n: v for n, v in meshes.items() if n in used},
+ "materials": {n: v for n, v in materials.items() if ("mat", n) in used}}
+
+
+# ------------------------------------------------------------------------------------------------ dressing
+def _meshdir(root) -> str:
+ c = root.find("compiler")
+ if c is None:
+ return ""
+ return c.get("meshdir") or c.get("assetdir") or ""
+
+
+def _asset_key(meshdir: str, file: str) -> str:
+ return os.path.normpath(os.path.join(meshdir, file)) if meshdir else file
+
+
+def _local_frame(el) -> tuple:
+ pos = np.array([float(x) for x in el.get("pos", "0 0 0").split()])
+ if any(el.get(a) is not None for a in ("euler", "axisangle", "xyaxes", "zaxis")):
+ return pos, None
+ return pos, _unitq([float(x) for x in el.get("quat", "1 0 0 0").split()])
+
+
+def dress(match: Scene, d: str | os.PathLike, meshes: str = "full", players: bool = False) -> Scene:
+ """The presentation scene declared in directory `d` for the match scene `match` (see the module docstring), the
+ models with `meshes` ("full" or a level of detail); players: the scene of the players' images (Scene.players).
+ The models' files come from `d`/assets when it exists (a simulator's bundle), else from the cache / lod/."""
+ from . import assets
+ if match.engine != "mujoco":
+ raise PresentationUnavailable(f"presentation scenes need an MJCF scene, not {match.engine!r}")
+ decl = load_decl(d)
+ if players and decl.get("players") is None:
+ raise ValueError(f"{Path(d) / DECL}: the players' images use a presentation scene only when it declares players")
+ bundled = Path(d) / BUNDLE
+ bundle_root = bundled if bundled.is_dir() else None
+ root = ET.fromstring(match.xml)
+ meshdir = _meshdir(root)
+ out_assets = dict(match.assets or {})
+ asset_el = root.find("asset")
+ if asset_el is None:
+ asset_el = ET.Element("asset")
+ root.insert(0, asset_el)
+ default = root.find("default")
+ if default is None:
+ default = ET.Element("default")
+ root.insert(0, default)
+ cls = ET.SubElement(default, "default", {"class": CLASS})
+ ET.SubElement(cls, "geom", {"type": "mesh", "contype": "0", "conaffinity": "0", "group": "2", "mass": "0",
+ "density": "0", "rgba": "0.5 0.5 0.5 1"})
+ parents = {c: p for p in root.iter() for c in p}
+ bodies = {b.get("name"): b for b in root.iter("body") if b.get("name")}
+ credits, n_added, dressed_all, meshes_added = [], 0, set(), set()
+ for ri, rob in enumerate(decl["robot"]):
+ if rob["model"].startswith("./"): # a model shipped in the presentation directory itself
+ xml_file = (Path(d) / rob["model"]).resolve()
+ if Path(d).resolve() not in xml_file.parents:
+ raise ValueError(f"{DECL}: a local model must lie inside the presentation directory")
+ credit = rob.get("credit", f"{rob['model']} (shipped with the sport)")
+ else:
+ xml_file, credit = assets.model_xml(rob["model"], meshes, bundle_root), assets.credit(rob["model"])
+ if meshes != "full":
+ credit += f", visual meshes decimated to level {meshes} (renderers/presentation/lod.json)"
+ parts = model_parts(xml_file)
+ tag = re.sub(r"[^A-Za-z0-9_]", "_", rob["model"])
+ pat = re.compile(rob["bodies"])
+ dressed = {}
+ for name, el in bodies.items():
+ mt = pat.fullmatch(name)
+ if not mt:
+ continue
+ mbody = rob["body"].format(**{k: v or "" for k, v in mt.groupdict().items()})
+ if mbody not in parts["bodies"]:
+ raise ValueError(f"{DECL}: scene body {name} -> {mbody}, which {rob['model']} does not have")
+ dressed[name] = mbody
+ if not dressed:
+ raise ValueError(f"{DECL}: no scene body matches {rob['bodies']!r}")
+ if dressed.keys() & dressed_all:
+ raise ValueError(f"{DECL}: bodies dressed twice: {sorted(dressed.keys() & dressed_all)}")
+ dressed_all |= dressed.keys()
+ for name, mbody in dressed.items(): # the declaration must name bodies in the model's frames
+ par = parents.get(bodies[name])
+ pname = par.get("name") if par is not None and par.tag == "body" else None
+ if pname in dressed and dressed[pname] == parts["bodies"][mbody]["parent"]:
+ pos, quat = _local_frame(bodies[name])
+ mb = parts["bodies"][mbody]
+ if quat is None or np.abs(pos - mb["pos"]).max() > FRAME_TOL or min(
+ np.abs(quat - _unitq(mb["quat"])).max(), np.abs(quat + _unitq(mb["quat"])).max()) > FRAME_TOL:
+ raise ValueError(f"{DECL}: scene body {name} does not sit in its parent's frame as "
+ f"{rob['model']}'s {mbody} does")
+ # assets: the model's meshes and materials, once per robot entry
+ colors = rob.get("colors", {})
+ if set(colors) - set(parts["materials"]) or any(len(v) != 4 for v in colors.values()):
+ raise ValueError(f"{DECL}: colors names materials of {rob['model']} ({sorted(parts['materials'])}), "
+ "each an rgba of 4 numbers")
+ for mname, mat in parts["materials"].items():
+ ET.SubElement(asset_el, "material", {"name": f"ro_{tag}_{ri}_{mname}",
+ "rgba": _f(colors.get(mname, mat["rgba"])),
+ "specular": repr(mat["specular"]),
+ "shininess": repr(mat["shininess"]),
+ "reflectance": repr(mat["reflectance"]),
+ "emission": repr(mat["emission"])})
+ for mname, me in parts["meshes"].items(): # meshes once per model, materials per robot entry
+ if f"ro_{tag}_{mname}" in meshes_added:
+ continue
+ meshes_added.add(f"ro_{tag}_{mname}")
+ rel = f"ro_presentation/{tag}/{me['file']}"
+ attrs = {"name": f"ro_{tag}_{mname}", "file": rel, "scale": _f(me["scale"])}
+ if np.any(np.asarray(me["refpos"]) != 0) or np.any(np.asarray(me["refquat"]) != [1, 0, 0, 0]):
+ attrs.update(refpos=_f(me["refpos"]), refquat=_f(me["refquat"]))
+ ET.SubElement(asset_el, "mesh", attrs)
+ out_assets[_asset_key(meshdir, rel)] = (xml_file.parent / me["file"]).read_bytes()
+ hide = rob.get("hide", "all")
+ hide_pat = re.compile(rob["hide_bodies"]) if rob.get("hide_bodies") else None
+ for name, mbody in dressed.items():
+ body = bodies[name]
+ if hide != "none" and (hide_pat is None or hide_pat.fullmatch(name)):
+ for g in body.findall("geom"):
+ if hide == "all" or g.get("type") == "mesh" or (g.get("mesh") and g.get("type") is None):
+ g.set("group", HIDDEN_GROUP)
+ kids = list(body)
+ at = max([i for i, e in enumerate(kids) if e.tag in ("geom", "inertial", "joint", "freejoint")] + [-1]) + 1
+ for j, g in enumerate(parts["bodies"][mbody]["geoms"]):
+ attrs = {"name": f"{VISUAL_PREFIX}{name}:{j}", "class": CLASS, "mesh": f"ro_{tag}_{g['mesh']}",
+ "pos": _f(g["pos"]), "quat": _f(g["quat"])}
+ if g["material"]:
+ attrs["material"] = f"ro_{tag}_{ri}_{g['material']}"
+ elif not np.allclose(g["rgba"], [0.5, 0.5, 0.5, 1]):
+ attrs["rgba"] = _f(g["rgba"])
+ body.insert(at + j, ET.Element("geom", attrs))
+ n_added += 1
+ credits.append(credit)
+ xml = ET.tostring(root, encoding="unicode")
+ return Scene(engine=match.engine, xml=xml, assets=out_assets, look=match.look, match=match, players=players,
+ credits=tuple(credits) + (f"{decl.get('label', 'presentation scene')} (v{decl['version']}, "
+ f"{n_added} visual geoms" + (", the players' images" if players else "")
+ + ")",))
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/presentation/assets.py b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/presentation/assets.py
new file mode 100644
index 0000000000..14edb00e1d
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/presentation/assets.py
@@ -0,0 +1,198 @@
+"""Third-party model files of the presentation scenes, fetched at build time (never committed): every file is pinned
+to one upstream commit and checked against its sha256 in the manifest (menagerie.json, next to this file). The files
+are untrusted data: they are only read (MJCF parsed, meshes loaded by MuJoCo), never executed. Their licences are
+kept next to the manifest (LICENSE.<model>) and credited in NOTICE.
+
+ python3 -m renderers.presentation.assets fetch [MODEL ...] download the missing files (all models by default)
+ python3 -m renderers.presentation.assets verify [MODEL ...] check what is in the cache
+ python3 -m renderers.presentation.assets where print the cache directory
+
+The cache: $RO_ASSET_CACHE, else <repo>/.cache/assets (git-ignored); files at <cache>/<source>/<commit>/<path>.
+Standard library only (python >= 3.8), so the fetch runs on any host; the renderers read the cache inside the image.
+
+Levels of detail (players' images, renderer rule 6): lod.json lists decimated copies of a model's visual meshes
+(renderers/presentation/lod/<level>/<path>, committed: small, derived from the pinned files, licence unchanged; made by
+lod.py), each file pinned by sha256 like the upstream ones. `meshes` = "full" (the upstream files) or a level ("25k").
+A sport whose players' images use its presentation scene gets the model's files bundled into its simulator directory
+(`bundle`, tools/sportlib.assemble_sim): <sim>/sport/presentation/assets/<path>, checked against the same manifests,
+so a match needs neither the cache nor the network.
+"""
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import sys
+import urllib.request
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+MANIFESTS = ("menagerie.json",)
+LOD_MANIFEST = "lod.json"
+FULL = "full"
+_verified: set = set()
+
+
+class _Unavailable(RuntimeError):
+ pass
+
+
+def _err(msg):
+ try:
+ from . import PresentationUnavailable
+ except ImportError: # pragma: no cover - run as a script on a host without numpy
+ return _Unavailable(msg)
+ return PresentationUnavailable(msg)
+
+
+def manifests() -> list:
+ return [json.loads((HERE / m).read_text()) for m in MANIFESTS]
+
+
+def _find(name: str):
+ for man in manifests():
+ if name in man["models"]:
+ return man, man["models"][name]
+ raise KeyError(f"no presentation model {name!r} in {', '.join(MANIFESTS)}")
+
+
+def cache_root() -> Path:
+ env = os.environ.get("RO_ASSET_CACHE")
+ return Path(env) if env else HERE.parents[1] / ".cache" / "assets"
+
+
+def _base(man) -> Path:
+ return cache_root() / man["name"] / man["commit"]
+
+
+def _sha(p: Path) -> str:
+ h = hashlib.sha256()
+ with open(p, "rb") as f:
+ for chunk in iter(lambda: f.read(1 << 20), b""):
+ h.update(chunk)
+ return h.hexdigest()
+
+
+def lods() -> dict:
+ """lod.json: {"models": {model: {level: {"files": {path: sha256}, ...}}}, ...} ({} if absent)."""
+ p = HERE / LOD_MANIFEST
+ return json.loads(p.read_text()) if p.is_file() else {}
+
+
+def files(name: str, meshes: str = FULL) -> dict:
+ """{path: sha256} of model `name` with the given meshes ("full" or a level of lod.json)."""
+ man, mod = _find(name)
+ if meshes == FULL:
+ return dict(mod["files"])
+ lev = (lods().get("models", {}).get(name) or {}).get(meshes)
+ if lev is None:
+ raise KeyError(f"no level of detail {meshes!r} of {name} in {LOD_MANIFEST}")
+ return dict(lev["files"])
+
+
+def source_dir(name: str, meshes: str = FULL) -> Path:
+ """Where the files of `name` with `meshes` live on this checkout: the cache (full) or renderers/presentation/lod."""
+ man, _ = _find(name)
+ return _base(man) if meshes == FULL else lod_root() / meshes
+
+
+def lod_root() -> Path:
+ """The levels of detail: $RO_LOD_DIR (robot_coding_bench: the eai-olympiad image ships them at
+ /opt/roboolympics/lod, verified here against lod.json), else renderers/presentation/lod."""
+ env = os.environ.get("RO_LOD_DIR")
+ return Path(env) if env else HERE / "lod"
+
+
+def missing(name: str, meshes: str = FULL, root: Path | None = None) -> list:
+ """The files of model `name` that are absent (from `root`, default its source_dir) or do not match their sha256."""
+ base = Path(root) if root is not None else source_dir(name, meshes)
+ return [p for p, sha in files(name, meshes).items() if not (base / p).is_file() or _sha(base / p) != sha]
+
+
+def model_xml(name: str, meshes: str = FULL, root: Path | None = None) -> Path:
+ """The model's MJCF file, all its files verified (once per process): from `root` (a simulator's bundle) if given,
+ else from the cache (full meshes) or renderers/presentation/lod (a level of detail)."""
+ _, mod = _find(name)
+ base = Path(root) if root is not None else source_dir(name, meshes)
+ key = (name, meshes, str(base))
+ if key not in _verified:
+ bad = missing(name, meshes, base)
+ if bad:
+ how = (f"python3 -m renderers.presentation.assets fetch {name}" if meshes == FULL and root is None
+ else "regenerate the task (tools/generate.py)" if root is not None
+ else f"python3 -m renderers.presentation.lod build {name} {meshes}")
+ raise _err(f"presentation model {name} ({meshes} meshes): {len(bad)} of {len(files(name, meshes))} files "
+ f"missing or not matching their sha256 in {base} ({how})")
+ _verified.add(key)
+ return base / mod["xml"]
+
+
+def bundle(name: str, meshes: str, dst: Path) -> list:
+ """Copy model `name` with `meshes` (verified) and its licence into the directory `dst` (a simulator's
+ sport/presentation/assets): returns the paths written, relative to dst."""
+ import shutil
+ _, mod = _find(name)
+ src = source_dir(name, meshes)
+ model_xml(name, meshes) # verifies every file
+ out = []
+ for p in sorted(files(name, meshes)):
+ (Path(dst) / p).parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(src / p, Path(dst) / p)
+ out.append(p)
+ lic = mod["license_file"]
+ shutil.copyfile(HERE / lic, Path(dst) / lic)
+ return out + [lic]
+
+
+def credit(name: str) -> str:
+ man, mod = _find(name)
+ return (f"{mod['title']}: {man['title']} ({man['source']}, commit {man['commit'][:12]}, {mod['path']}), "
+ f"{mod['copyright']}, {mod['license']} (renderers/presentation/{mod['license_file']})")
+
+
+def fetch(name: str, log=print) -> int:
+ man, mod = _find(name)
+ base = _base(man)
+ n = 0
+ for p, sha in sorted(mod["files"].items()):
+ dst = base / p
+ if dst.is_file() and _sha(dst) == sha:
+ continue
+ url = man["url"].format(commit=man["commit"], path=p)
+ dst.parent.mkdir(parents=True, exist_ok=True)
+ tmp = dst.with_name(dst.name + ".part")
+ with urllib.request.urlopen(url, timeout=60) as r, open(tmp, "wb") as f:
+ f.write(r.read())
+ got = _sha(tmp)
+ if got != sha:
+ tmp.unlink()
+ raise _err(f"{url}: sha256 {got} != {sha} (manifest); nothing kept")
+ tmp.replace(dst)
+ n += 1
+ log(f"{name}: {len(mod['files'])} files in {base} ({n} downloaded)")
+ return n
+
+
+def main(argv) -> int:
+ cmd, names = (argv[0] if argv else "verify"), argv[1:]
+ if cmd == "where":
+ print(cache_root())
+ return 0
+ names = names or [n for man in manifests() for n in man["models"]]
+ rc = 0
+ for n in names:
+ if cmd == "fetch":
+ fetch(n)
+ elif cmd == "verify":
+ for meshes in [FULL] + sorted(lods().get("models", {}).get(n, {})):
+ bad = missing(n, meshes)
+ print(f"{n} ({meshes}): " + ("ok" if not bad else f"{len(bad)} files missing or changed"))
+ rc |= bool(bad)
+ else:
+ print(__doc__)
+ return 2
+ return rc
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/presentation/lod.json b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/presentation/lod.json
new file mode 100644
index 0000000000..d1eb0f5fcf
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/presentation/lod.json
@@ -0,0 +1,94 @@
+{
+ "models": {
+ "franka_emika_panda": {
+ "25k": {
+ "files": {
+ "franka_emika_panda/assets/link0_0.obj": "0e6958fd2f69a9c6ec82e59fb3a39689810bcd69180dd865866359b69d0204ba",
+ "franka_emika_panda/assets/link0_1.obj": "5ca2ade591ead9e9d3046468f6d861631b8fcd0434cb6dfbfbc7eb09cbc11c81",
+ "franka_emika_panda/assets/link0_10.obj": "c8daf1be7a5d3d89aa3f0976c6c43afa9d5841697c0ed91edcad8d60a75b1e60",
+ "franka_emika_panda/assets/link0_11.obj": "0ced2c2a707b13a391306d04f9ad9d4318caf2ce924cb242321a1cd9773c3753",
+ "franka_emika_panda/assets/link0_2.obj": "d7d11c50dee70b7d9149805576c85e026d3f4df2df1b824891451f72bce20e1d",
+ "franka_emika_panda/assets/link0_3.obj": "35bad1cdde8a1e6cee4522b22aa4e46d6a06a54bccc3bc966691f96cde0953fa",
+ "franka_emika_panda/assets/link0_4.obj": "ee1d81feeb6591b8a0b4d0e175f7541ffa40725aa6b97d048d289dc5c5517913",
+ "franka_emika_panda/assets/link0_5.obj": "17438838e57292cdc0c18f5417c020ed3290323e50ca4c1b58b07065961bc95c",
+ "franka_emika_panda/assets/link0_7.obj": "2ccf52f5c8b6155fd2764435028b59ad64d23820bb080d9079ba52b939ccee36",
+ "franka_emika_panda/assets/link0_8.obj": "7f895de6ec3ebdd93f5af7c446616da908cf423131dc2c24da50146b32718baa",
+ "franka_emika_panda/assets/link0_9.obj": "8ef4ff7f0676b60a8edf54380b4b696bae3b5a5202e38f7ca64bb3a2f6e0496b",
+ "franka_emika_panda/assets/link1.obj": "89a7387d65a311e92cd39dc65c0f5a7d00a5d342bf670613b87b09da016a82c8",
+ "franka_emika_panda/assets/link2.obj": "b66faa46466a258f1f36250bf4530424eb37b47ae1fcc4dbb114b37a499287a2",
+ "franka_emika_panda/assets/link3_0.obj": "b6124b7a17d85ce218ed739ae1792c4762718e43f135e3633008bc753aebe20f",
+ "franka_emika_panda/assets/link3_1.obj": "6d05236a2bb84117328a7d421f41058ddd9969d5317a5c5a5375da311dc17f30",
+ "franka_emika_panda/assets/link3_2.obj": "4d3f6753c0aa9469486317d5eee5e2ac8b1615b705a78e35335a298a4644cd03",
+ "franka_emika_panda/assets/link3_3.obj": "5afeb0a5722704920fe3930fd56fa30dde7faf1932377e9b5fbaafbf1b6f5030",
+ "franka_emika_panda/assets/link4_0.obj": "ef4c8095c339dbf8e10e727f5361598220833689cd79ac59d10508423934fc93",
+ "franka_emika_panda/assets/link4_1.obj": "7050225b33d23afafac7f597b250e59c7353e3193ecb1098c3708f2f4d561e52",
+ "franka_emika_panda/assets/link4_2.obj": "e084c51cdddb612869d45ae94e31b19a1d011f9c182faff07b1f953ca9e7e6c1",
+ "franka_emika_panda/assets/link4_3.obj": "c5ef5783e41d161269018a4b16446db8e400eb7780527a161e62bf7ed2289e46",
+ "franka_emika_panda/assets/link5_0.obj": "f64a7b7f023bdcaf8d8fac082145d365751c69e9b6bda942c5de3dd3dc8806a4",
+ "franka_emika_panda/assets/link5_1.obj": "8bfc7df033b58c4e7b5f1080dc05da81699ffc237a91b8da9e2a6119cb79b494",
+ "franka_emika_panda/assets/link5_2.obj": "437ee6f13c4d98db88ad75d832aa6bdcb5453db256d5691be1931c4acd935bf9",
+ "franka_emika_panda/assets/link6_0.obj": "9c87e9689cfeacb6b1d2ce305cddcbad463f420584dbd220b2080e3c636b3762",
+ "franka_emika_panda/assets/link6_1.obj": "6445e25a8759385c43f0d5285d50f77eb08f34afe6fbb2d07ddf352c8b3d13b5",
+ "franka_emika_panda/assets/link6_10.obj": "05ec79c4defd0548107dc58f2d7ab26b010a2ca7b7878ed0b282a3540679f620",
+ "franka_emika_panda/assets/link6_11.obj": "96dc648b3382a4b3688d801bb94eb3b6cb1d6e64367e8cae29d2a7c3178324c3",
+ "franka_emika_panda/assets/link6_12.obj": "7b2bea2a736a63661cdae29ef30740a26d08ce43c4a787788907d44d2853413e",
+ "franka_emika_panda/assets/link6_13.obj": "5f6745688f8c3a4172af1689d6a52f320264104414853e72c5a022bdaac77026",
+ "franka_emika_panda/assets/link6_14.obj": "569977e1c13942d0aa84ba42188f5256de447266e1db2e0f46159482791acbc5",
+ "franka_emika_panda/assets/link6_15.obj": "3d201820c51a032ee1e12232b5cb709b20062b8a991d6446a225f6aa8471e486",
+ "franka_emika_panda/assets/link6_16.obj": "ad4f0e691598a70ef3de25b8840d8893b48150dcbb6012a7295cbe706e8de05c",
+ "franka_emika_panda/assets/link6_2.obj": "b6bc873ba1bcbf54af2667d197722f681d82f591173cecb75cad0a67e2b47e3d",
+ "franka_emika_panda/assets/link6_3.obj": "9da48c192b317dde105666470c4898e0ca6ae54cd57f386867de76f3e75f8116",
+ "franka_emika_panda/assets/link6_4.obj": "ed80f9d8e9da1c3252cc375704f80bec5b8263198178db9a4fca72587d9525d2",
+ "franka_emika_panda/assets/link6_5.obj": "68eba154d3031354e6682dea960993b668ce3229fde73d1aaf9456e2978be95e",
+ "franka_emika_panda/assets/link6_6.obj": "c8316be35257df937810664619b67b45820b60dcbd0b219fe7e540bc12e81156",
+ "franka_emika_panda/assets/link6_7.obj": "6bc1c0ce40b6fbf22d37000ffe95255c044a168cd5241a5c56e86bdf5c171f92",
+ "franka_emika_panda/assets/link6_8.obj": "d821b8c3875eca9ad19aa6112a86eb2a0cc0d75ad07349d004c449e85eb00f14",
+ "franka_emika_panda/assets/link6_9.obj": "bd9beb29cdef7b5c6014529f65520245fa83bd8b84c0b57288a9235da2fc94c5",
+ "franka_emika_panda/assets/link7_0.obj": "16a21aac2faf5c012b1b2b2aac5c6170f78caba505a0885fed7c14b3a672899b",
+ "franka_emika_panda/assets/link7_1.obj": "7f5391b3b7104189b38c65d10a8fe213ef6d6443dc05ea7c2c6d7b31fb483ff9",
+ "franka_emika_panda/assets/link7_2.obj": "16e8c340cc6f3c9d2f15760f58892e15d0e668b09b81088a39b3a77929de0721",
+ "franka_emika_panda/assets/link7_3.obj": "47795dd7fc1d3d253313b7b39f94e06036169b3380b2d7486fb51ce53916e04d",
+ "franka_emika_panda/assets/link7_4.obj": "8c3614d6cf07660c5cbfa12edae41bd22a49d4bec9f9c4a2139a00607d1e8f63",
+ "franka_emika_panda/assets/link7_5.obj": "23e7ba2a16fca00e48b6e397d6da49b25af4e5327c6b186217aedcc808f0892f",
+ "franka_emika_panda/assets/link7_6.obj": "40e6a822ade171dcb2ecc6d5d510c9b878505e2af3b497f7e772605fdf2b9c2b",
+ "franka_emika_panda/assets/link7_7.obj": "d70d61a09b7a605a47caf5d5b7225f3d5cce1af1c849b262ab9ea0242c50464b",
+ "franka_emika_panda/panda_nohand.xml": "e7090a5e2384b18a223ef532d98bf914f7f9a6b74dc8bc9f74c8291201074071"
+ },
+ "source": "menagerie@f054586a8e90465d49ee5be15335c4a0c7f57caf",
+ "source_triangles": 126562,
+ "target_triangles": 25000,
+ "triangles": 25568
+ }
+ },
+ "kuka_iiwa_14": {
+ "25k": {
+ "files": {
+ "kuka_iiwa_14/assets/band.obj": "40784c36ec38f8ff2fa804e3c242656b9ed3ae41a33785af33c917de1bbd566f",
+ "kuka_iiwa_14/assets/kuka.obj": "b79762633220dcfae4b45b40d2880a83128e373003f794f0d9a19f4989c92ec7",
+ "kuka_iiwa_14/assets/link_0.obj": "fc2590b0e7ce20e1fa9a5ab4f48259908508c6ad4aeebc4d2ef13e5d22ba23e5",
+ "kuka_iiwa_14/assets/link_1.obj": "81f65e2f348ac6bfdd4968a1440406c9abc9ca6b51de7a404024a08ef46127eb",
+ "kuka_iiwa_14/assets/link_2_grey.obj": "07bc12ae4e6edc159e4123e9a5571a08d03211de8afa503c9cfb74dff51208b2",
+ "kuka_iiwa_14/assets/link_2_orange.obj": "4b151e4dc5689342ad6be614c9114ab3c0668a1aaba25eafc78c8e2e9f7a01f8",
+ "kuka_iiwa_14/assets/link_3.obj": "77be645b049e35bfb1c2bf05d610c95044b39dc17209b4d5e63ded1e4b87832d",
+ "kuka_iiwa_14/assets/link_4_grey.obj": "79f6693b2031e1f24069c56546490d7d1ff6907b3871bd049bba187d4ff0786a",
+ "kuka_iiwa_14/assets/link_4_orange.obj": "2e0613541153884f9a3cc2de654492d7aa563368c6fae335c82109b5def79f4d",
+ "kuka_iiwa_14/assets/link_5.obj": "2f0ee7aeb51dfa86f98954f8673fafdb8c63dfa37618d4e0e76c7db037af267c",
+ "kuka_iiwa_14/assets/link_6_grey.obj": "4eb7481b31d88612b6cc791d8390c3145e367ca87537a2f6763e3c2c2b01dd13",
+ "kuka_iiwa_14/assets/link_6_orange.obj": "450b41e8691e1ccfa427da45d65d4f95c40cd388433fc753c1ab86087d178cdc",
+ "kuka_iiwa_14/assets/link_7.obj": "c35ef794a848268745f3d1e283dbcdb0bf117373110364b62c8405af4275eac1",
+ "kuka_iiwa_14/iiwa14.xml": "ee7e6d796a9f8642de6097f95077281d15f43678dc5285beafeda99b84cf9ef5"
+ },
+ "source": "menagerie@f054586a8e90465d49ee5be15335c4a0c7f57caf",
+ "source_triangles": 73989,
+ "target_triangles": 25000,
+ "triangles": 25141
+ }
+ }
+ },
+ "name": "lod",
+ "note": "Levels of detail of the presentation models (players' images, renderer rule 6): a model's visual meshes decimated to a triangle budget, so that a sport can draw its players' images with fine meshes on the CPU at a small cost and bundle them into its simulator directory (a few MB instead of 30).",
+ "tools": {
+ "fast-simplification": "0.2.0",
+ "trimesh": "5.1.1"
+ }
+}
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/presentation/menagerie.json b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/presentation/menagerie.json
new file mode 100644
index 0000000000..f20f9bb91f
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/presentation/menagerie.json
@@ -0,0 +1,135 @@
+{
+ "name": "menagerie",
+ "title": "MuJoCo Menagerie",
+ "source": "https://github.com/google-deepmind/mujoco_menagerie",
+ "commit": "f054586a8e90465d49ee5be15335c4a0c7f57caf",
+ "url": "https://raw.githubusercontent.com/google-deepmind/mujoco_menagerie/{commit}/{path}",
+ "note": "Generated from the pinned commit: per model its MJCF description and the visual meshes of its visual geoms (no collision meshes, textures or scripts). Untrusted data: read only.",
+ "models": {
+ "franka_emika_panda": {
+ "title": "Franka Emika Panda (no hand)",
+ "path": "franka_emika_panda/",
+ "xml": "franka_emika_panda/panda_nohand.xml",
+ "license": "Apache-2.0",
+ "license_file": "LICENSE.franka_emika_panda",
+ "copyright": "MuJoCo Menagerie authors, derived from Franka Emika's franka_ros description",
+ "files": {
+ "franka_emika_panda/assets/link0_0.obj": "6b9f41a4c203540daaeb7a33cc3d0d6c6a32dc8bba187074eeaf97b3e36b3f9c",
+ "franka_emika_panda/assets/link0_1.obj": "57673d2ee2a9db2e10c8986ae57c56a7c39c012b60fd26d7d8549553b664a5ed",
+ "franka_emika_panda/assets/link0_10.obj": "c9198b9d8534d628d097b0f2b239bb30343353182df098ce0d9db6bc13326848",
+ "franka_emika_panda/assets/link0_11.obj": "f0adec78d6677b7799d25121981270e8bfe119b5c18d08a91ee37a54ad75f65c",
+ "franka_emika_panda/assets/link0_2.obj": "1ca435a2a87a9608a146a47955724d43dd7ce10fc3dd3018800aa98f8ba86e05",
+ "franka_emika_panda/assets/link0_3.obj": "3e9c6334d2b3b47944af3458ee5f20519abc20fe7ee23063bb53405ccab28046",
+ "franka_emika_panda/assets/link0_4.obj": "215d25789704936120f119c0bc1cc7f68516dd3f8f1df61457b71acac3873f26",
+ "franka_emika_panda/assets/link0_5.obj": "9361b104e93743045107aa5b15fb1a0835ba9c1f355aae71f56403cf6a9c33f6",
+ "franka_emika_panda/assets/link0_7.obj": "2dc0b8ebbbc80e4c065d71e195adbc384f673438641fac82b07b801b4d2837cb",
+ "franka_emika_panda/assets/link0_8.obj": "3b8c436999db5586b8eb47bed2b0aa7de6993868b2681b4c04246eeac42fdb7a",
+ "franka_emika_panda/assets/link0_9.obj": "45178f97d2b5da6bce11f610212c4ef7d08c73db33a4fc38e1b7f66b93d023f5",
+ "franka_emika_panda/assets/link1.obj": "51091e776b16babdbe2f3849b5c041f921d1f11dd94ac19a0f1c81abf496fbae",
+ "franka_emika_panda/assets/link2.obj": "5c9f8e715de52c3eb71b475de35993b3b96081e02abea9f28c414768877fc59b",
+ "franka_emika_panda/assets/link3_0.obj": "ce2da87f51708e11b189249d41401065dabe89a06e251185a06cef4d5ff27178",
+ "franka_emika_panda/assets/link3_1.obj": "2880b7753a7173f38fa87ee21da4dfc7fa7be46fbe07bac5aef9e128513cb118",
+ "franka_emika_panda/assets/link3_2.obj": "670cff81ae84693769ca4ae658c154cf909d81167e7c8d22b70ea977f2504efa",
+ "franka_emika_panda/assets/link3_3.obj": "30ede0c812efd0e0b767d134a4eae0b84e0fa407bb6325a5a555e0569b3a3ffd",
+ "franka_emika_panda/assets/link4_0.obj": "443bf6d178177cf347951ecf107ccd10ca444e605e375b67304579e5f948806f",
+ "franka_emika_panda/assets/link4_1.obj": "ca935ec7cc8b3f0e86aa079c76b0b3bf593b1e9830bab0fa7131ac51577c74f0",
+ "franka_emika_panda/assets/link4_2.obj": "c89caf26d379c35bb9e191ee2d91d09ab29ecc792b48d8bc10b39e5b38222175",
+ "franka_emika_panda/assets/link4_3.obj": "1495d17f45bdb230cf58b0beef9da4e8c9cfe76a3d2d38da89017efe5e093136",
+ "franka_emika_panda/assets/link5_0.obj": "a3238b8f2af0f2eb66d9fe63dc5d41ac52d5d38507241b5ed10e3cb019ab3e71",
+ "franka_emika_panda/assets/link5_1.obj": "9d994bbf83ec241e301b5197a6846da13f2a4a0582edb2c0f76962c5549649d6",
+ "franka_emika_panda/assets/link5_2.obj": "83b4ffe9f772cd7fe182e98640650eebc899aaf01842656574b0416c90dd40a4",
+ "franka_emika_panda/assets/link6_0.obj": "0504c70ebf1b284ee8faae7dcb896b8830bc672a6552015dd5dbd121fa031fb9",
+ "franka_emika_panda/assets/link6_1.obj": "45f7ca77695198b6d86ec2417ad4e42e6275044f0f96266699ee8e1057757ac1",
+ "franka_emika_panda/assets/link6_10.obj": "365f26c21d10332cab8d8704645cb46930c30b3085956f2d097498c793f24db4",
+ "franka_emika_panda/assets/link6_11.obj": "8ae61e08b3ad064f25bbf03b22e59cc15d65883b5a7ce92711aff29df2493901",
+ "franka_emika_panda/assets/link6_12.obj": "f28d1bfd62b0244ffd19fb35fe9edefdf583d3c9167db944e87185d919e1d021",
+ "franka_emika_panda/assets/link6_13.obj": "0a55fa92dccb261d07200e6565fca4c850fd17f0c1ecf38821c0b97d51796c7d",
+ "franka_emika_panda/assets/link6_14.obj": "750ae3ee4781e62e3a045c662195247b03f6642b05aa93104f08258e5f6eba26",
+ "franka_emika_panda/assets/link6_15.obj": "5999c1c2497a004a7c4bbe034cdf13744f839d85ae7a11b1bc386c48a3e642e6",
+ "franka_emika_panda/assets/link6_16.obj": "551d7a8b37c53e7a152d008b4e36992e5b5abe74a4be18b57ee6319c27def09f",
+ "franka_emika_panda/assets/link6_2.obj": "e54eee4d8232947ee8af65afd5a067e09dac2da6e7e585cb1dccb65496457da0",
+ "franka_emika_panda/assets/link6_3.obj": "d4f6a25ef32fa1fa4734146981994ee760232cb077c80fea6487d78a077c7f27",
+ "franka_emika_panda/assets/link6_4.obj": "be353480fe71d46f7a96f0a3cbb7e112caaf8d88368826f321a36a253c8749b2",
+ "franka_emika_panda/assets/link6_5.obj": "7c87664623c3e1a6cb330db273227a69626dc5e53b4caff1d4ee7911eb3340c6",
+ "franka_emika_panda/assets/link6_6.obj": "8fbc031e0d07b795ebf99115c75223141caaba317cab569159f3d477a7821681",
+ "franka_emika_panda/assets/link6_7.obj": "7dc5ebb799fe281aab27d6e84e7a4efa0a8e42da2369ec83de3ea3f206f62d73",
+ "franka_emika_panda/assets/link6_8.obj": "e3f77381817a341030f9dcc4c4aa7c559f80411b453fd87eb0fefecca82151bf",
+ "franka_emika_panda/assets/link6_9.obj": "25a56ea9b02a03b6cb5a81f31c54f54d0185e1a0b3937c37e4289d896e50215a",
+ "franka_emika_panda/assets/link7_0.obj": "04586b0bde011715cfc22072ac72fe0717eb4d4817bcf665987ce6cd88eb2b93",
+ "franka_emika_panda/assets/link7_1.obj": "c3f72289f394c9d6749a4a327fb11f05b203c37c95032c92f28019b40ebe7e00",
+ "franka_emika_panda/assets/link7_2.obj": "d2faecedb304d0989040d082410378dc949dbbda23bd18c05134f08aae984db5",
+ "franka_emika_panda/assets/link7_3.obj": "b62d87c4d4bdb7b281ed341d347c39dad0e50bf36aed8ac11d050073701d5f70",
+ "franka_emika_panda/assets/link7_4.obj": "cb78ccb61fd4ad6c7bff4c4d2e6cb41e1964a5a3e1a28e67c0c6202371cfc018",
+ "franka_emika_panda/assets/link7_5.obj": "099071d3090b51471ba52f4f90814fd3089f4975d196e4d488117073d0bfe491",
+ "franka_emika_panda/assets/link7_6.obj": "99469e2d95ab74ce0292f2f16954c87a8a7dc16652e62e970fe37c94330a81bb",
+ "franka_emika_panda/assets/link7_7.obj": "426c3db8a19373f3dc73d4bec672e948121b2914c10e2e7b9c7ea80643a19e54",
+ "franka_emika_panda/panda_nohand.xml": "e7090a5e2384b18a223ef532d98bf914f7f9a6b74dc8bc9f74c8291201074071"
+ },
+ "bytes": 32259617,
+ "visual_geoms": 49
+ },
+ "kuka_iiwa_14": {
+ "title": "KUKA LBR iiwa 14",
+ "path": "kuka_iiwa_14/",
+ "xml": "kuka_iiwa_14/iiwa14.xml",
+ "license": "BSD-3-Clause",
+ "license_file": "LICENSE.kuka_iiwa_14",
+ "copyright": "MuJoCo Menagerie authors, derived from the Drake developers' iiwa14 description",
+ "files": {
+ "kuka_iiwa_14/assets/band.obj": "02cf16a93140489da3b05ce6bb30c5498bedaa5e5a77e56850ddbedb8d1ed23e",
+ "kuka_iiwa_14/assets/kuka.obj": "204a82d597d450f2a207731f8e3c17089f2de5a54c0d61feac454e96e325b834",
+ "kuka_iiwa_14/assets/link_0.obj": "6b607f6b5a601874863897ebfbb9821eb0c831c3115bca8350bf7856db6aaeee",
+ "kuka_iiwa_14/assets/link_1.obj": "47a82247b647639c3e1f384ce5b980d374323ca737d6ebc87447667a71981798",
+ "kuka_iiwa_14/assets/link_2_grey.obj": "842b8c3a9148b2fdf9c57ddfd80b595f8251792f94b71276dc9ce9a16674ba1a",
+ "kuka_iiwa_14/assets/link_2_orange.obj": "0d2d8829d89aa888ee04b0d97bed5f215fa0d9fd03d0d4cee2b2e0c8dd3c0124",
+ "kuka_iiwa_14/assets/link_3.obj": "b02d157e8090d82bfb78e7fd4dcd351033e0a5d7bb1937da01e66e7ff91a03a8",
+ "kuka_iiwa_14/assets/link_4_grey.obj": "e4555ea6954fffa40174baee25e6dd1b9efcc3eaf830b6e91d13e2ddc10b414a",
+ "kuka_iiwa_14/assets/link_4_orange.obj": "ef4cf2102e9df98636ff03b82d49d914a6e730b299b0a982d64947f038136cb7",
+ "kuka_iiwa_14/assets/link_5.obj": "f0eef60cddf06e46bd943abcc49ada87510f095f2840bc9c117ed7a2b1a6a787",
+ "kuka_iiwa_14/assets/link_6_grey.obj": "5b5f9883d4fc181c7aa06cb2037debfa4ca857fa0c3a5d55f8fd3e34d38c3100",
+ "kuka_iiwa_14/assets/link_6_orange.obj": "54aa0141e7f48497302f45daf074fd5c69320c620618c12fa76e8841c2a8a9fc",
+ "kuka_iiwa_14/assets/link_7.obj": "7307d0c852715ea234e575a0617ea2d8faf053469e7b823ac0c7c6c4dff36dad",
+ "kuka_iiwa_14/iiwa14.xml": "ee7e6d796a9f8642de6097f95077281d15f43678dc5285beafeda99b84cf9ef5"
+ },
+ "bytes": 5015391,
+ "visual_geoms": 15
+ },
+ "booster_t1": {
+ "title": "Booster T1",
+ "path": "booster_t1/",
+ "xml": "booster_t1/t1.xml",
+ "license": "Apache-2.0",
+ "license_file": "LICENSE.booster_t1",
+ "copyright": "MuJoCo Menagerie authors, derived from Booster Robotics' booster_gym T1 description",
+ "files": {
+ "booster_t1/assets/AL1.stl": "43f5d268152b3c169d34731545ddfa2a510a7e16f209a2a80f8ba9ae0e1a40aa",
+ "booster_t1/assets/AL2.stl": "4bca60adb29c73f701350abd23e8a8d660dc61e87c5163a80157650dd3ad88c3",
+ "booster_t1/assets/AL3.stl": "bfdf5611dfe90f8e02b07b037c36a244f4ce7184b45113371ef46e624fb30854",
+ "booster_t1/assets/AR1.stl": "6dbbd3dab4486600747be9d0e7f8523d67bf00d24d0dc9c23db1766c4d808fcf",
+ "booster_t1/assets/AR2.stl": "0499136785fe1bc0289d9e503e1e0ea48f5a63420a2e45b0fcd9e6b3bcf8f999",
+ "booster_t1/assets/AR3.stl": "92330bd8286fe420fb76949ee4c5d5bdec2e6bb30426acdc4d6fae9257464631",
+ "booster_t1/assets/Ankle_Cross_Left.stl": "e6ec38741838475834c147f2ad18196c0254741e602c2b676f888fd12b5d7981",
+ "booster_t1/assets/Ankle_Cross_Right.stl": "b15d91f0f2470fc4d5634db906a3d7efaf1f700302e6671824494da8faf50308",
+ "booster_t1/assets/H1.stl": "527a2e426db4e3d476a195754764b7f9565a950b809a34e47618f177b139c3f2",
+ "booster_t1/assets/H2.stl": "9cbf4fe83a721c809de65b1f0d0a379314f4523f7e2f8af7f0edc27c2ce385aa",
+ "booster_t1/assets/Hip_Pitch_Left.stl": "7bcb8be569aeb5379cb75a0827d682bc1d73a52a7f515d3aeffece43842c33c9",
+ "booster_t1/assets/Hip_Pitch_Right.stl": "054d579c3c6ccc1f97aaf1461d802dec748ce1bf26c6fdd289283a2d0dbb2032",
+ "booster_t1/assets/Hip_Roll_Left.stl": "72dbd65bdb4e87444c8e538474f631d63bf8c0960922517456b8cf2be9e1d0f0",
+ "booster_t1/assets/Hip_Roll_Right.stl": "d715a7649ea4bf20d7ee17b3a57bae31732e467b9da1053fee2242c90f50980f",
+ "booster_t1/assets/Hip_Yaw_Left.stl": "d588e0467094811e74ae1962fcb0eb669f9b50b74022e96a738bdc8e807e03a7",
+ "booster_t1/assets/Hip_Yaw_Right.stl": "5135f2fd5707364583d283e2fb21845054f3548c224f48e1f0a3d78ed3453497",
+ "booster_t1/assets/Shank_Left.stl": "6ae8dd7f88cb70a4a3cb3972cad4035a76f1604fd73ea66e285da553b3703c40",
+ "booster_t1/assets/Shank_Right.stl": "dc66a8a0e2e31e413884a053e427d9b5007bef4508986587916a638a8a448599",
+ "booster_t1/assets/Trunk.stl": "39d9610b23ef8ac7ea4343231a499f9c485903bede62df9729a2cd1254fede8f",
+ "booster_t1/assets/Waist.stl": "2fe0a9ccfc284beca402e554db38e83022592192afa00f02db13cb374ffe9fbc",
+ "booster_t1/assets/left_foot_link.stl": "82d653e30c0ae2e588c3c539266c9a1fee20e711448e13598f25384c7dc562ca",
+ "booster_t1/assets/left_hand_link.stl": "34df992aed438446481cfa20e78327810cd5cc5ecbb4a6f32ba2bf625462f53d",
+ "booster_t1/assets/right_foot_link.stl": "78440aa4bab7c397b8e507431b44b814e4cb89db0d03455f83ae54e3157cf15b",
+ "booster_t1/assets/right_hand_link.stl": "c5a73e493e17db7611a81785f80c01167f51018271b4042f72fa8d2351d8b0eb",
+ "booster_t1/t1.xml": "78af3f7910e4413894863b6427f44a7daf49e5eb47628e6fe2db775219e346b9"
+ },
+ "bytes": 8445726,
+ "visual_geoms": 24
+ }
+ }
+}
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/scene_check.py b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/scene_check.py
new file mode 100644
index 0000000000..5713371f35
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/renderers/scene_check.py
@@ -0,0 +1,164 @@
+"""Same scene (renderer rule 2): a non-default renderer draws the default renderer's scene. The geometry, kinematics,
+cameras and the colour a viewer sees of every untextured geom must be identical; a re-textured surface keeps its mean
+colour within TEXTURE_TOL. Only lights, materials (specular, shininess, reflectance, textures with the same mean
+colour) and image quality may differ. The same rule as scripts/olympiad/showcase/looks.same_scene, without the
+sport-specific decor exception (decor is presentation-only and never part of a renderer's player picture).
+
+Same kinematics (renderer rule 6): a presentation scene (renderers/presentation.py, spectators only) may differ from
+the match scene in appearance and by added visual-only geoms, never in bodies, joints, frames, inertias or cameras;
+same_kinematics() checks it before a renderer draws one, pose_diff() compares body poses over recorded states."""
+from __future__ import annotations
+
+import numpy as np
+
+SAME = ("nq", "nv", "nbody", "njnt", "ngeom", "nmesh", "ncam", "nmocap",
+ "body_parentid", "body_pos", "body_quat", "body_mass", "jnt_type", "jnt_qposadr", "jnt_pos", "jnt_axis",
+ "geom_type", "geom_bodyid", "geom_size", "geom_pos", "geom_quat", "geom_group", "geom_dataid",
+ "mesh_vertnum", "mesh_vert", "mesh_face",
+ "cam_mode", "cam_bodyid", "cam_pos", "cam_quat", "cam_fovy")
+DEFAULT_RGBA = (0.5, 0.5, 0.5, 1.0)
+TEXTURE_TOL = 0.02
+MESH = 7 # mjtGeom.mjGEOM_MESH
+
+
+def effective_rgba(m, g):
+ rgba = m.geom_rgba[g]
+ if m.geom_matid[g] >= 0 and np.allclose(rgba, DEFAULT_RGBA):
+ return m.mat_rgba[m.geom_matid[g]]
+ return rgba
+
+
+def _texid(m, g):
+ import mujoco as mj
+ mid = m.geom_matid[g]
+ return int(m.mat_texid[mid, mj.mjtTextureRole.mjTEXROLE_RGB]) if mid >= 0 else -1
+
+
+def _mean_colour(m, g):
+ """Mean drawn colour of a geom (texture mean x material/geom colour), 0..1 RGB."""
+ rgba = np.asarray(effective_rgba(m, g)[:3], float)
+ t = _texid(m, g)
+ if t < 0:
+ return rgba
+ h, w, c = m.tex_height[t], m.tex_width[t], m.tex_nchannel[t]
+ px = m.tex_data[m.tex_adr[t]:m.tex_adr[t] + h * w * c].reshape(-1, c)[:, :3]
+ return rgba * (px.mean(0) / 255.0)
+
+
+SPARE = "_ro_cam" # the renderers' own spare cameras (renderers/mujoco), posed per frame: not scene cameras
+
+
+def _scene_cams(m):
+ return [i for i in range(m.ncam) if not (m.camera(i).name or "").startswith(SPARE)]
+
+
+def same_scene(m0, m1) -> list:
+ """Differences between the default model m0 and the renderer's model m1 (empty list = the same scene)."""
+ bad = []
+ c0, c1 = _scene_cams(m0), _scene_cams(m1)
+ for name in SAME:
+ a, b = np.asarray(getattr(m0, name)), np.asarray(getattr(m1, name))
+ if name.startswith("cam_"):
+ a, b = a[c0], b[c1]
+ elif name == "ncam":
+ a, b = np.asarray(len(c0)), np.asarray(len(c1))
+ if np.shape(a) != np.shape(b) or not np.array_equal(a, b):
+ bad.append(name)
+ if bad:
+ return bad
+ if m0.vis.global_.fovy != m1.vis.global_.fovy:
+ bad.append("vis.global.fovy")
+ for g in range(m0.ngeom):
+ t0, t1 = _texid(m0, g) >= 0, _texid(m1, g) >= 0
+ if not t0 and not t1:
+ if not np.allclose(effective_rgba(m0, g), effective_rgba(m1, g)):
+ bad.append(f"colour of geom {m0.geom(g).name or g}")
+ elif float(np.abs(_mean_colour(m0, g) - _mean_colour(m1, g)).max()) > TEXTURE_TOL:
+ bad.append(f"mean colour of textured geom {m0.geom(g).name or g}")
+ return bad
+
+
+# ------------------------------------------------------------------------------------- presentation scenes (spectators)
+VISUAL_PREFIX = "_vis:" # the name prefix of a presentation scene's added geoms (renderers/presentation.py)
+KINEMATICS = ("nq", "nv", "nu", "nbody", "njnt", "nmocap", "nsite", "qpos0",
+ "body_parentid", "body_rootid", "body_weldid", "body_mocapid", "body_jntnum", "body_jntadr",
+ "body_dofnum", "body_dofadr", "body_pos", "body_quat", "body_ipos", "body_iquat", "body_mass",
+ "body_inertia", "jnt_type", "jnt_bodyid", "jnt_qposadr", "jnt_dofadr", "jnt_pos", "jnt_axis",
+ "jnt_range", "dof_bodyid", "dof_jntid", "dof_armature", "dof_damping", "actuator_trnid",
+ "site_bodyid", "site_pos", "site_quat", "opt.timestep", "opt.gravity")
+MATCH_GEOM = ("geom_type", "geom_bodyid", "geom_size", "geom_pos", "geom_quat", "geom_contype", "geom_conaffinity",
+ "geom_condim", "geom_priority", "geom_friction", "geom_solref", "geom_solimp", "geom_margin", "geom_gap")
+CAMERA = ("cam_mode", "cam_bodyid", "cam_pos", "cam_quat", "cam_fovy")
+
+
+def _arr(m, name):
+ o = m
+ for part in name.split("."):
+ o = getattr(o, part)
+ return np.asarray(o)
+
+
+def visual_geoms(m) -> list:
+ return [g for g in range(m.ngeom) if (m.geom(g).name or "").startswith(VISUAL_PREFIX)]
+
+
+def _mesh_verts(m, g):
+ i = m.geom_dataid[g]
+ return m.mesh_vert[m.mesh_vertadr[i]:m.mesh_vertadr[i] + m.mesh_vertnum[i]]
+
+
+def same_kinematics(m0, m1) -> list:
+ """Differences between the match model m0 and a presentation model m1 (empty list = the same kinematics):
+ every body, joint, dof, frame, inertia, site, mocap body and scene camera is identical; m0's geoms are all in m1,
+ in the same order, with the same geometry, pose and contact properties (only their appearance may change:
+ group, colour, material, e.g. a collision mesh moved to the hidden group 3); every other geom of m1 is an added
+ visual geom (name prefix VISUAL_PREFIX) that never collides (contype = conaffinity = 0) and is drawn (group
+ 0..2). Body masses and inertias being equal, the added geoms carry no mass. So the same qpos puts every body at
+ the same pose in both models: a presentation scene changes only what a spectator sees."""
+ bad = []
+ for name in KINEMATICS:
+ a, b = _arr(m0, name), _arr(m1, name)
+ if a.shape != b.shape or not np.array_equal(a, b):
+ bad.append(name)
+ c0, c1 = _scene_cams(m0), _scene_cams(m1)
+ if len(c0) != len(c1):
+ bad.append("ncam")
+ else:
+ bad += [n for n in CAMERA if not np.array_equal(_arr(m0, n)[c0], _arr(m1, n)[c1])]
+ if bad:
+ return bad
+ extra = visual_geoms(m1)
+ keep = [g for g in range(m1.ngeom) if g not in set(extra)]
+ if len(keep) != m0.ngeom:
+ return [f"{len(keep)} match geoms in the presentation scene for {m0.ngeom}"]
+ bad += [n for n in MATCH_GEOM if not np.array_equal(_arr(m0, n), _arr(m1, n)[keep])]
+ for g0, g1 in enumerate(keep):
+ if (m0.geom(g0).name or "") != (m1.geom(g1).name or ""):
+ bad.append(f"name of geom {g0}")
+ elif m0.geom_dataid[g0] >= 0 and m0.geom_type[g0] == MESH and not np.array_equal(_mesh_verts(m0, g0),
+ _mesh_verts(m1, g1)):
+ bad.append(f"mesh of geom {m0.geom(g0).name or g0}")
+ for g in extra:
+ if m1.geom_contype[g] or m1.geom_conaffinity[g] or not 0 <= m1.geom_group[g] <= 2:
+ bad.append(f"added geom {m1.geom(g).name} collides or is not drawn")
+ return bad
+
+
+def pose_diff(m0, m1, states) -> float:
+ """The largest difference of any body's (and site's) world position or orientation between the two models over
+ the given states ({"qpos", optional "mocap_pos", "mocap_quat"}); 0.0 = bit-identical poses."""
+ import mujoco as mj
+ d0, d1 = mj.MjData(m0), mj.MjData(m1)
+ worst = 0.0
+ for st in states:
+ for m, d in ((m0, d0), (m1, d1)):
+ d.qpos[:] = np.asarray(st["qpos"], float)
+ if m.nmocap and "mocap_pos" in st:
+ d.mocap_pos[:] = np.asarray(st["mocap_pos"], float).reshape(m.nmocap, 3)
+ if m.nmocap and "mocap_quat" in st:
+ d.mocap_quat[:] = np.asarray(st["mocap_quat"], float).reshape(m.nmocap, 4)
+ mj.mj_kinematics(m, d)
+ for a, b in ((d0.xpos, d1.xpos), (d0.xquat, d1.xquat), (d0.xmat, d1.xmat), (d0.site_xpos, d1.site_xpos)):
+ if np.asarray(a).size:
+ worst = max(worst, float(np.abs(np.asarray(a) - np.asarray(b)).max()))
+ return worst
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/server.py b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/server.py
new file mode 100644
index 0000000000..5eb03f3410
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/server.py
@@ -0,0 +1,30 @@
+"""eai-standard/2.3 sim service for RoboOlympics: rcb_realtime.py (the sidecar's entry point, `python /srv/rcb_realtime.py`)
+imports this module and calls build(). The sport and its frozen instance come from environment/docker-compose.yaml:
+ RO_PLUGIN the sport's plugin (/srv/sport/plugin.py)
+ RO_FORMAT the sport's format (match: one player against the scripted opponent)
+ RO_SEED the frozen instance's seed (serves, the opponent's returns, the execution scatter)
+ RO_LEVEL the scripted opponent's level
+ RO_ACTION_LEVEL the action level (high: strokes the service plans; low: joint or mallet targets)
+ RO_TASK_TEXT, RO_EPISODE_TEXT one sentence each for /spec
+ RCB_SLOWDOWN the slowdown S (badminton's stroke lead depends on it); RCB_DATA, RCB_RESET_BUDGET,
+ RCB_WALL_CLOCK_S: the service's own (rcb_service.main)
+"""
+from __future__ import annotations
+
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from core.sport import MatchConfig # noqa: E402
+from rcb_olympics import Olympics # noqa: E402
+
+
+def build() -> Olympics:
+ env = os.environ.get
+ plugin = env("RO_PLUGIN", "/srv/sport/plugin.py")
+ sport = os.path.basename(os.path.dirname(os.path.abspath(plugin)))
+ cfg = MatchConfig(sport=env("RO_SPORT", sport), format=env("RO_FORMAT", "match"), seats=("A",),
+ seed=int(env("RO_SEED", "101")), first="A", slowdown=float(env("RCB_SLOWDOWN") or 10),
+ level=int(env("RO_LEVEL", "1")), action_level=env("RO_ACTION_LEVEL", "high"), play="program")
+ return Olympics(plugin, cfg, data=env("RCB_DATA", "/data"), task_text=env("RO_TASK_TEXT", ""),
+ episode_text=env("RO_EPISODE_TEXT", ""))
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/sport/hockey.py b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/sport/hockey.py
new file mode 100644
index 0000000000..b1a3a13db3
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/sport/hockey.py
@@ -0,0 +1,387 @@
+"""Two physical 7-axis iiwa arms on an air hockey table: fixed-step Cartesian execution and the referee.
+
+Robot dynamics are derived from AirHockeyChallenge (MIT, see scene/). The table is new and mesh-free. The referee
+follows the USAA Official Rules of Air Hockey (sport.toml [rulebook]) with the deviations listed there
+([[deviations]]): one game to 7 points, the seven-second rule (a foul: the puck goes to the opponent), dead-puck
+face-offs, a safety cap on the playing time with a stated last resort (no draws) and a 0.35 m goal mouth (D10).
+"""
+from __future__ import annotations
+
+import hashlib
+import json
+import math
+import os
+from pathlib import Path
+import xml.etree.ElementTree as ET
+
+import mujoco
+import numpy as np
+
+REVISION = 'airhockey-program-v4' # v4 (2026-10-08, review item B13): goal mouth 0.35 m (v3: 0.40 m, v2: 0.25 m)
+DT, PHYSICS_DT = .01, .001 # 10 ms control step (eai-standard-realtime/1.0), 1 kHz physics
+SUBSTEPS = round(DT / PHYSICS_DT)
+POINTS_TO_WIN = 7 # USAA I.1
+SEVEN_S = 7. # USAA I.10: seven seconds to shoot the puck across the centre line
+DEAD_S = 2. # dead puck: out of both robots' reach this long -> face-off
+LINE_S = 7. # dead puck: resting on the centre line this long -> face-off
+CAP_S = 120. # safety cap: at most this much playing time (game seconds) ...
+MAX_RALLIES = 40 # ... and at most this many rallies; then the last resort decides
+CAM_W, CAM_H = 320, 240
+LENGTH, WIDTH = 1.948, 1.038
+GOAL_DEFAULT = .35 # sport.toml deviation D10 (the AirHockeyChallenge table: .25)
+
+
+def goal_width():
+ """The goal mouth (m): GOAL_DEFAULT, or the experiment-only override RO_AIRHOCKEY_GOAL_M (0.2-0.6; the official
+ tasks never set it; plugin.REVISION and final.json record a non-default width)."""
+ v = os.environ.get('RO_AIRHOCKEY_GOAL_M', '').strip()
+ if not v: return GOAL_DEFAULT
+ g = float(v)
+ if not (math.isfinite(g) and .2 <= g <= .6): raise ValueError('RO_AIRHOCKEY_GOAL_M must be within 0.2-0.6 m')
+ return g
+
+
+GOAL = goal_width()
+PUCK_R, MALLET_R = .03165, .04815
+CONTACT = PUCK_R + MALLET_R
+PUCK_DAMPING = '.001' # N s/m on the 10 g puck: the air cushion's drag (about 10 % speed per second)
+BASE_X = 1.51 # robot bases at x = -1.51 (A) and +1.51 (B), y = 0
+REACH = 1.45 # mallet centre at most this far from its robot's base
+X_NEAR, X_FAR, Y_MAX = .05, .92, .47 # mallet centre workspace in its own half: X_NEAR <= |x| <= X_FAR, |y| <= Y_MAX
+HOME_X, SPOT_X = .82, .58 # mallet home and the puck's placement spot (|x|), in the own half
+MAX_SPEED, MAX_ACCEL = 2., 10. # the mallet's Cartesian trajectory limits (m/s, m/s^2)
+LEVELS = { # the scripted opponent (seat B of the single-player game): mallet
+ 1: dict(speed=.4, delay=15, guard=None, gain=0., tol=.25, aim=0., lead=False), # speed cap m/s, reaction delay
+ 2: dict(speed=.6, delay=10, guard=.80, gain=1., tol=.15, aim=0., lead=False), # steps, guard line |x| m, gain
+ 3: dict(speed=1., delay=6, guard=.80, gain=1., tol=.08, aim=.07, lead=False), # on the puck's y, line-up
+ 4: dict(speed=2., delay=3, guard=.80, gain=1., tol=.05, aim=.08, lead=True)} # tolerance rad, aim (y at the
+ # goal), crossing prediction
+SCENE = Path(__file__).with_name('scene')
+OWN = {'A': -1., 'B': 1.} # the sign of x in each seat's own half
+OTHER = {'A': 'B', 'B': 'A'}
+
+
+def source_sha():
+ h = hashlib.sha256(Path(__file__).read_bytes())
+ for f in sorted(SCENE.glob('*.xml')):
+ h.update(f.name.encode()); h.update(f.read_bytes())
+ return h.hexdigest()
+
+
+def scene_xml(seed=101):
+ root = ET.Element('mujoco', model='visual_iiwa_airhockey')
+ ET.SubElement(root, 'compiler', angle='radian', autolimits='true')
+ ET.SubElement(root, 'option', timestep=str(PHYSICS_DT), integrator='implicitfast', cone='elliptic', iterations='40')
+ visual = ET.SubElement(root, 'visual'); ET.SubElement(visual, 'global', offwidth='640', offheight='480')
+ ET.SubElement(visual, 'headlight', ambient='.5 .5 .5', diffuse='.5 .5 .5')
+ world = ET.SubElement(root, 'worldbody')
+ ET.SubElement(world, 'light', pos='0 0 3', dir='0 0 -1', directional='true', castshadow='false')
+ ET.SubElement(world, 'geom', name='table_surface', type='box', pos='0 0 -.045', size='1.07 .61 .045', rgba='.9 .92 .94 1', contype='0', conaffinity='0')
+ ET.SubElement(world, 'geom', name='floor', type='plane', pos='0 0 -.15', size='4 4 .1', rgba='.16 .2 .24 1', contype='0', conaffinity='0')
+ for side in (-1, 1):
+ ET.SubElement(world, 'geom', name=f'wall_side_{side}', type='box', pos=f'0 {side*(WIDTH/2+.025)} .035', size='1.07 .025 .035', rgba='.2 .25 .3 1', friction='0 0 0', solref='.0075 .1', solimp='.99 .999 .001')
+ for end in (-1, 1):
+ half = (WIDTH-GOAL)/4
+ ET.SubElement(world, 'geom', name=f'wall_end_{side}_{end}', type='box', pos=f'{end*(LENGTH/2+.025)} {side*(GOAL/2+half)} .035', size=f'.025 {half} .035', rgba='.2 .25 .3 1', friction='0 0 0', solref='.0075 .1', solimp='.99 .999 .001')
+ # Four public calibration markers outside the puck lane, plus a center line.
+ for i, (x, y) in enumerate([(-.9, -.46), (-.9, .46), (.9, -.46), (.9, .46)]):
+ ET.SubElement(world, 'geom', type='cylinder', pos=f'{x} {y} .001', size='.015 .001', rgba='1 .75 .03 1', contype='0', conaffinity='0')
+ ET.SubElement(world, 'geom', type='box', pos='0 0 .001', size='.002 .5 .001', rgba='.7 .72 .75 1', contype='0', conaffinity='0')
+ base = ET.SubElement(world, 'body', name='puck_base')
+ for name, kind, axis, damping in [('puck_x', 'slide', '1 0 0', PUCK_DAMPING), ('puck_y', 'slide', '0 1 0', PUCK_DAMPING), ('puck_yaw', 'hinge', '0 0 1', '0.000002')]:
+ ET.SubElement(base, 'joint', name=name, type=kind, axis=axis, damping=damping, limited='false')
+ ET.SubElement(base, 'inertial', pos='0 0 0', mass='.01', diaginertia='0.0000025 0.0000025 0.000005')
+ ET.SubElement(base, 'geom', name='puck', type='cylinder', pos='0 0 .012', size=f'{PUCK_R} .01', rgba='.95 .03 .04 1', friction='0 0 0', condim='4', solref='.0075 .1')
+ for seat, pos, axes in [('A', '0 -1.3 2.2', '1 0 0 0 .861 .509'), ('B', '0 1.3 2.2', '-1 0 0 0 -.861 .509')]:
+ ET.SubElement(world, 'camera', name=f'front_{seat}', pos=pos, xyaxes=axes, fovy='48')
+ ET.SubElement(world, 'camera', name='overview', pos='0 -2.3 2.5', xyaxes='1 0 0 0 .736 .677', fovy='55')
+ # Merge upstream robot defaults/world/actuators without any external assets.
+ for i in (1, 2):
+ robot = ET.parse(SCENE/f'iiwa{i}.xml').getroot()
+ for child in robot:
+ if child.tag == 'compiler': continue
+ if child.tag == 'worldbody':
+ for body in child: world.append(body)
+ elif child.tag == 'default':
+ if i == 1: root.append(child) # iiwa1.xml declares the shared classes (vis, robot)
+ elif child.tag == 'actuator':
+ acts = root.find('actuator')
+ if acts is None: acts = ET.SubElement(root, 'actuator')
+ for act in child: acts.append(act)
+ return ET.tostring(root, encoding='unicode')
+
+
+def workspace(seat, xy):
+ """The nearest point of the seat's mallet workspace (own half, X_NEAR <= |x| <= X_FAR, |y| <= Y_MAX, at most
+ REACH from its robot's base) to a point (approximately: box clip, then radial clip towards the base)."""
+ u, v = OWN[seat]*float(xy[0]), float(xy[1])
+ u, v = min(max(u, X_NEAR), X_FAR), min(max(v, -Y_MAX), Y_MAX)
+ d = math.hypot(BASE_X-u, v)
+ if d > REACH:
+ u, v = BASE_X-(BASE_X-u)*REACH/d, v*REACH/d
+ return [OWN[seat]*u, v]
+
+
+def reachable(seat, p):
+ """Whether the seat's mallet can touch a puck centred at p (a mallet centre in the workspace within CONTACT)."""
+ q = workspace(seat, p)
+ return math.hypot(float(p[0])-q[0], float(p[1])-q[1]) <= CONTACT-.005
+
+
+def in_workspace(seat, xy, eps=1e-4):
+ u, v = OWN[seat]*float(xy[0]), float(xy[1])
+ return X_NEAR-eps <= u <= X_FAR+eps and abs(v) <= Y_MAX+eps and math.hypot(BASE_X-u, v) <= REACH+eps
+
+
+def validate_action(body, seat):
+ """None for `none`; else the target [x, y]. Non-finite, wrong half or outside the workspace -> ValueError (400)."""
+ if body.get('type') == 'none': return None
+ if body.get('type', 'target') != 'target': raise ValueError('action type must be target or none')
+ values = [body.get('x'), body.get('y')]
+ if any(type(v) not in (int, float) or not math.isfinite(v) for v in values): raise ValueError('x,y must be finite numbers')
+ if seat not in ('A', 'B'): raise ValueError('unknown seat')
+ if OWN[seat]*values[0] <= 0: raise ValueError('mallet must stay in own half')
+ if not in_workspace(seat, values):
+ raise ValueError(f'target outside the mallet workspace ({X_NEAR} <= |x| <= {X_FAR}, |y| <= {Y_MAX}, '
+ f'at most {REACH} m from the robot base at ({OWN[seat]*BASE_X:+.2f}, 0))')
+ return [float(v) for v in values]
+
+
+class Hockey:
+ def __init__(self, seed=101, level=1, duel=False, first='A'):
+ if level not in (1, 2, 3, 4) or first not in ('A', 'B'): raise ValueError('invalid configuration')
+ self.seed, self.level, self.duel, self.first = seed, level, duel, first
+ self.source_sha = source_sha(); self.model = mujoco.MjModel.from_xml_string(scene_xml())
+ self.data = mujoco.MjData(self.model); self.ik = mujoco.MjData(self.model)
+ self.rng = np.random.default_rng(seed)
+ self.k = 0 # control steps of play (the world's clock; frozen time does not count)
+ self.point_k = 0 # control steps since the current point started
+ self.results = [] # one entry per rally: how it ended (goal, foul, dead puck, time cap)
+ self.done = self.awaiting_review = False
+ self.decided_by = None # 'score' | 'cap_points' | 'cap_last_goal' | 'cap_territory' | 'cap_first_possession'
+ self.rail_contact_steps = self.contact_steps = 0
+ self.half_steps = {'A': 0, 'B': 0} # steps the puck spent wholly in each half (the cap's territory measure)
+ self.ids = {}; self.qadr = {}; self.dadr = {}; self.acts = {}; self.targets = {}
+ for s, n in [('A', 1), ('B', 2)]:
+ names = [f'iiwa_{n}/joint_{j}' for j in range(1, 8)]+[f'iiwa_{n}/striker_joint_{j}' for j in (1, 2)]
+ self.ids[s] = [self.model.joint(name).id for name in names]
+ self.qadr[s] = self.model.jnt_qposadr[self.ids[s]]; self.dadr[s] = self.model.jnt_dofadr[self.ids[s]]
+ self.acts[s] = [self.model.actuator(name).id for name in names]
+ self.ee = {'A': self.model.geom('iiwa_1/ee').id, 'B': self.model.geom('iiwa_2/ee').id}
+ self.mallet_body = {'A': self.model.body('iiwa_1/striker_mallet').id, 'B': self.model.body('iiwa_2/striker_mallet').id}
+ self.puck_geom = self.model.geom('puck').id
+ self.wall_geoms = {i for i in range(self.model.ngeom) if (self.model.geom(i).name or '').startswith('wall_')}
+ self.px = int(self.model.jnt_qposadr[self.model.joint('puck_x').id]); self.py = self.px+1
+ self.pvx = int(self.model.jnt_dofadr[self.model.joint('puck_x').id])
+ mujoco.mj_resetData(self.model, self.data)
+ self.restart(self.first, 'start')
+
+ # ---------------------------------------------------------------- state
+ def position(self, seat): return self.data.geom_xpos[self.ee[seat]].copy()
+
+ def puck(self): return np.array([self.data.qpos[self.px], self.data.qpos[self.py]])
+
+ def puck_velocity(self): return np.array([self.data.qvel[self.pvx], self.data.qvel[self.pvx+1]])
+
+ def restart(self, holder, why):
+ """Play stops: both mallets go back to their home positions (instantly) and the referee places the puck at
+ rest, at the holder's spot in its own half (seeded y), or at the table centre for a face-off (holder None)."""
+ puck = [0., 0.] if holder is None else [OWN[holder]*SPOT_X, round(float(self.rng.uniform(-.18, .18)), 6)]
+ self.data.qvel[:] = 0
+ for s in ('A', 'B'):
+ self.data.qpos[self.qadr[s]] = np.array([0, -.1961, 0, -1.8436, 0, .9704, 0, 0, 0.])
+ self.data.qpos[self.px], self.data.qpos[self.py], self.data.qpos[self.py+1] = puck[0], puck[1], 0.
+ mujoco.mj_forward(self.model, self.data)
+ for s in ('A', 'B'):
+ self.targets[s] = np.array([OWN[s]*HOME_X, 0.])
+ self.data.qpos[self.qadr[s]] = self.solve(s, self.data.qpos[self.qadr[s]].copy(), self.targets[s], 80)
+ self.data.ctrl[:] = 0
+ self.commands = {s: list(self.targets[s]) for s in ('A', 'B')}
+ self.qtarget = {s: self.data.qpos[self.qadr[s]].copy() for s in ('A', 'B')}
+ self.cart_velocity = {s: np.zeros(2) for s in ('A', 'B')}
+ self.side, self.side_steps = holder, 0 # possession: the half the puck is wholly in
+ self.line_steps = self.dead_steps = 0
+ self.last_touch = None
+ self.script = dict(until=-1, target=None, hist=[])
+ self.restart_k, self.restart_why = self.k, why
+ mujoco.mj_forward(self.model, self.data)
+
+ def solve(self, seat, q, target, iterations):
+ adr = self.qadr[seat]; dof = self.dadr[seat]
+ desired = np.diag([-1., 1., -1.]) if seat == 'A' else np.diag([1., -1., -1.])
+ body = self.mallet_body[seat]
+ jp = np.zeros((3, self.model.nv)); jr = np.zeros_like(jp)
+ self.ik.qpos[:] = self.data.qpos
+ ranges = self.model.jnt_range[self.ids[seat]]
+ for _ in range(iterations):
+ self.ik.qpos[adr] = q; mujoco.mj_kinematics(self.model, self.ik); mujoco.mj_comPos(self.model, self.ik)
+ current = self.ik.xmat[body].reshape(3, 3)
+ err = np.r_[np.array([target[0], target[1], .0645])-self.ik.xpos[body],
+ sum(np.cross(current[:, i], desired[:, i]) for i in range(3))*.5]
+ mujoco.mj_jacBody(self.model, self.ik, jp, jr, body)
+ jac = np.vstack([jp[:, dof], jr[:, dof]])
+ delta = [email protected]([email protected]+.001*np.eye(6), err)
+ q = q+np.clip(delta, -.08, .08)
+ q = np.clip(q, ranges[:, 0]+.01, ranges[:, 1]-.01)
+ return q
+
+ def set_command(self, seat, command):
+ if command is None: self.commands[seat] = workspace(seat, self.position(seat)[:2]); return
+ if OWN[seat]*command[0] <= 0: raise ValueError('mallet must stay in own half')
+ self.commands[seat] = list(command)
+
+ # ---------------------------------------------------------------- scripted opponent (single player, seat B)
+ def scripted(self, seat='B'):
+ """Trusted referee-side opponent, from the true puck position `delay` steps ago: guards its goal while the
+ puck is in the other half or coming at it fast, else lines up behind the puck and strikes it at the other
+ goal. Levels differ in mallet speed, reaction delay, how far the guard follows the puck, how precisely it lines
+ up and where it aims (LEVELS)."""
+ lv = LEVELS[self.level]; sg = OWN[seat]; sc = self.script
+ sc['hist'].append(self.puck()); sc['hist'] = sc['hist'][-(lv['delay']+2):]
+ P = sc['hist'][0]; W = (sc['hist'][1]-sc['hist'][0])/DT if len(sc['hist']) > 1 else np.zeros(2)
+ p = np.array([sg*P[0], P[1]]); w = np.array([sg*W[0], W[1]]) # local: u > 0 is the own half
+ m = self.position(seat)[:2]; m = np.array([sg*m[0], m[1]])
+ p = p+w*lv['delay']*DT # now, by its own extrapolation
+ world = lambda u, v: workspace(seat, [sg*u, v])
+ if p[0] < -.02 or w[0] > .15: # guard: at its guard line, following the puck's y (or its crossing)
+ sc['until'] = -1
+ if lv['guard'] is None: # level 1 does not guard: it stays where it is
+ return world(*m)
+ y = p[1]
+ if lv['lead'] and w[0] > .1:
+ y = p[1]+w[1]*(lv['guard']-p[0])/w[0]
+ r = WIDTH/2-PUCK_R; y = (y+r) % (4*r); y = (y if y < 2*r else 4*r-y)-r # rail bounces folded in
+ return world(lv['guard'], float(np.clip(y*lv['gain'], -.42, .42)))
+ if self.k < sc['until']: return sc['target']
+ aim = 0. if not lv['aim'] else (lv['aim'] if p[1] < 0 else -lv['aim']) # the far corner of the goal
+ d = np.array([-1.05, aim])-p; d /= np.linalg.norm(d)
+ rel = p-m; dist = np.linalg.norm(rel)
+ if .12 < dist < .3 and float(rel@d)/dist > math.cos(lv['tol']): # lined up: strike through the puck
+ sc['target'] = world(*(m+rel/dist*(dist+.25))); sc['until'] = self.k+40
+ return sc['target']
+ return world(*(p-d*.18))
+
+ # ---------------------------------------------------------------- one control step
+ def step(self):
+ if self.done or self.awaiting_review: raise RuntimeError('world frozen')
+ if not self.duel: self.set_command('B', self.scripted('B'))
+ qvelocity = {}; qprevious = {}
+ for s in ('A', 'B'):
+ previous_q = self.qtarget[s].copy(); qprevious[s] = previous_q
+ target = np.array(self.commands[s]); delta = target-self.targets[s]
+ vmax = MAX_SPEED if s == 'A' or self.duel else LEVELS[self.level]['speed']
+ accel = 80*delta-18*self.cart_velocity[s]
+ accel *= min(1., MAX_ACCEL/max(1e-9, np.linalg.norm(accel)))
+ self.cart_velocity[s] += accel*DT
+ self.cart_velocity[s] *= min(1., vmax/max(1e-9, np.linalg.norm(self.cart_velocity[s])))
+ self.targets[s] += self.cart_velocity[s]*DT
+ self.qtarget[s] = self.solve(s, self.qtarget[s], self.targets[s], 4)
+ qvelocity[s] = np.clip((self.qtarget[s]-previous_q)/DT, -3., 3.)
+ contact = set()
+ mass = np.zeros((self.model.nv, self.model.nv))
+ for substep in range(SUBSTEPS):
+ mujoco.mj_forward(self.model, self.data)
+ mujoco.mj_fullM(self.model, mass, self.data.qM)
+ for s in ('A', 'B'):
+ q = self.data.qpos[self.qadr[s]]; v = self.data.qvel[self.dadr[s]]
+ reference = qprevious[s]+(self.qtarget[s]-qprevious[s])*(substep+1)/SUBSTEPS
+ acceleration = np.clip(100*(reference-q)+20*(qvelocity[s]-v), -50, 50)
+ torque = mass[np.ix_(self.dadr[s], self.dadr[s])]@acceleration+self.data.qfrc_bias[self.dadr[s]]
+ bounds = self.model.actuator_ctrlrange[self.acts[s]]
+ self.data.ctrl[self.acts[s]] = np.clip(torque, bounds[:, 0], bounds[:, 1])
+ mujoco.mj_step(self.model, self.data)
+ for i in range(self.data.ncon):
+ c = self.data.contact[i]; g = (int(c.geom1), int(c.geom2))
+ if self.puck_geom in g:
+ for s in ('A', 'B'):
+ if self.ee[s] in g: contact.add(s)
+ if g[0] in self.wall_geoms or g[1] in self.wall_geoms: contact.add('wall')
+ self.k += 1; self.point_k += 1
+ for s in ('A', 'B'):
+ if s in contact: self.last_touch = s
+ if contact & {'A', 'B'}: self.contact_steps += 1
+ if 'wall' in contact: self.rail_contact_steps += 1
+ self.referee()
+ return contact
+
+ def referee(self):
+ """After each control step: a goal, a seven-second foul or a dead puck ends the rally; the world then freezes
+ for the review and the next rally starts from the placement the rules give (ready())."""
+ p = self.puck()
+ if abs(p[0]) > LENGTH/2+PUCK_R and abs(p[1]) <= GOAL/2-PUCK_R: # wholly in a goal (USAA I.2, V.1)
+ scorer = 'A' if p[0] > 0 else 'B'
+ return self.end_rally('goal', winner=scorer, next=OTHER[scorer], # the scored-upon serves (I.4)
+ own_goal=self.last_touch == OTHER[scorer])
+ side = 'A' if p[0] < -PUCK_R else ('B' if p[0] > PUCK_R else None) # on the centre line: nobody's (I.11)
+ if side:
+ self.half_steps[side] += 1
+ self.line_steps = 0
+ if side != self.side: self.side, self.side_steps = side, 0
+ self.side_steps += 1
+ else:
+ self.line_steps += 1
+ self.dead_steps = 0 if (reachable('A', p) or reachable('B', p)) else self.dead_steps+1
+ if self.dead_steps*DT >= DEAD_S-1e-9:
+ return self.end_rally('dead_puck', where='out_of_reach', next=None)
+ if self.line_steps*DT >= LINE_S-1e-9:
+ return self.end_rally('dead_puck', where='centre_line', next=None)
+ if side and self.side_steps*DT >= SEVEN_S-1e-9: # a foul: forfeiture of the puck (VI.1)
+ return self.end_rally('seven_second_foul', guilty=side, next=OTHER[side])
+ if self.k*DT >= CAP_S-1e-9:
+ return self.end_rally('time_cap', next=None)
+
+ def end_rally(self, how, winner=None, guilty=None, next=None, **extra):
+ self.results.append(dict(rally=len(self.results)+1, how=how, winner=winner, guilty=guilty,
+ next='faceoff' if next is None else next, k=self.k, steps=self.point_k, **extra))
+ sc = self.scores()
+ if max(sc['A']['points'], sc['B']['points']) >= POINTS_TO_WIN:
+ self.done, self.decided_by = True, 'score'
+ elif how == 'time_cap' or self.k*DT >= CAP_S-1e-9 or len(self.results) >= MAX_RALLIES:
+ self.done, self.decided_by = True, self.cap_decision()
+ else:
+ self.awaiting_review = True
+
+ def cap_decision(self):
+ sc = self.scores(); a, b = sc['A']['points'], sc['B']['points']
+ if a != b: return 'cap_points'
+ if any(r['how'] == 'goal' for r in self.results): return 'cap_last_goal'
+ if self.half_steps['A'] != self.half_steps['B']: return 'cap_territory'
+ return 'cap_first_possession'
+
+ def ready(self):
+ if not self.awaiting_review: raise ValueError('not in review')
+ self.awaiting_review = False; self.point_k = 0
+ nxt = self.results[-1]['next']
+ self.restart(None if nxt == 'faceoff' else nxt, self.results[-1]['how'])
+
+ # ---------------------------------------------------------------- result
+ def scores(self):
+ return {s: dict(points=sum(r['how'] == 'goal' and r['winner'] == s for r in self.results),
+ fouls=sum(r['guilty'] == s for r in self.results)) for s in ('A', 'B')}
+
+ def winner(self):
+ """'A' or 'B' once the game is over (never a draw), else None."""
+ if not self.done: return None
+ sc = self.scores(); a, b = sc['A']['points'], sc['B']['points']
+ if a != b: return 'A' if a > b else 'B'
+ goals = [r for r in self.results if r['how'] == 'goal']
+ if goals: return goals[-1]['winner'] # the winner of the last point
+ if self.half_steps['A'] != self.half_steps['B']: # 0:0: less time with the puck in
+ return 'A' if self.half_steps['A'] < self.half_steps['B'] else 'B' # one's own half (more pressure)
+ return OTHER[self.first] # identical: the player who did not have the first possession
+
+ def digest(self):
+ state = np.empty(mujoco.mj_stateSize(self.model, mujoco.mjtState.mjSTATE_INTEGRATION))
+ mujoco.mj_getState(self.model, self.data, state, mujoco.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha256(state.tobytes())
+ h.update(json.dumps(dict(k=self.k, point_k=self.point_k, results=self.results,
+ commands=self.commands, targets={s: t.tolist() for s, t in self.targets.items()},
+ cart_velocity={s: t.tolist() for s, t in self.cart_velocity.items()},
+ qtarget={s: q.tolist() for s, q in self.qtarget.items()}, side=self.side,
+ side_steps=self.side_steps, line_steps=self.line_steps, dead_steps=self.dead_steps,
+ half_steps=self.half_steps, last_touch=self.last_touch, rng=self.rng.bit_generator.state,
+ script=dict(until=self.script['until'], target=self.script['target'],
+ hist=[x.tolist() for x in self.script['hist']]),
+ contacts=self.contact_steps, rails=self.rail_contact_steps, done=self.done,
+ decided_by=self.decided_by, awaiting_review=self.awaiting_review), sort_keys=True).encode())
+ return h.hexdigest()
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/sport/plugin.py b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/sport/plugin.py
new file mode 100644
index 0000000000..126bbaae02
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/sport/plugin.py
@@ -0,0 +1,241 @@
+"""airhockey: robot air hockey after the USAA rules on the v0.2 core (docs/framework_zh.md §4.2). Migrated from the
+legacy tree (scripts/olympiad/airhockey, scripts/olympiad/shared/airhockey/sim) in stage 2; the simulator hockey.py
+(two physically simulated KUKA iiwa arms with mallets, the Cartesian path, IK and torque controller, the puck, the
+referee and the scripted opponent) and its robot files (scene/) are the legacy ones except the goal mouth, 0.35 m
+since revision v4 (sport.toml D10; v3: 0.40 m; the legacy recordings of revision v2 no longer replay, golden/ holds
+native recordings). The four groups of contract ② (core/sport.py):
+
+ world hockey.Hockey: one table, both arms in one MuJoCo world (physics 1 kHz); one control step (10 ms) =
+ Hockey.step(): both arms' Cartesian paths, IK and joint torques, the scripted opponent (format match,
+ seat B inside the world) and the referee after the step
+ actions low only: {"type": "target", x, y} (the mallet's target in the own workspace, hockey.validate_action)
+ or {"type": "none"} (hold where the mallet is) -> Hockey.set_command, at the next control step
+ referee a unit = a rally (a goal, a seven-second foul or a dead puck ends it; the world freezes for the reviews);
+ first to 7 goals, else the safety cap (120 s of play or 40 rallies) and Hockey.winner()'s chain:
+ goals -> the last goal -> territory -> the player who did not have the first possession
+ observation observe = the seat's own arm and mallet and the referee's calls (score, rallies; no puck or opponent
+ coordinate); cameras = the seat's fixed camera above and behind its end (the legacy front_<seat>),
+ drawn by the task's renderer from scene() (hockey.scene_xml) and render_state() (the qpos)
+"""
+from __future__ import annotations
+
+import os
+
+import numpy as np
+
+import hockey as H
+from core.sport import FINISHED, PLAYING, UNIT_OVER, LowLayer, MatchBase, Phase, Refused, check_command
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+REVISION = "airhockey-program-v4+players-25k+core-0.2" + ("" if H.GOAL == H.GOAL_DEFAULT else f"+goal{H.GOAL:g}m") # experiment knob
+NUM = {"type": "number"}
+SCHEMA = {
+ "target": {"x": {**NUM, "min": -H.X_FAR, "max": H.X_FAR, "unit": "m",
+ "doc": f"the mallet centre's target x (world frame); own half only: {H.X_NEAR} <= |x| <= {H.X_FAR}"},
+ "y": {**NUM, "min": -H.Y_MAX, "max": H.Y_MAX, "unit": "m",
+ "doc": f"target y; |y| <= {H.Y_MAX} and at most {H.REACH} m from your robot's base"}},
+ "none": {}}
+TIEBREAKS = ("goals", "last_goal", "territory", "first_possession")
+LEGACY_DECIDED = {"score": "goals", "cap_points": "goals", "cap_last_goal": "last_goal",
+ "cap_territory": "territory", "cap_first_possession": "first_possession"}
+CAM = {"width": H.CAM_W, "height": H.CAM_H, "fovy_deg": 48}
+
+
+def front_camera(seat: str) -> dict:
+ """The legacy fixed camera front_<seat> of hockey.scene_xml (pos, xyaxes) as a camera definition: forward is
+ -(x_axis x y_axis), up the y axis."""
+ pos, x, y = {"A": ((0, -1.3, 2.2), (1, 0, 0), (0, .861, .509)),
+ "B": ((0, 1.3, 2.2), (-1, 0, 0), (0, -.861, .509))}[seat]
+ fwd = -np.cross(x, y)
+ return {"name": "front", "pos": list(map(float, pos)), "lookat": (np.add(pos, fwd)).tolist(),
+ "up": list(map(float, y)), **CAM}
+
+
+def is_single(cfg) -> bool:
+ return len(cfg.seats) == 1
+
+
+class AirHockey(MatchBase):
+ def __init__(self, cfg):
+ self.cfg, self.seats = cfg, tuple(cfg.seats)
+ if self.seats not in (("A",), ("A", "B")):
+ raise ValueError("airhockey: one seat (A, against the scripted opponent) or two (A, B)")
+ self.single = is_single(cfg)
+ level = int(cfg.level or 1) if self.single else 1
+ if level not in H.LEVELS:
+ raise ValueError("level must be 1, 2, 3 or 4")
+ first = cfg.first or "A"
+ if first not in ("A", "B"):
+ raise ValueError("first must be A or B")
+ self.h = H.Hockey(seed=int(cfg.seed), level=level, duel=not self.single, first=first)
+ self.dt = H.DT
+ self.side = {"A": "A", "B": "opponent" if self.single else "B"} # hockey seat -> side of the match
+
+ @property
+ def k(self):
+ return self.h.k
+
+ # ------------------------------------------------------------------ world
+ def step(self):
+ h = self.h
+ n = len(h.results)
+ contact = h.step()
+ events = [{"kind": "contact", "with": sorted(contact)}] if contact else []
+ if len(h.results) > n:
+ events.append({"kind": "rally", **h.results[-1]})
+ return events
+
+ def state_digest(self):
+ """hockey.Hockey.digest(): the full MuJoCo integration state, the controllers, the RNG, the scripted opponent
+ and the referee."""
+ return self.h.digest()
+
+ # ------------------------------------------------------------------ actions
+ def schema(self, seat):
+ return SCHEMA
+
+ def apply(self, seat, cmd):
+ h = self.h
+ if h.done or h.awaiting_review:
+ return {"rejected": "the world is frozen"}
+ h.set_command(seat, None if cmd["type"] == "none" else [cmd["x"], cmd["y"]])
+ return {"command": [round(float(v), 5) for v in h.commands[seat]]}
+
+ # ------------------------------------------------------------------ referee
+ def phase(self):
+ h = self.h
+ if h.done:
+ return Phase(FINISHED, reason="match_over")
+ if h.awaiting_review:
+ return Phase(UNIT_OVER, review=self.seats, reason=h.results[-1]["how"])
+ return Phase(PLAYING)
+
+ def resume(self):
+ self.h.ready()
+
+ def unit(self):
+ return len(self.h.results)
+
+ def scores(self):
+ sc = self.h.scores()
+ return {self.side[s]: sc[s]["points"] for s in ("A", "B")}
+
+ def tiebreaks(self):
+ """Hockey.winner() split into its named steps (USAA I.1 first to 7; the safety cap's chain)."""
+ def goals(m):
+ sc = m.h.scores()
+ a, b = sc["A"]["points"], sc["B"]["points"]
+ return None if a == b else m.side["A" if a > b else "B"]
+
+ def last_goal(m):
+ g = [r for r in m.h.results if r["how"] == "goal"]
+ return m.side[g[-1]["winner"]] if g else None
+
+ def territory(m):
+ hs = m.h.half_steps
+ return None if hs["A"] == hs["B"] else m.side["A" if hs["A"] < hs["B"] else "B"]
+
+ def first_possession(m):
+ return m.side[H.OTHER[m.h.first]]
+ return list(zip(TIEBREAKS, (goals, last_goal, territory, first_possession)))
+
+ # ------------------------------------------------------------------ observation
+ def rally(self, res):
+ sc = {s: sum(r["how"] == "goal" and r["winner"] == s for r in self.h.results[:res["rally"]]) for s in "AB"}
+ return {"rally": res["rally"], "how": res["how"], "scored": res["winner"], "fouled": res["guilty"],
+ "next_puck": res["next"], "score": sc, "t_play": round(res["k"] * H.DT, 2)}
+
+ def observe(self, seat, query=None):
+ h = self.h
+ frozen = h.awaiting_review or h.done
+ return {"rally": len(h.results) + (0 if frozen else 1), "t_play": round(h.k * H.DT, 3),
+ "play_time_left_s": round(max(0.0, H.CAP_S - h.k * H.DT), 3), "score": h.scores(),
+ "own": {"mallet_xyz": [round(float(x), 5) for x in h.position(seat)],
+ "command": [round(float(x), 5) for x in h.commands[seat]],
+ "joint_position": [round(float(x), 5) for x in h.data.qpos[h.qadr[seat]]],
+ "joint_velocity": [round(float(x), 5) for x in h.data.qvel[h.dadr[seat]]]},
+ "rallies": [self.rally(r) for r in h.results],
+ "last_rally": self.rally(h.results[-1]) if h.results else None}
+
+ def cameras(self, seat, query=None):
+ return [front_camera(seat)]
+
+ def render_state(self):
+ return {"qpos": np.asarray(self.h.data.qpos).tolist()}
+
+ def final_fields(self):
+ h = self.h
+ return {"hockey_revision": H.REVISION, "goal_width_m": H.GOAL, "level": h.level, "first_player": h.first, "duel": h.duel,
+ "scores": h.scores(), "results": h.results, "decided_by": h.decided_by,
+ "match_limit": bool(h.decided_by and h.decided_by.startswith("cap")), "done": h.done,
+ "half_steps": dict(h.half_steps), "rail_contact_steps": h.rail_contact_steps,
+ "mallet_contact_steps": h.contact_steps}
+
+
+class TargetLayer(LowLayer):
+ """The only action level: the schema's types and finite numbers (core.sport.check_command), then the legacy
+ hockey.validate_action (own half, the workspace box and the reach; 400 otherwise). A body without a type is a
+ target, as in the legacy `POST /act {"x": X, "y": Y}`."""
+
+ def __init__(self):
+ super().__init__(None)
+
+ def parse(self, seat, body, match, ctx):
+ if isinstance(body, dict) and "type" not in body and "x" in body:
+ body = {"type": "target", **body}
+ cmd = check_command(SCHEMA, body)
+ if "entity" in cmd:
+ raise Refused("the mallet takes no entity")
+ if seat not in match.seats:
+ raise Refused("unknown seat")
+ if cmd["type"] == "target":
+ try:
+ H.validate_action({"type": "target", "x": cmd["x"], "y": cmd["y"]}, seat)
+ except ValueError as exc:
+ raise Refused(str(exc)) from exc
+ return cmd
+
+
+class AirHockeySport:
+ name, protocol, revision, source_dirs, workers = "airhockey", "realtime", REVISION, [HERE], ("render",)
+
+ def build(self, cfg):
+ return AirHockey(cfg)
+
+ def action_layer(self, level):
+ return TargetLayer()
+
+ def scene(self, cfg):
+ from renderers.base import Scene
+ return Scene(xml=H.scene_xml())
+
+ def spec(self, cfg, seat, match):
+ """hockey.py's public constants (no seed): the action workspace, the limits, the geometry and the timing."""
+ h = match.h
+ out = {"match": {"first_player": h.first, "points_to_win": H.POINTS_TO_WIN,
+ **({"opponent_level": h.level, "opponent_seat": "B"} if match.single else {})},
+ "workspace": {"x_abs_m": [H.X_NEAR, H.X_FAR], "y_abs_max_m": H.Y_MAX, "reach_m": H.REACH,
+ "robot_base": {"A": [-H.BASE_X, 0.0], "B": [H.BASE_X, 0.0]}},
+ "mallet_path": {"max_speed_m_s": H.MAX_SPEED, "max_accel_m_s2": H.MAX_ACCEL,
+ "takes_effect": "at the next control step", "hold": "until replaced"},
+ "referee_timing": {"seven_second_rule_s": H.SEVEN_S, "dead_puck_s": H.DEAD_S, "centre_line_s": H.LINE_S,
+ "play_time_cap_s": H.CAP_S, "max_rallies": H.MAX_RALLIES},
+ "geometry": {"length_m": H.LENGTH, "width_m": H.WIDTH, "goal_width_m": H.GOAL,
+ "puck_radius_m": H.PUCK_R, "mallet_radius_m": H.MALLET_R, "puck_plane_z_m": 0.012,
+ "mallet_centre_z_m": 0.0645, "home": {"A": [-H.HOME_X, 0.0], "B": [H.HOME_X, 0.0]},
+ "puck_spot_abs_x_m": H.SPOT_X}}
+ if H.GOAL != H.GOAL_DEFAULT: # the experiment knob RO_AIRHOCKEY_GOAL_M: the rules text follows
+ g = H.GOAL
+ out["table"] = (f"metres, seconds; the table frame: x along the table (seat A's end at x < 0, seat B's at "
+ f"x > 0), y across, z up. Playing surface 1.948 x 1.038 m (|x| <= 0.974, |y| <= 0.519), "
+ f"surrounded by rails; a goal mouth {g:g} m wide (|y| <= {g / 2:g}) in the middle of each "
+ f"end rail; the centre line is x = 0 (experiment setting: this goal width replaces the "
+ f"default {H.GOAL_DEFAULT:g} m)")
+ return out
+
+ def players(self):
+ import builtin_players as bp
+ return {"reference": bp.Reference, "random": bp.Random}
+
+
+SPORT = AirHockeySport()
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/sport/presentation/presentation.toml b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/sport/presentation/presentation.toml
new file mode 100644
index 0000000000..b2ebf396ee
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/sport/presentation/presentation.toml
@@ -0,0 +1,17 @@
+# Appearance of air hockey's robots (docs/framework_zh.md §3.1, renderer rule 6; renderers/presentation/__init__.py):
+# the KUKA LBR iiwa 14's visual meshes on the arm's bodies, same kinematics. Since revision airhockey-program-v4 /
+# players-25k the players' images use it too (`players`): tools/sportlib bundles this directory and the 25k level of
+# detail of the meshes (renderers/presentation/lod.json, sha256-pinned, licence kept) into the simulator, and the core's
+# camera worker draws the players' scene (core/observe.players_scene), so they are part of source_sha; spectator
+# re-renders from a checkout use the full meshes.
+[presentation]
+version = 2
+label = "KUKA LBR iiwa 14 visual meshes (MuJoCo Menagerie)"
+players = "25k" # the players' images: the meshes decimated to ~25k triangles per arm
+
+[[presentation.robot]]
+model = "kuka_iiwa_14" # renderers/presentation/menagerie.json (fetched, sha256-pinned)
+bodies = '^iiwa_[12]/(?P<x>base|link)_?(?P<n>[1-7]?)$'
+body = "{x}{n}" # iiwa_1/base -> base, iiwa_1/link_3 -> link3 (the challenge's frames are Menagerie's)
+hide = "all" # the arm's capsules move to the hidden group 3 ...
+hide_bodies = '^iiwa_[12]/(base|link_[1-6])$' # ... but link_7 keeps its capsule: the striker's 0.585 m shaft
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/sport/scene/ORIGIN.md b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/sport/scene/ORIGIN.md
new file mode 100644
index 0000000000..b9b4146c7c
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/sport/scene/ORIGIN.md
@@ -0,0 +1 @@
+Robot joint transforms, inertias, limits and motors derived from AirHockeyChallenge/air_hockey_challenge, commit 34729081d4327141dcf560c0fb8274cd4882e82c, qualifying-2025. MIT license retained. Visual meshes replaced by self-authored capsule primitives; no external mesh files. New benchmark table/cameras/referee/controllers are not the official challenge tournament.
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/sport/scene/UPSTREAM_LICENSE b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/sport/scene/UPSTREAM_LICENSE
new file mode 100644
index 0000000000..4cbe8acdef
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/sport/scene/UPSTREAM_LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2025 Atalay Donat, Puze Liu, Jonas Guenster, Davide Tateo.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/sport/scene/iiwa1.xml b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/sport/scene/iiwa1.xml
new file mode 100644
index 0000000000..94d6709c9f
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/sport/scene/iiwa1.xml
@@ -0,0 +1,66 @@
+<mujoco model="iiwa_1">
+ <compiler angle="radian" autolimits="true" />
+
+ <default>
+ <default class="vis">
+ <geom contype="0" conaffinity="0" />
+ </default>
+ <default class="robot">
+ <geom condim="4" solref="0.02 0.3" priority="2" />
+ </default>
+ </default>
+ <worldbody>
+ <body name="iiwa_1/base" pos="-1.51 0 -0.1">
+ <body name="iiwa_1/link_1" pos="0 0 0.1575">
+ <inertial pos="4.007709e-06 -0.033936 0.122467" mass="8.240527" fullinertia="0.021981 0.022182 0.008234 -2.897243e-07 6.3165236e-07 0.003285" />
+ <joint name="iiwa_1/joint_1" pos="0 0 0" axis="0 0 1" range="-2.96706 2.96706" damping="0.33032" frictionloss="0.384477" />
+ <body name="iiwa_1/link_2" pos="0 0 0.2025" quat="0 0 0.707107 0.707107">
+ <inertial pos="0.003402 0.034792 0.046725" mass="6.357896" fullinertia="0.015565 0.005180 0.015484 -4.147301e-06 1.192255e-05 0.002538" />
+ <joint name="iiwa_1/joint_2" pos="0 0 0" axis="0 0 1" range="-2.0944 2.0944" damping="0.21216" frictionloss="0.496333" />
+ <body name="iiwa_1/link_3" pos="0 0.2045 0" quat="0 0 0.707107 0.707107">
+ <inertial pos="-0.001452 0.031526 0.133584" mass="4.042756" fullinertia="0.010914 0.010381 0.003139 -3.540575e-06 -9.059062e-06 -0.002128" />
+ <joint name="iiwa_1/joint_3" pos="0 0 0" axis="0 0 1" range="-2.96706 2.96706" damping="0.1" frictionloss="0.173951" />
+ <body name="iiwa_1/link_4" pos="0 0 0.2155" quat="0.707107 0.707107 0 0">
+ <inertial pos="-0.002527 0.053508 0.037205" mass="3.642249" fullinertia="0.007536 0.002538 0.007206 -5.707028e-06 2.781894e-06 0.001256" />
+ <joint name="iiwa_1/joint_4" pos="0 0 0" axis="0 0 1" range="-2.0944 2.0944" damping="0.219041" frictionloss="0.3751" />
+ <body name="iiwa_1/link_5" pos="0 0.1845 0" quat="0 0 0.707107 0.707107">
+ <inertial pos="0.001855 0.024573 0.080131" mass="2.580896" fullinertia="0.005201 0.004488 0.002242 1.089316e-07 9.035623e-07 -0.001613" />
+ <joint name="iiwa_1/joint_5" pos="0 0 0" axis="0 0 1" range="-2.96706 2.96706" damping="0.185923" frictionloss="0.481099" />
+ <body name="iiwa_1/link_6" pos="0 0 0.2155" quat="0.707107 0.707107 0 0">
+ <inertial pos="-0.001739 -0.001973 -0.002502" mass="2.760564" fullinertia="0.002534 0.001821 0.002393 -1.311766e-06 9.508242e-07 0.000134" />
+ <joint name="iiwa_1/joint_6" pos="0 0 0" axis="0 0 1" range="-2.0944 2.0944" damping="0.1" frictionloss="0.196149" />
+ <body name="iiwa_1/link_7" pos="0 0.081 0" quat="0 0 0.707107 0.707107">
+ <inertial pos="0.000735 0.000387 0.026460" mass="1.285417" fullinertia="0.000151 0.000150 0.000187 -7.223100e-08 2.038333e-06 -3.396830e-07" />
+ <joint name="iiwa_1/joint_7" pos="0 0 0" axis="0 0 1" range="-3.05433 3.05433" damping="0.1" frictionloss="0.299238" armature="0.01" />
+ <body name="iiwa_1/striker_joint_link" pos="0 0 0.585">
+ <inertial pos="0 0 0" mass="0.1" diaginertia="0.001 0.001 0.001" />
+ <body name="iiwa_1/striker_mallet" pos="0 0 0">
+ <inertial pos="0 0 0.0682827" mass="0.283" diaginertia="0.005 0.005 0.005" />
+ <joint name="iiwa_1/striker_joint_1" pos="0 0 0" axis="0 1 0" range="-1.5708 1.5708" damping="0.0" />
+ <joint name="iiwa_1/striker_joint_2" pos="0 0 0" axis="1 0 0" range="-1.5708 1.5708" damping="0.0" />
+ <geom name="iiwa_1/ee" type="cylinder" rgba=".1 .3 .9 1" size="0.04815 0.03" pos="0 0 0.0505" friction="0 0 0" class="robot" />
+ </body>
+ </body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.0 0.585" size=".028" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.081 0.0" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.0 0.2155" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.1845 0.0" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.0 0.2155" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.2045 0.0" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.0 0.2025" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.0 0.1575" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ </worldbody>
+
+
+ <actuator>
+ <motor name="iiwa_1/joint_1" joint="iiwa_1/joint_1" ctrlrange="-320 320" />
+ <motor name="iiwa_1/joint_2" joint="iiwa_1/joint_2" ctrlrange="-320 320" />
+ <motor name="iiwa_1/joint_3" joint="iiwa_1/joint_3" ctrlrange="-176 176" />
+ <motor name="iiwa_1/joint_4" joint="iiwa_1/joint_4" ctrlrange="-176 176" />
+ <motor name="iiwa_1/joint_5" joint="iiwa_1/joint_5" ctrlrange="-110 110" />
+ <motor name="iiwa_1/joint_6" joint="iiwa_1/joint_6" ctrlrange="-40 40" />
+ <motor name="iiwa_1/joint_7" joint="iiwa_1/joint_7" ctrlrange="-40 40" />
+ <motor name="iiwa_1/striker_joint_1" joint="iiwa_1/striker_joint_1" ctrlrange="-10 10" />
+ <motor name="iiwa_1/striker_joint_2" joint="iiwa_1/striker_joint_2" ctrlrange="-10 10" />
+ </actuator>
+</mujoco>
\ No newline at end of file
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/sport/scene/iiwa2.xml b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/sport/scene/iiwa2.xml
new file mode 100644
index 0000000000..295c57a9c5
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/sport/scene/iiwa2.xml
@@ -0,0 +1,59 @@
+<mujoco model="iiwa_2">
+ <compiler angle="radian" autolimits="true" />
+
+ <worldbody>
+ <body name="iiwa_2/base" pos="1.51 0 -0.1" quat="0 0 0 1">
+ <body name="iiwa_2/link_1" pos="0 0 0.1575">
+ <inertial pos="4.007709e-06 -0.033936 0.122467" mass="8.240527" fullinertia="0.021981 0.022182 0.008234 -2.897243e-07 6.3165236e-07 0.003285" />
+ <joint name="iiwa_2/joint_1" pos="0 0 0" axis="0 0 1" range="-2.96706 2.96706" damping="0.33032" frictionloss="0.384477" />
+ <body name="iiwa_2/link_2" pos="0 0 0.2025" quat="0 0 0.707107 0.707107">
+ <inertial pos="0.003402 0.034792 0.046725" mass="6.357896" fullinertia="0.015565 0.005180 0.015484 -4.147301e-06 1.192255e-05 0.002538" />
+ <joint name="iiwa_2/joint_2" pos="0 0 0" axis="0 0 1" range="-2.0944 2.0944" damping="0.21216" frictionloss="0.496333" />
+ <body name="iiwa_2/link_3" pos="0 0.2045 0" quat="0 0 0.707107 0.707107">
+ <inertial pos="-0.001452 0.031526 0.133584" mass="4.042756" fullinertia="0.010914 0.010381 0.003139 -3.540575e-06 -9.059062e-06 -0.002128" />
+ <joint name="iiwa_2/joint_3" pos="0 0 0" axis="0 0 1" range="-2.96706 2.96706" damping="0.1" frictionloss="0.173951" />
+ <body name="iiwa_2/link_4" pos="0 0 0.2155" quat="0.707107 0.707107 0 0">
+ <inertial pos="-0.002527 0.053508 0.037205" mass="3.642249" fullinertia="0.007536 0.002538 0.007206 -5.707028e-06 2.781894e-06 0.001256" />
+ <joint name="iiwa_2/joint_4" pos="0 0 0" axis="0 0 1" range="-2.0944 2.0944" damping="0.219041" frictionloss="0.3751" />
+ <body name="iiwa_2/link_5" pos="0 0.1845 0" quat="0 0 0.707107 0.707107">
+ <inertial pos="0.001855 0.024573 0.080131" mass="2.580896" fullinertia="0.005201 0.004488 0.002242 1.089316e-07 9.035623e-07 -0.001613" />
+ <joint name="iiwa_2/joint_5" pos="0 0 0" axis="0 0 1" range="-2.96706 2.96706" damping="0.185923" frictionloss="0.481099" />
+ <body name="iiwa_2/link_6" pos="0 0 0.2155" quat="0.707107 0.707107 0 0">
+ <inertial pos="-0.001739 -0.001973 -0.002502" mass="2.760564" fullinertia="0.002534 0.001821 0.002393 -1.311766e-06 9.508242e-07 0.000134" />
+ <joint name="iiwa_2/joint_6" pos="0 0 0" axis="0 0 1" range="-2.0944 2.0944" damping="0.1" frictionloss="0.196149" />
+ <body name="iiwa_2/link_7" pos="0 0.081 0" quat="0 0 0.707107 0.707107">
+ <inertial pos="0.000735 0.000387 0.026460" mass="1.285417" fullinertia="0.000151 0.000150 0.000187 -7.223100e-08 2.038333e-06 -3.396830e-07" />
+ <joint name="iiwa_2/joint_7" pos="0 0 0" axis="0 0 1" range="-3.05433 3.05433" damping="0.1" frictionloss="0.299238" armature="0.01" />
+ <body name="iiwa_2/striker_joint_link" pos="0 0 0.585">
+ <inertial pos="0 0 0" mass="0.1" diaginertia="0.001 0.001 0.001" />
+ <body name="iiwa_2/striker_mallet" pos="0 0 0">
+ <inertial pos="0 0 0.0682827" mass="0.283" diaginertia="0.005 0.005 0.005" />
+ <joint name="iiwa_2/striker_joint_1" pos="0 0 0" axis="0 1 0" range="-1.5708 1.5708" damping="0.0" />
+ <joint name="iiwa_2/striker_joint_2" pos="0 0 0" axis="1 0 0" range="-1.5708 1.5708" damping="0.0" />
+ <geom name="iiwa_2/ee" type="cylinder" rgba=".05 .65 .2 1" size="0.04815 0.03" pos="0 0 0.0505" friction="0 0 0" class="robot" />
+ </body>
+ </body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.0 0.585" size=".028" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.081 0.0" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.0 0.2155" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.1845 0.0" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.0 0.2155" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.2045 0.0" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.0 0.2025" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ <geom type="capsule" fromto="0 0 0 0.0 0.0 0.1575" size=".045" rgba="1 .42 .04 1" contype="0" conaffinity="0" /></body>
+ </worldbody>
+
+
+ <actuator>
+ <motor name="iiwa_2/joint_1" joint="iiwa_2/joint_1" ctrlrange="-320 320" />
+ <motor name="iiwa_2/joint_2" joint="iiwa_2/joint_2" ctrlrange="-320 320" />
+ <motor name="iiwa_2/joint_3" joint="iiwa_2/joint_3" ctrlrange="-176 176" />
+ <motor name="iiwa_2/joint_4" joint="iiwa_2/joint_4" ctrlrange="-176 176" />
+ <motor name="iiwa_2/joint_5" joint="iiwa_2/joint_5" ctrlrange="-110 110" />
+ <motor name="iiwa_2/joint_6" joint="iiwa_2/joint_6" ctrlrange="-40 40" />
+ <motor name="iiwa_2/joint_7" joint="iiwa_2/joint_7" ctrlrange="-40 40" />
+ <motor name="iiwa_2/striker_joint_1" joint="iiwa_2/striker_joint_1" ctrlrange="-10 10" />
+ <motor name="iiwa_2/striker_joint_2" joint="iiwa_2/striker_joint_2" ctrlrange="-10 10" />
+ </actuator>
+
+</mujoco>
\ No newline at end of file
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/sport/sport.toml b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/sport/sport.toml
new file mode 100644
index 0000000000..9d2204ae4c
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/environment/sim/sport/sport.toml
@@ -0,0 +1,220 @@
+# airhockey: robot air hockey after the USAA rules (docs/framework_zh.md §4.2, §8). Migrated from the legacy tree in
+# stage 2 (scripts/olympiad/airhockey, scripts/olympiad/shared/airhockey/sim); revision v3 (2026-10-07, review item
+# B13) widened the goal mouth to 0.40 m (D10), so the legacy recordings (revision v2) no longer replay and golden/ holds
+# native recordings; revision v4 (2026-10-08) sets it to 0.35 m (a medium width, decided after the goal-width study).
+# The [[tasks]] ids keep the Season-1 task names (airhockey-match-wallclock-program-standard,
+# airhockey-duel-wallclock-program-standard).
+
+[sport]
+name = "airhockey"
+title = "Air hockey"
+summary = "robot air hockey on a physical MuJoCo table: a seven-axis KUKA iiwa arm holding a mallet at each end, the puck sliding on the air cushion, in a continuous world slowed by a factor S; you command your mallet's target in your own half and see the table only through your fixed camera; one game to 7 goals under the USAA rules (seven-second rule, dead-puck face-offs, a safety cap with a stated last resort, a 0.35 m goal mouth); format match: you against a scripted opponent (level 1-4), format duel: two players"
+protocol = "realtime"
+revision = "airhockey-program-v4+players-25k+core-0.2" # plugin.REVISION; bump on any change that alters play (players-25k: the players' images draw the arms with the KUKA iiwa 14's 25k visual meshes)
+physics = "mujoco 3.3.7 (1 kHz physics, 10 ms control): two physically simulated KUKA iiwa arms with passive striker joints (AirHockeyChallenge robot model), a 10 g puck on an air-cushion plane, physical rails and mallets"
+image = "ghcr.io/mll-lab-nu/eai-olympiad:0.1.0"
+status = "sport"
+publish = true
+category = "robotics-sports-arena"
+
+[rulebook]
+name = "USAA (United States Air Hockey Association) Official Rules of Air Hockey, as published by Gold Standard Air Hockey"
+version = "retrieved 2026-10-05"
+url = "https://goldstandardairhockey.com/usaa-official-rules-of-air-hockey/"
+
+[[deviations]]
+id = "D1"
+rule = "I.1, III.1"
+text = "one game to 7 points instead of a match of several games"
+affects_result = true
+[[deviations]]
+id = "D2"
+rule = "- (the rules have no time limit)"
+text = "a safety cap of 120 s of play (frozen time does not count) or 40 rallies; then the player with more goals wins, at equal goals the scorer of the last goal, at 0:0 the player in whose half the puck spent less time, and if that is equal the player who did not have the first possession (the stated last resort: no draws)"
+affects_result = true
+[[deviations]]
+id = "D3"
+rule = "III.1-2"
+text = "the game starts with the puck at rest in the half of the first player (FIRST_PLAYER, the coin toss) instead of a face-off; a face-off places the puck at rest at the table centre with both mallets at home instead of a referee's release"
+affects_result = true
+[[deviations]]
+id = "D4"
+rule = "I.10, VI.1"
+text = "the seven-second rule is a foul with the rulebook's penalty, forfeiture of the puck: the opponent gets it at rest on its spot; a foul gives no point"
+affects_result = true
+[[deviations]]
+id = "D5"
+rule = "IV.6, I.11"
+text = "a dead puck (play suspended) is added for a puck that no mallet can reach for 2 s (the robots' reach) or that touches the centre line for 7 s (I.11 has no limit); it is followed by a face-off"
+affects_result = true
+[[deviations]]
+id = "D6"
+rule = "I.4, I.14-15"
+text = "after every goal (I.4: the player scored upon gets the puck), foul or dead puck both mallets return home and the world freezes for the reviews; the time-outs are not used"
+affects_result = false
+[[deviations]]
+id = "D7"
+rule = "I.8, I.13, VI.6"
+text = "palming, goal-tending and topping cannot occur: only the mallets touch the puck and it stays flat on the table"
+affects_result = false
+[[deviations]]
+id = "D8"
+rule = "I.12, VI.9"
+text = "the mallets cannot cross the centre line: the mallet workspace ends 0.05 m before it (and at 1.45 m from the robot's base), so the players cannot touch each other"
+affects_result = true
+[[deviations]]
+id = "D9"
+rule = "-"
+text = "the players are seven-axis KUKA iiwa arms holding a mallet, commanded by a Cartesian target for the mallet (a smooth path of at most 2 m/s and 10 m/s^2, inverse kinematics and torque-limited motors), not human hands"
+affects_result = false
+[[deviations]]
+id = "D10"
+rule = "II.A.1 (the rules name the sanctioned tables, not their dimensions)"
+text = "the goal mouth is 0.35 m wide (|y| <= 0.175) instead of the 0.25 m of the table model (AirHockeyChallenge, 1.948 x 1.038 m): the arms move the mallet at about 2 m/s, so a shot takes 0.5-1 s to arrive and a defender that follows the puck would cover a 0.25 m mouth almost completely"
+affects_result = true
+
+[formats.match] # one seat against the scripted opponent inside the world (seat B of hockey.py)
+seats = ["A"]
+opponent = true # success = winning a valid game (core/grading.py), as in the legacy task
+levels = [1, 2, 3, 4] # the opponent level (RCB_LEVEL; default 1)
+[formats.duel]
+seats = ["A", "B"]
+first = ["A", "B"] # who has the puck first (FIRST_PLAYER); the runner plays both orders
+
+[modes]
+action_levels = ["low"] # the mallet target is the only level (the legacy interface)
+plays = ["program"]
+
+[timing]
+slowdown = 20 # S (RCB_SLOWDOWN); the legacy default of both tasks (official: match 1-20, duel 10, 20)
+start_timeout_s = 1800 # after the first seat started (duel); format match: from the service start
+ready_timeout_s = 300 # each review (legacy duel: 300 s; the legacy single had no limit)
+
+[actions.cli] # `game target X Y`, `game none`
+low = { target = ["x", "y"], none = [] }
+
+[observation]
+fields = ["rally", "t_play", "play_time_left_s", "score", "own", "rallies", "last_rally"]
+renderer = "mujoco"
+frame_budget_ms = 250 # one 320 x 240 tile (CPU, osmesa)
+columns = 1
+# Since revision airhockey-program-v4+players-25k the arms are drawn with the KUKA LBR iiwa 14's visual meshes
+# (presentation/presentation.toml players = "25k", bundled into the simulator; the core's camera worker draws the
+# players' scene, renderer rule 6). Measured 2026-10-08 (osmesa, host load ~8-10 on 32 cores), median / p95 ms per
+# observation at 1 llvmpipe thread: match scene 8.6 / 17.7, 25k meshes 12.0 / 15.2 (duel 12.1 / 25.0); 2 threads:
+# 6.3 / 9.5 and 8.7 / 16.9
+render_threads = 1 # llvmpipe threads per render process (LP_NUM_THREADS): one tile is cheap
+
+[spec] # the rules (also /spec); the numeric tables come from hockey.py (/spec)
+real_time = "this sport is real time (where the generic text above says otherwise, this line holds): `game wait DT` (POST /wait {\"dt\": DT}, 0 < DT <= 1) lets the world run DT game seconds; `game ready \"WHY\" \"PLAN\"` is due only after each rally, not after each action; acts are never out of turn, one in flight at a time; there is no release point and no execution scatter: your target goes to the mallet's path, the arm's inverse kinematics and its motors"
+robot = "a seven-axis KUKA iiwa arm whose end holds a mallet; seat A plays from the end x < 0, seat B from the end x > 0 (format match: you are A, the scripted opponent is B; `match.opponent_level` in /spec)"
+action = "target: a target for your mallet's centre in table metres (world frame). It must lie in your mallet's workspace (`workspace` in /spec): in your own half, 0.05 <= |x| <= 0.92, |y| <= 0.47, and at most 1.45 m from your robot's base at (-1.51, 0) for seat A, (+1.51, 0) for seat B; a target outside it is refused (HTTP 400). The mallet moves towards the target along a smooth path of at most 2 m/s and 10 m/s^2, driven by the arm's inverse kinematics and torque-limited motors, so it arrives later than the command and may lag when the arm is loaded or hits the puck. A command takes effect at the next 10 ms control step and holds until replaced; none holds the mallet where it is. The service has no puck tracking: aiming, timing and defending are up to you"
+observation = "one 320 x 240 RGB image per observation from your fixed camera above and behind your end of the table (`cameras` in /spec: pose, field of view, focal length; pixel centres at (column + 0.5, row + 0.5)). The puck is red, the mallet of seat A blue, the mallet of seat B green, the arms orange; four yellow markers are at (+-0.9, +-0.46) on the table surface and the centre line is grey. The state gives the score (points and fouls per seat), the time of play, your own mallet position, its command and your arm's joint positions and velocities (`own`), and the rallies that ended (`rallies`, the latest `last_rally`); no puck or opponent coordinates and no seed. Both seats see the game the same way: the two cameras are images of each other turned half a turn about the table centre"
+rally = "a rally starts with the puck at rest in one player's half on a spot at |x| = 0.58 (y varies between -0.18 and 0.18, from the seed), both mallets at home (|x| = 0.82, y = 0); the first rally starts with the puck in the half of `match.first_player`"
+goal = "the puck wholly inside a goal scores 1 point for the other player, whoever touched it last; the player scored upon gets the puck for the next rally"
+seven_second_rule = "if the puck stays wholly in one player's half for 7 s, that player commits a foul: the next rally starts with the puck in the opponent's half; a foul gives no point; the 7 s start again when the puck has wholly entered the other half; while it touches the centre line it is in nobody's half (either player may hit it)"
+dead_puck = "if for 2 s neither mallet can reach the puck (near the centre line at the sides, beyond both workspaces), or the puck touches the centre line for 7 s, the next rally starts with a face-off: the puck at rest at the table centre"
+review = "every goal, foul or dead puck ends the rally: both mallets return home, the world freezes for the reviews, then the next rally starts"
+game = "the first player to score 7 goals wins; the game also ends after 120 s of play (frozen time does not count) or 40 rallies, then the tiebreaks below decide"
+opponent = "format match: the scripted opponent (seat B, in the trusted simulator) guards its goal and strikes the puck at yours from the true puck position a reaction delay ago; levels 1-4 differ in its mallet speed (0.4 / 0.6 / 1 / 2 m/s), reaction delay and defence (level 1 does not guard its goal; level 4 guards the puck's predicted crossing point); it never reads your commands"
+table = "metres, seconds; the table frame: x along the table (seat A's end at x < 0, seat B's at x > 0), y across, z up. Playing surface 1.948 x 1.038 m (|x| <= 0.974, |y| <= 0.519), surrounded by rails; a goal mouth 0.35 m wide (|y| <= 0.175) in the middle of each end rail; the centre line is x = 0"
+puck = "radius 0.03165 m, mass 10 g; it slides flat on the air cushion and slows by about 10 % per second; rails return about 80 % of the puck's speed across them; mallets push it physically (a hit gives the puck up to about 1.3 times the mallet's speed); the puck's top face is at z = 0.022, its centre plane z = 0.012"
+mallet = "radius 0.04815 m, its centre 0.0645 m above the surface; home (-0.82, 0) for A, (0.82, 0) for B; the arm links have no collision geometry"
+cameras_pose = "the camera of seat A at (0, -1.3, 2.2), image right (1, 0, 0), image up (0, 0.861, 0.509), 48 degree vertical field of view; seat B's is the same turned half a turn about the table centre"
+rates = "physics 1000 Hz, control 100 Hz (10 ms steps)"
+
+[tiebreaks]
+order = ["goals", "last_goal", "territory", "first_possession"]
+text = "the first player to score 7 goals wins; at the safety cap (120 s of play or 40 rallies) the player with more goals wins; at equal goals the player who scored the last goal; if nobody has scored, the player in whose half the puck spent less time; last resort (not from the rulebook): the player who did not have the puck first"
+last_resort_in_prompt = true
+
+[[exploits]]
+id = "E1"
+text = "an out-of-range or malformed target (the other half, outside the workspace or the reach, non-finite, unknown fields) is refused (HTTP 400) and changes nothing; acting while the world is frozen is refused (409)"
+test = "test_exploit_bad_and_frozen_actions_are_refused"
+[[exploits]]
+id = "E2"
+text = "stalling with the puck in the own half is a seven-second foul, not a point: the opponent gets the puck"
+test = "test_exploit_stalling_with_the_puck_is_a_foul_not_a_point"
+[[exploits]]
+id = "E3"
+text = "parking the puck where no mallet reaches it is a dead puck after 2 s, followed by a face-off at the centre (which both mallets reach)"
+test = "test_exploit_parking_the_puck_out_of_reach_is_a_dead_puck"
+[[exploits]]
+id = "E4"
+text = "a puck resting on the centre line (nobody's half, no seven-second count) is a dead puck after 7 s"
+test = "test_exploit_centre_line_stall_is_a_dead_puck"
+[[exploits]]
+id = "E5"
+text = "every puck position away from the centre line can be reached by the mallet of its half (no dead zone at the rails)"
+test = "test_exploit_puck_at_the_rails_is_reachable"
+[[exploits]]
+id = "E6"
+text = "parking the mallet in front of the own goal and never playing loses to a player that plays"
+test = "test_exploit_parking_in_front_of_the_goal_loses"
+[[exploits]]
+id = "E7"
+text = "doing nothing loses to the scripted opponent (format match)"
+test = "test_exploit_doing_nothing_loses_to_the_scripted_opponent"
+[[exploits]]
+id = "E8"
+text = "the observation and /spec hold no puck or opponent coordinate and no seed (only the camera image shows the puck)"
+test = "test_exploit_world_state_hidden"
+[[exploits]]
+id = "E9"
+text = "the two robots are identical and point-symmetric through the table centre (geometry, physical parameters, and the puck's path under mirrored commands)"
+test = "test_exploit_mirror_symmetric_robots"
+[[exploits]]
+id = "E10"
+text = "no draws: a game without any play still ends at the cap and every step of the tiebreak chain decides; seven goals end the game at once"
+test = "test_exploit_no_draw_tiebreak_chain"
+
+[players]
+reference = "reference" # Sport.players() names: camera-only, wins the default configuration
+reference_class = "builtin_players:Reference"
+check = ["random"] # policies for the generic tests
+
+[fairness]
+# Two copies of the reference player. Realtime: a wide interval only warns; a reference duel is up to 12000 control
+# steps with two camera images every 5 steps (about 100 s of CPU each), so N is small. Result (README, revision v4):
+# N = 40, first mover 0.0 pp (95% CI +-15.5 pp), seat A -15.0 pp (+-14.8 pp) (no failure; wide: a warning for a
+# realtime sport); 28 of the 40 games decided by goals (26 by the count, 2 by the last goal), 12 by territory (v3 at
+# 0.40 m: 24 and 16; v2: 4 and 36).
+policy = "reference"
+matches_per_order = 20
+max_advantage_pp = 5
+mirror = "statistical" # world-frame observations and actions: a swapped match is not the same view
+
+[check] # tools/check time limits
+stage_timeout_s = 10800 # fairness: 40 reference duels of about 100 s each, over an hour on a shared host
+live_player_timeout_s = 3600 # live: a capped game is 2400 s at x20 plus the reviews
+
+[official] # grade.py applies the legacy rule per format (match: the level's own seeds)
+seeds = [1, 2, 3, 101, 111, 121, 202, 212, 222, 303, 313, 323, 404, 414, 424]
+levels = [1, 2, 3, 4]
+first_any = true
+
+[golden]
+episodes = "golden" # native recordings of revision v4 (tools/golden.py record)
+
+[[tasks]]
+id = "airhockey-match-wallclock-program-standard"
+format = "match"
+action_level = "low"
+[[tasks]]
+id = "airhockey-duel-wallclock-program-standard"
+format = "duel"
+action_level = "low"
+
+[broadcast] # spectators: the replay video's camera (the legacy `overview` camera)
+camera = { name = "broadcast", pos = [0.0, -2.3, 2.5], lookat = [0.0, -1.623, 1.764], up = [0.0, 0.736, 0.677], fovy_deg = 55, width = 640, height = 360 }
+
+[capabilities] # docs/capabilities_zh.md: 2 primary, 1 secondary, 0 none
+a1 = 2 # 3D: the puck and the opponent's mallet only from the oblique camera image
+a2 = 2 # puck dynamics: rail rebounds, air-cushion drag, mallet impacts
+a3 = 2 # execution: an arm with a lagging Cartesian path, IK and torque limits
+a4 = 2 # real time: the puck moves while the program thinks
+b1 = 0
+b2 = 1 # attack vs defence, shots away from the opponent's mallet
+b3 = 0
+physics = ["collision", "friction_rolling"]
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/instruction.md b/tasks/roboolympics-airhockey-match-i00-standard-realtime/instruction.md
new file mode 100644
index 0000000000..89618db0da
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/instruction.md
@@ -0,0 +1,99 @@
+# Air hockey: a match against a scripted opponent, in real time
+
+You play robot air hockey (USAA rules with the deviations below) against a scripted opponent: a MuJoCo KUKA iiwa 14 arm holding a mallet at your end of the table (x < 0), seen only through one fixed camera. A rally starts with the puck at rest in one player's half; a goal, a seven-second foul or a dead puck ends it. The first to 7 goals wins.
+
+**Your goal: win the match.** The task succeeds if the match finishes and you won it. Keep your scripts, logs and notes
+in `/app/output/`; there is nothing else to hand in: the simulator records the match.
+
+## Time does not stop
+- The world runs at 1/10 of real speed (`spec()["timing"]["slowdown"]` = 10): one 10 ms control
+ step of game time every 0.1 s of wall time. It never waits for you: while you think, the opponent
+ plays on and your robot keeps executing its last command.
+- The match starts paused. Its clock starts at your first `submit` or `get_obs(seconds > 0)`, and from then on it runs
+ until the match is over. Look at the cameras and read `spec()` first (`get_obs(seconds=0)` does not start the clock).
+- **Breaks.** After every rally the match stands still for 12 s of game time (120 s of wall time):
+ the clock keeps running, nothing moves and nothing scores, and play resumes by itself at the end of the break. Use it
+ to look at what happened and fix your program. Send a `ready` row to resume earlier (put your review, why you won or
+ lost the rally and what you change, in `submit`'s `note`). Commands planned for steps inside a break are dropped.
+- You have 7200 s in all. **If your session ends before the match is over, you lose** (success 0); so
+ start the match well before your time runs out and stay until it is over (`meta["done"]`).
+- No reset: one match is the whole episode.
+
+## Write a program
+A model response takes seconds, a rally only a few seconds of game time, so play with a program of your own: it
+observes, measures in the images, computes its next command and submits it, in a loop, without a new model response
+for each action. Run it in the background, watch its log, and stop, fix and restart it whenever needed (also during the
+match). Use only the camera images, the service's replies and this document: no simulator internals or hidden state.
+
+## Interface
+The client is installed: `from rcb_client import Robot, EpisodeOver` (`/opt/tools/rcb_client.py`, on `PYTHONPATH`;
+its docstring is the reference). Your container has Python 3.12 with numpy, SciPy, Pillow, requests and
+opencv-python-headless; no internet except your model's API.
+
+```python
+r = Robot() # connects to the simulator, waits until it is ready
+spec = r.spec() # the facts: action_types, cameras, proprio_layout, rules, break, timing
+res = r.get_obs(seconds=0) # now, at once: res.last[cam] (H x W x 3 uint8), res.proprio (rows)
+res = r.get_obs(seconds=0.12, video_fps=25, video="frames") # watch 0.12 s of game time: res.frames[cam] (N x H x W x 3)
+r.submit("mallet", [row]) # a command: answers at once; it takes effect at the next control step
+r.submit("ready", [[0]], note="WHY ... PLAN ...") # during a break: resume now
+```
+
+- `get_obs(cameras=None, seconds=0, video_fps=10, video="frames")`: `seconds=0` returns the current images and one
+ proprio row; `seconds > 0` (at most `spec()["max_watch_s"]`) waits while that much game time runs and returns the
+ frames the cameras saw (one every 1/`video_fps` s) and one proprio row per frame. `cameras=[]`: proprio only.
+- `submit(type, rows, at=None, note="")`: one command per row; the rows become the plan from control step `at` (the
+ next step by default; `meta["control_steps"]` is the next step's number), replacing whatever was planned from there.
+ A row takes effect at its step: the command is checked and planned there, from the state of that step. Rows for
+ steps that are already gone when the request arrives are dropped (`meta["late_steps"]`); out-of-range values are
+ clipped (`meta["clipped"]`); a command the rules refuse at its step (e.g. a mallet target while the match stands still) changes nothing and
+ counts in the proprio column `commands_refused`.
+- `res.meta`: `control_steps`, `sim_time_s`, `time_left_s`, `done`, `reason`, `running`, `lag_s`, and `proprio`
+ (`layout`, `now`). `EpisodeOver` is raised once the match is over.
+
+Your commands (`spec()["action_types"]`):
+
+| type | row | what it does |
+|---|---|---|
+| `mallet` | `[x, y]` | the mallet centre's target (m, table frame): the robot drives the mallet there along a speed- and acceleration-limited path (`spec()["rules"]["mallet_path"]`) and holds it until replaced. Own half only: a target outside the workspace (`spec()["rules"]["workspace"]`: 0.05 <= -x <= 0.92, \|y\| <= 0.47, at most 1.45 m from your base) is moved to its nearest point (`meta["clipped"]`). Rows may be a chunk `dt` apart with `interpolate="linear"`; a row equal to the target in force changes nothing |
+| `stop` | `[0]` | the mallet stops where it is (its target becomes its position) |
+| `ready` | `[0]` | end the break now (see Time) |
+
+Proprioception and the referee's information (`spec()["proprio_layout"]`, one float row per frame; NaN = not
+applicable now; times in game seconds, positions in metres in your frame): `match_step`, `break`, `break_left_s`, `finished`; `score_you`, `score_opponent`, `rally` (the rally being played, from 1), `t_play` (seconds of play; breaks do not count), `play_time_left_s` (to the 120 s cap); your mallet: `mallet_x/y/z` (its centre), `target_x/y` (the target in force); your arm: `q1`..`q7`, `q_striker1/2` and their velocities `qd1`..`qd7`, `qd_striker1/2`; the last rally: `last_rally_how` (1 goal, 2 seven-second foul, 3 dead puck, 4 time cap), `last_rally_scored` (1 you, -1 the opponent, 0 nobody), `last_rally_fouled` (who committed a foul), `last_rally_next_puck` (who gets the puck next, 0 a face-off); `commands_applied`, `commands_refused`, `last_refused_step`.
+
+Cameras: one camera, `front`, 320 x 240 RGB, fixed above and behind your end of the table (pose, field of view 48 degrees, `focal_px`, `principal_point_px` in `spec()["cameras"]`). The puck is red; the opponent's mallet is at the far end.
+
+The puck moves fast: track it over several consecutive images (`get_obs(seconds=0)` in a loop, each with its `t_play`) and move the mallet with a program that runs in the background.
+
+## Rules
+The rule texts come from RoboOlympics' `sport.toml`. Where they name RoboOlympics' own interface (`{'type': 'act', ...}`, `{'type': 'toss', ...}`, `{'type': 'none'}`, `{'type': 'target', ...}`, `state.*`, `game spec`, `/spec`), read: your `stroke`, `toss`, `rest`, `mallet` and `stop` rows, the proprio columns and `spec()`; where they say the world freezes for reviews, read: the break.
+
+- `robot`: a seven-axis KUKA iiwa arm whose end holds a mallet; seat A plays from the end x < 0, seat B from the end x > 0 (format match: you are A, the scripted opponent is B; `match.opponent_level` in /spec)
+- `rally`: a rally starts with the puck at rest in one player's half on a spot at |x| = 0.58 (y varies between -0.18 and 0.18, from the seed), both mallets at home (|x| = 0.82, y = 0); the first rally starts with the puck in the half of `match.first_player`
+- `goal`: the puck wholly inside a goal scores 1 point for the other player, whoever touched it last; the player scored upon gets the puck for the next rally
+- `seven_second_rule`: if the puck stays wholly in one player's half for 7 s, that player commits a foul: the next rally starts with the puck in the opponent's half; a foul gives no point; the 7 s start again when the puck has wholly entered the other half; while it touches the centre line it is in nobody's half (either player may hit it)
+- `dead_puck`: if for 2 s neither mallet can reach the puck (near the centre line at the sides, beyond both workspaces), or the puck touches the centre line for 7 s, the next rally starts with a face-off: the puck at rest at the table centre
+- `review`: every goal, foul or dead puck ends the rally: both mallets return home, the break follows (spec.break), then the next rally starts
+- `game`: the first player to score 7 goals wins; the game also ends after 120 s of play (frozen time does not count) or 40 rallies, then the tiebreaks below decide
+- `opponent`: format match: the scripted opponent (seat B, in the trusted simulator) guards its goal and strikes the puck at yours from the true puck position a reaction delay ago; levels 1-4 differ in its mallet speed (0.4 / 0.6 / 1 / 2 m/s), reaction delay and defence (level 1 does not guard its goal; level 4 guards the puck's predicted crossing point); it never reads your commands
+- `table`: metres, seconds; the table frame: x along the table (seat A's end at x < 0, seat B's at x > 0), y across, z up. Playing surface 1.948 x 1.038 m (|x| <= 0.974, |y| <= 0.519), surrounded by rails; a goal mouth 0.35 m wide (|y| <= 0.175) in the middle of each end rail; the centre line is x = 0
+- `puck`: radius 0.03165 m, mass 10 g; it slides flat on the air cushion and slows by about 10 % per second; rails return about 80 % of the puck's speed across them; mallets push it physically (a hit gives the puck up to about 1.3 times the mallet's speed); the puck's top face is at z = 0.022, its centre plane z = 0.012
+- `mallet`: radius 0.04815 m, its centre 0.0645 m above the surface; home (-0.82, 0) for A, (0.82, 0) for B; the arm links have no collision geometry
+- `cameras_pose`: the camera of seat A at (0, -1.3, 2.2), image right (1, 0, 0), image up (0, 0.861, 0.509), 48 degree vertical field of view; seat B's is the same turned half a turn about the table centre
+- `rates`: physics 1000 Hz, control 100 Hz (10 ms steps)
+- Winner: the first player to score 7 goals wins; at the safety cap (120 s of play or 40 rallies) the player with more goals wins; at equal goals the player who scored the last goal; if nobody has scored, the player in whose half the puck spent less time; last resort (not from the rulebook): the player who did not have the puck first
+- Rulebook: USAA (United States Air Hockey Association) Official Rules of Air Hockey, as published by Gold Standard Air Hockey, retrieved 2026-10-05
+- Deviation D1 (I.1, III.1): one game to 7 points instead of a match of several games
+- Deviation D2 (- (the rules have no time limit)): a safety cap of 120 s of play (frozen time does not count) or 40 rallies; then the player with more goals wins, at equal goals the scorer of the last goal, at 0:0 the player in whose half the puck spent less time, and if that is equal the player who did not have the first possession (the stated last resort: no draws)
+- Deviation D3 (III.1-2): the game starts with the puck at rest in the half of the first player (FIRST_PLAYER, the coin toss) instead of a face-off; a face-off places the puck at rest at the table centre with both mallets at home instead of a referee's release
+- Deviation D4 (I.10, VI.1): the seven-second rule is a foul with the rulebook's penalty, forfeiture of the puck: the opponent gets it at rest on its spot; a foul gives no point
+- Deviation D5 (IV.6, I.11): a dead puck (play suspended) is added for a puck that no mallet can reach for 2 s (the robots' reach) or that touches the centre line for 7 s (I.11 has no limit); it is followed by a face-off
+- Deviation D6 (I.4, I.14-15): after every goal (I.4: the player scored upon gets the puck), foul or dead puck both mallets return home and the world freezes for the reviews; the time-outs are not used
+- Deviation D7 (I.8, I.13, VI.6): palming, goal-tending and topping cannot occur: only the mallets touch the puck and it stays flat on the table
+- Deviation D8 (I.12, VI.9): the mallets cannot cross the centre line: the mallet workspace ends 0.05 m before it (and at 1.45 m from the robot's base), so the players cannot touch each other
+- Deviation D9 (-): the players are seven-axis KUKA iiwa arms holding a mallet, commanded by a Cartesian target for the mallet (a smooth path of at most 2 m/s and 10 m/s^2, inverse kinematics and torque-limited motors), not human hands
+- Deviation D10 (II.A.1 (the rules name the sanctioned tables, not their dimensions)): the goal mouth is 0.35 m wide (|y| <= 0.175) instead of the 0.25 m of the table model (AirHockeyChallenge, 1.948 x 1.038 m): the arms move the mallet at about 2 m/s, so a shot takes 0.5-1 s to arrive and a defender that follows the puck would cover a 0.25 m mouth almost completely
+
+Your robot: KUKA LBR iiwa 14 holding a mallet (the striker on two passive joints), its base at (-1.51, 0) beside your end. Everything else you need (the frame, the geometry and the rule constants) is in
+`spec()["rules"]`; the physics engine is MuJoCo.
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/solution/builtin_players.py b/tasks/roboolympics-airhockey-match-i00-standard-realtime/solution/builtin_players.py
new file mode 100644
index 0000000000..35623d0ced
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/solution/builtin_players.py
@@ -0,0 +1,325 @@
+"""airhockey's built-in players (same action interface as a model's program; core/client.py plays them over HTTP).
+
+ Reference the camera-only reference player (rewritten 2026-10-07, review item B13; the legacy camera_player.py
+ rarely scored: 0.05 goals per game against itself). It finds the red puck and the opponent's mallet by
+ colour in its camera image (the camera definition of /spec) and fits the puck's velocity over the recent
+ images. Defence: on the defence line where the puck will cross it (side-rail bounces predicted with the
+ rails' restitution), at the near post when the puck will slide along the end rail towards the mouth,
+ and a puck deep beside the own goal is pushed out from the goal side, never across the mouth. Attack:
+ a puck in the own half is struck hard: wind-up behind it on the chosen line (straight or off a rail, at
+ the part of the goal the opponent's mallet needs longest to reach), then a drive through it towards a
+ target far beyond, so the mallet hits at the path's top speed.
+ Random uniform random targets in the own workspace (generic tests: no draw, whitelist, determinism).
+No simulator import: this file runs in the player's container as the task's oracle (numpy + pillow only)."""
+from __future__ import annotations
+
+import base64
+import io
+import math
+
+import numpy as np
+
+X_NEAR, X_FAR, Y_MAX, REACH, BASE_X = .05, .92, .47, 1.45, 1.51 # the public workspace (game spec: workspace)
+PUCK_R, MALLET_R = .03165, .04815 # game spec: geometry
+CONTACT = PUCK_R + MALLET_R
+END = 1.948 / 2 # the end line (half length)
+RAIL = .519 - PUCK_R # the puck centre's reach across the table (half width - radius)
+MOUTH = .125 - PUCK_R # the puck centre scores within |y| < MOUTH
+E_RAIL = .8 # the rails return about 80 % of the speed across them (spec)
+GUARD = .80 # the defence line (local u)
+WIND = .26 # the wind-up distance behind the puck before a strike
+TOL = .07 # line-up tolerance (rad) before a strike
+MALLET_Z = .005 # the mallet blob's centroid back-projects best onto this height
+
+
+def image_of(view):
+ """The seat's camera tile of the observation as an H x W x 3 float array (None without an image)."""
+ from PIL import Image
+ obs = view.get("observation") or {}
+ if not obs.get("image_png_b64"):
+ return None
+ img = np.asarray(Image.open(io.BytesIO(base64.b64decode(obs["image_png_b64"]))).convert("RGB")).astype(float)
+ tile = next((t for t in obs.get("tiles") or [] if t.get("camera") == "front"), None)
+ if tile:
+ img = img[tile["y"]:tile["y"] + tile["height"], tile["x"]:tile["x"] + tile["width"]]
+ return img
+
+
+def locate(a, cam, seat, what="puck"):
+ """The table-plane position of the puck (red) or of the opponent's mallet top (B green, A blue): the centroid of
+ the colour mask back-projected through the camera definition (pinhole, pixel centres at i + 0.5)."""
+ R, G, B = a[:, :, 0], a[:, :, 1], a[:, :, 2]
+ if what == "puck":
+ mask = (R > 150) & (R > 2.5 * G) & (R > 2.5 * B)
+ elif seat == "A":
+ mask = (G > 100) & (G > 2 * R) & (G > 1.5 * B) # B's green mallet
+ else:
+ mask = (B > 150) & (B > 2 * R) & (B > 1.3 * G) # A's blue mallet
+ rows, cols = np.nonzero(mask)
+ if len(rows) < 3:
+ return None
+ pos, look = np.array(cam["pos"], float), np.array(cam["lookat"], float)
+ fwd = (look - pos) / np.linalg.norm(look - pos)
+ right = np.cross(fwd, np.array(cam.get("up", [0, 0, 1]), float))
+ right /= np.linalg.norm(right)
+ up = np.cross(right, fwd)
+ f = cam["focal_px"]
+ cx, cy = cam["principal_point_px"]
+ ray = fwd + right * ((float(cols.mean()) + .5 - cx) / f) + up * ((cy - float(rows.mean()) - .5) / f)
+ z = .012 if what == "puck" else MALLET_Z # the puck's centre plane / the mallet blob (calibrated)
+ return (pos + ray * ((z - pos[2]) / ray[2]))[:2]
+
+
+def clip(u, v):
+ """Local coordinates (u > 0 into the own half): the nearest workspace point."""
+ u, v = min(max(u, X_NEAR), X_FAR), min(max(v, -Y_MAX), Y_MAX)
+ d = math.hypot(BASE_X - u, v)
+ if d > REACH - 1e-3:
+ u, v = BASE_X - (BASE_X - u) * (REACH - 1e-3) / d, v * (REACH - 1e-3) / d
+ return u, v
+
+
+def inside(u, v):
+ return X_NEAR <= u <= X_FAR and abs(v) <= Y_MAX and math.hypot(BASE_X - u, v) <= REACH
+
+
+def seg_dist(q, a, b):
+ ab = b - a
+ t = float(np.clip((q - a) @ ab / max(1e-9, ab @ ab), 0, 1))
+ return float(np.linalg.norm(q - (a + t * ab)))
+
+
+def cross(p, w, line, bounces=4):
+ """Where (v), after how long (s, at constant speed) and with what velocity across (wv) a puck at p moving with w
+ (local coordinates) crosses u = line, bouncing off the side rails (the speed across a rail scales by E_RAIL);
+ None if it moves away."""
+ pu, pv = float(p[0]), float(p[1])
+ wu, wv = float(w[0]), float(w[1])
+ if (line - pu) * wu <= 1e-9:
+ return None
+ t = 0.
+ for _ in range(bounces + 1):
+ tu = (line - pu) / wu
+ tv = (RAIL - pv) / wv if wv > 1e-9 else ((-RAIL - pv) / wv if wv < -1e-9 else math.inf)
+ if tu <= tv:
+ return pv + wv * tu, t + tu, wv
+ pu, pv, t, wv = pu + wu * tv, pv + wv * tv, t + tv, -E_RAIL * wv
+ return None
+
+
+def shots(p, mouth=MOUTH):
+ """Candidate strikes of a puck at p (local): (unit direction, path points), straight at the other goal or off
+ one side rail (aimed with the rail's restitution), at five points of the goal mouth."""
+ out = []
+ x = END + p[0] # the distance to the other end line along -u
+ for gy in (-.7 * mouth, -.35 * mouth, 0., .35 * mouth, .7 * mouth):
+ out.append((0, gy, np.array([-x, gy - p[1]]), [p, np.array([-END, gy])]))
+ for b in (1, -1):
+ k = ((b * RAIL - p[1]) + (b * RAIL - gy) / E_RAIL) / x
+ if abs(k) < 1e-6:
+ continue
+ x1 = (b * RAIL - p[1]) / k
+ if not 0 < x1 < x:
+ continue
+ out.append((b, gy, np.array([-1., k]), [p, np.array([p[0] - x1, b * RAIL]), np.array([-END, gy])]))
+ return [(b, gy, d / np.linalg.norm(d), path) for b, gy, d, path in out]
+
+
+def defender_time(dist):
+ """Seconds an opponent's mallet needs to move `dist` (a 10 m/s^2 path from rest, plus a reaction)."""
+ return .12 + 2 * math.sqrt(max(dist, 0.) / 10.)
+
+
+def choose(p, opp, speed=1.8, wind=WIND, mouth=MOUTH):
+ """The strike direction for a puck at p: the candidate the opponent's mallet `opp` (local) is least likely to
+ reach in time, among those whose wind-up point behind the puck lies in the workspace."""
+ best = None
+ for b, gy, d, path in shots(p, mouth):
+ w = p - d * wind
+ if not inside(*w):
+ continue
+ if opp is None:
+ score = -.02 * abs(b) + .1 * abs(gy)
+ else:
+ clear, s = 9., 0.
+ for i in range(len(path) - 1):
+ a_, b_ = path[i], path[i + 1]
+ seg = float(np.linalg.norm(b_ - a_))
+ ab = b_ - a_
+ tt = float(np.clip((opp - a_) @ ab / max(1e-9, ab @ ab), 0, 1))
+ dd = float(np.linalg.norm(opp - (a_ + tt * ab)))
+ if dd < clear:
+ clear, s_at = dd, s + tt * seg
+ s += seg
+ t_puck = s_at / (speed * (E_RAIL if b and s_at > float(np.linalg.norm(path[1] - path[0])) else 1.))
+ score = min(defender_time(clear - CONTACT + .01) - t_puck, .3) - .03 * abs(b)
+ if best is None or score > best[0]:
+ best = (score, d)
+ return None if best is None else best[1]
+
+
+class Reference:
+ """Works in local coordinates: u = own * x (own half u > 0, own goal at u = +END), v = y.
+
+ Defence: while the puck is in the other half or coming at the own goal, the mallet stands on the defence line
+ (u = GUARD) where the puck will cross it (the side-rail bounces predicted with the rails' restitution), or, while
+ the puck goes away or rests over there, on the line from the puck to the goal centre. Attack: a puck resting or
+ moving slowly in the own half is struck hard: the mallet winds up WIND behind the puck on the chosen line
+ (choose(): straight or off a rail, where the opponent's mallet has to travel farthest in the time the puck takes),
+ then drives through it towards a target far beyond, so it reaches the path's top speed at the impact."""
+
+ def __init__(self, spec, seat, seed=0):
+ self.seat, self.own = seat, (-1. if seat == "A" else 1.)
+ self.cam = next(c for c in spec["cameras"] if c["name"] == "front")
+ self.mouth = float((spec.get("geometry") or {}).get("goal_width_m", 2 * (MOUTH + PUCK_R))) / 2 - PUCK_R
+ self.rally = None
+ self.reset()
+
+ def reset(self):
+ self.until, self.stroke, self.hist, self.w, self.p, self.t_side = -1., None, [], np.zeros(2), None, None
+ self.deep_stroke = False
+
+ def world(self, u, v):
+ u, v = clip(u, v)
+ return [round(self.own * u, 4), round(v, 4)]
+
+ def track(self, p, t):
+ """The puck's velocity: a straight-line fit over the recent images, restarted at a hit or a rail bounce
+ (an image off the fitted line by more than 1.2 cm)."""
+ if self.hist and t <= self.hist[-1][0] + 1e-6:
+ return
+ if len(self.hist) >= 2:
+ t0, p0 = self.hist[-1]
+ if float(np.linalg.norm(p0 + self.w * (t - t0) - p)) > .012:
+ self.hist = self.hist[-1:]
+ self.hist = (self.hist + [(t, p.copy())])[-5:]
+ if len(self.hist) >= 2:
+ ts = np.array([h[0] for h in self.hist])
+ ps = np.array([h[1] for h in self.hist])
+ tc = ts - ts.mean()
+ self.w = (tc[:, None] * (ps - ps.mean(0))).sum(0) / max(1e-9, float((tc * tc).sum()))
+ else:
+ self.w = np.zeros(2)
+
+ def guard(self, p, w):
+ c = cross(p, w, GUARD) if w[0] > .05 else None
+ e = cross(p, w, END) if w[0] > .05 else None
+ if e is not None and self.mouth - .01 < abs(e[0]) < .34 and e[0] * e[2] < 0 and e[1] < 3.:
+ # it will hit the end rail beside the goal and slide on towards the mouth: block the near post
+ return self.world(X_FAR - .02, float(np.sign(e[0])) * .05)
+ if c is not None and c[1] < 3.:
+ y = c[0]
+ else: # between the puck and the goal centre
+ y = p[1] * (END - GUARD) / max(.2, END - p[0])
+ return self.world(GUARD, float(np.clip(y, -.22, .22)))
+
+ def clear_deep(self, p, w, m, t):
+ """A puck deep beside the own goal: block the near post while it slides towards the goal mouth; else get to
+ its goal side (round the front, never through it) and push it outwards, away from the mouth."""
+ sg = 1. if p[1] >= 0 else -1. # the outer side of the puck
+ if w[1] * sg < -.15 and abs(p[1]) > .1: # sliding along the end rail towards the mouth
+ return self.world(X_FAR, sg * .05)
+ stage = np.array([min(X_FAR, p[0] + .04), p[1] - sg * .075])
+ if float(np.linalg.norm(m - stage)) < .03:
+ q = p - stage
+ self.stroke, self.until = self.world(*(p + q / float(np.linalg.norm(q)) * .25)), t + .3
+ return self.stroke
+ if (m[1] - p[1]) * sg < -.05 and abs(m[0] - p[0]) < .1: # on the goal side: close in
+ return self.world(*stage)
+ beside = np.array([p[0], p[1] - sg * .095])
+ if seg_dist(p, m, beside) > CONTACT + .015:
+ return self.world(*beside)
+ return self.world(p[0] - .13, p[1] - sg * .095) # first in front of the puck
+
+ def decide(self, puck, own_xyz, t, opp=None):
+ m = np.array([self.own * own_xyz[0], own_xyz[1]])
+ if puck is None:
+ if self.p is None or not self.hist or t > self.hist[-1][0] + .25:
+ return self.world(GUARD, 0.)
+ p = self.p + self.w * (t - self.hist[-1][0])
+ else:
+ p = np.array([self.own * puck[0], puck[1]])
+ self.track(p, t)
+ self.p = p
+ w = self.w
+ o = None if opp is None else np.array([self.own * opp[0], opp[1]])
+ if p[0] > PUCK_R: # seven-second clock: time the puck has spent in the own half
+ self.t_side = t if self.t_side is None else self.t_side
+ else:
+ self.t_side = None
+ deep = p[0] > .86 and abs(p[1]) < .26 and w[0] > -.6
+ if t < self.until: # a stroke in progress: drive through until the puck has gone
+ if w[0] < -.4 or p[0] < 0 or (deep and not self.deep_stroke):
+ self.until = -1.
+ else:
+ return self.stroke
+ self.deep_stroke = deep
+ if deep: # deep beside the own goal
+ return self.clear_deep(p + w * .05, w, m, t)
+ if p[0] < -.02 or w[0] > .35 or (w[0] < -.3 and p[0] < .3) or (w[0] > .12 and m[0] < p[0] + .05):
+ return self.guard(p, w) # (also: coming at the goal while the mallet is not behind it)
+ pp = p + w * .1 # where the puck will be when the mallet gets there
+ hurry = self.t_side is not None and t - self.t_side > 4.
+ d, wind = None, WIND
+ for wind in (WIND, .2, .14):
+ d = choose(pp, o, wind=wind, mouth=self.mouth)
+ if d is not None:
+ break
+ if d is None: # no line-up possible (a corner): push it out past the mallet
+ q = pp - m
+ q = q / max(1e-9, float(np.linalg.norm(q)))
+ self.stroke, self.until = self.world(*(pp + q * .25)), t + .3
+ return self.stroke
+ wpt = pp - d * wind
+ rel = pp - m
+ dist = float(np.linalg.norm(rel))
+ tol = TOL * (2.5 if hurry else 1.)
+ if (float(np.linalg.norm(m - wpt)) < .06 or hurry) and CONTACT + .02 < dist < wind + .12 \
+ and float(rel @ d) / dist > math.cos(tol): # lined up: drive through the puck
+ reach = .1
+ for L in (.5, .4, .3, .2):
+ if inside(*(pp + d * L)):
+ reach = L
+ break
+ self.stroke = self.world(*(pp + d * reach))
+ self.until = t + .35
+ return self.stroke
+ if seg_dist(pp, m, wpt) < CONTACT + .03 and float((m - pp) @ d) > -wind + .06:
+ n = np.array([-d[1], d[0]]) # the way to the wind-up point runs through the puck:
+ s = 1. if float(n @ (m - pp)) >= 0 else -1. # first beside it, on the mallet's side
+ q = pp + n * s * .17
+ if not inside(*q):
+ q = pp - d * .12 + n * s * .14
+ if not inside(*q):
+ q = pp - d * .12 - n * s * .14
+ return self.world(*q)
+ return self.world(*wpt)
+
+ def act(self, view):
+ st = view.get("state") or {}
+ if st.get("rally") != self.rally: # a new rally
+ self.rally = st.get("rally")
+ self.reset()
+ img = image_of(view)
+ if img is None or "own" not in st:
+ return None
+ puck = locate(img, self.cam, self.seat)
+ opp = locate(img, self.cam, self.seat, "opponent")
+ x, y = self.decide(puck, st["own"]["mallet_xyz"], float(st.get("t_play", st.get("t_sim", 0.0))), opp)
+ return {"type": "target", "x": x, "y": y}
+
+ def review(self, reply):
+ self.reset()
+ return "A goal, foul or dead puck ended the rally.", "Guard the crossing point; wind up and strike hard at the open side."
+
+
+class Random:
+ def __init__(self, spec, seat, seed=0):
+ self.own = -1. if seat == "A" else 1.
+ self.g = np.random.default_rng(int(seed) * 7919 + 17) # by seed, not by seat
+
+ def act(self, view):
+ if self.g.random() < .2:
+ return {"type": "none"}
+ u, v = clip(float(self.g.uniform(X_NEAR, X_FAR)), float(self.g.uniform(-Y_MAX, Y_MAX)))
+ return {"type": "target", "x": round(self.own * u, 4), "y": round(v, 4)}
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/solution/oracle_play.py b/tasks/roboolympics-airhockey-match-i00-standard-realtime/solution/oracle_play.py
new file mode 100644
index 0000000000..0f36ecd9a3
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/solution/oracle_play.py
@@ -0,0 +1,236 @@
+"""Harbor oracle: the sport's RoboOlympics reference player (builtin_players.Reference, next to this file: camera images
+and the documented facts only) driven through the agent's own client (rcb_client.py, eai-standard/2.3).
+
+The reference players were written for RoboOlympics' realtime interface: each step they get a `view` -- the state
+(score, the ball's clock, what was heard, the robot's own body) and a tiled PNG of the newest camera frames -- and
+return an act body or nothing. This loop builds that view from /observe (a short watch: the frames and one proprio row
+per frame), turns the act into a /submit row of the task's action type, and sends `ready` (with the player's review as
+the note) once per break. Nothing here reads simulator state the agent could not read.
+
+Timing (table tennis, badminton): the players also have an in-process mode in which an act takes effect exactly at the
+observed step. 2.3's `at` makes that exact over HTTP too: the loop picks the control step its command will take effect
+at (a margin of LEAD_STEPS after the step it estimates is running now), hands the player the view as of that step (the
+step and the times relative to it shifted accordingly; images and frame steps are absolute), and submits the command
+with `at` = that step. Host load then delays the command's arrival, never its effect.
+"""
+from __future__ import annotations
+
+import base64
+import io
+import math
+import os
+import sys
+import time
+
+import numpy as np
+from PIL import Image
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import builtin_players as bp # noqa: E402
+from rcb_client import EpisodeOver, Robot # noqa: E402
+
+NAN = float("nan")
+LEAD_STEPS = 5 # control steps between "now" (estimated) and a command's planned effect: 0.5 s of wall
+ # time at S = 10 for the player's own computation and the request
+
+
+def num(x):
+ return None if x is None or (isinstance(x, float) and math.isnan(x)) else x
+
+
+def png_b64(rows: list) -> tuple[str, list]:
+ """rows of tiles (one row per camera) -> base64 PNG and the tile list."""
+ sheet = np.concatenate([np.concatenate(r, axis=1) for r in rows], axis=0)
+ buf = io.BytesIO()
+ Image.fromarray(np.ascontiguousarray(sheet[..., :3])).save(buf, format="PNG", compress_level=1)
+ return base64.b64encode(buf.getvalue()).decode(), []
+
+
+class Bridge:
+ def __init__(self):
+ self.r = Robot()
+ self.spec = self.r.spec()
+ self.sport = self.spec["sport"]
+ self.layout = self.spec["proprio_layout"]
+ self.dt = float(self.spec["control_dt"])
+ self.period = float(self.spec["timing"]["wall_s_per_control_step"])
+ self.cams = list(self.spec["cameras"])
+ rules = self.spec.get("rules") or {}
+ cams = []
+ for name in self.cams:
+ c = dict(self.spec["cameras"][name], name=name)
+ if self.sport == "airhockey":
+ c.update(width=c["hw"][1], height=c["hw"][0])
+ cams.append(c)
+ self.exact = self.sport in ("tabletennis", "badminton") # the in-process timing mode (module docstring)
+ ref = {"cameras": cams, "action_level": self.spec["match"]["action_level"],
+ "timing": {"period_s": None if self.exact else self.period}, **rules}
+ self.player = bp.Reference(ref, "A", 0)
+ self.reviewed_break = None
+ self.n_obs = 0
+ self.hist: list = [] # (match step, proprio row, {cam: image}) of recent observations
+ self.spacing = {"tabletennis": 4, "badminton": 6}.get(self.sport, 1) # 40 / 60 ms, as RoboOlympics' views
+ self.running = False
+ # how often the loop looks (control steps): badminton at RoboOlympics' own client cadence (an observation, then
+ # `wait 0.05`): a player that re-plans its stroke at every step keeps the arm from ever finishing a swing
+ self.every = {"badminton": 5}.get(self.sport, 1)
+ # badminton: a command waits `lead_steps` after its step (stroke_pending_effect_step shows it then); before
+ # that it is still in the service's plan, which the proprio does not show: the loop marks it pending itself
+ self.lead = int(((self.spec.get("rules") or {}).get("act") or {}).get("lead_steps", 0))
+ self.pending_until = -1
+
+ # ------------------------------------------------------------------ one view
+ def rows(self, res) -> list[dict]:
+ P = np.asarray(res.proprio, float).reshape(-1, len(self.layout))
+ return [dict(zip(self.layout, map(float, row))) for row in P]
+
+ def state(self, p: dict, shift: int = 0) -> dict:
+ """The player's state as of `shift` control steps after the proprio row p (relative times shifted)."""
+ p = dict(p)
+ for k in ("t_since_played",):
+ if k in p and not math.isnan(p[k]):
+ p[k] += shift * self.dt
+ for k in ("serve_opens_in_s", "serve_deadline_in_s", "stroke_contact_in_s"):
+ if k in p and not math.isnan(p[k]):
+ p[k] -= shift * self.dt
+ if "serve_opens_in_s" in p and not math.isnan(p["serve_opens_in_s"]):
+ p["serve_opens_in_s"] = max(0.0, p["serve_opens_in_s"])
+ st = {"step": int(p["match_step"]) + shift, "world": "frozen" if p["break"] > 0.5 else "running",
+ "done": p["finished"] > 0.5}
+ if self.sport == "tabletennis":
+ heard = [{"event": ev, "t": p[f"heard_{k}_t"]} for k, ev in
+ (("opp_bounce", "bounce on the opponent's half"), ("own_bounce", "bounce on your half"),
+ ("net", "net"), ("paddle", "paddle"), ("robot", "robot"), ("floor", "floor"))
+ if not math.isnan(p[f"heard_{k}_t"])]
+ st.update(point=int(p["point"]), ball="serve" if p["ball_is_serve"] > 0.5 else "opponent's return",
+ t_since_played=p["t_since_played"], ball_in_play=p["ball_in_play"] > 0.5, heard=heard,
+ ball_state="coming to you" if p["ball_coming"] > 0.5 else
+ "going to the opponent" if p["ball_going"] > 0.5 else "dead")
+ elif self.sport == "badminton":
+ phase = {0: "waiting", 1: "open", 2: "tossed", 3: "done"}.get(int(p["serve_phase"]) if not
+ math.isnan(p["serve_phase"]) else -1)
+ sv = {"phase": phase, "court": "right" if p["serve_court_right"] > 0.5 else "left",
+ "opens_in_s": num(p["serve_opens_in_s"]), "deadline_in_s": num(p["serve_deadline_in_s"])}
+ if not math.isnan(p["serve_tossed_at_step"]):
+ sv["tossed_at_step"] = int(p["serve_tossed_at_step"])
+ notes = "; ".join(n for n, k in (("head speed limited", "stroke_head_speed_limited"),
+ ("pose not delivered", "stroke_pose_not_delivered")) if p[k] > 0.5)
+ st.update(point=int(p["point"]), score={"you": int(p["score_you"]), "opponent": int(p["score_opponent"])},
+ you_serve=p["you_serve"] > 0.5, serve=sv, robot_base_xy=[p["base_x"], p["base_y"]],
+ t_since_played=num(p["t_since_played"]),
+ ball_state="coming to you" if p["ball_coming"] > 0.5 else
+ "going to the opponent" if p["ball_going"] > 0.5 else
+ "tossed: yours to hit (your serve)" if p["ball_tossed"] > 0.5 else
+ "not yet served" if p["ball_not_served"] > 0.5 else "dead")
+ if p["stroke_active"] > 0.5:
+ st["command"] = {"contact_in_s": p["stroke_contact_in_s"], "stroke": notes}
+ if not math.isnan(p["stroke_pending_effect_step"]):
+ st["pending_commands"] = [{"takes_effect_at_step": int(p["stroke_pending_effect_step"])}]
+ else:
+ st.update(rally=int(p["rally"]), t_play=p["t_play"],
+ own={"mallet_xyz": [p["mallet_x"], p["mallet_y"], p["mallet_z"]]})
+ return st
+
+ def observe(self):
+ """Air hockey: watch 0.05 s (the players' cadence) and take the last image. Table tennis, badminton: the
+ current images at once (the clock is started by a short watch first), kept in a history from which the view
+ takes four frames about SPACING control steps apart, newest last, as RoboOlympics' observation did."""
+ if self.sport == "airhockey":
+ res = self.r.get_obs(cameras=self.cams, seconds=0.05, video="none")
+ return res, self.rows(res), {c: res.last[c][None] for c in self.cams}
+ res = self.r.get_obs(cameras=self.cams, seconds=0 if self.running else 0.05, video="frames")
+ self.running = True
+ rows = self.rows(res)
+ k = int(rows[-1]["match_step"])
+ if not self.hist or self.hist[-1][0] != k:
+ self.hist.append((k, rows[-1], {c: res.frames[c][-1] for c in self.cams}))
+ self.hist = self.hist[-40:]
+ sel, last = [], None
+ for k, row, fr in reversed(self.hist):
+ if last is None or last - k >= self.spacing:
+ sel.append((k, row, fr))
+ last = k
+ if len(sel) == 4:
+ break
+ sel.reverse()
+ return res, [r for _, r, _ in sel], {c: np.stack([fr[c] for _, _, fr in sel]) for c in self.cams}
+
+ def view(self, res, rows, frames, shift: int = 0) -> tuple[dict, dict, dict]:
+ now = rows[-1]
+ st = self.state(now, shift)
+ n = min(len(rows), min(len(f) for f in frames.values()))
+ rows, frames = rows[-n:], {c: f[-n:] for c, f in frames.items()}
+ self.n_obs += 1
+ ob = {"view_steps": [int(p["match_step"]) for p in rows],
+ "view_sim_times": [round(p["match_step"] * self.dt, 4) for p in rows]}
+ if not self.exact:
+ ob.update(obs_id=self.n_obs, obs_age_wall_s=0.0, render_wall_s=0.0)
+ if self.sport == "airhockey":
+ img = frames[self.cams[0]][-1]
+ ob["image_png_b64"], _ = png_b64([[img]])
+ ob["tiles"] = [{"camera": self.cams[0], "x": 0, "y": 0, "width": img.shape[1], "height": img.shape[0]}]
+ else:
+ ob["image_png_b64"], _ = png_b64([[f for f in frames[c]] for c in self.cams])
+ return st, ob, now
+
+ # ------------------------------------------------------------------ one action
+ def send(self, body: dict, at=None) -> None:
+ t = body.get("type")
+ if t == "act":
+ row = [body["t"], *body["pos"], *body["normal"], *body["vel"]]
+ self.r.submit("stroke", [row], at=at)
+ elif t == "toss":
+ self.r.submit("toss", [[*body["pos"], float(body.get("height", 0.0))]], at=at)
+ elif t == "target":
+ self.r.submit("mallet", [[body["x"], body["y"]]], at=at)
+ elif t == "none":
+ self.r.submit("stop" if self.sport == "airhockey" else "rest", [[0.0]], at=at)
+
+ def run(self) -> dict:
+ t_last = 0.0
+ while True:
+ time.sleep(max(0.0, t_last + self.every * self.period - time.monotonic())) # one view per `every` steps
+ t_last = time.monotonic()
+ try:
+ res, rows, frames = self.observe()
+ except EpisodeOver:
+ break
+ t_reply = time.monotonic()
+ if res.meta.get("done"):
+ break
+ at = shift = None
+ if self.exact: # the step the command will take effect at, and the view as of then
+ at = math.ceil(res.meta["control_steps"] + 0.5) + LEAD_STEPS
+ at = max(at, math.ceil(res.meta["control_steps"] + (time.monotonic() - t_reply) / self.period)
+ + LEAD_STEPS)
+ shift = at - int(res.meta["control_steps"])
+ st, ob, now = self.view(res, rows, frames, shift or 0)
+ if st["world"] == "frozen":
+ key = int(now["match_step"]) # the match stands still in a break: one key per break
+ if key != self.reviewed_break:
+ self.reviewed_break = key
+ f = getattr(self.player, "review", None)
+ why, plan = f(now) if f else ("played as planned", "same plan")
+ try:
+ self.r.submit("ready", [[1.0]], note=f"WHY: {why} PLAN: {plan}"[:200])
+ except EpisodeOver:
+ break
+ continue
+ if self.sport == "badminton" and res.meta["control_steps"] <= self.pending_until:
+ st["pending_commands"] = [{"takes_effect_at_step": int(now["match_step"]) + self.pending_until
+ - int(res.meta["control_steps"]) + 1}]
+ body = self.player.act({"state": st, "observation": ob})
+ if body:
+ if at is not None:
+ self.pending_until = at + self.lead
+ try:
+ self.send(body, at)
+ except EpisodeOver:
+ break
+ return self.r.status()
+
+
+if __name__ == "__main__":
+ t0 = time.time()
+ out = Bridge().run()
+ print({"status": out, "wall_s": round(time.time() - t0, 1)})
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/solution/solve.sh b/tasks/roboolympics-airhockey-match-i00-standard-realtime/solution/solve.sh
new file mode 100755
index 0000000000..a1680309dd
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/solution/solve.sh
@@ -0,0 +1,5 @@
+#!/bin/bash
+# Oracle: the sport's RoboOlympics reference player (camera images, proprio and /spec only) through the agent's client.
+set -e
+mkdir -p /app/output
+cd /solution && python3 oracle_play.py 2>&1 | tee /app/output/oracle.log
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/task.toml b/tasks/roboolympics-airhockey-match-i00-standard-realtime/task.toml
new file mode 100644
index 0000000000..03cee81011
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/task.toml
@@ -0,0 +1,74 @@
+# RoboOlympics Air hockey against the scripted opponent, standard-realtime mode (docs/PROTOCOL.md §4b, docs/benchmarks/roboolympics.md).
+# Generated by scripts/roboolympics/gen_tasks.py from tasks.toml, sports.toml and templates/ -- edit those, not this.
+schema_version = "1.3"
+artifacts = [
+ { source = "/data/final.json", service = "sim" },
+ { source = "/data/match.json", service = "sim" },
+ { source = "/data/episode.jsonl", service = "sim" },
+ { source = "/data/trajectory.npz", service = "sim" },
+ { source = "/data/trajectory_live.f64", service = "sim" },
+ { source = "/data/commands.jsonl", service = "sim" },
+ { source = "/data/replay.mp4", service = "sim" },
+ { source = "/data/replay.last.png", service = "sim" },
+ { source = "/data/ticks.f64", service = "sim" },
+ { source = "/data/calls.jsonl", service = "sim" },
+ { source = "/data/submitted.f64", service = "sim" },
+ { source = "/data/startups.jsonl", service = "sim" },
+ "/app/output/",
+]
+
+[task]
+name = "robot-coding-bench/roboolympics-airhockey-match-i00-standard-realtime"
+description = "STANDARD-REALTIME MODE (robot as a service on a clock that does not stop, eai-standard/2.3): RoboOlympics air hockey, one match against a scripted opponent (level 1, frozen seed 101). The world runs at 1/10 of real speed (S = 10, the benchmark's official slowdown) and never waits: the agent sees only camera images and its own robot through the client, and drives the robot with the sport's commands (`mallet`, `stop`, `ready`) from a program of its own. Between rallys a break of 12 s of game time (120 s of wall time) in which the clock runs on and nothing plays; no reset, no privileged state. The sim service records every command at the step it took effect, replays the match in a fresh process and grades it: success = a finished match that the agent won."
+authors = [{ name = "RoboOlympics (CHIGUI0)" }]
+keywords = ["robotics", "roboolympics", "sports", "airhockey", "mujoco", "standard-realtime-mode", "vision", "real-time"]
+
+[metadata]
+author_name = "RoboOlympics"
+task_type = "trajectory"
+simulator = "mujoco"
+robot = "kuka-iiwa14"
+family = "airhockey_match"
+mode = "standard-realtime"
+protocol = "eai-standard/2.3"
+instance_seed = 101
+opponent_level = 1
+slowdown = 10
+revision = "airhockey-program-v4+players-25k+core-0.2"
+play = "program"
+action_level = "low"
+source_task = "roboolympics/airhockey-match-wallclock-program-standard"
+expert_time_estimate_hours = 0.5
+oracle = "full"
+oracle_evidence = "solution/: the sport's RoboOlympics reference player (camera images, proprio and /spec only) through the agent's client; it wins this instance (PR #106)"
+
+[verifier]
+timeout_sec = 900.0
+environment_mode = "separate"
+network_mode = "no-network"
+
+# The agent's time is up: stop whatever it left running in its container (a program would keep playing).
+[[verifier.collect]]
+service = "main"
+command = "kill -9 -1 2>/dev/null; exit 0"
+timeout_sec = 30
+
+# Then the match ends: SIGUSR1 to the service (re-sent every 30 s, in case it was restarting), which replays and grades it.
+[[verifier.collect]]
+service = "sim"
+command = "for i in $(seq 1 90); do [ -f /data/server.pid ] && break; sleep 2; done; for i in $(seq 1 400); do grep -q '\"finalized\": true' /data/final.json 2>/dev/null && break; [ $((i % 15)) -eq 1 ] && kill -USR1 $(cat /data/server.pid) 2>/dev/null; sleep 2; done; cat /data/final.json"
+timeout_sec = 900
+
+[agent]
+timeout_sec = 7200
+# The agent reaches the model APIs and the sim (localhost:8000, Harbor's egress control) and nothing else.
+network_mode = "allowlist"
+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com"]
+
+[environment]
+build_timeout_sec = 1200.0
+cpus = 2
+memory_mb = 4096
+
+[verifier.environment]
+build_timeout_sec = 600.0
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/tests/Dockerfile b/tasks/roboolympics-airhockey-match-i00-standard-realtime/tests/Dockerfile
new file mode 100644
index 0000000000..0ecd542d19
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/tests/Dockerfile
@@ -0,0 +1,4 @@
+# Separate verifier sandbox: grades the sim service's own artifacts; needs nothing but Python.
+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f
+COPY test.sh grade.py /tests/
+RUN chmod +x /tests/test.sh
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/tests/grade.py b/tasks/roboolympics-airhockey-match-i00-standard-realtime/tests/grade.py
new file mode 100644
index 0000000000..32f4465282
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/tests/grade.py
@@ -0,0 +1,93 @@
+"""Standard-realtime verifier (eai-standard/2.3) for RoboOlympics: grades what the sim service -- which the agent could
+not touch -- wrote.
+
+/data/final.json holds the live match's outcome and the verdict of a fresh-process replay of its record:
+success = live_success (the match finished and the agent won it) AND replay_success (the replay's match too) AND
+deterministic (the replay ends in the live run's state). /data/match.json (the replay's summary: the score, the breaks,
+the commands) only adds information to reward.json; it never decides the verdict.
+Writes /logs/verifier/reward.txt (1/0) and a numeric-only reward.json, and copies the evidence (replay video, last
+frame, the replay's summary, event log) next to them for humans.
+infra_error = 1: no verdict on the agent (the service crashed past its restarts, failed to resume, ended on a simulator
+error, never finished, or failed to finalize; PROTOCOL §4b).
+"""
+import json
+import math
+import os
+import shutil
+import traceback
+
+DATA = os.environ.get("RCB_DATA", "/data")
+LOG = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")
+os.makedirs(LOG, exist_ok=True)
+
+
+def write(ok: bool, out: dict) -> None:
+ with open(os.path.join(LOG, "reward.txt"), "w") as f:
+ f.write("1\n" if ok else "0\n")
+ with open(os.path.join(LOG, "reward.json"), "w") as f:
+ json.dump(out, f)
+ print(json.dumps(out))
+
+
+def num(x, default=0.0) -> float:
+ try:
+ x = float(x)
+ except (TypeError, ValueError):
+ return default
+ return x if math.isfinite(x) else default
+
+
+def match_fields() -> dict:
+ """Information from the replay's summary (numbers only); {} if there is none."""
+ try:
+ with open(os.path.join(DATA, "match.json")) as f:
+ m = json.load(f)
+ except (OSError, ValueError):
+ return {}
+ return {"match_finished": int(bool(m.get("finished"))), "match_won": int(bool(m.get("won"))),
+ "points_for": num(m.get("points_for")), "points_against": num(m.get("points_against")),
+ "match_steps": int(num(m.get("match_steps"))), "breaks": len(m.get("breaks") or []),
+ "breaks_ended_by_ready": sum(1 for b in m.get("breaks") or [] if b.get("by") == "ready"),
+ "commands_applied": int(num(m.get("commands_applied"))),
+ "commands_refused": int(num(m.get("commands_refused")))}
+
+
+def main() -> None:
+ path = os.path.join(DATA, "final.json")
+ if not os.path.exists(path):
+ write(False, {"success": 0, "missing_log": 1, "infra_error": 1, "grader_error": 0})
+ return
+ try:
+ with open(path) as f:
+ d = json.load(f)
+ live, replay, det = (bool(d.get(k)) for k in ("live_success", "replay_success", "deterministic"))
+ failed_finalize = bool(d.get("finalize_error"))
+ unfinished = not d.get("finalized")
+ sim_error = d.get("reason") == "error"
+ infra = bool(d.get("infra_error")) or failed_finalize or unfinished or sim_error
+ ok = live and replay and det and not infra
+ out = {"success": int(ok), "live_success": int(live), "replay_success": int(replay), "deterministic": int(det),
+ "finalized": int(not unfinished), "missing_log": 0, "infra_error": int(infra),
+ "sim_error": int(sim_error), "grader_error": int(failed_finalize),
+ "timeout": int(d.get("reason") == "timeout"),
+ "n_actions": int(num(d.get("n_actions"))), "control_steps": int(num(d.get("control_steps_total"))),
+ "calls": int(num(d.get("calls"))), "rows": int(num(d.get("rows"))),
+ "reset_budget": int(num(d.get("reset_budget"))), "slowdown": num(d.get("slowdown")),
+ "max_lag_s": num(d.get("max_lag_s")), "stalls": int(num(d.get("stalls"))),
+ "late_steps": int(num(d.get("late_steps"))), "sim_startups": int(num(d.get("sim_startups"))),
+ "elapsed_s": num(d.get("elapsed_s")), "video_rendered": int(bool(d.get("video"))), **match_fields()}
+ except Exception: # noqa: BLE001 -- an unreadable final.json is the grader's failure, not the agent's
+ traceback.print_exc()
+ write(False, {"success": 0, "missing_log": 0, "infra_error": 1, "grader_error": 1})
+ return
+ for name in ("replay.mp4", "replay.last.png", "match.json", "episode.jsonl"):
+ try:
+ if os.path.exists(os.path.join(DATA, name)):
+ shutil.copy(os.path.join(DATA, name), os.path.join(LOG, name))
+ except OSError:
+ traceback.print_exc()
+ write(ok, out)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/roboolympics-airhockey-match-i00-standard-realtime/tests/test.sh b/tasks/roboolympics-airhockey-match-i00-standard-realtime/tests/test.sh
new file mode 100755
index 0000000000..75622ada21
--- /dev/null
+++ b/tasks/roboolympics-airhockey-match-i00-standard-realtime/tests/test.sh
@@ -0,0 +1,5 @@
+#!/bin/bash
+# Verifier (separate sandbox): the sim sidecar's artifacts were uploaded to /data by Harbor.
+mkdir -p /logs/verifier
+rm -rf /logs/verifier/*
+python /tests/grade.py 2> /logs/verifier/grade.log
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/README.md b/tasks/roboolympics-badminton-match-i00-standard-realtime/README.md
new file mode 100644
index 0000000000..4004309783
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/README.md
@@ -0,0 +1,57 @@
+# roboolympics-badminton-match-i00-standard-realtime
+
+| | |
+|---|---|
+| Benchmark | RoboOlympics |
+| Mode | standard-realtime (`eai-standard/2.3`) |
+| Twin | — (none: RoboOlympics is standard-realtime only, PROTOCOL §4b) |
+| Simulator / robot | `mujoco` / `franka-panda` |
+| Family / instance | `badminton_match` / seed 101 |
+| Oracle | `full` — solution/: the sport's RoboOlympics reference player (camera images, proprio and /spec only) through the agent's client; it wins this instance (PR #106) |
+| Agent time budget | 7200 s; tokens: protocol default (PROTOCOL §5) |
+| Base image | `ghcr.io/mll-lab-nu/eai-olympiad:0.2.0` |
+
+## Task
+RoboOlympics badminton (`badminton-match-wallclock-program-standard`), one match against the scripted opponent (level 1, frozen seed
+101), in standard-realtime mode (`eai-standard/2.3`, PROTOCOL §4b): the robot as a service on a clock that does
+not stop. The sport runs in the `sim` sidecar (`environment/docker-compose.yaml`; `environment/sim/rcb_realtime.py`
+runs the clock, `environment/sim/rcb_olympics.py` is the RoboOlympics adapter, `environment/sim/sport/` the sport's
+simulator, referee and opponent), which records every command at the control step it took effect, replays the match in
+a fresh process and renders the replay video; the verifier grades the sidecar's record in a container of its own
+(`tests/Dockerfile`, no network).
+
+## Difficulty
+The agent sees the game only through cameras and has no simulator of its own. A point is decided in a few seconds of
+game time, faster than a model's turn even at S = 10, so the agent has to write a perception and control
+program (find the shuttle in the images, fit its flight, choose and time the command) that plays by itself, and
+improve it between points and during the match. The opponent returns every ball it can reach; level 1 of
+the sport's levels.
+
+## Reference solution
+`solution/oracle_play.py` runs the sport's RoboOlympics reference player (`solution/builtin_players.py`: camera images,
+the proprio columns and `/spec` only; perception by colour, triangulation, a fitted flight model, the sport's contact
+law) through the agent's own client; it wins this instance (PR #106).
+
+## Verification
+`success` = live success (the match finished and the agent won it) ∧ replay success ∧ deterministic (the fresh-process
+replay of the recorded commands ends in the live run's state), computed in the sidecar. The record is
+`trajectory_live.f64` (per control step: the id of the command that took effect, -1 for none, and the `ready` flag) with
+`commands.jsonl` (the commands as the sport's action layer lowered them), so the replay re-applies what the live match
+applied, whatever the timing; `ticks.f64`, `calls.jsonl` and `submitted.f64` record the timing and every call, and
+`final.json` the clock's lag (`max_lag_s`, `stalls`). `match.json` is the replay's summary (score, breaks, commands).
+`tests/grade.py` reads `/data/final.json` and copies the evidence to `/logs/verifier/` (`replay.mp4`). A simulator
+crash or error is an infrastructure failure (`infra_error = 1`), not the agent's (PROTOCOL §4b). `nop` scores 0: the
+match never starts.
+
+Generated by `scripts/roboolympics/gen_tasks.py` from `tasks.toml`, `sports.toml`, `templates/` and `shared/` (the
+RoboOlympics simulator code, CHIGUI0/roboolympics 596d551a862c4236e74aea2beb25654b9783f9a7 (branch upstream-export, core 0.2.13)); do not edit by hand.
+
+## Details
+| | |
+|---|---|
+| sport | You play robot singles badminton (BWF rules with the deviations below) against a scripted opponent: a MuJoCo Franka Panda on a 1 m pedestal whose base slides on rails, holding a racket, seen only through two cameras. Rally scoring; you serve the first point, then the winner of each rally serves. One game to 5 points. |
+| time | S = 10 (RoboOlympics' official slowdown; `RCB_SLOWDOWN` overrides it, results under another S are reported separately): one 10 ms control step every 0.1 s of wall time; the match starts paused and its clock starts at the first `submit` or `get_obs(seconds > 0)`; after every point a break of 12 s of game time (120 s of wall time) in which the clock runs on and nothing plays, ended early by the agent's `ready` row |
+| actions | `stroke`, `toss`, `rest`, `ready`: the sport's own commands (action level `high`), one per row, effective at the row's control step |
+| observation | camera images and the agent's own robot plus the referee's information as proprio columns; no ball or opponent state, no seed |
+| budget | 7200 s, no reset (one match is the episode), no privileged twin (PROTOCOL §4b exceptions, `docs/benchmarks/roboolympics.md`) |
+| agent API | `environment/rcb_client.py` (the realtime client); `instruction.md` documents the commands, the proprio columns and the cameras |
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/Dockerfile b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/Dockerfile
new file mode 100644
index 0000000000..36d483206f
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/Dockerfile
@@ -0,0 +1,10 @@
+# Standard-realtime mode: the agent container has no simulator and no RoboOlympics code -- only Python, the client and
+# OpenCV (RoboOlympics' player image).
+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f
+COPY client-requirements.txt /tmp/
+RUN pip install --no-cache-dir -r /tmp/client-requirements.txt
+RUN pip install --no-cache-dir -c /tmp/client-requirements.txt opencv-python-headless==5.0.0.93 && pip check
+COPY rcb_client.py rcb1.py /opt/tools/
+ENV PYTHONPATH=/opt/tools
+RUN mkdir -p /app/output
+WORKDIR /app
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/client-requirements.txt b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/client-requirements.txt
new file mode 100644
index 0000000000..8aa73a968f
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/client-requirements.txt
@@ -0,0 +1,11 @@
+# Exact pins for what the standard agent container installs (and a verifier, if it installs anything): the closure of
+# `pip install requests numpy pillow scipy`, the unpinned line of every standard task at 9eb18edf, resolved on
+# 2026-10-01 in CLIENT_IMAGE (client.env: Python 3.12.14, pip 25.0.1). A change here is a shared-files PR.
+certifi==2026.7.22
+charset-normalizer==3.5.2
+idna==3.20
+numpy==2.5.3
+pillow==12.3.0
+requests==2.34.2
+scipy==1.18.1
+urllib3==2.8.0
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/docker-compose.yaml b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/docker-compose.yaml
new file mode 100644
index 0000000000..2ef2c8ca8b
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/docker-compose.yaml
@@ -0,0 +1,35 @@
+# Standard-realtime mode (PROTOCOL §4b): RoboOlympics badminton runs in the `sim` sidecar (the agent cannot open it), on
+# its own clock once the match starts (sim/rcb_realtime.py, the adapter sim/rcb_olympics.py); the agent only reaches
+# port 8000. No `expose`/`ports` on sim: under Harbor's egress control it shares main's network namespace
+# (localhost:8000). CPU only: MuJoCo physics and OSMesa rendering (the players' meshes come with the image).
+services:
+ main:
+ depends_on: [sim]
+ sim:
+ image: ghcr.io/mll-lab-nu/eai-olympiad:0.2.0
+ volumes:
+ - ./sim:/srv:ro
+ command: python /srv/rcb_realtime.py
+ restart: on-failure:6 # a crash resumes the same match, paused, never a reset
+ cpus: 6
+ mem_limit: 8g
+ pids_limit: 256
+ environment:
+ RO_PLUGIN: /srv/sport/plugin.py
+ RO_SPORT: badminton
+ RO_FORMAT: match-wallclock
+ RO_SEED: "101"
+ RO_LEVEL: "1"
+ RO_ACTION_LEVEL: high
+ RO_TASK_TEXT: "Win a game of singles badminton against the scripted opponent: serve, and return its shots into its court."
+ RO_EPISODE_TEXT: "Ends when the game is decided (first to 5 points, from 4-4 by 2, at most 7; or a player disqualified; success: you won), when your time is up (timeout), or on a simulator error."
+ RCB_WALL_CLOCK_S: "7200"
+ # Knobs: ${NAME:-default} takes NAME from the shell that runs harbor. The defaults are the official
+ # configuration; results under other settings are reported separately.
+ RCB_SLOWDOWN: "${RCB_SLOWDOWN:-10}" # 10: RoboOlympics' official slowdown (PROTOCOL §4b exception); results state S
+ RCB_RESET_BUDGET: "${RCB_RESET_BUDGET:-0}" # 0: one match is one episode (PROTOCOL §4b, the mode's default)
+ MUJOCO_GL: osmesa
+ PYOPENGL_PLATFORM: osmesa
+ LP_NUM_THREADS: "2"
+ OMP_NUM_THREADS: "1"
+ OPENBLAS_NUM_THREADS: "1"
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/rcb1.py b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/rcb1.py
@@ -0,0 +1,83 @@
+"""RCB1 — a tiny binary frame for one JSON header plus N raw blobs (videos, image arrays, depth, proprio).
+
+ frame = b"RCB1" | header_len uint32 LE | header JSON (UTF-8) | blob_0 | blob_1 | ...
+ header = {"v": 1, "meta": {...}, "parts": [{"name", "kind", "len", ...}, ...]} # blobs in the same order
+
+kinds: "mp4" (fps, n), "jpeg", "array" (dtype, shape; C-order raw bytes), "json" (utf-8), "bytes".
+Zero dependencies for bytes/json parts; numpy only when you ask for arrays. Used on both sides (server and client),
+over HTTP bodies (Content-Type: application/x-rcb1) and equally usable over a raw socket. `python -m rcb1 unpack f dir`.
+"""
+from __future__ import annotations
+import json, struct, sys, pathlib
+
+MAGIC = b"RCB1"
+
+
+def encode(meta: dict, parts: list[tuple[str, str, bytes, dict]]) -> bytes:
+ """parts: [(name, kind, blob, extra), ...]; extra carries dtype/shape/fps/n."""
+ hdr_parts = []
+ for name, kind, blob, extra in parts:
+ d = {"name": name, "kind": kind, "len": len(blob)}
+ d.update({k: v for k, v in (extra or {}).items() if v is not None})
+ hdr_parts.append(d)
+ header = json.dumps({"v": 1, "meta": meta, "parts": hdr_parts}, separators=(",", ":")).encode()
+ return b"".join([MAGIC, struct.pack("<I", len(header)), header] + [blob for _, _, blob, _ in parts])
+
+
+def array_part(name: str, arr, extra: dict | None = None) -> tuple[str, str, bytes, dict]:
+ import numpy as np
+ a = np.ascontiguousarray(arr)
+ return (name, "array", a.tobytes(), {"dtype": str(a.dtype), "shape": list(a.shape), **(extra or {})})
+
+
+def decode(buf: bytes, arrays: bool = True) -> tuple[dict, dict]:
+ """-> (meta, parts) where parts[name] = {"kind", ..., "data"}; arrays become numpy arrays when arrays=True."""
+ if buf[:4] != MAGIC:
+ raise ValueError("not an RCB1 frame")
+ n = struct.unpack("<I", buf[4:8])[0]
+ header = json.loads(buf[8:8 + n].decode()); off = 8 + n
+ out = {}
+ for p in header["parts"]:
+ blob = buf[off:off + p["len"]]; off += p["len"]
+ d = dict(p)
+ if p["kind"] == "array" and arrays:
+ import numpy as np
+ d["data"] = np.frombuffer(blob, dtype=np.dtype(p["dtype"])).reshape(p["shape"])
+ elif p["kind"] == "json":
+ d["data"] = json.loads(blob.decode())
+ else:
+ d["data"] = blob
+ out[p["name"]] = d
+ return header.get("meta", {}), out
+
+
+def unpack_to_dir(buf: bytes, out_dir: str) -> list[str]:
+ """Write a frame's parts as files: mp4/jpeg/bytes verbatim, arrays as .npy, meta as meta.json."""
+ import numpy as np
+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)
+ meta, parts = decode(buf, arrays=True); written = []
+ (out / "meta.json").write_text(json.dumps(meta, indent=1)); written.append("meta.json")
+ for name, p in parts.items():
+ safe = name.replace("/", "__")
+ if p["kind"] == "array":
+ f = out / f"{safe}.npy"; np.save(f, p["data"])
+ elif p["kind"] == "mp4":
+ f = out / f"{safe}.mp4"; f.write_bytes(p["data"])
+ elif p["kind"] == "jpeg":
+ f = out / f"{safe}.jpg"; f.write_bytes(p["data"])
+ elif p["kind"] == "json":
+ f = out / f"{safe}.json"; f.write_text(json.dumps(p["data"], indent=1))
+ else:
+ f = out / f"{safe}.bin"; f.write_bytes(p["data"])
+ written.append(f.name)
+ return written
+
+
+if __name__ == "__main__":
+ if len(sys.argv) == 4 and sys.argv[1] == "unpack":
+ print("\n".join(unpack_to_dir(open(sys.argv[2], "rb").read(), sys.argv[3])))
+ elif len(sys.argv) == 3 and sys.argv[1] == "info":
+ meta, parts = decode(open(sys.argv[2], "rb").read(), arrays=False)
+ print(json.dumps(meta, indent=1)); [print(n, {k: v for k, v in p.items() if k != "data"}) for n, p in parts.items()]
+ else:
+ print(__doc__)
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/rcb_client.py b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/rcb_client.py
new file mode 100644
index 0000000000..f2b0559bf9
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/rcb_client.py
@@ -0,0 +1,209 @@
+"""eai-standard/2.3 client (standard-realtime mode): your whole interface to the robot (installed at /opt/tools/rcb_client.py, on
+PYTHONPATH).
+
+ from rcb_client import Robot, EpisodeOver
+ r = Robot() # finds the service (SIM_URL, http://sim:8000, http://localhost:8000), waits until it is ready
+
+TIME DOES NOT STOP (spec()["timing"]). An episode starts paused; its clock starts at its first submit() or
+get_obs(seconds > 0) (again after every reset()) and from then on runs one control step every spec()["control_dt"] x
+spec()["timing"]["slowdown"] seconds of wall time, whether or not you call, until the episode ends. The service keeps a
+plan, one servo-target row per coming control step: submit() writes into it and answers at once; when the plan runs out
+the last target is held. Whatever you do in between -- think, print, run a model -- the robot keeps executing.
+
+Calls (each is one HTTP request; every answer that carries data is an RCB1 frame, decoded into a Result):
+ r.spec() GET /spec, fetched when connecting: the robot's facts. "action_types"
+ ("joint_position": dim, layout (actuator order), lower/upper, range_rad,
+ units, semantics), "control_dt" (0.02 s), "max_control_steps" (the
+ episode), "timing" (realtime, slowdown, max_ahead_steps), "cameras" {name:
+ rgb, depth, hw, fovy_deg, pose, mounted}, "proprio_layout" and "proprio"
+ (joints, axes, positions), "imu", "links" (masses, centres of mass, the
+ feet's boxes), "depth", "budget" {"reset", "wall_clock_s"}, "episode"
+ r.status() GET /status: calls, rows, control_steps, done, reason, elapsed_s, running,
+ planned_steps, lag_s (and episode, resets_left with a reset budget)
+ r.get_obs(cameras=None, seconds=0.0, video_fps=10, include_depth=False, video="frames")
+ POST /observe. seconds=0: the robot now, at once. seconds>0 (at most
+ spec()["max_watch_s"]): waits while that much robot time runs (starting the
+ clock if it is not running) and returns what the cameras saw; it never
+ changes the plan
+ r.submit("joint_position", actions, dt=None, interpolate="linear", at=None, cameras=None, video_fps=10,
+ video="none", include_depth=False, note="")
+ POST /submit: answers at once with the robot as it is now (the rows
+ have not run yet). actions (T, dim): rows dt apart (a multiple of
+ control_dt, the default; T x dt at most spec()["max_chunk_s"]); each step's
+ target is the row (interpolate="hold") or a straight line from the previous
+ row's ("linear", starting from the target in force just before `at`). They
+ become the plan from control step `at` (an episode step number; None = the
+ next step), replacing whatever was planned from `at` on and keeping what is
+ planned before it; at most spec()["timing"]["max_ahead_steps"] ahead. Rows
+ for steps already gone when the request arrives are dropped
+ (meta["late_steps"]). The first submit of an episode starts its clock
+ r.reset(cameras=None, include_depth=False)
+ POST /reset, only when spec()["budget"]["reset"] > 0: abandons the
+ running episode and starts a new one, paused, from the same starting state;
+ only the last episode is graded, and a success ends the trial
+
+cameras=None means every camera in spec()["cameras"]; cameras=[] means no images at all, only proprioception (the
+fastest call: what a controller loop wants). video: "mp4" (one H.264 file per camera), "frames" (the images as arrays),
+"both" or "none" (only the last frame); a submit returns no video (no time passes inside it). include_depth adds depth
+for the cameras that have it.
+
+Result (what get_obs / submit / reset return):
+ res.meta dict: calls, rows, control_steps (steps run in this episode: the next one is this number),
+ sim_time_s, time_s, time_left_s, proprio {"layout", "now"}, done, reason ("success" |
+ "failed" | "timeout" | "error"; None while the episode runs), running, planned_steps,
+ lag_s; per submit: start_step, late_steps, plan_end_step, clipped [{row, index, reason}]
+ (values outside [-1, 1] are clipped, not refused); with a reset budget also episode,
+ resets_left
+ res.last[cam] uint8 H x W x 3: the last frame (unless cameras=[])
+ res.frames[cam] uint8 N x H x W x 3 (get_obs, video="frames"/"both") res.video[cam] mp4 bytes
+ res.depth[cam] float16 N x H x W, metres, 0 = nothing in range (include_depth)
+ res.proprio float32 rows of spec()["proprio_layout"]: one at the call's start, one every 1/video_fps s
+ of a watch, one at its end
+ res.done the episode is over
+ res.save(dir) meta.json, <cam>.mp4, last/<cam>.jpg, frames/<cam>/NNN.jpg, depth_<cam>.npy, proprio.npy
+
+Errors: ValueError -- refused, nothing changed (400: wrong type or shape, NaN, a bad dt or at, too many frames, an
+unknown camera; or a request over 64 MB, refused before it is sent); EpisodeOver -- the episode, or the trial, is over
+(409); RuntimeError -- the service failed (5xx: see spec()["on_service_error"]) or the endpoint does not exist in this
+run (404).
+"""
+from __future__ import annotations
+
+import json
+import os
+import pathlib
+import time
+
+import numpy as np
+import requests
+
+import rcb1
+
+PROTOCOLS = ("eai-standard/2.", "rcb-limited/2.") # any 2.x service, under either name (rcb-limited is the old one)
+MAX_BODY = 64 * 1024 * 1024 # the protocol's request limit: a larger request is refused
+
+
+class EpisodeOver(RuntimeError):
+ pass
+
+
+class Result:
+ """A decoded RCB1 answer: meta, video, frames, last, depth, proprio; save(dir) writes them all out."""
+
+ def __init__(self, meta: dict, parts: dict):
+ self.meta, self.raw = meta, parts
+ self.video, self.frames, self.last, self.depth, self.proprio = {}, {}, {}, {}, None
+ for name, p in parts.items():
+ kind, data = p["kind"], p["data"]
+ if name.startswith("video/") and kind == "mp4":
+ self.video[name[6:]] = data
+ elif name.startswith("frames/"):
+ self.frames[name[7:]] = data
+ elif name.startswith("last/"):
+ self.last[name[5:]] = data
+ elif name.startswith("depth/"):
+ self.depth[name[6:]] = data
+ elif name == "proprio":
+ self.proprio = data
+
+ @property
+ def done(self) -> bool:
+ return bool(self.meta.get("done"))
+
+ def save(self, out_dir: str) -> str:
+ from PIL import Image
+ out = pathlib.Path(out_dir)
+ out.mkdir(parents=True, exist_ok=True)
+ (out / "meta.json").write_text(json.dumps(self.meta, indent=1))
+ for cam, b in self.video.items():
+ (out / f"{cam}.mp4").write_bytes(b)
+ for cam, img in self.last.items():
+ (out / "last").mkdir(exist_ok=True)
+ Image.fromarray(np.ascontiguousarray(img)).save(out / "last" / f"{cam}.jpg", quality=90)
+ for cam, arr in self.frames.items():
+ d = out / "frames" / cam
+ d.mkdir(parents=True, exist_ok=True)
+ for i, f in enumerate(arr):
+ Image.fromarray(np.ascontiguousarray(f)).save(d / f"{i:03d}.jpg", quality=85)
+ for cam, arr in self.depth.items():
+ np.save(out / f"depth_{cam}.npy", arr)
+ if self.proprio is not None:
+ np.save(out / "proprio.npy", self.proprio)
+ return str(out)
+
+
+class Robot:
+ def __init__(self, base: str | None = None, timeout: float = 600.0):
+ candidates = [c for c in (base or os.environ.get("SIM_URL"), "http://sim:8000", "http://localhost:8000") if c]
+ t0, last = time.time(), None
+ while time.time() - t0 < timeout:
+ for b in candidates:
+ try:
+ r = requests.get(b + "/spec", timeout=(5, 60))
+ if r.status_code == 503:
+ last = "warming up"
+ continue
+ r.raise_for_status()
+ self.base, self._spec = b, r.json()
+ if not str(self._spec.get("protocol", "")).startswith(PROTOCOLS):
+ raise RuntimeError(f"not an eai-standard/2.x service: {self._spec.get('protocol')}")
+ return
+ except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e:
+ last = e # not up yet (the scene takes about a minute), or busy
+ time.sleep(2)
+ raise RuntimeError(f"sim service unavailable: {last}")
+
+ def spec(self) -> dict:
+ return self._spec
+
+ def status(self) -> dict:
+ r = requests.get(self.base + "/status", timeout=(5, 60))
+ r.raise_for_status()
+ return r.json()
+
+ def get_obs(self, cameras=None, seconds: float = 0.0, video_fps: int = 10, include_depth: bool = False,
+ video: str = "frames") -> Result:
+ meta = {"cameras": _names(cameras), "seconds": float(seconds), "video_fps": int(video_fps),
+ "include_depth": bool(include_depth), "video": video}
+ return self._post("/observe", meta, [], timeout=900)
+
+ def submit(self, action_type: str, actions, dt: float | None = None, interpolate: str = "linear",
+ at: int | None = None, cameras=None, video_fps: int = 10, video: str = "none",
+ include_depth: bool = False, note: str = "") -> Result:
+ a = np.asarray(actions, dtype=np.float64)
+ if a.ndim == 1:
+ a = a[None, :]
+ if not np.all(np.isfinite(a)):
+ raise ValueError("actions contain NaN or inf")
+ meta = {"type": action_type, "dt": None if dt is None else float(dt), "interpolate": interpolate,
+ "at": None if at is None else int(at), "cameras": _names(cameras), "video_fps": int(video_fps),
+ "video": video,
+ "include_depth": bool(include_depth), "note": note}
+ return self._post("/submit", meta, [rcb1.array_part("actions", a)], timeout=1800)
+
+ def reset(self, cameras=None, include_depth: bool = False) -> Result:
+ return self._post("/reset", {"cameras": _names(cameras), "include_depth": bool(include_depth)}, [], timeout=900)
+
+ def _post(self, path: str, meta: dict, parts: list, timeout: float) -> Result:
+ body = rcb1.encode(meta, parts)
+ if len(body) > MAX_BODY: # the service would close the connection on it unread
+ raise ValueError(f"{path}: {len(body)} bytes, over the protocol's {MAX_BODY}: send fewer rows")
+ r = requests.post(self.base + path, data=body, headers={"Content-Type": "application/x-rcb1"},
+ timeout=(5, timeout))
+ if r.headers.get("Content-Type", "").startswith("application/x-rcb1") and r.status_code == 200:
+ return Result(*rcb1.decode(r.content))
+ try:
+ err = r.json()
+ except ValueError:
+ err = {"error": r.text[:300]}
+ msg = f"{r.status_code} {path}: {err.get('error')}" + (f" ({err['detail']})" if err.get("detail") else "")
+ if r.status_code == 409:
+ raise EpisodeOver(msg + (f"; reason {err['reason']}" if err.get("reason") else "")
+ + (f"; resets_left {err['resets_left']}" if "resets_left" in err else ""))
+ if r.status_code in (400, 413):
+ raise ValueError(msg)
+ raise RuntimeError(msg)
+
+
+def _names(cameras) -> list[str] | None:
+ return None if cameras is None else [cameras] if isinstance(cameras, str) else list(cameras)
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/core/README.md b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/core/README.md
new file mode 100644
index 0000000000..6d80cefa51
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/core/README.md
@@ -0,0 +1,18 @@
+# core/
+
+The match core (docs/framework_zh.md §5): it hosts every match under one set of rules and never names a sport or a
+harness. Version: `VERSION` in `__init__.py` (bump on every change; every sport's golden replay must still pass).
+
+| File | Contract / job |
+|---|---|
+| `sport.py` | ② the sport interface: `MatchConfig` (seats, sides, format, modes, renderer), `Phase`, `Refused`, `MatchBase` (the optional hooks and their defaults), `ActionLayer` / `LowLayer` / `SchemaLayer`, `check_command`; request validation (core 0.2.11): `check_body` (every request), `check_action` + `parse_action` (every act: any exception while reading an action is the player's 400, never a technical failure) |
+| `http.py`, `client.py`, `game.py` | ① the player protocol: the HTTP envelope (`/<seat>/<endpoint>`, limits), the client loop of built-in players, the generic `game` CLI |
+| `realtime.py`, `turn.py`, `service.py` | flow: `eai-standard-realtime/1.0` (slowdown, freeze and review, act pipeline, delayed effects, entities) and `eai-standard-turn/1.0` (turns, chess clocks, reviews); what both share (seats and sides, observations, team channel, retirement, final.json) |
+| `episode.py` | ③ the match record: `episode.jsonl` and the fresh-process replay (`python -m core.episode PLUGIN DIR`) |
+| `outcome.py`, `grading.py` | judgement: the no-draw chain, N-side ranking, solo scoring; the verifier (validity, reward fields, no-code audit hookup) |
+| `observe.py`, `channel.py`, `rng.py`, `spec.py` | the observation whitelist and camera tiles (through `renderers/`), the reply images of an action (`Match.reply_views`, core 0.2.8: snapshotted under the lock, drawn off it by the same camera worker, attached to the reply as `observation`), the team channel, random streams by name, sport.toml |
+| `seats.py`, `metering/` | per-seat counters, locks and chess clocks; the metering hookup (`think_clock.py`, `api_errors.py`: byte-identical copies); player modes (`PLAYER_MODE_<seat>`): `model` (metered by the seat's proxy, required for validity), `oracle` (exempt), `unmetered` (core 0.2.13: the runner meters the model itself, e.g. a plain Harbor with native agents; no proxy, no meter required) |
+| `spectator.py` | the broadcast log (`broadcast.jsonl`, the legacy writer copied as `spectator/broadcast_log.py`) and the replay video (`replay.mp4`, a fresh-process replay drawn by the spectator renderer); never read back |
+| final.json compatibility | `service.py` `COMPAT`: the sport's fields are lifted to the top level (unless a core field has the name) and `score` is set, so the Season-1 readers work; the sport fields also stay under `sport_fields` |
+| `workers.py`, `serve.py`, `launch.py` | worker processes (plan, render, camera), the service entry point, the launcher (one metering proxy per seat, none for an unmetered seat) |
+| `local.py`, `testkit.py`, `tests/` | in-process matches of built-in players, the generic test suite of every sport, the core's own tests |
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/core/__init__.py b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/core/__init__.py
new file mode 100644
index 0000000000..fd44c1d84c
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/core/__init__.py
@@ -0,0 +1,8 @@
+"""RoboOlympics match core (docs/framework_zh.md §5): hosts every match under one set of rules.
+
+Flow (clock, slowdown, freeze and review, seats and turns), rules (formats, modes), records (episode log, replay,
+metering) and judgement (outcome, validity). It names no sport and no harness (ci_checks/check-core-purity.sh), computes
+no physics, and changes only in its own commits with a version bump (VERSION) and every sport's golden replay passing.
+"""
+VERSION = "0.2.13"
+PROTOCOLS = {"realtime": "eai-standard-realtime/1.0", "turn": "eai-standard-turn/1.0"}
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/core/observe.py b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/core/observe.py
new file mode 100644
index 0000000000..94b46fc9b3
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/core/observe.py
@@ -0,0 +1,154 @@
+"""Observations (sport rule 1, docs/framework_zh.md §9): what a seat gets is the camera images, its own body and the
+referee's information, and nothing else. The sport declares the fields of Match.observe() in sport.toml
+([observation] fields); a field outside that whitelist is never delivered and is a technical error of the match.
+
+The camera images: Match.cameras(seat, query) returns camera definitions, the task's renderer (renderers/, chosen by
+the task parameter `renderer`) draws them from the sport's scene and Match.render_state(), and the core lays the
+images out as tiles of one PNG (left to right, `columns` per row), described in the reply (`tiles`).
+
+Reply images (core 0.2.8): Match.reply_views(seat, cmd, info) right after an action -> reply_job() snapshots the
+frames under the lock -> CameraWorker.draw_job() draws them off the lock (the same renderer, scene and worker as the
+observation) -> one PNG of tiles, each tile also naming its frame (`frame`, `label`) when there are several.
+
+The scene of the players' images (core 0.2.9, renderer rule 6): Sport.scene(cfg), or the presentation scene the sport
+declares for its players (sports/<sport>/presentation/presentation.toml `players`, bundled into the simulator by the
+generator; renderers/presentation.players_scene): the same kinematics, finer visual meshes. Any other presentation
+scene is refused (spectators only)."""
+from __future__ import annotations
+
+import copy
+import struct
+import zlib
+from pathlib import Path
+
+import numpy as np
+
+
+class WhitelistError(Exception):
+ pass
+
+
+def filter_fields(obs: dict, allowed: set[str] | None) -> tuple[dict, list[str]]:
+ """(the whitelisted part of obs, the names that were not allowed)."""
+ if allowed is None:
+ return obs, []
+ bad = sorted(k for k in obs if k not in allowed)
+ return {k: v for k, v in obs.items() if k in allowed}, bad
+
+
+def png(img: np.ndarray) -> bytes:
+ """A minimal RGB8 PNG encoder (no imaging library needed in the sim)."""
+ img = np.ascontiguousarray(img, dtype=np.uint8)
+ h, w = img.shape[:2]
+ raw = b"".join(b"\x00" + img[y].tobytes() for y in range(h))
+
+ def chunk(tag, data):
+ return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
+
+ return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0))
+ + chunk(b"IDAT", zlib.compress(raw, 6)) + chunk(b"IEND", b""))
+
+
+def reply_job(m, spec: dict | None, columns: int) -> dict | None:
+ """Under the lock: Match.reply_views()'s answer -> a self-contained draw job (deep copies: the match may move on
+ while the job is drawn off the lock). A frame without a state gets render_state() now."""
+ if not spec or not spec.get("frames"):
+ return None
+ order = spec.get("order", "frame")
+ if order not in ("frame", "camera"):
+ raise ValueError(f"reply_views: order must be 'frame' or 'camera', not {order!r}")
+ now = None
+ frames = []
+ for f in spec["frames"]:
+ st = f.get("state")
+ if st is None:
+ now = m.render_state() if now is None else now
+ st = now
+ cams = list(f.get("cameras") or [])
+ if not cams:
+ raise ValueError("reply_views: every frame needs at least one camera")
+ frames.append({"state": st, "cams": cams, "label": f.get("label")})
+ return copy.deepcopy({"frames": frames, "order": order, "columns": int(spec.get("columns") or columns),
+ "note": spec.get("note")})
+
+
+def compose(images: list[np.ndarray], names: list[str], columns: int = 2) -> tuple[np.ndarray, list[dict]]:
+ """Tiles left to right, `columns` per row, each at its own size; -> (sheet, [{camera, x, y, width, height}])."""
+ rows = [list(range(i, min(i + columns, len(images)))) for i in range(0, len(images), columns)]
+ widths = [sum(images[j].shape[1] for j in r) for r in rows]
+ heights = [max(images[j].shape[0] for j in r) for r in rows]
+ sheet = np.zeros((sum(heights), max(widths), 3), np.uint8)
+ tiles, y = [], 0
+ for r, hgt in zip(rows, heights):
+ x = 0
+ for j in r:
+ h, w = images[j].shape[:2]
+ sheet[y:y + h, x:x + w] = images[j][..., :3]
+ tiles.append({"camera": names[j], "x": x, "y": y, "width": w, "height": h})
+ x += w
+ y += hgt
+ return sheet, tiles
+
+
+def players_scene(sport, plugin: str, cfg):
+ """The scene of the players' images: the sport's presentation scene when it declares `players`, else
+ Sport.scene(cfg)."""
+ scene = sport.scene(cfg)
+ d = Path(plugin).resolve().parent
+ if not (d / "presentation" / "presentation.toml").is_file():
+ return scene
+ from renderers import presentation
+ return presentation.players_scene(d, scene)
+
+
+class CameraWorker:
+ """Draws a seat's camera definitions with the task's renderer (in-process or inside a render worker process)."""
+
+ def __init__(self, scene, renderer_name: str | None):
+ import renderers
+ if getattr(scene, "match", None) is not None and not getattr(scene, "players", False):
+ raise ValueError("the players' images are drawn from the match scene (Sport.scene) or the presentation "
+ "scene the sport declares for them; any other presentation scene is for spectators only "
+ "(renderer rule 6)")
+ self.name = renderer_name or renderers.DEFAULT
+ self.renderer = renderers.load(self.name)(scene)
+
+ def draw(self, state: dict, cams: list[dict], columns: int = 2) -> dict:
+ from renderers.base import CameraDef
+ defs = [CameraDef.from_dict(c) for c in cams]
+ images = self.renderer.render(state, defs)
+ sheet, tiles = compose(images, [c.name for c in defs], columns)
+ return {"png": png(sheet), "tiles": tiles, "renderer": self.name}
+
+ def draw_frames(self, job: dict) -> dict:
+ """A reply job (reply_job()): every frame's cameras drawn from that frame's state, laid out frame after
+ frame or camera after camera; a tile names its camera, and its frame (index, label) when there are several."""
+ from renderers.base import CameraDef
+ frames = job["frames"]
+ drawn = [] # per frame: [(name, image)]
+ for f in frames:
+ defs = [CameraDef.from_dict(c) for c in f["cams"]]
+ drawn.append(list(zip([c.name for c in defs], self.renderer.render(f["state"], defs))))
+ cells = [] # (frame index, camera name, image)
+ if job.get("order") == "camera":
+ for j in range(max(len(d) for d in drawn)):
+ cells += [(i, d[j][0], d[j][1]) for i, d in enumerate(drawn) if j < len(d)]
+ else:
+ cells = [(i, name, img) for i, d in enumerate(drawn) for name, img in d]
+ sheet, tiles = compose([c[2] for c in cells], [c[1] for c in cells], int(job.get("columns", 2)))
+ many = len(frames) > 1
+ for t, (i, _, _) in zip(tiles, cells):
+ if many:
+ t["frame"] = i
+ if frames[i].get("label"):
+ t["label"] = frames[i]["label"]
+ out = {"png": png(sheet), "tiles": tiles, "renderer": self.name}
+ if job.get("note"):
+ out["note"] = job["note"]
+ return out
+
+ def draw_job(self, job: dict) -> dict:
+ """Any job of the core's camera worker: a reply job (frames) or an observation (state + cameras)."""
+ if "frames" in job:
+ return self.draw_frames(job)
+ return self.draw(job["state"], job["cams"], job.get("columns", 2))
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/core/outcome.py b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/core/outcome.py
new file mode 100644
index 0000000000..11916961f2
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/core/outcome.py
@@ -0,0 +1,50 @@
+"""The no-draw decision chain (docs/framework_zh.md §5): a forfeit (a core decision: review or clock time, abandonment,
+or a side that never started, "no_show"; sides that retired before it rank last, the last to retire first), then the
+sport's tiebreaks in order (rulebook result -> rulebook tiebreak -> capped extra play -> last resort; the last one must
+decide). A match with more than two sides is decided by the sport's classification (Match.ranking, best first). A solo
+match (single format without an opponent: tiebreaks() == []) has no winner; its result is the score against the
+success line. A match that did not finish has no winner."""
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+from .sport import FINISHED
+
+
+@dataclass
+class Outcome:
+ winner: str | None
+ decided_by: str
+ scores: dict
+ ranking: list = field(default_factory=list)
+ solo: bool = False
+
+
+def decide(match, forfeit_seat: str | None = None, why: str | None = None, sides=("A", "B"),
+ side_of=lambda s: s, retired=()) -> Outcome:
+ scores = match.scores()
+ sides = list(sides)
+ rules = match.tiebreaks()
+ solo = len(sides) == 1 and not rules
+ if forfeit_seat is not None:
+ lost = side_of(forfeit_seat)
+ others = [s for s in sides if s != lost and s not in retired]
+ if len(others) == 1:
+ return Outcome(others[0], f"forfeit:{why}", scores, others + [lost] + list(reversed(retired)))
+ if not others and len(sides) == 1: # a single player who forfeits loses (to the line or the opponent)
+ return Outcome(None, f"forfeit:{why}", scores, [], solo)
+ if match.phase().state != FINISHED:
+ return Outcome(None, "unfinished", scores, [], solo)
+ if solo:
+ return Outcome(None, "score", scores, list(sides), True)
+ if len(sides) > 2:
+ ranking = list(match.ranking() or [])
+ if sorted(ranking) != sorted(sides):
+ raise RuntimeError("a match of more than two sides must rank every side (Match.ranking)")
+ return Outcome(ranking[0], "ranking", scores, ranking)
+ for name, rule in rules:
+ w = rule(match)
+ if w is not None:
+ rest = [s for s in sides if s != w]
+ return Outcome(w, name, scores, [w] + rest)
+ raise RuntimeError("a finished match must be decided by its last tiebreak (no draws)")
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/core/spec.py b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/core/spec.py
new file mode 100644
index 0000000000..9cc5599b5c
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/core/spec.py
@@ -0,0 +1,20 @@
+"""The sport's declarations (sport.toml next to its plugin.py, docs/framework_zh.md §4.2): data, read by the core
+(observation whitelist, team channel, success line, timing), the generator, the checks and the documentation."""
+from __future__ import annotations
+
+import os
+import tomllib
+from pathlib import Path
+
+
+def load(plugin_path: str | os.PathLike) -> dict:
+ p = Path(plugin_path)
+ p = p / "sport.toml" if p.is_dir() else p.with_name("sport.toml")
+ if not p.exists():
+ return {}
+ return tomllib.loads(p.read_text())
+
+
+def whitelist(decl: dict) -> set[str] | None:
+ fields = (decl.get("observation") or {}).get("fields")
+ return set(fields) if fields is not None else None
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/core/sport.py b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/core/sport.py
new file mode 100644
index 0000000000..a60647ec26
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/core/sport.py
@@ -0,0 +1,455 @@
+"""Contract ② (docs/framework_zh.md §4.2): the one interface between the core and a sport (sports/<sport>/).
+
+A sport's plugin module exports SPORT. The core calls only the functions below and never names a sport; a sport never
+imports another sport. A sport answers four questions, one group of functions each (10 required):
+
+ world Sport.build(cfg) -> Match Match.step() -> events Match.state_digest() -> hex
+ actions Match.schema(seat) Match.apply(seat, low_cmd) -> info
+ optional high-level plugin: Sport.action_layer(level) -> ActionLayer whose lower() turns a high-level
+ command into a low-level one (the episode log holds LOW-LEVEL commands only)
+ referee Match.phase() -> Phase Match.scores() -> {side: n} Match.tiebreaks() -> [(name, rule)]
+ optional: to_move(), forfeit(), resume(), retire(), ranking()
+ observation Match.observe(seat, query) -> dict (own body + referee information, whitelisted in sport.toml)
+ Match.cameras(seat, query) -> [camera definitions] (drawn by the task's renderer, renderers/)
+
+Optional hooks have defaults in MatchBase; none of them is required by every sport, and the core never branches on a
+sport. Stage-0 hooks (all optional): sides != seats (MatchConfig.sides, Match.entities: one act in flight per entity),
+N sides with a classification (Match.ranking) and in-match retirement (Match.retire), a delayed effect
+(ActionLayer.delay_steps), observation parameters (the `query` of observe/cameras), a team channel (core/channel.py,
+declared in sport.toml) and a scored single format without an opponent (tiebreaks() == []).
+
+Reply images (core 0.2.8, optional): Match.reply_views(seat, cmd, info) names the cameras (and optionally a short
+strip of frames) that show the result of an action; the core snapshots them under the lock right after the action
+took effect, draws them off the lock with the task's renderer (the path of the observation images) and attaches them
+to the action's reply as `observation` (image_png_b64 + tiles, as /observe). In the turn protocol the core also tells
+the sport whose review is due (Match.awaiting_review), so that a sport serving images only on turn can hold them
+back from the other seats while the actor reviews.
+
+Presentation (core 0.2.4, optional, spectators only): sports/<sport>/presentation/presentation.toml dresses the scene
+of Sport.scene(cfg) for spectator renderers (renderers/presentation; e.g. fine visual meshes on a robot's bodies,
+same kinematics). It is not part of the simulator directory and never reaches the players' images, unless the sport
+declares `players` there (core 0.2.9): then the generator bundles it (and the models' files) into the simulator and
+the players' images are drawn from it (core/observe.players_scene; a sport drawing its own images uses
+renderers.players_model).
+"""
+from __future__ import annotations
+
+import hashlib
+import json
+import math
+from dataclasses import asdict, dataclass, field, fields
+from typing import Any, Callable, Protocol
+
+
+@dataclass(frozen=True)
+class MatchConfig:
+ sport: str
+ format: str # single | duel | team | multi (the sport declares which it supports)
+ seats: tuple[str, ...] # e.g. ("A", "B"); the HTTP addresses /<seat>/<endpoint>
+ seed: int
+ first: str | None = None # the side that starts (serves / throws first; the rules say what that means)
+ slowdown: float | None = None # realtime only
+ level: int | None = None # scripted opponent level (single)
+ action_level: str = "high" # high | low
+ play: str = "program" # program | direct
+ params: dict = field(default_factory=dict)
+ sides: dict | None = None # seat -> side; default: every seat is its own side
+ renderer: str | None = None # the renderer of the players' images (renderers/; None = the default)
+
+ def side_of(self, seat: str) -> str:
+ return (self.sides or {}).get(seat, seat)
+
+ def side_list(self) -> list[str]:
+ out: list[str] = []
+ for s in self.seats:
+ if self.side_of(s) not in out:
+ out.append(self.side_of(s))
+ return out
+
+ def seats_of(self, side: str) -> list[str]:
+ return [s for s in self.seats if self.side_of(s) == side]
+
+ def to_json(self) -> dict:
+ d = asdict(self)
+ d["seats"] = list(self.seats)
+ return d
+
+ @staticmethod
+ def from_json(d: dict) -> "MatchConfig":
+ known = {f.name for f in fields(MatchConfig)}
+ return MatchConfig(**{**{k: v for k, v in d.items() if k in known}, "seats": tuple(d["seats"])})
+
+
+PLAYING, UNIT_OVER, FINISHED = "playing", "unit_over", "finished"
+
+
+@dataclass
+class Phase:
+ state: str # PLAYING | UNIT_OVER | FINISHED
+ review: tuple[str, ...] = () # seats that review before play resumes (realtime: usually all seats)
+ reason: str = ""
+
+
+class Refused(Exception):
+ """An action the core must refuse: HTTP `code` (400 bad body, 409 wrong time) with `message`."""
+
+ def __init__(self, message: str, code: int = 400):
+ super().__init__(message)
+ self.code = code
+ self.cause = "" # parse_action: the hidden exception (logs only)
+
+
+Tiebreak = tuple[str, Callable[["Match"], "str | None"]] # (name, rule) -> winning side or None (undecided)
+
+
+class Match(Protocol):
+ k: int # [R] control steps (realtime) / actions (turn) so far
+ dt: float # [R realtime] control step, seconds
+
+ # world
+ def step(self) -> list[dict]: ... # [R realtime] advance one control step; events
+ def state_digest(self) -> str: ... # [R] hex digest of everything that affects the score
+ # actions
+ def schema(self, seat: str) -> dict: ... # [R] the low-level command types and ranges (/spec)
+ def apply(self, seat: str, cmd: dict) -> dict: ... # [R] a LOW-LEVEL command takes effect now; info
+ # referee
+ def phase(self) -> Phase: ... # [R]
+ def scores(self) -> dict[str, float]: ... # [R] by side (informational: tiebreaks decide)
+ def tiebreaks(self) -> list[Tiebreak]: ... # [R] rulebook -> extra play -> last resort; [] = solo
+ # observation
+ def observe(self, seat: str, query: dict | None = None) -> dict: ... # [R] own body + referee information
+ def cameras(self, seat: str, query: dict | None = None) -> list[dict]: ... # [R] camera definitions (renderers/)
+
+
+class MatchBase:
+ """Defaults of every optional hook (a sport subclasses this and overrides what it needs)."""
+ k = 0
+ dt = 0.0
+ awaiting_review = None # turn protocol, set by the core: the seat whose review
+ # is due now (None: nobody's); never part of the digest
+
+ # referee
+ def resume(self) -> None: # leaving a review: frozen-time work (next serve ...)
+ pass
+
+ def to_move(self): # turn protocol: the seat whose turn it is
+ return None
+
+ def forfeit(self, seat, why) -> bool: # record a core decision inside the world (True)
+ return False
+
+ def retire(self, side, why) -> bool: # N sides: True = the match goes on without `side`
+ return False
+
+ def ranking(self): # N sides: the classification, best first
+ return None
+
+ def unit(self) -> int: # index of the current unit (acts of an old unit drop)
+ return 0
+
+ # actions
+ def schema(self, seat) -> dict:
+ return {}
+
+ def entities(self, seat) -> tuple[str, ...]: # what a seat commands; one act in flight per entity
+ return ()
+
+ # observation
+ def cameras(self, seat, query=None) -> list[dict]:
+ return []
+
+ def render_state(self) -> dict: # what a renderer needs to draw the scene now
+ return {}
+
+ def camera_job(self, seat): # a sport that draws its own images: (job, meta)
+ return None, {}
+
+ def reply_views(self, seat, cmd, info) -> dict | None:
+ """The images of an action's result for its reply (core 0.2.8), or None. Called under the lock right after
+ Match.apply(seat, cmd) returned `info` (realtime: only for an act without a delayed effect); it must not change
+ the match, and what it returns must follow from the match state and (seat, cmd, info) alone, so that a replay
+ can draw the same images (python -m core.episode PLUGIN DIR --reply N).
+ {"frames": [{"cameras": [camera definitions, as cameras()],
+ "state": render state (optional; default: render_state() now),
+ "label": short text (optional, e.g. "-200 ms"; shown in the tiles)}, ...],
+ "order": "frame" (default: frame after frame) | "camera" (camera after camera: one strip per camera),
+ "columns": tiles per row (default: sport.toml [observation] columns),
+ "note": one line for the player (optional)}
+ Drawn like the observation images: the task's renderer, the match scene (never a presentation scene),
+ sport.toml [observation] frame_budget_ms for the whole reply image."""
+ return None
+
+ def final_fields(self) -> dict: # sport fields for final.json
+ return {}
+
+ def broadcast_frame(self): # spectator frame (never read back)
+ return None
+
+
+class ActionLayer(Protocol):
+ level: str # "high" | "low"
+ worker: str | None # Sport worker kind that runs prepare(), or None
+ delay_steps: int # realtime: the effect is delay_steps after lowering
+
+ def parse(self, seat: str, body: dict, match: Match, ctx: dict) -> dict: ...
+ # validate a request body (raise Refused); ctx = core facts at the request (e.g. both chess clocks), which the
+ # plugin may copy into the command so that replay sees them
+ def snapshot(self, seat: str, cmd: dict, match: Match, ordinal: int) -> Any: ... # under the lock, for prepare
+ def prepare(self, job: Any) -> Any: ... # off the lock (in `worker` if set); expensive planning
+ def lower(self, seat: str, cmd: dict, prepared: Any, match: Match) -> tuple[dict, dict]: ...
+ # at the effect boundary, cheap: -> (low-level command for Match.apply, info for the reply)
+ def reply(self, seat: str, cmd: dict, info: dict, match: Match) -> dict: ...
+
+
+class LowLayer:
+ """The identity layer: the request body, validated by `validate(seat, body, match, ctx) -> cmd`, is the command."""
+ level = "low"
+ worker = None
+ delay_steps = 0
+
+ def __init__(self, validate):
+ self._validate = validate
+
+ def schema(self, match, seat): # what /spec shows of this layer's commands
+ return match.schema(seat)
+
+ def parse(self, seat, body, match, ctx):
+ return self._validate(seat, body, match, ctx)
+
+ def snapshot(self, seat, cmd, match, ordinal):
+ return None
+
+ def prepare(self, job):
+ return None
+
+ def lower(self, seat, cmd, prepared, match):
+ return cmd, {}
+
+ def reply(self, seat, cmd, info, match):
+ return info
+
+
+def check_command(schema: dict, body: dict) -> dict:
+ """Validate a request body against a Match.schema() and return the clean command (raises Refused).
+
+ schema = {TYPE: {FIELD: {"type": "number"|"integer"|"boolean"|"enum"|"vector", "min", "max", "values", "len",
+ "unit", "doc", "default"}}}; the command is {"type": TYPE, FIELD: value, ...}."""
+ if not isinstance(body, dict):
+ raise Refused("the action must be a JSON object")
+ kind = body.get("type")
+ if kind not in schema:
+ raise Refused(f"unknown action type {kind!r}; one of {sorted(schema)}")
+ out: dict = {"type": kind}
+ spec = schema[kind]
+ extra = sorted(set(body) - set(spec) - {"type", "entity"})
+ if extra:
+ raise Refused(f"unknown field(s) {extra} for {kind}")
+ for name, f in spec.items():
+ if name not in body:
+ if "default" in f:
+ out[name] = f["default"]
+ continue
+ raise Refused(f"{kind} needs {name}")
+ out[name] = _value(name, f, body[name])
+ if "entity" in body:
+ out["entity"] = str(body["entity"])
+ return out
+
+
+def _value(name, f, v):
+ t = f.get("type", "number")
+ if t == "boolean":
+ if not isinstance(v, bool):
+ raise Refused(f"{name} must be true or false")
+ return v
+ if t == "enum":
+ if v not in f["values"]:
+ raise Refused(f"{name} must be one of {f['values']}")
+ return v
+ if t == "vector":
+ if not isinstance(v, list) or len(v) != f["len"]:
+ raise Refused(f"{name} must be a list of {f['len']} numbers")
+ return [_number(f"{name}[{i}]", f, x) for i, x in enumerate(v)]
+ x = _number(name, f, v)
+ if t == "integer":
+ if x != int(x):
+ raise Refused(f"{name} must be an integer")
+ return int(x)
+ return x
+
+
+def _number(name, f, v):
+ if isinstance(v, bool) or not isinstance(v, (int, float)) or (isinstance(v, int) and v.bit_length() > 60) or \
+ not math.isfinite(v):
+ raise Refused(f"{name} must be a finite number")
+ lo, hi = f.get("min", -math.inf), f.get("max", math.inf)
+ if not lo <= v <= hi:
+ raise Refused(f"{name} must be in [{lo}, {hi}]")
+ return round(float(v), f.get("digits", 6))
+
+
+# ------------------------------------------------------------------ request validation (core 0.2.11)
+# Every request body is checked before an endpoint reads it (check_body), and every act body against the action
+# layer's published schema before the layer parses it (check_action). A body that fails, or that makes the layer's
+# parse raise ANY exception, is the player's own error: refused (HTTP 400, counted), never a technical failure.
+BODY_MAX_DEPTH = 10 # nesting of lists / objects (the body object is depth 1)
+BODY_MAX_ITEMS = 4096 # elements of one list, keys of one object
+BODY_MAX_STR = 8192 # characters of one string (keys included)
+BODY_MAX_ABS = 1e15 # |number|: no action of any sport needs more (and a huge integer overflows a float)
+TYPE_MAX_STR = 64 # characters of the action type
+
+
+def check_body(value, depth: int = 1) -> None:
+ """Generic sanity of a decoded JSON request body (raises Refused): finite, bounded numbers; bounded strings, list
+ lengths and nesting."""
+ if depth > BODY_MAX_DEPTH:
+ raise Refused(f"the request is nested deeper than {BODY_MAX_DEPTH} levels")
+ if value is None or isinstance(value, bool):
+ return
+ if isinstance(value, str):
+ if len(value) > BODY_MAX_STR:
+ raise Refused(f"strings are limited to {BODY_MAX_STR} characters")
+ return
+ if isinstance(value, int):
+ if value.bit_length() > 60 or abs(value) > BODY_MAX_ABS:
+ raise Refused(f"numbers are limited to +-{BODY_MAX_ABS:g}")
+ return
+ if isinstance(value, float):
+ if not math.isfinite(value) or abs(value) > BODY_MAX_ABS:
+ raise Refused(f"numbers must be finite and within +-{BODY_MAX_ABS:g}")
+ return
+ if isinstance(value, (list, dict)):
+ if len(value) > BODY_MAX_ITEMS:
+ raise Refused(f"lists and objects are limited to {BODY_MAX_ITEMS} items")
+ for k in value if isinstance(value, dict) else ():
+ if not isinstance(k, str) or len(k) > BODY_MAX_STR:
+ raise Refused("object keys must be strings")
+ for x in value.values() if isinstance(value, dict) else value:
+ check_body(x, depth + 1)
+ return
+ raise Refused("unsupported JSON value")
+
+
+def _is_num(v) -> bool:
+ return not isinstance(v, bool) and isinstance(v, (int, float))
+
+
+def _lens(spec_len) -> set | None:
+ """A field's declared length: an int, or a text such as "1 or 2" (None: not declared)."""
+ if isinstance(spec_len, int) and not isinstance(spec_len, bool):
+ return {spec_len}
+ if isinstance(spec_len, str):
+ return {int(x) for x in spec_len.replace(",", " ").split() if x.isdigit()} or None
+ return None
+
+
+def _check_field(kind: str, name: str, f, v) -> None:
+ """The shape of one declared field (ranges and meaning stay with the layer's parse)."""
+ if not isinstance(f, dict):
+ return
+ t, where = f.get("type", "number"), f"{kind}.{name}"
+ if t in ("number", "integer"):
+ if not _is_num(v):
+ raise Refused(f"{where} must be a number")
+ elif t == "boolean":
+ if not isinstance(v, bool):
+ raise Refused(f"{where} must be true or false")
+ elif t == "enum":
+ if isinstance(v, (list, dict)):
+ raise Refused(f"{where} must be one of {f.get('values')}")
+ elif t == "vector":
+ lens = _lens(f.get("len"))
+ if not isinstance(v, list) or (lens and len(v) not in lens) or not all(_is_num(x) for x in v):
+ raise Refused(f"{where} must be a list of {f.get('len', 'some')} numbers")
+ elif t == "rows":
+ lens, top = _lens(f.get("len")), f.get("max_rows")
+ if not isinstance(v, list) or (isinstance(top, int) and len(v) > top) or not all(
+ isinstance(r, list) and (not lens or len(r) in lens) and all(_is_num(x) for x in r) for r in v):
+ raise Refused(f"{where} must be a list of rows of {f.get('len', 'some')} numbers"
+ + (f", at most {top} rows" if isinstance(top, int) else ""))
+ elif t == "list":
+ if not isinstance(v, list):
+ raise Refused(f"{where} must be a list")
+ elif t == "object":
+ if not isinstance(v, dict):
+ raise Refused(f"{where} must be an object")
+ keys = f.get("keys")
+ if isinstance(keys, (list, tuple)) and set(v) - set(keys):
+ raise Refused(f"{where}: unknown key(s) {sorted(set(v) - set(keys))[:8]}; the keys are {list(keys)}")
+
+
+def check_action(schema, body) -> None:
+ """An act body against the action layer's published schema, before the layer parses it (raises Refused). The
+ type, if given, must be a short string; for a type the schema names, each declared field that is present must
+ have its shape (number, boolean, scalar enum value, vector / rows lengths, list, object keys). Unknown types and
+ fields, ranges and defaults stay with the layer's parse (a layer may take an implicit type)."""
+ if not isinstance(body, dict):
+ raise Refused("the action must be a JSON object")
+ kind = body.get("type")
+ if kind is not None and (not isinstance(kind, str) or len(kind) > TYPE_MAX_STR):
+ raise Refused(f"type must be a string of at most {TYPE_MAX_STR} characters")
+ spec = schema.get(kind) if isinstance(schema, dict) and kind is not None else None
+ if isinstance(spec, dict):
+ for name, f in spec.items():
+ if name in body:
+ _check_field(kind, name, f, body[name])
+
+
+def parse_action(layer, seat: str, body, match, ctx: dict):
+ """What the core runs for every act (and core.local for built-in players): check_body, check_action against the
+ layer's schema (what /spec shows), then layer.parse. ANY exception on the way is the player's own error: Refused
+ (HTTP 400); a malformed action never ends a match as a technical failure. The exception's text is not shown to
+ the player; the caller may log it (`Refused.cause`)."""
+ try:
+ check_body(body)
+ check_action(layer.schema(match, seat) if hasattr(layer, "schema") else {}, body)
+ return layer.parse(seat, body, match, ctx)
+ except Refused:
+ raise
+ except Exception as exc: # noqa: BLE001
+ err = Refused("invalid action: the action layer could not read it (see /spec for the command schema)")
+ err.cause = f"{type(exc).__name__}: {str(exc)[:200]}"
+ raise err from exc
+
+
+class SchemaLayer(LowLayer):
+ """The default low level: the body is checked against Match.schema(seat); `ctx_keys` copies core facts (e.g. the
+ chess clocks) into the command so that the replay sees them."""
+
+ def __init__(self, ctx_keys: tuple[str, ...] = ()):
+ super().__init__(None)
+ self.ctx_keys = ctx_keys
+
+ def parse(self, seat, body, match, ctx):
+ cmd = check_command(match.schema(seat), body)
+ ents = tuple(match.entities(seat))
+ if ents and cmd.get("entity", ents[0]) not in ents:
+ raise Refused(f"entity must be one of {list(ents)}")
+ if ents:
+ cmd.setdefault("entity", ents[0])
+ for k in self.ctx_keys:
+ cmd[k] = ctx.get(k)
+ return cmd
+
+
+class Sport(Protocol):
+ name: str
+ protocol: str # "realtime" | "turn"
+ revision: str # bump on any change that alters play
+ source_dirs: list[str] # whose files enter source_sha (the plugin dir; the core adds itself)
+
+ def build(self, cfg: MatchConfig) -> Match: ...
+ def action_layer(self, level: str) -> ActionLayer: ...
+ def spec(self, cfg: MatchConfig, seat: str, match: Match) -> dict: ...
+ # optional: the scene for renderers, worker processes (render / plan), built-in players
+ def scene(self, cfg: MatchConfig): ... # renderers.base.Scene (needed when cameras() is used);
+ # the MATCH scene: the base of the presentation scene
+ # (sports/<s>/presentation) and the players' images
+ # unless that declares `players`
+ def worker_init(self, kind: str, seat: str, cfg: MatchConfig) -> Any: ...
+ def worker_call(self, obj: Any, kind: str, job: Any) -> dict: ...
+ def players(self) -> dict: ... # {name: factory(spec, seat, seed) -> built-in player}
+
+
+def sha_json(value) -> str:
+ return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"), default=float).encode()).hexdigest()
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/rcb1.py b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/rcb1.py
@@ -0,0 +1,83 @@
+"""RCB1 — a tiny binary frame for one JSON header plus N raw blobs (videos, image arrays, depth, proprio).
+
+ frame = b"RCB1" | header_len uint32 LE | header JSON (UTF-8) | blob_0 | blob_1 | ...
+ header = {"v": 1, "meta": {...}, "parts": [{"name", "kind", "len", ...}, ...]} # blobs in the same order
+
+kinds: "mp4" (fps, n), "jpeg", "array" (dtype, shape; C-order raw bytes), "json" (utf-8), "bytes".
+Zero dependencies for bytes/json parts; numpy only when you ask for arrays. Used on both sides (server and client),
+over HTTP bodies (Content-Type: application/x-rcb1) and equally usable over a raw socket. `python -m rcb1 unpack f dir`.
+"""
+from __future__ import annotations
+import json, struct, sys, pathlib
+
+MAGIC = b"RCB1"
+
+
+def encode(meta: dict, parts: list[tuple[str, str, bytes, dict]]) -> bytes:
+ """parts: [(name, kind, blob, extra), ...]; extra carries dtype/shape/fps/n."""
+ hdr_parts = []
+ for name, kind, blob, extra in parts:
+ d = {"name": name, "kind": kind, "len": len(blob)}
+ d.update({k: v for k, v in (extra or {}).items() if v is not None})
+ hdr_parts.append(d)
+ header = json.dumps({"v": 1, "meta": meta, "parts": hdr_parts}, separators=(",", ":")).encode()
+ return b"".join([MAGIC, struct.pack("<I", len(header)), header] + [blob for _, _, blob, _ in parts])
+
+
+def array_part(name: str, arr, extra: dict | None = None) -> tuple[str, str, bytes, dict]:
+ import numpy as np
+ a = np.ascontiguousarray(arr)
+ return (name, "array", a.tobytes(), {"dtype": str(a.dtype), "shape": list(a.shape), **(extra or {})})
+
+
+def decode(buf: bytes, arrays: bool = True) -> tuple[dict, dict]:
+ """-> (meta, parts) where parts[name] = {"kind", ..., "data"}; arrays become numpy arrays when arrays=True."""
+ if buf[:4] != MAGIC:
+ raise ValueError("not an RCB1 frame")
+ n = struct.unpack("<I", buf[4:8])[0]
+ header = json.loads(buf[8:8 + n].decode()); off = 8 + n
+ out = {}
+ for p in header["parts"]:
+ blob = buf[off:off + p["len"]]; off += p["len"]
+ d = dict(p)
+ if p["kind"] == "array" and arrays:
+ import numpy as np
+ d["data"] = np.frombuffer(blob, dtype=np.dtype(p["dtype"])).reshape(p["shape"])
+ elif p["kind"] == "json":
+ d["data"] = json.loads(blob.decode())
+ else:
+ d["data"] = blob
+ out[p["name"]] = d
+ return header.get("meta", {}), out
+
+
+def unpack_to_dir(buf: bytes, out_dir: str) -> list[str]:
+ """Write a frame's parts as files: mp4/jpeg/bytes verbatim, arrays as .npy, meta as meta.json."""
+ import numpy as np
+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)
+ meta, parts = decode(buf, arrays=True); written = []
+ (out / "meta.json").write_text(json.dumps(meta, indent=1)); written.append("meta.json")
+ for name, p in parts.items():
+ safe = name.replace("/", "__")
+ if p["kind"] == "array":
+ f = out / f"{safe}.npy"; np.save(f, p["data"])
+ elif p["kind"] == "mp4":
+ f = out / f"{safe}.mp4"; f.write_bytes(p["data"])
+ elif p["kind"] == "jpeg":
+ f = out / f"{safe}.jpg"; f.write_bytes(p["data"])
+ elif p["kind"] == "json":
+ f = out / f"{safe}.json"; f.write_text(json.dumps(p["data"], indent=1))
+ else:
+ f = out / f"{safe}.bin"; f.write_bytes(p["data"])
+ written.append(f.name)
+ return written
+
+
+if __name__ == "__main__":
+ if len(sys.argv) == 4 and sys.argv[1] == "unpack":
+ print("\n".join(unpack_to_dir(open(sys.argv[2], "rb").read(), sys.argv[3])))
+ elif len(sys.argv) == 3 and sys.argv[1] == "info":
+ meta, parts = decode(open(sys.argv[2], "rb").read(), arrays=False)
+ print(json.dumps(meta, indent=1)); [print(n, {k: v for k, v in p.items() if k != "data"}) for n, p in parts.items()]
+ else:
+ print(__doc__)
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/rcb_olympics.py b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/rcb_olympics.py
new file mode 100644
index 0000000000..f62893059e
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/rcb_olympics.py
@@ -0,0 +1,723 @@
+"""RoboOlympics sports behind eai-standard/2.3 (docs/PROTOCOL.md §4b; docs/benchmarks/roboolympics.md): the adapter
+that puts one RoboOlympics match (a sport plugin under sport/, core/sport.py's contract ②) behind rcb_service's `Sim`
+contract. The protocol itself -- the endpoints, RCB1, the realtime clock and its plan, budgets, evidence, crash
+recovery, finalize -- is rcb_realtime.py + rcb_service.py, unchanged (copied from HumanoidBench's 2.3 layer).
+
+The world. One control step of the service is one control step of the match (Match.step(), 10 ms of game time), with
+one exception, the break: when a unit ends (a point, a rally) the match stands still for BREAK_S of game time -- the
+clock keeps running (the service's control steps go on at 1/S of real speed, the agent's plan is consumed), nothing
+moves, nothing scores -- and play resumes by itself when the break is over, or at the agent's `ready` row, whichever
+comes first. Like a break in a real match: the time passes, the game does not.
+
+Actions. The agent's rows are the sport's own commands (the RoboOlympics action layer of the task's level), one row per
+command: table tennis and badminton (high level) `stroke` (the paddle's / racket's state at contact, t seconds after
+the command takes effect; the service plans the swing), badminton's `toss` (the serve), `rest` (back to the ready
+pose), air hockey (low level) `mallet` (the mallet's target, a row per control step, interpolable) and `stop`; every
+sport `ready`. A command takes effect at the control step its row is planned for: the sport's action layer parses it
+there, plans it from the state of that step and lowers it to a low-level command (core/sport.py ActionLayer.lower),
+which Match.apply() installs before the step runs -- the RoboOlympics realtime service's effect boundary. A row the
+sport refuses at that moment (e.g. a toss when it is not your serve) changes nothing and is counted in proprio.
+
+The journal. A sim row is [command id, ready]: the id of the low-level command that took effect at that step (-1:
+none), and 1 when the step carries the agent's ready. The low-level commands themselves are kept in
+DATA/commands.jsonl (one JSON line per id, written before the row that names it), so the journal plus that table is the
+whole record: a replay re-applies exactly the commands the live match applied, at their steps, and never plans again.
+The match is bit-exact (the RoboOlympics sports' golden replays), so a crash resumes by replaying the journal and a
+fresh-process replay decides the verdict (`success` = a finished match the agent won).
+"""
+from __future__ import annotations
+
+import hashlib
+import importlib.util
+import json
+import math
+import os
+import subprocess
+import sys
+import tempfile
+
+import numpy as np
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+if HERE not in sys.path:
+ sys.path.insert(0, HERE)
+
+from core import spec as spec_mod # noqa: E402
+from core.outcome import decide # noqa: E402
+from core.sport import FINISHED, UNIT_OVER, MatchConfig, Refused, parse_action # noqa: E402
+
+BREAK_S = 12.0 # game seconds of the break after every unit (120 s of wall time at S = 10)
+NAN = float("nan")
+READY_DOC = ("end the break now (between units only; ignored during play): play resumes at the next control step "
+ "(the row's value is ignored; put your review in submit's note)")
+
+
+def load_plugin(path: str):
+ """The sport's plugin module at `path` (its directory first on sys.path, so its simulator modules import); its
+ SPORT is the sport."""
+ path = os.path.abspath(path)
+ if os.path.dirname(path) not in sys.path:
+ sys.path.insert(0, os.path.dirname(path))
+ spec = importlib.util.spec_from_file_location("ro_plugin", path)
+ mod = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(mod)
+ return mod
+
+
+def _f(x, default=NAN) -> float:
+ try:
+ return float(x)
+ except (TypeError, ValueError):
+ return default
+
+
+def _json(x):
+ """JSON-exact Python values: what DATA/commands.jsonl holds, so the live match applies what a replay reads back."""
+ return json.loads(json.dumps(x, default=lambda o: o.tolist() if hasattr(o, "tolist") else float(o)))
+
+
+def _clip_box(row, i, lo, hi, name, out, k):
+ v = float(row[i])
+ c = min(max(v, lo), hi)
+ if c != v:
+ out.append({"row": k, "index": i, "reason": f"{name} clipped to [{lo:g}, {hi:g}]"})
+ row[i] = c
+
+
+def _clip_norm(row, sl, cap, name, out, k):
+ v = np.asarray(row[sl], float)
+ n = float(np.linalg.norm(v))
+ if n > cap:
+ row[sl] = v * (cap / n)
+ out.append({"row": k, "index": sl.start, "reason": f"|{name}| = {n:.3f} scaled to {cap:g}"})
+
+
+def _heard(o: dict, names: dict) -> list:
+ """The first time of each heard event (seconds on the current ball's clock), NaN if not heard."""
+ out = []
+ for key in names.values():
+ out.append(next((_f(h.get("t")) for h in o.get("heard") or [] if h.get("event") == key), NAN))
+ return out
+
+
+def _last_point(points, you="you") -> float:
+ if not points:
+ return NAN
+ w = points[-1].get("winner")
+ return 1.0 if w == you else 0.0 if w in (None, "let") else -1.0
+
+
+# ================================================================================================ per-sport profiles
+class _Profile:
+ """What differs between the sports: the agent's action types (as rows), their limits, the proprio columns, the
+ cameras and how they are drawn."""
+ types: dict = {}
+ interp: tuple = ()
+ cams: dict = {}
+ drop: tuple = () # sport.toml [spec] / Sport.spec() entries about RoboOlympics' own interface
+ rules: dict = {} # ... and what replaces them here
+
+ def __init__(self, sim):
+ self.sim = sim
+
+ def body(self, typ, row): # an agent row -> the sport's act body (None: nothing new)
+ raise NotImplementedError
+
+ def clip(self, typ, rows):
+ return rows, []
+
+ def command(self, typ):
+ """The row a gap in the plan is filled with (rcb_realtime: a submit whose `at` lies ahead holds "the target in
+ force" until then; a row is also interpolated from it): for a command that is not a target, zeros, which
+ to_sim reads as no command. No agent row is all zeros after clip() (Olympics.clip)."""
+ return np.zeros(int(self.types[typ]["dim"]))
+
+ def proprio(self) -> list:
+ raise NotImplementedError
+
+ def images(self, cams) -> dict:
+ raise NotImplementedError
+
+
+def _stroke_type(what, t_max, box, extra=""):
+ return {"dim": 10, "layout": ["t", "x", "y", "z", "nx", "ny", "nz", "vx", "vy", "vz"],
+ "units": "s, m, unit-free normal, m/s (your frame)",
+ "limits": {"t": [0.0, t_max], **box, "normal": "non-zero", "speed_max": 8.0},
+ "semantics": (f"the {what}'s state at contact t seconds after the command takes effect: centre x y z, face "
+ f"normal nx ny nz (pointing where the ball should go), velocity vx vy vz; it replaces the "
+ f"stroke under way; the service plans the swing (IK, joint speed limits) and the robot goes "
+ f"back to its ready pose after it. Out-of-range values are clipped (meta.clipped){extra}"),
+ "interpolable": False}
+
+
+class TableTennis(_Profile):
+ types = {
+ "stroke": _stroke_type("paddle blade", 2.5, {"x": [-1.2, 1.2], "y": [-2.5, -0.5], "z": [0.0, 1.2]},
+ "; the delivered state scatters by about 4 mm, 0.6 degrees and 2 %"),
+ "rest": {"dim": 1, "layout": ["unused"], "interpolable": False,
+ "semantics": "cancel the stroke under way: the arm returns to its ready pose (the value is ignored)"},
+ "ready": {"dim": 1, "layout": ["unused"], "interpolable": False, "semantics": READY_DOC}}
+ drop = ("duel", "observation", "action_high", "action_low", "real_time", "scatter_and_seed")
+ rules = {"scatter": "the serves, the opponent's returns and your strokes' execution scatter are drawn from the "
+ "task's frozen seed (never shown)"}
+ HEARD = {"opp_bounce": "bounce on the opponent's half", "own_bounce": "bounce on your half", "net": "net",
+ "paddle": "paddle", "robot": "robot", "floor": "floor"}
+ layout = (["score_you", "score_opponent", "point", "ball_is_serve", "t_since_played", "serve_in_s",
+ "ball_in_play", "ball_coming", "ball_going"]
+ + [f"heard_{k}_t" for k in HEARD]
+ + [f"q{i}" for i in range(1, 8)] + ["paddle_x", "paddle_y", "paddle_z", "paddle_nx", "paddle_ny", "paddle_nz"]
+ + ["stroke_active", "stroke_contact_in_s", "stroke_speed_scale", "stroke_blade_error_m",
+ "stroke_normal_error_deg", "stroke_ik_residual", "last_point_won"])
+
+ def __init__(self, sim):
+ super().__init__(sim)
+ import match
+ self.cams = {c["name"]: dict(c, fovy_deg=45.0, hw=[360, 480], focal_px=434.6, principal_point_px=[240, 180])
+ for c in match.Match.CAM_INFO}
+ self.view = None
+
+ def body(self, typ, row):
+ if typ == "rest":
+ return {"type": "none"}
+ r = [float(x) for x in row]
+ return {"type": "act", "t": r[0], "pos": r[1:4], "normal": r[4:7], "vel": r[7:10]}
+
+ def clip(self, typ, rows):
+ out = []
+ if typ != "stroke":
+ return rows, out
+ rows = np.array(rows, dtype=np.float64)
+ for k, row in enumerate(rows):
+ _clip_box(row, 0, 0.01, 2.5, "t", out, k)
+ for i, (lo, hi) in zip((1, 2, 3), ((-1.2, 1.2), (-2.5, -0.5), (0.0, 1.2))):
+ _clip_box(row, i, lo, hi, "xyz"[i - 1], out, k)
+ if np.linalg.norm(row[4:7]) < 1e-6:
+ row[4:7] = [0.0, 1.0, 0.0]
+ out.append({"row": k, "index": 4, "reason": "a zero normal replaced by (0, 1, 0)"})
+ _clip_norm(row, slice(7, 10), 8.0, "vel", out, k)
+ return rows, out
+
+ def proprio(self):
+ m = self.sim.m
+ o = m.observe(self.sim.seat)
+ R = m.R
+ bs = o.get("ball_state")
+ cmd = o.get("command")
+ la = getattr(R, "_last_act", None) or {}
+ active = isinstance(cmd, dict)
+ return ([_f(o["score"]["you"]), _f(o["score"]["opponent"]), _f(o.get("point")),
+ 1.0 if o.get("ball") == "serve" else 0.0, _f(o.get("t_since_played")), _f(o.get("serve_in_s"), 0.0),
+ float(bool(o.get("ball_in_play"))), float(bs == "coming to you"), float(bs == "going to the opponent")]
+ + _heard(o, self.HEARD) + [_f(x) for x in o["q"]] + [_f(x) for x in o["paddle_pos"]]
+ + [_f(x) for x in o["paddle_normal"]]
+ + [float(active), _f(cmd.get("contact_in_s")) if active else NAN,
+ _f(la.get("speed_scale")) if active else NAN, _f(la.get("blade_error_m")) if active else NAN,
+ _f(la.get("normal_error_deg")) if active else NAN, _f(la.get("ik_residual")) if active else NAN,
+ _last_point(R.points)])
+
+ def images(self, cams):
+ if self.view is None:
+ self.view = self.sim.mod.MatchView()
+ import match
+ R = self.sim.m.R
+ names = list(self.cams)
+ q, ox = R.s.d.qpos.copy(), R.opp_x()
+ text = f"k={R.k} t={R.t_since_launch():.2f}s"
+ return {c: self.view.tile(names.index(c), q, text, lambda scn, o=ox: match.Match._extra_geoms(None, scn, o), ox)
+ for c in cams}
+
+
+class Badminton(_Profile):
+ types = {
+ "stroke": _stroke_type("racket head", 5.0, {"x": [-3.4, 3.4], "y": [-7.5, -0.3], "z": [0.2, 3.0]},
+ "; it takes effect spec.rules.act.lead_steps control steps after its row's step (the "
+ "planning time), and t counts from then; a stroke or toss sent before the previous one "
+ "took effect is refused"),
+ "toss": {"dim": 4, "layout": ["x", "y", "z", "height"], "units": "m (your frame)", "interpolable": False,
+ "limits": {"z": [0.5, 1.8], "height": [0.0, 0.5], "y_max": -0.5, "reach_from_base": 1.0},
+ "semantics": ("your serve: the shuttle appears at x y z (from rest, or rising `height` straight up) "
+ "when the command takes effect (the same lead as a stroke); only the server, once per "
+ "serve, from the step the receiver is ready (proprio serve_phase = 1, open); then hit "
+ "it with a stroke (which may be sent before the toss)")},
+ "rest": {"dim": 1, "layout": ["unused"], "interpolable": False,
+ "semantics": "cancel the stroke under way: the robot returns to its ready pose, the base home"},
+ "ready": {"dim": 1, "layout": ["unused"], "interpolable": False, "semantics": READY_DOC}}
+ drop = ("duel", "observation", "lowlevel", "act")
+ PHASES = {"waiting": 0.0, "open": 1.0, "tossed": 2.0, "done": 3.0}
+ layout = (["score_you", "score_opponent", "point", "you_serve", "serve_court_right", "serve_phase",
+ "serve_opens_in_s", "serve_deadline_in_s", "serve_tossed_at_step", "ball_kind", "t_since_played",
+ "ball_in_play", "ball_not_served", "ball_tossed", "ball_coming", "ball_going",
+ "base_x", "base_y"] + [f"q{i}" for i in range(1, 8)]
+ + ["racket_x", "racket_y", "racket_z", "racket_nx", "racket_ny", "racket_nz",
+ "stroke_active", "stroke_contact_in_s", "stroke_traj_steps_left", "stroke_pending_effect_step",
+ "stroke_head_speed_limited", "stroke_pose_not_delivered", "last_point_won"])
+
+ def __init__(self, sim):
+ super().__init__(sim)
+ import bm
+ FOCAL_PX = sim.mod.FOCAL_PX
+ self.TOSS_Z, self.TOSS_H = tuple(bm.TOSS_Z), float(bm.TOSS_H_MAX)
+ self.types = dict(self.types)
+ self.types["toss"] = dict(self.types["toss"], limits={"z": list(bm.TOSS_Z), "height": [0.0, bm.TOSS_H_MAX],
+ "y_max": -0.5, "reach_from_base": bm.TOSS_REACH})
+ lead = sim.mod.lead_steps(sim.cfg.slowdown)
+ self.rules = {"act": {"lead_steps": lead, "lead_game_s": round(lead * bm.CONTROL_DT, 4),
+ "rule": (f"a stroke, a toss or a rest takes effect {lead} control steps after the step "
+ "its row is planned for (the stroke is planned meanwhile; proprio "
+ "stroke_pending_effect_step shows it); a stroke's t counts from that effect "
+ "step; another stroke, toss or rest planned before then is refused")},
+ "serve": {"command": ("a `toss` row: the shuttle appears at x y z when the command takes effect "
+ "(the same lead as a stroke) and rises `height` straight up (0: released "
+ "from rest); then hit it with a stroke (it may be sent before the toss)"),
+ "phases": ("proprio serve_phase: 0 waiting (the receiver is getting ready), 1 open "
+ "(toss now), 2 tossed, 3 done")}}
+ w, h = bm.Match.TILE
+ self.cams = {c["name"]: dict(c, fovy_deg=45.0, hw=[h, w], focal_px=FOCAL_PX, principal_point_px=[w / 2, h / 2])
+ for c in bm.Match.cam_info()}
+ self.view = None
+
+ def body(self, typ, row):
+ r = [float(x) for x in row]
+ if typ == "rest":
+ return {"type": "none"}
+ if typ == "toss":
+ return {"type": "toss", "pos": r[0:3], "height": r[3]}
+ return {"type": "act", "t": r[0], "pos": r[1:4], "normal": r[4:7], "vel": r[7:10]}
+
+ def clip(self, typ, rows):
+ out = []
+ rows = np.array(rows, dtype=np.float64)
+ if typ == "stroke":
+ for k, row in enumerate(rows):
+ _clip_box(row, 0, 0.01, 5.0, "t", out, k)
+ for i, (lo, hi) in zip((1, 2, 3), ((-3.4, 3.4), (-7.5, -0.3), (0.2, 3.0))):
+ _clip_box(row, i, lo, hi, "xyz"[i - 1], out, k)
+ if np.linalg.norm(row[4:7]) < 1e-6:
+ row[4:7] = [0.0, 1.0, 0.0]
+ out.append({"row": k, "index": 4, "reason": "a zero normal replaced by (0, 1, 0)"})
+ _clip_norm(row, slice(7, 10), 8.0, "vel", out, k)
+ elif typ == "toss":
+ for k, row in enumerate(rows):
+ _clip_box(row, 1, -7.5, -0.5, "y", out, k)
+ _clip_box(row, 2, self.TOSS_Z[0], self.TOSS_Z[1], "z", out, k)
+ _clip_box(row, 3, 0.0, self.TOSS_H, "height", out, k)
+ return rows, out
+
+ def proprio(self):
+ m = self.sim.m
+ o = m.observe(self.sim.seat)
+ sv = o.get("serve") or {}
+ bs = str(o.get("ball_state") or "")
+ cmd = o.get("command")
+ active = isinstance(cmd, dict) and "contact_in_s" in cmd
+ notes = str(cmd.get("stroke") or "") if active else ""
+ pend = o.get("pending_commands") or []
+ kind = {"serve": 0.0, "your serve": 1.0}.get(o.get("ball"), 2.0)
+ return ([_f(o["score"]["you"]), _f(o["score"]["opponent"]), _f(o.get("point")), float(bool(o.get("you_serve"))),
+ float(sv.get("court") == "right"), self.PHASES.get(sv.get("phase"), NAN), _f(sv.get("opens_in_s")),
+ _f(sv.get("deadline_in_s")), _f(sv.get("tossed_at_step")), kind, _f(o.get("t_since_played")),
+ float(bool(o.get("ball_in_play"))), float(bs == "not yet served"), float(bs.startswith("tossed")),
+ float(bs == "coming to you"), float(bs == "going to the opponent")]
+ + [_f(x) for x in o["robot_base_xy"]] + [_f(x) for x in o["q_arm"]] + [_f(x) for x in o["racket_pos"]]
+ + [_f(x) for x in o["racket_normal"]]
+ + [float(active), _f(cmd.get("contact_in_s")) if active else NAN,
+ _f(cmd.get("traj_steps_left"), 0.0) if isinstance(cmd, dict) else 0.0,
+ _f(pend[0].get("takes_effect_at_step")) if pend else NAN,
+ float("head speed limited" in notes), float("pose not delivered" in notes),
+ _last_point(m.g.points)])
+
+ def images(self, cams):
+ if self.view is None:
+ self.view = self.sim.mod.Views(True, "A")
+ g = self.sim.m.g
+ sn = {"qpos": g.s.d.qpos.copy(), "sh": tuple(float(x) for x in g.s.sh_p),
+ "shv": tuple(float(x) for x in g.s.sh_v), "opp": [float(x) for x in g.opp_xy()],
+ "k": int(g.k), "t": float(g.t_since_launch())}
+ names = list(self.cams)
+ return {c: self.view.tile(names.index(c), sn) for c in cams}
+
+
+class AirHockey(_Profile):
+ types = {
+ "mallet": {"dim": 2, "layout": ["x", "y"], "units": "m (the table frame)", "interpolable": True,
+ "semantics": ("the mallet centre's target; the robot drives the mallet there along a speed- and "
+ "acceleration-limited path (spec.sport.mallet_path) and holds it until replaced; "
+ "own half only: a target outside the workspace (spec.sport.workspace) is moved to "
+ "its nearest point (meta.clipped)")},
+ "stop": {"dim": 1, "layout": ["unused"], "interpolable": False,
+ "semantics": "the mallet stops where it is (its target becomes its position)"},
+ "ready": {"dim": 1, "layout": ["unused"], "interpolable": False, "semantics": READY_DOC}}
+ interp = ("mallet",)
+ drop = ("real_time", "action", "observation")
+ rules = {"review": ("every goal, foul or dead puck ends the rally: both mallets return home, the break follows "
+ "(spec.break), then the next rally starts")}
+ HOW = {"goal": 1.0, "seven_second_foul": 2.0, "dead_puck": 3.0, "time_cap": 4.0}
+ layout = (["score_you", "score_opponent", "rally", "t_play", "play_time_left_s",
+ "mallet_x", "mallet_y", "mallet_z", "target_x", "target_y"]
+ + [f"q{i}" for i in range(1, 8)] + ["q_striker1", "q_striker2"]
+ + [f"qd{i}" for i in range(1, 8)] + ["qd_striker1", "qd_striker2"]
+ + ["last_rally_how", "last_rally_scored", "last_rally_fouled", "last_rally_next_puck"])
+
+ def __init__(self, sim):
+ super().__init__(sim)
+ from renderers.base import CameraDef
+ self.P = sim.mod
+ self.camdefs = [CameraDef.from_dict(c) for c in sim.m.cameras(sim.seat)]
+ self.cams = {c.name: dict(c.to_dict(), **c.intrinsics(), hw=[c.height, c.width]) for c in self.camdefs}
+ self.renderer = None
+
+ def body(self, typ, row):
+ h = self.sim.m.h
+ if typ == "stop":
+ return {"type": "none"}
+ x, y = float(row[0]), float(row[1])
+ cur = h.commands.get(self.sim.seat) if isinstance(h.commands, dict) else None
+ if cur is not None and abs(float(cur[0]) - x) < 1e-9 and abs(float(cur[1]) - y) < 1e-9:
+ return None # the target in force: nothing new
+ return {"type": "target", "x": x, "y": y}
+
+ def clip(self, typ, rows):
+ out = []
+ rows = np.array(rows, dtype=np.float64)
+ if typ != "mallet":
+ return rows, out
+ H = self.P.H
+ for k, row in enumerate(rows):
+ w = H.workspace(self.sim.seat, row)
+ if not H.in_workspace(self.sim.seat, w, eps=0.0): # the box-then-radial clip may land a hair outside
+ w = H.workspace(self.sim.seat, [w[0] * 0.999999, w[1] * 0.999999])
+ w = [round(float(w[0]), 6), round(float(w[1]), 6)]
+ if abs(w[0] - row[0]) > 1e-9 or abs(w[1] - row[1]) > 1e-9:
+ out.append({"row": k, "index": 0, "reason": "outside the mallet workspace: moved to its nearest point"})
+ row[0], row[1] = w
+ return rows, out
+
+ def command(self, typ):
+ if typ == "mallet":
+ h = self.sim.m.h
+ return np.asarray(h.commands[self.sim.seat], np.float64)
+ return super().command(typ)
+
+ def proprio(self):
+ m = self.sim.m
+ o = m.observe(self.sim.seat)
+ h = m.h
+ sc = h.scores()
+ last = h.results[-1] if h.results else None
+ side = lambda s: NAN if last is None else (1.0 if s == "A" else -1.0 if s == "B" else 0.0) # noqa: E731
+ return ([_f(sc["A"]["points"]), _f(sc["B"]["points"]), _f(o["rally"]), _f(o["t_play"]),
+ _f(o["play_time_left_s"])] + [_f(x) for x in o["own"]["mallet_xyz"]]
+ + [_f(x) for x in o["own"]["command"]] + [_f(x) for x in o["own"]["joint_position"]]
+ + [_f(x) for x in o["own"]["joint_velocity"]]
+ + [NAN if last is None else self.HOW.get(last["how"], 5.0), side(last and last["winner"]),
+ side(last and last["guilty"]), side(last and last["next"])])
+
+ def images(self, cams):
+ if self.renderer is None:
+ import renderers
+ from core.observe import players_scene
+ sim = self.sim
+ self.renderer = renderers.load(sim.cfg.renderer or renderers.DEFAULT)(
+ players_scene(sim.sport, sim.plugin, sim.cfg))
+ imgs = self.renderer.render(self.sim.m.render_state(), self.camdefs)
+ return {c.name: img for c, img in zip(self.camdefs, imgs) if c.name in cams}
+
+
+PROFILES = {"tabletennis": TableTennis, "badminton": Badminton, "airhockey": AirHockey}
+
+
+# ================================================================================================ the Sim contract
+class Olympics:
+ """One RoboOlympics match against the scripted opponent (seat A) behind rcb_service.Sim (module docstring)."""
+
+ raw_dim = 2 # [command id (-1: none), ready]
+ depth_cameras: tuple = ()
+
+ def __init__(self, plugin: str, cfg: MatchConfig, data: str | None = None, task_text: str = "",
+ episode_text: str = "", break_s: float = BREAK_S):
+ self.plugin, self.cfg, self.data = os.path.abspath(plugin), cfg, data
+ self.mod = load_plugin(self.plugin)
+ self.sport = self.mod.SPORT
+ self.decl = spec_mod.load(self.plugin)
+ self.seat = cfg.seats[0]
+ self.task_text, self.episode_text = task_text, episode_text
+ self.commands: list = []
+ self.cmd_path = os.path.join(data, "commands.jsonl") if data else None
+ if self.cmd_path and os.path.exists(self.cmd_path): # a resumed service: the table so far
+ with open(self.cmd_path) as f:
+ for line in f:
+ try:
+ rec = json.loads(line)
+ except ValueError:
+ break # a line cut by a crash: no journal row names it
+ if rec.get("id") == len(self.commands):
+ self.commands.append(rec["low"])
+ self._new_match()
+ self.control_dt = float(self.m.dt)
+ self.break_steps = max(1, int(round(break_s / self.control_dt)))
+ self.max_control_steps = 10 ** 8 # no step cap: the match ends by its rules, else the wall clock
+ self.profile = PROFILES[self.sport.name](self)
+ self.cameras = tuple(self.profile.cams)
+ self.proprio_layout = (["match_step", "break", "break_left_s", "finished"] + list(self.profile.layout)
+ + ["commands_applied", "commands_refused", "last_refused_step"])
+
+ def _new_match(self):
+ self.m = self.sport.build(self.cfg)
+ self.layer = self.sport.action_layer(self.cfg.action_level)
+ self.steps = 0 # control steps of this episode, breaks included
+ self.in_break, self.break_left, self.breaks = False, 0, []
+ self.finished = self.won = False
+ self.applied = self.refused = self.dropped = 0
+ self.last_refused = -1
+
+ # ------------------------------------------------------------------ facts
+ def spec(self) -> dict:
+ sport = dict(self.decl.get("spec") or {}) # as RoboOlympics' public_spec: sport.toml, then Sport.spec()
+ sport.update(self.sport.spec(self.cfg, self.seat, self.m))
+ for k in ("calls", "image", "image_layout", "cameras", "action_interface") + tuple(self.profile.drop):
+ sport.pop(k, None)
+ for k, v in self.profile.rules.items():
+ sport[k] = {**sport[k], **v} if isinstance(v, dict) and isinstance(sport.get(k), dict) else v
+ if (self.decl.get("tiebreaks") or {}).get("text"):
+ sport["tiebreaks"] = self.decl["tiebreaks"]["text"]
+ types = {k: {kk: vv for kk, vv in v.items() if kk != "interpolable"} for k, v in self.profile.types.items()}
+ s = self.decl.get("sport") or {}
+ return {"simulator": "RoboOlympics on MuJoCo 3.3.7 (CPU)", "sport": s.get("name", self.sport.name),
+ "title": s.get("title"), "revision": self.sport.revision, "robot": sport.pop("robot", None),
+ "task_text": self.task_text, "episode": self.episode_text,
+ "match": {"format": self.cfg.format, "opponent_level": self.cfg.level, "action_level":
+ self.cfg.action_level, "you": self.seat},
+ "action_types": types, "cameras": self.profile.cams, "rules": sport,
+ "break": {"game_s": self.break_steps * self.control_dt, "control_steps": self.break_steps,
+ "rule": ("after every unit (a point, a rally) the match stands still for this much game "
+ "time: the clock runs on (control steps, wall time, your plan), nothing moves and "
+ "nothing scores; play resumes by itself at the end of the break, or at the control "
+ "step of your `ready` row. proprio: break (1 during it), break_left_s")},
+ "proprio_notes": ("one row per frame, columns proprio_layout; NaN = not applicable now; match_step = "
+ "the match's own control step (it stands still in a break; meta.control_steps "
+ "counts every step); times in game seconds; positions in your frame")}
+
+ def interpolable(self, typ: str) -> bool:
+ return typ in self.profile.interp
+
+ # ------------------------------------------------------------------ observation
+ def images(self, cameras, depth):
+ return self.profile.images(list(cameras)), {}
+
+ def proprio(self) -> np.ndarray:
+ own = [float(self.m.k), float(self.in_break), self.break_left * self.control_dt if self.in_break else 0.0,
+ float(self.finished)]
+ return np.asarray(own + self.profile.proprio() + [float(self.applied), float(self.refused),
+ float(self.last_refused)], np.float32)
+
+ # ------------------------------------------------------------------ actions
+ def clip(self, typ, rows):
+ """The profile's limits; a one-value command (rest, stop, ready: the value is ignored) becomes 1, so that no
+ agent row is all zeros, the gap filler's row (command())."""
+ try:
+ if int(self.profile.types.get(typ, {}).get("dim", 0)) == 1 and typ not in self.profile.interp:
+ return np.ones((len(rows), 1)), []
+ return self.profile.clip(typ, rows)
+ except Exception as exc: # noqa: BLE001 -- clip must never fail a request that passed the checks
+ return np.asarray(rows, np.float64), [{"row": 0, "index": 0, "reason": f"unchecked: {exc!r}"[:200]}]
+
+ def command(self, typ):
+ try:
+ return self.profile.command(typ)
+ except Exception: # noqa: BLE001
+ return np.zeros(int(self.profile.types.get(typ, {"dim": 1})["dim"]))
+
+ def hold(self):
+ return "hold", np.zeros(1)
+
+ def to_sim(self, typ, row) -> np.ndarray:
+ """At the step the row is planned for (rcb_service._step, right before step()): the row as a sim row. A
+ command is parsed, planned and lowered here, from this step's state, and enters the command table. An all-zero
+ row of a command type is no command: a gap the service filled with command() (clip() leaves no agent row so)."""
+ if typ not in self.profile.interp and not np.any(np.asarray(row, dtype=np.float64)):
+ return np.array([-1.0, 0.0])
+ if typ == "ready":
+ return np.array([-1.0, 1.0])
+ if typ not in self.profile.types or self.finished:
+ return np.array([-1.0, 0.0])
+ if self.in_break:
+ self.dropped += 1
+ return np.array([-1.0, 0.0])
+ body = self.profile.body(typ, row)
+ if body is None:
+ return np.array([-1.0, 0.0])
+ rec = {"id": len(self.commands), "step": self.steps, "match_k": int(self.m.k), "type": typ,
+ "row": [float(x) for x in row]}
+ try:
+ cmd = parse_action(self.layer, self.seat, body, self.m, {})
+ job = self.layer.snapshot(self.seat, cmd, self.m, self.applied + self.refused + 1)
+ prepared = self.layer.prepare(job) if job is not None else None
+ low, info = self.layer.lower(self.seat, cmd, prepared, self.m)
+ except Refused as exc:
+ self.refused += 1
+ self.last_refused = int(self.m.k)
+ self._log({**rec, "id": None, "refused": str(exc)[:300]})
+ return np.array([-1.0, 0.0])
+ rec.update(low=_json(low), info=_json(info))
+ self.commands.append(rec["low"])
+ self._log(rec)
+ return np.array([float(rec["id"]), 0.0])
+
+ def _log(self, rec):
+ if self.cmd_path:
+ with open(self.cmd_path, "a") as f:
+ f.write(json.dumps(rec, default=float) + "\n")
+ f.flush()
+
+ def step(self, row) -> tuple[bool, bool, dict]:
+ cid, ready = int(round(float(row[0]))), float(row[1]) > 0.5
+ self.steps += 1
+ if self.finished:
+ return True, self.won, {}
+ if self.in_break:
+ if ready or self.break_left <= 1:
+ self.in_break = False
+ self.breaks[-1].update(end=self.steps, by="ready" if ready else "time")
+ self.m.resume()
+ else:
+ self.break_left -= 1
+ return False, False, {}
+ if cid >= 0:
+ info = self.m.apply(self.seat, self.commands[cid]) or {}
+ if isinstance(info, dict) and "rejected" in info:
+ self.refused += 1
+ self.last_refused = int(self.m.k)
+ else:
+ self.applied += 1
+ self.m.step()
+ ph = self.m.phase()
+ if ph.state == FINISHED:
+ self.finished = True
+ out = decide(self.m, None, None, self.cfg.side_list(), self.cfg.side_of)
+ self.won = out.winner == self.cfg.side_of(self.seat)
+ return True, self.won, {}
+ if ph.state == UNIT_OVER:
+ self.in_break, self.break_left = True, self.break_steps
+ self.breaks.append({"start": self.steps, "match_k": int(self.m.k), "reason": ph.reason})
+ return False, False, {}
+
+ # ------------------------------------------------------------------ episode
+ def reset(self) -> None:
+ self._new_match()
+ self.profile = PROFILES[self.sport.name](self)
+
+ def state_sha(self) -> str:
+ own = json.dumps([self.steps, self.in_break, self.break_left, self.finished, self.won], sort_keys=True)
+ return hashlib.sha256((self.m.state_digest() + own).encode()).hexdigest()
+
+ def summary(self) -> dict:
+ out = decide(self.m, None, None, self.cfg.side_list(), self.cfg.side_of)
+ scores = self.m.scores()
+ you = self.cfg.side_of(self.seat)
+ them = [s for s in scores if s != you]
+ return {"sport": self.sport.name, "revision": self.sport.revision, "finished": self.finished,
+ "won": bool(self.finished and out.winner == you), "winner": out.winner, "decided_by": out.decided_by,
+ "scores": scores, "points_for": scores.get(you), "points_against": scores.get(them[0]) if them else None,
+ "match_steps": int(self.m.k), "control_steps": self.steps, "breaks": self.breaks,
+ "commands_applied": self.applied, "commands_refused": self.refused,
+ "rows_dropped_in_breaks": self.dropped, "cfg": self.cfg.to_json(), "break_steps": self.break_steps,
+ "sport_fields": _json(self.m.final_fields())}
+
+ # ------------------------------------------------------------------ the record, the replay, the video
+ def save_trajectory(self, rows, path, meta) -> None:
+ np.savez_compressed(path, rows=np.asarray(rows, np.float64).reshape(-1, self.raw_dim),
+ commands=np.array(json.dumps(self.commands)), cfg=np.array(json.dumps(self.cfg.to_json())),
+ break_steps=np.array(self.break_steps), meta=np.array(json.dumps(meta, default=str)),
+ layout=np.array(json.dumps(["command_id", "ready"])))
+
+ def _sub(self, mode: str, rows, out: str) -> dict:
+ """A fresh process (python rcb_olympics.py MODE ...): the replay never shares state with the live match."""
+ fd, tmp = tempfile.mkstemp(suffix=".npz", dir=self.data or None)
+ os.close(fd)
+ try:
+ self.save_trajectory(rows, tmp, {"for": mode})
+ env = dict(os.environ, RO_TASK_TEXT=self.task_text, RO_EPISODE_TEXT=self.episode_text)
+ r = subprocess.run([sys.executable, os.path.abspath(__file__), mode, self.plugin, tmp, out],
+ capture_output=True, text=True, env=env, timeout=3600)
+ if r.returncode:
+ raise RuntimeError(f"{mode} failed: {r.stderr[-1500:]}")
+ return json.loads(r.stdout.strip().splitlines()[-1])
+ finally:
+ os.unlink(tmp)
+
+ def verify(self, rows) -> dict:
+ out = os.path.join(self.data, "match.json") if self.data else os.devnull
+ rep = self._sub("replay", rows, out)
+ return {"success": bool(rep["won"]), "state_sha": rep["state_sha"]}
+
+ def render_video(self, rows, path) -> None:
+ self._sub("video", rows, path)
+
+
+# ================================================================================================ fresh processes
+def _rebuild(plugin: str, npz: str) -> tuple[Olympics, np.ndarray]:
+ z = np.load(npz)
+ cfg = MatchConfig.from_json(json.loads(str(z["cfg"])))
+ sim = Olympics(plugin, cfg, None, os.environ.get("RO_TASK_TEXT", ""), os.environ.get("RO_EPISODE_TEXT", ""))
+ sim.break_steps = int(z["break_steps"])
+ sim.commands = json.loads(str(z["commands"]))
+ return sim, np.asarray(z["rows"], np.float64).reshape(-1, sim.raw_dim)
+
+
+def replay_main(plugin: str, npz: str, out: str) -> dict:
+ sim, rows = _rebuild(plugin, npz)
+ for row in rows:
+ sim.step(row)
+ summary = {**sim.summary(), "state_sha": sim.state_sha()}
+ with open(out, "w") as f:
+ json.dump(summary, f, default=float)
+ return {"won": summary["won"], "state_sha": summary["state_sha"], "scores": summary["scores"]}
+
+
+def video_main(plugin: str, npz: str, out: str, max_frames: int = 1500) -> dict:
+ """The replay for humans: the cameras side by side, one frame every 4 control steps of play (game time at real speed:
+ 25 fps; sparser for a long match, at most about max_frames frames), breaks skipped; the score in the corner.
+ Writes out and out.last.png."""
+ import imageio.v2 as imageio
+ from PIL import Image, ImageDraw
+ sim, rows = _rebuild(plugin, npz)
+ every = max(4, math.ceil(len(rows) / max_frames))
+ cams = list(sim.cameras)
+ w = imageio.get_writer(out, fps=round(1.0 / (every * sim.control_dt)), macro_block_size=8, codec="libx264",
+ output_params=["-pix_fmt", "yuv420p"])
+ last, n = None, 0
+
+ def frame():
+ imgs = sim.images(cams, False)[0]
+ h = max(i.shape[0] for i in imgs.values())
+ row = np.concatenate([np.pad(imgs[c], ((0, h - imgs[c].shape[0]), (0, 0), (0, 0))) for c in cams], axis=1)
+ im = Image.fromarray(np.ascontiguousarray(row[..., :3]))
+ sc = sim.m.scores()
+ ImageDraw.Draw(im).text((8, im.height - 16), " ".join(f"{k} {v}" for k, v in sc.items()), fill=(255, 255, 0))
+ return np.asarray(im)
+
+ try:
+ for i, row in enumerate(rows):
+ was = sim.in_break
+ sim.step(row)
+ if (not was and i % every == 0) or sim.finished:
+ last = frame()
+ w.append_data(last)
+ n += 1
+ if sim.finished:
+ break
+ if last is None:
+ last = frame()
+ w.append_data(last)
+ n += 1
+ finally:
+ w.close()
+ Image.fromarray(last).save((out[:-4] if out.endswith(".mp4") else out) + ".last.png") # replay.last.png
+ return {"frames": n, "every": every}
+
+
+if __name__ == "__main__":
+ mode, plugin_path, npz_path, out_path = sys.argv[1:5]
+ res = replay_main(plugin_path, npz_path, out_path) if mode == "replay" else video_main(plugin_path, npz_path,
+ out_path)
+ print(json.dumps(res, default=float))
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/rcb_realtime.py b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/rcb_realtime.py
new file mode 100644
index 0000000000..e23f8cbd2c
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/rcb_realtime.py
@@ -0,0 +1,480 @@
+"""eai-standard/2.3, the standard-realtime mode's protocol: the sim service of HumanoidBench's `-standard-realtime` tasks
+(docs/PROTOCOL.md §4b, docs/LIMITED_MODE_PROTOCOL.md "Standard-realtime mode"; docs/benchmarks/humanoidbench.md). Entry
+point of the sidecar: `python /srv/rcb_realtime.py` (the adapter is server.py's, unchanged). 2.3 is 2.2 plus the realtime
+capability, every 2.2 addition optional: this service is rcb_service's 2.1 service with the capability, and reports
+eai-standard/2.3.
+
+It extends rcb_service.Service: the same endpoints, RCB1 frames, budgets (reset, wall clock), evidence, crash recovery
+and finalize. Only the time model differs. In standard mode time moves only inside calls; here the episode has a clock:
+
+- An episode starts paused, at the frozen start with the servos holding their starting targets. Its clock starts at its
+ first POST /submit or POST /observe with seconds > 0 (again after every reset, and after a crash recovery). From then
+ on one control step runs every control_dt x slowdown seconds of wall time, whether or not the agent sends anything,
+ until the episode ends; the clock stops there.
+- The service keeps a plan: one target row per coming control step. /submit expands its chunk (rows dt apart, `linear`
+ or `hold`, exactly as 2.1 does) into control steps and writes it into the plan from control step `at` (default: the
+ next one), replacing whatever was planned from there on, and answers at once. A chunk that arrives after its `at`
+ loses the rows whose steps are gone (`late_steps`). When the plan runs out the last target is held (zero-order
+ hold): a slow agent's robot keeps its last servo targets.
+- /observe with seconds = 0 answers at once; with seconds > 0 it watches the running episode that long (robot time)
+ and returns what the cameras saw. It never changes the plan.
+- `cameras = []` asks for no images at all (in 2.1 an empty list means every camera): a controller's proprio-only call.
+
+Grading is unchanged: every executed control step's sim row is journaled (trajectory_live.f64) and the graded episode's
+rows are replayed in a fresh simulator at the end. What is graded is the rows the simulator applied, not what was
+submitted, so the replay equals the live run however the timing went. Evidence added (never visible to the agent):
+ticks.f64 (per journal row: wall time, and the call whose chunk gave the row, -1 for a held one), calls.jsonl (one line
+per call; no calls/NNNNNN/ directories: a controller calls 50 times a second) and submitted.f64 (every row as sent:
+call id, then the row). final.json adds realtime, slowdown, max_lag_s, stalls, held_steps and late_steps.
+
+Threads: the simulator and its GL context belong to the main thread, which runs the clock and serves every request in
+between control steps; the HTTP threads only read, queue and encode. A control step that is due runs before any waiting
+request. A service that falls behind (a long render) runs the missed steps back to back, skipping none; more than
+MAX_LAG_S behind, it drops the debt instead (a stall, counted) rather than fast-forward the robot.
+
+A crash resumes the same episode from its last checkpoint (one per second of robot time while the clock runs), paused.
+A simulator crash is an infrastructure failure, never the agent's (PROTOCOL §4b, owner 2026-10-08). No call spans a
+crash here (submit answers at once), so a crash is never put down to the agent's call: past RCB_MAX_RESUMES restarts the
+trial ends `sim_crashed` (infra_error), a failed resume `resume_failed` (infra_error), and a simulator error that ends
+the graded episode (reason "error") sets infra_error in final.json too.
+"""
+from __future__ import annotations
+
+import collections
+import json
+import os
+import queue
+import sys
+import threading
+import time
+import traceback
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from urllib.parse import urlparse
+
+import numpy as np
+
+import rcb_service
+from rcb_service import MAX_BODY, Recorder, Refused, Service, bad_request
+
+PROTOCOL = "eai-standard/2.3" # the standard-realtime mode's protocol (PROTOCOL §4b); rcb_service.py itself serves 2.1
+MAX_LAG_S = 0.5 # behind the clock by more than this: drop the debt (a stall) instead of catching up
+CHECKPOINT_S = 1.0 # robot time between checkpoints while the clock runs (the most a crash loses)
+
+
+class _Job:
+ """One HTTP request, handed from its HTTP thread to the simulator's thread and back."""
+
+ def __init__(self, method: str, path: str, body: bytes, content_length: int | None = None):
+ self.method, self.path, self.body, self.content_length = method, path, body, content_length
+ self.done = threading.Event()
+ self.reply: tuple = () # ("raw", code, ctype, body) | ("rcb1", meta, parts) | ("rec", meta, Recorder)
+
+ def finish(self, *reply) -> None:
+ self.reply = reply
+ self.done.set()
+
+
+class _Watch:
+ """A pending /observe with seconds > 0: completes once its control steps have run (or the episode ended)."""
+
+ def __init__(self, job: _Job, rec: Recorder, start: int, steps: int, cameras: list[str], obs_id: int):
+ self.job, self.rec, self.cameras, self.obs_id = job, rec, cameras, obs_id
+ self.start, self.end = start, start + steps
+
+
+class RealtimeService(Service):
+ """rcb_service.Service with the realtime clock (module docstring)."""
+
+ def __init__(self, sim, *, slowdown: float | None = None, **kw):
+ self.slowdown = float(os.environ.get("RCB_SLOWDOWN") or 1.0) if slowdown is None else float(slowdown)
+ if not self.slowdown > 0:
+ raise ValueError("RCB_SLOWDOWN must be > 0")
+ self.wall_dt = sim.control_dt * self.slowdown
+ self.max_ahead = int(round(float(kw.get("max_chunk_s", 10.0)) / sim.control_dt)) # how far ahead `at` may be
+ self.plan: collections.deque = collections.deque() # (type, row, call id) for each coming control step
+ self.running = False
+ self.anchor_t = self.anchor_n = 0 # the clock: control step anchor_n was due at anchor_t
+ self.watches: list[_Watch] = []
+ self.q: queue.Queue = queue.Queue()
+ self.max_lag = self.lag = 0.0
+ self.stalls = self.held_steps = self.late_steps = 0
+ self._ticks: list[tuple[float, float]] = [] # (wall time, call id) per journal row not yet on disk
+ super().__init__(sim, **kw)
+ self.ticks_path = os.path.join(self.data, "ticks.f64")
+ self.ckpt_every = max(1, int(round(CHECKPOINT_S / sim.control_dt)))
+
+ # ------------------------------------------------------------------ spec, status, evidence
+ def _spec(self) -> dict:
+ spec = super()._spec()
+ spec["protocol"] = PROTOCOL
+ cdt = self.sim.control_dt
+ spec["timing"] = {
+ "realtime": True, "slowdown": self.slowdown, "control_dt": cdt,
+ "wall_s_per_control_step": cdt * self.slowdown,
+ "clock": "an episode starts paused; its clock starts at its first submit or observe with seconds > 0 (also "
+ "after a reset) and then runs one control step every wall_s_per_control_step seconds, whatever "
+ "you do, until the episode ends",
+ "submit": "answers at once: the chunk (rows dt apart, linear or hold) becomes the plan from control step "
+ "`at` (default: the next one), replacing what was planned from there; rows for steps already "
+ "gone are dropped (meta.late_steps); after the plan's last row that target is held",
+ "observe": "seconds = 0: now, at once; seconds > 0: watches the running episode that long and returns what "
+ "the cameras saw; never changes the plan",
+ "max_ahead_steps": self.max_ahead,
+ "no_images": "cameras = [] returns no images, only proprioception (the fastest call)"}
+ return spec
+
+ def _realtime_counters(self) -> dict:
+ return {"running": self.running, "planned_steps": len(self.plan), "lag_s": round(self.lag, 4)}
+
+ def status(self) -> dict:
+ return {**super().status(), **self._realtime_counters()}
+
+ def meta(self) -> dict:
+ return {**super().meta(), **self._realtime_counters()}
+
+ def _timing_record(self) -> dict:
+ return {"protocol": PROTOCOL, "realtime": 1, "slowdown": self.slowdown, "max_lag_s": round(self.max_lag, 4),
+ "stalls": self.stalls, "held_steps": self.held_steps, "late_steps": self.late_steps}
+
+ def _write_final(self) -> None:
+ self.verdict.update(self._timing_record()) # final.json merges the verdict; none of these keys is a verdict's
+ if self.reason == "error": # a simulator error ended the graded episode: infrastructure (§4b)
+ self.verdict["infra_error"] = 1
+ else: # (an episode that erred and was reset away is not graded)
+ self.verdict.pop("infra_error", None)
+ super()._write_final()
+
+ def _checkpoint(self, ev: str, **kw) -> None:
+ if self._ticks: # the tick log first: a crash in between leaves it too long
+ with open(self.ticks_path, "ab") as f:
+ f.write(np.asarray(self._ticks, dtype=np.float64).tobytes())
+ self._ticks = []
+ super()._checkpoint(ev, **kw)
+
+ def _save_call(self, meta: dict, actions: np.ndarray | None) -> None:
+ keep = ("type", "n_rows", "dt", "interpolate", "at", "start_step", "late_steps", "planned_steps", "seconds",
+ "control_steps", "episode", "done", "reason", "n_clipped", "lag_s", "note")
+ line = {"call": self.calls, "ts": time.time(), **{k: meta[k] for k in keep if k in meta}}
+ with open(os.path.join(self.data, "calls.jsonl"), "a") as f:
+ f.write(json.dumps(line) + "\n")
+ if actions is not None:
+ rows = np.concatenate([np.full((len(actions), 1), float(self.calls)), actions], axis=1)
+ with open(os.path.join(self.data, "submitted.f64"), "ab") as f:
+ f.write(np.asarray(rows, dtype=np.float64).tobytes())
+
+ # ------------------------------------------------------------------ start, clock
+ def start(self) -> None:
+ super().start()
+ rows = np.fromfile(self.ticks_path, dtype=np.float64) if os.path.exists(self.ticks_path) else np.zeros(0)
+ n = self.journal_rows
+ if rows.size > 2 * n: # the steps a crash lost from the journal go from the tick log too
+ rows[: 2 * n].tofile(self.ticks_path)
+ elif rows.size < 2 * n: # (an older tick log, short of the journal: pad it as unknown)
+ np.concatenate([rows, np.full(2 * n - rows.size, np.nan)]).tofile(self.ticks_path)
+ self.running = False # a resumed episode waits, paused, for the agent's next call
+
+ def _start_clock(self) -> None:
+ if not self.running and not self.done and not self.stopping:
+ self.running, self.anchor_t, self.anchor_n = True, time.monotonic(), len(self.episode)
+ self.log("clock_start", control_steps=len(self.episode), episode=self.resets + 1)
+
+ def _stop_clock(self, why: str) -> None:
+ if self.running:
+ self.running = False
+ self.log("clock_stop", why=why, control_steps=len(self.episode), max_lag_s=round(self.max_lag, 4))
+ self.plan.clear()
+
+ def _end(self, reason: str) -> None:
+ super()._end(reason)
+ self._stop_clock(reason) # pending watches are completed by whoever ended it, after this
+
+ def due_in(self, now: float) -> float | None:
+ """Seconds until the next control step is due (<= 0: due now); None while the clock is stopped."""
+ if not self.running or self.done or self.stopping:
+ return None
+ return self.anchor_t + (len(self.episode) - self.anchor_n) * self.wall_dt - now
+
+ def tick(self) -> None:
+ """One control step of the clock: the plan's row for it, or the held target."""
+ now = time.monotonic()
+ lag = -(self.due_in(now) or 0.0)
+ if lag > MAX_LAG_S: # far behind: re-anchor rather than rush the robot through the debt
+ self.stalls += 1
+ self.log("stall", behind_s=round(lag, 3), control_steps=len(self.episode))
+ self.anchor_t, self.anchor_n, lag = now, len(self.episode), 0.0
+ self.lag, self.max_lag = max(lag, 0.0), max(self.max_lag, lag)
+ if self.plan:
+ typ, row, src = self.plan.popleft()
+ else:
+ (typ, row), src = self.sim.hold(), -1
+ self.held_steps += 1
+ before = self.journal_rows
+ self._ticks.append((time.time(), float(src)))
+ try:
+ self._step(typ, row)
+ except Exception as exc: # noqa: BLE001 -- it ran and failed: the episode ends, as on hardware
+ traceback.print_exc()
+ if self.journal_rows == before:
+ self._ticks.pop()
+ self.log("error", path="clock", error=repr(exc)[:500])
+ self._end("error")
+ self._release_watches()
+ return
+ for w in list(self.watches):
+ w.rec.step()
+ if self.done or len(self.episode) >= w.end:
+ self._complete_watch(w)
+ if not self.done and len(self.episode) % self.ckpt_every == 0:
+ self._checkpoint("tick")
+
+ # ------------------------------------------------------------------ requests (simulator thread)
+ def dispatch(self, job: _Job) -> None:
+ """Serve one queued request; a watch finishes later, from tick()."""
+ try:
+ self.first_request()
+ path = urlparse(job.path).path
+ if job.method == "GET" and path in ("/spec", "/status"):
+ return job.finish("raw", *self._reply_json(200, self.spec if path == "/spec" else self.status()))
+ routes = {"/submit": self._rt_submit, "/observe": self._rt_observe}
+ if self.reset_budget:
+ routes["/reset"] = self._rt_reset
+ if job.method != "POST" or path not in routes:
+ return job.finish("raw", *self._reply_json(404, {"error": "no such endpoint"}))
+ if (len(job.body) if job.content_length is None else job.content_length) > MAX_BODY:
+ return job.finish("raw", *self._reply_json(413, {"error": f"request body over {MAX_BODY} bytes"}))
+ try:
+ meta, parts = self._decode(job.body)
+ except Exception as exc: # noqa: BLE001 -- any malformed body is the caller's error
+ return job.finish("raw", *self._reply_json(400, {"error": f"malformed body: {exc}"[:300]}))
+ try:
+ routes[path](meta, parts, job)
+ except Refused as exc: # 400 (bad_request), 409: nothing changed
+ job.finish("raw", *self._reply_json(exc.code, exc.body))
+ except Exception as exc: # noqa: BLE001 -- it ran and failed: the episode ends, as on hardware
+ traceback.print_exc()
+ self.log("error", path=path, error=repr(exc)[:500])
+ self._end("error")
+ self._release_watches()
+ if not job.done.is_set():
+ job.finish("raw", *self._reply_json(500, {"error": "simulator error", "detail": repr(exc)[:200]}))
+ except Exception as exc: # noqa: BLE001 -- never leave an HTTP thread waiting forever
+ traceback.print_exc()
+ if not job.done.is_set():
+ job.finish("raw", *self._reply_json(500, {"error": "service error", "detail": repr(exc)[:200]}))
+
+ def _view_rt(self, meta: dict, default_video: str) -> tuple[list[str], int, str, bool]:
+ """2.1's _view, plus cameras = [] for no images."""
+ none = isinstance(meta.get("cameras"), list) and not meta["cameras"]
+ cams, fps, video, depth = self._view(meta, default_video)
+ return ([], fps, "none", False) if none else (cams, fps, video, depth)
+
+ def _planned(self, step: int, nxt: int, typ: str) -> np.ndarray:
+ """The target in force at control step `step` (>= nxt - 1) as things stand: the plan's row for it, else the
+ plan's last row (held), else -- nothing planned, or a step already run -- the current command."""
+ i = step - nxt
+ if i < 0 or not self.plan:
+ return np.asarray(self.sim.command(typ), dtype=np.float64)
+ return np.asarray(self.plan[min(i, len(self.plan) - 1)][1], dtype=np.float64)
+
+ def _rt_submit(self, meta: dict, parts: dict, job: _Job) -> None:
+ if self.done or self.stopping:
+ raise self._conflict()
+ nxt = len(self.episode)
+ with bad_request():
+ typ = meta.get("type")
+ if not isinstance(typ, str) or typ not in self.types:
+ raise ValueError(f"type must be one of {sorted(self.types)}")
+ try:
+ A = np.asarray(parts["actions"]["data"] if "actions" in parts else meta.get("actions"),
+ dtype=np.float64)
+ except (TypeError, ValueError, KeyError):
+ raise ValueError("send the actions as an RCB1 array part `actions` or a JSON list of rows") from None
+ dim = int(self.types[typ]["dim"])
+ if A.ndim != 2 or A.shape[0] < 1 or A.shape[1] != dim:
+ raise ValueError(f"{typ} actions must be (T, {dim}) with T >= 1, got {list(A.shape)}")
+ if not np.all(np.isfinite(A)):
+ raise ValueError("actions contain NaN or inf")
+ cdt = self.sim.control_dt
+ try:
+ dt = cdt if meta.get("dt") is None else float(meta["dt"])
+ except (TypeError, ValueError):
+ raise ValueError("dt must be a number of seconds") from None
+ k = round(dt / cdt) if np.isfinite(dt / cdt) else 0
+ if k < 1 or abs(k * cdt - dt) > 1e-9:
+ raise ValueError(f"dt must be a positive whole multiple of control_dt = {cdt} s (never rounded)")
+ if k > 1 and not self.sim.interpolable(typ):
+ raise ValueError(f"{typ}: one row is one control step, so dt must be control_dt = {cdt} s")
+ if len(A) * k * cdt > self.max_chunk_s + 1e-9:
+ raise ValueError(f"the chunk covers {len(A) * k * cdt:g} s: "
+ f"more than max_chunk_s = {self.max_chunk_s:g}")
+ interp = meta.get("interpolate", "linear")
+ if interp not in ("linear", "hold"):
+ raise ValueError("interpolate must be linear or hold")
+ at = meta.get("at")
+ if at is not None:
+ if isinstance(at, bool) or not isinstance(at, (int, float)) or at != int(at) or at < 0:
+ raise ValueError("at must be a control step of this episode (an integer >= 0), "
+ "or null for the next one")
+ at = int(at)
+ if at - nxt > self.max_ahead:
+ raise ValueError(f"at = {at} is more than max_ahead_steps = {self.max_ahead} control steps ahead "
+ f"of the next one ({nxt})")
+ at = nxt if at is None else at
+ cams, fps, video, depth = self._view_rt(meta, "none")
+ rows, clipped = self.sim.clip(typ, A)
+ prev = self._planned(at - 1, nxt, typ) # linear starts from the target in force just before `at`
+ steps = []
+ for row in rows:
+ for j in range(1, k + 1):
+ steps.append(row if interp == "hold" else prev + (row - prev) * (j / k))
+ prev = row
+ late = max(0, nxt - at)
+ keep = at - nxt if at > nxt else 0
+ self.calls += 1
+ self.rows += len(A)
+ head = list(self.plan)[:keep]
+ if len(head) < keep: # a gap before `at`: the target in force then is held through it
+ fill = self._planned(at - 1, nxt, typ)
+ head += [(typ, fill, -1)] * (keep - len(head))
+ self.plan = collections.deque(head + [(typ, s, self.calls) for s in steps[late:]])
+ self.late_steps += min(late, len(steps))
+ self._start_clock()
+ rec = Recorder(self.sim, cams, fps, depth, "none")
+ rec.start()
+ rec.finish()
+ out = {**self.meta(), "chunk_id": self.calls, "type": typ, "n_rows": int(len(A)), "dt": dt,
+ "interpolate": interp, "at": at, "start_step": max(at, nxt), "late_steps": late,
+ "plan_end_step": nxt + len(self.plan), "clipped": clipped[:200], "n_clipped": len(clipped), "ok": True}
+ self._save_call({**out, "note": str(meta.get("note") or "")[:200]}, A)
+ job.finish("rec", out, rec)
+
+ def _rt_observe(self, meta: dict, parts: dict, job: _Job) -> None:
+ with bad_request():
+ try:
+ seconds = float(meta.get("seconds") or 0.0)
+ except (TypeError, ValueError):
+ raise ValueError("seconds must be a number") from None
+ if not 0.0 <= seconds <= self.max_watch_s:
+ raise ValueError(f"seconds must be in [0, {self.max_watch_s:g}]")
+ cams, fps, video, depth = self._view_rt(meta, "frames")
+ n = int(round(seconds / self.sim.control_dt)) if not (self.done or self.stopping) else 0
+ rec = Recorder(self.sim, cams, fps, depth, video if n or video != "mp4" else "frames") # no time: no video
+ self._frame_budget(rec, n)
+ self.calls += 1
+ rec.start()
+ if not n:
+ rec.finish()
+ out = {**self.meta(), "obs_id": self.calls, "seconds": 0.0, "control_steps_watch": 0, "ok": True}
+ self._save_call(out, None)
+ return job.finish("rec", out, rec)
+ self._start_clock()
+ self.watches.append(_Watch(job, rec, len(self.episode), n, cams, self.calls))
+
+ def _complete_watch(self, w: _Watch) -> None:
+ self.watches.remove(w)
+ w.rec.finish()
+ ran = max(0, min(len(self.episode), w.end) - w.start)
+ out = {**self.meta(), "obs_id": w.obs_id, "seconds": round(ran * self.sim.control_dt, 4),
+ "control_steps_watch": ran, "ok": True}
+ self._save_call(out, None)
+ w.job.finish("rec", out, w.rec)
+
+ def _release_watches(self) -> None:
+ for w in list(self.watches):
+ self._complete_watch(w)
+
+ def _rt_reset(self, meta: dict, parts: dict, job: _Job) -> None:
+ self._release_watches()
+ out, prts = self._reset(meta, parts) # 2.1's reset: checks, abandons the episode, a new one (paused)
+ self._stop_clock("reset")
+ job.finish("rcb1", {**out, **self._realtime_counters()}, prts)
+
+ # ------------------------------------------------------------------ the loop (simulator thread) and HTTP
+ def poll(self) -> None:
+ """After SIGUSR1: end the episode, answer the pending watches, finalize (Service.poll, plus the watches)."""
+ if self.stopping and not self.finalized:
+ if not self.done:
+ self._end("timeout")
+ self._release_watches()
+ self._finalize()
+
+ def loop(self, until: threading.Event | None = None) -> None:
+ """The simulator thread: control steps when due, requests in between, the wrap-up after SIGUSR1."""
+ while until is None or not until.is_set():
+ self.poll()
+ wait = self.due_in(time.monotonic())
+ if wait is not None and wait <= 0:
+ self.tick()
+ continue
+ try:
+ job = self.q.get(timeout=0.25 if wait is None else min(wait, 0.25))
+ except queue.Empty:
+ continue
+ self.dispatch(job)
+
+ def submit_job(self, job: _Job) -> tuple[int, str, bytes]:
+ """From an HTTP thread: queue the request, wait for the simulator thread, encode the answer here."""
+ self.q.put(job)
+ job.done.wait()
+ kind, *rest = job.reply
+ if kind == "raw":
+ return tuple(rest)
+ meta, payload = rest # a Recorder's parts are encoded here, off the simulator's thread
+ return self._reply_rcb1(meta, payload.parts() if kind == "rec" else payload)
+
+ def http_server(self, address: tuple[str, int]) -> ThreadingHTTPServer:
+ svc = self
+
+ class Handler(BaseHTTPRequestHandler):
+ timeout = 120
+
+ def log_message(self, *a):
+ pass
+
+ def _send(self, code: int, ctype: str, body: bytes) -> None:
+ self.send_response(code)
+ self.send_header("Content-Type", ctype)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_GET(self):
+ self._send(*svc.submit_job(_Job("GET", self.path, b"")))
+
+ def do_POST(self):
+ try:
+ n = int(self.headers.get("Content-Length") or 0)
+ except ValueError:
+ return self._send(*svc._reply_json(400, {"error": "bad Content-Length"}))
+ if n > MAX_BODY: # refused unread: drop the connection with it
+ self.close_connection = True
+ return self._send(*svc.submit_job(_Job("POST", self.path, b"", content_length=n)))
+ self._send(*svc.submit_job(_Job("POST", self.path, self.rfile.read(n))))
+
+ class Server(ThreadingHTTPServer):
+ daemon_threads = True
+
+ return Server(address, Handler)
+
+ def serve(self, port: int = 8000) -> None:
+ import signal
+ signal.signal(signal.SIGUSR1, self.on_sigusr1)
+ srv = self.bind(port)
+ threading.Thread(target=srv.serve_forever, name="http", daemon=True).start()
+ print(f"{rcb_service.PROTOCOL} sim service (realtime, slowdown {self.slowdown:g}) ready on :{port}", flush=True)
+ self.loop()
+
+
+def main(build, port: int = 8000) -> None:
+ """rcb_service.main -- the start count, back-off, startup watchdog, resume -- with this service in place of
+ Service (RCB_SLOWDOWN: 1 = real time), and eai-standard/2.3 in everything it logs and writes."""
+ rcb_service.Service = RealtimeService
+ rcb_service.PROTOCOL = PROTOCOL
+ rcb_service.main(build, port)
+
+
+if __name__ == "__main__":
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ import server # noqa: E402 -- the HumanoidBench adapter; picks the GL backend and restores the reward on import
+
+ main(server.build)
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/rcb_service.py b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/rcb_service.py
new file mode 100644
index 0000000000..14c53a477b
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/rcb_service.py
@@ -0,0 +1,759 @@
+"""eai-standard/2.1 sim service: the simulator-agnostic half of a standard-mode sidecar (docs/PROTOCOL.md §4,
+docs/LIMITED_MODE_PROTOCOL.md).
+
+The robot as a service: the agent reaches a simulator it cannot open over HTTP. GET /spec, GET /status, POST /observe
+and POST /submit; POST /reset exists only when the run grants resets (budget.reset > 0); everything else is 404.
+Responses that carry data are RCB1 frames (rcb1.py), never base64. Everything simulator-specific comes in through an
+adapter (the `Sim` contract below), so this file imports no simulator: a sidecar is its benchmark's adapter plus this.
+
+One thread does all of it -- the HTTP requests, the SIGUSR1 wrap-up, the finalize -- because a simulator's GL context
+belongs to the thread that made it (MuJoCo renders black frames from any other).
+
+The episode starts when the service is ready. It ends on success, by the task's own rule ("failed": the robot fell,
+the episode's control steps ran out), on a simulator error ("error"), or at SIGUSR1 ("timeout": the collect hook, once
+the agent's container is gone). With a reset budget, POST /reset abandons the running episode and starts another from
+the frozen instance; only the last episode is graded, and a success ends the trial.
+
+A request is checked in full before anything runs: whatever is wrong with it is a 400 and nothing ran. Once it runs,
+any failure is the simulator's: a 500, and the episode ends ("error").
+
+Evidence under DATA, never visible to the agent:
+ episode.jsonl one line per event; every state the service may resume from is a checkpoint (it carries
+ state_sha and journal_rows)
+ trajectory_live.f64 the journal: every executed control step in the simulator's own action space, float64
+ calls/NNNNNN/ each call's response meta and the actions as sent
+ startups.jsonl one line per process start
+ final.json kept current (written atomically); "finalized": true once the verdict is in
+ trajectory.npz, replay.mp4, replay.last.png the graded episode and its fresh replay
+
+Crash recovery: compose restarts a crashed service (restart: on-failure). It replays the journal up to the last
+checkpoint, checks the state hash, and continues the SAME episode -- never a reset. A call in flight is lost as a
+whole (its caller got an error, not a result, so nothing was learned). More than RCB_MAX_RESUMES restarts since the
+episode began (every process start counts, also one that died building the scene or replaying the journal) end the
+trial: sim_crashed_on_call if every crash happened while serving a call (the agent's failure), else sim_crashed
+(infrastructure, infra_error = 1). A verdict already on disk is never overwritten; a crash while rendering the video
+loses only the video.
+"""
+from __future__ import annotations
+
+import contextlib
+import errno
+import faulthandler
+import json
+import os
+import signal
+import tempfile
+import time
+import traceback
+from http.server import BaseHTTPRequestHandler, HTTPServer
+from typing import Callable
+from urllib.parse import urlparse
+
+import numpy as np
+
+import rcb1
+
+PROTOCOL = "eai-standard/2.1"
+MAX_BODY = 64 * 1024 * 1024 # request bodies above this are refused (413)
+MAX_RESPONSE = 256 * 1024 * 1024 # responses above this drop frames/ and depth/ (meta.degraded says so)
+MAX_VIDEO_FPS = 30
+MAX_FRAMES_PER_CALL = 3000 # images in one response (cameras x frames, depth counted again): bounds memory
+VIDEOS = ("mp4", "frames", "both", "none")
+ON_SERVICE_ERROR = ("if a call fails with a connection error or a 5xx, the service may have crashed and resumed the "
+ "same episode (never a reset): the state is the one after the last call that completed on the "
+ "service, which you may not have received; check GET /status before continuing")
+
+
+class Sim:
+ """The adapter contract, duck-typed (this class only documents it). One object = one frozen scene.
+
+ Rows come in three forms: what the agent sends (an action of one of spec()["action_types"]), the same after
+ clip(), and a "sim row" (to_sim()), the action in the simulator's own space, which step() executes and the
+ journal and the graded trajectory record (raw_dim floats)."""
+ control_dt: float # seconds per control step; a chunk's dt is a whole multiple of it
+ max_control_steps: int # the task's episode length: the episode ends there
+ cameras: tuple[str, ...] # every camera the agent may ask for
+ depth_cameras: tuple[str, ...] # the ones that also give depth
+ proprio_layout: list[str] # the proprio row's columns
+ raw_dim: int # a sim row's width
+
+ def spec(self) -> dict: ... # simulator, robot, task_text, episode, action_types, cameras, robot facts
+ def interpolable(self, type: str) -> bool: ... # may a row of this type span several control steps?
+ def images(self, cameras: list[str], depth: bool) -> tuple[dict, dict]: ... # ({cam: uint8 HxWx3}, {cam: float32 HxW m})
+ def proprio(self) -> np.ndarray: ... # float32, one value per proprio_layout column
+ def clip(self, type: str, rows: np.ndarray) -> tuple[np.ndarray, list]: ... # into the limits; [{row, index, reason}]
+ def to_sim(self, type: str, row: np.ndarray) -> np.ndarray: ... # an agent row -> a sim row
+ def command(self, type: str) -> np.ndarray: ... # the last row executed, exactly as clip() returned it: a chunk
+ # interpolates from it, so a chunk equals its rows sent one by one
+ def hold(self) -> tuple[str, np.ndarray]: ... # the row that holds the last command (/observe with seconds > 0)
+ def step(self, row: np.ndarray) -> tuple[bool, bool, dict]: ... # one control step -> (done, success, info)
+ def reset(self) -> None: ... # back to the frozen instance
+ def state_sha(self) -> str: ...
+ def verify(self, rows: np.ndarray) -> dict: ... # replay in a fresh simulator -> {"success", "state_sha"}
+ def save_trajectory(self, rows: np.ndarray, path: str, meta: dict) -> None: ...
+ def render_video(self, rows: np.ndarray, path: str) -> None: ... # path and path.last.png
+
+
+class GiveUp(Exception):
+ """The service will not run this trial's episode again; final.json says why."""
+
+
+class Refused(Exception):
+ """A request the service turns down with `code` and the JSON `body`; nothing was executed."""
+
+ def __init__(self, code: int, body: dict):
+ super().__init__(body.get("error"))
+ self.code, self.body = code, body
+
+
+def bad_request():
+ """Checking a request, before anything runs: whatever goes wrong here is the request's fault (400)."""
+ try:
+ yield
+ except Refused:
+ raise
+ except Exception as exc: # noqa: BLE001 -- a wrong type, value or shape of any field
+ raise Refused(400, {"error": str(exc)[:300] or type(exc).__name__}) from None
+
+
+def count_start(data: str) -> int:
+ """Record one process start in startups.jsonl; returns how many there have been."""
+ path = os.path.join(data, "startups.jsonl")
+ with open(path, "a") as f:
+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid()}) + "\n")
+ with open(path) as f:
+ return sum(1 for _ in f)
+
+
+def write_json_atomic(path: str, obj: dict) -> None:
+ """Write then rename: the collect hook polling the file never reads half of it."""
+ fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), suffix=".tmp")
+ with os.fdopen(fd, "w") as f:
+ json.dump(obj, f)
+ os.replace(tmp, path)
+
+
+def encode_mp4(frames: np.ndarray, fps: float) -> bytes:
+ import imageio.v2 as imageio
+ fd, path = tempfile.mkstemp(suffix=".mp4")
+ os.close(fd)
+ try:
+ with imageio.get_writer(path, format="FFMPEG", mode="I", fps=fps, codec="libx264", macro_block_size=1,
+ output_params=["-movflags", "+faststart", "-pix_fmt", "yuv420p"]) as w:
+ for f in frames:
+ w.append_data(np.ascontiguousarray(f))
+ with open(path, "rb") as f:
+ return f.read()
+ finally:
+ os.unlink(path)
+
+
+class Recorder:
+ """What one call returns: a proprio row at its start, every `every` control steps (the requested video_fps, rounded to
+ whole control steps) and at its end; with them the cameras' frames when a video or the frames are asked for, else
+ only the last frame (rendering is most of a call's cost)."""
+
+ def __init__(self, sim, cameras: list[str], fps: int, depth: bool, video: str):
+ self.sim, self.cams, self.depth, self.video = sim, cameras, depth, video
+ self.every = max(1, round(1.0 / (sim.control_dt * fps)))
+ self.fps = 1.0 / (self.every * sim.control_dt)
+ self.images = video != "none"
+ self.frames = {c: [] for c in cameras}
+ self.dep = {c: [] for c in cameras}
+ self.prop: list[np.ndarray] = []
+ self.k, self.grabbed_at = 0, None
+
+ def images_per_call(self, steps: int) -> int:
+ per_frame = len(self.cams) + (len(set(self.cams) & set(self.sim.depth_cameras)) if self.depth else 0)
+ return (steps // self.every + 2 if self.images else 1) * per_frame
+
+ def start(self) -> None:
+ self._grab(self.images)
+
+ def step(self) -> None:
+ self.k += 1
+ if self.k % self.every == 0:
+ self._grab(self.images)
+
+ def finish(self) -> None:
+ if self.grabbed_at != self.k:
+ self._grab(self.images)
+ if not self.images:
+ self._grab(True, proprio=False) # the one frame a call without video returns: the last
+
+ def _grab(self, images: bool, proprio: bool = True) -> None:
+ if images:
+ rgb, dep = self.sim.images(self.cams, self.depth)
+ for c in self.cams:
+ self.frames[c].append(rgb[c])
+ if c in dep:
+ self.dep[c].append(dep[c])
+ if proprio:
+ self.prop.append(np.asarray(self.sim.proprio(), np.float32))
+ self.grabbed_at = self.k
+
+ def parts(self) -> list:
+ out = []
+ for c in self.cams:
+ fr = np.stack(self.frames[c])
+ if self.video in ("mp4", "both"):
+ out.append((f"video/{c}", "mp4", encode_mp4(fr, self.fps), {"fps": round(self.fps, 3), "n": int(len(fr))}))
+ if self.video in ("frames", "both"):
+ out.append(rcb1.array_part(f"frames/{c}", fr))
+ out.append(rcb1.array_part(f"last/{c}", fr[-1]))
+ if self.dep[c]:
+ out.append(rcb1.array_part(f"depth/{c}", np.stack(self.dep[c]).astype(np.float16)))
+ out.append(rcb1.array_part("proprio", np.stack(self.prop)))
+ return out
+
+
+class Service:
+ """Episode bookkeeping, evidence and the HTTP endpoints around one `Sim`."""
+
+ def __init__(self, sim, *, data: str = "/data", reset_budget: int = 0, wall_clock_s: float = 3600.0,
+ max_chunk_s: float = 10.0, max_watch_s: float = 30.0, max_frames_per_call: int = MAX_FRAMES_PER_CALL,
+ max_resumes: int = 2):
+ self.sim, self.data = sim, data
+ self.reset_budget, self.wall_clock_s = int(reset_budget), float(wall_clock_s)
+ self.max_chunk_s, self.max_watch_s = float(max_chunk_s), float(max_watch_s)
+ self.max_frames, self.max_resumes = int(max_frames_per_call), int(max_resumes)
+ os.makedirs(os.path.join(data, "calls"), exist_ok=True)
+ self.journal_path = os.path.join(data, "trajectory_live.f64")
+ self.spec = self._spec()
+ self.types = {k: v for k, v in self.spec["action_types"].items() if isinstance(v, dict)}
+ self.calls = self.rows = self.resets = 0
+ self.journal_rows = 0 # control steps executed over the whole trial (the journal's length)
+ self.ep_start = 0 # where the current episode begins in the journal
+ self.episode: list[np.ndarray] = [] # the current episode's sim rows: what finalize grades
+ self.done, self.reason, self.success = False, None, False
+ self.stopping = False # SIGUSR1 seen: the agent is gone
+ self.finalized, self.verdict = False, {}
+ self.t0 = self.t_end = None # the clock starts at the agent's first request
+ self.starts = 1
+ self._unwritten: list[np.ndarray] = [] # sim rows executed since the last checkpoint
+
+ # ------------------------------------------------------------------ spec and status
+ def _spec(self) -> dict:
+ own = self.sim.spec()
+ core = {"protocol": PROTOCOL, "control_dt": self.sim.control_dt, "max_control_steps": self.sim.max_control_steps,
+ "max_chunk_s": self.max_chunk_s, "max_watch_s": self.max_watch_s, "max_video_fps": MAX_VIDEO_FPS,
+ "max_frames_per_call": self.max_frames, "proprio_layout": list(self.sim.proprio_layout),
+ "budget": {"reset": self.reset_budget, "wall_clock_s": self.wall_clock_s},
+ "clock": "time_s and elapsed_s count from your first request to the service; time_left_s is "
+ "budget.wall_clock_s minus time_s",
+ "on_service_error": ON_SERVICE_ERROR}
+ if clash := sorted(set(core) & set(own)):
+ raise ValueError(f"the adapter's spec() must not set {clash}")
+ cams = {c: {"rgb": True, "depth": c in self.sim.depth_cameras, **own["cameras"].get(c, {})}
+ for c in self.sim.cameras}
+ spec = {**core, **own, "cameras": cams}
+ if self.reset_budget:
+ spec["reset"] = ("POST /reset abandons the running episode and starts a new one from the same starting "
+ "state, budget.reset times in all; only the last episode is graded, and a success ends "
+ "the trial")
+ return spec
+
+ def clock(self) -> float:
+ return 0.0 if self.t0 is None else time.time() - self.t0
+
+ def _counters(self) -> dict:
+ out = {"calls": self.calls, "rows": self.rows, "control_steps": len(self.episode), "done": self.done,
+ "reason": self.reason}
+ if self.reset_budget:
+ out.update(episode=self.resets + 1, control_steps_total=self.journal_rows,
+ resets_left=0 if self.success or self.stopping else self.reset_budget - self.resets)
+ return out
+
+ def status(self) -> dict:
+ return {**self._counters(), "elapsed_s": round(self.clock(), 1)}
+
+ def meta(self) -> dict:
+ t = self.clock()
+ return {**self._counters(), "sim_time_s": round(len(self.episode) * self.sim.control_dt, 4),
+ "time_s": round(t, 2), "time_left_s": max(0.0, round(self.wall_clock_s - t, 1)),
+ "proprio": {"layout": list(self.sim.proprio_layout),
+ "now": np.asarray(self.sim.proprio(), np.float32).tolist()}}
+
+ # ------------------------------------------------------------------ evidence
+ def log(self, ev: str, **kw) -> None:
+ with open(os.path.join(self.data, "episode.jsonl"), "a") as f:
+ f.write(json.dumps({"ts": time.time(), "ev": ev, **kw}) + "\n")
+
+ def _events(self) -> list[dict]:
+ try:
+ with open(os.path.join(self.data, "episode.jsonl")) as f:
+ return [json.loads(line) for line in f if line.strip()]
+ except OSError:
+ return []
+
+ def _checkpoint(self, ev: str, **kw) -> None:
+ """Log a state this service may resume from, after appending everything executed since the last one to the
+ journal. Rows of a call that never reaches its checkpoint are lost with it, as the call is."""
+ if self._unwritten:
+ with open(self.journal_path, "ab") as f:
+ f.write(np.asarray(self._unwritten, dtype=np.float64).tobytes())
+ self._unwritten = []
+ self.log(ev, **kw, calls=self.calls, rows=self.rows, resets=self.resets, ep_start=self.ep_start,
+ journal_rows=self.journal_rows, done=self.done, reason=self.reason, success=self.success,
+ state_sha=self.sim.state_sha())
+ self._write_final()
+
+ def _write_final(self) -> None:
+ end = self.t_end or time.time()
+ d = {"protocol": PROTOCOL, "success": False, "live_success": self.success, "done": self.done,
+ "reason": self.reason, "calls": self.calls, "rows": self.rows, "control_steps": len(self.episode),
+ "control_steps_total": self.journal_rows, "episodes": self.resets + 1, "resets": self.resets,
+ "reset_budget": self.reset_budget, "elapsed_s": round(end - self.t0, 1) if self.t0 else 0.0,
+ "sim_startups": self.starts, "finalized": self.finalized, **self.verdict}
+ if "deterministic" in self.verdict:
+ d["success"] = bool(self.success and self.verdict["replay_success"] and self.verdict["deterministic"])
+ write_json_atomic(os.path.join(self.data, "final.json"), d)
+
+ def _save_call(self, meta: dict, actions: np.ndarray | None) -> None:
+ d = os.path.join(self.data, "calls", f"{self.calls:06d}")
+ os.makedirs(d, exist_ok=True)
+ with open(os.path.join(d, "meta.json"), "w") as f:
+ json.dump(meta, f)
+ if actions is not None:
+ np.save(os.path.join(d, "actions.npy"), actions)
+
+ # ------------------------------------------------------------------ start, resume, give up
+ def start(self) -> None:
+ """A fresh episode, or -- after a crash -- the same one again. Raises GiveUp when it must not run again."""
+ try:
+ with open(os.path.join(self.data, "startups.jsonl")) as f:
+ self.starts = max(1, sum(1 for _ in f))
+ except OSError:
+ self.starts = 1
+ ev = self._events()
+ if not any(e["ev"] == "start" for e in ev):
+ open(self.journal_path, "wb").close()
+ self._checkpoint("start", protocol=PROTOCOL, spec=self.spec, startup=self.starts)
+ else:
+ self._resume(ev)
+ with open(os.path.join(self.data, "server.pid"), "w") as f:
+ f.write(str(os.getpid()))
+
+ def _resume(self, ev: list[dict]) -> None:
+ path = os.path.join(self.data, "final.json")
+ try:
+ with open(path) as f:
+ fin = json.load(f)
+ except (OSError, ValueError):
+ fin = {}
+ if fin.get("finalized") or "deterministic" in fin:
+ # Graded already. A verdict that is not finalized: the process died rendering the video, all it lost.
+ if not fin.get("finalized"):
+ write_json_atomic(path, {**fin, "finalized": True, "video": False})
+ self._give_up("restarted after finalize", infra=False)
+ restarts = self.starts - int(next(e for e in ev if e["ev"] == "start")["startup"])
+ last = max(i for i, e in enumerate(ev) if e["ev"] in ("start", "resuming"))
+ in_call = False # did the process that died do so while serving a call?
+ for e in ev[last:]:
+ in_call = {"call_begin": True, "call_end": False}.get(e["ev"], in_call)
+ in_calls = sum(bool(e["crashed_in_call"]) for e in ev if e["ev"] == "resuming") + int(in_call)
+ if restarts > self.max_resumes:
+ agent = in_calls == restarts # every crash happened inside a call: the agent's commands did it
+ self._give_up("sim_crashed_on_call" if agent else "sim_crashed", infra=not agent)
+ self.log("resuming", crashed_in_call=in_call, restart=restarts)
+ cp = [e for e in ev if "state_sha" in e and "journal_rows" in e][-1]
+ n, dim = int(cp["journal_rows"]), int(self.sim.raw_dim)
+ rows = np.fromfile(self.journal_path, dtype=np.float64) if os.path.exists(self.journal_path) else np.zeros(0)
+ if rows.size < n * dim:
+ self._give_up("resume_failed: journal shorter than the log", infra=True)
+ rows = rows[: n * dim].reshape(n, dim)
+ for row in rows[cp["ep_start"]:]:
+ self.sim.step(row)
+ if self.sim.state_sha() != cp["state_sha"]:
+ self._give_up("resume_failed: replayed state differs from the logged one", infra=True)
+ rows.tofile(self.journal_path) # drop the steps of the call that was in flight
+ self.calls, self.rows, self.resets = int(cp["calls"]), int(cp["rows"]), int(cp["resets"])
+ self.ep_start, self.journal_rows = int(cp["ep_start"]), n
+ self.episode = [r.copy() for r in rows[self.ep_start:]]
+ self.done, self.reason, self.success = bool(cp["done"]), cp["reason"], bool(cp["success"])
+ self.t0 = next((e["t0"] for e in ev if e["ev"] == "first_request"), None)
+ if self.done:
+ self.t_end = next((e["ts"] for e in reversed(ev) if e["ev"] == "end"), cp["ts"])
+ self._checkpoint("resumed", downtime_s=round(time.time() - float(ev[-1]["ts"]), 1))
+
+ def _give_up(self, reason: str, infra: bool) -> None:
+ """End the trial without running its episode again: mark it failed (a finalized final.json is kept as it is),
+ leave the PID file for the collect hook, and stop."""
+ self.log("restart_refused", reason=reason)
+ path = os.path.join(self.data, "final.json")
+ try:
+ with open(path) as f:
+ fin = json.load(f)
+ except (OSError, ValueError):
+ fin = {}
+ if not fin.get("finalized"):
+ fin.update({"protocol": PROTOCOL, "success": False, "done": True, "reason": reason, "finalized": True,
+ **({"infra_error": 1} if infra else {})})
+ write_json_atomic(path, fin)
+ with open(os.path.join(self.data, "server.pid"), "w") as f:
+ f.write(str(os.getpid()))
+ raise GiveUp(reason)
+
+ # ------------------------------------------------------------------ requests
+ def first_request(self) -> None:
+ if self.t0 is None:
+ self.t0 = time.time()
+ self.log("first_request", t0=self.t0)
+
+ def handle(self, method: str, path: str, body: bytes = b"", content_length: int | None = None) -> tuple[int, str, bytes]:
+ """One request -> (status, content type, body): the whole HTTP surface, without the HTTP."""
+ self.first_request()
+ path = urlparse(path).path
+ if method == "GET" and path in ("/spec", "/status"):
+ return self._reply_json(200, self.spec if path == "/spec" else self.status())
+ routes = {"/submit": self._submit, "/observe": self._observe}
+ if self.reset_budget:
+ routes["/reset"] = self._reset
+ if method != "POST" or path not in routes:
+ return self._reply_json(404, {"error": "no such endpoint"})
+ if (len(body) if content_length is None else content_length) > MAX_BODY:
+ return self._reply_json(413, {"error": f"request body over {MAX_BODY} bytes"})
+ try:
+ meta, parts = self._decode(body)
+ except Exception as exc: # noqa: BLE001 -- any malformed body is the caller's error
+ return self._reply_json(400, {"error": f"malformed body: {exc}"[:300]})
+ self.log("call_begin", path=path, call=self.calls + 1)
+ try:
+ out, blobs = routes[path](meta, parts)
+ except Refused as exc: # 400 (bad_request), 409: nothing ran
+ return self._reply_json(exc.code, exc.body)
+ except Exception as exc: # noqa: BLE001 -- it ran and failed: the episode ends, as on hardware
+ traceback.print_exc()
+ self.log("error", path=path, error=repr(exc)[:500])
+ self._end("error")
+ return self._reply_json(500, {"error": "simulator error", "detail": repr(exc)[:200]})
+ finally:
+ self.log("call_end", path=path)
+ return self._reply_rcb1(out, blobs)
+
+ @staticmethod
+ def _decode(body: bytes) -> tuple[dict, dict]:
+ if body[:4] == rcb1.MAGIC:
+ meta, parts = rcb1.decode(body)
+ else:
+ meta, parts = json.loads(body or b"{}"), {}
+ if not isinstance(meta, dict):
+ raise ValueError("the body must be a JSON object or an RCB1 frame")
+ return meta, parts
+
+ @staticmethod
+ def _reply_json(code: int, obj: dict) -> tuple[int, str, bytes]:
+ return code, "application/json", json.dumps(obj).encode()
+
+ @staticmethod
+ def _reply_rcb1(meta: dict, parts: list) -> tuple[int, str, bytes]:
+ body = rcb1.encode(meta, parts)
+ if len(body) > MAX_RESPONSE:
+ parts = [p for p in parts if not p[0].startswith(("frames/", "depth/"))]
+ meta = {**meta, "degraded": f"response over {MAX_RESPONSE} bytes: frames/ and depth/ dropped"}
+ body = rcb1.encode(meta, parts)
+ return 200, "application/x-rcb1", body
+
+ def _view(self, meta: dict, default_video: str) -> tuple[list[str], int, str, bool]:
+ cams = meta.get("cameras") or list(self.sim.cameras)
+ if isinstance(cams, str):
+ cams = [c for c in cams.split(",") if c]
+ if not isinstance(cams, list) or (unknown := sorted(set(map(str, cams)) - set(self.sim.cameras))):
+ raise ValueError(f"unknown camera(s) {unknown if isinstance(cams, list) else cams}; "
+ f"the cameras are {list(self.sim.cameras)}")
+ try:
+ fps = int(meta.get("video_fps", 10))
+ except (TypeError, ValueError, OverflowError):
+ raise ValueError("video_fps must be an integer") from None
+ if not 1 <= fps <= MAX_VIDEO_FPS:
+ raise ValueError(f"video_fps must be in [1, {MAX_VIDEO_FPS}]")
+ video = meta.get("video", default_video)
+ if video not in VIDEOS:
+ raise ValueError(f"video must be one of {list(VIDEOS)}")
+ depth = bool(meta.get("include_depth", False))
+ if depth and not set(cams) & set(self.sim.depth_cameras):
+ raise ValueError(f"include_depth: none of {cams} has depth; spec()['cameras'][name]['depth'] says which do")
+ return cams, fps, video, depth
+
+ def _frame_budget(self, rec: Recorder, steps: int) -> None:
+ n = rec.images_per_call(steps)
+ if n > self.max_frames:
+ raise ValueError(f"this call would return {n} images (cameras x frames, depth counted again); the limit is "
+ f"{self.max_frames}: ask for fewer cameras, a lower video_fps or a shorter chunk")
+
+ def _conflict(self) -> Refused:
+ if self.stopping:
+ return Refused(409, {"error": "trial finished: your time is up", "reason": self.reason})
+ body = {"error": "episode finished", "reason": self.reason}
+ if self.reset_budget:
+ body["resets_left"] = 0 if self.success else self.reset_budget - self.resets
+ return Refused(409, body)
+
+ def _step(self, typ: str, row: np.ndarray) -> dict:
+ """One control step: execute, journal, and end the episode if it is over."""
+ sim_row = np.asarray(self.sim.to_sim(typ, row), dtype=np.float64)
+ done, success, info = self.sim.step(sim_row)
+ self._unwritten.append(sim_row)
+ self.journal_rows += 1
+ self.episode.append(sim_row)
+ if success:
+ self._end("success")
+ elif done or len(self.episode) >= self.sim.max_control_steps:
+ self._end("failed")
+ return info
+
+ def _end(self, reason: str) -> None:
+ if self.done:
+ return
+ self.done, self.reason, self.success = True, reason, reason == "success"
+ self.t_end = time.time()
+ try:
+ self._checkpoint("end")
+ except Exception as exc: # noqa: BLE001 -- a broken simulator may not even hash: the end is still logged
+ self.log("end", reason=reason, checkpoint_error=repr(exc)[:300])
+ self._write_final()
+
+ def _submit(self, meta: dict, parts: dict) -> tuple[dict, list]:
+ if self.done or self.stopping:
+ raise self._conflict()
+ with bad_request():
+ typ = meta.get("type")
+ if not isinstance(typ, str) or typ not in self.types:
+ raise ValueError(f"type must be one of {sorted(self.types)}")
+ try:
+ A = np.asarray(parts["actions"]["data"] if "actions" in parts else meta.get("actions"), dtype=np.float64)
+ except (TypeError, ValueError, KeyError):
+ raise ValueError("send the actions as an RCB1 array part `actions` or a JSON list of rows") from None
+ dim = int(self.types[typ]["dim"])
+ if A.ndim != 2 or A.shape[0] < 1 or A.shape[1] != dim:
+ raise ValueError(f"{typ} actions must be (T, {dim}) with T >= 1, got {list(A.shape)}")
+ if not np.all(np.isfinite(A)):
+ raise ValueError("actions contain NaN or inf")
+ cdt = self.sim.control_dt
+ try:
+ dt = cdt if meta.get("dt") is None else float(meta["dt"])
+ except (TypeError, ValueError):
+ raise ValueError("dt must be a number of seconds") from None
+ k = round(dt / cdt) if np.isfinite(dt / cdt) else 0
+ if k < 1 or abs(k * cdt - dt) > 1e-9:
+ raise ValueError(f"dt must be a positive whole multiple of control_dt = {cdt} s (never rounded)")
+ if k > 1 and not self.sim.interpolable(typ):
+ raise ValueError(f"{typ}: one row is one control step, so dt must be control_dt = {cdt} s")
+ if len(A) * k * cdt > self.max_chunk_s + 1e-9:
+ raise ValueError(f"the chunk covers {len(A) * k * cdt:g} s: more than max_chunk_s = {self.max_chunk_s:g}")
+ interp = meta.get("interpolate", "linear")
+ if interp not in ("linear", "hold"):
+ raise ValueError("interpolate must be linear or hold")
+ cams, fps, video, depth = self._view(meta, "mp4")
+ rec = Recorder(self.sim, cams, fps, depth, video)
+ self._frame_budget(rec, len(A) * k)
+ rows, clipped = self.sim.clip(typ, A)
+ before, info, executed, stop = len(self.episode), {}, 0, False
+ prev = np.asarray(self.sim.command(typ), dtype=np.float64)
+ rec.start()
+ for i, row in enumerate(rows):
+ for j in range(1, k + 1):
+ info = self._step(typ, row if interp == "hold" else prev + (row - prev) * (j / k))
+ rec.step()
+ if self.done or self.stopping or info.get("blocked"):
+ stop = True
+ break
+ executed, prev = i + 1, row
+ if stop:
+ break
+ rec.finish()
+ self.calls += 1
+ self.rows += executed
+ out = {**self.meta(), "chunk_id": self.calls, "type": typ, "executed_rows": executed,
+ "control_steps_chunk": len(self.episode) - before, "clipped": clipped[:200], "n_clipped": len(clipped),
+ **info, "ok": True}
+ self._checkpoint("submit", type=typ, n_rows=len(A), dt=dt, interpolate=interp, cameras=cams,
+ note=str(meta.get("note") or "")[:500], executed_rows=executed, n_clipped=len(clipped), **info)
+ self._save_call(out, A)
+ return out, rec.parts()
+
+ def _observe(self, meta: dict, parts: dict) -> tuple[dict, list]:
+ with bad_request():
+ try:
+ seconds = float(meta.get("seconds") or 0.0)
+ except (TypeError, ValueError):
+ raise ValueError("seconds must be a number") from None
+ if not 0.0 <= seconds <= self.max_watch_s:
+ raise ValueError(f"seconds must be in [0, {self.max_watch_s:g}]")
+ cams, fps, video, depth = self._view(meta, "frames")
+ n = int(round(seconds / self.sim.control_dt)) if not (self.done or self.stopping) else 0
+ rec = Recorder(self.sim, cams, fps, depth, video if n or video != "mp4" else "frames") # no time: no video
+ self._frame_budget(rec, n)
+ before = len(self.episode)
+ rec.start()
+ if n:
+ typ, row = self.sim.hold()
+ for _ in range(n):
+ self._step(typ, row)
+ rec.step()
+ if self.done or self.stopping:
+ break
+ rec.finish()
+ self.calls += 1
+ ran = len(self.episode) - before
+ out = {**self.meta(), "obs_id": self.calls, "seconds": round(ran * self.sim.control_dt, 4),
+ "control_steps_watch": ran, "ok": True}
+ self._checkpoint("observe", seconds=out["seconds"], cameras=cams)
+ self._save_call(out, None)
+ return out, rec.parts()
+
+ def _reset(self, meta: dict, parts: dict) -> tuple[dict, list]:
+ if self.success or self.stopping:
+ raise Refused(409, {"error": "trial finished: " + ("an episode succeeded" if self.success else "your time is up"),
+ "reason": self.reason})
+ if self.resets >= self.reset_budget:
+ raise Refused(409, {"error": "reset budget exhausted", "budget": self.reset_budget})
+ with bad_request():
+ cams, fps, video, depth = self._view(meta, "frames")
+ if not self.done:
+ self._end("reset") # the running episode is abandoned
+ self.sim.reset()
+ self.resets += 1
+ self.ep_start, self.episode = self.journal_rows, []
+ self.done, self.reason, self.success, self.t_end = False, None, False, None
+ rec = Recorder(self.sim, cams, fps, depth, "frames" if video == "mp4" else video) # no time: no video
+ rec.start()
+ rec.finish()
+ self.calls += 1
+ out = {**self.meta(), "ok": True}
+ self._checkpoint("reset", cameras=cams)
+ self._save_call(out, None)
+ return out, rec.parts()
+
+ # ------------------------------------------------------------------ the end of the trial
+ def on_sigusr1(self, *_) -> None:
+ """The agent is gone (the [[verifier.collect]] hook). Only a flag: the handler may fire in the middle of a
+ request; a chunk stops at its next control step and poll() wraps up between requests."""
+ self.stopping = True
+
+ def poll(self) -> None:
+ """Between requests (the HTTP loop calls it every 0.5 s): after SIGUSR1, end the episode and finalize."""
+ if self.stopping and not self.finalized:
+ if not self.done:
+ self._end("timeout")
+ self._finalize()
+
+ def _finalize(self) -> None:
+ """The graded episode (every control step since the last reset) as a trajectory, its replay in a fresh
+ simulator (success, and bit-exact agreement with the live run), and a video for humans."""
+ try:
+ rows = np.asarray(self.episode, dtype=np.float64).reshape(-1, self.sim.raw_dim)
+ live_sha = self.sim.state_sha()
+ self.sim.save_trajectory(rows, os.path.join(self.data, "trajectory.npz"),
+ {"source": "standard-mode episode", "protocol": PROTOCOL, "reason": self.reason,
+ "episode": self.resets + 1})
+ rep = self.sim.verify(rows)
+ self.verdict = {"n_actions": int(len(rows)), "replay_success": bool(rep["success"]),
+ "deterministic": rep["state_sha"] == live_sha, "state_sha": live_sha, "video": False}
+ self.log("replay", **self.verdict)
+ self._write_final() # the verdict is on disk before any video is rendered
+ try:
+ self.sim.render_video(rows, os.path.join(self.data, "replay.mp4"))
+ self.verdict["video"] = True
+ except Exception: # noqa: BLE001 -- the video is for humans; it never decides the verdict
+ traceback.print_exc()
+ except Exception as exc: # noqa: BLE001
+ traceback.print_exc()
+ self.log("finalize_error", error=repr(exc)[:500])
+ self.verdict = {"finalize_error": repr(exc)[:300]}
+ self.finalized = True
+ self._write_final()
+
+ # ------------------------------------------------------------------ HTTP
+ def http_server(self, address: tuple[str, int]) -> HTTPServer:
+ svc = self
+
+ class Handler(BaseHTTPRequestHandler):
+ timeout = 120 # a client that stalls mid-request is dropped: one thread serves everyone
+
+ def log_message(self, *a):
+ pass
+
+ def _send(self, code: int, ctype: str, body: bytes) -> None:
+ self.send_response(code)
+ self.send_header("Content-Type", ctype)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_GET(self):
+ self._send(*svc.handle("GET", self.path))
+
+ def do_POST(self):
+ try:
+ n = int(self.headers.get("Content-Length") or 0)
+ except ValueError:
+ return self._send(*svc._reply_json(400, {"error": "bad Content-Length"}))
+ if n > MAX_BODY: # refused unread: drop the connection with it
+ self.close_connection = True
+ return self._send(*svc.handle("POST", self.path, b"", content_length=n))
+ self._send(*svc.handle("POST", self.path, self.rfile.read(n)))
+
+ class Server(HTTPServer):
+ def service_actions(self):
+ svc.poll()
+
+ return Server(address, Handler)
+
+ def bind(self, port: int) -> HTTPServer:
+ """The HTTP server on `port`. Something else may hold the port -- in the network namespace it shares with the
+ agent's container, an agent's process can take it while this service (re)starts -- so wait, not die (a death
+ here would count as a crash); the trial can still end meanwhile (SIGUSR1)."""
+ busy = False
+ while True:
+ try:
+ return self.http_server(("0.0.0.0", port))
+ except OSError as exc:
+ if exc.errno != errno.EADDRINUSE:
+ raise
+ if not busy:
+ busy = True
+ self.log("port_busy", port=port)
+ self.poll()
+ time.sleep(1.0)
+
+ def serve(self, port: int = 8000) -> None:
+ signal.signal(signal.SIGUSR1, self.on_sigusr1)
+ srv = self.bind(port)
+ print(f"{PROTOCOL} sim service ready on :{port}", flush=True)
+ srv.serve_forever()
+
+
+def main(build: Callable[[], Sim], port: int = 8000) -> None:
+ """A sidecar's life: count the start, back off after a failed one, build the scene under a startup watchdog, resume
+ or start the episode, serve. Settings: RCB_DATA (/data), RCB_RESET_BUDGET (0), RCB_WALL_CLOCK_S (3600),
+ RCB_STARTUP_TIMEOUT_S (300), RCB_MAX_RESUMES (2)."""
+ env = os.environ.get
+ data = env("RCB_DATA", "/data")
+ os.makedirs(data, exist_ok=True)
+ starts = count_start(data)
+ # Compose restarts a failed start at once; a scene that failed to build (e.g. the GPU full of other trials) would
+ # meet the same conditions every time, so wait before rebuilding -- only before the episode exists.
+ if starts > 1 and not os.path.exists(os.path.join(data, "episode.jsonl")):
+ time.sleep(min(120, 20 * (starts - 1)))
+ pending: list[int] = []
+ signal.signal(signal.SIGUSR1, lambda *_: pending.append(1)) # its default action would kill the process
+ # A scene build that hangs (no crash, so compose never restarts it) must end the process. Neither a Python thread
+ # (a native hang may hold the GIL) nor SIGALRM's default action (PID 1 ignores it) can; faulthandler's C watchdog
+ # dumps every thread's traceback and exits. Before the scene exists no episode exists: the retry is no reset.
+ faulthandler.dump_traceback_later(float(env("RCB_STARTUP_TIMEOUT_S", "300")), exit=True)
+ sim = build()
+ faulthandler.cancel_dump_traceback_later() # a resume replay may take minutes
+ svc = Service(sim, data=data, reset_budget=int(env("RCB_RESET_BUDGET") or 0),
+ wall_clock_s=float(env("RCB_WALL_CLOCK_S") or 3600), max_resumes=int(env("RCB_MAX_RESUMES") or 2))
+ try:
+ svc.start()
+ except GiveUp as exc:
+ print(f"restart refused: {exc}", flush=True)
+ signal.signal(signal.SIGUSR1, lambda *_: None)
+ while True:
+ time.sleep(3600)
+ if pending:
+ svc.on_sigusr1()
+ svc.serve(port)
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/__init__.py b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/__init__.py
new file mode 100644
index 0000000000..9a55e841d4
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/__init__.py
@@ -0,0 +1,40 @@
+"""Renderer plugins (docs/framework_zh.md §3.1): a renderer draws a sport's scene, from its camera definitions, for
+one world state. Sports never import a renderer; the core calls the task's observation renderer (task parameter
+`renderer`, default DEFAULT) and the viewing tools any renderer for re-renders.
+
+ from renderers import load, Scene, CameraDef
+ R = load("mujoco")(Scene.from_file("scene.xml"))
+ images = R.render({"qpos": qpos}, [CameraDef("behind", pos, lookat)])
+"""
+from __future__ import annotations
+
+import importlib
+
+from .base import CameraDef, Renderer, RendererUnavailable, Scene # noqa: F401
+
+DEFAULT = "mujoco"
+REGISTRY = { # name -> (module, realtime, needs_gpu, requires)
+ "mujoco": ("renderers.mujoco", True, False, "mujoco; MUJOCO_GL=osmesa (CPU) or egl (GPU)"),
+ "mujoco-showcase": ("renderers.mujoco_showcase", True, False, "as mujoco"),
+ "cycles": ("renderers.cycles", False, True, "Docker, the rcb-showcase-blender image, an NVIDIA GPU (or device=CPU)"),
+ "isaac": ("renderers.isaac", False, True, "Docker, the Isaac Sim 4.5 image, an NVIDIA RTX GPU"),
+}
+
+
+def load(name: str = DEFAULT):
+ """The Renderer subclass registered under `name`."""
+ if name not in REGISTRY:
+ raise KeyError(f"unknown renderer {name!r}; have {sorted(REGISTRY)}")
+ return importlib.import_module(REGISTRY[name][0]).RENDERER
+
+
+def available() -> dict:
+ return {n: {"realtime": rt, "needs_gpu": gpu, "requires": req} for n, (_, rt, gpu, req) in REGISTRY.items()}
+
+
+def players_model(sport_dir, match: Scene):
+ """For a sport that draws its own images (the renderers' interface for sports): the compiled MjModel of the
+ players' presentation scene its presentation.toml declares (`players`, renderer rule 6; the same kinematics as
+ `match` checked), or None when it declares none (draw the match model). See renderers/presentation."""
+ from .presentation import players_model as _players_model
+ return _players_model(sport_dir, match)
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/base.py b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/base.py
new file mode 100644
index 0000000000..7cf75e40ba
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/base.py
@@ -0,0 +1,156 @@
+"""The renderer plugin interface (docs/framework_zh.md §3.1, renderer rules §9): a renderer turns a sport's scene,
+camera definitions and one world state into images. It never changes physics or the match state: it draws on its own
+copy of the model.
+
+ scene = Scene(engine="mujoco", xml=MJCF text, assets={relative path: bytes}, look=None or a presentation look)
+ a presentation scene (renderers/presentation.py, spectators only) also carries `match`, the match scene
+ it dresses: same kinematics, extra visual-only geoms (scene_check.same_kinematics)
+ cameras = [CameraDef(name, pos, lookat, up, fovy_deg, width, height), ...] (what Match.cameras(seat) returns)
+ state = {"qpos": [...], optional "mocap_pos": [...], "mocap_quat": [...]}
+ images = Renderer(scene).render(state, cameras) -> one H x W x 3 uint8 array per camera
+
+The camera model is a pinhole that every renderer must reproduce (CameraDef.project): pixel (u, v) from the image's
+top-left corner, u to the right, v down, vertical field of view fovy_deg. Only numpy is needed here; engines import
+their own libraries inside their backend packages. Never put the renderers/ directory itself on sys.path (its
+`mujoco` backend package would shadow the mujoco library); import it as the package `renderers`.
+"""
+from __future__ import annotations
+
+import math
+from abc import ABC, abstractmethod
+from dataclasses import dataclass, field
+from pathlib import Path
+
+import numpy as np
+
+
+class RendererUnavailable(RuntimeError):
+ """The renderer cannot run here; `requirements` says what it needs (GPU, image, library ...)."""
+
+ def __init__(self, name: str, why: str, requirements: str = ""):
+ super().__init__(f"renderer {name!r} unavailable: {why}" + (f" (requires: {requirements})" if requirements else ""))
+ self.name, self.why, self.requirements = name, why, requirements
+
+
+def _unit(v):
+ v = np.asarray(v, dtype=float)
+ n = np.linalg.norm(v)
+ if not np.isfinite(n) or n < 1e-12:
+ raise ValueError("degenerate camera direction")
+ return v / n
+
+
+@dataclass
+class CameraDef:
+ name: str
+ pos: tuple
+ lookat: tuple
+ up: tuple = (0.0, 0.0, 1.0)
+ fovy_deg: float = 45.0
+ width: int = 320
+ height: int = 240
+
+ def __post_init__(self):
+ self.pos = tuple(float(x) for x in self.pos)
+ self.lookat = tuple(float(x) for x in self.lookat)
+ self.up = tuple(float(x) for x in self.up)
+ self.fovy_deg, self.width, self.height = float(self.fovy_deg), int(self.width), int(self.height)
+ if len(self.pos) != 3 or len(self.lookat) != 3 or len(self.up) != 3:
+ raise ValueError("pos, lookat and up are 3-vectors")
+ if not 0 < self.fovy_deg < 180 or self.width <= 0 or self.height <= 0:
+ raise ValueError("fovy_deg in (0, 180), positive width and height")
+ self.basis() # raises on a degenerate pose
+
+ @staticmethod
+ def from_dict(d: dict) -> "CameraDef":
+ keys = ("name", "pos", "lookat", "up", "fovy_deg", "width", "height")
+ return CameraDef(**{k: d[k] for k in keys if k in d})
+
+ def to_dict(self) -> dict:
+ return {"name": self.name, "pos": list(self.pos), "lookat": list(self.lookat), "up": list(self.up),
+ "fovy_deg": self.fovy_deg, "width": self.width, "height": self.height}
+
+ def focal_px(self) -> float:
+ return (self.height / 2) / math.tan(math.radians(self.fovy_deg) / 2)
+
+ def intrinsics(self) -> dict:
+ return {"focal_px": self.focal_px(), "principal_point_px": [self.width / 2, self.height / 2],
+ "width": self.width, "height": self.height}
+
+ def basis(self):
+ """(right, up, forward) unit vectors in the world frame."""
+ fwd = _unit(np.subtract(self.lookat, self.pos))
+ right = _unit(np.cross(fwd, self.up))
+ up = np.cross(right, fwd)
+ return right, up, fwd
+
+ def project(self, point):
+ """Pixel (u, v) of a world point (u right, v down, from the top-left corner; continuous coordinates, so the
+ centre of pixel column i is u = i + 0.5). None if the point is behind the camera."""
+ right, up, fwd = self.basis()
+ d = np.subtract(point, self.pos)
+ depth = float(d @ fwd)
+ if depth <= 1e-9:
+ return None
+ f = self.focal_px()
+ return (self.width / 2 + f * float(d @ right) / depth, self.height / 2 - f * float(d @ up) / depth)
+
+ def spherical(self):
+ """(lookat, distance, azimuth_deg, elevation_deg): the free-camera form the showcase exporters use."""
+ d = np.subtract(self.lookat, self.pos)
+ dist = float(np.linalg.norm(d))
+ az = math.degrees(math.atan2(d[1], d[0]))
+ el = math.degrees(math.asin(max(-1.0, min(1.0, d[2] / dist))))
+ return list(self.lookat), dist, az, el
+
+
+@dataclass
+class Scene:
+ engine: str = "mujoco" # the physics engine whose scene format `xml` is in
+ xml: str = "" # MJCF text (engine "mujoco")
+ assets: dict = field(default_factory=dict) # {path as referenced by the xml (with meshdir/texturedir): bytes}
+ look: dict | None = None # optional presentation appearance (showcase renderers only)
+ match: "Scene | None" = None # set on a presentation scene only: the match scene it dresses
+ credits: tuple = () # presentation scene: what was added, with its source and licence
+ players: bool = False # a presentation scene the sport declares for its players' images too
+
+ @property
+ def is_presentation(self) -> bool:
+ """A presentation scene (renderers/presentation): drawn for the players' images only when `players` is set
+ (the sport declares it, renderer rule 6), else for spectators only."""
+ return self.match is not None
+
+ @staticmethod
+ def from_file(path, look=None) -> "Scene":
+ """A scene file plus every other file below its directory as an asset (paths relative to that directory)."""
+ p = Path(path)
+ assets = {str(f.relative_to(p.parent)): f.read_bytes() for f in sorted(p.parent.rglob("*"))
+ if f.is_file() and f != p and "__pycache__" not in f.parts}
+ return Scene(engine="mujoco", xml=p.read_text(), assets=assets, look=look)
+
+
+class Renderer(ABC):
+ name: str = ""
+ realtime: bool = True # fast enough for player images (still subject to the task's frame budget)
+ needs_gpu: bool = False
+ label: str | None = None # the tag a re-rendered frame carries ("re-rendered: <engine>"); None = default
+
+ def __init__(self, scene: Scene, **opts):
+ self.scene, self.opts = scene, opts
+
+ @abstractmethod
+ def render(self, state: dict, cameras: list) -> list:
+ """One H x W x 3 uint8 image per camera (CameraDef or its dict form), for the given world state."""
+
+ def close(self):
+ pass
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ self.close()
+
+
+def as_cameras(cameras) -> list:
+ return [c if isinstance(c, CameraDef) else CameraDef.from_dict(c) for c in cameras]
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/mujoco/__init__.py b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/mujoco/__init__.py
new file mode 100644
index 0000000000..1f52d6a69d
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/mujoco/__init__.py
@@ -0,0 +1,144 @@
+"""The default renderer: MuJoCo's own rasterizer (CPU with MUJOCO_GL=osmesa, GPU with egl), real time.
+
+The scene is compiled once from its MJCF text with spare world-body cameras added; each CameraDef is drawn by
+setting one spare camera's pose and vertical field of view exactly (cam_pos / cam_quat / cam_fovy), so the picture
+follows CameraDef.project to the pixel. The renderer keeps its own MjModel / MjData: the match's world is never
+touched. A presentation scene (Scene.match set; spectators only) is drawn only when its kinematics equal the match
+scene's (scene_check.same_kinematics); every renderer built on this one inherits the check."""
+from __future__ import annotations
+
+import numpy as np
+
+from ..base import CameraDef, Renderer, RendererUnavailable, Scene, as_cameras
+
+SPARE = "_ro_cam"
+
+
+def camera_quat(cam: CameraDef):
+ """MuJoCo camera frame: x = image right, y = image up, looking along -z."""
+ import mujoco as mj
+ right, up, fwd = cam.basis()
+ R = np.column_stack([right, up, -fwd])
+ q = np.zeros(4)
+ mj.mju_mat2Quat(q, R.reshape(-1))
+ return q
+
+
+def compile_spec(spec, n_cams: int, size):
+ """Add n spare cameras and make the off-screen buffer at least `size` (w, h); returns the compiled model."""
+ g = spec.visual.global_
+ g.offwidth, g.offheight = max(int(g.offwidth), int(size[0])), max(int(g.offheight), int(size[1]))
+ for i in range(n_cams):
+ spec.worldbody.add_camera(name=f"{SPARE}{i}", pos=[0, 0, 0], quat=[1, 0, 0, 0], fovy=45)
+ return spec.compile()
+
+
+def load_spec(scene: Scene):
+ import mujoco as mj
+ if scene.engine != "mujoco":
+ raise RendererUnavailable("mujoco", f"scene engine {scene.engine!r} is not MJCF")
+ return mj.MjSpec.from_string(scene.xml, assets=dict(scene.assets or {}))
+
+
+class MujocoRenderer(Renderer):
+ name = "mujoco"
+ title = "MuJoCo"
+ realtime = True
+ needs_gpu = False
+ label = None # the competition picture: no tag
+
+ def __init__(self, scene: Scene, n_cams: int = 8, size=(640, 480), **opts):
+ super().__init__(scene, **opts)
+ try:
+ import mujoco # noqa: F401
+ except ImportError as exc: # pragma: no cover - the sim images have it
+ raise RendererUnavailable(self.name, "the mujoco Python package is missing", "mujoco") from exc
+ self._n, self._size = int(n_cams), tuple(size)
+ self._build()
+
+ # ---------------------------------------------------------------- model
+ def make_spec(self):
+ """The MjSpec to draw (subclasses change only visual properties)."""
+ return load_spec(self.scene)
+
+ def _build(self):
+ import mujoco as mj
+ self.close()
+ self.m = compile_spec(self.make_spec(), self._n, self._size)
+ if self.scene.match is not None: # a presentation scene: same kinematics as the match scene
+ from ..scene_check import same_kinematics
+ bad = same_kinematics(compile_spec(load_spec(self.scene.match), self._n, self._size), self.m)
+ if bad:
+ raise RuntimeError(f"{self.name}: the presentation scene's kinematics differ from the match scene: "
+ f"{bad[:8]}")
+ self.d = mj.MjData(self.m)
+ self.cam_ids = [self.m.camera(f"{SPARE}{i}").id for i in range(self._n)]
+ self._r = {}
+
+ def _renderer(self, w, h):
+ import mujoco as mj
+ if (w, h) not in self._r:
+ self._r[w, h] = mj.Renderer(self.m, height=h, width=w)
+ return self._r[w, h]
+
+ def set_state(self, state: dict):
+ import mujoco as mj
+ m, d = self.m, self.d
+ q = np.asarray(state.get("qpos", d.qpos), dtype=float)
+ if q.shape != (m.nq,):
+ raise ValueError(f"state qpos has {q.size} values, the scene has nq={m.nq}")
+ d.qpos[:] = q
+ if m.nmocap:
+ if "mocap_pos" in state:
+ d.mocap_pos[:] = np.asarray(state["mocap_pos"], float).reshape(m.nmocap, 3)
+ if "mocap_quat" in state:
+ d.mocap_quat[:] = np.asarray(state["mocap_quat"], float).reshape(m.nmocap, 4)
+ mj.mj_kinematics(m, d)
+ mj.mj_comPos(m, d)
+ mj.mj_camlight(m, d)
+
+ # ---------------------------------------------------------------- drawing
+ def render(self, state: dict, cameras: list) -> list:
+ import mujoco as mj
+ cams = as_cameras(cameras)
+ w_max, h_max = max([c.width for c in cams] + [1]), max([c.height for c in cams] + [1])
+ if len(cams) > self._n or w_max > self.m.vis.global_.offwidth or h_max > self.m.vis.global_.offheight:
+ self._n = max(self._n, len(cams))
+ self._size = (max(self._size[0], w_max), max(self._size[1], h_max))
+ self._build()
+ self.set_state(state)
+ for cam, cid in zip(cams, self.cam_ids):
+ self.m.cam_pos[cid] = cam.pos
+ self.m.cam_quat[cid] = camera_quat(cam)
+ self.m.cam_fovy[cid] = cam.fovy_deg
+ mj.mj_camlight(self.m, self.d) # camera world poses from the new cam_pos / cam_quat
+ self._clip(cams)
+ out = []
+ for cam, cid in zip(cams, self.cam_ids):
+ r = self._renderer(cam.width, cam.height)
+ r.update_scene(self.d, camera=cid)
+ out.append(self.post(np.array(r.render(), dtype=np.uint8, copy=True), cam))
+ return out
+
+ def _clip(self, cams):
+ """MuJoCo clips at zfar * stat.extent: keep every geom of the current state inside every camera's far plane
+ (a small scene seen from afar, or a body far from the scene centre, would otherwise vanish). Visualization
+ only, on our own model copy."""
+ m, d = self.m, self.d
+ ext = max(float(m.stat.extent), 1e-6)
+ pts = np.asarray(d.geom_xpos) if m.ngeom else np.zeros((1, 3))
+ rb = float(np.max(m.geom_rbound)) if m.ngeom else 0.0
+ reach = max(float(np.max(np.linalg.norm(pts - np.asarray(c.pos), axis=1))) for c in cams) + rb
+ if m.vis.map.zfar * ext < 1.05 * reach:
+ m.vis.map.zfar = 1.05 * reach / ext
+
+ def post(self, img, cam):
+ return img
+
+ def close(self):
+ for r in getattr(self, "_r", {}).values():
+ r.close()
+ self._r = {}
+
+
+RENDERER = MujocoRenderer
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/presentation/LICENSE.franka_emika_panda b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/presentation/LICENSE.franka_emika_panda
new file mode 100644
index 0000000000..d9a10c0d8e
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/presentation/LICENSE.franka_emika_panda
@@ -0,0 +1,176 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/presentation/LICENSE.kuka_iiwa_14 b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/presentation/LICENSE.kuka_iiwa_14
new file mode 100644
index 0000000000..d4681a468e
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/presentation/LICENSE.kuka_iiwa_14
@@ -0,0 +1,31 @@
+All components of Drake are licensed under the BSD 3-Clause License
+shown below. Where noted in the source code, some portions may
+be subject to other permissive, non-viral licenses.
+
+Copyright 2012-2022 Robot Locomotion Group @ CSAIL
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+Redistributions of source code must retain the above copyright notice,
+this list of conditions and the following disclaimer. Redistributions
+in binary form must reproduce the above copyright notice, this list of
+conditions and the following disclaimer in the documentation and/or
+other materials provided with the distribution. Neither the name of
+the Massachusetts Institute of Technology nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/presentation/__init__.py b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/presentation/__init__.py
new file mode 100644
index 0000000000..7c589751f7
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/presentation/__init__.py
@@ -0,0 +1,326 @@
+"""Presentation scenes (docs/framework_zh.md §3.1, renderer rule 6): a sport may dress its match scene for spectators,
+e.g. draw its robot arms with a manufacturer-grade visual model instead of their collision meshes. A presentation
+scene is the match scene plus visual-only geoms on the SAME bodies; nothing that moves or collides changes
+(scene_check.same_kinematics, checked by every renderer before it draws one), so a recorded match replays and
+re-renders with identical body poses. By default it is for spectator renderers only (replay videos, re-renders,
+stills): the players' images use the match scene (core/observe.CameraWorker refuses a presentation scene).
+
+Players' images (core 0.2.9): a sport may declare `players = "<meshes>"` below; then the players' images are drawn
+from the presentation scene too, with the meshes named ("full" = the upstream files, or a level of detail of lod.json,
+e.g. "25k": decimated, a few MB, cheap on the CPU). tools/sportlib.assemble_sim then copies this directory and the
+models' files (verified by sha256, with their licences) into the simulator directory (<sim>/sport/presentation/,
+assets under assets/), so they are part of source_sha and a match needs no cache or network; `players_scene` builds
+that scene (Scene.players set: CameraWorker accepts it, after the same kinematics check), `players_model` compiles it
+for a sport that draws its own images. Changing the declaration changes the players' images: bump the sport's
+revision.
+
+Declaration: sports/<sport>/presentation/presentation.toml (outside the simulator directory: tools/sportlib.NOT_IN_SIM,
+so source_sha, the golden replays and the task directories do not change):
+
+ [presentation]
+ version = 1 # bump on any change of the dressing
+ label = "Franka Panda visual meshes (MuJoCo Menagerie)"
+ [[presentation.robot]]
+ model = "franka_emika_panda" # a model of the asset manifest (renderers/presentation/menagerie.json),
+ # or "./<path>.xml": a (self-authored) model in this directory
+ bodies = '^(?P<pre>[AB]_)?link(?P<n>[0-7])$' # scene bodies to dress (Python regex, full match) ...
+ body = "link{n}" # ... and the model body whose visual geoms each one gets
+ hide = "all" # the dressed bodies' own geoms: "all" (default) | "mesh" | "none"
+ # are hidden (moved to group 3), not removed
+ hide_bodies = '^...$' # optional: hide only in these dressed bodies (default: all of them)
+ colors = { white = [0.92, 0.5, 0.42, 1] } # optional: a model material's colour for this robot (e.g. a side colour)
+ scenes = ["sim/scene/a.xml"] # optional: the match scene files (relative to the sport directory),
+ # for spectator tools when the sport has no Sport.scene()
+ players = "25k" # optional, top level: the players' images use this scene too, with
+ # these meshes ("full" or a level of lod.json); absent = spectators only
+
+The model's visual geoms (contype = conaffinity = 0, group 0..2) are copied, with their meshes, materials and poses
+in the body frame, onto each matching scene body; a body whose parent is dressed too must sit in its parent's frame
+exactly as the model's does (else the declaration names the wrong bodies and dressing fails). The models' files come
+from the asset cache (renderers/presentation/assets.py: pinned commit, sha256 per file; `python3 -m
+renderers.presentation.assets fetch`), never from the repository.
+
+ from renderers.presentation import for_plugin
+ scene = for_plugin("sports/tabletennis/plugin.py", match_scene) # None if the sport declares no presentation
+"""
+from __future__ import annotations
+
+import os
+import re
+import xml.etree.ElementTree as ET
+from pathlib import Path
+
+import numpy as np
+
+from ..base import Scene
+from ..scene_check import VISUAL_PREFIX
+
+DECL = "presentation.toml"
+BUNDLE = "assets" # <sim>/sport/presentation/assets: the models' files bundled into a simulator
+CLASS = "ro_presentation" # the default class of the added geoms (inherits nothing from a robot's childclass)
+HIDDEN_GROUP = "3" # renderers draw groups 0..2; the dressed bodies' own geoms move here
+FRAME_TOL = 1e-6
+
+
+class PresentationUnavailable(RuntimeError):
+ """The sport declares a presentation scene that cannot be built here (e.g. the model assets are not fetched)."""
+
+
+def match_scenes(sport_dir: str | os.PathLike) -> list:
+ """The match scene files a presentation declares (`scenes`), as Scenes; [] if none."""
+ d = Path(sport_dir) / "presentation"
+ if not declared(d):
+ return []
+ return [Scene.from_file(Path(sport_dir) / f) for f in load_decl(d).get("scenes", [])]
+
+
+def directory(plugin: str | os.PathLike) -> Path:
+ return Path(plugin).resolve().parent / "presentation"
+
+
+def declared(d: str | os.PathLike) -> bool:
+ return (Path(d) / DECL).is_file()
+
+
+def load_decl(d: str | os.PathLike) -> dict:
+ import tomllib
+ p = (tomllib.loads((Path(d) / DECL).read_text()).get("presentation") or {})
+ if int(p.get("version", 0)) < 1 or not p.get("robot"):
+ raise ValueError(f"{Path(d) / DECL}: [presentation] needs version >= 1 and at least one [[presentation.robot]]")
+ for r in p["robot"]:
+ for k in ("model", "bodies", "body"):
+ if k not in r:
+ raise ValueError(f"{Path(d) / DECL}: a [[presentation.robot]] needs {k!r}")
+ if r.get("hide", "all") not in ("all", "mesh", "none"):
+ raise ValueError(f"{Path(d) / DECL}: hide is all | mesh | none")
+ pl = p.get("players")
+ if pl is not None and (not isinstance(pl, str) or not (pl == "full" or re.fullmatch(r"\d+k", pl))):
+ raise ValueError(f"{Path(d) / DECL}: players is \"full\" or a level of detail like \"25k\"")
+ return p
+
+
+def players_meshes(d: str | os.PathLike) -> str | None:
+ """The meshes the players' images use ("full" or a level of detail), None = spectators only (the default)."""
+ return load_decl(d).get("players") if declared(d) else None
+
+
+def players_scene(sport_dir: str | os.PathLike, match: Scene) -> Scene:
+ """The scene of the players' images: the presentation scene of `sport_dir` (the sport's directory, or the
+ simulator's sport/) when it declares `players`, else `match` itself."""
+ d = Path(sport_dir) / "presentation"
+ meshes = players_meshes(d)
+ return match if meshes is None else dress(match, d, meshes=meshes, players=True)
+
+
+def players_model(sport_dir: str | os.PathLike, match: Scene):
+ """For a sport that draws its own images: the compiled MjModel of the players' scene, after the same kinematics
+ check against the match scene; None when the sport does not declare `players` (draw the match model)."""
+ sc = players_scene(sport_dir, match)
+ if sc is match:
+ return None
+ import mujoco as mj
+ from ..scene_check import same_kinematics
+ m = mj.MjSpec.from_string(sc.xml, assets=dict(sc.assets or {})).compile()
+ bad = same_kinematics(mj.MjSpec.from_string(match.xml, assets=dict(match.assets or {})).compile(), m)
+ if bad:
+ raise RuntimeError(f"the players' presentation scene's kinematics differ from the match scene: {bad[:8]}")
+ return m
+
+
+def for_plugin(plugin, match: Scene) -> Scene | None:
+ """The presentation scene of the sport whose plugin is `plugin`, dressing `match` (the sport's scene for the same
+ configuration); None when the sport declares none. Raises PresentationUnavailable when it cannot be built. Inside a
+ simulator directory (a bundle, players' presentation) it is the players' scene."""
+ d = directory(plugin)
+ if not declared(d):
+ return None
+ meshes = players_meshes(d)
+ if meshes is not None and (d / BUNDLE).is_dir(): # inside a simulator: only the players' meshes are bundled
+ return dress(match, d, meshes=meshes, players=True)
+ return dress(match, d)
+
+
+# ------------------------------------------------------------------------------------------------ robot models
+def _f(v) -> str:
+ return " ".join(repr(float(x)) for x in np.asarray(v, float).reshape(-1))
+
+
+def _unitq(q):
+ q = np.asarray(q, float)
+ return q / np.linalg.norm(q)
+
+
+def model_parts(xml_path: str | os.PathLike) -> dict:
+ """The visual model of a robot description (parsed by MuJoCo's MJCF parser, nothing compiled or executed):
+ {"bodies": {name: {"parent", "pos", "quat", "geoms": [{"mesh", "material", "rgba", "pos", "quat"}]}},
+ "meshes": {name: {"file" (relative to the description's directory), "scale", "refpos", "refquat"}},
+ "materials": {name: {"rgba", "specular", "shininess", "reflectance", "emission"}}}"""
+ import mujoco as mj
+ xml_path = Path(xml_path)
+ spec = mj.MjSpec.from_file(str(xml_path))
+ meshdir = spec.meshdir or ""
+ meshes = {}
+ for me in spec.meshes:
+ if not me.file:
+ raise ValueError(f"{xml_path.name}: mesh {me.name!r} has no file (only file meshes are supported)")
+ name = me.name or Path(me.file).stem
+ meshes[name] = {"file": os.path.normpath(os.path.join(meshdir, me.file)), "scale": list(me.scale),
+ "refpos": list(me.refpos), "refquat": list(me.refquat)}
+ materials = {mt.name: {"rgba": list(mt.rgba), "specular": float(mt.specular), "shininess": float(mt.shininess),
+ "reflectance": float(mt.reflectance), "emission": float(mt.emission)}
+ for mt in spec.materials}
+ bodies, used = {}, set()
+ for b in spec.bodies:
+ if not b.name or b.name == "world":
+ continue
+ if b.alt.type != mj.mjtOrientation.mjORIENTATION_QUAT:
+ raise ValueError(f"{xml_path.name}: body {b.name} uses an alternative orientation")
+ geoms = []
+ for g in b.geoms:
+ if g.type != mj.mjtGeom.mjGEOM_MESH or g.contype or g.conaffinity or not 0 <= g.group <= 2:
+ continue
+ if g.alt.type != mj.mjtOrientation.mjORIENTATION_QUAT:
+ raise ValueError(f"{xml_path.name}: a visual geom of {b.name} uses an alternative orientation")
+ geoms.append({"mesh": g.meshname, "material": g.material or None, "rgba": list(g.rgba),
+ "pos": list(g.pos), "quat": list(g.quat)})
+ used.add(g.meshname)
+ if g.material:
+ used.add(("mat", g.material))
+ bodies[b.name] = {"parent": b.parent.name if b.parent is not None else "world", "pos": list(b.pos),
+ "quat": list(b.quat), "geoms": geoms}
+ return {"bodies": bodies, "meshes": {n: v for n, v in meshes.items() if n in used},
+ "materials": {n: v for n, v in materials.items() if ("mat", n) in used}}
+
+
+# ------------------------------------------------------------------------------------------------ dressing
+def _meshdir(root) -> str:
+ c = root.find("compiler")
+ if c is None:
+ return ""
+ return c.get("meshdir") or c.get("assetdir") or ""
+
+
+def _asset_key(meshdir: str, file: str) -> str:
+ return os.path.normpath(os.path.join(meshdir, file)) if meshdir else file
+
+
+def _local_frame(el) -> tuple:
+ pos = np.array([float(x) for x in el.get("pos", "0 0 0").split()])
+ if any(el.get(a) is not None for a in ("euler", "axisangle", "xyaxes", "zaxis")):
+ return pos, None
+ return pos, _unitq([float(x) for x in el.get("quat", "1 0 0 0").split()])
+
+
+def dress(match: Scene, d: str | os.PathLike, meshes: str = "full", players: bool = False) -> Scene:
+ """The presentation scene declared in directory `d` for the match scene `match` (see the module docstring), the
+ models with `meshes` ("full" or a level of detail); players: the scene of the players' images (Scene.players).
+ The models' files come from `d`/assets when it exists (a simulator's bundle), else from the cache / lod/."""
+ from . import assets
+ if match.engine != "mujoco":
+ raise PresentationUnavailable(f"presentation scenes need an MJCF scene, not {match.engine!r}")
+ decl = load_decl(d)
+ if players and decl.get("players") is None:
+ raise ValueError(f"{Path(d) / DECL}: the players' images use a presentation scene only when it declares players")
+ bundled = Path(d) / BUNDLE
+ bundle_root = bundled if bundled.is_dir() else None
+ root = ET.fromstring(match.xml)
+ meshdir = _meshdir(root)
+ out_assets = dict(match.assets or {})
+ asset_el = root.find("asset")
+ if asset_el is None:
+ asset_el = ET.Element("asset")
+ root.insert(0, asset_el)
+ default = root.find("default")
+ if default is None:
+ default = ET.Element("default")
+ root.insert(0, default)
+ cls = ET.SubElement(default, "default", {"class": CLASS})
+ ET.SubElement(cls, "geom", {"type": "mesh", "contype": "0", "conaffinity": "0", "group": "2", "mass": "0",
+ "density": "0", "rgba": "0.5 0.5 0.5 1"})
+ parents = {c: p for p in root.iter() for c in p}
+ bodies = {b.get("name"): b for b in root.iter("body") if b.get("name")}
+ credits, n_added, dressed_all, meshes_added = [], 0, set(), set()
+ for ri, rob in enumerate(decl["robot"]):
+ if rob["model"].startswith("./"): # a model shipped in the presentation directory itself
+ xml_file = (Path(d) / rob["model"]).resolve()
+ if Path(d).resolve() not in xml_file.parents:
+ raise ValueError(f"{DECL}: a local model must lie inside the presentation directory")
+ credit = rob.get("credit", f"{rob['model']} (shipped with the sport)")
+ else:
+ xml_file, credit = assets.model_xml(rob["model"], meshes, bundle_root), assets.credit(rob["model"])
+ if meshes != "full":
+ credit += f", visual meshes decimated to level {meshes} (renderers/presentation/lod.json)"
+ parts = model_parts(xml_file)
+ tag = re.sub(r"[^A-Za-z0-9_]", "_", rob["model"])
+ pat = re.compile(rob["bodies"])
+ dressed = {}
+ for name, el in bodies.items():
+ mt = pat.fullmatch(name)
+ if not mt:
+ continue
+ mbody = rob["body"].format(**{k: v or "" for k, v in mt.groupdict().items()})
+ if mbody not in parts["bodies"]:
+ raise ValueError(f"{DECL}: scene body {name} -> {mbody}, which {rob['model']} does not have")
+ dressed[name] = mbody
+ if not dressed:
+ raise ValueError(f"{DECL}: no scene body matches {rob['bodies']!r}")
+ if dressed.keys() & dressed_all:
+ raise ValueError(f"{DECL}: bodies dressed twice: {sorted(dressed.keys() & dressed_all)}")
+ dressed_all |= dressed.keys()
+ for name, mbody in dressed.items(): # the declaration must name bodies in the model's frames
+ par = parents.get(bodies[name])
+ pname = par.get("name") if par is not None and par.tag == "body" else None
+ if pname in dressed and dressed[pname] == parts["bodies"][mbody]["parent"]:
+ pos, quat = _local_frame(bodies[name])
+ mb = parts["bodies"][mbody]
+ if quat is None or np.abs(pos - mb["pos"]).max() > FRAME_TOL or min(
+ np.abs(quat - _unitq(mb["quat"])).max(), np.abs(quat + _unitq(mb["quat"])).max()) > FRAME_TOL:
+ raise ValueError(f"{DECL}: scene body {name} does not sit in its parent's frame as "
+ f"{rob['model']}'s {mbody} does")
+ # assets: the model's meshes and materials, once per robot entry
+ colors = rob.get("colors", {})
+ if set(colors) - set(parts["materials"]) or any(len(v) != 4 for v in colors.values()):
+ raise ValueError(f"{DECL}: colors names materials of {rob['model']} ({sorted(parts['materials'])}), "
+ "each an rgba of 4 numbers")
+ for mname, mat in parts["materials"].items():
+ ET.SubElement(asset_el, "material", {"name": f"ro_{tag}_{ri}_{mname}",
+ "rgba": _f(colors.get(mname, mat["rgba"])),
+ "specular": repr(mat["specular"]),
+ "shininess": repr(mat["shininess"]),
+ "reflectance": repr(mat["reflectance"]),
+ "emission": repr(mat["emission"])})
+ for mname, me in parts["meshes"].items(): # meshes once per model, materials per robot entry
+ if f"ro_{tag}_{mname}" in meshes_added:
+ continue
+ meshes_added.add(f"ro_{tag}_{mname}")
+ rel = f"ro_presentation/{tag}/{me['file']}"
+ attrs = {"name": f"ro_{tag}_{mname}", "file": rel, "scale": _f(me["scale"])}
+ if np.any(np.asarray(me["refpos"]) != 0) or np.any(np.asarray(me["refquat"]) != [1, 0, 0, 0]):
+ attrs.update(refpos=_f(me["refpos"]), refquat=_f(me["refquat"]))
+ ET.SubElement(asset_el, "mesh", attrs)
+ out_assets[_asset_key(meshdir, rel)] = (xml_file.parent / me["file"]).read_bytes()
+ hide = rob.get("hide", "all")
+ hide_pat = re.compile(rob["hide_bodies"]) if rob.get("hide_bodies") else None
+ for name, mbody in dressed.items():
+ body = bodies[name]
+ if hide != "none" and (hide_pat is None or hide_pat.fullmatch(name)):
+ for g in body.findall("geom"):
+ if hide == "all" or g.get("type") == "mesh" or (g.get("mesh") and g.get("type") is None):
+ g.set("group", HIDDEN_GROUP)
+ kids = list(body)
+ at = max([i for i, e in enumerate(kids) if e.tag in ("geom", "inertial", "joint", "freejoint")] + [-1]) + 1
+ for j, g in enumerate(parts["bodies"][mbody]["geoms"]):
+ attrs = {"name": f"{VISUAL_PREFIX}{name}:{j}", "class": CLASS, "mesh": f"ro_{tag}_{g['mesh']}",
+ "pos": _f(g["pos"]), "quat": _f(g["quat"])}
+ if g["material"]:
+ attrs["material"] = f"ro_{tag}_{ri}_{g['material']}"
+ elif not np.allclose(g["rgba"], [0.5, 0.5, 0.5, 1]):
+ attrs["rgba"] = _f(g["rgba"])
+ body.insert(at + j, ET.Element("geom", attrs))
+ n_added += 1
+ credits.append(credit)
+ xml = ET.tostring(root, encoding="unicode")
+ return Scene(engine=match.engine, xml=xml, assets=out_assets, look=match.look, match=match, players=players,
+ credits=tuple(credits) + (f"{decl.get('label', 'presentation scene')} (v{decl['version']}, "
+ f"{n_added} visual geoms" + (", the players' images" if players else "")
+ + ")",))
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/presentation/assets.py b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/presentation/assets.py
new file mode 100644
index 0000000000..14edb00e1d
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/presentation/assets.py
@@ -0,0 +1,198 @@
+"""Third-party model files of the presentation scenes, fetched at build time (never committed): every file is pinned
+to one upstream commit and checked against its sha256 in the manifest (menagerie.json, next to this file). The files
+are untrusted data: they are only read (MJCF parsed, meshes loaded by MuJoCo), never executed. Their licences are
+kept next to the manifest (LICENSE.<model>) and credited in NOTICE.
+
+ python3 -m renderers.presentation.assets fetch [MODEL ...] download the missing files (all models by default)
+ python3 -m renderers.presentation.assets verify [MODEL ...] check what is in the cache
+ python3 -m renderers.presentation.assets where print the cache directory
+
+The cache: $RO_ASSET_CACHE, else <repo>/.cache/assets (git-ignored); files at <cache>/<source>/<commit>/<path>.
+Standard library only (python >= 3.8), so the fetch runs on any host; the renderers read the cache inside the image.
+
+Levels of detail (players' images, renderer rule 6): lod.json lists decimated copies of a model's visual meshes
+(renderers/presentation/lod/<level>/<path>, committed: small, derived from the pinned files, licence unchanged; made by
+lod.py), each file pinned by sha256 like the upstream ones. `meshes` = "full" (the upstream files) or a level ("25k").
+A sport whose players' images use its presentation scene gets the model's files bundled into its simulator directory
+(`bundle`, tools/sportlib.assemble_sim): <sim>/sport/presentation/assets/<path>, checked against the same manifests,
+so a match needs neither the cache nor the network.
+"""
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import sys
+import urllib.request
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+MANIFESTS = ("menagerie.json",)
+LOD_MANIFEST = "lod.json"
+FULL = "full"
+_verified: set = set()
+
+
+class _Unavailable(RuntimeError):
+ pass
+
+
+def _err(msg):
+ try:
+ from . import PresentationUnavailable
+ except ImportError: # pragma: no cover - run as a script on a host without numpy
+ return _Unavailable(msg)
+ return PresentationUnavailable(msg)
+
+
+def manifests() -> list:
+ return [json.loads((HERE / m).read_text()) for m in MANIFESTS]
+
+
+def _find(name: str):
+ for man in manifests():
+ if name in man["models"]:
+ return man, man["models"][name]
+ raise KeyError(f"no presentation model {name!r} in {', '.join(MANIFESTS)}")
+
+
+def cache_root() -> Path:
+ env = os.environ.get("RO_ASSET_CACHE")
+ return Path(env) if env else HERE.parents[1] / ".cache" / "assets"
+
+
+def _base(man) -> Path:
+ return cache_root() / man["name"] / man["commit"]
+
+
+def _sha(p: Path) -> str:
+ h = hashlib.sha256()
+ with open(p, "rb") as f:
+ for chunk in iter(lambda: f.read(1 << 20), b""):
+ h.update(chunk)
+ return h.hexdigest()
+
+
+def lods() -> dict:
+ """lod.json: {"models": {model: {level: {"files": {path: sha256}, ...}}}, ...} ({} if absent)."""
+ p = HERE / LOD_MANIFEST
+ return json.loads(p.read_text()) if p.is_file() else {}
+
+
+def files(name: str, meshes: str = FULL) -> dict:
+ """{path: sha256} of model `name` with the given meshes ("full" or a level of lod.json)."""
+ man, mod = _find(name)
+ if meshes == FULL:
+ return dict(mod["files"])
+ lev = (lods().get("models", {}).get(name) or {}).get(meshes)
+ if lev is None:
+ raise KeyError(f"no level of detail {meshes!r} of {name} in {LOD_MANIFEST}")
+ return dict(lev["files"])
+
+
+def source_dir(name: str, meshes: str = FULL) -> Path:
+ """Where the files of `name` with `meshes` live on this checkout: the cache (full) or renderers/presentation/lod."""
+ man, _ = _find(name)
+ return _base(man) if meshes == FULL else lod_root() / meshes
+
+
+def lod_root() -> Path:
+ """The levels of detail: $RO_LOD_DIR (robot_coding_bench: the eai-olympiad image ships them at
+ /opt/roboolympics/lod, verified here against lod.json), else renderers/presentation/lod."""
+ env = os.environ.get("RO_LOD_DIR")
+ return Path(env) if env else HERE / "lod"
+
+
+def missing(name: str, meshes: str = FULL, root: Path | None = None) -> list:
+ """The files of model `name` that are absent (from `root`, default its source_dir) or do not match their sha256."""
+ base = Path(root) if root is not None else source_dir(name, meshes)
+ return [p for p, sha in files(name, meshes).items() if not (base / p).is_file() or _sha(base / p) != sha]
+
+
+def model_xml(name: str, meshes: str = FULL, root: Path | None = None) -> Path:
+ """The model's MJCF file, all its files verified (once per process): from `root` (a simulator's bundle) if given,
+ else from the cache (full meshes) or renderers/presentation/lod (a level of detail)."""
+ _, mod = _find(name)
+ base = Path(root) if root is not None else source_dir(name, meshes)
+ key = (name, meshes, str(base))
+ if key not in _verified:
+ bad = missing(name, meshes, base)
+ if bad:
+ how = (f"python3 -m renderers.presentation.assets fetch {name}" if meshes == FULL and root is None
+ else "regenerate the task (tools/generate.py)" if root is not None
+ else f"python3 -m renderers.presentation.lod build {name} {meshes}")
+ raise _err(f"presentation model {name} ({meshes} meshes): {len(bad)} of {len(files(name, meshes))} files "
+ f"missing or not matching their sha256 in {base} ({how})")
+ _verified.add(key)
+ return base / mod["xml"]
+
+
+def bundle(name: str, meshes: str, dst: Path) -> list:
+ """Copy model `name` with `meshes` (verified) and its licence into the directory `dst` (a simulator's
+ sport/presentation/assets): returns the paths written, relative to dst."""
+ import shutil
+ _, mod = _find(name)
+ src = source_dir(name, meshes)
+ model_xml(name, meshes) # verifies every file
+ out = []
+ for p in sorted(files(name, meshes)):
+ (Path(dst) / p).parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(src / p, Path(dst) / p)
+ out.append(p)
+ lic = mod["license_file"]
+ shutil.copyfile(HERE / lic, Path(dst) / lic)
+ return out + [lic]
+
+
+def credit(name: str) -> str:
+ man, mod = _find(name)
+ return (f"{mod['title']}: {man['title']} ({man['source']}, commit {man['commit'][:12]}, {mod['path']}), "
+ f"{mod['copyright']}, {mod['license']} (renderers/presentation/{mod['license_file']})")
+
+
+def fetch(name: str, log=print) -> int:
+ man, mod = _find(name)
+ base = _base(man)
+ n = 0
+ for p, sha in sorted(mod["files"].items()):
+ dst = base / p
+ if dst.is_file() and _sha(dst) == sha:
+ continue
+ url = man["url"].format(commit=man["commit"], path=p)
+ dst.parent.mkdir(parents=True, exist_ok=True)
+ tmp = dst.with_name(dst.name + ".part")
+ with urllib.request.urlopen(url, timeout=60) as r, open(tmp, "wb") as f:
+ f.write(r.read())
+ got = _sha(tmp)
+ if got != sha:
+ tmp.unlink()
+ raise _err(f"{url}: sha256 {got} != {sha} (manifest); nothing kept")
+ tmp.replace(dst)
+ n += 1
+ log(f"{name}: {len(mod['files'])} files in {base} ({n} downloaded)")
+ return n
+
+
+def main(argv) -> int:
+ cmd, names = (argv[0] if argv else "verify"), argv[1:]
+ if cmd == "where":
+ print(cache_root())
+ return 0
+ names = names or [n for man in manifests() for n in man["models"]]
+ rc = 0
+ for n in names:
+ if cmd == "fetch":
+ fetch(n)
+ elif cmd == "verify":
+ for meshes in [FULL] + sorted(lods().get("models", {}).get(n, {})):
+ bad = missing(n, meshes)
+ print(f"{n} ({meshes}): " + ("ok" if not bad else f"{len(bad)} files missing or changed"))
+ rc |= bool(bad)
+ else:
+ print(__doc__)
+ return 2
+ return rc
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/presentation/lod.json b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/presentation/lod.json
new file mode 100644
index 0000000000..d1eb0f5fcf
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/presentation/lod.json
@@ -0,0 +1,94 @@
+{
+ "models": {
+ "franka_emika_panda": {
+ "25k": {
+ "files": {
+ "franka_emika_panda/assets/link0_0.obj": "0e6958fd2f69a9c6ec82e59fb3a39689810bcd69180dd865866359b69d0204ba",
+ "franka_emika_panda/assets/link0_1.obj": "5ca2ade591ead9e9d3046468f6d861631b8fcd0434cb6dfbfbc7eb09cbc11c81",
+ "franka_emika_panda/assets/link0_10.obj": "c8daf1be7a5d3d89aa3f0976c6c43afa9d5841697c0ed91edcad8d60a75b1e60",
+ "franka_emika_panda/assets/link0_11.obj": "0ced2c2a707b13a391306d04f9ad9d4318caf2ce924cb242321a1cd9773c3753",
+ "franka_emika_panda/assets/link0_2.obj": "d7d11c50dee70b7d9149805576c85e026d3f4df2df1b824891451f72bce20e1d",
+ "franka_emika_panda/assets/link0_3.obj": "35bad1cdde8a1e6cee4522b22aa4e46d6a06a54bccc3bc966691f96cde0953fa",
+ "franka_emika_panda/assets/link0_4.obj": "ee1d81feeb6591b8a0b4d0e175f7541ffa40725aa6b97d048d289dc5c5517913",
+ "franka_emika_panda/assets/link0_5.obj": "17438838e57292cdc0c18f5417c020ed3290323e50ca4c1b58b07065961bc95c",
+ "franka_emika_panda/assets/link0_7.obj": "2ccf52f5c8b6155fd2764435028b59ad64d23820bb080d9079ba52b939ccee36",
+ "franka_emika_panda/assets/link0_8.obj": "7f895de6ec3ebdd93f5af7c446616da908cf423131dc2c24da50146b32718baa",
+ "franka_emika_panda/assets/link0_9.obj": "8ef4ff7f0676b60a8edf54380b4b696bae3b5a5202e38f7ca64bb3a2f6e0496b",
+ "franka_emika_panda/assets/link1.obj": "89a7387d65a311e92cd39dc65c0f5a7d00a5d342bf670613b87b09da016a82c8",
+ "franka_emika_panda/assets/link2.obj": "b66faa46466a258f1f36250bf4530424eb37b47ae1fcc4dbb114b37a499287a2",
+ "franka_emika_panda/assets/link3_0.obj": "b6124b7a17d85ce218ed739ae1792c4762718e43f135e3633008bc753aebe20f",
+ "franka_emika_panda/assets/link3_1.obj": "6d05236a2bb84117328a7d421f41058ddd9969d5317a5c5a5375da311dc17f30",
+ "franka_emika_panda/assets/link3_2.obj": "4d3f6753c0aa9469486317d5eee5e2ac8b1615b705a78e35335a298a4644cd03",
+ "franka_emika_panda/assets/link3_3.obj": "5afeb0a5722704920fe3930fd56fa30dde7faf1932377e9b5fbaafbf1b6f5030",
+ "franka_emika_panda/assets/link4_0.obj": "ef4c8095c339dbf8e10e727f5361598220833689cd79ac59d10508423934fc93",
+ "franka_emika_panda/assets/link4_1.obj": "7050225b33d23afafac7f597b250e59c7353e3193ecb1098c3708f2f4d561e52",
+ "franka_emika_panda/assets/link4_2.obj": "e084c51cdddb612869d45ae94e31b19a1d011f9c182faff07b1f953ca9e7e6c1",
+ "franka_emika_panda/assets/link4_3.obj": "c5ef5783e41d161269018a4b16446db8e400eb7780527a161e62bf7ed2289e46",
+ "franka_emika_panda/assets/link5_0.obj": "f64a7b7f023bdcaf8d8fac082145d365751c69e9b6bda942c5de3dd3dc8806a4",
+ "franka_emika_panda/assets/link5_1.obj": "8bfc7df033b58c4e7b5f1080dc05da81699ffc237a91b8da9e2a6119cb79b494",
+ "franka_emika_panda/assets/link5_2.obj": "437ee6f13c4d98db88ad75d832aa6bdcb5453db256d5691be1931c4acd935bf9",
+ "franka_emika_panda/assets/link6_0.obj": "9c87e9689cfeacb6b1d2ce305cddcbad463f420584dbd220b2080e3c636b3762",
+ "franka_emika_panda/assets/link6_1.obj": "6445e25a8759385c43f0d5285d50f77eb08f34afe6fbb2d07ddf352c8b3d13b5",
+ "franka_emika_panda/assets/link6_10.obj": "05ec79c4defd0548107dc58f2d7ab26b010a2ca7b7878ed0b282a3540679f620",
+ "franka_emika_panda/assets/link6_11.obj": "96dc648b3382a4b3688d801bb94eb3b6cb1d6e64367e8cae29d2a7c3178324c3",
+ "franka_emika_panda/assets/link6_12.obj": "7b2bea2a736a63661cdae29ef30740a26d08ce43c4a787788907d44d2853413e",
+ "franka_emika_panda/assets/link6_13.obj": "5f6745688f8c3a4172af1689d6a52f320264104414853e72c5a022bdaac77026",
+ "franka_emika_panda/assets/link6_14.obj": "569977e1c13942d0aa84ba42188f5256de447266e1db2e0f46159482791acbc5",
+ "franka_emika_panda/assets/link6_15.obj": "3d201820c51a032ee1e12232b5cb709b20062b8a991d6446a225f6aa8471e486",
+ "franka_emika_panda/assets/link6_16.obj": "ad4f0e691598a70ef3de25b8840d8893b48150dcbb6012a7295cbe706e8de05c",
+ "franka_emika_panda/assets/link6_2.obj": "b6bc873ba1bcbf54af2667d197722f681d82f591173cecb75cad0a67e2b47e3d",
+ "franka_emika_panda/assets/link6_3.obj": "9da48c192b317dde105666470c4898e0ca6ae54cd57f386867de76f3e75f8116",
+ "franka_emika_panda/assets/link6_4.obj": "ed80f9d8e9da1c3252cc375704f80bec5b8263198178db9a4fca72587d9525d2",
+ "franka_emika_panda/assets/link6_5.obj": "68eba154d3031354e6682dea960993b668ce3229fde73d1aaf9456e2978be95e",
+ "franka_emika_panda/assets/link6_6.obj": "c8316be35257df937810664619b67b45820b60dcbd0b219fe7e540bc12e81156",
+ "franka_emika_panda/assets/link6_7.obj": "6bc1c0ce40b6fbf22d37000ffe95255c044a168cd5241a5c56e86bdf5c171f92",
+ "franka_emika_panda/assets/link6_8.obj": "d821b8c3875eca9ad19aa6112a86eb2a0cc0d75ad07349d004c449e85eb00f14",
+ "franka_emika_panda/assets/link6_9.obj": "bd9beb29cdef7b5c6014529f65520245fa83bd8b84c0b57288a9235da2fc94c5",
+ "franka_emika_panda/assets/link7_0.obj": "16a21aac2faf5c012b1b2b2aac5c6170f78caba505a0885fed7c14b3a672899b",
+ "franka_emika_panda/assets/link7_1.obj": "7f5391b3b7104189b38c65d10a8fe213ef6d6443dc05ea7c2c6d7b31fb483ff9",
+ "franka_emika_panda/assets/link7_2.obj": "16e8c340cc6f3c9d2f15760f58892e15d0e668b09b81088a39b3a77929de0721",
+ "franka_emika_panda/assets/link7_3.obj": "47795dd7fc1d3d253313b7b39f94e06036169b3380b2d7486fb51ce53916e04d",
+ "franka_emika_panda/assets/link7_4.obj": "8c3614d6cf07660c5cbfa12edae41bd22a49d4bec9f9c4a2139a00607d1e8f63",
+ "franka_emika_panda/assets/link7_5.obj": "23e7ba2a16fca00e48b6e397d6da49b25af4e5327c6b186217aedcc808f0892f",
+ "franka_emika_panda/assets/link7_6.obj": "40e6a822ade171dcb2ecc6d5d510c9b878505e2af3b497f7e772605fdf2b9c2b",
+ "franka_emika_panda/assets/link7_7.obj": "d70d61a09b7a605a47caf5d5b7225f3d5cce1af1c849b262ab9ea0242c50464b",
+ "franka_emika_panda/panda_nohand.xml": "e7090a5e2384b18a223ef532d98bf914f7f9a6b74dc8bc9f74c8291201074071"
+ },
+ "source": "menagerie@f054586a8e90465d49ee5be15335c4a0c7f57caf",
+ "source_triangles": 126562,
+ "target_triangles": 25000,
+ "triangles": 25568
+ }
+ },
+ "kuka_iiwa_14": {
+ "25k": {
+ "files": {
+ "kuka_iiwa_14/assets/band.obj": "40784c36ec38f8ff2fa804e3c242656b9ed3ae41a33785af33c917de1bbd566f",
+ "kuka_iiwa_14/assets/kuka.obj": "b79762633220dcfae4b45b40d2880a83128e373003f794f0d9a19f4989c92ec7",
+ "kuka_iiwa_14/assets/link_0.obj": "fc2590b0e7ce20e1fa9a5ab4f48259908508c6ad4aeebc4d2ef13e5d22ba23e5",
+ "kuka_iiwa_14/assets/link_1.obj": "81f65e2f348ac6bfdd4968a1440406c9abc9ca6b51de7a404024a08ef46127eb",
+ "kuka_iiwa_14/assets/link_2_grey.obj": "07bc12ae4e6edc159e4123e9a5571a08d03211de8afa503c9cfb74dff51208b2",
+ "kuka_iiwa_14/assets/link_2_orange.obj": "4b151e4dc5689342ad6be614c9114ab3c0668a1aaba25eafc78c8e2e9f7a01f8",
+ "kuka_iiwa_14/assets/link_3.obj": "77be645b049e35bfb1c2bf05d610c95044b39dc17209b4d5e63ded1e4b87832d",
+ "kuka_iiwa_14/assets/link_4_grey.obj": "79f6693b2031e1f24069c56546490d7d1ff6907b3871bd049bba187d4ff0786a",
+ "kuka_iiwa_14/assets/link_4_orange.obj": "2e0613541153884f9a3cc2de654492d7aa563368c6fae335c82109b5def79f4d",
+ "kuka_iiwa_14/assets/link_5.obj": "2f0ee7aeb51dfa86f98954f8673fafdb8c63dfa37618d4e0e76c7db037af267c",
+ "kuka_iiwa_14/assets/link_6_grey.obj": "4eb7481b31d88612b6cc791d8390c3145e367ca87537a2f6763e3c2c2b01dd13",
+ "kuka_iiwa_14/assets/link_6_orange.obj": "450b41e8691e1ccfa427da45d65d4f95c40cd388433fc753c1ab86087d178cdc",
+ "kuka_iiwa_14/assets/link_7.obj": "c35ef794a848268745f3d1e283dbcdb0bf117373110364b62c8405af4275eac1",
+ "kuka_iiwa_14/iiwa14.xml": "ee7e6d796a9f8642de6097f95077281d15f43678dc5285beafeda99b84cf9ef5"
+ },
+ "source": "menagerie@f054586a8e90465d49ee5be15335c4a0c7f57caf",
+ "source_triangles": 73989,
+ "target_triangles": 25000,
+ "triangles": 25141
+ }
+ }
+ },
+ "name": "lod",
+ "note": "Levels of detail of the presentation models (players' images, renderer rule 6): a model's visual meshes decimated to a triangle budget, so that a sport can draw its players' images with fine meshes on the CPU at a small cost and bundle them into its simulator directory (a few MB instead of 30).",
+ "tools": {
+ "fast-simplification": "0.2.0",
+ "trimesh": "5.1.1"
+ }
+}
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/presentation/menagerie.json b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/presentation/menagerie.json
new file mode 100644
index 0000000000..f20f9bb91f
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/presentation/menagerie.json
@@ -0,0 +1,135 @@
+{
+ "name": "menagerie",
+ "title": "MuJoCo Menagerie",
+ "source": "https://github.com/google-deepmind/mujoco_menagerie",
+ "commit": "f054586a8e90465d49ee5be15335c4a0c7f57caf",
+ "url": "https://raw.githubusercontent.com/google-deepmind/mujoco_menagerie/{commit}/{path}",
+ "note": "Generated from the pinned commit: per model its MJCF description and the visual meshes of its visual geoms (no collision meshes, textures or scripts). Untrusted data: read only.",
+ "models": {
+ "franka_emika_panda": {
+ "title": "Franka Emika Panda (no hand)",
+ "path": "franka_emika_panda/",
+ "xml": "franka_emika_panda/panda_nohand.xml",
+ "license": "Apache-2.0",
+ "license_file": "LICENSE.franka_emika_panda",
+ "copyright": "MuJoCo Menagerie authors, derived from Franka Emika's franka_ros description",
+ "files": {
+ "franka_emika_panda/assets/link0_0.obj": "6b9f41a4c203540daaeb7a33cc3d0d6c6a32dc8bba187074eeaf97b3e36b3f9c",
+ "franka_emika_panda/assets/link0_1.obj": "57673d2ee2a9db2e10c8986ae57c56a7c39c012b60fd26d7d8549553b664a5ed",
+ "franka_emika_panda/assets/link0_10.obj": "c9198b9d8534d628d097b0f2b239bb30343353182df098ce0d9db6bc13326848",
+ "franka_emika_panda/assets/link0_11.obj": "f0adec78d6677b7799d25121981270e8bfe119b5c18d08a91ee37a54ad75f65c",
+ "franka_emika_panda/assets/link0_2.obj": "1ca435a2a87a9608a146a47955724d43dd7ce10fc3dd3018800aa98f8ba86e05",
+ "franka_emika_panda/assets/link0_3.obj": "3e9c6334d2b3b47944af3458ee5f20519abc20fe7ee23063bb53405ccab28046",
+ "franka_emika_panda/assets/link0_4.obj": "215d25789704936120f119c0bc1cc7f68516dd3f8f1df61457b71acac3873f26",
+ "franka_emika_panda/assets/link0_5.obj": "9361b104e93743045107aa5b15fb1a0835ba9c1f355aae71f56403cf6a9c33f6",
+ "franka_emika_panda/assets/link0_7.obj": "2dc0b8ebbbc80e4c065d71e195adbc384f673438641fac82b07b801b4d2837cb",
+ "franka_emika_panda/assets/link0_8.obj": "3b8c436999db5586b8eb47bed2b0aa7de6993868b2681b4c04246eeac42fdb7a",
+ "franka_emika_panda/assets/link0_9.obj": "45178f97d2b5da6bce11f610212c4ef7d08c73db33a4fc38e1b7f66b93d023f5",
+ "franka_emika_panda/assets/link1.obj": "51091e776b16babdbe2f3849b5c041f921d1f11dd94ac19a0f1c81abf496fbae",
+ "franka_emika_panda/assets/link2.obj": "5c9f8e715de52c3eb71b475de35993b3b96081e02abea9f28c414768877fc59b",
+ "franka_emika_panda/assets/link3_0.obj": "ce2da87f51708e11b189249d41401065dabe89a06e251185a06cef4d5ff27178",
+ "franka_emika_panda/assets/link3_1.obj": "2880b7753a7173f38fa87ee21da4dfc7fa7be46fbe07bac5aef9e128513cb118",
+ "franka_emika_panda/assets/link3_2.obj": "670cff81ae84693769ca4ae658c154cf909d81167e7c8d22b70ea977f2504efa",
+ "franka_emika_panda/assets/link3_3.obj": "30ede0c812efd0e0b767d134a4eae0b84e0fa407bb6325a5a555e0569b3a3ffd",
+ "franka_emika_panda/assets/link4_0.obj": "443bf6d178177cf347951ecf107ccd10ca444e605e375b67304579e5f948806f",
+ "franka_emika_panda/assets/link4_1.obj": "ca935ec7cc8b3f0e86aa079c76b0b3bf593b1e9830bab0fa7131ac51577c74f0",
+ "franka_emika_panda/assets/link4_2.obj": "c89caf26d379c35bb9e191ee2d91d09ab29ecc792b48d8bc10b39e5b38222175",
+ "franka_emika_panda/assets/link4_3.obj": "1495d17f45bdb230cf58b0beef9da4e8c9cfe76a3d2d38da89017efe5e093136",
+ "franka_emika_panda/assets/link5_0.obj": "a3238b8f2af0f2eb66d9fe63dc5d41ac52d5d38507241b5ed10e3cb019ab3e71",
+ "franka_emika_panda/assets/link5_1.obj": "9d994bbf83ec241e301b5197a6846da13f2a4a0582edb2c0f76962c5549649d6",
+ "franka_emika_panda/assets/link5_2.obj": "83b4ffe9f772cd7fe182e98640650eebc899aaf01842656574b0416c90dd40a4",
+ "franka_emika_panda/assets/link6_0.obj": "0504c70ebf1b284ee8faae7dcb896b8830bc672a6552015dd5dbd121fa031fb9",
+ "franka_emika_panda/assets/link6_1.obj": "45f7ca77695198b6d86ec2417ad4e42e6275044f0f96266699ee8e1057757ac1",
+ "franka_emika_panda/assets/link6_10.obj": "365f26c21d10332cab8d8704645cb46930c30b3085956f2d097498c793f24db4",
+ "franka_emika_panda/assets/link6_11.obj": "8ae61e08b3ad064f25bbf03b22e59cc15d65883b5a7ce92711aff29df2493901",
+ "franka_emika_panda/assets/link6_12.obj": "f28d1bfd62b0244ffd19fb35fe9edefdf583d3c9167db944e87185d919e1d021",
+ "franka_emika_panda/assets/link6_13.obj": "0a55fa92dccb261d07200e6565fca4c850fd17f0c1ecf38821c0b97d51796c7d",
+ "franka_emika_panda/assets/link6_14.obj": "750ae3ee4781e62e3a045c662195247b03f6642b05aa93104f08258e5f6eba26",
+ "franka_emika_panda/assets/link6_15.obj": "5999c1c2497a004a7c4bbe034cdf13744f839d85ae7a11b1bc386c48a3e642e6",
+ "franka_emika_panda/assets/link6_16.obj": "551d7a8b37c53e7a152d008b4e36992e5b5abe74a4be18b57ee6319c27def09f",
+ "franka_emika_panda/assets/link6_2.obj": "e54eee4d8232947ee8af65afd5a067e09dac2da6e7e585cb1dccb65496457da0",
+ "franka_emika_panda/assets/link6_3.obj": "d4f6a25ef32fa1fa4734146981994ee760232cb077c80fea6487d78a077c7f27",
+ "franka_emika_panda/assets/link6_4.obj": "be353480fe71d46f7a96f0a3cbb7e112caaf8d88368826f321a36a253c8749b2",
+ "franka_emika_panda/assets/link6_5.obj": "7c87664623c3e1a6cb330db273227a69626dc5e53b4caff1d4ee7911eb3340c6",
+ "franka_emika_panda/assets/link6_6.obj": "8fbc031e0d07b795ebf99115c75223141caaba317cab569159f3d477a7821681",
+ "franka_emika_panda/assets/link6_7.obj": "7dc5ebb799fe281aab27d6e84e7a4efa0a8e42da2369ec83de3ea3f206f62d73",
+ "franka_emika_panda/assets/link6_8.obj": "e3f77381817a341030f9dcc4c4aa7c559f80411b453fd87eb0fefecca82151bf",
+ "franka_emika_panda/assets/link6_9.obj": "25a56ea9b02a03b6cb5a81f31c54f54d0185e1a0b3937c37e4289d896e50215a",
+ "franka_emika_panda/assets/link7_0.obj": "04586b0bde011715cfc22072ac72fe0717eb4d4817bcf665987ce6cd88eb2b93",
+ "franka_emika_panda/assets/link7_1.obj": "c3f72289f394c9d6749a4a327fb11f05b203c37c95032c92f28019b40ebe7e00",
+ "franka_emika_panda/assets/link7_2.obj": "d2faecedb304d0989040d082410378dc949dbbda23bd18c05134f08aae984db5",
+ "franka_emika_panda/assets/link7_3.obj": "b62d87c4d4bdb7b281ed341d347c39dad0e50bf36aed8ac11d050073701d5f70",
+ "franka_emika_panda/assets/link7_4.obj": "cb78ccb61fd4ad6c7bff4c4d2e6cb41e1964a5a3e1a28e67c0c6202371cfc018",
+ "franka_emika_panda/assets/link7_5.obj": "099071d3090b51471ba52f4f90814fd3089f4975d196e4d488117073d0bfe491",
+ "franka_emika_panda/assets/link7_6.obj": "99469e2d95ab74ce0292f2f16954c87a8a7dc16652e62e970fe37c94330a81bb",
+ "franka_emika_panda/assets/link7_7.obj": "426c3db8a19373f3dc73d4bec672e948121b2914c10e2e7b9c7ea80643a19e54",
+ "franka_emika_panda/panda_nohand.xml": "e7090a5e2384b18a223ef532d98bf914f7f9a6b74dc8bc9f74c8291201074071"
+ },
+ "bytes": 32259617,
+ "visual_geoms": 49
+ },
+ "kuka_iiwa_14": {
+ "title": "KUKA LBR iiwa 14",
+ "path": "kuka_iiwa_14/",
+ "xml": "kuka_iiwa_14/iiwa14.xml",
+ "license": "BSD-3-Clause",
+ "license_file": "LICENSE.kuka_iiwa_14",
+ "copyright": "MuJoCo Menagerie authors, derived from the Drake developers' iiwa14 description",
+ "files": {
+ "kuka_iiwa_14/assets/band.obj": "02cf16a93140489da3b05ce6bb30c5498bedaa5e5a77e56850ddbedb8d1ed23e",
+ "kuka_iiwa_14/assets/kuka.obj": "204a82d597d450f2a207731f8e3c17089f2de5a54c0d61feac454e96e325b834",
+ "kuka_iiwa_14/assets/link_0.obj": "6b607f6b5a601874863897ebfbb9821eb0c831c3115bca8350bf7856db6aaeee",
+ "kuka_iiwa_14/assets/link_1.obj": "47a82247b647639c3e1f384ce5b980d374323ca737d6ebc87447667a71981798",
+ "kuka_iiwa_14/assets/link_2_grey.obj": "842b8c3a9148b2fdf9c57ddfd80b595f8251792f94b71276dc9ce9a16674ba1a",
+ "kuka_iiwa_14/assets/link_2_orange.obj": "0d2d8829d89aa888ee04b0d97bed5f215fa0d9fd03d0d4cee2b2e0c8dd3c0124",
+ "kuka_iiwa_14/assets/link_3.obj": "b02d157e8090d82bfb78e7fd4dcd351033e0a5d7bb1937da01e66e7ff91a03a8",
+ "kuka_iiwa_14/assets/link_4_grey.obj": "e4555ea6954fffa40174baee25e6dd1b9efcc3eaf830b6e91d13e2ddc10b414a",
+ "kuka_iiwa_14/assets/link_4_orange.obj": "ef4cf2102e9df98636ff03b82d49d914a6e730b299b0a982d64947f038136cb7",
+ "kuka_iiwa_14/assets/link_5.obj": "f0eef60cddf06e46bd943abcc49ada87510f095f2840bc9c117ed7a2b1a6a787",
+ "kuka_iiwa_14/assets/link_6_grey.obj": "5b5f9883d4fc181c7aa06cb2037debfa4ca857fa0c3a5d55f8fd3e34d38c3100",
+ "kuka_iiwa_14/assets/link_6_orange.obj": "54aa0141e7f48497302f45daf074fd5c69320c620618c12fa76e8841c2a8a9fc",
+ "kuka_iiwa_14/assets/link_7.obj": "7307d0c852715ea234e575a0617ea2d8faf053469e7b823ac0c7c6c4dff36dad",
+ "kuka_iiwa_14/iiwa14.xml": "ee7e6d796a9f8642de6097f95077281d15f43678dc5285beafeda99b84cf9ef5"
+ },
+ "bytes": 5015391,
+ "visual_geoms": 15
+ },
+ "booster_t1": {
+ "title": "Booster T1",
+ "path": "booster_t1/",
+ "xml": "booster_t1/t1.xml",
+ "license": "Apache-2.0",
+ "license_file": "LICENSE.booster_t1",
+ "copyright": "MuJoCo Menagerie authors, derived from Booster Robotics' booster_gym T1 description",
+ "files": {
+ "booster_t1/assets/AL1.stl": "43f5d268152b3c169d34731545ddfa2a510a7e16f209a2a80f8ba9ae0e1a40aa",
+ "booster_t1/assets/AL2.stl": "4bca60adb29c73f701350abd23e8a8d660dc61e87c5163a80157650dd3ad88c3",
+ "booster_t1/assets/AL3.stl": "bfdf5611dfe90f8e02b07b037c36a244f4ce7184b45113371ef46e624fb30854",
+ "booster_t1/assets/AR1.stl": "6dbbd3dab4486600747be9d0e7f8523d67bf00d24d0dc9c23db1766c4d808fcf",
+ "booster_t1/assets/AR2.stl": "0499136785fe1bc0289d9e503e1e0ea48f5a63420a2e45b0fcd9e6b3bcf8f999",
+ "booster_t1/assets/AR3.stl": "92330bd8286fe420fb76949ee4c5d5bdec2e6bb30426acdc4d6fae9257464631",
+ "booster_t1/assets/Ankle_Cross_Left.stl": "e6ec38741838475834c147f2ad18196c0254741e602c2b676f888fd12b5d7981",
+ "booster_t1/assets/Ankle_Cross_Right.stl": "b15d91f0f2470fc4d5634db906a3d7efaf1f700302e6671824494da8faf50308",
+ "booster_t1/assets/H1.stl": "527a2e426db4e3d476a195754764b7f9565a950b809a34e47618f177b139c3f2",
+ "booster_t1/assets/H2.stl": "9cbf4fe83a721c809de65b1f0d0a379314f4523f7e2f8af7f0edc27c2ce385aa",
+ "booster_t1/assets/Hip_Pitch_Left.stl": "7bcb8be569aeb5379cb75a0827d682bc1d73a52a7f515d3aeffece43842c33c9",
+ "booster_t1/assets/Hip_Pitch_Right.stl": "054d579c3c6ccc1f97aaf1461d802dec748ce1bf26c6fdd289283a2d0dbb2032",
+ "booster_t1/assets/Hip_Roll_Left.stl": "72dbd65bdb4e87444c8e538474f631d63bf8c0960922517456b8cf2be9e1d0f0",
+ "booster_t1/assets/Hip_Roll_Right.stl": "d715a7649ea4bf20d7ee17b3a57bae31732e467b9da1053fee2242c90f50980f",
+ "booster_t1/assets/Hip_Yaw_Left.stl": "d588e0467094811e74ae1962fcb0eb669f9b50b74022e96a738bdc8e807e03a7",
+ "booster_t1/assets/Hip_Yaw_Right.stl": "5135f2fd5707364583d283e2fb21845054f3548c224f48e1f0a3d78ed3453497",
+ "booster_t1/assets/Shank_Left.stl": "6ae8dd7f88cb70a4a3cb3972cad4035a76f1604fd73ea66e285da553b3703c40",
+ "booster_t1/assets/Shank_Right.stl": "dc66a8a0e2e31e413884a053e427d9b5007bef4508986587916a638a8a448599",
+ "booster_t1/assets/Trunk.stl": "39d9610b23ef8ac7ea4343231a499f9c485903bede62df9729a2cd1254fede8f",
+ "booster_t1/assets/Waist.stl": "2fe0a9ccfc284beca402e554db38e83022592192afa00f02db13cb374ffe9fbc",
+ "booster_t1/assets/left_foot_link.stl": "82d653e30c0ae2e588c3c539266c9a1fee20e711448e13598f25384c7dc562ca",
+ "booster_t1/assets/left_hand_link.stl": "34df992aed438446481cfa20e78327810cd5cc5ecbb4a6f32ba2bf625462f53d",
+ "booster_t1/assets/right_foot_link.stl": "78440aa4bab7c397b8e507431b44b814e4cb89db0d03455f83ae54e3157cf15b",
+ "booster_t1/assets/right_hand_link.stl": "c5a73e493e17db7611a81785f80c01167f51018271b4042f72fa8d2351d8b0eb",
+ "booster_t1/t1.xml": "78af3f7910e4413894863b6427f44a7daf49e5eb47628e6fe2db775219e346b9"
+ },
+ "bytes": 8445726,
+ "visual_geoms": 24
+ }
+ }
+}
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/scene_check.py b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/scene_check.py
new file mode 100644
index 0000000000..5713371f35
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/renderers/scene_check.py
@@ -0,0 +1,164 @@
+"""Same scene (renderer rule 2): a non-default renderer draws the default renderer's scene. The geometry, kinematics,
+cameras and the colour a viewer sees of every untextured geom must be identical; a re-textured surface keeps its mean
+colour within TEXTURE_TOL. Only lights, materials (specular, shininess, reflectance, textures with the same mean
+colour) and image quality may differ. The same rule as scripts/olympiad/showcase/looks.same_scene, without the
+sport-specific decor exception (decor is presentation-only and never part of a renderer's player picture).
+
+Same kinematics (renderer rule 6): a presentation scene (renderers/presentation.py, spectators only) may differ from
+the match scene in appearance and by added visual-only geoms, never in bodies, joints, frames, inertias or cameras;
+same_kinematics() checks it before a renderer draws one, pose_diff() compares body poses over recorded states."""
+from __future__ import annotations
+
+import numpy as np
+
+SAME = ("nq", "nv", "nbody", "njnt", "ngeom", "nmesh", "ncam", "nmocap",
+ "body_parentid", "body_pos", "body_quat", "body_mass", "jnt_type", "jnt_qposadr", "jnt_pos", "jnt_axis",
+ "geom_type", "geom_bodyid", "geom_size", "geom_pos", "geom_quat", "geom_group", "geom_dataid",
+ "mesh_vertnum", "mesh_vert", "mesh_face",
+ "cam_mode", "cam_bodyid", "cam_pos", "cam_quat", "cam_fovy")
+DEFAULT_RGBA = (0.5, 0.5, 0.5, 1.0)
+TEXTURE_TOL = 0.02
+MESH = 7 # mjtGeom.mjGEOM_MESH
+
+
+def effective_rgba(m, g):
+ rgba = m.geom_rgba[g]
+ if m.geom_matid[g] >= 0 and np.allclose(rgba, DEFAULT_RGBA):
+ return m.mat_rgba[m.geom_matid[g]]
+ return rgba
+
+
+def _texid(m, g):
+ import mujoco as mj
+ mid = m.geom_matid[g]
+ return int(m.mat_texid[mid, mj.mjtTextureRole.mjTEXROLE_RGB]) if mid >= 0 else -1
+
+
+def _mean_colour(m, g):
+ """Mean drawn colour of a geom (texture mean x material/geom colour), 0..1 RGB."""
+ rgba = np.asarray(effective_rgba(m, g)[:3], float)
+ t = _texid(m, g)
+ if t < 0:
+ return rgba
+ h, w, c = m.tex_height[t], m.tex_width[t], m.tex_nchannel[t]
+ px = m.tex_data[m.tex_adr[t]:m.tex_adr[t] + h * w * c].reshape(-1, c)[:, :3]
+ return rgba * (px.mean(0) / 255.0)
+
+
+SPARE = "_ro_cam" # the renderers' own spare cameras (renderers/mujoco), posed per frame: not scene cameras
+
+
+def _scene_cams(m):
+ return [i for i in range(m.ncam) if not (m.camera(i).name or "").startswith(SPARE)]
+
+
+def same_scene(m0, m1) -> list:
+ """Differences between the default model m0 and the renderer's model m1 (empty list = the same scene)."""
+ bad = []
+ c0, c1 = _scene_cams(m0), _scene_cams(m1)
+ for name in SAME:
+ a, b = np.asarray(getattr(m0, name)), np.asarray(getattr(m1, name))
+ if name.startswith("cam_"):
+ a, b = a[c0], b[c1]
+ elif name == "ncam":
+ a, b = np.asarray(len(c0)), np.asarray(len(c1))
+ if np.shape(a) != np.shape(b) or not np.array_equal(a, b):
+ bad.append(name)
+ if bad:
+ return bad
+ if m0.vis.global_.fovy != m1.vis.global_.fovy:
+ bad.append("vis.global.fovy")
+ for g in range(m0.ngeom):
+ t0, t1 = _texid(m0, g) >= 0, _texid(m1, g) >= 0
+ if not t0 and not t1:
+ if not np.allclose(effective_rgba(m0, g), effective_rgba(m1, g)):
+ bad.append(f"colour of geom {m0.geom(g).name or g}")
+ elif float(np.abs(_mean_colour(m0, g) - _mean_colour(m1, g)).max()) > TEXTURE_TOL:
+ bad.append(f"mean colour of textured geom {m0.geom(g).name or g}")
+ return bad
+
+
+# ------------------------------------------------------------------------------------- presentation scenes (spectators)
+VISUAL_PREFIX = "_vis:" # the name prefix of a presentation scene's added geoms (renderers/presentation.py)
+KINEMATICS = ("nq", "nv", "nu", "nbody", "njnt", "nmocap", "nsite", "qpos0",
+ "body_parentid", "body_rootid", "body_weldid", "body_mocapid", "body_jntnum", "body_jntadr",
+ "body_dofnum", "body_dofadr", "body_pos", "body_quat", "body_ipos", "body_iquat", "body_mass",
+ "body_inertia", "jnt_type", "jnt_bodyid", "jnt_qposadr", "jnt_dofadr", "jnt_pos", "jnt_axis",
+ "jnt_range", "dof_bodyid", "dof_jntid", "dof_armature", "dof_damping", "actuator_trnid",
+ "site_bodyid", "site_pos", "site_quat", "opt.timestep", "opt.gravity")
+MATCH_GEOM = ("geom_type", "geom_bodyid", "geom_size", "geom_pos", "geom_quat", "geom_contype", "geom_conaffinity",
+ "geom_condim", "geom_priority", "geom_friction", "geom_solref", "geom_solimp", "geom_margin", "geom_gap")
+CAMERA = ("cam_mode", "cam_bodyid", "cam_pos", "cam_quat", "cam_fovy")
+
+
+def _arr(m, name):
+ o = m
+ for part in name.split("."):
+ o = getattr(o, part)
+ return np.asarray(o)
+
+
+def visual_geoms(m) -> list:
+ return [g for g in range(m.ngeom) if (m.geom(g).name or "").startswith(VISUAL_PREFIX)]
+
+
+def _mesh_verts(m, g):
+ i = m.geom_dataid[g]
+ return m.mesh_vert[m.mesh_vertadr[i]:m.mesh_vertadr[i] + m.mesh_vertnum[i]]
+
+
+def same_kinematics(m0, m1) -> list:
+ """Differences between the match model m0 and a presentation model m1 (empty list = the same kinematics):
+ every body, joint, dof, frame, inertia, site, mocap body and scene camera is identical; m0's geoms are all in m1,
+ in the same order, with the same geometry, pose and contact properties (only their appearance may change:
+ group, colour, material, e.g. a collision mesh moved to the hidden group 3); every other geom of m1 is an added
+ visual geom (name prefix VISUAL_PREFIX) that never collides (contype = conaffinity = 0) and is drawn (group
+ 0..2). Body masses and inertias being equal, the added geoms carry no mass. So the same qpos puts every body at
+ the same pose in both models: a presentation scene changes only what a spectator sees."""
+ bad = []
+ for name in KINEMATICS:
+ a, b = _arr(m0, name), _arr(m1, name)
+ if a.shape != b.shape or not np.array_equal(a, b):
+ bad.append(name)
+ c0, c1 = _scene_cams(m0), _scene_cams(m1)
+ if len(c0) != len(c1):
+ bad.append("ncam")
+ else:
+ bad += [n for n in CAMERA if not np.array_equal(_arr(m0, n)[c0], _arr(m1, n)[c1])]
+ if bad:
+ return bad
+ extra = visual_geoms(m1)
+ keep = [g for g in range(m1.ngeom) if g not in set(extra)]
+ if len(keep) != m0.ngeom:
+ return [f"{len(keep)} match geoms in the presentation scene for {m0.ngeom}"]
+ bad += [n for n in MATCH_GEOM if not np.array_equal(_arr(m0, n), _arr(m1, n)[keep])]
+ for g0, g1 in enumerate(keep):
+ if (m0.geom(g0).name or "") != (m1.geom(g1).name or ""):
+ bad.append(f"name of geom {g0}")
+ elif m0.geom_dataid[g0] >= 0 and m0.geom_type[g0] == MESH and not np.array_equal(_mesh_verts(m0, g0),
+ _mesh_verts(m1, g1)):
+ bad.append(f"mesh of geom {m0.geom(g0).name or g0}")
+ for g in extra:
+ if m1.geom_contype[g] or m1.geom_conaffinity[g] or not 0 <= m1.geom_group[g] <= 2:
+ bad.append(f"added geom {m1.geom(g).name} collides or is not drawn")
+ return bad
+
+
+def pose_diff(m0, m1, states) -> float:
+ """The largest difference of any body's (and site's) world position or orientation between the two models over
+ the given states ({"qpos", optional "mocap_pos", "mocap_quat"}); 0.0 = bit-identical poses."""
+ import mujoco as mj
+ d0, d1 = mj.MjData(m0), mj.MjData(m1)
+ worst = 0.0
+ for st in states:
+ for m, d in ((m0, d0), (m1, d1)):
+ d.qpos[:] = np.asarray(st["qpos"], float)
+ if m.nmocap and "mocap_pos" in st:
+ d.mocap_pos[:] = np.asarray(st["mocap_pos"], float).reshape(m.nmocap, 3)
+ if m.nmocap and "mocap_quat" in st:
+ d.mocap_quat[:] = np.asarray(st["mocap_quat"], float).reshape(m.nmocap, 4)
+ mj.mj_kinematics(m, d)
+ for a, b in ((d0.xpos, d1.xpos), (d0.xquat, d1.xquat), (d0.xmat, d1.xmat), (d0.site_xpos, d1.site_xpos)):
+ if np.asarray(a).size:
+ worst = max(worst, float(np.abs(np.asarray(a) - np.asarray(b)).max()))
+ return worst
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/server.py b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/server.py
new file mode 100644
index 0000000000..5eb03f3410
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/server.py
@@ -0,0 +1,30 @@
+"""eai-standard/2.3 sim service for RoboOlympics: rcb_realtime.py (the sidecar's entry point, `python /srv/rcb_realtime.py`)
+imports this module and calls build(). The sport and its frozen instance come from environment/docker-compose.yaml:
+ RO_PLUGIN the sport's plugin (/srv/sport/plugin.py)
+ RO_FORMAT the sport's format (match: one player against the scripted opponent)
+ RO_SEED the frozen instance's seed (serves, the opponent's returns, the execution scatter)
+ RO_LEVEL the scripted opponent's level
+ RO_ACTION_LEVEL the action level (high: strokes the service plans; low: joint or mallet targets)
+ RO_TASK_TEXT, RO_EPISODE_TEXT one sentence each for /spec
+ RCB_SLOWDOWN the slowdown S (badminton's stroke lead depends on it); RCB_DATA, RCB_RESET_BUDGET,
+ RCB_WALL_CLOCK_S: the service's own (rcb_service.main)
+"""
+from __future__ import annotations
+
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from core.sport import MatchConfig # noqa: E402
+from rcb_olympics import Olympics # noqa: E402
+
+
+def build() -> Olympics:
+ env = os.environ.get
+ plugin = env("RO_PLUGIN", "/srv/sport/plugin.py")
+ sport = os.path.basename(os.path.dirname(os.path.abspath(plugin)))
+ cfg = MatchConfig(sport=env("RO_SPORT", sport), format=env("RO_FORMAT", "match"), seats=("A",),
+ seed=int(env("RO_SEED", "101")), first="A", slowdown=float(env("RCB_SLOWDOWN") or 10),
+ level=int(env("RO_LEVEL", "1")), action_level=env("RO_ACTION_LEVEL", "high"), play="program")
+ return Olympics(plugin, cfg, data=env("RCB_DATA", "/data"), task_text=env("RO_TASK_TEXT", ""),
+ episode_text=env("RO_EPISODE_TEXT", ""))
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/plugin.py b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/plugin.py
new file mode 100644
index 0000000000..a0c82ff87c
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/plugin.py
@@ -0,0 +1,918 @@
+"""badminton: robot singles badminton in real time (docs/framework_zh.md §4.2). Migrated from the Season-1 tasks
+badminton-match-wallclock-program-standard and badminton-duel-wallclock-program-standard (docs §10 stage 3). The four
+groups of contract ②, on the unchanged legacy simulator (sim/bm.py, sim/bduel.py, sim/wc.py, sim/scene/):
+ world + referee format match-wallclock = bm.Match (seat A against the scripted opponent, levels 1-2, which plays
+ inside the world), format duel-wallclock = bduel.World (seats A and B, mirrored robots); the players
+ serve (BWF Law 9: the rally winner serves; the server tosses the shuttle with `toss`, then hits
+ it below 1.15 m, upwards, into the diagonal service court); step = one 10 ms control step (the
+ legacy services' rt_advance(1) / advance()); a point end freezes the world for the reviews
+ actions low = joint targets: `traj` (a list of 9 joint targets [base_x, base_y, q1..q7], one per control
+ step, followed exactly, then the robot returns to its ready pose and the base to its spot), `none`
+ and `toss` (the shuttle appears at a point, from rest or rising: the server's missing hand);
+ high = the legacy racket command `act` (the racket state at contact T s after the act takes
+ effect), planned in the seat's plan worker by the legacy stroke controller (bm.Match.plan_racket,
+ through the legacy wc.plan_on / bduel.plan_on) on an exact copy of the match (or of the seat's
+ robot) advanced to the act's effect step k0 = request step + lead (the legacy services' lead:
+ ceil(0.4 s / wall time per step)), and lowered to the SAME `traj` command with k0, the planner's
+ state key at k0 and the stroke's hit configuration; `toss` takes effect at k0 too (nothing to
+ plan); the episode holds only `traj`, `none` and `toss`
+ referee phase / scores / tiebreaks (disqualification, then the legacy winner chain in three rules)
+ observation observe = the legacy state (score, what was heard, the robot's own body, its command); camera_job =
+ the legacy 2 cameras x 4 frames (60 ms apart), drawn by the sport itself (the legacy scenes and
+ extra geometry) in the seat's render worker
+"""
+from __future__ import annotations
+
+import copy
+import hashlib
+import itertools
+import json
+import math
+import os
+import struct
+import sys
+import time
+import zlib
+
+import numpy as np
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+SIM = os.path.join(HERE, "sim")
+if SIM not in sys.path:
+ sys.path.insert(0, SIM)
+os.environ.pop("MATCH_SEED", None) # bm.Match reads it at construction; the seed comes from the config only
+
+import bduel as BD # noqa: E402
+import bm as BM # noqa: E402
+import wc as WC # noqa: E402
+
+from core.sport import FINISHED, PLAYING, UNIT_OVER, MatchBase, Phase, Refused # noqa: E402
+
+REVISION = "badminton-wallclock-5+duel-7+core-0.2"
+SEATS2 = ("A", "B")
+OPPONENT = "opponent" # the scripted opponent's side in format match-wallclock (no seat)
+DT = BM.CONTROL_DT
+PLAN_LEAD_S = 0.4 # wall-time budget of an act's stroke planning (legacy WALLCLOCK_PLAN_LEAD_S)
+T_MAX_S = 5.0
+TRAJ_MAX = 600 # joint targets in one low-level traj command
+STROKE_KEYS = ("stroke", "base", "base_goal", "k_hit", "n_swing_steps_available", "n_swing_steps", "ik_residual",
+ "blade_error_m", "normal_error_deg", "speed_scale", "racket_vel_delivered", "T_from_now")
+VEL_LIM = BM.VEL_LIMIT * DT * (1 + 1e-6) + 1e-12
+FOCAL_PX = 434.6 # 45 degree vertical field of view on a 360 px tile
+IMAGE_LAYOUT = ("2 rows x 4 columns of 480 x 360 tiles. Row 1: camera behind and above your base line looking down the "
+ "court; row 2: camera at the side of the court (x < 0 in your frame) looking along +x: your half (y < 0) "
+ "is on the right. Columns: four camera frames 60 ms apart, oldest left; each tile is stamped with its "
+ "control step k and its time t since the shuttle shown was played (view_steps, view_times). The "
+ "shuttle is drawn enlarged: an orange cork (12 cm ball centred on the shuttle's position) with a white "
+ "skirt behind it, cork first along its flight. Yellow marks every 1 m along the outside of the singles "
+ "side lines and behind the base lines.")
+_TOKENS = itertools.count(1)
+
+
+def lead_steps(slowdown) -> int:
+ """Control steps from an act's request to its effect (the legacy services' LEAD_STEPS)."""
+ period = DT * float(slowdown or 20)
+ return max(1, int(math.ceil(PLAN_LEAD_S / period - 1e-9)))
+
+
+def _clean(x):
+ """JSON-exact python values (what the episode log holds and the replay reads back)."""
+ return json.loads(json.dumps(x, default=lambda o: o.tolist() if hasattr(o, "tolist") else float(o)))
+
+
+class Badminton(MatchBase):
+ def __init__(self, cfg):
+ self.cfg = cfg
+ self.single = len(cfg.seats) == 1
+ self.dt = DT
+ self.token = next(_TOKENS)
+ self.review_due = False
+ self.review_hist = None # single: the finished point's last camera frames (display only)
+ self.deferred = {s: None for s in cfg.seats} # a lowered command waiting for its effect step k0
+ self.rejected = {s: 0 for s in cfg.seats}
+ self.mismatch = {s: 0 for s in cfg.seats} # acts re-planned late or planned for another state
+ self.level_ = None
+ if self.single:
+ self.level_ = 1 if cfg.level is None else int(cfg.level)
+ if self.level_ not in BM.LEVELS:
+ raise ValueError(f"opponent level must be one of {sorted(BM.LEVELS)}")
+ self.g = BM.Match(self.level_, lv_override={"seed": int(cfg.seed)})
+ else:
+ self.first = cfg.first if cfg.first in SEATS2 else "A"
+ self._ctx()
+ self.g = BD.World()
+
+ def _ctx(self):
+ """bduel.py keeps the seed and the first server in module globals: set them for this match."""
+ if not self.single:
+ BD.SEED, BD.FIRST_SERVER = int(self.cfg.seed), self.first
+
+ @property
+ def k(self):
+ return self.g.k
+
+ # ------------------------------------------------------------------ robot access
+ def robot(self, seat):
+ """The object that owns the seat's robot and stroke state (bm.Match or bduel.Side)."""
+ return self.g if self.single else self.g.sides[seat]
+
+ def key(self, seat) -> str:
+ """Everything the stroke planner reads, hashed (the legacy services' state key)."""
+ return WC.state_key(self.g) if self.single else self.g.sides[seat].state_key()
+
+ # ------------------------------------------------------------------ world + referee
+ def step(self):
+ self._ctx()
+ for s in self.cfg.seats: # A, then B (the legacy apply_due order)
+ item = self.deferred[s]
+ if item is not None and item["k0"] == self.g.k:
+ self.deferred[s] = None
+ if "rejected" in self._take_effect(s, item):
+ self.rejected[s] += 1
+ g = self.g
+ n0 = len(g.points)
+ if self.single:
+ pre = list(g.hist)
+ g.rt_advance(1)
+ if g.hist and g.hist[-1]["k"] == g.k and "leg_id" not in g.hist[-1]:
+ g.hist[-1]["leg_id"] = len(g.legs) - 1 # display only (the legacy _frame_extras)
+ g.hist[-1]["wall_mono"] = time.monotonic()
+ else:
+ g.advance()
+ if len(g.points) > n0:
+ self.deferred = {s: None for s in self.cfg.seats} # no command carries over to the next point
+ if self.single:
+ self.review_hist = pre or None
+ if not g.done:
+ self.review_due = True
+ return [{"kind": "point", **_clean(g.points[-1])}]
+ return []
+
+ def state_digest(self):
+ if not self.single:
+ return self.g.state_sha()
+ g = self.g # the robot and shuttle state + the referee's record
+ rec = json.dumps({"score": list(g.score), "points": g.points}, sort_keys=True, default=float)
+ return hashlib.sha256((g.s.state_sha() + rec).encode()).hexdigest()
+
+ def capped(self):
+ return bool(self.g.points and self.g.points[-1].get("cap"))
+
+ def phase(self):
+ if self.g.done:
+ return Phase(FINISHED, reason="disqualified" if self.g.disqualified else
+ "match_limit" if self.capped() else "match_over")
+ if self.review_due:
+ return Phase(UNIT_OVER, review=tuple(self.cfg.seats), reason=self.g.points[-1]["how"])
+ return Phase(PLAYING)
+
+ def resume(self):
+ self.review_due = False
+
+ def unit(self):
+ return len(self.g.points)
+
+ def sides(self):
+ return [self.cfg.seats[0], OPPONENT] if self.single else list(SEATS2)
+
+ def scores(self):
+ if self.single:
+ return {self.cfg.seats[0]: int(self.g.score[0]), OPPONENT: int(self.g.score[1])}
+ return {s: int(self.g.score[s]) for s in SEATS2}
+
+ def tiebreaks(self):
+ """The winner chain as three rules: the score (first to 5, from 4-4 by 2, at most 7; at the match limit the
+ player ahead), else the winner of the last point that was not a let, else (last resort, not from the
+ rulebook) the player who received first (format match-wallclock: the opponent, since you serve first)."""
+ def score(m):
+ sc = m.scores()
+ a, b = m.sides()
+ return None if sc[a] == sc[b] else (a if sc[a] > sc[b] else b)
+
+ def last_point(m):
+ names = {"you": m.sides()[0], "opponent": OPPONENT} if m.single else {s: s for s in SEATS2}
+ won = [names[p["winner"]] for p in m.g.points if p.get("winner") in names]
+ return won[-1] if won else None
+
+ def first_receiver(m):
+ return OPPONENT if m.single else BD.OTHER[m.first]
+
+ def disqualification(m): # Law 16.7: the third undue-delay fault disqualifies a player
+ if m.single:
+ return OPPONENT if m.g.disqualified else None
+ return BD.OTHER[m.g.disqualified] if m.g.disqualified else None
+ return [("disqualification", disqualification), ("score", score), ("last_point", last_point),
+ ("first_receiver", first_receiver)]
+
+ def forfeit(self, seat, why):
+ return False # the core decides a forfeit; the world is left as it was
+
+ # ------------------------------------------------------------------ actions (low level)
+ def schema(self, seat):
+ return LOW_SCHEMA
+
+ def apply(self, seat, cmd):
+ self._ctx()
+ typ = cmd.get("type")
+ if typ not in ("traj", "none", "toss"):
+ return {"rejected": f"unknown command {typ!r}"}
+ k0 = cmd.get("k0")
+ if k0 is None or k0 == self.g.k:
+ return self._take_effect(seat, cmd)
+ if k0 < self.g.k:
+ return {"rejected": f"late: planned to take effect at step {k0}, now {self.g.k}"}
+ self.deferred[seat] = dict(cmd)
+ return {"effect_step": int(k0)}
+
+ def _take_effect(self, seat, cmd):
+ """A command takes effect: `toss` puts the shuttle at the given point, from rest or rising (height) (the server only, in its
+ serve window; refused with no change otherwise); `none` cancels the stroke (the legacy rt_clear); a `traj`
+ replaces the stroke under way with exactly the attribute changes of the legacy install (wc.install /
+ bduel.install). A traj is refused (no change) if it breaks a joint range or speed limit, or if the state it was
+ planned for (its key) is not the live one at its effect step."""
+ if cmd["type"] == "toss":
+ try:
+ if self.single:
+ self.g.toss(cmd["pos"], cmd.get("height", 0.0))
+ else:
+ self.g.toss(seat, cmd["pos"], cmd.get("height", 0.0))
+ except ValueError as e:
+ return {"rejected": f"serve: {e}"}
+ return {"tossed_step": int(self.g.k)}
+ if cmd["type"] == "none":
+ if self.single:
+ WC.install(self.g, {"type": "none"})
+ else:
+ BD.install(self.g.sides[seat], {"type": "none"})
+ return {"command": "cleared: the robot returns to the ready pose, the base home"}
+ key = cmd.get("key")
+ if key is not None and key != self.key(seat):
+ self.mismatch[seat] += 1
+ return {"rejected": "the robot's state at the effect step differs from the planned one"}
+ rob = self.robot(seat)
+ cur = np.asarray(rob.s.target, np.float64)
+ q = np.asarray(cmd.get("q") or np.zeros((0, 9)), np.float64).reshape(-1, 9)
+ lo, hi = rob.s.lo, rob.s.hi
+ prev = cur
+ for i, qi in enumerate(q):
+ if not np.all(np.isfinite(qi)) or (qi < lo - 1e-9).any() or (qi > hi + 1e-9).any():
+ return {"rejected": f"joint target {i} outside the joint ranges"}
+ if (np.abs(qi - prev) > VEL_LIM).any():
+ return {"rejected": f"joint target {i} breaks a joint speed limit"}
+ prev = qi
+ if (cmd.get("info") or {}).get("replanned_late_steps"):
+ self.mismatch[seat] += 1
+ q_hit = cmd.get("q_hit")
+ res = {"type": "act", "plan": [x.copy() for x in q], "info": copy.deepcopy(cmd.get("info") or {}),
+ "q_hit": None if q_hit is None else np.asarray(q_hit, np.float64), "ik_seed": None,
+ "swing_last": None}
+ if self.single:
+ WC.install(self.g, res)
+ else:
+ BD.install(self.g.sides[seat], res)
+ return {"took_effect_step": int(self.g.k), "n_targets": int(len(q))}
+
+ # ------------------------------------------------------------------ the serve
+ def serve_state(self, seat) -> dict:
+ """The current point's serve as the seat sees it: whether it serves, the phase (ready: the receiver is getting
+ waiting: the receiver is getting ready; open: the server may toss; tossed; done: the serve was delivered), the
+ steps that bound it, its base (docs/conventions/racket_serve_zh.md)."""
+ g = self.g
+ if self.single:
+ leg = g.leg
+ first = next(x for x in reversed(g.legs) if x["kind"] in ("serve", "our_serve") and x["point"] == leg["point"])
+ server = first["kind"] == "our_serve"
+ right = first["service_court_right"]
+ if server:
+ ready, deadline, rel = first["ready"], first["deadline"], first.get("toss_k")
+ phase = ("waiting" if first["state"] == "held" and g.k < ready else "open" if first["state"] == "held"
+ else "tossed" if first["state"] == "falling" else "done")
+ else:
+ ready = deadline = rel = first["launch"]
+ phase = "waiting" if g.k < ready else "done"
+ base = g.s.d.qpos[g.s.qa[:2]]
+ else:
+ rs = g.rs
+ server = rs["server"] == seat
+ right, ready, deadline, rel = rs["service_court_right"], rs["ready"], rs["deadline"], rs["toss_k"]
+ phase = {"ready": "waiting", "to_serve": "open", "tossed": "tossed"}.get(rs["state"], "done")
+ ph = g.sides[seat].s
+ base = ph.d.qpos[ph.qa[:2]]
+ return {"server": server, "right": right, "phase": phase, "ready_k": ready, "deadline_k": deadline,
+ "toss_k": rel, "base": np.asarray(base, float).copy()}
+
+ def serve_refusal(self, seat, k_eff, pos, height):
+ """Why a toss (at `pos`, rising `height`, effective at step k_eff) is refused now: (message, HTTP code) or None."""
+ sv = self.serve_state(seat)
+ if self.g.done or not sv["server"]:
+ return "it is not your serve", 409
+ if sv["phase"] not in ("waiting", "open"):
+ return "the shuttle was already tossed (one toss per serve)", 409
+ why = BM.toss_problem(pos, height, sv["base"])
+ if why:
+ return why, 400
+ if k_eff < sv["ready_k"]:
+ return (f"the receiver is ready at step {sv['ready_k']}: the toss would take effect at step {k_eff}; "
+ "send it so that it takes effect then or later (state.serve_in_s)"), 409
+ return None
+
+ def _serve_obs(self, seat):
+ g, sv = self.g, self.serve_state(seat)
+ o = {"court": "right" if sv["right"] else "left", "phase": sv["phase"]}
+ if sv["phase"] in ("waiting", "open") and sv["server"]:
+ o["opens_in_s"] = round(max(0.0, (sv["ready_k"] - g.k) * DT), 3)
+ o["deadline_in_s"] = round(max(0.0, (sv["deadline_k"] - g.k) * DT), 3)
+ if sv["toss_k"] is not None and sv["phase"] in ("tossed", "done"):
+ o["tossed_at_step"] = int(sv["toss_k"])
+ return {"you_serve": sv["server"], "you_receive_serve": not sv["server"], "serve": o,
+ "serve_in_s": round(max(0.0, (sv["ready_k"] - g.k) * DT), 3) if sv["phase"] in ("waiting", "open")
+ else None}
+
+ # ------------------------------------------------------------------ observation
+ def observe(self, seat, query=None):
+ g = self.g
+ if self.single:
+ o = self._single_state()
+ leg = g.leg
+ o.update(self._serve_obs(seat))
+ if leg["kind"] == "our_serve" and leg["state"] in ("held", "falling"):
+ o["ball_in_play"] = leg["state"] == "falling"
+ o["ball_state"] = "not yet served" if leg["state"] == "held" else "tossed: yours to hit (your serve)"
+ o["t_since_played"] = None if leg["state"] == "held" else g.t_since_launch()
+ o["heard"] = [] if leg["state"] == "held" else [{"event": "you tossed the shuttle", "t": 0.0}]
+ elif not g.in_play():
+ o["ball_in_play"] = False
+ o["ball_state"] = "not yet served"
+ o["heard"] = []
+ o["t_since_played"] = None
+ else:
+ o["ball_in_play"] = leg["state"] in ("incoming", "to_opp")
+ o["ball_state"] = {"incoming": "coming to you", "to_opp": "going to the opponent",
+ "done": "dead"}.get(leg["state"], leg["state"])
+ if leg["state"] == "to_opp":
+ o["heard"] = o["heard"] + [{"event": "you served" if leg["kind"] == "our_serve" else
+ "you hit the shuttle",
+ "t": round((leg["hit"]["k"] - leg["launch"]) * DT, 3)
+ if "k" in leg.get("hit", {}) else None}]
+ o["last_points"] = [{k: p[k] for k in ("point", "winner", "how", "score")} for p in g.points[-3:]]
+ o["last_shots"] = [{k: r.get(k) for k in ("returned", "summary", "speed_out")} for r in g.results[-3:]]
+ o["opponent_level"] = self.level_
+ else:
+ o = self._duel_state(seat)
+ rob = self.robot(seat)
+ la, active = rob._last_act, rob.plan_j < len(rob.plan)
+ k_hit = la.get("k_hit") if la else None
+ o["command"] = ({"contact_in_s": round((k_hit - g.k) * DT, 3) if k_hit is not None and k_hit >= g.k
+ else "passed",
+ "phase": "approach" if k_hit is not None and g.k < k_hit else "follow_through",
+ "pos": la.get("racket_pos"), "normal": la.get("racket_normal"), "vel": la.get("racket_vel"),
+ "stroke": la.get("stroke")}
+ if active and la else
+ {"traj_steps_left": len(rob.plan) - rob.plan_j} if active else
+ "none (the robot returns to / holds the ready pose, the base to its spot)")
+ it = self.deferred[seat]
+ if it is not None:
+ o["pending_commands"] = [{"type": {"traj": "act"}.get(it["type"], it["type"]),
+ "takes_effect_at_step": int(it["k0"])}]
+ if self.cfg.action_level == "low":
+ o["q_target"] = [float(x) for x in rob.s.target]
+ return o
+
+ def _single_state(self):
+ """bm.Match.decision_observation() without view_times (the frames' times come with the images)."""
+ g = self.g
+ ph, leg = g.s, g.leg
+ heard = [{"event": "the opponent served" if leg["kind"] == "serve" else "the opponent hit the shuttle",
+ "t": 0.0}] if leg["kind"] in ("serve", "return") else []
+ c, n, _ = ph.racket_state()
+ return {"score": {"you": g.score[0], "opponent": g.score[1]}, "point": len(g.points) + 1,
+ "ball": {"serve": "serve", "our_serve": "your serve"}.get(leg["kind"], "opponent's return"),
+ "t_since_played": g.t_since_launch(), "heard": heard,
+ "robot_base_xy": [round(float(x), 3) for x in ph.d.qpos[ph.qa[:2]]],
+ "q_arm": [round(float(x), 4) for x in ph.d.qpos[ph.qa[2:]]],
+ "racket_pos": [round(float(x), 3) for x in c], "racket_normal": [round(float(x), 3) for x in n]}
+
+ def _duel_state(self, side):
+ """The duel's state(side), without the core's fields (phase, world, step, ready ...)."""
+ w = self.g
+ rs, other, me = w.rs, BD.OTHER[side], w.sides[side]
+ ph = me.s
+ c, n, _ = ph.racket_state()
+ st = rs["state"]
+ server = rs["server"] == side
+ if st in ("ready", "to_serve"):
+ ball = "not yet served"
+ elif st == "tossed":
+ ball = "tossed: yours to hit (your serve)" if server else "the opponent tossed the shuttle (serving)"
+ elif st == "live":
+ ball = "coming to you" if rs["expect"] == side else "going to the opponent"
+ else:
+ ball = "dead"
+ heard = []
+ for e in w.events:
+ if e["kind"] == "toss":
+ heard.append({"event": "you tossed the shuttle" if e["side"] == side else
+ "the opponent tossed the shuttle", "t": round((e["k"] - rs["ready"]) * DT, 3)})
+ elif e["kind"] == "hit":
+ first = e["k"] == (rs["serve"] or {}).get("hit_k")
+ what = ("served" if first else "hit the shuttle")
+ heard.append({"event": f"you {what}" if e["side"] == side else f"the opponent {what}",
+ "t": round((e["k"] - rs["ready"]) * DT, 3)})
+ o = {"point": rs["point"] + 1, "score": {"you": w.score[side], "opponent": w.score[other]},
+ "ball_state": ball, "ball_in_play": st in ("tossed", "live"),
+ "t_since_played": round((w.k - rs["played_k"]) * DT, 3) if st in ("tossed", "live", "over") else None,
+ "heard": heard, "robot_base_xy": [round(float(x), 3) for x in ph.d.qpos[ph.qa[:2]]],
+ "q_arm": [round(float(x), 4) for x in ph.d.qpos[ph.qa[2:]]],
+ "racket_pos": [round(float(x), 3) for x in c], "racket_normal": [round(float(x), 3) for x in n],
+ "last_points": [{"point": p["point"], "how": p["how"], "let": p["let"],
+ "winner": "let" if p["winner"] is None else ("you" if p["winner"] == side else
+ "opponent"),
+ "server": "you" if p["server"] == side else "opponent",
+ "score": {"you": p["score"][side], "opponent": p["score"][other]}}
+ for p in w.points[-3:]]}
+ o.update(self._serve_obs(side))
+ return o
+
+ def _snaps(self):
+ """The 4 camera frames 60 ms apart ending at the newest one; during a review the finished point's last frames.
+ Before the first frame of a point: the current state (not stored: observing changes nothing)."""
+ g = self.g
+ if self.single:
+ hist = list(self.review_hist if (self.review_due and self.review_hist) else g.hist)
+ if not hist:
+ hist = [{"k": g.k, "t": g.t_since_launch(), "qpos": g.s.d.qpos.copy(), "sh": g.s.sh_p,
+ "shv": g.s.sh_v, "opp": g.opp_xy().copy(), "leg_id": len(g.legs) - 1}]
+ else:
+ hist = list(g.review_hist or []) if (self.review_due and g.review_hist) else list(g.hist)
+ if not hist:
+ hist = [g.snap()]
+ return [hist[max(0, len(hist) - 1 - b)] for b in reversed(BM.Match.VIEW_BACK)]
+
+ def camera_job(self, seat):
+ snaps = self._snaps()
+ if self.single:
+ frames = [{"qpos": np.asarray(s["qpos"], np.float64).copy(), "sh": tuple(float(x) for x in s["sh"]),
+ "shv": tuple(float(x) for x in s["shv"]), "opp": [float(x) for x in s["opp"]],
+ "k": int(s["k"]), "t": float(s["t"])} for s in snaps]
+ times = [round(float(s["t"]), 3) for s in snaps]
+ legs = [s.get("leg_id") for s in snaps]
+ else:
+ frames = [{"qA": np.asarray(s["qA"], np.float64).copy(), "qB": np.asarray(s["qB"], np.float64).copy(),
+ "sh": tuple(float(x) for x in s["sh"]), "shv": tuple(float(x) for x in s["shv"]),
+ "k": int(s["k"]), "played_k": int(s["played_k"])} for s in snaps]
+ times = [round((s["k"] - s["played_k"]) * DT, 3) for s in snaps]
+ legs = [s.get("flight") for s in snaps]
+ job = {"single": self.single, "side": "A" if self.single else seat, "snaps": frames}
+ meta = {"view_times": times, "view_steps": [int(s["k"]) for s in snaps], "view_leg_ids": legs,
+ "view_sim_times": [round(s["k"] * DT, 4) for s in snaps], "image_layout": IMAGE_LAYOUT,
+ "wall_mono": snaps[-1].get("wall_mono", time.monotonic())}
+ return job, meta
+
+ def final_fields(self):
+ g = self.g
+ lead = lead_steps(self.cfg.slowdown)
+ if self.single:
+ a = self.cfg.seats[0]
+ return {"level": self.level_, "points_for": int(g.score[0]), "points_against": int(g.score[1]),
+ "win_points": BM.WIN_POINTS, "won": bool(g.done and g.winner == 0),
+ "returns": int(sum(r["returned"] for r in g.results)), "our_legs": int(g.n_our_legs),
+ "match_limit": self.capped(), "hits": int(g.hits),
+ "lets": sum(1 for p in g.points if p.get("let")), "points": _clean(g.points),
+ "results": _clean(g.results), "shots": _clean(g.shots), "physics_steps": int(g.s.steps_total),
+ "opponent": _clean([x.get("opp") for x in g.legs if x.get("opp")]),
+ "serves": [{"server": "opponent", "type": x.get("serve")} if x["kind"] == "serve" else
+ {"server": "you", "toss": x.get("toss"), "toss_k": x.get("toss_k"),
+ "contact_z": (x.get("hit") or {}).get("pos", [None] * 3)[2],
+ "speed": (x.get("hit") or {}).get("speed")}
+ for x in g.legs if x.get("kind") in ("serve", "our_serve")],
+ "plan_lead_steps": lead, "rejected_acts": dict(self.rejected), "plan_mismatch": dict(self.mismatch),
+ "seats": {a: {"rejected_acts": self.rejected[a]}}}
+ return {"score": dict(g.score), "points": _clean(g.points), "hits": int(g.hits), "match_limit": self.capped(),
+ "first_server": self.first, "lead_steps": lead, "rejected_acts": dict(self.rejected),
+ "plan_mismatch": dict(self.mismatch),
+ "seats": {s: {"rejected_acts": self.rejected[s]} for s in SEATS2}}
+
+
+# ---------------------------------------------------------------------------------------------- action layers
+NUM = {"type": "number"}
+VEC3 = {"type": "vector", "len": 3}
+NONE = {"none": {}}
+SERVE = {"toss": {"pos": {**VEC3, "unit": "m",
+ "doc": f"your serve's toss (docs/conventions/racket_serve_zh.md): the shuttle appears at this "
+ f"point (your frame) when the command takes effect; {BM.TOSS_Z[0]} <= z <= "
+ f"{BM.TOSS_Z[1]}, within {BM.TOSS_REACH} m (horizontally) of your base, y <= -0.5; "
+ "only the server, once per serve, from the step the receiver is ready (state.serve)"},
+ "height": {**NUM, "min": 0.0, "max": BM.TOSS_H_MAX, "unit": "m", "optional": True,
+ "doc": f"how far it rises straight up from pos (0 <= height <= {BM.TOSS_H_MAX}; default "
+ "0: released from rest)"}}}
+HIGH_SCHEMA = {
+ "act": {"t": {**NUM, "min": 0.0, "max": T_MAX_S, "unit": "s",
+ "doc": "contact T s after the act takes effect (0 < T <= 5)"},
+ "pos": {**VEC3, "unit": "m", "doc": "racket-head centre at contact: |x| <= 3.4, -7.5 <= y <= -0.3, "
+ "0.2 <= z <= 3.0"},
+ "normal": {**VEC3, "doc": "string-face normal at contact (non-zero)"},
+ "vel": {**VEC3, "unit": "m/s", "doc": "racket-head velocity at contact, |vel| <= 8"}},
+ **SERVE, **NONE}
+LOW_SCHEMA = {
+ "traj": {"q": {"type": "list", "doc": f"1-{TRAJ_MAX} joint-target vectors [base_x, base_y, q1..q7], one per 10 ms "
+ "control step from the next step on, followed exactly (then the robot returns "
+ "to its ready pose, the base home); each within the joint ranges and the "
+ "joint speed limits"}},
+ **SERVE, **NONE}
+
+
+def _vec(body, key, n):
+ v = body.get(key)
+ if not isinstance(v, (list, tuple)) or len(v) != n:
+ raise Refused(f"{key} must be a list of {n} numbers")
+ out = []
+ for x in v:
+ if isinstance(x, bool) or not isinstance(x, (int, float)) or not math.isfinite(x):
+ raise Refused(f"{key} must hold {n} finite numbers")
+ out.append(float(x))
+ return out
+
+
+def _common(seat, body, match, allowed, lead=0):
+ if not isinstance(body, dict):
+ raise Refused("the action must be a JSON object")
+ typ = body.get("type")
+ if typ not in allowed:
+ raise Refused(f"unknown action type {typ!r}; one of {sorted(allowed)}")
+ extra = sorted(set(body) - set(allowed[typ]) - {"type"})
+ if extra:
+ raise Refused(f"unknown field(s) {extra} for {typ}")
+ item = match.deferred.get(seat)
+ if item is not None and item["k0"] > match.k:
+ raise Refused(f"your previous act takes effect at step {item['k0']}; send the next command after that", 409)
+ if typ == "none":
+ return {"type": "none"}
+ if typ == "toss":
+ rel = _vec(body, "pos", 3)
+ h = body.get("height", 0.0)
+ if isinstance(h, bool) or not isinstance(h, (int, float)) or not math.isfinite(h):
+ raise Refused("height must be a finite number (0: released from rest)")
+ bad = match.serve_refusal(seat, match.k + lead, rel, float(h))
+ if bad:
+ raise Refused(f"toss refused: {bad[0]}", bad[1])
+ return {"type": "toss", "pos": rel, "height": float(h)}
+ return None
+
+
+class LowLayer:
+ """Low level: joint targets (traj), none and toss, effective at the next control step."""
+ level = "low"
+ worker = None
+ delay_steps = 0
+
+ def schema(self, match, seat):
+ return LOW_SCHEMA
+
+ def parse(self, seat, body, match, ctx):
+ out = _common(seat, body, match, LOW_SCHEMA)
+ if out is not None:
+ return out
+ q = body.get("q")
+ if not isinstance(q, list) or not 1 <= len(q) <= TRAJ_MAX:
+ raise Refused(f"q must be a list of 1 to {TRAJ_MAX} joint-target vectors")
+ return {"type": "traj", "k0": None, "q": [_vec({"q": r}, "q", 9) for r in q]}
+
+ def snapshot(self, seat, cmd, match, ordinal):
+ return None
+
+ def prepare(self, job):
+ return None
+
+ def lower(self, seat, cmd, prepared, match):
+ return cmd, {}
+
+ def reply(self, seat, cmd, info, match):
+ return info
+
+
+def plan_job(job, model) -> dict:
+ """The legacy planner (wc._worker / the duel's workers.plan): restore the exact copy taken at the request step,
+ advance it to the effect step k0 = request step + lead with the command in force, and plan the act there
+ (wc.plan_on / bduel.plan_on: what Match.rt_act at k0 would do). Single: if the point ends on the way, the act
+ is dropped (as in the legacy planner)."""
+ k0 = int(job["k_req"]) + int(job["lead"])
+ out = {"k_effect": k0, "status": "ok"}
+ if job.get("none"):
+ return out
+ t0 = time.monotonic()
+ if job["single"]:
+ m = WC.restore(job["snap"], model)
+ while m.k < k0:
+ n0 = len(m.points)
+ m.rt_advance(1)
+ if len(m.points) > n0 or m.done:
+ out["status"] = "dropped"
+ return out
+ out["key"] = WC.state_key(m)
+ res = WC.plan_on(m, job["dec"])
+ else:
+ side = BD.restore(job["snap"], model)
+ while side.k < k0:
+ side.solo_step()
+ out["key"] = side.state_key()
+ res = BD.plan_on(side, job["dec"])
+ out.update(plan=[np.asarray(q, np.float64) for q in res["plan"]],
+ q_hit=None if res["q_hit"] is None else np.asarray(res["q_hit"], np.float64), info=res["info"],
+ plan_s=time.monotonic() - t0)
+ return out
+
+
+class PlanCtx:
+ """The seat's plan worker: the MjModel the snapshots are restored with."""
+
+ def __init__(self):
+ self.model = BM.Phys().m
+
+ def plan(self, job):
+ return plan_job(job, self.model)
+
+
+class RacketLayer(LowLayer):
+ """High level: the legacy racket command. `act` (and `none`) take effect `lead` control steps after the step at
+ which the request arrives (the legacy act lead); an act is planned in the seat's plan worker from a snapshot of
+ that step and lowered to a low-level traj with its effect step."""
+ level = "high"
+ worker = "plan"
+
+ def __init__(self, lead):
+ self.lead = lead
+ self.ctx = None # an in-process planner for a late act (see lower)
+
+ def schema(self, match, seat):
+ return HIGH_SCHEMA
+
+ def parse(self, seat, body, match, ctx):
+ out = _common(seat, body, match, HIGH_SCHEMA, self.lead)
+ if out is not None:
+ return out
+ T = body.get("t")
+ if isinstance(T, bool) or not isinstance(T, (int, float)) or not math.isfinite(T):
+ raise Refused("t must be a finite number")
+ pos, nrm, vel = _vec(body, "pos", 3), _vec(body, "normal", 3), _vec(body, "vel", 3)
+ if np.linalg.norm(nrm) < 1e-6:
+ raise Refused("normal must be a non-zero vector")
+ if not 0.0 < T <= T_MAX_S:
+ raise Refused(f"t must be in (0, {T_MAX_S}] s from when the act takes effect")
+ if not (abs(pos[0]) <= 3.4 and -7.5 <= pos[1] <= -0.3 and 0.2 <= pos[2] <= 3.0):
+ raise Refused("pos out of range: |x| <= 3.4, -7.5 <= y <= -0.3, 0.2 <= z <= 3.0")
+ if np.linalg.norm(vel) > 8.0:
+ raise Refused("vel too large: |vel| <= 8 m/s")
+ return {"type": "act", "t": float(T), "pos": pos, "normal": nrm, "vel": vel}
+
+ def snapshot(self, seat, cmd, match, ordinal):
+ job = {"single": match.single, "k_req": int(match.k), "lead": self.lead}
+ if cmd["type"] in ("none", "toss"): # nothing to plan: takes effect `lead` steps after the request
+ return dict(job, none=True)
+ match._ctx()
+ snap = WC.snapshot(match.g) if match.single else BD.snapshot(match.g.sides[seat])
+ return dict(job, snap=snap, dec=cmd)
+
+ def prepare(self, job):
+ if job.get("none"):
+ return plan_job(job, None)
+ if self.ctx is None:
+ self.ctx = PlanCtx()
+ return self.ctx.plan(job)
+
+ def lower(self, seat, cmd, prepared, match):
+ k0 = int(prepared["k_effect"])
+ if cmd["type"] == "none":
+ return {"type": "none", "k0": k0}, {"effect_step": k0}
+ if cmd["type"] == "toss":
+ return {"type": "toss", "k0": max(k0, int(match.k)), "pos": cmd["pos"], "height": cmd["height"]}, \
+ {"effect_step": k0}
+ late = match.k - k0
+ if late > 0 and prepared.get("status") == "ok" and cmd["t"] - late * DT > 0:
+ # the plan worker missed the effect step (the legacy service stalled the world until the plan came): plan
+ # again here, from the state now, for an effect now and the same contact time (the world waits)
+ d = dict(cmd, t=round(cmd["t"] - late * DT, 6))
+ job = dict(self.snapshot(seat, d, match, 0), lead=0)
+ prepared = self.prepare(job)
+ prepared["info"]["replanned_late_steps"] = late
+ k0 = int(prepared["k_effect"])
+ if prepared.get("status") != "ok": # the point ends before the effect step: nothing to install
+ return {"type": "traj", "k0": k0, "q": [], "key": "dropped: the point ends before the effect step"}, \
+ {"effect_step": k0, "stroke": {"stroke": "dropped: the point ends before the act takes effect"}}
+ info = _clean({k: v for k, v in prepared["info"].items() if k in STROKE_KEYS + ("replanned_late_steps",)})
+ low = _clean({"type": "traj", "k0": k0, "q": prepared["plan"], "q_hit": prepared["q_hit"],
+ "key": prepared["key"], "info": prepared["info"]})
+ return low, {"stroke": info, "effect_step": k0}
+
+ def reply(self, seat, cmd, info, match):
+ return info
+
+
+# ---------------------------------------------------------------------------------------------- render
+def _players_model(live, scene_file):
+ """The model the cameras draw: the players' presentation scene (presentation/presentation.toml `players`: the
+ Franka Panda's visual meshes on the same bodies, renderer rule 6; same kinematics, checked) with the live model's
+ marker settings, else the live model itself."""
+ from renderers import Scene, players_model
+ fine = players_model(HERE, Scene.from_file(scene_file))
+ if fine is None:
+ return live
+ if fine.nsite == live.nsite:
+ fine.site_pos[:], fine.site_size[:], fine.site_rgba[:] = live.site_pos, live.site_size, live.site_rgba
+ return fine
+
+
+class Views:
+ """The legacy observation images: 2 cameras x 4 frames, each tile stamped `k=.. t=..`, one PNG. Tiles are cached by
+ their content, so a frame shown in several observations is drawn once (same pixels). Since revision wallclock-5 /
+ duel-7 the arms are drawn with the players' presentation scene (the Franka Panda's 25k visual meshes)."""
+
+ def __init__(self, single, side):
+ import mujoco as mj
+ self.mj, self.single = mj, single
+ if single:
+ self.m = _players_model(mj.MjModel.from_xml_path(str(BM.SCENE)), BM.SCENE)
+ w, h = BM.Match.TILE
+ self.r = mj.Renderer(self.m, height=h, width=w)
+ self.rd = mj.MjData(self.m)
+ self.cams = []
+ for lookat, dist, az, el in BM.Match.CAMS:
+ c = mj.MjvCamera()
+ c.lookat[:] = lookat
+ c.distance, c.azimuth, c.elevation = dist, az, el
+ self.cams.append(c)
+ else:
+ self.dr = dr = BD.Renderer(side) # the legacy duel renderer: both robots, the side's own cameras
+ fine = _players_model(dr.m, BD.SCENE2)
+ if fine is not dr.m: # the same joints and qpos addresses (kinematics checked identical)
+ h, w = dr.r.height, dr.r.width
+ dr.r.close()
+ dr.m, dr.d = fine, mj.MjData(fine)
+ dr.r = mj.Renderer(fine, height=h, width=w)
+ self.cams = self.dr.cams
+ self.cache: dict = {}
+
+ def tile(self, ci, sn):
+ from PIL import Image, ImageDraw
+ mj = self.mj
+ if self.single:
+ rd = self.rd
+ rd.qpos[:] = sn["qpos"]
+ rd.mocap_pos[0] = sn["sh"]
+ v = np.asarray(sn["shv"], float)
+ if np.linalg.norm(v) < 1e-6:
+ v = np.array([0.0, 0.0, -1.0])
+ rd.mocap_quat[0] = BM.quat_z_to(v)
+ mj.mj_kinematics(self.m, rd)
+ self.r.update_scene(rd, camera=self.cams[ci])
+ BM.Match._extra_geoms(self.r.scene, np.asarray(sn["opp"], float), sn["sh"])
+ im = Image.fromarray(self.r.render())
+ ImageDraw.Draw(im).text((6, 4), f"k={sn['k']} t={sn['t']:.2f}s", fill=(255, 255, 255))
+ else:
+ dr = self.dr
+ dr.set_state(sn)
+ dr.r.update_scene(dr.d, camera=self.cams[ci])
+ im = Image.fromarray(dr.r.render())
+ t = (sn["k"] - sn["played_k"]) * DT
+ ImageDraw.Draw(im).text((6, 4), f"k={sn['k']} t={t:.2f}s", fill=(255, 255, 255))
+ return np.asarray(im)
+
+ @staticmethod
+ def content_key(ci, sn):
+ h = hashlib.sha1()
+ for name in sorted(sn):
+ v = sn[name]
+ h.update(name.encode())
+ h.update(np.ascontiguousarray(v, np.float64).tobytes() if isinstance(v, (np.ndarray, list, tuple))
+ else repr(v).encode())
+ return ci, h.hexdigest()
+
+ def draw(self, job):
+ rows = []
+ for ci in range(len(self.cams)):
+ tiles = []
+ for sn in job["snaps"]:
+ key = self.content_key(ci, sn)
+ if key not in self.cache:
+ self.cache[key] = self.tile(ci, sn)
+ tiles.append(self.cache[key])
+ rows.append(np.concatenate(tiles, axis=1))
+ if len(self.cache) > 64:
+ for key in list(self.cache)[:len(self.cache) - 48]:
+ del self.cache[key]
+ return png(np.concatenate(rows, axis=0))
+
+
+def png(img: np.ndarray) -> bytes:
+ """RGB8 PNG without row filters, zlib level 1 (the same pixels as the legacy imageio PNG, about 3x faster)."""
+ h, w = img.shape[:2]
+ raw = np.zeros((h, w * 3 + 1), np.uint8)
+ raw[:, 1:] = np.ascontiguousarray(img[..., :3], np.uint8).reshape(h, -1)
+
+ def chunk(tag, data):
+ return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
+ return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0))
+ + chunk(b"IDAT", zlib.compress(raw.tobytes(), 1)) + chunk(b"IEND", b""))
+
+
+_LOCAL_VIEWS: dict = {}
+
+
+class BadmintonSport:
+ name = "badminton"
+ protocol = "realtime"
+ revision = REVISION
+ source_dirs = [HERE]
+ workers = ("plan", "render")
+
+ def __init__(self):
+ self._lead = lead_steps(None)
+
+ def build(self, cfg):
+ self._lead = lead_steps(cfg.slowdown) # the core asks for the action layer right after build()
+ return Badminton(cfg)
+
+ def action_layer(self, level):
+ return RacketLayer(self._lead) if level == "high" else LowLayer()
+
+ def worker_init(self, kind, seat, cfg):
+ if kind == "plan":
+ return PlanCtx()
+ return Views(len(cfg.seats) == 1, seat if len(cfg.seats) > 1 else "A")
+
+ def worker_call(self, obj, kind, job):
+ if kind == "plan":
+ if obj is None:
+ obj = PlanCtx()
+ return obj.plan(job)
+ if obj is None: # in-process (core/local.py): one renderer per (format, side)
+ key = (job["single"], job["side"])
+ if key not in _LOCAL_VIEWS:
+ _LOCAL_VIEWS[key] = Views(*key)
+ obj = _LOCAL_VIEWS[key]
+ return {"png": obj.draw(job)}
+
+ def spec(self, cfg, seat, m):
+ lead = lead_steps(cfg.slowdown)
+ single = len(cfg.seats) == 1
+ out = {
+ "robot": ("franka-panda on a 1.0 m pedestal, base on x-y rails (<= 6 m/s, <= 20 m/s^2) + badminton racket "
+ f"(head centre 0.56 m beyond the flange, string bed radius {BM.R_HEAD} m)"),
+ "base": {"max_speed_mps": BM.BASE_VMAX, "max_accel_mps2": BM.BASE_AMAX, "home_xy": [float(x) for x in BM.HOME],
+ "range": {"x": [float(BM.BASE_LO[0]), float(BM.BASE_HI[0])],
+ "y": [float(BM.BASE_LO[1]), float(BM.BASE_HI[1])]}},
+ "frame": ("your own: x to your right, y towards the opponent, z up; your half y < 0, your base's home "
+ f"{[float(x) for x in BM.HOME]}" + ("" if single else "; the opponent's robot plays from y > 0 (in "
+ "its own frame it sees the game as you do)")),
+ "match": {"win_points": BM.WIN_POINTS, "two_point_lead_from": BM.WIN_POINTS - 1,
+ "cap_points": BM.CAP_POINTS, "max_hits": BM.MAX_HITS, "max_points_played": BM.MAX_POINTS,
+ "scoring": "rally point",
+ **({"opponent_level": m.level_, "first_player": seat, "first_server": seat,
+ "serves": "you serve the first point; then the winner of each rally serves the next point "
+ "(a let: the same server); the opponent serves like you, by the rules"} if single else
+ {"first_player": m.first, "first_server": m.first, "first_server_is_you": m.first == seat,
+ "serves": "match.first_server serves the first point; then the winner of each rally serves "
+ "the next point (a let: the same server)"})},
+ "serve": {"spot_right_court_xy": [float(x) for x in BM.serve_spot(True)],
+ "spot_left_court_xy": [float(x) for x in BM.serve_spot(False)],
+ "courts": "both robots stand in their right service courts when the server's score is even, else "
+ "in their left ones (diagonally opposite); the spot is your base's home for the point",
+ "base_tolerance_m": BM.BASE_TOL, "ready_s": round(BD.READY_STEPS * DT, 3),
+ "window_s": round(BM.SERVE_WINDOW_STEPS * DT, 3), "toss_z_m": list(BM.TOSS_Z),
+ "toss_reach_m": BM.TOSS_REACH, "toss_height_m": [0.0, BM.TOSS_H_MAX], "max_contact_z_m": BM.SERVE_MAX_Z,
+ "command": "{'type': 'toss', 'pos': [x, y, z], 'height': H}: the shuttle appears at the point "
+ "when the command takes effect (the same lead as an act) and rises H straight up "
+ "(0 <= H <= 0.5; 0 or omitted: released from rest); then hit it with an act (it may "
+ "be sent before the toss)",
+ "phases": "serve.phase: waiting (the receiver is getting ready), open (toss now), tossed, done",
+ "faults": "serve faults are recorded as 'serve_fault:<reason>: ...' (reasons: undue_delay, "
+ "missed, too_high, not_upwards, net, out, moved); the receiver's base moving early: "
+ "'receive_fault:moved: ...'"},
+ "act": {"lead_steps": lead, "lead_game_s": round(lead * DT, 4), "T_max_s": T_MAX_S,
+ "rule": (f"an act (and none) takes effect {lead} control steps after the step at which it arrives "
+ "(the stroke is planned meanwhile; the reply gives effect_step, the state shows "
+ "pending_commands, and a command sent before then is refused with HTTP 409); T counts "
+ "from the effect step" if cfg.action_level == "high" else
+ "traj and none take effect at the next control step")},
+ "cameras": [dict(c, fovy_deg=45.0, tile_px=list(BM.Match.TILE), focal_px=FOCAL_PX,
+ principal_point_px=[240, 180], image_right="forward x up") for c in BM.Match.cam_info()],
+ "image": "2 rows (behind, side) x 4 columns (camera frames 60 ms apart, oldest left); tile 480 x 360",
+ "shuttle": {"model": "point mass, gravity 9.81 + quadratic drag: dv/dt = g - K |v| v",
+ "K_per_m": round(BM.K_DRAG, 4), "terminal_speed_mps": BM.V_TERM,
+ "bounce": "none: the rally ends when it reaches the floor"},
+ }
+ if cfg.action_level == "low":
+ rob = m.robot(seat)
+ out["joints"] = {"names": BM.JOINTS, "low": [float(x) for x in rob.s.lo],
+ "high": [float(x) for x in rob.s.hi],
+ "max_step": [float(x) for x in BM.VEL_LIMIT * DT],
+ "ready_pose_arm": [float(x) for x in BM.Q0_ARM],
+ "rule": "each target within [low, high] and within max_step of the previous target "
+ "(the first one: of q_target in the state)"}
+ return out
+
+ def players(self):
+ import builtin_players as bp
+ return {"reference": bp.Reference, "random": bp.Random}
+
+
+SPORT = BadmintonSport()
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/presentation/presentation.toml b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/presentation/presentation.toml
new file mode 100644
index 0000000000..c219480297
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/presentation/presentation.toml
@@ -0,0 +1,16 @@
+# Appearance of badminton's robots (docs/framework_zh.md §3.1, renderer rule 6; renderers/presentation/__init__.py):
+# the Franka Panda's visual meshes on the arm's bodies, same kinematics. Since revision wallclock-5 / duel-7 the
+# players' images use it too (`players`): tools/sportlib bundles this directory and the 25k level of detail of the
+# meshes (renderers/presentation/lod.json, sha256-pinned, licence kept) into the simulator, so they are part of
+# source_sha; spectator re-renders from a checkout use the full meshes.
+[presentation]
+version = 2
+label = "Franka Panda visual meshes (MuJoCo Menagerie)"
+players = "25k" # the players' images: the meshes decimated to ~25k triangles per arm
+scenes = ["sim/scene/bm_scene.xml", "sim/scene/bm_duel.xml"] # the match scenes (badminton has no Sport.scene())
+
+[[presentation.robot]]
+model = "franka_emika_panda" # renderers/presentation/menagerie.json (fetched, sha256-pinned)
+bodies = '^link(?P<n>[0-7])(?P<b>_b)?$'
+body = "link{n}"
+hide = "mesh" # the arm's collision meshes move to the hidden group 3
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/bduel.py b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/bduel.py
new file mode 100644
index 0000000000..df3b2e91ae
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/bduel.py
@@ -0,0 +1,628 @@
+"""Badminton duel: two robots, two players; rally scoring, first to 5 points, from 4-4 a two-point lead, at most 7.
+
+Robot A (y < 0, facing +y) and robot B (y > 0, facing -y) are identical: the match task's robot (a Franka Panda on a
+sliding base with a racket, bm.py). Each player sees and acts in its OWN frame, the frame of the single-player task
+(its home at (0, -4.0), its half y < 0); B's frame is the world rotated 180 degrees about z: (x, y, z) -> (-x, -y, z).
+
+Physics. MuJoCo contacts are off in the badminton scene and the shuttle is not a MuJoCo body, so the two robots never
+interact physically: each robot runs in its OWN copy of the single-player model (scene/bm_scene.xml, `bm.Phys`), in its
+own frame, stepped in lock-step at 1 ms; the shuttle (bm's point mass with quadratic drag) is integrated once, in the
+world frame (A's frame). At every 1 ms step the racket of the player whose turn it is is tested against the shuttle
+with the match task's contact model (bm.Phys._check_hit), and only while the shuttle is on that player's half. The
+two-robot scene scene/bm_duel.xml only draws the game.
+
+Stroke control. A player's act is the match task's racket-level command, planned by the match task's stroke controller
+(`bm.Match.plan_racket`) on that player's own robot (`Side`). Because each robot's motion depends only on its own
+joint targets, a planner process can advance an exact copy of the robot to the act's effect step and plan there; the
+result is bit-identical to planning in the world thread (`apply_inline`, which the replay uses).
+
+Points (the referee is a deterministic function of the 1 ms flight, evaluated inside every control step, so the
+logged acts replay the match bit-exactly):
+ * ready: both robots at rest in the ready pose at their spots in their service courts (bm.serve_spot: the right
+ courts when the server's score is even, else the left ones; diagonally opposite, BWF 10.1, 9.1.3); FIRST_SERVER
+ serves the first point, then the rally winner (Law 10.3; a let keeps the server). READY_STEPS (1 s) after play
+ resumes the receiver is ready (state to_serve) and the server may toss the shuttle (`toss`: it appears at a point
+ within bm.TOSS_REACH of its base, bm.TOSS_Z high, from rest or rising up to bm.TOSS_H_MAX) within
+ SERVE_WINDOW_STEPS, else a service fault (undue delay; the MAX_DELAY_FAULTS-th disqualifies the player, Law
+ 16.7). Faults are recorded as "serve_fault:<reason>: ..." (docs/conventions/racket_serve_zh.md). The server must
+ hit the tossed shuttle (a miss: fault, 9.1.8) below SERVE_MAX_Z (9.1.6) and upwards (9.1). Both bases stay within BASE_TOL of
+ their spots until the serve is delivered (9.1.4; the mover's fault, both: a let);
+ * the receiver must hit the serve; then the players hit in turn. A racket meets the shuttle only when it is that
+ player's turn and the shuttle is on that player's half; after a hit the hitter's racket no longer touches it;
+ * the shuttle lands (no bounce): in the court of the player whose turn it is (lines in) -> that player loses; out of
+ that court -> the last hitter loses; on the last hitter's own half -> the hitter loses; into the net (below the
+ top, between the posts) -> the hitter loses. An unreturned serve must land in the receiver's diagonal service
+ court (else a service fault: the receiver's point).
+"""
+from __future__ import annotations
+
+import hashlib
+import io
+import json
+import os
+import pickle
+from collections import deque
+from pathlib import Path
+
+import numpy as np
+
+import mujoco as mj
+import bm
+
+# The robot, its base (6 m/s, 20 m/s^2), the scoring (first to 5, two-point lead from 4-4, at most 7), the hit cap and
+# the shot timeout are the match task's (bm.py): the single-player task and the duel play by the same rules.
+from bm import (BASE_VMAX, BASE_AMAX, WIN_POINTS, CAP_POINTS, MAX_HITS, MAX_POINTS, LEG_STEPS) # noqa: E402,F401
+from bm import (CONTROL_DT, SUBSTEPS, PHYS_DT, KP, KD, HOME, NET_TOP, POST_X, R_HEAD, RACKET_GAIN, E_SHUTTLE,
+ OFFCENTRE_LOSS, SHOT_THETAS, SHOT_VMAX, sh_step, solve_shots, in_court)
+from bm import SERVE_MAX_Z, SERVE_WINDOW_STEPS, BASE_TOL, MAX_DELAY_FAULTS, serve_spot, toss_problem, toss_vz # noqa: E402
+
+HERE = Path(__file__).resolve().parent
+SCENE2 = HERE / "scene" / "bm_duel.xml"
+REVISION = "bm-duel-wallclock-6" # 2: base 6 m/s; 3: BWF serve courts, net 1.524 m, win by 2 (cap 7), receiver every point; 4: no draws (cap winner), rules in bm.py; 5: one scatter sequence for both robots; 6: the players serve (BWF Law 9)
+SEED = int(os.environ.get("DUEL_SEED", "1")) # the (shared) execution scatter
+FIRST_SERVER = os.environ.get("FIRST_SERVER", "A") # the side that serves the first point (Law 6: the toss)
+if FIRST_SERVER not in ("A", "B"):
+ raise ValueError("FIRST_SERVER must be A or B")
+SIDES = ("A", "B")
+OTHER = {"A": "B", "B": "A"}
+MIR = np.array([-1.0, -1.0, 1.0])
+READY_STEPS = 100 # 1.0 s from resume until the receiver is ready and the server may toss
+CAM_EVERY = 2
+Q_HOME = np.r_[HOME, bm.Q0_ARM]
+
+
+def mir(v):
+ return np.asarray(v, float) * MIR
+
+
+def to_side(side, v):
+ """World (A's frame) -> the side's own frame (and back: the map is its own inverse)."""
+ return np.asarray(v, float) if side == "A" else mir(v)
+
+
+# ---------------------------------------------------------------------------------------------- one player's robot
+class Side(bm.Match):
+ """One player's robot and stroke controller in its own frame: the match task's `Match` without the shuttle, the
+ opponent and the referee (those live in `World`). Used live, in the planner process (an exact copy) and in the
+ replay."""
+
+ def __init__(self, side: str): # noqa: D107 (bm.Match.__init__ is not called on purpose)
+ self.side = side
+ self.level = 0
+ # the execution scatter: ONE seeded sequence shared by both robots (the n-th act of each robot gets the same
+ # scatter draw, bm.Match.plan_racket), so neither seat nor role picks a luckier stream (as baseball's duel
+ # gives both batters the same pitches); revision 4 drew a stream per role (seed x 10 + 0 for the first
+ # receiver, + 1 for the other), which made the first receiver win 30 of 40 fairness matches
+ self.lv = {"seed": SEED * 10}
+ self.s = bm.Phys()
+ self.s.reset(Q_HOME.copy())
+ self.home = HOME.copy() # the ready target's base goal: the point's spot (go_home)
+ self._twin = None
+ self.plan, self.plan_j = [], 0
+ self.leg = {"launch": 0}
+ self.shots: list = []
+ self._last_act = None
+ self._q_hit_active = None
+ self._ik_seed = None
+ self.n_applied = 0 # acts applied so far (the execution scatter's stream index)
+ self.n_since_reset = 0 # control steps since the robot was last put back at home
+
+ @property
+ def n_our_legs(self): # bm.Match.plan_racket's scatter index: this player's act ordinal
+ return self.n_applied
+
+ def _target_vel(self):
+ a = self.s._actions
+ return (a[-1] - a[-2]) / CONTROL_DT if self.n_since_reset >= 2 and len(a) >= 2 else np.zeros(9)
+
+ def rt_act(self, T, pos, nrm, vel):
+ self.leg = {"launch": self.k} # T counts from now
+ return super().rt_act(T, pos, nrm, vel)
+
+ def go_home(self, spot):
+ """Before a serve: the robot at its spot in its service court (its home for the point) in the ready pose, at
+ rest, no command."""
+ ph = self.s
+ self.home = np.asarray(spot, float).copy()
+ q = np.r_[self.home, bm.Q0_ARM]
+ ph.d.qpos[ph.qa] = q; ph.d.qvel[ph.va] = 0.0
+ mj.mj_forward(ph.m, ph.d)
+ ph.target = q.copy()
+ self.plan, self.plan_j = [], 0
+ self._last_act = None; self._q_hit_active = None
+ self.n_since_reset = 0
+
+ def solo_step(self):
+ """One control step of this robot alone (the planner's copy): the same targets and robot physics as World."""
+ q = np.asarray(self._arm_target(), float)
+ self.s.step(q)
+ self.n_since_reset += 1
+
+ def state_key(self) -> str:
+ """Everything the stroke planner reads, hashed."""
+ ph = self.s
+ h = hashlib.sha256()
+ for a in (ph.d.qpos, ph.d.qvel, ph.d.qacc_warmstart, ph.d.ctrl, np.array([ph.d.time]), ph.target):
+ h.update(np.ascontiguousarray(a, dtype=np.float64).tobytes())
+ h.update(repr((self.k, self.plan_j, len(self.plan), self.n_applied, self.n_since_reset)).encode())
+ h.update(np.ascontiguousarray(self.home, dtype=np.float64).tobytes())
+ if len(ph._actions) >= 2:
+ h.update(np.ascontiguousarray(ph._actions[-2], dtype=np.float64).tobytes())
+ if self._q_hit_active is not None:
+ h.update(np.ascontiguousarray(self._q_hit_active, dtype=np.float64).tobytes())
+ if self.plan_j < len(self.plan):
+ h.update(np.ascontiguousarray(np.asarray(self.plan[self.plan_j:]), dtype=np.float64).tobytes())
+ return h.hexdigest()
+
+
+def plan_on(side: Side, dec: dict) -> dict:
+ """What `apply_inline` would do at the copy's current step, as an installable result."""
+ if dec["type"] == "none":
+ return {"type": "none"}
+ T = float(dec["t"])
+ side.leg = {"launch": side.k}
+ ik_seed = side._q_hit_active if side.plan_j < len(side.plan) else None
+ side._ik_seed = ik_seed
+ plan, info = side.plan_racket(T, dec["pos"], dec["normal"], dec["vel"])
+ q_hit = info.pop("_q_hit", None)
+ info["T_from_now"] = round(T, 4)
+ return {"type": "act", "plan": plan, "q_hit": q_hit, "info": info, "ik_seed": ik_seed,
+ "swing_last": getattr(side, "_swing_last", None)}
+
+
+def install(side: Side, res: dict):
+ """Apply a planned result with exactly the attribute changes of `apply_inline`."""
+ side.n_applied += 1
+ if res["type"] == "none":
+ side.rt_clear()
+ return None
+ side.leg = {"launch": side.k}
+ side._ik_seed = res["ik_seed"]
+ if res["swing_last"] is not None:
+ side._swing_last = res["swing_last"]
+ info = res["info"]
+ if res["plan"]:
+ side.plan, side.plan_j = res["plan"], 0
+ side._q_hit_active = res["q_hit"]
+ side.shots.append({"k": side.k, "leg": side.n_applied - 1, **info})
+ side._last_act = info
+ return info
+
+
+def apply_inline(side: Side, dec: dict):
+ """The reference semantics (also the replay's): plan and apply at the current step."""
+ if dec["type"] == "none":
+ side.n_applied += 1
+ side.rt_clear()
+ return None
+ info = side.rt_act(dec["t"], dec["pos"], dec["normal"], dec["vel"])
+ side.n_applied += 1
+ return info
+
+
+# ---------------------------------------------------------------------------------------------- snapshots
+class _Pickler(pickle.Pickler):
+ def persistent_id(self, obj):
+ return "MODEL" if isinstance(obj, mj.MjModel) else None
+
+
+class _Unpickler(pickle.Unpickler):
+ def __init__(self, f, model):
+ super().__init__(f)
+ self.model = model
+
+ def persistent_load(self, pid):
+ if pid != "MODEL":
+ raise pickle.UnpicklingError(pid)
+ return self.model
+
+
+def snapshot(side: Side) -> bytes:
+ """Exact copy of one robot for planning (not copied: the MjModel, the scratch twin, older joint targets)."""
+ tw = side.__dict__.pop("_twin", None)
+ acts = side.s._actions
+ side.s._actions = acts[-2:]
+ try:
+ f = io.BytesIO()
+ _Pickler(f, protocol=pickle.HIGHEST_PROTOCOL).dump(side)
+ return f.getvalue()
+ finally:
+ side._twin = tw
+ side.s._actions = acts
+
+
+def restore(b: bytes, model) -> Side:
+ side = _Unpickler(io.BytesIO(b), model).load()
+ side._twin = None
+ return side
+
+
+# ---------------------------------------------------------------------------------------------- the world
+class World:
+ def __init__(self):
+ self.sides = {s: Side(s) for s in SIDES}
+ self.k = 0
+ self.sh_p, self.sh_v, self.sh_live = (0.0, 3.0, 1.0), (0.0, 0.0, 0.0), False
+ self.prev = {s: None for s in SIDES}
+ self.events: list[dict] = []
+ self.score = {"A": 0, "B": 0}
+ self.points: list[dict] = []
+ self.hits = 0
+ self.plays = 0 # tosses + hits in the match (a flight's id)
+ self.done = False
+ self.winner = None
+ self.hist: deque = deque(maxlen=16)
+ self.review_hist = None
+ self._pending_point = None
+ self.delay_faults = {"A": 0, "B": 0} # serves not tossed in time (undue delay)
+ self.disqualified = None # the side with MAX_DELAY_FAULTS (Law 16.7): it loses the match
+ self._start_point(0)
+
+ # ------------------------------------------------------------------ points
+ def next_server(self):
+ """FIRST_SERVER serves the first point (Law 6); then the winner of the last rally serves (Law 10.3); after a
+ let the same player serves again (Law 14.3)."""
+ if not self.points:
+ return FIRST_SERVER
+ last = self.points[-1]
+ return last["server"] if last["let"] else last["winner"]
+
+ def receiver(self):
+ return self.rs["receiver"]
+
+ def match_over(self):
+ """First to WIN_POINTS; from 4-4 a two-point lead is needed, capped: the first to CAP_POINTS wins."""
+ hi, lo = max(self.score.values()), min(self.score.values())
+ return (hi >= WIN_POINTS and hi - lo >= 2) or hi >= CAP_POINTS
+
+ def _start_point(self, hold_from):
+ n = len(self.points)
+ srv = self.next_server()
+ recv = OTHER[srv]
+ right = self.score[srv] % 2 == 0 # the server's right court when its score is even (Law 10.1)
+ spot = serve_spot(right) # both robots in their right (left) service courts: diagonal (9.1.3)
+ ready = hold_from + READY_STEPS
+ self.rs = {"point": n, "server": srv, "receiver": recv, "service_court_right": right,
+ "hold_from": hold_from, "ready": ready, "deadline": ready + SERVE_WINDOW_STEPS, "launch": ready,
+ "expect": srv, "last_hitter": None, "played_k": ready, "state": "ready", "flight": self.plays,
+ "hits_in_point": 0, "serve_flight": False, "toss_k": None, "serve": None, "spot": spot.copy()}
+ # the shuttle is held in the server's (missing) free hand, beside its ready pose, until the toss
+ self.sh_p = tuple(float(x) for x in to_side(srv, np.r_[spot + np.array([-0.25, 0.35]), 1.0]))
+ self.sh_v = (0.0, 0.0, 0.0)
+ self.sh_live = False; self.hit_enabled = False
+ self.events = []
+ self.hist.clear()
+ for s in SIDES:
+ self.sides[s].go_home(spot)
+ self.prev[s] = None
+
+ def delivered(self):
+ """The serve of the current point was delivered (hit or faulted)."""
+ return self.rs["state"] not in ("ready", "to_serve", "tossed")
+
+ def toss(self, side, p, h=0.0):
+ """The server's toss: the shuttle appears at p (its own frame) now and rises h straight up (0: from rest).
+ Raises ValueError if not allowed."""
+ rs = self.rs
+ if self.done or side != rs["server"]:
+ raise ValueError("it is not your serve")
+ if rs["state"] == "ready":
+ raise ValueError(f"the receiver is not ready before step {rs['ready']}")
+ if rs["state"] != "to_serve":
+ raise ValueError("the shuttle was already tossed")
+ ph = self.sides[side].s
+ why = toss_problem(p, h, ph.d.qpos[ph.qa[:2]])
+ if why:
+ raise ValueError(why)
+ self.sh_p = tuple(float(x) for x in to_side(side, p)); self.sh_v = (0.0, 0.0, toss_vz(h))
+ self.sh_live = True; self.hit_enabled = True
+ rs.update(state="tossed", toss_k=self.k, played_k=self.k, launch=self.k)
+ rs["serve"] = {"toss": [round(float(x), 4) for x in p], "toss_height": float(h), "toss_k": self.k}
+ self.plays += 1; rs["flight"] = self.plays
+ self.events.append({"kind": "toss", "side": side, "k": self.k})
+
+ def in_play(self):
+ return self.rs["state"] in ("tossed", "live")
+
+ def _end_point(self, loser, how):
+ if self._pending_point is None:
+ self._pending_point = (loser, how)
+
+ def _commit_point(self):
+ loser, how = self._pending_point
+ self._pending_point = None
+ winner = OTHER[loser] if loser is not None else None
+ if winner is not None:
+ self.score[winner] += 1
+ self.review_hist = list(self.hist)
+ self.points.append({"point": len(self.points) + 1, "winner": winner, "loser": loser, "how": how,
+ "score": dict(self.score), "hits": self.rs["hits_in_point"], "step": self.k,
+ "server": self.rs["server"], "receiver": self.rs["receiver"],
+ "court": "right" if self.rs["service_court_right"] else "left",
+ "serve": self.rs["serve"], "let": loser is None})
+ self.rs["state"] = "over"
+ if self.disqualified:
+ self.points[-1]["disqualified"] = self.disqualified
+ self.winner = OTHER[self.disqualified]
+ self.done = True
+ return
+ if self.match_over():
+ self.winner = max(SIDES, key=lambda s: self.score[s])
+ self.done = True
+ return
+ if self.hits >= MAX_HITS or len(self.points) >= MAX_POINTS:
+ # the cap: the leader wins; if level, the winner of the last point (no draws; as in the single task); the
+ # last resort (no point won, not from the rulebook): the player who received first
+ last = next((p["winner"] for p in reversed(self.points) if p["winner"]), OTHER[FIRST_SERVER])
+ sa, sb = self.score["A"], self.score["B"]
+ self.winner = "A" if sa > sb else "B" if sb > sa else last
+ self.points[-1]["cap"] = True
+ self.done = True
+ return
+ self._start_point(self.k)
+
+ # ------------------------------------------------------------------ physics (shared by live and replay)
+ def advance(self):
+ """One control step: both robots follow their commands (the planned stroke, else back to the ready pose)."""
+ if self.done:
+ raise ValueError("the match is over")
+ qs = {s: np.asarray(self.sides[s]._arm_target(), float) for s in SIDES}
+ for s in SIDES:
+ self.sides[s].s.check_target(qs[s])
+ prev_t = {s: self.sides[s].s.target for s in SIDES}
+ qd_des = {s: (qs[s] - prev_t[s]) / CONTROL_DT for s in SIDES}
+ rk = {}
+ for j in range(1, SUBSTEPS + 1):
+ for s in SIDES: # the robot part of bm.Phys.step, per robot in its own model
+ ph = self.sides[s].s
+ m, d = ph.m, ph.d
+ q_des = prev_t[s] + (qs[s] - prev_t[s]) * (j / SUBSTEPS)
+ tau = KP * (q_des - d.qpos[ph.qa]) + KD * (qd_des[s] - d.qvel[ph.va]) + d.qfrc_bias[ph.va]
+ d.ctrl[:] = np.clip(tau, m.actuator_ctrlrange[:, 0], m.actuator_ctrlrange[:, 1])
+ mj.mj_step(m, d)
+ c = d.site_xpos[ph.site].copy(); n = d.site_xmat[ph.site].reshape(3, 3)[:, 0].copy()
+ rk[s] = (to_side(s, c), to_side(s, n))
+ if self.sh_live:
+ e = self.rs["expect"]
+ own_half = self.sh_p[1] < 0 if e == "A" else self.sh_p[1] > 0
+ if self.hit_enabled and own_half and self.prev[e] is not None:
+ self._check_hit(e, *rk[e])
+ for s in SIDES:
+ self.prev[s] = (rk[s][0], rk[s][1], self.sh_p)
+ self._advance_shuttle()
+ else:
+ for s in SIDES:
+ self.prev[s] = (rk[s][0], rk[s][1], self.sh_p)
+ for s in SIDES:
+ ph = self.sides[s].s
+ ph.target = qs[s].copy()
+ ph._actions.append(qs[s].copy())
+ ph.k += 1
+ ph.steps_total += SUBSTEPS
+ self.sides[s].n_since_reset += 1
+ self.k += 1
+ rs = self.rs
+ if rs["state"] == "ready" and self.k >= rs["ready"]:
+ rs["state"] = "to_serve" # the receiver is ready (Law 9.4): the server may toss
+ if self._pending_point is None and rs["state"] != "over":
+ self._referee()
+ if self.k % CAM_EVERY == 0 or self._pending_point is not None:
+ self.hist.append(self.snap())
+ if self._pending_point is not None:
+ self._commit_point()
+
+ def snap(self):
+ return {"k": self.k, "qA": self.sides["A"].s.d.qpos.copy(), "qB": self.sides["B"].s.d.qpos.copy(),
+ "sh": self.sh_p, "shv": self.sh_v, "played_k": self.rs["played_k"], "point": self.rs["point"],
+ "flight": self.rs["flight"], "wall_mono": __import__("time").monotonic()}
+
+ def _check_hit(self, side, c, n):
+ """bm.Phys._check_hit for one racket (world frame)."""
+ cp, npv, sp = self.prev[side]
+ sp = np.array(sp); sh = np.array(self.sh_p)
+ s0 = float((sp - cp) @ npv); s1 = float((sh - c) @ n)
+ if s0 * s1 > 0 or (s0 == 0 and s1 == 0):
+ return
+ f = s0 / (s0 - s1) if s0 != s1 else 0.0
+ pc = cp + f * (c - cp); ps = sp + f * (sh - sp)
+ r = ps - pc
+ off = float(np.linalg.norm(r - (r @ n) * n))
+ if off > R_HEAD:
+ return
+ vr = (c - cp) / PHYS_DT; vs = np.array(self.sh_v)
+ n_out = n if float((vr - vs) @ n) >= 0 else -n
+ u = float(vr @ n_out); vin = float(vs @ n_out)
+ spd = RACKET_GAIN * max(u, 0.0) * (1 - OFFCENTRE_LOSS * (off / R_HEAD) ** 2) + E_SHUTTLE * max(0.0, -vin)
+ v_out = n_out * spd
+ p_new = ps + n_out * 0.002
+ self.sh_p = tuple(float(x) for x in p_new); self.sh_v = tuple(float(x) for x in v_out)
+ rs = self.rs
+ serve = rs["state"] == "tossed" # the server's hit of the tossed shuttle: the serve
+ rs["last_hitter"] = side; rs["expect"] = OTHER[side]; rs["played_k"] = self.k
+ rs["hits_in_point"] += 1; self.hits += 1; self.plays += 1; rs["flight"] = self.plays
+ rs["serve_flight"] = serve
+ self.events.append({"kind": "hit", "side": side, "k": self.k, "pos": [round(float(x), 4) for x in ps],
+ "offcentre": round(off, 4), "racket_speed": round(u, 3), "speed": round(spd, 3),
+ "v_out": [round(float(x), 3) for x in v_out]})
+ if serve:
+ rs["state"] = "live"
+ z = float(ps[2])
+ rs["serve"].update(hit_k=self.k, contact_z=round(z, 4), speed=round(spd, 3),
+ v_out=[round(float(x), 3) for x in to_side(side, v_out)])
+ if z > SERVE_MAX_Z: # Law 9.1.6: the whole shuttle below 1.15 m when hit
+ self._end_point(side, f"serve_fault:too_high: {side} hit the shuttle {z:.2f} m high, above {SERVE_MAX_Z} m "
+ "(Law 9.1.6)")
+ elif float(v_out[2]) <= 0.0: # Law 9.1: the flight upwards from the server's racket
+ self._end_point(side, f"serve_fault:not_upwards: {side}'s serve did not go upwards from the racket (Law 9.1)")
+
+ def _advance_shuttle(self):
+ """bm.Phys._advance_shuttle (world frame)."""
+ p, v = self.sh_p, self.sh_v
+ p1, v1 = sh_step(p, v)
+ if (p[1] > 0) != (p1[1] > 0) and p[1] != p1[1]:
+ f = p[1] / (p[1] - p1[1])
+ z = p[2] + f * (p1[2] - p[2]); x = p[0] + f * (p1[0] - p[0])
+ self.events.append({"kind": "cross", "k": self.k, "x": round(x, 4), "z": round(z, 4),
+ "to": "B" if p1[1] > 0 else "A"})
+ if z < NET_TOP and abs(x) <= POST_X:
+ self.sh_p = (x, 0.0, z); self.sh_v = (0.0, 0.0, 0.0); self.sh_live = False
+ self.events.append({"kind": "net", "k": self.k, "x": round(x, 4), "z": round(z, 4)})
+ return
+ if p1[2] <= 0.0:
+ f = p[2] / (p[2] - p1[2]) if p[2] != p1[2] else 1.0
+ x = p[0] + f * (p1[0] - p[0]); y = p[1] + f * (p1[1] - p[1])
+ self.sh_p = (x, y, 0.0); self.sh_v = (0.0, 0.0, 0.0); self.sh_live = False
+ self.events.append({"kind": "land", "k": self.k, "x": round(x, 4), "y": round(y, 4)})
+ return
+ self.sh_p, self.sh_v = p1, v1
+
+ def _referee(self):
+ rs = self.rs
+ if not self.delivered(): # Law 9.1.4: server and receiver stand still until the serve
+ moved = {}
+ for s in SIDES:
+ ph = self.sides[s].s
+ d = float(np.hypot(*(ph.d.qpos[ph.qa[:2]] - rs["spot"])))
+ if d > BASE_TOL:
+ moved[s] = d
+ if len(moved) == 2:
+ return self._end_point(None, "let: both bases moved before the serve was delivered (Law 14.2.2)")
+ if moved:
+ s, d = next(iter(moved.items()))
+ who = "serve_fault:moved" if s == rs["server"] else "receive_fault:moved"
+ return self._end_point(s, f"{who}: {s}'s base moved {d:.2f} m from its spot before the serve was "
+ "delivered (Law 9.1.4)")
+ srv = rs["server"]
+ if rs["state"] == "to_serve":
+ if self.k >= rs["deadline"]:
+ self.delay_faults[srv] += 1
+ dq = self.delay_faults[srv] >= MAX_DELAY_FAULTS
+ if dq:
+ self.disqualified = srv
+ return self._end_point(srv, f"serve_fault:undue_delay: {srv} did not toss the shuttle within "
+ f"{SERVE_WINDOW_STEPS * CONTROL_DT:.0f} s (undue delay, Law 9.1.1)"
+ + (f"; {srv}'s {MAX_DELAY_FAULTS}rd undue-delay fault disqualifies it "
+ "(Law 16.7)" if dq else ""))
+ return
+ if rs["state"] not in ("tossed", "live"):
+ return
+ exp, hitter = rs["expect"], rs["last_hitter"]
+ ends = [e for e in self.events if e["kind"] in ("net", "land") and e["k"] == self.k - 1]
+ if ends:
+ e = ends[0]
+ if rs["state"] == "tossed": # the tossed shuttle reached the floor: the server missed it
+ return self._end_point(srv, f"serve_fault:missed: {srv} missed the shuttle (Law 9.1.8)")
+ if e["kind"] == "net":
+ if rs["serve_flight"]:
+ return self._end_point(hitter, f"serve_fault:net: {hitter}'s serve hit the net (x={e['x']:.2f}, "
+ f"height {e['z']:.2f} m; Laws 9.1, 13.3.2)")
+ return self._end_point(hitter, f"{hitter}'s shot hit the net (x={e['x']:.2f}, height {e['z']:.2f} m)")
+ x, y = e["x"], e["y"]
+ half = "A" if y < 0 else "B"
+ sign = lambda s: -1 if s == "A" else 1 # in_court's side argument in the world frame
+ if half == hitter:
+ return self._end_point(hitter, f"{hitter}'s shot came down on its own side (x={x:.2f}, y={y:.2f})")
+ if rs["serve_flight"]: # the serve: it must land in the receiver's diagonal service court
+ xr, yr = to_side(exp, [x, y, 0.0])[:2]
+ if bm.in_service_court(xr, yr, rs["service_court_right"]):
+ return self._end_point(exp, f"{hitter}'s serve landed in {exp}'s service court (x={x:.2f}, "
+ f"y={y:.2f}): {exp} did not return it")
+ return self._end_point(hitter, f"serve_fault:out: {hitter}'s serve landed outside {exp}'s service court "
+ f"(x={x:.2f}, y={y:.2f})")
+ if in_court(x, y, sign(exp)):
+ return self._end_point(exp, f"{hitter}'s shot landed in {exp}'s court (x={x:.2f}, y={y:.2f}): {exp} did not return it")
+ return self._end_point(hitter, f"{hitter}'s shot landed out (x={x:.2f}, y={y:.2f})")
+ if self.k - rs["played_k"] > LEG_STEPS:
+ return self._end_point(exp, f"{exp} did not play the shuttle in time")
+
+ # ------------------------------------------------------------------ replay and fingerprints
+ def actions(self):
+ return {s: [q.tolist() for q in self.sides[s].s._actions] for s in SIDES}
+
+ def state_sha(self):
+ h = hashlib.sha256()
+ for s in SIDES:
+ d = self.sides[s].s.d
+ for a in (d.qpos, d.qvel, d.qacc_warmstart, d.ctrl, np.array([d.time])):
+ h.update(np.ascontiguousarray(a, dtype=np.float64).tobytes())
+ h.update(np.array(self.sh_p + self.sh_v, dtype=np.float64).tobytes())
+ h.update(json.dumps(self.points, sort_keys=True).encode())
+ return h.hexdigest()
+
+ def targets_sha(self):
+ return hashlib.sha256(json.dumps(self.actions(), sort_keys=True, separators=(",", ":")).encode()).hexdigest()
+
+
+# ---------------------------------------------------------------------------------------------- rendering
+CAMS = bm.Match.CAMS # behind and side, in the player's own frame (as in the match task)
+VIEW_BACK = bm.Match.VIEW_BACK # 0, 60, 120, 180 ms back
+TILE = bm.Match.TILE
+
+
+class Renderer:
+ """Draws the two-robot scene: the player's two cameras (in its own frame) x 4 frames."""
+
+ def __init__(self, side="A", width=TILE[0], height=TILE[1]):
+ self.m = mj.MjModel.from_xml_path(str(SCENE2))
+ self.d = mj.MjData(self.m)
+ jid = lambda n: self.m.jnt_qposadr[mj.mj_name2id(self.m, mj.mjtObj.mjOBJ_JOINT, n)]
+ self.qa = {"A": np.array([jid(j) for j in bm.JOINTS]), "B": np.array([jid(j + "_b") for j in bm.JOINTS])}
+ self.r = mj.Renderer(self.m, height=height, width=width)
+ self.cams = []
+ for lookat, dist, az, el in CAMS:
+ c = mj.MjvCamera()
+ c.lookat[:] = to_side(side, lookat); c.distance = dist; c.azimuth = az + (0.0 if side == "A" else 180.0)
+ c.elevation = el
+ self.cams.append(c)
+
+ def set_state(self, sn):
+ d = self.d
+ d.qpos[self.qa["A"]] = sn["qA"]; d.qpos[self.qa["B"]] = sn["qB"]
+ d.mocap_pos[0] = sn["sh"]
+ v = np.asarray(sn["shv"], float)
+ if np.linalg.norm(v) < 1e-6:
+ v = np.array([0.0, 0.0, -1.0])
+ d.mocap_quat[0] = bm.quat_z_to(v)
+ mj.mj_kinematics(self.m, d)
+
+ def views(self, snaps) -> bytes:
+ import imageio.v2 as imageio
+ from PIL import Image, ImageDraw
+ rows = []
+ for c in self.cams:
+ tiles = []
+ for sn in snaps:
+ self.set_state(sn)
+ self.r.update_scene(self.d, camera=c)
+ im = Image.fromarray(self.r.render())
+ t = (sn["k"] - sn["played_k"]) * CONTROL_DT
+ ImageDraw.Draw(im).text((6, 4), f"k={sn['k']} t={t:.2f}s", fill=(255, 255, 255))
+ tiles.append(np.asarray(im))
+ rows.append(np.concatenate(tiles, axis=1))
+ buf = io.BytesIO()
+ imageio.imwrite(buf, np.concatenate(rows, axis=0), format="png")
+ return buf.getvalue()
+
+
+def render_video(acts, k_end, out, fps=25, every=2):
+ """Replay video from the logged acts: a high side view of the whole court, 2x slow motion, with the score."""
+ import imageio.v2 as imageio
+ from PIL import Image, ImageDraw
+ w = World()
+ rd = Renderer("A", 640, 360)
+ cam = mj.MjvCamera(); cam.lookat[:] = [0.0, 0.0, 1.0]; cam.distance = 17.0; cam.azimuth = 0.0; cam.elevation = -22.0
+ vw = imageio.get_writer(out, fps=fps, macro_block_size=8)
+ i = 0
+ while w.k < k_end and not w.done:
+ while i < len(acts) and acts[i][0] == w.k:
+ apply_inline(w.sides[acts[i][1]], acts[i][2]); i += 1
+ w.advance()
+ if w.k % every or (w.rs["state"] != "live" and w.k % (3 * every)):
+ continue
+ rd.set_state(w.snap())
+ rd.r.update_scene(rd.d, camera=cam)
+ im = Image.fromarray(rd.r.render())
+ ImageDraw.Draw(im).text((10, 8), f"B (left) {w.score['B']} : {w.score['A']} A (right) point {len(w.points) + 1}",
+ fill=(255, 255, 255))
+ vw.append_data(np.asarray(im))
+ vw.close()
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/bm.py b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/bm.py
new file mode 100644
index 0000000000..3b313fd3db
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/bm.py
@@ -0,0 +1,1600 @@
+"""Core of the robot badminton match service (interactive mode): first to 5 (two-point lead from 4-4, at most 7) against a scripted opponent.
+
+World (metres, seconds): floor z = 0, court long axis y, net = the plane y = 0 with its top at 1.524 m. The robot's
+half is y < 0, the opponent's y > 0. Singles court |x| <= 2.59, |y| <= 6.70.
+
+Robot: a Franka Panda arm on a 1.0 m pedestal whose base slides in x and y (a mobile base: 2 prismatic joints, speed
+<= 6 m/s), holding a badminton racket (head centre 0.56 m beyond the flange). One action = 9 absolute joint targets
+[base_x, base_y, q1..q7] held for 10 ms; a PD controller with bias compensation (1 ms physics steps) tracks them;
+target steps are limited to the joint speed limits (base 6 m/s, Franka datasheet for the arm).
+
+Shuttlecock (not a MuJoCo body; integrated here at 1 ms, semi-implicit Euler, pure Python floats, deterministic):
+a point mass under gravity and quadratic drag, dv/dt = g - K |v| v with K = g / V_TERM^2, V_TERM = 6.8 m/s (the
+measured terminal speed of a feather shuttle). A real shuttle flips to fly cork first within a few centimetres of a
+hit; a point mass has no orientation, it is drawn cork first along its velocity. No bounce: when the shuttle reaches
+the floor (z <= 0) the rally is over.
+
+Racket-shuttle contact (a model, not MuJoCo contact): at every 1 ms step the shuttle's centre is tested against the
+racket's string plane; when it crosses the plane within R_HEAD of the head centre, the shuttle leaves along the face
+normal (the side facing the relative motion) at
+ speed = RACKET_GAIN * (racket-head speed along the normal) * (1 - OFFCENTRE_LOSS (r / R_HEAD)^2)
+ + E_SHUTTLE * (incoming speed into the face)
+RACKET_GAIN = 20 stands for the string bed and the wrist snap a Franka does not have (a Franka moves the head at a few
+m/s; a badminton shot needs 15-50 m/s). One hit per shot.
+
+Point flow (all inside Match.step() and the player's commands, so a recorded command sequence replays the whole match
+bit-exactly). You serve the first point; then the winner of the last rally serves (BWF Law 10.3). Both players stand
+at their spots in their service courts (serve_spot, diagonally opposite) before every serve:
+ ready READY_STEPS; the server holds the shuttle.
+ serve the opponent's serve: high and deep, or short (a seeded choice per point, by level), hit at 1.05 m
+ upwards into your diagonal service court. Your serve (leg kind "our_serve"): within SERVE_WINDOW_STEPS you
+ toss the shuttle (toss(), the `toss` command) and hit it below SERVE_MAX_Z, upwards; then it flies
+ to the opponent like any of your shots (it must land in the opponent's diagonal service court).
+ our leg the shuttle comes to us; the model decides the shot (live code: swing / adjust decision points); the
+ robot hits it or not. Our shot is good if the shuttle crosses the net above its top and would land in the
+ opponent's court. The shuttle landing in our court, the net, out = the opponent's point.
+ opp leg the opponent (below) returns it (a new "our leg" starts at its hit) or cannot reach it (our point when it
+ lands in); a shot that would land out it leaves (our fault).
+
+The opponent (LEVELS): a kinematic player on its half, at home (0, 3.8) between rallies. `reaction_s` after our hit it
+predicts the flight perfectly and moves in a straight line towards the best interception point at `chase` m/s; after
+its own shots it walks back home at `recover` m/s. For every point of the flight in its hitting envelope (its half,
+height 0.1-2.7 m) it evaluates
+ pressure = max(max(0, distance - chase * time) / reach, (shuttle speed there - SPEED_FREE) / (max_speed - SPEED_FREE))
+takes the shuttle at the earliest point whose pressure is within 0.05 of the minimum, and there, deterministically:
+pressure > 1 -> it misses (our point); > PRESSURE_WEAK -> a weak lift to the middle of our court; < PRESSURE_PASSIVE ->
+it attacks (a smash from above 1.9 m, else a tight drop or a fast push to a corner, at its widest); otherwise a
+normal return (a seeded clear / drop / drive within the level's width and pace). It sets the shuttle's velocity (an
+impulse; its racket is drawn only) so that the shuttle lands at its target, clears the net by >= 15 cm, and our robot
+can reach the flight from where it stands; an unreachable shot moves towards the centre and becomes gentler.
+Our strokes scatter: the aim is perturbed by a seeded N(0, EXEC_SIGMA[power]) per shot.
+"""
+from __future__ import annotations
+
+import hashlib
+import io
+import json
+import math
+import os
+from collections import deque
+from pathlib import Path
+
+import numpy as np
+
+import mujoco as mj
+
+HERE = Path(__file__).resolve().parent
+SCENE = Path(os.environ.get("RCB_BM_SCENE", HERE / "scene" / "bm_scene.xml"))
+
+CONTROL_DT, SUBSTEPS, PHYS_DT = 0.01, 10, 0.001
+GRAV, V_TERM = 9.81, 6.8
+K_DRAG = GRAV / V_TERM ** 2
+NET_TOP, COURT_X, COURT_Y, POST_X = 1.524, 2.59, 6.70, 3.05 # BWF Law 1.10: net top 1.524 m (at the centre)
+SHORT_SERVICE_Y = 1.98
+R_HEAD, RACKET_GAIN, E_SHUTTLE, OFFCENTRE_LOSS = 0.14, 20.0, 0.15, 0.3
+ARM_VEL = np.array([2.175, 2.175, 2.175, 2.175, 2.61, 2.61, 2.61])
+BASE_VMAX, BASE_AMAX = 6.0, 20.0 # the base moves like a fast badminton player (single and duel; 2026-10-03)
+VEL_LIMIT = np.r_[BASE_VMAX, BASE_VMAX, ARM_VEL]
+KP = np.array([4e4, 4e4, 2400.0, 2400.0, 2400.0, 2400.0, 1000.0, 600.0, 200.0])
+KD = np.array([3e3, 3e3, 100.0, 100.0, 100.0, 100.0, 30.0, 20.0, 6.0])
+JOINTS = ["base_x", "base_y"] + [f"joint{i}" for i in range(1, 8)]
+HOME = np.array([0.0, -4.0]) # the robot's base between shots
+PED_H = 1.0 # link0 height on the pedestal; shoulder at PED_H + 0.333
+Q0_ARM = np.array([0.0, -0.3, 0.0, -1.9, 0.0, 1.9, 0.785]) # ready pose (refined at import by IK, see _ready_pose)
+BASE_LO, BASE_HI = np.array([-3.25, -7.5]), np.array([3.25, -0.5])
+
+WIN_POINTS = 5 # first to 5; from 4-4 a two-point lead is needed; the first to CAP_POINTS wins
+CAP_POINTS = 7
+MAX_HITS = 300 # cap on hits in the match (both sides): the match ends after that point; the leader wins,
+MAX_POINTS = 40 # if level the winner of the last point (no draws; the same in single and duel)
+READY_STEPS = 100 # 1.0 s between points
+LEG_STEPS = 600 # safety: 6 s after a serve or hit without a decision -> the player to hit loses
+CAM_EVERY = 2 # 50 Hz camera snapshots
+SWING_AFTER = 20 # first decision point: 0.2 s after the shuttle was played (serve or opponent's hit)
+ADJUST_BEFORE = 30 # second decision point: 0.3 s before the planned contact
+OPP_HOME = np.array([0.0, 3.8])
+OPP_Z = (0.10, 2.70) # the opponent's hitting envelope (height)
+SPEED_FREE = 12.0
+PRESSURE_WEAK, PRESSURE_PASSIVE = 0.75, 0.35
+EXEC_SIGMA = {"soft": 0.12, "normal": 0.20, "hard": 0.30}
+POWER = ("soft", "normal", "hard")
+AIM_DEFAULT = (0.0, 4.0)
+
+LEVELS = { # defence: reaction, chase / recovery speed, reach, too-fast threshold; attack: width, pace (smash speed);
+ # serve: share of high serves, |x| range of the serve's target, depth range of a short serve (receiver frame)
+ 1: dict(reaction_s=0.30, chase=2.2, recover=1.6, reach=0.95, max_speed=24.0, width=1.4, pace=24.0, seed=101,
+ serve_high=0.7, serve_x=(0.4, 1.6), serve_short_y=(-2.5, -2.8)),
+ 2: dict(reaction_s=0.25, chase=2.6, recover=1.9, reach=1.05, max_speed=28.0, width=1.9, pace=30.0, seed=202,
+ serve_high=0.5, serve_x=(0.25, 2.2), serve_short_y=(-2.2, -2.5)),
+}
+
+# The players' serve (BWF Laws 9-10; 2026-10-07). Before every serve both robots are put in their service courts at
+# their spot (serve_spot: x = +SPOT_X in the right court, -SPOT_X in the left one; own frame), at rest in the ready
+# pose; the spot is the robot's home (the ready target's base goal) for the whole point. READY_STEPS after play
+# resumes the receiver is ready (Law 9.4) and the server may toss the shuttle (docs/conventions/racket_serve_zh.md):
+# it appears at a point the server chooses, within TOSS_REACH (horizontally) of its base and TOSS_Z high, and is
+# released from rest (height 0) or projected straight up to rise at most TOSS_H_MAX (the robot has no free hand: the
+# toss stands for the server's hand letting go of the shuttle, Law 9.1.5: no spin), within SERVE_WINDOW_STEPS (else a
+# fault: undue delay, Law 9.1.1). Then the server must hit it (a miss is a fault, Law 9.1.8) below SERVE_MAX_Z (Law 9.1.6) and upwards (Law
+# 9.1), over the net into the receiver's diagonal service court (Laws 9.1, 10.1). Both bases stay within BASE_TOL of
+# their spots until the serve is delivered (Law 9.1.4; both moving: a let, Law 14.2.2). The rally winner serves next
+# (Law 10.3).
+SPOT_X, SPOT_Y = 0.3, -4.0
+TOSS_REACH, TOSS_Z, TOSS_H_MAX = 1.0, (0.5, 1.8), 0.5
+SERVE_MAX_Z = 1.15
+SERVE_WINDOW_STEPS = 300 # 3 s after the receiver is ready
+BASE_TOL = 0.05
+MAX_DELAY_FAULTS = 3 # the third undue-delay fault of a player disqualifies it (Laws 16.6.1, 16.7)
+
+
+def serve_spot(right: bool) -> np.ndarray:
+ """Where both robots stand before a serve (own frame): in their right service courts when the server's score is
+ even (BWF 10.1), else in their left ones."""
+ return np.array([SPOT_X if right else -SPOT_X, SPOT_Y])
+
+
+def toss_problem(p, h, base) -> str | None:
+ """Why a toss (point p in the own frame, height h) is not allowed for a robot whose base is at `base`, or None."""
+ p = np.asarray(p, float)
+ if p.shape != (3,) or not np.all(np.isfinite(p)):
+ return "the toss point must be 3 finite numbers"
+ if not (isinstance(h, (int, float)) and math.isfinite(h) and 0.0 <= h <= TOSS_H_MAX):
+ return f"the toss height must be 0-{TOSS_H_MAX} m (0: released from rest)"
+ if not TOSS_Z[0] <= p[2] <= TOSS_Z[1]:
+ return f"the toss point must be {TOSS_Z[0]}-{TOSS_Z[1]} m high"
+ d = float(np.hypot(p[0] - base[0], p[1] - base[1]))
+ if d > TOSS_REACH:
+ return f"the toss point must be within {TOSS_REACH} m (horizontally) of your base; it is {d:.2f} m away"
+ if p[1] > -0.5:
+ return "the toss point must be on your half, y <= -0.5"
+ return None
+
+
+def toss_vz(h) -> float:
+ """The upward speed that makes a shuttle rise h metres under gravity and quadratic drag (exact for the continuous
+ model: h = V_TERM^2 / (2 g) ln(1 + vz^2 / V_TERM^2))."""
+ return float(V_TERM * math.sqrt(math.expm1(2.0 * GRAV * float(h) / V_TERM ** 2)))
+
+# launch-angle families (deg) of the opponent's shots, tried in order; max launch speed (m/s)
+SHOT_THETAS = {"clear": (50, 45, 55, 40, 60, 35), "lift": (58, 52, 64, 46), "drop": (5, 0, 10, 15, -5, 20, 25, 30),
+ "drive": (6, 2, 10, 14, -2, 18), "smash": (-14, -10, -18, -6, -22, -2), "push": (28, 32, 24, 36, 20),
+ "serve_high": (55, 50, 60, 45), "serve_short": (22, 26, 18, 30, 34)}
+SHOT_VMAX = {"clear": 60.0, "lift": 50.0, "drop": 25.0, "drive": 34.0, "smash": 45.0, "push": 34.0,
+ "serve_high": 55.0, "serve_short": 14.0}
+OUR_THETAS = (-30, -22, -15, -9, -4, 0, 4, 8, 13, 19, 26, 34, 43, 52, 61)
+OUR_VMAX = 55.0
+
+
+# ---------------------------------------------------------------------- shuttle physics
+def sh_step(p, v):
+ """One 1 ms step of the shuttle (python floats)."""
+ vx, vy, vz = v
+ c = K_DRAG * math.sqrt(vx * vx + vy * vy + vz * vz) * PHYS_DT
+ vx -= c * vx
+ vy -= c * vy
+ vz -= GRAV * PHYS_DT + c * vz
+ return (p[0] + vx * PHYS_DT, p[1] + vy * PHYS_DT, p[2] + vz * PHYS_DT), (vx, vy, vz)
+
+
+def predict(p, v, n_max=6000):
+ """Shuttle-only flight from (p, v): arrays P, V (N, 3) after 1..N steps of 1 ms, until the floor (inclusive) or
+ the net (the step at which it crossed y = 0 below the net top, inclusive)."""
+ p = tuple(float(x) for x in p); v = tuple(float(x) for x in v)
+ P, V = [], []
+ for _ in range(n_max):
+ p1, v1 = sh_step(p, v)
+ if (p[1] > 0) != (p1[1] > 0) and p[1] != p1[1]:
+ f = p[1] / (p[1] - p1[1])
+ z = p[2] + f * (p1[2] - p[2]); x = p[0] + f * (p1[0] - p[0])
+ if z < NET_TOP and abs(x) <= POST_X:
+ P.append(p1); V.append(v1)
+ break
+ P.append(p1); V.append(v1)
+ p, v = p1, v1
+ if p[2] <= 0.0:
+ break
+ return np.array(P), np.array(V)
+
+
+def flight_table(p0, heading, thetas_deg, speeds, dt=0.002, t_max=4.0):
+ """Vectorised planar flights from p0 along `heading` (unit xy) for every (theta, speed): horizontal range at the
+ floor, height when crossing the net plane y = 0 (nan if it never does), flight time. Solver only (2 ms steps);
+ the real flight is the 1 ms 3-D integration."""
+ th = np.deg2rad(np.asarray(thetas_deg, float))[:, None]
+ sp = np.asarray(speeds, float)[None, :]
+ vh = (np.cos(th) * sp).ravel(); vz = (np.sin(th) * sp).ravel()
+ n = vh.size
+ h = np.zeros(n); z = np.full(n, float(p0[2]))
+ s_net = (-p0[1] / heading[1]) if abs(heading[1]) > 1e-9 else np.inf
+ rng_ = np.full(n, np.nan); znet = np.full(n, np.nan); tf = np.full(n, np.nan)
+ alive = np.ones(n, bool)
+ for i in range(int(t_max / dt)):
+ s = np.sqrt(vh * vh + vz * vz)
+ c = K_DRAG * s * dt
+ vh = vh - c * vh; vz = vz - GRAV * dt - c * vz
+ h1 = h + vh * dt; z1 = z + vz * dt
+ cross = alive & (h < s_net) & (h1 >= s_net)
+ if cross.any():
+ f = (s_net - h[cross]) / (h1[cross] - h[cross])
+ znet[cross] = z[cross] + f * (z1[cross] - z[cross])
+ land = alive & (z1 <= 0.0)
+ if land.any():
+ f = z[land] / (z[land] - z1[land])
+ rng_[land] = h[land] + f * (h1[land] - h[land]); tf[land] = (i + f) * dt
+ alive &= ~land
+ h, z = h1, z1
+ if not alive.any():
+ break
+ shp = (len(thetas_deg), len(speeds))
+ return rng_.reshape(shp), znet.reshape(shp), tf.reshape(shp)
+
+
+def solve_shots(p0, target, thetas, vmax, net_margin=0.15, vmin=2.0):
+ """Launch velocities from p0 that land at `target` (xy) and clear the net top by >= net_margin: one per launch
+ angle that works (in the order given). Returns [(theta, speed, v (3,), flight time)]."""
+ p0 = np.asarray(p0, float); target = np.asarray(target, float)
+ d = target - p0[:2]; H = float(np.linalg.norm(d))
+ if H < 1e-6:
+ return []
+ hd = d / H
+ speeds = np.linspace(vmin, vmax, 90)
+ R, ZN, TF = flight_table(p0, hd, thetas, speeds)
+ out = []
+ for i, th in enumerate(thetas):
+ r = R[i]; ok = np.isfinite(r)
+ if not ok.any():
+ continue
+ r_ok = r[ok]; s_ok = speeds[ok]
+ j = np.nonzero(r_ok >= H)[0]
+ if len(j) == 0:
+ continue
+ j = j[0]
+ if j == 0:
+ v = s_ok[0]; f = 0.0; j0 = 0
+ else:
+ f = (H - r_ok[j - 1]) / (r_ok[j] - r_ok[j - 1]); v = s_ok[j - 1] + f * (s_ok[j] - s_ok[j - 1]); j0 = j - 1
+ zn = ZN[i][ok]; tf = TF[i][ok]
+ crosses = (p0[1] > 0) != (target[1] > 0)
+ if crosses:
+ z_net = zn[j0] + f * (zn[min(j, len(zn) - 1)] - zn[j0]) if j > 0 else zn[0]
+ if not np.isfinite(z_net) or z_net < NET_TOP + net_margin:
+ continue
+ t_f = tf[j0] + f * (tf[min(j, len(tf) - 1)] - tf[j0]) if j > 0 else tf[0]
+ thr = math.radians(th)
+ vel = np.array([hd[0] * v * math.cos(thr), hd[1] * v * math.cos(thr), v * math.sin(thr)])
+ out.append((th, float(v), vel, float(t_f)))
+ return out
+
+
+def in_service_court(x, y, right):
+ """The receiver's service court in the receiver's frame (receiver on y < 0, facing +y; singles: between the short
+ service line and the back line; its right court is x >= 0). BWF Laws 9.1 / 10.1: the serve must land in the court
+ diagonally opposite, the receiver's right court when the server's score is even (lines are in)."""
+ return (0.0 <= x <= COURT_X if right else -COURT_X <= x <= 0.0) and -COURT_Y <= y <= -SHORT_SERVICE_Y
+
+
+def serve_plan(seed, n, server_score, base, reachable, lv=None):
+ """The scripted opponent's serve (type, hitting point p0, velocity) in the RECEIVER's frame, from the server's
+ service court into the receiver's diagonal service court (BWF 10.1.1: from the right court when the server's score
+ is even), hit at 1.05 m (below 1.15 m, Law 9.1.6) and upwards (Law 9.1). The server faces -y, so its right court is
+ x < 0. seed: the rng seed list prefix; n: the point's serial number (lets included, for the seeded choice);
+ reachable(p0, v, base): the receiver can meet the flight; lv: the level (share of high serves, target range)."""
+ lv = lv or LEVELS[1]
+ rng = np.random.default_rng(list(seed) + [11, n])
+ u = rng.uniform(-1, 1, 4)
+ right = server_score % 2 == 0
+ sx = -0.45 if right else 0.45 # the server's right court is at x < 0 in the receiver's frame
+ p0 = np.array([sx, 2.3, 1.05])
+ high = (u[0] + 1.0) / 2.0 < lv["serve_high"]
+ typ = "serve_high" if high else "serve_short"
+ side = 1.0 if right else -1.0 # the receiver's diagonal court: x > 0 when the server serves from its right
+ x0, x1 = lv["serve_x"]
+ tx = side * (x0 + (x1 - x0) * (u[1] + 1.0) / 2.0)
+ y0, y1 = lv["serve_short_y"]
+ ty = -5.9 - 0.4 * abs(u[2]) if high else y0 + (y1 - y0) * abs(u[2])
+ v = None
+ for frac in (1.0, 0.6, 0.3):
+ c = solve_shots(p0, (side * max(0.25, abs(tx) * frac), ty), SHOT_THETAS[typ], SHOT_VMAX[typ])
+ c = [x for x in c if reachable(p0, x[2], base)]
+ if c:
+ v = c[0][2]; break
+ if v is None:
+ v = solve_shots(p0, (side * 0.6, -5.5), SHOT_THETAS["serve_high"], 60.0)[0][2]
+ return typ, p0, np.asarray(v, float), right
+
+
+def in_court(x, y, side):
+ """side +1: the opponent's court, -1: ours (lines are in)."""
+ return abs(x) <= COURT_X and (0.0 < side * y <= COURT_Y)
+
+
+def base_goto(b, v, goal):
+ """One control step of the base's go-to generator (bounded speed and acceleration): new (target, velocity)."""
+ e = goal - b; dist = float(np.hypot(e[0], e[1]))
+ sp = float(np.hypot(v[0], v[1]))
+ if dist < 0.004 and sp < 0.15:
+ return goal.copy(), np.zeros(2)
+ vdes = e / max(dist, 1e-9) * min(BASE_VMAX * 0.98, math.sqrt(2 * BASE_AMAX * 0.85 * dist))
+ dv = vdes - v; ndv = float(np.hypot(dv[0], dv[1])); lim = BASE_AMAX * CONTROL_DT
+ if ndv > lim:
+ dv = dv * (lim / ndv)
+ v = v + dv
+ nv = float(np.hypot(v[0], v[1]))
+ if nv > BASE_VMAX * 0.98:
+ v = v * (BASE_VMAX * 0.98 / nv)
+ return np.clip(b + v * CONTROL_DT, BASE_LO, BASE_HI), v
+
+
+def base_time(dist):
+ """Approximate time for the base to travel `dist` from rest to rest."""
+ a, vm = BASE_AMAX * 0.85, BASE_VMAX * 0.98
+ return 2 * math.sqrt(dist / a) if dist < vm * vm / a else dist / vm + vm / a
+
+
+SHOULDER_Z = PED_H + 0.333
+
+
+def stance(p):
+ """Where the base should stand to meet the shuttle at p with a forehand: the contact to the right of and in front
+ of the base, closer in for high and low contacts."""
+ dz = float(p[2]) - SHOULDER_Z
+ r = max(0.30, 0.95 - 0.35 * abs(dz))
+ off = np.array([0.62 * r, 0.62 * r])
+ return np.clip(np.asarray(p[:2], float) - off, BASE_LO, BASE_HI)
+
+
+def quat_z_to(v):
+ """Quaternion rotating the local z axis onto the direction v."""
+ v = np.asarray(v, float); n = np.linalg.norm(v)
+ if n < 1e-9:
+ return np.array([1.0, 0, 0, 0])
+ v = v / n; z = np.array([0.0, 0, 1])
+ c = float(z @ v)
+ if c < -0.999999:
+ return np.array([0.0, 1, 0, 0])
+ ax = np.cross(z, v); s = math.sqrt((1 + c) * 2)
+ return np.array([s / 2, ax[0] / s, ax[1] / s, ax[2] / s])
+
+
+def hermite(q0, v0, q1, v1, T, n):
+ t = np.arange(1, n + 1) * (T / n)
+ s = t / T
+ h00 = 2 * s**3 - 3 * s**2 + 1; h10 = s**3 - 2 * s**2 + s; h01 = -2 * s**3 + 3 * s**2; h11 = s**3 - s**2
+ return h00[:, None] * q0 + h10[:, None] * T * v0 + h01[:, None] * q1 + h11[:, None] * T * v1
+
+
+# ---------------------------------------------------------------------- robot + shuttle physics
+class Phys:
+ """MuJoCo robot (mobile base + Franka + racket), the shuttle integrator and the racket-shuttle contact model."""
+
+ def __init__(self):
+ self.m = mj.MjModel.from_xml_path(str(SCENE))
+ self.d = mj.MjData(self.m)
+ m = self.m
+ jid = [mj.mj_name2id(m, mj.mjtObj.mjOBJ_JOINT, j) for j in JOINTS]
+ self.qa = np.array([m.jnt_qposadr[j] for j in jid]); self.va = np.array([m.jnt_dofadr[j] for j in jid])
+ self.lo = m.jnt_range[jid, 0].copy(); self.hi = m.jnt_range[jid, 1].copy()
+ self.site = mj.mj_name2id(m, mj.mjtObj.mjOBJ_SITE, "racket_center")
+ self.kin = mj.MjData(m)
+ self.steps_total = 0
+
+ def reset(self, q9):
+ m, d = self.m, self.d
+ mj.mj_resetData(m, d)
+ d.qpos[self.qa] = q9
+ mj.mj_forward(m, d)
+ self.target = np.asarray(q9, float).copy()
+ self.k = 0
+ self._actions: list[np.ndarray] = []
+ self.sh_p, self.sh_v, self.sh_live = (0.0, 3.0, 1.0), (0.0, 0.0, 0.0), False
+ self.hit_enabled = False
+ self.events: list[dict] = []
+ self._prev = None
+
+ def copy_from(self, o: "Phys"):
+ d = self.d
+ mj.mj_resetData(self.m, d)
+ d.qpos[:] = o.d.qpos; d.qvel[:] = o.d.qvel; d.qacc_warmstart[:] = o.d.qacc_warmstart; d.time = o.d.time
+ d.ctrl[:] = o.d.ctrl
+ mj.mj_forward(self.m, d)
+ self.target = o.target.copy(); self.k = o.k; self._actions = []
+ self.sh_p, self.sh_v, self.sh_live, self.hit_enabled = o.sh_p, o.sh_v, o.sh_live, o.hit_enabled
+ self.events = []
+ self._prev = None if o._prev is None else (o._prev[0].copy(), o._prev[1].copy(), o._prev[2])
+
+ def check_target(self, q):
+ if q.shape != (9,) or not np.all(np.isfinite(q)):
+ raise ValueError(f"action must be 9 finite joint targets, got {q.shape}")
+ if (q < self.lo - 1e-9).any() or (q > self.hi + 1e-9).any():
+ raise ValueError(f"step {self.k}: joint target outside range: {q}")
+ dq = np.abs(q - self.target)
+ lim = VEL_LIMIT * CONTROL_DT * (1 + 1e-6) + 1e-12
+ if (dq > lim).any():
+ j = int(np.argmax(dq / lim))
+ raise ValueError(f"step {self.k}: joint {JOINTS[j]} target moved {dq[j]:.5f} in one control step "
+ f"(limit {VEL_LIMIT[j] * CONTROL_DT:.5f})")
+
+ def step(self, q):
+ q = np.asarray(q, dtype=np.float64).reshape(-1)
+ self.check_target(q)
+ m, d = self.m, self.d
+ q_prev = self.target
+ qd_des = (q - q_prev) / CONTROL_DT
+ lo, hi = m.actuator_ctrlrange[:, 0], m.actuator_ctrlrange[:, 1]
+ for j in range(1, SUBSTEPS + 1):
+ q_des = q_prev + (q - q_prev) * (j / SUBSTEPS)
+ tau = KP * (q_des - d.qpos[self.qa]) + KD * (qd_des - d.qvel[self.va]) + d.qfrc_bias[self.va]
+ d.ctrl[:] = np.clip(tau, lo, hi)
+ mj.mj_step(m, d)
+ # site pose now = the pose at the start of this step (time t_n), the same time as self.sh_p
+ c = d.site_xpos[self.site].copy(); n = d.site_xmat[self.site].reshape(3, 3)[:, 0].copy()
+ if self.sh_live:
+ if self.hit_enabled and self._prev is not None and self.sh_p[1] < 0: # only on our half (BWF 13.4.2)
+ self._check_hit(c, n)
+ self._prev = (c, n, self.sh_p)
+ self._advance_shuttle()
+ else:
+ self._prev = (c, n, self.sh_p)
+ self.target = q.copy()
+ self._actions.append(q.copy())
+ self.k += 1
+ self.steps_total += SUBSTEPS
+
+ def actions(self) -> np.ndarray:
+ """(N, 9) joint targets applied since the reset."""
+ return np.array(self._actions, dtype=np.float64).reshape(-1, 9)
+
+ def _advance_shuttle(self):
+ p, v = self.sh_p, self.sh_v
+ p1, v1 = sh_step(p, v)
+ if (p[1] > 0) != (p1[1] > 0) and p[1] != p1[1]:
+ f = p[1] / (p[1] - p1[1])
+ z = p[2] + f * (p1[2] - p[2]); x = p[0] + f * (p1[0] - p[0])
+ self.events.append({"kind": "cross", "k": self.k, "x": round(x, 4), "z": round(z, 4),
+ "to": "opp" if p1[1] > 0 else "own"})
+ if z < NET_TOP and abs(x) <= POST_X:
+ self.sh_p = (x, 0.0, z); self.sh_v = (0.0, 0.0, 0.0); self.sh_live = False
+ self.events.append({"kind": "net", "k": self.k, "x": round(x, 4), "z": round(z, 4)})
+ return
+ if p1[2] <= 0.0:
+ f = p[2] / (p[2] - p1[2]) if p[2] != p1[2] else 1.0
+ x = p[0] + f * (p1[0] - p[0]); y = p[1] + f * (p1[1] - p[1])
+ self.sh_p = (x, y, 0.0); self.sh_v = (0.0, 0.0, 0.0); self.sh_live = False
+ self.events.append({"kind": "land", "k": self.k, "x": round(x, 4), "y": round(y, 4)})
+ return
+ self.sh_p, self.sh_v = p1, v1
+
+ def _check_hit(self, c, n):
+ cp, npv, sp = self._prev
+ sp = np.array(sp); sh = np.array(self.sh_p)
+ s0 = float((sp - cp) @ npv); s1 = float((sh - c) @ n)
+ if s0 * s1 > 0 or (s0 == 0 and s1 == 0):
+ return
+ f = s0 / (s0 - s1) if s0 != s1 else 0.0
+ pc = cp + f * (c - cp); ps = sp + f * (sh - sp)
+ r = ps - pc
+ off = float(np.linalg.norm(r - (r @ n) * n))
+ if off > R_HEAD:
+ return
+ vr = (c - cp) / PHYS_DT; vs = np.array(self.sh_v)
+ n_out = n if float((vr - vs) @ n) >= 0 else -n
+ u = float(vr @ n_out); vin = float(vs @ n_out)
+ spd = RACKET_GAIN * max(u, 0.0) * (1 - OFFCENTRE_LOSS * (off / R_HEAD) ** 2) + E_SHUTTLE * max(0.0, -vin)
+ v_out = n_out * spd
+ p_new = ps + n_out * 0.002
+ self.sh_p = tuple(float(x) for x in p_new); self.sh_v = tuple(float(x) for x in v_out)
+ self.hit_enabled = False
+ self.events.append({"kind": "hit", "k": self.k, "pos": [round(float(x), 4) for x in ps],
+ "offcentre": round(off, 4), "racket_speed": round(u, 3), "speed": round(spd, 3),
+ "v_out": [round(float(x), 3) for x in v_out]})
+
+ # kinematics (scratch data; never stepped)
+ def kin_set(self, q9):
+ self.kin.qpos[:] = self.d.qpos
+ self.kin.qpos[self.qa] = q9
+ mj.mj_kinematics(self.m, self.kin)
+ mj.mj_comPos(self.m, self.kin)
+
+ def fk(self, q9):
+ self.kin_set(np.asarray(q9, float))
+ return self.kin.site_xpos[self.site].copy(), self.kin.site_xmat[self.site].reshape(3, 3).copy()
+
+ def jac(self, q9):
+ """(6, 7) racket-centre Jacobian w.r.t. the arm joints."""
+ self.kin_set(np.asarray(q9, float))
+ jp = np.zeros((3, self.m.nv)); jr = np.zeros((3, self.m.nv))
+ mj.mj_jacSite(self.m, self.kin, jp, jr, self.site)
+ return np.vstack([jp[:, self.va[2:]], jr[:, self.va[2:]]])
+
+ def racket_state(self):
+ d = self.d
+ jp = np.zeros((3, self.m.nv)); jr = np.zeros((3, self.m.nv))
+ mj.mj_jacSite(self.m, d, jp, jr, self.site)
+ return (d.site_xpos[self.site].copy(), d.site_xmat[self.site].reshape(3, 3)[:, 0].copy(), jp @ d.qvel)
+
+ def state_sha(self):
+ d = self.d
+ h = hashlib.sha256()
+ for a in (d.qpos, d.qvel, d.qacc_warmstart, d.ctrl, np.array([d.time]), np.array(self.sh_p + self.sh_v)):
+ h.update(np.ascontiguousarray(a, dtype=np.float64).tobytes())
+ h.update(json.dumps(self.events, sort_keys=True).encode())
+ return h.hexdigest()
+
+
+def ik(ph: Phys, pos, normal, base_xy, q_init, iters=150, tol=1e-4):
+ """Damped least squares over the 7 arm joints (base fixed at base_xy): racket centre at pos, face normal along
+ `normal` (rotation about the normal free)."""
+ q = np.r_[base_xy, q_init].astype(float)
+ n_t = np.asarray(normal, float); n_t = n_t / np.linalg.norm(n_t)
+ lo, hi = ph.lo[2:] + 1e-4, ph.hi[2:] - 1e-4
+ err = np.inf
+ for _ in range(iters):
+ p, R = ph.fk(q)
+ n = R[:, 0]
+ e = np.r_[pos - p, np.cross(n, n_t)]
+ err = float(np.linalg.norm(e[:3]) + np.arcsin(min(1.0, np.linalg.norm(e[3:]))))
+ if n @ n_t < 0:
+ e[3:] = np.cross(n, n_t) + 0.5 * np.cross(n, R[:, 1]); err += np.pi / 2
+ if err < tol:
+ break
+ J = ph.jac(q)
+ dq = J.T @ np.linalg.solve(J @ J.T + 1e-3 * np.eye(6), e)
+ nd = float(np.max(np.abs(dq)))
+ if nd > 0.25:
+ dq *= 0.25 / nd
+ q[2:] = np.clip(q[2:] + dq, lo, hi)
+ return q[2:].copy(), err
+
+
+# fixed extra IK start poses (offsets from the ready pose Q0_ARM): arm lowered / raised, turned left / right, wrist
+# turned. Deterministic: the same list every run, so the plan is a pure function of the state (replay is bit-exact).
+IK_SEED_OFFSETS = np.array([
+ [0.0, 0.5, 0.0, 0.6, 0.0, -0.4, 0.0],
+ [0.0, -0.4, 0.0, -0.3, 0.0, 0.4, 0.0],
+ [0.6, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [-0.6, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.3, 0.0, 0.3, 1.2, 0.0, 0.0],
+ [0.0, 0.3, 0.0, 0.3, -1.2, 0.0, 0.0],
+])
+IK_OK = 2e-3 # an IK solution with a residual below this counts as reaching the pose
+
+
+def ik_multi(ph: Phys, pos, normal, base_xy, seeds, q_now):
+ """Deterministic multi-start IK for both string faces: starts from `seeds` (the caller's seed, the current joint
+ targets, the ready pose) and the fixed IK_SEED_OFFSETS poses. Of the solutions that reach the pose
+ (residual < IK_OK) it takes the one nearest to the current joint state in joint-speed terms (the least time at the
+ joint speed limits, max_j |q_j - q_now_j| / ARM_VEL_j), so the swing does not wander into a far, flipped
+ configuration; if none reaches it, the lowest residual. Returns (q, residual, face sign, fallbacks): up
+ to 2 more distinct solutions, next-nearest first, for when the nearest one cannot be swung to in time."""
+ n_t = np.asarray(normal, float); n_t = n_t / np.linalg.norm(n_t)
+ q_now = np.asarray(q_now, float)
+ lo, hi = ph.lo[2:] + 1e-3, ph.hi[2:] - 1e-3
+ starts = []
+ for s in list(seeds) + [Q0_ARM + d for d in IK_SEED_OFFSETS]:
+ s = np.clip(np.asarray(s, float), lo, hi)
+ if not any(np.array_equal(s, t) for t in starts):
+ starts.append(s)
+ cands = []
+ for i, sd in enumerate(starts):
+ for sgn in (1.0, -1.0): # the string bed has two faces (the commanded one first)
+ q, r = ik(ph, pos, sgn * n_t, base_xy, sd)
+ cands.append((float(np.max(np.abs(q - q_now) / ARM_VEL)), r, i, sgn, q))
+ good = sorted((c for c in cands if c[1] < IK_OK), key=lambda c: (round(c[0], 9), c[2], -c[3]))
+ if not good:
+ c = min(cands, key=lambda c: (c[1], c[2]))
+ return c[4], c[1], c[3], []
+ alts = [] # the next-nearest distinct solutions (fallbacks), at most 2
+ for c in good[1:]:
+ if len(alts) < 2 and all(np.max(np.abs(c[4] - o[4])) > 0.2 for o in [good[0]] + alts):
+ alts.append(c)
+ return good[0][4], good[0][1], good[0][3], [(c[4], c[1], c[3]) for c in alts]
+
+
+def swing_score(perr, nerr_deg, verr):
+ """How far a rehearsed swing is from the commanded racket state (m-equivalent: 1 cm ~ 1.7 deg ~ 0.5 m/s)."""
+ return float(perr) + 0.006 * float(nerr_deg) + 0.02 * float(verr)
+
+
+DELIVERY_POS_WARN, DELIVERY_ANG_WARN = 0.03, 5.0 # stroke note when the rehearsed delivery is off by more
+
+
+# ---------------------------------------------------------------------- the match
+class Match:
+ """The match. Live: run_to_decision() / shot() / adjust(). Replay: replay(actions)."""
+
+ # decision cameras: (lookat, distance, azimuth, elevation) of MuJoCo free cameras
+ CAMS = (([0.0, -1.0, 2.8], 13.5, 90.0, -6.0), # behind and above the robot's baseline, looking down the court
+ ([0.0, -1.5, 3.0], 14.0, 0.0, -4.0)) # at the side of the court (x < 0), looking along +x
+ VIEW_BACK = (0, 3, 6, 9) # snapshots back from the latest: 0, 60, 120, 180 ms
+ TILE = (480, 360)
+
+ def __init__(self, level: int = 1, lv_override: dict | None = None):
+ self.level = int(level)
+ self.lv = dict(LEVELS.get(self.level, LEVELS[1]))
+ if lv_override:
+ self.lv.update(lv_override)
+ if os.environ.get("MATCH_SEED"): # other instances of the same level: serves + opponent + scatter
+ self.lv["seed"] = int(os.environ["MATCH_SEED"])
+ self.s = Phys()
+ self.s.reset(np.r_[HOME, Q0_ARM])
+ self._twin = None
+ self.score = [0, 0]
+ self.points: list[dict] = []
+ self.legs: list[dict] = []
+ self.results: list[dict] = []
+ self.shots: list[dict] = []
+ self.hist: deque = deque(maxlen=16)
+ self.done = False
+ self.winner = None # 0 you, 1 the opponent (set when the match ends)
+ self.hits = 0 # hits in the match, both sides (the MAX_HITS cap)
+ self.phase = "swing"
+ self.plan, self.plan_j, self._rec = [], 0, {}
+ self._adj_k = None
+ self.n_our_legs = 0
+ self.delay_faults = 0 # your serves not tossed in time (undue delay)
+ self.disqualified = False # MAX_DELAY_FAULTS reached: you lose the match (Law 16.7)
+ self._start_point(hold_from=0)
+
+ @property
+ def k(self) -> int:
+ return self.s.k
+
+ # ------------------------------------------------------------------ points / legs
+ def next_server(self) -> int:
+ """0 (you) or 1 (the opponent): you serve the first point (Law 6: the toss is fixed in this format); then the
+ winner of the last rally serves (Law 10.3); after a let the same player serves again (Law 14.3)."""
+ if not self.points:
+ return 0
+ last = self.points[-1]
+ if last.get("let"):
+ return last["server"]
+ return 0 if last["winner"] == "you" else 1
+
+ def _start_point(self, hold_from: int):
+ self.hist.clear() # camera history (display only): no frames of the previous point in the next views
+ n = len(self.points)
+ server = self.point_server = self.next_server()
+ right = self.score[server] % 2 == 0 # the server's right court when its score is even (Law 10.1)
+ self.home = serve_spot(right) # both robots in their right (left) courts, diagonally (Law 9.1.3)
+ if server == 1:
+ # the opponent serves from its right court when its own score is even (BWF 10.1.1), diagonally to us
+ typ, p0, v, right = serve_plan([self.lv["seed"]], n, self.score[1], self.home, self._reachable, self.lv)
+ sx = float(p0[0])
+ self.leg = {"kind": "serve", "serve": typ, "point": n, "hold_from": hold_from, "server": 1,
+ "launch": hold_from + READY_STEPS, "state": "incoming", "p0": p0.tolist(),
+ "v0": [float(x) for x in v], "service_court_right": right}
+ # the server stands at its serving spot and walks home from the moment it serves
+ self.opp = {"xy0": np.array([sx, 2.7]), "k0": hold_from + READY_STEPS, "txy": OPP_HOME.copy(),
+ "speed": self.lv["recover"]}
+ else:
+ # you serve: READY_STEPS after play resumes the opponent is ready and you may toss the shuttle
+ ready = hold_from + READY_STEPS
+ self.leg = {"kind": "our_serve", "point": n, "hold_from": hold_from, "server": 0, "launch": ready,
+ "ready": ready, "deadline": ready + SERVE_WINDOW_STEPS, "state": "held",
+ "service_court_right": right}
+ # the opponent receives in its diagonal service court (its right court is x < 0 in your frame) and
+ # stands still until the serve is delivered
+ spot = np.array([-0.45 if right else 0.45, OPP_HOME[1]])
+ self.opp = {"xy0": spot, "k0": hold_from, "txy": spot.copy(), "speed": 0.0}
+ p0 = np.r_[self.home + np.array([-0.25, 0.35]), 1.0] # held in the server's (missing) free hand
+ v = np.zeros(3)
+ self.legs.append(self.leg)
+ self._new_leg()
+ self.s.sh_p = tuple(float(x) for x in p0); self.s.sh_v = tuple(float(x) for x in v); self.s.sh_live = False
+ self._go_home()
+
+ def _go_home(self):
+ """Before every serve: the robot at its spot in its service court (its home for the point) in the ready pose,
+ at rest, no command (as in the duel)."""
+ ph = self.s
+ q = np.r_[self.home, Q0_ARM]
+ ph.d.qpos[ph.qa] = q; ph.d.qvel[ph.va] = 0.0
+ mj.mj_forward(ph.m, ph.d)
+ ph.target = q.copy()
+ self.plan, self.plan_j = [], 0
+ self._last_act = None; self._q_hit_active = None
+ self._since_reset = 0
+
+ def toss(self, p, h=0.0):
+ """Your serve: the shuttle appears at p (your frame) now and rises h straight up (0: from rest). Raises
+ ValueError if not allowed."""
+ leg = self.leg
+ if self.done or leg["kind"] != "our_serve":
+ raise ValueError("it is not your serve")
+ if leg["state"] != "held":
+ raise ValueError("the shuttle was already tossed")
+ if self.k < leg["ready"]:
+ raise ValueError(f"the opponent is not ready before step {leg['ready']}")
+ why = toss_problem(p, h, self.s.d.qpos[self.s.qa[:2]])
+ if why:
+ raise ValueError(why)
+ self.s.sh_p = tuple(float(x) for x in p); self.s.sh_v = (0.0, 0.0, toss_vz(h))
+ self.s.sh_live = True; self.s.hit_enabled = True
+ leg["state"] = "falling"; leg["toss_k"] = self.k; leg["launch"] = self.k
+ leg["toss"] = [round(float(x), 4) for x in p]; leg["toss_height"] = float(h)
+
+ def delivered(self) -> bool:
+ """The serve of the current point was delivered (hit, missed or faulted)."""
+ leg = self.leg
+ if leg["kind"] == "our_serve":
+ return leg["state"] not in ("held", "falling")
+ if leg["kind"] == "serve":
+ return self.k >= leg["launch"]
+ return True
+
+ def _new_leg(self):
+ self.s.events.clear()
+ self.s.hit_enabled = False
+ self._opp_plan_k = None
+
+ def in_play(self) -> bool:
+ return self.k >= self.leg["launch"]
+
+ def t_since_launch(self) -> float:
+ return round((self.k - self.leg["launch"]) * CONTROL_DT, 6)
+
+ # ------------------------------------------------------------------ the opponent
+ def opp_xy(self, k=None) -> np.ndarray:
+ k = self.k if k is None else k
+ o = self.opp
+ dt = max(0.0, (k - o["k0"]) * CONTROL_DT)
+ e = o["txy"] - o["xy0"]; dist = float(np.hypot(e[0], e[1]))
+ if dist < 1e-9:
+ return o["xy0"].copy()
+ return o["xy0"] + e / dist * min(dist, o["speed"] * dt)
+
+ def _opp_plan(self):
+ """`reaction_s` after our hit: predict the flight, choose the interception point, start moving."""
+ leg = self.leg
+ P, V = predict(self.s.sh_p, self.s.sh_v)
+ o = self.opp_xy()
+ last = P[-1]
+ if leg["kind"] == "our_serve": # a serve must land in the opponent's diagonal service court
+ lands_in = bool(last[2] <= 1e-9 and in_service_court(-last[0], -last[1], leg["service_court_right"]))
+ else:
+ lands_in = bool(last[2] <= 1e-9 and in_court(last[0], last[1], +1))
+ leg["opp_x_react"] = [round(float(x), 3) for x in o]
+ if not lands_in:
+ leg["opp_leave"] = True
+ return
+ idx = np.arange(9, len(P), 10)
+ j = (idx + 1) // 10
+ Pc, sp = P[idx], np.linalg.norm(V[idx], axis=1)
+ ok = (Pc[:, 1] > 0.3) & (Pc[:, 2] >= OPP_Z[0]) & (Pc[:, 2] <= OPP_Z[1])
+ if not ok.any():
+ leg["opp_leave"] = True
+ leg["opp_miss"] = "the shuttle never came into the opponent's hitting range"
+ return
+ lv = self.lv
+ dist = np.hypot(Pc[:, 0] - o[0], Pc[:, 1] - o[1])
+ t = j * CONTROL_DT
+ pp = np.maximum(0.0, dist - lv["chase"] * t) / lv["reach"]
+ ps = (sp - SPEED_FREE) / (lv["max_speed"] - SPEED_FREE)
+ pr = np.where(ok, np.maximum(pp, ps), np.inf)
+ pmin = float(pr.min())
+ js = int(np.nonzero(pr <= pmin + 0.05)[0][0])
+ leg["opp_hit_k"] = self.k + int(j[js])
+ leg["opp_pressure"] = round(float(pr[js]), 3)
+ leg["opp_gap"] = round(float(max(0.0, dist[js] - lv["chase"] * t[js])), 3)
+ leg["opp_speed_in"] = round(float(sp[js]), 2)
+ self.opp = {"xy0": o, "k0": self.k, "txy": Pc[js, :2].copy(), "speed": lv["chase"]}
+
+ def _opp_hit(self):
+ leg = self.leg
+ p = np.array(self.s.sh_p)
+ pr = leg["opp_pressure"]
+ rec = {"k": self.k, "pos": [round(float(x), 3) for x in p], "opp_xy": [round(float(x), 3) for x in self.opp_xy()],
+ "pressure": pr, "gap": leg.get("opp_gap"), "speed_in": leg.get("opp_speed_in")}
+ leg["opp"] = rec
+ if pr > 1.0:
+ gap = leg.get("opp_gap", 0.0)
+ why = (f"out of reach: the opponent was {gap:.2f} m short of the shuttle (reach {self.lv['reach']:.2f} m)"
+ if gap > self.lv["reach"] else
+ f"too fast: the shuttle arrived at {leg.get('opp_speed_in'):.1f} m/s (it handles up to "
+ f"{self.lv['max_speed']:.0f} m/s)")
+ leg["opp_miss"] = why; rec["missed"] = why
+ return
+ mode = "weak" if pr > PRESSURE_WEAK else ("attack" if pr < PRESSURE_PASSIVE else "normal")
+ rec["mode"] = mode
+ shot, v, target = self._opp_return(p, mode)
+ rec.update(shot=shot, target=[round(float(x), 3) for x in target], speed=round(float(np.linalg.norm(v)), 2))
+ self._close_our_leg(True, f"good: the opponent played it ({mode} return, a {shot})")
+ self.hits += 1
+ self.s.sh_v = tuple(float(x) for x in v)
+ leg["state"] = "done"
+ self.opp = {"xy0": self.opp_xy(), "k0": self.k, "txy": OPP_HOME.copy(), "speed": self.lv["recover"]}
+ self.leg = {"kind": "return", "shot": shot, "point": len(self.points), "launch": self.k, "state": "incoming",
+ "opp_hit_pos": rec["pos"]}
+ self.legs.append(self.leg)
+ self._new_leg()
+ self.s.hit_enabled = True
+
+ def _opp_return(self, p, mode):
+ lv = self.lv
+ rng = np.random.default_rng([lv["seed"], len(self.points), len(self.legs)])
+ u = rng.uniform(-1, 1, 5)
+ side = 1.0 if u[0] >= 0 else -1.0
+ high = p[2] >= 1.9
+ W = lv["width"]
+ if mode == "weak":
+ plan = [("lift", 0.35 * u[0], -3.9 + 0.4 * u[1], 45.0)]
+ elif mode == "attack":
+ if high:
+ plan = [("smash", side * W, -3.3 + 0.5 * u[1], lv["pace"])]
+ elif u[1] > 0:
+ plan = [("drop", side * W, -1.2, 25.0)]
+ else:
+ plan = [("push", side * W, -6.0, 34.0)]
+ else:
+ x = side * W * abs(u[0]) ** 0.5
+ if high and u[3] > 0.5:
+ plan = [("smash", x, -3.6 + 0.4 * u[1], 0.8 * lv["pace"])]
+ elif u[2] < -0.1:
+ plan = [("clear", x, -5.9 + 0.3 * u[1], 60.0)]
+ elif u[2] < 0.5:
+ plan = [("drop", x, -1.7 + 0.3 * u[1], 25.0)]
+ else:
+ plan = [("drive", x, -4.6 + 0.4 * u[1], 30.0)]
+ base = self.s.d.qpos[self.s.qa[:2]].copy()
+ typ, tx, ty, vmax = plan[0]
+ for frac, t2 in ((1.0, typ), (0.6, typ), (0.3, typ), (0.6, "clear"), (0.0, "clear"), (0.0, "lift")):
+ vm = vmax if t2 == typ else SHOT_VMAX[t2]
+ tyy = ty if t2 == typ else (-5.6 if t2 == "clear" else -4.0)
+ for c in solve_shots(p, (tx * frac, tyy), SHOT_THETAS[t2], vm):
+ if self._reachable(p, c[2], base):
+ return t2, c[2], (tx * frac, tyy)
+ c = solve_shots(p, (0.0, -4.0), SHOT_THETAS["lift"] + (70, 40, 30), 60.0)
+ v = c[0][2] if c else np.array([0.0, -8.0, 12.0])
+ return "lift", v, (0.0, -4.0)
+
+ def _reachable(self, p0, v, base) -> bool:
+ """Our robot can meet this flight: a point 0.5-2.5 m high inside our court, >= 0.55 s after the shot, whose
+ stance the base can reach in time (0.45 s kept for the decision and the swing)."""
+ P, _ = predict(p0, v)
+ if len(P) == 0 or P[-1][2] > 1e-9 or not in_court(P[-1][0], P[-1][1], -1):
+ return False
+ idx = np.arange(549, len(P) - 20, 20)
+ for i in idx:
+ q = P[i]
+ if not (0.5 <= q[2] <= 2.5 and q[1] < -0.5):
+ continue
+ st = stance(q)
+ if base_time(float(np.hypot(*(st - base)))) <= (i + 1) * PHYS_DT - 0.45:
+ return True
+ return False
+
+ # ------------------------------------------------------------------ stepping (shared by live and replay)
+ def step(self, q):
+ self.s.step(q)
+ self._since_reset = getattr(self, "_since_reset", 0) + 1
+ leg = self.leg
+ if leg["kind"] == "serve" and leg["state"] == "incoming" and self.k == leg["launch"]:
+ self.s.sh_live = True; self.s.hit_enabled = True
+ self._referee()
+ if self.k % CAM_EVERY == 0:
+ self.hist.append({"k": self.k, "t": self.t_since_launch(), "qpos": self.s.d.qpos.copy(),
+ "sh": self.s.sh_p, "shv": self.s.sh_v, "opp": self.opp_xy().copy()})
+
+ def _referee(self):
+ if self.done:
+ return
+ leg, s = self.leg, self.s
+ kinds = [e["kind"] for e in s.events]
+ if not self.delivered():
+ moved = float(np.hypot(*(s.d.qpos[s.qa[:2]] - self.home)))
+ if moved > BASE_TOL: # Law 9.1.4: both players stand still until the serve
+ who = "serve_fault:moved" if leg["kind"] == "our_serve" else "receive_fault:moved"
+ self._close_our_leg(False, f"{who}: your base moved {moved:.2f} m from its spot before the serve was "
+ "delivered (Law 9.1.4)")
+ self._end_point(1, self.results[-1]["summary"])
+ return
+ if leg["kind"] == "our_serve" and leg["state"] in ("held", "falling"):
+ if leg["state"] == "held":
+ if self.k >= leg["deadline"]:
+ self.delay_faults += 1
+ dq = self.delay_faults >= MAX_DELAY_FAULTS
+ self.disqualified = dq
+ self._close_our_leg(False, f"serve_fault:undue_delay: you did not toss the shuttle within "
+ f"{SERVE_WINDOW_STEPS * CONTROL_DT:.0f} s (undue delay, Law 9.1.1)"
+ + (f"; your {MAX_DELAY_FAULTS}rd undue-delay fault disqualifies you (Law 16.7)"
+ if dq else ""))
+ self._end_point(1, self.results[-1]["summary"])
+ return
+ if "hit" in kinds:
+ e = next(e for e in s.events if e["kind"] == "hit")
+ leg["hit"] = e; self.hits += 1
+ if e["pos"][2] > SERVE_MAX_Z:
+ self._close_our_leg(False, f"serve_fault:too_high: you hit the shuttle {e['pos'][2]:.2f} m high, above "
+ f"{SERVE_MAX_Z} m (Law 9.1.6)")
+ self._end_point(1, self.results[-1]["summary"])
+ elif e["v_out"][2] <= 0.0:
+ self._close_our_leg(False, "serve_fault:not_upwards: the serve did not go upwards from your racket (Law 9.1)")
+ self._end_point(1, self.results[-1]["summary"])
+ else:
+ leg["state"] = "to_opp"; leg["delivered_k"] = self.k
+ self._opp_plan_k = self.k + int(round(self.lv["reaction_s"] / CONTROL_DT))
+ return
+ if "land" in kinds or self.k - leg["launch"] >= LEG_STEPS:
+ self._close_our_leg(False, "serve_fault:missed: you missed the shuttle (Law 9.1.8)")
+ self._end_point(1, self.results[-1]["summary"])
+ return
+ if leg["state"] == "incoming":
+ if "hit" in kinds:
+ e = next(e for e in s.events if e["kind"] == "hit")
+ leg["hit"] = e; leg["state"] = "to_opp"; self.hits += 1
+ self._opp_plan_k = self.k + int(round(self.lv["reaction_s"] / CONTROL_DT))
+ return
+ if "net" in kinds: # never seen: serves and returns are solved over the net
+ e = next(x for x in s.events if x["kind"] == "net")
+ what = "serve_fault:net: the opponent's serve" if leg["kind"] == "serve" else "the opponent's shot"
+ self._close_our_leg(True, f"{what} hit the net (x={e['x']:.2f}, height {e['z']:.2f} m)")
+ self._end_point(0, self.results[-1]["summary"])
+ return
+ if "land" in kinds:
+ e = next(x for x in s.events if x["kind"] == "land")
+ if leg["kind"] == "serve" and not in_service_court(e["x"], e["y"], leg["service_court_right"]):
+ self._close_our_leg(True, f"serve_fault:out: the opponent's serve landed outside your service court "
+ f"(x={e['x']:.2f}, y={e['y']:.2f})")
+ self._end_point(0, self.results[-1]["summary"])
+ elif in_court(e["x"], e["y"], -1):
+ self._close_our_leg(False, f"missed: the shuttle landed in your court at x={e['x']:.2f}, y={e['y']:.2f}")
+ self._end_point(1, self.results[-1]["summary"])
+ else:
+ self._close_our_leg(True, f"the opponent's shot landed out (x={e['x']:.2f}, y={e['y']:.2f})")
+ self._end_point(0, self.results[-1]["summary"])
+ elif self.in_play() and self.k - leg["launch"] >= LEG_STEPS:
+ self._close_our_leg(False, "missed"); self._end_point(1, "missed")
+ return
+ if leg["state"] == "to_opp":
+ serve = leg["kind"] == "our_serve"
+ if "net" in kinds:
+ e = next(x for x in s.events if x["kind"] == "net")
+ what = "serve_fault:net: your serve" if serve else "fault: your shot"
+ self._close_our_leg(False, f"{what} hit the net (x={e['x']:.2f}, height {e['z']:.2f} m)")
+ self._end_point(1, self.results[-1]["summary"])
+ return
+ if "land" in kinds:
+ e = next(x for x in s.events if x["kind"] == "land")
+ if e["y"] < 0:
+ self._close_our_leg(False, f"fault: your shot came down on your own side (x={e['x']:.2f}, y={e['y']:.2f})")
+ self._end_point(1, self.results[-1]["summary"])
+ elif serve and not in_service_court(-e["x"], -e["y"], leg["service_court_right"]):
+ self._close_our_leg(False, f"serve_fault:out: your serve landed outside the opponent's service court "
+ f"at x={e['x']:.2f}, y={e['y']:.2f} (the opponent let it go)")
+ self._end_point(1, self.results[-1]["summary"])
+ elif serve or in_court(e["x"], e["y"], +1):
+ why = leg.get("opp_miss") or "the opponent could not reach it"
+ self._close_our_leg(True, f"winner: landed in at x={e['x']:.2f}, y={e['y']:.2f} ({why})")
+ self._end_point(0, self.results[-1]["summary"])
+ else:
+ self._close_our_leg(False, f"fault: your shot landed out at x={e['x']:.2f}, y={e['y']:.2f} "
+ "(the opponent let it go)")
+ self._end_point(1, self.results[-1]["summary"])
+ return
+ if self._opp_plan_k is not None and self.k == self._opp_plan_k:
+ self._opp_plan()
+ if leg.get("opp_hit_k") == self.k and "opp_miss" not in leg:
+ self._opp_hit()
+ elif self.k - leg["launch"] >= 3 * LEG_STEPS:
+ self._close_our_leg(False, "?"); self._end_point(1, "timeout")
+
+ def _close_our_leg(self, ok, summary):
+ leg = self.leg
+ if leg.get("closed"):
+ return
+ leg["closed"] = True
+ h = leg.get("hit")
+ res = {"leg": self.n_our_legs, "point": len(self.points), "kind": leg["kind"], "returned": bool(ok),
+ "summary": summary, "hit": int(h is not None), "speed_out": None if h is None else h["speed"],
+ "offcentre": None if h is None else h["offcentre"], "step": self.k}
+ self.results.append(res)
+ self.n_our_legs += 1
+
+ def match_over(self) -> bool:
+ """First to WIN_POINTS; from 4-4 a two-point lead is needed; the first to CAP_POINTS wins."""
+ hi, lo = max(self.score), min(self.score)
+ return (hi >= WIN_POINTS and hi - lo >= 2) or hi >= CAP_POINTS
+
+ def _end_point(self, winner, how: str):
+ """winner 0 (you), 1 (the opponent) or None (a let: the point is replayed)."""
+ if winner is not None:
+ self.score[winner] += 1
+ self.points.append({"point": len(self.points), "winner": None if winner is None else
+ ("you" if winner == 0 else "opponent"), "how": how, "score": list(self.score),
+ "step": self.k, "let": winner is None, "server": self.point_server})
+ self.leg["state"] = "done"
+ if self.disqualified:
+ self.points[-1]["disqualified"] = "you"
+ self.winner = 1
+ self.done = True
+ return
+ if self.match_over():
+ self.winner = 0 if self.score[0] > self.score[1] else 1
+ self.done = True
+ return
+ if getattr(self, "hits", 0) >= MAX_HITS or len(self.points) >= MAX_POINTS:
+ # the cap: the leader wins; if level, the winner of the last point (no draws)
+ last = next((p["winner"] for p in reversed(self.points) if p["winner"]), "opponent")
+ self.winner = (0 if self.score[0] > self.score[1] else 1 if self.score[1] > self.score[0]
+ else 0 if last == "you" else 1)
+ self.points[-1]["cap"] = True
+ self.done = True
+ return
+ self._start_point(hold_from=self.k)
+
+ def replay(self, actions) -> None:
+ for q in actions:
+ self.step(q)
+
+ # ------------------------------------------------------------------ live control
+ def _target_vel(self):
+ a = self.s._actions
+ return (a[-1] - a[-2]) / CONTROL_DT if len(a) >= 2 and getattr(self, "_since_reset", 2) >= 2 else np.zeros(9)
+
+ def _ready_target(self):
+ """Service-driven recovery: the arm back to the ready pose (60 % of its speed limits), the base to its home
+ (the point's spot in its service court, serve_spot)."""
+ tgt = self.s.target
+ lim = ARM_VEL * CONTROL_DT * 0.6
+ arm = tgt[2:] + np.clip(Q0_ARM - tgt[2:], -lim, lim)
+ b, _ = base_goto(tgt[:2], self._target_vel()[:2], self.home)
+ return np.r_[b, arm]
+
+ def _arm_target(self):
+ if self.plan_j < len(self.plan):
+ q = self.plan[self.plan_j]; self.plan_j += 1
+ return q
+ return self._ready_target()
+
+ def decision_due(self) -> bool:
+ leg = self.leg
+ if self.done or leg["state"] != "incoming" or not self.in_play():
+ return False
+ if any(e["kind"] == "hit" for e in self.s.events):
+ return False
+ if self.phase == "swing":
+ return self.k - leg["launch"] >= SWING_AFTER
+ return self._adj_k is not None and self.k >= self._adj_k
+
+ def run_to_decision(self) -> None:
+ self.phase = "swing"
+ while not self.done:
+ if self.decision_due():
+ return
+ self.step(self._arm_target())
+
+ def shot(self, decision: dict, delay_steps: int) -> dict:
+ leg_i = self.n_our_legs
+ rec = {"leg": leg_i, "decision": decision, "delay_steps": int(delay_steps), "k_decision": self.k}
+ for _ in range(delay_steps):
+ if self.leg["state"] != "incoming" or self.done:
+ break
+ self.step(self._arm_target())
+ rec["k_exec"] = self.k
+ self._adj_k = None
+ if decision.get("type") == "swing" and self.leg["state"] == "incoming" and not self.done:
+ self._ik_seed = None
+ if "normal" in decision:
+ self.plan, info = self.plan_racket(float(decision["t"]), decision["pos"], decision["normal"],
+ decision["vel"])
+ else:
+ self.plan, info = self.plan_stroke(float(decision["t"]), np.asarray(decision["pos"], float),
+ np.asarray(decision.get("aim", AIM_DEFAULT), float),
+ decision.get("power", "normal"))
+ self.plan_j = 0
+ rec.update(info)
+ if self.plan and info.get("k_hit") is not None and info["k_hit"] - ADJUST_BEFORE >= self.k + 5:
+ self._adj_k = info["k_hit"] - ADJUST_BEFORE
+ self._rec = rec
+ if decision.get("type") == "swing" and self._adj_k is not None:
+ self.phase = "adjust"
+ while not self.done and self.n_our_legs == leg_i:
+ if self.decision_due():
+ return {"phase": "adjust", **{k: rec[k] for k in rec if k != "decision"}}
+ self.step(self._arm_target())
+ return self._after_leg(rec, leg_i)
+
+ def adjust(self, decision: dict, delay_steps: int) -> dict:
+ rec, leg_i = self._rec, self.n_our_legs
+ rec["adjust"] = decision
+ rec["adjust_delay_steps"] = int(delay_steps)
+ for _ in range(delay_steps):
+ if self.n_our_legs != leg_i or self.done:
+ break
+ self.step(self._arm_target())
+ if decision.get("type") == "adjust" and self.n_our_legs == leg_i and not self.done \
+ and self.leg["state"] == "incoming":
+ self._ik_seed = rec.get("_q_hit")
+ if "normal" in decision:
+ plan, info = self.plan_racket(float(decision["t"]), decision["pos"], decision["normal"], decision["vel"])
+ else:
+ plan, info = self.plan_stroke(float(decision["t"]), np.asarray(decision["pos"], float),
+ np.asarray(decision.get("aim", rec.get("aim", AIM_DEFAULT)), float),
+ decision.get("power", rec.get("power", "normal")))
+ q_hit = info.pop("_q_hit", None)
+ rec["adjust_info"] = info
+ if plan:
+ rec["_q_hit"] = q_hit
+ self.plan, self.plan_j = plan, 0
+ return self._after_leg(rec, leg_i)
+
+ # ------------------------------------------------------------------ real-time protocol (no decision points)
+ def rt_advance(self, n_steps: int):
+ """Run up to n_steps control steps with the current command (the planned stroke, then the return to ready);
+ stops early when a point ends (the command is then dropped). Returns (steps run, points, our results)."""
+ n0, r0, n = len(self.points), len(self.results), 0
+ while n < n_steps and not self.done and len(self.points) == n0:
+ self.step(self._arm_target()); n += 1
+ if len(self.points) > n0:
+ self.plan, self.plan_j = [], 0
+ self._last_act = None
+ return n, self.points[n0:], self.results[r0:]
+
+ def rt_act(self, T, pos, nrm, vel) -> dict:
+ """A new command: the racket state at contact T s from now, planned from the robot's current motion; it
+ replaces the stroke under way (the hit configuration of the replaced stroke seeds the IK)."""
+ t_hit = (self.k - self.leg["launch"]) * CONTROL_DT + float(T)
+ self._ik_seed = getattr(self, "_q_hit_active", None) if self.plan_j < len(self.plan) else None
+ plan, info = self.plan_racket(t_hit, pos, nrm, vel)
+ q_hit = info.pop("_q_hit", None)
+ info["T_from_now"] = round(float(T), 4)
+ if plan:
+ self.plan, self.plan_j = plan, 0
+ self._q_hit_active = q_hit
+ self.shots.append({"k": self.k, "leg": self.n_our_legs, **info})
+ self._last_act = info
+ return info
+
+ def rt_clear(self):
+ self.plan, self.plan_j = [], 0
+ self._last_act = None
+
+ def _after_leg(self, rec, leg_i) -> dict:
+ n0 = len(self.points)
+ while not self.done and self.n_our_legs == leg_i:
+ self.step(self._arm_target())
+ rec.pop("_q_hit", None)
+ self.shots.append(rec)
+ res = dict(self.results[leg_i]) if leg_i < len(self.results) else {"summary": "match over"}
+ self.run_to_decision()
+ res["points_finished"] = self.points[n0:]
+ return res
+
+ # ------------------------------------------------------------------ stroke controller
+ def _twin_phys(self) -> Phys:
+ if self._twin is None:
+ self._twin = Phys()
+ self._twin.reset(self.s.target)
+ return self._twin
+
+ def _base_plan(self, goal, n):
+ """n base targets of the go-to generator from the current base target/velocity towards goal; and the step
+ index at which it has arrived (None if not within n)."""
+ b = self.s.target[:2].copy(); v = self._target_vel()[:2].copy()
+ out, arrived = [], None
+ for i in range(n):
+ b, v = base_goto(b, v, goal)
+ out.append(b.copy())
+ if arrived is None and np.all(b == goal) and not v.any():
+ arrived = i
+ return out, arrived
+
+ def _stroke_for(self, v_in, v_out, p_hit, bxy, seed):
+ ph = self.s
+ sp = float(np.linalg.norm(v_out)); nrm = v_out / sp
+ vin_n = float(v_in @ nrm)
+ u = max(0.05, (sp - E_SHUTTLE * max(0.0, -vin_n)) / RACKET_GAIN)
+ v_p = u * nrm
+ best = None
+ for sgn in (1.0, -1.0):
+ q_h, res = ik(ph, p_hit, sgn * nrm, bxy, seed)
+ if best is None or res < best[1] - 1e-6:
+ best = (q_h, res)
+ q_h, res = best
+ Jp = ph.jac(np.r_[bxy, q_h])[:3]
+ Winv = np.diag(ARM_VEL ** 2)
+ qd_h = Winv @ Jp.T @ np.linalg.solve(Jp @ Winv @ Jp.T + 1e-9 * np.eye(3), v_p)
+ ratio = float(np.max(np.abs(qd_h) / ARM_VEL))
+ return dict(nrm=nrm, v_p=v_p, q_h=q_h, qd_h=qd_h, ik=res, ratio=ratio, v_out=v_out, u=u,
+ p_hit=np.asarray(p_hit, float))
+
+ def plan_stroke(self, t_hit, p_hit, aim, power="normal"):
+ """Swing so that the racket-head centre meets a shuttle centred at p_hit at t_hit (s after it was played)
+ and sends it towards aim. Base: the go-to generator to the forehand stance for p_hit (or as far as it gets
+ 0.05 s before the contact). Shot: the launch velocities that land at aim and clear the net (one per launch
+ angle, the controller's own flight model); power: soft = the slowest, hard = the fastest the arm can swing,
+ normal = the least demanding for the arm. Face normal = the launch direction, head speed from the racket
+ model; IK + a speed-weighted Jacobian inverse give the hit configuration; a cubic swing and follow-through,
+ refined by robot-only rehearsals on a twin; then up to 4 full rehearsals (arm and the real shuttle) correct
+ the aim by the rehearsed landing error. A wrong contact misses in the rehearsal too and is not corrected."""
+ power = power if power in POWER else "normal"
+ info = {"t_hit": t_hit, "p_hit": [float(x) for x in p_hit], "aim": [float(x) for x in aim], "power": power}
+ k_hit = self.leg["launch"] + int(round(t_hit / CONTROL_DT))
+ n_avail = k_hit - self.k
+ info["n_swing_steps_available"] = int(n_avail)
+ info["k_hit"] = None
+ if n_avail < 3:
+ info["stroke"] = "too late: the contact time has already passed"
+ return [], info
+ info["k_hit"] = int(k_hit)
+ # base: stance, or as far as it gets
+ st = stance(p_hit)
+ goal = st
+ b0 = self.s.target[:2].copy()
+ _, arr = self._base_plan(goal, n_avail)
+ if arr is None or arr > n_avail - 5:
+ lo_, hi_ = 0.0, 1.0
+ for _ in range(10):
+ mid = 0.5 * (lo_ + hi_)
+ _, a2 = self._base_plan(b0 + mid * (st - b0), n_avail)
+ if a2 is not None and a2 <= n_avail - 5:
+ lo_ = mid
+ else:
+ hi_ = mid
+ goal = b0 + lo_ * (st - b0)
+ info["base"] = f"could not reach the stance in time: {float(np.linalg.norm(st - goal)):.2f} m short"
+ else:
+ info["base"] = "ok"
+ info["base_goal"] = [round(float(x), 3) for x in goal]
+ base_tg, _ = self._base_plan(goal, n_avail + 40)
+ # incoming shuttle at the contact (the controller's forward model from the true current state)
+ P, V = predict(self.s.sh_p, self.s.sh_v, n_max=int(n_avail * SUBSTEPS))
+ v_in = V[-1] if len(V) else np.zeros(3)
+ rng = np.random.default_rng([self.lv["seed"], 7, self.n_our_legs])
+ aim_n = np.asarray(aim, float) + rng.normal(0.0, EXEC_SIGMA[power], 2)
+ aim_eff = aim_n.copy()
+ seed = getattr(self, "_ik_seed", None)
+ seed = Q0_ARM if seed is None else seed
+ best = None
+ for it in range(4):
+ cands = solve_shots(p_hit, aim_eff, OUR_THETAS, OUR_VMAX, net_margin=0.08)
+ if not cands:
+ info["stroke"] = "no shot from this contact point reaches the aim over the net"
+ if best is None:
+ cands = solve_shots(p_hit, (0.0, 4.0), OUR_THETAS, OUR_VMAX, net_margin=0.08)
+ if not cands:
+ return [], info
+ else:
+ break
+ strokes = [self._stroke_for(v_in, c[2], p_hit, goal, seed) for c in cands]
+ c = self._pick_stroke(strokes, power)
+ tg, sinfo = self._swing(c, goal, base_tg, n_avail)
+ L, spd = self._rehearse(tg)
+ err = None if L is None else float(np.linalg.norm(np.asarray(L) - aim_n))
+ if best is None or (err is not None and (best[2] is None or err < best[2])):
+ best = (tg, sinfo, err, L, spd, c)
+ if L is None or err < 0.08:
+ break
+ aim_eff = aim_eff + (aim_n - np.asarray(L))
+ tg, sinfo, err, L, spd, c = best
+ info.update(sinfo)
+ info["_q_hit"] = c["q_h"]
+ info["rehearsal_landing"] = None if L is None else [round(float(x), 3) for x in L]
+ info["rehearsal_speed"] = None if spd is None else round(float(spd), 2)
+ info.setdefault("stroke", "ok" if L is not None else "the rehearsal missed the shuttle")
+ return tg, info
+
+ RACKET_SCATTER = dict(pos=0.006, ang_deg=0.8, speed=0.03) # execution scatter of the racket state at contact
+
+ def plan_racket(self, t_hit, p_c, nrm, v_p):
+ """Racket-level decision: the player gives the racket state at contact (time t_hit s after the shuttle was
+ played, head centre p_c, string-face normal nrm, head velocity v_p). The controller only makes the robot
+ deliver it: the base to the forehand stance for p_c (or as far as it gets), IK, a speed-weighted Jacobian
+ inverse, a joint-speed-limited cubic swing and robot-only rehearsals that correct the PD lag. It uses no
+ shuttle state and does not aim. The delivered state scatters (seeded, RACKET_SCATTER)."""
+ p_c = np.asarray(p_c, float); nrm = np.asarray(nrm, float); nrm = nrm / np.linalg.norm(nrm)
+ v_p = np.asarray(v_p, float)
+ info = {"t_hit": t_hit, "racket_pos": p_c.round(4).tolist(), "racket_normal": nrm.round(4).tolist(),
+ "racket_vel": v_p.round(3).tolist()}
+ k_hit = self.leg["launch"] + int(round(t_hit / CONTROL_DT))
+ n_avail = k_hit - self.k
+ info["n_swing_steps_available"] = int(n_avail)
+ info["k_hit"] = None
+ if n_avail < 3:
+ info["stroke"] = "too late: the contact time has already passed"
+ return [], info
+ info["k_hit"] = int(k_hit)
+ rng = np.random.default_rng([self.lv["seed"], 13, self.n_our_legs])
+ sc = self.RACKET_SCATTER
+ p_c = p_c + rng.normal(0.0, sc["pos"], 3)
+ axis = np.cross(nrm, rng.normal(0.0, 1.0, 3)); axis /= np.linalg.norm(axis)
+ ang = np.radians(rng.normal(0.0, sc["ang_deg"]))
+ nrm = nrm * np.cos(ang) + np.cross(axis, nrm) * np.sin(ang); nrm /= np.linalg.norm(nrm)
+ v_p = v_p * (1.0 + rng.normal(0.0, sc["speed"]))
+ st = stance(p_c)
+ goal = st
+ b0 = self.s.target[:2].copy()
+ _, arr = self._base_plan(goal, n_avail)
+ if arr is None or arr > n_avail - 5:
+ lo_, hi_ = 0.0, 1.0
+ for _ in range(10):
+ mid = 0.5 * (lo_ + hi_)
+ _, a2 = self._base_plan(b0 + mid * (st - b0), n_avail)
+ if a2 is not None and a2 <= n_avail - 5:
+ lo_ = mid
+ else:
+ hi_ = mid
+ goal = b0 + lo_ * (st - b0)
+ info["base"] = f"could not reach the stance in time: {float(np.linalg.norm(st - goal)):.2f} m short"
+ else:
+ info["base"] = "ok"
+ info["base_goal"] = [round(float(x), 3) for x in goal]
+ base_tg, _ = self._base_plan(goal, n_avail + 40)
+ ph = self.s
+ seed = getattr(self, "_ik_seed", None)
+ q_now = ph.target[2:].copy() # the swing starts from the current joint targets
+ seeds = ([] if seed is None else [seed]) + [q_now, Q0_ARM]
+ q_h, res, sgn, alts = ik_multi(ph, p_c, nrm, goal, seeds, q_now) # deterministic multi-start, nearest first
+ Winv = np.diag(ARM_VEL ** 2)
+ tried = None
+ for q_h, res, _ in [(q_h, res, sgn)] + alts:
+ Jp = ph.jac(np.r_[goal, q_h])[:3]
+ qd_h = Winv @ Jp.T @ np.linalg.solve(Jp @ Winv @ Jp.T + 1e-9 * np.eye(3), v_p)
+ ratio = float(np.max(np.abs(qd_h) / ARM_VEL))
+ c = dict(nrm=nrm, v_p=v_p, q_h=q_h, qd_h=qd_h, ik=res, ratio=ratio, v_out=np.zeros(3), p_hit=p_c)
+ tg, sinfo = self._swing(c, goal, base_tg, n_avail)
+ sc = swing_score(sinfo["blade_error_m"], sinfo["normal_error_deg"],
+ np.linalg.norm(self._swing_last[2] - v_p / sinfo["speed_scale"]))
+ if tried is None or sc < tried[0]:
+ tried = (sc, tg, sinfo, self._swing_last, q_h, res)
+ if sinfo["blade_error_m"] <= DELIVERY_POS_WARN and sinfo["normal_error_deg"] <= DELIVERY_ANG_WARN:
+ break # delivered: the nearest solution that works
+ _, tg, sinfo, self._swing_last, q_h, res = tried
+ for k in ("shot_speed_plan", "launch_dir", "head_speed_plan"):
+ sinfo.pop(k, None)
+ info.update(sinfo)
+ p, n_act, v_act = self._swing_last
+ info["racket_vel_delivered"] = [round(float(x), 3) for x in v_act]
+ info["_q_hit"] = q_h
+ notes = []
+ if res > IK_OK: notes.append(f"pose not reachable exactly (IK residual {res:.3f})")
+ if sinfo["blade_error_m"] > DELIVERY_POS_WARN or sinfo["normal_error_deg"] > DELIVERY_ANG_WARN:
+ notes.append(f"pose not delivered: the rehearsed racket head is {100 * sinfo['blade_error_m']:.1f} cm off "
+ f"and the face {sinfo['normal_error_deg']:.1f} deg off the command at the contact time")
+ if sinfo["speed_scale"] > 1.005: notes.append(f"head speed limited by the joint speed limits (x{1 / sinfo['speed_scale']:.2f})")
+ if sinfo["n_swing_steps"] < 20: notes.append("short swing (little time left)")
+ if info["base"] != "ok": notes.append(info["base"])
+ info["stroke"] = "; ".join(notes) or "ok"
+ return tg, info
+
+ @staticmethod
+ def _pick_stroke(strokes, power):
+ good = ([c for c in strokes if c["ik"] < 2e-3 and c["ratio"] <= 1.0] or [c for c in strokes if c["ik"] < 2e-3]
+ or strokes)
+ if power == "normal":
+ return min(good, key=lambda c: c["ratio"])
+ sp = sorted(good, key=lambda c: float(np.linalg.norm(c["v_out"])))
+ return sp[-1] if power == "hard" else sp[0]
+
+ def _swing(self, c, goal, base_tg, n_avail):
+ """Arm swing (cubic to the hit configuration, follow-through) + base plan; 5 robot-only twin rehearsals
+ correct the hit configuration/velocity for the PD lag, and the best of them (swing_score) is kept."""
+ ph = self.s
+ scale = max(1.0, c["ratio"] / 0.9)
+ q_h, qd_h = c["q_h"].copy(), c["qd_h"] / scale
+ v_p = c["v_p"] / scale
+ q_s = ph.target[2:].copy(); v_s = self._target_vel()[2:]
+ n_sw = int(n_avail)
+ if np.max(np.abs(v_s)) < 1e-6:
+ for n in range(25, int(n_avail) + 1):
+ sw = hermite(q_s, np.zeros(7), q_h, qd_h, n * CONTROL_DT, n)
+ if np.max(np.abs(np.diff(np.vstack([q_s, sw]), axis=0)) / (ARM_VEL * CONTROL_DT)) <= 0.97:
+ n_sw = n
+ break
+ n_sw = int(min(n_sw, n_avail))
+ Winv = np.diag(ARM_VEL ** 2)
+ q_goal, qd_goal = q_h.copy(), qd_h.copy()
+ best = None
+ for it in range(5):
+ tg = self._swing_targets(q_goal, qd_goal, n_avail, n_sw, base_tg)
+ p, n_act, v_act = self._simulate_arm(tg, n_avail)
+ sg = 1.0 if n_act @ c["nrm"] >= 0 else -1.0
+ perr = float(np.linalg.norm(p - c["p_hit"]))
+ nerr = float(np.degrees(np.arccos(np.clip(abs(float(n_act @ c["nrm"])), 0.0, 1.0))))
+ sc = swing_score(perr, nerr, np.linalg.norm(v_act - v_p))
+ if best is None or sc < best[0]: # keep the best of the correction passes, not the last one
+ best = (sc, tg, (p, n_act, v_act), perr, nerr)
+ if it == 4:
+ break
+ J = ph.jac(np.r_[goal, q_goal])
+ e = np.r_[c["p_hit"] - p, np.cross(n_act, sg * c["nrm"])]
+ q_goal = np.clip(q_goal + J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), e),
+ ph.lo[2:] + 1e-4, ph.hi[2:] - 1e-4)
+ Jp = J[:3]
+ qd_goal = qd_goal + Winv @ Jp.T @ np.linalg.solve(Jp @ Winv @ Jp.T + 1e-9 * np.eye(3), v_p - v_act) * 0.7
+ qd_goal = qd_goal / max(1.0, float(np.max(np.abs(qd_goal) / ARM_VEL)))
+ _, tg, self._swing_last, perr, nerr = best
+ info = {"ik_residual": round(float(c["ik"]), 5), "speed_scale": round(scale, 3), "n_swing_steps": n_sw,
+ "blade_error_m": round(perr, 4), "normal_error_deg": round(nerr, 2),
+ "head_speed_plan": round(float(np.linalg.norm(v_p)), 2),
+ "shot_speed_plan": round(float(np.linalg.norm(c["v_out"]) / scale), 2),
+ "launch_dir": [round(float(x), 3) for x in c["nrm"]]}
+ info["stroke"] = "ok" if n_sw >= 20 else "short swing (little time left: slow racket)"
+ return tg, info
+
+ def _swing_targets(self, q_h, qd_h, n_avail, n_sw, base_tg):
+ ph = self.s
+ q_s = ph.target[2:].copy(); v_s = self._target_vel()[2:]
+ pre = np.tile(q_s, (n_avail - n_sw, 1))
+ swing = hermite(q_s, v_s if n_sw == n_avail else np.zeros(7), q_h, qd_h, n_sw * CONTROL_DT, n_sw)
+ n_f = 25
+ follow = hermite(q_h, qd_h, q_h + qd_h * 0.5 * n_f * CONTROL_DT, np.zeros(7), n_f * CONTROL_DT, n_f)
+ out, prev = [], ph.target.copy()
+ lim = VEL_LIMIT * CONTROL_DT * 0.999
+ for i, q in enumerate(np.vstack([pre, swing, follow])):
+ q9 = np.r_[base_tg[min(i, len(base_tg) - 1)], q]
+ q9 = np.clip(q9, ph.lo + 1e-4, ph.hi - 1e-4)
+ q9 = prev + np.clip(q9 - prev, -lim, lim)
+ out.append(q9); prev = q9
+ return out
+
+ def _simulate_arm(self, targets, n):
+ """Robot-only twin rollout from the live robot state: racket (pos, normal, velocity) after n steps."""
+ tw = self._twin_phys()
+ tw.copy_from(self.s)
+ tw.sh_live = False; tw.hit_enabled = False
+ for j in range(n):
+ tw.step(targets[j])
+ mj.mj_forward(tw.m, tw.d)
+ return tw.racket_state()
+
+ def _rehearse(self, targets):
+ """Full twin rehearsal (robot and the real shuttle): landing xy of our shot (shuttle-only prediction after
+ the hit) and its speed off the racket; (None, None) if the racket never meets the shuttle."""
+ tw = self._twin_phys()
+ tw.copy_from(self.s)
+ for j in range(len(targets) + 30):
+ tw.step(targets[j] if j < len(targets) else targets[-1])
+ h = [e for e in tw.events if e["kind"] == "hit"]
+ if h:
+ P, _ = predict(tw.sh_p, tw.sh_v)
+ return (P[-1][:2].tolist() if len(P) else list(tw.sh_p[:2])), h[0]["speed"]
+ if not tw.sh_live:
+ break
+ return None, None
+
+ # ------------------------------------------------------------------ views
+ @staticmethod
+ def cam_pose(lookat, dist, az, el):
+ a, e = math.radians(az), math.radians(el)
+ fwd = np.array([math.cos(e) * math.cos(a), math.cos(e) * math.sin(a), math.sin(e)])
+ up = np.array([-math.sin(e) * math.cos(a), -math.sin(e) * math.sin(a), math.cos(e)])
+ pos = np.asarray(lookat, float) - dist * fwd
+ return pos, fwd, up
+
+ @classmethod
+ def cam_info(cls):
+ out = []
+ for name, c in zip(("behind", "side"), cls.CAMS):
+ pos, fwd, up = cls.cam_pose(*c)
+ out.append({"name": name, "position": [round(float(x), 4) for x in pos],
+ "forward": [round(float(x), 4) for x in fwd], "up": [round(float(x), 4) for x in up]})
+ return out
+
+ def _set_render_state(self, rd, sn):
+ rd.qpos[:] = sn["qpos"]
+ rd.mocap_pos[0] = sn["sh"]
+ v = np.asarray(sn["shv"], float)
+ if np.linalg.norm(v) < 1e-6:
+ v = np.array([0.0, 0.0, -1.0])
+ rd.mocap_quat[0] = quat_z_to(v)
+ mj.mj_kinematics(self.s.m, rd)
+
+ @staticmethod
+ def _extra_geoms(scn, opp_xy, sh=None):
+ def add(typ, size, pos, rgba, mat=np.eye(3)):
+ if scn.ngeom >= scn.maxgeom:
+ return
+ mj.mjv_initGeom(scn.geoms[scn.ngeom], typ, np.asarray(size, float), np.asarray(pos, float),
+ np.asarray(mat, float).ravel(), np.asarray(rgba, np.float32))
+ scn.ngeom += 1
+ ox, oy = float(opp_xy[0]), float(opp_xy[1])
+ add(mj.mjtGeom.mjGEOM_CAPSULE, [0.16, 0.55, 0], [ox, oy, 0.75], [0.35, 0.35, 0.42, 1])
+ add(mj.mjtGeom.mjGEOM_SPHERE, [0.12, 0, 0], [ox, oy, 1.55], [0.85, 0.7, 0.6, 1])
+ # the opponent's racket: red head, reaching towards the shuttle when it is near
+ rp = np.array([ox + 0.45, oy - 0.1, 1.9])
+ if sh is not None:
+ d = np.array(sh) - np.array([ox, oy, 1.2])
+ if np.linalg.norm(d) < 1.6:
+ rp = np.array([ox, oy, 1.2]) + d / max(1e-6, np.linalg.norm(d)) * min(1.2, np.linalg.norm(d))
+ add(mj.mjtGeom.mjGEOM_ELLIPSOID, [0.10, 0.02, 0.13], rp, [0.9, 0.1, 0.1, 1])
+
+ def _renderer(self, w, h):
+ key = (w, h)
+ if getattr(self, "_rkey", None) != key:
+ self._r = mj.Renderer(self.s.m, height=h, width=w)
+ self._rd = mj.MjData(self.s.m)
+ self._rkey = key
+ self._cams = []
+ for lookat, dist, az, el in self.CAMS:
+ c = mj.MjvCamera(); c.lookat[:] = lookat; c.distance = dist; c.azimuth = az; c.elevation = el
+ self._cams.append(c)
+ return self._r, self._rd
+
+ def render_views(self) -> bytes:
+ """PNG: 2 rows (behind camera, side camera) x 4 columns (snapshots 60 ms apart, oldest left), each tile
+ stamped with its time since the shuttle was played."""
+ import imageio.v2 as imageio
+ from PIL import Image, ImageDraw
+ w, h = self.TILE
+ r, rd = self._renderer(w, h)
+ hist = list(self.hist)
+ snaps = [hist[max(0, len(hist) - 1 - b)] for b in reversed(self.VIEW_BACK)]
+ rows = []
+ for c in self._cams:
+ tiles = []
+ for sn in snaps:
+ self._set_render_state(rd, sn)
+ r.update_scene(rd, camera=c)
+ self._extra_geoms(r.scene, sn["opp"], sn["sh"])
+ im = Image.fromarray(r.render())
+ ImageDraw.Draw(im).text((6, 4), f"t={sn['t']:.2f}s", fill=(255, 255, 255))
+ tiles.append(np.asarray(im))
+ rows.append(np.concatenate(tiles, axis=1))
+ buf = io.BytesIO()
+ imageio.imwrite(buf, np.concatenate(rows, axis=0), format="png")
+ return buf.getvalue()
+
+ def view_times(self):
+ hist = list(self.hist)
+ return [hist[max(0, len(hist) - 1 - b)]["t"] for b in reversed(self.VIEW_BACK)]
+
+ def decision_observation(self) -> dict:
+ ph = self.s
+ leg = self.leg
+ heard = []
+ if leg["kind"] == "serve":
+ heard.append({"event": "the opponent served", "t": 0.0})
+ else:
+ heard.append({"event": "the opponent hit the shuttle", "t": 0.0})
+ c, n, _ = ph.racket_state()
+ return {"score": {"you": self.score[0], "opponent": self.score[1]}, "point": len(self.points) + 1,
+ "ball": "serve" if leg["kind"] == "serve" else "opponent's return",
+ "t_since_played": self.t_since_launch(), "heard": heard, "view_times": self.view_times(),
+ "robot_base_xy": [round(float(x), 3) for x in ph.d.qpos[ph.qa[:2]]],
+ "q_arm": [round(float(x), 4) for x in ph.d.qpos[ph.qa[2:]]],
+ "racket_pos": [round(float(x), 3) for x in c], "racket_normal": [round(float(x), 3) for x in n]}
+
+
+def _ready_pose():
+ """Ready pose: racket head up in front of the robot's right shoulder, face towards the net."""
+ global Q0_ARM
+ ph = Phys(); ph.reset(np.r_[HOME, Q0_ARM])
+ q, err = ik(ph, np.r_[HOME + np.array([0.35, 0.45]), SHOULDER_Z + 0.45], np.array([0.0, 1.0, 0.25]), HOME,
+ np.array([0.0, -0.2, 0.0, -1.6, 0.0, 1.6, 0.785]), iters=400)
+ Q0_ARM = np.round(q, 4)
+
+
+_ready_pose()
+
+
+def render_video(actions, level, out, fps=25, every=2):
+ """Replay video: the two decision cameras side by side, 2x slow motion (every `every` control steps at 25 fps),
+ 3x fewer frames while no shuttle is in play."""
+ import imageio.v2 as imageio
+ from PIL import Image, ImageDraw
+ mt = Match(level)
+ r = mj.Renderer(mt.s.m, height=360, width=640)
+ rd = mj.MjData(mt.s.m)
+ cams = []
+ for lookat, dist, az, el in Match.CAMS:
+ c = mj.MjvCamera(); c.lookat[:] = lookat; c.distance = dist; c.azimuth = az; c.elevation = el
+ cams.append(c)
+ w = imageio.get_writer(out, fps=fps, macro_block_size=8)
+ for k, q in enumerate(actions):
+ mt.step(q)
+ live = mt.s.sh_live
+ if k % (every if live else 3 * every):
+ continue
+ sn = {"qpos": mt.s.d.qpos.copy(), "sh": mt.s.sh_p, "shv": mt.s.sh_v}
+ mt._set_render_state(rd, sn)
+ imgs = []
+ for c in cams:
+ r.update_scene(rd, camera=c)
+ mt._extra_geoms(r.scene, mt.opp_xy(), mt.s.sh_p)
+ imgs.append(r.render())
+ im = Image.fromarray(np.concatenate(imgs, axis=1))
+ ImageDraw.Draw(im).text((8, 6), f"robot {mt.score[0]} : {mt.score[1]} opponent (level {level})",
+ fill=(255, 255, 255))
+ w.append_data(np.asarray(im))
+ w.close(); r.close()
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/LICENSE.menagerie-franka b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/LICENSE.menagerie-franka
new file mode 100644
index 0000000000..d9a10c0d8e
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/LICENSE.menagerie-franka
@@ -0,0 +1,176 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link0.stl b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link0.stl
new file mode 100644
index 0000000000..def070c707
Binary files /dev/null and b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link0.stl differ
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link1.stl b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link1.stl
new file mode 100644
index 0000000000..426bcf2d7a
Binary files /dev/null and b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link1.stl differ
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link2.stl b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link2.stl
new file mode 100644
index 0000000000..b369f1599a
Binary files /dev/null and b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link2.stl differ
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link3.stl b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link3.stl
new file mode 100644
index 0000000000..25162eeedf
Binary files /dev/null and b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link3.stl differ
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link4.stl b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link4.stl
new file mode 100644
index 0000000000..76c8c33c3e
Binary files /dev/null and b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link4.stl differ
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link5_collision_0.obj b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link5_collision_0.obj
new file mode 100644
index 0000000000..6d6eb5203b
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link5_collision_0.obj
@@ -0,0 +1,188 @@
+v 0.029063642 0.095448048 -0.133538792
+v 0.049877137 -0.013343874 -0.215408068
+v 0.046604998 0.029219000 -0.259000003
+v -0.043494001 0.033698998 -0.259000003
+v -0.030187000 -0.020500001 -0.186547995
+v -0.017736474 -0.052050648 -0.258999242
+v 0.012548444 0.082957777 -0.202027869
+v 0.050364564 0.017247290 -0.214926371
+v 0.020709741 -0.020753554 -0.182012846
+v -0.038214683 0.050463360 -0.167851336
+v 0.045944492 -0.030214707 -0.258999161
+v -0.051997126 -0.017851673 -0.259000003
+v 0.026338819 0.085091480 -0.183646959
+v 0.020922000 0.050882000 -0.259000003
+v 0.045491802 0.013339541 -0.187636452
+v 0.050951000 0.020726001 -0.259000003
+v 0.023551804 0.063747043 -0.133252288
+v -0.013548823 -0.047308172 -0.207602441
+v -0.023108632 0.089348183 -0.175470195
+v 0.028642003 -0.042568484 -0.211525585
+v -0.051912808 0.016682228 -0.233346078
+v 0.021637405 0.093787480 -0.156753967
+v 0.028892799 0.093108394 -0.147202451
+v -0.021765672 0.050517374 -0.259000003
+v 0.029191773 0.046614188 -0.259000003
+v 0.020095230 0.083558674 -0.197022477
+v 0.050294057 0.012853477 -0.210481151
+v 0.041400984 -0.012110881 -0.190499104
+v 0.050274495 0.021321905 -0.223857806
+v 0.050395896 -0.021963709 -0.259000003
+v -0.014053484 -0.016454442 -0.177588961
+v -0.023077204 0.053522191 -0.146035077
+v 0.028830698 0.067305577 -0.135375573
+v -0.038313158 -0.038208997 -0.224413296
+v 0.045422879 -0.030121078 -0.229083894
+v 0.011903144 -0.042590730 -0.199122301
+v 0.012319026 -0.051745998 -0.224350901
+v -0.052457958 0.016511494 -0.258999590
+v -0.046985660 -0.009035359 -0.196875560
+v 0.022625311 0.097598446 -0.133939149
+v 0.012620136 0.087869933 -0.188952639
+v 0.025225283 0.087563533 -0.179602397
+v -0.009634502 0.083175007 -0.202322834
+v -0.024273001 0.085358001 -0.188354000
+v 0.022706000 0.084515996 -0.192412004
+v 0.031834746 0.074158814 -0.139114503
+v 0.050391338 -0.004898283 -0.210560332
+v 0.036850054 -0.028951537 -0.199617216
+v 0.028814057 -0.007357717 -0.177964311
+v 0.007988000 -0.025363000 -0.182107002
+v -0.017462573 -0.033546585 -0.190912689
+v -0.022334082 -0.002848132 -0.172981292
+v -0.030079996 0.053249859 -0.151432391
+v 0.045789921 -0.008346553 -0.194042762
+v 0.037322809 -0.011895567 -0.186316195
+v -0.034569787 -0.042770809 -0.259000003
+v -0.026268487 -0.046990059 -0.224191914
+v 0.033556075 -0.043548766 -0.258998990
+v 0.049874237 -0.022123435 -0.233471659
+v -0.005066666 -0.052041921 -0.219576018
+v 0.016204123 -0.046663484 -0.207808223
+v -0.051942493 -0.005029111 -0.219727096
+v -0.029441908 0.082404274 -0.175896559
+v -0.042174398 -0.025291337 -0.202643498
+f 12 4 3
+f 14 3 4
+f 16 12 3
+f 23 3 13
+f 23 16 3
+f 23 1 16
+f 24 14 4
+f 25 13 3
+f 25 3 14
+f 26 14 7
+f 26 25 14
+f 27 8 1
+f 29 16 1
+f 29 1 8
+f 29 8 16
+f 30 12 16
+f 32 31 17
+f 33 1 17
+f 38 4 12
+f 40 22 19
+f 40 23 22
+f 40 1 23
+f 40 32 17
+f 40 17 1
+f 41 19 22
+f 41 26 7
+f 42 23 13
+f 42 22 23
+f 42 41 22
+f 43 7 14
+f 43 14 24
+f 43 41 7
+f 43 19 41
+f 44 24 4
+f 44 43 24
+f 44 19 43
+f 45 13 25
+f 45 25 26
+f 45 42 13
+f 45 26 41
+f 45 41 42
+f 46 27 1
+f 46 15 27
+f 46 1 33
+f 47 27 15
+f 47 30 16
+f 47 16 8
+f 47 8 27
+f 48 20 35
+f 48 35 2
+f 48 36 20
+f 48 9 36
+f 49 17 9
+f 50 9 17
+f 50 17 31
+f 50 36 9
+f 51 31 5
+f 51 50 31
+f 51 18 36
+f 51 36 50
+f 52 32 5
+f 52 5 31
+f 52 31 32
+f 53 10 39
+f 53 39 5
+f 53 5 32
+f 53 32 40
+f 54 33 28
+f 54 46 33
+f 54 15 46
+f 54 47 15
+f 54 2 47
+f 54 48 2
+f 54 28 48
+f 55 33 17
+f 55 28 33
+f 55 17 49
+f 55 48 28
+f 55 49 9
+f 55 9 48
+f 56 34 12
+f 56 30 6
+f 56 12 30
+f 57 56 6
+f 57 34 56
+f 58 35 20
+f 58 11 35
+f 58 20 37
+f 58 37 6
+f 58 30 11
+f 58 6 30
+f 59 2 35
+f 59 47 2
+f 59 30 47
+f 59 35 11
+f 59 11 30
+f 60 6 37
+f 60 57 6
+f 60 18 57
+f 61 37 20
+f 61 20 36
+f 61 60 37
+f 61 36 18
+f 61 18 60
+f 62 38 12
+f 62 21 38
+f 62 39 10
+f 62 10 21
+f 63 38 21
+f 63 21 10
+f 63 19 44
+f 63 44 4
+f 63 4 38
+f 63 10 53
+f 63 53 40
+f 63 40 19
+f 64 5 39
+f 64 51 5
+f 64 18 51
+f 64 57 18
+f 64 34 57
+f 64 12 34
+f 64 62 12
+f 64 39 62
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link5_collision_1.obj b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link5_collision_1.obj
new file mode 100644
index 0000000000..2eeeeea170
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link5_collision_1.obj
@@ -0,0 +1,119 @@
+v 0.029605924 0.107695894 -0.057770639
+v 0.028114332 0.082823920 -0.058553905
+v 0.038816102 0.053402838 -0.175505396
+v -0.026856016 0.088084521 -0.175136227
+v -0.030626847 0.107119812 -0.057687294
+v 0.025670733 0.088513946 -0.175229901
+v -0.004989269 0.102164150 -0.123603135
+v -0.038214683 0.050463360 -0.167851336
+v 0.029153411 0.097073936 -0.123627471
+v -0.039514421 0.050433927 -0.176900026
+v -0.009555079 0.106683172 -0.095345165
+v -0.018650687 0.092581494 -0.165880068
+v 0.028410194 0.050382871 -0.151882879
+v -0.025116868 0.079917612 -0.059207257
+v 0.027728461 0.088850155 -0.170468824
+v 0.012301352 0.106583136 -0.090584029
+v -0.033031356 0.072019963 -0.176122603
+v -0.028518812 0.083365915 -0.058497467
+v 0.017236843 0.092763911 -0.165977938
+v -0.013955552 0.101873439 -0.118898329
+v -0.028958102 0.093907525 -0.142630397
+v 0.017254189 0.075705868 -0.064336333
+v -0.014409871 0.075430847 -0.064290830
+v 0.028214046 0.087293870 -0.171111784
+v 0.025659250 0.106544369 -0.076459959
+v 0.003562050 0.106723586 -0.095327997
+v -0.038642138 0.054804181 -0.176806387
+v 0.024373464 0.079432104 -0.059087522
+v 0.021627842 0.092908946 -0.161300197
+v -0.022714762 0.106727072 -0.081193925
+v -0.026651997 0.092292062 -0.156493182
+v -0.028411485 0.090537503 -0.161463618
+v -0.033238728 0.052765384 -0.155973185
+v 0.028928091 0.106502887 -0.067219353
+v 0.003488032 0.101747359 -0.123570031
+v 0.025518961 0.096898989 -0.133035213
+v 0.021620985 0.097180492 -0.137775852
+v -0.029182131 0.097825064 -0.119030284
+v -0.022783418 0.101743257 -0.109443270
+v -0.027976784 0.086163124 -0.175228428
+v -0.029871457 0.106777512 -0.062281333
+f 1 2 3
+f 5 2 1
+f 9 1 3
+f 10 6 3
+f 11 5 1
+f 12 6 4
+f 13 3 2
+f 13 10 3
+f 13 8 10
+f 17 4 6
+f 18 10 8
+f 18 5 10
+f 18 8 14
+f 18 2 5
+f 19 12 7
+f 19 6 12
+f 20 11 7
+f 20 7 12
+f 23 14 8
+f 23 13 22
+f 24 15 9
+f 24 9 3
+f 24 3 6
+f 24 6 15
+f 25 16 1
+f 26 11 1
+f 26 1 16
+f 26 7 11
+f 26 16 19
+f 27 17 6
+f 27 6 10
+f 27 10 5
+f 27 5 21
+f 28 18 14
+f 28 2 18
+f 28 23 22
+f 28 14 23
+f 28 22 13
+f 28 13 2
+f 29 15 6
+f 29 6 19
+f 30 5 11
+f 30 11 20
+f 31 12 4
+f 31 21 30
+f 32 27 21
+f 32 17 27
+f 32 31 4
+f 32 21 31
+f 33 23 8
+f 33 8 13
+f 33 13 23
+f 34 25 1
+f 34 1 9
+f 34 9 25
+f 35 26 19
+f 35 19 7
+f 35 7 26
+f 36 9 15
+f 36 15 29
+f 36 25 9
+f 37 29 19
+f 37 19 16
+f 37 16 25
+f 37 36 29
+f 37 25 36
+f 38 30 21
+f 38 21 5
+f 39 30 20
+f 39 20 12
+f 39 31 30
+f 39 12 31
+f 40 32 4
+f 40 4 17
+f 40 17 32
+f 41 38 5
+f 41 5 30
+f 41 30 38
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link5_collision_2.obj b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link5_collision_2.obj
new file mode 100644
index 0000000000..6b563bff79
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link5_collision_2.obj
@@ -0,0 +1,188 @@
+v 0.016219155 0.099363113 0.048750773
+v 0.046550363 0.015799999 0.011058674
+v 0.046166659 0.105324245 -0.019041548
+v -0.005436418 0.111465780 -0.067873175
+v -0.043746749 0.015799999 0.019475930
+v 0.032618475 0.015799999 -0.035021468
+v 0.012971462 0.125447286 0.026076443
+v 0.045556378 0.100993129 0.023528159
+v 0.016534659 0.015799999 0.044952921
+v 0.045622136 0.015799999 -0.014505461
+v 0.031590266 0.097675904 -0.057701935
+v -0.026144502 0.015799999 -0.040104519
+v 0.020916727 0.125582876 -0.010159381
+v -0.043170314 0.100482302 0.027956662
+v 0.046145375 0.108191241 0.006346428
+v 0.028387091 0.112218342 0.031375415
+v 0.033002187 0.099171431 0.039965413
+v 0.016412747 0.015799999 -0.044989475
+v 0.036705779 0.015799999 -0.030707024
+v -0.022295018 0.125131249 -0.010109805
+v 0.029605924 0.107695894 -0.057770639
+v -0.013213095 0.112592014 0.039924672
+v -0.017325918 0.015799999 0.044664757
+v -0.047688079 0.104963029 -0.014858533
+v 0.045808408 0.103510400 0.019105049
+v 0.032957420 0.121769349 -0.001719666
+v 0.011885780 0.108060682 0.044095325
+v 0.016109216 0.089384114 0.048719259
+v 0.041214473 0.103236411 0.027403040
+v 0.041650999 0.015799999 0.023706000
+v 0.028114332 0.082823920 -0.058553905
+v -0.017699993 0.015799999 -0.044454039
+v 0.030954458 0.092818151 -0.058089685
+v -0.013656957 0.125189726 -0.019080479
+v 0.020627846 0.125801899 0.015541304
+v 0.008510412 0.111150243 -0.067818128
+v -0.029781181 0.121768239 0.014799138
+v -0.038794729 0.015799999 0.028113908
+v -0.017496539 0.098143056 0.049083962
+v -0.044002704 0.015799999 -0.018961373
+v -0.047333769 0.101445201 0.019313718
+v -0.030626847 0.107119812 -0.057687294
+v 0.046107670 0.108070694 -0.010345774
+v 0.028871230 0.120837663 -0.014381368
+v 0.011692637 0.121507793 0.031446733
+v 0.020178268 0.103656248 0.044326107
+v 0.024954524 0.015799999 0.040826797
+v 0.037099553 0.099607308 0.036020114
+v 0.028145238 0.121197152 0.018754182
+v -0.021927781 0.125344027 0.015252414
+v 0.020917077 0.111451583 -0.057406886
+v 0.012405067 0.125386135 -0.019235931
+v 0.024373464 0.079432104 -0.059087522
+v -0.033976639 0.107508587 0.031219781
+v -0.032505696 0.120513471 -0.010314825
+v -0.026112117 0.015799999 0.040139331
+v -0.008981987 0.108489258 0.044495871
+v -0.005033433 0.070411983 0.049486264
+v -0.047363327 0.103674321 0.015035708
+v -0.033832737 0.116474922 0.018745562
+v -0.047827588 0.074670758 0.002492660
+v -0.028518812 0.083365915 -0.058497467
+v -0.022142435 0.111037086 -0.057352830
+v 0.041463828 0.111761132 -0.014586542
+f 6 2 5
+f 9 5 2
+f 10 3 2
+f 10 2 6
+f 11 3 10
+f 12 6 5
+f 15 2 3
+f 18 6 12
+f 19 10 6
+f 21 3 11
+f 23 5 9
+f 25 8 2
+f 25 2 15
+f 28 17 1
+f 29 8 25
+f 30 9 2
+f 30 2 8
+f 31 6 18
+f 31 19 6
+f 32 18 12
+f 32 4 18
+f 33 11 10
+f 33 10 19
+f 33 19 31
+f 35 13 34
+f 35 26 13
+f 36 21 11
+f 36 11 33
+f 36 33 31
+f 36 18 4
+f 38 14 5
+f 38 5 23
+f 40 12 5
+f 41 5 14
+f 42 40 24
+f 43 26 15
+f 43 15 3
+f 44 26 21
+f 44 21 13
+f 44 13 26
+f 45 16 7
+f 45 7 22
+f 46 17 16
+f 46 45 27
+f 46 16 45
+f 46 27 1
+f 46 1 17
+f 47 28 9
+f 47 17 28
+f 47 9 30
+f 48 8 29
+f 48 30 8
+f 48 47 30
+f 48 17 47
+f 48 29 16
+f 48 16 17
+f 49 29 25
+f 49 16 29
+f 49 25 15
+f 49 15 26
+f 49 26 35
+f 49 35 7
+f 49 7 16
+f 50 7 35
+f 50 37 22
+f 50 22 7
+f 50 35 34
+f 50 34 20
+f 51 13 21
+f 51 21 36
+f 52 34 13
+f 52 51 36
+f 52 13 51
+f 52 36 4
+f 52 4 34
+f 53 36 31
+f 53 31 18
+f 53 18 36
+f 54 22 37
+f 54 39 22
+f 54 14 39
+f 55 42 24
+f 55 50 20
+f 55 37 50
+f 56 38 23
+f 56 23 39
+f 56 39 14
+f 56 14 38
+f 57 22 39
+f 57 45 22
+f 57 27 45
+f 57 39 1
+f 57 1 27
+f 58 28 1
+f 58 1 39
+f 58 9 28
+f 58 39 23
+f 58 23 9
+f 59 55 24
+f 59 37 55
+f 60 41 14
+f 60 59 41
+f 60 37 59
+f 60 54 37
+f 60 14 54
+f 61 40 5
+f 61 5 41
+f 61 24 40
+f 61 59 24
+f 61 41 59
+f 62 12 40
+f 62 40 42
+f 62 32 12
+f 62 42 4
+f 62 4 32
+f 63 34 4
+f 63 4 42
+f 63 20 34
+f 63 55 20
+f 63 42 55
+f 64 43 3
+f 64 3 21
+f 64 21 26
+f 64 26 43
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link6.stl b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link6.stl
new file mode 100644
index 0000000000..2e9594a873
Binary files /dev/null and b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link6.stl differ
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link7.stl b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link7.stl
new file mode 100644
index 0000000000..0532d05750
Binary files /dev/null and b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link7.stl differ
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/bm_duel.xml b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/bm_duel.xml
new file mode 100644
index 0000000000..64d44c831a
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/bm_duel.xml
@@ -0,0 +1,245 @@
+<!--
+ Robot badminton DUEL scene (render only), generated by scripts/olympiad/badminton/mk_duel_scene.py from
+ bm_scene.xml: robot A as in the match scene; robot B (names *_b, identical) the same robot in
+ a body rotated 180 degrees about z. The physics runs each robot in its own copy of bm_scene.xml (bduel.py).
+-->
+<mujoco model="rcb_badminton_duel">
+ <compiler angle="radian" meshdir="assets" autolimits="true"/>
+ <option integrator="implicitfast" timestep="0.001">
+ <flag contact="disable"/>
+ </option>
+ <size memory="20M"/>
+ <visual>
+ <headlight diffuse=".55 .55 .55" ambient=".25 .25 .25" specular=".2 .2 .2"/>
+ <global offwidth="1280" offheight="720"/>
+ <map znear="0.02" zfar="80"/>
+ </visual>
+ <default>
+ <default class="panda">
+ <joint armature="0.1" damping="1" axis="0 0 1" range="-2.8973 2.8973"/>
+ <geom type="mesh" rgba="0.92 0.93 0.94 1" group="2" contype="0" conaffinity="0"/>
+ <motor ctrlrange="-87 87"/>
+ </default>
+ </default>
+ <asset>
+ <texture type="skybox" builtin="gradient" rgb1=".45 .5 .6" rgb2="0.12 0.12 0.16" width="10" height="10"/>
+ <texture type="2d" name="hall" builtin="checker" rgb1=".30 .30 .34" rgb2=".26 .26 .30" width="300" height="300"/>
+ <material name="hall" texture="hall" texrepeat="10 10"/>
+ <mesh name="link0_c" file="link0.stl"/>
+ <mesh name="link1_c" file="link1.stl"/>
+ <mesh name="link2_c" file="link2.stl"/>
+ <mesh name="link3_c" file="link3.stl"/>
+ <mesh name="link4_c" file="link4.stl"/>
+ <mesh name="link5_c0" file="link5_collision_0.obj"/>
+ <mesh name="link5_c1" file="link5_collision_1.obj"/>
+ <mesh name="link5_c2" file="link5_collision_2.obj"/>
+ <mesh name="link6_c" file="link6.stl"/>
+ <mesh name="link7_c" file="link7.stl"/>
+ </asset>
+ <worldbody>
+ <light pos="0 -3 9" dir="0 0.2 -1" diffuse="0.8 0.8 0.8" specular="0.2 0.2 0.2" castshadow="false"/>
+ <light pos="0 4 9" dir="0 -0.2 -1" diffuse="0.5 0.5 0.5" specular="0.1 0.1 0.1" castshadow="false"/>
+ <geom name="hall_floor" type="plane" size="14 14 0.1" pos="0 0 -0.002" material="hall" contype="0" conaffinity="0"/>
+ <geom name="court" type="box" size="3.35 7.3 0.001" pos="0 0 -0.001" rgba="0.13 0.45 0.30 1" contype="0" conaffinity="0"/>
+ <geom name="side_sL" type="box" size="0.02 6.7 0.001" pos="-2.59 0 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="side_sR" type="box" size="0.02 6.7 0.001" pos="2.59 0 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="side_dL" type="box" size="0.02 6.7 0.001" pos="-3.05 0 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="side_dR" type="box" size="0.02 6.7 0.001" pos="3.05 0 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="base_line-1" type="box" size="3.05 0.02 0.001" pos="0 -6.7 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="short_service-1" type="box" size="3.05 0.02 0.001" pos="0 -1.98 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="centre_line-1" type="box" size="0.02 2.3600000000000003 0.001" pos="0 -4.34 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="base_line1" type="box" size="3.05 0.02 0.001" pos="0 6.7 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="short_service1" type="box" size="3.05 0.02 0.001" pos="0 1.98 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="centre_line1" type="box" size="0.02 2.3600000000000003 0.001" pos="0 4.34 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="mk0" type="box" size="0.1 0.025 0.0015" pos="-2.73 -6 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk1" type="box" size="0.1 0.025 0.0015" pos="2.73 -6 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk2" type="box" size="0.1 0.025 0.0015" pos="-2.73 -5 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk3" type="box" size="0.1 0.025 0.0015" pos="2.73 -5 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk4" type="box" size="0.1 0.025 0.0015" pos="-2.73 -4 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk5" type="box" size="0.1 0.025 0.0015" pos="2.73 -4 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk6" type="box" size="0.1 0.025 0.0015" pos="-2.73 -3 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk7" type="box" size="0.1 0.025 0.0015" pos="2.73 -3 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk8" type="box" size="0.1 0.025 0.0015" pos="-2.73 -2 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk9" type="box" size="0.1 0.025 0.0015" pos="2.73 -2 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk10" type="box" size="0.1 0.025 0.0015" pos="-2.73 -1 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk11" type="box" size="0.1 0.025 0.0015" pos="2.73 -1 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk12" type="box" size="0.1 0.025 0.0015" pos="-2.73 0 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk13" type="box" size="0.1 0.025 0.0015" pos="2.73 0 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk14" type="box" size="0.1 0.025 0.0015" pos="-2.73 1 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk15" type="box" size="0.1 0.025 0.0015" pos="2.73 1 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk16" type="box" size="0.1 0.025 0.0015" pos="-2.73 2 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk17" type="box" size="0.1 0.025 0.0015" pos="2.73 2 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk18" type="box" size="0.1 0.025 0.0015" pos="-2.73 3 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk19" type="box" size="0.1 0.025 0.0015" pos="2.73 3 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk20" type="box" size="0.1 0.025 0.0015" pos="-2.73 4 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk21" type="box" size="0.1 0.025 0.0015" pos="2.73 4 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk22" type="box" size="0.1 0.025 0.0015" pos="-2.73 5 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk23" type="box" size="0.1 0.025 0.0015" pos="2.73 5 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk24" type="box" size="0.1 0.025 0.0015" pos="-2.73 6 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk25" type="box" size="0.1 0.025 0.0015" pos="2.73 6 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk26" type="box" size="0.025 0.1 0.0015" pos="-2 -6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk27" type="box" size="0.025 0.1 0.0015" pos="-2 6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk28" type="box" size="0.025 0.1 0.0015" pos="-1 -6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk29" type="box" size="0.025 0.1 0.0015" pos="-1 6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk30" type="box" size="0.025 0.1 0.0015" pos="1 -6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk31" type="box" size="0.025 0.1 0.0015" pos="1 6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk32" type="box" size="0.025 0.1 0.0015" pos="2 -6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk33" type="box" size="0.025 0.1 0.0015" pos="2 6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <!-- net: 0.76 m deep band whose top is 1.524 m (BWF Law 1.10), posts (1.55 m) at the doubles side lines -->
+ <geom name="net" type="box" size="3.05 0.004 0.38" pos="0 0 1.144" rgba="0.9 0.9 0.9 0.35" contype="0" conaffinity="0"/>
+ <geom name="net_tape" type="box" size="3.05 0.012 0.018" pos="0 0 1.506" rgba="1 1 1 1" contype="0" conaffinity="0"/>
+ <geom name="post_L" type="cylinder" size="0.025 0.775" pos="-3.05 0 0.775" rgba="0.2 0.2 0.2 1" contype="0" conaffinity="0"/>
+ <geom name="post_R" type="cylinder" size="0.025 0.775" pos="3.05 0 0.775" rgba="0.2 0.2 0.2 1" contype="0" conaffinity="0"/>
+
+ <body name="shuttle" mocap="true" pos="0 5 1">
+ <geom name="shuttle_cork" type="sphere" size="0.06" pos="0 0 0" rgba="1.0 0.45 0.05 1" contype="0" conaffinity="0"/>
+ <geom name="shuttle_skirt" type="ellipsoid" size="0.07 0.07 0.11" pos="0 0 -0.11" rgba="1 1 0.92 1" contype="0" conaffinity="0"/>
+ </body>
+
+ <body name="base" pos="0 0 0">
+ <inertial pos="0 0 0.3" mass="40" diaginertia="4 4 2"/>
+ <joint name="base_x" type="slide" axis="1 0 0" range="-3.3 3.3" damping="0"/>
+ <joint name="base_y" type="slide" axis="0 1 0" range="-7.6 -0.4" damping="0"/>
+ <geom name="platform" type="box" size="0.32 0.32 0.06" pos="0 0 0.07" rgba="0.22 0.22 0.26 1" contype="0" conaffinity="0"/>
+ <geom name="pedestal" type="cylinder" size="0.11 0.47" pos="0 0 0.53" rgba="0.3 0.3 0.34 1" contype="0" conaffinity="0"/>
+ <body name="link0" childclass="panda" pos="0 0 1.0" quat="0.7071068 0 0 0.7071068">
+ <inertial mass="0.629769" pos="-0.041018 -0.00014 0.049974"
+ fullinertia="0.00315 0.00388 0.004285 8.2904e-7 0.00015 8.2299e-6"/>
+ <geom name="link0_c" mesh="link0_c"/>
+ <body name="link1" pos="0 0 0.333">
+ <inertial mass="4.970684" pos="0.003875 0.002081 -0.04762"
+ fullinertia="0.70337 0.70661 0.0091170 -0.00013900 0.0067720 0.019169"/>
+ <joint name="joint1"/>
+ <geom name="link1_c" mesh="link1_c"/>
+ <body name="link2" quat="1 -1 0 0">
+ <inertial mass="0.646926" pos="-0.003141 -0.02872 0.003495"
+ fullinertia="0.0079620 2.8110e-2 2.5995e-2 -3.925e-3 1.0254e-2 7.04e-4"/>
+ <joint name="joint2" range="-1.7628 1.7628"/>
+ <geom name="link2_c" mesh="link2_c"/>
+ <body name="link3" pos="0 -0.316 0" quat="1 1 0 0">
+ <joint name="joint3"/>
+ <inertial mass="3.228604" pos="2.7518e-2 3.9252e-2 -6.6502e-2"
+ fullinertia="3.7242e-2 3.6155e-2 1.083e-2 -4.761e-3 -1.1396e-2 -1.2805e-2"/>
+ <geom name="link3_c" mesh="link3_c"/>
+ <body name="link4" pos="0.0825 0 0" quat="1 1 0 0">
+ <inertial mass="3.587895" pos="-5.317e-2 1.04419e-1 2.7454e-2"
+ fullinertia="2.5853e-2 1.9552e-2 2.8323e-2 7.796e-3 -1.332e-3 8.641e-3"/>
+ <joint name="joint4" range="-3.0718 -0.0698"/>
+ <geom name="link4_c" mesh="link4_c"/>
+ <body name="link5" pos="-0.0825 0.384 0" quat="1 -1 0 0">
+ <inertial mass="1.225946" pos="-1.1953e-2 4.1065e-2 -3.8437e-2"
+ fullinertia="3.5549e-2 2.9474e-2 8.627e-3 -2.117e-3 -4.037e-3 2.29e-4"/>
+ <joint name="joint5"/>
+ <geom name="link5_c0" mesh="link5_c0"/>
+ <geom name="link5_c1" mesh="link5_c1"/>
+ <geom name="link5_c2" mesh="link5_c2"/>
+ <body name="link6" quat="1 1 0 0">
+ <inertial mass="1.666555" pos="6.0149e-2 -1.4117e-2 -1.0517e-2"
+ fullinertia="1.964e-3 4.354e-3 5.433e-3 1.09e-4 -1.158e-3 3.41e-4"/>
+ <joint name="joint6" range="-0.0175 3.7525"/>
+ <geom name="link6_c" mesh="link6_c"/>
+ <body name="link7" pos="0.088 0 0" quat="1 1 0 0">
+ <inertial mass="7.35522e-01" pos="1.0517e-2 -4.252e-3 6.1597e-2"
+ fullinertia="1.2516e-2 1.0027e-2 4.815e-3 -4.28e-4 -1.196e-3 -7.41e-4"/>
+ <joint name="joint7"/>
+ <geom name="link7_c" mesh="link7_c"/>
+ <body name="racket" pos="0 0 0.107">
+ <!-- badminton racket: handle + shaft along the flange z axis, oval head; face normal = local +x -->
+ <geom name="racket_handle" type="capsule" fromto="0 0 0 0 0 0.20" size="0.016" mass="0.05" rgba="0.15 0.15 0.18 1" group="2"/>
+ <geom name="racket_shaft" type="capsule" fromto="0 0 0.20 0 0 0.44" size="0.005" mass="0.015" rgba="0.8 0.8 0.85 1" group="2"/>
+ <geom name="racket_frame" type="ellipsoid" pos="0 0 0.56" size="0.006 0.12 0.15" mass="0.02" rgba="0.1 0.3 0.85 1" group="2"/>
+ <geom name="racket_strings" type="ellipsoid" pos="0 0 0.56" size="0.008 0.11 0.14" mass="0.001" rgba="0.95 0.95 0.95 0.55" group="2"/>
+ <site name="racket_center" pos="0 0 0.56" size="0.005" rgba="1 1 1 1" group="4"/>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+
+ </body>
+ <!-- robot B: the same robot in B's frame, (x, y, z) -> (-x, -y, z) -->
+ <body name="side_b" quat="0 0 0 1">
+ <body name="base_b" pos="0 0 0">
+ <inertial pos="0 0 0.3" mass="40" diaginertia="4 4 2"/>
+ <joint name="base_x_b" type="slide" axis="1 0 0" range="-3.3 3.3" damping="0"/>
+ <joint name="base_y_b" type="slide" axis="0 1 0" range="-7.6 -0.4" damping="0"/>
+ <geom name="platform_b" type="box" size="0.32 0.32 0.06" pos="0 0 0.07" rgba="0.22 0.22 0.26 1" contype="0" conaffinity="0"/>
+ <geom name="pedestal_b" type="cylinder" size="0.11 0.47" pos="0 0 0.53" rgba="0.3 0.3 0.34 1" contype="0" conaffinity="0"/>
+ <body name="link0_b" childclass="panda" pos="0 0 1.0" quat="0.7071068 0 0 0.7071068">
+ <inertial mass="0.629769" pos="-0.041018 -0.00014 0.049974"
+ fullinertia="0.00315 0.00388 0.004285 8.2904e-7 0.00015 8.2299e-6"/>
+ <geom name="link0_c_b" mesh="link0_c"/>
+ <body name="link1_b" pos="0 0 0.333">
+ <inertial mass="4.970684" pos="0.003875 0.002081 -0.04762"
+ fullinertia="0.70337 0.70661 0.0091170 -0.00013900 0.0067720 0.019169"/>
+ <joint name="joint1_b"/>
+ <geom name="link1_c_b" mesh="link1_c"/>
+ <body name="link2_b" quat="1 -1 0 0">
+ <inertial mass="0.646926" pos="-0.003141 -0.02872 0.003495"
+ fullinertia="0.0079620 2.8110e-2 2.5995e-2 -3.925e-3 1.0254e-2 7.04e-4"/>
+ <joint name="joint2_b" range="-1.7628 1.7628"/>
+ <geom name="link2_c_b" mesh="link2_c"/>
+ <body name="link3_b" pos="0 -0.316 0" quat="1 1 0 0">
+ <joint name="joint3_b"/>
+ <inertial mass="3.228604" pos="2.7518e-2 3.9252e-2 -6.6502e-2"
+ fullinertia="3.7242e-2 3.6155e-2 1.083e-2 -4.761e-3 -1.1396e-2 -1.2805e-2"/>
+ <geom name="link3_c_b" mesh="link3_c"/>
+ <body name="link4_b" pos="0.0825 0 0" quat="1 1 0 0">
+ <inertial mass="3.587895" pos="-5.317e-2 1.04419e-1 2.7454e-2"
+ fullinertia="2.5853e-2 1.9552e-2 2.8323e-2 7.796e-3 -1.332e-3 8.641e-3"/>
+ <joint name="joint4_b" range="-3.0718 -0.0698"/>
+ <geom name="link4_c_b" mesh="link4_c"/>
+ <body name="link5_b" pos="-0.0825 0.384 0" quat="1 -1 0 0">
+ <inertial mass="1.225946" pos="-1.1953e-2 4.1065e-2 -3.8437e-2"
+ fullinertia="3.5549e-2 2.9474e-2 8.627e-3 -2.117e-3 -4.037e-3 2.29e-4"/>
+ <joint name="joint5_b"/>
+ <geom name="link5_c0_b" mesh="link5_c0"/>
+ <geom name="link5_c1_b" mesh="link5_c1"/>
+ <geom name="link5_c2_b" mesh="link5_c2"/>
+ <body name="link6_b" quat="1 1 0 0">
+ <inertial mass="1.666555" pos="6.0149e-2 -1.4117e-2 -1.0517e-2"
+ fullinertia="1.964e-3 4.354e-3 5.433e-3 1.09e-4 -1.158e-3 3.41e-4"/>
+ <joint name="joint6_b" range="-0.0175 3.7525"/>
+ <geom name="link6_c_b" mesh="link6_c"/>
+ <body name="link7_b" pos="0.088 0 0" quat="1 1 0 0">
+ <inertial mass="7.35522e-01" pos="1.0517e-2 -4.252e-3 6.1597e-2"
+ fullinertia="1.2516e-2 1.0027e-2 4.815e-3 -4.28e-4 -1.196e-3 -7.41e-4"/>
+ <joint name="joint7_b"/>
+ <geom name="link7_c_b" mesh="link7_c"/>
+ <body name="racket_b" pos="0 0 0.107">
+ <!-- badminton racket: handle + shaft along the flange z axis, oval head; face normal = local +x -->
+ <geom name="racket_handle_b" type="capsule" fromto="0 0 0 0 0 0.20" size="0.016" mass="0.05" rgba="0.15 0.15 0.18 1" group="2"/>
+ <geom name="racket_shaft_b" type="capsule" fromto="0 0 0.20 0 0 0.44" size="0.005" mass="0.015" rgba="0.8 0.8 0.85 1" group="2"/>
+ <geom name="racket_frame_b" type="ellipsoid" pos="0 0 0.56" size="0.006 0.12 0.15" mass="0.02" rgba="0.1 0.3 0.85 1" group="2"/>
+ <geom name="racket_strings_b" type="ellipsoid" pos="0 0 0.56" size="0.008 0.11 0.14" mass="0.001" rgba="0.95 0.95 0.95 0.55" group="2"/>
+ <site name="racket_center_b" pos="0 0 0.56" size="0.005" rgba="1 1 1 1" group="4"/>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+
+ </body>
+ </body>
+
+ </worldbody>
+ <actuator>
+ <motor name="motor_bx" joint="base_x" ctrlrange="-1500 1500"/>
+ <motor name="motor_by" joint="base_y" ctrlrange="-1500 1500"/>
+ <motor class="panda" name="motor1" joint="joint1"/>
+ <motor class="panda" name="motor2" joint="joint2"/>
+ <motor class="panda" name="motor3" joint="joint3"/>
+ <motor class="panda" name="motor4" joint="joint4"/>
+ <motor class="panda" name="motor5" joint="joint5" ctrlrange="-12 12"/>
+ <motor class="panda" name="motor6" joint="joint6" ctrlrange="-12 12"/>
+ <motor class="panda" name="motor7" joint="joint7" ctrlrange="-12 12"/>
+ </actuator>
+</mujoco>
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/bm_scene.xml b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/bm_scene.xml
new file mode 100644
index 0000000000..27e658f778
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/bm_scene.xml
@@ -0,0 +1,181 @@
+<!--
+ Robot badminton scene for robot_coding_bench (generated; see the task README).
+ * World frame: floor z = 0, the court's long axis is y, the net is the plane y = 0 (top 1.524 m, BWF Law 1.10). The robot's half
+ is y < 0, the opponent's y > 0. Singles court |x| <= 2.59, |y| <= 6.70 (doubles side lines drawn at 3.05).
+ * Robot: a Franka Panda arm (MuJoCo Menagerie panda_nohand, Apache-2.0, assets/LICENSE.menagerie-franka) on a
+ 1.0 m pedestal whose base slides in x and y (two prismatic joints, a mobile base), holding a badminton racket
+ (head centre 0.56 m beyond the flange; face normal = racket local +x).
+ * The shuttlecock is NOT a MuJoCo body: it is integrated by bm.py (point mass, quadratic drag); the mocap body
+ `shuttle` only draws it (cork first along its velocity). MuJoCo contacts are disabled (nothing touches).
+-->
+<mujoco model="rcb_badminton">
+ <compiler angle="radian" meshdir="assets" autolimits="true"/>
+ <option integrator="implicitfast" timestep="0.001">
+ <flag contact="disable"/>
+ </option>
+ <size memory="20M"/>
+ <visual>
+ <headlight diffuse=".55 .55 .55" ambient=".25 .25 .25" specular=".2 .2 .2"/>
+ <global offwidth="1280" offheight="720"/>
+ <map znear="0.02" zfar="80"/>
+ </visual>
+ <default>
+ <default class="panda">
+ <joint armature="0.1" damping="1" axis="0 0 1" range="-2.8973 2.8973"/>
+ <geom type="mesh" rgba="0.92 0.93 0.94 1" group="2" contype="0" conaffinity="0"/>
+ <motor ctrlrange="-87 87"/>
+ </default>
+ </default>
+ <asset>
+ <texture type="skybox" builtin="gradient" rgb1=".45 .5 .6" rgb2="0.12 0.12 0.16" width="10" height="10"/>
+ <texture type="2d" name="hall" builtin="checker" rgb1=".30 .30 .34" rgb2=".26 .26 .30" width="300" height="300"/>
+ <material name="hall" texture="hall" texrepeat="10 10"/>
+ <mesh name="link0_c" file="link0.stl"/>
+ <mesh name="link1_c" file="link1.stl"/>
+ <mesh name="link2_c" file="link2.stl"/>
+ <mesh name="link3_c" file="link3.stl"/>
+ <mesh name="link4_c" file="link4.stl"/>
+ <mesh name="link5_c0" file="link5_collision_0.obj"/>
+ <mesh name="link5_c1" file="link5_collision_1.obj"/>
+ <mesh name="link5_c2" file="link5_collision_2.obj"/>
+ <mesh name="link6_c" file="link6.stl"/>
+ <mesh name="link7_c" file="link7.stl"/>
+ </asset>
+ <worldbody>
+ <light pos="0 -3 9" dir="0 0.2 -1" diffuse="0.8 0.8 0.8" specular="0.2 0.2 0.2" castshadow="false"/>
+ <light pos="0 4 9" dir="0 -0.2 -1" diffuse="0.5 0.5 0.5" specular="0.1 0.1 0.1" castshadow="false"/>
+ <geom name="hall_floor" type="plane" size="14 14 0.1" pos="0 0 -0.002" material="hall" contype="0" conaffinity="0"/>
+ <geom name="court" type="box" size="3.35 7.3 0.001" pos="0 0 -0.001" rgba="0.13 0.45 0.30 1" contype="0" conaffinity="0"/>
+ <geom name="side_sL" type="box" size="0.02 6.7 0.001" pos="-2.59 0 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="side_sR" type="box" size="0.02 6.7 0.001" pos="2.59 0 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="side_dL" type="box" size="0.02 6.7 0.001" pos="-3.05 0 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="side_dR" type="box" size="0.02 6.7 0.001" pos="3.05 0 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="base_line-1" type="box" size="3.05 0.02 0.001" pos="0 -6.7 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="short_service-1" type="box" size="3.05 0.02 0.001" pos="0 -1.98 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="centre_line-1" type="box" size="0.02 2.3600000000000003 0.001" pos="0 -4.34 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="base_line1" type="box" size="3.05 0.02 0.001" pos="0 6.7 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="short_service1" type="box" size="3.05 0.02 0.001" pos="0 1.98 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="centre_line1" type="box" size="0.02 2.3600000000000003 0.001" pos="0 4.34 0.001" rgba="0.97 0.97 0.97 1" contype="0" conaffinity="0"/>
+ <geom name="mk0" type="box" size="0.1 0.025 0.0015" pos="-2.73 -6 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk1" type="box" size="0.1 0.025 0.0015" pos="2.73 -6 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk2" type="box" size="0.1 0.025 0.0015" pos="-2.73 -5 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk3" type="box" size="0.1 0.025 0.0015" pos="2.73 -5 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk4" type="box" size="0.1 0.025 0.0015" pos="-2.73 -4 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk5" type="box" size="0.1 0.025 0.0015" pos="2.73 -4 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk6" type="box" size="0.1 0.025 0.0015" pos="-2.73 -3 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk7" type="box" size="0.1 0.025 0.0015" pos="2.73 -3 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk8" type="box" size="0.1 0.025 0.0015" pos="-2.73 -2 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk9" type="box" size="0.1 0.025 0.0015" pos="2.73 -2 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk10" type="box" size="0.1 0.025 0.0015" pos="-2.73 -1 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk11" type="box" size="0.1 0.025 0.0015" pos="2.73 -1 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk12" type="box" size="0.1 0.025 0.0015" pos="-2.73 0 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk13" type="box" size="0.1 0.025 0.0015" pos="2.73 0 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk14" type="box" size="0.1 0.025 0.0015" pos="-2.73 1 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk15" type="box" size="0.1 0.025 0.0015" pos="2.73 1 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk16" type="box" size="0.1 0.025 0.0015" pos="-2.73 2 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk17" type="box" size="0.1 0.025 0.0015" pos="2.73 2 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk18" type="box" size="0.1 0.025 0.0015" pos="-2.73 3 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk19" type="box" size="0.1 0.025 0.0015" pos="2.73 3 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk20" type="box" size="0.1 0.025 0.0015" pos="-2.73 4 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk21" type="box" size="0.1 0.025 0.0015" pos="2.73 4 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk22" type="box" size="0.1 0.025 0.0015" pos="-2.73 5 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk23" type="box" size="0.1 0.025 0.0015" pos="2.73 5 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk24" type="box" size="0.1 0.025 0.0015" pos="-2.73 6 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk25" type="box" size="0.1 0.025 0.0015" pos="2.73 6 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk26" type="box" size="0.025 0.1 0.0015" pos="-2 -6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk27" type="box" size="0.025 0.1 0.0015" pos="-2 6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk28" type="box" size="0.025 0.1 0.0015" pos="-1 -6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk29" type="box" size="0.025 0.1 0.0015" pos="-1 6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk30" type="box" size="0.025 0.1 0.0015" pos="1 -6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk31" type="box" size="0.025 0.1 0.0015" pos="1 6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk32" type="box" size="0.025 0.1 0.0015" pos="2 -6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <geom name="mk33" type="box" size="0.025 0.1 0.0015" pos="2 6.84 0.0015" rgba="1 0.85 0.1 1" contype="0" conaffinity="0"/>
+ <!-- net: 0.76 m deep band whose top is 1.524 m (BWF Law 1.10), posts (1.55 m) at the doubles side lines -->
+ <geom name="net" type="box" size="3.05 0.004 0.38" pos="0 0 1.144" rgba="0.9 0.9 0.9 0.35" contype="0" conaffinity="0"/>
+ <geom name="net_tape" type="box" size="3.05 0.012 0.018" pos="0 0 1.506" rgba="1 1 1 1" contype="0" conaffinity="0"/>
+ <geom name="post_L" type="cylinder" size="0.025 0.775" pos="-3.05 0 0.775" rgba="0.2 0.2 0.2 1" contype="0" conaffinity="0"/>
+ <geom name="post_R" type="cylinder" size="0.025 0.775" pos="3.05 0 0.775" rgba="0.2 0.2 0.2 1" contype="0" conaffinity="0"/>
+
+ <body name="shuttle" mocap="true" pos="0 5 1">
+ <geom name="shuttle_cork" type="sphere" size="0.06" pos="0 0 0" rgba="1.0 0.45 0.05 1" contype="0" conaffinity="0"/>
+ <geom name="shuttle_skirt" type="ellipsoid" size="0.07 0.07 0.11" pos="0 0 -0.11" rgba="1 1 0.92 1" contype="0" conaffinity="0"/>
+ </body>
+
+ <body name="base" pos="0 0 0">
+ <inertial pos="0 0 0.3" mass="40" diaginertia="4 4 2"/>
+ <joint name="base_x" type="slide" axis="1 0 0" range="-3.3 3.3" damping="0"/>
+ <joint name="base_y" type="slide" axis="0 1 0" range="-7.6 -0.4" damping="0"/>
+ <geom name="platform" type="box" size="0.32 0.32 0.06" pos="0 0 0.07" rgba="0.22 0.22 0.26 1" contype="0" conaffinity="0"/>
+ <geom name="pedestal" type="cylinder" size="0.11 0.47" pos="0 0 0.53" rgba="0.3 0.3 0.34 1" contype="0" conaffinity="0"/>
+ <body name="link0" childclass="panda" pos="0 0 1.0" quat="0.7071068 0 0 0.7071068">
+ <inertial mass="0.629769" pos="-0.041018 -0.00014 0.049974"
+ fullinertia="0.00315 0.00388 0.004285 8.2904e-7 0.00015 8.2299e-6"/>
+ <geom name="link0_c" mesh="link0_c"/>
+ <body name="link1" pos="0 0 0.333">
+ <inertial mass="4.970684" pos="0.003875 0.002081 -0.04762"
+ fullinertia="0.70337 0.70661 0.0091170 -0.00013900 0.0067720 0.019169"/>
+ <joint name="joint1"/>
+ <geom name="link1_c" mesh="link1_c"/>
+ <body name="link2" quat="1 -1 0 0">
+ <inertial mass="0.646926" pos="-0.003141 -0.02872 0.003495"
+ fullinertia="0.0079620 2.8110e-2 2.5995e-2 -3.925e-3 1.0254e-2 7.04e-4"/>
+ <joint name="joint2" range="-1.7628 1.7628"/>
+ <geom name="link2_c" mesh="link2_c"/>
+ <body name="link3" pos="0 -0.316 0" quat="1 1 0 0">
+ <joint name="joint3"/>
+ <inertial mass="3.228604" pos="2.7518e-2 3.9252e-2 -6.6502e-2"
+ fullinertia="3.7242e-2 3.6155e-2 1.083e-2 -4.761e-3 -1.1396e-2 -1.2805e-2"/>
+ <geom name="link3_c" mesh="link3_c"/>
+ <body name="link4" pos="0.0825 0 0" quat="1 1 0 0">
+ <inertial mass="3.587895" pos="-5.317e-2 1.04419e-1 2.7454e-2"
+ fullinertia="2.5853e-2 1.9552e-2 2.8323e-2 7.796e-3 -1.332e-3 8.641e-3"/>
+ <joint name="joint4" range="-3.0718 -0.0698"/>
+ <geom name="link4_c" mesh="link4_c"/>
+ <body name="link5" pos="-0.0825 0.384 0" quat="1 -1 0 0">
+ <inertial mass="1.225946" pos="-1.1953e-2 4.1065e-2 -3.8437e-2"
+ fullinertia="3.5549e-2 2.9474e-2 8.627e-3 -2.117e-3 -4.037e-3 2.29e-4"/>
+ <joint name="joint5"/>
+ <geom name="link5_c0" mesh="link5_c0"/>
+ <geom name="link5_c1" mesh="link5_c1"/>
+ <geom name="link5_c2" mesh="link5_c2"/>
+ <body name="link6" quat="1 1 0 0">
+ <inertial mass="1.666555" pos="6.0149e-2 -1.4117e-2 -1.0517e-2"
+ fullinertia="1.964e-3 4.354e-3 5.433e-3 1.09e-4 -1.158e-3 3.41e-4"/>
+ <joint name="joint6" range="-0.0175 3.7525"/>
+ <geom name="link6_c" mesh="link6_c"/>
+ <body name="link7" pos="0.088 0 0" quat="1 1 0 0">
+ <inertial mass="7.35522e-01" pos="1.0517e-2 -4.252e-3 6.1597e-2"
+ fullinertia="1.2516e-2 1.0027e-2 4.815e-3 -4.28e-4 -1.196e-3 -7.41e-4"/>
+ <joint name="joint7"/>
+ <geom name="link7_c" mesh="link7_c"/>
+ <body name="racket" pos="0 0 0.107">
+ <!-- badminton racket: handle + shaft along the flange z axis, oval head; face normal = local +x -->
+ <geom name="racket_handle" type="capsule" fromto="0 0 0 0 0 0.20" size="0.016" mass="0.05" rgba="0.15 0.15 0.18 1" group="2"/>
+ <geom name="racket_shaft" type="capsule" fromto="0 0 0.20 0 0 0.44" size="0.005" mass="0.015" rgba="0.8 0.8 0.85 1" group="2"/>
+ <geom name="racket_frame" type="ellipsoid" pos="0 0 0.56" size="0.006 0.12 0.15" mass="0.02" rgba="0.1 0.3 0.85 1" group="2"/>
+ <geom name="racket_strings" type="ellipsoid" pos="0 0 0.56" size="0.008 0.11 0.14" mass="0.001" rgba="0.95 0.95 0.95 0.55" group="2"/>
+ <site name="racket_center" pos="0 0 0.56" size="0.005" rgba="1 1 1 1" group="4"/>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+
+ </body>
+ </worldbody>
+ <actuator>
+ <motor name="motor_bx" joint="base_x" ctrlrange="-1500 1500"/>
+ <motor name="motor_by" joint="base_y" ctrlrange="-1500 1500"/>
+ <motor class="panda" name="motor1" joint="joint1"/>
+ <motor class="panda" name="motor2" joint="joint2"/>
+ <motor class="panda" name="motor3" joint="joint3"/>
+ <motor class="panda" name="motor4" joint="joint4"/>
+ <motor class="panda" name="motor5" joint="joint5" ctrlrange="-12 12"/>
+ <motor class="panda" name="motor6" joint="joint6" ctrlrange="-12 12"/>
+ <motor class="panda" name="motor7" joint="joint7" ctrlrange="-12 12"/>
+ </actuator>
+</mujoco>
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/mk_duel_scene.py b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/mk_duel_scene.py
new file mode 100644
index 0000000000..e9e85bf070
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/scene/mk_duel_scene.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python3
+"""Write the two-robot badminton scene of the duel's renderer (bm_duel.xml, next to this file) from the match scene.
+
+The duel's physics runs each robot in its own copy of the single-player model (scene/bm_scene.xml; see
+duel/environment/sim/bduel.py); this scene only DRAWS both: robot A as in bm_scene.xml, robot B as a copy of the same
+robot body (every name suffixed `_b`) inside a body rotated 180 degrees about z, so that B's joint values are those of
+B's own frame (x, y, z) -> (-x, -y, z). No actuators are copied (the renderer only sets joint positions).
+
+ python3 sports/badminton/sim/scene/mk_duel_scene.py (then tools/generate.py badminton)
+
+The header written into bm_duel.xml keeps the wording of the legacy script (scripts/olympiad/badminton/), so the
+scene file stays byte-identical to the one the legacy duel recordings were made with.
+"""
+import re
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+SRC = HERE / "bm_scene.xml"
+OUT = HERE / "bm_duel.xml"
+
+
+def robot_block(xml: str) -> str:
+ """The <body name="base"> element (the whole robot), found by balancing <body> tags."""
+ i = xml.index('<body name="base"')
+ depth, j = 0, i
+ for m in re.finditer(r"<body\b[^>]*?(/?)>|</body>", xml[i:]):
+ if m.group(0).startswith("</"):
+ depth -= 1
+ elif not m.group(1):
+ depth += 1
+ if depth == 0:
+ j = i + m.end()
+ break
+ return xml[i:j]
+
+
+def main():
+ xml = SRC.read_text()
+ block = robot_block(xml)
+ copy = re.sub(r'\bname="([^"]+)"', r'name="\1_b"', block)
+ side_b = ('\n <!-- robot B: the same robot in B\'s frame, (x, y, z) -> (-x, -y, z) -->\n'
+ ' <body name="side_b" quat="0 0 0 1">\n ' + copy + '\n </body>\n')
+ out = xml.replace(block, block + side_b)
+ out = out.replace('<mujoco model="rcb_badminton">', '<mujoco model="rcb_badminton_duel">')
+ out = re.sub(r"<!--.*?-->", "", out, count=1, flags=re.S)
+ header = ("<!--\n Robot badminton DUEL scene (render only), generated by scripts/olympiad/badminton/mk_duel_scene.py from\n"
+ " bm_scene.xml: robot A as in the match scene; robot B (names *_b, identical) the same robot in\n"
+ " a body rotated 180 degrees about z. The physics runs each robot in its own copy of bm_scene.xml (bduel.py).\n-->\n")
+ OUT.parent.mkdir(parents=True, exist_ok=True)
+ OUT.write_text(header + out.lstrip())
+ print("wrote", OUT)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/wc.py b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/wc.py
new file mode 100644
index 0000000000..eeaa2f50d9
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sim/wc.py
@@ -0,0 +1,311 @@
+"""Wall-clock helpers for the badminton match service: exact match snapshots, the stroke-planner process and the
+reference advisor (oracle mode only).
+
+Why a planner process. An `act` is planned by the stroke controller (`bm.Match.plan_racket`: deterministic multi-start
+IK, up to three candidate solutions, five robot-only twin rehearsals each), 0.15-0.26 s of CPU. Done inside the sim
+thread it would stall the world by up to 26 control steps at x1 and 2.6 at x10, beyond the 100 ms completion-lag
+bound. So the service plans OUTSIDE the sim thread and its process, without changing what the plan is:
+
+ * an act queued while the match is at step k_q takes effect at the fixed step k_e = k_q + LEAD_STEPS
+ (LEAD_STEPS = ceil(PLAN_LEAD_S / wall seconds per step), a constant of the task);
+ * at queue time the service pickles the whole match (an exact copy, MjData included; the MjModel is shared by
+ reference) and sends it to the planner process; the planner advances the copy to k_e with the command in force
+ (installing any earlier act that takes effect before k_e, from its own earlier result) and plans the stroke there,
+ exactly as `Match.rt_act` at k_e would;
+ * at k_e the sim thread compares the live state with the planner's state key at k_e and installs the plan (the
+ same attribute changes as `rt_act`). The result is bit-identical to calling `rt_act` at k_e, which is what the
+ fresh-process replay does. A key mismatch (never seen) falls back to `rt_act` in the sim thread and is counted
+ (`plan_mismatch`). If the plan is not back by k_e the sim thread waits for it; the lateness is recorded.
+
+Wire format: length-prefixed pickles over the worker's stdin/stdout (`_send` / `_recv`).
+"""
+from __future__ import annotations
+
+import hashlib
+import io
+import os
+import pickle
+import select
+import struct
+import subprocess
+import sys
+import threading
+import time
+from pathlib import Path
+
+import numpy as np
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+REVISION = "wallclock-4" # 4: the players serve (bm.Match.toss)
+SOURCE_FILES = ("bm.py", "wc.py")
+
+
+def source_sha() -> str:
+ """Fingerprint of everything that decides the match (engine, planning/installation, scene)."""
+ root = Path(HERE)
+ h = hashlib.sha256()
+ names = list(SOURCE_FILES) + [str(p.relative_to(root)) for p in sorted((root / "scene").rglob("*")) if p.is_file()]
+ for name in names:
+ h.update(name.encode()); h.update((root / name).read_bytes())
+ return h.hexdigest()
+
+
+# ---------------------------------------------------------------------------------------------- pipes
+def _send(f, obj, deadline=None) -> None:
+ b = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)
+ packet = struct.pack("<Q", len(b)) + b
+ if deadline is None:
+ view = memoryview(packet)
+ while len(view):
+ n = os.write(f.fileno(), view[:1 << 20])
+ view = view[n:]
+ return
+ offset = 0
+ while offset < len(packet):
+ remaining = deadline - time.monotonic()
+ if remaining <= 0 or not select.select([], [f], [], remaining)[1]:
+ raise TimeoutError("worker request timed out")
+ offset += os.write(f.fileno(), packet[offset:offset + 65536])
+
+
+def _read_exact(f, n, deadline=None):
+ chunks = []
+ while n:
+ if deadline is not None:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0 or not select.select([f], [], [], remaining)[0]:
+ raise TimeoutError("worker response timed out")
+ chunk = os.read(f.fileno(), min(n, 1 << 20))
+ if not chunk:
+ raise EOFError("worker closed its pipe")
+ chunks.append(chunk)
+ n -= len(chunk)
+ return b"".join(chunks)
+
+
+def _recv(f, deadline=None):
+ n = struct.unpack("<Q", _read_exact(f, 8, deadline))[0]
+ return pickle.loads(_read_exact(f, n, deadline))
+
+
+# ---------------------------------------------------------------------------------------------- snapshots
+class _Pickler(pickle.Pickler):
+ def persistent_id(self, obj):
+ import mujoco as mj
+ return "MODEL" if isinstance(obj, mj.MjModel) else None
+
+
+class _Unpickler(pickle.Unpickler):
+ def __init__(self, f, model):
+ super().__init__(f)
+ self.model = model
+
+ def persistent_load(self, pid):
+ if pid != "MODEL":
+ raise pickle.UnpicklingError(pid)
+ return self.model
+
+
+def snapshot(m) -> bytes:
+ """Exact copy of the match state for planning. Not copied: the MjModel (shared by reference), the scratch twin, and
+ the joint-target history except its last two entries (the planner reads only those, for the target velocity)."""
+ tw = m.__dict__.pop("_twin", None)
+ acts = m.s._actions
+ m.s._actions = acts[-2:]
+ try:
+ f = io.BytesIO()
+ _Pickler(f, protocol=pickle.HIGHEST_PROTOCOL).dump(m)
+ return f.getvalue()
+ finally:
+ m._twin = tw
+ m.s._actions = acts
+
+
+def restore(b: bytes, model):
+ m = _Unpickler(io.BytesIO(b), model).load()
+ m._twin = None
+ return m
+
+
+def state_key(m) -> str:
+ """Everything the stroke planner reads, hashed: physics state, command, leg and shot counters."""
+ h = hashlib.sha256()
+ h.update(m.s.state_sha().encode())
+ h.update(repr((m.k, m.plan_j, len(m.plan), m.n_our_legs, len(m.points), len(m.legs), m.leg.get("launch"),
+ m.leg.get("state"), m.done)).encode())
+ h.update(np.ascontiguousarray(m.s.target, dtype=np.float64).tobytes())
+ if len(m.s._actions) >= 2:
+ h.update(np.ascontiguousarray(m.s._actions[-2], dtype=np.float64).tobytes())
+ qa = getattr(m, "_q_hit_active", None)
+ if qa is not None:
+ h.update(np.ascontiguousarray(qa, dtype=np.float64).tobytes())
+ if m.plan_j < len(m.plan):
+ h.update(np.ascontiguousarray(np.asarray(m.plan[m.plan_j:]), dtype=np.float64).tobytes())
+ return h.hexdigest()
+
+
+# ---------------------------------------------------------------------------------------------- plan / install
+def plan_on(m, dec: dict) -> dict:
+ """What `Match.rt_act` / `rt_clear` would do at the current step of m (a copy), as an installable result."""
+ if dec["type"] == "none":
+ return {"type": "none"}
+ import bm
+ T = float(dec["t"])
+ t_hit = (m.k - m.leg["launch"]) * bm.CONTROL_DT + T
+ ik_seed = getattr(m, "_q_hit_active", None) if m.plan_j < len(m.plan) else None
+ m._ik_seed = ik_seed
+ plan, info = m.plan_racket(t_hit, dec["pos"], dec["normal"], dec["vel"])
+ q_hit = info.pop("_q_hit", None)
+ info["T_from_now"] = round(T, 4)
+ return {"type": "act", "plan": plan, "q_hit": q_hit, "info": info, "ik_seed": ik_seed,
+ "swing_last": getattr(m, "_swing_last", None)}
+
+
+def install(m, res: dict) -> dict | None:
+ """Apply a planned result to m with exactly the attribute changes of `Match.rt_act` (or `rt_clear`)."""
+ if res["type"] == "none":
+ m.rt_clear()
+ return None
+ m._ik_seed = res["ik_seed"]
+ if res["swing_last"] is not None:
+ m._swing_last = res["swing_last"]
+ info = res["info"]
+ if res["plan"]:
+ m.plan, m.plan_j = res["plan"], 0
+ m._q_hit_active = res["q_hit"]
+ m.shots.append({"k": m.k, "leg": m.n_our_legs, **info})
+ m._last_act = info
+ return info
+
+
+def apply_inline(m, dec: dict) -> dict | None:
+ """The reference semantics (also the replay's): plan and apply at the current step."""
+ if dec["type"] == "none":
+ m.rt_clear()
+ return None
+ return m.rt_act(dec["t"], dec["pos"], dec["normal"], dec["vel"])
+
+
+# ---------------------------------------------------------------------------------------------- worker process
+def _worker(conn_in, conn_out) -> None:
+ import bm
+ model = bm.Phys().m
+ cache: dict = {} # act_id -> (k_e, result), the planner's earlier results (for later forks)
+ _send(conn_out, "ready")
+ while True:
+ try:
+ job = _recv(conn_in)
+ except EOFError:
+ return
+ t0 = time.monotonic()
+ try:
+ m = restore(job["snap"], model)
+ t1 = time.monotonic()
+ if job["op"] == "plan":
+ k_e = int(job["k_e"])
+ pend = [(cache[i][0], i) for i in job.get("pending", []) if i in cache]
+ applied = set()
+ status = "ok"
+ while True:
+ for ke, i in pend:
+ if ke == m.k and i not in applied and cache[i][1] is not None:
+ install(m, cache[i][1]); applied.add(i)
+ if m.k >= k_e:
+ break
+ n0 = len(m.points)
+ m.rt_advance(1)
+ if len(m.points) > n0 or m.done:
+ status = "dropped"
+ break
+ t2 = time.monotonic()
+ out = {"act_id": job["act_id"], "status": status, "fork_steps": int(m.k - job["k_q"]),
+ "unpickle_ms": round((t1 - t0) * 1e3, 2), "fork_ms": round((t2 - t1) * 1e3, 2)}
+ if status == "ok":
+ out["key"] = state_key(m)
+ res = plan_on(m, job["dec"])
+ out["res"] = res
+ cache[job["act_id"]] = (k_e, res)
+ else:
+ cache[job["act_id"]] = (k_e, None)
+ out["plan_ms"] = round((time.monotonic() - t2) * 1e3, 2)
+ for i in sorted(cache)[:-64]:
+ cache.pop(i)
+ elif job["op"] == "advise":
+ import oracle_ref
+ out = oracle_ref.advise(m)
+ out["unpickle_ms"] = round((t1 - t0) * 1e3, 2)
+ out["advice_ms"] = round((time.monotonic() - t1) * 1e3, 2)
+ else:
+ raise ValueError(f"unknown job {job.get('op')}")
+ out["worker_ms"] = round((time.monotonic() - t0) * 1e3, 2)
+ _send(conn_out, ("ok", out))
+ except Exception as exc: # noqa: BLE001
+ import traceback
+ traceback.print_exc()
+ _send(conn_out, ("error", {"act_id": job.get("act_id"), "error": repr(exc)[:300]}))
+
+
+class Worker:
+ """A planner / advisor child process. `submit` is asynchronous (results arrive through `on_result` from a reader
+ thread); `call` is synchronous (one request at a time)."""
+
+ def __init__(self, name: str, on_result=None):
+ self.name = name
+ self.proc = subprocess.Popen([sys.executable, os.path.abspath(__file__), "worker"], stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE, cwd=HERE, env=dict(os.environ))
+ self.fin, self.fout = self.proc.stdout, self.proc.stdin
+ if _recv(self.fin, time.monotonic() + 120) != "ready":
+ raise RuntimeError(f"{name} worker handshake failed")
+ self.on_result = on_result
+ self.lock = threading.Lock()
+ self.jobs: "list" = []
+ self.cv = threading.Condition()
+ if on_result is not None:
+ threading.Thread(target=self._sender, daemon=True).start()
+ threading.Thread(target=self._reader, daemon=True).start()
+
+ def submit(self, job: dict) -> None:
+ with self.cv:
+ self.jobs.append(job)
+ self.cv.notify()
+
+ def _sender(self):
+ while True:
+ with self.cv:
+ while not self.jobs:
+ self.cv.wait()
+ job = self.jobs.pop(0)
+ try:
+ _send(self.fout, job)
+ except Exception as exc: # noqa: BLE001
+ self.on_result(("error", {"act_id": job.get("act_id"), "error": repr(exc)[:300]}))
+
+ def _reader(self):
+ while True:
+ try:
+ msg = _recv(self.fin)
+ except Exception as exc: # noqa: BLE001
+ self.on_result(("dead", {"error": repr(exc)[:300]}))
+ return
+ self.on_result(msg)
+
+ def call(self, job: dict, timeout_s: float):
+ deadline = time.monotonic() + timeout_s
+ if not self.lock.acquire(timeout=timeout_s):
+ raise TimeoutError(f"{self.name} worker busy")
+ try:
+ _send(self.fout, job, deadline)
+ st, out = _recv(self.fin, deadline)
+ if st != "ok":
+ raise RuntimeError(out.get("error"))
+ return out
+ finally:
+ self.lock.release()
+
+
+if __name__ == "__main__" and sys.argv[1:] == ["worker"]:
+ sys.path.insert(0, HERE)
+ proto_out = os.fdopen(os.dup(1), "wb") # the protocol keeps the real stdout; anything printed goes to stderr
+ os.dup2(2, 1)
+ sys.stdout = sys.stderr
+ _worker(sys.stdin.buffer, proto_out)
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sport.toml b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sport.toml
new file mode 100644
index 0000000000..8be6f85df7
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/environment/sim/sport/sport.toml
@@ -0,0 +1,200 @@
+# badminton: robot singles badminton in real time (docs/framework_zh.md §4.2, §8). Migrated from the legacy tree in
+# stage 3 (scripts/olympiad/badminton, scripts/olympiad/shared/badminton; sim/bm.py: court, shuttle, robot, stroke
+# controller, scripted opponent, referee; sim/bduel.py: the two-robot match; sim/wc.py: the legacy planner's exact
+# snapshots and plan installation). The physics (shuttle drag, racket contact law, robots) is the legacy one; the
+# serve is not: since 2026-10-07 the players' robots serve by the BWF service laws (D2, D4, D6, D7; README), so the
+# legacy machine-serve recordings no longer apply and were retired from the golden set. The format names keep the
+# legacy task names (badminton-match-wallclock-program-standard, badminton-duel-wallclock-program-standard).
+
+[sport]
+name = "badminton"
+title = "Robot badminton"
+summary = "robot singles badminton on a regulation court in real time (slowed down): a Franka Panda arm with a racket on an x-y sliding base, a point-mass shuttle with high quadratic drag (terminal speed 6.8 m/s) and no bounce, a racket contact law; first to 5 points, rally scoring; the players' robots serve (the rally winner serves next): the server tosses the shuttle (from rest or rising up to 0.5 m) at a point it chooses and hits it underhand, below 1.15 m, into the diagonal service court; format match-wallclock: you against a scripted computer opponent (levels 1-2, `game spec` match.opponent_level), format duel-wallclock: two players"
+protocol = "realtime"
+revision = "badminton-wallclock-5+duel-7+core-0.2" # bump on any change that alters play (4/6: the players serve; 5/7: the players' images draw the arms with the Franka Panda's 25k visual meshes)
+physics = "mujoco (robots, PD-controlled joints at 1 ms) + a point-mass shuttle with quadratic drag integrated at 1 ms (sim/bm.py)"
+image = "ghcr.io/mll-lab-nu/eai-olympiad:0.1.0"
+status = "sport"
+publish = true
+category = "robotics-sports-arena"
+
+[rulebook]
+name = "BWF Laws of Badminton (BWF Statutes, Section 4.1, version 5.0)"
+version = "2025-04-26"
+url = "https://extranet.bwf.sport/docs/document-system/81/1466/1470/Section%204.1%20-%20Laws%20of%20Badminton%20-%2026%20April%202025%20V5.0%20(2)%20.pdf"
+
+[[deviations]]
+id = "D1"
+rule = "7"
+text = "one short game: first to 5 points, from 4-4 a two-point lead is needed, at most 7 (6-6: the next point wins) instead of best of three games to 21 (cap 30); the match also ends after 300 hits (both sides) or 40 points played (lets included): the player ahead wins, at equal points the winner of the last point"
+affects_result = true
+[[deviations]]
+id = "D2"
+rule = "9.1.5-9.1.8"
+text = "the robot has no free hand to hold and drop the shuttle: the server tosses it with the command toss {pos: [x, y, z], height: H} (the common racket-sport toss, docs/conventions/racket_serve_zh.md): when the command takes effect the shuttle appears at that point (0.5-1.8 m high, within 1.0 m horizontally of the server's base, on its half) and is released from rest (H = 0) or projected straight up to rise H (at most 0.5 m; the Laws do not forbid a small toss); until then it is held beside the server. The toss has no spin (a point mass has none, Law 9.1.5). Judged: the server's racket must hit it (a miss is a fault, Law 9.1.8), with the shuttle below 1.15 m at the hit (Law 9.1.6, judged at the shuttle's point: it has no size) and leaving the racket upwards (Law 9.1). Not judged: the racket hitting the base of the shuttle first and moving forwards throughout the service (Laws 9.1.5, 9.1.7)"
+affects_result = true
+[[deviations]]
+id = "D3"
+rule = "13.3-13.4"
+text = "the shuttle is a point mass: a crossing of the net plane below the net top (between the posts) is a fault of the hitter; touching the net or reaching over it is not judged; a racket meets the shuttle only on its own half and only when it is that player's turn (no double hits)"
+affects_result = true
+[[deviations]]
+id = "D4"
+rule = "9.1.3-9.1.4"
+text = "before every serve the referee puts both robots at rest in the ready pose at a fixed spot in their service courts (diagonally opposite: the right courts when the server's score is even, Law 10.1): x = +0.3 (right court) or -0.3 (left court), y = -4.0 in each robot's frame; the spot is the robot's home for the point (where its base returns between strokes). Standing still (Law 9.1.4) is judged on the base: a base more than 5 cm from its spot before the serve is delivered (hit, or faulted) is that player's fault; both at once: a let (Law 14.2.2). The base moves within |x| <= 3.25, -7.5 <= y <= -0.5 at up to 6 m/s and 20 m/s^2"
+affects_result = true
+[[deviations]]
+id = "D5"
+rule = "-"
+text = "the last resort of the no-draw rule (equal points at the match limit and no point won) is not from the rulebook: the player who received first wins (format match-wallclock: the opponent)"
+affects_result = true
+[[deviations]]
+id = "D6"
+rule = "9.1.1, 16.6-16.7"
+text = "undue delay has a fixed limit: the server must toss the shuttle within 3 s after the receiver is ready (1 s after play resumes, Law 9.4), else it is a service fault (the receiver's point); a player's third such fault disqualifies it (it loses the match) instead of the umpire's warning and the referee's discretion (Laws 16.7.1-16.7.2)"
+affects_result = true
+[[deviations]]
+id = "D7"
+rule = "6"
+text = "no toss: format duel-wallclock: the runner plays both orders of the first server (match.first_server); format match-wallclock: you serve the first point"
+affects_result = true
+
+[formats.match-wallclock] # one model seat against the scripted opponent inside the world (bm.Match)
+seats = ["A"]
+opponent = true # success = winning a valid match (core/grading.py), as in the legacy task
+levels = [1, 2] # the opponent level (RCB_LEVEL; default 1)
+[formats.duel-wallclock] # two seats (bduel.World), mirrored: each plays in its own frame
+seats = ["A", "B"]
+first = ["A", "B"] # the first server (Law 6, D7); the runner plays both orders
+
+[modes]
+action_levels = ["high", "low"] # high: the racket command `act` (lowered to joint targets); low: joint targets
+plays = ["program"]
+
+[timing]
+slowdown = 20 # the legacy default (RCB_SLOWDOWN; official 1, 2, 5, 10, 20)
+start_timeout_s = 1800 # the second seat may start up to 30 min after the first (legacy START_TIMEOUT_S)
+ready_timeout_s = 300 # each review after a point (legacy READY_TIMEOUT_S), else the late side loses
+
+[actions.cli] # `game none`; act takes vectors: `game act '{"type": "act", "t": 0.8, ...}'`
+high = { none = [] }
+low = { none = [] }
+
+[observation]
+fields = ["score", "point", "ball", "t_since_played", "heard", "robot_base_xy", "q_arm", "racket_pos", "racket_normal",
+ "ball_in_play", "ball_state", "serve_in_s", "you_receive_serve", "serve", "command", "pending_commands",
+ "last_points", "last_shots", "opponent_level", "q_target", "you_serve"]
+renderer = "mujoco" # the sport draws its own views (the legacy 2 x 4 tiles, MuJoCo; plugin.Views)
+frame_budget_ms = 4000 # one observation, 8 tiles of 480 x 360 (CPU osmesa, a loaded host)
+columns = 4
+# Since wallclock-5 / duel-7 the arms are drawn with the Franka Panda's visual meshes (presentation/
+# presentation.toml players = "25k", bundled into the simulator; renderer rule 6). Measured 2026-10-08 (observations
+# with new tiles, 30 control steps apart, osmesa, 6 CPUs, host load ~8-10 on 32 cores), median / p95 ms per observation
+# at 2 llvmpipe threads: match scene 137 / 171 (duel 142 / 190), 25k meshes 154 / 195 (duel 192 / 220); 1 thread:
+# 223 / 255 (223 / 249) and 254 / 281 (303 / 357)
+render_threads = 2 # llvmpipe threads per render process (LP_NUM_THREADS); one render process per seat
+sim_cpus = 6 # the sim container: 2 seats x 2 render threads + the world, the planners and the core
+
+[spec] # the rule constants (the simulator's values; tests/test_badminton.py checks them)
+match = "first to 5 points (rally scoring); from 4-4 a player must lead by 2, and at 6-6 the next point wins (at most 7); the match also ends after 300 hits (both sides) or 40 points played (replayed lets included): then the player with more points wins, at equal points the player who won the last point"
+play = "there is no bounce: hit the shuttle before it reaches the floor. Your shot is good if your racket meets the shuttle once, on your half, and the shuttle passes over the net and lands in your opponent's singles court (lines are in); after your hit your racket no longer touches it. You lose the point if your shot goes into the net (crosses the net plane below the top), comes down on your own side or lands out, or if a shuttle that is yours to hit lands in your court; an opponent's shot that would land out of your court wins you the point, so you may let it go. Serves (BWF Law 9): the winner of a rally serves the next point (after a let the same server; state.you_serve, state.serve). Before every serve both robots are put at rest in the ready pose at their spots: x = +0.3 in the right service court or -0.3 in the left one, y = -4.0 (your frame); both stand in their right courts when the server's score is even, else in their left ones (diagonally opposite); the spot is your base's home for the point. From 1 s after play resumes (the receiver is ready; state.serve.phase 'open') the server has 3 s to toss the shuttle with {'type':'toss','pos':[X,Y,Z],'height':H}: when the command takes effect (the same lead as an act) the shuttle appears at that point (0.5 <= Z <= 1.8, within 1.0 m horizontally of your base, Y <= -0.5) and is released from rest (H = 0 or omitted) or rises H straight up (0 <= H <= 0.5) before it falls (until then it is held beside the server). Then hit it with your racket (an act, which you may send before the toss): the serve is good if your racket meets the shuttle below 1.15 m, the shuttle leaves the racket upwards, passes over the net and lands in the receiver's diagonally opposite service court (between its short service line and its back line, lines in) or is returned. It is the server's fault (the receiver's point) if it does not toss the shuttle in time (undue delay; the third time disqualifies the player: it loses the match), misses the shuttle, hits it above 1.15 m or not upwards, or the serve hits the net or lands outside that court. Both bases must stay within 5 cm of their spots until the serve is hit (or faulted): a base moving earlier is that player's fault (both at once: a let, replayed)"
+opponent = "format match-wallclock: a scripted computer opponent. You serve the first point; the opponent serves when it won the last rally: from its service court at 1.05 m, upwards, high and deep or short into your diagonal service court, always within your reach (level 1: 70 % high serves, towards the middle of the court; level 2: 50 % high, wider and closer to the short service line); it stands still in its service court while you serve. It never makes an unforced error: it returns every shuttle it can reach, into your court and within your reach; shuttles far from it or fast beat it; level 2 reacts and moves faster and reaches further than level 1"
+world = "metres; your own frame: x to your right, y towards the opponent, z up. Floor z = 0; singles court |x| <= 2.59, |y| <= 6.70 (lines in); the net is the plane y = 0 with its top at z = 1.524 (posts at x = +-3.05); short service lines at |y| = 1.98; the centre line x = 0 divides each half into a right and a left service court. Your half is y < 0"
+robot = "a Franka Panda arm on a 1.0 m pedestal whose base slides on rails (|bx| <= 3.25, -7.5 <= by <= -0.5, up to 6 m/s and 20 m/s^2; home: the point's spot (+-0.3, -4.0), see play); the racket head centre is 0.56 m beyond the flange; the string face is a disc of radius 0.14 m. The racket meets shuttles 0.4-2.5 m above the floor; overhead contacts (1.8-2.5 m) allow the fastest, steepest shots"
+shuttle = "a point mass under gravity (9.81 m/s^2) and quadratic air drag, dv/dt = g - K |v| v with K = 0.212 per metre (terminal speed 6.8 m/s): hit at 40 m/s it slows to about 10 m/s within 0.3 s, and a high shuttle falls almost vertically at close to 6.8 m/s. No spin, no wind, no bounce"
+racket_contact = "the racket meets the shuttle when the shuttle's centre crosses the string plane within 0.14 m of the head centre; the shuttle leaves exactly along the face normal n (the side the head moves towards, relative to the shuttle) at the speed 20 max(0, v_head.n) (1 - 0.3 (r/0.14)^2) + 0.15 max(0, -v_in.n), where v_head is the head velocity, r the contact's distance from the head centre and v_in the shuttle's incoming velocity; the rest of the head and incoming velocity is lost. A head speed along the normal of 0.5 m/s gives about 10 m/s, 2 m/s about 40 m/s; the arm manages up to about 2.4 m/s"
+act = "high level: {'type':'act','t':T,'pos':[PX,PY,PZ],'normal':[NX,NY,NZ],'vel':[VX,VY,VZ]}: the racket's state at contact, T s after the act takes effect: the head centre, the string-face normal and the head velocity (m/s). Limits: 0 < T <= 5, |x| <= 3.4, -7.5 <= y <= -0.3, 0.2 <= z <= 3.0, speed <= 8 m/s. The act takes effect `act.lead_steps` control steps after the step at which it arrives (`game spec`; the stroke is planned meanwhile) and replaces the stroke under way; until then the robot keeps its current command. The controller drives the base to stand for a forehand at the contact point (or as far as it gets in time) and swings the arm under the joint speed limits; it knows nothing about the shuttle. The delivered state scatters by about 6 mm, 0.8 degrees and 3 % (seeded; format duel-wallclock: both robots draw from one sequence, the n-th act of each robot gets the same scatter). {'type':'none'} cancels the stroke (the robot returns to its ready pose, the base to its spot), with the same lead; {'type':'toss','pos':[X,Y,Z],'height':H} tosses the shuttle for your serve (see play), with the same lead"
+lowlevel = "low level: {'type':'traj','q':[[base_x, base_y, q1..q7], ...]}: joint targets, one per 10 ms control step from the next step on (then the robot returns to its ready pose and the base to its spot), each within the joint ranges and speed limits of `game spec` joints; none and serve as above, at the next step"
+observation = "a PNG of 2 rows x 4 columns of 480 x 360 tiles: row 1 a camera behind and above your base line looking down the court, row 2 a camera at the side of the court (x < 0) looking along +x (your half on the right); the columns are frames 60 ms apart, newest on the right, with each frame's step and game time (view_steps, view_sim_times). No shuttle coordinates: the shuttle is drawn enlarged, an orange cork (12 cm ball centred on its position) with a white skirt behind it. `game spec` gives both cameras' poses and intrinsics (pinhole, 45 degree vertical field of view, focal length 434.6 px, principal point at the tile centre). The state gives your robot (robot_base_xy, q_arm, racket_pos, racket_normal), what you heard (tosses, serves and hits, with their times), whether the shuttle is coming to you, and the serve: you_serve, serve.court (right or left), serve.phase (waiting: the receiver is getting ready; open: the server may toss; tossed; done: the serve was delivered), serve.opens_in_s and serve.deadline_in_s for the server, serve.tossed_at_step; a point lost by a service fault says 'serve_fault:<reason>: ...' (undue_delay, missed, too_high, not_upwards, net, out, moved), the receiver's early move 'receive_fault:moved: ...'"
+duel = "format duel-wallclock: another agent controls an identical robot across the net; in each player's frame its own half is y < 0. match.first_server serves the first point; then the winner of each rally serves (both players serve by the same rules, see play)"
+
+[tiebreaks]
+order = ["disqualification", "score", "last_point", "first_receiver"]
+text = "a player disqualified for repeated undue delay (its third serve not tossed in time) loses; else first to 5 points (from 4-4 by 2, at most 7); at the match limit (300 hits or 40 points played) the player with more points; at equal points the player who won the last point that was not a let; then (last resort, not from the rulebook) the player who received first (format match-wallclock: the opponent)"
+last_resort_in_prompt = true
+
+[[exploits]]
+id = "E1"
+text = "an out-of-range, non-finite or malformed command is refused (HTTP 400) and changes nothing"
+test = "test_exploit_bad_commands_are_refused"
+[[exploits]]
+id = "E2"
+text = "low-level joint targets outside the joint ranges or faster than the joint speed limits are refused when they would take effect and change nothing"
+test = "test_exploit_joint_limits"
+[[exploits]]
+id = "E3"
+text = "acts cannot be stacked: a command sent before the previous act took effect is refused (HTTP 409)"
+test = "test_exploit_no_stacked_acts"
+[[exploits]]
+id = "E4"
+text = "the observation holds no shuttle position or velocity and no opponent state (only the images, what was heard and the player's own robot); the legacy privileged /oracle endpoint is gone"
+test = "test_exploit_no_shuttle_state_in_observation"
+[[exploits]]
+id = "E5"
+text = "doing nothing gains nothing: a player who never hits loses the points it receives, and a player who never serves faults on every serve (undue delay): it loses the match"
+test = "test_exploit_idle_loses"
+[[exploits]]
+id = "E6"
+text = "a racket meets the shuttle only on its own half and only on its turn: a robot standing at the net cannot hit the opponent's shot before it crosses, and cannot hit twice"
+test = "test_exploit_no_reach_over_or_double_hit"
+[[exploits]]
+id = "E7"
+text = "the rule constants the players are told (/spec, [spec]) are the simulator's"
+test = "test_exploit_spec_is_the_simulator"
+[[exploits]]
+id = "E8"
+text = "a lowered act replays exactly: the episode holds the low-level joint targets (planned by the legacy stroke controller at the effect step), and a fresh replay reproduces the live state"
+test = "test_exploit_lowered_act_replays"
+[[exploits]]
+id = "E9"
+text = "the serve is judged by the service laws: only the server tosses the shuttle, once per serve, from the step the receiver is ready, within the toss limits (else refused); a miss, a hit above 1.15 m or not upwards, a serve into the net or outside the diagonal service court is the server's fault; a base leaving its spot before the serve is that player's fault; the rally winner serves next from the court of its score's parity"
+test = "test_exploit_serve_rules"
+[[exploits]]
+id = "E10"
+text = "never serving does not pay: a player who wins rallies but never tosses the shuttle is disqualified at its third undue-delay fault and loses, even when ahead on points"
+test = "test_exploit_never_serving_is_disqualified"
+
+[players]
+reference = "reference" # camera-only (the legacy duel's cam_player.py) + a scripted serve: wins the default configuration
+reference_class = "builtin_players:Reference"
+check = [] # the generic tests play the reference only (each match draws thousands of tiles)
+
+[fairness]
+policy = "reference"
+matches_per_order = 20 # N = 40 (the minimum): one in-process duel takes minutes (planning + tiles);
+ # a realtime sport's wide interval only warns
+max_advantage_pp = 5
+mirror = "statistical" # seats are mirrored worlds (one shared scatter sequence; the players serve, the first server alternates)
+
+[official]
+seeds = [1, 2, 3, 101, 111, 121, 202, 212, 222] # duel: 1-3; match: the legacy level seeds (L1 101-121, L2 202-222)
+levels = [1, 2]
+slowdowns = { program = [1, 2, 5, 10, 20] }
+first_any = true
+
+[golden]
+episodes = "golden" # recorded under the player-serve rules; the legacy machine-serve records are retired (README)
+
+[[tasks]]
+format = "match-wallclock"
+action_level = "high"
+id = "badminton-match-wallclock-program-standard" # the legacy task name
+[[tasks]]
+format = "duel-wallclock"
+action_level = "high"
+id = "badminton-duel-wallclock-program-standard" # the legacy task name
+
+[capabilities] # docs/capabilities_zh.md §6
+a1 = 2 # the shuttle's flight only from the camera images (rays, a flight fit)
+a2 = 2 # high drag: the shuttle's flight, the racket contact law
+a3 = 2 # a robot arm on a sliding base, a stroke under joint limits and scatter
+a4 = 2 # real time: the shuttle does not wait; the act lead
+b1 = 1 # the scoring, service (who serves, courts, toss, faults) and fault rules, the match limit
+b2 = 2 # placement against the opponent (deep corners, short), reading its position
+b3 = 0
+physics = ["drag"] # high-drag flight (docs/capabilities_zh.md §6: 高阻力飞行); the shuttle has no
+ # spin and no bounce in this simulator, so spin_bounce is not tested
+
+[check] # tools/check limits: an in-process duel takes 6-15 min (planning + 2 seats' tiles)
+stage_timeout_s = 36000 # stage 2 (~25 in-process matches) and stage 4 (40 duels, serial) take hours
+live_player_timeout_s = 4500 # the live duel at x20 took 1888 s of 3000
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/instruction.md b/tasks/roboolympics-badminton-match-i00-standard-realtime/instruction.md
new file mode 100644
index 0000000000..c60a92f239
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/instruction.md
@@ -0,0 +1,91 @@
+# Badminton: a match against a scripted opponent, in real time
+
+You play robot singles badminton (BWF rules with the deviations below) against a scripted opponent: a MuJoCo Franka Panda on a 1 m pedestal whose base slides on rails, holding a racket, seen only through two cameras. Rally scoring; you serve the first point, then the winner of each rally serves. One game to 5 points.
+
+**Your goal: win the match.** The task succeeds if the match finishes and you won it. Keep your scripts, logs and notes
+in `/app/output/`; there is nothing else to hand in: the simulator records the match.
+
+## Time does not stop
+- The world runs at 1/10 of real speed (`spec()["timing"]["slowdown"]` = 10): one 10 ms control
+ step of game time every 0.1 s of wall time. It never waits for you: while you think, the opponent
+ plays on and your robot keeps executing its last command.
+- The match starts paused. Its clock starts at your first `submit` or `get_obs(seconds > 0)`, and from then on it runs
+ until the match is over. Look at the cameras and read `spec()` first (`get_obs(seconds=0)` does not start the clock).
+- **Breaks.** After every point the match stands still for 12 s of game time (120 s of wall time):
+ the clock keeps running, nothing moves and nothing scores, and play resumes by itself at the end of the break. Use it
+ to look at what happened and fix your program. Send a `ready` row to resume earlier (put your review, why you won or
+ lost the point and what you change, in `submit`'s `note`). Commands planned for steps inside a break are dropped.
+- You have 7200 s in all. **If your session ends before the match is over, you lose** (success 0); so
+ start the match well before your time runs out and stay until it is over (`meta["done"]`).
+- No reset: one match is the whole episode.
+
+## Write a program
+A model response takes seconds, a point only a few seconds of game time, so play with a program of your own: it
+observes, measures in the images, computes its next command and submits it, in a loop, without a new model response
+for each action. Run it in the background, watch its log, and stop, fix and restart it whenever needed (also during the
+match). Use only the camera images, the service's replies and this document: no simulator internals or hidden state.
+
+## Interface
+The client is installed: `from rcb_client import Robot, EpisodeOver` (`/opt/tools/rcb_client.py`, on `PYTHONPATH`;
+its docstring is the reference). Your container has Python 3.12 with numpy, SciPy, Pillow, requests and
+opencv-python-headless; no internet except your model's API.
+
+```python
+r = Robot() # connects to the simulator, waits until it is ready
+spec = r.spec() # the facts: action_types, cameras, proprio_layout, rules, break, timing
+res = r.get_obs(seconds=0) # now, at once: res.last[cam] (H x W x 3 uint8), res.proprio (rows)
+res = r.get_obs(seconds=0.12, video_fps=25, video="frames") # watch 0.12 s of game time: res.frames[cam] (N x H x W x 3)
+r.submit("stroke", [row]) # a command: answers at once; it takes effect at the next control step
+r.submit("ready", [[0]], note="WHY ... PLAN ...") # during a break: resume now
+```
+
+- `get_obs(cameras=None, seconds=0, video_fps=10, video="frames")`: `seconds=0` returns the current images and one
+ proprio row; `seconds > 0` (at most `spec()["max_watch_s"]`) waits while that much game time runs and returns the
+ frames the cameras saw (one every 1/`video_fps` s) and one proprio row per frame. `cameras=[]`: proprio only.
+- `submit(type, rows, at=None, note="")`: one command per row; the rows become the plan from control step `at` (the
+ next step by default; `meta["control_steps"]` is the next step's number), replacing whatever was planned from there.
+ A row takes effect at its step: the command is checked and planned there, from the state of that step. Rows for
+ steps that are already gone when the request arrives are dropped (`meta["late_steps"]`); out-of-range values are
+ clipped (`meta["clipped"]`); a command the rules refuse at its step (e.g. a toss when it is not your serve) changes nothing and
+ counts in the proprio column `commands_refused`.
+- `res.meta`: `control_steps`, `sim_time_s`, `time_left_s`, `done`, `reason`, `running`, `lag_s`, and `proprio`
+ (`layout`, `now`). `EpisodeOver` is raised once the match is over.
+
+Your commands (`spec()["action_types"]`):
+
+| type | row | what it does |
+|---|---|---|
+| `stroke` | `[t, x, y, z, nx, ny, nz, vx, vy, vz]` | the racket head's state at contact, `t` seconds after the command takes effect: head centre `x y z` (m), string-face normal `nx ny nz`, head velocity `vx vy vz` (m/s). It takes effect `spec()["rules"]["act"]["lead_steps"]` control steps after its row's step (4 at S = 10: the planning time; `stroke_pending_effect_step` shows it) and `t` counts from then; the service plans the swing and the base's move, then the robot returns to its ready pose and the base home. A stroke, toss or rest planned before the previous one took effect is refused. Limits: 0 < t <= 5, \|x\| <= 3.4, -7.5 <= y <= -0.3, 0.2 <= z <= 3.0, speed <= 8 m/s (clipped) |
+| `toss` | `[x, y, z, height]` | your serve's toss: the shuttle appears at `x y z` (your half, y <= -0.5, 0.5-1.8 m high, within 1.0 m of your base horizontally) when the command takes effect (the same lead), from rest or rising `height` (0-0.5 m) straight up. Only the server, once per serve, once the receiver is ready (`serve_phase` 1, open). Then hit it with a stroke (it may be sent before the toss); the serve rules are in `spec()["rules"]["serve"]` |
+| `rest` | `[0]` | cancel the stroke under way (the same lead) |
+| `ready` | `[0]` | end the break now (see Time) |
+
+Proprioception and the referee's information (`spec()["proprio_layout"]`, one float row per frame; NaN = not
+applicable now; times in game seconds, positions in metres in your frame): `match_step`, `break`, `break_left_s`, `finished`; `score_you`, `score_opponent`, `point`; the serve: `you_serve`, `serve_court_right`, `serve_phase` (0 waiting: the receiver is getting ready, 1 open: toss now, 2 tossed, 3 done), `serve_opens_in_s`, `serve_deadline_in_s` (toss before it: an undue delay is a fault), `serve_tossed_at_step`; the shuttle: `ball_kind` (0 the opponent's serve, 1 your serve, 2 the opponent's return), `t_since_played` (seconds since it was played: served, tossed or hit; NaN before), `ball_in_play`, `ball_not_served`, `ball_tossed` (yours to hit), `ball_coming`, `ball_going`; your robot: `base_x`, `base_y`, `q1`..`q7`, `racket_x/y/z`, `racket_nx/ny/nz`; the stroke under way: `stroke_active`, `stroke_contact_in_s`, `stroke_traj_steps_left`, `stroke_pending_effect_step` (a stroke, toss or rest waiting for its effect step, NaN if none), `stroke_head_speed_limited`, `stroke_pose_not_delivered` (the planner's notes); `last_point_won`; `commands_applied`, `commands_refused`, `last_refused_step`.
+
+Cameras: two cameras, 480 x 360 RGB each: `behind` (behind and above your base line, looking down the court) and `side` (at the side of the court, x < 0, looking along +x: your half is on the right). Pose, field of view (45 degrees), `focal_px` and `principal_point_px` in `spec()["cameras"]`. The shuttle is drawn enlarged: an orange cork (a 12 cm ball centred on its position) with a white skirt behind it; yellow marks every 1 m outside the singles side lines and behind the base lines. Each image is stamped with the match step `k` and the shuttle's clock `t`.
+
+Four frames 60 ms apart (`get_obs(seconds=0.18, video_fps=17, video="frames")`) with the two cameras let you triangulate the shuttle and fit its flight (gravity and quadratic drag, `spec()["rules"]["shuttle"]`).
+
+## Rules
+The rule texts come from RoboOlympics' `sport.toml`. Where they name RoboOlympics' own interface (`{'type': 'act', ...}`, `{'type': 'toss', ...}`, `{'type': 'none'}`, `{'type': 'target', ...}`, `state.*`, `game spec`, `/spec`), read: your `stroke`, `toss`, `rest`, `mallet` and `stop` rows, the proprio columns and `spec()`; where they say the world freezes for reviews, read: the break.
+
+- `match`: first to 5 points (rally scoring); from 4-4 a player must lead by 2, and at 6-6 the next point wins (at most 7); the match also ends after 300 hits (both sides) or 40 points played (replayed lets included): then the player with more points wins, at equal points the player who won the last point
+- `play`: there is no bounce: hit the shuttle before it reaches the floor. Your shot is good if your racket meets the shuttle once, on your half, and the shuttle passes over the net and lands in your opponent's singles court (lines are in); after your hit your racket no longer touches it. You lose the point if your shot goes into the net (crosses the net plane below the top), comes down on your own side or lands out, or if a shuttle that is yours to hit lands in your court; an opponent's shot that would land out of your court wins you the point, so you may let it go. Serves (BWF Law 9): the winner of a rally serves the next point (after a let the same server; state.you_serve, state.serve). Before every serve both robots are put at rest in the ready pose at their spots: x = +0.3 in the right service court or -0.3 in the left one, y = -4.0 (your frame); both stand in their right courts when the server's score is even, else in their left ones (diagonally opposite); the spot is your base's home for the point. From 1 s after play resumes (the receiver is ready; state.serve.phase 'open') the server has 3 s to toss the shuttle with {'type':'toss','pos':[X,Y,Z],'height':H}: when the command takes effect (the same lead as an act) the shuttle appears at that point (0.5 <= Z <= 1.8, within 1.0 m horizontally of your base, Y <= -0.5) and is released from rest (H = 0 or omitted) or rises H straight up (0 <= H <= 0.5) before it falls (until then it is held beside the server). Then hit it with your racket (an act, which you may send before the toss): the serve is good if your racket meets the shuttle below 1.15 m, the shuttle leaves the racket upwards, passes over the net and lands in the receiver's diagonally opposite service court (between its short service line and its back line, lines in) or is returned. It is the server's fault (the receiver's point) if it does not toss the shuttle in time (undue delay; the third time disqualifies the player: it loses the match), misses the shuttle, hits it above 1.15 m or not upwards, or the serve hits the net or lands outside that court. Both bases must stay within 5 cm of their spots until the serve is hit (or faulted): a base moving earlier is that player's fault (both at once: a let, replayed)
+- `opponent`: format match-wallclock: a scripted computer opponent. You serve the first point; the opponent serves when it won the last rally: from its service court at 1.05 m, upwards, high and deep or short into your diagonal service court, always within your reach (level 1: 70 % high serves, towards the middle of the court; level 2: 50 % high, wider and closer to the short service line); it stands still in its service court while you serve. It never makes an unforced error: it returns every shuttle it can reach, into your court and within your reach; shuttles far from it or fast beat it; level 2 reacts and moves faster and reaches further than level 1
+- `world`: metres; your own frame: x to your right, y towards the opponent, z up. Floor z = 0; singles court |x| <= 2.59, |y| <= 6.70 (lines in); the net is the plane y = 0 with its top at z = 1.524 (posts at x = +-3.05); short service lines at |y| = 1.98; the centre line x = 0 divides each half into a right and a left service court. Your half is y < 0
+- `robot`: a Franka Panda arm on a 1.0 m pedestal whose base slides on rails (|bx| <= 3.25, -7.5 <= by <= -0.5, up to 6 m/s and 20 m/s^2; home: the point's spot (+-0.3, -4.0), see play); the racket head centre is 0.56 m beyond the flange; the string face is a disc of radius 0.14 m. The racket meets shuttles 0.4-2.5 m above the floor; overhead contacts (1.8-2.5 m) allow the fastest, steepest shots
+- `shuttle`: a point mass under gravity (9.81 m/s^2) and quadratic air drag, dv/dt = g - K |v| v with K = 0.212 per metre (terminal speed 6.8 m/s): hit at 40 m/s it slows to about 10 m/s within 0.3 s, and a high shuttle falls almost vertically at close to 6.8 m/s. No spin, no wind, no bounce
+- `racket_contact`: the racket meets the shuttle when the shuttle's centre crosses the string plane within 0.14 m of the head centre; the shuttle leaves exactly along the face normal n (the side the head moves towards, relative to the shuttle) at the speed 20 max(0, v_head.n) (1 - 0.3 (r/0.14)^2) + 0.15 max(0, -v_in.n), where v_head is the head velocity, r the contact's distance from the head centre and v_in the shuttle's incoming velocity; the rest of the head and incoming velocity is lost. A head speed along the normal of 0.5 m/s gives about 10 m/s, 2 m/s about 40 m/s; the arm manages up to about 2.4 m/s
+- Winner: a player disqualified for repeated undue delay (its third serve not tossed in time) loses; else first to 5 points (from 4-4 by 2, at most 7); at the match limit (300 hits or 40 points played) the player with more points; at equal points the player who won the last point that was not a let; then (last resort, not from the rulebook) the player who received first (format match-wallclock: the opponent)
+- Rulebook: BWF Laws of Badminton (BWF Statutes, Section 4.1, version 5.0), 2025-04-26
+- Deviation D1 (7): one short game: first to 5 points, from 4-4 a two-point lead is needed, at most 7 (6-6: the next point wins) instead of best of three games to 21 (cap 30); the match also ends after 300 hits (both sides) or 40 points played (lets included): the player ahead wins, at equal points the winner of the last point
+- Deviation D2 (9.1.5-9.1.8): the robot has no free hand to hold and drop the shuttle: the server tosses it with the command toss {pos: [x, y, z], height: H} (the common racket-sport toss, docs/conventions/racket_serve_zh.md): when the command takes effect the shuttle appears at that point (0.5-1.8 m high, within 1.0 m horizontally of the server's base, on its half) and is released from rest (H = 0) or projected straight up to rise H (at most 0.5 m; the Laws do not forbid a small toss); until then it is held beside the server. The toss has no spin (a point mass has none, Law 9.1.5). Judged: the server's racket must hit it (a miss is a fault, Law 9.1.8), with the shuttle below 1.15 m at the hit (Law 9.1.6, judged at the shuttle's point: it has no size) and leaving the racket upwards (Law 9.1). Not judged: the racket hitting the base of the shuttle first and moving forwards throughout the service (Laws 9.1.5, 9.1.7)
+- Deviation D3 (13.3-13.4): the shuttle is a point mass: a crossing of the net plane below the net top (between the posts) is a fault of the hitter; touching the net or reaching over it is not judged; a racket meets the shuttle only on its own half and only when it is that player's turn (no double hits)
+- Deviation D4 (9.1.3-9.1.4): before every serve the referee puts both robots at rest in the ready pose at a fixed spot in their service courts (diagonally opposite: the right courts when the server's score is even, Law 10.1): x = +0.3 (right court) or -0.3 (left court), y = -4.0 in each robot's frame; the spot is the robot's home for the point (where its base returns between strokes). Standing still (Law 9.1.4) is judged on the base: a base more than 5 cm from its spot before the serve is delivered (hit, or faulted) is that player's fault; both at once: a let (Law 14.2.2). The base moves within |x| <= 3.25, -7.5 <= y <= -0.5 at up to 6 m/s and 20 m/s^2
+- Deviation D5 (-): the last resort of the no-draw rule (equal points at the match limit and no point won) is not from the rulebook: the player who received first wins (format match-wallclock: the opponent)
+- Deviation D6 (9.1.1, 16.6-16.7): undue delay has a fixed limit: the server must toss the shuttle within 3 s after the receiver is ready (1 s after play resumes, Law 9.4), else it is a service fault (the receiver's point); a player's third such fault disqualifies it (it loses the match) instead of the umpire's warning and the referee's discretion (Laws 16.7.1-16.7.2)
+- Deviation D7 (6): no toss: format duel-wallclock: the runner plays both orders of the first server (match.first_server); format match-wallclock: you serve the first point
+
+Your robot: Franka Panda on a 1.0 m pedestal whose base slides on x-y rails, holding a badminton racket. Everything else you need (the frame, the geometry and the rule constants) is in
+`spec()["rules"]`; the physics engine is MuJoCo.
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/solution/builtin_players.py b/tasks/roboolympics-badminton-match-i00-standard-realtime/solution/builtin_players.py
new file mode 100644
index 0000000000..569d0eda55
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/solution/builtin_players.py
@@ -0,0 +1,566 @@
+"""badminton's built-in players (the same action interface as a model's program; core/client.py plays them over HTTP).
+
+ Reference the camera-only reference player of the legacy duel task (scripts/olympiad/badminton/duel/solution/
+ cam_player.py + oracle_play.py; its perception, flight fit and stroke choice unchanged below), for either
+ format and seat: it detects the orange cork in the 8 tiles, triangulates each frame, fits the documented
+ drag model, picks a contact the base can reach and a target (deep corners or short), turns the launch
+ velocity into the racket state with the documented contact law and sends `act` with T counted from the
+ act's effect step; while the shuttle flies it corrects the command when the refined prediction moves the
+ contact, or when the contact step it gets back (state.command) differs from the planned one. Only the
+ images, the state, /spec and the documented physics (the legacy task's privileged /oracle endpoint is
+ gone). Placement: the legacy privileged oracle's rule (oracle_ref.aim_place: a corner away from the
+ opponent, deep if it stands forward, short if it stands back), with the opponent's spot estimated as
+ the point the shuttle was played from (the fitted flight integrated back to its start). A shuttle the
+ fit lands clearly out of its court (0.3 m) is let go, and commands stay within the documented ranges.
+ Its serve (the documented serve rules, /spec serve): it plans a contact at its forehand point at 0.95 m
+ (so the stroke controller keeps the base on its spot), a toss point straight above it from which the
+ shuttle, released from rest (toss height 0), falls to the contact in SERVE_FALL_S, and a high-deep or a
+ short serve into the diagonal service court (a seeded choice per point, the same for either seat); it sends the stroke first (contact
+ SERVE_LEAD_S ahead) and then the toss timed so that the shuttle meets the racket; if the toss took
+ effect at another step than planned, it moves the contact time accordingly.
+ Random occasional random cancels (a check policy).
+No simulator import: this file runs in the player's container as the task's oracle (numpy + Pillow only).
+"""
+from __future__ import annotations
+
+import base64
+import io
+import math
+import random
+import time
+
+import numpy as np
+from PIL import Image
+
+G, K = 9.81, 9.81 / 6.8 ** 2 # gravity; drag K |v| v (terminal speed 6.8 m/s): from /spec
+DT = 0.002 # integration step of the player's own flight model
+STEP = 0.01 # the control step
+NET_TOP, COURT_X, COURT_Y = 1.524, 2.59, 6.70
+TILE_W, TILE_H = 480, 360
+REFINE_M = 0.03 # re-act when the predicted contact moves by more than this
+LAST_REFINE_S = 0.25 # no corrections closer to the contact than this (game seconds)
+OUT_MARGIN = 0.3 # let a shuttle go that the fit lands this far out of your court
+
+
+# ------------------------------------------------------------------------------------------------ cameras
+class Cam:
+ def __init__(self, c: dict):
+ self.pos = np.array(c["position"], float)
+ self.fw = np.array(c["forward"], float)
+ self.fw /= np.linalg.norm(self.fw)
+ self.up = np.array(c["up"], float)
+ self.up /= np.linalg.norm(self.up)
+ self.rt = np.cross(self.fw, self.up)
+ self.f = float(c.get("focal_px", 434.6))
+ pp = c.get("principal_point_px", [240, 180])
+ self.cx, self.cy = float(pp[0]), float(pp[1])
+
+ def ray(self, u, v):
+ d = self.fw + ((u - self.cx) / self.f) * self.rt - ((v - self.cy) / self.f) * self.up
+ return self.pos, d / np.linalg.norm(d)
+
+
+def triangulate(rays):
+ A = np.zeros((3, 3))
+ b = np.zeros(3)
+ for o, d in rays:
+ P = np.eye(3) - np.outer(d, d)
+ A += P
+ b += P @ o
+ X = np.linalg.solve(A, b)
+ res = [np.linalg.norm((np.eye(3) - np.outer(d, d)) @ (X - o)) for o, d in rays]
+ return X, float(np.sqrt(np.mean(np.square(res))))
+
+
+def decode(png: bytes) -> np.ndarray:
+ return np.asarray(Image.open(io.BytesIO(png)).convert("RGB"))
+
+
+def detect_tile(t: np.ndarray):
+ """(u, v) of the orange cork's centroid in a tile, or None."""
+ r = t[..., 0].astype(np.int16)
+ g = t[..., 1].astype(np.int16)
+ b = t[..., 2].astype(np.int16)
+ m = (r > 110) & (g * 100 > 25 * r) & (g * 100 < 72 * r) & (b * 100 < 35 * r)
+ m[:16, :160] = False # the time stamp
+ ys, xs = np.nonzero(m)
+ if len(xs) == 0 or len(xs) > 3000:
+ return None
+ mx, my = np.median(xs), np.median(ys)
+ sel = (np.abs(xs - mx) <= 25) & (np.abs(ys - my) <= 25)
+ if sel.sum() == 0:
+ return None
+ return float(xs[sel].mean()) + 0.5, float(ys[sel].mean()) + 0.5
+
+
+def detect_views(img, cams, times, max_res=0.12):
+ out = []
+ for j, tt in enumerate(times):
+ rays = []
+ for i, c in enumerate(cams):
+ uv = detect_tile(img[i * TILE_H:(i + 1) * TILE_H, j * TILE_W:(j + 1) * TILE_W])
+ if uv is not None:
+ rays.append(c.ray(*uv))
+ if len(rays) == 2:
+ X, res = triangulate(rays)
+ if res < max_res and -0.2 < X[2] < 12.0 and abs(X[0]) < 4.0 and abs(X[1]) < 8.0:
+ out.append((float(tt), X))
+ return out
+
+
+# ------------------------------------------------------------------------------------------------ flight model
+def rollout(p, v, n, dt=DT):
+ """(m, 3) states, integrated n steps (semi-implicit Euler); vectorised over m trajectories."""
+ p = np.array(p, float, ndmin=2)
+ v = np.array(v, float, ndmin=2)
+ P = np.empty((n + 1,) + p.shape)
+ V = np.empty_like(P)
+ P[0] = p
+ V[0] = v
+ for i in range(1, n + 1):
+ s = np.sqrt((v * v).sum(-1, keepdims=True))
+ v = v - (K * s * v + np.array([0.0, 0.0, G])) * dt
+ p = p + v * dt
+ P[i] = p
+ V[i] = v
+ return P, V
+
+
+def positions_at(p, v, t0, times):
+ times = np.asarray(times, float)
+ n = int(math.ceil((times.max() - t0) / DT)) + 1
+ P, _ = rollout(p, v, n)
+ idx = (times - t0) / DT
+ i0 = np.clip(np.floor(idx).astype(int), 0, n - 1)
+ f = (idx - i0)[:, None, None]
+ return P[i0] * (1 - f) + P[i0 + 1] * f # (len(times), m, 3)
+
+
+def fit(obs):
+ """Least-squares (p, v) at the first observation time from [(t, X)] (Gauss-Newton, numerical Jacobian)."""
+ obs = sorted(obs, key=lambda o: o[0])
+ t0 = obs[0][0]
+ ts = np.array([o[0] for o in obs])
+ Xs = np.array([o[1] for o in obs])
+ p = Xs[0].copy()
+ v = (Xs[-1] - Xs[0]) / max(ts[-1] - t0, 0.02) if len(obs) > 1 else np.zeros(3)
+ x = np.r_[p, v]
+ for _ in range(8):
+ eps = np.r_[np.full(3, 1e-3), np.full(3, 1e-3)]
+ X = np.vstack([x] + [x + np.eye(6)[i] * eps[i] for i in range(6)])
+ Pt = positions_at(X[:, :3], X[:, 3:], t0, ts) # (T, 7, 3)
+ r = (Xs - Pt[:, 0]).ravel()
+ J = np.stack([((Pt[:, i + 1] - Pt[:, 0]) / eps[i]).ravel() for i in range(6)], 1)
+ dx = np.linalg.lstsq(J.T @ J + 1e-6 * np.eye(6), J.T @ r, rcond=None)[0]
+ x = x + dx
+ if np.abs(dx).max() < 1e-4:
+ break
+ Pt = positions_at(x[None, :3], x[None, 3:], t0, ts)[:, 0]
+ return t0, x[:3], x[3:], float(np.sqrt(np.mean(np.sum((Xs - Pt) ** 2, 1))))
+
+
+def predict(p, v, t0, t_max=4.0):
+ """Times, positions, velocities until the floor or the net plane below the top."""
+ P, V = rollout(p, v, int(t_max / DT))
+ P, V = P[:, 0], V[:, 0]
+ end = len(P)
+ below = np.nonzero(P[:, 2] <= 0.0)[0]
+ if len(below):
+ end = below[0] + 1
+ cross = np.nonzero((np.sign(P[1:end, 1]) != np.sign(P[:end - 1, 1])) & (P[1:end, 2] < NET_TOP))[0]
+ if len(cross):
+ end = cross[0] + 1
+ return t0 + DT * np.arange(end), P[:end], V[:end]
+
+
+def backtrack(p, v, t, dt=0.001):
+ """The flight integrated backwards for t seconds (the documented model): where the shuttle was t s before (p, v)."""
+ p, v = np.array(p, float), np.array(v, float)
+ for _ in range(int(round(t / dt))):
+ p = p - v * dt
+ v = v + (K * np.linalg.norm(v) * v + np.array([0.0, 0.0, G])) * dt
+ return p
+
+
+# ------------------------------------------------------------------------------------------------ shots
+def solve_launch(p, target, thetas, vmax=45.0, dt=0.003):
+ """Launch velocities from p landing near `target` (xy, opponent's court), clearing the net by 20 cm: one per launch
+ angle that works, in the order given. Planar flights along the heading, vectorised over angle x speed."""
+ p = np.asarray(p, float)
+ d = np.asarray(target, float) - p[:2]
+ H = float(np.linalg.norm(d))
+ hd = d / H
+ th = np.radians(np.asarray(thetas, float))[:, None]
+ sp = np.linspace(2.0, vmax, 120)[None, :]
+ vh = (np.cos(th) * sp).ravel()
+ vz = (np.sin(th) * sp).ravel()
+ h = np.zeros_like(vh)
+ z = np.full_like(vh, p[2])
+ s_net = -p[1] / hd[1] if hd[1] > 1e-9 else np.inf
+ rng_ = np.full(vh.size, np.nan)
+ znet = np.full(vh.size, np.nan)
+ alive = np.ones(vh.size, bool)
+ for _ in range(int(4.0 / dt)):
+ s = np.sqrt(vh * vh + vz * vz)
+ vh = vh - K * s * vh * dt
+ vz = vz - (G + K * s * vz) * dt
+ h1 = h + vh * dt
+ z1 = z + vz * dt
+ cr = alive & (h < s_net) & (h1 >= s_net)
+ znet[cr] = z[cr] + (s_net - h[cr]) / (h1[cr] - h[cr]) * (z1[cr] - z[cr])
+ ld = alive & (z1 <= 0)
+ rng_[ld] = h[ld] + z[ld] / (z[ld] - z1[ld]) * (h1[ld] - h[ld])
+ alive &= ~ld
+ h, z = h1, z1
+ if not alive.any():
+ break
+ R = rng_.reshape(th.shape[0], -1)
+ ZN = znet.reshape(th.shape[0], -1)
+ S = sp[0]
+ out = []
+ for a, tdeg in enumerate(thetas):
+ ok = np.nonzero(np.isfinite(R[a]) & (R[a] >= H))[0]
+ if not len(ok) or ok[0] == 0:
+ continue
+ k = ok[0]
+ f = (H - R[a][k - 1]) / (R[a][k] - R[a][k - 1])
+ v = S[k - 1] + f * (S[k] - S[k - 1])
+ zn = ZN[a][k - 1] + f * (ZN[a][k] - ZN[a][k - 1])
+ if not np.isfinite(zn) or zn < NET_TOP + 0.20:
+ continue
+ c, s_ = math.cos(math.radians(tdeg)), math.sin(math.radians(tdeg))
+ out.append((tdeg, float(v), np.array([hd[0] * c * v, hd[1] * c * v, s_ * v])))
+ return out
+
+
+def racket_state(v_in, v_out):
+ """Contact law: the shuttle leaves along n at 20 (v_head . n) + 0.15 max(0, -v_in . n)."""
+ sp = float(np.linalg.norm(v_out))
+ n = v_out / sp
+ u = max(0.05, (sp - 0.15 * max(0.0, -float(v_in @ n))) / 20.0)
+ return n, u * n
+
+
+def base_time(dist, vmax, amax):
+ a, vm = 0.85 * amax, 0.98 * vmax
+ return 2 * math.sqrt(dist / a) if dist < vm * vm / a else dist / vm + vm / a
+
+
+def stance(p):
+ dz = float(p[2]) - 1.333
+ r = max(0.30, 0.95 - 0.35 * abs(dz))
+ return np.asarray(p[:2], float) - 0.62 * r
+
+
+def choose(ts, P, V, t_now, base_xy, vmax, amax, rng, margin=0.12, opp=None):
+ """Contact (time, position, incoming velocity) and racket state, or None. opp: where the opponent played the
+ shuttle from (x, y in the player's frame), for the placement."""
+ cands = []
+ for i in range(0, len(ts), 5):
+ p = P[i]
+ dt = ts[i] - t_now
+ if dt < 0.22 or not (0.45 <= p[2] <= 2.45 and -7.4 <= p[1] < -0.45 and abs(p[0]) <= 3.3):
+ continue
+ if base_time(float(np.linalg.norm(stance(p) - base_xy)), vmax, amax) <= dt - margin:
+ cands.append(i)
+ if not cands:
+ ok = [i for i in range(0, len(ts), 5) if ts[i] - t_now >= 0.22 and 0.45 <= P[i][2] <= 2.95
+ and -7.4 <= P[i][1] < -0.45 and abs(P[i][0]) <= 3.3]
+ if not ok:
+ return None
+ cands = [ok[-1]]
+ hi = [i for i in cands if 1.7 <= P[i][2] <= 2.45]
+ i = hi[0] if hi else max(cands, key=lambda j: P[j][2])
+ p, v_in = P[i], V[i]
+ if opp is None: # where the opponent is unknown: the legacy random placement
+ deep = rng.random() < 0.65
+ side = 1.0 if rng.random() < 0.5 else -1.0
+ target = np.array([side * 1.8, 5.6]) if deep else np.array([side * 1.5, 2.4])
+ else: # the legacy oracle's placement: a corner away from the opponent,
+ deep = opp[1] < 3.6 # deep if it stands forward, short if it stands back
+ side = -1.0 if opp[0] > 0 else 1.0
+ target = np.array([side * 1.9, 5.9]) if deep else np.array([side * 1.9, 1.6])
+ thetas = DEEP_THETAS if deep else SHORT_THETAS
+ opts = strokes(p, v_in, target, thetas) or strokes(p, v_in, np.array([0.0, 4.5]), (45, 35, 55, 25, 60))
+ if not opts:
+ return None
+ return ts[i], p, v_in, opts, target
+
+
+def strokes(p, v_in, target, thetas, vmax_head=2.2):
+ """Racket states (normal, head velocity) for the shots from p to target, the slowest head first."""
+ out = []
+ for th, sp, v_out in solve_launch(p, target, thetas):
+ n, vel = racket_state(v_in, v_out)
+ if np.linalg.norm(vel) <= vmax_head:
+ out.append((float(np.linalg.norm(vel)), n, vel))
+ return [(n, vel) for _, n, vel in sorted(out, key=lambda o: o[0])]
+
+
+DEEP_THETAS, SHORT_THETAS = (40, 30, 50, 20, 55, 10, 60), (10, 0, 20, -5, 30)
+SERVE_Z = 0.95 # the serve's contact height (below 1.15 m, Law 9.1.6)
+SERVE_FALL_S = 0.35 # from the toss (from rest) to the contact
+SERVE_LEAD_S = 1.0 # the stroke's contact time when it is sent (time to swing from rest)
+SERVE_THETAS = {"high": (50, 45, 55, 40, 60, 35), "short": (20, 14, 26, 10, 32, 6)} # launch angles (deg), in order
+
+
+def fall(t, dt=0.001):
+ """Drop of a shuttle released from rest after t s, and its speed then (the documented model)."""
+ z, v = 0.0, 0.0
+ for _ in range(int(round(t / dt))):
+ v += (G - K * v * v) * dt
+ z += v * dt
+ return z, v
+
+
+def serve_choice(spec_seed, st):
+ """The serve to play: (kind, target xy in your frame). Seeded by the match seed, the point and the score (not the
+ seat), into the receiver's diagonal service court: your right court (state.serve.court) faces its right court,
+ which is on your left (x < 0)."""
+ sc = st.get("score") or {}
+ g = random.Random(f"serve-{int(spec_seed)}-{st.get('point')}-{sc.get('you')}-{sc.get('opponent')}")
+ sgn = -1.0 if (st.get("serve") or {}).get("court") == "right" else 1.0
+ if g.random() < 0.5:
+ return "high", np.array([sgn * g.uniform(0.6, 1.8), g.uniform(5.6, 6.2)])
+ return "short", np.array([sgn * g.uniform(0.4, 1.6), g.uniform(2.25, 2.6)])
+
+
+def serve_plan(base_xy, kind, target):
+ """Contact point, toss point, incoming velocity and the racket states (normal, head velocity) of a serve from
+ the base at base_xy: contact at the forehand point at SERVE_Z (where the stroke controller's stance is the base
+ itself), the shuttle released SERVE_FALL_S of fall above it."""
+ dz = SERVE_Z - 1.333
+ off = 0.62 * max(0.30, 0.95 - 0.35 * abs(dz))
+ pc = np.array([base_xy[0] + off, base_xy[1] + off, SERVE_Z])
+ drop, vf = fall(SERVE_FALL_S)
+ rel = np.array([pc[0], pc[1], SERVE_Z + drop])
+ v_in = np.array([0.0, 0.0, -vf])
+ opts = [] # in the order of the launch angles (a high serve goes high), not by head speed
+ for th, sp, v_out in solve_launch(pc, target, SERVE_THETAS[kind]):
+ n, vel = racket_state(v_in, v_out)
+ if np.linalg.norm(vel) <= 2.2:
+ opts.append((n, vel))
+ return pc, rel, v_in, opts
+
+
+# ------------------------------------------------------------------------------------------------ players
+class Reference:
+ """The legacy play loop (oracle_play.play) as act(view): one command (or None) per call. In-process
+ (core/local.py) the view's step is exact and an act takes effect `lead` steps after it; over HTTP (the
+ observation has an obs_id) the step at which the act arrives is estimated from the wall clock (the newest frame's
+ step and its age give the step and its phase at the reply), and the contact step the service reports back
+ (state.command.contact_in_s) corrects both the act and the estimate."""
+
+ def __init__(self, spec, seat, seed=0):
+ self.high = spec.get("action_level", "high") == "high"
+ self.cams = [Cam(c) for c in spec["cameras"]]
+ self.lead = int(spec["act"]["lead_steps"])
+ self.period = float((spec.get("timing") or {}).get("period_s") or 0.2)
+ base = spec.get("base") or {}
+ self.vmax = float(base.get("max_speed_mps", 6.0))
+ self.amax = float(base.get("max_accel_mps2", 20.0))
+ self.rng = random.Random(f"{seat}-{int(seed)}")
+ self.seed = int(seed)
+ self.srv = None # the serve under way: {point, k_c (contact step), rel (the toss point), released (toss sent)}
+ self.flight, self.obs, self.plan = None, [], None
+ self.k_bias = 0.0 # learned offset of the estimated arrival step (over HTTP)
+ self.sent = None # the last act sent: {k_c (planned contact step), checked}
+
+ def review(self, reply):
+ return "reference player: camera-only, scripted", "reference player: same policy"
+
+ def _now_k(self, st, ob):
+ """The step at which a command sent now arrives (over HTTP: estimated from the newest frame and its age)."""
+ k = float(st.get("step", 0))
+ if "obs_id" in ob:
+ vs, age = ob.get("view_steps") or [], ob.get("obs_age_wall_s")
+ if vs and isinstance(age, (int, float)):
+ k = max(k, float(vs[-1]) + (float(age) + 0.02) / self.period)
+ k += self.k_bias
+ return k
+
+ def serve(self, st, ob):
+ """Your serve: the stroke first, then the toss timed so that the shuttle falls into the racket."""
+ sv = st.get("serve") or {}
+ phase, point = sv.get("phase"), st.get("point")
+ if self.srv is None or self.srv["point"] != point:
+ if phase not in ("waiting", "open"):
+ return None
+ kind, target = serve_choice(self.seed, st)
+ base = np.asarray(st.get("robot_base_xy") or [0.0, -4.0], float)
+ centre = np.array([0.5 * np.sign(target[0]) * COURT_X, 0.5 * (1.98 + COURT_Y)])
+ opts = None
+ for kd in [kind] + [x for x in SERVE_THETAS if x != kind]: # then the other kinds of serve
+ for f in (1.0, 0.75, 0.5, 0.25, 0.0): # no stroke delivers it: a target nearer the court's centre
+ pc, rel, v_in, opts = serve_plan(base, kd, centre + f * (target - centre))
+ if opts:
+ break
+ if opts:
+ kind = kd
+ break
+ if not opts:
+ return None
+ self.srv = {"point": point, "kind": kind, "target": centre + f * (target - centre), "pc": pc, "rel": rel,
+ "opts": opts, "k_c": None,
+ "released": False, "fixed": False}
+ srv = self.srv
+ k_now = self._now_k(st, ob)
+ n_fall = int(round(SERVE_FALL_S / STEP))
+ if phase == "open" and srv["k_c"] is None:
+ k_e = int(math.floor(k_now + 1e-6)) + self.lead
+ n_lead = int(round(SERVE_LEAD_S / STEP))
+ # the toss must take effect once the receiver is ready
+ k_open = int(st.get("step", 0)) + int(round(float(sv.get("opens_in_s") or 0.0) / STEP))
+ if k_e + n_lead - n_fall < k_open:
+ n_lead = k_open - k_e + n_fall
+ if n_lead * STEP > 4.9:
+ return None
+ srv["k_c"] = k_e + n_lead
+ n, vel = srv["opts"][0]
+ return {"type": "act", "t": round(n_lead * STEP, 3), "pos": [round(float(x), 4) for x in srv["pc"]],
+ "normal": [round(float(x), 4) for x in n], "vel": [round(float(x), 4) for x in vel]}
+ c = st.get("command")
+ if isinstance(c, dict) and isinstance(c.get("contact_in_s"), (int, float)) and not srv["released"]:
+ srv["k_c"] = int(st.get("step", 0)) + int(round(c["contact_in_s"] / STEP)) # the reported contact step
+ notes = str(c.get("stroke") or "")
+ k_e = int(math.floor(k_now + 1e-6)) + self.lead
+ if (("pose not delivered" in notes or "head speed limited" in notes) and srv["opts"][1:]
+ and srv["k_c"] - k_e > n_fall + 30 and srv.get("tried") != srv["k_c"]):
+ srv["opts"].pop(0) # the next stroke to the same target, for the same contact step
+ srv["tried"] = srv["k_c"]
+ n, vel = srv["opts"][0]
+ return {"type": "act", "t": round((srv["k_c"] - k_e) * STEP, 3),
+ "pos": [round(float(x), 4) for x in srv["pc"]], "normal": [round(float(x), 4) for x in n],
+ "vel": [round(float(x), 4) for x in vel]}
+ if phase == "open" and not srv["released"] and srv["k_c"] is not None:
+ k_e = int(math.floor(k_now + 1e-6)) + self.lead
+ if k_e >= srv["k_c"] - n_fall - 2: # (in-process the steps line up exactly)
+ srv["released"] = True
+ return {"type": "toss", "pos": [round(float(x), 4) for x in srv["rel"]], "height": 0.0}
+ return None
+ if phase == "tossed" and not srv["fixed"]:
+ srv["fixed"] = True
+ k_rel = sv.get("tossed_at_step")
+ if isinstance(k_rel, int) and k_rel + n_fall != srv["k_c"]:
+ # the toss took effect at another step than planned: move the contact time to meet the shuttle
+ k_e = int(math.floor(k_now + 1e-6)) + self.lead
+ T = (k_rel + n_fall - k_e) * STEP
+ if T > 0.12:
+ n, vel = srv["opts"][0]
+ return {"type": "act", "t": round(T, 3), "pos": [round(float(x), 4) for x in srv["pc"]],
+ "normal": [round(float(x), 4) for x in n], "vel": [round(float(x), 4) for x in vel]}
+ return None
+
+ def act(self, view):
+ st, ob = view.get("state") or {}, view.get("observation") or {}
+ if not self.high or st.get("world") != "running" or st.get("pending_commands"):
+ return None
+ if st.get("you_serve") and (st.get("serve") or {}).get("phase") in ("waiting", "open", "tossed"):
+ return self.serve(st, ob)
+ if st.get("ball_state") != "coming to you" or st.get("t_since_played") is None:
+ self.flight, self.obs, self.plan, self.sent = None, [], None, None
+ return None
+ live = "obs_id" in ob
+ t_entry = time.monotonic()
+ step = int(st.get("step", 0))
+ k_obs = float(step)
+ if live:
+ # the step at the reply, with its phase: the newest frame was taken at its step, obs_age_wall_s ago
+ vs, age = ob.get("view_steps") or [], ob.get("obs_age_wall_s")
+ if vs and isinstance(age, (int, float)):
+ k_obs = max(k_obs, float(vs[-1]) + (float(age) + 0.02) / self.period)
+ else:
+ k_obs += (float(ob.get("render_wall_s") or 0.0) + 0.03) / self.period
+
+ def now_k():
+ return k_obs + ((time.monotonic() - t_entry) / self.period if live else 0.0)
+
+ t_sim = step * STEP
+ t0 = round(t_sim - float(st["t_since_played"]), 3)
+ if self.flight != (st.get("point"), t0):
+ self.flight, self.obs, self.plan, self.sent = (st.get("point"), t0), [], None, None
+ if self.sent is not None and not self.sent["checked"]:
+ c = st.get("command")
+ if isinstance(c, dict) and isinstance(c.get("contact_in_s"), (int, float)):
+ k_true = step + int(round(c["contact_in_s"] / STEP))
+ err = k_true - self.sent["k_c"]
+ self.sent["checked"] = True
+ if live and abs(err) <= 10: # it took effect err steps later than assumed: arrive later next time
+ self.k_bias = max(-5.0, min(5.0, self.k_bias + 0.7 * err))
+ plan = self.plan
+ if plan is not None and not plan.get("skip"):
+ if err != 0:
+ plan["redo"] = True # the act took effect at another step than assumed: send it again
+ # the reply's stroke notes predict the delivery: if the joint speed limits cap the head speed or
+ # the pose is not delivered, take the next (faster-head or other-angle) stroke to the same target
+ notes = str(c.get("stroke") or "")
+ if (("head speed limited" in notes or "pose not delivered" in notes) and plan.get("opts")
+ and plan["t"] - t_sim > 0.3):
+ plan["normal"], plan["vel"] = plan["opts"].pop(0)
+ plan["redo"] = True
+ if "image_png_b64" not in ob:
+ return None
+ img = decode(base64.b64decode(ob["image_png_b64"]))
+ seen = {round(t, 3) for t, _ in self.obs}
+ for t, X in detect_views(img, self.cams, ob.get("view_sim_times") or []):
+ if t > t0 + 0.005 and round(t, 3) not in seen:
+ self.obs.append((t, X))
+ obs = self.obs
+ if len(obs) < 4 or max(t for t, _ in obs) - min(t for t, _ in obs) < 0.05:
+ return None
+ tf, p, v, res = fit(obs)
+ if res > 0.08:
+ self.obs = obs[-4:]
+ return None
+ ts, P, V = predict(p, v, tf)
+ land = P[-1]
+ if land[2] <= 0.05 and (abs(land[0]) > COURT_X + OUT_MARGIN or land[1] < -COURT_Y - OUT_MARGIN):
+ self.plan = {"skip": True} # it lands out of your court: let it go (your point)
+ return None
+ t_now = now_k() * STEP
+ plan = self.plan
+ if plan is None:
+ opp = backtrack(p, v, max(0.0, tf - t0))[:2] # the shuttle where it was played: the opponent's spot
+ c = choose(ts, P, V, t_now + (self.lead + 2) * STEP, np.asarray(st.get("robot_base_xy") or [0.0, -4.0]),
+ self.vmax, self.amax, self.rng, opp=opp)
+ if c is None:
+ self.plan = {"skip": True}
+ return None
+ t_c, pos, v_in, opts, target = c
+ plan = self.plan = dict(t=float(t_c), pos=pos, normal=opts[0][0], vel=opts[0][1], target=target,
+ opts=opts[1:])
+ elif plan.get("skip") or plan["t"] - t_now < LAST_REFINE_S:
+ return None
+ elif plan.pop("redo", False):
+ pass
+ else:
+ i = int(np.argmin(np.abs(ts - plan["t"])))
+ if np.linalg.norm(P[i] - plan["pos"]) < REFINE_M:
+ return None
+ opts = strokes(P[i], V[i], plan["target"], DEEP_THETAS if plan["target"][1] > 4 else SHORT_THETAS)
+ if not opts:
+ return None
+ plan.update(pos=P[i], normal=opts[0][0], vel=opts[0][1], opts=opts[1:])
+ k_e = int(math.floor(now_k() + (self.k_bias if live else 0.0) + 1e-6)) + self.lead
+ T = round(plan["t"] - k_e * STEP, 3)
+ pos = np.asarray(plan["pos"], float)
+ if not (0.03 <= T <= 4.9 and abs(pos[0]) <= 3.35 and -7.45 <= pos[1] <= -0.35 and 0.25 <= pos[2] <= 2.95
+ and np.linalg.norm(plan["vel"]) <= 7.9):
+ return None # outside the act's documented ranges
+ self.sent = {"k_c": k_e + int(round(T / STEP)), "checked": False}
+ return {"type": "act", "t": T, "pos": [round(float(x), 4) for x in plan["pos"]],
+ "normal": [round(float(x), 4) for x in plan["normal"]],
+ "vel": [round(float(x), 4) for x in plan["vel"]]}
+
+
+class Random:
+ """Occasional random cancels (a check policy; seeded by the seed, not the seat)."""
+
+ def __init__(self, spec, seat, seed=0):
+ self.g = np.random.default_rng(int(seed) * 7919 + 17)
+
+ def act(self, view):
+ st = view.get("state") or {}
+ if st.get("world") != "running" or st.get("pending_commands") or self.g.uniform() > 0.05:
+ return None
+ return {"type": "none"}
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/solution/oracle_play.py b/tasks/roboolympics-badminton-match-i00-standard-realtime/solution/oracle_play.py
new file mode 100644
index 0000000000..0f36ecd9a3
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/solution/oracle_play.py
@@ -0,0 +1,236 @@
+"""Harbor oracle: the sport's RoboOlympics reference player (builtin_players.Reference, next to this file: camera images
+and the documented facts only) driven through the agent's own client (rcb_client.py, eai-standard/2.3).
+
+The reference players were written for RoboOlympics' realtime interface: each step they get a `view` -- the state
+(score, the ball's clock, what was heard, the robot's own body) and a tiled PNG of the newest camera frames -- and
+return an act body or nothing. This loop builds that view from /observe (a short watch: the frames and one proprio row
+per frame), turns the act into a /submit row of the task's action type, and sends `ready` (with the player's review as
+the note) once per break. Nothing here reads simulator state the agent could not read.
+
+Timing (table tennis, badminton): the players also have an in-process mode in which an act takes effect exactly at the
+observed step. 2.3's `at` makes that exact over HTTP too: the loop picks the control step its command will take effect
+at (a margin of LEAD_STEPS after the step it estimates is running now), hands the player the view as of that step (the
+step and the times relative to it shifted accordingly; images and frame steps are absolute), and submits the command
+with `at` = that step. Host load then delays the command's arrival, never its effect.
+"""
+from __future__ import annotations
+
+import base64
+import io
+import math
+import os
+import sys
+import time
+
+import numpy as np
+from PIL import Image
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import builtin_players as bp # noqa: E402
+from rcb_client import EpisodeOver, Robot # noqa: E402
+
+NAN = float("nan")
+LEAD_STEPS = 5 # control steps between "now" (estimated) and a command's planned effect: 0.5 s of wall
+ # time at S = 10 for the player's own computation and the request
+
+
+def num(x):
+ return None if x is None or (isinstance(x, float) and math.isnan(x)) else x
+
+
+def png_b64(rows: list) -> tuple[str, list]:
+ """rows of tiles (one row per camera) -> base64 PNG and the tile list."""
+ sheet = np.concatenate([np.concatenate(r, axis=1) for r in rows], axis=0)
+ buf = io.BytesIO()
+ Image.fromarray(np.ascontiguousarray(sheet[..., :3])).save(buf, format="PNG", compress_level=1)
+ return base64.b64encode(buf.getvalue()).decode(), []
+
+
+class Bridge:
+ def __init__(self):
+ self.r = Robot()
+ self.spec = self.r.spec()
+ self.sport = self.spec["sport"]
+ self.layout = self.spec["proprio_layout"]
+ self.dt = float(self.spec["control_dt"])
+ self.period = float(self.spec["timing"]["wall_s_per_control_step"])
+ self.cams = list(self.spec["cameras"])
+ rules = self.spec.get("rules") or {}
+ cams = []
+ for name in self.cams:
+ c = dict(self.spec["cameras"][name], name=name)
+ if self.sport == "airhockey":
+ c.update(width=c["hw"][1], height=c["hw"][0])
+ cams.append(c)
+ self.exact = self.sport in ("tabletennis", "badminton") # the in-process timing mode (module docstring)
+ ref = {"cameras": cams, "action_level": self.spec["match"]["action_level"],
+ "timing": {"period_s": None if self.exact else self.period}, **rules}
+ self.player = bp.Reference(ref, "A", 0)
+ self.reviewed_break = None
+ self.n_obs = 0
+ self.hist: list = [] # (match step, proprio row, {cam: image}) of recent observations
+ self.spacing = {"tabletennis": 4, "badminton": 6}.get(self.sport, 1) # 40 / 60 ms, as RoboOlympics' views
+ self.running = False
+ # how often the loop looks (control steps): badminton at RoboOlympics' own client cadence (an observation, then
+ # `wait 0.05`): a player that re-plans its stroke at every step keeps the arm from ever finishing a swing
+ self.every = {"badminton": 5}.get(self.sport, 1)
+ # badminton: a command waits `lead_steps` after its step (stroke_pending_effect_step shows it then); before
+ # that it is still in the service's plan, which the proprio does not show: the loop marks it pending itself
+ self.lead = int(((self.spec.get("rules") or {}).get("act") or {}).get("lead_steps", 0))
+ self.pending_until = -1
+
+ # ------------------------------------------------------------------ one view
+ def rows(self, res) -> list[dict]:
+ P = np.asarray(res.proprio, float).reshape(-1, len(self.layout))
+ return [dict(zip(self.layout, map(float, row))) for row in P]
+
+ def state(self, p: dict, shift: int = 0) -> dict:
+ """The player's state as of `shift` control steps after the proprio row p (relative times shifted)."""
+ p = dict(p)
+ for k in ("t_since_played",):
+ if k in p and not math.isnan(p[k]):
+ p[k] += shift * self.dt
+ for k in ("serve_opens_in_s", "serve_deadline_in_s", "stroke_contact_in_s"):
+ if k in p and not math.isnan(p[k]):
+ p[k] -= shift * self.dt
+ if "serve_opens_in_s" in p and not math.isnan(p["serve_opens_in_s"]):
+ p["serve_opens_in_s"] = max(0.0, p["serve_opens_in_s"])
+ st = {"step": int(p["match_step"]) + shift, "world": "frozen" if p["break"] > 0.5 else "running",
+ "done": p["finished"] > 0.5}
+ if self.sport == "tabletennis":
+ heard = [{"event": ev, "t": p[f"heard_{k}_t"]} for k, ev in
+ (("opp_bounce", "bounce on the opponent's half"), ("own_bounce", "bounce on your half"),
+ ("net", "net"), ("paddle", "paddle"), ("robot", "robot"), ("floor", "floor"))
+ if not math.isnan(p[f"heard_{k}_t"])]
+ st.update(point=int(p["point"]), ball="serve" if p["ball_is_serve"] > 0.5 else "opponent's return",
+ t_since_played=p["t_since_played"], ball_in_play=p["ball_in_play"] > 0.5, heard=heard,
+ ball_state="coming to you" if p["ball_coming"] > 0.5 else
+ "going to the opponent" if p["ball_going"] > 0.5 else "dead")
+ elif self.sport == "badminton":
+ phase = {0: "waiting", 1: "open", 2: "tossed", 3: "done"}.get(int(p["serve_phase"]) if not
+ math.isnan(p["serve_phase"]) else -1)
+ sv = {"phase": phase, "court": "right" if p["serve_court_right"] > 0.5 else "left",
+ "opens_in_s": num(p["serve_opens_in_s"]), "deadline_in_s": num(p["serve_deadline_in_s"])}
+ if not math.isnan(p["serve_tossed_at_step"]):
+ sv["tossed_at_step"] = int(p["serve_tossed_at_step"])
+ notes = "; ".join(n for n, k in (("head speed limited", "stroke_head_speed_limited"),
+ ("pose not delivered", "stroke_pose_not_delivered")) if p[k] > 0.5)
+ st.update(point=int(p["point"]), score={"you": int(p["score_you"]), "opponent": int(p["score_opponent"])},
+ you_serve=p["you_serve"] > 0.5, serve=sv, robot_base_xy=[p["base_x"], p["base_y"]],
+ t_since_played=num(p["t_since_played"]),
+ ball_state="coming to you" if p["ball_coming"] > 0.5 else
+ "going to the opponent" if p["ball_going"] > 0.5 else
+ "tossed: yours to hit (your serve)" if p["ball_tossed"] > 0.5 else
+ "not yet served" if p["ball_not_served"] > 0.5 else "dead")
+ if p["stroke_active"] > 0.5:
+ st["command"] = {"contact_in_s": p["stroke_contact_in_s"], "stroke": notes}
+ if not math.isnan(p["stroke_pending_effect_step"]):
+ st["pending_commands"] = [{"takes_effect_at_step": int(p["stroke_pending_effect_step"])}]
+ else:
+ st.update(rally=int(p["rally"]), t_play=p["t_play"],
+ own={"mallet_xyz": [p["mallet_x"], p["mallet_y"], p["mallet_z"]]})
+ return st
+
+ def observe(self):
+ """Air hockey: watch 0.05 s (the players' cadence) and take the last image. Table tennis, badminton: the
+ current images at once (the clock is started by a short watch first), kept in a history from which the view
+ takes four frames about SPACING control steps apart, newest last, as RoboOlympics' observation did."""
+ if self.sport == "airhockey":
+ res = self.r.get_obs(cameras=self.cams, seconds=0.05, video="none")
+ return res, self.rows(res), {c: res.last[c][None] for c in self.cams}
+ res = self.r.get_obs(cameras=self.cams, seconds=0 if self.running else 0.05, video="frames")
+ self.running = True
+ rows = self.rows(res)
+ k = int(rows[-1]["match_step"])
+ if not self.hist or self.hist[-1][0] != k:
+ self.hist.append((k, rows[-1], {c: res.frames[c][-1] for c in self.cams}))
+ self.hist = self.hist[-40:]
+ sel, last = [], None
+ for k, row, fr in reversed(self.hist):
+ if last is None or last - k >= self.spacing:
+ sel.append((k, row, fr))
+ last = k
+ if len(sel) == 4:
+ break
+ sel.reverse()
+ return res, [r for _, r, _ in sel], {c: np.stack([fr[c] for _, _, fr in sel]) for c in self.cams}
+
+ def view(self, res, rows, frames, shift: int = 0) -> tuple[dict, dict, dict]:
+ now = rows[-1]
+ st = self.state(now, shift)
+ n = min(len(rows), min(len(f) for f in frames.values()))
+ rows, frames = rows[-n:], {c: f[-n:] for c, f in frames.items()}
+ self.n_obs += 1
+ ob = {"view_steps": [int(p["match_step"]) for p in rows],
+ "view_sim_times": [round(p["match_step"] * self.dt, 4) for p in rows]}
+ if not self.exact:
+ ob.update(obs_id=self.n_obs, obs_age_wall_s=0.0, render_wall_s=0.0)
+ if self.sport == "airhockey":
+ img = frames[self.cams[0]][-1]
+ ob["image_png_b64"], _ = png_b64([[img]])
+ ob["tiles"] = [{"camera": self.cams[0], "x": 0, "y": 0, "width": img.shape[1], "height": img.shape[0]}]
+ else:
+ ob["image_png_b64"], _ = png_b64([[f for f in frames[c]] for c in self.cams])
+ return st, ob, now
+
+ # ------------------------------------------------------------------ one action
+ def send(self, body: dict, at=None) -> None:
+ t = body.get("type")
+ if t == "act":
+ row = [body["t"], *body["pos"], *body["normal"], *body["vel"]]
+ self.r.submit("stroke", [row], at=at)
+ elif t == "toss":
+ self.r.submit("toss", [[*body["pos"], float(body.get("height", 0.0))]], at=at)
+ elif t == "target":
+ self.r.submit("mallet", [[body["x"], body["y"]]], at=at)
+ elif t == "none":
+ self.r.submit("stop" if self.sport == "airhockey" else "rest", [[0.0]], at=at)
+
+ def run(self) -> dict:
+ t_last = 0.0
+ while True:
+ time.sleep(max(0.0, t_last + self.every * self.period - time.monotonic())) # one view per `every` steps
+ t_last = time.monotonic()
+ try:
+ res, rows, frames = self.observe()
+ except EpisodeOver:
+ break
+ t_reply = time.monotonic()
+ if res.meta.get("done"):
+ break
+ at = shift = None
+ if self.exact: # the step the command will take effect at, and the view as of then
+ at = math.ceil(res.meta["control_steps"] + 0.5) + LEAD_STEPS
+ at = max(at, math.ceil(res.meta["control_steps"] + (time.monotonic() - t_reply) / self.period)
+ + LEAD_STEPS)
+ shift = at - int(res.meta["control_steps"])
+ st, ob, now = self.view(res, rows, frames, shift or 0)
+ if st["world"] == "frozen":
+ key = int(now["match_step"]) # the match stands still in a break: one key per break
+ if key != self.reviewed_break:
+ self.reviewed_break = key
+ f = getattr(self.player, "review", None)
+ why, plan = f(now) if f else ("played as planned", "same plan")
+ try:
+ self.r.submit("ready", [[1.0]], note=f"WHY: {why} PLAN: {plan}"[:200])
+ except EpisodeOver:
+ break
+ continue
+ if self.sport == "badminton" and res.meta["control_steps"] <= self.pending_until:
+ st["pending_commands"] = [{"takes_effect_at_step": int(now["match_step"]) + self.pending_until
+ - int(res.meta["control_steps"]) + 1}]
+ body = self.player.act({"state": st, "observation": ob})
+ if body:
+ if at is not None:
+ self.pending_until = at + self.lead
+ try:
+ self.send(body, at)
+ except EpisodeOver:
+ break
+ return self.r.status()
+
+
+if __name__ == "__main__":
+ t0 = time.time()
+ out = Bridge().run()
+ print({"status": out, "wall_s": round(time.time() - t0, 1)})
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/solution/solve.sh b/tasks/roboolympics-badminton-match-i00-standard-realtime/solution/solve.sh
new file mode 100755
index 0000000000..a1680309dd
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/solution/solve.sh
@@ -0,0 +1,5 @@
+#!/bin/bash
+# Oracle: the sport's RoboOlympics reference player (camera images, proprio and /spec only) through the agent's client.
+set -e
+mkdir -p /app/output
+cd /solution && python3 oracle_play.py 2>&1 | tee /app/output/oracle.log
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/task.toml b/tasks/roboolympics-badminton-match-i00-standard-realtime/task.toml
new file mode 100644
index 0000000000..db4b15d760
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/task.toml
@@ -0,0 +1,74 @@
+# RoboOlympics Badminton against the scripted opponent, standard-realtime mode (docs/PROTOCOL.md §4b, docs/benchmarks/roboolympics.md).
+# Generated by scripts/roboolympics/gen_tasks.py from tasks.toml, sports.toml and templates/ -- edit those, not this.
+schema_version = "1.3"
+artifacts = [
+ { source = "/data/final.json", service = "sim" },
+ { source = "/data/match.json", service = "sim" },
+ { source = "/data/episode.jsonl", service = "sim" },
+ { source = "/data/trajectory.npz", service = "sim" },
+ { source = "/data/trajectory_live.f64", service = "sim" },
+ { source = "/data/commands.jsonl", service = "sim" },
+ { source = "/data/replay.mp4", service = "sim" },
+ { source = "/data/replay.last.png", service = "sim" },
+ { source = "/data/ticks.f64", service = "sim" },
+ { source = "/data/calls.jsonl", service = "sim" },
+ { source = "/data/submitted.f64", service = "sim" },
+ { source = "/data/startups.jsonl", service = "sim" },
+ "/app/output/",
+]
+
+[task]
+name = "robot-coding-bench/roboolympics-badminton-match-i00-standard-realtime"
+description = "STANDARD-REALTIME MODE (robot as a service on a clock that does not stop, eai-standard/2.3): RoboOlympics badminton, one match against a scripted opponent (level 1, frozen seed 101). The world runs at 1/10 of real speed (S = 10, the benchmark's official slowdown) and never waits: the agent sees only camera images and its own robot through the client, and drives the robot with the sport's commands (`stroke`, `toss`, `rest`, `ready`) from a program of its own. Between points a break of 12 s of game time (120 s of wall time) in which the clock runs on and nothing plays; no reset, no privileged state. The sim service records every command at the step it took effect, replays the match in a fresh process and grades it: success = a finished match that the agent won."
+authors = [{ name = "RoboOlympics (CHIGUI0)" }]
+keywords = ["robotics", "roboolympics", "sports", "badminton", "mujoco", "standard-realtime-mode", "vision", "real-time"]
+
+[metadata]
+author_name = "RoboOlympics"
+task_type = "trajectory"
+simulator = "mujoco"
+robot = "franka-panda"
+family = "badminton_match"
+mode = "standard-realtime"
+protocol = "eai-standard/2.3"
+instance_seed = 101
+opponent_level = 1
+slowdown = 10
+revision = "badminton-wallclock-5+duel-7+core-0.2"
+play = "program"
+action_level = "high"
+source_task = "roboolympics/badminton-match-wallclock-program-standard"
+expert_time_estimate_hours = 0.5
+oracle = "full"
+oracle_evidence = "solution/: the sport's RoboOlympics reference player (camera images, proprio and /spec only) through the agent's client; it wins this instance (PR #106)"
+
+[verifier]
+timeout_sec = 900.0
+environment_mode = "separate"
+network_mode = "no-network"
+
+# The agent's time is up: stop whatever it left running in its container (a program would keep playing).
+[[verifier.collect]]
+service = "main"
+command = "kill -9 -1 2>/dev/null; exit 0"
+timeout_sec = 30
+
+# Then the match ends: SIGUSR1 to the service (re-sent every 30 s, in case it was restarting), which replays and grades it.
+[[verifier.collect]]
+service = "sim"
+command = "for i in $(seq 1 90); do [ -f /data/server.pid ] && break; sleep 2; done; for i in $(seq 1 400); do grep -q '\"finalized\": true' /data/final.json 2>/dev/null && break; [ $((i % 15)) -eq 1 ] && kill -USR1 $(cat /data/server.pid) 2>/dev/null; sleep 2; done; cat /data/final.json"
+timeout_sec = 900
+
+[agent]
+timeout_sec = 7200
+# The agent reaches the model APIs and the sim (localhost:8000, Harbor's egress control) and nothing else.
+network_mode = "allowlist"
+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com"]
+
+[environment]
+build_timeout_sec = 1200.0
+cpus = 2
+memory_mb = 4096
+
+[verifier.environment]
+build_timeout_sec = 600.0
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/tests/Dockerfile b/tasks/roboolympics-badminton-match-i00-standard-realtime/tests/Dockerfile
new file mode 100644
index 0000000000..0ecd542d19
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/tests/Dockerfile
@@ -0,0 +1,4 @@
+# Separate verifier sandbox: grades the sim service's own artifacts; needs nothing but Python.
+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f
+COPY test.sh grade.py /tests/
+RUN chmod +x /tests/test.sh
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/tests/grade.py b/tasks/roboolympics-badminton-match-i00-standard-realtime/tests/grade.py
new file mode 100644
index 0000000000..32f4465282
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/tests/grade.py
@@ -0,0 +1,93 @@
+"""Standard-realtime verifier (eai-standard/2.3) for RoboOlympics: grades what the sim service -- which the agent could
+not touch -- wrote.
+
+/data/final.json holds the live match's outcome and the verdict of a fresh-process replay of its record:
+success = live_success (the match finished and the agent won it) AND replay_success (the replay's match too) AND
+deterministic (the replay ends in the live run's state). /data/match.json (the replay's summary: the score, the breaks,
+the commands) only adds information to reward.json; it never decides the verdict.
+Writes /logs/verifier/reward.txt (1/0) and a numeric-only reward.json, and copies the evidence (replay video, last
+frame, the replay's summary, event log) next to them for humans.
+infra_error = 1: no verdict on the agent (the service crashed past its restarts, failed to resume, ended on a simulator
+error, never finished, or failed to finalize; PROTOCOL §4b).
+"""
+import json
+import math
+import os
+import shutil
+import traceback
+
+DATA = os.environ.get("RCB_DATA", "/data")
+LOG = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")
+os.makedirs(LOG, exist_ok=True)
+
+
+def write(ok: bool, out: dict) -> None:
+ with open(os.path.join(LOG, "reward.txt"), "w") as f:
+ f.write("1\n" if ok else "0\n")
+ with open(os.path.join(LOG, "reward.json"), "w") as f:
+ json.dump(out, f)
+ print(json.dumps(out))
+
+
+def num(x, default=0.0) -> float:
+ try:
+ x = float(x)
+ except (TypeError, ValueError):
+ return default
+ return x if math.isfinite(x) else default
+
+
+def match_fields() -> dict:
+ """Information from the replay's summary (numbers only); {} if there is none."""
+ try:
+ with open(os.path.join(DATA, "match.json")) as f:
+ m = json.load(f)
+ except (OSError, ValueError):
+ return {}
+ return {"match_finished": int(bool(m.get("finished"))), "match_won": int(bool(m.get("won"))),
+ "points_for": num(m.get("points_for")), "points_against": num(m.get("points_against")),
+ "match_steps": int(num(m.get("match_steps"))), "breaks": len(m.get("breaks") or []),
+ "breaks_ended_by_ready": sum(1 for b in m.get("breaks") or [] if b.get("by") == "ready"),
+ "commands_applied": int(num(m.get("commands_applied"))),
+ "commands_refused": int(num(m.get("commands_refused")))}
+
+
+def main() -> None:
+ path = os.path.join(DATA, "final.json")
+ if not os.path.exists(path):
+ write(False, {"success": 0, "missing_log": 1, "infra_error": 1, "grader_error": 0})
+ return
+ try:
+ with open(path) as f:
+ d = json.load(f)
+ live, replay, det = (bool(d.get(k)) for k in ("live_success", "replay_success", "deterministic"))
+ failed_finalize = bool(d.get("finalize_error"))
+ unfinished = not d.get("finalized")
+ sim_error = d.get("reason") == "error"
+ infra = bool(d.get("infra_error")) or failed_finalize or unfinished or sim_error
+ ok = live and replay and det and not infra
+ out = {"success": int(ok), "live_success": int(live), "replay_success": int(replay), "deterministic": int(det),
+ "finalized": int(not unfinished), "missing_log": 0, "infra_error": int(infra),
+ "sim_error": int(sim_error), "grader_error": int(failed_finalize),
+ "timeout": int(d.get("reason") == "timeout"),
+ "n_actions": int(num(d.get("n_actions"))), "control_steps": int(num(d.get("control_steps_total"))),
+ "calls": int(num(d.get("calls"))), "rows": int(num(d.get("rows"))),
+ "reset_budget": int(num(d.get("reset_budget"))), "slowdown": num(d.get("slowdown")),
+ "max_lag_s": num(d.get("max_lag_s")), "stalls": int(num(d.get("stalls"))),
+ "late_steps": int(num(d.get("late_steps"))), "sim_startups": int(num(d.get("sim_startups"))),
+ "elapsed_s": num(d.get("elapsed_s")), "video_rendered": int(bool(d.get("video"))), **match_fields()}
+ except Exception: # noqa: BLE001 -- an unreadable final.json is the grader's failure, not the agent's
+ traceback.print_exc()
+ write(False, {"success": 0, "missing_log": 0, "infra_error": 1, "grader_error": 1})
+ return
+ for name in ("replay.mp4", "replay.last.png", "match.json", "episode.jsonl"):
+ try:
+ if os.path.exists(os.path.join(DATA, name)):
+ shutil.copy(os.path.join(DATA, name), os.path.join(LOG, name))
+ except OSError:
+ traceback.print_exc()
+ write(ok, out)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/roboolympics-badminton-match-i00-standard-realtime/tests/test.sh b/tasks/roboolympics-badminton-match-i00-standard-realtime/tests/test.sh
new file mode 100755
index 0000000000..75622ada21
--- /dev/null
+++ b/tasks/roboolympics-badminton-match-i00-standard-realtime/tests/test.sh
@@ -0,0 +1,5 @@
+#!/bin/bash
+# Verifier (separate sandbox): the sim sidecar's artifacts were uploaded to /data by Harbor.
+mkdir -p /logs/verifier
+rm -rf /logs/verifier/*
+python /tests/grade.py 2> /logs/verifier/grade.log
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/README.md b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/README.md
new file mode 100644
index 0000000000..23a4b09054
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/README.md
@@ -0,0 +1,57 @@
+# roboolympics-tabletennis-match-i00-standard-realtime
+
+| | |
+|---|---|
+| Benchmark | RoboOlympics |
+| Mode | standard-realtime (`eai-standard/2.3`) |
+| Twin | — (none: RoboOlympics is standard-realtime only, PROTOCOL §4b) |
+| Simulator / robot | `mujoco` / `franka-panda` |
+| Family / instance | `tabletennis_match` / seed 101 |
+| Oracle | `full` — solution/: the sport's RoboOlympics reference player (camera images, proprio and /spec only) through the agent's client; it wins this instance (PR #106) |
+| Agent time budget | 7200 s; tokens: protocol default (PROTOCOL §5) |
+| Base image | `ghcr.io/mll-lab-nu/eai-olympiad:0.2.0` |
+
+## Task
+RoboOlympics table tennis (`tabletennis-match-wallclock-program-standard`), one match against the scripted opponent (level 1, frozen seed
+101), in standard-realtime mode (`eai-standard/2.3`, PROTOCOL §4b): the robot as a service on a clock that does
+not stop. The sport runs in the `sim` sidecar (`environment/docker-compose.yaml`; `environment/sim/rcb_realtime.py`
+runs the clock, `environment/sim/rcb_olympics.py` is the RoboOlympics adapter, `environment/sim/sport/` the sport's
+simulator, referee and opponent), which records every command at the control step it took effect, replays the match in
+a fresh process and renders the replay video; the verifier grades the sidecar's record in a container of its own
+(`tests/Dockerfile`, no network).
+
+## Difficulty
+The agent sees the game only through cameras and has no simulator of its own. A point is decided in a few seconds of
+game time, faster than a model's turn even at S = 10, so the agent has to write a perception and control
+program (find the ball in the images, fit its flight, choose and time the command) that plays by itself, and
+improve it between points and during the match. The opponent returns every ball it can reach; level 1 of
+the sport's levels.
+
+## Reference solution
+`solution/oracle_play.py` runs the sport's RoboOlympics reference player (`solution/builtin_players.py`: camera images,
+the proprio columns and `/spec` only; perception by colour, triangulation, a fitted flight model, the sport's contact
+law) through the agent's own client; it wins this instance (PR #106).
+
+## Verification
+`success` = live success (the match finished and the agent won it) ∧ replay success ∧ deterministic (the fresh-process
+replay of the recorded commands ends in the live run's state), computed in the sidecar. The record is
+`trajectory_live.f64` (per control step: the id of the command that took effect, -1 for none, and the `ready` flag) with
+`commands.jsonl` (the commands as the sport's action layer lowered them), so the replay re-applies what the live match
+applied, whatever the timing; `ticks.f64`, `calls.jsonl` and `submitted.f64` record the timing and every call, and
+`final.json` the clock's lag (`max_lag_s`, `stalls`). `match.json` is the replay's summary (score, breaks, commands).
+`tests/grade.py` reads `/data/final.json` and copies the evidence to `/logs/verifier/` (`replay.mp4`). A simulator
+crash or error is an infrastructure failure (`infra_error = 1`), not the agent's (PROTOCOL §4b). `nop` scores 0: the
+match never starts.
+
+Generated by `scripts/roboolympics/gen_tasks.py` from `tasks.toml`, `sports.toml`, `templates/` and `shared/` (the
+RoboOlympics simulator code, CHIGUI0/roboolympics 596d551a862c4236e74aea2beb25654b9783f9a7 (branch upstream-export, core 0.2.13)); do not edit by hand.
+
+## Details
+| | |
+|---|---|
+| sport | You play robot table tennis (ITTF rules with the deviations below) against a scripted opponent: a MuJoCo Franka Panda holding a paddle, at your end of a real-size table, seen only through two cameras. The opponent serves every point (recorded real serves) and returns every ball it can reach; you always receive. One game to 5 points. |
+| time | S = 10 (RoboOlympics' official slowdown; `RCB_SLOWDOWN` overrides it, results under another S are reported separately): one 10 ms control step every 0.1 s of wall time; the match starts paused and its clock starts at the first `submit` or `get_obs(seconds > 0)`; after every point a break of 12 s of game time (120 s of wall time) in which the clock runs on and nothing plays, ended early by the agent's `ready` row |
+| actions | `stroke`, `rest`, `ready`: the sport's own commands (action level `high`), one per row, effective at the row's control step |
+| observation | camera images and the agent's own robot plus the referee's information as proprio columns; no ball or opponent state, no seed |
+| budget | 7200 s, no reset (one match is the episode), no privileged twin (PROTOCOL §4b exceptions, `docs/benchmarks/roboolympics.md`) |
+| agent API | `environment/rcb_client.py` (the realtime client); `instruction.md` documents the commands, the proprio columns and the cameras |
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/Dockerfile b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/Dockerfile
new file mode 100644
index 0000000000..36d483206f
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/Dockerfile
@@ -0,0 +1,10 @@
+# Standard-realtime mode: the agent container has no simulator and no RoboOlympics code -- only Python, the client and
+# OpenCV (RoboOlympics' player image).
+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f
+COPY client-requirements.txt /tmp/
+RUN pip install --no-cache-dir -r /tmp/client-requirements.txt
+RUN pip install --no-cache-dir -c /tmp/client-requirements.txt opencv-python-headless==5.0.0.93 && pip check
+COPY rcb_client.py rcb1.py /opt/tools/
+ENV PYTHONPATH=/opt/tools
+RUN mkdir -p /app/output
+WORKDIR /app
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/client-requirements.txt b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/client-requirements.txt
new file mode 100644
index 0000000000..8aa73a968f
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/client-requirements.txt
@@ -0,0 +1,11 @@
+# Exact pins for what the standard agent container installs (and a verifier, if it installs anything): the closure of
+# `pip install requests numpy pillow scipy`, the unpinned line of every standard task at 9eb18edf, resolved on
+# 2026-10-01 in CLIENT_IMAGE (client.env: Python 3.12.14, pip 25.0.1). A change here is a shared-files PR.
+certifi==2026.7.22
+charset-normalizer==3.5.2
+idna==3.20
+numpy==2.5.3
+pillow==12.3.0
+requests==2.34.2
+scipy==1.18.1
+urllib3==2.8.0
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/docker-compose.yaml b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/docker-compose.yaml
new file mode 100644
index 0000000000..e11b262be2
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/docker-compose.yaml
@@ -0,0 +1,35 @@
+# Standard-realtime mode (PROTOCOL §4b): RoboOlympics table tennis runs in the `sim` sidecar (the agent cannot open it), on
+# its own clock once the match starts (sim/rcb_realtime.py, the adapter sim/rcb_olympics.py); the agent only reaches
+# port 8000. No `expose`/`ports` on sim: under Harbor's egress control it shares main's network namespace
+# (localhost:8000). CPU only: MuJoCo physics and OSMesa rendering (the players' meshes come with the image).
+services:
+ main:
+ depends_on: [sim]
+ sim:
+ image: ghcr.io/mll-lab-nu/eai-olympiad:0.2.0
+ volumes:
+ - ./sim:/srv:ro
+ command: python /srv/rcb_realtime.py
+ restart: on-failure:6 # a crash resumes the same match, paused, never a reset
+ cpus: 6
+ mem_limit: 8g
+ pids_limit: 256
+ environment:
+ RO_PLUGIN: /srv/sport/plugin.py
+ RO_SPORT: tabletennis
+ RO_FORMAT: match
+ RO_SEED: "101"
+ RO_LEVEL: "1"
+ RO_ACTION_LEVEL: high
+ RO_TASK_TEXT: "Win a game of table tennis against the scripted opponent: return its serves and shots onto its half."
+ RO_EPISODE_TEXT: "Ends when the game is decided (first to 5 points, from 4:4 a lead of 2, at most 7; success: you won), when your time is up (timeout), or on a simulator error."
+ RCB_WALL_CLOCK_S: "7200"
+ # Knobs: ${NAME:-default} takes NAME from the shell that runs harbor. The defaults are the official
+ # configuration; results under other settings are reported separately.
+ RCB_SLOWDOWN: "${RCB_SLOWDOWN:-10}" # 10: RoboOlympics' official slowdown (PROTOCOL §4b exception); results state S
+ RCB_RESET_BUDGET: "${RCB_RESET_BUDGET:-0}" # 0: one match is one episode (PROTOCOL §4b, the mode's default)
+ MUJOCO_GL: osmesa
+ PYOPENGL_PLATFORM: osmesa
+ LP_NUM_THREADS: "2"
+ OMP_NUM_THREADS: "1"
+ OPENBLAS_NUM_THREADS: "1"
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/rcb1.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/rcb1.py
@@ -0,0 +1,83 @@
+"""RCB1 — a tiny binary frame for one JSON header plus N raw blobs (videos, image arrays, depth, proprio).
+
+ frame = b"RCB1" | header_len uint32 LE | header JSON (UTF-8) | blob_0 | blob_1 | ...
+ header = {"v": 1, "meta": {...}, "parts": [{"name", "kind", "len", ...}, ...]} # blobs in the same order
+
+kinds: "mp4" (fps, n), "jpeg", "array" (dtype, shape; C-order raw bytes), "json" (utf-8), "bytes".
+Zero dependencies for bytes/json parts; numpy only when you ask for arrays. Used on both sides (server and client),
+over HTTP bodies (Content-Type: application/x-rcb1) and equally usable over a raw socket. `python -m rcb1 unpack f dir`.
+"""
+from __future__ import annotations
+import json, struct, sys, pathlib
+
+MAGIC = b"RCB1"
+
+
+def encode(meta: dict, parts: list[tuple[str, str, bytes, dict]]) -> bytes:
+ """parts: [(name, kind, blob, extra), ...]; extra carries dtype/shape/fps/n."""
+ hdr_parts = []
+ for name, kind, blob, extra in parts:
+ d = {"name": name, "kind": kind, "len": len(blob)}
+ d.update({k: v for k, v in (extra or {}).items() if v is not None})
+ hdr_parts.append(d)
+ header = json.dumps({"v": 1, "meta": meta, "parts": hdr_parts}, separators=(",", ":")).encode()
+ return b"".join([MAGIC, struct.pack("<I", len(header)), header] + [blob for _, _, blob, _ in parts])
+
+
+def array_part(name: str, arr, extra: dict | None = None) -> tuple[str, str, bytes, dict]:
+ import numpy as np
+ a = np.ascontiguousarray(arr)
+ return (name, "array", a.tobytes(), {"dtype": str(a.dtype), "shape": list(a.shape), **(extra or {})})
+
+
+def decode(buf: bytes, arrays: bool = True) -> tuple[dict, dict]:
+ """-> (meta, parts) where parts[name] = {"kind", ..., "data"}; arrays become numpy arrays when arrays=True."""
+ if buf[:4] != MAGIC:
+ raise ValueError("not an RCB1 frame")
+ n = struct.unpack("<I", buf[4:8])[0]
+ header = json.loads(buf[8:8 + n].decode()); off = 8 + n
+ out = {}
+ for p in header["parts"]:
+ blob = buf[off:off + p["len"]]; off += p["len"]
+ d = dict(p)
+ if p["kind"] == "array" and arrays:
+ import numpy as np
+ d["data"] = np.frombuffer(blob, dtype=np.dtype(p["dtype"])).reshape(p["shape"])
+ elif p["kind"] == "json":
+ d["data"] = json.loads(blob.decode())
+ else:
+ d["data"] = blob
+ out[p["name"]] = d
+ return header.get("meta", {}), out
+
+
+def unpack_to_dir(buf: bytes, out_dir: str) -> list[str]:
+ """Write a frame's parts as files: mp4/jpeg/bytes verbatim, arrays as .npy, meta as meta.json."""
+ import numpy as np
+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)
+ meta, parts = decode(buf, arrays=True); written = []
+ (out / "meta.json").write_text(json.dumps(meta, indent=1)); written.append("meta.json")
+ for name, p in parts.items():
+ safe = name.replace("/", "__")
+ if p["kind"] == "array":
+ f = out / f"{safe}.npy"; np.save(f, p["data"])
+ elif p["kind"] == "mp4":
+ f = out / f"{safe}.mp4"; f.write_bytes(p["data"])
+ elif p["kind"] == "jpeg":
+ f = out / f"{safe}.jpg"; f.write_bytes(p["data"])
+ elif p["kind"] == "json":
+ f = out / f"{safe}.json"; f.write_text(json.dumps(p["data"], indent=1))
+ else:
+ f = out / f"{safe}.bin"; f.write_bytes(p["data"])
+ written.append(f.name)
+ return written
+
+
+if __name__ == "__main__":
+ if len(sys.argv) == 4 and sys.argv[1] == "unpack":
+ print("\n".join(unpack_to_dir(open(sys.argv[2], "rb").read(), sys.argv[3])))
+ elif len(sys.argv) == 3 and sys.argv[1] == "info":
+ meta, parts = decode(open(sys.argv[2], "rb").read(), arrays=False)
+ print(json.dumps(meta, indent=1)); [print(n, {k: v for k, v in p.items() if k != "data"}) for n, p in parts.items()]
+ else:
+ print(__doc__)
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/rcb_client.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/rcb_client.py
new file mode 100644
index 0000000000..f2b0559bf9
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/rcb_client.py
@@ -0,0 +1,209 @@
+"""eai-standard/2.3 client (standard-realtime mode): your whole interface to the robot (installed at /opt/tools/rcb_client.py, on
+PYTHONPATH).
+
+ from rcb_client import Robot, EpisodeOver
+ r = Robot() # finds the service (SIM_URL, http://sim:8000, http://localhost:8000), waits until it is ready
+
+TIME DOES NOT STOP (spec()["timing"]). An episode starts paused; its clock starts at its first submit() or
+get_obs(seconds > 0) (again after every reset()) and from then on runs one control step every spec()["control_dt"] x
+spec()["timing"]["slowdown"] seconds of wall time, whether or not you call, until the episode ends. The service keeps a
+plan, one servo-target row per coming control step: submit() writes into it and answers at once; when the plan runs out
+the last target is held. Whatever you do in between -- think, print, run a model -- the robot keeps executing.
+
+Calls (each is one HTTP request; every answer that carries data is an RCB1 frame, decoded into a Result):
+ r.spec() GET /spec, fetched when connecting: the robot's facts. "action_types"
+ ("joint_position": dim, layout (actuator order), lower/upper, range_rad,
+ units, semantics), "control_dt" (0.02 s), "max_control_steps" (the
+ episode), "timing" (realtime, slowdown, max_ahead_steps), "cameras" {name:
+ rgb, depth, hw, fovy_deg, pose, mounted}, "proprio_layout" and "proprio"
+ (joints, axes, positions), "imu", "links" (masses, centres of mass, the
+ feet's boxes), "depth", "budget" {"reset", "wall_clock_s"}, "episode"
+ r.status() GET /status: calls, rows, control_steps, done, reason, elapsed_s, running,
+ planned_steps, lag_s (and episode, resets_left with a reset budget)
+ r.get_obs(cameras=None, seconds=0.0, video_fps=10, include_depth=False, video="frames")
+ POST /observe. seconds=0: the robot now, at once. seconds>0 (at most
+ spec()["max_watch_s"]): waits while that much robot time runs (starting the
+ clock if it is not running) and returns what the cameras saw; it never
+ changes the plan
+ r.submit("joint_position", actions, dt=None, interpolate="linear", at=None, cameras=None, video_fps=10,
+ video="none", include_depth=False, note="")
+ POST /submit: answers at once with the robot as it is now (the rows
+ have not run yet). actions (T, dim): rows dt apart (a multiple of
+ control_dt, the default; T x dt at most spec()["max_chunk_s"]); each step's
+ target is the row (interpolate="hold") or a straight line from the previous
+ row's ("linear", starting from the target in force just before `at`). They
+ become the plan from control step `at` (an episode step number; None = the
+ next step), replacing whatever was planned from `at` on and keeping what is
+ planned before it; at most spec()["timing"]["max_ahead_steps"] ahead. Rows
+ for steps already gone when the request arrives are dropped
+ (meta["late_steps"]). The first submit of an episode starts its clock
+ r.reset(cameras=None, include_depth=False)
+ POST /reset, only when spec()["budget"]["reset"] > 0: abandons the
+ running episode and starts a new one, paused, from the same starting state;
+ only the last episode is graded, and a success ends the trial
+
+cameras=None means every camera in spec()["cameras"]; cameras=[] means no images at all, only proprioception (the
+fastest call: what a controller loop wants). video: "mp4" (one H.264 file per camera), "frames" (the images as arrays),
+"both" or "none" (only the last frame); a submit returns no video (no time passes inside it). include_depth adds depth
+for the cameras that have it.
+
+Result (what get_obs / submit / reset return):
+ res.meta dict: calls, rows, control_steps (steps run in this episode: the next one is this number),
+ sim_time_s, time_s, time_left_s, proprio {"layout", "now"}, done, reason ("success" |
+ "failed" | "timeout" | "error"; None while the episode runs), running, planned_steps,
+ lag_s; per submit: start_step, late_steps, plan_end_step, clipped [{row, index, reason}]
+ (values outside [-1, 1] are clipped, not refused); with a reset budget also episode,
+ resets_left
+ res.last[cam] uint8 H x W x 3: the last frame (unless cameras=[])
+ res.frames[cam] uint8 N x H x W x 3 (get_obs, video="frames"/"both") res.video[cam] mp4 bytes
+ res.depth[cam] float16 N x H x W, metres, 0 = nothing in range (include_depth)
+ res.proprio float32 rows of spec()["proprio_layout"]: one at the call's start, one every 1/video_fps s
+ of a watch, one at its end
+ res.done the episode is over
+ res.save(dir) meta.json, <cam>.mp4, last/<cam>.jpg, frames/<cam>/NNN.jpg, depth_<cam>.npy, proprio.npy
+
+Errors: ValueError -- refused, nothing changed (400: wrong type or shape, NaN, a bad dt or at, too many frames, an
+unknown camera; or a request over 64 MB, refused before it is sent); EpisodeOver -- the episode, or the trial, is over
+(409); RuntimeError -- the service failed (5xx: see spec()["on_service_error"]) or the endpoint does not exist in this
+run (404).
+"""
+from __future__ import annotations
+
+import json
+import os
+import pathlib
+import time
+
+import numpy as np
+import requests
+
+import rcb1
+
+PROTOCOLS = ("eai-standard/2.", "rcb-limited/2.") # any 2.x service, under either name (rcb-limited is the old one)
+MAX_BODY = 64 * 1024 * 1024 # the protocol's request limit: a larger request is refused
+
+
+class EpisodeOver(RuntimeError):
+ pass
+
+
+class Result:
+ """A decoded RCB1 answer: meta, video, frames, last, depth, proprio; save(dir) writes them all out."""
+
+ def __init__(self, meta: dict, parts: dict):
+ self.meta, self.raw = meta, parts
+ self.video, self.frames, self.last, self.depth, self.proprio = {}, {}, {}, {}, None
+ for name, p in parts.items():
+ kind, data = p["kind"], p["data"]
+ if name.startswith("video/") and kind == "mp4":
+ self.video[name[6:]] = data
+ elif name.startswith("frames/"):
+ self.frames[name[7:]] = data
+ elif name.startswith("last/"):
+ self.last[name[5:]] = data
+ elif name.startswith("depth/"):
+ self.depth[name[6:]] = data
+ elif name == "proprio":
+ self.proprio = data
+
+ @property
+ def done(self) -> bool:
+ return bool(self.meta.get("done"))
+
+ def save(self, out_dir: str) -> str:
+ from PIL import Image
+ out = pathlib.Path(out_dir)
+ out.mkdir(parents=True, exist_ok=True)
+ (out / "meta.json").write_text(json.dumps(self.meta, indent=1))
+ for cam, b in self.video.items():
+ (out / f"{cam}.mp4").write_bytes(b)
+ for cam, img in self.last.items():
+ (out / "last").mkdir(exist_ok=True)
+ Image.fromarray(np.ascontiguousarray(img)).save(out / "last" / f"{cam}.jpg", quality=90)
+ for cam, arr in self.frames.items():
+ d = out / "frames" / cam
+ d.mkdir(parents=True, exist_ok=True)
+ for i, f in enumerate(arr):
+ Image.fromarray(np.ascontiguousarray(f)).save(d / f"{i:03d}.jpg", quality=85)
+ for cam, arr in self.depth.items():
+ np.save(out / f"depth_{cam}.npy", arr)
+ if self.proprio is not None:
+ np.save(out / "proprio.npy", self.proprio)
+ return str(out)
+
+
+class Robot:
+ def __init__(self, base: str | None = None, timeout: float = 600.0):
+ candidates = [c for c in (base or os.environ.get("SIM_URL"), "http://sim:8000", "http://localhost:8000") if c]
+ t0, last = time.time(), None
+ while time.time() - t0 < timeout:
+ for b in candidates:
+ try:
+ r = requests.get(b + "/spec", timeout=(5, 60))
+ if r.status_code == 503:
+ last = "warming up"
+ continue
+ r.raise_for_status()
+ self.base, self._spec = b, r.json()
+ if not str(self._spec.get("protocol", "")).startswith(PROTOCOLS):
+ raise RuntimeError(f"not an eai-standard/2.x service: {self._spec.get('protocol')}")
+ return
+ except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e:
+ last = e # not up yet (the scene takes about a minute), or busy
+ time.sleep(2)
+ raise RuntimeError(f"sim service unavailable: {last}")
+
+ def spec(self) -> dict:
+ return self._spec
+
+ def status(self) -> dict:
+ r = requests.get(self.base + "/status", timeout=(5, 60))
+ r.raise_for_status()
+ return r.json()
+
+ def get_obs(self, cameras=None, seconds: float = 0.0, video_fps: int = 10, include_depth: bool = False,
+ video: str = "frames") -> Result:
+ meta = {"cameras": _names(cameras), "seconds": float(seconds), "video_fps": int(video_fps),
+ "include_depth": bool(include_depth), "video": video}
+ return self._post("/observe", meta, [], timeout=900)
+
+ def submit(self, action_type: str, actions, dt: float | None = None, interpolate: str = "linear",
+ at: int | None = None, cameras=None, video_fps: int = 10, video: str = "none",
+ include_depth: bool = False, note: str = "") -> Result:
+ a = np.asarray(actions, dtype=np.float64)
+ if a.ndim == 1:
+ a = a[None, :]
+ if not np.all(np.isfinite(a)):
+ raise ValueError("actions contain NaN or inf")
+ meta = {"type": action_type, "dt": None if dt is None else float(dt), "interpolate": interpolate,
+ "at": None if at is None else int(at), "cameras": _names(cameras), "video_fps": int(video_fps),
+ "video": video,
+ "include_depth": bool(include_depth), "note": note}
+ return self._post("/submit", meta, [rcb1.array_part("actions", a)], timeout=1800)
+
+ def reset(self, cameras=None, include_depth: bool = False) -> Result:
+ return self._post("/reset", {"cameras": _names(cameras), "include_depth": bool(include_depth)}, [], timeout=900)
+
+ def _post(self, path: str, meta: dict, parts: list, timeout: float) -> Result:
+ body = rcb1.encode(meta, parts)
+ if len(body) > MAX_BODY: # the service would close the connection on it unread
+ raise ValueError(f"{path}: {len(body)} bytes, over the protocol's {MAX_BODY}: send fewer rows")
+ r = requests.post(self.base + path, data=body, headers={"Content-Type": "application/x-rcb1"},
+ timeout=(5, timeout))
+ if r.headers.get("Content-Type", "").startswith("application/x-rcb1") and r.status_code == 200:
+ return Result(*rcb1.decode(r.content))
+ try:
+ err = r.json()
+ except ValueError:
+ err = {"error": r.text[:300]}
+ msg = f"{r.status_code} {path}: {err.get('error')}" + (f" ({err['detail']})" if err.get("detail") else "")
+ if r.status_code == 409:
+ raise EpisodeOver(msg + (f"; reason {err['reason']}" if err.get("reason") else "")
+ + (f"; resets_left {err['resets_left']}" if "resets_left" in err else ""))
+ if r.status_code in (400, 413):
+ raise ValueError(msg)
+ raise RuntimeError(msg)
+
+
+def _names(cameras) -> list[str] | None:
+ return None if cameras is None else [cameras] if isinstance(cameras, str) else list(cameras)
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/core/README.md b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/core/README.md
new file mode 100644
index 0000000000..6d80cefa51
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/core/README.md
@@ -0,0 +1,18 @@
+# core/
+
+The match core (docs/framework_zh.md §5): it hosts every match under one set of rules and never names a sport or a
+harness. Version: `VERSION` in `__init__.py` (bump on every change; every sport's golden replay must still pass).
+
+| File | Contract / job |
+|---|---|
+| `sport.py` | ② the sport interface: `MatchConfig` (seats, sides, format, modes, renderer), `Phase`, `Refused`, `MatchBase` (the optional hooks and their defaults), `ActionLayer` / `LowLayer` / `SchemaLayer`, `check_command`; request validation (core 0.2.11): `check_body` (every request), `check_action` + `parse_action` (every act: any exception while reading an action is the player's 400, never a technical failure) |
+| `http.py`, `client.py`, `game.py` | ① the player protocol: the HTTP envelope (`/<seat>/<endpoint>`, limits), the client loop of built-in players, the generic `game` CLI |
+| `realtime.py`, `turn.py`, `service.py` | flow: `eai-standard-realtime/1.0` (slowdown, freeze and review, act pipeline, delayed effects, entities) and `eai-standard-turn/1.0` (turns, chess clocks, reviews); what both share (seats and sides, observations, team channel, retirement, final.json) |
+| `episode.py` | ③ the match record: `episode.jsonl` and the fresh-process replay (`python -m core.episode PLUGIN DIR`) |
+| `outcome.py`, `grading.py` | judgement: the no-draw chain, N-side ranking, solo scoring; the verifier (validity, reward fields, no-code audit hookup) |
+| `observe.py`, `channel.py`, `rng.py`, `spec.py` | the observation whitelist and camera tiles (through `renderers/`), the reply images of an action (`Match.reply_views`, core 0.2.8: snapshotted under the lock, drawn off it by the same camera worker, attached to the reply as `observation`), the team channel, random streams by name, sport.toml |
+| `seats.py`, `metering/` | per-seat counters, locks and chess clocks; the metering hookup (`think_clock.py`, `api_errors.py`: byte-identical copies); player modes (`PLAYER_MODE_<seat>`): `model` (metered by the seat's proxy, required for validity), `oracle` (exempt), `unmetered` (core 0.2.13: the runner meters the model itself, e.g. a plain Harbor with native agents; no proxy, no meter required) |
+| `spectator.py` | the broadcast log (`broadcast.jsonl`, the legacy writer copied as `spectator/broadcast_log.py`) and the replay video (`replay.mp4`, a fresh-process replay drawn by the spectator renderer); never read back |
+| final.json compatibility | `service.py` `COMPAT`: the sport's fields are lifted to the top level (unless a core field has the name) and `score` is set, so the Season-1 readers work; the sport fields also stay under `sport_fields` |
+| `workers.py`, `serve.py`, `launch.py` | worker processes (plan, render, camera), the service entry point, the launcher (one metering proxy per seat, none for an unmetered seat) |
+| `local.py`, `testkit.py`, `tests/` | in-process matches of built-in players, the generic test suite of every sport, the core's own tests |
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/core/__init__.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/core/__init__.py
new file mode 100644
index 0000000000..fd44c1d84c
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/core/__init__.py
@@ -0,0 +1,8 @@
+"""RoboOlympics match core (docs/framework_zh.md §5): hosts every match under one set of rules.
+
+Flow (clock, slowdown, freeze and review, seats and turns), rules (formats, modes), records (episode log, replay,
+metering) and judgement (outcome, validity). It names no sport and no harness (ci_checks/check-core-purity.sh), computes
+no physics, and changes only in its own commits with a version bump (VERSION) and every sport's golden replay passing.
+"""
+VERSION = "0.2.13"
+PROTOCOLS = {"realtime": "eai-standard-realtime/1.0", "turn": "eai-standard-turn/1.0"}
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/core/observe.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/core/observe.py
new file mode 100644
index 0000000000..94b46fc9b3
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/core/observe.py
@@ -0,0 +1,154 @@
+"""Observations (sport rule 1, docs/framework_zh.md §9): what a seat gets is the camera images, its own body and the
+referee's information, and nothing else. The sport declares the fields of Match.observe() in sport.toml
+([observation] fields); a field outside that whitelist is never delivered and is a technical error of the match.
+
+The camera images: Match.cameras(seat, query) returns camera definitions, the task's renderer (renderers/, chosen by
+the task parameter `renderer`) draws them from the sport's scene and Match.render_state(), and the core lays the
+images out as tiles of one PNG (left to right, `columns` per row), described in the reply (`tiles`).
+
+Reply images (core 0.2.8): Match.reply_views(seat, cmd, info) right after an action -> reply_job() snapshots the
+frames under the lock -> CameraWorker.draw_job() draws them off the lock (the same renderer, scene and worker as the
+observation) -> one PNG of tiles, each tile also naming its frame (`frame`, `label`) when there are several.
+
+The scene of the players' images (core 0.2.9, renderer rule 6): Sport.scene(cfg), or the presentation scene the sport
+declares for its players (sports/<sport>/presentation/presentation.toml `players`, bundled into the simulator by the
+generator; renderers/presentation.players_scene): the same kinematics, finer visual meshes. Any other presentation
+scene is refused (spectators only)."""
+from __future__ import annotations
+
+import copy
+import struct
+import zlib
+from pathlib import Path
+
+import numpy as np
+
+
+class WhitelistError(Exception):
+ pass
+
+
+def filter_fields(obs: dict, allowed: set[str] | None) -> tuple[dict, list[str]]:
+ """(the whitelisted part of obs, the names that were not allowed)."""
+ if allowed is None:
+ return obs, []
+ bad = sorted(k for k in obs if k not in allowed)
+ return {k: v for k, v in obs.items() if k in allowed}, bad
+
+
+def png(img: np.ndarray) -> bytes:
+ """A minimal RGB8 PNG encoder (no imaging library needed in the sim)."""
+ img = np.ascontiguousarray(img, dtype=np.uint8)
+ h, w = img.shape[:2]
+ raw = b"".join(b"\x00" + img[y].tobytes() for y in range(h))
+
+ def chunk(tag, data):
+ return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
+
+ return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0))
+ + chunk(b"IDAT", zlib.compress(raw, 6)) + chunk(b"IEND", b""))
+
+
+def reply_job(m, spec: dict | None, columns: int) -> dict | None:
+ """Under the lock: Match.reply_views()'s answer -> a self-contained draw job (deep copies: the match may move on
+ while the job is drawn off the lock). A frame without a state gets render_state() now."""
+ if not spec or not spec.get("frames"):
+ return None
+ order = spec.get("order", "frame")
+ if order not in ("frame", "camera"):
+ raise ValueError(f"reply_views: order must be 'frame' or 'camera', not {order!r}")
+ now = None
+ frames = []
+ for f in spec["frames"]:
+ st = f.get("state")
+ if st is None:
+ now = m.render_state() if now is None else now
+ st = now
+ cams = list(f.get("cameras") or [])
+ if not cams:
+ raise ValueError("reply_views: every frame needs at least one camera")
+ frames.append({"state": st, "cams": cams, "label": f.get("label")})
+ return copy.deepcopy({"frames": frames, "order": order, "columns": int(spec.get("columns") or columns),
+ "note": spec.get("note")})
+
+
+def compose(images: list[np.ndarray], names: list[str], columns: int = 2) -> tuple[np.ndarray, list[dict]]:
+ """Tiles left to right, `columns` per row, each at its own size; -> (sheet, [{camera, x, y, width, height}])."""
+ rows = [list(range(i, min(i + columns, len(images)))) for i in range(0, len(images), columns)]
+ widths = [sum(images[j].shape[1] for j in r) for r in rows]
+ heights = [max(images[j].shape[0] for j in r) for r in rows]
+ sheet = np.zeros((sum(heights), max(widths), 3), np.uint8)
+ tiles, y = [], 0
+ for r, hgt in zip(rows, heights):
+ x = 0
+ for j in r:
+ h, w = images[j].shape[:2]
+ sheet[y:y + h, x:x + w] = images[j][..., :3]
+ tiles.append({"camera": names[j], "x": x, "y": y, "width": w, "height": h})
+ x += w
+ y += hgt
+ return sheet, tiles
+
+
+def players_scene(sport, plugin: str, cfg):
+ """The scene of the players' images: the sport's presentation scene when it declares `players`, else
+ Sport.scene(cfg)."""
+ scene = sport.scene(cfg)
+ d = Path(plugin).resolve().parent
+ if not (d / "presentation" / "presentation.toml").is_file():
+ return scene
+ from renderers import presentation
+ return presentation.players_scene(d, scene)
+
+
+class CameraWorker:
+ """Draws a seat's camera definitions with the task's renderer (in-process or inside a render worker process)."""
+
+ def __init__(self, scene, renderer_name: str | None):
+ import renderers
+ if getattr(scene, "match", None) is not None and not getattr(scene, "players", False):
+ raise ValueError("the players' images are drawn from the match scene (Sport.scene) or the presentation "
+ "scene the sport declares for them; any other presentation scene is for spectators only "
+ "(renderer rule 6)")
+ self.name = renderer_name or renderers.DEFAULT
+ self.renderer = renderers.load(self.name)(scene)
+
+ def draw(self, state: dict, cams: list[dict], columns: int = 2) -> dict:
+ from renderers.base import CameraDef
+ defs = [CameraDef.from_dict(c) for c in cams]
+ images = self.renderer.render(state, defs)
+ sheet, tiles = compose(images, [c.name for c in defs], columns)
+ return {"png": png(sheet), "tiles": tiles, "renderer": self.name}
+
+ def draw_frames(self, job: dict) -> dict:
+ """A reply job (reply_job()): every frame's cameras drawn from that frame's state, laid out frame after
+ frame or camera after camera; a tile names its camera, and its frame (index, label) when there are several."""
+ from renderers.base import CameraDef
+ frames = job["frames"]
+ drawn = [] # per frame: [(name, image)]
+ for f in frames:
+ defs = [CameraDef.from_dict(c) for c in f["cams"]]
+ drawn.append(list(zip([c.name for c in defs], self.renderer.render(f["state"], defs))))
+ cells = [] # (frame index, camera name, image)
+ if job.get("order") == "camera":
+ for j in range(max(len(d) for d in drawn)):
+ cells += [(i, d[j][0], d[j][1]) for i, d in enumerate(drawn) if j < len(d)]
+ else:
+ cells = [(i, name, img) for i, d in enumerate(drawn) for name, img in d]
+ sheet, tiles = compose([c[2] for c in cells], [c[1] for c in cells], int(job.get("columns", 2)))
+ many = len(frames) > 1
+ for t, (i, _, _) in zip(tiles, cells):
+ if many:
+ t["frame"] = i
+ if frames[i].get("label"):
+ t["label"] = frames[i]["label"]
+ out = {"png": png(sheet), "tiles": tiles, "renderer": self.name}
+ if job.get("note"):
+ out["note"] = job["note"]
+ return out
+
+ def draw_job(self, job: dict) -> dict:
+ """Any job of the core's camera worker: a reply job (frames) or an observation (state + cameras)."""
+ if "frames" in job:
+ return self.draw_frames(job)
+ return self.draw(job["state"], job["cams"], job.get("columns", 2))
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/core/outcome.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/core/outcome.py
new file mode 100644
index 0000000000..11916961f2
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/core/outcome.py
@@ -0,0 +1,50 @@
+"""The no-draw decision chain (docs/framework_zh.md §5): a forfeit (a core decision: review or clock time, abandonment,
+or a side that never started, "no_show"; sides that retired before it rank last, the last to retire first), then the
+sport's tiebreaks in order (rulebook result -> rulebook tiebreak -> capped extra play -> last resort; the last one must
+decide). A match with more than two sides is decided by the sport's classification (Match.ranking, best first). A solo
+match (single format without an opponent: tiebreaks() == []) has no winner; its result is the score against the
+success line. A match that did not finish has no winner."""
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+from .sport import FINISHED
+
+
+@dataclass
+class Outcome:
+ winner: str | None
+ decided_by: str
+ scores: dict
+ ranking: list = field(default_factory=list)
+ solo: bool = False
+
+
+def decide(match, forfeit_seat: str | None = None, why: str | None = None, sides=("A", "B"),
+ side_of=lambda s: s, retired=()) -> Outcome:
+ scores = match.scores()
+ sides = list(sides)
+ rules = match.tiebreaks()
+ solo = len(sides) == 1 and not rules
+ if forfeit_seat is not None:
+ lost = side_of(forfeit_seat)
+ others = [s for s in sides if s != lost and s not in retired]
+ if len(others) == 1:
+ return Outcome(others[0], f"forfeit:{why}", scores, others + [lost] + list(reversed(retired)))
+ if not others and len(sides) == 1: # a single player who forfeits loses (to the line or the opponent)
+ return Outcome(None, f"forfeit:{why}", scores, [], solo)
+ if match.phase().state != FINISHED:
+ return Outcome(None, "unfinished", scores, [], solo)
+ if solo:
+ return Outcome(None, "score", scores, list(sides), True)
+ if len(sides) > 2:
+ ranking = list(match.ranking() or [])
+ if sorted(ranking) != sorted(sides):
+ raise RuntimeError("a match of more than two sides must rank every side (Match.ranking)")
+ return Outcome(ranking[0], "ranking", scores, ranking)
+ for name, rule in rules:
+ w = rule(match)
+ if w is not None:
+ rest = [s for s in sides if s != w]
+ return Outcome(w, name, scores, [w] + rest)
+ raise RuntimeError("a finished match must be decided by its last tiebreak (no draws)")
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/core/spec.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/core/spec.py
new file mode 100644
index 0000000000..9cc5599b5c
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/core/spec.py
@@ -0,0 +1,20 @@
+"""The sport's declarations (sport.toml next to its plugin.py, docs/framework_zh.md §4.2): data, read by the core
+(observation whitelist, team channel, success line, timing), the generator, the checks and the documentation."""
+from __future__ import annotations
+
+import os
+import tomllib
+from pathlib import Path
+
+
+def load(plugin_path: str | os.PathLike) -> dict:
+ p = Path(plugin_path)
+ p = p / "sport.toml" if p.is_dir() else p.with_name("sport.toml")
+ if not p.exists():
+ return {}
+ return tomllib.loads(p.read_text())
+
+
+def whitelist(decl: dict) -> set[str] | None:
+ fields = (decl.get("observation") or {}).get("fields")
+ return set(fields) if fields is not None else None
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/core/sport.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/core/sport.py
new file mode 100644
index 0000000000..a60647ec26
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/core/sport.py
@@ -0,0 +1,455 @@
+"""Contract ② (docs/framework_zh.md §4.2): the one interface between the core and a sport (sports/<sport>/).
+
+A sport's plugin module exports SPORT. The core calls only the functions below and never names a sport; a sport never
+imports another sport. A sport answers four questions, one group of functions each (10 required):
+
+ world Sport.build(cfg) -> Match Match.step() -> events Match.state_digest() -> hex
+ actions Match.schema(seat) Match.apply(seat, low_cmd) -> info
+ optional high-level plugin: Sport.action_layer(level) -> ActionLayer whose lower() turns a high-level
+ command into a low-level one (the episode log holds LOW-LEVEL commands only)
+ referee Match.phase() -> Phase Match.scores() -> {side: n} Match.tiebreaks() -> [(name, rule)]
+ optional: to_move(), forfeit(), resume(), retire(), ranking()
+ observation Match.observe(seat, query) -> dict (own body + referee information, whitelisted in sport.toml)
+ Match.cameras(seat, query) -> [camera definitions] (drawn by the task's renderer, renderers/)
+
+Optional hooks have defaults in MatchBase; none of them is required by every sport, and the core never branches on a
+sport. Stage-0 hooks (all optional): sides != seats (MatchConfig.sides, Match.entities: one act in flight per entity),
+N sides with a classification (Match.ranking) and in-match retirement (Match.retire), a delayed effect
+(ActionLayer.delay_steps), observation parameters (the `query` of observe/cameras), a team channel (core/channel.py,
+declared in sport.toml) and a scored single format without an opponent (tiebreaks() == []).
+
+Reply images (core 0.2.8, optional): Match.reply_views(seat, cmd, info) names the cameras (and optionally a short
+strip of frames) that show the result of an action; the core snapshots them under the lock right after the action
+took effect, draws them off the lock with the task's renderer (the path of the observation images) and attaches them
+to the action's reply as `observation` (image_png_b64 + tiles, as /observe). In the turn protocol the core also tells
+the sport whose review is due (Match.awaiting_review), so that a sport serving images only on turn can hold them
+back from the other seats while the actor reviews.
+
+Presentation (core 0.2.4, optional, spectators only): sports/<sport>/presentation/presentation.toml dresses the scene
+of Sport.scene(cfg) for spectator renderers (renderers/presentation; e.g. fine visual meshes on a robot's bodies,
+same kinematics). It is not part of the simulator directory and never reaches the players' images, unless the sport
+declares `players` there (core 0.2.9): then the generator bundles it (and the models' files) into the simulator and
+the players' images are drawn from it (core/observe.players_scene; a sport drawing its own images uses
+renderers.players_model).
+"""
+from __future__ import annotations
+
+import hashlib
+import json
+import math
+from dataclasses import asdict, dataclass, field, fields
+from typing import Any, Callable, Protocol
+
+
+@dataclass(frozen=True)
+class MatchConfig:
+ sport: str
+ format: str # single | duel | team | multi (the sport declares which it supports)
+ seats: tuple[str, ...] # e.g. ("A", "B"); the HTTP addresses /<seat>/<endpoint>
+ seed: int
+ first: str | None = None # the side that starts (serves / throws first; the rules say what that means)
+ slowdown: float | None = None # realtime only
+ level: int | None = None # scripted opponent level (single)
+ action_level: str = "high" # high | low
+ play: str = "program" # program | direct
+ params: dict = field(default_factory=dict)
+ sides: dict | None = None # seat -> side; default: every seat is its own side
+ renderer: str | None = None # the renderer of the players' images (renderers/; None = the default)
+
+ def side_of(self, seat: str) -> str:
+ return (self.sides or {}).get(seat, seat)
+
+ def side_list(self) -> list[str]:
+ out: list[str] = []
+ for s in self.seats:
+ if self.side_of(s) not in out:
+ out.append(self.side_of(s))
+ return out
+
+ def seats_of(self, side: str) -> list[str]:
+ return [s for s in self.seats if self.side_of(s) == side]
+
+ def to_json(self) -> dict:
+ d = asdict(self)
+ d["seats"] = list(self.seats)
+ return d
+
+ @staticmethod
+ def from_json(d: dict) -> "MatchConfig":
+ known = {f.name for f in fields(MatchConfig)}
+ return MatchConfig(**{**{k: v for k, v in d.items() if k in known}, "seats": tuple(d["seats"])})
+
+
+PLAYING, UNIT_OVER, FINISHED = "playing", "unit_over", "finished"
+
+
+@dataclass
+class Phase:
+ state: str # PLAYING | UNIT_OVER | FINISHED
+ review: tuple[str, ...] = () # seats that review before play resumes (realtime: usually all seats)
+ reason: str = ""
+
+
+class Refused(Exception):
+ """An action the core must refuse: HTTP `code` (400 bad body, 409 wrong time) with `message`."""
+
+ def __init__(self, message: str, code: int = 400):
+ super().__init__(message)
+ self.code = code
+ self.cause = "" # parse_action: the hidden exception (logs only)
+
+
+Tiebreak = tuple[str, Callable[["Match"], "str | None"]] # (name, rule) -> winning side or None (undecided)
+
+
+class Match(Protocol):
+ k: int # [R] control steps (realtime) / actions (turn) so far
+ dt: float # [R realtime] control step, seconds
+
+ # world
+ def step(self) -> list[dict]: ... # [R realtime] advance one control step; events
+ def state_digest(self) -> str: ... # [R] hex digest of everything that affects the score
+ # actions
+ def schema(self, seat: str) -> dict: ... # [R] the low-level command types and ranges (/spec)
+ def apply(self, seat: str, cmd: dict) -> dict: ... # [R] a LOW-LEVEL command takes effect now; info
+ # referee
+ def phase(self) -> Phase: ... # [R]
+ def scores(self) -> dict[str, float]: ... # [R] by side (informational: tiebreaks decide)
+ def tiebreaks(self) -> list[Tiebreak]: ... # [R] rulebook -> extra play -> last resort; [] = solo
+ # observation
+ def observe(self, seat: str, query: dict | None = None) -> dict: ... # [R] own body + referee information
+ def cameras(self, seat: str, query: dict | None = None) -> list[dict]: ... # [R] camera definitions (renderers/)
+
+
+class MatchBase:
+ """Defaults of every optional hook (a sport subclasses this and overrides what it needs)."""
+ k = 0
+ dt = 0.0
+ awaiting_review = None # turn protocol, set by the core: the seat whose review
+ # is due now (None: nobody's); never part of the digest
+
+ # referee
+ def resume(self) -> None: # leaving a review: frozen-time work (next serve ...)
+ pass
+
+ def to_move(self): # turn protocol: the seat whose turn it is
+ return None
+
+ def forfeit(self, seat, why) -> bool: # record a core decision inside the world (True)
+ return False
+
+ def retire(self, side, why) -> bool: # N sides: True = the match goes on without `side`
+ return False
+
+ def ranking(self): # N sides: the classification, best first
+ return None
+
+ def unit(self) -> int: # index of the current unit (acts of an old unit drop)
+ return 0
+
+ # actions
+ def schema(self, seat) -> dict:
+ return {}
+
+ def entities(self, seat) -> tuple[str, ...]: # what a seat commands; one act in flight per entity
+ return ()
+
+ # observation
+ def cameras(self, seat, query=None) -> list[dict]:
+ return []
+
+ def render_state(self) -> dict: # what a renderer needs to draw the scene now
+ return {}
+
+ def camera_job(self, seat): # a sport that draws its own images: (job, meta)
+ return None, {}
+
+ def reply_views(self, seat, cmd, info) -> dict | None:
+ """The images of an action's result for its reply (core 0.2.8), or None. Called under the lock right after
+ Match.apply(seat, cmd) returned `info` (realtime: only for an act without a delayed effect); it must not change
+ the match, and what it returns must follow from the match state and (seat, cmd, info) alone, so that a replay
+ can draw the same images (python -m core.episode PLUGIN DIR --reply N).
+ {"frames": [{"cameras": [camera definitions, as cameras()],
+ "state": render state (optional; default: render_state() now),
+ "label": short text (optional, e.g. "-200 ms"; shown in the tiles)}, ...],
+ "order": "frame" (default: frame after frame) | "camera" (camera after camera: one strip per camera),
+ "columns": tiles per row (default: sport.toml [observation] columns),
+ "note": one line for the player (optional)}
+ Drawn like the observation images: the task's renderer, the match scene (never a presentation scene),
+ sport.toml [observation] frame_budget_ms for the whole reply image."""
+ return None
+
+ def final_fields(self) -> dict: # sport fields for final.json
+ return {}
+
+ def broadcast_frame(self): # spectator frame (never read back)
+ return None
+
+
+class ActionLayer(Protocol):
+ level: str # "high" | "low"
+ worker: str | None # Sport worker kind that runs prepare(), or None
+ delay_steps: int # realtime: the effect is delay_steps after lowering
+
+ def parse(self, seat: str, body: dict, match: Match, ctx: dict) -> dict: ...
+ # validate a request body (raise Refused); ctx = core facts at the request (e.g. both chess clocks), which the
+ # plugin may copy into the command so that replay sees them
+ def snapshot(self, seat: str, cmd: dict, match: Match, ordinal: int) -> Any: ... # under the lock, for prepare
+ def prepare(self, job: Any) -> Any: ... # off the lock (in `worker` if set); expensive planning
+ def lower(self, seat: str, cmd: dict, prepared: Any, match: Match) -> tuple[dict, dict]: ...
+ # at the effect boundary, cheap: -> (low-level command for Match.apply, info for the reply)
+ def reply(self, seat: str, cmd: dict, info: dict, match: Match) -> dict: ...
+
+
+class LowLayer:
+ """The identity layer: the request body, validated by `validate(seat, body, match, ctx) -> cmd`, is the command."""
+ level = "low"
+ worker = None
+ delay_steps = 0
+
+ def __init__(self, validate):
+ self._validate = validate
+
+ def schema(self, match, seat): # what /spec shows of this layer's commands
+ return match.schema(seat)
+
+ def parse(self, seat, body, match, ctx):
+ return self._validate(seat, body, match, ctx)
+
+ def snapshot(self, seat, cmd, match, ordinal):
+ return None
+
+ def prepare(self, job):
+ return None
+
+ def lower(self, seat, cmd, prepared, match):
+ return cmd, {}
+
+ def reply(self, seat, cmd, info, match):
+ return info
+
+
+def check_command(schema: dict, body: dict) -> dict:
+ """Validate a request body against a Match.schema() and return the clean command (raises Refused).
+
+ schema = {TYPE: {FIELD: {"type": "number"|"integer"|"boolean"|"enum"|"vector", "min", "max", "values", "len",
+ "unit", "doc", "default"}}}; the command is {"type": TYPE, FIELD: value, ...}."""
+ if not isinstance(body, dict):
+ raise Refused("the action must be a JSON object")
+ kind = body.get("type")
+ if kind not in schema:
+ raise Refused(f"unknown action type {kind!r}; one of {sorted(schema)}")
+ out: dict = {"type": kind}
+ spec = schema[kind]
+ extra = sorted(set(body) - set(spec) - {"type", "entity"})
+ if extra:
+ raise Refused(f"unknown field(s) {extra} for {kind}")
+ for name, f in spec.items():
+ if name not in body:
+ if "default" in f:
+ out[name] = f["default"]
+ continue
+ raise Refused(f"{kind} needs {name}")
+ out[name] = _value(name, f, body[name])
+ if "entity" in body:
+ out["entity"] = str(body["entity"])
+ return out
+
+
+def _value(name, f, v):
+ t = f.get("type", "number")
+ if t == "boolean":
+ if not isinstance(v, bool):
+ raise Refused(f"{name} must be true or false")
+ return v
+ if t == "enum":
+ if v not in f["values"]:
+ raise Refused(f"{name} must be one of {f['values']}")
+ return v
+ if t == "vector":
+ if not isinstance(v, list) or len(v) != f["len"]:
+ raise Refused(f"{name} must be a list of {f['len']} numbers")
+ return [_number(f"{name}[{i}]", f, x) for i, x in enumerate(v)]
+ x = _number(name, f, v)
+ if t == "integer":
+ if x != int(x):
+ raise Refused(f"{name} must be an integer")
+ return int(x)
+ return x
+
+
+def _number(name, f, v):
+ if isinstance(v, bool) or not isinstance(v, (int, float)) or (isinstance(v, int) and v.bit_length() > 60) or \
+ not math.isfinite(v):
+ raise Refused(f"{name} must be a finite number")
+ lo, hi = f.get("min", -math.inf), f.get("max", math.inf)
+ if not lo <= v <= hi:
+ raise Refused(f"{name} must be in [{lo}, {hi}]")
+ return round(float(v), f.get("digits", 6))
+
+
+# ------------------------------------------------------------------ request validation (core 0.2.11)
+# Every request body is checked before an endpoint reads it (check_body), and every act body against the action
+# layer's published schema before the layer parses it (check_action). A body that fails, or that makes the layer's
+# parse raise ANY exception, is the player's own error: refused (HTTP 400, counted), never a technical failure.
+BODY_MAX_DEPTH = 10 # nesting of lists / objects (the body object is depth 1)
+BODY_MAX_ITEMS = 4096 # elements of one list, keys of one object
+BODY_MAX_STR = 8192 # characters of one string (keys included)
+BODY_MAX_ABS = 1e15 # |number|: no action of any sport needs more (and a huge integer overflows a float)
+TYPE_MAX_STR = 64 # characters of the action type
+
+
+def check_body(value, depth: int = 1) -> None:
+ """Generic sanity of a decoded JSON request body (raises Refused): finite, bounded numbers; bounded strings, list
+ lengths and nesting."""
+ if depth > BODY_MAX_DEPTH:
+ raise Refused(f"the request is nested deeper than {BODY_MAX_DEPTH} levels")
+ if value is None or isinstance(value, bool):
+ return
+ if isinstance(value, str):
+ if len(value) > BODY_MAX_STR:
+ raise Refused(f"strings are limited to {BODY_MAX_STR} characters")
+ return
+ if isinstance(value, int):
+ if value.bit_length() > 60 or abs(value) > BODY_MAX_ABS:
+ raise Refused(f"numbers are limited to +-{BODY_MAX_ABS:g}")
+ return
+ if isinstance(value, float):
+ if not math.isfinite(value) or abs(value) > BODY_MAX_ABS:
+ raise Refused(f"numbers must be finite and within +-{BODY_MAX_ABS:g}")
+ return
+ if isinstance(value, (list, dict)):
+ if len(value) > BODY_MAX_ITEMS:
+ raise Refused(f"lists and objects are limited to {BODY_MAX_ITEMS} items")
+ for k in value if isinstance(value, dict) else ():
+ if not isinstance(k, str) or len(k) > BODY_MAX_STR:
+ raise Refused("object keys must be strings")
+ for x in value.values() if isinstance(value, dict) else value:
+ check_body(x, depth + 1)
+ return
+ raise Refused("unsupported JSON value")
+
+
+def _is_num(v) -> bool:
+ return not isinstance(v, bool) and isinstance(v, (int, float))
+
+
+def _lens(spec_len) -> set | None:
+ """A field's declared length: an int, or a text such as "1 or 2" (None: not declared)."""
+ if isinstance(spec_len, int) and not isinstance(spec_len, bool):
+ return {spec_len}
+ if isinstance(spec_len, str):
+ return {int(x) for x in spec_len.replace(",", " ").split() if x.isdigit()} or None
+ return None
+
+
+def _check_field(kind: str, name: str, f, v) -> None:
+ """The shape of one declared field (ranges and meaning stay with the layer's parse)."""
+ if not isinstance(f, dict):
+ return
+ t, where = f.get("type", "number"), f"{kind}.{name}"
+ if t in ("number", "integer"):
+ if not _is_num(v):
+ raise Refused(f"{where} must be a number")
+ elif t == "boolean":
+ if not isinstance(v, bool):
+ raise Refused(f"{where} must be true or false")
+ elif t == "enum":
+ if isinstance(v, (list, dict)):
+ raise Refused(f"{where} must be one of {f.get('values')}")
+ elif t == "vector":
+ lens = _lens(f.get("len"))
+ if not isinstance(v, list) or (lens and len(v) not in lens) or not all(_is_num(x) for x in v):
+ raise Refused(f"{where} must be a list of {f.get('len', 'some')} numbers")
+ elif t == "rows":
+ lens, top = _lens(f.get("len")), f.get("max_rows")
+ if not isinstance(v, list) or (isinstance(top, int) and len(v) > top) or not all(
+ isinstance(r, list) and (not lens or len(r) in lens) and all(_is_num(x) for x in r) for r in v):
+ raise Refused(f"{where} must be a list of rows of {f.get('len', 'some')} numbers"
+ + (f", at most {top} rows" if isinstance(top, int) else ""))
+ elif t == "list":
+ if not isinstance(v, list):
+ raise Refused(f"{where} must be a list")
+ elif t == "object":
+ if not isinstance(v, dict):
+ raise Refused(f"{where} must be an object")
+ keys = f.get("keys")
+ if isinstance(keys, (list, tuple)) and set(v) - set(keys):
+ raise Refused(f"{where}: unknown key(s) {sorted(set(v) - set(keys))[:8]}; the keys are {list(keys)}")
+
+
+def check_action(schema, body) -> None:
+ """An act body against the action layer's published schema, before the layer parses it (raises Refused). The
+ type, if given, must be a short string; for a type the schema names, each declared field that is present must
+ have its shape (number, boolean, scalar enum value, vector / rows lengths, list, object keys). Unknown types and
+ fields, ranges and defaults stay with the layer's parse (a layer may take an implicit type)."""
+ if not isinstance(body, dict):
+ raise Refused("the action must be a JSON object")
+ kind = body.get("type")
+ if kind is not None and (not isinstance(kind, str) or len(kind) > TYPE_MAX_STR):
+ raise Refused(f"type must be a string of at most {TYPE_MAX_STR} characters")
+ spec = schema.get(kind) if isinstance(schema, dict) and kind is not None else None
+ if isinstance(spec, dict):
+ for name, f in spec.items():
+ if name in body:
+ _check_field(kind, name, f, body[name])
+
+
+def parse_action(layer, seat: str, body, match, ctx: dict):
+ """What the core runs for every act (and core.local for built-in players): check_body, check_action against the
+ layer's schema (what /spec shows), then layer.parse. ANY exception on the way is the player's own error: Refused
+ (HTTP 400); a malformed action never ends a match as a technical failure. The exception's text is not shown to
+ the player; the caller may log it (`Refused.cause`)."""
+ try:
+ check_body(body)
+ check_action(layer.schema(match, seat) if hasattr(layer, "schema") else {}, body)
+ return layer.parse(seat, body, match, ctx)
+ except Refused:
+ raise
+ except Exception as exc: # noqa: BLE001
+ err = Refused("invalid action: the action layer could not read it (see /spec for the command schema)")
+ err.cause = f"{type(exc).__name__}: {str(exc)[:200]}"
+ raise err from exc
+
+
+class SchemaLayer(LowLayer):
+ """The default low level: the body is checked against Match.schema(seat); `ctx_keys` copies core facts (e.g. the
+ chess clocks) into the command so that the replay sees them."""
+
+ def __init__(self, ctx_keys: tuple[str, ...] = ()):
+ super().__init__(None)
+ self.ctx_keys = ctx_keys
+
+ def parse(self, seat, body, match, ctx):
+ cmd = check_command(match.schema(seat), body)
+ ents = tuple(match.entities(seat))
+ if ents and cmd.get("entity", ents[0]) not in ents:
+ raise Refused(f"entity must be one of {list(ents)}")
+ if ents:
+ cmd.setdefault("entity", ents[0])
+ for k in self.ctx_keys:
+ cmd[k] = ctx.get(k)
+ return cmd
+
+
+class Sport(Protocol):
+ name: str
+ protocol: str # "realtime" | "turn"
+ revision: str # bump on any change that alters play
+ source_dirs: list[str] # whose files enter source_sha (the plugin dir; the core adds itself)
+
+ def build(self, cfg: MatchConfig) -> Match: ...
+ def action_layer(self, level: str) -> ActionLayer: ...
+ def spec(self, cfg: MatchConfig, seat: str, match: Match) -> dict: ...
+ # optional: the scene for renderers, worker processes (render / plan), built-in players
+ def scene(self, cfg: MatchConfig): ... # renderers.base.Scene (needed when cameras() is used);
+ # the MATCH scene: the base of the presentation scene
+ # (sports/<s>/presentation) and the players' images
+ # unless that declares `players`
+ def worker_init(self, kind: str, seat: str, cfg: MatchConfig) -> Any: ...
+ def worker_call(self, obj: Any, kind: str, job: Any) -> dict: ...
+ def players(self) -> dict: ... # {name: factory(spec, seat, seed) -> built-in player}
+
+
+def sha_json(value) -> str:
+ return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"), default=float).encode()).hexdigest()
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/rcb1.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/rcb1.py
@@ -0,0 +1,83 @@
+"""RCB1 — a tiny binary frame for one JSON header plus N raw blobs (videos, image arrays, depth, proprio).
+
+ frame = b"RCB1" | header_len uint32 LE | header JSON (UTF-8) | blob_0 | blob_1 | ...
+ header = {"v": 1, "meta": {...}, "parts": [{"name", "kind", "len", ...}, ...]} # blobs in the same order
+
+kinds: "mp4" (fps, n), "jpeg", "array" (dtype, shape; C-order raw bytes), "json" (utf-8), "bytes".
+Zero dependencies for bytes/json parts; numpy only when you ask for arrays. Used on both sides (server and client),
+over HTTP bodies (Content-Type: application/x-rcb1) and equally usable over a raw socket. `python -m rcb1 unpack f dir`.
+"""
+from __future__ import annotations
+import json, struct, sys, pathlib
+
+MAGIC = b"RCB1"
+
+
+def encode(meta: dict, parts: list[tuple[str, str, bytes, dict]]) -> bytes:
+ """parts: [(name, kind, blob, extra), ...]; extra carries dtype/shape/fps/n."""
+ hdr_parts = []
+ for name, kind, blob, extra in parts:
+ d = {"name": name, "kind": kind, "len": len(blob)}
+ d.update({k: v for k, v in (extra or {}).items() if v is not None})
+ hdr_parts.append(d)
+ header = json.dumps({"v": 1, "meta": meta, "parts": hdr_parts}, separators=(",", ":")).encode()
+ return b"".join([MAGIC, struct.pack("<I", len(header)), header] + [blob for _, _, blob, _ in parts])
+
+
+def array_part(name: str, arr, extra: dict | None = None) -> tuple[str, str, bytes, dict]:
+ import numpy as np
+ a = np.ascontiguousarray(arr)
+ return (name, "array", a.tobytes(), {"dtype": str(a.dtype), "shape": list(a.shape), **(extra or {})})
+
+
+def decode(buf: bytes, arrays: bool = True) -> tuple[dict, dict]:
+ """-> (meta, parts) where parts[name] = {"kind", ..., "data"}; arrays become numpy arrays when arrays=True."""
+ if buf[:4] != MAGIC:
+ raise ValueError("not an RCB1 frame")
+ n = struct.unpack("<I", buf[4:8])[0]
+ header = json.loads(buf[8:8 + n].decode()); off = 8 + n
+ out = {}
+ for p in header["parts"]:
+ blob = buf[off:off + p["len"]]; off += p["len"]
+ d = dict(p)
+ if p["kind"] == "array" and arrays:
+ import numpy as np
+ d["data"] = np.frombuffer(blob, dtype=np.dtype(p["dtype"])).reshape(p["shape"])
+ elif p["kind"] == "json":
+ d["data"] = json.loads(blob.decode())
+ else:
+ d["data"] = blob
+ out[p["name"]] = d
+ return header.get("meta", {}), out
+
+
+def unpack_to_dir(buf: bytes, out_dir: str) -> list[str]:
+ """Write a frame's parts as files: mp4/jpeg/bytes verbatim, arrays as .npy, meta as meta.json."""
+ import numpy as np
+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)
+ meta, parts = decode(buf, arrays=True); written = []
+ (out / "meta.json").write_text(json.dumps(meta, indent=1)); written.append("meta.json")
+ for name, p in parts.items():
+ safe = name.replace("/", "__")
+ if p["kind"] == "array":
+ f = out / f"{safe}.npy"; np.save(f, p["data"])
+ elif p["kind"] == "mp4":
+ f = out / f"{safe}.mp4"; f.write_bytes(p["data"])
+ elif p["kind"] == "jpeg":
+ f = out / f"{safe}.jpg"; f.write_bytes(p["data"])
+ elif p["kind"] == "json":
+ f = out / f"{safe}.json"; f.write_text(json.dumps(p["data"], indent=1))
+ else:
+ f = out / f"{safe}.bin"; f.write_bytes(p["data"])
+ written.append(f.name)
+ return written
+
+
+if __name__ == "__main__":
+ if len(sys.argv) == 4 and sys.argv[1] == "unpack":
+ print("\n".join(unpack_to_dir(open(sys.argv[2], "rb").read(), sys.argv[3])))
+ elif len(sys.argv) == 3 and sys.argv[1] == "info":
+ meta, parts = decode(open(sys.argv[2], "rb").read(), arrays=False)
+ print(json.dumps(meta, indent=1)); [print(n, {k: v for k, v in p.items() if k != "data"}) for n, p in parts.items()]
+ else:
+ print(__doc__)
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/rcb_olympics.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/rcb_olympics.py
new file mode 100644
index 0000000000..f62893059e
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/rcb_olympics.py
@@ -0,0 +1,723 @@
+"""RoboOlympics sports behind eai-standard/2.3 (docs/PROTOCOL.md §4b; docs/benchmarks/roboolympics.md): the adapter
+that puts one RoboOlympics match (a sport plugin under sport/, core/sport.py's contract ②) behind rcb_service's `Sim`
+contract. The protocol itself -- the endpoints, RCB1, the realtime clock and its plan, budgets, evidence, crash
+recovery, finalize -- is rcb_realtime.py + rcb_service.py, unchanged (copied from HumanoidBench's 2.3 layer).
+
+The world. One control step of the service is one control step of the match (Match.step(), 10 ms of game time), with
+one exception, the break: when a unit ends (a point, a rally) the match stands still for BREAK_S of game time -- the
+clock keeps running (the service's control steps go on at 1/S of real speed, the agent's plan is consumed), nothing
+moves, nothing scores -- and play resumes by itself when the break is over, or at the agent's `ready` row, whichever
+comes first. Like a break in a real match: the time passes, the game does not.
+
+Actions. The agent's rows are the sport's own commands (the RoboOlympics action layer of the task's level), one row per
+command: table tennis and badminton (high level) `stroke` (the paddle's / racket's state at contact, t seconds after
+the command takes effect; the service plans the swing), badminton's `toss` (the serve), `rest` (back to the ready
+pose), air hockey (low level) `mallet` (the mallet's target, a row per control step, interpolable) and `stop`; every
+sport `ready`. A command takes effect at the control step its row is planned for: the sport's action layer parses it
+there, plans it from the state of that step and lowers it to a low-level command (core/sport.py ActionLayer.lower),
+which Match.apply() installs before the step runs -- the RoboOlympics realtime service's effect boundary. A row the
+sport refuses at that moment (e.g. a toss when it is not your serve) changes nothing and is counted in proprio.
+
+The journal. A sim row is [command id, ready]: the id of the low-level command that took effect at that step (-1:
+none), and 1 when the step carries the agent's ready. The low-level commands themselves are kept in
+DATA/commands.jsonl (one JSON line per id, written before the row that names it), so the journal plus that table is the
+whole record: a replay re-applies exactly the commands the live match applied, at their steps, and never plans again.
+The match is bit-exact (the RoboOlympics sports' golden replays), so a crash resumes by replaying the journal and a
+fresh-process replay decides the verdict (`success` = a finished match the agent won).
+"""
+from __future__ import annotations
+
+import hashlib
+import importlib.util
+import json
+import math
+import os
+import subprocess
+import sys
+import tempfile
+
+import numpy as np
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+if HERE not in sys.path:
+ sys.path.insert(0, HERE)
+
+from core import spec as spec_mod # noqa: E402
+from core.outcome import decide # noqa: E402
+from core.sport import FINISHED, UNIT_OVER, MatchConfig, Refused, parse_action # noqa: E402
+
+BREAK_S = 12.0 # game seconds of the break after every unit (120 s of wall time at S = 10)
+NAN = float("nan")
+READY_DOC = ("end the break now (between units only; ignored during play): play resumes at the next control step "
+ "(the row's value is ignored; put your review in submit's note)")
+
+
+def load_plugin(path: str):
+ """The sport's plugin module at `path` (its directory first on sys.path, so its simulator modules import); its
+ SPORT is the sport."""
+ path = os.path.abspath(path)
+ if os.path.dirname(path) not in sys.path:
+ sys.path.insert(0, os.path.dirname(path))
+ spec = importlib.util.spec_from_file_location("ro_plugin", path)
+ mod = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(mod)
+ return mod
+
+
+def _f(x, default=NAN) -> float:
+ try:
+ return float(x)
+ except (TypeError, ValueError):
+ return default
+
+
+def _json(x):
+ """JSON-exact Python values: what DATA/commands.jsonl holds, so the live match applies what a replay reads back."""
+ return json.loads(json.dumps(x, default=lambda o: o.tolist() if hasattr(o, "tolist") else float(o)))
+
+
+def _clip_box(row, i, lo, hi, name, out, k):
+ v = float(row[i])
+ c = min(max(v, lo), hi)
+ if c != v:
+ out.append({"row": k, "index": i, "reason": f"{name} clipped to [{lo:g}, {hi:g}]"})
+ row[i] = c
+
+
+def _clip_norm(row, sl, cap, name, out, k):
+ v = np.asarray(row[sl], float)
+ n = float(np.linalg.norm(v))
+ if n > cap:
+ row[sl] = v * (cap / n)
+ out.append({"row": k, "index": sl.start, "reason": f"|{name}| = {n:.3f} scaled to {cap:g}"})
+
+
+def _heard(o: dict, names: dict) -> list:
+ """The first time of each heard event (seconds on the current ball's clock), NaN if not heard."""
+ out = []
+ for key in names.values():
+ out.append(next((_f(h.get("t")) for h in o.get("heard") or [] if h.get("event") == key), NAN))
+ return out
+
+
+def _last_point(points, you="you") -> float:
+ if not points:
+ return NAN
+ w = points[-1].get("winner")
+ return 1.0 if w == you else 0.0 if w in (None, "let") else -1.0
+
+
+# ================================================================================================ per-sport profiles
+class _Profile:
+ """What differs between the sports: the agent's action types (as rows), their limits, the proprio columns, the
+ cameras and how they are drawn."""
+ types: dict = {}
+ interp: tuple = ()
+ cams: dict = {}
+ drop: tuple = () # sport.toml [spec] / Sport.spec() entries about RoboOlympics' own interface
+ rules: dict = {} # ... and what replaces them here
+
+ def __init__(self, sim):
+ self.sim = sim
+
+ def body(self, typ, row): # an agent row -> the sport's act body (None: nothing new)
+ raise NotImplementedError
+
+ def clip(self, typ, rows):
+ return rows, []
+
+ def command(self, typ):
+ """The row a gap in the plan is filled with (rcb_realtime: a submit whose `at` lies ahead holds "the target in
+ force" until then; a row is also interpolated from it): for a command that is not a target, zeros, which
+ to_sim reads as no command. No agent row is all zeros after clip() (Olympics.clip)."""
+ return np.zeros(int(self.types[typ]["dim"]))
+
+ def proprio(self) -> list:
+ raise NotImplementedError
+
+ def images(self, cams) -> dict:
+ raise NotImplementedError
+
+
+def _stroke_type(what, t_max, box, extra=""):
+ return {"dim": 10, "layout": ["t", "x", "y", "z", "nx", "ny", "nz", "vx", "vy", "vz"],
+ "units": "s, m, unit-free normal, m/s (your frame)",
+ "limits": {"t": [0.0, t_max], **box, "normal": "non-zero", "speed_max": 8.0},
+ "semantics": (f"the {what}'s state at contact t seconds after the command takes effect: centre x y z, face "
+ f"normal nx ny nz (pointing where the ball should go), velocity vx vy vz; it replaces the "
+ f"stroke under way; the service plans the swing (IK, joint speed limits) and the robot goes "
+ f"back to its ready pose after it. Out-of-range values are clipped (meta.clipped){extra}"),
+ "interpolable": False}
+
+
+class TableTennis(_Profile):
+ types = {
+ "stroke": _stroke_type("paddle blade", 2.5, {"x": [-1.2, 1.2], "y": [-2.5, -0.5], "z": [0.0, 1.2]},
+ "; the delivered state scatters by about 4 mm, 0.6 degrees and 2 %"),
+ "rest": {"dim": 1, "layout": ["unused"], "interpolable": False,
+ "semantics": "cancel the stroke under way: the arm returns to its ready pose (the value is ignored)"},
+ "ready": {"dim": 1, "layout": ["unused"], "interpolable": False, "semantics": READY_DOC}}
+ drop = ("duel", "observation", "action_high", "action_low", "real_time", "scatter_and_seed")
+ rules = {"scatter": "the serves, the opponent's returns and your strokes' execution scatter are drawn from the "
+ "task's frozen seed (never shown)"}
+ HEARD = {"opp_bounce": "bounce on the opponent's half", "own_bounce": "bounce on your half", "net": "net",
+ "paddle": "paddle", "robot": "robot", "floor": "floor"}
+ layout = (["score_you", "score_opponent", "point", "ball_is_serve", "t_since_played", "serve_in_s",
+ "ball_in_play", "ball_coming", "ball_going"]
+ + [f"heard_{k}_t" for k in HEARD]
+ + [f"q{i}" for i in range(1, 8)] + ["paddle_x", "paddle_y", "paddle_z", "paddle_nx", "paddle_ny", "paddle_nz"]
+ + ["stroke_active", "stroke_contact_in_s", "stroke_speed_scale", "stroke_blade_error_m",
+ "stroke_normal_error_deg", "stroke_ik_residual", "last_point_won"])
+
+ def __init__(self, sim):
+ super().__init__(sim)
+ import match
+ self.cams = {c["name"]: dict(c, fovy_deg=45.0, hw=[360, 480], focal_px=434.6, principal_point_px=[240, 180])
+ for c in match.Match.CAM_INFO}
+ self.view = None
+
+ def body(self, typ, row):
+ if typ == "rest":
+ return {"type": "none"}
+ r = [float(x) for x in row]
+ return {"type": "act", "t": r[0], "pos": r[1:4], "normal": r[4:7], "vel": r[7:10]}
+
+ def clip(self, typ, rows):
+ out = []
+ if typ != "stroke":
+ return rows, out
+ rows = np.array(rows, dtype=np.float64)
+ for k, row in enumerate(rows):
+ _clip_box(row, 0, 0.01, 2.5, "t", out, k)
+ for i, (lo, hi) in zip((1, 2, 3), ((-1.2, 1.2), (-2.5, -0.5), (0.0, 1.2))):
+ _clip_box(row, i, lo, hi, "xyz"[i - 1], out, k)
+ if np.linalg.norm(row[4:7]) < 1e-6:
+ row[4:7] = [0.0, 1.0, 0.0]
+ out.append({"row": k, "index": 4, "reason": "a zero normal replaced by (0, 1, 0)"})
+ _clip_norm(row, slice(7, 10), 8.0, "vel", out, k)
+ return rows, out
+
+ def proprio(self):
+ m = self.sim.m
+ o = m.observe(self.sim.seat)
+ R = m.R
+ bs = o.get("ball_state")
+ cmd = o.get("command")
+ la = getattr(R, "_last_act", None) or {}
+ active = isinstance(cmd, dict)
+ return ([_f(o["score"]["you"]), _f(o["score"]["opponent"]), _f(o.get("point")),
+ 1.0 if o.get("ball") == "serve" else 0.0, _f(o.get("t_since_played")), _f(o.get("serve_in_s"), 0.0),
+ float(bool(o.get("ball_in_play"))), float(bs == "coming to you"), float(bs == "going to the opponent")]
+ + _heard(o, self.HEARD) + [_f(x) for x in o["q"]] + [_f(x) for x in o["paddle_pos"]]
+ + [_f(x) for x in o["paddle_normal"]]
+ + [float(active), _f(cmd.get("contact_in_s")) if active else NAN,
+ _f(la.get("speed_scale")) if active else NAN, _f(la.get("blade_error_m")) if active else NAN,
+ _f(la.get("normal_error_deg")) if active else NAN, _f(la.get("ik_residual")) if active else NAN,
+ _last_point(R.points)])
+
+ def images(self, cams):
+ if self.view is None:
+ self.view = self.sim.mod.MatchView()
+ import match
+ R = self.sim.m.R
+ names = list(self.cams)
+ q, ox = R.s.d.qpos.copy(), R.opp_x()
+ text = f"k={R.k} t={R.t_since_launch():.2f}s"
+ return {c: self.view.tile(names.index(c), q, text, lambda scn, o=ox: match.Match._extra_geoms(None, scn, o), ox)
+ for c in cams}
+
+
+class Badminton(_Profile):
+ types = {
+ "stroke": _stroke_type("racket head", 5.0, {"x": [-3.4, 3.4], "y": [-7.5, -0.3], "z": [0.2, 3.0]},
+ "; it takes effect spec.rules.act.lead_steps control steps after its row's step (the "
+ "planning time), and t counts from then; a stroke or toss sent before the previous one "
+ "took effect is refused"),
+ "toss": {"dim": 4, "layout": ["x", "y", "z", "height"], "units": "m (your frame)", "interpolable": False,
+ "limits": {"z": [0.5, 1.8], "height": [0.0, 0.5], "y_max": -0.5, "reach_from_base": 1.0},
+ "semantics": ("your serve: the shuttle appears at x y z (from rest, or rising `height` straight up) "
+ "when the command takes effect (the same lead as a stroke); only the server, once per "
+ "serve, from the step the receiver is ready (proprio serve_phase = 1, open); then hit "
+ "it with a stroke (which may be sent before the toss)")},
+ "rest": {"dim": 1, "layout": ["unused"], "interpolable": False,
+ "semantics": "cancel the stroke under way: the robot returns to its ready pose, the base home"},
+ "ready": {"dim": 1, "layout": ["unused"], "interpolable": False, "semantics": READY_DOC}}
+ drop = ("duel", "observation", "lowlevel", "act")
+ PHASES = {"waiting": 0.0, "open": 1.0, "tossed": 2.0, "done": 3.0}
+ layout = (["score_you", "score_opponent", "point", "you_serve", "serve_court_right", "serve_phase",
+ "serve_opens_in_s", "serve_deadline_in_s", "serve_tossed_at_step", "ball_kind", "t_since_played",
+ "ball_in_play", "ball_not_served", "ball_tossed", "ball_coming", "ball_going",
+ "base_x", "base_y"] + [f"q{i}" for i in range(1, 8)]
+ + ["racket_x", "racket_y", "racket_z", "racket_nx", "racket_ny", "racket_nz",
+ "stroke_active", "stroke_contact_in_s", "stroke_traj_steps_left", "stroke_pending_effect_step",
+ "stroke_head_speed_limited", "stroke_pose_not_delivered", "last_point_won"])
+
+ def __init__(self, sim):
+ super().__init__(sim)
+ import bm
+ FOCAL_PX = sim.mod.FOCAL_PX
+ self.TOSS_Z, self.TOSS_H = tuple(bm.TOSS_Z), float(bm.TOSS_H_MAX)
+ self.types = dict(self.types)
+ self.types["toss"] = dict(self.types["toss"], limits={"z": list(bm.TOSS_Z), "height": [0.0, bm.TOSS_H_MAX],
+ "y_max": -0.5, "reach_from_base": bm.TOSS_REACH})
+ lead = sim.mod.lead_steps(sim.cfg.slowdown)
+ self.rules = {"act": {"lead_steps": lead, "lead_game_s": round(lead * bm.CONTROL_DT, 4),
+ "rule": (f"a stroke, a toss or a rest takes effect {lead} control steps after the step "
+ "its row is planned for (the stroke is planned meanwhile; proprio "
+ "stroke_pending_effect_step shows it); a stroke's t counts from that effect "
+ "step; another stroke, toss or rest planned before then is refused")},
+ "serve": {"command": ("a `toss` row: the shuttle appears at x y z when the command takes effect "
+ "(the same lead as a stroke) and rises `height` straight up (0: released "
+ "from rest); then hit it with a stroke (it may be sent before the toss)"),
+ "phases": ("proprio serve_phase: 0 waiting (the receiver is getting ready), 1 open "
+ "(toss now), 2 tossed, 3 done")}}
+ w, h = bm.Match.TILE
+ self.cams = {c["name"]: dict(c, fovy_deg=45.0, hw=[h, w], focal_px=FOCAL_PX, principal_point_px=[w / 2, h / 2])
+ for c in bm.Match.cam_info()}
+ self.view = None
+
+ def body(self, typ, row):
+ r = [float(x) for x in row]
+ if typ == "rest":
+ return {"type": "none"}
+ if typ == "toss":
+ return {"type": "toss", "pos": r[0:3], "height": r[3]}
+ return {"type": "act", "t": r[0], "pos": r[1:4], "normal": r[4:7], "vel": r[7:10]}
+
+ def clip(self, typ, rows):
+ out = []
+ rows = np.array(rows, dtype=np.float64)
+ if typ == "stroke":
+ for k, row in enumerate(rows):
+ _clip_box(row, 0, 0.01, 5.0, "t", out, k)
+ for i, (lo, hi) in zip((1, 2, 3), ((-3.4, 3.4), (-7.5, -0.3), (0.2, 3.0))):
+ _clip_box(row, i, lo, hi, "xyz"[i - 1], out, k)
+ if np.linalg.norm(row[4:7]) < 1e-6:
+ row[4:7] = [0.0, 1.0, 0.0]
+ out.append({"row": k, "index": 4, "reason": "a zero normal replaced by (0, 1, 0)"})
+ _clip_norm(row, slice(7, 10), 8.0, "vel", out, k)
+ elif typ == "toss":
+ for k, row in enumerate(rows):
+ _clip_box(row, 1, -7.5, -0.5, "y", out, k)
+ _clip_box(row, 2, self.TOSS_Z[0], self.TOSS_Z[1], "z", out, k)
+ _clip_box(row, 3, 0.0, self.TOSS_H, "height", out, k)
+ return rows, out
+
+ def proprio(self):
+ m = self.sim.m
+ o = m.observe(self.sim.seat)
+ sv = o.get("serve") or {}
+ bs = str(o.get("ball_state") or "")
+ cmd = o.get("command")
+ active = isinstance(cmd, dict) and "contact_in_s" in cmd
+ notes = str(cmd.get("stroke") or "") if active else ""
+ pend = o.get("pending_commands") or []
+ kind = {"serve": 0.0, "your serve": 1.0}.get(o.get("ball"), 2.0)
+ return ([_f(o["score"]["you"]), _f(o["score"]["opponent"]), _f(o.get("point")), float(bool(o.get("you_serve"))),
+ float(sv.get("court") == "right"), self.PHASES.get(sv.get("phase"), NAN), _f(sv.get("opens_in_s")),
+ _f(sv.get("deadline_in_s")), _f(sv.get("tossed_at_step")), kind, _f(o.get("t_since_played")),
+ float(bool(o.get("ball_in_play"))), float(bs == "not yet served"), float(bs.startswith("tossed")),
+ float(bs == "coming to you"), float(bs == "going to the opponent")]
+ + [_f(x) for x in o["robot_base_xy"]] + [_f(x) for x in o["q_arm"]] + [_f(x) for x in o["racket_pos"]]
+ + [_f(x) for x in o["racket_normal"]]
+ + [float(active), _f(cmd.get("contact_in_s")) if active else NAN,
+ _f(cmd.get("traj_steps_left"), 0.0) if isinstance(cmd, dict) else 0.0,
+ _f(pend[0].get("takes_effect_at_step")) if pend else NAN,
+ float("head speed limited" in notes), float("pose not delivered" in notes),
+ _last_point(m.g.points)])
+
+ def images(self, cams):
+ if self.view is None:
+ self.view = self.sim.mod.Views(True, "A")
+ g = self.sim.m.g
+ sn = {"qpos": g.s.d.qpos.copy(), "sh": tuple(float(x) for x in g.s.sh_p),
+ "shv": tuple(float(x) for x in g.s.sh_v), "opp": [float(x) for x in g.opp_xy()],
+ "k": int(g.k), "t": float(g.t_since_launch())}
+ names = list(self.cams)
+ return {c: self.view.tile(names.index(c), sn) for c in cams}
+
+
+class AirHockey(_Profile):
+ types = {
+ "mallet": {"dim": 2, "layout": ["x", "y"], "units": "m (the table frame)", "interpolable": True,
+ "semantics": ("the mallet centre's target; the robot drives the mallet there along a speed- and "
+ "acceleration-limited path (spec.sport.mallet_path) and holds it until replaced; "
+ "own half only: a target outside the workspace (spec.sport.workspace) is moved to "
+ "its nearest point (meta.clipped)")},
+ "stop": {"dim": 1, "layout": ["unused"], "interpolable": False,
+ "semantics": "the mallet stops where it is (its target becomes its position)"},
+ "ready": {"dim": 1, "layout": ["unused"], "interpolable": False, "semantics": READY_DOC}}
+ interp = ("mallet",)
+ drop = ("real_time", "action", "observation")
+ rules = {"review": ("every goal, foul or dead puck ends the rally: both mallets return home, the break follows "
+ "(spec.break), then the next rally starts")}
+ HOW = {"goal": 1.0, "seven_second_foul": 2.0, "dead_puck": 3.0, "time_cap": 4.0}
+ layout = (["score_you", "score_opponent", "rally", "t_play", "play_time_left_s",
+ "mallet_x", "mallet_y", "mallet_z", "target_x", "target_y"]
+ + [f"q{i}" for i in range(1, 8)] + ["q_striker1", "q_striker2"]
+ + [f"qd{i}" for i in range(1, 8)] + ["qd_striker1", "qd_striker2"]
+ + ["last_rally_how", "last_rally_scored", "last_rally_fouled", "last_rally_next_puck"])
+
+ def __init__(self, sim):
+ super().__init__(sim)
+ from renderers.base import CameraDef
+ self.P = sim.mod
+ self.camdefs = [CameraDef.from_dict(c) for c in sim.m.cameras(sim.seat)]
+ self.cams = {c.name: dict(c.to_dict(), **c.intrinsics(), hw=[c.height, c.width]) for c in self.camdefs}
+ self.renderer = None
+
+ def body(self, typ, row):
+ h = self.sim.m.h
+ if typ == "stop":
+ return {"type": "none"}
+ x, y = float(row[0]), float(row[1])
+ cur = h.commands.get(self.sim.seat) if isinstance(h.commands, dict) else None
+ if cur is not None and abs(float(cur[0]) - x) < 1e-9 and abs(float(cur[1]) - y) < 1e-9:
+ return None # the target in force: nothing new
+ return {"type": "target", "x": x, "y": y}
+
+ def clip(self, typ, rows):
+ out = []
+ rows = np.array(rows, dtype=np.float64)
+ if typ != "mallet":
+ return rows, out
+ H = self.P.H
+ for k, row in enumerate(rows):
+ w = H.workspace(self.sim.seat, row)
+ if not H.in_workspace(self.sim.seat, w, eps=0.0): # the box-then-radial clip may land a hair outside
+ w = H.workspace(self.sim.seat, [w[0] * 0.999999, w[1] * 0.999999])
+ w = [round(float(w[0]), 6), round(float(w[1]), 6)]
+ if abs(w[0] - row[0]) > 1e-9 or abs(w[1] - row[1]) > 1e-9:
+ out.append({"row": k, "index": 0, "reason": "outside the mallet workspace: moved to its nearest point"})
+ row[0], row[1] = w
+ return rows, out
+
+ def command(self, typ):
+ if typ == "mallet":
+ h = self.sim.m.h
+ return np.asarray(h.commands[self.sim.seat], np.float64)
+ return super().command(typ)
+
+ def proprio(self):
+ m = self.sim.m
+ o = m.observe(self.sim.seat)
+ h = m.h
+ sc = h.scores()
+ last = h.results[-1] if h.results else None
+ side = lambda s: NAN if last is None else (1.0 if s == "A" else -1.0 if s == "B" else 0.0) # noqa: E731
+ return ([_f(sc["A"]["points"]), _f(sc["B"]["points"]), _f(o["rally"]), _f(o["t_play"]),
+ _f(o["play_time_left_s"])] + [_f(x) for x in o["own"]["mallet_xyz"]]
+ + [_f(x) for x in o["own"]["command"]] + [_f(x) for x in o["own"]["joint_position"]]
+ + [_f(x) for x in o["own"]["joint_velocity"]]
+ + [NAN if last is None else self.HOW.get(last["how"], 5.0), side(last and last["winner"]),
+ side(last and last["guilty"]), side(last and last["next"])])
+
+ def images(self, cams):
+ if self.renderer is None:
+ import renderers
+ from core.observe import players_scene
+ sim = self.sim
+ self.renderer = renderers.load(sim.cfg.renderer or renderers.DEFAULT)(
+ players_scene(sim.sport, sim.plugin, sim.cfg))
+ imgs = self.renderer.render(self.sim.m.render_state(), self.camdefs)
+ return {c.name: img for c, img in zip(self.camdefs, imgs) if c.name in cams}
+
+
+PROFILES = {"tabletennis": TableTennis, "badminton": Badminton, "airhockey": AirHockey}
+
+
+# ================================================================================================ the Sim contract
+class Olympics:
+ """One RoboOlympics match against the scripted opponent (seat A) behind rcb_service.Sim (module docstring)."""
+
+ raw_dim = 2 # [command id (-1: none), ready]
+ depth_cameras: tuple = ()
+
+ def __init__(self, plugin: str, cfg: MatchConfig, data: str | None = None, task_text: str = "",
+ episode_text: str = "", break_s: float = BREAK_S):
+ self.plugin, self.cfg, self.data = os.path.abspath(plugin), cfg, data
+ self.mod = load_plugin(self.plugin)
+ self.sport = self.mod.SPORT
+ self.decl = spec_mod.load(self.plugin)
+ self.seat = cfg.seats[0]
+ self.task_text, self.episode_text = task_text, episode_text
+ self.commands: list = []
+ self.cmd_path = os.path.join(data, "commands.jsonl") if data else None
+ if self.cmd_path and os.path.exists(self.cmd_path): # a resumed service: the table so far
+ with open(self.cmd_path) as f:
+ for line in f:
+ try:
+ rec = json.loads(line)
+ except ValueError:
+ break # a line cut by a crash: no journal row names it
+ if rec.get("id") == len(self.commands):
+ self.commands.append(rec["low"])
+ self._new_match()
+ self.control_dt = float(self.m.dt)
+ self.break_steps = max(1, int(round(break_s / self.control_dt)))
+ self.max_control_steps = 10 ** 8 # no step cap: the match ends by its rules, else the wall clock
+ self.profile = PROFILES[self.sport.name](self)
+ self.cameras = tuple(self.profile.cams)
+ self.proprio_layout = (["match_step", "break", "break_left_s", "finished"] + list(self.profile.layout)
+ + ["commands_applied", "commands_refused", "last_refused_step"])
+
+ def _new_match(self):
+ self.m = self.sport.build(self.cfg)
+ self.layer = self.sport.action_layer(self.cfg.action_level)
+ self.steps = 0 # control steps of this episode, breaks included
+ self.in_break, self.break_left, self.breaks = False, 0, []
+ self.finished = self.won = False
+ self.applied = self.refused = self.dropped = 0
+ self.last_refused = -1
+
+ # ------------------------------------------------------------------ facts
+ def spec(self) -> dict:
+ sport = dict(self.decl.get("spec") or {}) # as RoboOlympics' public_spec: sport.toml, then Sport.spec()
+ sport.update(self.sport.spec(self.cfg, self.seat, self.m))
+ for k in ("calls", "image", "image_layout", "cameras", "action_interface") + tuple(self.profile.drop):
+ sport.pop(k, None)
+ for k, v in self.profile.rules.items():
+ sport[k] = {**sport[k], **v} if isinstance(v, dict) and isinstance(sport.get(k), dict) else v
+ if (self.decl.get("tiebreaks") or {}).get("text"):
+ sport["tiebreaks"] = self.decl["tiebreaks"]["text"]
+ types = {k: {kk: vv for kk, vv in v.items() if kk != "interpolable"} for k, v in self.profile.types.items()}
+ s = self.decl.get("sport") or {}
+ return {"simulator": "RoboOlympics on MuJoCo 3.3.7 (CPU)", "sport": s.get("name", self.sport.name),
+ "title": s.get("title"), "revision": self.sport.revision, "robot": sport.pop("robot", None),
+ "task_text": self.task_text, "episode": self.episode_text,
+ "match": {"format": self.cfg.format, "opponent_level": self.cfg.level, "action_level":
+ self.cfg.action_level, "you": self.seat},
+ "action_types": types, "cameras": self.profile.cams, "rules": sport,
+ "break": {"game_s": self.break_steps * self.control_dt, "control_steps": self.break_steps,
+ "rule": ("after every unit (a point, a rally) the match stands still for this much game "
+ "time: the clock runs on (control steps, wall time, your plan), nothing moves and "
+ "nothing scores; play resumes by itself at the end of the break, or at the control "
+ "step of your `ready` row. proprio: break (1 during it), break_left_s")},
+ "proprio_notes": ("one row per frame, columns proprio_layout; NaN = not applicable now; match_step = "
+ "the match's own control step (it stands still in a break; meta.control_steps "
+ "counts every step); times in game seconds; positions in your frame")}
+
+ def interpolable(self, typ: str) -> bool:
+ return typ in self.profile.interp
+
+ # ------------------------------------------------------------------ observation
+ def images(self, cameras, depth):
+ return self.profile.images(list(cameras)), {}
+
+ def proprio(self) -> np.ndarray:
+ own = [float(self.m.k), float(self.in_break), self.break_left * self.control_dt if self.in_break else 0.0,
+ float(self.finished)]
+ return np.asarray(own + self.profile.proprio() + [float(self.applied), float(self.refused),
+ float(self.last_refused)], np.float32)
+
+ # ------------------------------------------------------------------ actions
+ def clip(self, typ, rows):
+ """The profile's limits; a one-value command (rest, stop, ready: the value is ignored) becomes 1, so that no
+ agent row is all zeros, the gap filler's row (command())."""
+ try:
+ if int(self.profile.types.get(typ, {}).get("dim", 0)) == 1 and typ not in self.profile.interp:
+ return np.ones((len(rows), 1)), []
+ return self.profile.clip(typ, rows)
+ except Exception as exc: # noqa: BLE001 -- clip must never fail a request that passed the checks
+ return np.asarray(rows, np.float64), [{"row": 0, "index": 0, "reason": f"unchecked: {exc!r}"[:200]}]
+
+ def command(self, typ):
+ try:
+ return self.profile.command(typ)
+ except Exception: # noqa: BLE001
+ return np.zeros(int(self.profile.types.get(typ, {"dim": 1})["dim"]))
+
+ def hold(self):
+ return "hold", np.zeros(1)
+
+ def to_sim(self, typ, row) -> np.ndarray:
+ """At the step the row is planned for (rcb_service._step, right before step()): the row as a sim row. A
+ command is parsed, planned and lowered here, from this step's state, and enters the command table. An all-zero
+ row of a command type is no command: a gap the service filled with command() (clip() leaves no agent row so)."""
+ if typ not in self.profile.interp and not np.any(np.asarray(row, dtype=np.float64)):
+ return np.array([-1.0, 0.0])
+ if typ == "ready":
+ return np.array([-1.0, 1.0])
+ if typ not in self.profile.types or self.finished:
+ return np.array([-1.0, 0.0])
+ if self.in_break:
+ self.dropped += 1
+ return np.array([-1.0, 0.0])
+ body = self.profile.body(typ, row)
+ if body is None:
+ return np.array([-1.0, 0.0])
+ rec = {"id": len(self.commands), "step": self.steps, "match_k": int(self.m.k), "type": typ,
+ "row": [float(x) for x in row]}
+ try:
+ cmd = parse_action(self.layer, self.seat, body, self.m, {})
+ job = self.layer.snapshot(self.seat, cmd, self.m, self.applied + self.refused + 1)
+ prepared = self.layer.prepare(job) if job is not None else None
+ low, info = self.layer.lower(self.seat, cmd, prepared, self.m)
+ except Refused as exc:
+ self.refused += 1
+ self.last_refused = int(self.m.k)
+ self._log({**rec, "id": None, "refused": str(exc)[:300]})
+ return np.array([-1.0, 0.0])
+ rec.update(low=_json(low), info=_json(info))
+ self.commands.append(rec["low"])
+ self._log(rec)
+ return np.array([float(rec["id"]), 0.0])
+
+ def _log(self, rec):
+ if self.cmd_path:
+ with open(self.cmd_path, "a") as f:
+ f.write(json.dumps(rec, default=float) + "\n")
+ f.flush()
+
+ def step(self, row) -> tuple[bool, bool, dict]:
+ cid, ready = int(round(float(row[0]))), float(row[1]) > 0.5
+ self.steps += 1
+ if self.finished:
+ return True, self.won, {}
+ if self.in_break:
+ if ready or self.break_left <= 1:
+ self.in_break = False
+ self.breaks[-1].update(end=self.steps, by="ready" if ready else "time")
+ self.m.resume()
+ else:
+ self.break_left -= 1
+ return False, False, {}
+ if cid >= 0:
+ info = self.m.apply(self.seat, self.commands[cid]) or {}
+ if isinstance(info, dict) and "rejected" in info:
+ self.refused += 1
+ self.last_refused = int(self.m.k)
+ else:
+ self.applied += 1
+ self.m.step()
+ ph = self.m.phase()
+ if ph.state == FINISHED:
+ self.finished = True
+ out = decide(self.m, None, None, self.cfg.side_list(), self.cfg.side_of)
+ self.won = out.winner == self.cfg.side_of(self.seat)
+ return True, self.won, {}
+ if ph.state == UNIT_OVER:
+ self.in_break, self.break_left = True, self.break_steps
+ self.breaks.append({"start": self.steps, "match_k": int(self.m.k), "reason": ph.reason})
+ return False, False, {}
+
+ # ------------------------------------------------------------------ episode
+ def reset(self) -> None:
+ self._new_match()
+ self.profile = PROFILES[self.sport.name](self)
+
+ def state_sha(self) -> str:
+ own = json.dumps([self.steps, self.in_break, self.break_left, self.finished, self.won], sort_keys=True)
+ return hashlib.sha256((self.m.state_digest() + own).encode()).hexdigest()
+
+ def summary(self) -> dict:
+ out = decide(self.m, None, None, self.cfg.side_list(), self.cfg.side_of)
+ scores = self.m.scores()
+ you = self.cfg.side_of(self.seat)
+ them = [s for s in scores if s != you]
+ return {"sport": self.sport.name, "revision": self.sport.revision, "finished": self.finished,
+ "won": bool(self.finished and out.winner == you), "winner": out.winner, "decided_by": out.decided_by,
+ "scores": scores, "points_for": scores.get(you), "points_against": scores.get(them[0]) if them else None,
+ "match_steps": int(self.m.k), "control_steps": self.steps, "breaks": self.breaks,
+ "commands_applied": self.applied, "commands_refused": self.refused,
+ "rows_dropped_in_breaks": self.dropped, "cfg": self.cfg.to_json(), "break_steps": self.break_steps,
+ "sport_fields": _json(self.m.final_fields())}
+
+ # ------------------------------------------------------------------ the record, the replay, the video
+ def save_trajectory(self, rows, path, meta) -> None:
+ np.savez_compressed(path, rows=np.asarray(rows, np.float64).reshape(-1, self.raw_dim),
+ commands=np.array(json.dumps(self.commands)), cfg=np.array(json.dumps(self.cfg.to_json())),
+ break_steps=np.array(self.break_steps), meta=np.array(json.dumps(meta, default=str)),
+ layout=np.array(json.dumps(["command_id", "ready"])))
+
+ def _sub(self, mode: str, rows, out: str) -> dict:
+ """A fresh process (python rcb_olympics.py MODE ...): the replay never shares state with the live match."""
+ fd, tmp = tempfile.mkstemp(suffix=".npz", dir=self.data or None)
+ os.close(fd)
+ try:
+ self.save_trajectory(rows, tmp, {"for": mode})
+ env = dict(os.environ, RO_TASK_TEXT=self.task_text, RO_EPISODE_TEXT=self.episode_text)
+ r = subprocess.run([sys.executable, os.path.abspath(__file__), mode, self.plugin, tmp, out],
+ capture_output=True, text=True, env=env, timeout=3600)
+ if r.returncode:
+ raise RuntimeError(f"{mode} failed: {r.stderr[-1500:]}")
+ return json.loads(r.stdout.strip().splitlines()[-1])
+ finally:
+ os.unlink(tmp)
+
+ def verify(self, rows) -> dict:
+ out = os.path.join(self.data, "match.json") if self.data else os.devnull
+ rep = self._sub("replay", rows, out)
+ return {"success": bool(rep["won"]), "state_sha": rep["state_sha"]}
+
+ def render_video(self, rows, path) -> None:
+ self._sub("video", rows, path)
+
+
+# ================================================================================================ fresh processes
+def _rebuild(plugin: str, npz: str) -> tuple[Olympics, np.ndarray]:
+ z = np.load(npz)
+ cfg = MatchConfig.from_json(json.loads(str(z["cfg"])))
+ sim = Olympics(plugin, cfg, None, os.environ.get("RO_TASK_TEXT", ""), os.environ.get("RO_EPISODE_TEXT", ""))
+ sim.break_steps = int(z["break_steps"])
+ sim.commands = json.loads(str(z["commands"]))
+ return sim, np.asarray(z["rows"], np.float64).reshape(-1, sim.raw_dim)
+
+
+def replay_main(plugin: str, npz: str, out: str) -> dict:
+ sim, rows = _rebuild(plugin, npz)
+ for row in rows:
+ sim.step(row)
+ summary = {**sim.summary(), "state_sha": sim.state_sha()}
+ with open(out, "w") as f:
+ json.dump(summary, f, default=float)
+ return {"won": summary["won"], "state_sha": summary["state_sha"], "scores": summary["scores"]}
+
+
+def video_main(plugin: str, npz: str, out: str, max_frames: int = 1500) -> dict:
+ """The replay for humans: the cameras side by side, one frame every 4 control steps of play (game time at real speed:
+ 25 fps; sparser for a long match, at most about max_frames frames), breaks skipped; the score in the corner.
+ Writes out and out.last.png."""
+ import imageio.v2 as imageio
+ from PIL import Image, ImageDraw
+ sim, rows = _rebuild(plugin, npz)
+ every = max(4, math.ceil(len(rows) / max_frames))
+ cams = list(sim.cameras)
+ w = imageio.get_writer(out, fps=round(1.0 / (every * sim.control_dt)), macro_block_size=8, codec="libx264",
+ output_params=["-pix_fmt", "yuv420p"])
+ last, n = None, 0
+
+ def frame():
+ imgs = sim.images(cams, False)[0]
+ h = max(i.shape[0] for i in imgs.values())
+ row = np.concatenate([np.pad(imgs[c], ((0, h - imgs[c].shape[0]), (0, 0), (0, 0))) for c in cams], axis=1)
+ im = Image.fromarray(np.ascontiguousarray(row[..., :3]))
+ sc = sim.m.scores()
+ ImageDraw.Draw(im).text((8, im.height - 16), " ".join(f"{k} {v}" for k, v in sc.items()), fill=(255, 255, 0))
+ return np.asarray(im)
+
+ try:
+ for i, row in enumerate(rows):
+ was = sim.in_break
+ sim.step(row)
+ if (not was and i % every == 0) or sim.finished:
+ last = frame()
+ w.append_data(last)
+ n += 1
+ if sim.finished:
+ break
+ if last is None:
+ last = frame()
+ w.append_data(last)
+ n += 1
+ finally:
+ w.close()
+ Image.fromarray(last).save((out[:-4] if out.endswith(".mp4") else out) + ".last.png") # replay.last.png
+ return {"frames": n, "every": every}
+
+
+if __name__ == "__main__":
+ mode, plugin_path, npz_path, out_path = sys.argv[1:5]
+ res = replay_main(plugin_path, npz_path, out_path) if mode == "replay" else video_main(plugin_path, npz_path,
+ out_path)
+ print(json.dumps(res, default=float))
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/rcb_realtime.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/rcb_realtime.py
new file mode 100644
index 0000000000..e23f8cbd2c
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/rcb_realtime.py
@@ -0,0 +1,480 @@
+"""eai-standard/2.3, the standard-realtime mode's protocol: the sim service of HumanoidBench's `-standard-realtime` tasks
+(docs/PROTOCOL.md §4b, docs/LIMITED_MODE_PROTOCOL.md "Standard-realtime mode"; docs/benchmarks/humanoidbench.md). Entry
+point of the sidecar: `python /srv/rcb_realtime.py` (the adapter is server.py's, unchanged). 2.3 is 2.2 plus the realtime
+capability, every 2.2 addition optional: this service is rcb_service's 2.1 service with the capability, and reports
+eai-standard/2.3.
+
+It extends rcb_service.Service: the same endpoints, RCB1 frames, budgets (reset, wall clock), evidence, crash recovery
+and finalize. Only the time model differs. In standard mode time moves only inside calls; here the episode has a clock:
+
+- An episode starts paused, at the frozen start with the servos holding their starting targets. Its clock starts at its
+ first POST /submit or POST /observe with seconds > 0 (again after every reset, and after a crash recovery). From then
+ on one control step runs every control_dt x slowdown seconds of wall time, whether or not the agent sends anything,
+ until the episode ends; the clock stops there.
+- The service keeps a plan: one target row per coming control step. /submit expands its chunk (rows dt apart, `linear`
+ or `hold`, exactly as 2.1 does) into control steps and writes it into the plan from control step `at` (default: the
+ next one), replacing whatever was planned from there on, and answers at once. A chunk that arrives after its `at`
+ loses the rows whose steps are gone (`late_steps`). When the plan runs out the last target is held (zero-order
+ hold): a slow agent's robot keeps its last servo targets.
+- /observe with seconds = 0 answers at once; with seconds > 0 it watches the running episode that long (robot time)
+ and returns what the cameras saw. It never changes the plan.
+- `cameras = []` asks for no images at all (in 2.1 an empty list means every camera): a controller's proprio-only call.
+
+Grading is unchanged: every executed control step's sim row is journaled (trajectory_live.f64) and the graded episode's
+rows are replayed in a fresh simulator at the end. What is graded is the rows the simulator applied, not what was
+submitted, so the replay equals the live run however the timing went. Evidence added (never visible to the agent):
+ticks.f64 (per journal row: wall time, and the call whose chunk gave the row, -1 for a held one), calls.jsonl (one line
+per call; no calls/NNNNNN/ directories: a controller calls 50 times a second) and submitted.f64 (every row as sent:
+call id, then the row). final.json adds realtime, slowdown, max_lag_s, stalls, held_steps and late_steps.
+
+Threads: the simulator and its GL context belong to the main thread, which runs the clock and serves every request in
+between control steps; the HTTP threads only read, queue and encode. A control step that is due runs before any waiting
+request. A service that falls behind (a long render) runs the missed steps back to back, skipping none; more than
+MAX_LAG_S behind, it drops the debt instead (a stall, counted) rather than fast-forward the robot.
+
+A crash resumes the same episode from its last checkpoint (one per second of robot time while the clock runs), paused.
+A simulator crash is an infrastructure failure, never the agent's (PROTOCOL §4b, owner 2026-10-08). No call spans a
+crash here (submit answers at once), so a crash is never put down to the agent's call: past RCB_MAX_RESUMES restarts the
+trial ends `sim_crashed` (infra_error), a failed resume `resume_failed` (infra_error), and a simulator error that ends
+the graded episode (reason "error") sets infra_error in final.json too.
+"""
+from __future__ import annotations
+
+import collections
+import json
+import os
+import queue
+import sys
+import threading
+import time
+import traceback
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from urllib.parse import urlparse
+
+import numpy as np
+
+import rcb_service
+from rcb_service import MAX_BODY, Recorder, Refused, Service, bad_request
+
+PROTOCOL = "eai-standard/2.3" # the standard-realtime mode's protocol (PROTOCOL §4b); rcb_service.py itself serves 2.1
+MAX_LAG_S = 0.5 # behind the clock by more than this: drop the debt (a stall) instead of catching up
+CHECKPOINT_S = 1.0 # robot time between checkpoints while the clock runs (the most a crash loses)
+
+
+class _Job:
+ """One HTTP request, handed from its HTTP thread to the simulator's thread and back."""
+
+ def __init__(self, method: str, path: str, body: bytes, content_length: int | None = None):
+ self.method, self.path, self.body, self.content_length = method, path, body, content_length
+ self.done = threading.Event()
+ self.reply: tuple = () # ("raw", code, ctype, body) | ("rcb1", meta, parts) | ("rec", meta, Recorder)
+
+ def finish(self, *reply) -> None:
+ self.reply = reply
+ self.done.set()
+
+
+class _Watch:
+ """A pending /observe with seconds > 0: completes once its control steps have run (or the episode ended)."""
+
+ def __init__(self, job: _Job, rec: Recorder, start: int, steps: int, cameras: list[str], obs_id: int):
+ self.job, self.rec, self.cameras, self.obs_id = job, rec, cameras, obs_id
+ self.start, self.end = start, start + steps
+
+
+class RealtimeService(Service):
+ """rcb_service.Service with the realtime clock (module docstring)."""
+
+ def __init__(self, sim, *, slowdown: float | None = None, **kw):
+ self.slowdown = float(os.environ.get("RCB_SLOWDOWN") or 1.0) if slowdown is None else float(slowdown)
+ if not self.slowdown > 0:
+ raise ValueError("RCB_SLOWDOWN must be > 0")
+ self.wall_dt = sim.control_dt * self.slowdown
+ self.max_ahead = int(round(float(kw.get("max_chunk_s", 10.0)) / sim.control_dt)) # how far ahead `at` may be
+ self.plan: collections.deque = collections.deque() # (type, row, call id) for each coming control step
+ self.running = False
+ self.anchor_t = self.anchor_n = 0 # the clock: control step anchor_n was due at anchor_t
+ self.watches: list[_Watch] = []
+ self.q: queue.Queue = queue.Queue()
+ self.max_lag = self.lag = 0.0
+ self.stalls = self.held_steps = self.late_steps = 0
+ self._ticks: list[tuple[float, float]] = [] # (wall time, call id) per journal row not yet on disk
+ super().__init__(sim, **kw)
+ self.ticks_path = os.path.join(self.data, "ticks.f64")
+ self.ckpt_every = max(1, int(round(CHECKPOINT_S / sim.control_dt)))
+
+ # ------------------------------------------------------------------ spec, status, evidence
+ def _spec(self) -> dict:
+ spec = super()._spec()
+ spec["protocol"] = PROTOCOL
+ cdt = self.sim.control_dt
+ spec["timing"] = {
+ "realtime": True, "slowdown": self.slowdown, "control_dt": cdt,
+ "wall_s_per_control_step": cdt * self.slowdown,
+ "clock": "an episode starts paused; its clock starts at its first submit or observe with seconds > 0 (also "
+ "after a reset) and then runs one control step every wall_s_per_control_step seconds, whatever "
+ "you do, until the episode ends",
+ "submit": "answers at once: the chunk (rows dt apart, linear or hold) becomes the plan from control step "
+ "`at` (default: the next one), replacing what was planned from there; rows for steps already "
+ "gone are dropped (meta.late_steps); after the plan's last row that target is held",
+ "observe": "seconds = 0: now, at once; seconds > 0: watches the running episode that long and returns what "
+ "the cameras saw; never changes the plan",
+ "max_ahead_steps": self.max_ahead,
+ "no_images": "cameras = [] returns no images, only proprioception (the fastest call)"}
+ return spec
+
+ def _realtime_counters(self) -> dict:
+ return {"running": self.running, "planned_steps": len(self.plan), "lag_s": round(self.lag, 4)}
+
+ def status(self) -> dict:
+ return {**super().status(), **self._realtime_counters()}
+
+ def meta(self) -> dict:
+ return {**super().meta(), **self._realtime_counters()}
+
+ def _timing_record(self) -> dict:
+ return {"protocol": PROTOCOL, "realtime": 1, "slowdown": self.slowdown, "max_lag_s": round(self.max_lag, 4),
+ "stalls": self.stalls, "held_steps": self.held_steps, "late_steps": self.late_steps}
+
+ def _write_final(self) -> None:
+ self.verdict.update(self._timing_record()) # final.json merges the verdict; none of these keys is a verdict's
+ if self.reason == "error": # a simulator error ended the graded episode: infrastructure (§4b)
+ self.verdict["infra_error"] = 1
+ else: # (an episode that erred and was reset away is not graded)
+ self.verdict.pop("infra_error", None)
+ super()._write_final()
+
+ def _checkpoint(self, ev: str, **kw) -> None:
+ if self._ticks: # the tick log first: a crash in between leaves it too long
+ with open(self.ticks_path, "ab") as f:
+ f.write(np.asarray(self._ticks, dtype=np.float64).tobytes())
+ self._ticks = []
+ super()._checkpoint(ev, **kw)
+
+ def _save_call(self, meta: dict, actions: np.ndarray | None) -> None:
+ keep = ("type", "n_rows", "dt", "interpolate", "at", "start_step", "late_steps", "planned_steps", "seconds",
+ "control_steps", "episode", "done", "reason", "n_clipped", "lag_s", "note")
+ line = {"call": self.calls, "ts": time.time(), **{k: meta[k] for k in keep if k in meta}}
+ with open(os.path.join(self.data, "calls.jsonl"), "a") as f:
+ f.write(json.dumps(line) + "\n")
+ if actions is not None:
+ rows = np.concatenate([np.full((len(actions), 1), float(self.calls)), actions], axis=1)
+ with open(os.path.join(self.data, "submitted.f64"), "ab") as f:
+ f.write(np.asarray(rows, dtype=np.float64).tobytes())
+
+ # ------------------------------------------------------------------ start, clock
+ def start(self) -> None:
+ super().start()
+ rows = np.fromfile(self.ticks_path, dtype=np.float64) if os.path.exists(self.ticks_path) else np.zeros(0)
+ n = self.journal_rows
+ if rows.size > 2 * n: # the steps a crash lost from the journal go from the tick log too
+ rows[: 2 * n].tofile(self.ticks_path)
+ elif rows.size < 2 * n: # (an older tick log, short of the journal: pad it as unknown)
+ np.concatenate([rows, np.full(2 * n - rows.size, np.nan)]).tofile(self.ticks_path)
+ self.running = False # a resumed episode waits, paused, for the agent's next call
+
+ def _start_clock(self) -> None:
+ if not self.running and not self.done and not self.stopping:
+ self.running, self.anchor_t, self.anchor_n = True, time.monotonic(), len(self.episode)
+ self.log("clock_start", control_steps=len(self.episode), episode=self.resets + 1)
+
+ def _stop_clock(self, why: str) -> None:
+ if self.running:
+ self.running = False
+ self.log("clock_stop", why=why, control_steps=len(self.episode), max_lag_s=round(self.max_lag, 4))
+ self.plan.clear()
+
+ def _end(self, reason: str) -> None:
+ super()._end(reason)
+ self._stop_clock(reason) # pending watches are completed by whoever ended it, after this
+
+ def due_in(self, now: float) -> float | None:
+ """Seconds until the next control step is due (<= 0: due now); None while the clock is stopped."""
+ if not self.running or self.done or self.stopping:
+ return None
+ return self.anchor_t + (len(self.episode) - self.anchor_n) * self.wall_dt - now
+
+ def tick(self) -> None:
+ """One control step of the clock: the plan's row for it, or the held target."""
+ now = time.monotonic()
+ lag = -(self.due_in(now) or 0.0)
+ if lag > MAX_LAG_S: # far behind: re-anchor rather than rush the robot through the debt
+ self.stalls += 1
+ self.log("stall", behind_s=round(lag, 3), control_steps=len(self.episode))
+ self.anchor_t, self.anchor_n, lag = now, len(self.episode), 0.0
+ self.lag, self.max_lag = max(lag, 0.0), max(self.max_lag, lag)
+ if self.plan:
+ typ, row, src = self.plan.popleft()
+ else:
+ (typ, row), src = self.sim.hold(), -1
+ self.held_steps += 1
+ before = self.journal_rows
+ self._ticks.append((time.time(), float(src)))
+ try:
+ self._step(typ, row)
+ except Exception as exc: # noqa: BLE001 -- it ran and failed: the episode ends, as on hardware
+ traceback.print_exc()
+ if self.journal_rows == before:
+ self._ticks.pop()
+ self.log("error", path="clock", error=repr(exc)[:500])
+ self._end("error")
+ self._release_watches()
+ return
+ for w in list(self.watches):
+ w.rec.step()
+ if self.done or len(self.episode) >= w.end:
+ self._complete_watch(w)
+ if not self.done and len(self.episode) % self.ckpt_every == 0:
+ self._checkpoint("tick")
+
+ # ------------------------------------------------------------------ requests (simulator thread)
+ def dispatch(self, job: _Job) -> None:
+ """Serve one queued request; a watch finishes later, from tick()."""
+ try:
+ self.first_request()
+ path = urlparse(job.path).path
+ if job.method == "GET" and path in ("/spec", "/status"):
+ return job.finish("raw", *self._reply_json(200, self.spec if path == "/spec" else self.status()))
+ routes = {"/submit": self._rt_submit, "/observe": self._rt_observe}
+ if self.reset_budget:
+ routes["/reset"] = self._rt_reset
+ if job.method != "POST" or path not in routes:
+ return job.finish("raw", *self._reply_json(404, {"error": "no such endpoint"}))
+ if (len(job.body) if job.content_length is None else job.content_length) > MAX_BODY:
+ return job.finish("raw", *self._reply_json(413, {"error": f"request body over {MAX_BODY} bytes"}))
+ try:
+ meta, parts = self._decode(job.body)
+ except Exception as exc: # noqa: BLE001 -- any malformed body is the caller's error
+ return job.finish("raw", *self._reply_json(400, {"error": f"malformed body: {exc}"[:300]}))
+ try:
+ routes[path](meta, parts, job)
+ except Refused as exc: # 400 (bad_request), 409: nothing changed
+ job.finish("raw", *self._reply_json(exc.code, exc.body))
+ except Exception as exc: # noqa: BLE001 -- it ran and failed: the episode ends, as on hardware
+ traceback.print_exc()
+ self.log("error", path=path, error=repr(exc)[:500])
+ self._end("error")
+ self._release_watches()
+ if not job.done.is_set():
+ job.finish("raw", *self._reply_json(500, {"error": "simulator error", "detail": repr(exc)[:200]}))
+ except Exception as exc: # noqa: BLE001 -- never leave an HTTP thread waiting forever
+ traceback.print_exc()
+ if not job.done.is_set():
+ job.finish("raw", *self._reply_json(500, {"error": "service error", "detail": repr(exc)[:200]}))
+
+ def _view_rt(self, meta: dict, default_video: str) -> tuple[list[str], int, str, bool]:
+ """2.1's _view, plus cameras = [] for no images."""
+ none = isinstance(meta.get("cameras"), list) and not meta["cameras"]
+ cams, fps, video, depth = self._view(meta, default_video)
+ return ([], fps, "none", False) if none else (cams, fps, video, depth)
+
+ def _planned(self, step: int, nxt: int, typ: str) -> np.ndarray:
+ """The target in force at control step `step` (>= nxt - 1) as things stand: the plan's row for it, else the
+ plan's last row (held), else -- nothing planned, or a step already run -- the current command."""
+ i = step - nxt
+ if i < 0 or not self.plan:
+ return np.asarray(self.sim.command(typ), dtype=np.float64)
+ return np.asarray(self.plan[min(i, len(self.plan) - 1)][1], dtype=np.float64)
+
+ def _rt_submit(self, meta: dict, parts: dict, job: _Job) -> None:
+ if self.done or self.stopping:
+ raise self._conflict()
+ nxt = len(self.episode)
+ with bad_request():
+ typ = meta.get("type")
+ if not isinstance(typ, str) or typ not in self.types:
+ raise ValueError(f"type must be one of {sorted(self.types)}")
+ try:
+ A = np.asarray(parts["actions"]["data"] if "actions" in parts else meta.get("actions"),
+ dtype=np.float64)
+ except (TypeError, ValueError, KeyError):
+ raise ValueError("send the actions as an RCB1 array part `actions` or a JSON list of rows") from None
+ dim = int(self.types[typ]["dim"])
+ if A.ndim != 2 or A.shape[0] < 1 or A.shape[1] != dim:
+ raise ValueError(f"{typ} actions must be (T, {dim}) with T >= 1, got {list(A.shape)}")
+ if not np.all(np.isfinite(A)):
+ raise ValueError("actions contain NaN or inf")
+ cdt = self.sim.control_dt
+ try:
+ dt = cdt if meta.get("dt") is None else float(meta["dt"])
+ except (TypeError, ValueError):
+ raise ValueError("dt must be a number of seconds") from None
+ k = round(dt / cdt) if np.isfinite(dt / cdt) else 0
+ if k < 1 or abs(k * cdt - dt) > 1e-9:
+ raise ValueError(f"dt must be a positive whole multiple of control_dt = {cdt} s (never rounded)")
+ if k > 1 and not self.sim.interpolable(typ):
+ raise ValueError(f"{typ}: one row is one control step, so dt must be control_dt = {cdt} s")
+ if len(A) * k * cdt > self.max_chunk_s + 1e-9:
+ raise ValueError(f"the chunk covers {len(A) * k * cdt:g} s: "
+ f"more than max_chunk_s = {self.max_chunk_s:g}")
+ interp = meta.get("interpolate", "linear")
+ if interp not in ("linear", "hold"):
+ raise ValueError("interpolate must be linear or hold")
+ at = meta.get("at")
+ if at is not None:
+ if isinstance(at, bool) or not isinstance(at, (int, float)) or at != int(at) or at < 0:
+ raise ValueError("at must be a control step of this episode (an integer >= 0), "
+ "or null for the next one")
+ at = int(at)
+ if at - nxt > self.max_ahead:
+ raise ValueError(f"at = {at} is more than max_ahead_steps = {self.max_ahead} control steps ahead "
+ f"of the next one ({nxt})")
+ at = nxt if at is None else at
+ cams, fps, video, depth = self._view_rt(meta, "none")
+ rows, clipped = self.sim.clip(typ, A)
+ prev = self._planned(at - 1, nxt, typ) # linear starts from the target in force just before `at`
+ steps = []
+ for row in rows:
+ for j in range(1, k + 1):
+ steps.append(row if interp == "hold" else prev + (row - prev) * (j / k))
+ prev = row
+ late = max(0, nxt - at)
+ keep = at - nxt if at > nxt else 0
+ self.calls += 1
+ self.rows += len(A)
+ head = list(self.plan)[:keep]
+ if len(head) < keep: # a gap before `at`: the target in force then is held through it
+ fill = self._planned(at - 1, nxt, typ)
+ head += [(typ, fill, -1)] * (keep - len(head))
+ self.plan = collections.deque(head + [(typ, s, self.calls) for s in steps[late:]])
+ self.late_steps += min(late, len(steps))
+ self._start_clock()
+ rec = Recorder(self.sim, cams, fps, depth, "none")
+ rec.start()
+ rec.finish()
+ out = {**self.meta(), "chunk_id": self.calls, "type": typ, "n_rows": int(len(A)), "dt": dt,
+ "interpolate": interp, "at": at, "start_step": max(at, nxt), "late_steps": late,
+ "plan_end_step": nxt + len(self.plan), "clipped": clipped[:200], "n_clipped": len(clipped), "ok": True}
+ self._save_call({**out, "note": str(meta.get("note") or "")[:200]}, A)
+ job.finish("rec", out, rec)
+
+ def _rt_observe(self, meta: dict, parts: dict, job: _Job) -> None:
+ with bad_request():
+ try:
+ seconds = float(meta.get("seconds") or 0.0)
+ except (TypeError, ValueError):
+ raise ValueError("seconds must be a number") from None
+ if not 0.0 <= seconds <= self.max_watch_s:
+ raise ValueError(f"seconds must be in [0, {self.max_watch_s:g}]")
+ cams, fps, video, depth = self._view_rt(meta, "frames")
+ n = int(round(seconds / self.sim.control_dt)) if not (self.done or self.stopping) else 0
+ rec = Recorder(self.sim, cams, fps, depth, video if n or video != "mp4" else "frames") # no time: no video
+ self._frame_budget(rec, n)
+ self.calls += 1
+ rec.start()
+ if not n:
+ rec.finish()
+ out = {**self.meta(), "obs_id": self.calls, "seconds": 0.0, "control_steps_watch": 0, "ok": True}
+ self._save_call(out, None)
+ return job.finish("rec", out, rec)
+ self._start_clock()
+ self.watches.append(_Watch(job, rec, len(self.episode), n, cams, self.calls))
+
+ def _complete_watch(self, w: _Watch) -> None:
+ self.watches.remove(w)
+ w.rec.finish()
+ ran = max(0, min(len(self.episode), w.end) - w.start)
+ out = {**self.meta(), "obs_id": w.obs_id, "seconds": round(ran * self.sim.control_dt, 4),
+ "control_steps_watch": ran, "ok": True}
+ self._save_call(out, None)
+ w.job.finish("rec", out, w.rec)
+
+ def _release_watches(self) -> None:
+ for w in list(self.watches):
+ self._complete_watch(w)
+
+ def _rt_reset(self, meta: dict, parts: dict, job: _Job) -> None:
+ self._release_watches()
+ out, prts = self._reset(meta, parts) # 2.1's reset: checks, abandons the episode, a new one (paused)
+ self._stop_clock("reset")
+ job.finish("rcb1", {**out, **self._realtime_counters()}, prts)
+
+ # ------------------------------------------------------------------ the loop (simulator thread) and HTTP
+ def poll(self) -> None:
+ """After SIGUSR1: end the episode, answer the pending watches, finalize (Service.poll, plus the watches)."""
+ if self.stopping and not self.finalized:
+ if not self.done:
+ self._end("timeout")
+ self._release_watches()
+ self._finalize()
+
+ def loop(self, until: threading.Event | None = None) -> None:
+ """The simulator thread: control steps when due, requests in between, the wrap-up after SIGUSR1."""
+ while until is None or not until.is_set():
+ self.poll()
+ wait = self.due_in(time.monotonic())
+ if wait is not None and wait <= 0:
+ self.tick()
+ continue
+ try:
+ job = self.q.get(timeout=0.25 if wait is None else min(wait, 0.25))
+ except queue.Empty:
+ continue
+ self.dispatch(job)
+
+ def submit_job(self, job: _Job) -> tuple[int, str, bytes]:
+ """From an HTTP thread: queue the request, wait for the simulator thread, encode the answer here."""
+ self.q.put(job)
+ job.done.wait()
+ kind, *rest = job.reply
+ if kind == "raw":
+ return tuple(rest)
+ meta, payload = rest # a Recorder's parts are encoded here, off the simulator's thread
+ return self._reply_rcb1(meta, payload.parts() if kind == "rec" else payload)
+
+ def http_server(self, address: tuple[str, int]) -> ThreadingHTTPServer:
+ svc = self
+
+ class Handler(BaseHTTPRequestHandler):
+ timeout = 120
+
+ def log_message(self, *a):
+ pass
+
+ def _send(self, code: int, ctype: str, body: bytes) -> None:
+ self.send_response(code)
+ self.send_header("Content-Type", ctype)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_GET(self):
+ self._send(*svc.submit_job(_Job("GET", self.path, b"")))
+
+ def do_POST(self):
+ try:
+ n = int(self.headers.get("Content-Length") or 0)
+ except ValueError:
+ return self._send(*svc._reply_json(400, {"error": "bad Content-Length"}))
+ if n > MAX_BODY: # refused unread: drop the connection with it
+ self.close_connection = True
+ return self._send(*svc.submit_job(_Job("POST", self.path, b"", content_length=n)))
+ self._send(*svc.submit_job(_Job("POST", self.path, self.rfile.read(n))))
+
+ class Server(ThreadingHTTPServer):
+ daemon_threads = True
+
+ return Server(address, Handler)
+
+ def serve(self, port: int = 8000) -> None:
+ import signal
+ signal.signal(signal.SIGUSR1, self.on_sigusr1)
+ srv = self.bind(port)
+ threading.Thread(target=srv.serve_forever, name="http", daemon=True).start()
+ print(f"{rcb_service.PROTOCOL} sim service (realtime, slowdown {self.slowdown:g}) ready on :{port}", flush=True)
+ self.loop()
+
+
+def main(build, port: int = 8000) -> None:
+ """rcb_service.main -- the start count, back-off, startup watchdog, resume -- with this service in place of
+ Service (RCB_SLOWDOWN: 1 = real time), and eai-standard/2.3 in everything it logs and writes."""
+ rcb_service.Service = RealtimeService
+ rcb_service.PROTOCOL = PROTOCOL
+ rcb_service.main(build, port)
+
+
+if __name__ == "__main__":
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ import server # noqa: E402 -- the HumanoidBench adapter; picks the GL backend and restores the reward on import
+
+ main(server.build)
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/rcb_service.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/rcb_service.py
new file mode 100644
index 0000000000..14c53a477b
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/rcb_service.py
@@ -0,0 +1,759 @@
+"""eai-standard/2.1 sim service: the simulator-agnostic half of a standard-mode sidecar (docs/PROTOCOL.md §4,
+docs/LIMITED_MODE_PROTOCOL.md).
+
+The robot as a service: the agent reaches a simulator it cannot open over HTTP. GET /spec, GET /status, POST /observe
+and POST /submit; POST /reset exists only when the run grants resets (budget.reset > 0); everything else is 404.
+Responses that carry data are RCB1 frames (rcb1.py), never base64. Everything simulator-specific comes in through an
+adapter (the `Sim` contract below), so this file imports no simulator: a sidecar is its benchmark's adapter plus this.
+
+One thread does all of it -- the HTTP requests, the SIGUSR1 wrap-up, the finalize -- because a simulator's GL context
+belongs to the thread that made it (MuJoCo renders black frames from any other).
+
+The episode starts when the service is ready. It ends on success, by the task's own rule ("failed": the robot fell,
+the episode's control steps ran out), on a simulator error ("error"), or at SIGUSR1 ("timeout": the collect hook, once
+the agent's container is gone). With a reset budget, POST /reset abandons the running episode and starts another from
+the frozen instance; only the last episode is graded, and a success ends the trial.
+
+A request is checked in full before anything runs: whatever is wrong with it is a 400 and nothing ran. Once it runs,
+any failure is the simulator's: a 500, and the episode ends ("error").
+
+Evidence under DATA, never visible to the agent:
+ episode.jsonl one line per event; every state the service may resume from is a checkpoint (it carries
+ state_sha and journal_rows)
+ trajectory_live.f64 the journal: every executed control step in the simulator's own action space, float64
+ calls/NNNNNN/ each call's response meta and the actions as sent
+ startups.jsonl one line per process start
+ final.json kept current (written atomically); "finalized": true once the verdict is in
+ trajectory.npz, replay.mp4, replay.last.png the graded episode and its fresh replay
+
+Crash recovery: compose restarts a crashed service (restart: on-failure). It replays the journal up to the last
+checkpoint, checks the state hash, and continues the SAME episode -- never a reset. A call in flight is lost as a
+whole (its caller got an error, not a result, so nothing was learned). More than RCB_MAX_RESUMES restarts since the
+episode began (every process start counts, also one that died building the scene or replaying the journal) end the
+trial: sim_crashed_on_call if every crash happened while serving a call (the agent's failure), else sim_crashed
+(infrastructure, infra_error = 1). A verdict already on disk is never overwritten; a crash while rendering the video
+loses only the video.
+"""
+from __future__ import annotations
+
+import contextlib
+import errno
+import faulthandler
+import json
+import os
+import signal
+import tempfile
+import time
+import traceback
+from http.server import BaseHTTPRequestHandler, HTTPServer
+from typing import Callable
+from urllib.parse import urlparse
+
+import numpy as np
+
+import rcb1
+
+PROTOCOL = "eai-standard/2.1"
+MAX_BODY = 64 * 1024 * 1024 # request bodies above this are refused (413)
+MAX_RESPONSE = 256 * 1024 * 1024 # responses above this drop frames/ and depth/ (meta.degraded says so)
+MAX_VIDEO_FPS = 30
+MAX_FRAMES_PER_CALL = 3000 # images in one response (cameras x frames, depth counted again): bounds memory
+VIDEOS = ("mp4", "frames", "both", "none")
+ON_SERVICE_ERROR = ("if a call fails with a connection error or a 5xx, the service may have crashed and resumed the "
+ "same episode (never a reset): the state is the one after the last call that completed on the "
+ "service, which you may not have received; check GET /status before continuing")
+
+
+class Sim:
+ """The adapter contract, duck-typed (this class only documents it). One object = one frozen scene.
+
+ Rows come in three forms: what the agent sends (an action of one of spec()["action_types"]), the same after
+ clip(), and a "sim row" (to_sim()), the action in the simulator's own space, which step() executes and the
+ journal and the graded trajectory record (raw_dim floats)."""
+ control_dt: float # seconds per control step; a chunk's dt is a whole multiple of it
+ max_control_steps: int # the task's episode length: the episode ends there
+ cameras: tuple[str, ...] # every camera the agent may ask for
+ depth_cameras: tuple[str, ...] # the ones that also give depth
+ proprio_layout: list[str] # the proprio row's columns
+ raw_dim: int # a sim row's width
+
+ def spec(self) -> dict: ... # simulator, robot, task_text, episode, action_types, cameras, robot facts
+ def interpolable(self, type: str) -> bool: ... # may a row of this type span several control steps?
+ def images(self, cameras: list[str], depth: bool) -> tuple[dict, dict]: ... # ({cam: uint8 HxWx3}, {cam: float32 HxW m})
+ def proprio(self) -> np.ndarray: ... # float32, one value per proprio_layout column
+ def clip(self, type: str, rows: np.ndarray) -> tuple[np.ndarray, list]: ... # into the limits; [{row, index, reason}]
+ def to_sim(self, type: str, row: np.ndarray) -> np.ndarray: ... # an agent row -> a sim row
+ def command(self, type: str) -> np.ndarray: ... # the last row executed, exactly as clip() returned it: a chunk
+ # interpolates from it, so a chunk equals its rows sent one by one
+ def hold(self) -> tuple[str, np.ndarray]: ... # the row that holds the last command (/observe with seconds > 0)
+ def step(self, row: np.ndarray) -> tuple[bool, bool, dict]: ... # one control step -> (done, success, info)
+ def reset(self) -> None: ... # back to the frozen instance
+ def state_sha(self) -> str: ...
+ def verify(self, rows: np.ndarray) -> dict: ... # replay in a fresh simulator -> {"success", "state_sha"}
+ def save_trajectory(self, rows: np.ndarray, path: str, meta: dict) -> None: ...
+ def render_video(self, rows: np.ndarray, path: str) -> None: ... # path and path.last.png
+
+
+class GiveUp(Exception):
+ """The service will not run this trial's episode again; final.json says why."""
+
+
+class Refused(Exception):
+ """A request the service turns down with `code` and the JSON `body`; nothing was executed."""
+
+ def __init__(self, code: int, body: dict):
+ super().__init__(body.get("error"))
+ self.code, self.body = code, body
+
+
+def bad_request():
+ """Checking a request, before anything runs: whatever goes wrong here is the request's fault (400)."""
+ try:
+ yield
+ except Refused:
+ raise
+ except Exception as exc: # noqa: BLE001 -- a wrong type, value or shape of any field
+ raise Refused(400, {"error": str(exc)[:300] or type(exc).__name__}) from None
+
+
+def count_start(data: str) -> int:
+ """Record one process start in startups.jsonl; returns how many there have been."""
+ path = os.path.join(data, "startups.jsonl")
+ with open(path, "a") as f:
+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid()}) + "\n")
+ with open(path) as f:
+ return sum(1 for _ in f)
+
+
+def write_json_atomic(path: str, obj: dict) -> None:
+ """Write then rename: the collect hook polling the file never reads half of it."""
+ fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), suffix=".tmp")
+ with os.fdopen(fd, "w") as f:
+ json.dump(obj, f)
+ os.replace(tmp, path)
+
+
+def encode_mp4(frames: np.ndarray, fps: float) -> bytes:
+ import imageio.v2 as imageio
+ fd, path = tempfile.mkstemp(suffix=".mp4")
+ os.close(fd)
+ try:
+ with imageio.get_writer(path, format="FFMPEG", mode="I", fps=fps, codec="libx264", macro_block_size=1,
+ output_params=["-movflags", "+faststart", "-pix_fmt", "yuv420p"]) as w:
+ for f in frames:
+ w.append_data(np.ascontiguousarray(f))
+ with open(path, "rb") as f:
+ return f.read()
+ finally:
+ os.unlink(path)
+
+
+class Recorder:
+ """What one call returns: a proprio row at its start, every `every` control steps (the requested video_fps, rounded to
+ whole control steps) and at its end; with them the cameras' frames when a video or the frames are asked for, else
+ only the last frame (rendering is most of a call's cost)."""
+
+ def __init__(self, sim, cameras: list[str], fps: int, depth: bool, video: str):
+ self.sim, self.cams, self.depth, self.video = sim, cameras, depth, video
+ self.every = max(1, round(1.0 / (sim.control_dt * fps)))
+ self.fps = 1.0 / (self.every * sim.control_dt)
+ self.images = video != "none"
+ self.frames = {c: [] for c in cameras}
+ self.dep = {c: [] for c in cameras}
+ self.prop: list[np.ndarray] = []
+ self.k, self.grabbed_at = 0, None
+
+ def images_per_call(self, steps: int) -> int:
+ per_frame = len(self.cams) + (len(set(self.cams) & set(self.sim.depth_cameras)) if self.depth else 0)
+ return (steps // self.every + 2 if self.images else 1) * per_frame
+
+ def start(self) -> None:
+ self._grab(self.images)
+
+ def step(self) -> None:
+ self.k += 1
+ if self.k % self.every == 0:
+ self._grab(self.images)
+
+ def finish(self) -> None:
+ if self.grabbed_at != self.k:
+ self._grab(self.images)
+ if not self.images:
+ self._grab(True, proprio=False) # the one frame a call without video returns: the last
+
+ def _grab(self, images: bool, proprio: bool = True) -> None:
+ if images:
+ rgb, dep = self.sim.images(self.cams, self.depth)
+ for c in self.cams:
+ self.frames[c].append(rgb[c])
+ if c in dep:
+ self.dep[c].append(dep[c])
+ if proprio:
+ self.prop.append(np.asarray(self.sim.proprio(), np.float32))
+ self.grabbed_at = self.k
+
+ def parts(self) -> list:
+ out = []
+ for c in self.cams:
+ fr = np.stack(self.frames[c])
+ if self.video in ("mp4", "both"):
+ out.append((f"video/{c}", "mp4", encode_mp4(fr, self.fps), {"fps": round(self.fps, 3), "n": int(len(fr))}))
+ if self.video in ("frames", "both"):
+ out.append(rcb1.array_part(f"frames/{c}", fr))
+ out.append(rcb1.array_part(f"last/{c}", fr[-1]))
+ if self.dep[c]:
+ out.append(rcb1.array_part(f"depth/{c}", np.stack(self.dep[c]).astype(np.float16)))
+ out.append(rcb1.array_part("proprio", np.stack(self.prop)))
+ return out
+
+
+class Service:
+ """Episode bookkeeping, evidence and the HTTP endpoints around one `Sim`."""
+
+ def __init__(self, sim, *, data: str = "/data", reset_budget: int = 0, wall_clock_s: float = 3600.0,
+ max_chunk_s: float = 10.0, max_watch_s: float = 30.0, max_frames_per_call: int = MAX_FRAMES_PER_CALL,
+ max_resumes: int = 2):
+ self.sim, self.data = sim, data
+ self.reset_budget, self.wall_clock_s = int(reset_budget), float(wall_clock_s)
+ self.max_chunk_s, self.max_watch_s = float(max_chunk_s), float(max_watch_s)
+ self.max_frames, self.max_resumes = int(max_frames_per_call), int(max_resumes)
+ os.makedirs(os.path.join(data, "calls"), exist_ok=True)
+ self.journal_path = os.path.join(data, "trajectory_live.f64")
+ self.spec = self._spec()
+ self.types = {k: v for k, v in self.spec["action_types"].items() if isinstance(v, dict)}
+ self.calls = self.rows = self.resets = 0
+ self.journal_rows = 0 # control steps executed over the whole trial (the journal's length)
+ self.ep_start = 0 # where the current episode begins in the journal
+ self.episode: list[np.ndarray] = [] # the current episode's sim rows: what finalize grades
+ self.done, self.reason, self.success = False, None, False
+ self.stopping = False # SIGUSR1 seen: the agent is gone
+ self.finalized, self.verdict = False, {}
+ self.t0 = self.t_end = None # the clock starts at the agent's first request
+ self.starts = 1
+ self._unwritten: list[np.ndarray] = [] # sim rows executed since the last checkpoint
+
+ # ------------------------------------------------------------------ spec and status
+ def _spec(self) -> dict:
+ own = self.sim.spec()
+ core = {"protocol": PROTOCOL, "control_dt": self.sim.control_dt, "max_control_steps": self.sim.max_control_steps,
+ "max_chunk_s": self.max_chunk_s, "max_watch_s": self.max_watch_s, "max_video_fps": MAX_VIDEO_FPS,
+ "max_frames_per_call": self.max_frames, "proprio_layout": list(self.sim.proprio_layout),
+ "budget": {"reset": self.reset_budget, "wall_clock_s": self.wall_clock_s},
+ "clock": "time_s and elapsed_s count from your first request to the service; time_left_s is "
+ "budget.wall_clock_s minus time_s",
+ "on_service_error": ON_SERVICE_ERROR}
+ if clash := sorted(set(core) & set(own)):
+ raise ValueError(f"the adapter's spec() must not set {clash}")
+ cams = {c: {"rgb": True, "depth": c in self.sim.depth_cameras, **own["cameras"].get(c, {})}
+ for c in self.sim.cameras}
+ spec = {**core, **own, "cameras": cams}
+ if self.reset_budget:
+ spec["reset"] = ("POST /reset abandons the running episode and starts a new one from the same starting "
+ "state, budget.reset times in all; only the last episode is graded, and a success ends "
+ "the trial")
+ return spec
+
+ def clock(self) -> float:
+ return 0.0 if self.t0 is None else time.time() - self.t0
+
+ def _counters(self) -> dict:
+ out = {"calls": self.calls, "rows": self.rows, "control_steps": len(self.episode), "done": self.done,
+ "reason": self.reason}
+ if self.reset_budget:
+ out.update(episode=self.resets + 1, control_steps_total=self.journal_rows,
+ resets_left=0 if self.success or self.stopping else self.reset_budget - self.resets)
+ return out
+
+ def status(self) -> dict:
+ return {**self._counters(), "elapsed_s": round(self.clock(), 1)}
+
+ def meta(self) -> dict:
+ t = self.clock()
+ return {**self._counters(), "sim_time_s": round(len(self.episode) * self.sim.control_dt, 4),
+ "time_s": round(t, 2), "time_left_s": max(0.0, round(self.wall_clock_s - t, 1)),
+ "proprio": {"layout": list(self.sim.proprio_layout),
+ "now": np.asarray(self.sim.proprio(), np.float32).tolist()}}
+
+ # ------------------------------------------------------------------ evidence
+ def log(self, ev: str, **kw) -> None:
+ with open(os.path.join(self.data, "episode.jsonl"), "a") as f:
+ f.write(json.dumps({"ts": time.time(), "ev": ev, **kw}) + "\n")
+
+ def _events(self) -> list[dict]:
+ try:
+ with open(os.path.join(self.data, "episode.jsonl")) as f:
+ return [json.loads(line) for line in f if line.strip()]
+ except OSError:
+ return []
+
+ def _checkpoint(self, ev: str, **kw) -> None:
+ """Log a state this service may resume from, after appending everything executed since the last one to the
+ journal. Rows of a call that never reaches its checkpoint are lost with it, as the call is."""
+ if self._unwritten:
+ with open(self.journal_path, "ab") as f:
+ f.write(np.asarray(self._unwritten, dtype=np.float64).tobytes())
+ self._unwritten = []
+ self.log(ev, **kw, calls=self.calls, rows=self.rows, resets=self.resets, ep_start=self.ep_start,
+ journal_rows=self.journal_rows, done=self.done, reason=self.reason, success=self.success,
+ state_sha=self.sim.state_sha())
+ self._write_final()
+
+ def _write_final(self) -> None:
+ end = self.t_end or time.time()
+ d = {"protocol": PROTOCOL, "success": False, "live_success": self.success, "done": self.done,
+ "reason": self.reason, "calls": self.calls, "rows": self.rows, "control_steps": len(self.episode),
+ "control_steps_total": self.journal_rows, "episodes": self.resets + 1, "resets": self.resets,
+ "reset_budget": self.reset_budget, "elapsed_s": round(end - self.t0, 1) if self.t0 else 0.0,
+ "sim_startups": self.starts, "finalized": self.finalized, **self.verdict}
+ if "deterministic" in self.verdict:
+ d["success"] = bool(self.success and self.verdict["replay_success"] and self.verdict["deterministic"])
+ write_json_atomic(os.path.join(self.data, "final.json"), d)
+
+ def _save_call(self, meta: dict, actions: np.ndarray | None) -> None:
+ d = os.path.join(self.data, "calls", f"{self.calls:06d}")
+ os.makedirs(d, exist_ok=True)
+ with open(os.path.join(d, "meta.json"), "w") as f:
+ json.dump(meta, f)
+ if actions is not None:
+ np.save(os.path.join(d, "actions.npy"), actions)
+
+ # ------------------------------------------------------------------ start, resume, give up
+ def start(self) -> None:
+ """A fresh episode, or -- after a crash -- the same one again. Raises GiveUp when it must not run again."""
+ try:
+ with open(os.path.join(self.data, "startups.jsonl")) as f:
+ self.starts = max(1, sum(1 for _ in f))
+ except OSError:
+ self.starts = 1
+ ev = self._events()
+ if not any(e["ev"] == "start" for e in ev):
+ open(self.journal_path, "wb").close()
+ self._checkpoint("start", protocol=PROTOCOL, spec=self.spec, startup=self.starts)
+ else:
+ self._resume(ev)
+ with open(os.path.join(self.data, "server.pid"), "w") as f:
+ f.write(str(os.getpid()))
+
+ def _resume(self, ev: list[dict]) -> None:
+ path = os.path.join(self.data, "final.json")
+ try:
+ with open(path) as f:
+ fin = json.load(f)
+ except (OSError, ValueError):
+ fin = {}
+ if fin.get("finalized") or "deterministic" in fin:
+ # Graded already. A verdict that is not finalized: the process died rendering the video, all it lost.
+ if not fin.get("finalized"):
+ write_json_atomic(path, {**fin, "finalized": True, "video": False})
+ self._give_up("restarted after finalize", infra=False)
+ restarts = self.starts - int(next(e for e in ev if e["ev"] == "start")["startup"])
+ last = max(i for i, e in enumerate(ev) if e["ev"] in ("start", "resuming"))
+ in_call = False # did the process that died do so while serving a call?
+ for e in ev[last:]:
+ in_call = {"call_begin": True, "call_end": False}.get(e["ev"], in_call)
+ in_calls = sum(bool(e["crashed_in_call"]) for e in ev if e["ev"] == "resuming") + int(in_call)
+ if restarts > self.max_resumes:
+ agent = in_calls == restarts # every crash happened inside a call: the agent's commands did it
+ self._give_up("sim_crashed_on_call" if agent else "sim_crashed", infra=not agent)
+ self.log("resuming", crashed_in_call=in_call, restart=restarts)
+ cp = [e for e in ev if "state_sha" in e and "journal_rows" in e][-1]
+ n, dim = int(cp["journal_rows"]), int(self.sim.raw_dim)
+ rows = np.fromfile(self.journal_path, dtype=np.float64) if os.path.exists(self.journal_path) else np.zeros(0)
+ if rows.size < n * dim:
+ self._give_up("resume_failed: journal shorter than the log", infra=True)
+ rows = rows[: n * dim].reshape(n, dim)
+ for row in rows[cp["ep_start"]:]:
+ self.sim.step(row)
+ if self.sim.state_sha() != cp["state_sha"]:
+ self._give_up("resume_failed: replayed state differs from the logged one", infra=True)
+ rows.tofile(self.journal_path) # drop the steps of the call that was in flight
+ self.calls, self.rows, self.resets = int(cp["calls"]), int(cp["rows"]), int(cp["resets"])
+ self.ep_start, self.journal_rows = int(cp["ep_start"]), n
+ self.episode = [r.copy() for r in rows[self.ep_start:]]
+ self.done, self.reason, self.success = bool(cp["done"]), cp["reason"], bool(cp["success"])
+ self.t0 = next((e["t0"] for e in ev if e["ev"] == "first_request"), None)
+ if self.done:
+ self.t_end = next((e["ts"] for e in reversed(ev) if e["ev"] == "end"), cp["ts"])
+ self._checkpoint("resumed", downtime_s=round(time.time() - float(ev[-1]["ts"]), 1))
+
+ def _give_up(self, reason: str, infra: bool) -> None:
+ """End the trial without running its episode again: mark it failed (a finalized final.json is kept as it is),
+ leave the PID file for the collect hook, and stop."""
+ self.log("restart_refused", reason=reason)
+ path = os.path.join(self.data, "final.json")
+ try:
+ with open(path) as f:
+ fin = json.load(f)
+ except (OSError, ValueError):
+ fin = {}
+ if not fin.get("finalized"):
+ fin.update({"protocol": PROTOCOL, "success": False, "done": True, "reason": reason, "finalized": True,
+ **({"infra_error": 1} if infra else {})})
+ write_json_atomic(path, fin)
+ with open(os.path.join(self.data, "server.pid"), "w") as f:
+ f.write(str(os.getpid()))
+ raise GiveUp(reason)
+
+ # ------------------------------------------------------------------ requests
+ def first_request(self) -> None:
+ if self.t0 is None:
+ self.t0 = time.time()
+ self.log("first_request", t0=self.t0)
+
+ def handle(self, method: str, path: str, body: bytes = b"", content_length: int | None = None) -> tuple[int, str, bytes]:
+ """One request -> (status, content type, body): the whole HTTP surface, without the HTTP."""
+ self.first_request()
+ path = urlparse(path).path
+ if method == "GET" and path in ("/spec", "/status"):
+ return self._reply_json(200, self.spec if path == "/spec" else self.status())
+ routes = {"/submit": self._submit, "/observe": self._observe}
+ if self.reset_budget:
+ routes["/reset"] = self._reset
+ if method != "POST" or path not in routes:
+ return self._reply_json(404, {"error": "no such endpoint"})
+ if (len(body) if content_length is None else content_length) > MAX_BODY:
+ return self._reply_json(413, {"error": f"request body over {MAX_BODY} bytes"})
+ try:
+ meta, parts = self._decode(body)
+ except Exception as exc: # noqa: BLE001 -- any malformed body is the caller's error
+ return self._reply_json(400, {"error": f"malformed body: {exc}"[:300]})
+ self.log("call_begin", path=path, call=self.calls + 1)
+ try:
+ out, blobs = routes[path](meta, parts)
+ except Refused as exc: # 400 (bad_request), 409: nothing ran
+ return self._reply_json(exc.code, exc.body)
+ except Exception as exc: # noqa: BLE001 -- it ran and failed: the episode ends, as on hardware
+ traceback.print_exc()
+ self.log("error", path=path, error=repr(exc)[:500])
+ self._end("error")
+ return self._reply_json(500, {"error": "simulator error", "detail": repr(exc)[:200]})
+ finally:
+ self.log("call_end", path=path)
+ return self._reply_rcb1(out, blobs)
+
+ @staticmethod
+ def _decode(body: bytes) -> tuple[dict, dict]:
+ if body[:4] == rcb1.MAGIC:
+ meta, parts = rcb1.decode(body)
+ else:
+ meta, parts = json.loads(body or b"{}"), {}
+ if not isinstance(meta, dict):
+ raise ValueError("the body must be a JSON object or an RCB1 frame")
+ return meta, parts
+
+ @staticmethod
+ def _reply_json(code: int, obj: dict) -> tuple[int, str, bytes]:
+ return code, "application/json", json.dumps(obj).encode()
+
+ @staticmethod
+ def _reply_rcb1(meta: dict, parts: list) -> tuple[int, str, bytes]:
+ body = rcb1.encode(meta, parts)
+ if len(body) > MAX_RESPONSE:
+ parts = [p for p in parts if not p[0].startswith(("frames/", "depth/"))]
+ meta = {**meta, "degraded": f"response over {MAX_RESPONSE} bytes: frames/ and depth/ dropped"}
+ body = rcb1.encode(meta, parts)
+ return 200, "application/x-rcb1", body
+
+ def _view(self, meta: dict, default_video: str) -> tuple[list[str], int, str, bool]:
+ cams = meta.get("cameras") or list(self.sim.cameras)
+ if isinstance(cams, str):
+ cams = [c for c in cams.split(",") if c]
+ if not isinstance(cams, list) or (unknown := sorted(set(map(str, cams)) - set(self.sim.cameras))):
+ raise ValueError(f"unknown camera(s) {unknown if isinstance(cams, list) else cams}; "
+ f"the cameras are {list(self.sim.cameras)}")
+ try:
+ fps = int(meta.get("video_fps", 10))
+ except (TypeError, ValueError, OverflowError):
+ raise ValueError("video_fps must be an integer") from None
+ if not 1 <= fps <= MAX_VIDEO_FPS:
+ raise ValueError(f"video_fps must be in [1, {MAX_VIDEO_FPS}]")
+ video = meta.get("video", default_video)
+ if video not in VIDEOS:
+ raise ValueError(f"video must be one of {list(VIDEOS)}")
+ depth = bool(meta.get("include_depth", False))
+ if depth and not set(cams) & set(self.sim.depth_cameras):
+ raise ValueError(f"include_depth: none of {cams} has depth; spec()['cameras'][name]['depth'] says which do")
+ return cams, fps, video, depth
+
+ def _frame_budget(self, rec: Recorder, steps: int) -> None:
+ n = rec.images_per_call(steps)
+ if n > self.max_frames:
+ raise ValueError(f"this call would return {n} images (cameras x frames, depth counted again); the limit is "
+ f"{self.max_frames}: ask for fewer cameras, a lower video_fps or a shorter chunk")
+
+ def _conflict(self) -> Refused:
+ if self.stopping:
+ return Refused(409, {"error": "trial finished: your time is up", "reason": self.reason})
+ body = {"error": "episode finished", "reason": self.reason}
+ if self.reset_budget:
+ body["resets_left"] = 0 if self.success else self.reset_budget - self.resets
+ return Refused(409, body)
+
+ def _step(self, typ: str, row: np.ndarray) -> dict:
+ """One control step: execute, journal, and end the episode if it is over."""
+ sim_row = np.asarray(self.sim.to_sim(typ, row), dtype=np.float64)
+ done, success, info = self.sim.step(sim_row)
+ self._unwritten.append(sim_row)
+ self.journal_rows += 1
+ self.episode.append(sim_row)
+ if success:
+ self._end("success")
+ elif done or len(self.episode) >= self.sim.max_control_steps:
+ self._end("failed")
+ return info
+
+ def _end(self, reason: str) -> None:
+ if self.done:
+ return
+ self.done, self.reason, self.success = True, reason, reason == "success"
+ self.t_end = time.time()
+ try:
+ self._checkpoint("end")
+ except Exception as exc: # noqa: BLE001 -- a broken simulator may not even hash: the end is still logged
+ self.log("end", reason=reason, checkpoint_error=repr(exc)[:300])
+ self._write_final()
+
+ def _submit(self, meta: dict, parts: dict) -> tuple[dict, list]:
+ if self.done or self.stopping:
+ raise self._conflict()
+ with bad_request():
+ typ = meta.get("type")
+ if not isinstance(typ, str) or typ not in self.types:
+ raise ValueError(f"type must be one of {sorted(self.types)}")
+ try:
+ A = np.asarray(parts["actions"]["data"] if "actions" in parts else meta.get("actions"), dtype=np.float64)
+ except (TypeError, ValueError, KeyError):
+ raise ValueError("send the actions as an RCB1 array part `actions` or a JSON list of rows") from None
+ dim = int(self.types[typ]["dim"])
+ if A.ndim != 2 or A.shape[0] < 1 or A.shape[1] != dim:
+ raise ValueError(f"{typ} actions must be (T, {dim}) with T >= 1, got {list(A.shape)}")
+ if not np.all(np.isfinite(A)):
+ raise ValueError("actions contain NaN or inf")
+ cdt = self.sim.control_dt
+ try:
+ dt = cdt if meta.get("dt") is None else float(meta["dt"])
+ except (TypeError, ValueError):
+ raise ValueError("dt must be a number of seconds") from None
+ k = round(dt / cdt) if np.isfinite(dt / cdt) else 0
+ if k < 1 or abs(k * cdt - dt) > 1e-9:
+ raise ValueError(f"dt must be a positive whole multiple of control_dt = {cdt} s (never rounded)")
+ if k > 1 and not self.sim.interpolable(typ):
+ raise ValueError(f"{typ}: one row is one control step, so dt must be control_dt = {cdt} s")
+ if len(A) * k * cdt > self.max_chunk_s + 1e-9:
+ raise ValueError(f"the chunk covers {len(A) * k * cdt:g} s: more than max_chunk_s = {self.max_chunk_s:g}")
+ interp = meta.get("interpolate", "linear")
+ if interp not in ("linear", "hold"):
+ raise ValueError("interpolate must be linear or hold")
+ cams, fps, video, depth = self._view(meta, "mp4")
+ rec = Recorder(self.sim, cams, fps, depth, video)
+ self._frame_budget(rec, len(A) * k)
+ rows, clipped = self.sim.clip(typ, A)
+ before, info, executed, stop = len(self.episode), {}, 0, False
+ prev = np.asarray(self.sim.command(typ), dtype=np.float64)
+ rec.start()
+ for i, row in enumerate(rows):
+ for j in range(1, k + 1):
+ info = self._step(typ, row if interp == "hold" else prev + (row - prev) * (j / k))
+ rec.step()
+ if self.done or self.stopping or info.get("blocked"):
+ stop = True
+ break
+ executed, prev = i + 1, row
+ if stop:
+ break
+ rec.finish()
+ self.calls += 1
+ self.rows += executed
+ out = {**self.meta(), "chunk_id": self.calls, "type": typ, "executed_rows": executed,
+ "control_steps_chunk": len(self.episode) - before, "clipped": clipped[:200], "n_clipped": len(clipped),
+ **info, "ok": True}
+ self._checkpoint("submit", type=typ, n_rows=len(A), dt=dt, interpolate=interp, cameras=cams,
+ note=str(meta.get("note") or "")[:500], executed_rows=executed, n_clipped=len(clipped), **info)
+ self._save_call(out, A)
+ return out, rec.parts()
+
+ def _observe(self, meta: dict, parts: dict) -> tuple[dict, list]:
+ with bad_request():
+ try:
+ seconds = float(meta.get("seconds") or 0.0)
+ except (TypeError, ValueError):
+ raise ValueError("seconds must be a number") from None
+ if not 0.0 <= seconds <= self.max_watch_s:
+ raise ValueError(f"seconds must be in [0, {self.max_watch_s:g}]")
+ cams, fps, video, depth = self._view(meta, "frames")
+ n = int(round(seconds / self.sim.control_dt)) if not (self.done or self.stopping) else 0
+ rec = Recorder(self.sim, cams, fps, depth, video if n or video != "mp4" else "frames") # no time: no video
+ self._frame_budget(rec, n)
+ before = len(self.episode)
+ rec.start()
+ if n:
+ typ, row = self.sim.hold()
+ for _ in range(n):
+ self._step(typ, row)
+ rec.step()
+ if self.done or self.stopping:
+ break
+ rec.finish()
+ self.calls += 1
+ ran = len(self.episode) - before
+ out = {**self.meta(), "obs_id": self.calls, "seconds": round(ran * self.sim.control_dt, 4),
+ "control_steps_watch": ran, "ok": True}
+ self._checkpoint("observe", seconds=out["seconds"], cameras=cams)
+ self._save_call(out, None)
+ return out, rec.parts()
+
+ def _reset(self, meta: dict, parts: dict) -> tuple[dict, list]:
+ if self.success or self.stopping:
+ raise Refused(409, {"error": "trial finished: " + ("an episode succeeded" if self.success else "your time is up"),
+ "reason": self.reason})
+ if self.resets >= self.reset_budget:
+ raise Refused(409, {"error": "reset budget exhausted", "budget": self.reset_budget})
+ with bad_request():
+ cams, fps, video, depth = self._view(meta, "frames")
+ if not self.done:
+ self._end("reset") # the running episode is abandoned
+ self.sim.reset()
+ self.resets += 1
+ self.ep_start, self.episode = self.journal_rows, []
+ self.done, self.reason, self.success, self.t_end = False, None, False, None
+ rec = Recorder(self.sim, cams, fps, depth, "frames" if video == "mp4" else video) # no time: no video
+ rec.start()
+ rec.finish()
+ self.calls += 1
+ out = {**self.meta(), "ok": True}
+ self._checkpoint("reset", cameras=cams)
+ self._save_call(out, None)
+ return out, rec.parts()
+
+ # ------------------------------------------------------------------ the end of the trial
+ def on_sigusr1(self, *_) -> None:
+ """The agent is gone (the [[verifier.collect]] hook). Only a flag: the handler may fire in the middle of a
+ request; a chunk stops at its next control step and poll() wraps up between requests."""
+ self.stopping = True
+
+ def poll(self) -> None:
+ """Between requests (the HTTP loop calls it every 0.5 s): after SIGUSR1, end the episode and finalize."""
+ if self.stopping and not self.finalized:
+ if not self.done:
+ self._end("timeout")
+ self._finalize()
+
+ def _finalize(self) -> None:
+ """The graded episode (every control step since the last reset) as a trajectory, its replay in a fresh
+ simulator (success, and bit-exact agreement with the live run), and a video for humans."""
+ try:
+ rows = np.asarray(self.episode, dtype=np.float64).reshape(-1, self.sim.raw_dim)
+ live_sha = self.sim.state_sha()
+ self.sim.save_trajectory(rows, os.path.join(self.data, "trajectory.npz"),
+ {"source": "standard-mode episode", "protocol": PROTOCOL, "reason": self.reason,
+ "episode": self.resets + 1})
+ rep = self.sim.verify(rows)
+ self.verdict = {"n_actions": int(len(rows)), "replay_success": bool(rep["success"]),
+ "deterministic": rep["state_sha"] == live_sha, "state_sha": live_sha, "video": False}
+ self.log("replay", **self.verdict)
+ self._write_final() # the verdict is on disk before any video is rendered
+ try:
+ self.sim.render_video(rows, os.path.join(self.data, "replay.mp4"))
+ self.verdict["video"] = True
+ except Exception: # noqa: BLE001 -- the video is for humans; it never decides the verdict
+ traceback.print_exc()
+ except Exception as exc: # noqa: BLE001
+ traceback.print_exc()
+ self.log("finalize_error", error=repr(exc)[:500])
+ self.verdict = {"finalize_error": repr(exc)[:300]}
+ self.finalized = True
+ self._write_final()
+
+ # ------------------------------------------------------------------ HTTP
+ def http_server(self, address: tuple[str, int]) -> HTTPServer:
+ svc = self
+
+ class Handler(BaseHTTPRequestHandler):
+ timeout = 120 # a client that stalls mid-request is dropped: one thread serves everyone
+
+ def log_message(self, *a):
+ pass
+
+ def _send(self, code: int, ctype: str, body: bytes) -> None:
+ self.send_response(code)
+ self.send_header("Content-Type", ctype)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_GET(self):
+ self._send(*svc.handle("GET", self.path))
+
+ def do_POST(self):
+ try:
+ n = int(self.headers.get("Content-Length") or 0)
+ except ValueError:
+ return self._send(*svc._reply_json(400, {"error": "bad Content-Length"}))
+ if n > MAX_BODY: # refused unread: drop the connection with it
+ self.close_connection = True
+ return self._send(*svc.handle("POST", self.path, b"", content_length=n))
+ self._send(*svc.handle("POST", self.path, self.rfile.read(n)))
+
+ class Server(HTTPServer):
+ def service_actions(self):
+ svc.poll()
+
+ return Server(address, Handler)
+
+ def bind(self, port: int) -> HTTPServer:
+ """The HTTP server on `port`. Something else may hold the port -- in the network namespace it shares with the
+ agent's container, an agent's process can take it while this service (re)starts -- so wait, not die (a death
+ here would count as a crash); the trial can still end meanwhile (SIGUSR1)."""
+ busy = False
+ while True:
+ try:
+ return self.http_server(("0.0.0.0", port))
+ except OSError as exc:
+ if exc.errno != errno.EADDRINUSE:
+ raise
+ if not busy:
+ busy = True
+ self.log("port_busy", port=port)
+ self.poll()
+ time.sleep(1.0)
+
+ def serve(self, port: int = 8000) -> None:
+ signal.signal(signal.SIGUSR1, self.on_sigusr1)
+ srv = self.bind(port)
+ print(f"{PROTOCOL} sim service ready on :{port}", flush=True)
+ srv.serve_forever()
+
+
+def main(build: Callable[[], Sim], port: int = 8000) -> None:
+ """A sidecar's life: count the start, back off after a failed one, build the scene under a startup watchdog, resume
+ or start the episode, serve. Settings: RCB_DATA (/data), RCB_RESET_BUDGET (0), RCB_WALL_CLOCK_S (3600),
+ RCB_STARTUP_TIMEOUT_S (300), RCB_MAX_RESUMES (2)."""
+ env = os.environ.get
+ data = env("RCB_DATA", "/data")
+ os.makedirs(data, exist_ok=True)
+ starts = count_start(data)
+ # Compose restarts a failed start at once; a scene that failed to build (e.g. the GPU full of other trials) would
+ # meet the same conditions every time, so wait before rebuilding -- only before the episode exists.
+ if starts > 1 and not os.path.exists(os.path.join(data, "episode.jsonl")):
+ time.sleep(min(120, 20 * (starts - 1)))
+ pending: list[int] = []
+ signal.signal(signal.SIGUSR1, lambda *_: pending.append(1)) # its default action would kill the process
+ # A scene build that hangs (no crash, so compose never restarts it) must end the process. Neither a Python thread
+ # (a native hang may hold the GIL) nor SIGALRM's default action (PID 1 ignores it) can; faulthandler's C watchdog
+ # dumps every thread's traceback and exits. Before the scene exists no episode exists: the retry is no reset.
+ faulthandler.dump_traceback_later(float(env("RCB_STARTUP_TIMEOUT_S", "300")), exit=True)
+ sim = build()
+ faulthandler.cancel_dump_traceback_later() # a resume replay may take minutes
+ svc = Service(sim, data=data, reset_budget=int(env("RCB_RESET_BUDGET") or 0),
+ wall_clock_s=float(env("RCB_WALL_CLOCK_S") or 3600), max_resumes=int(env("RCB_MAX_RESUMES") or 2))
+ try:
+ svc.start()
+ except GiveUp as exc:
+ print(f"restart refused: {exc}", flush=True)
+ signal.signal(signal.SIGUSR1, lambda *_: None)
+ while True:
+ time.sleep(3600)
+ if pending:
+ svc.on_sigusr1()
+ svc.serve(port)
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/__init__.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/__init__.py
new file mode 100644
index 0000000000..9a55e841d4
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/__init__.py
@@ -0,0 +1,40 @@
+"""Renderer plugins (docs/framework_zh.md §3.1): a renderer draws a sport's scene, from its camera definitions, for
+one world state. Sports never import a renderer; the core calls the task's observation renderer (task parameter
+`renderer`, default DEFAULT) and the viewing tools any renderer for re-renders.
+
+ from renderers import load, Scene, CameraDef
+ R = load("mujoco")(Scene.from_file("scene.xml"))
+ images = R.render({"qpos": qpos}, [CameraDef("behind", pos, lookat)])
+"""
+from __future__ import annotations
+
+import importlib
+
+from .base import CameraDef, Renderer, RendererUnavailable, Scene # noqa: F401
+
+DEFAULT = "mujoco"
+REGISTRY = { # name -> (module, realtime, needs_gpu, requires)
+ "mujoco": ("renderers.mujoco", True, False, "mujoco; MUJOCO_GL=osmesa (CPU) or egl (GPU)"),
+ "mujoco-showcase": ("renderers.mujoco_showcase", True, False, "as mujoco"),
+ "cycles": ("renderers.cycles", False, True, "Docker, the rcb-showcase-blender image, an NVIDIA GPU (or device=CPU)"),
+ "isaac": ("renderers.isaac", False, True, "Docker, the Isaac Sim 4.5 image, an NVIDIA RTX GPU"),
+}
+
+
+def load(name: str = DEFAULT):
+ """The Renderer subclass registered under `name`."""
+ if name not in REGISTRY:
+ raise KeyError(f"unknown renderer {name!r}; have {sorted(REGISTRY)}")
+ return importlib.import_module(REGISTRY[name][0]).RENDERER
+
+
+def available() -> dict:
+ return {n: {"realtime": rt, "needs_gpu": gpu, "requires": req} for n, (_, rt, gpu, req) in REGISTRY.items()}
+
+
+def players_model(sport_dir, match: Scene):
+ """For a sport that draws its own images (the renderers' interface for sports): the compiled MjModel of the
+ players' presentation scene its presentation.toml declares (`players`, renderer rule 6; the same kinematics as
+ `match` checked), or None when it declares none (draw the match model). See renderers/presentation."""
+ from .presentation import players_model as _players_model
+ return _players_model(sport_dir, match)
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/base.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/base.py
new file mode 100644
index 0000000000..7cf75e40ba
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/base.py
@@ -0,0 +1,156 @@
+"""The renderer plugin interface (docs/framework_zh.md §3.1, renderer rules §9): a renderer turns a sport's scene,
+camera definitions and one world state into images. It never changes physics or the match state: it draws on its own
+copy of the model.
+
+ scene = Scene(engine="mujoco", xml=MJCF text, assets={relative path: bytes}, look=None or a presentation look)
+ a presentation scene (renderers/presentation.py, spectators only) also carries `match`, the match scene
+ it dresses: same kinematics, extra visual-only geoms (scene_check.same_kinematics)
+ cameras = [CameraDef(name, pos, lookat, up, fovy_deg, width, height), ...] (what Match.cameras(seat) returns)
+ state = {"qpos": [...], optional "mocap_pos": [...], "mocap_quat": [...]}
+ images = Renderer(scene).render(state, cameras) -> one H x W x 3 uint8 array per camera
+
+The camera model is a pinhole that every renderer must reproduce (CameraDef.project): pixel (u, v) from the image's
+top-left corner, u to the right, v down, vertical field of view fovy_deg. Only numpy is needed here; engines import
+their own libraries inside their backend packages. Never put the renderers/ directory itself on sys.path (its
+`mujoco` backend package would shadow the mujoco library); import it as the package `renderers`.
+"""
+from __future__ import annotations
+
+import math
+from abc import ABC, abstractmethod
+from dataclasses import dataclass, field
+from pathlib import Path
+
+import numpy as np
+
+
+class RendererUnavailable(RuntimeError):
+ """The renderer cannot run here; `requirements` says what it needs (GPU, image, library ...)."""
+
+ def __init__(self, name: str, why: str, requirements: str = ""):
+ super().__init__(f"renderer {name!r} unavailable: {why}" + (f" (requires: {requirements})" if requirements else ""))
+ self.name, self.why, self.requirements = name, why, requirements
+
+
+def _unit(v):
+ v = np.asarray(v, dtype=float)
+ n = np.linalg.norm(v)
+ if not np.isfinite(n) or n < 1e-12:
+ raise ValueError("degenerate camera direction")
+ return v / n
+
+
+@dataclass
+class CameraDef:
+ name: str
+ pos: tuple
+ lookat: tuple
+ up: tuple = (0.0, 0.0, 1.0)
+ fovy_deg: float = 45.0
+ width: int = 320
+ height: int = 240
+
+ def __post_init__(self):
+ self.pos = tuple(float(x) for x in self.pos)
+ self.lookat = tuple(float(x) for x in self.lookat)
+ self.up = tuple(float(x) for x in self.up)
+ self.fovy_deg, self.width, self.height = float(self.fovy_deg), int(self.width), int(self.height)
+ if len(self.pos) != 3 or len(self.lookat) != 3 or len(self.up) != 3:
+ raise ValueError("pos, lookat and up are 3-vectors")
+ if not 0 < self.fovy_deg < 180 or self.width <= 0 or self.height <= 0:
+ raise ValueError("fovy_deg in (0, 180), positive width and height")
+ self.basis() # raises on a degenerate pose
+
+ @staticmethod
+ def from_dict(d: dict) -> "CameraDef":
+ keys = ("name", "pos", "lookat", "up", "fovy_deg", "width", "height")
+ return CameraDef(**{k: d[k] for k in keys if k in d})
+
+ def to_dict(self) -> dict:
+ return {"name": self.name, "pos": list(self.pos), "lookat": list(self.lookat), "up": list(self.up),
+ "fovy_deg": self.fovy_deg, "width": self.width, "height": self.height}
+
+ def focal_px(self) -> float:
+ return (self.height / 2) / math.tan(math.radians(self.fovy_deg) / 2)
+
+ def intrinsics(self) -> dict:
+ return {"focal_px": self.focal_px(), "principal_point_px": [self.width / 2, self.height / 2],
+ "width": self.width, "height": self.height}
+
+ def basis(self):
+ """(right, up, forward) unit vectors in the world frame."""
+ fwd = _unit(np.subtract(self.lookat, self.pos))
+ right = _unit(np.cross(fwd, self.up))
+ up = np.cross(right, fwd)
+ return right, up, fwd
+
+ def project(self, point):
+ """Pixel (u, v) of a world point (u right, v down, from the top-left corner; continuous coordinates, so the
+ centre of pixel column i is u = i + 0.5). None if the point is behind the camera."""
+ right, up, fwd = self.basis()
+ d = np.subtract(point, self.pos)
+ depth = float(d @ fwd)
+ if depth <= 1e-9:
+ return None
+ f = self.focal_px()
+ return (self.width / 2 + f * float(d @ right) / depth, self.height / 2 - f * float(d @ up) / depth)
+
+ def spherical(self):
+ """(lookat, distance, azimuth_deg, elevation_deg): the free-camera form the showcase exporters use."""
+ d = np.subtract(self.lookat, self.pos)
+ dist = float(np.linalg.norm(d))
+ az = math.degrees(math.atan2(d[1], d[0]))
+ el = math.degrees(math.asin(max(-1.0, min(1.0, d[2] / dist))))
+ return list(self.lookat), dist, az, el
+
+
+@dataclass
+class Scene:
+ engine: str = "mujoco" # the physics engine whose scene format `xml` is in
+ xml: str = "" # MJCF text (engine "mujoco")
+ assets: dict = field(default_factory=dict) # {path as referenced by the xml (with meshdir/texturedir): bytes}
+ look: dict | None = None # optional presentation appearance (showcase renderers only)
+ match: "Scene | None" = None # set on a presentation scene only: the match scene it dresses
+ credits: tuple = () # presentation scene: what was added, with its source and licence
+ players: bool = False # a presentation scene the sport declares for its players' images too
+
+ @property
+ def is_presentation(self) -> bool:
+ """A presentation scene (renderers/presentation): drawn for the players' images only when `players` is set
+ (the sport declares it, renderer rule 6), else for spectators only."""
+ return self.match is not None
+
+ @staticmethod
+ def from_file(path, look=None) -> "Scene":
+ """A scene file plus every other file below its directory as an asset (paths relative to that directory)."""
+ p = Path(path)
+ assets = {str(f.relative_to(p.parent)): f.read_bytes() for f in sorted(p.parent.rglob("*"))
+ if f.is_file() and f != p and "__pycache__" not in f.parts}
+ return Scene(engine="mujoco", xml=p.read_text(), assets=assets, look=look)
+
+
+class Renderer(ABC):
+ name: str = ""
+ realtime: bool = True # fast enough for player images (still subject to the task's frame budget)
+ needs_gpu: bool = False
+ label: str | None = None # the tag a re-rendered frame carries ("re-rendered: <engine>"); None = default
+
+ def __init__(self, scene: Scene, **opts):
+ self.scene, self.opts = scene, opts
+
+ @abstractmethod
+ def render(self, state: dict, cameras: list) -> list:
+ """One H x W x 3 uint8 image per camera (CameraDef or its dict form), for the given world state."""
+
+ def close(self):
+ pass
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ self.close()
+
+
+def as_cameras(cameras) -> list:
+ return [c if isinstance(c, CameraDef) else CameraDef.from_dict(c) for c in cameras]
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/mujoco/__init__.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/mujoco/__init__.py
new file mode 100644
index 0000000000..1f52d6a69d
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/mujoco/__init__.py
@@ -0,0 +1,144 @@
+"""The default renderer: MuJoCo's own rasterizer (CPU with MUJOCO_GL=osmesa, GPU with egl), real time.
+
+The scene is compiled once from its MJCF text with spare world-body cameras added; each CameraDef is drawn by
+setting one spare camera's pose and vertical field of view exactly (cam_pos / cam_quat / cam_fovy), so the picture
+follows CameraDef.project to the pixel. The renderer keeps its own MjModel / MjData: the match's world is never
+touched. A presentation scene (Scene.match set; spectators only) is drawn only when its kinematics equal the match
+scene's (scene_check.same_kinematics); every renderer built on this one inherits the check."""
+from __future__ import annotations
+
+import numpy as np
+
+from ..base import CameraDef, Renderer, RendererUnavailable, Scene, as_cameras
+
+SPARE = "_ro_cam"
+
+
+def camera_quat(cam: CameraDef):
+ """MuJoCo camera frame: x = image right, y = image up, looking along -z."""
+ import mujoco as mj
+ right, up, fwd = cam.basis()
+ R = np.column_stack([right, up, -fwd])
+ q = np.zeros(4)
+ mj.mju_mat2Quat(q, R.reshape(-1))
+ return q
+
+
+def compile_spec(spec, n_cams: int, size):
+ """Add n spare cameras and make the off-screen buffer at least `size` (w, h); returns the compiled model."""
+ g = spec.visual.global_
+ g.offwidth, g.offheight = max(int(g.offwidth), int(size[0])), max(int(g.offheight), int(size[1]))
+ for i in range(n_cams):
+ spec.worldbody.add_camera(name=f"{SPARE}{i}", pos=[0, 0, 0], quat=[1, 0, 0, 0], fovy=45)
+ return spec.compile()
+
+
+def load_spec(scene: Scene):
+ import mujoco as mj
+ if scene.engine != "mujoco":
+ raise RendererUnavailable("mujoco", f"scene engine {scene.engine!r} is not MJCF")
+ return mj.MjSpec.from_string(scene.xml, assets=dict(scene.assets or {}))
+
+
+class MujocoRenderer(Renderer):
+ name = "mujoco"
+ title = "MuJoCo"
+ realtime = True
+ needs_gpu = False
+ label = None # the competition picture: no tag
+
+ def __init__(self, scene: Scene, n_cams: int = 8, size=(640, 480), **opts):
+ super().__init__(scene, **opts)
+ try:
+ import mujoco # noqa: F401
+ except ImportError as exc: # pragma: no cover - the sim images have it
+ raise RendererUnavailable(self.name, "the mujoco Python package is missing", "mujoco") from exc
+ self._n, self._size = int(n_cams), tuple(size)
+ self._build()
+
+ # ---------------------------------------------------------------- model
+ def make_spec(self):
+ """The MjSpec to draw (subclasses change only visual properties)."""
+ return load_spec(self.scene)
+
+ def _build(self):
+ import mujoco as mj
+ self.close()
+ self.m = compile_spec(self.make_spec(), self._n, self._size)
+ if self.scene.match is not None: # a presentation scene: same kinematics as the match scene
+ from ..scene_check import same_kinematics
+ bad = same_kinematics(compile_spec(load_spec(self.scene.match), self._n, self._size), self.m)
+ if bad:
+ raise RuntimeError(f"{self.name}: the presentation scene's kinematics differ from the match scene: "
+ f"{bad[:8]}")
+ self.d = mj.MjData(self.m)
+ self.cam_ids = [self.m.camera(f"{SPARE}{i}").id for i in range(self._n)]
+ self._r = {}
+
+ def _renderer(self, w, h):
+ import mujoco as mj
+ if (w, h) not in self._r:
+ self._r[w, h] = mj.Renderer(self.m, height=h, width=w)
+ return self._r[w, h]
+
+ def set_state(self, state: dict):
+ import mujoco as mj
+ m, d = self.m, self.d
+ q = np.asarray(state.get("qpos", d.qpos), dtype=float)
+ if q.shape != (m.nq,):
+ raise ValueError(f"state qpos has {q.size} values, the scene has nq={m.nq}")
+ d.qpos[:] = q
+ if m.nmocap:
+ if "mocap_pos" in state:
+ d.mocap_pos[:] = np.asarray(state["mocap_pos"], float).reshape(m.nmocap, 3)
+ if "mocap_quat" in state:
+ d.mocap_quat[:] = np.asarray(state["mocap_quat"], float).reshape(m.nmocap, 4)
+ mj.mj_kinematics(m, d)
+ mj.mj_comPos(m, d)
+ mj.mj_camlight(m, d)
+
+ # ---------------------------------------------------------------- drawing
+ def render(self, state: dict, cameras: list) -> list:
+ import mujoco as mj
+ cams = as_cameras(cameras)
+ w_max, h_max = max([c.width for c in cams] + [1]), max([c.height for c in cams] + [1])
+ if len(cams) > self._n or w_max > self.m.vis.global_.offwidth or h_max > self.m.vis.global_.offheight:
+ self._n = max(self._n, len(cams))
+ self._size = (max(self._size[0], w_max), max(self._size[1], h_max))
+ self._build()
+ self.set_state(state)
+ for cam, cid in zip(cams, self.cam_ids):
+ self.m.cam_pos[cid] = cam.pos
+ self.m.cam_quat[cid] = camera_quat(cam)
+ self.m.cam_fovy[cid] = cam.fovy_deg
+ mj.mj_camlight(self.m, self.d) # camera world poses from the new cam_pos / cam_quat
+ self._clip(cams)
+ out = []
+ for cam, cid in zip(cams, self.cam_ids):
+ r = self._renderer(cam.width, cam.height)
+ r.update_scene(self.d, camera=cid)
+ out.append(self.post(np.array(r.render(), dtype=np.uint8, copy=True), cam))
+ return out
+
+ def _clip(self, cams):
+ """MuJoCo clips at zfar * stat.extent: keep every geom of the current state inside every camera's far plane
+ (a small scene seen from afar, or a body far from the scene centre, would otherwise vanish). Visualization
+ only, on our own model copy."""
+ m, d = self.m, self.d
+ ext = max(float(m.stat.extent), 1e-6)
+ pts = np.asarray(d.geom_xpos) if m.ngeom else np.zeros((1, 3))
+ rb = float(np.max(m.geom_rbound)) if m.ngeom else 0.0
+ reach = max(float(np.max(np.linalg.norm(pts - np.asarray(c.pos), axis=1))) for c in cams) + rb
+ if m.vis.map.zfar * ext < 1.05 * reach:
+ m.vis.map.zfar = 1.05 * reach / ext
+
+ def post(self, img, cam):
+ return img
+
+ def close(self):
+ for r in getattr(self, "_r", {}).values():
+ r.close()
+ self._r = {}
+
+
+RENDERER = MujocoRenderer
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/presentation/LICENSE.franka_emika_panda b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/presentation/LICENSE.franka_emika_panda
new file mode 100644
index 0000000000..d9a10c0d8e
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/presentation/LICENSE.franka_emika_panda
@@ -0,0 +1,176 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/presentation/LICENSE.kuka_iiwa_14 b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/presentation/LICENSE.kuka_iiwa_14
new file mode 100644
index 0000000000..d4681a468e
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/presentation/LICENSE.kuka_iiwa_14
@@ -0,0 +1,31 @@
+All components of Drake are licensed under the BSD 3-Clause License
+shown below. Where noted in the source code, some portions may
+be subject to other permissive, non-viral licenses.
+
+Copyright 2012-2022 Robot Locomotion Group @ CSAIL
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+Redistributions of source code must retain the above copyright notice,
+this list of conditions and the following disclaimer. Redistributions
+in binary form must reproduce the above copyright notice, this list of
+conditions and the following disclaimer in the documentation and/or
+other materials provided with the distribution. Neither the name of
+the Massachusetts Institute of Technology nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/presentation/__init__.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/presentation/__init__.py
new file mode 100644
index 0000000000..7c589751f7
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/presentation/__init__.py
@@ -0,0 +1,326 @@
+"""Presentation scenes (docs/framework_zh.md §3.1, renderer rule 6): a sport may dress its match scene for spectators,
+e.g. draw its robot arms with a manufacturer-grade visual model instead of their collision meshes. A presentation
+scene is the match scene plus visual-only geoms on the SAME bodies; nothing that moves or collides changes
+(scene_check.same_kinematics, checked by every renderer before it draws one), so a recorded match replays and
+re-renders with identical body poses. By default it is for spectator renderers only (replay videos, re-renders,
+stills): the players' images use the match scene (core/observe.CameraWorker refuses a presentation scene).
+
+Players' images (core 0.2.9): a sport may declare `players = "<meshes>"` below; then the players' images are drawn
+from the presentation scene too, with the meshes named ("full" = the upstream files, or a level of detail of lod.json,
+e.g. "25k": decimated, a few MB, cheap on the CPU). tools/sportlib.assemble_sim then copies this directory and the
+models' files (verified by sha256, with their licences) into the simulator directory (<sim>/sport/presentation/,
+assets under assets/), so they are part of source_sha and a match needs no cache or network; `players_scene` builds
+that scene (Scene.players set: CameraWorker accepts it, after the same kinematics check), `players_model` compiles it
+for a sport that draws its own images. Changing the declaration changes the players' images: bump the sport's
+revision.
+
+Declaration: sports/<sport>/presentation/presentation.toml (outside the simulator directory: tools/sportlib.NOT_IN_SIM,
+so source_sha, the golden replays and the task directories do not change):
+
+ [presentation]
+ version = 1 # bump on any change of the dressing
+ label = "Franka Panda visual meshes (MuJoCo Menagerie)"
+ [[presentation.robot]]
+ model = "franka_emika_panda" # a model of the asset manifest (renderers/presentation/menagerie.json),
+ # or "./<path>.xml": a (self-authored) model in this directory
+ bodies = '^(?P<pre>[AB]_)?link(?P<n>[0-7])$' # scene bodies to dress (Python regex, full match) ...
+ body = "link{n}" # ... and the model body whose visual geoms each one gets
+ hide = "all" # the dressed bodies' own geoms: "all" (default) | "mesh" | "none"
+ # are hidden (moved to group 3), not removed
+ hide_bodies = '^...$' # optional: hide only in these dressed bodies (default: all of them)
+ colors = { white = [0.92, 0.5, 0.42, 1] } # optional: a model material's colour for this robot (e.g. a side colour)
+ scenes = ["sim/scene/a.xml"] # optional: the match scene files (relative to the sport directory),
+ # for spectator tools when the sport has no Sport.scene()
+ players = "25k" # optional, top level: the players' images use this scene too, with
+ # these meshes ("full" or a level of lod.json); absent = spectators only
+
+The model's visual geoms (contype = conaffinity = 0, group 0..2) are copied, with their meshes, materials and poses
+in the body frame, onto each matching scene body; a body whose parent is dressed too must sit in its parent's frame
+exactly as the model's does (else the declaration names the wrong bodies and dressing fails). The models' files come
+from the asset cache (renderers/presentation/assets.py: pinned commit, sha256 per file; `python3 -m
+renderers.presentation.assets fetch`), never from the repository.
+
+ from renderers.presentation import for_plugin
+ scene = for_plugin("sports/tabletennis/plugin.py", match_scene) # None if the sport declares no presentation
+"""
+from __future__ import annotations
+
+import os
+import re
+import xml.etree.ElementTree as ET
+from pathlib import Path
+
+import numpy as np
+
+from ..base import Scene
+from ..scene_check import VISUAL_PREFIX
+
+DECL = "presentation.toml"
+BUNDLE = "assets" # <sim>/sport/presentation/assets: the models' files bundled into a simulator
+CLASS = "ro_presentation" # the default class of the added geoms (inherits nothing from a robot's childclass)
+HIDDEN_GROUP = "3" # renderers draw groups 0..2; the dressed bodies' own geoms move here
+FRAME_TOL = 1e-6
+
+
+class PresentationUnavailable(RuntimeError):
+ """The sport declares a presentation scene that cannot be built here (e.g. the model assets are not fetched)."""
+
+
+def match_scenes(sport_dir: str | os.PathLike) -> list:
+ """The match scene files a presentation declares (`scenes`), as Scenes; [] if none."""
+ d = Path(sport_dir) / "presentation"
+ if not declared(d):
+ return []
+ return [Scene.from_file(Path(sport_dir) / f) for f in load_decl(d).get("scenes", [])]
+
+
+def directory(plugin: str | os.PathLike) -> Path:
+ return Path(plugin).resolve().parent / "presentation"
+
+
+def declared(d: str | os.PathLike) -> bool:
+ return (Path(d) / DECL).is_file()
+
+
+def load_decl(d: str | os.PathLike) -> dict:
+ import tomllib
+ p = (tomllib.loads((Path(d) / DECL).read_text()).get("presentation") or {})
+ if int(p.get("version", 0)) < 1 or not p.get("robot"):
+ raise ValueError(f"{Path(d) / DECL}: [presentation] needs version >= 1 and at least one [[presentation.robot]]")
+ for r in p["robot"]:
+ for k in ("model", "bodies", "body"):
+ if k not in r:
+ raise ValueError(f"{Path(d) / DECL}: a [[presentation.robot]] needs {k!r}")
+ if r.get("hide", "all") not in ("all", "mesh", "none"):
+ raise ValueError(f"{Path(d) / DECL}: hide is all | mesh | none")
+ pl = p.get("players")
+ if pl is not None and (not isinstance(pl, str) or not (pl == "full" or re.fullmatch(r"\d+k", pl))):
+ raise ValueError(f"{Path(d) / DECL}: players is \"full\" or a level of detail like \"25k\"")
+ return p
+
+
+def players_meshes(d: str | os.PathLike) -> str | None:
+ """The meshes the players' images use ("full" or a level of detail), None = spectators only (the default)."""
+ return load_decl(d).get("players") if declared(d) else None
+
+
+def players_scene(sport_dir: str | os.PathLike, match: Scene) -> Scene:
+ """The scene of the players' images: the presentation scene of `sport_dir` (the sport's directory, or the
+ simulator's sport/) when it declares `players`, else `match` itself."""
+ d = Path(sport_dir) / "presentation"
+ meshes = players_meshes(d)
+ return match if meshes is None else dress(match, d, meshes=meshes, players=True)
+
+
+def players_model(sport_dir: str | os.PathLike, match: Scene):
+ """For a sport that draws its own images: the compiled MjModel of the players' scene, after the same kinematics
+ check against the match scene; None when the sport does not declare `players` (draw the match model)."""
+ sc = players_scene(sport_dir, match)
+ if sc is match:
+ return None
+ import mujoco as mj
+ from ..scene_check import same_kinematics
+ m = mj.MjSpec.from_string(sc.xml, assets=dict(sc.assets or {})).compile()
+ bad = same_kinematics(mj.MjSpec.from_string(match.xml, assets=dict(match.assets or {})).compile(), m)
+ if bad:
+ raise RuntimeError(f"the players' presentation scene's kinematics differ from the match scene: {bad[:8]}")
+ return m
+
+
+def for_plugin(plugin, match: Scene) -> Scene | None:
+ """The presentation scene of the sport whose plugin is `plugin`, dressing `match` (the sport's scene for the same
+ configuration); None when the sport declares none. Raises PresentationUnavailable when it cannot be built. Inside a
+ simulator directory (a bundle, players' presentation) it is the players' scene."""
+ d = directory(plugin)
+ if not declared(d):
+ return None
+ meshes = players_meshes(d)
+ if meshes is not None and (d / BUNDLE).is_dir(): # inside a simulator: only the players' meshes are bundled
+ return dress(match, d, meshes=meshes, players=True)
+ return dress(match, d)
+
+
+# ------------------------------------------------------------------------------------------------ robot models
+def _f(v) -> str:
+ return " ".join(repr(float(x)) for x in np.asarray(v, float).reshape(-1))
+
+
+def _unitq(q):
+ q = np.asarray(q, float)
+ return q / np.linalg.norm(q)
+
+
+def model_parts(xml_path: str | os.PathLike) -> dict:
+ """The visual model of a robot description (parsed by MuJoCo's MJCF parser, nothing compiled or executed):
+ {"bodies": {name: {"parent", "pos", "quat", "geoms": [{"mesh", "material", "rgba", "pos", "quat"}]}},
+ "meshes": {name: {"file" (relative to the description's directory), "scale", "refpos", "refquat"}},
+ "materials": {name: {"rgba", "specular", "shininess", "reflectance", "emission"}}}"""
+ import mujoco as mj
+ xml_path = Path(xml_path)
+ spec = mj.MjSpec.from_file(str(xml_path))
+ meshdir = spec.meshdir or ""
+ meshes = {}
+ for me in spec.meshes:
+ if not me.file:
+ raise ValueError(f"{xml_path.name}: mesh {me.name!r} has no file (only file meshes are supported)")
+ name = me.name or Path(me.file).stem
+ meshes[name] = {"file": os.path.normpath(os.path.join(meshdir, me.file)), "scale": list(me.scale),
+ "refpos": list(me.refpos), "refquat": list(me.refquat)}
+ materials = {mt.name: {"rgba": list(mt.rgba), "specular": float(mt.specular), "shininess": float(mt.shininess),
+ "reflectance": float(mt.reflectance), "emission": float(mt.emission)}
+ for mt in spec.materials}
+ bodies, used = {}, set()
+ for b in spec.bodies:
+ if not b.name or b.name == "world":
+ continue
+ if b.alt.type != mj.mjtOrientation.mjORIENTATION_QUAT:
+ raise ValueError(f"{xml_path.name}: body {b.name} uses an alternative orientation")
+ geoms = []
+ for g in b.geoms:
+ if g.type != mj.mjtGeom.mjGEOM_MESH or g.contype or g.conaffinity or not 0 <= g.group <= 2:
+ continue
+ if g.alt.type != mj.mjtOrientation.mjORIENTATION_QUAT:
+ raise ValueError(f"{xml_path.name}: a visual geom of {b.name} uses an alternative orientation")
+ geoms.append({"mesh": g.meshname, "material": g.material or None, "rgba": list(g.rgba),
+ "pos": list(g.pos), "quat": list(g.quat)})
+ used.add(g.meshname)
+ if g.material:
+ used.add(("mat", g.material))
+ bodies[b.name] = {"parent": b.parent.name if b.parent is not None else "world", "pos": list(b.pos),
+ "quat": list(b.quat), "geoms": geoms}
+ return {"bodies": bodies, "meshes": {n: v for n, v in meshes.items() if n in used},
+ "materials": {n: v for n, v in materials.items() if ("mat", n) in used}}
+
+
+# ------------------------------------------------------------------------------------------------ dressing
+def _meshdir(root) -> str:
+ c = root.find("compiler")
+ if c is None:
+ return ""
+ return c.get("meshdir") or c.get("assetdir") or ""
+
+
+def _asset_key(meshdir: str, file: str) -> str:
+ return os.path.normpath(os.path.join(meshdir, file)) if meshdir else file
+
+
+def _local_frame(el) -> tuple:
+ pos = np.array([float(x) for x in el.get("pos", "0 0 0").split()])
+ if any(el.get(a) is not None for a in ("euler", "axisangle", "xyaxes", "zaxis")):
+ return pos, None
+ return pos, _unitq([float(x) for x in el.get("quat", "1 0 0 0").split()])
+
+
+def dress(match: Scene, d: str | os.PathLike, meshes: str = "full", players: bool = False) -> Scene:
+ """The presentation scene declared in directory `d` for the match scene `match` (see the module docstring), the
+ models with `meshes` ("full" or a level of detail); players: the scene of the players' images (Scene.players).
+ The models' files come from `d`/assets when it exists (a simulator's bundle), else from the cache / lod/."""
+ from . import assets
+ if match.engine != "mujoco":
+ raise PresentationUnavailable(f"presentation scenes need an MJCF scene, not {match.engine!r}")
+ decl = load_decl(d)
+ if players and decl.get("players") is None:
+ raise ValueError(f"{Path(d) / DECL}: the players' images use a presentation scene only when it declares players")
+ bundled = Path(d) / BUNDLE
+ bundle_root = bundled if bundled.is_dir() else None
+ root = ET.fromstring(match.xml)
+ meshdir = _meshdir(root)
+ out_assets = dict(match.assets or {})
+ asset_el = root.find("asset")
+ if asset_el is None:
+ asset_el = ET.Element("asset")
+ root.insert(0, asset_el)
+ default = root.find("default")
+ if default is None:
+ default = ET.Element("default")
+ root.insert(0, default)
+ cls = ET.SubElement(default, "default", {"class": CLASS})
+ ET.SubElement(cls, "geom", {"type": "mesh", "contype": "0", "conaffinity": "0", "group": "2", "mass": "0",
+ "density": "0", "rgba": "0.5 0.5 0.5 1"})
+ parents = {c: p for p in root.iter() for c in p}
+ bodies = {b.get("name"): b for b in root.iter("body") if b.get("name")}
+ credits, n_added, dressed_all, meshes_added = [], 0, set(), set()
+ for ri, rob in enumerate(decl["robot"]):
+ if rob["model"].startswith("./"): # a model shipped in the presentation directory itself
+ xml_file = (Path(d) / rob["model"]).resolve()
+ if Path(d).resolve() not in xml_file.parents:
+ raise ValueError(f"{DECL}: a local model must lie inside the presentation directory")
+ credit = rob.get("credit", f"{rob['model']} (shipped with the sport)")
+ else:
+ xml_file, credit = assets.model_xml(rob["model"], meshes, bundle_root), assets.credit(rob["model"])
+ if meshes != "full":
+ credit += f", visual meshes decimated to level {meshes} (renderers/presentation/lod.json)"
+ parts = model_parts(xml_file)
+ tag = re.sub(r"[^A-Za-z0-9_]", "_", rob["model"])
+ pat = re.compile(rob["bodies"])
+ dressed = {}
+ for name, el in bodies.items():
+ mt = pat.fullmatch(name)
+ if not mt:
+ continue
+ mbody = rob["body"].format(**{k: v or "" for k, v in mt.groupdict().items()})
+ if mbody not in parts["bodies"]:
+ raise ValueError(f"{DECL}: scene body {name} -> {mbody}, which {rob['model']} does not have")
+ dressed[name] = mbody
+ if not dressed:
+ raise ValueError(f"{DECL}: no scene body matches {rob['bodies']!r}")
+ if dressed.keys() & dressed_all:
+ raise ValueError(f"{DECL}: bodies dressed twice: {sorted(dressed.keys() & dressed_all)}")
+ dressed_all |= dressed.keys()
+ for name, mbody in dressed.items(): # the declaration must name bodies in the model's frames
+ par = parents.get(bodies[name])
+ pname = par.get("name") if par is not None and par.tag == "body" else None
+ if pname in dressed and dressed[pname] == parts["bodies"][mbody]["parent"]:
+ pos, quat = _local_frame(bodies[name])
+ mb = parts["bodies"][mbody]
+ if quat is None or np.abs(pos - mb["pos"]).max() > FRAME_TOL or min(
+ np.abs(quat - _unitq(mb["quat"])).max(), np.abs(quat + _unitq(mb["quat"])).max()) > FRAME_TOL:
+ raise ValueError(f"{DECL}: scene body {name} does not sit in its parent's frame as "
+ f"{rob['model']}'s {mbody} does")
+ # assets: the model's meshes and materials, once per robot entry
+ colors = rob.get("colors", {})
+ if set(colors) - set(parts["materials"]) or any(len(v) != 4 for v in colors.values()):
+ raise ValueError(f"{DECL}: colors names materials of {rob['model']} ({sorted(parts['materials'])}), "
+ "each an rgba of 4 numbers")
+ for mname, mat in parts["materials"].items():
+ ET.SubElement(asset_el, "material", {"name": f"ro_{tag}_{ri}_{mname}",
+ "rgba": _f(colors.get(mname, mat["rgba"])),
+ "specular": repr(mat["specular"]),
+ "shininess": repr(mat["shininess"]),
+ "reflectance": repr(mat["reflectance"]),
+ "emission": repr(mat["emission"])})
+ for mname, me in parts["meshes"].items(): # meshes once per model, materials per robot entry
+ if f"ro_{tag}_{mname}" in meshes_added:
+ continue
+ meshes_added.add(f"ro_{tag}_{mname}")
+ rel = f"ro_presentation/{tag}/{me['file']}"
+ attrs = {"name": f"ro_{tag}_{mname}", "file": rel, "scale": _f(me["scale"])}
+ if np.any(np.asarray(me["refpos"]) != 0) or np.any(np.asarray(me["refquat"]) != [1, 0, 0, 0]):
+ attrs.update(refpos=_f(me["refpos"]), refquat=_f(me["refquat"]))
+ ET.SubElement(asset_el, "mesh", attrs)
+ out_assets[_asset_key(meshdir, rel)] = (xml_file.parent / me["file"]).read_bytes()
+ hide = rob.get("hide", "all")
+ hide_pat = re.compile(rob["hide_bodies"]) if rob.get("hide_bodies") else None
+ for name, mbody in dressed.items():
+ body = bodies[name]
+ if hide != "none" and (hide_pat is None or hide_pat.fullmatch(name)):
+ for g in body.findall("geom"):
+ if hide == "all" or g.get("type") == "mesh" or (g.get("mesh") and g.get("type") is None):
+ g.set("group", HIDDEN_GROUP)
+ kids = list(body)
+ at = max([i for i, e in enumerate(kids) if e.tag in ("geom", "inertial", "joint", "freejoint")] + [-1]) + 1
+ for j, g in enumerate(parts["bodies"][mbody]["geoms"]):
+ attrs = {"name": f"{VISUAL_PREFIX}{name}:{j}", "class": CLASS, "mesh": f"ro_{tag}_{g['mesh']}",
+ "pos": _f(g["pos"]), "quat": _f(g["quat"])}
+ if g["material"]:
+ attrs["material"] = f"ro_{tag}_{ri}_{g['material']}"
+ elif not np.allclose(g["rgba"], [0.5, 0.5, 0.5, 1]):
+ attrs["rgba"] = _f(g["rgba"])
+ body.insert(at + j, ET.Element("geom", attrs))
+ n_added += 1
+ credits.append(credit)
+ xml = ET.tostring(root, encoding="unicode")
+ return Scene(engine=match.engine, xml=xml, assets=out_assets, look=match.look, match=match, players=players,
+ credits=tuple(credits) + (f"{decl.get('label', 'presentation scene')} (v{decl['version']}, "
+ f"{n_added} visual geoms" + (", the players' images" if players else "")
+ + ")",))
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/presentation/assets.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/presentation/assets.py
new file mode 100644
index 0000000000..14edb00e1d
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/presentation/assets.py
@@ -0,0 +1,198 @@
+"""Third-party model files of the presentation scenes, fetched at build time (never committed): every file is pinned
+to one upstream commit and checked against its sha256 in the manifest (menagerie.json, next to this file). The files
+are untrusted data: they are only read (MJCF parsed, meshes loaded by MuJoCo), never executed. Their licences are
+kept next to the manifest (LICENSE.<model>) and credited in NOTICE.
+
+ python3 -m renderers.presentation.assets fetch [MODEL ...] download the missing files (all models by default)
+ python3 -m renderers.presentation.assets verify [MODEL ...] check what is in the cache
+ python3 -m renderers.presentation.assets where print the cache directory
+
+The cache: $RO_ASSET_CACHE, else <repo>/.cache/assets (git-ignored); files at <cache>/<source>/<commit>/<path>.
+Standard library only (python >= 3.8), so the fetch runs on any host; the renderers read the cache inside the image.
+
+Levels of detail (players' images, renderer rule 6): lod.json lists decimated copies of a model's visual meshes
+(renderers/presentation/lod/<level>/<path>, committed: small, derived from the pinned files, licence unchanged; made by
+lod.py), each file pinned by sha256 like the upstream ones. `meshes` = "full" (the upstream files) or a level ("25k").
+A sport whose players' images use its presentation scene gets the model's files bundled into its simulator directory
+(`bundle`, tools/sportlib.assemble_sim): <sim>/sport/presentation/assets/<path>, checked against the same manifests,
+so a match needs neither the cache nor the network.
+"""
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import sys
+import urllib.request
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+MANIFESTS = ("menagerie.json",)
+LOD_MANIFEST = "lod.json"
+FULL = "full"
+_verified: set = set()
+
+
+class _Unavailable(RuntimeError):
+ pass
+
+
+def _err(msg):
+ try:
+ from . import PresentationUnavailable
+ except ImportError: # pragma: no cover - run as a script on a host without numpy
+ return _Unavailable(msg)
+ return PresentationUnavailable(msg)
+
+
+def manifests() -> list:
+ return [json.loads((HERE / m).read_text()) for m in MANIFESTS]
+
+
+def _find(name: str):
+ for man in manifests():
+ if name in man["models"]:
+ return man, man["models"][name]
+ raise KeyError(f"no presentation model {name!r} in {', '.join(MANIFESTS)}")
+
+
+def cache_root() -> Path:
+ env = os.environ.get("RO_ASSET_CACHE")
+ return Path(env) if env else HERE.parents[1] / ".cache" / "assets"
+
+
+def _base(man) -> Path:
+ return cache_root() / man["name"] / man["commit"]
+
+
+def _sha(p: Path) -> str:
+ h = hashlib.sha256()
+ with open(p, "rb") as f:
+ for chunk in iter(lambda: f.read(1 << 20), b""):
+ h.update(chunk)
+ return h.hexdigest()
+
+
+def lods() -> dict:
+ """lod.json: {"models": {model: {level: {"files": {path: sha256}, ...}}}, ...} ({} if absent)."""
+ p = HERE / LOD_MANIFEST
+ return json.loads(p.read_text()) if p.is_file() else {}
+
+
+def files(name: str, meshes: str = FULL) -> dict:
+ """{path: sha256} of model `name` with the given meshes ("full" or a level of lod.json)."""
+ man, mod = _find(name)
+ if meshes == FULL:
+ return dict(mod["files"])
+ lev = (lods().get("models", {}).get(name) or {}).get(meshes)
+ if lev is None:
+ raise KeyError(f"no level of detail {meshes!r} of {name} in {LOD_MANIFEST}")
+ return dict(lev["files"])
+
+
+def source_dir(name: str, meshes: str = FULL) -> Path:
+ """Where the files of `name` with `meshes` live on this checkout: the cache (full) or renderers/presentation/lod."""
+ man, _ = _find(name)
+ return _base(man) if meshes == FULL else lod_root() / meshes
+
+
+def lod_root() -> Path:
+ """The levels of detail: $RO_LOD_DIR (robot_coding_bench: the eai-olympiad image ships them at
+ /opt/roboolympics/lod, verified here against lod.json), else renderers/presentation/lod."""
+ env = os.environ.get("RO_LOD_DIR")
+ return Path(env) if env else HERE / "lod"
+
+
+def missing(name: str, meshes: str = FULL, root: Path | None = None) -> list:
+ """The files of model `name` that are absent (from `root`, default its source_dir) or do not match their sha256."""
+ base = Path(root) if root is not None else source_dir(name, meshes)
+ return [p for p, sha in files(name, meshes).items() if not (base / p).is_file() or _sha(base / p) != sha]
+
+
+def model_xml(name: str, meshes: str = FULL, root: Path | None = None) -> Path:
+ """The model's MJCF file, all its files verified (once per process): from `root` (a simulator's bundle) if given,
+ else from the cache (full meshes) or renderers/presentation/lod (a level of detail)."""
+ _, mod = _find(name)
+ base = Path(root) if root is not None else source_dir(name, meshes)
+ key = (name, meshes, str(base))
+ if key not in _verified:
+ bad = missing(name, meshes, base)
+ if bad:
+ how = (f"python3 -m renderers.presentation.assets fetch {name}" if meshes == FULL and root is None
+ else "regenerate the task (tools/generate.py)" if root is not None
+ else f"python3 -m renderers.presentation.lod build {name} {meshes}")
+ raise _err(f"presentation model {name} ({meshes} meshes): {len(bad)} of {len(files(name, meshes))} files "
+ f"missing or not matching their sha256 in {base} ({how})")
+ _verified.add(key)
+ return base / mod["xml"]
+
+
+def bundle(name: str, meshes: str, dst: Path) -> list:
+ """Copy model `name` with `meshes` (verified) and its licence into the directory `dst` (a simulator's
+ sport/presentation/assets): returns the paths written, relative to dst."""
+ import shutil
+ _, mod = _find(name)
+ src = source_dir(name, meshes)
+ model_xml(name, meshes) # verifies every file
+ out = []
+ for p in sorted(files(name, meshes)):
+ (Path(dst) / p).parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(src / p, Path(dst) / p)
+ out.append(p)
+ lic = mod["license_file"]
+ shutil.copyfile(HERE / lic, Path(dst) / lic)
+ return out + [lic]
+
+
+def credit(name: str) -> str:
+ man, mod = _find(name)
+ return (f"{mod['title']}: {man['title']} ({man['source']}, commit {man['commit'][:12]}, {mod['path']}), "
+ f"{mod['copyright']}, {mod['license']} (renderers/presentation/{mod['license_file']})")
+
+
+def fetch(name: str, log=print) -> int:
+ man, mod = _find(name)
+ base = _base(man)
+ n = 0
+ for p, sha in sorted(mod["files"].items()):
+ dst = base / p
+ if dst.is_file() and _sha(dst) == sha:
+ continue
+ url = man["url"].format(commit=man["commit"], path=p)
+ dst.parent.mkdir(parents=True, exist_ok=True)
+ tmp = dst.with_name(dst.name + ".part")
+ with urllib.request.urlopen(url, timeout=60) as r, open(tmp, "wb") as f:
+ f.write(r.read())
+ got = _sha(tmp)
+ if got != sha:
+ tmp.unlink()
+ raise _err(f"{url}: sha256 {got} != {sha} (manifest); nothing kept")
+ tmp.replace(dst)
+ n += 1
+ log(f"{name}: {len(mod['files'])} files in {base} ({n} downloaded)")
+ return n
+
+
+def main(argv) -> int:
+ cmd, names = (argv[0] if argv else "verify"), argv[1:]
+ if cmd == "where":
+ print(cache_root())
+ return 0
+ names = names or [n for man in manifests() for n in man["models"]]
+ rc = 0
+ for n in names:
+ if cmd == "fetch":
+ fetch(n)
+ elif cmd == "verify":
+ for meshes in [FULL] + sorted(lods().get("models", {}).get(n, {})):
+ bad = missing(n, meshes)
+ print(f"{n} ({meshes}): " + ("ok" if not bad else f"{len(bad)} files missing or changed"))
+ rc |= bool(bad)
+ else:
+ print(__doc__)
+ return 2
+ return rc
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/presentation/lod.json b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/presentation/lod.json
new file mode 100644
index 0000000000..d1eb0f5fcf
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/presentation/lod.json
@@ -0,0 +1,94 @@
+{
+ "models": {
+ "franka_emika_panda": {
+ "25k": {
+ "files": {
+ "franka_emika_panda/assets/link0_0.obj": "0e6958fd2f69a9c6ec82e59fb3a39689810bcd69180dd865866359b69d0204ba",
+ "franka_emika_panda/assets/link0_1.obj": "5ca2ade591ead9e9d3046468f6d861631b8fcd0434cb6dfbfbc7eb09cbc11c81",
+ "franka_emika_panda/assets/link0_10.obj": "c8daf1be7a5d3d89aa3f0976c6c43afa9d5841697c0ed91edcad8d60a75b1e60",
+ "franka_emika_panda/assets/link0_11.obj": "0ced2c2a707b13a391306d04f9ad9d4318caf2ce924cb242321a1cd9773c3753",
+ "franka_emika_panda/assets/link0_2.obj": "d7d11c50dee70b7d9149805576c85e026d3f4df2df1b824891451f72bce20e1d",
+ "franka_emika_panda/assets/link0_3.obj": "35bad1cdde8a1e6cee4522b22aa4e46d6a06a54bccc3bc966691f96cde0953fa",
+ "franka_emika_panda/assets/link0_4.obj": "ee1d81feeb6591b8a0b4d0e175f7541ffa40725aa6b97d048d289dc5c5517913",
+ "franka_emika_panda/assets/link0_5.obj": "17438838e57292cdc0c18f5417c020ed3290323e50ca4c1b58b07065961bc95c",
+ "franka_emika_panda/assets/link0_7.obj": "2ccf52f5c8b6155fd2764435028b59ad64d23820bb080d9079ba52b939ccee36",
+ "franka_emika_panda/assets/link0_8.obj": "7f895de6ec3ebdd93f5af7c446616da908cf423131dc2c24da50146b32718baa",
+ "franka_emika_panda/assets/link0_9.obj": "8ef4ff7f0676b60a8edf54380b4b696bae3b5a5202e38f7ca64bb3a2f6e0496b",
+ "franka_emika_panda/assets/link1.obj": "89a7387d65a311e92cd39dc65c0f5a7d00a5d342bf670613b87b09da016a82c8",
+ "franka_emika_panda/assets/link2.obj": "b66faa46466a258f1f36250bf4530424eb37b47ae1fcc4dbb114b37a499287a2",
+ "franka_emika_panda/assets/link3_0.obj": "b6124b7a17d85ce218ed739ae1792c4762718e43f135e3633008bc753aebe20f",
+ "franka_emika_panda/assets/link3_1.obj": "6d05236a2bb84117328a7d421f41058ddd9969d5317a5c5a5375da311dc17f30",
+ "franka_emika_panda/assets/link3_2.obj": "4d3f6753c0aa9469486317d5eee5e2ac8b1615b705a78e35335a298a4644cd03",
+ "franka_emika_panda/assets/link3_3.obj": "5afeb0a5722704920fe3930fd56fa30dde7faf1932377e9b5fbaafbf1b6f5030",
+ "franka_emika_panda/assets/link4_0.obj": "ef4c8095c339dbf8e10e727f5361598220833689cd79ac59d10508423934fc93",
+ "franka_emika_panda/assets/link4_1.obj": "7050225b33d23afafac7f597b250e59c7353e3193ecb1098c3708f2f4d561e52",
+ "franka_emika_panda/assets/link4_2.obj": "e084c51cdddb612869d45ae94e31b19a1d011f9c182faff07b1f953ca9e7e6c1",
+ "franka_emika_panda/assets/link4_3.obj": "c5ef5783e41d161269018a4b16446db8e400eb7780527a161e62bf7ed2289e46",
+ "franka_emika_panda/assets/link5_0.obj": "f64a7b7f023bdcaf8d8fac082145d365751c69e9b6bda942c5de3dd3dc8806a4",
+ "franka_emika_panda/assets/link5_1.obj": "8bfc7df033b58c4e7b5f1080dc05da81699ffc237a91b8da9e2a6119cb79b494",
+ "franka_emika_panda/assets/link5_2.obj": "437ee6f13c4d98db88ad75d832aa6bdcb5453db256d5691be1931c4acd935bf9",
+ "franka_emika_panda/assets/link6_0.obj": "9c87e9689cfeacb6b1d2ce305cddcbad463f420584dbd220b2080e3c636b3762",
+ "franka_emika_panda/assets/link6_1.obj": "6445e25a8759385c43f0d5285d50f77eb08f34afe6fbb2d07ddf352c8b3d13b5",
+ "franka_emika_panda/assets/link6_10.obj": "05ec79c4defd0548107dc58f2d7ab26b010a2ca7b7878ed0b282a3540679f620",
+ "franka_emika_panda/assets/link6_11.obj": "96dc648b3382a4b3688d801bb94eb3b6cb1d6e64367e8cae29d2a7c3178324c3",
+ "franka_emika_panda/assets/link6_12.obj": "7b2bea2a736a63661cdae29ef30740a26d08ce43c4a787788907d44d2853413e",
+ "franka_emika_panda/assets/link6_13.obj": "5f6745688f8c3a4172af1689d6a52f320264104414853e72c5a022bdaac77026",
+ "franka_emika_panda/assets/link6_14.obj": "569977e1c13942d0aa84ba42188f5256de447266e1db2e0f46159482791acbc5",
+ "franka_emika_panda/assets/link6_15.obj": "3d201820c51a032ee1e12232b5cb709b20062b8a991d6446a225f6aa8471e486",
+ "franka_emika_panda/assets/link6_16.obj": "ad4f0e691598a70ef3de25b8840d8893b48150dcbb6012a7295cbe706e8de05c",
+ "franka_emika_panda/assets/link6_2.obj": "b6bc873ba1bcbf54af2667d197722f681d82f591173cecb75cad0a67e2b47e3d",
+ "franka_emika_panda/assets/link6_3.obj": "9da48c192b317dde105666470c4898e0ca6ae54cd57f386867de76f3e75f8116",
+ "franka_emika_panda/assets/link6_4.obj": "ed80f9d8e9da1c3252cc375704f80bec5b8263198178db9a4fca72587d9525d2",
+ "franka_emika_panda/assets/link6_5.obj": "68eba154d3031354e6682dea960993b668ce3229fde73d1aaf9456e2978be95e",
+ "franka_emika_panda/assets/link6_6.obj": "c8316be35257df937810664619b67b45820b60dcbd0b219fe7e540bc12e81156",
+ "franka_emika_panda/assets/link6_7.obj": "6bc1c0ce40b6fbf22d37000ffe95255c044a168cd5241a5c56e86bdf5c171f92",
+ "franka_emika_panda/assets/link6_8.obj": "d821b8c3875eca9ad19aa6112a86eb2a0cc0d75ad07349d004c449e85eb00f14",
+ "franka_emika_panda/assets/link6_9.obj": "bd9beb29cdef7b5c6014529f65520245fa83bd8b84c0b57288a9235da2fc94c5",
+ "franka_emika_panda/assets/link7_0.obj": "16a21aac2faf5c012b1b2b2aac5c6170f78caba505a0885fed7c14b3a672899b",
+ "franka_emika_panda/assets/link7_1.obj": "7f5391b3b7104189b38c65d10a8fe213ef6d6443dc05ea7c2c6d7b31fb483ff9",
+ "franka_emika_panda/assets/link7_2.obj": "16e8c340cc6f3c9d2f15760f58892e15d0e668b09b81088a39b3a77929de0721",
+ "franka_emika_panda/assets/link7_3.obj": "47795dd7fc1d3d253313b7b39f94e06036169b3380b2d7486fb51ce53916e04d",
+ "franka_emika_panda/assets/link7_4.obj": "8c3614d6cf07660c5cbfa12edae41bd22a49d4bec9f9c4a2139a00607d1e8f63",
+ "franka_emika_panda/assets/link7_5.obj": "23e7ba2a16fca00e48b6e397d6da49b25af4e5327c6b186217aedcc808f0892f",
+ "franka_emika_panda/assets/link7_6.obj": "40e6a822ade171dcb2ecc6d5d510c9b878505e2af3b497f7e772605fdf2b9c2b",
+ "franka_emika_panda/assets/link7_7.obj": "d70d61a09b7a605a47caf5d5b7225f3d5cce1af1c849b262ab9ea0242c50464b",
+ "franka_emika_panda/panda_nohand.xml": "e7090a5e2384b18a223ef532d98bf914f7f9a6b74dc8bc9f74c8291201074071"
+ },
+ "source": "menagerie@f054586a8e90465d49ee5be15335c4a0c7f57caf",
+ "source_triangles": 126562,
+ "target_triangles": 25000,
+ "triangles": 25568
+ }
+ },
+ "kuka_iiwa_14": {
+ "25k": {
+ "files": {
+ "kuka_iiwa_14/assets/band.obj": "40784c36ec38f8ff2fa804e3c242656b9ed3ae41a33785af33c917de1bbd566f",
+ "kuka_iiwa_14/assets/kuka.obj": "b79762633220dcfae4b45b40d2880a83128e373003f794f0d9a19f4989c92ec7",
+ "kuka_iiwa_14/assets/link_0.obj": "fc2590b0e7ce20e1fa9a5ab4f48259908508c6ad4aeebc4d2ef13e5d22ba23e5",
+ "kuka_iiwa_14/assets/link_1.obj": "81f65e2f348ac6bfdd4968a1440406c9abc9ca6b51de7a404024a08ef46127eb",
+ "kuka_iiwa_14/assets/link_2_grey.obj": "07bc12ae4e6edc159e4123e9a5571a08d03211de8afa503c9cfb74dff51208b2",
+ "kuka_iiwa_14/assets/link_2_orange.obj": "4b151e4dc5689342ad6be614c9114ab3c0668a1aaba25eafc78c8e2e9f7a01f8",
+ "kuka_iiwa_14/assets/link_3.obj": "77be645b049e35bfb1c2bf05d610c95044b39dc17209b4d5e63ded1e4b87832d",
+ "kuka_iiwa_14/assets/link_4_grey.obj": "79f6693b2031e1f24069c56546490d7d1ff6907b3871bd049bba187d4ff0786a",
+ "kuka_iiwa_14/assets/link_4_orange.obj": "2e0613541153884f9a3cc2de654492d7aa563368c6fae335c82109b5def79f4d",
+ "kuka_iiwa_14/assets/link_5.obj": "2f0ee7aeb51dfa86f98954f8673fafdb8c63dfa37618d4e0e76c7db037af267c",
+ "kuka_iiwa_14/assets/link_6_grey.obj": "4eb7481b31d88612b6cc791d8390c3145e367ca87537a2f6763e3c2c2b01dd13",
+ "kuka_iiwa_14/assets/link_6_orange.obj": "450b41e8691e1ccfa427da45d65d4f95c40cd388433fc753c1ab86087d178cdc",
+ "kuka_iiwa_14/assets/link_7.obj": "c35ef794a848268745f3d1e283dbcdb0bf117373110364b62c8405af4275eac1",
+ "kuka_iiwa_14/iiwa14.xml": "ee7e6d796a9f8642de6097f95077281d15f43678dc5285beafeda99b84cf9ef5"
+ },
+ "source": "menagerie@f054586a8e90465d49ee5be15335c4a0c7f57caf",
+ "source_triangles": 73989,
+ "target_triangles": 25000,
+ "triangles": 25141
+ }
+ }
+ },
+ "name": "lod",
+ "note": "Levels of detail of the presentation models (players' images, renderer rule 6): a model's visual meshes decimated to a triangle budget, so that a sport can draw its players' images with fine meshes on the CPU at a small cost and bundle them into its simulator directory (a few MB instead of 30).",
+ "tools": {
+ "fast-simplification": "0.2.0",
+ "trimesh": "5.1.1"
+ }
+}
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/presentation/menagerie.json b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/presentation/menagerie.json
new file mode 100644
index 0000000000..f20f9bb91f
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/presentation/menagerie.json
@@ -0,0 +1,135 @@
+{
+ "name": "menagerie",
+ "title": "MuJoCo Menagerie",
+ "source": "https://github.com/google-deepmind/mujoco_menagerie",
+ "commit": "f054586a8e90465d49ee5be15335c4a0c7f57caf",
+ "url": "https://raw.githubusercontent.com/google-deepmind/mujoco_menagerie/{commit}/{path}",
+ "note": "Generated from the pinned commit: per model its MJCF description and the visual meshes of its visual geoms (no collision meshes, textures or scripts). Untrusted data: read only.",
+ "models": {
+ "franka_emika_panda": {
+ "title": "Franka Emika Panda (no hand)",
+ "path": "franka_emika_panda/",
+ "xml": "franka_emika_panda/panda_nohand.xml",
+ "license": "Apache-2.0",
+ "license_file": "LICENSE.franka_emika_panda",
+ "copyright": "MuJoCo Menagerie authors, derived from Franka Emika's franka_ros description",
+ "files": {
+ "franka_emika_panda/assets/link0_0.obj": "6b9f41a4c203540daaeb7a33cc3d0d6c6a32dc8bba187074eeaf97b3e36b3f9c",
+ "franka_emika_panda/assets/link0_1.obj": "57673d2ee2a9db2e10c8986ae57c56a7c39c012b60fd26d7d8549553b664a5ed",
+ "franka_emika_panda/assets/link0_10.obj": "c9198b9d8534d628d097b0f2b239bb30343353182df098ce0d9db6bc13326848",
+ "franka_emika_panda/assets/link0_11.obj": "f0adec78d6677b7799d25121981270e8bfe119b5c18d08a91ee37a54ad75f65c",
+ "franka_emika_panda/assets/link0_2.obj": "1ca435a2a87a9608a146a47955724d43dd7ce10fc3dd3018800aa98f8ba86e05",
+ "franka_emika_panda/assets/link0_3.obj": "3e9c6334d2b3b47944af3458ee5f20519abc20fe7ee23063bb53405ccab28046",
+ "franka_emika_panda/assets/link0_4.obj": "215d25789704936120f119c0bc1cc7f68516dd3f8f1df61457b71acac3873f26",
+ "franka_emika_panda/assets/link0_5.obj": "9361b104e93743045107aa5b15fb1a0835ba9c1f355aae71f56403cf6a9c33f6",
+ "franka_emika_panda/assets/link0_7.obj": "2dc0b8ebbbc80e4c065d71e195adbc384f673438641fac82b07b801b4d2837cb",
+ "franka_emika_panda/assets/link0_8.obj": "3b8c436999db5586b8eb47bed2b0aa7de6993868b2681b4c04246eeac42fdb7a",
+ "franka_emika_panda/assets/link0_9.obj": "45178f97d2b5da6bce11f610212c4ef7d08c73db33a4fc38e1b7f66b93d023f5",
+ "franka_emika_panda/assets/link1.obj": "51091e776b16babdbe2f3849b5c041f921d1f11dd94ac19a0f1c81abf496fbae",
+ "franka_emika_panda/assets/link2.obj": "5c9f8e715de52c3eb71b475de35993b3b96081e02abea9f28c414768877fc59b",
+ "franka_emika_panda/assets/link3_0.obj": "ce2da87f51708e11b189249d41401065dabe89a06e251185a06cef4d5ff27178",
+ "franka_emika_panda/assets/link3_1.obj": "2880b7753a7173f38fa87ee21da4dfc7fa7be46fbe07bac5aef9e128513cb118",
+ "franka_emika_panda/assets/link3_2.obj": "670cff81ae84693769ca4ae658c154cf909d81167e7c8d22b70ea977f2504efa",
+ "franka_emika_panda/assets/link3_3.obj": "30ede0c812efd0e0b767d134a4eae0b84e0fa407bb6325a5a555e0569b3a3ffd",
+ "franka_emika_panda/assets/link4_0.obj": "443bf6d178177cf347951ecf107ccd10ca444e605e375b67304579e5f948806f",
+ "franka_emika_panda/assets/link4_1.obj": "ca935ec7cc8b3f0e86aa079c76b0b3bf593b1e9830bab0fa7131ac51577c74f0",
+ "franka_emika_panda/assets/link4_2.obj": "c89caf26d379c35bb9e191ee2d91d09ab29ecc792b48d8bc10b39e5b38222175",
+ "franka_emika_panda/assets/link4_3.obj": "1495d17f45bdb230cf58b0beef9da4e8c9cfe76a3d2d38da89017efe5e093136",
+ "franka_emika_panda/assets/link5_0.obj": "a3238b8f2af0f2eb66d9fe63dc5d41ac52d5d38507241b5ed10e3cb019ab3e71",
+ "franka_emika_panda/assets/link5_1.obj": "9d994bbf83ec241e301b5197a6846da13f2a4a0582edb2c0f76962c5549649d6",
+ "franka_emika_panda/assets/link5_2.obj": "83b4ffe9f772cd7fe182e98640650eebc899aaf01842656574b0416c90dd40a4",
+ "franka_emika_panda/assets/link6_0.obj": "0504c70ebf1b284ee8faae7dcb896b8830bc672a6552015dd5dbd121fa031fb9",
+ "franka_emika_panda/assets/link6_1.obj": "45f7ca77695198b6d86ec2417ad4e42e6275044f0f96266699ee8e1057757ac1",
+ "franka_emika_panda/assets/link6_10.obj": "365f26c21d10332cab8d8704645cb46930c30b3085956f2d097498c793f24db4",
+ "franka_emika_panda/assets/link6_11.obj": "8ae61e08b3ad064f25bbf03b22e59cc15d65883b5a7ce92711aff29df2493901",
+ "franka_emika_panda/assets/link6_12.obj": "f28d1bfd62b0244ffd19fb35fe9edefdf583d3c9167db944e87185d919e1d021",
+ "franka_emika_panda/assets/link6_13.obj": "0a55fa92dccb261d07200e6565fca4c850fd17f0c1ecf38821c0b97d51796c7d",
+ "franka_emika_panda/assets/link6_14.obj": "750ae3ee4781e62e3a045c662195247b03f6642b05aa93104f08258e5f6eba26",
+ "franka_emika_panda/assets/link6_15.obj": "5999c1c2497a004a7c4bbe034cdf13744f839d85ae7a11b1bc386c48a3e642e6",
+ "franka_emika_panda/assets/link6_16.obj": "551d7a8b37c53e7a152d008b4e36992e5b5abe74a4be18b57ee6319c27def09f",
+ "franka_emika_panda/assets/link6_2.obj": "e54eee4d8232947ee8af65afd5a067e09dac2da6e7e585cb1dccb65496457da0",
+ "franka_emika_panda/assets/link6_3.obj": "d4f6a25ef32fa1fa4734146981994ee760232cb077c80fea6487d78a077c7f27",
+ "franka_emika_panda/assets/link6_4.obj": "be353480fe71d46f7a96f0a3cbb7e112caaf8d88368826f321a36a253c8749b2",
+ "franka_emika_panda/assets/link6_5.obj": "7c87664623c3e1a6cb330db273227a69626dc5e53b4caff1d4ee7911eb3340c6",
+ "franka_emika_panda/assets/link6_6.obj": "8fbc031e0d07b795ebf99115c75223141caaba317cab569159f3d477a7821681",
+ "franka_emika_panda/assets/link6_7.obj": "7dc5ebb799fe281aab27d6e84e7a4efa0a8e42da2369ec83de3ea3f206f62d73",
+ "franka_emika_panda/assets/link6_8.obj": "e3f77381817a341030f9dcc4c4aa7c559f80411b453fd87eb0fefecca82151bf",
+ "franka_emika_panda/assets/link6_9.obj": "25a56ea9b02a03b6cb5a81f31c54f54d0185e1a0b3937c37e4289d896e50215a",
+ "franka_emika_panda/assets/link7_0.obj": "04586b0bde011715cfc22072ac72fe0717eb4d4817bcf665987ce6cd88eb2b93",
+ "franka_emika_panda/assets/link7_1.obj": "c3f72289f394c9d6749a4a327fb11f05b203c37c95032c92f28019b40ebe7e00",
+ "franka_emika_panda/assets/link7_2.obj": "d2faecedb304d0989040d082410378dc949dbbda23bd18c05134f08aae984db5",
+ "franka_emika_panda/assets/link7_3.obj": "b62d87c4d4bdb7b281ed341d347c39dad0e50bf36aed8ac11d050073701d5f70",
+ "franka_emika_panda/assets/link7_4.obj": "cb78ccb61fd4ad6c7bff4c4d2e6cb41e1964a5a3e1a28e67c0c6202371cfc018",
+ "franka_emika_panda/assets/link7_5.obj": "099071d3090b51471ba52f4f90814fd3089f4975d196e4d488117073d0bfe491",
+ "franka_emika_panda/assets/link7_6.obj": "99469e2d95ab74ce0292f2f16954c87a8a7dc16652e62e970fe37c94330a81bb",
+ "franka_emika_panda/assets/link7_7.obj": "426c3db8a19373f3dc73d4bec672e948121b2914c10e2e7b9c7ea80643a19e54",
+ "franka_emika_panda/panda_nohand.xml": "e7090a5e2384b18a223ef532d98bf914f7f9a6b74dc8bc9f74c8291201074071"
+ },
+ "bytes": 32259617,
+ "visual_geoms": 49
+ },
+ "kuka_iiwa_14": {
+ "title": "KUKA LBR iiwa 14",
+ "path": "kuka_iiwa_14/",
+ "xml": "kuka_iiwa_14/iiwa14.xml",
+ "license": "BSD-3-Clause",
+ "license_file": "LICENSE.kuka_iiwa_14",
+ "copyright": "MuJoCo Menagerie authors, derived from the Drake developers' iiwa14 description",
+ "files": {
+ "kuka_iiwa_14/assets/band.obj": "02cf16a93140489da3b05ce6bb30c5498bedaa5e5a77e56850ddbedb8d1ed23e",
+ "kuka_iiwa_14/assets/kuka.obj": "204a82d597d450f2a207731f8e3c17089f2de5a54c0d61feac454e96e325b834",
+ "kuka_iiwa_14/assets/link_0.obj": "6b607f6b5a601874863897ebfbb9821eb0c831c3115bca8350bf7856db6aaeee",
+ "kuka_iiwa_14/assets/link_1.obj": "47a82247b647639c3e1f384ce5b980d374323ca737d6ebc87447667a71981798",
+ "kuka_iiwa_14/assets/link_2_grey.obj": "842b8c3a9148b2fdf9c57ddfd80b595f8251792f94b71276dc9ce9a16674ba1a",
+ "kuka_iiwa_14/assets/link_2_orange.obj": "0d2d8829d89aa888ee04b0d97bed5f215fa0d9fd03d0d4cee2b2e0c8dd3c0124",
+ "kuka_iiwa_14/assets/link_3.obj": "b02d157e8090d82bfb78e7fd4dcd351033e0a5d7bb1937da01e66e7ff91a03a8",
+ "kuka_iiwa_14/assets/link_4_grey.obj": "e4555ea6954fffa40174baee25e6dd1b9efcc3eaf830b6e91d13e2ddc10b414a",
+ "kuka_iiwa_14/assets/link_4_orange.obj": "ef4cf2102e9df98636ff03b82d49d914a6e730b299b0a982d64947f038136cb7",
+ "kuka_iiwa_14/assets/link_5.obj": "f0eef60cddf06e46bd943abcc49ada87510f095f2840bc9c117ed7a2b1a6a787",
+ "kuka_iiwa_14/assets/link_6_grey.obj": "5b5f9883d4fc181c7aa06cb2037debfa4ca857fa0c3a5d55f8fd3e34d38c3100",
+ "kuka_iiwa_14/assets/link_6_orange.obj": "54aa0141e7f48497302f45daf074fd5c69320c620618c12fa76e8841c2a8a9fc",
+ "kuka_iiwa_14/assets/link_7.obj": "7307d0c852715ea234e575a0617ea2d8faf053469e7b823ac0c7c6c4dff36dad",
+ "kuka_iiwa_14/iiwa14.xml": "ee7e6d796a9f8642de6097f95077281d15f43678dc5285beafeda99b84cf9ef5"
+ },
+ "bytes": 5015391,
+ "visual_geoms": 15
+ },
+ "booster_t1": {
+ "title": "Booster T1",
+ "path": "booster_t1/",
+ "xml": "booster_t1/t1.xml",
+ "license": "Apache-2.0",
+ "license_file": "LICENSE.booster_t1",
+ "copyright": "MuJoCo Menagerie authors, derived from Booster Robotics' booster_gym T1 description",
+ "files": {
+ "booster_t1/assets/AL1.stl": "43f5d268152b3c169d34731545ddfa2a510a7e16f209a2a80f8ba9ae0e1a40aa",
+ "booster_t1/assets/AL2.stl": "4bca60adb29c73f701350abd23e8a8d660dc61e87c5163a80157650dd3ad88c3",
+ "booster_t1/assets/AL3.stl": "bfdf5611dfe90f8e02b07b037c36a244f4ce7184b45113371ef46e624fb30854",
+ "booster_t1/assets/AR1.stl": "6dbbd3dab4486600747be9d0e7f8523d67bf00d24d0dc9c23db1766c4d808fcf",
+ "booster_t1/assets/AR2.stl": "0499136785fe1bc0289d9e503e1e0ea48f5a63420a2e45b0fcd9e6b3bcf8f999",
+ "booster_t1/assets/AR3.stl": "92330bd8286fe420fb76949ee4c5d5bdec2e6bb30426acdc4d6fae9257464631",
+ "booster_t1/assets/Ankle_Cross_Left.stl": "e6ec38741838475834c147f2ad18196c0254741e602c2b676f888fd12b5d7981",
+ "booster_t1/assets/Ankle_Cross_Right.stl": "b15d91f0f2470fc4d5634db906a3d7efaf1f700302e6671824494da8faf50308",
+ "booster_t1/assets/H1.stl": "527a2e426db4e3d476a195754764b7f9565a950b809a34e47618f177b139c3f2",
+ "booster_t1/assets/H2.stl": "9cbf4fe83a721c809de65b1f0d0a379314f4523f7e2f8af7f0edc27c2ce385aa",
+ "booster_t1/assets/Hip_Pitch_Left.stl": "7bcb8be569aeb5379cb75a0827d682bc1d73a52a7f515d3aeffece43842c33c9",
+ "booster_t1/assets/Hip_Pitch_Right.stl": "054d579c3c6ccc1f97aaf1461d802dec748ce1bf26c6fdd289283a2d0dbb2032",
+ "booster_t1/assets/Hip_Roll_Left.stl": "72dbd65bdb4e87444c8e538474f631d63bf8c0960922517456b8cf2be9e1d0f0",
+ "booster_t1/assets/Hip_Roll_Right.stl": "d715a7649ea4bf20d7ee17b3a57bae31732e467b9da1053fee2242c90f50980f",
+ "booster_t1/assets/Hip_Yaw_Left.stl": "d588e0467094811e74ae1962fcb0eb669f9b50b74022e96a738bdc8e807e03a7",
+ "booster_t1/assets/Hip_Yaw_Right.stl": "5135f2fd5707364583d283e2fb21845054f3548c224f48e1f0a3d78ed3453497",
+ "booster_t1/assets/Shank_Left.stl": "6ae8dd7f88cb70a4a3cb3972cad4035a76f1604fd73ea66e285da553b3703c40",
+ "booster_t1/assets/Shank_Right.stl": "dc66a8a0e2e31e413884a053e427d9b5007bef4508986587916a638a8a448599",
+ "booster_t1/assets/Trunk.stl": "39d9610b23ef8ac7ea4343231a499f9c485903bede62df9729a2cd1254fede8f",
+ "booster_t1/assets/Waist.stl": "2fe0a9ccfc284beca402e554db38e83022592192afa00f02db13cb374ffe9fbc",
+ "booster_t1/assets/left_foot_link.stl": "82d653e30c0ae2e588c3c539266c9a1fee20e711448e13598f25384c7dc562ca",
+ "booster_t1/assets/left_hand_link.stl": "34df992aed438446481cfa20e78327810cd5cc5ecbb4a6f32ba2bf625462f53d",
+ "booster_t1/assets/right_foot_link.stl": "78440aa4bab7c397b8e507431b44b814e4cb89db0d03455f83ae54e3157cf15b",
+ "booster_t1/assets/right_hand_link.stl": "c5a73e493e17db7611a81785f80c01167f51018271b4042f72fa8d2351d8b0eb",
+ "booster_t1/t1.xml": "78af3f7910e4413894863b6427f44a7daf49e5eb47628e6fe2db775219e346b9"
+ },
+ "bytes": 8445726,
+ "visual_geoms": 24
+ }
+ }
+}
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/scene_check.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/scene_check.py
new file mode 100644
index 0000000000..5713371f35
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/renderers/scene_check.py
@@ -0,0 +1,164 @@
+"""Same scene (renderer rule 2): a non-default renderer draws the default renderer's scene. The geometry, kinematics,
+cameras and the colour a viewer sees of every untextured geom must be identical; a re-textured surface keeps its mean
+colour within TEXTURE_TOL. Only lights, materials (specular, shininess, reflectance, textures with the same mean
+colour) and image quality may differ. The same rule as scripts/olympiad/showcase/looks.same_scene, without the
+sport-specific decor exception (decor is presentation-only and never part of a renderer's player picture).
+
+Same kinematics (renderer rule 6): a presentation scene (renderers/presentation.py, spectators only) may differ from
+the match scene in appearance and by added visual-only geoms, never in bodies, joints, frames, inertias or cameras;
+same_kinematics() checks it before a renderer draws one, pose_diff() compares body poses over recorded states."""
+from __future__ import annotations
+
+import numpy as np
+
+SAME = ("nq", "nv", "nbody", "njnt", "ngeom", "nmesh", "ncam", "nmocap",
+ "body_parentid", "body_pos", "body_quat", "body_mass", "jnt_type", "jnt_qposadr", "jnt_pos", "jnt_axis",
+ "geom_type", "geom_bodyid", "geom_size", "geom_pos", "geom_quat", "geom_group", "geom_dataid",
+ "mesh_vertnum", "mesh_vert", "mesh_face",
+ "cam_mode", "cam_bodyid", "cam_pos", "cam_quat", "cam_fovy")
+DEFAULT_RGBA = (0.5, 0.5, 0.5, 1.0)
+TEXTURE_TOL = 0.02
+MESH = 7 # mjtGeom.mjGEOM_MESH
+
+
+def effective_rgba(m, g):
+ rgba = m.geom_rgba[g]
+ if m.geom_matid[g] >= 0 and np.allclose(rgba, DEFAULT_RGBA):
+ return m.mat_rgba[m.geom_matid[g]]
+ return rgba
+
+
+def _texid(m, g):
+ import mujoco as mj
+ mid = m.geom_matid[g]
+ return int(m.mat_texid[mid, mj.mjtTextureRole.mjTEXROLE_RGB]) if mid >= 0 else -1
+
+
+def _mean_colour(m, g):
+ """Mean drawn colour of a geom (texture mean x material/geom colour), 0..1 RGB."""
+ rgba = np.asarray(effective_rgba(m, g)[:3], float)
+ t = _texid(m, g)
+ if t < 0:
+ return rgba
+ h, w, c = m.tex_height[t], m.tex_width[t], m.tex_nchannel[t]
+ px = m.tex_data[m.tex_adr[t]:m.tex_adr[t] + h * w * c].reshape(-1, c)[:, :3]
+ return rgba * (px.mean(0) / 255.0)
+
+
+SPARE = "_ro_cam" # the renderers' own spare cameras (renderers/mujoco), posed per frame: not scene cameras
+
+
+def _scene_cams(m):
+ return [i for i in range(m.ncam) if not (m.camera(i).name or "").startswith(SPARE)]
+
+
+def same_scene(m0, m1) -> list:
+ """Differences between the default model m0 and the renderer's model m1 (empty list = the same scene)."""
+ bad = []
+ c0, c1 = _scene_cams(m0), _scene_cams(m1)
+ for name in SAME:
+ a, b = np.asarray(getattr(m0, name)), np.asarray(getattr(m1, name))
+ if name.startswith("cam_"):
+ a, b = a[c0], b[c1]
+ elif name == "ncam":
+ a, b = np.asarray(len(c0)), np.asarray(len(c1))
+ if np.shape(a) != np.shape(b) or not np.array_equal(a, b):
+ bad.append(name)
+ if bad:
+ return bad
+ if m0.vis.global_.fovy != m1.vis.global_.fovy:
+ bad.append("vis.global.fovy")
+ for g in range(m0.ngeom):
+ t0, t1 = _texid(m0, g) >= 0, _texid(m1, g) >= 0
+ if not t0 and not t1:
+ if not np.allclose(effective_rgba(m0, g), effective_rgba(m1, g)):
+ bad.append(f"colour of geom {m0.geom(g).name or g}")
+ elif float(np.abs(_mean_colour(m0, g) - _mean_colour(m1, g)).max()) > TEXTURE_TOL:
+ bad.append(f"mean colour of textured geom {m0.geom(g).name or g}")
+ return bad
+
+
+# ------------------------------------------------------------------------------------- presentation scenes (spectators)
+VISUAL_PREFIX = "_vis:" # the name prefix of a presentation scene's added geoms (renderers/presentation.py)
+KINEMATICS = ("nq", "nv", "nu", "nbody", "njnt", "nmocap", "nsite", "qpos0",
+ "body_parentid", "body_rootid", "body_weldid", "body_mocapid", "body_jntnum", "body_jntadr",
+ "body_dofnum", "body_dofadr", "body_pos", "body_quat", "body_ipos", "body_iquat", "body_mass",
+ "body_inertia", "jnt_type", "jnt_bodyid", "jnt_qposadr", "jnt_dofadr", "jnt_pos", "jnt_axis",
+ "jnt_range", "dof_bodyid", "dof_jntid", "dof_armature", "dof_damping", "actuator_trnid",
+ "site_bodyid", "site_pos", "site_quat", "opt.timestep", "opt.gravity")
+MATCH_GEOM = ("geom_type", "geom_bodyid", "geom_size", "geom_pos", "geom_quat", "geom_contype", "geom_conaffinity",
+ "geom_condim", "geom_priority", "geom_friction", "geom_solref", "geom_solimp", "geom_margin", "geom_gap")
+CAMERA = ("cam_mode", "cam_bodyid", "cam_pos", "cam_quat", "cam_fovy")
+
+
+def _arr(m, name):
+ o = m
+ for part in name.split("."):
+ o = getattr(o, part)
+ return np.asarray(o)
+
+
+def visual_geoms(m) -> list:
+ return [g for g in range(m.ngeom) if (m.geom(g).name or "").startswith(VISUAL_PREFIX)]
+
+
+def _mesh_verts(m, g):
+ i = m.geom_dataid[g]
+ return m.mesh_vert[m.mesh_vertadr[i]:m.mesh_vertadr[i] + m.mesh_vertnum[i]]
+
+
+def same_kinematics(m0, m1) -> list:
+ """Differences between the match model m0 and a presentation model m1 (empty list = the same kinematics):
+ every body, joint, dof, frame, inertia, site, mocap body and scene camera is identical; m0's geoms are all in m1,
+ in the same order, with the same geometry, pose and contact properties (only their appearance may change:
+ group, colour, material, e.g. a collision mesh moved to the hidden group 3); every other geom of m1 is an added
+ visual geom (name prefix VISUAL_PREFIX) that never collides (contype = conaffinity = 0) and is drawn (group
+ 0..2). Body masses and inertias being equal, the added geoms carry no mass. So the same qpos puts every body at
+ the same pose in both models: a presentation scene changes only what a spectator sees."""
+ bad = []
+ for name in KINEMATICS:
+ a, b = _arr(m0, name), _arr(m1, name)
+ if a.shape != b.shape or not np.array_equal(a, b):
+ bad.append(name)
+ c0, c1 = _scene_cams(m0), _scene_cams(m1)
+ if len(c0) != len(c1):
+ bad.append("ncam")
+ else:
+ bad += [n for n in CAMERA if not np.array_equal(_arr(m0, n)[c0], _arr(m1, n)[c1])]
+ if bad:
+ return bad
+ extra = visual_geoms(m1)
+ keep = [g for g in range(m1.ngeom) if g not in set(extra)]
+ if len(keep) != m0.ngeom:
+ return [f"{len(keep)} match geoms in the presentation scene for {m0.ngeom}"]
+ bad += [n for n in MATCH_GEOM if not np.array_equal(_arr(m0, n), _arr(m1, n)[keep])]
+ for g0, g1 in enumerate(keep):
+ if (m0.geom(g0).name or "") != (m1.geom(g1).name or ""):
+ bad.append(f"name of geom {g0}")
+ elif m0.geom_dataid[g0] >= 0 and m0.geom_type[g0] == MESH and not np.array_equal(_mesh_verts(m0, g0),
+ _mesh_verts(m1, g1)):
+ bad.append(f"mesh of geom {m0.geom(g0).name or g0}")
+ for g in extra:
+ if m1.geom_contype[g] or m1.geom_conaffinity[g] or not 0 <= m1.geom_group[g] <= 2:
+ bad.append(f"added geom {m1.geom(g).name} collides or is not drawn")
+ return bad
+
+
+def pose_diff(m0, m1, states) -> float:
+ """The largest difference of any body's (and site's) world position or orientation between the two models over
+ the given states ({"qpos", optional "mocap_pos", "mocap_quat"}); 0.0 = bit-identical poses."""
+ import mujoco as mj
+ d0, d1 = mj.MjData(m0), mj.MjData(m1)
+ worst = 0.0
+ for st in states:
+ for m, d in ((m0, d0), (m1, d1)):
+ d.qpos[:] = np.asarray(st["qpos"], float)
+ if m.nmocap and "mocap_pos" in st:
+ d.mocap_pos[:] = np.asarray(st["mocap_pos"], float).reshape(m.nmocap, 3)
+ if m.nmocap and "mocap_quat" in st:
+ d.mocap_quat[:] = np.asarray(st["mocap_quat"], float).reshape(m.nmocap, 4)
+ mj.mj_kinematics(m, d)
+ for a, b in ((d0.xpos, d1.xpos), (d0.xquat, d1.xquat), (d0.xmat, d1.xmat), (d0.site_xpos, d1.site_xpos)):
+ if np.asarray(a).size:
+ worst = max(worst, float(np.abs(np.asarray(a) - np.asarray(b)).max()))
+ return worst
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/server.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/server.py
new file mode 100644
index 0000000000..5eb03f3410
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/server.py
@@ -0,0 +1,30 @@
+"""eai-standard/2.3 sim service for RoboOlympics: rcb_realtime.py (the sidecar's entry point, `python /srv/rcb_realtime.py`)
+imports this module and calls build(). The sport and its frozen instance come from environment/docker-compose.yaml:
+ RO_PLUGIN the sport's plugin (/srv/sport/plugin.py)
+ RO_FORMAT the sport's format (match: one player against the scripted opponent)
+ RO_SEED the frozen instance's seed (serves, the opponent's returns, the execution scatter)
+ RO_LEVEL the scripted opponent's level
+ RO_ACTION_LEVEL the action level (high: strokes the service plans; low: joint or mallet targets)
+ RO_TASK_TEXT, RO_EPISODE_TEXT one sentence each for /spec
+ RCB_SLOWDOWN the slowdown S (badminton's stroke lead depends on it); RCB_DATA, RCB_RESET_BUDGET,
+ RCB_WALL_CLOCK_S: the service's own (rcb_service.main)
+"""
+from __future__ import annotations
+
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from core.sport import MatchConfig # noqa: E402
+from rcb_olympics import Olympics # noqa: E402
+
+
+def build() -> Olympics:
+ env = os.environ.get
+ plugin = env("RO_PLUGIN", "/srv/sport/plugin.py")
+ sport = os.path.basename(os.path.dirname(os.path.abspath(plugin)))
+ cfg = MatchConfig(sport=env("RO_SPORT", sport), format=env("RO_FORMAT", "match"), seats=("A",),
+ seed=int(env("RO_SEED", "101")), first="A", slowdown=float(env("RCB_SLOWDOWN") or 10),
+ level=int(env("RO_LEVEL", "1")), action_level=env("RO_ACTION_LEVEL", "high"), play="program")
+ return Olympics(plugin, cfg, data=env("RCB_DATA", "/data"), task_text=env("RO_TASK_TEXT", ""),
+ episode_text=env("RO_EPISODE_TEXT", ""))
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/plugin.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/plugin.py
new file mode 100644
index 0000000000..3d601fff71
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/plugin.py
@@ -0,0 +1,589 @@
+"""Table tennis on the v0.2 core (docs/framework_zh.md §4.2): the legacy simulator of Season 1, unchanged (sim/), behind
+contract ②. Two formats, both action levels, both plays:
+
+ world + referee match arm_commands.Core (match.Match: one Franka + paddle against the scripted opponent inside the
+ world; the opponent serves every point; step = Core.rt_advance(1))
+ duel duel.Duel (two arms, a neutral serve machine, the ITTF referee; step = Duel.advance())
+ A point end freezes the world for the reviews (Phase.review); first to 5 (lead by 2 from 4:4, cap 7).
+ actions low the arm command layer: traj / slew / hold joint targets (action_low.validate)
+ high the paddle state at contact (action_high.validate), lowered at the effect boundary to the
+ SAME low-level traj command: match - match.Match.plan_paddle (IK, swing, robot-only rehearsals,
+ seeded scatter) then a slew back to the ready pose; duel - IK off the world lock in the seat's
+ plan worker (workers.prepare), the swing at the boundary (workers.trajectory). The episode
+ holds low-level commands only.
+ observation observe(): own arm, score, heard bounces, the command in force (every position in the seat's own
+ frame); camera_job(): the legacy cameras (behind and beside the seat's robot, 4 frames 40 ms
+ apart), drawn by the sport itself (a frame history is not one renderer state).
+Nothing in sim/ is edited: its seed and first receiver come from the config (duel.py reads them as module constants).
+"""
+from __future__ import annotations
+
+import copy
+import hashlib
+import json
+import os
+import sys
+import time
+from pathlib import Path
+
+import numpy as np
+
+from core.sport import FINISHED, PLAYING, UNIT_OVER, MatchBase, Phase, Refused
+
+HERE = Path(__file__).resolve().parent
+SIM = HERE / "sim"
+if str(SIM) not in sys.path:
+ sys.path.insert(0, str(SIM))
+
+import action_high # noqa: E402
+import action_low # noqa: E402
+import rcb_tt # noqa: E402
+
+DT = rcb_tt.CONTROL_DT
+SEATS = ("A", "B")
+REST_SPEED = action_high.REST # the high level's return to the ready pose (60 % of the limits)
+_INSTALL_KEYS = ("command", "first_row_used", "rows_left")
+IMAGE_LAYOUT = ("2 rows x 4 columns. Row 1: camera behind your robot looking down the table; row 2: camera at the side. "
+ "Columns: four camera frames 40 ms apart, oldest left, latest right; each tile is stamped with its "
+ "control step k and its time t since the current ball was played (observation.view_steps, "
+ "view_times). Yellow marks every 0.25 m along the table edges. Single format: the opponent is the red "
+ "paddle on the far side. The side camera looks along +x: your robot is on the right.")
+
+
+def _duel(cfg):
+ """duel.py reads its seed and first receiver from the environment at import (module constants): set both from the
+ config, also for a module imported by an earlier match of this process."""
+ first = cfg.first or "A"
+ os.environ["DUEL_SEED"], os.environ["FIRST_RECEIVER"] = str(cfg.seed), first
+ import duel
+ duel.SEED, duel.FIRST_RECEIVER = int(cfg.seed), first
+ return duel
+
+
+# ================================================================================================ format "match"
+class TTMatch(MatchBase):
+ """One seat (A) against the scripted opponent (arm_commands.Core)."""
+
+ def __init__(self, cfg):
+ self.cfg, self.level = cfg, int(cfg.level or 1)
+ os.environ["MATCH_SEED"] = str(cfg.seed) # match.Match reads it at construction: serves, opponent, scatter
+ import arm_commands
+ import ladder
+ import levels
+ self.R = arm_commands.Core(self.level, levels.plugin(cfg.action_level))
+ self.contacts = ladder.PaddleContacts(self.R) # read-only (the score ladder's blade speeds)
+ self.dt = DT
+ self.reviewed = 0
+
+ @property
+ def k(self):
+ return self.R.k
+
+ # world + referee
+ def step(self):
+ R = self.R
+ n0, r0 = len(R.points), len(R.results)
+ R.rt_advance(1)
+ self.contacts.after_step(R.k)
+ ev = [{"kind": "shot", **{k: r.get(k) for k in ("returned", "summary")}} for r in R.results[r0:]]
+ return ev + [{"kind": "point", **p} for p in R.points[n0:]]
+
+ def apply(self, seat, cmd):
+ if cmd["type"] == "noop": # a high-level act whose stroke could not be planned
+ return {}
+ return self.R.submit(cmd)
+
+ def phase(self):
+ R = self.R
+ if R.done:
+ return Phase(FINISHED, reason="match_over")
+ if len(R.points) > self.reviewed:
+ return Phase(UNIT_OVER, review=tuple(self.cfg.seats), reason=R.points[-1]["how"])
+ return Phase(PLAYING)
+
+ def resume(self):
+ self.reviewed = len(self.R.points)
+
+ def unit(self):
+ return len(self.R.points)
+
+ def scores(self):
+ return {"A": self.R.score[0], "opponent": self.R.score[1]}
+
+ def tiebreaks(self):
+ return [("game", lambda m: {0: "A", 1: "opponent"}.get(m.R.winner))] # first to 5, lead 2, cap 7; let guard
+
+ def state_digest(self):
+ """The simulator's own state hash (physics + the ball's contact events) and the points (score, how)."""
+ return hashlib.sha256((self.R.s.state_sha() + json.dumps(self.R.points, sort_keys=True)).encode()).hexdigest()
+
+ # observation
+ def observe(self, seat, query=None):
+ R = self.R
+ st, leg = R.s.state(), R.leg
+ heard = [{"event": {"table_opp": "bounce on the opponent's half", "table_own": "bounce on your half",
+ "net": "net"}.get(e["kind"], e["kind"]),
+ "t": round(e["t"] - leg["launch"] * DT, 3)} for e in R.s._events]
+ o = {"score": {"you": R.score[0], "opponent": R.score[1]}, "point": len(R.points) + 1,
+ "ball": "serve" if leg["kind"] == "serve" else "opponent's return", "t_since_played": R.t_since_launch(),
+ "heard": heard, "q": st["q"].round(4).tolist(), "paddle_pos": st["paddle_pos"].round(3).tolist(),
+ "paddle_normal": st["paddle_normal"].round(3).tolist(),
+ "ball_in_play": R.in_play() and leg["state"] in ("incoming", "to_opp", "opp_missed"),
+ "ball_state": {"incoming": "coming to you", "to_opp": "going to the opponent",
+ "opp_missed": "going to the opponent", "done": "dead"}.get(leg["state"], leg["state"]),
+ "points": [{k: p[k] for k in ("point", "winner", "how", "score")} for p in R.points[-2:]],
+ "shots": [{k: r.get(k) for k in ("returned", "summary", "speed_out")} for r in R.results[-2:]]}
+ if not R.in_play():
+ o["serve_in_s"] = round(max(0.0, (leg["launch"] - R.k) * DT), 3)
+ o.update(R.plugin.state(R)) # the command in force (low level: also qd, q_target)
+ return o
+
+ def camera_job(self, seat):
+ R = self.R
+ reviewing = len(R.points) > self.reviewed and not R.done
+ hist = list(R.review_hist if reviewing and hasattr(R, "review_hist") else R.hist)
+ if not hist: # before the first step: the current state (display only)
+ hist = [{"k": R.k, "t": R.t_since_launch(), "qpos": R.s.d.qpos.copy(), "opp_x": R.opp_x(),
+ "leg_id": len(R.legs) - 1, "wall_mono": time.monotonic()}]
+ import match
+ sel = [hist[max(0, len(hist) - 1 - b)] for b in reversed(match.Match.VIEW_BACK)]
+ snaps = [{"qpos": np.asarray(s["qpos"], float).copy(), "t": float(s["t"]), "opp_x": float(s["opp_x"]),
+ "k": int(s["k"])} for s in sel]
+ meta = dict(view_times=[s["t"] for s in sel], view_steps=[s["k"] for s in sel],
+ view_leg_ids=[s.get("leg_id") for s in sel], view_sim_times=[round(s["k"] * DT, 4) for s in sel],
+ wall_mono=sel[-1].get("wall_mono", time.monotonic()), image_layout=IMAGE_LAYOUT)
+ return {"format": "match", "seat": seat, "snaps": snaps}, meta
+
+ def render_state(self):
+ return {"qpos": self.R.s.d.qpos.tolist()}
+
+ def broadcast_frame(self):
+ return {"q": self.R.s.d.qpos.round(5).tolist(), "o": round(self.R.opp_x(), 4)}
+
+ def final_fields(self):
+ import ladder
+ R = self.R
+ return {"level": self.level, "seed": int(R.lv["seed"]), "points_for": R.score[0], "points_against": R.score[1],
+ "win_points": 5, "won": R.winner == 0, "winner_side": {0: "you", 1: "opponent"}.get(R.winner),
+ "returns": int(sum(r["returned"] for r in R.results)), "our_legs": R.n_our_legs,
+ "our_shots": R.n_our_shots, "rejected_acts": R.n_rejected, "physics_steps": int(R.s.sim_steps_total),
+ "points": R.points, "results": R.results, "shots": R.shots, "serves": R.serve_ids,
+ "opponent": [lg.get("opp") for lg in R.legs if lg.get("opp")],
+ "ladder": ladder.ladder(R.points, R.results, contacts=self.contacts.out)}
+
+
+# ================================================================================================ format "duel"
+class TTDuel(MatchBase):
+ def __init__(self, cfg):
+ self.cfg = cfg
+ self.D = D = _duel(cfg)
+ self.g = D.Duel()
+ self.g.rest_ready = cfg.action_level == "high" # the high level returns the arm to the ready pose between strokes
+ self.dt = D.CONTROL_DT
+ self.level = cfg.action_level
+ self.commands = {s: None for s in SEATS} # the high level's stroke in force (shown in the observation)
+
+ @property
+ def k(self):
+ return self.g.k
+
+ def step(self):
+ n = len(self.g.points)
+ self.g.advance()
+ if len(self.g.points) > n:
+ self.commands = {s: None for s in SEATS}
+ return [{"kind": "point", **self.g.points[-1]}]
+ return []
+
+ def apply(self, seat, cmd):
+ return self.g.install(seat, cmd)
+
+ def phase(self):
+ if self.g.done:
+ return Phase(FINISHED, reason="match_over")
+ if self.g.review_due:
+ return Phase(UNIT_OVER, review=SEATS, reason=self.g.points[-1]["how"])
+ return Phase(PLAYING)
+
+ def resume(self):
+ self.g.review_done()
+
+ def unit(self):
+ return self.g.rs["point"]
+
+ def scores(self):
+ return dict(self.g.score)
+
+ def tiebreaks(self):
+ return [("game", lambda m: m.g.winner)] # ITTF game to 5 (lead by 2, cap 7); the let guard inside Duel
+
+ def state_digest(self):
+ return self.g.state_sha()
+
+ def observe(self, seat, query=None):
+ g, D = self.g, self.D
+ other = D.OTHER[seat]
+ p = g.d.site_xpos[g.site_paddle[seat]].copy()
+ normal = g.d.site_xmat[g.site_paddle[seat]].reshape(3, 3)[:, 0].copy()
+ if seat == "B":
+ p, normal = D.mir(p), D.mir(normal)
+ command = copy.deepcopy(self.commands[seat])
+ if command:
+ command["contact_in_s"] = max(0., (command["contact_step"] - g.k) * self.dt)
+ heard = {f"table_{seat}": "bounce on your half", f"table_{other}": "bounce on the opponent's half",
+ f"paddle_{seat}": "paddle", f"paddle_{other}": "opponent hit", f"robot_{seat}": "robot",
+ f"robot_{other}": "opponent arm"}
+ o = dict(point=g.rs["point"] + 1, score=dict(you=g.score[seat], opponent=g.score[other]),
+ ball="serve" if g.rs["last_hitter"] is None else "return",
+ t_since_played=(g.k - g.rs["played_k"]) * self.dt,
+ serve_in_s=max(0., (g.rs["launch"] - g.k) * self.dt), ball_in_play=g.in_play(),
+ ball_state="coming to you" if g.rs["expect"] == seat else "going to opponent",
+ you_receive_serves=g.rs["receiver"] == seat, q=g.d.qpos[g.qadr[seat]].tolist(),
+ paddle_pos=p.tolist(), paddle_normal=normal.tolist(),
+ command=command if self.level == "high" else g.command_state(seat),
+ points=[{k: v for k, v in pt.items() if k != "receiver"} for pt in g.points[-2:]],
+ heard=[dict(event=heard.get(x["kind"], x["kind"]), t=x["t"] - g.rs["played_k"] * self.dt)
+ for x in g.events[-12:] if x["t"] >= g.rs["played_k"] * self.dt - .011])
+ if self.level == "low":
+ o.update(qd=g.d.qvel[g.vadr[seat]].round(4).tolist(), q_target=g.target[seat].round(6).tolist())
+ return o
+
+ def camera_job(self, seat):
+ g = self.g
+ hist = g.review_hist if g.review_due and hasattr(g, "review_hist") else list(g.hist)
+ if not hist:
+ hist = [dict(k=g.k, qpos=g.d.qpos.copy(), played_k=g.rs["played_k"], point=g.rs["point"],
+ wall_mono=time.monotonic())]
+ hist = copy.deepcopy(list(hist))
+ sel = [hist[max(0, len(hist) - 1 - b)] for b in reversed(g.VIEW_BACK)]
+ meta = dict(view_steps=[x["k"] for x in sel], view_points=[x["point"] + 1 for x in sel],
+ view_sim_times=[x["k"] * self.dt for x in sel],
+ view_times=[round((x["k"] - x.get("played_k", g.rs["played_k"])) * self.dt, 3) for x in sel],
+ wall_mono=sel[-1].get("wall_mono", time.monotonic()), image_layout=IMAGE_LAYOUT)
+ return {"format": "duel", "seat": seat, "snapshots": hist, "rs": copy.deepcopy(g.rs)}, meta
+
+ def render_state(self):
+ return {"qpos": self.g.d.qpos.tolist()}
+
+ def broadcast_frame(self):
+ return {"q": self.g.d.qpos.round(5).tolist()}
+
+ def final_fields(self):
+ g = self.g
+ return {"score": dict(g.score), "points": g.points, "hits": g.hits, "rejected_acts": dict(g.rejected),
+ "first_receiver": self.D.FIRST_RECEIVER, "serves": g.serve_ids}
+
+
+# ================================================================================================ action levels
+class _LowShim:
+ """What action_low needs of a simulator (joint ranges, the ready pose), from the duel's model."""
+
+ def __init__(self, g, D):
+ self.s = type("S", (), dict(JOINT_LOW=g.JLOW, JOINT_HIGH=g.JHIGH, inst={"q0": D.Q0}))()
+
+
+def _rows(m):
+ return m.R if isinstance(m, TTMatch) else _LowShim(m.g, m.D)
+
+
+def _vec(n, doc):
+ return {"type": "vector", "len": n, "doc": doc}
+
+
+LOW_SCHEMA = {
+ "traj": {"k0": {"type": "integer", "min": 0, "doc": "control step of the first row"},
+ "q": {"type": "rows", "len": 7, "max_rows": action_low.MAX_ROWS,
+ "doc": "row i = the 7 joint targets (rad) of control step k0 + i; consecutive rows within the "
+ "per-step speed limit (limits.max_target_step_rad)"}},
+ "slew": {"q": _vec(7, "joint goal (rad)"),
+ "speed": {"type": "number", "min": 0.0, "max": 1.0, "default": 1.0,
+ "doc": "fraction of each joint's speed limit, (0, 1]"}},
+ "hold": {}}
+HIGH_SCHEMA = {
+ "act": {"t": {"type": "number", "min": 0.0, "max": 2.5, "unit": "s",
+ "doc": "time from the act's effect until contact, 0 < t <= 2.5"},
+ "pos": _vec(3, "blade centre at contact (m, your frame): |x| <= 1.2, -2.5 <= y <= -0.5, 0 <= z <= 1.2"),
+ "normal": _vec(3, "blade face normal at contact (non-zero)"),
+ "vel": _vec(3, "blade velocity at contact (m/s), |vel| <= 8")},
+ "none": {}}
+
+
+class JointLayer:
+ """Low level: the player's joint-target commands go straight to the arm command layer."""
+ level = "low"
+ worker = None
+ delay_steps = 0
+
+ def schema(self, match, seat):
+ return LOW_SCHEMA
+
+ def parse(self, seat, body, match, ctx):
+ dec = action_low.validate(body if isinstance(body, dict) else {}, _rows(match))
+ if isinstance(dec, str):
+ raise Refused(dec)
+ return dec
+
+ def snapshot(self, seat, cmd, match, ordinal):
+ return None
+
+ def prepare(self, job):
+ return None
+
+ def lower(self, seat, cmd, prepared, match):
+ return cmd, {}
+
+ def reply(self, seat, cmd, info, match):
+ return {"result": info} if isinstance(match, TTMatch) else info
+
+
+class StrokeLayer:
+ """High level: the paddle state at contact, lowered at the effect boundary to a low-level traj command."""
+ level = "high"
+ worker = "plan" # the duel's IK (the match plans at the boundary: no job)
+ delay_steps = 0
+
+ def schema(self, match, seat):
+ return HIGH_SCHEMA
+
+ def parse(self, seat, body, match, ctx):
+ dec = action_high.validate(body if isinstance(body, dict) else {}, None)
+ if isinstance(dec, str):
+ raise Refused(dec)
+ return dec
+
+ def snapshot(self, seat, cmd, match, ordinal):
+ if cmd["type"] == "none" or isinstance(match, TTMatch):
+ return None
+ g = match.g
+ return dict(decision=cmd, point=g.rs["point"], ordinal=ordinal, q=g.d.qpos[g.qadr[seat]].tolist(),
+ target=g.target[seat].tolist())
+
+ def prepare(self, job):
+ raise RuntimeError("runs in the plan worker")
+
+ def lower(self, seat, cmd, prepared, match):
+ if isinstance(match, TTMatch):
+ return self._lower_match(cmd, match.R)
+ g = match.g
+ if cmd["type"] == "none":
+ match.commands[seat] = None
+ return {"type": "hold"}, {}
+ from workers import trajectory
+ prev = g.actions[seat][-2] if (len(g.actions[seat]) >= 2 and
+ np.array_equal(g.target[seat], g.actions[seat][-1])) else g.target[seat]
+ path, info = trajectory(g.target[seat], prev, prepared, cmd["t"], g.JLOW, g.JHIGH)
+ match.commands[seat] = dict(pos=cmd["pos"], normal=cmd["normal"], vel=cmd["vel"],
+ contact_step=g.k + info["contact_steps"])
+ info.update(ik_residual=prepared["ik_residual"], speed_scale=prepared["speed_scale"])
+ return {"type": "traj", "k0": g.k, "q": [q.tolist() for q in path]}, info
+
+ @staticmethod
+ def _lower_match(cmd, R):
+ """= action_high.apply at the effect boundary (the legacy service planned there too), with the plan handed
+ to the arm command layer as a low-level command instead of being submitted directly."""
+ rest = {"type": "slew", "q": [float(x) for x in R.s.inst["q0"]], "speed": REST_SPEED}
+ if cmd["type"] == "none":
+ R._last_act = None
+ R.contact_k = R.k
+ return rest, {"stroke": "cleared: the arm returns to the ready pose"}
+ T = float(cmd["t"])
+ t_hit = (R.k - R.leg["launch"]) * DT + T
+ R._ik_seed = R._planned_hit if R.traj_active() else None
+ plan, info = R.plan_paddle(t_hit, cmd["pos"], cmd["normal"], cmd["vel"])
+ info["T_from_now"] = round(T, 4)
+ R.shots.append({"k": R.k, "leg": R.n_our_legs, **{k: info[k] for k in info if k != "paddle_vel_delivered"}})
+ if not plan:
+ return {"type": "noop"}, info
+ R.contact_k = R.k + info["n_swing_steps_available"]
+ R._last_act = info
+ return {"type": "traj", "k0": R.k, "q": [np.asarray(q, float).tolist() for q in plan], "then": rest}, info
+
+ def reply(self, seat, cmd, info, match):
+ if isinstance(match, TTMatch):
+ return action_high.reply(cmd, info)
+ return {k: v for k, v in info.items() if k not in _INSTALL_KEYS}
+
+
+# ================================================================================================ the cameras
+class _Tiles:
+ """Draws camera tiles exactly as the legacy services did (render_worker.py for the match, Duel.render_views for the
+ duel), with a cache: consecutive observations share most of their frames (a frame every 2 control steps, the 4
+ tiles span 12), and a tile is a pure function of its snapshot, so a cached tile is the same picture."""
+
+ def __init__(self, model, cams):
+ import mujoco as mj
+ self.mj = mj
+ self.m = model
+ self.r = mj.Renderer(self.m, height=360, width=480)
+ self.rd = mj.MjData(self.m)
+ self.cams, self.cache = [], {}
+ for lookat, dist, az, el in cams:
+ c = mj.MjvCamera()
+ c.lookat[:] = lookat
+ c.distance, c.azimuth, c.elevation = dist, az, el
+ self.cams.append(c)
+
+ def tile(self, ci, qpos, text, extra, key):
+ from PIL import Image, ImageDraw
+ key = (ci, key, text, np.asarray(qpos, float).tobytes())
+ if key not in self.cache:
+ mj = self.mj
+ self.rd.qpos[:] = qpos
+ mj.mj_forward(self.m, self.rd)
+ self.r.update_scene(self.rd, camera=self.cams[ci])
+ extra(self.r.scene)
+ im = Image.fromarray(self.r.render())
+ ImageDraw.Draw(im).text((6, 4), text, fill=(255, 255, 255))
+ if len(self.cache) > 96:
+ self.cache.clear()
+ self.cache[key] = np.asarray(im)
+ return self.cache[key]
+
+ def sheet(self, tiles_per_cam):
+ from core.observe import png
+ return png(np.concatenate([np.concatenate(row, axis=1) for row in tiles_per_cam], axis=0))
+
+
+def _players_model(live, scene_file):
+ """The model the cameras draw: the players' presentation scene (presentation/presentation.toml `players`: the
+ Franka Panda's visual meshes on the same bodies, renderer rule 6; same kinematics, checked) with the live model's
+ marker settings, else the live model itself."""
+ from renderers import Scene, players_model
+ fine = players_model(HERE, Scene.from_file(scene_file))
+ if fine is None:
+ return live
+ fine.site_pos[:], fine.site_size[:], fine.site_rgba[:] = live.site_pos, live.site_size, live.site_rgba
+ return fine
+
+
+class MatchView(_Tiles):
+ """The single format's cameras (= the legacy render_worker.py): 2 cameras x 4 frames, 480 x 360 tiles."""
+
+ def __init__(self):
+ import match
+ self.Match = match.Match
+ m = rcb_tt.Session(instance=str(match.INSTANCE), scene=str(match.SCENE)).m # the live match's model
+ super().__init__(_players_model(m, match.SCENE), match.Match.CAMS)
+
+ def draw(self, snaps):
+ return self.sheet([[self.tile(ci, sn["qpos"], f"k={sn['k']} t={sn['t']:.2f}s",
+ lambda scn, o=sn["opp_x"]: self.Match._extra_geoms(None, scn, o), sn["opp_x"])
+ for sn in snaps] for ci in range(len(self.cams))])
+
+
+class DuelView(_Tiles):
+ """A duel seat's cameras (= duel.Duel.render_views): behind and beside the seat's robot, in its own frame."""
+
+ def __init__(self, seat):
+ import duel
+ self.D = duel
+ cams = [(lk if seat == "A" else duel.mir(lk), dist, az if seat == "A" else az + 180.0, el)
+ for lk, dist, az, el in duel.Duel.CAMS]
+ import mujoco as mj
+ super().__init__(_players_model(mj.MjModel.from_xml_path(str(duel.SCENE2)), duel.SCENE2), cams) # = Duel()'s
+
+ def draw(self, snapshots, rs):
+ D, out = self.D, []
+ sel = [snapshots[max(0, len(snapshots) - 1 - b)] for b in reversed(D.Duel.VIEW_BACK)]
+ for ci in range(len(self.cams)):
+ row = []
+ for sn in sel:
+ q = np.array(sn["qpos"], float)
+ pk = sn.get("played_k", rs["played_k"])
+ if sn["k"] <= pk:
+ q[:3] = [0, 0, -10]
+ row.append(self.tile(ci, q, f"k={sn['k']} t={(sn['k'] - pk) * D.CONTROL_DT:.2f}s",
+ lambda scn: D.Duel._extra_geoms(None, scn), pk))
+ out.append(row)
+ return self.sheet(out)
+
+
+_LOCAL: dict = {} # in-process views (core/local.py: no worker processes)
+
+
+# ================================================================================================ the sport
+class TableTennis:
+ name = "tabletennis"
+ protocol = "realtime"
+ revision = "wallclock-6+duel-wallclock-4+core-0.2"
+ source_dirs = [str(HERE)]
+ workers = ("plan", "render")
+
+ def build(self, cfg):
+ return TTDuel(cfg) if len(cfg.seats) > 1 else TTMatch(cfg)
+
+ def action_layer(self, level):
+ return StrokeLayer() if level == "high" else JointLayer()
+
+ def worker_init(self, kind, seat, cfg):
+ duel = len(cfg.seats) > 1
+ if kind == "plan":
+ return _duel(cfg).Planner(seat) if duel else None
+ if duel:
+ _duel(cfg)
+ v = DuelView(seat)
+ else:
+ v = MatchView()
+ v.tile(0, v.rd.qpos.copy(), "", lambda scn: None, "warm-up") # creates the GL context before the handshake
+ v.cache.clear()
+ return v
+
+ def worker_call(self, obj, kind, job):
+ if kind == "plan":
+ from workers import prepare
+ return prepare(obj, job)
+ if obj is None: # in-process (core/local.py)
+ key = (job["format"], job["seat"])
+ if key not in _LOCAL:
+ _LOCAL[key] = MatchView() if job["format"] == "match" else DuelView(job["seat"])
+ obj = _LOCAL[key]
+ if job["format"] == "match":
+ return {"png": obj.draw(job["snaps"])}
+ return {"png": obj.draw(job["snapshots"], job["rs"])}
+
+ def scene(self, cfg):
+ from renderers.base import Scene
+ return Scene.from_file(SIM / "scene" / ("tt_duel.xml" if len(cfg.seats) > 1 else "tt_scene.xml"))
+
+ def players(self):
+ import builtin_players as bp
+ return {"reference": bp.Reference, "idle": bp.Idle}
+
+ def spec(self, cfg, seat, m):
+ import match
+ cams = [dict(c, fovy_deg=45.0, tile_px=[480, 360], focal_px=434.6, principal_point_px=[240, 180],
+ image_right="forward x up") for c in match.Match.CAM_INFO]
+ out = dict(robot="franka-panda + paddle (MuJoCo Menagerie panda_nohand)", cameras=cams,
+ image="2 rows (behind, side) x 4 columns (camera frames 40 ms apart, oldest left); tile 480 x 360",
+ image_layout=IMAGE_LAYOUT,
+ frame="your robot's base is at (0, -1.75, 0) facing +y; your half is y < 0; table top z = 0, "
+ "|x| <= 0.7625, |y| <= 1.37, net at y = 0 (top z = 0.1525); every position you are given "
+ "or send is in this frame",
+ calls={"observe": "{} -> the state + the newest camera frames (observation.image_png_b64)",
+ "act": (action_high.ACT_CALL if cfg.action_level == "high" else action_low.ACT_CALL),
+ "wait": "{'dt': game seconds, 0 < dt <= 1}"})
+ if isinstance(m, TTMatch):
+ out["match"] = dict(win_points=5, win_by=2, cap_points=7, expedite_returns=13, opponent_level=m.level,
+ serves="the opponent serves every point; you always receive",
+ format="first to 5; from 4:4 lead by 2, up to 7 (at 6:6 the next point wins)")
+ else:
+ D = m.D
+ out["match"] = dict(win_points=D.WIN_POINTS, win_by=D.WIN_BY, cap_points=D.CAP_POINTS,
+ expedite_returns=D.EXPEDITE_RETURNS, first_receiver=D.FIRST_RECEIVER,
+ serves="a neutral machine serves recorded real serves; the receiver changes every point",
+ format=f"first to {D.WIN_POINTS}; from {D.WIN_POINTS - 1}:{D.WIN_POINTS - 1} lead by "
+ f"{D.WIN_BY}, up to {D.CAP_POINTS} (at {D.CAP_POINTS - 1}:{D.CAP_POINTS - 1} "
+ "the next point wins); the receiver changes every point")
+ if cfg.action_level == "low":
+ import robot_model
+ mm = m.R.s.m if isinstance(m, TTMatch) else m.g.m # the duel: robot A's chain (= B's, own frame)
+ out.update(action_interface="joint position targets at 100 Hz; no IK or stroke planner (your own frame: "
+ "the same kinematic chain for both duel seats)",
+ kinematics=action_low.kinematics(mm), limits=action_low.limits(_rows(m).s),
+ robot_model={"robot_only_xml": robot_model.robot_only_xml(),
+ "note": "the arm + paddle cut out of the simulator's scene (MJCF; the mesh files "
+ "are MuJoCo Menagerie panda_nohand's); nothing of the world"})
+ return out
+
+
+SPORT = TableTennis()
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/presentation/presentation.toml b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/presentation/presentation.toml
new file mode 100644
index 0000000000..b193733953
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/presentation/presentation.toml
@@ -0,0 +1,15 @@
+# Appearance of tabletennis' robots (docs/framework_zh.md §3.1, renderer rule 6; renderers/presentation/__init__.py):
+# the Franka Panda's visual meshes on the arm's bodies, same kinematics. Since revision wallclock-6 / duel-wallclock-4
+# the players' images use it too (`players`): tools/sportlib bundles this directory and the 25k level of detail of the
+# meshes (renderers/presentation/lod.json, sha256-pinned, licence kept) into the simulator, so they are part of
+# source_sha; spectator re-renders from a checkout use the full meshes.
+[presentation]
+version = 2
+label = "Franka Panda visual meshes (MuJoCo Menagerie)"
+players = "25k" # the players' images: the meshes decimated to ~25k triangles per arm
+
+[[presentation.robot]]
+model = "franka_emika_panda" # renderers/presentation/menagerie.json (fetched, sha256-pinned)
+bodies = '^link(?P<n>[0-7])(?P<b>_b)?$'
+body = "link{n}"
+hide = "mesh" # the arm's collision meshes move to the hidden group 3
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/action_high.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/action_high.py
new file mode 100644
index 0000000000..ad29366e37
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/action_high.py
@@ -0,0 +1,79 @@
+"""High-level action plugin (action level `high`, the switch on): the player gives the paddle state at contact; the
+plugin plans the stroke with match.Match's planner (IK, a joint-speed-limited swing, rehearsals on a simulator copy,
+seeded execution scatter) and hands the swing to the arm command layer (core.py) as a `traj` command followed by a
+slew back to the ready pose at 60 % of the speed limits. With no stroke under way the arm returns to / holds the ready
+pose. This reproduces the original high-level tasks target for target (scripts/olympiad/tabletennis/test_modes.py).
+"""
+from __future__ import annotations
+
+import numpy as np
+
+from rcb_tt import CONTROL_DT
+
+LEVEL = "high"
+REST = 0.6 # rest command: slew to the ready pose at 60 % of the joint speed limits
+ACT_CALL = "{'type':'act','t':T_from_now,'pos':[x,y,z],'normal':[nx,ny,nz],'vel':[vx,vy,vz]} or {'type':'none'}"
+OBSERVE_CALL = "the newest camera frames (2 x 4), heard bounces, time, your arm and command"
+
+
+def validate(body: dict, core) -> dict | str:
+ if body.get("type") == "none":
+ return {"type": "none"}
+ try:
+ T = float(body["t"]); pos = [float(x) for x in body["pos"]]
+ nrm = [float(x) for x in body["normal"]]; vel = [float(x) for x in body["vel"]]
+ except Exception: # noqa: BLE001
+ return ("act needs T (s from now until contact), pos [x, y, z] (blade centre at contact), normal [nx, ny, nz] "
+ "(blade face normal) and vel [vx, vy, vz] (blade velocity at contact, m/s); or `act none`")
+ if len(pos) != 3 or len(nrm) != 3 or len(vel) != 3 or not np.all(np.isfinite(pos + nrm + vel + [T])):
+ return "pos, normal and vel must have 3 finite numbers each"
+ if np.linalg.norm(nrm) < 1e-6:
+ return "normal must be a non-zero vector"
+ if not (0.0 < T <= 2.5):
+ return "T must be in (0, 2.5] s from now"
+ if not (abs(pos[0]) <= 1.2 and -2.5 <= pos[1] <= -0.5 and 0.0 <= pos[2] <= 1.2):
+ return "pos out of range: |x| <= 1.2, -2.5 <= y <= -0.5, 0 <= z <= 1.2"
+ if np.linalg.norm(vel) > 8.0:
+ return "vel too large: |vel| <= 8 m/s"
+ return {"type": "act", "t": T, "pos": pos, "normal": nrm, "vel": vel}
+
+
+def apply(R, dec: dict) -> dict:
+ if dec["type"] == "none": # cancel: the arm returns to the ready pose
+ R.cmd = R.rest_command()
+ R._last_act = None
+ R.contact_k = R.k
+ return {"stroke": "cleared: the arm returns to the ready pose"}
+ T = float(dec["t"])
+ t_hit = (R.k - R.leg["launch"]) * CONTROL_DT + T
+ R._ik_seed = R._planned_hit if R.traj_active() else None
+ plan, info = R.plan_paddle(t_hit, dec["pos"], dec["normal"], dec["vel"])
+ info["T_from_now"] = round(T, 4)
+ if plan: # the swing, then back to the ready pose
+ res = R.submit({"type": "traj", "k0": R.k, "q": plan, "then": R.rest_command()})
+ assert "command" in res, res # the planner's swing starts at the target in force
+ R.shots.append({"k": R.k, "leg": R.n_our_legs, **{k: info[k] for k in info if k != "paddle_vel_delivered"}})
+ if plan:
+ R.contact_k = R.k + info["n_swing_steps_available"]
+ R._last_act = info
+ return info
+
+
+def reply(dec: dict, info: dict) -> dict:
+ if dec["type"] == "none":
+ return {"command": "cleared: the arm returns to the ready pose"}
+ return {"stroke": {k: info.get(k) for k in ("stroke", "n_swing_steps_available", "n_swing_steps", "ik_residual",
+ "blade_error_m", "normal_error_deg", "speed_scale",
+ "paddle_vel_delivered", "T_from_now")}}
+
+
+def state(R) -> dict:
+ la = getattr(R, "_last_act", None)
+ return {"command": ({"contact_in_s": round(max(0, R.contact_k - R.k) * CONTROL_DT, 3),
+ "phase": "approach" if R.k < R.contact_k else "follow_through", "pos": la.get("paddle_pos"),
+ "normal": la.get("paddle_normal"), "vel": la.get("paddle_vel"), "stroke": la.get("stroke")}
+ if R.traj_active() and la else "none (the arm returns to / holds the ready pose)")}
+
+
+def spec(R) -> dict:
+ return {}
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/action_low.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/action_low.py
new file mode 100644
index 0000000000..7cfe8deae9
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/action_low.py
@@ -0,0 +1,130 @@
+"""Low-level action plugin (action level `low`, the high-level switch off): the player's commands go straight to the
+arm command layer (arm_commands.py); nothing plans for it (no IK, no stroke planner, no rehearsal, no return to a ready pose,
+no execution scatter). The robot's own joint controller (PD + gravity/Coriolis compensation at 1 kHz, torque limits;
+rcb_tt.Session.step) tracks the targets. `spec` documents the robot's kinematic chain, limits and controller.
+
+Commands (each replaces the previous one when it takes effect, at the start of the next control step after it
+arrives):
+ traj {"type": "traj", "k0": K0, "q": [[q1..q7], ...]} 1..MAX_ROWS rows; row i is the joint target of control
+ step K0 + i. Passed rows are skipped; before K0 the current target is held; after the last row it is held.
+ Rows must lie in the joint ranges and consecutive rows may differ by at most VEL_LIMIT x 10 ms per joint
+ (HTTP 400). The first row used must be within that limit of the target in force (else rejected, arm_commands.py).
+ slew {"type": "slew", "q": [q1..q7], "speed": F} every joint independently towards q at F x its speed limit.
+ hold {"type": "hold"}
+At the end of a point the command is cleared: the arm holds its targets.
+"""
+from __future__ import annotations
+
+import numpy as np
+
+import mujoco as mj
+from arm_commands import STEP_LIM
+from rcb_tt import KD, KP, TORQUE_LIMIT, VEL_LIMIT
+
+LEVEL = "low"
+REST = None # rest command: hold
+MAX_ROWS = 300 # 3 s of targets per command
+CHAIN = ["link0", "link1", "link2", "link3", "link4", "link5", "link6", "link7", "paddle"]
+ACT_CALL = ("{'type':'traj','k0':K0,'q':[[7 joint targets], ...]} (row i = target of control step K0+i, <= 300 rows) "
+ "| {'type':'slew','q':[7],'speed':F} | {'type':'hold'}")
+OBSERVE_CALL = "the newest camera frames (2 x 4), heard bounces, time, your arm (q, qd, q_target) and command"
+
+
+def validate(body: dict, core) -> dict | str:
+ low, high = core.s.JOINT_LOW, core.s.JOINT_HIGH
+ t = body.get("type")
+ if t == "hold":
+ return {"type": "hold"}
+ if t == "slew":
+ try:
+ q = [float(x) for x in body["q"]]
+ speed = float(body.get("speed", 1.0))
+ except Exception: # noqa: BLE001
+ return "slew needs q: 7 joint angles (rad) and optionally speed in (0, 1]"
+ if len(q) != 7 or not np.all(np.isfinite(q)):
+ return "q must be 7 finite joint angles (rad)"
+ if not (0.0 < speed <= 1.0):
+ return "speed must be in (0, 1] (fraction of each joint's speed limit)"
+ if np.any(np.asarray(q) < low) or np.any(np.asarray(q) > high):
+ return f"q outside the joint ranges: low {np.round(low, 4).tolist()}, high {np.round(high, 4).tolist()}"
+ return {"type": "slew", "q": q, "speed": speed}
+ if t == "traj":
+ try:
+ k0 = body["k0"]
+ if type(k0) is not int:
+ raise TypeError
+ Q = np.asarray(body["q"], dtype=float)
+ except Exception: # noqa: BLE001
+ return "traj needs k0 (an integer control step) and q: a list of rows of 7 joint targets (rad)"
+ if Q.ndim != 2 or Q.shape[1] != 7 or not (1 <= len(Q) <= MAX_ROWS) or not np.all(np.isfinite(Q)):
+ return f"q must be 1..{MAX_ROWS} rows of 7 finite joint targets"
+ if k0 < 0:
+ return "k0 must be >= 0"
+ if np.any(Q < low) or np.any(Q > high):
+ r, j = np.argwhere((Q < low) | (Q > high))[0]
+ return f"row {int(r)}, joint {int(j) + 1}: {Q[r, j]:.5f} outside its range [{low[j]:.4f}, {high[j]:.4f}]"
+ if len(Q) > 1:
+ dq = np.abs(np.diff(Q, axis=0))
+ if (dq > STEP_LIM).any():
+ r, j = np.argwhere(dq > STEP_LIM)[0]
+ return (f"rows {int(r)}->{int(r) + 1}, joint {int(j) + 1}: moves {dq[r, j]:.5f} rad in one 10 ms step "
+ f"(limit {STEP_LIM[j]:.5f} = {VEL_LIMIT[j]} rad/s)")
+ return {"type": "traj", "k0": int(k0), "q": Q.tolist()}
+ return "act type must be traj, slew or hold (this task's action level is low: joint targets)"
+
+
+def apply(R, dec: dict) -> dict:
+ return R.submit(dec)
+
+
+def reply(dec: dict, info: dict) -> dict:
+ return {"result": info}
+
+
+def state(R) -> dict:
+ st = R.s.state()
+ return {"qd": st["qd"].round(4).tolist(), "q_target": st["q_target"].round(6).tolist(),
+ "command": R.command_state()}
+
+
+def kinematics(m: mj.MjModel) -> dict:
+ """The robot's kinematic model (its own body, not world state): the body chain from the world to the paddle."""
+ bodies = []
+ for name in CHAIN:
+ b = mj.mj_name2id(m, mj.mjtObj.mjOBJ_BODY, name)
+ j = [i for i in range(m.njnt) if m.jnt_bodyid[i] == b]
+ e = {"body": name, "pos_in_parent": [round(float(x), 6) for x in m.body_pos[b]],
+ "quat_in_parent_wxyz": [round(float(x), 7) for x in m.body_quat[b]]}
+ if j:
+ e["joint"] = mj.mj_id2name(m, mj.mjtObj.mjOBJ_JOINT, j[0])
+ e["joint_axis_in_body"] = [float(x) for x in m.jnt_axis[j[0]]]
+ e["joint_pos_in_body"] = [float(x) for x in m.jnt_pos[j[0]]]
+ bodies.append(e)
+ site = mj.mj_name2id(m, mj.mjtObj.mjOBJ_SITE, "paddle_center")
+ return {
+ "chain": bodies,
+ "rule": ("world pose of a body = parent pose x translate(pos_in_parent) x rotate(quat_in_parent_wxyz); a body "
+ "with a joint then rotates by the joint angle q about joint_axis_in_body (through joint_pos_in_body). "
+ "The parent of link0 is the world."),
+ "blade_center_in_paddle": [round(float(x), 6) for x in m.site_pos[site]],
+ "blade_normal": "the paddle body's local +x axis (the face normal); the handle runs along its local +z",
+ "blade_half_size_m": [0.0075, 0.075, 0.075],
+ }
+
+
+def limits(s) -> dict:
+ return {"joint_low_rad": [round(float(x), 4) for x in s.JOINT_LOW],
+ "joint_high_rad": [round(float(x), 4) for x in s.JOINT_HIGH],
+ "joint_speed_limit_rad_s": VEL_LIMIT.tolist(), "torque_limit_nm": TORQUE_LIMIT.tolist(),
+ "max_target_step_rad": [round(float(x), 6) for x in STEP_LIM],
+ "controller": {"kp": KP.tolist(), "kd": KD.tolist(),
+ "law": "tau = kp (q_des - q) + kd (qd_des - qd) + gravity/Coriolis compensation, clipped "
+ "at the torque limits, at 1 kHz; q_des interpolates linearly from the previous "
+ "target to the new one over the 10 ms step and qd_des is their difference / 10 ms"},
+ "ready_pose_rad": [round(float(x), 5) for x in s.inst["q0"]],
+ "max_rows_per_command": MAX_ROWS}
+
+
+def spec(R) -> dict:
+ return {"action_interface": "joint position targets at 100 Hz; no IK or stroke planner",
+ "kinematics": kinematics(R.s.m), "limits": limits(R.s)}
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/arm_commands.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/arm_commands.py
new file mode 100644
index 0000000000..b5b8320dc7
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/arm_commands.py
@@ -0,0 +1,107 @@
+"""The one table-tennis simulator core of every play mode and action level (docs/benchmarks/roboolympics-modes.md).
+
+Layers, bottom up:
+ physics + referee + opponent rcb_tt.Session, rally.Rally, match.Match (unchanged; Match also holds the stroke
+ planner the high-level plugin uses);
+ arm command layer (this file) the only source of the arm's joint targets: one command at a time -
+ `traj` (joint position targets stamped with absolute control steps, optionally
+ followed by another command), `slew` (every joint towards q at a fraction of its
+ speed limit) or `hold`; a command whose first used target jumps by more than one
+ step's speed limit from the target in force is rejected (the previous one goes on);
+ at the end of a point the command falls back to the level's rest command;
+ action plugin action_low.py (switch off: the player's commands go straight to this layer) or
+ action_high.py (switch on: the paddle state at contact -> IK + stroke planner ->
+ a `traj` command, then a slew back to the ready pose).
+Live service and replay both drive the match only through Core.apply (the plugin) and Core.rt_advance.
+"""
+from __future__ import annotations
+
+import numpy as np
+
+import match
+from rcb_tt import CONTROL_DT, VEL_LIMIT
+
+STEP_LIM = VEL_LIMIT * CONTROL_DT # rad per control step and joint (the arm's speed limits)
+
+
+class Core(match.Match):
+ """match.Match whose arm targets come from the command layer; `plugin` is action_low or action_high."""
+
+ def __init__(self, level: int = 1, plugin=None, lv_override: dict | None = None):
+ super().__init__(level, lv_override)
+ if plugin is None:
+ import action_high as plugin
+ self.plugin = plugin
+ self.n_rejected = 0
+ self.cmd = self.rest_command()
+
+ # ------------------------------------------------------------------ the command layer
+ def rest_command(self):
+ """What the arm does when no command is in force: the plugin's rest (hold, or a slew to the ready pose)."""
+ r = self.plugin.REST
+ return None if r is None else {"type": "slew", "q": np.asarray(self.s.inst["q0"], float), "speed": r}
+
+ def traj_active(self) -> bool:
+ c = self.cmd
+ return c is not None and c["type"] == "traj" and self.k - c["k0"] < len(c["q"])
+
+ def _arm_target(self):
+ c = self.cmd
+ if c is not None and c["type"] == "traj":
+ i = self.k - c["k0"]
+ if i >= len(c["q"]) and c.get("then") is not None:
+ self.cmd = c = c["then"] # e.g. the high level's return to the ready pose
+ elif i < 0:
+ return self.s._target.copy()
+ else:
+ return c["q"][min(i, len(c["q"]) - 1)].copy()
+ tgt = self.s._target
+ if c is None:
+ return tgt.copy()
+ lim = STEP_LIM * c["speed"] # slew
+ return tgt + np.clip(c["q"] - tgt, -lim, lim)
+
+ def submit(self, cmd: dict) -> dict:
+ """At the start of control step self.k: `cmd` (validated) becomes the command in force, or is rejected."""
+ if cmd["type"] == "hold":
+ self.cmd = None
+ return {"command": "hold"}
+ if cmd["type"] == "slew":
+ self.cmd = {"type": "slew", "q": np.asarray(cmd["q"], float), "speed": float(cmd["speed"])}
+ return {"command": "slew"}
+ Q = np.asarray(cmd["q"], float)
+ k0 = int(cmd["k0"])
+ j0 = max(0, self.k - k0)
+ if j0 >= len(Q):
+ self.n_rejected += 1
+ return {"rejected": f"stale: the trajectory's last row was for step {k0 + len(Q) - 1}; this is step {self.k}"}
+ jump = np.abs(Q[j0] - self.s._target)
+ if (jump > STEP_LIM).any():
+ j = int(np.argmax(jump / STEP_LIM))
+ self.n_rejected += 1
+ return {"rejected": f"discontinuous: row {j0} (step {self.k}) moves joint {j + 1} by {jump[j]:.5f} rad from "
+ f"the target in force (limit {STEP_LIM[j]:.5f} per step); the previous command goes on",
+ "first_row_used": j0}
+ self.cmd = {"type": "traj", "q": Q, "k0": k0, "then": cmd.get("then")}
+ return {"command": "traj", "first_row_used": j0, "rows_left": int(len(Q) - j0)}
+
+ def rt_advance(self, n_steps: int):
+ n0 = len(self.points)
+ out = super().rt_advance(n_steps)
+ if len(self.points) > n0:
+ self.cmd = self.rest_command() # a command does not carry over to the next point
+ return out
+
+ def apply(self, dec: dict) -> dict:
+ """A validated player command (live: when it takes effect; replay: at its logged step)."""
+ return self.plugin.apply(self, dec)
+
+ def command_state(self) -> dict | str:
+ c = self.cmd
+ if c is None:
+ return "hold"
+ if c["type"] == "slew":
+ return {"type": "slew", "q": [round(float(x), 5) for x in c["q"]], "speed": c["speed"]}
+ i = self.k - c["k0"]
+ return {"type": "traj", "k0": c["k0"], "rows": int(len(c["q"])),
+ "next_row": int(i), "rows_left": int(max(0, len(c["q"]) - max(i, 0)))}
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/instance.npz b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/instance.npz
new file mode 100644
index 0000000000..a947eff645
Binary files /dev/null and b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/instance.npz differ
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/ladder.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/ladder.py
new file mode 100644
index 0000000000..3113c65f5b
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/ladder.py
@@ -0,0 +1,116 @@
+"""The score ladder (analysis only; it never changes who wins): how far the agent got with each ball and in each point.
+
+ touched the paddle (blade) touched the ball
+ active ... with the blade moving at >= ACTIVE_SPEED at the contact (a swing or a push; a blade held still at the
+ ready pose also meets some serves: the nop player "touches" 2-3 balls of 5 at L1)
+ over_net ... and after that touch the ball first came down beyond the net (y > 0: the opponent's half or the floor
+ behind it; touching the net on the way is allowed)
+ landed_in ... and that first contact was the opponent's half of the table
+ returned ... a good return (also: one own bounce before the hit, one paddle contact, no arm contact with the table)
+ won the point was won; split into `won_expedite` (the agent, always the receiver, made 13 good returns: the
+ expedite rule, ITTF 2.15.4) and `won_rally` (every other won point: the opponent missed or hit out)
+
+Per point a rung counts if any of the agent's balls in that point reached it ("won" counts the point itself; a point
+can be won without a touch, e.g. the opponent's ball passing the agent's half). Lets are not points. Computed from the
+match's own per-ball results (`Match.results`) and points (`Match.points`), live and again in the replay.
+"""
+from __future__ import annotations
+
+RUNGS = ("touched", "active", "over_net", "landed_in", "returned")
+EXPEDITE_TAG = "(expedite rule)" # in a point's `how` when the expedite rule decided it (match.py, duel.py)
+
+
+def by_expedite(p: dict) -> bool:
+ """Whether the expedite rule decided this point (from its `how`; the rules are unchanged, this only reports it)."""
+ return EXPEDITE_TAG in str(p.get("how", ""))
+ACTIVE_SPEED = 0.2 # m/s, blade-centre speed at the paddle contact (a held blade: < 0.01 m/s)
+
+
+def contact_speeds(results: list, contacts: list) -> list:
+ """Per result, the largest blade speed of its paddle contacts. contacts: [(control step, blade speed m/s)] in
+ order; a result's contacts are those after the previous result's close step up to its own (`step`)."""
+ out, prev, i = [], -1, 0
+ for r in results:
+ v = None
+ while i < len(contacts) and contacts[i][0] <= r["step"]:
+ if contacts[i][0] > prev:
+ v = max(v or 0.0, float(contacts[i][1]))
+ i += 1
+ out.append(v)
+ prev = r["step"]
+ return out
+
+
+def ball_rungs(r: dict, speed: float | None = None) -> dict:
+ """The rungs one of the agent's balls (one entry of Match.results) reached; `active` needs the contact speed."""
+ kinds = list(r.get("events") or [])
+ touched = bool(r.get("hit"))
+ post = [k for k in kinds[kinds.index("paddle") + 1:] if k not in ("paddle", "net")] if "paddle" in kinds else []
+ over = touched and bool(post) and float(r.get("landing_y", 0.0)) > 0.0
+ landed = over and post[0] == "table_opp"
+ return {"touched": touched, "active": touched and speed is not None and speed >= ACTIVE_SPEED, "over_net": over,
+ "landed_in": landed, "returned": bool(r.get("returned"))}
+
+
+def ladder(points: list, results: list, me: str = "you", contacts: list | None = None) -> dict:
+ """Counts per match: `points_*` (points that reached the rung) and `balls_*` (the agent's balls that did).
+ contacts: the paddle contacts with the blade speed (replay.py records them); without them `active` is -1."""
+ speeds = contact_speeds(results, contacts) if contacts is not None else [None] * len(results)
+ played = [i for i, p in enumerate(points) if p.get("winner") != "let"]
+ per_point = {i: dict.fromkeys(RUNGS, False) for i in played}
+ balls = dict.fromkeys(RUNGS, 0)
+ for r, v in zip(results, speeds):
+ rg = ball_rungs(r, v)
+ for k in RUNGS:
+ balls[k] += int(rg[k])
+ if r.get("point") in per_point and rg[k]:
+ per_point[r["point"]][k] = True
+ out = {"points": len(played), "balls": len(results)}
+ for k in RUNGS:
+ out["points_" + k] = sum(per_point[i][k] for i in played)
+ out["points_won"] = sum(points[i].get("winner") == me for i in played)
+ out["points_won_expedite"] = sum(points[i].get("winner") == me and by_expedite(points[i]) for i in played)
+ out["points_won_rally"] = out["points_won"] - out["points_won_expedite"]
+ for k in RUNGS:
+ out["balls_" + k] = balls[k]
+ if contacts is None:
+ out["points_active"] = out["balls_active"] = -1
+ out["per_point"] = [{"point": i, **{k: int(per_point[i][k]) for k in RUNGS},
+ "won": int(points[i].get("winner") == me),
+ "expedite": int(points[i].get("winner") == me and by_expedite(points[i]))} for i in played]
+ return out
+
+
+# The flat reward.json fields (tests/grade.py LADDER_KEYS, prefixed `ladder_`; test_modes.py checks they agree).
+REWARD_KEYS = tuple(["points", "balls"] + ["points_" + k for k in RUNGS] + ["points_won", "points_won_expedite", "points_won_rally"] + ["balls_" + k for k in RUNGS])
+
+
+class PaddleContacts:
+ """Records (control step, blade-centre speed) at every new paddle contact of a running match (replay.py calls
+ after_step() after every control step). It also looks when the match closes one of the agent's balls (a contact
+ and the end of the point can fall into the same control step, after which the step's events are cleared).
+ Read-only: it never changes the simulation (the replay's hashes are unchanged)."""
+
+ def __init__(self, match):
+ import numpy as np
+ self.m, self.s, self.out, self._n, self._first = match, match.s, [], 0, None
+ self._v = np.zeros(6)
+ close = match._close_our_leg
+
+ def _close_our_leg(*a, **kw):
+ self.after_step(match.k)
+ return close(*a, **kw)
+ match._close_our_leg = _close_our_leg
+
+ def after_step(self, k: int) -> None:
+ import mujoco as mj
+ import numpy as np
+ ev = self.s._events
+ first = (ev[0]["t"], ev[0]["kind"]) if ev else None # (an object id could be reused after the clear)
+ if first != self._first: # the per-leg event list was cleared (a new leg)
+ self._first, self._n = first, 0
+ n = sum(e["kind"] == "paddle" for e in ev)
+ if n > self._n:
+ mj.mj_objectVelocity(self.s.m, self.s.d, mj.mjtObj.mjOBJ_SITE, self.s._paddle_site, self._v, 0)
+ self.out += [(int(k), round(float(np.linalg.norm(self._v[3:])), 3))] * (n - self._n)
+ self._n = n
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/levels.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/levels.py
new file mode 100644
index 0000000000..e68595af64
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/levels.py
@@ -0,0 +1,8 @@
+"""The action-level switch: `high` (the high-level plugin on) or `low` (off: the arm command layer only)."""
+import importlib
+
+
+def plugin(level: str):
+ if level not in ("high", "low"):
+ raise ValueError(f"action level must be high or low, not {level!r}")
+ return importlib.import_module("action_" + level)
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/match.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/match.py
new file mode 100644
index 0000000000..deb2cb9b73
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/match.py
@@ -0,0 +1,886 @@
+"""Core of the table-tennis match service (interactive mode): one game against a scripted opponent, with the duel's
+rules: first to 5 points, from 4:4 a lead of 2, at 6:6 the next point wins (7 at most); the expedite rule (the
+receiver's 13th good return in a rally wins it the point, ITTF 2.15.4) bounds every rally. The opponent serves every
+point, so the agent is always the receiver (the duel's receiver rotation cannot apply: the robot cannot serve).
+
+The robot (Franka + paddle, y < 0) plays a scripted opponent on the far side (y > 0). The opponent is part of the
+world, like the physics: a deterministic function of the simulator state, evaluated inside every control step, so a
+recorded sequence of the robot's joint targets replays the whole match bit-exactly (no schedule is needed).
+
+Point flow (all inside step()):
+ ready READY_STEPS control steps; the next serve is held at its launch state, out of play.
+ serve the opponent serves: a recorded DeepMind serve (bounces on its half, crosses the net, bounces on ours).
+ our leg the ball comes to us (a serve, or the opponent's return). The model decides the shot (live code:
+ swing / adjust decision points); the robot hits or not. The leg is judged like the rally task: exactly one
+ own bounce before the hit, one paddle contact, first contact after the hit other than the net = the
+ opponent's half (a return may touch the net, ITTF 2.7.1). A failed leg = the opponent's point. A serve
+ that touches the net is a let (ITTF 2.9.1.1: no point, the next serve; the recorded serves clear the net
+ by >= 3.9 cm, so this does not happen with the pool).
+ opp leg our return bounced on the opponent's half. The opponent (below) either returns it (a new "our leg"
+ starts at its hit) or misses it (our point once the ball is dead).
+
+The opponent (LEVELS): a kinematic paddle on its end line, at the centre when it serves. `reaction_s` after our hit it
+moves towards the (perfectly predicted) ball at `chase`; after each of its shots it walks back towards the centre at
+`recover`. When the ball reaches the top of its bounce on its half (or y = HIT_Y) it evaluates our shot's pressure
+ pressure = max(|ball x - its paddle x| / reach, (our speed off the paddle - SPEED_FREE) / (max_speed - SPEED_FREE))
+and, deterministically: pressure > 1 -> it misses (our point); > PRESSURE_WEAK -> a weak return (slow, central, no
+spin); < PRESSURE_PASSIVE -> it attacks (its widest, fastest ball, full spin); else a normal return (a seeded target
+within the level's width, its pace, top- or backspin plus a sidespin share). It sets the ball's velocity and spin (an
+impulse; it never touches the ball physically) so that the ball lands on our half and its apex after our bounce is in
+the box the reference stroke returns reliably; an unreachable target moves towards the centre and the pace down.
+It never misses except by the rule above.
+Our strokes scatter: the aim is perturbed by a seeded N(0, EXEC_SIGMA[power]) per shot before the stroke is planned.
+"""
+from __future__ import annotations
+
+import io
+import json
+import os
+import time
+from collections import deque
+from pathlib import Path
+
+import numpy as np
+
+import mujoco as mj
+import rally
+import rcb_tt
+from rally import BallModel, world_spin, hermite # noqa: F401
+from rcb_tt import CONTROL_DT, VEL_LIMIT
+
+HERE = Path(__file__).resolve().parent
+SCENE, INSTANCE = rally.SCENE, rally.INSTANCE
+SERVES = {b["id"]: b for b in json.load(open(HERE / "serves_pool.json"))["serves"]}
+REVISION = "wallclock-5"
+WIN_POINTS = 5 # the duel's format (duel.py): first to 5 ...
+WIN_BY = 2 # ... from 4:4 a lead of 2 ...
+CAP_POINTS = 7 # ... at 6:6 the next point wins
+EXPEDITE_RETURNS = 13 # ITTF 2.15.4: the receiver's (our) 13th good return in a rally wins us the point
+MAX_POINTS_WITH_LETS = 40 # guard: 13 scoring points at most, so this needs 27+ lets; then the player ahead wins,
+ # at a level score the player who won the last point
+READY_STEPS = 80 # 0.8 s between points
+LEG_STEPS = 250 # our leg is lost if nothing decisive happens 2.5 s after it started
+CAM_EVERY = 2 # 50 Hz camera frames
+DECISION_AFTER_OPP_BOUNCE = 5 # serve legs: 5th frame (0.1 s) after the serve bounced on the opponent's half
+DECISION_AFTER_OPP_HIT = 6 # return legs: 6th frame (0.12 s) after the opponent's hit
+ADJUST_FRAMES = 3 # second decision point: 3rd frame (0.06 s) after the ball bounced on our half
+HIT_Y = 1.55
+OPP_Y, OPP_Z = 1.75, 0.22 # where the opponent's paddle is drawn
+SHOULDER = np.array([0.0, -1.75, 0.33])
+APEX_X_MAX = 0.30 # the opponent only plays balls whose apex after our bounce is in the box the reference
+ # stroke returns reliably (|x| <= 0.30, -1.38 <= y <= -1.10, 0.25 <= z <= 0.45)
+rcb_tt.HORIZON = 10 ** 7
+OPP_HALF = rally.OPP_HALF
+
+LEVELS = { # defence: reaction, chase / recovery speed, reach, too-fast threshold; attack: width, pace, spin, sidespin share
+ 1: dict(reaction_s=0.27, chase=0.47, recover=0.33, reach=0.27, max_speed=5.4,
+ width=0.15, pace=4.0, spin=10.0, side=0.0, seed=101),
+ 2: dict(reaction_s=0.25, chase=0.50, recover=0.35, reach=0.29, max_speed=5.6,
+ width=0.22, pace=4.4, spin=20.0, side=0.3, seed=202),
+ 3: dict(reaction_s=0.24, chase=0.53, recover=0.37, reach=0.31, max_speed=5.8,
+ width=0.28, pace=4.9, spin=30.0, side=0.6, seed=303),
+ 4: dict(reaction_s=0.22, chase=0.55, recover=0.40, reach=0.33, max_speed=6.0,
+ width=0.30, pace=5.4, spin=40.0, side=1.0, seed=404),
+}
+SPEED_FREE = 3.8 # our shot's speed off the paddle below this puts no pressure on the opponent
+PRESSURE_WEAK = 0.75 # our shot's pressure above this (but <= 1) -> the opponent only manages a weak return
+PRESSURE_PASSIVE = 0.35 # below this the opponent attacks: its widest, fastest ball with its most spin
+EXEC_SIGMA = {"soft": 0.04, "normal": 0.06, "hard": 0.09} # our stroke's landing scatter (m, per axis)
+POWER = ("soft", "normal", "hard")
+
+
+def match_winner(score):
+ """0 (us) / 1 (opponent) if the game is won at this score [us, opponent], else None (same rule as the duel)."""
+ for i in (0, 1):
+ a, b = score[i], score[1 - i]
+ if a >= CAP_POINTS or (a >= WIN_POINTS and a - b >= WIN_BY):
+ return i
+ return None
+
+
+def towards_own_half(p, v, horizon_s=0.5):
+ """Whether a ball at p moving with v is over our half (y < 0) or its straight-line path reaches it within horizon_s:
+ a ball touching a robot outside this is not obstruction, the shot was going out (the duel's rule)."""
+ for t in np.linspace(0.0, horizon_s, 26):
+ x, y = p[0] + v[0] * t, p[1] + v[1] * t
+ if abs(x) <= 0.7625 and -1.37 <= y <= 0.0:
+ return True
+ return False
+
+
+def ball_state(d):
+ return d.qpos[0:3].copy(), d.qvel[0:3].copy(), world_spin(d)
+
+
+class Match(rally.Rally):
+ """The match. Live: run_to_decision() / shot() / adjust(). Replay: replay(actions)."""
+
+ def __init__(self, level: int = 1, lv_override: dict | None = None):
+ self.level = int(level)
+ self.lv = dict(LEVELS.get(self.level, LEVELS[1]))
+ if lv_override:
+ self.lv.update(lv_override)
+ if os.environ.get("MATCH_SEED"): # other instances of the same level: serves + opponent + scatter
+ self.lv["seed"] = int(os.environ["MATCH_SEED"])
+ self.s = rcb_tt.Session(instance=str(INSTANCE), scene=str(SCENE))
+ self.bm = BallModel()
+ self._twin = None
+ self._ik_seed = None
+ self._planned_hit = None
+ rng = np.random.default_rng(self.lv["seed"])
+ ids = sorted(SERVES)
+ self.serve_ids = [int(x) for x in rng.choice(ids, size=2 * CAP_POINTS - 1, replace=False)]
+ self.score = [0, 0] # [robot, opponent]
+ self.points: list[dict] = [] # per point: winner, how, legs
+ self.legs: list[dict] = [] # every leg of the match (ours and the opponent's shots)
+ self.results: list[dict] = [] # our legs' results (rally-style)
+ self.shots: list[dict] = []
+ self.hist: deque = deque(maxlen=12) # recent camera snapshots for the views
+ self.frames: list[dict] = [] # (internal) ball camera frames of the current leg, for timing only
+ self.done = False
+ self.winner = None # 0 us, 1 the opponent (set when the game ends)
+ self.phase = "swing"
+ self.plan, self.plan_j, self._rec = [], 0, {}
+ self.contact_k = 0
+ self.n_our_legs = 0 # every ball that came to us (also the per-leg RNG streams)
+ self.n_our_shots = 0 # our shots: legs in which our paddle touched the ball
+ self.i = 0
+ self._start_point(hold_from=0)
+
+ # ------------------------------------------------------------------ point / leg bookkeeping
+ def _start_point(self, hold_from: int):
+ n = len(self.points)
+ sid = self.serve_ids[n % len(self.serve_ids)]
+ self.point_returns = 0 # our good returns in this rally (expedite rule)
+ self.leg = {"kind": "serve", "serve": sid, "point": n, "hold_from": hold_from,
+ "launch": hold_from + READY_STEPS, "state": "incoming"}
+ self.legs.append(self.leg)
+ b = SERVES[sid]
+ self.opp = {"x0": 0.0, "k0": self.leg["launch"], "tx": 0.0, "plan_k": None, # ready at the centre
+ "speed": self.lv["recover"]}
+ self._new_leg_bookkeeping()
+ self._park()
+
+ def _new_leg_bookkeeping(self):
+ self.frames = []
+ s = self.s
+ s._events.clear(); s._last_touch.clear(); s._robot_table = 0; s._v_out = None
+ self.i = self.n_our_legs
+
+ def _park(self):
+ b = SERVES[self.leg["serve"]]
+ d = self.s.d
+ d.qpos[0:3] = b["pos"]; d.qpos[3:7] = [1, 0, 0, 0]; d.qvel[0:3] = b["vel"]; d.qvel[3:6] = b["spin"]
+
+ def _cur(self) -> dict:
+ return self.leg
+
+ def in_play(self) -> bool:
+ return self.k > self.leg["launch"]
+
+ def t_since_launch(self) -> float:
+ return round((self.k - self.leg["launch"]) * CONTROL_DT, 6)
+
+ # ------------------------------------------------------------------ the opponent
+ def opp_x(self, k=None) -> float:
+ k = self.k if k is None else k
+ o = self.opp
+ dt = max(0.0, (k - o["k0"]) * CONTROL_DT)
+ dx = o["tx"] - o["x0"]
+ step = min(abs(dx), o.get("speed", self.lv["recover"]) * dt)
+ return float(o["x0"] + np.sign(dx) * step)
+
+ def _opp_move(self, tx: float):
+ self.opp = {"x0": self.opp_x(), "k0": self.k, "tx": float(tx), "plan_k": self.opp.get("plan_k"),
+ "speed": self.lv["chase"]}
+
+ def _predict_opp_hit(self):
+ """Where the ball will be when the opponent hits it (ball-only model, true state)."""
+ p, v, w = ball_state(self.s.d)
+ P, V, _, _ = self.bm.rollout(p, v, w, 1500)
+ bounced = False
+ for i in range(1, len(P)):
+ if not bounced and P[i, 1] > 0 and P[i, 2] < 0.03 and V[i, 2] > 0:
+ bounced = True
+ if bounced and (V[i, 2] <= 0 or P[i, 1] >= HIT_Y):
+ return P[i]
+ return P[-1]
+
+ def _opp_return(self, p_hit, mode="normal"):
+ """Opponent's shot from p_hit: (v, w, target, pace). normal: a seeded target within the level's width, its pace
+ and spin (top- or backspin, plus a sidespin share); attack: its widest and fastest ball with full spin; weak:
+ a slow, central, spinless ball (a chance for us). Only balls whose apex after our bounce is in the reliably
+ returnable box are played; otherwise the target moves towards the centre and the pace down."""
+ lv = self.lv
+ rng = np.random.default_rng([lv["seed"], len(self.points), len(self.legs)])
+ u = rng.uniform(-1, 1, 5)
+ if mode == "weak":
+ tx, ty, pace = 0.08 * u[0], -0.6 + 0.1 * u[1], 3.7
+ w = np.zeros(3)
+ else:
+ width = lv["width"] * (1.0 if mode == "attack" else abs(u[0]) ** 0.5)
+ tx = float(np.sign(u[0]) or 1.0) * width
+ ty = -0.6 + 0.15 * u[1]
+ pace = lv["pace"] + (0.5 if mode == "attack" else 0.0)
+ mag = lv["spin"] * (1.0 if mode == "attack" else 0.5 + 0.5 * abs(u[2]))
+ sgn = 1.0 if u[3] > -0.4 else -1.0 # 70 % topspin, 30 % backspin
+ w = np.array([sgn * mag, 0.0, lv["side"] * mag * u[4]])
+ if "explore" in lv: # calibration only: random pace / spin
+ pace = float(rng.uniform(3.6, lv.get("pace_max", 5.0)))
+ sm = lv.get("spin_max", 15.0)
+ w = np.array([float(rng.uniform(-sm, sm)), 0.0, float(rng.uniform(-sm, sm)) * lv.get("side", 0.0)])
+ tx = float(u[0]) * lv["width"]
+ # Search depth as well as width before weakening a nominal shot. Every return is checked.
+ candidates = 0
+ nominal_w = w.copy()
+ for relax in (1.0, .75, .5, 0.0):
+ for dp in (0.0, -.4, .4):
+ for depth in (ty, -.45, -.75, -.3, -.9):
+ candidates += 1
+ target = np.array([tx*relax, depth])
+ speed = max(3.6, pace+dp)
+ spin = nominal_w*relax
+ v = self._solve_shot(p_hit, target, speed, spin)
+ if v is not None and self._reachable(p_hit, v, spin):
+ self._return_search = {"candidates": candidates, "relax": relax,
+ "nominal_pace": pace, "nominal_target_x": tx}
+ return v, spin, target.tolist(), speed
+ raise RuntimeError("opponent solver could not construct a legal reachable return")
+
+ def _solve_shot(self, p0, target, pace, w):
+ """Newton on (vx, vz) with vy = -pace so that the ball-only flight lands at `target` and clears the net."""
+ flight = max(.15, abs(target[1]-p0[1])/pace*1.12)
+ v = np.array([(target[0]-p0[0])/flight, -pace,
+ (rally.BALL_R-p0[2]+.5*9.81*flight**2)/flight])
+ for _ in range(12):
+ L, ok = self._landing(p0, v, w)
+ if L is None:
+ v[2] += 0.4
+ continue
+ err = L - target
+ if np.linalg.norm(err) < 0.01:
+ return v if ok else None
+ J = np.zeros((2, 2))
+ for c, idx in enumerate((0, 2)):
+ dv = np.zeros(3); dv[idx] = 2e-2
+ L2, _ = self._landing(p0, v + dv, w)
+ if L2 is None:
+ return None
+ J[:, c] = (L2 - L) / 2e-2
+ try:
+ dx = np.linalg.lstsq(J, err, rcond=None)[0]
+ except np.linalg.LinAlgError:
+ return None
+ dx = np.clip(dx, -0.8, 0.8)
+ v[0] -= dx[0]; v[2] -= dx[1]
+ return None
+
+ def _landing(self, p0, v, w):
+ """First table contact on our half (interpolated to the ball-radius height) and whether the flight clears
+ the net by >= 3 cm; None if the first contact is anything else."""
+ P, _, _, first = self.bm.rollout(p0, v, w, 1500, stop_at_contact=True)
+ if not first or first[1] != "table_own" or len(P) < 3:
+ return None, False
+ a, b = P[-3], P[-2]
+ z0 = rally.BALL_R
+ f = 0.0 if abs(a[2] - b[2]) < 1e-9 else float(np.clip((a[2] - z0) / (a[2] - b[2]), 0.0, 2.0))
+ L = a[:2] + f * (b[:2] - a[:2])
+ i0 = int(np.argmin(np.abs(P[:, 1])))
+ clear = P[i0, 2] > 0.1525 + 0.02 + 0.03
+ return L, bool(clear)
+
+ def _reachable(self, p0, v, w) -> bool:
+ P, V, _, _ = self.bm.rollout(p0, v, w, 1500)
+ bounced = False
+ for i in range(1, len(P)):
+ if not bounced:
+ if P[i, 2] < 0.03 and V[i, 2] > 0 and P[i, 1] < 0:
+ bounced = True
+ continue
+ if V[i, 2] <= 0:
+ a = P[i]
+ return bool(.17 <= a[2] <= .65 and -1.55 <= a[1] <= -.90 and abs(a[0]) <= .45
+ and np.linalg.norm(a-SHOULDER) <= .82)
+ return False
+
+ # ------------------------------------------------------------------ stepping (shared by live and replay)
+ def step(self, q):
+ self.s.step(q)
+ leg = self.leg
+ if leg["kind"] == "serve" and self.k <= leg["launch"]:
+ self._park()
+ else:
+ self._referee()
+ if self.k % CAM_EVERY == 0:
+ d = self.s.d
+ self.hist.append({"k": self.k, "t": self.t_since_launch(), "qpos": d.qpos.copy(), "opp_x": self.opp_x(),
+ "leg_id": len(self.legs)-1, "wall_mono": time.monotonic()})
+ if self.in_play() and leg["state"] == "incoming":
+ p = d.qpos[0:3]
+ self.frames.append({"t": self.t_since_launch(), "pos": [float(x) for x in p]})
+
+ def _leg_verdict(self):
+ return rcb_tt.judge(self.s._events, OPP_HALF, robot_env_contact=self.s._robot_table)
+
+ def _referee(self):
+ if self.done:
+ return
+ leg, d = self.leg, self.s.d
+ kinds = [e["kind"] for e in self.s._events]
+ p = d.qpos[0:3]
+ dead = any(x in ("floor", "robot", "other") for x in kinds) or p[2] < -0.3 or abs(p[1]) > 2.8 or abs(p[0]) > 2.5
+ if (leg["state"] in ("incoming", "to_opp") and self.opp.get("plan_k") is not None
+ and self.k >= self.opp["plan_k"]):
+ leg["opp_x_react"] = round(self.opp_x(), 3) # the opponent reacts `reaction_s` after our hit
+ self._opp_move(self._predict_opp_hit()[0])
+ self.opp["plan_k"] = None
+ if leg["state"] == "incoming":
+ if leg["kind"] == "serve" and "net" in (kinds[:kinds.index("paddle")] if "paddle" in kinds else kinds):
+ self._end_point(winner=None, how="let: the serve touched the net")
+ return
+ if leg["kind"] == "return" and "robot" in kinds and "paddle" not in kinds and "table_own" not in kinds:
+ e = next(x for x in self.s._events if x["kind"] == "robot")
+ if not towards_own_half(e["pos"], e["vel_pre"]): # as in the duel (ITTF 2.10.1.4 vs 2.10.1.6)
+ self._end_point(winner=0, how="the opponent's shot went out (it passed your half and hit your robot)")
+ return
+ post = kinds[kinds.index("paddle") + 1:] if "paddle" in kinds else []
+ post = [x for x in post if x not in ("paddle", "net")] # a return may touch the net (ITTF 2.7.1)
+ if "paddle" in kinds and self.opp.get("plan_k") is None and "paddle_t" not in leg:
+ ip = next(e for e in self.s._events if e["kind"] == "paddle")
+ leg["paddle_t"] = ip["t"]
+ self.opp["plan_k"] = int(round(ip["t"] / CONTROL_DT)) + int(round(self.lv["reaction_s"] / CONTROL_DT))
+ if post or dead or self.k - leg["launch"] >= LEG_STEPS:
+ v = self._leg_verdict()
+ ok = bool(v["success"]) and not dead
+ self._close_our_leg(v, ok)
+ if ok:
+ self.point_returns += 1
+ if ok and self.point_returns >= EXPEDITE_RETURNS:
+ self._end_point(winner=0, how=f"you made {EXPEDITE_RETURNS} good returns as the receiver "
+ "(expedite rule)")
+ elif ok:
+ leg["state"] = "to_opp"
+ else:
+ self._end_point(winner=1, how=self.results[-1]["summary"])
+ return
+ if leg["state"] == "to_opp":
+ v = d.qvel[0:3]
+ bounced = kinds.count("table_opp") >= 1
+ if bounced and p[1] > 0 and (v[2] <= 0 or p[1] >= HIT_Y) and p[2] > 0.05:
+ self._opp_hit()
+ elif dead or self.k - leg["launch"] >= 2 * LEG_STEPS:
+ self._end_point(winner=0, how=leg.get("opp_miss", "the opponent could not reach the ball"))
+ return
+ if leg["state"] == "opp_missed":
+ if dead or self.k - leg["opp_k"] >= 60:
+ self._end_point(winner=0, how=leg["opp_miss"])
+
+ def _opp_hit(self):
+ d = self.s.d
+ p, v, w = ball_state(d)
+ ox = self.opp_x()
+ vo = self.leg.get("v_out")
+ speed = float(np.linalg.norm(vo)) if vo is not None else float(np.linalg.norm(v)) # our shot's pace off the paddle
+ gap = abs(float(p[0]) - ox)
+ rec = {"k": self.k, "ball_x": round(float(p[0]), 3), "opp_x": round(ox, 3), "gap": round(gap, 3),
+ "speed": round(speed, 3)}
+ self.leg["opp"] = rec
+ rec["t_flight"] = round((self.k - int(round(self.leg.get("paddle_t", 0) / CONTROL_DT))) * CONTROL_DT, 3) if self.leg.get("paddle_t") else None
+ rec["opp_x_at_react"] = self.leg.get("opp_x_react")
+ pressure = max(gap / self.lv["reach"], (speed - SPEED_FREE) / (self.lv["max_speed"] - SPEED_FREE))
+ rec["pressure"] = round(pressure, 3)
+ if pressure > 1.0:
+ why = (f"too wide: the ball passed {gap:.2f} m from the opponent's paddle (its reach {self.lv['reach']:.2f} m)"
+ if gap > self.lv["reach"] else
+ f"too fast: {speed:.1f} m/s off your paddle (it handles up to {self.lv['max_speed']:.1f} m/s)")
+ self.leg["state"] = "opp_missed"; self.leg["opp_miss"] = why; self.leg["opp_k"] = self.k
+ rec["missed"] = why
+ return
+ mode = "weak" if pressure > PRESSURE_WEAK else ("attack" if pressure < PRESSURE_PASSIVE else "normal")
+ rec["mode"] = mode
+ try:
+ vo, wo, target, pace = self._opp_return(p, mode)
+ except RuntimeError: # no legal return from where it met the ball: the opponent misses it
+ why = "the opponent could not play a legal return from where it met the ball"
+ self.leg["state"] = "opp_missed"; self.leg["opp_miss"] = why; self.leg["opp_k"] = self.k
+ rec["missed"] = why
+ return
+ rec.update(target=[round(x, 3) for x in target], pace=pace, spin=[float(x) for x in wo],
+ search=dict(self._return_search))
+ R = np.zeros(9); mj.mju_quat2Mat(R, d.qpos[3:7])
+ d.qvel[0:3] = vo
+ d.qvel[3:6] = R.reshape(3, 3).T @ wo
+ self.leg["state"] = "done"
+ self.opp = {"x0": ox, "k0": self.k, "tx": 0.0, "plan_k": None, "speed": self.lv["recover"]}
+ self.leg = {"kind": "return", "point": len(self.points), "launch": self.k, "state": "incoming",
+ "opp_hit_x": round(float(p[0]), 3)}
+ self.legs.append(self.leg)
+ self._new_leg_bookkeeping()
+
+ def _close_our_leg(self, v, ok):
+ kinds = [e["kind"] for e in self.s._events]
+ vo = self.s._v_out
+ self.leg["v_out"] = None if vo is None else [float(x) for x in vo]
+ res = {"leg": self.n_our_legs, "point": len(self.points), "kind": self.leg["kind"], "returned": ok,
+ "speed_out": None if vo is None else round(float(np.linalg.norm(vo)), 2),
+ "hit": int(v["hit"]), "landing_x": round(float(v["landing_x"]), 3),
+ "landing_y": round(float(v["landing_y"]), 3), "events": kinds, "step": self.k}
+ if ok:
+ res["summary"] = f"returned: landed on the opponent's half at x={v['landing_x']:.2f}, y={v['landing_y']:.2f}"
+ elif not v["hit"]:
+ res["summary"] = "missed: no paddle contact"
+ elif v["robot_env_contact"]:
+ res["summary"] = "fault: the arm or paddle touched the table/net/floor"
+ elif v["n_paddle_contacts"] != 1:
+ res["summary"] = "fault: more than one paddle contact"
+ elif v["own_bounces_before_hit"] != 1:
+ res["summary"] = "fault: hit before the ball bounced on your half (volley)"
+ elif v["landed"]:
+ nxt = kinds[kinds.index("paddle") + 1:]
+ nxt = [x for x in nxt if x not in ("paddle", "net")]
+ where = {"table_own": "your own half", "floor": "the floor (out)"}.get(nxt[0], nxt[0]) if nxt else "?"
+ via = " (after touching the net)" if v["net_touch"] else ""
+ res["summary"] = f"fault: after your hit the ball hit {where}{via} (x={v['landing_x']:.2f}, y={v['landing_y']:.2f})"
+ else:
+ res["summary"] = "fault: after your hit the ball flew out without touching the table"
+ if ok and v["net_touch"]:
+ res["summary"] += " after touching the net"
+ res["net_touch"] = int(v["net_touch"])
+ self.results.append(res)
+ self.n_our_legs += 1
+ self.n_our_shots += int(bool(v["hit"]))
+ res["shot"] = self.n_our_shots if v["hit"] else None
+
+ def _end_point(self, winner: int | None, how: str):
+ if winner is not None: # None: a let (no point scored, the next serve)
+ self.score[winner] += 1
+ self.points.append({"point": len(self.points), "how": how,
+ "winner": "you" if winner == 0 else "opponent" if winner == 1 else "let",
+ "score": list(self.score), "step": self.k, "serve": self.legs[-1].get("serve")
+ if self.legs[-1]["kind"] == "serve" else None})
+ self.review_hist = list(self.hist)
+ self.review_hist.append({"k": self.k, "t": self.t_since_launch(), "qpos": self.s.d.qpos.copy(),
+ "opp_x": self.opp_x(), "leg_id": len(self.legs)-1, "wall_mono": time.monotonic()})
+ self.leg["state"] = "done"
+ w = match_winner(self.score)
+ if w is None and len(self.points) >= MAX_POINTS_WITH_LETS: # guard (never reached in practice)
+ w = (0 if self.score[0] > self.score[1] else 1 if self.score[1] > self.score[0] else
+ next((0 if p["winner"] == "you" else 1) for p in reversed(self.points) if p["winner"] != "let"))
+ if w is not None:
+ self.winner = w
+ self.done = True
+ return
+ self.hist.clear()
+ self._start_point(hold_from=self.k)
+
+ def replay(self, actions) -> None:
+ for q in actions:
+ self.step(q)
+
+ # ------------------------------------------------------------------ live control
+ def _arm_target(self):
+ if self.plan_j < len(self.plan):
+ q = self.plan[self.plan_j]; self.plan_j += 1
+ return q
+ return self._ready_target()
+
+ def decision_due(self) -> bool:
+ leg = self.leg
+ if self.done or leg["state"] != "incoming" or not self.in_play():
+ return False
+ ev = self.s._events
+ if any(e["kind"] == "paddle" for e in ev):
+ return False
+ n_frames = len(self.frames)
+ if self.phase == "swing":
+ if leg["kind"] == "serve":
+ b = [e for e in ev if e["kind"] == "table_opp"]
+ if not b:
+ return False
+ t_b = b[0]["t"] - leg["launch"] * CONTROL_DT
+ return sum(1 for f in self.frames if f["t"] > t_b) >= DECISION_AFTER_OPP_BOUNCE
+ return n_frames >= DECISION_AFTER_OPP_HIT
+ b = [e for e in ev if e["kind"] == "table_own"]
+ if not b:
+ return False
+ t_b = b[0]["t"] - leg["launch"] * CONTROL_DT
+ return sum(1 for f in self.frames if f["t"] > t_b) >= ADJUST_FRAMES
+
+ def run_to_decision(self) -> None:
+ """Advance (arm: rest of the plan, then back to ready) until the next decision point or the match end."""
+ self.phase = "swing"
+ while not self.done:
+ if self.decision_due():
+ return
+ self.step(self._arm_target())
+
+ def shot(self, decision: dict, delay_steps: int) -> dict:
+ leg_i = self.n_our_legs
+ rec = {"leg": leg_i, "decision": decision, "delay_steps": int(delay_steps), "k_decision": self.k}
+ for _ in range(delay_steps):
+ if self.leg["state"] != "incoming" or self.done:
+ break
+ self.step(self._arm_target())
+ rec["k_exec"] = self.k
+ self._ik_seed = None
+ if decision.get("type") == "swing" and self.leg["state"] == "incoming" and not self.done:
+ if "normal" in decision:
+ self.plan, info = self.plan_paddle(float(decision["t"]), decision["pos"], decision["normal"], decision["vel"])
+ else:
+ self.plan, info = self.plan_stroke(float(decision["t"]), np.asarray(decision["pos"], float),
+ np.asarray(decision.get("aim", rally.AIM_DEFAULT), float),
+ decision.get("power", "normal"))
+ self.plan_j = 0
+ rec.update(info)
+ self._rec = rec
+ if decision.get("type") == "swing":
+ self.phase = "adjust"
+ while not self.done and self.n_our_legs == leg_i:
+ if self.decision_due():
+ return {"phase": "adjust", **{k: rec[k] for k in rec if k != "decision"}}
+ self.step(self._arm_target())
+ return self._after_leg(rec, leg_i)
+
+ def adjust(self, decision: dict, delay_steps: int) -> dict:
+ rec, leg_i = self._rec, self.n_our_legs
+ rec["adjust"] = decision
+ rec["adjust_delay_steps"] = int(delay_steps)
+ for _ in range(delay_steps):
+ if self.n_our_legs != leg_i or self.done:
+ break
+ self.step(self._arm_target())
+ self._ik_seed = self._planned_hit
+ if decision.get("type") == "adjust" and self.n_our_legs == leg_i and not self.done and "normal" in decision:
+ plan, info = self.plan_paddle(float(decision["t"]), decision["pos"], decision["normal"], decision["vel"])
+ rec["adjust_info"] = info
+ if plan:
+ self.plan, self.plan_j = plan, 0
+ elif decision.get("type") == "adjust" and self.n_our_legs == leg_i and not self.done:
+ plan, info = self.plan_stroke(float(decision["t"]), np.asarray(decision["pos"], float),
+ np.asarray(decision.get("aim", rec.get("aim", rally.AIM_DEFAULT)), float),
+ decision.get("power", rec.get("power", "normal")))
+ rec["adjust_info"] = info
+ if plan:
+ self.plan, self.plan_j = plan, 0
+ return self._after_leg(rec, leg_i)
+
+ def _after_leg(self, rec, leg_i) -> dict:
+ n0 = len(self.points)
+ while not self.done and self.n_our_legs == leg_i:
+ self.step(self._arm_target())
+ self.shots.append(rec)
+ res = dict(self.results[leg_i]) if leg_i < len(self.results) else {"summary": "match over"}
+ self.run_to_decision()
+ res["points_finished"] = self.points[n0:]
+ return res
+
+ # ------------------------------------------------------------------ stroke controller (rally's, + power)
+ def plan_stroke(self, t_hit, p_hit, aim, power="normal"):
+ """The rally's stroke controller, plus (a) a pace choice and (b) up to 3 full rehearsals of the stroke on a
+ twin simulator from the current state (arm + the real ball): the aim point is corrected by the rehearsed
+ landing error. The rehearsal uses the player's contact time/point as given: a wrong contact misses in the
+ rehearsal too and is not corrected."""
+ self._power = power if power in POWER else "normal"
+ aim = np.asarray(aim, float)
+ rng = np.random.default_rng([self.lv["seed"], 7, self.n_our_legs]) # one draw per shot (adjust reuses it)
+ aim = aim + rng.normal(0.0, EXEC_SIGMA[self._power], 2)
+ aim_eff = aim.copy()
+ seed = self._ik_seed
+ best = None
+ for it in range(4):
+ self._ik_seed = seed
+ tg, info = rally.Rally.plan_stroke(self, t_hit, p_hit, aim_eff)
+ if not tg:
+ return tg, info
+ L, speed = self._rehearse(tg)
+ err = None if L is None else float(np.linalg.norm(np.asarray(L) - aim))
+ if best is None or (err is not None and (best[2] is None or err < best[2])):
+ best = (tg, info, err, L, speed)
+ if L is None or err < 0.04:
+ break
+ aim_eff = aim_eff + (aim - np.asarray(L))
+ tg, info, err, L, speed = best
+ info["power"] = self._power
+ info["rehearsal_landing"] = None if L is None else [round(float(x), 3) for x in L]
+ info["rehearsal_speed"] = None if speed is None else round(float(speed), 2)
+ return tg, info
+
+ def _rehearse(self, targets):
+ """Run `targets` on the twin from the full current state (arm and ball); (landing xy of the first contact
+ after the paddle, outgoing speed) or (None, None) if the paddle never touches the ball."""
+ tw = self._twin_session()
+ m, d = tw.m, tw.d
+ mj.mj_resetData(m, d)
+ d.qpos[:] = self.s.d.qpos; d.qvel[:] = self.s.d.qvel; d.qacc_warmstart[:] = self.s.d.qacc_warmstart
+ d.time = self.s.d.time
+ mj.mj_forward(m, d)
+ tw._target = self.s._target.copy(); tw._k = 0; tw._events = []; tw._last_touch = {}
+ tw._robot_table = 0; tw._v_out = None; tw._actions = []
+ for j in range(len(targets) + 150):
+ tw.step(targets[j] if j < len(targets) else targets[-1])
+ kinds = [e["kind"] for e in tw._events]
+ if "paddle" in kinds:
+ post = [e for e in tw._events[kinds.index("paddle") + 1:] if e["kind"] not in ("paddle", "net")]
+ if post:
+ sp = None if tw._v_out is None else float(np.linalg.norm(tw._v_out))
+ return post[0]["pos"][:2], sp
+ if d.qpos[2] < -0.3:
+ break
+ return None, None
+
+ def _pick_stroke(self, cands):
+ good = ([c for c in cands if c["ik"] < 1e-3 and c["ratio"] <= 1.0] or [c for c in cands if c["ik"] < 1e-3]
+ or cands)
+ power = getattr(self, "_power", "normal")
+ if power == "normal":
+ return min(good, key=lambda c: c["ratio"])
+ sp = sorted(good, key=lambda c: float(np.linalg.norm(c["v_out"])))
+ return sp[-1] if power == "hard" else sp[0]
+
+ # ------------------------------------------------------------------ views
+ CAMS = (([0.0, 0.30, 0.05], 3.6, 72.0, -33.0), # behind and above the robot, looking down the table
+ ([0.0, 0.05, 0.25], 4.0, 0.0, -8.0)) # from the side
+ # world poses of the two cameras as rendered (OpenGL: forward = view direction, image right = forward x up);
+ # pinhole, vertical field of view 45 deg, tiles 480 x 360 px -> focal length 434.6 px, principal point at the centre
+ # (wall-clock tasks: the positions are the centre of MuJoCo's two stereo eye cameras, which is what the mono render
+ # uses; the lock-step tasks' spec gave scene.camera[0], the left eye, 3.4 cm (ipd / 2) to the left: ~4-7 px off)
+ CAM_INFO = [{"name": "behind", "position": [-0.933, -2.5714, 2.0107], "forward": [0.2592, 0.7976, -0.5446],
+ "up": [0.1683, 0.518, 0.8387]},
+ {"name": "side", "position": [-3.9611, 0.05, 0.8067], "forward": [0.9903, 0.0, -0.1392],
+ "up": [0.1392, 0.0, 0.9903]}]
+ VIEW_BACK = (0, 2, 4, 6) # camera frames back from the latest: 0, 40, 80, 120 ms
+
+ def _extra_geoms(self, scn, opp_x):
+ def add(typ, size, pos, rgba, mat=np.eye(3)):
+ if scn.ngeom >= scn.maxgeom:
+ return
+ mj.mjv_initGeom(scn.geoms[scn.ngeom], typ, np.asarray(size, float), np.asarray(pos, float),
+ np.asarray(mat, float).ravel(), np.asarray(rgba, np.float32))
+ scn.ngeom += 1
+ # opponent: red paddle + a grey body behind it
+ add(mj.mjtGeom.mjGEOM_BOX, [0.075, 0.008, 0.075], [opp_x, OPP_Y, OPP_Z], [0.85, 0.1, 0.1, 1])
+ add(mj.mjtGeom.mjGEOM_CAPSULE, [0.14, 0.30, 0], [opp_x, OPP_Y + 0.35, 0.30], [0.35, 0.35, 0.4, 1])
+ # scale marks every 0.25 m along both side edges of the table and along both end lines
+ for y in np.arange(-1.25, 1.26, 0.25):
+ for x in (-0.7625, 0.7625):
+ add(mj.mjtGeom.mjGEOM_BOX, [0.03, 0.006, 0.002], [x, y, 0.002], [1, 0.9, 0.1, 1])
+ for x in np.arange(-0.75, 0.76, 0.25):
+ for y in (-1.37, 1.37):
+ add(mj.mjtGeom.mjGEOM_BOX, [0.006, 0.03, 0.002], [x, y, 0.002], [1, 0.9, 0.1, 1])
+
+ def render_views(self, width=480, height=360) -> bytes:
+ """PNG: 2 rows (behind-the-robot camera, side camera) x 4 columns (oldest -> latest camera frame, 40 ms
+ apart), each tile stamped with its time since the current ball was played."""
+ import imageio.v2 as imageio
+ from PIL import Image, ImageDraw
+ if not hasattr(self, "_renderer"):
+ self._renderer = mj.Renderer(self.s.m, height=height, width=width)
+ self._rd = mj.MjData(self.s.m)
+ self._cams = []
+ for lookat, dist, az, el in self.CAMS:
+ c = mj.MjvCamera(); c.lookat[:] = lookat; c.distance = dist; c.azimuth = az; c.elevation = el
+ self._cams.append(c)
+ r, rd = self._renderer, self._rd
+ hist = list(self.hist)
+ snaps = [hist[max(0, len(hist) - 1 - b)] for b in reversed(self.VIEW_BACK)]
+ rows = []
+ for c in self._cams:
+ tiles = []
+ for sn in snaps:
+ rd.qpos[:] = sn["qpos"]; mj.mj_forward(self.s.m, rd)
+ r.update_scene(rd, camera=c)
+ self._extra_geoms(r.scene, sn["opp_x"])
+ im = Image.fromarray(r.render())
+ ImageDraw.Draw(im).text((6, 4), f"t={sn['t']:.2f}s", fill=(255, 255, 255))
+ tiles.append(np.asarray(im))
+ rows.append(np.concatenate(tiles, axis=1))
+ buf = io.BytesIO()
+ imageio.imwrite(buf, np.concatenate(rows, axis=0), format="png")
+ return buf.getvalue()
+
+ def view_times(self):
+ hist = list(self.hist)
+ return [hist[max(0, len(hist) - 1 - b)]["t"] for b in reversed(self.VIEW_BACK)]
+
+ def decision_observation(self) -> dict:
+ st = self.s.state()
+ leg = self.leg
+ heard = [{"event": {"table_opp": "bounce on the opponent's half", "table_own": "bounce on your half",
+ "net": "net"}.get(e["kind"], e["kind"]),
+ "t": round(e["t"] - leg["launch"] * CONTROL_DT, 3)} for e in self.s._events]
+ return {"score": {"you": self.score[0], "opponent": self.score[1]}, "point": len(self.points) + 1,
+ "ball": "serve" if leg["kind"] == "serve" else "opponent's return",
+ "t_since_played": self.t_since_launch(),
+ "heard": heard, "view_times": self.view_times(),
+ "q": st["q"].round(4).tolist(), "paddle_pos": st["paddle_pos"].round(3).tolist(),
+ "paddle_normal": st["paddle_normal"].round(3).tolist()}
+
+ # ------------------------------------------------------------------ real-time control (observe / act / wait)
+ # The real-time protocol has no decision points: the world advances only through the agent's calls, each of which
+ # first costs its latency (the service decides how many control steps; see server.py). Between calls the arm keeps
+ # executing its current command: the rest of its planned stroke, then the speed-limited return to the ready pose.
+ def rt_advance(self, n_steps: int):
+ """Run up to n_steps control steps with the arm's current command. Stops early when a point ends (the world is
+ then static until the review) or the match is over. Returns (steps run, points finished, our shot results)."""
+ n0, r0, n = len(self.points), len(self.results), 0
+ while n < n_steps and not self.done and len(self.points) == n0:
+ self.step(self._arm_target()); n += 1
+ if len(self.points) > n0:
+ self.plan, self.plan_j = [], 0 # a new point: no stroke carries over; the arm returns to ready
+ return n, self.points[n0:], self.results[r0:]
+
+ def rt_act(self, T: float, pos, nrm, vel) -> dict:
+ """Replace the arm's command: the paddle state at contact T s from now (scheme B, no ball state). The swing is
+ planned from the arm's current state, so a new `act` corrects the one under way."""
+ t_hit = (self.k - self.leg["launch"]) * CONTROL_DT + float(T)
+ self._ik_seed = self._planned_hit if self.plan_j < len(self.plan) else None
+ plan, info = self.plan_paddle(t_hit, pos, nrm, vel)
+ info["T_from_now"] = round(float(T), 4)
+ if plan:
+ self.plan, self.plan_j = plan, 0
+ self.shots.append({"k": self.k, "leg": self.n_our_legs, **{k: info[k] for k in info if k != "paddle_vel_delivered"}})
+ if plan:
+ self.contact_k = self.k + info["n_swing_steps_available"]
+ self._last_act = info
+ return info
+
+ def rt_clear(self) -> None:
+ self.plan, self.plan_j = [], 0
+ self._last_act = None
+ self.contact_k = self.k
+
+ # ------------------------------------------------------------------ paddle-level stroke (scheme B)
+ PADDLE_SCATTER = dict(pos=0.004, ang_deg=0.6, speed=0.02) # execution scatter of the paddle state at contact
+
+ def _ik_best(self, pos, normal, preferred=None):
+ """Choose an accurate branch the arm can reach with little joint travel.
+
+ A precise pose on the far side of a joint's range can take longer than the
+ entire incoming flight. Preserve cheap local solves for nearby commands;
+ otherwise compare deterministic starts using joint-speed-normalized travel.
+ """
+ s = self.s
+ first = preferred if preferred is not None else s.d.qpos[s._qadr]
+ best = self._ik(pos, normal, first)
+ def travel(candidate):
+ return float(np.max(np.abs(candidate[0] - s._target) / VEL_LIMIT))
+ def rank(candidate):
+ return (0, travel(candidate)) if candidate[1] < 1e-4 else (1, candidate[1])
+ if best[1] < 1e-4 and travel(best) <= .35:
+ return best
+ if not hasattr(self, "_ik_starts"):
+ rng = np.random.default_rng(0)
+ q0 = s.inst["q0"]
+ self._ik_starts = [q0] + [np.clip(q0+rng.normal(0, .8, 7), s.JOINT_LOW+.05, s.JOINT_HIGH-.05)
+ for _ in range(12)]
+ for seed in self._ik_starts:
+ if np.array_equal(seed, first):
+ continue
+ candidate = self._ik(pos, normal, seed)
+ if rank(candidate) < rank(best):
+ best = candidate
+ if best[1] < 1e-4 and travel(best) <= .35:
+ break
+ return best
+
+ def plan_paddle(self, t_hit, p_c, nrm, v_p):
+ """Scheme B: the player gives the paddle state at contact (time t_hit s after the ball was played, blade-centre
+ position p_c, blade face normal nrm, blade velocity v_p). The controller only makes the arm deliver it: IK,
+ a speed-weighted Jacobian inverse, a joint-speed-limited cubic swing and robot-only rehearsals (no ball) that
+ correct the PD controller's lag. It uses no ball state and does not aim."""
+ s = self.s
+ p_c = np.asarray(p_c, float); nrm = np.asarray(nrm, float); nrm = nrm / np.linalg.norm(nrm)
+ v_p = np.asarray(v_p, float)
+ info = {"t_hit": t_hit, "paddle_pos": p_c.round(4).tolist(), "paddle_normal": nrm.round(4).tolist(),
+ "paddle_vel": v_p.round(3).tolist()}
+ k_hit = self._cur()["launch"] + int(round(t_hit / CONTROL_DT))
+ n_avail = k_hit - self.k
+ info["n_swing_steps_available"] = int(n_avail)
+ if n_avail < 1:
+ info["stroke"] = "too late: the contact time has already passed"
+ return [], info
+ rng = np.random.default_rng([self.lv["seed"], 11, self.n_our_legs])
+ sc = self.PADDLE_SCATTER
+ p_c = p_c + rng.normal(0.0, sc["pos"], 3)
+ axis = np.cross(nrm, rng.normal(0.0, 1.0, 3)); axis /= np.linalg.norm(axis)
+ ang = np.radians(rng.normal(0.0, sc["ang_deg"]))
+ nrm = nrm * np.cos(ang) + np.cross(axis, nrm) * np.sin(ang); nrm /= np.linalg.norm(nrm)
+ v_p = v_p * (1.0 + rng.normal(0.0, sc["speed"]))
+ q_h, res = self._ik_best(p_c, nrm, self._ik_seed)
+ info["ik_residual"] = round(float(res), 5)
+ Jp = s.jacobian(q_h)[:3]
+ Winv = np.diag(VEL_LIMIT ** 2)
+ qd_h = Winv @ Jp.T @ np.linalg.solve(Jp @ Winv @ Jp.T, v_p)
+ ratio = float(np.max(np.abs(qd_h) / VEL_LIMIT))
+ scale = max(1.0, ratio / 0.9)
+ qd_h = qd_h / scale
+ info["speed_scale"] = round(scale, 3)
+ q_s = s._target.copy(); v_s = self._target_vel()
+ n_sw = int(n_avail)
+ for n in (range(25, int(n_avail) + 1) if np.max(np.abs(v_s)) < 1e-6 else []):
+ sw = hermite(q_s, np.zeros(7), q_h, qd_h, n * CONTROL_DT, n)
+ if np.max(np.abs(np.diff(np.vstack([q_s, sw]), axis=0)) / (VEL_LIMIT * CONTROL_DT)) <= 0.97:
+ n_sw = n
+ break
+ n_sw = int(min(n_sw, n_avail))
+ info["n_swing_steps"] = n_sw
+ q_goal, qd_goal = q_h.copy(), qd_h.copy()
+ self._planned_hit = q_h.copy()
+ best = None
+ for it in range(5):
+ tg = self._swing_targets(q_goal, qd_goal, n_avail, n_sw)
+ p, n_act, v_act = self._simulate_arm(tg, n_avail)
+ angle = float(np.arccos(np.clip(n_act @ nrm, -1, 1)))
+ loss = np.linalg.norm(p-p_c) + .1*angle + .01*np.linalg.norm(v_act-v_p/scale)
+ if best is None or loss < best[0]:
+ best = (loss, tg, p.copy(), n_act.copy(), v_act.copy())
+ # Further rehearsal is unnecessary once delivery is already well
+ # below the declared scatter; avoid holding up the wallclock loop.
+ if (it == 4 or (np.linalg.norm(p-p_c) < .0005 and angle < np.radians(.1)
+ and np.linalg.norm(v_act-v_p/scale) < .005)):
+ break
+ J = s.jacobian(q_goal)
+ e = np.r_[p_c - p, np.cross(n_act, nrm)]
+ q_goal = np.clip(q_goal + J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), e),
+ s.JOINT_LOW + 1e-4, s.JOINT_HIGH - 1e-4)
+ qd_goal = qd_goal + Winv @ Jp.T @ np.linalg.solve(Jp @ Winv @ Jp.T, (v_p / scale) - v_act) * 0.7
+ qd_goal = qd_goal / max(1.0, float(np.max(np.abs(qd_goal) / VEL_LIMIT)))
+ _, tg, p, n_act, v_act = best
+ info["normal_error_deg"] = round(float(np.degrees(np.arccos(np.clip(n_act @ nrm, -1, 1)))), 3)
+ info["blade_error_m"] = round(float(np.linalg.norm(p - p_c)), 4)
+ info["paddle_vel_delivered"] = [round(float(x), 3) for x in v_act]
+ notes = []
+ if info["blade_error_m"] > .03 or info["normal_error_deg"] > 5:
+ notes.append("command not achievable accurately: see blade_error_m / normal_error_deg")
+ if res > 1e-3: notes.append(f"pose not reachable exactly (IK residual {res:.3f})")
+ if scale > 1.0: notes.append(f"paddle speed limited by the joint speed limits (x{1 / scale:.2f})")
+ if n_sw < 20: notes.append("short swing (little time left)")
+ info["stroke"] = "; ".join(notes) or "ok"
+ return tg, info
+
+
+def render_video(actions, level, out, fps=25):
+ """Replay video, the two decision cameras side by side, 4x slow motion (every 3rd frame while no ball is live)."""
+ import imageio.v2 as imageio
+ mt = Match(level)
+ r = mj.Renderer(mt.s.m, height=360, width=560)
+ cams = []
+ for lookat, dist, az, el in Match.CAMS:
+ c = mj.MjvCamera(); c.lookat[:] = lookat; c.distance = dist; c.azimuth = az; c.elevation = el
+ cams.append(c)
+ w = imageio.get_writer(out, fps=fps, macro_block_size=8)
+ from PIL import Image, ImageDraw
+ for k, q in enumerate(actions):
+ mt.step(q)
+ if (not mt.in_play() or mt.leg["state"] == "done") and k % 3:
+ continue
+ imgs = []
+ for c in cams:
+ r.update_scene(mt.s.d, camera=c)
+ mt._extra_geoms(r.scene, mt.opp_x())
+ imgs.append(r.render())
+ im = Image.fromarray(np.concatenate(imgs, axis=1))
+ ImageDraw.Draw(im).text((8, 6), f"you {mt.score[0]} : {mt.score[1]} opponent (level {level})",
+ fill=(255, 255, 255))
+ w.append_data(np.asarray(im))
+ w.close(); r.close()
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/rally.json b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/rally.json
new file mode 100644
index 0000000000..0b9a9f3a1e
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/rally.json
@@ -0,0 +1,100 @@
+{
+ "note": "5 incoming balls (DeepMind serves, CC-BY-4.0), reach-filtered and robust for the reference stroke; selected with numpy seed 2026 (one per hit-x quintile)",
+ "balls": [
+ {
+ "id": 827,
+ "pos": [
+ 0.3060355857000118,
+ 1.4674673460073875,
+ 0.12820465262917263
+ ],
+ "vel": [
+ -1.112151855228876,
+ -5.471515434933733,
+ -2.1092454631890125
+ ],
+ "spin": [
+ -0.35320826583928316,
+ -4.619090418978232,
+ -6.529630599015004
+ ],
+ "source": "DeepMind competitive_robot_table_tennis serves.json id 827"
+ },
+ {
+ "id": 1757,
+ "pos": [
+ -0.21216441586239737,
+ 1.418508513075304,
+ 0.3219075218156344
+ ],
+ "vel": [
+ 0.27465526732770573,
+ -4.462502801964814,
+ -0.8987376693020879
+ ],
+ "spin": [
+ 12.36978943317683,
+ -6.740979501213409,
+ -23.313588111238552
+ ],
+ "source": "DeepMind competitive_robot_table_tennis serves.json id 1757"
+ },
+ {
+ "id": 1598,
+ "pos": [
+ -0.6098590604191972,
+ 1.498004960690973,
+ 0.2866195108684692
+ ],
+ "vel": [
+ 0.8978951239877346,
+ -4.961401750364483,
+ -1.3173997993835385
+ ],
+ "spin": [
+ -0.6843690522592096,
+ -1.650588570147271,
+ -3.1858990293973255
+ ],
+ "source": "DeepMind competitive_robot_table_tennis serves.json id 1598"
+ },
+ {
+ "id": 579,
+ "pos": [
+ -0.3343478406667241,
+ 1.4504041815872282,
+ 0.3109239191740299
+ ],
+ "vel": [
+ 0.7853063428661995,
+ -4.725880944434543,
+ -2.352729350492706
+ ],
+ "spin": [
+ 5.394878666089257,
+ 5.7460033881289005,
+ -2.6452322700214332
+ ],
+ "source": "DeepMind competitive_robot_table_tennis serves.json id 579"
+ },
+ {
+ "id": 2618,
+ "pos": [
+ -0.470465824135137,
+ 1.4562762311376845,
+ 0.18153216758206328
+ ],
+ "vel": [
+ 1.3926624045407625,
+ -5.707174242684581,
+ -2.1689460676131613
+ ],
+ "spin": [
+ 12.004333357799021,
+ -3.2651510124388516,
+ -23.603094304286483
+ ],
+ "source": "DeepMind competitive_robot_table_tennis serves.json id 2618"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/rally.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/rally.py
new file mode 100644
index 0000000000..cd3f7ad7a5
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/rally.py
@@ -0,0 +1,570 @@
+"""Core of the table-tennis rally service (interactive mode): the episode, the stroke controller and the views.
+
+An episode = N_BALLS incoming balls (recorded DeepMind serves, `rally.json`), one after another. Per ball:
+ ready READY_STEPS control steps: the service brings the arm back to the ready pose Q0; the next ball is held
+ at its launch state, out of play.
+ launch the ball is released from its recorded state (bounces on the opponent's half, crosses the net).
+ pause at the 5th camera frame after the ball's bounce on the opponent's half the world stops: DECISION POINT.
+ shot the decision (swing: contact time, contact point, aim point; or skip) arrives; first the think delay
+ runs (arm holding the ready pose, ball flying), then the stroke controller plans and executes the swing.
+ outcome the ball's first contact after the paddle, or the ball out of play / 2.5 s after the launch.
+The whole episode is recorded as (applied joint targets, launch schedule) and replays bit-exactly (`replay()`).
+"""
+from __future__ import annotations
+
+import io
+import json
+import os
+import xml.etree.ElementTree as ET
+from pathlib import Path
+
+import numpy as np
+
+import mujoco as mj
+import rcb_tt
+from rcb_tt import CONTROL_DT, VEL_LIMIT
+
+HERE = Path(__file__).resolve().parent
+SCENE = HERE / "scene" / "tt_scene.xml"
+INSTANCE = HERE / "instance.npz"
+BALLS = json.load(open(HERE / "rally.json"))["balls"]
+N_BALLS = len(BALLS)
+READY_STEPS = 60 # 0.6 s between one outcome and the next launch
+BALL_STEPS = 250 # a ball is over at the latest 2.5 s after its launch
+CAM_EVERY = 2 # 50 Hz camera
+NOISE_SIGMA = 0.003
+NOISE_SEED = 314159
+AIM_DEFAULT = (0.0, 0.7)
+ADJUST_FRAMES = 3 # adjust point: 3rd camera frame (0.06 s) after the bounce on our half
+DECISION_FRAMES = 5 # decision point: 5th camera frame (0.1 s) after the bounce on the opponent's half
+AIM_BIAS = np.array([-0.1, -0.28]) # controller calibration: its forward model sends clean contacts ~(0.1, 0.28) m long/right
+BALL_R, HALF_T, E_PADDLE = 0.02, 0.0075, 0.985
+OPP_HALF = dict(table_edges_valid=True, target_center=np.array([0.0, 0.685]), target_half=np.array([0.7625, 0.685]))
+rcb_tt.HORIZON = 10 ** 7 # no episode-level step cap in the tooling; the rally ends itself
+
+
+def world_spin(d) -> np.ndarray:
+ R = np.zeros(9)
+ mj.mju_quat2Mat(R, d.qpos[3:7])
+ return R.reshape(3, 3) @ d.qvel[3:6]
+
+
+def _ball_only_xml(path: Path) -> str:
+ root = ET.parse(path).getroot()
+ wb = root.find("worldbody")
+ for b in list(wb):
+ if b.tag == "body" and b.get("name") == "link0":
+ wb.remove(b)
+ for el in root.findall("actuator"):
+ root.remove(el)
+ con = root.find("contact")
+ for el in list(con):
+ if el.tag == "exclude" or (el.tag == "pair" and el.get("geom2") == "paddle_blade"):
+ con.remove(el)
+ root.find("compiler").set("meshdir", str((path.parent / "assets").resolve()))
+ return ET.tostring(root, encoding="unicode")
+
+
+class BallModel:
+ """Ball-only copy of the scene (same ball / table / net physics): the stroke controller's own forward model."""
+
+ def __init__(self):
+ from mujoco import rollout
+ root = ET.fromstring(_ball_only_xml(SCENE))
+ sensors = ET.SubElement(root, "sensor")
+ for geom in ("geom_table", "geom_net", "floor"):
+ ET.SubElement(sensors, "distance", geom1="geom_ball", geom2=geom, cutoff="10")
+ self.m = mj.MjModel.from_xml_string(ET.tostring(root, encoding="unicode"))
+ self.d = mj.MjData(self.m)
+ self.native = rollout.Rollout()
+
+ def rollout(self, p, v, w_world, n, stop_at_contact=False):
+ # MuJoCo's native loop releases the GIL and avoids thousands of Python transitions.
+ state0 = np.r_[0.0, p, 1.0, 0.0, 0.0, 0.0, v, w_world]
+ states, distances = self.native.rollout(self.m, self.d, state0, nstep=n)
+ st = states[0]
+ P, V = st[:, 1:4].copy(), st[:, 8:11].copy()
+ q, w = st[:, 4:8], st[:, 11:14]
+ # Quaternion rotation of local angular velocity into world coordinates.
+ qw, qv = q[:, :1], q[:, 1:]
+ W = w + 2*np.cross(qv, np.cross(qv, w) + qw*w)
+ hits = np.flatnonzero(np.any(distances[0] <= 0, axis=1))
+ first = None
+ if len(hits):
+ i = int(hits[0]); geom = int(np.argmin(distances[0, i]))
+ kind = "net" if geom == 1 else ("floor" if geom == 2 else
+ ("table_opp" if P[i, 1] > 0 else "table_own"))
+ first = (i, kind, P[i].copy())
+ if stop_at_contact:
+ return P[:i+1], V[:i+1], W[:i+1], first
+ return P, V, W, first
+
+
+def hermite(q0, v0, q1, v1, T, n):
+ t = np.arange(1, n + 1) * (T / n)
+ s = t / T
+ h00 = 2 * s**3 - 3 * s**2 + 1; h10 = s**3 - 2 * s**2 + s; h01 = -2 * s**3 + 3 * s**2; h11 = s**3 - s**2
+ return h00[:, None] * q0 + h10[:, None] * T * v0 + h01[:, None] * q1 + h11[:, None] * T * v1
+
+
+class Rally:
+ """The episode. Live: step() / run_to_decision() / shot(). Replay: replay(actions, schedule)."""
+
+ def __init__(self):
+ self.s = rcb_tt.Session(instance=str(INSTANCE), scene=str(SCENE))
+ self.bm = BallModel()
+ self.schedule: list[dict] = [] # per ball: {"ball", "hold_from", "launch"}
+ self.i = -1 # current ball (index into BALLS), -1 before the first hold
+ self.frames: list[dict] = [] # camera frames of the current ball
+ self.results: list[dict] = [] # per-ball outcome
+ self.shots: list[dict] = [] # per-ball decision record
+ self.done = False
+ self.phase = "swing" # which decision the episode waits for: swing | adjust | done
+ self.plan, self.plan_j, self._rec = [], 0, {}
+ self._twin = None
+ self._ik_seed = None
+ self._schedule_ball(0, 0)
+
+ # ------------------------------------------------------------------ bookkeeping
+ @property
+ def k(self) -> int:
+ return self.s._k
+
+ def _schedule_ball(self, i, hold_from):
+ self.schedule.append({"ball": i, "hold_from": hold_from, "launch": hold_from + READY_STEPS})
+ self.i = i
+ self.frames = []
+ self._park()
+
+ def _cur(self) -> dict:
+ return self.schedule[-1]
+
+ def _park(self):
+ b = BALLS[self.i]
+ d = self.s.d
+ d.qpos[0:3] = b["pos"]; d.qpos[3:7] = [1, 0, 0, 0]; d.qvel[0:3] = b["vel"]; d.qvel[3:6] = b["spin"]
+ s = self.s
+ s._events.clear(); s._last_touch.clear(); s._robot_table = 0; s._v_out = None
+
+ def in_play(self) -> bool:
+ return self.k > self._cur()["launch"]
+
+ def t_since_launch(self) -> float:
+ return round((self.k - self._cur()["launch"]) * CONTROL_DT, 6)
+
+ def ball_outcome_final(self) -> bool:
+ if not self.in_play():
+ return False
+ if self.k - self._cur()["launch"] >= BALL_STEPS:
+ return True
+ kinds = [e["kind"] for e in self.s._events]
+ if "paddle" in kinds and any(x != "paddle" for x in kinds[kinds.index("paddle") + 1:]):
+ return True
+ if any(x in ("floor", "robot", "other") for x in kinds):
+ return True
+ p = self.s.d.qpos
+ return bool(p[2] < -0.3 or p[1] < -2.6)
+
+ # ------------------------------------------------------------------ stepping (shared by live and replay)
+ def step(self, q):
+ self.s.step(q)
+ cur = self._cur()
+ if self.k <= cur["launch"]:
+ self._park() # held out of play until the launch step
+ elif (self.k - cur["launch"]) % CAM_EVERY == 0:
+ p = self.s.d.qpos[0:3]
+ if p[2] > -0.5 and p[1] > -2.6 and abs(p[0]) < 2.0:
+ f = (self.k - cur["launch"]) // CAM_EVERY
+ noise = np.random.default_rng([NOISE_SEED, cur["ball"], f]).normal(0.0, NOISE_SIGMA, 3)
+ self.frames.append({"t": self.t_since_launch(), "pos": [round(float(x), 4) for x in p + noise]})
+
+ def _close_ball(self):
+ v = rcb_tt.judge(self.s._events, OPP_HALF, robot_env_contact=self.s._robot_table)
+ kinds = [e["kind"] for e in self.s._events]
+ ret = bool(v["success"])
+ res = {"ball": self.i, "returned": ret, "hit": int(v["hit"]), "n_paddle_contacts": int(v["n_paddle_contacts"]),
+ "landed_opponent_half": int(v["landed_opponent_half"]), "landing_x": round(float(v["landing_x"]), 4),
+ "landing_y": round(float(v["landing_y"]), 4), "net_touch": int(v["net_touch"]),
+ "robot_env_contact": int(v["robot_env_contact"]), "events": kinds, "step": self.k,
+ "own_bounces_before_hit": int(v["own_bounces_before_hit"])}
+ if ret:
+ res["summary"] = f"returned: landed on the opponent's half at x={v['landing_x']:.2f}, y={v['landing_y']:.2f}"
+ elif not v["hit"]:
+ res["summary"] = "missed: no paddle contact"
+ elif v["robot_env_contact"]:
+ res["summary"] = "fault: the arm or paddle touched the table/net/floor"
+ elif v["n_paddle_contacts"] != 1:
+ res["summary"] = "fault: more than one paddle contact"
+ elif v["own_bounces_before_hit"] != 1:
+ res["summary"] = "fault: hit before the ball bounced on your half (volley)"
+ elif v["landed"]:
+ res["summary"] = (f"fault: first contact after the hit was {kinds[kinds.index('paddle') + 1:][0]} at "
+ f"x={v['landing_x']:.2f}, y={v['landing_y']:.2f}")
+ else:
+ res["summary"] = "fault: the ball did not land"
+ self.results.append(res)
+ return res
+
+ def replay(self, actions, schedule) -> None:
+ """Fresh replay of a recorded episode (same actions and launch schedule). Each ball is judged at the
+ first step its outcome is final, exactly as in the live episode (results in self.results)."""
+ sched = [dict(x) for x in schedule]
+ self.schedule = [sched[0]]; self.i = sched[0]["ball"]; self._park()
+ j, closed = 1, set()
+ for q in actions:
+ if j < len(sched) and self.k == sched[j]["hold_from"]:
+ self.schedule.append(sched[j]); self.i = sched[j]["ball"]; self.frames = []; self._park()
+ j += 1
+ self.step(q)
+ if self.i not in closed and self.ball_outcome_final():
+ self._close_ball(); closed.add(self.i)
+
+ # ------------------------------------------------------------------ live episode
+ def _ready_target(self):
+ """Service-driven return to the ready pose Q0 (speed-limited, 60 % of the joint speed limits)."""
+ tgt = self.s._target
+ lim = VEL_LIMIT * CONTROL_DT * 0.6
+ return tgt + np.clip(self.s.inst["q0"] - tgt, -lim, lim)
+
+ def run_to_decision(self) -> None:
+ """Advance until the current ball reaches its decision point (first camera frame past the net)."""
+ while not self.done:
+ self.step(self._ready_target())
+ if self.in_play() and self._decision_due():
+ return
+ if self.ball_outcome_final(): # (cannot normally happen before the decision point)
+ self._next_ball()
+
+ def _decision_due(self) -> bool:
+ """Decision point: the DECISION_FRAMES-th camera frame after the ball's bounce on the opponent's half
+ (or, if it never bounces there, the first frame past the net)."""
+ ev = [e for e in self.s._events if e["kind"] == "table_opp"]
+ if ev:
+ t_b = ev[0]["t"] - self._cur()["launch"] * CONTROL_DT
+ return sum(1 for f in self.frames if f["t"] > t_b) >= DECISION_FRAMES
+ return bool(self.frames and self.frames[-1]["pos"][1] < 0.0)
+
+ def _next_ball(self):
+ self._close_ball()
+ if self.i + 1 < N_BALLS:
+ self._schedule_ball(self.i + 1, self.k)
+ else:
+ for _ in range(20): # a short tail so the last landing is in the video
+ self.step(self.s._target)
+ self.done = True
+
+ def decision_observation(self) -> dict:
+ st = self.s.state()
+ return {"ball_index": self.i, "n_balls": N_BALLS, "t_since_launch": self.t_since_launch(),
+ "frames": list(self.frames), "q": st["q"].round(4).tolist(),
+ "paddle_pos": st["paddle_pos"].round(4).tolist(), "paddle_normal": st["paddle_normal"].round(4).tolist(),
+ "events": [{"event": e["kind"], "t_since_launch": round(e["t"] - self._cur()["launch"] * CONTROL_DT, 3)}
+ for e in self.s._events],
+ "returns_so_far": sum(r["returned"] for r in self.results), "results_so_far": list(self.results)}
+
+ def _adjust_due(self) -> bool:
+ """Second decision point: the ADJUST_FRAMES-th camera frame after the bounce on our half."""
+ ev = [e for e in self.s._events if e["kind"] == "table_own"]
+ if not ev or any(e["kind"] == "paddle" for e in self.s._events):
+ return False
+ t_b = ev[0]["t"] - self._cur()["launch"] * CONTROL_DT
+ return sum(1 for f in self.frames if f["t"] > t_b) >= ADJUST_FRAMES
+
+ def _run_plan(self, stop_at_adjust: bool) -> bool:
+ """Execute the current plan (then hold) until the ball's outcome (False) or the adjust point (True)."""
+ while not self.ball_outcome_final():
+ self.step(self.plan[self.plan_j] if self.plan_j < len(self.plan) else self.s._target)
+ self.plan_j += 1
+ if stop_at_adjust and self._adjust_due():
+ return True
+ return False
+
+ def _finish_ball(self, rec) -> dict:
+ if self.s._v_out is not None:
+ rec["v_out_actual"] = [round(float(x), 3) for x in self.s._v_out]
+ self.shots.append(rec)
+ self._next_ball()
+ res = dict(self.results[-1]); res.update({k: rec[k] for k in rec if k not in ("decision", "adjust")})
+ self.phase = "done" if self.done else "swing"
+ if not self.done:
+ self.run_to_decision()
+ return res
+
+ def shot(self, decision: dict, delay_steps: int) -> dict:
+ """Decision 1 (swing / skip): think delay (the arm holds its ready pose, the ball flies), then the stroke
+ controller plans and starts the swing; runs to the adjust point (-> {"phase": "adjust"}) or, if there is
+ none, to the ball's outcome and on to the next ball's first decision point (-> the ball's result)."""
+ rec = {"ball": self.i, "decision": decision, "delay_steps": int(delay_steps), "k_decision": self.k}
+ self.plan, self.plan_j = [], 0
+ self._ik_seed = None
+ self._planned_hit = None
+ for _ in range(delay_steps):
+ if self.ball_outcome_final():
+ break
+ self.step(self.s._target)
+ rec["k_exec"] = self.k
+ if decision.get("type") == "swing" and not self.ball_outcome_final():
+ self.plan, info = self.plan_stroke(float(decision["t"]), np.asarray(decision["pos"], float),
+ np.asarray(decision.get("aim", AIM_DEFAULT), float))
+ rec.update(info)
+ self._rec = rec
+ if decision.get("type") == "swing" and self._run_plan(stop_at_adjust=True):
+ self.phase = "adjust"
+ return {"phase": "adjust", "ball": self.i, **{k: rec[k] for k in rec if k != "decision"}}
+ self._run_plan(stop_at_adjust=False)
+ return self._finish_ball(rec)
+
+ def adjust(self, decision: dict, delay_steps: int) -> dict:
+ """Decision 2 (adjust / keep): during the think delay the swing already under way continues; then, for an
+ adjust, the stroke controller re-plans the rest of the swing from the arm's current motion."""
+ rec = self._rec
+ rec["adjust"] = decision
+ rec["adjust_delay_steps"] = int(delay_steps)
+ rec["k_adjust_decision"] = self.k
+ for _ in range(delay_steps):
+ if self.ball_outcome_final():
+ break
+ self.step(self.plan[self.plan_j] if self.plan_j < len(self.plan) else self.s._target)
+ self.plan_j += 1
+ rec["k_adjust_exec"] = self.k
+ self._ik_seed = getattr(self, "_planned_hit", None)
+ if decision.get("type") == "adjust" and not self.ball_outcome_final():
+ plan, info = self.plan_stroke(float(decision["t"]), np.asarray(decision["pos"], float),
+ np.asarray(decision.get("aim", rec.get("aim", AIM_DEFAULT)), float))
+ rec["adjust_info"] = info
+ if plan:
+ self.plan, self.plan_j = plan, 0
+ self._run_plan(stop_at_adjust=False)
+ return self._finish_ball(rec)
+
+ # ------------------------------------------------------------------ stroke controller
+ def _twin_session(self):
+ if self._twin is None:
+ self._twin = rcb_tt.Session(instance=str(INSTANCE), scene=str(SCENE))
+ return self._twin
+
+ def _simulate_arm(self, targets, n):
+ """Robot-only rollout of `targets` from the live arm state; paddle (pos, normal, vel) after n steps."""
+ tw = self._twin_session()
+ m, d = tw.m, tw.d
+ mj.mj_resetData(m, d)
+ d.qpos[tw._qadr] = self.s.d.qpos[self.s._qadr]; d.qvel[tw._vadr] = self.s.d.qvel[self.s._vadr]
+ d.qpos[0:3] = [3.0, 3.0, 5.0]; d.qpos[3:7] = [1, 0, 0, 0]
+ mj.mj_forward(m, d)
+ tw._target = self.s._target.copy(); tw._k = 0; tw._actions = []; tw._events = []; tw._last_touch = {}
+ for j in range(n):
+ d.qpos[0:3] = [3.0, 3.0, 5.0]; d.qvel[0:6] = 0
+ tw.step(targets[j])
+ st = tw.state()
+ return st["paddle_pos"], st["paddle_normal"], st["paddle_vel"]
+
+ def _shoot(self, p0, spin, aim):
+ """Outgoing velocities whose ball-only flight lands at `aim` and clears the net by >= 5 cm (one per launch
+ angle)."""
+ cands = []
+ for vz in (0.5, 1.0, 1.5, 2.0, 2.5, 3.0):
+ v = np.array([aim[0] - p0[0], 5.0, vz])
+ for _ in range(10):
+ P, _, _, first = self.bm.rollout(p0, v, spin, 1500, stop_at_contact=True)
+ L = first[2][:2] if first else np.array([9.0, 9.0])
+ err = L - aim
+ if np.linalg.norm(err) < 0.01:
+ i0 = np.argmin(np.abs(P[:, 1]))
+ if first[1] == "table_opp" and P[i0, 2] > 0.2:
+ cands.append(v.copy())
+ break
+ J = np.zeros((2, 2))
+ for c in range(2):
+ dv = np.zeros(3); dv[c] = 1e-3
+ _, _, _, f2 = self.bm.rollout(p0, v + dv, spin, 1500, stop_at_contact=True)
+ L2 = f2[2][:2] if f2 else np.array([9.0, 9.0])
+ J[:, c] = (L2 - L) / 1e-3
+ try:
+ v[:2] -= np.linalg.lstsq(J, err, rcond=None)[0]
+ except np.linalg.LinAlgError:
+ break
+ return cands or [np.array([aim[0] - p0[0], 5.0, 1.5])]
+
+ def _stroke_for(self, v_in, v_out, p_hit):
+ """Impulse model -> blade normal, contact point, paddle velocity; IK and joint velocity at the hit."""
+ s = self.s
+ dv = v_out - v_in
+ nrm = dv / np.linalg.norm(dv)
+ vpn = np.linalg.norm(dv) / (1 + E_PADDLE) + v_in @ nrm
+ v_p = vpn * nrm + (v_in - (v_in @ nrm) * nrm)
+ p_c = p_hit - nrm * (BALL_R + HALF_T)
+ q_h, res = self._ik(p_c, nrm, self._ik_seed if self._ik_seed is not None else s.inst["q0"])
+ Jp = s.jacobian(q_h)[:3]
+ Winv = np.diag(VEL_LIMIT ** 2)
+ qd_h = Winv @ Jp.T @ np.linalg.solve(Jp @ Winv @ Jp.T, v_p)
+ ratio = float(np.max(np.abs(qd_h) / VEL_LIMIT))
+ return dict(nrm=nrm, v_p=v_p, p_c=p_c, q_h=q_h, qd_h=qd_h, ik=res, ratio=ratio, v_out=v_out)
+
+ def plan_stroke(self, t_hit, p_hit, aim):
+ """Swing so that the blade centre meets a ball centred at `p_hit` at `t_hit` (s after launch) and sends it
+ towards `aim`. The blade angle and speed come from the incoming ball's velocity/spin at that time (the
+ controller's own forward model) and an impulse model of the paddle (normal restitution 0.985 in the paddle frame, no slip); IK + a
+ speed-weighted Jacobian inverse give the hit configuration; a cubic swing (at most 0.35 s) and follow-through,
+ refined by 4 robot-only rehearsals so the lagging PD controller puts the blade where it was planned."""
+ info = {"t_hit": t_hit, "p_hit": [float(x) for x in p_hit], "aim": [float(x) for x in aim]}
+ cur = self._cur()
+ k_hit = cur["launch"] + int(round(t_hit / CONTROL_DT))
+ n_avail = k_hit - self.k
+ info["n_swing_steps_available"] = int(n_avail)
+ if n_avail < 1:
+ info["stroke"] = "too late: the contact time has already passed"
+ return [], info
+ # incoming ball at the contact time, from the ball's current state (forward model)
+ d = self.s.d
+ n_roll = max(1, int(round((k_hit - self.k) * CONTROL_DT / 0.001)))
+ P, V, W, _ = self.bm.rollout(d.qpos[0:3].copy(), d.qvel[0:3].copy(), world_spin(d), n_roll)
+ v_in, w_in = V[-1], W[-1]
+ cands = [self._stroke_for(v_in, v, np.asarray(p_hit, float))
+ for v in self._shoot(np.asarray(p_hit, float), -0.5 * w_in, np.asarray(aim, float) + AIM_BIAS)]
+ c = self._pick_stroke(cands)
+ v_out, nrm, v_p, p_c, q_h, qd_h = c["v_out"], c["nrm"], c["v_p"], c["p_c"], c["q_h"], c["qd_h"]
+ s = self.s
+ info["ik_residual"] = round(float(c["ik"]), 5)
+ Jp = s.jacobian(q_h)[:3]
+ Winv = np.diag(VEL_LIMIT ** 2)
+ scale = max(1.0, c["ratio"] / 0.9)
+ qd_h = qd_h / scale
+ info["speed_scale"] = round(scale, 3)
+ # swing duration: the shortest (>= 0.25 s) whose cubic stays under the speed limits, within the time left
+ q_s = self.s._target.copy()
+ v_s = self._target_vel()
+ n_sw = int(n_avail)
+ for n in (range(25, int(n_avail) + 1) if np.max(np.abs(v_s)) < 1e-6 else []):
+ sw = hermite(q_s, np.zeros(7), q_h, qd_h, n * CONTROL_DT, n)
+ if np.max(np.abs(np.diff(np.vstack([q_s, sw]), axis=0)) / (VEL_LIMIT * CONTROL_DT)) <= 0.97:
+ n_sw = n
+ break
+ n_sw = int(min(n_sw, n_avail))
+ info["n_swing_steps"] = n_sw
+ q_goal, qd_goal = q_h.copy(), qd_h.copy()
+ self._planned_hit = q_h.copy()
+ for it in range(5):
+ tg = self._swing_targets(q_goal, qd_goal, n_avail, n_sw)
+ p, n_act, v_act = self._simulate_arm(tg, n_avail)
+ if it == 4:
+ break
+ J = s.jacobian(q_goal)
+ e = np.r_[p_c - p, np.cross(n_act, nrm)]
+ q_goal = np.clip(q_goal + J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), e),
+ s.JOINT_LOW + 1e-4, s.JOINT_HIGH - 1e-4)
+ qd_goal = qd_goal + Winv @ Jp.T @ np.linalg.solve(Jp @ Winv @ Jp.T, (v_p / scale) - v_act) * 0.7
+ qd_goal = qd_goal / max(1.0, float(np.max(np.abs(qd_goal) / VEL_LIMIT)))
+ info["blade_error_m"] = round(float(np.linalg.norm(p - p_c)), 4)
+ info["n_plan"] = [round(float(x), 4) for x in nrm]; info["v_out_plan"] = [round(float(x), 3) for x in v_out]; info["v_in"] = [round(float(x), 3) for x in v_in]
+ info["paddle_v_plan"] = [round(float(x), 3) for x in v_p / scale]; info["paddle_v_twin"] = [round(float(x), 3) for x in v_act]
+ info["stroke"] = "ok" if n_sw >= 20 else "short swing (little time left: slow paddle)"
+ return tg, info
+
+ def _pick_stroke(self, cands):
+ good = [c for c in cands if c["ik"] < 1e-3] or cands
+ return min(good, key=lambda c: c["ratio"]) # the least demanding stroke
+
+ def _target_vel(self) -> np.ndarray:
+ a = self.s._actions
+ return (a[-1] - a[-2]) / CONTROL_DT if len(a) >= 2 else np.zeros(7)
+
+ def _swing_targets(self, q_h, qd_h, n_avail, n_sw):
+ q_s = self.s._target.copy()
+ v_s = self._target_vel()
+ pre = np.tile(q_s, (n_avail - n_sw, 1))
+ swing = hermite(q_s, v_s if n_sw == n_avail else np.zeros(7), q_h, qd_h, n_sw * CONTROL_DT, n_sw)
+ n_f = 25
+ follow = hermite(q_h, qd_h, q_h + qd_h * 0.5 * n_f * CONTROL_DT, np.zeros(7), n_f * CONTROL_DT, n_f)
+ out, prev = [], q_s
+ lim = VEL_LIMIT * CONTROL_DT * 0.999
+ for q in np.vstack([pre, swing, follow]):
+ q = np.clip(q, self.s.JOINT_LOW + 1e-4, self.s.JOINT_HIGH - 1e-4)
+ q = prev + np.clip(q - prev, -lim, lim)
+ out.append(q); prev = q
+ return out
+
+ def _ik(self, pos, normal, q_init, iters=200, tol=1e-4):
+ s = self.s
+ q = np.array(q_init, float)
+ n_t = normal / np.linalg.norm(normal)
+ err = np.inf
+ jacp = np.zeros((3, s.m.nv)); jacr = np.zeros((3, s.m.nv))
+ damping = 1e-3 * np.eye(6)
+ # These vectors are always length three. Avoid numpy.cross's general
+ # broadcasting machinery inside every iteration of every IK start.
+ def cross(a, b):
+ return np.array([a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]])
+ for _ in range(iters):
+ # FK and the Jacobian use the same q; refresh scratch kinematics once.
+ s._kin_set(q)
+ p = s._kin.site_xpos[s._paddle_site]
+ R = s._kin.site_xmat[s._paddle_site].reshape(3, 3)
+ n = R[:, 0]
+ e = np.concatenate((pos - p, cross(n, n_t)))
+ err = float(np.linalg.norm(e[:3]) + np.arcsin(min(1.0, np.linalg.norm(e[3:]))))
+ if n @ n_t < 0:
+ e[3:] = cross(n, n_t) + 0.5 * cross(n, R[:, 1]); err += np.pi / 2
+ if err < tol:
+ break
+ mj.mj_jacSite(s.m, s._kin, jacp, jacr, s._paddle_site)
+ J = np.vstack([jacp[:, s._vadr], jacr[:, s._vadr]])
+ q = np.clip(q + J.T @ np.linalg.solve(J @ J.T + damping, e), s.JOINT_LOW + 1e-4, s.JOINT_HIGH - 1e-4)
+ return q, err
+
+ # ------------------------------------------------------------------ views
+ def render_views(self, width=480, height=320) -> bytes:
+ """PNG: three camera views side by side (behind the robot, side, top), the camera detections of the
+ current ball drawn as cyan dots (older = darker)."""
+ import imageio.v2 as imageio
+ if not hasattr(self, "_renderer"):
+ self._renderer = mj.Renderer(self.s.m, height=height, width=width)
+ cams = []
+ for lookat, dist, az, el in (([0.0, -0.9, 0.15], 2.4, 60.0, -28.0), ([0.0, -0.3, 0.1], 3.4, 0.0, -10.0),
+ ([0.0, -0.35, 0.0], 3.9, 90.0, -89.0)):
+ c = mj.MjvCamera(); c.lookat[:] = lookat; c.distance = dist; c.azimuth = az; c.elevation = el
+ cams.append(c)
+ self._cams = cams
+ r = self._renderer
+ imgs = []
+ n = len(self.frames)
+ for c in self._cams:
+ r.update_scene(self.s.d, camera=c)
+ for j, fr in enumerate(self.frames):
+ if r.scene.ngeom >= r.scene.maxgeom:
+ break
+ a = 0.35 + 0.65 * (j + 1) / max(1, n)
+ g = r.scene.geoms[r.scene.ngeom]
+ mj.mjv_initGeom(g, mj.mjtGeom.mjGEOM_SPHERE, np.array([0.012, 0, 0]), np.array(fr["pos"], float),
+ np.eye(3).ravel(), np.array([0.1 * a, 0.9 * a, 1.0 * a, 1.0], np.float32))
+ r.scene.ngeom += 1
+ imgs.append(r.render())
+ buf = io.BytesIO()
+ imageio.imwrite(buf, np.concatenate(imgs, axis=1), format="png")
+ return buf.getvalue()
+
+
+def render_video(actions, schedule, out, fps=25):
+ """Replay video, two views, 4x slow motion (frames during the ready phases are skipped every other step)."""
+ import imageio.v2 as imageio
+ rp = Rally()
+ r = mj.Renderer(rp.s.m, height=360, width=640)
+ cams = []
+ for lookat, dist, az, el in (([0.0, -0.4, 0.15], 3.0, 90.0, -14.0), ([0.0, -0.3, 0.1], 3.6, 0.0, -14.0)):
+ c = mj.MjvCamera(); c.lookat[:] = lookat; c.distance = dist; c.azimuth = az; c.elevation = el
+ cams.append(c)
+ w = imageio.get_writer(out, fps=fps, macro_block_size=8)
+ sched = [dict(x) for x in schedule]
+ rp.schedule = [sched[0]]; rp.i = sched[0]["ball"]; rp._park()
+ j = 1
+ for k, q in enumerate(actions):
+ if j < len(sched) and rp.k == sched[j]["hold_from"]:
+ rp.schedule.append(sched[j]); rp.i = sched[j]["ball"]; rp.frames = []; rp._park(); j += 1
+ rp.step(q)
+ if not rp.in_play() and k % 3:
+ continue
+ imgs = []
+ for c in cams:
+ r.update_scene(rp.s.d, camera=c)
+ imgs.append(r.render())
+ w.append_data(np.concatenate(imgs, axis=1))
+ w.close(); r.close()
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/rcb_tt.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/rcb_tt.py
new file mode 100644
index 0000000000..53df368e21
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/rcb_tt.py
@@ -0,0 +1,499 @@
+"""
+rcb_tt.py — task-local tooling for the robot table tennis tasks (MuJoCo, Franka Panda with a paddle).
+
+World frame (metres): table top is z = 0, the table's long axis is y, the net is the plane y = 0.
+The robot stands behind the y < 0 end (base at (0, -1.75, 0), facing +y); the opponent half is y > 0.
+
+Control: one action = 7 absolute joint-position targets (rad), held for CONTROL_DT = 10 ms (100 Hz). Inside a
+control step the target is interpolated linearly over the 10 physics steps (1 ms each), and a joint-space
+PD controller with bias (gravity + Coriolis) compensation turns it into joint torques, clipped at the Franka
+torque limits (87 Nm joints 1-4, 12 Nm joints 5-7). The target velocity fed to the D term is the target's
+finite difference. Target limits (checked, a violation raises ValueError / fails the verifier):
+ * every target inside the joint range (JOINT_LOW..JOINT_HIGH),
+ * |target_k - target_{k-1}| <= VEL_LIMIT * CONTROL_DT per joint (Franka joint speed limits);
+ target_{-1} is the instance's initial joint configuration q0.
+An episode lasts HORIZON_S = 2.5 s (250 control steps). A trajectory with fewer than 250 rows holds its last
+target for the rest of the episode.
+
+Python
+------
+ from rcb_tt import Session
+ s = Session() # loads /app/instance.npz (or Session(instance=...))
+ s.reset(); s.step(q_target); s.state(); s.status(); s.actions()
+ s.predict_ball(duration=1.5) # ball-only rollout (no robot) from the current (or a given) ball state
+ s.fk(q) / s.jacobian(q) / s.ik(pos, normal, q_init) # paddle kinematics helpers
+ s.replay(actions) -> status; s.save_trajectory(actions, path)
+
+CLI
+---
+ python rcb_tt.py info
+ python rcb_tt.py replay --traj /app/output/trajectory.npz [--repeat 2]
+ python rcb_tt.py render --traj /app/output/trajectory.npz --out replay.mp4
+"""
+from __future__ import annotations
+
+import argparse
+import copy
+import hashlib
+import json
+import os
+import sys
+import xml.etree.ElementTree as ET
+from pathlib import Path
+
+import numpy as np
+
+import mujoco as mj # rendering backend: MUJOCO_GL (the image sets osmesa = CPU offscreen)
+
+HERE = Path(__file__).resolve().parent
+SCENE_XML = Path(os.environ.get("RCB_TT_SCENE", HERE / "scene" / "tt_scene.xml"))
+DEFAULT_INSTANCE = os.environ.get("RCB_TT_INSTANCE", "/app/instance.npz")
+
+CONTROL_DT = 0.01
+SUBSTEPS = 10 # physics steps per control step (timestep 1 ms)
+HORIZON_S = 2.5
+HORIZON = int(round(HORIZON_S / CONTROL_DT)) # 250 control steps
+VEL_LIMIT = np.array([2.175, 2.175, 2.175, 2.175, 2.61, 2.61, 2.61]) # rad/s (Franka datasheet)
+TORQUE_LIMIT = np.array([87.0, 87.0, 87.0, 87.0, 12.0, 12.0, 12.0]) # Nm
+KP = np.array([2400.0, 2400.0, 2400.0, 2400.0, 1000.0, 600.0, 200.0])
+KD = np.array([100.0, 100.0, 100.0, 100.0, 30.0, 20.0, 6.0])
+MERGE_GAP_S = 0.005 # contacts with the same object closer than this in time count as one
+NET_TOP_Z = 0.1525
+TABLE_HALF_X, TABLE_HALF_Y = 0.7625, 1.37
+
+JOINTS = [f"joint{i}" for i in range(1, 8)]
+
+
+def _robot_geom_ids(m: mj.MjModel) -> set[int]:
+ root = mj.mj_name2id(m, mj.mjtObj.mjOBJ_BODY, "link0")
+ ids = set()
+ for g in range(m.ngeom):
+ b = m.geom_bodyid[g]
+ while b not in (0, root):
+ b = m.body_parentid[b]
+ if b == root:
+ ids.add(g)
+ return ids
+
+
+def _ball_only_xml(path: Path) -> str:
+ """The same scene with the robot removed: used by predict_ball (identical ball/table/net physics)."""
+ tree = ET.parse(path)
+ root = tree.getroot()
+ wb = root.find("worldbody")
+ for b in list(wb):
+ if b.tag == "body" and b.get("name") == "link0":
+ wb.remove(b)
+ for tag in ("actuator",):
+ for el in root.findall(tag):
+ root.remove(el)
+ con = root.find("contact")
+ for el in list(con):
+ if el.tag == "exclude" or (el.tag == "pair" and el.get("geom2") == "paddle_blade"):
+ con.remove(el)
+ root.find("compiler").set("meshdir", str((path.parent / "assets").resolve()))
+ return ET.tostring(root, encoding="unicode")
+
+
+def load_instance(path: str | Path) -> dict:
+ d = np.load(path, allow_pickle=False)
+ return {k: d[k].copy() for k in d.files}
+
+
+class Session:
+ """One simulator (MuJoCo, single thread) for the frozen instance. Unlimited resets."""
+
+ def __init__(self, instance: str | Path | None = None, scene: str | Path | None = None):
+ self.instance_path = str(instance or DEFAULT_INSTANCE)
+ self.inst = load_instance(self.instance_path)
+ self.scene = Path(scene) if scene else SCENE_XML
+ self.m = mj.MjModel.from_xml_path(str(self.scene))
+ self.d = mj.MjData(self.m)
+ m = self.m
+ self._qadr = np.array([m.jnt_qposadr[mj.mj_name2id(m, mj.mjtObj.mjOBJ_JOINT, j)] for j in JOINTS])
+ self._vadr = np.array([m.jnt_dofadr[mj.mj_name2id(m, mj.mjtObj.mjOBJ_JOINT, j)] for j in JOINTS])
+ self.JOINT_LOW = m.jnt_range[[mj.mj_name2id(m, mj.mjtObj.mjOBJ_JOINT, j) for j in JOINTS], 0].copy()
+ self.JOINT_HIGH = m.jnt_range[[mj.mj_name2id(m, mj.mjtObj.mjOBJ_JOINT, j) for j in JOINTS], 1].copy()
+ self._ball_geom = mj.mj_name2id(m, mj.mjtObj.mjOBJ_GEOM, "geom_ball")
+ self._table_geom = mj.mj_name2id(m, mj.mjtObj.mjOBJ_GEOM, "geom_table")
+ self._net_geom = mj.mj_name2id(m, mj.mjtObj.mjOBJ_GEOM, "geom_net")
+ self._floor_geom = mj.mj_name2id(m, mj.mjtObj.mjOBJ_GEOM, "floor")
+ self._blade_geom = mj.mj_name2id(m, mj.mjtObj.mjOBJ_GEOM, "paddle_blade")
+ self._robot_geoms = _robot_geom_ids(m)
+ self._paddle_site = mj.mj_name2id(m, mj.mjtObj.mjOBJ_SITE, "paddle_center")
+ tz = mj.mj_name2id(m, mj.mjtObj.mjOBJ_SITE, "target_zone")
+ m.site_pos[tz, :2] = self.inst["target_center"]
+ m.site_size[tz, :2] = self.inst["target_half"]
+ m.site_rgba[tz, 3] = 0.0 # target-zone visualization is not part of the match
+ self._kin = mj.MjData(m) # scratch data for fk / jacobian / ik (never stepped)
+ self._ball_model = None
+ self.sim_steps_total = 0
+ self.resets = 0
+ self.reset()
+
+ # ------------------------------------------------------------------ episode
+ def reset(self) -> dict:
+ """Back to the frozen initial state (ball in flight, arm at rest at q0, t = 0)."""
+ m, d = self.m, self.d
+ mj.mj_resetData(m, d)
+ d.qpos[0:7] = self.inst["ball_qpos"]
+ d.qvel[0:6] = self.inst["ball_qvel"]
+ d.qpos[self._qadr] = self.inst["q0"]
+ d.ctrl[:] = 0.0
+ mj.mj_forward(m, d)
+ self._target = self.inst["q0"].astype(np.float64).copy()
+ self._actions: list[np.ndarray] = []
+ self._k = 0
+ self._events: list[dict] = [] # contact onsets involving the ball (merged, see MERGE_GAP_S)
+ self._last_touch: dict[str, float] = {}
+ self._robot_table = 0
+ self._robot_contact_names: set[str] = set()
+ self._v_out = None # ball velocity 5 ms after the first paddle contact
+ self.resets += 1
+ return self.state()
+
+ def _check_target(self, q: np.ndarray) -> None:
+ if q.shape != (7,) or not np.all(np.isfinite(q)):
+ raise ValueError(f"action must be 7 finite joint targets, got shape {q.shape}")
+ lo_bad = q < self.JOINT_LOW - 1e-9
+ hi_bad = q > self.JOINT_HIGH + 1e-9
+ if lo_bad.any() or hi_bad.any():
+ raise ValueError(f"step {self._k}: joint target outside range {np.nonzero(lo_bad | hi_bad)[0].tolist()}: {q}")
+ dq = np.abs(q - self._target)
+ lim = VEL_LIMIT * CONTROL_DT * (1 + 1e-6) + 1e-12
+ if (dq > lim).any():
+ j = int(np.argmax(dq / lim))
+ raise ValueError(f"step {self._k}: joint {j + 1} target moved {dq[j]:.5f} rad in one control step "
+ f"(limit {VEL_LIMIT[j] * CONTROL_DT:.5f} = {VEL_LIMIT[j]} rad/s x {CONTROL_DT} s)")
+
+ def step(self, q_target) -> dict:
+ """Apply one action (7 joint targets) for CONTROL_DT = 10 ms. Returns state()."""
+ if self._k >= HORIZON:
+ raise RuntimeError(f"episode is over ({HORIZON} control steps = {HORIZON_S} s); call reset()")
+ q = np.asarray(q_target, dtype=np.float64).reshape(-1)
+ self._check_target(q)
+ m, d = self.m, self.d
+ q_prev = self._target
+ qd_des = (q - q_prev) / CONTROL_DT
+ lo, hi = m.actuator_ctrlrange[:, 0], m.actuator_ctrlrange[:, 1]
+ for j in range(1, SUBSTEPS + 1):
+ q_des = q_prev + (q - q_prev) * (j / SUBSTEPS)
+ tau = KP * (q_des - d.qpos[self._qadr]) + KD * (qd_des - d.qvel[self._vadr]) + d.qfrc_bias[self._vadr]
+ d.ctrl[:] = np.clip(tau, lo, hi)
+ self._v_pre = d.qvel[0:3].copy() # the ball's velocity before this substep (pre-contact)
+ mj.mj_step(m, d)
+ self._scan_contacts()
+ if self._v_out is None and self._events and any(e["kind"] == "paddle" for e in self._events):
+ t_hit = next(e["t"] for e in self._events if e["kind"] == "paddle")
+ if d.time >= t_hit + 0.005 - 1e-9:
+ self._v_out = d.qvel[0:3].copy()
+ self._target = q.copy()
+ self._actions.append(q.copy())
+ self._k += 1
+ self.sim_steps_total += SUBSTEPS
+ return self.state()
+
+ def _scan_contacts(self) -> None:
+ d, t = self.d, self.d.time
+ bg = self._ball_geom
+ for i in range(d.ncon):
+ c = d.contact[i]
+ g1, g2 = int(c.geom1), int(c.geom2)
+ if bg in (g1, g2):
+ other = g2 if g1 == bg else g1
+ if other == self._table_geom:
+ kind = "table_own" if d.qpos[1] < 0 else "table_opp"
+ elif other == self._blade_geom:
+ kind = "paddle"
+ elif other == self._net_geom:
+ kind = "net"
+ elif other == self._floor_geom:
+ kind = "floor"
+ elif other in self._robot_geoms:
+ kind = "robot"
+ else:
+ kind = "other"
+ last = self._last_touch.get(kind)
+ if last is None or t - last > MERGE_GAP_S + 1e-9:
+ # MuJoCo's frame points geom1 -> geom2. Store a stable
+ # surface -> ball convention, independent of geom ordering.
+ normal = c.frame[:3] if g2 == bg else -c.frame[:3]
+ self._events.append(dict(t=round(float(t), 6), kind=kind, pos=d.qpos[0:3].tolist(),
+ vel=d.qvel[0:3].tolist(), vel_pre=self._v_pre.tolist(),
+ contact_pos=c.pos.tolist(),
+ contact_normal=normal.tolist()))
+ self._last_touch[kind] = t
+ else:
+ rob1, rob2 = g1 in self._robot_geoms, g2 in self._robot_geoms
+ if rob1 != rob2: # robot touches the environment (table, net, floor)
+ self._robot_table = 1
+ self._robot_contact_names.add(mj.mj_id2name(self.m, mj.mjtObj.mjOBJ_GEOM, g2 if rob1 else g1) or "?")
+
+ def run_to_end(self) -> dict:
+ """Hold the last target until the episode horizon (what the verifier does after the last action)."""
+ while self._k < HORIZON:
+ self.step(self._target)
+ return self.status()
+
+ # ------------------------------------------------------------------ observation
+ def state(self) -> dict:
+ d = self.d
+ R = d.site_xmat[self._paddle_site].reshape(3, 3)
+ jacp = np.zeros((3, self.m.nv)); jacr = np.zeros((3, self.m.nv))
+ mj.mj_jacSite(self.m, d, jacp, jacr, self._paddle_site)
+ qd = d.qvel[self._vadr]
+ return dict(
+ t=float(d.time), k=self._k,
+ q=d.qpos[self._qadr].copy(), qd=qd.copy(), q_target=self._target.copy(),
+ ball_pos=d.qpos[0:3].copy(), ball_vel=d.qvel[0:3].copy(), ball_spin=d.qvel[3:6].copy(),
+ paddle_pos=d.site_xpos[self._paddle_site].copy(), paddle_R=R.copy(), paddle_normal=R[:, 0].copy(),
+ paddle_vel=jacp[:, self._vadr] @ qd, paddle_angvel=jacr[:, self._vadr] @ qd,
+ events=copy.deepcopy(self._events),
+ )
+
+ def actions(self) -> np.ndarray:
+ """(N, 7) joint targets applied since the last reset."""
+ return np.array(self._actions, dtype=np.float64).reshape(-1, 7)
+
+ def status(self) -> dict:
+ """Judge the episode so far (final only once the ball has landed or the horizon is reached)."""
+ st = judge(self._events, self.inst, robot_env_contact=self._robot_table, t=float(self.d.time), k=self._k)
+ if self._v_out is not None:
+ st["hit_speed_out"] = float(np.linalg.norm(self._v_out))
+ return st
+
+ def state_sha(self) -> str:
+ d = self.d
+ h = hashlib.sha256()
+ for a in (d.qpos, d.qvel, d.act, d.qacc_warmstart, d.ctrl, np.array([d.time])):
+ h.update(np.ascontiguousarray(a, dtype=np.float64).tobytes())
+ h.update(json.dumps(self._events, sort_keys=True).encode())
+ return h.hexdigest()
+
+ # ------------------------------------------------------------------ replay / io
+ def replay(self, actions) -> dict:
+ """Reset, apply `actions` open-loop, hold the last target to the 2.5 s horizon, return status()."""
+ a = np.asarray(actions, dtype=np.float64)
+ if a.ndim != 2 or a.shape[1] != 7 or not (1 <= len(a) <= HORIZON):
+ raise ValueError(f"actions must have shape (N, 7) with 1 <= N <= {HORIZON}, got {a.shape}")
+ self.reset()
+ for q in a:
+ self.step(q)
+ st = self.run_to_end()
+ st["n_actions"] = int(len(a))
+ st["state_sha"] = self.state_sha()
+ return st
+
+ @staticmethod
+ def save_trajectory(actions, path: str = "/app/output/trajectory.npz") -> str:
+ a = np.asarray(actions, dtype=np.float64)
+ if a.ndim != 2 or a.shape[1] != 7:
+ raise ValueError(f"actions must be (N, 7), got {a.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=a, control_dt=np.float64(CONTROL_DT), task=np.str_("tabletennis_return"))
+ return path
+
+ # ------------------------------------------------------------------ helpers (privileged, allowed)
+ def predict_ball(self, pos=None, vel=None, spin=None, duration: float = 1.5) -> dict:
+ """Roll the ball out WITHOUT the robot (same ball/table/net physics, 1 ms steps) from the current ball
+ state or from (pos, vel, spin). Returns t (N,), pos (N,3), vel (N,3), spin (N,3) and the table/net
+ contact onsets. Times are relative to the current sim time. Matches the full sim until the ball
+ touches the robot (up to floating-point differences)."""
+ if self._ball_model is None:
+ self._ball_model = mj.MjModel.from_xml_string(_ball_only_xml(self.scene))
+ self._ball_data = mj.MjData(self._ball_model)
+ bm, bd = self._ball_model, self._ball_data
+ mj.mj_resetData(bm, bd)
+ bd.qpos[0:7] = self.d.qpos[0:7]
+ bd.qvel[0:6] = self.d.qvel[0:6]
+ if pos is not None:
+ bd.qpos[0:3] = pos
+ if vel is not None:
+ bd.qvel[0:3] = vel
+ if spin is not None:
+ bd.qvel[3:6] = spin
+ mj.mj_forward(bm, bd)
+ n = int(round(duration / bm.opt.timestep))
+ P = np.zeros((n, 3)); V = np.zeros((n, 3)); W = np.zeros((n, 3)); T = np.zeros(n)
+ tg = mj.mj_name2id(bm, mj.mjtObj.mjOBJ_GEOM, "geom_table")
+ ng = mj.mj_name2id(bm, mj.mjtObj.mjOBJ_GEOM, "geom_net")
+ fg = mj.mj_name2id(bm, mj.mjtObj.mjOBJ_GEOM, "floor")
+ events, prev = [], set()
+ for i in range(n):
+ mj.mj_step(bm, bd)
+ T[i] = (i + 1) * bm.opt.timestep
+ P[i], V[i], W[i] = bd.qpos[0:3], bd.qvel[0:3], bd.qvel[3:6]
+ cur = set()
+ for c in range(bd.ncon):
+ g = {int(bd.contact[c].geom1), int(bd.contact[c].geom2)}
+ if tg in g:
+ cur.add("table_own" if bd.qpos[1] < 0 else "table_opp")
+ if ng in g:
+ cur.add("net")
+ if fg in g:
+ cur.add("floor")
+ for kind in cur - prev:
+ events.append(dict(t=float(T[i]), kind=kind, pos=P[i].tolist()))
+ prev = cur
+ return dict(t=T, pos=P, vel=V, spin=W, events=events)
+
+ def _kin_set(self, q):
+ self._kin.qpos[:] = self.d.qpos
+ self._kin.qpos[self._qadr] = q
+ mj.mj_kinematics(self.m, self._kin)
+ mj.mj_comPos(self.m, self._kin)
+
+ def fk(self, q) -> tuple[np.ndarray, np.ndarray]:
+ """Paddle blade centre position (3,) and rotation matrix (3,3) for joint config q. Column 0 of the
+ rotation is the blade face normal, column 2 points along the handle (away from the wrist)."""
+ self._kin_set(np.asarray(q, dtype=np.float64))
+ return (self._kin.site_xpos[self._paddle_site].copy(),
+ self._kin.site_xmat[self._paddle_site].reshape(3, 3).copy())
+
+ def jacobian(self, q) -> np.ndarray:
+ """(6, 7) paddle-centre Jacobian [linear; angular] (world frame) at joint config q."""
+ self._kin_set(np.asarray(q, dtype=np.float64))
+ jacp = np.zeros((3, self.m.nv)); jacr = np.zeros((3, self.m.nv))
+ mj.mj_jacSite(self.m, self._kin, jacp, jacr, self._paddle_site)
+ return np.vstack([jacp[:, self._vadr], jacr[:, self._vadr]])
+
+ def ik(self, pos, normal, q_init=None, iters: int = 200, tol: float = 1e-4) -> tuple[np.ndarray, float]:
+ """Damped-least-squares IK for the paddle: blade centre at `pos` with face normal along `normal`
+ (rotation about the normal is free). Joint limits are respected by clipping. Returns (q, residual)
+ where residual = position error (m) + normal error (rad); check it."""
+ q = np.array(self.inst["q0"] if q_init is None else q_init, dtype=np.float64)
+ pos = np.asarray(pos, dtype=np.float64)
+ n_t = np.asarray(normal, dtype=np.float64); n_t = n_t / np.linalg.norm(n_t)
+ err = np.inf
+ for _ in range(iters):
+ p, R = self.fk(q)
+ n = R[:, 0]
+ e = np.r_[pos - p, np.cross(n, n_t)]
+ err = float(np.linalg.norm(e[:3]) + np.arcsin(min(1.0, np.linalg.norm(e[3:]))))
+ if n @ n_t < 0:
+ e[3:] = np.cross(n, n_t) + 0.5 * np.cross(n, R[:, 1]) # flip out of the antipodal solution
+ err += np.pi / 2
+ if err < tol:
+ break
+ J = self.jacobian(q)
+ lam = 1e-3
+ dq = J.T @ np.linalg.solve(J @ J.T + lam * np.eye(6), e)
+ q = np.clip(q + dq, self.JOINT_LOW + 1e-4, self.JOINT_HIGH - 1e-4)
+ return q, err
+
+ # ------------------------------------------------------------------ rendering
+ def render_video(self, actions, out: str, fps: int = 25, every: int = 1, width: int = 640, height: int = 360,
+ slowmo_label: bool = True) -> str:
+ """Replay `actions` and write an mp4 (two views side by side). One frame per `every` control steps
+ (10 ms): fps=25, every=1 is 4x slow motion."""
+ import imageio.v2 as imageio
+ a = np.asarray(actions, dtype=np.float64)
+ r = mj.Renderer(self.m, height=height, width=width)
+ cams = []
+ for lookat, dist, az, el in (([0.0, -0.2, 0.1], 3.6, 0.0, -18.0), ([0.0, 0.0, 0.1], 4.2, -90.0, -22.0)):
+ c = mj.MjvCamera(); c.lookat[:] = lookat; c.distance = dist; c.azimuth = az; c.elevation = el
+ cams.append(c)
+ opt = mj.MjvOption()
+ writer = imageio.get_writer(out, fps=fps, macro_block_size=8)
+
+ def frame():
+ imgs = []
+ for c in cams:
+ r.update_scene(self.d, camera=c, scene_option=opt)
+ imgs.append(r.render())
+ writer.append_data(np.concatenate(imgs, axis=1))
+
+ self.reset(); frame()
+ for k in range(HORIZON):
+ self.step(a[k] if k < len(a) else self._target)
+ if (k + 1) % every == 0:
+ frame()
+ writer.close(); r.close()
+ return out
+
+
+# ---------------------------------------------------------------------- judging
+def judge(events: list[dict], inst: dict, robot_env_contact: int = 0, t: float = 0.0, k: int = 0) -> dict:
+ """Success iff: the ball bounces exactly once on the robot's half and touches nothing else before the hit;
+ exactly one paddle contact; after the hit the ball's first contact other than the net is the table on the
+ opponent half inside the target zone; the robot never touches the table, net or floor.
+ The net is transparent to the judgement (ITTF 2.7.1: a return is good if it touches the opponent's court
+ "directly or after touching the net assembly"); `net_touch` reports it. A serve that touches the net is a let:
+ the caller decides that before calling judge."""
+ center = np.asarray(inst["target_center"], dtype=np.float64)
+ half = np.asarray(inst["target_half"], dtype=np.float64)
+ def top_contact(e):
+ cp, cn = e.get("contact_pos"), e.get("contact_normal")
+ # Top edges have an upward component; vertical sides and the underside
+ # do not. Contact midpoints may lie well below z=0 at higher impact
+ # speeds, so height cannot distinguish top contact from side contact.
+ return bool(cp is not None and cn is not None and cn[2] > 1e-6 and
+ abs(cp[0]) <= .7625 + .001 and abs(cp[1]) <= 1.37 + .001)
+ kinds = [e["kind"] for e in events]
+ out = dict(success=False, hit=0, n_paddle_contacts=kinds.count("paddle"), own_bounces_before_hit=0,
+ bad_contact_before_hit=0, landed=0, landed_opponent_half=0, in_zone=0, landing_error_m=-1.0,
+ landing_x=0.0, landing_y=0.0, net_touch=int("net" in kinds), robot_env_contact=int(robot_env_contact),
+ hit_time=-1.0, hit_speed_out=0.0, t=t, k=k)
+ if "paddle" not in kinds:
+ return out
+ ip = kinds.index("paddle")
+ out["hit"] = 1
+ out["hit_time"] = float(events[ip]["t"])
+ pre = kinds[:ip]
+ edge_rules = bool(inst.get("table_edges_valid"))
+ out["own_bounces_before_hit"] = sum(e["kind"] == "table_own" and (not edge_rules or top_contact(e))
+ for e in events[:ip])
+ out["bad_contact_before_hit"] = int(any(x in ("robot", "floor", "other") for x in pre) or
+ (edge_rules and any(e["kind"] in ("table_own", "table_opp") and not top_contact(e)
+ for e in events[:ip])))
+ post = [e for e in events[ip + 1:] if e["kind"] not in ("paddle", "net")]
+ if post:
+ e = post[0]
+ out["landed"] = 1
+ out["landing_x"], out["landing_y"] = float(e["pos"][0]), float(e["pos"][1])
+ if e["kind"] == "table_opp":
+ out["landed_opponent_half"] = 1
+ err = np.abs(np.array(e["pos"][:2]) - center)
+ if edge_rules:
+ cp = e.get("contact_pos")
+ out["in_zone"] = int(top_contact(e) and cp[1] >= 0)
+ else:
+ out["in_zone"] = int(bool(np.all(err <= half)))
+ out["landing_error_m"] = float(np.linalg.norm(np.array(e["pos"][:2]) - center))
+ out["success"] = bool(out["n_paddle_contacts"] == 1 and out["own_bounces_before_hit"] == 1
+ and not out["bad_contact_before_hit"] and out["landed_opponent_half"] == 1
+ and out["in_zone"] == 1 and not out["robot_env_contact"])
+ return out
+
+
+# ---------------------------------------------------------------------- CLI
+def _main(argv=None) -> int:
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ p = sub.add_parser("info"); p.add_argument("--instance", default=DEFAULT_INSTANCE)
+ p = sub.add_parser("replay"); p.add_argument("--instance", default=DEFAULT_INSTANCE)
+ p.add_argument("--traj", required=True); p.add_argument("--repeat", type=int, default=1)
+ p = sub.add_parser("render"); p.add_argument("--instance", default=DEFAULT_INSTANCE)
+ p.add_argument("--traj", required=True); p.add_argument("--out", default="replay.mp4")
+ a = ap.parse_args(argv)
+ s = Session(instance=a.instance)
+ if a.cmd == "info":
+ inst = {k: (v.tolist() if hasattr(v, "tolist") else v) for k, v in s.inst.items()}
+ print(json.dumps(dict(instance=inst, horizon_s=HORIZON_S, control_dt=CONTROL_DT,
+ joint_low=s.JOINT_LOW.tolist(), joint_high=s.JOINT_HIGH.tolist(),
+ vel_limit=VEL_LIMIT.tolist()), indent=1))
+ return 0
+ acts = np.load(a.traj, allow_pickle=False)["actions"]
+ if a.cmd == "replay":
+ for _ in range(a.repeat):
+ st = s.replay(acts)
+ print(json.dumps({k: v for k, v in st.items()}, default=float))
+ return 0
+ if a.cmd == "render":
+ print(s.render_video(acts, a.out))
+ return 0
+ return 1
+
+
+if __name__ == "__main__":
+ sys.exit(_main())
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/LICENSE.menagerie-franka b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/LICENSE.menagerie-franka
new file mode 100644
index 0000000000..d9a10c0d8e
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/LICENSE.menagerie-franka
@@ -0,0 +1,176 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link0.stl b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link0.stl
new file mode 100644
index 0000000000..def070c707
Binary files /dev/null and b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link0.stl differ
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link1.stl b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link1.stl
new file mode 100644
index 0000000000..426bcf2d7a
Binary files /dev/null and b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link1.stl differ
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link2.stl b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link2.stl
new file mode 100644
index 0000000000..b369f1599a
Binary files /dev/null and b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link2.stl differ
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link3.stl b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link3.stl
new file mode 100644
index 0000000000..25162eeedf
Binary files /dev/null and b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link3.stl differ
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link4.stl b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link4.stl
new file mode 100644
index 0000000000..76c8c33c3e
Binary files /dev/null and b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link4.stl differ
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link5_collision_0.obj b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link5_collision_0.obj
new file mode 100644
index 0000000000..6d6eb5203b
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link5_collision_0.obj
@@ -0,0 +1,188 @@
+v 0.029063642 0.095448048 -0.133538792
+v 0.049877137 -0.013343874 -0.215408068
+v 0.046604998 0.029219000 -0.259000003
+v -0.043494001 0.033698998 -0.259000003
+v -0.030187000 -0.020500001 -0.186547995
+v -0.017736474 -0.052050648 -0.258999242
+v 0.012548444 0.082957777 -0.202027869
+v 0.050364564 0.017247290 -0.214926371
+v 0.020709741 -0.020753554 -0.182012846
+v -0.038214683 0.050463360 -0.167851336
+v 0.045944492 -0.030214707 -0.258999161
+v -0.051997126 -0.017851673 -0.259000003
+v 0.026338819 0.085091480 -0.183646959
+v 0.020922000 0.050882000 -0.259000003
+v 0.045491802 0.013339541 -0.187636452
+v 0.050951000 0.020726001 -0.259000003
+v 0.023551804 0.063747043 -0.133252288
+v -0.013548823 -0.047308172 -0.207602441
+v -0.023108632 0.089348183 -0.175470195
+v 0.028642003 -0.042568484 -0.211525585
+v -0.051912808 0.016682228 -0.233346078
+v 0.021637405 0.093787480 -0.156753967
+v 0.028892799 0.093108394 -0.147202451
+v -0.021765672 0.050517374 -0.259000003
+v 0.029191773 0.046614188 -0.259000003
+v 0.020095230 0.083558674 -0.197022477
+v 0.050294057 0.012853477 -0.210481151
+v 0.041400984 -0.012110881 -0.190499104
+v 0.050274495 0.021321905 -0.223857806
+v 0.050395896 -0.021963709 -0.259000003
+v -0.014053484 -0.016454442 -0.177588961
+v -0.023077204 0.053522191 -0.146035077
+v 0.028830698 0.067305577 -0.135375573
+v -0.038313158 -0.038208997 -0.224413296
+v 0.045422879 -0.030121078 -0.229083894
+v 0.011903144 -0.042590730 -0.199122301
+v 0.012319026 -0.051745998 -0.224350901
+v -0.052457958 0.016511494 -0.258999590
+v -0.046985660 -0.009035359 -0.196875560
+v 0.022625311 0.097598446 -0.133939149
+v 0.012620136 0.087869933 -0.188952639
+v 0.025225283 0.087563533 -0.179602397
+v -0.009634502 0.083175007 -0.202322834
+v -0.024273001 0.085358001 -0.188354000
+v 0.022706000 0.084515996 -0.192412004
+v 0.031834746 0.074158814 -0.139114503
+v 0.050391338 -0.004898283 -0.210560332
+v 0.036850054 -0.028951537 -0.199617216
+v 0.028814057 -0.007357717 -0.177964311
+v 0.007988000 -0.025363000 -0.182107002
+v -0.017462573 -0.033546585 -0.190912689
+v -0.022334082 -0.002848132 -0.172981292
+v -0.030079996 0.053249859 -0.151432391
+v 0.045789921 -0.008346553 -0.194042762
+v 0.037322809 -0.011895567 -0.186316195
+v -0.034569787 -0.042770809 -0.259000003
+v -0.026268487 -0.046990059 -0.224191914
+v 0.033556075 -0.043548766 -0.258998990
+v 0.049874237 -0.022123435 -0.233471659
+v -0.005066666 -0.052041921 -0.219576018
+v 0.016204123 -0.046663484 -0.207808223
+v -0.051942493 -0.005029111 -0.219727096
+v -0.029441908 0.082404274 -0.175896559
+v -0.042174398 -0.025291337 -0.202643498
+f 12 4 3
+f 14 3 4
+f 16 12 3
+f 23 3 13
+f 23 16 3
+f 23 1 16
+f 24 14 4
+f 25 13 3
+f 25 3 14
+f 26 14 7
+f 26 25 14
+f 27 8 1
+f 29 16 1
+f 29 1 8
+f 29 8 16
+f 30 12 16
+f 32 31 17
+f 33 1 17
+f 38 4 12
+f 40 22 19
+f 40 23 22
+f 40 1 23
+f 40 32 17
+f 40 17 1
+f 41 19 22
+f 41 26 7
+f 42 23 13
+f 42 22 23
+f 42 41 22
+f 43 7 14
+f 43 14 24
+f 43 41 7
+f 43 19 41
+f 44 24 4
+f 44 43 24
+f 44 19 43
+f 45 13 25
+f 45 25 26
+f 45 42 13
+f 45 26 41
+f 45 41 42
+f 46 27 1
+f 46 15 27
+f 46 1 33
+f 47 27 15
+f 47 30 16
+f 47 16 8
+f 47 8 27
+f 48 20 35
+f 48 35 2
+f 48 36 20
+f 48 9 36
+f 49 17 9
+f 50 9 17
+f 50 17 31
+f 50 36 9
+f 51 31 5
+f 51 50 31
+f 51 18 36
+f 51 36 50
+f 52 32 5
+f 52 5 31
+f 52 31 32
+f 53 10 39
+f 53 39 5
+f 53 5 32
+f 53 32 40
+f 54 33 28
+f 54 46 33
+f 54 15 46
+f 54 47 15
+f 54 2 47
+f 54 48 2
+f 54 28 48
+f 55 33 17
+f 55 28 33
+f 55 17 49
+f 55 48 28
+f 55 49 9
+f 55 9 48
+f 56 34 12
+f 56 30 6
+f 56 12 30
+f 57 56 6
+f 57 34 56
+f 58 35 20
+f 58 11 35
+f 58 20 37
+f 58 37 6
+f 58 30 11
+f 58 6 30
+f 59 2 35
+f 59 47 2
+f 59 30 47
+f 59 35 11
+f 59 11 30
+f 60 6 37
+f 60 57 6
+f 60 18 57
+f 61 37 20
+f 61 20 36
+f 61 60 37
+f 61 36 18
+f 61 18 60
+f 62 38 12
+f 62 21 38
+f 62 39 10
+f 62 10 21
+f 63 38 21
+f 63 21 10
+f 63 19 44
+f 63 44 4
+f 63 4 38
+f 63 10 53
+f 63 53 40
+f 63 40 19
+f 64 5 39
+f 64 51 5
+f 64 18 51
+f 64 57 18
+f 64 34 57
+f 64 12 34
+f 64 62 12
+f 64 39 62
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link5_collision_1.obj b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link5_collision_1.obj
new file mode 100644
index 0000000000..2eeeeea170
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link5_collision_1.obj
@@ -0,0 +1,119 @@
+v 0.029605924 0.107695894 -0.057770639
+v 0.028114332 0.082823920 -0.058553905
+v 0.038816102 0.053402838 -0.175505396
+v -0.026856016 0.088084521 -0.175136227
+v -0.030626847 0.107119812 -0.057687294
+v 0.025670733 0.088513946 -0.175229901
+v -0.004989269 0.102164150 -0.123603135
+v -0.038214683 0.050463360 -0.167851336
+v 0.029153411 0.097073936 -0.123627471
+v -0.039514421 0.050433927 -0.176900026
+v -0.009555079 0.106683172 -0.095345165
+v -0.018650687 0.092581494 -0.165880068
+v 0.028410194 0.050382871 -0.151882879
+v -0.025116868 0.079917612 -0.059207257
+v 0.027728461 0.088850155 -0.170468824
+v 0.012301352 0.106583136 -0.090584029
+v -0.033031356 0.072019963 -0.176122603
+v -0.028518812 0.083365915 -0.058497467
+v 0.017236843 0.092763911 -0.165977938
+v -0.013955552 0.101873439 -0.118898329
+v -0.028958102 0.093907525 -0.142630397
+v 0.017254189 0.075705868 -0.064336333
+v -0.014409871 0.075430847 -0.064290830
+v 0.028214046 0.087293870 -0.171111784
+v 0.025659250 0.106544369 -0.076459959
+v 0.003562050 0.106723586 -0.095327997
+v -0.038642138 0.054804181 -0.176806387
+v 0.024373464 0.079432104 -0.059087522
+v 0.021627842 0.092908946 -0.161300197
+v -0.022714762 0.106727072 -0.081193925
+v -0.026651997 0.092292062 -0.156493182
+v -0.028411485 0.090537503 -0.161463618
+v -0.033238728 0.052765384 -0.155973185
+v 0.028928091 0.106502887 -0.067219353
+v 0.003488032 0.101747359 -0.123570031
+v 0.025518961 0.096898989 -0.133035213
+v 0.021620985 0.097180492 -0.137775852
+v -0.029182131 0.097825064 -0.119030284
+v -0.022783418 0.101743257 -0.109443270
+v -0.027976784 0.086163124 -0.175228428
+v -0.029871457 0.106777512 -0.062281333
+f 1 2 3
+f 5 2 1
+f 9 1 3
+f 10 6 3
+f 11 5 1
+f 12 6 4
+f 13 3 2
+f 13 10 3
+f 13 8 10
+f 17 4 6
+f 18 10 8
+f 18 5 10
+f 18 8 14
+f 18 2 5
+f 19 12 7
+f 19 6 12
+f 20 11 7
+f 20 7 12
+f 23 14 8
+f 23 13 22
+f 24 15 9
+f 24 9 3
+f 24 3 6
+f 24 6 15
+f 25 16 1
+f 26 11 1
+f 26 1 16
+f 26 7 11
+f 26 16 19
+f 27 17 6
+f 27 6 10
+f 27 10 5
+f 27 5 21
+f 28 18 14
+f 28 2 18
+f 28 23 22
+f 28 14 23
+f 28 22 13
+f 28 13 2
+f 29 15 6
+f 29 6 19
+f 30 5 11
+f 30 11 20
+f 31 12 4
+f 31 21 30
+f 32 27 21
+f 32 17 27
+f 32 31 4
+f 32 21 31
+f 33 23 8
+f 33 8 13
+f 33 13 23
+f 34 25 1
+f 34 1 9
+f 34 9 25
+f 35 26 19
+f 35 19 7
+f 35 7 26
+f 36 9 15
+f 36 15 29
+f 36 25 9
+f 37 29 19
+f 37 19 16
+f 37 16 25
+f 37 36 29
+f 37 25 36
+f 38 30 21
+f 38 21 5
+f 39 30 20
+f 39 20 12
+f 39 31 30
+f 39 12 31
+f 40 32 4
+f 40 4 17
+f 40 17 32
+f 41 38 5
+f 41 5 30
+f 41 30 38
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link5_collision_2.obj b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link5_collision_2.obj
new file mode 100644
index 0000000000..6b563bff79
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link5_collision_2.obj
@@ -0,0 +1,188 @@
+v 0.016219155 0.099363113 0.048750773
+v 0.046550363 0.015799999 0.011058674
+v 0.046166659 0.105324245 -0.019041548
+v -0.005436418 0.111465780 -0.067873175
+v -0.043746749 0.015799999 0.019475930
+v 0.032618475 0.015799999 -0.035021468
+v 0.012971462 0.125447286 0.026076443
+v 0.045556378 0.100993129 0.023528159
+v 0.016534659 0.015799999 0.044952921
+v 0.045622136 0.015799999 -0.014505461
+v 0.031590266 0.097675904 -0.057701935
+v -0.026144502 0.015799999 -0.040104519
+v 0.020916727 0.125582876 -0.010159381
+v -0.043170314 0.100482302 0.027956662
+v 0.046145375 0.108191241 0.006346428
+v 0.028387091 0.112218342 0.031375415
+v 0.033002187 0.099171431 0.039965413
+v 0.016412747 0.015799999 -0.044989475
+v 0.036705779 0.015799999 -0.030707024
+v -0.022295018 0.125131249 -0.010109805
+v 0.029605924 0.107695894 -0.057770639
+v -0.013213095 0.112592014 0.039924672
+v -0.017325918 0.015799999 0.044664757
+v -0.047688079 0.104963029 -0.014858533
+v 0.045808408 0.103510400 0.019105049
+v 0.032957420 0.121769349 -0.001719666
+v 0.011885780 0.108060682 0.044095325
+v 0.016109216 0.089384114 0.048719259
+v 0.041214473 0.103236411 0.027403040
+v 0.041650999 0.015799999 0.023706000
+v 0.028114332 0.082823920 -0.058553905
+v -0.017699993 0.015799999 -0.044454039
+v 0.030954458 0.092818151 -0.058089685
+v -0.013656957 0.125189726 -0.019080479
+v 0.020627846 0.125801899 0.015541304
+v 0.008510412 0.111150243 -0.067818128
+v -0.029781181 0.121768239 0.014799138
+v -0.038794729 0.015799999 0.028113908
+v -0.017496539 0.098143056 0.049083962
+v -0.044002704 0.015799999 -0.018961373
+v -0.047333769 0.101445201 0.019313718
+v -0.030626847 0.107119812 -0.057687294
+v 0.046107670 0.108070694 -0.010345774
+v 0.028871230 0.120837663 -0.014381368
+v 0.011692637 0.121507793 0.031446733
+v 0.020178268 0.103656248 0.044326107
+v 0.024954524 0.015799999 0.040826797
+v 0.037099553 0.099607308 0.036020114
+v 0.028145238 0.121197152 0.018754182
+v -0.021927781 0.125344027 0.015252414
+v 0.020917077 0.111451583 -0.057406886
+v 0.012405067 0.125386135 -0.019235931
+v 0.024373464 0.079432104 -0.059087522
+v -0.033976639 0.107508587 0.031219781
+v -0.032505696 0.120513471 -0.010314825
+v -0.026112117 0.015799999 0.040139331
+v -0.008981987 0.108489258 0.044495871
+v -0.005033433 0.070411983 0.049486264
+v -0.047363327 0.103674321 0.015035708
+v -0.033832737 0.116474922 0.018745562
+v -0.047827588 0.074670758 0.002492660
+v -0.028518812 0.083365915 -0.058497467
+v -0.022142435 0.111037086 -0.057352830
+v 0.041463828 0.111761132 -0.014586542
+f 6 2 5
+f 9 5 2
+f 10 3 2
+f 10 2 6
+f 11 3 10
+f 12 6 5
+f 15 2 3
+f 18 6 12
+f 19 10 6
+f 21 3 11
+f 23 5 9
+f 25 8 2
+f 25 2 15
+f 28 17 1
+f 29 8 25
+f 30 9 2
+f 30 2 8
+f 31 6 18
+f 31 19 6
+f 32 18 12
+f 32 4 18
+f 33 11 10
+f 33 10 19
+f 33 19 31
+f 35 13 34
+f 35 26 13
+f 36 21 11
+f 36 11 33
+f 36 33 31
+f 36 18 4
+f 38 14 5
+f 38 5 23
+f 40 12 5
+f 41 5 14
+f 42 40 24
+f 43 26 15
+f 43 15 3
+f 44 26 21
+f 44 21 13
+f 44 13 26
+f 45 16 7
+f 45 7 22
+f 46 17 16
+f 46 45 27
+f 46 16 45
+f 46 27 1
+f 46 1 17
+f 47 28 9
+f 47 17 28
+f 47 9 30
+f 48 8 29
+f 48 30 8
+f 48 47 30
+f 48 17 47
+f 48 29 16
+f 48 16 17
+f 49 29 25
+f 49 16 29
+f 49 25 15
+f 49 15 26
+f 49 26 35
+f 49 35 7
+f 49 7 16
+f 50 7 35
+f 50 37 22
+f 50 22 7
+f 50 35 34
+f 50 34 20
+f 51 13 21
+f 51 21 36
+f 52 34 13
+f 52 51 36
+f 52 13 51
+f 52 36 4
+f 52 4 34
+f 53 36 31
+f 53 31 18
+f 53 18 36
+f 54 22 37
+f 54 39 22
+f 54 14 39
+f 55 42 24
+f 55 50 20
+f 55 37 50
+f 56 38 23
+f 56 23 39
+f 56 39 14
+f 56 14 38
+f 57 22 39
+f 57 45 22
+f 57 27 45
+f 57 39 1
+f 57 1 27
+f 58 28 1
+f 58 1 39
+f 58 9 28
+f 58 39 23
+f 58 23 9
+f 59 55 24
+f 59 37 55
+f 60 41 14
+f 60 59 41
+f 60 37 59
+f 60 54 37
+f 60 14 54
+f 61 40 5
+f 61 5 41
+f 61 24 40
+f 61 59 24
+f 61 41 59
+f 62 12 40
+f 62 40 42
+f 62 32 12
+f 62 42 4
+f 62 4 32
+f 63 34 4
+f 63 4 42
+f 63 20 34
+f 63 55 20
+f 63 42 55
+f 64 43 3
+f 64 3 21
+f 64 21 26
+f 64 26 43
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link6.stl b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link6.stl
new file mode 100644
index 0000000000..2e9594a873
Binary files /dev/null and b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link6.stl differ
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link7.stl b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link7.stl
new file mode 100644
index 0000000000..0532d05750
Binary files /dev/null and b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/assets/link7.stl differ
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/tt_scene.xml b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/tt_scene.xml
new file mode 100644
index 0000000000..0da7de1898
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/scene/tt_scene.xml
@@ -0,0 +1,157 @@
+<!--
+ Robot table tennis scene for robot_coding_bench.
+ * Ball, table, net and the ball-table contact pair: Google DeepMind competitive_robot_table_tennis
+ (system-identified MJCF from ball_states_viz.ipynb, Apache-2.0). World frame: table top at z=0, the long
+ axis is y, the net is the plane y=0. The opponent half is y>0; the robot stands behind the y<0 end.
+ * Arm: MuJoCo Menagerie franka_emika_panda/panda_nohand.xml (Apache-2.0, assets/LICENSE.menagerie-franka),
+ collision meshes only (also used for display), torque (motor) actuators at the Franka torque limits.
+ The joint-space controller (PD + bias compensation) runs in rcb_tt.py at every 1 ms physics step.
+ * Paddle: a 15 x 15 x 1.5 cm box blade on a short handle bolted to the flange instead of the hand.
+ The blade face normal is the paddle's local +x axis; the handle runs along the flange z axis.
+ The ball-paddle contact parameters are hand-picked (not system-identified).
+-->
+<mujoco model="rcb_tabletennis">
+ <compiler angle="radian" meshdir="assets" autolimits="true"/>
+ <option density="1.225" viscosity="1.8e-5" wind="0 0 0" integrator="implicitfast" timestep="0.001"
+ cone="elliptic" impratio="10"/>
+ <size memory="20M"/>
+
+ <visual>
+ <headlight diffuse=".5 .5 .5" specular=".3 .3 .3"/>
+ <global offwidth="1280" offheight="720"/>
+ </visual>
+
+ <default>
+ <default class="panda">
+ <joint armature="0.1" damping="1" axis="0 0 1" range="-2.8973 2.8973"/>
+ <geom type="mesh" rgba="0.92 0.93 0.94 1" group="2"/>
+ <motor ctrlrange="-87 87"/>
+ </default>
+ </default>
+
+ <asset>
+ <texture type="skybox" builtin="gradient" rgb1=".55 .6 .7" rgb2="0.1 0.1 0.15" width="10" height="10"/>
+ <texture type="2d" name="floor" builtin="checker" rgb1=".32 .32 .36" rgb2=".26 .26 .3" width="300" height="300"/>
+ <material name="floor" texture="floor" texrepeat="8 8"/>
+ <mesh name="link0_c" file="link0.stl"/>
+ <mesh name="link1_c" file="link1.stl"/>
+ <mesh name="link2_c" file="link2.stl"/>
+ <mesh name="link3_c" file="link3.stl"/>
+ <mesh name="link4_c" file="link4.stl"/>
+ <mesh name="link5_c0" file="link5_collision_0.obj"/>
+ <mesh name="link5_c1" file="link5_collision_1.obj"/>
+ <mesh name="link5_c2" file="link5_collision_2.obj"/>
+ <mesh name="link6_c" file="link6.stl"/>
+ <mesh name="link7_c" file="link7.stl"/>
+ </asset>
+
+ <worldbody>
+ <light pos="0 -0.5 3" diffuse="0.9 0.9 0.9" specular="0.3 0.3 0.3" castshadow="false"/>
+ <geom name="floor" type="plane" size="6 6 0.1" pos="0 0 -0.76" material="floor"/>
+
+ <body name="ball" pos="0.0 1.4 0.3">
+ <inertial pos="0 0 0" mass="2.7e-3" diaginertia="0.00000072 0.00000072 0.00000072"/>
+ <freejoint name="ball"/>
+ <geom name="geom_ball" size=".02" shellinertia="false" fluidcoef="0.235 0.25 0.0 1.0 1.0" group="1"
+ rgba="0.98 0.70 0.015 1" solref="-100000 -0" fluidshape="ellipsoid"/>
+ </body>
+
+ <body name="table" pos="0 0 -0.76" quat="0.7071068 0 0 0.7071068">
+ <geom name="geom_table" size="1.37 0.7625 0.02" pos="0 0 0.74" type="box" rgba="0.27 0.51 0.14 1"/>
+ <geom name="geom_net" size="0.005 0.915 0.07625" pos="0 0 0.83625" type="box" rgba="1 1 1 0.5"/>
+ <geom size="1.371 0.7635 0.02" pos="0 0 0.739" type="box" contype="0" conaffinity="0" group="1"
+ density="0" rgba="0 0 0 1"/>
+ <geom size="0.03 0.03 0.36" pos="1.1 0.6 0.36" type="box" contype="0" conaffinity="0" rgba=".2 .2 .2 1"/>
+ <geom size="0.03 0.03 0.36" pos="1.1 -0.6 0.36" type="box" contype="0" conaffinity="0" rgba=".2 .2 .2 1"/>
+ <geom size="0.03 0.03 0.36" pos="-1.1 0.6 0.36" type="box" contype="0" conaffinity="0" rgba=".2 .2 .2 1"/>
+ <geom size="0.03 0.03 0.36" pos="-1.1 -0.6 0.36" type="box" contype="0" conaffinity="0" rgba=".2 .2 .2 1"/>
+ </body>
+
+ <!-- visual target zone on the opponent half (the verifier uses the numbers in instance.npz) -->
+ <site name="target_zone" type="box" pos="0 1 0.0005" size="0.2 0.2 0.0005" rgba="1 0.2 0.2 0.45"/>
+
+ <!-- pedestal: visual only -->
+ <geom name="pedestal" type="cylinder" size="0.12 0.38" pos="0 -1.75 -0.38" contype="0" conaffinity="0"
+ rgba=".25 .25 .28 1"/>
+
+ <body name="link0" childclass="panda" pos="0 -1.75 0" quat="0.7071068 0 0 0.7071068">
+ <inertial mass="0.629769" pos="-0.041018 -0.00014 0.049974"
+ fullinertia="0.00315 0.00388 0.004285 8.2904e-7 0.00015 8.2299e-6"/>
+ <geom name="link0_c" mesh="link0_c"/>
+ <body name="link1" pos="0 0 0.333">
+ <inertial mass="4.970684" pos="0.003875 0.002081 -0.04762"
+ fullinertia="0.70337 0.70661 0.0091170 -0.00013900 0.0067720 0.019169"/>
+ <joint name="joint1"/>
+ <geom name="link1_c" mesh="link1_c"/>
+ <body name="link2" quat="1 -1 0 0">
+ <inertial mass="0.646926" pos="-0.003141 -0.02872 0.003495"
+ fullinertia="0.0079620 2.8110e-2 2.5995e-2 -3.925e-3 1.0254e-2 7.04e-4"/>
+ <joint name="joint2" range="-1.7628 1.7628"/>
+ <geom name="link2_c" mesh="link2_c"/>
+ <body name="link3" pos="0 -0.316 0" quat="1 1 0 0">
+ <joint name="joint3"/>
+ <inertial mass="3.228604" pos="2.7518e-2 3.9252e-2 -6.6502e-2"
+ fullinertia="3.7242e-2 3.6155e-2 1.083e-2 -4.761e-3 -1.1396e-2 -1.2805e-2"/>
+ <geom name="link3_c" mesh="link3_c"/>
+ <body name="link4" pos="0.0825 0 0" quat="1 1 0 0">
+ <inertial mass="3.587895" pos="-5.317e-2 1.04419e-1 2.7454e-2"
+ fullinertia="2.5853e-2 1.9552e-2 2.8323e-2 7.796e-3 -1.332e-3 8.641e-3"/>
+ <joint name="joint4" range="-3.0718 -0.0698"/>
+ <geom name="link4_c" mesh="link4_c"/>
+ <body name="link5" pos="-0.0825 0.384 0" quat="1 -1 0 0">
+ <inertial mass="1.225946" pos="-1.1953e-2 4.1065e-2 -3.8437e-2"
+ fullinertia="3.5549e-2 2.9474e-2 8.627e-3 -2.117e-3 -4.037e-3 2.29e-4"/>
+ <joint name="joint5"/>
+ <geom name="link5_c0" mesh="link5_c0"/>
+ <geom name="link5_c1" mesh="link5_c1"/>
+ <geom name="link5_c2" mesh="link5_c2"/>
+ <body name="link6" quat="1 1 0 0">
+ <inertial mass="1.666555" pos="6.0149e-2 -1.4117e-2 -1.0517e-2"
+ fullinertia="1.964e-3 4.354e-3 5.433e-3 1.09e-4 -1.158e-3 3.41e-4"/>
+ <joint name="joint6" range="-0.0175 3.7525"/>
+ <geom name="link6_c" mesh="link6_c"/>
+ <body name="link7" pos="0.088 0 0" quat="1 1 0 0">
+ <inertial mass="7.35522e-01" pos="1.0517e-2 -4.252e-3 6.1597e-2"
+ fullinertia="1.2516e-2 1.0027e-2 4.815e-3 -4.28e-4 -1.196e-3 -7.41e-4"/>
+ <joint name="joint7"/>
+ <geom name="link7_c" mesh="link7_c"/>
+ <body name="paddle" pos="0 0 0.107">
+ <!-- handle along the flange z axis; blade centre 0.14 m beyond the flange -->
+ <geom name="paddle_handle" type="capsule" fromto="0 0 0 0 0 0.06" size="0.014"
+ mass="0.05" rgba="0.55 0.35 0.2 1" group="2"/>
+ <geom name="paddle_blade" type="box" pos="0 0 0.14" size="0.0075 0.075 0.075"
+ mass="0.09" rgba="0.75 0.08 0.08 1" group="2"/>
+ <site name="paddle_center" pos="0 0 0.14" size="0.005" rgba="1 1 1 1" group="4"/>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </body>
+ </worldbody>
+
+ <contact>
+ <exclude body1="link0" body2="link1"/>
+ <exclude body1="link7" body2="paddle"/>
+ <exclude body1="link6" body2="paddle"/>
+ <!-- system-identified ball-table contact (DeepMind) -->
+ <pair geom1="geom_ball" geom2="geom_table" solref="-1000000 -17" friction="0.1 0.1 0.005 0.0001 0.0001"
+ solimp="0.98 0.99 0.001 0.5 2" solreffriction="-0.0 -200.0"/>
+ <!-- ball-paddle contact: hand-picked, NOT system-identified -->
+ <pair geom1="geom_ball" geom2="paddle_blade" solref="-600000 -12" friction="0.8 0.8 0.005 0.0001 0.0001"
+ solimp="0.98 0.99 0.001 0.5 2" solreffriction="-0.0 -200.0"/>
+ </contact>
+
+ <actuator>
+ <motor class="panda" name="motor1" joint="joint1"/>
+ <motor class="panda" name="motor2" joint="joint2"/>
+ <motor class="panda" name="motor3" joint="joint3"/>
+ <motor class="panda" name="motor4" joint="joint4"/>
+ <motor class="panda" name="motor5" joint="joint5" ctrlrange="-12 12"/>
+ <motor class="panda" name="motor6" joint="joint6" ctrlrange="-12 12"/>
+ <motor class="panda" name="motor7" joint="joint7" ctrlrange="-12 12"/>
+ </actuator>
+</mujoco>
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/serves_pool.json b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/serves_pool.json
new file mode 100644
index 0000000000..76569e0835
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sim/serves_pool.json
@@ -0,0 +1 @@
+{"note": "DeepMind competitive_robot_table_tennis serves.json (CC-BY-4.0): the 109 serves the rally task's stroke controller returns robustly (see tabletennis-rally-interactive README)", "serves": [{"id": 11, "pos": [-0.4049581366048593, 1.4486604589550924, 0.3062632910837785], "vel": [1.0540687388742394, -4.866961343628475, -0.9738064550343261], "spin": [21.723326268467314, 7.826555003862861, -16.343148641254796]}, {"id": 24, "pos": [-0.32775633462433706, 1.2505211863990273, 0.15318614928165003], "vel": [0.21685165997738276, -4.846903311004677, -1.74417390141446], "spin": [-8.470302843515311, 5.974802906253454, 2.22544122554239]}, {"id": 98, "pos": [-0.239689307574105, 1.4175126556604447, 0.16299332678515244], "vel": [0.5408770631283645, -5.8732988912516175, -2.1538360535222045], "spin": [25.148466071415665, -12.322980651175794, -23.531344660791536]}, {"id": 110, "pos": [-0.5768223704206398, 1.4139927402114323, 0.31399513408138247], "vel": [1.247381517760839, -4.310839710568873, -0.5233117398675065], "spin": [3.8602003686804123, 2.0153756161626317, -24.24698699003726]}, {"id": 117, "pos": [0.4621538093247055, 1.2354671003504092, 0.38270532257843964], "vel": [-1.354577004598282, -3.970934399476786, -1.1350348584734755], "spin": [4.505974479522077, -4.165620559951317, 6.897404062739265]}, {"id": 119, "pos": [-0.38513632136491927, 1.4397619670932646, 0.07849106518003968], "vel": [0.3808588557472728, -5.427401884573038, -2.610272723178758], "spin": [-1.1554431023880938, -5.926682793189628, -17.1975634508498]}, {"id": 193, "pos": [0.31964363629133535, 1.3986685623211956, 0.3532919745295203], "vel": [-0.543850139679536, -4.7938639335335615, -0.9041924699248935], "spin": [8.105159001337276, -3.1340466719264275, 9.85122117029645]}, {"id": 194, "pos": [0.06705028714960473, 1.461402600670063, 0.25490866183129945], "vel": [-0.24089958178035534, -4.481258200884452, -2.245424514204765], "spin": [19.291977327021566, -7.505706476658349, -7.656202478577812]}, {"id": 261, "pos": [-0.2680919095017574, 1.4330059515718243, 0.1921022530081258], "vel": [0.17651746877933863, -5.168074822385836, -2.7397793915939195], "spin": [4.777644997301909, -2.4587988699054333, -0.5945738000448773]}, {"id": 273, "pos": [-0.37919349540365205, 1.4292437348394598, 0.20969925175606507], "vel": [0.5081292493844393, -5.144531273889067, -1.8725370084211856], "spin": [0.6670736010404095, 13.859542825234914, -1.735295520860477]}, {"id": 337, "pos": [-0.23222762261603136, 1.4190443358479734, 0.26033008779310185], "vel": [0.23980670349643987, -5.26595903948819, -1.6118596363618145], "spin": [28.037148460519905, -3.028471948611366, -9.45666205823031]}, {"id": 424, "pos": [-0.20573937744572177, 1.4283624624349494, 0.29441235631551066], "vel": [0.2958696709883265, -4.973864037488604, -1.7576077642322923], "spin": [-19.963262845149718, 15.700031965719354, 21.053424374291133]}, {"id": 428, "pos": [0.39185877543202075, 1.4634420795955345, 0.1768245469539992], "vel": [-1.2479586068415625, -5.454738608000466, -1.918446664110609], "spin": [19.222594500057788, -15.6922920219571, -5.9853613704018525]}, {"id": 465, "pos": [0.5516428827217219, 1.4132861096231577, 0.270403030464896], "vel": [-1.9930764902752915, -5.077640450294763, -1.1927146201637715], "spin": [35.607608536135004, -26.121935144166454, 30.41348398307529]}, {"id": 491, "pos": [0.3457104418865123, 1.3988969116435186, 0.2705809043447504], "vel": [-0.44202151764332975, -4.3365730816055175, -2.3118037740386908], "spin": [-16.533820222124966, 5.8936483427768485, -5.235631243170789]}, {"id": 501, "pos": [0.29902607957976185, 1.2873562889814063, 0.3766640814753633], "vel": [-0.7474113957046168, -3.9582688933848953, -0.862508668925518], "spin": [5.964538110259766, -5.98081743335991, 5.507724138666307]}, {"id": 510, "pos": [-0.3828109893813139, 1.416526607659857, 0.3462224343021844], "vel": [1.219255415011712, -4.72377553082806, -0.6343590953422089], "spin": [33.7282324847763, 25.919364605175563, -20.72705882306522]}, {"id": 514, "pos": [-0.13539712243010632, 1.4498183695747962, 0.35802383521022385], "vel": [-0.18393713198692355, -4.662521012827509, -1.801425537646406], "spin": [-5.752446495483427, 14.111004236938125, 13.448834088984288]}, {"id": 539, "pos": [0.44506968865152663, 1.4611718889960748, 0.30621112680889057], "vel": [-1.3309772973021823, -4.307650747226612, -1.8616890567347866], "spin": [-14.328330175559168, 2.669450178013314, -14.270898376295214]}, {"id": 550, "pos": [0.234135592180883, 1.4433793965369843, 0.3869475586448191], "vel": [-0.47580007398912416, -4.420862422913165, -2.2028710959842943], "spin": [-2.8615871578075125, 6.96288428887937, 3.8703287989351627]}, {"id": 552, "pos": [-0.14395418016668207, 1.4229826333860867, 0.31888732693708743], "vel": [0.5067758056048255, -5.09864422025642, -1.609247439530009], "spin": [22.35682798568819, 4.451869963975116, -15.865353187273692]}, {"id": 559, "pos": [0.2871264638269937, 1.2760916193806848, 0.18271958870177732], "vel": [-1.0099153024629999, -4.761876809617584, -1.932722344634323], "spin": [-8.137329192357807, -0.29752252903940324, -2.9025084691583056]}, {"id": 578, "pos": [-0.39970839334328995, 1.423545183051101, 0.18849539675646385], "vel": [0.3278611370728181, -4.847816695561695, -2.0475399124829434], "spin": [15.475560751089873, -21.18846489407994, -22.293078935909257]}, {"id": 579, "pos": [-0.3343478406667241, 1.4504041815872282, 0.3109239191740299], "vel": [0.7853063428661995, -4.725880944434543, -2.352729350492706], "spin": [5.394878666089257, 5.7460033881289005, -2.6452322700214332]}, {"id": 585, "pos": [-0.3872725033864609, 1.4254962241912374, 0.13050359214993934], "vel": [1.0181370057787311, -4.9724707693461205, -2.499696056345045], "spin": [0.9283660717595468, -5.251126185854607, -44.059309084669025]}, {"id": 600, "pos": [-0.31011640587625416, 1.478993608249081, 0.14263871170590653], "vel": [0.6879578002603645, -5.74184064455354, -2.836447424944301], "spin": [13.834892179447017, -6.881318249973792, -9.484570379338285]}, {"id": 633, "pos": [-0.3817098213046743, 1.1880561977397082, 0.15285250086103463], "vel": [-0.06154719954534229, -4.982192996285556, -1.508537050017422], "spin": [16.624313443626892, 2.7405149797099333, 4.081886357446737]}, {"id": 676, "pos": [0.12626788692626156, 1.4440650983331489, 0.30197623145903385], "vel": [-0.8080334508322459, -4.214754814782631, -1.671526507588609], "spin": [-0.5012250468524888, 3.8316085540526137, 24.736488244552724]}, {"id": 695, "pos": [-0.4011534547651849, 1.4498378540123045, 0.31125889979511767], "vel": [0.926377333509501, -4.846918705365502, -1.5325221442114363], "spin": [18.828300637928965, 8.44532773416693, -15.565398641265707]}, {"id": 763, "pos": [0.0952444593817259, 1.4452483980916797, 0.22298557853674306], "vel": [-0.8707816872478126, -5.272072194615711, -1.5664933512353474], "spin": [-11.462618410747313, 31.25968720144166, 11.996136061981671]}, {"id": 827, "pos": [0.3060355857000118, 1.4674673460073875, 0.12820465262917263], "vel": [-1.112151855228876, -5.471515434933733, -2.1092454631890125], "spin": [-0.35320826583928316, -4.619090418978232, -6.529630599015004]}, {"id": 828, "pos": [-0.4526520576254581, 1.2962867267482296, 0.29626608596853043], "vel": [0.7559205101376528, -4.470262428070959, -2.540592210230233], "spin": [-10.680417403757241, 35.26700770911677, -1.8372008617845823]}, {"id": 837, "pos": [0.1519319690858182, 1.4405960375521691, 0.2602364776855966], "vel": [-0.6908944115018857, -4.123072637936164, -2.4780521526261943], "spin": [-1.767409443094369, -24.05089433459393, -14.921775326553922]}, {"id": 847, "pos": [-0.5314931279808703, 1.427454078295705, 0.2878770624720682], "vel": [1.1724840966082195, -5.045365550864894, -1.150500601208381], "spin": [14.400007707204045, -15.255877129651603, -14.026897202550298]}, {"id": 882, "pos": [-0.5512157568545957, 1.4012265053924253, 0.3716314751102631], "vel": [1.2173162973159775, -4.672501739157819, -0.7653332687688074], "spin": [6.904575402351405, 6.307419887850615, -11.529169533850247]}, {"id": 914, "pos": [0.47826321041814357, 1.4574653860095121, 0.2457214591659434], "vel": [-1.3024975098096907, -4.3852695687604575, -2.5573650632547262], "spin": [-0.3377661114238659, -9.027051045984303, 0.4287762138110602]}, {"id": 1066, "pos": [-0.34213889644035556, 1.4107445872125262, 0.36261298317773305], "vel": [0.4920595595952536, -4.543341364848694, -1.4347235566034195], "spin": [2.1655237386264026, -1.3259054196603872, -12.69139467887272]}, {"id": 1088, "pos": [-0.25244494648347293, 1.4382853780032687, 0.28735707529548044], "vel": [0.5828379561784516, -4.8101433858443015, -1.9576675024433483], "spin": [21.12654262023895, 11.604095752063243, -1.1906576636996016]}, {"id": 1149, "pos": [-0.3241917065788105, 1.4255236253414671, 0.22701356431620465], "vel": [0.5797914398854357, -4.8595617899842845, -1.414266417071141], "spin": [-3.781733383642301, -15.31329350103228, -23.35177333577788]}, {"id": 1159, "pos": [-0.29659596184277315, 1.4825826543870906, 0.35297779370616233], "vel": [0.4079343353869322, -4.465705553356311, -2.351000374619085], "spin": [-0.6065151860945768, -0.49406795849030105, -1.1784654294554875]}, {"id": 1190, "pos": [-0.10236539633338974, 1.2827712637008568, 0.3418216146573035], "vel": [0.706776680622113, -4.3998016045192845, -2.393628193058326], "spin": [-12.800702520829173, -14.269076611572741, -4.37651652608102]}, {"id": 1191, "pos": [-0.24627551649087032, 1.4629566159851934, 0.2320677032386983], "vel": [0.6812856890879699, -4.7361782471140375, -3.0362617670442744], "spin": [-7.300519468506536, -6.274066782563657, 14.730487004334437]}, {"id": 1193, "pos": [0.11552979909687829, 1.4109782559628052, 0.4026550276656417], "vel": [-0.7267673645902548, -4.280920775219681, -1.1989364779760898], "spin": [3.5727469048237857, -1.7052352128413508, 9.065267299592312]}, {"id": 1216, "pos": [0.16998329036725243, 1.4448024697139548, 0.25280025346310275], "vel": [-0.4772269814454274, -4.460037882258443, -1.9988787279902716], "spin": [31.987321573940715, -21.40518952732062, -18.50143562406671]}, {"id": 1228, "pos": [-0.2715786619859439, 1.1543840012284887, 0.31738194927374214], "vel": [0.7104263812812404, -3.667011149602738, -2.158531813580238], "spin": [-16.91620632030224, -9.879798546394637, -5.511573118491288]}, {"id": 1258, "pos": [-0.37836355836546826, 1.2625447791344666, 0.1358547118197364], "vel": [-0.10979071028818145, -4.706099237177528, -1.8678369166442645], "spin": [2.484897942623334, -4.87599463433698, 2.585116236807913]}, {"id": 1281, "pos": [-0.5240077991949766, 1.4347345312797715, 0.3866331920830992], "vel": [0.7807733155006649, -4.310324567681965, -2.2548034997137347], "spin": [-2.295515989189582, -3.7907525245093208, -3.2655808052542583]}, {"id": 1286, "pos": [-0.4812020658633066, 1.3542498937207659, 0.2939528350690088], "vel": [1.1682246453834035, -4.368763387061333, -1.13881245860569], "spin": [0.4742897179677393, -9.757425859977367, -28.1590621252726]}, {"id": 1322, "pos": [-0.4613711200042408, 1.4311379119854988, 0.26467415472870603], "vel": [1.113507110452349, -5.0496088496614036, -1.9808026481178513], "spin": [1.4407011961535376, -7.807532214620735, -7.857357490725972]}, {"id": 1364, "pos": [-0.2113559596111618, 1.4237804574844695, 0.1992363701582818], "vel": [0.03571714111178461, -4.88940498967645, -1.8712862615804393], "spin": [0.8617841060123149, 2.461855808903895, 2.4406862238435263]}, {"id": 1402, "pos": [-0.13402118648082215, 1.4334108457853478, 0.3358452140041156], "vel": [-0.0070981437176074556, -4.539762382860411, -1.3975647548678842], "spin": [-19.43489315424744, -10.209803775436994, -6.961326496625412]}, {"id": 1419, "pos": [-0.1424687980998095, 1.4505101592454746, 0.26412753445794135], "vel": [0.5021583593582322, -5.089840972241625, -1.9927637029823944], "spin": [14.751736498831693, -4.415946209883158, -14.558836752795209]}, {"id": 1425, "pos": [-0.17455724066921177, 1.4413841383390333, 0.215107135178888], "vel": [-0.10529541447893435, -5.654573657815397, -1.6125987670901734], "spin": [-17.509183633104367, -80.2902486330937, 50.86243570206514]}, {"id": 1499, "pos": [-0.36382607453051735, 1.4186682280091545, 0.32156091988949953], "vel": [0.9265769838445211, -4.693755075606908, -1.8805071986474655], "spin": [-3.483070412731041, -9.65697958001554, -13.616718647189016]}, {"id": 1514, "pos": [-0.286066250592241, 1.3465448314230573, 0.41853265345793456], "vel": [0.15682282139212225, -4.276617855325889, -1.1868396934047798], "spin": [1.0286325706930666, 0.7790555352924469, -3.1491320515961982]}, {"id": 1534, "pos": [-0.06485967638509445, 1.4511674284683203, 0.2578124173577285], "vel": [-0.01758283807838969, -4.421811132859035, -1.9216400922002153], "spin": [20.94278494733252, -13.186731149491585, -13.01485070301071]}, {"id": 1566, "pos": [-0.2334835359961089, 1.4356474517033955, 0.3829663257634473], "vel": [0.1774085836832497, -4.352025738593028, -2.2043539138332973], "spin": [-8.081554386375776, 1.1479565373421317, 16.560201434754628]}, {"id": 1598, "pos": [-0.6098590604191972, 1.498004960690973, 0.2866195108684692], "vel": [0.8978951239877346, -4.961401750364483, -1.3173997993835385], "spin": [-0.6843690522592096, -1.650588570147271, -3.1858990293973255]}, {"id": 1633, "pos": [-0.6481412607628801, 1.3773110152408532, 0.3270679612145034], "vel": [1.1704851268988705, -4.439963988103589, -1.81766887266196], "spin": [1.4907780754348856, -7.875809196005324, -7.689952963266001]}, {"id": 1672, "pos": [0.04589016267043134, 1.480408436735658, 0.2936485750285157], "vel": [0.13316718243002743, -4.541454740843564, -2.813572147866275], "spin": [0.8478150882030504, 3.269848272684665, 2.5230907809797842]}, {"id": 1678, "pos": [0.0690781159916203, 1.449812554597973, 0.4292443268437318], "vel": [-0.40183696203443986, -4.227021853806545, -1.4010737722710158], "spin": [-1.2297519759413384, -8.576881006211556, 5.65656284613449]}, {"id": 1703, "pos": [0.5759773983395609, 1.4365433310956617, 0.3000045076966916], "vel": [-1.3587940780282133, -4.6054123261694695, -1.3596150467929333], "spin": [-1.7443743225004966, 0.4829481472061006, -10.773623220617822]}, {"id": 1707, "pos": [-0.1563245343370212, 1.4353926361554739, 0.21179580212867846], "vel": [0.623759435514275, -5.713474076502528, -1.5502867529647653], "spin": [-2.598742497249355, -7.845140795915077, -18.96073927998756]}, {"id": 1730, "pos": [-0.3931186673251525, 1.434540639709042, 0.29934741025319533], "vel": [0.8369784102615869, -5.049665646844286, -1.886461119941323], "spin": [6.697695443636102, 10.761941938196944, -1.298852293932447]}, {"id": 1757, "pos": [-0.21216441586239737, 1.418508513075304, 0.3219075218156344], "vel": [0.27465526732770573, -4.462502801964814, -0.8987376693020879], "spin": [12.36978943317683, -6.740979501213409, -23.313588111238552]}, {"id": 1800, "pos": [-0.45368920069082563, 1.4375345891391187, 0.3205575312594913], "vel": [0.5040579262796396, -4.053054763422549, -2.109060379362117], "spin": [1.4241785914356304, 2.195087237066038, 2.2519625178373173]}, {"id": 1825, "pos": [-0.12166145879216621, 1.489059386593448, 0.3273623861389793], "vel": [0.17667259377099995, -4.996354353658553, -2.61830740201127], "spin": [3.7458647832216356, 5.048084122354173, 7.994971154603341]}, {"id": 1900, "pos": [-0.5177639220529926, 1.4685391016517557, 0.27686515243385135], "vel": [1.5695778000260039, -5.427926027871897, -1.514872918387209], "spin": [28.55490089067588, -20.0303915081788, -29.08217302121048]}, {"id": 1939, "pos": [-0.04244879500557531, 1.4413613657285391, 0.2427725403511884], "vel": [0.3080043273045943, -4.758413661046424, -1.7278791594721117], "spin": [-27.194251377134393, -24.547908360562793, -23.823165206319807]}, {"id": 1971, "pos": [0.512422302467441, 1.4014615080852866, 0.4156530903426546], "vel": [-1.18382460046776, -4.0508732812940735, -1.5542803961119827], "spin": [-1.4981317659351197, -0.5942179675340213, 8.600036151627029]}, {"id": 1988, "pos": [0.1722283342657115, 1.448361799057779, 0.3035212106849696], "vel": [-0.5290143303727703, -4.547798288079958, -2.711741871017806], "spin": [-14.694789382604673, 5.429419830546253, 0.28108927089226443]}, {"id": 1991, "pos": [-0.04988101591029433, 1.1899263250768197, 0.16357659385905304], "vel": [-0.6672423703668178, -4.9627149139323405, -1.5301676177201682], "spin": [16.439207731959694, -3.0024177550205366, 3.4059983954873547]}, {"id": 2026, "pos": [0.3044266424038287, 1.468045981235012, 0.18670515813372746], "vel": [-1.0462387910708313, -5.769632436441097, -1.7836712747572698], "spin": [-18.22067907679871, -2.2086269242262246, -2.5089039627472762]}, {"id": 2033, "pos": [-0.34172486264960256, 1.4338184934098408, 0.272067403519489], "vel": [0.9988146067052398, -5.38288402400957, -1.2743198621257728], "spin": [5.07674838935463, -5.827310641258366, -22.690851648913434]}, {"id": 2044, "pos": [-0.4257850835097349, 1.2979614171136091, 0.36077551340390746], "vel": [0.8236652305973449, -4.327174026777351, -1.9933695333728831], "spin": [35.72092107074317, 31.138068954480886, -12.888324484352744]}, {"id": 2061, "pos": [-0.6531966250399616, 1.4692693439809388, 0.2796573863763134], "vel": [0.6899070149462255, -4.519266968379127, -1.939507884160626], "spin": [-12.881273191824645, -42.34301049738489, 28.078188016654767]}, {"id": 2063, "pos": [0.031076001380951155, 1.4469186563722225, 0.2531599363755095], "vel": [-0.5360830827315086, -5.253921174336332, -2.364150636458015], "spin": [-10.94771035110867, 50.28355479593482, 27.827826384242083]}, {"id": 2070, "pos": [0.24491935174483762, 1.4415507121175728, 0.3468021452244696], "vel": [-0.18813661635825463, -4.701893375386033, -2.4502568003938383], "spin": [-17.239060143247304, -2.734022721073727, -1.6623524061012593]}, {"id": 2072, "pos": [-0.32335859338331413, 1.4428513314470184, 0.2636065841851759], "vel": [0.8171380576727789, -4.696183470123974, -1.7519899536081045], "spin": [0.7751500529061292, -13.12128330031004, -9.268205959004485]}, {"id": 2095, "pos": [0.08868019890244752, 1.3982033031702448, 0.1581554366269831], "vel": [-0.26546474125835884, -5.899385042735905, -1.7031282997194157], "spin": [7.134359664969598, 4.988356362817072, 7.799304795857916]}, {"id": 2113, "pos": [0.576357520716982, 1.4748545451614103, 0.4099003518704902], "vel": [-1.0819114474384748, -4.165787849917945, -2.0554312105676473], "spin": [17.053176140981883, -10.551714930376097, -10.600421351423199]}, {"id": 2114, "pos": [-0.49399619857531046, 1.4363813011177058, 0.3663324124950697], "vel": [0.8529583854279472, -5.0970534667214515, -1.220839455831288], "spin": [1.2722706744307772, -0.6134905255222327, -6.475745072872328]}, {"id": 2137, "pos": [-0.4053644161442993, 1.3460774494867933, 0.36298393616002395], "vel": [1.2366110299763742, -4.3647715101438465, -2.2092466124334313], "spin": [6.694496417478496, -12.271677034326698, -8.066652206935723]}, {"id": 2145, "pos": [0.2982530990686171, 1.429517853243929, 0.28587526739543495], "vel": [-0.77959599147891, -5.342097319829765, -1.8165251355835483], "spin": [2.3777276890011723, 19.258287031038336, 31.164364787932023]}, {"id": 2199, "pos": [-0.012451933400186773, 1.4382061507968305, 0.28168164622477826], "vel": [-0.04165616555120048, -5.008015773832297, -1.6961475981614054], "spin": [9.597886050117646, 6.421689212551959, 8.144699201356124]}, {"id": 2217, "pos": [0.23464088486320855, 1.457274904498396, 0.25079849116235187], "vel": [-1.4457413646018369, -4.7849284712001, -1.9563808681453132], "spin": [8.962294262428141, 9.828315170880558, 31.011176179368555]}, {"id": 2224, "pos": [-0.1354386948238012, 1.481206968182418, 0.25790649384099923], "vel": [0.2780593178099566, -4.8111723543884874, -2.5053538870518617], "spin": [-3.209462490737015, 3.1640948728306406, 5.930777861661515]}, {"id": 2249, "pos": [-0.35695342841133004, 1.4432851231709032, 0.25060648485715975], "vel": [0.6090913728368651, -5.526804046440282, -1.8413614419512787], "spin": [-11.379144501999738, -10.57919144100746, -1.215776537381708]}, {"id": 2267, "pos": [-0.4534601456417101, 1.3906491444609772, 0.22236613435770144], "vel": [0.5228705537712461, -5.450438056161476, -1.6883406065227289], "spin": [8.853184786762245, -1.256610891704211, 1.694424866655136]}, {"id": 2271, "pos": [0.05443652134829731, 1.4324654388313534, 0.35871304302811946], "vel": [-0.5049567016088181, -4.016352519312174, -0.800732667943064], "spin": [5.230464776803802, -6.3792638413567015, -11.63531087512327]}, {"id": 2296, "pos": [0.5629832747944347, 1.3975831719757028, 0.16745128832173728], "vel": [-1.6725877758158338, -5.758491360442465, -1.6760310426458471], "spin": [2.0249860949345497, -9.790748292399948, -17.076047218539586]}, {"id": 2302, "pos": [-0.4082344929405746, 1.439063477676491, 0.33904585409309446], "vel": [0.8951505892100406, -4.2733553679788745, -1.6737707309115497], "spin": [18.009978722533287, 2.2575469169714286, -21.21827659584833]}, {"id": 2334, "pos": [0.492937631799761, 1.4393608235103403, 0.16357323357449896], "vel": [-1.3077425546579282, -5.798793752314654, -2.0939879971949074], "spin": [31.98004390342229, -32.817590396377334, -36.74224406215835]}, {"id": 2345, "pos": [-0.3188394859272696, 1.438213568604347, 0.36334806715118073], "vel": [1.1733213053860947, -4.503387279472462, -1.7368508932221973], "spin": [-5.691202364883631, -7.324239493306263, -28.62952609763727]}, {"id": 2353, "pos": [-0.3210157398388675, 1.3826960652878446, 0.3291507909688976], "vel": [0.9210914561879103, -4.5417608223838055, -2.155520609758438], "spin": [-11.081896038509232, 12.219229390173764, -10.672944698476808]}, {"id": 2367, "pos": [-0.560513671641388, 1.4088075199623395, 0.3485842530837476], "vel": [1.3292646634130316, -4.927888966877444, -1.199980041841227], "spin": [11.781552390718439, 3.1279892550557946, -18.555032525703545]}, {"id": 2377, "pos": [-0.30317545915022015, 1.4217605594473486, 0.3306340959878263], "vel": [0.922610690682124, -4.594600953197403, -1.3261711692171276], "spin": [-3.4284368351482017, -6.793316111136656, -26.43863516307784]}, {"id": 2393, "pos": [-0.4086172828345945, 1.4290793266702095, 0.3910144389240547], "vel": [0.5090588491774186, -3.781553873696944, -0.9059826485141945], "spin": [-5.055166829898362, -9.335730972489076, -29.128204500716613]}, {"id": 2425, "pos": [-0.20060495468700196, 1.3334919253552544, 0.38416765347511694], "vel": [0.025292609087780967, -3.8864365801837013, -1.1769216072650412], "spin": [-5.410048078127717, -3.6754303130400405, -6.076306884552507]}, {"id": 2447, "pos": [-0.3484570544497421, 1.4032295327806799, 0.42982027652916405], "vel": [0.41465832486120696, -4.449324901376074, -1.8573351031684906], "spin": [8.78283142373407, 8.21290942013584, -5.490736169717853]}, {"id": 2474, "pos": [-0.27785207814718577, 1.4997375491192224, 0.2295965471133732], "vel": [0.9462395036338209, -5.117948021290964, -2.3904443274054437], "spin": [-5.749180855079036, -4.629866794822625, -8.183908171803177]}, {"id": 2475, "pos": [-0.3960502358050527, 1.4300106493416196, 0.28210103164094796], "vel": [0.8827167576055289, -4.708740796834323, -2.682109697409332], "spin": [11.141550673573963, 7.534739006868594, -3.009926645752371]}, {"id": 2525, "pos": [0.4560408258373585, 1.4243536808370676, 0.262912553268286], "vel": [-0.540824058119839, -5.100761293339064, -2.183867815603693], "spin": [30.29236128296459, -2.5148646479717973, 13.30413467066702]}, {"id": 2550, "pos": [0.14002354196493214, 1.4399703530503334, 0.3731570920122777], "vel": [-0.40024044029979333, -4.5506285693514, -2.0562042772213496], "spin": [-26.419410889560005, 17.23310379916552, 8.793755573145726]}, {"id": 2556, "pos": [-0.5922234165038366, 1.4005635122253106, 0.32643412908645975], "vel": [1.145720551612384, -4.143890849878027, -1.9449776985186542], "spin": [-1.9833882252762494, -9.11573715852647, -12.642217941795762]}, {"id": 2576, "pos": [-0.3652671830861511, 1.4118560950164865, 0.3777035018870971], "vel": [0.14384217958663548, -3.8553232910353135, -0.9281948351573029], "spin": [2.237370805092966, -60.02464510531289, -12.572908651579588]}, {"id": 2618, "pos": [-0.470465824135137, 1.4562762311376845, 0.18153216758206328], "vel": [1.3926624045407625, -5.707174242684581, -2.1689460676131613], "spin": [12.004333357799021, -3.2651510124388516, -23.603094304286483]}, {"id": 2660, "pos": [0.30110698322735324, 1.427693465219787, 0.2238191912318034], "vel": [-0.30275253023008386, -4.970271641804054, -2.342877966391577], "spin": [-3.571656623890767, -9.825332181091039, -20.805032744749653]}, {"id": 2702, "pos": [0.0748104301052215, 1.458625800314788, 0.17038560652947707], "vel": [0.12269544154493864, -5.464210401490957, -2.4665698931424305], "spin": [-0.2712173657895323, -18.05490705721318, -15.061496335855276]}]}
\ No newline at end of file
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sport.toml b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sport.toml
new file mode 100644
index 0000000000..85aa5d580e
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/environment/sim/sport/sport.toml
@@ -0,0 +1,228 @@
+# tabletennis: robot table tennis, real time (docs/framework_zh.md §4.2, §8). Migrated from the legacy tree in stage 2
+# (scripts/olympiad/tabletennis, scripts/olympiad/shared/tabletennis): the simulator (sim/: the physics, the referee,
+# the scripted opponent, the stroke planner, the arm command layer, the duel) is unchanged, so the legacy recordings
+# replay bit-exactly (golden/convert.py). The declarations below are data: the core, tools/generate.py, tools/check
+# and the prompt read them.
+
+[sport]
+name = "tabletennis"
+title = "Table tennis"
+summary = "robot table tennis in a continuous world slowed by a factor S (MuJoCo Franka Panda + paddle, DeepMind ball and table model, recorded real serves), seen only through two cameras of four frames each; one game to 5 points (lead by 2 from 4:4, at 6:6 the next point wins); format match: you against a scripted opponent (level 1-4) that serves every point, format duel: two players and a neutral serve machine, the receiver changing every point"
+protocol = "realtime"
+revision = "wallclock-6+duel-wallclock-4+core-0.2" # bump on any change that alters play (sim/, the rules, the observation)
+physics = "mujoco"
+image = "ghcr.io/mll-lab-nu/eai-olympiad:0.1.0"
+status = "sport"
+publish = true
+category = "robotics-sports-arena"
+
+[rulebook]
+name = "ITTF Laws of Table Tennis (ITTF Statutes 2025, chapter 2)"
+version = "2025 (effective 1 January 2025)"
+url = "https://db.ittf.com/sites/default/files/public/2025-02/ITTF_Statutes_2025_tracked_changes_version.pdf"
+
+[[deviations]]
+id = "D1"
+rule = "ITTF 2.11, 2.12"
+text = "one game to 5 points (from 4:4 a lead of 2 is needed, at 6:6 the next point wins: 7 points at most) instead of a best-of-games match with games to 11"
+affects_result = true
+[[deviations]]
+id = "D2"
+rule = "ITTF 2.6, 2.13"
+text = "the robots cannot toss the ball: format match - the opponent serves every point with recorded real serves and you always receive; format duel - a neutral machine serves recorded real serves and the receiver changes every point (as under the expedite system, 2.13.3, 2.15.3)"
+affects_result = true
+[[deviations]]
+id = "D3"
+rule = "ITTF 2.5.7"
+text = "only the blade can strike the ball: the ball touching the handle or arm loses the point"
+affects_result = true
+[[deviations]]
+id = "D4"
+rule = "ITTF 2.10.1.9-2.10.1.11"
+text = "a robot has no free hand: any contact of the arm or paddle with the table, net or floor loses the point"
+affects_result = true
+[[deviations]]
+id = "D5"
+rule = "ITTF 2.10.1.7"
+text = "any double hit loses the point, deliberate or not"
+affects_result = true
+[[deviations]]
+id = "D6"
+rule = "ITTF 2.15.4"
+text = "the expedite rule applies from the first point: the receiver's 13th good return in a rally wins it the point (this bounds every rally)"
+affects_result = true
+[[deviations]]
+id = "D7"
+rule = "ITTF 2.9.1.1 (let)"
+text = "a serve that touches the net or is irregular is a let; duel: faults by both players at the same instant are a let; the robot that is not receiving is transparent to the serve until it bounces on the receiver's half (the recorded serves were made for an empty serving end)"
+affects_result = true
+[[deviations]]
+id = "D8"
+rule = "- (cost limit, not from the rulebook)"
+text = "if 40 points (lets included) are played the game ends: the player ahead wins; at a level score the player who won the last point (never reached in practice)"
+affects_result = true
+
+[formats.match] # one model seat against the scripted opponent inside the world (match.Match)
+seats = ["A"]
+opponent = true # success = winning a valid match (core/grading.py), as in the legacy task
+levels = [1, 2, 3, 4] # the opponent level (RCB_LEVEL; default 1)
+[formats.duel]
+seats = ["A", "B"]
+first = ["A", "B"] # the first receiver (FIRST_PLAYER); the runner plays both orders
+
+[modes]
+action_levels = ["high", "low"] # high: the paddle state at contact (the stroke planner); low: joint targets
+plays = ["program", "direct"]
+
+[timing]
+slowdown = 20 # the legacy default (RCB_SLOWDOWN); the direct tasks: [[tasks]] slowdown = 50
+start_timeout_s = 1800 # duel: up to 30 minutes to start after the first player
+ready_timeout_s = 300 # each review (after every point), else the side loses
+
+[actions.cli] # the `game` shortcuts per action level (anything else: game act JSON)
+high = { none = [] }
+low = { hold = [] }
+
+[seat] # every task's player image (the legacy tasks' OpenCV)
+pip = ["opencv-python-headless==5.0.0.93"]
+[seat.low] # the low action level's information boundary: the robot's own model + MuJoCo
+files = { "/opt/robot/robot_only.xml" = "seat/robot_only.xml", "/opt/robot/assets" = "sim/scene/assets" }
+pip = ["mujoco==3.3.7", "absl-py==2.5.0", "etils==1.14.0", "fsspec==2026.9.0", "glfw==2.10.2", "PyOpenGL==3.1.10",
+ "typing_extensions==4.16.0", "zipp==4.1.0"] # = the sim image's MuJoCo and its closure (tests check the pin)
+run = ["python -c \"import mujoco; m = mujoco.MjModel.from_xml_path('/opt/robot/robot_only.xml'); assert (m.nbody, m.njnt, m.nu) == (10, 7, 7)\""]
+note = "Your robot's own model is /opt/robot/robot_only.xml (MJCF: the arm and paddle only, nothing of the world; meshes in /opt/robot/assets), with MuJoCo at the simulator's version"
+
+[actions.direct] # direct play: the commands of the `game` MCP tool (players/nocode/game_mcp.py)
+high = [["game act T PX PY PZ NX NY NZ VX VY VZ", "POST /act {\"type\":\"act\",\"t\":T,\"pos\":[PX,PY,PZ],\"normal\":[NX,NY,NZ],\"vel\":[VX,VY,VZ]}", "a paddle command: the blade's state at contact, T s after the command takes effect"],
+ ["game act none", "POST /act {\"type\":\"none\"}", "cancel; the arm returns to its ready pose"]]
+
+[observation]
+fields = ["point", "score", "ball", "t_since_played", "serve_in_s", "ball_in_play", "ball_state", "you_receive_serves",
+ "q", "paddle_pos", "paddle_normal", "command", "qd", "q_target", "points", "shots", "heard"]
+renderer = "mujoco" # the sport draws its own images (camera_job: a 4-frame history); see README
+frame_budget_ms = 1500 # the legacy images (8 tiles 480 x 360, MuJoCo osmesa on CPU): about 0.1-0.2 s per tile, ~1.3 s per observation measured under host load (tiles cached between observations, same pixels)
+columns = 4
+# Since wallclock-6 / duel-wallclock-4 the arms are drawn with the Franka Panda's visual meshes (presentation/
+# presentation.toml players = "25k", bundled into the simulator; renderer rule 6). Measured 2026-10-07 (8 new tiles,
+# osmesa, host load 20-50 on 32 cores), median / p95 ms per observation at 2 llvmpipe threads: match scene 88 / 112,
+# 25k meshes 161 / 182, full meshes 387 / 451 (1 thread: 148, 233, 564)
+render_threads = 2 # llvmpipe threads per render process (LP_NUM_THREADS); one render process per seat
+sim_cpus = 6 # the sim container: 2 seats x 2 render threads + the world, the planners and the core
+
+[spec] # the rule constants and conventions (also in /spec and the prompt)
+game_format = "first to 5 points; from 4:4 a lead of 2 is needed; at 6:6 the next point wins (7 at most)"
+rules = "after exactly one bounce on your half, hit the ball once so that it lands on your opponent's half, directly or after touching the net (the upper table edges count, the vertical sides do not); the same holds for your opponent's returns. You lose the point for a volley, a double hit, two bounces, a miss, a ball that lands on your own half or out, the ball touching your arm or handle while it is over or travelling towards your half, or your arm or paddle touching the table, net or floor. A shot that passes a player's half without touching it is out, even if it then hits that player's robot. A serve that touches the net or is irregular is a let. The receiver's 13th good return in a rally wins it the point (expedite rule). At 40 points played (lets included) the player ahead wins, at a level score the player who won the last point"
+opponent = "format match: the opponent serves every point (you always receive) and returns every ball it can reach; higher levels react faster, reach further and play faster, wider balls with more spin (`match.opponent_level` in game spec)"
+duel = "format duel: a neutral machine serves every point (first on the server's half, then on the receiver's); the receiver changes every point, `match.first_receiver` receives the first; both players get this document and see the game in their own frame"
+world = "metres; your frame: x to your right, y towards the opponent, z up; table top z = 0, |x| <= 0.7625, |y| <= 1.37; net at y = 0, top z = 0.1525; your half y < 0; your robot's base at (0, -1.75, 0) facing +y"
+ball = "radius 0.02 m, orange; gravity 9.81 m/s^2; air drag about 0.13 |v| v; spin bends the flight by a few cm; a bounce keeps about 96 % of the vertical and 87 % of the horizontal speed; a ball takes about 0.6-0.9 s from the opponent to you"
+reach = "the blade can meet a ball whose centre is within about 0.85 m of the shoulder (0, -1.75, 0.33) and above z = 0.12"
+blade = "15 x 15 cm; at contact its centre is 2.75 cm from the ball's centre along the face normal; with n the unit face normal the ball leaves with about v_out = v_paddle - 0.96((v_in - v_paddle).n)n + (v_in - v_paddle) - ((v_in - v_paddle).n)n"
+observation = "observe: one PNG of 2 rows (camera behind your robot, camera at the side) x 4 columns (frames 40 ms apart, newest right) of 480 x 360 tiles, with each frame's control step (observation.view_steps); no ball coordinates; yellow marks every 0.25 m along the table edges; cameras' poses and intrinsics in game spec (pinhole, 45 degree vertical field of view, focal length 434.6 px, principal point at the tile centre)"
+action_high = "high action level: act {type: act, t, pos, normal, vel} = the blade's state at contact t seconds after the command takes effect (centre pos, face normal pointing at the opponent, velocity m/s); limits 0 < t <= 2.5, |x| <= 1.2, -2.5 <= y <= -0.5, 0 <= z <= 1.2, speed <= 8 m/s; it replaces the stroke under way; the service plans the swing (IK, joint speed limits) and the reply predicts how close the arm gets; the delivered state scatters by about 4 mm, 0.6 degrees and 2 %; {type: none} returns the arm to its ready pose"
+action_low = "low action level: joint position targets at 100 Hz, no IK or stroke planner: traj {k0, q: rows of 7 targets} (row i = control step k0 + i, <= 300 rows, consecutive rows within the per-step speed limit, the first row used within that limit of the target in force), slew {q, speed} (every joint towards q at speed x its limit), hold; game spec gives the kinematic chain, limits, the joint controller and the robot's own model (robot_model.robot_only_xml)"
+real_time = "the world runs on its own clock at 1/S of real speed (S = timing.slowdown in game spec); it never waits for you; an act takes effect at the next 10 ms control step after it arrives (the reply's took_effect); one act and one observation per seat in flight; after each point the world freezes until every player has sent game ready WHY PLAN"
+scatter_and_seed = "the serves, the opponent's returns and the execution scatter are drawn from the seed (RCB_SEED / DUEL_SEED)"
+
+[tiebreaks]
+order = ["game"]
+text = "the first player to 5 points with a lead of 2, or the first to 7, wins the game (the match); a let scores no point; if 40 points (lets included) are played, the player ahead wins and at a level score the player who won the last point (last resort, not from the rulebook)"
+last_resort_in_prompt = true
+
+[[exploits]]
+id = "E1"
+text = "an out-of-range, non-finite, too fast or malformed command is refused (HTTP 400) and changes nothing"
+test = "test_exploit_bad_commands_are_refused"
+[[exploits]]
+id = "E2"
+text = "a trajectory whose first row jumps beyond the joint speed limit from the target in force is rejected; the previous command goes on and the simulator never sees the jump"
+test = "test_exploit_discontinuous_start_is_rejected"
+[[exploits]]
+id = "E3"
+text = "the observation holds no ball, opponent or seed state (only the cameras show the ball); /spec holds no seed"
+test = "test_exploit_no_hidden_state"
+[[exploits]]
+id = "E4"
+text = "a player that never moves loses every point (stalling gains nothing)"
+test = "test_exploit_never_moving_loses"
+[[exploits]]
+id = "E5"
+text = "the high action level is the legacy service's planner: the same acts give the same joint targets (no hidden advantage or handicap from the migration)"
+test = "test_exploit_high_level_equals_legacy_planner"
+[[exploits]]
+id = "E6"
+text = "the robot's own model and kinematic chain given at the low level reproduce the simulator's arm and hold nothing of the world"
+test = "test_exploit_robot_model_is_the_simulator_arm"
+[[exploits]]
+id = "E7"
+text = "direct play: a program, a pipe or any tool call other than a literal game command or opening a camera image forfeits the match (players/nocode audit, core grading)"
+test = "test_exploit_nocode_audit_forfeits"
+
+[players]
+reference = "reference" # Sport.players() names: camera-only, wins the default configuration
+reference_class = "builtin_players:Reference"
+check = ["idle"] # the generic tests' check policy (never acts: every point ends quickly)
+
+[fairness]
+policy = "reference" # the camera-only reference on both seats (high level), seeds 1..N, both first receivers
+matches_per_order = 20 # the contract minimum: N = 40 (95% CI about +-15 pp; realtime: a wide CI only warns); an in-process duel takes 15-20 min on the shared host
+max_advantage_pp = 5
+mirror = "statistical" # seat B is the mirrored world: floating-point physics is not bit-symmetric
+
+[official] # grade.py computes official_config with the legacy per-format rule (README)
+seeds = [1, 2, 3, 101, 111, 121, 202, 212, 222, 303, 313, 323, 404, 414, 424]
+levels = [1, 2, 3, 4]
+slowdowns = { program = [1, 2, 5, 10, 20], direct = [20, 50, 100] }
+first_any = true
+
+[golden]
+episodes = "golden" # + the legacy records of the golden-data store, converted by golden/convert.py
+
+[[tasks]]
+id = "tabletennis-match-wallclock-program-standard" # the Season-1 task name
+format = "match"
+action_level = "high"
+play = "program"
+[[tasks]]
+id = "tabletennis-match-wallclock-program-lowlevel-standard" # the Season-1 task name
+format = "match"
+action_level = "low"
+play = "program"
+[[tasks]]
+id = "tabletennis-match-wallclock-direct-standard" # the Season-1 task name
+format = "match"
+action_level = "high"
+play = "direct"
+slowdown = 50 # the legacy direct default (a model call per act); agent budget 10800 s
+[[tasks]]
+id = "tabletennis-duel-wallclock-program-standard" # the Season-1 task name
+format = "duel"
+action_level = "high"
+play = "program"
+[[tasks]]
+id = "tabletennis-duel-wallclock-program-lowlevel-standard" # the Season-1 task name
+format = "duel"
+action_level = "low"
+play = "program"
+[[tasks]]
+id = "tabletennis-duel-wallclock-direct-standard" # the Season-1 task name
+format = "duel"
+action_level = "high"
+play = "direct"
+slowdown = 50
+
+[broadcast] # spectators: the replay video's camera (the whole table from the side, above)
+camera = { name = "broadcast", pos = [4.4, 0.0, 2.2], lookat = [0.0, 0.0, 0.2], fovy_deg = 50, width = 640, height = 360 }
+
+[capabilities] # docs/capabilities_zh.md §6
+a1 = 2 # 3D: the ball only from two cameras (triangulation, the contact point)
+a2 = 2 # dynamics: drag, spin, bounce, the contact law
+a3 = 2 # embodiment: the paddle state (high) or joint targets with its own IK (low)
+a4 = 2 # real time: the world never waits; latency costs game time
+b1 = 1 # rules: the ITTF point rules
+b2 = 2 # strategy: placement away from the opponent, reading its returns
+b3 = 0
+physics = ["spin_bounce"]
+
+[check]
+stage_timeout_s = 10800 # stage 2 (~20 in-process matches) took ~75 min on a loaded shared host (4238 s on main without fine meshes)
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/instruction.md b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/instruction.md
new file mode 100644
index 0000000000..0791e8c639
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/instruction.md
@@ -0,0 +1,92 @@
+# Table tennis: a match against a scripted opponent, in real time
+
+You play robot table tennis (ITTF rules with the deviations below) against a scripted opponent: a MuJoCo Franka Panda holding a paddle, at your end of a real-size table, seen only through two cameras. The opponent serves every point (recorded real serves) and returns every ball it can reach; you always receive. One game to 5 points.
+
+**Your goal: win the match.** The task succeeds if the match finishes and you won it. Keep your scripts, logs and notes
+in `/app/output/`; there is nothing else to hand in: the simulator records the match.
+
+## Time does not stop
+- The world runs at 1/10 of real speed (`spec()["timing"]["slowdown"]` = 10): one 10 ms control
+ step of game time every 0.1 s of wall time. It never waits for you: while you think, the opponent
+ plays on and your robot keeps executing its last command.
+- The match starts paused. Its clock starts at your first `submit` or `get_obs(seconds > 0)`, and from then on it runs
+ until the match is over. Look at the cameras and read `spec()` first (`get_obs(seconds=0)` does not start the clock).
+- **Breaks.** After every point the match stands still for 12 s of game time (120 s of wall time):
+ the clock keeps running, nothing moves and nothing scores, and play resumes by itself at the end of the break. Use it
+ to look at what happened and fix your program. Send a `ready` row to resume earlier (put your review, why you won or
+ lost the point and what you change, in `submit`'s `note`). Commands planned for steps inside a break are dropped.
+- You have 7200 s in all. **If your session ends before the match is over, you lose** (success 0); so
+ start the match well before your time runs out and stay until it is over (`meta["done"]`).
+- No reset: one match is the whole episode.
+
+## Write a program
+A model response takes seconds, a point only a few seconds of game time, so play with a program of your own: it
+observes, measures in the images, computes its next command and submits it, in a loop, without a new model response
+for each action. Run it in the background, watch its log, and stop, fix and restart it whenever needed (also during the
+match). Use only the camera images, the service's replies and this document: no simulator internals or hidden state.
+
+## Interface
+The client is installed: `from rcb_client import Robot, EpisodeOver` (`/opt/tools/rcb_client.py`, on `PYTHONPATH`;
+its docstring is the reference). Your container has Python 3.12 with numpy, SciPy, Pillow, requests and
+opencv-python-headless; no internet except your model's API.
+
+```python
+r = Robot() # connects to the simulator, waits until it is ready
+spec = r.spec() # the facts: action_types, cameras, proprio_layout, rules, break, timing
+res = r.get_obs(seconds=0) # now, at once: res.last[cam] (H x W x 3 uint8), res.proprio (rows)
+res = r.get_obs(seconds=0.12, video_fps=25, video="frames") # watch 0.12 s of game time: res.frames[cam] (N x H x W x 3)
+r.submit("stroke", [row]) # a command: answers at once; it takes effect at the next control step
+r.submit("ready", [[0]], note="WHY ... PLAN ...") # during a break: resume now
+```
+
+- `get_obs(cameras=None, seconds=0, video_fps=10, video="frames")`: `seconds=0` returns the current images and one
+ proprio row; `seconds > 0` (at most `spec()["max_watch_s"]`) waits while that much game time runs and returns the
+ frames the cameras saw (one every 1/`video_fps` s) and one proprio row per frame. `cameras=[]`: proprio only.
+- `submit(type, rows, at=None, note="")`: one command per row; the rows become the plan from control step `at` (the
+ next step by default; `meta["control_steps"]` is the next step's number), replacing whatever was planned from there.
+ A row takes effect at its step: the command is checked and planned there, from the state of that step. Rows for
+ steps that are already gone when the request arrives are dropped (`meta["late_steps"]`); out-of-range values are
+ clipped (`meta["clipped"]`); a command the rules refuse at its step (e.g. a stroke whose contact time has already passed) changes nothing and
+ counts in the proprio column `commands_refused`.
+- `res.meta`: `control_steps`, `sim_time_s`, `time_left_s`, `done`, `reason`, `running`, `lag_s`, and `proprio`
+ (`layout`, `now`). `EpisodeOver` is raised once the match is over.
+
+Your commands (`spec()["action_types"]`):
+
+| type | row | what it does |
+|---|---|---|
+| `stroke` | `[t, x, y, z, nx, ny, nz, vx, vy, vz]` | the blade's state at contact, `t` seconds after the command takes effect: centre `x y z` (m), face normal `nx ny nz` (pointing where the ball should go), velocity `vx vy vz` (m/s). The service plans the swing (IK, joint speed limits, rehearsals on its own copy of the arm) from the arm's state at that step, then the arm returns to its ready pose. A new stroke replaces the one under way. Limits: 0 < t <= 2.5, \|x\| <= 1.2, -2.5 <= y <= -0.5, 0 <= z <= 1.2, speed <= 8 m/s (clipped, `meta["clipped"]`). The delivered state scatters by about 4 mm, 0.6 degrees and 2 % (from the task's frozen seed) |
+| `rest` | `[0]` | cancel the stroke under way: the arm returns to its ready pose |
+| `ready` | `[0]` | end the break now (see Time) |
+
+Proprioception and the referee's information (`spec()["proprio_layout"]`, one float row per frame; NaN = not
+applicable now; times in game seconds, positions in metres in your frame): `match_step`, `break`, `break_left_s`, `finished`; `score_you`, `score_opponent`, `point` (the point being played, from 1); the current ball: `ball_is_serve` (1: the opponent's serve, 0: its return), `t_since_played` (seconds since the opponent served or hit it; negative while a serve waits), `serve_in_s`, `ball_in_play`, `ball_coming` (coming to you), `ball_going` (going to the opponent); what you heard of the current ball, as the time on its clock (`t_since_played`) of the first event of each kind, NaN if not heard yet: `heard_opp_bounce_t` (a bounce on the opponent's half), `heard_own_bounce_t` (a bounce on your half), `heard_net_t`, `heard_paddle_t` (your paddle), `heard_robot_t` (your arm), `heard_floor_t`; your arm: `q1`..`q7` (joint angles, rad), `paddle_x/y/z` (blade centre), `paddle_nx/ny/nz` (face normal); the stroke under way: `stroke_active`, `stroke_contact_in_s`, and how well the planner can deliver it: `stroke_speed_scale` (> 1: the paddle speed was cut by the joint speed limits), `stroke_blade_error_m`, `stroke_normal_error_deg`, `stroke_ik_residual`; `last_point_won` (1 you, -1 the opponent, 0 a let); `commands_applied`, `commands_refused`, `last_refused_step`.
+
+Cameras: two cameras, 480 x 360 RGB each: `behind` (behind and above your robot, looking down the table) and `side` (at the side of the table, looking along +x: your robot is on the right). Pose (`position`, `forward`, `up`), field of view (45 degrees vertical), `focal_px` (434.6) and `principal_point_px` in `spec()["cameras"]`; pinhole: u = cx + f x_right / depth, v = cy - f y_up / depth. The ball is orange, the opponent is the red paddle; yellow marks every 0.25 m along the table edges. Each image is stamped with the match step `k` and the current ball's clock `t`.
+
+A ball takes about 0.6-0.9 s of game time from the opponent to you (6-9 s of wall time at S = 10). Three or more frames of the ball (`get_obs(seconds=0.12, video_fps=25, video="frames")` returns four, 40 ms apart, with one proprio row each) let you triangulate it with the two cameras and fit its flight.
+
+## Rules
+The rule texts come from RoboOlympics' `sport.toml`. Where they name RoboOlympics' own interface (`{'type': 'act', ...}`, `{'type': 'toss', ...}`, `{'type': 'none'}`, `{'type': 'target', ...}`, `state.*`, `game spec`, `/spec`), read: your `stroke`, `toss`, `rest`, `mallet` and `stop` rows, the proprio columns and `spec()`; where they say the world freezes for reviews, read: the break.
+
+- `game_format`: first to 5 points; from 4:4 a lead of 2 is needed; at 6:6 the next point wins (7 at most)
+- `rules`: after exactly one bounce on your half, hit the ball once so that it lands on your opponent's half, directly or after touching the net (the upper table edges count, the vertical sides do not); the same holds for your opponent's returns. You lose the point for a volley, a double hit, two bounces, a miss, a ball that lands on your own half or out, the ball touching your arm or handle while it is over or travelling towards your half, or your arm or paddle touching the table, net or floor. A shot that passes a player's half without touching it is out, even if it then hits that player's robot. A serve that touches the net or is irregular is a let. The receiver's 13th good return in a rally wins it the point (expedite rule). At 40 points played (lets included) the player ahead wins, at a level score the player who won the last point
+- `opponent`: format match: the opponent serves every point (you always receive) and returns every ball it can reach; higher levels react faster, reach further and play faster, wider balls with more spin (`match.opponent_level` in game spec)
+- `world`: metres; your frame: x to your right, y towards the opponent, z up; table top z = 0, |x| <= 0.7625, |y| <= 1.37; net at y = 0, top z = 0.1525; your half y < 0; your robot's base at (0, -1.75, 0) facing +y
+- `ball`: radius 0.02 m, orange; gravity 9.81 m/s^2; air drag about 0.13 |v| v; spin bends the flight by a few cm; a bounce keeps about 96 % of the vertical and 87 % of the horizontal speed; a ball takes about 0.6-0.9 s from the opponent to you
+- `reach`: the blade can meet a ball whose centre is within about 0.85 m of the shoulder (0, -1.75, 0.33) and above z = 0.12
+- `blade`: 15 x 15 cm; at contact its centre is 2.75 cm from the ball's centre along the face normal; with n the unit face normal the ball leaves with about v_out = v_paddle - 0.96((v_in - v_paddle).n)n + (v_in - v_paddle) - ((v_in - v_paddle).n)n
+- `scatter`: the serves, the opponent's returns and your strokes' execution scatter are drawn from the task's frozen seed (never shown)
+- Winner: the first player to 5 points with a lead of 2, or the first to 7, wins the game (the match); a let scores no point; if 40 points (lets included) are played, the player ahead wins and at a level score the player who won the last point (last resort, not from the rulebook)
+- Rulebook: ITTF Laws of Table Tennis (ITTF Statutes 2025, chapter 2), 2025 (effective 1 January 2025)
+- Deviation D1 (ITTF 2.11, 2.12): one game to 5 points (from 4:4 a lead of 2 is needed, at 6:6 the next point wins: 7 points at most) instead of a best-of-games match with games to 11
+- Deviation D2 (ITTF 2.6, 2.13): the robots cannot toss the ball: format match - the opponent serves every point with recorded real serves and you always receive; format duel - a neutral machine serves recorded real serves and the receiver changes every point (as under the expedite system, 2.13.3, 2.15.3)
+- Deviation D3 (ITTF 2.5.7): only the blade can strike the ball: the ball touching the handle or arm loses the point
+- Deviation D4 (ITTF 2.10.1.9-2.10.1.11): a robot has no free hand: any contact of the arm or paddle with the table, net or floor loses the point
+- Deviation D5 (ITTF 2.10.1.7): any double hit loses the point, deliberate or not
+- Deviation D6 (ITTF 2.15.4): the expedite rule applies from the first point: the receiver's 13th good return in a rally wins it the point (this bounds every rally)
+- Deviation D7 (ITTF 2.9.1.1 (let)): a serve that touches the net or is irregular is a let; duel: faults by both players at the same instant are a let; the robot that is not receiving is transparent to the serve until it bounces on the receiver's half (the recorded serves were made for an empty serving end)
+- Deviation D8 (- (cost limit, not from the rulebook)): if 40 points (lets included) are played the game ends: the player ahead wins; at a level score the player who won the last point (never reached in practice)
+
+Your robot: Franka Panda (MuJoCo Menagerie panda_nohand) holding a 15 x 15 cm paddle; its base at (0, -1.75, 0) facing +y. Everything else you need (the frame, the geometry and the rule constants) is in
+`spec()["rules"]`; the physics engine is MuJoCo.
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/solution/builtin_players.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/solution/builtin_players.py
new file mode 100644
index 0000000000..d2e88fec56
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/solution/builtin_players.py
@@ -0,0 +1,663 @@
+"""Table tennis' built-in players (core/client.py plays them over HTTP, core/local.py in-process; the same action
+interface as a model's program). Camera images, the replies and /spec only: no simulator import, no ball state.
+
+ Reference the legacy reference player of Season 1 (scripts/olympiad/tabletennis/*/solution: wc_player.py + arm.py
+ + the oracle loops), one class for every format and action level:
+ perception detect the orange ball in the 8 tiles (2 cameras x 4 frames), triangulate each frame from
+ the two cameras (/spec intrinsics), fit the flight (gravity + quadratic drag, an extra
+ constant acceleration for the unknown spin) and predict the contact after our bounce;
+ shot the paddle state at contact from the contact law, aimed away from the opponent;
+ high level `act` {t, pos, normal, vel} (the service plans the stroke);
+ low level its own arm model from /spec (FK of the documented chain, damped least-squares IK, a
+ joint-speed-limited Hermite swing) streamed as `traj` joint targets, a slew back to the
+ ready pose between balls.
+ Over HTTP it estimates when its act takes effect from the observation's step, the render time and its
+ own latency; in-process (no `timing` in /spec) the act takes effect at the observed step.
+ Idle never acts (the generic tests' check policy: every point ends quickly).
+numpy + Pillow only: this file is also the task's oracle (solution/)."""
+from __future__ import annotations
+
+import base64
+import io
+import math
+import time
+
+import numpy as np
+from PIL import Image
+
+
+# ================================================================================================ perception and shot (wc_player.py)
+G = np.array([0.0, 0.0, -9.81])
+KD = 0.13 # drag: deceleration KD |v| v (instructions: about 0.13)
+E_BOUNCE_Z, E_BOUNCE_XY = 0.96, 0.87
+BALL_R = 0.02
+OFFSET = 0.0275 # blade centre = ball centre - OFFSET * normal (ball radius + half the blade thickness)
+E_PADDLE = 0.96
+TILE_W, TILE_H = 480, 360
+TABLE_X, TABLE_Y = 0.7625, 1.37
+NET_Z = 0.1525
+
+
+# ------------------------------------------------------------------------------------------------ cameras
+class Cam:
+ def __init__(self, c: dict):
+ self.pos = np.array(c["position"], float)
+ self.fw = np.array(c["forward"], float); self.fw /= np.linalg.norm(self.fw)
+ self.up = np.array(c["up"], float); self.up /= np.linalg.norm(self.up)
+ self.rt = np.cross(self.fw, self.up)
+ self.f = float(c.get("focal_px", 434.6))
+ pp = c.get("principal_point_px", [240, 180])
+ self.cx, self.cy = float(pp[0]), float(pp[1])
+
+ def project(self, X):
+ d = np.asarray(X, float) - self.pos
+ z = d @ self.fw
+ return self.cx + self.f * (d @ self.rt) / z, self.cy - self.f * (d @ self.up) / z
+
+ def ray(self, u, v):
+ d = self.fw + ((u - self.cx) / self.f) * self.rt - ((v - self.cy) / self.f) * self.up
+ return self.pos, d / np.linalg.norm(d)
+
+
+def triangulate(rays):
+ """Least-squares point closest to all rays; (point, rms distance to the rays)."""
+ A = np.zeros((3, 3)); b = np.zeros(3)
+ for o, d in rays:
+ P = np.eye(3) - np.outer(d, d)
+ A += P; b += P @ o
+ X = np.linalg.solve(A, b)
+ res = [np.linalg.norm((np.eye(3) - np.outer(d, d)) @ (X - o)) for o, d in rays]
+ return X, float(np.sqrt(np.mean(np.square(res))))
+
+
+# ------------------------------------------------------------------------------------------------ detection
+def decode(png: bytes) -> np.ndarray:
+ return np.asarray(Image.open(io.BytesIO(png)).convert("RGB"))
+
+
+def ball_mask(t: np.ndarray) -> np.ndarray:
+ r = t[..., 0].astype(np.int16); g = t[..., 1].astype(np.int16); b = t[..., 2].astype(np.int16)
+ return (r > 70) & (b * 8 < r) & (g * 100 > 58 * r) & (g * 100 < 82 * r)
+
+
+def detect_tile(t: np.ndarray):
+ """(u, v) of the ball's centroid in a tile, or None."""
+ m = ball_mask(t)
+ m[:16, :70] = False # the time stamp
+ ys, xs = np.nonzero(m)
+ if len(xs) == 0:
+ return None
+ if len(xs) > 400: # far too many: not a ball
+ return None
+ mx, my = np.median(xs), np.median(ys)
+ sel = (np.abs(xs - mx) <= 8) & (np.abs(ys - my) <= 8)
+ if sel.sum() == 0:
+ return None
+ w = t[ys[sel], xs[sel], 0].astype(float)
+ # +0.5: pixel i covers [i, i + 1) in the pinhole model
+ return float(np.average(xs[sel], weights=w)) + 0.5, float(np.average(ys[sel], weights=w)) + 0.5
+
+
+def detect_views(img: np.ndarray, cams: list[Cam], times: list[float], max_res: float = 0.03):
+ """Per frame time: the triangulated ball centre (or nothing). img: 2 rows (cameras) x 4 columns (frames)."""
+ out = []
+ for j, tt in enumerate(times):
+ rays = []
+ for i, c in enumerate(cams):
+ tile = img[i * TILE_H:(i + 1) * TILE_H, j * TILE_W:(j + 1) * TILE_W]
+ uv = detect_tile(tile)
+ if uv is not None:
+ rays.append(c.ray(*uv))
+ if len(rays) == 2:
+ X, res = triangulate(rays)
+ if res < max_res and -0.2 < X[2] < 2.0 and abs(X[1]) < 3.0:
+ out.append((float(tt), X))
+ return out
+
+
+# ------------------------------------------------------------------------------------------------ flight model
+def rollout(p, v, dt, n, bounce=True, a_extra=None):
+ """Explicit integration (semi-implicit Euler) of gravity + drag (+ a constant extra acceleration); the table bounce
+ (restitution) when bounce=True. Returns positions (n+1, 3), velocities (n+1, 3), list of bounce indices."""
+ p = np.array(p, float); v = np.array(v, float)
+ P = np.empty((n + 1, 3)); V = np.empty((n + 1, 3)); P[0] = p; V[0] = v
+ ae = np.zeros(3) if a_extra is None else np.asarray(a_extra, float)
+ bounces = []
+ for i in range(1, n + 1):
+ sp = math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2])
+ a = G - KD * sp * v + ae
+ v = v + a * dt
+ p = p + v * dt
+ if bounce and p[2] < BALL_R and v[2] < 0 and abs(p[0]) <= TABLE_X + 0.01 and abs(p[1]) <= TABLE_Y + 0.01:
+ v = np.array([v[0] * E_BOUNCE_XY, v[1] * E_BOUNCE_XY, -v[2] * E_BOUNCE_Z])
+ p[2] = 2 * BALL_R - p[2]
+ bounces.append(i)
+ P[i] = p; V[i] = v
+ return P, V, bounces
+
+
+def _states_at(p0, v0, t0, times, dt=0.002, a_extra=None):
+ """Positions at `times` (all >= t0, no bounce in between) from the state (p0, v0) at t0."""
+ times = np.asarray(times, float)
+ n = int(math.ceil((times.max() - t0) / dt)) + 1
+ P, _, _ = rollout(p0, v0, dt, n, bounce=False, a_extra=a_extra)
+ idx = (times - t0) / dt
+ i0 = np.clip(np.floor(idx).astype(int), 0, n - 1)
+ f = (idx - i0)[:, None]
+ return P[i0] * (1 - f) + P[i0 + 1] * f
+
+
+def fit_flight(obs, n_iter=6, fit_accel=False, a_fixed=None):
+ """obs: [(t, X)] of one flight segment (no bounce in between). Returns (t0, p0, v0, a_extra, rms) with t0 = the
+ first observation's time, or None. fit_accel: also fit a constant extra acceleration (the Magnus force of the
+ unknown spin) when there are >= 6 points; a_fixed: use this extra acceleration instead."""
+ af = None if a_fixed is None else np.asarray(a_fixed, float)
+ if len(obs) < 2:
+ return None
+ obs = sorted(obs, key=lambda o: o[0])
+ T = np.array([o[0] for o in obs]); X = np.array([o[1] for o in obs])
+ t0 = T[0]
+ if len(obs) == 2:
+ v = (X[1] - X[0]) / (T[1] - T[0]) - 0.5 * G * (T[1] - T[0])
+ return t0, X[0], v, (np.zeros(3) if af is None else af), 0.0
+ # initial guess: quadratic fit per axis
+ A = np.vstack([np.ones_like(T), T - t0, (T - t0) ** 2]).T
+ coef = np.linalg.lstsq(A, X, rcond=None)[0]
+ th = np.r_[coef[0], coef[1], np.zeros(3)]
+ npar = 9 if (fit_accel and af is None and len(obs) >= 6) else 6
+ th = th[:npar]
+ for _ in range(n_iter):
+ def pred(th_):
+ ae = th_[6:9] if npar == 9 else af
+ return _states_at(th_[0:3], th_[3:6], t0, T, a_extra=ae).ravel()
+ r = X.ravel() - pred(th)
+ J = np.zeros((len(r), npar))
+ for c in range(npar):
+ d = np.zeros(npar); d[c] = 1e-4
+ J[:, c] = (pred(th + d) - pred(th)) / 1e-4
+ reg = 1e-6 * np.eye(npar)
+ if npar == 9:
+ reg[6:, 6:] = np.eye(3) * 1e-2 # keep the extra acceleration small unless the data insist
+ step = np.linalg.solve(J.T @ J + reg, J.T @ r)
+ th = th + step
+ if np.linalg.norm(step) < 1e-6:
+ break
+ rms = float(np.sqrt(np.mean((X.ravel() - pred(th)) ** 2)))
+ ae = th[6:9] if npar == 9 else (np.zeros(3) if af is None else af)
+ return t0, th[0:3], th[3:6], ae, rms
+
+
+def predict_contact(t0, p0, v0, a_extra=None, need_bounce=True, t_max=1.6, dt=0.001):
+ """From the state at t0: our bounce (if need_bounce), then the top of the arc after it (or the point where the ball
+ crosses y = -1.38 going down-table, if earlier). Returns (t_contact, p, v) or None."""
+ n = int(t_max / dt)
+ P, V, bounces = rollout(p0, v0, dt, n, bounce=True, a_extra=a_extra)
+ if need_bounce:
+ own = [i for i in bounces if P[i, 1] < 0]
+ if not own:
+ return None
+ i_b = own[0]
+ else:
+ i_b = 0
+ for i in range(i_b + 1, n):
+ if V[i, 2] <= 0 or P[i, 1] < -1.38:
+ return t0 + i * dt, P[i].copy(), V[i].copy()
+ if P[i, 2] < BALL_R:
+ return None
+ return None
+
+
+# ------------------------------------------------------------------------------------------------ stroke
+def landing(p, v, dt=0.004, n=450):
+ """First table contact (x, y) of a free flight after our hit and whether it cleared the net."""
+ P, _, b = rollout(p, v, dt, n, bounce=True)
+ i_net = None
+ for i in range(1, len(P)):
+ if P[i - 1, 1] < 0 <= P[i, 1]:
+ i_net = i
+ if b and i == b[0]:
+ clear = i_net is not None and P[i_net, 2] > NET_Z + BALL_R + 0.03
+ return P[i, :2], clear
+ if P[i, 2] < -0.5:
+ break
+ return None, False
+
+
+def solve_out(p, aim, vy=5.0):
+ """Outgoing ball velocity (vx, vy, vz) from p that lands at `aim` (Newton on vx, vz)."""
+ v = np.array([(aim[0] - p[0]) * vy / max(0.5, aim[1] - p[1]), vy, 1.2])
+ for _ in range(12):
+ L, ok = landing(p, v)
+ if L is None:
+ v[2] += 0.3
+ continue
+ err = L - np.asarray(aim)
+ if np.linalg.norm(err) < 0.01:
+ return v, ok
+ J = np.zeros((2, 2))
+ for c, ix in enumerate((0, 2)):
+ dv = np.zeros(3); dv[ix] = 0.02
+ L2, _ = landing(p, v + dv)
+ if L2 is None:
+ return v, False
+ J[:, c] = (L2 - L) / 0.02
+ try:
+ dx = np.linalg.solve(J, err)
+ except np.linalg.LinAlgError:
+ return v, False
+ dx = np.clip(dx, -1.0, 1.0)
+ v[0] -= dx[0]; v[2] -= dx[1]
+ L, ok = landing(p, v)
+ return v, bool(ok and L is not None and np.linalg.norm(L - np.asarray(aim)) < 0.05)
+
+
+def paddle_for(p_hit, v_in, v_out, tangential=True):
+ """Contact law (instructions): the normal component of the relative velocity reverses with restitution E_PADDLE,
+ the tangential one is kept. With n along (v_out - v_in) the tangential part of the ball is unchanged, so the paddle
+ moves with the ball tangentially and v_p.n = (v_out.n + E v_in.n) / (1 + E)."""
+ dv = v_out - v_in
+ n = dv / np.linalg.norm(dv)
+ vpn = (v_out @ n + E_PADDLE * (v_in @ n)) / (1 + E_PADDLE)
+ v_t = v_in - (v_in @ n) * n
+ v_p = vpn * n + (v_t if tangential else 0.0)
+ p_c = p_hit - OFFSET * n
+ return p_c, n, v_p
+
+
+# ------------------------------------------------------------------------------------------------ the player
+DT = 0.01
+
+
+class Player:
+ """Keeps the frames of the current incoming ball, predicts the contact, decides when to (re-)act.
+
+ update(obs, img, k_req): one observation (its `view_times`, `heard`, `t_since_played`, `step`, `point`, `ball`).
+ decide(k_now): an act dict {"t", "pos", "normal", "vel"} (T from the step k_now) or None.
+ """
+
+ def __init__(self, cams, aim_y=0.85, aim_x=0.45, vys=(5.0, 4.6, 4.2, 3.8, 3.4, 3.0), vp_max=1.4, tangential=True,
+ verbose=False):
+ self.cams = cams
+ self.aim_y, self.aim_x, self.vys, self.vp_max, self.tangential = aim_y, aim_x, tuple(vys), vp_max, tangential
+ self.verbose = verbose
+ self.leg = None
+ self.log = []
+
+ def _new_leg(self, key, obs):
+ self.leg = {"key": key, "frames": {}, "heard": [], "acts": [], "launch": key[2], "kind": obs.get("ball"),
+ "opp_x": None, "done": False, "pred": None}
+
+ def update(self, obs: dict, img, k_req: int):
+ launch = int(round(k_req - float(obs["t_since_played"]) / DT))
+ key = (obs.get("point"), obs.get("ball"), launch)
+ if self.leg is None or self.leg["key"] != key:
+ self._new_leg(key, obs)
+ L = self.leg
+ L["heard"] = obs.get("heard") or []
+ if any(h["event"] in ("paddle", "robot") for h in L["heard"]):
+ L["done"] = True
+ if obs.get("ball_state") != "coming to you":
+ L["done"] = True
+ if img is not None and not L["done"]:
+ # frame times on this ball's clock from the absolute frame steps (a tile's own stamp is relative to the
+ # ball that was current when the frame was taken: right after the opponent's hit, older tiles show our
+ # outgoing ball with that ball's clock)
+ if obs.get("view_steps") is not None:
+ times = [round((k - L["launch"]) * DT, 3) for k in obs["view_steps"]]
+ else:
+ times = obs["view_times"]
+ for t, X in detect_views(img, self.cams, times):
+ if t > 0.005:
+ L["frames"][round(t, 3)] = X
+ return L
+
+ def _bounce_t(self, which):
+ ev = {"opp": "bounce on the opponent's half", "own": "bounce on your half"}[which]
+ ts = [h["t"] for h in self.leg["heard"] if h["event"] == ev]
+ return ts[0] if ts else None
+
+ def predict(self):
+ L = self.leg
+ F = sorted(L["frames"].items())
+ t_own = self._bounce_t("own")
+ if L["kind"] == "serve":
+ t_opp = self._bounce_t("opp")
+ if t_opp is None:
+ return None
+ start = t_opp + 0.005
+ else:
+ start = 0.0
+ A = [(t, X) for t, X in F if start < t and (t_own is None or t < t_own - 0.003)]
+ fa = fit_flight(A, fit_accel=True) if len(A) >= 3 else None
+ if t_own is not None:
+ B = [(t, X) for t, X in F if t > t_own + 0.003]
+ if len(B) >= 3:
+ fb = fit_flight(B, a_fixed=None if fa is None else fa[3])
+ pc = predict_contact(fb[0], fb[1], fb[2], fb[3], need_bounce=False)
+ if pc is not None:
+ return pc + ("post", len(B))
+ if fa is None:
+ return None
+ pc = predict_contact(fa[0], fa[1], fa[2], fa[3], need_bounce=t_own is None)
+ if pc is None:
+ return None
+ return pc + ("pre", len(A))
+
+ def opp_x(self):
+ """Where the opponent is: for a return, where it hit the ball (the first frames of this ball); at a serve it
+ stands at the centre."""
+ L = self.leg
+ if L["kind"] == "serve" or not L["frames"]:
+ return 0.0
+ t, X = min(L["frames"].items())
+ return float(X[0]) if t < 0.2 else 0.0
+
+ def stroke(self, p_hit, v_in, vp_max=None):
+ """Aim away from the opponent; among outgoing speeds (vy = 5.0 ... 3.8 m/s) take the fastest whose paddle
+ speed the arm can deliver (about VP_MAX m/s at the usual contact poses, from the `act` replies)."""
+ ox = self.opp_x()
+ side = -1.0 if ox > 0.05 else (1.0 if ox < -0.05 else (-1.0 if p_hit[0] > 0 else 1.0))
+ aim = np.array([side * self.aim_x, self.aim_y])
+ best = None
+ for vy in self.vys:
+ v_out, ok = solve_out(p_hit, aim, vy)
+ if not ok:
+ continue
+ p_c, n, v_p = paddle_for(p_hit, v_in, v_out, self.tangential)
+ sp = float(np.linalg.norm(v_p))
+ if sp <= (self.vp_max if vp_max is None else vp_max):
+ return p_c, n, v_p, aim
+ if best is None or sp < best[0]:
+ best = (sp, p_c, n, v_p)
+ if best is None:
+ v_out, _ = solve_out(p_hit, aim, self.vys[-1])
+ p_c, n, v_p = paddle_for(p_hit, v_in, v_out, self.tangential)
+ return p_c, n, v_p, aim
+ return best[1], best[2], best[3], aim
+
+ def decide(self, k_now_fn):
+ """k_now_fn(): the current game time in (fractional) control steps, as well as the client can tell; called
+ again after the stroke is computed, so T counts from when the act will reach the service."""
+ L = self.leg
+ if L is None or L["done"]:
+ return None
+ pr = self.predict()
+ if pr is None:
+ return None
+ tc, p, v, phase, nfr = pr
+ L["pred"] = pr
+ t_now = (k_now_fn() - L["launch"]) * DT
+ lead = tc - t_now
+ if lead < 0.04:
+ return None
+ last = L["acts"][-1] if L["acts"] else None
+ cap_changed = last is not None and last.get("vp_cap") != L.get("vp_cap")
+ if last is not None and not cap_changed:
+ dp = float(np.linalg.norm(p - last["p_hit"]))
+ dtc = abs(tc - last["tc"])
+ new_phase = phase == "post" and last["phase"] == "pre"
+ if not new_phase and dp < 0.012 and dtc < 0.006:
+ return None
+ if lead < 0.07 and dp < 0.03 and not new_phase:
+ return None
+ p_c, n, v_p, aim = self.stroke(p, v, L.get("vp_cap", self.vp_max))
+ k_eff = math.floor(k_now_fn()) # the act applies at the start of the step after the current state
+ T = tc - (k_eff - L["launch"]) * DT
+ if T <= 0.02:
+ return None
+ act = {"t": round(float(T), 4), "pos": [round(float(x), 4) for x in p_c],
+ "normal": [round(float(x), 4) for x in n], "vel": [round(float(x), 3) for x in v_p]}
+ L["acts"].append({"tc": tc, "p_hit": p.copy(), "phase": phase, "k_eff": k_eff, "act": act, "nfr": nfr,
+ "aim": aim.tolist(), "vp": float(np.linalg.norm(v_p)), "vp_cap": L.get("vp_cap")})
+ return act
+
+ def on_act_reply(self, stroke: dict | None):
+ """The service says how much of the paddle speed the arm can deliver (speed_scale): cap the next strokes of this
+ ball below that, and re-plan."""
+ L = self.leg
+ if not stroke or L is None or not L["acts"]:
+ return
+ sc = stroke.get("speed_scale") or 1.0
+ if sc > 1.02:
+ cap = 0.95 * L["acts"][-1]["vp"] / sc
+ L["vp_cap"] = round(min(cap, L.get("vp_cap", self.vp_max)), 3)
+
+
+# ================================================================================================ the arm model (arm.py, low level)
+
+
+def quat_mat(q):
+ w, x, y, z = q
+ return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
+ [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
+ [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]])
+
+
+def axis_rot(a, t):
+ a = np.asarray(a, float) / np.linalg.norm(a)
+ K = np.array([[0, -a[2], a[1]], [a[2], 0, -a[0]], [-a[1], a[0], 0]])
+ return np.eye(3) + np.sin(t) * K + (1 - np.cos(t)) * K @ K
+
+
+def hermite(q0, v0, q1, v1, T, n):
+ t = np.arange(1, n + 1) * (T / n)
+ s = t / T
+ h00 = 2 * s**3 - 3 * s**2 + 1; h10 = s**3 - 2 * s**2 + s; h01 = -2 * s**3 + 3 * s**2; h11 = s**3 - s**2
+ return h00[:, None] * q0 + h10[:, None] * T * v0 + h01[:, None] * q1 + h11[:, None] * T * v1
+
+
+class Arm:
+ def __init__(self, spec: dict):
+ kin, lim = spec["kinematics"], spec["limits"]
+ self.chain = [(np.array(b["pos_in_parent"], float), quat_mat(b["quat_in_parent_wxyz"]),
+ None if "joint" not in b else np.array(b["joint_axis_in_body"], float)) for b in kin["chain"]]
+ self.site = np.array(kin["blade_center_in_paddle"], float)
+ self.low = np.array(lim["joint_low_rad"], float)
+ self.high = np.array(lim["joint_high_rad"], float)
+ self.vlim = np.array(lim["joint_speed_limit_rad_s"], float)
+ self.step_lim = np.array(lim["max_target_step_rad"], float)
+ self.q0 = np.array(lim["ready_pose_rad"], float)
+ rng = np.random.default_rng(0)
+ self.starts = [self.q0] + [np.clip(self.q0 + rng.normal(0, .8, 7), self.low + .05, self.high - .05)
+ for _ in range(12)]
+
+ def fk_full(self, q):
+ """(blade centre, paddle rotation (columns: x = face normal), joint axes (7, 3), joint origins (7, 3))."""
+ p, R = np.zeros(3), np.eye(3)
+ axes, origins, j = [], [], 0
+ for pos, Rb, ax in self.chain:
+ p = p + R @ pos
+ R = R @ Rb
+ if ax is not None:
+ axes.append(R @ ax); origins.append(p.copy())
+ R = R @ axis_rot(ax, q[j]); j += 1
+ return p + R @ self.site, R, np.array(axes), np.array(origins)
+
+ def fk(self, q):
+ p, R, _, _ = self.fk_full(q)
+ return p, R
+
+ def jacobian(self, q):
+ p, R, Z, O = self.fk_full(q)
+ Jp = np.cross(Z, p - O).T
+ return np.vstack([Jp, Z.T]), p, R
+
+ def ik(self, pos, normal, q_init, iters=200, tol=1e-4):
+ q = np.array(q_init, float)
+ n_t = np.asarray(normal, float) / np.linalg.norm(normal)
+ err = np.inf
+ for _ in range(iters):
+ J, p, R = self.jacobian(q)
+ n = R[:, 0]
+ e = np.concatenate((pos - p, np.cross(n, n_t)))
+ err = float(np.linalg.norm(e[:3]) + np.arcsin(min(1.0, np.linalg.norm(e[3:]))))
+ if n @ n_t < 0:
+ e[3:] = np.cross(n, n_t) + 0.5 * np.cross(n, R[:, 1]); err += np.pi / 2
+ if err < tol:
+ break
+ q = np.clip(q + J.T @ np.linalg.solve(J @ J.T + 1e-3 * np.eye(6), e), self.low + 1e-4, self.high - 1e-4)
+ return q, err
+
+ def ik_best(self, pos, normal, q_ref):
+ """An accurate branch with little joint travel from q_ref (as the high-level service chooses it)."""
+ def travel(c):
+ return float(np.max(np.abs(c[0] - q_ref) / self.vlim))
+ def rank(c):
+ return (0, travel(c)) if c[1] < 1e-4 else (1, c[1])
+ best = self.ik(pos, normal, q_ref)
+ if best[1] < 1e-4 and travel(best) <= .35:
+ return best
+ for s in self.starts:
+ c = self.ik(pos, normal, s)
+ if rank(c) < rank(best):
+ best = c
+ if best[1] < 1e-4 and travel(best) <= .35:
+ break
+ return best
+
+ def stroke(self, q_s, v_s, n_avail, p_c, nrm, v_p, q_ref=None):
+ """Joint targets for the next n_avail steps + a follow-through, from the target q_s moving at v_s, so that at
+ the end of step n_avail the blade centre is at p_c with face normal nrm and velocity v_p. Returns (rows, info).
+ """
+ nrm = np.asarray(nrm, float) / np.linalg.norm(nrm)
+ q_h, res = self.ik_best(np.asarray(p_c, float), nrm, q_s if q_ref is None else q_ref)
+ J, _, _ = self.jacobian(q_h)
+ Jp = J[:3]
+ W = np.diag(self.vlim ** 2)
+ qd_h = W @ Jp.T @ np.linalg.solve(Jp @ W @ Jp.T, np.asarray(v_p, float))
+ ratio = float(np.max(np.abs(qd_h) / self.vlim))
+ scale = max(1.0, ratio / 0.9)
+ qd_h = qd_h / scale
+ n_sw = n_avail
+ if np.max(np.abs(v_s)) < 1e-6:
+ for n in range(25, n_avail + 1):
+ sw = hermite(q_s, np.zeros(7), q_h, qd_h, n * DT, n)
+ if np.max(np.abs(np.diff(np.vstack([q_s, sw]), axis=0)) / (self.vlim * DT)) <= 0.97:
+ n_sw = n
+ break
+ n_sw = int(min(n_sw, n_avail))
+ pre = np.tile(q_s, (n_avail - n_sw, 1))
+ swing = hermite(q_s, v_s if n_sw == n_avail else np.zeros(7), q_h, qd_h, n_sw * DT, n_sw)
+ n_f = 25
+ follow = hermite(q_h, qd_h, q_h + qd_h * 0.5 * n_f * DT, np.zeros(7), n_f * DT, n_f)
+ rows, prev = [], q_s
+ lim = self.step_lim * 0.995
+ for q in np.vstack([pre, swing, follow]):
+ q = np.clip(q, self.low + 1e-4, self.high - 1e-4)
+ q = prev + np.clip(q - prev, -lim, lim)
+ rows.append(q); prev = q
+ return np.array(rows), {"ik_residual": round(float(res), 5), "speed_scale": round(scale, 3), "n_swing": n_sw}
+
+ def back_to_ready(self, q_s, n=60, frac=0.6):
+ """Speed-limited joint-space return to the ready pose (60 % of the speed limits)."""
+ rows, q = [], np.array(q_s, float)
+ lim = self.step_lim * frac
+ for _ in range(n):
+ q = q + np.clip(self.q0 - q, -lim, lim)
+ rows.append(q.copy())
+ return np.array(rows)
+
+
+# ================================================================================================ the built-in players
+LEAD = 2 # low level: steps between "now" and where a new swing branches off
+MAX_ROWS = 300 # low level: rows per traj command (/spec limits.max_rows_per_command)
+
+
+def _in_range(a):
+ p, v, n = (np.asarray(a[k], float) for k in ("pos", "vel", "normal"))
+ return bool(0 < a["t"] <= 2.5 and abs(p[0]) <= 1.2 and -2.5 <= p[1] <= -0.5 and 0 <= p[2] <= 1.2
+ and np.linalg.norm(v) <= 8 and np.linalg.norm(n) > 1e-6 and np.all(np.isfinite(np.r_[p, v, n])))
+
+
+class Reference:
+ def __init__(self, spec: dict, seat: str, seed: int = 0):
+ self.low = spec.get("action_level") == "low"
+ self.period = (spec.get("timing") or {}).get("period_s") # None in-process (core/local.py)
+ self.P = Player([Cam(c) for c in spec["cameras"]])
+ self.A = Arm(spec) if self.low else None
+ q0 = self.A.q0.copy() if self.low else None
+ self.cmd = {"kind": "hold", "k0": 0, "rows": None, "anchor": (0, q0), "slew": None}
+
+ # ---------------------------------------------------------------- when an act takes effect
+ def _clock(self, st, ob):
+ step, t0 = float(st["step"]), time.monotonic()
+ if self.period is None:
+ return lambda: step # in-process: the act takes effect before this control step
+ # the state is from before the images were drawn; an act takes effect at the control-step boundary after it
+ # arrives, i.e. before step floor(now) runs (+ about 30 ms for the request and, in the duel, the IK)
+ lag = float(ob.get("render_wall_s") or 0.0) + 0.03
+ return lambda: step + (lag + time.monotonic() - t0) / self.period
+
+ # ---------------------------------------------------------------- low level: the command in force
+ def _observe_cmd(self, st):
+ c = self.cmd
+ c["anchor"] = (int(st["step"]) - 1, np.array(st["q_target"], float))
+ now = st.get("command")
+ if now == "hold":
+ c["kind"] = "hold"
+ elif isinstance(now, dict) and now.get("type") == "slew" and c["kind"] == "traj":
+ c["kind"], c["slew"] = "slew", np.array(now["q"], float)
+
+ def _target(self, k):
+ c = self.cmd
+ ka, qa = c["anchor"]
+ if c["kind"] == "traj" and k >= c["k0"]:
+ return c["rows"][min(k - c["k0"], len(c["rows"]) - 1)]
+ if c["kind"] == "slew":
+ q, lim = qa.copy(), self.A.step_lim * 0.6
+ for _ in range(max(0, k - ka)):
+ q = q + np.clip(c["slew"] - q, -lim, lim)
+ return q
+ return qa.copy()
+
+ # ---------------------------------------------------------------- one decision
+ def act(self, view):
+ st, ob = view["state"], view.get("observation") or {}
+ if st.get("world") not in (None, "running"):
+ return None
+ k_now = self._clock(st, ob)
+ incoming = st.get("ball_state") == "coming to you" and bool(st.get("ball_in_play"))
+ if self.low:
+ self._observe_cmd(st)
+ img = None
+ if incoming and ob.get("image_png_b64"):
+ img = decode(base64.b64decode(ob["image_png_b64"]))
+ obs = dict(st, view_steps=ob.get("view_steps"), view_times=ob.get("view_times"))
+ self.P.update(obs, img, int(st["step"]))
+ a = self.P.decide(k_now) if incoming else None
+ if a and not self.low and not _in_range(a): # the act limits (/spec actions): never send a 400
+ a = None
+ if not self.low:
+ return {"type": "act", **a} if a else None
+ if a:
+ k_eff = math.floor(k_now())
+ k_hit, kb = k_eff + int(round(a["t"] / DT)), k_eff + LEAD
+ if k_hit - kb >= 3:
+ q_s = self._target(kb - 1)
+ v_s = (self._target(kb - 1) - self._target(kb - 2)) / DT
+ rows, info = self.A.stroke(q_s, v_s, k_hit - kb, a["pos"], a["normal"], a["vel"])
+ self.P.on_act_reply({"speed_scale": info["speed_scale"]})
+ head = np.array([self._target(k) for k in range(k_eff, kb)]).reshape(-1, 7)
+ rows = np.round(np.vstack([head, rows]), 6)[:MAX_ROWS]
+ self.cmd.update(kind="traj", k0=int(k_eff), rows=rows)
+ return {"type": "traj", "k0": int(k_eff), "q": rows.tolist()}
+ return None
+ k = int(st["step"])
+ c = self.cmd
+ busy = c["kind"] == "traj" and k < c["k0"] + len(c["rows"]) - 1
+ if not incoming and not busy and c["kind"] != "slew" and np.max(np.abs(self._target(k) - self.A.q0)) > 1e-4:
+ q0 = self.A.q0.round(6)
+ c.update(kind="slew", slew=q0)
+ return {"type": "slew", "q": q0.tolist(), "speed": 0.6}
+ return None
+
+ def review(self, reply):
+ return "reference player: scripted", "reference player: same policy"
+
+
+class Idle:
+ def __init__(self, spec: dict, seat: str, seed: int = 0):
+ pass
+
+ def act(self, view):
+ return None
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/solution/oracle_play.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/solution/oracle_play.py
new file mode 100644
index 0000000000..0f36ecd9a3
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/solution/oracle_play.py
@@ -0,0 +1,236 @@
+"""Harbor oracle: the sport's RoboOlympics reference player (builtin_players.Reference, next to this file: camera images
+and the documented facts only) driven through the agent's own client (rcb_client.py, eai-standard/2.3).
+
+The reference players were written for RoboOlympics' realtime interface: each step they get a `view` -- the state
+(score, the ball's clock, what was heard, the robot's own body) and a tiled PNG of the newest camera frames -- and
+return an act body or nothing. This loop builds that view from /observe (a short watch: the frames and one proprio row
+per frame), turns the act into a /submit row of the task's action type, and sends `ready` (with the player's review as
+the note) once per break. Nothing here reads simulator state the agent could not read.
+
+Timing (table tennis, badminton): the players also have an in-process mode in which an act takes effect exactly at the
+observed step. 2.3's `at` makes that exact over HTTP too: the loop picks the control step its command will take effect
+at (a margin of LEAD_STEPS after the step it estimates is running now), hands the player the view as of that step (the
+step and the times relative to it shifted accordingly; images and frame steps are absolute), and submits the command
+with `at` = that step. Host load then delays the command's arrival, never its effect.
+"""
+from __future__ import annotations
+
+import base64
+import io
+import math
+import os
+import sys
+import time
+
+import numpy as np
+from PIL import Image
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import builtin_players as bp # noqa: E402
+from rcb_client import EpisodeOver, Robot # noqa: E402
+
+NAN = float("nan")
+LEAD_STEPS = 5 # control steps between "now" (estimated) and a command's planned effect: 0.5 s of wall
+ # time at S = 10 for the player's own computation and the request
+
+
+def num(x):
+ return None if x is None or (isinstance(x, float) and math.isnan(x)) else x
+
+
+def png_b64(rows: list) -> tuple[str, list]:
+ """rows of tiles (one row per camera) -> base64 PNG and the tile list."""
+ sheet = np.concatenate([np.concatenate(r, axis=1) for r in rows], axis=0)
+ buf = io.BytesIO()
+ Image.fromarray(np.ascontiguousarray(sheet[..., :3])).save(buf, format="PNG", compress_level=1)
+ return base64.b64encode(buf.getvalue()).decode(), []
+
+
+class Bridge:
+ def __init__(self):
+ self.r = Robot()
+ self.spec = self.r.spec()
+ self.sport = self.spec["sport"]
+ self.layout = self.spec["proprio_layout"]
+ self.dt = float(self.spec["control_dt"])
+ self.period = float(self.spec["timing"]["wall_s_per_control_step"])
+ self.cams = list(self.spec["cameras"])
+ rules = self.spec.get("rules") or {}
+ cams = []
+ for name in self.cams:
+ c = dict(self.spec["cameras"][name], name=name)
+ if self.sport == "airhockey":
+ c.update(width=c["hw"][1], height=c["hw"][0])
+ cams.append(c)
+ self.exact = self.sport in ("tabletennis", "badminton") # the in-process timing mode (module docstring)
+ ref = {"cameras": cams, "action_level": self.spec["match"]["action_level"],
+ "timing": {"period_s": None if self.exact else self.period}, **rules}
+ self.player = bp.Reference(ref, "A", 0)
+ self.reviewed_break = None
+ self.n_obs = 0
+ self.hist: list = [] # (match step, proprio row, {cam: image}) of recent observations
+ self.spacing = {"tabletennis": 4, "badminton": 6}.get(self.sport, 1) # 40 / 60 ms, as RoboOlympics' views
+ self.running = False
+ # how often the loop looks (control steps): badminton at RoboOlympics' own client cadence (an observation, then
+ # `wait 0.05`): a player that re-plans its stroke at every step keeps the arm from ever finishing a swing
+ self.every = {"badminton": 5}.get(self.sport, 1)
+ # badminton: a command waits `lead_steps` after its step (stroke_pending_effect_step shows it then); before
+ # that it is still in the service's plan, which the proprio does not show: the loop marks it pending itself
+ self.lead = int(((self.spec.get("rules") or {}).get("act") or {}).get("lead_steps", 0))
+ self.pending_until = -1
+
+ # ------------------------------------------------------------------ one view
+ def rows(self, res) -> list[dict]:
+ P = np.asarray(res.proprio, float).reshape(-1, len(self.layout))
+ return [dict(zip(self.layout, map(float, row))) for row in P]
+
+ def state(self, p: dict, shift: int = 0) -> dict:
+ """The player's state as of `shift` control steps after the proprio row p (relative times shifted)."""
+ p = dict(p)
+ for k in ("t_since_played",):
+ if k in p and not math.isnan(p[k]):
+ p[k] += shift * self.dt
+ for k in ("serve_opens_in_s", "serve_deadline_in_s", "stroke_contact_in_s"):
+ if k in p and not math.isnan(p[k]):
+ p[k] -= shift * self.dt
+ if "serve_opens_in_s" in p and not math.isnan(p["serve_opens_in_s"]):
+ p["serve_opens_in_s"] = max(0.0, p["serve_opens_in_s"])
+ st = {"step": int(p["match_step"]) + shift, "world": "frozen" if p["break"] > 0.5 else "running",
+ "done": p["finished"] > 0.5}
+ if self.sport == "tabletennis":
+ heard = [{"event": ev, "t": p[f"heard_{k}_t"]} for k, ev in
+ (("opp_bounce", "bounce on the opponent's half"), ("own_bounce", "bounce on your half"),
+ ("net", "net"), ("paddle", "paddle"), ("robot", "robot"), ("floor", "floor"))
+ if not math.isnan(p[f"heard_{k}_t"])]
+ st.update(point=int(p["point"]), ball="serve" if p["ball_is_serve"] > 0.5 else "opponent's return",
+ t_since_played=p["t_since_played"], ball_in_play=p["ball_in_play"] > 0.5, heard=heard,
+ ball_state="coming to you" if p["ball_coming"] > 0.5 else
+ "going to the opponent" if p["ball_going"] > 0.5 else "dead")
+ elif self.sport == "badminton":
+ phase = {0: "waiting", 1: "open", 2: "tossed", 3: "done"}.get(int(p["serve_phase"]) if not
+ math.isnan(p["serve_phase"]) else -1)
+ sv = {"phase": phase, "court": "right" if p["serve_court_right"] > 0.5 else "left",
+ "opens_in_s": num(p["serve_opens_in_s"]), "deadline_in_s": num(p["serve_deadline_in_s"])}
+ if not math.isnan(p["serve_tossed_at_step"]):
+ sv["tossed_at_step"] = int(p["serve_tossed_at_step"])
+ notes = "; ".join(n for n, k in (("head speed limited", "stroke_head_speed_limited"),
+ ("pose not delivered", "stroke_pose_not_delivered")) if p[k] > 0.5)
+ st.update(point=int(p["point"]), score={"you": int(p["score_you"]), "opponent": int(p["score_opponent"])},
+ you_serve=p["you_serve"] > 0.5, serve=sv, robot_base_xy=[p["base_x"], p["base_y"]],
+ t_since_played=num(p["t_since_played"]),
+ ball_state="coming to you" if p["ball_coming"] > 0.5 else
+ "going to the opponent" if p["ball_going"] > 0.5 else
+ "tossed: yours to hit (your serve)" if p["ball_tossed"] > 0.5 else
+ "not yet served" if p["ball_not_served"] > 0.5 else "dead")
+ if p["stroke_active"] > 0.5:
+ st["command"] = {"contact_in_s": p["stroke_contact_in_s"], "stroke": notes}
+ if not math.isnan(p["stroke_pending_effect_step"]):
+ st["pending_commands"] = [{"takes_effect_at_step": int(p["stroke_pending_effect_step"])}]
+ else:
+ st.update(rally=int(p["rally"]), t_play=p["t_play"],
+ own={"mallet_xyz": [p["mallet_x"], p["mallet_y"], p["mallet_z"]]})
+ return st
+
+ def observe(self):
+ """Air hockey: watch 0.05 s (the players' cadence) and take the last image. Table tennis, badminton: the
+ current images at once (the clock is started by a short watch first), kept in a history from which the view
+ takes four frames about SPACING control steps apart, newest last, as RoboOlympics' observation did."""
+ if self.sport == "airhockey":
+ res = self.r.get_obs(cameras=self.cams, seconds=0.05, video="none")
+ return res, self.rows(res), {c: res.last[c][None] for c in self.cams}
+ res = self.r.get_obs(cameras=self.cams, seconds=0 if self.running else 0.05, video="frames")
+ self.running = True
+ rows = self.rows(res)
+ k = int(rows[-1]["match_step"])
+ if not self.hist or self.hist[-1][0] != k:
+ self.hist.append((k, rows[-1], {c: res.frames[c][-1] for c in self.cams}))
+ self.hist = self.hist[-40:]
+ sel, last = [], None
+ for k, row, fr in reversed(self.hist):
+ if last is None or last - k >= self.spacing:
+ sel.append((k, row, fr))
+ last = k
+ if len(sel) == 4:
+ break
+ sel.reverse()
+ return res, [r for _, r, _ in sel], {c: np.stack([fr[c] for _, _, fr in sel]) for c in self.cams}
+
+ def view(self, res, rows, frames, shift: int = 0) -> tuple[dict, dict, dict]:
+ now = rows[-1]
+ st = self.state(now, shift)
+ n = min(len(rows), min(len(f) for f in frames.values()))
+ rows, frames = rows[-n:], {c: f[-n:] for c, f in frames.items()}
+ self.n_obs += 1
+ ob = {"view_steps": [int(p["match_step"]) for p in rows],
+ "view_sim_times": [round(p["match_step"] * self.dt, 4) for p in rows]}
+ if not self.exact:
+ ob.update(obs_id=self.n_obs, obs_age_wall_s=0.0, render_wall_s=0.0)
+ if self.sport == "airhockey":
+ img = frames[self.cams[0]][-1]
+ ob["image_png_b64"], _ = png_b64([[img]])
+ ob["tiles"] = [{"camera": self.cams[0], "x": 0, "y": 0, "width": img.shape[1], "height": img.shape[0]}]
+ else:
+ ob["image_png_b64"], _ = png_b64([[f for f in frames[c]] for c in self.cams])
+ return st, ob, now
+
+ # ------------------------------------------------------------------ one action
+ def send(self, body: dict, at=None) -> None:
+ t = body.get("type")
+ if t == "act":
+ row = [body["t"], *body["pos"], *body["normal"], *body["vel"]]
+ self.r.submit("stroke", [row], at=at)
+ elif t == "toss":
+ self.r.submit("toss", [[*body["pos"], float(body.get("height", 0.0))]], at=at)
+ elif t == "target":
+ self.r.submit("mallet", [[body["x"], body["y"]]], at=at)
+ elif t == "none":
+ self.r.submit("stop" if self.sport == "airhockey" else "rest", [[0.0]], at=at)
+
+ def run(self) -> dict:
+ t_last = 0.0
+ while True:
+ time.sleep(max(0.0, t_last + self.every * self.period - time.monotonic())) # one view per `every` steps
+ t_last = time.monotonic()
+ try:
+ res, rows, frames = self.observe()
+ except EpisodeOver:
+ break
+ t_reply = time.monotonic()
+ if res.meta.get("done"):
+ break
+ at = shift = None
+ if self.exact: # the step the command will take effect at, and the view as of then
+ at = math.ceil(res.meta["control_steps"] + 0.5) + LEAD_STEPS
+ at = max(at, math.ceil(res.meta["control_steps"] + (time.monotonic() - t_reply) / self.period)
+ + LEAD_STEPS)
+ shift = at - int(res.meta["control_steps"])
+ st, ob, now = self.view(res, rows, frames, shift or 0)
+ if st["world"] == "frozen":
+ key = int(now["match_step"]) # the match stands still in a break: one key per break
+ if key != self.reviewed_break:
+ self.reviewed_break = key
+ f = getattr(self.player, "review", None)
+ why, plan = f(now) if f else ("played as planned", "same plan")
+ try:
+ self.r.submit("ready", [[1.0]], note=f"WHY: {why} PLAN: {plan}"[:200])
+ except EpisodeOver:
+ break
+ continue
+ if self.sport == "badminton" and res.meta["control_steps"] <= self.pending_until:
+ st["pending_commands"] = [{"takes_effect_at_step": int(now["match_step"]) + self.pending_until
+ - int(res.meta["control_steps"]) + 1}]
+ body = self.player.act({"state": st, "observation": ob})
+ if body:
+ if at is not None:
+ self.pending_until = at + self.lead
+ try:
+ self.send(body, at)
+ except EpisodeOver:
+ break
+ return self.r.status()
+
+
+if __name__ == "__main__":
+ t0 = time.time()
+ out = Bridge().run()
+ print({"status": out, "wall_s": round(time.time() - t0, 1)})
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/solution/solve.sh b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/solution/solve.sh
new file mode 100755
index 0000000000..a1680309dd
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/solution/solve.sh
@@ -0,0 +1,5 @@
+#!/bin/bash
+# Oracle: the sport's RoboOlympics reference player (camera images, proprio and /spec only) through the agent's client.
+set -e
+mkdir -p /app/output
+cd /solution && python3 oracle_play.py 2>&1 | tee /app/output/oracle.log
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/task.toml b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/task.toml
new file mode 100644
index 0000000000..6f4a877442
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/task.toml
@@ -0,0 +1,74 @@
+# RoboOlympics Table tennis against the scripted opponent, standard-realtime mode (docs/PROTOCOL.md §4b, docs/benchmarks/roboolympics.md).
+# Generated by scripts/roboolympics/gen_tasks.py from tasks.toml, sports.toml and templates/ -- edit those, not this.
+schema_version = "1.3"
+artifacts = [
+ { source = "/data/final.json", service = "sim" },
+ { source = "/data/match.json", service = "sim" },
+ { source = "/data/episode.jsonl", service = "sim" },
+ { source = "/data/trajectory.npz", service = "sim" },
+ { source = "/data/trajectory_live.f64", service = "sim" },
+ { source = "/data/commands.jsonl", service = "sim" },
+ { source = "/data/replay.mp4", service = "sim" },
+ { source = "/data/replay.last.png", service = "sim" },
+ { source = "/data/ticks.f64", service = "sim" },
+ { source = "/data/calls.jsonl", service = "sim" },
+ { source = "/data/submitted.f64", service = "sim" },
+ { source = "/data/startups.jsonl", service = "sim" },
+ "/app/output/",
+]
+
+[task]
+name = "robot-coding-bench/roboolympics-tabletennis-match-i00-standard-realtime"
+description = "STANDARD-REALTIME MODE (robot as a service on a clock that does not stop, eai-standard/2.3): RoboOlympics table tennis, one match against a scripted opponent (level 1, frozen seed 101). The world runs at 1/10 of real speed (S = 10, the benchmark's official slowdown) and never waits: the agent sees only camera images and its own robot through the client, and drives the robot with the sport's commands (`stroke`, `rest`, `ready`) from a program of its own. Between points a break of 12 s of game time (120 s of wall time) in which the clock runs on and nothing plays; no reset, no privileged state. The sim service records every command at the step it took effect, replays the match in a fresh process and grades it: success = a finished match that the agent won."
+authors = [{ name = "RoboOlympics (CHIGUI0)" }]
+keywords = ["robotics", "roboolympics", "sports", "tabletennis", "mujoco", "standard-realtime-mode", "vision", "real-time"]
+
+[metadata]
+author_name = "RoboOlympics"
+task_type = "trajectory"
+simulator = "mujoco"
+robot = "franka-panda"
+family = "tabletennis_match"
+mode = "standard-realtime"
+protocol = "eai-standard/2.3"
+instance_seed = 101
+opponent_level = 1
+slowdown = 10
+revision = "wallclock-6+duel-wallclock-4+core-0.2"
+play = "program"
+action_level = "high"
+source_task = "roboolympics/tabletennis-match-wallclock-program-standard"
+expert_time_estimate_hours = 0.5
+oracle = "full"
+oracle_evidence = "solution/: the sport's RoboOlympics reference player (camera images, proprio and /spec only) through the agent's client; it wins this instance (PR #106)"
+
+[verifier]
+timeout_sec = 900.0
+environment_mode = "separate"
+network_mode = "no-network"
+
+# The agent's time is up: stop whatever it left running in its container (a program would keep playing).
+[[verifier.collect]]
+service = "main"
+command = "kill -9 -1 2>/dev/null; exit 0"
+timeout_sec = 30
+
+# Then the match ends: SIGUSR1 to the service (re-sent every 30 s, in case it was restarting), which replays and grades it.
+[[verifier.collect]]
+service = "sim"
+command = "for i in $(seq 1 90); do [ -f /data/server.pid ] && break; sleep 2; done; for i in $(seq 1 400); do grep -q '\"finalized\": true' /data/final.json 2>/dev/null && break; [ $((i % 15)) -eq 1 ] && kill -USR1 $(cat /data/server.pid) 2>/dev/null; sleep 2; done; cat /data/final.json"
+timeout_sec = 900
+
+[agent]
+timeout_sec = 7200
+# The agent reaches the model APIs and the sim (localhost:8000, Harbor's egress control) and nothing else.
+network_mode = "allowlist"
+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com"]
+
+[environment]
+build_timeout_sec = 1200.0
+cpus = 2
+memory_mb = 4096
+
+[verifier.environment]
+build_timeout_sec = 600.0
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/tests/Dockerfile b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/tests/Dockerfile
new file mode 100644
index 0000000000..0ecd542d19
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/tests/Dockerfile
@@ -0,0 +1,4 @@
+# Separate verifier sandbox: grades the sim service's own artifacts; needs nothing but Python.
+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f
+COPY test.sh grade.py /tests/
+RUN chmod +x /tests/test.sh
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/tests/grade.py b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/tests/grade.py
new file mode 100644
index 0000000000..32f4465282
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/tests/grade.py
@@ -0,0 +1,93 @@
+"""Standard-realtime verifier (eai-standard/2.3) for RoboOlympics: grades what the sim service -- which the agent could
+not touch -- wrote.
+
+/data/final.json holds the live match's outcome and the verdict of a fresh-process replay of its record:
+success = live_success (the match finished and the agent won it) AND replay_success (the replay's match too) AND
+deterministic (the replay ends in the live run's state). /data/match.json (the replay's summary: the score, the breaks,
+the commands) only adds information to reward.json; it never decides the verdict.
+Writes /logs/verifier/reward.txt (1/0) and a numeric-only reward.json, and copies the evidence (replay video, last
+frame, the replay's summary, event log) next to them for humans.
+infra_error = 1: no verdict on the agent (the service crashed past its restarts, failed to resume, ended on a simulator
+error, never finished, or failed to finalize; PROTOCOL §4b).
+"""
+import json
+import math
+import os
+import shutil
+import traceback
+
+DATA = os.environ.get("RCB_DATA", "/data")
+LOG = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")
+os.makedirs(LOG, exist_ok=True)
+
+
+def write(ok: bool, out: dict) -> None:
+ with open(os.path.join(LOG, "reward.txt"), "w") as f:
+ f.write("1\n" if ok else "0\n")
+ with open(os.path.join(LOG, "reward.json"), "w") as f:
+ json.dump(out, f)
+ print(json.dumps(out))
+
+
+def num(x, default=0.0) -> float:
+ try:
+ x = float(x)
+ except (TypeError, ValueError):
+ return default
+ return x if math.isfinite(x) else default
+
+
+def match_fields() -> dict:
+ """Information from the replay's summary (numbers only); {} if there is none."""
+ try:
+ with open(os.path.join(DATA, "match.json")) as f:
+ m = json.load(f)
+ except (OSError, ValueError):
+ return {}
+ return {"match_finished": int(bool(m.get("finished"))), "match_won": int(bool(m.get("won"))),
+ "points_for": num(m.get("points_for")), "points_against": num(m.get("points_against")),
+ "match_steps": int(num(m.get("match_steps"))), "breaks": len(m.get("breaks") or []),
+ "breaks_ended_by_ready": sum(1 for b in m.get("breaks") or [] if b.get("by") == "ready"),
+ "commands_applied": int(num(m.get("commands_applied"))),
+ "commands_refused": int(num(m.get("commands_refused")))}
+
+
+def main() -> None:
+ path = os.path.join(DATA, "final.json")
+ if not os.path.exists(path):
+ write(False, {"success": 0, "missing_log": 1, "infra_error": 1, "grader_error": 0})
+ return
+ try:
+ with open(path) as f:
+ d = json.load(f)
+ live, replay, det = (bool(d.get(k)) for k in ("live_success", "replay_success", "deterministic"))
+ failed_finalize = bool(d.get("finalize_error"))
+ unfinished = not d.get("finalized")
+ sim_error = d.get("reason") == "error"
+ infra = bool(d.get("infra_error")) or failed_finalize or unfinished or sim_error
+ ok = live and replay and det and not infra
+ out = {"success": int(ok), "live_success": int(live), "replay_success": int(replay), "deterministic": int(det),
+ "finalized": int(not unfinished), "missing_log": 0, "infra_error": int(infra),
+ "sim_error": int(sim_error), "grader_error": int(failed_finalize),
+ "timeout": int(d.get("reason") == "timeout"),
+ "n_actions": int(num(d.get("n_actions"))), "control_steps": int(num(d.get("control_steps_total"))),
+ "calls": int(num(d.get("calls"))), "rows": int(num(d.get("rows"))),
+ "reset_budget": int(num(d.get("reset_budget"))), "slowdown": num(d.get("slowdown")),
+ "max_lag_s": num(d.get("max_lag_s")), "stalls": int(num(d.get("stalls"))),
+ "late_steps": int(num(d.get("late_steps"))), "sim_startups": int(num(d.get("sim_startups"))),
+ "elapsed_s": num(d.get("elapsed_s")), "video_rendered": int(bool(d.get("video"))), **match_fields()}
+ except Exception: # noqa: BLE001 -- an unreadable final.json is the grader's failure, not the agent's
+ traceback.print_exc()
+ write(False, {"success": 0, "missing_log": 0, "infra_error": 1, "grader_error": 1})
+ return
+ for name in ("replay.mp4", "replay.last.png", "match.json", "episode.jsonl"):
+ try:
+ if os.path.exists(os.path.join(DATA, name)):
+ shutil.copy(os.path.join(DATA, name), os.path.join(LOG, name))
+ except OSError:
+ traceback.print_exc()
+ write(ok, out)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/roboolympics-tabletennis-match-i00-standard-realtime/tests/test.sh b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/tests/test.sh
new file mode 100755
index 0000000000..75622ada21
--- /dev/null
+++ b/tasks/roboolympics-tabletennis-match-i00-standard-realtime/tests/test.sh
@@ -0,0 +1,5 @@
+#!/bin/bash
+# Verifier (separate sandbox): the sim sidecar's artifacts were uploaded to /data by Harbor.
+mkdir -p /logs/verifier
+rm -rf /logs/verifier/*
+python /tests/grade.py 2> /logs/verifier/grade.log