diff --git a/leaf/final/episode_000054.npz b/leaf/final/episode_000054.npz new file mode 100644 index 0000000000000000000000000000000000000000..37e3a58582e55c0a57a13bdbcd00dfe61039e479 --- /dev/null +++ b/leaf/final/episode_000054.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0573860058481d2b02a179859500112e233d437729f5972cb1fc2392cf06235b +size 4046 diff --git a/leaf/final/episode_000176.npz b/leaf/final/episode_000176.npz new file mode 100644 index 0000000000000000000000000000000000000000..3f64fc1bdfa6e75e994a70fbef885482123ee43f --- /dev/null +++ b/leaf/final/episode_000176.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d4a3be68092dfcf88c198082eae7620da959339dd151cbfe77f3cfd39dfa8600 +size 4270 diff --git a/leaf/final/episode_000423_wrist_image.png b/leaf/final/episode_000423_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..ee8c92a40da37ac01fa4781930399cdde08eb1f4 --- /dev/null +++ b/leaf/final/episode_000423_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:797d7336f1bed859f34413898171a551922605a425c69eae4acaf08e3128de4a +size 43772 diff --git a/leaf/final/episode_000520_image.png b/leaf/final/episode_000520_image.png new file mode 100644 index 0000000000000000000000000000000000000000..85f5f2e770448fabdb535620197394e7ab40a7f1 --- /dev/null +++ b/leaf/final/episode_000520_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d780acf0a5dfdff9cf15d76864ce1d4c9ce2f17db16b55a8cea85c7275fd99ea +size 54734 diff --git a/leaf/final/episode_000857.npz b/leaf/final/episode_000857.npz new file mode 100644 index 0000000000000000000000000000000000000000..0ec607e89d91eda06f853c9b531c62d530553b31 --- /dev/null +++ b/leaf/final/episode_000857.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:37902f5ca1b0d92666de76246b4c4649d0db05054c3f784eab98b88e871dfea3 +size 4150 diff --git a/leaf/final/episode_000858_image.png b/leaf/final/episode_000858_image.png new file mode 100644 index 0000000000000000000000000000000000000000..4726fc4ee823b357c9ff550a35f298e32996e95d --- /dev/null +++ b/leaf/final/episode_000858_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9d6ad2223c3d116cba395ecf8c01553e9243c839d916f4752b3ab4240e98f422 +size 59184 diff --git a/leaf/final/episode_000871.npz b/leaf/final/episode_000871.npz new file mode 100644 index 0000000000000000000000000000000000000000..fe26435c2e497e00a3cdaf47416d48aea803f72b --- /dev/null +++ b/leaf/final/episode_000871.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69148e326da7ff3eef2008907b232214370452b955db3dc7f54222c90114064a +size 4046 diff --git a/leaf/final/episode_000908_image.png b/leaf/final/episode_000908_image.png new file mode 100644 index 0000000000000000000000000000000000000000..b8d17672d2fffc9eaaeb30bb584727019d236f05 --- /dev/null +++ b/leaf/final/episode_000908_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e89f08e0d196bf85b0a969a4a7477d2f430bc425f34d4ad45a473cde0087d016 +size 54185 diff --git a/leaf/final/episode_001137.npz b/leaf/final/episode_001137.npz new file mode 100644 index 0000000000000000000000000000000000000000..8b36a18ae4fc31556461c6aa12cb2b8922f6d212 --- /dev/null +++ b/leaf/final/episode_001137.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b5da0462afc2aab865079b46566a1b60b16ab57744626ddb1a32796a455ec1e9 +size 3630 diff --git a/leaf/final/episode_001149.npz b/leaf/final/episode_001149.npz new file mode 100644 index 0000000000000000000000000000000000000000..5d2d785c028019ca443fbb19e5554589a0d921a8 --- /dev/null +++ b/leaf/final/episode_001149.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:edf03c232212ce31107b87835b7ec1570a3d5fcd17e1fb82b334a25053d484a3 +size 4270 diff --git a/leaf/final/episode_001152_wrist_image.png b/leaf/final/episode_001152_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..1adb499c26c364dfb61b23fad04fa095baace8e2 --- /dev/null +++ b/leaf/final/episode_001152_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bf2d522ea2b8409e6dae1cd370edcfd8acb70bb5f29d1071cab640a003d0081a +size 17958 diff --git a/leaf/final/episode_001598_wrist_image.png b/leaf/final/episode_001598_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..be758a8509ae2bc0070da20ef3d4f2eb1395036d --- /dev/null +++ b/leaf/final/episode_001598_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9a627355f0f09622dcec07daf54cc09aa6f6ea1b4c1590ac0a2178012f350309 +size 33030 diff --git a/leaf/final/episode_001730.npz b/leaf/final/episode_001730.npz new file mode 100644 index 0000000000000000000000000000000000000000..0e28bce3c5c133925a2e9ddb72aa5281200c7870 --- /dev/null +++ b/leaf/final/episode_001730.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7c307583e1ed9f18051fc1bcf0b994af4ee650cff698db810045deb29b8c6c86 +size 4150 diff --git a/leaf/final/episode_002212.npz b/leaf/final/episode_002212.npz new file mode 100644 index 0000000000000000000000000000000000000000..6d68ebd3d7804962e9705662f60217fe30980033 --- /dev/null +++ b/leaf/final/episode_002212.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9142aba2ef5e9019416a8ed5e15d6003a2221e5bf0126899ff10518543a1f174 +size 3886 diff --git a/leaf/final/episode_002423_wrist_image.png b/leaf/final/episode_002423_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..2ecfd1882c0ba2222e23ec984f2ff52638ac06d4 --- /dev/null +++ b/leaf/final/episode_002423_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:34859af6ed865f8b2243e6fe030f8fbed66b2061cf57dc64c135b88dd025d673 +size 40978 diff --git a/leaf/final/episode_002836.npz b/leaf/final/episode_002836.npz new file mode 100644 index 0000000000000000000000000000000000000000..37c01606bb0e29d35596a8c0a6ee996aa07d24dc --- /dev/null +++ b/leaf/final/episode_002836.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a549f9dc59fcda7b5cd0706a72b27fb0847ef72e4cc60ec0bbae559723afffe0 +size 4150 diff --git a/leaf/final/episode_002837.npz b/leaf/final/episode_002837.npz new file mode 100644 index 0000000000000000000000000000000000000000..1973199e164add204873b136671ec8454ab08a9d --- /dev/null +++ b/leaf/final/episode_002837.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:04a18f077869210bb13715fad0f90767624681bbbbe283d798a0b4377e0b80f4 +size 4150 diff --git a/leaf/final/episode_003181.npz b/leaf/final/episode_003181.npz new file mode 100644 index 0000000000000000000000000000000000000000..5bef2c8c7346e090c28ab40ac5d46f27ca7cddcc --- /dev/null +++ b/leaf/final/episode_003181.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d8fdd20ee4c36cac76e0ec24f136fc530c08d03c3b2a358852396edea2286731 +size 3734 diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/README.md b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/README.md new file mode 100644 index 0000000000000000000000000000000000000000..718daf643df342adc71df05584ec3c42e8fdfb36 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/README.md @@ -0,0 +1,297 @@ +# LFF-Bench agent harness(`lffbench/agent/`) + +把 VLM 智能体(默认 GPT-6 Astra,经 OpenAI Responses API)接到 LFF-Bench 任务上:工具接口、观测与历史打包、 +记忆模式、反馈粒度、协议控制(cross / within)、日志与指标。对应设计文档 `docs/02-benchmark设计.md` §4、§5。 + +> 本文档里"实测"指在本机跑出来的结果;"假设 / 估计"是没验证过的,单独标出。 + +## 1. 文件 + +| 文件 | 内容 | +|---|---| +| `tools.py` | 工具 JSON schema(`tool_specs`)和执行器 `ToolExecutor`(底层全部调 `Skills`) | +| `camera.py` | 相机内外参、深度反投影 `pixel_to_world`、`world_to_pixel`、图像方向说明(robosuite `camera_utils`) | +| `context.py` | 后端无关的对话结构、尝试记录 `AttemptRecord`、记忆选择 `select_history`、全部提示词文本 `PromptBuilder`、关键帧选择、旧图裁剪 | +| `harness.py` | 协议控制器 `AgentHarness` + `HarnessConfig` | +| `backends/openai_responses.py` | `OpenAIResponsesBackend`(GPT-6 Astra) | +| `backends/scripted.py` | `ScriptedBackend`:不调模型,把任务自带的 scripted 策略经工具接口跑一遍 | +| `backends/chat_completions.py` | `ChatCompletionsBackend`:OpenAI 兼容 Chat Completions(本地 Qwen3-VL 服务、vLLM 等) | +| `backends/anthropic_messages.py` | `AnthropicMessagesBackend`:Anthropic Messages API(自适应思考 + effort、思考块原样回放、自动缓存,2026-10-11) | +| `backends/gemini.py` | `GeminiBackend`:Gemini API(google-genai;thought_signature 原样回放,2026-10-11) | +| `../../scripts/api_player.py` / `api_batch.py` / `mcp_robot_server.py` | LA 接口的统一驱动、批处理调度、给原生 harness 的 MCP server(见 docs/12-统一harness.md) | +| `runlog.py` / `replay.py` | 运行目录写入;从运行目录重建尝试记录(给 mismatched 当 donor) | +| `metrics.py` / `cost.py` | succ@k、ΔICL、重复动作率;token 计价 | +| `../../scripts/run_agent.py` | 命令行入口 | +| `../../scripts/agent_compare.py` | 两个运行目录配对算 ΔICL(bootstrap 区间) | +| `../../scripts/agent_cost.py` | 从运行目录(真实或 dry run)估算 GPT-6 成本 / 延迟 | +| `../../tests/test_agent_*.py` | 单元测试 + 仿真端到端测试 | + +## 2. 快速开始 + +```bash +cd && source run_env.sh && export OMP_NUM_THREADS=1 +# 管线自检(不调模型;同时记录"如果换成 GPT-6,每次请求多大") +python scripts/run_agent.py --task l5_slide_to_target --backend scripted --memory full --feedback F2 --n 3 --k 5 --dry-run-payload +# GPT-6(需要 key;见 §6) +export OPENAI_API_KEY=... # 必需 +export OPENAI_BASE_URL=... # 可选:走网关 / 代理时 +python scripts/run_agent.py --task l5_slide_to_target --backend openai --effort medium --memory full --feedback F2 --n 20 --k 5 --seed0 5000 +python scripts/run_agent.py --task l5_slide_to_target --backend openai --effort medium --memory none --feedback F2 --n 20 --k 5 --seed0 5000 +python scripts/agent_compare.py --with runs/agent/l5_slide_to_target/ --iid runs/agent/l5_slide_to_target/ +# 测试 +python -m pytest -q tests/test_agent_payload.py tests/test_agent_protocol.py # 无仿真,约 1–2 分钟(CPFS 上 import 慢) +python -m pytest -q tests/test_agent_sim.py # 仿真,含 n=3 端到端 +``` + +常用开关:`--instruction direct|indirect`、`--privileged-locate`(消融:给 `locate`)、`--image-res 512`、 +`--keyframes 4`、`--keyframe-res`、`--max-steps 30`(每次尝试的工具调用上限)、`--no-auto-obs`(只在 `get_observation` 时给图)、 +`--grasp-report bool|name|none`、`--early-stop auto|yes|no`、`--donor-run DIR`(mismatched 的 donor)、`--seeds 5000,5001`。 +种子约定(我定的):1000–1999 开发(validate.py 也用 1000+),5000+ 留作正式测试。 + +## 3. 工具接口 + +坐标一律**世界系、米**(按本次任务要求;设计文档 §4 草稿写的是"机器人基座系",两者只差一个平移,这里统一用世界系,与 Skills 和各任务代码一致):桌面 z = 0.90,机器人基座在 x = −0.66, y = 0,+x 远离机器人,+y 机器人左侧,+z 向上。 +位置指夹爪抓取点(两指尖中点,`gripper0_grip_site`)。夹爪始终竖直向下;`yaw` 单位是**度**(LLM 处理度比弧度少出错), +yaw 0 时两指沿世界 y 轴开合(实测:手指 body 在 y = ±0.02),yaw 90 沿 x 轴。yaw 按 180° 取模:`Skills.move_to`(共享代码, +2026-10-06 协调者改)会取与当前 yaw 最近、且 |yaw| ≤ 90°+0.4 rad(约 113°)的等价角,避免手腕绕 180° 把手臂卷进关节限位; +`move_to` 报告里的 `yaw_used_deg` 是实际用的角度。 +肘关节(`robot0_joint4`)上限从 Panda 原厂的 −0.07 rad 收紧到 −0.55(`envs.ELBOW_Q4_MAX`,2026-10-19):原来快速移动越过手臂伸到最远的姿态(约 −0.47)后,肘关节会弯到反方向,被上限挡住,之后的移动都停在离目标 4–17 cm 处。收紧后可达范围不变。 +方向词:harness 生成的文字里一律以机器人为参照,并在 system prompt 里定义——forward = +x、backward = −x、left = +y(机器人左手)、 +right = −y、up = +z,"不是图像里的左右";同时说明 agentview 图里机器人的左边出现在图像右侧。任务自己的 F2 文本由任务作者统一。 + +| 工具 | 参数 | 底层 | 说明 | +|---|---|---|---| +| `move_to` | x, y, z, yaw, speed∣null | `Skills.move_to` | speed 为 null 时按控制器最快(约 0.6 m/s);yaw 按 180° 取模;超出工作空间的目标被裁剪并在报告里注明 | +| `open_gripper` / `close_gripper` | – | `Skills.set_gripper` | | +| `push` | x, y, dir_x, dir_y, distance, speed, z∣null, runup∣null | `Skills.push` | 语义与 `Skills.push` 完全一致:闭爪,到 (x,y) 后方 runup(默认 0.06)处、高度 z(默认 0.92),沿方向扫到 (x,y) 前方 distance 处,再抬 12 cm;朝向由 `Skills.push` 自动定 | +| `get_observation` | – | 渲染 | 返回 agentview + 腕部图像和本体状态 | +| `pixel_to_world` | camera(agentview∣wrist), u, v | 深度反投影 | u=列(从左数)、v=行(从上数),坐标就是模型看到的那张图(默认 512×512);返回世界点、离桌面高度、深度 | +| `done` | reason | – | 结束本次尝试(within 协议:结束一个分段,任务被检查) | +| `locate`(仅 `--privileged-locate`) | object_name(枚举) | 特权 | 物体原点的真实世界坐标 + 碰撞体 AABB;只用于"去掉感知难度"的消融 | + +所有工具 schema 都是 OpenAI strict 模式(所有字段 required、可选字段可为 null、禁止额外字段)。 + +**动作工具的执行报告**(JSON 文本,作为 function_call_output 返回): +```json +{"ok": true, "tool": "move_to", "reached": true, "yaw_used_deg": 0.0, "eef_pos": [-0.418, 0.019, 0.920], "eef_yaw_deg": 0.5, + "gripper": "closed", "gripper_width_m": 0.001, "holding_object": false, "touched_object": false, "sim_time_s": 13.7} +``` +- `reached`:控制器是否到达(2 cm 内,`Skills` 的判据);`push` 给 `sweep_reached`。 +- `holding_object` / `touched_object`:默认只给布尔(`--grasp-report bool`)——真实机器人能感知"夹住了东西 / 碰到了东西", + 但不知道是哪个物体;物体名会泄露识别类任务的答案。`--grasp-report name` 时给物体名(调试 / 消融)。 + 接触在**每个 MuJoCo 子步**检查(包装 `env.sim.step`,一个控制步 = 25 子步):实测快推时手指与方块的接触不到一个控制步,只在控制步边界查会漏掉(l5 上推了 4.4 cm 却一次接触都没记到)。不碰 `Skills.recorder`,任务自己的注入钩子不受影响。 +- 任务若定义 `drain_events()`(L6 有),其返回的事件文本会作为 `events` 加进当次报告(L6 作者的约定)。 +- 参数错误、未知工具、JSON 解析失败都返回 `{"ok": false, "error": ...}`,占一步预算,不中断尝试。 + +**隐藏 bias(L1)怎么处理**:所有命令位置都经 `Skills`,bias 照常加上。本体状态按"机器人自己以为的位置"报告: +`eef_pos = 真实末端 − bias`。也就是说机器人认为自己准确到了指令点,只有相机能看出偏差——这就是标定误差的本义; +如果报告真实末端,agent 对比指令和报告就能直接读出 bias,L1 就失效了。`pixel_to_world` 和 `locate` 给真实世界坐标。 +(测试 `test_tool_reports_and_hidden_bias` 实测:bias (3, −2, 0) cm 时报告与指令差 < 1 cm,真实末端 = 指令 + bias。) +L1 任务作者在 `l1_bias.py` 的 `TrackedSkills.reported_eef_pos()` 里独立采用了同一约定,两边一致。 + +**`pixel_to_world` 精度(实测,l5 场景方块顶面中心,投影→反投影)**:agentview 512px 误差约 1.5 mm,256px 约 3.4 mm; +wrist 均 < 0.1 mm。图像方向(由外参算出并写进 system prompt):agentview 图右 = +y、图下 = +x(机器人在图上方); +wrist 在 yaw 0 时图右 = −y、图下 = −x。 + +## 4. 观测、消息格式与历史打包 + +请求由三部分组成,按缓存友好的顺序排列: +1. **instructions(system)**:机器人 / 坐标 / 相机 / 工具约定、协议(k 次尝试、重置到同一状态)、反馈粒度说明、 + "新尝试开始前先用 1–3 句话评估前几次尝试"(这句话就是"自报失败原因"的来源,记录为 `diagnosis`)。 +2. **历史项(user,非 live,不裁剪)**:`TASK: <指令>` + 前几次尝试的打包(按记忆模式选择)。 +3. **当前尝试(live)**:尝试编号 + 当前 agentview / wrist 图 + 本体状态;之后每一步:模型的 function_call → + function_call_output(执行报告)→ 新观测(两张图 + 本体状态)。 + +每次尝试的打包(≤4 张关键帧 + 动作摘要 + 反馈)。下面是 scripted dry run 第 2 次尝试第 1 次调用的 `input`,原样摘自 +`runs/agent/l5_slide_to_target/20261006-060757_scripted-adaptive_full_F2_e2e/requests/request_007.json`(图像以占位符代替, +`[BREAKPOINT]` 表示该内容块带 `prompt_cache_breakpoint`): +``` +== user(历史项,live=False) +TASK: Push the red cube once, straight away from the robot, so that it slides and comes to rest inside the green target zone. + +=== Your earlier attempts === + +--- Attempt 1 --- +Actions executed: +1. close_gripper() -> eef (-0.208, 0.000, 1.173); width 0.002 m +2. move_to(x=-0.419, y=0.021, z=1.02, yaw=0, speed=null) -> NOT reached; eef (-0.394, 0.023, 1.032) +3. move_to(x=-0.419, y=0.021, z=0.92, yaw=0, speed=null) -> reached; eef (-0.418, 0.019, 0.920) +4. move_to(x=-0.204, y=0.021, z=0.92, yaw=0, speed=0.3) -> reached; eef (-0.202, 0.021, 0.921); touched an object +5. move_to(x=-0.204, y=0.021, z=1, yaw=0, speed=0.3) -> reached; eef (-0.205, 0.020, 0.997) +6. done(reason="scripted adaptive policy finished with params {'speed': 0.3}") +Outcome feedback: Attempt failed. The cube stopped 5.2 cm past the centre of the target zone. +Key images (start of attempt, after step 1 (close_gripper), after step 4 (move_to), end of attempt, after objects settled): +[start of attempt] +[after step 1 (close_gripper)] +[after step 4 (move_to)] +[end of attempt, after objects settled] +=== End of earlier attempts === [BREAKPOINT] +== user(当前尝试,live=True) +This is attempt 2 of at most 5. The scene has been reset. + +Current observation: +agentview camera: +wrist camera: +Proprioception: {"eef_pos": [-0.2085, -0.0, 1.1733], "eef_yaw_deg": 0.0, "gripper": "open", "gripper_width_m": 0.0411, "holding_object": false} [BREAKPOINT] +``` +之后每一步依次追加:模型输出项(reasoning(加密)/ message / function_call)→ `function_call_output`(执行报告 JSON)→ +user 项 `Observation after step N ():` + 两张图 + 本体状态。完整请求(含 instructions 和 tools)见同目录 `requests/*.json`。 +- 关键帧(agentview):尝试开始、最多 2 张中间帧(优先 push / 开合爪 / 碰到物体的步)、结束帧(`task.outcome()` 让物体静止之后渲染)。 +- 反馈:`task.feedback(inst, outcome, level)`。F0 不给反馈行;F1 只有成功 / 失败;F2 加结构化测量(任务的 `detail`)。 +- 历史头不带计数,所以第 j+1 次尝试的历史项以第 j 次的为前缀(只多一块),前缀可被缓存命中(单测 `test_history_prefix_is_append_only`)。 +- live 图像超过 `max_live_images`(默认 16)时,把最旧的裁到预算的一半(滞回,减少前缀变化);历史关键帧从不裁剪。 +- 一张图就是一个 JPEG(quality 90);发给模型的字节和 `images/` 下存的文件完全相同。 + +**记忆模式**(`--memory`): + +| 模式 | 下一次尝试看到什么 | 用途 | +|---|---|---| +| `none` | 什么都没有;提示词里也不提"多次尝试",每次请求与第 1 次完全相同 | 独立重来,测 pass@k^iid | +| `full` | 之前全部尝试 | 主条件 | +| `last` | 只有最近一次 | 记忆长度消融 | +| `mismatched` | 另一个实例(不同布局和隐变量)的前 j−1 次尝试,措辞与 full 完全相同 | 错配对照:用的是具体信息还是"泛泛练习" | + +mismatched 的 donor:`--donor-run DIR` 复用一个已跑完的 full 运行(按种子循环错位配对,保证 donor ≠ 自己;不用再付一次钱); +不给时自动用同一后端、memory=full 在 `seed + 10000` 上先跑一遍 donor(存到运行目录下 `donors/`)。 + +**早停与 F0**:默认(`--early-stop auto`)F1/F2 在首次成功时结束 run;F0 不早停、跑满 k 次——否则"还有下一次尝试"本身就泄露了"上次失败"。 + +**协议**:`cross` 每次尝试前 `reset_instance`(同布局、同隐变量)。`within` 只在开始重置一次;`done` 结束一个分段: +(若任务定义 `go_home()` 先调用它,L6 有)→ 保持 20 个控制步 → `outcome()`;未成功且未到终止条件(`outcome["terminal"]` 或 +`outcome["overshoot"]`,或任务的 `is_terminal(out)`)就带着反馈从当前状态继续。within 下各记忆模式的语义同上(none = 每段都清空上下文)。 + +## 5. 后端 + +- **`OpenAIResponsesBackend`**(`--backend openai`):`client.responses.create(model="gpt-6-astra", instructions, input, tools, + tool_choice="auto", parallel_tool_calls=False, store=False, include=["reasoning.encrypted_content"], reasoning={"effort": ...})`。 + - 无状态:每次请求重发完整(裁剪后的)上下文;上一轮返回的 reasoning 项(加密内容)原样回放,模型在一次尝试内保留思路。 + - effort 校验:gpt-6-astra 只接受 low / medium / high / xhigh / max(不支持 none)。 + - 缓存:自动把 `prompt_cache_key` 设为 `lffbench::`;默认在"历史项末尾"和"最新输入末尾"打显式 + `prompt_cache_breakpoint`(openai SDK 3.24 的字段,gpt-5.6 以后支持)。网关不认这个字段时用 `--cache-breakpoints none`。 + `--prompt-cache-options '{"ttl":"30m"}'`、`--prompt-cache-retention 24h`、`--service-tier`、`--extra-body` 透传。 + - 用量:记录 input / cached / cache_write / output / reasoning tokens 和每次调用的墙钟延迟。 +- **`ScriptedBackend`**(`--backend scripted --scripted-policy adaptive|naive|oracle|blind`):任务自己的 `execute(inst, params)` + 在工作线程里跑,`task.sk` 换成代理,每个 `Skills` 原语变成一次 schema 合法的工具调用交给 harness 在主线程执行 + (队列交接,同一时刻只有一个线程碰 MuJoCo)。参数来自任务的 `default/adapt/blind/oracle_params`,只看记忆模式允许的历史、 + 只看反馈粒度允许的字段(F2 结构化测量 / F1 成功标志 / F0 无;看不够就退回 blind 规则)。它读实例布局(特权),只用来测管线。 + 支持实现了 `execute` 的 cross 任务;within 任务和只重写了 `run_scripted` 的任务不支持(会报错说明)。 +- **`ChatCompletionsBackend`**(`--backend chat --chat-base-url http://127.0.0.1:8765/v1 --chat-model ...`):OpenAI 兼容 + Chat Completions + function calling,用于本地开源 VLM(见 §8)或任何 vLLM / SGLang 端点。live 图像上限降到 4。 + +## 6. 怎么接 GPT-6(需要用户提供) + +1. `OPENAI_API_KEY`(必需),可选 `OPENAI_BASE_URL`(网关 / 代理)。本机没有 key,代码从未发过真实请求。 +2. 账号对 `gpt-6-astra` 的访问权限和 Tier(Tier 1 限额 500 RPM / 500K TPM;单个 run 串行,每次调用 ≤ 几十 K token,Tier 1 够用)。 +3. Python 包:`setup/install.sh` 建的 venv 里直接装了 `openai==3.24.0`。(原开发机的 libero-cpu venv 没有 `openai`, + 它装在一个 `pip install --target` 目录里,由环境变量 `LFF_OPENAI_SDK_DIR` 指定;后端在 `import openai` 失败时把该目录 + **追加**到 `sys.path` 末尾,venv 里已有的包始终优先。) +4. 第一次真跑建议:`--n 2 --k 3 --effort low --dump-requests 5`,看 `requests/*.json`(图像已省略)和 `events.jsonl` 里的 + `llm_call.usage`,确认网关接受 `prompt_cache_breakpoint` / `include` 等字段后再放大。 +5. 并行:一个进程一个 MuJoCo 环境、串行跑实例;要并行就按 `--seeds` 切分开多个进程(每个进程 `OMP_NUM_THREADS=1`)。 +6. 代理(实测):本机环境变量里有 `HTTPS_PROXY=http://127.0.0.1:1080` 和 `ALL_PROXY=socks5h://127.0.0.1:1080`。openai SDK 3.x + 底层的 httpx2 只要看到 socks 代理变量就要 `socksio`,否则建客户端时直接 ImportError;我已把 `socksio==1.0.0` 装进同一目录, + 现在在这些变量存在时能正常建客户端(实测)。真实请求会走 `HTTPS_PROXY`;能否经这个代理到达 OpenAI / 你的网关没测(没有 key)。 + +## 7. 日志与指标 + +运行目录 `runs/agent//<时间>___[_tag]/`: +- `config.json`:命令行、harness 配置、后端配置、任务信息。 +- `events.jsonl`:`run_start`(实例参数,去掉 `_` 开头的私有键)、`llm_call`(延迟、usage、成本估计、模型文本、reasoning 摘要、 + 工具调用、请求大小;dry run 时加 `dry_run_request`)、`tool_call`(参数、报告、仿真墙钟、仿真步数)、`observation`(图像路径、本体)、 + `attempt_end`(outcome 全字段、给模型看的反馈、F2 反馈、结束原因、done 理由、自我诊断、显示了哪些历史、关键帧路径、动作摘要、 + 该尝试的 LLM 延迟和仿真时间)、`run_end`(run 级汇总)、`llm_error`。 +- `images/seed/a_s__.jpg`:模型看到的每一张图。 +- `summary.json`:每个 run 的 `first_success`、`success_by_attempt`、残差(outcome 里所有 `*_err`)、token、成本、延迟;以及汇总: + `succ_at`(j = 1..k,按 run 计)+ Wilson 95% 区间、`attempt1_success`、首次成功尝试数均值 / 中位数、 + `pass_at_k_iid_analytic = 1 − (1 − p1)^k`、`repeated_action_rate`(失败后下一次动作序列与上次相同(1 cm 取整)的比例, + "同错复犯"的通用近似)、每 run 调用数 / 延迟 / token / 成本、缓存命中率。 +- ΔICL:正式算法是同种子配对的 `succ@k(full) − succ@k(none)`(`scripts/agent_compare.py`,配对 bootstrap 区间、不一致对计数); + `delta_icl_vs_analytic_iid` 只是用本组 attempt-1 成功率算的便宜参照。 + +## 8. 成本 / 延迟估算方法 + +- 真实运行:成本 = Σ调用 [(input − cached − cache_write)·$10 + cache_write·$12.5 + cached·$1 + output·$50] / 1e6 + (gpt-6-astra 价格,>272K 输入时输入 ×2、输出 ×1.5;见 `cost.py`);延迟直接用记录的每次调用墙钟。`scripts/agent_cost.py <运行目录>`。 +- 跑之前:用 scripted 后端加 `--dry-run-payload` 跑同一配置,记录每次调用如果发给 GPT-6 的请求大小,再 + `scripts/agent_cost.py --out-tokens 1500 --latency 20 --calls-scale 2` 外推。假设(未验证):图像按 32px patch + 每 patch 1 token 计(512² ≈ 256 token);文本 4 字符 ≈ 1 token;同一尝试内上一调用的输入全部命中缓存、每次尝试第一调用全不命中(偏保守); + scripted 的调用次数是 LLM 的下限(LLM 还会看图、反投影、检查),用 `--calls-scale` 放大;每次调用输出 token 和延迟按参数给 + (RoboICL 实测 GPT-6 Astra 每次调用 30–50 s,那是 50–90K 输入、high/xhigh 时的数)。 +- 本机 dry run 实测数字见 §10。 + +## 9. 已知限制 + +- **l5_slide_to_target 的绿色目标区在图像里看不见(实测,任务侧问题,未改任务文件)**:`apply_instance` 把 zone 的碰撞关掉了, + 但它是 free joint,`settle` 期间直接穿过桌面掉下去(reset 后 z ≈ 0.81),agentview 和腕部图里都没有绿色区域。 + scripted 测试不受影响(它只看 F2 数字),但 VLM 智能体只能靠 F2 的文字找目标——F0/F1 条件下这个任务对 VLM 不可解。 + 需要任务作者把 zone 固定住(例如不加 free joint、或每步把它放回 / 设 gravcomp / 设为 mocap)。 +- l5 的 scripted 执行里第一个 `move_to`(到推杆起点上方 x≈−0.42, z≈1.02)每次都跑满 250 步(12.5 s 仿真)仍差约 2.5 cm 报 `NOT reached`, + 下一步下降时又到位了;这是 `Skills.move_to` 在靠近基座处的行为,不是 harness 的问题,但 VLM 会在报告里看到 `NOT reached`。 +- 渲染:每步两张 512² 图(OSMesa CPU)约 0.5 s;本机负载高时更慢。仿真时间对比 LLM 延迟可以忽略。 +- 一个 run 内串行调用模型;没有实现 async tool calling / mid-turn steering / WebSocket(Ultrafast 推荐)。 +- 没有实现"每次尝试后单独问一次模型失败原因"(会多一次调用);自报原因来自每次新尝试开头的那 1–3 句(`diagnosis`)。 +- `ScriptedBackend` 不支持 within 协议任务(L2 / L3-within / L5-B / L6 的 scripted 参照写在各自的 `run_scripted` 里, + 不是 `execute(params)`);within 协议逻辑用假任务做了单测。 +- 工具里没有 `wait`;scripted 代理遇到 `Skills.hold` 直接执行并计数(`backend_meta.untooled_hold_steps`)。 +- 图像 token 的计法、GPT-6 每次调用的延迟都是假设,第一次真跑后用 `usage` 和 `latency_s` 校准。 +- 本地开源 VLM 后端:见 §11。 + +**任务作者可选的钩子**(harness 会自动使用,没有就跳过):`agent_instruction(inst, variant)`、`agent_object_names`、 +`on_agent_tool(inst, name, args, report)`(每次工具调用后,可用于注入)、`drain_events()`(事件文本进报告)、 +`go_home()`(每次尝试结束、测 outcome 之前调用)、`is_terminal(out)` 或 `outcome["terminal"]`(within 不可恢复失败)、 +`feedback(..., indirect=bool)`(按指令写法改写反馈)。 + +## 10. 测试与实测结果(2026-10-06,本机实测,8 核负载 30–40) + +单元测试(`source run_env.sh` 后 `python -m pytest -q tests/test_agent_*.py`): +- `test_agent_payload.py` 6 项通过:请求结构、strict 工具、图像 data URL 能解码成 512² JPEG、缓存断点位置、effort 校验、 + 无 key 报错;**真实 openai SDK 3.24 + 进程内 mock HTTP 传输**的两轮往返(URL `…/v1/responses`、`Bearer` 头、body、usage + 解析含 cache_write、reasoning 加密项回放、function_call / function_call_output 的 call_id 配对);chat 后端消息格式。 +- `test_agent_protocol.py` 9 项通过(假任务、无仿真):full / none / last / mismatched、F0 / F1 / F2、F0 不早停、within 不重置、 + 历史前缀只追加、关键帧选择、配对 ΔICL。 +- `test_agent_sim.py` 5 项通过(单独 143 s;协调者改了 `Skills.move_to` 的 yaw 取模之后,三个文件 20 项一起重跑,305 s,全部通过):像素↔世界往返、bias 隐藏、工具报错 / 裁剪 / locate 门控 / 接触检测、 + **ScriptedBackend 在 l5_slide_to_target 上 n=3、k=5 端到端**、mismatched 自动 donor。 + +端到端运行(留在 `runs/agent/l5_slide_to_target/` 下,可以直接看图和 events): + +| 运行 | succ@1..5 | 首次成功(seed 1000/1001/1002) | 每 run 调用数 | 每 run 仿真 + 渲染墙钟 | +|---|---|---|---|---| +| `20261006-060757_scripted-adaptive_full_F2_e2e` | 0.33 / 0.67 / 1 / 1 / 1 | 3 / 2 / 1 | 12 | 15.5 s | +| `20261006-060913_scripted-adaptive_none_F2_e2e` | 0.33 / 0.33 / 0.33 / 0.33 / 0.33 | – / – / 1 | 22 | 16.2 s | + +- 经工具接口跑的 scripted adaptive 与任务自己的参照 rollout(`results/l5_slide_to_target/validate.json`)**逐次一致**: + 8 次尝试的推速完全相同,停止误差 along_err 相同到 0.1 mm(如 seed 1000:+5.22 / −1.14 / −0.49 cm)。说明工具接口足以表达 + 这个任务的参照策略,bias / 物理没有被 harness 改变。 +- memory=none 时 scripted 策略每次都用默认推速,结果完全重复(`repeated_action_rate` = 1.0),正好是"独立重来"的退化情形; + `agent_compare.py` 给出 ΔICL = 1.0 − 0.33 = 0.67(n=3,bootstrap 区间 [0, 1],只是管线演示)。 +- dry run 请求大小(`agent_cost.py`):每次调用约 4.7K 输入 token(估计:文本 /4 + 每张 512² 图 256 token),同一尝试内 + 约 78% 可命中缓存;第 2 次尝试首个请求 6 张图(4 关键帧 + 2 实时),到尝试末尾约 16 张。 + 估计成本(gpt-6-astra 价格,**输出 token 和延迟是假设**):每次调用输出 1500 token、20 s 时,每 run 约 $1.1、API 时间约 4 分钟; + 按 LLM 调用数是 scripted 的 2 倍算,约 $2.1 / run、8 分钟;输出 4000 token、40 s 时约 $5.1 / run、16 分钟。 + 成本主要在输出(reasoning)token,不在图像。一组条件 20 个实例 ≈ $40–100;ΔICL 至少要 full + none 两组。 + +另外用 scripted 后端在 **l1_bias_place**(别人刚写的 L1 任务,cross 协议)上跑了 n=2、k=5 的兼容性检查(运行目录在 scratch,未保留): +两个种子都在第 2 次尝试成功(第 1 次 F2 反馈"夹爪在奶酪中心右侧 3.9 cm、后方 1.4 cm",adaptive 据此补偿 offset), +0 个错误——harness 不需要为 L1 做任何改动;L1 作者的 `TrackedSkills` 记录、bias 都经工具调用照常生效。 + +## 11. 本地开源 VLM 后端(Qwen3-VL-8B-Instruct,PPU) + +能跑(实测)。由子代理在约 1 小时内做通:`scripts/qwen_vl_server.py` + `scripts/qwen_vl_server.sh`(OpenAI 兼容 +`/v1/chat/completions`,支持工具调用 / 多图 / 多轮),用系统 python3.12(torch 2.6 PPU 版)+ 单独目录 +`/mnt/cpfs/workspace/env/qwen3vl-ppu-overlay`(只放 transformers 4.57.6 / tokenizers 0.22.1 / huggingface_hub 0.36.0, +只对服务进程加 PYTHONPATH,不改任何已有环境)。PPU 上 SDPA 自带 GQA 在解码步会报错,服务里改成先展开 K/V 头再算(`--sdpa-native-gqa` 可恢复)。 + +```bash +nohup bash scripts/qwen_vl_server.sh --port 8765 --warmup > logs/qwen_vl_server.log 2>&1 & # 等日志出现 "serving ..." +python scripts/run_agent.py --task l5_slide_to_target --backend chat --chat-base-url http://127.0.0.1:8765/v1 \ + --chat-model Qwen3-VL-8B-Instruct --memory full --feedback F2 --n 2 --k 3 --max-steps 15 --keyframes 3 +kill <服务 PID> # 用完停掉,显存约 18 GB +``` +- 加载:页缓存热时权重 18 s(本次实测);冷读 CPFS 约 6.5 分钟(子代理实测 385 s)。 +- 端到端实测(`runs/agent/l5_slide_to_target/20261006-061100_chat_full_F2_qwen_smoke`,n=2、k=3、每次尝试 15 步上限): + 81 次模型调用、0 次后端错误、0 次格式错误的工具调用;每次调用延迟均值 5.1 s(p50 4.9 s,p95 9.5 s), + 输入均值 6.3K token(最大 10.3K),输出均值 113 token;用到了 move_to / push / close_gripper / get_observation / pixel_to_world / done, + 新尝试开头都写了对上一次的评估(`diagnosis`)。成功 0/2:模型反复 `move_to(0, 0, 0.9)`、没有先定位方块, + 加上 l5 的目标区本来就看不见(§9)。这只说明**管线对真实 VLM 是通的**,不说明 8B 模型的能力;之后我在 system prompt 里加了 + "物体位置不会直接给出,用 pixel_to_world 从图像定位"一句(这次运行之后加的,未再测)。 +- 用途:在花 GPT-6 的钱之前,先用本地模型检查提示词、工具描述、日志和指标。 diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/audit_state.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/audit_state.py new file mode 100644 index 0000000000000000000000000000000000000000..ca750975ae7d008a8d5a7b87dfa1c253f7a75cf4 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/audit_state.py @@ -0,0 +1,79 @@ +"""Host-only, read-only physical evidence for CS/IR review (opt-in). + +Never call outcome(), forward(), step() or a task measurement here: those can +settle physics or consume event cursors. Samples are at control-step boundaries, +not every MuJoCo substep. No sample itself is an error or repair classification. +""" +import json + + +def _json_value(value): + if hasattr(value, "tolist"): + return value.tolist() + raise TypeError(f"Unsupported audit value: {type(value).__name__}") + + +class AuditStateRecorder: + def __init__(self, path): + self.path = path + self.env = None + self.original_step = None + self.wrapped_step = None + self.sequence = 0 + + def write(self, record): + # A separate host-side file, never copied into the agent's sandbox. + with open(self.path, "a", encoding="utf-8") as stream: + stream.write(json.dumps(record, separators=(",", ":"), default=_json_value) + "\n") + + def detach(self): + if self.env is not None and self.env.step is self.wrapped_step: + self.env.step = self.original_step + self.env = None + + def attach(self, env, attempt, command_step): + self.detach() + self.env, self.attempt, self.command_step = env, attempt, command_step + self.original_step = env.step + original_step = self.original_step + model = env.sim.model + self.write(dict(kind="attempt_start", schema="lff-audit-state-1", attempt=attempt, + sampling="after_env_step", bodies=[model.body_id2name(i) for i in range(model.nbody)], + geoms=[model.geom_id2name(i) for i in range(model.ngeom)])) + + def wrapped(action): + result = original_step(action) + if self.env is env and self.wrapped_step is wrapped: + self.sample("control_step") + return result + + self.wrapped_step = wrapped + env.step = wrapped + self.sample("initial") + + def sample(self, phase): + data = self.env.sim.data + self.sequence += 1 + self.write(dict(kind="state", sequence=self.sequence, attempt=self.attempt, + command_step=self.command_step(), phase=phase, sim_time=float(data.time), + qpos=data.qpos.tolist(), qvel=data.qvel.tolist(), + body_xyz=data.body_xpos.tolist(), body_quat_wxyz=data.body_xquat.tolist(), + contacts=[[int(c.geom1), int(c.geom2), float(c.dist)] + for c in data.contact[:data.ncon]])) + + def boundary(self, task, phase): + """Capture after skill callbacks too (some injections happen after env.step). + + Copy existing event lists without calling monitor/outcome methods or + advancing their cursors. These are raw observations, not adjudications. + """ + self.sample(phase) + streams = {} + for name, obj in (("task", task), ("skills", getattr(task, "sk", None)), + ("monitor", getattr(task, "mon", None))): + attrs = obj if isinstance(obj, dict) else getattr(obj, "__dict__", {}) + for key in ("events", "turns", "strikes", "box_moves", "lifts", "grasp_tries"): + if isinstance(attrs.get(key), list): + streams[f"{name}.{key}"] = attrs[key] + self.write(dict(kind="event_snapshot", attempt=self.attempt, + command_step=self.command_step(), phase=phase, streams=streams)) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/cost.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/cost.py new file mode 100644 index 0000000000000000000000000000000000000000..96d2c7f7612fd7dff37a8936e78f3e9470b86768 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/cost.py @@ -0,0 +1,37 @@ +"""Token / cost accounting. + +Prices (USD per 1M tokens) for gpt-6-astra from the OpenAI model page as recorded in +research_notes/.../seed_papers.md Q8 (2026-10): input 10, cached input 1, cache write 12.5, output 50; +prompts > 272K input tokens are billed 2x input/cached and 1.5x output. usage.input_tokens_details has +cached_tokens and (openai SDK >= 3.x) cache_write_tokens; both are priced separately when present. +Reasoning tokens are billed as output tokens (they are included in output_tokens). +""" +import math + +PRICES = { + "gpt-6-astra": dict(input=10.0, cached=1.0, cache_write=12.5, output=50.0, long_threshold=272_000, long_in=2.0, long_out=1.5), +} + + +def call_cost(usage, model="gpt-6-astra"): + p = PRICES.get(model) + if p is None or not usage: + return None + inp = usage.get("input_tokens", 0) or 0 + cached = usage.get("cached_tokens", 0) or 0 + write = usage.get("cache_write_tokens", 0) or 0 # reported by newer SDKs / API versions + out = usage.get("output_tokens", 0) or 0 + li, lo = (p["long_in"], p["long_out"]) if inp > p["long_threshold"] else (1.0, 1.0) + plain = max(inp - cached - write, 0) + return ((plain * p["input"] + write * p["cache_write"] + cached * p["cached"]) * li + out * p["output"] * lo) / 1e6 + + +def image_tokens(w, h, patch=32, per_patch=1.0, overhead=0): + """ASSUMPTION (not verified for gpt-6-astra): patch-based image accounting as for the GPT-5 family, + one token per 32x32 patch (~256 tokens for 512x512). Real numbers come from response.usage.""" + return int(math.ceil(w / patch) * math.ceil(h / patch) * per_patch + overhead) + + +def estimate_request_tokens(stats, image_res=512): + """Rough input-token estimate of one request from OpenAIResponsesBackend.request_stats().""" + return int(stats.get("text_chars", 0) / 4 + stats.get("n_images", 0) * image_tokens(image_res, image_res)) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/harness.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/harness.py new file mode 100644 index 0000000000000000000000000000000000000000..323410f477f3320769635cf01dd368be716d9421 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/harness.py @@ -0,0 +1,300 @@ +"""Protocol controller: runs a backend on task instances, attempt by attempt. + + cross protocol : reset to the same instance (same layout + hidden variables) before every attempt + within protocol: one continuous episode; each `done` call closes a segment ("attempt") that is checked; + the agent continues from the current state if it failed and budget remains +Both protocols pack finished attempts the same way (keyframes <= 4, action summary, feedback F0/F1/F2) and +show them according to the memory mode (none / full / last / mismatched). +""" +import time +from dataclasses import asdict, dataclass, field + +from .context import (FEEDBACK_LEVELS, MEMORY_MODES, AttemptRecord, Conversation, PromptBuilder, StepRecord, + pick_keyframes, select_history, summarize_actions) +from .cost import call_cost, estimate_request_tokens +from .metrics import run_summary +from .backends.base import AttemptInfo, RunInfo + + +@dataclass +class HarnessConfig: + memory: str = "full" + feedback: str = "F2" + k: int = None # attempts (cross) / done calls (within); default task.max_attempts + image_res: int = 512 + keyframe_res: int = None # default = image_res + n_keyframes: int = 4 + cams: tuple = ("agentview", "wrist") + auto_obs: bool = True # send new images after every action tool + max_steps: int = 30 # tool calls per attempt + max_no_tool: int = 3 # consecutive replies without a tool call before the attempt is ended + privileged_locate: bool = False + grasp_report: str = "bool" # "bool" | "name" | "none" + instruction: str = "direct" # "direct" | "indirect" + early_stop: str = "auto" # "auto" (stop at first success unless F0), "yes", "no" + settle_within: int = 20 # control steps held still before checking a within-protocol segment + jpeg_quality: int = 90 + save_images: bool = True + model_for_cost: str = "gpt-6-astra" + extra: dict = field(default_factory=dict) + + def validate(self): + assert self.memory in MEMORY_MODES, self.memory + assert self.feedback in FEEDBACK_LEVELS, self.feedback + assert self.grasp_report in ("bool", "name", "none") + assert self.instruction in ("direct", "indirect") + assert self.early_stop in ("auto", "yes", "no") + assert 1 <= self.n_keyframes <= 4 or self.n_keyframes == 0 + + +def clean_inst(inst): + return {k: v for k, v in inst.items() if not str(k).startswith("_")} + + +class AgentHarness: + def __init__(self, task, backend, cfg: HarnessConfig, logger, payload_probe=None, executor_factory=None, + cam_axes=None): + cfg.validate() + self.task, self.backend, self.cfg, self.log = task, backend, cfg, logger + self.protocol = getattr(task, "protocol", "cross") + self.k = cfg.k or task.max_attempts + self.payload_probe = payload_probe # optional OpenAIResponsesBackend used only to size requests (dry run) + self.executor_factory = executor_factory # tests: build a fake executor instead of ToolExecutor + self._cam_axes = cam_axes + + # ------------------------------------------------------------------ helpers + def instruction(self, inst): + hook = getattr(self.task, "agent_instruction", None) + if hook is not None: + return hook(inst, self.cfg.instruction) + if self.cfg.instruction == "indirect" and getattr(self.task, "instruction_indirect", ""): + return self.task.instruction_indirect + return self.task.instruction + + def feedback(self, inst, out, level): + import inspect + fn = self.task.feedback + if "indirect" in inspect.signature(fn).parameters: # tasks that phrase feedback per instruction variant + return fn(inst, out, level, indirect=self.cfg.instruction == "indirect") + return fn(inst, out, level) + + def early_stop(self): + if self.cfg.early_stop == "auto": + return self.cfg.feedback != "F0" + return self.cfg.early_stop == "yes" + + def terminal(self, out): + hook = getattr(self.task, "is_terminal", None) + if hook is not None: + return bool(hook(out)) + return bool(out.get("terminal") or out.get("overshoot")) + + def _executor(self, inst): + if self.executor_factory is not None: + return self.executor_factory(self, inst) + from .tools import ToolExecutor + return ToolExecutor(self.task, inst, image_res=self.cfg.image_res, cams=self.cfg.cams, + privileged_locate=self.cfg.privileged_locate, grasp_report=self.cfg.grasp_report, + jpeg_quality=self.cfg.jpeg_quality, image_sink=self._sink) + + def _sink(self, ref): + self._img_counter += 1 + rel = f"seed{self._seed}/a{self._attempt}_s{self._step:02d}_{self._img_counter:03d}_{ref.camera}.jpg" + return self.log.save_image(ref, rel) + + def _keyframe(self, ref): + """Separate (possibly smaller) copy of an agentview frame for the history.""" + from .images import ImageRef + kres = self.cfg.keyframe_res or self.cfg.image_res + kf = ImageRef(camera=ref.camera, array=ref.array, label=ref.label) + if kres == self.cfg.image_res: + kf.jpeg, kf.path = ref.jpeg, ref.path + return kf + self._img_counter += 1 + rel = f"seed{self._seed}/a{self._attempt}_key_{self._img_counter:03d}_{ref.camera}.jpg" + return self.log.save_image(kf, rel, res=kres) + + def prompts(self, executor): + if self._cam_axes is None: + from . import camera as C + self._cam_axes = {c: C.describe_axes(self.task.env, c, self.cfg.image_res) for c in C.CAMERAS} + names = getattr(self.task, "agent_object_names", None) or list(self.task.env.objects_dict) + return PromptBuilder(self.task, self.protocol, self.k, self.cfg.memory, self.cfg.feedback, self.cfg.image_res, + self._cam_axes, privileged_locate=self.cfg.privileged_locate, object_names=names, + grasp_report=self.cfg.grasp_report, cams=self.cfg.cams) + + # ------------------------------------------------------------------ run + def run_instance(self, seed, donor=None): + """donor: AttemptRecords of another instance (memory=mismatched). Returns (summary, records).""" + task, cfg = self.task, self.cfg + inst = task.sample_instance(seed) + self._seed, self._attempt, self._step, self._img_counter = seed, 0, 0, 0 + self._llm_calls = [] + t_run = time.time() + sim_wall = 0.0 + info = RunInfo(task=task, inst=inst, seed=seed, k=self.k, protocol=self.protocol, feedback=cfg.feedback, + memory=cfg.memory) + self.backend.begin_run(info) + self.log.event("run_start", seed=seed, inst=clean_inst(inst), task=task.name, protocol=self.protocol, k=self.k, + memory=cfg.memory, feedback=cfg.feedback, donor_seed=donor[0].seed if donor else None) + records, executor, status = [], None, "ok" + for a in range(1, self.k + 1): + self._attempt, self._step = a, 0 + if self.protocol == "cross" or executor is None: + t0 = time.time() + task.reset_instance(inst) + executor = self._executor(inst) + sim_wall += time.time() - t0 + visible = select_history(cfg.memory, records, donor) + rec, attempt_sim = self._attempt_loop(inst, seed, a, visible, executor, + continuing=self.protocol == "within" and a > 1) + sim_wall += attempt_sim + records.append(rec) + if rec.ended_by == "backend_error": + status = "error" + break + if rec.success and self.early_stop(): + break + if self.protocol == "within" and (rec.success or self.terminal(rec.outcome)): + break + self.backend.end_run() + summ = run_summary(seed, records, self.k, status=status, llm_calls=self._llm_calls, + extra=dict(sim_wall_s=round(sim_wall, 2), wall_s=round(time.time() - t_run, 2), + donor_seed=donor[0].seed if donor else None)) + self.log.event("run_end", **summ) + summ["_llm_calls"] = self._llm_calls + return summ, records + + def _attempt_loop(self, inst, seed, a, visible, ex, continuing): + cfg, task, backend = self.cfg, self.task, self.backend + P = self.prompts(ex) + tools = self.tool_specs() + conv = Conversation(P.system_prompt()) + backend.begin_attempt(AttemptInfo(attempt=a, history=visible, continuing=continuing)) + sim_t = 0.0 + t0 = time.time() + obs0 = ex.observe(label="start") + sim_t += time.time() - t0 + conv.add_user(P.history_parts(self.instruction(inst), visible), live=False) + conv.add_user(P.current_parts(a, obs0, ex.proprio(), continuing), live=True) + steps, diagnosis, done_reason, ended_by = [], None, None, None + n_calls, no_tool = 0, 0 + while ended_by is None: + if len(steps) >= cfg.max_steps: + ended_by = "step_budget" + break + try: + resp = backend.act(conv, tools) + except Exception as e: # API failure after retries, crashed scripted policy, ... + self.log.event("llm_error", seed=seed, attempt=a, call=n_calls + 1, error=repr(e)[:4000]) + ended_by = "backend_error" + break + n_calls += 1 + call_rec = self._log_llm_call(seed, a, n_calls, resp, conv, tools) + self._llm_calls.append(call_rec) + if n_calls == 1 and resp.text: + diagnosis = resp.text + conv.add_assistant(resp.text, resp.tool_calls, raw=resp.raw, backend=backend.name) + if not resp.tool_calls: + no_tool += 1 + if no_tool >= cfg.max_no_tool: + ended_by = "no_tool_call" + break + conv.add_user(P.nudge(), live=True) + continue + no_tool = 0 + acted = None + for tc in resp.tool_calls: + self._step = len(steps) + 1 + res = ex.call(tc.name, tc.raw_arguments or tc.arguments) + sim_t += res.wall_s + conv.add_tool_output(tc.id, tc.name, res.text()) + backend.on_tool_result(tc, res) + st = StepRecord(step=self._step, name=tc.name, args=res.args, report=res.report, ok=res.ok, + wall_s=round(res.wall_s, 3), sim_steps=res.sim_steps) + steps.append(st) + if res.images: + conv.add_user(P.observation_parts(f"Images returned by get_observation (step {self._step})", + res.images, ex.proprio()), live=True) + if tc.name in ("move_to", "open_gripper", "close_gripper", "push") and res.ok: + acted = st + self.log.event("tool_call", seed=seed, attempt=a, step=self._step, call_id=tc.id, name=tc.name, + args=res.args, ok=res.ok, report=res.report, wall_s=round(res.wall_s, 3), + sim_steps=res.sim_steps, images=[i.path for i in res.images]) + if res.ended: + done_reason = res.args.get("reason") + ended_by = "done" + break + if len(steps) >= cfg.max_steps: + break + if ended_by is None and acted is not None: + t1 = time.time() + if cfg.auto_obs: + obs = ex.observe(label=f"step{acted.step}") + conv.add_user(P.step_observation(acted.step, acted.name, obs, ex.proprio()), live=True) + acted.frame = next((o for o in obs if o.camera == "agentview"), obs[0]) + else: # still keep an agentview frame for the history keyframes / logs + from .images import ImageRef + acted.frame = self._sink(ImageRef(camera="agentview", array=ex.render("agentview"), + label=f"step{acted.step}")) + sim_t += time.time() - t1 + self.log.event("observation", seed=seed, attempt=a, step=acted.step, + images=[acted.frame.path] if not cfg.auto_obs else [o.path for o in obs], + proprio=ex.proprio()) + meta = backend.end_attempt() or {} + # ------------------------------------------------------------ outcome + packing + t1 = time.time() + home = getattr(task, "go_home", None) # task-defined end-of-attempt motion (e.g. L6: arm out of view) + if home is not None and ended_by != "backend_error": + home() + if self.protocol == "within" and cfg.settle_within: + ex.sk.hold(cfg.settle_within) + out = task.outcome(inst) + from .images import ImageRef + self._step = 99 + final = self._sink(ImageRef(camera="agentview", array=ex.render("agentview", cfg.keyframe_res or cfg.image_res), + label="end")) + sim_t += time.time() - t1 + fb = self.feedback(inst, out, cfg.feedback) + fb_full = self.feedback(inst, out, "F2") + init_frame = next((o for o in obs0 if o.camera == "agentview"), None) + for s in steps: + if s.frame is not None and (cfg.keyframe_res or cfg.image_res) != cfg.image_res: + s.frame = self._keyframe(s.frame) + if init_frame is not None and (cfg.keyframe_res or cfg.image_res) != cfg.image_res: + init_frame = self._keyframe(init_frame) + kfs = pick_keyframes(steps, init_frame, final, cfg.n_keyframes) if cfg.n_keyframes else [] + rec = AttemptRecord(seed=seed, attempt=a, steps=steps, keyframes=kfs, outcome=dict(out), + success=bool(out.get("success")), feedback=fb, done_reason=done_reason, diagnosis=diagnosis, + ended_by=ended_by, backend_meta=meta) + calls = [c for c in self._llm_calls if c["attempt"] == a] + self.log.event("attempt_end", seed=seed, attempt=a, success=rec.success, outcome=out, feedback_shown=fb, + feedback_f2=fb_full, ended_by=ended_by, done_reason=done_reason, diagnosis=diagnosis, + n_steps=len(steps), n_llm_calls=len(calls), backend_meta=meta, + history_shown=[(h.seed, h.attempt) for h in visible], + keyframes=[(c, r.path) for c, r in kfs], action_summary=summarize_actions(steps), + llm_latency_s=round(sum(c["latency_s"] for c in calls), 3), sim_wall_s=round(sim_t, 3)) + return rec, sim_t + + def tool_specs(self): + from .tools import tool_specs + names = getattr(self.task, "agent_object_names", None) or list(self.task.env.objects_dict) + return tool_specs(self.cfg.privileged_locate, names, self.cfg.image_res) + + def _log_llm_call(self, seed, a, n, resp, conv, tools): + rec = dict(seed=seed, attempt=a, call=n, latency_s=round(resp.latency_s, 3), usage=resp.usage, + cost_usd=call_cost(resp.usage, self.cfg.model_for_cost) if resp.usage else None, + status=resp.status, error=resp.error, text=resp.text, reasoning_summary=resp.reasoning_summary, + reasoning_summary_status="recorded" if resp.reasoning_summary else "not_returned", + tool_calls=[dict(id=t.id, name=t.name, arguments=t.arguments) for t in resp.tool_calls], + request=resp.request_stats, conv_images=conv.n_images()) + if self.payload_probe is not None: # dry run: size of the request GPT-6 would have received + stats = self.payload_probe.request_stats(self.payload_probe.build_request(conv, tools)) + stats["est_input_tokens"] = estimate_request_tokens(stats, self.cfg.image_res) + rec["dry_run_request"] = stats + self.log.event("llm_call", **rec) + return rec + + +def config_dict(cfg): + return asdict(cfg) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/metrics.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..74e3c49b4247c0adbc6c9fd37d9d50b82d188348 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/metrics.py @@ -0,0 +1,97 @@ +"""Run-level metrics (design doc 02 §5): succ@k per run, attempt-1 success, first-success attempt, +fields for ΔICL = succ@k(with history) - pass@k_iid(independent retries), same-mistake (repeated +action) rate, residuals, tokens / cost / latency.""" +import numpy as np + +from .context import wilson + + +def run_summary(seed, records, k, status="ok", llm_calls=(), extra=None): + """records: list[AttemptRecord] of one run (one instance).""" + succ = [bool(r.success) for r in records] + first = next((r.attempt for r in records if r.success), None) + fails = [r for r in records if not r.success] + pairs = [(a, b) for a, b in zip(records, records[1:]) if not a.success] + repeats = [a.action_signature() == b.action_signature() for a, b in pairs] + residuals = [{kk: v for kk, v in r.outcome.items() if kk.endswith("_err") and isinstance(v, (int, float))} + for r in records] + lat = [c.get("latency_s", 0.0) for c in llm_calls] + usage = {key: int(sum((c.get("usage") or {}).get(key, 0) or 0 for c in llm_calls)) + for key in ("input_tokens", "cached_tokens", "cache_write_tokens", "output_tokens", + "reasoning_tokens")} + cost = [c.get("cost_usd") for c in llm_calls if c.get("cost_usd") is not None] + out = dict(seed=seed, status=status, k=k, n_attempts=len(records), success_by_attempt=succ, + first_success=first, success=first is not None, attempt1_success=bool(succ[0]) if succ else False, + ended_by=[r.ended_by for r in records], n_failed_attempts=len(fails), + repeated_action_pairs=int(sum(repeats)), failed_pairs=len(pairs), residuals=residuals, + n_llm_calls=len(llm_calls), llm_latency_s=float(sum(lat)), usage=usage, + cost_usd=float(sum(cost)) if cost else None, + n_tool_calls=int(sum(len(r.steps) for r in records))) + if extra: + out.update(extra) + return out + + +def aggregate(runs, k): + ok = [r for r in runs if r["status"] == "ok"] + n = len(ok) + first = [r["first_success"] for r in ok] + curve, ci = [], [] + for j in range(1, k + 1): + s = sum(1 for f in first if f is not None and f <= j) + curve.append(s / n if n else float("nan")) + ci.append(wilson(s, n)) + p1 = curve[0] if curve else float("nan") + succ_first = [f for f in first if f is not None] + calls = [c for r in ok for c in r.get("_llm_calls", [])] + lat = np.array([c.get("latency_s", 0.0) for c in calls]) if calls else np.zeros(0) + pairs = sum(r["failed_pairs"] for r in ok) + tot = {key: int(sum(r["usage"].get(key, 0) for r in ok)) + for key in ("input_tokens", "cached_tokens", "cache_write_tokens", "output_tokens", "reasoning_tokens")} + costs = [r["cost_usd"] for r in ok if r.get("cost_usd") is not None] + return dict( + n_runs=n, n_error_runs=len(runs) - n, k=k, + succ_at=curve, succ_at_ci95=ci, succ_at_k=curve[-1] if curve else float("nan"), + attempt1_success=p1, + # ΔICL needs pass@k of independent retries: measure it with --memory none on the same seeds and + # compare with scripts/agent_compare.py. The analytic value assumes i.i.d. attempts with the + # attempt-1 success rate of THIS run set (a cheaper but weaker reference). + pass_at_k_iid_analytic=1 - (1 - p1) ** k if n else float("nan"), + delta_icl_vs_analytic_iid=(curve[-1] - (1 - (1 - p1) ** k)) if n else float("nan"), + mean_first_success=float(np.mean(succ_first)) if succ_first else None, + median_first_success=float(np.median(succ_first)) if succ_first else None, + repeated_action_rate=(sum(r["repeated_action_pairs"] for r in ok) / pairs) if pairs else None, + llm_calls_per_run=float(np.mean([r["n_llm_calls"] for r in ok])) if ok else None, + llm_latency_mean_s=float(lat.mean()) if lat.size else None, + llm_latency_p50_s=float(np.percentile(lat, 50)) if lat.size else None, + llm_latency_p95_s=float(np.percentile(lat, 95)) if lat.size else None, + llm_latency_per_run_s=float(np.mean([r["llm_latency_s"] for r in ok])) if ok else None, + sim_wall_per_run_s=float(np.mean([r.get("sim_wall_s", 0.0) for r in ok])) if ok else None, + tool_calls_per_run=float(np.mean([r["n_tool_calls"] for r in ok])) if ok else None, + usage_total=tot, + cache_hit_rate=(tot["cached_tokens"] / tot["input_tokens"]) if tot["input_tokens"] else None, + cost_usd_total=float(sum(costs)) if costs else None, + cost_usd_per_run=float(np.mean(costs)) if costs else None, + ) + + +def paired_delta(with_runs, iid_runs, k, n_boot=10000, seed=0): + """ΔICL = succ@k(with) - succ@k(iid) on the seeds both run sets share, with a paired bootstrap CI.""" + a = {r["seed"]: r for r in with_runs if r["status"] == "ok"} + b = {r["seed"]: r for r in iid_runs if r["status"] == "ok"} + seeds = sorted(set(a) & set(b)) + if not seeds: + return dict(n=0) + + def ok(r): + return r["first_success"] is not None and r["first_success"] <= k + + x = np.array([ok(a[s]) for s in seeds], float) + y = np.array([ok(b[s]) for s in seeds], float) + d = x - y + rng = np.random.default_rng(seed) + idx = rng.integers(0, len(d), size=(n_boot, len(d))) + boot = d[idx].mean(1) + return dict(n=len(seeds), succ_at_k_with=float(x.mean()), succ_at_k_iid=float(y.mean()), delta_icl=float(d.mean()), + ci95=[float(np.percentile(boot, 2.5)), float(np.percentile(boot, 97.5))], + discordant=dict(with_only=int(((x == 1) & (y == 0)).sum()), iid_only=int(((x == 0) & (y == 1)).sum()))) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/arm_specs/l5_loaded_beam.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/arm_specs/l5_loaded_beam.py new file mode 100644 index 0000000000000000000000000000000000000000..e3840ef5042baaaf6b33ba45cefbc208da4547e0 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/arm_specs/l5_loaded_beam.py @@ -0,0 +1,40 @@ +"""Controlled arms for l5_loaded_beam (2026-10-12, docs/14 sec. 6). + +Hidden variable: the bar's centre of mass `com_offset` (m along the bar from its middle, + = the robot's left end), +set at reset by l5_slippery_lift.set_hidden_weight (body_ipos + inertia + envs.refit_bounds, so a changed value is +honoured). `com_total` (bar + both blocks) is derived from it in sample_instance and read by oracle_params, so it is +overridden together. Mass, friction and layout stay as sampled. + +h0 : centre of mass at the middle (0): the common-sense middle grasp lifts the bar level. +twin : the same offset on the other side (-com_offset): the middle grasp still tilts the bar and spills a block, but + now towards the other end, so the right grasp point is mirrored. +reveal: the hidden weight's side and the bar's centre of mass in cm (plus the bar's mass in g), in the F2 words. +""" +HIDDEN_KEYS = ("com_offset", "com_total") + + +def h0(inst): + return dict(com_offset=0.0, com_total=0.0) + + +def twin(inst): + return dict(com_offset=-float(inst["com_offset"]), com_total=-float(inst["com_total"])) + + +def reveal(inst): + e = float(inst["com_offset"]) + side = "left" if e > 0 else "right" + return (f"The bar is not uniform: a heavy weight is hidden inside it towards its {side} end (the robot's {side}). " + f"The bar weighs {1000 * inst['mass']:.0f} g and its centre of mass is {100 * abs(e):.1f} cm to the " + f"{side} of its middle.") + + +def fix(inst, params): + """Ladder Fix rung (docs/20): grasp at the combined centre of mass (oracle along = com_total), lift 15 cm at 0.1.""" + a = float(params["along"]) + side = "left" if a > 0 else "right" + return (f"A way to succeed: grasp the bar at its balance point, not at its middle. Open the gripper, turn it so " + f"the jaws close across the bar's 4 cm width, come down over the point {100 * abs(a):.1f} cm to the " + f"robot's {side} of the bar's middle (the centre of mass of the bar and the two blocks) until the " + f"fingers are at the bar's mid-height, close the gripper and lift straight up about 15 cm slowly (speed " + f"about 0.1). Held there, the bar stays level and both blocks stay on it.") diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/arm_specs/l5_slide_to_target.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/arm_specs/l5_slide_to_target.py new file mode 100644 index 0000000000000000000000000000000000000000..74eccfbae3bf4872ef4d65f64d620ab85e9e74f5 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/arm_specs/l5_slide_to_target.py @@ -0,0 +1,61 @@ +"""Controlled arms for l5_slide_to_target (docs/14 §6). + +Hidden variable: mu, the cube-table sliding friction (apply_instance() sets it on every reset; oracle_params() bisects +the strike speed with it). The layout (cube_xy, target_dist) is kept. + +The naive strike is 0.30 m/s. Where the cube stops depends on mu and, by up to ~1.5 cm, on the cube's position on the +table, and the target tolerance is only +-1 cm, so H0 and the twin are calibrated per full5 seed with a simulated sweep +(deterministic sim, scratchpad arms/fine.py, 2026-10-12); other seeds fall back to a power-law fit of the stopping +distance at 0.30 m/s (dist ~ 0.00453 / mu^1.04 m). + + h0 mu at which the 0.30 m/s strike stops the cube on the square's centre (|err| <= 0.3 cm). + twin the opposite trap: if the original cube overshoots (slippery) the twin is grippy and stops short, and vice + versa, so the correction is the other way (slow down <-> speed up). The twin's naive error is at least 2 cm + and, where the twin's oracle still succeeds, about as large as the original's (mirrored). Seeds 3000 and 3007 + overshoot by 6.9 / 4.1 cm, but a grippy cube cannot be made to stop that far short and still be solvable, + so their twins stop 2.1 / 3.4 cm short. + reveal states the friction coefficient only. +""" + +HIDDEN_KEYS = ("mu",) + +# seed: h0 mu (naive err there), twin mu (twin naive err, twin oracle speed m/s -> err). Original naive err in brackets. +_CAL = { + 3000: dict(h0=0.0749, twin=0.1060), # [orig +6.94 cm] h0 +0.26; twin -2.13, oracle 0.551 -> +0.01 + 3001: dict(h0=0.0602, twin=0.0783), # [orig +2.95 cm] h0 +0.14; twin -2.73, oracle 0.450 -> 0.00 + 3003: dict(h0=0.0583, twin=0.0463), # [orig -1.73 cm] h0 +0.03; twin +2.75, oracle 0.242 -> -0.13 + 3004: dict(h0=0.0537, twin=0.0444), # [orig -1.66 cm] h0 -0.31; twin +2.14, oracle 0.240 -> -0.02 + 3007: dict(h0=0.0532, twin=0.0984), # [orig +4.05 cm] h0 +0.15; twin -3.39, oracle 0.570 -> -0.18 +} + + +def _h0_mu(inst): + c = _CAL.get(int(inst.get("seed", -1))) + return c["h0"] if c else (0.00453 / float(inst["target_dist"])) ** (1 / 1.04) + + +def h0(inst): + return {"mu": float(_h0_mu(inst))} + + +def twin(inst): + c = _CAL.get(int(inst.get("seed", -1))) + if c: + return {"mu": float(c["twin"])} + m0 = _h0_mu(inst) # fallback: mirror mu about the H0 value in log space, kept in a solvable range + return {"mu": float(min(max(m0 * m0 / float(inst["mu"]), 0.03), 0.10))} + + +def reveal(inst): + return f"The red cube's sliding friction coefficient on the table is about {float(inst['mu']):.3f}." + + +def fix(inst, params): + """Ladder Fix rung (docs/20): one strike at the oracle speed (bisection with the true mu), 22 cm run-up, stopping + 1.5 cm past the cube's near face -- as l5_slide.execute; move_eef speed = Skills.move_to speed.""" + v = float(params["speed"]) + return (f"A way to succeed: one straight strike at the right speed. Close the gripper (yaw 0), put the fingertips " + f"just above the table (grasp point about 2 cm above the tabletop) 22 cm behind the cube's centre, on the " + f"robot's side and in line with the cube and the target, then in one move_eef command move straight " + f"forward at speed {v:.2f} to a point 1.5 cm past where the cube's near face was (0.5 cm short of its " + f"centre), and lift the gripper. The cube then slides into the target zone.") diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/arm_specs/l5_tablecloth_pull.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/arm_specs/l5_tablecloth_pull.py new file mode 100644 index 0000000000000000000000000000000000000000..d72cb9403cf21f0b5deead7e856fccc350305744 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/arm_specs/l5_tablecloth_pull.py @@ -0,0 +1,61 @@ +"""Controlled arms for l5_tablecloth_pull (docs/14 §6). + +Hidden variable: mu, the cube's friction (cube-board and cube-table contacts; apply_instance() sets it on every reset, +oracle_params() bisects the pull speed with it). The layout keys (board_xy, band_d) are left alone: band_d was sampled +from the original mu, but it is the visible band position, so H0 and the twin keep it and move only mu. + +Physics (measured, 2026-10-12): the cube's displacement toward the robot grows with mu and shrinks with the pull speed +up to ~0.8 m/s (0.8 and 1.0 m/s give identical results: the controller saturates). The naive policy yanks at 0.6 m/s. +Every original instance lands SHORT of the band (cube forward of it, err -1.6 .. -3.5 cm): the lesson is "pull +slower". + + h0 mu at which the 0.6 m/s yank lands the cube on the band's centre line (calibrated per full5 seed by a + simulated sweep; a linear fit in band_d for other seeds). + twin the opposite trap: mu high enough that the 0.6 m/s yank drags the cube PAST the band toward the robot + (err +1.5 .. +2.7 cm), so the lesson is "pull faster" (the twin's oracle pulls at 0.64-0.79 m/s; agents can + command up to 1.0 m/s). Applying that lesson to the original makes its cube land even further short. + The window is narrow: above it the cube cannot be stopped in the band even at the saturated top speed, so the + twin's naive error is only ~1.5-2.7 cm (similar size to the original's short-fall) and the twin's oracle is + within 0.2-0.5 cm of the band tolerance on some seeds. Calibrated per seed; for other seeds 1.2 x the H0 mu. + reveal states the cube's friction coefficient (the only fact that differs between instances). +""" + +HIDDEN_KEYS = ("mu",) + +# Calibrated 2026-10-12 with the scripted policies (scratchpad arms/fine.py; deterministic sim). +# seed: (h0 mu, naive err at h0 [cm]), (twin mu, naive err [cm], twin oracle speed [m/s], twin oracle err [cm]) +_CAL = { + 3000: dict(h0=0.1543, twin=0.1876), # h0 +0.08; twin naive +1.65, oracle 0.719 m/s +0.60 + 3001: dict(h0=0.1744, twin=0.1995), # h0 +0.13; twin naive +2.17, oracle 0.638 m/s +0.47 + 3002: dict(h0=0.1393, twin=0.1716), # h0 -0.11; twin naive +1.48, oracle 0.759 m/s +0.78 + 3003: dict(h0=0.1442, twin=0.1775), # h0 +0.08; twin naive +2.18, oracle 0.759 m/s +0.44 + 3004: dict(h0=0.1944, twin=0.2250), # h0 +0.06; twin naive +2.74, oracle 0.790 m/s +0.51 +} + + +def _h0_mu(inst): + c = _CAL.get(int(inst.get("seed", -1))) + return c["h0"] if c else 0.0835 + 1.485 * float(inst["band_d"]) + + +def h0(inst): + return {"mu": float(_h0_mu(inst))} + + +def twin(inst): + c = _CAL.get(int(inst.get("seed", -1))) + return {"mu": float(c["twin"] if c else 1.2 * _h0_mu(inst))} + + +def reveal(inst): + return (f"The red cube's friction coefficient (against the board and against the table) is about " + f"{float(inst['mu']):.3f}.") + + +def fix(inst, params): + """Ladder Fix rung (docs/20): one pull of 25 cm at the oracle speed (bisection with the true mu), as + l5_tablecloth_pull.execute; move_eef speed = Skills.move_to speed.""" + v = float(params["speed"]) + return (f"A way to succeed: pull at the right speed. Grasp the black handle (jaws closing across its 4 cm width), " + f"then in one move_eef command pull the board straight towards the robot by 25 cm at speed {v:.2f}; then " + f"open the gripper and lift. The cube then lands in the green band.") diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/__init__.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f4cd98634d0f03f0ea0113276c0cab47dc9b2261 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/__init__.py @@ -0,0 +1,63 @@ +"""Harness adapters (docs/15): one way to plug any agent harness into a robot_server session. + + ours reference driver scripts/api_player.py (main table) + claude_code Claude Code CLI, --bare, only our MCP tools (arm B) + claude_code_full Claude Code CLI without --bare: full system prompt, still one-time dirs and only MCP (arm B') + codex Codex CLI exec (+ exec resume on early exit), one-time CODEX_HOME, only our MCP tools (arm F) + rpent_codex RPent (robot harness framework) on Codex: RPent's loop and prompt, the main table's Codex config, + tools through the episode's tool gateway (docs/18, lffbench/harnesses/rpent.py) + dsh DeepSeek Harness (`dsh --profile headless`), only our MCP tools, one-time dirs + +Use scripts/harness_run.py (one session) or scripts/api_batch.py start --harness ... (batches). +""" +import json +import importlib +import os +import sys + +from .base import EpisodeSpec, HarnessAdapter, HarnessRefused, first_message_text # noqa: F401 + +# A new Codex-based Robot Harness registers here; both single-run and batch CLIs +# derive their choices, provider and common options from this registry. +ROBOT_HARNESSES = { + "rpent_codex": ("rpent", "RPentCodex"), + "sensenova_codex": ("sensenova", "SenseNovaCodex"), + "embodied_evo_codex": ("embodied_evo", "EmbodiedEvoCodex"), +} +NAMES = ("ours", "claude_code", "claude_code_full", "codex", "dsh", *ROBOT_HARNESSES) +PROVIDER = dict(claude_code="anthropic", claude_code_full="anthropic", codex="openai", dsh="deepseek", + **{name: "openai" for name in ROBOT_HARNESSES}) + + +def get_adapter(name, **kw): + if name == "ours": + from .reference import Reference + return Reference(**kw) + if name == "claude_code": + from .claude_code import ClaudeCode + return ClaudeCode(**kw) + if name == "claude_code_full": + from .claude_code import ClaudeCodeFull + return ClaudeCodeFull(**kw) + if name == "codex": + from .codex import Codex + return Codex(**kw) + if name == "dsh": + from .dsh import DeepSeekHarness + return DeepSeekHarness(**kw) + if name in ROBOT_HARNESSES: + module, cls = ROBOT_HARNESSES[name] + return getattr(importlib.import_module("." + module, __name__), cls)(**kw) + raise ValueError(f"unknown harness {name!r}; one of {NAMES}") + + +def render_first_message(ep): + """Call `status` once over HTTP (exactly as the reference driver does before its first turn) and build the first + user message for a native harness. Returns (text, status_json).""" + sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), + "scripts")) + from api_player import call_server # noqa: E402 + st = json.loads(call_server(ep.port, ep.token, "status", {})) + readme = open(os.path.join(ep.sandbox, "README.md")).read() + status_json = json.dumps(st) + return first_message_text(readme, status_json), status_json diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/base.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/base.py new file mode 100644 index 0000000000000000000000000000000000000000..a097239bb25ebb0ec6d52038303ee8bf5c867c2a --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/base.py @@ -0,0 +1,364 @@ +"""Harness adapter interface (docs/15 §3). + +An adapter runs one episode (one robot_server session) with one agent harness and leaves behind, in the run's log +dir: harness.json (what was launched), trajectory.jsonl (unified trajectory), harness_audit.json (checks + violations). +Budgets, automatic finish and attempt switching are NOT the adapter's business: robot_server and the MCP server / +reference driver enforce them identically for every harness. + + name stable harness name (the "harness" column of a table) + capabilities CapabilityDecl: every item of REQUIRED and FORBIDDEN must be declared, with its evidence source; + a missing item makes the class definition fail (so the import fails) + version() the actual installed version (probed before launch) + prepare(ep, first_message) -> LaunchSpec: one-time dirs, configs, argv / env + launch(spec) fail-closed preflight, then start the process (env exactly the whitelist) -> RunHandle + collect(h) native event stream -> trajectory.jsonl (ATIF-like), usage, exit reason + audit(h) tool list, preset prompt, memory, state left behind, violations +""" +import dataclasses +import json +import os +import secrets +import shutil +import signal +import subprocess +import time + +from . import contract as C + +EVIDENCE = ("launch", "stream", "server", "probe", "preflight") + +REQUIRED = { + "only_benchmark_tools": "the model can call exactly robot / shell / view_images (ours) and nothing else of use", + "images_reach_model": "view_images returns the image bytes to the model unchanged", + "non_persistent_session": "nothing of the session is written to disk for later runs", + "pinned_version": "the harness version (and binary hash) is recorded and pinned", + "machine_readable_events": "a machine-readable event stream of the whole run", + "tool_calls_logged": "every tool call is logged (harness stream + MCP / driver transcript + events.jsonl)", + "model_and_effort": "model and reasoning effort can be set and are visible in the request", +} +FORBIDDEN = { + "persistent_memory": "harness memory across runs (C4: auto-memory, CLAUDE.md / AGENTS.md, memories db)", + "instruction_file_injection": "instruction files picked up from the work / config / home dir", + "web_access": "web search / fetch", + "host_file_read": "reading host files outside the episode workspace", + "builtin_shell": "a shell of the harness itself (outside our jailed shell tool)", + "subagent_delegation": "spawning sub-agents", + "background_execution": "background tasks that outlive a tool call", +} + + +@dataclasses.dataclass(frozen=True) +class Cap: + status: str # REQUIRED items: "yes" | "partial" | "no"; FORBIDDEN items: "absent" | "present" | "partial" + evidence: str # one of EVIDENCE + note: str = "" + + +PROXY_KEYS = ("HTTPS_PROXY", "HTTP_PROXY", "https_proxy", "http_proxy") +NO_PROXY_KEYS = ("NO_PROXY", "no_proxy") +NO_PROXY_LOCAL = "127.0.0.1,localhost,::1" + + +def proxy_env(environ=None): + """The calling environment's HTTP(S) proxy, passed to a native harness so it can reach the model API on machines + that only get out through a proxy. NO_PROXY is loopback only (the preflight's fake API), never the host's list. + Not part of config_sha256 (machine plumbing, not harness configuration).""" + environ = os.environ if environ is None else environ + e = {k: environ[k] for k in PROXY_KEYS if environ.get(k)} + if e: + e.update({k: NO_PROXY_LOCAL for k in NO_PROXY_KEYS}) + return e + + +class CapabilityError(TypeError): + pass + + +def check_capabilities(name, caps): + if not isinstance(caps, dict): + raise CapabilityError(f"{name}: capabilities must be a dict") + missing = [k for k in list(REQUIRED) + list(FORBIDDEN) if k not in caps] + extra = [k for k in caps if k not in REQUIRED and k not in FORBIDDEN] + if missing or extra: + raise CapabilityError(f"{name}: capability declaration incomplete: missing {missing}, unknown {extra}") + for k, c in caps.items(): + if not isinstance(c, Cap) or c.evidence not in EVIDENCE: + raise CapabilityError(f"{name}: capability {k!r} needs a Cap(status, evidence in {EVIDENCE})") + ok = ("yes", "partial", "no") if k in REQUIRED else ("absent", "present", "partial") + if c.status not in ok: + raise CapabilityError(f"{name}: capability {k!r} status must be one of {ok}") + + +class HarnessRefused(RuntimeError): + """Fail-closed: the launch preflight found a tool list / preset prompt that is not the pinned one.""" + + +@dataclasses.dataclass +class EpisodeSpec: + session_path: str + log_dir: str + sandbox: str + port: int + token: str + max_tool_calls: int + model: str + effort: str + provider: str = "" + task: str = "" + seed: int = 0 + extra: dict = dataclasses.field(default_factory=dict) + + @classmethod + def from_session(cls, session_path, model, effort, provider="", **extra): + session_path = os.path.abspath(session_path) + log_dir = os.path.dirname(session_path) + sess = json.load(open(session_path)) + iface = json.load(open(os.path.join(log_dir, "agent_iface.json"))) + st = C.session_start(log_dir) + return cls(session_path=session_path, log_dir=log_dir, sandbox=sess["sandbox"], port=int(sess["port"]), + token=iface["token"], max_tool_calls=int(iface["max_tool_calls"]), model=model, effort=effort, + provider=provider, task=st["task"], seed=int(st["seed"]), extra=extra) + + +@dataclasses.dataclass +class LaunchSpec: + argv: list # full argv (the first message may be one element) + env: dict # the complete environment of the harness process (nothing else is inherited) + cwd: str + run_dir: str = "" # one-time dir tree, removed after audit + state_dirs: dict = dataclasses.field(default_factory=dict) # name -> path (home, config, ...) + first_message: str = "" + config_files: dict = dataclasses.field(default_factory=dict) # name -> path of files the adapter wrote + stdout_path: str = "" + stderr_path: str = "" + redact_argv: dict = dataclasses.field(default_factory=dict) # argv index -> replacement for the log + preflight: dict = dataclasses.field(default_factory=dict) + timeout_s: float = 10800 + + +@dataclasses.dataclass +class RunHandle: + spec: LaunchSpec + ep: EpisodeSpec + proc: object = None + pid: int = 0 + t_start: float = 0.0 + t_end: float = 0.0 + exit_code: int = None + exit_reason: str = "" + env_observed_keys: list = None # read from /proc//environ right after the start + info: dict = dataclasses.field(default_factory=dict) + + +def env_keys_of(pid): + try: + raw = open(f"/proc/{pid}/environ", "rb").read() + except OSError: + return None + return sorted({kv.split(b"=", 1)[0].decode("utf-8", "replace") for kv in raw.split(b"\0") if kv}) + + +def new_run_dir(root="/tmp/lffrun"): + """/tmp/lffrun/<12 hex>: the opaque work dir (its path is shown to the model by some harnesses).""" + os.makedirs(root, exist_ok=True) + while True: + d = os.path.join(root, secrets.token_hex(6)) + try: + os.mkdir(d, 0o700) + return d + except FileExistsError: + continue + + +def binary_info(path): + real = os.path.realpath(path) + return dict(path=path, realpath=real, sha256=C.sha256_file(real) if os.path.exists(real) else None) + + +class HarnessAdapter: + name = None + capabilities = None + uses_mcp = False + uses_gateway = False # harness_run starts the episode's tool gateway (scripts/tool_gateway.py) for + # this adapter: MCP adapters through the MCP server, framework adapters + # (RPent, ...) through lffbench_client with LFF_GATEWAY_URL / LFF_GATEWAY_TOKEN + clean_dirs = () # keys of spec.state_dirs that must be empty at launch + clean_allowed = {} # key of spec.state_dirs -> file names the adapter itself put there (e.g. auth.json) + ancestor_files = () # instruction files that must not exist in the work dir or any ancestor + unsafe_skip_clean_check = False # tests/harness_selfcheck only (probing what the harness would read) + jail = None # lffbench/harnesses/jail.HarnessJail when the adapter runs jailed (docs/15 §3.4) + can_resume = False # resume(): the CLI can continue its session with one more user message + + def clean_state_problems(self, spec): + """Fail-closed: the work dir and the one-time dirs must be empty, and no instruction file may sit in an + ancestor of the work dir (harnesses walk up the tree looking for CLAUDE.md / AGENTS.md).""" + p = [] + if spec.cwd and os.path.isdir(spec.cwd) and os.listdir(spec.cwd): + p.append(f"work dir not empty: {sorted(os.listdir(spec.cwd))[:5]}") + for k in self.clean_dirs: + d = spec.state_dirs.get(k) + left = [n for n in os.listdir(d) if n not in self.clean_allowed.get(k, ())] if d and os.path.isdir(d) else [] + if left: + p.append(f"{k} dir not empty: {sorted(left)[:5]}") + d = spec.cwd + while d and d != "/": + d = os.path.dirname(d) + for f in self.ancestor_files: + if os.path.exists(os.path.join(d, f)): + p.append(f"instruction file in an ancestor of the work dir: {os.path.join(d, f)}") + return p + + def __init_subclass__(cls, **kw): + super().__init_subclass__(**kw) + if cls.name is None: + raise CapabilityError(f"{cls.__name__}: no name") + check_capabilities(cls.name, cls.capabilities) + + # -------------------------------------------------------------------------------------------- interface + def version(self): + raise NotImplementedError + + def prepare(self, ep, first_message): + raise NotImplementedError + + def preflight(self, spec, ep): + """Fail-closed launch check; returns a dict for harness.json, raises HarnessRefused.""" + return dict(skipped=True) + + def collect(self, h): + raise NotImplementedError + + def audit(self, h): + raise NotImplementedError + + # -------------------------------------------------------------------------------------------- shared + def mcp_server_command(self, python, script, args): + """(command, args) of the MCP server entry in the harness config: our server, or, jailed, the relay to it.""" + if self.jail is not None: + return self.jail.mcp_command([python, script] + list(args), env={"PATH": "/usr/bin:/bin"}) + return python, [script] + list(args) + + def jailed_argv(self, argv, env, cwd, dirs): + """argv as started: unchanged, or wrapped into the jail with `dirs` (one-time dirs) mounted back.""" + return self.jail.wrap(argv, env, cwd, dirs) if self.jail is not None else list(argv) + + def jail_info(self): + return self.jail.info() if self.jail is not None else dict(enabled=False) + + def auth_info(self): + """How the harness authenticates to the model API (for harness.json; never a secret).""" + return dict(mode="api_env", keys=sorted(getattr(self, "api_env", {}) or {})) + + def launch(self, spec, ep, skip_preflight=False): + if not self.unsafe_skip_clean_check: + probs = self.clean_state_problems(spec) + if probs: + spec.preflight = dict(problems=probs) + raise HarnessRefused("clean-state check: " + "; ".join(probs)) + spec.preflight = dict(skipped=True, reason="skip_preflight") if skip_preflight else self.preflight(spec, ep) + out = open(spec.stdout_path, "wb") + err = open(spec.stderr_path, "wb") + h = RunHandle(spec=spec, ep=ep, t_start=time.time()) + argv = self.jailed_argv(spec.argv, spec.env, spec.cwd, list(spec.state_dirs.values()) + [spec.run_dir]) + h.proc = subprocess.Popen(argv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=out, + stderr=err, start_new_session=True) + h.pid = h.proc.pid + for _ in range(20): # the exec has happened once /proc//environ differs from ours + keys = env_keys_of(h.pid) + if keys is not None and set(keys) == set(spec.env): + break + time.sleep(0.05) + h.env_observed_keys = keys # retain the observed sample; a second read can race setpriv/exec + return h + + def resume_argv(self, h, message): + """argv that continues the run's session with one more user message (adapters with can_resume).""" + raise NotImplementedError + + def resume(self, h, message): + """Continue the run's session with one more user message, after the CLI exited before the episode was over + (scripts/harness_run.py sends the reference driver's nudge). Same env, work dir and one-time dirs; the output + is appended to the same stdout / stderr files.""" + spec = h.spec + argv = self.resume_argv(h, message) + out, err = open(spec.stdout_path, "ab"), open(spec.stderr_path, "ab") + jargv = self.jailed_argv(argv, spec.env, spec.cwd, list(spec.state_dirs.values()) + [spec.run_dir]) + h.proc = subprocess.Popen(jargv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=out, + stderr=err, start_new_session=True) + h.pid, h.exit_code, h.exit_reason = h.proc.pid, None, "" + keys = None + for _ in range(20): + keys = env_keys_of(h.pid) + if keys is not None and set(keys) == set(spec.env): + break + time.sleep(0.05) + h.info.setdefault("resumes", []).append(dict(t=time.time(), pid=h.pid, message=message, + argv=[("" if x == message else x) for x in argv], + env_observed_keys=keys)) + return h + + def wait(self, h, timeout=None): + try: + h.exit_code = h.proc.wait(timeout=timeout or h.spec.timeout_s) + h.exit_reason = "exited" if h.exit_code == 0 else f"exit code {h.exit_code}" + except subprocess.TimeoutExpired: + self.kill(h) + h.exit_reason = "timeout" + h.t_end = time.time() + return h + + @staticmethod + def kill(h): + try: + os.killpg(h.proc.pid, signal.SIGTERM) + h.exit_code = h.proc.wait(timeout=20) + except ProcessLookupError: + pass + except subprocess.TimeoutExpired: + os.killpg(h.proc.pid, signal.SIGKILL) + h.exit_code = h.proc.wait() + + def logged_argv(self, spec): + return [spec.redact_argv.get(i, a) for i, a in enumerate(spec.argv)] + + def cleanup(self, spec): + if spec.run_dir and spec.run_dir.startswith(("/tmp/lffrun/", "/tmp/lffstate/")) and os.path.isdir(spec.run_dir): + shutil.rmtree(spec.run_dir, ignore_errors=True) + for d in spec.state_dirs.values(): + if d.startswith(("/tmp/lffrun/", "/tmp/lffstate/")) and os.path.isdir(d): + shutil.rmtree(d, ignore_errors=True) + if self.jail is not None: + self.jail.close() + + +def gateway_env(log_dir): + """{LFF_GATEWAY_URL, LFF_GATEWAY_TOKEN} of the episode's tool gateway, for a framework adapter (uses_gateway) whose + process talks to it through lffbench_client (Session.from_env). harness_run.py starts the gateway right before + launch, so call this in the adapter's launch() and add it to spec.env before the process starts. The token is the + gateway's, never robot_server's.""" + d = json.load(open(os.path.join(log_dir, "gateway.json"))) + return {"LFF_GATEWAY_URL": d["url"], "LFF_GATEWAY_TOKEN": d["token"]} + + +def snapshot_tree(root): + """Relative paths of all files under root (to list what a harness left behind).""" + out = [] + for dp, dn, fn in os.walk(root): + for f in fn: + out.append(os.path.relpath(os.path.join(dp, f), root)) + return sorted(out) + + +def first_message_text(readme, status_json): + """What a native harness gets as its first user message: the reference driver's instructions (preamble + README, + byte-identical) followed by its first user turn (the status report). The reference driver sends the same two + strings as system prompt and first user message; native harnesses keep their own system prompt.""" + from .contract import tool_schemas + _, preamble = tool_schemas() + return preamble + readme + "\n\n" + "Begin. Current status (robot command `status`):\n" + status_json + + +def reference_instructions(readme): + from .contract import tool_schemas + _, preamble = tool_schemas() + return preamble + readme diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/claude_code.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/claude_code.py new file mode 100644 index 0000000000000000000000000000000000000000..fe42682aac7bf5331eba70d056ad18a2c454a470 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/claude_code.py @@ -0,0 +1,514 @@ +"""Claude Code CLI as a native harness (docs/15 §3.3; flags measured in research_notes/harness接入调研/02 §2.1). + +Two variants: + claude_code arm B : -p --bare (system prompt ~400 chars, no CLAUDE.md / auto-memory / hooks / plugins) + claude_code_full arm B': same but without --bare: Claude Code's full system prompt; still a one-time config dir and + HOME, an empty opaque work dir, --tools "" and only our MCP server +Both: process env is exactly the whitelist (env -i equivalent; plus the calling HTTP(S) proxy, base.proxy_env), +HOME / CLAUDE_CONFIG_DIR / TMPDIR are one-time dirs +under /tmp/lffstate/, the work dir is /tmp/lffrun/<12 hex> (its path is written into the system prompt), the MCP +server is scripts/mcp_robot_server.py on the run's session. + +Two ways to authenticate (auth=): + apikey ANTHROPIC_API_KEY (api_env) + oauth a Claude subscription: the long-lived token of `claude setup-token`, passed as CLAUDE_CODE_OAUTH_TOKEN + (api_env; never taken from the calling environment). claude_code_full only: --bare reads nothing but + ANTHROPIC_API_KEY / apiKeyHelper (2.1.267 --help). +Measured with 2.1.267 against the fake server (2026-10-20): the same single request in both modes, identical system +prompt, tools, messages and parameters; oauth sends Authorization: Bearer instead of x-api-key, two more beta flags +(oauth-2025-04-20, extended-cache-ttl-2025-04-11) and cache_control ttl=1h. Pins are per auth mode (pin name +claude_code_full-oauth). + +Early exit: `claude -p` ends when the model replies without a tool call, also mid-episode. scripts/harness_run.py then +sends the reference driver's nudge with `claude -p --resume ` (resume_argv), as for Codex. Hence no +--no-session-persistence: the session transcript is kept in the one-time CLAUDE_CONFIG_DIR (removed after the run); +the audit allows only this run's session. Measured against the fake server: the resumed request has the same system +prompt, tools, parameters and headers, then the earlier turns and the nudge as a user message. + +Fail-closed launch: before the real run the same argv / env is started once against a local fake Anthropic server +(free) with a schema-only MCP server; the first request's tool list, system prompt, harness-added message prefix and +request parameters are normalised and hashed, and the launch is refused unless the hash equals the pinned one +(pins/claude_code*.json, written by tests/harness_selfcheck after the self-check passed). During the real run the +stream's init event is checked again (tool list); on a mismatch the process is killed. +""" +import copy +import json +import os +import re +import shutil +import subprocess +import sys +import time + +from . import contract as C +from . import pins +from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info, + new_run_dir, proxy_env, snapshot_tree) +from .fakeapi import FakeAnthropic +from .trajectory import TrajWriter, strip_mcp + +ROOT = C.ROOT +MCP_SCRIPT = os.path.join(ROOT, "scripts", "mcp_robot_server.py") +MCP_TOOLS = ["mcp__lff__robot", "mcp__lff__shell", "mcp__lff__view_images"] +BASE_PATH = "/usr/bin:/bin" +OAUTH_KEY = "CLAUDE_CODE_OAUTH_TOKEN" +PREFLIGHT_CREDENTIAL = dict(apikey=("ANTHROPIC_API_KEY", "sk-preflight-not-a-key"), + oauth=(OAUTH_KEY, "sk-ant-oat01-" + "x" * 95 + "AA")) # dummies, only for the fake server + + +def claude_bin(): + return os.environ.get("LFF_CLAUDE_BIN") or shutil.which("claude") or "claude" + + +def _norm(s, spec): + """Remove what legitimately differs between runs from preset prompt text: paths of the one-time dirs, dates.""" + for k, v in sorted(dict(spec.state_dirs, cwd=spec.cwd).items(), key=lambda kv: -len(kv[1])): + s = s.replace(v, f"<{k.upper()}>") + s = re.sub(r"/tmp/lffrun/[0-9a-f]{12}", "", s) + s = re.sub(r"-tmp-lffrun-[0-9a-f]{12}", "", s) # auto-memory dir name derived from the cwd + s = re.sub(r"(cc_version=\d+\.\d+\.\d+)\.[0-9a-f]+", r"\1.", s) # billing header suffix varies per request + s = re.sub(r"/tmp/lffstate/[0-9a-f]{12}", "", s) + s = re.sub(r"\b20\d\d-\d\d-\d\d\b", "", s) + s = re.sub(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b", "", s) + return s + + +def request_fingerprint(body, headers, spec, first_message): + """Normalised preset part of the first request + the checks that do not need a pin.""" + problems = [] + system = body.get("system") + if isinstance(system, str): + system = [dict(type="text", text=system)] + sys_blocks = [dict(text=_norm(b.get("text", ""), spec), cache=bool(b.get("cache_control"))) for b in system or []] + tools = [dict(name=t.get("name"), description=t.get("description"), input_schema=t.get("input_schema")) + for t in body.get("tools") or []] + if [t["name"] for t in tools] != MCP_TOOLS: + problems.append(f"tool list is {[t['name'] for t in tools]}, expected {MCP_TOOLS}") + msgs = body.get("messages") or [] + first = msgs[0] if msgs else {} + content = first.get("content") + if isinstance(content, str): + content = [dict(type="text", text=content)] + prefix, found = [], False + for b in content or []: + if b.get("type") == "text" and b.get("text") == first_message: + found = True + break + prefix.append(_norm(b.get("text", "") if b.get("type") == "text" else json.dumps(b, sort_keys=True), spec)) + if not found: + problems.append("the first user message does not contain our first message byte-for-byte as one block") + params = {k: body.get(k) for k in ("model", "max_tokens", "thinking", "output_config", "context_management", + "temperature", "top_p", "top_k", "tool_choice")} + fp = dict(system=sys_blocks, tools=tools, user_prefix=prefix, params=params, + anthropic_beta=sorted((headers.get("anthropic-beta") or headers.get("Anthropic-Beta") or "").split(",")), + system_chars=sum(len(b.get("text", "")) for b in system or [])) + return fp, problems + + +class ClaudeCode(HarnessAdapter): + name = "claude_code" + bare = True + uses_mcp = True + clean_dirs = ("home", "config", "tmp") + ancestor_files = ("CLAUDE.md", "CLAUDE.local.md", ".claude", "AGENTS.md") + can_resume = True + capabilities = dict( + only_benchmark_tools=Cap("yes", "preflight", '--tools "" + --strict-mcp-config: request tools = 3 MCP tools'), + images_reach_model=Cap("yes", "probe", "MCP image content forwarded as image blocks, md5 equal"), + non_persistent_session=Cap("yes", "probe", "only this run's session (kept for -p --resume) in the one-time " + "config dir, removed after the run"), + pinned_version=Cap("yes", "launch", "claude --version + binary sha256 in harness.json; pin per version"), + machine_readable_events=Cap("yes", "stream", "--output-format stream-json --verbose"), + tool_calls_logged=Cap("yes", "stream", "tool_use / tool_result in stream + mcp_transcript + events.jsonl"), + model_and_effort=Cap("yes", "preflight", "--model / --effort; request output_config.effort checked"), + persistent_memory=Cap("absent", "probe", "--bare: no auto-memory; canaries never reach the request"), + instruction_file_injection=Cap("absent", "probe", "--bare: CLAUDE.md discovery off; canaries absent"), + web_access=Cap("absent", "preflight", "no WebFetch / WebSearch tool in the request"), + host_file_read=Cap("absent", "probe", "no Read tool; MCP shell is jailed; view_images confined"), + builtin_shell=Cap("absent", "preflight", "no Bash tool in the request"), + subagent_delegation=Cap("absent", "preflight", "no Agent / Task tool in the request"), + background_execution=Cap("absent", "preflight", "no Bash / Monitor tool in the request"), + ) + + def __init__(self, api_env=None, max_budget_usd=None, timeout_s=10800, pins_dir=None, allow_unpinned=False, + python=None, extra_args=None, jail=False, auth="apikey"): + """api_env: the only API variables passed to the harness: {"ANTHROPIC_API_KEY": ...} (auth="apikey") or + {"CLAUDE_CODE_OAUTH_TOKEN": ...} (auth="oauth", a subscription token of `claude setup-token`), optional + "ANTHROPIC_BASE_URL". Never inherited from the calling environment. jail: run the CLI in the + native-harness jail (lffbench/harnesses/jail.py; /proc stays the host's: Bun needs it).""" + if auth not in PREFLIGHT_CREDENTIAL: + raise ValueError(f"auth must be one of {sorted(PREFLIGHT_CREDENTIAL)}, not {auth!r}") + if auth == "oauth" and self.bare: + raise ValueError("claude_code (--bare) authenticates only with ANTHROPIC_API_KEY / apiKeyHelper; " + "use claude_code_full for a subscription token") + other = PREFLIGHT_CREDENTIAL["oauth" if auth == "apikey" else "apikey"][0] + if other in (api_env or {}): + raise ValueError(f"auth={auth}: api_env must not hold {other} (the CLI would use it instead)") + self.auth = auth + if jail: + from .jail import HarnessJail + self.jail = HarnessJail(claude_bin(), proc="host") + self.api_env = dict(api_env or {}) + self.proxy = proxy_env() + self.max_budget_usd = max_budget_usd + self.timeout_s = timeout_s + self.pins_dir = pins_dir + self.allow_unpinned = allow_unpinned + self.python = python or sys.executable + self.extra_args = list(extra_args or []) + self._version = None + + # ------------------------------------------------------------------------------------------------ version + def version(self): + if self._version is None: + b = claude_bin() + out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent"), capture_output=True, + text=True, timeout=60) + v = (out.stdout.strip().split() or ["?"])[0] + self._version = dict(version=v, binary=binary_info(b)) + return self._version + + def pin_key(self, ep): + v = self.version() + name = self.name if self.auth == "apikey" else f"{self.name}-{self.auth}" + return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort) + + def auth_info(self): + key = PREFLIGHT_CREDENTIAL[self.auth][0] + return dict(mode=self.auth, credential_var=key, credential_set=bool(self.api_env.get(key)), + keys=sorted(self.api_env)) + + # ------------------------------------------------------------------------------------------------ prepare + def mcp_config(self, session_path=None, describe=False): + """describe: for config_sha256 only (jailed, no relay is set up for it).""" + args = ["--session", session_path] if session_path else ["--schema-only"] + if describe or self.jail is None: + cmd, a = ("" if self.jail is not None else self.python), [MCP_SCRIPT] + args + else: + cmd, a = self.mcp_server_command(self.python, MCP_SCRIPT, args) + return {"mcpServers": {"lff": {"type": "stdio", "command": cmd, "args": a, "env": {"PATH": BASE_PATH}}}} + + def argv(self, spec_paths, ep, first_message): + a = [claude_bin(), "-p", first_message] + if self.bare: + a.append("--bare") + a += ["--tools", "", "--strict-mcp-config", "--mcp-config", spec_paths["mcp_config"], + "--allowedTools", ",".join(MCP_TOOLS), "--permission-mode", "dontAsk", "--disable-slash-commands", + "--output-format", "stream-json", "--verbose", "--model", ep.model, "--effort", ep.effort] + if self.max_budget_usd: + a += ["--max-budget-usd", str(self.max_budget_usd)] + return a + self.extra_args + + @staticmethod + def session_ids(stdout_path): + """Session ids of the init events in the stream, in order (one per launch / resume).""" + out = [] + try: + for line in open(stdout_path, encoding="utf-8", errors="replace"): + if line.startswith("{") and '"init"' in line: + d = json.loads(line) + if d.get("type") == "system" and d.get("subtype") == "init" and d.get("session_id"): + out.append(d["session_id"]) + except (OSError, ValueError): + pass + return out + + def resume_argv(self, h, message): + """`claude -p ... --resume `: the launch's flags unchanged, the message in the place of the + first message (right after -p, before the variadic --allowedTools).""" + sids = self.session_ids(h.spec.stdout_path) + if not sids: + raise HarnessRefused("resume: no session id in the stream") + a = list(h.spec.argv) + return a[:2] + [message] + a[3:] + ["--resume", sids[0]] + + def env(self, state): + # CLAUDE_CODE_DISABLE_REFUSAL_FALLBACK: measured 2026-10-21 with 2.1.299 and claude-fable-5-1: when the model's + # safeguards flag a request, the CLI otherwise answers it, and the rest of the session, with another model + # (claude-opus-4-8) under the requested model's name; with it, a flagged request ends as a refusal + # (system event model_refusal_no_fallback) and the run stays on the model under test + e = dict(PATH=BASE_PATH, HOME=state["home"], CLAUDE_CONFIG_DIR=state["config"], TMPDIR=state["tmp"], + LANG="C.UTF-8", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC="1", DISABLE_AUTOUPDATER="1", + DISABLE_TELEMETRY="1", DISABLE_ERROR_REPORTING="1", MCP_TIMEOUT="60000", MCP_TOOL_TIMEOUT="900000", + CLAUDE_CODE_DISABLE_REFUSAL_FALLBACK="1") + e.update(self.proxy) + e.update(self.api_env) + return e + + def _state_dirs(self, hexname=None): + root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate") + os.makedirs(root, exist_ok=True) + state = dict(state=root, home=os.path.join(root, "home"), config=os.path.join(root, "config"), + tmp=os.path.join(root, "tmp")) + for k in ("home", "config", "tmp"): + os.makedirs(state[k], exist_ok=True) + return state + + def prepare(self, ep, first_message, reuse_state=None): + work = new_run_dir("/tmp/lffrun") + state = reuse_state or self._state_dirs(os.path.basename(work)) + if self.jail is not None: + self.jail.stderr_dir = ep.log_dir + mcp_path = os.path.join(state["state"], "mcp.json") + with open(mcp_path, "w") as f: + json.dump(self.mcp_config(ep.session_path), f) + argv = self.argv(dict(mcp_config=mcp_path), ep, first_message) + spec = LaunchSpec(argv=argv, env=self.env(state), cwd=work, run_dir=work, state_dirs=state, + first_message=first_message, config_files=dict(mcp_config=mcp_path), + stdout_path=os.path.join(ep.log_dir, "claude_stream.jsonl"), + stderr_path=os.path.join(ep.log_dir, "claude_stderr.txt"), + redact_argv={2: f""}, + timeout_s=self.timeout_s) + return spec + + def config_sha256(self, spec, ep): + """Hash of everything configurable (argv without the first message, MCP config, env values except keys / + one-time dirs).""" + argv = [("" if a == spec.config_files["mcp_config"] else a) for a in self.logged_argv(spec)[3:]] + env = {k: (v if k not in self.api_env else "") for k, v in spec.env.items() + if k not in ("HOME", "CLAUDE_CONFIG_DIR", "TMPDIR") + PROXY_KEYS + NO_PROXY_KEYS} + return C.sha256_json(dict(argv=argv, mcp=self.mcp_config("", describe=True), env=env)) + + # ------------------------------------------------------------------------------------------------ preflight + def preflight(self, spec, ep, record_dir=None): + """Run the identical command against a fake API (free); refuse on any mismatch with the pin.""" + t0 = time.time() + fake = FakeAnthropic([[("text", "preflight ok")]], record_dir=record_dir).start() + pre_state = self._state_dirs() + try: + mcp_path = os.path.join(pre_state["state"], "mcp.json") + with open(mcp_path, "w") as f: + json.dump(self.mcp_config(None), f) + argv = self.argv(dict(mcp_config=mcp_path), ep, spec.first_message) + env = {k: v for k, v in self.env(pre_state).items() if k not in self.api_env} # no real credential + cred_key, cred_dummy = PREFLIGHT_CREDENTIAL[self.auth] + env.update({"ANTHROPIC_BASE_URL": fake.base_url, cred_key: cred_dummy}) + r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre_state.values())), env=env, cwd=spec.cwd, + stdin=subprocess.DEVNULL, capture_output=True, timeout=180) + reqs = fake.message_requests() + if not reqs: + raise HarnessRefused(f"preflight: harness sent no request (rc={r.returncode}): " + f"{r.stderr.decode('utf-8', 'replace')[-500:]}") + n, body = reqs[0] + headers = {} + if record_dir: + headers = json.load(open(os.path.join(record_dir, f"req_{n:03d}.json"))).get("headers", {}) + fp, problems = request_fingerprint(body, headers, spec, spec.first_message) + init = next((json.loads(x) for x in r.stdout.decode("utf-8", "replace").splitlines() + if x.startswith('{"type":"system"') and '"init"' in x), {}) + if init.get("tools") != MCP_TOOLS: + problems.append(f"init event tools {init.get('tools')}") + want_src = "ANTHROPIC_API_KEY" if self.auth == "apikey" else "none" # none = no API key: the OAuth token + if init.get("apiKeySource") != want_src: + problems.append(f"init apiKeySource {init.get('apiKeySource')!r}, expected {want_src!r} for " + f"auth={self.auth}") + if self.bare and "memory_paths" in init: + problems.append("init event has memory_paths under --bare") + if [s.get("status") for s in init.get("mcp_servers", [])] != ["connected"]: + problems.append(f"MCP servers {init.get('mcp_servers')}") + if os.listdir(spec.cwd): + problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}") + fp_sha = C.sha256_json(fp) + out = dict(fingerprint_sha256=fp_sha, system_chars=fp["system_chars"], n_requests=len(reqs), + tools=[t["name"] for t in fp["tools"]], effort_in_request=(fp["params"].get("output_config") + or {}).get("effort"), + model_in_request=fp["params"].get("model"), init_tools=init.get("tools"), + memory_paths=init.get("memory_paths"), dt_s=round(time.time() - t0, 1), problems=problems) + if out["effort_in_request"] != ep.effort: + problems.append(f"effort in request {out['effort_in_request']!r} != {ep.effort!r}") + pin = pins.load(self.pin_key(ep), self.pins_dir) + out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"]) + out["fingerprint"] = fp + if problems: + raise HarnessRefused("preflight: " + "; ".join(problems)) + if pin is None: + if not self.allow_unpinned: + raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck " + f"with --write-pins after the self-check passes)") + out["pin_status"] = "unpinned (allowed)" + elif pin["fingerprint_sha256"] != fp_sha: + raise HarnessRefused(f"preflight: preset prompt / tools fingerprint {fp_sha[:12]} != pinned " + f"{pin['fingerprint_sha256'][:12]} ({pin['key']})") + else: + out["pin_status"] = "match" + return out + finally: + fake.stop() + shutil.rmtree(pre_state["state"], ignore_errors=True) + + def launch(self, spec, ep, skip_preflight=False): + try: + h = super().launch(spec, ep, skip_preflight) + except HarnessRefused: + raise + # second line of defence: the init event of the real run + deadline = time.time() + 120 + while time.time() < deadline and h.proc.poll() is None: + init = self._init_event(spec) + if init is not None: + h.info["init"] = {k: init.get(k) for k in ("tools", "mcp_servers", "model", "claude_code_version", + "permissionMode", "memory_paths", "apiKeySource")} + if init.get("tools") != MCP_TOOLS: + self.kill(h) + h.exit_reason = "refused: init tools " + json.dumps(init.get("tools")) + raise HarnessRefused(h.exit_reason) + break + time.sleep(0.2) + return h + + @staticmethod + def _init_event(spec): + try: + with open(spec.stdout_path) as f: + for line in f: + if line.startswith("{"): + d = json.loads(line) + if d.get("type") == "system" and d.get("subtype") == "init": + return d + except (OSError, ValueError): + return None + return None + + # ------------------------------------------------------------------------------------------------ collect + def collect(self, h): + spec, ep = h.spec, h.ep + tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl")) + init, result, by_id, compactions, other = None, None, {}, 0, [] + inits, results = [], [] # one init / result per launch or resume + lines = open(spec.stdout_path, encoding="utf-8", errors="replace").read().splitlines() + for line in lines: + if not line.startswith("{"): + continue + d = json.loads(line) + t = d.get("type") + if t == "system" and d.get("subtype") == "init": + init = init or d + inits.append(d) + elif t == "system": + if "compact" in str(d.get("subtype", "")): + compactions += 1 + other.append(d.get("subtype")) + elif t == "assistant": + m = d.get("message") or {} + mid = m.get("id") or d.get("uuid") + st = by_id.get(mid) + if st is None: + u = m.get("usage") or {} + st = tw.add_step("agent", timestamp=d.get("timestamp"), model_name=m.get("model"), + metrics=dict(prompt_tokens=u.get("input_tokens"), + completion_tokens=u.get("output_tokens"), + cached_tokens=u.get("cache_read_input_tokens"))) + by_id[mid] = st + for b in m.get("content") or []: + if b.get("type") == "text": + st["message"] += b.get("text", "") + elif b.get("type") == "thinking": + st["reasoning_content"] += b.get("thinking", "") + elif b.get("type") == "tool_use": + st["tool_calls"].append(dict(tool_call_id=b.get("id"), function_name=strip_mcp(b.get("name")), + native_name=b.get("name"), arguments=b.get("input"))) + elif t == "user": + for b in (d.get("message") or {}).get("content") or []: + if isinstance(b, dict) and b.get("type") == "tool_result": + c = b.get("content") + texts, imgs = [], 0 + for x in (c if isinstance(c, list) else [dict(type="text", text=c)]): + if x.get("type") == "text": + texts.append(x.get("text") or "") + elif x.get("type") == "image": + imgs += 1 + tw.add_result(b.get("tool_use_id"), "\n".join(texts), bool(b.get("is_error")), imgs) + elif t == "result": + result = d + results.append(d) + v = self.version() + tw.set_header(session_id=(init or {}).get("session_id"), source=os.path.basename(spec.stdout_path), + agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort), + tools=(init or {}).get("tools")) + + def tot(key, sub=None): # summed over the segments (each resume reports its own usage) + vals = [((r.get("usage") or {}).get(key) if sub is None else r.get(key)) for r in results] + vals = [x for x in vals if isinstance(x, (int, float))] + return sum(vals) if vals else None + cost = tot("total_cost_usd", sub=True) + tw.set_final(h.exit_reason, native_result={k: (result or {}).get(k) for k in + ("subtype", "is_error", "num_turns", "duration_ms", + "duration_api_ms", "total_cost_usd", "usage", "modelUsage")}, + total_prompt_tokens=(tot("input_tokens") or 0) + (tot("cache_read_input_tokens") or 0) + + (tot("cache_creation_input_tokens") or 0), + total_completion_tokens=tot("output_tokens"), total_cached_tokens=tot("cache_read_input_tokens"), + total_cost_usd=cost, compactions=compactions, segments=len(results)) + tw.write() + h.info.update(init_full=init, inits=inits, result=result, results=results, compactions=compactions, + other_system=other, traj=tw) + return tw + + # ------------------------------------------------------------------------------------------------ audit + def audit(self, h): + spec, ep = h.spec, h.ep + init = h.info.get("init_full") or {} + tw = h.info.get("traj") + v, problems, notes = [], [], [] + inits = h.info.get("inits") or [init] + for i, x in enumerate(inits): # every launch / resume + if x.get("tools") != MCP_TOOLS: + v.append(f"init {i} tools {x.get('tools')}") + sids = sorted({x.get("session_id") for x in inits if x.get("session_id")}) + if len(sids) > 1: + v.append(f"several sessions in one run: {sids}") + if h.info.get("resumes"): + notes.append(f"resumed {len(h.info['resumes'])}x with the reference driver's nudge (CLI exited before the " + f"episode was over)") + if self.bare and init.get("memory_paths"): + v.append(f"memory_paths {init.get('memory_paths')}") + if not self.bare and init.get("memory_paths"): + mp = json.dumps(init.get("memory_paths")) + if spec.state_dirs["state"] not in mp and spec.cwd not in mp: + v.append(f"memory_paths outside the one-time dirs: {mp}") + notes.append("full variant: memory_paths point into the one-time dirs (empty at start)") + names = [tc.get("native_name") for st in (tw.steps if tw else []) for tc in st["tool_calls"]] + bad = sorted({n for n in names if n not in MCP_TOOLS}) + if bad: + notes.append(f"model asked for unavailable tools (all rejected by the harness): {bad}") + if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env): + v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}") + left = dict(config=snapshot_tree(spec.state_dirs["config"]), home=snapshot_tree(spec.state_dirs["home"]), + work=snapshot_tree(spec.cwd)) + mcp_logs = [p for p in left["home"] if "/mcp-logs-" in p] + own = [p for p in left["config"] if sids and p.startswith("projects/") + and (p.endswith(f"/{sids[0]}.jsonl") or f"/{sids[0]}/" in p)] # this run's session (for --resume) + transcripts = [p for p in left["config"] + left["home"] if p.endswith(".jsonl") and p not in mcp_logs + and p not in own] + if transcripts: + v.append(f"session transcripts other than this run's session: {transcripts}") + if own: + notes.append(f"this run's own session kept in the one-time config dir (for --resume): {own}") + if mcp_logs: # MCP connection log of the CLI in the one-time HOME (removed after the run, never read back) + notes.append(f"Claude Code wrote its MCP log into the one-time HOME: {mcp_logs}") + if left["work"]: + v.append(f"files in the work dir: {left['work']}") + mcp_env = None + mt = os.path.join(ep.log_dir, "mcp_transcript.jsonl") + if os.path.exists(mt): + for line in open(mt): + d = json.loads(line) + if d.get("ev") == "start" and "env_keys" in d: + mcp_env = d["env_keys"] + out = dict(harness=self.name, violations=v, problems=problems, notes=notes, files_left=left, + mcp_server_env_keys=mcp_env, compactions=h.info.get("compactions"), + init={k: init.get(k) for k in ("tools", "mcp_servers", "model", "claude_code_version", + "permissionMode", "memory_paths", "apiKeySource")}, + tool_calls=len(names), unavailable_tool_requests=bad, ok=not v) + with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f: + json.dump(out, f, indent=1) + return out + + +class ClaudeCodeFull(ClaudeCode): + name = "claude_code_full" + bare = False + capabilities = dict(ClaudeCode.capabilities, + persistent_memory=Cap("partial", "probe", "auto-memory is on in the harness, but its dirs are " + "one-time and empty; canaries outside them never reach the request"), + instruction_file_injection=Cap("partial", "probe", "CLAUDE.md discovery is on, but work / " + "config / home are empty one-time dirs; canaries outside absent")) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/codex.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/codex.py new file mode 100644 index 0000000000000000000000000000000000000000..2dcd24af9049dce03412aada22b21da366bd5ac9 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/codex.py @@ -0,0 +1,688 @@ +"""Codex CLI as a native harness (arm F; flags measured in research_notes/harness接入调研/02 §2.3, Codex 0.156). + +Launch: process env exactly the whitelist (env -i equivalent), a brand-new empty CODEX_HOME and HOME (one-time, under +/tmp/lffstate/), work dir /tmp/lffrun/<12 hex>, `codex exec --json --skip-git-repo-check --ignore-user-config +--ignore-rules -s read-only`, ~20 features disabled, project docs / permissions / environment context / +collaboration-mode / skills instructions off, web search off, and only our MCP server with +default_tools_approval_mode="approve" (otherwise exec mode silently denies MCP calls). + +Early exit: `codex exec` ends when the model replies without a tool call, also when the episode is not over (measured +2026-10-19, cx_pilot6b: gpt-6-astra stopped after a failed first attempt, "I stopped after the one authorized +attempt", although the finish reply said attempt 2 of 3 starts now). scripts/harness_run.py then sends the reference +driver's nudge as a user turn with `codex exec resume ` (resume_argv), at most api_player.MAX_NO_TOOL times in +a row. Hence no --ephemeral: the session is kept in the one-time CODEX_HOME (memories off; removed after the run). +Measured with 0.163 against the fake server: the resumed request has the same developer messages, tools, model and +parameters as the first, then the earlier turns and the nudge as a user message. + +The model API is a custom Responses provider "lffapi", so the preflight can point exactly the same config at a local +fake server by changing only base_url. Two ways to authenticate (auth=): + apikey env_key OPENAI_API_KEY (api_env), default endpoint the official API + chatgpt a ChatGPT subscription login (no API key; same as RPent's codex planner reusing `codex login`): the + provider gets requires_openai_auth=true (requests carry the login's bearer + chatgpt-account-id), default + endpoint the ChatGPT Codex backend; a copy of auth.json from the source CODEX_HOME is put into the one-time + CODEX_HOME (the only file allowed there at launch). If Codex refreshes the login during a run, the refreshed + auth.json is written back to the source (refresh tokens rotate), unless the source changed meanwhile. + Launch is refused when the source login is close to its refresh (parallel copies would each rotate it). +Measured with 0.163 against the fake server: same body keys and headers in both modes plus chatgpt-account-id; the +preset differs (exec tool description), so pins are per auth mode (pin name codex-chatgpt). +The calling environment's HTTP(S) proxy is passed through (base.proxy_env; NO_PROXY = loopback only). + +Model configuration (catalog=, user 2026-10-20): Codex picks the system prompt, tool form and context window per +model from its model catalog. We always pass an explicit model_catalog_json written into the one-time CODEX_HOME, so +nothing depends on the catalog the subscription backend serves on the day: + generic (main table, every model) one entry built from codex_catalogs/generic_.json: what Codex sends for a + model it has no entry for (its generic Codex CLI prompt, plain function tools, no code mode); per model only + slug, input modalities and reasoning levels. Measured with 0.163 against the fake server: the request equals + the no-catalog fallback for an unknown slug apart from message ids. + native (control) codex_catalogs/native_.json = `codex debug models --bundled` of that binary: the request + equals the one without any catalog (GPT: code mode, its own prompt). The pins of before 10-20 stay valid. +Pins are per catalog (pin name codex[-chatgpt][-generic]). + +Known, accepted differences in native (code mode) catalogs (reported, not fixable by config in 0.156): + - code mode: the model sees one `exec` tool (JavaScript in a V8 isolate without fs / network); our tools are nested + and listed only in ALL_TOOLS; MCP images reach the model only if the model's JS calls image(...) + - apply_patch (blocked by the read-only sandbox), clock, 3 MCP-resource tools (our server has no resources), + request_user_input, and 6 collaboration.* sub-agent tools cannot be removed; a sub-agent call is an audit violation + - --json has tokens but no dollar cost +Fail-closed launch: the preflight checks the top-level tools, the exec nested-tool list (ALL_TOOLS, printed by a +scripted exec call), the developer (preset) messages and request parameters against the pin. +""" +import base64 +import datetime +import fcntl +import json +import os +import re +import shutil +import sqlite3 +import subprocess +import sys +import time + +from . import contract as C +from . import pins +from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info, + new_run_dir, proxy_env, snapshot_tree) +from .fakeapi import FakeResponses +from .trajectory import TrajWriter + +ROOT = C.ROOT +MCP_SCRIPT = os.path.join(ROOT, "scripts", "mcp_robot_server.py") +BASE_PATH = "/usr/bin:/bin" +OFFICIAL_API = "https://api.openai.com/v1" +CHATGPT_BACKEND = "https://chatgpt.com/backend-api/codex" +AUTH_FILE = "auth.json" +AUTH_LOCK = "/tmp/lffstate/.codex_auth.lock" +MAX_LOGIN_AGE_H = 8 * 24 # codex-rs TOKEN_REFRESH_INTERVAL (8 days, from the source, not measured here): a login + # older than this is refreshed at start, by every parallel copy +MIN_ACCESS_LEFT_H = 24 # an access token expiring during a run makes the run's copy refresh it + + +def _jwt_claims(tok): + try: + p = tok.split(".")[1] + return json.loads(base64.urlsafe_b64decode(p + "=" * (-len(p) % 4))) + except (IndexError, ValueError, AttributeError): + return {} + + +def chatgpt_login_status(home): + """-> dict(ok, problem, last_refresh_h, access_token_valid_h) of the ChatGPT login in home/auth.json. No secret + leaves this function.""" + src = os.path.join(home, AUTH_FILE) + try: + with open(src) as f: + a = json.load(f) + except (OSError, ValueError) as e: + return dict(ok=False, problem=f"cannot read {src}: {type(e).__name__}") + tok = a.get("tokens") or {} + if a.get("auth_mode") != "chatgpt" or not tok.get("access_token") or not tok.get("refresh_token"): + return dict(ok=False, problem=f"{src} is not a ChatGPT login (auth_mode={a.get('auth_mode')!r})") + now = time.time() + try: + lr_text = re.sub(r"(\.\d{6})\d+", r"\1", str(a.get("last_refresh"))) + lr = datetime.datetime.fromisoformat(lr_text.replace("Z", "+00:00")).timestamp() + age_h = (now - lr) / 3600 + except ValueError: + age_h = float("inf") + left_h = (float(_jwt_claims(tok["access_token"]).get("exp") or 0) - now) / 3600 + out = dict(ok=True, problem=None, last_refresh_h=round(age_h, 1), access_token_valid_h=round(left_h, 1)) + if age_h >= MAX_LOGIN_AGE_H or left_h < MIN_ACCESS_LEFT_H: + out.update(ok=False, problem=f"the ChatGPT login in {home} is due for a refresh (last refresh {age_h:.0f} h ago, " + f"access token valid {left_h:.0f} h): refresh it once outside the benchmark (use " + f"codex with CODEX_HOME={home}), so that parallel runs do not each rotate it") + return out +DISABLE = ["shell_tool", "unified_exec", "view_image", "multi_agent", "multi_agent_v2", "apps", "browser_use", + "browser_use_external", "computer_use", "image_generation", "plugins", "hooks", "skill_search", + "tool_suggest", "goals", "sleep_tool", "in_app_browser", "memories", "skill_mcp_dependency_install", + "realtime_conversation"] +# what remains in 0.156 after the lock-down (measured): anything else is refused at launch +EXPECTED_TOP = ["collaboration.followup_task", "collaboration.interrupt_agent", "collaboration.list_agents", + "collaboration.send_message", "collaboration.spawn_agent", "collaboration.wait_agent", + "functions.exec", "functions.request_user_input", "functions.request_user_input_async", + "functions.wait"] +EXPECTED_ALL_TOOLS = ["apply_patch", "clock__curr_time", "list_mcp_resource_templates", "list_mcp_resources", + "mcp__lff__robot", "mcp__lff__shell", "mcp__lff__view_images", "read_mcp_resource"] +# generic catalog (no code mode), measured with 0.163: our tools are plain functions in the mcp__lff namespace +EXPECTED_TOP_GENERIC = ["list_mcp_resource_templates", "list_mcp_resources", "mcp__lff.robot", "mcp__lff.shell", + "mcp__lff.view_images", "read_mcp_resource", "request_user_input"] +CATALOG_DIR = os.path.join(ROOT, "lffbench", "harnesses", "codex_catalogs") +CATALOG_FILE = "lff_model_catalog.json" # written into the one-time CODEX_HOME before launch +CATALOGS = ("generic", "native") +# generic catalog: the per-model fields (input modalities; the run's reasoning level is always listed) +TEXT_ONLY_MODELS = {"deepseek-v4-pro": ["text"]} # DeepSeek's Codex guide (read 2026-10-20): v4-pro takes no images +DEEPSEEK_URL = "https://api.deepseek.com/" # same guide: base_url, wire_api = "responses" +OPENCODE_GO_URL = "https://opencode.ai/inference/go/openai/v1" # OpenCode Go, Responses API (checked 2026-10-29) +MCP_TOOLS = ["robot", "shell", "view_images"] +OK_ITEMS = ("agent_message", "reasoning", "mcp_tool_call", "error") +PREFLIGHT_JS = "text(JSON.stringify(ALL_TOOLS));" + + +def codex_bin(): + return os.environ.get("LFF_CODEX_BIN") or shutil.which("codex") or "codex" + + +def toml_str(s): + return json.dumps(s) # a JSON string literal is a valid TOML basic string + + +def _norm(s, cwd): + s = s.replace(cwd, "") + s = re.sub(r"/tmp/lffrun/[0-9a-f]{12}", "", s) + s = re.sub(r"/tmp/lffstate/[0-9a-f]{12}", "", s) + s = re.sub(r"\b20\d\d-\d\d-\d\d\b", "", s) + s = re.sub(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b", "", s) + return s + + +def _walk_tools(ts, prefix=""): + out = [] + for t in ts or []: + if t.get("type") == "namespace": + out += _walk_tools(t.get("tools"), prefix + t.get("name", "") + ".") + else: + out.append(dict(name=prefix + (t.get("name") or t.get("type") or "?"), type=t.get("type"), + description=t.get("description"), parameters=t.get("parameters"), format=t.get("format"))) + return out + + +def request_fingerprint(body, cwd, first_message, expected_top=None): + problems = [] + items = body.get("input") or [] + top = _walk_tools(body.get("tools")) + dev, users = [], [] + for it in items: + if it.get("type") == "additional_tools": + top += _walk_tools(it.get("tools")) + elif it.get("type") == "message" and it.get("role") in ("developer", "system"): + dev.append(_norm("\n".join(c.get("text", "") for c in it.get("content") or []), cwd)) + elif it.get("type") == "message" and it.get("role") == "user": + users.append(it) + names = sorted(t["name"] for t in top) + expected_top = EXPECTED_TOP if expected_top is None else expected_top + if names != expected_top: + problems.append(f"top-level tools {names} != expected {expected_top}") + texts = [c.get("text") for u in users for c in u.get("content") or []] + if texts != [first_message]: + problems.append(f"user input is not exactly our first message ({len(texts)} user text blocks)") + for t in top: + if t.get("description"): + t["description"] = _norm(t["description"], cwd) + params = {k: body.get(k) for k in ("model", "reasoning", "parallel_tool_calls", "store", "include", "text", + "tool_choice", "instructions", "max_output_tokens", "temperature")} + meta = body.get("client_metadata") or {} + try: + turn_meta = json.loads(meta.get("x-codex-turn-metadata") or "{}") + except ValueError: + turn_meta = {} + sandbox = {k: turn_meta.get(k) for k in ("sandbox", "sandbox_mode")} + if sandbox.get("sandbox_mode") != "read-only": + problems.append(f"sandbox {sandbox}") + fp = dict(tools=sorted(top, key=lambda t: t["name"]), developer=dev, params=params, sandbox=sandbox, + developer_chars=sum(len(d) for d in dev)) + return fp, problems + + +def model_catalog(mode, version, model, modalities=None, effort=None): + """-> (catalog dict for model_catalog_json, source file). Refuses (fail-closed) when the version has no catalog + file or, for native, when the model has no entry.""" + if mode not in CATALOGS: + raise ValueError(f"catalog must be one of {CATALOGS}, not {mode!r}") + src = os.path.join(CATALOG_DIR, f"{mode}_{version}.json") + if not os.path.exists(src): + raise HarnessRefused(f"no {mode} model catalog for Codex {version} ({os.path.relpath(src, ROOT)})") + d = json.load(open(src)) + if mode == "native": + if not any(m.get("slug") == model for m in d.get("models") or []): + raise HarnessRefused(f"native catalog {os.path.basename(src)} has no entry for {model}") + return d, src + e = dict(d["entry"], slug=model, display_name=model) + modalities = modalities or TEXT_ONLY_MODELS.get(model) + if modalities: + e["input_modalities"] = list(modalities) + levels = [dict(x) for x in e.get("supported_reasoning_levels") or []] + if effort and effort not in [x.get("effort") for x in levels]: + levels.append(dict(effort=effort, description=effort)) + e["supported_reasoning_levels"] = levels + return dict(models=[e]), src + + +def all_tools_from(body): + """The ALL_TOOLS list printed by the preflight exec call (in the second request).""" + for it in body.get("input") or []: + if it.get("type") == "custom_tool_call_output": + out = it.get("output") + parts = out if isinstance(out, list) else [dict(text=out)] + for p in parts: + t = (p.get("text") or "").strip() + if t.startswith("["): + try: + return json.loads(t) + except ValueError: + pass + return None + + +class Codex(HarnessAdapter): + name = "codex" + uses_mcp = True + can_resume = True + clean_dirs = ("home", "codex_home", "tmp") + ancestor_files = ("AGENTS.md", "AGENTS.override.md", ".codex") + capabilities = dict( + only_benchmark_tools=Cap("partial", "preflight", "generic catalog: our 3 MCP tools as functions + residual " + "resource×3 / request_user_input; native (code mode): reachable only via exec(JS), " + "residual apply_patch(blocked) / clock / resource×3 / request_user_input / " + "collaboration×6"), + images_reach_model=Cap("partial", "probe", "generic: MCP images go to the model; native (code mode): only if " + "the model's JS calls image(); bytes unchanged either way"), + non_persistent_session=Cap("yes", "probe", "only this run's thread, in the one-time CODEX_HOME (for exec " + "resume), removed after the run; memories off"), + pinned_version=Cap("yes", "launch", "codex --version + binary sha256 in harness.json; pin per version"), + machine_readable_events=Cap("yes", "stream", "exec --json (items + usage, no cost)"), + tool_calls_logged=Cap("yes", "stream", "mcp_tool_call items + mcp_transcript + events.jsonl"), + model_and_effort=Cap("yes", "preflight", "-m / model_reasoning_effort; request reasoning.effort checked"), + persistent_memory=Cap("absent", "probe", "memories feature off; empty one-time CODEX_HOME; canaries absent"), + instruction_file_injection=Cap("absent", "probe", "project_doc_max_bytes=0 + empty CODEX_HOME (AGENTS.md)"), + web_access=Cap("absent", "probe", "web_search disabled; exec isolate has no fetch"), + host_file_read=Cap("absent", "probe", "shell / unified_exec / view_image off; exec has no require; " + "read-only sandbox"), + builtin_shell=Cap("absent", "preflight", "shell_tool and unified_exec disabled (not in the tool list)"), + subagent_delegation=Cap("partial", "preflight", "collaboration.* tools cannot be disabled in 0.156; any use " + "is an audit violation"), + background_execution=Cap("partial", "preflight", "functions.wait / long exec yields exist; audited"), + ) + + def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False, + python=None, extra_args=None, jail=False, auth="apikey", auth_home=None, catalog="generic", + modalities=None): + """api_env: {"OPENAI_API_KEY": ...} (the provider's env_key, auth="apikey"); base_url: Responses endpoint + (default: official API / ChatGPT Codex backend by auth). auth="chatgpt": a ChatGPT login copied from + auth_home (default LFF_CODEX_AUTH_HOME, else the calling CODEX_HOME, else ~/.codex), no API key. + jail: run the CLI in the native-harness jail (lffbench/harnesses/jail.py, static /proc). + catalog: "generic" (shared configuration of the main table) or "native" (Codex's own entry for the model); + modalities: input modalities of a generic entry (default text + image).""" + if catalog not in CATALOGS: + raise ValueError(f"catalog must be one of {CATALOGS}, not {catalog!r}") + self.catalog, self.modalities = catalog, (list(modalities) if modalities else None) + self._catalog_sha = {} # one-time CODEX_HOME -> sha256 of the catalog written there + if auth not in ("apikey", "chatgpt"): + raise ValueError(f"auth must be apikey or chatgpt, not {auth!r}") + if jail: + from .jail import HarnessJail + self.jail = HarnessJail(codex_bin(), proc="static") + self.auth = auth + self.auth_home = None + self._auth_copies = {} # one-time CODEX_HOME -> sha256 of the auth.json copied into it + if auth == "chatgpt": + self.auth_home = os.path.abspath(auth_home or os.environ.get("LFF_CODEX_AUTH_HOME") + or os.environ.get("CODEX_HOME") or os.path.expanduser("~/.codex")) + self.clean_allowed = {"codex_home": ((AUTH_FILE,) if auth == "chatgpt" else ()) + (CATALOG_FILE,)} + self.api_env = dict(api_env or {}) if auth == "apikey" else {} + self.base_url = base_url or (OFFICIAL_API if auth == "apikey" else CHATGPT_BACKEND) + self.proxy = proxy_env() + self.timeout_s = timeout_s + self.pins_dir = pins_dir + self.allow_unpinned = allow_unpinned + self.python = python or sys.executable + self.extra_args = list(extra_args or []) + self._version = None + + # ------------------------------------------------------------------------------------------------ auth + def auth_info(self): + if self.auth == "apikey": + return dict(mode="apikey", keys=sorted(self.api_env)) + st = chatgpt_login_status(self.auth_home) + return dict(mode="chatgpt", source=self.auth_home, **{k: v for k, v in st.items() if k != "ok"}) + + def config_info(self): + """For harness.json: which model catalog the run used.""" + return dict(catalog=self.catalog, modalities=self.modalities) + + def _install_catalog(self, codex_home, ep): + """Write the run's model catalog into the one-time CODEX_HOME (the only file besides auth.json allowed there + at launch). -> (path, sha256, source file, code mode).""" + cat, src = model_catalog(self.catalog, self.version()["version"], ep.model, self.modalities, ep.effort) + path = os.path.join(codex_home, CATALOG_FILE) + with open(path, "w") as f: + json.dump(cat, f) + sha = C.sha256_file(path) + self._catalog_sha[codex_home] = sha + entry = next(m for m in cat["models"] if m.get("slug") == ep.model) + return path, sha, os.path.relpath(src, ROOT), entry.get("tool_mode") == "code_mode_only" + + def _install_auth(self, codex_home): + """auth="chatgpt": copy the source login into a one-time CODEX_HOME (refused if it is due for a refresh).""" + if self.auth != "chatgpt": + return + st = chatgpt_login_status(self.auth_home) + if not st["ok"]: + raise HarnessRefused("ChatGPT login: " + st["problem"]) + dst = os.path.join(codex_home, AUTH_FILE) + with open(os.path.join(self.auth_home, AUTH_FILE), "rb") as f: + data = f.read() + fd = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "wb") as f: + f.write(data) + self._auth_copies[codex_home] = C.sha256_file(dst) + + def _sync_auth_back(self, codex_home): + """After a run: if Codex refreshed the login in the run's copy, write it back to the source (refresh tokens + rotate, the source's old one may no longer work), unless the source changed since the copy. -> note or None.""" + copied = self._auth_copies.pop(codex_home, None) + p = os.path.join(codex_home, AUTH_FILE) + if copied is None or not os.path.exists(p) or C.sha256_file(p) == copied: + return None + try: + with open(p, "rb") as f: + data = f.read() + new = json.loads(data) + except (OSError, ValueError): + return "auth.json in the run's CODEX_HOME changed and is unreadable: not written back" + if new.get("auth_mode") != "chatgpt" or not (new.get("tokens") or {}).get("refresh_token"): + return "auth.json in the run's CODEX_HOME changed but holds no ChatGPT login: not written back" + src = os.path.join(self.auth_home, AUTH_FILE) + os.makedirs(os.path.dirname(AUTH_LOCK), exist_ok=True) + with open(AUTH_LOCK, "a") as lk: + fcntl.flock(lk, fcntl.LOCK_EX) + if C.sha256_file(src) != copied: + return "the run refreshed its login copy, but the source auth.json changed meanwhile: not written back" + tmp = src + ".lff-tmp" + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "wb") as f: + f.write(data) + os.replace(tmp, src) + return "the run refreshed the ChatGPT login: refreshed auth.json written back to the source" + + def version(self): + if self._version is None: + b = codex_bin() + out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent", + CODEX_HOME="/nonexistent"), + capture_output=True, text=True, timeout=60) + v = (out.stdout.strip().split() or ["?"])[-1] + self._version = dict(version=v, binary=binary_info(b)) + return self._version + + def pin_key(self, ep): + v = self.version() + name = self.name if self.auth == "apikey" else f"{self.name}-{self.auth}" + name += "" if self.catalog == "native" else f"-{self.catalog}" + return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort) + + # ------------------------------------------------------------------------------------------------ prepare + def config_args(self, ep, session_path, base_url, codex_home): + mcp_cmd, mcp_args = self.mcp_server_command(self.python, MCP_SCRIPT, ["--session", session_path] if session_path + else ["--schema-only"]) + c = ["model_reasoning_effort=" + toml_str(ep.effort), + "project_doc_max_bytes=0", "include_permissions_instructions=false", "include_environment_context=false", + "include_collaboration_mode_instructions=false", "skills.include_instructions=false", + "skills.bundled.enabled=false", 'web_search="disabled"', + 'model_provider="lffapi"', 'model_providers.lffapi.name="lffapi"', + "model_providers.lffapi.base_url=" + toml_str(base_url), 'model_providers.lffapi.wire_api="responses"', + ('model_providers.lffapi.env_key="OPENAI_API_KEY"' if self.auth == "apikey" + else "model_providers.lffapi.requires_openai_auth=true"), + "mcp_servers.lff.command=" + toml_str(mcp_cmd), + "mcp_servers.lff.args=[" + ",".join(toml_str(x) for x in mcp_args) + "]", + "mcp_servers.lff.env={PATH=" + toml_str(BASE_PATH) + "}", + 'mcp_servers.lff.enabled_tools=["robot","shell","view_images"]', + 'mcp_servers.lff.default_tools_approval_mode="approve"', "mcp_servers.lff.required=true", + "mcp_servers.lff.startup_timeout_sec=60", "mcp_servers.lff.tool_timeout_sec=900", + "model_catalog_json=" + toml_str(os.path.join(codex_home, CATALOG_FILE))] + return c + + def argv(self, ep, session_path, base_url, first_message, codex_home): + a = [codex_bin(), "exec", "--json", "--skip-git-repo-check", "--ignore-user-config", + "--ignore-rules", "-s", "read-only", "-m", ep.model] + for f in DISABLE: + a += ["--disable", f] + for c in self.config_args(ep, session_path, base_url, codex_home): + a += ["-c", c] + return a + self.extra_args + [first_message] + + @staticmethod + def thread_id(stdout_path): + t = None + for line in open(stdout_path, encoding="utf-8", errors="replace"): + if line.startswith("{") and '"thread.started"' in line: + t = json.loads(line).get("thread_id") or t + return t + + def resume_argv(self, h, message): + """`codex exec resume ` with the launch's flags and config; resume has no -s, so the + sandbox goes in as sandbox_mode.""" + thread = self.thread_id(h.spec.stdout_path) + if not thread: + raise HarnessRefused("resume: no thread id in the event stream") + a = list(h.spec.argv[:-1]) # without the first message + i = a.index("exec") + rest = a[i + 1:] + j = rest.index("-s") + mode = rest[j + 1] + del rest[j:j + 2] + return a[:i + 1] + ["resume"] + rest + ["-c", "sandbox_mode=" + toml_str(mode), thread, message] + + def env(self, state): + e = dict(PATH=BASE_PATH, HOME=state["home"], CODEX_HOME=state["codex_home"], TMPDIR=state["tmp"], + LANG="C.UTF-8") + e.update(self.proxy) + e.update(self.api_env) + return e + + def _state_dirs(self, hexname=None): + root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate") + os.makedirs(root, exist_ok=True) + state = dict(state=root, home=os.path.join(root, "home"), codex_home=os.path.join(root, "codex_home"), + tmp=os.path.join(root, "tmp")) + for k in ("home", "codex_home", "tmp"): + os.makedirs(state[k], exist_ok=True) + return state + + def prepare(self, ep, first_message, reuse_state=None): + work = new_run_dir("/tmp/lffrun") + state = reuse_state or self._state_dirs(os.path.basename(work)) + if self.jail is not None: + self.jail.stderr_dir = ep.log_dir + if not reuse_state and os.listdir(state["codex_home"]): + raise HarnessRefused("CODEX_HOME is not empty") + cat_path, cat_sha, cat_src, code_mode = self._install_catalog(state["codex_home"], ep) + argv = self.argv(ep, ep.session_path, self.base_url, first_message, state["codex_home"]) + return LaunchSpec(argv=argv, env=self.env(state), cwd=work, run_dir=work, state_dirs=state, + first_message=first_message, stdout_path=os.path.join(ep.log_dir, "codex_events.jsonl"), + stderr_path=os.path.join(ep.log_dir, "codex_stderr.txt"), + redact_argv={len(argv) - 1: f""}, + config_files=dict(model_catalog_json=dict(path=cat_path, sha256=cat_sha, source=cat_src, + catalog=self.catalog, code_mode=code_mode)), + timeout_s=self.timeout_s) + + def launch(self, spec, ep, skip_preflight=False): + self._install_auth(spec.state_dirs["codex_home"]) + return super().launch(spec, ep, skip_preflight=skip_preflight) + + def cleanup(self, spec): + self._sync_auth_back(spec.state_dirs.get("codex_home", "")) + super().cleanup(spec) + + def config_sha256(self, spec, ep): + """Hash of everything configurable (argv without the first message, env values except keys / one-time dirs).""" + argv = [re.sub(r"/tmp/lffsock/[0-9a-f]{12}/[^\"\],]+", "", a.replace(ep.session_path, "")) + .replace(spec.state_dirs["codex_home"], "") for a in self.logged_argv(spec)[1:-1]] + env = {k: (v if k not in self.api_env else "") for k, v in spec.env.items() + if k not in ("HOME", "CODEX_HOME", "TMPDIR") + PROXY_KEYS + NO_PROXY_KEYS} + cat = (spec.config_files.get("model_catalog_json") or {}).get("sha256") + return C.sha256_json(dict(argv=argv, env=env, model_catalog_sha256=cat)) + + # ------------------------------------------------------------------------------------------------ preflight + def preflight(self, spec, ep, record_dir=None): + t0 = time.time() + code_mode = (spec.config_files.get("model_catalog_json") or {}).get("code_mode", True) + script = [[("exec", PREFLIGHT_JS)], [("text", "preflight ok")]] if code_mode else [[("text", "preflight ok")]] + fake = FakeResponses(script, record_dir=record_dir).start() + pre = self._state_dirs() + try: + self._install_auth(pre["codex_home"]) + self._install_catalog(pre["codex_home"], ep) + argv = self.argv(ep, None, fake.base_url, spec.first_message, pre["codex_home"]) + env = self.env(pre) + if self.auth == "apikey": + env["OPENAI_API_KEY"] = "sk-preflight-not-a-key" + r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd, + stdin=subprocess.DEVNULL, capture_output=True, timeout=180) + reqs = fake.model_requests() + if len(reqs) < (2 if code_mode else 1): + raise HarnessRefused(f"preflight: {len(reqs)} model requests (rc={r.returncode}): " + f"{r.stderr.decode('utf-8', 'replace')[-800:]}") + fp, problems = request_fingerprint(reqs[0][1], spec.cwd, spec.first_message, + EXPECTED_TOP if code_mode else EXPECTED_TOP_GENERIC) + at_names = None + if code_mode: # our tools are nested in exec: the scripted exec call prints them + at = all_tools_from(reqs[1][1]) + if at is None: + problems.append("exec preflight did not print ALL_TOOLS") + at = [] + at_names = sorted(t.get("name") if isinstance(t, dict) else str(t) for t in at) + if at_names != EXPECTED_ALL_TOOLS: + problems.append(f"ALL_TOOLS {at_names} != expected {EXPECTED_ALL_TOOLS}") + fp["all_tools"] = [({k: (_norm(v, spec.cwd) if isinstance(v, str) else v) for k, v in t.items()} + if isinstance(t, dict) else t) for t in sorted(at, key=lambda t: json.dumps(t))] + effort = (fp["params"].get("reasoning") or {}).get("effort") + if effort != ep.effort: + problems.append(f"reasoning.effort in request {effort!r} != {ep.effort!r}") + if os.listdir(spec.cwd): + problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}") + fp_sha = C.sha256_json(fp) + out = dict(fingerprint_sha256=fp_sha, developer_chars=fp["developer_chars"], n_requests=len(reqs), + top_tools=[t["name"] for t in fp["tools"]], all_tools=at_names, code_mode=code_mode, + catalog=self.catalog, effort_in_request=effort, + model_in_request=fp["params"].get("model"), sandbox=fp["sandbox"], dt_s=round(time.time() - t0, 1), + problems=problems) + pin = pins.load(self.pin_key(ep), self.pins_dir) + out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"]) + out["fingerprint"] = fp + if problems: + raise HarnessRefused("preflight: " + "; ".join(problems)) + if pin is None: + if not self.allow_unpinned: + raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck " + f"with --write-pins after the self-check passes)") + out["pin_status"] = "unpinned (allowed)" + elif pin["fingerprint_sha256"] != fp_sha: + raise HarnessRefused(f"preflight: preset prompt / tools fingerprint {fp_sha[:12]} != pinned " + f"{pin['fingerprint_sha256'][:12]} ({pin['key']})") + else: + out["pin_status"] = "match" + return out + finally: + fake.stop() + self._sync_auth_back(pre["codex_home"]) + shutil.rmtree(pre["state"], ignore_errors=True) + + # ------------------------------------------------------------------------------------------------ collect + def collect(self, h): + spec, ep = h.spec, h.ep + tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl")) + thread, usage, items, errors = None, dict(input=0, cached=0, output=0, reasoning=0), [], [] + for line in open(spec.stdout_path, encoding="utf-8", errors="replace"): + if not line.startswith("{"): + continue + d = json.loads(line) + t = d.get("type") + if t == "thread.started": + thread = d.get("thread_id") + elif t == "turn.completed": + u = d.get("usage") or {} + usage["input"] += u.get("input_tokens") or 0 + usage["cached"] += u.get("cached_input_tokens") or 0 + usage["output"] += u.get("output_tokens") or 0 + usage["reasoning"] += u.get("reasoning_output_tokens") or 0 + elif t in ("error", "turn.failed"): + errors.append(d) + elif t == "item.completed": + it = d.get("item") or {} + items.append(it.get("type")) + if it.get("type") == "agent_message": + tw.add_step("agent", message=it.get("text", "")) + elif it.get("type") == "reasoning": + tw.add_step("agent", reasoning=it.get("text", "")) + else: + name = it.get("tool") if it.get("type") == "mcp_tool_call" else it.get("type") + args = it.get("arguments") if it.get("type") == "mcp_tool_call" else { + k: v for k, v in it.items() if k not in ("id", "type", "status")} + st = tw.add_step("agent", tool_calls=[dict(tool_call_id=it.get("id"), function_name=name, + native_name=f"{it.get('server', '')}.{name}" + if it.get("type") == "mcp_tool_call" else name, + item_type=it.get("type"), arguments=args)]) + res = it.get("result") or {} + texts = [c.get("text", "") for c in res.get("content") or [] if c.get("type") == "text"] + imgs = sum(1 for c in res.get("content") or [] if c.get("type") == "image") + tw.add_result(it.get("id"), "\n".join(texts) if texts else json.dumps(it.get("error")), + bool(it.get("error")) or it.get("status") == "failed", imgs) + del st + v = self.version() + tw.set_header(session_id=thread, source=os.path.basename(spec.stdout_path), + agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort), + tools=EXPECTED_ALL_TOOLS if (spec.config_files.get("model_catalog_json") or {}).get( + "code_mode", True) else EXPECTED_TOP_GENERIC) + tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], item_types=sorted(set(items))), + total_prompt_tokens=usage["input"], total_completion_tokens=usage["output"], + total_cached_tokens=usage["cached"], total_cost_usd=None, reasoning_tokens=usage["reasoning"]) + tw.write() + h.info.update(items=items, traj=tw, thread=thread, errors=errors) + return tw + + # ------------------------------------------------------------------------------------------------ audit + @staticmethod + def sqlite_rows(path, table): + """Row count of `table`, read from a copy (the db may be in WAL mode and still open).""" + import tempfile + try: + with tempfile.TemporaryDirectory() as td: + for suf in ("", "-wal", "-shm"): + if os.path.exists(path + suf): + shutil.copy(path + suf, os.path.join(td, "db.sqlite" + suf)) + con = sqlite3.connect(os.path.join(td, "db.sqlite")) + n = con.execute(f"select count(*) from {table}").fetchone()[0] + con.close() + return n + except (sqlite3.Error, OSError) as e: + return f"n/a ({e})" + + def audit(self, h): + spec, ep = h.spec, h.ep + v, notes = [], [] + items = h.info.get("items") or [] + bad = sorted({i for i in items if i not in OK_ITEMS}) + if bad: + v.append(f"non-MCP items in the event stream: {bad}") + tw = h.info.get("traj") + residual = [] + for st in (tw.steps if tw else []): + for tc in st["tool_calls"]: + if tc.get("item_type") != "mcp_tool_call": + continue + if tc["native_name"].startswith("lff.") and tc["function_name"] in MCP_TOOLS: + continue + if tc["function_name"] in ("list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"): + residual.append(tc["function_name"]) # our server has no resources: always empty + else: + v.append(f"unexpected MCP call {tc['native_name']}") + if residual: + notes.append(f"residual MCP-resource tool calls (empty, our server has no resources): {residual}") + if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env): + v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}") + ch = spec.state_dirs["codex_home"] + note = self._sync_auth_back(ch) + if note: + notes.append(note) + left = dict(codex_home=snapshot_tree(ch), home=snapshot_tree(spec.state_dirs["home"]), + work=snapshot_tree(spec.cwd)) + threads = None + for f in left["codex_home"]: + if re.match(r"state_\d+\.sqlite$", f): + threads = self.sqlite_rows(os.path.join(ch, f), "threads") + if isinstance(threads, int) and threads > 1: + v.append(f"{threads} threads persisted in CODEX_HOME (only this run's one is expected)") + thread = h.info.get("thread") + sessions = [f for f in left["codex_home"] if f.startswith(("sessions/", "archived_sessions/"))] + foreign = [f for f in sessions if not (thread and f.startswith("sessions/") and f.endswith(f"-{thread}.jsonl"))] + if foreign: + v.append(f"session files other than this run's thread: {foreign}") + if h.info.get("resumes"): + notes.append(f"resumed {len(h.info['resumes'])}x with the reference driver's nudge (CLI exited before the " + f"episode was over)") + if left["work"]: + v.append(f"files in the work dir: {left['work']}") + if (spec.config_files.get("model_catalog_json") or {}).get("code_mode", True): + notes.append("image forwarding (model calls image()) is not visible in --json; needs the model proxy (P1)") + mcp_env = None + mt = os.path.join(ep.log_dir, "mcp_transcript.jsonl") + if os.path.exists(mt): + for line in open(mt): + d = json.loads(line) + if d.get("ev") == "start" and "env_keys" in d: + mcp_env = d["env_keys"] + out = dict(harness=self.name, violations=v, notes=notes, files_left=left, threads_rows=threads, + mcp_server_env_keys=mcp_env, item_types=sorted(set(items)), errors=h.info.get("errors"), ok=not v) + with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f: + json.dump(out, f, indent=1) + return out diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/contract.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/contract.py new file mode 100644 index 0000000000000000000000000000000000000000..5efe5079fdb7ef9581c6772a9954c3f64b8eda49 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/contract.py @@ -0,0 +1,160 @@ +"""Information contract of one run (docs/15 §1 layer 2) and its hash `contract_sha256`. + +The contract is everything the agent is given that must be identical across harnesses and models for the same +instance and condition: the README text, the three tool schemas, the image spec, the feedback level, --hide-k, the +budgets, the memory condition, the task and seed, and the code that builds the scene and judges it. Two runs whose +`contract_sha256` differ must not share a table cell. + +What is NOT in the contract on purpose: the harness (it is the thing being compared), the model, the port, the +sandbox / log paths, timestamps. + + contract = build_contract(log_dir) # reads session.json, agent_iface.json, events.jsonl, README.md + contract_sha256(contract) # sha256 of the canonical JSON + write_contract(log_dir) # -> /contract.json, returns (contract, sha) +""" +import glob +import hashlib +import json +import os +import re +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # the lffbench repo +CONTRACT_VERSION = 1 +IMAGE_SPEC = dict(cameras=["agentview", "wrist"], width=512, height=512, format="JPEG", jpeg_quality=90, + delivery="files in the workspace, viewed with view_images (bytes unchanged)") +# code that builds the scene, runs the robot and judges the result (task modules are added per task) +SERVER_CODE = ["lffbench/agent/robot_server.py", "lffbench/agent/tools.py", "lffbench/agent/camera.py", + "lffbench/agent/context.py", "lffbench/agent/images.py", "lffbench/envs.py", "lffbench/skills.py", + "lffbench/task_base.py", "lffbench/bddl.py", "lffbench/objects.py"] +# real-robot backend (added for real_* tasks only; the driver itself is recorded as contract["real_driver"]) +REAL_CODE = ["lffbench/real/tasks.py", "lffbench/real/session.py", "lffbench/real/executor.py", "lffbench/real/protocol.py"] + + +def sha256_bytes(b): + return hashlib.sha256(b).hexdigest() + + +def sha256_text(s): + return sha256_bytes(s.encode("utf-8")) + + +def sha256_file(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for chunk in iter(lambda: f.read(1 << 20), b""): + h.update(chunk) + return h.hexdigest() + + +def canonical(obj): + return json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(",", ":")) + + +def sha256_json(obj): + return sha256_text(canonical(obj)) + + +def tool_schemas(): + """The three LA tools exactly as the reference driver and the MCP server define them.""" + sys.path.insert(0, os.path.join(ROOT, "scripts")) + from api_player import SHELL_TOOL, TOOL_LA, VIEW_TOOL_LA, PREAMBLE_LA # noqa: E402 + return [TOOL_LA, SHELL_TOOL, VIEW_TOOL_LA], PREAMBLE_LA + + +def task_module_files(task): + """Source files of the task class `task` (found by its `name = ""` line; .bak files are ignored).""" + pat = re.compile(r"""^\s*name\s*=\s*["']%s["']""" % re.escape(task), re.M) + hits = [] + for p in sorted(glob.glob(os.path.join(ROOT, "lffbench", "tasks", "*.py"))): + try: + if pat.search(open(p, encoding="utf-8").read()): + hits.append(os.path.relpath(p, ROOT)) + except OSError: + pass + arm = os.path.join(ROOT, "lffbench", "arm_specs", f"{task}.py") + if os.path.exists(arm): + hits.append(os.path.relpath(arm, ROOT)) + real = os.path.join(ROOT, "lffbench", "real", "tasks.py") # real-robot tasks (docs/17): add the real backend's code + if not hits and os.path.exists(real) and pat.search(open(real, encoding="utf-8").read()): + hits += REAL_CODE + return hits + + +def server_code_sha(task): + files = SERVER_CODE + task_module_files(task) + per = {f: (sha256_file(os.path.join(ROOT, f)) if os.path.exists(os.path.join(ROOT, f)) else None) for f in files} + return sha256_json(per), per + + +def session_start(log_dir): + with open(os.path.join(log_dir, "events.jsonl")) as f: + for line in f: + d = json.loads(line) + if d.get("ev") == "session_start": + return d + raise RuntimeError(f"no session_start event in {log_dir}/events.jsonl") + + +def readme_budget(readme): + """The per-attempt budgets as the README states them (what the agent is told).""" + out = {} + for key, pat in (("robot_commands", r"at most (\d+) robot commands"), + ("sim_seconds", r"at most ([\d.]+) s of (?:simulated )?robot motion"), # real robot: "s of robot motion" + ("tool_calls", r"at most (\d+) tool calls")): + m = re.search(pat, readme) + out[key] = float(m.group(1)) if m and "." in m.group(1) else (int(m.group(1)) if m else None) + return out + + +def build_contract(log_dir): + log_dir = os.path.abspath(log_dir) + sess = json.load(open(os.path.join(log_dir, "session.json"))) + iface = json.load(open(os.path.join(log_dir, "agent_iface.json"))) + st = session_start(log_dir) + readme = open(os.path.join(sess["sandbox"], "README.md"), encoding="utf-8").read() + tools, preamble = tool_schemas() + code_sha, code_files = server_code_sha(st["task"]) + out = dict( + contract_version=CONTRACT_VERSION, + task=st["task"], seed=st["seed"], + readme_sha256=sha256_text(readme), + preamble_sha256=sha256_text(preamble), + tools=tools, + image_spec=dict(IMAGE_SPEC, perception=st.get("perception", iface.get("perception"))), + feedback=st.get("feedback"), instruction=st.get("instruction"), + memory=st.get("memory"), k=st.get("k"), k_shown=st.get("k_shown"), hide_k=st.get("k_shown") != st.get("k"), + protocol=st.get("protocol"), arm=st.get("arm"), dossier_sha256=sha256_text(st.get("dossier") or ""), + budget=dict(readme_budget(readme), max_tool_calls=iface.get("max_tool_calls"), + tool_call_budget_enforced_by="mcp_robot_server / api_player (per attempt)"), + agent_iface=iface.get("agent_iface"), + server_code_sha256=code_sha, server_code_files=code_files, + ) + if st.get("backend") == "real": # only real-robot runs get this key, so simulated contracts are unchanged + di = st.get("driver_info") or {} + out["real_driver"] = {k: di.get(k) for k in ("protocol", "robot", "n_joints", "workspace", "yaw_range_deg", + "max_speed", "ik", "driver_version")} + out["real_agent_workspace"] = st.get("agent_workspace") + from .redteam import marker # adversarial acceptance runs only (harness_run --red-team): others are unchanged + rt = marker(log_dir) + if rt: + out["red_team"] = rt + return out + + +def contract_sha256(contract): + return sha256_json(contract) + + +def write_contract(log_dir): + c = build_contract(log_dir) + sha = contract_sha256(c) + with open(os.path.join(log_dir, "contract.json"), "w") as f: + json.dump(dict(contract_sha256=sha, contract=c), f, indent=1, ensure_ascii=False) + return c, sha + + +if __name__ == "__main__": + for d in sys.argv[1:]: + c, sha = write_contract(d) + print(sha, d) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/dsh.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/dsh.py new file mode 100644 index 0000000000000000000000000000000000000000..cabe50c03f3c404aa8f93e5620581f66bbe902a5 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/dsh.py @@ -0,0 +1,403 @@ +"""DeepSeek Harness (`dsh`, deepseek-ai/deepseek-harness, developer preview) as a native harness. + +Launch: `node /lib/bin.js --profile headless --patch --json `, process env exactly +the whitelist, a brand-new empty DSH_HOME and HOME under /tmp/lffstate/, work dir /tmp/lffrun/<12 hex>. The patch +is a Cordis overlay on the shipped headless profile: it switches off every built-in tool plugin and what serves only +them (memory-like instructions, skills, goals, web, sub-agents, plan mode, code-mode tool calls) and adds our MCP +server. What stays as shipped is the harness under test: its system prompt, agent loop, retry policy, compaction, +tool-result pruning and image offload. + +Two more plugins are off because they are provider telemetry, not agent behaviour (model-hidden top-level request +fields, docs/deepseek-llm-api-wire-extensions.md): session-log-deepseek (`dsh_session_log`: the session log on every +request) and plugin-package-inventory-deepseek (`dsh_plugin_packages`). session-title-llm is off: an extra model call +that only names the session. + +The model API is the direct DeepSeek adapter (Anthropic Messages, default root https://api.deepseek.com/anthropic, or +OpenCode Go's https://opencode.ai/inference/go; model id passed through, `output_config.effort`). DeepSeek's adapter uploads each request image through /v1/files and +sends file ids, falling back to inline base64; the model gateway allows the Files path for this harness +(scripts/model_gateway.py --allow-files), otherwise each image would first fail an upload. + +Release layout (LFF_DSH_HOME, default /mnt/cpfs/workspace/env/dsh-): bin/node (official Node.js build, no +dependency on /etc/dsw, so it runs in the jail) + node_modules/ from `npm install @deepseek-ai/dsh@`. The pin +key's hash covers bin/node and package-lock.json. + +Early exit: as for the other CLIs, the process ends when the model replies without a tool call, also mid-episode; +scripts/harness_run.py then sends the reference driver's nudge with `--session-id ` (resume_argv). + +The --json stream caps strings at 8 KiB and is not lossless, so the durable session log (session.v4.jsonl.zstd) is +copied into the run's log dir in audit(), before the one-time dirs are removed. + +Fail-closed launch: as Claude Code (claude_code.py): the same argv / env against a local fake Anthropic server with a +schema-only MCP server; tools, system prompt, harness-added message prefix and parameters are hashed against the pin. +""" +import json +import os +import re +import shutil +import subprocess +import sys +import time + +from . import contract as C +from . import pins +from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info, + new_run_dir, proxy_env, snapshot_tree) +from .claude_code import MCP_TOOLS, request_fingerprint +from .fakeapi import FakeAnthropic +from .trajectory import TrajWriter, strip_mcp + +ROOT = C.ROOT +MCP_SCRIPT = os.path.join(ROOT, "scripts", "mcp_robot_server.py") +BASE_PATH = "/usr/bin:/bin" +DEFAULT_RELEASE = "/mnt/cpfs/workspace/env/dsh-0.2.1-rc.5" +DEEPSEEK_ANTHROPIC_URL = "https://api.deepseek.com/anthropic" +BIN_JS = os.path.join("node_modules", "@deepseek-ai", "dsh", "lib", "bin.js") +PACKAGE_JSON = os.path.join("node_modules", "@deepseek-ai", "dsh", "package.json") +CONTEXT_WINDOW = 1048576 # GET https://api.deepseek.com/models, DeepSeek-V4.1-Flash, 2026-10-30 +SESSION_LOG = "session.v4.jsonl.zstd" +OK_EVENTS = ("session", "status", "text", "thinking", "tool_call", "tool_result", "final", "error") +# request fields of the provider telemetry plugins switched off in the patch: their return is a launch refusal +TELEMETRY_FIELDS = ("dsh_session_log", "dsh_plugin_packages") +DISABLE = ["tool-bash", "tool-pwsh", "tool-jobs", "tool-fs", "tool-fs-search", "tool-skill", "tool-todo", "tool-goal", + "tool-web", "tool-subagent", "tool-subagent-fork", "tool-subagent-control", "tool-workflow", + "tool-working-directory", "mcp-resources", "agent-instructions", "skill-filesystem", "skill", + "goal-round-driver", "command-goal", "goal", "plan-mode", "subagent-fork-in-process", + "subagent-spawn-in-process", "subagent", "workflow-ptc", "tool-executor-ptc", "ptc-runtime", + "web-fetch-http", "web-deepseek-api", "web-search-deepseek", "web", "session-title-llm", + "session-log-deepseek", "plugin-package-inventory-deepseek", "llm-deepseek-account"] + + +def release_dir(): + return os.environ.get("LFF_DSH_HOME") or DEFAULT_RELEASE + + +def node_bin(): + return os.path.join(release_dir(), "bin", "node") + + +def _yaml_str(s): + return json.dumps(s) # a JSON string is a valid YAML flow scalar + + +def patch_yaml(mcp_cmd, mcp_args, cwd, effort, base_url, model): + """The Cordis overlay of a run. A config override replaces the whole entry config, hence the full llm-deepseek row. + The model is declared in `models` because dsh treats a model id outside its built-in catalog as text-only + (docs/user/guide/providers.md), and the OpenCode Go id is one; capacity and image input from DeepSeek's /models.""" + out = [f"- id: {name}\n disabled: true\n" for name in DISABLE] + out.append("- id: llm-deepseek\n config:\n" + f" baseURL: {_yaml_str(base_url)}\n apiKeyEnv: DEEPSEEK_API_KEY\n" + f" reasoningEffort: {_yaml_str(effort)}\n" + f" models:\n - id: {_yaml_str(model)}\n contextWindow: {CONTEXT_WINDOW}\n" + " inputModalities: [text, image]\n") + out.append("- insert:\n - id: mcp-lff\n name: '@deepseek-ai/dsh-mcp-client'\n config:\n" + " serverName: lff\n transport: stdio\n" + f" command: {_yaml_str(mcp_cmd)}\n" + f" args: {json.dumps(list(mcp_args))}\n" + f" env: {{PATH: {_yaml_str(BASE_PATH)}}}\n" + f" cwd: {_yaml_str(cwd)}\n" + " toolCallTimeoutMs: 900000\n failOnStartupError: true\n") + return "".join(out) + + +class DeepSeekHarness(HarnessAdapter): + name = "dsh" + uses_mcp = True + can_resume = True + clean_dirs = ("home", "dsh_home", "tmp") + ancestor_files = ("AGENTS.md", "CLAUDE.md", ".dsh", ".agents") + capabilities = dict( + only_benchmark_tools=Cap("yes", "preflight", "built-in tool plugins off in the patch: request tools = 3 MCP " + "tools"), + images_reach_model=Cap("partial", "probe", "MCP images reach the model through dsh's request-image pipeline, " + "which resizes to DeepSeek's vision grid (at most 1024 tokens an image) and may offload " + "the oldest images of a long run; not byte-identical above that size"), + non_persistent_session=Cap("yes", "probe", "only this run's session (for --session-id) in the one-time " + "DSH_HOME, removed after the run"), + pinned_version=Cap("yes", "launch", "package version + hash of bin/node and package-lock.json in harness.json"), + machine_readable_events=Cap("partial", "stream", "--json NDJSON, strings capped at 8 KiB; the lossless session " + "log is copied into the log dir"), + tool_calls_logged=Cap("yes", "stream", "tool_call / tool_result in stream + mcp_transcript + events.jsonl"), + model_and_effort=Cap("yes", "preflight", "agent default model / llm-deepseek reasoningEffort; request " + "output_config.effort checked"), + persistent_memory=Cap("absent", "probe", "no memory plugin in the profile; empty one-time DSH_HOME"), + instruction_file_injection=Cap("absent", "preflight", "agent-instructions and skills plugins off; empty dirs"), + web_access=Cap("absent", "preflight", "web plugins off; no web tool in the request"), + host_file_read=Cap("absent", "preflight", "tool-fs / tool-fs-search off; MCP shell is jailed"), + builtin_shell=Cap("absent", "preflight", "tool-bash / tool-pwsh off; not in the request"), + subagent_delegation=Cap("absent", "preflight", "subagent plugins off; not in the request"), + background_execution=Cap("absent", "preflight", "tool-jobs off; not in the request"), + ) + + def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False, python=None, + extra_args=None, jail=False): + """api_env: {"DEEPSEEK_API_KEY": ...}; base_url: Messages root (default the official one; never read from the + calling environment).""" + self.release = release_dir() + self.node = node_bin() + if not os.access(self.node, os.X_OK): + raise HarnessRefused(f"dsh: no {self.node} (see lffbench/harnesses/dsh.py, release layout)") + if jail: + from .jail import HarnessJail + self.jail = HarnessJail(self.node, proc="host") # /proc: Node reads the host's cgroup / cpu files + self.api_env = dict(api_env or {}) + self.base_url = base_url or DEEPSEEK_ANTHROPIC_URL + self.proxy = proxy_env() + self.timeout_s = timeout_s + self.pins_dir = pins_dir + self.allow_unpinned = allow_unpinned + self.python = python or sys.executable + self.extra_args = list(extra_args or []) + self._version = None + + # ------------------------------------------------------------------------------------------------ version + def version(self): + if self._version is None: + pkg = json.load(open(os.path.join(self.release, PACKAGE_JSON))) + lock = C.sha256_file(os.path.join(self.release, "package-lock.json")) + node = binary_info(self.node) + self._version = dict(version=pkg["version"], binary=node, package_lock_sha256=lock, + pin_sha256=C.sha256_text(node["sha256"] + lock)) + return self._version + + def pin_key(self, ep): + v = self.version() + return pins.key(self.name, v["version"], v["pin_sha256"], ep.model, ep.effort) + + def auth_info(self): + return dict(mode="apikey", keys=sorted(self.api_env)) + + # ------------------------------------------------------------------------------------------------ prepare + def bin_js(self): + """lib/bin.js as the process sees it: in the jail, inside the verified copy of the release dir.""" + if self.jail is not None: + root = os.path.dirname(os.path.dirname(self.jail.binary_jailed)) + return os.path.join(root, BIN_JS) + return os.path.join(self.release, BIN_JS) + + def argv(self, patch_path, first_message): + return [self.node, self.bin_js(), "--profile", "headless", "--patch", patch_path, "--json"] + self.extra_args + [ + first_message] + + def write_patch(self, state, session_path, cwd, ep, base_url): + args = ["--session", session_path] if session_path else ["--schema-only"] + cmd, a = self.mcp_server_command(self.python, MCP_SCRIPT, args) + path = os.path.join(state["state"], "patch.yml") + with open(path, "w") as f: + f.write(patch_yaml(cmd, a, cwd, ep.effort, base_url, ep.model)) + return path + + def env(self, state, base_url_unused=None): + e = dict(PATH=BASE_PATH, HOME=state["home"], DSH_HOME=state["dsh_home"], TMPDIR=state["tmp"], LANG="C.UTF-8", + NO_UPDATE_NOTIFIER="1") + e.update(self.proxy) + e.update(self.api_env) + return e + + def _state_dirs(self, hexname=None): + root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate") + os.makedirs(root, exist_ok=True) + state = dict(state=root, home=os.path.join(root, "home"), dsh_home=os.path.join(root, "dsh_home"), + tmp=os.path.join(root, "tmp")) + for k in ("home", "dsh_home", "tmp"): + os.makedirs(state[k], exist_ok=True) + return state + + def _write_profile_default(self, state, ep): + """The run's model as the profile's default (a config override of agent-default-model) goes into the patch of + the same directory: dsh has no --model flag in headless mode.""" + path = os.path.join(state["state"], "patch.yml") + with open(path, "a") as f: + f.write("- id: agent-default-model\n config:\n provider: deepseek-official\n" + f" model: {_yaml_str(ep.model)}\n") + + def prepare(self, ep, first_message, reuse_state=None): + work = new_run_dir("/tmp/lffrun") + state = reuse_state or self._state_dirs(os.path.basename(work)) + if self.jail is not None: + self.jail.stderr_dir = ep.log_dir + patch = self.write_patch(state, ep.session_path, work, ep, self.base_url) + self._write_profile_default(state, ep) + argv = self.argv(patch, first_message) + return LaunchSpec(argv=argv, env=self.env(state), cwd=work, run_dir=work, state_dirs=state, + first_message=first_message, config_files=dict(patch=patch), + stdout_path=os.path.join(ep.log_dir, "dsh_events.jsonl"), + stderr_path=os.path.join(ep.log_dir, "dsh_stderr.txt"), + redact_argv={len(argv) - 1: f""}, + timeout_s=self.timeout_s) + + def config_sha256(self, spec, ep): + """Hash of everything configurable: argv without the first message, the patch with the run's paths normalised, + env values except keys / one-time dirs.""" + def norm(s): + s = s.replace(spec.state_dirs["state"], "").replace(spec.cwd, "").replace(ep.session_path, + "") + s = re.sub(r"/tmp/lffsock/[0-9a-f]{12}/[^\"\],]+", "", s) + return re.sub(r"http://127\.0\.0\.1:\d+[^\"\s]*", "", s) + argv = [norm(a) for a in self.logged_argv(spec)[1:-1]] + patch = norm(open(spec.config_files["patch"]).read()) + env = {k: (v if k not in self.api_env else "") for k, v in spec.env.items() + if k not in ("HOME", "DSH_HOME", "TMPDIR") + PROXY_KEYS + NO_PROXY_KEYS} + return C.sha256_json(dict(argv=argv, patch=patch, env=env)) + + # ------------------------------------------------------------------------------------------------ preflight + def preflight(self, spec, ep, record_dir=None): + t0 = time.time() + fake = FakeAnthropic([[("text", "preflight ok")]], record_dir=record_dir).start() + pre = self._state_dirs() + try: + patch = self.write_patch(pre, None, spec.cwd, ep, fake.base_url) + self._write_profile_default(pre, ep) + argv = self.argv(patch, spec.first_message) + env = {k: v for k, v in self.env(pre).items() if k not in self.api_env} + env["DEEPSEEK_API_KEY"] = "sk-preflight-not-a-key" + r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd, + stdin=subprocess.DEVNULL, capture_output=True, timeout=300) + reqs = fake.message_requests() + if not reqs: + raise HarnessRefused(f"preflight: harness sent no request (rc={r.returncode}): " + f"{r.stderr.decode('utf-8', 'replace')[-800:]}" + f"{r.stdout.decode('utf-8', 'replace')[-400:]}") + n, body = reqs[0] + fp, problems = request_fingerprint(body, {}, spec, spec.first_message) + fp.pop("anthropic_beta", None) + fp["body_keys"] = sorted(body) + for f in TELEMETRY_FIELDS: + if f in body: + problems.append(f"request carries the telemetry field {f}") + if os.listdir(spec.cwd): + problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}") + fp_sha = C.sha256_json(fp) + out = dict(fingerprint_sha256=fp_sha, system_chars=fp["system_chars"], n_requests=len(reqs), + tools=[t["name"] for t in fp["tools"]], + effort_in_request=(fp["params"].get("output_config") or {}).get("effort"), + model_in_request=fp["params"].get("model"), dt_s=round(time.time() - t0, 1), problems=problems) + if out["effort_in_request"] != ep.effort: + problems.append(f"effort in request {out['effort_in_request']!r} != {ep.effort!r}") + if out["model_in_request"] != ep.model: + problems.append(f"model in request {out['model_in_request']!r} != {ep.model!r}") + pin = pins.load(self.pin_key(ep), self.pins_dir) + out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"]) + out["fingerprint"] = fp + if problems: + raise HarnessRefused("preflight: " + "; ".join(problems)) + if pin is None: + if not self.allow_unpinned: + raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck " + f"with --write-pins after the self-check passes)") + out["pin_status"] = "unpinned (allowed)" + elif pin["fingerprint_sha256"] != fp_sha: + raise HarnessRefused(f"preflight: preset prompt / tools fingerprint {fp_sha[:12]} != pinned " + f"{pin['fingerprint_sha256'][:12]} ({pin['key']})") + else: + out["pin_status"] = "match" + return out + finally: + fake.stop() + shutil.rmtree(pre["state"], ignore_errors=True) + + # ------------------------------------------------------------------------------------------------ resume + @staticmethod + def session_ids(stdout_path): + out = [] + try: + for line in open(stdout_path, encoding="utf-8", errors="replace"): + if line.startswith('{"type":"session"'): + out.append(json.loads(line)["sessionId"]) + except (OSError, ValueError, KeyError): + pass + return out + + def resume_argv(self, h, message): + sids = self.session_ids(h.spec.stdout_path) + if not sids: + raise HarnessRefused("resume: no session id in the stream") + return list(h.spec.argv[:-1]) + ["--session-id", sids[0], message] + + # ------------------------------------------------------------------------------------------------ collect + def collect(self, h): + spec, ep = h.spec, h.ep + tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl")) + usage, sid, kinds, errors, turn_ends, truncated = dict(input=0, cached=0, output=0, cache_write=0), None, [], [], [], 0 + cur = None + for line in open(spec.stdout_path, encoding="utf-8", errors="replace"): + if not line.startswith("{"): + continue + d = json.loads(line) + t = d.get("type") + kinds.append(t) + truncated += bool(d.get("truncated")) + if t == "session": + sid = sid or d.get("sessionId") + elif t == "text": + cur = tw.add_step("agent", message=d.get("text", "")) + elif t == "thinking": + cur = tw.add_step("agent", reasoning=d.get("text", "")) + elif t == "tool_call": + tw.add_step("agent", tool_calls=[dict(tool_call_id=d.get("callId"), function_name=strip_mcp(d.get("tool")), + native_name=d.get("tool"), arguments=d.get("input"))]) + elif t == "tool_result": + tw.add_result(d.get("callId"), d.get("result", ""), d.get("status") == "error", 0) + elif t == "status" and d.get("phase") == "step_end": + u = d.get("usage") or {} + usage["input"] += u.get("inputTokens") or 0 + usage["output"] += u.get("outputTokens") or 0 + usage["cached"] += u.get("cacheReadTokens") or 0 + usage["cache_write"] += u.get("cacheWriteTokens") or 0 + elif t == "status" and d.get("phase") == "turn_end": + turn_ends.append(d.get("reason")) + elif t == "error": + errors.append(d) + del cur + v = self.version() + tw.set_header(session_id=sid, source=os.path.basename(spec.stdout_path), + agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort), + tools=MCP_TOOLS) + tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], turn_ends=turn_ends[-5:]), + total_prompt_tokens=usage["input"] + usage["cached"] + usage["cache_write"], + total_completion_tokens=usage["output"], total_cached_tokens=usage["cached"], + total_cost_usd=None, segments=len(turn_ends), truncated_events=truncated) + tw.write() + h.info.update(kinds=kinds, traj=tw, session=sid, errors=errors, turn_ends=turn_ends) + return tw + + # ------------------------------------------------------------------------------------------------ audit + def audit(self, h): + spec, ep = h.spec, h.ep + v, notes = [], [] + bad = sorted({k for k in h.info.get("kinds") or [] if k not in OK_EVENTS}) + if bad: + notes.append(f"unknown event types in the stream: {bad}") + tw = h.info.get("traj") + names = [tc.get("native_name") for st in (tw.steps if tw else []) for tc in st["tool_calls"]] + badt = sorted({n for n in names if n not in MCP_TOOLS}) + if badt: + notes.append(f"model asked for unavailable tools: {badt}") + if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env): + v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}") + left = dict(dsh_home=snapshot_tree(spec.state_dirs["dsh_home"]), home=snapshot_tree(spec.state_dirs["home"]), + work=snapshot_tree(spec.cwd)) + sid = h.info.get("session") + logs = [p for p in left["dsh_home"] if p.endswith(SESSION_LOG)] + foreign = [p for p in logs if not (sid and f"/{sid}/" in p)] + if foreign: + v.append(f"session logs other than this run's: {foreign}") + for p in logs: + shutil.copy(os.path.join(spec.state_dirs["dsh_home"], p), os.path.join(ep.log_dir, SESSION_LOG)) + if h.info.get("resumes"): + notes.append(f"resumed {len(h.info['resumes'])}x with the reference driver's nudge (CLI exited before the " + f"episode was over)") + if left["work"]: + v.append(f"files in the work dir: {left['work']}") + mcp_env = None + mt = os.path.join(ep.log_dir, "mcp_transcript.jsonl") + if os.path.exists(mt): + for line in open(mt): + d = json.loads(line) + if d.get("ev") == "start" and "env_keys" in d: + mcp_env = d["env_keys"] + out = dict(harness=self.name, violations=v, notes=notes, files_left=left, mcp_server_env_keys=mcp_env, + errors=h.info.get("errors"), turn_ends=h.info.get("turn_ends"), tool_calls=len(names), + unavailable_tool_requests=badt, ok=not v) + with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f: + json.dump(out, f, indent=1) + return out diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/embodied_evo.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/embodied_evo.py new file mode 100644 index 0000000000000000000000000000000000000000..4fe7bbab6f494d3cfae2f6802e6c266f4561f6dc --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/embodied_evo.py @@ -0,0 +1,135 @@ +"""EmbodiedEvo's Codex launcher and skills/lessons workflow on LFF's MCP. + +Controlled port: same-episode knowledge only, no Playground pretraining, recipes, +native simulator execution or reset. Programs generate/revise action plans in +shell; individual robot commands are executed through MCP. This is explicitly +not EmbodiedEvo's full native code-as-policy evaluation. +""" +import copy +import hashlib +import importlib.util +import json +import os +import subprocess +import sys +from pathlib import Path + +from . import contract as C, pins +from .base import HarnessRefused +from .codex import Codex, DISABLE, codex_bin +from .rpent import tree_sha256 + +DEFAULT_SOURCE = "/mnt/cpfs/workspace/env/embodied-evo/src" + + +def load_source(path, module_name): + if sys.version_info < (3, 11): + import tomli + sys.modules.setdefault("tomllib", tomli) + spec = importlib.util.spec_from_file_location(module_name, path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def workflow(source): + text = (Path(source) / "tasks/RoboDojo/Workspace/playground.md").read_text() + loop = text.split("Organize your work as an iterative loop:", 1)[1].split("# Environment and Primitives", 1)[0] + evolution = text.split("# Evolution: skills and lessons", 1)[1].split("# Playground rules", 1)[0] + evolution = evolution.replace("Read `skills/example.md` and `lessons/example.md` first.", + "Start with empty skills/ and lessons/; create them through shell when needed.") + return ("You are an embodied coding agent. Follow the EmbodiedEvo workflow below, adapted to the " + "benchmark's MCP interface. The benchmark instructions following this workflow are authoritative.\n\n" + "Organize your work as an iterative loop:" + loop + "\n# Skills and lessons\n" + evolution + + "\n# MCP adaptation\n" + "Use shell to write and run Python for visual analysis and incremental action-plan generation. " + "Keep reusable helpers and preconditions in skills/, failure evidence and corrections in lessons/, " + "and current plans in submission/. Execute each robot command with the robot MCP tool and inspect " + "its feedback before the next stage; Python in shell cannot contact the robot. Use view_images " + "for obs/ images. Do not assume scripts/env.py, native step(), get_observation(), reset(), or " + "Playground records exist. No preloaded recipes or skills are supplied. Preserve and revise your " + "skills and lessons across attempts of this episode only; the benchmark controls resets and " + "termination. Never replay earlier actions just because you rewrote a plan.\n\n") + + +class EmbodiedEvoCodex(Codex): + name = "embodied_evo_codex" + + def __init__(self, *args, source=None, **kwargs): + self.source = source or os.environ.get("LFF_EMBODIED_EVO_SOURCE", DEFAULT_SOURCE) + self._source_info = None + self.prefix = workflow(self.source) + self.native_launch = load_source(Path(self.source) / "orchestrator/launch_agent.py", "lff_evo_launch") + self.native_recovery = load_source(Path(self.source) / "orchestrator/agent_recovery.py", "lff_evo_recovery") + super().__init__(*args, **kwargs) + if self.catalog != "generic": + raise HarnessRefused("EmbodiedEvo controlled variant requires generic catalog") + + def source_info(self): + if self._source_info is None: + commit = subprocess.check_output(["git", "-C", self.source, "rev-parse", "HEAD"], text=True).strip() + self._source_info = dict(commit=commit, tree_sha256=tree_sha256(self.source), + workflow_sha256=hashlib.sha256(self.prefix.encode()).hexdigest()) + return self._source_info + + def version(self): + return dict(super().version(), framework=self.source_info()) + + def pin_key(self, ep): + v = self.version() + identity = C.sha256_json(v["framework"])[:12] + mode = "" if self.auth == "apikey" else "-chatgpt" + return pins.key(self.name + mode + "-generic-" + identity, v["version"], v["binary"]["sha256"], ep.model, ep.effort) + + def config_info(self): + return dict(super().config_info(), framework=self.source_info(), variant="mcp-skills-lessons", + history="same-thread", cross_episode_memory=False, native_code_execution=False) + + def argv(self, ep, session_path, base_url, first_message, codex_home): + prompt = first_message if first_message.startswith(self.prefix) else self.prefix + first_message + args = self.native_launch.agent_argv("codex", prompt, model=ep.model, effort=ep.effort) + args[0] = codex_bin() + args[args.index("--sandbox") + 1] = "read-only" + # The benchmark fixes the middle layer; native orchestration provides the workflow and launch. + extra = ["--json", "--ignore-user-config", "--ignore-rules"] + for feature in DISABLE: + extra += ["--disable", feature] + for setting in self.config_args(ep, session_path, base_url, codex_home): + extra += ["-c", setting] + return args[:-1] + extra + [prompt] + + def resume_argv(self, handle, message): + thread = self.thread_id(handle.spec.stdout_path) + if not thread: + raise HarnessRefused("EmbodiedEvo resume: missing current thread ID") + args = list(handle.spec.argv) + binary, args[0] = args[0], "codex" + i = args.index("--sandbox") + mode = args[i+1] + del args[i:i+2] + args[-1:-1] = ["-c", "sandbox_mode=" + json.dumps(mode)] + args = self.native_recovery.resume_argv(args, thread) + args[0], args[-1] = binary, message # benchmark-owned continuation; same native resume construction + return args + + def preflight(self, spec, ep, record_dir=None): + proxy = copy.copy(spec) + proxy.first_message = self.prefix + spec.first_message + # super checks all middle-layer fields; this adapter's pin binds the source and workflow hash too. + out = super().preflight(proxy, ep, record_dir) + v = self.version() + anchor_name = "codex-generic" if self.auth == "apikey" else "codex-chatgpt-generic" + anchor_key = pins.key(anchor_name, v["version"], v["binary"]["sha256"], ep.model, ep.effort) + anchor = pins.load(anchor_key, self.pins_dir) + if anchor is None or anchor["fingerprint_sha256"] != out["fingerprint_sha256"]: + raise HarnessRefused("EmbodiedEvo middle layer does not match the pinned Codex baseline") + out.update(anchor_status="match", middle_fingerprint_sha256=out["fingerprint_sha256"], + framework_prefix_sha256=self.source_info()["workflow_sha256"], + framework_prefix_chars=len(self.prefix)) + return out + + def collect(self, handle): + traj = super().collect(handle) + # Preserve provenance alongside native CLI traces. + (Path(handle.ep.log_dir) / "framework.json").write_text(json.dumps(self.config_info(), indent=2)) + return traj diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/fakeapi.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/fakeapi.py new file mode 100644 index 0000000000000000000000000000000000000000..ba9482378574fd6e4fec4b25b958f94103ff4fee --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/fakeapi.py @@ -0,0 +1,188 @@ +"""Local fake model APIs for offline harness checks (no real model, no cost). + +Both servers listen on 127.0.0.1, record every request body (auth headers dropped) and answer from a script, so a +native harness can be driven turn by turn without a model: + FakeAnthropic Anthropic Messages API (streaming SSE), used by Claude Code and by api_player --provider anthropic + FakeResponses OpenAI Responses API (streaming SSE), used by Codex through a custom model provider + +A script is a list of turns; turn i is answered to the request that already holds i assistant turns, so retries get +the same answer. Past the end of the script the server answers with a final text. A turn is a list of steps: + ("tool", name, args) Anthropic: tool_use block (name as given, e.g. "mcp__lff__robot" or "Read") + ("text", s) a text block / assistant message + ("exec", js) Responses: one `exec` custom tool call (Codex code mode) with this JavaScript + ("fcall", name, args) Responses: a plain function call + ("nscall", ns, name, args) Responses: a function call into a tool namespace (Codex without code mode calls our MCP + tools this way: name "robot", namespace "mcp__lff"; measured with 0.163) + + srv = FakeAnthropic(script, record_dir).start(); ... srv.base_url ...; srv.stop() +""" +import itertools +import json +import os +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +DROP_HEADERS = ("x-api-key", "authorization", "cookie", "chatgpt-account-id") + + +class _Base: + final_text = "done" + + def __init__(self, script=None, record_dir=None, port=0): + self.script = list(script or []) + self.record_dir = record_dir + self.port = port + self.lock = threading.Lock() + self.counter = itertools.count(1) + self.requests = [] # (n, path, body) + if record_dir: + os.makedirs(record_dir, exist_ok=True) + + # ------------------------------------------------------------------ plumbing + def start(self): + outer = self + + class H(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *a): + pass + + def _record(self, body): + with outer.lock: + n = next(outer.counter) + outer.requests.append((n, self.path, body)) + if outer.record_dir: + with open(os.path.join(outer.record_dir, f"req_{n:03d}.json"), "w") as f: + json.dump(dict(method=self.command, path=self.path, body=body, + headers={k: v for k, v in self.headers.items() if k.lower() not in DROP_HEADERS}), + f, indent=1, ensure_ascii=False) + return n + + def do_GET(self): + self._record(None) + self._send(404, b"{}", "application/json") + + def do_HEAD(self): + self._send(404, b"", "application/json") + + def do_POST(self): + raw = self.rfile.read(int(self.headers.get("content-length", 0) or 0)) + try: + body = json.loads(raw) + except ValueError: + body = raw[:4000].decode("utf-8", "replace") + n = self._record(body) + outer.handle(self, n, body) + + def _send(self, code, data, ctype): + self.send_response(code) + self.send_header("content-type", ctype) + self.send_header("content-length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + self.httpd = ThreadingHTTPServer(("127.0.0.1", self.port), H) + self.httpd.daemon_threads = True + self.port = self.httpd.server_address[1] + threading.Thread(target=self.httpd.serve_forever, daemon=True).start() + return self + + def stop(self): + self.httpd.shutdown() + self.httpd.server_close() + + def turn(self, i): + return self.script[i] if i < len(self.script) else [("text", self.final_text)] + + @staticmethod + def send_sse(h, events): + data = b"".join(f"event: {ev}\ndata: {json.dumps(d)}\n\n".encode() for ev, d in events) + h._send(200, data, "text/event-stream") + + +class FakeAnthropic(_Base): + @property + def base_url(self): + return f"http://127.0.0.1:{self.port}" + + def handle(self, h, n, body): + if not h.path.startswith("/v1/messages") or "count_tokens" in h.path or not isinstance(body, dict): + h._send(200, json.dumps({"input_tokens": 10}).encode(), "application/json") + return + msgs = body.get("messages", []) + i = sum(1 for m in msgs if m.get("role") == "assistant") + steps = self.turn(i) + blocks = [] + for j, st in enumerate(steps): + if st[0] == "tool": + blocks.append(dict(type="tool_use", id=f"toolu_fake_{i:03d}_{j}", name=st[1], input=st[2])) + else: + blocks.append(dict(type="text", text=st[1])) + stop = "tool_use" if any(b["type"] == "tool_use" for b in blocks) else "end_turn" + model = body.get("model", "fake") + evs = [("message_start", dict(type="message_start", message=dict( + id=f"msg_fake_{n}", type="message", role="assistant", model=model, content=[], stop_reason=None, + stop_sequence=None, usage=dict(input_tokens=100, output_tokens=1))))] + for k, b in enumerate(blocks): + if b["type"] == "tool_use": + evs.append(("content_block_start", dict(type="content_block_start", index=k, content_block=dict( + type="tool_use", id=b["id"], name=b["name"], input={})))) + evs.append(("content_block_delta", dict(type="content_block_delta", index=k, delta=dict( + type="input_json_delta", partial_json=json.dumps(b["input"]))))) + else: + evs.append(("content_block_start", dict(type="content_block_start", index=k, + content_block=dict(type="text", text="")))) + evs.append(("content_block_delta", dict(type="content_block_delta", index=k, + delta=dict(type="text_delta", text=b["text"])))) + evs.append(("content_block_stop", dict(type="content_block_stop", index=k))) + evs.append(("message_delta", dict(type="message_delta", delta=dict(stop_reason=stop, stop_sequence=None), + usage=dict(output_tokens=5)))) + evs.append(("message_stop", dict(type="message_stop"))) + self.send_sse(h, evs) + + def message_requests(self): + return [(n, b) for n, p, b in self.requests if isinstance(b, dict) and p.startswith("/v1/messages") + and "count_tokens" not in p] + + +class FakeResponses(_Base): + @property + def base_url(self): + return f"http://127.0.0.1:{self.port}/v1" + + def handle(self, h, n, body): + if not isinstance(body, dict) or "input" not in body: + h._send(404, b"{}", "application/json") + return + items = body.get("input") or [] + i = sum(1 for it in items if isinstance(it, dict) and it.get("type") in + ("custom_tool_call", "function_call") or (isinstance(it, dict) and it.get("type") == "message" + and it.get("role") == "assistant")) + steps = self.turn(i) + out = [] + for j, st in enumerate(steps): + if st[0] == "exec": + out.append(dict(type="custom_tool_call", id=f"ctc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}", + name="exec", status="completed", input=st[1])) + elif st[0] == "fcall": + out.append(dict(type="function_call", id=f"fc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}", + name=st[1], arguments=json.dumps(st[2]), status="completed")) + elif st[0] == "nscall": + out.append(dict(type="function_call", id=f"fc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}", + namespace=st[1], name=st[2], arguments=json.dumps(st[3]), status="completed")) + else: + out.append(dict(type="message", id=f"msg_fake_{n}_{j}", role="assistant", status="completed", + content=[dict(type="output_text", text=st[1], annotations=[])])) + rid = f"resp_fake_{n}" + evs = [("response.created", dict(type="response.created", response=dict(id=rid, status="in_progress")))] + for k, it in enumerate(out): + evs.append(("response.output_item.done", dict(type="response.output_item.done", output_index=k, item=it))) + evs.append(("response.completed", dict(type="response.completed", response=dict( + id=rid, status="completed", output=out, usage=dict( + input_tokens=100, input_tokens_details=dict(cached_tokens=0), output_tokens=3, + output_tokens_details=dict(reasoning_tokens=0), total_tokens=103))))) + self.send_sse(h, evs) + + def model_requests(self): + return [(n, b) for n, p, b in self.requests if isinstance(b, dict) and "input" in b] diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/framework_codex.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/framework_codex.py new file mode 100644 index 0000000000000000000000000000000000000000..68a8d7d09835f053760d9d0ca718cd79959b97e4 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/framework_codex.py @@ -0,0 +1,542 @@ +"""Shared launcher for robot frameworks using a native Codex backend. + +The external integration contract is Session.first_message(), Session.tool_specs(), +and Session.call(name, arguments). This launcher owns isolation, model configuration, +pins, trajectory collection and audits; framework plugins own their native loop. +Based on the validated RPent launcher; RPent's historical launcher remains frozen. +""" +import hashlib +import json +import os +import shutil +import subprocess +import time + +from . import contract as C +from . import pins +from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info, + gateway_env, new_run_dir, proxy_env, snapshot_tree) +from .codex import (AUTH_FILE, Codex, CATALOG_FILE, CATALOGS, DISABLE, EXPECTED_TOP_GENERIC, OFFICIAL_API, codex_bin, model_catalog, + request_fingerprint, toml_str) +from .fakeapi import FakeResponses +from .trajectory import TrajWriter + +ROOT = C.ROOT +JAIL_FRAMEWORK_DIR = "/opt/lffjail/hjail/framework" +BASE_PATH = "/usr/bin:/bin" +MCP_SERVER = "lff" +MCP_TOOLS = ["robot", "shell", "view_images"] +TREE_SKIP = {".git", "__pycache__", ".pytest_cache", ".ruff_cache", ".mypy_cache", "docs", "tests", ".github"} + + + +def tree_sha256(root, skip=TREE_SKIP): + """sha256 over (relative path, file sha256 / symlink target) of every file under root, skipping `skip` dirs.""" + h = hashlib.sha256() + for dp, dn, fn in os.walk(root): + dn[:] = sorted(d for d in dn if d not in skip) + for f in sorted(fn): + if f.endswith(".pyc"): + continue + p = os.path.join(dp, f) + rel = os.path.relpath(p, root) + if os.path.islink(p): + h.update(f"L {rel} {os.readlink(p)}\n".encode()) + else: + h.update(f"F {rel} {C.sha256_file(p)}\n".encode()) + return h.hexdigest() + + +def runtime_info(home): + """The robot framework runtime: upstream commit, our patch on top, and the tree hash of src + venv.""" + src, venv = os.path.join(home, "src"), os.path.join(home, "venv") + for d in (src, venv): + if not os.path.isdir(d): + raise HarnessRefused(f"robot framework runtime incomplete: {d} missing (run the selected framework setup script under integrations/)") + + def git(*a): + r = subprocess.run(["git", "-C", src] + list(a), capture_output=True, text=True, timeout=60) + return r.stdout.strip() if r.returncode == 0 else None + commit = git("rev-parse", "HEAD") + patch = subprocess.run(["git", "-C", src, "diff", "HEAD"], capture_output=True, timeout=60).stdout + untracked = (git("ls-files", "--others", "--exclude-standard") or "").split() + return dict(home=home, commit=commit, patch_sha256=hashlib.sha256(patch).hexdigest(), + untracked=sorted(u for u in untracked if "__pycache__" not in u), + tree_sha256=hashlib.sha256((tree_sha256(src) + tree_sha256(venv)).encode()).hexdigest()) + + +def jail_runtime_copy(home, tree): + """A verified read-only copy of the runtime under /opt/lffjail/hjail/framework (visible in the jail; /mnt is not).""" + dst = os.path.join(JAIL_FRAMEWORK_DIR, f"framework-{tree[:12]}") + stamp = os.path.join(dst, ".tree_sha256") + if os.path.exists(stamp) and open(stamp).read().strip() == tree: + return dst + os.makedirs(JAIL_FRAMEWORK_DIR, mode=0o755, exist_ok=True) + tmp = dst + ".tmp-" + os.urandom(3).hex() + shutil.copytree(os.path.join(home, "src"), os.path.join(tmp, "src"), symlinks=True, + ignore=shutil.ignore_patterns(".git", "__pycache__", "*.pyc")) + shutil.copytree(os.path.join(home, "venv"), os.path.join(tmp, "venv"), symlinks=True, + ignore=shutil.ignore_patterns("__pycache__", "*.pyc")) + got = hashlib.sha256((tree_sha256(os.path.join(tmp, "src")) + tree_sha256(os.path.join(tmp, "venv"))).encode() + ).hexdigest() + if got != tree: + shutil.rmtree(tmp, ignore_errors=True) + raise HarnessRefused(f"copy of the robot framework runtime does not match its tree hash ({got[:12]} != {tree[:12]})") + for dp, dn, fn in os.walk(tmp): + os.chmod(dp, 0o755) + for f in fn: + p = os.path.join(dp, f) + if not os.path.islink(p): + os.chmod(p, os.stat(p).st_mode | 0o444) + with open(os.path.join(tmp, ".tree_sha256"), "w") as f: + f.write(tree) + if os.path.exists(dst): + shutil.rmtree(dst) + os.rename(tmp, dst) + return dst + + +def codex_overrides(effort, catalog_path): + """The main table's Codex configuration (lffbench/harnesses/codex.py Codex.config_args / --disable), as -c + overrides for robot framework's planner; the provider and the MCP server URL are robot framework's own (CODEX_BASE_URL, in-process).""" + return (["model_reasoning_effort=" + toml_str(effort), + "include_permissions_instructions=false", "include_environment_context=false", + "include_collaboration_mode_instructions=false", "skills.include_instructions=false", + "skills.bundled.enabled=false", 'web_search="disabled"', + f"mcp_servers.{MCP_SERVER}.enabled_tools=" + json.dumps(MCP_TOOLS), + f'mcp_servers.{MCP_SERVER}.default_tools_approval_mode="approve"', + f"mcp_servers.{MCP_SERVER}.required=true", f"mcp_servers.{MCP_SERVER}.startup_timeout_sec=60", + f"mcp_servers.{MCP_SERVER}.tool_timeout_sec=900", + "model_catalog_json=" + toml_str(catalog_path)] + + [f"features.{f}=false" for f in DISABLE]) + + +def _items(stream_path): + """Codex app-server notifications of one robot framework session (robot framework writes them as JSONL).""" + out = [] + if not os.path.exists(stream_path): + return out + for line in open(stream_path, encoding="utf-8", errors="replace"): + try: + out.append(json.loads(line)) + except ValueError: + continue + return out + + +def _item_of(ev): + it = (ev.get("payload") or {}).get("item") or {} + return it.get("root", it) if isinstance(it, dict) else {} + + +class RobotFrameworkCodex(HarnessAdapter): + name = "framework_codex" + runtime_home = "/nonexistent" + runtime_module = "lff_integration.run" + default_steps = 500 + uses_mcp = False + uses_gateway = True + can_resume = False + clean_dirs = ("home", "codex_home", "tmp", "out") + clean_allowed = {"codex_home": (CATALOG_FILE,)} + ancestor_files = ("AGENTS.md", "AGENTS.override.md", ".codex") + capabilities = dict( + only_benchmark_tools=Cap("partial", "preflight", "Codex generic catalog (as the main table): our 3 tools as " + "mcp__lff functions + residual resource×3 / request_user_input; robot framework registers " + "no tool of its own (no file tools, no finish)"), + images_reach_model=Cap("yes", "probe", "gateway content blocks preserved by the framework bridge, " + "JPEG with its own MIME type"), + non_persistent_session=Cap("yes", "probe", "robot framework's threads only in the one-time CODEX_HOME, removed after the " + "run; no preloaded or cross-episode framework memory"), + pinned_version=Cap("yes", "launch", "codex binary sha256 + robot framework commit / patch / tree hash (src + venv) in " + "harness.json; pin per version and tree"), + machine_readable_events=Cap("yes", "stream", "Codex app-server notifications per robot framework session " + "(codex.out.stream.jsonl) + robot framework run.json"), + tool_calls_logged=Cap("yes", "stream", "mcpToolCall items + gateway_transcript (named framework face) + events.jsonl"), + model_and_effort=Cap("yes", "preflight", "model and effort in the request checked"), + persistent_memory=Cap("absent", "probe", "memories feature off; empty one-time CODEX_HOME; robot framework memory not " + "constructed"), + instruction_file_injection=Cap("absent", "probe", "project_doc_max_bytes=0, empty CODEX_HOME, no skills"), + web_access=Cap("absent", "preflight", "web_search disabled (not in the tool list)"), + host_file_read=Cap("absent", "preflight", "no file tools; the only shell is the gateway's jailed shell"), + builtin_shell=Cap("absent", "preflight", "shell_tool and unified_exec disabled (not in the tool list)"), + subagent_delegation=Cap("absent", "preflight", "multi_agent disabled; no collaboration tools in the request"), + background_execution=Cap("absent", "preflight", "no background tool in the request"), + ) + + def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False, + jail=False, auth="apikey", catalog="generic", sessions=1, attempts_per_session=0, max_turns=500, + home=None, provider=None, auth_home=None): + """Common controlled Codex SDK launcher. + + The plugin entrypoint interprets its declared loop options. For SenseNova, + max_turns is the upstream SDK-step limit, not a provider-response count. + Robot commands, simulation time and tool budgets are always server-owned. + """ + if auth not in ("apikey", "chatgpt"): + raise ValueError("framework_codex auth must be apikey or chatgpt") + if catalog not in CATALOGS: + raise ValueError(f"catalog must be one of {CATALOGS}") + self.auth, self.catalog = auth, catalog + self._auth_manager = Codex(auth=auth, auth_home=auth_home, api_env=api_env, base_url=base_url, catalog=catalog) + self.api_env = self._auth_manager.api_env + self.base_url = self._auth_manager.base_url + self.clean_allowed = {"codex_home": ((AUTH_FILE,) if auth == "chatgpt" else ()) + (CATALOG_FILE,)} + self.timeout_s, self.pins_dir, self.allow_unpinned = timeout_s, pins_dir, allow_unpinned + self.sessions, self.attempts_per_session, self.max_turns = int(sessions), int(attempts_per_session), \ + int(max_turns) + self.home = home or os.environ.get("LFF_FRAMEWORK_HOME") or self.runtime_home + self.proxy = proxy_env() + self._version = None + self._runtime = None + self.runtime_dir = self.home + if jail: + from .jail import HarnessJail + self.jail = HarnessJail(codex_bin(), proc="static") + + # ------------------------------------------------------------------------------------------------ identity + def runtime(self): + if self._runtime is None: + self._runtime = runtime_info(self.home) + if self.jail is not None: + self.runtime_dir = jail_runtime_copy(self.home, self._runtime["tree_sha256"]) + return self._runtime + + def version(self): + if self._version is None: + b = codex_bin() + out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent", + CODEX_HOME="/nonexistent"), + capture_output=True, text=True, timeout=60) + v = (out.stdout.strip().split() or ["?"])[-1] + rt = self.runtime() + self._version = dict(version=v, binary=binary_info(b), + framework=dict(commit=rt["commit"], patch_sha256=rt["patch_sha256"], + tree_sha256=rt["tree_sha256"], untracked=rt["untracked"])) + return self._version + + def pin_key(self, ep): + v = self.version() + mode = "" if self.auth == "apikey" else "-chatgpt" + name = f"{self.name}{mode}-{self.catalog}-{v['framework']['tree_sha256'][:12]}" + return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort) + + def anchor_pin_key(self, ep): + """The main table's codex pin for the same model / effort (apikey, same catalog).""" + v = self.version() + name = "codex" + ("" if self.auth == "apikey" else "-chatgpt") + ("" if self.catalog == "native" else f"-{self.catalog}") + return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort) + + def auth_info(self): + if self.auth == "chatgpt": + return self._auth_manager.auth_info() + return dict(mode="apikey", credential_var="CODEX_API_KEY", credential_set=bool(self.api_env.get( + "OPENAI_API_KEY")), keys=["CODEX_API_KEY"]) + + def config_info(self): + return dict(auth=self.auth, catalog=self.catalog, sessions=self.sessions, attempts_per_session=self.attempts_per_session, + max_turns=self.max_turns, framework=self.version()["framework"]) + + # ------------------------------------------------------------------------------------------------ prepare + def _state_dirs(self, hexname=None): + root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate") + os.makedirs(root, exist_ok=True) + state = dict(state=root, **{k: os.path.join(root, k) for k in ("home", "codex_home", "tmp", "out")}) + for k in ("home", "codex_home", "tmp", "out"): + os.makedirs(state[k], exist_ok=True) + return state + + def _install_catalog(self, codex_home, ep): + cat, src = model_catalog(self.catalog, self.version()["version"], ep.model, None, ep.effort) + path = os.path.join(codex_home, CATALOG_FILE) + with open(path, "w") as f: + json.dump(cat, f) + return path, C.sha256_file(path), os.path.relpath(src, ROOT) + + def argv(self, ep, out_dir, sessions=None, preflight=False): + py = os.path.join(self.runtime_dir, "venv", "bin", "python") + return [py, "-m", self.runtime_module, "--model", ep.model, "--effort", ep.effort, "--out", out_dir, + "--sessions", str(sessions or self.sessions), "--attempts-per-session", str(self.attempts_per_session), + "--max-turns", str(self.max_turns), "--timeout-s", str(int(self.timeout_s) - 60)] \ + + (["--no-continue"] if preflight else []) + + def env(self, state, ep, base_url, work): + e = dict(PATH=BASE_PATH, HOME=state["home"], TMPDIR=state["tmp"], CODEX_HOME=state["codex_home"], + CODEX_BIN=(self.jail.binary_jailed if self.jail is not None else codex_bin()), + CODEX_BASE_URL=base_url, FRAMEWORK_CODEX_SANDBOX="read_only", FRAMEWORK_MCP_SERVER_NAME=MCP_SERVER, + FRAMEWORK_CODEX_CONFIG_OVERRIDES=json.dumps(codex_overrides( + ep.effort, os.path.join(state["codex_home"], CATALOG_FILE))), + FRAMEWORK_REPO_ROOT=work, LFF_FRAMEWORK_FACE=self.name, PYTHONPATH=os.path.join(self.runtime_dir, "src"), + PYTHONDONTWRITEBYTECODE="1", PYTHONUNBUFFERED="1", LANG="C.UTF-8") + if self.auth == "chatgpt": + # The native API provider declares env_key. Codex app-server still requires that + # variable even with requires_openai_auth=true, so select a separate provider + # with no env_key. Do not inject a dummy key or modify the upstream runtime. + provider_id = "lffsubscription" + overrides = json.loads(e["FRAMEWORK_CODEX_CONFIG_OVERRIDES"]) + overrides += ["model_provider=" + toml_str(provider_id), + f"model_providers.{provider_id}.name=" + toml_str(provider_id), + f"model_providers.{provider_id}.wire_api=\"responses\"", + f"model_providers.{provider_id}.base_url=" + toml_str(base_url), + f"model_providers.{provider_id}.requires_openai_auth=true"] + e["FRAMEWORK_CODEX_CONFIG_OVERRIDES"] = json.dumps(overrides) + e.update(self.proxy) + if self.api_env.get("OPENAI_API_KEY"): + e["CODEX_API_KEY"] = self.api_env["OPENAI_API_KEY"] + return e + + def prepare(self, ep, first_message, reuse_state=None): + self.version() + work = new_run_dir("/tmp/lffrun") + state = reuse_state or self._state_dirs(os.path.basename(work)) + if self.jail is not None: + self.jail.stderr_dir = ep.log_dir + if not reuse_state and os.listdir(state["codex_home"]): + raise HarnessRefused("CODEX_HOME is not empty") + cat_path, cat_sha, cat_src = self._install_catalog(state["codex_home"], ep) + return LaunchSpec(argv=self.argv(ep, state["out"]), env=self.env(state, ep, self.base_url, work), cwd=work, + run_dir=work, state_dirs=state, first_message=first_message, + stdout_path=os.path.join(ep.log_dir, "framework_stdout.txt"), + stderr_path=os.path.join(ep.log_dir, "framework_stderr.txt"), + config_files=dict(model_catalog_json=dict(path=cat_path, sha256=cat_sha, source=cat_src, + catalog=self.catalog, code_mode=False)), + timeout_s=self.timeout_s) + + def config_sha256(self, spec, ep): + argv = [a.replace(spec.state_dirs["out"], "").replace(self.runtime_dir, "") + for a in spec.argv] + hidden = ("HOME", "TMPDIR", "CODEX_HOME", "CODEX_BIN", "CODEX_API_KEY", "FRAMEWORK_REPO_ROOT", "PYTHONPATH", + "LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") + PROXY_KEYS + NO_PROXY_KEYS + env = {k: v for k, v in spec.env.items() if k not in hidden} + env["FRAMEWORK_CODEX_CONFIG_OVERRIDES"] = env.get("FRAMEWORK_CODEX_CONFIG_OVERRIDES", "").replace( + spec.state_dirs["codex_home"], "") + cat = (spec.config_files.get("model_catalog_json") or {}).get("sha256") + return C.sha256_json(dict(argv=argv, env=env, model_catalog_sha256=cat, + framework_tree_sha256=self.version()["framework"]["tree_sha256"])) + + # ------------------------------------------------------------------------------------------------ launch + def launch(self, spec, ep, skip_preflight=False): + """harness_run starts the gateway after prepare(), right before launch: hand its address to the process.""" + self._auth_manager._install_auth(spec.state_dirs["codex_home"]) + spec.env.update(gateway_env(ep.log_dir)) + return super().launch(spec, ep, skip_preflight=skip_preflight) + + def cleanup(self, spec): + self._auth_manager._sync_auth_back(spec.state_dirs.get("codex_home", "")) + super().cleanup(spec) + + def preflight(self, spec, ep, record_dir=None): + """The same framework process, one session, against a local fake Responses server that answers with text + only: no tool call reaches the gateway. Checks the first request (tools, developer message, parameters, + sandbox, robot framework's prefix + our first message) against the pins.""" + t0 = time.time() + fake = FakeResponses([[("text", "preflight ok")]], record_dir=record_dir).start() + pre = self._state_dirs() + try: + self._auth_manager._install_auth(pre["codex_home"]) + self._install_catalog(pre["codex_home"], ep) + env = self.env(pre, ep, fake.base_url, spec.cwd) + if self.auth == "apikey": + env["CODEX_API_KEY"] = "sk-preflight-not-a-key" + env.update({k: spec.env[k] for k in ("LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") if k in spec.env}) + argv = self.argv(ep, pre["out"], sessions=1, preflight=True) # no status call on the episode + r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd, + stdin=subprocess.DEVNULL, capture_output=True, timeout=300) + reqs = fake.model_requests() + if not reqs: + # Native planners may record failures only in run.json, with empty stdout/stderr. + record = os.path.join(pre["out"], "run.json") + detail = "" + if os.path.isfile(record): + with open(record) as f: + failed_run = json.load(f) + detail = "; ".join(str(s.get("error")) for s in failed_run.get("sessions", []) if s.get("error")) + raise HarnessRefused(f"preflight: no model request (rc={r.returncode}): " + f"{(r.stdout + r.stderr).decode('utf-8', 'replace')[-1200:]} {detail[-1200:]}") + body = reqs[0][1] + fp, problems = request_fingerprint(body, spec.cwd, spec.first_message, EXPECTED_TOP_GENERIC) + problems = [p for p in problems if not p.startswith("user input is not exactly our first message")] + users = [c.get("text") for it in body.get("input") or [] if it.get("type") == "message" + and it.get("role") == "user" for c in it.get("content") or []] + prefix = None + if len(users) != 1 or not users[0].endswith(spec.first_message): + problems.append(f"the first user message does not end with our first message ({len(users)} blocks)") + else: + prefix = users[0][:-len(spec.first_message)] + effort = (fp["params"].get("reasoning") or {}).get("effort") + if effort != ep.effort: + problems.append(f"reasoning.effort in request {effort!r} != {ep.effort!r}") + if fp["params"].get("model") != ep.model: + problems.append(f"model in request {fp['params'].get('model')!r} != {ep.model!r}") + if os.listdir(spec.cwd): + problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}") + mid_sha = C.sha256_json(fp) + full = dict(middle=fp, framework_prefix=prefix) + fp_sha = C.sha256_json(full) + anchor = pins.load(self.anchor_pin_key(ep), self.pins_dir) + out = dict(fingerprint_sha256=fp_sha, middle_fingerprint_sha256=mid_sha, + framework_prefix_sha256=C.sha256_text(prefix) if prefix is not None else None, + framework_prefix_chars=len(prefix) if prefix is not None else None, + developer_chars=fp["developer_chars"], n_requests=len(reqs), + top_tools=[t["name"] for t in fp["tools"]], catalog=self.catalog, effort_in_request=effort, + model_in_request=fp["params"].get("model"), sandbox=fp["sandbox"], + dt_s=round(time.time() - t0, 1), problems=problems, + anchor_pin=anchor and dict(key=anchor["key"], fingerprint_sha256=anchor["fingerprint_sha256"])) + if anchor is None: + out["anchor_status"] = "no main-table pin for this model / effort" + elif anchor["fingerprint_sha256"] != mid_sha: + problems.append(f"Codex request {mid_sha[:12]} != main-table pin {anchor['fingerprint_sha256'][:12]} " + f"({anchor['key']}): the middle layer is not the main table's") + else: + out["anchor_status"] = "match" + pin = pins.load(self.pin_key(ep), self.pins_dir) + out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"]) + out["fingerprint"] = full + if problems: + raise HarnessRefused("preflight: " + "; ".join(problems)) + if pin is None: + if not self.allow_unpinned: + raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck " + f"with --write-pins after the self-check passes)") + out["pin_status"] = "unpinned (allowed)" + elif pin["fingerprint_sha256"] != fp_sha: + raise HarnessRefused(f"preflight: fingerprint {fp_sha[:12]} != pinned {pin['fingerprint_sha256'][:12]} " + f"({pin['key']})") + else: + out["pin_status"] = "match" + return out + finally: + fake.stop() + self._auth_manager._sync_auth_back(pre["codex_home"]) + shutil.rmtree(pre["state"], ignore_errors=True) + + # ------------------------------------------------------------------------------------------------ collect + def collect(self, h): + spec, ep = h.spec, h.ep + dst = os.path.join(ep.log_dir, "framework") + if os.path.isdir(spec.state_dirs["out"]): + shutil.copytree(spec.state_dirs["out"], dst, dirs_exist_ok=True) + run = {} + if os.path.exists(os.path.join(dst, "run.json")): + run = json.load(open(os.path.join(dst, "run.json"))) + tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl")) + usage = dict(input=0, cached=0, output=0, reasoning=0) + items, threads, errors = [], [], [] + for sdir in sorted(os.listdir(os.path.join(dst, "sessions"))) if os.path.isdir(os.path.join(dst, "sessions")) \ + else []: + last = None + for ev in _items(os.path.join(dst, "sessions", sdir, "codex.out.stream.jsonl")): + m = ev.get("method") or ev.get("type") + p = ev.get("payload") or {} + if m == "thread/tokenUsage/updated": + last = (p.get("token_usage") or {}).get("total") or last + if p.get("thread_id") and p["thread_id"] not in threads: + threads.append(p["thread_id"]) + elif m in ("error", "fatal", "timeout"): + errors.append(ev) + elif m == "item/completed": + it = _item_of(ev) + t = it.get("type") + items.append(t) + if t == "agentMessage": + tw.add_step("agent", message=it.get("text", "")) + elif t == "reasoning": + tw.add_step("agent", reasoning=json.dumps(it.get("summary") or it.get("content") or "")) + elif t in ("mcpToolCall", "dynamicToolCall", "commandExecution", "fileChange"): + name = it.get("tool") or t + tw.add_step("agent", tool_calls=[dict(tool_call_id=it.get("id"), function_name=name, + native_name=f"{it.get('server', '')}.{name}", + item_type=t, arguments=it.get("arguments"), + session=sdir)]) + res = it.get("result") or {} + texts = [c.get("text", "") for c in res.get("content") or [] if c.get("type") == "text"] + imgs = sum(1 for c in res.get("content") or [] if c.get("type") == "image") + tw.add_result(it.get("id"), "\n".join(texts) if texts else json.dumps(it.get("error")), + bool(it.get("error")) or it.get("status") == "failed", imgs) + if last: + usage["input"] += last.get("input_tokens") or 0 + usage["cached"] += last.get("cached_input_tokens") or 0 + usage["output"] += last.get("output_tokens") or 0 + usage["reasoning"] += last.get("reasoning_output_tokens") or 0 + # Framework close-out uses the same counted gateway shell, outside + # the model stream. Keep it visible in trajectories and tool totals. + session_record = next((s for s in run.get("sessions", []) + if sdir == f"session_{s['number']:03d}"), {}) + handoff = session_record.get("handoff") or {} + if handoff: + call_id = f"framework-handoff-{sdir}" + tw.add_step("framework", tool_calls=[dict( + tool_call_id=call_id, function_name="shell", native_name=f"{MCP_SERVER}.shell", + item_type="frameworkToolCall", arguments=handoff["arguments"], session=sdir)]) + tw.add_result(call_id, "\n".join(c.get("text", "") for c in handoff["content"] + if c.get("type") == "text")) + v = self.version() + tw.set_header(session_id=",".join(threads), source="framework/sessions/*/codex.out.stream.jsonl", + agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort, + framework=v["framework"]), tools=EXPECTED_TOP_GENERIC) + tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], item_types=sorted(set(items)), + run={k: run.get(k) for k in ("stop", "finished", + "attempts_failed", "tool_calls")}, + sessions=len(run.get("sessions") or [])), + total_prompt_tokens=usage["input"], total_completion_tokens=usage["output"], + total_cached_tokens=usage["cached"], total_cost_usd=None, reasoning_tokens=usage["reasoning"]) + tw.write() + h.info.update(items=items, traj=tw, threads=threads, errors=errors, run=run) + return tw + + # ------------------------------------------------------------------------------------------------ audit + def audit(self, h): + spec, ep = h.spec, h.ep + v, notes = [], [] + items = h.info.get("items") or [] + bad = sorted({i for i in items if i not in ("userMessage", "agentMessage", "reasoning", "mcpToolCall", + "plan", "hookPrompt")}) + if bad: + v.append(f"items other than messages / reasoning / MCP calls: {bad}") + residual = [] + tw = h.info.get("traj") + for st in (tw.steps if tw else []): + for tc in st["tool_calls"]: + if tc["native_name"] == f"{MCP_SERVER}.{tc['function_name']}" and tc["function_name"] in MCP_TOOLS: + continue + if tc["function_name"] in ("list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"): + residual.append(tc["function_name"]) + else: + v.append(f"unexpected tool call {tc['native_name']}") + if residual: + notes.append(f"residual MCP-resource tool calls (empty): {residual}") + if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env): + v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}") + run = h.info.get("run") or {} + nsess = len(run.get("sessions") or []) + if len(h.info.get("threads") or []) > max(1, nsess): + v.append(f"{len(h.info['threads'])} Codex threads for {nsess} robot framework sessions") + if nsess > 1: + notes.append(f"{nsess} robot framework sessions (handoff after a session ended before the episode was over)") + if run.get("stop") not in (None, "episode over"): + notes.append(f"robot framework stopped: {run.get('stop')}") + left = dict(codex_home=snapshot_tree(spec.state_dirs["codex_home"]), home=snapshot_tree(spec.state_dirs["home"]), + work=snapshot_tree(spec.cwd)) + if left["work"]: + v.append(f"files in the work dir: {left['work']}") + foreign = [f for f in left["codex_home"] if f.startswith(("sessions/", "archived_sessions/")) + and not any(t in f for t in (h.info.get("threads") or []))] + if foreign: + v.append(f"session files other than this run's threads: {foreign}") + gt = os.path.join(ep.log_dir, "gateway_transcript.jsonl") + faces = set() + if os.path.exists(gt): + for line in open(gt): + try: + d = json.loads(line) + except ValueError: + continue + if d.get("ev") == "tool" and d.get("face"): + faces.add(d["face"]) + if faces - {self.name}: + v.append(f"gateway calls from other access paths: {sorted(faces)}") + out = dict(harness=self.name, violations=v, notes=notes, files_left=left, gateway_faces=sorted(faces), + item_types=sorted(set(items)), errors=h.info.get("errors"), run_stop=run.get("stop"), ok=not v) + with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f: + json.dump(out, f, indent=1) + return out diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/jail.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/jail.py new file mode 100644 index 0000000000000000000000000000000000000000..2fa92de82ca61f9ec86cc39756433bb829fe16d9 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/jail.py @@ -0,0 +1,228 @@ +"""Jail for native harness processes (docs/15 §3.4): the harness sees no host path at all, instead of only "having no +tool that reads files". + +Without it, Claude Code / Codex run as root on the host with /mnt visible (task code with the hidden-variable rules, +task cards, earlier runs' logs, .secrets); isolation then rests on every built-in tool being switched off. With it +(adapter option jail=True, `harness_run.py --jail`, `api_batch.py start --jail`): + - the harness runs as the unprivileged host user nobody (uid 65534) in new user + mount namespaces + (jail/harness_jail_inner.sh, installed under /opt/lffjail/hjail by jail/setup_harness_jail.sh): /mnt /home /root + /tmp /run/secrets /etc/dsw are empty tmpfs, system dirs read-only, all capabilities dropped; the network stays + (model API); + - /proc: "static" (Codex) = a read-only tmpfs with static copies of host-wide files (CPU, memory, kernel version) and + the process's own self/ entries, no other pid; "host" (Claude Code, a Bun executable that aborts without a real + procfs; a fresh procfs cannot be mounted in this container because its /proc has locked submounts) = the host + procfs, where as uid 65534 the harness can list processes and read their command lines but not their environ, fd, + cwd or root (checked in tests/harness_selfcheck/jail_probe.py); + - visible again, at their original paths: the one-time work dir, the one-time state dir and the socket dir of the + MCP relay (chowned to uid 65534); the harness binary runs from a verified copy of its release dir under + /opt/lffjail/hjail/bin (the original lives under 0700 dirs in /mnt); + - the MCP server (scripts/mcp_robot_server.py) runs outside the jail; the harness starts the relay + /opt/lffjail/hjail/mcp_fwd.py, which connects to a Unix socket served here: every connection gets its own MCP + server process with stdin / stdout on the socket and the environment {PATH} only. +The harness command line (except argv[0] = the copy), its environment (exact whitelist) and the paths it sees are +unchanged; only the MCP server entry of its config points to the relay. +""" +import hashlib +import os +import secrets +import shutil +import socket +import subprocess +import threading + +JAIL_DIR = "/opt/lffjail/hjail" +INNER = os.path.join(JAIL_DIR, "inner.sh") +RELAY = os.path.join(JAIL_DIR, "mcp_fwd.py") +BIN_DIR = os.path.join(JAIL_DIR, "bin") +RELAY_PYTHON = "/usr/bin/python3" +SOCK_ROOT = "/tmp/lffsock" +JAIL_UID = 65534 +MAX_BINDS = 16 + + +class JailError(RuntimeError): + pass + + +def installed_problems(): + p = [] + for f in (INNER, RELAY): + if not os.path.exists(f): + p.append(f"{f} missing (sudo bash jail/setup_harness_jail.sh)") + if not os.path.isdir(os.path.join(JAIL_DIR, "stage", str(MAX_BINDS - 1))): + p.append(f"{JAIL_DIR}/stage/0..{MAX_BINDS - 1} missing (sudo bash jail/setup_harness_jail.sh)") + if not os.access(RELAY_PYTHON, os.X_OK): + p.append(f"{RELAY_PYTHON} missing") + for t in ("unshare", "setpriv"): + if not shutil.which(t): + p.append(f"{t} not found") + return p + + +def sha256_file(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for b in iter(lambda: f.read(1 << 20), b""): + h.update(b) + return h.hexdigest() + + +def _outermost(dirs): + """Drop directories that lie inside another one of the list (one bind mount covers them).""" + ds = sorted({os.path.realpath(d) for d in dirs if d}, key=len) + out = [] + for d in ds: + if not any(d == o or d.startswith(o.rstrip("/") + "/") for o in out): + out.append(d) + return out + + +def _chown_tree(root, uid): + os.chown(root, uid, uid) + for dp, dn, fn in os.walk(root): + for n in dn + fn: + try: + os.lchown(os.path.join(dp, n), uid, uid) + except FileNotFoundError: + pass + + +def binary_copy(binary): + """A verified copy of the binary's release dir under /opt/lffjail/hjail/bin (readable by uid 65534); returns + (path of the binary in the copy, info). The release dir is the binary's dir, or its parent if that is a bin/.""" + real = os.path.realpath(binary) + if not os.path.isfile(real): + raise JailError(f"harness binary {binary} -> {real} not found") + sha = sha256_file(real) + rel_root = os.path.dirname(real) + if os.path.basename(rel_root) == "bin": + rel_root = os.path.dirname(rel_root) + dst_root = os.path.join(BIN_DIR, f"{os.path.basename(rel_root)}-{sha[:12]}") + dst = os.path.join(dst_root, os.path.relpath(real, rel_root)) + if not (os.path.isfile(dst) and sha256_file(dst) == sha): + os.makedirs(BIN_DIR, mode=0o755, exist_ok=True) + tmp = dst_root + ".tmp-" + secrets.token_hex(3) + shutil.copytree(rel_root, tmp, symlinks=True) + for dp, dn, fn in os.walk(tmp): + os.chmod(dp, 0o755) + if os.path.exists(dst_root): + shutil.rmtree(dst_root) + os.rename(tmp, dst_root) + if sha256_file(dst) != sha: + raise JailError(f"copy of {real} does not match its sha256") + return dst, dict(original=real, copy=dst, sha256=sha) + + +class _Relay: + """Serves one Unix socket; each connection gets a fresh MCP server process attached to it.""" + + def __init__(self, sock_path, argv, env, stderr_path, uid): + self.path, self.argv, self.env, self.stderr_path = sock_path, argv, env, stderr_path + self.procs = [] + self.closed = False + self.srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.srv.bind(sock_path) + os.chown(sock_path, uid, uid) + os.chmod(sock_path, 0o600) + self.srv.listen(8) + self.t = threading.Thread(target=self._serve, daemon=True) + self.t.start() + + def _serve(self): + while not self.closed: + try: + conn, _ = self.srv.accept() + except OSError: + return + try: + err = open(self.stderr_path, "ab") if self.stderr_path else subprocess.DEVNULL + p = subprocess.Popen(self.argv, stdin=conn.fileno(), stdout=conn.fileno(), stderr=err, env=self.env, + cwd="/", start_new_session=True) + self.procs.append(p) + if err is not subprocess.DEVNULL: + err.close() + finally: + conn.close() + + def close(self): + self.closed = True + try: + self.srv.close() + except OSError: + pass + for p in self.procs: + if p.poll() is None: + p.terminate() + for p in self.procs: + try: + p.wait(timeout=10) + except subprocess.TimeoutExpired: + p.kill() + + +class HarnessJail: + """One per adapter instance. mcp_command() registers a real MCP server command and returns the relay command for + the harness config; wrap() turns the harness argv into the jailed one; close() stops relays and removes sockets.""" + + def __init__(self, binary, proc="static", uid=JAIL_UID, stderr_dir=None): + probs = installed_problems() + if probs: + raise JailError("; ".join(probs)) + if proc not in ("static", "host"): + raise JailError(f"proc must be static or host, not {proc!r}") + self.binary_real = os.path.realpath(binary) + self.binary_jailed, self.binary_info = binary_copy(binary) + self.proc, self.uid = proc, uid + self.sock_dir = None + self.relays = [] + self.stderr_dir = stderr_dir + + def info(self): + return dict(enabled=True, uid=self.uid, proc=self.proc, binary=self.binary_info, inner=INNER, + inner_sha256=sha256_file(INNER), relay=RELAY) + + def _sock_dir(self): + if self.sock_dir is None: + os.makedirs(SOCK_ROOT, mode=0o711, exist_ok=True) + os.chmod(SOCK_ROOT, 0o711) + d = os.path.join(SOCK_ROOT, secrets.token_hex(6)) + os.mkdir(d, 0o700) + os.chown(d, self.uid, self.uid) + self.sock_dir = d + return self.sock_dir + + def mcp_command(self, real_argv, env=None, label="mcp"): + """-> (command, args) for the harness's MCP config: the relay on a new socket served by real_argv.""" + d = self._sock_dir() + path = os.path.join(d, f"{label}-{len(self.relays)}.sock") + err = os.path.join(self.stderr_dir, f"jail_{label}_stderr.log") if self.stderr_dir else None + self.relays.append(_Relay(path, list(real_argv), dict(env or {"PATH": "/usr/bin:/bin"}), err, self.uid)) + return RELAY_PYTHON, [RELAY, path] + + def wrap(self, argv, env, cwd, rw_dirs): + """The jailed argv. Popen it with the same env: the jail forwards exactly those variables. Chowns the + directories that are mounted back (one-time dirs only) to the jail uid.""" + rw = _outermost(list(rw_dirs) + ([self.sock_dir] if self.sock_dir else []) + ([cwd] if cwd else [])) + if len(rw) > MAX_BINDS: + raise JailError(f"too many bind mounts ({len(rw)} > {MAX_BINDS})") + for d in rw: + if not os.path.isdir(d): + raise JailError(f"bind source {d} is not a directory") + if not d.startswith(("/tmp/lffrun/", "/tmp/lffstate/", SOCK_ROOT + "/")): + raise JailError(f"refusing to mount {d} into the jail (only one-time dirs)") + _chown_tree(d, self.uid) + cmd = [self.binary_jailed if os.path.realpath(argv[0]) == self.binary_real else argv[0]] + list(argv[1:]) + out = ["setpriv", f"--reuid={self.uid}", f"--regid={self.uid}", "--clear-groups", "--", + "unshare", "--user", "--map-root-user", "--mount", "--fork", "--kill-child", + INNER, "--keep", ",".join(sorted(env)), "--proc", self.proc] + for d in rw: + out += ["--rw", d] + return out + ["--cwd", cwd or "/", "--exe", self.binary_jailed, "--"] + cmd + + def close(self): + for r in self.relays: + r.close() + self.relays = [] + if self.sock_dir and self.sock_dir.startswith(SOCK_ROOT + "/"): + shutil.rmtree(self.sock_dir, ignore_errors=True) + self.sock_dir = None diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/pins.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/pins.py new file mode 100644 index 0000000000000000000000000000000000000000..8af8749d43eed7047c1ffa6ed1b3df3bd1a76230 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/pins.py @@ -0,0 +1,40 @@ +"""Pinned launch fingerprints (fail-closed launch, docs/15 §0.4). + +A pin says: "harness at version (binary sha256 ) with model and effort sends exactly this preset +prompt and tool list" (the normalised fingerprint of the first request, see claude_code.request_fingerprint / +codex.request_fingerprint). Pins are written only by tests/harness_selfcheck/selfcheck.py --write-pins after every +offline check passed for that adapter; a launch without a matching pin is refused. + +Only hashes and sizes are stored here (the repo is public); the full fingerprint of each launch is in the run's +harness_preflight.json. +""" +import json +import os +import re +import time + +PINS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "pins") + + +def key(adapter, version, binary_sha, model, effort): + return f"{adapter}|{version}|{(binary_sha or 'nobin')[:16]}|{model}|{effort}" + + +def _path(k, pins_dir=None): + return os.path.join(pins_dir or PINS_DIR, re.sub(r"[^A-Za-z0-9.-]+", "_", k) + ".json") + + +def load(k, pins_dir=None): + p = _path(k, pins_dir) + if not os.path.exists(p): + return None + with open(p) as f: + return json.load(f) + + +def write(k, fingerprint_sha256, summary, pins_dir=None): + os.makedirs(pins_dir or PINS_DIR, exist_ok=True) + d = dict(key=k, fingerprint_sha256=fingerprint_sha256, written=time.strftime("%Y-%m-%d %H:%M:%S"), summary=summary) + with open(_path(k, pins_dir), "w") as f: + json.dump(d, f, indent=1) + return d diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/redteam.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/redteam.py new file mode 100644 index 0000000000000000000000000000000000000000..23c91f0e46b9df03459df1ac50d33a3fcf49dfc5 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/redteam.py @@ -0,0 +1,59 @@ +"""Adversarial acceptance (red-team) runs: an agent told to get "Attempt succeeded." without doing the task. + +Embodied First Exam merges a benchmark only after such a trial scored 0 on its tasks (PROTOCOL Appendix H.1). Here a +red-team run is an ordinary native-harness run whose first message starts with RED_TEAM_TEXT; everything else (task, +instance, tools, budgets, jail, model gateway) is unchanged. harness_run.py --red-team writes the marker file +red_team.json into the run's log dir before the contract is built, and contract.build_contract adds the key +"red_team" only for such runs, so their contract_sha256 never equals a normal run's and no table can mix them +(normal contracts are unchanged). scripts/redteam_report.py lists every success and every flag for a human look: a +success is either a hole in the success check / the sandbox (fix the task, bump its version) or the agent solving +the task anyway (legitimate; noted). +""" +import hashlib +import json +import os + +RED_TEAM_VERSION = "rt1" +MARKER = "red_team.json" +RED_TEAM_TEXT = """\ +[ADVERSARIAL ACCEPTANCE TEST - read this first] +This episode is a red-team test of the benchmark itself, not an evaluation of you. Your goal is to make the \ +environment report "Attempt succeeded." WITHOUT doing the task the way the instructions below intend. Look for any \ +way the success check, the simulator or the tools can be fooled, for example: +- end states that satisfy the letter of the success condition but not its intent (objects knocked, pushed off \ +supports or wedged so that a measured quantity reads as "done"; partial work that the check counts as complete); +- physics glitches (objects tunnelling, launching, jittering into place) or moving objects with something other \ +than the intended contact; +- command or protocol tricks (malformed or extreme arguments, sequences the robot interface does not expect, \ +finishing at an unusual moment); +- information you are not meant to have (files, environment variables, processes, network ports, logs or source \ +code reachable from the shell; anything that reveals the hidden properties of the scene or the success check). +Do not damage the machine and do not try to reach the internet. Do everything through the tools you have. Whenever \ +an attempt ends, write what you tried and what happened into the file redteam_notes.md in your workspace. At the \ +end, reply with a report that starts with "RED-TEAM REPORT:" and lists every trick you tried, whether the \ +environment reported success for it, and anything you found that a benchmark maintainer should fix. If you solve \ +the task in the ordinary way, say so explicitly: that is not a finding. +[END OF TEST NOTICE - the ordinary instructions of the episode follow] + +""" + + +def text_sha256(): + return hashlib.sha256(RED_TEAM_TEXT.encode("utf-8")).hexdigest() + + +def mark(log_dir): + """Write the marker before contract.write_contract runs.""" + with open(os.path.join(log_dir, MARKER), "w") as f: + json.dump(dict(version=RED_TEAM_VERSION, text_sha256=text_sha256()), f) + + +def marker(log_dir): + try: + return json.load(open(os.path.join(log_dir, MARKER))) + except (OSError, ValueError): + return None + + +def first_message(normal): + return RED_TEAM_TEXT + normal diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/reference.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..93a7ecef47a9e0f879e60d8521618b4378658db2 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/reference.py @@ -0,0 +1,143 @@ +"""The reference driver scripts/api_player.py wrapped as an adapter ("ours", the main table's harness). + +Nothing about the driver changes: it is started exactly as api_batch.py always started it (--style la), it makes its +own first `status` call, keeps its own transcript.jsonl and enforces the tool-call budget itself. The adapter only +adds harness.json, trajectory.jsonl (converted from transcript.jsonl) and harness_audit.json, like for every harness. +""" +import json +import os +import sys + +from . import contract as C +from .base import Cap, HarnessAdapter, LaunchSpec, reference_instructions +from .trajectory import TrajWriter + +ROOT = C.ROOT +PLAYER = os.path.join(ROOT, "scripts", "api_player.py") +DRIVER_FILES = ["scripts/api_player.py", "lffbench/agent/context.py", "lffbench/agent/backends/base.py", + "lffbench/agent/backends/anthropic_messages.py", "lffbench/agent/backends/openai_responses.py", + "lffbench/agent/backends/gemini.py", "lffbench/agent/backends/chat_completions.py"] + + +class Reference(HarnessAdapter): + name = "ours" + capabilities = dict( + only_benchmark_tools=Cap("yes", "launch", "the driver sends exactly TOOL_LA / SHELL_TOOL / VIEW_TOOL_LA"), + images_reach_model=Cap("yes", "probe", "FileImage sends the JPEG bytes the server wrote"), + non_persistent_session=Cap("yes", "launch", "no state outside the run's log dir"), + pinned_version=Cap("yes", "launch", "sha256 of the driver + backend sources"), + machine_readable_events=Cap("yes", "stream", "transcript.jsonl"), + tool_calls_logged=Cap("yes", "stream", "transcript.jsonl tool events + events.jsonl"), + model_and_effort=Cap("yes", "launch", "--model / --effort mapped per provider (docs/12 §2)"), + persistent_memory=Cap("absent", "launch", "strictly append-only context within the run only"), + instruction_file_injection=Cap("absent", "launch", "only README.md of the sandbox"), + web_access=Cap("absent", "launch", "no such tool"), + host_file_read=Cap("absent", "probe", "shell jailed, view_images confined to the workspace"), + builtin_shell=Cap("absent", "launch", "only the jailed shell tool"), + subagent_delegation=Cap("absent", "launch", "no such tool"), + background_execution=Cap("absent", "launch", "no such tool"), + ) + + def __init__(self, provider="anthropic", env=None, timeout_s=10800, python=None, **_): + self.provider = provider + self.base_env = dict(env if env is not None else os.environ) + self.timeout_s = timeout_s + self.python = python or sys.executable + + def version(self): + per = {f: C.sha256_file(os.path.join(ROOT, f)) for f in DRIVER_FILES if os.path.exists(os.path.join(ROOT, f))} + sha = C.sha256_json(per) + return dict(version=f"api_player@{sha[:12]}", sources_sha256=sha, binary=dict(path=PLAYER, sha256=per.get( + "scripts/api_player.py"))) + + def prepare(self, ep, first_message=None): + argv = [self.python, PLAYER, "--session", ep.session_path, "--provider", ep.provider or self.provider, + "--model", ep.model, "--effort", ep.effort, "--style", "la"] + return LaunchSpec(argv=argv, env=self.base_env, cwd=ROOT, first_message="", + stdout_path=os.path.join(ep.log_dir, "api_player.log"), + stderr_path=os.path.join(ep.log_dir, "api_player.log"), timeout_s=self.timeout_s) + + def config_sha256(self, spec, ep): + return C.sha256_json(dict(argv=[a.replace(ep.session_path, "") for a in spec.argv[1:]])) + + def launch(self, spec, ep, skip_preflight=True): + # stdout and stderr go to the same api_player.log (as before the adapter layer) + import subprocess + import time + from .base import RunHandle, env_keys_of + spec.preflight = dict(skipped=True, reason="reference driver: tools and instructions are our own code") + log = open(spec.stdout_path, "ab") + h = RunHandle(spec=spec, ep=ep, t_start=time.time()) + h.proc = subprocess.Popen(spec.argv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=log, + stderr=subprocess.STDOUT, start_new_session=True) + h.pid = h.proc.pid + time.sleep(0.2) + h.env_observed_keys = env_keys_of(h.pid) + return h + + def collect(self, h): + ep = h.ep + tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl")) + p = os.path.join(ep.log_dir, "transcript.jsonl") + start, end, first_user, tot = None, None, None, dict(inp=0, out=0, cached=0) + last_agent = None + for line in (open(p) if os.path.exists(p) else []): + d = json.loads(line) + e = d.get("ev") + if e == "start": + start = d + elif e == "user": + if first_user is None: + first_user = d.get("text") + tw.add_step("user", message=d.get("text", ""), timestamp=d.get("t")) + elif e == "assistant": + u = d.get("usage") or {} + tot["inp"] += u.get("input_tokens", 0) + tot["out"] += u.get("output_tokens", 0) + tot["cached"] += u.get("cached_tokens", 0) + last_agent = tw.add_step("agent", message=d.get("text") or "", reasoning=d.get("reasoning_summary") or "", + timestamp=d.get("t"), tool_calls=[dict(tool_call_id=c["id"], + function_name=c["name"], + native_name=c["name"], + arguments=c["arguments"]) + for c in d.get("tool_calls") or []], + metrics=dict(prompt_tokens=u.get("input_tokens"), + completion_tokens=u.get("output_tokens"), + cached_tokens=u.get("cached_tokens"))) + elif e == "tool" and last_agent is not None: + pending = [tc for tc in last_agent["tool_calls"] + if not any(r["source_call_id"] == tc["tool_call_id"] + for r in last_agent["observation"]["results"])] + if pending: + tw.add_result(pending[0]["tool_call_id"], d.get("output", ""), False, len(d.get("images") or [])) + elif e in ("end", "abort"): + end = d + tw.set_header(session_id=os.path.basename(ep.log_dir), source="transcript.jsonl", + agent=dict(name=self.name, version=self.version()["version"], model_name=ep.model, + effort=ep.effort, provider=ep.provider or self.provider), + tools=[t["name"] for t in (start or {}).get("tools") or []]) + tw.set_final(h.exit_reason if not end or end.get("ev") == "end" else "abort: " + str(end.get("reason")), + native_result=end, total_prompt_tokens=tot["inp"], total_completion_tokens=tot["out"], + total_cached_tokens=tot["cached"]) + tw.write() + h.info.update(traj=tw, start=start, first_user=first_user) + if start and first_user is not None: # the same string a native harness gets as its first message + readme = open(os.path.join(ep.sandbox, "README.md")).read() + h.info["instructions_match_readme"] = start.get("instructions") == reference_instructions(readme) + # the same composition as base.first_message_text: identical sha256 for the same instance + h.spec.first_message = start.get("instructions", "") + "\n\n" + first_user + return tw + + def audit(self, h): + ep = h.ep + start = h.info.get("start") or {} + tools, _ = C.tool_schemas() + v = [] + if start and start.get("tools") != tools: + v.append("driver tools differ from the contract's tool schemas") + if h.info.get("instructions_match_readme") is False: + v.append("driver instructions != preamble + README") + out = dict(harness=self.name, violations=v, ok=not v, notes=["reference driver: no preflight needed"]) + with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f: + json.dump(out, f, indent=1) + return out diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/rpent.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/rpent.py new file mode 100644 index 0000000000000000000000000000000000000000..e12f97b1bd6af40952ef4cf27c5c35e9883f8ae5 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/rpent.py @@ -0,0 +1,530 @@ +"""RPent (a robot harness framework, RLinf/RPent v0.1) on Codex as an upper-layer harness (docs/18; research note +harness接入调研/04 §13.7-13.9). + + rpent_codex RPent's session loop, prompt and archive / handoff rules (robots/lffbench in an RPent checkout with our + patch), driving Codex through RPent's own Codex planner (openai_codex SDK -> `codex app-server`) + +What the run is made of: + - the RPent runtime (LFF_RPENT_HOME, default /mnt/cpfs/workspace/env/rpent-v0.1): src/ = RPent at a pinned commit + plus our patch (integrations/rpent-v0.1), venv/ = its locked dependencies on /usr/bin/python3.12, no simulator; + hashed into rpent_tree_sha256 (recorded, and part of the pin); + - the framework process `python -m robots.lffbench.run` (one per episode), whose only way to the robot is the + episode's tool gateway (uses_gateway: LFF_GATEWAY_URL / LFF_GATEWAY_TOKEN, lffbench_client, face "rpent"); + - Codex: the same pinned binary and the same configuration as the main table's `codex` adapter (generic model + catalog in a one-time CODEX_HOME, the same disabled features and instruction switches, read-only sandbox, MCP + tools approved), passed to RPent's planner as RPENT_CODEX_CONFIG_OVERRIDES; RPent's in-process MCP server is named + "lff", so the model sees mcp__lff.robot / .shell / .view_images exactly as with `codex exec`. +Measured 2026-10-21 (fake API, Codex 0.163.0, gpt-6.1-sol / high): the first request of this path has the same +normalised fingerprint (tools, developer message, parameters, sandbox) as the `codex` adapter's preflight request; +the only difference is RPent's system prompt in front of the first user message (RPent puts system prompt and first +message into one user turn). The preflight checks both: the middle-layer fingerprint against the main table's codex +pin for the same model / effort (when it exists) and the whole fingerprint (incl. RPent's prefix) against this +adapter's own pin. + +The framework owns its loop (sessions, handoff, archive): harness_run's resume / nudge does not apply (can_resume +False). Episode budgets and attempt switching stay with robot_server and the gateway. Only an API key is supported +(auth="apikey"; the side table runs gpt-6.1-sol on an OpenAI key, user 2026-10-21). +""" +import hashlib +import json +import os +import shutil +import subprocess +import time + +from . import contract as C +from . import pins +from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info, + gateway_env, new_run_dir, proxy_env, snapshot_tree) +from .codex import (CATALOG_FILE, CATALOGS, DISABLE, EXPECTED_TOP_GENERIC, OFFICIAL_API, codex_bin, model_catalog, + request_fingerprint, toml_str) +from .fakeapi import FakeResponses +from .trajectory import TrajWriter + +ROOT = C.ROOT +RPENT_HOME = "/mnt/cpfs/workspace/env/rpent-v0.1" +JAIL_RPENT_DIR = "/opt/lffjail/hjail/rpent" +BASE_PATH = "/usr/bin:/bin" +MCP_SERVER = "lff" +MCP_TOOLS = ["robot", "shell", "view_images"] +TREE_SKIP = {".git", "__pycache__", "docs", "tests", ".github"} + + +def rpent_home(): + return os.environ.get("LFF_RPENT_HOME") or RPENT_HOME + + +def tree_sha256(root, skip=TREE_SKIP): + """sha256 over (relative path, file sha256 / symlink target) of every file under root, skipping `skip` dirs.""" + h = hashlib.sha256() + for dp, dn, fn in os.walk(root): + dn[:] = sorted(d for d in dn if d not in skip) + for f in sorted(fn): + if f.endswith(".pyc"): + continue + p = os.path.join(dp, f) + rel = os.path.relpath(p, root) + if os.path.islink(p): + h.update(f"L {rel} {os.readlink(p)}\n".encode()) + else: + h.update(f"F {rel} {C.sha256_file(p)}\n".encode()) + return h.hexdigest() + + +def runtime_info(home): + """The RPent runtime: upstream commit, our patch on top, and the tree hash of src + venv.""" + src, venv = os.path.join(home, "src"), os.path.join(home, "venv") + for d in (src, venv): + if not os.path.isdir(d): + raise HarnessRefused(f"RPent runtime incomplete: {d} missing (integrations/rpent-v0.1/setup.sh)") + + def git(*a): + r = subprocess.run(["git", "-C", src] + list(a), capture_output=True, text=True, timeout=60) + return r.stdout.strip() if r.returncode == 0 else None + commit = git("rev-parse", "HEAD") + patch = subprocess.run(["git", "-C", src, "diff", "HEAD"], capture_output=True, timeout=60).stdout + untracked = (git("ls-files", "--others", "--exclude-standard") or "").split() + return dict(home=home, commit=commit, patch_sha256=hashlib.sha256(patch).hexdigest(), + untracked=sorted(u for u in untracked if "__pycache__" not in u), + tree_sha256=hashlib.sha256((tree_sha256(src) + tree_sha256(venv)).encode()).hexdigest()) + + +def jail_runtime_copy(home, tree): + """A verified read-only copy of the runtime under /opt/lffjail/hjail/rpent (visible in the jail; /mnt is not).""" + dst = os.path.join(JAIL_RPENT_DIR, f"rpent-{tree[:12]}") + stamp = os.path.join(dst, ".tree_sha256") + if os.path.exists(stamp) and open(stamp).read().strip() == tree: + return dst + os.makedirs(JAIL_RPENT_DIR, mode=0o755, exist_ok=True) + tmp = dst + ".tmp-" + os.urandom(3).hex() + shutil.copytree(os.path.join(home, "src"), os.path.join(tmp, "src"), symlinks=True, + ignore=shutil.ignore_patterns(".git", "__pycache__", "*.pyc")) + shutil.copytree(os.path.join(home, "venv"), os.path.join(tmp, "venv"), symlinks=True, + ignore=shutil.ignore_patterns("__pycache__", "*.pyc")) + got = hashlib.sha256((tree_sha256(os.path.join(tmp, "src")) + tree_sha256(os.path.join(tmp, "venv"))).encode() + ).hexdigest() + if got != tree: + shutil.rmtree(tmp, ignore_errors=True) + raise HarnessRefused(f"copy of the RPent runtime does not match its tree hash ({got[:12]} != {tree[:12]})") + for dp, dn, fn in os.walk(tmp): + os.chmod(dp, 0o755) + for f in fn: + p = os.path.join(dp, f) + if not os.path.islink(p): + os.chmod(p, os.stat(p).st_mode | 0o444) + with open(os.path.join(tmp, ".tree_sha256"), "w") as f: + f.write(tree) + if os.path.exists(dst): + shutil.rmtree(dst) + os.rename(tmp, dst) + return dst + + +def codex_overrides(effort, catalog_path): + """The main table's Codex configuration (lffbench/harnesses/codex.py Codex.config_args / --disable), as -c + overrides for RPent's planner; the provider and the MCP server URL are RPent's own (CODEX_BASE_URL, in-process).""" + return (["model_reasoning_effort=" + toml_str(effort), + "include_permissions_instructions=false", "include_environment_context=false", + "include_collaboration_mode_instructions=false", "skills.include_instructions=false", + "skills.bundled.enabled=false", 'web_search="disabled"', + f"mcp_servers.{MCP_SERVER}.enabled_tools=" + json.dumps(MCP_TOOLS), + f'mcp_servers.{MCP_SERVER}.default_tools_approval_mode="approve"', + f"mcp_servers.{MCP_SERVER}.required=true", f"mcp_servers.{MCP_SERVER}.startup_timeout_sec=60", + f"mcp_servers.{MCP_SERVER}.tool_timeout_sec=900", + "model_catalog_json=" + toml_str(catalog_path)] + + [f"features.{f}=false" for f in DISABLE]) + + +def _items(stream_path): + """Codex app-server notifications of one RPent session (RPent writes them as JSONL).""" + out = [] + if not os.path.exists(stream_path): + return out + for line in open(stream_path, encoding="utf-8", errors="replace"): + try: + out.append(json.loads(line)) + except ValueError: + continue + return out + + +def _item_of(ev): + it = (ev.get("payload") or {}).get("item") or {} + return it.get("root", it) if isinstance(it, dict) else {} + + +class RPentCodex(HarnessAdapter): + name = "rpent_codex" + uses_mcp = False + uses_gateway = True + can_resume = False + clean_dirs = ("home", "codex_home", "tmp", "out") + clean_allowed = {"codex_home": (CATALOG_FILE,)} + ancestor_files = ("AGENTS.md", "AGENTS.override.md", ".codex") + capabilities = dict( + only_benchmark_tools=Cap("partial", "preflight", "Codex generic catalog (as the main table): our 3 tools as " + "mcp__lff functions + residual resource×3 / request_user_input; RPent registers " + "no tool of its own (no file tools, no finish)"), + images_reach_model=Cap("yes", "probe", "gateway content blocks passed through verbatim (ToolResult.content), " + "JPEG with its own MIME type"), + non_persistent_session=Cap("yes", "probe", "RPent's threads only in the one-time CODEX_HOME, removed after the " + "run; no RPent memory (no MemoryManager, no HF memory)"), + pinned_version=Cap("yes", "launch", "codex binary sha256 + RPent commit / patch / tree hash (src + venv) in " + "harness.json; pin per version and tree"), + machine_readable_events=Cap("yes", "stream", "Codex app-server notifications per RPent session " + "(codex.out.stream.jsonl) + RPent run.json"), + tool_calls_logged=Cap("yes", "stream", "mcpToolCall items + gateway_transcript (face rpent) + events.jsonl"), + model_and_effort=Cap("yes", "preflight", "model and effort in the request checked"), + persistent_memory=Cap("absent", "probe", "memories feature off; empty one-time CODEX_HOME; RPent memory not " + "constructed"), + instruction_file_injection=Cap("absent", "probe", "project_doc_max_bytes=0, empty CODEX_HOME, no skills"), + web_access=Cap("absent", "preflight", "web_search disabled (not in the tool list)"), + host_file_read=Cap("absent", "preflight", "no file tools; the only shell is the gateway's jailed shell"), + builtin_shell=Cap("absent", "preflight", "shell_tool and unified_exec disabled (not in the tool list)"), + subagent_delegation=Cap("absent", "preflight", "multi_agent disabled; no collaboration tools in the request"), + background_execution=Cap("absent", "preflight", "no background tool in the request"), + ) + + def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False, + jail=False, auth="apikey", catalog="generic", sessions=5, attempts_per_session=1, max_turns=100, + home=None, provider=None): + """api_env: {"OPENAI_API_KEY": ...}; base_url: Responses endpoint (default: the official API). sessions / + attempts_per_session / max_turns: RPent's --explore-sessions / --explore-attempts-per-session / --max-turns. + Defaults = the side table's setting (user 2026-10-21): variant H (one attempt per session, then a fresh session + with RPent's handoff), up to 5 sessions (k=3 + 2 spare), 100 model responses per session; within a session the + reference driver's continue rule (robots/lffbench/toolkit.py).""" + if auth != "apikey": + raise ValueError("rpent_codex supports auth=apikey only") + if catalog not in CATALOGS: + raise ValueError(f"catalog must be one of {CATALOGS}") + self.auth, self.catalog = auth, catalog + self.api_env = dict(api_env or {}) + self.base_url = base_url or OFFICIAL_API + self.timeout_s, self.pins_dir, self.allow_unpinned = timeout_s, pins_dir, allow_unpinned + self.sessions, self.attempts_per_session, self.max_turns = int(sessions), int(attempts_per_session), \ + int(max_turns) + self.home = home or rpent_home() + self.proxy = proxy_env() + self._version = None + self._runtime = None + self.runtime_dir = self.home + if jail: + from .jail import HarnessJail + self.jail = HarnessJail(codex_bin(), proc="static") + + # ------------------------------------------------------------------------------------------------ identity + def runtime(self): + if self._runtime is None: + self._runtime = runtime_info(self.home) + if self.jail is not None: + self.runtime_dir = jail_runtime_copy(self.home, self._runtime["tree_sha256"]) + return self._runtime + + def version(self): + if self._version is None: + b = codex_bin() + out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent", + CODEX_HOME="/nonexistent"), + capture_output=True, text=True, timeout=60) + v = (out.stdout.strip().split() or ["?"])[-1] + rt = self.runtime() + self._version = dict(version=v, binary=binary_info(b), + rpent=dict(commit=rt["commit"], patch_sha256=rt["patch_sha256"], + tree_sha256=rt["tree_sha256"], untracked=rt["untracked"])) + return self._version + + def pin_key(self, ep): + v = self.version() + name = f"{self.name}-{self.catalog}-{v['rpent']['tree_sha256'][:12]}" + return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort) + + def anchor_pin_key(self, ep): + """The main table's codex pin for the same model / effort (apikey, same catalog).""" + v = self.version() + name = "codex" + ("" if self.catalog == "native" else f"-{self.catalog}") + return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort) + + def auth_info(self): + return dict(mode="apikey", credential_var="CODEX_API_KEY", credential_set=bool(self.api_env.get( + "OPENAI_API_KEY")), keys=["CODEX_API_KEY"]) + + def config_info(self): + return dict(catalog=self.catalog, sessions=self.sessions, attempts_per_session=self.attempts_per_session, + max_turns=self.max_turns, rpent=self.version()["rpent"]) + + # ------------------------------------------------------------------------------------------------ prepare + def _state_dirs(self, hexname=None): + root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate") + os.makedirs(root, exist_ok=True) + state = dict(state=root, **{k: os.path.join(root, k) for k in ("home", "codex_home", "tmp", "out")}) + for k in ("home", "codex_home", "tmp", "out"): + os.makedirs(state[k], exist_ok=True) + return state + + def _install_catalog(self, codex_home, ep): + cat, src = model_catalog(self.catalog, self.version()["version"], ep.model, None, ep.effort) + path = os.path.join(codex_home, CATALOG_FILE) + with open(path, "w") as f: + json.dump(cat, f) + return path, C.sha256_file(path), os.path.relpath(src, ROOT) + + def argv(self, ep, out_dir, sessions=None, preflight=False): + py = os.path.join(self.runtime_dir, "venv", "bin", "python") + return [py, "-m", "robots.lffbench.run", "--model", ep.model, "--effort", ep.effort, "--out", out_dir, + "--sessions", str(sessions or self.sessions), "--attempts-per-session", str(self.attempts_per_session), + "--max-turns", str(self.max_turns), "--timeout-s", str(int(self.timeout_s) - 60)] \ + + (["--no-continue"] if preflight else []) + + def env(self, state, ep, base_url, work): + e = dict(PATH=BASE_PATH, HOME=state["home"], TMPDIR=state["tmp"], CODEX_HOME=state["codex_home"], + CODEX_BIN=(self.jail.binary_jailed if self.jail is not None else codex_bin()), + CODEX_BASE_URL=base_url, RPENT_CODEX_SANDBOX="read_only", RPENT_MCP_SERVER_NAME=MCP_SERVER, + RPENT_CODEX_CONFIG_OVERRIDES=json.dumps(codex_overrides( + ep.effort, os.path.join(state["codex_home"], CATALOG_FILE))), + RPENT_REPO_ROOT=work, PYTHONPATH=os.path.join(self.runtime_dir, "src"), + PYTHONDONTWRITEBYTECODE="1", PYTHONUNBUFFERED="1", LANG="C.UTF-8") + e.update(self.proxy) + if self.api_env.get("OPENAI_API_KEY"): + e["CODEX_API_KEY"] = self.api_env["OPENAI_API_KEY"] + return e + + def prepare(self, ep, first_message, reuse_state=None): + self.version() + work = new_run_dir("/tmp/lffrun") + state = reuse_state or self._state_dirs(os.path.basename(work)) + if self.jail is not None: + self.jail.stderr_dir = ep.log_dir + if not reuse_state and os.listdir(state["codex_home"]): + raise HarnessRefused("CODEX_HOME is not empty") + cat_path, cat_sha, cat_src = self._install_catalog(state["codex_home"], ep) + return LaunchSpec(argv=self.argv(ep, state["out"]), env=self.env(state, ep, self.base_url, work), cwd=work, + run_dir=work, state_dirs=state, first_message=first_message, + stdout_path=os.path.join(ep.log_dir, "rpent_stdout.txt"), + stderr_path=os.path.join(ep.log_dir, "rpent_stderr.txt"), + config_files=dict(model_catalog_json=dict(path=cat_path, sha256=cat_sha, source=cat_src, + catalog=self.catalog, code_mode=False)), + timeout_s=self.timeout_s) + + def config_sha256(self, spec, ep): + argv = [a.replace(spec.state_dirs["out"], "").replace(self.runtime_dir, "") + for a in spec.argv] + hidden = ("HOME", "TMPDIR", "CODEX_HOME", "CODEX_BIN", "CODEX_API_KEY", "RPENT_REPO_ROOT", "PYTHONPATH", + "LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") + PROXY_KEYS + NO_PROXY_KEYS + env = {k: v for k, v in spec.env.items() if k not in hidden} + env["RPENT_CODEX_CONFIG_OVERRIDES"] = env.get("RPENT_CODEX_CONFIG_OVERRIDES", "").replace( + spec.state_dirs["codex_home"], "") + cat = (spec.config_files.get("model_catalog_json") or {}).get("sha256") + return C.sha256_json(dict(argv=argv, env=env, model_catalog_sha256=cat, + rpent_tree_sha256=self.version()["rpent"]["tree_sha256"])) + + # ------------------------------------------------------------------------------------------------ launch + def launch(self, spec, ep, skip_preflight=False): + """harness_run starts the gateway after prepare(), right before launch: hand its address to the process.""" + spec.env.update(gateway_env(ep.log_dir)) + return super().launch(spec, ep, skip_preflight=skip_preflight) + + def preflight(self, spec, ep, record_dir=None): + """The same framework process, one session, against a local fake Responses server that answers with text + only: no tool call reaches the gateway. Checks the first request (tools, developer message, parameters, + sandbox, RPent's prefix + our first message) against the pins.""" + t0 = time.time() + fake = FakeResponses([[("text", "preflight ok")]], record_dir=record_dir).start() + pre = self._state_dirs() + try: + self._install_catalog(pre["codex_home"], ep) + env = self.env(pre, ep, fake.base_url, spec.cwd) + env["CODEX_API_KEY"] = "sk-preflight-not-a-key" + env.update({k: spec.env[k] for k in ("LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") if k in spec.env}) + argv = self.argv(ep, pre["out"], sessions=1, preflight=True) # no status call on the episode + r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd, + stdin=subprocess.DEVNULL, capture_output=True, timeout=300) + reqs = fake.model_requests() + if not reqs: + raise HarnessRefused(f"preflight: no model request (rc={r.returncode}): " + f"{(r.stdout + r.stderr).decode('utf-8', 'replace')[-1200:]}") + body = reqs[0][1] + fp, problems = request_fingerprint(body, spec.cwd, spec.first_message, EXPECTED_TOP_GENERIC) + problems = [p for p in problems if not p.startswith("user input is not exactly our first message")] + users = [c.get("text") for it in body.get("input") or [] if it.get("type") == "message" + and it.get("role") == "user" for c in it.get("content") or []] + prefix = None + if len(users) != 1 or not users[0].endswith(spec.first_message): + problems.append(f"the first user message does not end with our first message ({len(users)} blocks)") + else: + prefix = users[0][:-len(spec.first_message)] + effort = (fp["params"].get("reasoning") or {}).get("effort") + if effort != ep.effort: + problems.append(f"reasoning.effort in request {effort!r} != {ep.effort!r}") + if fp["params"].get("model") != ep.model: + problems.append(f"model in request {fp['params'].get('model')!r} != {ep.model!r}") + if os.listdir(spec.cwd): + problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}") + mid_sha = C.sha256_json(fp) + full = dict(middle=fp, rpent_prefix=prefix) + fp_sha = C.sha256_json(full) + anchor = pins.load(self.anchor_pin_key(ep), self.pins_dir) + out = dict(fingerprint_sha256=fp_sha, middle_fingerprint_sha256=mid_sha, + rpent_prefix_sha256=C.sha256_text(prefix) if prefix is not None else None, + rpent_prefix_chars=len(prefix) if prefix is not None else None, + developer_chars=fp["developer_chars"], n_requests=len(reqs), + top_tools=[t["name"] for t in fp["tools"]], catalog=self.catalog, effort_in_request=effort, + model_in_request=fp["params"].get("model"), sandbox=fp["sandbox"], + dt_s=round(time.time() - t0, 1), problems=problems, + anchor_pin=anchor and dict(key=anchor["key"], fingerprint_sha256=anchor["fingerprint_sha256"])) + if anchor is None: + out["anchor_status"] = "no main-table pin for this model / effort" + elif anchor["fingerprint_sha256"] != mid_sha: + problems.append(f"Codex request {mid_sha[:12]} != main-table pin {anchor['fingerprint_sha256'][:12]} " + f"({anchor['key']}): the middle layer is not the main table's") + else: + out["anchor_status"] = "match" + pin = pins.load(self.pin_key(ep), self.pins_dir) + out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"]) + out["fingerprint"] = full + if problems: + raise HarnessRefused("preflight: " + "; ".join(problems)) + if pin is None: + if not self.allow_unpinned: + raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck " + f"with --write-pins after the self-check passes)") + out["pin_status"] = "unpinned (allowed)" + elif pin["fingerprint_sha256"] != fp_sha: + raise HarnessRefused(f"preflight: fingerprint {fp_sha[:12]} != pinned {pin['fingerprint_sha256'][:12]} " + f"({pin['key']})") + else: + out["pin_status"] = "match" + return out + finally: + fake.stop() + shutil.rmtree(pre["state"], ignore_errors=True) + + # ------------------------------------------------------------------------------------------------ collect + def collect(self, h): + spec, ep = h.spec, h.ep + dst = os.path.join(ep.log_dir, "rpent") + if os.path.isdir(spec.state_dirs["out"]): + shutil.copytree(spec.state_dirs["out"], dst, dirs_exist_ok=True) + run = {} + if os.path.exists(os.path.join(dst, "run.json")): + run = json.load(open(os.path.join(dst, "run.json"))) + tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl")) + usage = dict(input=0, cached=0, output=0, reasoning=0) + items, threads, errors = [], [], [] + for sdir in sorted(os.listdir(os.path.join(dst, "sessions"))) if os.path.isdir(os.path.join(dst, "sessions")) \ + else []: + last = None + for ev in _items(os.path.join(dst, "sessions", sdir, "codex.out.stream.jsonl")): + m = ev.get("method") or ev.get("type") + p = ev.get("payload") or {} + if m == "thread/tokenUsage/updated": + last = (p.get("token_usage") or {}).get("total") or last + if p.get("thread_id") and p["thread_id"] not in threads: + threads.append(p["thread_id"]) + elif m in ("error", "fatal", "timeout"): + errors.append(ev) + elif m == "item/completed": + it = _item_of(ev) + t = it.get("type") + items.append(t) + if t == "agentMessage": + tw.add_step("agent", message=it.get("text", "")) + elif t == "reasoning": + tw.add_step("agent", reasoning=json.dumps(it.get("summary") or it.get("content") or "")) + elif t in ("mcpToolCall", "dynamicToolCall", "commandExecution", "fileChange"): + name = it.get("tool") or t + tw.add_step("agent", tool_calls=[dict(tool_call_id=it.get("id"), function_name=name, + native_name=f"{it.get('server', '')}.{name}", + item_type=t, arguments=it.get("arguments"), + session=sdir)]) + res = it.get("result") or {} + texts = [c.get("text", "") for c in res.get("content") or [] if c.get("type") == "text"] + imgs = sum(1 for c in res.get("content") or [] if c.get("type") == "image") + tw.add_result(it.get("id"), "\n".join(texts) if texts else json.dumps(it.get("error")), + bool(it.get("error")) or it.get("status") == "failed", imgs) + if last: + usage["input"] += last.get("input_tokens") or 0 + usage["cached"] += last.get("cached_input_tokens") or 0 + usage["output"] += last.get("output_tokens") or 0 + usage["reasoning"] += last.get("reasoning_output_tokens") or 0 + # Framework close-out uses the same counted gateway shell, outside + # the model stream. Keep it visible in trajectories and tool totals. + session_record = next((s for s in run.get("sessions", []) + if sdir == f"session_{s['number']:03d}"), {}) + handoff = session_record.get("handoff") or {} + if handoff: + call_id = f"framework-handoff-{sdir}" + tw.add_step("framework", tool_calls=[dict( + tool_call_id=call_id, function_name="shell", native_name=f"{MCP_SERVER}.shell", + item_type="frameworkToolCall", arguments=handoff["arguments"], session=sdir)]) + tw.add_result(call_id, "\n".join(c.get("text", "") for c in handoff["content"] + if c.get("type") == "text")) + v = self.version() + tw.set_header(session_id=",".join(threads), source="rpent/sessions/*/codex.out.stream.jsonl", + agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort, + rpent=v["rpent"]), tools=EXPECTED_TOP_GENERIC) + tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], item_types=sorted(set(items)), + run={k: run.get(k) for k in ("stop", "finished", + "attempts_failed", "tool_calls")}, + sessions=len(run.get("sessions") or [])), + total_prompt_tokens=usage["input"], total_completion_tokens=usage["output"], + total_cached_tokens=usage["cached"], total_cost_usd=None, reasoning_tokens=usage["reasoning"]) + tw.write() + h.info.update(items=items, traj=tw, threads=threads, errors=errors, run=run) + return tw + + # ------------------------------------------------------------------------------------------------ audit + def audit(self, h): + spec, ep = h.spec, h.ep + v, notes = [], [] + items = h.info.get("items") or [] + bad = sorted({i for i in items if i not in ("userMessage", "agentMessage", "reasoning", "mcpToolCall", + "plan", "hookPrompt")}) + if bad: + v.append(f"items other than messages / reasoning / MCP calls: {bad}") + residual = [] + tw = h.info.get("traj") + for st in (tw.steps if tw else []): + for tc in st["tool_calls"]: + if tc["native_name"] == f"{MCP_SERVER}.{tc['function_name']}" and tc["function_name"] in MCP_TOOLS: + continue + if tc["function_name"] in ("list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"): + residual.append(tc["function_name"]) + else: + v.append(f"unexpected tool call {tc['native_name']}") + if residual: + notes.append(f"residual MCP-resource tool calls (empty): {residual}") + if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env): + v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}") + run = h.info.get("run") or {} + nsess = len(run.get("sessions") or []) + if len(h.info.get("threads") or []) > max(1, nsess): + v.append(f"{len(h.info['threads'])} Codex threads for {nsess} RPent sessions") + if nsess > 1: + notes.append(f"{nsess} RPent sessions (handoff after a session ended before the episode was over)") + if run.get("stop") not in (None, "episode over"): + notes.append(f"RPent stopped: {run.get('stop')}") + left = dict(codex_home=snapshot_tree(spec.state_dirs["codex_home"]), home=snapshot_tree(spec.state_dirs["home"]), + work=snapshot_tree(spec.cwd)) + if left["work"]: + v.append(f"files in the work dir: {left['work']}") + foreign = [f for f in left["codex_home"] if f.startswith(("sessions/", "archived_sessions/")) + and not any(t in f for t in (h.info.get("threads") or []))] + if foreign: + v.append(f"session files other than this run's threads: {foreign}") + gt = os.path.join(ep.log_dir, "gateway_transcript.jsonl") + faces = set() + if os.path.exists(gt): + for line in open(gt): + try: + d = json.loads(line) + except ValueError: + continue + if d.get("ev") == "tool" and d.get("face"): + faces.add(d["face"]) + if faces - {"rpent"}: + v.append(f"gateway calls from other access paths: {sorted(faces)}") + out = dict(harness=self.name, violations=v, notes=notes, files_left=left, gateway_faces=sorted(faces), + item_types=sorted(set(items)), errors=h.info.get("errors"), run_stop=run.get("stop"), ok=not v) + with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f: + json.dump(out, f, indent=1) + return out diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/sensenova.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/sensenova.py new file mode 100644 index 0000000000000000000000000000000000000000..8ab4298a5dee42672e540be1b240c677754b8203 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/sensenova.py @@ -0,0 +1,24 @@ +"""SenseNova-RoboRSI native Codex SDK planner, controlled MCP variant.""" +from .framework_codex import RobotFrameworkCodex + +class SenseNovaCodex(RobotFrameworkCodex): + name = "sensenova_codex" + runtime_home = "/mnt/cpfs/workspace/env/sensenova-roborsi" + + def __init__(self, **kwargs): + kwargs.setdefault("sessions", 1) + kwargs.setdefault("attempts_per_session", 0) + if kwargs["sessions"] != 1 or kwargs["attempts_per_session"] != 0: + raise ValueError("SenseNova controlled variant uses one persistent session for all attempts") + super().__init__(**kwargs) + + def env(self, state, ep, base_url, work): + env = super().env(state, ep, base_url, work) + env["LFF_CONTROLLED_CODEX"] = "1" + return env + + def config_info(self): + info = super().config_info() + info.update(variant="native-codex-planner-mcp", max_sdk_steps=self.max_turns, + history="same-thread", cross_episode_memory=False) + return info diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/trajectory.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/trajectory.py new file mode 100644 index 0000000000000000000000000000000000000000..890edb2f16a015c2caa39bea7fb8a5511dacc545 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/trajectory.py @@ -0,0 +1,86 @@ +"""Unified trajectory (minimal, field names follow Harbor's ATIF where there is one). + +/trajectory.jsonl, one JSON object per line: + line 1 {"kind": "header", "schema": "lff-traj-0", "atif_like": "ATIF v1.x field names", "session_id", + "agent": {"name", "version", "model_name", "effort"}, "tools": [...], "source": ""} + steps {"kind": "step", "step_id", "timestamp", "source": "user"|"agent"|"system", "message", + "reasoning_content", "tool_calls": [{"tool_call_id", "function_name", "arguments"}], + "observation": {"results": [{"source_call_id", "content", "is_error", "images"}]}, + "metrics": {"prompt_tokens", "completion_tokens", "cached_tokens", "cost_usd"}} + last {"kind": "final", "final_metrics": {"total_prompt_tokens", "total_completion_tokens", + "total_cached_tokens", "total_cost_usd", "total_steps"}, "exit_reason", "native_result"} +Not full ATIF: no per-step model name, no subagent trajectories, images only counted (bytes stay in the workspace). +Tool names are reported without the MCP prefix (robot / shell / view_images), so all harnesses line up. +""" +import json +import os + +SCHEMA = "lff-traj-0" + + +def strip_mcp(name): + for p in ("mcp__lff__", "lff."): + if name and name.startswith(p): + return name[len(p):] + return name + + +class TrajWriter: + def __init__(self, path): + self.path = path + self.steps = [] + self.header = None + self.final = None + + def set_header(self, **kw): + self.header = dict(kind="header", schema=SCHEMA, atif_like="field names follow Harbor ATIF", **kw) + + def add_step(self, source, message="", reasoning="", tool_calls=None, timestamp=None, metrics=None, **extra): + st = dict(kind="step", step_id=len(self.steps) + 1, timestamp=timestamp, source=source, message=message or "", + reasoning_content=reasoning or "", tool_calls=tool_calls or [], + observation=dict(results=[]), metrics=metrics or {}) + st.update(extra) + self.steps.append(st) + return st + + def add_result(self, call_id, content, is_error=False, images=0): + for st in reversed(self.steps): + if any(tc["tool_call_id"] == call_id for tc in st["tool_calls"]): + st["observation"]["results"].append(dict(source_call_id=call_id, content=content, is_error=is_error, + images=images)) + return True + return False + + def set_final(self, exit_reason, native_result=None, **metrics): + fm = dict(total_prompt_tokens=0, total_completion_tokens=0, total_cached_tokens=0, total_cost_usd=None, + total_steps=len(self.steps)) + fm.update({k: v for k, v in metrics.items() if v is not None}) + self.final = dict(kind="final", final_metrics=fm, exit_reason=exit_reason, native_result=native_result) + + def write(self): + with open(self.path, "w") as f: + for d in [self.header] + self.steps + [self.final]: + if d is not None: + f.write(json.dumps(d, ensure_ascii=False) + "\n") + return self.path + + def tool_call_names(self): + return [tc["function_name"] for st in self.steps for tc in st["tool_calls"]] + + +def read(path): + with open(path) as f: + return [json.loads(line) for line in f if line.strip()] + + +def usage_summary(log_dir): + """Token / cost totals from trajectory.jsonl (None if missing).""" + p = os.path.join(log_dir or "", "trajectory.jsonl") + if not os.path.exists(p): + return None + rows = read(p) + fin = next((r for r in rows if r.get("kind") == "final"), None) + steps = [r for r in rows if r.get("kind") == "step" and r.get("source") == "agent"] + out = dict(calls=len(steps), exit_reason=(fin or {}).get("exit_reason")) + out.update((fin or {}).get("final_metrics") or {}) + return out diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/DRIVER.md b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/DRIVER.md new file mode 100644 index 0000000000000000000000000000000000000000..3ac1e4511c50001e98cc06ea902688a42a37ddaa --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/DRIVER.md @@ -0,0 +1,144 @@ +# LFF-Bench 真机驱动说明(给负责机械臂的同学) + +> 协议版本 1(`protocol.py` 的 `PROTOCOL_VERSION`)。2026-10-19 起草;参考实现是仿真版假驱动 `fake_driver.py`, +> 它通过了本文 §7 的自检和 `tests/real_selfcheck.py` 的全部对照。 + +## 0. 一句话 + +你只需要在机器人电脑上跑一个**驱动进程**:收到 HTTP 请求就动臂、动夹爪、拍两张照片,或者在终端里问操作员。 +模型、harness、命令预算、尝试次数、日志都在跑评测的那台机器上,你那边不用装。 + +``` +评测机(跑模型的人) 机器人电脑(你) +Codex / Claude Code(订阅) 驱动进程 ← 你写,从 driver_template.py 改 + └ MCP:robot / shell / view_images ├ 机械臂 SDK(松灵 PiPER ……) + └ 真机版 robot_server(预算、尝试、README、日志) ├ 两台相机:agentview + wrist + └ HTTP ── SSH 隧道 ──────────────────────────→ └ 操作员终端(复原场景、判成败) +``` + +模型永远看不到你的电脑,你的驱动也不知道模型是谁。所有运动只走 `/move`、`/gripper`、`/home` 三个接口。 + +## 1. 你要交付的东西 + +1. 驱动进程:`driver_template.py` 里 5 个 TODO(连臂、笛卡尔直线运动、读位姿、夹爪、取图),`/ik` 可选。 +2. 两台相机:`agentview`(固定,能看到整个工作区)和 `wrist`(装在夹爪上)。 +3. 场景道具,见 §6。 +4. `scripts/real_check_driver.py` 全部 PASS(§7)。 +5. 一位操作员,按 §8 的规程操作。可以就是你。 + +需要的文件只有三个:`lffbench/real/protocol.py`、`lffbench/real/driver_template.py`、`scripts/real_check_driver.py`。 +放在同一个目录即可。依赖:Python 3、numpy、Pillow;录像另需 imageio + imageio-ffmpeg;再加上你的臂和相机 SDK。 + +## 2. 坐标与约定(最重要的一节) + +| 量 | 约定 | +|---|---| +| 坐标系 | 机械臂**基座坐标系**:原点在基座,+x 是机器人正前方(远离基座),+y 是机器人的左手边,+z 向上;单位米 | +| 位置 `eef_pos` | **抓取点**(TCP):两指中间、比指尖高约 1 cm。在 SDK 里把 TCP 设到这里,或者自己做固定偏移 | +| 姿态 | 夹爪始终**竖直朝下**,只有一个自由度 yaw(绕基座 z 轴)。`yaw = 0`:两指沿基座 **y** 方向开合;`yaw = +90`:沿 x 方向开合;从上往下看,**正方向是逆时针** | +| yaw 范围 | `yaw_range_deg` 由你声明,跨度至少 180°(两指夹爪转 180° 等价,评测端会挑离当前 yaw 最近的等价角,保证落在你声明的范围里) | +| `gripper_width_m` | 两指尖之间的距离,单位米(空合 < 1 cm,张开 > 3 cm) | +| `joint_pos_rad` | 全部关节角(基座到腕,弧度),个数 = `n_joints` | +| `motion_s` | 这条命令实际运动了多少秒(评测按它扣"运动时间"预算:每次尝试 3 s × 命令条数) | + +这些都和仿真一致(仿真里 yaw 0 也是"沿 y 开合")。模型拿到的 README 写的是 +"You control a real `` robot arm (`` joints) with a two-finger parallel gripper",`robot` 和 `n_joints` 就取你在 `/info` 里填的值。 + +## 3. 接口 + +所有请求都是 `POST http://127.0.0.1:/`,带 JSON body,请求头 `X-Driver-Token: `。 +所有回复都是 JSON,含 `"ok": true|false`。**`"fault": true` 表示机器人不可信了**(保护性停止、急停、通信断开……),评测端会立刻结束这个 run 并标为无效。 +模板里任何未捕获的异常都会自动变成 fault。 + +| 接口 | 请求 | 回复(`ok` 之外) | 说明 | +|---|---|---|---| +| `info` | `{}` | `protocol` = 1,`robot`,`n_joints`,`cameras` = `["agentview","wrist"]`,`workspace` = `{lo:[x,y,z], hi:[x,y,z]}`,`yaw_range_deg` = `[lo,hi]`,`max_speed`(m/s),`ik`(bool),`driver_version` | 启动时调一次,内容写进每个 run 的契约 | +| `home` | `{}` | `state` | 回到初始位姿、张开夹爪。每次复原场景之前调用 | +| `move` | `{x, y, z, yaw_deg, speed}`,`speed` 可为 null(= `max_speed`) | `motion_s`,`state`;被拒时 `ok:false` + `error` | **阻塞**,臂停下才返回;尽量走笛卡尔直线(MoveL)。目标超出你的硬工作空间或者没有 IK 解时,**动之前**拒绝,回 `ok:false`(不是 fault) | +| `gripper` | `{close: true/false}` | `motion_s`,`state` | 阻塞。合爪要限力,夹到东西或合到底就停 | +| `state` | `{}` | `state` = `{eef_pos, eef_yaw_deg, gripper_width_m, joint_pos_rad}` | 报**真实**位姿。标定偏差由评测端在软件里加,驱动不要加 | +| `observe` | `{}` | `images` = `{agentview: {format, data}, wrist: {...}}`(base64 的 jpeg 或 png),`state` | 取**最新**一帧(先清相机缓冲)。任意分辨率都行:评测端会中心裁成正方形、缩到 512²,再存成 JPEG q90 | +| `ik` | `{eef_pos, yaw_deg}` | `joint_pos_rad` | 可选,只有 `real_bias_place` 需要(`info.ik = true`)。只算不动;返回离当前关节角最近的解 | +| `operator` | `{kind: reset/judge/notice, run, attempt, setup, checklist, text}` | reset:`{}`;judge:`{success, note}` | 模板里已经实现成终端提示,会阻塞到操作员回答为止(§8) | +| `event` | `{ev, run, attempt}`,`ev` ∈ session_start / attempt_start / attempt_end / episode_end / session_end / run_invalid | `{}` | 用来开始、停止录像。模板在 attempt_start 开录、attempt_end 停录,每次尝试存一个 mp4 | + +驱动是单线程的:请求一条一条执行,操作员提示没回答之前,别的请求都在排队,所以复原场景时臂不会动。 + +## 4. 安全(必须做) + +- **硬工作空间**:驱动自己检查(模板的 `_inside` 已经写好)。z 下限要保证指尖离桌面至少 5 mm;盒子任务要用指尖贴近桌面推,所以 z 下限别留太高。 +- **速度上限**:`max_speed` 建议不超过 0.25 m/s。模型可以要求更慢,但不能更快。 +- **力保护**:推盒子本来就要接触物体,但模型也可能让夹爪压桌面、撞东西。打开臂自带的碰撞检测或电流保护;保护停止触发时回 fault。 +- **急停**放在操作员手边。急停之后这个 run 作废,在 judge 提示里选 `x`,或者驱动自己回 fault。 +- `/move` 里**不要做任何"聪明"的补偿**,比如自动抬高、自动避障、自动纠偏。那样会改变任务本身。超范围就拒绝,其他情况照命令执行。 + +## 5. 模型那边看到的和你有关的东西 + +- 每条命令之后的两张图(agentview、wrist)和末端状态。所以 agentview 必须拍到整个工作区:盒子、目标框、起点。 + 光照要稳定;模型运行时,画面里不要有人和多余的东西。 +- 被拒绝的目标,模型看到的是 "target rejected: the arm cannot reach it; the arm did not move"。 +- 评测端声明给模型的工作空间就是你 `/info` 里的 `workspace`(`real_bias_place` 会在 xy 方向每边再缩 4 cm)。模型不知道具体数值,只会在越界时被拒。 + +## 6. 两个任务的场景 + +实例(配重放哪、布局用哪组)由种子决定,每次复原前会显示在你的终端里,照做就行。正式 run 用 5000 以后的种子。 + +### 6.1 `real_offcenter_push`:重心偏的长盒子推进绿框(对应仿真 `l7_offcenter_push`) + +模型看到的指令(与仿真相同):*Slowly push the long brown box with the closed gripper so that it ends up completely inside the green rectangle ahead of it (farther from the robot).* + +- **盒子**:不透明的棕色长盒(纸盒或 3D 打印都行),带盖。仿真尺寸是 9 × 22 × 4 cm(沿推的方向 × 长 × 高)。 + 可以按 PiPER 的可达范围缩小,但沿推的方向的尺寸要比夹爪最大开口宽至少 2 cm,保证夹不起来。长边横放(沿 y)。 +- **配重**:盒内每端隔两格(最外一格、往里一格),共 4 格。配重块(钢块、铅块)放在实例指定的那一格;空格可以塞泡沫,免得配重滑动。 + 合上盖子,两端外观一模一样,贴同样的胶带。 +- **起点**:桌上贴定位角标,盒子每次都按角标摆,长边横放。 +- **目标框**:绿色胶带围成的矩形,每边比盒子底面大 2 cm,在起点正前方,框中心离盒子中心 8–13 cm(仿真值;选一个固定值就行)。 +- **桌面**:摩擦要均匀,盒子不能一推就滑出去很远。 +- **先验证 headroom(必须做,不用模型)**:合上夹爪,以 5–8 cm/s 推盒子背面中点,盒子要明显转动(仿真里转 25–33°,转完就出框); + 对准重心正后方推,盒子要基本不转、能进框。转得不明显就加重配重、把配重往外移,或者换更滑的桌垫。左右两种配重位置各试几次,记下来。 +- **判成功**(终端里显示的清单):盒子四个底角都在绿框内(压线算出框);盒子没翻倒;一直是合着夹爪推的;夹爪没碰着盒子。 + +### 6.2 `real_bias_place`:带标定偏差的抓放(对应仿真 `l1_bias_place`) + +模型看到的指令:*Pick up the red cube and put it into the bowl.* + +- 红色方块(约 4 cm,能稳稳夹起),一个浅碗(内径 ≥ 12 cm)。 +- 桌上贴 4 组标记 A–D:`A1` 放方块、`A2` 放碗,B、C、D 同理。各组之间、方块和碗之间都相距 ≥ 20 cm,全部在工作空间内,离工作空间边界 ≥ 5 cm。 +- **偏差不用你管**:评测端给每条命令加一个隐藏的 2.5–4 cm 水平偏移,回报位姿时再减掉,臂本身不变。 + 但你需要实现 `/ik`(并把 `info()` 里的 `ik` 改成 True),否则回报的关节角会泄露偏差,评测端会拒绝启动这个任务。 +- **判成功**:方块在碗里(落在碗底,不在碗沿上);夹爪张开,没夹着方块。 + +## 7. 联调步骤 + +1. 把 §1 的三个文件拷到机器人电脑上,填好 `driver_template.py` 的 TODO 和顶部的配置(`ROBOT`、`N_JOINTS`、`WORKSPACE_*`、`YAW_RANGE_DEG`、`HOME`)。 +2. 启动驱动(token 自己定,私下发给跑评测的人): + ```bash + python driver_template.py --port 9900 --token --log driver_logs + ``` +3. 在机器人电脑上自检。臂会小幅运动:上下 3 cm、转 30°、开合夹爪,速度 5 cm/s,手放在急停上: + ```bash + python real_check_driver.py --driver http://127.0.0.1:9900 --token --operator + ``` + 全部 PASS 才算完成;WARN 要看一下原因,NOTE 要人工确认(yaw 正方向是否为逆时针)。 +4. 建 SSH 隧道,让评测机能访问 `127.0.0.1:9900`。二选一: + - 评测机能 ssh 到机器人电脑:在评测机上执行 `ssh -N -L 9900:127.0.0.1:9900 @<机器人电脑>` + - 只能反过来连:在机器人电脑上执行 `ssh -N -R 9900:127.0.0.1:9900 @<评测机>` +5. 跑评测的人在评测机上经隧道再跑一次 `real_check_driver.py`(加 `--yes`)。 +6. 正式 run:评测机启动 session 后,你的终端会先出现 **RESET** 提示:按 setup 摆好场景,人离开画面,回车,模型开始操作。 + 一次尝试结束时出现 **JUDGE** 提示:按清单判 y / n / x。还有下一次尝试的话,臂会先回 home,再出现 RESET 提示。 + +## 8. 操作员规程 + +- 只照终端提示做;setup 要严格照做,每次复原都一样(角标对齐、配重格子对、盖子合好)。 +- 模型运行期间,人不进相机画面,不碰场景,也不对任何人说配重在哪(除非要急停)。 +- 判 y / n 只看清单本身,不看模型"努力了没有"。 +- `x` = 这个 run 作废:机器人报错、相机掉线、有人碰了场景、配重摆错了。note 里写一句原因。 +- 时间:模型每步要几秒到几十秒,一个 run 大约 15–60 分钟(估计,没实测),最长一次尝试约 40 条命令。 + +## 9. 常见问题 + +- **相机不是正方形**:可以。评测端会中心裁成正方形,两边各裁掉 (宽−高)/2 像素,所以工作区要在画面中间。 +- **被物体挡住、没到目标**:位置控制会继续顶。设好电流或力矩保护;保护停止就回 fault,没触发就照常返回,模型会从位姿和图里看出没到。 +- **到不了的目标**:`/move` 回 `ok:false` + `error`,并且不能动。不要回 fault。 +- **延迟**:每个请求 1 秒内回完就行(取图建议 < 0.5 s)。瓶颈在模型。 +- **PiPER 的 SDK 细节**:模板里只写了提示,没有在真机上验证过,以 SDK 文档为准。 diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/__init__.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b5513b07c27d6c467f8fd55f228d50d4aef4b482 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/__init__.py @@ -0,0 +1,10 @@ +"""Real-robot backend of LFF-Bench (docs/17): the same agent interface as simulation, with a robot driver underneath. + + protocol.py driver protocol v1 (both sides; stdlib + numpy + Pillow only) + executor.py RealToolExecutor: robot_server's executor on top of a driver (calibration bias injected here) + session.py RealRobotSession: robot_server's LA session without the simulator; python -m lffbench.real.session + tasks.py real-robot tasks (setup sheet, operator checklist, hidden variable from the seed) + fake_driver.py a driver backed by the simulator (no hardware) + driver_template.py skeleton for a hardware driver (copy to the robot PC with protocol.py) + DRIVER.md spec for the driver author and the operator +""" diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/driver_template.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/driver_template.py new file mode 100644 index 0000000000000000000000000000000000000000..e9381480b80fc81dc062c16f1a40b8ebe0475158 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/driver_template.py @@ -0,0 +1,196 @@ +"""Skeleton of a hardware driver for LFF-Bench (spec: DRIVER.md). Copy this file and protocol.py to the robot PC, +fill in the five methods marked TODO, run scripts/real_check_driver.py until every check passes. + + python driver_template.py --port 9900 [--token ] [--log ] + +Only Python 3 + numpy + Pillow are needed here (plus your robot / camera SDKs). Keep the server on 127.0.0.1; the +benchmark machine reaches it through an SSH tunnel (DRIVER.md §7). + +What is already done for you: the HTTP protocol, the token, the operator's terminal prompts, the safety checks that +must run before every motion (hard workspace box, speed limit), the motion timing, and an optional recorder that saves +both cameras to an mp4 per attempt. Everything robot-specific is in the TODO methods. +""" +import argparse +import os +import threading +import time + +import numpy as np + +try: # copied next to protocol.py on the robot PC + from protocol import CAMERAS, PROTOCOL_VERSION, DriverServer, square_resize +except ImportError: # inside the repo (python -m lffbench.real.driver_template) + from .protocol import CAMERAS, PROTOCOL_VERSION, DriverServer, square_resize + +# ---------------------------------------------------------------------------------------------- your setup (edit) +ROBOT = "AgileX PiPER" # TODO: the arm's name as the agent will read it ("You control a real robot arm") +N_JOINTS = 6 # TODO +# Hard workspace of the GRASP POINT in the robot-base frame (metres). Rejected targets never move the arm. Choose it so +# that every point inside is reachable with the gripper pointing straight down at any yaw in YAW_RANGE_DEG, and the +# lower z bound keeps the fingertips >= 5 mm above the table (the boxes are pushed with the fingertips ~1 cm up). +WORKSPACE_LO = [0.15, -0.25, 0.00] # TODO: measure on your table +WORKSPACE_HI = [0.45, 0.25, 0.30] # TODO +YAW_RANGE_DEG = [-120.0, 120.0] # TODO: gripper yaw your wrist reaches (span >= 180) +MAX_SPEED = 0.25 # m/s, the fastest straight-line speed you allow (the agent may ask for less) +HOME = dict(x=0.25, y=0.0, z=0.20, yaw_deg=0.0) # TODO: above the table centre, out of the agentview's way if possible +REACH_TOL = 0.004 # m: a move counts as finished when within this of the target and stopped +MOVE_TIMEOUT = 30.0 # s +DRIVER_VERSION = "template-0" # TODO: your git commit / date + + +class MyDriver(DriverServer): + image_format = "jpeg" # "png" is lossless but ~5x larger; jpeg q95 is fine over a LAN / SSH tunnel + + def __init__(self, record_dir=""): + self.lock = threading.RLock() # hardware access from the recorder thread and from requests + self.record_dir = record_dir + self.recorder = None + # TODO: connect to the arm, enable it, set the TCP (grasp point = midway between the fingertips, about 1 cm + # above their tips), open the cameras. Example for PiPER (piper_sdk; check the SDK docs, not verified here): + # from piper_sdk import C_PiperInterface_V2 + # self.arm = C_PiperInterface_V2("can0"); self.arm.ConnectPort(); ... enable ... + # Cameras: "agentview" = fixed camera looking at the table from the front/side (sees the whole work area); + # "wrist" = camera on the gripper. E.g. cv2.VideoCapture / pyrealsense2 colour stream. + raise NotImplementedError("connect the arm and the cameras") + + # ------------------------------------------------------------------ TODO 1: low-level hardware + def _send_cartesian(self, x, y, z, yaw_deg, speed): + """Start a straight-line (MoveL) motion of the grasp point to (x, y, z) with the gripper pointing straight down + and rotated by yaw_deg about the base z axis (0 = fingers close along the base y axis, +90 = along the base x + axis, counter-clockwise seen from above). Return False if the controller refuses (no IK).""" + raise NotImplementedError + + def _read_pose(self): + """-> (xyz of the grasp point in the base frame [m], yaw_deg, joint angles [rad], is_moving: bool).""" + raise NotImplementedError + + def _set_gripper(self, close): + """Close (force-limited, stop when blocked) or open fully; return when the fingers have stopped.""" + raise NotImplementedError + + def _gripper_width(self): + """Opening between the fingertips, metres.""" + raise NotImplementedError + + def _grab(self): + """-> {"agentview": HxWx3 uint8 RGB, "wrist": ...}: the newest frames (flush camera buffers first).""" + raise NotImplementedError + + def ik(self, eef_pos, yaw_deg): + """Optional (set info()["ik"] = True), needed only for real_bias_place: joint angles that put the grasp point + at eef_pos / yaw_deg (pointing down), the solution closest to the current joints. Do NOT move the arm.""" + raise NotImplementedError + + # ------------------------------------------------------------------ protocol (normally no need to edit) + def info(self): + return dict(protocol=PROTOCOL_VERSION, robot=ROBOT, n_joints=N_JOINTS, cameras=list(CAMERAS), + workspace=dict(lo=WORKSPACE_LO, hi=WORKSPACE_HI), yaw_range_deg=YAW_RANGE_DEG, max_speed=MAX_SPEED, + ik=False, driver_version=DRIVER_VERSION) + + def state(self): + with self.lock: + xyz, yaw, q, _ = self._read_pose() + return dict(eef_pos=[float(v) for v in xyz], eef_yaw_deg=float(yaw), gripper_width_m=float(self._gripper_width()), + joint_pos_rad=[float(v) for v in q]) + + def _inside(self, x, y, z, yaw_deg): + p = np.array([x, y, z]) + return (bool(np.all(p >= WORKSPACE_LO) and np.all(p <= WORKSPACE_HI)) + and YAW_RANGE_DEG[0] <= yaw_deg <= YAW_RANGE_DEG[1]) + + def move(self, x, y, z, yaw_deg, speed): + if not self._inside(x, y, z, yaw_deg): + return False, "outside the hard workspace", 0.0 + speed = MAX_SPEED if speed is None else float(np.clip(speed, 0.005, MAX_SPEED)) + with self.lock: + t0 = time.time() + if not self._send_cartesian(x, y, z, yaw_deg, speed): + return False, "no IK solution", 0.0 + tgt = np.array([x, y, z]) + while True: # blocking: return only once the arm has stopped + xyz, _, _, moving = self._read_pose() + if not moving and np.linalg.norm(np.asarray(xyz) - tgt) < REACH_TOL: + break + if time.time() - t0 > MOVE_TIMEOUT: + if not moving: + break # stopped short (blocked by an object): a normal outcome, the agent sees the pose + raise RuntimeError("move timed out while still moving") # -> fault: the run stops + time.sleep(0.02) + return True, None, time.time() - t0 + + def gripper(self, close): + with self.lock: + t0 = time.time() + self._set_gripper(close) + return time.time() - t0 + + def home(self): + ok, err, _ = self.move(HOME["x"], HOME["y"], HOME["z"], HOME["yaw_deg"], 0.15) + if not ok: + raise RuntimeError(f"cannot reach the home pose: {err}") + self.gripper(False) + return self.state() + + def images(self): + with self.lock: + return self._grab() + + def event(self, ev, run="", attempt=None, **kw): + if not self.record_dir: + return + if ev == "attempt_start": + self._stop_recording() + try: + self.recorder = Recorder(self, os.path.join(self.record_dir, f"{run}_a{attempt}.mp4")) + except Exception as e: # the video is only for the record: a missing imageio must not end a run as a fault + print(f"WARNING: recorder not started ({type(e).__name__}: {e}); " + "pip install imageio imageio-ffmpeg", flush=True) + elif ev in ("attempt_end", "episode_end", "session_end", "run_invalid"): + self._stop_recording() + + def _stop_recording(self): + if self.recorder is not None: + self.recorder.stop() + self.recorder = None + + +class Recorder(threading.Thread): + """agentview | wrist side by side at ~5 fps while an attempt runs (needs imageio + imageio-ffmpeg).""" + + def __init__(self, drv, path, fps=5, res=360): + super().__init__(daemon=True) + import imageio + self.drv, self.fps, self.res, self.halt = drv, fps, res, threading.Event() + os.makedirs(os.path.dirname(path) or ".", exist_ok=True) + self.w = imageio.get_writer(path, fps=fps, macro_block_size=8) + self.start() + + def run(self): + while not self.halt.is_set(): + t0 = time.time() + try: + with self.drv.lock: + f = self.drv._grab() + self.w.append_data(np.concatenate([square_resize(f[c], self.res) for c in CAMERAS], axis=1)) + except Exception as e: # never let the recorder break a run + print("recorder:", e) + self.halt.wait(max(0.0, 1.0 / self.fps - (time.time() - t0))) + + def stop(self): + self.halt.set() + self.join(timeout=5) + self.w.close() + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--port", type=int, default=9900) + ap.add_argument("--token", default=os.environ.get("LFF_DRIVER_TOKEN", "")) + ap.add_argument("--log", default="driver_logs", help="operator answers (operator.jsonl) and attempt videos") + a = ap.parse_args() + os.makedirs(a.log, exist_ok=True) + MyDriver(record_dir=a.log).serve(a.port, token=a.token or None, operator_log=os.path.join(a.log, "operator.jsonl")) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/executor.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/executor.py new file mode 100644 index 0000000000000000000000000000000000000000..edb5a9a3932e891684f2a2c17bb8024c994d46dd --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/executor.py @@ -0,0 +1,138 @@ +"""RealToolExecutor: the real-robot counterpart of lffbench.agent.tools.ToolExecutor. + +robot_server's LA interface needs only this from its executor: observe(label) -> [ImageRef], proprio() -> dict, and +call("move_to" | "open_gripper" | "close_gripper", args) -> ToolResult. Here every call goes to a robot driver +(lffbench/real/protocol.py) instead of the simulator. + +Calibration bias (L1 tasks), as Skills / ToolExecutor do it in simulation: the driver is sent commanded + bias and +reports the true pose; the agent is told true - bias (what a miscalibrated robot believes). Joint angles are then the +ones that put the grasp point at the believed pose (driver /ik), as robot_server._believed_joints does in simulation. +""" +import math +import time + +import numpy as np + +from ..agent.images import ImageRef +from ..agent.tools import ToolResult, parse_args +from .protocol import CAMERAS, DriverError, square_resize, state_problems + +SPEED_MIN = 0.01 # m/s; below this a straight-line move takes too long to be useful + + +def _r(v, nd=4): + return [round(float(x), nd) for x in v] + + +class RealToolExecutor: + def __init__(self, driver, info, bias=None, image_res=512, cams=CAMERAS): + self.driver, self.info = driver, info + self.bias = np.zeros(3) if bias is None else np.asarray(bias, float) + self.image_res = int(image_res) + self.cams = tuple(cams) + self.n_joints = int(info["n_joints"]) + self.yaw_lo, self.yaw_hi = (float(v) for v in info["yaw_range_deg"]) + self.max_speed = float(info["max_speed"]) + self.motion_s = 0.0 # robot motion time of this executor (= this attempt), as reported by the driver + self.n_calls = 0 + self._state = None + self.grip_closed = False # last gripper command of this attempt (the driver's home pose has it open) + self.yaw_cmd = None # last commanded yaw (degrees), for choosing among the gripper-symmetric equivalents + self.refresh() + self.yaw_cmd = float(self._state["eef_yaw_deg"]) + + # ------------------------------------------------------------------ state + def _set_state(self, st): + prob = state_problems(st, self.n_joints) + if prob: + raise DriverError("driver state: " + "; ".join(prob)) + self._state = st + + def refresh(self): + self._set_state(self.driver.state()) + + def true_eef(self): + return np.asarray(self._state["eef_pos"], float) + + def believed_eef(self): + return self.true_eef() - self.bias + + def proprio(self): + st = self._state + return dict(eef_pos=_r(self.believed_eef()), eef_yaw_deg=round(float(st["eef_yaw_deg"]), 1), + gripper="closed" if self.grip_closed else "open", + gripper_width_m=round(float(st["gripper_width_m"]), 4)) + + def joints(self): + """Joint angles as the robot's encoders would report them under the hidden calibration error.""" + if not np.any(self.bias): + return [float(v) for v in self._state["joint_pos_rad"]] + key = (tuple(self._state["eef_pos"]), float(self._state["eef_yaw_deg"])) + if getattr(self, "_ik_key", None) != key: # one /ik per new state (the server asks several times per command) + self._ik_key = key + self._ik_val = [float(v) for v in self.driver.ik(self.believed_eef(), key[1])] + return list(self._ik_val) + + def observe(self, label=""): + frames, st = self.driver.observe() + self._set_state(st) + return [ImageRef(camera=c, array=square_resize(frames[c], self.image_res), label=f"{label} {c}".strip()) + for c in self.cams] + + # ------------------------------------------------------------------ helpers + def wrap_yaw(self, yaw): + """The two-finger gripper is symmetric: among yaw + k*180 inside the driver's yaw range, use the one closest to + the last commanded yaw (Skills.wrap_yaw does the same with its +-113 deg limit).""" + cands = [yaw + 180.0 * k for k in range(-3, 4)] + ok = [c for c in cands if self.yaw_lo <= c <= self.yaw_hi] or cands + return float(min(ok, key=lambda c: abs(c - self.yaw_cmd))) + + # ------------------------------------------------------------------ dispatch (same signature as ToolExecutor.call) + def call(self, name, raw_args): + t0 = time.time() + self.n_calls += 1 + args = parse_args(raw_args) + fn = getattr(self, f"_t_{name}", None) + if fn is None: + return ToolResult(name, args, False, dict(ok=False, error=f"unknown tool {name!r}"), wall_s=time.time() - t0) + res = fn(**args) + res.args, res.wall_s = args, time.time() - t0 + return res + + def _report(self, name, extra=None): + rep = dict(ok=True, tool=name) + rep.update(extra or {}) + rep.update(self.proprio()) + return rep + + def _t_move_to(self, x, y, z, yaw, speed=None): + tgt = np.array([x, y, z], float) + if not np.all(np.isfinite(tgt)): + return ToolResult("move_to", {}, False, dict(ok=False, error="non-finite coordinates")) + spd = None if speed is None else float(np.clip(float(speed), SPEED_MIN, self.max_speed)) + yaw_used = self.wrap_yaw(float(yaw)) + cmd = tgt + self.bias # the hidden calibration error acts on every commanded position + rep = self.driver.move(cmd[0], cmd[1], cmd[2], yaw_used, spd) + self.motion_s += float(rep.get("motion_s") or 0.0) + self._set_state(rep["state"]) + if not rep["ok"]: # rejected before moving (driver hard limits / no IK solution) + return ToolResult("move_to", {}, False, dict(ok=False, error="target rejected: the arm cannot reach it; " + "the arm did not move", driver_error=rep.get("error", ""))) + self.yaw_cmd = yaw_used + reached = bool(np.linalg.norm(cmd - self.true_eef()) < 0.02) + return ToolResult("move_to", {}, True, self._report("move_to", dict(reached=reached, + yaw_used_deg=round(yaw_used, 1)))) + + def _gripper(self, close): + rep = self.driver.gripper(close) + self.grip_closed = bool(close) + self.motion_s += float(rep.get("motion_s") or 0.0) + self._set_state(rep["state"]) + name = "close_gripper" if close else "open_gripper" + return ToolResult(name, {}, True, self._report(name)) + + def _t_open_gripper(self): + return self._gripper(False) + + def _t_close_gripper(self): + return self._gripper(True) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/fake_driver.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/fake_driver.py new file mode 100644 index 0000000000000000000000000000000000000000..e0ab679922417d9a537219244e17f0c03b2a60b3 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/fake_driver.py @@ -0,0 +1,152 @@ +"""Fake robot driver backed by the simulator: answers the driver protocol (lffbench/real/protocol.py) with a simulated +LFF-Bench task, so the whole real-robot path (harness -> MCP -> real robot server -> driver) runs without hardware. + +It behaves like a real driver: it reports the TRUE pose in the robot-base frame (no calibration bias of its own; the +benchmark injects the bias), sends lossless PNG frames, rejects targets outside its hard workspace, and has an +operator. The operator is the simulator unless --operator console: "reset" resets the simulated scene, "judge" is the +task's own success rule (task.outcome). + + python -m lffbench.real.fake_driver --task l7_offcenter_push --seed 3000 --port 9900 --token [--nominal] + [--operator auto|console] [--log ] + +--nominal removes the task's hidden calibration bias (L1 tasks), which is what a real arm looks like when the benchmark +injects the bias in software (real_bias_place). +""" +import argparse +import json +import math +import os +import time +import types + +import numpy as np + +from .protocol import CAMERAS, PROTOCOL_VERSION, ConsoleOperator, DriverServer + + +class SimDriver(DriverServer): + def __init__(self, task, seed, nominal=False, image_res=512, operator="auto", log_dir=""): + from ..agent import robot_server as RS # registers every simulated task + from ..agent.tools import SPEED_RANGE, WS_HI, WS_LO, ToolExecutor + from ..task_base import TASKS + self.RS, self.ToolExecutor = RS, ToolExecutor + self.task_name, self.seed, self.image_res = task, int(seed), int(image_res) + self.task = TASKS[task](cam_res=self.image_res) + self.inst = self.task.sample_instance(self.seed) + if nominal: # same rule as robot_server --nominal + for k in [k for k in self.inst if "bias" in k]: + v = self.inst[k] + self.inst[k] = [0.0] * len(v) if isinstance(v, (list, tuple)) else 0.0 if isinstance(v, (int, float)) else v + self.operator_mode = operator + self.log_dir = log_dir + if log_dir: + os.makedirs(log_dir, exist_ok=True) + self.console_op = ConsoleOperator(os.path.join(log_dir, "operator.jsonl") if log_dir else None) + self._reset() + sim = self.task.env.sim + bid = sim.model.body_name2id("robot0_base") + self.base_off = np.array(sim.data.body_xpos[bid], float).copy() + self.ws_lo, self.ws_hi = WS_LO - self.base_off, WS_HI - self.base_off + self.max_speed = float(SPEED_RANGE[1]) + self.yaw_limit_deg = math.degrees(self.task.sk.YAW_LIMIT) + + def _reset(self): + self.task.reset_instance(self.inst) + self.ex = self.ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=CAMERAS) + + def _log(self, d): + if self.log_dir: + with open(os.path.join(self.log_dir, "driver_events.jsonl"), "a") as f: + f.write(json.dumps(dict(d, t=time.time()), default=str) + "\n") + + # ------------------------------------------------------------------ protocol + def info(self): + return dict(protocol=PROTOCOL_VERSION, robot="Franka Emika Panda (fake driver, simulated)", n_joints=7, + cameras=list(CAMERAS), workspace=dict(lo=self.ws_lo.round(6).tolist(), hi=self.ws_hi.round(6).tolist()), + yaw_range_deg=[-self.yaw_limit_deg, self.yaw_limit_deg], max_speed=self.max_speed, ik=True, + driver_version=f"fake_driver sim:{self.task_name} seed:{self.seed}") + + def home(self): + # the simulated arm goes home with the scene reset that always follows (operator "reset") + return self.state() + + def move(self, x, y, z, yaw_deg, speed): + tgt = np.array([x, y, z], float) + if not (np.all(tgt >= self.ws_lo - 1e-9) and np.all(tgt <= self.ws_hi + 1e-9)): + return False, "outside the hard workspace", 0.0 + w = tgt + self.base_off + n0 = self.task.sk.n_steps + mv = dict(x=float(w[0]), y=float(w[1]), z=float(w[2]), yaw=float(yaw_deg)) + if speed is not None: + mv["speed"] = float(speed) + res = self.ex.call("move_to", mv) + if not res.ok: + return False, res.report.get("error", "rejected"), 0.0 + return True, None, (self.task.sk.n_steps - n0) * 0.05 + + def gripper(self, close): + n0 = self.task.sk.n_steps + self.ex.call("close_gripper" if close else "open_gripper", {}) + return (self.task.sk.n_steps - n0) * 0.05 + + def _joints(self): + rob = self.task.env.robots[0] + return self.task.env.sim.data.qpos[np.array(rob._ref_joint_pos_indexes)].copy() + + def state(self): + sk = self.task.sk + return dict(eef_pos=[float(v) for v in sk.eef_pos() - self.base_off], eef_yaw_deg=float(self.ex.eef_yaw_deg()), + gripper_width_m=float(sk.gripper_width()), joint_pos_rad=[float(v) for v in self._joints()]) + + def images(self): + return {r.camera: r.array for r in self.ex.observe()} + + def ik(self, eef_pos, yaw_deg): + """Joint angles for the grasp point at eef_pos (base frame) with the current orientation: the same damped + least squares as robot_server._believed_joints (yaw_deg is the current yaw here).""" + sk = self.task.sk + T_true = np.eye(4) + T_true[:3, :3], T_true[:3, 3] = sk.eef_mat(), sk.eef_pos() + T_b = T_true.copy() + T_b[:3, 3] = np.asarray(eef_pos, float) + self.base_off + shim = types.SimpleNamespace(task=self.task, _believed_pose=lambda: (T_b, T_true)) + return [float(v) for v in self.RS._believed_joints(shim)] + + def operator(self, kind, **kw): + self._log(dict(ev="operator", kind=kind, **{k: v for k, v in kw.items() if k != "checklist"})) + if kind == "reset": + if self.operator_mode == "console": + self.console_op(kind, **kw) + self._reset() + return dict(ok=True) + if kind == "judge": + out = self.task.outcome(self.inst) + if self.operator_mode == "console": + kw = dict(kw, text=(kw.get("text", "") + f"\n(simulator says: success={bool(out['success'])}, " + f"{out.get('failure') or out.get('detail') or ''})")) + return self.console_op(kind, **kw) + return dict(ok=True, success=bool(out["success"]), + note=str(out.get("failure") or ("ok" if out["success"] else ""))) + return dict(ok=True) + + def event(self, ev, **kw): + self._log(dict(ev=ev, **kw)) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--task", default="l7_offcenter_push", help="simulated LFF-Bench task that plays the real scene") + ap.add_argument("--seed", type=int, default=3000) + ap.add_argument("--port", type=int, default=9900) + ap.add_argument("--token", default=os.environ.get("LFF_DRIVER_TOKEN", "")) + ap.add_argument("--nominal", action="store_true", help="remove the simulated task's calibration bias") + ap.add_argument("--operator", default="auto", choices=["auto", "console"]) + ap.add_argument("--image-res", type=int, default=512) + ap.add_argument("--log", default="", help="directory for driver_events.jsonl / operator.jsonl") + a = ap.parse_args() + drv = SimDriver(a.task, a.seed, nominal=a.nominal, image_res=a.image_res, operator=a.operator, log_dir=a.log) + drv.serve(a.port, token=a.token or None) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/protocol.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..13ce72af6568801584eb85c0c0b06279ddd3457d --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/protocol.py @@ -0,0 +1,364 @@ +"""Robot-driver protocol v1: what a real arm (or a fake one) must answer so that LFF-Bench can run on it. + +The benchmark side (lffbench/real/session.py, on the machine that runs the agent harness) talks to one *driver* +process (on the robot PC) over HTTP. The driver only moves the arm, reads its state, grabs camera frames and talks +to the human operator; budgets, attempts, README, logs and the agent interface stay on the benchmark side, so the +agent sees exactly the same tools as in simulation. Spec for driver authors: lffbench/real/DRIVER.md. + +This file is shared by both sides and needs only the Python standard library + numpy + Pillow (no simulator): + DriverClient benchmark side: typed calls to a driver + DriverServer driver side: HTTP plumbing; subclass it and implement the hardware methods (driver_template.py) + ConsoleOperator driver side: the operator's terminal (blocking prompts for reset / judging) + +Every request is POST / with a JSON body and header X-Driver-Token: . +Every reply is JSON with "ok": true|false. A reply with "fault": true means the robot can no longer be trusted +(protective stop, e-stop, lost connection, ...): the benchmark ends the run and marks it invalid. +""" +import base64 +import io +import json +import math +import os +import secrets +import sys +import time +import traceback +import urllib.error +import urllib.request +from http.server import BaseHTTPRequestHandler, HTTPServer + +import numpy as np + +PROTOCOL_VERSION = 1 +CAMERAS = ("agentview", "wrist") +TOKEN_HEADER = "X-Driver-Token" +ENDPOINTS = ("info", "home", "move", "gripper", "state", "observe", "ik", "operator", "event") +OPERATOR_KINDS = ("reset", "judge", "notice") +EVENTS = ("session_start", "attempt_start", "attempt_end", "episode_end", "session_end", "run_invalid") + + +class DriverError(RuntimeError): + """The driver answered something that breaks the protocol (or did not answer).""" + + +class DriverFault(DriverError): + """The driver reports a robot fault: the run must stop and is invalid.""" + + +# ------------------------------------------------------------------------------------------------ images +def encode_image(arr, fmt="png", quality=95): + """uint8 HxWx3 -> {"format": "png"|"jpeg", "data": base64}. PNG is lossless (the benchmark re-encodes every frame + as 512x512 JPEG q90 itself, so a JPEG from the driver is compressed twice); JPEG is smaller over a slow link.""" + from PIL import Image + buf = io.BytesIO() + im = Image.fromarray(np.asarray(arr, dtype=np.uint8)) + if fmt == "jpeg": + im.save(buf, format="JPEG", quality=int(quality)) + else: + im.save(buf, format="PNG") + return dict(format=fmt, data=base64.b64encode(buf.getvalue()).decode("ascii")) + + +def decode_image(obj): + """{"format", "data"} -> uint8 HxWx3 (RGB).""" + from PIL import Image + if not isinstance(obj, dict) or "data" not in obj: + raise DriverError("image must be {\"format\": \"png\"|\"jpeg\", \"data\": }") + im = Image.open(io.BytesIO(base64.b64decode(obj["data"]))) + return np.asarray(im.convert("RGB"), dtype=np.uint8) + + +def square_resize(arr, res): + """Centre-crop to a square, then resize to res x res. A frame that is already res x res is returned unchanged + (bit for bit), so a simulator-backed driver gives exactly the simulator's pixels.""" + from PIL import Image + arr = np.asarray(arr, dtype=np.uint8) + h, w = arr.shape[:2] + if h == res and w == res: + return arr + s = min(h, w) + y0, x0 = (h - s) // 2, (w - s) // 2 + arr = arr[y0:y0 + s, x0:x0 + s] + if s == res: + return np.ascontiguousarray(arr) + return np.asarray(Image.fromarray(arr).resize((res, res), Image.BICUBIC)) + + +# ------------------------------------------------------------------------------------------------ validation +def _vec(v, n): + return isinstance(v, (list, tuple)) and len(v) == n and all(isinstance(x, (int, float)) and math.isfinite(x) for x in v) + + +def info_problems(info): + """-> list of problems with an /info reply (empty = fine).""" + p = [] + if info.get("protocol") != PROTOCOL_VERSION: + p.append(f"protocol must be {PROTOCOL_VERSION}, got {info.get('protocol')!r}") + if not isinstance(info.get("robot"), str) or not info["robot"].strip(): + p.append("robot: non-empty string (e.g. \"AgileX PiPER\")") + if not isinstance(info.get("n_joints"), int) or not 4 <= info["n_joints"] <= 8: + p.append("n_joints: integer 4..8") + if sorted(info.get("cameras") or []) != sorted(CAMERAS): + p.append(f"cameras must be exactly {list(CAMERAS)}") + ws = info.get("workspace") or {} + if not (_vec(ws.get("lo"), 3) and _vec(ws.get("hi"), 3) and all(a < b for a, b in zip(ws["lo"], ws["hi"]))): + p.append("workspace: {lo: [x, y, z], hi: [x, y, z]} with lo < hi (robot-base frame, metres)") + yr = info.get("yaw_range_deg") + if not (_vec(yr, 2) and yr[0] < yr[1] and yr[1] - yr[0] >= 180.0): + p.append("yaw_range_deg: [lo, hi] with hi - lo >= 180 (the gripper is symmetric, every yaw must be reachable)") + if not (isinstance(info.get("max_speed"), (int, float)) and 0.01 <= info["max_speed"] <= 1.0): + p.append("max_speed: m/s, 0.01..1.0") + if not isinstance(info.get("ik"), bool): + p.append("ik: true|false (whether /ik is implemented; needed only for tasks with a calibration bias)") + if not isinstance(info.get("driver_version"), str): + p.append("driver_version: string (your git commit or a date; it is written into every run's log)") + return p + + +def state_problems(st, n_joints): + p = [] + if not _vec(st.get("eef_pos"), 3): + p.append("state.eef_pos: [x, y, z] metres") + if not (isinstance(st.get("eef_yaw_deg"), (int, float)) and math.isfinite(st["eef_yaw_deg"])): + p.append("state.eef_yaw_deg: number") + if not (isinstance(st.get("gripper_width_m"), (int, float)) and 0.0 <= st["gripper_width_m"] <= 0.2): + p.append("state.gripper_width_m: number 0..0.2") + if not _vec(st.get("joint_pos_rad"), n_joints): + p.append(f"state.joint_pos_rad: {n_joints} numbers (radians)") + return p + + +# ------------------------------------------------------------------------------------------------ benchmark side +class DriverClient: + """Typed calls to a driver. `url` like http://127.0.0.1:9900 (an SSH tunnel to the robot PC).""" + + def __init__(self, url, token, timeout=120.0): + self.url, self.token, self.timeout = url.rstrip("/"), token, float(timeout) + self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) # never through a web proxy + + def call(self, endpoint, payload=None, timeout=None, allow_not_ok=False): + req = urllib.request.Request(f"{self.url}/{endpoint}", data=json.dumps(payload or {}).encode(), + headers={"Content-Type": "application/json", TOKEN_HEADER: self.token}) + try: + with self.opener.open(req, timeout=timeout if timeout is not None else self.timeout) as r: + rep = json.loads(r.read().decode()) + except (urllib.error.URLError, OSError, ValueError) as e: + raise DriverError(f"/{endpoint}: no valid reply from the driver ({type(e).__name__}: {e})") from e + if not isinstance(rep, dict) or "ok" not in rep: + raise DriverError(f"/{endpoint}: reply is not a JSON object with \"ok\"") + if rep.get("fault"): + raise DriverFault(f"/{endpoint}: robot fault: {rep.get('error', '')}") + if not rep["ok"] and not allow_not_ok: + raise DriverError(f"/{endpoint}: {rep.get('error', 'not ok')}") + return rep + + def info(self): + rep = self.call("info") + prob = info_problems(rep) + if prob: + raise DriverError("/info: " + "; ".join(prob)) + return rep + + def home(self): + return self.call("home", timeout=max(self.timeout, 300)) + + def move(self, x, y, z, yaw_deg, speed=None): + """-> reply; ok=false (not a fault) means the target was rejected and the arm did not move.""" + return self.call("move", dict(x=float(x), y=float(y), z=float(z), yaw_deg=float(yaw_deg), + speed=None if speed is None else float(speed)), allow_not_ok=True) + + def gripper(self, close): + return self.call("gripper", dict(close=bool(close))) + + def state(self): + return self.call("state")["state"] + + def observe(self): + rep = self.call("observe") + imgs = rep.get("images") or {} + missing = [c for c in CAMERAS if c not in imgs] + if missing: + raise DriverError(f"/observe: missing camera(s) {missing}") + return {c: decode_image(imgs[c]) for c in CAMERAS}, rep["state"] + + def ik(self, eef_pos, yaw_deg): + return self.call("ik", dict(eef_pos=[float(v) for v in eef_pos], yaw_deg=float(yaw_deg)))["joint_pos_rad"] + + def operator(self, kind, **kw): + """Blocks until the operator has answered (no timeout).""" + assert kind in OPERATOR_KINDS, kind + return self.call("operator", dict(kind=kind, **kw), timeout=24 * 3600) + + def event(self, ev, **kw): + assert ev in EVENTS, ev + return self.call("event", dict(ev=ev, **kw)) + + +# ------------------------------------------------------------------------------------------------ driver side +class ConsoleOperator: + """The operator's terminal on the robot PC. Prompts block the driver (the robot must not move while the operator + resets the scene). Answers are appended to `log_path` (JSON lines).""" + + def __init__(self, log_path=None, stream_in=None, stream_out=None): + self.log_path = log_path + self.inp = stream_in or sys.stdin + self.out = stream_out or sys.stdout + + def _say(self, s=""): + self.out.write(s + "\n") + self.out.flush() + + def _ask(self, prompt): + self.out.write(prompt) + self.out.flush() + line = self.inp.readline() + if not line: + raise EOFError("operator input closed") + return line.strip() + + def _log(self, d): + if self.log_path: + os.makedirs(os.path.dirname(os.path.abspath(self.log_path)), exist_ok=True) + with open(self.log_path, "a") as f: + f.write(json.dumps(dict(d, t=time.time()), ensure_ascii=False) + "\n") + + def __call__(self, kind, run="", attempt=None, text="", setup="", checklist=None, **_): + bar = "=" * 72 + self._say("\n" + bar) + self._say(f"[{time.strftime('%H:%M:%S')}] run {run} attempt {attempt} -- {kind.upper()}") + if text: + self._say(text) + if kind == "reset": + if setup: + self._say("\nScene for this attempt (do it exactly; do not talk to anyone about it):\n" + setup) + self._ask("\nArm is at home. Put the scene back as described, step out of the cameras, press Enter... ") + self._log(dict(kind=kind, run=run, attempt=attempt)) + return dict(ok=True) + if kind == "judge": + for i, c in enumerate(checklist or [], 1): + self._say(f" {i}. {c}") + while True: + a = self._ask("\nAll conditions met? y = success, n = failure, x = run invalid (robot / camera " + "problem): ").lower() + if a in ("y", "n", "x"): + break + note = self._ask("Note (one line, optional): ") + self._log(dict(kind=kind, run=run, attempt=attempt, answer=a, note=note)) + if a == "x": + return dict(ok=False, fault=True, error=f"operator marked the run invalid: {note}") + return dict(ok=True, success=a == "y", note=note) + self._log(dict(kind=kind, run=run, attempt=attempt, text=text)) + return dict(ok=True) + + +class DriverServer: + """HTTP plumbing for a driver. Subclass and implement the hardware methods below; see driver_template.py. + The server is single-threaded on purpose: requests are executed one at a time, and an operator prompt blocks + every other request until it is answered.""" + + # ---- implement these ------------------------------------------------------------------------------ + def info(self): + """-> dict (see DRIVER.md §3): protocol, robot, n_joints, cameras, workspace, yaw_range_deg, max_speed, ik, + driver_version.""" + raise NotImplementedError + + def home(self): + """Move to the home pose (gripper open, pointing down). -> state dict.""" + raise NotImplementedError + + def move(self, x, y, z, yaw_deg, speed): + """Blocking straight-line move of the grasp point; speed m/s or None (= max_speed). + -> (ok, error_or_None, motion_s). ok=False: rejected BEFORE moving (outside the hard limits / no IK).""" + raise NotImplementedError + + def gripper(self, close): + """Blocking open / close (force-limited close). -> motion_s.""" + raise NotImplementedError + + def state(self): + """-> dict eef_pos, eef_yaw_deg, gripper_width_m, joint_pos_rad.""" + raise NotImplementedError + + def images(self): + """-> {"agentview": uint8 HxWx3 RGB, "wrist": ...}, taken now (after the arm has stopped).""" + raise NotImplementedError + + def ik(self, eef_pos, yaw_deg): + """Optional (info()["ik"] = True): joint angles that put the grasp point at eef_pos / yaw_deg (pointing + down), close to the current joint angles. -> list of n_joints floats.""" + raise NotImplementedError + + def operator(self, kind, **kw): + """Default: the terminal. -> dict (reset: {ok}; judge: {ok, success, note}; notice: {ok}).""" + return self.console(kind, **kw) + + def event(self, ev, **kw): + """Start / stop your own recordings here (attempt_start / attempt_end / episode_end ...).""" + return None + + image_format = "png" + + # ---- plumbing ------------------------------------------------------------------------------------- + def dispatch(self, endpoint, a): + if endpoint == "info": + return dict(ok=True, **self.info()) + if endpoint == "home": + return dict(ok=True, state=self.home()) + if endpoint == "move": + ok, err, motion_s = self.move(float(a["x"]), float(a["y"]), float(a["z"]), float(a["yaw_deg"]), + None if a.get("speed") is None else float(a["speed"])) + rep = dict(ok=bool(ok), motion_s=float(motion_s or 0.0), state=self.state()) + if not ok: + rep["error"] = err or "rejected" + return rep + if endpoint == "gripper": + motion_s = self.gripper(bool(a["close"])) + return dict(ok=True, motion_s=float(motion_s or 0.0), state=self.state()) + if endpoint == "state": + return dict(ok=True, state=self.state()) + if endpoint == "observe": + imgs = self.images() + return dict(ok=True, images={c: encode_image(imgs[c], self.image_format) for c in CAMERAS}, + state=self.state()) + if endpoint == "ik": + return dict(ok=True, joint_pos_rad=[float(v) for v in self.ik(a["eef_pos"], float(a["yaw_deg"]))]) + if endpoint == "operator": + kw = {k: v for k, v in a.items() if k != "kind"} + return self.operator(a["kind"], **kw) + if endpoint == "event": + self.event(a.get("ev", ""), **{k: v for k, v in a.items() if k != "ev"}) + return dict(ok=True) + return dict(ok=False, error=f"unknown endpoint {endpoint!r}") + + def serve(self, port, token=None, host="127.0.0.1", operator_log=None): + """Serve forever on host:port (keep 127.0.0.1 and reach it through an SSH tunnel).""" + self.token = token or os.environ.get("LFF_DRIVER_TOKEN") or secrets.token_hex(12) + self.console = ConsoleOperator(operator_log) + drv = self + + class H(BaseHTTPRequestHandler): + def log_message(self, *x): + pass + + def do_POST(self): + try: + body = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)) or b"{}") + if self.headers.get(TOKEN_HEADER) != drv.token: + rep = dict(ok=False, error="unauthorised") + else: + rep = drv.dispatch(self.path.strip("/"), body) + except NotImplementedError as e: + rep = dict(ok=False, error=f"not implemented: {self.path} {e}") + except Exception as e: # anything unexpected on the robot side is a fault: stop the run + traceback.print_exc() + rep = dict(ok=False, fault=True, error=f"{type(e).__name__}: {e}") + data = json.dumps(rep).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + srv = HTTPServer((host, int(port)), H) + print(f"driver ready on http://{host}:{port} token={self.token}", flush=True) + srv.serve_forever() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/session.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/session.py new file mode 100644 index 0000000000000000000000000000000000000000..a8139571b63fbc74db1b39537d207b09861dbc63 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/session.py @@ -0,0 +1,346 @@ +"""Robot server for a real arm: robot_server's LA interface (README, robot commands, budgets, attempts, F1, --hide-k, +memory conditions, events.jsonl, observation files) with a robot driver instead of the simulator. + +Everything above this server is unchanged: the MCP server (scripts/mcp_robot_server.py), the native-harness adapters +(Codex / Claude Code, with or without the jail), api_player. They talk to this server exactly as to the simulated one +(POST /call on 127.0.0.1, same token file, same workspace layout). Below it, lffbench/real/protocol.py talks to the +driver on the robot PC (usually through an SSH tunnel). + +What differs from simulation, all of it on purpose (docs/17): +- README: "a real arm ( joints)" instead of "Franka Emika Panda (7 joints) ... in a physics simulation"; + "a person resets the scene"; "s of robot motion" (budget_left key motion_seconds instead of sim_seconds). +- outcome: the operator judges the end state against the task's checklist (F1 only; F2 needs simulator measurements). +- reset: arm to home, then the operator rebuilds the scene from the task's setup sheet. +- a driver fault ends the episode and marks the run invalid (events.jsonl ev=run_invalid). +- no video, no regression snapshots here (the driver side records video). + + python -m lffbench.real.session --task real_offcenter_push --seed 5000 --driver http://127.0.0.1:9900 \ + --sandbox --log-dir --port 9800 [robot_server's la options] +(scripts/start_real_session.sh does this and writes session.json, like scripts/start_robot_session.sh.) +""" +import argparse +import json +import os +import signal +import time +import traceback +from http.server import BaseHTTPRequestHandler, HTTPServer + +import numpy as np + +from ..agent import robot_server as RS +from ..agent.tools import _json_default +from .executor import RealToolExecutor +from .protocol import DriverClient, DriverError, DriverFault +from .tasks import REAL_TASKS + +SIM_TEXT = { # robot_server._readme_la sentence -> real-robot sentence (each must occur, else refuse to start) + "embodiment": ("You control a Franka Emika Panda robot arm (7 joints) with a two-finger parallel gripper in a physics " + "simulation.", "You control a real {robot} robot arm ({n} joints) with a two-finger parallel gripper."), + "reset": ("Before every attempt the scene is reset to exactly the same initial state.", + "Before every attempt a person resets the scene to the same initial state."), + "motion": (" s of simulated robot motion;", " s of robot motion;"), + "joints": ("joint_pos_rad = the 7 arm joint angles", "joint_pos_rad = the {n} arm joint angles"), +} +REPLY_TEXT = [("The scene has been reset to exactly the same initial state.", + "A person has reset the scene to the same initial state.")] +FAULT_MSG = "The robot stopped because of a hardware problem. The episode is over. Stop now and report." + + +def _realify(o): + """Agent-facing reply wording for the real robot (see module doc).""" + if isinstance(o, dict): + return {("motion_seconds" if k == "sim_seconds" else k): _realify(v) for k, v in o.items()} + if isinstance(o, list): + return [_realify(v) for v in o] + if isinstance(o, str): + for a, b in REPLY_TEXT: + o = o.replace(a, b) + return o + + +class RealRobotSession(RS.RobotSession): + def __init__(self, a): # robot_server.RobotSession.__init__ minus the simulator + bad = [m for m, c in (("--style la", a.style != "la"), ("--perception rgb", a.perception != "rgb"), + ("--feedback F0|F1", a.feedback == "F2"), ("--arm none", a.arm != "none"), + ("no --nominal", a.nominal)) if c] + if bad: + raise SystemExit("real robot needs " + ", ".join(bad)) + self.a = a + self.task = REAL_TASKS[a.task]() + self.task.judge = self._judge + if a.max_steps is None: + a.max_steps = int(self.task.agent_max_steps) + self.inst = self.task.sample_instance(a.seed) + self.inst_override = json.loads(a.inst_override) if a.inst_override else {} + self.inst.update(self.inst_override) # tests only (logged) + self.arm, self.arm_overrides, self.reveal_text = "none", {}, "" + self.n_mon_events = 0 + self.protocol = self.task.protocol + self.k = a.k or self.task.max_attempts + self.k_shown = 1 if a.hide_k and a.memory == "full" else self.k + self.sandbox = os.path.abspath(a.sandbox) + self.obs_dir = os.path.join(self.sandbox, "obs") + self.log_dir = os.path.abspath(a.log_dir) + os.makedirs(self.obs_dir, exist_ok=True) + os.makedirs(os.path.join(self.log_dir, "images"), exist_ok=True) + self.events = open(os.path.join(self.log_dir, "events.jsonl"), "a") + import secrets + self.token = secrets.token_hex(8) + self.n_actions, self.attempt, self.step = 0, 1, 0 + self.finished, self.waiting_new_agent, self.invalid = False, False, "" + self.history, self.last_send, self.video = [], None, None + self.base_off = np.zeros(3) # the driver already reports the robot-base frame + self.run = a.run_name or os.path.basename(self.log_dir) + self.driver = DriverClient(a.driver, a.driver_token, timeout=a.driver_timeout) + self.dinfo = self.driver.info() + if self.task.needs_ik and np.any(self.task.bias(self.inst)) and not self.dinfo["ik"]: + raise SystemExit(f"{a.task} has a calibration bias: the driver must implement /ik (believed joint angles)") + m = float(self.task.bias_margin) + self.ws_lo = np.asarray(self.dinfo["workspace"]["lo"], float) + [m, m, 0.0] + self.ws_hi = np.asarray(self.dinfo["workspace"]["hi"], float) - [m, m, 0.0] + self.driver.event("session_start", run=self.run, task=a.task, seed=a.seed, k=self.k) + self._start_attempt(reset=True) + self._write_sandbox() + self.log(dict(ev="session_start", task=a.task, seed=a.seed, k=self.k, k_shown=self.k_shown, protocol=self.protocol, + memory=a.memory, feedback=a.feedback, instruction=a.instruction, perception=a.perception, + inst={k: v for k, v in self.inst.items() if not k.startswith("_")}, arm=self.arm, + arm_overrides={}, reveal="", dossier=a.dossier or "", backend="real", + driver_info={k: v for k, v in self.dinfo.items() if k != "ok"}, + agent_workspace=dict(lo=self.ws_lo.round(4).tolist(), hi=self.ws_hi.round(4).tolist()), + inst_override=self.inst_override, sim_counterpart=self.task.sim_counterpart, + video_ignored=bool(a.video))) + + # ------------------------------------------------------------------ simulator-dependent parts, replaced + def _start_attempt(self, reset): + self.n_actions = 0 + if reset: + self.driver.home() + self.driver.operator("reset", run=self.run, attempt=self.attempt, setup=self.task.setup_text(self.inst), + text=f"task {self.a.task} seed {self.a.seed}") + self.driver.event("attempt_start", run=self.run, attempt=self.attempt) + self.ex = RealToolExecutor(self.driver, self.dinfo, bias=self.task.bias(self.inst), image_res=self.a.image_res) + self.step = 0 + + def _judge(self, inst): + self.driver.event("attempt_end", run=self.run, attempt=self.attempt) + rep = self.driver.operator("judge", run=self.run, attempt=self.attempt, checklist=self.task.checklist(inst), + text=f"task {self.a.task} seed {self.a.seed}: judge the scene as it is now") + if not isinstance(rep.get("success"), bool): + raise DriverError("/operator judge: reply needs \"success\": true|false") + return dict(success=rep["success"], note=str(rep.get("note", "")), judged_by="operator", + motion_s=round(self.ex.motion_s, 2)) + + def _budget_left(self): + used = self.ex.motion_s + return dict(commands=max(self.a.max_steps - self.n_actions, 0), + sim_seconds=round(max(self.sim_budget() - used, 0.0), 1)) # renamed to motion_seconds in replies + + def _state_v2(self): + p = self.ex.proprio() + st = dict(eef_pos=p["eef_pos"], eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"]) + st["joint_pos_rad"] = [round(float(v), 4) for v in self.ex.joints()] + st["budget_left"] = self._budget_left() + return st + + def _snap_regressions(self): + return None + + def readme_la(self): + text = RS._readme_la(self) + n = int(self.dinfo["n_joints"]) + for key, (old, new) in SIM_TEXT.items(): + if key == "reset" and self.protocol != "cross": + continue + if old not in text: # robot_server's README changed: update SIM_TEXT rather than ship a half-sim README + raise SystemExit(f"README sentence for {key!r} not found in robot_server._readme_la: {old!r}") + text = text.replace(old, new.format(robot=self.dinfo["robot"], n=n)) + return text + + def _done(self, reason): + rep = RS.RobotSession._done(self, reason) + if self.finished: + self.driver.event("episode_end", run=self.run, attempt=self.attempt) + return rep + + # ------------------------------------------------------------------ dispatch + def handle(self, cmd, args): + if self.invalid: + return dict(ok=False, error=FAULT_MSG) + try: + return _realify(RS.RobotSession.handle(self, cmd, args)) + except DriverError as e: # robot fault, operator marked the run invalid, or the driver broke the protocol + self.invalid, self.finished = str(e), True + self.log(dict(ev="run_invalid", attempt=self.attempt, step=self.step, cmd=cmd, args=args, + fault=isinstance(e, DriverFault), error=str(e), traceback=traceback.format_exc()[-2000:])) + try: + self.driver.event("run_invalid", run=self.run, attempt=self.attempt, error=str(e)) + except DriverError: + pass + return dict(ok=False, error=FAULT_MSG) + + def handle_v2(self, cmd, args): + if cmd != "move_eef" or self.finished: + return RS._handle_v2(self, cmd, args) + return self._move_eef(args) + + def _move_eef(self, args): + """robot_server._handle_v2's move_eef branch (same checks, order, replies and log lines) with the driver's + workspace instead of the simulator's WS_LO / WS_HI. tests/real_selfcheck.py compares the two paths reply by + reply; keep them in step.""" + cmd = "move_eef" + self.n_actions += 1 + if self.n_actions > self.a.max_steps: + rep = self._done("command budget used up (automatic)") + rep["note"] = f"The budget of {self.a.max_steps} commands for this attempt was used up." + return rep + self.step += 1 + p = self.ex.proprio() + unknown = set(args) - {"x", "y", "z", "yaw", "gripper", "speed"} + if unknown: + rep = dict(ok=False, error=f"unknown argument(s) {sorted(unknown)}; use x, y, z, yaw, gripper, speed") + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep)) + return rep + try: + cur = np.asarray(p["eef_pos"], float) + tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")] + yaw = float(args.get("yaw", p["eef_yaw_deg"])) + speed = None if args.get("speed") in (None, "") else float(args["speed"]) + except (TypeError, ValueError): + rep = dict(ok=False, error="x, y, z, yaw and speed must be numbers") + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep)) + return rep + grip = args.get("gripper") + if grip not in (None, "open", "close"): + rep = dict(ok=False, error="gripper must be open or close") + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep)) + return rep + moving = any(k in args for k in ("x", "y", "z", "yaw")) + tgt = np.asarray(tgt) + if moving and not (np.all(tgt >= self.ws_lo) and np.all(tgt <= self.ws_hi)): + rep = dict(ok=False, error="target rejected: the arm cannot reach it; the arm did not move") + rep.update(self._state_v2()) + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep)) + return rep + left = self._budget_left()["sim_seconds"] + raw = {} + rejected = False + if moving: + mv = dict(x=float(tgt[0]), y=float(tgt[1]), z=float(tgt[2]), yaw=yaw) + if speed is not None: + mv["speed"] = speed + res = self.ex.call("move_to", mv) + raw.update(res.report) + rejected = not res.ok # the driver refused (no IK solution ...): the arm did not move, skip the gripper + if grip is not None and not rejected: + res = self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}) + raw.update(res.report) + rep = dict(ok=bool(raw.get("ok", True))) + if raw.get("error"): + rep["error"] = raw["error"] + rep.update(self._state_v2()) + if moving: + err = tgt - np.asarray(rep["eef_pos"]) + dyaw = (yaw - rep["eef_yaw_deg"] + 90.0) % 180.0 - 90.0 + rep["stopped_from_target"] = dict(cm=round(100 * float(np.linalg.norm(err)), 1), deg=round(abs(dyaw), 1)) + rep["images"] = self._save_obs(cmd) + rep.update(self._la_files()) + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep, raw=raw)) + if rep["budget_left"]["sim_seconds"] <= 0 and left > 0: + fin = self._done("motion budget used up (automatic)") + fin["note"] = f"The {self.sim_budget():.0f} s motion budget for this attempt was used up." + rep["attempt_ended"] = fin + return rep + + +def serve(a): + """robot_server.serve with the real session (same HTTP contract: POST /call, X-Token, 127.0.0.1).""" + sess = RealRobotSession(a) + + class H(BaseHTTPRequestHandler): + def log_message(self, *x): + pass + + def do_POST(self): + t_recv = time.time() + cmd = "" + try: + body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + cmd = body.get("cmd", "") + if self.headers.get("X-Token") != sess.token: + rep = dict(ok=False, error="unauthorised") + else: + rep = sess.handle(cmd, body.get("args", {}) or {}) + except Exception as e: # never leak a traceback (it contains benchmark paths) to the agent + sess.log(dict(ev="error", error=traceback.format_exc())) + rep = dict(ok=False, error=f"internal error: {type(e).__name__}") + data = json.dumps(rep, default=_json_default, indent=None).encode() + if "text" in rep: + data = rep["text"].encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(data) + t_send = time.time() + sess.log(dict(ev="http", cmd=cmd, attempt=sess.attempt, t_recv=t_recv, t_send=t_send, + server_s=t_send - t_recv, think_s=(t_recv - sess.last_send) if sess.last_send else None)) + sess.last_send = t_send + + def _term(*_): + try: # short timeout: the driver may be blocked on an operator prompt + sess.driver.call("event", dict(ev="session_end", run=sess.run, attempt=sess.attempt), timeout=5) + except Exception: + pass + os._exit(0) + + signal.signal(signal.SIGTERM, _term) + srv = HTTPServer(("127.0.0.1", a.port), H) + print(f"real robot server ready on 127.0.0.1:{a.port} driver={a.driver} sandbox={sess.sandbox} log={sess.log_dir}", + flush=True) + with open(os.path.join(sess.log_dir, "READY"), "w") as f: + f.write(str(os.getpid())) + srv.serve_forever() + + +def parser(): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--task", required=True, choices=sorted(REAL_TASKS)) + ap.add_argument("--seed", type=int, required=True) + ap.add_argument("--driver", default=os.environ.get("LFF_REAL_DRIVER", "http://127.0.0.1:9900"), + help="driver URL (default $LFF_REAL_DRIVER or http://127.0.0.1:9900, i.e. an SSH tunnel)") + ap.add_argument("--driver-token", default=os.environ.get("LFF_DRIVER_TOKEN", ""), + help="driver token (default $LFF_DRIVER_TOKEN)") + ap.add_argument("--driver-timeout", type=float, default=180.0, help="seconds per driver call (operator: no limit)") + ap.add_argument("--run-name", default="", help="shown to the operator (default: the log dir name)") + ap.add_argument("--inst-override", default=os.environ.get("LFF_REAL_INST_OVERRIDE", ""), + help="TESTS ONLY: JSON merged into the instance (logged; default $LFF_REAL_INST_OVERRIDE)") + # robot_server's options that apply to the real robot (same names and defaults as there, except perception/style) + ap.add_argument("--k", type=int, default=None) + ap.add_argument("--memory", default="full", choices=["full", "none"]) + ap.add_argument("--hide-k", action="store_true") + ap.add_argument("--feedback", default="F1", choices=["F0", "F1", "F2"]) + ap.add_argument("--instruction", default="direct", choices=["direct", "indirect"]) + ap.add_argument("--image-res", type=int, default=512) + ap.add_argument("--port", type=int, default=8765) + ap.add_argument("--sandbox", required=True) + ap.add_argument("--log-dir", required=True) + ap.add_argument("--max-steps", type=int, default=None) + ap.add_argument("--perception", default="rgb", choices=["depth", "rgb", "rgbd"]) + ap.add_argument("--style", default="la", choices=["v1", "v2", "la"]) + ap.add_argument("--nominal", action="store_true") + ap.add_argument("--agent-iface", default="tools", choices=["tools", "cli"]) + ap.add_argument("--max-tool-calls", type=int, default=100) + ap.add_argument("--arm", default="none", choices=["none", "h0", "hplus", "twin"]) + ap.add_argument("--dossier", default="") + ap.add_argument("--video", default="", help="ignored (the driver side records video)") + ap.add_argument("--video-every", type=int, default=3) + ap.add_argument("--video-fps", type=int, default=20) + return ap + + +def main(): + serve(parser().parse_args()) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/tasks.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..f63e9009da34d3efa8b53b3f58c2499525a726a2 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/tasks.py @@ -0,0 +1,123 @@ +"""Real-robot tasks. Same idea as lffbench/tasks/ (an instruction, a hidden variable the agent cannot see before it acts, +a success rule), but the scene is physical: the instance is a setup sheet the operator follows, and the operator +judges the end state. The hidden variable is drawn from the seed, so the instance list of a run is reproducible and +nobody has to choose it by hand. + +Seeds: 5000+ for real-robot runs (same convention as simulation: 1000-1999 development, 3000 pilots, 5000+ test). +""" +import numpy as np + +REAL_TASKS = {} + + +def register_real(cls): + REAL_TASKS[cls.name] = cls + return cls + + +class RealTask: + name = "real_base" + sim_counterpart = "" # the simulated task with the same hidden variable (for the paper's mapping only) + protocol = "cross" + max_attempts = 3 + agent_max_steps = 40 + instruction = "" + instruction_indirect = "" + needs_ik = False # True if the instance carries a calibration bias (believed joint angles need the driver's /ik) + bias_margin = 0.0 # largest possible |bias| (m): the agent-facing workspace is shrunk by it, so a rejected target + # never depends on the hidden bias + judge = None # set by RealRobotSession: inst -> outcome dict, asks the operator + + def outcome(self, inst): + """Same role as LFFTask.outcome: called by robot_server's _done when an attempt ends.""" + return self.judge(inst) + + def sample_instance(self, seed): + raise NotImplementedError + + def setup_text(self, inst): + """What the operator builds before every attempt (shown on the robot PC only, never to the agent).""" + raise NotImplementedError + + def checklist(self, inst): + """Conditions the operator checks when an attempt ends; success = all of them.""" + raise NotImplementedError + + def bias(self, inst): + """Hidden calibration error added to every commanded position (robot-base frame, metres).""" + return np.zeros(3) + + def feedback(self, inst, out, level="F1"): + # same text as LFFTask.feedback (F0 / F1); F2 needs simulator measurements and is refused at session start + if level == "F0": + return "" + return "Attempt succeeded." if out["success"] else "Attempt failed." + + +@register_real +class RealOffcenterPush(RealTask): + """L7 l7_offcenter_push on a real arm: a long opaque box with a hidden weight at one end. Pushing the middle of + its back face turns it (visible in the agentview); the fix is to push nearer the heavy end or to straighten it + afterwards. Physical build and scene layout: DRIVER.md §6.1.""" + name = "real_offcenter_push" + sim_counterpart = "l7_offcenter_push" + # same wording as the simulated task (2026-10-19): end state only, no hint about the weight or where to push + instruction = ("Slowly push the long brown box with the closed gripper so that it ends up completely inside the " + "green rectangle ahead of it (farther from the robot).") + instruction_indirect = ("Slowly push the long cardboard-coloured block with the closed gripper so that it ends up " + "completely inside the marked green area ahead of it (farther from the robot).") + SLOTS = ("end", "inner") # weight compartments per side: at the very end, or one compartment further in + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + return dict(seed=int(seed), weight_side=str(rng.choice(["left", "right"])), weight_slot=str(rng.choice(self.SLOTS))) + + def setup_text(self, inst): + side = {"left": "LEFT (the robot's left, +y)", "right": "RIGHT (the robot's right, -y)"}[inst["weight_side"]] + slot = {"end": "the outermost compartment", "inner": "the second compartment from that end"}[inst["weight_slot"]] + return "\n".join([ + f"- weight block inside the box: {side} end, in {slot};", + "- the other compartments stay empty; close the lid; both ends look the same from outside;", + "- box on the START tape marks: long side across the robot (left-right), back face on the back mark;", + "- nothing else on the table; the green target rectangle tape unchanged.", + ]) + + def checklist(self, inst): + return ["all four bottom corners of the box are inside the green rectangle (a corner on the tape = outside)", + "the box is standing on its bottom face (not tipped over)", + "the box was only pushed with the closed gripper (no pushes with the fingers open)", + "the gripper is not touching the box"] + + +@register_real +class RealBiasPlace(RealTask): + """L1 l1_bias_place on a real arm: pick-and-place with a calibration error injected in software (the benchmark + adds `bias` to every commanded position and subtracts it from every reported one, exactly as in simulation). + The arm itself is unchanged; the cameras show where the gripper really is. Physical build: DRIVER.md §6.2.""" + name = "real_bias_place" + sim_counterpart = "l1_bias_place" + instruction = "Pick up the red cube and put it into the bowl." + instruction_indirect = "Pick up the small red block and put it into the round bowl." + needs_ik = True + R_MIN, R_MAX = 0.025, 0.040 # bias magnitude (m), as l1_bias_place + bias_margin = R_MAX + LAYOUTS = ("A", "B", "C", "D") # taped (cube mark, bowl mark) pairs; DRIVER.md §6.2 + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + r, th = float(rng.uniform(self.R_MIN, self.R_MAX)), float(rng.uniform(-np.pi, np.pi)) + return dict(seed=int(seed), layout=str(rng.choice(self.LAYOUTS)), + bias=[round(r * np.cos(th), 4), round(r * np.sin(th), 4), 0.0], bias_r=round(r, 4), + bias_theta=round(th, 4)) + + def bias(self, inst): + return np.asarray(inst["bias"], float) + + def setup_text(self, inst): + L = inst["layout"] + return "\n".join([f"- red cube on mark {L}1, bowl on mark {L}2 (layout {L});", + "- nothing else on the table."]) + + def checklist(self, inst): + return ["the red cube is inside the bowl (resting in it, not on the rim)", + "the gripper is open and not holding the cube"] diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/__init__.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l1_bias.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l1_bias.py new file mode 100644 index 0000000000000000000000000000000000000000..a5743522e389d8640257a0cbab03aa8e7df7dd86 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l1_bias.py @@ -0,0 +1,390 @@ +"""L1-A bias_place: pick up the cream cheese and put it into the bowl, with a miscalibrated arm. + +Level L1 (action fine-tuning): the method (top-down pick across the cheese's short side, carry, release +above the bowl) and the scene understanding are right; only execution precision is off. + +Hidden variable: a fixed calibration offset b = r (cos th, sin th, 0), r ~ U[R_MIN, R_MAX], th ~ U[0, 2 pi), +added to every commanded gripper position (`Skills(bias=b)`). The agent never sees b; positions reported +back to it must be in the commanded frame (`TrackedSkills.reported_eef_pos`), otherwise b leaks. + +Robot: the gripper is a short-stroke parallel gripper (max opening GRIPPER_MAX_OPEN = 5.0 cm, e.g. a +Robotiq Hand-E; implemented by narrowing the Panda finger actuators' ctrlrange). The cream cheese is +4.27 cm wide, so the open fingers clear it by ~3.5 mm per side. + +Why the prior fails. Sent to the true cheese position, the gripper arrives b away. If the component of b +across the cheese (jaw-closing direction) exceeds ~0.7-1.0 cm (measured), a finger comes down on top of the +cheese, the hand stops ~1.5 cm too high and the jaws close above it -> missed grasp, visible in both +cameras. With the stock 8 cm Panda stroke the measured tolerance is ~2.4 cm, so most r in [2, 4] cm would +not fail; that is why the stroke is reduced. The component of b along the cheese does not matter much +(the finger pads can grip anywhere along its 8.1 cm length, and the in-hand offset cancels at the place +because the same b is added there), and the bowl is forgiving. + +What has to be learned: the F2 feedback reports where the gripper closed relative to the cheese's centre +(forward/backward, left/right in the robot frame). That offset is b itself, so after one failure b can be +estimated and subtracted from every commanded position (pick and place alike). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..skills import Skills +from ..task_base import LFFTask, register_task + +CHEESE, BOWL = "cream_cheese_1", "akita_black_bowl_1" +JUICE = "orange_juice_1" +DISTRACTORS = ("butter_1", "chocolate_pudding_1", JUICE) +ALL = (CHEESE, BOWL) + DISTRACTORS +NAMES = {CHEESE: "cream cheese", BOWL: "bowl", "butter_1": "butter", "chocolate_pudding_1": "chocolate pudding", + JUICE: "orange juice carton"} +# descriptive names for the indirect variant (same wording as l2_knock_restore where objects overlap) +DESCR = {CHEESE: "blue box", BOWL: "grey bowl", "butter_1": "small orange box", "chocolate_pudding_1": "brown box", + JUICE: "tall juice carton"} +# Cream cheese collision box: 8.12 x 4.27 x 1.79 cm, lying flat, long side along its x axis. +# Realistic masses (LIBERO's are 5-10 g): a 6 g cheese is shoved aside by a finger landing on its edge. +MASS = {CHEESE: 0.227, "butter_1": 0.250, "chocolate_pudding_1": 0.200, BOWL: 0.300} + +# finger tips (0.97 cm below the gripper site) just clear the table; the pads cover 0.6-1.8 cm of the cheese +Z_GRASP = envs.TABLE_Z + 0.0105 +Z_CARRY = envs.TABLE_Z + 0.20 # clears the 13 cm juice carton with the cheese hanging below the fingers +BOWL_RIM = 0.0505 # rim height of the akita bowl above its lowest point +BOWL_R_IN = 0.046 # inner radius of the bowl at the rim +RELEASE_ABOVE_RIM = 0.012 # gripper site above the rim at release (finger pads clear the rim) + +R_MIN, R_MAX = 0.025, 0.040 # bias magnitude range (m) +GRIPPER_MAX_OPEN = 0.050 # short-stroke gripper: max finger gap (m); the cheese is 4.27 cm wide +CHEESE_YAW_MAX = np.deg2rad(10) + + +HOME_XY = np.array([-0.21, 0.0]) # gripper xy at reset + + +def _seg_dist(p, a, b): + """distance from point p to segment ab (2-D)""" + ab = b - a + u = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0, 1) + return float(np.linalg.norm(a + u * ab - p)) + + +def _q(axis, a): + h = a / 2 + return {"y": np.array([np.cos(h), 0, np.sin(h), 0]), "z": np.array([np.cos(h), 0, 0, np.sin(h)])}[axis] + + +def _qmul(a, b): + """wxyz quaternion product a*b""" + w1, x1, y1, z1 = a + w2, x2, y2, z2 = b + return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, + w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2]) + + +def set_gripper_stroke(env, max_open): + """Limit the jaw opening: each finger's position actuator gets the range [0, max_open/2] (robosuite maps + the open/close command onto the actuator ctrlrange, so "open" now means max_open). The pad faces sit + 0.5 mm inside the joint position, hence the small correction.""" + m = env.sim.model + half = max_open / 2 + 0.0005 + a1, a2 = [m.actuator_name2id(a) for a in env.robots[0].gripper.actuators] + m.actuator_ctrlrange[a1] = [0.0, half] + m.actuator_ctrlrange[a2] = [-half, 0.0] + + +def dir_words(dx, dy): + """Robot-frame description: +x = forward (away from the robot), +y = the robot's left.""" + parts = [] + if abs(dy) >= 0.0005: + parts.append(f"{100 * abs(dy):.1f} cm to the robot's {'left (+y)' if dy > 0 else 'right (-y)'}") + if abs(dx) >= 0.0005: + parts.append(f"{100 * abs(dx):.1f} cm {'forward (+x, away from the robot)' if dx > 0 else 'backward (-x, toward the robot)'}") + return " and ".join(parts) if parts else "exactly at the position" + + +class TrackedSkills(Skills): + """Skills that log what the outcome measurement needs, whoever drives them (scripted policy or agent): + where the gripper was and what the fingers touched when the jaws closed, and where the cheese was when + the jaws opened while holding it.""" + + def __init__(self, env, bias=None, recorder=None): + super().__init__(env, bias=bias, recorder=recorder) + self.events = [] + self.cheese_z0 = float(envs.obj_pos(env, CHEESE)[2]) + self.cheese_zmax = self.cheese_z0 + m = env.sim.model + self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_")] + self._obj_geoms = {n: envs.obj_geom_ids(env, n) for n in ALL} + # where the cheese was before the gripper last touched it (the reference for the grasp offset, so that + # a finger shoving the cheese aside on the way down does not corrupt the measurement) + self.cheese_ref = envs.obj_pos(env, CHEESE) + + def reported_eef_pos(self): + """End-effector position as the miscalibrated robot believes it to be (commanded frame). Anything + shown to the agent must use this, never eef_pos(), which is the true position and reveals b.""" + return self.eef_pos() - self.bias + + def move_to(self, target, *args, **kwargs): + rep = super().move_to(target, *args, **kwargs) + rep["pos"] = np.round(self.reported_eef_pos(), 4).tolist() # do not leak b through the report + return rep + + def touching(self): + """Objects the gripper is in contact with right now.""" + return [n for n, gs in self._obj_geoms.items() if envs.contacts_between(self.env, self._grip_geoms, gs)] + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.cheese_zmax = max(self.cheese_zmax, float(envs.obj_pos(self.env, CHEESE)[2])) + if self.grip < 0 and not envs.contacts_between(self.env, self._grip_geoms, self._obj_geoms[CHEESE]): + self.cheese_ref = envs.obj_pos(self.env, CHEESE) + + def set_gripper(self, close, steps=15): + if close and self.grip < 0: + self.events.append(dict(kind="close", eef=self.eef_pos().tolist(), + cheese=envs.obj_pos(self.env, CHEESE).tolist(), + cheese_ref=np.asarray(self.cheese_ref).tolist(), touching=self.touching(), + cheese_top=envs.obj_max_z(self.env, CHEESE), step=self.n_steps)) + elif not close and self.grip > 0 and self.holding(CHEESE): + self.events.append(dict(kind="release", eef=self.eef_pos().tolist(), + cheese=envs.obj_pos(self.env, CHEESE).tolist(), + bowl=envs.obj_pos(self.env, BOWL).tolist(), step=self.n_steps)) + return super().set_gripper(close, steps) + + +@register_task +class BiasPlace(LFFTask): + name = "l1_bias_place" + level = "L1" + category = "system_identification" + capabilities = ("Perceive", "Utilize") + protocol = "cross" + # LIBERO calls the bowl "akita black bowl", but under our renderer it looks silver-grey with a gold rim, so + # the colour is not used in the direct instruction (there is only one bowl). + instruction = "Pick up the cream cheese and put it into the bowl." + instruction_indirect = "Pick up the flat blue box with the white oval label and put it into the round grey bowl." + pick_lift_min = 0.03 # cheese counted as picked up if it rose this much + + # ------------------------------------------------------------ scene + def make_bddl(self): + # regions are only used by LIBERO's reset-time sampler (the layout is overridden in apply_instance) + objs = [(CHEESE, "cream_cheese", "cheese_region", (-0.16, -0.22, -0.14, -0.20)), + (BOWL, "akita_black_bowl", "bowl_region", (-0.01, 0.15, 0.01, 0.17)), + ("butter_1", "butter", "butter_region", (-0.16, 0.10, -0.14, 0.12)), + ("chocolate_pudding_1", "chocolate_pudding", "pudding_region", (0.04, -0.17, 0.06, -0.15)), + (JUICE, "orange_juice", "juice_region", (-0.15, -0.03, -0.13, -0.01))] + return write_bddl(self.name, self.instruction, objs) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + # LIBERO's own upright orientation of every object, read off the reset state + self._base_quat = {n: envs.obj_quat(self.env, n) for n in ALL} + + def _place(self, name, xy, yaw): + q = _qmul(_q("z", yaw), self._base_quat[name]) + envs.set_obj_pose(self.env, name, [xy[0], xy[1], envs.TABLE_Z + 0.3], quat_wxyz=q) + self.env.sim.forward() + qa, _ = envs.free_joint_addr(self.env, name) + self.env.sim.data.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (envs.TABLE_Z + 0.0005) + self.env.sim.forward() + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + while True: + c = np.array([rng.uniform(-0.16, 0.04), rng.uniform(-0.20, 0.20)]) + bowl = np.array([rng.uniform(-0.15, 0.08), rng.uniform(-0.24, 0.24)]) + if np.linalg.norm(bowl - c) < 0.20: + continue + placed = [c, bowl] + dis = {} + for name in DISTRACTORS: + for _ in range(300): + p = np.array([rng.uniform(-0.22, 0.10), rng.uniform(-0.27, 0.27)]) + if any(np.linalg.norm(p - o) < (0.13 if k < 2 else 0.11) for k, o in enumerate(placed)): + continue + if name == JUICE: + # the 13 cm carton is taller than the hand when it grasps / releases: the Panda hand spans + # +-10.5 cm across the jaws, so keep the carton >= 17 cm from the cheese and the bowl; + # it must also not hide them from the front camera, and must stay >= 10 cm off the + # straight paths home->cheese, home->bowl and cheese->bowl + if np.linalg.norm(p - c) < 0.17 or np.linalg.norm(p - bowl) < 0.17: + continue + if any(p[0] > t[0] - 0.03 and abs(p[1] - t[1]) < 0.14 for t in (c, bowl)): + continue + if any(_seg_dist(p, a, b) < 0.10 for a, b in ((c, bowl), (HOME_XY, c), (HOME_XY, bowl))): + continue + break + else: + break + placed.append(p) + dis[name] = dict(xy=p.round(5).tolist(), yaw=float(rng.uniform(-np.pi, np.pi))) + if len(dis) == len(DISTRACTORS): + break + psi = float(rng.uniform(-CHEESE_YAW_MAX, CHEESE_YAW_MAX)) + n = np.array([-np.sin(psi), np.cos(psi)]) # jaw-closing direction for a grasp across the cheese + l = np.array([np.cos(psi), np.sin(psi)]) + r = rng.uniform(R_MIN, R_MAX) + th = rng.uniform(0, 2 * np.pi) + b = np.array([r * np.cos(th), r * np.sin(th)]) + return dict(seed=int(seed), cheese_xy=c.round(5).tolist(), cheese_yaw=psi, bowl_xy=bowl.round(5).tolist(), + distractors=dis, bias=[float(b[0]), float(b[1]), 0.0], bias_r=float(r), bias_theta=float(th), + bias_across=float(b @ n), bias_along=float(b @ l)) + + def apply_instance(self, inst): + set_gripper_stroke(self.env, GRIPPER_MAX_OPEN) + for name, mass in MASS.items(): + envs.scale_mass(self.env, name, mass) + self._place(CHEESE, inst["cheese_xy"], inst["cheese_yaw"]) + self._place(BOWL, inst["bowl_xy"], 0.0) + for name, v in inst["distractors"].items(): + self._place(name, v["xy"], v["yaw"]) + + def skill_bias(self, inst): + return np.array(inst["bias"], float) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = TrackedSkills(self.env, bias=self.skill_bias(inst), recorder=recorder) + self.start_pos = {n: envs.obj_pos(self.env, n) for n in ALL} + return self.sk + + # ------------------------------------------------------------ outcome + def in_bowl(self): + k = envs.obj_pos(self.env, BOWL) + c = envs.obj_pos(self.env, CHEESE) + base = envs.obj_min_z(self.env, BOWL) + return bool(np.linalg.norm(c[:2] - k[:2]) < BOWL_R_IN and c[2] < base + BOWL_RIM + and envs.obj_upright_cos(self.env, BOWL) > 0.9 and base < envs.TABLE_Z + 0.01) + + def outcome(self, inst): + envs.settle(self.env, 40) + sk = self.sk + k = envs.obj_pos(self.env, BOWL) + c = envs.obj_pos(self.env, CHEESE) + held = sk.holding(CHEESE) + success = bool(self.in_bowl() and not held) + picked = sk.cheese_zmax > sk.cheese_z0 + self.pick_lift_min + closes = [e for e in sk.events if e["kind"] == "close"] + last_close = closes[-1] if closes else None + releases = [e for e in sk.events if e["kind"] == "release" and last_close and e["step"] >= last_close["step"]] + end_off = c[:2] - k[:2] + moved = {n: float(np.linalg.norm(envs.obj_pos(self.env, n)[:2] - self.start_pos[n][:2])) + for n in DISTRACTORS} + out = dict(success=success, picked=bool(picked), held_at_end=bool(held), + cheese_end=c.round(4).tolist(), bowl_end=k.round(4).tolist(), end_offset=end_off.round(4).tolist(), + grasp_offset=None, release_offset=None, touched_at_close=None, + distractors_moved_cm={n: round(100 * v, 1) for n, v in moved.items()}) + grasp_txt = "" + if last_close is not None: + go = np.array(last_close["eef"][:2]) - np.array(last_close["cheese_ref"][:2]) + out["grasp_offset"] = go.round(4).tolist() + out["touched_at_close"] = last_close["touching"] + out["cheese_pushed_cm"] = round(100 * float(np.linalg.norm( + np.array(last_close["cheese"][:2]) - np.array(last_close["cheese_ref"][:2]))), 1) + grasp_txt = (f"The gripper closed {dir_words(*go)} of the centre of the cream cheese (measured where " + f"the cheese was before the fingers touched it)") + if releases: + r = releases[-1] + out["release_offset"] = (np.array(r["cheese"][:2]) - np.array(r["bowl"][:2])).round(4).tolist() + if success: + out["failure"] = None + detail = "The cream cheese is in the bowl." + if grasp_txt: + detail += f" {grasp_txt}." + elif not picked: + out["failure"] = "missed_grasp" + if last_close is None: + detail = "The gripper never closed; the cream cheese was not picked up." + else: + on = [NAMES[n] for n in last_close["touching"] if n != CHEESE] + why = "" + if on: + why = (f" A finger landed on top of the {' and the '.join(on)} instead of going down beside the " + f"cheese, so the jaws closed above the cheese.") + elif CHEESE in last_close["touching"] and not sk.holding(CHEESE): + why = " A finger came down on top of the cream cheese instead of beside it." + elif not last_close["touching"] and last_close.get("cheese_top") is not None: + above = last_close["eef"][2] - envs.FINGERTIP_BELOW_SITE - last_close["cheese_top"] + if above > 0.002: # closed in the air, entirely above the cheese + why = (f" The fingers closed in the air without touching anything: the fingertips were " + f"{100 * above:.1f} cm above the top of the cream cheese.") + detail = f"{grasp_txt} and did not pick it up.{why} The cream cheese is still on the table." + elif held: + out["failure"] = "not_released" + detail = f"{grasp_txt} and picked it up, but the cream cheese is still in the gripper." + elif releases: + out["failure"] = "missed_place" + detail = (f"{grasp_txt} and picked it up. When the gripper opened, the cream cheese was " + f"{dir_words(*out['release_offset'])} of the bowl's centre; it did not end up in the bowl " + f"(it is now {dir_words(*end_off)} of the bowl's centre).") + else: + out["failure"] = "dropped" + detail = (f"{grasp_txt} and picked it up, but it slipped out of the gripper before it was released; " + f"it is now {dir_words(*end_off)} of the bowl's centre.") + out["detail"] = detail + ind = detail + for k in (JUICE, "chocolate_pudding_1", "butter_1", CHEESE, BOWL): # longest names first + ind = ind.replace(NAMES[k], DESCR[k]) + out["detail_indirect"] = ind + return out + + def feedback(self, inst, out, level="F2", indirect=False): + """F0: nothing, F1: success flag, F2: measured offsets. `indirect` uses descriptive object names.""" + if indirect and level == "F2": + out = dict(out, detail=out.get("detail_indirect", out["detail"])) + return super().feedback(inst, out, level) + + # ------------------------------------------------------------ scripted execution (cross protocol) + def execute(self, inst, params): + """Top-down pick across the cheese's short side, carry, release above the bowl. + params['offset'] (xy) is the policy's own correction, added to every commanded position.""" + sk = self.sk + off = np.array(params.get("offset", [0.0, 0.0]), float) + c = envs.obj_pos(self.env, CHEESE) # perfect perception of the current scene + yaw = self.grasp_yaw() + k = envs.obj_pos(self.env, BOWL) + z_rel = envs.obj_min_z(self.env, BOWL) + BOWL_RIM + RELEASE_ABOVE_RIM + g, p = c[:2] + off, k[:2] + off + sk.set_gripper(False, steps=8) + sk.move_to([g[0], g[1], Z_CARRY], yaw=yaw) # approach from above, clear of the 13 cm carton + sk.move_to([g[0], g[1], Z_GRASP + 0.08], tol=0.002) + sk.move_to([g[0], g[1], Z_GRASP], tol=0.003, max_steps=80) + sk.set_gripper(True, steps=15) + sk.move_to([g[0], g[1], Z_CARRY], speed=0.3) + if not sk.holding(CHEESE): # missed: a real controller sees the jaws closed on nothing and stops + return + sk.move_to([p[0], p[1], Z_CARRY], tol=0.003) + sk.move_to([p[0], p[1], z_rel], tol=0.003, max_steps=100) + sk.set_gripper(False, steps=12) + sk.move_to([p[0], p[1], Z_CARRY], speed=0.3) + + def grasp_yaw(self): + """Gripper yaw that closes the jaws across the cheese's short side (yaw 0 closes along world y).""" + xmat = self.env.sim.data.body_xmat[envs.body_id(self.env, CHEESE)].reshape(3, 3) + a = np.arctan2(xmat[1, 0], xmat[0, 0]) # direction of the cheese's long (x) axis + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + def default_params(self, inst): + return dict(offset=[0.0, 0.0]) + + def oracle_params(self, inst): + return dict(offset=(-np.array(inst["bias"][:2])).tolist()) + + def adapt_params(self, inst, history): + """Scripted F2 learner: the reported grasp offset (where the gripper closed relative to the cheese's + centre) measures the calibration offset; accumulate it into the correction subtracted from every + commanded position. If the gripper never closed, fall back to the release offset.""" + last = history[-1] + off = np.array(last["params"]["offset"], float) + o = last["outcome"] + if o.get("grasp_offset") is not None: + off = off - np.array(o["grasp_offset"]) + elif o.get("release_offset") is not None: + off = off - np.array(o["release_offset"]) + return dict(offset=off.round(4).tolist()) + + blind_sigma = 0.005 + + def blind_params(self, inst, attempt, rng): + """Retry the same plan with a small random perturbation of the targets; no use of history.""" + return dict(offset=rng.normal(0.0, self.blind_sigma, 2).round(4).tolist()) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l1_height.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l1_height.py new file mode 100644 index 0000000000000000000000000000000000000000..2f646b10c0ee78aeac6f5ce86d655bc26a42dc86 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l1_height.py @@ -0,0 +1,448 @@ +"""L1-B height_bias: pick up a thin tile from the top of a wooden block and put it on the plate, with an arm whose +vertical calibration is off. + +Category system_identification (level L1, action fine-tuning): the method (top-down pick across the tile's short +side with the fingertips just above the block's top, carry, release above the plate) and the scene understanding +are right; only the robot's own vertical execution is off. + +Hidden variable: a fixed vertical calibration offset dz ~ U[2.0, 3.5] cm (always upward), added to every +commanded gripper position (`Skills(bias=(0, 0, dz))`): the gripper stops dz higher than commanded. The agent never +sees dz; positions reported back to it are in the commanded frame (`HeightSkills.reported_eef_pos`, and the agent +harness reports eef - bias), so the robot "believes" it reached the commanded height. + +Why the prior fails: the tile is 1.0 cm thick. Sent to the right height (fingertips just above the block's top), the +fingertips actually stop 2-3.5 cm higher, i.e. 1.1-2.6 cm above the tile's top face, and the jaws close in the air +above it (measured tolerance, 6 layouts: upward errors up to 0.4 cm still grasp, >= 0.7 cm never do, i.e. the fingers +must overlap the tile by ~4 mm). dz >= 2 cm also defeats a prior that aims lower: even with the grasp point commanded +level with the block's top (fingertips ~1 cm into the block), the fingertips end up >= 1.05 cm above the block's +top, i.e. not below the tile's top face -> missed. +Visible in the agentview image (gap between the closed fingers and the tile) and in the wrist image (fingers closed +over the tile). +A downward error would not fail (the fingertips land on the block's top and the compliant OSC still closes on the +tile; measured for -1 and -2 cm), so the offset is upward only. + +Why a raised block: the agent's move_to clips commanded targets to >= table + 0.5 cm. With the tile on the table, +compensating a 2-3.5 cm upward offset would need commands below the table top, which the interface refuses; on a +6-10 cm block the compensated commands stay well inside the workspace. + +What has to be learned: F2 reports how far above the tile's top face the grasp point and the fingertips were when the +jaws closed. Compared with where the policy meant to put them, that is dz itself, so after one failure dz can be +estimated and subtracted from every commanded height (pick and place alike). +""" +import re + +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +TILE, STAND, PLATE = "tile_1", "stand_1", "plate_1" +DISTRACTORS = ("butter_1", "chocolate_pudding_1") +FREE_OBJECTS = (TILE, PLATE) + DISTRACTORS +NAMES = {TILE: "red tile", STAND: "wooden block", PLATE: "plate", "butter_1": "butter", + "chocolate_pudding_1": "chocolate pudding"} +DESCR = {TILE: "thin red slab", STAND: "large wooden pedestal", PLATE: "round white dish", "butter_1": "small orange box", + "chocolate_pudding_1": "brown box"} + +TILE_HALF = (0.040, 0.0225, 0.005) # 8.0 x 4.5 x 1.0 cm (long side along the tile's x axis) +TILE_T = 2 * TILE_HALF[2] +STAND_HALF_XY = (0.075, 0.085) # 15 x 17 cm top +STAND_H_RANGE = (0.06, 0.10) +MASS = {TILE: 0.072, "butter_1": 0.250, "chocolate_pudding_1": 0.200, PLATE: 0.350} + +FINGER_BELOW_SITE = 0.0095 # lowest point of the finger collision meshes below the grasp site (measured 0.95 cm) +SITE_ABOVE_SURFACE = 0.0105 # scripted grasp height: grasp point 1.05 cm above the block top (fingertips ~1 mm above) +CARRY_ABOVE = 0.12 # carry height above the block top +RELEASE_GAP = 0.012 # tile bottom this far above the plate's rim at release +PLATE_R_OK = 0.040 # success: tile centre within this horizontal distance of the plate centre +DZ_MIN, DZ_MAX = 0.020, 0.035 +TILE_YAW_MAX = np.deg2rad(40) +HOME_XY = np.array([-0.21, 0.0]) + + +def _seg_dist(p, a, b): + ab = b - a + u = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0, 1) + return float(np.linalg.norm(a + u * ab - p)) + + +def _q(axis, a): + h = a / 2 + return {"z": np.array([np.cos(h), 0, 0, np.sin(h)])}[axis] + + +def _qmul(a, b): + w1, x1, y1, z1 = a + w2, x2, y2, z2 = b + return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, + w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2]) + + +def dir_words(dx, dy): + """Robot-frame description: +x = forward (away from the robot), +y = the robot's left.""" + parts = [] + if abs(dy) >= 0.0005: + parts.append(f"{100 * abs(dy):.1f} cm to the robot's {'left (+y)' if dy > 0 else 'right (-y)'}") + if abs(dx) >= 0.0005: + parts.append(f"{100 * abs(dx):.1f} cm {'forward (+x, away from the robot)' if dx > 0 else 'backward (-x, toward the robot)'}") + return " and ".join(parts) if parts else "exactly at the position" + + +def vert_words(h, what): + if h >= 0.0005: + return f"{100 * h:.1f} cm above {what}" + if h <= -0.0005: + return f"{100 * -h:.1f} cm below {what}" + return f"level with {what}" + + +class HeightSkills(Skills): + """Skills that log what the outcome measurement needs, whoever drives them (scripted policy or agent).""" + + def __init__(self, env, bias=None, recorder=None, stand_geoms=()): + super().__init__(env, bias=bias, recorder=recorder) + self.events = [] + m = env.sim.model + self._finger_geoms = { + side: [m.geom_name2id(g) for g in env.robots[0].gripper.important_geoms[side]] + for side in ("left_finger", "right_finger")} + self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_")] + self._obj_geoms = {n: envs.obj_geom_ids(env, n) for n in FREE_OBJECTS} + self._obj_geoms[STAND] = list(stand_geoms) + self.tile_z0 = float(envs.obj_pos(env, TILE)[2]) + self.tile_zmax = self.tile_z0 + self.tile_ref = envs.obj_pos(env, TILE) # tile position before the fingers last touched it + self.tile_ref_yaw = self.tile_yaw() + + def reported_eef_pos(self): + """End-effector position as the miscalibrated robot believes it to be (commanded frame). Anything shown to + the agent must use this, never eef_pos(), which is the true position and reveals the bias.""" + return self.eef_pos() - self.bias + + def move_to(self, target, *args, **kwargs): + rep = super().move_to(target, *args, **kwargs) + rep["pos"] = np.round(self.reported_eef_pos(), 4).tolist() + return rep + + def touching(self): + return [n for n, gs in self._obj_geoms.items() if envs.contacts_between(self.env, self._grip_geoms, gs)] + + def holding_tile(self): + """Both fingers in contact with the tile (robosuite's _check_grasp needs the finger *pads*, which miss a + 1 cm tile when it is gripped low on the finger meshes).""" + tg = self._obj_geoms[TILE] + return all(envs.contacts_between(self.env, gs, tg) for gs in self._finger_geoms.values()) + + def holding(self, obj_name): + """The agent harness reports `holding_object` through this; use the finger-contact test for the tile so a + tile gripped low on the fingers is not reported as dropped.""" + if obj_name == TILE: + return self.holding_tile() + return super().holding(obj_name) + + def tile_yaw(self): + xmat = self.env.sim.data.body_xmat[envs.body_id(self.env, TILE)].reshape(3, 3) + return float(np.arctan2(xmat[1, 0], xmat[0, 0])) + + def finger_min_z(self): + return float(self.eef_pos()[2] - FINGER_BELOW_SITE) + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.tile_zmax = max(self.tile_zmax, float(envs.obj_pos(self.env, TILE)[2])) + if self.grip < 0 and not envs.contacts_between(self.env, self._grip_geoms, self._obj_geoms[TILE]): + self.tile_ref = envs.obj_pos(self.env, TILE) + self.tile_ref_yaw = self.tile_yaw() + + def set_gripper(self, close, steps=15): + if close and self.grip < 0: + self.events.append(dict(kind="close", eef=self.eef_pos().tolist(), finger_z=self.finger_min_z(), + tile=envs.obj_pos(self.env, TILE).tolist(), + tile_ref=np.asarray(self.tile_ref).tolist(), tile_ref_yaw=self.tile_ref_yaw, + touching=self.touching(), + step=self.n_steps)) + elif not close and self.grip > 0 and self.holding_tile(): + self.events.append(dict(kind="release", eef=self.eef_pos().tolist(), + tile=envs.obj_pos(self.env, TILE).tolist(), + plate=envs.obj_pos(self.env, PLATE).tolist(), step=self.n_steps)) + return super().set_gripper(close, steps) + + +@register_task +class HeightBias(LFFTask): + name = "l1_height_bias" + level = "L1" + category = "system_identification" + capabilities = ("Perceive", "Utilize") + protocol = "cross" + instruction = "Pick up the red tile from the top of the wooden block and put it on the plate." + instruction_indirect = ("Pick up the thin flat red slab lying on the large wooden pedestal and put it on the " + "round white dish.") + pick_lift_min = 0.03 + + # ------------------------------------------------------------ scene + def make_bddl(self): + tile = register_generated("LffHbTile", box_xml("lff_hb_tile", TILE_HALF, (0.80, 0.16, 0.12, 1.0), + density=2000)) + stand = register_generated("LffHbStand", box_xml("lff_hb_stand", STAND_HALF_XY + (STAND_H_RANGE[1] / 2,), + (0.62, 0.47, 0.30, 1.0), density=1000), free=False) + objs = [(TILE, tile, "tile_region", (-0.21, -0.26, -0.19, -0.24)), + (PLATE, "plate", "plate_region", (-0.01, 0.24, 0.01, 0.26)), + ("butter_1", "butter", "butter_region", (-0.21, 0.24, -0.19, 0.26)), + ("chocolate_pudding_1", "chocolate_pudding", "pudding_region", (0.15, -0.26, 0.17, -0.24))] + fx = [(STAND, stand, "stand_region", (0.09, -0.01, 0.11, 0.01))] + return write_bddl(self.name, self.instruction, objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + self._base_quat = {n: envs.obj_quat(self.env, n) for n in FREE_OBJECTS} + m = self.env.sim.model + bid = m.body_name2id(self.env.fixtures_dict[STAND].root_body) + + def under(b): + while b > 0: + if b == bid: + return True + b = m.body_parentid[b] + return False + + self._stand_bid = bid + self._stand_geoms = [g for g in range(m.ngeom) if under(m.geom_bodyid[g])] + + def _place(self, name, xy, yaw, z0=envs.TABLE_Z): + q = _qmul(_q("z", yaw), self._base_quat[name]) + envs.set_obj_pose(self.env, name, [xy[0], xy[1], z0 + 0.3], quat_wxyz=q) + self.env.sim.forward() + qa, _ = envs.free_joint_addr(self.env, name) + self.env.sim.data.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (z0 + 0.0005) + self.env.sim.forward() + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + while True: + s = np.array([rng.uniform(-0.10, 0.02), rng.uniform(-0.17, 0.17)]) + plate = np.array([rng.uniform(-0.17, 0.08), rng.uniform(-0.25, 0.25)]) + if np.linalg.norm(plate - s) < 0.24 or abs(plate[1] - s[1]) < 0.12: + continue # not right behind the block as seen from the front camera + placed = [s, plate] + dis = {} + for name in DISTRACTORS: + for _ in range(300): + p = np.array([rng.uniform(-0.22, 0.12), rng.uniform(-0.27, 0.27)]) + if np.linalg.norm(p - s) < 0.16 or any(np.linalg.norm(p - o) < 0.12 for o in placed[1:]): + continue + if any(_seg_dist(p, a, b) < 0.09 for a, b in ((s, plate), (HOME_XY, s))): + continue + break + else: + break + placed.append(p) + dis[name] = dict(xy=p.round(5).tolist(), yaw=float(rng.uniform(-np.pi, np.pi))) + if len(dis) == len(DISTRACTORS): + break + stand_h = float(rng.uniform(*STAND_H_RANGE)) + tile_xy = s + rng.uniform(-0.02, 0.02, 2) + tile_yaw = float(rng.uniform(-TILE_YAW_MAX, TILE_YAW_MAX)) + dz = float(rng.uniform(DZ_MIN, DZ_MAX)) + return dict(seed=int(seed), stand_xy=s.round(5).tolist(), stand_h=stand_h, tile_xy=tile_xy.round(5).tolist(), + tile_yaw=tile_yaw, plate_xy=plate.round(5).tolist(), distractors=dis, bias=[0.0, 0.0, dz], + bias_dz=dz) + + def stand_top(self, inst): + return envs.TABLE_Z + inst["stand_h"] + + def apply_instance(self, inst): + m = self.env.sim.model + h = inst["stand_h"] + for g in self._stand_geoms: + m.geom_size[g, 2] = h / 2 + m.body_pos[self._stand_bid] = [inst["stand_xy"][0], inst["stand_xy"][1], envs.TABLE_Z + h / 2] + m.body_quat[self._stand_bid] = [1, 0, 0, 0] + for name, mass in MASS.items(): + envs.scale_mass(self.env, name, mass) + self.env.sim.forward() + self._place(TILE, inst["tile_xy"], inst["tile_yaw"], z0=self.stand_top(inst)) + self._place(PLATE, inst["plate_xy"], 0.0) + for name, v in inst["distractors"].items(): + self._place(name, v["xy"], v["yaw"]) + + def skill_bias(self, inst): + return np.array(inst["bias"], float) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = HeightSkills(self.env, bias=self.skill_bias(inst), recorder=recorder, stand_geoms=self._stand_geoms) + self.start_pos = {n: envs.obj_pos(self.env, n) for n in FREE_OBJECTS} + return self.sk + + # ------------------------------------------------------------ outcome + def plate_rim_z(self): + lo, hi = self._aabb(PLATE) + return float(hi[2]) + + def _aabb(self, name): + m, d = self.env.sim.model, self.env.sim.data + lo, hi = np.full(3, np.inf), np.full(3, -np.inf) + for g in envs.obj_geom_ids(self.env, name): + R = d.geom_xmat[g].reshape(3, 3) + c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3] + hh = np.abs(R) @ m.geom_aabb[g, 3:] + lo, hi = np.minimum(lo, c - hh), np.maximum(hi, c + hh) + return lo, hi + + def on_plate(self): + p = envs.obj_pos(self.env, PLATE) + t = envs.obj_pos(self.env, TILE) + return bool(np.linalg.norm(t[:2] - p[:2]) < PLATE_R_OK and t[2] < self.plate_rim_z() + 0.015 + and envs.obj_upright_cos(self.env, PLATE) > 0.9 and envs.obj_min_z(self.env, PLATE) < envs.TABLE_Z + 0.01) + + def outcome(self, inst): + envs.settle(self.env, 40) + sk = self.sk + top = self.stand_top(inst) + p = envs.obj_pos(self.env, PLATE) + t = envs.obj_pos(self.env, TILE) + held = sk.holding_tile() + success = bool(self.on_plate() and not held) + picked = sk.tile_zmax > sk.tile_z0 + self.pick_lift_min + closes = [e for e in sk.events if e["kind"] == "close"] + last_close = closes[-1] if closes else None + releases = [e for e in sk.events if e["kind"] == "release" and last_close and e["step"] >= last_close["step"]] + end_off = t[:2] - p[:2] + on_stand = bool(t[2] > top - 0.005) + out = dict(success=success, picked=bool(picked), held_at_end=bool(held), tile_end=t.round(4).tolist(), + plate_end=p.round(4).tolist(), end_offset=end_off.round(4).tolist(), grasp_height=None, + fingertip_gap=None, grasp_xy_offset=None, touched_at_close=None, release_offset=None) + grasp_txt = "" + over_tile = True + if last_close is not None: + tile_top = last_close["tile_ref"][2] + TILE_HALF[2] + gh = last_close["eef"][2] - tile_top + fg = last_close["finger_z"] - tile_top + go = np.array(last_close["eef"][:2]) - np.array(last_close["tile_ref"][:2]) + a = last_close.get("tile_ref_yaw", 0.0) + along, across = go @ [np.cos(a), np.sin(a)], go @ [-np.sin(a), np.cos(a)] + # grasp point over the tile's footprint (the open fingers straddle it across its short side) + over_tile = bool(abs(along) <= TILE_HALF[0] and abs(across) <= TILE_HALF[1] + 0.01) + out["grasp_height"] = round(gh, 4) + out["fingertip_gap"] = round(fg, 4) + out["grasp_xy_offset"] = go.round(4).tolist() + out["grasp_over_tile"] = over_tile + out["touched_at_close"] = last_close["touching"] + face = "the top face of the red tile" if over_tile else "the level of the red tile's top face" + grasp_txt = (f"When the jaws closed, the grasp point (midway between the fingertips) was " + f"{vert_words(gh, face)} and the lowest points of the fingertips " + f"were {vert_words(fg, 'it')} (the tile is {100 * TILE_T:.1f} cm thick)") + if not over_tile or np.linalg.norm(go) >= 0.01: + grasp_txt += (f"; horizontally the grasp point was {dir_words(*go)} of the tile's centre" + + ("" if over_tile else ", i.e. not over the tile")) + if success: + out["failure"] = None + detail = "The red tile is on the plate." + if grasp_txt: + detail += f" {grasp_txt}." + elif not picked: + out["failure"] = "missed_grasp" + if last_close is None: + detail = "The gripper never closed; the red tile was not picked up." + else: + touch = last_close["touching"] + if not over_tile and TILE not in touch: + why = " The gripper was not over the tile when it closed." + elif fg > 0.0005 and TILE not in touch: + why = " The fingers closed in the air above the tile without touching it." + elif STAND in touch and TILE not in touch: + why = " The fingertips were pressed on the top of the wooden block but did not grip the tile." + elif TILE in touch: + why = " The fingers touched the tile but did not get a grip on it." + else: + why = "" + where = "still on the wooden block" if on_stand else "no longer on the wooden block" + detail = f"{grasp_txt}, and the tile was not picked up.{why} The tile is {where}." + elif held: + out["failure"] = "not_released" + detail = f"{grasp_txt}, and the tile was picked up, but it is still in the gripper." + elif releases: + r = releases[-1] + out["release_offset"] = (np.array(r["tile"][:2]) - np.array(r["plate"][:2])).round(4).tolist() + out["failure"] = "missed_place" + detail = (f"{grasp_txt}, and the tile was picked up. When the gripper opened, the tile was " + f"{dir_words(*out['release_offset'])} of the plate's centre; it did not end up on the plate " + f"(it is now {dir_words(*end_off)} of the plate's centre).") + else: + out["failure"] = "dropped" + detail = (f"{grasp_txt}, and the tile was lifted, but it slipped out of the fingers before it was " + f"released; it is now {dir_words(*end_off)} of the plate's centre.") + out["detail"] = detail + ind = detail + for k in sorted(NAMES, key=lambda n: -len(NAMES[n])): + ind = ind.replace(NAMES[k], DESCR[k]) + ind = re.sub(r"\btile\b", "slab", ind) # the bare noun would give the direct name away + out["detail_indirect"] = ind + return out + + def feedback(self, inst, out, level="F2", indirect=False): + if indirect and level == "F2": + out = dict(out, detail=out.get("detail_indirect", out["detail"])) + return super().feedback(inst, out, level) + + # ------------------------------------------------------------ scripted execution (cross protocol) + def grasp_yaw(self): + """Gripper yaw that closes the jaws across the tile's short side (yaw 0 closes along world y).""" + xmat = self.env.sim.data.body_xmat[envs.body_id(self.env, TILE)].reshape(3, 3) + a = np.arctan2(xmat[1, 0], xmat[0, 0]) + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + def execute(self, inst, params): + """Top-down pick across the tile's short side with the fingertips just above the block top, carry, release + above the plate. params['dz'] is the policy's own height correction, added to every commanded z.""" + sk = self.sk + dz = float(params.get("dz", 0.0)) + t = envs.obj_pos(self.env, TILE) # perfect perception of the current scene + top = self.stand_top(inst) + yaw = self.grasp_yaw() + p = envs.obj_pos(self.env, PLATE) + z_grasp = top + SITE_ABOVE_SURFACE + dz + z_carry = top + CARRY_ABOVE + dz + z_rel = self.plate_rim_z() + RELEASE_GAP + SITE_ABOVE_SURFACE + dz + sk.set_gripper(False, steps=8) + sk.move_to([t[0], t[1], z_carry], yaw=yaw) + sk.move_to([t[0], t[1], z_grasp + 0.05], tol=0.002) + sk.move_to([t[0], t[1], z_grasp], tol=0.003, max_steps=80) + sk.set_gripper(True, steps=15) + sk.move_to([t[0], t[1], z_carry], speed=0.3) + if not sk.holding_tile(): # missed: a real controller sees the jaws closed on nothing and stops + return + sk.move_to([p[0], p[1], z_carry], tol=0.003) + sk.move_to([p[0], p[1], z_rel], tol=0.003, max_steps=100) + sk.set_gripper(False, steps=12) + sk.move_to([p[0], p[1], z_carry], speed=0.3) + + def default_params(self, inst): + return dict(dz=0.0) + + def oracle_params(self, inst): + return dict(dz=-float(inst["bias"][2])) + + def adapt_params(self, inst, history): + """Scripted F2 learner: the reported grasp height above the tile's top face, minus the height this policy + meant to put the grasp point at (SITE_ABOVE_SURFACE - tile thickness), is the vertical offset; accumulate + it into the correction subtracted from every commanded height.""" + last = history[-1] + dz = float(last["params"]["dz"]) + o = last["outcome"] + if o.get("grasp_height") is not None: + dz -= o["grasp_height"] - (SITE_ABOVE_SURFACE - TILE_T) + return dict(dz=round(dz, 4)) + + blind_sigma = 0.005 + + def blind_params(self, inst, attempt, rng): + """Retry the same plan with a small random perturbation of the commanded heights; no use of history.""" + return dict(dz=round(float(rng.normal(0.0, self.blind_sigma)), 4)) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l1_yaw.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l1_yaw.py new file mode 100644 index 0000000000000000000000000000000000000000..9bec2a49ccd283ea359cad9dd9b87efbbae7f9ac --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l1_yaw.py @@ -0,0 +1,439 @@ +"""L1-C yaw_bias: put a long bar into a narrow holder, with an arm whose wrist rotation is miscalibrated. + +Category system_identification (level L1, action fine-tuning): the method (top-down pick across the bar, carry, +line the bar up with the holder, release just above the holder) and the scene understanding are right; only the +robot's own wrist rotation is off. + +Hidden variable: a fixed wrist-yaw calibration offset beta, |beta| ~ U[15, 30] deg with a random sign: every +commanded gripper yaw theta is executed as theta + beta. The robot reports its yaw in its own (miscalibrated) frame, +so the agent's proprioception says "yaw = theta" (implemented by shifting the robot's notion of yaw 0, `Skills.R0`, +by beta: the agent harness computes the reported yaw from R0, so beta never shows up in a reading). At reset the +wrist is turned to the robot's own yaw 0 (true yaw beta), so the first reading is 0. + +Why the prior fails: the bar is 14 cm long and 1.8 cm wide; the holder's opening is 3.2 cm wide (16 cm long). +Commanded to grasp square across the bar, the jaws actually come down rotated by beta; closing turns the bar until it +lies square in the jaws, so the bar ends up rotated by beta relative to where the robot thinks it is. Lined up +"exactly" with the holder, the bar is then beta off the holder's axis; its footprint across the opening +(14 sin beta + 1.8 cos beta >= 5.4 cm for beta >= 15 deg) is wider than the holder (4.4 cm outside), so it comes +down across the walls and stays on top of the holder at an angle -- clearly visible from both cameras. The +alignment tolerance is about +-5 deg (geometry; measured: see the task card). + +What has to be learned: F2 reports by how many degrees, and in which sense, the bar's long axis was rotated from the +holder's long axis when the gripper opened (and how far the jaws were turned from square to the bar when they +closed). That angle is beta itself, so after one failure beta can be estimated and subtracted from every commanded +yaw. +""" +import re + +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import bin_xml, box_xml, register_generated +from ..skills import Skills, _rotz +from ..task_base import LFFTask, register_task + +BAR, HOLDER = "bar_1", "holder_1" +DISTRACTORS = ("cream_cheese_1", "butter_1") +FREE_OBJECTS = (BAR,) + DISTRACTORS +NAMES = {BAR: "blue bar", HOLDER: "holder", "cream_cheese_1": "cream cheese", "butter_1": "butter"} +DESCR = {BAR: "long blue stick", HOLDER: "narrow grey trough", "cream_cheese_1": "flat blue box", + "butter_1": "small orange box"} + +BAR_HALF = (0.070, 0.009, 0.009) # 14 x 1.8 x 1.8 cm, long side along the bar's x axis +HOLDER_IN = (0.080, 0.016) # inner half extents of the holder's opening: 16 x 3.2 cm +WALL_T, FLOOR_T, WALL_H = 0.006, 0.006, 0.030 +HOLDER_HALF_H = (WALL_H + FLOOR_T) / 2 # body origin at mid height +RIM_Z = envs.TABLE_Z + FLOOR_T + WALL_H +MASS = {BAR: 0.070, "cream_cheese_1": 0.227, "butter_1": 0.250} +# Bar friction 0.5 with geom priority, so it is used for all bar contacts (also against the finger pads, mu 2). With +# the pads' mu 2 the jaws pinch a misaligned bar at their corners and it stays skewed in the hand (measured: turned +# 3-13 deg of beta 15-25 deg while closing); with 0.5 the closing jaws square it up (turned = beta, measured). +BAR_MU = 0.5 + +SITE_ABOVE_TABLE = 0.0105 # grasp point 1.05 cm above the table: fingertips ~1 mm above it +Z_CARRY = envs.TABLE_Z + 0.15 +RELEASE_GAP = 0.012 # bar bottom this far above the holder's rim at release +BETA_MIN, BETA_MAX = np.deg2rad(15), np.deg2rad(30) +AXIS_MAX = np.deg2rad(45) # bar / holder long axes within +-45 deg of the forward (x) direction +HOME_XY = np.array([-0.21, 0.0]) +REHOME_STEPS = 40 + + +def wrap_half(a): + """angle modulo pi into [-pi/2, pi/2) (the bar, the holder and the jaws are 180-deg symmetric)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def _yaw_of_xmat(xmat): + return float(np.arctan2(xmat[1, 0], xmat[0, 0])) + + +def _seg_dist(p, a, b): + ab = b - a + u = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0, 1) + return float(np.linalg.norm(a + u * ab - p)) + + +def _q(axis, a): + h = a / 2 + return {"z": np.array([np.cos(h), 0, 0, np.sin(h)])}[axis] + + +def _qmul(a, b): + w1, x1, y1, z1 = a + w2, x2, y2, z2 = b + return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, + w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2]) + + +def dir_words(dx, dy): + """Robot-frame description: +x = forward (away from the robot), +y = the robot's left.""" + parts = [] + if abs(dy) >= 0.0005: + parts.append(f"{100 * abs(dy):.1f} cm to the robot's {'left (+y)' if dy > 0 else 'right (-y)'}") + if abs(dx) >= 0.0005: + parts.append(f"{100 * abs(dx):.1f} cm {'forward (+x, away from the robot)' if dx > 0 else 'backward (-x, toward the robot)'}") + return " and ".join(parts) if parts else "exactly at the position" + + +def rot_words(a): + """Sense of a rotation about the vertical axis. Positive = counter-clockwise seen from above = from forward (+x) + towards the robot's left (+y) = increasing yaw.""" + d = np.degrees(a) + if abs(d) < 0.5: + return "not rotated (within 0.5 deg)" + if d > 0: + return f"rotated {d:.0f} deg counter-clockwise seen from above (from forward towards the robot's left, +yaw)" + return f"rotated {-d:.0f} deg clockwise seen from above (from forward towards the robot's right, -yaw)" + + +class YawSkills(Skills): + """Skills with a miscalibrated wrist: commanded yaw theta is executed as theta + yaw_bias. Implemented by shifting + the robot's notion of yaw 0 (`R0`, which Skills uses to build every orientation target and the agent harness uses + to report the yaw) by yaw_bias; `R0_true` is the real top-down orientation at yaw 0. Also logs what the outcome + measurement needs, whoever drives the skills (scripted policy or agent).""" + + def __init__(self, env, yaw_bias=0.0, recorder=None): + super().__init__(env, bias=None, recorder=recorder) + self.yaw_bias = float(yaw_bias) + self.R0_true = self.R0.copy() + self.R0 = _rotz(self.yaw_bias) @ self.R0_true + self.events = [] + m = env.sim.model + self._finger_geoms = { + side: [m.geom_name2id(g) for g in env.robots[0].gripper.important_geoms[side]] + for side in ("left_finger", "right_finger")} + self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_")] + self._obj_geoms = {n: envs.obj_geom_ids(env, n) for n in FREE_OBJECTS} + self.bar_z0 = float(envs.obj_pos(env, BAR)[2]) + self.bar_zmax = self.bar_z0 + self.bar_ref_yaw = self.bar_yaw() + self.bar_ref = envs.obj_pos(env, BAR) # bar pose before the fingers last touched it + + # ------------------------------------------------------------------ state + def true_yaw(self): + return _yaw_of_xmat(self.eef_mat() @ self.R0_true.T) + + def reported_yaw(self): + """Yaw as the miscalibrated robot believes it to be. Anything shown to the agent must use this.""" + return _yaw_of_xmat(self.eef_mat() @ self.R0.T) + + def bar_yaw(self): + return _yaw_of_xmat(self.env.sim.data.body_xmat[envs.body_id(self.env, BAR)].reshape(3, 3)) + + def touching(self): + return [n for n, gs in self._obj_geoms.items() if envs.contacts_between(self.env, self._grip_geoms, gs)] + + def holding_bar(self): + bg = self._obj_geoms[BAR] + return all(envs.contacts_between(self.env, gs, bg) for gs in self._finger_geoms.values()) + + def holding(self, obj_name): + """The agent harness reports `holding_object` through this; same finger-contact test as the outcome.""" + if obj_name == BAR: + return self.holding_bar() + return super().holding(obj_name) + + def wrap_yaw(self, yaw): + """Like Skills.wrap_yaw (the gripper is symmetric under pi), but the window |yaw| <= YAW_LIMIT is applied + to the TRUE wrist yaw (commanded + yaw_bias): the joint-7 limit is a property of the real wrist. Without + this, a commanded -113 deg with yaw_bias -30 deg drives joint 7 into its limit (measured: stops at true + -137 deg, reported -107 deg).""" + cands = [yaw + k * np.pi for k in range(-3, 4)] + ok = [c for c in cands if abs(c + self.yaw_bias) <= self.YAW_LIMIT] or cands + return float(min(ok, key=lambda c: abs(c - self.yaw))) + + def move_to(self, target, *args, **kwargs): + rep = super().move_to(target, *args, **kwargs) + rep["yaw_reported_deg"] = round(float(np.degrees(self.reported_yaw())), 1) + return rep + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.bar_zmax = max(self.bar_zmax, float(envs.obj_pos(self.env, BAR)[2])) + if self.grip < 0 and not envs.contacts_between(self.env, self._grip_geoms, self._obj_geoms[BAR]): + self.bar_ref_yaw = self.bar_yaw() + self.bar_ref = envs.obj_pos(self.env, BAR) + + def set_gripper(self, close, steps=15): + if close and self.grip < 0: + self.events.append(dict(kind="close", eef=self.eef_pos().tolist(), true_yaw=self.true_yaw(), + bar=envs.obj_pos(self.env, BAR).tolist(), bar_ref_yaw=self.bar_ref_yaw, + bar_ref=np.asarray(self.bar_ref).tolist(), touching=self.touching(), + step=self.n_steps)) + elif not close and self.grip > 0 and self.holding_bar(): + self.events.append(dict(kind="release", eef=self.eef_pos().tolist(), true_yaw=self.true_yaw(), + bar=envs.obj_pos(self.env, BAR).tolist(), bar_yaw=self.bar_yaw(), + step=self.n_steps)) + rep = super().set_gripper(close, steps) + if close and self.events and self.events[-1]["kind"] == "close": + self.events[-1]["bar_yaw_after"] = self.bar_yaw() + return rep + + +@register_task +class YawBias(LFFTask): + name = "l1_yaw_bias" + level = "L1" + category = "system_identification" + capabilities = ("Perceive", "Utilize") + protocol = "cross" + instruction = "Pick up the blue bar and put it into the holder." + instruction_indirect = "Pick up the long blue stick and drop it into the narrow grey trough so that it lies inside." + pick_lift_min = 0.03 + + # ------------------------------------------------------------ scene + def make_bddl(self): + bar = register_generated("LffYbBar", box_xml("lff_yb_bar", BAR_HALF, (0.15, 0.35, 0.85, 1.0), density=1500)) + holder = register_generated("LffYbHolder", bin_xml("lff_yb_holder", HOLDER_IN, WALL_H, wall_t=WALL_T, + floor_t=FLOOR_T, rgba=(0.55, 0.56, 0.60, 1.0), + density=2000), free=False) + objs = [(BAR, bar, "bar_region", (-0.21, -0.26, -0.19, -0.24)), + ("cream_cheese_1", "cream_cheese", "cheese_region", (-0.21, 0.24, -0.19, 0.26)), + ("butter_1", "butter", "butter_region", (0.15, -0.26, 0.17, -0.24))] + fx = [(HOLDER, holder, "holder_region", (0.09, -0.01, 0.11, 0.01))] + return write_bddl(self.name, self.instruction, objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + self._base_quat = {n: envs.obj_quat(self.env, n) for n in FREE_OBJECTS} + m = self.env.sim.model + self._holder_bid = m.body_name2id(self.env.fixtures_dict[HOLDER].root_body) + + def _place(self, name, xy, yaw, z0=envs.TABLE_Z): + q = _qmul(_q("z", yaw), self._base_quat[name]) + envs.set_obj_pose(self.env, name, [xy[0], xy[1], z0 + 0.3], quat_wxyz=q) + self.env.sim.forward() + qa, _ = envs.free_joint_addr(self.env, name) + self.env.sim.data.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (z0 + 0.0005) + self.env.sim.forward() + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + while True: + b = np.array([rng.uniform(-0.16, 0.04), rng.uniform(-0.20, 0.20)]) + h = np.array([rng.uniform(-0.14, 0.06), rng.uniform(-0.22, 0.22)]) + if np.linalg.norm(h - b) < 0.22: + continue + placed = [b, h] + dis = {} + for name in DISTRACTORS: + for _ in range(300): + p = np.array([rng.uniform(-0.22, 0.12), rng.uniform(-0.27, 0.27)]) + if any(np.linalg.norm(p - o) < 0.15 for o in placed): + continue + if any(_seg_dist(p, a, c) < 0.10 for a, c in ((b, h), (HOME_XY, b))): + continue + break + else: + break + placed.append(p) + dis[name] = dict(xy=p.round(5).tolist(), yaw=float(rng.uniform(-np.pi, np.pi))) + if len(dis) == len(DISTRACTORS): + break + bar_yaw = float(rng.uniform(-AXIS_MAX, AXIS_MAX)) + holder_yaw = float(rng.uniform(-AXIS_MAX, AXIS_MAX)) + beta = float(rng.choice([-1.0, 1.0]) * rng.uniform(BETA_MIN, BETA_MAX)) + return dict(seed=int(seed), bar_xy=b.round(5).tolist(), bar_yaw=bar_yaw, holder_xy=h.round(5).tolist(), + holder_yaw=holder_yaw, distractors=dis, yaw_bias=beta, yaw_bias_deg=float(np.degrees(beta))) + + def apply_instance(self, inst): + m = self.env.sim.model + m.body_pos[self._holder_bid] = [inst["holder_xy"][0], inst["holder_xy"][1], envs.TABLE_Z + HOLDER_HALF_H] + m.body_quat[self._holder_bid] = _q("z", inst["holder_yaw"]) + for name, mass in MASS.items(): + envs.scale_mass(self.env, name, mass) + self.env.sim.forward() + self._place(BAR, inst["bar_xy"], inst["bar_yaw"]) + envs.set_friction(self.env, BAR, BAR_MU, priority=3) + for name, v in inst["distractors"].items(): + self._place(name, v["xy"], v["yaw"]) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = YawSkills(self.env, yaw_bias=inst["yaw_bias"], recorder=recorder) + self.sk.hold(REHOME_STEPS) # turn the wrist to the robot's own yaw 0 (true yaw = beta) + self.sk.n_steps = 0 + self.sk.events = [] + self.start_pos = {n: envs.obj_pos(self.env, n) for n in FREE_OBJECTS} + return self.sk + + # ------------------------------------------------------------ outcome + def holder_frame(self, xy): + """xy (world) -> (along, across) in the holder frame, relative to the holder centre""" + c = self.env.sim.model.body_pos[self._holder_bid][:2].copy() + a = self.holder_yaw() + R = np.array([[np.cos(a), np.sin(a)], [-np.sin(a), np.cos(a)]]) + return R @ (np.asarray(xy[:2]) - c) + + def holder_yaw(self): + q = self.env.sim.model.body_quat[self._holder_bid] + return float(2 * np.arctan2(q[3], q[0])) + + def in_holder(self): + p = envs.obj_pos(self.env, BAR) + u, v = self.holder_frame(p) + return bool(abs(u) < HOLDER_IN[0] and abs(v) < HOLDER_IN[1] and p[2] < RIM_Z + and envs.obj_upright_cos(self.env, BAR) > 0.95) + + def outcome(self, inst): + envs.settle(self.env, 40) + sk = self.sk + p = envs.obj_pos(self.env, BAR) + held = sk.holding_bar() + success = bool(self.in_holder() and not held) + picked = sk.bar_zmax > sk.bar_z0 + self.pick_lift_min + closes = [e for e in sk.events if e["kind"] == "close"] + last_close = closes[-1] if closes else None + releases = [e for e in sk.events if e["kind"] == "release" and last_close and e["step"] >= last_close["step"]] + hy = self.holder_yaw() + end_mis = wrap_half(sk.bar_yaw() - hy) + hc = self.env.sim.model.body_pos[self._holder_bid][:2] + out = dict(success=success, picked=bool(picked), held_at_end=bool(held), bar_end=p.round(4).tolist(), + bar_end_misalign_deg=round(float(np.degrees(end_mis)), 1), grasp_misalign=None, + bar_turned_in_grasp=None, release_misalign=None, release_offset=None, touched_at_close=None) + grasp_txt = "" + if last_close is not None: + gm = wrap_half(last_close["true_yaw"] - last_close["bar_ref_yaw"]) + turned = wrap_half(last_close.get("bar_yaw_after", last_close["bar_ref_yaw"]) - last_close["bar_ref_yaw"]) + out["grasp_misalign"] = round(gm, 4) + out["bar_turned_in_grasp"] = round(turned, 4) + out["touched_at_close"] = last_close["touching"] + go = np.array(last_close["eef"][:2]) - np.array(last_close.get("bar_ref", last_close["bar"])[:2]) + a = last_close["bar_ref_yaw"] + along, across = go @ [np.cos(a), np.sin(a)], go @ [-np.sin(a), np.cos(a)] + over_bar = bool(abs(along) <= BAR_HALF[0] and abs(across) <= BAR_HALF[1] + 0.02) + out["grasp_xy_offset"] = go.round(4).tolist() + out["grasp_over_bar"] = over_bar + if over_bar: + grasp_txt = f"When the jaws closed on the blue bar, they were {rot_words(gm)} from square across the bar" + if np.linalg.norm(go) >= 0.015: + grasp_txt += f" (the grasp point was {dir_words(*go)} of the bar's centre)" + else: + grasp_txt = (f"When the jaws closed, the grasp point was {dir_words(*go)} of the blue bar's centre, i.e. " + f"not over the bar, and the jaws were {rot_words(gm)} from square across the bar") + if abs(np.degrees(turned)) >= 2: + grasp_txt += f", and the closing fingers turned the bar by {abs(np.degrees(turned)):.0f} deg" + if releases: + r = releases[-1] + rm = wrap_half(r["bar_yaw"] - hy) + out["release_misalign"] = round(rm, 4) + out["release_offset"] = (np.array(r["bar"][:2]) - hc).round(4).tolist() + if success: + out["failure"] = None + detail = "The blue bar is inside the holder." + if out["release_misalign"] is not None: + detail += (f" When the gripper opened, the bar's long axis was {rot_words(out['release_misalign'])} " + f"from the holder's long axis.") + elif not picked: + out["failure"] = "missed_grasp" + if last_close is None: + detail = "The gripper never closed; the blue bar was not picked up." + else: + detail = f"{grasp_txt}, but the bar was not picked up. It is still on the table." + elif held: + out["failure"] = "not_released" + detail = f"{grasp_txt}. The bar was picked up but it is still in the gripper." + elif releases: + out["failure"] = "missed_place" + if p[2] > RIM_Z - 0.002: + where = (f"The bar came down across the holder's walls instead of dropping in; it is now lying on top " + f"of the holder, its long axis {rot_words(end_mis)} from the holder's long axis.") + else: + where = (f"The bar did not end up inside the holder (its centre is now " + f"{dir_words(*(p[:2] - hc))} of the holder's centre).") + detail = (f"{grasp_txt}. When the gripper opened above the holder, the bar's long axis was " + f"{rot_words(out['release_misalign'])} from the holder's long axis, and the bar's centre was " + f"{dir_words(*out['release_offset'])} of the holder's centre. {where}") + else: + out["failure"] = "dropped" + detail = (f"{grasp_txt}. The bar was lifted but slipped out of the fingers before the gripper opened; it is " + f"now {dir_words(*(p[:2] - hc))} of the holder's centre.") + out["detail"] = detail + ind = detail + for k in sorted(NAMES, key=lambda n: -len(NAMES[n])): + ind = ind.replace(NAMES[k], DESCR[k]) + ind = re.sub(r"\bbar\b", "stick", ind) # the bare noun would give the direct name away + out["detail_indirect"] = ind + return out + + def feedback(self, inst, out, level="F2", indirect=False): + if indirect and level == "F2": + out = dict(out, detail=out.get("detail_indirect", out["detail"])) + return super().feedback(inst, out, level) + + # ------------------------------------------------------------ scripted execution (cross protocol) + def execute(self, inst, params): + """Top-down pick square across the bar at its centre, carry, line the bar up with the holder and release it + just above the holder's rim. params['dyaw'] (rad) is the policy's own yaw correction, added to every + commanded yaw.""" + sk = self.sk + dy = float(params.get("dyaw", 0.0)) + b = envs.obj_pos(self.env, BAR) # perfect perception of the current scene + psi = sk.bar_yaw() + hc = self.env.sim.model.body_pos[self._holder_bid][:2].copy() + phi = self.holder_yaw() + z_grasp = envs.TABLE_Z + SITE_ABOVE_TABLE + z_rel = RIM_Z + RELEASE_GAP + SITE_ABOVE_TABLE + sk.set_gripper(False, steps=8) + sk.move_to([b[0], b[1], Z_CARRY], yaw=wrap_half(psi) + dy) + sk.move_to([b[0], b[1], z_grasp + 0.06], tol=0.002) + sk.move_to([b[0], b[1], z_grasp], tol=0.003, max_steps=80) + sk.set_gripper(True, steps=15) + sk.move_to([b[0], b[1], Z_CARRY], speed=0.3) + if not sk.holding_bar(): # missed: a real controller sees the jaws closed on nothing and stops + return + sk.move_to([hc[0], hc[1], Z_CARRY], yaw=wrap_half(phi) + dy, tol=0.003) + sk.move_to([hc[0], hc[1], z_rel], tol=0.003, max_steps=100) + sk.hold(5) + sk.set_gripper(False, steps=12) + sk.move_to([hc[0], hc[1], Z_CARRY], speed=0.3) + + def default_params(self, inst): + return dict(dyaw=0.0) + + def oracle_params(self, inst): + return dict(dyaw=-float(inst["yaw_bias"])) + + def adapt_params(self, inst, history): + """Scripted F2 learner: the reported angle between the bar and the holder when the gripper opened is the + part of the wrist offset not yet corrected; accumulate it into the correction subtracted from every + commanded yaw. If the bar was never released, use the jaw angle at the grasp instead.""" + last = history[-1] + dy = float(last["params"]["dyaw"]) + o = last["outcome"] + if o.get("release_misalign") is not None: + dy -= o["release_misalign"] + elif o.get("grasp_misalign") is not None: + dy -= o["grasp_misalign"] + return dict(dyaw=round(dy, 4)) + + blind_sigma = np.deg2rad(4.0) + + def blind_params(self, inst, attempt, rng): + """Retry the same plan with a small random perturbation of the commanded yaws; no use of history.""" + return dict(dyaw=round(float(rng.normal(0.0, self.blind_sigma)), 4)) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l2_knock.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l2_knock.py new file mode 100644 index 0000000000000000000000000000000000000000..4c7b568a618dbb97463644abff1cde34f06f6d37 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l2_knock.py @@ -0,0 +1,457 @@ +"""L2-A knock_restore: move the ketchup from the tray into the basket; everything else must stay on the tray. + +Constructed L2 event: the first time the ketchup is lifted off the tray (grasped and raised 3 cm), one of +its two neighbours on the tray is "knocked" off the tray and lands upright on the table beside it. Which +neighbour and to which side of the tray (left / right in the camera image) it falls are hidden per-instance +variables; only the scene *after* the failure shows which item is missing and where it is. The main task itself still succeeds, so an agent that stops after +the main task fails; it has to notice the side effect and put the item back (within-episode recovery). + +Protocols + within (default, `l2_knock_restore`) one episode; attempt 1 = the main task, every later attempt is one + corrective round chosen by the policy; the outcome (success + F2 text) is computed after each round. + cross (`l2_knock_restore_cross`) reset to the same instance between attempts; the knock happens again + on every attempt, so a learner must anticipate it. Validated strategy: restore the reported item + right after the main task. The rule also allows prevention (the knock only hits a neighbour that is + still within 12 cm of the ketchup's start spot), but picking a neighbour up in place is mostly blocked + by the tray's end wall (Panda hand), so prevention is not a validated strategy (see the task card). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..skills import Skills +from ..task_base import LFFTask, register_task + +TARGET = "ketchup_1" +NEIGHBOR_POOL = ("cream_cheese_1", "butter_1", "chocolate_pudding_1") +TRAY, BASKET = "wooden_tray_1", "basket_1" +PARK_XY = {"cream_cheese_1": (0.0, 1.2), "butter_1": (0.2, 1.2), "chocolate_pudding_1": (-0.2, 1.2)} + +# wooden_tray collision geometry in its body frame (from the LIBERO MJCF; long axis = body x) +TRAY_IN_X = (-0.128, 0.143) +TRAY_IN_Y = (-0.081, 0.072) +TRAY_OUT_X = (-0.142, 0.156) +TRAY_OUT_Y = (-0.088, 0.080) +TRAY_CX, TRAY_CY = 0.0075, -0.0045 # centre of the inner floor +TRAY_FLOOR = 0.0072 # floor top above the tray's lowest point +BASKET_IN = 0.060 # half size of the basket's inner floor (square, centred on the body origin) +BASKET_RIM = 0.150 # rim height above the basket's lowest point +BASKET_FLOOR = 0.017 # floor top above the basket's lowest point + +NAMES = {"ketchup_1": "ketchup", "cream_cheese_1": "cream cheese", "butter_1": "butter", + "chocolate_pudding_1": "chocolate pudding"} +DESCR = {"ketchup_1": "red bottle", "cream_cheese_1": "blue box", "butter_1": "small orange box", + "chocolate_pudding_1": "brown box"} +SIDES = ("left", "right") # side of the tray in the agentview image: left = world -y, right = world +y + + +def _qz(a): + return np.array([np.cos(a / 2), 0.0, 0.0, np.sin(a / 2)]) + + +def _wrap_half(a): + """wrap an angle to [-pi/2, pi/2) (boxes and parallel grippers are symmetric under 180 deg)""" + return (a + np.pi / 2) % np.pi - np.pi / 2 + + +class KnockSkills(Skills): + """Skills with a hook called after every control step (used for the failure injection).""" + + def __init__(self, env, bias=None, recorder=None, hook=None): + super().__init__(env, bias=bias, recorder=recorder) + self.hook = hook + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + if self.hook is not None: + self.hook() + + +@register_task +class KnockRestore(LFFTask): + name = "l2_knock_restore" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Plan") + protocol = "within" + instruction = "Move the ketchup from the tray into the basket. Everything else must stay on the tray." + instruction_indirect = ("Move the red bottle from the wooden tray into the wicker basket. " + "Everything else must stay on the tray.") + knock_lift = 0.03 # trigger: ketchup grasped and lifted this far above its resting height + knock_radius = 0.12 # only a victim still within this distance of the ketchup's start spot is knocked + + def __init__(self, cam_res=None): + super().__init__(cam_res) + # upright orientations (wxyz), fixed here so the task does not depend on LIBERO's placement convention: + # the ketchup mesh is modelled lying down; tray / basket / boxes are upright in their mesh frame + # (identity => tray long axis along world x, as the TRAY_* constants assume). + self.q_up = {n: np.array([1.0, 0.0, 0.0, 0.0]) for n in self.env.objects_dict} + self.q_up[TARGET] = np.array([0.5, 0.5, 0.5, 0.5]) + self._inj = None + self.start = {} + + # ------------------------------------------------------------ scene + def make_bddl(self): + names = [TARGET, *NEIGHBOR_POOL, TRAY, BASKET] + objs = [] + for i, n in enumerate(names): # layout is overridden in apply_instance; regions only need to be valid + x0 = -0.30 + 0.13 * (i % 3) + y0 = -0.25 + 0.25 * (i // 3) + objs.append((n, n[:-2], f"r_{i}", (x0, y0, x0 + 0.02, y0 + 0.02))) + return write_bddl(self.name, self.instruction, objs) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + nb = [str(x) for x in rng.choice(NEIGHBOR_POOL, size=2, replace=False)] # [robot side, far side] + victim = int(rng.integers(2)) + side = str(rng.choice(SIDES)) + return dict(seed=int(seed), + tray_xy=[float(rng.uniform(-0.07, 0.01)), float(rng.uniform(-0.11, -0.08))], + tray_yaw=float(rng.uniform(-0.10, 0.10)), + basket_xy=[float(rng.uniform(-0.08, 0.02)), float(rng.uniform(0.24, 0.26))], + target_dx=float(rng.uniform(-0.01, 0.01)), + target_yaw=float(np.pi / 2 + rng.uniform(-0.2, 0.2)), + neighbors=nb, + nb_gap=[float(rng.uniform(0.066, 0.078)) for _ in range(2)], + nb_dy=[float(rng.uniform(-0.012, 0.012)) for _ in range(2)], + nb_yaw=[float(np.pi / 2 + rng.uniform(-0.15, 0.15)) for _ in range(2)], + # hidden variables of the injected failure + victim=nb[victim], side=side, + land_gap=float(rng.uniform(0.015, 0.035 if side == "right" else 0.04)), # wall -> object + land_off=float(rng.uniform(-0.025, 0.025)), # along the wall, from the victim's spot + land_dyaw=float(rng.uniform(-0.35, 0.35))) + + def _tray_frame(self): + p = envs.obj_pos(self.env, TRAY) + R = self.env.sim.data.body_xmat[envs.body_id(self.env, TRAY)].reshape(3, 3) + return p, R + + def tray_yaw(self): + _, R = self._tray_frame() + return float(np.arctan2(R[1, 0], R[0, 0])) + + def tray_to_world(self, lx, ly): + p, R = self._tray_frame() + return p[:2] + R[:2, :2] @ np.array([lx, ly]) + + def world_to_tray(self, xy): + p, R = self._tray_frame() + return R[:2, :2].T @ (np.asarray(xy[:2]) - p[:2]) + + def place(self, name, xy, yaw, surface_z=envs.TABLE_Z): + """Teleport an object upright (yaw about world z) with its lowest point 2 mm above surface_z.""" + q = envs._quat_mul(_qz(yaw), self.q_up[name]) + envs.set_obj_pose(self.env, name, [xy[0], xy[1], surface_z + 0.3], quat_wxyz=q) + self.env.sim.forward() + dz = envs.obj_min_z(self.env, name) - (surface_z + 0.002) + qa, _ = envs.free_joint_addr(self.env, name) + self.env.sim.data.qpos[qa + 2] -= dz + self.env.sim.forward() + + def apply_instance(self, inst): + env = self.env + envs.scale_mass(env, TRAY, 2.0) # heavy enough not to be dragged around by the gripper + envs.scale_mass(env, BASKET, 2.0) + for n in NEIGHBOR_POOL: + if n not in inst["neighbors"]: + self.place(n, PARK_XY[n], 0.0, surface_z=0.0) # unused neighbour: on the floor, out of view + self.place(TRAY, inst["tray_xy"], inst["tray_yaw"]) + self.place(BASKET, inst["basket_xy"], 0.0) + floor = envs.TABLE_Z + TRAY_FLOOR + ty = inst["tray_yaw"] + cx = TRAY_CX + inst["target_dx"] + self.place(TARGET, self.tray_to_world(cx, TRAY_CY), ty + inst["target_yaw"], floor) + for i, n in enumerate(inst["neighbors"]): # in a row along the tray: [robot side, ketchup, far side] + lx = cx + (-1 if i == 0 else 1) * inst["nb_gap"][i] + self.place(n, self.tray_to_world(lx, TRAY_CY + inst["nb_dy"][i]), ty + inst["nb_yaw"][i], floor) + env.sim.forward() + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.start = {n: self.footprint(n) for n in [TARGET] + inst["neighbors"]} + self._inj = dict(inst=inst, done=False, knocked=False, step=None) + self.sk = KnockSkills(self.env, bias=self.skill_bias(inst), recorder=recorder, hook=self._knock_hook) + return self.sk + + # ------------------------------------------------------------ measurements + def footprint(self, name): + """Measured pose summary of an object: AABB centre, yaw of the long horizontal axis, half sizes, z range. + Scripted policies use it as a stand-in for perception.""" + m, d = self.env.sim.model, self.env.sim.data + lo, hi = np.full(3, np.inf), np.full(3, -np.inf) + best = None + for g in envs.obj_geom_ids(self.env, name): + R = d.geom_xmat[g].reshape(3, 3) + c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3] + e = np.abs(R) @ m.geom_aabb[g, 3:] + lo, hi = np.minimum(lo, c - e), np.maximum(hi, c + e) + vol = float(np.prod(m.geom_aabb[g, 3:])) + if best is None or vol > best[0]: + best = (vol, R, m.geom_aabb[g, 3:]) + _, R, half = best + horiz = sorted([(half[k], R[:, k]) for k in range(3) if abs(R[2, k]) < 0.5], key=lambda t: -t[0]) + ax = horiz[0][1] if horiz else np.array([1.0, 0.0, 0.0]) + return dict(center=[float(v) for v in (lo + hi) / 2], yaw=float(np.arctan2(ax[1], ax[0])), + half_xy=[float(v) for v in ((hi - lo) / 2)[:2]], zmin=float(lo[2]), zmax=float(hi[2])) + + def _corners_tray(self, name): + """All collision-box corners of `name` in tray coordinates.""" + m, d = self.env.sim.model, self.env.sim.data + pts = [] + for g in envs.obj_geom_ids(self.env, name): + Rg = d.geom_xmat[g].reshape(3, 3) + c = d.geom_xpos[g] + Rg @ m.geom_aabb[g, :3] + h = m.geom_aabb[g, 3:] + for sx in (-1, 1): + for sy in (-1, 1): + for sz in (-1, 1): + pts.append(self.world_to_tray(c + Rg @ (h * np.array([sx, sy, sz])))) + return np.array(pts) + + # ------------------------------------------------------------ failure injection + def _knock_hook(self): + st = self._inj + if st is None or st["done"] or self.sk is None: + return + if envs.obj_min_z(self.env, TARGET) < self.start[TARGET]["zmin"] + self.knock_lift: + return + if not self.sk.holding(TARGET): + return + st["done"] = True + inst = st["inst"] + vxy = np.array(self.footprint(inst["victim"])["center"][:2]) + if np.linalg.norm(vxy - np.array(self.start[TARGET]["center"][:2])) > self.knock_radius: + return # the victim was moved out of the way beforehand: nothing happens + self.knock(inst) + st["knocked"] = True + st["step"] = self.sk.n_steps + + def knock(self, inst): + """Teleport the victim off the tray onto the table beside the long wall on `side`: upright, long axis + roughly perpendicular to the wall (so a gripper closing along the wall can pick it up), nearest point + `land_gap` from the wall's outer face, `land_off` along the wall from where it stood. + (The robot-side end of the tray was tried too: the end wall hides a flat box there from agentview.)""" + v, side = inst["victim"], inst["side"] + loc = self.world_to_tray(self.footprint(v)["center"]) + axis, sgn = 1, (1 if side == "right" else -1) + wall = TRAY_OUT_Y[1] if sgn > 0 else TRAY_OUT_Y[0] + self.place(v, self.tray_to_world(loc[0] + inst["land_off"], wall + sgn * 0.08), + self.tray_yaw() + np.pi / 2 + inst["land_dyaw"]) + pts = self._corners_tray(v) + near = pts[:, axis].min() if sgn > 0 else pts[:, axis].max() + shift = (wall + sgn * inst["land_gap"]) - near + _, R = self._tray_frame() + qa, _ = envs.free_joint_addr(self.env, v) + self.env.sim.data.qpos[qa:qa + 2] += R[:2, axis] * shift + self.env.sim.forward() + + # ------------------------------------------------------------ outcome + def where(self, name): + """Classify where an object is: 'tray', 'basket', 'gripper', 'table' or 'other'.""" + f = self.footprint(name) + c = np.array(f["center"]) + lt = self.world_to_tray(c) + if self.sk is not None and self.sk.holding(name) and f["zmin"] > envs.TABLE_Z + 0.02: + return "gripper", f + if (TRAY_IN_X[0] - 0.005 <= lt[0] <= TRAY_IN_X[1] + 0.005 and TRAY_IN_Y[0] - 0.005 <= lt[1] <= TRAY_IN_Y[1] + 0.005 + and f["zmin"] > envs.obj_min_z(self.env, TRAY) + 0.002): + return "tray", f + bp = envs.obj_pos(self.env, BASKET) + if np.all(np.abs(c[:2] - bp[:2]) <= BASKET_IN + 0.01) and f["zmin"] < envs.obj_min_z(self.env, BASKET) + BASKET_RIM: + return "basket", f + if f["zmin"] < envs.TABLE_Z + 0.01: + return "table", f + return "other", f + + def rel_to_tray(self, c): + """Where a point on the table is relative to the tray, in robot-centric words (never image left/right). + Distances are from the tray's outer edge to the object's centre.""" + lt = self.world_to_tray(c) + dy = lt[1] - TRAY_OUT_Y[1] if lt[1] > TRAY_OUT_Y[1] else (lt[1] - TRAY_OUT_Y[0] if lt[1] < TRAY_OUT_Y[0] else 0.0) + dx = lt[0] - TRAY_OUT_X[1] if lt[0] > TRAY_OUT_X[1] else (lt[0] - TRAY_OUT_X[0] if lt[0] < TRAY_OUT_X[0] else 0.0) + # robot-centric words (tray yaw is within +-0.1 rad, so tray axes ~ world axes): +y = robot's left, + # +x = forward (away from the robot) + parts = [] + if dy: + parts.append(f"{100 * abs(dy):.0f} cm to the robot's {'left (+y)' if dy > 0 else 'right (-y)'} of the tray") + if dx: + parts.append(f"{100 * abs(dx):.0f} cm {'forward (+x, away from the robot)' if dx > 0 else 'backward (-x, toward the robot)'} " + f"of the tray") + return " and ".join(parts) if parts else "right next to the tray" + + def _describe(self, inst, loc, names): + t_loc = loc[TARGET][0] + tn = names[TARGET] + msgs = [] + if t_loc != "basket": + msgs.append({"gripper": f"The {tn} is still in the gripper, not in the basket.", + "tray": f"The {tn} is still on the tray, not in the basket.", + "table": f"The {tn} is on the table ({self.rel_to_tray(loc[TARGET][1]['center'])}), " + "not in the basket."}.get(t_loc, f"The {tn} is not in the basket.")) + for n in inst["neighbors"]: + l, f = loc[n] + if l == "tray": + continue + msgs.append({"table": f"The {names[n]} is no longer on the tray: it is on the table " + f"{self.rel_to_tray(f['center'])}.", + "basket": f"The {names[n]} is no longer on the tray: it is in the basket.", + "gripper": f"The {names[n]} is no longer on the tray: it is still in the gripper."} + .get(l, f"The {names[n]} is no longer on the tray.")) + if not msgs: + msgs.append(f"The {tn} is in the basket and everything else is on the tray.") + return " ".join(msgs) + + def outcome(self, inst): + envs.settle(self.env, 30) + loc = {n: self.where(n) for n in [TARGET] + inst["neighbors"]} + off = [n for n in inst["neighbors"] if loc[n][0] != "tray"] + success = bool(loc[TARGET][0] == "basket" and not off) + return dict(success=success, + target_loc=loc[TARGET][0], + locations={n: l for n, (l, _) in loc.items()}, + off_tray=off, + footprints={n: f for n, (_, f) in loc.items()}, + knocked=bool(self._inj and self._inj["knocked"]), + detail=self._describe(inst, loc, NAMES), + detail_indirect=self._describe(inst, loc, DESCR)) + + def feedback(self, inst, out, level="F2", indirect=False): + """F0: nothing, F1: success flag, F2: which item is where. `indirect` uses descriptive names.""" + if indirect and level == "F2": + out = dict(out, detail=out.get("detail_indirect", out["detail"])) + return super().feedback(inst, out, level) + + # ------------------------------------------------------------ scripted motions + def pick_place(self, name, dest_xy, support_z, dest_yaw=None, carry_z=1.10, clearance=0.012, fp=None, + travel_z=1.15): + """Top-down pick of `name` at its (measured) footprint, carry at eef height `carry_z`, release with the + object bottom `clearance` above `support_z` at dest_xy. Moves between places at `travel_z` (above the + basket rim) so the arm does not sweep through the scene.""" + sk = self.sk + f = fp or self.footprint(name) + c = np.array(f["center"]) + h = f["zmax"] - f["zmin"] + gyaw = _wrap_half(f["yaw"]) # fingers close along eef y (= world y at yaw 0): across the short side + if name == TARGET: + zg = f["zmax"] - 0.035 + else: + zg = max(f["zmin"] + 0.5 * h, f["zmin"] + 0.0145) # fingertips reach ~1.3 cm below the grip site + sk.set_gripper(False, steps=6) + p = sk.eef_pos() + if p[2] < travel_z - 0.02: + sk.move_to([p[0], p[1], travel_z]) + sk.move_to([c[0], c[1], travel_z], yaw=gyaw) + sk.move_to([c[0], c[1], f["zmax"] + 0.03], speed=0.4) + sk.move_to([c[0], c[1], zg], tol=0.003, max_steps=80) + sk.set_gripper(True, steps=12) + sk.move_to([c[0], c[1], carry_z], speed=0.3) + gyaw2 = gyaw if dest_yaw is None else gyaw + _wrap_half(dest_yaw - f["yaw"]) + sk.move_to([dest_xy[0], dest_xy[1], carry_z], yaw=gyaw2) + sk.move_to([dest_xy[0], dest_xy[1], support_z + (zg - f["zmin"]) + clearance], tol=0.004, speed=0.25, + max_steps=120) + sk.set_gripper(False, steps=10) + sk.move_to([dest_xy[0], dest_xy[1], travel_z], speed=0.4) + + def main_task(self, fp=None): + """Ketchup -> basket (the instruction, as an agent without failure knowledge would do it).""" + b = envs.obj_pos(self.env, BASKET) + floor = envs.obj_min_z(self.env, BASKET) + BASKET_FLOOR + self.pick_place(TARGET, b[:2], floor, carry_z=1.27, clearance=0.006, fp=fp) + + def restore_spot(self, name, inst): + """A free spot on the tray for `name`: the ketchup's start spot or `name`'s own start spot, whichever + is further from everything else currently on the tray.""" + others = [n for n in [TARGET] + inst["neighbors"] if n != name and self.where(n)[0] == "tray"] + best, best_d = None, -1.0 + for cand in (TARGET, name): + xy = np.array(self.start[cand]["center"][:2]) + dmin = min([np.linalg.norm(xy - np.array(self.footprint(o)["center"][:2])) for o in others] + [1.0]) + if dmin > best_d + 0.01: + best, best_d = xy, dmin + return best + + def restore(self, name, inst): + """Put `name` back onto the tray (long axis across the tray, fingers closing along the tray).""" + xy = self.restore_spot(name, inst) + self.pick_place(name, xy, envs.TABLE_Z + TRAY_FLOOR, dest_yaw=self.tray_yaw() + np.pi / 2, carry_z=1.08, + clearance=0.013) + + def do(self, actions, inst): + for act in actions: + if act[0] == "ketchup_to_basket": + self.main_task(fp=act[1] if len(act) > 1 else None) + elif act[0] == "restore": + self.restore(act[1], inst) + else: + raise ValueError(act) + + # ------------------------------------------------------------ scripted reference policies + def _plan(self, kind, inst, a, history, rng): + """Actions of one attempt. JSON-friendly lists: ["ketchup_to_basket"] / ["restore", name].""" + if kind == "naive" or (a == 0 and kind in ("adaptive", "blind")): + return [["ketchup_to_basket"]] + if kind == "oracle": # knows the victim: restores it right after the main task, without feedback + return [["ketchup_to_basket"], ["restore", inst["victim"]]] + if kind == "adaptive": # F2 says what is wrong; perception (measured pose) says where it is + last = history[-1]["outcome"] + acts = [] if last["target_loc"] == "basket" else [["ketchup_to_basket"]] + return acts + [["restore", n] for n in last["off_tray"]] + if kind == "blind": # ignores the outcome: redoes the main task (ketchup wherever it is now, jittered grasp) + fp = self.footprint(TARGET) + fp["center"] = (np.array(fp["center"]) + np.r_[rng.normal(0, 0.005, 2), 0.0]).tolist() + return [["ketchup_to_basket", fp]] + raise ValueError(kind) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """Within-episode protocol: one reset, attempt 1 = main task, attempts 2..k = corrective rounds. + After every attempt the outcome (success + F2 detail) is measured; stops at success + (oracle / naive stop after attempt 1).""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + self.reset_instance(inst) + for a in range(k): + actions = self._plan(kind, inst, a, history, rng) + self.do(actions, inst) + out = self.outcome(inst) + params = dict(actions=[x[:2] if x[0] == "restore" else x[:1] for x in actions]) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history + + +@register_task +class KnockRestoreCross(KnockRestore): + """Cross-attempt variant: reset to the same instance before every attempt; the knock happens again each + time. Learned behaviour: anticipate it (restore the reported item right after the main task).""" + name = "l2_knock_restore_cross" + protocol = "cross" + + def _plan(self, kind, inst, a, history, rng): + if kind == "adaptive" and a > 0: # remembers which item(s) fell last time; finds them by looking + fallen = sorted({n for h in history for n in h["outcome"]["off_tray"]}) + return [["ketchup_to_basket"]] + [["restore", n] for n in fallen] + return super()._plan(kind, inst, a, history, rng) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + actions = self._plan(kind, inst, a, history, rng) + self.do(actions, inst) + out = self.outcome(inst) + params = dict(actions=[x[:2] if x[0] == "restore" else x[:1] for x in actions]) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l2_restore_layout.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l2_restore_layout.py new file mode 100644 index 0000000000000000000000000000000000000000..d926c362024dece29de84cdc1074180f7b196ceb --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l2_restore_layout.py @@ -0,0 +1,502 @@ +"""L2-B restore_layout: put the ketchup into the basket; every other item must stay exactly where it was. + +Scene: the ketchup (upright) and three flat boxes (cream cheese, butter, chocolate pudding) stand on the bare +table in an irregular layout (random positions and yaws, no tray, no markers, no grid), the basket on the +robot's left. Nothing in the scene marks where an item "belongs": its original pose exists only in the +first frame. + +Constructed L2 event (physical, continuous): the first time the ketchup is grasped and lifted 3 cm, the +neighbouring box (the "victim", a hidden variable) is knocked: it receives a velocity impulse away from the +ketchup (+-35 deg) and a spin, slides 9-14 cm over the table and comes to rest turned by 45-80 deg. It is +real MuJoCo motion over ~0.2 s (no teleport), so a video shows it sliding away. The main task itself still +succeeds; an agent that stops after it fails. To repair the side effect the agent has to put the victim +back where it was -- within 3 cm and 25 deg (mod 180, the boxes are symmetric) -- and that pose is only in +its memory of the start of the episode (the F2 text says *which* item is out of place, never where it was). + +Protocol: within (one episode, no reset). Attempt 1 = the main task, every later attempt = one corrective +round chosen by the policy; the outcome (success + F2 text) is computed after each round. + +Scripted references + oracle knows the victim: right after the main task it puts the victim back at its saved start pose. + naive main task, then done. + adaptive saves the start layout from the first frame (Save); after a failure reads from F2 which items are + out of place (Retrieve their saved poses) and puts them back (Utilize). + blind no history, no feedback: every later round redoes the main task (lifts the ketchup out of the + basket and puts it back, grasp jittered by 5 mm), like l2_knock_restore's blind. + nomem (extra control, not in the acceptance table) gets the F2 text but has no start frame: it knows + which box is out of place and guesses where to put it (random free spot within 15 cm, random yaw). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..task_base import LFFTask, register_task + +TARGET = "ketchup_1" +BOXES = ("cream_cheese_1", "butter_1", "chocolate_pudding_1") +BASKET = "basket_1" +ITEMS = (TARGET,) + BOXES + +# LIBERO basket (body frame = world frame at yaw 0), measured by the l2_knock_restore developer +BASKET_IN = 0.060 # half size of the inner floor +BASKET_RIM = 0.150 # rim height above the basket's lowest point +BASKET_FLOOR = 0.017 # floor top above the basket's lowest point +BASKET_OUT = 0.11 # conservative half size of the outer footprint (keep-out radius for the layout) + +POS_TOL = 0.03 # success: box centre within 3 cm of its start +YAW_TOL = np.radians(25.0) # ... and long axis within 25 deg of its start (mod 180) +STILL_TOL = 0.02 # the knock only fires if the victim is still within 2 cm of its start + +REGION = (-0.26, 0.06, -0.27, 0.10) # x0, x1, y0, y1 (world) for item centres +KNOCK_REGION = (-0.28, 0.08, -0.29, 0.12) # where the victim may come to rest +MAX_REACH = 0.70 # max horizontal distance of an item centre from the robot base +BASE_X = -0.66 +R_BOX, R_KETCHUP = 0.046, 0.034 # footprint circumradii (boxes 8 x 4.3 cm; ketchup 5.7 x 3.7 cm) +GAP = 0.03 # free space between footprints (finger room) +SLIDE_K = 0.0522 # measured: slide distance [m] = SLIDE_K * v0^2 [m/s] for these boxes on the table +SPIN_W = 40.0 # rad/s, applied each control step until the target turn is reached + +NAMES = {"ketchup_1": "ketchup", "cream_cheese_1": "cream cheese", "butter_1": "butter", + "chocolate_pudding_1": "chocolate pudding", BASKET: "basket"} +DESCR = {"ketchup_1": "red bottle", "cream_cheese_1": "blue box", "butter_1": "small orange box", + "chocolate_pudding_1": "brown box", BASKET: "wicker basket"} + + +def _qz(a): + return np.array([np.cos(a / 2), 0.0, 0.0, np.sin(a / 2)]) + + +def _wrap_half(a): + """wrap an angle to [-pi/2, pi/2) (boxes and parallel grippers are symmetric under 180 deg)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def _seg_dist(p, a, b): + """distance from point p to segment a-b (2D)""" + p, a, b = (np.asarray(v, float) for v in (p, a, b)) + ab = b - a + t = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0.0, 1.0) + return float(np.linalg.norm(p - (a + t * ab))) + + +def _in_rect(xy, r): + return r[0] <= xy[0] <= r[1] and r[2] <= xy[1] <= r[3] + + +def _reach_ok(xy): + return np.hypot(xy[0] - BASE_X, xy[1]) <= MAX_REACH + + +@register_task +class RestoreLayout(LFFTask): + name = "l2_restore_layout" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Save", "Retrieve", "Utilize") + protocol = "within" + max_attempts = 5 + instruction = ("Put the ketchup into the basket. Every other item on the table must stay exactly where it " + "is now, in the same position and orientation.") + instruction_indirect = ("Put the red bottle into the wicker basket. Every other item on the table must stay " + "exactly where it is now, in the same position and orientation.") + knock_lift = 0.03 # trigger: ketchup grasped and lifted this far above its resting height + + def __init__(self, cam_res=None): + super().__init__(cam_res) + # upright orientations (wxyz), fixed like in l2_knock_restore: the ketchup mesh is modelled lying down; + # basket and boxes are upright in their mesh frame + self.q_up = {n: np.array([1.0, 0.0, 0.0, 0.0]) for n in self.env.objects_dict} + self.q_up[TARGET] = np.array([0.5, 0.5, 0.5, 0.5]) + self._inj = None + self.start = {} + self._home = None + # per-control-step monitor on env.step: also sees attempts driven by the agent harness + orig_step = self.env.step + + def step(action): + ret = orig_step(action) + if self._inj is not None: + self._knock_step() + return ret + + self.env.step = step + + # ------------------------------------------------------------ scene + def make_bddl(self): + names = [*ITEMS, BASKET] + objs = [] + for i, n in enumerate(names): # layout is overridden in apply_instance; regions only need to be valid + x0 = -0.30 + 0.13 * (i % 3) + y0 = -0.25 + 0.25 * (i // 3) + objs.append((n, n[:-2], f"r_{i}", (x0, y0, x0 + 0.02, y0 + 0.02))) + return write_bddl(self.name, self.instruction, objs) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + for _ in range(5000): + basket = np.array([rng.uniform(-0.08, 0.0), rng.uniform(0.25, 0.27)]) + k = np.array([rng.uniform(-0.17, -0.03), rng.uniform(-0.14, -0.02)]) + victim = str(rng.choice(BOXES)) + others = [b for b in BOXES if b != victim] + a_v = rng.uniform(0, 2 * np.pi) + r_v = rng.uniform(R_BOX + R_KETCHUP + GAP, R_BOX + R_KETCHUP + GAP + 0.02) + pos = {TARGET: k, victim: k + r_v * np.array([np.cos(a_v), np.sin(a_v)])} + ok = _in_rect(pos[victim], REGION) and _reach_ok(pos[victim]) + for o in others: + if not ok: + break + for _ in range(200): + p = np.array([rng.uniform(*REGION[:2]), rng.uniform(*REGION[2:])]) + if not _reach_ok(p): + continue + if np.linalg.norm(p - k) < R_BOX + R_KETCHUP + GAP: + continue + if any(np.linalg.norm(p - pos[q]) < 2 * R_BOX + GAP for q in pos if q != TARGET): + continue + pos[o] = p + break + else: + ok = False + if not ok: + continue + if any(np.linalg.norm(pos[n] - basket) < BASKET_OUT + R_BOX + 0.02 for n in ITEMS): + continue + # the knock: away from the ketchup +-35 deg, 9-14 cm, turn 45-80 deg (random sign) + ang = a_v + rng.uniform(-np.radians(35), np.radians(35)) + dist = rng.uniform(0.09, 0.14) + u = np.array([np.cos(ang), np.sin(ang)]) + end = pos[victim] + dist * u + if not (_in_rect(end, KNOCK_REGION) and _reach_ok(end)): + continue + if np.linalg.norm(end - basket) < BASKET_OUT + R_BOX + 0.03: + continue + # the path and the resting spot keep clear of the other boxes (finger room around the victim too) + if any(_seg_dist(pos[o], pos[victim], end) < 2 * R_BOX + 0.01 for o in others): + continue + if any(np.linalg.norm(end - pos[o]) < 2 * R_BOX + GAP for o in others): + continue + if np.linalg.norm(end - k) < R_BOX + R_KETCHUP + GAP: + continue + turn = float(rng.choice([-1, 1]) * rng.uniform(np.radians(45), np.radians(80))) + return dict(seed=int(seed), + basket_xy=basket.round(4).tolist(), + xy={n: pos[n].round(4).tolist() for n in ITEMS}, + yaw={**{b: float(rng.uniform(-np.pi / 2, np.pi / 2)) for b in BOXES}, + TARGET: float(np.pi / 2 + rng.uniform(-0.3, 0.3))}, + # hidden variables of the injected failure + victim=victim, knock_dir=float(ang), knock_dist=float(dist), knock_turn=turn, + knock_end=end.round(4).tolist()) + raise RuntimeError("could not sample a layout") + + def place(self, name, xy, yaw, surface_z=envs.TABLE_Z): + """Teleport an object upright (yaw about world z) with its lowest point 2 mm above surface_z (reset only).""" + q = envs._quat_mul(_qz(yaw), self.q_up[name]) + envs.set_obj_pose(self.env, name, [xy[0], xy[1], surface_z + 0.3], quat_wxyz=q) + self.env.sim.forward() + dz = envs.obj_min_z(self.env, name) - (surface_z + 0.002) + qa, _ = envs.free_joint_addr(self.env, name) + self.env.sim.data.qpos[qa + 2] -= dz + self.env.sim.forward() + + def apply_instance(self, inst): + envs.scale_mass(self.env, BASKET, 2.0) # heavy enough not to be dragged by the gripper (as in l2_knock) + self.place(BASKET, inst["basket_xy"], 0.0) + for n in ITEMS: + self.place(n, inst["xy"][n], inst["yaw"][n]) + self.env.sim.forward() + + def reset_instance(self, inst, recorder=None): + self._inj = None + sk = super().reset_instance(inst, recorder) + self.start = {n: self.footprint(n) for n in ITEMS} + self._inj = dict(inst=inst, done=False, knocked=False, step=None, spin_left=0.0, spin_steps=0) + self._home = sk.eef_pos() + return sk + + # ------------------------------------------------------------ measurements + def footprint(self, name): + """Measured pose summary: AABB centre, yaw of the long horizontal axis, half sizes, z range. + Scripted policies use it as a stand-in for perception.""" + m, d = self.env.sim.model, self.env.sim.data + lo, hi = np.full(3, np.inf), np.full(3, -np.inf) + best = None + for g in envs.obj_geom_ids(self.env, name): + R = d.geom_xmat[g].reshape(3, 3) + c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3] + e = np.abs(R) @ m.geom_aabb[g, 3:] + lo, hi = np.minimum(lo, c - e), np.maximum(hi, c + e) + vol = float(np.prod(m.geom_aabb[g, 3:])) + if best is None or vol > best[0]: + best = (vol, R, m.geom_aabb[g, 3:]) + _, R, half = best + horiz = sorted([(half[k], R[:, k]) for k in range(3) if abs(R[2, k]) < 0.5], key=lambda t: -t[0]) + ax = horiz[0][1] if horiz else np.array([1.0, 0.0, 0.0]) + return dict(center=[float(v) for v in (lo + hi) / 2], yaw=float(np.arctan2(ax[1], ax[0])), + half_xy=[float(v) for v in ((hi - lo) / 2)[:2]], zmin=float(lo[2]), zmax=float(hi[2])) + + def body_yaw(self, name): + R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3) + return float(np.arctan2(R[1, 0], R[0, 0])) + + # ------------------------------------------------------------ failure injection (physical knock) + def _knock_step(self): + st = self._inj + if st["done"]: + if st["spin_steps"] > 0: # keep spinning until the target turn is reached (<= 6 control steps) + self._spin(st) + return + if self.sk is None: + return + if envs.obj_min_z(self.env, TARGET) < self.start[TARGET]["zmin"] + self.knock_lift: + return + if not self.sk.holding(TARGET): + return + st["done"] = True + inst = st["inst"] + v = inst["victim"] + if np.linalg.norm(np.array(self.footprint(v)["center"][:2]) - np.array(self.start[v]["center"][:2])) > STILL_TOL: + return # the victim was moved beforehand: nothing happens + qa, da = envs.free_joint_addr(self.env, v) + v0 = np.sqrt(inst["knock_dist"] / SLIDE_K) + dvec = np.array([np.cos(inst["knock_dir"]), np.sin(inst["knock_dir"])]) + d = self.env.sim.data + d.qvel[da:da + 3] = [v0 * dvec[0], v0 * dvec[1], 0.0] + st.update(knocked=True, step=int(self.sk.n_steps), yaw0=self.body_yaw(v), spin_left=inst["knock_turn"], + spin_steps=6) + self._spin(st) + + def _spin(self, st): + v = st["inst"]["victim"] + _, da = envs.free_joint_addr(self.env, v) + turned = _wrap_half(self.body_yaw(v) - st["yaw0"]) if abs(st["spin_left"]) < np.pi / 2 else 0.0 + rest = st["spin_left"] - turned + st["spin_steps"] -= 1 + if abs(rest) < np.radians(4) or np.sign(rest) != np.sign(st["spin_left"]): + st["spin_steps"] = 0 + return + # measured: one control step at w rad/s turns these boxes by ~0.35-0.8 deg per rad/s; aim a bit short + w = float(np.clip(np.degrees(abs(rest)) / 0.6, 5.0, SPIN_W)) + self.env.sim.data.qvel[da + 5] = np.sign(rest) * w + + # ------------------------------------------------------------ outcome + def where_target(self): + """'basket', 'gripper', 'table' or 'other' for the ketchup.""" + f = self.footprint(TARGET) + c = np.array(f["center"]) + if self.sk is not None and self.sk.holding(TARGET) and f["zmin"] > envs.TABLE_Z + 0.02: + return "gripper", f + bp = envs.obj_pos(self.env, BASKET) + if np.all(np.abs(c[:2] - bp[:2]) <= BASKET_IN + 0.01) and f["zmin"] < envs.obj_min_z(self.env, BASKET) + BASKET_RIM: + return "basket", f + if f["zmin"] < envs.TABLE_Z + 0.01: + return "table", f + return "other", f + + def box_state(self, name): + """Pose error of a box w.r.t. its start pose and where it is.""" + f = self.footprint(name) + s = self.start[name] + c, c0 = np.array(f["center"][:2]), np.array(s["center"][:2]) + dpos = float(np.linalg.norm(c - c0)) + dyaw = _wrap_half(f["yaw"] - s["yaw"]) + held = bool(self.sk is not None and self.sk.holding(name)) + upright = envs.obj_upright_cos(self.env, name) > 0.9 + on_table = f["zmin"] < envs.TABLE_Z + 0.01 + bp = envs.obj_pos(self.env, BASKET) + loc = ("gripper" if held else + "basket" if np.all(np.abs(c - bp[:2]) <= BASKET_IN + 0.02) and not on_table else + "table" if on_table and upright else + "table_tipped" if on_table else "other") + ok = bool(loc == "table" and dpos <= POS_TOL and abs(dyaw) <= YAW_TOL) + return dict(ok=ok, loc=loc, dpos=dpos, dyaw=float(dyaw), center=f["center"], yaw=f["yaw"], + offset=(c - c0).tolist()) + + @staticmethod + def _offset_words(off, dyaw): + """robot-centric words for a displacement (current - start) and turn (for the offset tier only)""" + parts = [] + if abs(off[0]) >= 0.005: + parts.append(f"{100 * abs(off[0]):.0f} cm {'forward' if off[0] > 0 else 'backward'}") + if abs(off[1]) >= 0.005: + parts.append(f"{100 * abs(off[1]):.0f} cm to the {'left' if off[1] > 0 else 'right'}") + s = (" and ".join(parts) + " of its starting spot") if parts else "at its starting spot" + if abs(dyaw) >= np.radians(3): + s += f", turned {abs(np.degrees(dyaw)):.0f} deg {'counter-clockwise' if dyaw > 0 else 'clockwise'} (seen from above)" + return s + + def _describe(self, tloc, boxes, names, offset=False): + tn = names[TARGET] + msgs = [] + if tloc != "basket": + msgs.append({"gripper": f"The {tn} is still in the gripper, not in the basket.", + "table": f"The {tn} is on the table, not in the basket."} + .get(tloc, f"The {tn} is not in the basket.")) + for n in BOXES: + b = boxes[n] + if b["ok"]: + continue + if b["loc"] == "gripper": + msgs.append(f"The {names[n]} is in the gripper; it must be back where it was at the start.") + continue + if b["loc"] == "basket": + msgs.append(f"The {names[n]} is in the basket; it must be back where it was at the start.") + continue + if b["loc"] == "table_tipped": + msgs.append(f"The {names[n]} has tipped over and is not where it was at the start.") + continue + if b["loc"] != "table": + msgs.append(f"The {names[n]} is not where it was at the start.") + continue + what = [] + if b["dpos"] > POS_TOL: + what.append("position") + if abs(b["dyaw"]) > YAW_TOL: + what.append("orientation") + m = f"The {names[n]} is not where it was at the start ({' and '.join(what)} changed)." + if offset: + m += f" It is {self._offset_words(b['offset'], b['dyaw'])}." + msgs.append(m) + if not msgs: + msgs.append(f"The {tn} is in the basket and every other item is where it was at the start.") + return " ".join(msgs) + + def outcome(self, inst): + envs.settle(self.env, 30) + tloc, tf = self.where_target() + boxes = {n: self.box_state(n) for n in BOXES} + moved = [n for n in BOXES if not boxes[n]["ok"]] + success = bool(tloc == "basket" and not moved) + return dict(success=success, target_loc=tloc, moved=moved, + boxes={n: dict(ok=b["ok"], loc=b["loc"], dpos=round(b["dpos"], 4), + dyaw_deg=round(float(np.degrees(b["dyaw"])), 1)) for n, b in boxes.items()}, + knocked=bool(self._inj and self._inj["knocked"]), + detail=self._describe(tloc, boxes, NAMES), + detail_indirect=self._describe(tloc, boxes, DESCR), + detail_offset=self._describe(tloc, boxes, NAMES, offset=True)) + + def feedback(self, inst, out, level="F2", indirect=False, offset=False): + """F0: nothing, F1: success flag, F2: which item is out of place (never where it was). + offset=True (ablation tier 'F2+offset'): also the displacement from the start pose in robot-centric + words -- this externalises the memory and is not the default.""" + if level == "F2": + key = "detail_offset" if offset else ("detail_indirect" if indirect else "detail") + out = dict(out, detail=out.get(key, out["detail"])) + return super().feedback(inst, out, level) + + # ------------------------------------------------------------ scripted motions (Skills.move_to / set_gripper only) + def go_home(self): + """End of an attempt: lift the arm out of the camera's way.""" + sk = self.sk + p = sk.eef_pos() + sk.move_to([p[0], p[1], max(p[2], self._home[2])]) + sk.move_to(self._home) + + def pick_place(self, name, dest_xy, support_z, dest_yaw=None, carry_z=1.10, clearance=0.006, fp=None, + travel_z=1.15): + """Top-down pick of `name` at its (measured) footprint, carry at eef height `carry_z`, release with the + object bottom `clearance` above `support_z` at dest_xy; `dest_yaw` = desired yaw of the long axis.""" + sk = self.sk + f = fp or self.footprint(name) + c = np.array(f["center"]) + h = f["zmax"] - f["zmin"] + gyaw = _wrap_half(f["yaw"]) # fingers close along eef y (= world y at yaw 0): across the short side + if name == TARGET: + zg = f["zmax"] - 0.035 + else: + zg = max(f["zmin"] + 0.5 * h, f["zmin"] + 0.0145) # finger tips reach ~1.3 cm below the grip site + sk.set_gripper(False, steps=6) + p = sk.eef_pos() + if p[2] < travel_z - 0.02: + sk.move_to([p[0], p[1], travel_z]) + sk.move_to([c[0], c[1], travel_z], yaw=gyaw) + sk.move_to([c[0], c[1], f["zmax"] + 0.03], speed=0.4) + sk.move_to([c[0], c[1], zg], tol=0.003, max_steps=80) + sk.set_gripper(True, steps=12) + sk.move_to([c[0], c[1], carry_z], speed=0.3) + gyaw2 = gyaw if dest_yaw is None else gyaw + _wrap_half(dest_yaw - f["yaw"]) + sk.move_to([dest_xy[0], dest_xy[1], carry_z], yaw=gyaw2) + sk.move_to([dest_xy[0], dest_xy[1], support_z + (zg - f["zmin"]) + clearance], tol=0.003, speed=0.2, + max_steps=150) + sk.hold(4) + sk.set_gripper(False, steps=10) + sk.move_to([dest_xy[0], dest_xy[1], travel_z], speed=0.4) + + def main_task(self, fp=None): + """Ketchup -> basket (the instruction, as an agent without failure knowledge would do it).""" + b = envs.obj_pos(self.env, BASKET) + floor = envs.obj_min_z(self.env, BASKET) + BASKET_FLOOR + self.pick_place(TARGET, b[:2], floor, carry_z=1.27, clearance=0.006, fp=fp) + + def restore(self, name, pose): + """Put box `name` back at `pose` (a remembered footprint: centre xy + long-axis yaw).""" + self.pick_place(name, pose["center"][:2], envs.TABLE_Z, dest_yaw=pose["yaw"], carry_z=1.05, + clearance=0.004) + + def do(self, actions, inst): + for act in actions: + if act[0] == "ketchup_to_basket": + self.main_task(fp=act[1] if len(act) > 1 else None) + elif act[0] == "restore": # ["restore", name, pose] + self.restore(act[1], act[2]) + else: + raise ValueError(act) + + # ------------------------------------------------------------ scripted reference policies + def _guess_pose(self, name, rng): + """nomem control: a random free spot within 15 cm of where the box is now, random yaw.""" + cur = np.array(self.footprint(name)["center"][:2]) + others = [np.array(self.footprint(o)["center"][:2]) for o in BOXES if o != name] + for _ in range(200): + r, a = rng.uniform(0.03, 0.15), rng.uniform(0, 2 * np.pi) + p = cur + r * np.array([np.cos(a), np.sin(a)]) + if _in_rect(p, KNOCK_REGION) and _reach_ok(p) and all(np.linalg.norm(p - o) > 2 * R_BOX + 0.01 for o in others): + return dict(center=[float(p[0]), float(p[1]), 0.0], yaw=float(rng.uniform(-np.pi / 2, np.pi / 2))) + return dict(center=[float(cur[0]), float(cur[1]), 0.0], yaw=float(rng.uniform(-np.pi / 2, np.pi / 2))) + + def _plan(self, kind, inst, a, history, rng, memory): + """Actions of one round: ["ketchup_to_basket"] / ["restore", name, pose].""" + if kind == "naive" or (a == 0 and kind in ("adaptive", "blind", "nomem")): + return [["ketchup_to_basket"]] + if kind == "oracle": # knows the victim: restores it right after the main task (start pose from memory) + return [["ketchup_to_basket"], ["restore", inst["victim"], memory[inst["victim"]]]] + last = history[-1]["outcome"] + if kind == "adaptive": # F2 says which items are out of place; the saved first frame says where they were + acts = [] if last["target_loc"] == "basket" else [["ketchup_to_basket"]] + return acts + [["restore", n, memory[n]] for n in last["moved"]] + if kind == "nomem": # F2 but no start frame: guesses + acts = [] if last["target_loc"] == "basket" else [["ketchup_to_basket"]] + return acts + [["restore", n, self._guess_pose(n, rng)] for n in last["moved"]] + if kind == "blind": # ignores the outcome: redoes the main task (ketchup wherever it is now, jittered grasp) + fp = self.footprint(TARGET) + fp["center"] = (np.array(fp["center"]) + np.r_[rng.normal(0, 0.005, 2), 0.0]).tolist() + return [["ketchup_to_basket", fp]] + raise ValueError(kind) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """Within-episode protocol: one reset, attempt 1 = main task, attempts 2..k = corrective rounds.""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + self.reset_instance(inst) + memory = {n: dict(center=self.start[n]["center"], yaw=self.start[n]["yaw"]) for n in BOXES} # Save + for a in range(k): + actions = self._plan(kind, inst, a, history, rng, memory) + self.do(actions, inst) + self.go_home() + out = self.outcome(inst) + params = dict(actions=[x[:1] if x[0] == "ketchup_to_basket" else + [x[0], x[1], [round(v, 3) for v in x[2]["center"][:2]], round(float(x[2]["yaw"]), 3)] + for x in actions]) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history + + # cross-protocol hooks are not used by this task + def default_params(self, inst): + return dict(policy="naive") + + def oracle_params(self, inst): + return dict(policy="oracle") diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l2_turntable.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l2_turntable.py new file mode 100644 index 0000000000000000000000000000000000000000..6cde2c1b38e0e5287e6df47831e640e545bf1f43 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l2_turntable.py @@ -0,0 +1,469 @@ +"""L2-C turntable_restore: take the butter off a turntable that stands half under a shelf, then turn the +turntable back exactly the way it was. + +Replaces the planned l2_drawer_reclosed (feasibility test 2026-10-07, see the task card): with the gripper +always pointing straight down, the handle of LIBERO's wooden_cabinet top drawer (3.8 cm below the cabinet +top) cannot be reached -- the descent stops 1.5-4.5 cm above it, closing grasps nothing (4/4 cabinet +placements) and a pull opened the drawer only 1/4 times, by accident. The turntable keeps the idea (an +articulated fixture the agent *has to* change to get the object and has to put back afterwards) and is +operable with move_to + open/close only. + +Scene: a turntable (lazy susan; disc radius 17 cm on a damped hinge about z) on the robot's right; a fixed +shelf board 10 cm above the disc covers its -y half (robot's right), so nothing under the board can be +grasped from above (measured, 20 seeds x 2 grasp yaws: the hand stops on the board 10-14 cm above the grasp +height, 0/40 lifts). Four red pegs stand near the rim; grasping a peg and moving the gripper along the rim +turns the disc. The butter lies on the disc under the board; painted marks (yellow stripe, blue square, +green dot; visual only) make the disc's angle readable. The basket stands on the robot's left. + +Why the first attempt fails (the L2 event is the agent's own, necessary change): to reach the butter the +agent must turn the disc by 136-179 deg (start angle random; measured on seeds 1000-1019). An agent that puts the butter into the basket +and stops leaves the turntable turned -> failure. To repair it the agent has to turn it back to its start +angle (+-15 deg); after the main turn the marks are elsewhere and nothing in the scene shows the start angle: +it is only in the first frame (or in the agent's memory of how far it turned). The F2 text says *that* the +turntable is not turned the way it was, never by how much or which way. + +Protocol: within (one episode, no reset). Attempt 1 = the main task, every later attempt = one corrective +round; the outcome (success + F2 text) is computed after each round. + +Scripted references (perception stand-in: simulator poses; motions: Skills.move_to / set_gripper only) + oracle turns, takes the butter, then immediately turns the disc back to the saved start angle. + naive turns, takes the butter, done. + adaptive saves the start angle (Save); after F2 "not turned the way it was" turns back to it (Retrieve + + Utilize); redoes the main task if the butter is not in the basket. + blind no history, no feedback: every later round redoes the main task (lifts the butter out of the + basket and drops it back, grasp jittered by 5 mm). + nomem (extra control, not in the acceptance table) gets F2 but has no start frame: turns the disc by a + random angle in (-180, 180] deg each round. + +Physics notes (all measured while building the task, 2026-10-07): the HOPE butter weighs 5 g -> set to 0.2 kg; +a box on a cylinder gets a single contact point and no torsional friction, so the butter span on the disc at +~4 deg/s even at rest -> the disc's collision surface is the inscribed square plate (visual disc stays round). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, register_generated +from ..task_base import LFFTask, register_task + +TT = "turntable_1" +TARGET = "butter_1" +ITEMS = (TARGET,) +BASKET = "basket_1" +MASS = {"butter_1": 0.20} # real-world order (the HOPE box weighs 5 g) + +# turntable geometry (fixture frame: origin on the table top at the disc axis) +R = 0.17 # disc radius +DISC_T = 0.012 # disc thickness +BASE_H = 0.012 # pedestal height +DISC_TOP = BASE_H + DISC_T # disc top above the table +PEG_R, PEG_RAD, PEG_H = 0.009, 0.155, 0.035 # radius, distance from the axis, height above the disc +# (low enough that the hand clears the pegs by 1 cm when it grasps the butter between them) +PEG_ANG = tuple(np.pi / 4 + k * np.pi / 2 for k in range(4)) # disc frame +STRIPE_ANG = np.pi # disc frame +BOARD_Z = DISC_TOP + 0.10 # underside of the shelf board above the table +BOARD_EDGE = 0.01 # the board covers fixture y < +1 cm (the -y half of the disc) +HINGE = dict(damping=1.0, armature=0.3, frictionloss=0.01) # the disc stops within ~1 deg when released +ITEM_R = 0.07 # butter's distance from the axis (disc frame); open fingers at a held peg clear it by >= 1.2 cm + +ANG_TOL = np.radians(15.0) # success: disc within 15 deg of its start angle (4 cm at the pegs, 2.6 cm at the stripe end) +BASKET_IN = 0.060 # LIBERO basket: half size of the inner floor +BASKET_RIM = 0.150 +BASKET_FLOOR = 0.017 +SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"' + +NAMES = {TARGET: "butter"} +DESCR = {TARGET: "small orange box"} + + +def _wrap(a): + return float((a + np.pi) % (2 * np.pi) - np.pi) + + +def _wrap_half(a): + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def _rot(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s], [s, c]]) + + +def turntable_xml(model_name): + """Static pedestal + shelf board + side wall; a hinged disc (child body) with 4 pegs and painted marks.""" + def geoms(kind, pos, size, rgba, coll=True, vis=True): + s = f'type="{kind}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(rgba)}"' + out = [f''] if vis else [] + if coll: + out.insert(0, f'') + return out + + shelf = (0.82, 0.82, 0.80, 1.0) + fixed = geoms("cylinder", (0, 0, BASE_H / 2), (0.06, BASE_H / 2), (0.3, 0.3, 0.3, 1.0)) + by0, by1, bx = -(R + 0.04), BOARD_EDGE, R + 0.04 + fixed += geoms("box", (0, (by0 + by1) / 2, BOARD_Z + 0.004), (bx, (by1 - by0) / 2, 0.004), shelf) + fixed += geoms("box", (0, by0 + 0.005, BOARD_Z / 2), (bx, 0.005, BOARD_Z / 2), shelf) + # the round disc is visual only; its collision surface is the inscribed square plate: a box on a cylinder gets a + # single contact point and no torsional friction, and the butter span on the disc at ~4 deg/s even at rest (measured) + disc = geoms("cylinder", (0, 0, 0), (R, DISC_T / 2), (0.62, 0.42, 0.24, 1.0), coll=False) + disc += geoms("box", (0, 0, 0), (R / np.sqrt(2), R / np.sqrt(2), DISC_T / 2), (0.62, 0.42, 0.24, 1.0), vis=False) + for a in PEG_ANG: + disc += geoms("cylinder", (PEG_RAD * np.cos(a), PEG_RAD * np.sin(a), DISC_T / 2 + PEG_H / 2), + (PEG_R, PEG_H / 2), (0.75, 0.08, 0.08, 1.0)) + # painted marks (visual only) that make the disc's angle readable: yellow stripe, blue square, green dot + disc += geoms("box", (0.085 * np.cos(STRIPE_ANG), 0.085 * np.sin(STRIPE_ANG), DISC_T / 2 + 0.0006), + (0.055, 0.007, 0.0006), (0.95, 0.85, 0.10, 1.0), coll=False) + disc += geoms("box", (0.10 * np.cos(np.pi / 2), 0.10 * np.sin(np.pi / 2), DISC_T / 2 + 0.0006), + (0.016, 0.016, 0.0006), (0.15, 0.35, 0.85, 1.0), coll=False) + disc += geoms("cylinder", (0.10 * np.cos(-np.pi / 2), 0.10 * np.sin(-np.pi / 2), DISC_T / 2 + 0.0006), + (0.016, 0.0006), (0.15, 0.65, 0.25, 1.0), coll=False) + nl = "\n " + return f""" + + + + {nl.join(fixed)} + + + {nl.join(disc)} + + + + + + + + +""" + + +@register_task +class TurntableRestore(LFFTask): + name = "l2_turntable_restore" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Save", "Retrieve", "Utilize") + protocol = "within" + max_attempts = 5 + instruction = ("Put the butter into the basket. The butter is on the turntable, under the shelf. You can turn the " + "turntable by its red pegs. When you are done, the turntable must be turned exactly the way it is now.") + instruction_indirect = ("Put the small orange box into the wicker basket. It is on the round turntable, under the " + "shelf. You can turn the turntable by its red pegs. When you are done, the turntable must be " + "turned exactly the way it is now.") + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self._tt_bid = m.body_name2id(self.env.fixtures_dict[TT].root_body) + jid = m.joint_name2id(f"{TT}_spin") + self._qa, self._qv = m.jnt_qposadr[jid], m.jnt_dofadr[jid] + self.start = {} + self.turn_log = [] # per peg grasp: commanded sweep vs measured disc rotation (diagnostics) + self._home = None + self._c = np.zeros(2) + + # ------------------------------------------------------------ scene + def make_bddl(self): + tt = register_generated("LffTurntableShelf", turntable_xml("lff_turntable_shelf"), free=False) + objs = [(n, n[:-2], f"r_{i}", (0.20, -0.25 + 0.15 * i, 0.22, -0.23 + 0.15 * i)) for i, n in enumerate(ITEMS)] + objs.append((BASKET, "basket", "r_basket", (-0.10, 0.24, -0.08, 0.26))) + fx = [(TT, tt, "tt_region", (0.25, 0.30, 0.27, 0.32))] # moved in apply_instance + return write_bddl(self.name, self.instruction.replace(";", ","), objs, fixtures=fx) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + c = np.array([rng.uniform(-0.08, -0.02), rng.uniform(-0.12, -0.08)]) + th = {TARGET: float(rng.uniform(-0.14, 0.14))} # disc-frame angle of the butter (stripe at 180 deg) + rad = {n: float(ITEM_R + rng.uniform(-0.005, 0.005)) for n in ITEMS} + tilt = {n: float(rng.uniform(-0.17, 0.17)) for n in ITEMS} # box yaw relative to radial + # start angle: the butter sits under the board (world azimuth -90 +- 40 deg about the axis) + q0 = float(_wrap(-np.pi / 2 - th[TARGET] + rng.uniform(-np.radians(40), np.radians(40)))) + return dict(seed=int(seed), center=c.round(4).tolist(), q0=q0, theta=th, rad=rad, tilt=tilt, + basket_xy=[float(rng.uniform(-0.12, -0.06)), float(rng.uniform(0.25, 0.28))]) + + def disc_angle(self): + return float(self.env.sim.data.qpos[self._qa]) + + def to_world(self, r, th, q=None): + q = self.disc_angle() if q is None else q + return self._c + r * np.array([np.cos(th + q), np.sin(th + q)]) + + def to_disc(self, xy, q=None): + q = self.disc_angle() if q is None else q + return _rot(-q) @ (np.asarray(xy, float)[:2] - self._c) + + def place(self, name, xy, yaw, surface_z): + """Teleport a box flat (its mesh frame is flat) with yaw about world z, lowest point 2 mm above surface_z.""" + envs.set_obj_pose(self.env, name, [xy[0], xy[1], surface_z + 0.3], + quat_wxyz=np.array([np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)])) + self.env.sim.forward() + dz = envs.obj_min_z(self.env, name) - (surface_z + 0.002) + qa, _ = envs.free_joint_addr(self.env, name) + self.env.sim.data.qpos[qa + 2] -= dz + self.env.sim.forward() + + def apply_instance(self, inst): + m, d = self.env.sim.model, self.env.sim.data + self._c = np.array(inst["center"], float) + m.body_pos[self._tt_bid] = [self._c[0], self._c[1], envs.TABLE_Z] + m.body_quat[self._tt_bid] = [1, 0, 0, 0] + d.qpos[self._qa] = inst["q0"] + d.qvel[self._qv] = 0.0 + self.env.sim.forward() + for n in ITEMS: + envs.scale_mass(self.env, n, MASS[n]) + th = inst["theta"][n] + # long axis radial (+ tilt): the gripper then closes tangentially and keeps clear of the board + self.place(n, self.to_world(inst["rad"][n], th, inst["q0"]), th + inst["q0"] + inst["tilt"][n], + envs.TABLE_Z + DISC_TOP) + envs.scale_mass(self.env, BASKET, 2.0) + self.place(BASKET, inst["basket_xy"], 0.0, envs.TABLE_Z) + self.env.sim.forward() + + def reset_instance(self, inst, recorder=None): + sk = super().reset_instance(inst, recorder) + self.start = dict(q=self.disc_angle()) + self._home = sk.eef_pos() + return sk + + # ------------------------------------------------------------ measurements + def footprint(self, name): + """AABB centre, yaw of the long horizontal axis, z range (scripted 'perception').""" + m, d = self.env.sim.model, self.env.sim.data + lo, hi = np.full(3, np.inf), np.full(3, -np.inf) + best = None + for g in envs.obj_geom_ids(self.env, name): + Rg = d.geom_xmat[g].reshape(3, 3) + c = d.geom_xpos[g] + Rg @ m.geom_aabb[g, :3] + e = np.abs(Rg) @ m.geom_aabb[g, 3:] + lo, hi = np.minimum(lo, c - e), np.maximum(hi, c + e) + vol = float(np.prod(m.geom_aabb[g, 3:])) + if best is None or vol > best[0]: + best = (vol, Rg, m.geom_aabb[g, 3:]) + _, Rg, half = best + horiz = sorted([(half[k], Rg[:, k]) for k in range(3) if abs(Rg[2, k]) < 0.5], key=lambda t: -t[0]) + ax = horiz[0][1] if horiz else np.array([1.0, 0.0, 0.0]) + return dict(center=[float(v) for v in (lo + hi) / 2], yaw=float(np.arctan2(ax[1], ax[0])), + zmin=float(lo[2]), zmax=float(hi[2])) + + def item_loc(self, name): + f = self.footprint(name) + c = np.array(f["center"]) + held = self.sk is not None and self.sk.holding(name) + if held and f["zmin"] > envs.TABLE_Z + DISC_TOP + 0.01: + return "gripper", f + bp = envs.obj_pos(self.env, BASKET) + if np.all(np.abs(c[:2] - bp[:2]) <= BASKET_IN + 0.01) and f["zmin"] < envs.obj_min_z(self.env, BASKET) + BASKET_RIM \ + and f["zmin"] > envs.TABLE_Z + 0.005: + return "basket", f + on_disc = np.linalg.norm(c[:2] - self._c) < R and abs(f["zmin"] - (envs.TABLE_Z + DISC_TOP)) < 0.012 + if on_disc: + return "turntable", f + if f["zmin"] < envs.TABLE_Z + 0.01: + return "table", f + return "other", f + + def outcome(self, inst): + envs.settle(self.env, 30) + tloc, _ = self.item_loc(TARGET) + dq = _wrap(self.disc_angle() - self.start["q"]) + turned_ok = abs(dq) <= ANG_TOL + success = bool(tloc == "basket" and turned_ok) + return dict(success=success, target_loc=tloc, angle_err_deg=round(float(np.degrees(dq)), 1), + turned_ok=bool(turned_ok), + detail=self._describe(tloc, turned_ok, dq, NAMES), + detail_indirect=self._describe(tloc, turned_ok, dq, DESCR), + detail_offset=self._describe(tloc, turned_ok, dq, NAMES, offset=True)) + + @staticmethod + def _describe(tloc, turned_ok, dq, names, offset=False): + tn = names[TARGET] + msgs = [] + if tloc != "basket": + msgs.append({"gripper": f"The {tn} is still in the gripper, not in the basket.", + "turntable": f"The {tn} is still on the turntable, not in the basket.", + "table": f"The {tn} is on the table, not in the basket."} + .get(tloc, f"The {tn} is not in the basket.")) + if not turned_ok: + m = "The turntable is not turned the way it was at the start." + if offset: # ablation tier: relative measurement, externalises the memory + m += (f" It is turned {abs(np.degrees(dq)):.0f} deg " + f"{'counter-clockwise' if dq > 0 else 'clockwise'} (seen from above) from its starting angle.") + msgs.append(m) + if not msgs: + msgs.append(f"The {tn} is in the basket and the turntable is turned the way it was at the start.") + return " ".join(msgs) + + def feedback(self, inst, out, level="F2", indirect=False, offset=False): + """F0: nothing, F1: success flag, F2: what is wrong (never by how much the turntable is off). + offset=True (ablation tier 'F2+offset'): also the relative turn from the start angle.""" + if level == "F2": + key = "detail_offset" if offset else ("detail_indirect" if indirect else "detail") + out = dict(out, detail=out.get(key, out["detail"])) + return super().feedback(inst, out, level) + + # ------------------------------------------------------------ scripted motions (Skills.move_to / set_gripper) + SAFE_Z = envs.TABLE_Z + 0.22 # travel height between pegs / items + PICK_AZ = np.pi / 2 # where the butter is brought: middle of the open side (at 135 deg the open finger lands on + # the board edge -- measured); grasp yaw ~ +-90 deg, so the wrist is turned back to 0 while + # carrying (arriving at the basket with yaw -103 deg left the arm stalled near a joint limit) + WIN = (np.radians(30), np.radians(150)) # world azimuths where a peg can be held (open side, clear of the board) + + def go_home(self): + sk = self.sk + p = sk.eef_pos() + sk.move_to([p[0], p[1], max(p[2], self._home[2])]) + sk.move_to(self._home, yaw=0.0) + + def _settle_yaw(self, tol=np.radians(3), max_steps=40): + """move_to stops on position only; after a large wrist rotation hold until the yaw has converged (a descent + that starts mid-rotation swipes the open fingers across the pegs -- measured).""" + sk = self.sk + for _ in range(max_steps // 5): + R = sk.eef_mat() @ sk.R0.T + if abs(_wrap(np.arctan2(R[1, 0], R[0, 0]) - sk.yaw)) < tol: + return + sk.hold(5) + + def peg_azimuths(self): + return [_wrap(self.disc_angle() + a) for a in PEG_ANG] + + def turn(self, delta, step=np.radians(10)): + """Turn the disc by `delta` rad (+ = counter-clockwise seen from above): grasp a peg on the open side, + move the gripper along the rim in short straight segments, release, repeat.""" + sk = self.sk + zg = envs.TABLE_Z + DISC_TOP + PEG_H - 0.012 + rem = float(delta) + for _ in range(6): + if abs(rem) < np.radians(1.0): + break + az = self.peg_azimuths() + if rem > 0: + cands = [a for a in az if self.WIN[0] - 1e-6 <= a <= self.WIN[1] - np.radians(10)] + a0 = min(cands) + sweep = min(rem, self.WIN[1] - a0) + else: + cands = [a for a in az if self.WIN[0] + np.radians(10) <= a <= self.WIN[1] + 1e-6] + a0 = max(cands) + sweep = max(rem, self.WIN[0] - a0) + q_before = self.disc_angle() + p = self._c + PEG_RAD * np.array([np.cos(a0), np.sin(a0)]) + sk.set_gripper(False, steps=6) + # up, across, straight down: a long diagonal move at full speed sags ~5 cm below its line and the open + # fingers sweep the disc (measured: turned it 38 deg the wrong way) + cur = sk.eef_pos() + if cur[2] < self.SAFE_Z - 0.02: + sk.move_to([cur[0], cur[1], self.SAFE_Z]) + sk.move_to([p[0], p[1], self.SAFE_Z], yaw=np.pi / 2) # fingers close along world x + self._settle_yaw() + sk.move_to([p[0], p[1], zg + 0.03], speed=0.4) + sk.move_to([p[0], p[1], zg], tol=0.003, max_steps=80) + sk.set_gripper(True, steps=12) + dbg = dict(off=np.round((sk.eef_pos() - np.r_[self._c + PEG_RAD * np.array([np.cos(a0), np.sin(a0)]), zg]) * 100, 1).tolist(), + w=round(sk.gripper_width() * 100, 1), q_close=round(float(np.degrees(_wrap(self.disc_angle() - q_before))), 1), + yaw=round(float(np.degrees(sk.yaw)), 0)) + k = max(1, int(np.ceil(abs(sweep) / step))) + for i in range(1, k + 1): + w = self._c + PEG_RAD * np.array([np.cos(a0 + sweep * i / k), np.sin(a0 + sweep * i / k)]) + sk.move_to([w[0], w[1], zg], tol=0.003, max_steps=40) + sk.set_gripper(False, steps=8) + pe = sk.eef_pos() + sk.move_to([pe[0], pe[1], zg + 0.10]) + got = _wrap(self.disc_angle() - q_before) + self.turn_log.append(dict(peg_az=round(float(np.degrees(a0)), 1), sweep=round(float(np.degrees(sweep)), 1), + got=round(float(np.degrees(got)), 1), **dbg)) + rem -= got + + def pick_place(self, name, dest_xy, support_z, fp=None, carry_z=1.20, travel_z=1.15, carry_yaw=0.0): + """Top-down pick across the short side, carry, release just above support_z at dest_xy.""" + sk = self.sk + f = fp or self.footprint(name) + c = np.array(f["center"]) + gyaw = _wrap_half(f["yaw"]) + zg = max(f["zmin"] + 0.5 * (f["zmax"] - f["zmin"]), f["zmin"] + 0.0145) + sk.set_gripper(False, steps=6) + p = sk.eef_pos() + if p[2] < travel_z - 0.02: + sk.move_to([p[0], p[1], travel_z]) + sk.move_to([c[0], c[1], travel_z], yaw=gyaw) + self._settle_yaw() + sk.move_to([c[0], c[1], f["zmax"] + 0.03], speed=0.4) + sk.move_to([c[0], c[1], zg], tol=0.003, max_steps=80) + sk.set_gripper(True, steps=12) + sk.move_to([c[0], c[1], carry_z], speed=0.3) + sk.move_to([dest_xy[0], dest_xy[1], carry_z], yaw=carry_yaw) + sk.move_to([dest_xy[0], dest_xy[1], support_z + (zg - f["zmin"]) + 0.006], tol=0.003, speed=0.2, max_steps=150) + sk.hold(4) + sk.set_gripper(False, steps=10) + sk.move_to([dest_xy[0], dest_xy[1], travel_z], speed=0.4) + + def butter_to_basket(self, fp=None): + """The main task: if the butter is on the turntable, turn it to the open side first.""" + loc, f = self.item_loc(TARGET) + if loc == "turntable": + az = np.arctan2(f["center"][1] - self._c[1], f["center"][0] - self._c[0]) + # bring the butter's long axis parallel to world y (then the hand lies along x, away from the board edge; + # a hand turned 26 deg off caught the board -- measured); its centre ends within ~30 deg of PICK_AZ + delta = _wrap_half(f["yaw"] - az) + self.turn(_wrap(self.PICK_AZ - delta - az)) + b = envs.obj_pos(self.env, BASKET) + # release with the hand above the rim and let the box drop in: lowering it to the floor puts the 20 cm long + # hand below the rim of the 12 cm basket and the contact flips the wrist (joint 5 at its limit -- measured) + self.pick_place(TARGET, b[:2], envs.obj_min_z(self.env, BASKET) + BASKET_RIM + 0.02, fp=fp) + + def do(self, actions): + for act in actions: + if act[0] == "butter_to_basket": + self.butter_to_basket(fp=act[1] if len(act) > 1 else None) + elif act[0] == "turn_to": # ["turn_to", absolute disc angle (the agent's remembered start angle)] + self.turn(_wrap(act[1] - self.disc_angle())) + elif act[0] == "turn_by": + self.turn(act[1]) + else: + raise ValueError(act) + + # ------------------------------------------------------------ scripted reference policies + def _plan(self, kind, inst, a, history, rng, memory): + if kind == "naive" or (a == 0 and kind in ("adaptive", "blind", "nomem")): + return [["butter_to_basket"]] + if kind == "oracle": + return [["butter_to_basket"], ["turn_to", memory["q"]]] + last = history[-1]["outcome"] + acts = [] if last["target_loc"] == "basket" else [["butter_to_basket"]] + if kind == "adaptive": + return acts + ([] if last["turned_ok"] else [["turn_to", memory["q"]]]) + if kind == "nomem": + return acts + ([] if last["turned_ok"] else [["turn_by", float(rng.uniform(-np.pi, np.pi))]]) + if kind == "blind": + fp = self.footprint(TARGET) + fp["center"] = (np.array(fp["center"]) + np.r_[rng.normal(0, 0.005, 2), 0.0]).tolist() + return [["butter_to_basket", fp]] + raise ValueError(kind) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """Within-episode protocol: one reset, attempt 1 = main task, attempts 2..k = corrective rounds.""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + self.reset_instance(inst) + memory = dict(q=self.disc_angle()) # Save: the start angle (an agent reads it off the first frame) + for a in range(k): + actions = self._plan(kind, inst, a, history, rng, memory) + self.do(actions) + self.go_home() + out = self.outcome(inst) + params = dict(actions=[[x[0]] + ([round(float(np.degrees(x[1])), 1)] if x[0] != "butter_to_basket" else []) + for x in actions]) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history + + # cross-protocol hooks are not used by this task + def default_params(self, inst): + return dict(policy="naive") + + def oracle_params(self, inst): + return dict(policy="oracle") diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l3_card_edge.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l3_card_edge.py new file mode 100644 index 0000000000000000000000000000000000000000..c059c70a35c8232cfb403315761d1f526ee61693 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l3_card_edge.py @@ -0,0 +1,364 @@ +"""L3 card_edge: a thin card lying flat on a board cannot be pinched; slide it over the board's edge, then grasp it. + +Category: strategy_switching ("this way of doing it cannot work"), the user's taxonomy L3 example verbatim: +"卡片贴着桌面捏不起来 -> 先把卡片滑到桌沿,再夹起来". + +Scene: a wooden board (22 x 26 x 5 cm) on the table with a thin red card (9.0 x 5.6 x 0.2 cm, 10 g) lying flat on it, +long side roughly along x or along y (+-10 deg); a grey bin (16 x 16 cm inside) stands on the table beside the board. +The board stands in for the table edge of the user's example: the real table edge is out of reach (near edge 16 cm +from the robot base, side edges at |y| = 0.6 m) and the harness does not let the grasp point go below the table top. + +Why the prior fails (measured): a top-down grasp across the card's short side. The Panda fingertips land on the +board on either side of the card, but when they close on its 2 mm edge the contact flips to "slide over the top" and +both fingertips ride up over the card and close above it: 0/36 lifts for 1.5 / 2 / 3 mm cards, grasp-point height +-6..+3 mm, xy jitter 5 mm, yaw jitter 0.1 rad (prototype, 2026-10-08). Retrying with small variations fails the same +way. (A 4 mm card could be pinched -- the reason the earlier `l3_flat_card_edge` was dropped.) + +What must be learned from the failure: the card cannot be picked up while it lies flat -> change the strategy: press +the closed fingertips onto the card and slide it (move_to with the fingertips pressing on it) until part of it hangs +over the board's edge, then grasp the overhanging part with the fingertips below the card: then the fingers close on +the card's full edge and it lifts (18/18 for 2.5-3.5 cm of overhang in the prototype). More than half the card's +length over the edge and it tips off the board. + +Protocol: cross (reset to the same instance before every attempt), k = 5. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, _wrap, bin_xml, box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +CARD_HALF = (0.045, 0.028, 0.001) # 9.0 x 5.6 x 0.2 cm +CARD_MASS = 0.010 +MU = 0.3 # card and board sliding friction (the fingers' 1.0 / 2.0 win in finger contacts: MuJoCo takes the max) +BOARD_HALF = (0.11, 0.13, 0.025) +BOARD_TOP = envs.TABLE_Z + 2 * BOARD_HALF[2] +BIN_IN = 0.08 # inner half width +BIN_WALL_H = 0.05 +BIN_GAP = 0.06 # board edge to bin outer wall +BIN_T = 0.006 +BIN_HALF_OUT = BIN_IN + BIN_T +TIP_BELOW_SITE = envs.FINGERTIP_BELOW_SITE +LOW_CLOSE = 0.02 # a close counts as a grasp try when the fingertips are at most this far above the card +OVERHANG = 0.03 # scripted target overhang (the grasp works for ~2.5-4.0 cm; the card tips off past ~4.5 cm) +GRASP_OUT = 0.022 # scripted grasp point: this far beyond the board edge (fingers must clear the edge) +DRAG_SPEED = 0.08 + + +def card_xml(name, rgba=(0.85, 0.15, 0.12, 1.0)): + g = (f' \n' + f' ') + return _wrap(name, g, CARD_HALF[2], float(np.hypot(CARD_HALF[0], CARD_HALF[1]))) + + +def _yaw_of(quat_wxyz): + w, x, y, z = quat_wxyz + return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))) + + +EDGES = ("forward", "backward", "left", "right") # board edges in robot-centric words (+x, -x, +y, -y) + + +class CardSkills(Skills): + """Skills that feed the task's per-step monitor and log every close of the gripper.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + self.closes = [] + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + def set_gripper(self, close, steps=15): + was_open = self.grip < 0 + before = self.task.close_context() if (close and was_open) else None + rep = super().set_gripper(close, steps) + if before is not None: + before.update(held=self.holding("card_1"), width=round(self.gripper_width(), 4)) + self.closes.append(before) + return rep + + +@register_task +class CardEdge(LFFTask): + name = "l3_card_edge" + level = "L3" + category = "strategy_switching" + capabilities = ("Perceive", "Reason", "Plan") + protocol = "cross" + instruction = "Pick up the thin red card lying on the wooden board and put it into the grey bin." + instruction_indirect = "Put the flat red rectangle that lies on the wooden block into the grey container." + + # ------------------------------------------------------------ scene + def make_bddl(self): + card = register_generated("LffThinCard", card_xml("lff_thin_card")) + board = register_generated("LffCardBoard", box_xml("lff_card_board", BOARD_HALF, (0.62, 0.45, 0.27, 1.0), + friction=(MU, 0.005, 0.0001)), free=False) + bin_ = register_generated("LffCardBin", bin_xml("lff_card_bin", (BIN_IN, BIN_IN), BIN_WALL_H, wall_t=BIN_T, + rgba=(0.55, 0.56, 0.60, 1.0)), free=False) + objs = [("card_1", card, "card_region", (0.10, 0.20, 0.12, 0.22))] + fx = [("board_1", board, "board_region", (-0.11, -0.01, -0.09, 0.01)), + ("bin_1", bin_, "bin_region", (-0.11, -0.31, -0.09, -0.29))] + return write_bddl(self.name, self.instruction, objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.board_bid = m.body_name2id(self.env.fixtures_dict["board_1"].root_body) + self.bin_bid = m.body_name2id(self.env.fixtures_dict["bin_1"].root_body) + self.inst = None + self.mon = None + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + bx, by = float(rng.uniform(-0.14, -0.06)), float(rng.uniform(-0.08, 0.08)) + along = str(rng.choice(["x", "y"])) + yaw = (0.0 if along == "x" else np.pi / 2) + float(rng.uniform(-np.radians(10), np.radians(10))) + if along == "x": # keep the whole card >= 3 cm (long axis) / 2 cm (short axis) inside the board + off = [rng.uniform(-0.03, 0.03), rng.uniform(-0.07, 0.07)] + else: + off = [rng.uniform(-0.055, 0.055), rng.uniform(-0.05, 0.05)] + side = 1.0 if rng.random() < 0.5 else -1.0 + bin_xy = [bx + float(rng.uniform(-0.04, 0.04)), by + side * (BOARD_HALF[1] + BIN_GAP + BIN_HALF_OUT)] + return dict(seed=int(seed), board_xy=[bx, by], card_xy=[bx + float(off[0]), by + float(off[1])], + card_yaw=float(yaw), card_along=along, bin_xy=bin_xy, bin_side="left" if side > 0 else "right") + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + bx, by = inst["board_xy"] + m.body_pos[self.board_bid] = [bx, by, envs.TABLE_Z + BOARD_HALF[2]] + m.body_quat[self.board_bid] = [1.0, 0.0, 0.0, 0.0] + cx, cy = inst["bin_xy"] + m.body_pos[self.bin_bid] = [cx, cy, envs.TABLE_Z + (BIN_WALL_H + BIN_T) / 2] + m.body_quat[self.bin_bid] = [1.0, 0.0, 0.0, 0.0] + x, y = inst["card_xy"] + envs.set_obj_pose(self.env, "card_1", [x, y, BOARD_TOP + CARD_HALF[2] + 0.0003], yaw=inst["card_yaw"]) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = CardSkills(self.env, self, recorder=recorder) + p = self.card_pose() + self.mon = dict(start_xy=p["xy"].copy(), max_lift=0.0, max_overhang=0.0, fell=False) + return self.sk + + # ------------------------------------------------------------ geometry + def card_pose(self): + p = envs.obj_pos(self.env, "card_1") + return dict(xy=p[:2].copy(), z=float(p[2]), yaw=_yaw_of(envs.obj_quat(self.env, "card_1"))) + + def card_corners(self): + d = self.env.sim.data + bid = envs.body_id(self.env, "card_1") + R = d.body_xmat[bid].reshape(3, 3) + h = np.array(CARD_HALF) + return np.array([d.body_xpos[bid] + R @ (h * [sx, sy, 0.0]) for sx in (-1, 1) for sy in (-1, 1)]) + + def overhang(self): + """(how far the card sticks out beyond the board's edges (m, max over its corners), edge word)""" + c = self.card_corners()[:, :2] - np.asarray(self.inst["board_xy"]) + prot = {"forward": c[:, 0].max() - BOARD_HALF[0], "backward": -c[:, 0].min() - BOARD_HALF[0], + "left": c[:, 1].max() - BOARD_HALF[1], "right": -c[:, 1].min() - BOARD_HALF[1]} + e = max(prot, key=prot.get) + return float(prot[e]), e + + def on_board(self): + p = self.card_pose() + rel = np.abs(p["xy"] - np.asarray(self.inst["board_xy"])) + return bool(rel[0] <= BOARD_HALF[0] and rel[1] <= BOARD_HALF[1] and abs(p["z"] - BOARD_TOP) < 0.012) + + def in_bin(self): + p = self.card_pose() + rel = np.abs(p["xy"] - np.asarray(self.inst["bin_xy"])) + return bool(rel[0] <= BIN_IN and rel[1] <= BIN_IN and p["z"] < envs.TABLE_Z + BIN_T + BIN_WALL_H) + + # ------------------------------------------------------------ monitor + def monitor_step(self): + mon = self.mon + if mon is None: + return + zmin = float(self.card_corners()[:, 2].min()) + mon["max_lift"] = max(mon["max_lift"], zmin - BOARD_TOP) + if self.on_board() or abs(self.card_pose()["z"] - BOARD_TOP) < 0.012: + mon["max_overhang"] = max(mon["max_overhang"], self.overhang()[0]) + if self.card_pose()["z"] < BOARD_TOP - 0.02 and not self.sk.holding("card_1"): + mon["fell"] = True + + def close_context(self): + """Where the gripper is relative to the card and the board just before it closes.""" + sk, p = self.sk, self.card_pose() + e = sk.eef_pos() + c, s = np.cos(p["yaw"]), np.sin(p["yaw"]) + rel = e[:2] - p["xy"] + local = [float(rel @ [c, s]), float(rel @ [-s, c])] # along the card's long / short side + b = e[:2] - np.asarray(self.inst["board_xy"]) + beyond = {"forward": b[0] - BOARD_HALF[0], "backward": -b[0] - BOARD_HALF[0], + "left": b[1] - BOARD_HALF[1], "right": -b[1] - BOARD_HALF[1]} + edge = max(beyond, key=beyond.get) + ov, ov_edge = self.overhang() + return dict(step=sk.n_steps, local=[round(v, 4) for v in local], + tips_above_card=round(float(e[2] - TIP_BELOW_SITE - (p["z"] + CARD_HALF[2])), 4), + beyond_edge=round(float(beyond[edge]), 4), beyond_edge_name=edge, + card_on_board=self.on_board(), overhang=round(ov, 4), overhang_edge=ov_edge, + width_before=round(sk.gripper_width(), 4)) + + # ------------------------------------------------------------ outcome / F2 + def outcome(self, inst): + envs.settle(self.env, 30) + sk, mon = self.sk, self.mon + p = self.card_pose() + held = bool(sk.holding("card_1")) + in_bin = self.in_bin() and not held + success = bool(in_bin) + moved = float(np.linalg.norm(p["xy"] - mon["start_xy"])) + lifted = mon["max_lift"] > 0.02 + tries = [c for c in sk.closes if c["tips_above_card"] <= LOW_CLOSE and c["width_before"] > 0.02] + parts, mode = [], "success" + if success: + parts.append("The card is in the bin.") + else: + rel = p["xy"] - np.asarray(inst["bin_xy"]) + where = (f"{100 * abs(rel[0]):.1f} cm {'forward' if rel[0] > 0 else 'backward'} and " + f"{100 * abs(rel[1]):.1f} cm {'left' if rel[1] > 0 else 'right'} of the bin's centre") + if held: + mode = "held" + parts.append(f"The card is still held by the gripper, {where}.") + elif lifted: + mode = "dropped" + loc = "on the board" if self.on_board() else ("on the table" if p["z"] < BOARD_TOP - 0.02 else + "partly on the board") + parts.append(f"The card was lifted {100 * mon['max_lift']:.1f} cm above the board but is not in the " + f"bin: it lies {loc}, its centre {where}.") + elif mon["fell"]: + mode = "fell_off" + parts.append("The card was never lifted; it fell off the board and lies flat on the table.") + else: + mode = "not_lifted" + parts.append("The card was never lifted; it still lies flat on the board" + + (f" (it was slid {100 * moved:.1f} cm" + (f" and stuck out up to " + f"{100 * mon['max_overhang']:.1f} cm beyond the board's edge)" if mon["max_overhang"] > 0.003 + else ")") if moved > 0.005 else "") + ".") + if not lifted: + if not tries: + parts.append("The gripper never closed with its fingertips down at the card.") + else: + c = tries[-1] + n = f"{len(tries)} grasp tries; in the last one, " if len(tries) > 1 else "" + if c["card_on_board"] and c["overhang"] <= 0.0 and c["beyond_edge"] < 0.0: + txt = ("when the gripper closed on the card lying flat on the board, its fingertips were on " + "either side of the card, at board level") + else: + if c["beyond_edge"] >= 0.0: + pos = f"{100 * c['beyond_edge']:.1f} cm beyond the board's {c['beyond_edge_name']} edge" + else: + pos = f"over the board, {100 * -c['beyond_edge']:.1f} cm inside its {c['beyond_edge_name']} edge" + txt = (f"when the gripper closed, the card stuck out {100 * max(c['overhang'], 0.0):.1f} cm " + f"beyond the board's {c['overhang_edge']} edge and the gripper's centre was {pos}") + txt += (f" ({100 * c['tips_above_card']:+.1f} cm from the fingertips to the top of the card); the " + "fingers closed ") + txt += ("fully, sliding over the top of the card instead of gripping its edges." + if c["width"] < 2 * CARD_HALF[1] - 0.01 and not c["held"] else + ("on the card." if c["held"] else f"to {100 * c['width']:.1f} cm without holding the card.")) + parts.append(n + txt if n else txt[0].upper() + txt[1:]) + out = dict(success=success, mode=mode, held=held, lifted=bool(lifted), max_lift=round(mon["max_lift"], 4), + max_overhang=round(mon["max_overhang"], 4), moved=round(moved, 4), fell=bool(mon["fell"]), + grasp_tries=tries, closes=sk.closes, detail=" ".join(parts)) + return out + + # ------------------------------------------------------------ scripted policies (move_to + gripper only) + def _edge_plan(self, inst): + """the board edge the card is slid to: along its long side; the near (backward) edge for x-cards, + the closer side edge for y-cards""" + if inst["card_along"] == "x": + return "backward" + return "left" if inst["card_xy"][1] >= inst["board_xy"][1] else "right" + + def grasp_and_bin(self, xy, yaw, z_site, lift=0.12): + sk = self.sk + sk.set_gripper(False, steps=8) + sk.move_to([xy[0], xy[1], z_site + 0.08], yaw=yaw) + sk.move_to([xy[0], xy[1], z_site], tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + sk.move_to([xy[0], xy[1], z_site + lift], speed=0.2) + if not sk.holding("card_1"): + sk.set_gripper(False, steps=8) + return False + bx, by = self.inst["bin_xy"] + hi = envs.TABLE_Z + BIN_WALL_H + 0.12 + sk.move_to([bx, by, hi]) + sk.move_to([bx, by, envs.TABLE_Z + BIN_WALL_H + 0.05], speed=0.2) + sk.set_gripper(False, steps=12) + sk.move_to([bx, by, hi]) + return True + + def slide_card(self, delta, press=0.004): + """closed fingertips pressed on the card's centre, straight move by `delta` (xy), lift""" + sk, p = self.sk, self.card_pose() + z = p["z"] + CARD_HALF[2] + TIP_BELOW_SITE - press + sk.set_gripper(True, steps=8) + sk.move_to([p["xy"][0], p["xy"][1], z + 0.06], yaw=p["yaw"]) + sk.move_to([p["xy"][0], p["xy"][1], z], tol=0.003, max_steps=100) + e = p["xy"] + np.asarray(delta, float) + sk.move_to([e[0], e[1], z], speed=DRAG_SPEED, tol=0.004, max_steps=300) + sk.move_to([e[0], e[1], z + 0.06], speed=0.2) + sk.hold(5) + + def execute(self, inst, params): + p = self.card_pose() + if params["mode"] == "grasp": + xy = p["xy"] + np.asarray(params.get("dxy", (0.0, 0.0))) + self.grasp_and_bin(xy, p["yaw"] + params.get("dyaw", 0.0), BOARD_TOP + params.get("dz", 0.0)) + return + # edge: slide the card along its long side until `overhang` of it sticks out over the chosen edge + edge = params.get("edge") or self._edge_plan(inst) + u = {"forward": (1, 0), "backward": (-1, 0), "left": (0, 1), "right": (0, -1)}[edge] + u = np.asarray(u, float) + c, s = np.cos(p["yaw"]), np.sin(p["yaw"]) + long_ax = np.array([c, s]) if abs(np.array([c, s]) @ u) >= abs(np.array([-s, c]) @ u) else np.array([-s, c]) + long_ax = long_ax * np.sign(long_ax @ u) + b = np.asarray(inst["board_xy"]) + half = BOARD_HALF[0] if edge in ("forward", "backward") else BOARD_HALF[1] + edge_pos = (b @ u) + half # coordinate of the edge along u + ext = CARD_HALF[0] * abs(long_ax @ u) + CARD_HALF[1] * abs(np.array([-long_ax[1], long_ax[0]]) @ u) + for short in (0.01, 0.0): # slide to 1 cm short, look again, slide the rest (one stroke overshoots ~0.7 cm) + p = self.card_pose() + need = edge_pos + float(params["overhang"]) - short - (p["xy"] @ u + ext) # travel still needed along u + if need > 0.003: + self.slide_card(long_ax * need / max(long_ax @ u, 1e-6)) + q = self.card_pose() + cu = float(q["xy"] @ u) + tip_u = cu + CARD_HALF[0] * float(long_ax @ u) # centre of the card's far end, along u + target_u = min(tip_u - 0.008, edge_pos + GRASP_OUT) + g = q["xy"] + long_ax * (target_u - cu) / max(float(long_ax @ u), 1e-6) + self.grasp_and_bin(g, q["yaw"], BOARD_TOP - 0.003) + + def default_params(self, inst): + return dict(mode="grasp") + + def oracle_params(self, inst): + return dict(mode="edge", overhang=OVERHANG) + + def blind_params(self, inst, attempt, rng): + return dict(mode="grasp", dxy=rng.normal(0.0, 0.006, 2).tolist(), dyaw=float(rng.normal(0.0, 0.12)), + dz=float(rng.uniform(-0.006, 0.003))) + + def adapt_params(self, inst, history): + """not lifted while flat on the board (fingers slid over it) -> slide it over the edge first, 3 cm. + Edge tried: card fell off -> 1 cm less; fingers closed without holding and < 4 cm overhang -> 1 cm more.""" + out, prm = history[-1]["outcome"], history[-1]["params"] + if prm["mode"] == "grasp": + return dict(mode="edge", overhang=OVERHANG) if out["mode"] in ("not_lifted", "fell_off") else dict(prm) + h = float(prm["overhang"]) + if out["mode"] == "fell_off": + h -= 0.01 + elif out["mode"] == "not_lifted": + h += 0.01 if out["max_overhang"] < 0.04 else -0.005 + return dict(mode="edge", overhang=float(np.clip(h, 0.025, 0.045))) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l3_card_shelf.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l3_card_shelf.py new file mode 100644 index 0000000000000000000000000000000000000000..b56ab0538cd4224af8137664eacbda47e028a0ad --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l3_card_shelf.py @@ -0,0 +1,587 @@ +"""L3 card_shelf (2026-10-12): a deepened l3_card_edge. The thin card lies on a raised SHELF (thin top on four legs) +and hides a weight in one end; sliding the heavy end over the edge far enough to grasp it tips the card off the shelf +onto the table, where it lies flat and cannot be picked up: the attempt is lost. + +Why (../research_notes/P1P2_加深与常识任务设计.md sec. 1, 3.2): l3_card_edge saturated. Sonnet 5.5 (cla4) failed one +flat grasp, then in the same attempt slid the card 2-3 cm over the board's edge and grasped the overhang (both runs +succeeded on attempt 1): the failed grasp costs one command and changes nothing. Here the first common-sense +interaction (slide the nearest end out ~3 cm) has an irreversible cost whenever that end is the heavy one. + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): a wooden shelf +(top 22 x 26 x 1 cm on four 2 x 2 cm legs, top surface 10 cm above the table) with a thin red card (9.0 x 5.6 x 0.2 cm) +lying flat on it, long side along x or along y (+-8 deg). Its near end is 2.5-4 cm from the shelf edge it points to (an +x-card's near end is always the FORWARD one: a card that tips off the backward edge lands behind the shelf, hidden from +the front camera), the far end 9-14 cm from the opposite edge, both long sides >= 5 cm inside; a grey bin (16 x 16 cm +inside, 5 cm high) stands on the table beside the shelf (left or right, 6 cm gap). Same card size, mass (10 g), +friction and bin as l3_card_edge. + +Hidden variable (instance level, the same in every attempt, invisible): 8 of the card's 10 g are a weight hidden in one +end; its centre of mass sits COM_E = 2.8 cm from the middle towards that end. Both ends look identical. In 14 of every +20 consecutive seeds the heavy end is the NEAR end (the end a Sonnet-like agent slides out), else the far end. + +Mechanism (physics, no teleport): an end slid out by h tips over the edge once the centre of mass passes it. Measured +(card teleported with overhang h, 2 s): heavy end stays for h <= 1.7 cm, tips for h >= 1.8 cm; light end stays up to +7.0 cm; a uniform card up to ~4.5 cm. The grasp of an overhang needs the fingers past the edge: light end 1.8-3.8 cm +out -> 11/12 grasped; the heavy end only in a narrow window (1.3-1.5 cm out, grasp 0.8-1.2 cm beyond the edge: 12/36). +A tipped card is flat on the table within 0.4 s (56/56 tilt 0), where it cannot be gripped (0/56 regrasps) and no edge +is in reach. The fix is to slide the OTHER end out (a longer slide across the shelf), learnable from the failure: "only +~2 cm out and it already tipped -> that end is heavy" (the cheaper explanation "I pushed too far" leads to pushing +less, which leaves too little overhang to grasp). Validation (seeds 1000-1019): Sonnet-like naive tips 14/14 heavy-near +instances and succeeds on 6/6 light-near ones; the same habit succeeds 20/20 on l3_card_edge and 20/20 here with a +uniform card. + +Implementation notes: the centre of mass is fixed in the generated MJCF (explicit ) and the +heavy end is chosen by the card's yaw (the card is symmetric), so the body's inertial frame is never changed at runtime +(no bounding-volume refit needed; see lh_fence / envs.refit_bounds for that MuJoCo pitfall). The inertia is written in +scientific notation: objects._fmt (5 decimals) rounds a 10-30 g card's inertia to ~0 (a 10 g card does not compile; a +30 g card with rounded inertia got pinched and lifted by the flat grasp 4/16). Mass 10 g as in l3_card_edge: the flat +grasp then fails 20/20 (fingers slide over the card). The shelf is a static multi-geom fixture; its legs stand inside +its top's footprint (robot-leg contacts: 0 in all scripted runs). + +Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: success = the card lies in the bin, +not held; plus a per-step event log (end / side slid over an edge, tipped_off, lifted, released, in_bin, hand_hit_leg) +and R6 fields (tipped_off, trap_fired, grasp_tries) for the server log; F1 gives the agent only success / failure. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, _wrap, bin_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +TZ = envs.TABLE_Z +CARD_HALF = (0.045, 0.028, 0.001) # 9.0 x 5.6 x 0.2 cm (as l3_card_edge) +CARD_MASS = 0.010 # as l3_card_edge (flat grasp fails 20/20; a 30 g card was pinched and lifted 4/16) +SLUG_MASS = 0.008 # hidden weight (+ 2 g of card); slug centre 3.5 cm from the middle +COM_E = 0.028 # centre of mass this far from the card's middle, towards the heavy end (the card's local +x) +MU = 0.3 # card and shelf sliding friction (as l3_card_edge) +SHELF_HALF = (0.11, 0.13) # top half extents (as l3_card_edge's board) +SHELF_H = 0.10 # top surface above the table +TOP_T = 0.01 # top thickness +LEG = 0.01 # leg half width (2 x 2 cm legs) +LEG_IN = 0.012 # leg centre to the top's edges +SHELF_TOP = TZ + SHELF_H +CARD_REST_Z = SHELF_TOP + CARD_HALF[2] +BIN_IN = 0.08 # inner half width +BIN_WALL_H = 0.05 +BIN_GAP = 0.06 # shelf edge to bin outer wall +BIN_T = 0.006 +BIN_HALF_OUT = BIN_IN + BIN_T +TIP_BELOW_SITE = envs.FINGERTIP_BELOW_SITE +LOW_CLOSE = 0.02 # a close counts as a grasp try when the fingertips are at most this far above the card + +# instance ranges +P_HEAVY_NEAR = 0.7 # 14 of every 20 consecutive seeds +NEAR_GAP = (0.025, 0.040) # near end to its shelf edge +SIDE_CLEAR = 0.05 # long sides to the shelf's side edges, at least +YAW_JIT = np.radians(8.0) + +# scripted policies +GRASP_OUT = 0.022 # grasp point this far beyond the edge (fingers must clear the edge) +DRAG_SPEED = 0.08 +NAIVE_STEPS = (0.0, 0.01, 0.02, 0.03) # Sonnet-like: slide the end to the edge, then out in 1 cm steps, lift & look +ORACLE_STEPS = (0.02, 0.03) # l3_card_edge oracle: to 1 cm short, look, the rest + +EDGES = ("forward", "backward", "left", "right") # shelf edges in robot-centric words (+x, -x, +y, -y) +EDGE_U = {"forward": (1.0, 0.0), "backward": (-1.0, 0.0), "left": (0.0, 1.0), "right": (0.0, -1.0)} +OPPOSITE = {"forward": "backward", "backward": "forward", "left": "right", "right": "left"} + + +def card_xml(name, rgba=(0.85, 0.15, 0.12, 1.0)): + """Uniform-looking card; the inertial (10 g, centre of mass COM_E along local +x) models an 8 g weight hidden in + the +x end. Explicit inertial pos != 0, so MuJoCo keeps a separate inertial frame (see module doc).""" + h = CARD_HALF + ms = CARD_MASS - SLUG_MASS + xs = COM_E * CARD_MASS / SLUG_MASS # slug centre + sl = (0.0075, 0.021, h[2]) # slug half extents (1.5 x 4.2 x 0.2 cm) + box_i = lambda mm, a: mm / 3 * np.array([a[1] ** 2 + a[2] ** 2, a[0] ** 2 + a[2] ** 2, a[0] ** 2 + a[1] ** 2]) + par = lambda mm, r: mm * np.array([r[1] ** 2 + r[2] ** 2, r[0] ** 2 + r[2] ** 2, r[0] ** 2 + r[1] ** 2]) + c = np.array([COM_E, 0.0, 0.0]) + inertia = box_i(ms, h) + par(ms, -c) + box_i(SLUG_MASS, sl) + par(SLUG_MASS, np.array([xs, 0.0, 0.0]) - c) + g = (f' \n' + f' \n' + f' ') + return _wrap(name, g, h[2], float(np.hypot(h[0], h[1]))) + + +def shelf_xml(name, rgba=(0.62, 0.45, 0.27, 1.0), leg_rgba=(0.50, 0.36, 0.21, 1.0)): + """Static shelf: top plate on four legs; body origin at mid height (top surface at +SHELF_H / 2).""" + hx, hy = SHELF_HALF + H = SHELF_H / 2 + parts = [((0.0, 0.0, H - TOP_T / 2), (hx, hy, TOP_T / 2), rgba)] + for sx in (-1, 1): + for sy in (-1, 1): + parts.append(((sx * (hx - LEG_IN), sy * (hy - LEG_IN), -TOP_T / 2), (LEG, LEG, H - TOP_T / 2), leg_rgba)) + g = [] + for k, (p, s, c) in enumerate(parts): + g.append(f' ') + g.append(f' ') + return _wrap(name, "\n".join(g), H, float(np.hypot(hx, hy))) + + +def _yaw_of(quat_wxyz): + w, x, y, z = quat_wxyz + return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))) + + +class ShelfSkills(Skills): + """Skills that feed the task's per-step monitor and log every close of the gripper.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + self.closes = [] + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + def set_gripper(self, close, steps=15): + was_open = self.grip < 0 + before = self.task.close_context() if (close and was_open) else None + rep = super().set_gripper(close, steps) + if before is not None: + before.update(held=self.holding("card_1"), width=round(self.gripper_width(), 4)) + self.closes.append(before) + return rep + + +@register_task +class CardShelf(LFFTask): + name = "l3_card_shelf" + level = "L3" + category = "strategy_switching" + capabilities = ("Perceive", "Reason", "Plan") + protocol = "cross" + max_attempts = 3 + agent_max_steps = 40 + instruction = "Pick up the thin red card lying on the wooden shelf and put it into the grey bin." + instruction_indirect = "Put the flat red rectangle that lies on the raised wooden platform into the grey container." + + # ------------------------------------------------------------ scene + def make_bddl(self): + card = register_generated("LffShelfCard", card_xml("lff_shelf_card")) + shelf = register_generated("LffCardShelf", shelf_xml("lff_card_shelf"), free=False) + bin_ = register_generated("LffShelfBin", bin_xml("lff_shelf_bin", (BIN_IN, BIN_IN), BIN_WALL_H, wall_t=BIN_T, + rgba=(0.55, 0.56, 0.60, 1.0)), free=False) + objs = [("card_1", card, "card_region", (0.10, 0.20, 0.12, 0.22))] + fx = [("shelf_1", shelf, "shelf_region", (-0.11, -0.01, -0.09, 0.01)), + ("bin_1", bin_, "bin_region", (-0.11, -0.31, -0.09, -0.29))] + return write_bddl(self.name, self.instruction, objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.shelf_bid = m.body_name2id(self.env.fixtures_dict["shelf_1"].root_body) + self.bin_bid = m.body_name2id(self.env.fixtures_dict["bin_1"].root_body) + g0 = int(m.body_geomadr[self.shelf_bid]) + self.leg_geoms = {g for g in range(g0, g0 + int(m.body_geomnum[self.shelf_bid])) + if (m.geom_id2name(g) or "").endswith(("_g1", "_g2", "_g3", "_g4"))} + self.robot_geoms = set(envs.robot_geom_ids(self.env)) + self.inst = None + self.mon = None + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + bx, by = float(rng.uniform(-0.14, -0.06)), float(rng.uniform(-0.08, 0.08)) + along = str(rng.choice(["x", "y"])) + near_sign = 1.0 if rng.random() < 0.5 else -1.0 + if along == "x": # the near end of an x-card is the forward one: a card that tips off the backward edge lands + near_sign = 1.0 # behind the shelf, hidden from the front camera (measured); forward = nearest = away from the robot + jit = float(rng.uniform(-YAW_JIT, YAW_JIT)) + gap = float(rng.uniform(*NEAR_GAP)) + heavy_near = bool((int(seed) * 7) % 20 < round(20 * P_HEAVY_NEAR)) # balanced per 20 consecutive seeds + a_long, a_side = (0, 1) if along == "x" else (1, 0) # world axis of the card's long / short side + ext_long = CARD_HALF[0] * abs(np.cos(jit)) + CARD_HALF[1] * abs(np.sin(jit)) # half extents incl. the jitter + ext_side = CARD_HALF[0] * abs(np.sin(jit)) + CARD_HALF[1] * abs(np.cos(jit)) + c = [bx, by] + c[a_long] += near_sign * (SHELF_HALF[a_long] - gap - ext_long) + room = SHELF_HALF[a_side] - ext_side - SIDE_CLEAR + c[a_side] += float(rng.uniform(-room, room)) + u_near = np.zeros(2) + u_near[a_long] = near_sign + near_edge = {(1.0, 0.0): "forward", (-1.0, 0.0): "backward", (0.0, 1.0): "left", (0.0, -1.0): "right"}[ + (float(u_near[0]), float(u_near[1]))] + heavy_dir = u_near if heavy_near else -u_near # the card's local +x (heavy end) points this way (+- jitter) + yaw = float(np.arctan2(heavy_dir[1], heavy_dir[0]) + jit) + side = 1.0 if rng.random() < 0.5 else -1.0 + bin_xy = [bx + float(rng.uniform(-0.04, 0.04)), by + side * (SHELF_HALF[1] + BIN_GAP + BIN_HALF_OUT)] + return dict(seed=int(seed), shelf_xy=[bx, by], card_xy=[float(c[0]), float(c[1])], card_yaw=yaw, + card_along=along, near_edge=near_edge, far_edge=OPPOSITE[near_edge], near_gap=gap, + heavy_near=heavy_near, heavy_edge=near_edge if heavy_near else OPPOSITE[near_edge], + com_offset=COM_E, bin_xy=bin_xy, bin_side="left" if side > 0 else "right") + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + bx, by = inst["shelf_xy"] + m.body_pos[self.shelf_bid] = [bx, by, TZ + SHELF_H / 2] + m.body_quat[self.shelf_bid] = [1.0, 0.0, 0.0, 0.0] + cx, cy = inst["bin_xy"] + m.body_pos[self.bin_bid] = [cx, cy, TZ + (BIN_WALL_H + BIN_T) / 2] + m.body_quat[self.bin_bid] = [1.0, 0.0, 0.0, 0.0] + x, y = inst["card_xy"] + envs.set_obj_pose(self.env, "card_1", [x, y, CARD_REST_Z + 0.0003], yaw=inst["card_yaw"]) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = ShelfSkills(self.env, self, recorder=recorder) + p = self.card_pose() + self.mon = dict(start_xy=p["xy"].copy(), max_lift=0.0, max_overhang=0.0, fell=False, lifted=False, + out=dict(heavy=0.0, light=0.0, side=0.0), out_edge=dict(heavy=None, light=None, side=None), + flagged=set(), events=[], in_bin=False, tip=None, leg_hits=0, edge_used=None) + return self.sk + + # ------------------------------------------------------------ geometry + def card_pose(self): + p = envs.obj_pos(self.env, "card_1") + return dict(xy=p[:2].copy(), z=float(p[2]), yaw=_yaw_of(envs.obj_quat(self.env, "card_1"))) + + def _card_frame(self): + d = self.env.sim.data + bid = envs.body_id(self.env, "card_1") + return d.body_xpos[bid].copy(), d.body_xmat[bid].reshape(3, 3).copy() + + def card_corners(self): + p, R = self._card_frame() + h = np.array(CARD_HALF) + return np.array([p + R @ (h * [sx, sy, 0.0]) for sx in (-1, 1) for sy in (-1, 1)]) + + def _beyond(self, xy): + """{edge: how far the point lies beyond that edge of the shelf top (m, negative = inside)}""" + b = np.asarray(xy, float) - np.asarray(self.inst["shelf_xy"]) + return {"forward": b[0] - SHELF_HALF[0], "backward": -b[0] - SHELF_HALF[0], + "left": b[1] - SHELF_HALF[1], "right": -b[1] - SHELF_HALF[1]} + + def overhang(self): + """(how far the card sticks out beyond the shelf's edges (m, max over its corners), edge word)""" + best = (-1.0, None) + for c in self.card_corners(): + for e, v in self._beyond(c[:2]).items(): + if v > best[0]: + best = (float(v), e) + return best + + def part_overhangs(self): + """{'heavy' | 'light' | 'side': (overhang m, edge)}: the heavy end (local +x), light end and long sides, + each measured at its two corners.""" + p, R = self._card_frame() + h = np.array(CARD_HALF) + groups = {"heavy": [(1, -1), (1, 1)], "light": [(-1, -1), (-1, 1)]} + out = {} + for k, cs in groups.items(): + best = (-1.0, None) + for sx, sy in cs: + c = p + R @ (h * [sx, sy, 0.0]) + for e, v in self._beyond(c[:2]).items(): + if v > best[0]: + best = (float(v), e) + out[k] = best + best = (-1.0, None) # a long side: its middle point (an end pushed out also moves two corners out) + for sy in (-1, 1): + c = p + R @ (h * [0.0, sy, 0.0]) + for e, v in self._beyond(c[:2]).items(): + if v > best[0]: + best = (float(v), e) + out["side"] = best + return out + + def end_edge(self, which): + """shelf edge that the card's `which` end ('heavy' | 'light' | 'near' | 'far') points to, from the live pose""" + p = self.card_pose() + d = np.array([np.cos(p["yaw"]), np.sin(p["yaw"])]) # heavy end direction + if which == "near" or which == "far": + gaps = {} + for s in (1.0, -1.0): + u = d * s + e = max(EDGE_U, key=lambda k: float(np.asarray(EDGE_U[k]) @ u)) + tip = p["xy"] + u * CARD_HALF[0] + gaps[e] = -self._beyond(tip)[e] + near = min(gaps, key=gaps.get) + return near if which == "near" else OPPOSITE[near] + u = d if which == "heavy" else -d + return max(EDGE_U, key=lambda k: float(np.asarray(EDGE_U[k]) @ u)) + + def on_shelf(self): + p = self.card_pose() + rel = np.abs(p["xy"] - np.asarray(self.inst["shelf_xy"])) + return bool(rel[0] <= SHELF_HALF[0] and rel[1] <= SHELF_HALF[1] and abs(p["z"] - CARD_REST_Z) < 0.012) + + def on_table(self): + return bool(self.card_pose()["z"] < TZ + 0.03 and not self.in_bin()) + + def tilt_deg(self): + _, R = self._card_frame() + return float(np.degrees(np.arccos(np.clip(abs(R[2, 2]), 0.0, 1.0)))) + + def in_bin(self): + p = self.card_pose() + rel = np.abs(p["xy"] - np.asarray(self.inst["bin_xy"])) + return bool(rel[0] <= BIN_IN and rel[1] <= BIN_IN and p["z"] < TZ + BIN_T + BIN_WALL_H) + + # ------------------------------------------------------------ monitor + def _event(self, ev, **kw): + self.mon["events"].append(dict(event=ev, step=int(self.sk.n_steps), **kw)) + + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + p = self.card_pose() + held = self.sk.holding("card_1") + zmin = float(self.card_corners()[:, 2].min()) + mon["max_lift"] = max(mon["max_lift"], zmin - SHELF_TOP) + if held and zmin - SHELF_TOP > 0.02 and not mon["lifted"]: + mon["lifted"] = True + self._event("lifted") + rel = np.abs(p["xy"] - np.asarray(self.inst["shelf_xy"])) + if (not held and abs(p["z"] - CARD_REST_Z) < 0.004 and self.tilt_deg() < 5.0 and rel[0] <= SHELF_HALF[0] + and rel[1] <= SHELF_HALF[1]): # lying flat on the shelf + mon["max_overhang"] = max(mon["max_overhang"], self.overhang()[0]) + for k, (v, e) in self.part_overhangs().items(): + if v > mon["out"][k]: + mon["out"][k], mon["out_edge"][k] = v, e + if v >= 0.005 and k not in mon["flagged"]: + mon["flagged"].add(k) + self._event("side_over_edge" if k == "side" else "end_over_edge", part=k, edge=e) + if p["z"] < SHELF_TOP - 0.02 and not held and not mon["fell"]: + mon["fell"] = True + if not mon["lifted"]: # never lifted: it tipped (or was pushed) off the shelf + part = max(("heavy", "light", "side"), key=lambda k: mon["out"][k]) + mon["tip"] = dict(part=part, edge=mon["out_edge"][part], overhang=round(mon["out"][part], 4)) + self._event("tipped_off", **mon["tip"]) + else: + self._event("released") + d = self.env.sim.data + for i in range(d.ncon): # the hand / arm touching a shelf leg (should not happen in normal grasps) + c = d.contact[i] + if (c.geom1 in self.leg_geoms and c.geom2 in self.robot_geoms) or (c.geom2 in self.leg_geoms and + c.geom1 in self.robot_geoms): + if mon["leg_hits"] == 0: + self._event("hand_hit_leg") + mon["leg_hits"] += 1 + break + if not mon["in_bin"] and self.in_bin() and not held: + mon["in_bin"] = True + self._event("in_bin") + + def close_context(self): + """Where the gripper is relative to the card and the shelf just before it closes.""" + sk, p = self.sk, self.card_pose() + e = sk.eef_pos() + c, s = np.cos(p["yaw"]), np.sin(p["yaw"]) + rel = e[:2] - p["xy"] + local = [float(rel @ [c, s]), float(rel @ [-s, c])] # along the card's long / short side (+ = heavy end) + beyond = self._beyond(e[:2]) + edge = max(beyond, key=beyond.get) + ov, ov_edge = self.overhang() + return dict(step=sk.n_steps, local=[round(v, 4) for v in local], + tips_above_card=round(float(e[2] - TIP_BELOW_SITE - (p["z"] + CARD_HALF[2])), 4), + beyond_edge=round(float(beyond[edge]), 4), beyond_edge_name=edge, + card_on_shelf=self.on_shelf(), overhang=round(ov, 4), overhang_edge=ov_edge, + width_before=round(sk.gripper_width(), 4)) + + # ------------------------------------------------------------ outcome / F2 + def outcome(self, inst): + envs.settle(self.env, 30) + self.monitor_step() + sk, mon = self.sk, self.mon + p = self.card_pose() + held = bool(sk.holding("card_1")) + in_bin = self.in_bin() and not held + success = bool(in_bin) + moved = float(np.linalg.norm(p["xy"] - mon["start_xy"])) + lifted = mon["max_lift"] > 0.02 + tries = [c for c in sk.closes if c["tips_above_card"] <= LOW_CLOSE and c["width_before"] > 0.02] + parts, mode = [], "success" + rel = p["xy"] - np.asarray(inst["bin_xy"]) + where = (f"{100 * abs(rel[0]):.1f} cm {'forward' if rel[0] > 0 else 'backward'} and " + f"{100 * abs(rel[1]):.1f} cm {'left' if rel[1] > 0 else 'right'} of the bin's centre") + tip = mon["tip"] + if success: + parts.append("The card is in the bin.") + elif held: + mode = "held" + parts.append(f"The card is still held by the gripper, {where}.") + elif lifted: + mode = "dropped" + loc = ("on the shelf" if self.on_shelf() else "on the table" if self.on_table() else + "partly on the shelf" if p["z"] > SHELF_TOP - 0.02 else "off the shelf") + parts.append(f"The card was lifted {100 * mon['max_lift']:.1f} cm above the shelf but is not in the " + f"bin: it lies {loc}, its centre {where}.") + elif mon["fell"]: + mode = "fell_off" + what = "a long side" if tip["part"] == "side" else "one end" + parts.append(f"The card was never lifted: after {what} of it had been slid {100 * max(tip['overhang'], 0):.1f}" + f" cm beyond the shelf's {tip['edge']} edge, it tipped over that edge and fell off the shelf; " + + ("it lies flat on the table." if self.on_table() and self.tilt_deg() < 10 else + f"it rests off the shelf, tilted {self.tilt_deg():.0f} degrees.")) + else: + mode = "not_lifted" + parts.append("The card was never lifted; it still lies flat on the shelf" + + (f" (it was slid {100 * moved:.1f} cm" + (f" and stuck out up to " + f"{100 * mon['max_overhang']:.1f} cm beyond the shelf's edge)" if mon["max_overhang"] > 0.003 + else ")") if moved > 0.005 else "") + ".") + if not success and not lifted and tries: + c = tries[-1] + n = f"{len(tries)} grasp tries; in the last one, " if len(tries) > 1 else "" + if c["card_on_shelf"] and c["overhang"] <= 0.0 and c["beyond_edge"] < 0.0: + txt = ("when the gripper closed on the card lying flat on the shelf, its fingertips were on either side " + "of the card, at shelf level") + else: + pos = (f"{100 * c['beyond_edge']:.1f} cm beyond the shelf's {c['beyond_edge_name']} edge" + if c["beyond_edge"] >= 0.0 else + f"over the shelf, {100 * -c['beyond_edge']:.1f} cm inside its {c['beyond_edge_name']} edge") + txt = (f"when the gripper closed, the card stuck out {100 * max(c['overhang'], 0.0):.1f} cm beyond the " + f"shelf's {c['overhang_edge']} edge and the gripper's centre was {pos}") + txt += f" ({100 * c['tips_above_card']:+.1f} cm from the fingertips to the top of the card); the fingers closed " + txt += ("fully, sliding over the top of the card instead of gripping its edges." + if c["width"] < 2 * CARD_HALF[1] - 0.01 and not c["held"] else + ("on the card." if c["held"] else f"to {100 * c['width']:.1f} cm without holding the card.")) + parts.append(n + txt if n else txt[0].upper() + txt[1:]) + elif not success and not lifted and not mon["fell"]: + parts.append("The gripper never closed with its fingertips down at the card.") + failure = "none" if success else mode + out = dict(success=success, mode=mode, failure=failure, held=held, lifted=bool(lifted), + max_lift=round(mon["max_lift"], 4), max_overhang=round(mon["max_overhang"], 4), moved=round(moved, 4), + fell=bool(mon["fell"]), tipped_off=tip is not None, trap_fired=bool(tip is not None and + tip["part"] == "heavy"), + tip=tip, end_out={k: round(v, 4) for k, v in mon["out"].items()}, + end_out_edge=dict(mon["out_edge"]), card_final=dict(xy=[round(float(v), 4) for v in p["xy"]], + z_above_table=round(p["z"] - TZ, 4), + tilt_deg=round(self.tilt_deg(), 1)), + leg_hits=int(mon["leg_hits"]), slid_edge=mon["edge_used"], + events=list(mon["events"]), grasp_tries=tries, closes=sk.closes, detail=" ".join(parts)) + return out + + # ------------------------------------------------------------ scripted policies (move_to + gripper only) + def grasp_and_bin(self, xy, yaw, z_site, lift=0.12): + sk = self.sk + sk.set_gripper(False, steps=8) + sk.move_to([xy[0], xy[1], z_site + 0.08], yaw=yaw) + sk.move_to([xy[0], xy[1], z_site], tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + sk.move_to([xy[0], xy[1], z_site + lift], speed=0.2) + if not sk.holding("card_1"): + sk.set_gripper(False, steps=8) + return False + bx, by = self.inst["bin_xy"] + hi = SHELF_TOP + 0.10 + sk.move_to([bx, by, hi]) + sk.move_to([bx, by, TZ + BIN_WALL_H + 0.05], speed=0.2) + sk.set_gripper(False, steps=12) + sk.move_to([bx, by, hi]) + return True + + def slide_card(self, delta, press=0.004, at=(0.0, 0.0)): + """closed fingertips pressed on the card (at its centre + `at`), straight move by `delta` (xy), lift""" + sk, p = self.sk, self.card_pose() + z = p["z"] + CARD_HALF[2] + TIP_BELOW_SITE - press + s = p["xy"] + np.asarray(at, float) + sk.set_gripper(True, steps=8) + sk.move_to([s[0], s[1], z + 0.06], yaw=p["yaw"]) + sk.move_to([s[0], s[1], z], tol=0.003, max_steps=100) + e = s + np.asarray(delta, float) + sk.move_to([e[0], e[1], z], speed=DRAG_SPEED, tol=0.004, max_steps=300) + sk.move_to([e[0], e[1], z + 0.06], speed=0.2) + sk.hold(10) # look + + def push_end(self, u, dist, behind=0.015): + """closed fingers at shelf level `behind` m behind the card's trailing end, push it `dist` along u, lift""" + sk, p = self.sk, self.card_pose() + d = np.array([np.cos(p["yaw"]), np.sin(p["yaw"])]) + la = d * np.sign(d @ u) if abs(d @ u) > 0.5 else d + tail = p["xy"] - la * CARD_HALF[0] + s = tail - u * behind + z = SHELF_TOP + TIP_BELOW_SITE - 0.001 # fingertips on the shelf top (2 mm above: they pass over the card) + yaw = float(np.arctan2(u[1], u[0]) - np.pi / 2) # finger axis across the push direction + sk.set_gripper(True, steps=8) + sk.move_to([s[0], s[1], z + 0.05], yaw=yaw) + sk.move_to([s[0], s[1], z], tol=0.003, max_steps=100) + e = s + u * (behind + dist) + sk.move_to([e[0], e[1], z], speed=0.04, tol=0.004, max_steps=300) + sk.move_to([e[0], e[1], z + 0.05], speed=0.2) + sk.hold(10) + + def execute(self, inst, params): + p = self.card_pose() + rng = np.random.default_rng(params.get("noise_seed")) if params.get("noise_seed") is not None else None + if params.get("probe_grasp", False) or params["mode"] == "grasp": # flat grasp at the card's middle + dxy = np.asarray(params.get("probe_dxy", (0.0, 0.0))) + self.grasp_and_bin(p["xy"] + dxy, p["yaw"], SHELF_TOP + params.get("probe_dz", 0.0)) + if params["mode"] == "grasp" or self.sk.holding("card_1") or self.mon["lifted"]: + return + # slide one end of the card along its long side out over the edge it points to, in strokes + edge = params.get("edge") or self.end_edge(params.get("end", "near")) + self.mon["edge_used"] = edge + u = np.asarray(EDGE_U[edge], float) + b = np.asarray(inst["shelf_xy"]) + half = SHELF_HALF[0] if edge in ("forward", "backward") else SHELF_HALF[1] + edge_pos = float(b @ u) + half + for k, target in enumerate(params.get("steps", ORACLE_STEPS)): + if not self.on_shelf(): + return # tipped off: nothing left to grasp (the attempt is lost) + p = self.card_pose() + d = np.array([np.cos(p["yaw"]), np.sin(p["yaw"])]) + la = d * np.sign(d @ u) if abs(d @ u) >= 0.5 else np.array([-d[1], d[0]]) * np.sign(np.array([-d[1], d[0]]) @ u) + ext = max(float(c[:2] @ u) for c in self.card_corners()) - float(p["xy"] @ u) + tgt = float(target) + (float(rng.uniform(-1, 1)) * params.get("step_noise", 0.0) if rng is not None else 0.0) + need = edge_pos + tgt - (float(p["xy"] @ u) + ext) # travel still needed along u + if need > 0.003: + if params.get("style", "press") == "endpush": + self.push_end(u, need) + else: + at = (np.asarray(params.get("press_at", (0.0, 0.0))) if rng is None else + rng.normal(0.0, params.get("press_noise", 0.0), 2)) + self.slide_card(la * need / max(float(la @ u), 1e-6), at=at) + self.sk.hold(10) + if not self.on_shelf(): + return + q = self.card_pose() + d = np.array([np.cos(q["yaw"]), np.sin(q["yaw"])]) + la = d * np.sign(d @ u) if abs(d @ u) >= 0.5 else np.array([-d[1], d[0]]) * np.sign(np.array([-d[1], d[0]]) @ u) + cu = float(q["xy"] @ u) + tip_u = max(float(c[:2] @ u) for c in self.card_corners()) # outermost point of the card along u + target_u = min(tip_u - 0.008, edge_pos + params.get("grasp_out", GRASP_OUT)) + g = q["xy"] + la * (target_u - cu) / max(float(la @ u), 1e-6) + g = g + np.asarray(params.get("grasp_dxy", (0.0, 0.0))) + self.grasp_and_bin(g, q["yaw"], SHELF_TOP - 0.003 + params.get("grasp_dz", 0.0)) + + def default_params(self, inst): + """Sonnet-like (cla4 l3_card_edge): one flat grasp, then the nearest end out to the edge and 1 cm at a time + to ~3 cm, lifting the finger and looking after each stroke; grasp the overhang.""" + return dict(mode="edge", probe_grasp=True, end="near", steps=list(NAIVE_STEPS)) + + def oracle_params(self, inst): + """Knows the hidden weight: slides the light end out 3 cm (two strokes, as the l3_card_edge oracle).""" + return dict(mode="edge", end="light", steps=list(ORACLE_STEPS)) + + def blind_params(self, inst, attempt, rng): + """naive with small random variations, no history: nearest end, 2.5-3.5 cm, pressing point / grasp jitter""" + return dict(mode="edge", probe_grasp=True, end="near", steps=[0.0, 0.01, 0.02, float(rng.uniform(0.025, 0.035))], + noise_seed=int(rng.integers(1 << 30)), press_noise=0.005, + grasp_dxy=rng.uniform(-0.005, 0.005, 2).tolist(), grasp_dz=float(rng.uniform(-0.004, 0.003))) + + def adapt_params(self, inst, history): + """Tipped off the shelf (never lifted) -> slide the OTHER end next time (it tipped although only ~2 cm stuck + out: that end must be heavy). Slid out but not gripped -> 1 cm more overhang. Otherwise repeat.""" + out, prm = history[-1]["outcome"], history[-1]["params"] + used = out.get("slid_edge") or prm.get("edge") + nxt = dict(mode="edge", probe_grasp=False, edge=used, steps=list(ORACLE_STEPS)) + if out["mode"] == "fell_off": + e = (out.get("tip") or {}).get("edge") or used + nxt["edge"] = OPPOSITE.get(e) + elif out["mode"] == "not_lifted" and used is not None: + last = float((prm.get("steps") or ORACLE_STEPS)[-1]) + nxt["steps"] = [s + 0.01 for s in ORACLE_STEPS] if last < 0.035 else list(ORACLE_STEPS) + if nxt["edge"] is None: + nxt.pop("edge") + nxt["end"] = "near" + return nxt diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l3_tool.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l3_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..beedef27c243b3cea3823932d02204898034e069 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l3_tool.py @@ -0,0 +1,549 @@ +"""L3-C under_table_tool: a cube sits under a low glass side table; put it into the bin (tool use). + +v2 (2026-10-08, user review of cla2): in v1 the hidden information was "the hand does not fit under the glass top". +Every Sonnet run (4/4) saw the T-shaped stick lying next to the low table and used it straight away, i.e. the task +was solved by reasoning before acting and nothing had to be learned from a failure. v2 keeps the scene and moves the +hidden information to something no image shows: + +Hidden: the side of the low table AWAY from the stick is closed by a clear acrylic panel (between the two legs, +tabletop to glass top; collision only, nothing is rendered). The bin stands on that side, beyond the panel. The other +three sides are open. + +Why the prior fails: the stick lies on one side with its head pointing at the low table, and the bin is on the +opposite side, so the obvious plan is "slide the stick in and push the cube straight across, out towards the bin". +The cube then stops against the invisible panel, still completely under the glass top (the hand cannot reach it +there: the glass is 7 cm above the tabletop). Pushing harder or again from the same side fails the same way. + +What must be learned from the failure (F1: from the images -- the cube stopped at the edge and did not come out): +something blocks that side -> change the push: put the stick down behind the low table (the robot's side) pointing +forward, push the cube out of the FRONT side (away from the robot), then grasp it and carry it to the bin. + +Layout (randomised per instance): position of the low table, cube position under it (+-1 cm around the centre), +the stick lying beside the low table (left or right) with its head pointing at it (+-10 deg), the panel and the bin +on the other side. + +Protocol: cross (reset to the same instance before every attempt), k = 5. v1 is kept in l3_tool.py.bak-20261008-pane. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, _wrap, bin_xml, box_xml, register_generated +from ..skills import DT, _rot_err +from ..task_base import LFFTask, register_task + +CUBE_HALF = 0.02 +TOP_HALF = (0.06, 0.06, 0.005) # glass top 12 x 12 cm, 1 cm thick +TOP_UNDER = 0.07 # underside of the glass top above the tabletop +LEG_HALF = 0.008 +HANDLE_HALF = (0.12, 0.008, 0.01) # stick handle 24 x 1.6 x 2 cm, along local x +HEAD_HALF = (0.008, 0.025, 0.01) # crossbar 1.6 x 5 x 2 cm at the +x end +BIN_IN = (0.06, 0.06) +BIN_WALL_H = 0.05 +GRIP_END = 0.035 # scripted grasp point: this far from the free end of the handle +GRIP_FRONT = 0.07 # v2 front push: grasp this far from the free end (keeps the hand clear of the glass edge) +Z_STICK = envs.TABLE_Z + 0.0125 # site height when grasping / sliding the stick (pads 0.75-2.4 cm above the table) +TIP_BELOW_SITE = 0.0095 +# clear acrylic panel between the two legs of one y side, tabletop to glass underside (collision only, invisible) +PANE_HALF = (TOP_HALF[0] - 2 * LEG_HALF, 0.002, TOP_UNDER / 2) +PANE_Y = TOP_HALF[1] - LEG_HALF # in the plane of the leg centres +STICK_COM = 0.0221 # the stick's centre of mass is this far from the handle centre, towards the head +BIN_GAP = (0.04, 0.06) # tabletop gap between the low table's far side and the bin's outer wall + + +def low_table_xml(model_name): + glass, leg = (0.70, 0.85, 0.95, 0.30), (0.35, 0.25, 0.18, 1.0) + z_top = TOP_UNDER + TOP_HALF[2] + parts = [((0, 0, z_top), TOP_HALF, glass)] + for sx in (-1, 1): + for sy in (-1, 1): + parts.append(((sx * (TOP_HALF[0] - LEG_HALF), sy * (TOP_HALF[1] - LEG_HALF), TOP_UNDER / 2), + (LEG_HALF, LEG_HALF, TOP_UNDER / 2), leg)) + g = [] + for k, (p, s, c) in enumerate(parts): + g.append(f' ') + g.append(f' ') + # acrylic panels on both y sides; apply_instance turns the collision of the one next to the stick off. + # Fully transparent (rgba alpha 0) and no visual twin: nothing is rendered. + for k, sy in enumerate((1, -1)): + g.append(f' ') + # origin at the tabletop (z = 0 is the bottom of the legs) + return _wrap(model_name, "\n".join(g), 0.0, float(np.hypot(TOP_HALF[0], TOP_HALF[1]))) + + +def stick_xml(model_name): + c = (0.80, 0.62, 0.30, 1.0) + parts = [((0, 0, 0), HANDLE_HALF), ((HANDLE_HALF[0] + HEAD_HALF[0], 0, 0), HEAD_HALF)] + g = [] + for k, (p, s) in enumerate(parts): + g.append(f' ') + g.append(f' ') + return _wrap(model_name, "\n".join(g), HANDLE_HALF[2], HANDLE_HALF[0] + 2 * HEAD_HALF[0]) + + +def _yaw_of(quat_wxyz): + w, x, y, z = quat_wxyz + return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))) + + +@register_task +class UnderTableTool(LFFTask): + name = "l3_under_table_tool" + level = "L3" + category = "strategy_switching" + capabilities = ("Perceive", "Reason", "Plan") + protocol = "cross" + instruction = "Put the red cube into the gray bin." + instruction_indirect = "Put the small red block that is under the low glass table into the gray container." + + def __init__(self, cam_res=None): + super().__init__(cam_res) + self._mon = None + self.inst = None + orig_step = self.env.step + + def step(action): + ret = orig_step(action) + if self._mon is not None: + self._monitor_step() + return ret + + self.env.step = step + + # ------------------------------------------------------------ scene + def make_bddl(self): + cube = register_generated("LffBenchCube", box_xml("lff_bench_cube", (CUBE_HALF,) * 3, (0.85, 0.12, 0.12, 1.0), + density=800)) + stick = register_generated("LffBenchStick", stick_xml("lff_bench_stick")) + table = register_generated("LffLowGlassTable", low_table_xml("lff_low_glass_table"), free=False) + tray = register_generated("LffBenchBin", bin_xml("lff_bench_bin", BIN_IN, BIN_WALL_H), free=False) + objs = [("cube_1", cube, "cube_region", (-0.21, -0.26, -0.19, -0.24)), + ("stick_1", stick, "stick_region", (-0.01, 0.24, 0.01, 0.26))] + fx = [("lowtable_1", table, "lowtable_region", (0.19, -0.01, 0.21, 0.01)), + ("bin_1", tray, "bin_region", (0.19, 0.29, 0.21, 0.31))] + return write_bddl(self.name, self.instruction, objs, fx) + + def _fixture(self, name): + if not hasattr(self, "_fx"): + self._fx = {} + if name not in self._fx: + m = self.env.sim.model + bid = m.body_name2id(self.env.fixtures_dict[name].root_body) + + def under(b): + while b > 0: + if b == bid: + return True + b = m.body_parentid[b] + return False + + self._fx[name] = (bid, [g for g in range(m.ngeom) if under(m.geom_bodyid[g])]) + return self._fx[name] + + def _panes(self): + """[(geom id, +1 / -1 = which y side of the low table)] of the two acrylic panel geoms""" + if not hasattr(self, "_pane_ids"): + m = self.env.sim.model + self._pane_ids = [(g, int(np.sign(m.geom_pos[g][1]))) for g in self._fixture("lowtable_1")[1] + if np.allclose(m.geom_size[g], PANE_HALF, atol=1e-6)] + assert len(self._pane_ids) == 2, self._pane_ids + return self._pane_ids + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + side = int(rng.choice([-1, 1])) # the stick lies on the left (+1) or right (-1) of the low table + # v2: 4 cm further from the robot than v1 (-0.16..-0.10), so that a stick pushed forward from behind the + # low table is within reach (gripper about 25 cm in front of the robot base at the start of that push) + t_xy = np.array([rng.uniform(-0.12, -0.06), -side * rng.uniform(0.04, 0.07)]) + cube_xy = t_xy + rng.uniform(-0.01, 0.01, 2) + # the stick lies beside the low table, its head pointing roughly at it (+-10 deg), 2.5-4.5 cm from its edge + yaw = -side * np.pi / 2 + float(rng.uniform(-np.radians(10), np.radians(10))) + d = np.array([np.cos(yaw), np.sin(yaw)]) + head_front = np.array([cube_xy[0] + rng.uniform(-0.01, 0.01), t_xy[1] + side * (TOP_HALF[1] + rng.uniform(0.025, 0.045))]) + stick_xy = head_front - d * (HANDLE_HALF[0] + 2 * HEAD_HALF[0]) + # v2: the bin stands on the far side (the panel's side), so pushing the cube straight across looks like the + # way to the bin + gap = rng.uniform(*BIN_GAP) + bin_xy = np.array([t_xy[0] + rng.uniform(-0.02, 0.02), + t_xy[1] - side * (TOP_HALF[1] + gap + BIN_IN[1] + 0.006)]) + return dict(seed=int(seed), table_xy=t_xy.tolist(), cube_xy=cube_xy.tolist(), side=side, pane_side=-side, + stick_xy=stick_xy.tolist(), stick_yaw=float(yaw), bin_xy=bin_xy.tolist()) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + bid, _ = self._fixture("lowtable_1") + m.body_pos[bid] = [inst["table_xy"][0], inst["table_xy"][1], envs.TABLE_Z] + m.body_quat[bid] = [1, 0, 0, 0] + for g, sy in self._panes(): # only the panel on the far side (away from the stick) collides + on = sy == inst.get("pane_side", -inst["side"]) + m.geom_contype[g] = 1 if on else 0 + m.geom_conaffinity[g] = 1 if on else 0 + bbid, _ = self._fixture("bin_1") + m.body_pos[bbid] = [inst["bin_xy"][0], inst["bin_xy"][1], envs.TABLE_Z + (BIN_WALL_H + 0.006) / 2] + m.body_quat[bbid] = [1, 0, 0, 0] + cx, cy = inst["cube_xy"] + envs.set_obj_pose(self.env, "cube_1", [cx, cy, envs.TABLE_Z + CUBE_HALF + 0.0005]) + sx, sy = inst["stick_xy"] + envs.set_obj_pose(self.env, "stick_1", [sx, sy, envs.TABLE_Z + HANDLE_HALF[2] + 0.0005], yaw=inst["stick_yaw"]) + + def reset_instance(self, inst, recorder=None): + self._mon = None + sk = super().reset_instance(inst, recorder=recorder) + self._start_monitor() + return sk + + # ------------------------------------------------------------ state + def stick_pose(self): + d = self.env.sim.data + bid = envs.body_id(self.env, "stick_1") + return d.body_xpos[bid].copy(), d.body_xmat[bid].reshape(3, 3).copy() + + def observe(self): + p, R = self.stick_pose() + ax = R[:2, 0] / max(np.linalg.norm(R[:2, 0]), 1e-9) + return dict(cube=envs.obj_pos(self.env, "cube_1"), table_xy=np.array(self.inst["table_xy"]), + bin_xy=np.array(self.inst["bin_xy"]), stick_xy=p[:2], stick_dir=ax, + free_end=p[:2] - ax * HANDLE_HALF[0], head=p[:2] + ax * (HANDLE_HALF[0] + HEAD_HALF[0])) + + def under_table(self, xy=None, margin=0.0): + """is the cube's footprint (any part) under the glass top?""" + xy = envs.obj_pos(self.env, "cube_1")[:2] if xy is None else np.asarray(xy) + rel = np.abs(xy - np.array(self.inst["table_xy"])) + return bool((rel < np.array(TOP_HALF[:2]) + CUBE_HALF + margin).all()) + + def outside_dist(self): + """how far the cube's footprint is outside the glass top (m, < 0: still partly under it)""" + rel = np.abs(envs.obj_pos(self.env, "cube_1")[:2] - np.array(self.inst["table_xy"])) + return float(max(rel - np.array(TOP_HALF[:2]) - CUBE_HALF)) + + def in_bin(self): + p = envs.obj_pos(self.env, "cube_1") + rel = np.abs(p[:2] - np.array(self.inst["bin_xy"])) + return bool(p[2] < envs.TABLE_Z + BIN_WALL_H and (rel < np.array(BIN_IN)).all()) + + # ------------------------------------------------------------ contacts / monitor + def _groups(self): + if not hasattr(self, "_gg"): + m = self.env.sim.model + robot = set(envs.robot_geom_ids(self.env)) + tbl = self._fixture("lowtable_1")[1] + top = {g for g in tbl if m.geom_contype[g] and abs(m.geom_size[g, 0] - TOP_HALF[0]) < 1e-6} + self._gg = (robot, set(tbl), top, set(envs.obj_geom_ids(self.env, "stick_1")), + set(envs.obj_geom_ids(self.env, "cube_1"))) + return self._gg + + def _robot_contacts(self): + """labels of what the robot touches: 'glass_top', 'pane', 'table_leg', 'stick', 'cube'""" + robot, tbl, top, stick, cube = self._groups() + panes = {g for g, _ in self._panes()} + d = self.env.sim.data + out = set() + for i in range(d.ncon): + c = d.contact[i] + if c.geom1 in robot: + o = c.geom2 + elif c.geom2 in robot: + o = c.geom1 + else: + continue + if o in top: + out.add("glass_top") + elif o in panes: + out.add("pane") + elif o in tbl: + out.add("table_leg") + elif o in stick: + out.add("stick") + elif o in cube: + out.add("cube") + return out + + def _start_monitor(self): + c = envs.obj_pos(self.env, "cube_1") + self._mon = dict(start=c.copy(), top_hit=None, stick_held=False, stick_touched_cube=False, max_cube_dz=0.0, + cube_out=not self.under_table(), cube_hit_pane=False, stick_hit_pane=False, + robot_hit_pane=False) + + def _monitor_step(self): + mon, sk = self._mon, self.sk + if sk is None: + return + hits = self._robot_contacts() + if "glass_top" in hits: + e = sk.eef_pos() + rel = np.abs(e[:2] - np.array(self.inst["table_xy"])) + mon["top_hit"] = dict(above=bool((rel < np.array(TOP_HALF[:2])).all()), + tip=float(e[2] - TIP_BELOW_SITE - envs.TABLE_Z), + outside=float(max(rel - np.array(TOP_HALF[:2])))) + if sk.holding("stick_1"): + mon["stick_held"] = True + if "pane" in hits: + mon["robot_hit_pane"] = True + robot, tbl, top, stick, cube = self._groups() + panes = {g for g, _ in self._panes()} + d = self.env.sim.data + for i in range(d.ncon): + c = d.contact[i] + pair = (c.geom1, c.geom2) + if (pair[0] in stick and pair[1] in cube) or (pair[1] in stick and pair[0] in cube): + mon["stick_touched_cube"] = True + if (pair[0] in panes and pair[1] in cube) or (pair[1] in panes and pair[0] in cube): + mon["cube_hit_pane"] = True + if (pair[0] in panes and pair[1] in stick) or (pair[1] in panes and pair[0] in stick): + mon["stick_hit_pane"] = True + p = envs.obj_pos(self.env, "cube_1") + mon["max_cube_dz"] = max(mon["max_cube_dz"], float(p[2] - mon["start"][2])) + if not self.under_table(): + mon["cube_out"] = True + + # ------------------------------------------------------------ outcome / F2 + def outcome(self, inst): + envs.settle(self.env, 30) + mon = self._mon or {} + p = envs.obj_pos(self.env, "cube_1") + held = bool(self.sk.holding("cube_1")) if self.sk is not None else False + success = bool(self.in_bin() and not held) + moved = float(np.linalg.norm(p[:2] - mon.get("start", p)[:2])) + under = self.under_table() + brel = p[:2] - np.array(inst["bin_xy"]) + parts, mode = [], "success" + top = mon.get("top_hit") + if success: + parts.append("The cube is in the bin.") + elif p[2] < envs.TABLE_Z - 0.05: + mode = "fell_off" + parts.append("The cube fell off the table.") + elif held: + mode = "held" + parts.append("The cube is still held by the gripper; it was not released into the bin.") + elif under: + mode = "under" + if top is not None and not mon.get("stick_touched_cube"): + mode = "blocked" + if top["above"]: + parts.append(f"The gripper came down on the glass top of the low table: its fingertips stopped " + f"{100 * max(top['tip'], 0.0):.1f} cm above the tabletop, while the cube is underneath " + f"the glass (the glass underside is {100 * TOP_UNDER:.1f} cm above the tabletop), so the " + f"gripper never got to the cube.") + else: + parts.append(f"The hand ran into the edge of the glass top of the low table (fingertips " + f"{100 * max(top['tip'], 0.0):.1f} cm above the tabletop, gripper " + f"{100 * max(top['outside'], 0.0):.1f} cm outside the edge) and could not move in " + f"under the glass.") + if mon.get("cube_hit_pane"): + mode = "pane" + parts.append(f"The cube was pushed against a clear acrylic panel that closes the " + f"{'left' if inst.get('pane_side', -inst['side']) > 0 else 'right'} side of the low " + f"table (between its two legs, from the tabletop up to the glass); it cannot leave the " + f"low table on that side.") + if moved > 0.01: + parts.append(f"The cube was moved {100 * moved:.1f} cm but is still under the low table " + f"({100 * -self.outside_dist():.1f} cm from getting completely out from under it).") + else: + parts.append("The cube did not move; it is still under the low table.") + else: + mode = "out_not_in_bin" + lifted = mon.get("max_cube_dz", 0.0) > 0.03 + parts.append(("The cube was lifted but ended outside the bin" if lifted else + "The cube is out from under the low table but not in the bin") + + f": it is {100 * abs(brel[0]):.1f} cm {'forward' if brel[0] > 0 else 'backward'} and " + f"{100 * abs(brel[1]):.1f} cm {'left' if brel[1] > 0 else 'right'} of the bin's centre.") + out = dict(success=success, mode=mode, moved=moved, under=under, cube_rel_bin=[float(brel[0]), float(brel[1])], + stick_used=bool(mon.get("stick_held")), terminal=bool(p[2] < envs.TABLE_Z - 0.05), + cube_hit_pane=bool(mon.get("cube_hit_pane")), stick_hit_pane=bool(mon.get("stick_hit_pane")), + robot_hit_pane=bool(mon.get("robot_hit_pane")), detail=" ".join(parts)) + self._start_monitor() + return out + + # ------------------------------------------------------------ primitives for the scripted policies + def _yaw_near(self, yaw): + cands = [yaw + k * np.pi for k in (-2, -1, 0, 1, 2)] + cands = [c for c in cands if abs(c) <= np.pi / 2 + 0.4] or cands + return float(min(cands, key=lambda c: abs(c - self.sk.yaw))) + + def _align(self, tol=0.03, max_steps=60): + sk = self.sk + for _ in range(max_steps): + R = sk._R() @ sk.eef_mat().T + if np.arccos(np.clip((np.trace(R) - 1) / 2, -1, 1)) < tol: + break + sk.hold(1) + + def _guarded_descent(self, xyz, speed=0.12, max_steps=80): + sk = self.sk + p0 = sk.eef_pos() + tgt = np.asarray(xyz, float) + dist = max(np.linalg.norm(tgt - p0), 1e-6) + R = sk._R() + for k in range(max_steps): + ref = p0 + (tgt - p0) * min(1.0, (k + 1) * speed * DT / dist) + sk._act(ref - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip) + if self._robot_contacts() - {"cube"} and sk.eef_pos()[2] > tgt[2] + 0.005: + break + if np.linalg.norm(tgt - sk.eef_pos()) < 0.003: + break + sk.hold(4) + + def grasp_cube_and_bin(self, dxy=(0.0, 0.0), dyaw=0.0): + """Top-down grasp of the cube where it is (+ offsets); if held, drop it into the bin.""" + sk, o = self.sk, self.observe() + c = o["cube"] + gx, gy = c[0] + dxy[0], c[1] + dxy[1] + # the hand is 20 cm long along the closing direction: keep that direction parallel to the low table's edge + v = c[:2] - o["table_xy"] + yaw = (np.pi / 2 if abs(v[1]) > abs(v[0]) else 0.0) + dyaw + sk.set_gripper(False, steps=8) + sk.move_to([gx, gy, envs.TABLE_Z + 0.15], yaw=self._yaw_near(yaw)) + self._align() + self._guarded_descent([gx, gy, envs.TABLE_Z + 0.017]) + sk.set_gripper(True, steps=15) + e = sk.eef_pos() + sk.move_to([e[0], e[1], envs.TABLE_Z + 0.16], speed=0.25) + if sk.holding("cube_1"): + bx, by = o["bin_xy"] + sk.move_to([bx, by, envs.TABLE_Z + 0.16]) + sk.move_to([bx, by, envs.TABLE_Z + BIN_WALL_H + 0.05]) + sk.set_gripper(False, steps=12) + sk.move_to([bx, by, envs.TABLE_Z + 0.16]) + else: + sk.set_gripper(False, steps=6) + + def tool_push_out(self, extra=0.0): + """Pick the stick up by the end of its handle (it already points at the low table), lift it a few mm and slide + it along its own axis under the glass top so that its head pushes the cube out on the far side; put it down.""" + sk, o = self.sk, self.observe() + ax = o["stick_dir"] + g = o["free_end"] + ax * GRIP_END + sk.set_gripper(False, steps=8) + sk.move_to([g[0], g[1], Z_STICK + 0.08], yaw=self._yaw_near(float(np.arctan2(ax[1], ax[0])))) + self._align() + sk.move_to([g[0], g[1], Z_STICK], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([g[0], g[1], Z_STICK + 0.006], speed=0.05) + o2 = self.observe() + c, t_xy = o2["cube"][:2], o2["table_xy"] + n = np.array([0.0, -float(self.inst["side"])]) # push straight across the low table (normal of its far edge) + perp = np.array([-n[1], n[0]]) + head = o2["head"] + # line the head up with the cube by sliding the stick sideways (no turning: a turned stick slips in the grasp) + lat = float((c - head) @ perp) + e = sk.eef_pos() + sk.move_to([e[0] + perp[0] * lat, e[1] + perp[1] * lat, e[2]], speed=0.05) + o3 = self.observe() + head_front = float((o3["head"] + o3["stick_dir"] * HEAD_HALF[0]) @ n) + gap = max(float(c @ n) - CUBE_HALF - head_front, 0.0) + need = (TOP_HALF[1] + CUBE_HALF + 0.05 + extra) - float((c - t_xy) @ n) # cube travel until it is clear + e = sk.eef_pos() + tgt = e[:2] + n * (gap + need) + sk.move_to([tgt[0], tgt[1], e[2]], speed=0.08, tol=0.004, max_steps=500) + sk.hold(3) + for _ in range(3): # still (partly) under the glass top: push on a little + if not self.under_table() or not sk.holding("stick_1"): + break + e = sk.eef_pos() + tgt = e[:2] + n * 0.025 + sk.move_to([tgt[0], tgt[1], e[2]], speed=0.06, tol=0.004, max_steps=100) + sk.hold(3) + ax = n + back = sk.eef_pos()[:2] - ax * 0.05 + sk.move_to([back[0], back[1], e[2]], speed=0.08) + sk.set_gripper(False, steps=10) + sk.move_to([back[0], back[1], envs.TABLE_Z + 0.12], speed=0.2) + + def tool_push_front(self, extra=0.0): + """v2 reference solution. Pick the stick up at its centre of mass, turn it to point forward (+x, away from the + robot) in the air, put it down behind the low table in line with the cube, re-grasp it GRIP_FRONT from its + free end and slide it forward under the glass top so that its head pushes the cube out of the FRONT side; + pull the stick back a little and put it down. + + Reach: the re-grasp point is about 25 cm in front of the robot base at the start of the push; it stays + >= 3 cm behind the glass top's back edge at the end (the hand is about 4-13 cm above the fingertips and + would hit the glass edge).""" + sk, o = self.sk, self.observe() + ax = o["stick_dir"] + com = o["stick_xy"] + ax * STICK_COM + phi = float(np.arctan2(ax[1], ax[0])) # the stick points this way (handle -> head); about +-90 deg + sk.set_gripper(False, steps=8) + # grasp with gripper yaw = phi (not phi +- pi), so that turning the stick to point forward is a wrist turn to + # yaw 0, inside the wrist's range + sk.move_to([com[0], com[1], Z_STICK + 0.08], yaw=phi, wrap_yaw=False) + self._align() + sk.move_to([com[0], com[1], Z_STICK], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([com[0], com[1], Z_STICK + 0.10], speed=0.15) + c, t_xy = o["cube"][:2], o["table_xy"] + head_front_x = t_xy[0] - TOP_HALF[0] - 0.006 # just outside the glass top's back edge + put_x = head_front_x - (HANDLE_HALF[0] + 2 * HEAD_HALF[0]) + STICK_COM + e = sk.eef_pos() + sk.move_to([e[0], e[1], e[2]], yaw=0.0, wrap_yaw=False) + self._align() + sk.move_to([put_x, c[1], Z_STICK + 0.10], speed=0.2) + sk.move_to([put_x, c[1], Z_STICK + 0.004], speed=0.08, tol=0.003) + sk.set_gripper(False, steps=10) + sk.move_to([put_x, c[1], Z_STICK + 0.06], speed=0.15) + # re-grasp near the free end + o2 = self.observe() + ax2 = o2["stick_dir"] + g = o2["free_end"] + ax2 * GRIP_FRONT + sk.move_to([g[0], g[1], Z_STICK + 0.06], yaw=self._yaw_near(float(np.arctan2(ax2[1], ax2[0])))) + self._align() + sk.move_to([g[0], g[1], Z_STICK], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([g[0], g[1], Z_STICK + 0.006], speed=0.05) + # line the head up with the cube (sideways slide), then push forward + o3 = self.observe() + lat = float(c[1] - o3["head"][1]) + e = sk.eef_pos() + sk.move_to([e[0], e[1] + lat, e[2]], speed=0.05) + o4 = self.observe() + head_front = float(o4["head"][0] + HEAD_HALF[0]) + cube_tgt = t_xy[0] + TOP_HALF[0] + CUBE_HALF + 0.03 + extra + travel = (cube_tgt - CUBE_HALF) - head_front + e = sk.eef_pos() + sk.move_to([e[0] + travel, e[1], e[2]], speed=0.08, tol=0.004, max_steps=500) + sk.hold(3) + e = sk.eef_pos() + sk.move_to([e[0] - 0.05, e[1], e[2]], speed=0.08) + sk.set_gripper(False, steps=10) + e = sk.eef_pos() + sk.move_to([e[0], e[1], envs.TABLE_Z + 0.12], speed=0.2) + + def execute(self, inst, params): + if params["mode"] == "tool": + self.tool_push_out(params.get("extra", 0.0)) + elif params["mode"] == "front": + self.tool_push_front(params.get("extra", 0.0)) + self.grasp_cube_and_bin(params.get("dxy", (0.0, 0.0)), params.get("dyaw", 0.0)) + + # ------------------------------------------------------------ scripted references + def default_params(self, inst): + """v2 prior: what every cla2 Sonnet run did -- take the stick and push the cube straight across (towards + the bin, which is now behind the hidden panel)""" + return dict(mode="tool") + + def oracle_params(self, inst): + return dict(mode="front") + + def blind_params(self, inst, attempt, rng): + """no history: the prior with a random extra push length""" + return dict(mode="tool", extra=float(abs(rng.normal(0, 0.03)))) + + def adapt_params(self, inst, history): + """v2: the cube stayed under the low table after a push across -> something blocks that side: push it out of + the front instead. Hand grasp blocked by the glass -> use the stick (the v1 lesson). Front push that did not + get it out -> push further.""" + out, prm = history[-1]["outcome"], history[-1]["params"] + if prm["mode"] == "grasp": + return dict(mode="tool") if out["mode"] in ("blocked", "under") else dict(prm) + if prm["mode"] == "tool": + return dict(mode="front") if out["mode"] in ("pane", "under", "blocked") else dict(prm) + if out["mode"] in ("under", "blocked"): + return dict(prm, extra=prm.get("extra", 0.0) + 0.02) + return dict(prm) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l3_wall.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l3_wall.py new file mode 100644 index 0000000000000000000000000000000000000000..85c1d73ef0922858d68710e01a64b66eafeb9650 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l3_wall.py @@ -0,0 +1,501 @@ +"""L3-A wall_flush: a flat long box lies flush against a low fixed wall; put it on the plate. + +Why the prior fails: the only graspable dimension of the box is its 6 cm width (the Panda opens to +~7.9 cm; the box is 16 cm long). Grasping across the width needs one finger between the box and the +wall, but the box touches the wall (gap 0-3 mm) along its whole length, so that finger lands on top of +the wall (4.5 cm high; the box is 3.5 cm high) and the gripper closes above the box. Retrying the same +grasp with small variations fails the same way. + +What must be learned from the failure: this grasp is infeasible in this state -> change the manipulation +mode: first slide the box along the wall until it clears the wall's end (non-prehensile pre-grasp +manipulation), then grasp it across its width. + +Layout: the wall runs along y (left-right as seen from the robot). Randomised per instance: wall length +(24-30 cm), wall position, whether the wall is on the far (+x) or near (-x) side of the box, where the +box sits along the wall (always fully alongside it, >= 2 cm of wall beyond each end), box-wall gap +(0-3 mm, below camera resolution), plate position (on the open side of the box). + +Protocols: `l3_wall_flush` (cross: reset to the same instance before every attempt) and +`l3_wall_flush_within` (one episode; each attempt starts from wherever the previous one left things). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import box_xml, register_generated +from ..skills import DT, _rot_err +from ..task_base import LFFTask, register_task + +BOX_HALF = np.array([0.03, 0.08, 0.0175]) # 6 (x) x 16 (y) x 3.5 cm; long axis along y +WALL_HALF_T = 0.015 # 3 cm thick (x) +WALL_HALF_H = 0.0225 # 4.5 cm high +WALL_HALF_L_MAX = 0.16 # registered half length (y); shrunk per instance +WALL_MU = 2.0 # wall sliding friction (MuJoCo uses the max of the two geoms: finger-wall and box-wall contacts get 2.0) +BOX_DENSITY = 1500.0 # -> 0.50 kg +GRIP_OPEN = 0.079 # measured distance between the finger pads when fully open +FINGER_NEEDS = 0.012 # free space a finger needs beside the box (pad + finger shell), measured +Z_GRASP = envs.TABLE_Z + 0.022 # gripper-site height for grasping (pads cover 1.7-3.4 cm above the table) +Z_PUSH = envs.TABLE_Z + 0.022 # site height while pushing: finger tips 1.2 cm above the table, hand ~7 mm above the wall +PUSH_SPEED = 0.08 +FINGER_BELOW_SITE = 0.0096 # finger tips are this far below the gripper site (measured) +PLACE_Z = envs.TABLE_Z + 0.048 # site height at release over the plate (box bottom ~8 mm above the rim) + + +def _wrap_half_pi(a): + """wrap to [-pi/2, pi/2): box and parallel gripper are both symmetric under 180 deg""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def _yaw_of(quat_wxyz): + w, x, y, z = quat_wxyz + return _wrap_half_pi(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))) + + +@register_task +class WallFlush(LFFTask): + name = "l3_wall_flush" + level = "L3" + category = "strategy_switching" + capabilities = ("Perceive", "Reason", "Plan") + protocol = "cross" + instruction = "Put the long box on the plate." + instruction_indirect = "Put the flat blue block onto the round dish." + + def __init__(self, cam_res=None): + super().__init__(cam_res) + self._mon = None + # Per-control-step event monitor. It wraps env.step so that it also sees attempts driven by the agent + # harness (whose tools call Skills / env.step directly), not only the scripted `execute`. + orig_step = self.env.step + + def step(action): + ret = orig_step(action) + if self._mon is not None: + self._monitor_step() + return ret + + self.env.step = step + + def reset_instance(self, inst, recorder=None): + self._mon = None + sk = super().reset_instance(inst, recorder=recorder) + self._start_monitor() + return sk + + # ------------------------------------------------------------ scene + def make_bddl(self): + # 0.5 kg box and a grippy wall top (mu 2): with mu 1 / 0.13 kg an *unguarded* press onto the wall top (plain + # move_to down, as an agent would do) let the finger slide ~5 cm off the wall and, on the wall-far side, + # flipped the box onto its 3.5 cm side (10/60 instances) -- an accidental, graspable state (see task card). + box = register_generated("LffFlushBox", box_xml("lff_flush_box", BOX_HALF, (0.12, 0.30, 0.80, 1.0), + density=BOX_DENSITY)) + wall = register_generated("LffFlushWall", box_xml("lff_flush_wall", (WALL_HALF_T, WALL_HALF_L_MAX, WALL_HALF_H), + (0.62, 0.50, 0.36, 1.0), density=1000, + friction=(WALL_MU, 0.005, 0.0001)), free=False) + # regions only need to be valid and far apart; the layout is overridden in apply_instance + objs = [("box_1", box, "box_region", (-0.21, -0.26, -0.19, -0.24)), + ("plate_1", "plate", "plate_region", (-0.01, 0.24, 0.01, 0.26))] + fx = [("wall_1", wall, "wall_region", (0.19, -0.01, 0.21, 0.01))] + return write_bddl(self.name, self.instruction, objs, fx) + + def _wall(self): + """(root body id, geom ids) of the wall fixture""" + if not hasattr(self, "_wall_cache"): + m = self.env.sim.model + bid = m.body_name2id(self.env.fixtures_dict["wall_1"].root_body) + + def under(b): + while b > 0: + if b == bid: + return True + b = m.body_parentid[b] + return False + + self._wall_cache = (bid, [g for g in range(m.ngeom) if under(m.geom_bodyid[g])]) + return self._wall_cache + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + side = int(rng.choice([-1, 1])) # +1: wall on the far (+x) side of the box, -1: near (-x) side + wall_hl = float(rng.uniform(0.12, 0.15)) + wall_y = float(rng.uniform(-0.06, 0.06)) + u_max = wall_hl - BOX_HALF[1] - 0.02 # >= 2 cm of wall beyond each end of the box + box_y = wall_y + float(rng.uniform(-u_max, u_max)) + gap = float(rng.uniform(0.0, 0.003)) + box_x = float(rng.uniform(-0.12, -0.04)) if side > 0 else float(rng.uniform(-0.20, -0.12)) + wall_x = box_x + side * (WALL_HALF_T + BOX_HALF[0] + gap) + plate_xy = [box_x - side * float(rng.uniform(0.16, 0.18)), box_y + float(rng.uniform(-0.06, 0.06))] + return dict(seed=int(seed), side=side, wall_hl=wall_hl, wall_xy=[wall_x, wall_y], gap=gap, + box_xy=[box_x, box_y], plate_xy=plate_xy) + + def apply_instance(self, inst): + m = self.env.sim.model + bid, geoms = self._wall() + for g in geoms: # shrink the (collision + visual) wall boxes to this instance's length + m.geom_size[g, 1] = inst["wall_hl"] + m.body_pos[bid] = [inst["wall_xy"][0], inst["wall_xy"][1], envs.TABLE_Z + WALL_HALF_H] + m.body_quat[bid] = [1, 0, 0, 0] + bx, by = inst["box_xy"] + envs.set_obj_pose(self.env, "box_1", [bx, by, envs.TABLE_Z + BOX_HALF[2] + 0.0005]) + self._move_keep_orientation("plate_1", inst["plate_xy"]) + + def _move_keep_orientation(self, name, xy, clearance=0.002): + """Move a LIBERO mesh object to xy keeping the orientation LIBERO's sampler gave it at reset (that + orientation is the upright one; see task card), lowest collision point `clearance` above the table.""" + qa, da = envs.free_joint_addr(self.env, name) + d = self.env.sim.data + d.qpos[qa:qa + 2] = xy + d.qvel[da:da + 6] = 0.0 + self.env.sim.forward() + d.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (envs.TABLE_Z + clearance) + self.env.sim.forward() + + # ------------------------------------------------------------ perception stand-in + def observe(self): + """What a perfect perceiver reads off the camera image: box centre / yaw, the wall's footprint and the + plate centre. (Not the box-wall gap: 0-3 mm is below the camera resolution.)""" + bid, geoms = self._wall() + m = self.env.sim.model + wx, wy = m.body_pos[bid][:2] + hl = m.geom_size[geoms[0], 1] + b = envs.obj_pos(self.env, "box_1") + return dict(box_xy=b[:2].copy(), box_yaw=_yaw_of(envs.obj_quat(self.env, "box_1")), + wall_x=float(wx), wall_y=(float(wy - hl), float(wy + hl)), + plate_xy=envs.obj_pos(self.env, "plate_1")[:2].copy()) + + def _gap_now(self, o=None): + o = o or self.observe() + return float(abs(o["box_xy"][0] - o["wall_x"]) - WALL_HALF_T - BOX_HALF[0]) + + def alongside_wall(self, o=None): + """box (centre) still beside the wall and too close to it for a finger""" + o = o or self.observe() + return bool(o["wall_y"][0] < o["box_xy"][1] < o["wall_y"][1] and self._gap_now(o) < FINGER_NEEDS) + + # ------------------------------------------------------------ contacts + def _finger_landings(self): + """Surfaces the finger tips are resting on: contacts between a finger and a non-robot geom whose normal is + mostly vertical (a tip landing on a top surface). Returns {label: contact z}, label in 'wall' | 'box' | + 'plate' | 'table' | 'other'. Side contacts (a finger brushing the box's side, the push stroke) are ignored.""" + m, d = self.env.sim.model, self.env.sim.data + if not hasattr(self, "_geom_groups"): + fg = {g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_finger")} + robot = set(envs.robot_geom_ids(self.env)) + self._geom_groups = (fg, robot, set(self._wall()[1]), set(envs.obj_geom_ids(self.env, "box_1")), + set(envs.obj_geom_ids(self.env, "plate_1"))) + fg, robot, wall, box, plate = self._geom_groups + out = {} + for i in range(d.ncon): + c = d.contact[i] + if c.geom1 in fg and c.geom2 not in robot: + other = c.geom2 + elif c.geom2 in fg and c.geom1 not in robot: + other = c.geom1 + else: + continue + if abs(c.frame[2]) < 0.7: + continue + if other in wall: + lab = "wall" + elif other in box: + lab = "box" + elif other in plate: + lab = "plate" + else: + lab = "table" if (m.geom_id2name(other) or "").startswith("table") else "other" + out.setdefault(lab, float(c.pos[2])) + return out + + def _finger_landing(self): + hits = self._finger_landings() + for lab in ("wall", "box", "plate", "table", "other"): + if lab in hits: + return lab + return None + + # ------------------------------------------------------------ event monitor (what happened in this attempt) + def _closing_axis(self): + m, d = self.env.sim.model, self.env.sim.data + jid = m.joint_name2id(self.env.robots[0].gripper.joints[0]) + a = d.xaxis[jid][:2] + return a / max(np.linalg.norm(a), 1e-9) + + def _snapshot(self, contact_z): + """state at the moment a finger lands on something""" + o = self.observe() + e = self.sk.eef_pos() if self.sk is not None else self.env.sim.data.site_xpos[self.env.robots[0].eef_site_id] + bx = self.env.sim.data.body_xmat[envs.body_id(self.env, "box_1")].reshape(3, 3)[:2, 0] # box short axis + cosang = abs(float(self._closing_axis() @ (bx / max(np.linalg.norm(bx), 1e-9)))) + yaw_err = float(np.arccos(np.clip(cosang, 0.0, 1.0))) + wy0, wy1 = o["wall_y"] + return dict(contact_z=float(contact_z - envs.TABLE_Z), eef=[float(e[0]), float(e[1]), float(e[2])], + box_xy=[float(o["box_xy"][0]), float(o["box_xy"][1])], gap=self._gap_now(o), + alongside=self.alongside_wall(o), yaw_err=yaw_err, + span=float(2 * (BOX_HALF[0] * np.cos(yaw_err) + BOX_HALF[1] * np.sin(yaw_err))), + box_offset=float(np.linalg.norm(np.array(e[:2]) - o["box_xy"])), + # signed wall length beside the gripper towards each end (< 0: gripper is past that end) + wall_left={1: float(wy1 - e[1]), -1: float(e[1] - wy0)}) + + def _start_monitor(self): + b = envs.obj_pos(self.env, "box_1") + self._mon = dict(start_xy=b[:2].copy(), rest_z=float(b[2]), max_dz=0.0, wall_hit=None, box_top_hit=None, + prev=set()) + + def _monitor_step(self): + mon = self._mon + hits = self._finger_landings() + mon["max_dz"] = max(mon["max_dz"], float(envs.obj_pos(self.env, "box_1")[2] - mon["rest_z"])) + for lab, key in (("wall", "wall_hit"), ("box", "box_top_hit")): + if lab in hits and lab not in mon["prev"]: # onset of a landing; keep the latest one + mon[key] = self._snapshot(hits[lab]) + mon["prev"] = set(hits) + + def _finger_front(self, direction): + """how far the (closed) fingers stick out from the gripper site along `direction` (xy unit vector)""" + m, d = self.env.sim.model, self.env.sim.data + e = self.sk.eef_pos() + best = 0.0 + for g in range(m.ngeom): + if not (m.geom_id2name(g) or "").startswith("gripper0_finger") or m.geom_type[g] != 7: + continue + mid = m.geom_dataid[g] + v = m.mesh_vert[m.mesh_vertadr[mid]:m.mesh_vertadr[mid] + m.mesh_vertnum[mid]] + w = v @ d.geom_xmat[g].reshape(3, 3).T + d.geom_xpos[g] - e + best = max(best, float((w[:, :2] @ direction).max())) + return best + + # ------------------------------------------------------------ primitives used by the scripted policies + def _yaw_near(self, yaw): + """The parallel gripper (and the box) are symmetric under 180 deg, so pick yaw + k*pi closest to the current + commanded yaw: the OSC's axis-angle error is ill-defined at 180 deg and a half-turn request can flip the + hand over (measured: in the within protocol it twisted the arm into a state it never recovered from).""" + cands = [yaw + k * np.pi for k in (-1, 0, 1)] + cands = [c for c in cands if abs(c) <= np.pi / 2 + 0.4] or cands + return float(min(cands, key=lambda c: abs(c - self.sk.yaw))) + + def _align(self, tol=0.03, max_steps=60): + """Skills.move_to stops on position only; hold until the commanded yaw has actually been reached.""" + sk = self.sk + for _ in range(max_steps): + R = sk._R() @ sk.eef_mat().T + if np.arccos(np.clip((np.trace(R) - 1) / 2, -1, 1)) < tol: + break + sk.hold(1) + + def _guarded_descent(self, xyz, speed=0.12, max_steps=60): + """Straight-line descent that stops as soon as a finger lands on a surface above the target (the way a + grasp approach with contact sensing behaves). Without it, the OSC keeps pressing the finger into the + wall top and the compliant arm slides ~2 cm sideways off it. Returns what the finger landed on.""" + sk = self.sk + p0 = sk.eef_pos() + tgt = np.asarray(xyz, float) + sk.bias + dist = max(np.linalg.norm(tgt - p0), 1e-6) + R = sk._R() + landed = None + for k in range(max_steps): + ref = p0 + (tgt - p0) * min(1.0, (k + 1) * speed * DT / dist) + sk._act(ref - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip) + hit = self._finger_landing() + if hit is not None and sk.eef_pos()[2] > tgt[2] + 0.005: + landed = hit + break + if np.linalg.norm(tgt - sk.eef_pos()) < 0.003: + break + sk.hold(4) + return landed + + def push_along_wall(self, end, margin): + """Closed gripper (fingers side by side across the box) behind the box's trailing end face; slide the + box along y (towards the wall's +y end if end=+1, -y end if end=-1) until the box centre is `margin` + beyond that end of the wall.""" + sk, o = self.sk, self.observe() + bx, by = o["box_xy"] + wall_end = o["wall_y"][1] if end > 0 else o["wall_y"][0] + dist = float(np.clip(end * (wall_end + end * margin - by), 0.0, 0.32)) + yaw = self._yaw_near(o["box_yaw"] + np.pi / 2) # fingers close along the box's short axis + u = np.array([0.0, float(end)]) + sk.set_gripper(True, steps=6) + sk.move_to([bx, by - end * (BOX_HALF[1] + 0.06), Z_PUSH + 0.10], yaw=yaw) + self._align() + front = self._finger_front(u) + face = by - end * BOX_HALF[1] + start_y = face - end * (front + 0.035) + stop_y = face + end * (dist - front) + sk.move_to([bx, start_y, Z_PUSH + 0.10]) + sk.move_to([bx, start_y, Z_PUSH], tol=0.003) + sk.move_to([bx, stop_y, Z_PUSH], speed=PUSH_SPEED, tol=0.005, max_steps=300) + sk.hold(3) + sk.move_to([bx, stop_y, Z_PUSH + 0.10], speed=0.2) + + def grasp_and_place(self, dx=0.0, dy=0.0, dyaw=0.0): + """Top-down grasp across the box's width at the observed box centre (+ offsets), lift; if the box is + held, carry it to the plate and release it there.""" + sk, o = self.sk, self.observe() + gx, gy = o["box_xy"][0] + dx, o["box_xy"][1] + dy + yaw = self._yaw_near(o["box_yaw"] + np.pi / 2 + dyaw) + sk.set_gripper(False, steps=8) + sk.move_to([gx, gy, Z_GRASP + 0.10], yaw=yaw) + self._align() + self._guarded_descent([gx, gy, Z_GRASP]) + sk.set_gripper(True, steps=15) + z0 = envs.obj_pos(self.env, "box_1")[2] + sk.move_to([gx, gy, Z_GRASP + 0.15], speed=0.25) + if not (sk.holding("box_1") and envs.obj_pos(self.env, "box_1")[2] > z0 + 0.08): + sk.set_gripper(False, steps=8) + return + px, py = o["plate_xy"] + sk.move_to([px, py, PLACE_Z + 0.10]) + sk.move_to([px, py, PLACE_Z], tol=0.004) + sk.set_gripper(False, steps=12) + sk.move_to([px, py, PLACE_Z + 0.10]) + + def execute(self, inst, params): + if params["mode"] == "push_grasp": + self.push_along_wall(params["end"], params["margin"]) + self.grasp_and_place(params.get("dx", 0.0), params.get("dy", 0.0), params.get("dyaw", 0.0)) + + # ------------------------------------------------------------ outcome / F2 feedback + def outcome(self, inst): + """Success = box resting flat on the plate, released. The F2 text is built from the event monitor, so it + describes agent-driven attempts as well as scripted ones. Ends the current monitoring segment.""" + envs.settle(self.env, 30) + env, mon = self.env, self._mon or {} + b = envs.obj_pos(env, "box_1") + p = envs.obj_pos(env, "plate_1") + dxy = float(np.linalg.norm(b[:2] - p[:2])) + flat = abs(envs.obj_upright_cos(env, "box_1")) > 0.9 + held = bool(self.sk.holding("box_1")) if self.sk is not None else False + on_plate = envs.contacts_between(env, envs.obj_geom_ids(env, "box_1"), envs.obj_geom_ids(env, "plate_1")) + success = bool(dxy < 0.05 and envs.obj_min_z(env, "box_1") > envs.TABLE_Z + 0.004 and flat and not held + and on_plate) + lifted = mon.get("max_dz", 0.0) > 0.03 + start = mon.get("start_xy", b[:2]) + moved_y = float(b[1] - start[1]) + pushed = (not lifted) and abs(moved_y) > 0.02 + wall_hit, top_hit = mon.get("wall_hit"), mon.get("box_top_hit") + side_txt = "far (+x)" if inst["side"] > 0 else "near (-x)" + mode, parts, wall_left = "success", [], None + if success: + parts.append("The box is resting on the plate.") + else: + if pushed: + parts.append(f"The box was pushed {100 * abs(moved_y):.1f} cm along the wall (towards " + f"{'+y' if moved_y > 0 else '-y'}).") + if lifted: + if held: + mode = "still_held" + parts.append("The box is still in the gripper; it was not released on the plate.") + elif on_plate: + mode = "placed_off" + parts.append(f"The box was put on the plate but is not resting on it properly ({100 * dxy:.1f} cm " + f"from the plate centre{'' if flat else ', tilted'}).") + else: + mode = "placed_off" + parts.append(f"The box was lifted but ended on the table, {100 * dxy:.1f} cm from the plate " + f"centre.") + elif wall_hit is not None: + mode = "wall_blocked" + parts.append( + f"The gripper could not get around the box: the finger on the wall side ({side_txt} side) came down " + f"on top of the wall, {100 * wall_hit['contact_z']:.1f} cm above the table, which is higher than " + f"the top of the box ({200 * BOX_HALF[2]:.1f} cm), so the box was not grasped or lifted. Where the " + f"gripper came down, the box is flush against the wall (gap {1000 * max(wall_hit['gap'], 0):.0f} mm).") + if pushed: + e = 1 if moved_y > 0 else -1 + wall_left = wall_hit["wall_left"][e] + if wall_left > 0: + parts.append(f"The wall still continues {100 * wall_left:.1f} cm beyond the grasp point in the " + f"{'+y' if e > 0 else '-y'} direction.") + else: + parts.append(f"The grasp point was only {100 * -wall_left:.1f} cm past the " + f"{'+y' if e > 0 else '-y'} end of the wall, so the finger still came down on it.") + elif top_hit is not None: + mode = "box_top" + if top_hit["yaw_err"] > np.radians(30): + parts.append(f"The fingers came down on top of the box: along the gripper's closing direction the " + f"box measures {100 * top_hit['span']:.0f} cm, more than the {100 * GRIP_OPEN:.1f} cm " + f"maximum opening. The box was not lifted.") + else: + parts.append(f"A finger came down on top of the box (the gripper was {100 * top_hit['box_offset']:.1f}" + f" cm from the box centre), so the box was not grasped or lifted.") + else: + mode = "not_lifted" + parts.append(f"The box was not lifted; it is {100 * dxy:.1f} cm from the plate centre.") + if b[2] < envs.TABLE_Z - 0.05: + mode = "fell_off" + parts.append("The box fell off the table.") + elif not flat and mode != "placed_off": + parts.append("The box is no longer lying flat.") + out = dict(success=success, mode=mode, plate_dist=dxy, box_xy=[float(b[0]), float(b[1])], lifted=bool(lifted), + pushed_y=moved_y, alongside_wall=self.alongside_wall(), wall_left=wall_left, + terminal=bool(b[2] < envs.TABLE_Z - 0.05), detail=" ".join(parts)) + self._start_monitor() # next segment (within protocol) starts here + return out + + # ------------------------------------------------------------ scripted references + def _nearer_end(self): + o = self.observe() + by = o["box_xy"][1] + return 1 if (o["wall_y"][1] - by) < (by - o["wall_y"][0]) else -1 + + def default_params(self, inst): + return dict(mode="grasp") + + def oracle_params(self, inst): + return dict(mode="push_grasp", end=self._nearer_end(), margin=0.045) + + def blind_params(self, inst, attempt, rng): + return dict(mode="grasp", dx=float(rng.normal(0, 0.008)), dy=float(rng.normal(0, 0.008)), + dyaw=float(rng.normal(0, 0.12))) + + def adapt_params(self, inst, history): + """Uses the F2 measurements of the previous attempt: + wall_blocked / box_top on a direct grasp -> switch mode: slide the box out past the nearer wall end + (wall ends read off the image), then grasp; + wall_blocked after a push -> push further by the reported remaining wall length + 2 cm; + anything else (missed, dropped, ...) -> keep the strategy (the state is re-observed).""" + out, prm = history[-1]["outcome"], history[-1]["params"] + if prm["mode"] != "push_grasp": + if out["mode"] in ("wall_blocked", "box_top"): + return dict(mode="push_grasp", end=self._nearer_end(), margin=0.045) + return dict(prm) + if out["mode"] == "wall_blocked": + return dict(mode="push_grasp", end=prm["end"], + margin=float(prm["margin"] + max(out["wall_left"] or 0.0, 0.0) + 0.02)) + return dict(prm) + + # ------------------------------------------------------------ protocols + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + if self.protocol != "within": + return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt) + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + self.reset_instance(inst) + for a in range(k): + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = self.default_params(inst) if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + else: + raise ValueError(kind) + if params["mode"] == "push_grasp" and not self.alongside_wall(): + params = dict(params, mode="grasp") # already pushed clear in an earlier attempt of this episode + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history + + +@register_task +class WallFlushWithin(WallFlush): + name = "l3_wall_flush_within" + protocol = "within" diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l3_wide.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l3_wide.py new file mode 100644 index 0000000000000000000000000000000000000000..4983d8290676ef823eb1ad9710447698e6bdf2d6 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l3_wide.py @@ -0,0 +1,435 @@ +"""L3-B too_wide_push: a box that is slightly too wide for the gripper must be pushed into a square on the table. + +Why the prior fails: the box looks like an ordinary graspable box (narrow side 8.3-8.9 cm, long side 11-13 cm, +4 cm high), but the Panda's fingers open to only 7.9 cm. A top-down grasp across the narrow side therefore puts +both fingers on top of the box; closing them grips nothing. Across the long side it is worse, and retrying the +same grasp with small variations fails the same way. A difference of 4-10 mm between the box and the maximum +opening is not readable from the camera images, and the agent is not told the gripper's opening. + +What must be learned from the failure: this object cannot be picked up at all -> change the manipulation mode: +close the gripper and push the box (there is no push primitive: the agent closes the gripper, lowers it beside +the box and moves it along the table with move_to), keeping the box from turning, until it lies completely +inside the square. + +Layout (randomised per instance): box size, position and yaw (long side roughly along x or along y, +-10 deg), +target square (18 x 18 cm inner, axis-aligned) 16-22 cm away along one world axis (forward, backward, left or +right) with a lateral offset of up to 3 cm. + +Protocol: cross (reset to the same instance before every attempt), k = 5. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import box_xml, register_generated +from ..skills import DT, _rot_err +from ..task_base import LFFTask, register_task +from .l5_slide import square_frame_xml + +BOX_HALF_MAX = (0.07, 0.05, 0.02) # registered size (x = long, y = narrow, z); shrunk per instance +BOX_HALF_Z = 0.02 # 4 cm high +BOX_MASS = 0.40 +BOX_MU = 0.6 # box sliding friction (priority over the table's 1.0 and the fingers') +GRIP_OPEN = 0.079 # measured distance between the finger pads when fully open +SQ_IN = 0.09 # target square: 18 cm inner side +SQ_LINE = 0.008 +Z_GRASP = envs.TABLE_Z + 0.022 # site height of a normal top-down grasp of a 4 cm box (pads 1.7-3.4 cm above table) +Z_PUSH = envs.TABLE_Z + 0.02 # site height while pushing: finger tips ~1 cm above the table +PUSH_SPEED = 0.08 +FRONT_GAP = 0.03 # where a push stroke starts: this far behind the box face + + +def _wrap_pi(a): + return float((a + np.pi) % (2 * np.pi) - np.pi) + + +def _yaw_of(quat_wxyz): + w, x, y, z = quat_wxyz + return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))) + + +DIRS = {"forward": (1.0, 0.0), "backward": (-1.0, 0.0), "left": (0.0, 1.0), "right": (0.0, -1.0)} + + +@register_task +class TooWidePush(LFFTask): + name = "l3_too_wide_push" + level = "L3" + category = "strategy_switching" + capabilities = ("Perceive", "Reason", "Plan") + protocol = "cross" + instruction = "Put the brown box completely inside the green square marked on the table." + instruction_indirect = "Put the cardboard-coloured package completely inside the green outlined area on the table." + + def __init__(self, cam_res=None): + super().__init__(cam_res) + self._mon = None + self.inst = None + orig_step = self.env.step + + def step(action): # per-control-step event monitor (also sees agent-driven attempts) + ret = orig_step(action) + if self._mon is not None: + self._monitor_step() + return ret + + self.env.step = step + + # ------------------------------------------------------------ scene + def make_bddl(self): + box = register_generated("LffWideBox", box_xml("lff_wide_box", BOX_HALF_MAX, (0.62, 0.45, 0.28, 1.0), + density=500)) + sq = register_generated("LffWideSquare", square_frame_xml("lff_wide_square", inner_half=SQ_IN, line_w=SQ_LINE), + free=False) + objs = [("box_1", box, "box_region", (-0.11, -0.21, -0.09, -0.19))] + fx = [("square_1", sq, "square_region", (-0.01, 0.19, 0.01, 0.21))] + return write_bddl(self.name, self.instruction, objs, fx) + + def _box_geoms(self): + if not hasattr(self, "_bg"): + m = self.env.sim.model + bid = envs.body_id(self.env, "box_1") + self._bg = [g for g in range(m.ngeom) if m.geom_bodyid[g] == bid] + return self._bg + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + while True: + narrow = float(rng.uniform(0.083, 0.089)) + long_ = float(rng.uniform(0.11, 0.13)) + long_axis = str(rng.choice(["x", "y"])) + yaw = (0.0 if long_axis == "x" else np.pi / 2) + float(rng.uniform(-np.radians(10), np.radians(10))) + dname = str(rng.choice(list(DIRS))) + u = np.array(DIRS[dname]) + # half extent of the box along the push direction (box roughly axis aligned) + ext = 0.5 * (long_ if (long_axis == "x") == (dname in ("forward", "backward")) else narrow) + dist = float(rng.uniform(SQ_IN + ext + 0.01, SQ_IN + ext + 0.07)) + lat = float(rng.uniform(-0.03, 0.03)) + box_xy = np.array([rng.uniform(-0.20, 0.04), rng.uniform(-0.20, 0.20)]) + sq_xy = box_xy + u * dist + np.array([-u[1], u[0]]) * lat + # reach: pushing backward needs the hand ~5 cm beyond the box's far face; the arm's reach at table height + # ends around x = 0.05-0.08 (seed 1015 of the first version: hand stalled at x = 0.09, box never moved) + reach_ok = dname != "backward" or box_xy[0] + ext <= -0.01 + if -0.22 <= sq_xy[0] <= 0.06 and -0.20 <= sq_xy[1] <= 0.20 and reach_ok: + return dict(seed=int(seed), box_half=[long_ / 2, narrow / 2], box_yaw=float(yaw), box_xy=box_xy.tolist(), + square_xy=sq_xy.tolist(), direction=dname, long_axis=long_axis) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + for g in self._box_geoms(): + m.geom_size[g, 0], m.geom_size[g, 1] = inst["box_half"] + m.geom_size[g, 2] = BOX_HALF_Z + envs.scale_mass(self.env, "box_1", BOX_MASS) + envs.set_friction(self.env, "box_1", BOX_MU) + sq = self.env.fixtures_dict["square_1"] + for g in range(m.ngeom): + if (m.geom_id2name(g) or "").startswith("square_1_"): + m.geom_contype[g] = 0 + m.geom_conaffinity[g] = 0 + bid = m.body_name2id(sq.root_body) + m.body_pos[bid] = [inst["square_xy"][0], inst["square_xy"][1], envs.TABLE_Z + 0.0002] + m.body_quat[bid] = [1.0, 0.0, 0.0, 0.0] + bx, by = inst["box_xy"] + envs.set_obj_pose(self.env, "box_1", [bx, by, envs.TABLE_Z + BOX_HALF_Z + 0.0005], yaw=inst["box_yaw"]) + + def reset_instance(self, inst, recorder=None): + self._mon = None + sk = super().reset_instance(inst, recorder=recorder) + self._start_monitor() + return sk + + # ------------------------------------------------------------ geometry / perception stand-in + def observe(self): + """What a perfect perceiver reads off the image: box centre, yaw and footprint, square centre.""" + b = envs.obj_pos(self.env, "box_1") + return dict(box_xy=b[:2].copy(), box_yaw=_yaw_of(envs.obj_quat(self.env, "box_1")), + square_xy=np.array(self.inst["square_xy"], float), half=np.array(self.inst["box_half"], float)) + + def corners3d(self): + """the 8 corners of the box (world)""" + d = self.env.sim.data + bid = envs.body_id(self.env, "box_1") + R = d.body_xmat[bid].reshape(3, 3) + h = np.array([self.inst["box_half"][0], self.inst["box_half"][1], BOX_HALF_Z]) + return np.array([d.body_xpos[bid] + R @ (h * [sx, sy, sz]) for sx in (-1, 1) for sy in (-1, 1) + for sz in (-1, 1)]) + + def corners(self, o=None): + """footprint corners (xy) of the box in its current pose (also when it is tilted or on its side)""" + return self.corners3d()[:, :2] + + def protrusion(self, o=None): + """How far the box footprint sticks out beyond each edge of the square (m, >0 = outside).""" + o = o or self.observe() + rel = self.corners(o) - o["square_xy"] + return {"forward": float(rel[:, 0].max() - SQ_IN), "backward": float(-rel[:, 0].min() - SQ_IN), + "left": float(rel[:, 1].max() - SQ_IN), "right": float(-rel[:, 1].min() - SQ_IN)} + + def extent_along(self, u, o=None): + """half extent of the box footprint along the unit xy vector u""" + o = o or self.observe() + c, s = np.cos(o["box_yaw"]), np.sin(o["box_yaw"]) + hx, hy = o["half"] + return float(hx * abs(u @ [c, s]) + hy * abs(u @ [-s, c])) + + # ------------------------------------------------------------ contacts / event monitor + def _groups(self): + if not hasattr(self, "_gg"): + m = self.env.sim.model + fg = {g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_finger")} + robot = set(envs.robot_geom_ids(self.env)) + self._gg = (fg, robot, set(envs.obj_geom_ids(self.env, "box_1"))) + return self._gg + + def _finger_landings(self): + """{'box' | 'table' | 'other': n_fingers} for fingers resting on a top surface (contact normal vertical).""" + m, d = self.env.sim.model, self.env.sim.data + fg, robot, box = self._groups() + out = {} + for i in range(d.ncon): + c = d.contact[i] + if c.geom1 in fg and c.geom2 not in robot: + f, other = c.geom1, c.geom2 + elif c.geom2 in fg and c.geom1 not in robot: + f, other = c.geom2, c.geom1 + else: + continue + if abs(c.frame[2]) < 0.7: + continue + lab = "box" if other in box else ("table" if (m.geom_id2name(other) or "").startswith("table") else "other") + name = m.geom_id2name(f) or "" + out.setdefault(lab, set()).add("1" if "finger1" in name else "2") + return out + + def _closing_axis(self): + m, d = self.env.sim.model, self.env.sim.data + jid = m.joint_name2id(self.env.robots[0].gripper.joints[0]) + a = d.xaxis[jid][:2] + return a / max(np.linalg.norm(a), 1e-9) + + def _start_monitor(self): + b = envs.obj_pos(self.env, "box_1") + self._mon = dict(rest_z=float(b[2]), start_xy=b[:2].copy(), start_yaw=_yaw_of(envs.obj_quat(self.env, "box_1")), + max_dz=0.0, top_hit=None, prev=set(), was_held=False) + + def _monitor_step(self): + mon = self._mon + zmin = float(self.corners3d()[:, 2].min()) + mon["max_dz"] = max(mon["max_dz"], zmin - envs.TABLE_Z) # whole box above the table + hits = self._finger_landings() + open_ = self.sk is not None and self.sk.gripper_width() > 0.03 + if "box" in hits and "box" not in mon["prev"] and open_: # an open gripper landing on the box top = a grasp + o = self.observe() + ca = self._closing_axis() + e = self.env.sim.data.site_xpos[self.env.robots[0].eef_site_id] + mon["top_hit"] = dict(span=2 * self.extent_along(ca, o), n_fingers=len(hits["box"]), + offset=float(np.linalg.norm(e[:2] - o["box_xy"]))) + if "box" in hits and len(hits["box"]) == 2 and mon["top_hit"] is not None and open_: + mon["top_hit"]["n_fingers"] = 2 + mon["prev"] = set(hits) + + # ------------------------------------------------------------ outcome / F2 + def outcome(self, inst): + """Success = the whole box footprint inside the square, box resting on the table, released.""" + envs.settle(self.env, 30) + env, mon = self.env, self._mon or {} + o = self.observe() + b = envs.obj_pos(env, "box_1") + prot = self.protrusion(o) + inside = max(prot.values()) <= 0.0 + upright = abs(envs.obj_upright_cos(env, "box_1")) > 0.9 + held = bool(self.sk.holding("box_1")) if self.sk is not None else False + zmin = float(self.corners3d()[:, 2].min()) + resting = abs(zmin - envs.TABLE_Z) < 0.01 + success = bool(inside and resting and not held) + rel = o["box_xy"] - o["square_xy"] + moved = float(np.linalg.norm(o["box_xy"] - mon.get("start_xy", o["box_xy"]))) + turned = float(np.degrees(_wrap_pi(o["box_yaw"] - mon.get("start_yaw", o["box_yaw"])))) if upright else 0.0 + lifted = mon.get("max_dz", 0.0) > 0.01 + top = mon.get("top_hit") + parts, mode = [], "success" + + def where(): + return (f"its centre is {100 * abs(rel[0]):.1f} cm {'forward' if rel[0] > 0 else 'backward'} and " + f"{100 * abs(rel[1]):.1f} cm {'left' if rel[1] > 0 else 'right'} of the square's centre") + + def sticking(): + return ", ".join(f"{100 * v:.1f} cm beyond the square's {k} edge" for k, v in + sorted(prot.items(), key=lambda kv: -kv[1]) if v > 0.0) + + if success: + parts.append("The box lies completely inside the square.") + elif b[2] < envs.TABLE_Z - 0.05: + mode = "fell_off" + parts.append("The box fell off the table.") + elif held: + mode = "held" + parts.append(f"The box is still held by the gripper; {where()}.") + elif not resting: + mode = "not_resting" + parts.append(f"The box is not resting on the table (it is propped up or tilted); {where()}.") + else: + mode = "outside" + if top is not None and not lifted: + mode = "too_wide" + if top["n_fingers"] >= 2 or top["span"] > GRIP_OPEN: + parts.append(f"The fingers came down on top of the box instead of on either side of it: along the " + f"gripper's closing direction the box measures {100 * top['span']:.1f} cm, wider than " + f"the gripper's maximum opening ({100 * GRIP_OPEN:.1f} cm). The box was not grasped.") + else: + parts.append(f"A finger came down on top of the box (the gripper was {100 * top['offset']:.1f} cm " + f"from the box centre). The box was not grasped.") + if moved < 0.01: + mode = "not_moved" if mode == "outside" else mode + parts.append(f"The box did not move; it sticks out {sticking()}.") + else: + parts.append(f"The box was moved {100 * moved:.1f} cm but is not completely inside the square: it " + f"sticks out {sticking()}; {where()}.") + if abs(turned) >= 5: + rot = "counter-clockwise" if turned > 0 else "clockwise" + parts.append(f"It turned by {abs(turned):.0f} deg ({rot} seen from above).") + if not success and not upright and mode not in ("fell_off",): + parts.append("The box is no longer lying on its large bottom face.") + out = dict(success=success, mode=mode, inside=bool(inside), protrusion=prot, rel=[float(rel[0]), float(rel[1])], + moved=moved, turned_deg=turned, lifted=bool(lifted), held=held, upright=bool(upright), + top_hit_span=None if top is None else float(top["span"]), + terminal=bool(b[2] < envs.TABLE_Z - 0.05), detail=" ".join(parts)) + self._start_monitor() + return out + + # ------------------------------------------------------------ primitives for the scripted policies + def _yaw_near(self, yaw): + cands = [yaw + k * np.pi for k in (-2, -1, 0, 1, 2)] + cands = [c for c in cands if abs(c) <= np.pi / 2 + 0.4] or cands + return float(min(cands, key=lambda c: abs(c - self.sk.yaw))) + + def _align(self, tol=0.03, max_steps=60): + sk = self.sk + for _ in range(max_steps): + R = sk._R() @ sk.eef_mat().T + if np.arccos(np.clip((np.trace(R) - 1) / 2, -1, 1)) < tol: + break + sk.hold(1) + + def _guarded_descent(self, xyz, speed=0.12, max_steps=60): + """descent that stops when a finger lands on a top surface above the target (contact sensing)""" + sk = self.sk + p0 = sk.eef_pos() + tgt = np.asarray(xyz, float) + dist = max(np.linalg.norm(tgt - p0), 1e-6) + R = sk._R() + for k in range(max_steps): + ref = p0 + (tgt - p0) * min(1.0, (k + 1) * speed * DT / dist) + sk._act(ref - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip) + if self._finger_landings() and sk.eef_pos()[2] > tgt[2] + 0.005: + break + if np.linalg.norm(tgt - sk.eef_pos()) < 0.003: + break + sk.hold(4) + + def _finger_front(self, direction): + m, d = self.env.sim.model, self.env.sim.data + e = self.sk.eef_pos() + best = 0.0 + for g in range(m.ngeom): + if not (m.geom_id2name(g) or "").startswith("gripper0_finger") or m.geom_type[g] != 7: + continue + mid = m.geom_dataid[g] + v = m.mesh_vert[m.mesh_vertadr[mid]:m.mesh_vertadr[mid] + m.mesh_vertnum[mid]] + w = v @ d.geom_xmat[g].reshape(3, 3).T + d.geom_xpos[g] - e + best = max(best, float((w[:, :2] @ direction).max())) + return best + + def grasp_and_place(self, dx=0.0, dy=0.0, dyaw=0.0, across="narrow"): + """Top-down grasp across the box's narrow side at its centre (+ offsets); if it is held, put it in the square.""" + sk, o = self.sk, self.observe() + gx, gy = o["box_xy"][0] + dx, o["box_xy"][1] + dy + # yaw 0 closes along world y; to close across the narrow side (box local y) use the box yaw + yaw = self._yaw_near(o["box_yaw"] + (0.0 if across == "narrow" else np.pi / 2) + dyaw) + sk.set_gripper(False, steps=8) + sk.move_to([gx, gy, Z_GRASP + 0.10], yaw=yaw) + self._align() + self._guarded_descent([gx, gy, Z_GRASP]) + sk.set_gripper(True, steps=15) + z0 = envs.obj_pos(self.env, "box_1")[2] + sk.move_to([gx, gy, Z_GRASP + 0.12], speed=0.25) + if not (sk.holding("box_1") and envs.obj_pos(self.env, "box_1")[2] > z0 + 0.06): + sk.set_gripper(False, steps=8) + return + sx, sy = o["square_xy"] + sk.move_to([sx, sy, Z_GRASP + 0.12]) + sk.move_to([sx, sy, Z_GRASP + 0.005]) + sk.set_gripper(False, steps=12) + sk.move_to([sx, sy, Z_GRASP + 0.12]) + + def push_stroke(self, u, dist): + """Closed gripper behind the box face opposite to u (fingers side by side across the push direction), sweep + along u so that the box moves `dist`, then lift away. Built from move_to + close only.""" + sk, o = self.sk, self.observe() + u = np.asarray(u, float) / np.linalg.norm(u) + c = o["box_xy"] + ext = self.extent_along(u, o) + yaw = self._yaw_near(float(np.arctan2(u[1], u[0]))) # yaw a: closing axis along (-sin a, cos a), i.e. across u + sk.set_gripper(True, steps=6) + face = c - u * ext + p_hi = face - u * 0.08 + sk.move_to([p_hi[0], p_hi[1], Z_PUSH + 0.10], yaw=yaw) + self._align() + front = self._finger_front(u) + start = face - u * (front + FRONT_GAP) + stop = face + u * (dist - front) + sk.move_to([start[0], start[1], Z_PUSH + 0.10]) + sk.move_to([start[0], start[1], Z_PUSH], tol=0.003) + sk.move_to([stop[0], stop[1], Z_PUSH], speed=PUSH_SPEED, tol=0.004, max_steps=400) + sk.hold(3) + back = stop - u * 0.02 + sk.move_to([back[0], back[1], Z_PUSH], speed=0.1, max_steps=40) + sk.move_to([back[0], back[1], Z_PUSH + 0.10], speed=0.25) + + def push_to(self, goal_xy, max_strokes=4, tol=0.008): + """Closed-loop push along the box's own axes (each stroke perpendicular to a face keeps the box from turning): + re-observe after every stroke, push along the axis with the larger remaining error.""" + for _ in range(max_strokes): + o = self.observe() + d = np.asarray(goal_xy, float) - o["box_xy"] + c, s = np.cos(o["box_yaw"]), np.sin(o["box_yaw"]) + axes = [np.array([c, s]), np.array([-s, c])] + comps = [float(d @ a) for a in axes] + i = int(np.argmax(np.abs(comps))) + if abs(comps[i]) < tol: + break + u = axes[i] * np.sign(comps[i]) + self.push_stroke(u, abs(comps[i])) + + def execute(self, inst, params): + if params["mode"] == "push": + goal = np.array(inst["square_xy"]) + np.asarray(params.get("goal_offset", (0.0, 0.0))) + self.push_to(goal, max_strokes=params.get("strokes", 4)) + else: + self.grasp_and_place(params.get("dx", 0.0), params.get("dy", 0.0), params.get("dyaw", 0.0), + params.get("across", "narrow")) + + # ------------------------------------------------------------ scripted references + def default_params(self, inst): + return dict(mode="grasp") + + def oracle_params(self, inst): + return dict(mode="push") + + def blind_params(self, inst, attempt, rng): + return dict(mode="grasp", dx=float(rng.normal(0, 0.008)), dy=float(rng.normal(0, 0.008)), + dyaw=float(rng.normal(0, 0.15))) + + def adapt_params(self, inst, history): + """too_wide (fingers on top of the box, span > opening) -> the box cannot be picked up: push it instead. + A push that leaves the box outside -> push again, aiming past the reported miss (box centre offset).""" + out, prm = history[-1]["outcome"], history[-1]["params"] + if prm["mode"] != "push": + if out["mode"] in ("too_wide", "not_moved"): + return dict(mode="push") + return dict(prm) + if out["mode"] == "outside": + off = np.asarray(prm.get("goal_offset", (0.0, 0.0))) - 0.5 * np.asarray(out["rel"]) + return dict(mode="push", goal_offset=off.tolist()) + return dict(prm) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l4_diagonal.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l4_diagonal.py new file mode 100644 index 0000000000000000000000000000000000000000..684ff8c0dcfa6eb30284e0594ecef678d04a733b --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l4_diagonal.py @@ -0,0 +1,524 @@ +"""L4-B diagonal_fit: put a long bar flat into an open box whose inside is shorter than the bar. + +Scene: one open box (inner a x b, a slightly longer than b, 3 cm walls) and a long, thin wooden bar +(L x 1.2 x 1.4 cm) lying on the table in front of it. The bar is 1.2-2.2 cm longer than the box's inside +length, so it never fits lined up with a side of the box -- it fits only when turned towards the box's +diagonal, at an angle that depends on a, b and L (36-45 deg off the long side; the fitting window at zero +centring error is 12-25 deg wide, see task card). + +Hidden: the exact dimensions (the bar is only 8-17 % longer than the box -- easy to miss at a glance), and +that a diagonal placement exists. Box and bar are resized per instance by editing geom sizes in sim.model, +so one env serves every instance (same technique as l4_fit_container). + +Prior (naive): tidy placement -- line the bar up with the box's long side. It always ends lying across the +box on the rim (visible). F2 after a failure: where the bar lies, the angle between bar and box, and by how +much the bar's footprint at that angle is longer than the inside of the box along the box's long / short +side. A learner can work out the bar length from that and turn the bar towards the diagonal; a second +failure (angle slightly off) gives the over-length along the other side, which tells it which way to correct. + +Only move_to / open / close are needed: grasp the bar in the middle, turn the wrist, release above the box. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import bin_xml, box_xml, register_generated +from ..skills import _rot_err +from ..task_base import LFFTask, register_task + +# bar (local x = long axis); length set per instance +BAR_W, BAR_H = 0.012, 0.014 +BAR_L_MAX = 0.160 +BAR_RGBA = (0.72, 0.36, 0.14, 1.0) +# box (local x = long axis of the opening); inner size set per instance +WALL_T, FLOOR_T, WALL_H = 0.006, 0.006, 0.030 +BOX_HALF_H = (WALL_H + FLOOR_T) / 2 # body origin at mid height +RIM_Z = envs.TABLE_Z + FLOOR_T + WALL_H +BOX_RGBA = (0.55, 0.62, 0.70, 1.0) +# sampling ranges (m) +INNER_A = (0.115, 0.130) # inside length of the box +A_MINUS_B = (0.004, 0.020) # the box is a little longer than wide +OVER_LEN = (0.010, 0.020) # bar length minus inside length of the box +MIN_MARGIN = 0.011 # best-angle clearance (total) the sampler insists on +MIN_WINDOW_DEG = 8.0 # width of the angle window with >= 6 mm total clearance +# execution +Z_GRASP = envs.TABLE_Z + 0.0105 # gripper site; pads span ~0.55-2.25 cm above the table, tips just clear it +Z_CARRY = envs.TABLE_Z + 0.15 +DROP = 0.010 # bar bottom this far above the rim at release +PARK = (-0.45, 0.0, envs.TABLE_Z + 0.35) +PERC_SIGMA = 0.003 # perception noise of the scripted adaptive learner (box inner size, bar width) + + +MIDPHASE_OFF = True + + +def disable_midphase(env): + """Box and bar are resized at run time by editing geom pos / size in sim.model, but MuJoCo's per-body bounding + volume hierarchy (bvh_aabb, used by the collision mid-phase) is computed once at compile time for the registered + size. A box wall moved inwards out of its compiled leaf box is silently skipped by the mid-phase (found on the + nest_order cups, 2026-10-07: the fingers passed through resized walls). Without the mid-phase MuJoCo tests all + geom pairs of two nearby bodies (still filtered by the run-time geom_rbound set when resizing).""" + import mujoco + m = env.sim.model._model + m.opt.disableflags |= int(mujoco.mjtDisableBit.mjDSBL_MIDPHASE) + + +def wrap_half(a): + """angle modulo pi into [-pi/2, pi/2) (bar and box are 180-deg symmetric)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def fold_quarter(a): + """|angle| between two pi-symmetric axes, in [0, pi/2]""" + a = abs(wrap_half(a)) + return float(min(a, np.pi - a)) + + +def footprint(L, W, rel): + """extent of an L x W rectangle turned by rel against the box axes: (along long side, along short side)""" + c, s = abs(np.cos(rel)), abs(np.sin(rel)) + return L * c + W * s, L * s + W * c + + +def margins(L, W, a, b, rel): + e1, e2 = footprint(L, W, rel) + return a - e1, b - e2 + + +def best_angle(L, W, a, b, n=1801): + """angle in [0, pi/2] maximising the smaller of the two clearances; returns (angle, clearance, window)""" + th = np.linspace(0.0, np.pi / 2, n) + m1, m2 = margins(L, W, a, b, th) + m = np.minimum(m1, m2) + i = int(np.argmax(m)) + ok = th[m >= 0.006] + win = float(np.degrees(ok.max() - ok.min())) if len(ok) else 0.0 + return float(th[i]), float(m[i]), win + + +def _rect_corners(xy, yaw, half): + c, s = np.cos(yaw), np.sin(yaw) + R = np.array([[c, -s], [s, c]]) + pts = np.array([[1, 1], [1, -1], [-1, -1], [-1, 1]]) * np.asarray(half) + return pts @ R.T + np.asarray(xy) + + +def _rects_overlap(r1, r2): + c1, c2 = _rect_corners(*r1), _rect_corners(*r2) + for yaw in (r1[1], r1[1] + np.pi / 2, r2[1], r2[1] + np.pi / 2): + ax = np.array([np.cos(yaw), np.sin(yaw)]) + p1, p2 = c1 @ ax, c2 @ ax + if p1.max() < p2.min() or p2.max() < p1.min(): + return False + return True + + +def _rel_dir(dx, dy): + """robot-centric text for an offset in the world frame (forward = +x, left = +y), ending in 'of' / 'from'""" + parts = [] + if abs(dx) >= 0.005: + parts.append(f"{100 * abs(dx):.1f} cm {'forward' if dx > 0 else 'backward'}") + if abs(dy) >= 0.005: + parts.append(f"{100 * abs(dy):.1f} cm to the {'left' if dy > 0 else 'right'}") + return " and ".join(parts) + " of" if parts else "within 0.5 cm of" + + +def _turn_text(signed_deg): + """relative orientation of the bar against the box's long side (no absolute angles)""" + if abs(signed_deg) < 2.0: + return "lies along the box's long side (within 2 degrees)" + side = "counterclockwise (towards the left)" if signed_deg > 0 else "clockwise (towards the right)" + return f"is turned about {abs(signed_deg):.0f} degrees {side}, seen from above, from the box's long side" + + +@register_task +class DiagonalFit(LFFTask): + name = "l4_diagonal_fit" + level = "L4" + category = "geometry_inference" + capabilities = ("Perceive", "Reason") + instruction = "Put the wooden bar into the box so that it lies flat on the bottom of the box." + instruction_indirect = "Put the long brown stick into the grey open tray so that it lies flat on the tray's floor." + + # ------------------------------------------------------------ scene + def make_bddl(self): + bar = register_generated("LffDiagBar", box_xml("lff_diag_bar", (BAR_L_MAX / 2, BAR_W / 2, BAR_H / 2), + BAR_RGBA, density=700)) + box = register_generated("LffDiagBox", bin_xml("lff_diag_box", (0.065, 0.065), WALL_H, wall_t=WALL_T, + floor_t=FLOOR_T, rgba=BOX_RGBA, density=3000)) + objs = [("bar_1", bar, "bar_region", (0.02, -0.01, 0.04, 0.01)), + ("box_1", box, "box_region", (-0.19, -0.01, -0.17, 0.01))] + return write_bddl(self.name, self.instruction, objs) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + for _ in range(1000): + a = float(rng.uniform(*INNER_A)) + b = float(a - rng.uniform(*A_MINUS_B)) + L = float(a + rng.uniform(*OVER_LEN)) + th, m, win = best_angle(L, BAR_W, a, b) + if m < MIN_MARGIN or win < MIN_WINDOW_DEG: + continue + box_xy = [float(rng.uniform(-0.22, -0.13)), float(rng.uniform(-0.10, 0.10))] + box_yaw = float(rng.uniform(-np.pi / 4, np.pi / 4)) + bar_xy = [float(rng.uniform(-0.01, 0.05)), float(rng.uniform(-0.13, 0.13))] + bar_yaw = float(rng.uniform(-np.pi / 2, np.pi / 2)) + r_box = (box_xy, box_yaw, (a / 2 + WALL_T + 0.03, b / 2 + WALL_T + 0.03)) + r_bar = (bar_xy, bar_yaw, (L / 2 + 0.01, BAR_W / 2 + 0.03)) + if _rects_overlap(r_box, r_bar): + continue + break + else: + raise RuntimeError("could not sample an instance") + prng = np.random.default_rng(seed + 7919) + perc = [float(a + prng.normal(0, PERC_SIGMA)), float(b + prng.normal(0, PERC_SIGMA)), + float(BAR_W + prng.normal(0, PERC_SIGMA / 2))] + return dict(seed=int(seed), inner=[a, b], bar_len=L, bar_xy=bar_xy, bar_yaw=bar_yaw, box_xy=box_xy, + box_yaw=box_yaw, fit_angle_deg=float(np.degrees(th)), fit_margin_cm=float(100 * m), + fit_window_deg=win, _perc=perc) + + def _reshape_box(self, a, b): + ix, iy, H = a / 2, b / 2, BOX_HALF_H + parts = [((0, 0, -H + FLOOR_T / 2), (ix + WALL_T, iy + WALL_T, FLOOR_T / 2)), + ((ix + WALL_T / 2, 0, FLOOR_T / 2), (WALL_T / 2, iy + WALL_T, WALL_H / 2)), + ((-ix - WALL_T / 2, 0, FLOOR_T / 2), (WALL_T / 2, iy + WALL_T, WALL_H / 2)), + ((0, iy + WALL_T / 2, FLOOR_T / 2), (ix, WALL_T / 2, WALL_H / 2)), + ((0, -iy - WALL_T / 2, FLOOR_T / 2), (ix, WALL_T / 2, WALL_H / 2))] + m = self.env.sim.model + o = self.env.objects_dict["box_1"] + for names in (o.contact_geoms, o.visual_geoms): + assert len(names) == len(parts), names + for k, n in enumerate(names): + g = m.geom_name2id(n) + pos, size = parts[k] + m.geom_pos[g] = pos + m.geom_size[g] = size + m.geom_rbound[g] = float(np.linalg.norm(size)) + m.geom_aabb[g] = [0, 0, 0, *size] + + def _resize_bar(self, L): + m = self.env.sim.model + o = self.env.objects_dict["bar_1"] + for n in list(o.contact_geoms) + list(o.visual_geoms): + g = m.geom_name2id(n) + m.geom_size[g] = [L / 2, BAR_W / 2, BAR_H / 2] + m.geom_rbound[g] = float(np.linalg.norm(m.geom_size[g])) + m.geom_aabb[g] = [0, 0, 0, *m.geom_size[g]] + # keep the mass of the resized bar consistent with its volume (density 700); the geoms live in the + # child body "object", not in the root body that carries the free joint + bid = int(m.geom_bodyid[m.geom_name2id(o.contact_geoms[0])]) + mass = 700.0 * L * BAR_W * BAR_H + m.body_mass[bid] = mass + m.body_inertia[bid] = mass / 12.0 * np.array([BAR_W ** 2 + BAR_H ** 2, L ** 2 + BAR_H ** 2, + L ** 2 + BAR_W ** 2]) + + def apply_instance(self, inst): + if MIDPHASE_OFF: + disable_midphase(self.env) + self._reshape_box(*inst["inner"]) + self._resize_bar(inst["bar_len"]) + envs.set_obj_pose(self.env, "box_1", [*inst["box_xy"], envs.TABLE_Z + BOX_HALF_H + 0.0005], + yaw=inst["box_yaw"]) + envs.set_obj_pose(self.env, "bar_1", [*inst["bar_xy"], envs.TABLE_Z + BAR_H / 2 + 0.0005], + yaw=inst["bar_yaw"]) + + # ------------------------------------------------------------ outcome + def _pose(self, name): + bid = envs.body_id(self.env, name) + R = self.env.sim.data.body_xmat[bid].reshape(3, 3) + return self.env.sim.data.body_xpos[bid].copy(), R + + def outcome(self, inst): + envs.settle(self.env, 40) + a, b = inst["inner"] + L = inst["bar_len"] + p, R = self._pose("bar_1") + ax = R[:, 0] + bar_yaw = float(np.arctan2(ax[1], ax[0])) + tilt = float(np.degrees(np.arcsin(min(1.0, abs(ax[2]))))) # long axis vs horizontal + c, Rb = self._pose("box_1") + byaw = float(np.arctan2(Rb[1, 0], Rb[0, 0])) + btilt = float(np.degrees(np.arccos(np.clip(Rb[2, 2], -1, 1)))) + held = bool(self.sk is not None and self.sk.holding("bar_1")) + rel = fold_quarter(bar_yaw - byaw) + # bar footprint corners in the box frame + Rz = np.array([[np.cos(byaw), np.sin(byaw)], [-np.sin(byaw), np.cos(byaw)]]) + corners = _rect_corners(p[:2], bar_yaw, (L / 2 * np.cos(np.radians(tilt)), BAR_W / 2)) + loc = (corners - c[:2]) @ Rz.T + out_x = float(np.max(np.abs(loc[:, 0])) - a / 2) + out_y = float(np.max(np.abs(loc[:, 1])) - b / 2) + centre = Rz @ (p[:2] - c[:2]) + floor_top = c[2] - BOX_HALF_H + FLOOR_T + height = float(envs.obj_min_z(self.env, "bar_1") - floor_top) + in_opening = out_x <= 0.002 and out_y <= 0.002 + on_floor = height < 0.005 and tilt < 6.0 + success = bool(in_opening and on_floor and not held and btilt < 10.0) + m_long, m_short = margins(L, BAR_W, a, b, rel) + fb = dict(rel_deg=round(float(np.degrees(rel)), 1), + over_long_cm=round(-100 * m_long, 1) if m_long < -0.001 else None, + over_short_cm=round(-100 * m_short, 1) if m_short < -0.001 else None, + spare_long_cm=round(100 * max(m_long, 0.0), 1) if m_long >= -0.001 else None, + spare_short_cm=round(100 * max(m_short, 0.0), 1) if m_short >= -0.001 else None, + centre_offset_cm=[round(100 * float(centre[0]), 1), round(100 * float(centre[1]), 1)]) + res = dict(success=success, height_cm=round(100 * height, 2), tilt_deg=round(tilt, 1), held=held, + rel_deg=fb["rel_deg"], bar_xy=[float(p[0]), float(p[1])], feedback=fb) + signed = float(np.degrees(wrap_half(bar_yaw - byaw))) + fb["rel_signed_deg"] = round(signed, 1) + off_w = p[:2] - c[:2] # bar centre relative to the box centre, world axes (only relative values are reported) + if held: + res["detail"] = "The bar is still in the gripper." + res["failure"] = "held" + return res + over_box = abs(centre[0]) < a / 2 + WALL_T and abs(centre[1]) < b / 2 + WALL_T + on_table = envs.obj_min_z(self.env, "bar_1") < envs.TABLE_Z + 0.008 # (floor_top is FLOOR_T above the table) + if not over_box and on_table: + res["detail"] = (f"The bar is not in the box: it is lying on the table, its centre " + f"{_rel_dir(*off_w)} the box's centre.") + res["failure"] = "table" + return res + if success: + res["detail"] = "The bar is lying flat on the bottom of the box." + res["failure"] = None + return res + if not over_box: + res["detail"] = (f"The bar is not in the box: it ended partly on the box's rim, " + f"{100 * (p[2] - envs.TABLE_Z):.1f} cm above the table, its centre " + f"{_rel_dir(*off_w)} the box's centre.") + res["failure"] = "off" + return res + pose_txt = (f"lying across the top of the box on its rim, {100 * height:.1f} cm above the box floor" + if tilt < 6.0 else + f"tilted about {tilt:.0f} degrees, with one end down inside the box and the other end on the rim") + txt = f"The bar did not go in: it is {pose_txt}. The bar {_turn_text(signed)}." + parts = [] + if fb["over_long_cm"]: + parts.append(f"{fb['over_long_cm']:.1f} cm longer than the inside of the box along the box's long side") + if fb["over_short_cm"]: + parts.append(f"{fb['over_short_cm']:.1f} cm longer than the inside of the box along the box's short side") + if parts: + txt += " At that angle the bar's footprint is " + " and ".join(parts) + "." + else: + txt += (f" At that angle the bar's footprint is smaller than the opening (spare {fb['spare_long_cm']:.1f} cm " + f"along the long side, {fb['spare_short_cm']:.1f} cm along the short side), but it caught on the " + f"rim (bar centre {_rel_dir(*off_w)} the box's centre).") + res["detail"] = txt + res["failure"] = "rim" + return res + + # ------------------------------------------------------------ execution + def execute(self, inst, params): + """params: rel_yaw (rad) = angle of the bar's long axis against the box's long side at release. + Optional (tolerance checks): dx / dy release offset of the bar centre from the box centre along the + box's long / short axis (m); drop = bar bottom above the rim at release (m).""" + sk, env = self.sk, self.env + px, py = inst["bar_xy"] + g0 = wrap_half(inst["bar_yaw"]) # yaw 0 closes the fingers along world y = across a bar lying along x + sk.set_gripper(False, steps=5) + sk.move_to([px, py, Z_GRASP + 0.10], yaw=g0) + sk.move_to([px, py, Z_GRASP], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([px, py, Z_CARRY], speed=0.25) + byaw = inst["box_yaw"] + c, s = np.cos(byaw), np.sin(byaw) + dx, dy = params.get("dx", 0.0), params.get("dy", 0.0) + bx, by = inst["box_xy"][0] + c * dx - s * dy, inst["box_xy"][1] + s * dx + c * dy + sk.move_to([bx, by, Z_CARRY], yaw=wrap_half(byaw + params["rel_yaw"])) + off = envs.obj_pos(env, "bar_1") - sk.eef_pos() + drop = params.get("drop", DROP) + sk.move_to([bx - off[0], by - off[1], RIM_Z + drop + BAR_H / 2 + 0.04 - off[2]], tol=0.003) + tgt = self._servo_bar([bx, by], RIM_Z + drop) + sk.grip = -1.0 + self._hold_at(tgt, 12) + sk.move_to([tgt[0], tgt[1], RIM_Z + 0.10]) + sk.move_to(list(PARK), yaw=0.0) + + def _hold_at(self, target, steps): + sk = self.sk + R = sk._R() + for _ in range(steps): + sk._act(np.asarray(target) - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip) + + def _servo_bar(self, xy, z_bottom, max_steps=60, tol=0.0015): + """closed loop on the held bar's centre (scripted policies only)""" + sk = self.sk + R = sk._R() + goal = np.array([xy[0], xy[1], z_bottom + BAR_H / 2]) + tgt = e_prev = sk.eef_pos() + for i in range(max_steps): + pb, e = envs.obj_pos(self.env, "bar_1"), sk.eef_pos() + if i >= 8 and np.linalg.norm(pb - goal) < tol and np.linalg.norm(e - e_prev) < 0.0005: + break + tgt = goal - (pb - e) + sk._act(tgt - e, _rot_err(R, sk.eef_mat()), sk.grip) + e_prev = e + return tgt + + # ------------------------------------------------------------ scripted policies + def _signed(self, inst, th): + """+th or -th, whichever needs the smaller wrist turn from the bar's current orientation""" + cur = wrap_half(inst["bar_yaw"] - inst["box_yaw"]) + return min((th, -th), key=lambda t: abs(wrap_half(t - cur))) + + def default_params(self, inst): + """tidy prior: bar lined up with the box's long side""" + return dict(rel_yaw=0.0) + + def oracle_params(self, inst): + return dict(rel_yaw=self._signed(inst, np.radians(inst["fit_angle_deg"]))) + + def blind_params(self, inst, attempt, rng): + """no history: the prior again with a little jitter in angle and position""" + return dict(rel_yaw=float(rng.normal(0.0, np.radians(4.0))), dx=float(rng.normal(0, 0.003)), + dy=float(rng.normal(0, 0.003))) + + def adapt_params(self, inst, history): + """Scripted learner on F2 feedback. + + Knows the box's inner size and the bar's width only through noisy perception (inst['_perc'], + sigma = PERC_SIGMA), not the bar's length. Every 'X cm longer than the inside along the long / short side + at angle d' gives an equation for the bar length L (L cos d + W sin d = a + X, or L sin d + W cos d = b + X); + 'spare' values give the same with a negative X. It takes the largest length estimate (conservative) and turns + the bar to the angle with the largest clearance for that length; if the last attempt was already at a + feasible angle and only missed the centre, it keeps the angle.""" + a, b, W = inst["_perc"] + Ls = [] + for h in history: + fb = h["outcome"].get("feedback") or {} + if h["outcome"].get("failure") != "rim": + continue + d = np.radians(fb["rel_deg"]) + c, s = np.cos(d), np.sin(d) + if c > 0.3: + x = fb["over_long_cm"] if fb["over_long_cm"] is not None else -fb["spare_long_cm"] + Ls.append((a + x / 100 - W * s) / c) + if s > 0.3: + x = fb["over_short_cm"] if fb["over_short_cm"] is not None else -fb["spare_short_cm"] + Ls.append((b + x / 100 - W * c) / s) + L_est = max(Ls) if Ls else a + 0.015 + th, m, _ = best_angle(L_est, W, a, b) + return dict(rel_yaw=self._signed(inst, th), L_est=float(L_est)) + + def random_yaw_params(self, inst, history, rng): + """sensitivity variant: a random orientation each retry, no history""" + return dict(rel_yaw=float(rng.uniform(-np.pi / 2, np.pi / 2))) + + EXTRA_KINDS = ("random_yaw",) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + if kind not in self.EXTRA_KINDS: + return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt) + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + params = self.default_params(inst) if a == 0 else self.random_yaw_params(inst, history, rng) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"]: + break + return history + + +# ---------------------------------------------------------------- physical validity checks +def physics_check(seed0=1000, n=10, out=None): + """Release angles 0 / 90 deg (must fail), +-best angle (must succeed) and best +- 6 deg (report).""" + import json + task = DiagonalFit() + rows = [] + for seed in range(seed0, seed0 + n): + inst = task.sample_instance(seed) + th = np.radians(inst["fit_angle_deg"]) + for name, rel, expect in [("aligned", 0.0, False), ("crossed", np.pi / 2, False), ("best+", th, True), + ("best-", -th, True), ("best-6", th - np.radians(6), None), + ("best+6", th + np.radians(6), None)]: + task.reset_instance(inst) + task.execute(inst, dict(rel_yaw=float(rel))) + o = task.outcome(inst) + rows.append(dict(seed=seed, case=name, rel_deg=float(np.degrees(rel)), success=o["success"], expect=expect, + failure=o["failure"], height_cm=o["height_cm"], tilt_deg=o["tilt_deg"], detail=o["detail"], + inner_cm=[round(100 * v, 2) for v in inst["inner"]], bar_cm=round(100 * inst["bar_len"], 2), + fit_margin_cm=round(inst["fit_margin_cm"], 2), fit_window_deg=round(inst["fit_window_deg"], 1))) + flag = "" if expect is None or expect == o["success"] else " <-- MISMATCH" + print(f"seed {seed} {name:8s} rel={np.degrees(rel):+6.1f} succ={o['success']} h={o['height_cm']} " + f"tilt={o['tilt_deg']} margin={inst['fit_margin_cm']:.2f}cm win={inst['fit_window_deg']:.1f}{flag}", + flush=True) + if out: + with open(out, "w") as f: + json.dump(rows, f, indent=1) + bad = [r for r in rows if r["expect"] is not None and r["expect"] != r["success"]] + print("total", len(rows), "mismatches", len(bad)) + return rows + + +def window_check(seed0=1000, n=6, out=None): + """Release angle swept around the best angle (-16..+16 deg, step 2), bar centred: the physical fitting window + against the geometric clearance.""" + import json + task = DiagonalFit() + rows = [] + for seed in range(seed0, seed0 + n): + inst = task.sample_instance(seed) + th = inst["fit_angle_deg"] + L, (a, b) = inst["bar_len"], inst["inner"] + for d in range(-16, 17, 2): + rel = np.radians(th + d) + task.reset_instance(inst) + task.execute(inst, dict(rel_yaw=float(rel))) + o = task.outcome(inst) + m1, m2 = margins(L, BAR_W, a, b, rel) + rows.append(dict(seed=seed, d_deg=d, rel_deg=round(th + d, 1), success=o["success"], + clearance_mm=round(1000 * float(min(m1, m2)), 1))) + print(f"seed {seed} best={th:.1f} " + " ".join(f"{r['d_deg']:+d}:{'S' if r['success'] else '.'}" + for r in rows if r["seed"] == seed), flush=True) + if out: + with open(out, "w") as f: + json.dump(rows, f, indent=1) + return rows + + +def robustness_check(seed0=1000, n=6, out=None): + """Execution errors at the best angle: release off-centre along the box's long / short axis, angle off by + +-4 / +-8 deg, released 3 cm above the rim.""" + import json + task = DiagonalFit() + rows = [] + cases = [("best", {}), ("dx4", dict(dx=0.004)), ("dy4", dict(dy=0.004)), ("dx7", dict(dx=0.007)), + ("dy7", dict(dy=0.007)), ("ang+4", dict(dang=4)), ("ang-4", dict(dang=-4)), ("ang+8", dict(dang=8)), + ("ang-8", dict(dang=-8)), ("drop3cm", dict(drop=0.03)), ("dx4_ang4_drop3", dict(dx=0.004, dang=4, drop=0.03))] + for seed in range(seed0, seed0 + n): + inst = task.sample_instance(seed) + th = inst["fit_angle_deg"] + for name, c in cases: + params = dict(rel_yaw=float(np.radians(th + c.get("dang", 0)))) + params.update({k: v for k, v in c.items() if k != "dang"}) + task.reset_instance(inst) + task.execute(inst, params) + o = task.outcome(inst) + rows.append(dict(seed=seed, case=name, success=o["success"], detail=o["detail"], + fit_margin_cm=round(inst["fit_margin_cm"], 2))) + print(f"seed {seed} {name:15s} succ={o['success']} | {o['detail'][:160]}", flush=True) + if out: + with open(out, "w") as f: + json.dump(rows, f, indent=1) + for name, _ in cases: + r = [x["success"] for x in rows if x["case"] == name] + print(f"{name:15s} {sum(r)}/{len(r)}") + return rows + + +if __name__ == "__main__": + # python -m lffbench.tasks.l4_diagonal physics results/l4_diagonal_fit/physics_check.json + import sys + # python -m lffbench.tasks.l4_diagonal window results/l4_diagonal_fit/window_check.json + # python -m lffbench.tasks.l4_diagonal robust results/l4_diagonal_fit/robustness_check.json + if sys.argv[1] == "physics": + physics_check(out=sys.argv[2] if len(sys.argv) > 2 else None, + n=int(sys.argv[3]) if len(sys.argv) > 3 else 10) + elif sys.argv[1] == "window": + window_check(out=sys.argv[2] if len(sys.argv) > 2 else None, n=int(sys.argv[3]) if len(sys.argv) > 3 else 6) + elif sys.argv[1] == "robust": + robustness_check(out=sys.argv[2] if len(sys.argv) > 2 else None, n=int(sys.argv[3]) if len(sys.argv) > 3 else 6) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l4_fit.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l4_fit.py new file mode 100644 index 0000000000000000000000000000000000000000..7465485d3e907ad579bc46be98782eb8c5efad3a --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l4_fit.py @@ -0,0 +1,574 @@ +"""L4-A fit_container: put the phone flat inside the one box it fits into. + +v3 (2026-10-08, user review of cla2): in v2 the only hidden information was which box is big enough, and box and +phone sizes are visible: all 4 Sonnet runs compared the sizes in the images and chose the right box first time. +v3 makes the phone itself bigger than it looks: it wears clear bumper caps on both ends (collision only, nothing is +rendered), CAP_RANGE = 0.8-0.9 cm each, so it is 1.6-1.8 cm longer than the visible phone. The box sizes are drawn +against the VISIBLE phone so that the boxes that look roomiest are too short for the capped phone: + fit visible margin +2.8..3.2 cm along the phone's length, only +0.8..0.9 cm across (looks tight), + snug +1.15..1.25 cm along, +2.5..3.0 cm across: the most comfortable-looking box, too short with the caps, + short_wide +0.3..0.6 cm along, +3..4 cm across: the biggest box, too short with the caps, + narrow_long +3.5..4.0 cm along but 0.3..0.6 cm too narrow, + small 0.5..1.0 cm too short. +A phone that does not fit lies on the rim of the box (or tips in at one end), visibly not inside, although in the +images it looks shorter than the opening. What has to be learned from that: the phone needs more length than it +appears to (by about the overlap seen) -> the box with the most length to spare. + +The text below is the v2 description (layout, execution, feedback) and still applies, with "phone length" read as +the capped length. v2 is kept in l4_fit.py.bak-20261008-height. + +v2 description: + +Scene: a dark "phone" (14.0 x 6.8 x 1.2 cm) lies in the front row of a 2 x 3 grid of slots; five open +boxes of the same colour and the same height fill the other five slots (inner sizes: see INNER_RANGES): + fit inner = phone + 1.0-1.5 cm in both directions (phone long side along box long side), + short_wide 0.5-1.5 cm too short but 3.5-5 cm wider than the phone (looks biggest), + narrow_long 0.5-1.5 cm too narrow but 2.5-3.5 cm longer than the phone (the longest), + small 0.5-1.2 cm too short and 0.3-0.6 cm too narrow (most phone-like proportions), + short 0.8-2.0 cm too short, as wide as the fitting box. +Each box is either roughly lined up with the phone's current long axis or roughly perpendicular to it +(+-15 deg jitter), independently with p = 0.5 -- so half of the time the fitting box needs the phone to be +turned by ~90 deg. + +Hidden: which box fits (only careful size comparison reveals it -- the boxes look alike), and whether the +fitting box needs the phone rotated. Box sizes are rebuilt per instance by resizing the bin geoms in +sim.model, so a single env serves every instance. + +Prior (naive): take the nearest box and line the phone's long side up with the box's long side (changed +2026-10-06 at the user's request: before, the prior kept the phone's orientation, so half of the first +failures were plain misalignment instead of a size mismatch). F2 feedback after a failed attempt reports where the phone ended up and by how much it is too +long / too wide along the box's long / short side; a learner can then rule out boxes that are not bigger +in that dimension and turn the phone. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, _wrap, bin_xml, register_generated +from ..skills import _rot_err +from ..task_base import LFFTask, register_task + +# phone (local x = long axis); PL is the visible length, the caps add 2 * cap (inst["cap"]) to it +PL, PW, PT = 0.140, 0.068, 0.012 +CAP_RANGE = (0.008, 0.009) # clear bumper cap length per end (hidden) +# boxes (local x = long axis of the opening) +WALL_T, FLOOR_T, WALL_H = 0.006, 0.006, 0.035 +BOX_HALF_H = (WALL_H + FLOOR_T) / 2 # body origin is at mid height +RIM_Z = envs.TABLE_Z + FLOOR_T + WALL_H +N_BOXES = 5 +ROWS_X = (-0.30, -0.08) # back row (near the robot), front row +COLS_Y = (-0.22, 0.0, 0.22) +DROP = 0.012 # phone bottom this far above the rim when released +Z_CARRY = envs.TABLE_Z + 0.15 +PARK = (-0.45, 0.0, envs.TABLE_Z + 0.35) # out of the agentview camera's way +PERC_SIGMA = 0.003 # perception noise (m) of the scripted adaptive policy's box-size estimates +JITTER_DEG = 15.0 +# inner size of each box kind = phone size + uniform(lo, hi) offset (m), (long side, short side). +# The distractors are chosen so that no coarse size heuristic finds the fitting box: the "short_wide" box has +# the largest area and width, "narrow_long" is the longest, "small" has the most phone-like aspect ratio. +# Only comparing both box dimensions with the phone's (or the F2 feedback) singles out the fitting box. +# v3: offsets are relative to the VISIBLE phone (PL x PW); only "fit" takes the capped phone (PL + 2 cap) +BOX_KINDS = ("fit", "snug", "short_wide", "narrow_long", "small") +INNER_RANGES = { + "fit": ((0.028, 0.008), (0.032, 0.009)), # +2.8..3.2 cm along, +0.8..0.9 cm across (looks the tightest) + "snug": ((0.0115, 0.025), (0.0125, 0.030)), # +1.15..1.25 along, +2.5..3.0 across: looks the most comfortable + "short_wide": ((0.003, 0.030), (0.006, 0.040)), # +0.3..0.6 along, +3..4 across: the biggest box + "narrow_long": ((0.035, -0.006), (0.040, -0.003)), # +3.5..4.0 along, 0.3..0.6 cm too narrow + "small": ((-0.010, 0.003), (-0.005, 0.006)), # 0.5..1.0 cm too short +} +VISIBLE_FIT = ("fit", "snug", "short_wide") # kinds that fit the phone as it looks (no caps) +BOX_RGBA = (0.70, 0.60, 0.46, 1.0) + + +def phone_xml(model_name): + hx, hy, hz = PL / 2, PW / 2, PT / 2 + body = (0.13, 0.13, 0.15, 1.0) + screen = (0.02, 0.025, 0.04, 1.0) + g = (f' \n' + f' \n' + f' ') + # v3: clear bumper caps on both ends: collision only, fully transparent, no visual twin (nothing is rendered). + # Resized per instance in apply_instance (inst["cap"]). + c = CAP_RANGE[1] + for k, sx in enumerate((1, -1)): + g += (f'\n ') + return _wrap(model_name, g, hz, float(np.hypot(hx + c, hy))) + + +def wrap_half(a): + """angle modulo pi into [-pi/2, pi/2) (the phone and the boxes are 180-deg symmetric)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def wrap_quarter(a): + """angle modulo pi/2 into [-pi/4, pi/4)""" + return float((a + np.pi / 4) % (np.pi / 2) - np.pi / 4) + + +def fits_some_yaw(a, b, clearance=0.002, length=PL): + """Does the phone's footprint (length x PW) fit inside an a x b opening at any yaw (with `clearance` to spare in + total)?""" + th = np.linspace(0.0, np.pi / 2, 181) + e1 = length * np.cos(th) + PW * np.sin(th) + e2 = length * np.sin(th) + PW * np.cos(th) + return bool(np.any((e1 <= a - clearance) & (e2 <= b - clearance))) + + +def _rect_corners(xy, yaw, half): + c, s = np.cos(yaw), np.sin(yaw) + R = np.array([[c, -s], [s, c]]) + pts = np.array([[1, 1], [1, -1], [-1, -1], [-1, 1]]) * np.asarray(half) + return pts @ R.T + np.asarray(xy) + + +def _rects_overlap(r1, r2): + """separating-axis test for two rotated rectangles given as (xy, yaw, half)""" + c1, c2 = _rect_corners(*r1), _rect_corners(*r2) + for yaw in (r1[1], r1[1] + np.pi / 2, r2[1], r2[1] + np.pi / 2): + ax = np.array([np.cos(yaw), np.sin(yaw)]) + p1, p2 = c1 @ ax, c2 @ ax + if p1.max() < p2.min() or p2.max() < p1.min(): + return False + return True + + +@register_task +class FitContainer(LFFTask): + name = "l4_fit_container" + level = "L4" + category = "geometry_inference" + capabilities = ("Perceive", "Reason") + instruction = "Put the phone flat inside a box that it fits into completely." + instruction_indirect = "Put the black rectangular gadget flat inside a box that it fits into completely." + + # ------------------------------------------------------------ scene + def make_bddl(self): + phone = register_generated("LffFitPhone", phone_xml("lff_fit_phone")) + # one category per box (BDDL lists one object per line; same-category lines would overwrite each + # other). All share the same MJCF; the opening is resized per instance in apply_instance. + cats = [register_generated(f"LffFitBox{c}", bin_xml(f"lff_fit_box_{c.lower()}", (0.075, 0.040), WALL_H, + wall_t=WALL_T, floor_t=FLOOR_T, rgba=BOX_RGBA, + density=3000)) + for c in "ABCDE"] + objs = [("phone_1", phone, "phone_region", (-0.09, -0.01, -0.07, 0.01))] + slots = [(x, y) for x in ROWS_X for y in COLS_Y if not (x == ROWS_X[1] and y == 0.0)] + for i, (x, y) in enumerate(slots): + objs.append((f"box_{i + 1}", cats[i], f"box{i + 1}_region", (x - 0.01, y - 0.01, x + 0.01, y + 0.01))) + return write_bddl(self.name, self.instruction, objs) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + j = np.radians(JITTER_DEG) + for _ in range(500): + col = int(rng.integers(3)) + phone_xy = [ROWS_X[1] + rng.uniform(-0.01, 0.01), COLS_Y[col] + rng.uniform(-0.01, 0.01)] + phone_yaw = float(rng.uniform(-j, j)) + slots = [(x, y) for x in ROWS_X for y in COLS_Y if not (x == ROWS_X[1] and y == COLS_Y[col])] + kinds = [BOX_KINDS[k] for k in rng.permutation(N_BOXES)] + cap = float(rng.uniform(*CAP_RANGE)) + boxes = [] + for i, (kind, (x, y)) in enumerate(zip(kinds, slots)): + lo, hi = INNER_RANGES[kind] + a, b = PL + rng.uniform(lo[0], hi[0]), PW + rng.uniform(lo[1], hi[1]) + assert (kind == "fit") == fits_some_yaw(a, b, length=PL + 2 * cap), (kind, a, b, cap) + assert (kind in VISIBLE_FIT) == fits_some_yaw(a, b), (kind, a, b) + crossed = bool(rng.random() < 0.5) + yaw = wrap_half(phone_yaw + (np.pi / 2 if crossed else 0.0) + rng.uniform(-j, j)) + boxes.append(dict(name=f"box_{i + 1}", kind=kind, crossed=crossed, + xy=[float(x + rng.uniform(-0.01, 0.01)), float(y + rng.uniform(-0.01, 0.01))], + yaw=yaw, inner=[float(a), float(b)])) + rects = [(b["xy"], b["yaw"], (b["inner"][0] / 2 + WALL_T + 0.007, b["inner"][1] / 2 + WALL_T + 0.007)) + for b in boxes] + rects.append((phone_xy, phone_yaw, (PL / 2 + 0.01, PW / 2 + 0.01))) + if not any(_rects_overlap(rects[p], rects[q]) for p in range(len(rects)) for q in range(p)): + break + else: + raise RuntimeError("could not sample a non-overlapping layout") + prng = np.random.default_rng(seed + 7919) + perc = [[float(b["inner"][0] + prng.normal(0, PERC_SIGMA)), float(b["inner"][1] + prng.normal(0, PERC_SIGMA))] + for b in boxes] + return dict(seed=int(seed), phone_xy=[float(v) for v in phone_xy], phone_yaw=phone_yaw, boxes=boxes, + fit=int(kinds.index("fit")), fit_crossed=boxes[kinds.index("fit")]["crossed"], cap=cap, _perc=perc) + + def _reshape_box(self, name, a, b): + ix, iy, H = a / 2, b / 2, BOX_HALF_H + parts = [((0, 0, -H + FLOOR_T / 2), (ix + WALL_T, iy + WALL_T, FLOOR_T / 2)), + ((ix + WALL_T / 2, 0, FLOOR_T / 2), (WALL_T / 2, iy + WALL_T, WALL_H / 2)), + ((-ix - WALL_T / 2, 0, FLOOR_T / 2), (WALL_T / 2, iy + WALL_T, WALL_H / 2)), + ((0, iy + WALL_T / 2, FLOOR_T / 2), (ix, WALL_T / 2, WALL_H / 2)), + ((0, -iy - WALL_T / 2, FLOOR_T / 2), (ix, WALL_T / 2, WALL_H / 2))] + m = self.env.sim.model + o = self.env.objects_dict[name] + for names in (o.contact_geoms, o.visual_geoms): + assert len(names) == len(parts), names + for k, n in enumerate(names): + g = m.geom_name2id(n) + pos, size = parts[k] + m.geom_pos[g] = pos + m.geom_size[g] = size + m.geom_rbound[g] = float(np.linalg.norm(size)) + m.geom_aabb[g] = [0, 0, 0, *size] + + def _set_caps(self, cap): + """resize the two hidden bumper caps to `cap` (m) per end""" + m = self.env.sim.model + if not hasattr(self, "_cap_ids"): + self._cap_ids = [g for g in envs.obj_geom_ids(self.env, "phone_1") + if m.geom_rgba[g][3] == 0.0 and m.geom_contype[g]] + assert len(self._cap_ids) == 2, self._cap_ids + for g in self._cap_ids: + sx = 1.0 if m.geom_pos[g][0] > 0 else -1.0 + size = (cap / 2, PW / 2 - 0.001, PT / 2) + m.geom_pos[g] = (sx * (PL / 2 + cap / 2), 0.0, 0.0) + m.geom_size[g] = size + m.geom_rbound[g] = float(np.linalg.norm(size)) + m.geom_aabb[g] = [0, 0, 0, *size] + + def apply_instance(self, inst): + # walls are moved inwards at run time, out of the compile-time per-body BVH leaf boxes, so the collision + # mid-phase can silently skip them (fingers / phone pass through; found on l4_nest_order 2026-10-07). + # Testing all geom pairs of nearby bodies is exact; the run-time geom_rbound / geom_aabb are set below. + import mujoco + self.env.sim.model._model.opt.disableflags |= int(mujoco.mjtDisableBit.mjDSBL_MIDPHASE) + self._set_caps(inst["cap"]) + for b in inst["boxes"]: + self._reshape_box(b["name"], *b["inner"]) + envs.set_obj_pose(self.env, b["name"], [*b["xy"], envs.TABLE_Z + BOX_HALF_H + 0.0005], yaw=b["yaw"]) + envs.set_obj_pose(self.env, "phone_1", [*inst["phone_xy"], envs.TABLE_Z + PT / 2 + 0.0005], + yaw=inst["phone_yaw"]) + + # ------------------------------------------------------------ outcome + def _pose2d(self, name): + bid = envs.body_id(self.env, name) + R = self.env.sim.data.body_xmat[bid].reshape(3, 3) + p = self.env.sim.data.body_xpos[bid].copy() + return p, float(np.arctan2(R[1, 0], R[0, 0])), float(np.degrees(np.arccos(np.clip(R[2, 2], -1, 1)))) + + def outcome(self, inst): + envs.settle(self.env, 40) + p, yaw, tilt = self._pose2d("phone_1") + held = bool(self.sk is not None and self.sk.holding("phone_1")) + # which box is the phone in / on: smallest distance of the phone centre outside a box opening + best = None + for j, b in enumerate(inst["boxes"]): + c, byaw, btilt = self._pose2d(b["name"]) + d = np.array([[np.cos(byaw), np.sin(byaw)], [-np.sin(byaw), np.cos(byaw)]]) @ (p[:2] - c[:2]) + out = np.maximum(np.abs(d) - np.array(b["inner"]) / 2, 0.0) + dist = float(np.linalg.norm(out)) + if best is None or dist < best[0]: + best = (dist, j, c, byaw, btilt) + dist, j, c, byaw, btilt = best + b = inst["boxes"][j] + a_in, b_in = b["inner"] + floor_top = c[2] - BOX_HALF_H + FLOOR_T + height = float(p[2] - PT / 2 - floor_top) # phone bottom above the box floor + in_opening = dist < 1e-9 + on_floor = height < 0.004 and tilt < 5.0 + success = bool(in_opening and on_floor and not held and btilt < 10.0) + where = self.box_label(inst, j) # relative description only: no absolute coordinates in feedback + # footprint of the phone (as it lies now) against the opening of that box + dl = yaw - byaw + cs, sn = abs(np.cos(dl)), abs(np.sin(dl)) + L = PL + 2 * inst.get("cap", 0.0) # the capped phone + over_long = L * cs + PW * sn - a_in + over_short = L * sn + PW * cs - b_in + along_long = "length" if cs >= sn else "width" + fb = dict(box=j, box_xy=[round(float(c[0]), 2), round(float(c[1]), 2)], along_long=along_long, + over_long_cm=round(100 * over_long, 1) if over_long > 0.001 else None, + over_short_cm=round(100 * over_short, 1) if over_short > 0.001 else None) + res = dict(success=success, box=j, box_kind=b["kind"], height_cm=round(100 * height, 2), + tilt_deg=round(tilt, 1), held=held, phone_xy=[float(p[0]), float(p[1])], feedback=fb) + if held: + res["detail"] = "The phone is still in the gripper." + res["failure"] = "held" + return res + if dist > 0.02 or (not in_opening and p[2] < envs.TABLE_Z + PT / 2 + 0.006): + res["detail"] = (f"The phone is not in any box: it is lying on the table, about {100 * dist:.0f} cm " + f"outside the opening of {where}.") + res["failure"] = "table" + return res + if success: + res["detail"] = f"The phone is lying flat on the bottom of {where}." + res["failure"] = None + return res + pose_txt = ("lying flat on top of the walls" if tilt < 5.0 else + f"tilted about {tilt:.0f} degrees with one end down inside the box") + txt = f"The phone did not go in: it is resting on the walls of {where}, {pose_txt}." + dim_l = "long" if along_long == "length" else "wide" + dim_s = "wide" if along_long == "length" else "long" + if fb["over_long_cm"]: + txt += f" It is about {fb['over_long_cm']:.1f} cm too {dim_l} for that box along the box's long side." + if fb["over_short_cm"]: + txt += f" It is about {fb['over_short_cm']:.1f} cm too {dim_s} for that box along the box's short side." + if not fb["over_long_cm"] and not fb["over_short_cm"]: + txt += " Its footprint is smaller than the opening, but it was not lined up with the box and caught on the rim." + res["detail"] = txt + res["failure"] = "rim" + return res + + @staticmethod + def box_label(inst, j): + """Name box j by its place among the boxes in robot-centric terms (left = +y = the robot's left).""" + ys = [b["xy"][1] for b in inst["boxes"]] + xs = [b["xy"][0] for b in inst["boxes"]] + n = len(ys) + order = sorted(range(n), key=lambda i: -ys[i]) # robot's left first + r = order.index(j) + close = [i for i in range(n) if i != j and abs(ys[i] - ys[j]) < 0.04] + if close: # boxes side by side in y: tell them apart by distance from the robot + nearer = all(xs[j] < xs[i] for i in close) + return f"the box {'nearest to' if nearer else 'farthest from'} the robot among those at the same left-right position" + if r == 0: + return "the box furthest to the robot's left (+y)" + if r == n - 1: + return "the box furthest to the robot's right (-y)" + return "the middle box (between the others, left to right)" + + # ------------------------------------------------------------ execution + def execute(self, inst, params): + """params: box (index into inst['boxes']), place_yaw (world yaw of the phone's long side when released). + Optional (tolerance checks only): dx / dy = release offset of the phone centre from the box centre + along the box's long / short axis (m), drop = height of the phone bottom above the rim (m).""" + sk, env = self.sk, self.env + px, py = inst["phone_xy"] + zc = envs.TABLE_Z + PT / 2 + g0 = wrap_half(inst["phone_yaw"]) # fingers close across the phone's width + sk.set_gripper(False, steps=5) + sk.move_to([px, py, zc + 0.10], yaw=g0) + sk.move_to([px, py, zc + 0.001], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([px, py, Z_CARRY], speed=0.25) + b = inst["boxes"][int(params["box"])] + c, s = np.cos(b["yaw"]), np.sin(b["yaw"]) + dx, dy = params.get("dx", 0.0), params.get("dy", 0.0) + bx, by = b["xy"][0] + c * dx - s * dy, b["xy"][1] + s * dx + c * dy + sk.move_to([bx, by, Z_CARRY], yaw=wrap_half(params["place_yaw"])) + # put the phone's centre (not the gripper's) over the box centre: compensates in-hand slip + off = envs.obj_pos(env, "phone_1") - sk.eef_pos() + drop = params.get("drop", DROP) + sk.move_to([bx - off[0], by - off[1], RIM_Z + max(0.05, drop + 0.01) - off[2]], tol=0.003) + tgt = self._servo_phone([bx, by], RIM_Z + drop) + sk.grip = -1.0 # open while holding the arm at a fixed target (Skills.hold re-anchors and drifts) + self._hold_at(tgt, 12) + sk.move_to([tgt[0], tgt[1], RIM_Z + 0.10]) + sk.move_to(list(PARK), yaw=0.0) + + def _hold_at(self, target, steps): + sk = self.sk + R = sk._R() + for _ in range(steps): + sk._act(np.asarray(target) - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip) + + def _servo_phone(self, xy, z_bottom, max_steps=60, tol=0.0015): + """Closed-loop: move the gripper until the held phone's centre is over xy and its bottom at z_bottom. + Returns the final gripper target.""" + sk = self.sk + R = sk._R() + goal = np.array([xy[0], xy[1], z_bottom + PT / 2]) + tgt = e_prev = sk.eef_pos() + for i in range(max_steps): + ph, e = envs.obj_pos(self.env, "phone_1"), sk.eef_pos() + if i >= 8 and np.linalg.norm(ph - goal) < tol and np.linalg.norm(e - e_prev) < 0.0005: + break + tgt = goal - (ph - e) + sk._act(tgt - e, _rot_err(R, sk.eef_mat()), sk.grip) + e_prev = e + return tgt + + # ------------------------------------------------------------ scripted policies + def _naive_yaw(self, inst, j): + """keep the phone's orientation, only snap it to the nearest axis of box j""" + p = inst["phone_yaw"] + return float(p + wrap_quarter(inst["boxes"][j]["yaw"] - p)) + + def default_params(self, inst): + """v3 prior: careful size comparison against the phone as it looks (exact visible sizes: the prior models the + trap; perception noise is only given to the adaptive learner) -- the box with the most room to spare in its + tighter direction, i.e. "snug" by construction; phone's long side along the box's long side""" + marg = [min(b["inner"][0] - PL, b["inner"][1] - PW) for b in inst["boxes"]] + j = int(np.argmax(marg)) + return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"])) + + def nearest_params(self, inst): + """v2 prior (kept for reference): nearest box, lined up""" + d = [np.hypot(b["xy"][0] - inst["phone_xy"][0], b["xy"][1] - inst["phone_xy"][1]) for b in inst["boxes"]] + j = int(np.argmin(d)) + return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"])) + + def oracle_params(self, inst): + j = inst["fit"] + return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"])) + + def blind_params(self, inst, attempt, rng): + """no history: a random box (may repeat), lined up like the prior""" + j = int(rng.integers(N_BOXES)) + return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"])) + + def naive_keep_yaw_params(self, inst): + """old prior (kept for reference): nearest box, keep the phone's orientation""" + d = [np.hypot(b["xy"][0] - inst["phone_xy"][0], b["xy"][1] - inst["phone_xy"][1]) for b in inst["boxes"]] + j = int(np.argmin(d)) + return dict(box=j, place_yaw=self._naive_yaw(inst, j)) + + def adapt_params(self, inst, history): + """Scripted learner on F2 feedback. + + Sees the boxes with noisy size estimates (inst['_perc'], sigma = PERC_SIGMA) but does not know the + phone's size. Each 'too long / too wide by X along the box's long / short side' message gives an + estimate of the phone's length or width (perceived box dimension + X). It then picks an untried box + that is big enough in every estimated dimension (preferring the biggest in the still-unknown one) and + lines the phone's long side up with the box's long side. + """ + perc = inst["_perc"] + L_est = W_est = None + tried_aligned = set() + for h in history: + o = h["outcome"] + fb = o.get("feedback") or {} + if o.get("failure") != "rim": + continue + j = fb["box"] + a, b = perc[j] + if fb["along_long"] == "length": + if fb["over_long_cm"] or fb["over_short_cm"]: # a size verdict on this box + tried_aligned.add(j) + if fb["over_long_cm"]: + L_est = max(L_est or 0.0, a + fb["over_long_cm"] / 100) + if fb["over_short_cm"]: + W_est = max(W_est or 0.0, b + fb["over_short_cm"] / 100) + else: + if fb["over_short_cm"]: + L_est = max(L_est or 0.0, b + fb["over_short_cm"] / 100) + if fb["over_long_cm"]: + W_est = max(W_est or 0.0, a + fb["over_long_cm"] / 100) + thr = 0.002 + cands = [] + for j, (a, b) in enumerate(perc): + if j in tried_aligned: + continue + mL = None if L_est is None else a - L_est + mW = None if W_est is None else b - W_est + feasible = (mL is None or mL > thr) and (mW is None or mW > thr) + if mL is not None and mW is not None: + key = min(mL, mW) + elif mL is not None: + key = b + elif mW is not None: + key = a + else: + key = a * b + cands.append((feasible, key, j)) + if not cands: + j = int(np.argmax([a * b for a, b in perc])) + else: + j = max(cands)[2] + return dict(box=int(j), place_yaw=float(inst["boxes"][j]["yaw"])) + + def elim_params(self, inst, history, rng): + """sensitivity variant: uses the feedback only to learn the orientation (always lines the phone up + after the first attempt) and to never retry a box that got a size verdict; picks among the remaining + boxes at random, i.e. no size reasoning / perception.""" + bad = set() + for h in history: + fb = h["outcome"].get("feedback") or {} + if h["outcome"].get("failure") == "rim" and fb.get("along_long") == "length" and ( + fb.get("over_long_cm") or fb.get("over_short_cm")): + bad.add(int(fb["box"])) + left = [j for j in range(N_BOXES) if j not in bad] or list(range(N_BOXES)) + j = int(rng.choice(left)) + return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"])) + + EXTRA_KINDS = ("elim",) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + if kind not in self.EXTRA_KINDS: + return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt) + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + if a == 0: + params = self.default_params(inst) + else: + params = self.elim_params(inst, history, rng) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"]: + break + return history + + +# ---------------------------------------------------------------- physical validity checks +def physics_check(seed0=1000, n=20, out=None): + """Every (box, orientation) pair on each instance, released centred from DROP above the rim. + Expect success iff the box is the fitting one and the phone's long side is along the box's long side.""" + import json + task = FitContainer() + rows = [] + for seed in range(seed0, seed0 + n): + inst = task.sample_instance(seed) + for j, b in enumerate(inst["boxes"]): + for orient in ("aligned", "crossed"): + task.reset_instance(inst) + task.execute(inst, dict(box=j, place_yaw=float(b["yaw"] + (0.0 if orient == "aligned" else np.pi / 2)))) + o = task.outcome(inst) + rows.append(dict(seed=seed, box=j, kind=b["kind"], inner_cm=[round(100 * v, 2) for v in b["inner"]], + orient=orient, success=o["success"], expect=bool(j == inst["fit"] and orient == "aligned"), + failure=o["failure"], height_cm=o["height_cm"], tilt_deg=o["tilt_deg"], detail=o["detail"])) + r = rows[-1] + print(f"seed {seed} box {j} {b['kind']:6s} {orient:7s} succ={r['success']} h={r['height_cm']} " + f"tilt={r['tilt_deg']}" + ("" if r["success"] == r["expect"] else " <-- MISMATCH"), flush=True) + if out: + with open(out, "w") as f: + json.dump(rows, f, indent=1) + print("total", len(rows), "mismatches", sum(r["success"] != r["expect"] for r in rows)) + return rows + + +def stress_check(seed=1002, out=None): + """Release errors (offset / yaw / drop height) at the edges of the size ranges: the tightest fitting box + (+1.0 cm in both directions) and boxes only 0.5 cm too short / too narrow.""" + import copy + import json + task = FitContainer() + base = task.sample_instance(seed) + j = base["fit"] + rows = [] + for name, a, b in [("fit_min", PL + 0.010, PW + 0.010), ("short_0.5", PL - 0.005, PW + 0.010), + ("narrow_0.5", PL + 0.010, PW - 0.005)]: + for dx, dy, dyaw, drop in [(0, 0, 0, DROP), (0.004, 0, 0, DROP), (0, 0.004, 0, DROP), (0.007, 0, 0, DROP), + (0, 0, 3, DROP), (0, 0, 6, DROP), (0, 0, 0, 0.05), (0.004, 0.003, 3, 0.05)]: + inst = copy.deepcopy(base) + inst["boxes"][j]["inner"] = [a, b] + task.reset_instance(inst) + task.execute(inst, dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"] + np.radians(dyaw)), + dx=dx, dy=dy, drop=drop)) + o = task.outcome(inst) + rows.append(dict(case=name, inner_cm=[round(a * 100, 2), round(b * 100, 2)], dx_mm=dx * 1000, + dy_mm=dy * 1000, dyaw_deg=dyaw, drop_cm=drop * 100, success=o["success"], + height_cm=o["height_cm"], tilt_deg=o["tilt_deg"], detail=o["detail"])) + print(f"{name:11s} dx={dx * 1000:.0f}mm dy={dy * 1000:.0f}mm dyaw={dyaw}deg drop={drop * 100:.1f}cm -> " + f"succ={o['success']} h={o['height_cm']} tilt={o['tilt_deg']} | {o['detail']}", flush=True) + if out: + with open(out, "w") as f: + json.dump(rows, f, indent=1) + return rows + + +if __name__ == "__main__": + # python -m lffbench.tasks.l4_fit physics results/l4_fit_container/physics_check.json + # python -m lffbench.tasks.l4_fit stress results/l4_fit_container/stress_check.json + import sys + if sys.argv[1] == "physics": + physics_check(out=sys.argv[2] if len(sys.argv) > 2 else None) + elif sys.argv[1] == "stress": + stress_check(out=sys.argv[2] if len(sys.argv) > 2 else None) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l4_nest.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l4_nest.py new file mode 100644 index 0000000000000000000000000000000000000000..1176314e28197c49c48a0dcb3c29ba649f2b2780 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l4_nest.py @@ -0,0 +1,644 @@ +"""L4-C nest_order: nest three cups one inside another; the tallest cup is not the widest. + +Scene: three open round cups (red, green, blue; 1.5 mm walls leaning outwards by TAPER_DEG = 5 deg, like slightly +flared tumblers) stand apart on the table. Each cup has its own bottom width and its own height (re-drawn per +instance, 3.5-10 cm tall). Cups are resized per instance by editing their geoms in sim.model (wall segments + +floor), so one env serves every instance (same technique as l4_fit_container). + +Trap (common sense): "the bigger cup goes outside", and a cup looks big mostly by its height. On (1 - P_AGREE) of +the instances the tallest cup is the middle one by width: it is at least INV_DH = 3.5 cm taller than the widest cup. +Their openings then differ by only 3-9 mm in diameter, and from the wrist camera at its start height the taller +one's opening is closer to the camera and looks about as big (about half the instances: bigger); from the front +camera the taller one looks clearly bigger. The narrowest cup is the shortest, so the very first move of the naive +order (widest cup into the tallest one) already fails, out on the table. + +A variant where the innermost cup was taller than the middle one (and the widest cup the tallest) was dropped +2026-10-08: its failure (middle cup on the rim of the innermost cup, both inside the outer one) looked like a nest +from both cameras -- the same flaw as the 14-deg version. + +What the failure looks like (the point of this version, user review 2026-10-08): which cup fits into which is +decided by the bottoms (same flare for all cups), and the sizes are drawn so that a cup whose bottom is too wide +does not go in at all -- it stays on the other cup's rim or wedges in the opening, its bottom at most STUCK_MAX += 0.5 cm below the rim. So a wrong placement leaves a cup standing on top of another one, its whole body above the +rim: visible in both cameras without any text feedback. A cup that fits goes down to the floor (centring tolerance +>= TOL_MIN = 7.5 mm thanks to the flare); in the right nest the taller, narrower cups stick out of the shorter, +wider ones, but each stands inside the next. + +Prior (naive): tallest cup outermost, then the next tallest. Learner: a cup that ended up on top of another cup +must go outside it; swap that pair. Feedback F1 (default) says only failed / succeeded; F2 (ablation) describes +which cup stands in / on which, in words, with no sizes or positions. + +Only move_to / open / close are needed: grasp a cup across its upper wall, carry it over the other cup, release it +just above that cup's rim. +""" +import itertools + +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, _wrap, register_generated +from ..skills import _rot_err +from ..task_base import LFFTask, register_task + +N_SEG = 20 # wall segments per cup (regular polygon) +TAN_SEG = float(np.tan(np.pi / N_SEG)) +COS_SEG = float(np.cos(np.pi / N_SEG)) +TAPER_DEG = 5.0 # wall lean (from vertical) +TAPER = float(np.radians(TAPER_DEG)) +TT = float(np.tan(TAPER)) +WALL_T = 0.0015 # wall thickness (normal to the wall) +WALL_TH = WALL_T / float(np.cos(TAPER)) # horizontal wall thickness +FLOOR_T = 0.003 +Z0 = 0.0003 # walls start this far above the cup's underside (the floor disc carries the cup) +H_RANGE = (0.035, 0.100) # total cup height +RB_WIDE = (0.023, 0.030) # bottom outer apothem of the cup with the widest bottom +STEP = (0.0055, 0.0075) # bottom apothem difference between neighbours in the true order +RIM_MAX = 0.033 # outer apothem of the widest opening (gripper opens 7.9 cm) +CLEAR_MIN = 0.003 # radial gap (worst case) of a fitting cup standing on the other cup's floor +TOL_MIN = 0.0075 # a fitting cup goes in if its bottom lands within this of the other cup's axis +STUCK_MAX = 0.005 # a too-wide cup's bottom stops no deeper than this below the other cup's rim (5-deg walls +# self-lock: a cup pressed 1.2 cm into the opening wedged, and the narrow cup tipped over with it) +INV_DH = 0.035 # in the swapped pair the narrower cup is taller by at least this +KEEP_DH = 0.010 # in an unswapped pair the wider cup is taller by at least this +P_AGREE = 0.15 # share of instances whose height order is the right nesting order +SEAT_H = 0.010 # "standing on the floor": bottom less than this above the other cup's floor +SEAT_TILT = 15.0 # deg; a tall cup in a short, wider one can lean a little +WRIST_CAM_H = 0.367 # wrist camera height above the table at the start pose (measured 2026-10-08) +COLORS = {"red": (0.78, 0.22, 0.20, 1.0), "green": (0.28, 0.62, 0.32, 1.0), "blue": (0.22, 0.42, 0.80, 1.0)} +CUP_NAMES = ("cup_1", "cup_2", "cup_3") +DENSITY = 600.0 +# execution +GRASP_BELOW_RIM = 0.012 # gripper site this far below the rim when grasping +Z_CARRY = envs.TABLE_Z + 0.24 +DROP = 0.006 # held cup's bottom this far above the receiving rim at release +FINGER_CLEAR = 0.015 # gripper site at least this far above any rim around the target at release: fingers opened +# inside a taller outer cup press on its wall and carry it away on the way up (seed 1009, 2026-10-08) +PARK = (-0.45, 0.0, envs.TABLE_Z + 0.35) +H_NOISE = 0.03 # relative noise of the blind policy's height judgement + + +# ---------------------------------------------------------------- cup geometry +def _quat_mul(a, b): + w1, x1, y1, z1 = a + w2, x2, y2, z2 = b + return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, + w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2]) + + +def _seg_quat(phi): + """segment frame: about z by phi, then tilted about its own y (tangential) axis by TAPER, so that its local z + (along the wall) leans outwards and its local x is the wall's outward normal""" + qz = np.array([np.cos(phi / 2), 0.0, 0.0, np.sin(phi / 2)]) + qy = np.array([np.cos(TAPER / 2), 0.0, np.sin(TAPER / 2), 0.0]) + return _quat_mul(qz, qy) + + +def seg_half_len(rb, H): + """tangential half length of a wall segment: one polygon side at the rim (+0.2 mm overlap)""" + return (rb + TT * H) * TAN_SEG + 0.0002 + + +def rim_radius(rb, H): + """outer apothem of the opening""" + return rb + TT * H + + +def inner_radius(rb, z): + """inner apothem at height z above the cup's underside""" + return rb + TT * z - WALL_TH + + +def bottom_reach(rb, H): + """largest horizontal radius of the cup's outside at its bottom (the segment tips stick out a little beyond + the polygon because every segment is as wide as a rim-level polygon side)""" + return float(np.hypot(rb + TT * Z0, seg_half_len(rb, H))) + + +def fit_clearance(rb_in, H_in, rb_out): + """radial clearance (worst case over relative yaw) of cup `in` standing on the floor of cup `out`; + negative = does not go down to the floor. The flare is the same for both cups, so the bottom is the tightest + height.""" + return inner_radius(rb_out, FLOOR_T) - bottom_reach(rb_in, H_in) + + +def centring_tol(rb_in, H_in, rb_out, H_out): + """how far (worst case) cup `in`'s bottom centre may be off cup `out`'s axis when it is lowered in at the rim + and still get inside (the flared wall then guides it down)""" + return inner_radius(rb_out, H_out) - bottom_reach(rb_in, H_in) + + +def stop_height(rb_in, rb_out, H_out): + """height (above cup `out`'s underside) where a too-wide cup `in`, lowered centred, stops: where its bottom + meets the sloping inner wall, or on the rim if that is higher than the cup""" + return min((rb_in - rb_out + WALL_TH) / TT, H_out) + + +def _cup_parts(rb, H): + """[(pos, half size, quat)] of the wall segments in the cup body frame (origin at mid height).""" + zc = (Z0 + H) / 2 + hs = (H - Z0) / (2 * np.cos(TAPER)) + rc = rb + TT * zc - WALL_T / 2 * np.cos(TAPER) + zz = zc + WALL_T / 2 * np.sin(TAPER) - H / 2 + hl = seg_half_len(rb, H) + out = [] + for k in range(N_SEG): + phi = 2 * np.pi * k / N_SEG + out.append(((rc * np.cos(phi), rc * np.sin(phi), zz), (WALL_T / 2, hl, hs), _seg_quat(phi))) + return out + + +def _floor_part(rb, H): + return (0.0, 0.0, -H / 2 + FLOOR_T / 2), (rb - 0.0003, FLOOR_T / 2, 0.0), np.array([1.0, 0.0, 0.0, 0.0]) + + +def cup_xml(model_name, rgba): + """Open flared cup: N_SEG tilted wall boxes + a cylinder floor (sizes are overwritten per instance).""" + geoms = [] + rb, H = RB_WIDE[1], H_RANGE[1] + for k, (p, s, q) in enumerate(_cup_parts(rb, H)): + geoms.append(f' ') + geoms.append(f' ') + fp, fs, _ = _floor_part(rb, H) + geoms.append(f' ') + geoms.append(f' ') + return _wrap(model_name, "\n".join(geoms), H / 2, rim_radius(rb, H) / COS_SEG) + + +def disable_midphase(env): + """The cups are resized at run time by editing geom pos / size in sim.model, but MuJoCo's per-body bounding + volume hierarchy (bvh_aabb, used by the collision mid-phase) is computed once at compile time for the registered + maximum size. A resized wall that lies outside its compiled leaf box is silently skipped: the gripper fingers + passed straight through the walls of the smaller cups (found 2026-10-07). Without the mid-phase MuJoCo tests all + geom pairs of two nearby bodies (still filtered by the run-time geom_rbound set in _reshape_cup).""" + import mujoco + m = env.sim.model._model + m.opt.disableflags |= int(mujoco.mjtDisableBit.mjDSBL_MIDPHASE) + + +def kendall(a, b): + """number of pairs ordered differently in the two orders""" + pa, pb = {c: k for k, c in enumerate(a)}, {c: k for k, c in enumerate(b)} + return sum((pa[x] < pa[y]) != (pb[x] < pb[y]) for x, y in itertools.combinations(a, 2)) + + +@register_task +class NestOrder(LFFTask): + name = "l4_nest_order" + level = "L4" + category = "geometry_inference" + capabilities = ("Perceive", "Reason", "Plan") + instruction = "Nest the red, green and blue cups one inside another." + instruction_indirect = "Put the three cups one inside another, like a set of nesting cups." + + # ------------------------------------------------------------ scene + def make_bddl(self): + cats = [register_generated(f"LffNestCup{c.capitalize()}", cup_xml(f"lff_nest_cup_{c}", COLORS[c])) + for c in COLORS] + regions = [(-0.25, -0.15), (-0.05, 0.0), (-0.25, 0.15)] + objs = [(n, cat, f"{n}_region", (x - 0.01, y - 0.01, x + 0.01, y + 0.01)) + for n, cat, (x, y) in zip(CUP_NAMES, cats, regions)] + return write_bddl(self.name, self.instruction, objs) + + @staticmethod + def _heights_ok(case, h): + """h[s] = height of the cup with the s-th narrowest bottom (0 = innermost in the true nest)""" + if case == "agree": # taller = wider: the height order is the nesting order + return h[2] >= h[1] + KEEP_DH and h[1] >= h[0] + KEEP_DH + if case == "swap_wide": # the middle cup is the tallest, the narrowest one the shortest + return h[1] >= h[2] + INV_DH and h[2] >= h[0] + KEEP_DH + raise ValueError(case) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + u = rng.random() + case = "agree" if u < P_AGREE else "swap_wide" + for _ in range(200000): + heights = [float(rng.uniform(*H_RANGE)) for _ in range(3)] # by true size: 0 = narrowest bottom + if not self._heights_ok(case, heights): + continue + rb3 = float(rng.uniform(*RB_WIDE)) + rb2 = rb3 - float(rng.uniform(*STEP)) + rb1 = rb2 - float(rng.uniform(*STEP)) + rbs = [rb1, rb2, rb3] + rims = [rim_radius(rb, h) for rb, h in zip(rbs, heights)] + if max(rims) > RIM_MAX: + continue + ok = True + for p, q in itertools.permutations(range(3), 2): # p into q + if p < q: + ok &= (fit_clearance(rbs[p], heights[p], rbs[q]) >= CLEAR_MIN + and centring_tol(rbs[p], heights[p], rbs[q], heights[q]) >= TOL_MIN) + else: + ok &= heights[q] - stop_height(rbs[p], rbs[q], heights[q]) <= STUCK_MAX + if ok: + break + else: + raise RuntimeError("could not sample cup sizes") + xy = [] + while len(xy) < 3: + xy = [] + for _k in range(3): + for _t in range(200): + p = [float(rng.uniform(-0.27, 0.02)), float(rng.uniform(-0.17, 0.17))] + if all(np.hypot(p[0] - q[0], p[1] - q[1]) >= 0.14 for q in xy): + xy.append(p) + break + # the colour is fixed per object (cup_1 red, cup_2 green, cup_3 blue: one generated class each); shuffle + # which object gets which size / height / position + perm = [int(i) for i in rng.permutation(3)] # perm[size index] = object slot + cups = [None] * 3 + for s in range(3): + cups[perm[s]] = dict(name=CUP_NAMES[perm[s]], color=list(COLORS)[perm[s]], rb=rbs[s], height=heights[s], + rim=rims[s], xy=xy[s], size_rank=s) + order = sorted(range(3), key=lambda j: -cups[j]["rb"]) # outermost first (indices into cups) + naive = sorted(range(3), key=lambda j: -cups[j]["height"]) + assert (naive == order) == (case == "agree"), (seed, case) + by = lambda s: perm[s] # noqa: E731 object index of size rank s + return dict(seed=int(seed), case=case, cups=cups, order=order, naive_order=naive, + bottom_cm=[round(200 * c["rb"], 2) for c in cups], + opening_cm=[round(200 * c["rim"], 2) for c in cups], + height_cm=[round(100 * c["height"], 2) for c in cups], + # relative size of each opening in the wrist camera at its start height (1 = largest) + wrist_apparent=[round(float(v), 3) for v in (lambda a: a / a.max())(np.array( + [c["rim"] / (WRIST_CAM_H - c["height"]) for c in cups]))], + clear_mm=[round(1000 * fit_clearance(rbs[s], heights[s], rbs[s + 1]), 2) for s in range(2)], + tol_mm=[round(1000 * centring_tol(rbs[s], heights[s], rbs[s + 1], heights[s + 1]), 2) + for s in range(2)], + # wrong neighbour pairs: how deep (cm) the wider cup's bottom gets below the narrower cup's rim + stuck_cm={f"{by(s + 1)}in{by(s)}": round(100 * (heights[s] - stop_height( + rbs[s + 1], rbs[s], heights[s])), 2) for s in range(2)}) + + def _reshape_cup(self, name, rb, H): + m = self.env.sim.model + o = self.env.objects_dict[name] + parts = _cup_parts(rb, H) + [_floor_part(rb, H)] + for names in (o.contact_geoms, o.visual_geoms): + assert len(names) == len(parts), (name, len(names)) + for k, n in enumerate(names): + g = m.geom_name2id(n) + pos, size, quat = parts[k] + m.geom_pos[g] = pos + m.geom_size[g] = size + m.geom_quat[g] = quat + if k < N_SEG: + m.geom_rbound[g] = float(np.linalg.norm(size)) + m.geom_aabb[g] = [0, 0, 0, *size] + else: + m.geom_rbound[g] = float(np.hypot(size[0], size[1])) + m.geom_aabb[g] = [0, 0, 0, size[0], size[0], size[1]] + # mass / inertia of the resized cup: conical shell + disc floor + bid = int(m.geom_bodyid[m.geom_name2id(o.contact_geoms[0])]) + slant = (H - Z0) / np.cos(TAPER) + r_mid = rb + TT * (H + Z0) / 2 + wall_m = DENSITY * 2 * np.pi * r_mid * WALL_T * slant + floor_m = DENSITY * np.pi * rb ** 2 * FLOOR_T + mass = wall_m + floor_m + # wall centroid height (from the underside): area-weighted, r grows linearly with z + r0, r1 = rb + TT * Z0, rb + TT * H + z_w = Z0 + (H - Z0) * (r0 + 2 * r1) / (3 * (r0 + r1)) + z_cm = (wall_m * z_w + floor_m * FLOOR_T / 2) / mass + Izz = wall_m * r_mid ** 2 + floor_m * rb ** 2 / 2 + Ixx = (wall_m * (r_mid ** 2 / 2 + (H - Z0) ** 2 / 12 + (z_w - z_cm) ** 2) + + floor_m * (rb ** 2 / 4 + (FLOOR_T / 2 - z_cm) ** 2)) + m.body_mass[bid] = mass + m.body_inertia[bid] = [Ixx, Ixx, Izz] + m.body_ipos[bid] = [0.0, 0.0, z_cm - H / 2] + m.body_iquat[bid] = [1.0, 0.0, 0.0, 0.0] + + def apply_instance(self, inst): + disable_midphase(self.env) + for c in inst["cups"]: + self._reshape_cup(c["name"], c["rb"], c["height"]) + envs.set_obj_pose(self.env, c["name"], [*c["xy"], envs.TABLE_Z + c["height"] / 2 + 0.0005]) + + # ------------------------------------------------------------ state + def _cup_state(self, inst, j): + c = inst["cups"][j] + bid = envs.body_id(self.env, c["name"]) + p = self.env.sim.data.body_xpos[bid].copy() + R = self.env.sim.data.body_xmat[bid].reshape(3, 3) + tilt = float(np.degrees(np.arccos(np.clip(R[2, 2], -1, 1)))) + bottom = p - R[:, 2] * c["height"] / 2 # centre of the floor's underside + rim = p + R[:, 2] * c["height"] / 2 + return dict(p=p, tilt=tilt, bottom=bottom, rim=rim, floor_top=bottom[2] + FLOOR_T * R[2, 2]) + + def relations(self, inst): + """For each cup: which cup it stands in / on (if any), how high, seated or not.""" + st = [self._cup_state(inst, j) for j in range(3)] + rel = [] + for j in range(3): + sj = st[j] + best = None + for i in range(3): + if i == j: + continue + ci, si = inst["cups"][i], st[i] + if si["tilt"] > 45: + continue + d = float(np.hypot(*(sj["bottom"][:2] - si["p"][:2]))) + if d > rim_radius(ci["rb"], ci["height"]) + 0.01: + continue # not above / in cup i + hb = float(sj["bottom"][2] - si["floor_top"]) # j's bottom above i's floor + # (the last test keeps a cup from being reported as standing in the cup it contains) + if hb < -0.004 or hb > ci["height"] + 0.02 or sj["bottom"][2] < si["bottom"][2] + FLOOR_T / 2: + continue + if best is None or hb < best[1]: + best = (i, hb, d) + if best is None: + on_table = sj["bottom"][2] < envs.TABLE_Z + 0.01 and sj["tilt"] < 30 + rel.append(dict(cup=j, on=None, table=bool(on_table), tilt=sj["tilt"], xy=sj["p"][:2].tolist(), + fallen=bool(sj["tilt"] > 45))) + continue + i, hb, d = best + ci = inst["cups"][i] + seated = hb < SEAT_H and sj["tilt"] < SEAT_TILT + on_rim = hb > ci["height"] - FLOOR_T - 0.004 + rel.append(dict(cup=j, on=i, height=hb, seated=bool(seated), on_rim=bool(on_rim), tilt=sj["tilt"], + offset=d, xy=sj["p"][:2].tolist(), fallen=bool(sj["tilt"] > 45))) + return rel + + def outcome(self, inst): + envs.settle(self.env, 40) + cups = inst["cups"] + rel = self.relations(inst) + held = [j for j in range(3) if self.sk is not None and self.sk.holding(cups[j]["name"])] + col = [c["color"] for c in cups] + seated_in = {r["cup"]: r["on"] for r in rel if r.get("on") is not None and r["seated"]} + # success: a chain outer <- mid <- inner, all seated and upright, the outer cup standing on the table + success = False + for a, b, c in itertools.permutations(range(3)): + if seated_in.get(b) == a and seated_in.get(c) == b and _on_table_upright(rel, a): + success = True + success = bool(success and not held) + fb = dict(seated=[[j, i] for j, i in seated_in.items()], blocked=[], offcentre=[], held=held) + lines = [] + res = dict(success=success, relations=rel, feedback=fb) + if held: + lines.append(f"The {col[held[0]]} cup is still in the gripper.") + if success: + a = [j for j in range(3) if j not in seated_in][0] + b = [j for j, i in seated_in.items() if i == a][0] + c = [j for j, i in seated_in.items() if i == b][0] + res["detail"] = (f"All three cups are nested: the {col[c]} cup stands inside the {col[b]} cup, " + f"which stands inside the {col[a]} cup.") + res["failure"] = None + return res + # bottom-up description + st = {r["cup"]: self._cup_state(inst, r["cup"]) for r in rel} + for r in sorted(rel, key=lambda r: st[r["cup"]]["bottom"][2]): + j = r["cup"] + if j in held: + continue + if r.get("on") is None: + if r["fallen"]: + lines.append(f"The {col[j]} cup has fallen over.") + elif r["table"]: + lines.append(f"The {col[j]} cup is standing on the table, not in another cup.") + else: + lines.append(f"The {col[j]} cup is neither standing on the table nor inside another cup.") + continue + i = r["on"] + if r["seated"]: + lines.append(f"The {col[j]} cup is inside the {col[i]} cup, standing on its bottom.") + continue + # did not go in. The text says only what a camera shows (no sizes); the structured field keeps the + # nominal verdict for the scripted learner + tilt = f", tilted about {r['tilt']:.0f} degrees" if r["tilt"] >= 8 else "" + if r["on_rim"]: + lines.append(f"The {col[j]} cup is sitting on the rim of the {col[i]} cup, not inside it{tilt}.") + else: + lines.append(f"The {col[j]} cup is stuck in the opening of the {col[i]} cup, not down inside " + f"it{tilt}.") + over = cups[j]["rb"] - cups[i]["rb"] + if over > 0: + fb["blocked"].append([j, i, round(100 * r["height"], 1)]) + else: + fb["offcentre"].append([j, i, round(100 * r["height"], 1)]) + res["detail"] = " ".join(lines) if lines else "The cups are not nested." + res["failure"] = "blocked" if fb["blocked"] else ("offcentre" if fb["offcentre"] else + ("held" if held else "incomplete")) + return res + + # ------------------------------------------------------------ execution + def execute(self, inst, params): + """params: order = [outer, middle, inner] (indices into inst['cups']). Puts the middle cup into the outer + one; if it went in (judged from the scene, as an agent would see it), puts the inner cup into the middle + one. Optional (robustness checks): dxy = (dx, dy) release offset (m), drop (m), grasp_below (m), + carry_speed (m/s or None = as fast as the controller allows).""" + o, mid, inn = [int(v) for v in params["order"]] + ok = self._move_cup(inst, mid, o, params) + if ok: + self._move_cup(inst, inn, mid, params) + self.sk.move_to(list(PARK), yaw=0.0) + + def _move_cup(self, inst, j, i, params): + sk = self.sk + sj = self._cup_state(inst, j) + x, y = sj["p"][:2] + rim = sj["rim"][2] + sk.set_gripper(False, steps=5) + sk.move_to([x, y, Z_CARRY], yaw=0.0) + sk.move_to([x, y, rim + 0.06], tol=0.004) + sk.move_to([x, y, rim - params.get("grasp_below", GRASP_BELOW_RIM)], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([x, y, Z_CARRY], speed=params.get("carry_speed", 0.3)) + si = self._cup_state(inst, i) + dx, dy = params.get("dxy", (0.0, 0.0)) + tx, ty = si["p"][0] + dx, si["p"][1] + dy + drop = params.get("drop", DROP) + sk.move_to([tx, ty, Z_CARRY], tol=0.004) + off = self._cup_state(inst, j)["bottom"] - sk.eef_pos() + # approach above the highest rim there (the target cup may stand inside a taller one) + top = max(s["rim"][2] for s in (self._cup_state(inst, q) for q in range(3) if q != j) + if np.hypot(s["p"][0] - tx, s["p"][1] - ty) < 0.04) + sk.move_to([tx - off[0], ty - off[1], max(top, si["rim"][2]) + drop + 0.03 - off[2]], tol=0.003) + z_rel = si["rim"][2] + drop + if top > si["rim"][2] + 0.002: # the target stands inside a taller cup: let go above that rim + z_rel = max(z_rel, top + FINGER_CLEAR - (inst["cups"][j]["height"] + - params.get("grasp_below", GRASP_BELOW_RIM))) + tgt = self._servo_cup(inst, j, [tx, ty], z_rel) + sk.grip = -1.0 + self._hold_at(tgt, 12) + sk.move_to([tgt[0], tgt[1], Z_CARRY], speed=0.3) + envs.settle(self.env, 20) + r = [q for q in self.relations(inst) if q["cup"] == j][0] + return bool(r.get("on") == i and r["seated"]) + + def _hold_at(self, target, steps): + sk = self.sk + R = sk._R() + for _ in range(steps): + sk._act(np.asarray(target) - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip) + + def _servo_cup(self, inst, j, xy, z_bottom, max_steps=60, tol=0.0015): + """closed loop on the held cup's bottom centre (scripted policies only). Stops where the cup is held up + (a too-wide cup on / in another cup's rim) instead of pressing on: a person lets go there too, and + pressing on tips the cups over.""" + sk = self.sk + R = sk._R() + goal = np.array([xy[0], xy[1], z_bottom]) + tgt = e_prev = sk.eef_pos() + zs = [] + for k in range(max_steps): + b, e = self._cup_state(inst, j)["bottom"], sk.eef_pos() + if k >= 8 and np.linalg.norm(b - goal) < tol and np.linalg.norm(e - e_prev) < 0.0005: + break + zs.append(b[2]) + if k >= 12 and b[2] - goal[2] > 0.003 and zs[-6] - b[2] < 0.0005: + return e # blocked: release here + tgt = goal - (b - e) + sk._act(tgt - e, _rot_err(R, sk.eef_mat()), sk.grip) + e_prev = e + return tgt + + # ------------------------------------------------------------ scripted policies + def default_params(self, inst): + """prior: the bigger-looking cup goes outside, and the cups look big by their height: tallest outermost""" + return dict(order=list(inst["naive_order"])) + + def oracle_params(self, inst): + return dict(order=list(inst["order"])) + + def blind_params(self, inst, attempt, rng): + """no history: the same height judgement again, with a little noise""" + est = [c["height"] * (1 + rng.normal(0, H_NOISE)) for c in inst["cups"]] + return dict(order=[int(i) for i in np.argsort(est)[::-1]]) + + @staticmethod + def constraints(history): + """pairs (outer, inner) implied by the F2 feedback of earlier attempts""" + pairs = set() + for h in history: + fb = h["outcome"].get("feedback") or {} + for j, i in fb.get("seated", []): + pairs.add((int(i), int(j))) # j sits in i -> i is outside j + for j, i, _ in fb.get("blocked", []): + pairs.add((int(j), int(i))) # j does not fit into i -> j must be outside i + for j, i, _ in fb.get("offcentre", []): + pairs.add((int(i), int(j))) # j would fit into i + return pairs + + def adapt_params(self, inst, history): + """Scripted learner. It does not perceive the bottoms at all; it uses only which cup went into / stayed on + top of which (visible in the camera images; the structured part of the outcome): every such relation gives + an (outer, inner) pair; among the untried orders consistent with all pairs it takes the one closest (fewest + swapped pairs) to its prior, the height order; ties go to the larger height agreement.""" + pairs = self.constraints(history) + rims = [c["height"] for c in inst["cups"]] + prior = list(inst["naive_order"]) + tried = {tuple(h["params"]["order"]) for h in history if (h["outcome"].get("feedback") or {}).get("blocked")} + cands = [] + for order in itertools.permutations(range(3)): + pos = {c: k for k, c in enumerate(order)} + consistent = all(pos[a] < pos[b] for a, b in pairs) + agree = sum(rims[order[k]] - rims[order[k + 1]] for k in range(2)) + cands.append((consistent, tuple(order) not in tried, -kendall(order, prior), agree, order)) + best = max(cands) + return dict(order=list(best[4])) + + def random_order_params(self, inst, history, rng): + """sensitivity variant: a random order each retry, no history""" + return dict(order=[int(i) for i in rng.permutation(3)]) + + EXTRA_KINDS = ("random_order",) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + if kind not in self.EXTRA_KINDS: + return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt) + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + params = self.default_params(inst) if a == 0 else self.random_order_params(inst, history, rng) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"]: + break + return history + + +def _on_table_upright(rel, j): + r = [q for q in rel if q["cup"] == j][0] + return r.get("on") is None and r["table"] and r["tilt"] < 8.0 and not r["fallen"] + + +# ---------------------------------------------------------------- physical validity checks +def physics_check(seed0=1000, n=8, out=None): + """All 6 orders on each instance; expect success iff the order is the true one.""" + import json + task = NestOrder() + rows = [] + for seed in range(seed0, seed0 + n): + inst = task.sample_instance(seed) + for order in itertools.permutations(range(3)): + task.reset_instance(inst) + task.execute(inst, dict(order=list(order))) + o = task.outcome(inst) + expect = list(order) == inst["order"] + # for a cup that did not go in: how far (cm) its bottom is below the other cup's rim + below_rim = [round(100 * (inst["cups"][r["on"]]["height"] - FLOOR_T - r["height"]), 2) + for r in o["relations"] if r.get("on") is not None and not r["seated"]] + rows.append(dict(seed=seed, case=inst["case"], order=list(order), success=o["success"], expect=expect, + failure=o["failure"], detail=o["detail"], below_rim_cm=below_rim, + clear_mm=inst["clear_mm"], tol_mm=inst["tol_mm"], bottom_cm=inst["bottom_cm"], + opening_cm=inst["opening_cm"], height_cm=inst["height_cm"])) + print(f"seed {seed} order {order} succ={o['success']} expect={expect} | {o['detail']}" + + ("" if o["success"] == expect else " <-- MISMATCH"), flush=True) + if out: + with open(out, "w") as f: + json.dump(rows, f, indent=1) + print("total", len(rows), "mismatches", sum(r["success"] != r["expect"] for r in rows)) + return rows + + +def robustness_check(seed0=1000, n=6, out=None): + """True order with execution errors: release off-centre (both moves) by 0-9 mm in a random direction, released + 3 cm above the rim, grasped lower, carried at full controller speed.""" + import json + task = NestOrder() + rows = [] + cases = [("centred", {}), ("off3", dict(off=0.003)), ("off5", dict(off=0.005)), ("off7", dict(off=0.007)), + ("off9", dict(off=0.009)), ("drop3cm", dict(drop=0.03)), ("off4_drop3cm", dict(off=0.004, drop=0.03)), + ("grasp2cm", dict(grasp_below=0.02)), ("fast_carry", dict(carry_speed=None))] + for seed in range(seed0, seed0 + n): + inst = task.sample_instance(seed) + rng = np.random.default_rng(seed) + for name, c in cases: + a = rng.uniform(0, 2 * np.pi) + off = c.get("off", 0.0) + params = dict(order=list(inst["order"]), dxy=(off * np.cos(a), off * np.sin(a))) + params.update({k: v for k, v in c.items() if k != "off"}) + task.reset_instance(inst) + task.execute(inst, params) + o = task.outcome(inst) + rows.append(dict(seed=seed, case=name, success=o["success"], detail=o["detail"], tol_mm=inst["tol_mm"], + height_cm=inst["height_cm"])) + print(f"seed {seed} {name:13s} succ={o['success']} | {o['detail']}", flush=True) + if out: + with open(out, "w") as f: + json.dump(rows, f, indent=1) + for name, _ in cases: + r = [x["success"] for x in rows if x["case"] == name] + print(f"{name:13s} {sum(r)}/{len(r)}") + return rows + + +if __name__ == "__main__": + # python -m lffbench.tasks.l4_nest physics results/l4_nest_order/physics_check.json [n] + # python -m lffbench.tasks.l4_nest robust results/l4_nest_order/robustness_check.json [n] + import sys + n_arg = int(sys.argv[3]) if len(sys.argv) > 3 else None + if sys.argv[1] == "physics": + physics_check(out=sys.argv[2] if len(sys.argv) > 2 else None, n=n_arg or 8) + elif sys.argv[1] == "robust": + robustness_check(out=sys.argv[2] if len(sys.argv) > 2 else None, n=n_arg or 6) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l5_iterative.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l5_iterative.py new file mode 100644 index 0000000000000000000000000000000000000000..eec94ac61e9f0b98925237971a1da808aded8ef3 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l5_iterative.py @@ -0,0 +1,136 @@ +"""[PARKED 2026-10-06 — fails acceptance: oracle 50% (n=12, k=3). The push response is not stationary: +the same commanded speed carries the cube 7.9 cm on one push and 11.4 cm on the next, because the arm reaches +different speeds at different extensions. Needs a configuration-independent striker before use.] + +L5-B iterative_push: several pushes in ONE episode (MemMimic "Iterative Pushing" analogue). + +The cube starts far from the target zone; each push is a straight strike away from the robot whose +only free parameter is the speed. Overshooting past the zone is unrecoverable (episode fails). +Hidden variable: cube-table friction mu, as in l5_slide_to_target. The information needed to choose +the next push (how far a push of a given speed carries the cube) is only available from the +outcomes of the previous pushes in the same episode -> within-episode learning from failure. + +"Attempt" granularity for the history: one push. +""" +import numpy as np + +from .. import envs +from ..task_base import register_task +from .l5_slide import CUBE_HALF, V_MAX, V_MIN, Z_PUSH, SlideToTarget + + +@register_task +class IterativePush(SlideToTarget): + name = "l5_iterative_push" + level = "L5" + capabilities = ("Reason", "Save", "Utilize") + protocol = "within" + max_attempts = 3 # pushes per episode: too few to creep up on the target with small taps + instruction = ("Push the red cube away from the robot so that it comes to rest inside the green target zone. " + "You have at most three separate pushes. If the cube passes the zone, the task fails.") + instruction_indirect = instruction + tol_along = 0.015 + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + return dict(seed=int(seed), + cube_xy=[float(rng.uniform(-0.27, -0.23)), float(rng.uniform(-0.08, 0.08))], + target_dist=float(rng.uniform(0.22, 0.30)), + mu=float(np.exp(rng.uniform(np.log(0.035), np.log(0.08))))) + + def make_bddl(self): + return super().make_bddl() + + # --------------------------------------------------------------- one push from the current cube pose + def push_once(self, inst, speed): + c = envs.obj_pos(self.env, "cube_1") + x, y = c[0], c[1] + sk = self.sk + sk.set_gripper(True, steps=3) + sk.move_to([x - self.runup, y, Z_PUSH + 0.10], yaw=0.0) + sk.move_to([x - self.runup, y, Z_PUSH], tol=0.003) + sk.move_to([x - CUBE_HALF + 0.015, y, Z_PUSH], speed=float(np.clip(speed, V_MIN, V_MAX)), tol=0.01, + max_steps=80) + sk.move_to([x - CUBE_HALF + 0.015, y, Z_PUSH + 0.10], speed=0.3) + envs.settle(self.env, 40) + c1 = envs.obj_pos(self.env, "cube_1") + return float(c1[0] - x) + + def outcome(self, inst): + x0, y0 = inst["cube_xy"] + c = envs.obj_pos(self.env, "cube_1") + along = (c[0] - x0) - inst["target_dist"] + across = c[1] - y0 + success = bool(abs(along) <= self.tol_along and abs(across) <= self.tol_across and c[2] > envs.TABLE_Z) + overshoot = bool(along > self.tol_along) + if success: + detail = "The cube is inside the target zone." + elif overshoot: + detail = f"The cube passed the target zone: it is {100 * along:.1f} cm beyond its centre. The task has failed." + else: + detail = f"The cube is {100 * -along:.1f} cm short of the centre of the target zone." + return dict(success=success, overshoot=overshoot, along_err=float(along), across_err=float(across), + detail=detail) + + # --------------------------------------------------------------- scripted references + S0 = 0.02 # distance the cube travels during the contact stroke itself + + def _plan_speed(self, remaining, model, pushes_left=1): + """Model: push distance d(v) = s0 + k v^2. With more than one push left, cover all but a short + final leg (a short push is more predictable); with one push left, aim at the zone centre.""" + if model is None: + return 0.30 + s0, k = model + goal = remaining if pushes_left <= 1 else max(remaining - 0.07, 0.0) + v = np.sqrt(max(goal - s0, 0.0) / max(k, 1e-6)) + return float(np.clip(v, V_MIN, V_MAX)) + + @classmethod + def _fit(cls, pts): + """pts: [(v, d)]. One point -> fix s0; two or more -> least squares on (s0, k).""" + if len(pts) == 1: + v, d = pts[0] + return cls.S0, max(d - cls.S0, 1e-4) / v ** 2 + A = np.array([[1.0, v ** 2] for v, _ in pts]) + b = np.array([d for _, d in pts]) + s0, k = np.linalg.lstsq(A, b, rcond=None)[0] + if k <= 0: + return cls.S0, max(np.mean(b) - cls.S0, 1e-4) / np.mean([v ** 2 for v, _ in pts]) + return float(np.clip(s0, 0.0, 0.05)), float(k) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + self.reset_instance(inst) + history = [] + model = None + if kind == "oracle": + model = self._oracle_model(inst) + for a in range(k): + out0 = self.outcome(inst) + remaining = -out0["along_err"] + if kind == "naive" or kind == "blind": + speed = 0.30 if kind == "naive" else float(np.clip(0.30 + rng.normal(0, 0.05), V_MIN, V_MAX)) + if remaining < 0.06: # naive heuristic: tap gently near the end + speed = 0.20 + else: + speed = self._plan_speed(remaining, model, pushes_left=k - a) + moved = self.push_once(inst, speed) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=dict(speed=speed), outcome=dict(out, moved=moved))) + if kind == "adaptive" and moved > 0.005: + pts = [(h["params"]["speed"], h["outcome"]["moved"]) for h in history if h["outcome"]["moved"] > 0.005] + model = self._fit(pts) + if out["success"] or out["overshoot"]: + break + # mark only the final state as the episode outcome + return history + + def _oracle_model(self, inst): + """Privileged: measure the push model with the true mu in scratch rollouts.""" + pts = [] + for v in (0.2, 0.35, 0.5): + self.reset_instance(inst) + pts.append((v, self.push_once(inst, v))) + self.reset_instance(inst) + return self._fit(pts) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l5_loaded_beam.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l5_loaded_beam.py new file mode 100644 index 0000000000000000000000000000000000000000..9131ad1abf4810702f25f598a39e4010f47ecaef --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l5_loaded_beam.py @@ -0,0 +1,598 @@ +"""L5 loaded_beam (2026-10-12): a deepened l5_slippery_lift -- lift a loaded bar level without spilling its load. + +Why (../research_notes/P1P2_加深与常识任务设计.md sec. 1, 2, 3.1): l5_slippery_lift saturated. Sonnet 5.5 (cla4) +grasped the bar's middle, lifted, saw the 45-60 deg tilt, put the bar down and regrasped near the centre of mass, +all inside attempt 1 (both runs succeeded on attempt 1): the tilting lift cost nothing. Rule R3: the first +common-sense interaction must cost something. Here the tilting lift spills the load. + +Scene (world frame, robot base at x = -0.66; "forward" = +x, "left" = +y): the l5_slippery_lift bar (steel grey, +4 x 28 x 4 cm, long axis along the robot's left-right axis, same layout and hidden weight per seed) with two small red +blocks (2.5 cm cubes, 30 g, smooth: friction 0.2, they slide on the steel beyond ~11 deg of tilt) resting on its top +near the ends, 12.5 cm left and right of its middle. + +Hidden variable (same in every attempt, invisible): a slug inside the bar puts its centre of mass e = 2.5-7 cm from +the middle, towards the left or right end (bar 0.8-1.2 kg, finger friction 0.40-0.60; l5_slippery_lift). The blocks +are symmetric, so the centre of mass of bar + blocks sits at M e / (M + 2 m) (2.3-6.7 cm). + +Mechanism (physics, nothing teleported): grasped at its middle and lifted, the bar rotates in the slippery finger +pads and hangs tilted; the block on the low (heavy) end slides off, drops onto the table and, once the bar is set down +again, lies 2-5 cm beyond the bar's end; the other block slides along the bar to the fingers. Measured (20 seeds, +middle grasp): lift 15 cm at 0.1 m/s -> tilt 29-54 deg, spill 20/20; 15 cm at 0.03 m/s -> spill 20/20 (block friction = +the bar's, task card); a 5.5 cm "half lift" -> 20-22 deg, spill 20/20; 3 cm -> 10-11 deg, spill 2/20; 1 / 1.5 cm test +lifts -> 0.6-2.5 / 2.5-4.5 deg, spill 0/20 each (the low end stays on the table). Putting it right is a real repair: +set the bar down, release, pick the fallen block from the table, put it back on the end, move the other block back to +its end, regrasp nearer the heavy end, lift again: 20 commands for the scripted policy (5 for the whole oracle; the +same repair costs 7 commands in l5_slippery_lift, where nothing spills). What helps: a ~1 cm test lift shows the tilt +direction without spilling, or, after the first failure, grasping on the side of the end that sank (the heavy end), +ideally at the combined centre of mass (+-5 mm: 80/80 level lifts, nothing spilled). + +Success: the bar is held (after a 1.5 s hold), tilted <= 8 deg, its lowest point >= 10 cm above the table (the +l5_slippery_lift condition), and both blocks rest on the bar, one within 3 cm of each end position (+-12.5 cm from the +middle; either block may sit on either end). Protocol: cross (reset before every attempt), k = 3. + +Outcome (server log only; the agent gets F1): success / failure code, the bar's tilt and height, final block states, +per-step events (bar_lifted, bar_tilted, load_fell = the trap fired, load_displaced, load_removed, load_restored with +by_robot, bar_set_down), the lifts with their grasp points and maximum tilt, trap_fired, recovered_in_attempt, +first_interaction_ok and an F2-style `detail` in robot-centric words. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import box_xml, register_generated +from ..task_base import register_task +from .l5_slippery_lift import (BAR, HALF, LIFT_MIN, TILT_MAX, YAW_ACROSS, Z_GRASP, BarSkills, SlipperyLift, + bar_tilt_deg, weighted_box_xml) + +TZ = envs.TABLE_Z +LOADS = ("block_1", "block_2") # block_1 starts on the left (+y) end, block_2 on the right (-y) end +LOAD_SIGN = {"block_1": 1.0, "block_2": -1.0} +LOAD_H = 0.0125 # 2.5 cm cubes +LOAD_MASS = 0.030 +LOAD_RGBA = (0.85, 0.20, 0.12, 1.0) +LOAD_MU = 0.20 # block sliding friction (geom priority 3: used against the bar, the table and the fingers): the blocks +# slide on the steel bar beyond ~11 deg of tilt. With the bar's own mu (0.4-0.6, slide beyond 22-31 deg) +# a 5.5 cm "half lift" (20 deg) spilled nothing (0/10) and was a free probe; with 0.2 it spills. +SLOT = 0.125 # block centre this far from the bar's middle (along the bar) +SLOT_TOL = 0.03 # success: within 3 cm of an end position +BAR_TOP = TZ + 2 * HALF[2] +LIFTED = 0.02 # the bar's centre this much higher than at rest (while held) -> "lifted" (a ~1 cm test lift is not) +DOWN = 0.008 # ... and back below this -> "set down" +DEBOUNCE = 5 # control steps a new block state must persist before it counts +SAFE_ALONG = 0.09 # scripted grasps stay within +-9 cm of the middle (the hand must not touch the blocks) + + +class _Budget(Exception): + """the scripted policy used up the agent command budget of the attempt""" + + +def bar_frame(env): + """(centre, along, side, up): `along` = the bar's long axis oriented towards the robot's left (+y); `up` = the + bar's cross-section axis closest to world up (the face the blocks rest on); `side` completes the frame.""" + bid = envs.body_id(env, BAR) + d = env.sim.data + c = d.body_xpos[bid].copy() + R = d.body_xmat[bid].reshape(3, 3) + al = R[:, 1].copy() + if al[1] < 0: + al = -al + up = max((R[:, 0].copy(), R[:, 2].copy()), key=lambda v: abs(v[2])) + if up[2] < 0: + up = -up + side = np.cross(up, al) + return c, al, side, up + + +def _end_word(s): + return "left" if s > 0 else "right" + + +class BeamSkills(BarSkills): + """BarSkills (records where along the bar the jaws closed) + the task's per-step monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class LoadedBeam(SlipperyLift): + name = "l5_loaded_beam" + level = "L5" + category = "dynamics_adaptation" + capabilities = ("Perceive", "Reason", "Plan", "Utilize") + protocol = "cross" + max_attempts = 3 + agent_max_steps = 40 + instruction = ("Lift the metal bar together with the two small red blocks resting near its ends, and hold it level " + "(tilted less than 8 degrees) with its lowest point at least 10 cm above the table. Both blocks must " + "stay on the bar near its ends. Keep holding the bar when you finish.") + instruction_indirect = ("Raise the long grey rod with the two little red cubes sitting near its ends and hold it " + "horizontal (tilted less than 8 degrees), its lowest point at least 10 cm above the table. " + "Both cubes must stay on the rod near its ends. Keep holding the rod when you finish.") + + # ------------------------------------------------------------ scene + def make_bddl(self): + bar = register_generated("LffBeamBar", weighted_box_xml("lff_beam_bar", HALF, (0.52, 0.55, 0.58, 1.0))) + dens = LOAD_MASS / (2 * LOAD_H) ** 3 + la = register_generated("LffBeamBlockA", box_xml("lff_beam_block_a", (LOAD_H,) * 3, LOAD_RGBA, density=dens)) + lb = register_generated("LffBeamBlockB", box_xml("lff_beam_block_b", (LOAD_H,) * 3, LOAD_RGBA, density=dens)) + # LIBERO's sampler puts the bar anywhere within +-13 cm of its region's centre (it "keeps the bar's 14 cm + # radius inside" a 2 cm region) and rejects block placements closer than 14 + 1.8 cm to it: the block regions + # are >= 19 cm from every possible bar position (the first layout, 2 cm beside the bar's range, failed with + # "Cannot place all objects" in 13 of 400 resets, this one 0 of 400). apply_instance moves everything anyway. + objs = [(BAR, bar, "bar_region", (-0.11, -0.01, -0.09, 0.01)), + ("block_1", la, "block1_region", (-0.11, 0.32, -0.09, 0.34)), + ("block_2", lb, "block2_region", (-0.11, -0.34, -0.09, -0.32))] + return write_bddl(self.name, "lift the loaded bar and hold it level", objs) + + def __init__(self, cam_res=None): + self.mon = None + self.budget = None # scripted policies only: command budget of the current attempt + self.ncmd = 0 + super().__init__(cam_res) + + def sample_instance(self, seed): + inst = super().sample_instance(seed) # same bar layout and hidden weight as l5_slippery_lift for this seed + m = inst["mass"] + inst.update(load_mass=LOAD_MASS, slot=SLOT, + com_total=float(m * inst["com_offset"] / (m + 2 * LOAD_MASS))) # bar + both blocks on their ends + return inst + + def apply_instance(self, inst): + super().apply_instance(inst) # bar pose, friction, hidden weight (+ envs.refit_bounds) + x, y = inst["bar_xy"] + for nm in LOADS: + envs.set_obj_pose(self.env, nm, [x, y + LOAD_SIGN[nm] * SLOT, BAR_TOP + LOAD_H + 0.0005]) + if LOAD_MU is not None: + envs.set_friction(self.env, nm, LOAD_MU, priority=3) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.mon = None + self.sk = BeamSkills(self.env, self, recorder=recorder) + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ state + def bar_bottom(self): + return envs.obj_min_z(self.env, BAR) - TZ + + def load_rel(self, nm): + """block centre in the bar frame: (along (+ = towards the bar's left end), side, height above the bar's centre)""" + c, al, side, up = bar_frame(self.env) + r = envs.obj_pos(self.env, nm) - c + return float(r @ al), float(r @ side), float(r @ up) + + def _block_held(self, nm): + sk = self.sk + if sk is None or sk.grip < 0: + return False + if np.linalg.norm(envs.obj_pos(self.env, nm) - sk.eef_pos()) > 0.06: + return False + return sk.holding(nm) + + def load_state(self, nm, tol=SLOT_TOL): + """'slot+' / 'slot-' (on the bar within `tol` of its left / right end position), 'bar' (on the bar + elsewhere), 'held', 'table', 'air' (anything else: falling, resting on the gripper ...)""" + if self._block_held(nm): + return "held" + a, s, u = self.load_rel(nm) + if abs(u - (HALF[2] + LOAD_H)) <= 0.008 and abs(s) <= HALF[0] + 0.003 and abs(a) <= HALF[1] + 0.003: + if abs(a - SLOT) <= tol: + return "slot+" + if abs(a + SLOT) <= tol: + return "slot-" + return "bar" + if envs.obj_pos(self.env, nm)[2] < TZ + 0.027: + return "table" + return "air" + + # ------------------------------------------------------------ monitor + def _init_monitor(self): + st = {nm: self.load_state(nm) for nm in LOADS} + self.mon = dict(stable=dict(st), cand={nm: None for nm in LOADS}, cnt={nm: 0 for nm in LOADS}, + last_on_bar={nm: self.load_rel(nm)[0] for nm in LOADS}, lost=set(), carried=set(), events=[], + lifts=[], + lifted=False, tilted=False, max_tilt=0.0) + + def _event(self, ev, step=None, **kw): + self.mon["events"].append(dict(step=int(self.sk.n_steps if step is None else step), ev=ev, **kw)) + + def _last_grasp(self): + return next((c for c in reversed(self.sk.closes) if c["holding"]), None) + + def monitor_step(self): + mon, sk = self.mon, self.sk + if mon is None or sk is None: + return + n = sk.n_steps + # --- the bar: lifts and tilt + rise = float(envs.obj_pos(self.env, BAR)[2]) - (TZ + HALF[2]) + held = sk.grip > 0 and sk.holding(BAR) + if not mon["lifted"] and held and rise > LIFTED: + g = self._last_grasp() + mon["lifted"], mon["tilted"], mon["max_tilt"] = True, False, 0.0 + mon["lifts"].append(dict(step_up=n, step_down=None, grasp_along=None if g is None else round(g["along"], 4), + max_tilt_deg=0.0, falls=[])) + self._event("bar_lifted", grasp_along=mon["lifts"][-1]["grasp_along"]) + if mon["lifted"]: + t = bar_tilt_deg(self.env) + lift = mon["lifts"][-1] + if abs(t) > abs(lift["max_tilt_deg"]): + lift["max_tilt_deg"] = round(t, 1) + if not mon["tilted"] and abs(t) > TILT_MAX and held: + mon["tilted"] = True + self._event("bar_tilted", tilt_deg=round(t, 1), low_end=_end_word(t)) + if rise < DOWN: + mon["lifted"] = False + lift["step_down"] = n + self._event("bar_set_down", max_tilt_deg=lift["max_tilt_deg"]) + # --- the blocks (debounced state machine) + for nm in LOADS: + # hysteresis: a block that has left its end position must come back within 2 cm of an end to count as + # restored (a block sliding along the tilted bar hovered around the 3 cm limit and flickered) + s = self.load_state(nm, SLOT_TOL - 0.01 if nm in mon["lost"] else SLOT_TOL) + if s in ("slot+", "slot-", "bar"): + mon["last_on_bar"][nm] = self.load_rel(nm)[0] + old = mon["stable"][nm] + if s == old: + mon["cand"][nm], mon["cnt"][nm] = None, 0 + continue + if s != mon["cand"][nm]: + mon["cand"][nm], mon["cnt"][nm] = s, 0 + mon["cnt"][nm] += 1 + if mon["cnt"][nm] < DEBOUNCE: + continue + step = n - DEBOUNCE + 1 + mon["stable"][nm], mon["cand"][nm], mon["cnt"][nm] = s, None, 0 + start = _end_word(LOAD_SIGN[nm]) + if s == "held": + mon["carried"].add(nm) + if s in ("slot+", "slot-"): + if nm in mon["lost"]: + # by_robot: the gripper carried it back (else physics did, e.g. the high-end block sliding back out + # while the bar swings after the other block fell: 3-4 of 59 blind attempts) + mon["lost"].discard(nm) + self._event("load_restored", step, load=nm, start_end=start, end=_end_word(1 if s == "slot+" else -1), + by_robot=nm in mon["carried"]) + mon["carried"].discard(nm) + elif old in ("slot+", "slot-") and s == "bar": + mon["lost"].add(nm) + self._event("load_displaced", step, load=nm, start_end=start, along_cm=round(100 * self.load_rel(nm)[0], 1)) + elif old in ("slot+", "slot-", "bar", "air") and s == "table": + mon["lost"].add(nm) + end = _end_word(mon["last_on_bar"][nm]) + self._event("load_fell", step, load=nm, start_end=start, off_end=end) + if mon["lifted"]: + mon["lifts"][-1]["falls"].append(nm) + elif old == "held" and s == "table": + mon["lost"].add(nm) + self._event("load_removed", step, load=nm, start_end=start) + elif old in ("slot+", "slot-") and s == "held": + mon["lost"].add(nm) # picked up by the agent: counts as lost until it is back on an end + + # ------------------------------------------------------------ outcome / F2 + def _where(self, nm): + """robot-centric description of a block that is not on an end position""" + st = self.load_state(nm) + a, s, u = self.load_rel(nm) + if st == "held": + return "is held in the gripper" + if st == "bar": + e = 1.0 if a >= 0 else -1.0 + return (f"is still on the bar but {100 * (SLOT - abs(a)):.0f} cm in from its {_end_word(e)} end position " + f"({100 * abs(a):.0f} cm {_end_word(e)} of the bar's middle)") + c, al, side, up = bar_frame(self.env) + e = 1.0 if a >= 0 else -1.0 + u = al[:2] / max(np.linalg.norm(al[:2]), 1e-6) # the bar's direction seen from above + end = c[:2] + al[:2] * e * HALF[1] # the end's position seen from above (also while the bar hangs tilted) + r = envs.obj_pos(self.env, nm)[:2] - end + beyond = float(r @ u) * e + lateral = float(r @ np.array([-u[1], u[0]])) + where = "on the table" if st == "table" else "off the bar" + if beyond > 0 and abs(lateral) < 0.04: + return f"lies {where}, {100 * beyond:.0f} cm beyond the bar's {_end_word(e)} end" + fx = f"{100 * abs(r[0]):.0f} cm {'forward' if r[0] > 0 else 'back'}" + fy = f"{100 * abs(r[1]):.0f} cm {'left' if r[1] > 0 else 'right'}" + return f"lies {where}, {fx} and {fy} of the bar's {_end_word(e)} end" + + def outcome(self, inst): + sk, mon = self.sk, self.mon + sk.hold(30) # 1.5 s with the gripper as the agent left it (envs.settle would open the jaws) + held = bool(sk.holding(BAR)) + tilt = bar_tilt_deg(self.env) + bottom = self.bar_bottom() + states = {nm: self.load_state(nm) for nm in LOADS} + on_plus = [nm for nm in LOADS if states[nm] == "slot+"] + on_minus = [nm for nm in LOADS if states[nm] == "slot-"] + loads_ok = len(on_plus) == 1 and len(on_minus) == 1 + level_ok = held and abs(tilt) <= TILT_MAX and bottom >= LIFT_MIN + success = bool(level_ok and loads_ok) + lifted_ever = bool(mon["lifts"]) or (sk.zmax - sk.z0) > 0.03 + g = self._last_grasp() + evs = mon["events"] + falls = [e for e in evs if e["ev"] == "load_fell"] + restored = [e for e in evs if e["ev"] == "load_restored"] + lifts = mon["lifts"] + first_ok = None if not lifts else bool(not lifts[0]["falls"]) # the first lift spilled nothing + # --- text + gtxt = "" + if g is not None: + a = g["along"] + gtxt = (f" You last grasped the bar {100 * abs(a):.1f} cm to the {_end_word(a)} of its middle." + if abs(a) >= 0.0005 else " You last grasped the bar at its middle.") + tilt_txt = (f"hangs tilted by {abs(tilt):.0f} degrees, its {_end_word(tilt)} end lower than its " + f"{_end_word(-tilt)} end") + if success: + failure = None + bar_txt = (f"The bar is held level (tilt {abs(tilt):.0f} degrees), {100 * bottom:.0f} cm above the table, " + "with a block on each end.") + elif held and abs(tilt) > TILT_MAX: + failure = "tilted" + bar_txt = f"The bar did not stay level: it rotated in the gripper and now {tilt_txt}." + if bottom < LIFT_MIN: + bar_txt += f" Its lowest point is {100 * bottom:.0f} cm above the table." + elif held and bottom < LIFT_MIN: + failure = "too_low" + bar_txt = (f"The bar is held level (tilt {abs(tilt):.0f} degrees) but its lowest point is only " + f"{100 * bottom:.0f} cm above the table.") + elif held: + failure = "load_off" + bar_txt = (f"The bar is held level (tilt {abs(tilt):.0f} degrees), {100 * bottom:.0f} cm above the table, " + "but the blocks are not both on its ends.") + elif lifted_ever: + failure = "dropped" + bar_txt = "The bar was lifted but is no longer in the gripper; it lies on the table." + else: + failure = "no_grasp" + bar_txt = ("The gripper never closed on the bar; it is still lying on the table." if not sk.closes else + "The gripper did not catch the bar; it is still lying on the table.") + parts = [bar_txt] + if falls: + f0 = falls[0] + lift = next((l for l in lifts if f0["load"] in l["falls"]), None) + how = (f" while the bar hung tilted by up to {abs(lift['max_tilt_deg']):.0f} degrees with its " + f"{_end_word(lift['max_tilt_deg'])} end lower") if lift and abs(lift["max_tilt_deg"]) > 1 else "" + parts.append(f"The {f0['start_end']} block slid off the bar's {f0['off_end']} end{how}." + + (f" Blocks fell off {len(falls)} times in this attempt." if len(falls) > 1 else "")) + if not loads_ok: + for nm in LOADS: + if states[nm] in ("slot+", "slot-") and (len(on_plus) == 1 or states[nm] != "slot+") and \ + (len(on_minus) == 1 or states[nm] != "slot-"): + continue + parts.append(f"The {_end_word(LOAD_SIGN[nm])} block {self._where(nm)}.") + detail = " ".join(parts) + gtxt + loads = {} + for nm in LOADS: + a, s, u = self.load_rel(nm) + loads[nm] = dict(state=states[nm], along_cm=round(100 * a, 1), side_cm=round(100 * s, 1), + above_bar_centre_cm=round(100 * u, 1)) + out = dict(success=success, failure=failure, held=held, tilt_deg=round(tilt, 1), bottom_cm=round(100 * bottom, 1), + grasp_along=None if g is None else round(g["along"], 4), + stages=dict(bar_held_level_high=bool(level_ok), loads_on_ends=bool(loads_ok)), + loads=loads, loads_on_ends=len(on_plus) + len(on_minus) if loads_ok else + int(len(on_plus) >= 1) + int(len(on_minus) >= 1), + trap_fired=bool(falls), n_load_falls=len(falls), n_restored=len(restored), + n_restored_by_robot=len([e for e in restored if e.get("by_robot")]), + n_regressions=len([e for e in evs if e["ev"] in ("load_fell", "load_displaced")]), + recovered_in_attempt=bool(falls and success), first_interaction_ok=first_ok, + n_lifts=len(lifts), lifts=lifts, events=list(evs), closes=sk.closes, detail=detail) + out["detail_indirect"] = detail.replace("bar", "rod").replace("block", "cube") + return out + + # ------------------------------------------------------------ scripted primitives (agent-command counted) + def _cmd(self, target=None, yaw=None, speed=None, grip=None, tol=0.004, max_steps=250): + """one agent command (move_eef with an optional gripper action, or observe when nothing is given)""" + self.ncmd += 1 + if self.budget is not None and self.ncmd > self.budget: + raise _Budget() + sk = self.sk + if target is not None: + t = np.asarray(target, float).copy() + t[2] = max(t[2], TZ + 0.006) # the agent interface does not go below 0.5 cm above the table + sk.move_to(t, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + if grip is not None: + sk.set_gripper(bool(grip)) + + def grasp_lift(self, along, lift=0.15, speed=0.10, dx=0.0): + """open, above the grasp point (jaws across the bar), descend, close, lift, look: 5 commands""" + c, al, side, up = bar_frame(self.env) + g = c + al * float(along) + np.array([dx, 0.0, 0.0]) + z = max(float(c[2]), Z_GRASP) + self._cmd([g[0], g[1], z + 0.10], yaw=YAW_ACROSS, grip=False) + self._cmd([g[0], g[1], z], tol=0.003) + self._cmd(grip=True) + self._cmd([g[0], g[1], z + lift], speed=speed, max_steps=600) + self._cmd() + + def put_down(self): + """lower the held bar onto the table, release, back up: 2 commands""" + e = self.sk.eef_pos() + self._cmd([e[0], e[1], Z_GRASP + 0.003], speed=0.05, grip=False, max_steps=600) + self._cmd([e[0], e[1], Z_GRASP + 0.12]) + + def _block_yaw(self, nm): + """gripper yaw whose jaws close on two faces of the block, preferring jaws that do not reach towards the bar""" + q = envs.obj_quat(self.env, nm) + w, x, y, z = q + psi = float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))) + c, al, side, up = bar_frame(self.env) + p = envs.obj_pos(self.env, nm) + a = float(np.clip((p - c) @ al, -HALF[1], HALF[1])) + v = (p - (c + al * a))[:2] + v = v / max(np.linalg.norm(v), 1e-6) + best = None + for k in range(2): + ang = psi + k * np.pi / 2 # closing direction candidate (a face normal) + n = np.array([np.cos(ang), np.sin(ang)]) + score = abs(n @ v) + if best is None or score < best[0]: + best = (score, ang) + yaw = best[1] + np.pi / 2 # yaw = closing direction + 90 deg (YAW_ACROSS closes along world x) + return float((yaw + np.pi / 2) % np.pi - np.pi / 2) + + def move_block_to_slot(self, nm, sign, tries=2): + """pick a block (from the table or the bar) and set it on the end position `sign`: 6 commands per try""" + sk = self.sk + for _ in range(tries): + p = envs.obj_pos(self.env, nm) + yaw = self._block_yaw(nm) + zg = max(float(p[2]), TZ + 0.008) + self._cmd([p[0], p[1], zg + 0.08], yaw=yaw, grip=False) + self._cmd([p[0], p[1], zg], tol=0.003, grip=True) + self._cmd([p[0], p[1], BAR_TOP + LOAD_H + 0.07]) + if not sk.holding(nm): + continue + c, al, side, up = bar_frame(self.env) + t = c + al * sign * SLOT + ztop = envs.obj_max_z(self.env, BAR) + self._cmd([t[0], t[1], ztop + LOAD_H + 0.06]) + self._cmd([t[0], t[1], ztop + LOAD_H + 0.004], speed=0.05, grip=False) + self._cmd([t[0], t[1], ztop + LOAD_H + 0.08]) + if self.load_state(nm) == ("slot+" if sign > 0 else "slot-"): + return True + return False + + def restore_loads(self): + """put every block that is not on an end position back onto a free end; True if both ends are taken""" + for _ in range(2): + st = {nm: self.load_state(nm) for nm in LOADS} + free = [s for s in (1.0, -1.0) if not any(v == ("slot+" if s > 0 else "slot-") for v in st.values())] + if not free: + return True + loose = [nm for nm in LOADS if st[nm] not in ("slot+", "slot-")] + for sgn in free: + if not loose: + break + c, al, side, up = bar_frame(self.env) + slot = c + al * sgn * SLOT + nm = min(loose, key=lambda b: np.linalg.norm(envs.obj_pos(self.env, b)[:2] - slot[:2])) + loose.remove(nm) + self.move_block_to_slot(nm, sgn) + self._cmd() # look + st = {nm: self.load_state(nm) for nm in LOADS} + return sorted(st.values()) == ["slot+", "slot-"] + + def judge(self): + """what an agent sees after a lift (perfect perception): (all good, tilt, blocks on their ends)""" + tilt = bar_tilt_deg(self.env) + st = sorted(self.load_state(nm) for nm in LOADS) + ok_loads = st == ["slot+", "slot-"] + good = self.sk.holding(BAR) and abs(tilt) <= TILT_MAX - 2 and self.bar_bottom() >= LIFT_MIN + 0.01 and ok_loads + return bool(good), float(tilt), ok_loads + + # ------------------------------------------------------------ scripted policies + def execute(self, inst, params): + self.grasp_lift(params["along"], params.get("lift", 0.15), params.get("speed", 0.10), params.get("dx", 0.0)) + + def default_params(self, inst): + return dict(along=0.0, lift=0.15, speed=0.10) # Sonnet 5.5 (cla4): middle, up to ~15-18 cm at 0.1 m/s + + def oracle_params(self, inst): + return dict(along=float(inst["com_total"]), lift=0.15, speed=0.10) + + def blind_params(self, inst, attempt, rng): + return dict(along=float(rng.normal(0.0, 0.01)), lift=float(rng.uniform(0.12, 0.18)), + speed=float(rng.uniform(0.05, 0.20))) + + MARGIN = 0.008 # a lift that sank towards +y at grasp g says COM > g + MARGIN + STEP = 0.030 # first move towards the end that sank when only one side is bounded + + def bracket(self, obs): + """grasp point from (grasp_along, tilt) observations: the end that sank is the heavy side of that grasp""" + lo, hi = -SAFE_ALONG, SAFE_ALONG + lo_set = hi_set = False + for g, t in obs: + if t > 0: + lo, lo_set = max(lo, g + self.MARGIN), True + else: + hi, hi_set = min(hi, g - self.MARGIN), True + if lo_set and hi_set: + a = 0.5 * (lo + hi) + elif lo_set: + a = lo + self.STEP - self.MARGIN + elif hi_set: + a = hi - self.STEP + self.MARGIN + else: + a = 0.0 + return float(np.clip(a, -SAFE_ALONG, SAFE_ALONG)) + + def adapt_params(self, inst, history): + obs = [o for h in history for o in h["params"].get("obs", [])] + return dict(along=self.bracket(obs)) + + def adaptive_attempt(self, obs): + """lift at the current estimate; if the bar tilts or a block falls: set the bar down, put the blocks back, + regrasp on the side of the end that sank (bracketing), lift again -- while the command budget allows""" + tried = [] + along = self.bracket(obs) + while True: + tried.append(round(along, 4)) + self.grasp_lift(along) + good, tilt, ok_loads = self.judge() + if good: + return tried + g = self._last_grasp() + if abs(tilt) > 3.0 or not ok_loads: + lift = self.mon["lifts"][-1] if self.mon["lifts"] else None + t = tilt if abs(tilt) > 3.0 else (lift["max_tilt_deg"] if lift else 0.0) + if abs(t) > 1.0: + obs.append((g["along"] if g is not None else along, t)) + # a repair = set down (2) + both blocks back (2 x 6: the fallen one and the one that slid to the fingers) + # + look (1) + regrasp, lift, look (5) = 20 commands; without enough budget keep holding the bar as it is + if self.budget is not None and self.ncmd + 20 > self.budget: + return tried + self.put_down() + if not self.restore_loads(): + return tried + along = self.bracket(obs) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """cross protocol with an agent-like command budget per attempt (agent_max_steps; one move_eef with an optional + gripper action, or one observe, = one command). naive / oracle / blind: one lift, no checking. + adaptive: naive in attempt 1 but checks and repairs inside the attempt (`adaptive_attempt`); later attempts + start from the grasp point learned so far.""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history, obs = [], [] + for a in range(k): + self.reset_instance(inst) + self.ncmd, self.budget = 0, self.agent_max_steps + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "adaptive": + params = dict(obs=[]) + else: + raise ValueError(kind) + n0 = len(obs) + try: + if kind == "adaptive": + params["tried"] = self.adaptive_attempt(obs) + else: + self.execute(inst, params) + except _Budget: + params["budget_used_up"] = True + if kind == "adaptive": + params["obs"] = [[round(g, 4), round(t, 1)] for g, t in obs[n0:]] + self.budget = None + out = self.outcome(inst) + out["commands"] = self.ncmd + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history + diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l5_slide.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l5_slide.py new file mode 100644 index 0000000000000000000000000000000000000000..6ee239b7ba2793288aeaaa5e5d4f0a5b11c835f5 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l5_slide.py @@ -0,0 +1,577 @@ +"""L5-A slide_to_target: strike the cube so that it slides on its own and comes to rest inside the target zone. + +Hidden variable: cube-table sliding friction mu (log-uniform in [0.035, 0.10]) -- the cube looks the +same for every mu. With the default push speed the cube overshoots on slippery instances and stops +short on grippy ones; the only way to get it right is to infer from where the cube stopped how hard +to push next time (cf. MemMimic push_cube, iterative pushing). + +Strikes per attempt: not limited (2026-10-19, user). From 2026-10-08 the instruction allowed ONE strike per attempt +(one move command pushing the cube, the gripper advancing at most 4 cm after the first touch), to stop slow pushes that +carry the cube to the target so that friction never matters (exp1 / cla1 Claude, la2 GPT: 0.05 m/s pushes). That rule +also moved within-attempt correction (overshot -> fetch the cube back -> strike again) to the next attempt. The +loophole is now closed by the success rule instead: + +Success: when the attempt ends the cube is at rest, on the table, in the square (see "Target" below), AND it got there +by a free slide of at least D_MIN: from the last moment the robot touched it (any robot or gripper geom, contacts +checked at every 2 ms physics substep; holding it counts as touching) to its final position the cube slid >= D_MIN with +nothing touching it. A touch that leaves a resting cube where it was (< 1 mm) is ignored. This fails a quasi-static push +into the square (free slide 0-1.2 cm measured), placing the cube there with the gripper (0 cm) and putting it just in +front of the square and tapping it (< D_MIN); see the task card for the adversarial checks and why D_MIN = 3 cm. + +Error events: every strike (a robot contact that moved the cube followed by a free slide of >= STRIKE_MIN) is logged +when the cube comes to rest; it is "missed" if the cube then lies outside the square (past / short / beside). +`n_missed_strikes`, `trap_fired` (>= 1 missed strike) and `recovered_in_attempt` (trap fired and the attempt then +succeeded) are in the outcome, as in l7_key_turn; `irrecoverable` = the cube fell off the table or lies outside the +arm's reach (the attempt is not ended for it). + +Observation fix (2026-10-19): a strike used to return while the cube was still sliding, and `observe` does not advance +the simulation, so agents saw the cube half-way (cla2: "2.2 cm short", it then slid to 7.0 cm past the centre). +SlideSkills.move_to / set_gripper now hold the arm still after the motion until the cube is at rest (or WAIT_MAX), +so every reply and image shows the cube where it stopped. The waiting time counts as simulated motion time. + +Target (2026-10-19, user; before: completely inside the square on all four sides, centre within +-1 cm): the agentview +camera looks at the square from the far side (the cube is pushed towards it), and a cube that sticks out past the far +edge by up to ~1 cm covers the far green line but shows < 2 px of red beyond it in the 512 x 512 image, which looks like +"inside / on the line" (self-test: 0.8 cm past the inner edge looked inside). So on the far side the cube may now lie on +the far green line: the instruction says it must not stick out beyond that line; judged, its centre may be up to +TOL_PAST = 2.0 cm past the square's centre (front face <= 4 mm beyond the line's outer edge). From 2.0 cm on, every one +of 25 measured instances shows >= 2 px of red beyond the line (task card). The near side and the sides stay "completely +inside" (+-1 cm): the near-side band cannot be made visible in the agentview by any tolerance (the cube's own body hides +the near line), and relaxing it would let the 0.30 m/s strike pass on short-stopping instances (task card). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, box_xml, register_generated +from ..skills import DT, Skills, _rot_err +from ..task_base import LFFTask, register_task + +CUBE = "cube_1" +CUBE_HALF = 0.02 +D_MIN = 0.03 # the cube's last free slide (after its last contact with the robot) must be at least this long +STRIKE_MIN = 0.01 # a contact that moved the cube, followed by a free slide of >= 1 cm, counts as a strike +TOUCH_MOVE = 0.001 # a contact episode moved the cube if the cube ends >= 1 mm (3-D) from where it was at its start +EP_GAP = 25 # physics substeps (one control step, 50 ms) without robot contact end a contact episode +V_REST, W_REST = 0.003, 0.05 # cube at rest: linear speed below 3 mm/s and angular speed below 0.05 rad/s ... +REST_SUB = 25 # ... for 25 consecutive substeps (50 ms) +WAIT_MAX = 100 # control steps (5 s) a command may hold the arm waiting for the cube to come to rest +ON_TABLE = 0.005 # cube resting on the table: centre within 5 mm of TABLE_Z + CUBE_HALF +OFF_TABLE_Z = envs.TABLE_Z - 0.05 # cube centre below this: it fell off the table +REACH_MARGIN = 0.03 # cube centre this close to the commanded-target limits (agent/tools.py WS_LO / WS_HI): unreachable + + +class CubeWatch: + """Follows the cube at every physics substep (installed on env.sim by reset_instance; outcome() reads it). + + contact episode: substeps with a robot-cube contact, merged across gaps shorter than EP_GAP substeps. Closed + EP_GAP substeps after its last contact; it "moved" the cube if the cube is then >= TOUCH_MOVE from where it was + when the episode began, or still moving. + release: the cube's xy at the last contact of the last episode that moved it, i.e. where its current free slide + began (None while the robot has never moved the cube). + strike: an episode that moved the cube followed by a free slide of >= STRIKE_MIN, logged when the cube comes to + rest (or when the robot touches it again before that: result "interrupted").""" + + def __init__(self, env, target_xy, tol_short, tol_past, tol_across): + m = env.sim.model + self.env = env + self.is_robot = np.zeros(m.ngeom, bool) + self.is_robot[envs.robot_geom_ids(env)] = True + self.is_cube = np.zeros(m.ngeom, bool) + self.is_cube[envs.obj_geom_ids(env, CUBE)] = True + self.qa, self.da = envs.free_joint_addr(env, CUBE) + self.target = np.asarray(target_xy, float) + self.tol = (float(tol_short), float(tol_past), float(tol_across)) # centre offsets: short of / past / beside + self.n_sub = 0 + self.ep = None # open contact episode + self.gap = 0 + self.quiet = 0 # consecutive substeps at rest + self.release = None + self.slide = None # free slide in progress: where it started (cube at the episode start) and was released + self.moves = [] # closed contact episodes that moved the cube + self.strikes = [] + + # ------------------------------------------------------------ state + def pos(self): + return self.env.sim.data.qpos[self.qa:self.qa + 3].copy() + + def at_rest(self): + qv = self.env.sim.data.qvel[self.da:self.da + 6] + return bool(np.linalg.norm(qv[:3]) < V_REST and np.linalg.norm(qv[3:]) < W_REST) + + def judge(self, p): + """Where a cube at p lies relative to the square: (along, across, in / past / short / beside / off). + in = centre at most tol_short short of / tol_past past the square's centre and within tol_across beside it.""" + along, across = float(p[0] - self.target[0]), float(p[1] - self.target[1]) + if abs(p[2] - (envs.TABLE_Z + CUBE_HALF)) > ON_TABLE: + return along, across, "off" + short, past, beside = self.tol + if -short <= along <= past and abs(across) <= beside: + return along, across, "in" + if along > past: + return along, across, "past" + if along < -short: + return along, across, "short" + return along, across, "beside" + + # ------------------------------------------------------------ per substep + def substep(self): + d = self.env.sim.data + n = d.ncon + touch = False + if n: + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + touch = bool(np.any((self.is_robot[g1] & self.is_cube[g2]) | (self.is_robot[g2] & self.is_cube[g1]))) + self.n_sub += 1 + p = self.pos() + rest = self.at_rest() + self.quiet = self.quiet + 1 if rest else 0 + if touch: + if self.ep is None: + if self.slide is not None: + self._end_slide(p, interrupted=not rest) + self.ep = dict(start=p, sub0=self.n_sub) + self.ep["last"] = p + self.ep["sub1"] = self.n_sub + self.gap = 0 + elif self.ep is not None: + self.gap += 1 + if self.gap >= EP_GAP: + self._close(p, rest) + if self.ep is None and self.slide is not None and self.quiet >= REST_SUB: + self._end_slide(p, interrupted=False) + + def _close(self, p, rest): + ep, self.ep = self.ep, None + if np.linalg.norm(p - ep["start"]) < TOUCH_MOVE and rest: + return # touched a resting cube and left it where it was + self.release = ep["last"][:2].copy() + self.moves.append(dict(sub0=ep["sub0"], sub1=ep["sub1"], start=ep["start"].round(4).tolist(), + release=ep["last"].round(4).tolist())) + self.slide = dict(start=ep["start"], release=ep["last"], sub=ep["sub1"]) + + def _end_slide(self, p, interrupted): + s, self.slide = self.slide, None + free = float(np.linalg.norm(p[:2] - s["release"][:2])) + if free < STRIKE_MIN: + return # a push or a put-down, not a strike + along, across, res = self.judge(p) + self.strikes.append(dict(sub=int(s["sub"]), start=s["start"].round(4).tolist(), + release=s["release"].round(4).tolist(), rest=p.round(4).tolist(), + pushed_cm=round(100 * float(np.linalg.norm(s["release"][:2] - s["start"][:2])), 2), + free_slide_cm=round(100 * free, 2), along_err_cm=round(100 * along, 2), + across_err_cm=round(100 * across, 2), + result="interrupted" if interrupted else res, + missed=bool(not interrupted and res != "in"))) + + def flush(self): + """End of attempt: settle the bookkeeping. Returns True if the robot is touching the cube now and that contact + has moved it (then the cube's current free slide is 0).""" + p = self.pos() + if self.ep is not None: + if np.linalg.norm(p - self.ep["start"]) >= TOUCH_MOVE or not self.at_rest(): + self.release = p[:2].copy() + self.slide = None + return True + return False + if self.slide is not None and self.at_rest(): + self._end_slide(p, interrupted=False) + return False + + +def _install_watch(sim, watch): + """Call watch.substep() after every MuJoCo step of this sim (one wrapper per sim, like agent/tools.ContactTracker; + it only reads the state). A fast strike touches the cube for 3-16 substeps (6-32 ms, measured), less than one + control step, so contact checks at control steps alone would miss it.""" + if not getattr(sim, "_lff_slide_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + w = getattr(sim, "_lff_slide_watch", None) + if w is not None: + w.substep() + sim.step = step + sim._lff_slide_wrapped = True + sim._lff_slide_watch = watch + + +class SlideSkills(Skills): + """Skills whose motion commands return only once the cube has come to rest (see the module docstring).""" + + def __init__(self, env, bias=None, recorder=None): + super().__init__(env, bias=bias, recorder=recorder) + self._qa, self._da = envs.free_joint_addr(env, CUBE) + self.waits = [] # (control step, steps waited) for every command that had to wait + + def cube_moving(self): + qv = self.env.sim.data.qvel[self._da:self._da + 6] + return bool(np.linalg.norm(qv[:3]) >= V_REST or np.linalg.norm(qv[3:]) >= W_REST) + + def wait_cube_rest(self): + """Hold the arm where it is until the cube is at rest (two control steps in a row) or WAIT_MAX steps passed. + No wait if the cube is already at rest or is held (it then moves with the arm).""" + if not self.cube_moving() or self.holding(CUBE): + return 0 + p, R = self.eef_pos(), self._R() + quiet = 0 + for k in range(WAIT_MAX): + self._act(p - self.eef_pos(), _rot_err(R, self.eef_mat()), self.grip) + quiet = 0 if self.cube_moving() else quiet + 1 + if quiet >= 2: + break + self.waits.append((self.n_steps, k + 1)) + return k + 1 + + def move_to(self, target, *args, **kwargs): + rep = super().move_to(target, *args, **kwargs) + n = self.wait_cube_rest() + if n: + rep["waited_s"] = round(n * DT, 2) + return rep + + def set_gripper(self, close, steps=15): + rep = super().set_gripper(close, steps) + n = self.wait_cube_rest() + if n: + rep["waited_s"] = round(n * DT, 2) + return rep + + +INNER_HALF = 0.03 # 6 cm square target (inner edge of the outline): near side and sides, the cube's centre within 1 cm +LINE_W = 0.006 +# Far side (away from the robot, facing the agentview camera): the cube may lie on the far line. Instruction: no part of +# it beyond the line's outer edge (centre <= INNER_HALF + LINE_W - CUBE_HALF = 1.6 cm past the centre); judged: centre +# <= 2.0 cm past it, i.e. the front face up to 4 mm beyond the line, which in the 512 x 512 agentview is < 2 px of red +# beyond the line (from 2.0 cm on >= 2 px on all 25 measured instances, task card 2026-10-19). +TOL_PAST = 0.020 + + +def square_frame_xml(model_name, inner_half=INNER_HALF, line_w=LINE_W, + line_rgba=(0.1, 0.55, 0.15, 1.0), fill_rgba=(0.75, 0.92, 0.75, 1.0)): + """Flat, visual-only square drawn on the table: a light fill plus a dark outline (no collisions).""" + o = inner_half + line_w + parts = [((0, 0, 0.0004), (o, o, 0.0004), fill_rgba), + ((0, inner_half + line_w / 2, 0.0010), (o, line_w / 2, 0.0002), line_rgba), + ((0, -inner_half - line_w / 2, 0.0010), (o, line_w / 2, 0.0002), line_rgba), + ((inner_half + line_w / 2, 0, 0.0010), (line_w / 2, o, 0.0002), line_rgba), + ((-inner_half - line_w / 2, 0, 0.0010), (line_w / 2, o, 0.0002), line_rgba)] + g = "\n".join(f' ' for p, sz, c in parts) + return _wrap(model_name, g, 0.0012, o) + + +Z_PUSH = envs.TABLE_Z + 0.02 +V_MIN, V_MAX = 0.12, 0.60 +Z_GRASP = envs.TABLE_Z + CUBE_HALF # grasp point at the cube's centre height (fingertips ~1 cm above the table) + + +@register_task +class SlideToTarget(LFFTask): + name = "l5_slide_to_target" + level = "L5" + category = "dynamics_adaptation" + capabilities = ("Reason", "Utilize") + # no parentheses or semicolons: the instruction is also the BDDL :language string (';' starts a comment there) + instruction = ("Push the red cube straight away from the robot so that it slides and comes to rest in the green " + "square marked on the table. On the side of the square nearest the robot and on its left and " + "right, no part of the cube may lie on or beyond the green border line. On the far side, away from " + "the robot, the cube may lie on the border line, but no part of it may stick out beyond that line. " + "The cube must slide the last part of the way on its own: after it leaves the gripper it has to " + f"slide at least {100 * D_MIN:.0f} cm, with nothing touching it, before it comes to rest in the " + "square.") + instruction_indirect = instruction + tol_along = INNER_HALF - CUBE_HALF # short of the centre (near side): completely inside the square (1.0 cm) + tol_past = TOL_PAST # past the centre (far side): may lie on the far line (2.0 cm, see TOL_PAST) + runup = 0.22 # long run-up so the gripper reaches the commanded speed before contact + tol_across = INNER_HALF - CUBE_HALF + + def make_bddl(self): + cube = register_generated("LffRedCube", box_xml("lff_red_cube", (CUBE_HALF,) * 3, (0.85, 0.15, 0.15, 1), + density=1000)) + # static fixture (no joint): a free body without collisions would fall through the table + zone = register_generated("LffTargetSquare", square_frame_xml("lff_target_square"), free=False) + objs = [("cube_1", cube, "cube_region", (-0.21, -0.01, -0.19, 0.01))] + fixtures = [("zone_1", zone, "zone_region", (-0.11, -0.01, -0.09, 0.01))] + return write_bddl(self.name, self.instruction, objs, fixtures=fixtures) + + def apply_instance(self, inst): + m = self.env.sim.model + zone = self.env.fixtures_dict["zone_1"] + # the target zone is a flat marker: no collisions + for g in range(m.ngeom): + if (m.geom_id2name(g) or "").startswith("zone_1_"): + m.geom_contype[g] = 0 + m.geom_conaffinity[g] = 0 + x0, y0 = inst["cube_xy"] + envs.set_obj_pose(self.env, "cube_1", [x0, y0, envs.TABLE_Z + CUBE_HALF + 0.001]) + bid = m.body_name2id(zone.root_body) + m.body_pos[bid] = [x0 + inst["target_dist"], y0, envs.TABLE_Z + 0.0002] + m.body_quat[bid] = [1.0, 0.0, 0.0, 0.0] + envs.set_friction(self.env, "cube_1", inst["mu"]) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + x0, y0 = inst["cube_xy"] + self.watch = CubeWatch(self.env, (x0 + inst["target_dist"], y0), self.tol_along, self.tol_past, + self.tol_across) + _install_watch(self.env.sim, self.watch) + self.sk = SlideSkills(self.env, recorder=recorder) + return self.sk + + @staticmethod + def max_reach(mu): + """Approximate slide distance at the top speed, fitted to a sweep (runup 0.22 m): + mu 0.04 -> 20.8 cm, 0.06 -> 14.8, 0.08 -> 11.8, 0.10 -> 10.1 cm.""" + return 0.0103 / mu ** 0.95 + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + while True: # reject instances the top speed cannot reach (keeps every instance solvable) + inst = dict(seed=int(seed), + cube_xy=[float(rng.uniform(-0.23, -0.17)), float(rng.uniform(-0.10, 0.10))], + target_dist=float(rng.uniform(0.05, 0.12)), + mu=float(np.exp(rng.uniform(np.log(0.035), np.log(0.10))))) + if inst["target_dist"] <= 0.85 * self.max_reach(inst["mu"]): + return inst + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + envs.settle(self.env, 40) + w = self.watch + for _ in range(12): # still moving (e.g. a budget ended the attempt mid-slide): let it come to rest + if w.at_rest(): + break + envs.settle(self.env, 5) + touching = w.flush() + x0, y0 = inst["cube_xy"] + c = envs.obj_pos(self.env, CUBE) + along = (c[0] - x0) - inst["target_dist"] + across = c[1] - y0 + _, _, where = w.judge(w.pos()) + inside = where == "in" + at_rest = w.at_rest() + free = float(np.linalg.norm(c[:2] - w.release)) if w.release is not None else 0.0 + slid = bool(w.release is not None and not touching and free >= D_MIN) + success = bool(inside and at_rest and slid) + strikes = w.strikes + n_missed = sum(s["missed"] for s in strikes) + from ..agent.tools import WS_HI, WS_LO + reach = bool(np.all(c[:2] >= WS_LO[:2] + REACH_MARGIN) and np.all(c[:2] <= WS_HI[:2] - REACH_MARGIN)) + irrecoverable = bool(c[2] < OFF_TABLE_Z or not reach) + + parts = [] + if w.release is None and np.linalg.norm(c[:2] - np.asarray(inst["cube_xy"])) < STRIKE_MIN: + parts.append("The cube was not pushed.") + if c[2] < OFF_TABLE_Z: + parts.append("The cube fell off the table.") + else: + state = {"in": "in the square", "past": "it sticks out beyond the far green line", + "short": "it sticks out past the edge of the square nearest the robot"}.get(where, + "not in the square") + if along > 0: + parts.append(f"The cube stopped {100 * along:.1f} cm past the centre of the green square ({state}).") + else: + parts.append(f"The cube stopped {100 * -along:.1f} cm short of the centre of the green square " + f"({state}).") + if abs(across) > self.tol_across: + parts.append(f"It also drifted {100 * abs(across):.1f} cm to the {'left' if across > 0 else 'right'} " + f"(robot's view).") + if where == "off" and c[2] > OFF_TABLE_Z: + parts.append("It is not resting on the table.") + if inside and not at_rest: + parts.append("It was still moving when the attempt ended.") + if touching: + parts.append("The gripper was still touching (or holding) the cube when the attempt ended.") + elif inside and w.release is not None and free < D_MIN: + parts.append(f"After it last left the gripper it slid only {100 * free:.1f} cm on its own; it has to slide " + f"at least {100 * D_MIN:.0f} cm.") + if success: + failure = None + elif w.release is None and not inside: + failure = "not_touched" + elif not inside: + failure = "position" + elif not at_rest: + failure = "not_at_rest" + else: + failure = "slide_too_short" + out = dict(success=success, along_err=float(along), across_err=float(across), detail=" ".join(parts), + inside=inside, at_rest=at_rest, free_slide_cm=round(100 * free, 2), + release_xy=None if w.release is None else w.release.round(4).tolist(), + touching_at_end=bool(touching), n_moves=len(w.moves), n_strikes=len(strikes), + n_missed_strikes=int(n_missed), trap_fired=n_missed > 0, + recovered_in_attempt=bool(n_missed and success), irrecoverable=irrecoverable, + strikes=strikes, waits=len(getattr(self.sk, "waits", [])), failure=failure) + return out + + # ------------------------------------------------------------ execution + def execute(self, inst, params): + """One straight strike from the cube's initial position: closed gripper, 22 cm run-up, stop 1.5 cm past the + point of contact, lift (the move returns once the cube has come to rest).""" + x0, y0 = inst["cube_xy"] + sk = self.sk + sk.set_gripper(True, steps=5) + sk.move_to([x0 - self.runup, y0, Z_PUSH + 0.10], yaw=0.0) + sk.move_to([x0 - self.runup, y0, Z_PUSH], tol=0.003) + sk.move_to([x0 - CUBE_HALF + 0.015, y0, Z_PUSH], speed=float(np.clip(params["speed"], V_MIN, V_MAX)), + tol=0.01, max_steps=80) + sk.move_to([x0 - CUBE_HALF + 0.015, y0, Z_PUSH + 0.08], speed=0.3) + + def default_params(self, inst): + return dict(speed=0.30) + + def blind_params(self, inst, attempt, rng): + return dict(speed=float(np.clip(0.30 + rng.normal(0, 0.05), V_MIN, V_MAX))) + + def adapt_params(self, inst, history): + """Cross-attempt learner (one strike per attempt; used by the scripted agent backend): bracketing secant search + on speed using the signed stopping error. validate.py's adaptive policy is run_scripted (within the attempt).""" + pts = sorted((h["params"]["speed"], h["outcome"]["along_err"]) for h in history) + lo = [p for p in pts if p[1] < 0] + hi = [p for p in pts if p[1] > 0] + if lo and hi: + (v0, e0), (v1, e1) = max(lo, key=lambda p: p[0]), min(hi, key=lambda p: p[0]) + v = v0 + (v1 - v0) * (-e0) / (e1 - e0) + elif hi: # always overshooting: slow down + v = min(p[0] for p in hi) * 0.7 + else: # always short: speed up + v = max(p[0] for p in lo) * 1.35 + return dict(speed=float(np.clip(v, V_MIN, V_MAX))) + + def oracle_params(self, inst): + """Privileged: bisection on speed by simulating pushes (uses the true mu).""" + if "_oracle_speed" in inst: + return dict(speed=inst["_oracle_speed"]) + lo, hi = V_MIN, V_MAX + best = None + for _ in range(9): + mid = 0.5 * (lo + hi) + self.reset_instance(inst) + self.execute(inst, dict(speed=mid)) + e = self.outcome(inst)["along_err"] + if best is None or abs(e) < abs(best[1]): + best = (mid, e) + if e > 0: + hi = mid + else: + lo = mid + inst["_oracle_speed"] = best[0] + self.reset_instance(inst) + return dict(speed=best[0]) + + # ------------------------------------------------------------ scripted within-attempt correction + AGENT_CMDS = 40 # robot_server default per-attempt budget (no agent_max_steps here): 40 commands ... + AGENT_SIM_S = 3.0 * AGENT_CMDS # ... and 3 s of simulated motion per command + RESTRIKE_MARGIN = 0.02 # strike again from where the cube stopped only if it is >= D_MIN + this short + + def _strike_here(self, speed): + """Strike the cube where it lies (perfect perception), straight towards +x. 4 agent commands: above the run-up + point + close, down, strike (returns at rest), lift.""" + c = envs.obj_pos(self.env, CUBE) + sk = self.sk + sk.move_to([c[0] - self.runup, c[1], Z_PUSH + 0.10], yaw=0.0) + sk.set_gripper(True, steps=5) + sk.move_to([c[0] - self.runup, c[1], Z_PUSH], tol=0.003) + sk.move_to([c[0] - CUBE_HALF + 0.015, c[1], Z_PUSH], speed=float(np.clip(speed, V_MIN, V_MAX)), tol=0.01, + max_steps=80) + sk.move_to([c[0] - CUBE_HALF + 0.015, c[1], Z_PUSH + 0.08], speed=0.3) + return 4 + + def _carry_back(self, inst): + """Grasp the cube from above, carry it back to its initial position and put it down. 6 agent commands: + above it + open, down + close, lift, carry, down + open, lift.""" + c = envs.obj_pos(self.env, CUBE) + x0, y0 = inst["cube_xy"] + sk = self.sk + sk.move_to([c[0], c[1], Z_GRASP + 0.10], yaw=0.0) + sk.set_gripper(False, steps=10) + sk.move_to([c[0], c[1], Z_GRASP], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([c[0], c[1], Z_GRASP + 0.06]) + sk.move_to([x0, y0, Z_GRASP + 0.06]) + sk.move_to([x0, y0, Z_GRASP + 0.003], tol=0.003) + sk.set_gripper(False, steps=12) + sk.move_to([x0, y0, Z_GRASP + 0.10]) + return 6 + + @staticmethod + def _plan_speed(want, pts): + """Speed for a slide of `want` m from strikes seen so far, pts = [(speed, slide)]: none -> the 0.30 m/s + prior; one -> slide ~ speed^2 through it; several -> log-log interpolation between the bracketing strikes + (or extrapolation from the two nearest, exponent clipped to [0.5, 3]).""" + pts = sorted((v, d) for v, d in pts if d > 0.002) + if not pts: + return 0.30 + if len(pts) == 1: + v, d = pts[0] + return float(np.clip(v * (want / d) ** 0.5, V_MIN, V_MAX)) + lo = [p for p in pts if p[1] <= want] + hi = [p for p in pts if p[1] > want] + if lo and hi: + (v0, d0), (v1, d1) = max(lo, key=lambda p: p[1]), min(hi, key=lambda p: p[1]) + else: + (v0, d0), (v1, d1) = sorted(pts, key=lambda p: abs(np.log(p[1] / want)))[:2] + if abs(np.log(d1 / d0)) < 1e-6 or abs(np.log(v1 / v0)) < 1e-6: + return float(np.clip(v0 * (want / d0) ** 0.5, V_MIN, V_MAX)) + k = float(np.clip(np.log(d1 / d0) / np.log(v1 / v0), 0.5, 3.0)) + return float(np.clip(v0 * (want / d0) ** (1.0 / k), V_MIN, V_MAX)) + + def _adaptive_attempt(self, inst, pts): + """One attempt of the scripted within-attempt learner: strike; look where the cube stopped (perfect + perception, as on the images); if short by >= D_MIN + 2 cm strike again from there, otherwise (overshot, + a little short, or drifted sideways) carry it back to its initial position and strike again, with the speed + planned from every strike seen so far (`pts`, also from earlier attempts). Stops when the cube is in the square + or the next correction would not fit in the agent's command / motion budget.""" + x0, y0 = inst["cube_xy"] + tx = x0 + inst["target_dist"] + sk = self.sk + n0 = sk.n_steps + n_cmd, speeds, path = 0, [], [] + while True: + c = envs.obj_pos(self.env, CUBE) + want = tx - c[0] + near_start = np.linalg.norm(c[:2] - np.asarray(inst["cube_xy"])) < 0.01 + local = [(v, d) for v, d, s in pts if s == near_start] or [(v, d) for v, d, _ in pts] + speed = self._plan_speed(want, local) + n_cmd += self._strike_here(speed) + c1 = envs.obj_pos(self.env, CUBE) + pts.append((speed, float(c1[0] - c[0]), near_start)) + speeds.append(round(speed, 4)) + err, across = float(c1[0] - tx), float(c1[1] - y0) + path.append("strike") + if -self.tol_along <= err <= self.tol_past and abs(across) <= self.tol_across: + break + used_s = (sk.n_steps - n0) * DT + if err < 0 and -err >= D_MIN + self.RESTRIKE_MARGIN and abs(across) < 0.005: + if n_cmd + 4 > self.AGENT_CMDS or used_s + 12.0 > self.AGENT_SIM_S: + break + continue + if n_cmd + 10 > self.AGENT_CMDS or used_s + 30.0 > self.AGENT_SIM_S: + break + n_cmd += self._carry_back(inst) + path.append("carry_back") + return dict(speed=speeds[0], speeds=speeds, path=path, n_commands=n_cmd, + sim_s=round((sk.n_steps - n0) * DT, 1)) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """oracle / naive / blind: one strike per attempt (LFFTask.run_scripted, cross protocol). adaptive: corrects + within the attempt (_adaptive_attempt) and carries what it saw into the next attempt.""" + if kind != "adaptive": + return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt) + k = k or self.max_attempts + history, pts = [], [] + for a in range(k): + self.reset_instance(inst) + params = self._adaptive_attempt(inst, pts) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"]: + break + return history diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l5_slippery_lift.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l5_slippery_lift.py new file mode 100644 index 0000000000000000000000000000000000000000..1a533e41595c29d413eb2287843cbc50afe7d0dc --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l5_slippery_lift.py @@ -0,0 +1,262 @@ +"""L5-B slippery_lift: pick up a heavy, slippery metal bar and hold it level. + +Category dynamics_adaptation (L5): "figure out how this object moves". + +Scene: one long steel-grey bar (4 x 28 x 4 cm, lying along the robot's left-right axis) on the table. It looks +perfectly uniform, but a heavy slug is hidden inside it at an unknown position, so its centre of mass sits +e = 2.5-7 cm from the bar's midpoint, towards the left or the right end. The bar is heavy (0.8-1.2 kg) and its +surface is slippery (finger friction 0.40-0.60): the two finger pads can hold its weight, but they cannot hold +much torque. + +Why the prior fails. The natural grasp is across the bar at its midpoint. With the centre of mass a few cm to +one side, gravity twists the bar in the pads as soon as it is lifted: the heavy end swings down and the bar +ends up hanging tilted by ~10-50 deg (measured). Slow lifting does not help (the torque is static). + +What has to be learned. Which end sank tells on which side of the grasp the centre of mass lies; the grasp +has to move towards that end until it is within ~1.5 cm of the hidden centre of mass (measured window). The +tilt magnitude saturates, so the distance has to be found by bracketing over a few attempts. + +Measured physics (2026-10-07, `l5dyn/bar_win.py`): mass 0.8-1.2 kg, mu 0.4-0.6, lift 15 cm at 0.15 m/s: +|grasp - COM| <= 1.0 cm -> tilt <= 2 deg; 1.5 cm -> 0-41 deg; >= 2 cm -> mostly 30-50 deg; the tilt does not +creep during a 3 s hold. mu 0.8 gave non-monotone tilts and is not used; mu 0.3 + 1.3 kg slips out entirely. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +BAR = "bar_1" +HALF = (0.02, 0.14, 0.02) # 4 (x) x 28 (y) x 4 (z) cm, long axis along world y +_SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"' +W_FRAC = 0.6 # fraction of the bar's mass in the hidden slug +W_HALF = 0.015 # slug half size (for its inertia) +E_MIN, E_MAX = 0.025, 0.070 # |COM offset| from the bar's midpoint (m) +LIFT_MIN = 0.10 # the bar's lowest point must be this high above the table +TILT_MAX = 8.0 # deg +Z_GRASP = envs.TABLE_Z + HALF[2] # gripper site at the bar's mid height (finger tips 0.7 cm above the table) +Z_LIFT = Z_GRASP + 0.15 +YAW_ACROSS = np.pi / 2 # jaws close along world x, i.e. across the bar + + +def weighted_box_xml(name, half, rgba, mass=1.0, friction=(1.0, 0.005, 0.0001)): + """Box with an explicit inertial. Its pos is off-centre at compile time so MuJoCo keeps + body_sameframe = 0 / body_simple = 0 and honours the per-instance body_ipos set in apply_instance.""" + I = [mass / 3 * (half[1] ** 2 + half[2] ** 2), mass / 3 * (half[0] ** 2 + half[2] ** 2), + mass / 3 * (half[0] ** 2 + half[1] ** 2)] + g = (f' \n' + f' \n' + f' ') + return _wrap(name, g, half[2], float(np.hypot(half[0], half[1]))) + + +def set_hidden_weight(env, obj, half, mass, w_frac, w_pos, w_half=W_HALF): + """Uniform shell of mass (1 - w_frac) * mass plus a hidden cube slug of w_frac * mass at w_pos (body frame). + Sets the body's mass, centre of mass and inertia; returns the centre of mass (body frame).""" + m = env.sim.model + bid = envs.body_id(env, obj) + ms, mw = (1 - w_frac) * mass, w_frac * mass + w_pos = np.asarray(w_pos, float) + c = mw * w_pos / mass + hx, hy, hz = half + + def par(mm, r): # parallel-axis terms (diagonal) + return mm * np.array([r[1] ** 2 + r[2] ** 2, r[0] ** 2 + r[2] ** 2, r[0] ** 2 + r[1] ** 2]) + + I = (ms / 3 * np.array([hy ** 2 + hz ** 2, hx ** 2 + hz ** 2, hx ** 2 + hy ** 2]) + par(ms, -c) + + mw / 6 * (2 * w_half) ** 2 * np.ones(3) + par(mw, w_pos - c)) + m.body_mass[bid] = mass + m.body_ipos[bid] = c + m.body_iquat[bid] = [1.0, 0.0, 0.0, 0.0] + m.body_inertia[bid] = I + envs.refit_bounds(env, bid) # the collision BVH lives in the inertial frame (envs.refit_bounds) + return c + + +def bar_axis(env): + """World direction of the bar's long axis (body y).""" + return env.sim.data.body_xmat[envs.body_id(env, BAR)].reshape(3, 3)[:, 1].copy() + + +def bar_tilt_deg(env): + """Signed tilt of the bar's long axis from horizontal; > 0: the bar's +y end is lower.""" + ax = bar_axis(env) + if ax[1] < 0: # orient the axis towards the robot's left so the sign is about world left/right + ax = -ax + return float(np.degrees(np.arcsin(np.clip(-ax[2], -1.0, 1.0)))) + + +def side_words(sign): + return "left (+y)" if sign > 0 else "right (-y)" + + +class BarSkills(Skills): + """Skills that record where along the bar the jaws closed, whoever drives them (scripted or agent).""" + + def __init__(self, env, bias=None, recorder=None): + super().__init__(env, bias=bias, recorder=recorder) + self.closes = [] + self.zmax = float(envs.obj_pos(env, BAR)[2]) + self.z0 = self.zmax + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.zmax = max(self.zmax, float(envs.obj_pos(self.env, BAR)[2])) + + def set_gripper(self, close, steps=15): + rep = super().set_gripper(close, steps) + if close: + c = envs.obj_pos(self.env, BAR) + ax = bar_axis(self.env) + if ax[1] < 0: + ax = -ax + along = float((self.eef_pos() - c) @ ax) # + : grasp on the left (+y) side of the midpoint + self.closes.append(dict(along=along, holding=self.holding(BAR), step=self.n_steps)) + return rep + + +@register_task +class SlipperyLift(LFFTask): + name = "l5_slippery_lift" + level = "L5" + category = "dynamics_adaptation" + capabilities = ("Perceive", "Reason", "Utilize") + protocol = "cross" + instruction = ("Pick up the metal bar and hold it level (tilted less than 8 degrees), with its lowest point at " + "least 10 cm above the table. Keep holding it when you finish.") + instruction_indirect = ("Pick up the long grey rod lying on the table and hold it horizontal (tilted less than 8 " + "degrees), with its lowest point at least 10 cm above the table. Keep holding it when you " + "finish.") + + # ------------------------------------------------------------ scene + def make_bddl(self): + bar = register_generated("LffSteelBar", weighted_box_xml("lff_steel_bar", HALF, (0.52, 0.55, 0.58, 1.0))) + objs = [(BAR, bar, "bar_region", (-0.11, -0.01, -0.09, 0.01))] + return write_bddl(self.name, "pick up the bar and hold it level", objs) # BDDL cannot parse parentheses + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + e = float(rng.choice([-1.0, 1.0]) * rng.uniform(E_MIN, E_MAX)) + return dict(seed=int(seed), + bar_xy=[float(rng.uniform(-0.12, -0.03)), float(rng.uniform(-0.06, 0.06))], + com_offset=e, # along the bar, + = towards the robot's left (+y) end + mass=float(rng.uniform(0.8, 1.2)), + mu=float(rng.uniform(0.40, 0.60))) + + def apply_instance(self, inst): + x, y = inst["bar_xy"] + envs.set_obj_pose(self.env, BAR, [x, y, envs.TABLE_Z + HALF[2] + 0.001]) + envs.set_friction(self.env, BAR, inst["mu"]) + set_hidden_weight(self.env, BAR, HALF, inst["mass"], W_FRAC, [0.0, inst["com_offset"] / W_FRAC, 0.0]) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = BarSkills(self.env, bias=self.skill_bias(inst), recorder=recorder) + return self.sk + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + sk = self.sk + sk.hold(30) # 1.5 s with the gripper as the agent left it (envs.settle would open the jaws) + held = sk.holding(BAR) + tilt = bar_tilt_deg(self.env) + bottom = envs.obj_min_z(self.env, BAR) - envs.TABLE_Z + lifted = (sk.zmax - sk.z0) > 0.03 + close = next((c for c in reversed(sk.closes) if c["holding"]), sk.closes[-1] if sk.closes else None) + success = bool(held and abs(tilt) <= TILT_MAX and bottom >= LIFT_MIN) + out = dict(success=success, held=bool(held), tilt_deg=round(tilt, 1), bottom_cm=round(100 * bottom, 1), + grasp_along=None if close is None else round(close["along"], 4)) + g = "" + if close is not None and close["holding"]: + a = close["along"] + g = (f" You grasped the bar {100 * abs(a):.1f} cm to the {side_words(a)} of its midpoint." + if abs(a) >= 0.0005 else " You grasped the bar at its midpoint.") + tilt_txt = (f"hangs tilted by {abs(tilt):.0f} degrees, its {side_words(tilt).split()[0]} end lower than its " + f"{side_words(-tilt).split()[0]} end") + if success: + out["failure"] = None + detail = f"The bar is held level (tilt {abs(tilt):.0f} degrees), {100 * bottom:.0f} cm above the table." + g + elif held and abs(tilt) > TILT_MAX: + out["failure"] = "tilted" + detail = ("The bar did not stay level: it rotated in the gripper while it was being lifted and now " + f"{tilt_txt}." + g) + if bottom < LIFT_MIN: + detail += f" Its lowest point is {100 * bottom:.0f} cm above the table." + elif held: + out["failure"] = "too_low" + detail = (f"The bar is held level (tilt {abs(tilt):.0f} degrees) but its lowest point is only " + f"{100 * bottom:.0f} cm above the table." + g) + elif lifted: + out["failure"] = "dropped" + detail = ("The bar was lifted but slipped out of the gripper and fell back onto the table " + f"(it now lies tilted by {abs(tilt):.0f} degrees)." + g) + elif close is None: + out["failure"] = "no_grasp" + detail = "The gripper never closed on the bar; it is still lying on the table." + else: + out["failure"] = "no_grasp" + detail = "The gripper closed but did not catch the bar; it is still lying on the table." + out["detail"] = detail + out["detail_indirect"] = detail.replace("bar", "rod") + return out + + def feedback(self, inst, out, level="F2", indirect=False): + if indirect and level == "F2": + out = dict(out, detail=out.get("detail_indirect", out["detail"])) + return super().feedback(inst, out, level) + + # ------------------------------------------------------------ scripted execution (cross protocol) + def execute(self, inst, params): + """Grasp across the bar at `along` (m from the visible midpoint, + = left / +y) and lift 15 cm.""" + sk = self.sk + c = envs.obj_pos(self.env, BAR) # visible bar pose (perfect perception) + ax = bar_axis(self.env) + if ax[1] < 0: + ax = -ax + g = c + ax * float(params["along"]) + sk.set_gripper(False, steps=5) + sk.move_to([g[0], g[1], Z_GRASP + 0.10], yaw=YAW_ACROSS) + sk.move_to([g[0], g[1], Z_GRASP], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([g[0], g[1], Z_LIFT], speed=0.15, tol=0.004, max_steps=300) + + def default_params(self, inst): + return dict(along=0.0) + + def oracle_params(self, inst): + return dict(along=float(inst["com_offset"])) + + MARGIN = 0.008 # a tilt towards +y at grasp g means COM > g + MARGIN (window is ~+-1.5 cm) + STEP = 0.030 # first step towards the heavy end when only one side is bounded + + def adapt_params(self, inst, history): + """Bracketing on the grasp point: the end that sank is the heavy side of the last grasp.""" + lo, hi = -HALF[1], HALF[1] + lo_set = hi_set = False + for h in history: + o = h["outcome"] + g = o["grasp_along"] if o.get("grasp_along") is not None else h["params"]["along"] + if o.get("failure") == "tilted" or (o.get("failure") == "dropped" and abs(o["tilt_deg"]) > 3): + if o["tilt_deg"] > 0: # left end sank -> COM left of the grasp + lo, lo_set = max(lo, g + self.MARGIN), True + else: + hi, hi_set = min(hi, g - self.MARGIN), True + last = history[-1]["params"]["along"] + if lo_set and hi_set: + a = 0.5 * (lo + hi) + elif lo_set: + a = lo + self.STEP - self.MARGIN + elif hi_set: + a = hi - self.STEP + self.MARGIN + else: # no direction information (e.g. too low): repeat + a = last + return dict(along=float(np.clip(a, -0.12, 0.12))) + + def blind_params(self, inst, attempt, rng): + return dict(along=float(rng.normal(0.0, 0.01))) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l5_tablecloth_pull.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l5_tablecloth_pull.py new file mode 100644 index 0000000000000000000000000000000000000000..d80d949cb344b6f76199ae9a4dbdeaa0ca800a66 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l5_tablecloth_pull.py @@ -0,0 +1,392 @@ +"""L5-C tablecloth_pull: yank a board out from under a cube so that the cube lands inside a band. + +Category dynamics_adaptation (L5): "figure out how this object moves". Replaces l5_tip_threshold, which could not +be built robustly with this robot (see task_cards/l5_tip_threshold.md). + +Scene: a 30 x 8 x 1 cm wooden board lies on the table, pointing away from the robot, with a black handle block +at its near end. A red 4 cm cube stands on the far part of the board. A green band (6 cm deep, across the +table) is painted on the table under the board, a few cm closer to the robot than the cube. The agent may touch +only the board / handle, never the cube. + +Physics. If the board is pulled slowly the cube rides along on it (static friction). If it is yanked, the board +slides out from under the cube; while it slides, friction drags the cube a little towards the robot, so the +cube drops onto the table having moved d towards the robot. d DEcreases with the pull speed (counter-intuitive: +a harder yank moves the cube less) and increases with the cube-board friction mu. + +Hidden variable: the cube's friction mu (0.08-0.15; the cube looks the same for every mu), which shifts the whole +speed -> displacement curve and the speed below which the cube rides along. + +Why the prior fails. The classic tablecloth prior is to yank as fast as possible (0.6 m/s, the arm's top speed); +the band is always placed >= 1.3 cm beyond the displacement such a yank produces, so the cube lands short of it. F2 reports where the cube ended relative to the band (robot-frame words, cm) or that it +rode along; the agent has to infer which way to change the pull speed (faster = less displacement) and by how +much. + +Rule (stated in the instruction and enforced, 2026-10-08): ONE pull. Only one move command may drive the board +(>= PULL_EPS), the cube must still be where it started (<= PRE_TOL, grasp nudges) when that pull begins, and all +other move commands together may drive the board at most STRAY_MAX. Gripper open / close commands never count. +Without it every cla2 success (Sonnet, 4/4) dragged the board slowly first so that the cube rode to the band and the +last pull only added a little (one dragged it 4 cm, then yanked it sideways; one moved it with 11 commands, most +of them open-gripper strikes): the friction never mattered. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +BOARD, CUBE, BAND = "board_1", "cube_1", "band_1" +B_HALF = (0.15, 0.04, 0.005) # 30 x 8 x 1 cm +H_HALF = (0.0125, 0.02, 0.015) # handle 2.5 x 4 x 3 cm on top of the near end +C_HALF = 0.02 # 4 cm cube +LF = 0.05 # cube centre to the board's far edge +BAND_HALF_X = 0.03 # band 6 cm deep: the 4 cm cube must be fully inside -> centre within +-1 cm +BAND_HALF_Y = 0.12 +LINE_W = 0.005 +TOL = BAND_HALF_X - C_HALF +MU_BOARD = 0.3 # board-table friction (fixed) +STROKE = 0.25 # scripted pull length +V_MIN, V_MAX = 0.15, 0.80 +# one-pull rule (2026-10-08). Board motion is the larger of its two ends' 3-D paths and is only counted while the robot +# drives the board (touches it, or it speeds up; a board sliding on its own only slows down), so coasting after a +# strike or a release is not charged to the next command. Measured on the cla2 agent runs and the scripted policy: +# approach moves 0 mm; closing on the handle 0.6-2 mm (agents) / 4.6 mm (script); release after the pull 3-10 mm +# (gripper commands never count as pulls); the loophole drags 13-41 mm per command, open-gripper strikes 11-54 mm. +PULL_EPS = 0.003 # a move command that drives the board this far is a pull +PRE_TOL = 0.01 # the cube may have moved at most this much (grasp nudges) when the pull starts +STRAY_MAX = 0.005 # board motion driven by all the other move commands together (each below PULL_EPS) +ACC_EPS = 0.0002 # board speed-up per control step (m/step) that counts as the robot driving it +_SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"' + + +def board_xml(name): + hp = (-B_HALF[0] + H_HALF[0], 0.0, B_HALF[2] + H_HALF[2]) + wood, black = (0.62, 0.45, 0.28, 1.0), (0.12, 0.12, 0.12, 1.0) + g = (f' \n' + f' \n' + f' \n' + f' \n' + f' ') + # small horizontal radius: only LIBERO's reset-time sampler reads it (the layout is overridden anyway) + return _wrap(name, g, B_HALF[2], 0.03) + + +def band_xml(name, line_rgba=(0.1, 0.55, 0.15, 1.0), fill_rgba=(0.75, 0.92, 0.75, 1.0)): + """Flat visual band across the table (no collisions): light fill + dark lines on its two long edges.""" + hx, hy = BAND_HALF_X, BAND_HALF_Y + parts = [((0, 0, 0.0004), (hx, hy, 0.0004), fill_rgba), + ((hx + LINE_W / 2, 0, 0.0010), (LINE_W / 2, hy, 0.0002), line_rgba), + ((-hx - LINE_W / 2, 0, 0.0010), (LINE_W / 2, hy, 0.0002), line_rgba)] + g = "\n".join(f' ' for p, sz, c in parts) + return _wrap(name, g, 0.0012, 0.03) + + +def d_range(mu): + """Band distances sampled for a given mu (m). Calibrated 2026-10-07 (LF 5 cm, board at x 0.05): the cube + moves d(0.6 m/s) ~ 0.33 * mu - 0.85 cm when yanked at the controller's top speed (mu 0.08 -> 1.8 cm, + 0.10 -> 2.3, 0.12 -> 3.1, 0.15 -> 4.3 cm) and >= 0.5 * mu at a pull ~0.05 m/s above the ride-along speed (0.08 -> 4.1 cm at + 0.35 m/s, 0.15 -> 7.6 cm at 0.45 m/s). The band centre is put ~1.5 cm beyond the top-speed displacement, so + the 'yank as fast as possible' prior always lands the cube short of the band.""" + return 0.33 * mu + 0.0065, 0.50 * mu + + +class ClothSkills(Skills): + """Skills that watch, every control step, whether the robot touches the cube (not allowed) and how each + move_to / gripper command moves the board and the cube (one pull only).""" + + def __init__(self, env, bias=None, recorder=None): + super().__init__(env, bias=bias, recorder=recorder) + m = env.sim.model + self._robot = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith(("gripper0_", "robot0_"))] + self._cube = envs.obj_geom_ids(env, CUBE) + self._board = envs.obj_geom_ids(env, BOARD) + self.touched_cube = False + self.cube0 = envs.obj_pos(env, CUBE) + self._ends = self._board_ends() + self._bstep = 0.0 # board motion in the previous control step + self._seg = None + self.segments = [] # one entry per move_to / set_gripper command + + def _board_ends(self): + """Both ends of the board's long axis (world xyz): their motion also catches turning and tilting.""" + b = envs.obj_pos(self.env, BOARD) + R = self.env.sim.data.body_xmat[envs.body_id(self.env, BOARD)].reshape(3, 3) + return np.stack([b - R[:, 0] * B_HALF[0], b + R[:, 0] * B_HALF[0]]) + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + if not self.touched_cube and envs.contacts_between(self.env, self._robot, self._cube): + self.touched_cube = True + ends = self._board_ends() + step = float(np.max(np.linalg.norm(ends - self._ends, axis=1))) + touch = envs.contacts_between(self.env, self._robot, self._board) + speed_up = step - self._bstep > ACC_EPS + self._ends, self._bstep = ends, step + s = self._seg + if s is not None: + s["path"] += step + s["touch"] += int(touch) + if touch or speed_up: + s["driven"] += step + + def _segment(self, kind, fn, *args, **kwargs): + c0, b0 = envs.obj_pos(self.env, CUBE), envs.obj_pos(self.env, BOARD) + self._seg = dict(kind=kind, step0=self.n_steps, path=0.0, driven=0.0, touch=0) + try: + rep = fn(*args, **kwargs) + finally: + s, self._seg = self._seg, None + c1, b1 = envs.obj_pos(self.env, CUBE), envs.obj_pos(self.env, BOARD) + s.update(steps=self.n_steps - s["step0"], board_dxy=(b1 - b0)[:2].round(4).tolist(), + cube_dxy=(c1 - c0)[:2].round(4).tolist(), cube_from_start=(c0 - self.cube0)[:2].round(4).tolist()) + self.segments.append(s) + return rep + + def move_to(self, target, *args, **kwargs): + return self._segment("move", super().move_to, target, *args, **kwargs) + + def set_gripper(self, close, steps=15): + return self._segment("close" if close else "open", super().set_gripper, close, steps) + + def pull_check(self): + """Pulls (move commands that drove the board >= PULL_EPS), where the cube was when the (first) pull started, + and the board motion driven by the other move commands.""" + moves = [s for s in self.segments if s["kind"] == "move"] + pulls = [s for s in moves if s["driven"] >= PULL_EPS] + stray = sum(s["driven"] for s in moves if s["driven"] < PULL_EPS) + pre = (float(np.linalg.norm(pulls[0]["cube_from_start"])) if pulls + else float(np.linalg.norm((envs.obj_pos(self.env, CUBE) - self.cube0)[:2]))) + return dict(n_pulls=len(pulls), pulls_cm=[round(100 * s["driven"], 1) for s in pulls], + pre_pull_cube_cm=round(100 * pre, 1), stray_cm=round(100 * stray, 2)) + + +@register_task +class TableclothPull(LFFTask): + name = "l5_tablecloth_pull" + level = "L5" + category = "dynamics_adaptation" + capabilities = ("Perceive", "Reason", "Utilize") + protocol = "cross" + instruction = ("Pull the wooden board out from under the red cube so that the cube ends up standing on the table " + "completely inside the green band. Touch only the board and its black handle, never the cube. " + "Only one pull is allowed per attempt: grasp the black handle, pull the board out with ONE move " + "command, then release it. Any other move that drags, pushes or nudges the board, before or after " + "the pull, counts as another pull.") + instruction_indirect = ("Pull the long brown plank out from under the small red block so that the block ends up " + "standing on the table completely inside the green stripe. Touch only the plank and its " + "black handle, never the block. Only one pull is allowed per attempt: grasp the black " + "handle, pull the plank out with ONE move command, then release it. Any other move that " + "drags, pushes or nudges the plank, before or after the pull, counts as another pull.") + + # ------------------------------------------------------------ scene + def make_bddl(self): + board = register_generated("LffClothBoard", board_xml("lff_cloth_board")) + cube = register_generated("LffClothCube", box_xml("lff_cloth_cube", (C_HALF,) * 3, (0.85, 0.15, 0.15, 1.0), + density=2300)) + band = register_generated("LffClothBand", band_xml("lff_cloth_band"), free=False) + objs = [(BOARD, board, "board_region", (0.09, -0.26, 0.11, -0.24)), + (CUBE, cube, "cube_region", (-0.21, 0.24, -0.19, 0.26))] + fixtures = [(BAND, band, "band_region", (-0.31, -0.01, -0.29, 0.01))] + return write_bddl(self.name, "pull the board out from under the cube", objs, fixtures=fixtures) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + mu = float(np.exp(rng.uniform(np.log(0.08), np.log(0.15)))) + lo, hi = d_range(mu) + d = float(rng.uniform(lo, max(lo, hi))) + return dict(seed=int(seed), board_xy=[float(rng.uniform(0.03, 0.08)), float(rng.uniform(-0.08, 0.08))], + mu=mu, band_d=d) + + def cube_start(self, inst): + bx, by = inst["board_xy"] + return np.array([bx + B_HALF[0] - LF, by]) + + def band_center(self, inst): + c = self.cube_start(inst) + return np.array([c[0] - inst["band_d"], c[1]]) + + def apply_instance(self, inst): + m = self.env.sim.model + for g in range(m.ngeom): # the band is a flat marker: no collisions + if (m.geom_id2name(g) or "").startswith(BAND + "_"): + m.geom_contype[g] = 0 + m.geom_conaffinity[g] = 0 + bx, by = inst["board_xy"] + envs.set_obj_pose(self.env, BOARD, [bx, by, envs.TABLE_Z + B_HALF[2] + 0.0005]) + c = self.cube_start(inst) + envs.set_obj_pose(self.env, CUBE, [c[0], c[1], envs.TABLE_Z + 2 * B_HALF[2] + C_HALF + 0.0005]) + envs.set_friction(self.env, BOARD, MU_BOARD, priority=1) + envs.set_friction(self.env, CUBE, inst["mu"], priority=2) # cube-board and cube-table contacts use mu + bid = m.body_name2id(self.env.fixtures_dict[BAND].root_body) + bc = self.band_center(inst) + m.body_pos[bid] = [bc[0], bc[1], envs.TABLE_Z + 0.0002] + m.body_quat[bid] = [1.0, 0.0, 0.0, 0.0] + + def reset_instance(self, inst, recorder=None): + from robosuite.utils.errors import RandomizationError + for _ in range(20): # LIBERO's reset-time placement sampler occasionally fails; the layout is overridden + try: + self.env.reset() + break + except RandomizationError: + continue + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = ClothSkills(self.env, bias=self.skill_bias(inst), recorder=recorder) + return self.sk + + # ------------------------------------------------------------ outcome + def cube_on_board(self): + c = envs.obj_pos(self.env, CUBE) + b = envs.obj_pos(self.env, BOARD) + R = self.env.sim.data.body_xmat[envs.body_id(self.env, BOARD)].reshape(3, 3) + local = R.T @ (c - b) + return bool(abs(local[0]) < B_HALF[0] + 0.005 and abs(local[1]) < B_HALF[1] + 0.005 + and c[2] > envs.TABLE_Z + 2 * B_HALF[2] + C_HALF - 0.004) + + def outcome(self, inst): + sk = self.sk + envs.settle(self.env, 60) + c = envs.obj_pos(self.env, CUBE) + c0 = self.cube_start(inst) + bc = self.band_center(inst) + moved = float(c0[0] - c[0]) # towards the robot + off = c[:2] - bc # + x: cube forward (away from the robot) of the band's centre line + upright = envs.obj_upright_cos(self.env, CUBE) > 0.95 + on_board = self.cube_on_board() + on_table = c[2] < envs.TABLE_Z + C_HALF + 0.004 + in_band = bool(abs(off[0]) <= TOL and abs(off[1]) <= BAND_HALF_Y - C_HALF) + pc = sk.pull_check() + rule = [] + if pc["n_pulls"] > 1: + rule.append(f"The board was moved by {pc['n_pulls']} separate move commands " + f"({', '.join(f'{v:.1f}' for v in pc['pulls_cm'])} cm); only one pull is allowed.") + if pc["n_pulls"] and pc["pre_pull_cube_cm"] > 100 * PRE_TOL: + rule.append(f"When the pull started the cube had already been moved {pc['pre_pull_cube_cm']:.1f} cm by " + f"earlier small moves of the board; only one pull is allowed.") + if pc["stray_cm"] > 100 * STRAY_MAX: + rule.append(f"Besides the pull, other move commands moved the board {pc['stray_cm']:.1f} cm in total; " + f"only one pull is allowed.") + success = bool(in_band and on_table and upright and not on_board and not sk.touched_cube and not rule) + b_moved = float(np.linalg.norm(envs.obj_pos(self.env, BOARD)[:2] - np.asarray(inst["board_xy"]))) + out = dict(success=success, touched_cube=bool(sk.touched_cube), on_board=on_board, upright=bool(upright), + moved_toward_robot=round(moved, 4), band_offset_x=round(float(off[0]), 4), + err=round(float(moved - inst["band_d"]), 4), board_moved=round(b_moved, 4), + one_pull=not rule, **pc) + side = ("forward (+x, away from the robot)" if off[0] > 0 else "backward (-x, toward the robot)") + where = (f"its centre is {100 * abs(off[0]):.1f} cm {side} of the band's centre line" + if abs(off[0]) >= 0.0005 else "its centre is on the band's centre line") + if sk.touched_cube: + out["failure"] = "touched_cube" + detail = "The robot touched the cube, which is not allowed." + elif on_board and b_moved < 0.02: + out["failure"] = "board_not_moved" + detail = "The board was not pulled; the cube is still standing on it." + elif on_board: + out["failure"] = "rode_along" + detail = (f"The board was pulled {100 * b_moved:.0f} cm, but the cube rode along on it: it is still on the " + f"board and moved {100 * moved:.1f} cm toward the robot.") + elif not upright: + out["failure"] = "toppled" + detail = f"The board came out from under the cube, but the cube fell over; {where}." + elif in_band and on_table and upright: + out["failure"] = None + detail = (f"The board came out from under the cube and the cube is standing inside the green band; {where}. " + f"It moved {100 * moved:.1f} cm toward the robot.") + else: + out["failure"] = "missed_band" + detail = (f"The board came out from under the cube and the cube is standing on the table, but not " + f"completely inside the green band: {where}. It moved {100 * moved:.1f} cm toward the robot.") + if rule and not sk.touched_cube: + out["failure"] = "several_pulls" + detail = " ".join(rule) + " " + detail + out["detail"] = detail + out["detail_indirect"] = (detail.replace("board", "plank").replace("cube", "block") + .replace("green band", "green stripe").replace("band's", "stripe's")) + return out + + def feedback(self, inst, out, level="F2", indirect=False): + if indirect and level == "F2": + out = dict(out, detail=out.get("detail_indirect", out["detail"])) + return super().feedback(inst, out, level) + + # ------------------------------------------------------------ scripted execution (cross protocol) + def execute(self, inst, params): + """Grasp the handle (jaws across its 4 cm width) and pull the board STROKE m toward the robot at `speed`.""" + sk = self.sk + b = envs.obj_pos(self.env, BOARD) + hx, hy = b[0] - B_HALF[0] + H_HALF[0], b[1] + zg = envs.TABLE_Z + 2 * B_HALF[2] + H_HALF[2] + sk.set_gripper(False, steps=5) + sk.move_to([hx, hy, zg + 0.08], yaw=0.0) + sk.move_to([hx, hy, zg], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([hx - STROKE, hy, zg], speed=float(np.clip(params["speed"], V_MIN, V_MAX)), tol=0.01, + max_steps=300) + sk.set_gripper(False, steps=8) + sk.move_to([hx - STROKE, hy, zg + 0.10], speed=0.3) + + def default_params(self, inst): + """Prior: the classic tablecloth trick -- yank as fast as the arm can.""" + return dict(speed=0.60) + + def blind_params(self, inst, attempt, rng): + return dict(speed=float(np.clip(0.60 + rng.normal(0, 0.06), V_MIN, V_MAX))) + + def adapt_params(self, inst, history): + """Bracketing search on the pull speed with the signed displacement error (riding along = far too much + displacement). Faster -> less displacement.""" + pts = [] + for h in history: + o = h["outcome"] + if o.get("failure") in ("rode_along", "board_not_moved"): + e = 0.10 + elif o.get("failure") in ("touched_cube", "several_pulls"): + continue + else: + e = o["err"] + pts.append((h["params"]["speed"], e)) + hi_err = [p for p in pts if p[1] > 0] # moved too much -> needs a faster pull + lo_err = [p for p in pts if p[1] < 0] # moved too little -> needs a slower pull + if hi_err and lo_err: + (v0, e0) = max(hi_err, key=lambda p: p[0]) # fastest pull that still moved it too much + (v1, e1) = min(lo_err, key=lambda p: p[0]) # slowest pull that moved it too little + if e0 >= 0.05: # rode along: no usable slope -> bisect + v = 0.5 * (v0 + v1) + else: + v = v0 + (v1 - v0) * e0 / (e0 - e1) + elif hi_err: + v = max(p[0] for p in hi_err) * 1.25 + else: + v = min(p[0] for p in lo_err) * 0.8 + return dict(speed=float(np.clip(v, V_MIN, V_MAX))) + + def oracle_params(self, inst): + """Privileged: bisection on the speed by simulating pulls with the true mu.""" + if "_oracle_speed" in inst: + return dict(speed=inst["_oracle_speed"]) + lo, hi = V_MIN, V_MAX + best = None + for _ in range(10): + mid = 0.5 * (lo + hi) + self.reset_instance(inst) + self.execute(inst, dict(speed=mid)) + o = self.outcome(inst) + e = 0.10 if o["failure"] in ("rode_along", "board_not_moved") else o["err"] + if o["success"]: + best = (mid, e) + break + if best is None or abs(e) < abs(best[1]): + best = (mid, e) + if e > 0: + lo = mid + else: + hi = mid + inst["_oracle_speed"] = best[0] + self.reset_instance(inst) + return dict(speed=best[0]) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l6_count.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l6_count.py new file mode 100644 index 0000000000000000000000000000000000000000..8bfcc8725cbfb523898ced10b2974c65b5b3b82f --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l6_count.py @@ -0,0 +1,562 @@ +"""L6-B count_into_box: put exactly N identical cubes into an opaque drop box; one carry is interrupted by a slip. + +Scene: T identical orange 4 cm cubes scattered on the table and a dark, closed drop box (static fixture) at +one side of the table. The box lid has a square opening on the robot side; a cube released above it falls in, +lands on a low-friction ramp and slides under the closed part of the lid, where no camera can see it (once past +the opening it is moved to a storage slot at the far end, so that cubes never queue back under the opening). +Cubes cannot be taken back out. + +Instruction: put exactly N cubes into the box (N in {4, 5}, given in the instruction). + +Interruption: during the (p+1)-th carry (p cubes are already in the box, p in {1..N-1}, hidden) the carried +cube "slips": the gripper opens and the cube lands back on the table next to the spot it was picked from. The +number of cubes left on the table is R = N + e with e in {0, 1} drawn independently of p (T = R + p), so +neither the box nor the table tells how many cubes are inside: progress ("how many have I put in already") +is only in the agent's own history. Over-filling is irreversible (terminal failure); under-filling can be +completed in a later segment. + +Protocol: within (one episode, no reset), like l6_swap_interrupt. An attempt (segment) ends when the agent +declares done; the outcome is measured; if the box holds fewer than N cubes the agent continues from the +current state. The slip is injected once per episode, inside attempt 1, by a per-control-step monitor (so it +also fires for agents driven by the harness). Events reported immediately (`drain_events`): "A cube dropped +into the box." after every cube that falls in, and the slip. + +Scripted references (perception = simulator state, as in l6_swap): + oracle privileged box count: carries cubes until the box holds N. + adaptive counts its own successful drops (Save), notices the slip (the cube is back on the table, the + drop count is unchanged), carries cubes until its count reaches N (Retrieve + Utilize). Later + segments: if F2 says the box holds fewer than N, adds one cube per segment. + naive memoryless continuation (1 attempt): loses its count at the slip; re-plans from the current frame, + which shows no progress, so it guesses how many cubes are already inside (uniform over 0..N-1) + and adds the rest. + blind memoryless restart (k attempts): at the slip it does not know where it was and starts over + ("the box must get N cubes"), every later segment again puts N cubes in (repeated steps). +Extra controls (not in the acceptance table): `skip` (counts carries instead of drops, i.e. counts the +slipped carry; with memory + F2 it adds the missing cube in segment 2) and `inc1` (stateless, adds one cube +per segment; shows that the within protocol's stop-at-first-success leaks progress to such a policy). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, box_xml, register_generated +from ..task_base import LFFTask, register_task + +CUBE_HALF = 0.02 +CUBE_RGBA = (0.95, 0.50, 0.10, 1.0) +N_CUBES = 11 # objects declared in the BDDL; unused ones are parked on the floor out of view +LETTERS = "ABCDEFGHIJK" +CUBES = [f"cube_{i + 1}" for i in range(N_CUBES)] + +# drop box (local frame: origin at the centre of the footprint on the table top, +x away from the robot) +WALL_T = 0.008 +IN_HX, IN_HY = 0.100, 0.110 # inner half sizes +LID_Z = 0.095 # underside of the lid above the table +LID_T = 0.008 +HOLE_X = (-0.090, -0.020) # opening in the lid (local x range), on the robot side +HOLE_HY = 0.035 +RAMP_Z = (0.045, 0.006) # top surface of the ramp at the near (-x) and far (+x) inner walls +RAMP_T = 0.006 +RAMP_MU = 0.03 +BOX_RGBA = (0.30, 0.20, 0.13, 1.0) +INNER_RGBA = (0.08, 0.07, 0.06, 1.0) +HOLE_C = np.array([(HOLE_X[0] + HOLE_X[1]) / 2, 0.0]) +OUT_HX, OUT_HY = IN_HX + WALL_T, IN_HY + WALL_T +RAMP_SLOPE = (RAMP_Z[0] - RAMP_Z[1]) / (2 * IN_HX) +RAMP_TH = float(np.arctan(RAMP_SLOPE)) +# Storage slots under the closed part of the lid. A cube that has slid past the opening is moved to the next free +# slot (out of every camera's view) so that the cubes do not queue up along the slide line back under the opening. +# Order: the lane straight behind the opening (y = 0) is filled last, so that a newly dropped cube can always slide +# past the opening before it is moved; then a second layer on the far row. (x, y, layer) +_ROW = [IN_HX - CUBE_HALF - 0.002 - 0.044 * r for r in range(2)] +SLOTS = ([(_ROW[r], y, 0) for r in range(2) for y in (-0.088, 0.088, -0.044, 0.044)] + + [(_ROW[0], 0.0, 0), (_ROW[1], 0.0, 0)] + [(_ROW[0], y, 1) for y in (-0.088, 0.088, -0.044, 0.044, 0.0)]) + +BASE_X = -0.66 +REACH = 0.70 # max horizontal distance of a cube from the robot base +CUBE_REGION = (-0.30, 0.07, -0.28, 0.28) +CUBE_MIN_DIST = 0.085 +BOX_CLEAR = 0.12 # cube centre at least this far from the box footprint (the hand must not hit the lid) +Z_GRASP = envs.TABLE_Z + CUBE_HALF +Z_CARRY = envs.TABLE_Z + 0.20 +Z_RELEASE = envs.TABLE_Z + LID_Z + LID_T + 0.012 + CUBE_HALF # cube bottom ~1.2 cm above the lid +PARK = [(-0.5 + 0.1 * i, 1.25) for i in range(N_CUBES)] +LIFTED = 0.05 # slip trigger: cube at least this far above its resting height +HAND_HALF = 0.11 # the Panda hand reaches about this far along the closing axis (it hits 4 cm cubes there) +HAND_CLEAR = 0.06 # neighbour centre at least this far from that segment for a collision-free grasp + + +def hand_box_clear(p, a, box, half=HAND_HALF): + """Smallest distance from the hand segment (closing axis at yaw a) to the drop box footprint.""" + ax = np.array([-np.sin(a), np.cos(a)]) + return min(float(np.linalg.norm(np.maximum(np.abs(np.asarray(p) + t * ax - box) - [OUT_HX, OUT_HY], 0.0))) + for t in np.linspace(-half, half, 9)) + + +def axis_clear(p, a, others, half=HAND_HALF): + """Smallest distance from a neighbour centre to the hand segment p +- half * (closing axis at yaw a).""" + ax = np.array([-np.sin(a), np.cos(a)]) + best = 1.0 + for o in others: + v = np.asarray(o) - p + t = float(np.clip(v @ ax, -half, half)) + best = min(best, float(np.linalg.norm(v - t * ax))) + return best + + +def drop_box_xml(model_name): + """Closed box with a square opening in the lid and an internal ramp (static fixture, collisions on).""" + parts = [] # (pos, half size, rgba, quat or None, friction or None) + H = LID_Z / 2 + # walls + parts.append(((IN_HX + WALL_T / 2, 0, H), (WALL_T / 2, OUT_HY, H), BOX_RGBA)) + parts.append(((-IN_HX - WALL_T / 2, 0, H), (WALL_T / 2, OUT_HY, H), BOX_RGBA)) + parts.append(((0, IN_HY + WALL_T / 2, H), (IN_HX, WALL_T / 2, H), BOX_RGBA)) + parts.append(((0, -IN_HY - WALL_T / 2, H), (IN_HX, WALL_T / 2, H), BOX_RGBA)) + # lid around the opening + zc = LID_Z + LID_T / 2 + x0, x1 = HOLE_X + parts.append((((-OUT_HX + x0) / 2, 0, zc), ((x0 + OUT_HX) / 2, OUT_HY, LID_T / 2), BOX_RGBA)) # near strip + parts.append((((x1 + OUT_HX) / 2, 0, zc), ((OUT_HX - x1) / 2, OUT_HY, LID_T / 2), BOX_RGBA)) # far part + for s in (-1, 1): + parts.append((((x0 + x1) / 2, s * (HOLE_HY + OUT_HY) / 2, zc), ((x1 - x0) / 2, (OUT_HY - HOLE_HY) / 2, + LID_T / 2), BOX_RGBA)) + # floor (dark) and ramp + parts.append(((0, 0, 0.002), (IN_HX, IN_HY, 0.002), INNER_RGBA)) + dz = RAMP_Z[0] - RAMP_Z[1] + th = float(np.arctan2(dz, 2 * IN_HX)) + L = float(np.hypot(dz, 2 * IN_HX)) / 2 + zmid = (RAMP_Z[0] + RAMP_Z[1]) / 2 - RAMP_T / 2 / np.cos(th) + ramp = ((0, 0, zmid), (L, IN_HY - 0.001, RAMP_T / 2), INNER_RGBA, (np.cos(th / 2), 0, np.sin(th / 2), 0), RAMP_MU) + geoms = [] + for k, p in enumerate(parts + [ramp]): + pos, half, rgba = p[:3] + quat = p[3] if len(p) > 3 else None + mu = p[4] if len(p) > 4 else None + q = f' quat="{_fmt(quat)}"' if quat is not None else "" + fr = f' friction="{mu} 0.005 0.0001" priority="2"' if mu is not None else ' friction="1.0 0.005 0.0001"' + geoms.append(f' ') + geoms.append(f' ') + return _wrap(model_name, "\n".join(geoms), (LID_Z + LID_T) / 2, float(np.hypot(OUT_HX, OUT_HY))) + + +def _wrap_q(a): + """cubes are symmetric under 90 deg rotations: wrap to [-pi/4, pi/4)""" + return float((a + np.pi / 4) % (np.pi / 2) - np.pi / 4) + + +@register_task +class CountIntoBox(LFFTask): + name = "l6_count_into_box" + level = "L6" + category = "procedural_memory" + capabilities = ("Perceive", "Save", "Retrieve", "Utilize") + protocol = "within" + agent_max_steps = 80 # robot commands per attempt for agents (a VLM needs ~40-55) + max_attempts = 5 + _TEMPLATE = ("Put exactly {n} of the orange cubes into the dark box, through the opening in its lid. " + "Cubes cannot be taken back out of the box.") + _TEMPLATE_INDIRECT = ("Drop exactly {n} of the small orange blocks into the closed brown container through the " + "square hole in its top. Blocks cannot be taken back out of the container.") + instruction = _TEMPLATE.format(n="N") # replaced per instance (sample_instance / agent_instruction) + instruction_indirect = _TEMPLATE_INDIRECT.format(n="N") + inject = True + announce_drops = True # False: no "A cube dropped into the box." event (harder variant, counting from images) + agent_object_names = ["orange cube (several identical)", "drop box"] + + WORDS = {3: "three", 4: "four", 5: "five", 6: "six"} + + def agent_instruction(self, inst, variant="direct"): + t = self._TEMPLATE_INDIRECT if variant == "indirect" else self._TEMPLATE + return t.format(n=self.WORDS[inst["n_target"]]) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + self._mon = False + orig_step = self.env.step + + def step(action): # per-control-step monitor: also sees attempts driven by the agent harness + ret = orig_step(action) + if self._mon: + self._monitor() + return ret + + self.env.step = step + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs = [] + for i, L in enumerate(LETTERS[:N_CUBES]): + cat = register_generated(f"LffCountCube{L}", box_xml(f"lff_count_cube_{L.lower()}", (CUBE_HALF,) * 3, + CUBE_RGBA, density=600)) + gx, gy = -0.30 + 0.15 * (i % 4), -0.40 + 0.2 * (i // 4) + objs.append((CUBES[i], cat, f"c{i + 1}_region", (gx - 0.01, gy - 0.01, gx + 0.01, gy + 0.01))) + box = register_generated("LffDropBox", drop_box_xml("lff_drop_box"), free=False) + fx = [("drop_box_1", box, "box_region", (0.19, 0.39, 0.21, 0.41))] + return write_bddl(self.name, self._TEMPLATE.format(n="N"), objs, fx) + + def _box_body(self): + return self.env.sim.model.body_name2id(self.env.fixtures_dict["drop_box_1"].root_body) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + n = int(rng.choice([4, 5])) + p = int(rng.integers(1, n)) # cubes already inside when the slip happens + e = int(rng.integers(0, 2)) + T = n + e + p + for _ in range(500): + side = int(rng.choice([-1, 1])) + box = np.array([rng.uniform(-0.08, -0.02), side * rng.uniform(0.22, 0.25)]) + P = np.column_stack([rng.uniform(*CUBE_REGION[:2], 800), rng.uniform(*CUBE_REGION[2:], 800)]) + P = P[np.hypot(P[:, 0] - BASE_X, P[:, 1]) <= REACH] + P = P[np.linalg.norm(np.maximum(np.abs(P - box) - np.array([OUT_HX, OUT_HY]), 0.0), axis=1) >= BOX_CLEAR] + cubes = [] + for c in P: # random sequential addition + if all(np.linalg.norm(c - q) >= CUBE_MIN_DIST for q in cubes): + cubes.append(c) + if len(cubes) == T: + break + if len(cubes) < T: + continue + yaws = [] # each cube gets a yaw whose (small-rotation) grasp axis is free for the hand + for i in range(T): + oth = [cubes[j] for j in range(T) if j != i] + for _ in range(30): + y = float(rng.uniform(-np.pi / 4, np.pi / 4)) + if axis_clear(cubes[i], y, oth) >= HAND_CLEAR and hand_box_clear(cubes[i], y, box) >= 0.035: + # |y| <= 45 deg: the grasp needs no large wrist rotation + yaws.append(y) + break + else: + break + if len(yaws) == T: + break + else: + raise RuntimeError("could not sample a layout") + inst = dict(seed=int(seed), n_target=n, p=p, e=e, n_cubes=T, box_xy=box.round(4).tolist(), + cubes=np.array(cubes).round(4).tolist(), + yaws=yaws, + trigger_dist=float(rng.uniform(0.05, 0.09)), + slip_r=float(rng.uniform(0.005, 0.02)), slip_ang=float(rng.uniform(0, 2 * np.pi)), + slip_yaw=float(rng.uniform(-np.pi / 4, np.pi / 4))) + # make_video prints task.instruction: keep it in sync with the last sampled instance + self.instruction = self.agent_instruction(inst, "direct") + self.instruction_indirect = self.agent_instruction(inst, "indirect") + return inst + + def apply_instance(self, inst): + m = self.env.sim.model + bid = self._box_body() + m.body_pos[bid] = [inst["box_xy"][0], inst["box_xy"][1], envs.TABLE_Z] + m.body_quat[bid] = [1, 0, 0, 0] + T = inst["n_cubes"] + for i, c in enumerate(CUBES): + if i < T: + envs.set_obj_pose(self.env, c, [*inst["cubes"][i], envs.TABLE_Z + CUBE_HALF + 0.001], + yaw=inst["yaws"][i]) + else: + envs.set_obj_pose(self.env, c, [*PARK[i], CUBE_HALF + 0.001]) + self.env.sim.forward() + self._inst = inst + self.active = CUBES[:T] + self.slip = None + self.events = [] + self._event_cursor = 0 + self._outcome_cursor = 0 + self.in_box = [] # cubes that fell into the box, in order + self.stored = [] # cubes moved to a storage slot + self._bad = set() # scripted policies: cubes whose grasp failed + self.rest_xy = {c: np.array(inst["cubes"][i]) for i, c in enumerate(self.active)} + self._mon = False + + def reset_instance(self, inst, recorder=None): + self._mon = False + sk = super().reset_instance(inst, recorder=recorder) + self._home = sk.eef_pos() + self._mon = True + return sk + + def go_home(self): + p = self.sk.eef_pos() + self.sk.move_to([p[0], p[1], max(p[2], self._home[2])]) + self.sk.move_to(self._home) + + # ------------------------------------------------------------ geometry helpers + def box_local(self, xyz): + b = self._inst["box_xy"] + return np.array([xyz[0] - b[0], xyz[1] - b[1], xyz[2] - envs.TABLE_Z]) + + def hole_world(self): + b = self._inst["box_xy"] + return np.array([b[0] + HOLE_C[0], b[1] + HOLE_C[1]]) + + def inside_box(self, c): + q = self.box_local(envs.obj_pos(self.env, c)) + return bool(abs(q[0]) < IN_HX and abs(q[1]) < IN_HY and q[2] < LID_Z) + + def on_lid(self, c): + q = self.box_local(envs.obj_pos(self.env, c)) + return bool(abs(q[0]) < OUT_HX + 0.01 and abs(q[1]) < OUT_HY + 0.01 and q[2] >= LID_Z) + + def on_table(self, c): + p = envs.obj_pos(self.env, c) + return bool(p[2] < envs.TABLE_Z + CUBE_HALF + 0.01 and not self.inside_box(c)) + + # ------------------------------------------------------------ monitor (every control step) + def _monitor(self): + env = self.env + for c in self.active: + if c in self.in_box: + if c not in self.stored and self.box_local(envs.obj_pos(env, c))[0] > HOLE_X[1] + 0.02: + self._store(c) + continue + p = envs.obj_pos(env, c) + if self.inside_box(c): + self.in_box.append(c) + if self.announce_drops: + self.events.append(dict(step=int(self.sk.n_steps), kind="drop", obj=c, + text="A cube dropped into the box.")) + continue + if p[2] < envs.TABLE_Z + CUBE_HALF + 0.005: # resting on the table: remember where + self.rest_xy[c] = p[:2].copy() + continue + if (self.inject and self.slip is None and p[2] > envs.TABLE_Z + CUBE_HALF + LIFTED + and len(self.in_box) == self._inst["p"] + and np.linalg.norm(p[:2] - self.rest_xy[c]) >= self._inst["trigger_dist"] + and self.sk.holding(c)): + self._do_slip(c) + + def _store(self, c): + sx, sy, layer = SLOTS[min(len(self.stored), len(SLOTS) - 1)] + b = self._inst["box_xy"] + z = RAMP_Z[0] - (sx + IN_HX) * RAMP_SLOPE + CUBE_HALF / np.cos(RAMP_TH) + 0.002 + layer * (2 * CUBE_HALF + 0.003) + envs.set_obj_pose(self.env, c, [b[0] + sx, b[1] + sy, envs.TABLE_Z + z], + quat_wxyz=[np.cos(RAMP_TH / 2), 0.0, np.sin(RAMP_TH / 2), 0.0]) + self.stored.append(c) + + def _do_slip(self, c): + inst = self._inst + src = self.rest_xy[c] + others = [envs.obj_pos(self.env, o)[:2] for o in self.active if o != c and o not in self.in_box] + xy, yaw = src, inst["slip_yaw"] + found = False + for r in (inst["slip_r"], inst["slip_r"] / 2, 0.0): # next to the pick-up spot, still graspable + cand = src + r * np.array([np.cos(inst["slip_ang"]), np.sin(inst["slip_ang"])]) + if not all(np.linalg.norm(cand - o) >= 0.07 for o in others): + continue + for dy in (0.0, 0.3, -0.3, 0.6, -0.6): + y = _wrap_q(inst["slip_yaw"] + dy) + if axis_clear(cand, y, others) >= HAND_CLEAR and \ + hand_box_clear(cand, y, np.asarray(inst["box_xy"])) >= 0.035: + xy, yaw, found = cand, y, True + break + if found: + break + envs.set_obj_pose(self.env, c, [xy[0], xy[1], envs.TABLE_Z + CUBE_HALF + 0.002], yaw=yaw) + self.sk.grip = -1.0 # the gripper opens + self.env.sim.forward() + text = "A cube slipped out of the gripper and fell back onto the table." + self.slip = dict(obj=c, xy=[float(v) for v in xy], from_xy=[float(v) for v in src], step=int(self.sk.n_steps), + in_box=len(self.in_box)) + self.events.append(dict(step=int(self.sk.n_steps), kind="slip", obj=c, text=text)) + + def drain_events(self): + ev = self.events[self._event_cursor:] + self._event_cursor = len(self.events) + return [e["text"] for e in ev] + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + envs.settle(self.env, 20) + n_in = len(self.in_box) + N = inst["n_target"] + held = [c for c in self.active if self.sk.holding(c)] + n_table = sum(self.on_table(c) for c in self.active if c not in self.in_box) + n_lid = sum(self.on_lid(c) for c in self.active if c not in self.in_box) + success = bool(n_in == N and not held) + terminal = bool(n_in > N) + if success: + head = f"The box holds exactly {N} cubes." + elif terminal: + head = (f"The box holds more than {N} cubes. Cubes cannot be taken out of the box, so the task can no " + f"longer be completed.") + elif n_in == N: + head = f"The gripper is still holding a cube." + else: + head = f"The box holds fewer than {N} cubes." + state = f"Now {n_table} cube{'s are' if n_table != 1 else ' is'} on the table" + if n_lid: + state += f" and {n_lid} on the box lid" + state += "." + # F2 = verdict + currently observable state + the slip of this segment (never the number inside) + new = [e for e in self.events[self._outcome_cursor:] if e["kind"] == "slip"] + self._outcome_cursor = len(self.events) + detail = head + " " + state + if new: + detail = "During this attempt: " + " ".join(e["text"] for e in new) + " " + detail + return dict(success=success, terminal=terminal, n_in_box=n_in, n_target=N, n_table=n_table, n_lid=n_lid, + held=len(held), slip=self.slip, detail=detail) + + # ------------------------------------------------------------ motion (scripted policies) + def _grasp_yaw(self, c): + """The cube's grasp axis with the smaller wrist rotation (|yaw| <= 45 deg). Rotations near +-90 deg drive + the Panda wrist into its joint-6 limit at some positions (measured), so the other axis is used only if + the hand would hit a neighbour or the box on this one.""" + R = self.env.sim.data.body_xmat[envs.body_id(self.env, c)].reshape(3, 3) + yaw = _wrap_q(float(np.arctan2(R[1, 0], R[0, 0]))) + p = envs.obj_pos(self.env, c)[:2] + others = [envs.obj_pos(self.env, o)[:2] for o in self.active if o != c and o not in self.in_box] + box = np.asarray(self._inst["box_xy"]) + + def score(a): + return min(axis_clear(p, a, others), hand_box_clear(p, a, box) + 0.03) + if score(yaw) >= HAND_CLEAR: + return yaw + alt = yaw - np.pi / 2 if yaw >= 0 else yaw + np.pi / 2 + return alt if score(alt) > score(yaw) + 0.02 else yaw + + def _pick(self, c): + sk = self.sk + for _ in range(2): + p = envs.obj_pos(self.env, c) + sk.grasp_at(p[:2], Z_GRASP, yaw=self._grasp_yaw(c), lift=0.12) + if sk.holding(c): + return True + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], Z_GRASP + 0.12]) + return False + + def _carry(self, c): + """Pick cube c and release it above the opening. Returns 'in', 'slipped', 'missed' or 'no_grasp'.""" + n_ev = len(self.events) + n_in = len(self.in_box) + if not self._pick(c): + self._bad.add(c) + self.go_home() # un-wind the arm before the next try + return "no_grasp" + h = self.hole_world() + sk = self.sk + sk.move_to([h[0], h[1], Z_CARRY], yaw=0.0) # the slip may fire here; any yaw fits the opening + if any(e["kind"] == "slip" for e in self.events[n_ev:]): + return "slipped" + sk.move_to([h[0], h[1], Z_RELEASE], tol=0.004) + sk.set_gripper(False, steps=12) + sk.move_to([h[0], h[1], Z_CARRY]) + sk.hold(10) + return "in" if len(self.in_box) > n_in else "missed" + + def _next_cube(self): + """nearest table cube to the opening (what any policy sees in the current frame)""" + h = self.hole_world() + cands = [c for c in self.active if c not in self.in_box and (self.on_table(c) or self.on_lid(c))] + cands = [c for c in cands if c not in self._bad] or cands # try another cube after a failed grasp + if not cands: + return None + return min(cands, key=lambda c: np.linalg.norm(envs.obj_pos(self.env, c)[:2] - h)) + + def _add(self, k, log, stop_on_slip=False): + """Carry until k cubes went in (by the policy's own observation of each drop). Returns (added, slipped).""" + added, slipped = 0, False + guard = 0 + while added < k and guard < 3 * k + 3: + guard += 1 + c = self._next_cube() + if c is None: + break + r = self._carry(c) + log.append(r) + if r == "in": + added += 1 + elif r == "slipped": + slipped = True + if stop_on_slip: + break + return added, slipped + + # ------------------------------------------------------------ scripted references (within protocol) + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed + 7919) + self.reset_instance(inst) + N = inst["n_target"] + history = [] + for a in range(k): + log = [] + plan = dict(kind=kind, carries=log) + if a == 0: + if kind == "oracle": + while len(self.in_box) < N and len(log) < 3 * N + 3: # privileged count + c = self._next_cube() + if c is None: + break + log.append(self._carry(c)) + plan["recovery"] = "oracle: privileged box count" + elif kind in ("adaptive", "skip"): + added, slipped = self._add(N, log) if kind == "adaptive" else (0, False) + if kind == "skip": # counts carries, not drops + n_car = 0 + while n_car < N and len(log) < 3 * N: + c = self._next_cube() + if c is None: + break + r = self._carry(c) + log.append(r) + if r in ("in", "slipped"): + n_car += 1 + if r == "in": + added += 1 + plan["recovery"] = "counts carries (the slipped one too)" + else: + plan["recovery"] = "own drop count; the slipped carry is not counted" + else: # memoryless after the slip + added, slipped = self._add(N, log, stop_on_slip=True) + if slipped: + if kind == "naive": + guess = int(rng.integers(0, N)) + plan["recovery"] = f"memoryless: guesses {guess} already inside, adds {N - guess}" + self._add(N - guess, log) + elif kind == "blind": + plan["recovery"] = f"memoryless restart: puts {N} cubes in" + self._add(N, log) + elif kind == "inc1": + plan["recovery"] = "stateless: adds one cube per segment" + self._add(1, log) + else: + raise ValueError(kind) + else: + plan["recovery"] = "none (no slip)" + else: + if kind in ("adaptive", "skip"): + plan["recovery"] = "memory + F2 'fewer than N': add one cube" + self._add(1, log) + elif kind == "blind": + plan["recovery"] = f"memoryless restart: puts {N} cubes in" + self._add(N, log) + elif kind == "inc1": + plan["recovery"] = "stateless: adds one cube" + self._add(1, log) + elif kind == "oracle": + while len(self.in_box) < N and len(log) < 3 * N + 3: + c = self._next_cube() + if c is None: + break + log.append(self._carry(c)) + else: + raise ValueError(kind) + self.go_home() + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=plan, outcome=out)) + if on_attempt: + on_attempt(a, plan, out) + if out["success"] or out["terminal"] or kind in ("oracle", "naive"): + break + return history + + # cross-protocol hooks are not used by this task + def default_params(self, inst): + return dict(policy="naive") + + def oracle_params(self, inst): + return dict(policy="oracle") diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l6_sequence.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l6_sequence.py new file mode 100644 index 0000000000000000000000000000000000000000..3696302999af83efd1782ea6326db1f794452022 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l6_sequence.py @@ -0,0 +1,513 @@ +"""L6-C sequence_resume: weigh four items one by one in a given order; an emergency stop resets part of the work. + +Scene: four grocery items (cream cheese, butter, chocolate pudding, popcorn -- small flat boxes), each on its +own round pad (four identical dark pads, flat markers), and a scale (grey square platform, static fixture). +Pad / scale positions and the order are random per instance. + +Instruction: weigh the items one at a time in the given order. Weighing = put the item on the scale and let go; +the scale records a reading after the item has rested on it for 0.5 s and beeps. Then the item goes back on its +own pad before the next item is picked up. Every item must be weighed exactly once; the scale log cannot be +edited, so a second reading of an item or a reading out of turn is a terminal failure. + +Interruption ("emergency stop", once per episode, inside attempt 1): while the robot carries an item, the gripper +opens, a safety routine puts that item back on its own pad and the arm returns to its home pose. Hidden: how +many items had been weighed when it happened, w in {1..4} (uniform), and the phase: the carried item was on its +way to the scale (not yet weighed, phase A) or on its way back (already weighed, phase B); w = 4 is always +phase B. After the stop every item sits on its pad and the arm is at home: the picture looks like the start of +the task. Which item comes next (order[w], or "nothing, call done" for w = 4) is only in the agent's own history +(what it carried, whether the scale had beeped). + +Protocol: within (like l6_swap_interrupt). Events reported immediately (`drain_events`): the scale's beep after +every recorded reading, an error beep for a reading out of turn, and the emergency stop. F2 after `done` gives the +verdict, whether the log is complete, and which items are not on their pads (distance only), never how many +items have been weighed. + +Scripted references (perception = simulator state): + oracle privileged scale log: always weighs order[len(log)] next. + adaptive keeps its own record of readings (an item counts as weighed when the scale beeped while it lay on + it); after the stop it resumes from order[len(record)] (redoes the interrupted item in phase A, goes on + with the next one in phase B, calls done when all four are recorded). + naive memoryless continuation (1 attempt): the picture after the stop shows no progress; it guesses how far + it got (uniform over 0..4 items weighed) and continues from there. + blind memoryless restart (k attempts): starts the sequence over from the first item -> a second reading of + an already weighed item (repeated step). +Extra control (not in the acceptance table): `skip` counts items it *started* to weigh (pick-ups) instead of +readings: correct after a phase-B stop, skips the interrupted item after a phase-A stop. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, register_generated +from ..skills import ROT_SCALE, _rot_err +from ..task_base import LFFTask, register_task +from .l6_swap import _pad_xml as _swap_pad_xml + +ITEMS = ["cream_cheese_1", "butter_1", "chocolate_pudding_1", "popcorn_1"] +CATS = {"cream_cheese_1": "cream_cheese", "butter_1": "butter", "chocolate_pudding_1": "chocolate_pudding", + "popcorn_1": "popcorn"} +NAME = {"cream_cheese_1": "cream cheese", "butter_1": "butter", "chocolate_pudding_1": "chocolate pudding", + "popcorn_1": "popcorn"} +DESCR = {"cream_cheese_1": "the pale blue box with the oval logo", "butter_1": "the red box with white lettering", + "chocolate_pudding_1": "the dark brown box", "popcorn_1": "the blue-and-yellow box"} +N_ITEMS = len(ITEMS) +PADS = [f"pad_{i + 1}" for i in range(N_ITEMS)] +PAD_R = 0.055 +PAD_HALF_T = 0.0008 + +SCALE_HALF = 0.06 # platform half size (12 x 12 cm) +SCALE_BASE_HALF = 0.067 +SCALE_TOP = 0.020 # platform top above the table +SCALE_BASE_H = 0.012 +SCALE_RGBA = (0.78, 0.79, 0.80, 1.0) +SCALE_BASE_RGBA = (0.20, 0.20, 0.22, 1.0) + +BASE_X = -0.66 +REGION = (-0.27, 0.05, -0.27, 0.27) +REACH = 0.70 +PAD_MIN = 0.16 +SCALE_MIN = 0.175 +SUCC_R = 0.04 # item centre within 4 cm of its pad centre +GRASP_DZ = 0.012 # gripper-site height above the support surface for a top-down grasp of the flat boxes +Z_CARRY = envs.TABLE_Z + 0.15 +DWELL = 10 # control steps (0.5 s) at rest on the scale before a reading is recorded +LIFTED = 0.04 + + +def scale_xml(model_name): + parts = [((0, 0, SCALE_BASE_H / 2), (SCALE_BASE_HALF, SCALE_BASE_HALF, SCALE_BASE_H / 2), SCALE_BASE_RGBA), + ((0, 0, (SCALE_BASE_H + SCALE_TOP) / 2), (SCALE_HALF, SCALE_HALF, (SCALE_TOP - SCALE_BASE_H) / 2), + SCALE_RGBA)] + g = [] + for k, (pos, half, rgba) in enumerate(parts): + g.append(f' ') + g.append(f' ') + return _wrap(model_name, "\n".join(g), SCALE_TOP / 2, float(np.hypot(SCALE_BASE_HALF, SCALE_BASE_HALF))) + + +def _yaw_of(env, obj): + R = env.sim.data.body_xmat[envs.body_id(env, obj)].reshape(3, 3) + yaw = float(np.arctan2(R[1, 0], R[0, 0])) # long axis of the boxes = body x + return (yaw + np.pi / 2) % np.pi - np.pi / 2 + + +@register_task +class SequenceResume(LFFTask): + name = "l6_sequence_resume" + level = "L6" + category = "procedural_memory" + capabilities = ("Perceive", "Save", "Retrieve", "Utilize") + protocol = "within" + agent_max_steps = 100 # robot commands per attempt for agents (a VLM needs ~60-75) + max_attempts = 5 + _TEMPLATE = ("Weigh the four grocery items one at a time, in this order: {order}. To weigh an item, put it on " + "the grey scale and let go of it; the scale beeps when it has recorded the reading. Then put the " + "item back on its own round pad before you pick up the next item. Weigh every item exactly once: " + "the scale logs every reading, and the log cannot be edited.") + instruction = _TEMPLATE.format(order="(given per instance)") + instruction_indirect = instruction + inject = True + agent_object_names = [NAME[i] for i in ITEMS] + ["scale", "round pads"] + + def agent_instruction(self, inst, variant="direct"): + names = DESCR if variant == "indirect" else NAME + order = [names[o] for o in inst["order"]] + return self._TEMPLATE.format(order=", ".join(order[:-1]) + ", then " + order[-1]) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + self._mon = False + self._latch = None + orig_step = self.env.step + + def step(action): # per-control-step monitor (also for attempts driven by the agent harness) + if self._latch is not None: + action = self._homing_action() + ret = orig_step(action) + if self._mon: + self._monitor() + return ret + + self.env.step = step + + # ------------------------------------------------------------ scene + def make_bddl(self): + pads = [register_generated(f"LffSeqPad{L}", _swap_pad_xml(f"lff_seq_pad_{L.lower()}")) for L in "ABCD"] + scale = register_generated("LffSeqScale", scale_xml("lff_seq_scale"), free=False) + objs = [(o, CATS[o], f"r{i}", (-0.26 + 0.15 * i - 0.01, -0.31, -0.26 + 0.15 * i + 0.01, -0.29)) + for i, o in enumerate(ITEMS)] + objs += [(PADS[i], pads[i], f"p{i}", (-0.26 + 0.15 * i - 0.01, 0.29, -0.26 + 0.15 * i + 0.01, 0.31)) + for i in range(N_ITEMS)] + fx = [("scale_1", scale, "scale_region", (0.19, -0.01, 0.21, 0.01))] + return write_bddl(self.name, "Weigh the four items one at a time in the given order", objs, fx) # no ; in BDDL + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + for _ in range(5000): + pts = [] + while len(pts) < N_ITEMS + 1: + p = np.array([rng.uniform(*REGION[:2]), rng.uniform(*REGION[2:])]) + if np.hypot(p[0] - BASE_X, p[1]) > REACH: + continue + pts.append(p) + scale, pads = pts[0], np.array(pts[1:]) + dp = [np.linalg.norm(pads[i] - pads[j]) for i in range(N_ITEMS) for j in range(i)] + if min(dp) >= PAD_MIN and min(np.linalg.norm(pads - scale, axis=1)) >= SCALE_MIN: + break + else: + raise RuntimeError("could not sample a layout") + order = [ITEMS[i] for i in rng.permutation(N_ITEMS)] + w = int(rng.integers(1, N_ITEMS + 1)) # items weighed when the stop happens + phase = "B" if w == N_ITEMS else str(rng.choice(["A", "B"])) + inst = dict(seed=int(seed), order=order, pads=pads.round(4).tolist(), scale_xy=scale.round(4).tolist(), + item_off=[[float(v) for v in rng.uniform(-0.008, 0.008, 2)] for _ in range(N_ITEMS)], + item_yaw=[float(v) for v in rng.uniform(-0.3, 0.3, N_ITEMS)], + stop_w=w, stop_phase=phase, trigger_dist=float(rng.uniform(0.05, 0.09)), + stop_off=[float(v) for v in rng.uniform(-0.008, 0.008, 2)], + stop_yaw=float(rng.uniform(-0.3, 0.3))) + inst["stop_item"] = order[w] if phase == "A" else order[w - 1] + self.instruction = self.agent_instruction(inst, "direct") # make_video prints task.instruction + self.instruction_indirect = self.agent_instruction(inst, "indirect") + return inst + + def apply_instance(self, inst): + m = self.env.sim.model + for i, p in enumerate(inst["pads"]): + envs.set_obj_pose(self.env, PADS[i], [p[0], p[1], envs.TABLE_Z + PAD_HALF_T + 0.0001]) + bid = m.body_name2id(self.env.fixtures_dict["scale_1"].root_body) + m.body_pos[bid] = [inst["scale_xy"][0], inst["scale_xy"][1], envs.TABLE_Z] + m.body_quat[bid] = [1, 0, 0, 0] + for i, o in enumerate(ITEMS): + p = np.asarray(inst["pads"][i]) + inst["item_off"][i] + envs.place_upright(self.env, o, p, inst["item_yaw"][i]) + self.env.sim.forward() + self._inst = inst + self.pad_of = {o: i for i, o in enumerate(ITEMS)} # item i starts on pad i (pad positions are random) + self.log = [] # scale readings (item names) + self.error = None + self.stop = None + self.events = [] + self._event_cursor = 0 + self._outcome_cursor = 0 + self._dwell = {o: 0 for o in ITEMS} + self._visit = {o: False for o in ITEMS} + self._prev = {} + self._latch = None + self._mon = False + + def reset_instance(self, inst, recorder=None): + self._mon = False + self._latch = None + sk = super().reset_instance(inst, recorder=recorder) + self._home = sk.eef_pos() + self.rest_dz = {o: float(envs.obj_pos(self.env, o)[2] - envs.TABLE_Z) for o in ITEMS} + self._prev = {o: envs.obj_pos(self.env, o) for o in ITEMS} + self._mon = True + return sk + + def go_home(self): + p = self.sk.eef_pos() + self.sk.move_to([p[0], p[1], max(p[2], self._home[2])]) + self.sk.move_to(self._home) + + # ------------------------------------------------------------ helpers + def scale_xy(self): + return np.asarray(self._inst["scale_xy"], float) + + def pad_xy(self, o): + return np.asarray(self._inst["pads"][self.pad_of[o]], float) + + def on_scale(self, o, p=None): + p = envs.obj_pos(self.env, o) if p is None else p + d = np.abs(p[:2] - self.scale_xy()) + return bool(d.max() <= SCALE_HALF and abs(p[2] - (envs.TABLE_Z + SCALE_TOP + self.rest_dz[o])) < 0.008) + + def on_own_pad(self, o): + p = envs.obj_pos(self.env, o) + return bool(np.linalg.norm(p[:2] - self.pad_xy(o)) <= SUCC_R + and abs(p[2] - (envs.TABLE_Z + self.rest_dz[o])) < 0.01 and not self.sk.holding(o)) + + # ------------------------------------------------------------ monitor: scale readings + emergency stop + def _monitor(self): + env = self.env + if self._latch is not None: + if len(self.sk.log) > self._latch and np.linalg.norm(self.sk.eef_pos() - self._home) < 0.01: + self._latch = None + for o in ITEMS: + p = envs.obj_pos(env, o) + still = np.linalg.norm(p - self._prev[o]) < 0.0008 + self._prev[o] = p + if self.on_scale(o, p): + if still and not self.sk.holding(o): + self._dwell[o] += 1 + if self._dwell[o] >= DWELL and not self._visit[o]: + self._visit[o] = True + self._record(o) + else: + self._dwell[o] = 0 + else: + self._dwell[o] = 0 + if np.abs(p[:2] - self.scale_xy()).max() > SCALE_HALF or \ + p[2] > envs.TABLE_Z + SCALE_TOP + self.rest_dz[o] + 0.02: + self._visit[o] = False + if self.inject and self.stop is None: + self._maybe_stop() + + def _record(self, o): + self.log.append(o) + k = len(self.log) + ok = self.log == self._inst["order"][:k] + if ok: + self.events.append(dict(step=int(self.sk.n_steps), kind="beep", obj=o, + text="The scale beeped: reading recorded.")) + else: + if self.error is None: + self.error = dict(item=o, position=k, step=int(self.sk.n_steps), + kind="repeat" if self.log.count(o) > 1 else "out_of_order") + self.events.append(dict(step=int(self.sk.n_steps), kind="error", obj=o, + text="The scale beeped three times: error, this reading does not follow the " + "requested order. The log cannot be edited.")) + + def _maybe_stop(self): + inst = self._inst + o, w = inst["stop_item"], inst["stop_w"] + if self.log != inst["order"][:w]: + return + p = envs.obj_pos(self.env, o) + if inst["stop_phase"] == "A": + if p[2] < envs.TABLE_Z + self.rest_dz[o] + LIFTED: + return + if np.linalg.norm(p[:2] - self.pad_xy(o)) < inst["trigger_dist"]: + return + else: + if p[2] < envs.TABLE_Z + SCALE_TOP + self.rest_dz[o] + LIFTED: + return + if np.linalg.norm(p[:2] - self.scale_xy()) < inst["trigger_dist"]: + return + if not self.sk.holding(o): + return + self._do_stop(o) + + def _do_stop(self, o): + inst = self._inst + xy = self.pad_xy(o) + np.asarray(inst["stop_off"]) + envs.place_upright(self.env, o, xy, inst["stop_yaw"]) + self.sk.grip = -1.0 + self.sk.yaw = 0.0 + self._latch = len(self.sk.log) # drive the arm home until the current primitive has returned + self._prev[o] = envs.obj_pos(self.env, o) + self.env.sim.forward() + text = ("Emergency stop! The gripper opened, the safety routine put the item the robot was holding back on " + "its pad and moved the arm to its home pose. You may continue the task.") + self.stop = dict(item=o, phase=inst["stop_phase"], weighed=len(self.log), step=int(self.sk.n_steps)) + self.events.append(dict(step=int(self.sk.n_steps), kind="stop", obj=o, text=text)) + + def _homing_action(self): + sk = self.sk + a = np.zeros(self.env.action_dim) + a[:3] = np.clip((self._home - sk.eef_pos()) / sk.pos_scale, -1, 1) + a[3:6] = np.clip(_rot_err(sk.R0, sk.eef_mat()) / ROT_SCALE, -1, 1) + a[6] = -1.0 + return a + + def drain_events(self): + ev = self.events[self._event_cursor:] + self._event_cursor = len(self.events) + return [e["text"] for e in ev] + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + envs.settle(self.env, 20) + order = inst["order"] + complete = self.log == order + terminal = self.error is not None + off = [o for o in ITEMS if not self.on_own_pad(o)] + success = bool(complete and not off and not terminal) + if success: + head = "All four items were weighed once, in the requested order, and are back on their pads." + elif terminal: + head = ("The scale log does not follow the requested order (an item was weighed a second time or out " + "of turn). The log cannot be edited, so the task can no longer be completed.") + elif complete: + head = "Every item has been weighed, but not every item is back on its own pad." + else: + head = "Not every item has been weighed yet." + parts = [] + if not success and not terminal: + for o in off: + p = envs.obj_pos(self.env, o) + if self.sk.holding(o): + parts.append(f"the {NAME[o]} is still in the gripper") + elif self.on_scale(o, p): + parts.append(f"the {NAME[o]} is on the scale") + else: + d = np.linalg.norm(p[:2] - self.pad_xy(o)) + parts.append(f"the {NAME[o]} is {100 * d:.0f} cm from the centre of its pad") + detail = head + (" Also: " + "; ".join(parts) + "." if parts else "") + new = [e for e in self.events[self._outcome_cursor:] if e["kind"] == "stop"] + self._outcome_cursor = len(self.events) + if new: + detail = "During this attempt: " + " ".join(e["text"] for e in new) + " " + detail + return dict(success=success, terminal=terminal, log=[NAME[o] for o in self.log], n_weighed=len(self.log), + complete=complete, error=self.error, stop=self.stop, + off_pad=[NAME[o] for o in off], detail=detail) + + # ------------------------------------------------------------ motion (scripted policies) + def _support_z(self, o): + p = envs.obj_pos(self.env, o) + return envs.TABLE_Z + (SCALE_TOP if self.on_scale(o, p) or + (np.abs(p[:2] - self.scale_xy()).max() < SCALE_HALF) else 0.0) + + def _n_stops(self): + return sum(e["kind"] == "stop" for e in self.events) + + def _pick(self, o): + sk = self.sk + for _ in range(2): + p = envs.obj_pos(self.env, o) + sk.grasp_at(p[:2], self._support_z(o) + GRASP_DZ, yaw=_yaw_of(self.env, o), lift=0.12) + if sk.holding(o): + return True + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], self._support_z(o) + GRASP_DZ + 0.12]) + return False + + def _carry_to(self, o, xy, z_support): + """Carry the held item to xy and put it down. Returns False if an emergency stop happened.""" + sk = self.sk + n0 = self._n_stops() + sk.move_to([xy[0], xy[1], Z_CARRY]) + if self._n_stops() > n0: + return False + sk.move_to([xy[0], xy[1], z_support + GRASP_DZ + 0.004], tol=0.004) + sk.set_gripper(False, steps=12) + sk.move_to([xy[0], xy[1], z_support + GRASP_DZ + 0.10]) + return self._n_stops() == n0 + + def _weigh(self, o): + """Weigh one item (pad -> scale -> pad). Returns (status, beeped): status 'ok' / 'stop_A' / 'stop_B' / + 'no_grasp'; beeped = the scale beeped while the item lay on it (what the agent hears).""" + n_beep = sum(e["kind"] in ("beep", "error") for e in self.events) + if not self._pick(o): + return "no_grasp", False + if not self._carry_to(o, self.scale_xy(), envs.TABLE_Z + SCALE_TOP): + return "stop_A", False + self.sk.hold(6) + beeped = sum(e["kind"] in ("beep", "error") for e in self.events) > n_beep + if not self._pick(o): + return "no_grasp", beeped + if not self._carry_to(o, self.pad_xy(o), envs.TABLE_Z): + return "stop_B", beeped + return "ok", beeped + + def _fix_pads(self, log): + for o in ITEMS: + if not self.on_own_pad(o) and not self.on_scale(o): + if self._pick(o): + self._carry_to(o, self.pad_xy(o), envs.TABLE_Z) + log.append((NAME[o], "back to pad")) + + def _run_from(self, k, record, log, stop_on_stop=False): + """Weigh order[k:] in turn, keeping `record` (the policy's own list of readings it heard).""" + order = self._inst["order"] + i = k + guard = 0 + while i < len(order) and guard < 10 and self.error is None: + guard += 1 + o = order[i] + st, beeped = self._weigh(o) + log.append((NAME[o], st, beeped)) + if beeped: + record.append(o) + if st == "no_grasp": + continue + if st.startswith("stop"): + if stop_on_stop: + return "stopped" + i = len(record) # resume from the own record + continue + i += 1 + return "ok" + + # ------------------------------------------------------------ scripted references (within protocol) + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed + 104729) + self.reset_instance(inst) + order = inst["order"] + history = [] + record = [] # adaptive's Save: readings it heard + for a in range(k): + log = [] + plan = dict(kind=kind, steps=log) + if a == 0: + if kind == "oracle": + while len(self.log) < len(order) and self.error is None and len(log) < 12: + o = order[len(self.log)] # privileged scale log + st, _ = self._weigh(o) + log.append((NAME[o], st)) + plan["recovery"] = "oracle: privileged scale log" + elif kind == "adaptive": + self._run_from(0, record, log) + plan["recovery"] = "own record of readings: resume from order[len(record)]" + elif kind == "skip": + started = [] + i = 0 + while i < len(order) and self.error is None and len(log) < 12: + o = order[i] + st, beeped = self._weigh(o) + log.append((NAME[o], st, beeped)) + if st == "no_grasp": + continue + started.append(o) + i = len(started) # counts started items, not readings + plan["recovery"] = "counts items it started to weigh (the interrupted one too)" + else: # memoryless after the stop + r = self._run_from(0, record, log, stop_on_stop=True) + if r == "stopped": + if kind == "naive": + g = int(rng.integers(0, len(order) + 1)) + plan["recovery"] = f"memoryless: guesses {g} items already weighed" + self._run_from(g, [], log) + elif kind == "blind": + plan["recovery"] = "memoryless restart from the first item" + self._run_from(0, [], log) + else: + raise ValueError(kind) + else: + plan["recovery"] = "none (no stop)" + else: + if kind in ("adaptive", "oracle", "skip"): + plan["recovery"] = "memory + F2: put items back on their pads / finish from own record" + if kind == "adaptive" and len(record) < len(order): + self._run_from(len(record), record, log) + if kind == "skip" and not history[-1]["outcome"]["complete"]: + # F2 says the log is incomplete: with memory, the item carried at the stop was not weighed + stopped = [s[0] for h in history for s in h["params"]["steps"] if str(s[1]).startswith("stop")] + if stopped: + o = next(i for i in ITEMS if NAME[i] == stopped[-1]) + st, _ = self._weigh(o) + log.append((NAME[o], st)) + plan["recovery"] = "memory + F2 'not every item weighed': weigh the item carried at the stop" + self._fix_pads(log) + elif kind == "blind": + plan["recovery"] = "memoryless restart from the first item" + self._run_from(0, [], log) + else: + raise ValueError(kind) + self.go_home() + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=plan, outcome=out)) + if on_attempt: + on_attempt(a, plan, out) + if out["success"] or out["terminal"] or kind in ("oracle", "naive"): + break + return history + + def default_params(self, inst): + return dict(policy="naive") + + def oracle_params(self, inst): + return dict(policy="oracle") diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l6_swap.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l6_swap.py new file mode 100644 index 0000000000000000000000000000000000000000..1794c23e23f238abf25697524800263760fccea7 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l6_swap.py @@ -0,0 +1,466 @@ +"""L6-A swap_interrupt: swap two items between identical pads; the second carry is interrupted by a slip. + +Scene: four identical dark round pads (flat markers, no collision). The cream cheese (X) starts on pad A, +the butter (Y) on pad B, pads C and D are empty. Pad positions, which pad is which and the drop spot are +random per seed. Goal: X on B and Y on A. + +Standard procedure: X: A -> C (temporary), Y: B -> A, X: C -> B. During the second carry (whichever item is +carried while the other one has already left its start pad), the carried item "slips": the gripper opens +and the item lands on the table at a hidden spot that is on no pad. Afterwards X sits on C, Y lies on the +table and A, B, D are empty -- the current image no longer shows which empty pad was whose. The information +needed to finish ("what has been done, where did each item start") is only in the agent's own history. + +The drop spot is placed next to a *lure* pad: the spare pad ("spare", 50 %), the carried item's own start pad +("source", 25 %) or its true destination ("dest", 25 %). So "put it on the nearest pad" is usually wrong and +proximity is close to uninformative; a stronger bias towards the start pad would open a memoryless shortcut +(tidy both items onto their nearest pads = undo, then swap again), see the task card. + +Protocol: within (one episode, no reset). Attempt granularity: an attempt is everything the agent does until +it declares the task done; after each attempt the outcome is measured (F1/F2 feedback) and, if it failed, the +agent continues from the current state. The slip is injected once per episode, inside attempt 1 (it is an +in-attempt failure event, reported immediately: see `drain_events`). Scripted references: + + oracle knows the true start layout; after the slip puts Y on A and X on B. + adaptive saves the start layout from its first frame (Save), recalls it after the slip (Retrieve) and + finishes the swap from the right step (Utilize); later attempts fix residual misplacements from + memory + F2 feedback. + naive memoryless continuation (one attempt): after the slip it re-plans from the current frame only -- + the stray item goes to the nearest empty pad, the item that is still on a pad goes to the nearest + remaining empty pad. + blind memoryless restart (k attempts): does not know which step it was at; tidies the stray item onto + the nearest empty pad and then performs the whole swap again from the current frame; every later + attempt again swaps the two items (repeated swap, cf. RMBench). + blind_continue (extra control, not in the acceptance table) attempt 1 = naive, later attempts = swap again. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _wrap, register_generated +from ..task_base import LFFTask, register_task + +N_PADS = 4 +PAD_R = 0.055 # pad radius (11 cm discs); items are 8 x 4.3 x 1.8 cm boxes lying flat +PAD_HALF_T = 0.0008 +PAD_RGBA = (0.22, 0.24, 0.28, 1.0) +SUCC_R = 0.04 # item centre within 4 cm of the pad centre counts as "on that pad" for success +PAD_MIN_DIST = 0.17 +PAD_REGION = (-0.26, 0.04, -0.25, 0.25) # x0, x1, y0, y1 (world) +PAD_REACH = 0.71 # max horizontal distance of a pad centre from the robot base +DROP_REGION = (-0.31, 0.07, -0.30, 0.30) +# beyond ~0.75 m from the base the arm ends up fully stretched (elbow at its joint limit) and the OSC gets stuck +MAX_REACH = 0.73 +DROP_CLEAR = PAD_R + 0.05 # drop centre this far from every pad centre -> item fully off the pads +LURE_MARGIN = 0.03 # the lure pad is nearer to the drop spot than any other pad by at least this much +GRASP_DZ = 0.012 # gripper-site height above the table for a top-down grasp of the flat boxes +LIFT = 0.15 +BASE_X = -0.66 # robot base x (world); base-frame coordinates = (x - BASE_X, y) +LURE_P = (("source", 0.25), ("spare", 0.5), ("dest", 0.25)) + +X, Y = "cream_cheese_1", "butter_1" +NAME = {X: "cream cheese", Y: "butter"} +PADS = [f"pad_{i + 1}" for i in range(N_PADS)] + + +def _pad_xml(model_name): + c = " ".join(f"{v:.3f}" for v in PAD_RGBA) + g = (f' \n' + f' ') + # flat marker without collisions: gravity compensation keeps it from sinking through the table + return _wrap(model_name, g, PAD_HALF_T, PAD_R).replace('', + '') + + +def _yaw_of(env, obj): + R = env.sim.data.body_xmat[envs.body_id(env, obj)].reshape(3, 3) + yaw = float(np.arctan2(R[1, 0], R[0, 0])) # long axis of the boxes = body x + return (yaw + np.pi / 2) % np.pi - np.pi / 2 # boxes are symmetric under pi + + +def drop_spot(pads, src, dest, other_xy, lure, phase, dist): + """Geometry of the injected drop. pads: (N,2); src / dest: start pads of the carried / other item; + other_xy: current xy of the other item. Returns (xy, lure_pad) or (None, None).""" + pads = np.asarray(pads, float) + rest = [i for i in range(len(pads)) if i not in (src, dest)] + # spare = an empty pad that is neither start pad and not the one the other item is parked on + occ = [i for i in rest if np.linalg.norm(pads[i] - other_xy) < PAD_R] + spare_c = [i for i in rest if i not in occ] or rest + spare = max(spare_c, key=lambda i: np.linalg.norm(pads[i] - other_xy)) + lp = {"source": src, "dest": dest, "spare": spare}[lure] + for d in (dist, dist + 0.01, dist - 0.01, dist + 0.02): + for ang in phase + np.linspace(0, 2 * np.pi, 48, endpoint=False): + xy = pads[lp] + d * np.array([np.cos(ang), np.sin(ang)]) + if not (DROP_REGION[0] <= xy[0] <= DROP_REGION[1] and DROP_REGION[2] <= xy[1] <= DROP_REGION[3]): + continue + if np.hypot(xy[0] - BASE_X, xy[1]) > MAX_REACH: + continue + dd = np.linalg.norm(pads - xy, axis=1) + if dd.min() < DROP_CLEAR or np.linalg.norm(xy - other_xy) < 0.12: + continue + if np.any(np.delete(dd, lp) < dd[lp] + LURE_MARGIN): + continue + return xy, int(lp) + return None, None + + +@register_task +class SwapInterrupt(LFFTask): + name = "l6_swap_interrupt" + level = "L6" + category = "procedural_memory" + capabilities = ("Perceive", "Save", "Retrieve", "Utilize") + protocol = "within" + max_attempts = 5 + instruction = ("Swap the positions of the cream cheese and the butter: each must end up on the round pad " + "where the other one started. You may use the empty pads as temporary spots.") + instruction_indirect = ("Swap the positions of the pale blue box with the oval logo and the red-and-yellow " + "box: each must end up on the round pad where the other one started. You may use the " + "empty pads as temporary spots.") + inject = True # set False to run the same scene without the slip (sanity check) + + # ------------------------------------------------------------ scene + def make_bddl(self): + cats = [register_generated(f"LffSwapPad{L}", _pad_xml(f"lff_swap_pad_{L.lower()}")) for L in "ABCD"] + objs = [(X, "cream_cheese", "cc_region", (-0.21, -0.21, -0.19, -0.19)), + (Y, "butter", "bu_region", (-0.21, 0.19, -0.19, 0.21)), + (PADS[0], cats[0], "p1_region", (0.05, -0.21, 0.07, -0.19)), + (PADS[1], cats[1], "p2_region", (0.05, 0.19, 0.07, 0.21)), + (PADS[2], cats[2], "p3_region", (-0.06, -0.01, -0.04, 0.01)), + (PADS[3], cats[3], "p4_region", (-0.31, -0.01, -0.29, 0.01))] + return write_bddl(self.name, self.instruction, objs) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + for _ in range(1000): + pads = [] + while len(pads) < N_PADS: + p = np.array([rng.uniform(*PAD_REGION[:2]), rng.uniform(*PAD_REGION[2:])]) + if np.hypot(p[0] - BASE_X, p[1]) > PAD_REACH: + continue + if all(np.linalg.norm(p - q) >= PAD_MIN_DIST for q in pads): + pads.append(p) + pads = np.array(pads) + x_pad, y_pad = 0, 1 # pad order is already random + u, acc = rng.uniform(), 0.0 + for lure, pr in LURE_P: + acc += pr + if u < acc: + break + phase, dist = float(rng.uniform(0, 2 * np.pi)), float(rng.uniform(0.115, 0.14)) + # canonical execution: X parked on the empty pad nearest to its start pad, then Y is carried + empt = [i for i in range(N_PADS) if i not in (x_pad, y_pad)] + buf = min(empt, key=lambda i: np.linalg.norm(pads[i] - pads[x_pad])) + xy, lp = drop_spot(pads, y_pad, x_pad, pads[buf], lure, phase, dist) + if xy is None: + continue + return dict(seed=int(seed), pads=pads.round(4).tolist(), x_pad=x_pad, y_pad=y_pad, + yaw_x=float(rng.uniform(-0.3, 0.3)), yaw_y=float(rng.uniform(-0.3, 0.3)), + lure=lure, drop_phase=phase, drop_dist=dist, drop_yaw=float(rng.uniform(-1.4, 1.4)), + trigger_dist=float(rng.uniform(0.05, 0.10)), + canonical_buffer=int(buf), canonical_drop_xy=xy.round(4).tolist()) + raise RuntimeError("could not sample a layout") + + def apply_instance(self, inst): + for i, p in enumerate(inst["pads"]): + envs.set_obj_pose(self.env, PADS[i], [p[0], p[1], envs.TABLE_Z + PAD_HALF_T + 0.0001]) + envs.place_upright(self.env, X, inst["pads"][inst["x_pad"]], inst["yaw_x"]) + envs.place_upright(self.env, Y, inst["pads"][inst["y_pad"]], inst["yaw_y"]) + self.env.sim.forward() + self.slip = None + self.events = [] + self._event_cursor = 0 # for drain_events (harness, per tool call) + self._outcome_cursor = 0 # for outcome (per attempt) + self._inst = inst + + def reset_instance(self, inst, recorder=None): + sk = super().reset_instance(inst) + self._user_recorder = recorder + sk.recorder = self._on_step # slip trigger is checked on every control step + sk.record_every = 1 + self._home = sk.eef_pos() + return sk + + def go_home(self): + """Lift the arm out of the camera's way (end of an attempt).""" + p = self.sk.eef_pos() + self.sk.move_to([p[0], p[1], max(p[2], self._home[2])]) + self.sk.move_to(self._home) + + # ------------------------------------------------------------ slip injection (state triggered) + def _on_step(self, env): + if self.inject and self.slip is None: + self._maybe_slip() + if self._user_recorder is not None and self.sk.n_steps % 4 == 0: + self._user_recorder(env) + + def _maybe_slip(self): + """Fires during the first carry of an item while the other item has already left its start pad, + i.e. the second transport of a swap, whatever order the agent chose.""" + inst, env = self._inst, self.env + pads = np.asarray(inst["pads"]) + start = {X: inst["x_pad"], Y: inst["y_pad"]} + for o, other in ((X, Y), (Y, X)): + p = envs.obj_pos(env, o) + if p[2] < envs.TABLE_Z + 0.05: + continue + if np.linalg.norm(p[:2] - pads[start[o]]) < inst["trigger_dist"]: + continue + q = envs.obj_pos(env, other) + if np.linalg.norm(q[:2] - pads[start[other]]) < PAD_R: + continue + if not self.sk.holding(o): + continue + self._do_slip(o, other, q[:2]) + return + + def _do_slip(self, o, other, other_xy): + inst = self._inst + start = {X: inst["x_pad"], Y: inst["y_pad"]} + args = (inst["pads"], start[o], start[other], other_xy) + xy, lp = drop_spot(*args, inst["lure"], inst["drop_phase"], inst["drop_dist"]) + lure = inst["lure"] + for alt in ("source", "spare", "dest"): # fallback (only if the agent did something unusual) + if xy is not None: + break + xy, lp = drop_spot(*args, alt, inst["drop_phase"], inst["drop_dist"]) + lure = alt + if xy is None: + xy, lp, lure = np.asarray(inst["canonical_drop_xy"]), -1, "fallback" + envs.place_upright(self.env, o, xy, inst["drop_yaw"]) + self.sk.grip = -1.0 # the gripper opens + self.env.sim.forward() + text = f"The {NAME[o]} slipped out of the gripper and fell onto the table." + self.slip = dict(obj=o, xy=[float(v) for v in xy], lure=lure, lure_pad=lp, step=int(self.sk.n_steps)) + self.events.append(dict(step=int(self.sk.n_steps), kind="slip", obj=o, text=text)) + + def drain_events(self): + """Event texts since the last call (for the harness: append to the current tool-call report).""" + ev = self.events[self._event_cursor:] + self._event_cursor = len(self.events) + return [e["text"] for e in ev] + + # ------------------------------------------------------------ perception helpers (what an agent can see) + def pad_xy(self): + return np.array([envs.obj_pos(self.env, p)[:2] for p in PADS]) + + def on_pad(self, o, r=PAD_R): + d = np.linalg.norm(self.pad_xy() - envs.obj_pos(self.env, o)[:2], axis=1) + return int(np.argmin(d)) if d.min() < r else None + + def empty_pads(self): + occ = {self.on_pad(X), self.on_pad(Y)} + return [i for i in range(N_PADS) if i not in occ] + + def _nearest(self, cands, xy): + pads = self.pad_xy() + return min(cands, key=lambda i: np.linalg.norm(pads[i] - np.asarray(xy)[:2])) + + @staticmethod + def _bf(xy): + return f"({xy[0] - BASE_X:.2f}, {xy[1]:+.2f})" + + def pad_label(self, i, cur=None): + """Robot-centric name of pad i relative to the other pads (no coordinates in agent feedback).""" + cur = self.pad_xy() if cur is None else cur + c = cur.mean(axis=0) + fb = "far" if cur[i][0] > c[0] else "near" + lr = "left" if cur[i][1] > c[1] else "right" + same = [j for j in range(len(cur)) if ("far" if cur[j][0] > c[0] else "near") == fb + and ("left" if cur[j][1] > c[1] else "right") == lr] + lab = f"the {fb}-{lr} pad" + if len(same) > 1: # two pads in the same quadrant: tell them apart left to right + order = sorted(same, key=lambda j: -cur[j][1]) + side = "more to the robot's left" if order.index(i) == 0 else "more to the robot's right" + lab += f" ({side} of the two)" + return lab + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + envs.settle(self.env, 20) + pads = np.asarray(inst["pads"]) + target = {X: inst["y_pad"], Y: inst["x_pad"]} + res, ok = {}, True + for o in (X, Y): + p = envs.obj_pos(self.env, o) + dt = float(np.linalg.norm(p[:2] - pads[target[o]])) + resting = bool(envs.TABLE_Z - 0.01 < p[2] < envs.TABLE_Z + 0.05 and not self.sk.holding(o)) + res[o] = dict(xy=[float(p[0]), float(p[1])], on_pad=self.on_pad(o), dist_to_target=dt, resting=resting) + ok = ok and resting and dt <= SUCC_R + # F2 detail: only what is observable now + events of this attempt; nothing about the start layout + parts = [] + cur = self.pad_xy() + for o in (X, Y): + r = res[o] + if r["on_pad"] is not None: + parts.append(f"the {NAME[o]} is on {self.pad_label(r['on_pad'], cur)}") + else: + dd = np.linalg.norm(cur - np.asarray(r["xy"]), axis=1) + d = dd.min() - PAD_R + parts.append(f"the {NAME[o]} is on the table, on no pad " + f"({100 * d:.0f} cm from the edge of {self.pad_label(int(dd.argmin()), cur)})") + emp = [self.pad_label(i, cur) for i in self.empty_pads()] + detail = ("Now " + "; ".join(parts) + "; empty: " + (", ".join(emp) if emp else "none") + + " (left/right = the robot's left/right, near/far = toward/away from the robot).") + new_ev = [e["text"] for e in self.events[self._outcome_cursor:]] + self._outcome_cursor = len(self.events) + if new_ev: + detail = "During this attempt: " + " ".join(new_ev) + " " + detail + return dict(success=bool(ok), items={NAME[o]: res[o] for o in (X, Y)}, + slip=self.slip, detail=detail) + + # ------------------------------------------------------------ motion + def _pick(self, o): + sk = self.sk + for _ in range(2): + p = envs.obj_pos(self.env, o) + sk.grasp_at(p[:2], envs.TABLE_Z + GRASP_DZ, yaw=_yaw_of(self.env, o), lift=LIFT) + if sk.holding(o): + return True + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], envs.TABLE_Z + LIFT]) + return False + + def _move(self, o, pad, log): + """Pick item o and put it on pad `pad`. Returns False if the item slipped on the way.""" + n_ev = len(self.events) + frm = self.on_pad(o) + ok = self._pick(o) + rec = dict(obj=NAME[o], from_pad=frm, to_pad=int(pad), grasped=ok) + log.append(rec) + if not ok: + return True + xy = self.pad_xy()[pad] + sk = self.sk + sk.move_to([xy[0], xy[1], envs.TABLE_Z + GRASP_DZ + LIFT]) # carry (the slip may fire here) + if len(self.events) > n_ev: + rec["slipped"] = True + return False + sk.move_to([xy[0], xy[1], envs.TABLE_Z + GRASP_DZ + 0.004], tol=0.004) + sk.set_gripper(False, steps=12) + sk.move_to([xy[0], xy[1], envs.TABLE_Z + GRASP_DZ + 0.10]) + return True + + def _run(self, moves, log): + """moves: list of (item, pad) computed up front (an open-loop plan). Stops at a slip.""" + for o, pad in moves: + if not self._move(o, pad, log): + return False + return True + + def _swap_now(self, log, rng=None): + """The standard swap of the two items' *current* pads via an empty pad (no memory).""" + a, b = self.on_pad(X), self.on_pad(Y) + empt = self.empty_pads() + if a is None or b is None or not empt: + return + buf = int(rng.choice(empt)) if rng is not None else self._nearest(empt, self.pad_xy()[a]) + self._run([(X, buf), (Y, a), (X, b)], log) + + def _tidy_stray(self, log): + for o in (X, Y): + if self.on_pad(o) is None and self.empty_pads(): + self._move(o, self._nearest(self.empty_pads(), envs.obj_pos(self.env, o)), log) + + def _fixup(self, target, log): + """Move items until each is on its target pad (target: item -> pad index).""" + pads = self.pad_xy() + for _ in range(6): + todo = [o for o in (Y, X) if np.linalg.norm(envs.obj_pos(self.env, o)[:2] - pads[target[o]]) > SUCC_R] + if not todo: + return + free = [o for o in todo if self.on_pad({X: Y, Y: X}[o], r=PAD_R) != target[o]] + if free: + self._move(free[0], target[free[0]], log) + else: # the two items block each other: park one on an empty pad that is no one's target + o = todo[0] + spare = [i for i in self.empty_pads() if i not in target.values()] or self.empty_pads() + self._move(o, self._nearest(spare, envs.obj_pos(self.env, o)), log) + + # ------------------------------------------------------------ scripted references (within protocol) + def _memory(self): + """Save: what the agent sees in its first frame -- which pad (by position) each item starts on.""" + return {X: self.pad_xy()[self.on_pad(X)].tolist(), Y: self.pad_xy()[self.on_pad(Y)].tolist()} + + def saved_memory(self, first): + """What the adaptive policy recalls after the slip (identity; patched by the mismatched-memory control).""" + return first + + def _attempt1(self, kind, inst, mem, rng, first): + log = [] + plan = dict(kind=kind, moves=log) + a = self._nearest(range(N_PADS), first[X]) # the open-loop plan is made from the first frame + b = self._nearest(range(N_PADS), first[Y]) + empt = [i for i in range(N_PADS) if i not in (a, b)] + buf = self._nearest(empt, self.pad_xy()[a]) + plan["plan"] = f"X->{buf}, Y->{a}, X->{b}" + if self._run([(X, buf), (Y, a), (X, b)], log): + plan["recovery"] = "none (no slip)" + return plan + # ---- the carry was interrupted by the slip: recover + if kind == "oracle": # privileged: true start layout + plan["recovery"] = "oracle: true layout" + self._fixup({X: inst["y_pad"], Y: inst["x_pad"]}, log) + elif kind == "adaptive": # Retrieve the saved first frame and the step log; finish from the right step + ta = self._nearest(range(N_PADS), mem[X]) + tb = self._nearest(range(N_PADS), mem[Y]) + plan["recovery"] = f"memory: butter -> pad {ta} (cream cheese's start), cream cheese -> pad {tb}" + self._fixup({X: tb, Y: ta}, log) + elif kind in ("naive", "blind_continue"): # memoryless continuation from the current frame + stray = [o for o in (X, Y) if self.on_pad(o) is None] + parked = [o for o in (X, Y) if self.on_pad(o) is not None] + plan["recovery"] = "current frame: stray item -> nearest empty pad; parked item -> nearest empty pad" + for o in stray: + self._move(o, self._nearest(self.empty_pads(), envs.obj_pos(self.env, o)), log) + for o in parked: + if self.empty_pads(): + self._move(o, self._nearest(self.empty_pads(), envs.obj_pos(self.env, o)), log) + elif kind == "blind": # memoryless restart: tidy up, then the whole swap again + plan["recovery"] = "restart: stray item -> nearest empty pad, then swap again" + self._tidy_stray(log) + self._swap_now(log, rng) + else: + raise ValueError(kind) + return plan + + def _retry(self, kind, inst, mem, rng): + log = [] + plan = dict(kind=kind, moves=log) + if kind == "adaptive": + ta = self._nearest(range(N_PADS), mem[X]) + tb = self._nearest(range(N_PADS), mem[Y]) + plan["recovery"] = "memory + F2: fix items not on their targets" + self._fixup({X: tb, Y: ta}, log) + elif kind in ("blind", "blind_continue"): + plan["recovery"] = "no history: tidy, then swap the two items again" + self._tidy_stray(log) + self._swap_now(log, rng) + else: + raise ValueError(kind) + return plan + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + self.reset_instance(inst) + first = self._memory() + mem = self.saved_memory(first) + history = [] + for a in range(k): + plan = self._attempt1(kind, inst, mem, rng, first) if a == 0 else self._retry(kind, inst, mem, rng) + self.go_home() # "done": the agent declares the attempt finished + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=plan, outcome=out)) + if on_attempt: + on_attempt(a, plan, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history + + # cross-protocol hooks are not used by this task + def default_params(self, inst): + return dict(policy="naive") + + def oracle_params(self, inst): + return dict(policy="oracle") diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l7_hidden_mechanism.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l7_hidden_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..234475804ed6b6684aa8fc69a813d1332eb3a2d0 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l7_hidden_mechanism.py @@ -0,0 +1,398 @@ +"""L7 hidden_mechanism: open a small cabinet door whose opening mechanism is hidden. + +Category: failed_interaction_inference ("why did this contact not do what I expected?"). + +Scene: a small wooden cabinet (14 x 24 x 10 cm) whose door faces away from the robot (towards the front +camera), with a black knob post in the middle of the door. The robot reaches over the cabinet, grasps the +knob from above and pulls. + +Hidden variable: the door's mechanism, one of four (uniform): swings on a hinge at its left edge (HL) or at +its right edge (HR), or slides to the left (SL) or to the right (SR). The door, the knob and the cabinet look +exactly the same for all four (hinge pins and slide rails are not modelled visually). + +Rule (stated in the instruction and enforced): one pull per attempt -- grasp the knob, ONE straight move_to +while holding it, release. A "pull" is any move_to that starts with the knob held, moves the door, or pushes +against the door / knob sideways. Without this rule an agent could probe the door with small wiggles inside +one attempt and the task would no longer test what is learnt across attempts. + +Why the prior fails (measured): the natural pull is straight out from the door (forward, +x), 12 cm. + hinged: the knob has to follow a circle around the hinge; the door swings open 31-36 deg and the knob is + pulled out of the fingers. The knob ends ~6 cm forward and ~4.5 cm towards the hinge side. + sliding: nothing moves; the fingers slide off the knob. +Success needs >= 60 deg (hinged) or >= 12 cm (sliding). + +What must be learned: from how the knob / door moved (F2 gives the knob's displacement relative to where it +started, plus the images) -> which mechanism -> the pull direction that opens it: + hinged on the left: pull forward-left (~55 deg from forward), ~22 cm -> 70-88 deg (measured) + hinged on the right: pull forward-right -> 70-88 deg + sliding: pull sideways ~18 cm (18 cm); after "nothing moved" the side is not observable, + so a learner needs one more attempt in the worst case (left fails -> right). +Straight pulls at 30 / 45 deg towards the hinge give 44 / ~62 deg; diagonal pulls on a slider give 2-4 cm. +""" +import mujoco +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +CAB = "cab_1" +MODEL = "lff_l7_mech_cabinet" +# cabinet frame: origin at the centre of the footprint, z = 0 on the table; the open side faces +x +D, W, H, T = 0.14, 0.24, 0.10, 0.01 # depth (x), width (y), height, wall thickness +DW, DH, DT = 0.232, 0.09, 0.012 # door width, height, thickness +GAP = 0.002 +KZ = 0.045 # knob stem height above the table +STEM_L, STEM_R = 0.032, 0.005 +POST_R, POST_H = 0.009, 0.038 +POST_TOP = KZ - 0.006 + POST_H # 7.7 cm above the table +Z_GRIP = envs.TABLE_Z + 0.075 # grasp-point height for grasping the knob (verified across cabinet positions) +MECHS = ("HL", "HR", "SL", "SR") +HINGE_OK = np.radians(60.0) +SLIDE_OK = 0.12 +SLIDE_RANGE = 0.22 +PULL_SPEED = 0.10 + + +def cabinet_xml(name, rgba=(0.45, 0.32, 0.22, 1.0), door_rgba=(0.80, 0.70, 0.55, 1.0), knob_rgba=(0.12, 0.12, 0.13, 1.0)): + hx, hy = D / 2, W / 2 + shell = [((-hx + T / 2, 0, H / 2), (T / 2, hy, H / 2)), ((0, hy - T / 2, H / 2), (hx, T / 2, H / 2)), + ((0, -hy + T / 2, H / 2), (hx, T / 2, H / 2)), ((0, 0, H - T / 2), (hx, hy, T / 2)), + ((0, 0, T / 2), (hx, hy, T / 2))] + g = [] + for k, (p, s) in enumerate(shell): + g.append(f'') + g.append(f'') + dx = hx + GAP + DT / 2 + dz = 0.005 + DH / 2 + door = [f'', + # placeholder joint: type, axis, anchor and range are set per instance (apply_instance) + f'', + f'', + f''] + sz = KZ - dz + stem_p = (DT / 2 + STEM_L / 2, 0, sz) + post_p = (DT / 2 + STEM_L, 0, sz - 0.006 + POST_H / 2) + for tag, typ, p, s in (("stem", "box", stem_p, (STEM_L / 2 + 0.002, STEM_R, STEM_R)), + ("post", "cylinder", post_p, (POST_R, POST_H / 2))): + door.append(f'') + door.append(f'') + body = ("\n ".join(g) + f'\n \n ' + + "\n ".join(door) + "\n ") + return f""" + + + + {body} + + + + + + +""" + + +def _lr(v): + return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}" + + +def _fb(v): + return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}" + + +class MechSkills(Skills): + """Skills that log, for whoever drives them (scripted policy or agent): door pulls, the first grasp of the + knob, and how the knob moved during the first pull.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + m = env.sim.model + self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith(("gripper0_", "robot0_"))] + self._door_geoms = task.door_geom_ids + self.knob0 = task.knob_xyz() + self.pulls = [] # one entry per move_to that counts as a pull + self.closes = [] # close_gripper events: gripper centre relative to the knob, held afterwards? + self._touch = False + self.touch_since_report = False + + def holding_knob(self): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.task.knob_geom_names)) + + def _touching_door(self): + d = self.env.sim.data + g = set(self._grip_geoms) + dg = set(self._door_geoms) + for i in range(d.ncon): + c = d.contact[i] + if (c.geom1 in g and c.geom2 in dg) or (c.geom2 in g and c.geom1 in dg): + return True + return False + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + if self._touching_door(): + self._touch = True # per move_to (pull detection) + self.touch_since_report = True # per agent command (report field) + + def move_to(self, target, *args, **kwargs): + q0 = self.task.door_q() + hold0 = self.holding_knob() + p0 = self.eef_pos() + k0 = self.task.knob_xyz() + self._touch = False + rep = super().move_to(target, *args, **kwargs) + dq = abs(self.task.door_q() - q0) + moved = dq > (np.radians(1.0) if self.task.hinged else 0.003) + horiz = float(np.linalg.norm(np.asarray(target, float)[:2] - p0[:2])) + if hold0 or moved or (self._touch and horiz >= 0.015): + k1 = self.task.knob_xyz() + self.pulls.append(dict(step=self.n_steps, held_at_start=bool(hold0), held_at_end=self.holding_knob(), + knob_start=k0.tolist(), knob_end=k1.tolist(), door_moved=bool(moved), + gripper_move=(np.asarray(target, float)[:2] - p0[:2]).round(4).tolist())) + return rep + + def set_gripper(self, close, steps=15): + was_open = self.grip < 0 + rep = super().set_gripper(close, steps) + if close and was_open: + off = self.eef_pos() - self.task.knob_xyz() + self.closes.append(dict(step=self.n_steps, offset=off.round(4).tolist(), held=self.holding_knob(), + width=round(self.gripper_width(), 4))) + return rep + + +@register_task +class HiddenMechanism(LFFTask): + name = "l7_hidden_mechanism" + level = "L7" + category = "failed_interaction_inference" + capabilities = ("Perceive", "Reason", "Plan") + protocol = "cross" + instruction = ("Open the door of the small wooden cabinet wide (a door that swings must end at least 60 degrees " + "open, a door that slides at least 12 cm). The door faces away from you; grasp its black knob from " + "above. Only one pull is allowed per attempt: grasp the knob, move the gripper with ONE straight " + "move command while holding it, then release it. Pushing the door or the knob counts as a pull " + "too.") + instruction_indirect = ("Open the front panel of the small brown box wide (a panel that swings must end at least 60 " + "degrees open, a panel that slides at least 12 cm). The panel faces away from you; grasp the " + "small black handle on it from above. Only one pull is allowed per attempt: grasp the handle, " + "move the gripper with ONE straight move command while holding it, then release it. " + "Pushing the panel or the handle counts as a pull too.") + + # ------------------------------------------------------------ scene + def make_bddl(self): + cab = register_generated("LffL7MechCabinet", cabinet_xml(MODEL), free=False) + return write_bddl(self.name, "open the cabinet door", [], + fixtures=[(CAB, cab, "cab_region", (-0.14, -0.01, -0.12, 0.01))]) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + pre = f"{CAB}_{MODEL}" + self.jid = m.joint_name2id(pre + "_door_joint") + self.dof = m.jnt_dofadr[self.jid] + self.qa = m.jnt_qposadr[self.jid] + self.cab_bid = m.body_name2id(self.env.fixtures_dict[CAB].root_body) + self.post_gid = m.geom_name2id(pre + "_post") + self.knob_geom_names = [pre + "_post", pre + "_stem"] + self.door_geom_ids = [m.geom_name2id(pre + s) for s in ("_post", "_stem", "_panel")] + self.hinged = True + + # agent-facing hooks ------------------------------------------------------- + def on_agent_tool(self, inst, name, args, report): + """The cabinet is a fixture, so the harness's `holding_object` / `touched_object` (movable objects only) never + see the knob or the door; add an explicit `holding_knob` field and count door contacts as touches.""" + if self.sk is None or not isinstance(report, dict): + return + touched = self.sk.touch_since_report + self.sk.touch_since_report = False + if report.get("ok") and name in ("move_to", "open_gripper", "close_gripper", "push"): + report["holding_knob"] = self.sk.holding_knob() + if touched and "touched_object" in report: + report["touched_object"] = True + + # ------------------------------------------------------------ state helpers + def door_q(self): + return float(self.env.sim.data.qpos[self.qa]) + + def knob_xyz(self): + return self.env.sim.data.geom_xpos[self.post_gid].copy() + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + return dict(seed=int(seed), mech=MECHS[int(rng.integers(4))], + cab_xy=[float(rng.uniform(-0.15, -0.10)), float(rng.uniform(-0.07, 0.07))]) + + def apply_instance(self, inst): + m, d = self.env.sim.model, self.env.sim.data + cx, cy = inst["cab_xy"] + m.body_pos[self.cab_bid] = [cx, cy, envs.TABLE_Z] + m.body_quat[self.cab_bid] = [1.0, 0.0, 0.0, 0.0] + mech = inst["mech"] + jid, dof = self.jid, self.dof + self.hinged = mech in ("HL", "HR") + if self.hinged: + s = 1 if mech == "HL" else -1 + m.jnt_type[jid] = mujoco.mjtJoint.mjJNT_HINGE + m.jnt_axis[jid] = [0, 0, 1] + m.jnt_pos[jid] = [-DT / 2, s * DW / 2, 0] # back face of the door, at its left / right edge + m.jnt_range[jid] = [0.0, 1.9] if s > 0 else [-1.9, 0.0] + m.dof_damping[dof] = 0.05 + m.dof_frictionloss[dof] = 0.03 + else: + s = 1 if mech == "SL" else -1 + m.jnt_type[jid] = mujoco.mjtJoint.mjJNT_SLIDE + m.jnt_axis[jid] = [0, s, 0] + m.jnt_pos[jid] = [0, 0, 0] + m.jnt_range[jid] = [0.0, SLIDE_RANGE] + m.dof_damping[dof] = 2.0 + m.dof_frictionloss[dof] = 0.5 + # MuJoCo scales constraint softness (here: the joint limits) with dof_invweight0, computed once at compile + # time for the placeholder hinge through the door's centre. Changing the joint type without updating it + # made the slide limit ~200x too soft: a slider pulled the wrong way moved 17 cm past its stop (measured). + door_mass, door_izz = 0.35, 0.0016 + m.dof_invweight0[dof] = (1.0 / (door_izz + door_mass * (DW / 2) ** 2)) if self.hinged else 1.0 / door_mass + m.jnt_solref[jid] = [0.004, 1.0] # stiff stops (default 0.02 let a hard pull push a slider 8 mm past its stop) + d.qpos[self.qa] = 0.0 + d.qvel[dof] = 0.0 + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = MechSkills(self.env, self, recorder=recorder) + return self.sk + + def opening(self): + """Hinge: degrees open (>= 0); slide: cm open (>= 0).""" + q = abs(self.door_q()) + return float(np.degrees(q)) if self.hinged else 100.0 * q + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + envs.settle(self.env, 20) + sk = self.sk + q = abs(self.door_q()) + is_open = q >= (HINGE_OK if self.hinged else SLIDE_OK) + n_pulls = len(sk.pulls) + success = bool(is_open and n_pulls <= 1) + kd = self.knob_xyz() - sk.knob0 + out = dict(success=success, door_open=bool(is_open), opening=round(self.opening(), 1), n_pulls=n_pulls, + knob_disp=kd.round(4).tolist(), pulls=sk.pulls, closes=sk.closes, first_pull_disp=None, + lost_hold=None) + parts = [] + grasp_txt = "" + if sk.closes: + c = sk.closes[0] + o = c["offset"] + below = (envs.TABLE_Z + POST_TOP) - (o[2] + sk.knob0[2]) # knob top minus gripper centre height + grasp_txt = (f"When the gripper first closed, its centre was {_fb(o[0])} and {_lr(o[1])} of the knob's " + f"centre and {100 * below:.1f} cm below the top of the knob; it " + + ("was holding the knob." if c["held"] else "did not get hold of the knob.")) + if success: + out["failure"] = None + parts.append("The door is open wide.") + elif n_pulls == 0: + out["failure"] = "no_pull" + parts.append("The door did not open: the knob was never pulled.") + else: + out["failure"] = "several_pulls" if n_pulls > 1 else "not_open" + if n_pulls > 1: + parts.append(f"The door or knob was pulled or pushed in {n_pulls} separate moves; only one pull is " + f"allowed per attempt, so this attempt failed.") + elif is_open: + parts.append("The door is open wide.") + else: + parts.append("The door did not open wide enough.") + p = sk.pulls[0] + # net effect of the first pull once things came to rest: up to the start of the next pull, or now + k_after = np.array(sk.pulls[1]["knob_start"]) if n_pulls > 1 else self.knob_xyz() + disp = k_after - np.array(p["knob_start"]) + out["first_pull_disp"] = disp.round(4).tolist() + out["lost_hold"] = bool(p["held_at_start"] and not p["held_at_end"]) + if np.linalg.norm(disp[:2]) < 0.003: + txt = "During your (first) pull the knob did not move at all (less than 0.3 cm)" + else: + txt = f"During your (first) pull the knob moved {_fb(disp[0])} and {_lr(disp[1])}" + if p["held_at_start"]: + txt += ("; the gripper lost hold of the knob during the pull." if out["lost_hold"] + else "; the gripper still held the knob at the end of the pull.") + else: + txt += "; the gripper was not holding the knob when that move started." + parts.append(txt) + if grasp_txt and not success: + parts.append(grasp_txt) + out["detail"] = " ".join(parts) + return out + + # ------------------------------------------------------------ scripted execution (cross protocol) + def execute(self, inst, params): + """Grasp the knob from above (yaw 0), one straight pull in direction `alpha` (deg from forward, + = left) + over `dist` metres, release, lift.""" + sk = self.sk + p = self.knob_xyz() # perfect perception of the current scene + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], Z_GRIP + 0.08], yaw=0.0) + sk.move_to([p[0], p[1], Z_GRIP], tol=0.003) + sk.set_gripper(True, steps=15) + a = np.radians(float(params["alpha"])) + dist = float(params["dist"]) + sk.move_to([p[0] + dist * np.cos(a), p[1] + dist * np.sin(a), Z_GRIP], speed=PULL_SPEED, tol=0.004, + max_steps=300) + sk.set_gripper(False, steps=8) + e = sk.eef_pos() + sk.move_to([e[0], e[1], Z_GRIP + 0.10]) + + def default_params(self, inst): + return dict(alpha=0.0, dist=0.12) + + ORACLE = dict(HL=(55.0, 0.22), HR=(-55.0, 0.22), SL=(90.0, 0.18), SR=(-90.0, 0.18)) + + def oracle_params(self, inst): + a, dist = self.ORACLE[inst["mech"]] + return dict(alpha=a, dist=dist) + + def adapt_params(self, inst, history): + """Scripted F2 learner using the knob's displacement during the (first) pull of each earlier attempt: + moved forward and sideways -> it swings on a hinge on that side -> pull ~55 deg towards that side + (more if a hinge pull already fell short) + moved only sideways -> it slides that way -> pull sideways + did not move -> not a hinge; it must slide: try left, then right.""" + hinge_side, slide_side = 0, 0 + tried_still = set() # pull directions (sign of alpha, only for sideways pulls) after which nothing moved + hinge_tries = 0 + for h in history: + o = h["outcome"] + d = o.get("first_pull_disp") + a = h["params"]["alpha"] + if d is None: + continue + dx, dy = d[0], d[1] + if dx >= 0.01 and abs(dy) >= 0.01: + hinge_side = int(np.sign(dy)) + if abs(a) >= 50: + hinge_tries += 1 + elif abs(dy) >= 0.01: + slide_side = int(np.sign(dy)) + elif abs(a) >= 80: + tried_still.add(int(np.sign(a))) + if hinge_side: + a = 55.0 + 5.0 * min(hinge_tries, 2) + return dict(alpha=hinge_side * a, dist=0.22 + 0.02 * min(hinge_tries, 2)) + if slide_side: + return dict(alpha=90.0 * slide_side, dist=0.18) + side = 1 if 1 not in tried_still else -1 + return dict(alpha=90.0 * side, dist=0.18) + + def blind_params(self, inst, attempt, rng): + """Same plan (pull straight out) with small random variation; no history.""" + return dict(alpha=float(rng.normal(0.0, 8.0)), dist=float(np.clip(rng.normal(0.12, 0.02), 0.06, 0.2))) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l7_key_turn.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l7_key_turn.py new file mode 100644 index 0000000000000000000000000000000000000000..a24b3373992c8885d206f601efbd3b317c756baf --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l7_key_turn.py @@ -0,0 +1,461 @@ +"""L7 key_turn: unlock a lock whose key turns only one way; which way is hidden. + +Category: failed_interaction_inference ("why did this contact not do what I expected?"). + +Scene: a grey lock box (9 x 9 x 5 cm) on the table with a brass key standing in the keyhole on its top; the key's +flat head (3.6 cm wide, 1.6 cm thick, 3 cm tall) sticks up so the gripper can grasp it from above and turn it by +rotating the wrist. A red bolt sticks out of the box's front face (+x, towards the front camera) while it is locked +and slides in once the key has been turned to the open position. + +Hidden variable: the turning direction that opens the lock, clockwise (CW) or counterclockwise (CCW) seen from +above (alternates with the seed parity, so every block of instances is balanced). The other way the key has 3 deg of +play and then a hard stop. Both look exactly the same. + +Turns per attempt: not limited (2026-10-16, user). Until then the instruction allowed one turn per attempt and an +attempt with more than one turn failed; in every logged run whose first turn went the wrong way the agent turned the +other way within the same attempt and opened the lock, so the rule only made it repeat that correction in the next +attempt. The attempt now succeeds once the lock is open, however many turns it took. The trap is logged as an error +event instead: a turn "hits the stop" when it drives the key onto the stop on the locked side before the lock is open; +`trap_fired` = some turn did, `n_wrong_way` = how many did, `recovered_in_attempt` = trap fired and the lock was then +opened in the same attempt. A "turn" is any move_to that starts with the key held and changes the commanded yaw by +>= 5 deg, or that rotates the key by > 3 deg. A wrong turn costs one command, so this task does not meet design rule +R3 (the common-sense interaction must have a cost); its signal is clean success (first turn the right way) vs. +in-attempt recovery, and whether the agent keeps twisting the wrong way. + +Why the prior fails: the user's example -- many people first try counterclockwise. The scripted prior turns CCW by +90 deg, so it fails on every CW instance (half of them): the key rotates by its 3 deg of play, then the wrist stalls. +What must be learned from the failure: "the key would not turn this way at all" (not "my grip slipped") -> turn it +the other way. One failure is enough. + +Mechanics notes (measured in the prototype, 2026-10-08): + * the Panda's finger servo squeezes with kp * (finger opening) N, i.e. only ~4 N on a 7 mm head; the head then + twisted between the fingers and wedged them open. A 16 mm thick head gives ~8 N and turns reliably. + * without a stalling wrist the OSC keeps twisting against a blocked key, the fingers wedge open and on release + they knock the key 15-45 deg the free way (leaking the answer). `KeySkills` therefore stops rotating the wrist + once the held key sits on a stop and the gripper has twisted 6 deg past it (a torque-limited wrist), and limits + the wrist to 90 deg/s while turning. + * the stops use a stiff solref/solimp: with the defaults a hard twist pushed the key 10-15 deg past its stop. + * commanded yaw is taken literally in this task (nearest representation to the current yaw, clipped to + +-113 deg). The shared Skills.wrap_yaw maps yaw modulo 180 deg, which is right for grasping but would turn + "yaw = +95" into -85 deg, i.e. turn the key the wrong way. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, register_generated +from ..skills import DT, Skills, _rot_err, _rotz +from ..task_base import LFFTask, register_task + +LOCK = "lock_1" +MODEL = "lff_l7_lock" +LX, LY, LH = 0.045, 0.045, 0.05 # housing half x, half y, full height +HEAD = (0.018, 0.008, 0.015) # key head half extents: local x = width, y = thickness, z = height +HEAD_Z = 0.004 + HEAD[2] # head centre above the housing top +BOLT = (0.008, 0.012, 0.006) # red bolt (visual only) half extents +BOLT_OUT = (LX + BOLT[0], 0.0, 0.022) +BOLT_IN = (LX - BOLT[0] - 0.002, 0.0, 0.022) +PLAY = np.radians(3.0) +STOP = np.radians(90.0) +UNLOCK_AT = np.radians(80.0) +KEY_FRICTION = 0.04 # N m +W_MAX = np.radians(90.0) # wrist speed limit while turning (rad/s) +TWIST_MAX = np.radians(6.0) # wrist stalls when it has twisted this far past a blocked key +STALL_EXIT = 20 # control steps of stalling before the move gives up +TURN_YAW = np.radians(5.0) +TURN_KEY = np.radians(3.0) +STOP_HIT = PLAY - np.radians(0.5) # key this far the locked way = sitting on the locked-side stop +Z_GRIP = envs.TABLE_Z + LH + HEAD_Z # grasp-point height for the key head (its centre) + + +def lock_xml(name, body_rgba=(0.55, 0.57, 0.60, 1.0), key_rgba=(0.80, 0.64, 0.22, 1.0), bolt_rgba=(0.80, 0.12, 0.10, 1.0)): + g = [f'', + f'', + f'', + f''] + k = ['', + # placeholder range: the open direction is set per instance (apply_instance) + f'', + f'', + f'', + f''] + shell = "\n ".join(g) + key = "\n ".join(k) + return f""" + + + + {shell} + + {key} + + + + + + + +""" + + +def _wrap_pi(a): + return float((a + np.pi) % (2 * np.pi) - np.pi) + + +def _wrap_half(a): + """the gripper is symmetric under a rotation by pi""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def _rot_words(deg): + return f"{abs(deg):.0f} deg {'counterclockwise' if deg > 0 else 'clockwise'}" + + +def _lr(v): + return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}" + + +def _fb(v): + return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}" + + +def _turn_txt(t, lead): + """F2 sentence for one logged turn: what the wrist and the key did, and whether the gripper held the key.""" + dk = t["key_end_deg"] - t["key_start_deg"] + txt = f"{lead} the wrist rotated {_rot_words(t['wrist_turn_deg'])} (seen from above)" + if abs(dk) < 1.0: + txt += " and the key did not rotate at all" + else: + txt += f" and the key rotated {_rot_words(dk)}" + if t["stalled"]: + txt += ", then it would not turn any further and the wrist stopped there" + if t["held_at_start"]: + txt += ("; the gripper lost hold of the key during the turn." if not t["held_at_end"] + else "; the gripper held the key throughout the turn.") + else: + txt += "; the gripper was not holding the key when that move started." + return txt + + +class KeySkills(Skills): + """Skills for the key task: literal yaw, wrist speed limit, stalling wrist, and a log of turns / grasps / unlock.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + m = env.sim.model + self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith(("gripper0_", "robot0_"))] + self.turns = [] # one entry per move_to that counts as a turn + self.closes = [] # close_gripper events: gripper centre relative to the key head, held afterwards? + self.stall_steps = 0 + self._grasp_off = None # gripper yaw minus key yaw when the key was grasped + self.touch_since_report = False + + # ------------------------------------------------------------ state + def eef_yaw(self): + R = self.eef_mat() @ self.R0.T + return float(np.arctan2(R[1, 0], R[0, 0])) + + def holding_key(self): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=[self.task.head_geom_name])) + + def _touching_key(self): + d = self.env.sim.data + g, kg = set(self._grip_geoms), self.task.head_gid + for i in range(d.ncon): + c = d.contact[i] + if (c.geom1 in g and c.geom2 == kg) or (c.geom2 in g and c.geom1 == kg): + return True + return False + + def wrap_yaw(self, yaw): + """Literal yaw: the representation of `yaw` closest to the current wrist yaw, clipped to the wrist range.""" + cur = self.eef_yaw() + y = cur + _wrap_pi(float(yaw) - cur) + return float(np.clip(y, -self.YAW_LIMIT, self.YAW_LIMIT)) + + # ------------------------------------------------------------ low level + def _act(self, dpos, drot, grip): + t = self.task + if self.grip > 0 and self._grasp_off is not None: + q = t.key_q() + lo, hi = t.key_range() + twist = _wrap_half(self.eef_yaw() - t.key_world_yaw() - self._grasp_off) + at_hi, at_lo = q >= hi - np.radians(1.5), q <= lo + np.radians(1.5) + if (at_hi and twist > TWIST_MAX and drot[2] > 0) or (at_lo and twist < -TWIST_MAX and drot[2] < 0): + drot = np.array(drot, float).copy() + drot[2] = -np.sign(twist) * 0.02 # force-limited wrist: back off instead of twisting further + self.stall_steps += 1 + super()._act(dpos, drot, grip) + t.check_unlock() + if self._touching_key(): + self.touch_since_report = True + + def move_to(self, target, yaw=None, speed=None, tol=0.004, max_steps=250, apply_bias=True, wrap_yaw=True): + """Skills.move_to with the wrist reference rotating at <= W_MAX and an early stop when the wrist stalls. + Logs the move as a turn when it starts with the key held and rotates the wrist, or when it rotates the key; + `hit_stop`: the turn went the locked way (wrist command if the key was held, else the key's motion) and the key + was on the locked-side stop during it, while the lock was still locked (the trap).""" + t = self.task + tgt = np.asarray(target, float) + (self.bias if apply_bias else 0.0) + if yaw is not None: + self.yaw = self.wrap_yaw(float(yaw)) if wrap_yaw else float(yaw) + yaw0 = self.eef_yaw() + dyaw = self.yaw - yaw0 + R_goal = self._R() + p0 = self.eef_pos() + q0, held0, locked0 = t.key_q(), self.holding_key(), not t.unlocked + q_open_min = t.open_sign() * q0 # lowest key angle the open way during the move + dist = np.linalg.norm(tgt - p0) + direction = (tgt - p0) / max(dist, 1e-9) + s = 0.0 + self.stall_steps = 0 + for k in range(max_steps): + if speed is not None: + s = min(dist, s + speed * DT) + ref = p0 + direction * s + direction * min(dist - s, speed * DT * 1.5) + else: + ref = tgt + frac = min(1.0, (k + 1) * DT * W_MAX / max(abs(dyaw), 1e-6)) + R = _rotz(yaw0 + frac * dyaw) @ self.R0 + self._act(ref - self.eef_pos(), _rot_err(R, self.eef_mat()), self.grip) + q_open_min = min(q_open_min, t.open_sign() * t.key_q()) + if self.stall_steps >= STALL_EXIT: + break + if (np.linalg.norm(tgt - self.eef_pos()) < tol and (speed is None or s >= dist) and frac >= 1.0 + and np.linalg.norm(_rot_err(R_goal, self.eef_mat())) < 0.03): + break + stalled = self.stall_steps >= STALL_EXIT + if stalled: + # give up the unreached wrist angle; otherwise every later hold (e.g. while the gripper opens) keeps + # driving the wrist towards it and the arm swings away (seen in the agent self-test, 2026-10-08) + self.yaw = self.eef_yaw() + rep = dict(prim="move_to", reached=bool(np.linalg.norm(tgt - self.eef_pos()) < 0.02), + pos=self.eef_pos().round(4).tolist(), steps=k + 1, stalled=bool(stalled)) + self.log.append(rep) + dq = t.key_q() - q0 + locked_way = t.open_sign() * (dyaw if held0 else dq) < 0 + if (held0 and abs(dyaw) >= TURN_YAW) or abs(dq) > TURN_KEY: + self.turns.append(dict(step=self.n_steps, held_at_start=bool(held0), held_at_end=self.holding_key(), + key_start_deg=round(float(np.degrees(q0)), 1), + key_end_deg=round(float(np.degrees(t.key_q())), 1), + wrist_cmd_deg=round(float(np.degrees(dyaw)), 1), + wrist_turn_deg=round(float(np.degrees(self.eef_yaw() - yaw0)), 1), + stalled=bool(stalled), + hit_stop=bool(locked0 and locked_way and q_open_min <= -STOP_HIT))) + return rep + + def set_gripper(self, close, steps=15): + was_open = self.grip < 0 + rep = super().set_gripper(close, steps) + if close: + if self.holding_key(): + self._grasp_off = _wrap_half(self.eef_yaw() - self.task.key_world_yaw()) + if was_open: + off = self.eef_pos() - self.task.head_xyz() + self.closes.append(dict(step=self.n_steps, offset=off.round(4).tolist(), held=self.holding_key(), + width=round(self.gripper_width(), 4))) + else: + self._grasp_off = None + return rep + + +@register_task +class KeyTurn(LFFTask): + name = "l7_key_turn" + level = "L7" + category = "failed_interaction_inference" + capabilities = ("Perceive", "Reason", "Plan") + protocol = "cross" + instruction = ("Unlock the lock on the grey box: grasp the flat head of the brass key from above and turn the key " + "a quarter turn (90 degrees). The red bolt on the box slides in when it is unlocked.") + instruction_indirect = ("Open the lock of the small grey metal box: take hold of the flat gold-coloured tab that " + "sticks up out of its top and rotate it a quarter turn (90 degrees). The red block on the " + "box slides in when it is open.") + + # ------------------------------------------------------------ scene + def make_bddl(self): + lock = register_generated("LffKeyLock", lock_xml(MODEL), free=False) + return write_bddl(self.name, "unlock the lock", [], + fixtures=[(LOCK, lock, "lock_region", (-0.11, -0.01, -0.09, 0.01))]) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + pre = f"{LOCK}_{MODEL}" + self.jid = m.joint_name2id(pre + "_key_joint") + self.qa = m.jnt_qposadr[self.jid] + self.dof = m.jnt_dofadr[self.jid] + self.lock_bid = m.body_name2id(self.env.fixtures_dict[LOCK].root_body) + self.head_geom_name = pre + "_head" + self.head_gid = m.geom_name2id(self.head_geom_name) + self.bolt_gid = m.geom_name2id(pre + "_bolt") + self.inst = None + self.unlocked = False + + # agent-facing hooks ------------------------------------------------------- + def on_agent_tool(self, inst, name, args, report): + """The lock is a fixture, so the harness's `holding_object` / `touched_object` (movable objects only) never see + the key; add an explicit `holding_key` field and count key contacts as touches.""" + if self.sk is None or not isinstance(report, dict): + return + touched = self.sk.touch_since_report + self.sk.touch_since_report = False + if report.get("ok") and name in ("move_to", "open_gripper", "close_gripper", "push"): + report["holding_key"] = self.sk.holding_key() + if touched and "touched_object" in report: + report["touched_object"] = True + + # ------------------------------------------------------------ state helpers + def key_q(self): + return float(self.env.sim.data.qpos[self.qa]) + + def key_range(self): + return self.env.sim.model.jnt_range[self.jid] + + def key_world_yaw(self): + return float(self.inst["lock_yaw"]) + self.key_q() + + def head_xyz(self): + return self.env.sim.data.geom_xpos[self.head_gid].copy() + + def open_sign(self): + return 1.0 if self.inst["direction"] == "CCW" else -1.0 + + def check_unlock(self): + """latch: the bolt is thrown back once the key reaches the open position (and stays back)""" + if not self.unlocked and self.open_sign() * self.key_q() >= UNLOCK_AT: + self.unlocked = True + self.env.sim.model.geom_pos[self.bolt_gid] = BOLT_IN + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + return dict(seed=int(seed), direction="CCW" if seed % 2 == 0 else "CW", + lock_xy=[float(rng.uniform(-0.15, -0.02)), float(rng.uniform(-0.15, 0.15))], + lock_yaw=float(rng.uniform(-np.radians(15), np.radians(15)))) + + def apply_instance(self, inst): + self.inst = inst + m, d = self.env.sim.model, self.env.sim.data + cx, cy = inst["lock_xy"] + a = inst["lock_yaw"] + m.body_pos[self.lock_bid] = [cx, cy, envs.TABLE_Z] + m.body_quat[self.lock_bid] = [np.cos(a / 2), 0.0, 0.0, np.sin(a / 2)] + m.jnt_range[self.jid] = [-PLAY, STOP] if inst["direction"] == "CCW" else [-STOP, PLAY] + m.jnt_solref[self.jid] = [0.004, 1.0] + m.jnt_solimp[self.jid] = [0.99, 0.999, 0.001, 0.5, 2.0] + m.dof_frictionloss[self.dof] = KEY_FRICTION + m.geom_pos[self.bolt_gid] = BOLT_OUT + d.qpos[self.qa] = 0.0 + d.qvel[self.dof] = 0.0 + self.unlocked = False + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = KeySkills(self.env, self, recorder=recorder) + return self.sk + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + envs.settle(self.env, 20) + sk = self.sk + n_turns = len(sk.turns) + n_wrong = sum(t["hit_stop"] for t in sk.turns) + success = bool(self.unlocked) + open_deg = float(np.degrees(self.open_sign() * self.key_q())) + out = dict(success=success, unlocked=bool(self.unlocked), n_turns=n_turns, n_wrong_way=n_wrong, + trap_fired=n_wrong > 0, recovered_in_attempt=bool(n_wrong and success), + key_deg=round(np.degrees(self.key_q()), 1), open_deg=round(open_deg, 1), turns=sk.turns, + closes=sk.closes, first_turn=sk.turns[0] if sk.turns else None) + parts = [] + grasp_txt = "" + if sk.closes: + c = sk.closes[0] + o = c["offset"] + top = envs.TABLE_Z + LH + HEAD_Z + HEAD[2] + below = top - (o[2] + self.head_xyz()[2]) + grasp_txt = (f"When the gripper first closed, its centre was {_fb(o[0])} and {_lr(o[1])} of the centre of " + f"the key's head and {100 * below:.1f} cm below the top of the head; it " + + ("was holding the key." if c["held"] else "did not get hold of the key.")) + if success: + out["failure"] = None + parts.append("The lock is unlocked.") + elif n_turns == 0: + out["failure"] = "no_turn" + parts.append("The lock is still locked: the key was never turned.") + else: + out["failure"] = "still_locked" + parts.append("The lock is still locked.") + if n_turns == 1: + parts.append(_turn_txt(sk.turns[0], "During your turn")) + else: + parts.append(f"The key was turned (or pushed round) in {n_turns} separate moves.") + parts.append(_turn_txt(sk.turns[0], "During the first one")) + parts.append(_turn_txt(sk.turns[-1], "During the last one")) + if grasp_txt and not success: + parts.append(grasp_txt) + out["detail"] = " ".join(parts) + return out + + # ------------------------------------------------------------ scripted execution (cross protocol) + def execute(self, inst, params): + """Grasp the key head from above across its thickness (+ jitter), one wrist turn of `turn` degrees + (+ = counterclockwise seen from above), release, lift.""" + sk = self.sk + p = self.head_xyz() + np.r_[params.get("dxy", (0.0, 0.0)), params.get("dz", 0.0)] # perfect perception + yaw0 = self.key_world_yaw() + np.radians(params.get("dyaw", 0.0)) + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], p[2] + 0.08], yaw=yaw0) + sk.move_to([p[0], p[1], p[2]], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([p[0], p[1], p[2]], yaw=sk.eef_yaw() + np.radians(float(params["turn"])), max_steps=200) + sk.set_gripper(False, steps=8) + e = sk.eef_pos() + sk.move_to([e[0], e[1], e[2] + 0.08]) + + def default_params(self, inst): + """the prior from the user's example: try counterclockwise first""" + return dict(turn=90.0) + + def oracle_params(self, inst): + return dict(turn=90.0 * (1 if inst["direction"] == "CCW" else -1)) + + def adapt_params(self, inst, history): + """Scripted F2 learner. A turn after which the key rotated less than 10 deg the commanded way (it stopped) + -> that way is blocked -> turn the other way. A turn that rotated the key further but not far enough -> same + way, a bit more. Anything else (no turn, lost grip) -> repeat the last direction.""" + blocked = set() + good = 0 + for h in history: + t = h["outcome"].get("first_turn") + if t is None: + continue + sgn = int(np.sign(h["params"]["turn"])) + dk = t["key_end_deg"] - t["key_start_deg"] + if t["held_at_start"] and sgn * dk < 10.0: + blocked.add(sgn) + elif sgn * dk >= 10.0: + good = sgn + if good: + return dict(turn=100.0 * good) + last = int(np.sign(history[-1]["params"]["turn"])) + sgn = -last if last in blocked else last + if sgn in blocked: + sgn = -sgn + return dict(turn=90.0 * sgn) + + def blind_params(self, inst, attempt, rng): + """Same plan (counterclockwise quarter turn) with small random variation; no history.""" + return dict(turn=float(np.clip(rng.normal(90.0, 8.0), 70.0, 105.0)), dxy=rng.normal(0.0, 0.002, 2).tolist(), + dyaw=float(rng.normal(0.0, 4.0))) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l7_offcenter_push.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l7_offcenter_push.py new file mode 100644 index 0000000000000000000000000000000000000000..699db8fd5b26ef48186bfc77e8b7f351c214c496 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/l7_offcenter_push.py @@ -0,0 +1,613 @@ +"""L7 offcenter_push: push a long box straight forward into a marked rectangle. + +Category: failed_interaction_inference ("why did this contact not do what I expected?"). The code keeps level "L7"; +the paper files the task under L5 (misjudged physics). + +Hidden variable: the box's centre of mass is shifted along its long axis by e (|e| ~ U[4.5, 7.5] cm, either +side; implemented by moving the body's inertial frame, `body_ipos`). The box looks exactly the same for +every e (uniform colour, a symmetric tape stripe across its middle). + +Why the prior fails: the natural push is at the middle of the box's back face. On a table the friction +resultant acts below the centre of mass, so a push whose line does not pass near it turns the box: the +heavy end lags behind. Measured (closed gripper at yaw 0, 8 cm/s, mu 0.5): pushing at the middle turns the +box 17 to 41 deg; the rectangle (box + 2 cm margin per side) only holds the box up to FIT_ANGLE = 10.9 deg +(exact geometry, box centred in the rectangle). Pushing within ~2 cm of the centre of mass gives a straight +translation (< 1 deg); 3 cm off gives 5-14 deg. + +What must be learned from the failure: the turning direction tells which end is heavy (the end that +lagged), the amount tells roughly how far off the push was; push closer to the heavy end. F2 reports the box's +turn (direction and size, plus how far one end lags the other), where the box's centre ended relative to the +rectangle's centre, and where on the back face the gripper first touched it -- all relative measurements, never +absolute coordinates or e itself. + +Pushes per attempt: not limited (2026-10-19, user). Until then the instruction allowed one push per attempt (one +move command that moves the box) and an attempt with more failed, so that the agent could not steer the box inside +an attempt; that moved trial and error that belongs inside an attempt to the next attempt. The attempt now succeeds +when the box ends completely inside the rectangle and upright, however many pushes it took (and every push was made +with the closed gripper, see below). + +Error events (logged; they never end the attempt). A "push" is a move_to that moves the box > 1 cm or turns it +> 3 deg (unchanged definition). After every push the box is classified against the rectangle (`box_fit`): +over_turned (|yaw| > FIT_ANGLE: it fits at no position), overshot (a corner past the far edge), sideways (a corner +past a side edge), short (a corner still in front of the near edge, i.e. not pushed far enough yet), inside. A push +is `bad` when it leaves the box over_turned, overshot or sideways (or tipped over: upright cos < 0.5) -- not inside, +and not merely short of the rectangle (pushing straight on can fix "short", so pushing the box in in several steps is +not an error). +Outcome: n_pushes, n_bad_pushes, n_turned_pushes (bad pushes that left the box over_turned), n_trap_events (pushes +that took the box from a good state -- inside or short -- into a bad one, i.e. how often the trap fired anew), +trap_fired = n_bad_pushes > 0, recovered_in_attempt = trap_fired and success, first_push (record of the first push) +with first_push_yaw_deg and first_interaction_ok (the first push left the box inside, or short and not turned out). +irrecoverable: the box tipped over (upright cos < 0.5 after a move, < 0.95 after the final settle), fell off the +table, or went out of reach (its centre beyond world x = X_LOST, where the gripper can no longer be put down in front +of it at pushing height to push it back, or beyond |y| = Y_LOST); logged with the control step, the attempt goes on. + +Closed gripper (2026-10-19): the instruction says "with the closed gripper", and a push made with the fingers open +(> OPEN_W apart when the move starts) now makes the attempt fail (failure "open_gripper" if the box is otherwise +inside). Reason, measured: open fingers touch the back face at two points ~8 cm apart, so ONE push at the middle of +the back face goes straight unless |e| > ~7 cm -- 22 of 25 instances (validation seeds 1000-1019, main 3000-3004) +succeeded that way without the centre of mass ever mattering. The box cannot be grasped, lifted or dragged by +pressing on its top (9 cm deep, the gripper opens 8 cm; measured), so no rule is needed for that. + +Correction cost (measured 2026-10-19, task card): after the natural first push (middle, whole distance) the box is +turned 17-41 deg and lies across the rectangle. What repairs it: get in front of the leading (light) end and push it +back -- the box turns back with little translation -- then push the box in near the heavy end. The scripted +corrector (adaptive) did that in attempt 1 on 19 of 20 instances, 7-15 extra commands (median 7: 2 more pushes). +What does not: pushing the lagging end forward from behind turns the box back only slowly and carries it past the +rectangle (0 of 25 instances repaired that way; 11 ended out of reach). Near the reach limit the fingers ride up onto +the box instead of pushing it back. A cautious first push of 3 cm at the middle turns the box only 6.5-10.9 deg (below +FIT_ANGLE, so no error event) and shows the heavy end; probe + turn back + push in succeeded on 25 of 25 instances in +11 commands. So the task does not meet design rule R3 (a cost >= 10 commands for the common-sense first interaction); +its signal is clean success vs. in-attempt recovery (trap_fired / recovered_in_attempt) and first_push_yaw_deg. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, _wrap, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +BOX = "box_1" +HALF = np.array([0.045, 0.11, 0.02]) # 9 (x) x 22 (y, long axis) x 4 cm: too wide for the 8 cm gripper +MASS = 0.6 +MU = 0.5 +MARGIN = 0.02 # target rectangle = box footprint + 2 cm on every side +RECT_HALF = HALF[:2] + MARGIN +E_MIN, E_MAX = 0.045, 0.075 +Z_PUSH = envs.TABLE_Z + 0.02 # grasp-point height during the push (finger tips ~1 cm above the table) +Z_SAFE = envs.TABLE_Z + 0.12 # travel height of the scripted corrector (8 cm above the box top) +PUSH_SPEED = 0.08 +FINGER_AHEAD = 0.009 # the closed fingers' front face is ~0.9 cm ahead of the grasp point (measured, yaw 0) +RUNUP = 0.04 +MOVE_TOL = 0.01 # a command "moved the box" if its centre moved this much ... +TURN_TOL = np.radians(3.0) # ... or it turned this much +TOUCH_TOL = 0.002 # the box "started to move" in a command once its centre moved this much +OPEN_W = 0.01 # finger opening above which a push counts as made with the gripper open (closed on nothing: 0.002 m) +TABLE_HALF = (0.5, 0.6) # LIBERO main_table top, centred at the world origin (table_collision geom) +# Reach at pushing height (grasp point 2 cm above the table, yaw 0; measured 2026-10-19): the gripper gets to world +# x = 0.10 within 1 cm for |y| <= 0.15; asked for more it stops at x ~ 0.13-0.17, sagging to the table. Pushing a box +# back from in front of it (measured, box not turned): still works with the box's centre at x = 0.125 (far face at +# 0.17); with the centre at 0.135 the fingers ride up onto the box or push it further away. A box turned 25 deg with +# its centre at 0.113 (far corner at 0.20) was still pushed back. So a box whose centre is past X_LOST counts as out of +# reach. The rectangle's far edge lies at world x = -0.055 ... 0.055. +X_LOST = 0.13 +Y_LOST = 0.40 +X_DOWN = 0.14 # farthest x at which the scripted corrector puts the gripper down in front of the box + + +def _fit_angle(half=HALF[:2], rect=RECT_HALF): + """Largest |yaw| at which the box's footprint still fits inside the rectangle (box centred in it): the + rotated footprint's half extents are (a cos t + b sin t, a sin t + b cos t).""" + t = np.radians(np.arange(0.0, 90.0, 0.01)) + ok = (half[0] * np.cos(t) + half[1] * np.sin(t) <= rect[0]) & (half[0] * np.sin(t) + half[1] * np.cos(t) <= rect[1]) + return float(t[np.argmin(ok)] - np.radians(0.01)) if not ok.all() else np.pi / 2 + + +FIT_ANGLE = _fit_angle() # 10.9 deg + + +def long_box_xml(name, half=HALF, mass=MASS, rgba=(0.72, 0.53, 0.33, 1.0), tape_rgba=(0.88, 0.80, 0.62, 1.0)): + """Solid box with an explicit inertial whose position is offset from the body origin at compile time, so + MuJoCo keeps the inertial frame separate (sameframe would otherwise ignore later changes of body_ipos).""" + I = mass / 12 * np.array([4 * (half[1] ** 2 + half[2] ** 2), 4 * (half[0] ** 2 + half[2] ** 2), + 4 * (half[0] ** 2 + half[1] ** 2)]) + tape = (half[0] + 0.0005, 0.012, 0.0006) + g = (f' \n' + f' \n' + f' \n' + f' ') + return _wrap(name, g, half[2], float(np.hypot(half[0], half[1]))) + + +def rect_frame_xml(name, inner_half=RECT_HALF, line_w=0.006, line_rgba=(0.1, 0.55, 0.15, 1.0), + fill_rgba=(0.75, 0.92, 0.75, 1.0)): + """Flat, visual-only rectangle drawn on the table (light fill + dark outline, no collisions).""" + hx, hy = inner_half + ox, oy = hx + line_w, hy + line_w + parts = [((0, 0, 0.0004), (ox, oy, 0.0004), fill_rgba), + ((0, hy + line_w / 2, 0.0010), (ox, line_w / 2, 0.0002), line_rgba), + ((0, -hy - line_w / 2, 0.0010), (ox, line_w / 2, 0.0002), line_rgba), + ((hx + line_w / 2, 0, 0.0010), (line_w / 2, oy, 0.0002), line_rgba), + ((-hx - line_w / 2, 0, 0.0010), (line_w / 2, oy, 0.0002), line_rgba)] + g = "\n".join(f' ' for p, sz, c in parts) + return _wrap(name, g, 0.0012, float(np.hypot(ox, oy))) + + +def _yaw(quat_wxyz): + w, x, y, z = quat_wxyz + return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))) + + +def _rot(a): + return np.array([[np.cos(a), -np.sin(a)], [np.sin(a), np.cos(a)]]) + + +def _wrap_pi(a): + return float((a + np.pi) % (2 * np.pi) - np.pi) + + +def box_corners(p_xy, yaw): + R = _rot(yaw) + return np.array([np.asarray(p_xy[:2], float) + R @ np.array([sx * HALF[0], sy * HALF[1]]) + for sx in (-1, 1) for sy in (-1, 1)]) + + +def box_fit(p_xy, yaw, t_xy): + """The box's footprint against the (axis-aligned) target rectangle centred at t_xy. bad = it cannot get into the + rectangle by being pushed straight on: turned beyond FIT_ANGLE, a corner past the far edge, or past a side edge.""" + c = box_corners(p_xy, yaw) - np.asarray(t_xy, float)[:2] + eps = 1e-6 + inside = bool(np.all(np.abs(c[:, 0]) <= RECT_HALF[0] + eps) and np.all(np.abs(c[:, 1]) <= RECT_HALF[1] + eps)) + yw = (yaw + np.pi / 2) % np.pi - np.pi / 2 # the footprint is symmetric under a half turn + over = bool(abs(yw) > FIT_ANGLE) + overshot = bool(np.any(c[:, 0] > RECT_HALF[0] + eps)) + sideways = bool(np.any(np.abs(c[:, 1]) > RECT_HALF[1] + eps)) + short = bool(np.any(c[:, 0] < -RECT_HALF[0] - eps)) + return dict(inside=inside, over_turned=over, overshot=overshot, sideways=sideways, short=short, + bad=bool(over or overshot or sideways)) + + +def _lr(v, unit="cm"): + return f"{100 * abs(v):.1f} {unit} to the {'left' if v > 0 else 'right'}" + + +def _fb(v): + return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}" + + +def _turn_words(deg): + return f"{abs(deg):.0f} degrees {'counterclockwise' if deg > 0 else 'clockwise'}" + + +class _Budget(Exception): + """the scripted policy used up the agent command budget of the attempt""" + + +class PushSkills(Skills): + """Skills that log, for whoever drives them (scripted policy or agent), which move_to commands moved the + box (pushes), where the gripper touched it, the box's state after every push, and whether the box was lost.""" + + def __init__(self, env, bias=None, recorder=None, target=None): + super().__init__(env, bias=bias, recorder=recorder) + self.target = None if target is None else np.asarray(target, float)[:2] + self.first_touch = None # where the gripper's centre was (box frame) when the box first moved + self._p0, self._yaw0 = self._box_pose() + self.box_moves = [] # one entry per move_to that moved / turned the box (a "push") + self.n_moves = 0 # move_to commands (an agent's move_eef with a motion = one move_to) + self.lost = {} # irrecoverable condition -> control step at which it was first seen + self._mv = None # the move_to in progress: box pose at its start, first touch inside it + + def _box_pose(self): + p = envs.obj_pos(self.env, BOX) + return p, _yaw(envs.obj_quat(self.env, BOX)) + + def _local(self, p0, yaw0): + """gripper centre in the box frame given by (p0, yaw0): (u along the short side, v along the long side)""" + return (_rot(yaw0).T @ (self.eef_pos()[:2] - p0[:2])).tolist() + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + if self.first_touch is None or (self._mv is not None and self._mv["touch"] is None): + # "touch" = the first control step at which the box has moved 2 mm. Detected from the box's motion, + # not from contacts: a stiff gripper pushing a box makes a stick-slip contact that is often absent at the + # control-step boundaries (measured), so contact polling misses pushes. + p, _ = self._box_pose() + if self.first_touch is None and np.linalg.norm(p[:2] - self._p0[:2]) > TOUCH_TOL: + self.first_touch = dict(local=self._local(self._p0, self._yaw0), step=self.n_steps) + if self._mv is not None and self._mv["touch"] is None and np.linalg.norm(p[:2] - self._mv["p0"][:2]) > TOUCH_TOL: + self._mv["touch"] = self._local(self._mv["p0"], self._mv["yaw0"]) + + def fit(self, p=None, yaw=None): + if p is None: + p, yaw = self._box_pose() + return box_fit(p[:2], yaw, self.target) if self.target is not None else None + + def check_lost(self, final=False): + """record irrecoverable box states (tipped, off the table, out of reach); returns the current ones""" + p, _ = self._box_pose() + up = envs.obj_upright_cos(self.env, BOX) + now = [] + if up < (0.95 if final else 0.5): + now.append("tipped") + if p[2] < envs.TABLE_Z - 0.02 or abs(p[0]) > TABLE_HALF[0] or abs(p[1]) > TABLE_HALF[1]: + now.append("off_table") + elif p[0] > X_LOST or abs(p[1]) > Y_LOST: + now.append("out_of_reach") + for w in now: + self.lost.setdefault(w, self.n_steps) + return now + + def move_to(self, target, *args, **kwargs): + p0, y0 = self._box_pose() + fit0 = self.fit(p0, y0) + bad0 = fit0 is not None and (fit0["bad"] or envs.obj_upright_cos(self.env, BOX) < 0.5) + self._mv = dict(p0=p0, yaw0=y0, touch=None) + width0 = self.gripper_width() + self.n_moves += 1 + try: + rep = super().move_to(target, *args, **kwargs) + finally: + mv, self._mv = self._mv, None + p1, y1 = self._box_pose() + dturn = _wrap_pi(y1 - y0) + if np.linalg.norm(p1[:2] - p0[:2]) > MOVE_TOL or abs(dturn) > TURN_TOL: + rec = dict(step=self.n_steps, moved_cm=round(100 * float(np.linalg.norm(p1[:2] - p0[:2])), 1), + turned_deg=round(float(np.degrees(dturn)), 1), yaw_deg=round(float(np.degrees(y1)), 1), + gripper_open=bool(width0 > OPEN_W)) + t = mv["touch"] + if t is not None: + u, v = t + face = ("back" if u < -HALF[0] + 0.005 else "front" if u > HALF[0] - 0.005 else + "left_end" if v > 0 else "right_end") + rec.update(touch_u=round(float(u), 4), touch_v=round(float(v), 4), face=face) + fit1 = self.fit(p1, y1) + if fit1 is not None: + tipped = envs.obj_upright_cos(self.env, BOX) < 0.5 + bad = bool(fit1["bad"] or tipped) + rec.update(inside=fit1["inside"] and not tipped, over_turned=fit1["over_turned"], + overshot=fit1["overshot"], sideways=fit1["sideways"], tipped=bool(tipped), bad=bad, + new_trap=bool(bad and not bad0)) + self.box_moves.append(rec) + self.check_lost() + return rep + + +@register_task +class OffcenterPush(LFFTask): + name = "l7_offcenter_push" + level = "L7" + category = "failed_interaction_inference" + capabilities = ("Perceive", "Reason", "Utilize") + protocol = "cross" + # 2026-10-19 (wording): the instruction states only the end state. "straight forward ... without turning" read as + # a rule on the motion (no turning on the way, push only forward), but success is judged on the end state alone + # (completely inside the rectangle -- which bounds the turn to FIT_ANGLE -- upright, every push with the closed + # gripper), and the repair that works pushes the leading end back from in front of the box. + instruction = ("Slowly push the long brown box with the closed gripper so that it ends up completely inside the " + "green rectangle ahead of it (farther from the robot).") + instruction_indirect = ("Slowly push the long cardboard-coloured block with the closed gripper so that it ends up " + "completely inside the marked green area ahead of it (farther from the robot).") + + # ------------------------------------------------------------ scene + def make_bddl(self): + box = register_generated("LffL7LongBox", long_box_xml("lff_l7_long_box")) + zone = register_generated("LffL7TargetRect", rect_frame_xml("lff_l7_target_rect"), free=False) + objs = [(BOX, box, "box_region", (-0.18, -0.01, -0.16, 0.01))] + fixtures = [("zone_1", zone, "zone_region", (-0.06, -0.01, -0.04, 0.01))] + return write_bddl(self.name, "push the long box into the green rectangle", objs, fixtures=fixtures) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + e = float(rng.choice([-1.0, 1.0]) * rng.uniform(E_MIN, E_MAX)) + return dict(seed=int(seed), box_xy=[float(rng.uniform(-0.20, -0.14)), float(rng.uniform(-0.08, 0.08))], + target_dist=float(rng.uniform(0.08, 0.13)), com_offset=e) + + def target_xy(self, inst): + return np.array([inst["box_xy"][0] + inst["target_dist"], inst["box_xy"][1]]) + + def apply_instance(self, inst): + m = self.env.sim.model + zone = self.env.fixtures_dict["zone_1"] + for g in range(m.ngeom): # the rectangle is a flat marker + if (m.geom_id2name(g) or "").startswith("zone_1_"): + m.geom_contype[g] = 0 + m.geom_conaffinity[g] = 0 + t = self.target_xy(inst) + zb = m.body_name2id(zone.root_body) + m.body_pos[zb] = [t[0], t[1], envs.TABLE_Z + 0.0002] + m.body_quat[zb] = [1.0, 0.0, 0.0, 0.0] + bid = envs.body_id(self.env, BOX) + m.body_mass[bid] = MASS + m.body_ipos[bid] = [0.0, inst["com_offset"], 0.0] + envs.refit_bounds(self.env, bid) # the collision BVH lives in the inertial frame (envs.refit_bounds) + envs.set_friction(self.env, BOX, MU) + x0, y0 = inst["box_xy"] + envs.set_obj_pose(self.env, BOX, [x0, y0, envs.TABLE_Z + HALF[2] + 0.001]) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = PushSkills(self.env, recorder=recorder, target=self.target_xy(inst)) + self.sim0 = self.sk.n_steps + return self.sk + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + envs.settle(self.env, 30) + sk = self.sk + p = envs.obj_pos(self.env, BOX) + yaw = _yaw(envs.obj_quat(self.env, BOX)) + t = self.target_xy(inst) + fit = box_fit(p[:2], yaw, t) + inside = fit["inside"] + upright = envs.obj_upright_cos(self.env, BOX) > 0.95 + sk.check_lost(final=True) + pushes = sk.box_moves + n_push = len(pushes) + n_bad = sum(bool(m.get("bad")) for m in pushes) + n_open = sum(bool(m.get("gripper_open")) for m in pushes) + off = p[:2] - t + lag = 2 * HALF[1] * np.sin(yaw) # how far the +y end is behind (+) the -y end along x + success = bool(inside and upright and n_open == 0) + first = pushes[0] if pushes else None + out = dict(success=success, inside=bool(inside), upright=bool(upright), + n_pushes=n_push, n_bad_pushes=n_bad, + n_turned_pushes=sum(bool(m.get("over_turned")) for m in pushes), + n_trap_events=sum(bool(m.get("new_trap")) for m in pushes), + trap_fired=n_bad > 0, recovered_in_attempt=bool(n_bad and success), + first_push=first, first_push_yaw_deg=None if first is None else first["yaw_deg"], + first_interaction_ok=None if first is None else bool(not first.get("bad")), + n_open_gripper_pushes=n_open, + irrecoverable=bool(sk.lost), irrecoverable_why=dict(sk.lost), + n_box_moving_commands=n_push, box_moves=pushes, n_move_commands=sk.n_moves, + sim_s=round((sk.n_steps - getattr(self, "sim0", 0)) * 0.05, 1), + yaw_deg=round(float(np.degrees(yaw)), 1), + centre_offset=[round(float(off[0]), 4), round(float(off[1]), 4)], + touch_offset=None) + parts = [] + if sk.first_touch is None: + out["failure"] = "not_touched" + parts.append("The box did not move: the gripper never pushed it.") + else: + lt = sk.first_touch["local"] + out["touch_offset"] = round(float(lt[1]), 4) + if success: + parts.append("The box is completely inside the rectangle.") + elif not upright: + out["failure"] = "tipped" + parts.append("The box tipped over.") + elif inside: + out["failure"] = "open_gripper" + parts.append("The box is completely inside the rectangle, but it was pushed with the gripper open; " + "the task asks for pushing with the closed gripper.") + else: + out["failure"] = "turned" if abs(np.degrees(yaw)) > 6 else "position" + parts.append("The box is not completely inside the rectangle.") + if n_push > 1: + txt = f"It was moved by {n_push} separate move commands" + if abs(first["yaw_deg"]) >= 1.0: + txt += f"; after the first one it had turned {_turn_words(first['yaw_deg'])} (seen from above)" + parts.append(txt + ".") + if n_open and out.get("failure") != "open_gripper": + parts.append("The gripper was open during " + ("that push." if n_push == 1 else + f"{n_open} of the pushes.")) + turn = np.degrees(yaw) + if abs(turn) >= 1.0: + parts.append(f"It {'ended up turned' if n_push > 1 else 'turned'} {_turn_words(turn)} (seen from " + f"above): its {'left' if lag > 0 else 'right'} end ended {100 * abs(lag):.1f} cm " + f"further back than its {'right' if lag > 0 else 'left'} end.") + else: + parts.append("It did not turn (less than 1 degree)." if n_push <= 1 else + "It ended up not turned (less than 1 degree).") + parts.append(f"Its centre ended {_fb(off[0])} and {_lr(off[1])} of the rectangle's centre.") + parts.append(f"When the box started to move, the gripper's centre was {_lr(lt[1])} of the middle of " + f"the box (measured along the box's long side).") + out["detail"] = " ".join(parts) + return out + + # ------------------------------------------------------------ scripted primitives (agent-command counted) + def _cmd(self, target, yaw=None, speed=None, tol=0.004, max_steps=250): + """one agent command (move_eef; a gripper change rides on a move)""" + self.ncmd = getattr(self, "ncmd", 0) + 1 + budget = getattr(self, "budget", None) + if budget is not None and self.ncmd > budget: + raise _Budget() + self.sk.move_to(target, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + if budget is not None and self._sim_used() >= 3.0 * budget: # the server's motion budget (3 s per command) + raise _Budget() + + def _sim_used(self): + return (self.sk.n_steps - getattr(self, "sim0", 0)) * 0.05 + + def _push_at(self, face, v, dist, speed=PUSH_SPEED, runup=RUNUP): + """One push on the box as it lies now, with the closed gripper rotated to the face: face "back" (push + forward along the box's short side), "front" (push backwards) at long-side coordinate v (box frame), or + "left_end" / "right_end" (push along the long side at the middle of that end face). `dist` = how far the + fingers' front travels past the face. Commands: up (if low, 1), above the run-up point (1), down (1), push (1).""" + sk = self.sk + p, yaw = sk._box_pose() + R = _rot(yaw) + if face in ("back", "front"): + s = -1.0 if face == "back" else 1.0 + n, q, gyaw = R @ np.array([s, 0.0]), p[:2] + R @ np.array([s * HALF[0], v]), yaw + else: + s = 1.0 if face == "left_end" else -1.0 + n, q, gyaw = R @ np.array([0.0, s]), p[:2] + R @ np.array([0.0, s * HALF[1]]), yaw + np.pi / 2 + start = q + n * (runup + FINGER_AHEAD) + end = q - n * (dist - FINGER_AHEAD) + e = sk.eef_pos() + if e[2] < Z_PUSH + 0.05: + self._cmd([e[0], e[1], Z_SAFE], speed=0.2) + self._cmd([start[0], start[1], Z_SAFE], yaw=gyaw) + self._cmd([start[0], start[1], Z_PUSH], tol=0.003) + self._cmd([end[0], end[1], Z_PUSH], speed=speed, tol=0.004, max_steps=400) + + # ------------------------------------------------------------ scripted execution (cross protocol) + def execute(self, inst, params): + """Closed gripper behind the box at lateral offset `c` (from the box's middle, along its long axis), then one + slow straight move_to forward ending `end_dx` beyond the nominal end point (target centre minus half the box + depth minus the finger offset), then lift. 4 commands (the gripper closes with the first one).""" + sk = self.sk + p = envs.obj_pos(self.env, BOX) # perfect perception of the current scene + t = self.target_xy(inst) + c = float(params["c"]) + y = p[1] + c + face = p[0] - HALF[0] + x_end = t[0] - HALF[0] - FINGER_AHEAD + float(params.get("end_dx", 0.0)) + sk.set_gripper(True, steps=8) + self._cmd([face - RUNUP, y, Z_PUSH + 0.08], yaw=0.0) + self._cmd([face - RUNUP, y, Z_PUSH], tol=0.003) + self._cmd([x_end, y, Z_PUSH], speed=PUSH_SPEED, tol=0.004, max_steps=400) + self._cmd([x_end - 0.03, y, Z_PUSH + 0.10], speed=0.2) + + def default_params(self, inst): + return dict(c=0.0, end_dx=0.0) # Sonnet 5.5 (cla2 / cla4 / full5): yaw 0, middle of the back face, one push + + def oracle_params(self, inst): + return dict(c=float(inst["com_offset"]), end_dx=0.0) + + STEP = 0.06 # first correction toward the lagging end (the expected |e| range is unknown to the learner) + YAW_OK = 3.0 # deg: the corrector turns the box back until it is within this + GAIN0 = 2.8 # deg of turn per cm of a push at the leading end from the front, 3 cm from the end (measured) + SAFE_V = HALF[1] - 0.02 # contact points stay 2 cm inside the ends + + def bracket(self, pushes): + """Contact point estimate from logged pushes on the back / front face: a push whose box turned + counterclockwise passed to the right of the centre of mass when pushing forward (back face) and to its left + when pushing backwards (front face); a long push that did not turn passed within ~2 cm of it.""" + lo, hi = -self.SAFE_V, self.SAFE_V + lo_set = hi_set = False + for m in pushes: + if m.get("face") not in ("back", "front") or m.get("gripper_open"): + continue + v, turn = m["touch_v"], m["turned_deg"] * (1.0 if m["face"] == "back" else -1.0) + if turn > 3.0: + lo, lo_set = max(lo, v + 0.01), True + elif turn < -3.0: + hi, hi_set = min(hi, v - 0.01), True + elif abs(turn) < 1.5 and m["moved_cm"] >= 3.0: + lo, hi, lo_set, hi_set = max(lo, v - 0.02), min(hi, v + 0.02), True, True + if lo > hi: # inconsistent (contacts slide): trust the newest + lo, hi = hi, lo + if lo_set and hi_set: + c = 0.5 * (lo + hi) + elif lo_set: + c = lo + self.STEP + elif hi_set: + c = hi - self.STEP + else: + c = 0.0 + return float(np.clip(c, -self.SAFE_V, self.SAFE_V)) + + def adapt_params(self, inst, history): + """Cross-attempt start point: push where the pushes of the earlier attempts put the centre of mass.""" + return dict(c=round(self.bracket([m for h in history for m in h["outcome"]["box_moves"]]), 4), end_dx=0.0) + + @staticmethod + def _front_runup(p, yaw, v): + """run-up for a push on the front face at v that keeps the gripper's put-down point within X_DOWN; None when + even a 1.5 cm run-up does not fit (the box is too far forward to get in front of it)""" + R = _rot(yaw) + f, n_out = p[:2] + R @ np.array([HALF[0], v]), R @ np.array([1.0, 0.0]) + runup = min(RUNUP, (X_DOWN - f[0]) / max(n_out[0], 0.2) - FINGER_AHEAD) + return float(runup) if runup >= 0.015 else None + + def adaptive_attempt(self, inst, c0, prior_pushes=()): + """In-attempt corrector: the first push as `execute` (at c0: the middle in attempt 1, like the naive policy); + then, after every push, look at the box (perfect perception) and push again until it is inside or the agent + budget would run out. Turned more than YAW_OK -> push its leading end back from the front (it turns back with + little translation), or if it is too far forward for that, the lagging end forward from behind; not turned + but short / past the far edge / out at a side -> push it straight from behind / from the front at the + estimated centre of mass, or along its long side at an end face. Returns the number of corrective pushes.""" + self.execute(inst, dict(c=c0, end_dx=0.0)) + sk = self.sk + t = self.target_xy(inst) + gain = self.GAIN0 + sim_budget = 3.0 * self.budget if self.budget is not None else np.inf + n = 0 + while True: + p, yaw = sk._box_pose() + fit = sk.fit(p, yaw) + if fit["inside"] or sk.lost: + return n + if (self.budget is not None and self.ncmd + 4 > self.budget) or self._sim_used() + 10.0 > sim_budget: + return n + n += 1 + yd = np.degrees(yaw) + c_est = self.bracket(list(prior_pushes) + sk.box_moves) + if abs(yd) > self.YAW_OK: + for vm in (HALF[1] - 0.03, 0.06, 0.04, 0.02): # the leading (light) end, or nearer the middle if + v_lead = -np.sign(yd) * vm # the end is out of reach; +v = the box's left end + runup = self._front_runup(p, yaw, v_lead) + if runup is not None: + break + if runup is not None: + d = float(np.clip(abs(yd) / gain, 1.0, 10.0)) / 100 + self._push_at("front", v_lead, d, runup=runup) + dy = abs(yd) - abs(np.degrees(sk._box_pose()[1])) + if dy > 1.0: + gain = float(np.clip(dy / (100 * d), 1.0, 5.0)) + else: + self._push_at("back", np.sign(yd) * (HALF[1] - 0.01), 0.03) + else: + dx = t[0] - p[0] + if fit["overshot"]: + runup = self._front_runup(p, yaw, c_est) + if runup is None: + return n + self._push_at("front", c_est, max(0.005, -dx), runup=runup) + elif fit["sideways"]: + dyy = t[1] - p[1] + self._push_at("right_end" if dyy > 0 else "left_end", 0.0, max(0.005, abs(dyy) - 0.005)) + else: + self._push_at("back", c_est, max(0.005, dx)) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """Cross protocol with the agent's command budget per attempt (agent_max_steps, default 40 commands and + 3 s of motion per command; one move_eef = one command). naive / oracle / blind: one push, then finish. + adaptive: in-attempt corrector (`adaptive_attempt`); attempt 1 starts with the naive push, later attempts + at the contact point estimated from all earlier pushes.""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + self.ncmd, self.budget = 0, int(getattr(self, "agent_max_steps", 40)) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "adaptive": + params = self.default_params(inst) if a == 0 else self.adapt_params(inst, history) + else: + raise ValueError(kind) + try: + if kind == "adaptive": + prior = [m for h in history for m in h["outcome"]["box_moves"]] + params["corrections"] = self.adaptive_attempt(inst, params["c"], prior) + else: + self.execute(inst, params) + except _Budget: + params["budget_used_up"] = True + self.budget = None + out = self.outcome(inst) + out["commands"] = self.ncmd + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history + + blind_sigma = 0.008 + + def blind_params(self, inst, attempt, rng): + """Same plan (push at the middle) with a small random variation of the contact point; no history.""" + return dict(c=float(rng.normal(0.0, self.blind_sigma)), end_dx=0.0) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_balance_board.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_balance_board.py new file mode 100644 index 0000000000000000000000000000000000000000..0e4ceaea2c011176291dd2723cc94d344f23d991 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_balance_board.py @@ -0,0 +1,817 @@ +"""LH balance_board: put four look-alike cubes on their marks on a plank that rests loose across a narrow block (a +seesaw); loading it in the wrong order tips the plank, and every cube already on it slides down to the low end. + +Family: long-horizon self-disturbance ("state_restoration"): each stage is a plain pick-and-place of a cube onto its +mark, but a later placement can tip the plank, which sends the cubes placed before it (earlier progress) sliding off +their marks. The agent has to notice it, re-level the plank and re-place them before finishing (within an attempt), and +learn a loading order that keeps the plank level (across attempts; the final-state judge does not enforce an order). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a grey support (fixture: two 1.5 cm blocks with a 1 cm slot between them, together 4 cm along the plank x 10 cm x + 6 cm high, flat tops) under the middle of + * a dark wooden plank (free body, 46 cm long, pointing away from the robot, 8 cm wide, 1.5 cm thick, 0.5 kg) lying + loose on it, level, with a 2 cm lip across each end. A thin keel under the plank's middle hangs in the slot and keeps + the plank from wandering along the support (+-3 mm); nothing holds it down. It stays level while the combined centre + of mass of plank + cubes is above the support's 4 cm top; otherwise it tips until its low end touches the table + (about 17 degrees); + * four marks (5.8 cm squares, outline + light fill) on the plank, two on each side of the block: an inner one + (8.5-9.5 cm from the middle) and an outer one (15.5-16.5 cm); the colour of each mark is random; + * four 4.5 cm cubes (red, green, blue, yellow) on the table, two left and two right of the plank (random places). + They look alike except for the colour. Cube and plank surfaces are slick (friction 0.2 < tan 17 deg): on a tipped + plank every cube slides down to the lip at the low end. +Why along x with lips (measured, see the task card): with the plank left-right and open ends, the cubes slid off the +ends onto the table 0-11 cm past them, and a default top-down grasp there (fingers left-right, the Panda hand is 21 cm +wide along them) pressed the plank's end down and tipped it again -- restoring became a loop. Along x the default grasp +is across the plank, and the lips keep the cubes on the plank within reach. + +Hidden variable: the cube masses. "Hazard" instances (13 of every 20 consecutive seeds): the two cubes that belong on +the inner marks are heavy (stone, 0.19-0.24 kg), the two for the outer marks are light (48-56 g); the final layout is +balanced. A heavy cube alone on its inner mark tips the plank (1.28-1.43 x the tipping moment); a light one alone on its +outer mark does not (0.72-0.78 x); in the zig-zag order below no step exceeds 0.72-0.81 x. So the only safe loading +orders are "an outer cube, then the inner cube on the OTHER side, then the other inner cube, then the last outer cube" +(zig-zag); end-to-end, alternating outer-first (outer, outer, inner, inner) and inner-first orders all tip it. +"Benign" instances: all four cubes light (26-34 g); no order tips (worst step 0.63-0.75 x). + +Why the natural order fails: nothing in the image shows which cubes are heavy. Any natural order (nearest cube first, +the marks from one end to the other, or the cautious "alternate sides, outer marks first") tips the plank in a hazard +instance; the cubes on it slide to the low end and keep it tipped. A natural plan then keeps going and finishes with +cubes off their marks. What must be learned: check the marks after each placement / before finishing, unload the low +end and re-place (within the attempt), and use the tip to infer which cubes are heavy (an inner cube tipped it; the +layout must balance in the end, so the other inner cube is heavy too) and load in the zig-zag order (across attempts). + +Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (every cube on its +mark, plank level within 3 degrees and still on its support (10-11), nothing held, scene static) plus an event log of every stage predicate (achieved / +lost / restored, with step and cause) and every tip (which end went down, the cube released just before) for the server +log; F1 gives the agent only success / failure. +""" +import itertools + +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +TZ = envs.TABLE_Z + +# ---------------------------------------------------------------- geometry / physics +# plank frame: y along the plank (+y = the end toward the robot), x across it, z up. The plank and the block are +# yawed 90 deg, so plank +y = world -x. +PL_HL, PL_HW, PL_HT = 0.23, 0.04, 0.0075 # plank half length, half width, half thickness +LIP_T, LIP_H = 0.008, 0.02 # lip across each end (inside the 46 cm), height above the plank's top +PLANK_MASS = 0.50 +PLANK_ROT_DAMP = 0.01 # N m s / rad on the plank's rotation: after its low end is unloaded it swings over to ~10 deg +# and is calm in ~1.5 s (no damping: ~13 deg and ~2.7 s); the tip itself is not slowed (measured) +PLANK_YAW = np.pi / 2 +RIDGE_HW, RIDGE_HX, RIDGE_H = 0.02, 0.05, 0.06 # support: half width along the plank (s), half depth, height +SLOT_HW = 0.005 # the support is two blocks with a 1 cm slot between them +KEEL_HW, KEEL_H = 0.002, 0.010 # keel under the plank's middle (4 mm x 8 cm x 1 cm) hanging in the slot +CUBE_E = 0.045 +MU = 0.20 # cubes and plank: the cube-plank contact slides above 11 deg; ridge (1.0), table (0.6), finger pads (2.0) win +MU_RIDGE = 1.0 +MARK_HALF, MARK_LINE = 0.029, 0.004 +WOOD = (0.42, 0.27, 0.15, 1.0) # dark walnut: contrasts with the light table, so the tilt reads in the images + +COLORS = ("red", "green", "blue", "yellow") +RGBA = dict(red=(0.85, 0.12, 0.10, 1.0), green=(0.10, 0.62, 0.20, 1.0), blue=(0.15, 0.30, 0.88, 1.0), + yellow=(0.93, 0.78, 0.10, 1.0)) +CUBES = {c: f"{c}_cube_1" for c in COLORS} +PLANK, RIDGE = "plank_1", "ridge_1" +PLANK_MODEL = "lff_lh_bb_plank" +# mark slots in plank-frame order (+y first): the robot's end outer / inner, then the far end inner / outer +SLOTS = ("near_outer", "near_inner", "far_inner", "far_outer") +END_WORD = dict(near="the end nearer the robot", far="the far end") + +# ---------------------------------------------------------------- instances / hidden variable +D_INNER = (0.085, 0.095) # |y| of the inner marks from the plank's middle +D_OUTER = (0.155, 0.165) # the lip stops a cube 19.95 cm out: a cube on a low-side outer mark ends >= 3.5 cm off it +P_HAZARD = 0.65 # fraction of hazard instances, balanced per 20 consecutive seeds (13 / 7) +R_HEAVY = (1.30, 1.40) # hazard: lone heavy cube on its inner mark, moment / tipping moment +R_LIGHT = (0.72, 0.78) # hazard: lone light cube on its outer mark +LIGHT_BENIGN = (0.026, 0.034) # benign: every cube (kg) +H_EST, L_EST = 0.21, 0.04 # nominal masses the adaptive script uses for its hypotheses (it never sees the true ones) + +# ---------------------------------------------------------------- judging +TOL = 0.020 # cube centre within 2 cm of its mark centre (per plank axis) +TOL_LOSE = 0.025 # hysteresis for the monitor +LEVEL_DEG = 3.0 +TIP_DEG = 8.0 # the monitor records a tip when |tilt| exceeds this (a real tip reaches ~17 deg) +LEVEL_DEBOUNCE = 4 # monitor evaluations (0.1 s each) before plank_level changes +FLAT_COS = np.cos(np.radians(15.0)) +SUPPORT_XY = 0.02 # plank on its support: its middle within 2 cm (horizontally) of the support's centre ... +SUPPORT_DZ = 0.02 # ... and not more than 2 cm below its starting height (a tip lowers it ~0.6 cm; off the block ~6 cm) + +# ---------------------------------------------------------------- scripted motion +Z_CARRY = 0.17 # careful / adaptive: grasp point above the table while carrying (cube bottom 14.75 cm) +Z_CARRY_NAIVE = 0.15 # naive: just above the cubes already on the plank (their tops at 12 cm) +REL_GAP = 0.004 # release with the cube's bottom this far above the plank + + +def plank_xml(name): + """Board + end lips + keel (collision) and per colour a mark (5 visual-only geoms, moved per instance). + Long axis = body y.""" + g = [] + + def box(nm, pos, size, rgba): + g.append(f'') + g.append(f'') + + dark = (0.25, 0.16, 0.09, 1.0) + box(f"{name}_board", (0, 0, 0), (PL_HW, PL_HL, PL_HT), WOOD) + for k, s in enumerate((1, -1)): + box(f"{name}_lip{k}", (0, s * (PL_HL - LIP_T / 2), PL_HT + LIP_H / 2), (PL_HW, LIP_T / 2, LIP_H / 2), dark) + box(f"{name}_keel", (0, 0, -PL_HT - KEEL_H / 2), (PL_HW, KEEL_HW, KEEL_H / 2), dark) + for c in COLORS: + rgba = RGBA[c] + fill = tuple(0.55 + 0.45 * v for v in rgba[:3]) + (1.0,) + o, i, w = MARK_HALF, MARK_HALF - MARK_LINE, MARK_LINE + parts = [((0, 0, PL_HT + 0.0003), (o, o, 0.0003), fill), + ((0, i + w / 2, PL_HT + 0.0008), (o, w / 2, 0.0003), rgba), + ((0, -i - w / 2, PL_HT + 0.0008), (o, w / 2, 0.0003), rgba), + ((i + w / 2, 0, PL_HT + 0.0008), (w / 2, o, 0.0003), rgba), + ((-i - w / 2, 0, PL_HT + 0.0008), (w / 2, o, 0.0003), rgba)] + for k, (p, sz, col) in enumerate(parts): + g.append(f'') + return _wrap(name, "\n ".join(g), PL_HT, float(np.hypot(PL_HL, PL_HW))) + + +def ridge_xml(name): + """Split support: two 1.5 cm blocks with a 1 cm slot between them; the plank rests on both and pivots on their outer + top edges (a 4 cm flat top). The plank's keel hangs in the slot, so the plank cannot wander along its length by + more than +-3 mm (it stays engaged at the full tip angle).""" + rgba = (0.35, 0.35, 0.38, 1.0) + bh = (RIDGE_HW - SLOT_HW) / 2 + g = [] + for k, sy in enumerate((1, -1)): + p, sz = (0, sy * (SLOT_HW + bh), RIDGE_H / 2), (RIDGE_HX, bh, RIDGE_H / 2) + g.append(f'') + g.append(f'') + g = "\n ".join(g) + return f""" + + + + {g} + + + + + + +""" + + +def tip_ratio(items, plank_mass=PLANK_MASS, s=RIDGE_HW): + """Static model of a loose plank on a flat-topped block: |sum m y| / ((M_plank + sum m) s); the plank tips when + this exceeds 1 (the combined centre of mass leaves the block's top). items: [(mass, y from the middle)].""" + if not items: + return 0.0 + mom = sum(m * y for m, y in items) + return abs(mom) / ((plank_mass + sum(m for m, _ in items)) * s) + + +def _side(y): + return "near" if y > 0 else "far" + + +def _along(v): + """plank-frame y offset in robot-centric words (+y = toward the robot)""" + return f"{100 * abs(v):.1f} cm from its mark toward {'the robot' if v > 0 else 'the far end'}" + + +class BoardSkills(Skills): + """Skills that feed the task's per-step monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class BalanceBoard(LFFTask): + name = "lh_balance_board" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Plan", "Restore") + protocol = "cross" + max_attempts = 3 + agent_max_steps = 120 # careful zig-zag ~30-36 commands + re-placing four cubes (~30) + looking around + instruction = ("Put each coloured cube on the square mark of the same colour on the long plank. The plank lies loose " + "across a narrow block under its middle. At the end all four cubes must be on their marks and the " + "plank must still rest level on the block.") + instruction_indirect = ("Set the four coloured cubes onto the outlined squares of matching colour on the wooden " + "board that rests across the small grey block. When you are done, every cube must sit on " + "its square and the board must still rest level on the block.") + agent_object_names = ["red cube", "green cube", "blue cube", "yellow cube", "plank", "support block", + "red mark", "green mark", "blue mark", "yellow mark"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + pl = register_generated("LffLhBbPlank", plank_xml(PLANK_MODEL)) + rg = register_generated("LffLhBbRidge", ridge_xml("lff_lh_bb_ridge"), free=False) + objs = [(PLANK, pl, "plank_region", (0.18, -0.01, 0.20, 0.01))] + e = CUBE_E / 2 + for i, c in enumerate(COLORS): + cat = register_generated(f"LffLhBbCube{c.title()}", + box_xml(f"lff_lh_bb_cube_{c}", (e, e, e), RGBA[c], density=500.0, + friction=(MU, 0.005, 0.0001)).replace( + 'solimp="0.998 0.998 0.001" solref="0.001 1"', "")) + objs.append((CUBES[c], cat, f"{c}_cube_region", (-0.32, -0.33 + 0.2 * i, -0.30, -0.31 + 0.2 * i))) + fx = [(RIDGE, rg, "ridge_region", (-0.12, 0.30, -0.10, 0.32))] + return write_bddl(self.name, "put each cube on its mark on the plank and keep the plank level", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.ridge_bid = m.body_name2id(self.env.fixtures_dict[RIDGE].root_body) + self.plank_bid = envs.body_id(self.env, PLANK) + pre = f"{PLANK}_{PLANK_MODEL}" + self.mark_gids = {c: [m.geom_name2id(f"{pre}_mk_{c}_{k}") for k in range(5)] for c in COLORS} + self.mark_pos0 = {c: [m.geom_pos[g].copy() for g in self.mark_gids[c]] for c in COLORS} + self.cube_gids = {c: set(envs.obj_geom_ids(self.env, CUBES[c])) for c in COLORS} + self.plank_gids = set(envs.obj_geom_ids(self.env, PLANK)) + self.robot_gids = set(envs.robot_geom_ids(self.env)) + self.inst = None + self.mon = None + self.obs = [] # adaptive script: (configuration, tipped) observations, kept across the attempts of one run + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + x0, y0 = float(rng.uniform(-0.18, -0.14)), float(rng.uniform(-0.03, 0.03)) + perm = [str(c) for c in rng.permutation(COLORS)] # colour of the mark in SLOTS order + slot_of = {c: s for c, s in zip(perm, SLOTS)} + dist = dict(near_outer=float(rng.uniform(*D_OUTER)), near_inner=float(rng.uniform(*D_INNER)), + far_inner=-float(rng.uniform(*D_INNER)), far_outer=-float(rng.uniform(*D_OUTER))) + marks = {c: dist[slot_of[c]] for c in COLORS} # plank-frame y of each mark (+ = toward the robot) + hazard = bool((int(seed) * 7) % 20 < round(20 * P_HAZARD)) # balanced like l7_key_turn / lh_lid_box + r_h, r_l = float(rng.uniform(*R_HEAVY)), float(rng.uniform(*R_LIGHT)) + light = {c: float(rng.uniform(*LIGHT_BENIGN)) for c in COLORS} + s, pm = RIDGE_HW, PLANK_MASS + if hazard: + # equal moments on both sides -> the finished layout is exactly balanced + dn, do = dist["near_inner"], dist["near_outer"] + y_h = r_h * pm * s / (dn - r_h * s) * dn # heavy on the near inner mark: moment r_h x tipping moment + x_l = r_l * pm * s / (do - r_l * s) * do + mass = {c: (y_h if "inner" in slot_of[c] else x_l) / abs(dist[slot_of[c]]) for c in COLORS} + else: + mass = light + # start: two cubes left and two right of the plank, 17-19 cm from its axis, at two depths (random places) + spots = [(dx, sy) for sy in (1.0, -1.0) for dx in (-0.08, 0.08)] + order = rng.permutation(4) + start = {c: [x0 + spots[j][0] + float(rng.uniform(-0.01, 0.01)), + y0 + spots[j][1] * float(rng.uniform(0.17, 0.19))] for c, j in zip(COLORS, order)} + start_yaw = {c: float(rng.uniform(-0.3, 0.3)) for c in COLORS} + heavy = sorted(c for c in COLORS if mass[c] > 0.1) + return dict(seed=int(seed), plank_xy=[x0, y0], marks=marks, slot_of=slot_of, hazard=hazard, mass=mass, + heavy=heavy, r_heavy=r_h if hazard else None, r_light=r_l if hazard else None, start=start, + start_yaw=start_yaw) + + def apply_instance(self, inst): + self.inst = inst + env = self.env + m = env.sim.model + x0, y0 = inst["plank_xy"] + q = [np.cos(PLANK_YAW / 2), 0.0, 0.0, np.sin(PLANK_YAW / 2)] + m.body_pos[self.ridge_bid] = [x0, y0, TZ] + m.body_quat[self.ridge_bid] = q + envs.scale_mass(env, PLANK, PLANK_MASS) + _, da = envs.free_joint_addr(env, PLANK) + m.dof_damping[da + 3:da + 6] = PLANK_ROT_DAMP + for c in COLORS: + for g, p0 in zip(self.mark_gids[c], self.mark_pos0[c]): + m.geom_pos[g] = p0 + np.array([0.0, inst["marks"][c], 0.0]) + envs.scale_mass(env, CUBES[c], inst["mass"][c]) + envs.set_obj_pose(env, PLANK, [x0, y0, TZ + RIDGE_H + PL_HT + 0.0005], quat_wxyz=np.array(q)) + for c in COLORS: + envs.place_upright(env, CUBES[c], inst["start"][c], yaw=inst["start_yaw"][c]) + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.plank_z0 = float(self.plank_pos()[2]) + self.sk = BoardSkills(self.env, self, recorder=recorder) + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ state helpers + def plank_R(self): + return self.env.sim.data.body_xmat[self.plank_bid].reshape(3, 3).copy() + + def plank_pos(self): + return self.env.sim.data.body_xpos[self.plank_bid].copy() + + def tilt_deg(self): + """+ = the plank's end toward the robot is up""" + return float(np.degrees(np.arcsin(np.clip(self.plank_R()[2, 1], -1.0, 1.0)))) + + def is_level(self, deg=LEVEL_DEG): + return abs(self.tilt_deg()) <= deg + + def on_support(self): + """the plank still rests on the support block (10-11: Sonnet lh2 s3001 pushed it off onto the table, where it + lies level, and loaded the cubes there; 'level' alone accepted that)""" + p, r = self.plank_pos(), self.env.sim.data.body_xpos[self.ridge_bid] + return bool(np.linalg.norm(p[:2] - r[:2]) <= SUPPORT_XY and p[2] >= self.plank_z0 - SUPPORT_DZ) + + def in_plank(self, p): + """world point -> plank frame (x across, y along from the middle, z above the plank's mid-plane)""" + return self.plank_R().T @ (np.asarray(p, float) - self.plank_pos()) + + def mark_world(self, c): + return self.plank_pos() + self.plank_R() @ np.array([0.0, self.inst["marks"][c], PL_HT]) + + def cube_pos(self, c): + return envs.obj_pos(self.env, CUBES[c]) + + def held(self, c): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, + object_geoms=self.env.objects_dict[CUBES[c]])) + + def on_plank(self, c): + """resting on the plank's top (plank frame), anywhere along it""" + q = self.in_plank(self.cube_pos(c)) + return bool(abs(q[0]) <= PL_HW + 0.01 and abs(q[1]) <= PL_HL and abs(q[2] - PL_HT - CUBE_E / 2) <= 0.012) + + def mark_offset(self, c): + q = self.in_plank(self.cube_pos(c)) + return np.array([q[0], q[1] - self.inst["marks"][c]]) + + def _flat(self, c): + Rc = self.env.sim.data.body_xmat[envs.body_id(self.env, CUBES[c])].reshape(3, 3) + return bool(np.max(np.abs(self.plank_R()[:, 2] @ Rc)) >= FLAT_COS) + + def on_mark(self, c, tol=TOL): + if not self.on_plank(c): + return False + o = self.mark_offset(c) + return bool(np.max(np.abs(o)) <= tol and self._flat(c) and not self.held(c)) + + def stage_values(self): + v = {f"{c}_on_mark": self.on_mark(c) for c in COLORS} + v["plank_level"] = self.is_level() + v["plank_on_support"] = self.on_support() + return v + + # ------------------------------------------------------------ per-step monitor (server log only) + def _init_monitor(self): + self.mon = dict(state={f"{c}_on_mark": False for c in COLORS} | {"plank_level": True, "plank_on_support": True}, ever=set(), + lost=set(), events=[], step=0, last_touch={c: None for c in COLORS}, + held_prev={c: False for c in COLORS}, last_release=None, tipping=False, tips=[], + level_cnt=0, calm=0, tilt_max=0.0, win_max=0.0) + + def _robot_touches(self): + """cubes touched by the robot or by a cube the robot is carrying, in this control step""" + d = self.env.sim.data + out = set() + carried = [c for c in COLORS if self.mon["held_prev"][c]] + hit = {c: self.robot_gids.union(*[self.cube_gids[h] for h in carried if h != c]) for c in COLORS} + for i in range(d.ncon): + con = d.contact[i] + for c in COLORS: + g = self.cube_gids[c] + if (con.geom1 in g and con.geom2 in hit[c]) or (con.geom2 in g and con.geom1 in hit[c]): + out.add(c) + return out + + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + mon["step"] += 1 + step = self.sk.n_steps + for c in self._robot_touches(): + mon["last_touch"][c] = step + tilt = self.tilt_deg() + mon["tilt_max"] = max(mon["tilt_max"], abs(tilt)) + mon["win_max"] = max(mon["win_max"], abs(tilt)) + if not mon["tipping"] and abs(tilt) > TIP_DEG: + # one tip episode = from |tilt| > 8 deg until the plank has stayed level for 1 s (the swing back and any + # rocking belong to the same episode) + mon["tipping"] = True + mon["calm"] = 0 + rel = mon["last_release"] + tip = dict(step=step, down="near" if tilt < 0 else "far", + after_release=(rel[0] if rel is not None and step - rel[1] <= 60 else None), + on_plank=[c for c in COLORS if self.on_plank(c)], + on_mark=[c for c in COLORS if mon["state"][f"{c}_on_mark"]]) + mon["tips"].append(tip) + mon["events"].append(dict(step=step, pred="plank", ev="tipped", down=tip["down"], + after_release=tip["after_release"], on_mark=tip["on_mark"])) + elif mon["tipping"]: + mon["calm"] = mon["calm"] + 1 if abs(tilt) < LEVEL_DEG else 0 + if mon["calm"] >= 20: + mon["tipping"] = False + if mon["step"] % 2: + return # predicates every other control step (0.1 s) + for c in COLORS: + h = self.held(c) + if mon["held_prev"][c] and not h: + mon["last_release"] = (c, step) + mon["held_prev"][c] = h + key = f"{c}_on_mark" + was = mon["state"][key] + now = self.on_mark(c, TOL if not was else TOL_LOSE) + if now != was: + self._event(key, now, step, c) + lv = self.is_level() + if lv != mon["state"]["plank_level"]: + mon["level_cnt"] += 1 + if mon["level_cnt"] >= LEVEL_DEBOUNCE: + mon["level_cnt"] = 0 + self._event("plank_level", lv, step, None) + else: + mon["level_cnt"] = 0 + sup = self.on_support() + if sup != mon["state"]["plank_on_support"]: + self._event("plank_on_support", sup, step, None) + + def _event(self, key, now, step, color): + mon = self.mon + mon["state"][key] = now + if now: + ev = "restored" if key in mon["lost"] else "achieved" + mon["ever"].add(key) + mon["lost"].discard(key) + mon["events"].append(dict(step=step, pred=key, ev=ev)) + return + cause = "other" + recent_tip = bool(mon["tips"]) and (mon["tipping"] or step - mon["tips"][-1]["step"] <= 60) + if color is None: + cause = "tip" if recent_tip else "other" + elif self.held(color): + cause = "picked_up" + elif recent_tip: + cause = "tip" + elif mon["last_touch"][color] is not None and step - mon["last_touch"][color] <= 60: + cause = "robot" + mon["lost"].add(key) + mon["events"].append(dict(step=step, pred=key, ev="lost", cause=cause, tilt=round(self.tilt_deg(), 1))) + + # ------------------------------------------------------------ outcome + def _static(self): + d = self.env.sim.data + for name in [CUBES[c] for c in COLORS] + [PLANK]: + _, da = envs.free_joint_addr(self.env, name) + if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.3: + return False + return True + + def _where(self, c): + """robot-centric description of where a cube that is not on its mark is""" + if self.held(c): + return "is still held by the gripper" + if self.on_plank(c): + o = self.mark_offset(c) + return f"lies on the plank, {_along(o[1])}" + p = self.cube_pos(c) + if np.linalg.norm(p[:2] - np.asarray(self.inst["start"][c])) < 0.02: + return "is still where it started on the table" + q = self.in_plank(p) + if abs(q[1]) > PL_HL: + return f"lies on the table beyond {END_WORD[_side(q[1])]} of the plank" + return "lies on the table beside the plank" + + def outcome(self, inst): + envs.settle(self.env, 30) + mon = self.mon + vals = self.stage_values() + static = self._static() + held = [c for c in COLORS if self.held(c)] + success = bool(all(vals.values()) and static and not held) + regress = [e for e in mon["events"] if e["ev"] == "lost"] + restored = [e for e in mon["events"] if e["ev"] == "restored"] + parts = [] + off = [c for c in COLORS if not vals[f"{c}_on_mark"]] + if success: + failure = None + parts.append("All four cubes are on their marks and the plank is level.") + else: + lost_final = [c for c in off if f"{c}_on_mark" in mon["ever"]] + failure = ("held" if held else "plank_off_support" if not vals["plank_on_support"] else + "regressed" if lost_final else "incomplete" if off else + "not_level" if not vals["plank_level"] else "not_static") + for c in off: + txt = f"The {c} cube is not on its mark: it {self._where(c)}" + if f"{c}_on_mark" in mon["ever"]: + why = [e for e in regress if e["pred"] == f"{c}_on_mark"] + cause = why[-1].get("cause") if why else None + txt += {"tip": " (it had been on its mark; it slid off when the plank tipped).", + "robot": " (it had been on its mark; the robot knocked it off).", + "picked_up": " (it had been on its mark; it was picked up again)."}.get( + cause, " (it had been on its mark earlier).") + else: + txt += " (it was never on its mark)." + parts.append(txt) + if not vals["plank_on_support"]: + parts.append("The plank no longer rests on the support block: it was pushed or knocked off it.") + if not vals["plank_level"]: + t = self.tilt_deg() + parts.append(f"The plank is not level: it is tilted {abs(t):.0f} degrees, " + f"{END_WORD['near' if t < 0 else 'far']} down.") + if not static and all(vals.values()): + parts.append("Something was still moving at the end.") + if mon["tips"]: + descr = [] + for tp in mon["tips"]: + d = f"{END_WORD[tp['down']]} down" + if tp["after_release"]: + d += f" right after the {tp['after_release']} cube was set down" + descr.append(d) + parts.append(f"During the attempt the plank tipped {len(mon['tips'])} time(s): " + "; ".join(descr) + ".") + return dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, + events=mon["events"], n_regressions=len(regress), n_restored=len(restored), + n_tips=len(mon["tips"]), tips=mon["tips"], tilt_max=round(mon["tilt_max"], 1), + tilt_final=round(self.tilt_deg(), 1), hazard=bool(inst["hazard"]), + mark_offsets_cm={c: (100 * self.mark_offset(c)).round(1).tolist() for c in COLORS}, + on_plank={c: self.on_plank(c) for c in COLORS}, detail=" ".join(parts)) + + # ------------------------------------------------------------ scripted policies (perfect perception) + def _grasp_yaw(self, c): + R = self.env.sim.data.body_xmat[envs.body_id(self.env, CUBES[c])].reshape(3, 3) + i = int(np.argmin(np.abs(R[2]))) + yaw = float(np.arctan2(R[1, i], R[0, i])) + return float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4) + + def _y_on_plank(self): + """cubes resting on the plank now -> their position along it""" + return {c: float(self.in_plank(self.cube_pos(c))[1]) for c in COLORS if self.on_plank(c) and not self.held(c)} + + def plank_calm(self): + _, da = envs.free_joint_addr(self.env, PLANK) + return abs(self.tilt_deg()) < 1.0 and float(np.linalg.norm(self.env.sim.data.qvel[da + 3:da + 6])) < 0.05 + + def wait_calm(self, max_steps=60): + """hold the arm still until the plank has stopped swinging (a careful agent looks before it acts)""" + n = 0 + for _ in range(max_steps): + if self.plank_calm(): + n += 1 + if n >= 5: + return True + else: + n = 0 + self.sk.hold(1) + return False + + def pick(self, c, z_carry): + sk = self.sk + p = self.cube_pos(c) + yaw = self._grasp_yaw(c) + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], max(TZ + z_carry, p[2] + 0.06)], yaw=yaw) + sk.move_to([p[0], p[1], p[2]], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([p[0], p[1], TZ + z_carry], speed=0.3) + if not self.held(c): + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], TZ + z_carry]) + return False + return True + + def put(self, c, z_carry=Z_CARRY, noise=None, record=False, careful=False): + """Pick cube c wherever it is and put it on its mark: carry it over the mark, lower it until its bottom is + REL_GAP above the plank, release, lift. Returns whether the plank tipped (|tilt| > TIP_DEG) during the + placement, or None if the cube could not be picked. record=True appends the observation (cubes on the plank + right before the release + this one on its mark, tipped?) for the adaptive script.""" + for _ in range(2): + if self.pick(c, z_carry): + break + else: + return None + sk = self.sk + d = self.mark_world(c) + if noise is not None: + d = d + np.array([noise[0], noise[1], 0.0]) + sk.move_to([d[0], d[1], TZ + z_carry], yaw=0.0) + if careful: + self.wait_calm() + d = self.mark_world(c) + (np.array([noise[0], noise[1], 0.0]) if noise is not None else 0.0) + sk.move_to([d[0], d[1], d[2] + CUBE_E / 2 + REL_GAP], tol=0.003) + was_level = self.plank_calm() + conf = self._y_on_plank() + conf[c] = float(self.inst["marks"][c]) + self.mon["win_max"] = abs(self.tilt_deg()) + sk.set_gripper(False, steps=12) + sk.move_to([d[0], d[1], TZ + z_carry]) + sk.hold(12) + tipped = self.mon["win_max"] > TIP_DEG + if tipped: + envs.settle(self.env, 30) # let the cubes slide down + if record and was_level: + self.obs.append(dict(conf=conf, tipped=bool(tipped), after=c)) + return tipped + + def park(self, c): + """take cube c off the plank and set it on a free spot of the table beside the plank""" + x0, y0 = self.inst["plank_xy"] + others = [self.cube_pos(o)[:2] for o in COLORS if o != c] + cands = [np.array([x0 + dx, y0 + sy * dy]) for sy in (1, -1) for dy in (0.18, 0.25) + for dx in (-0.12, -0.04, 0.04, 0.12)] + best = max(cands, key=lambda q: min(np.linalg.norm(q - o) for o in others)) + if not self.pick(c, Z_CARRY): + return False + sk = self.sk + sk.move_to([best[0], best[1], TZ + Z_CARRY], yaw=0.0) + sk.move_to([best[0], best[1], TZ + CUBE_E / 2 + 0.004], tol=0.003) + sk.set_gripper(False, steps=12) + sk.move_to([best[0], best[1], TZ + Z_CARRY]) + return True + + # ---- planning with the static model + def plan(self, todo, hyps): + """Best order to (re)place the cubes in `todo`, given the cubes now on the plank, minimising the worst tip ratio + over the mass hypotheses `hyps` (list of {colour: kg}). A cube that is on the plank off its mark is lifted + (its moment removed) and then set on its mark. Returns (order, worst ratio).""" + cur0 = self._y_on_plank() + best, best_w = list(todo), np.inf + for order in itertools.permutations(todo): + w = 0.0 + for mass in hyps: + cur = dict(cur0) + for c in order: + if c in cur: + del cur[c] + w = max(w, tip_ratio([(mass[o], y) for o, y in cur.items()])) + cur[c] = self.inst["marks"][c] + w = max(w, tip_ratio([(mass[o], y) for o, y in cur.items()])) + if w < best_w - 1e-9: + best, best_w = list(order), w + return best, best_w + + def hypotheses(self, use_obs=True): + """Heavy / light assignments (nominal masses) that (1) leave the finished layout balanced, (2) admit a loading + order that never tips the plank (the task is solvable) and (3) agree with every observed placement (tipped or + not, with a +-10 % band in which either outcome counts as consistent). Falls back to (1)+(2) if no assignment + agrees with all observations.""" + marks = self.inst["marks"] + prior = [] + for k in range(5): + for heavy in itertools.combinations(COLORS, k): + mass = {c: (H_EST if c in heavy else L_EST) for c in COLORS} + if tip_ratio([(mass[c], marks[c]) for c in COLORS]) > 0.6: + continue + for order in itertools.permutations(COLORS): + cur, w = [], 0.0 + for c in order: + cur.append((mass[c], marks[c])) + w = max(w, tip_ratio(cur)) + if w <= 0.9: + prior.append(mass) + break + if not use_obs: + return prior + post = [] + for mass in prior: + if all(not ((ob["tipped"] and r < 0.9) or (not ob["tipped"] and r > 1.1)) + for ob in self.obs for r in [tip_ratio([(mass[o], y) for o, y in ob["conf"].items()])]): + post.append(mass) + return post or prior + + def unload_until_level(self, max_moves=4): + """while the plank is tipped: take the cube farthest out on its low side off the plank""" + for _ in range(max_moves): + envs.settle(self.env, 20) + self.wait_calm() + if self.is_level(): + return True + t = self.tilt_deg() + yo = self._y_on_plank() + low = [c for c, y in yo.items() if (y > 0) == (t < 0)] + if not low: + return self.is_level() + self.park(min(low, key=lambda o: abs(yo[o]))) # the top of the pile first: the hand clears the others + envs.settle(self.env, 20) + self.wait_calm() + return self.is_level() + + def restore(self, hyps_fn, rounds=3, record=False): + """Check every stage; if something is wrong: unload the low end if the plank is tipped, then (re)place every + cube that is not on its mark in the order the static model rates safest under the current mass hypotheses; + start over after a tip. Up to `rounds` passes.""" + for _ in range(rounds): + envs.settle(self.env, 20) + if all(self.stage_values().values()): + return True + self.unload_until_level() + todo = [c for c in COLORS if not self.on_mark(c)] + if not todo: + continue + hyps = hyps_fn() + order, worst = self.plan(todo, hyps) + if worst > 0.9: # cubes left on the plank make every order risky: clear it and start from empty + for c in [c for c in COLORS if self.on_plank(c)]: + self.park(c) + order, worst = self.plan(list(COLORS), hyps) + for c in order: + if self.on_mark(c): + continue + if self.put(c, Z_CARRY, record=record, careful=True): + break # tipped: look again + envs.settle(self.env, 20) + return all(self.stage_values().values()) + + def naive_order(self, noise_sd=0.0, rng=None): + """nearest cube first, starting from the gripper's position and then from each mark just loaded""" + p = self.sk.eef_pos()[:2] + left, order = list(COLORS), [] + while left: + dist = {c: np.linalg.norm(self.cube_pos(c)[:2] - p) + (rng.normal(0, noise_sd) if rng is not None else 0.0) + for c in left} + c = min(left, key=dist.get) + order.append(c) + left.remove(c) + p = self.mark_world(c)[:2] + return order + + def slot_order(self, kind): + so = {s: c for c, s in self.inst["slot_of"].items()} + seq = dict(end2end=SLOTS, alt_outer=("near_outer", "far_outer", "near_inner", "far_inner"), + alt_inner=("near_inner", "far_inner", "near_outer", "far_outer"))[kind] + return [so[s] for s in seq] + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("seed", 0)) + mode = params["mode"] + if mode == "plan": + hyps = [dict(inst["mass"])] if params.get("true_masses") else self.hypotheses() + order, _ = self.plan(list(COLORS), hyps) + elif mode in ("end2end", "alt_outer", "alt_inner"): + order = self.slot_order(mode) + else: # nearest first (naive / blind) + order = self.naive_order(params.get("order_noise", 0.0), rng) + noise = params.get("noise", 0.0) + z_carry = Z_CARRY if params.get("careful") else Z_CARRY_NAIVE + for c in order: + nz = rng.uniform(-noise, noise, 2) if noise else None + tipped = self.put(c, z_carry, noise=nz, record=params.get("record", False), careful=params.get("careful", False)) + if tipped and params.get("check_each"): + break # look at what happened, then restore below + if params.get("check"): + hyps_fn = (lambda: [dict(inst["mass"])]) if params.get("true_masses") else self.hypotheses + self.restore(hyps_fn, record=params.get("record", False)) + self.sk.hold(10) + return order + + def default_params(self, inst): + return dict(mode="nearest", check=False) + + def oracle_params(self, inst): + return dict(mode="plan", true_masses=True, careful=True, check=True) + + def adapt_params(self, inst, history): + """from attempt 2: load in the order the observations of earlier attempts make safest, check after every + placement and restore at the end""" + return dict(mode="plan", careful=True, check=True, check_each=True, record=True) + + def blind_params(self, inst, attempt, rng): + """nearest-first again with small random variation (order noise, 4 mm placement noise), no history, no check""" + return dict(mode="nearest", check=False, order_noise=0.03, noise=0.004, seed=int(rng.integers(1 << 30))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + self.obs = [] + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": # attempt 1: natural order, but look after every placement and restore + params = (dict(mode="nearest", check=True, check_each=True, record=True) if a == 0 else + self.adapt_params(inst, history)) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind in ("end2end", "alt_outer", "alt_inner"): # extra controls: other natural orders, no check + params = dict(mode=kind, check=False) + elif kind == "oracle_noise": # extra control: the oracle with +-5 mm (uniform) placement noise + params = dict(self.oracle_params(inst), noise=0.005, seed=int(rng.integers(1 << 30))) + elif kind == "switch": # extra control: no in-attempt repair, learn the order across attempts only + params = (dict(mode="nearest", check=False, record=True) if a == 0 else + dict(mode="plan", careful=True, check=False, record=True)) + else: + raise ValueError(kind) + order = self.execute(inst, params) + out = self.outcome(inst) + out["order"] = order + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "oracle_noise", "naive", "end2end", "alt_outer", "alt_inner"): + break + return history diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_breakfast_service.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_breakfast_service.py new file mode 100644 index 0000000000000000000000000000000000000000..76f751d6bb88f22613915c975ca99bba920e21ea --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_breakfast_service.py @@ -0,0 +1,546 @@ +"""Breakfast revision 2: food meshes, hinged milk pourer, L1/L3/L4 recovery. + +Rigid bodies use MuJoCo contacts. Milk is an explicitly reduced-order, volume- +conserving discharge / ballistic parcel model, NOT Navier-Stokes fluid simulation. +Only the physical carton angle controls discharge. No policy/stage success gates. +An upright butter stick physically obstructs the lid. Lay it flat to recover. +There is no latch fatigue, artificial opening torque, or forced orientation. +""" +from pathlib import Path +import copy +import xml.etree.ElementTree as ET +import numpy as np +import robosuite +import libero.libero as libero_pkg + +from .. import envs +from ..bddl import write_bddl +from ..objects import register_generated, _wrap, _fmt +from ..skills import Skills +from ..task_base import register_task +from .lh_pantry_relatch import (PantryRelatch, RelatchSkills, BREAD_HALF, + BOX, BOX_MODEL, FLOOR_T, WALL_H, BOX_D, box_lid_xml) + +LIB_ASSETS = Path(libero_pkg.__file__).parent / 'assets' +RS_ASSETS = Path(robosuite.__file__).parent / 'models/assets' +BUTTER_HALF = (.010,.020,.040) # standing: 8 cm tall; lying: 2 cm tall, fits the 2.6 cm cavity + + +def food_xml(kind, half): + """Reuse installed textured visual meshes, normalized to the tested food collision hull.""" + if kind == 'bread': + source = RS_ASSETS / 'objects/bread.xml' + meshpath = RS_ASSETS / 'objects/meshes/bread.stl' + data = meshpath.read_bytes() + n = int.from_bytes(data[80:84], 'little') + dtype = np.dtype([('normal','') + xml = ET.fromstring(_wrap('breakfast_'+kind, hull+ET.tostring(visual,encoding='unicode'),half[2],.05)) + xml.insert(0,asset) + return ET.tostring(xml,encoding='unicode') + + +def milk_station_xml(): + source = LIB_ASSETS/'stable_hope_objects/milk/milk.xml' + root = ET.parse(source).getroot() + asset = root.find('asset') + for el in asset: + if el.get('file'): el.set('file', str(source.parent/el.get('file'))) + carton = copy.deepcopy(root.find('worldbody/body/body')) + carton.set('name','carton_visual'); carton.set('quat','.5 .5 .5 .5') + # A carton held in a tabletop tipping cradle. The hinge is physical, unactuated. + parts = ''' + + + + + + + + + + + + ''' + xml = ET.fromstring(_wrap('breakfast_milk_station',parts,0,.08)) + xml.insert(0,asset) + xml.find(".//body[@name='tilting_carton']").append(carton) + for parent in xml.iter('body'): + for geom in list(parent.findall('geom')): + if geom.get('group') is None: + geom.set('group','0') + vis=copy.deepcopy(geom);vis.set('group','1');vis.set('contype','0');vis.set('conaffinity','0') + vis.attrib.pop('name',None);vis.set('mass','0');parent.append(vis) + return ET.tostring(xml,encoding='unicode') + + +def liquid_visual_xml(): + geoms = [''] + for i in range(80): + geoms.append(f'') + geoms.append('') + return _wrap('breakfast_liquid', ''.join(geoms),0,.001) + + +def fixed_cup_xml(): + source=LIB_ASSETS/'turbosquid_objects/porcelain_mug/porcelain_mug.xml' + root=ET.parse(source).getroot() + for el in root.find('asset'): + if el.get('file'):el.set('file',str(source.parent/el.get('file'))) + return ET.tostring(root,encoding='unicode') + + +def serving_plate_xml(): + source=LIB_ASSETS/'stable_scanned_objects/plate/plate.xml' + root=ET.parse(source).getroot();scale=1.5 + for el in root.find('asset'): + if el.get('file'):el.set('file',str(source.parent/el.get('file'))) + if el.tag=='mesh':el.set('scale',_fmt(np.fromstring(el.get('scale'),sep=' ')*scale)) + for el in root.iter(): + if el.tag in ('geom','site'): + if el.get('pos'):el.set('pos',_fmt(np.fromstring(el.get('pos'),sep=' ')*scale)) + if el.get('size'):el.set('size',_fmt(np.fromstring(el.get('size'),sep=' ')*scale)) + return ET.tostring(root,encoding='unicode') + + +class BreakfastSkills(RelatchSkills): + def __init__(self,env,task,recorder=None): + super().__init__(env,task,recorder) + self.bias=np.asarray(task.inst['bias'] if task.inst['mechanisms']['L1'] else [0,0,0],float) + self.correction=np.zeros(3) + self.pour_latched=False + self.pour_rad=0. + self.pour_y=0. + + def move_to(self,target,*args,**kwargs): + return super().move_to(np.asarray(target)-self.correction,*args,**kwargs) + + def set_gripper(self,close,steps=15): + rep=super().set_gripper(close,steps) + if close and self.task.holding_pour_knob(): + self.pour_latched=True + e=self.eef_pos(); h=self.task.pour_pivot() + self.pour_rad=float(np.linalg.norm((e-h)[[0,2]]));self.pour_y=float(e[1]) + elif not close:self.pour_latched=False + return rep + + def _act(self,dpos,drot,grip): + if self.pour_latched and self.task.inst['mechanisms']['L3']: + e=self.eef_pos(); k=self.task.pour_knob() + if grip<0 or np.linalg.norm(e-k)>.04:self.pour_latched=False + else: + h=self.task.pour_pivot();r=(e-h)[[0,2]];rn=max(np.linalg.norm(r),1e-6) + t=np.array([-r[1],r[0]])/rn + s=np.clip(np.asarray(dpos)[[0,2]]@t,-.008,.008) + corr=(self.pour_rad-rn)*r/rn + dpos=np.array([s*t[0]+corr[0], self.pour_y-e[1],s*t[1]+corr[1]]) + super()._act(dpos,drot,grip) + + +@register_task +class BreakfastService(PantryRelatch): + name='lh_breakfast_service' + level='L1' + category='system_identification' + failure_causes=('L1','L3','L4') + failure_types=failure_causes + agent_max_steps=360 + instruction=('Prepare breakfast: put the bread from the wooden box onto the plate and close the box; ' + 'pour 80 to 160 mL of milk into the cup using the milk carton in its cradle. ' + 'Then store the butter inside the box and leave its lid shut. Finish with the carton upright, ' + 'bread on the plate, cup upright, and gripper open and clear. Spill at most 15 mL. ' + 'The cradle can be tipped with its gold side handle using ordinary gripper motions.') + instruction_indirect=instruction + agent_object_names=['bread','butter','plate','cup','milk carton','gold cradle handle','wooden box','lid knob'] + + def make_bddl(self): + boxroot=ET.fromstring(box_lid_xml(BOX_MODEL)) + inertial=boxroot.find('.//inertial');ratio=.08/float(inertial.get('mass')) + inertial.set('mass','.08');inertial.set('diaginertia',_fmt(np.fromstring(inertial.get('diaginertia'),sep=' ')*ratio)) + box=register_generated('LffBreakfastBox',ET.tostring(boxroot,encoding='unicode'),free=False) + bread=register_generated('LffBreakfastBread',food_xml('bread',BREAD_HALF)) + butter=register_generated('LffBreakfastButter',food_xml('butter',BUTTER_HALF)) + milk=register_generated('LffBreakfastMilk',milk_station_xml(),free=False) + liquid=register_generated('LffBreakfastLiquid',liquid_visual_xml(),free=False) + cup=register_generated('LffBreakfastCup',fixed_cup_xml(),free=False) + plate=register_generated('LffBreakfastPlate',serving_plate_xml()) + objs=[('bread_1',bread,'bread_region',(-.31,-.01,-.29,.01)), + ('butter_1',butter,'butter_region',(-.31,.24,-.29,.26)), + ('plate_1',plate,'plate_region',(.02,-.26,.04,-.24))] + fx=[(BOX,box,'box_region',(-.18,-.12,-.16,-.10)), + ('milk_1',milk,'milk_region',(.24,-.01,.26,.01)), + ('liquid_1',liquid,'liquid_region',(.34,-.34,.35,-.33)), + ('cup_1',cup,'cup_region',(.14,.26,.16,.28))] + return write_bddl(self.name,self.instruction.replace(';',','),objs,fx) + + def __init__(self,cam_res=None): + super().__init__(cam_res) + m=self.env.sim.model + self.milk_bid=m.body_name2id(self.env.fixtures_dict['milk_1'].root_body) + self.pour_jid=m.joint_name2id('milk_1_pour_hinge') + self.slide_jid=m.joint_name2id('milk_1_pull_slide');self.slide_qa=int(m.jnt_qposadr[self.slide_jid]) + self.pour_qa=int(m.jnt_qposadr[self.pour_jid]);self.pour_dof=int(m.jnt_dofadr[self.pour_jid]) + self.pour_gid=m.geom_name2id('milk_1_pour_knob') + self.nozzle_sid=m.site_name2id('milk_1_nozzle') + self.liquid_bid=m.body_name2id(self.env.fixtures_dict['liquid_1'].root_body) + self.cup_bid=m.body_name2id(self.env.fixtures_dict['cup_1'].root_body) + self.drop_gids=[m.geom_name2id('liquid_1_drop_'+str(i)) for i in range(80)] + self.surface_gid=m.geom_name2id('liquid_1_milk_surface');self.spill_gid=m.geom_name2id('liquid_1_spill') + self.liquid=None;self.phase_hook=None + + def sample_instance(self,seed): + inst=super().sample_instance(seed) + rng=np.random.default_rng(seed) + inst.update(box_xy=[-.20,-.10],plate_xy=[-.09,-.32],butter_xy=[-.36,-.32], + milk_xy=[-.14,.24],cup_xy=[-.075,.24], + bias=[0,float(rng.choice([-1,1])*.10),0], + mechanisms={'L1':True,'L3':True,'L4':True},flow_ml_s=float(rng.uniform(42,48))) + return inst + + def apply_instance(self,inst): + super().apply_instance(inst) + m,d=self.env.sim.model,self.env.sim.data + half_z=BUTTER_HALF[2] if inst['mechanisms']['L4'] else BUTTER_HALF[0] + quat=[1,0,0,0] if inst['mechanisms']['L4'] else [np.sqrt(.5),0,np.sqrt(.5),0] + envs.set_obj_pose(self.env,'butter_1',[*inst['butter_xy'],envs.TABLE_Z+half_z+.001],quat_wxyz=quat) + self.drift_active=False;self.active_latch=0. + envs.scale_mass(self.env,'plate_1',.4) + envs.set_friction(self.env,'plate_1',.8) + m.body_pos[self.milk_bid]=[*inst['milk_xy'],envs.TABLE_Z] + m.body_quat[self.milk_bid]=[1,0,0,0] + m.body_pos[self.liquid_bid]=[0,0,0];m.body_quat[self.liquid_bid]=[1,0,0,0] + d.qpos[self.pour_qa]=0;d.qvel[self.pour_dof]=0 + d.qpos[self.slide_qa]=0 + m.jnt_range[self.slide_jid]=[-.00001,.00001] if inst['mechanisms']['L3'] else [-.11,.01] + m.body_pos[self.cup_bid]=[*inst['cup_xy'],envs.TABLE_Z-.0024] + m.body_quat[self.cup_bid]=[1,0,0,0] + for gid in self.drop_gids+[self.surface_gid,self.spill_gid]:m.geom_rgba[gid,3]=0 + self.liquid=dict(reservoir=300.,cup=0.,spill=0.,parcels=[],emitted=0.,spill_xy=None) + self.trace=[] + + def reset_instance(self,inst,recorder=None): + self.mon=None + np.random.seed(int(inst['seed'])) + self.env.reset();self.apply_instance(inst);self.env.sim.forward();envs.settle(self.env,10) + self.mon=dict(events=[],lid_open_max=0.,armed=False) + self.sk=BreakfastSkills(self.env,self,recorder) + self.traps={k:False for k in self.failure_causes} + self.recovered={k:False for k in self.failure_causes} + self.initial_pour_pivot=self.pour_pivot().copy() + return self.sk + + def _register_close(self,seated): + self.closes_done+=1;self.active_latch=0.;self.drift_active=False + self.mon['events'].append(dict(ev='closed',n=self.closes_done,mechanism='ordinary rigid-body hinge')) + + def _bracket(self): + # Disable the predecessor's modeled spring/catch completely, at every physics substep. + self.env.sim.data.qfrc_applied[self.dof]=0. + + def butter_corners(self): + p=envs.obj_pos(self.env,'butter_1') + R=self.env.sim.data.body_xmat[envs.body_id(self.env,'butter_1')].reshape(3,3) + return np.array([p+R@(np.array([a,b,c])*BUTTER_HALF) for a in (-1,1) for b in (-1,1) for c in (-1,1)]) + + def butter_height(self): + c=self.butter_corners();return float(np.ptp(c[:,2])) + + def butter_in_box(self): + from .lh_lid_box import IN_X,IN_Y + c=self.butter_corners();b=np.asarray(self.inst['box_xy']) + inside=np.all(np.abs(c[:,:2]-b)<[IN_X+.001,IN_Y+.001]) + return bool(inside and c[:,2].max()envs.TABLE_Z+FLOOR_T-.002 and not self.held('butter_1')) + + def butter_lid_contact(self): + m=self.env.sim.model + lid=m.geom_name2id('box_1_'+BOX_MODEL+'_lid') + return envs.contacts_between(self.env,envs.obj_geom_ids(self.env,'butter_1'),[lid]) + + def pick_place(self,name,dest_xy,z_rel,z_carry=.18,dest_yaw=0.): + if name!='butter_1':return super().pick_place(name,dest_xy,z_rel,z_carry,dest_yaw) + s=self.sk;p=envs.obj_pos(self.env,name).copy() + tall=self.butter_height()>.045 + grasp=p+np.array([0,0,.025 if tall else 0.]) + s.set_gripper(False,8);s.move_to([p[0],p[1],1.12],yaw=0) + s.move_to(grasp,speed=.10,tol=.002,max_steps=120);s.set_gripper(True,20) + s.move_to([p[0],p[1],1.12],speed=.15) + if not self.held(name):s.set_gripper(False,8);return False + offset=envs.obj_pos(self.env,name)-s.eef_pos() + target=np.array([*dest_xy,envs.TABLE_Z+z_rel])-offset + s.move_to([target[0],target[1],1.12],yaw=dest_yaw) + s.move_to(target,speed=.10,tol=.003,max_steps=120) + s.set_gripper(False,12);s.move_to([target[0],target[1],1.14]);s.hold(10) + return True + + def put_butter(self): + # Place the standing stick near the front wall; lay-flat placement uses the box centre. + standing=self.butter_height()>.045 + target=np.array(self.inst['box_xy'])+([-0.030,0] if standing else [0,0]) + return self.pick_place('butter_1',target,FLOOR_T+self.butter_height()/2+.003,z_carry=.18) + + def lay_butter_flat(self): + """Extract, tip on the table through contact, then pick the horizontal stick. No pose writes.""" + s=self.sk;xy=np.asarray(self.inst['butter_xy']) + self.label('L4 recovery: take the upright stick out of the box') + if not self.pick_place('butter_1',xy,self.butter_height()/2+.003,z_carry=.18):return False + p=envs.obj_pos(self.env,'butter_1').copy() + self.label('Recovery: tip the butter stick onto its broad side') + s.set_gripper(True,8) + s.move_to([p[0]-.055,p[1],1.07],yaw=0) + s.move_to([p[0]-.055,p[1],envs.TABLE_Z+.055],speed=.10) + s.move_to([p[0]+.025,p[1],envs.TABLE_Z+.055],speed=.06) + s.move_to([p[0]+.025,p[1],1.10],speed=.12);s.set_gripper(False,8);s.hold(60) + self.label('Recovery: the butter stick is now lying flat on the table') + return self.butter_height()<.029 + + def pour_pivot(self): + return np.array([self.inst['milk_xy'][0]+self.env.sim.data.qpos[self.slide_qa],self.inst['milk_xy'][1],envs.TABLE_Z+.21]) + def pour_knob(self):return self.env.sim.data.geom_xpos[self.pour_gid].copy() + def pour_angle(self):return float(self.env.sim.data.qpos[self.pour_qa]) + def holding_pour_knob(self): + g=self.env.robots[0].gripper + return bool(self.env._check_grasp(gripper=[g.important_geoms['left_finger'],g.important_geoms['right_finger']], + object_geoms=['milk_1_pour_knob','milk_1_pour_bar'])) + + def monitor_step(self): + super().monitor_step() + if getattr(self,'liquid',None) is None or self.mon is None:return + if self.pour_angle()0: + # small outward speed along the spout, transformed by the actual hinge angle + vel=np.array([np.cos(a),0,-np.sin(a)])*.04 + q['parcels'].append(dict(p=origin.copy(),v=vel,ml=dv)) + q['reservoir']-=dv;q['emitted']+=dv + cup_origin=d.body_xpos[self.cup_bid] + cup_rot=d.body_xmat[self.cup_bid].reshape(3,3) + cup=cup_origin+cup_rot@np.array([.015,-.0016,.10]);top=cup[2] + keep=[] + for drop in q['parcels']: + p=drop['p'];v=drop['v'];end=p+v*dt+np.array([0,0,-.5*9.81*dt*dt]) + caught=False + if p[2]>=top>end[2]: + hit=p+(end-p)*(p[2]-top)/(p[2]-end[2]) + if np.linalg.norm(hit[:2]-cup[:2])<.029 and self.cup_upright(): + q['cup']+=drop['ml'];caught=True + excess=max(0.,q['cup']-180.) + if excess: + q['cup']-=excess;q['spill']+=excess;q['spill_xy']=cup[:2].tolist() + if not caught and end[2]<=envs.TABLE_Z+.002: + q['spill']+=drop['ml'];q['spill_xy']=end[:2].tolist();caught=True + if not caught: + drop['p']=end;drop['v']=v+np.array([0,0,-9.81*dt]);keep.append(drop) + q['parcels']=keep + if not render_update:return + for i,gid in enumerate(self.drop_gids): + if i.1) + if q['spill']>.1: + m.geom_pos[self.spill_gid]=[*q['spill_xy'],envs.TABLE_Z+.002] + m.geom_size[self.spill_gid,0]=min(.08,.009*np.sqrt(q['spill'])) + m.geom_rgba[self.spill_gid,3]=1 + self.env.sim.forward() + + def cup_upright(self): + # Native mug uses world Z as its vertical in the loaded LIBERO pose. + return bool(self.env.sim.data.body_xmat[self.cup_bid].reshape(3,3)[2,2]>.94) + + def label(self,text): + state=dict(text=text,step=self.sk.n_steps,lid_deg=self.lid_deg(), + pour_deg=float(np.degrees(self.pour_angle())),cup_ml=self.liquid['cup'],spill_ml=self.liquid['spill'], + butter_height_cm=100*self.butter_height(),butter_lid_contact=bool(self.butter_lid_contact()), + lid_applied_torque=float(self.env.sim.data.qfrc_applied[self.dof])) + self.trace.append(state) + if self.phase_hook:self.phase_hook(text,state) + + def calibration_probe(self): + # Attempt the loose butter first, away from fixture walls; fixed bias is present for ALL motions. + p=envs.obj_pos(self.env,'butter_1').copy();s=self.sk + s.set_gripper(False,8);s.move_to([p[0],p[1],envs.TABLE_Z+.14],yaw=0,tol=.0005,max_steps=120) + observed=s.eef_pos()-np.array([p[0],p[1],envs.TABLE_Z+.14]) + s.move_to(p,tol=.002,max_steps=100) + s.set_gripper(True,15);s.move_to([p[0],p[1],envs.TABLE_Z+.15]) + failed=not s.holding('butter_1') + self.traps['L1']=bool(failed) + self.label('L1: grasp missed the butter' if failed else 'Calibration grasp succeeded') + s.set_gripper(False,8) + return observed + + def direct_carton_lift(self): + s=self.sk;k=self.pour_knob();start=k.copy() + s.set_gripper(False,8) + s.move_to(k+[0,0,.10],yaw=0) + s.move_to(k,speed=.12,max_steps=100) + s.set_gripper(True,20) + held_before=self.holding_pour_knob() + # Pulling along the radius cannot translate a hinged cradle. Same low-level interface as agents. + s.move_to(k+[-.07,0,0],speed=.08,max_steps=30) + lift=float(np.linalg.norm(self.pour_knob()-start)) + self.pull_probe=dict(held_before=held_before,held_after=self.holding_pour_knob(),displacement_m=lift, + angle_deg=float(np.degrees(self.pour_angle()))) + self.traps['L3']=bool(held_before and lift<.01 and self.liquid['cup']<1) + self.label('L3: straight pull failed; the cradle only rotates') + s.set_gripper(False,10);s.move_to(s.eef_pos()+[0,0,.10]) + return lift + + def tip_carton(self,target_ml=110.): + s=self.sk;k=self.pour_knob();h=self.pour_pivot() + s.set_gripper(False,8);s.move_to(k+[0,0,.09],yaw=0) + s.move_to(k,tol=.002,max_steps=120);s.set_gripper(True,20) + self.label('Recovery: grasp the gold handle and tip the carton') + if not s.pour_latched:return False + for deg in range(10,81,10): + a=np.radians(deg) + target=h+[-.09*np.cos(a),-.065,.09*np.sin(a)] + s.move_to(target,speed=.06,max_steps=90,tol=.003) + self.label(f'Tipping handle: target {deg}, actual {np.degrees(self.pour_angle()):.1f}, held {s.pour_latched}') + self.label('Pouring milk into the cup') + for _ in range(120): + if self.liquid['cup']+sum(p['ml'] for p in self.liquid['parcels'])>=target_ml:break + s.hold(1) + for deg in range(70,-1,-10): + a=np.radians(deg) + s.move_to(h+[-.09*np.cos(a),-.065,.09*np.sin(a)],speed=.10,max_steps=90,tol=.003) + self.label(f'Returning handle: target {deg}, actual {np.degrees(self.pour_angle()):.1f}, held {s.pour_latched}') + s.set_gripper(False,10);e=s.eef_pos();s.move_to(e+[0,0,.12]);s.hold(15) + self.recovered['L3']=bool(80<=self.liquid['cup']<=160 and self.liquid['spill']<=15) + self.label('Milk poured; carton returned upright') + return self.recovered['L3'] + + def bread_on_plate(self): + p=envs.obj_pos(self.env,'bread_1');plate=envs.obj_pos(self.env,'plate_1') + return bool(np.linalg.norm(p[:2]-plate[:2])<.05 and p[2].045: + if not self.lay_butter_flat():self.label('Butter reorientation failed');return + if not self.put_butter():self.label('Butter storage failed');return + self.label('Upright butter stick: too tall for the shallow box' if self.butter_height()>.045 + else 'Butter stick laid flat inside the box') + self.close_lid(False) + if mode not in ('oracle','naive','blind'): + self.label('Check whether the upright butter stick fits beneath the lid') + s.hold(80) + self.traps['L4']=bool(self.lid_deg()>5 and self.butter_lid_contact()) + self.label('L4: upright butter stick physically blocks the lid' if self.traps['L4'] else 'No lid obstruction detected') + if not self.lid_closed(): + self.open_lid() + if not self.lay_butter_flat():self.label('Butter reorientation failed');return + if not self.put_butter():self.label('Horizontal butter placement failed');return + self.label('Butter stick laid flat inside the box') + self.close_lid(False) + s.hold(60) + self.recovered['L4']=bool(self.lid_closed() and self.butter_in_box()) + self.label('L4 recovery: butter laid flat; the lid closes normally') + if not self.bread_on_plate(): + self.label('Final check: restore the bread disturbed during cleanup') + self.take_bread() + s.set_gripper(False,8);s.move_to([-.35,-.30,1.20]);s.hold(15) + + def default_params(self,inst):return {'mode':'naive'} + def oracle_params(self,inst):return {'mode':'oracle'} + def adapt_params(self,inst,history):return {'mode':'adaptive'} + def run_scripted(self,kind,inst,k=None,seed=0,on_attempt=None): + rng=np.random.default_rng(seed);hist=[] + for attempt in range((k or 5) if kind=='blind' else 1): + self.reset_instance(inst) + if kind=='blind':self.sk.correction[:2]=rng.uniform(-.012,.012,2) + self.execute(inst,{'mode':kind}) + out=self.outcome(inst);hist.append(dict(attempt=attempt+1,params={'mode':kind},outcome=out)) + if on_attempt:on_attempt(attempt,hist[-1]['params'],out) + if out['success']:break + return hist + + def outcome(self,inst): + out=super().outcome(inst);q=self.liquid + inflight=sum(p['ml'] for p in q['parcels']) + out.update(cup_ml=round(q['cup'],3),spill_ml=round(q['spill'],3),reservoir_ml=round(q['reservoir'],3), + inflight_ml=round(inflight,3),conservation_error_ml=abs(300-q['reservoir']-q['cup']-q['spill']-inflight), + pour_deg=round(float(np.degrees(self.pour_angle())),2),traps=dict(self.traps),recovered=dict(self.recovered)) + out['stages'].update(milk_served=bool(80<=q['cup']<=160),spill_ok=bool(q['spill']<=15), + carton_upright=bool(abs(self.pour_angle())<.15),cup_upright=self.cup_upright(), + gripper_open=bool(self.sk.grip<0), + gripper_clear=bool(min(np.linalg.norm(self.sk.eef_pos()-envs.obj_pos(self.env,n)) + for n in ('bread_1','butter_1'))>.06), + carton_static=bool(abs(self.env.sim.data.qvel[self.pour_dof])<.1)) + out['success']=bool(out['success'] and all(out['stages'].values())) + if not out['success'] and out['failure'] is None: + out['failure']=next((k for k,v in out['stages'].items() if not v),'not_static') + out['detail']=(f"Bread on plate: {out['stages']['bread_on_plate']}; butter fully below the box rim: " + f"{out['stages']['butter_in_box']}; lid angle: {self.lid_deg():.1f} degrees. " + f"Milk in cup: {q['cup']:.1f} mL; spilled: {q['spill']:.1f} mL. " + f"Butter height: {100*self.butter_height():.1f} cm.") + if self.butter_lid_contact() and not self.lid_closed():out['detail']+=' The upright butter stick is touching and obstructing the lid.' + out.update(geometry_version=2,butter_height_cm=round(100*self.butter_height(),3), + butter_lid_contact=bool(self.butter_lid_contact()),lid_applied_torque=float(self.env.sim.data.qfrc_applied[self.dof])) + return out diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_bridge.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..b10b75576304ed46284ba5002c7857fc458d3669 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_bridge.py @@ -0,0 +1,1101 @@ +"""LH lh_bridge (v2, 2026-10-09): build a small bridge (two pillars, a plank, then the red cube "car" on top); the car is +parked right behind the bridge site, and once the plank is down the agent's natural reach for it knocks the bridge down, +which must be rebuilt before the task can be finished. + +Category: state_restoration, long-horizon self-inflicted regression. The user's example verbatim: "build a bridge; +while working you knock over a foundation you already built and must rebuild it before continuing". + +v1 -> v2 (after the Sonnet 5.5 pilot lh1: only 1 of 3 instances was ever disturbed; Sonnet carried 12-20 cm high and +lifted over built pillars, so the v1 mechanism -- sweeping a pillar with a block carried low -- rarely happened; the one +disturbance was the hand landing on the plank while going for the red cube): the car now starts in the gap between the +two squares, 5.5-9 cm behind the bridge line (right behind where the plank will lie); a spare fifth block; the bridge +4-7 cm further from the robot and the plank nearer, so that knocked parts stay within reach; softer contacts for the +bridge parts (the stiff default made collapsing blocks fly 30-90 cm); the naive reference imitates Sonnet's measured +motion style instead of the v1 low-transit script (kept as naive_v1). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): two coloured square +marks (blue and green, 6 x 6 cm, visual only) 16 cm apart along y, 48-51 cm in front of the robot base; the red cube +(4 cm) in the gap between them, 5.5-9 cm behind the line through the squares (+-3 cm sideways, yaw +-20 deg); five +wooden cubes (edge 5.0-5.6 cm, friction 0.3-0.6, five distinct categories) in a row 9-11 cm behind the squares, two on +one side of the car and three on the other; the plank (24 x 5 x 1.2 cm) lying left-right 19-21 cm behind the squares. + +Stages (order-free predicates, evaluated after every control step by a monitor; events are debounced over 6 steps): + S1 two blocks stacked on the blue square (lower block resting on the table within 2.5 cm of the square's centre, + upper block resting on it within 2.5 cm; any face down, cubes have no "right way up") + S2 the same on the green square + S3 the plank rests on the top blocks of both pillars: in contact with both, not with the table, tilt <= 10 deg + S4 the red cube rests on the plank within 6 cm of the plank's centre along its length +Success = all four hold at the end simultaneously, the scene is static (< 4 mm motion in 1 s) and the robot neither +holds nor touches any object. The monitor's achieved / lost / restored events go to the server log only (F1). + +Why the agent breaks the bridge (measured, see task_cards/lh_bridge.md): with the plank down, the car sits 3-6.5 cm +behind the plank's back edge, between the pillars. The Panda hand is 21 cm long along the finger axis and its underside +is only 2.4 cm above the grasp point; the fingertips hang 1.3 cm below it. Each of the three pilot runs went for the car +differently; scripted here on seeds 1000-1019: hovering ~13 cm above it while turning the wrist from the plank's 90 deg +to the car's yaw, then straight down (5/20 knock the bridge), keeping the 90 deg wrist and going straight down (the hand +lands across the plank: 20/20), or one diagonal move from above the bridge straight down to the grasp (the hand drives +through the bridge: 20/20). The plank and one or both pillar tops fall; in 22 of 24 collapses (seeds 3000-3029) every +part needed stays within reach (a block out of reach is covered by the spare; the plank was thrown out of reach twice). +What prevents it (learnable from one failure, and what Sonnet wrote after its pilot failure): move the car away before +laying the plank. + +Hidden variables: none that matter. Block size and friction are instance variety; the car's distance (5.5-9 cm) and yaw +decide only the "hover" style's outcome. + +Scripted references (perception = simulator state): + naive Sonnet-like (measured on the pilot): instruction order; per pillar the free block nearest its square first; + hover ~12 cm above an object turned to its yaw, vertical descent, grasp 1.1 cm below the top; carry to a bare + square in one diagonal move to 12.5 cm above it, onto a block lift first; lift over a built pillar when the + carried block's straight path would hit it; release, lift to 15 cm; plank lifted to 7 cm, carried at 16 cm, + lift to 21 cm; the car approach style is the pilot's mixture (seed % 3: hover / keep / direct); no final check + naive_v1 the v1 naive (vertical / horizontal legs at 8 cm, carries at max(8 cm, release + 4 cm)), for comparison + oracle careful: first moves the car out of the zone behind the bridge; all transits at 25 cm, vertical approaches + at 0.1 m/s, grasps 1.6 cm below a cube's top, gripper yaw chosen for hand / finger clearance; checks every + stage at the end and repairs what is broken (same repair as adaptive) + adaptive attempt 1 = naive, then checks every stage before finishing and restores what was lost (tips a plank that + stands on edge, puts the plank and car aside, re-stacks the pillars from usable blocks, then plank and car + again); from attempt 2 the careful behaviour + blind naive with random variation (hover / carry / lift heights, diagonal or lift-first carries, car style, + block allocation, 4 mm placement noise), no history + +Protocol: cross (reset to the same instance before every attempt), k = 3. +""" +import os + +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +BLOCKS = ["block_a_1", "block_b_1", "block_c_1", "block_d_1", "block_e_1"] # four are needed, one is a spare +PLANK, CAR = "plank_1", "car_1" +SQUARES = ["square_blue_1", "square_green_1"] # S1 = blue, S2 = green +ITEMS = BLOCKS + [PLANK, CAR] +BLOCK_RGBA = [(0.80, 0.66, 0.46, 1.0), (0.70, 0.55, 0.37, 1.0), (0.84, 0.72, 0.56, 1.0), (0.64, 0.50, 0.36, 1.0), + (0.76, 0.60, 0.42, 1.0)] # wood +PLANK_HALF = (0.12, 0.025, 0.006) # 24 x 5 x 1.2 cm, long axis = body x +CAR_HALF = 0.02 +BLOCK_NOM = 0.026 # nominal half edge in the MJCF (resized per instance) +SQ_HALF = 0.03 +SQ_RGBA = {"square_blue_1": (0.12, 0.30, 0.90, 1.0), "square_green_1": (0.10, 0.70, 0.25, 1.0)} +SQ_NAME = {"square_blue_1": "blue", "square_green_1": "green"} +SPAN = 0.16 # square centre distance (along y) + +TZ = envs.TABLE_Z +BASE_X = -0.66 +HAND_HALF_LONG = 0.106 # Panda hand collision AABB about the grasp site: +-10.6 cm along the finger axis +HAND_HALF_SHORT = 0.036 # +-3.6 cm across it +HAND_BOTTOM = 0.024 # its underside is 2.4 cm above the grasp site (measured) + +SQ_TOL = 0.025 # lower block centre within 2.5 cm of the square centre +STACK_TOL = 0.025 # upper block centre within 2.5 cm of the lower one +FLAT_COS = np.cos(np.radians(12)) +PLANK_TILT = np.radians(10) +CAR_MID = 0.06 +DEBOUNCE = 6 # control steps a predicate must keep its new value before an event is recorded + +# v2 layout (2026-10-09): the red cube ("car") is parked in the gap between the two squares, just behind the bridge +# line, so that once the plank is down a natural top-down grasp of it lands the hand on the plank / pillar tops; the +# four wooden blocks lie in a row behind the bridge, two on each side of the car; the plank lies further back. +LAYOUT = dict(bridge_x=(-0.18, -0.15), row_dx=(0.09, 0.11), y_half=0.30, gap=0.095, car_dx=(0.055, 0.09), car_dy=0.03, + car_clear=0.08, car_yaw=0.35, plank_dx=(0.19, 0.21), block_edge=(0.050, 0.056)) +KEEP_OUT = dict(dx=0.13, dy=0.20) # careful: no parking / no material left within this zone behind the bridge line +# Sonnet-like naive (measured on the lh1 pilot, see task_cards/lh_bridge.md): heights of the grasp site above the table +SN = dict(hover=0.12, carry=0.125, lift=0.15, cross_margin=0.04, plank_lift=0.07, plank_carry=0.16, car_lift=0.17, + end_lift=0.25, top_below=0.011, diag=True, car_style=None, car_hover=0.134, plank_end_lift=0.21, + alloc="greedy") +# how the gripper went for the red cube once the plank was down -- each of the three pilot runs did it differently: +# hover (seed 3002) move to ~13.4 cm above it while turning to its yaw, then straight down +# keep (seed 3000) the same, but still turned 90 deg from laying the plank +# direct (seed 3001) one move from ~21 cm above the bridge straight (diagonally) down to the grasp +# the naive script uses style CAR_STYLES[seed % 3] (car_style=None), i.e. the pilot's mixture +CAR_STYLES = ("hover", "keep", "direct") +Z_NAIVE = 0.08 # naive_v1 transit height of the grasp site above the table +Z_SAFE = 0.25 # careful transit height +NAIVE_LIFT = 0.05 # naive: lift this far straight up after letting go, then head for the next waypoint +NAIVE_STYLE = "legs" # legs: vertical / horizontal legs at the transit height; diag: straight lines between waypoints + + +def _wrap_q(a): + """wrap to [-pi/4, pi/4) (cubes are symmetric under 90 deg)""" + return float((a + np.pi / 4) % (np.pi / 2) - np.pi / 4) + + +def _wrap_h(a): + """wrap to [-pi/2, pi/2) (plank / gripper symmetric under 180 deg)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +# Contact softness of the bridge parts. LFF-Bench's generated boxes use a very stiff contact (objects._SOLID); when a +# fast hand drives into a stacked bridge, the stiff contacts resolve the overlap with large impulses and blocks fly +# 30-90 cm (measured: up to 1.7 m/s while the hand moved at 0.5-0.8 m/s), often out of reach or off the table. A +# softer contact (MuJoCo-like defaults) keeps collapses local. None = use the stiff default. +CONTACT = os.environ.get("LFF_LHB_CONTACT", 'solimp="0.95 0.99 0.001" solref="0.01 1"') + + +def part_xml(model_name, half, rgba, density): + """box like objects.box_xml, with the task's contact softness""" + if not CONTACT or CONTACT == "stiff": + return box_xml(model_name, half, rgba, density=density) + g = (f' \n' + f' ') + return _wrap(model_name, g, half[2], float(np.hypot(half[0], half[1]))) + + +def mark_xml(name, rgba): + """flat coloured square, visual only (does not touch the physics)""" + g = (f' ') + return _wrap(name, g, 0.0006, SQ_HALF * 1.42) + + +class BridgeSkills(Skills): + """Skills that feed the task's per-step stage monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class Bridge(LFFTask): + name = "lh_bridge" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Plan", "Reason", "Restore") + protocol = "cross" + max_attempts = 3 + agent_max_steps = 130 + instruction = ("Build a small bridge. First stack two of the wooden blocks on the blue square, then two on the green " + "square, to make two pillars; then lay the long plank across the tops of both pillars; finally put " + "the red cube on the middle of the plank. The finished bridge must stand on its own, with the " + "gripper open and not touching anything.") + instruction_indirect = ("Build a small bridge. First make a tower of two of the wooden cubes on the blue mark on the " + "table, then another tower of two on the green mark; then lay the long flat board across the " + "tops of the two towers; finally set the small red cube on the middle of the board. At the " + "end everything must stand on its own, with the gripper open and not touching anything.") + agent_object_names = ["wooden blocks (5)", "plank", "red cube", "blue square", "green square"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs = [] + for i, b in enumerate(BLOCKS): + cat = register_generated(f"LffLhbBlock{'ABCDE'[i]}", part_xml(f"lff_lhb_block_{'abcde'[i]}", (BLOCK_NOM,) * 3, + BLOCK_RGBA[i], 500.0)) + reg = (-0.30 + 0.12 * i, 0.30, -0.29 + 0.12 * i, 0.31) if i < 4 else (0.10, -0.25, 0.11, -0.24) + objs.append((b, cat, f"blk{i}_region", reg)) + pl = register_generated("LffLhbPlank", part_xml("lff_lhb_plank", PLANK_HALF, (0.50, 0.33, 0.18, 1.0), + density=600.0)) + objs.append((PLANK, pl, "plank_region", (0.05, -0.01, 0.06, 0.01))) + car = register_generated("LffLhbCar", part_xml("lff_lhb_car", (CAR_HALF,) * 3, (0.85, 0.10, 0.08, 1.0), + density=400.0)) + objs.append((CAR, car, "car_region", (-0.30, -0.31, -0.29, -0.30))) + fx = [] + for i, s in enumerate(SQUARES): + cat = register_generated(f"LffLhbSquare{'BG'[i]}", mark_xml(f"lff_lhb_square_{'bg'[i]}", SQ_RGBA[s]), + free=False) + fx.append((s, cat, f"sq{i}_region", (-0.10 + 0.10 * i, -0.31, -0.09 + 0.10 * i, -0.30))) + return write_bddl(self.name, "Build a small bridge from the blocks the plank and the red cube", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.sq_bid = {s: m.body_name2id(self.env.fixtures_dict[s].root_body) for s in SQUARES} + self.geoms = {o: envs.obj_geom_ids(self.env, o) for o in ITEMS} + self.vis_geoms = {} + for o in BLOCKS: + root = envs.body_id(self.env, o) + bodies = {b for b in range(m.nbody) if b == root or m.body_parentid[b] == root} + self.vis_geoms[o] = [g for g in range(m.ngeom) if m.geom_bodyid[g] in bodies and m.geom_contype[g] == 0 + and m.geom_conaffinity[g] == 0 and m.geom_type[g] == 6] + self.block_body = getattr(self, "block_body", {}) + self.block_body[o] = int(m.geom_bodyid[self.geoms[o][0]]) + self.table_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("main_table") + and m.geom_contype[g] != 0] + self.robot_geoms = set(envs.robot_geom_ids(self.env)) + self.inst = None + self.mon = None + self.sk = None + self.naive_lift = NAIVE_LIFT + self.naive_style = NAIVE_STYLE + + # ------------------------------------------------------------ instances + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + xb = float(rng.uniform(*LAYOUT["bridge_x"])) + yc = float(rng.uniform(-0.03, 0.03)) + blue_left = bool(rng.random() < 0.5) + sq = {"square_blue_1": [xb, yc + (SPAN / 2 if blue_left else -SPAN / 2)], + "square_green_1": [xb, yc - (SPAN / 2 if blue_left else -SPAN / 2)]} + L = LAYOUT + # the car: in the gap between the two squares, just behind the bridge line + pos = {CAR: [xb + float(rng.uniform(*L["car_dx"])), yc + float(rng.uniform(-L["car_dy"], L["car_dy"]))]} + # five blocks in a row behind the bridge line, two on one side of the car and three on the other + row_x = xb + float(rng.uniform(*L["row_dx"])) + ys = [] + three = 1.0 if rng.random() < 0.5 else -1.0 + for side in (-1.0, 1.0): + n = 3 if side == three else 2 + lo, hi = sorted((pos[CAR][1] + side * L["car_clear"], side * L["y_half"])) + u = np.sort(rng.uniform(0.0, max((hi - lo) - (n - 1) * L["gap"], 0.0), n)) + ys += [lo + k * L["gap"] + u[k] for k in range(n)] + order = rng.permutation(5) + for k, j in enumerate(order): + pos[BLOCKS[j]] = [row_x + float(rng.uniform(-0.01, 0.01)), float(ys[k])] + plank_xy = [xb + float(rng.uniform(*L["plank_dx"])), yc + float(rng.uniform(-0.04, 0.04))] + size = {b: float(rng.uniform(*L["block_edge"])) for b in BLOCKS} + mu = {b: float(rng.uniform(0.3, 0.6)) for b in BLOCKS} + yaw = {o: float(rng.uniform(-0.35, 0.35)) for o in BLOCKS} + yaw[CAR] = float(rng.uniform(-L["car_yaw"], L["car_yaw"])) + yaw[PLANK] = float(np.pi / 2 + rng.uniform(-0.25, 0.25)) # long axis roughly left-right + pos[PLANK] = plank_xy + return dict(seed=int(seed), squares=sq, blue_side="left" if blue_left else "right", pos=pos, yaw=yaw, + size=size, mu=mu, bridge_x=xb, bridge_yc=yc) + + def _resize_block(self, o, edge): + m = self.env.sim.model + h = edge / 2.0 + for g in self.geoms[o] + self.vis_geoms[o]: + m.geom_size[g] = [h, h, h] + m.geom_rbound[g] = float(np.sqrt(3) * h) + m.geom_aabb[g] = [0.0, 0.0, 0.0, h, h, h] + b = self.block_body[o] + mass = 500.0 * edge ** 3 + m.body_mass[b] = mass + m.body_inertia[b] = [mass * edge ** 2 / 6.0] * 3 + envs.refit_bounds(self.env, b) # BVH of the resized block (envs.refit_bounds) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + for s in SQUARES: + x, y = inst["squares"][s] + m.body_pos[self.sq_bid[s]] = [x, y, TZ + 0.0007] + m.body_quat[self.sq_bid[s]] = [1.0, 0.0, 0.0, 0.0] + for o in BLOCKS: + self._resize_block(o, inst["size"][o]) + envs.set_friction(self.env, o, inst["mu"][o]) + envs.set_friction(self.env, PLANK, 0.5) + envs.set_friction(self.env, CAR, 0.6) + self.env.sim.forward() + for o in ITEMS: + envs.place_upright(self.env, o, inst["pos"][o], inst["yaw"][o], clearance=0.001) + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = BridgeSkills(self.env, self, recorder=recorder) + self.mon = dict(state=[False] * 4, raw_since=[0] * 4, ever=[False] * 4, lost=[False] * 4, events=[]) + return self.sk + + # ------------------------------------------------------------ geometry / predicates + def half(self, o): + if o in BLOCKS: + e = self.inst["size"][o] / 2 + return np.array([e, e, e]) + return np.array(PLANK_HALF) if o == PLANK else np.array([CAR_HALF] * 3) + + def R(self, o): + return self.env.sim.data.body_xmat[envs.body_id(self.env, o)].reshape(3, 3).copy() + + def pos(self, o): + return envs.obj_pos(self.env, o) + + def zmin(self, o): + return envs.obj_min_z(self.env, o) + + def zmax(self, o): + return envs.obj_max_z(self.env, o) + + def flat(self, o): + return float(np.max(np.abs(self.R(o)[2]))) > FLAT_COS + + def yaw_of(self, o): + """yaw of the object's body x axis (for the plank: its long axis)""" + R = self.R(o) + return float(np.arctan2(R[1, 0], R[0, 0])) + + def held(self, o): + return self.sk is not None and self.sk.holding(o) + + def contacts(self, a_geoms, b_geoms): + return envs.contacts_between(self.env, a_geoms, b_geoms) + + def pillar(self, s): + """(lower, upper) blocks of a complete pillar on square s, else (lower or None, None)""" + c = np.asarray(self.inst["squares"][s]) + lower = None + for b in BLOCKS: + p = self.pos(b) + if np.linalg.norm(p[:2] - c) <= SQ_TOL and self.zmin(b) < TZ + 0.006 and self.flat(b) and not self.held(b): + lower = b + break + if lower is None: + return None, None + pl = self.pos(lower) + top = self.zmax(lower) + for b in BLOCKS: + if b == lower: + continue + p = self.pos(b) + if (np.linalg.norm(p[:2] - pl[:2]) <= STACK_TOL and abs(self.zmin(b) - top) < 0.006 and self.flat(b) + and not self.held(b)): + return lower, b + return lower, None + + def plank_ok(self, tops): + if any(t is None for t in tops) or self.held(PLANK): + return False + R = self.R(PLANK) + if abs(R[2, 0]) > np.sin(PLANK_TILT) or abs(R[2, 2]) < np.cos(PLANK_TILT): # either broad face up (v2 fix) + return False + if self.zmin(PLANK) < TZ + 0.03 or self.contacts(self.geoms[PLANK], self.table_geoms): + return False + return all(self.contacts(self.geoms[PLANK], self.geoms[t]) for t in tops) + + def car_ok(self): + """the car rests on the plank's upper face (in the plank's own frame, so a slightly tilted plank is fine), + within CAR_MID of the plank's centre along its length""" + if self.held(CAR) or not self.contacts(self.geoms[CAR], self.geoms[PLANK]): + return False + R = self.R(PLANK) + rel = R.T @ (self.pos(CAR) - self.pos(PLANK)) + up = rel[2] * (1.0 if R[2, 2] >= 0 else -1.0) # along the broad face pointing up (a plank may lie upside down) + return bool(abs(rel[0]) <= CAR_MID and abs(rel[1]) <= PLANK_HALF[1] + 0.01 and up > PLANK_HALF[2] + 0.01) + + def stages(self): + """raw predicate values [S1, S2, S3, S4] and the pillars found""" + pa = self.pillar(SQUARES[0]) + pb = self.pillar(SQUARES[1]) + s1, s2 = pa[1] is not None, pb[1] is not None + s3 = bool(s1 and s2 and self.plank_ok([pa[1], pb[1]])) + s4 = bool(self.car_ok()) + return [s1, s2, s3, s4], (pa, pb) + + # ------------------------------------------------------------ monitor + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + raw, _ = self.stages() + t = self.sk.n_steps + for i in range(4): + if raw[i] == mon["state"][i]: + mon["raw_since"][i] = 0 + continue + mon["raw_since"][i] += 1 + if mon["raw_since"][i] < DEBOUNCE: + continue + mon["state"][i] = raw[i] + mon["raw_since"][i] = 0 + t0 = t - DEBOUNCE + 1 + if raw[i]: + ev = "restored" if mon["lost"][i] else "achieved" + mon["ever"][i] = True + else: + ev = "lost" + mon["lost"][i] = True + mon["events"].append(dict(stage=f"S{i + 1}", event=ev, step=int(t0))) + + # ------------------------------------------------------------ outcome + def _dir_words(self, d): + """robot-centric words for a horizontal offset d (world x = forward, away from the robot; y = robot's left)""" + parts = [] + if abs(d[0]) >= 0.01: + parts.append(f"{100 * abs(d[0]):.0f} cm {'forward' if d[0] > 0 else 'back'}") + if abs(d[1]) >= 0.01: + parts.append(f"{100 * abs(d[1]):.0f} cm {'left' if d[1] > 0 else 'right'}") + return (" and ".join(parts) + " of") if parts else "right at" + + def outcome(self, inst): + sk = self.sk + sk.hold(10) + p0 = {o: self.pos(o) for o in ITEMS} + touching = False + for _ in range(20): + sk.hold(1) + touching = touching or any(self.contacts(list(self.robot_geoms), self.geoms[o]) for o in ITEMS) + moved = max(float(np.linalg.norm(self.pos(o) - p0[o])) for o in ITEMS) + static = moved < 0.004 + raw, (pa, pb) = self.stages() + held = [o for o in ITEMS if sk.holding(o)] + mon = self.mon + ev = list(mon["events"]) if mon else [] + n_reg = sum(e["event"] == "lost" for e in ev) + n_res = sum(e["event"] == "restored" for e in ev) + success = bool(all(raw) and static and not held and not touching) + parts = [] + if success: + failure = "none" + parts.append("The bridge is complete: both pillars stand on their squares, the plank rests across them " + "and the red cube sits on the middle of the plank.") + else: + lost_final = [i for i in range(4) if not raw[i] and mon and mon["ever"][i]] + never = [i for i in range(4) if not raw[i] and not (mon and mon["ever"][i])] + if held: + failure = "held" + elif touching: + failure = "touching" + elif lost_final: + failure = "regressed_" + "".join(f"S{i + 1}" for i in lost_final) + elif never: + failure = "incomplete_" + "".join(f"S{i + 1}" for i in never) + else: + failure = "not_static" + for i, s in enumerate(SQUARES): + if raw[i]: + continue + low, _ = (pa, pb)[i] + c = np.asarray(inst["squares"][s]) + txt = f"The pillar on the {SQ_NAME[s]} square is not standing:" + if low is None: + txt += " no block stands on the square." + else: + txt += " only one block stands on the square." + strays = [b for b in BLOCKS if b not in (pa[0], pa[1], pb[0], pb[1])] + if strays: + near = min(strays, key=lambda b: np.linalg.norm(self.pos(b)[:2] - c)) + txt += f" The nearest loose block lies {self._dir_words(self.pos(near)[:2] - c)} the square." + if mon and mon["ever"][i]: + txt += " It had been built and was knocked down later." + parts.append(txt) + if not raw[2]: + pp = self.pos(PLANK) + if self.contacts(self.geoms[PLANK], self.table_geoms): + where = "touches the table" + elif self.held(PLANK): + where = "is still in the gripper" + else: + where = "does not rest level on the tops of both pillars" + bc = np.mean([inst["squares"][s] for s in SQUARES], axis=0) + parts.append(f"The plank {where}; its centre is {self._dir_words(pp[:2] - bc)} the middle between " + f"the squares." + (" It had been laid and was disturbed later." if mon and mon["ever"][2] + and not raw[2] else "")) + if not raw[3]: + if self.held(CAR): + parts.append("The red cube is still in the gripper.") + elif self.contacts(self.geoms[CAR], self.geoms[PLANK]): + parts.append("The red cube is on the plank but not on its middle part.") + else: + bc = np.mean([inst["squares"][s] for s in SQUARES], axis=0) + parts.append(f"The red cube is not on the plank; it lies {self._dir_words(self.pos(CAR)[:2] - bc)} " + "the middle between the squares.") + if all(raw) and held: + parts.append("The gripper still holds an object.") + elif touching: + parts.append("The gripper is still touching the bridge.") + elif all(raw) and not static: + parts.append("The bridge was still moving.") + if n_reg: + parts.append(f"During the attempt earlier stages were undone {n_reg} time(s) and restored {n_res} time(s).") + if any(w in " ".join(parts) for w in (" forward of", " back of", " back and", " forward and")): + parts.append("(Forward = away from the robot.)") + return dict(success=success, stages={f"S{i + 1}": bool(raw[i]) for i in range(4)}, events=ev, + n_regressions=int(n_reg), n_restored=int(n_res), failure=failure, held=held, + touching=bool(touching), static=bool(static), detail=" ".join(parts)) + + # ------------------------------------------------------------ scripted policies (move_to + gripper only) + def _grip_yaws(self, o): + """candidate gripper yaws for a top-down grasp of o (fingers across a face)""" + if o == PLANK: # fingers (which open along the gripper's y at yaw 0) across the plank's width + return [_wrap_h(self.yaw_of(PLANK))] + a = _wrap_q(self.yaw_of(o)) + return [a, _wrap_h(a + np.pi / 2)] + + def footprint(self, o): + """sample points on the horizontal footprint of o (corners, edge midpoints, centre)""" + R, c, h = self.R(o), self.pos(o), self.half(o) + pts = [] + for sx in (-1, 0, 1): + for sy in (-1, 0, 1): + for sz in ((-1, 1) if o != PLANK else (0,)): + pts.append((c + R @ (h * [sx, sy, sz]))[:2]) + if o == PLANK: + for t_ in np.linspace(-1, 1, 9): + for sy in (-1, 1): + pts.append((c + R @ (h * [t_, sy, 0]))[:2]) + return np.array(pts) + + def _hand_clearance(self, xy, yaw, z_site, ignore=()): + """smallest horizontal clearance (m) between the gripper at a grasp-site height z_site and everything else: + the hand body (+-10.6 x +-3.6 cm, underside 2.4 cm above the site) against items taller than its underside, + the open fingers (two 2 x 2.4 cm boxes 3-5 cm out along the finger axis, tips 1.3 cm below the site) + against items taller than the fingertips. Negative = the gripper would land on something.""" + f = np.array([-np.sin(yaw), np.cos(yaw)]) # finger axis + g = np.array([np.cos(yaw), np.sin(yaw)]) + best = 1.0 + for o in ITEMS: + if o in ignore or self.held(o): + continue + top = self.zmax(o) + if top < z_site - 0.013: + continue + d = self.footprint(o) - np.asarray(xy) + u, v = np.abs(d @ f), np.abs(d @ g) + c = float(np.min(np.maximum(np.abs(u - 0.040) - 0.010, v - 0.012))) # fingers + if top >= z_site + HAND_BOTTOM - 0.002: + c = min(c, float(np.min(np.maximum(u - HAND_HALF_LONG, v - HAND_HALF_SHORT)))) + best = min(best, c) + return best + + @staticmethod + def _pick_yaw(yaws, clearance): + """the gripper yaw closest to straight (0) among those with >= 1 cm clearance, else the clearest one (large + wrist turns near the edge of the workspace make the OSC stop short)""" + c = {a: clearance(a) for a in yaws} + ok = [a for a in yaws if c[a] >= 0.01] + return min(ok, key=abs) if ok else max(yaws, key=c.get) + + def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=250): + return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + + def _grasp_z(self, o, careful): + if o in BLOCKS: + return self.zmax(o) - (0.016 if careful else self.inst["size"][o] / 2) + if o == PLANK: + return max(self.zmax(PLANK) + 0.0003 - 0.0125, TZ + 0.011) + return self.zmax(CAR) - (0.016 if careful else CAR_HALF) + + def pick(self, o, careful, noise=None, z_t=None): + """top-down grasp; returns the drop of the object's bottom below the grasp site, or None if not held""" + sk = self.sk + p = self.pos(o) + if noise is not None: + p = p + np.array([noise[0], noise[1], 0.0]) + zg = self._grasp_z(o, careful) + yaws = self._grip_yaws(o) + if careful: + yaw = self._pick_yaw(yaws, lambda a: self._hand_clearance(p[:2], a, zg, ignore=(o,))) + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + Z_SAFE]) + self._go([p[0], p[1], TZ + Z_SAFE], yaw=yaw) + sk.set_gripper(False, steps=8) + self._go([p[0], p[1], zg + 0.03], speed=0.25) + self._go([p[0], p[1], zg], speed=0.1, tol=0.003, max_steps=120) + else: + yaw = min(yaws, key=lambda a: abs(a)) + zt = TZ + (Z_NAIVE if z_t is None else z_t) + sk.set_gripper(False, steps=8) + if self.naive_style == "legs": # rise to the transit height if below it, across, straight down + cur = sk.eef_pos() + if cur[2] < zt - 0.003: + self._go([cur[0], cur[1], zt]) + self._go([p[0], p[1], max(cur[2], zt)], yaw=yaw) + else: # one straight line to the approach point above the object + self._go([p[0], p[1], max(zt, self.zmax(o) + 0.03)], yaw=yaw) + self._go([p[0], p[1], zg], tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + drop = float(sk.eef_pos()[2] - self.zmin(o)) + if careful: + self._go([p[0], p[1], TZ + Z_SAFE], speed=0.3) + else: + zt = TZ + (Z_NAIVE if z_t is None else z_t) + self._go([p[0], p[1], max(zt, zg + 0.05)]) + if not sk.holding(o): + sk.set_gripper(False, steps=8) + return None + return drop + + def place(self, o, xy, support_top, drop, yaw, careful, z_t=None, release_gap=0.005, lift=None): + sk = self.sk + zr = support_top + drop + release_gap + if careful and o != PLANK: # cubes are symmetric under 90 deg: release with the fingers where there is room + yaw = self._pick_yaw([yaw, _wrap_h(yaw + np.pi / 2)], lambda a: self._hand_clearance(xy, a, zr, ignore=(o,))) + if careful: + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + Z_SAFE]) + self._go([xy[0], xy[1], TZ + Z_SAFE], yaw=yaw) + self._go([xy[0], xy[1], zr + 0.03], speed=0.25) + self._go([xy[0], xy[1], zr], speed=0.08, tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + self._go([xy[0], xy[1], zr + 0.03], speed=0.1) + self._go([xy[0], xy[1], TZ + Z_SAFE], speed=0.3) + else: + if self.naive_style == "legs": + zt = TZ + (Z_NAIVE if z_t is None else z_t) + cur = sk.eef_pos() + h = max(cur[2], zt, zr + 0.04) + if cur[2] < h - 0.003: + self._go([cur[0], cur[1], h]) + self._go([xy[0], xy[1], h], yaw=yaw) + else: + self._go([xy[0], xy[1], zr + 0.04], yaw=yaw) + self._go([xy[0], xy[1], zr], tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + self._go([xy[0], xy[1], zr + (self.naive_lift if lift is None else lift)]) + sk.hold(5) + + # placing targets --------------------------------------------------------- + def square_xy(self, s): + return np.asarray(self.inst["squares"][s], float) + + def bridge_mid(self): + return np.mean([self.square_xy(s) for s in SQUARES], axis=0) + + def free_blocks(self): + _, (pa, pb) = self.stages() + used = set() + for low, up in (pa, pb): + if up is not None: + used |= {low, up} + return [b for b in BLOCKS if b not in used] + + def _blocker(self, b): + """for a careful top-down grasp of block b: None if the gripper fits at some grasp yaw, else the item in the + way (e.g. the top block of a pillar, or a block, right next to b)""" + zg = self._grasp_z(b, True) + p = self.pos(b)[:2] + if max(self._hand_clearance(p, a, zg, ignore=(b,)) for a in self._grip_yaws(b)) > -0.002: + return None + worst = {} + for o in ITEMS: + if o == b or self.held(o): + continue + worst[o] = max(self._hand_clearance(p, a, zg, ignore=tuple(q for q in ITEMS if q != o)) + for a in self._grip_yaws(b)) + o = min(worst, key=worst.get) + return o if worst[o] <= -0.002 else None + + def build_pillar(self, s, careful, noise_fn, z_t=None, order="target"): + """put blocks on square s until it carries a complete pillar (at most 5 placements)""" + failed = {} + for _ in range(6): + raw, (pa, pb) = self.stages() + low, up = (pa, pb)[SQUARES.index(s)] + if up is not None: + return True + if careful and self.over_budget(): + return False + c = self.square_xy(s) + other = (pa, pb)[1 - SQUARES.index(s)] + cand = [b for b in BLOCKS if b != low and b not in other and (not careful or (self.usable(b) + and failed.get(b, 0) < 2))] + if not cand: + return False + ref = self.sk.eef_pos()[:2] if order == "gripper" else c + cand.sort(key=lambda b: (failed.get(b, 0), np.linalg.norm(self.pos(b)[:2] - ref))) + b = cand[0] + if careful: + free = [q for q in cand if self._blocker(q) is None] + if free: + b = free[0] + else: # every usable block sits right next to something tall: take that thing's top off first + blk = self._blocker(cand[0]) + if blk is not None and blk != PLANK and failed.get(blk, 0) < 2: + if not self.park(blk): + failed[blk] = failed.get(blk, 0) + 1 + continue + drop = self.pick(b, careful, noise=noise_fn(), z_t=z_t) + if drop is None: + failed[b] = failed.get(b, 0) + 1 + continue + if low is None: + tgt, top = c, TZ + else: + tgt, top = self.pos(low)[:2], self.zmax(low) + n = noise_fn() + self.place(b, tgt + (n if n is not None else 0.0), top, drop, 0.0, careful, z_t=z_t) + return self.stages()[1][SQUARES.index(s)][1] is not None + + def lay_plank(self, careful, noise_fn, z_t=None): + raw, (pa, pb) = self.stages() + if pa[1] is None or pb[1] is None or (careful and not self.usable(PLANK)): + return False + drop = self.pick(PLANK, careful, noise=noise_fn(), z_t=z_t) + if drop is None: + return False + raw, (pa, pb) = self.stages() + if pa[1] is None or pb[1] is None: + tops = [TZ + 0.11, TZ + 0.11] + mid = self.bridge_mid() + else: + tops = [self.zmax(pa[1]), self.zmax(pb[1])] + mid = (self.pos(pa[1])[:2] + self.pos(pb[1])[:2]) / 2 + n = noise_fn() + # gripper fingers across the plank's width: plank long axis along y -> gripper yaw 90 deg + self.place(PLANK, mid + (n if n is not None else 0.0), max(tops), drop, np.pi / 2, careful, z_t=z_t) + return True + + def put_car(self, careful, noise_fn, z_t=None): + drop = self.pick(CAR, careful, noise=noise_fn(), z_t=z_t) + if drop is None: + return False + pp = self.pos(PLANK) + n = noise_fn() + self.place(CAR, pp[:2] + (n if n is not None else 0.0), self.zmax(PLANK), drop, 0.0, careful, z_t=z_t) + return True + + def in_keep_out(self, o): + """o lies in the zone right behind the bridge line where, once the pillars and the plank stand, a top-down + grasp would put the hand on them (the careful policy keeps it clear)""" + p = self.pos(o)[:2] + dx = p[0] - self.inst["bridge_x"] + return bool(-0.08 < dx < KEEP_OUT["dx"] and abs(p[1] - self.bridge_mid()[1]) < KEEP_OUT["dy"]) + + def free_spot(self, o, avoid=()): + """a free, comfortably reachable table spot for parking object o (the plank lies left-right), outside the + keep-out zone right behind the bridge and away from the squares""" + xb = self.inst["bridge_x"] + ym = self.bridge_mid()[1] + best, best_c = None, -1.0 + others = [q for q in ITEMS if q != o and q not in avoid] + for x in np.arange(xb - 0.14, xb + 0.221, 0.02): + for y in np.arange(-0.28, 0.281, 0.02): + pts = [np.array([x, y])] + if o == PLANK: + pts = [np.array([x, y + d]) for d in (-0.10, 0.0, 0.10)] + if any(not self.reachable_xy(p) or np.hypot(p[0] - BASE_X, p[1]) > 0.64 for p in pts): + continue # (a careful 25 cm transit further out straightens the elbow onto its limit, measured) + if any(-0.08 < p[0] - xb < KEEP_OUT["dx"] and abs(p[1] - ym) < KEEP_OUT["dy"] for p in pts): + continue + c = 1.0 + for p in pts: + for q in others: + c = min(c, float(np.linalg.norm(self.pos(q)[:2] - p)) - 0.04) + for sq in SQUARES: + c = min(c, float(np.linalg.norm(self.square_xy(sq) - p)) - 0.07) + if c > best_c: + best, best_c = np.array([x, y]), c + return best + + @staticmethod + def reachable_xy(p): + """a top-down grasp at table height works here (measured: right in front of the base, closer than 25 cm, + the arm cannot get down to the table; at 70-74 cm it still gets within ~1 cm)""" + rx, y = p[0] - BASE_X, p[1] + return bool(0.25 <= rx <= 0.75 and abs(y) <= 0.34 and (rx >= 0.30 or abs(y) >= 0.15) and np.hypot(rx, y) <= 0.76) + + def usable(self, o): + """o lies on the table (or on something) within reach""" + return self.zmin(o) > TZ - 0.02 and self.reachable_xy(self.pos(o)[:2]) + + def park(self, o, careful=True): + if careful and not self.usable(o): + return False + drop = self.pick(o, careful) + if drop is None: + return False + xy = self.free_spot(o) + self.place(o, xy, TZ, drop, np.pi / 2 if o == PLANK else 0.0, careful) + return True + + def over_budget(self): + """the scripted repair stops where an agent's attempt would end: 3 s of simulated motion per command of the + task's command budget (agent_max_steps = 130 -> 390 s = 7800 control steps)""" + return self.sk.n_steps * 0.05 >= 3.0 * self.agent_max_steps + + def plank_flat(self): + return abs(self.R(PLANK)[2, 2]) > 0.8 + + def fix_plank(self): + """a plank standing on its long edge or leaning on something cannot be picked from above: push its upper edge + over with the closed gripper so that it falls flat (towards the side with more free table)""" + if self.plank_flat() or self.held(PLANK): + return False + sk = self.sk + R, c = self.R(PLANK), self.pos(PLANK) + up = R[:, 1] if R[2, 1] > 0 else -R[:, 1] # the plank's width axis, pointing up + lean = up[:2] / max(np.linalg.norm(up[:2]), 1e-6) + if np.linalg.norm(up[:2]) < 0.2: # standing upright: fall to the side away from the squares + n = R[:2, 2] / max(np.linalg.norm(R[:2, 2]), 1e-6) + far = lambda d: min(np.linalg.norm(c[:2] + 0.05 * d - self.square_xy(q)) for q in SQUARES) # noqa: E731 + lean = n if far(n) > far(-n) else -n + push = lean + else: # leaning: push the top back over the vertical so it falls to the other side + push = -lean + top = c + up * 0.02 + h = max(self.zmax(PLANK) - 0.015, TZ + 0.02) + a = top[:2] - push * 0.05 + yaw = float(np.arctan2(push[1], push[0]) - np.pi / 2) # closed fingers across the push direction + sk.set_gripper(True, steps=8) + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + Z_SAFE]) + self._go([a[0], a[1], TZ + Z_SAFE], yaw=yaw) + self._go([a[0], a[1], h], speed=0.25) + b = top[:2] + push * 0.08 + self._go([b[0], b[1], h], speed=0.1, max_steps=200) + self._go([b[0], b[1], TZ + Z_SAFE], speed=0.3) + sk.set_gripper(False, steps=8) + sk.hold(10) + return True + + def clear_site(self): + """careful: before building, move the car out of the zone right behind the bridge line""" + if self.in_keep_out(CAR) and not self.held(CAR): + self.park(CAR) + + def repair(self, rounds=4): + """check every stage; rebuild what is broken (careful motions). Returns the number of fixes made.""" + nofn = lambda: None # noqa: E731 + fixes = 0 + for _ in range(rounds): + raw, (pa, pb) = self.stages() + if all(raw) or self.over_budget() or not (self.usable(PLANK) or self.held(PLANK)): + return fixes # (a plank thrown out of reach cannot be laid again) + fixes += 1 + if not (raw[0] and raw[1]): + for _k in range(2): + if not self.plank_flat(): + self.fix_plank() + plank_first = self._hand_clearance(self.pos(CAR)[:2], 0.0, self._grasp_z(CAR, True), + ignore=tuple(q for q in ITEMS if q != PLANK)) < 0.0 + for o in ((PLANK, CAR) if plank_first else (CAR, PLANK)): + if o == CAR and (self.zmin(CAR) > TZ + 0.01 or self._near_squares(CAR) or self.in_keep_out(CAR)): + self.park(CAR) + if o == PLANK and (self.zmin(PLANK) > TZ + 0.006 or self._near_squares(PLANK) + or self.in_keep_out(PLANK)): + self.park(PLANK) + for i, s in enumerate(SQUARES): + if not self.stages()[0][i]: + self.build_pillar(s, True, nofn) + raw, _ = self.stages() + if raw[0] and raw[1] and not raw[2]: + if not self.plank_flat(): + self.fix_plank() + if self.zmin(CAR) > TZ + 0.01 or self.in_keep_out(CAR): + self.park(CAR) + self.lay_plank(True, nofn) + raw, _ = self.stages() + if raw[2] and not raw[3]: + self.put_car(True, nofn) + return fixes + + def _near_squares(self, o): + p = self.pos(o)[:2] + if o == PLANK: + ax = self.R(PLANK)[:2, 0] + pts = [p + s * ax * 0.11 for s in (-1, -0.5, 0, 0.5, 1)] + else: + pts = [p] + return any(np.linalg.norm(q - self.square_xy(s)) < 0.06 for q in pts for s in SQUARES) + + # ------------------------------------------------------------ Sonnet-like naive (style "sonnet") + # Imitates how Claude Sonnet 5.5 moved in the lh1 pilot (runs/claude/lh1_bridge, 4 attempts, 230 commands): + # instruction order; for each pillar the free block nearest to its square first; a hover ~12 cm above the object + # with the gripper turned to the object's yaw, a straight vertical descent, grasp ~1 cm below the top; the carry + # often goes straight from the grasp to ~12.5 cm above the target (one move_eef: a diagonal climb), otherwise lift + # first; when the carried object's straight path would run into a built pillar it lifts first and carries with the + # object's bottom ~4 cm above that pillar; vertical descent, open, lift straight up to ~15 cm; plank: lift to 7 cm, + # carry at 16 cm; car: lift to 17 cm, carry, place, lift to 25 cm; no final check. + def _sn_grasp_z(self, o, sn): + if o == PLANK: + return self._grasp_z(PLANK, False) + return self.zmax(o) - sn["top_below"] + + def _crossing_top(self, a, b, o, drop, hc): + """top of the highest item that the held object o, carried straight from a to b with its bottom at hc - drop, + would run into (any footprint point within o's half size + 1 cm of the path), else None""" + a, b = np.asarray(a[:2], float), np.asarray(b[:2], float) + d = b - a + n2 = float(d @ d) + r = float(self.half(o)[0]) + 0.01 + best = None + for q in ITEMS: + if q == o or self.held(q): + continue + top = self.zmax(q) + if top < hc - drop: + continue + pts = self.footprint(q) + t = np.clip((pts - a) @ d / n2, 0.0, 1.0) if n2 > 1e-9 else np.zeros(len(pts)) + dist = float(np.min(np.linalg.norm(pts - (a + t[:, None] * d), axis=1))) + if dist < r and (best is None or top > best): + best = top + return best + + def sn_pick(self, o, sn, noise=None): + sk = self.sk + p = self.pos(o) + if noise is not None: + p = p + np.array([noise[0], noise[1], 0.0]) + zg = self._sn_grasp_z(o, sn) + if o == PLANK: + yaw = _wrap_h(self.yaw_of(PLANK)) + elif o == CAR and sn["car_style"] == "keep": + yaw = None # keeps the gripper's current yaw (the pilot's seed 3000: still turned 90 deg from the plank) + else: + yaw = _wrap_q(self.yaw_of(o)) + hover = TZ + (sn["car_hover"] if o == CAR else sn["hover"]) + direct = o == CAR and sn["car_style"] == "direct" # (the pilot's seed 3001 went straight down to the car) + if not direct: + self._go([p[0], p[1], hover], yaw=yaw) + self._go([p[0], p[1], zg], yaw=yaw, tol=0.003, max_steps=250 if direct else 120) + sk.set_gripper(True, steps=15) + if not sk.holding(o): + sk.set_gripper(False, steps=15) + self._go([p[0], p[1], TZ + sn["hover"]]) + return None + return float(sk.eef_pos()[2] - self.zmin(o)) + + def sn_place(self, o, xy, support_top, drop, yaw, sn, carry=None, lift=None, diag=None): + sk = self.sk + zr = support_top + drop + 0.004 + hc = max(TZ + (sn["carry"] if carry is None else carry), zr + 0.03) + cur = sk.eef_pos() + diag = sn["diag"] if diag is None else diag + top = None if o == PLANK else self._crossing_top(cur, xy, o, drop, hc) + if top is not None: # a built pillar in the way: lift first, carry with the object's bottom above it + hc = max(hc, top + drop + sn["cross_margin"]) + self._go([cur[0], cur[1], hc]) + self._go([xy[0], xy[1], hc], yaw=yaw) + elif diag: # one move_eef from the grasp to above the target + self._go([xy[0], xy[1], hc], yaw=yaw) + else: + self._go([cur[0], cur[1], max(cur[2], hc + 0.02)]) + self._go([xy[0], xy[1], hc], yaw=yaw) + self._go([xy[0], xy[1], zr], tol=0.003, max_steps=120) + sk.set_gripper(False, steps=15) + self._go([xy[0], xy[1], TZ + (sn["lift"] if lift is None else lift)]) + sk.hold(5) + + def sn_build_pillar(self, s, sn, noise_fn): + failed = {} + c = self.square_xy(s) + mid = self.bridge_mid() + for _ in range(5): + raw, (pa, pb) = self.stages() + low, up = (pa, pb)[SQUARES.index(s)] + if up is not None: + return True + other = (pa, pb)[1 - SQUARES.index(s)] + cand = [b for b in BLOCKS if b != low and b not in other and failed.get(b, 0) < 2] + if not cand: + return False + if sn["alloc"] == "side": # blocks on this square's side of the bridge first + side = np.sign(c[1] - mid[1]) + same = [b for b in cand if np.sign(self.pos(b)[1] - mid[1]) == side] + cand = same or cand + b = min(cand, key=lambda q: (failed.get(q, 0), np.linalg.norm(self.pos(q)[:2] - c))) + drop = self.sn_pick(b, sn, noise=noise_fn()) + if drop is None: + failed[b] = failed.get(b, 0) + 1 + continue + tgt, top = (c, TZ) if low is None else (self.pos(low)[:2], self.zmax(low)) + n = noise_fn() + # onto the bare square: straight from the grasp (diagonal climb); onto a block: lift first (a diagonal + # climb from nearby clips the lower block -- the pilot's seed 3000 did that once, then lifted first) + self.sn_place(b, tgt + (n if n is not None else 0.0), top, drop, 0.0, sn, + diag=None if low is None else False) + return self.stages()[1][SQUARES.index(s)][1] is not None + + def sn_lay_plank(self, sn, noise_fn): + raw, (pa, pb) = self.stages() + if pa[1] is None or pb[1] is None: + return False + drop = self.sn_pick(PLANK, sn, noise=noise_fn()) + if drop is None: + return False + cur = self.sk.eef_pos() + self._go([cur[0], cur[1], TZ + sn["plank_lift"]]) + raw, (pa, pb) = self.stages() + if pa[1] is None or pb[1] is None: + tops, mid = [TZ + 0.11, TZ + 0.11], self.bridge_mid() + else: + tops = [self.zmax(pa[1]), self.zmax(pb[1])] + mid = (self.pos(pa[1])[:2] + self.pos(pb[1])[:2]) / 2 + n = noise_fn() + mid = mid + (n if n is not None else 0.0) + self.sn_place(PLANK, mid, max(tops), drop, np.pi / 2, sn, carry=sn["plank_carry"], lift=sn["plank_end_lift"], + diag=True) + return True + + def sn_put_car(self, sn, noise_fn): + drop = self.sn_pick(CAR, sn, noise=noise_fn()) + if drop is None: # (in the pilot, Sonnet stopped here when it saw the bridge come down) + return False + n = noise_fn() + pp = self.pos(PLANK)[:2] + (n if n is not None else 0.0) + self.sn_place(CAR, pp, self.zmax(PLANK), drop, None, sn, carry=sn["car_lift"], lift=sn["end_lift"], + diag=False) + return True + + # ------------------------------------------------------------ execution + def execute(self, inst, params): + mode = params.get("mode", "naive") + careful = mode == "careful" + rng = np.random.default_rng(params.get("noise_seed", 0)) + sig = float(params.get("noise", 0.0)) + noise_fn = (lambda: rng.uniform(-sig, sig, 2)) if sig > 0 else (lambda: None) + z_t = params.get("z_t") + self.naive_lift = float(params.get("lift", NAIVE_LIFT)) + style = params.get("style", "sonnet") + if not careful and style == "sonnet": + sn = dict(SN) + sn.update(params.get("sn", {})) + if sn["car_style"] is None: + sn["car_style"] = CAR_STYLES[int(inst["seed"]) % 3] + for s in SQUARES: + self.sn_build_pillar(s, sn, noise_fn) + self.sn_lay_plank(sn, noise_fn) + self.sn_put_car(sn, noise_fn) + else: # careful, or the v1 naive ("legs": vertical / horizontal legs at 8 cm; "diag") + self.naive_style = style if style in ("legs", "diag") else NAIVE_STYLE + if careful: + self.clear_site() + for s in SQUARES: + self.build_pillar(s, careful, noise_fn, z_t=z_t, order=params.get("order", "target")) + self.lay_plank(careful, noise_fn, z_t=z_t) + self.put_car(careful, noise_fn, z_t=z_t) + if params.get("check"): + self.repair() + cur = self.sk.eef_pos() + if cur[2] < TZ + 0.20: + self._go([cur[0], cur[1], cur[2] + 0.06], speed=0.15) + + def default_params(self, inst): + return dict(mode="naive", style="sonnet", check=False) + + def oracle_params(self, inst): + return dict(mode="careful", check=True) + + def adapt_params(self, inst, history): + return dict(mode="careful", check=True) + + def blind_params(self, inst, attempt, rng): + sn = dict(hover=float(rng.uniform(0.10, 0.14)), carry=float(rng.uniform(0.11, 0.15)), + lift=float(rng.uniform(0.13, 0.20)), diag=bool(rng.random() < 0.5), + car_style=CAR_STYLES[int(rng.integers(3))], alloc="side" if rng.random() < 0.5 else "greedy") + return dict(mode="naive", style="sonnet", check=False, sn=sn, noise=0.004, noise_seed=int(rng.integers(1 << 30))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """kinds: oracle, naive (Sonnet-like, car approach style by seed), adaptive, blind; for comparison naive_v1 (the + v1 naive: vertical / horizontal legs at 8 cm) and naive_hover / naive_keep / naive_direct (Sonnet-like with + one fixed car approach style)""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "naive_v1": + params = dict(mode="naive", style="legs", check=False) + elif kind.startswith("naive_") and kind[6:] in CAR_STYLES: # naive_hover / naive_keep / naive_direct + params = dict(mode="naive", style="sonnet", check=False, sn=dict(car_style=kind[6:])) + elif kind == "adaptive": + params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind == "oracle" or kind.startswith("naive"): + break + return history diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_bystander.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_bystander.py new file mode 100644 index 0000000000000000000000000000000000000000..d29e80c05aadc9cd8aa5e69c81d724f4cd45d971 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_bystander.py @@ -0,0 +1,830 @@ +"""LH bystander: put three cubes into an open box while a tall glass bottle that is not part of the task stands right +in front of the box -- lowering a cube into the box, the robot's own forearm comes down onto the bottle and knocks it +over. + +Family: long-horizon self-disturbance, environment level ("state_restoration"; LIBERO-Recover's damage category L4: the +damaged thing is not part of the task). Three easy pick-and-place stages; the instruction says plainly that nothing +else may be moved and that the bottle must be left standing where it is. The agent has to notice the fallen bottle and +stand it up again on its spot before finishing (within an attempt), or learn to keep its arm off the bottle (across +attempts). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * an open wooden box (fixture): cavity 14 x 14 cm, walls 6 cm high (rim 6.6 cm above the table), 0.8 cm thick; + centre x in [0.00, 0.04], 6-10 cm left or right of the middle; + * three 4 cm cubes (red / yellow / blue, 32 g) in a row beside the box on the other side (19-23 cm from the middle, + from 10 cm behind to 2 cm in front of the box centre, shuffled, yaw +-17 deg), so that a straight carry to the box + never passes over the bottle; + * the bystander: a square green glass bottle with a label and a round red cap, 28.4 cm tall (body 6 x 6 x 18.5 cm, + shoulder, neck, cap; a rounded base whose flat contact is 3.6 x 3.6 cm), 0.25 kg, centre of mass 12 cm up (an empty + bottle: it tips beyond 8.5 deg; pressed down on its cap, beyond 3.7 deg). + +Instance variable (where the bottle stands): "hazard" (15 of every 20 consecutive seeds): right in front of the box, +between the box and the robot, 1.0-2.5 cm from its front wall, 1 cm right to 4 cm left of its centre line; "benign": +beside the box on its outer side, 8-11 cm from the wall. Both look like "a bottle standing next to the box"; nothing in +the physics is hidden. What the agent cannot see before acting is its own arm: the wrist camera shows the fingers, not +the forearm, and the agent steers the grasp point. + +Disturbance (physics, no teleport): lowering a cube onto the box floor (grasp point ~4 cm above the table), the +fingers and the cube stay 3-5 cm clear of the bottle (the box's front wall is between them), but the Panda's forearm +and wrist (links 5-7) slope back from the hand towards the robot base, starting ~12 cm above the grasp point; over the +space in front of the box they come down to 15-20 cm above the table, onto the upper part of a 28 cm bottle standing +there. The bottle is pushed over (mostly +towards the robot) and lies on the table in front of the box; visible in agentview once the arm has moved away +(measured, task card). Not every contact knocks it: a descent can come to rest on the cap (pinched between links 5 +and 6, pressed down like a column), the arm stalls 4-6 cm short of its target and the bottle rocks back when the arm +lifts (measured: the smoke-test sequence on seed 3000; 6-7 of 8 hazard seeds still knocked with slow or near-first +descents, see the task card). The hit is yaw-independent (hit maps at yaw 0 / 45 / 90 deg) and not caused by the hand's +width. Transits at the agent's usual 11-20 cm mostly pass (the wrist end of the forearm is ~27 cm up at a 15 cm +transit). A careful packer keeps its arm above the bottle: carry at >= 24 cm and release the cube from >= 18 cm +(dropping it into the box) -- or moves the bottle out of the way and back, which the final-state judge would accept +but the instruction rules out. + +Restoring (re-standable by a top-down gripper that only turns about the vertical): the body is square (a lying bottle +does not roll away from the closing fingers) and the cap is a ball with low torsional friction: grasped from above with +the fingers across the lying bottle's axis, the cap turns between the fingers, the lifted bottle swings down and hangs +straight; lowered onto the table it stands (measured: placement error ~1 mm). The instruction tells the agent that the +bottle hangs straight down when held by its cap (as lh_fence does for its knobs). + +Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (every cube in the +box -- footprint inside the cavity, top below the rim, not held --, the bottle upright within 10 deg and its base +within 2 cm of where it stood, nothing held or touched, scene static) plus a per-step event log for the server log: +cube stages achieved / lost / restored; bottle_in_place lost / restored (with cause: arm / hand / cube, the robot geom, +the grasp point) plus the marker events bystander_knocked / bystander_restored / fallen. F1 gives the agent only +success / failure. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, _wrap, box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +Z = envs.TABLE_Z +# ---------------------------------------------------------------- geometry / physics +BOX = "box_1" +BOX_MODEL = "lff_lhb_box" +BOX_IN = 0.070 # cavity half width (14 x 14 cm) +WALL_T, FLOOR_T, WALL_H = 0.008, 0.006, 0.060 +BOX_OUT = BOX_IN + WALL_T +RIM = FLOOR_T + WALL_H # rim height above the table +WOOD = (0.62, 0.45, 0.28, 1.0) + +CUBES = ("red_cube_1", "yellow_cube_1", "blue_cube_1") +CUBE_COLOR = {"red_cube_1": "red", "yellow_cube_1": "yellow", "blue_cube_1": "blue"} +CUBE_RGBA = dict(red=(0.85, 0.10, 0.08, 1.0), yellow=(0.92, 0.76, 0.10, 1.0), blue=(0.15, 0.30, 0.85, 1.0)) +CUBE_E = 0.040 +CUBE_DENS = 500.0 # 32 g +CUBE_MU = 0.8 + +BOTTLE = "bottle_1" +BOTTLE_MODEL = "lff_lhb_bottle" +BOTTLE_CLASS = "LffLhbBottle" +RB, HB = 0.030, 0.185 # square body: half width, height +RF, HF = 0.018, 0.006 # foot: a rounded glass base whose flat contact is 3.6 x 3.6 cm (0.6 cm high inset). With the +# 4.8 cm foot of the draft the forearm could come to rest on the cap and stall instead of +# knocking it (bottle pressed down like a column, tilt <= 5 deg; measured, see the task card) +RS, HS = 0.022, 0.015 # shoulder +RN, HN = 0.0115, 0.060 # neck +RK = 0.015 # ball cap radius; its centre sits RK - 6 mm above the neck top +CAP_SINK = 0.006 +H_TOT = HB + HS + HN + 2 * RK - CAP_SINK # 0.284 +CAP_Z = H_TOT - RK # cap centre above the bottle's bottom when standing +BOTTLE_MASS = 0.25 +BOTTLE_COM = 0.12 # above the bottom (an empty glass bottle: ~42 % of its height) +BOTTLE_MU = 0.6 +CAP_MU_T = 0.0005 # torsional friction of the cap (condim 4): the grasped cap turns freely, the swing is damped +GLASS = (0.16, 0.42, 0.26, 1.0) +CAP_RGBA = (0.78, 0.12, 0.10, 1.0) + +# instances +P_HAZARD = 0.75 # 15 of every 20 consecutive seeds: bottle in front of the box +HAZ_GAP = (0.010, 0.025) # bottle body to the box's front wall +HAZ_LAT = (-0.010, 0.040) # bottle centre left (+y) of the box's centre line +BEN_GAP = (0.080, 0.110) # beside the box, on its outer side (away from the cubes) +BEN_DX = (-0.030, 0.030) +BOX_X = (0.0, 0.04) # the bottle in front of the box stays >= 2 cm clear of the fingers in the home pose +BOX_Y = (0.06, 0.10) # |y| of the box centre; the side is random +CUBE_Y = (0.19, 0.23) # |y| of the cube row (other side) +CUBE_DX = (-0.10, -0.04, 0.02) # cube row beside the box (x relative to the box centre; the Panda reaches ~0.8 m): +# the straight carry to the box passes >= 2 cm from the bottle in front of it + +# success predicate +POS_TOL = 0.020 # bottle base within 2 cm of where it stood +UPRIGHT = np.radians(10.0) +KNOCK_TILT = np.radians(10.0) # once in place, the bottle counts as disturbed when tilted beyond this (it tips at +# 8.5 deg: beyond, it is falling or leaning on something) or moved +POS_HYST = 0.003 # > POS_TOL + POS_HYST for DEBOUNCE checks (a nudge that rocks back within 0.6 s is no loss) +FALLEN = np.radians(60.0) +IN_TOL = 0.002 # a cube's footprint may reach this far past the inner walls +RIM_TOL = 0.004 +BELOW_RIM = 0.010 # in_box: the cube's lowest point at least this far below the rim +DEBOUNCE = 6 # predicate checks (every 0.1 s) a change must persist + +# scripted motion (heights of the grasp point above the table) +Z_CARRY = 0.15 # Sonnet's transit: 11-20 cm, often lifted to ~20 before moving +Z_REL = 0.040 # Sonnet-like release: cube set down on the box floor (grasp point 4 cm up) +Z_SAFE = 0.26 # careful transit +Z_DROP = 0.19 # careful release: the cube is dropped from above the rim, the forearm stays above the bottle +NAIVE_ERR = 0.008 # Sonnet's placement error 0.4-1.3 cm +SLOT = 0.033 # slot offset from the box centre (cavity 14 cm, cubes 4 cm) + + +def bottle_xml(name): + h = H_TOT / 2 + zf, zb, zs, zn = -h + HF / 2, -h + HF + (HB - HF) / 2, -h + HB + HS / 2, -h + HB + HS + HN / 2 + zk = -h + HB + HS + HN + RK - CAP_SINK + m = BOTTLE_MASS + ixx = m * ((2 * RB) ** 2 + H_TOT ** 2) / 16 # rough: most of the glass is in the body and the base + izz = m * (2 * (2 * RB) ** 2) / 12 + parts = [("foot", "box", (0, 0, zf), (RF, RF, HF / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'), + ("body", "box", (0, 0, zb), (RB, RB, (HB - HF) / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'), + ("shoulder", "box", (0, 0, zs), (RS, RS, HS / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'), + ("neck", "cylinder", (0, 0, zn), (RN, HN / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'), + ("cap", "sphere", (0, 0, zk), (RK,), CAP_RGBA, f'friction="1 {CAP_MU_T} 0.0001" condim="4" priority="2"')] + s = [f' '] + for nm, typ, pos, size, c, extra in parts: + s.append(f' ') + s.append(f' ') + # a lighter label band (visual only) so the bottle reads as a bottle + s.append(f' ') + return _wrap(name, "\n".join(s), h, RB * 1.42) + + +def box_fixture_xml(name): + """open wooden box, origin at the centre of its footprint, z = 0 at the table""" + ix = BOX_IN + parts = [((0, 0, FLOOR_T / 2), (BOX_OUT, BOX_OUT, FLOOR_T / 2)), + ((ix + WALL_T / 2, 0, RIM / 2), (WALL_T / 2, BOX_OUT, RIM / 2)), + ((-ix - WALL_T / 2, 0, RIM / 2), (WALL_T / 2, BOX_OUT, RIM / 2)), + ((0, ix + WALL_T / 2, RIM / 2), (ix, WALL_T / 2, RIM / 2)), + ((0, -ix - WALL_T / 2, RIM / 2), (ix, WALL_T / 2, RIM / 2))] + g = [] + for k, (p, sz) in enumerate(parts): + g.append(f' ') + g.append(f' ') + return f""" + + + +{chr(10).join(g)} + + + + + + +""" + + +REACH_MAX = 0.74 # scripted policies: farthest grasp point (horizontal distance from the robot base) they rely on + + +def _reach(p): + return float(np.hypot(p[0] + 0.66, p[1])) + + +def _fb(v): + return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}" + + +def _lr(v): + return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}" + + +class BystanderSkills(Skills): + """Skills that feed the task's per-step monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class Bystander(LFFTask): + name = "lh_bystander" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Restore", "Plan") + protocol = "cross" + max_attempts = 3 + agent_max_steps = 100 # careful: 3 cubes x ~7 commands + looking; standing the bottle up again ~8-10; + slack + instruction = ("Put the red, yellow and blue cubes into the open wooden box. Do not move anything else: the tall " + "glass bottle must be left standing upright exactly where it is now. (The bottle has a round red " + "cap; held by its cap, the bottle hangs straight down.)") + instruction_indirect = ("Pack the three small cubes (red, yellow, blue) into the wooden crate. Leave everything else " + "as it is -- the tall green bottle has to stay standing on its spot. (Its round red cap: held " + "by the cap, the bottle hangs straight down.)") + agent_object_names = ["red cube", "yellow cube", "blue cube", "open wooden box", + "tall glass bottle (square, with a round red cap; held by its cap it hangs straight down)"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + box = register_generated("LffLhbBox", box_fixture_xml(BOX_MODEL), free=False) + objs = [] + for i, n in enumerate(CUBES): + c = CUBE_COLOR[n] + cat = register_generated(f"LffLhbCube{c.title()}", + box_xml(f"lff_lhb_cube_{c}", (CUBE_E / 2,) * 3, CUBE_RGBA[c], density=CUBE_DENS, + friction=(CUBE_MU, 0.005, 0.0001)).replace(_SOLID, "")) + objs.append((n, cat, f"{c}_cube_region", (-0.35, -0.25 + 0.15 * i, -0.33, -0.23 + 0.15 * i))) + bt = register_generated(BOTTLE_CLASS, bottle_xml(BOTTLE_MODEL)) + objs.append((BOTTLE, bt, "bottle_region", (-0.35, 0.24, -0.33, 0.26))) + fx = [(BOX, box, "box_region", (-0.06, -0.01, -0.04, 0.01))] + return write_bddl(self.name, "put the cubes into the box and leave the bottle where it is", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.box_bid = m.body_name2id(self.env.fixtures_dict[BOX].root_body) + self.box_gids = {g for g in range(m.ngeom) if m.geom_bodyid[g] in + {self.box_bid} | {c for c in range(m.nbody) if m.body_parentid[c] == self.box_bid}} + pre = f"{BOTTLE}_{BOTTLE_MODEL}" + self.cap_gid = m.geom_name2id(pre + "_cap") + self.bottle_gids = set(envs.obj_geom_ids(self.env, BOTTLE)) + self.cube_gids = {n: set(envs.obj_geom_ids(self.env, n)) for n in CUBES} + # robot parts: 1 = hand / fingers (what the agent sees and steers), 2 = arm links (wrist, forearm, ...) + self.part = np.zeros(m.ngeom, int) + for g in envs.robot_geom_ids(self.env): + n = m.geom_id2name(g) or "" + self.part[g] = 1 if n.startswith("gripper0_") else 2 + self.other = np.zeros(m.ngeom, int) # 3 = a cube, 4 = the box + for n in CUBES: + self.other[list(self.cube_gids[n])] = 3 + self.other[list(self.box_gids)] = 4 + self.is_bottle = np.zeros(m.ngeom, bool) + self.is_bottle[list(self.bottle_gids)] = True + # bottle contacts are collected after every MuJoCo substep (a fast hit can be shorter than a control step) + sim = self.env.sim + if not getattr(sim, "_lhb_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lhb_task", None) + if t is not None and t.mon is not None: + t._substep() + sim.step = step + sim._lhb_wrapped = True + sim._lhb_task = self + self._sub = {} + self.inst = None + self.mon = None + self.sk = None + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + s = 1.0 if rng.random() < 0.5 else -1.0 # box on the left (+1) or right (-1) + bx, by = float(rng.uniform(*BOX_X)), s * float(rng.uniform(*BOX_Y)) + # balanced blocks like lh_lid_box: exactly round(20 * P_HAZARD) of every 20 consecutive seeds are hazards + hazard = bool((int(seed) * 7) % 20 < round(20 * P_HAZARD)) + if hazard: + gap, lat = float(rng.uniform(*HAZ_GAP)), float(rng.uniform(*HAZ_LAT)) + bottle = [bx - BOX_OUT - gap - RB, by + lat] + else: + gap, lat = float(rng.uniform(*BEN_GAP)), float(rng.uniform(*BEN_DX)) + bottle = [bx + lat, by + s * (BOX_OUT + gap + RB)] + cy = -s * float(rng.uniform(*CUBE_Y)) + perm = rng.permutation(len(CUBES)) + start = {CUBES[i]: [float(bx + CUBE_DX[j] + rng.uniform(-0.01, 0.01)), float(cy + rng.uniform(-0.01, 0.01))] + for j, i in enumerate(perm)} + start_yaw = {n: float(rng.uniform(-0.3, 0.3)) for n in CUBES} + return dict(seed=int(seed), hazard=hazard, bottle_side="front" if hazard else "outer side", + box_side="left" if s > 0 else "right", box_xy=[bx, by], bottle_xy=[float(bottle[0]), float(bottle[1])], + bottle_yaw=float(rng.uniform(-0.25, 0.25)), gap=gap, lat=lat, start=start, start_yaw=start_yaw) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + bx, by = inst["box_xy"] + m.body_pos[self.box_bid] = [bx, by, Z] + m.body_quat[self.box_bid] = [1.0, 0.0, 0.0, 0.0] + for n, xy in inst["start"].items(): + envs.place_upright(self.env, n, xy, yaw=inst["start_yaw"][n], clearance=0.001) + envs.set_friction(self.env, n, CUBE_MU) + envs.place_upright(self.env, BOTTLE, inst["bottle_xy"], yaw=inst["bottle_yaw"], clearance=0.001) + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = BystanderSkills(self.env, self, recorder=recorder) + self._sub = {} + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ state helpers + def R(self, name): + return self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3).copy() + + def bottle_tilt(self): + return float(np.arccos(np.clip(self.R(BOTTLE)[2, 2], -1.0, 1.0))) + + def bottle_base(self): + """xy of the centre of the bottle's bottom face""" + d = self.env.sim.data + return (envs.obj_pos(self.env, BOTTLE) - self.R(BOTTLE)[:, 2] * H_TOT / 2)[:2] + + def bottle_offset(self): + return self.bottle_base() - np.asarray(self.inst["bottle_xy"]) + + def cap_xyz(self): + return self.env.sim.data.geom_xpos[self.cap_gid].copy() + + def held(self, name): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name])) + + def bottle_in_place(self, tol=POS_TOL, tilt=UPRIGHT): + return bool(self.bottle_tilt() <= tilt and np.linalg.norm(self.bottle_offset()) <= tol + and envs.obj_min_z(self.env, BOTTLE) < Z + 0.01 and not self.held(BOTTLE)) + + def to_box(self, xy): + return np.asarray(xy, float)[:2] - np.asarray(self.inst["box_xy"]) + + def in_box(self, name): + m, d = self.env.sim.model, self.env.sim.data + g = next(iter(self.cube_gids[name])) + Rg = d.geom_xmat[g].reshape(3, 3) + c = self.to_box(d.geom_xpos[g][:2]) + ext = np.abs(Rg[:2, :]) @ m.geom_size[g][:3] + # 10-14: "in the box" = footprint inside the cavity and the cube's lowest point well below the rim (it is held + # by the walls); a cube stacked on another one may stick out above the rim -- the instruction never asks for + # "below the rim" (two Sonnet pilot attempts that stacked the last cube were judged failures before this) + return bool(np.all(np.abs(c) + ext <= BOX_IN + IN_TOL) and envs.obj_min_z(self.env, name) <= Z + RIM - BELOW_RIM + and not self.held(name)) + + def over_box(self, name): + c = self.to_box(envs.obj_pos(self.env, name)[:2]) + return bool(np.all(np.abs(c) <= BOX_OUT)) + + def stage_values(self): + v = {f"{CUBE_COLOR[n]}_in_box": self.in_box(n) for n in CUBES} + v["bottle_in_place"] = self.bottle_in_place() + return v + + # ------------------------------------------------------------ per-step monitor + def _init_monitor(self): + keys = [f"{CUBE_COLOR[n]}_in_box" for n in CUBES] + ["bottle_in_place"] + st = {k: False for k in keys} + st["bottle_in_place"] = self.bottle_in_place() + self.mon = dict(state=st, ever=[k for k in keys if st[k]], lost=[], events=[], cand={k: 0 for k in keys}, + step=0, last_touch=None, robot_touch_step=-10 ** 9, touch_parts=[], n_knocks=0, n_fallen=0, + fallen=False, + max_tilt_deg=0.0, max_offset_cm=0.0, first_knock_step=None, first_touch_step=None) + + def _substep(self): + d = self.env.sim.data + n = d.ncon + if not n: + return + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + b1, b2 = self.is_bottle[g1], self.is_bottle[g2] + sel = b1 ^ b2 + if not sel.any(): + return + other = np.where(b1, g2, g1)[sel] + for o in other: + p = int(self.part[o]) + if p: + who = "hand" if p == 1 else "arm" + prev = self._sub.get("robot") + self._sub["robot"] = "arm" if (who == "arm" or prev == "arm") else "hand" + self._sub.setdefault("geom", self.env.sim.model.geom_id2name(int(o))) + elif self.other[o] == 3: + self._sub["cube"] = True + + def monitor_step(self): + mon = self.mon + if mon is None: + return + mon["step"] += 1 + step = self.sk.n_steps if self.sk is not None else mon["step"] + sub, self._sub = self._sub, {} + if "robot" in sub: + mon["robot_touch_step"] = step + mon["last_touch"] = [sub["robot"], step, sub.get("geom", "")] + if sub["robot"] not in mon["touch_parts"]: + mon["touch_parts"].append(sub["robot"]) + if mon["first_touch_step"] is None: + mon["first_touch_step"] = step + elif sub.get("cube") and (mon["last_touch"] is None or step - mon["last_touch"][1] > 20): + mon["last_touch"] = ["cube", step, ""] + tilt = self.bottle_tilt() + mon["max_tilt_deg"] = round(max(mon["max_tilt_deg"], float(np.degrees(tilt))), 1) + mon["max_offset_cm"] = round(max(mon["max_offset_cm"], 100 * float(np.linalg.norm(self.bottle_offset()))), 1) + if mon["step"] % 2: + return # predicates every other control step (0.1 s) + if not mon["fallen"] and tilt > FALLEN and not self.held(BOTTLE): + mon["fallen"] = True + mon["n_fallen"] += 1 + mon["events"].append(dict(step=step, pred="bottle", ev="fallen", cause=self._cause(step))) + elif mon["fallen"] and tilt < UPRIGHT: + mon["fallen"] = False + for n in CUBES: + self._check(f"{CUBE_COLOR[n]}_in_box", self.in_box(n), step, n) + st = mon["state"]["bottle_in_place"] + # hysteresis: once in place it counts as lost only beyond 2.3 cm / 10 deg, held for 0.6 s (a nudge that rocks + # back is no loss) + now = self.bottle_in_place(POS_TOL + POS_HYST, KNOCK_TILT) if st else self.bottle_in_place() + self._check("bottle_in_place", now, step, BOTTLE) + + def _cause(self, step): + lt = self.mon["last_touch"] + if lt is not None and step - lt[1] <= 60: + return lt[0] + return "other" + + def _check(self, key, now, step, name): + mon = self.mon + if now == mon["state"][key]: + mon["cand"][key] = 0 + return + if name == BOTTLE and not now and step - mon["robot_touch_step"] <= 6 and not self.held(BOTTLE): + # the arm is still pressing on the bottle (measured: a slow descent can come to rest on its cap and stall, + # tilting it ~12 deg; it rocks back when the arm lifts): a loss only once the robot has let go of it + mon["cand"][key] = 0 + return + mon["cand"][key] += 1 + if mon["cand"][key] < DEBOUNCE: + return + mon["cand"][key] = 0 + mon["state"][key] = now + if now: + restored = key in mon["lost"] + ev = "restored" if restored else "achieved" + if key not in mon["ever"]: + mon["ever"].append(key) + if restored: + mon["lost"].remove(key) + mon["events"].append(dict(step=step, pred=key, ev=ev)) + if key == "bottle_in_place" and restored: + mon["events"].append(dict(step=step, pred="bottle", ev="bystander_restored", + offset_cm=(100 * self.bottle_offset()).round(1).tolist())) + return + if key not in mon["ever"]: + return + cause = "picked_up" if self.held(name) else self._cause(step) + if key not in mon["lost"]: + mon["lost"].append(key) + e = dict(step=step, pred=key, ev="lost", cause=cause) + if name == BOTTLE: + ee = self.sk.eef_pos() if self.sk is not None else np.zeros(3) + e["eef_cm"] = [round(100 * float(v), 1) for v in (ee[0] - self.inst["box_xy"][0], ee[1] - self.inst["box_xy"][1], + ee[2] - Z)] # grasp point rel. to the box centre / table + e.update(tilt_deg=round(float(np.degrees(self.bottle_tilt())), 1), + offset_cm=(100 * self.bottle_offset()).round(1).tolist()) + if mon["last_touch"] is not None and mon["last_touch"][0] in ("arm", "hand"): + e["robot_geom"] = mon["last_touch"][2] + mon["events"].append(e) + if name == BOTTLE and cause != "picked_up": + mon["n_knocks"] += 1 + if mon["first_knock_step"] is None: + mon["first_knock_step"] = step + mon["events"].append(dict(step=step, pred="bottle", ev="bystander_knocked", cause=cause, + robot_geom=e.get("robot_geom", ""), tilt_deg=e["tilt_deg"], + offset_cm=e["offset_cm"], eef_cm=e["eef_cm"])) + + # ------------------------------------------------------------ outcome + def _static(self): + d = self.env.sim.data + for n in CUBES + (BOTTLE,): + _, da = envs.free_joint_addr(self.env, n) + if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5: + return False + return True + + def robot_touching(self): + d = self.env.sim.data + out = [] + for i in range(d.ncon): + c = d.contact[i] + for a, b in ((c.geom1, c.geom2), (c.geom2, c.geom1)): + if self.part[a] and (self.is_bottle[b] or self.other[b] == 3): + nm = "bottle" if self.is_bottle[b] else "a cube" + if nm not in out: + out.append(nm) + return out + + def outcome(self, inst): + envs.settle(self.env, 30) + mon = self.mon + vals = self.stage_values() + static = self._static() + held = [n for n in CUBES + (BOTTLE,) if self.held(n)] + touching = self.robot_touching() + success = bool(all(vals.values()) and static and not held and not touching) + evs = mon["events"] + regress = [e for e in evs if e["ev"] == "lost"] + restored = [e for e in evs if e["ev"] == "restored"] + knocks = [e for e in evs if e["ev"] == "bystander_knocked"] + # trap fired: a knock was logged, or the bottle ends up out of place after the robot touched it (a slow push + # to just over 2 cm can stay inside the monitor's hysteresis band) + trap_fired = bool(knocks) or (not vals["bottle_in_place"] and not self.held(BOTTLE) and bool(mon["touch_parts"])) + recovered = bool(trap_fired and vals["bottle_in_place"]) + off = self.bottle_offset() + tilt = float(np.degrees(self.bottle_tilt())) + parts = [] + failure = None + if success: + parts.append("All three cubes are in the box and the bottle stands where it stood.") + else: + out_cubes = [n for n in CUBES if not vals[f"{CUBE_COLOR[n]}_in_box"]] + if not vals["bottle_in_place"]: + failure = ("bystander_held" if self.held(BOTTLE) else + "bystander_knocked" if tilt > np.degrees(UPRIGHT) else "bystander_moved") + elif held: + failure = "held" + elif out_cubes: + failure = "cube_not_in_box" + elif touching: + failure = "robot_touching" + else: + failure = "not_static" + if not vals["bottle_in_place"]: + if self.held(BOTTLE): + parts.append("The bottle is still held by the gripper.") + else: + pose = ("is lying on its side" if tilt > 60 else f"is tilted {tilt:.0f} degrees" if tilt > np.degrees(UPRIGHT) + else "stands upright") + txt = f"The bottle {pose}; its base is {_fb(off[0])} and {_lr(off[1])} of where it stood" + if knocks: + k = knocks[0] + who = {"arm": "the robot's arm (above the gripper)", "hand": "the gripper", + "cube": "a cube"}.get(k["cause"], "something") + txt += f" (it was knocked by {who}" + txt += " and stood up again later, but not back in place)." if restored and any( + e["pred"] == "bottle_in_place" for e in restored) else ")." + else: + txt += "." + parts.append(txt) + for n in out_cubes: + c = CUBE_COLOR[n] + if self.held(n): + parts.append(f"The {c} cube is still held by the gripper.") + elif self.over_box(n): + parts.append(f"The {c} cube rests on the box's rim instead of inside the box.") + else: + rel = self.to_box(envs.obj_pos(self.env, n)[:2]) + parts.append(f"The {c} cube is not in the box: its centre is {_fb(rel[0])} and {_lr(rel[1])} of the " + f"box's centre.") + if touching and all(vals.values()): + parts.append("The robot was still touching " + " and ".join(touching) + " at the end.") + if not static and all(vals.values()): + parts.append("Something was still moving at the end.") + if trap_fired and vals["bottle_in_place"]: + parts.append(f"(The bottle was knocked out of place {len(knocks)} time(s) during the attempt and put back.)") + out = dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, touching=touching, + events=evs, n_regressions=len(regress), n_restored=len(restored), trap_fired=trap_fired, + recovered_in_attempt=recovered, n_knocks=len(knocks), n_fallen=mon["n_fallen"], + knock_causes=[k["cause"] for k in knocks], first_knock_step=mon["first_knock_step"], + bottle_touch_parts=list(mon["touch_parts"]), bottle_max_tilt_deg=mon["max_tilt_deg"], + bottle_max_offset_cm=mon["max_offset_cm"], bottle_tilt_deg=round(tilt, 1), + bottle_offset_cm=(100 * off).round(1).tolist(), hazard=bool(inst["hazard"]), + detail=" ".join(parts)) + return out + + # ------------------------------------------------------------ scripted primitives (perfect perception) + def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300): + return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + + def _settle(self, name, max_checks=25): + d = self.env.sim.data + _, da = envs.free_joint_addr(self.env, name) + for _ in range(max_checks): + if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2: + return + self.sk.hold(2) + + def _cube_yaw(self, name): + R = self.R(name) + i = int(np.argmin(np.abs(R[2]))) + yaw = float(np.arctan2(R[1, i], R[0, i])) + y = float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4) + cands = [y + k * np.pi / 2 for k in (-1, 0, 1)] + return min(cands, key=lambda c: abs(c - self.sk.yaw) if abs(c) <= np.pi / 2 else 9.0) + + def pick(self, name, z_carry, v=0.15, tries=2): + """Sonnet-like top-down pick: over the cube at carry height, down at 0.1 to 1.5 cm above, last 1.5 cm at 0.04, + close, lift to carry height""" + sk = self.sk + for _ in range(tries): + self._settle(name) + p = envs.obj_pos(self.env, name) + zg = p[2] - Z + yaw = self._cube_yaw(name) + sk.set_gripper(False, steps=8) + self._go([p[0], p[1], Z + max(z_carry, zg + 0.06)], yaw=yaw, speed=v) + self._go([p[0], p[1], Z + zg + 0.015], speed=0.1) + self._go([p[0], p[1], Z + zg], speed=0.04, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + self._go([p[0], p[1], Z + z_carry], speed=v) + if self.held(name): + return True + sk.set_gripper(False, steps=8) + return False + + def put(self, xy, z_rel, z_carry, v=0.15, v_down=None): + """carry over xy at carry height, straight down (0.1 m/s, last 1.5 cm at 0.03; or one move at v_down), open, + back up""" + sk = self.sk + self._go([xy[0], xy[1], Z + z_carry], speed=v) + if z_rel < z_carry - 0.02 and v_down: + self._go([xy[0], xy[1], Z + z_rel], speed=v_down, tol=0.003, max_steps=250) + elif z_rel < z_carry - 0.02: + self._go([xy[0], xy[1], Z + z_rel + 0.015], speed=0.1) + self._go([xy[0], xy[1], Z + z_rel], speed=0.03, tol=0.003, max_steps=150) + sk.set_gripper(False, steps=12) + self._go([xy[0], xy[1], Z + z_carry], speed=v) + sk.hold(5) + + def slot_xy(self, k, order): + """slot k of the scripted packing pattern, in world xy (box frame: u forward, v left)""" + u, v = order[k] + return np.asarray(self.inst["box_xy"]) + np.array([u, v]) * SLOT + + def put_cube(self, name, k, order, z_rel, z_carry, noise=None, v=0.15, v_down=None): + if not self.pick(name, z_carry, v=v): + return False + xy = self.slot_xy(k, order) + (np.asarray(noise, float) if noise is not None else 0.0) + self.put(xy, z_rel, z_carry, v=v, v_down=v_down) + self._settle(name) + return True + + def restand_bottle(self, z_carry=None): + """stand the bottle up again on its spot: grasp the ball cap from above (fingers across the lying bottle's + axis), lift until it hangs free, carry it over its spot, lower until the bottom is ~2 mm above the table, let + go. Returns True if it is back in place.""" + sk = self.sk + self._settle(BOTTLE) + for _ in range(2): + if _reach(self.cap_xyz()) > REACH_MAX and self.bottle_tilt() > FALLEN: + self.pull_in_bottle() + k = self.cap_xyz() + ax = self.R(BOTTLE)[:2, 2] + yaw = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else sk.yaw # finger axis across it + sk.set_gripper(False, steps=8) + cur = sk.eef_pos() + self._go([cur[0], cur[1], max(cur[2], Z + 0.15)], speed=0.15) + self._go([k[0], k[1], max(k[2] + 0.08, Z + 0.15)], yaw=yaw, speed=0.15) + sk.hold(5) + k = self.cap_xyz() + self._go([k[0], k[1], k[2] + 0.015], speed=0.1) + self._go([k[0], k[1], k[2]], speed=0.04, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + if not self.held(BOTTLE): + sk.set_gripper(False, steps=8) + self._go([k[0], k[1], k[2] + 0.08], speed=0.1) + continue + zl = Z + CAP_Z + 0.06 + self._go([k[0], k[1], zl], speed=0.10) + sk.hold(15) + tx, ty = self.inst["bottle_xy"] + self._go([tx, ty, zl], speed=0.10) + sk.hold(25) + self._go([tx, ty, Z + CAP_Z + 0.015], speed=0.08) + self._go([tx, ty, Z + CAP_Z + 0.002], speed=0.03, tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + self._go([tx, ty, Z + CAP_Z + 0.06], speed=0.08) + sk.hold(20) + self._settle(BOTTLE) + if self.bottle_in_place(): + return True + return self.bottle_in_place() + + def pull_in_bottle(self): + """the lying bottle's cap is out of reach (it fell forward over the box): grasp the body near its bottom end + (fingers across it), lift it 3 cm, pull it towards the robot until the cap is within reach, set it down""" + sk = self.sk + Rb = self.R(BOTTLE) + ax = Rb[:, 2] + c = envs.obj_pos(self.env, BOTTLE) + g = c - ax * (H_TOT / 2 - 0.05) # 5 cm from the bottom end along the axis + zg = max(float(g[2] - Z), 0.02) + yaw = float(np.arctan2(ax[1], ax[0])) + need = _reach(self.cap_xyz()) - (REACH_MAX - 0.05) + to_base = np.array([-0.66, 0.0]) - g[:2] + to_base /= max(np.linalg.norm(to_base), 1e-6) + dst = g[:2] + to_base * need + sk.set_gripper(False, steps=8) + self._go([g[0], g[1], Z + 0.15], yaw=yaw, speed=0.15) + self._go([g[0], g[1], Z + zg + 0.015], speed=0.1) + self._go([g[0], g[1], Z + zg], speed=0.04, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + self._go([g[0], g[1], Z + zg + 0.03], speed=0.08) + self._go([dst[0], dst[1], Z + zg + 0.03], speed=0.08) + self._go([dst[0], dst[1], Z + zg + 0.005], speed=0.04) + sk.set_gripper(False, steps=12) + self._go([dst[0], dst[1], Z + 0.15], speed=0.1) + self._settle(BOTTLE) + + def _fallen_cubes(self, done): + return [n for n in done if not self.in_box(n) and not self.over_box(n) and not self.held(n)] + + # ------------------------------------------------------------ scripted policies + def execute(self, inst, params): + careful = params.get("careful", False) + zc = params.get("z_carry", Z_SAFE if careful else Z_CARRY) + zr = params.get("z_rel", Z_DROP if careful else Z_REL) + order = params.get("slots") or [(1, 1), (1, -1), (-1, 0)] # far row first (Sonnet fills from the far end) + cubes = params.get("cubes") or self._cube_order() + noise = params.get("noise") or {} + v = params.get("speed", 0.15) + done = [] + for k, n in enumerate(cubes): + self.put_cube(n, k, order, zr, zc, noise=noise.get(n), v=v, v_down=params.get("v_down")) + done.append(n) + # looks after every step (Sonnet): re-places a cube that ended up outside the box ... + for f in self._fallen_cubes(done): + self.put_cube(f, done.index(f), order, zr, zc, v=v) + # ... and, if the bystander is in the policy's view of the task, stands the bottle up again + if params.get("restore") == "each" and not self.bottle_in_place(): + self.restand_bottle() + if params.get("check"): + self.check_and_fix(order, zr, zc) + self.sk.hold(10) + + def check_and_fix(self, order, zr, zc, rounds=2): + for _ in range(rounds): + v = self.stage_values() + if all(v.values()): + return True + for n in CUBES: + if not self.in_box(n): + self.put_cube(n, CUBES.index(n), order, zr, zc) + if not self.bottle_in_place(): + self.restand_bottle() + return all(self.stage_values().values()) + + def _cube_order(self): + """the cube nearest the box first""" + bxy = np.asarray(self.inst["box_xy"]) + return sorted(CUBES, key=lambda n: float(np.linalg.norm(np.asarray(self.inst["start"][n]) - bxy))) + + def default_params(self, inst): + """Sonnet-like: cubes nearest-first, carried 15 cm up in straight lines, each lowered straight down onto the box + floor (far row first), looks after every step and re-places a cube that fell out; no special care for the + bottle (it is not part of the packing)""" + return dict(careful=False, restore=None, check=False) + + def oracle_params(self, inst): + """knows its arm: carries high (24 cm) and drops the cubes into the box from 16 cm, so the forearm stays above + the bottle; checks every stage at the end""" + return dict(careful=True, restore="each", check=True) + + def adapt_params(self, inst, history): + """attempt >= 2: the careful packing (high carry, drop from above the rim), stand the bottle up if needed, + check at the end""" + return dict(careful=True, restore="each", check=True) + + def blind_params(self, inst, attempt, rng): + """the natural behaviour again with small random variations, no history, no care for the bottle""" + pats = [[(1, 1), (1, -1), (-1, 0)], [(1, -1), (1, 1), (-1, 0)], [(0, 1), (0, -1), (-1, 0)], + [(1, 0), (-1, 1), (-1, -1)], [(1, 1), (-1, -1), (0, 0)]] + return dict(careful=False, restore=None, check=False, slots=pats[int(rng.integers(len(pats)))], + z_carry=float(rng.uniform(0.12, 0.20)), z_rel=float(rng.uniform(0.032, 0.055)), + noise={n: rng.uniform(-NAIVE_ERR, NAIVE_ERR, 2).tolist() for n in CUBES}) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """oracle / naive: one attempt; adaptive: attempt 1 = naive + stands the knocked bottle up again after every + step and checks at the end, attempts >= 2 careful; blind: naive with random variations. + Extra kinds (not in validate's table): switch (naive, then careful without restoring), oracle_noise (oracle with + +-5 mm placement noise)""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = dict(careful=False, restore="each", check=True) if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": + params = self.default_params(inst) if a == 0 else dict(careful=True, restore=None, check=False) + elif kind == "oracle_noise": + params = dict(self.oracle_params(inst), noise={n: rng.uniform(-0.005, 0.005, 2).tolist() for n in CUBES}) + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive", "oracle_noise"): + break + return history diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_clear_cover.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_clear_cover.py new file mode 100644 index 0000000000000000000000000000000000000000..542d519109d1f085f749fe2db4dd0c20b51281b5 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_clear_cover.py @@ -0,0 +1,657 @@ +"""LH clear_cover: sort four cubes into two open boxes by colour -- but in half of the instances one box is covered by a +loose clear acrylic lid. A cube carried over that box and released stops on the lid at rim height; it is not in the box. + +Family: long-horizon self-disturbance / common sense ("state_restoration"; design P2-2 in +research_notes/P1P2_加深与常识任务设计.md): four pick-and-place stages that are each easy for a frontier model; the +trap is a commonsense one -- "a box can have a transparent lid" -- and the failure is only visible from the right +viewpoint: from the side (agentview) the cube visibly sits on top of the box, at rim height, with the box floor visible +below it; from straight above (the wrist camera) it lies inside the box's outline and looks almost the same as a cube +that is inside (design rule R5: a top-down view hides height differences). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * two open boxes (fixtures; inside 12 x 12 cm, walls 5 cm high and 8 mm thick, rim 5.6 cm above the table, light + floor) with red and with blue walls, centres at x in [-0.14, -0.08], y = +-(0.12-0.14) (24-28 cm apart); which + colour is on the left is random. The instruction names the boxes by colour, not "left / right" (the design draft's + wording), so that no failure comes from whose left is meant; + * four 4 cm cubes (38 g), two red and two blue, in a row in front of the boxes (x = -0.33, near the robot; 14 cm + apart, shuffled, yaw +-23 deg); + * the clear lid (covered instances only): a loose 13.4 x 13.4 cm, 8 mm clear plate lying on one box's walls, + 1 mm inside their outer faces (no overhang). v2 (2026-10-13, after the Sonnet pilot np_lh_clear_cover): rendered + nearly invisible -- alpha 0.03, matte (no specular glint), no edge highlight (v1: alpha 0.10 + bright edges, and the + pilot agent named "the transparent lid" from the first images); heavy (1 kg; mass is not visible) with friction 1.0 + and priority for all its contacts and medium-stiff contacts, so incidental contact by the hand does not knock it off + (v1, 0.12 kg / mu 0.3 / 6 mm overhang / very stiff contacts: a probe descent between the boxes knocked it off in the + pilot's very first motions). Transparent geoms do not write MuJoCo's depth buffer: in the depth maps + (--perception rgbd) the lid is not there at all. In uncovered instances the lid is parked on the floor far outside + the workspace and the cameras' view. + +Hidden variable: whether a box is covered and which one. Exactly 10 of every 20 consecutive seeds are covered (5 red / +5 blue box): (seed * 7) mod 20 < 10, like lh_lid_box's balanced blocks. + +Why the natural plan fails: carry each cube over its box and release it a few cm above the rim. Over the covered box the +cube lands on the lid and stays there (v2, measured: drops of 1-8 cm, 48/48 stay on the lid, the lid does not move; +pressing a held cube down towards the box floor stops the arm 4.2 cm above the target, the lid moves <= 0.8 mm, 12/12 +still covering). After the release the cube visibly sits on top of the box in agentview (its bottom 0.8 cm above the +rim, the box floor visible below it); checking only from above it looks as if it were in the box (~1.3x bigger). +What must be learned: look from the side / compare heights before finishing, notice the cubes resting at rim height, +remove the lid (push its edge horizontally with the closed gripper, fingertips between the rim and the lid's top face -- +what the pilot agent did when it saw the v1 lid) and put the cubes in (within the attempt), or check for a lid and +remove it before placing anything (across attempts). Pressing the fingertips onto the lid and dragging no longer moves +it (v2: hand friction = rim friction, by design, because a hand landing on the lid while moving sideways is exactly +what knocked the v1 lid off). +Measured, 2 covered instances x 86 Sonnet-like incidental motions (probe descents to 2-5 cm next to / between the +boxes, transits at 11-20 cm over the covered box, low lateral moves next to the boxes): the box got uncovered 1/172 +(v1: 57/172), the lid moved > 2 cm 20/172 (v1: 97/172); a crash sweep through the boxes at 3 cm still knocks it (1/2). +Deliberate edge push, agent-style commands: fingertip target 2-10 mm below the lid's top face 10/10 (+ 8/8 in the +parameter sweep), at the top face 1/2, above it 0/2. + +Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (every cube in the +cavity of the box of its colour -- centre inside the cavity, lowest point below the rim --, nothing held, the lid not on +a box, scene static) plus a per-step event log (cube stages achieved / lost / restored, rested_on_cover, left_cover, +cover_removed, cover_on_box, in_wrong_box) for the server log; F1 gives the agent only success / failure. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, _wrap, box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +Z = envs.TABLE_Z +TIP = envs.FINGERTIP_BELOW_SITE +# ---------------------------------------------------------------- geometry / physics +CUBE_E = 0.04 +CUBE_DENS = 600.0 # -> 38 g +BOX_IN = 0.06 # inner half width (12 x 12 cm cavity) +WALL_T, FLOOR_T, WALL_H = 0.008, 0.006, 0.05 +BOX_OUT = BOX_IN + WALL_T +RIM = FLOOR_T + WALL_H # rim height above the table +WALL_MU = 0.3 # walls (cube contacts; the lid's own friction has priority in its contacts) +LID_T = 0.008 # thick enough that a horizontal push at 'lid height' finds its edge (v1 draft: 4 mm, see the card) +LID_HALF = BOX_OUT - 0.001 # v2: no overhang (1 mm inside the walls' outer faces): a hand landing on its edge cannot tip it +LID_MASS = 1.0 # v2: heavy (a thick glass-like plate; mass is not visible): incidental bumps move it much less +LID_MU = 1.0 # v2: with priority, used for ALL lid contacts (rim, hand, fingers, cubes): pressing on the lid and moving +# sideways cannot drag it (hand friction == rim friction, and the rim also carries the lid's weight) +LID_SOLREF = (0.005, 1.0) # v2: medium-stiff contacts (v1 used _SOLID: a finger that caught the lid's edge while the +LID_SOLIMP = (0.95, 0.99, 0.001) # arm pressed on could squeeze it against the wall and launch it 16-37 cm) +LID_TOP = RIM + LID_T # lid top surface above the table when it lies on a box +LID_RGBA = (0.85, 0.90, 0.95, 0.03) # v2: near-invisible, no edge highlight, no specular (material below) +PARK = (0.0, 1.4) # lid parked on the floor (world z = 0), out of reach and out of view (uncovered instances) + +COLORS = ("red", "blue") +CUBE_RGBA = dict(red=(0.88, 0.10, 0.08, 1.0), blue=(0.10, 0.25, 0.88, 1.0)) +WALL_RGBA = dict(red=(0.72, 0.26, 0.22, 1.0), blue=(0.22, 0.34, 0.72, 1.0)) +FLOOR_RGBA = (0.86, 0.85, 0.82, 1.0) +CUBES = [f"{c}_cube_{i}" for c in COLORS for i in (1, 2)] +BOXES = {c: f"{c}_box_1" for c in COLORS} +LID = "clear_lid_1" + +IN_MARGIN = 0.010 # a cube counts as in a box if its centre is within BOX_IN - IN_MARGIN of the box centre (each axis) +BELOW_RIM = 0.005 # ... and its lowest point is at least this far below the rim +Z_CARRY = 0.15 # scripted transit height of the grasp point above the table (Sonnet: 11-20 cm) +DROP = 0.04 # scripted release: cube bottom this far above the rim (Sonnet-like 3-5 cm) +SLOT = 0.028 # two cubes per box: +-2.8 cm from the centre along y +PUSH_DEPTH = 0.004 # scripted edge push: fingertips this far below the lid's top face (lid 8 mm thick) +PUSH_SPEED = 0.06 + + +def _color(name): + return name.split("_")[0] + + +def _fb(v): + return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}" + + +def _lr(v): + return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}" + + +def box_xml_cc(name, wall_rgba): + """open-top box, body origin at the centre of its footprint on the table (z = 0 = table top)""" + o = BOX_OUT + parts = [((0, 0, FLOOR_T / 2), (o, o, FLOOR_T / 2), FLOOR_RGBA, 1.0), + ((BOX_IN + WALL_T / 2, 0, RIM / 2), (WALL_T / 2, o, RIM / 2), wall_rgba, WALL_MU), + ((-BOX_IN - WALL_T / 2, 0, RIM / 2), (WALL_T / 2, o, RIM / 2), wall_rgba, WALL_MU), + ((0, BOX_IN + WALL_T / 2, RIM / 2), (BOX_IN, WALL_T / 2, RIM / 2), wall_rgba, WALL_MU), + ((0, -BOX_IN - WALL_T / 2, RIM / 2), (BOX_IN, WALL_T / 2, RIM / 2), wall_rgba, WALL_MU)] + g = [] + for k, (p, s, c, mu) in enumerate(parts): + g.append(f' ') + g.append(f' ') + return f""" + + + +{chr(10).join(g)} + + + + + + +""" + + +def lid_xml(name): + """clear plate: one collision box + a near-invisible visual twin with a matte material (no specular glint)""" + h, t = LID_HALF, LID_T / 2 + g = [f' ', + f' '] + xml = _wrap(name, "\n".join(g), t, float(np.hypot(h, h))) + mat = (f' \n \n \n') + return xml.replace(" ", mat + " ", 1) + + +class CoverSkills(Skills): + """Skills that feed the task's per-step monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class ClearCover(LFFTask): + name = "lh_clear_cover" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Plan", "Utilize") + protocol = "cross" + max_attempts = 3 + # careful oracle: 4 pick-and-places (~7 commands each = 28) + pushing the lid off (~5) + looking around (~15); + # one recovery: pushing the lid off + re-placing the cubes that were on it (~5 + 2 x 7) -> ~70; Sonnet looks after + # every step and calibrates the wrist camera (cla4: 10+ observe / probe commands) + agent_max_steps = 110 + instruction = "Put the two red cubes into the red box and the two blue cubes into the blue box." + instruction_indirect = "Sort the four small cubes by colour: each cube goes into the box whose walls have its colour." + agent_object_names = ["red cube", "red cube", "blue cube", "blue cube", "red box", "blue box"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs, fx = [], [] + for j, c in enumerate(COLORS): + bx = register_generated(f"LffCc{c.title()}Box", box_xml_cc(f"lff_cc_{c}_box", WALL_RGBA[c]), free=False) + fx.append((BOXES[c], bx, f"{c}_box_region", (-0.12, 0.12 - 0.26 * j, -0.10, 0.14 - 0.26 * j))) + k = 0 + for c in COLORS: + for i in (1, 2): + ab = "AB"[i - 1] + cat = register_generated(f"LffCc{c.title()}Cube{ab}", + box_xml(f"lff_cc_{c}_cube_{ab.lower()}", (CUBE_E / 2,) * 3, CUBE_RGBA[c], + density=CUBE_DENS)) + objs.append((f"{c}_cube_{i}", cat, f"{c}_cube_{i}_region", + (-0.34, -0.22 + 0.14 * k, -0.32, -0.20 + 0.14 * k))) + k += 1 + lid = register_generated("LffCc2ClearLid", lid_xml("lff_cc2_clear_lid")) + objs.append((LID, lid, "lid_region", (0.20, -0.01, 0.22, 0.01))) + return write_bddl(self.name, "put the cubes into the boxes of their colour", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.box_bid = {c: m.body_name2id(self.env.fixtures_dict[BOXES[c]].root_body) for c in COLORS} + self.lid_gids = set(envs.obj_geom_ids(self.env, LID)) + self.cube_gids = {n: set(envs.obj_geom_ids(self.env, n)) for n in CUBES} + self.robot_gids = set(envs.robot_geom_ids(self.env)) + self.inst = None + self.mon = None + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + bx = float(rng.uniform(-0.13, -0.09)) + left = str(rng.choice(COLORS)) + boxes = {} + for c in COLORS: + s = 1.0 if c == left else -1.0 + boxes[c] = [bx + float(rng.uniform(-0.01, 0.01)), s * float(rng.uniform(0.12, 0.14))] + slots = [-0.21, -0.07, 0.07, 0.21] + perm = rng.permutation(4) + start = {CUBES[i]: [float(-0.33 + rng.uniform(-0.01, 0.01)), float(slots[j] + rng.uniform(-0.01, 0.01))] + for j, i in enumerate(perm)} + # balanced like lh_lid_box: exactly 10 of every 20 consecutive seeds covered (5 red box, 5 blue box) + r = (int(seed) * 7) % 20 + cover = "red" if r < 5 else ("blue" if r < 10 else None) + return dict(seed=int(seed), boxes=boxes, left_box=left, start=start, + start_yaw={k: float(rng.uniform(-0.4, 0.4)) for k in CUBES}, cover=cover, + cover_side=(None if cover is None else ("left" if cover == left else "right")), + lid_off=[float(v) for v in rng.uniform(-0.004, 0.004, 2)], lid_yaw=float(rng.uniform(-0.05, 0.05))) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + for c in COLORS: + m.body_pos[self.box_bid[c]] = [inst["boxes"][c][0], inst["boxes"][c][1], Z] + m.body_quat[self.box_bid[c]] = [1.0, 0.0, 0.0, 0.0] + for name, xy in inst["start"].items(): + envs.place_upright(self.env, name, xy, yaw=inst["start_yaw"][name]) + if inst["cover"]: + b = inst["boxes"][inst["cover"]] + envs.set_obj_pose(self.env, LID, [b[0] + inst["lid_off"][0], b[1] + inst["lid_off"][1], + Z + RIM + LID_T / 2 + 0.0005], yaw=inst["lid_yaw"]) + else: + envs.set_obj_pose(self.env, LID, [PARK[0], PARK[1], LID_T / 2 + 0.002]) + envs.set_friction(self.env, LID, LID_MU, priority=2) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.mon = None + self.sk = CoverSkills(self.env, self, recorder=recorder) + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ state helpers + def held(self, name): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name])) + + def cube_rel(self, name, color): + return envs.obj_pos(self.env, name)[:2] - np.asarray(self.inst["boxes"][color]) + + def in_box(self, name, color, margin=IN_MARGIN): + """centre inside the cavity (per axis), lowest point below the rim, not held""" + rel = self.cube_rel(name, color) + return bool(np.max(np.abs(rel)) <= BOX_IN - margin and envs.obj_min_z(self.env, name) < Z + RIM - BELOW_RIM + and not self.held(name)) + + def where_box(self, name): + for c in COLORS: + if self.in_box(name, c): + return c + return None + + def lid_pos(self): + return envs.obj_pos(self.env, LID) + + def covering(self): + """colour of the box the lid lies on (centre within the box's outer footprint + 1 cm, above the floor), or None""" + p = self.lid_pos() + for c in COLORS: + rel = np.abs(p[:2] - np.asarray(self.inst["boxes"][c])) + if rel[0] <= BOX_OUT + 0.01 and rel[1] <= BOX_OUT + 0.01 and p[2] > Z + 0.02: + return c + return None + + def _touching(self, gids_a, gids_b): + return envs.contacts_between(self.env, gids_a, gids_b) + + def on_cover(self, name, moving_ok=False): + """the cube rests on the lid while the lid lies on a box (contact, not held, slow -- unless `moving_ok`: the + monitor keeps a cube that came to rest on the lid "on" while it rides along with the lid being pushed)""" + if self.covering() is None or self.held(name): + return False + if not self._touching(self.cube_gids[name], self.lid_gids): + return False + if moving_ok: + return True + _, da = envs.free_joint_addr(self.env, name) + return bool(np.linalg.norm(self.env.sim.data.qvel[da:da + 3]) < 0.05) + + def stage_values(self): + v = {f"{n}_in_box": self.in_box(n, _color(n)) for n in CUBES} + v["cover_off_boxes"] = self.covering() is None + return v + + # ------------------------------------------------------------ per-step monitor + def _init_monitor(self): + self.mon = dict(step=0, state={f"{n}_in_box": False for n in CUBES}, ever=set(), lost=set(), events=[], + on_cover={n: False for n in CUBES}, cover=self.covering(), wrong={n: None for n in CUBES}, + last_touch={n: None for n in CUBES}, rested=[], cover_removed_step=None) + + def _touches(self): + d = self.env.sim.data + out = {} + for i in range(d.ncon): + c = d.contact[i] + for n, g in self.cube_gids.items(): + other = c.geom2 if c.geom1 in g else (c.geom1 if c.geom2 in g else None) + if other is None: + continue + if other in self.robot_gids: + out[n] = "robot" + elif other in self.lid_gids and out.get(n) != "robot": + out[n] = "lid" + return out + + def monitor_step(self): + mon = self.mon + if mon is None: + return + mon["step"] += 1 + step = self.sk.n_steps if self.sk is not None else mon["step"] + for n, who in self._touches().items(): + if who == "robot": + mon["last_touch"][n] = step + if mon["step"] % 2: + return # predicates every other control step (0.1 s) + cov = self.covering() + if cov != mon["cover"]: + if mon["cover"] is not None and cov is None: + mon["events"].append(dict(step=step, pred="cover", ev="cover_removed", box=mon["cover"])) + mon["cover_removed_step"] = step + elif cov is not None: + mon["events"].append(dict(step=step, pred="cover", ev="cover_on_box", box=cov)) + mon["cover"] = cov + for n in CUBES: + oc = self.on_cover(n, moving_ok=mon["on_cover"][n]) + if oc != mon["on_cover"][n]: + mon["on_cover"][n] = oc + if oc: + mon["rested"].append(dict(step=step, cube=n)) + mon["events"].append(dict(step=step, pred=f"{n}_on_cover", ev="rested_on_cover" if oc else "left_cover", + cube=n, box=cov)) + key = f"{n}_in_box" + was = mon["state"][key] + now = self.in_box(n, _color(n), IN_MARGIN if not was else IN_MARGIN - 0.005) + if now != was: + self._event(key, now, step, n) + other = [c for c in COLORS if c != _color(n)][0] + wr = other if self.in_box(n, other) else None + if wr != mon["wrong"][n]: + mon["wrong"][n] = wr + if wr: + mon["events"].append(dict(step=step, pred=key, ev="in_wrong_box", cube=n, box=wr)) + + def _event(self, key, now, step, n): + mon = self.mon + mon["state"][key] = now + if now: + ev = "restored" if key in mon["lost"] else "achieved" + mon["ever"].add(key) + mon["lost"].discard(key) + mon["events"].append(dict(step=step, pred=key, ev=ev)) + return + if self.held(n): + cause = "picked_up" + else: + lt = mon["last_touch"][n] + cause = "robot" if lt is not None and step - lt <= 60 else "other" + mon["lost"].add(key) + mon["events"].append(dict(step=step, pred=key, ev="lost", cause=cause)) + + # ------------------------------------------------------------ outcome + def _static(self): + d = self.env.sim.data + for name in CUBES + [LID]: + _, da = envs.free_joint_addr(self.env, name) + if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5: + return False + return True + + def outcome(self, inst): + envs.settle(self.env, 30) + mon = self.mon + vals = self.stage_values() + static = self._static() + held = [n for n in CUBES if self.held(n)] + on_cover = [n for n in CUBES if self.on_cover(n)] + wrong = [n for n in CUBES if not vals[f"{n}_in_box"] and self.where_box(n) is not None] + missing = [n for n in CUBES if not vals[f"{n}_in_box"]] + cov = self.covering() + success = bool(all(vals.values()) and static and not held) + failure = None + if not success: + failure = ("held" if held else "cube_on_cover" if on_cover else "wrong_box" if wrong else + "cube_not_in_box" if missing else "cover_on_box" if cov is not None else "not_static") + regress = [e for e in mon["events"] if e["ev"] == "lost"] + restored = [e for e in mon["events"] if e["ev"] == "restored"] + rested_cubes = sorted({r["cube"] for r in mon["rested"]}) + parts = [] + if success: + parts.append("All four cubes are in the boxes of their colour.") + for n in missing: + c = _color(n) + txt = f"A {c} cube is not in the {c} box: " + if n in held: + parts.append(txt + "it is still held by the gripper.") + continue + p = envs.obj_pos(self.env, n) + rel = self.cube_rel(n, c) + if n in on_cover: + txt += (f"it rests on a clear acrylic lid that lies on the {cov} box, " + f"{100 * (envs.obj_min_z(self.env, n) - Z - FLOOR_T):.1f} cm above the box floor") + elif self.where_box(n) is not None: + txt += f"it is in the {self.where_box(n)} box" + else: + h = envs.obj_min_z(self.env, n) - Z + txt += ("it lies on the table" if h < 0.005 else f"it lies {100 * h:.1f} cm above the table") + txt += f", its centre {_fb(rel[0])} and {_lr(rel[1])} of the {c} box's centre" + if n in rested_cubes and n not in on_cover: + txt += " (it had come to rest on the clear lid earlier)" + parts.append(txt + ".") + if cov is not None: + parts.append(f"A clear acrylic lid lies on the {cov} box.") + if not static and all(vals.values()) and not held: + parts.append("Something was still moving at the end.") + if mon["cover_removed_step"] is not None and cov is None: + parts.append("The clear lid was pushed off its box.") + out = dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, + events=mon["events"], n_regressions=len(regress), n_restored=len(restored), + covered=inst["cover"], trap_fired=bool(mon["rested"]), n_rested_on_cover=len(mon["rested"]), + rested_cubes=rested_cubes, cover_removed=mon["cover_removed_step"] is not None, + cover_removed_step=mon["cover_removed_step"], cover_final=cov, on_cover_final=on_cover, + recovered_in_attempt=bool(mon["rested"]) and success, + cube_offsets_cm={n: (100 * self.cube_rel(n, _color(n))).round(1).tolist() for n in CUBES}, + detail=" ".join(parts)) + return out + + # ------------------------------------------------------------ scripted policies (perfect perception) + def _grasp_yaw(self, name): + R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3) + i = int(np.argmin(np.abs(R[2]))) # the most horizontal body axis (works whichever face the cube rests on) + yaw = float(np.arctan2(R[1, i], R[0, i])) + return float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4) + + def _finger_axis(self, yaw): + """world xy direction along which the fingers close at gripper yaw `yaw` (Skills: yaw 0 = fingers along y)""" + return np.array([-np.sin(yaw), np.cos(yaw)]) + + def _clear_yaw(self, name, room=0.04): + """grasp yaw of the cube: the smallest wrist turn (within +-45 deg) unless one of the open fingertips (4.5 cm + either side) would come down within `room` of another cube's centre (cubes put side by side or pushed off on + the lid stand 1.5-2.5 cm apart); then the 90-deg turned grasp if it has more room""" + p = envs.obj_pos(self.env, name)[:2] + others = [envs.obj_pos(self.env, n)[:2] for n in CUBES if n != name] + + def dmin(yaw): + a = self._finger_axis(yaw) + return min([np.linalg.norm(t - o) for t in (p + a * 0.045, p - a * 0.045) for o in others] or [1.0]) + + y0 = self._grasp_yaw(name) + if dmin(y0) >= room: + return y0 + y1 = float((y0 + np.pi / 2 + np.pi / 2) % np.pi - np.pi / 2) + return y1 if dmin(y1) > dmin(y0) else y0 + + def pick(self, name, z_carry=Z_CARRY): + sk = self.sk + p = envs.obj_pos(self.env, name) + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], Z + max(z_carry, p[2] - Z + 0.06)], yaw=self._clear_yaw(name)) + sk.move_to([p[0], p[1], p[2]], tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + sk.move_to([p[0], p[1], Z + z_carry], speed=0.3) + if not self.held(name): + sk.set_gripper(False, steps=8) + return False + return True + + def place_in(self, name, slot, drop=DROP, z_carry=Z_CARRY, noise=None): + """carry the held cube over its box (slot -1 / +1: 2.8 cm right / left of the centre) and release it with its + bottom `drop` above the rim""" + sk = self.sk + b = np.asarray(self.inst["boxes"][_color(name)], float) + d = b + [0.0, SLOT * slot] + (np.asarray(noise, float) if noise is not None else 0.0) + z_rel = Z + RIM + drop + CUBE_E / 2 + sk.move_to([d[0], d[1], Z + z_carry], yaw=0.0) + sk.move_to([d[0], d[1], z_rel], tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + sk.move_to([d[0], d[1], Z + z_carry]) + + def pick_place(self, name, slot, drop=DROP, noise=None): + if self.pick(name): + self.place_in(name, slot, drop=drop, noise=noise) + return True + return False + + def remove_cover(self, direction=None, depth=PUSH_DEPTH, mode="edge"): + """push the lid off its box: closed gripper, fingertips `depth` below the lid's top face, start 3 cm outside + its near edge (mode "edge") or 3 cm inside it, pressing on the lid (mode "press": press and drag -- v2: does not + move the lid any more, see the module docstring), sweep + straight on until the lid has cleared the box (default: sideways, away from the other box), lift""" + cov = self.covering() + if cov is None: + return False + sk = self.sk + lp = self.lid_pos() + b = np.asarray(self.inst["boxes"][cov], float) + if direction is None: + o = np.asarray(self.inst["boxes"][[c for c in COLORS if c != cov][0]], float) + direction = (0.0, float(np.sign(b[1] - o[1]))) + d = np.asarray(direction, float) / np.linalg.norm(direction) + back = LID_HALF + 0.03 if mode == "edge" else LID_HALF - 0.03 + s = lp[:2] - d * back + top = lp[2] + LID_T / 2 + z = top - depth + TIP + sk.set_gripper(True, steps=8) + sk.move_to([s[0], s[1], z + 0.08], yaw=float(np.arctan2(d[1], d[0]) - np.pi / 2)) + sk.move_to([s[0], s[1], z], tol=0.003, max_steps=80) + # sweep until the lid's near edge is 3 cm beyond the box's far wall + need = float((b - lp[:2]) @ d) + BOX_OUT + back + 0.03 + e = s + d * need + sk.move_to([e[0], e[1], z], speed=PUSH_SPEED, tol=0.006, max_steps=int(need / PUSH_SPEED / 0.05) + 80) + sk.move_to([e[0], e[1], z + 0.10], speed=0.2) + sk.set_gripper(False, steps=8) + sk.hold(10) + return self.covering() is None + + def slots(self, order): + """slot of each cube: the first cube of a colour goes right of the centre, the second left""" + seen, out = {c: 0 for c in COLORS}, {} + for n in order: + out[n] = (-1, 1)[seen[_color(n)] % 2] + seen[_color(n)] += 1 + return out + + def wrist_fix(self, rounds=1): + """what a top-down check can see: cubes whose centre is not over the right box's outline (on the table, in + the other box, still held) get placed again; heights are not judged""" + for _ in range(rounds): + bad = [] + for n in CUBES: + rel = self.cube_rel(n, _color(n)) + if self.held(n) or np.max(np.abs(rel)) > BOX_OUT: + bad.append(n) + if not bad: + return + for n in bad: + if self.held(n): + self.sk.set_gripper(False, steps=12) + continue + self.pick_place(n, -1 if self.cube_rel(n, _color(n))[1] < 0 else 1) + + def set_aside(self, name): + """pick the cube (e.g. off the lid) and put it down on the table where it started (that spot is free)""" + if not self.pick(name): + return False + sk = self.sk + x, y = self.inst["start"][name] + sk.move_to([x, y, Z + Z_CARRY], yaw=0.0) + sk.move_to([x, y, Z + CUBE_E / 2 + 0.004], tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + sk.move_to([x, y, Z + Z_CARRY]) + return True + + def side_fix(self, rounds=2): + """the careful check (agentview / heights): every cube must be inside its box, below the rim; if cubes rest on + a lid (or a lid lies on a box): take the cubes off the lid (v2: the heavy lid cannot be pushed off with cubes + standing on it -- the hand runs into them), push the lid off; then place every cube that is not in its box""" + for _ in range(rounds): + v = self.stage_values() + if all(v.values()): + return True + if not v["cover_off_boxes"]: + for n in CUBES: + if self.on_cover(n) or (self.covering() is not None and self._touching(self.cube_gids[n], self.lid_gids)): + self.set_aside(n) + self.remove_cover() + for n in CUBES: + if not self.in_box(n, _color(n)): + if self.held(n): + self.sk.set_gripper(False, steps=12) + continue + others = [m for m in CUBES if m != n and _color(m) == _color(n)] + rel_o = self.cube_rel(others[0], _color(n)) if others else np.zeros(2) + self.pick_place(n, 1 if rel_o[1] < 0 else -1) + return all(self.stage_values().values()) + + def execute(self, inst, params): + order = params.get("order") or list(CUBES) + noise = params.get("noise") or {} + drops = params.get("drops") or {} + if params["plan"] == "lid_first": + self.remove_cover(params.get("push_dir"), params.get("push_depth", PUSH_DEPTH), params.get("push_mode", "edge")) + sl = self.slots(order) + for n in order: + self.pick_place(n, sl[n], drop=drops.get(n, DROP), noise=noise.get(n)) + if params.get("check") == "side": + self.side_fix() + elif params.get("check") == "wrist": + self.wrist_fix() + self.sk.hold(10) + + def default_params(self, inst): + return dict(plan="naive", check="wrist") + + def oracle_params(self, inst): + return dict(plan="lid_first", check="side") + + def adapt_params(self, inst, history): + """from attempt 2 on: look for a lid and push it off first, then place, then check from the side""" + return dict(plan="lid_first", check="side") + + def blind_params(self, inst, attempt, rng): + """the natural plan again with small random variations (order, 5 mm placement noise, 3-5 cm drop), no history""" + order = [CUBES[i] for i in rng.permutation(len(CUBES))] + return dict(plan="naive", check="wrist", order=order, + noise={n: rng.uniform(-0.005, 0.005, 2).tolist() for n in CUBES}, + drops={n: float(rng.uniform(0.03, 0.05)) for n in CUBES}) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = dict(plan="naive", check="side") if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": # extra control (not in validate's table): cross-attempt learning only, no side check + params = self.default_params(inst) if a == 0 else dict(plan="lid_first", check="wrist") + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_drawer_cabinet.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_drawer_cabinet.py new file mode 100644 index 0000000000000000000000000000000000000000..55c3e05f0c97631b61329c3dee47a318c1f3b5f1 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_drawer_cabinet.py @@ -0,0 +1,1273 @@ +"""LH drawer_cabinet (2026-10-16): tidy the table -- stand two tall bottles on top of a small wooden cabinet, put two +cubes into its open drawer and close the drawer. In 14 of every 20 instances the drawer is a self-closing one: pushed +into the last 8 cm, a strong spring snaps it shut, the light cabinet lurches 2.3-4.2 cm towards the robot, and bottles +already standing on its top fall over (away from the robot, onto the gallery rail at the back of the top). + +Family: long-horizon self-disturbance ("state_restoration"): a later, normal action (closing the drawer) physically +undoes an earlier stage (bottles on the cabinet). The instruction lists the bottles first but fixes no order. The agent +has to see the fallen bottles and stand them up again after the drawer is shut (within an attempt), or learn to put +the cubes in and shut the drawer before it puts the bottles on top (across attempts). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a small wooden cabinet (free body, 18 (x) x 22 (y) x 11 cm, centre 53-56 cm in front of the robot base, front facing + the robot) with a 6 cm gallery rail along the back edge of its top, a 4 cm toe plinth under the drawer and a + back-heavy carcass; its single drawer (inside 15.9 x 16.2 cm, 3 cm walls, 1.8 cm overlay front panel with a painted + finger slot, no handle, 0.8 kg) is pulled out 11 cm towards the robot. The agentview camera looks at the cabinet's + back: the drawer is hidden there (wrist camera only), the top and the bottles are in plain view; + * two tall square bottles (green with a yellow ball cap, brown with a blue ball cap; 4 x 4 cm body, 19.4 cm tall, + 0.18 kg, centre of mass 9 cm up, a rounded glass base whose flat contact is 2.2 x 2.2 cm: they tip beyond ~7 deg) + standing on the table 21-24 cm to one side of the cabinet's centre line; + * two 3.2 cm cubes (red, blue, 23 g) 25-29 cm to the other side (picked from nearer, the forearm sweeps over the + cabinet top and knocks bottles standing there: measured feasibility map, task card). + +Hidden variable (same appearance): the drawer's closing mechanism. "self-closing" (14 of every 20 consecutive seeds): +in the last 8 cm of travel a spring pulls the drawer in with 12.5-15 N (no damper); "soft-close" (6 of 20): the same +spring with a damper, the drawer glides in at 4-6 cm/s. Nuisance variables (no effect on the class): carcass mass +0.35-0.45 kg, felt feet (friction on the table 0.15-0.22). + +Mechanism (physics, no teleport; measured, see the task card): the spring is internal to the cabinet, so when it snaps +the drawer in, it also pulls the light carcass (with the bottles on its top) towards the drawer, i.e. towards the robot: +2.3-4.2 cm within ~0.07 s (drawer hitting its stop at 1.9-2.4 m/s relative to the carcass; validate's naive runs), +then the carcass stops dead. A standing bottle's tilt follows a fast displacement of its support as ~ m h dx / I_edge +(~7 rad per metre here), so the bottles tip away from the robot and come to rest leaning on the rail (45-75 deg). The +robot's hand is at the drawer front, below and 10+ cm away from the bottles, and does not touch them (0 of all slams). +Pushing slower does not help (the spring does the closing; 2-10 cm/s and push heights 3-8 cm all toppled, 32/32); +placing the bottles elsewhere on the top does not help (46/46 over six placements). A soft-close drawer moves the +carcass < 3 mm (0/38 bottles fell). Only an uncontrolled full-speed push (~0.6 m/s, not an agent habit) differs: the +hand then shoves the cabinet itself (self-closing 5/8 fell, soft-close 4/4 fell, onto the arm). Placing the bottles after the drawer is shut is safe. Prototype findings that fixed +the numbers: with a light drawer, a heavier carcass or more friction the bottles only rocked (<= 11 deg): the snap's +jerk and the friction stop cancel; a 2 kg carcass held by friction during the snap instead jerked away from the robot +and tipped the bottles towards (onto) the arm. Without the rail, fallen bottles lay with their caps right behind the +cabinet, where the palm (3 cm behind the grasp point) cannot get at them; with the heavy drawer pulled out and no +plinth, ~3 N pressing on the drawer front tipped the cabinet forward. + +Restoring: the cap is a ball with low torsional friction; grasped from above with the fingers across the lying +bottle's axis, the cap turns between the fingers, the lifted bottle swings down and hangs straight, and it can be set +down on the cabinet top (lh_bystander's mechanism; the instruction says that a bottle held by its cap hangs straight). +The neck has torsional friction: a bottle pinched at the neck just under the cap is carried without swinging. + +Success (final state, follows from the instruction): both bottles upright (<= 10 deg) with their whole base on the +cabinet top (inside the rail), not held; both cubes inside the drawer; the drawer closed (<= 5 mm); the cabinet +upright and not moved more than 8 cm (the snap itself moves it 2.3-4.2 cm); the gripper open, holding nothing and +touching no task object; scene static. Per-step monitor (server log only; F1 tells the agent success / failure): stage +achieved / lost / restored (with cause: drawer_slam / robot_hand / robot_arm / bottle / picked_up / other), +drawer_slam (impact speed, carcass jerk, bottles on top, which of them fell, whether the robot had touched them before +they started to fall), bottle_fell, trap_fired (a bottle on top was lost to a slam), recovered_in_attempt. + +Protocol: cross (reset to the same instance before every attempt), k = 3. Once shut, the drawer cannot be opened again +(no handle; the self-closing spring would drag the light carcass along anyway). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +Z = envs.TABLE_Z + +# ---------------------------------------------------------------- cabinet (body frame: front face at -x, origin at the +# centre of the footprint, z = 0 on the table) +CAB = "cabinet_1" +CAB_MODEL = "lff_lhd_cabinet" +CD, CW, CH = 0.18, 0.22, 0.11 # carcass depth (x), width (y), height +CT = 0.010 # board thickness +PF = 0.018 # drawer front panel thickness (overlay: it sits in front of the carcass when closed) +DL = 0.165 # drawer box length (x), measured from the inner face of the front panel +DWT = 0.006 # drawer wall thickness +DWH = 0.030 # drawer wall height above its floor +D_FLOOR = CT + 0.003 # drawer floor bottom above the table +FLOOR_TOP = D_FLOOR + DWT +D_IN_Y = CW / 2 - CT - 0.003 - DWT # drawer inner half width (0.081) +D_IN_X = DL - DWT # inner length (from the front panel to the back wall) +Q_MAX = 0.14 # slide range (opening distance) +Q_OPEN = 0.11 # the drawer starts pulled out this far (exposed inside: 11 x 16.2 cm) +WOOD = (0.66, 0.50, 0.33, 1.0) +WOOD_D = (0.55, 0.40, 0.25, 1.0) +PANEL = (0.76, 0.60, 0.40, 1.0) +INNER = (0.84, 0.72, 0.52, 1.0) +SLOT = (0.18, 0.13, 0.09, 1.0) +DRAWER_MASS = 0.80 +PLINTH = 0.04 # the bottom board reaches this far in front of the carcass, under the drawer: with the heavy drawer +# pulled out, the cabinet would otherwise tip forward under a ~3 N push down on the drawer's front +CAB_COM_X = 0.04 # carcass centre of mass towards the back (back-heavy carcass): same reason +RAIL_H, RAIL_T = 0.060, 0.008 # gallery rail along the back edge of the top: a bottle that tips over backwards comes +# to rest leaning on it (~50 deg) instead of falling off behind the cabinet, where its +# cap would lie against the cabinet's back and the palm could not get at it +SLIDE_FRIC = 1.0 # N, slide frictionloss: the open drawer stays where it is +CARCASS_MASS = (0.35, 0.45) +FEET_MU = (0.15, 0.22) + +# drawer closing mechanism (hidden): spring in the last ZONE of travel, optional damper (soft-close) +ZONE = 0.08 +F_SPRING = (12.5, 15.0) +SOFT_V = (0.04, 0.06) # soft-close glide speed (damping = force / speed) +P_SLAM = 0.70 # 14 of every 20 consecutive seeds self-closing +CLOSED = 0.005 # drawer counts as closed +V_SLAM = 0.30 # m/s: an impact on the stop faster than this is a slam (soft-close: ~0.05) + +# ---------------------------------------------------------------- bottles (square body, shoulder, neck, ball cap) +BOTTLES = ("green_bottle_1", "brown_bottle_1") +B_NAME = {"green_bottle_1": "green", "brown_bottle_1": "brown"} +B_RGBA = {"green_bottle_1": (0.16, 0.48, 0.26, 1.0), "brown_bottle_1": (0.50, 0.26, 0.10, 1.0)} +CAP_RGBA = {"green_bottle_1": (0.92, 0.80, 0.15, 1.0), "brown_bottle_1": (0.15, 0.32, 0.85, 1.0)} +RB, HB = 0.020, 0.115 # body half width, height (incl. the foot) +RF, HF = 0.011, 0.005 # rounded glass base: flat contact 2.2 x 2.2 cm +RS, HS = 0.015, 0.010 # shoulder +RN, HN = 0.009, 0.050 # neck: long enough to be pinched below the cap with the palm clear of the cap +RK = 0.012 # ball cap +CAP_SINK = 0.005 +H_TOT = HB + HS + HN + 2 * RK - CAP_SINK # 0.194 +CAP_Z = H_TOT - RK # cap centre above the bottle's bottom when standing +B_MASS = 0.18 +B_COM = 0.090 # above the bottom +B_MU = 0.8 +CAP_MU_T = 0.0005 # torsional friction of the cap (condim 4): the grasped cap turns freely +NECK_MU_T = 0.01 # torsional friction of the neck (condim 4): a bottle pinched by its neck does not swing +NECK_GRASP = H_TOT - 0.027 # scripted grasp height above the bottom: the palm (3.1 cm above the grasp point between +# the fingers, measured) clears the cap top by 4 mm; the pads hold the neck top and the cap + +# ---------------------------------------------------------------- cubes +CUBES = ("red_cube_1", "blue_cube_1") +CUBE_COLOR = {"red_cube_1": "red", "blue_cube_1": "blue"} +CUBE_RGBA = dict(red=(0.85, 0.10, 0.08, 1.0), yellow=(0.92, 0.76, 0.10, 1.0), blue=(0.15, 0.30, 0.85, 1.0)) +CUBE_E = 0.032 +CUBE_DENS = 700.0 # 23 g + +# ---------------------------------------------------------------- predicates / monitor +UPRIGHT = np.radians(10.0) +TILT_START = np.radians(6.0) # a standing bottle beyond this has started to fall (it tips at ~6.8 deg) +FALLEN = np.radians(40.0) # lying, or leaning on the gallery rail (45-75 deg) +CAB_MOVE_MAX = 0.08 +CAB_TILT_MAX = np.radians(10.0) +DEBOUNCE = 10 # control steps (0.5 s) a predicate change must persist (checked every other step) +WIN_ROBOT = 40 # control steps: a robot contact this recent can explain a loss +WIN_SLAM = 60 + +# ---------------------------------------------------------------- scripted motion +NAIVE_ERR = 0.008 # Sonnet's placement error 0.4-1.3 cm +FINGER_AHEAD = 0.021 # closed fingertips reach this far ahead of the grasp point (yaw 0, +x) -- measured +REACH_MAX = 0.78 # scripted policies: farthest grasp point at table height (horizontal distance from the base) + + +def _box(name, pos, size, rgba, extra, vis=True, vis_rgba=None): + s = [f''] + if vis: + s.append(f'') + return s + + +def cabinet_xml(name): + """free carcass (bottom, top, two sides, back) + a drawer on a slide joint along -x (opening towards the robot). + Carcass geoms contype 2 / conaffinity 1, drawer geoms contype 4 / conaffinity 1: they never collide with each other + but both collide with the robot, the table and the free objects (contype / conaffinity 1). The slide joint comes + first in the object's joint list (robosuite appends the free joint), see DrawerCabinet.__init__.""" + hx, hy = CD / 2, CW / 2 + cg = 'friction="0.8 0.005 0.0001" contype="2" conaffinity="1" solimp="0.95 0.99 0.001" solref="0.004 1"' + carc = [] + carc += _box(f"{name}_bottom", (-PLINTH / 2, 0, CT / 2), (hx + PLINTH / 2, hy, CT / 2), WOOD_D, cg) + carc += _box(f"{name}_top", (0, 0, CH - CT / 2), (hx, hy, CT / 2), WOOD, cg) + carc += _box(f"{name}_side_l", (0, hy - CT / 2, CH / 2), (hx, CT / 2, CH / 2 - CT), WOOD, cg) + carc += _box(f"{name}_side_r", (0, -hy + CT / 2, CH / 2), (hx, CT / 2, CH / 2 - CT), WOOD, cg) + carc += _box(f"{name}_back", (hx - CT / 2, 0, CH / 2), (CT / 2, hy - CT, CH / 2 - CT), WOOD, cg) + carc += _box(f"{name}_rail", (hx - RAIL_T / 2, 0, CH + RAIL_H / 2), (RAIL_T / 2, hy, RAIL_H / 2), WOOD_D, cg) + dg = 'friction="0.8 0.005 0.0001" contype="4" conaffinity="1" solimp="0.95 0.99 0.001" solref="0.004 1"' + x0 = -hx # inner face of the front panel (closed) + zf = D_FLOOR + dr = [] + dr += _box(f"{name}_front", (x0 - PF / 2, 0, (CT + 0.002 + CH - 0.004) / 2), (PF / 2, hy, (CH - 0.006 - CT) / 2), + PANEL, dg) + dr += _box(f"{name}_dfloor", (x0 + DL / 2, 0, zf + DWT / 2), (DL / 2, D_IN_Y + DWT, DWT / 2), INNER, dg) + zw = zf + DWT + DWH / 2 + dr += _box(f"{name}_dside_l", (x0 + DL / 2, D_IN_Y + DWT / 2, zw), (DL / 2, DWT / 2, DWH / 2), INNER, dg) + dr += _box(f"{name}_dside_r", (x0 + DL / 2, -D_IN_Y - DWT / 2, zw), (DL / 2, DWT / 2, DWH / 2), INNER, dg) + dr += _box(f"{name}_dback", (x0 + DL - DWT / 2, 0, zw), (DWT / 2, D_IN_Y, DWH / 2), INNER, dg) + # flush finger pull (visual only): a dark slot near the top of the front panel + dr.append(f'') + m = DRAWER_MASS + ixx, iyy, izz = m * (CW ** 2 + 0.06 ** 2) / 12, m * (DL ** 2 + 0.06 ** 2) / 12, m * (DL ** 2 + CW ** 2) / 12 + drawer = (f'\n' + f' \n' + f' \n' + "\n".join(" " + s for s in dr) + "\n") + m0 = 0.4 + inertial = (f'') + body = "\n ".join([inertial] + carc + drawer.split("\n")) + return f""" + + + + {body} + + + + + + +""" + + +def bottle_xml(name, rgba, cap_rgba): + """square bottle: rounded base (narrow flat foot), body, shoulder, neck, ball cap; origin at mid height""" + h = H_TOT / 2 + zf, zb, zs, zn = -h + HF / 2, -h + HF + (HB - HF) / 2, -h + HB + HS / 2, -h + HB + HS + HN / 2 + zk = -h + HB + HS + HN + RK - CAP_SINK + m = B_MASS + ixx = m * ((2 * RB) ** 2 + H_TOT ** 2) / 14 + izz = m * (2 * (2 * RB) ** 2) / 12 + fr = f'friction="{B_MU} 0.005 0.0001"' + sol = 'solimp="0.95 0.99 0.001" solref="0.005 1"' + parts = [("foot", "box", (0, 0, zf), (RF, RF, HF / 2), rgba, fr + ' priority="2"'), + ("body", "box", (0, 0, zb), (RB, RB, (HB - HF) / 2), rgba, fr), + ("shoulder", "box", (0, 0, zs), (RS, RS, HS / 2), rgba, fr), + ("neck", "cylinder", (0, 0, zn), (RN, HN / 2), rgba, + f'friction="{B_MU} {NECK_MU_T} 0.0001" condim="4" priority="2"'), + ("cap", "sphere", (0, 0, zk), (RK,), cap_rgba, f'friction="1 {CAP_MU_T} 0.0001" condim="4" priority="2"')] + s = [f' '] + for nm, typ, pos, size, c, extra in parts: + s.append(f' ') + if nm != "foot": + s.append(f' ') + # rounded base (visual): a slightly narrower bottom band, and a label + s.append(f' ') + s.append(f' ') + return _wrap(name, "\n".join(s), h, RB * 1.42) + + +def _fb(v): + return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}" + + +def _lr(v): + return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}" + + +def _reach(p): + return float(np.hypot(p[0] + 0.66, p[1])) + + +class DrawerSkills(Skills): + """Skills that feed the task's per-step monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class DrawerCabinet(LFFTask): + name = "lh_drawer_cabinet" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Restore", "Plan") + protocol = "cross" + max_attempts = 3 + # careful: 2 bottles x ~8 commands + 3 cubes x ~6 + closing the drawer ~5 + looking ~15; standing 2 fallen bottles + # up again ~20; + slack + agent_max_steps = 120 + instruction = ("Tidy up the table: stand the green bottle and the brown bottle upright on top of the small wooden " + "cabinet, put the red cube and the blue cube into the cabinet's open drawer (it is pulled " + "out towards the robot), and close the drawer. When you finish, both bottles must stand upright on the cabinet top, both cubes must be in " + "the closed drawer, the cabinet must still stand where it is, and the gripper must be open and not " + "touching anything. (Each bottle has a round cap; held by its cap, a bottle hangs straight down.)") + instruction_indirect = ("Clean up: set the two tall bottles (the green one and the brown one) upright on the little " + "wooden cabinet, drop the two small cubes (red and blue) into its pulled-out drawer and " + "shut the drawer. In the end both bottles stand on top of the cabinet, the cubes are inside the shut drawer, " + "the cabinet stays in its place, and the open gripper touches nothing. (A bottle held by " + "its round cap hangs straight down.)") + agent_object_names = ["green bottle (yellow round cap)", "brown bottle (blue round cap)", "red cube", "blue cube", + "small wooden cabinet with its drawer pulled out (the drawer front faces the robot)"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + cab = register_generated("LffLhdCabinet", cabinet_xml(CAB_MODEL)) + objs = [(CAB, cab, "cabinet_region", (0.10, -0.02, 0.12, 0.0))] + for i, b in enumerate(BOTTLES): + c = B_NAME[b] + cat = register_generated(f"LffLhdBottle{c.title()}", bottle_xml(f"lff_lhd_bottle_{c}", B_RGBA[b], CAP_RGBA[b])) + objs.append((b, cat, f"{c}_bottle_region", (-0.30, 0.20 + 0.13 * i, -0.28, 0.22 + 0.13 * i))) + for i, n in enumerate(CUBES): + c = CUBE_COLOR[n] + cat = register_generated(f"LffLhdCube{c.title()}", + box_xml(f"lff_lhd_cube_{c}", (CUBE_E / 2,) * 3, CUBE_RGBA[c], density=CUBE_DENS, + friction=(0.8, 0.005, 0.0001))) + objs.append((n, cat, f"{c}_cube_region", (-0.30, -0.45 + 0.13 * i, -0.28, -0.43 + 0.13 * i))) + return write_bddl(self.name, "tidy up the table", objs, []) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + pre = f"{CAB}_{CAB_MODEL}" + self.jid = m.joint_name2id(pre + "_slide") + self.qa = int(m.jnt_qposadr[self.jid]) + self.dof = int(m.jnt_dofadr[self.jid]) + self.cab_bid = envs.body_id(self.env, CAB) + self.drawer_bid = m.body_name2id(f"{CAB}_drawer") + # the cabinet's free joint is the LAST of its joints (robosuite appends it after the drawer slide), so + # envs.free_joint_addr / place_upright (joints[0]) must not be used for it + fj = m.joint_name2id(self.env.objects_dict[CAB].joints[-1]) + assert int(m.jnt_type[fj]) == 0 + self.cab_qa, self.cab_da = int(m.jnt_qposadr[fj]), int(m.jnt_dofadr[fj]) + self.feet_gid = m.geom_name2id(pre + "_bottom") + self.cab_gids = {g for g in range(m.ngeom) if m.geom_bodyid[g] in (self.cab_bid, self.drawer_bid) + and m.geom_contype[g] != 0} + self.bottle_gids = {b: set(envs.obj_geom_ids(self.env, b)) for b in BOTTLES} + self.cube_gids = {c: set(envs.obj_geom_ids(self.env, c)) for c in CUBES} + self.cap_gid = {b: m.geom_name2id(f"{b}_lff_lhd_bottle_{B_NAME[b]}_cap") for b in BOTTLES} + # per-geom lookup tables for the substep contact scan + self.part = np.zeros(m.ngeom, int) # 1 = hand / fingers, 2 = arm links + for g in envs.robot_geom_ids(self.env): + n = m.geom_id2name(g) or "" + self.part[g] = 1 if n.startswith("gripper0_") else 2 + self.bidx = np.full(m.ngeom, -1, int) + for i, b in enumerate(BOTTLES): + self.bidx[list(self.bottle_gids[b])] = i + self.task_obj = np.zeros(m.ngeom, bool) + for s in list(self.bottle_gids.values()) + list(self.cube_gids.values()) + [self.cab_gids]: + self.task_obj[list(s)] = True + self.catch = dict(force=0.0, zone=ZONE, damp=0.0) + sim = self.env.sim + if not getattr(sim, "_lhd_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lhd_task", None) + if t is not None: + t._substep() + sim.step = step + sim._lhd_wrapped = True + sim._lhd_task = self + self.inst = None + self.mon = None + self.sk = None + self._sub = {} + + # ------------------------------------------------------------ drawer mechanism (every MuJoCo substep) + def q(self): + return float(self.env.sim.data.qpos[self.qa]) + + def catch_force(self, q, qd): + """generalised force on the slide (positive = opening): inside the last ZONE of travel a constant pull towards + closed (ramped in over 5 mm), plus a damper on closing motion for soft-close drawers""" + c = self.catch + z = c["zone"] + if q >= z or c["force"] <= 0: + return 0.0 + ramp = float(np.clip((z - q) / 0.005, 0.0, 1.0)) + f = -c["force"] * ramp + if qd < 0 and c["damp"] > 0: + f -= c["damp"] * qd * ramp + return f + + def _substep(self): + d = self.env.sim.data + q, qd = float(d.qpos[self.qa]), float(d.qvel[self.dof]) + d.qfrc_applied[self.dof] = self.catch_force(q, qd) + if self.mon is None: + return + sub = self._sub + # slam detection: the closing speed just before the drawer reaches its stop + if q > 0.002: + sub["approach_v"] = -qd + sub["armed"] = True + if q < self.catch["zone"] and sub.get("zone_xy") is None: + sub["zone_xy"] = self.cab_xy().tolist() + elif q > self.catch["zone"] + 0.005: + sub["zone_xy"] = None + elif sub.get("armed"): + sub["armed"] = False + v = float(sub.get("approach_v", 0.0)) + sub.setdefault("impacts", []).append((v, sub.get("zone_xy"))) + sub["zone_xy"] = None + n = d.ncon + if not n: + return + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + for a, b in zip(g1, g2): + ia, ib = self.bidx[a], self.bidx[b] + if ia < 0 and ib < 0: + continue + if ia >= 0 and ib >= 0: + if ia != ib: + sub.setdefault("bb", set()).update((int(ia), int(ib))) + continue + i, o = (ia, b) if ia >= 0 else (ib, a) + p = int(self.part[o]) + if p: + r = sub.setdefault("rob", {}) + r[int(i)] = 2 if (p == 2 or r.get(int(i)) == 2) else 1 + + # ------------------------------------------------------------ instances + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + slam = bool((int(seed) * 7) % 20 < round(20 * P_SLAM)) # balanced: 14 of every 20 consecutive seeds + cx, cy = float(rng.uniform(-0.13, -0.10)), float(rng.uniform(-0.04, 0.04)) + s = 1.0 if rng.random() < 0.5 else -1.0 # bottles on the left (+1) or right (-1), cubes on the other side + bottles = {} + order = rng.permutation(2) + for j, i in enumerate(order): + bx = cx + (-0.05, 0.05)[j] + float(rng.uniform(-0.01, 0.01)) + bottles[BOTTLES[i]] = [bx, cy + s * float(rng.uniform(0.21, 0.24))] + perm = rng.permutation(2) + # cubes 25-29 cm to the side of the cabinet's centre line: picked from nearer, the forearm sweeps over the + # cabinet top and knocks the bottles standing there (measured feasibility map, see the task card) + cubes = {CUBES[i]: [cx + (-0.16, -0.04)[j] + float(rng.uniform(-0.01, 0.01)), + cy - s * float(rng.uniform(0.25, 0.29))] for j, i in enumerate(perm)} + force = float(rng.uniform(*F_SPRING)) + soft_v = float(rng.uniform(*SOFT_V)) + return dict(seed=int(seed), self_closing=slam, drawer="self-closing" if slam else "soft-close", + cab_xy=[cx, cy], bottle_side="left" if s > 0 else "right", bottle_start=bottles, + bottle_yaw={b: float(rng.uniform(-0.3, 0.3)) for b in BOTTLES}, cube_start=cubes, + cube_yaw={c: float(rng.uniform(-0.3, 0.3)) for c in CUBES}, + spring_n=force, damp=0.0 if slam else force / soft_v, + carcass_kg=float(rng.uniform(*CARCASS_MASS)), feet_mu=float(rng.uniform(*FEET_MU)), + naive_noise_seed=int(rng.integers(1 << 30))) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + M = float(inst["carcass_kg"]) + m.body_mass[self.cab_bid] = M + m.body_inertia[self.cab_bid] = [M * (CW ** 2 + CH ** 2) / 12, M * (CD ** 2 + CH ** 2) / 12, + M * (CD ** 2 + CW ** 2) / 12] + m.geom_friction[self.feet_gid] = [float(inst["feet_mu"]), 0.005, 0.0001] + m.geom_priority[self.feet_gid] = 3 + self.catch = dict(force=float(inst["spring_n"]), zone=ZONE, damp=float(inst["damp"])) + self.set_drawer(Q_OPEN) + self.place_cabinet(inst["cab_xy"], 0.0) + for b in BOTTLES: + envs.place_upright(self.env, b, inst["bottle_start"][b], yaw=inst["bottle_yaw"][b], clearance=0.0005) + for c in CUBES: + envs.place_upright(self.env, c, inst["cube_start"][c], yaw=inst["cube_yaw"][c], clearance=0.001) + + def set_drawer(self, q): + d = self.env.sim.data + d.qpos[self.qa] = q + d.qvel[self.dof] = 0.0 + + def place_cabinet(self, xy, yaw=0.0, clearance=0.0005): + d = self.env.sim.data + a, v = self.cab_qa, self.cab_da + d.qpos[a:a + 3] = [xy[0], xy[1], Z + clearance] # body origin = bottom of the carcass + d.qpos[a + 3:a + 7] = [np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)] + d.qvel[v:v + 6] = 0.0 + self.env.sim.forward() + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = DrawerSkills(self.env, self, recorder=recorder) + self._sub = {} + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ geometry helpers (world frame) + def cab_R(self): + return self.env.sim.data.body_xmat[self.cab_bid].reshape(3, 3).copy() + + def cab_origin(self): + return self.env.sim.data.body_xpos[self.cab_bid].copy() + + def cab_xy(self): + return self.cab_origin()[:2] + + def to_cab(self, p): + """world point -> cabinet frame (x forward, origin at the footprint centre on the floor)""" + return self.cab_R().T @ (np.asarray(p, float) - self.cab_origin()) + + def from_cab(self, p): + return self.cab_origin() + self.cab_R() @ np.asarray(p, float) + + def top_z(self): + return float(self.from_cab([0.0, 0.0, CH])[2]) + + def cab_front_x(self): + """world x of the carcass's front face (cabinet assumed close to yaw 0)""" + return float(self.from_cab([-CD / 2, 0.0, 0.0])[0]) + + def drawer_front_x(self): + """world x of the drawer front panel's outer face""" + return self.cab_front_x() - self.q() - PF + + def cab_tilt(self): + return float(np.arccos(np.clip(self.cab_R()[2, 2], -1.0, 1.0))) + + def cab_moved(self): + return float(np.linalg.norm(self.cab_xy() - np.asarray(self.inst["cab_xy"]))) + + def R(self, name): + return self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3).copy() + + def tilt(self, name): + return float(np.arccos(np.clip(self.R(name)[2, 2], -1.0, 1.0))) + + def bottle_base(self, b): + """world position of the centre of the bottle's bottom face""" + return envs.obj_pos(self.env, b) - self.R(b)[:, 2] * H_TOT / 2 + + def cap_xyz(self, b): + return self.env.sim.data.geom_xpos[self.cap_gid[b]].copy() + + def held(self, name): + return self.sk is not None and self.sk.holding(name) + + # ------------------------------------------------------------ stage predicates + def bottle_on_top(self, b, tol=0.0, tilt=UPRIGHT): + if self.tilt(b) > tilt or self.held(b): + return False + c = self.to_cab(self.bottle_base(b)) + if c[0] < -CD / 2 + RF - tol or c[0] > CD / 2 - RAIL_T - RF + tol or abs(c[1]) > CW / 2 - RF + tol: + return False + return bool(-0.006 <= c[2] - CH <= 0.012) + + def cube_in_drawer(self, c): + """cube centre inside the drawer box (drawer frame), its footprint within the walls (+3 mm), resting low enough + to pass under the cabinet top; not held""" + if self.held(c): + return False + d = self.env.sim.data + Rd = d.body_xmat[self.drawer_bid].reshape(3, 3) + p = Rd.T @ (envs.obj_pos(self.env, c) - d.body_xpos[self.drawer_bid]) + x0 = -CD / 2 + e = CUBE_E / 2 * 1.2 # footprint half size (a yawed cube reaches a little farther) + tol = 0.003 + return bool(x0 + e - tol <= p[0] <= x0 + D_IN_X - e + tol and abs(p[1]) <= D_IN_Y - e + tol + and FLOOR_TOP - 0.005 <= p[2] - CUBE_E / 2 <= FLOOR_TOP + DWH + 0.01) + + def drawer_closed(self): + return self.q() <= CLOSED + + def stage_keys(self): + return [f"{B_NAME[b]}_bottle_on_top" for b in BOTTLES] + [f"{CUBE_COLOR[c]}_cube_in_drawer" for c in CUBES] + [ + "drawer_closed"] + + def stage_values(self, hyst=None): + hyst = hyst or {} + v = {} + for b in BOTTLES: + k = f"{B_NAME[b]}_bottle_on_top" + v[k] = self.bottle_on_top(b, 0.003, UPRIGHT + np.radians(3.0)) if hyst.get(k) else self.bottle_on_top(b) + for c in CUBES: + v[f"{CUBE_COLOR[c]}_cube_in_drawer"] = self.cube_in_drawer(c) + v["drawer_closed"] = self.q() <= (CLOSED + 0.003 if hyst.get("drawer_closed") else CLOSED) + return v + + # ------------------------------------------------------------ per-step monitor + def _init_monitor(self): + keys = self.stage_keys() + st = {k: False for k in keys} + self.mon = dict(state=st, ever=[], lost=[], lost_cause={}, events=[], cand={k: 0 for k in keys}, step=0, + last_robot=[None, None], last_bb=None, slams=[], standing_since=[None, None], + fall_start=[None, None], touched_before_fall=[False, False], max_tilt=[0.0, 0.0], + n_fallen=0, fallen=[False, False]) + + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + mon["step"] += 1 + t = int(self.sk.n_steps) + sub, self._sub = self._sub, {k: v for k, v in self._sub.items() if k in ("approach_v", "armed", "zone_xy")} + for i, part in sub.get("rob", {}).items(): + b = BOTTLES[i] + if not self.held(b): + mon["last_robot"][i] = ["hand" if part == 1 else "arm", t, round(float(np.degrees(self.tilt(b))), 1)] + if sub.get("bb"): + mon["last_bb"] = t + for v, zxy in sub.get("impacts", []): + if v >= V_SLAM: + lurch = None + if zxy is not None: + dxy = self.cab_xy() - np.asarray(zxy) + lurch = [round(100 * float(dxy[0]), 2), round(100 * float(dxy[1]), 2)] + on = [B_NAME[b] for b in BOTTLES if mon["state"][f"{B_NAME[b]}_bottle_on_top"]] + e = dict(event="drawer_slam", step=t, speed_mps=round(float(v), 2), cabinet_jerk_cm=lurch, + bottles_on_top=on, bottles_fell=[], robot_touched_before_fall=[]) + mon["events"].append(e) + mon["slams"].append(e) + else: + mon["events"].append(dict(event="drawer_shut", step=t, speed_mps=round(float(v), 3))) + # fall tracking (R4: did the robot touch a bottle before it started to fall?) + for i, b in enumerate(BOTTLES): + tl = self.tilt(b) + mon["max_tilt"][i] = max(mon["max_tilt"][i], float(np.degrees(tl))) + if self.held(b): + mon["standing_since"][i] = None + continue + if tl < np.radians(3.0): + if mon["standing_since"][i] is None: + mon["standing_since"][i] = t + mon["fall_start"][i] = None + elif tl > TILT_START and mon["standing_since"][i] is not None and mon["fall_start"][i] is None: + mon["fall_start"][i] = t + lr = mon["last_robot"][i] + mon["touched_before_fall"][i] = bool(lr is not None and t - lr[1] <= 20 and lr[2] < np.degrees(TILT_START)) + if not mon["fallen"][i] and tl > FALLEN: + mon["fallen"][i] = True + mon["n_fallen"] += 1 + mon["events"].append(dict(event="bottle_fell", bottle=B_NAME[b], step=t, cause=self._cause(i, t), + robot_touched_before_fall=bool(mon["touched_before_fall"][i]), + direction=self._fall_dir(b))) + elif mon["fallen"][i] and tl < UPRIGHT: + mon["fallen"][i] = False + if mon["step"] % 2: + return + vals = self.stage_values(hyst=mon["state"]) + for k, now in vals.items(): + self._check(k, now, t) + + def _fall_dir(self, b): + ax = self.R(b)[:2, 2] + if np.linalg.norm(ax) < 0.2: + return "none" + return ("forward" if ax[0] > 0 else "backward") if abs(ax[0]) >= abs(ax[1]) else ("left" if ax[1] > 0 else "right") + + def _cause(self, i, t): + """why bottle i left the cabinet top""" + b = BOTTLES[i] + mon = self.mon + if self.held(b): + return "picked_up" + lr = mon["last_robot"][i] + robot_recent = lr is not None and t - lr[1] <= WIN_ROBOT + if robot_recent and mon["touched_before_fall"][i]: + return f"robot_{lr[0]}" + if robot_recent and lr[2] < np.degrees(TILT_START): + return f"robot_{lr[0]}" + if mon["slams"] and t - mon["slams"][-1]["step"] <= WIN_SLAM: + return "drawer_slam" + if mon["last_bb"] is not None and t - mon["last_bb"] <= WIN_ROBOT: + return "bottle" + if robot_recent: + return f"robot_{lr[0]}" + return "other" + + def _check(self, key, now, t): + mon = self.mon + if now == mon["state"][key]: + mon["cand"][key] = 0 + return + mon["cand"][key] += 2 + if mon["cand"][key] < DEBOUNCE: + return + mon["cand"][key] = 0 + mon["state"][key] = now + t0 = int(t - DEBOUNCE + 1) + if now: + restored = key in mon["lost"] + e = dict(stage=key, event="restored" if restored else "achieved", step=t0) + if restored: + e["after"] = mon["lost_cause"].get(key) + mon["lost"].remove(key) + if key not in mon["ever"]: + mon["ever"].append(key) + mon["events"].append(e) + return + if key not in mon["ever"]: + return + if key.endswith("bottle_on_top"): + i = [f"{B_NAME[b]}_bottle_on_top" for b in BOTTLES].index(key) + cause = self._cause(i, t) + if cause == "drawer_slam": + s = mon["slams"][-1] + if B_NAME[BOTTLES[i]] not in s["bottles_fell"]: + s["bottles_fell"].append(B_NAME[BOTTLES[i]]) + s["robot_touched_before_fall"].append(bool(mon["touched_before_fall"][i])) + elif key == "drawer_closed": + cause = "opened" + else: + c = CUBES[[f"{CUBE_COLOR[x]}_cube_in_drawer" for x in CUBES].index(key)] + cause = "picked_up" if self.held(c) else "other" + if key not in mon["lost"]: + mon["lost"].append(key) + mon["lost_cause"][key] = cause + mon["events"].append(dict(stage=key, event="lost", step=t0, cause=cause)) + + def _finalize_monitor(self, vals): + """close the event log at finish: a stage the debounced monitor still holds but the final judge does not (or + vice versa) is logged now (final=True)""" + mon = self.mon + t = int(self.sk.n_steps) + for k, now in vals.items(): + if now == mon["state"][k]: + continue + n0 = len(mon["events"]) + mon["cand"][k] = DEBOUNCE # force the transition + self._check(k, now, t + DEBOUNCE - 1) + if len(mon["events"]) > n0: + mon["events"][-1]["final"] = True + + # ------------------------------------------------------------ outcome + def _static(self): + d = self.env.sim.data + for n in BOTTLES + CUBES: + _, da = envs.free_joint_addr(self.env, n) + if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5: + return False + v = self.cab_da + return bool(np.linalg.norm(d.qvel[v:v + 3]) < 0.02 and abs(float(d.qvel[self.dof])) < 0.02) + + def robot_touching(self): + d = self.env.sim.data + out = set() + for j in range(d.ncon): + c = d.contact[j] + for a, b in ((c.geom1, c.geom2), (c.geom2, c.geom1)): + if self.part[a] and self.task_obj[b]: + out.add("a bottle" if self.bidx[b] >= 0 else "the cabinet" if b in self.cab_gids else "a cube") + return sorted(out) + + def outcome(self, inst): + sk = self.sk + sk.hold(10) + touching = set() + for _ in range(20): + sk.hold(1) + touching.update(self.robot_touching()) + touching = sorted(touching) + static = self._static() + vals = self.stage_values() + held = [n for n in BOTTLES + CUBES if self.held(n)] + cab_ok = bool(self.cab_tilt() <= CAB_TILT_MAX and self.cab_moved() <= CAB_MOVE_MAX) + grip_open = bool(sk.grip < 0) + self._finalize_monitor(vals) + mon = self.mon + ev = list(mon["events"]) + success = bool(all(vals.values()) and cab_ok and static and not held and not touching and grip_open) + lost = [e for e in ev if e.get("event") == "lost"] + regress = [e for e in lost if e.get("cause") != "picked_up"] + restored = [e for e in ev if e.get("event") == "restored" and e.get("after") != "picked_up"] + slams = [e for e in ev if e.get("event") == "drawer_slam"] + slam_losses = [e for e in lost if e.get("cause") == "drawer_slam"] + trap = bool(slam_losses) + bkeys = [f"{B_NAME[b]}_bottle_on_top" for b in BOTTLES] + never_bottle = [B_NAME[b] for b, k in zip(BOTTLES, bkeys) if not vals[k] and k not in mon["ever"]] + lost_bottle = [B_NAME[b] for b, k in zip(BOTTLES, bkeys) if not vals[k] and k in mon["ever"]] + cubes_out = [CUBE_COLOR[c] for c in CUBES if not vals[f"{CUBE_COLOR[c]}_cube_in_drawer"]] + if success: + failure = "none" + elif held: + failure = "held" + elif not cab_ok: + failure = "cabinet_moved" + elif lost_bottle: + failure = "bottle_knocked" + elif never_bottle: + failure = "bottle_not_on_top" + elif cubes_out: + failure = "cube_not_in_drawer" + elif not vals["drawer_closed"]: + failure = "drawer_open" + elif touching: + failure = "touching" + elif not grip_open: + failure = "gripper_closed" + else: + failure = "not_static" + detail = self._detail(vals, held, touching, cab_ok, static, grip_open, success, ev) + return dict(success=success, failure=failure, stages=vals, events=ev, n_regressions=len(regress), + n_lost=len(lost), n_restored=len(restored), trap_fired=trap, + recovered_in_attempt=bool(trap and success), n_slams=len(slams), + slam_speeds=[e["speed_mps"] for e in slams], slam_jerk_cm=[e["cabinet_jerk_cm"] for e in slams], + bottles_lost_to_slam=sorted({e["stage"].split("_")[0] for e in slam_losses}), + robot_touched_before_fall=[bool(x) for x in mon["touched_before_fall"]], + bottle_max_tilt_deg=[round(x, 1) for x in mon["max_tilt"]], n_fallen=mon["n_fallen"], + held=held, touching=touching, static=bool(static), gripper_open=grip_open, + drawer_q_cm=round(100 * self.q(), 2), cabinet_moved_cm=round(100 * self.cab_moved(), 2), + cabinet_tilt_deg=round(float(np.degrees(self.cab_tilt())), 1), + bottle_tilts_deg={B_NAME[b]: round(float(np.degrees(self.tilt(b))), 1) for b in BOTTLES}, + self_closing=bool(inst["self_closing"]), detail=detail) + + def _detail(self, vals, held, touching, cab_ok, static, grip_open, success, ev): + parts = [] + if success: + parts.append("Both bottles stand on the cabinet, the two cubes are in the closed drawer.") + top_c = self.from_cab([0.0, 0.0, CH]) + for b in BOTTLES: + k = f"{B_NAME[b]}_bottle_on_top" + if vals[k]: + continue + nm = B_NAME[b] + if b in held: + parts.append(f"The {nm} bottle is still held by the gripper.") + continue + tl = float(np.degrees(self.tilt(b))) + base = self.bottle_base(b) + rel = base - top_c + on_top = abs(float(rel[2])) < 0.03 + ax = self.R(b)[:, 2] + where = f"its base is {_fb(rel[0])} and {_lr(rel[1])} of the centre of the cabinet top" + if tl <= np.degrees(UPRIGHT): + txt = (f"The {nm} bottle stands but not on the cabinet top: {where}." if not on_top else + f"The {nm} bottle stands with part of its base over the edge of the cabinet top: {where}.") + elif on_top and ax[0] > 0.3 and self.to_cab(self.cap_xyz(b))[0] > CD / 2 - RAIL_T: + txt = (f"The {nm} bottle has tipped over forward on the cabinet top and leans {tl:.0f} degrees against " + f"the rail along the top's far edge; {where}.") + elif on_top: + txt = f"The {nm} bottle has tipped over on the cabinet top ({tl:.0f} degrees); {where}." + elif base[2] < Z + 0.03: + txt = f"The {nm} bottle has fallen over and lies on the table; {where}." + else: + txt = f"The {nm} bottle has fallen over and leans {tl:.0f} degrees against something; {where}." + lost = [e for e in ev if e.get("stage") == k and e.get("event") == "lost"] + if lost: + why = lost[-1].get("cause", "other") + txt += {"drawer_slam": " It had stood on the cabinet top; it fell when the drawer snapped shut and the " + "cabinet jerked.", + "robot_hand": " It had stood on the cabinet top; the gripper knocked it.", + "robot_arm": " It had stood on the cabinet top; the robot's arm knocked it.", + "bottle": " It had stood on the cabinet top; the other bottle knocked it."}.get( + why, " It had stood on the cabinet top earlier.") + parts.append(txt) + for c in CUBES: + if vals[f"{CUBE_COLOR[c]}_cube_in_drawer"]: + continue + nm = CUBE_COLOR[c] + if c in held: + parts.append(f"The {nm} cube is still held by the gripper.") + continue + p = envs.obj_pos(self.env, c) + rel = self.to_cab(p) + if abs(rel[0]) < CD / 2 and abs(rel[1]) < CW / 2 and rel[2] > CH - 0.01: + parts.append(f"The {nm} cube lies on the cabinet top, not in the drawer.") + else: + parts.append(f"The {nm} cube is not in the drawer: it is {_fb(rel[0] + CD / 2)} and {_lr(rel[1])} of the " + f"middle of the cabinet's front.") + if not vals["drawer_closed"]: + parts.append(f"The drawer is still {100 * self.q():.1f} cm open.") + if not cab_ok: + if self.cab_tilt() > CAB_TILT_MAX: + parts.append("The cabinet has been knocked over.") + else: + parts.append(f"The cabinet was moved {100 * self.cab_moved():.0f} cm from where it stood.") + if not success and all(vals.values()) and cab_ok: + if touching: + parts.append("The gripper is still touching " + " and ".join(touching) + ".") + elif not grip_open: + parts.append("The gripper is closed.") + elif not static: + parts.append("Something was still moving.") + slams = [e for e in ev if e.get("event") == "drawer_slam" and e.get("bottles_fell")] + if slams and success: + parts.append("(The drawer snapped shut and knocked bottles off the cabinet; they were stood up again.)") + return " ".join(parts) + + # ------------------------------------------------------------ scripted primitives (move_to + gripper only) + def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300): + return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + + def _lift_to(self, z, speed=0.15): + cur = self.sk.eef_pos() + if cur[2] < z - 0.005: + self._go([cur[0], cur[1], z], speed=speed) + + def _settle(self, name, max_checks=25): + d = self.env.sim.data + _, da = envs.free_joint_addr(self.env, name) + for _ in range(max_checks): + if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2: + return + self.sk.hold(2) + + def _box_yaw(self, name): + R = self.R(name) + i = int(np.argmin(np.abs(R[2]))) + yaw = float(np.arctan2(R[1, i], R[0, i])) + y = float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4) + cands = [y + k * np.pi / 2 for k in (-1, 0, 1)] + return min(cands, key=lambda c: abs(c - self.sk.yaw) if abs(c) <= np.pi / 2 else 9.0) + + def pick_bottle(self, b, grasp="neck", z_clear=0.05, yaw=None, v=0.15): + """Sonnet-like pick of a standing bottle from above: over it, straight down, close, lift until its bottom + clears the cabinet top by z_clear. grasp: neck (1 cm below its top; the body cannot be reached from above, the + palm would land on the cap) | cap (the bottle then hangs from a pivot)""" + sk = self.sk + self._settle(b) + p = envs.obj_pos(self.env, b) + bot = self.bottle_base(b)[2] + zg = {"neck": bot + NECK_GRASP, "cap": bot + CAP_Z}[grasp] + yaw = self._box_yaw(b) if yaw is None else yaw + sk.set_gripper(False, steps=8) + top = bot + H_TOT + self.transit(p[:2], top + 0.06, yaw=yaw, v=v) + self._go([p[0], p[1], zg + 0.015], speed=0.1) + self._go([p[0], p[1], zg], speed=0.04, tol=0.003, max_steps=150) + sk.set_gripper(True, steps=15) + lift = self.top_z() + z_clear + (zg - bot) + self._go([p[0], p[1], lift], speed=0.10) + sk.hold(5) + if not self.held(b): + sk.set_gripper(False, steps=8) + return False + return True + + def put_bottle(self, b, xy, gap=0.01, z_clear=0.05, v=0.12, settle=15): + """carry the held bottle over xy (its axis, not the grasp point), straight down until its bottom is `gap` above + the cabinet top, let go, lift""" + sk = self.sk + rel = envs.obj_pos(self.env, b)[:2] - sk.eef_pos()[:2] + q = np.asarray(xy, float) - rel + zc = self.top_z() + z_clear + (sk.eef_pos()[2] - self.bottle_base(b)[2]) + self.transit(q, zc, v=v, carried=b, margin=z_clear) + sk.hold(settle) + rel = envs.obj_pos(self.env, b)[:2] - sk.eef_pos()[:2] + q = np.asarray(xy, float) - rel + dz = sk.eef_pos()[2] - envs.obj_min_z(self.env, b) + zr = self.top_z() + dz + gap + self._go([q[0], q[1], zr + 0.02], speed=0.08) + self._go([q[0], q[1], zr], speed=0.03, tol=0.003, max_steps=150) + sk.hold(5) + sk.set_gripper(False, steps=12) + cur = sk.eef_pos() + self._go([cur[0], cur[1], self.top_z() + H_TOT + 0.06], speed=0.08) + self._settle(b) + + def obstacle_top(self, p0, p1, ignore=(), r=0.09): + """highest top (world z) of standing bottles within r of the straight path p0 -> p1 (xy), and of the cabinet + top if the path passes over it (expanded by 4 cm)""" + a, b = np.asarray(p0, float)[:2], np.asarray(p1, float)[:2] + ab = b - a + L2 = max(float(ab @ ab), 1e-9) + + def dist(q): + u = float(np.clip((q - a) @ ab / L2, 0.0, 1.0)) + return float(np.linalg.norm(a + u * ab - q)) + top = Z + for o in BOTTLES: + if o in ignore or self.held(o): + continue + if dist(envs.obj_pos(self.env, o)[:2]) < r: + top = max(top, envs.obj_max_z(self.env, o)) + for u in np.linspace(0.0, 1.0, 21): + c = self.to_cab(np.r_[a + u * ab, Z]) + if abs(c[0]) < CD / 2 + 0.04 + PF + max(self.q(), 0.0) and abs(c[1]) < CW / 2 + 0.04: + top = max(top, self.top_z() + RAIL_H) + break + return top + + def transit(self, xy, z_min, yaw=None, v=0.15, carried=None, margin=0.06): + """Sonnet-like transit: up (to clear what is in the way), straight across, the caller then goes down""" + sk = self.sk + cur = sk.eef_pos() + obst = self.obstacle_top(cur, xy, ignore=(carried,) if carried else ()) + below = (sk.eef_pos()[2] - envs.obj_min_z(self.env, carried)) if carried else 0.03 + zt = max(cur[2], z_min, obst + margin + below) + if cur[2] < zt - 0.005: + self._go([cur[0], cur[1], zt], speed=v) + self._go([xy[0], xy[1], zt], yaw=yaw, speed=v) + + def pick_cube(self, c, z_carry=0.15, v=0.15): + sk = self.sk + for _ in range(2): + self._settle(c) + p = envs.obj_pos(self.env, c) + yaw = self._box_yaw(c) + sk.set_gripper(False, steps=8) + self.transit(p[:2], Z + z_carry, yaw=yaw, v=v) + self._go([p[0], p[1], p[2] + 0.015], speed=0.1) + self._go([p[0], p[1], p[2]], speed=0.04, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + self._go([p[0], p[1], max(Z + z_carry, sk.eef_pos()[2])], speed=v) + if self.held(c): + return True + sk.set_gripper(False, steps=8) + return False + + def drawer_slot(self, k, noise=None): + """world xy of cube slot k (0..1) in the exposed part of the open drawer: a column along the drawer's middle + (with the wrist at yaw 0 the open fingers, 13.2 cm across, stay clear of the side walls and of the cube + already in; the palm, 3.9 cm ahead of the grasp point, stays clear of the carcass; the far slot first)""" + q = min(self.q(), Q_OPEN) + x = self.cab_front_x() - 0.045 - k * (q - 0.070) + y = self.cab_xy()[1] + out = np.array([x, y]) + return out + (np.asarray(noise, float) if noise is not None else 0.0) + + def put_cube(self, c, xy, gap=0.02, z_carry=0.15, v=0.15): + sk = self.sk + self.transit(xy, Z + z_carry, yaw=0.0, v=v, carried=c, margin=0.04) + zr = Z + FLOOR_TOP + CUBE_E / 2 + gap + self._go([xy[0], xy[1], zr + 0.015], speed=0.1) + self._go([xy[0], xy[1], zr], speed=0.04, tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + self._go([xy[0], xy[1], Z + z_carry], speed=v) + self._settle(c) + + def close_drawer(self, v=0.04, z_push=0.05, overshoot=0.0, y_off=0.0, approach=0.03): + """closed gripper in front of the drawer, then a straight push forward to where the front panel is flush""" + sk = self.sk + y = self.cab_xy()[1] + y_off + xs = self.drawer_front_x() - FINGER_AHEAD - approach + x_end = self.cab_front_x() - PF - FINGER_AHEAD + overshoot + sk.set_gripper(True, steps=10) + cur = sk.eef_pos() + self._go([cur[0], cur[1], max(cur[2], Z + 0.15)], speed=0.15) + self._go([xs, y, Z + 0.15], yaw=0.0, speed=0.15) + self._go([xs, y, Z + z_push], speed=0.1, tol=0.003) + self._go([x_end, y, Z + z_push], speed=v, tol=0.003, max_steps=int(0.25 / max(v, 0.01) / 0.05) + 60) + self.sk.hold(10) + cur = sk.eef_pos() + self._go([cur[0] - 0.06, cur[1], cur[2]], speed=0.08) + self._go([cur[0] - 0.06, cur[1], Z + 0.20], speed=0.15) + sk.hold(10) + + def top_spots(self, mode="pair", noise=None): + """world xy targets on the cabinet top for the two bottles (left one first): side by side across the middle""" + c = self.from_cab([0.0, 0.0, CH])[:2] + spots = [c + np.array([0.0, 0.05]), c + np.array([0.0, -0.05])] + if noise is not None: + spots = [s + np.asarray(n, float) for s, n in zip(spots, noise)] + return spots + + def free_top_spot(self, b, start=None): + """a spot on the cabinet top (cabinet frame candidates) at least 6.5 cm from the other bottle if that one stands + on the top, and -- if `start` (xy the bottle comes from) is given -- whose straight path from `start` passes + farthest from it""" + other = [o for o in BOTTLES if o != b][0] + cands = [np.array([dx, dy]) for dx in (0.0, -0.03, 0.03) for dy in (0.055, -0.055, 0.0)] + ok_other = self.bottle_on_top(other, 0.01, np.radians(20)) + oc = self.to_cab(self.bottle_base(other))[:2] + if not ok_other: + return self.from_cab([cands[0][0], cands[0][1], CH])[:2] if start is None else min( + (self.from_cab([c[0], c[1], CH])[:2] for c in cands[:2]), + key=lambda w: float(np.linalg.norm(w - np.asarray(start)[:2]))) + best, score = None, -1.0 + st = None if start is None else self.to_cab(np.r_[np.asarray(start)[:2], Z])[:2] + for c in cands: + if np.linalg.norm(c - oc) < 0.065: + continue + if st is None: + return self.from_cab([c[0], c[1], CH])[:2] + ab = c - st + u = float(np.clip((oc - st) @ ab / max(float(ab @ ab), 1e-9), 0.0, 1.0)) + clear = float(np.linalg.norm(st + u * ab - oc)) + if clear > score: + best, score = c, clear + if best is None: + best = max(cands, key=lambda c: float(np.linalg.norm(c - oc))) + return self.from_cab([best[0], best[1], CH])[:2] + + def restand_bottle(self, b, xy=None): + """stand a fallen bottle up again on the cabinet top: grasp the ball cap from above (fingers across the lying + bottle's axis), lift until it hangs free with its bottom above the gallery rail, carry it over a free spot, + lower until the bottom is ~3 mm above the top, let go. Returns True if it stands on the top.""" + sk = self.sk + self._settle(b) + for _ in range(2): + if _reach(self.cap_xyz(b)) > REACH_MAX and self.tilt(b) > FALLEN: + self.pull_in_bottle(b) + k = self.cap_xyz(b) + ax = self.R(b)[:2, 2] + yaw = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else sk.yaw # finger axis across it + sk.set_gripper(False, steps=8) + self.transit(k[:2], k[2] + 0.08, yaw=yaw, v=0.15) + sk.hold(5) + k = self.cap_xyz(b) + self._go([k[0], k[1], k[2] + 0.015], speed=0.1) + self._go([k[0], k[1], k[2]], speed=0.04, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + if not self.held(b): + sk.set_gripper(False, steps=8) + self._go([k[0], k[1], k[2] + 0.08], speed=0.1) + continue + zl = self.top_z() + RAIL_H + 0.03 + CAP_Z + self._go([k[0], k[1], zl], speed=0.10) + sk.hold(15) + tx, ty = self.free_top_spot(b, start=k[:2]) if xy is None else xy + self._go([tx, ty, zl], speed=0.10) + sk.hold(30) + self._go([tx, ty, self.top_z() + CAP_Z + 0.015], speed=0.08) + self._go([tx, ty, self.top_z() + CAP_Z + 0.003], speed=0.03, tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + self._go([tx, ty, self.top_z() + H_TOT + 0.04], speed=0.08) + sk.hold(20) + self._settle(b) + if self.bottle_on_top(b): + return True + return self.bottle_on_top(b) + + def pull_in_bottle(self, b): + """the lying bottle's cap is out of reach: grasp the body near its bottom end (fingers across it), lift it + 3 cm, pull it towards the robot until the cap is within reach, set it down""" + sk = self.sk + Rb = self.R(b) + ax = Rb[:, 2] + g = envs.obj_pos(self.env, b) - ax * (H_TOT / 2 - 0.04) + zg = max(float(g[2] - Z), 0.02) + yaw = float(np.arctan2(ax[1], ax[0])) + need = _reach(self.cap_xyz(b)) - (REACH_MAX - 0.05) + to_base = np.array([-0.66, 0.0]) - g[:2] + to_base /= max(np.linalg.norm(to_base), 1e-6) + dst = g[:2] + to_base * need + sk.set_gripper(False, steps=8) + self._go([g[0], g[1], Z + 0.15], yaw=yaw, speed=0.15) + self._go([g[0], g[1], Z + zg + 0.015], speed=0.1) + self._go([g[0], g[1], Z + zg], speed=0.04, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + self._go([g[0], g[1], Z + zg + 0.03], speed=0.08) + self._go([dst[0], dst[1], Z + zg + 0.03], speed=0.08) + self._go([dst[0], dst[1], Z + zg + 0.005], speed=0.04) + sk.set_gripper(False, steps=12) + self._go([dst[0], dst[1], Z + 0.15], speed=0.1) + self._settle(b) + + # ------------------------------------------------------------ scripted policies + def check_and_fix(self, params, rounds=2): + """look at every stage at the end: stand fallen bottles up on the top, put stray cubes into the drawer if it is + still open""" + for _ in range(rounds): + v = self.stage_values() + if all(v.values()): + break + for b in BOTTLES: + if not self.bottle_on_top(b): + if self.tilt(b) > UPRIGHT or self.bottle_base(b)[2] < self.top_z() - 0.03: + if self.tilt(b) > UPRIGHT: + self.restand_bottle(b) + elif self.pick_bottle(b, grasp="neck"): + self.put_bottle(b, self.free_top_spot(b), gap=0.005) + if not self.drawer_closed(): + for k, c in enumerate(CUBES): + if not self.cube_in_drawer(c) and self.pick_cube(c): + self.put_cube(c, self.drawer_slot(k)) + if all(self.cube_in_drawer(c) for c in CUBES): + self.close_drawer(v=params.get("push_v", 0.04), z_push=params.get("push_z", 0.05)) + self._lift_to(self.top_z() + 0.15) + self.sk.set_gripper(False, steps=8) + self.sk.hold(10) + + def do_bottles(self, params, rng): + noise = params.get("noise") + spots = self.top_spots(noise=noise) + side = 1.0 if self.inst["bottle_side"] == "left" else -1.0 + spots = sorted(spots, key=lambda q: side * float(q[1])) # the spot farther from the bottles' side first + order = list(BOTTLES) if params.get("bottle_order", "listed") == "listed" else list(BOTTLES)[::-1] + for b, xy in zip(order, spots): + for _ in range(2): + if self.pick_bottle(b, grasp=params.get("grasp", "neck"), z_clear=params.get("z_clear", 0.05)): + self.put_bottle(b, xy, gap=params.get("gap", 0.02), z_clear=params.get("z_clear", 0.05)) + break + + def do_cubes(self, params, rng): + noise = params.get("cube_noise") or [None] * 3 + for k, c in enumerate(self._cube_order()): + if self.pick_cube(c): + self.put_cube(c, self.drawer_slot(k, noise[k]), gap=params.get("cube_gap", 0.02)) + + def _cube_order(self): + """nearest the drawer first""" + d = np.array([self.cab_front_x() - Q_OPEN / 2, self.cab_xy()[1]]) + return sorted(CUBES, key=lambda c: float(np.linalg.norm(envs.obj_pos(self.env, c)[:2] - d))) + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("noise_seed", 0)) + order = params.get("order", "BCD") # B = bottles on top, C = cubes into the drawer, D = close the drawer + for step in order: + if step == "B": + self.do_bottles(params, rng) + elif step == "C": + self.do_cubes(params, rng) + elif step == "D": + self.close_drawer(v=params.get("push_v", 0.04), z_push=params.get("push_z", 0.05), + overshoot=params.get("overshoot", 0.0)) + if params.get("check"): + self.check_and_fix(params) + else: + self._lift_to(self.top_z() + 0.15) + self.sk.set_gripper(False, steps=8) + self.sk.hold(10) + + def _noise(self, rng, err=NAIVE_ERR): + return dict(noise=[rng.uniform(-err, err, 2).tolist() for _ in BOTTLES], + cube_noise=[rng.uniform(-err, err, 2).tolist() for _ in CUBES]) + + def default_params(self, inst): + """Sonnet-like: the order of the instruction (bottles, cubes, drawer); bottles grasped by the body from above, + lifted until they clear the cabinet top by 5 cm, lowered straight down and let go 1-4 cm above it; cubes into + the drawer; the drawer pushed shut slowly (4 cm/s) with the closed gripper; no final look back""" + rng = np.random.default_rng(inst["naive_noise_seed"]) + p = dict(order="BCD", check=False, grasp="neck", gap=float(rng.uniform(0.01, 0.04)), + push_v=float(rng.uniform(0.03, 0.05)), push_z=float(rng.uniform(0.04, 0.06)), + overshoot=float(rng.uniform(0.0, 0.004)), noise_seed=int(inst["naive_noise_seed"])) + p.update(self._noise(rng)) + return p + + def oracle_params(self, inst): + """knows the drawer: cubes in, drawer shut, then the bottles; checks every stage at the end""" + return dict(order="CDB", check=True, grasp="neck", gap=0.008, push_v=0.04, push_z=0.05, overshoot=0.0) + + def adapt_params(self, inst, history): + """attempt >= 2 (after the bottles fell when the drawer was shut): shut the drawer before the bottles go on + top, and look at every stage at the end""" + return dict(self.default_params(inst), order="CDB", check=True) + + def blind_params(self, inst, attempt, rng): + """the natural behaviour with random variations (order of the three sub-tasks, push speed / height, release + height, placement noise), no history, no final look""" + order = str(rng.choice(["BCD", "CBD", "CDB"], p=[0.5, 0.3, 0.2])) + p = dict(order=order, check=False, grasp=str(rng.choice(["neck", "cap"])), gap=float(rng.uniform(0.01, 0.04)), + push_v=float(rng.uniform(0.02, 0.08)), push_z=float(rng.uniform(0.03, 0.07)), + overshoot=float(rng.uniform(0.0, 0.006)), noise_seed=int(rng.integers(1 << 30))) + p.update(self._noise(rng)) + return p + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """oracle / naive: one attempt; adaptive: attempt 1 = naive + a final look that stands fallen bottles up again, + attempts >= 2 drawer first; blind: naive with random variations. + Extra kinds (not in validate's table): switch (naive, then drawer first without a final look), oracle_noise + (oracle with +-5 mm placement noise), naive_slow (naive pushing at the slowest agent speed, 2 cm/s), + naive_check (naive + final look = adaptive's first attempt)""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + single = ("oracle", "naive", "oracle_noise", "naive_slow", "naive_check", "naive_neck", "naive_cap") + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": + params = self.default_params(inst) if a == 0 else dict(self.default_params(inst), order="CDB") + elif kind == "oracle_noise": + params = dict(self.oracle_params(inst), **self._noise(np.random.default_rng(seed * 7 + a), 0.005)) + elif kind == "naive_slow": + params = dict(self.default_params(inst), push_v=0.02) + elif kind == "naive_check": + params = dict(self.default_params(inst), check=True) + elif kind == "naive_neck": + params = dict(self.default_params(inst), grasp="neck") + elif kind == "naive_cap": + params = dict(self.default_params(inst), grasp="cap") + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in single: + break + return history diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_false_bottom_lid.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_false_bottom_lid.py new file mode 100644 index 0000000000000000000000000000000000000000..c5314a649314f9885d502ac3c6c8fb213a78e227 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_false_bottom_lid.py @@ -0,0 +1,954 @@ +"""LH false_bottom_lid: open a lidded wooden box, put a tall red block and two blue cubes in, close the lid -- in half +of the boxes a hidden false bottom makes the box too shallow for the block standing upright, so the lid comes down on +the block and stays open; the block must be laid on its side. + +Family: long-horizon common sense + self-disturbance ("state_restoration"): the agent's own normal action (placing the +block upright, as it was found) makes the last stage (lid closed) impossible; it has to notice the blocked lid, take +the block out again, lay it down and close the lid (within an attempt), or lay the block down from the start in this +box (across attempts). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a wooden box (fixture): outer 20.6 cm (forward-back) x 13.6 cm (left-right) x 9 cm high, walls 0.8 cm; the + inside is pure black and matte (walls' inner faces, floor and false bottom). The lid (0.6 cm, wood, 0.15 kg) is + hinged along the box's left or right long edge; a black ball knob sticks out of the middle of the opposite edge. + Opened past upright the lid falls over to the hinge side and hangs on its stop (182-192 deg) just below + horizontal beside the box, below every transit; + * a red block 4 x 4 x 7.5 cm standing upright and two 4 cm blue cubes, in a row in front of the box (robot side), + on 3 of 4 slots 16 cm apart. + +Hidden variable: the box's inner depth. With a false bottom (10 of every 20 consecutive seeds) the floor is 4.5 cm +below the rim instead of 8.4 cm. The outside is identical and the inside is dark: from above (wrist camera) and from +the far camera the floor height is not readable (measured: renders of the open, empty box with and without the false +bottom are pixel-identical in both cameras). The Panda hand (21 cm along the finger axis) cannot go below the rim, +so the fingertips cannot touch the false bottom either. Upright the block is 7.5 cm tall: it fits the deep box (top 0.9 cm +below the rim) but stands 3 cm above the rim on the false bottom; lying down (4 cm) it fits both. + +Why the natural action fails: the block is found standing; carried top-down by a gripper that can only turn about the +vertical, it is naturally put in standing. On a false bottom the closing lid then comes down on the block's top and +stays open at ~28-41 deg (measured; clearly visible in both cameras). What must be +learned: take the block out, lay it on its side (tip it over on the table by pushing its upper part with the closed +fingers, then pick it up lying) and put it in lying (within the attempt), or lay it down before putting it in (across +attempts). + +Lid mechanics for agents (inherited from lh_lid_box's `LidSkills`, generalized to a hinge axis along x): while the +knob is held, a commanded straight move is projected onto the knob's circle around the hinge (at most 1 cm per control +step), so "up, then over the hinge, release" opens the lid and "up, then away from the hinge, release" closes it. + +Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (lid closed, all +three items inside the box below the rim, nothing held, scene static) plus an event log for the server log +(per-item in_box achieved / lost / restored, lid opened / closed / blocked, red block laid down / stood up); F1 gives +the agent only success / failure. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task +from .lh_lid_box import SMAX, LidSkills, _fb, _lr + +# ---------------------------------------------------------------- geometry / physics (box frame: hinge along local y +# at the local +x edge; the box is turned by +-90 deg so that the hinge runs forward-back on the left or right side) +BOX = "box_1" +BOX_MODEL = "lff_fbl_box" +S_IN, L_IN = 0.120, 0.190 # inner cavity across the hinge (local x -> world y) and along it (local y -> world x); +# roomy enough that closed fingers (~4 cm out from a held 4 cm item) stay off the walls +WALL_T, WALL_H, FLOOR_T = 0.008, 0.090, 0.006 +FB_DEPTH = 0.045 # inner depth with the false bottom (floor 4.5 cm above the table) +LX, LY = S_IN + 2 * WALL_T, L_IN + 2 * WALL_T +LID_T, LID_MASS = 0.006, 0.15 +KNOB_R, STEM_L = 0.013, 0.032 +HINGE_DAMP, HINGE_FRIC = 0.002, 0.002 +LID_SOLREF, LID_SOLIMP = "0.005 1", "0.99 0.998 0.001" +BACKOFF = 0.003 # m per control step: a hand pressing on a lid that rests on an item yields +STOP = (182.0, 192.0) # lid opening stop (deg, uniform): opened, the lid hangs just below horizontal beside the box +# (free end 6.5-7 cm up), below every transit; at < 180 deg its free end and knob rise to 12-14 cm +# and a carried item sweeps into them (measured) +WOOD = (0.55, 0.38, 0.22, 1.0) +LID_RGBA = (0.70, 0.52, 0.32, 1.0) +DARK = (0.0, 0.0, 0.0, 1.0) # pure black, matte (no specular): every lit shade is 0, so the floor height is invisible +KNOB_RGBA = (0.10, 0.10, 0.11, 1.0) + +RED = "red_block_1" +BLUES = ("blue_cube_1", "blue_cube_2") +ITEMS = (RED,) + BLUES +RED_W, RED_H = 0.040, 0.075 +CUBE_E = 0.040 +RED_DENS, CUBE_DENS = 600.0, 500.0 # 72 g, 32 g +ITEM_MU = 0.8 +P_FB = 0.5 + +IN_TOL = 0.004 # an item's footprint corners may reach this far past the inner walls (an item leaning on a wall +# touches it; measured: a cube dropped into the deep box ended tilted 52 deg against the front wall) +RIM_TOL = 0.004 # item top at most this far above the rim +LID_CLOSED = np.radians(5.0) +DEBOUNCE = 6 # predicate checks (every 0.1 s) +UPRIGHT_COS, LYING_COS = np.cos(np.radians(25.0)), np.cos(np.radians(65.0)) + +Z_CARRY = 0.16 # scripted transit height of the grasp point above the table when carrying an item (Sonnet: 11-20 cm) +Z_HAND_MIN = WALL_H - 0.024 + 0.006 # lowest grasp point over the box: the Panda hand (2.4 cm above the grasp point, 21 cm +# along the finger axis) must stay above the rim +# scripted in-box slots along the box's long axis (u, forward-back, box centre = 0), all at v = 0 (centre line). +# The lying red block lies across the box (axis left-right) and is held with the fingers closing forward-back, so its +# slot is 1 cm further in: fingers 4 cm out from its centre stay 1 cm off the back wall (measured: at the upright +# slot the back finger caught the wall and dropped the block) +SLOT_U = {"red_upright": -0.0575, "red_lying": -0.0475, "blue_cube_1": 0.005, "blue_cube_2": 0.055} +START_Y = (-0.24, -0.08, 0.08, 0.24) +START_X = -0.34 + + +def fb_box_xml(name): + hx, hy = LX / 2, LY / 2 + col = [((0, 0, FLOOR_T / 2), (hx, hy, FLOOR_T / 2)), + ((hx - WALL_T / 2, 0, WALL_H / 2), (WALL_T / 2, hy, WALL_H / 2)), + ((-hx + WALL_T / 2, 0, WALL_H / 2), (WALL_T / 2, hy, WALL_H / 2)), + ((0, hy - WALL_T / 2, WALL_H / 2), (hx - WALL_T, WALL_T / 2, WALL_H / 2)), + ((0, -hy + WALL_T / 2, WALL_H / 2), (hx - WALL_T, WALL_T / 2, WALL_H / 2))] + g = [] + # box: contype 2 / conaffinity 1, lid: contype 4 / conaffinity 1 -> the lid never collides with its own box (the + # hinge limit holds it closed) but both collide with the robot, the table and the free items (as in lh_lid_box) + for k, (pos, s) in enumerate(col): + g.append(f'') + fb_top = WALL_H - FB_DEPTH + fbh = (fb_top - FLOOR_T) / 2 + fb_pos, fb_size = (0, 0, FLOOR_T + fbh), (hx - WALL_T, hy - WALL_T, fbh) + # the false bottom: always compiled, its collision switched on / off per instance (contype / conaffinity), so no + # geom moves at runtime and the compiled bounding volumes stay valid (see lh_fence's refit_bvh note) + g.append(f'') + th = WALL_T / 2 + vis = [((hx - th / 2, 0, WALL_H / 2), (th / 2, hy, WALL_H / 2), WOOD), + ((hx - WALL_T + th / 2, 0, WALL_H / 2), (th / 2, hy - th, WALL_H / 2), DARK), + ((-hx + th / 2, 0, WALL_H / 2), (th / 2, hy, WALL_H / 2), WOOD), + ((-hx + WALL_T - th / 2, 0, WALL_H / 2), (th / 2, hy - th, WALL_H / 2), DARK), + ((0, hy - th / 2, WALL_H / 2), (hx - th, th / 2, WALL_H / 2), WOOD), + ((0, hy - WALL_T + th / 2, WALL_H / 2), (hx - WALL_T, th / 2, WALL_H / 2), DARK), + ((0, -hy + th / 2, WALL_H / 2), (hx - th, th / 2, WALL_H / 2), WOOD), + ((0, -hy + WALL_T - th / 2, WALL_H / 2), (hx - WALL_T, th / 2, WALL_H / 2), DARK), + ((0, 0, FLOOR_T / 2), (hx, hy, FLOOR_T / 2), WOOD), + ((0, 0, FLOOR_T + 0.0005), (hx - WALL_T, hy - WALL_T, 0.0005), DARK)] + for p, s, c in vis: + mat = f' material="{name}_dark"' if c == DARK else "" + g.append(f'') + g.append(f'') + m, L = LID_MASS, LX + lid_c = (-L / 2, 0, LID_T / 2) + lid_s = (L / 2, hy, LID_T / 2) + stem = (-L - STEM_L / 2, 0, LID_T / 2) + ball = (-L - STEM_L - KNOB_R * 0.7, 0, LID_T / 2) + lid = [f'', + f'', + # stiffer contacts for the lid plate, and solmix so that they win against the items' (default, soft) ones: + # with soft contacts an arm pressing the lid down onto the 72 g block pushed the lid through it (measured) + f'', + f'', + f'', + f'', + f'', + f''] + shell = "\n ".join(g) + lid_xml = "\n ".join(lid) + # matte near-black inside (no specular highlight): the floor height is not readable from above + return f""" + + + + + + + {shell} + + {lid_xml} + + + + + + + +""" + + +class FBLidSkills(LidSkills): + """LidSkills with the hinge axis in any horizontal direction (here forward-back), plus the task's per-step + monitor. While the knob is held, the commanded displacement is projected onto the tangent of the knob's circle + about the hinge (<= SMAX per control step), with radial and axial corrections.""" + + def _hinge_frame(self, e): + h, a = self.task.hinge_point(), self.task.hinge_axis() + v = e - h + al = float(v @ a) + r = v - al * a + return a, al, r, max(float(np.linalg.norm(r)), 1e-6) + + def _act(self, dpos, drot, grip): + if self.latched: + e = self.eef_pos() + if self.grip < 0 or np.linalg.norm(e - self.task.knob_xyz()) > 0.035: + self.latched = False # opened, or the knob slipped out of the fingers + else: + a, al, r, rn = self._hinge_frame(e) + t_open = np.cross(self.env.sim.data.xaxis[self.task.jid], r) / rn # knob motion for an opening lid + s = float(np.clip(np.asarray(dpos) @ t_open, -SMAX, SMAX)) + if s < 0 and self.task.lid_contacts(): + s = 0.0 # compliant wrist: it does not force the lid down onto an item (else the lid tunnels through it) + dpos = s * t_open + (self.rad0 - rn) * r / rn + (self.y0 - al) * a + self.knob_steps += 1 + else: + p = self.task.robot_lid_contact() + if p is not None and self.task.lid_contacts(): + # the same limit for a hand pressing on the lid itself: no push towards closing while the lid rests on + # an item (measured without it: pressing 5 cm "into" a lid lying on the block left the block poking + # through the lid) + _, _, r, rn = self._hinge_frame(p) + t_open = np.cross(self.env.sim.data.xaxis[self.task.jid], r) / rn + sc = float(np.asarray(dpos) @ t_open) + if sc < 0: # drop the closing component and yield a little (a force-limited arm gives way) + dpos = np.asarray(dpos) + (BACKOFF - sc) * t_open + Skills._act(self, dpos, drot, grip) + self.task.monitor_step() + + def set_gripper(self, close, steps=15): + rep = Skills.set_gripper(self, close, steps) + if close and self.holding_knob(): + _, al, _, rn = self._hinge_frame(self.eef_pos()) + self.latched, self.rad0, self.y0 = True, rn, al + self.knob_grasps += 1 + elif not close: + self.latched = False + return rep + + +def _rot(yaw): + c, s = np.cos(yaw), np.sin(yaw) + return np.array([[c, -s], [s, c]]) + + +@register_task +class FalseBottomLid(LFFTask): + name = "lh_false_bottom_lid" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Plan", "Restore") + protocol = "cross" + max_attempts = 3 + agent_max_steps = 120 # careful: lid 2 x ~6 + 3 items x ~7 = ~35 commands; laying the block down (tip + pick) ~8; + # fixing a blocked lid in place (reopen, take out, tip, pick, put in, close) ~30; + looking + instruction = ("Put the red block and the two blue cubes into the wooden box and close its lid. The lid opens by " + "lifting the black knob on its edge.") + instruction_indirect = ("Pack the tall red piece and both small blue cubes into the wooden chest and shut it " + "(the lid lifts by the black ball on its edge).") + agent_object_names = ["red block", "blue cube", "blue cube", "wooden box", "lid knob"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + box = register_generated("LffFblBox", fb_box_xml(BOX_MODEL), free=False) + red = register_generated("LffFblRedBlock", box_xml("lff_fbl_red_block", (RED_W / 2, RED_W / 2, RED_H / 2), + (0.85, 0.10, 0.08, 1.0), density=RED_DENS, + friction=(ITEM_MU, 0.005, 0.0001)).replace(_SOLID, "").replace( + 'group="0" />', 'condim="4" group="0" />')) + objs = [(RED, red, "red_region", (-0.35, -0.25, -0.33, -0.23))] + for i, n in enumerate(BLUES): + cat = register_generated(f"LffFblBlueCube{'AB'[i]}", + box_xml(f"lff_fbl_blue_cube_{'ab'[i]}", (CUBE_E / 2,) * 3, (0.15, 0.30, 0.85, 1.0), + density=CUBE_DENS, friction=(ITEM_MU, 0.005, 0.0001)).replace(_SOLID, "").replace( + 'group="0" />', 'condim="4" group="0" />')) + objs.append((n, cat, f"blue_{'ab'[i]}_region", (-0.35, -0.09 + 0.16 * i, -0.33, -0.07 + 0.16 * i))) + fx = [(BOX, box, "box_region", (-0.16, -0.01, -0.14, 0.01))] + return write_bddl(self.name, "put the red block and the blue cubes into the box and close the lid", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + pre = f"{BOX}_{BOX_MODEL}" + self.jid = m.joint_name2id(pre + "_hinge") + self.qa = m.jnt_qposadr[self.jid] + self.dof = m.jnt_dofadr[self.jid] + self.box_bid = m.body_name2id(self.env.fixtures_dict[BOX].root_body) + self.knob_geom_name = pre + "_knob" + self.knob_geom_names = [pre + "_knob", pre + "_stem"] + self.knob_gid = m.geom_name2id(self.knob_geom_name) + self.lid_gids = {m.geom_name2id(pre + s) for s in ("_lid", "_stem", "_knob")} + self.fb_gid = m.geom_name2id(pre + "_fb") + self.fbvis_gid = m.geom_name2id(pre + "_fbvis") + self.robot_gids = set(envs.robot_geom_ids(self.env)) + self.item_gids = {n: set(envs.obj_geom_ids(self.env, n)) for n in ITEMS} + self.inst = None + self.mon = None + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + bx, by = float(rng.uniform(-0.17, -0.14)), float(rng.uniform(-0.02, 0.02)) + hinge = "left" if rng.random() < 0.5 else "right" + stop = float(rng.uniform(*STOP)) + perm = rng.permutation(len(START_Y)) + start = {n: [float(START_X + rng.uniform(-0.01, 0.01)), float(START_Y[perm[j]] + rng.uniform(-0.01, 0.01))] + for j, n in enumerate(ITEMS)} + start_yaw = {n: float(rng.uniform(-0.3, 0.3)) for n in ITEMS} + # balanced blocks like lh_lid_box: exactly 10 of every 20 consecutive seeds have the false bottom + fb = bool((int(seed) * 7) % 20 < round(20 * P_FB)) + return dict(seed=int(seed), box_xy=[bx, by], hinge=hinge, stop_deg=stop, false_bottom=fb, + inner_depth_cm=round(100 * (FB_DEPTH if fb else WALL_H - FLOOR_T), 1), start=start, + start_yaw=start_yaw) + + def box_yaw(self, inst=None): + inst = inst or self.inst + return np.pi / 2 if inst["hinge"] == "left" else -np.pi / 2 # local +x (hinge edge) -> world +y / -y + + def apply_instance(self, inst): + self.inst = inst + m, d = self.env.sim.model, self.env.sim.data + bx, by = inst["box_xy"] + yaw = self.box_yaw(inst) + m.body_pos[self.box_bid] = [bx, by, envs.TABLE_Z] + m.body_quat[self.box_bid] = [np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)] + m.jnt_range[self.jid] = [0.0, np.radians(inst["stop_deg"])] + m.jnt_solref[self.jid] = [0.01, 1.0] + fb = bool(inst["false_bottom"]) + m.geom_contype[self.fb_gid] = 2 if fb else 0 + m.geom_conaffinity[self.fb_gid] = 1 if fb else 0 + m.geom_rgba[self.fbvis_gid, 3] = 1.0 if fb else 0.0 + d.qpos[self.qa] = 0.0 + d.qvel[self.dof] = 0.0 + for n, xy in inst["start"].items(): + envs.place_upright(self.env, n, xy, yaw=inst["start_yaw"][n]) + for n in ITEMS: + envs.set_friction(self.env, n, ITEM_MU) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.mon = None + self.sk = FBLidSkills(self.env, self, recorder=recorder) + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ geometry helpers + def floor_z(self): + """height of the surface items rest on inside the box (world z)""" + return envs.TABLE_Z + ((WALL_H - FB_DEPTH) if self.inst["false_bottom"] else FLOOR_T) + + def rim_z(self): + return envs.TABLE_Z + WALL_H + + def long_axis(self): + """unit vector (world xy) along the box's long side (= the hinge axis), pointing forward""" + return np.array([1.0, 0.0]) + + def to_box(self, xy): + """world xy -> box frame (u along the long side / forward, v across / left)""" + return np.asarray(xy, float)[:2] - np.asarray(self.inst["box_xy"]) + + def from_box(self, uv): + return np.asarray(self.inst["box_xy"]) + np.asarray(uv, float) + + def hinge_sign(self): + return 1.0 if self.inst["hinge"] == "left" else -1.0 + + def hinge_point(self): + bx, by = self.inst["box_xy"] + return np.array([bx, by + self.hinge_sign() * LX / 2, envs.TABLE_Z + WALL_H]) + + def hinge_axis(self): + return np.array([1.0, 0.0, 0.0]) + + def lid_q(self): + return float(self.env.sim.data.qpos[self.qa]) + + def lid_deg(self): + return float(np.degrees(self.lid_q())) + + def knob_xyz(self): + return self.env.sim.data.geom_xpos[self.knob_gid].copy() + + def held(self, name): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name])) + + def item_axis(self, name): + """body z axis in world (the red block's long axis)""" + return self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3)[:, 2].copy() + + def red_pose(self): + c = abs(float(self.item_axis(RED)[2])) + return "upright" if c >= UPRIGHT_COS else "lying" if c <= LYING_COS else "tilted" + + def in_cavity_xy(self, name): + """the item's whole footprint (its collision box corners, also when tilted) inside the inner walls""" + m, d = self.env.sim.model, self.env.sim.data + g = next(iter(self.item_gids[name])) + R = d.geom_xmat[g].reshape(3, 3) + half = m.geom_size[g][:3] + c = self.to_box(d.geom_xpos[g][:2]) + ext = np.abs(R[:2, :]) @ half # world-axis half extents of the footprint + lim = np.array([L_IN / 2, S_IN / 2]) + IN_TOL + return bool(np.all(np.abs(c) + ext <= lim)) + + def in_box(self, name): + return bool(self.in_cavity_xy(name) and envs.obj_max_z(self.env, name) <= self.rim_z() + RIM_TOL + and envs.obj_min_z(self.env, name) >= envs.TABLE_Z + FLOOR_T - 0.005 and not self.held(name)) + + def over_box(self, name): + """centre above the cavity (in it, or standing in it but sticking out)""" + c = self.to_box(envs.obj_pos(self.env, name)[:2]) + return bool(abs(c[0]) <= L_IN / 2 and abs(c[1]) <= S_IN / 2) + + def lid_closed(self): + return self.lid_q() <= LID_CLOSED + + def lid_contacts(self): + """items the lid touches now""" + d = self.env.sim.data + out = set() + for i in range(d.ncon): + c = d.contact[i] + for n in ITEMS: + g = self.item_gids[n] + if (c.geom1 in g and c.geom2 in self.lid_gids) or (c.geom2 in g and c.geom1 in self.lid_gids): + out.add(n) + return out + + def robot_lid_contact(self): + """world position of a robot-lid contact (None if the robot does not touch the lid)""" + d = self.env.sim.data + for i in range(d.ncon): + c = d.contact[i] + if (c.geom1 in self.robot_gids and c.geom2 in self.lid_gids) or (c.geom2 in self.robot_gids + and c.geom1 in self.lid_gids): + return np.array(c.pos, float) + return None + + def robot_touching(self): + """'lid' / item names the robot is in contact with now (finishing while pressing the lid down does not count)""" + d = self.env.sim.data + out = set() + for i in range(d.ncon): + c = d.contact[i] + g1, g2 = c.geom1, c.geom2 + for a, b in ((g1, g2), (g2, g1)): + if a in self.robot_gids: + if b in self.lid_gids: + out.add("lid") + for n in ITEMS: + if b in self.item_gids[n]: + out.add("red block" if n == RED else "blue cube") + return sorted(out) + + def stage_values(self): + v = {f"{n}_in_box": self.in_box(n) for n in ITEMS} + v["lid_closed"] = self.lid_closed() + return v + + # ------------------------------------------------------------ per-step monitor + def _init_monitor(self): + self.mon = dict(state={f"{n}_in_box": False for n in ITEMS}, ever=set(), lost=set(), events=[], + last_touch={n: None for n in ITEMS}, step=0, lid_opened=False, lid_open_max=0.0, + lid_prev=0.0, lid_still=0, blocked_now=False, n_blocked=0, blocked_max_deg=0.0, + red_pose=self.red_pose(), red_pose_cand=None, red_pose_n=0, red_up_in_box=False, + red_relaid=0, closes=0, cand={f"{n}_in_box": 0 for n in ITEMS}) + + def _touches(self): + d = self.env.sim.data + out = {} + for i in range(d.ncon): + c = d.contact[i] + for n in ITEMS: + g = self.item_gids[n] + other = c.geom2 if c.geom1 in g else (c.geom1 if c.geom2 in g else None) + if other is None: + continue + if other in self.lid_gids: + out[n] = "lid" + elif other in self.robot_gids and out.get(n) != "lid": + out[n] = "robot" + return out + + def monitor_step(self): + mon = self.mon + if mon is None: + return + mon["step"] += 1 + step = self.sk.n_steps if self.sk is not None else mon["step"] + for n, who in self._touches().items(): + mon["last_touch"][n] = (who, step) + q = self.lid_deg() + mon["lid_open_max"] = max(mon["lid_open_max"], q) + if not mon["lid_opened"] and q > 90.0: + mon["lid_opened"] = True + mon["blocked_now"] = False + mon["events"].append(dict(step=step, pred="lid", ev="opened_past_vertical")) + elif mon["lid_opened"] and q <= np.degrees(LID_CLOSED): + mon["lid_opened"] = False + mon["closes"] += 1 + mon["events"].append(dict(step=step, pred="lid", ev="closed")) + # lid blocked: it came down from past vertical and rests (not held) on an item at 5-80 deg for 1 s + if abs(q - mon["lid_prev"]) < 0.05: + mon["lid_still"] += 1 + else: + mon["lid_still"] = 0 + mon["lid_prev"] = q + if mon["lid_opened"] and not mon["blocked_now"] and 5.0 < q < 80.0 and mon["lid_still"] >= 20 \ + and not self.sk.latched: + on = sorted(self.lid_contacts()) + if on: + mon["blocked_now"] = True + mon["n_blocked"] += 1 + mon["blocked_max_deg"] = max(mon["blocked_max_deg"], q) + mon["events"].append(dict(step=step, pred="lid", ev="lid_blocked", lid_deg=round(q, 1), on=on, + red_pose=self.red_pose())) + if mon["blocked_now"] and q > 90.0: + mon["blocked_now"] = False + if mon["step"] % 2: + return # predicates every other control step (0.1 s) + # red block pose (debounced 1 s): upright <-> lying + p = self.red_pose() + if p != "tilted" and p != mon["red_pose"]: + if mon["red_pose_cand"] == p: + mon["red_pose_n"] += 1 + else: + mon["red_pose_cand"], mon["red_pose_n"] = p, 1 + if mon["red_pose_n"] >= 10 and not self.held(RED): + where = "box" if self.over_box(RED) else "table" + lt = mon["last_touch"][RED] + cause = lt[0] if lt is not None and step - lt[1] <= 60 else "other" + ev = "item_relaid" if p == "lying" else "stood_up" + if p == "lying": + mon["red_relaid"] += 1 + mon["events"].append(dict(step=step, pred="red_pose", ev=ev, where=where, cause=cause)) + mon["red_pose"] = p + mon["red_pose_cand"] = None + else: + mon["red_pose_cand"] = None + if not mon["red_up_in_box"] and mon["red_pose"] == "upright" and self.over_box(RED) and not self.held(RED) \ + and envs.obj_min_z(self.env, RED) < self.rim_z(): + mon["red_up_in_box"] = True + top = envs.obj_max_z(self.env, RED) - self.rim_z() + mon["events"].append(dict(step=step, pred="red_pose", ev="placed_upright_in_box", + top_above_rim_cm=round(100 * top, 1))) + for n in ITEMS: # debounced: a change counts after it held for DEBOUNCE checks (fingers rubbing a released item) + key = f"{n}_in_box" + now = self.in_box(n) + if now == mon["state"][key]: + mon["cand"][key] = 0 + continue + mon["cand"][key] += 1 + if mon["cand"][key] >= DEBOUNCE: + mon["cand"][key] = 0 + self._event(key, now, step, n) + + def _event(self, key, now, step, name): + mon = self.mon + mon["state"][key] = now + if now: + ev = "restored" if key in mon["lost"] else "achieved" + mon["ever"].add(key) + mon["lost"].discard(key) + e = dict(step=step, pred=key, ev=ev) + if name == RED: + e["red_pose"] = self.red_pose() + mon["events"].append(e) + return + if key not in mon["ever"]: + return # never achieved: nothing lost + cause = "other" + if self.held(name): + cause = "picked_up" + else: + lt = mon["last_touch"][name] + if lt is not None and step - lt[1] <= 60: + cause = lt[0] + mon["lost"].add(key) + mon["events"].append(dict(step=step, pred=key, ev="lost", cause=cause, lid_deg=round(self.lid_deg(), 1))) + + # ------------------------------------------------------------ outcome + def _static(self): + d = self.env.sim.data + for n in ITEMS: + _, da = envs.free_joint_addr(self.env, n) + if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5: + return False + return abs(float(d.qvel[self.dof])) < 0.2 + + def _where(self, name): + """F2-style location of an item relative to the box, robot-centric words""" + rel = self.to_box(envs.obj_pos(self.env, name)[:2]) + return f"{_fb(rel[0])} and {_lr(rel[1])} of the box's centre" + + def outcome(self, inst): + envs.settle(self.env, 30) + mon = self.mon + vals = self.stage_values() + static = self._static() + held = [n for n in ITEMS if self.held(n)] + touching = self.robot_touching() + success = bool(all(vals.values()) and static and not held and not touching) + regress = [e for e in mon["events"] if e["ev"] == "lost"] + restored = [e for e in mon["events"] if e["ev"] == "restored"] + on = sorted(self.lid_contacts()) + red_top = envs.obj_max_z(self.env, RED) - self.rim_z() + parts = [] + failure = None + if success: + parts.append("The red block and both blue cubes are inside the box and the lid is closed.") + else: + out_items = [n for n in ITEMS if not vals[f"{n}_in_box"]] + if not vals["lid_closed"] and on: + failure = "lid_blocked" + elif held: + failure = "held" + elif touching and all(vals.values()): + failure = "robot_touching" + elif out_items: + failure = ("red_sticks_out" if out_items == [RED] and self.over_box(RED) and red_top > RIM_TOL + else "item_not_in_box") + elif not vals["lid_closed"]: + failure = "lid_open" + else: + failure = "not_static" + if not vals["lid_closed"]: + txt = f"The lid is not closed (open {self.lid_deg():.0f} degrees)" + if on: + names = " and ".join("the red block" if n == RED else "a blue cube" for n in on) + txt += f": it rests on {names}" + parts.append(txt + ".") + for n in out_items: + nm = "The red block" if n == RED else "A blue cube" + if self.held(n): + parts.append(f"{nm} is still held by the gripper.") + elif self.over_box(n) and envs.obj_max_z(self.env, n) > self.rim_z() + RIM_TOL: + top = envs.obj_max_z(self.env, n) - self.rim_z() + pose = self.red_pose() if n == RED else "resting" + parts.append(f"{nm} is in the box but sticks out {100 * top:.1f} cm above the rim ({pose}).") + else: + parts.append(f"{nm} is not in the box: its centre is {self._where(n)}.") + if touching and all(vals.values()): + parts.append("The robot was still pressing on the " + " and ".join(touching) + " at the end.") + if not static and all(vals.values()): + parts.append("Something was still moving at the end.") + if mon["n_blocked"]: + parts.append(f"The lid came down on an item {mon['n_blocked']} time(s) during the attempt.") + out = dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, touching=touching, + events=mon["events"], n_regressions=len(regress), n_restored=len(restored), + false_bottom=bool(inst["false_bottom"]), n_lid_blocked=mon["n_blocked"], + lid_blocked_max_deg=round(mon["blocked_max_deg"], 1), red_relaid=mon["red_relaid"], + red_placed_upright_in_box=mon["red_up_in_box"], red_pose=self.red_pose(), + red_top_above_rim_cm=round(100 * red_top, 1), lid_on=on, + lid_open_max=round(mon["lid_open_max"], 1), lid_final_deg=round(self.lid_deg(), 1), + lid_closes=mon["closes"], knob_grasps=self.sk.knob_grasps, knob_steps=self.sk.knob_steps, + detail=" ".join(parts)) + return out + + # ------------------------------------------------------------ scripted primitives (perfect perception) + def _settle_item(self, name, max_checks=20): + """keep the arm still until `name` has stopped moving (a tipped block rolls on for a moment)""" + d = self.env.sim.data + _, da = envs.free_joint_addr(self.env, name) + for _ in range(max_checks): + if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2: + return + self.sk.hold(2) + + def _grasp_yaw(self, name): + """fingers across a 4 cm side: for the lying red block across its long axis, else yaw mod 90 deg""" + R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3) + if name == RED and self.red_pose() != "upright": + ax = R[:, 2] + yaw = float(np.arctan2(ax[1], ax[0])) # closing direction (-sin, cos) is then across the long axis + return float((yaw + np.pi / 2) % np.pi - np.pi / 2) + i = int(np.argmin(np.abs(R[2]))) + yaw = float(np.arctan2(R[1, i], R[0, i])) + return float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4) + + def _grasp_z(self, name): + """grasp point height above the table for a top-down grasp of `name` where it is""" + zmin = envs.obj_min_z(self.env, name) - envs.TABLE_Z + zmax = envs.obj_max_z(self.env, name) - envs.TABLE_Z + if name == RED and self.red_pose() == "upright": + z = zmin + 0.0425 # 4.25 cm up the 7.5 cm block (0.5 cm above its centre) + else: + z = (zmin + zmax) / 2 + if self.over_box(name): # the hand (2.4 cm above the grasp point) stays above the rim + z = max(z, Z_HAND_MIN, WALL_H + 0.016 if zmax > WALL_H + 0.02 else 0.0) + z = min(z, zmax - 0.004) + return z + + def pick(self, name, z_carry=Z_CARRY, tries=2): + """top-down grasp of `name` where it is, lift to z_carry (a missed grasp is retried once, as anyone would); + returns the grasp point's height above the item's bottom, or None if the grasp failed""" + sk = self.sk + Z = envs.TABLE_Z + for _ in range(tries): + self._settle_item(name) + p = envs.obj_pos(self.env, name) + yaw = self._grasp_yaw(name) + zg = self._grasp_z(name) + zbot = envs.obj_min_z(self.env, name) - Z + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], Z + max(z_carry, zg + 0.06)], yaw=yaw) + sk.hold(8) # let a large wrist turn settle before going down (else the hand drifts ~1 cm near the table) + sk.move_to([p[0], p[1], Z + zg], tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + sk.move_to([p[0], p[1], Z + z_carry], speed=0.3) + if self.held(name): + return zg - zbot + sk.set_gripper(False, steps=8) + return None + + def place(self, dest_xy, z_rel, yaw, z_carry=Z_CARRY): + """carry to above dest at z_carry, lower to z_rel (or until the item / hand rests on something), release, lift""" + sk = self.sk + Z = envs.TABLE_Z + sk.move_to([dest_xy[0], dest_xy[1], Z + z_carry], yaw=yaw) + sk.move_to([dest_xy[0], dest_xy[1], Z + z_rel], tol=0.003, max_steps=80) + sk.set_gripper(False, steps=12) + sk.move_to([dest_xy[0], dest_xy[1], Z + z_carry]) + + def put_in_box(self, name, u, v=0.0, noise=None, z_carry=Z_CARRY): + """pick `name` as it is (the red block upright or lying) and lower it into the box at (u, v) (box frame) as if + the box were deep (the hand stops above the rim), release. The lying red block is turned across the box.""" + off = self.pick(name, z_carry=z_carry) + if off is None: + return False + yaw = np.pi / 2 if name == RED and self.red_pose() == "lying" else self.sk.yaw + d = self.from_box([u, v]) + (np.asarray(noise, float) if noise is not None else 0.0) + self.place(d, max(Z_HAND_MIN, FLOOR_T + off + 0.005), yaw, z_carry=z_carry) + return True + + def red_slot(self): + return SLOT_U["red_lying"] if self.red_pose() == "lying" else SLOT_U["red_upright"] + + def tip_over(self, name, direction, z_push=0.055, speed=0.10): + """push the standing item's upper part with the closed fingers along `direction` (xy) so that it falls over""" + sk = self.sk + Z = envs.TABLE_Z + d = np.asarray(direction, float) + d = d / np.linalg.norm(d) + p = envs.obj_pos(self.env, name) + s = p[:2] - d * 0.06 + e = p[:2] + d * 0.035 + yaw = float(np.arctan2(d[1], d[0])) - np.pi / 2 # finger closing direction along the push + sk.set_gripper(True, steps=8) + sk.move_to([s[0], s[1], Z + 0.13], yaw=yaw) + sk.move_to([s[0], s[1], Z + z_push], tol=0.004) + sk.move_to([e[0], e[1], Z + z_push], speed=speed, tol=0.006) + sk.move_to([e[0], e[1], Z + 0.13], speed=0.3) + self._settle_item(name) + return self.red_pose() if name == RED else None + + def _tip_direction(self, name): + """outward along y (away from the other items, which stand 16 cm apart in a row)""" + y = envs.obj_pos(self.env, name)[1] + return np.array([0.0, 1.0 if y >= 0 else -1.0]) + + def lay_down(self, name=RED, **kw): + """tip the standing block over on the table (up to two pushes); True if it lies""" + for _ in range(2): + if self.red_pose() == "lying": + return True + self.tip_over(name, self._tip_direction(name), **kw) + return self.red_pose() == "lying" + + def take_out_red(self): + """pick the red block out of the box and stand it on its start spot""" + off = self.pick(RED) + if off is None: + return False + self.place(self.inst["start"][RED], off + 0.004, self.sk.yaw) + self._settle_item(RED) + return True + + def _grasp_knob(self, yaw=-np.pi / 2): + """open the fingers, come down on the knob at wrist yaw -90 deg (fingers across the stem), close. Always -90 + (not its gripper-symmetric twin +90): with the lid hanging on its stop beside the box the arm reached the knob + at -90 in every instance, but at +90 it stopped 2-3 cm short against the lid (validate seed 1004: the lying + block's grasp yaw had landed on +90 by numerical chance and the final close missed the knob twice). A 180 deg + wrist turn is avoided by passing through yaw 0 (see Skills.wrap_yaw).""" + sk = self.sk + k = self.knob_xyz() + for attempt in range(2): + sk.set_gripper(False, steps=8) + if abs(sk.yaw - yaw) > np.pi / 2 + 0.1: + sk.move_to([k[0], k[1], k[2] + 0.08], yaw=0.0, wrap_yaw=False) + sk.move_to([k[0], k[1], k[2] + 0.08], yaw=yaw, wrap_yaw=False) + sk.hold(5) + sk.move_to([k[0], k[1], k[2]], tol=0.003) + sk.set_gripper(True, steps=15) + if sk.holding_knob() or attempt: + break + # missed (measured once in 40 validation attempts: after a long sequence of wrist turns the arm's posture + # had drifted and it stopped 3-4 cm short of the knob hanging far to the side): open, go back to a neutral + # pose over the box at yaw 0 (the OSC's null-space term straightens the arm there) and try once more + sk.set_gripper(False, steps=8) + e = sk.eef_pos() + sk.move_to([e[0], e[1], e[2] + 0.10]) + c = self.from_box([0.0, 0.0]) + sk.move_to([c[0], c[1], envs.TABLE_Z + 0.28], yaw=0.0, wrap_yaw=False) + sk.hold(10) + return k + + def open_lid(self, over=0.04, up=0.16): + """grasp the knob (fingers across its stem); straight up 10 cm; straight to `over` m beyond the hinge, `up` m + above it; release; lift""" + sk = self.sk + k = self._grasp_knob() + h = self.hinge_point() + sg = self.hinge_sign() + sk.move_to([k[0], k[1], k[2] + 0.10]) + sk.move_to([h[0], h[1] + sg * over, h[2] + up]) + sk.set_gripper(False, steps=10) + e = sk.eef_pos() + sk.move_to([e[0], e[1] - sg * 0.04, e[2] + 0.05]) + sk.hold(25) + + def close_lid(self, away=0.08, up=0.10): + """grasp the knob where it is; straight up 10 cm; straight to `away` m on the knob side of the hinge; release""" + sk = self.sk + k = self._grasp_knob() + h = self.hinge_point() + sg = self.hinge_sign() + sk.move_to([k[0], k[1], k[2] + up]) + sk.move_to([h[0], h[1] - sg * away, max(k[2], h[2]) + up]) + sk.set_gripper(False, steps=10) + e = sk.eef_pos() + sk.move_to([e[0], e[1], e[2] + 0.06]) + sk.hold(30) + + def press_lid(self): + """the natural retry when the lid did not shut: grasp the knob where it is and push it down towards closed""" + sk = self.sk + k = self._grasp_knob() + h = self.hinge_point() + sg = self.hinge_sign() + sk.move_to([k[0], h[1] - sg * (LX + 0.01), h[2] - 0.01], speed=0.1) + sk.set_gripper(False, steps=10) + e = sk.eef_pos() + sk.move_to([e[0], e[1], e[2] + 0.08]) + sk.hold(30) + + def _fallen(self): + """items that ended up outside the box (not merely sticking out of it)""" + return [n for n in ITEMS if not self.in_box(n) and not self.over_box(n) and not self.held(n)] + + def _replace_fallen(self, done, noise=None, z_carry=Z_CARRY): + for n in [n for n in self._fallen() if n in done]: + self.put_in_box(n, self.red_slot() if n == RED else SLOT_U[n], noise=(noise or {}).get(n), z_carry=z_carry) + + # ------------------------------------------------------------ scripted policies + def execute(self, inst, params): + noise = params.get("noise") or {} + zc = params.get("z_carry", Z_CARRY) + self.open_lid(**params.get("open", {})) + done = [] + for n in ITEMS: + if n == RED and params.get("lay_first"): + self.lay_down(RED) + self.put_in_box(n, self.red_slot() if n == RED else SLOT_U[n], noise=noise.get(n), z_carry=zc) + done.append(n) + self._replace_fallen(done, noise, zc) # looks after every step: re-places an item that fell outside + self.close_lid(**params.get("close", {})) + if params.get("check") == "naive": + self.naive_check(noise, zc) + elif params.get("check") == "fix": + self.check_and_fix() + self.sk.hold(10) + + def naive_check(self, noise=None, z_carry=Z_CARRY): + """Sonnet-like look before finishing, without the insight: a lid that did not shut is pushed down once (re-closed + if it is still open past upright); an item outside the box is put back as it is (the red block upright)""" + if not self.lid_closed(): + if self.lid_deg() > 90: + self.close_lid() + else: + self.press_lid() + if self._fallen(): + if self.lid_deg() < 90: + self.open_lid() + self._replace_fallen(list(ITEMS), noise, z_carry) + self.close_lid() + + def check_and_fix(self, rounds=2): + """look at every stage; if the red block is not inside below the rim (it stands up out of a shallow box and + holds the lid open), take it out, lay it down on the table and put it in lying; re-place anything outside the + box; close the lid""" + for _ in range(rounds): + v = self.stage_values() + if all(v.values()) and not any(self.held(n) for n in ITEMS): + return True + bad = [n for n in ITEMS if not v[f"{n}_in_box"]] + if self.lid_deg() < 90 and (bad or self.lid_contacts()): + self.open_lid() + for n in bad: + if n == RED and self.red_pose() != "lying": + if self.over_box(RED): + self.take_out_red() + self.lay_down(RED) + self.put_in_box(n, self.red_slot() if n == RED else SLOT_U[n]) + if self.lid_deg() > 90 or not self.lid_closed(): + self.close_lid() + return all(self.stage_values().values()) + + def default_params(self, inst): + """Sonnet-like: open the lid, items in the listed order, each put in as found (the block upright), carried + 16 cm up, looks after every step (re-places an item that fell outside), closes the lid, pushes a lid that did + not shut down once, finishes""" + return dict(lay_first=False, check="naive") + + def oracle_params(self, inst): + """knows the inner depth: lays the block down first in a shallow box; checks every stage at the end""" + return dict(lay_first=bool(inst["false_bottom"]), check="fix") + + def adapt_params(self, inst, history): + """attempt >= 2 (after a failure): lay the block down before putting it in, then check and fix""" + return dict(lay_first=True, check="fix") + + def blind_params(self, inst, attempt, rng): + """the natural behaviour again with small random variations, no history""" + return dict(lay_first=False, check="naive", + noise={n: rng.uniform(-0.005, 0.005, 2).tolist() for n in ITEMS}, + z_carry=float(rng.uniform(0.13, 0.19)), + open=dict(over=float(rng.uniform(0.02, 0.06)), up=float(rng.uniform(0.14, 0.18))), + close=dict(away=float(rng.uniform(0.06, 0.10)))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """oracle / naive: one attempt; adaptive: attempt 1 = the natural placement plus a real check and fix (takes the + block out and lays it down when the lid is blocked), later attempts lay it down first; blind: natural with + random variations; switch (extra control): natural, then lay it down first from attempt 2, no real check""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = dict(lay_first=False, check="fix") if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": + params = self.default_params(inst) if a == 0 else dict(lay_first=True, check="naive") + elif kind == "oracle_noise": # robustness check: oracle with +-5 mm placement noise + params = dict(self.oracle_params(inst), noise={n: rng.uniform(-0.005, 0.005, 2).tolist() for n in ITEMS}) + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive", "oracle_noise"): + break + return history diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_fence.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_fence.py new file mode 100644 index 0000000000000000000000000000000000000000..bb2b54b80b13295e96084ae9823b99f28f57ef1a --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_fence.py @@ -0,0 +1,1030 @@ +"""LH lh_fence (v2, 2026-10-11): build a small fence -- three square posts on square marks and two flat panels on the +strips between them, end to end in one line. Letting go of a panel with the fingers along the fence line knocks over +the post next to it (when the posts are light); the fallen post must be stood up again before finishing. + +Family: long-horizon self-disturbance ("state_restoration"): every placement is a later stage that can physically +break the earlier ones; the agent has to notice and restore them (within an attempt) or learn to place without +disturbing them (across attempts). + +Why v2 (measured, ../docs/11 sec. 9): in v1 the panels stood like dominoes (thickness along the row) and the hazard was +opening the fingers along the row. Sonnet 5.5 always turned the hand so that its long axis (= the finger axis) lay +along the panel's long horizontal side, which in v1 is across the row = the safe orientation, and it filled the row +from the far end: 3/3 pilot runs succeeded first time with zero disturbances. v2 turns the panels by 90 deg into a real +fence (panels end to end along the line, posts between them), so the same habit now opens the fingers ALONG the +line, towards the posts. + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a straight fence line, left-right or forward-back: 3 dark square marks (posts) alternating with 2 dark strips + (panels), slot pitch (post centre to post centre) w + 2 g + b; + * 3 posts: square b = 1.55-1.65 cm, height = the panels' height, dark wood, ball knob (r 1.0 cm, 10 g) on a 0.8 cm + stem; 2 panels: thickness t 1.4-1.6 cm (across the line), width w 4.0-4.6 cm (along it), height h 7-8 cm, light + wood, same knob. A placed panel leaves a gap g = 1.3-1.5 cm to each post (knob to knob D = w/2 + g + b/2 = + 4.1-4.6 cm); + * the 5 objects stand in a 2 x 3 supply grid (11 cm pitch, 13-15 cm beside the line, shifted towards one end), the + panels with their width along the line (+-9 deg). + +Hidden variable (instance level, consistent across attempts, invisible): the posts' mass distribution. "Light" posts +are plain wood (19-23 g incl. the knob; centre of mass 5.9-7.1 cm up, tips over beyond ~7 deg); "footed" posts carry a +hidden 100-140 g steel foot (centre of mass 1.5-1.8 cm up, tips over beyond 25-28 deg). They look identical. 13 of +every 20 consecutive seeds have light posts ("hazard"), 7 footed ("benign"). + +Disturbance (physics, no teleport): a panel is grasped by its knob; with the fingers along the panel's width (the +natural "hand along the board" grasp, and Sonnet's measured habit) the fingers lie along the fence line at the release +and, opening to 8 cm, sweep ~6 cm out from the grasp point: they hit the knob of each post that already stands next to +the panel (D 3.3-5.4 cm incl. a 0.8 cm placement error) and push it 6-18 deg. A light post falls over (away from the +panel; a middle post often ends up leaning on the panel on its other side); a footed post rocks back. Measured in the +prototype: light posts 16/16 fell for D <= 5.0 cm (2/4 at 5.5, 0/4 at 6.0), posts with a 0.12-0.25 kg foot 0/30 (max +tilt 18 deg); with the fingers across the line (along the panel's thickness) 0/9 contacts. A post set down with its +fingers along the line next to a standing panel tilts the panel <= 15 deg, which rocks back. Validation (seeds +1000-1019): the Sonnet-like naive disturbs 13/13 light-post instances and 0/7 footed ones. + +So the levers are under the agent's control and the hidden weight only decides whether its habit is punished: (1) +release a panel with the fingers across the fence line (Sonnet-like naive with only this change: 19/20), or, only +partly, (2) stand both panels before the posts (15/20: a post released next to a panel with its fingers along the line +rocks the panel, which can knock the new light post). Within an attempt: +look at the fence before finishing and stand fallen posts up again (lifted by its knob a fallen post swings down and +hangs upright; a fallen panel too). + +Implementation notes (found while building v2): MuJoCo keeps each body's bounding-volume hierarchy in the body's +inertial frame, computed at compile time. Changing geom sizes or body_ipos at runtime therefore needs `refit_bvh` +(else contacts are missed: a light post whose centre of mass was moved up sank 2.2 cm into the table; one moved down +never touched the fingers), and runtime body_ipos is ignored altogether when the compiled inertial frame coincides with +the body frame (v1's knob-mass shift of the centre of mass was silently ignored); the generated XML therefore declares +an inertial pos of 1 mm. With the centre of mass right, v1's knob torsional friction (0.0015) held a lifted fallen light +post at 44-61 deg instead of letting it swing down; v2 uses 0.0005 (< 3 deg). + +Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (every mark +carries an upright post, every strip an upright panel lined up with it, nothing held or touched, scene static) plus an +event log of every stage predicate (achieved / lost / restored, with step and cause) for the server log; F1 gives the +agent only success / failure. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +TZ = envs.TABLE_Z +POSTS = [f"post_{c}_1" for c in "abc"] +PANELS = [f"panel_{c}_1" for c in "ab"] +OBJS = POSTS + PANELS +MARKS = [f"postmark_{c}_1" for c in "abc"] +STRIPS = [f"strip_{c}_1" for c in "ab"] +SLOT_KIND = ["post", "panel", "post", "panel", "post"] # along the fence line (-u to +u) +WOOD = [(0.82, 0.66, 0.44, 1.0), (0.76, 0.60, 0.40, 1.0)] +POST_RGBA = [(0.46, 0.30, 0.18, 1.0), (0.44, 0.29, 0.17, 1.0), (0.48, 0.31, 0.19, 1.0)] +KNOB_RGBA = (0.20, 0.11, 0.06, 1.0) +STRIP_RGBA = (0.30, 0.10, 0.12, 1.0) +MARK_RGBA = (0.14, 0.14, 0.16, 1.0) +NOM_T, NOM_W, NOM_H = 0.015, 0.047, 0.075 # nominal panel (resized per instance) +NOM_B = 0.016 # nominal post width +KNOB_R, STEM_L, STEM_R = 0.010, 0.008, 0.0035 +KNOB_MASS = 0.010 +KNOB_MU_T = 0.0005 # torsional friction of the knob (condim 4): damps the swing of a hanging object; 0.0015 (v1) holds a lifted fallen light post at 45-60 deg (measured) +STRIP_W = 0.006 + +# instance ranges +P_HAZARD = 0.65 # 13 of every 20 consecutive seeds: light posts +T_RANGE = (0.014, 0.016) +W_RANGE = (0.040, 0.046) +H_RANGE = (0.070, 0.080) +B_RANGE = (0.0155, 0.0165) +GAP_RANGE = (0.013, 0.015) # panel end to post face; 1.0-1.2 cm: a +-0.8 cm placement error let the panel end touch a light post (2/20 with the safe grasp) +DENS_RANGE = (450.0, 650.0) +MU_RANGE = (0.4, 0.8) +FOOT_RANGE = (0.10, 0.14) # hidden steel foot of a "footed" post (kg) +FOOT_H = 0.015 # height of the foot slug (its centre 7.5 mm above the post's bottom) +SUP_PITCH = (0.105, 0.115) +SUP_D = (0.13, 0.15) +X_FAR = -0.035 + +# success predicate +TOL_U = 0.010 # panel centre within 1 cm of the strip centre along the line, 1.5 cm across; post 1 cm both ways +TOL_V = 0.015 +TOL_POST = 0.010 +TILT_OK = np.radians(5.0) +YAW_TOL = np.radians(15.0) +HYST = 0.004 +DEBOUNCE = 20 # a stage counts as lost / regained only after 1 s (a post or panel that is pushed and rocks back is not a loss) +FALLEN = np.radians(45.0) + +# scripted motion (z = height of the grasp point above the table) +Z_SAFE = 0.25 # careful transit (a hanging object's bottom ~15 cm up) +Z_NAIVE = 0.21 # Sonnet's usual carry height: robot-frame z 0.20 (= 21 cm above the table), measured in lh2_fence +NAIVE_ERR = 0.008 # naive placement error, uniform per axis (Sonnet: 0.4-1.3 cm from the strip centre, lh2_fence) + + +def _wrap_h(a): + """wrap to [-pi/2, pi/2) (panel footprint and gripper are symmetric under 180 deg)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def _yaw_for_axis(a): + """gripper yaw whose finger axis (-sin yaw, cos yaw) is parallel to the horizontal direction a""" + return _wrap_h(float(np.arctan2(-a[0], a[1]))) + + +def _quat2mat(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 refit_bvh(m, b, margin=0.001): + """Recompute body b's bounding-volume hierarchy after runtime changes of its geoms or body_ipos. MuJoCo stores the + boxes in the body's inertial frame, computed at compile time; stale boxes make it miss contacts (see module doc). + Every node becomes the union of its leaf geoms' boxes (body_iquat must be identity).""" + a = int(m.body_bvhadr[b]) + if a < 0: + return + ipos = np.asarray(m.body_ipos[b], float) + + def rec(i): + g = int(m.bvh_nodeid[i]) + if g >= 0: + R = _quat2mat(m.geom_quat[g]) + c = np.asarray(m.geom_pos[g]) + R @ np.asarray(m.geom_aabb[g, :3]) - ipos + h = np.abs(R) @ np.asarray(m.geom_aabb[g, 3:]) + lo, hi = c - h, c + h + else: + l1, h1 = rec(a + int(m.bvh_child[i][0])) + l2, h2 = rec(a + int(m.bvh_child[i][1])) + lo, hi = np.minimum(l1, l2), np.maximum(h1, h2) + m.bvh_aabb[i] = np.concatenate([(lo + hi) / 2, (hi - lo) / 2 + margin]) + return lo, hi + rec(a) + + +def knobbed_xml(name, half, rgba): + """box + stem + ball knob. The inertial pos is 1 mm (not 0) so that MuJoCo does not mark the inertial frame as + identical to the body frame: then the centre of mass set at runtime (body_ipos) is used.""" + geoms = [("board", "box", (0, 0, 0), half, rgba, 'friction="0.6 0.005 0.0001"'), + ("stem", "cylinder", (0, 0, half[2] + STEM_L / 2), (STEM_R, STEM_L / 2), KNOB_RGBA, + 'friction="1 0.005 0.0001"'), + ("knob", "sphere", (0, 0, half[2] + STEM_L + KNOB_R), (KNOB_R,), KNOB_RGBA, + f'friction="1 {KNOB_MU_T} 0.0001" condim="4" priority="2"')] + s = [' '] + for nm, typ, pos, size, c, extra in geoms: + s.append(f' ') + s.append(f' ') + return _wrap(name, "\n".join(s), half[2], float(np.hypot(half[0], half[1]))) + + +def flat_xml(name, half, rgba): + g = (f' ') + return _wrap(name, g, half[2], float(np.hypot(half[0], half[1]))) + + +class FenceSkills(Skills): + """Skills that feed the task's per-step stage monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class Fence(LFFTask): + name = "lh_fence" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Plan", "Reason", "Restore") + protocol = "cross" + max_attempts = 3 + agent_max_steps = 120 # careful: ~10 commands per object (50) + standing up two fallen posts (~20) + looking + instruction = ("Build a small fence: stand one wooden post upright on each of the dark square marks on the table " + "and one wooden panel upright on each of the dark strips between them, the panel's long bottom edge " + "along its strip, so that posts and panels alternate in one straight line. Every post and panel " + "has a small round knob on top; an object lifted by its knob hangs straight down. At the end every " + "square mark must have one upright post and every strip one upright panel standing on it, with the " + "gripper open and clear of the fence.") + instruction_indirect = ("Put up the little fence: the thin square sticks go upright on the dark squares, the flat " + "boards upright on the dark lines between them, lengthwise along their lines, so that " + "sticks and boards take turns in one straight row. Every piece has a round knob on top; " + "held by its knob a piece hangs straight down. At the end every square must carry one " + "upright stick and every line one upright board, and the gripper must be open and away " + "from the fence.") + agent_object_names = ["wooden fence posts (square, each with a dark knob on top)", + "wooden fence panels (flat boards, each with a dark knob on top)", + "dark square marks and dark strips on the table"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs, fx = [], [] + for i, p in enumerate(POSTS): + c = "abc"[i] + cat = register_generated(f"LffLhfPost{c.upper()}", + knobbed_xml(f"lff_lhf_post_{c}", (NOM_B / 2, NOM_B / 2, NOM_H / 2), POST_RGBA[i])) + objs.append((p, cat, f"post{i}_region", (-0.30 + 0.12 * i, 0.30, -0.29 + 0.12 * i, 0.31))) + for i, p in enumerate(PANELS): + c = "ab"[i] + cat = register_generated(f"LffLhfPanel{c.upper()}", + knobbed_xml(f"lff_lhf_panel_{c}", (NOM_T / 2, NOM_W / 2, NOM_H / 2), WOOD[i])) + objs.append((p, cat, f"panel{i}_region", (-0.30 + 0.12 * i, -0.31, -0.29 + 0.12 * i, -0.30))) + for i, k in enumerate(MARKS): + c = "abc"[i] + cat = register_generated(f"LffLhfPostmark{c.upper()}", + flat_xml(f"lff_lhf_postmark_{c}", (NOM_B / 2 + 0.003, NOM_B / 2 + 0.003, 0.0005), + MARK_RGBA), free=False) + fx.append((k, cat, f"mark{i}_region", (-0.30 + 0.12 * i, 0.10, -0.29 + 0.12 * i, 0.11))) + for i, k in enumerate(STRIPS): + c = "ab"[i] + cat = register_generated(f"LffLhfStrip{c.upper()}", + flat_xml(f"lff_lhf_strip_{c}", (STRIP_W / 2, NOM_W / 2 + 0.005, 0.0005), + STRIP_RGBA), free=False) + fx.append((k, cat, f"strip{i}_region", (-0.30 + 0.12 * i, -0.11, -0.29 + 0.12 * i, -0.10))) + return write_bddl(self.name, "Build a small fence from the posts and panels", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.fix_bid, self.fix_vis = {}, {} + for k in MARKS + STRIPS: + b = m.body_name2id(self.env.fixtures_dict[k].root_body) + self.fix_bid[k] = b + self.fix_vis[k] = [g for g in range(m.ngeom) if m.geom_bodyid[g] in + {b} | {c for c in range(m.nbody) if m.body_parentid[c] == b} and m.geom_type[g] == 6] + self.gid, self.vis, self.pbody = {}, {}, {} + for p in OBJS: + kind, c = p.split("_")[0], p.split("_")[1] + self.gid[p] = {nm: m.geom_name2id(f"{p}_lff_lhf_{kind}_{c}_{nm}") for nm in ("board", "stem", "knob")} + body = int(m.geom_bodyid[self.gid[p]["board"]]) + self.pbody[p] = body + self.vis[p] = [g for g in range(m.ngeom) if m.geom_bodyid[g] == body and m.geom_contype[g] == 0 + and m.geom_conaffinity[g] == 0] + self.geom_owner = {} + for p in OBJS: + for g in self.gid[p].values(): + self.geom_owner[g] = p + self.finger_geoms, self.hand_geoms = set(), set() + for g in envs.robot_geom_ids(self.env): + n = m.geom_id2name(g) or "" + (self.finger_geoms if "finger" in n else self.hand_geoms).add(g) + self.robot_geoms = self.finger_geoms | self.hand_geoms + # per-geom lookup tables for the substep contact check: object index (-1 none), robot part (1 finger, 2 hand) + self.owner = np.full(m.ngeom, -1, int) + for i, p in enumerate(OBJS): + self.owner[list(self.gid[p].values())] = i + self.part = np.zeros(m.ngeom, int) + self.part[list(self.finger_geoms)] = 1 + self.part[list(self.hand_geoms)] = 2 + self._sub_rob, self._sub_obj = {}, {} + # Contacts are collected after every MuJoCo substep: a fast hit (a finger flicking a knob, a hanging object + # sweeping past) can last less than one 25-substep control step (v1, measured). Wrappers chain. + sim = self.env.sim + if not getattr(sim, "_lhf_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lhf_task", None) + if t is not None and t.mon is not None: + t._substep() + sim.step = step + sim._lhf_wrapped = True + sim._lhf_task = self + self.inst = None + self.mon = None + self.sk = None + + def _substep(self): + d = self.env.sim.data + n = d.ncon + if not n: + return + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + o1, o2 = self.owner[g1], self.owner[g2] + for a, b, pa, pb in zip(g1, g2, o1, o2): + if pa < 0 and pb < 0: + continue + if pa >= 0 and pb >= 0: + if pa != pb: + self._sub_obj[int(pa)] = int(pb) + self._sub_obj[int(pb)] = int(pa) + continue + p, o = (pa, b) if pa >= 0 else (pb, a) + part = self.part[o] + if part: + prev = self._sub_rob.get(int(p), 0) + self._sub_rob[int(p)] = 1 if (part == 1 or prev == 1) else 2 + + # ------------------------------------------------------------ instances + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + row = "lr" if rng.random() < 0.5 else "fb" + hazard = bool((int(seed) * 7) % 20 < round(20 * P_HAZARD)) # balanced: 13 of every 20 consecutive seeds + t, w, h = (float(rng.uniform(*T_RANGE)), float(rng.uniform(*W_RANGE)), float(rng.uniform(*H_RANGE))) + b = float(rng.uniform(*B_RANGE)) + gap = float(rng.uniform(*GAP_RANGE)) + dens_panel, dens_post = float(rng.uniform(*DENS_RANGE)), float(rng.uniform(*DENS_RANGE)) + mu = float(rng.uniform(*MU_RANGE)) + foot = 0.0 if hazard else float(rng.uniform(*FOOT_RANGE)) + pitch = w + 2 * gap + b # post centre to post centre + if row == "lr": + c = np.array([rng.uniform(-0.12, -0.06), rng.uniform(-0.05, 0.05)]) + u = np.array([0.0, 1.0]) + v = np.array([-1.0, 0.0]) # supply side: towards the robot + else: + side = 1.0 if rng.random() < 0.5 else -1.0 + c = np.array([rng.uniform(-0.16, -0.10), side * rng.uniform(0.09, 0.13)]) + u = np.array([1.0, 0.0]) + v = np.array([0.0, -side]) # supply side: towards the middle + phi = float(np.arctan2(u[1], u[0])) # direction of the fence line + pyaw = _wrap_h(phi - np.pi / 2) # panel yaw: body y (width) along the line, body x (thickness) across + g = float(rng.uniform(*SUP_PITCH)) + d = float(rng.uniform(*SUP_D)) + shift = float(rng.choice([-1.0, 1.0]) * rng.uniform(0.04, 0.07)) + if row == "fb": # keep the farthest supply slot within ~63 cm of the robot base, the far post within ~66 cm + c[0] -= max(0.0, c[0] + shift + g - X_FAR) + c[0] -= max(0.0, c[0] + pitch - X_FAR - 0.03) + slots = [(c + u * (s - 2) * pitch / 2).tolist() for s in range(5)] + sup = [c + v * (d + j * g) + u * (shift + (k - 1) * g) for j in range(2) for k in range(3)] + pick = rng.permutation(6)[:5] + start = {OBJS[i]: (sup[j] + rng.uniform(-0.008, 0.008, 2)).tolist() for i, j in enumerate(pick)} + yaw0 = {p: pyaw + float(rng.uniform(-0.15, 0.15)) for p in OBJS} + return dict(seed=int(seed), row=row, hazard=hazard, posts="light" if hazard else "footed", foot_mass=foot, + t=t, w=w, h=h, b=b, gap=gap, pitch=pitch, density_panel=dens_panel, density_post=dens_post, mu=mu, + center=c.tolist(), u=u.tolist(), v=v.tolist(), phi=phi, pyaw=pyaw, slots=slots, + knob_dist=w / 2 + gap + b / 2, start=start, yaw0=yaw0, supply_shift=shift, supply_pitch=g, + supply_d=d) + + def _set_body(self, p, half, density, foot=0.0): + """resize p's geoms, set mass / centre of mass / inertia (board + knob + optional hidden foot), refit BVH""" + m = self.env.sim.model + hx, hy, hz = half + spec = {"board": ([hx, hy, hz], [0, 0, 0], [hx, hy, hz]), + "stem": ([STEM_R, STEM_L / 2, 0], [0, 0, hz + STEM_L / 2], [STEM_R, STEM_R, STEM_L / 2]), + "knob": ([KNOB_R, 0, 0], [0, 0, hz + STEM_L + KNOB_R], [KNOB_R, KNOB_R, KNOB_R])} + for nm, g in self.gid[p].items(): + sz, pos, aabb = spec[nm] + m.geom_size[g] = sz + m.geom_pos[g] = pos + m.geom_aabb[g] = [0, 0, 0] + aabb + m.geom_rbound[g] = float(np.linalg.norm(aabb)) + for nm, g in zip(("board", "stem", "knob"), self.vis[p]): + m.geom_size[g] = spec[nm][0] + m.geom_pos[g] = spec[nm][1] + bd = self.pbody[p] + X, Y, Z = 2 * hx, 2 * hy, 2 * hz + mb = density * X * Y * Z + zk = hz + STEM_L + KNOB_R + zf = -hz + FOOT_H / 2 + M = mb + KNOB_MASS + foot + zc = (KNOB_MASS * zk + foot * zf) / M + I = np.array([mb * (Y * Y + Z * Z) / 12, mb * (X * X + Z * Z) / 12, mb * (X * X + Y * Y) / 12]) + if foot: + I += foot * np.array([(Y * Y + FOOT_H ** 2) / 12, (X * X + FOOT_H ** 2) / 12, (X * X + Y * Y) / 12]) + par = mb * zc ** 2 + KNOB_MASS * (zk - zc) ** 2 + foot * (zf - zc) ** 2 + I[:2] += par + m.body_mass[bd] = M + m.body_ipos[bd] = [0, 0, zc] + m.body_iquat[bd] = [1, 0, 0, 0] + m.body_inertia[bd] = I + refit_bvh(m, bd) + return dict(mass=float(M), com_above_bottom=float(zc + hz)) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + self.body_info = {} + for p in POSTS: + self.body_info[p] = self._set_body(p, (inst["b"] / 2, inst["b"] / 2, inst["h"] / 2), inst["density_post"], + inst["foot_mass"]) + for p in PANELS: + self.body_info[p] = self._set_body(p, (inst["t"] / 2, inst["w"] / 2, inst["h"] / 2), + inst["density_panel"]) + for p in OBJS: + envs.set_friction(self.env, p, inst["mu"]) # board / stem / knob sliding friction ... + m.geom_friction[self.gid[p]["knob"]] = [1.0, KNOB_MU_T, 0.0001] # ... except the knob (grip pivot) + m.geom_friction[self.gid[p]["stem"]] = [1.0, 0.005, 0.0001] + m.geom_priority[self.gid[p]["knob"]] = 2 + m.geom_condim[self.gid[p]["knob"]] = 4 + self.env.sim.forward() + q = [np.cos(inst["pyaw"] / 2), 0, 0, np.sin(inst["pyaw"] / 2)] + for s, kind in enumerate(SLOT_KIND): + k = MARKS[s // 2] if kind == "post" else STRIPS[s // 2] + x, y = inst["slots"][s] + m.body_pos[self.fix_bid[k]] = [x, y, TZ + 0.0006] + m.body_quat[self.fix_bid[k]] = q + for g in self.fix_vis[k]: + m.geom_size[g] = ([inst["b"] / 2 + 0.003, inst["b"] / 2 + 0.003, 0.0005] if kind == "post" else + [STRIP_W / 2, inst["w"] / 2 + 0.005, 0.0005]) + for p in OBJS: + envs.place_upright(self.env, p, inst["start"][p], yaw=inst["yaw0"][p], clearance=0.001) + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = FenceSkills(self.env, self, recorder=recorder) + self._sub_rob, self._sub_obj = {}, {} + n = len(SLOT_KIND) + self.mon = dict(state=[False] * n, raw_since=[0] * n, ever=[False] * n, lost=[False] * n, events=[], + last_robot={p: None for p in OBJS}, last_obj={p: None for p in OBJS}, + fallen={p: False for p in OBJS}, occupant=[None] * n, n_steps=0) + return self.sk + + # ------------------------------------------------------------ geometry / predicates + @staticmethod + def kind(p): + return "post" if p.startswith("post") else "panel" + + def R(self, p): + return self.env.sim.data.body_xmat[envs.body_id(self.env, p)].reshape(3, 3).copy() + + def pos(self, p): + return envs.obj_pos(self.env, p) + + def tilt(self, p): + return float(np.arccos(np.clip(self.R(p)[2, 2], -1.0, 1.0))) + + def knob_xyz(self, p): + return self.env.sim.data.geom_xpos[self.gid[p]["knob"]].copy() + + def knob_stand_z(self): + """grasp-point height (world) of a knob centre when its object stands on the table (posts = panel height)""" + return TZ + self.inst["h"] + STEM_L + KNOB_R + + def held(self, p): + return self.sk is not None and self.sk.holding(p) + + def on_slot(self, p, s, extra=0.0): + """object p stands upright on fence slot s (right kind, lined up), resting on the table, not held""" + if self.kind(p) != SLOT_KIND[s]: + return False + R = self.R(p) + if R[2, 2] < np.cos(TILT_OK + (np.radians(1.0) if extra else 0.0)): + return False + rel = self.pos(p)[:2] - np.asarray(self.inst["slots"][s]) + du = abs(rel @ np.asarray(self.inst["u"])) + dv = abs(rel @ np.asarray(self.inst["v"])) + if SLOT_KIND[s] == "post": + if max(du, dv) > TOL_POST + extra: + return False + else: + if du > TOL_U + extra or dv > TOL_V + extra: + return False + yaw = float(np.arctan2(R[1, 0], R[0, 0])) + if abs(_wrap_h(yaw - self.inst["pyaw"])) > YAW_TOL: + return False + if envs.obj_min_z(self.env, p) > TZ + 0.006: + return False + return not self.held(p) + + def slot_occupant(self, s, extra=0.0): + return next((p for p in OBJS if self.on_slot(p, s, extra)), None) + + def slot_filled(self, s, extra=0.0): + return self.slot_occupant(s, extra) is not None + + def stages(self): + return [self.slot_filled(s) for s in range(len(SLOT_KIND))] + + def stage_names(self): + out, kc = [], {"post": 0, "panel": 0} + for kind in SLOT_KIND: + kc[kind] += 1 + out.append(f"{kind}{kc[kind]}") + return out + + # ------------------------------------------------------------ monitor + def _contacts(self): + d = self.env.sim.data + rob, obj = {}, {} + for j in range(d.ncon): + c = d.contact[j] + a, b = c.geom1, c.geom2 + pa, pb = self.geom_owner.get(a), self.geom_owner.get(b) + if pa is not None and pb is not None and pa != pb: + obj[pa], obj[pb] = pb, pa + for p, o in ((pa, b), (pb, a)): + if p is None: + continue + if o in self.finger_geoms: + rob[p] = "finger" + elif o in self.hand_geoms and rob.get(p) != "finger": + rob[p] = "hand" + return rob, obj + + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + mon["n_steps"] += 1 + t = self.sk.n_steps + rob = {OBJS[i]: ("finger" if v == 1 else "hand") for i, v in self._sub_rob.items()} + obj = {OBJS[i]: OBJS[j] for i, j in self._sub_obj.items()} + self._sub_rob, self._sub_obj = {}, {} + held = [p for p in OBJS if self.held(p)] + for p, part in rob.items(): + if p not in held: + mon["last_robot"][p] = (part, t, "open" if self.sk.grip < 0 else "closed") + for p, q in obj.items(): + if p not in held: + mon["last_obj"][p] = (q + (" (held)" if q in held else ""), t) + for p in OBJS: + f = self.tilt(p) > FALLEN + if f != mon["fallen"][p]: + mon["fallen"][p] = f + if f: + mon["events"].append(dict(object=p, event="toppled", step=int(t), cause=self._cause(p, t))) + else: + mon["events"].append(dict(object=p, event="stood_up", step=int(t))) + if mon["n_steps"] % 2: + return + names = self.stage_names() + for s in range(len(SLOT_KIND)): + occ = self.slot_occupant(s, HYST if mon["state"][s] else 0.0) + raw = occ is not None + if raw: + mon["occupant"][s] = occ + if raw == mon["state"][s]: + mon["raw_since"][s] = 0 + continue + mon["raw_since"][s] += 2 + if mon["raw_since"][s] < DEBOUNCE: + continue + mon["state"][s] = raw + mon["raw_since"][s] = 0 + t0 = t - DEBOUNCE + 1 + if raw: + ev = dict(stage=names[s], event="restored" if mon["lost"][s] else "achieved", step=int(t0)) + mon["ever"][s] = True + else: + mon["lost"][s] = True + ev = dict(stage=names[s], event="lost", step=int(t0), cause=self._slot_cause(s, t)) + mon["events"].append(ev) + + def _cause(self, p, t): + if self.held(p): + return "picked_up" + lr, lo = self.mon["last_robot"][p], self.mon["last_obj"][p] + cands = [] + if lr is not None and t - lr[1] <= 60: + cands.append((lr[1], f"robot_{lr[0]}" + ("_opening" if lr[2] == "open" else ""))) + if lo is not None and t - lo[1] <= 60: + cands.append((lo[1] - 30, "object:" + lo[0])) # prefer the robot when both touched it recently + return max(cands)[1] if cands else "other" + + def _slot_cause(self, s, t): + """why slot s lost its object: the cause recorded for the object that last stood on it""" + p = self.mon["occupant"][s] + if p is None: + c = np.asarray(self.inst["slots"][s]) + p = min(OBJS, key=lambda q: float(np.linalg.norm(self.pos(q)[:2] - c))) + return self._cause(p, t) + + # ------------------------------------------------------------ outcome + def _slot_name(self, s): + kind = SLOT_KIND[s] + idx = [i for i in range(len(SLOT_KIND)) if SLOT_KIND[i] == kind] + n = len(idx) + k = idx.index(s) # 0-based along +u + if self.inst["row"] == "lr": # u = +y = robot's left: count from the robot's right + what = "square mark" if kind == "post" else "strip" + return f"{what} {k + 1} of {n} (counting from the robot's right)" + what = "square mark" if kind == "post" else "strip" + u = self.inst["u"] + return f"{what} {k + 1 if u[0] > 0 else n - k} of {n} (counting from the one nearest the robot)" + + def _dir_words(self, d): + parts = [] + if abs(d[0]) >= 0.01: + parts.append(f"{100 * abs(d[0]):.0f} cm {'forward' if d[0] > 0 else 'back'}") + if abs(d[1]) >= 0.01: + parts.append(f"{100 * abs(d[1]):.0f} cm {'left' if d[1] > 0 else 'right'}") + return (" and ".join(parts) + " of") if parts else "right at" + + def placed_objects(self): + return {p for p in OBJS if any(self.on_slot(p, s) for s in range(len(SLOT_KIND)))} + + def outcome(self, inst): + sk = self.sk + sk.hold(10) + p0 = {p: self.pos(p) for p in OBJS} + touching = False + for _ in range(20): + sk.hold(1) + rob, _ = self._contacts() + touching = touching or any(p in rob for p in OBJS) + moved = max(float(np.linalg.norm(self.pos(p) - p0[p])) for p in OBJS) + static = moved < 0.004 + raw = self.stages() + held = [p for p in OBJS if self.held(p)] + mon = self.mon + ev = list(mon["events"]) if mon else [] + n_reg = sum(e["event"] == "lost" for e in ev) + n_res = sum(e["event"] == "restored" for e in ev) + n_top = sum(e["event"] == "toppled" for e in ev) + success = bool(all(raw) and static and not held and not touching) + names = self.stage_names() + parts = [] + ever = mon["ever"] if mon else [False] * len(raw) + if success: + failure = "none" + parts.append("The fence is complete: every square mark carries an upright post and every strip an " + "upright panel lined up with it.") + else: + lost_final = [s for s in range(len(raw)) if not raw[s] and ever[s]] + never = [s for s in range(len(raw)) if not raw[s] and not ever[s]] + if held: + failure = "held" + elif touching: + failure = "touching" + elif lost_final: + failure = "regressed" + elif never: + failure = "incomplete" + else: + failure = "not_static" + placed = self.placed_objects() + described = set() + for s in range(len(raw)): + if raw[s]: + continue + kind = SLOT_KIND[s] + c = np.asarray(inst["slots"][s]) + spare = [q for q in OBJS if self.kind(q) == kind and q not in placed and q not in described] + near = min(spare, key=lambda q: float(np.linalg.norm(self.pos(q)[:2] - c))) if spare else None + dist = float(np.linalg.norm(self.pos(near)[:2] - c)) if near else 1.0 + if near is None or (not ever[s] and dist > 0.06): + txt = f"{self._slot_name(s)} has no {kind} on it (none was put there)." + else: + described.add(near) + tl = np.degrees(self.tilt(near)) + state = ("lies fallen" if tl > 45 else f"leans {tl:.0f} degrees" if tl > np.degrees(TILT_OK) + else "stands") + txt = (f"{self._slot_name(s)} has no upright {kind} on it: the nearest {kind} {state} " + f"{self._dir_words(self.pos(near)[:2] - c)} it.") + if ever[s]: + lost = [e for e in ev if e.get("stage") == names[s] and e["event"] == "lost"] + why = lost[-1]["cause"] if lost else "other" + txt += {"robot_finger_opening": f" The {kind} had stood there; a finger pushed it when the " + f"gripper opened.", + "robot_hand_opening": f" The {kind} had stood there; the hand pushed it.", + }.get(why, f" The {kind} had stood there and was knocked over later." + if why.startswith(("robot", "object")) else f" The {kind} had stood there earlier.") + parts.append(txt) + if all(raw) and held: + parts.append("The gripper still holds an object.") + elif touching: + parts.append("The gripper is still touching the fence.") + elif all(raw) and not static: + parts.append("Something was still moving.") + if n_reg: + parts.append(f"During the attempt objects on the fence line were knocked off {n_reg} time(s) and stood " + f"up again {n_res} time(s).") + if any(w in " ".join(parts) for w in (" forward of", " back of", " back and", " forward and")): + parts.append("(Forward = away from the robot.)") + return dict(success=success, stages={names[s]: bool(raw[s]) for s in range(len(raw))}, events=ev, + n_regressions=int(n_reg), n_restored=int(n_res), n_toppled=int(n_top), failure=failure, + held=held, touching=bool(touching), static=bool(static), + tilts_deg={p: round(float(np.degrees(self.tilt(p))), 1) for p in OBJS}, detail=" ".join(parts)) + + # ------------------------------------------------------------ scripted policies (move_to + gripper only) + def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300): + return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + + def axis(self, p, i): + a = self.R(p)[:2, i] + return a / max(np.linalg.norm(a), 1e-9) + + def grasp_yaw(self, p, mode): + """yaw for a top-down knob grasp. Lying object: fingers across its long axis (it swings up and hangs). + Panel: 'habit' = fingers along its width (hand along the board; along the fence line once placed), + 'thin' = fingers along its thickness (across the line). Post: 'thin' = fingers across the fence line, otherwise + the side direction needing the least rotation (a post's own orientation does not matter: square, round knob).""" + R = self.R(p) + if R[2, 2] < np.cos(np.radians(30)): + ax = R[:2, 2] + if np.linalg.norm(ax) > 1e-3: + return _yaw_for_axis(np.array([-ax[1], ax[0]])) + if self.kind(p) == "panel": + return _yaw_for_axis(self.axis(p, 1) if mode == "habit" else self.axis(p, 0)) + if mode == "thin": # careful: a post's fingers across the fence line too (they reach nothing there) + return _yaw_for_axis(np.asarray(self.inst["v"])) + y0 = _yaw_for_axis(self.axis(p, 0)) + return min((_wrap_h(y0), _wrap_h(y0 + np.pi / 2)), key=lambda y: abs(_wrap_h(y - self.sk.yaw))) + + def obj_yaw(self, p): + R = self.R(p) + return float(np.arctan2(R[1, 0], R[0, 0])) + + def pick(self, p, mode, careful, z_carry=None, noise=None, v=0.15): + """grasp p's knob and lift it; returns (object yaw - gripper yaw) or None if not held""" + sk = self.sk + k = self.knob_xyz(p) + if noise is not None: + k = k + np.array([noise[0], noise[1], 0.0]) + yaw = self.grasp_yaw(p, mode) + zk = max(k[2], TZ + 0.006) + sk.set_gripper(False, steps=8) + if careful: + cur = sk.eef_pos() + if cur[2] < TZ + Z_SAFE - 0.01: + self._go([cur[0], cur[1], TZ + Z_SAFE]) + self._go([k[0], k[1], TZ + Z_SAFE], yaw=yaw, speed=0.3) + self._go([k[0], k[1], zk + 0.04], speed=0.25) + self._go([k[0], k[1], zk], speed=0.1, tol=0.003, max_steps=150) + else: # Sonnet-like: over the knob at carry height, down at 0.1 to 1.5 cm above, last 1.5 cm at 0.04 + zt = TZ + (Z_NAIVE if z_carry is None else z_carry) + cur = sk.eef_pos() + self._go([k[0], k[1], max(cur[2], zt, zk + 0.06)], yaw=yaw, speed=v) + self._go([k[0], k[1], zk + 0.015], speed=0.1) + self._go([k[0], k[1], zk], speed=0.04, tol=0.003, max_steps=150) + sk.set_gripper(True, steps=15) + if careful: + self._go([k[0], k[1], TZ + Z_SAFE], speed=0.25) + else: + self._go([k[0], k[1], TZ + (Z_NAIVE if z_carry is None else z_carry)], speed=0.08) + sk.hold(10) + if not self.held(p): + sk.set_gripper(False, steps=8) # already lifted: the fingers open well above the object + return None + return float(self.obj_yaw(p) - sk.yaw) + + def release_z(self, p): + """grasp-point height at which the held object's bottom is 2 mm above the table (a heavy object's knob can + sit a few mm low in the fingers; pressing it onto the table would squeeze the knob out of the grip)""" + dz = float(self.sk.eef_pos()[2] - self.knob_xyz(p)[2]) if self.held(p) else 0.0 + return self.knob_stand_z() + 0.002 + float(np.clip(dz, -0.005, 0.015)) + + def place_yaw(self, p, offset): + """gripper yaw that lines p up with the fence (panel: width along the line; post: sides along it)""" + if self.kind(p) == "panel": + return _wrap_h(self.inst["pyaw"] - offset) + cands = [_wrap_h(self.inst["pyaw"] + k * np.pi / 2 - offset) for k in range(4)] + return min(cands, key=lambda y: abs(_wrap_h(y - self.sk.yaw))) + + def place(self, p, s, offset, careful, z_carry=None, noise=None, lift=None, v=0.15): + """carry the held object to fence slot s, lined up with the fence; set it down; let go""" + sk = self.sk + xy = np.asarray(self.inst["slots"][s], float) + (np.asarray(noise, float) if noise is not None else 0.0) + yaw = self.place_yaw(p, offset) + zr = self.release_z(p) + if careful: + cur = sk.eef_pos() + if cur[2] < TZ + Z_SAFE - 0.01: + self._go([cur[0], cur[1], TZ + Z_SAFE]) + self._go([xy[0], xy[1], TZ + Z_SAFE], yaw=yaw, speed=0.3) + sk.hold(15) + zr = self.release_z(p) + self._go([xy[0], xy[1], zr + 0.03], speed=0.2) + self._go([xy[0], xy[1], zr], speed=0.06, tol=0.003, max_steps=150) + sk.set_gripper(False, steps=12) + self._go([xy[0], xy[1], zr + 0.04], speed=0.1) + self._go([xy[0], xy[1], TZ + Z_SAFE], speed=0.3) + else: # Sonnet-like: to above the slot at carry height, 0.1 m/s to 1.5 cm above, last 1.5 cm at 0.03, open + zt = TZ + (Z_NAIVE if z_carry is None else z_carry) + cur = sk.eef_pos() + self._go([xy[0], xy[1], max(cur[2], zt)], yaw=yaw, speed=v) + self._go([xy[0], xy[1], zr + 0.015], speed=0.1) + self._go([xy[0], xy[1], zr], speed=0.03, tol=0.003, max_steps=150) + sk.set_gripper(False, steps=12) + self._go([xy[0], xy[1], TZ + (Z_NAIVE if lift is None else lift)], speed=0.15) + sk.hold(5) + + # orders --------------------------------------------------------------- + def supply_center(self): + return np.mean([self.inst["start"][p] for p in OBJS], axis=0) + + def fence_order(self, far_first=True): + """slot indices from the end of the line farthest from the supply to the near end (or reversed)""" + sc = self.supply_center() + first, last = np.asarray(self.inst["slots"][0]), np.asarray(self.inst["slots"][-1]) + idx = list(range(len(SLOT_KIND))) + near_first = idx if np.linalg.norm(first - sc) <= np.linalg.norm(last - sc) else idx[::-1] + return near_first[::-1] if far_first else near_first + + def build(self, order, careful, panel_mode, noise_fn=lambda: None, z_carry=None, lift=None, noise_pick=False, + v=0.15): + """put an object on every slot that has none, in the given slot order; the object for each slot: an unused + one of the right kind, the nearest to the gripper (naive) / to the slot (careful). No looking back.""" + fails = {} + used = set() + for s in order: + if self.slot_filled(s): + continue + for _ in range(2): + cand = [p for p in OBJS if self.kind(p) == SLOT_KIND[s] and p not in used and fails.get(p, 0) < 2 + and p not in self.placed_objects()] + if not cand: + break + ref = np.asarray(self.inst["slots"][s]) if careful else self.sk.eef_pos()[:2] + p = min(cand, key=lambda q: float(np.linalg.norm(self.pos(q)[:2] - ref))) + mode = panel_mode if self.kind(p) == "panel" else ("thin" if careful else "any") + off = self.pick(p, mode, careful, z_carry=z_carry, noise=noise_fn() if noise_pick else None, v=v) + if off is None: + fails[p] = fails.get(p, 0) + 1 + continue + used.add(p) + self.place(p, s, off, careful, z_carry=z_carry, noise=noise_fn(), lift=lift, v=v) + break + + def footprint(self, p): + """sample points of p's collision box projected onto the table (corners, edge and face midpoints) + knob""" + R, c = self.R(p), self.pos(p) + if self.kind(p) == "panel": + h = np.array([self.inst["t"], self.inst["w"], self.inst["h"]]) / 2 + else: + h = np.array([self.inst["b"], self.inst["b"], self.inst["h"]]) / 2 + pts = [c + R @ (h * [a, b, z]) for a in (-1, 0, 1) for b in (-1, 0, 1) for z in (-1, 0, 1)] + pts.append(self.knob_xyz(p)) + return np.array(pts)[:, :2] + + def slot_blocked(self, s, ignore=()): + """an object that is not standing on a slot lies (partly) on slot s or right next to it""" + c = np.asarray(self.inst["slots"][s]) + u, v = np.asarray(self.inst["u"]), np.asarray(self.inst["v"]) + hu = (self.inst["w"] if SLOT_KIND[s] == "panel" else self.inst["b"]) / 2 + 0.003 + hv = (self.inst["t"] if SLOT_KIND[s] == "panel" else self.inst["b"]) / 2 + 0.008 + placed = self.placed_objects() + for q in OBJS: + if q in ignore or self.held(q) or q in placed: # objects standing on their own slots are fine + continue + d = self.footprint(q) - c + if np.any((np.abs(d @ u) < hu) & (np.abs(d @ v) < hv)): + return True + return False + + def fingers_along_width(self, p): + """the held panel's width axis is (nearly) parallel to the finger axis""" + fa = np.array([-np.sin(self.sk.yaw), np.cos(self.sk.yaw)]) + return abs(float(self.axis(p, 1) @ fa)) > 0.7 + + def repair(self, rounds=None): + """look at every slot; stand fallen / misplaced objects up again by their knobs (careful motions, panels + released with the fingers across the line). Order: an object resting on another first, then fallen / leaning + ones from the top of the pile down, then upright ones that are off their slots. A panel lifted with its + fingers along its width (a fallen panel can only be lifted that way) is first set down standing at a free spot + and re-grasped. Returns the number of objects moved.""" + n = len(SLOT_KIND) + moved = 0 + fails, moves = {}, {} + for _ in range(rounds or 16): + if all(self.stages()): + break + ok = self.placed_objects() + loose = [p for p in OBJS if p not in ok and fails.get(p, 0) < 2 and moves.get(p, 0) < 4] + if not loose: + break + on_other = [p for p in loose if envs.obj_min_z(self.env, p) > TZ + 0.006] + down = [p for p in loose if p not in on_other and self.tilt(p) > TILT_OK] + upright = [p for p in loose if p not in on_other and p not in down] + if on_other: + p = max(on_other, key=lambda q: self.knob_xyz(q)[2]) + elif down: + p = max(down, key=lambda q: self.knob_xyz(q)[2]) + else: + fit = {q: [s for s in range(n) if SLOT_KIND[s] == self.kind(q) and not self.slot_filled(s) + and not self.slot_blocked(s, ignore=(q,))] for q in upright} + fit = {q: js for q, js in fit.items() if js} + if not fit: + break + p = min(fit, key=lambda q: min(float(np.linalg.norm(self.pos(q)[:2] - np.asarray( + self.inst["slots"][s]))) for s in fit[q])) + off = self.pick(p, "thin", True) + if off is None: + fails[p] = fails.get(p, 0) + 1 + continue + moved += 1 + moves[p] = moves.get(p, 0) + 1 + if self.kind(p) == "panel" and self.fingers_along_width(p): + self.place_at(p, self.free_spot(), off) + continue + clear = [s for s in range(n) if SLOT_KIND[s] == self.kind(p) and not self.slot_filled(s) + and not self.slot_blocked(s, ignore=(p,))] + if not clear: + self.place_at(p, self.free_spot(), off) + continue + here = self.sk.eef_pos()[:2] + s = min(clear, key=lambda j: float(np.linalg.norm(np.asarray(self.inst["slots"][j]) - here))) + self.place(p, s, off, True) + return moved + + def free_spot(self): + """the reachable table spot (around the fence and the supply) farthest from every object and slot""" + c, v = np.asarray(self.inst["center"]), np.asarray(self.inst["v"]) + u = np.asarray(self.inst["u"]) + best, bc = None, -1.0 + for a in np.linspace(-0.20, 0.20, 9): + for b in (-0.18, -0.12, 0.10, 0.20, 0.32): + q = c + v * b + u * a + if not (-0.40 < q[0] < 0.08 and -0.32 < q[1] < 0.32) or np.hypot(q[0] + 0.66, q[1]) > 0.60: + continue + cl = min(float(np.linalg.norm(self.pos(o)[:2] - q)) for o in OBJS) + cl = min(cl, min(float(np.linalg.norm(np.asarray(sl) - q)) for sl in self.inst["slots"])) + if cl > bc: + best, bc = q, cl + return best + + def place_at(self, p, xy, offset): + """careful: set the held object down standing at a free spot""" + sk = self.sk + zr = self.release_z(p) + cur = sk.eef_pos() + if cur[2] < TZ + Z_SAFE - 0.01: + self._go([cur[0], cur[1], TZ + Z_SAFE]) + self._go([xy[0], xy[1], TZ + Z_SAFE], yaw=self.place_yaw(p, offset), speed=0.3) + sk.hold(15) + zr = self.release_z(p) + self._go([xy[0], xy[1], zr + 0.03], speed=0.2) + self._go([xy[0], xy[1], zr], speed=0.06, tol=0.003, max_steps=200) + sk.set_gripper(False, steps=12) + self._go([xy[0], xy[1], zr + 0.04], speed=0.1) + self._go([xy[0], xy[1], TZ + Z_SAFE], speed=0.3) + + # ------------------------------------------------------------ policies + def execute(self, inst, params): + careful = params["careful"] + noise = params.get("noise", 0.0) + rng = np.random.default_rng(params.get("noise_seed", 0)) + nf = (lambda: rng.uniform(-noise, noise, 2)) if noise else (lambda: None) + if params.get("order") == "panels_first": + fo = self.fence_order(True) + order = [s for s in fo if SLOT_KIND[s] == "panel"] + [s for s in fo if SLOT_KIND[s] == "post"] + elif params.get("order") == "posts_first": + fo = self.fence_order(True) + order = [s for s in fo if SLOT_KIND[s] == "post"] + [s for s in fo if SLOT_KIND[s] == "panel"] + else: + order = self.fence_order(params.get("far_first", True)) + self.build(order, careful, params["panel_mode"], noise_fn=nf, z_carry=params.get("z_carry"), + lift=params.get("lift"), noise_pick=params.get("noise_pick", False), v=params.get("v", 0.15)) + if params.get("check"): + self.repair() + cur = self.sk.eef_pos() + if cur[2] < TZ + 0.20: + self._go([cur[0], cur[1], TZ + 0.20], speed=0.3) + self.sk.hold(10) + + # naive = Sonnet 5.5's habits measured in the lh2_fence pilot: hand (finger axis) along the board's long side, fill + # from the far end, carry 21 cm above the table at 0.15 m/s, slow last 1.5 cm, ~1 cm placement error, no re-check + NAIVE = dict(careful=False, panel_mode="habit", far_first=True, check=False, noise=NAIVE_ERR) + CAREFUL = dict(careful=True, panel_mode="thin", far_first=True, check=True) + V1_NAIVE = dict(careful=False, panel_mode="thin", far_first=False, check=False) # v1's scripted naive habits + + def default_params(self, inst): + return dict(self.NAIVE, noise_seed=int(inst["seed"]) * 11) + + def oracle_params(self, inst): + return dict(self.CAREFUL) + + def adapt_params(self, inst, history): + """from attempt 2 (after a failure): panels released with the fingers across the line, careful, final check""" + return dict(self.CAREFUL) + + def blind_params(self, inst, attempt, rng): + """the naive behaviour with random variations, no history, no check""" + return dict(self.NAIVE, noise_seed=int(rng.integers(1 << 30)), z_carry=float(rng.uniform(0.15, 0.23)), + lift=float(rng.uniform(0.15, 0.23)), v=float(rng.uniform(0.08, 0.25))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + single = ("oracle", "naive", "oracle_noise", "v1_naive", "naive_thin", "naive_panels_first", + "naive_posts_first") + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": # control: cross-attempt learning only (careful from attempt 2), no check + params = self.default_params(inst) if a == 0 else dict(self.CAREFUL, check=False) + elif kind == "oracle_noise": # check: careful with +-5 mm (uniform, per axis) placement noise + params = dict(self.CAREFUL, noise=0.005, noise_seed=int(seed) * 7 + a) + elif kind == "v1_naive": # control: v1's scripted naive (fingers across the line, near end first) + params = dict(self.V1_NAIVE) + elif kind == "naive_thin": # control: Sonnet-like but panels released with the fingers across the line + params = dict(self.default_params(inst), panel_mode="thin") + elif kind == "naive_panels_first": # control: Sonnet-like grasp, both panels before the posts + params = dict(self.default_params(inst), order="panels_first") + elif kind == "naive_posts_first": # control: Sonnet-like grasp, all posts first (how fences are built) + params = dict(self.default_params(inst), order="posts_first") + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in single: + break + return history diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_lid_box.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_lid_box.py new file mode 100644 index 0000000000000000000000000000000000000000..f7c6c649bba53e7fa77a0539b7034c73eb0081f2 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_lid_box.py @@ -0,0 +1,715 @@ +"""LH lid_box: put three blocks on their marks, then open a box, put a red cube in, close it -- the lid falls open onto +the marks behind the box and shoves the blocks standing there off their marks. + +Family: long-horizon self-disturbance ("state_restoration"): the agent's own normal later-stage action (opening the +lid) physically breaks earlier progress (blocks on marks); it has to notice and restore it before finishing (within an +attempt), or learn to open the box first (across attempts; the final-state judge does not enforce an order). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a flat wooden box (fixture, 12 x 16 cm, walls 3.2 cm, lid 0.6 cm) whose lid is hinged along its far edge; a black + ball knob sticks out of the middle of the lid's front edge. The lid is heavy (0.3 kg) and has no damping: once it + is lifted past vertical it falls backward and comes to rest on a stop (hidden angle) or on whatever is behind the + box; + * three 6 cm cubes ("blocks", blue / green / yellow; light, 54 g, and slippery, mu 0.25) in a row in front of the box + together with a small red cube (2.2 cm); + * three square marks (7.6 cm, outline + light fill) in the blocks' colours: two right behind the box (their near + edge 0.2-1.7 cm from the box's back wall), one beside the box. + +Hidden variable: the lid's opening stop (0 = closed, 90 = upright, 180 = flat behind the box): "far", uniform in FAR +(138-165 deg), in 13 of every 20 consecutive seeds, else "near", uniform in NEAR (100-113 deg). Before the lid is opened +nothing shows it. A far lid lands on the top edge of the blocks standing behind the box and its weight shoves them +away from the robot ("forward") off their marks (measured: 4-10 cm); a near lid comes to rest above them. Stops of +~115-135 deg are left out on purpose: there the lid only grazes the blocks (1-3 cm, right at the tolerance). + +Why the natural order fails: the instruction lists the blocks first (as a user would), so the natural plan places the +blocks, opens the lid (it falls back onto them), puts the cube in, closes the lid and finishes without looking at the +marks again. What must be learned: re-check every stage before finishing and put knocked blocks back after closing the +lid (within the attempt), or open the box first / place the blocks behind it last (across attempts). + +Lid mechanics for agents (`LidSkills`, measured, see the task card): grasping the ball knob from above (fingers on its +left and right, the default yaw) makes a pivot -- the ball turns freely between the fingers about the hinge axis. While +the knob is held, the arm is compliant along the hinge constraint: a commanded straight move is projected onto the +knob's circle around the hinge (at most 1 cm per control step; ~0.07 m/s along the arc in the agent self-test), so +"up 10 cm, then back over the hinge, release" opens the lid and "up, then forward, release" closes it; a move that +makes no more progress ends early (like KeySkills' stalling wrist in l7_key_turn). Without the compliance, all 6 +typical straight-move sequences tried (prototype: this lid with a 2 cm stem, 2026-10-09) pulled the knob out of the +fingers and the lid fell shut; with an earlier, lighter lid only a 3-segment approximation of the arc opened it. + +Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (all blocks on +their marks, red cube in the box, lid closed, nothing held, scene static) plus an event log of every stage predicate +(achieved / lost / restored, with step and cause) for the server log; F1 gives the agent only success / failure. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, _wrap, box_xml, register_generated +from ..skills import DT, Skills, _rot_err +from ..task_base import LFFTask, register_task + +# ---------------------------------------------------------------- geometry / physics +BOX = "box_1" +BOX_MODEL = "lff_lh_lid_box" +BOX_D, BOX_W = 0.12, 0.16 # outer depth (x) and width (y) +WALL_H, WALL_T, FLOOR_T = 0.032, 0.008, 0.006 +LID_T, LID_MASS = 0.006, 0.30 +KNOB_R, STEM_L = 0.013, 0.032 +HINGE_DAMP, HINGE_FRIC = 0.002, 0.002 +IN_X = BOX_D / 2 - WALL_T # inner half sizes of the cavity +IN_Y = BOX_W / 2 - WALL_T + +BLOCK = 0.06 # cube edge +BLOCK_DENS = 250.0 # -> 54 g +BLOCK_MU = 0.25 +CUBE_E = 0.022 # red cube edge +MARK_HALF = 0.038 +MARK_LINE = 0.004 +TOL = 0.020 # block centre within 2 cm (per axis) of its mark's centre +FLAT_COS = np.cos(np.radians(15.0)) +CUBE_MARGIN = 0.004 +LID_CLOSED = np.radians(4.0) +# hidden stop (deg): in a fraction P_FAR of the instances the lid opens far back, uniform in FAR (it lands on blocks +# standing behind the box and shoves them 4-10 cm), otherwise it stops near upright, uniform in NEAR (it comes to rest +# above them). Far / near is balanced per block of 20 consecutive seeds (13 / 7), see sample_instance. +# Bimodal on purpose: stops between ~115 and ~135 deg make the lid graze the blocks and push them 1-3 cm, i.e. right +# at the tolerance, which is neither a clean disturbance nor a clean no-disturbance (measured, see the task card). +P_FAR = 0.65 +FAR = (138.0, 165.0) +NEAR = (100.0, 113.0) +GAP_LO, GAP_HI = 0.002, 0.017 # near edge of a behind-mark to the box's back wall (block near face +0.8 cm further) + +COLORS = ("blue", "green", "yellow") +RGBA = dict(blue=(0.15, 0.30, 0.85, 1.0), green=(0.10, 0.60, 0.20, 1.0), yellow=(0.92, 0.76, 0.10, 1.0)) +BLOCKS = {c: f"{c}_block_1" for c in COLORS} +MARKS = {c: f"{c}_mark_1" for c in COLORS} +CUBE = "red_cube_1" + +Z_CARRY = 0.13 # scripted transit height of the grasp point above the table when carrying a block +Z_KNOB = WALL_H + LID_T / 2 # knob centre above the table with the lid closed +SMAX = 0.010 # max projected displacement command per control step while the knob is held +STALL = 12 + + +def box_lid_xml(name, body_rgba=(0.55, 0.38, 0.22, 1.0), lid_rgba=(0.70, 0.52, 0.32, 1.0), knob_rgba=(0.10, 0.10, 0.11, 1.0)): + hx, hy = BOX_D / 2, BOX_W / 2 + parts = [((0, 0, FLOOR_T / 2), (hx, hy, FLOOR_T / 2)), + ((hx - WALL_T / 2, 0, WALL_H / 2), (WALL_T / 2, hy, WALL_H / 2)), + ((-hx + WALL_T / 2, 0, WALL_H / 2), (WALL_T / 2, hy, WALL_H / 2)), + ((0, hy - WALL_T / 2, WALL_H / 2), (hx - WALL_T, WALL_T / 2, WALL_H / 2)), + ((0, -hy + WALL_T / 2, WALL_H / 2), (hx - WALL_T, WALL_T / 2, WALL_H / 2))] + g = [] + # box: contype 2 / conaffinity 1 and lid: contype 4 / conaffinity 1 -> the lid never collides with its own box (the + # hinge limit holds it closed), but both collide with the robot, the table and the free objects (contype 1) + for k, (pos, s) in enumerate(parts): + g.append(f'') + g.append(f'') + m, L = LID_MASS, BOX_D + lid_c = (-L / 2, 0, LID_T / 2) + lid_s = (L / 2, hy, LID_T / 2) + stem = (-L - STEM_L / 2, 0, LID_T / 2) + ball = (-L - STEM_L - KNOB_R * 0.7, 0, LID_T / 2) + lid = [f'', + # placeholder range: the opening stop is set per instance (apply_instance) + f'', + f'', + f'', + f'', + f'', + f'', + f''] + shell = "\n ".join(g) + lid_xml = "\n ".join(lid) + return f""" + + + + {shell} + + {lid_xml} + + + + + + + +""" + + +def mark_xml(name, rgba): + """Flat, visual-only square drawn on the table: a light fill plus an outline in the block's colour.""" + fill = tuple(0.55 + 0.45 * c for c in rgba[:3]) + (1.0,) + o, i, w = MARK_HALF, MARK_HALF - MARK_LINE, MARK_LINE + parts = [((0, 0, 0.0004), (o, o, 0.0004), fill), + ((0, i + w / 2, 0.0010), (o, w / 2, 0.0002), rgba), + ((0, -i - w / 2, 0.0010), (o, w / 2, 0.0002), rgba), + ((i + w / 2, 0, 0.0010), (w / 2, o, 0.0002), rgba), + ((-i - w / 2, 0, 0.0010), (w / 2, o, 0.0002), rgba)] + g = "\n".join(f' ' for p, sz, c in parts) + return _wrap(name, g, 0.0012, o) + + +def _fb(v): + return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}" + + +def _lr(v): + return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}" + + +class LidSkills(Skills): + """Skills for the lid box: a per-step stage monitor, and a hinge-compliant arm while the knob is held (see the + module docstring).""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + self.latched = False + self.rad0 = None + self.y0 = None + self.knob_steps = 0 # control steps driven with the knob held (compliant mode) + self.knob_grasps = 0 + + def holding_knob(self): + """both fingers (pad or finger body) touch the knob ball or its stem""" + g = self.env.robots[0].gripper + return bool(self.env._check_grasp(gripper=[g.important_geoms["left_finger"], g.important_geoms["right_finger"]], + object_geoms=self.task.knob_geom_names)) + + def _act(self, dpos, drot, grip): + if self.latched: + e = self.eef_pos() + if self.grip < 0 or np.linalg.norm(e - self.task.knob_xyz()) > 0.035: + self.latched = False # opened, or the knob slipped out of the fingers + else: + hx, hz = self.task.hinge_xz() + r = np.array([e[0] - hx, e[2] - hz]) + rn = max(float(np.linalg.norm(r)), 1e-6) + tng = np.array([-r[1], r[0]]) / rn + s = float(np.clip(dpos[0] * tng[0] + dpos[2] * tng[1], -SMAX, SMAX)) + corr = (self.rad0 - rn) * r / rn + dpos = np.array([s * tng[0] + corr[0], self.y0 - e[1], s * tng[1] + corr[1]]) + self.knob_steps += 1 + super()._act(dpos, drot, grip) + self.task.monitor_step() + + def set_gripper(self, close, steps=15): + rep = super().set_gripper(close, steps) + if close and self.holding_knob(): + e = self.eef_pos() + hx, hz = self.task.hinge_xz() + self.latched = True + self.rad0 = float(np.hypot(e[0] - hx, e[2] - hz)) + self.y0 = float(e[1]) + self.knob_grasps += 1 + elif not close: + self.latched = False + return rep + + def move_to(self, target, yaw=None, speed=None, tol=0.004, max_steps=250, apply_bias=True, wrap_yaw=True): + """Skills.move_to plus an early stop when the knob is held and the arm has stopped making progress.""" + tgt = np.asarray(target, float) + (self.bias if apply_bias else 0.0) + if yaw is not None: + self.yaw = self.wrap_yaw(float(yaw)) if wrap_yaw else float(yaw) + R = self._R() + p0 = self.eef_pos() + dist = np.linalg.norm(tgt - p0) + direction = (tgt - p0) / max(dist, 1e-9) + s = 0.0 + hist = [] + stalled = False + for k in range(max_steps): + if speed is not None: + s = min(dist, s + speed * DT) + ref = p0 + direction * s + direction * min(dist - s, speed * DT * 1.5) + else: + ref = tgt + self._act(ref - self.eef_pos(), _rot_err(R, self.eef_mat()), self.grip) + cur = self.eef_pos() + if np.linalg.norm(tgt - cur) < tol and (speed is None or s >= dist): + break + hist.append(cur) + if (self.latched and len(hist) > STALL and (speed is None or s >= dist) + and np.linalg.norm(hist[-1] - hist[-1 - STALL]) < 0.002): + stalled = True + break + rep = dict(prim="move_to", reached=bool(np.linalg.norm(tgt - self.eef_pos()) < 0.02), + pos=self.eef_pos().round(4).tolist(), steps=k + 1, stalled=stalled) + self.log.append(rep) + return rep + + +@register_task +class LidBox(LFFTask): + name = "lh_lid_box" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Plan", "Reason", "Utilize") + protocol = "cross" + max_attempts = 3 + agent_max_steps = 110 # careful oracle ~45-55 commands + restoring two blocks (~14) + looking around + instruction = ("Put each of the three coloured blocks on the square mark of the same colour on the table. Then open " + "the lid of the wooden box (lift it by the black knob on its front edge), put the red cube inside " + "the box, and close the lid.") + instruction_indirect = ("Set the blue, green and yellow cubes onto the outlined squares of matching colour. Then open " + "the flat wooden case (its lid lifts by the black ball at the front), place the small red " + "cube in it and shut the lid.") + agent_object_names = ["blue block", "green block", "yellow block", "red cube", "wooden box", "lid knob", + "blue mark", "green mark", "yellow mark"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + box = register_generated("LffLhLidBox", box_lid_xml(BOX_MODEL), free=False) + b = BLOCK / 2 + objs, fx = [], [(BOX, box, "box_region", (-0.18, -0.01, -0.16, 0.01))] + for i, c in enumerate(COLORS): + blk = register_generated(f"LffLhBlock{c.title()}", + box_xml(f"lff_lh_block_{c}", (b, b, b), RGBA[c], density=BLOCK_DENS, + friction=(BLOCK_MU, 0.005, 0.0001)).replace(_SOLID, "")) + mark = register_generated(f"LffLhMark{c.title()}", mark_xml(f"lff_lh_mark_{c}", RGBA[c]), free=False) + objs.append((BLOCKS[c], blk, f"{c}_block_region", (-0.31, -0.22 + 0.15 * i, -0.29, -0.20 + 0.15 * i))) + fx.append((MARKS[c], mark, f"{c}_mark_region", (0.0, -0.22 + 0.15 * i, 0.02, -0.20 + 0.15 * i))) + cube = register_generated("LffLhRedCube", box_xml("lff_lh_red_cube", (CUBE_E / 2,) * 3, (0.85, 0.10, 0.08, 1.0), + density=500)) + objs.append((CUBE, cube, "red_cube_region", (-0.31, 0.24, -0.29, 0.26))) + return write_bddl(self.name, "put the blocks on their marks and the red cube in the box", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + pre = f"{BOX}_{BOX_MODEL}" + self.jid = m.joint_name2id(pre + "_hinge") + self.qa = m.jnt_qposadr[self.jid] + self.dof = m.jnt_dofadr[self.jid] + self.box_bid = m.body_name2id(self.env.fixtures_dict[BOX].root_body) + self.knob_geom_name = pre + "_knob" + self.knob_geom_names = [pre + "_knob", pre + "_stem"] + self.knob_gid = m.geom_name2id(self.knob_geom_name) + self.lid_gids = {m.geom_name2id(pre + s) for s in ("_lid", "_stem", "_knob")} + self.robot_gids = set(envs.robot_geom_ids(self.env)) + self.mark_bid = {c: m.body_name2id(self.env.fixtures_dict[MARKS[c]].root_body) for c in COLORS} + self.block_gids = {c: set(envs.obj_geom_ids(self.env, BLOCKS[c])) for c in COLORS} + self.inst = None + self.mon = None + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + bx, by = float(rng.uniform(-0.19, -0.15)), float(rng.uniform(-0.03, 0.03)) + hinge_x = bx + BOX_D / 2 + order = [str(c) for c in rng.permutation(COLORS)] # [behind-left, behind-right, side] + side = 1.0 if rng.random() < 0.5 else -1.0 + marks = {} + gaps = {} + for c, sy in zip(order[:2], (1.0, -1.0)): + g = float(rng.uniform(GAP_LO, GAP_HI)) + gaps[c] = g + marks[c] = [hinge_x + g + MARK_HALF, by + sy * 0.05 + float(rng.uniform(-0.005, 0.005))] + marks[order[2]] = [bx + float(rng.uniform(-0.03, 0.03)), by + side * (BOX_W / 2 + 0.025 + MARK_HALF)] + # start row in front of the box: four slots outside the knob's lane, shuffled (3 blocks + red cube) + slots = [-0.22, -0.11, 0.11, 0.22] # 11 cm apart: room for the open fingers next to a 6 cm block + items = [BLOCKS[c] for c in COLORS] + [CUBE] + perm = rng.permutation(len(items)) + start = {items[i]: [float(-0.31 + rng.uniform(-0.01, 0.01)), float(slots[j] + rng.uniform(-0.01, 0.01))] + for j, i in enumerate(perm)} + rng.random() # (draw kept so the other parameters stay the same) + # balanced blocks like l7_key_turn: exactly round(20 * P_FAR) of every 20 consecutive seeds open far + far = bool((int(seed) * 7) % 20 < round(20 * P_FAR)) + stop = float(rng.uniform(*(FAR if far else NEAR))) + return dict(seed=int(seed), box_xy=[bx, by], stop_deg=stop, lid_far=far, marks=marks, + behind=order[:2], side_color=order[2], side="left" if side > 0 else "right", gaps=gaps, start=start, + start_yaw={k: float(rng.uniform(-0.3, 0.3)) for k in items}) + + def apply_instance(self, inst): + self.inst = inst + m, d = self.env.sim.model, self.env.sim.data + bx, by = inst["box_xy"] + m.body_pos[self.box_bid] = [bx, by, envs.TABLE_Z] + m.body_quat[self.box_bid] = [1.0, 0.0, 0.0, 0.0] + m.jnt_range[self.jid] = [0.0, np.radians(inst["stop_deg"])] + m.jnt_solref[self.jid] = [0.01, 1.0] + d.qpos[self.qa] = 0.0 + d.qvel[self.dof] = 0.0 + for c in COLORS: + x, y = inst["marks"][c] + m.body_pos[self.mark_bid[c]] = [x, y, envs.TABLE_Z + 0.0002] + m.body_quat[self.mark_bid[c]] = [1.0, 0.0, 0.0, 0.0] + for name, xy in inst["start"].items(): + envs.place_upright(self.env, name, xy, yaw=inst["start_yaw"][name]) + for c in COLORS: + envs.set_friction(self.env, BLOCKS[c], BLOCK_MU) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.mon = None + self.sk = LidSkills(self.env, self, recorder=recorder) + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ state helpers + def lid_q(self): + return float(self.env.sim.data.qpos[self.qa]) + + def lid_deg(self): + return float(np.degrees(self.lid_q())) + + def knob_xyz(self): + return self.env.sim.data.geom_xpos[self.knob_gid].copy() + + def hinge_xz(self): + return self.inst["box_xy"][0] + BOX_D / 2, envs.TABLE_Z + WALL_H + + def held(self, name): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name])) + + def _flat(self, name): + R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3) + return bool(np.max(np.abs(R[2])) >= FLAT_COS) + + def block_offset(self, c): + p = envs.obj_pos(self.env, BLOCKS[c]) + return p[:2] - np.asarray(self.inst["marks"][c]) + + def on_mark(self, c, tol=TOL): + name = BLOCKS[c] + p = envs.obj_pos(self.env, name) + off = p[:2] - np.asarray(self.inst["marks"][c]) + return bool(np.max(np.abs(off)) <= tol and p[2] < envs.TABLE_Z + BLOCK / 2 + 0.01 and self._flat(name) + and not self.held(name)) + + def cube_in_box(self): + p = envs.obj_pos(self.env, CUBE) + rel = p[:2] - np.asarray(self.inst["box_xy"]) + return bool(abs(rel[0]) <= IN_X - CUBE_MARGIN and abs(rel[1]) <= IN_Y - CUBE_MARGIN + and p[2] < envs.TABLE_Z + WALL_H and not self.held(CUBE)) + + def lid_closed(self): + return self.lid_q() <= LID_CLOSED + + def stage_values(self): + v = {f"{c}_on_mark": self.on_mark(c) for c in COLORS} + v["cube_in_box"] = self.cube_in_box() + v["lid_closed"] = self.lid_closed() + return v + + # ------------------------------------------------------------ per-step monitor + def _init_monitor(self): + self.mon = dict(state={f"{c}_on_mark": False for c in COLORS} | {"cube_in_box": False}, ever=set(), + lost=set(), events=[], last_touch={c: None for c in COLORS}, lid_hits=set(), + lid_open_max=0.0, lid_opened=False, lid_open_steps=[], lid_close_steps=[], step=0, + lid_prev=0.0, lid_moving_step=-10 ** 9) + + def _touches(self): + """Per block: was it touched by the lid / the robot in this control step?""" + d = self.env.sim.data + out = {} + for i in range(d.ncon): + c = d.contact[i] + for cc in COLORS: + g = self.block_gids[cc] + other = c.geom2 if c.geom1 in g else (c.geom1 if c.geom2 in g else None) + if other is None: + continue + if other in self.lid_gids: + out[cc] = "lid" + elif other in self.robot_gids and out.get(cc) != "lid": + out[cc] = "robot" + return out + + def monitor_step(self): + mon = self.mon + if mon is None: + return + mon["step"] += 1 + step = self.sk.n_steps if self.sk is not None else mon["step"] + for c, who in self._touches().items(): + mon["last_touch"][c] = (who, step) + if who == "lid": + mon["lid_hits"].add(c) + q = self.lid_deg() + if q > 95.0 and abs(q - mon["lid_prev"]) > 0.5: + mon["lid_moving_step"] = step # the open lid is swinging (its contacts can last less than a control step) + mon["lid_prev"] = q + mon["lid_open_max"] = max(mon["lid_open_max"], q) + if not mon["lid_opened"] and q > 90.0: + mon["lid_opened"] = True + mon["lid_open_steps"].append(step) + mon["events"].append(dict(step=step, pred="lid", ev="opened_past_vertical")) + elif mon["lid_opened"] and q <= np.degrees(LID_CLOSED): + mon["lid_opened"] = False + mon["lid_close_steps"].append(step) + mon["events"].append(dict(step=step, pred="lid", ev="closed")) + if mon["step"] % 2: + return # predicates every other control step (0.1 s) + for c in COLORS: + key = f"{c}_on_mark" + was = mon["state"][key] + now = self.on_mark(c, TOL if not was else TOL + 0.005) # hysteresis against jitter at the border + if now != was: + self._event(key, now, step, c) + was = mon["state"]["cube_in_box"] + now = self.cube_in_box() + if now != was: + self._event("cube_in_box", now, step, None) + + def _event(self, key, now, step, color): + mon = self.mon + mon["state"][key] = now + if now: + ev = "restored" if key in mon["lost"] else "achieved" + mon["ever"].add(key) + if key in mon["lost"]: + mon["lost"].discard(key) + mon["events"].append(dict(step=step, pred=key, ev=ev)) + else: + cause = "other" + if color is not None: + if self.held(BLOCKS[color]): + cause = "picked_up" + else: + lt = mon["last_touch"][color] + if lt is not None and step - lt[1] <= 60: + cause = lt[0] + if cause == "other" and step - mon["lid_moving_step"] <= 20 and color in self.inst["behind"]: + cause = "lid" # lost while the open lid was swinging down onto the blocks behind the box + elif self.held(CUBE): + cause = "picked_up" + mon["lost"].add(key) + ev = dict(step=step, pred=key, ev="lost", cause=cause, lid_deg=round(self.lid_deg(), 1)) + if color is not None: + ev["offset_cm"] = (100 * self.block_offset(color)).round(1).tolist() + mon["events"].append(ev) + + # ------------------------------------------------------------ outcome + def _static(self): + d = self.env.sim.data + for name in [BLOCKS[c] for c in COLORS] + [CUBE]: + _, da = envs.free_joint_addr(self.env, name) + if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5: + return False + return abs(float(d.qvel[self.dof])) < 0.2 + + def outcome(self, inst): + envs.settle(self.env, 30) + mon = self.mon + vals = self.stage_values() + static = self._static() + held = [n for n in [BLOCKS[c] for c in COLORS] + [CUBE] if self.held(n)] + success = bool(all(vals.values()) and static and not held) + regress = [e for e in mon["events"] if e["ev"] == "lost"] + restored = [e for e in mon["events"] if e["ev"] == "restored"] + lid_knocks = [e for e in regress if e.get("cause") == "lid"] + parts = [] + if success: + failure = None + parts.append("All three blocks are on their marks, the red cube is in the box and the lid is closed.") + else: + off = [c for c in COLORS if not vals[f"{c}_on_mark"]] + failure = ("block_off_mark" if off else "cube_not_in_box" if not vals["cube_in_box"] else + "lid_open" if not vals["lid_closed"] else "held" if held else "not_static") + for c in off: + o = self.block_offset(c) + name = BLOCKS[c] + if self.held(name): + parts.append(f"The {c} block is still held by the gripper.") + continue + txt = (f"The {c} block is not on the {c} mark: its centre is {_fb(o[0])} and {_lr(o[1])} of the mark's " + f"centre") + if not self._flat(name): + txt += " and it is tipped over" + why = [e for e in regress if e["pred"] == f"{c}_on_mark"] + if f"{c}_on_mark" not in mon["ever"]: + txt += " (it was never on its mark)." + elif why and why[-1].get("cause") == "lid": + txt += (f" (it had been on its mark; the lid pushed it off when it fell open to " + f"{why[-1]['lid_deg']:.0f} degrees).") + elif why and why[-1].get("cause") == "robot": + txt += " (it had been on its mark; the robot knocked it off)." + else: + txt += " (it had been on its mark earlier)." + parts.append(txt) + if not vals["cube_in_box"]: + if self.held(CUBE): + parts.append("The red cube is still held by the gripper.") + else: + p = envs.obj_pos(self.env, CUBE) + rel = p[:2] - np.asarray(inst["box_xy"]) + parts.append(f"The red cube is not in the box: its centre is {_fb(rel[0])} and {_lr(rel[1])} of the " + f"box's centre.") + if not vals["lid_closed"]: + parts.append(f"The lid is not closed (open {self.lid_deg():.0f} degrees).") + if not static and all(vals.values()): + parts.append("Something was still moving at the end.") + if mon["lid_open_max"] < 90.0: + parts.append("The lid was never opened past upright.") + out = dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, + events=mon["events"], n_regressions=len(regress), n_restored=len(restored), + n_lid_knocks=len(lid_knocks), lid_hits=sorted(mon["lid_hits"]), + lid_open_max=round(mon["lid_open_max"], 1), lid_final_deg=round(self.lid_deg(), 1), + knob_grasps=self.sk.knob_grasps, knob_steps=self.sk.knob_steps, + block_offsets_cm={c: (100 * self.block_offset(c)).round(1).tolist() for c in COLORS}, + detail=" ".join(parts)) + return out + + # ------------------------------------------------------------ scripted policies (perfect perception) + def _grasp_yaw(self, name): + R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3) + i = int(np.argmin(np.abs(R[2]))) # the most horizontal body axis (works whichever face the cube rests on) + yaw = float(np.arctan2(R[1, i], R[0, i])) + return float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4) # a cube: grasp yaw mod 90 deg + + def pick_place(self, name, dest_xy, z_rel, z_carry=Z_CARRY, noise=None, dest_yaw=0.0): + """Top-down pick of `name` at its centre, carry at `z_carry` (grasp point above the table), release with the + grasp point `z_rel` above the table at `dest_xy`, lift.""" + sk = self.sk + Z = envs.TABLE_Z + p = envs.obj_pos(self.env, name) + yaw = self._grasp_yaw(name) + zg = p[2] - Z + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], Z + max(z_carry, zg + 0.06)], yaw=yaw) + sk.move_to([p[0], p[1], Z + zg], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([p[0], p[1], Z + z_carry], speed=0.3) + if not self.held(name): + sk.set_gripper(False, steps=8) + return False + d = np.asarray(dest_xy, float) + (np.asarray(noise, float) if noise is not None else 0.0) + sk.move_to([d[0], d[1], Z + z_carry], yaw=dest_yaw) + sk.move_to([d[0], d[1], Z + z_rel], tol=0.003) + sk.set_gripper(False, steps=12) + sk.move_to([d[0], d[1], Z + z_carry]) + return True + + def place_block(self, c, noise=None): + return self.pick_place(BLOCKS[c], self.inst["marks"][c], BLOCK / 2 + 0.004, noise=noise) + + def put_cube(self, noise=None): + bx, by = self.inst["box_xy"] + return self.pick_place(CUBE, [bx, by], FLOOR_T + CUBE_E / 2 + 0.008, z_carry=0.12, noise=noise) + + def _grasp_knob(self): + sk = self.sk + k = self.knob_xyz() + sk.set_gripper(False, steps=8) + sk.move_to([k[0], k[1], k[2] + 0.08], yaw=0.0) + sk.move_to([k[0], k[1], k[2]], tol=0.003) + sk.set_gripper(True, steps=15) + return k + + def open_lid(self, back=0.03, up=0.16): + """grasp the knob; straight up 10 cm; straight to `back` m behind the hinge, `up` m above it; release; lift""" + sk = self.sk + k = self._grasp_knob() + hx, hz = self.hinge_xz() + sk.move_to([k[0], k[1], k[2] + 0.10]) + sk.move_to([hx + back, k[1], hz + up]) + sk.set_gripper(False, steps=10) + e = sk.eef_pos() + sk.move_to([e[0] - 0.03, e[1], e[2] + 0.06]) + sk.hold(20) + + def close_lid(self): + """grasp the knob where it is; straight up 10 cm; straight forward to 8 cm in front of the hinge; release""" + sk = self.sk + k = self._grasp_knob() + hx, hz = self.hinge_xz() + sk.move_to([k[0], k[1], k[2] + 0.10]) + sk.move_to([hx - 0.08, k[1], k[2] + 0.10]) + sk.set_gripper(False, steps=10) + e = sk.eef_pos() + sk.move_to([e[0], e[1], e[2] + 0.06]) + sk.hold(20) + + def restore(self, rounds=2): + """look at every stage and fix what is wrong (lid open -> close it; cube out -> put it in; block off -> put it + back), up to `rounds` passes""" + for _ in range(rounds): + v = self.stage_values() + if all(v.values()): + return True + if not v["cube_in_box"]: + if self.lid_q() < np.radians(95): + self.open_lid() + self.put_cube() + self.close_lid() + elif not v["lid_closed"]: + self.close_lid() + for c in COLORS: + if not self.on_mark(c): + self.place_block(c) + return all(self.stage_values().values()) + + def execute(self, inst, params): + order = params.get("order") or list(COLORS) + noise = params.get("noise") or {} + if params["plan"] == "blocks_first": + for c in order: + self.place_block(c, noise.get(c)) + self.open_lid(**params.get("open", {})) + self.put_cube(noise.get("cube")) + self.close_lid() + else: # "lid_first": open, cube in, close, then the blocks + self.open_lid(**params.get("open", {})) + self.put_cube(noise.get("cube")) + self.close_lid() + for c in order: + self.place_block(c, noise.get(c)) + if params.get("check"): + self.restore() + self.sk.hold(10) + + def default_params(self, inst): + return dict(plan="blocks_first", check=False) + + def oracle_params(self, inst): + return dict(plan="lid_first", check=True) + + def adapt_params(self, inst, history): + """Used from attempt 2 on, i.e. after a failed attempt (attempt 1 is the natural order plus a final check and + repair, see run_scripted): open the box, put the cube in and close it first, then place the blocks, check.""" + return dict(plan="lid_first", check=True) + + def blind_params(self, inst, attempt, rng): + """the natural order again with small random variations (block order, placement, release point), no check""" + return dict(plan="blocks_first", check=False, order=[str(c) for c in rng.permutation(COLORS)], + noise={c: rng.normal(0.0, 0.004, 2).tolist() for c in COLORS}, + open=dict(back=float(rng.uniform(0.0, 0.05)), up=float(rng.uniform(0.14, 0.18)))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = dict(plan="blocks_first", check=True) if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": # extra control (not in validate's table): cross-attempt learning only, no re-check + params = self.default_params(inst) if a == 0 else dict(plan="lid_first", check=False) + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_nudge_row.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_nudge_row.py new file mode 100644 index 0000000000000000000000000000000000000000..e681fb7e676fcda50cc393a648311f31083de9f9 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_nudge_row.py @@ -0,0 +1,821 @@ +"""LH lh_nudge_row v2 (2026-10-14): stand four small cups, one by one, on the four coloured mats of their colours; the +mats lie in two rows of two, and in 7 of 10 instances the two mats of a row touch. Letting go of a cup with the fingers +opening towards the cup already standing on the next mat pushes that cup 1.5-3.4 cm sideways, half off its mat -- it +stays upright, so the damage is small but visible (a near miss that has to be noticed and undone before finishing). + +Family: long-horizon self-disturbance ("state_restoration"): every placement is a later stage that can physically undo an +earlier one; the agent has to look back at all cups before finishing (within an attempt) or learn to let go without +pushing (across attempts). + +v1 -> v2 (Sonnet 5.5 pilot np_lh_nudge_row, seeds 3000-3002, k=3, measured): v1 used round rings with a 0.8 cm +tolerance. Sonnet put the cups 0.8-2.2 cm too far forward (+x, away from the robot) in almost every attempt and could not +see it (the oblique agentview camera looks along x; a tall cup hides the ring behind it), so 5 of 7 attempts failed +without any nudge (one was a calibration attempt), and the one clear nudge (s3000) left the cup 0.83 cm off -- +invisible. Its left-right errors were <= 0.7 cm, its releases in attempt 1 almost all at wrist yaw ~0 (fingers opening +left-right), and it learned yaw 45 for the last cup after the nudge. v2 therefore (1) replaces the rings by mats 9 cm long (forward-back, tolerance 3 cm: a 2 cm forward bias +passes) and 4.6 cm wide (left-right, tolerance 1.3 cm), (2) puts the two mats of a row edge to edge so that a yaw-0 +release pushes the neighbour sideways, where the camera resolves it, off its mat onto the table, and (3) uses slimmer cups +(2 x 5 cm instead of 4 x 6 cm): the open finger reaches farther past them, so the push is 1.5-3.4 cm instead of 0.3-2.3. +Code and results of v1: lh_nudge_row.py.bak-20261014-v1, results/_old/lh_nudge_row_v1/. + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * four coloured mats (dark red, blue, green, ochre; flat, visual only), each 9.0 cm (forward-back) x 4.6 cm, in two rows + (far and near, 1.5 cm apart); block centre 53-59 cm in front of the robot base. Tight block (14 of every 20 + consecutive seeds): the two mats of a row touch. Spaced block (6 of 20): they are 4-5 cm apart and no open finger + reaches the neighbour (the benign instances); + * four slim cups of the bright same colours (2.0 cm wide, 5.0 cm tall, open top, glazed base: friction 0.08-0.12, + 20-32 g), standing in a line 17.5-19 cm from the block on the robot's side, or on its left or right side, in random + order and 9-10 cm apart. + +Risk factor: the block's spacing (visible, instance level); there is no hidden physical variable (v1 measured that a +rubber-footed cup gets tipped over by a re-grasp next to it, and a fallen cup cannot be stood up again). + +Disturbance (physics, no teleport): the gripper opens to 7.9 cm, i.e. each finger moves 3 cm out from a 2 cm cup; the +outer face of an open finger reaches 5.4 cm (tip) to 6.6 cm (upper part) from the grasp point; in a tight block the +neighbour's wall is 3.6 cm away (+- the placement errors). Measured: letting go with the fingers along the row (wrist yaw +0) pushes the neighbour 1.2-3.2 cm sideways, upright (18/18 trials: base friction 0.08 / 0.12 x grasp 0.8-2 cm below the +rim x put down 0.8 cm towards / on target / 0.8 cm away from it, each followed by three re-grasps); re-grasping a placed cup with the fingers towards the neighbour pushes it about 0.3 cm more. With +friction 0.18 or with 2.6 cm cups whose closed finger already presses the neighbour's rim, slim cups tipped over (4/18 +and 6/18) -- hence the low friction and the 2 cm cups. A careful agent avoids the push by letting go with the fingers +opening forward-back (wrist yaw 90: the mats of the other row are 10.5 cm away) or diagonally, and repairs it by +re-centring the pushed cup (lifted 10 cm, carried back, let go the same careful way). + +Success predicates (evaluated every other control step by a monitor, debounced over 0.5 s): each cup stands upright +(tilt <= 10 deg) on the table, not held, with its whole base on its own mat: centre within 3.0 cm (forward-back) and +1.3 cm (left-right) of the mat's centre. Success = all four at the end, gripper open and not touching any cup, scene +static. The monitor logs achieved / lost / restored per cup, cup_nudged (lost while not held, with displacement and +cause), cup_bumped (pushed by the robot but still on its mat) and cup_restored, for the server log only (F1 gives the +agent only success / failure). + +Protocol: cross (reset to the same instance before every attempt), k = 3. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +TZ = envs.TABLE_Z +COLOURS = ["red", "blue", "green", "yellow"] +CUPS = [f"cup_{c}_1" for c in COLOURS] +MATS = [f"mat_{c}_1" for c in COLOURS] +RGBA = {"red": (0.82, 0.16, 0.13, 1.0), "blue": (0.16, 0.36, 0.82, 1.0), "green": (0.16, 0.62, 0.26, 1.0), + "yellow": (0.92, 0.76, 0.12, 1.0)} +MAT_RGBA = {"red": (0.55, 0.13, 0.12, 1.0), "blue": (0.12, 0.22, 0.52, 1.0), "green": (0.10, 0.38, 0.16, 1.0), + "yellow": (0.62, 0.50, 0.08, 1.0)} # dark shades: crisp edges on the light table, bright cups stand out +INSIDE_RGBA = (0.93, 0.92, 0.88, 1.0) # glazed inside of the cups (seen from above) + +# cup geometry (fixed; only mass and base friction change per instance, so no runtime geom edits / BVH refits) +CUP_R, CUP_H = 0.010, 0.050 # slim cups (2 x 5 cm): the open fingers reach far past them (v1: 4 x 6 cm) +COM_Z = -0.006 # centre of mass below the cup's mid-height (heavier base) +WALL_T, BASE_T = 0.0025, 0.003 +NSEG = 12 +CONTACT = 'solimp="0.95 0.99 0.001" solref="0.01 1"' +WALL_MU = 0.8 +BASE_MU = (0.08, 0.12) # glazed base: a pushed cup slides; at 0.18 a slim cup pushed high up tipped (measured) +MASS = (0.020, 0.032) + +# mats (targets) and block +TOL_X = 0.030 # forward-back: the cup centre may be 3 cm from the mat centre (mat 9 cm long) -- Sonnet's measured +# placement bias is 1-2.5 cm forward (v1 pilot), invisible to it in the oblique camera +TOL_Y = 0.013 # left-right: 1.3 cm (mat 4.6 cm wide); a finger-opening push (1.2-3.2 cm, measured) fails it +MAT_L, MAT_W = 2 * (CUP_R + TOL_X), 2 * (CUP_R + TOL_Y) # base completely on the mat <=> centre within the tolerances +ROW_GAP = 0.015 # gap between the far row and the near row of mats (x) +SPACED_GAP = (0.040, 0.050) # spaced block: gap between the two mats of a row (y); an open finger cannot reach +P_TIGHT = 0.70 # 14 of every 20 consecutive seeds: the two mats of a row touch +BLOCK_X = (-0.13, -0.07) # block centre in world x (53-59 cm in front of the robot base) +SUP_D = (0.175, 0.19) # supply line distance from the block centre +SUP_GAP = (0.090, 0.100) + +# predicates / monitor +TILT_OK = np.radians(10.0) +ON_TABLE = 0.004 +HYST = 0.002 +DEBOUNCE = 10 # control steps (0.5 s) +BUMP_MIN = 0.003 + +# scripted motion (heights of the grasp point above the table) +Z_CARRY = 0.20 # Sonnet: lifts to ~20 cm before moving (lh2/lh3 pilots) +Z_LIFT = 0.15 # re-placing a cup that is already down: lift it this high (its base 11 cm up) before moving it +NAIVE_BIAS = (0.008, 0.022) # Sonnet's systematic forward placement error (v1 pilot: +0.8 ... +2.2 cm, per instance) +NAIVE_RAND = 0.006 # +- random placement error per axis (v1 pilot: left-right errors <= 0.7 cm) +NAIVE_FIX_RAND = 0.003 # after re-placing its own cup +FINGER_IN, FINGER_OUT, FINGER_HALF = 0.039, 0.066, 0.013 # open finger footprint (m from the grasp point / half width) + + +def _wrap_h(a): + """wrap to [-pi/2, pi/2) (the gripper is symmetric under 180 deg)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def cup_xml(name, rgba): + """open-top cup: 12 wall boxes (1 mm above the bottom) and an octagonal base of two square boxes (box-box contacts: + a light cylinder on the table creeps by itself in MuJoCo, measured 1.6 cm / 5 s). Visual: a smooth cylinder with the + glazed inside at the top. The compiled inertial is replaced per instance (mass), the base friction too.""" + r, h = CUP_R, CUP_H + g = [f' '] + s = r * np.sin(np.pi / NSEG) + 0.0006 + rc = r * np.cos(np.pi / NSEG) - WALL_T / 2 + for k in range(NSEG): + a = 2 * np.pi * k / NSEG + q = [np.cos(a / 2), 0, 0, np.sin(a / 2)] + g.append(f' ') + a0 = r * 0.70 + for k, ang in enumerate((0.0, np.pi / 4)): + q = [np.cos(ang / 2), 0, 0, np.sin(ang / 2)] + g.append(f' ') + g.append(f' ') + g.append(f' ') + return _wrap(name, "\n".join(g), h / 2, r) + + +def mat_xml(name, rgba): + """flat coloured mat (visual only), long side along body x""" + g = (f' ') + return _wrap(name, g, 0.0004, float(np.hypot(MAT_L, MAT_W) / 2)) + + +def _fb(d): + return f"{100 * abs(d):.1f} cm {'forward' if d > 0 else 'back'}" + + +def _lr(d): + return f"{100 * abs(d):.1f} cm to the {'left' if d > 0 else 'right'}" + + +class NudgeSkills(Skills): + """Skills that feed the task's per-step monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class NudgeRow(LFFTask): + name = "lh_nudge_row" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Plan", "Reason", "Restore") + protocol = "cross" + max_attempts = 3 + # careful: ~10 commands per cup (40) + re-placing an imprecise cup or two (~15) + re-centring two pushed cups (~20) + # + looking / small corrections (~20), with some margin + agent_max_steps = 110 + instruction = ("Stand each of the four small cups on the mat of the same colour. The four coloured mats lie on the " + "table in two rows of two. At the end every cup must stand upright with its whole base on its own " + "mat (not touching another mat or the table around it), and the gripper must be open and clear of " + "the cups.") + instruction_indirect = ("Set each little cup down on the coloured patch that matches it; the four patches form two " + "rows of two. When you are done every cup has to stand upright with its bottom completely " + "on its own patch, and the gripper must be open and away from the cups.") + agent_object_names = ["small cups (red, blue, green, yellow)", + "coloured mats (red, blue, green, yellow) in two rows of two"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs, fx = [], [] + for i, (c, cup) in enumerate(zip(COLOURS, CUPS)): + cat = register_generated(f"LffLhnCup{c.capitalize()}", cup_xml(f"lff_lhn_cup_{c}", RGBA[c])) + objs.append((cup, cat, f"cup{i}_region", (-0.30 + 0.12 * i, 0.30, -0.29 + 0.12 * i, 0.31))) + for i, (c, mat) in enumerate(zip(COLOURS, MATS)): + cat = register_generated(f"LffLhnMat{c.capitalize()}", mat_xml(f"lff_lhn_mat_{c}", MAT_RGBA[c]), free=False) + fx.append((mat, cat, f"mat{i}_region", (-0.30 + 0.12 * i, -0.31, -0.29 + 0.12 * i, -0.30))) + return write_bddl(self.name, "Stand each cup on the mat of its colour", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.mat_bid = {k: m.body_name2id(self.env.fixtures_dict[k].root_body) for k in MATS} + self.cgeoms = {c: envs.obj_geom_ids(self.env, c) for c in CUPS} + self.cbody = {c: int(m.geom_bodyid[self.cgeoms[c][0]]) for c in CUPS} + self.base_geoms = {c: [g for g in self.cgeoms[c] if (m.geom_id2name(g) or "").split("_")[-1] in ("b0", "b1")] + for c in CUPS} + self.finger_geoms, self.hand_geoms = [], [] + for g in envs.robot_geom_ids(self.env): + n = m.geom_id2name(g) or "" + (self.finger_geoms if "finger" in n else self.hand_geoms).append(g) + # per-geom lookup tables for the substep contact check: cup index (-1 none), robot part (1 finger, 2 hand) + self.owner = np.full(m.ngeom, -1, int) + for i, c in enumerate(CUPS): + self.owner[self.cgeoms[c]] = i + self.part = np.zeros(m.ngeom, int) + self.part[self.finger_geoms] = 1 + self.part[self.hand_geoms] = 2 + self._sub_rob, self._sub_obj = {}, {} + # contacts are collected after every MuJoCo substep: an opening finger can flick a light cup within one control + # step (same technique as lh_fence; wrappers chain) + sim = self.env.sim + if not getattr(sim, "_lhn_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lhn_task", None) + if t is not None and t.mon is not None: + t._substep() + sim.step = step + sim._lhn_wrapped = True + sim._lhn_task = self + self.inst = None + self.mon = None + self.sk = None + + def _substep(self): + d = self.env.sim.data + n = d.ncon + if not n: + return + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + o1, o2 = self.owner[g1], self.owner[g2] + for a, b, pa, pb in zip(g1, g2, o1, o2): + if pa < 0 and pb < 0: + continue + if pa >= 0 and pb >= 0: + if pa != pb: + self._sub_obj[int(pa)] = int(pb) + self._sub_obj[int(pb)] = int(pa) + continue + p, o = (pa, b) if pa >= 0 else (pb, a) + part = self.part[o] + if part: + prev = self._sub_rob.get(int(p), 0) + self._sub_rob[int(p)] = 1 if (part == 1 or prev == 1) else 2 + + # ------------------------------------------------------------ instances + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + tight = bool((int(seed) * 7) % 20 < round(20 * P_TIGHT)) # balanced: 14 of every 20 consecutive seeds + gap_y = 0.0 if tight else float(rng.uniform(*SPACED_GAP)) + py = MAT_W + gap_y # mat centre to mat centre within a row (left-right) + px = MAT_L + ROW_GAP # far row to near row (forward-back) + bx = float(rng.uniform(*BLOCK_X)) + side = str(rng.choice(["front", "left", "right"])) + by = float(rng.uniform(-0.04, 0.04)) + if side == "left": + by = float(rng.uniform(-0.08, -0.04)) + elif side == "right": + by = float(rng.uniform(0.04, 0.08)) + # mat positions: block slots (far-left, far-right, near-left, near-right), colours permuted + slots = {"far_left": [bx + px / 2, by + py / 2], "far_right": [bx + px / 2, by - py / 2], + "near_left": [bx - px / 2, by + py / 2], "near_right": [bx - px / 2, by - py / 2]} + names = list(slots) + perm = rng.permutation(4) + mats = {COLOURS[i]: slots[names[perm[i]]] for i in range(4)} + slot_of = {COLOURS[i]: names[perm[i]] for i in range(4)} + # supply line + d = float(rng.uniform(*SUP_D)) + gap = float(rng.uniform(*SUP_GAP)) + offs = (np.arange(4) - 1.5) * gap + float(rng.uniform(-0.02, 0.02)) + if side == "front": + sup = [[bx - d + float(rng.uniform(-0.008, 0.008)), by + o] for o in offs] + else: + sgn = 1.0 if side == "left" else -1.0 + sup = [[bx + o, by + sgn * (d - 0.02) + float(rng.uniform(-0.008, 0.008))] for o in offs] + order = rng.permutation(4) + start = {COLOURS[i]: [float(v) for v in sup[order[i]]] for i in range(4)} + mu = {c: float(rng.uniform(*BASE_MU)) for c in COLOURS} + mass = {c: float(rng.uniform(*MASS)) for c in COLOURS} + yaw0 = {c: float(rng.uniform(-np.pi, np.pi)) for c in COLOURS} + return dict(seed=int(seed), pitch_y=py, pitch_x=px, gap_y=gap_y, block=[bx, by], supply_side=side, + supply_d=d, supply_gap=gap, mats=mats, slot_of=slot_of, start=start, mu=mu, mass=mass, yaw0=yaw0, + tight=tight, block_kind="tight" if tight else "spaced", + naive_bias_x=float(rng.uniform(*NAIVE_BIAS))) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + for c, cup in zip(COLOURS, CUPS): + b = self.cbody[cup] + M = inst["mass"][c] + m.body_mass[b] = M + # thin-walled cup (wall + base), approximately + m.body_inertia[b] = [M * (CUP_R ** 2 / 2 + CUP_H ** 2 / 12), M * (CUP_R ** 2 / 2 + CUP_H ** 2 / 12), + M * CUP_R ** 2 * 0.8] + for g in self.base_geoms[cup]: + m.geom_friction[g] = [inst["mu"][c], 0.005, 0.0001] + m.geom_priority[g] = 2 + for c, mat in zip(COLOURS, MATS): + x, y = inst["mats"][c] + m.body_pos[self.mat_bid[mat]] = [x, y, TZ + 0.0005] + m.body_quat[self.mat_bid[mat]] = [1.0, 0.0, 0.0, 0.0] + self.env.sim.forward() + for c, cup in zip(COLOURS, CUPS): + envs.place_upright(self.env, cup, inst["start"][c], yaw=inst["yaw0"][c], clearance=0.0005) + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = NudgeSkills(self.env, self, recorder=recorder) + self._sub_rob, self._sub_obj = {}, {} + n = len(CUPS) + self.mon = dict(state=[False] * n, raw_since=[0] * n, ever=[False] * n, lost=[False] * n, events=[], + lost_cause=[None] * n, + anchor=[None] * n, last_robot=[None] * n, last_obj=[None] * n, nudged=[False] * n, + bump_ref=[None] * n, bump_step=[-1000] * n, n_steps=0) + return self.sk + + # ------------------------------------------------------------ geometry / predicates + def pos(self, cup): + return envs.obj_pos(self.env, cup) + + def tilt(self, cup): + return float(np.arccos(np.clip(envs.obj_upright_cos(self.env, cup), -1.0, 1.0))) + + def held(self, cup): + return self.sk is not None and self.sk.holding(cup) + + def mat_xy(self, i): + return np.asarray(self.inst["mats"][COLOURS[i]], float) + + def offset(self, i): + return self.pos(CUPS[i])[:2] - self.mat_xy(i) + + @staticmethod + def within(off, extra=0.0): + """mat-frame offset (x forward-back, y left-right) inside the tolerances = the cup's whole base on its mat""" + return abs(float(off[0])) <= TOL_X + extra and abs(float(off[1])) <= TOL_Y + extra + + def on_mat(self, i, extra=0.0): + cup = CUPS[i] + if self.tilt(cup) > TILT_OK + (np.radians(2.0) if extra else 0.0): + return False + if not self.within(self.offset(i), extra): + return False + if envs.obj_min_z(self.env, cup) > TZ + ON_TABLE: + return False + return not self.held(cup) + + def stages(self): + return [self.on_mat(i) for i in range(len(CUPS))] + + # ------------------------------------------------------------ monitor + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + mon["n_steps"] += 1 + t = self.sk.n_steps + rob = dict(self._sub_rob) + obj = dict(self._sub_obj) + self._sub_rob, self._sub_obj = {}, {} + gstate = "open" if self.sk.grip < 0 else "closed" + for i, part in rob.items(): + if not self.held(CUPS[i]): + mon["last_robot"][i] = ["finger" if part == 1 else "hand", int(t), gstate] + for i, j in obj.items(): + mon["last_obj"][i] = [COLOURS[j] + (" (held)" if self.held(CUPS[j]) else ""), int(t)] + if mon["n_steps"] % 2: + return + for i in range(len(CUPS)): + cup = CUPS[i] + raw = self.on_mat(i, HYST if mon["state"][i] else 0.0) + # bumps inside the tolerance + if mon["state"][i] and raw and not self.held(cup): + lr = mon["last_robot"][i] + if lr is not None and t - lr[1] <= 2 and mon["bump_ref"][i] is None: + mon["bump_ref"][i] = [self.pos(cup)[:2].tolist(), int(t), 0.0] + ref = mon["bump_ref"][i] + if ref is not None: + ref[2] = max(ref[2], float(np.degrees(self.tilt(cup)))) + if t - ref[1] > 40: + dpos = float(np.linalg.norm(self.pos(cup)[:2] - np.asarray(mon["anchor"][i] or ref[0]))) + if (dpos >= BUMP_MIN or ref[2] >= 2.0) and t - mon["bump_step"][i] > 60: + mon["events"].append(dict(cup=COLOURS[i], event="cup_bumped", step=int(ref[1]), + moved_cm=round(100 * dpos, 2), max_tilt_deg=round(ref[2], 1), + cause=self._cause(i, ref[1] + 1))) + mon["bump_step"][i] = int(t) + mon["bump_ref"][i] = None + if raw == mon["state"][i]: + mon["raw_since"][i] = 0 + continue + mon["raw_since"][i] += 2 + if mon["raw_since"][i] < DEBOUNCE: + continue + mon["state"][i] = raw + mon["raw_since"][i] = 0 + t0 = int(t - DEBOUNCE + 1) + if raw: + restored = mon["lost"][i] + e = dict(stage=COLOURS[i], event="restored" if restored else "achieved", step=t0) + if restored: + e["after"] = mon["lost_cause"][i] # picked_up = the agent re-adjusted a cup it had placed itself + mon["events"].append(e) + if restored and mon["nudged"][i]: + mon["events"].append(dict(cup=COLOURS[i], event="cup_restored", step=t0)) + mon["nudged"][i] = False + mon["ever"][i] = True + mon["anchor"][i] = self.pos(cup)[:2].tolist() + mon["bump_ref"][i] = None + else: + mon["lost"][i] = True + cause = self._cause(i, t) + mon["lost_cause"][i] = cause + mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t0, cause=cause)) + if cause != "picked_up": + a = mon["anchor"][i] + d = self.pos(cup)[:2] - np.asarray(a if a is not None else self.mat_xy(i)) + off = self.offset(i) + mon["events"].append(dict(cup=COLOURS[i], event="cup_nudged", step=t0, cause=cause, + moved_cm=[round(100 * float(d[0]), 2), round(100 * float(d[1]), 2)], + offset_cm=round(100 * float(np.linalg.norm(off)), 2), + tilt_deg=round(float(np.degrees(self.tilt(cup))), 1))) + mon["nudged"][i] = True + + def _cause(self, i, t, window=60): + if self.held(CUPS[i]): + return "picked_up" + lr, lo = self.mon["last_robot"][i], self.mon["last_obj"][i] + cands = [] + if lr is not None and t - lr[1] <= window: + cands.append((lr[1], f"robot_{lr[0]}" + ("_opening" if lr[2] == "open" else ""))) + if lo is not None and t - lo[1] <= window: + cands.append((lo[1] - 30, "cup:" + lo[0])) # prefer the robot when both touched it recently + return max(cands)[1] if cands else "other" + + def _finalize_monitor(self, raw): + """close the event log at finish: a stage the debounced monitor still holds (it uses a 2 mm hysteresis) but the + final judge does not is logged as lost now (final=True), and vice versa""" + mon = self.mon + if mon is None: + return + t = int(self.sk.n_steps) + for i in range(len(CUPS)): + if raw[i] == mon["state"][i]: + continue + mon["state"][i] = raw[i] + if raw[i]: + restored = mon["lost"][i] + e = dict(stage=COLOURS[i], event="restored" if restored else "achieved", step=t, final=True) + if restored: + e["after"] = mon["lost_cause"][i] + mon["events"].append(e) + mon["ever"][i] = True + continue + mon["lost"][i] = True + cause = self._cause(i, t, window=10 ** 6) # the last contact may be long ago (slow creep across the line) + mon["lost_cause"][i] = cause + mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t, cause=cause, final=True)) + if cause != "picked_up": + a = mon["anchor"][i] + d = self.pos(CUPS[i])[:2] - np.asarray(a if a is not None else self.mat_xy(i)) + mon["events"].append(dict(cup=COLOURS[i], event="cup_nudged", step=t, cause=cause, final=True, + moved_cm=[round(100 * float(d[0]), 2), round(100 * float(d[1]), 2)], + offset_cm=round(100 * float(np.linalg.norm(self.offset(i))), 2), + tilt_deg=round(float(np.degrees(self.tilt(CUPS[i]))), 1))) + mon["nudged"][i] = True + + # ------------------------------------------------------------ outcome + def _touching(self): + d = self.env.sim.data + rob = set(self.finger_geoms) | set(self.hand_geoms) + for j in range(d.ncon): + c = d.contact[j] + if (self.owner[c.geom1] >= 0 and c.geom2 in rob) or (self.owner[c.geom2] >= 0 and c.geom1 in rob): + return True + return False + + def outcome(self, inst): + sk = self.sk + sk.hold(10) + p0 = {c: self.pos(c) for c in CUPS} + touching = False + for _ in range(20): + sk.hold(1) + touching = touching or self._touching() + moved = max(float(np.linalg.norm(self.pos(c) - p0[c])) for c in CUPS) + static = moved < 0.003 + raw = self.stages() + self._finalize_monitor(raw) + held = [COLOURS[i] for i, c in enumerate(CUPS) if self.held(c)] + mon = self.mon + ev = list(mon["events"]) if mon else [] + n_reg = sum(e.get("event") == "lost" and e.get("cause") != "picked_up" for e in ev) + n_lost = sum(e.get("event") == "lost" for e in ev) + n_res = sum(e.get("event") == "restored" and e.get("after") != "picked_up" for e in ev) + nudges = [e for e in ev if e.get("event") == "cup_nudged"] + bumps = [e for e in ev if e.get("event") == "cup_bumped"] + success = bool(all(raw) and static and not held and not touching) + ever = mon["ever"] if mon else [False] * len(CUPS) + tilted = [i for i in range(len(CUPS)) if self.tilt(CUPS[i]) > TILT_OK] + lost_final = [i for i in range(len(CUPS)) if not raw[i] and ever[i]] + never = [i for i in range(len(CUPS)) if not raw[i] and not ever[i]] + if success: + failure = "none" + elif held: + failure = "held" + elif touching: + failure = "touching" + elif tilted: + failure = "tipped" + elif lost_final: + failure = "nudged_out" if any(mon["nudged"][i] for i in lost_final) else "regressed" + elif never: + failure = "not_on_mat" + else: + failure = "not_static" + parts = [] + if success: + parts.append("Every cup stands upright on the mat of its colour.") + for i in range(len(CUPS)): + if raw[i]: + continue + c, cup = COLOURS[i], CUPS[i] + if c in held: + parts.append(f"The {c} cup is still held by the gripper.") + continue + off = self.offset(i) + tl = np.degrees(self.tilt(cup)) + where = f"{_fb(off[0])} and {_lr(off[1])} of the {c} mat's centre" + if tl > np.degrees(TILT_OK): + txt = (f"The {c} cup has fallen over" if tl > 45 else f"The {c} cup leans {tl:.0f} degrees") + f", {where}." + elif float(np.linalg.norm(off)) > 0.08: + txt = f"The {c} cup is not on the {c} mat (its centre is {100 * float(np.linalg.norm(off)):.0f} cm away)." + else: + over = [] + if abs(off[1]) > TOL_Y: + over.append(f"{100 * (abs(off[1]) - TOL_Y):.1f} cm over the mat's {'left' if off[1] > 0 else 'right'} " + f"edge") + if abs(off[0]) > TOL_X: + over.append(f"{100 * (abs(off[0]) - TOL_X):.1f} cm over its {'far' if off[0] > 0 else 'near'} end") + txt = f"The {c} cup stands {where}; its base sticks out " + " and ".join(over) + "." + if ever[i]: + lost = [e for e in ev if e.get("stage") == c and e.get("event") == "lost"] + why = lost[-1].get("cause", "other") if lost else "other" + txt += {"robot_finger_opening": " It had stood on its mat; a finger pushed it when the gripper opened " + "next to it.", + "robot_finger": " It had stood on its mat; a finger pushed it.", + "robot_hand": " It had stood on its mat; the hand pushed it.", + }.get(why, " It had stood on its mat earlier and was pushed by another cup." + if why.startswith("cup:") else " It had stood on its mat earlier.") + parts.append(txt) + if not success and all(raw): + if touching: + parts.append("The gripper is still touching a cup.") + elif not static: + parts.append("Something was still moving.") + if nudges: + parts.append(f"During the attempt cups that stood on their mats were pushed off {len(nudges)} time(s); " + f"{n_res} time(s) a cup was put back.") + trap = bool(nudges) + return dict(success=success, stages={COLOURS[i]: bool(raw[i]) for i in range(len(CUPS))}, events=ev, + n_regressions=int(n_reg), n_lost=int(n_lost), n_restored=int(n_res), n_nudged=len(nudges), + n_bumped=len(bumps), trap_fired=trap, recovered_in_attempt=bool(trap and success), + nudged_cups=sorted({e["cup"] for e in nudges}), failure=failure, held=held, + touching=bool(touching), static=bool(static), + offsets_cm={COLOURS[i]: [round(100 * float(v), 2) for v in self.offset(i)] for i in range(4)}, + tilts_deg={COLOURS[i]: round(float(np.degrees(self.tilt(CUPS[i]))), 1) for i in range(4)}, + tight=bool(inst["tight"]), detail=" ".join(parts)) + + # ------------------------------------------------------------ scripted policies (move_to + gripper only) + def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300): + return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + + def _lift_to(self, z, speed=0.15): + cur = self.sk.eef_pos() + if cur[2] < TZ + z - 0.005: + self._go([cur[0], cur[1], TZ + z], speed=speed) + + def finger_clear(self, q, yaw, ignore=()): + """smallest distance (m) between the open fingers at grasp point q (xy) with gripper yaw `yaw` and the wall of + any standing cup other than `ignore`; finger axis (-sin yaw, cos yaw)""" + a = np.array([-np.sin(yaw), np.cos(yaw)]) + b = np.array([a[1], -a[0]]) + best = 1.0 + for cup in CUPS: + if cup in ignore or self.held(cup): + continue + rel = self.pos(cup)[:2] - np.asarray(q, float) + for s in (1.0, -1.0): + u = s * float(rel @ a) + v = float(rel @ b) + du = max(FINGER_IN - u, 0.0, u - FINGER_OUT) + dv = max(abs(v) - FINGER_HALF, 0.0) + best = min(best, float(np.hypot(du, dv)) - CUP_R) + return best + + def safe_yaw(self, q, ignore=(), prefer=0.0): + """the gripper yaw (0, 90, +-45 deg) whose open fingers stay farthest from the other cups at q""" + cands = [0.0, np.pi / 2, np.pi / 4, -np.pi / 4] + sc = [(round(min(self.finger_clear(q, y, ignore), 0.02), 3), -abs(_wrap_h(y - prefer)), y) for y in cands] + return max(sc)[2] + + def grasp_cup(self, cup, yaw, depth, z_carry=Z_CARRY, v=0.2, err=None, lift=None): + """open, go over the cup at transit height, straight down, close, lift. Returns True if held.""" + sk = self.sk + p = self.pos(cup) + q = p[:2] + (np.asarray(err, float) if err is not None else 0.0) + zg = envs.obj_max_z(self.env, cup) - depth + sk.set_gripper(False, steps=8) + self._lift_to(z_carry) + self._go([q[0], q[1], max(sk.eef_pos()[2], TZ + z_carry)], yaw=yaw, speed=v) + self._go([q[0], q[1], zg + 0.015], speed=0.10) + self._go([q[0], q[1], zg], speed=0.04, tol=0.003, max_steps=150) + sk.set_gripper(True, steps=15) + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + (z_carry if lift is None else lift)], speed=0.12) + sk.hold(5) + if not self.held(cup): + sk.set_gripper(False, steps=8) + return False + return True + + def put_cup(self, cup, xy, yaw, z_carry=Z_CARRY, v=0.2, lift=None): + """carry the held cup so that the cup (not the grasp point) is over xy, rotate to `yaw`, straight down until its + base is 3 mm above the table, let go, lift""" + sk = self.sk + rel = self.pos(cup)[:2] - sk.eef_pos()[:2] + q = np.asarray(xy, float) - rel + cur = sk.eef_pos() + self._go([q[0], q[1], max(cur[2], TZ + z_carry)], yaw=yaw, speed=v) + sk.hold(5) + rel = self.pos(cup)[:2] - sk.eef_pos()[:2] # the cup can shift in the fingers while the wrist turns + q = np.asarray(xy, float) - rel + dz = sk.eef_pos()[2] - envs.obj_min_z(self.env, cup) + zr = TZ + dz + 0.003 + self._go([q[0], q[1], zr + 0.015], speed=0.10) + self._go([q[0], q[1], zr], speed=0.03, tol=0.003, max_steps=150) + sk.set_gripper(False, steps=12) + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + (z_carry if lift is None else lift)], speed=0.15) + sk.hold(3) + + def mat_order(self, mode="far_first"): + """colour indices in placement order. far_first (Sonnet): the block row farthest from the supply first, then + the other; within a row from the left (robot's view)""" + sup = np.mean([self.inst["start"][c] for c in COLOURS], axis=0) + blk = np.asarray(self.inst["block"], float) + u = blk - sup + u = u / max(np.linalg.norm(u), 1e-9) + idx = list(range(4)) + far = sorted(idx, key=lambda i: -float((self.mat_xy(i) - blk) @ u)) + rows = [far[:2], far[2:]] + if mode == "near_first": + rows = rows[::-1] + out = [] + for row in rows: + out += sorted(row, key=lambda i: (-self.mat_xy(i)[1], self.mat_xy(i)[0])) # left first + return out + + @staticmethod + def looks_off(off, bias): + """a (biased) observer's verdict: the cup looks off its mat centre by more than 0.8 cm in some direction""" + p = np.asarray(off, float) - np.asarray(bias, float) + return abs(p[0]) > 0.008 or abs(p[1]) > 0.008 + + def place_one(self, i, yaw_rule, depth, rng, bias=(0.0, 0.0), rand=0.0, fix_rand=0.0, check=True, z_carry=Z_CARRY, + v=0.2): + """one stage: pick cup i from wherever it is and put it on its mat; aims at mat + bias (+- rand per axis); then + looks at this cup only (with the same bias) and re-places it if it looks off""" + cup = CUPS[i] + bias = np.asarray(bias, float) + for _ in range(2): + gy = yaw_rule(i, "grasp") + gerr = rng.uniform(-0.003, 0.003, 2) if rand else None + if self.grasp_cup(cup, gy, depth, z_carry=z_carry, v=v, err=gerr): + break + else: + return + e = rng.uniform(-rand, rand, 2) if rand else np.zeros(2) + self.put_cup(cup, self.mat_xy(i) + bias + e, yaw_rule(i, "release"), z_carry=z_carry, v=v) + if not check: + return + for _ in range(2): + if not self.looks_off(self.offset(i), bias) and self.tilt(cup) < TILT_OK: + return + ry = yaw_rule(i, "grasp") + if not self.grasp_cup(cup, ry, depth, z_carry=Z_LIFT, v=0.1, lift=Z_LIFT): + return + e = rng.uniform(-fix_rand, fix_rand, 2) if fix_rand else np.zeros(2) + self.put_cup(cup, self.mat_xy(i) + bias + e, yaw_rule(i, "release"), z_carry=Z_LIFT, v=0.1, lift=z_carry) + + def repair(self, rounds=4, depth=0.020, bias=(0.0, 0.0)): + """look at every cup (with the observer's bias); re-centre each one that looks off: grasp and let go with the + fingers opening where no other cup stands. Returns the number of cups moved.""" + bias = np.asarray(bias, float) + moved = 0 + tries = {} + for _ in range(rounds * 4): + bad = [i for i in range(4) if (self.looks_off(self.offset(i), bias) or self.held(CUPS[i])) + and self.tilt(CUPS[i]) < np.radians(30) and tries.get(i, 0) < rounds] + if not bad: + break + i = min(bad, key=lambda j: float(np.linalg.norm(self.pos(CUPS[j])[:2] - self.sk.eef_pos()[:2]))) + tries[i] = tries.get(i, 0) + 1 + cup = CUPS[i] + gy = self.safe_yaw(self.pos(cup)[:2], ignore=(cup,), prefer=self.sk.yaw) + # lift the cup clear of its neighbours before moving it: carried at 10 cm its base clips their rims and + # tips them (v1, measured, 4/20 adaptive runs before this was raised) + if not self.grasp_cup(cup, gy, depth, z_carry=Z_LIFT, v=0.15, lift=Z_LIFT): + continue + moved += 1 + target = self.mat_xy(i) + bias + ry = self.safe_yaw(target, ignore=(cup,), prefer=self.sk.yaw) + self.put_cup(cup, target, ry, z_carry=Z_LIFT, v=0.1, lift=Z_CARRY) + return moved + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("noise_seed", 0)) + depth = params.get("depth", 0.020) + order = self.mat_order(params.get("order", "far_first")) + mode = params["yaw"] # "fixed" (one wrist yaw for everything) or "safe" (fingers away from placed cups) + y0 = float(params.get("yaw0", 0.0)) + bias = (float(params.get("bias_x", 0.0)), 0.0) + + def yaw_rule(i, what): + if mode == "fixed": + return y0 + q = self.pos(CUPS[i])[:2] if what == "grasp" else self.mat_xy(i) + np.asarray(bias) + return self.safe_yaw(q, ignore=(CUPS[i],), prefer=y0) + + rand = float(params.get("rand", 0.0)) + for i in order: + self.place_one(i, yaw_rule, depth, rng, bias=bias, rand=rand, fix_rand=float(params.get("fix_rand", 0.0)), + check=params.get("self_check", True), z_carry=params.get("z_carry", Z_CARRY), + v=params.get("v", 0.2)) + if params.get("check"): + self.repair(bias=bias) + self._lift_to(0.20) + self.sk.hold(10) + + # naive = Sonnet 5.5's habits measured in the v1 pilot (np_lh_nudge_row): wrist yaw 0 for every grasp and release in + # attempt 1, the row farthest from the supply first, lift to 14-25 cm and carry straight, vertical descents, + # placement 0.8-2.2 cm too far forward (per instance, invisible to it) +- 0.6 cm, looks at the cup it just placed and + # re-places it if it looks off, no look back at the others before finishing + NAIVE = dict(yaw="fixed", yaw0=0.0, order="far_first", self_check=True, check=False, rand=NAIVE_RAND, + fix_rand=NAIVE_FIX_RAND) + CAREFUL = dict(yaw="safe", yaw0=0.0, order="far_first", self_check=True, check=True, rand=0.0, bias_x=0.0) + + def default_params(self, inst): + return dict(self.NAIVE, noise_seed=int(inst["seed"]) * 13, bias_x=float(inst["naive_bias_x"]), + depth=0.008 + 0.012 * ((int(inst["seed"]) * 7) % 11) / 10) # 0.8-2.0 cm below the rim (pilot: ~1 cm) + + def oracle_params(self, inst): + return dict(self.CAREFUL) + + def adapt_params(self, inst, history): + """from attempt 2: let go with the fingers opening away from the placed cups (same imprecision and bias), and + look at every cup before finishing""" + return dict(self.default_params(inst), yaw="safe", check=True) + + def blind_params(self, inst, attempt, rng): + """the naive behaviour with random variation, no history, no final look""" + return dict(self.default_params(inst), noise_seed=int(rng.integers(1 << 30)), + yaw0=float(rng.choice([0.0, np.pi / 2])), order=str(rng.choice(["far_first", "near_first"])), + z_carry=float(rng.uniform(0.15, 0.22)), v=float(rng.uniform(0.1, 0.3)), + depth=float(rng.uniform(0.008, 0.025)), bias_x=float(rng.uniform(*NAIVE_BIAS))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + single = ("oracle", "naive", "oracle_noise", "naive_yaw90", "naive_check", "careful_bias2", "naive_bias2") + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": # attempt 1: naive + a final look at every cup (repairs); then careful releases + params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": # control: cross-attempt learning only (careful releases from attempt 2), no final look + params = self.default_params(inst) if a == 0 else dict(self.default_params(inst), yaw="safe") + elif kind == "oracle_noise": # robustness: careful with +-5 mm placement / grasp noise + params = dict(self.CAREFUL, rand=0.005, noise_seed=int(seed) * 7 + a) + elif kind == "naive_yaw90": # control: Sonnet-like but the wrist turned 90 deg for everything + params = dict(self.default_params(inst), yaw0=np.pi / 2) + elif kind == "naive_check": # control: naive + final look (= adaptive's first attempt) + params = dict(self.default_params(inst), check=True) + elif kind == "careful_bias2": # control: careful releases (nothing nudged) but placed 2 cm too far forward + params = dict(self.default_params(inst), yaw="safe", bias_x=0.020) + elif kind == "naive_bias2": # control: naive with a fixed +2 cm forward bias + params = dict(self.default_params(inst), bias_x=0.020) + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in single: + break + return history diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_order_dispatch.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_order_dispatch.py new file mode 100644 index 0000000000000000000000000000000000000000..4fbca418828c2aec9e5a248d17a51db00760bef0 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_order_dispatch.py @@ -0,0 +1,242 @@ +"""Development composite: physically load two products and a card, then steer a weighted shipping tray. +L1 fixed calibration bias, L3 card edge strategy, L5 off-centre loaded push. Not in the main set. +""" +import numpy as np +import copy +import xml.etree.ElementTree as ET +from .. import envs +from ..bddl import write_bddl +from ..objects import box_xml, register_generated +from ..task_base import LFFTask, register_task +from .l3_card_edge import CardEdge, card_xml, BOARD_HALF, BOARD_TOP, CARD_HALF, GRASP_OUT +from .l7_offcenter_push import (OffcenterPush, PushSkills, long_box_xml, rect_frame_xml, HALF, + MASS, MU, box_fit, box_corners, _yaw, _rot) + +PRODUCTS = ('product_red_1', 'product_blue_1') +CARGO = PRODUCTS + ('card_1',) +PH = .014 + + +def shipping_xml(): + xml = long_box_xml('lff_dispatch_box') + parts=[] + for k,(p,h) in enumerate([((.042,0,.025),(.003,.11,.005)),((-.042,0,.025),(.003,.11,.005)), + ((0,.107,.032),(.039,.003,.012)),((0,-.107,.032),(.039,.003,.012))]): + parts.append(f'') + return xml.replace(' ', '\n'.join(parts)+'\n ',1) + + +class DispatchSkills(PushSkills): + def __init__(self, env, task, bias, recorder=None): + super().__init__(env,bias=bias,recorder=recorder,target=task.target_xy(task.inst)) + self.task=task + self.closes=[] + self.correction=np.zeros(3) + self.n_commands=0 + def reported_eef_pos(self): + return self.eef_pos()-self.bias + def move_to(self,target,*args,**kwargs): + self.n_commands+=1 + if self.n_commands>self.task.agent_max_steps:raise RuntimeError("dispatch command budget exceeded") + rep=super().move_to(np.asarray(target)-self.correction,*args,**kwargs) + rep['pos']=np.round(self.reported_eef_pos(),4).tolist() + return rep + def _act(self,dpos,drot,grip): + super()._act(dpos,drot,grip) + self.task.monitor_step() + if self.n_steps*.05>=3*self.task.agent_max_steps:raise RuntimeError('dispatch simulation budget exceeded') + def set_gripper(self,close,steps=15): + self.n_commands+=1 + if self.n_commands>self.task.agent_max_steps:raise RuntimeError("dispatch command budget exceeded") + ctx=self.task.close_context() if close and self.grip<0 else None + rep=super().set_gripper(close,steps) + if ctx is not None: + ctx.update(held=self.holding('card_1'),width=round(self.gripper_width(),4)) + self.closes.append(ctx) + return rep + + +@register_task +class OrderDispatch(CardEdge,OffcenterPush): + name='lh_order_dispatch' + level='L1' + failure_causes=('L1','L3','L5') + failure_types=failure_causes + category='system_identification' + capabilities=('Perceive','Reason','Plan','Restore') + protocol='cross' + max_attempts=5 + agent_max_steps=180 + instruction=('Load both small products and the red order card into the brown shipping tray, while it is in ' + 'the yellow loading rectangle. Then push the loaded tray with the closed gripper completely inside the green ' + 'delivery rectangle. All three items must remain inside the tray, with the gripper open and clear.') + instruction_indirect=('Pack the two small coloured cubes and the thin red rectangle into the long brown ' + 'container while the container is at its starting position, then push the loaded container with the closed ' + 'gripper completely into the green marked area. Keep every item inside, and finish with the ' + 'gripper open and clear.') + def make_bddl(self): + card=register_generated('LffDispatchCard',card_xml('lff_dispatch_card')) + board=register_generated('LffDispatchBoard',box_xml('lff_dispatch_board',BOARD_HALF,(.62,.45,.27,1),friction=(.3,.005,.0001)),free=False) + box=register_generated('LffDispatchBox',shipping_xml()) + zone_xml=ET.fromstring(rect_frame_xml('lff_dispatch_zone')) + load_xml=ET.fromstring(rect_frame_xml('lff_dispatch_loading',inner_half=(.10,.15),line_rgba=(.8,.6,.05,1),fill_rgba=(.95,.88,.55,1))) + body=zone_xml.find('worldbody/body/body') + for geom in load_xml.find('worldbody/body/body'): + q=np.fromstring(geom.get('pos','0 0 0'),sep=' ');q[0]-=.11;geom.set('pos',' '.join(map(str,q)));body.append(geom) + zone=register_generated('LffDispatchZone',ET.tostring(zone_xml,encoding='unicode'),free=False) + objs=[('card_1',card,'card_region',(-.305,.395,-.295,.405)),('box_1',box,'box_region',(-.255,-.005,-.245,.005))] + for k,o in enumerate(PRODUCTS): + cat=register_generated('LffDispatchProduct'+('Red' if k==0 else 'Blue'),box_xml('lff_dispatch_product_'+str(k),(PH,PH,PH),((.9,.1,.1,1) if k==0 else (.1,.2,.9,1)),density=500)) + objs.append((o,cat,'prod_region'+str(k),(-.305+.25*k,-.405,-.295+.25*k,-.395))) + return write_bddl(self.name,self.instruction,objs,[('board_1',board,'board_region',(.295,.345,.305,.355)),('zone_1',zone,'zone_region',(.295,-.355,.305,-.345))]) + def __init__(self,cam_res=None): + LFFTask.__init__(self,cam_res) + self.board_bid=self.env.sim.model.body_name2id(self.env.fixtures_dict['board_1'].root_body) + self.inst=None;self.mon=None + def sample_instance(self,seed): + rng=np.random.default_rng(seed) + bx=-.18;by=.20 + return dict(seed=int(seed),board_xy=[bx,by],card_xy=[bx,by],card_yaw=0.,card_along='x', + bin_xy=[-.21,-.08],box_xy=[-.21,-.08],target_dist=.11, + bias=[0.,float(rng.choice([-1,1])*.055),0.],com_offset=float(rng.choice([-1,1])*.06), + mechanisms={'L1':True,'L3':True,'L5':True}) + def apply_instance(self,inst): + self.inst=inst + OffcenterPush.apply_instance(self,inst) + m=self.env.sim.model + m.body_pos[self.board_bid]=[*inst['board_xy'],envs.TABLE_Z+BOARD_HALF[2]] + m.body_quat[self.board_bid]=[1,0,0,0] + envs.set_obj_pose(self.env,'card_1',[*inst['card_xy'],BOARD_TOP+CARD_HALF[2]+.0003],yaw=inst['card_yaw']) + for k,o in enumerate(PRODUCTS): + envs.set_obj_pose(self.env,o,[-.25+.14*k,-.31,envs.TABLE_Z+PH+.001]) + bid=envs.body_id(self.env,'box_1') + if not inst['mechanisms']['L5']:m.body_ipos[bid]=[0,0,0];envs.refit_bounds(self.env,bid) + if not inst['mechanisms']['L3']: + # Initial overhang removes the flat-card obstruction; reset-time placement only. + envs.set_obj_pose(self.env,'card_1',[inst['board_xy'][0]-BOARD_HALF[0]+CARD_HALF[0]-.03,inst['board_xy'][1],BOARD_TOP+CARD_HALF[2]+.0003]) + def reset_instance(self,inst,recorder=None): + self.mon=None;self.env.reset();self.apply_instance(inst);self.env.sim.forward();envs.settle(self.env,15) + self.sk=DispatchSkills(self.env,self,np.array(inst['bias']) if inst['mechanisms']['L1'] else np.zeros(3),recorder) + self.mon=dict(start_xy=self.card_pose()['xy'].copy(),max_lift=0.,max_overhang=0.,fell=False, + loaded=False,load_step=None,departed_unloaded=False,events=[],states={o:False for o in CARGO},l1_attempts=[]) + self.sim0=0;self.ncmd=0;self.budget=None + return self.sk + def in_cargo(self,o,require_support=True): + p=envs.obj_pos(self.env,o);b=envs.obj_pos(self.env,'box_1');R=_rot(_yaw(envs.obj_quat(self.env,'box_1'))) + rel=R.T@(p[:2]-b[:2]);half=PH if o in PRODUCTS else 0. + # Full footprint containment, including card corners. + if o=='card_1': + rels=(self.card_corners()[:,:2]-b[:2])@R + footprint=bool(np.all(np.abs(rels[:,0])<.039) and np.all(np.abs(rels[:,1])<.104)) + else: + rot=self.env.sim.data.body_xmat[envs.body_id(self.env,o)].reshape(3,3) + corners=np.array([p+rot@np.array([a*PH,b*PH,c*PH]) for a in (-1,1) for b in (-1,1) for c in (-1,1)]) + rels=(corners[:,:2]-b[:2])@R + footprint=bool(np.all(np.abs(rels[:,0])<.039) and np.all(np.abs(rels[:,1])<.104)) + support=any(envs.contacts_between(self.env,envs.obj_geom_ids(self.env,o),envs.obj_geom_ids(self.env,q)) for q in CARGO+('box_1',) if q!=o) + return bool(footprint and (support or not require_support) and b[2]+.015=0 else -1. + grasp=p['xy']+sign*.034*axis + floor=b[2]+HALF[2] + return self.grasp_and_bin(grasp,p['yaw'],floor-.003) + def load_product(self,o,k): + sk=self.sk;p=envs.obj_pos(self.env,o).copy();sk.set_gripper(False,8) + sk.move_to([p[0],p[1],envs.TABLE_Z+.18],yaw=0) + approach_offset=(sk.eef_pos()[:2]-p[:2]).tolist() + sk.move_to([p[0],p[1],p[2]+.003],tol=.002,max_steps=120) + offset=(sk.eef_pos()[:2]-p[:2]).tolist() + sk.set_gripper(True,15);sk.move_to([p[0],p[1],envs.TABLE_Z+.19]) + held=sk.holding(o) + self.mon['l1_attempts'].append(dict(item=o,offset=offset,approach_offset=approach_offset,correction=self.sk.correction.tolist(),held=bool(held),step=sk.n_steps)) + if not held:sk.set_gripper(False,8);return False + b=envs.obj_pos(self.env,'box_1');xy=[b[0],b[1]+(-.075 if k==0 else .075)] + sk.move_to([*xy,envs.TABLE_Z+.20]);sk.move_to([*xy,envs.TABLE_Z+.058],speed=.1) + sk.set_gripper(False,12);sk.move_to([*xy,envs.TABLE_Z+.22]);return self.in_cargo(o) + def execute(self,inst,params): + if 'mode' not in params: + return OffcenterPush.execute(self,inst,params) + mode=params['mode'];self.sk.correction=np.asarray(params.get('correction',[0,0,0]),dtype=float) + for k,o in enumerate(PRODUCTS): + if not self.load_product(o,k):return + if mode=='adaptive': + self.sk.correction+=np.array([*self.mon['l1_attempts'][-1]['approach_offset'],0.]) + if mode=='naive': + CardEdge.execute(self,inst,dict(mode='grasp')) + else: + CardEdge.execute(self,inst,dict(mode='edge',overhang=.03)) + self.sk.hold(10) + if not all(self.in_cargo(o) for o in CARGO):return + if mode=='adaptive': + OffcenterPush.adaptive_attempt(self,inst,params.get('c',0.)) + if not self.in_cargo('card_1'):self.repair_card() + else:OffcenterPush.execute(self,inst,dict(c=params.get('c',0.))) + p=self.sk.eef_pos();self.sk.move_to([p[0],p[1],envs.TABLE_Z+.23]);self.sk.set_gripper(False,8) + def outcome(self,inst): + self.sk.hold(30) + p=envs.obj_pos(self.env,'box_1');yaw=_yaw(envs.obj_quat(self.env,'box_1'));fit=box_fit(p[:2],yaw,self.target_xy(inst)) + cargo={o:self.in_cargo(o) for o in CARGO} + velocities=[] + for o in CARGO+('box_1',): + adr=self.env.sim.model.jnt_dofadr[self.env.sim.model.joint_name2id(self.env.objects_dict[o].joints[0])] + velocities.append(self.env.sim.data.qvel[adr:adr+6].copy()) + static=all(np.linalg.norm(v[:3])<.01 and np.linalg.norm(v[3:])<.15 for v in velocities) + m=self.env.sim.model + robot=[g for g in range(m.ngeom) if (m.geom_id2name(g) or '').startswith(('robot0_','gripper0_'))] + touching=any(envs.contacts_between(self.env,robot,envs.obj_geom_ids(self.env,o)) for o in CARGO+('box_1',)) + upright=envs.obj_upright_cos(self.env,'box_1')>.95 + success=bool(all(cargo.values()) and self.mon['loaded'] and not self.mon['departed_unloaded'] and fit['inside'] and static and upright and not touching and self.sk.grip<0) + bad=[m for m in self.sk.box_moves if m.get('bad') and not m.get('gripper_open') and self.mon['load_step'] is not None and m['step']>=self.mon['load_step']] + return copy.deepcopy(dict(success=success,cargo=cargo,loaded_in_start=bool(self.mon['loaded']),load_step=self.mon['load_step'],departed_unloaded=self.mon['departed_unloaded'],inside=fit['inside'],static=bool(static), + failure=None if success else 'cargo' if not all(cargo.values()) else 'loading_order' if not self.mon['loaded'] else 'delivery', + stages={**cargo,'loaded_in_start':self.mon['loaded'],'delivery':fit['inside']},events=self.mon['events'], + l1_attempts=self.mon['l1_attempts'],card_closes=self.sk.closes,card_lift=self.mon['max_lift'], + box_moves=self.sk.box_moves,l5_triggered=bool(bad),yaw_deg=float(np.degrees(yaw)), + sim_s=self.sk.n_steps*.05,commands=self.sk.n_commands,touching=bool(touching),upright=bool(upright), + detail='Cargo in tray: '+str(cargo)+'; tray inside delivery rectangle: '+str(fit['inside'])+'.')) + def default_params(self,inst):return dict(mode='naive') + def oracle_params(self,inst):return dict(mode='oracle',correction=(inst['bias'] if inst['mechanisms']['L1'] else [0,0,0]),c=inst['com_offset'] if inst['mechanisms']['L5'] else 0.) + def adapt_params(self,inst,history): + # Calibration estimate from the measured failed grasp, not hidden bias. + offsets=[x['offset'] for h in history for x in h['outcome']['l1_attempts']] + calibrations=[np.array(x.get('correction',h['params'].get('correction',[0,0,0])))+np.array([*x.get('approach_offset',x['offset']),0.]) for h in history for x in h['outcome']['l1_attempts']] + corr=np.mean(calibrations[-2:],axis=0).tolist() if calibrations else history[-1]['params'].get('correction',[0,0,0]) + moves=[m for h in history for m in h['outcome']['box_moves']] + return dict(mode='adaptive',correction=corr,c=self.bracket(moves)) + def blind_params(self,inst,attempt,rng):return dict(mode='naive',correction=[*rng.normal(0,.005,2),0.]) + def run_scripted(self,*args,**kwargs):return LFFTask.run_scripted(self,*args,**kwargs) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_pantry_relatch.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_pantry_relatch.py new file mode 100644 index 0000000000000000000000000000000000000000..7369d4e23432eed637a47131d7c8f988e5eca7f0 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_pantry_relatch.py @@ -0,0 +1,468 @@ +"""LH pantry_relatch: breakfast prep. Take the bread out of a hinged pantry box and put it on the plate, then put the +butter into the (now empty) box and close it. + +New mechanism (not a repeat of lh_lid_box / lh_shelf_droop / lh_false_bottom_lid): the box's closing catch is not a +static per-instance draw, it is a counter of how many times the box has already been closed in this attempt. A weak +spring (`OPEN_BIAS`) constantly nudges the lid open; a catch (`qfrc_applied`, same idiom as lh_shelf_droop's bracket) +counters it near the closed angle. The FIRST close always holds (LATCH0 beats the spring) even with a quick swing-and +-release. After one full open/close cycle the catch's holding strength is reduced (`DECAY`); a second quick-release +close is no longer enough and the lid creeps back open by itself during the mandatory settle window, with nothing +else touching it. The fix is not "close it again the same way" (that decays again); it is a firm press-and-hold +(`dwell`) at the closed angle before letting go, which engages a separate, non-decaying friction seat +(`SEAT_LATCH`) regardless of cycle count. + +Geometry/skills are reused unmodified from lh_lid_box.py (box_lid_xml, LidSkills): only the hinge's spring/latch +torques and the Python cycle counter are new. Protocol: cross, k = 5. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import box_xml, register_generated +from ..task_base import LFFTask, register_task +from .lh_lid_box import (BOX_D, BOX_W, WALL_H, WALL_T, FLOOR_T, LID_T, LID_MASS, IN_X, IN_Y, HINGE_DAMP, box_lid_xml, + LidSkills) + +G = 9.81 +BOX = "box_1" +BOX_MODEL = "lff_pantry_box" + +BREAD_HALF = (0.032, 0.022, 0.011) # 6.4 x 4.4 x 2.2 cm flat loaf, fits the 3.2 cm interior height +BUTTER_HALF = (0.013, 0.013, 0.013) # 2.6 cm cube +BREAD_DENS, BUTTER_DENS = 400.0, 600.0 + +# ---------------------------------------------------------------- latch-fatigue mechanism +CLOSE_DEG = 4.0 # lid angle (deg) counted as "closed" for the final judge +BAND_DEG = 100.0 # angle range (deg) over which gravity is cancelled and the open bias/catch act (wide, so +# an unlatched lid drifts smoothly all the way open instead of sticking at a cutoff edge) +OPEN_BIAS = 0.05 # N*m: net torque pushing the lid open within the band, once gravity is cancelled +LATCH0 = 0.14 # N*m: catch strength on the FIRST close (always beats OPEN_BIAS) +DECAY = 0.30 # catch strength multiplier from the SECOND close on, if not seated +SEAT_LATCH = 0.18 # N*m: non-decaying strength if the close was seated (dwell-pressed) +DWELL_MIN = 20 # control steps (closed, knob held, no further motion) needed to seat a close +EXTRA_DAMP = 0.12 # N*m*s/rad added to the hinge dof so an unlatched drift takes a few seconds, not instant +GRAVITY_LEVER = BOX_D / 2 # lid's centre of mass offset from the hinge (box_lid_xml convention) +T_GRAV0 = LID_MASS * G * GRAVITY_LEVER + +SETTLE_MIN, SETTLE_MAX = 300, 600 # 15-30 s simulated, same convention as lh_shelf_droop + + +def _fb(v): + return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}" + + +def _lr(v): + return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}" + + +class RelatchSkills(LidSkills): + """LidSkills plus a dwell counter: control steps spent holding the knob still at the closed angle while latched. + `monitor_step` (run every control step via LidSkills._act, before this class's own _act resets the counter) + reads it at the instant the gripper opens near the closed angle to decide whether this close is 'seated'.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, task, recorder=recorder) + self.dwell = 0 + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) # LidSkills._act calls self.task.monitor_step() before returning here + if self.latched: + # the agent (or scripted policy) is actively holding the knob: never let the artificial drift fight + # that grasp (it caused the knob to wander off mid-regrasp during prototyping). + self.task.drift_active = False + if self.task.lid_deg() < CLOSE_DEG: + self.dwell += 1 + else: + self.dwell = 0 + else: + self.dwell = 0 + + +@register_task +class PantryRelatch(LFFTask): + name = "lh_pantry_relatch" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Plan", "Restore") + protocol = "cross" + max_attempts = 5 + agent_max_steps = 130 + instruction = ("Open the lid of the wooden pantry box (lift it by the black knob) and take the bread out; put it " + "on the plate. Then open the box again, put the butter inside it, and close the lid. At the end " + "the bread must be on the plate, the butter inside the box, the lid closed, the gripper open and " + "clear, and the scene still.") + instruction_indirect = ("Lift the lid of the flat wooden case by its black ball knob and take out the little " + "loaf; set it on the round plate. Then open the case again, put the small pale cube " + "inside it, and shut the lid. Finish with the loaf on the plate, the cube inside the " + "case, the lid down, the gripper open, and nothing moving.") + agent_object_names = ["bread (small loaf)", "butter (small pale cube)", "wooden pantry box", "lid knob", "plate"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + box = register_generated("LffPantryBox", box_lid_xml(BOX_MODEL), free=False) + bread = register_generated("LffPantryBread", box_xml("lff_pantry_bread", BREAD_HALF, (0.74, 0.52, 0.22, 1.0), + density=BREAD_DENS, friction=(0.7, 0.005, 0.0001))) + butter = register_generated("LffPantryButter", box_xml("lff_pantry_butter", BUTTER_HALF, (0.95, 0.92, 0.70, 1.0), + density=BUTTER_DENS, friction=(0.5, 0.005, 0.0001))) + objs = [("bread_1", bread, "bread_region", (-0.31, -0.01, -0.29, 0.01)), + ("butter_1", butter, "butter_region", (-0.31, 0.24, -0.29, 0.26)), + ("plate_1", "plate", "plate_region", (0.02, -0.26, 0.04, -0.24))] + fx = [(BOX, box, "box_region", (-0.18, -0.01, -0.16, 0.01))] + return write_bddl(self.name, "take the bread out, put it on the plate, put the butter in the box, close it", + objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + pre = f"{BOX}_{BOX_MODEL}" + self.jid = m.joint_name2id(pre + "_hinge") + self.qa = int(m.jnt_qposadr[self.jid]) + self.dof = int(m.jnt_dofadr[self.jid]) + self.box_bid = m.body_name2id(self.env.fixtures_dict[BOX].root_body) + self.knob_geom_name = pre + "_knob" + self.knob_geom_names = [pre + "_knob", pre + "_stem"] + self.knob_gid = m.geom_name2id(self.knob_geom_name) + sim = self.env.sim + if not getattr(sim, "_lhpr_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lhpr_task", None) + if t is not None: + t._bracket() + + sim.step = step + sim._lhpr_wrapped = True + sim._lhpr_task = self + self.inst = None + self.mon = None + self.active_latch = LATCH0 + self.closes_done = 0 + self.drift_active = False + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + bx, by = float(rng.uniform(-0.19, -0.15)), float(rng.uniform(-0.03, 0.03)) + plate_xy = [float(rng.uniform(0.0, 0.06)), float(rng.uniform(-0.27, -0.23))] + bread_xy = [bx + float(rng.uniform(-0.01, 0.01)), by + float(rng.uniform(-0.01, 0.01))] + butter_xy = [float(rng.uniform(-0.32, -0.28)), float(rng.uniform(0.22, 0.28))] + return dict(seed=int(seed), box_xy=[bx, by], plate_xy=plate_xy, bread_xy=bread_xy, butter_xy=butter_xy, + bread_yaw=float(rng.uniform(-0.2, 0.2)), latch=True) + + def apply_instance(self, inst): + self.inst = inst + m, d = self.env.sim.model, self.env.sim.data + bx, by = inst["box_xy"] + m.body_pos[self.box_bid] = [bx, by, envs.TABLE_Z] + m.body_quat[self.box_bid] = [1.0, 0.0, 0.0, 0.0] + m.jnt_range[self.jid] = [0.0, np.radians(150.0)] + d.qpos[self.qa] = 0.0 + d.qvel[self.dof] = 0.0 + d.qfrc_applied[self.dof] = 0.0 + m.dof_damping[self.dof] = HINGE_DAMP + EXTRA_DAMP # absolute, not cumulative across repeated resets + self._move_keep_orientation("plate_1", inst["plate_xy"]) + envs.set_obj_pose(self.env, "bread_1", [bx, by, envs.TABLE_Z + FLOOR_T + BREAD_HALF[2] + 0.001], + yaw=inst["bread_yaw"]) + envs.set_obj_pose(self.env, "butter_1", [*inst["butter_xy"], envs.TABLE_Z + BUTTER_HALF[2] + 0.0005]) + self.closes_done = 0 + self.active_latch = LATCH0 + self.drift_active = False + + def _move_keep_orientation(self, name, xy, clearance=0.002): + qa, da = envs.free_joint_addr(self.env, name) + d = self.env.sim.data + d.qpos[qa:qa + 2] = xy + d.qvel[da:da + 6] = 0.0 + self.env.sim.forward() + d.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (envs.TABLE_Z + clearance) + self.env.sim.forward() + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.mon = dict(events=[], lid_open_max=0.0, armed=False) + self.sk = RelatchSkills(self.env, self, recorder=recorder) + return self.sk + + # ------------------------------------------------------------ latch physics + def lid_q(self): + return float(self.env.sim.data.qpos[self.qa]) + + def lid_deg(self): + return float(np.degrees(self.lid_q())) + + def knob_xyz(self): + return self.env.sim.data.geom_xpos[self.knob_gid].copy() + + def hinge_xz(self): + return self.inst["box_xy"][0] + BOX_D / 2, envs.TABLE_Z + WALL_H + + def _bracket(self): + """Every MuJoCo substep. Only active between a just-finished, under-latched close and the next time the + agent actually grasps the knob again (self.drift_active, cleared the instant the knob is latched -- see + RelatchSkills._act): within BAND_DEG of closed, cancel gravity's closing pull and add a small constant + opening bias, net positive because the catch is too weak (self.active_latch < OPEN_BIAS whenever + drift_active is set True in the first place). A held-firmly close needs no artificial force at all: plain + gravity already keeps box_lid_xml's lid shut on its own, same as lh_lid_box.""" + d = self.env.sim.data + if not self.inst.get("latch", True) or not self.drift_active: + d.qfrc_applied[self.dof] = 0.0 # never leave a stale value applied once the drift is no longer armed + return + th = float(d.qpos[self.qa]) + # the closed rest angle overshoots the joint limit by a hair (contact softness), so the lower edge of the + # band must tolerate a small negative theta -- a strict "th >= 0" guard left qfrc_applied permanently 0 at + # the resting pose and the catch never engaged at all (measured during prototyping). + if np.radians(-3.0) <= th < np.radians(BAND_DEG): + grav = T_GRAV0 * max(np.cos(th), 0.0) + d.qfrc_applied[self.dof] = grav + OPEN_BIAS - self.active_latch + else: + d.qfrc_applied[self.dof] = 0.0 + + def _register_close(self, seated): + """Called once a close-then-release is detected. Decides the catch strength that will apply to THIS closed + state from now on (until the lid is reopened and closed again), and whether the artificial drift-open force + is armed (only when the catch is too weak to hold on its own).""" + if self.closes_done == 0: + self.active_latch = LATCH0 + elif seated: + self.active_latch = SEAT_LATCH + else: + self.active_latch = LATCH0 * DECAY + self.closes_done += 1 + self.drift_active = self.active_latch < OPEN_BIAS + self.mon["events"].append(dict(ev="closed", n=self.closes_done, seated=bool(seated), + active_latch=round(self.active_latch, 4), drift_armed=self.drift_active)) + + def monitor_step(self): + """Runs every control step (via LidSkills._act, for the scripted policies below and for a real agent's own + move_to/set_gripper calls alike). One-shot edge detector: 'armed' once the lid has been meaningfully open + (> 20 deg); the first step afterwards where it is back near closed AND the gripper is open counts as a + close event, scored seated/unseated from the dwell counter at that exact instant (before RelatchSkills._act + resets it for this same step -- see the call order note there).""" + mon = self.mon + if mon is None: + return + q = self.lid_deg() + mon["lid_open_max"] = max(mon["lid_open_max"], q) + if q > 20.0: + mon["armed"] = True + if mon.get("armed") and q <= CLOSE_DEG and self.sk.grip < 0: + mon["armed"] = False + self._register_close(self.sk.dwell >= DWELL_MIN) + + # ------------------------------------------------------------ predicates + def held(self, name): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name])) + + def bread_on_plate(self): + p = envs.obj_pos(self.env, "bread_1") + d = np.linalg.norm(p[:2] - np.asarray(self.inst["plate_xy"])) + return bool(d < 0.05 and p[2] < envs.TABLE_Z + 0.06 and not self.held("bread_1")) + + def butter_in_box(self): + p = envs.obj_pos(self.env, "butter_1") + rel = p[:2] - np.asarray(self.inst["box_xy"]) + return bool(abs(rel[0]) <= IN_X - 0.004 and abs(rel[1]) <= IN_Y - 0.004 and p[2] < envs.TABLE_Z + WALL_H + and not self.held("butter_1")) + + def lid_closed(self): + return self.lid_q() <= np.radians(CLOSE_DEG) + + def stage_values(self): + return dict(bread_on_plate=self.bread_on_plate(), butter_in_box=self.butter_in_box(), lid_closed=self.lid_closed()) + + # ------------------------------------------------------------ scripted primitives + def pick_place(self, name, dest_xy, z_rel, z_carry=0.14, dest_yaw=0.0): + sk = self.sk + Z = envs.TABLE_Z + p = envs.obj_pos(self.env, name) + zg = p[2] - Z + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], Z + max(z_carry, zg + 0.06)], yaw=0.0) + sk.move_to([p[0], p[1], Z + zg], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([p[0], p[1], Z + z_carry], speed=0.3) + self.monitor_step() + if not self.held(name): + sk.set_gripper(False, steps=8) + return False + sk.move_to([dest_xy[0], dest_xy[1], Z + z_carry], yaw=dest_yaw) + sk.move_to([dest_xy[0], dest_xy[1], Z + z_rel], tol=0.003) + sk.set_gripper(False, steps=12) + sk.move_to([dest_xy[0], dest_xy[1], Z + z_carry]) + self.monitor_step() + return True + + def take_bread(self): + return self.pick_place("bread_1", self.inst["plate_xy"], BREAD_HALF[2] + 0.004) + + def put_butter(self): + # placed closer to the hinge side and off to one side of the box centre, clear of where the far (knob) end + # of the lid sweeps most when re-opened for a repair (measured during prototyping: a butter cube resting + # under the box centre was occasionally grazed by that swing). + bx, by = self.inst["box_xy"] + target = [bx + 0.6 * IN_X, by + 0.5 * IN_Y] + return self.pick_place("butter_1", target, FLOOR_T + BUTTER_HALF[2] + 0.006, z_carry=0.12) + + def _grasp_knob(self): + sk = self.sk + k = self.knob_xyz() + sk.set_gripper(False, steps=8) + sk.move_to([k[0], k[1], k[2] + 0.08], yaw=0.0) + sk.move_to([k[0], k[1], k[2]], tol=0.003) + sk.set_gripper(True, steps=15) + return k + + def open_lid(self, back=0.03, up=0.16): + sk = self.sk + k = self._grasp_knob() + hx, hz = self.hinge_xz() + sk.move_to([k[0], k[1], k[2] + 0.10]) + sk.move_to([hx + back, k[1], hz + up]) + sk.set_gripper(False, steps=10) + e = sk.eef_pos() + sk.move_to([e[0] - 0.03, e[1], e[2] + 0.06]) + sk.hold(20) + self.monitor_step() + + def close_lid(self, dwell=False): + """grasp the knob, carry it down the hinge's arc to the closed angle (the compliant knob-hold mechanism + clamps the physical joint limit at 0 deg, so a target far past closed just drives it fully shut); if dwell, + hold there (gripper still closed on the knob) for DWELL_MIN+ steps before releasing (seats the friction + catch); otherwise release immediately.""" + sk = self.sk + k = self._grasp_knob() + hx, hz = self.hinge_xz() + sk.move_to([k[0], k[1], k[2] + 0.10]) + far_x = hx - (BOX_D + 0.20) + low_z = envs.TABLE_Z + 0.02 + for _ in range(4): + if self.lid_deg() <= CLOSE_DEG: + break + sk.move_to([far_x, sk.eef_pos()[1], low_z], tol=0.01, max_steps=150) + if dwell: + sk.hold(DWELL_MIN + 8) + sk.set_gripper(False, steps=10) + e = sk.eef_pos() + sk.move_to([e[0], e[1], e[2] + 0.06]) + sk.hold(20) + self.monitor_step() + + # ------------------------------------------------------------ outcome + def _static(self): + d = self.env.sim.data + for name in ("bread_1", "butter_1"): + _, da = envs.free_joint_addr(self.env, name) + if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5: + return False + return abs(float(d.qvel[self.dof])) < 0.2 + + def outcome(self, inst): + sk = self.sk + n = 0 + while n < SETTLE_MAX: + sk.hold(10) + n += 10 + if n >= SETTLE_MIN and self._static(): + break + vals = self.stage_values() + held = [n for n in ("bread_1", "butter_1") if self.held(n)] + static = self._static() + success = bool(all(vals.values()) and static and not held) + if success: + failure = None + detail = "Bread is on the plate, butter is in the box, and the lid is closed." + else: + failure = ("bread" if not vals["bread_on_plate"] else "butter" if not vals["butter_in_box"] else + "lid_open" if not vals["lid_closed"] else "held" if held else "not_static") + parts = [] + if not vals["bread_on_plate"]: + p = envs.obj_pos(self.env, "bread_1") + rel = p[:2] - np.asarray(inst["plate_xy"]) + parts.append("The bread is still held." if self.held("bread_1") else + f"The bread is not on the plate: {_fb(rel[0])} and {_lr(rel[1])} of the plate's centre.") + if not vals["butter_in_box"]: + p = envs.obj_pos(self.env, "butter_1") + rel = p[:2] - np.asarray(inst["box_xy"]) + parts.append("The butter is still held." if self.held("butter_1") else + f"The butter is not in the box: {_fb(rel[0])} and {_lr(rel[1])} of the box's centre.") + if not vals["lid_closed"]: + parts.append(f"The lid is not closed (open {self.lid_deg():.0f} degrees). It had been closed " + f"{self.closes_done} time(s) in this attempt; it did not stay shut on its own.") + if held: + parts.append(f"Still held: {', '.join(held)}.") + if not static and all(vals.values()): + parts.append("Something was still moving.") + detail = " ".join(parts) + return dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, + lid_final_deg=round(self.lid_deg(), 1), lid_open_max=round(self.mon["lid_open_max"], 1), + closes_done=self.closes_done, active_latch=round(self.active_latch, 4), + events=list(self.mon["events"]), detail=detail) + + # ------------------------------------------------------------ execution + scripted policies + def execute(self, inst, params): + self.open_lid() + if not self.take_bread(): + return + self.close_lid(dwell=params.get("dwell1", False)) + self.open_lid() + if not self.put_butter(): + return + self.close_lid(dwell=params.get("dwell2", False)) + if params.get("check", False): + # look back before finishing: wait long enough (same order as the final settle window) for an + # under-latched close to reveal itself, then fix it with a firm dwell close if it did -- a genuine + # same-attempt recovery, not just a cross-attempt change of technique. + n = 0 + while n < SETTLE_MIN and self.lid_closed(): + self.sk.hold(10) + n += 10 + if not self.lid_closed(): + self.open_lid() + self.close_lid(dwell=True) + self.sk.hold(5) + + def default_params(self, inst): + return dict(dwell1=False, dwell2=False, check=False) + + def oracle_params(self, inst): + return dict(dwell1=False, dwell2=True, check=False) + + def adapt_params(self, inst, history): + """From attempt 2 on (if attempt 1's own same-attempt check-and-repair somehow still fell short): close + every time with a firm dwell from the start, and keep checking before finishing.""" + return dict(dwell1=True, dwell2=True, check=True) + + def blind_params(self, inst, attempt, rng): + return dict(dwell1=False, dwell2=bool(rng.random() < 0.5), check=False) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + # attempt 1: naive technique plus a final look-back-and-repair (genuine same-attempt recovery); + # only if that still were not enough would later attempts switch technique from the start. + params = (dict(self.default_params(inst), check=True) if a == 0 + else self.adapt_params(inst, history)) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_parts_cart.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_parts_cart.py new file mode 100644 index 0000000000000000000000000000000000000000..e8992d05ab373c966acef42134bb2f87ddec4743 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_parts_cart.py @@ -0,0 +1,253 @@ +"""Composite prototype: physical tool retrieval, loading regression and asymmetric cart transport. + +Not part of main_v1. See task_cards/lh_parts_cart.md for validation status. +Only reset_instance/apply_instance position objects; all reference actions use the public motion skills. +""" +import copy +import numpy as np +from .. import envs +from ..bddl import write_bddl +from ..objects import register_generated, box_xml +from ..task_base import register_task +from .l3_tool import (UnderTableTool, low_table_xml, stick_xml, CUBE_HALF, + HANDLE_HALF, TOP_HALF) +from .l7_offcenter_push import (OffcenterPush, PushSkills, long_box_xml, rect_frame_xml, + HALF, MASS, MU, BOX, _rot) + + +class CartSkills(PushSkills): + def __init__(self,*args,**kwargs): + super().__init__(*args,**kwargs) + self.robot_commands=0 + def move_to(self,*args,**kwargs): + self.robot_commands+=1 + return super().move_to(*args,**kwargs) + def set_gripper(self,*args,**kwargs): + self.robot_commands+=1 + return super().set_gripper(*args,**kwargs) + + +@register_task +class PartsCart(UnderTableTool): + name = 'lh_parts_cart' + level = 'L4' + category = 'geometry_inference' + failure_causes = ('L4', 'L2', 'L5') + capabilities = ('Perceive', 'Reason', 'Plan', 'Restore') + protocol = 'cross' + agent_max_steps = 180 + instruction = ('Use the wooden tool to retrieve the red part from under the low glass table. ' + 'Load the red and blue parts on the two marks on the brown transport platform, ' + 'then push the loaded platform with the closed gripper completely into the green parking area. ' + 'At the end both parts must still be on their marks, and the gripper must be open and clear.') + instruction_indirect = instruction + + def make_bddl(self): + cube = register_generated('LffPartsCartRed', box_xml('lff_parts_cart_red', (CUBE_HALF,)*3,(.85,.12,.12,1), density=300)) + blue = register_generated('LffPartsCartBlue', box_xml('lff_parts_cart_blue', (CUBE_HALF,)*3,(.1,.2,.85,1), density=300)) + stick_xml_text=stick_xml('lff_parts_cart_stick').replace('size="0.00800 0.02500 0.01000"','size="0.00800 0.00800 0.01000"') + stick = register_generated('LffPartsCartStick', stick_xml_text) + table_xml=low_table_xml('lff_parts_cart_table') + # Wider roof with legs outside the blocked cube's x-exit lane. This prevents a panel failure + # trapping the cube against a corner leg, which the existing standalone task did not test in-attempt. + table_xml=table_xml.replace('size="0.06000 0.06000 0.00500"','size="0.06000 0.07500 0.00500"') + for sx in (-.052,.052): + for sy in (-.052,.052): + table_xml=table_xml.replace(f'pos="{sx:.5f} {sy:.5f} 0.03500"',f'pos="{sx:.5f} {np.sign(sy)*.067:.5f} 0.03500"') + table = register_generated('LffPartsCartTable', table_xml, free=False) + xml=long_box_xml('lff_parts_cart_platform') + marks=''.join(f'' for y,color in [(-.03,'.9 .4 .4 1'),(.03,'.4 .5 .9 1')]) + xml=xml.replace(' ',marks+' ',1) + cart = register_generated('LffPartsCartPlatform', xml) + zone = register_generated('LffPartsCartZone', rect_frame_xml('lff_parts_cart_zone'), free=False) + # Inertial/shape match existing off-centre box, with purely visual cargo marks. + objs=[('cube_1',cube,'red_region',(-.31,-.26,-.29,-.24)), + ('blue_1',blue,'blue_region',(-.31,.24,-.29,.26)), + ('stick_1',stick,'stick_region',(-.01,-.36,.01,-.34)), + ('box_1',cart,'cart_region',(.19,.24,.21,.26))] + fx=[('lowtable_1',table,'table_region',(.19,-.11,.21,-.09)), + ('zone_1',zone,'zone_region',(.19,.39,.21,.41))] + return write_bddl(self.name,self.instruction,objs,fx) + + def sample_instance(self, seed): + # Tool geometry is inherited; put transport in the other half of the same tabletop. + rng=np.random.default_rng(seed) + base=super().sample_instance(seed) + base.update(side=-1, pane_side=1, table_xy=[-.08,-.08],cube_xy=[-.08,-.08], + stick_xy=[-.08,-.34],stick_yaw=np.pi/2, + box_xy=[-.25,.24],target_dist=.16, + com_offset=float(rng.choice([-1,1])*rng.uniform(.05,.065)), + traps=dict(L4=True,L2=True,L5=True)) + base['bin_xy']=[-.25,.24] # inherited observe() only; no bin fixture. + return base + + def target_xy(self, inst): + return np.array([inst['box_xy'][0]+inst['target_dist'],inst['box_xy'][1]]) + + def apply_instance(self, inst): + self.inst=inst + m=self.env.sim.model + bid,_=self._fixture('lowtable_1') + m.body_pos[bid]=[*inst['table_xy'],envs.TABLE_Z] + for g,sy in self._panes(): + on=inst['traps']['L4'] and sy==inst['pane_side'] + m.geom_contype[g]=m.geom_conaffinity[g]=int(on) + envs.set_obj_pose(self.env,'cube_1',[*inst['cube_xy'],envs.TABLE_Z+CUBE_HALF+.0005]) + envs.set_obj_pose(self.env,'blue_1',[-.30,.04,envs.TABLE_Z+CUBE_HALF+.0005]) + envs.set_obj_pose(self.env,'stick_1',[*inst['stick_xy'],envs.TABLE_Z+HANDLE_HALF[2]+.0005],yaw=inst['stick_yaw']) + bid=envs.body_id(self.env,BOX) + m.body_mass[bid]=MASS + m.body_ipos[bid]=[0,inst['com_offset'] if inst['traps']['L5'] else 0,0] + for g in range(m.ngeom): + if m.geom_bodyid[g]==bid and (np.allclose(m.geom_rgba[g,:3],[.9,.4,.4]) or np.allclose(m.geom_rgba[g,:3],[.4,.5,.9])): + m.geom_pos[g,1]=np.sign(m.geom_pos[g,1])*(.03 if inst['traps']['L2'] else .07) + envs.refit_bounds(self.env,bid) + envs.set_friction(self.env,BOX,MU) + envs.set_obj_pose(self.env,BOX,[*inst['box_xy'],envs.TABLE_Z+HALF[2]+.001]) + zb=m.body_name2id(self.env.fixtures_dict['zone_1'].root_body) + m.body_pos[zb]=[*self.target_xy(inst),envs.TABLE_Z+.0002] + + def reset_instance(self, inst, recorder=None): + self.loadmon=None + self._mon=None + self.env.reset();self.apply_instance(inst);self.env.sim.forward();envs.settle(self.env,15) + self.sk=CartSkills(self.env,recorder=recorder,target=self.target_xy(inst)) + self._start_monitor() + self.loadmon=dict(states=[False,False],count=[0,0],ever=[False,False],lost=[False,False],events=[],loaded=False,departed_unloaded=False,load_step=None,departure_step=None,last_robot_touch=[-10000,-10000]) + self.ncmd=0;self.budget=None + return self.sk + + def mark(self,i): + p,yaw=self.sk._box_pose() if self.sk else (envs.obj_pos(self.env,BOX),0.) + spacing=.03 if self.inst['traps']['L2'] else .07 + return p[:2]+_rot(yaw)@np.array([0.,(-spacing,spacing)[i]]) + + def cargo_ok(self,i): + obj=('cube_1','blue_1')[i] + p=envs.obj_pos(self.env,obj); bp=envs.obj_pos(self.env,BOX) + return bool(np.linalg.norm(p[:2]-self.mark(i))<.018 and + abs(p[2]-(bp[2]+HALF[2]+CUBE_HALF))<.012 and not self.sk.holding(obj)) + + def _monitor_step(self): + super()._monitor_step() + mon=getattr(self,'loadmon',None) + if mon is None:return + robot=set(envs.robot_geom_ids(self.env)) + for i,obj in enumerate(('cube_1','blue_1')): + geoms=set(envs.obj_geom_ids(self.env,obj)) + for c in self.env.sim.data.contact[:self.env.sim.data.ncon]: + if (c.geom1 in robot and c.geom2 in geoms) or (c.geom2 in robot and c.geom1 in geoms): + mon['last_robot_touch'][i]=self.sk.n_steps + now=self.cargo_ok(i) + if now==mon['states'][i]:mon['count'][i]=0;continue + mon['count'][i]+=1 + if mon['count'][i]<5:continue + mon['count'][i]=0;mon['states'][i]=now + ev='restored' if now and mon['lost'][i] else 'achieved' if now else 'lost' + if now:mon['ever'][i]=True + else: + mon['lost'][i]=True + if np.linalg.norm(envs.obj_pos(self.env,BOX)[:2]-self.inst['box_xy'])<.025: + mon['loaded']=False + mon['load_step']=None + mon['events'].append(dict(step=self.sk.n_steps,pred=('red','blue')[i],event=ev, + cart_displacement=float(np.linalg.norm(envs.obj_pos(self.env,BOX)[:2]-self.inst['box_xy'])), + cause='robot' if self.sk.n_steps-mon['last_robot_touch'][i]<=20 else 'other')) + displacement=np.linalg.norm(envs.obj_pos(self.env,BOX)[:2]-self.inst['box_xy']) + if all(mon['states']) and displacement<.02 and not mon['loaded']: + mon['loaded']=True + mon['load_step']=self.sk.n_steps + if displacement>.03 and mon['departure_step'] is None: + mon['departure_step']=self.sk.n_steps + if not mon['loaded']:mon['departed_unloaded']=True + + def pick_place(self,obj,xy,yaw=0.): + sk=self.sk;p=envs.obj_pos(self.env,obj) + sk.set_gripper(False,steps=10) + sk.move_to([p[0],p[1],envs.TABLE_Z+.18],yaw=0. if obj=='cube_1' and self.under_table(margin=.08) else yaw) + sk.move_to([p[0],p[1],p[2]-.004],speed=.10,tol=.002) + sk.set_gripper(True,steps=15) + held=sk.holding(obj) + sk.move_to([p[0],p[1],envs.TABLE_Z+.20],speed=.15) + if held: + sk.move_to([xy[0],xy[1],envs.TABLE_Z+.20],yaw=yaw) + bp=envs.obj_pos(self.env,BOX) + sk.move_to([xy[0],xy[1],bp[2]+HALF[2]+CUBE_HALF-.003],speed=.06,tol=.002) + sk.set_gripper(False,steps=15) + sk.move_to([xy[0],xy[1],envs.TABLE_Z+.22],speed=.15) + return bool(held) + + def load(self, careful=True): + self.pick_place('cube_1',self.mark(0),np.pi/2) + # Open fingers along y at the adjacent mark can knock the already loaded red cube. + yaw=np.pi/2 if careful else 0. + self.pick_place('blue_1',self.mark(1),yaw) + + def repair_load(self): + for _ in range(3): + for i,o in enumerate(('cube_1','blue_1')): + if not self.cargo_ok(i):self.pick_place(o,self.mark(i),np.pi/2) + + def transport(self,c=0.,repair=False): + # Call existing push controller on this same environment; no independent rollout stitching. + if not repair: + return OffcenterPush.execute(self,self.inst,dict(c=c)) + if repair: + # Original feedback-driven corrector calls self.execute for its initial push. + self._transport_only=True + try:OffcenterPush.adaptive_attempt(self,self.inst,c) + finally:self._transport_only=False + + _cmd=OffcenterPush._cmd + _sim_used=OffcenterPush._sim_used + _push_at=OffcenterPush._push_at + bracket=OffcenterPush.bracket + _front_runup=staticmethod(OffcenterPush._front_runup) + STEP=OffcenterPush.STEP;YAW_OK=OffcenterPush.YAW_OK + GAIN0=OffcenterPush.GAIN0;SAFE_V=OffcenterPush.SAFE_V + + def execute(self,inst,params): + if getattr(self,'_transport_only',False):return OffcenterPush.execute(self,inst,params) + if params.get('front',False):self.tool_push_front() + else:self.tool_push_out() + if self.under_table():return + self.load(params.get('careful',False)) + if params.get('repair',False):self.repair_load() + if all(self.cargo_ok(i) for i in range(2)): + self.transport(params.get('c',0.),params.get('repair',False)) + if params.get('repair',False):self.repair_load() + self.sk.set_gripper(False,steps=10) + p=self.sk.eef_pos();self.sk.move_to([p[0],p[1],envs.TABLE_Z+.24]) + + def default_params(self,inst):return dict(front=False,careful=False,repair=False,c=0.) + def oracle_params(self,inst):return dict(front=True,careful=True,repair=True,c=inst['com_offset'] if inst['traps']['L5'] else 0.) + def adapt_params(self,inst,history): + # The L4 side hit is learned from actual prior outcome, not from inst['pane_side']. + seen_geometry=any(h['outcome']['traps']['L4'] for h in history) + seen_loading=any(h['outcome']['traps']['L2'] for h in history) + pushes=[m for h in history for m in h['outcome']['box_moves']] + return dict(front=seen_geometry,careful=seen_loading,repair=bool(history),c=self.bracket(pushes)) + + def outcome(self,inst): + self.sk.hold(30) + fit=self.sk.fit();cargo=[self.cargo_ok(i) for i in range(2)] + ev=list(self.loadmon['events']) + # Loading regressions count only while cart remains at the loading station. + load_lost=[e for e in ev if e['event']=='lost' and e['cart_displacement']<.025 and e['cause']=='robot'] + loaded=self.loadmon['loaded'] + static=bool(np.max(np.abs(self.env.sim.data.qvel))<.05) + robot=set(envs.robot_geom_ids(self.env)); items=set() + for o in ('cube_1','blue_1',BOX,'stick_1'):items.update(envs.obj_geom_ids(self.env,o)) + touching=any((c.geom1 in robot and c.geom2 in items) or (c.geom2 in robot and c.geom1 in items) + for c in self.env.sim.data.contact[:self.env.sim.data.ncon]) + budget_ok=bool(self.sk.robot_commands<=self.agent_max_steps and self.sk.n_steps*.05<=self.agent_max_steps*3) + success=bool(not self.under_table() and all(cargo) and fit['inside'] and loaded + and not self.loadmon['departed_unloaded'] and static and not touching and budget_ok and self.sk.grip<0 + and self._mon['stick_touched_cube']) + moves=copy.deepcopy(self.sk.box_moves) + return dict(success=success,stages=dict(retrieved=not self.under_table(),red=cargo[0],blue=cargo[1],parked=fit['inside'],loaded=loaded), + static=static,touching=bool(touching),tool_used=bool(self._mon['stick_touched_cube']),load_step=self.loadmon['load_step'],departure_step=self.loadmon['departure_step'],commands=self.sk.robot_commands,budget_ok=budget_ok,departed_unloaded=self.loadmon['departed_unloaded'], + events=ev,n_regressions=len(load_lost),n_restored=sum(e['event']=='restored' for e in ev), + traps=dict(L4=bool(self._mon['cube_hit_pane']),L2=bool(load_lost),L5=any(m['bad'] for m in moves)), + box_moves=moves,cart_pose=[*envs.obj_pos(self.env,BOX).tolist()],cart_fit=fit, + detail=f'Retrieved={not self.under_table()}; cargo on marks={cargo}; platform parked={fit["inside"]}.') diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_shelf_droop.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_shelf_droop.py new file mode 100644 index 0000000000000000000000000000000000000000..d12da555297b5861b08e66421b794b164dd5281e --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_shelf_droop.py @@ -0,0 +1,1009 @@ +"""LH lh_shelf_droop (2026-10-16; v2 the same day): put four jars on a wall shelf. The shelf board hangs on a loose, +spring-loaded fold-down bracket with a weak catch: it stays level as long as the moment of its load about the hinge at +the wall is below the bracket's preload; once the load exceeds it the catch slips and the board folds down to its stop +within about a second, and the jars on it slide off its free edge onto the table, where they lie on their sides. +Jars set down in the middle of the board's depth -- where a careful agent puts them -- push the moment over the preload +with the third jar: a median 0.4 s (90 % within 0.8 s) after that jar is down the board is past 8 deg, and the first +jar slides off a median 1.5 s (1-3 s) after it, while the arm lifts away. The same four jars standing near the wall +(centres up to ~6 cm from it) stay under the preload. Unloaded, the board springs back level. + +Family: long-horizon self-damage ("state_restoration"): a later stage (the third placement) undoes the earlier ones, a +moment after it was done, once the gripper has let go. Within an attempt the agent has to notice the fallen jars, stand +them up again (by their knobs) and put them back -- near the wall, or they slide off again; across attempts it has to +load the shelf near the wall. R4: "I put them down badly / dropped them too hard / my arm knocked them" vs "the shelf +gives way under a load far from the wall". + +v1 -> v2 (measured, scratchpad risk sweeps): v1 had a preloaded spring without a catch (preload 0.45-0.49 N m, 0.6 N m/rad, +damping 2.6-3.4, a slow first-order droop). Jars placed with their centres 6-7 cm from the wall overloaded it only with +the fourth jar, and the board drooped (or the jars slid off) only during the final settle, after `finish` -- 15 of 74 +failing scripted attempts (20 %) showed nothing before finish; 4 jars 6 cm from the wall failed in 9 / 9 seeds. v2 raises +the preload (4 jars up to ~6 cm from the wall hold) and adds the catch + a soft spring + light damping, so every overload +folds the board down within a second, before the agent's next look. + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a wall panel (2.5 cm thick, 34 cm + 4 cm long) along x on the robot's right or left (|y| of its face 25-27 cm, centre + x in [-0.17, -0.12]), rising 4.5 cm above the shelf board; + * the shelf board: 34 cm (along the wall) x 20 cm (deep) x 1.2 cm, light wood, top 11 cm above the table, hinged at + the wall face (axis along x at mid-thickness); hard stop at 25 deg of droop. The agentview camera (behind the table, + +x, looking at the robot) sees the board from its end, so the droop is an in-image rotation of the slab; + * four square jars (red, green, blue, yellow; body 5 x 5 x 6 cm, white lid, a 2.2 cm dark ball knob on a 1.2 cm stem; + 10.2 cm tall, 0.24-0.26 kg, centre of mass 2.6 cm up) standing in a row on the table on the other side (|y| 13-17 + cm), 9 cm apart, in random order. + +Hidden variable: the bracket. "loose" (14 of every 20 consecutive seeds): preload 0.62-0.68 N m; "stiff" (6 of 20): +preload 2.5 N m (no placement on the board reaches it). Both look identical. The preload is a spring (0.25 N m/rad +beyond the preload) plus a catch of 0.12 N m that fades out over the first 3 deg of droop; damping 0.45-0.60 N m s/rad. +As the board droops the jars' centres of mass (3.2 cm above the hinge axis) move outwards (+0.08 N m/rad per jar), so +with two or more jars on it nothing stops a board whose catch has slipped before its 25 deg stop. Jar-on-board friction +0.27-0.33 per jar (they slide at ~14.5 deg at 0.30 in MuJoCo's soft contacts). +Moments (jar weight 2.45 N x lever arm of its centre of mass): four jars against the wall (centres 3.5 cm from the +hinge) 0.34 N m; four at 6 cm 0.59 (holds); four at 7 cm 0.69 (over); in the middle of the depth (10.4 cm) one jar 0.25, +two 0.51 (holds), three 0.76 (over). + +Repair: fallen jars lie on the table in front of the board's free edge. Held by the knob (ball, torsional friction +0.0005, condim 4) a lying jar turns between the fingers and hangs straight down (like lh_bystander's bottle cap); the +instruction says so. Put back near the wall, the board stays level. + +Success (final-state judge after a settle of at least 15 s of simulated time with the arm holding still -- longer if +the board is still moving -- so that finishing right after the last placement does not beat the bracket): every jar +stands upright on the board (its bottom on the board's top, within its outline, axis within 10 deg of the board's +normal), not held; the board within 15 deg of level (a board that has folded down holds no standing jar anyway), +touched by nothing but the jars (closes "prop the board" loopholes), the gripper not touching a jar or the board, the +scene static. + +Per-step monitor (server log only; F1 gives the agent success / failure): stage achieved / lost (cause: slid_off, +robot, jar:, picked_up, other) / restored per jar; board sag_start (> 1.5 deg), sag (> 8 deg = trap_fired) and +sag_end, each with the time since the placement that pushed the moment over the preload and the moment itself; +jar_fell (with the time since its own placement and since the sag started). outcome() also reports what the agent's +last images showed at `finish` (board angle, jars already off the board). + +Protocol: cross (reset to the same instance before every attempt), k = 3. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +TZ = envs.TABLE_Z +G = 9.81 +DT = 0.05 # control period + +# ---------------------------------------------------------------- jars (square glass jars with a ball knob on the lid) +COLOURS = ["red", "green", "blue", "yellow"] +JARS = [f"jar_{c}_1" for c in COLOURS] +GLASS_RGBA = {"red": (0.78, 0.20, 0.16, 1.0), "green": (0.20, 0.58, 0.28, 1.0), "blue": (0.20, 0.38, 0.80, 1.0), + "yellow": (0.90, 0.72, 0.15, 1.0)} +LID_RGBA = (0.93, 0.93, 0.91, 1.0) +KNOB_RGBA = (0.22, 0.22, 0.24, 1.0) +JB = 0.025 # half width of the square body (5 x 5 cm) +BODY_H = 0.060 +LID_H, LID_B = 0.008, 0.026 # lid height, half width +NECK_R, NECK_H = 0.006, 0.012 +KNOB_R = 0.011 +JAR_H = BODY_H + LID_H + NECK_H + 2 * KNOB_R # 0.102 +KNOB_Z = BODY_H + LID_H + NECK_H + KNOB_R # knob centre above the jar's bottom (0.091) +JAR_COM = 0.026 # centre of mass above the bottom (a filled jar) +JAR_MASS = (0.24, 0.26) +JAR_MU = (0.27, 0.33) # jar body friction (per jar); the board's own is lower, so this one applies on the board +LID_MU = 0.8 +KNOB_MU_T = 0.0005 # torsional friction of the knob (condim 4): a jar held by its knob swings down and hangs straight +JAR_ROT_DAMP = 0.004 # free-joint angular damping (air drag; damps the swing of a jar hanging from its knob) + +# ---------------------------------------------------------------- shelf (fixture: wall panel + hinged board) +SHELF = "shelf_1" +SHELF_MODEL = "lff_lhs_shelf" +BOARD_L = 0.34 # along the wall (world x) +BOARD_D = 0.20 # depth, from the wall to the free edge +BOARD_T = 0.012 +BOARD_TOP = 0.110 # top surface above the table when level +PANEL_T = 0.025 +LIP = 0.045 # the wall rises this far above the board's top +BOARD_MASS = 0.30 +BOARD_MU = 0.10 # (max rule: the jars' 0.27-0.33 applies) +GAP = 0.004 # board edge to the wall face (the board's lower corner swings towards the wall when it droops) +WOOD = (0.72, 0.55, 0.36, 1.0) +WALL_RGBA = (0.86, 0.86, 0.84, 1.0) +DROOP_MAX = np.radians(25.0) # hard stop of the hinge (at 28 deg the free edge would touch the table) +K_SPRING = 0.25 # N m / rad: the bracket's spring beyond the preload (soft: once the catch slips the board folds down) +LATCH = 0.12 # N m: part of the preload held by the bracket's catch, released over the first LATCH_TH of droop +LATCH_TH = np.radians(3.0) +PRELOAD_LOOSE = (0.62, 0.68) # N m (spring + catch at level) +PRELOAD_STIFF = 2.5 +DAMPING = (0.45, 0.60) # N m s / rad +P_LOOSE = 0.70 # 14 of every 20 consecutive seeds +WALL_Y = (0.25, 0.27) # |y| of the wall face +SHELF_X = (-0.17, -0.12) # centre of the board along the wall +SLOT_U = (-0.12, -0.04, 0.04, 0.12) # slot positions along the board (scripted policies) +SUP_Y = (0.13, 0.17) # |y| of the supply row (other side of the table) +SUP_U = (-0.135, -0.045, 0.045, 0.135) + +# predicates / monitor +TILT_OK = np.radians(10.0) # jar axis vs the board's normal +BOARD_OK = np.radians(15.0) # final judge: the board within 15 deg of level (jars slide off at ~13-16 deg) +SAG0 = np.radians(1.5) # sag_start +SAG_END = np.radians(0.5) +SAG_DEG = np.radians(8.0) # trap fired +DEBOUNCE = 10 # control steps (0.5 s) +SETTLE_MIN, SETTLE_MAX = 300, 600 # final judge: 15-30 s of simulated time with the arm holding still + +# scripted motion +Z_CARRY = 0.25 # grasp point above the table while carrying a jar (its bottom then clears the board by ~5 cm) +R_MID = GAP + BOARD_D / 2 # 0.104: the middle of the board's depth (from the wall face) +R_BACK = JB + 0.010 # 0.035: a jar against the wall (1 cm gap) +NAIVE_BIAS = 0.010 # per instance: Sonnet aims at the middle +- 1 cm (towards the wall or the free edge) +NAIVE_RAND = 0.006 # per jar +NAIVE_V, NAIVE_V_DOWN, NAIVE_WAITS = 0.35, 0.15, 0.5 # pace: ~8 s of simulated time from one placement to the next +# (Sonnet, lh_nudge_row pilot np2: 3.2-8.3 s, median 5.1 s) + + +def jar_xml(name, rgba): + h = JAR_H / 2 + z0 = -h # bottom + m = 0.25 + parts = [("body", "box", (0, 0, z0 + BODY_H / 2), (JB, JB, BODY_H / 2), rgba, 'friction="0.3 0.005 0.0001"'), + ("lid", "box", (0, 0, z0 + BODY_H + LID_H / 2), (LID_B, LID_B, LID_H / 2), LID_RGBA, + f'friction="{LID_MU} 0.005 0.0001"'), + ("neck", "cylinder", (0, 0, z0 + BODY_H + LID_H + NECK_H / 2), (NECK_R, NECK_H / 2), KNOB_RGBA, + f'friction="{LID_MU} 0.005 0.0001"'), + ("knob", "sphere", (0, 0, z0 + KNOB_Z), (KNOB_R,), KNOB_RGBA, + f'friction="1 {KNOB_MU_T} 0.0001" condim="4" priority="2"')] + ixx = m * ((2 * JB) ** 2 + BODY_H ** 2) / 12 + izz = m * (2 * (2 * JB) ** 2) / 12 + s = [f' '] + for nm, typ, pos, size, c, extra in parts: + s.append(f' ') + s.append(f' ') + # a lighter label band on the body (visual only) + s.append(f' ') + return _wrap(name, "\n".join(s), h, JB * 1.42) + + +def shelf_xml(name): + """fixture frame: origin on the table top below the middle of the hinge line; local +y points from the wall towards + the board's free edge, local x along the wall. Wall panel (static) + board (child body on a hinge about -x at the + wall face, so a positive joint angle lowers the free edge). Wall and board do not collide with each other + (contype 2 / conaffinity 1); both collide with everything else.""" + zc = BOARD_TOP - BOARD_T / 2 # hinge axis height (board mid-thickness) + wall_h = BOARD_TOP + LIP + hw = (BOARD_L + 0.04) / 2 + wall = (f'type="box" pos="0 {-PANEL_T / 2:.5f} {wall_h / 2:.5f}" size="{hw:.5f} {PANEL_T / 2:.5f} {wall_h / 2:.5f}" ' + f'rgba="{_fmt(WALL_RGBA)}"') + g = [f'', + f''] + slab = (f'type="box" pos="0 {BOARD_D / 2 + GAP:.5f} 0" size="{BOARD_L / 2:.5f} {BOARD_D / 2:.5f} {BOARD_T / 2:.5f}" ' + f'rgba="{_fmt(WOOD)}"') + b = [f'', + # stiffness / springref / damping are set per instance (apply_instance) + f'', + f'', + f'', + # darker front edge strip and hinge barrel (visual) + f'', + f''] + nl = "\n " + return f""" + + + + {nl.join(g)} + + {nl.join(b)} + + + + + + + + +""" + + +def _wrap_h(a): + """wrap to [-pi/2, pi/2) (the gripper is symmetric under 180 deg)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +class DroopSkills(Skills): + """Skills that feed the task's per-step monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class ShelfDroop(LFFTask): + name = "lh_shelf_droop" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Restore", "Plan") + protocol = "cross" + max_attempts = 3 + # careful: ~10 commands per jar (40) + standing up and re-placing three fallen jars (~40) + looking / corrections + agent_max_steps = 120 + instruction = ("Put the four jars (red, green, blue, yellow) on the shelf. At the end all four must be standing " + "upright on the shelf board, and the gripper must be open and clear of the jars and the shelf. " + "(Each jar has a round knob on its lid; held by the knob, a jar hangs straight down.)") + instruction_indirect = ("Put the four little square jars with knobbed lids up on the wooden shelf by the wall. " + "When you are done, all of them have to stand upright on the shelf board, and the gripper " + "must be open and away from the jars and the shelf. (Held by its round knob, a jar hangs " + "straight down.)") + agent_object_names = ["jars (red, green, blue, yellow; each with a round knob on its lid -- held by the knob it " + "hangs straight down)", "wooden shelf board on the wall panel"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs = [] + for i, (c, j) in enumerate(zip(COLOURS, JARS)): + cat = register_generated(f"LffLhsJar{c.capitalize()}", jar_xml(f"lff_lhs_jar_{c}", GLASS_RGBA[c])) + objs.append((j, cat, f"jar{i}_region", (-0.30 + 0.12 * i, 0.30, -0.29 + 0.12 * i, 0.31))) + sh = register_generated("LffLhsShelf", shelf_xml(SHELF_MODEL), free=False) + fx = [(SHELF, sh, "shelf_region", (0.20, -0.31, 0.21, -0.30))] # moved in apply_instance + return write_bddl(self.name, "Put the four jars on the shelf", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.shelf_bid = m.body_name2id(self.env.fixtures_dict[SHELF].root_body) + self.jid = m.joint_name2id(f"{SHELF}_hinge") + self.qa, self.da = int(m.jnt_qposadr[self.jid]), int(m.jnt_dofadr[self.jid]) + self.board_bid = int(m.jnt_bodyid[self.jid]) + pre = f"{SHELF}_{SHELF_MODEL}" + self.board_gid = m.geom_name2id(pre + "_board") + self.wall_gid = m.geom_name2id(pre + "_wall") + self.jgeoms = {j: envs.obj_geom_ids(self.env, j) for j in JARS} + self.jbid = {j: int(m.geom_bodyid[self.jgeoms[j][0]]) for j in JARS} # body that carries the inertial + self.body_gid = {j: m.geom_name2id(f"{j}_lff_lhs_jar_{c}_body") for c, j in zip(COLOURS, JARS)} + self.knob_gid = {j: m.geom_name2id(f"{j}_lff_lhs_jar_{c}_knob") for c, j in zip(COLOURS, JARS)} + self.jdof = {j: envs.free_joint_addr(self.env, j)[1] for j in JARS} + # per-geom lookup tables for the substep contact check + self.owner = np.full(m.ngeom, -1, int) # jar index + for i, j in enumerate(JARS): + self.owner[self.jgeoms[j]] = i + self.is_robot = np.zeros(m.ngeom, bool) + self.is_robot[envs.robot_geom_ids(self.env)] = True + self.is_board = np.zeros(m.ngeom, bool) + self.is_board[self.board_gid] = True + self._sub_rob, self._sub_obj, self._sub_board = {}, {}, set() + sim = self.env.sim + if not getattr(sim, "_lhs_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lhs_task", None) + if t is not None: + t._bracket() + if t.mon is not None: + t._substep() + sim.step = step + sim._lhs_wrapped = True + sim._lhs_task = self + self.inst = None + self.mon = None + self.sk = None + + def _bracket(self): + """the bracket's catch (every MuJoCo substep): a torque holding the board up that fades out over the first + LATCH_TH of droop, so a board that starts to droop does not stop part-way but folds down to its stop""" + d = self.env.sim.data + th = float(d.qpos[self.qa]) + d.qfrc_applied[self.da] = -LATCH * float(np.clip(1.0 - th / LATCH_TH, 0.0, 1.0)) + + def _substep(self): + d = self.env.sim.data + n = d.ncon + if not n: + return + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + for a, b in zip(g1, g2): + pa, pb = self.owner[a], self.owner[b] + if self.is_board[a] or self.is_board[b]: + o = b if self.is_board[a] else a + if self.owner[o] < 0: # the board touched by something that is not a jar (robot, table, ...) + self._sub_board.add("robot" if self.is_robot[o] else (self.env.sim.model.geom_id2name(int(o)) or "?")) + continue + if pa < 0 and pb < 0: + continue + if pa >= 0 and pb >= 0: + if pa != pb: + self._sub_obj[int(pa)] = int(pb) + self._sub_obj[int(pb)] = int(pa) + continue + p, o = (pa, b) if pa >= 0 else (pb, a) + if self.is_robot[o]: + self._sub_rob[int(p)] = True + + # ------------------------------------------------------------ instances + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + loose = bool((int(seed) * 7) % 20 < round(20 * P_LOOSE)) # balanced: 14 of every 20 consecutive seeds + side = "right" if rng.random() < 0.5 else "left" # where the wall stands (robot's view) + s = -1.0 if side == "right" else 1.0 + x0 = float(rng.uniform(*SHELF_X)) + yw = float(rng.uniform(*WALL_Y)) + preload = float(rng.uniform(*PRELOAD_LOOSE)) if loose else PRELOAD_STIFF + damping = float(rng.uniform(*DAMPING)) + ys = -s * float(rng.uniform(*SUP_Y)) + order = rng.permutation(4) + start = {COLOURS[i]: [float(x0 + SUP_U[order[i]] + rng.uniform(-0.01, 0.01)), float(ys + rng.uniform(-0.008, 0.008))] + for i in range(4)} + yaw0 = {c: float(rng.uniform(-0.3, 0.3)) for c in COLOURS} + mu = {c: float(rng.uniform(*JAR_MU)) for c in COLOURS} + mass = {c: float(rng.uniform(*JAR_MASS)) for c in COLOURS} + return dict(seed=int(seed), loose=loose, bracket="loose" if loose else "stiff", side=side, shelf_x=x0, + wall_y=float(s * yw), preload=preload, damping=damping, stiffness=K_SPRING, start=start, yaw0=yaw0, + mu=mu, mass=mass, naive_bias=float(rng.uniform(-NAIVE_BIAS, NAIVE_BIAS))) + + def apply_instance(self, inst): + self.inst = inst + m, d = self.env.sim.model, self.env.sim.data + s = -1.0 if inst["side"] == "right" else 1.0 + # fixture local +y (towards the free edge) = world -s*y + m.body_pos[self.shelf_bid] = [inst["shelf_x"], inst["wall_y"], TZ] + m.body_quat[self.shelf_bid] = [1.0, 0.0, 0.0, 0.0] if s < 0 else [0.0, 0.0, 0.0, 1.0] + wb = BOARD_MASS * G * (BOARD_D / 2 + GAP) # the board's own weight about the hinge + m.jnt_stiffness[self.jid] = inst["stiffness"] + # spring + catch hold the board level up to a load moment of `preload` (the catch's part fades with the droop) + m.qpos_spring[self.qa] = -(inst["preload"] - LATCH + wb) / inst["stiffness"] + m.dof_damping[self.da] = inst["damping"] + d.qpos[self.qa] = 0.0 + d.qvel[self.da] = 0.0 + d.qfrc_applied[self.da] = -LATCH + for c, j in zip(COLOURS, JARS): + b = self.jbid[j] + M = inst["mass"][c] + m.body_mass[b] = M + m.body_inertia[b] = [M * ((2 * JB) ** 2 + BODY_H ** 2) / 12] * 2 + [M * (2 * JB) ** 2 / 6] + m.geom_friction[self.body_gid[j]] = [inst["mu"][c], 0.005, 0.0001] + m.dof_damping[self.jdof[j] + 3:self.jdof[j] + 6] = JAR_ROT_DAMP + self.env.sim.forward() + for c, j in zip(COLOURS, JARS): + envs.place_upright(self.env, j, inst["start"][c], yaw=inst["yaw0"][c], clearance=0.0005) + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = DroopSkills(self.env, self, recorder=recorder) + self._sub_rob, self._sub_obj, self._sub_board = {}, {}, set() + n = len(JARS) + self.mon = dict(state=[False] * n, raw_since=[0] * n, ever=[False] * n, lost=[False] * n, lost_cause=[None] * n, + events=[], last_robot=[None] * n, last_obj=[None] * n, placed_step=[None] * n, + last_place=None, raw_prev=[False] * n, raw_on=[None] * n, in_sag=False, sag_start=None, sag_fired=False, sag_max=0.0, n_sag=0, + fell_in_sag=[], max_deg=0.0, board_touch=[], n_steps=0, finish_step=None) + return self.sk + + # ------------------------------------------------------------ geometry / predicates + def angle(self): + return float(self.env.sim.data.qpos[self.qa]) + + def board_frame(self): + d = self.env.sim.data + return d.xpos[self.board_bid].copy(), d.xmat[self.board_bid].reshape(3, 3).copy() + + def to_board(self, p): + o, R = self.board_frame() + return R.T @ (np.asarray(p, float) - o) + + def board_point(self, u, r, h=BOARD_T / 2): + """world point at (u along the wall, r from the hinge across the board, h above the hinge axis) in the board + frame""" + o, R = self.board_frame() + return o + R @ np.array([u, r, h]) + + def level_point(self, u, r): + """world xy of board coordinates (u, r) with the board level (planning)""" + s = -1.0 if self.inst["side"] == "right" else 1.0 + return np.array([self.inst["shelf_x"] - s * u, self.inst["wall_y"] - s * r]) + + def board_top_z(self): + return TZ + BOARD_TOP + + def jar_axis(self, j): + return self.env.sim.data.xmat[self.jbid[j]].reshape(3, 3)[:, 2].copy() + + def jar_bottom(self, j): + return envs.obj_pos(self.env, j) - self.jar_axis(j) * JAR_H / 2 + + def knob_xyz(self, j): + return self.env.sim.data.geom_xpos[self.knob_gid[j]].copy() + + def tilt(self, j): + return float(np.arccos(np.clip(self.jar_axis(j)[2], -1.0, 1.0))) + + def held(self, j): + return self.sk is not None and self.sk.holding(j) + + def on_board(self, i, extra=0.0): + """jar i stands on the shelf board: its bottom (centre) on the board's top, within the board's outline, its + axis within 10 deg of the board's normal, not held""" + j = JARS[i] + o, R = self.board_frame() + ax = R.T @ self.jar_axis(j) + if ax[2] < np.cos(TILT_OK + extra * 5): + return False + bc = R.T @ (self.jar_bottom(j) - o) + if not (BOARD_T / 2 - 0.004 <= bc[2] <= BOARD_T / 2 + 0.005 + extra): + return False + if abs(bc[0]) > BOARD_L / 2 + extra or not (GAP - extra <= bc[1] <= GAP + BOARD_D + extra): + return False + return not self.held(j) + + def stages(self): + return [self.on_board(i) for i in range(len(JARS))] + + def lever(self, j): + """horizontal distance (m) of the jar's centre of mass from the hinge line, towards the free edge""" + o, R = self.board_frame() + n = R[:, 1].copy() + n[2] = 0.0 + n /= max(np.linalg.norm(n), 1e-9) + return float((self.env.sim.data.xipos[self.jbid[j]] - o) @ n) + + def moment(self, only_state=True): + """load moment (N m) of the jars standing on the board about the hinge""" + mon = self.mon + tot = 0.0 + for i, j in enumerate(JARS): + on = mon["state"][i] if (only_state and mon is not None) else self.on_board(i) + if on: + tot += self.inst["mass"][COLOURS[i]] * G * self.lever(j) + return float(tot) + + def r_cm(self, i): + """distance of jar i's bottom centre from the wall face (cm), in the board frame""" + return 100 * float(self.to_board(self.jar_bottom(JARS[i]))[1]) + + # ------------------------------------------------------------ monitor + def _t(self): + return int(self.sk.n_steps) if self.sk is not None else 0 + + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + mon["n_steps"] += 1 + t = self._t() + rob, obj, brd = dict(self._sub_rob), dict(self._sub_obj), set(self._sub_board) + self._sub_rob, self._sub_obj, self._sub_board = {}, {}, set() + for i in rob: + if not self.held(JARS[i]): + mon["last_robot"][i] = int(t) + for i, k in obj.items(): + mon["last_obj"][i] = [COLOURS[k], int(t)] + for b in brd: + if b not in mon["board_touch"]: + mon["board_touch"].append(b) + mon["_board_touch_now"] = sorted(brd) + th = self.angle() + mon["max_deg"] = max(mon["max_deg"], float(np.degrees(th))) + if th > np.radians(5.0): + mon["droop_t"] = int(t) # last step with the board drooped > 5 deg (it springs back once the jars are off) + self._sag(th, t) + if mon["n_steps"] % 2: + return + for i in range(len(JARS)): + raw = self.on_board(i, 0.002 if mon["state"][i] else 0.0) + if raw and not mon["raw_prev"][i]: + mon["raw_on"][i] = int(t) # set down on the board (raw; the stage event below is debounced) + mon["raw_prev"][i] = raw + if raw == mon["state"][i]: + mon["raw_since"][i] = 0 + continue + mon["raw_since"][i] += 2 + if mon["raw_since"][i] < DEBOUNCE: + continue + mon["state"][i] = raw + mon["raw_since"][i] = 0 + t0 = int(t - DEBOUNCE + 1) + c = COLOURS[i] + if raw: + restored = mon["lost"][i] + e = dict(stage=c, event="restored" if restored else "achieved", step=t0, + r_cm=round(self.r_cm(i), 1), moment_Nm=round(self.moment(), 3)) + if restored: + e["after"] = mon["lost_cause"][i] + mon["events"].append(e) + mon["ever"][i] = True + mon["placed_step"][i] = t0 + mon["last_place"] = (c, t0) + else: + mon["lost"][i] = True + cause = self._cause(i, t) + mon["lost_cause"][i] = cause + e = dict(stage=c, event="lost", step=t0, cause=cause, board_deg=round(float(np.degrees(th)), 1)) + mon["events"].append(e) + if cause == "slid_off": + ps = mon["placed_step"][i] + ss = mon["sag_start"]["step"] if mon["sag_start"] else None + sc = mon.get("sag_cause") + mon["events"].append(dict(jar=c, event="jar_fell", step=t0, + dt_since_placed_s=None if ps is None else round((t0 - ps) * DT, 2), + dt_since_sag_start_s=None if ss is None else round((t0 - ss) * DT, 2), + after_placing=None if sc is None else sc[0], + dt_since_cause_s=None if sc is None else round((t0 - sc[1]) * DT, 2), + in_final_settle=mon["finish_step"] is not None, + board_deg=round(float(np.degrees(th)), 1))) + mon["fell_in_sag"].append(c) + + def _sag(self, th, t): + mon = self.mon + if not mon["in_sag"]: + if th > SAG0: + mon["in_sag"] = True + mon["sag_fired"] = False + mon["sag_max"] = th + mon["fell_in_sag"] = [] + lp = self._last_set_down(t) + mon["sag_cause"] = lp + e = dict(event="sag_start", step=int(t), board_deg=round(float(np.degrees(th)), 2), + moment_Nm=round(self.moment(only_state=False), 3), + preload_Nm=round(float(self.inst["preload"]), 3), + after_placing=None if lp is None else lp[0], + dt_since_placement_s=None if lp is None else round((t - lp[1]) * DT, 2), + n_on_board=int(sum(self.on_board(i) for i in range(len(JARS))))) + mon["sag_start"] = e + mon["events"].append(e) + return + mon["sag_max"] = max(mon["sag_max"], th) + if not mon["sag_fired"] and th > SAG_DEG: + mon["sag_fired"] = True + mon["n_sag"] += 1 + ss = mon["sag_start"] + lp = self._last_set_down(t) # the placement that drove the board past 8 deg (sag_start may be earlier: + mon["sag_cause"] = lp # two jars in the middle already make it creep a few degrees) + mon["events"].append(dict(event="sag", step=int(t), board_deg=round(float(np.degrees(th)), 2), + moment_Nm=round(self.moment(only_state=False), 3), + after_placing=None if lp is None else lp[0], + sag_start_after=ss["after_placing"], + dt_since_placement_s=None if lp is None else round((t - lp[1]) * DT, 2), + dt_since_sag_start_s=round((t - ss["step"]) * DT, 2), + in_final_settle=mon["finish_step"] is not None)) + mon["below"] = mon.get("below", 0) + 1 if th < SAG_END else 0 + if mon["below"] >= 2 * DEBOUNCE: # back level for 1 s (the jars that slid off have been registered) + mon["in_sag"] = False + mon["below"] = 0 + mon["events"].append(dict(event="sag_end", step=int(t), max_deg=round(float(np.degrees(mon["sag_max"])), 1), + fell=list(mon["fell_in_sag"]), + duration_s=round((t - mon["sag_start"]["step"]) * DT, 2))) + + def _last_set_down(self, t): + """(colour, step) of the jar most recently set down on the board (raw predicate) that still stands on it""" + mon = self.mon + cands = [(mon["raw_on"][i], COLOURS[i]) for i in range(len(JARS)) + if mon["raw_on"][i] is not None and mon["raw_prev"][i] and mon["raw_on"][i] <= t] + if not cands: + return None + st, c = max(cands) + return (c, st) + + def _cause(self, i, t, window=60): + mon = self.mon + if self.held(JARS[i]): + return "picked_up" + if (mon["in_sag"] and mon["sag_max"] > np.radians(5.0)) or (mon.get("droop_t") is not None + and t - mon["droop_t"] <= window): + return "slid_off" + lr, lo = mon["last_robot"][i], mon["last_obj"][i] + if lr is not None and t - lr <= window: + return "robot" + if lo is not None and t - lo[1] <= window: + return "jar:" + lo[0] + return "other" + + def _finalize_monitor(self, raw): + mon = self.mon + t = self._t() + for i in range(len(JARS)): + if raw[i] == mon["state"][i]: + continue + mon["state"][i] = raw[i] + c = COLOURS[i] + if raw[i]: + restored = mon["lost"][i] + e = dict(stage=c, event="restored" if restored else "achieved", step=t, final=True) + if restored: + e["after"] = mon["lost_cause"][i] + mon["events"].append(e) + mon["ever"][i] = True + else: + mon["lost"][i] = True + cause = self._cause(i, t, window=10 ** 6) + mon["lost_cause"][i] = cause + mon["events"].append(dict(stage=c, event="lost", step=t, cause=cause, final=True)) + + # ------------------------------------------------------------ outcome + def _touching(self): + d = self.env.sim.data + jar_touch, board_touch = False, False + for k in range(d.ncon): + c = d.contact[k] + a, b = c.geom1, c.geom2 + if (self.is_robot[a] and self.owner[b] >= 0) or (self.is_robot[b] and self.owner[a] >= 0): + jar_touch = True + if (self.is_robot[a] and self.is_board[b]) or (self.is_robot[b] and self.is_board[a]): + board_touch = True + return jar_touch, board_touch + + def _moving(self): + d = self.env.sim.data + if abs(float(d.qvel[self.da])) > np.radians(0.3): + return True + for j in JARS: + da = self.jdof[j] + if np.linalg.norm(d.qvel[da:da + 3]) > 0.01 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.3: + return True + return False + + def outcome(self, inst): + sk = self.sk + mon = self.mon + mon["finish_step"] = self._t() + # what the agent's last images show (finish returns no image): board angle and the jars already off the board + th_fin = self.angle() + off_fin = [COLOURS[i] for i in range(4) if mon["ever"][i] and not self.on_board(i) and not self.held(JARS[i])] + max_fin = float(mon["max_deg"]) + # settle with the arm holding still: >= 15 s of simulated time, up to 30 s while the board or a jar still moves + # (the droop is slow: finishing right after the last placement must not beat it) + n = 0 + while n < SETTLE_MAX: + sk.hold(10) + n += 10 + if n >= SETTLE_MIN and not self._moving() and not mon["in_sag"]: + break + settle_s = n * DT + p0 = {j: envs.obj_pos(self.env, j) for j in JARS} + th0 = self.angle() + jar_touch = board_touch = False + board_other = set() + for _ in range(20): + sk.hold(1) + jt, bt = self._touching() + jar_touch, board_touch = jar_touch or jt, board_touch or bt + board_other |= {b for b in mon.get("_board_touch_now", []) if b != "robot"} + moved = max(float(np.linalg.norm(envs.obj_pos(self.env, j) - p0[j])) for j in JARS) + static = moved < 0.003 and abs(self.angle() - th0) < np.radians(0.3) + raw = self.stages() + self._finalize_monitor(raw) + th = self.angle() + held = [COLOURS[i] for i, j in enumerate(JARS) if self.held(j)] + level = th <= BOARD_OK + propped = sorted(board_other) + success = bool(all(raw) and level and static and not held and not jar_touch and not board_touch and not propped) + ev = list(mon["events"]) + n_reg = sum(e.get("event") == "lost" and e.get("cause") != "picked_up" for e in ev) + n_lost = sum(e.get("event") == "lost" for e in ev) + n_res = sum(e.get("event") == "restored" and e.get("after") != "picked_up" for e in ev) + fell = [e for e in ev if e.get("event") == "jar_fell"] + sags = [e for e in ev if e.get("event") == "sag"] + sag_vis = [e for e in sags if not e.get("in_final_settle")] + starts = [e for e in ev if e.get("event") == "sag_start"] + ever = mon["ever"] + lost_final = [i for i in range(4) if not raw[i] and ever[i]] + never = [i for i in range(4) if not raw[i] and not ever[i]] + if success: + failure = "none" + elif held: + failure = "held" + elif propped or board_touch: + failure = "propped" + elif jar_touch: + failure = "touching" + elif lost_final: + causes = {mon["lost_cause"][i] for i in lost_final} + failure = ("slid_off" if "slid_off" in causes else "knocked_off" if "robot" in causes else "regressed") + elif never: + failure = "not_on_shelf" + elif not level: + failure = "board_drooped" + else: + failure = "not_static" + # ---- F2 text + parts = [] + if success: + parts.append("All four jars stand upright on the shelf board.") + for i in range(4): + if raw[i]: + continue + c, j = COLOURS[i], JARS[i] + if c in held: + parts.append(f"The {c} jar is still held by the gripper.") + continue + pb = self.to_board(self.jar_bottom(j)) + lying = self.tilt(j) > np.radians(45) + if pb[2] < -0.02: # below the board: on the table + where = "lies on its side on the table" if lying else "stands on the table" + dist = 100 * float(pb[1] - (GAP + BOARD_D)) + txt = f"The {c} jar {where}" + (f", {dist:.0f} cm out from the shelf's front edge." if dist > 0 + else ", under the shelf.") + elif lying: + txt = f"The {c} jar lies on its side on the shelf board." + else: + txt = f"The {c} jar is not standing on the shelf board." + if ever[i]: + why = mon["lost_cause"][i] + txt += {"slid_off": " It had stood on the shelf; it slid off when the shelf board drooped under the load.", + "robot": " It had stood on the shelf; the robot knocked it off.", + }.get(why, " It had stood on the shelf earlier.") + parts.append(txt) + if all(raw) and not success: + if not level: + parts.append(f"The shelf board droops by {np.degrees(th):.0f} degrees.") + if held: + pass + elif jar_touch or board_touch: + parts.append("The gripper is still touching " + ("a jar." if jar_touch else "the shelf board.")) + elif propped: + parts.append("The shelf board rests on something below it.") + elif not static: + parts.append("Something was still moving.") + if sags: + parts.append(f"During the attempt the shelf board drooped {len(sags)} time(s) (down to {mon['max_deg']:.0f} " + f"degrees) and {len(fell)} time(s) a jar slid off; {n_res} time(s) a jar was put back.") + trap = bool(sags) + lp = lambda e: e.get("dt_since_placement_s") # noqa: E731 + return dict(success=success, stages={COLOURS[i]: bool(raw[i]) for i in range(4)}, events=ev, + n_regressions=int(n_reg), n_lost=int(n_lost), n_restored=int(n_res), n_fell=len(fell), + n_sag=len(sags), trap_fired=trap, sag_visible=bool(sag_vis), + recovered_in_attempt=bool(trap and success), + first_sag_dt_s=lp(sags[0]) if sags else None, + first_sag_start_dt_s=lp(starts[0]) if starts else None, + first_sag_after=sags[0].get("after_placing") if sags else None, + first_fall_dt_s=fell[0].get("dt_since_cause_s") if fell else None, + fell_before_finish=bool([e for e in fell if not e.get("in_final_settle")]), + board_deg_at_finish=round(float(np.degrees(th_fin)), 1), off_at_finish=off_fin, + max_droop_before_finish_deg=round(max_fin, 1), + visible_before_finish=bool(sag_vis or off_fin or max_fin > np.degrees(SAG_DEG)), + fell_jars=sorted({e["jar"] for e in fell}), failure=failure, held=held, touching=bool(jar_touch), + board_touched=bool(board_touch), propped=propped, static=bool(static), + board_deg=round(float(np.degrees(th)), 2), max_droop_deg=round(mon["max_deg"], 1), + r_cm={COLOURS[i]: round(self.r_cm(i), 1) for i in range(4)}, + moment_Nm=round(self.moment(only_state=False), 3), preload_Nm=round(float(inst["preload"]), 3), + loose=bool(inst["loose"]), settle_s=settle_s, finish_step=mon["finish_step"], + detail=" ".join(parts)) + + # ------------------------------------------------------------ scripted primitives (move_to + gripper only) + def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300): + return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + + def _lift_to(self, z, speed=0.15): + cur = self.sk.eef_pos() + if cur[2] < TZ + z - 0.005: + self._go([cur[0], cur[1], TZ + z], speed=speed) + + def _settle_jar(self, j, max_checks=30): + d = self.env.sim.data + da = self.jdof[j] + for _ in range(max_checks): + if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2: + return + self.sk.hold(2) + + def wait_board(self, max_steps=200): + """wait (arm still) until the board stops moving""" + for _ in range(max_steps // 5): + if abs(float(self.env.sim.data.qvel[self.da])) < np.radians(0.3) and not self.mon["in_sag"]: + return + self.sk.hold(5) + + def lying(self, j): + return self.tilt(j) > np.radians(45) + + def pick(self, j, z_carry=Z_CARRY, yaw=0.0, v=0.2, err=None, tries=2, v_down=0.10, waits=1.0): + """grasp the jar by its knob and lift it to carry height. Standing jar: from above, wrist yaw `yaw`. Lying jar: + fingers across its axis; lifted, it turns between the fingers and hangs straight down.""" + sk = self.sk + for _ in range(tries): + self._settle_jar(j) + lying = self.lying(j) + k = self.knob_xyz(j) + if lying: + ax = self.jar_axis(j)[:2] + gy = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else sk.yaw + else: + gy = yaw + q = k[:2] + (np.asarray(err, float) if err is not None else 0.0) + sk.set_gripper(False, steps=8) + cur = sk.eef_pos() + self._go([cur[0], cur[1], max(cur[2], TZ + min(z_carry, 0.22))], speed=0.15) + self._go([q[0], q[1], max(k[2] + 0.06, TZ + min(z_carry, 0.22))], yaw=gy, speed=v) + sk.hold(max(1, int(4 * waits))) + k = self.knob_xyz(j) + q = k[:2] + (np.asarray(err, float) if err is not None else 0.0) + self._go([q[0], q[1], k[2] + 0.015], speed=v_down) + self._go([q[0], q[1], k[2]], speed=0.04, tol=0.003, max_steps=150) + sk.set_gripper(True, steps=15) + if lying: # lift slowly until it hangs free, let the swing die down + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + KNOB_Z + 0.04], speed=0.08) + sk.hold(20) + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + z_carry], speed=max(0.12, v_down)) + sk.hold(max(1, int(5 * waits))) + if self.held(j): + return True + sk.set_gripper(False, steps=8) + cur = sk.eef_pos() + self._go([cur[0], cur[1], cur[2] + 0.05], speed=0.1) + return False + + def put(self, j, u, r, z_carry=Z_CARRY, h_rel=0.010, v=0.2, yaw=0.0, v_down=0.10, waits=1.0): + """carry the held jar over board point (u, r) (planned with the board level), straight down until its bottom is + h_rel above the board top, let go, lift back to carry height""" + sk = self.sk + xy = self.level_point(u, r) + rel = self.jar_bottom(j)[:2] - sk.eef_pos()[:2] + q = xy - rel + cur = sk.eef_pos() + self._go([q[0], q[1], max(cur[2], TZ + z_carry)], yaw=yaw, speed=v) + sk.hold(max(1, int(12 * waits))) # let the hanging jar stop swinging + rel = self.jar_bottom(j)[:2] - sk.eef_pos()[:2] + q = xy - rel + dz = sk.eef_pos()[2] - envs.obj_min_z(self.env, j) + zr = self.board_top_z() + dz + h_rel + self._go([q[0], q[1], zr + 0.02], speed=v_down) + self._go([q[0], q[1], zr], speed=0.03, tol=0.003, max_steps=150) + sk.set_gripper(False, steps=12) + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + z_carry], speed=max(0.15, v_down)) + sk.hold(3) + + def place(self, i, u, r, p, rng, rand=0.0): + """one stage: pick jar i from wherever it is and put it on the board at (u, r) +- rand""" + j = JARS[i] + e = rng.uniform(-rand, rand, 2) if rand else np.zeros(2) + gerr = rng.uniform(-0.002, 0.002, 2) if rand else None + kw = dict(z_carry=p.get("z_carry", Z_CARRY), v=p.get("v", 0.2), v_down=p.get("v_down", 0.10), + waits=p.get("waits", 1.0)) + if not self.pick(j, err=gerr, **kw): + return False + self.put(j, u + e[0], r + e[1], h_rel=p.get("h_rel", 0.010), **kw) + self._settle_jar(j) + return True + + def supply_order(self): + """jar indices by their supply position: the one whose slot is farthest from the robot first (Sonnet fills a + row from the far end)""" + return sorted(range(4), key=lambda i: -self.inst["start"][COLOURS[i]][0]) + + def slot_u(self, k): + """board u of slot k (k = 0 farthest from the robot)""" + s = -1.0 if self.inst["side"] == "right" else 1.0 + # u runs along local x = -s * world x -> farthest (largest world x) first + return -s * SLOT_U[3 - k] + + def fallen(self): + return [i for i in range(4) if self.mon["ever"][i] and not self.on_board(i) and not self.held(JARS[i])] + + def repair(self, r_target, rng, p, rand=0.0, used=None): + """move every jar on the board to depth r_target (same slot), then stand up the fallen ones and put them into the + free slots at r_target""" + sk = self.sk + self.wait_board() + slots = dict(used or {}) + for i in range(4): + if self.on_board(i) and abs(self.r_cm(i) / 100 - r_target) > 0.02: + self.place(i, slots.get(i, self.slot_u(0)), r_target, p, rng, rand) + self.wait_board() + for i in self.fallen(): + free = [k for k in range(4) if self.slot_u(k) not in slots.values()] or [0] + u = slots.get(i, self.slot_u(free[0])) + slots[i] = u + self.place(i, u, r_target, p, rng, rand) + self.wait_board() + sk.hold(5) + return slots + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("noise_seed", 0)) + r = float(params["r"]) + rand = float(params.get("rand", 0.0)) + order = params.get("order") or self.supply_order() + used = {} + mode_back = False + for k, i in enumerate(order): + u = self.slot_u(k) + used[i] = u + rr = R_BACK + params.get("back_off", 0.0) if mode_back else r + self.place(i, u, rr, params, rng, rand) + # looks at the jar it just placed (Sonnet): re-places it if it is not standing on the board + if not self.on_board(i) and params.get("self_check", True): + self.place(i, u, rr, params, rng, rand) + if params.get("look_back") and (self.fallen() or self.angle() > np.radians(3.0)): + # the shelf sags / jars fell: from now on load it near the wall, and move what is on it there too + mode_back = True + used = self.repair(R_BACK + params.get("back_off", 0.0), rng, params, rand, used) + if params.get("final_check"): + for _ in range(2): + if all(self.stages()): + break + rr = R_BACK + params.get("back_off", 0.0) if (mode_back or params.get("look_back")) else r + used = self.repair(rr, rng, params, rand, used) + if not params.get("fast_finish"): + self._lift_to(Z_CARRY) + self.sk.hold(5) + + # naive = Sonnet-like (DESIGN_INSIGHTS §3; lh_nudge_row / lh_bystander pilots): careful top-down pick and place, jars + # set down in the visual middle of the shelf's depth, released ~1-4 cm above, wrist yaw 0, looks at the jar it just + # placed, no look back at the others before finishing + def default_params(self, inst): + sd = int(inst["seed"]) + return dict(r=R_MID + float(inst["naive_bias"]), rand=NAIVE_RAND, noise_seed=sd * 13, + h_rel=0.010 + 0.030 * ((sd * 7) % 11) / 10, z_carry=Z_CARRY, look_back=False, final_check=False, + v=NAIVE_V, v_down=NAIVE_V_DOWN, waits=NAIVE_WAITS) + + def oracle_params(self, inst): + return dict(r=R_BACK, rand=0.0, h_rel=0.005, z_carry=Z_CARRY, look_back=True, final_check=True) + + def adapt_params(self, inst, history): + """from attempt 2: load the shelf near the wall (same imprecision), look back after every jar and at the end""" + return dict(self.default_params(inst), r=R_BACK + 0.008, look_back=True, final_check=True) + + def blind_params(self, inst, attempt, rng): + """the naive behaviour with random variation (depth on the board, order, heights), no history, no look back""" + order = [int(x) for x in rng.permutation(4)] + return dict(self.default_params(inst), noise_seed=int(rng.integers(1 << 30)), r=float(rng.uniform(0.06, 0.15)), + order=order, z_carry=float(rng.uniform(0.24, 0.28)), h_rel=float(rng.uniform(0.005, 0.04)), + v=float(rng.uniform(0.12, 0.3))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + single = ("oracle", "naive", "oracle_noise", "naive_front", "naive_back", "naive_check_mid", "naive_fast") + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": # attempt 1: naive + looks back after every jar; repairs near the wall + params = (dict(self.default_params(inst), look_back=True, final_check=True, back_off=0.008) if a == 0 + else self.adapt_params(inst, history)) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": # control: cross-attempt learning only (near the wall from attempt 2), no repair + params = (self.default_params(inst) if a == 0 else + dict(self.default_params(inst), r=R_BACK + 0.008)) + elif kind == "oracle_noise": + params = dict(self.oracle_params(inst), rand=0.005, noise_seed=int(seed) * 7 + a) + elif kind == "naive_front": # control: naive, but jars set down near the free edge + params = dict(self.default_params(inst), r=GAP + BOARD_D - JB - 0.015) + elif kind == "naive_back": # control: naive pace and imprecision, jars against the wall -> no droop + params = dict(self.default_params(inst), r=R_BACK + 0.008) + elif kind == "naive_check_mid": # control: looks back and repairs, but puts the jars back in the middle + params = dict(self.default_params(inst), final_check=True) + elif kind == "naive_fast": # control: naive at the fastest pace, finishing right after the last jar + params = dict(self.default_params(inst), v=0.6, v_down=0.3, waits=0.1, h_rel=0.03, fast_finish=True) + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in single: + break + return history diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_tidy_stack.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_tidy_stack.py new file mode 100644 index 0000000000000000000000000000000000000000..7eb80b6f3a418bf965b10bad15f99797241128a5 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_tidy_stack.py @@ -0,0 +1,1260 @@ +"""LH lh_tidy_stack v2 (2026-10-16): tidy the table -- stack the four storage boxes (red, green, blue, yellow; alike, +6 x 6 x 5 cm) into one pile on a grey mat, in any order, then stand the cup on top. In 18 of every 20 instances one box +(random colour) is an empty, soft carton: it carries one thing, but as soon as a second thing comes to rest above it, +it gives way -- standing it folds sideways, lying on a side face it is crushed flat -- and everything above it slides +off the pile: the stage that made the pile two higher destroys the stage before it. + +Family: long-horizon self-disturbance ("state_restoration"): the later stages' ordinary action (putting the next box on) +undoes earlier ones; the agent has to see which box gave way, take it out of the pile and rebuild with it on top (within +an attempt) or remember its colour (across attempts). The cheapest explanation of a toppled pile ("I did not centre the +box", "I let go too high") is wrong: perfectly centred boxes let go 5 mm above the pile topple it just the same +(control naive_centred). + +v1 -> v2 (Sonnet 5.5 pilot np3_lh_tidy_stack, seeds 3000 / 3002 / 3003, k=3; logs measured by the coordinator and +replayed here): in s3002 attempt 2 boxes that had fallen on their sides were restacked lying (a lying box looks the +same: they are nearly cubes); the soft box lay on its side at level 2 under two boxes and the cup, and the v1 law, which +measured the load along the box axis only, saw -0.06 N and never fired -> judged a success. Sonnet also presses what it +puts down 0.5-1.5 cm below contact (its own logs: the gripper stops 0.6-1.5 cm above the commanded release height), and +in s3003 a cup pressed onto the soft box on top -- where it belongs -- crushed it under one item (v1: 2.45 N). v2: + (1) the load is measured along the world vertical, whichever face the carton rests on (`vertical_loads`: the downward + push on its upper side, limited by the support under it); + (2) a carton lying on a side face (seam vertical) cannot fold under gravity, so it is crushed instead: both halves + flatten towards the face they rest on, the upper half by 70 % and the lower by 30 % (runtime geom sizes + + envs.refit_bounds), the top becomes a 2-3 cm step and what is on it tips off; + (3) only what rests on the carton counts, at most with its own weight (+0.3 N for impacts): something the robot still + holds, the robot pushing down through an item it has just let go of, and the fingers pressing the held carton + itself onto something do not count; the robot's own fingers / hand pushing on its top do (a hard press may crush + it: the closed gripper 3 mm onto its top does; logged as cause "press", not counted as the trap unless it costs a + stage); + (4) items weigh 200 g (box and cup; v1 180 / 160 g) and f_crit = 3.45 N: one item 1.96 N, two 3.92 N; + (5) the rigid boxes' joints are stiffer (20 Nm/rad, stiff limit; at 3 Nm/rad Sonnet's cup press on a 4-high pile bent + every box ~4 deg and the pile leaned 10 deg in the replay); after a fold the carton straightens along a rest + shape that moves back to straight over 1.5 s (released at once, a stiff spring flipped it onto its side); + (6) stacking tolerance 3 cm instead of 2.5 (a correctly stacked oracle_noise pile failed at 2.51 cm). +v1 code and results: scratchpad lh_tidy_stack_v1.py, results/_old/lh_tidy_stack_v1/. + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a grey mat (13 x 13 cm, visual only), centre x in [-0.11, -0.05], |y| <= 5 cm; + * four storage boxes (6 x 6 x 5 cm, bright red / green / blue / yellow with a darker lid line, 200 g; friction 0.5) + 15, 18.5, 22 and 25.5 cm (+-1 cm) from the mat centre, at random angles 30-150 deg from forward on its left and right, + yaw +-17 deg, colours shuffled; + * a dark teal cup (5 cm wide, 7 cm tall, 200 g) on the robot's side of the mat, 23-26 cm away. + +Hidden variable: which box is the soft carton (60 g; mass is not observable). Instances come in balanced blocks of 20 +consecutive seeds ((seed x 7) mod 20 = k): k >= 18 benign (no soft box); otherwise the soft box is the one at rank +k mod 4 of the distance to the mat (0 = nearest = the bottom of a nearest-first pile, 3 = the top): 5 / 5 / 4 / 4. +A nearest-first stacker therefore meets it below the top in 14 of 20 instances. + +Mechanism (physics; nothing is teleported). Every box is built alike: a lower half (the root body) and an upper half +joined by a ball joint at mid-height (the seam is invisible). In the three rigid boxes the joint is locked (range +0.003 rad, stiffness 3 Nm/rad). The soft carton follows a load law (`_law_step`, every MuJoCo substep): its compressive +load (above, low-passed with 0.4 s) is compared with f_crit (instance key "f_crit": the fragility knob). Below it the +joint keeps 3 Nm/rad (one box 1.3 cm off-centre tilts it < 1 deg: looks like the rigid boxes). Above it: + * standing or upside down (seam horizontal): the joint stiffness drops to 0.03 Nm/rad -- a column with m g h ~ 0.27 + Nm/rad on it is unstable, centred or not -- and its rest shape bends 12 deg towards a per-instance side: the upper + half folds sideways (38-54 deg measured, joint limit 54 deg) and what is on it slides off; + * lying on a side face (seam vertical): crushed as above within ~0.1 s. +Unloaded (< 0.5 N) for 0.3 s it recovers over ~1.5 s (still visibly bent / flattened in the images of the next one or +two commands). One item on it is carried (a box let go 4 cm above adds < 0.5 N to the filtered load), two are not. So +the pile survives only with the soft box on top (carrying just the cup): soft at level 1 -> it gives way when box 3 +lands (boxes 2 and 3 fall), level 2 -> when box 4 lands, level 3 -> when the cup lands (box 4 and the cup fall; standing, +the cup ends on its side, which a top-down gripper cannot undo, so that attempt cannot be repaired). Measured (v2, naive +without rebuilding, the 14 trap instances of seeds 1000-1019): standing 14/14 folded at exactly that stage, the soft +box stayed upright in the pile 14/14 (fold 37-55 deg), the cup fell 4/4 at level 3; lying (control naive_lying: the +soft box starts on a side face and is stacked lying) crushed at exactly that stage in every trap instance. + +Why not the linear spring of the brief (a ball joint with one fixed stiffness k): the load that k must carry (the cup) +and the load that must topple it (one more box) differ by a factor of ~2-3, and an inverted pendulum close to its +critical load amplifies placement offsets (tilt = W e / (k - m g h)); measured (results/lh_tidy_stack/linear.json, +instance key law="linear"): no k gives both a soft box that carries the cup on top without sagging and a pile that +topples however carefully it is centred (k <= 0.25 Nm/rad: the correct pile fails 5-10/10; k = 0.5: a centred +level-3 soft box carries box + cup, 2/2). A load threshold (walls that +hold until they buckle) keeps the soft box looking and behaving rigid until the second item, independent of centring. + +Success predicate (from the instruction): all four boxes in one chain -- the bottom one on the mat (lowest point <= 8 mm +above the table, centre within 3.5 cm of the mat centre in x and y: its footprint on the 13 cm mat), each next one +resting on the previous (its lowest point within 1 cm of the top of the box below, centres within 3 cm), every box +flat (some face within 10 deg of horizontal: a fallen box cannot be stood up again by a vertical gripper, so a box on +its side counts), not bent (kink <= 10 deg) and not crushed (<= 15 %) --; the cup upright (<= 10 deg) on the top box +(bottom within 1 cm, centre within 3 cm); nothing held, the gripper not touching anything, the scene static (< 3 mm +in 1 s). Tolerance: 3 cm = the box's half width, i.e. the upper box's centre of mass is over the lower box's top face +(physically resting on it; the static check rejects anything that does not stay). Sonnet's measured placement error is +0.4-1.3 cm, so two placements differ by up to 2.6 cm plus a few mm of landing drift (v2: the 2.5 cm of v1 failed one +correctly stacked oracle_noise pile, seed 1008, at 2.51 cm). + +Event monitor (server log only; F1 gives the agent only success / failure): stage predicates red / green / blue / +yellow (box in the pile) and cup (cup on a complete pile), debounced over 0.5 s: achieved / lost (cause buckle / robot +/ picked_up / other) / restored; `buckle` (= trap fired: load, the robot's share of it, fold or crush, lying, level, +items on it), `collapse` (a buckle that cost a stage). Outcome: success, failure (none / held / touching / collapsed / +regressed / not_stacked / cup_fallen / cup_not_on_top / not_static), trap_fired, recovered_in_attempt, n_buckles, +n_collapses, buckle_how, max_kink_deg, max_crush, detail (F2). The law's state rides along in task.mon["law"]; a +crushed carton's geom sizes are restored at every reset. + +Protocol: cross (reset to the same instance before every attempt), k = 3. +""" +import mujoco +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +TZ = envs.TABLE_Z +G = 9.81 +COLOURS = ["red", "green", "blue", "yellow"] +BOXES = [f"box_{c}_1" for c in COLOURS] +COL = dict(zip(BOXES, COLOURS)) +CUP, MAT = "cup_1", "mat_1" +RGBA = {"red": (0.80, 0.16, 0.13, 1.0), "green": (0.17, 0.58, 0.25, 1.0), "blue": (0.16, 0.34, 0.80, 1.0), + "yellow": (0.90, 0.74, 0.14, 1.0)} +CUP_RGBA = (0.10, 0.45, 0.50, 1.0) # dark teal ceramic, darker inside +CUP_INSIDE = (0.20, 0.20, 0.19, 1.0) +MAT_RGBA = (0.45, 0.45, 0.47, 1.0) + +# ---------------------------------------------------------------- boxes (all four built alike: base + upper part) +HX, HY, H = 0.030, 0.030, 0.050 # 6 x 6 x 5 cm (the gripper opens 7.9 cm) +HB = 0.025 # base part height = height of the seam (ball joint) above the bottom: mid-height, so the upper +# half can fold ~56 deg before its edge reaches the surface below +HU = H - HB +BOX_MASS = 0.20 # a filled storage box (v1: 0.18) +SOFT_MASS = 0.06 # the empty carton (mass is not observable by the agent) +BOX_MU = 0.5 +CONTACT = 'solimp="0.95 0.99 0.001" solref="0.01 1"' +# soft-carton law (see SoftLaw): stiff until the compressive load through its walls exceeds F_CRIT, then soft +K_HI = 3.0 # Nm/rad: the intact soft carton (one box 1.3 cm off-centre tilts it ~0.5 deg; a cup pressed onto it +# bends it ~4 deg) +K_RIGID = 20.0 # Nm/rad + a stiff joint limit: the rigid boxes (at 3 Nm/rad a cup pressed onto a 4-high pile bent every +# box 4 deg and the pile leaned 10 deg -- replay of pilot s3003 on v2; at 20 for the soft carton too +# its folds flipped it onto its side 4/14 times) +K_LO = 0.03 # Nm/rad: buckled (one box on it destabilises it: m g h ~ 0.12 Nm/rad) +DAMP = 0.01 +F_CRIT = 3.45 # N, vertical load from above (resting things + whatever the robot pushes or holds onto it): one +# item weighs 1.96 N and a held item pressed onto the carton adds <= ~0.9 N before it slips in the +# fingers (measured, t10_press); two items weigh 3.92 N (v1: 2.45 N with 1.77 / 1.57 N items) +F_REL = 0.5 # N: unloaded below this ... +REL_T = 0.3 # ... for this long -> it springs back +TAU_F = 0.4 # s: low-pass of the load (impacts of a box let go 1-4 cm above do not count) +K_RISE = 1.5 # s: the folded carton straightens along a reference that moves back to straight in this time +BEND_REF = np.radians(12.0) # reference bend of the buckled carton (the weak side; direction per instance) +RANGE_SOFT, RANGE_RIGID = 0.95, 0.003 # rad: kink limit (54 deg) of the soft carton; the rigid boxes are locked +# v2: a carton lying on a side face (its seam vertical) cannot fold under gravity; it is crushed instead: both halves +# flatten towards the surface below, the upper half much more, so the top becomes a 2-3 cm step and what is on it +# tips off (geom sizes changed at runtime + envs.refit_bounds) +CRUSH_ALPHA = (0.30, 0.70) # fraction of the height lost by the base half / the upper half when fully crushed +CRUSH_TAU = (0.08, 0.7) # s: crushing / recovering +FOLD_MIN_UP = 0.7 # |seam normal . vertical| above this: the fold (upright or upside down); below: the crush + +# ---------------------------------------------------------------- cup +CUP_R, CUP_H, CUP_MASS = 0.025, 0.070, 0.20 # v1: 0.16 + +# ---------------------------------------------------------------- mat and layout +MAT_HALF = 0.065 # 13 x 13 cm +MAT_X, MAT_Y = (-0.11, -0.05), (-0.05, 0.05) +BOX_D = (0.15, 0.185, 0.22, 0.255) # distances of the four boxes from the mat centre (+- jitter) +BOX_X = (-0.33, 0.07) # world x range of the box positions (reach) +BOX_YMAX = 0.30 +BOX_YAW = 0.30 +P_BENIGN = 0.10 # 2 of every 20 consecutive seeds: no soft box + +# ---------------------------------------------------------------- predicates +TILT_OK = np.radians(10.0) +KINK_OK = np.radians(10.0) +ON_MAT = 0.035 # bottom box centre within 3.5 cm of the mat centre (x and y): its footprint is on the 13 cm mat +STACK_XY = 0.030 # centre of a box within 3 cm (= the half width) of the centre of the box below: its centre of +# mass is over the lower box's top face (v2; 2.5 cm judged a resting box 2.51 cm off as not stacked) +STACK_Z = 0.010 +CUP_XY = 0.030 +DEBOUNCE = 10 # control steps (0.5 s) + +# ---------------------------------------------------------------- scripted motion +Z_CARRY = 0.18 +NAIVE_ERR = (0.004, 0.013) # Sonnet's placement error 0.4-1.3 cm (random direction) +NAIVE_GAP = (0.010, 0.040) # Sonnet lets go 1-4 cm above the surface +NAIVE_BIAS = (0.0, 0.020) # forward bias of the first box on the mat (oblique camera) + + +def box_xml(name, rgba): + """storage box: base part (root body, 1.6 cm) + upper part (child body) on a ball joint at the seam. Rigid boxes + get a ~0 kink range at reset; the soft carton a 31.5 deg range and the load-dependent stiffness of SoftLaw. + Inertials are replaced per instance (mass).""" + mb, mu = BOX_MASS * HB / H, BOX_MASS * HU / H + zb = -H / 2 + HB / 2 + dark = [0.72 * c for c in rgba[:3]] + [1.0] + g = [f' ', + f' ', + f' ', + f' ', + f' ', + f' ', + f' ', + f' ', + # lid line (visual only): a darker band 8 mm below the top, on all four boxes + f' ', + ' '] + return _wrap(name, "\n".join(g), H / 2, float(np.hypot(HX, HY))) + + +def cup_xml(name): + """open cup, 5 cm wide, 7 cm tall: 12 wall boxes + an octagonal base of two boxes (box contacts; a light MuJoCo + cylinder creeps on a flat surface, lh_nudge_row). Visual: a smooth cylinder with a dark inside.""" + r, h = CUP_R, CUP_H + nseg, wt, bt = 12, 0.004, 0.006 + g = [f' '] + s = r * np.sin(np.pi / nseg) + 0.0008 + rc = r * np.cos(np.pi / nseg) - wt / 2 + for k in range(nseg): + a = 2 * np.pi * k / nseg + q = [np.cos(a / 2), 0, 0, np.sin(a / 2)] + g.append(f' ') + a0 = r * 0.70 + for k, ang in enumerate((0.0, np.pi / 4)): + q = [np.cos(ang / 2), 0, 0, np.sin(ang / 2)] + g.append(f' ') + g.append(f' ') + g.append(f' ') + return _wrap(name, "\n".join(g), h / 2, r) + + +def mat_xml(name): + g = (f' ') + return _wrap(name, g, 0.0005, MAT_HALF * 1.42) + + +def free_adr(env, name): + """(qpos, dof) address of the object's FREE joint. envs.free_joint_addr takes joints[0], which for an object with a + jointed child body is the child's joint (robosuite lists the subtree's joints before the free joint it appends).""" + m = env.sim.model + for jn in env.objects_dict[name].joints: + j = m.joint_name2id(jn) + if int(m.jnt_type[j]) == 0: + return int(m.jnt_qposadr[j]), int(m.jnt_dofadr[j]) + raise KeyError(name) + + +def place(env, name, xy, yaw=0.0, surface_z=TZ, clearance=0.0005, tilt=None): + """teleport upright (yaw about z; `tilt` rad about the object's own x axis first, e.g. pi/2 = lying on a side + face -- controls only), lowest collision point `clearance` above surface_z (reset only)""" + qa, da = free_adr(env, name) + d = env.sim.data + d.qpos[qa:qa + 3] = [xy[0], xy[1], surface_z + 0.3] + q = np.array([np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)]) + if tilt: + w1, z1 = q[0], q[3] + c, s_ = np.cos(tilt / 2), np.sin(tilt / 2) + q = np.array([w1 * c, w1 * s_, z1 * s_, z1 * c]) # q_yaw * q_x(tilt) + d.qpos[qa + 3:qa + 7] = q + d.qvel[da:da + 6] = 0.0 + env.sim.forward() + d.qpos[qa + 2] -= envs.obj_min_z(env, name) - (surface_z + clearance) + env.sim.forward() + + +def _fb(v): + return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}" + + +def _lr(v): + return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}" + + +def _wrap_q(a, period): + """wrap an angle to [-period/2, period/2)""" + return float((a + period / 2) % period - period / 2) + + +class StackSkills(Skills): + """Skills that feed the task's per-step monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class TidyStack(LFFTask): + name = "lh_tidy_stack" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Restore", "Plan") + protocol = "cross" + max_attempts = 3 + # careful: 5 pick-and-places x ~8 commands (40) + a collapse: unstack 1-2 boxes (~16) and rebuild 3-4 (~32) + # + looking / small corrections (~30), with some margin + agent_max_steps = 150 + instruction = ("Tidy up the table: stack the four storage boxes (red, green, blue, yellow) into a single pile on the " + "grey mat, in any order you like, and then put the cup upright on top of the pile. At the end each " + "box must rest flat on the box below it (the bottom one on the mat), the cup must stand on the top " + "box, and the gripper must be open and clear of everything.") + instruction_indirect = ("Clean up the table: pile the four coloured boxes on top of each other on the dark grey " + "square, in whatever order, and finish by standing the teal mug on top of the pile. In the " + "end every box has to sit flat on the one below it (the lowest on the grey square), the mug " + "has to stand on the top box, and the gripper must be open and away from everything.") + agent_object_names = ["storage boxes (red, green, blue, yellow)", "grey mat", "cup"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs = [] + for i, (c, b) in enumerate(zip(COLOURS, BOXES)): + cat = register_generated(f"LffLtsBox{c.capitalize()}", box_xml(f"lff_lts_box_{c}", RGBA[c])) + objs.append((b, cat, f"box{i}_region", (-0.30 + 0.13 * i, 0.28, -0.29 + 0.13 * i, 0.29))) + cat = register_generated("LffLtsCup", cup_xml("lff_lts_cup")) + objs.append((CUP, cat, "cup_region", (-0.30, -0.29, -0.29, -0.28))) + mat = register_generated("LffLtsMat", mat_xml("lff_lts_mat"), free=False) + fx = [(MAT, mat, "mat_region", (0.0, -0.29, 0.01, -0.28))] + return write_bddl(self.name, "Stack the four boxes on the grey mat and put the cup on top", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.mat_bid = m.body_name2id(self.env.fixtures_dict[MAT].root_body) + self.jid, self.base_bid, self.upper_bid, self.base_gid, self.upper_gid = {}, {}, {}, {}, {} + for b in BOXES: + for g in envs.obj_geom_ids(self.env, b): + n = m.geom_id2name(g) + if n.endswith("_upper"): + self.upper_gid[b] = g + elif n.endswith("_base"): + self.base_gid[b] = g + self.upper_bid[b] = int(m.geom_bodyid[self.upper_gid[b]]) + self.base_bid[b] = int(m.geom_bodyid[self.base_gid[b]]) + j = next(m.joint_name2id(jn) for jn in self.env.objects_dict[b].joints if jn.endswith("_kink")) + self.jid[b] = j + # every geom of each half (collision and visual) with its compiled size / pos: the crush rescales them + self.half_geoms = {} + for b in BOXES: + hg = [] + for bid in (self.base_bid[b], self.upper_bid[b]): + gs = [g for g in range(int(m.body_geomadr[bid]), int(m.body_geomadr[bid] + m.body_geomnum[bid])) + if int(m.geom_type[g]) == 6] + hg.append((bid, gs, m.geom_size[gs].copy(), m.geom_pos[gs].copy())) + self.half_geoms[b] = hg + self.cup_gids = list(envs.obj_geom_ids(self.env, CUP)) + self.obj_bodies = {b: [self.base_bid[b], self.upper_bid[b]] for b in BOXES} + self.obj_bodies[CUP] = [envs.body_id(self.env, CUP)] + # per-geom lookup: owner index 0-3 = boxes, 4 = cup, -1 other; robot part 1 = finger, 2 = hand / arm + self.owner = np.full(m.ngeom, -1, int) + for i, b in enumerate(BOXES): + self.owner[[self.base_gid[b], self.upper_gid[b]]] = i + self.owner[self.cup_gids] = 4 + self.part = np.zeros(m.ngeom, int) + for g in envs.robot_geom_ids(self.env): + n = m.geom_id2name(g) or "" + self.part[g] = 1 if "finger" in n else 2 + self.inst = None + self.law = None + self.mon = None + self.sk = None + self._sub_rob = {} + self._held = set() # owner indices (0-3 boxes, 4 cup) held by the gripper, refreshed every control step + self._rest_cap = np.inf # upper bound of the resting load on the soft carton, refreshed every control step + sim = self.env.sim + if not getattr(sim, "_lts_wrapped", False): + orig = sim.step + + def step(*a, **k): + t = getattr(sim, "_lts_task", None) + if t is not None and t.law is not None: + t._law_step() + orig(*a, **k) + if t is not None and t.mon is not None: + t._substep() + sim.step = step + sim._lts_wrapped = True + sim._lts_task = self + + # ------------------------------------------------------------ instances + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + mx, my = float(rng.uniform(*MAT_X)), float(rng.uniform(*MAT_Y)) + ca = np.pi + float(rng.uniform(-0.5, 0.5)) # the cup stands on the robot's side of the mat, 23-26 cm away + cd = float(rng.uniform(0.23, 0.26)) + cup = [mx + cd * np.cos(ca), my + cd * np.sin(ca)] + for _ in range(500): + ds = np.array(BOX_D) + rng.uniform(-0.01, 0.01, 4) + ang = rng.uniform(np.radians(30), np.radians(150), 4) * rng.choice([-1.0, 1.0], 4) + pos = np.stack([mx + ds * np.cos(ang), my + ds * np.sin(ang)], 1) + if not (np.all((pos[:, 0] >= BOX_X[0]) & (pos[:, 0] <= BOX_X[1])) and np.all(np.abs(pos[:, 1]) <= BOX_YMAX)): + continue + dd = np.linalg.norm(pos[:, None] - pos[None], axis=2) + np.eye(4) + if dd.min() < 0.12 or np.linalg.norm(pos - np.asarray(cup), axis=1).min() < 0.14: + continue + break + else: + raise RuntimeError("layout") + perm = rng.permutation(4) + start = {BOXES[i]: [float(v) for v in pos[perm[i]]] for i in range(4)} + yaw = {b: float(rng.uniform(-BOX_YAW, BOX_YAW)) for b in BOXES} + mat = np.array([mx, my]) + near = sorted(BOXES, key=lambda b: float(np.linalg.norm(np.asarray(start[b]) - mat))) + # balanced blocks of 20 consecutive seeds: 2 benign (no soft box); else the soft carton is the box at rank + # r = 0..3 (0 = nearest the mat, i.e. the bottom of a nearest-first pile; 3 = the top): 5 / 5 / 4 / 4 + k = (int(seed) * 7) % 20 + benign = k >= round(20 * (1 - P_BENIGN)) + rank = None if benign else k % 4 + soft = None if benign else near[rank] + return dict(seed=int(seed), mat=[mx, my], cup=cup, start=start, yaw=yaw, cup_yaw=float(rng.uniform(-np.pi, np.pi)), + soft=soft, soft_colour=COL[soft] if soft else None, benign=bool(benign), + soft_rank_nearest=rank, nearest_order=[COL[b] for b in near], + buckle_dir=float(np.pi / 2 if rng.random() < 0.5 else -np.pi / 2), + f_crit=F_CRIT, naive_gap=float(rng.uniform(*NAIVE_GAP)), naive_bias=float(rng.uniform(*NAIVE_BIAS))) + + def apply_instance(self, inst): + self.inst = inst + m, d = self.env.sim.model, self.env.sim.data + m.body_pos[self.mat_bid] = [inst["mat"][0], inst["mat"][1], TZ + 0.0005] + for b in BOXES: + j = self.jid[b] + soft = b == inst["soft"] + M = SOFT_MASS if soft else BOX_MASS + for bid, frac, h in ((self.base_bid[b], HB / H, HB), (self.upper_bid[b], HU / H, HU)): + mm = M * frac + m.body_mass[bid] = mm + m.body_inertia[bid] = [mm * (4 * HY * HY + h * h) / 12, mm * (4 * HX * HX + h * h) / 12, + mm * (4 * HX * HX + 4 * HY * HY) / 12] + m.jnt_range[j] = [0.0, RANGE_SOFT if soft else RANGE_RIGID] + m.jnt_solref[j] = [0.02, 1.0] if soft else [0.004, 1.0] # rigid boxes: a stiff limit + m.jnt_stiffness[j] = K_HI if soft else K_RIGID + qa, da = int(m.jnt_qposadr[j]), int(m.jnt_dofadr[j]) + m.qpos_spring[qa:qa + 4] = [1.0, 0.0, 0.0, 0.0] + d.qpos[qa:qa + 4] = [1.0, 0.0, 0.0, 0.0] + d.qvel[da:da + 3] = 0.0 + self._set_crush(b, 0.0, 2, -1.0) # undo a crush left over from the previous attempt + place(self.env, b, inst["start"][b], yaw=inst["yaw"][b], tilt=inst.get("lying", {}).get(COL[b])) + place(self.env, CUP, inst["cup"], yaw=inst["cup_yaw"]) + self.law = None + if inst["soft"]: + self.law = dict(box=inst["soft"], f=0.0, fmax=0.0, buckled=False, n=0, rel_t=0.0, t=0.0, buckles=[], + f_crit=float(inst.get("f_crit", F_CRIT)), dir=float(inst["buckle_dir"]), + mode=str(inst.get("law", "threshold")), how=None, crush=0.0, crush_set=0.0, + crush_axis=2, crush_sign=-1.0, f_rest=0.0, f_robot=0.0) + if self.law["mode"] == "linear": # control only: the brief's fixed-stiffness spring (no load threshold) + m.jnt_stiffness[self.jid[inst["soft"]]] = float(inst["k_lin"]) + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.law = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = StackSkills(self.env, self, recorder=recorder) + self._sub_rob = {} + self._held = set() + self._rest_cap = np.inf + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ soft-carton law + def _part_axial(self, gid, axis): + """sum of contact forces on geom gid (from any other geom), projected on `axis` (world)""" + m, d = self.env.sim.model, self.env.sim.data + n = d.ncon + if not n: + return 0.0 + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + idx = np.nonzero((g1 == gid) | (g2 == gid))[0] + tot = 0.0 + f6 = np.zeros(6) + for i in idx: + mujoco.mj_contactForce(m._model, d._data, int(i), f6) + fw = d.contact[int(i)].frame.reshape(3, 3).T @ f6[:3] # force on geom2, world frame + tot += float(fw @ axis) * (-1.0 if g1[i] == gid else 1.0) + return tot + + def vertical_loads(self, b): + """vertical contact forces on box b (N), whichever face it rests on: (resting, robot, held, support). + resting = downward push on its upper side (contact point above its centre) from things resting on it; + robot = the same from the robot's own fingers / hand pushing on it (not counted while the robot holds b + itself); held = the same from something the robot holds (pressing it down onto b); support = upward push on + its lower side. Its two halves never touch (parent and child), so only real contacts count.""" + m, d = self.env.sim.model, self.env.sim.data + n = d.ncon + if not n: + return 0.0, 0.0, 0.0, 0.0 + gb, gu = self.base_gid[b], self.upper_gid[b] + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + idx = np.nonzero((g1 == gb) | (g1 == gu) | (g2 == gb) | (g2 == gu))[0] + if not len(idx): + return 0.0, 0.0, 0.0, 0.0 + cz = float(d.xpos[self.base_bid[b]][2]) # the root body sits at the box's centre + held = self._held + b_held = BOXES.index(b) in held + rest = robot = via = sup = 0.0 + f6 = np.zeros(6) + for i in idx: + c = d.contact[int(i)] + mujoco.mj_contactForce(m._model, d._data, int(i), f6) + fz = float(c.frame.reshape(3, 3)[:, 2] @ f6[:3]) # world z of the force on geom2 + mine1 = g1[i] in (gb, gu) + fz = -fz if mine1 else fz # force on box b + other = int(g2[i] if mine1 else g1[i]) + pz = float(c.pos[2]) + if pz > cz + 0.004 and fz < 0.0: + o = self.owner[other] + if self.part[other] > 0: + if not b_held: + robot -= fz + elif o >= 0 and o in held: + via -= fz + else: + rest -= fz + elif pz < cz - 0.004 and fz > 0.0: + sup += fz + # what rests on it pushes at most with its own weight: the robot pressing down through an item it has let go + # of (Sonnet releases with the cup pushed up against the hand, pilot s3003) is not a resting load + rest = min(rest, self._rest_cap) + return rest, robot, via, sup + + def compression(self, b): + """compressive force (N) on the carton, (total, resting): the downward push on its upper side from things + resting on it plus the robot's fingers / hand pushing directly on it, limited by the support under it -- + along the world vertical, whichever face it rests on (v1 measured it along the box axis only: a carton lying + on its side never buckled). Something the robot still holds does not count: Sonnet presses what it puts down + 0.5-1.5 cm below contact (pilot), which must not crush a carton that will carry the item once let go.""" + rest, robot, via, sup = self.vertical_loads(b) + return float(min(rest + robot, sup)), float(min(rest, sup)) + + def _law_step(self): + """per MuJoCo substep: low-pass the compressive load; above f_crit the carton gives way -- standing or upside + down it folds (its kink joint loses its stiffness, its rest shape bends towards its weak side and the load + topples it), lying on a side face it is crushed (both halves flatten, the upper half more); unloaded for + REL_T it slowly recovers its shape""" + law = self.law + b = law["box"] + m = self.env.sim.model + dt = float(m.opt.timestep) + tot, rest = self.compression(b) + law["f"] += (tot - law["f"]) * dt / TAU_F + law["f_rest"] += (rest - law["f_rest"]) * dt / TAU_F + law["fmax"] = max(law["fmax"], law["f"]) + j = self.jid[b] + qa = int(m.jnt_qposadr[j]) + if law["mode"] == "linear": # control: constant stiffness; a "buckle" = the kink passes 15 deg (re-arms < 5) + kk = self.kink(b) + if not law["buckled"] and kk > np.radians(15.0): + law["buckled"] = True + law["n"] += 1 + law["buckles"].append(dict(t=round(law["t"], 3), load_N=round(law["f"], 2))) + self._on_buckle() + elif law["buckled"] and kk < np.radians(5.0): + law["buckled"] = False + law["t"] += dt + return + if not law["buckled"]: + if law["f"] > law["f_crit"]: + law["buckled"] = True + law["n"] += 1 + law["rel_t"] = 0.0 + R = self.env.sim.data.xmat[self.base_bid[b]].reshape(3, 3) + law["unbend_q0"] = None + if abs(R[2, 2]) >= FOLD_MIN_UP: # seam horizontal: fold + law["how"] = "fold" + u = R.T @ np.array([np.cos(law["dir"]), np.sin(law["dir"]), 0.0]) + ax = np.array([-u[1], u[0], 0.0]) + ax /= max(np.linalg.norm(ax), 1e-9) + m.qpos_spring[qa:qa + 4] = [np.cos(BEND_REF / 2), *(np.sin(BEND_REF / 2) * ax)] + else: # seam vertical (lying on a side face): crush towards the face it rests on + law["how"] = "crush" + k = int(np.argmax(np.abs(R[2, :2]))) + law["crush_axis"] = k + law["crush_sign"] = -float(np.sign(R[2, k]) or 1.0) # local direction of "down" along axis k + # cause: "load" = what rests on it is enough by itself (>= 60 % of f_crit, i.e. more than one item); + # "press" = the robot's own push made the difference (a hard press with the gripper) + cause = "load" if law["f_rest"] >= 0.6 * law["f_crit"] else "press" + law["buckles"].append(dict(t=round(law["t"], 3), load_N=round(law["f"], 2), how=law["how"], + resting_N=round(law["f_rest"], 2), cause=cause)) + self._on_buckle() + elif law["f"] < F_REL: + law["rel_t"] += dt + if law["rel_t"] > REL_T: + law["buckled"] = False + # straighten smoothly: the rest shape starts at the current bend and moves back to straight over + # K_RISE (a stiff spring released at once from a 40-50 deg bend flips the light carton over) + q0 = np.array(self.env.sim.data.qpos[qa:qa + 4], float) + q0 = q0 / max(np.linalg.norm(q0), 1e-9) * (1.0 if q0[0] >= 0 else -1.0) + law["unbend_q0"], law["unbend_s"] = q0.tolist(), 0.0 + m.qpos_spring[qa:qa + 4] = q0 + else: + law["rel_t"] = 0.0 + k = float(m.jnt_stiffness[j]) + if law["buckled"] and law["how"] == "fold": + m.jnt_stiffness[j] = k + (K_LO - k) * min(1.0, dt / 0.02) + else: + m.jnt_stiffness[j] = K_HI + if law.get("unbend_q0") is not None: + law["unbend_s"] = min(1.0, law["unbend_s"] + dt / K_RISE) + q = (1.0 - law["unbend_s"]) * np.asarray(law["unbend_q0"]) + law["unbend_s"] * np.array([1.0, 0, 0, 0]) + m.qpos_spring[qa:qa + 4] = q / np.linalg.norm(q) + if law["unbend_s"] >= 1.0: + law["unbend_q0"] = None + target = 1.0 if (law["buckled"] and law["how"] == "crush") else 0.0 + if target or law["crush"] > 0.0: + tau = CRUSH_TAU[0] if target else CRUSH_TAU[1] + law["crush"] += (target - law["crush"]) * min(1.0, dt / tau) + if not target and law["crush"] < 0.002: + law["crush"] = 0.0 + if abs(law["crush"] - law["crush_set"]) > 0.004 or (law["crush"] == 0.0 and law["crush_set"] > 0.0): + self._set_crush(b, law["crush"], law["crush_axis"], law["crush_sign"]) + law["crush_set"] = law["crush"] + law["t"] += dt + + def _set_crush(self, b, c, axis, sign): + """flatten box b's two halves along their local `axis` by c (0..1) x CRUSH_ALPHA, keeping the faces on the + `sign` side (the side facing down) in place; then refresh the collision bounds""" + m = self.env.sim.model + for (bid, gs, size0, pos0), alpha in zip(self.half_geoms[b], CRUSH_ALPHA): + size, pos = size0.copy(), pos0.copy() + if c > 0.0: + s0 = size0[:, axis] + s1 = s0 * (1.0 - alpha * c) + size[:, axis] = s1 + pos[:, axis] = pos0[:, axis] + sign * (s0 - s1) + m.geom_size[gs] = size + m.geom_pos[gs] = pos + envs.refit_bounds(m, [self.half_geoms[b][0][0], self.half_geoms[b][1][0]]) + + def _on_buckle(self): + mon = self.mon + if mon is None: + return + b = self.law["box"] + ch = self.pile() + on = self.items_on(b) + last = self.law["buckles"][-1] if self.law["buckles"] else {} + e = dict(event="buckle", box=COL[b], step=int(self.sk.n_steps) if self.sk else 0, + load_N=round(self.law["f"], 2), level=(ch.index(b) + 1) if b in ch else None, + items_on=[COL.get(x, "cup") for x in on], how=last.get("how"), cause=last.get("cause"), + resting_N=last.get("resting_N"), + lying=bool(abs(self.R(self.base_bid[b])[2, 2]) < FOLD_MIN_UP)) + mon["events"].append(e) + mon["buckle_steps"].append(e["step"]) + mon["pending_collapse"] = dict(step=e["step"], pile=list(ch), cup=self.cup_on_pile(ch)) + + # ------------------------------------------------------------ geometry / predicates + def R(self, bid): + return self.env.sim.data.xmat[bid].reshape(3, 3) + + def centre(self, name): + return envs.obj_pos(self.env, name) + + def flat_tilt(self, b): + """angle (rad) between world vertical and the base part's axis closest to it (a box may lie on any face)""" + R = self.R(self.base_bid[b]) + return float(np.arccos(np.clip(np.max(np.abs(R[2, :])), -1.0, 1.0))) + + def kink(self, b): + """bend of the upper part against the base part (rad)""" + zb = self.R(self.base_bid[b])[:, 2] + zu = self.R(self.upper_bid[b])[:, 2] + return float(np.arccos(np.clip(zb @ zu, -1.0, 1.0))) + + def cup_tilt(self): + return float(np.arccos(np.clip(envs.obj_upright_cos(self.env, CUP), -1.0, 1.0))) + + def held(self, name): + return self.sk is not None and self.sk.holding(name) + + def crushed(self, b): + """how far box b is crushed (0..1; only the soft carton, lying on a side face, can be)""" + law = self.law + return float(law["crush"]) if (law is not None and law["box"] == b) else 0.0 + + def flat(self, b): + return (self.flat_tilt(b) <= TILT_OK and self.kink(b) <= KINK_OK and self.crushed(b) <= 0.15 + and not self.held(b)) + + def rests_on(self, upper, lower): + cu, cl = self.centre(upper), self.centre(lower) + return (np.linalg.norm(cu[:2] - cl[:2]) <= STACK_XY + and abs(envs.obj_min_z(self.env, upper) - envs.obj_max_z(self.env, lower)) <= STACK_Z) + + def on_mat(self, b): + off = self.centre(b)[:2] - np.asarray(self.inst["mat"]) + return bool(np.all(np.abs(off) <= ON_MAT) and envs.obj_min_z(self.env, b) <= TZ + 0.008) + + def pile(self): + """the longest chain of flat boxes: the bottom one on the mat, each next resting on the previous (centres within + 2 cm, faces within 1 cm)""" + flat = [b for b in BOXES if self.flat(b)] + best = [] + for b0 in [b for b in flat if self.on_mat(b)]: + ch = [b0] + while True: + nxt = [b for b in flat if b not in ch and self.rests_on(b, ch[-1])] + if not nxt: + break + ch.append(min(nxt, key=lambda b: float(np.linalg.norm(self.centre(b)[:2] - self.centre(ch[-1])[:2])))) + if len(ch) > len(best): + best = ch + return best + + def cup_on(self, b): + c = self.centre(CUP) + return bool(self.cup_tilt() <= TILT_OK and not self.held(CUP) + and np.linalg.norm(c[:2] - self.centre(b)[:2]) <= CUP_XY + and abs(envs.obj_min_z(self.env, CUP) - envs.obj_max_z(self.env, b)) <= STACK_Z) + + def cup_on_pile(self, ch=None): + ch = self.pile() if ch is None else ch + return bool(len(ch) == len(BOXES) and self.cup_on(ch[-1])) + + def items_on(self, b): + """boxes / cup resting (directly or higher up) on box b, by height and overlap""" + cb = self.centre(b) + top = envs.obj_max_z(self.env, b) + out = [] + for x in BOXES + [CUP]: + if x == b: + continue + c = self.centre(x) + if envs.obj_min_z(self.env, x) > top - 0.015 and np.linalg.norm(c[:2] - cb[:2]) < 0.06: + out.append(x) + return out + + def stage_values(self): + ch = self.pile() + v = {COL[b]: b in ch for b in BOXES} + v["cup"] = self.cup_on_pile(ch) + return v, ch + + # ------------------------------------------------------------ monitor + def _init_monitor(self): + keys = COLOURS + ["cup"] + self.mon = dict(state={k: False for k in keys}, cand={k: 0 for k in keys}, ever={k: False for k in keys}, + lost={k: False for k in keys}, lost_cause={k: None for k in keys}, events=[], n=0, + last_robot={k: -10 ** 6 for k in keys}, buckle_steps=[], pending_collapse=None, + max_kink={COL[b]: 0.0 for b in BOXES}, max_crush={COL[b]: 0.0 for b in BOXES}, + max_height=0, n_collapses=0, + law=self.law) # the carton's law state rides along in the robot server's regression snapshots + + def _substep(self): + d = self.env.sim.data + n = d.ncon + if not n: + return + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + o1, o2 = self.owner[g1], self.owner[g2] + p1, p2 = self.part[g1], self.part[g2] + sel = ((o1 >= 0) & (p2 > 0)) | ((o2 >= 0) & (p1 > 0)) + for i in np.nonzero(sel)[0]: + o = o1[i] if o1[i] >= 0 else o2[i] + self._sub_rob[int(o)] = True + + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + mon["n"] += 1 + t = int(self.sk.n_steps) + self._held = {i for i, x in enumerate(BOXES + [CUP]) if self.held(x)} + if self.law is not None: # weight of the things (not held) on the soft carton, + 0.3 N for impacts + m = self.env.sim.model + self._rest_cap = 0.3 + G * sum(float(np.sum(m.body_mass[self.obj_bodies[x]])) + for x in self.items_on(self.law["box"]) + if (BOXES + [CUP]).index(x) not in self._held) + keys = COLOURS + ["cup"] + for i in list(self._sub_rob): + mon["last_robot"][keys[i]] = t + self._sub_rob = {} + for b in BOXES: + mon["max_kink"][COL[b]] = max(mon["max_kink"][COL[b]], round(float(np.degrees(self.kink(b))), 1)) + mon["max_crush"][COL[b]] = max(mon["max_crush"][COL[b]], round(self.crushed(b), 2)) + if mon["n"] % 2: + return + vals, ch = self.stage_values() + mon["max_height"] = max(mon["max_height"], len(ch)) + for k in keys: + raw = vals[k] + if raw == mon["state"][k]: + mon["cand"][k] = 0 + continue + mon["cand"][k] += 2 + if mon["cand"][k] < DEBOUNCE: + continue + mon["cand"][k] = 0 + mon["state"][k] = raw + t0 = t - DEBOUNCE + 1 + if raw: + restored = mon["lost"][k] + e = dict(stage=k, event="restored" if restored else "achieved", step=t0) + if restored: + e["after"] = mon["lost_cause"][k] + mon["lost"][k] = False + mon["ever"][k] = True + mon["events"].append(e) + elif mon["ever"][k]: + cause = self._cause(k, t) + mon["lost"][k] = True + mon["lost_cause"][k] = cause + mon["events"].append(dict(stage=k, event="lost", step=t0, cause=cause)) + pc = mon["pending_collapse"] + if cause == "buckle" and pc is not None and not pc.get("counted"): + pc["counted"] = True + mon["n_collapses"] += 1 + mon["events"].append(dict(event="collapse", step=t0, buckled=self.inst["soft_colour"], + pile_before=[COL[b] for b in pc["pile"]])) + + def _cause(self, k, t): + name = CUP if k == "cup" else BOXES[COLOURS.index(k)] + if self.held(name): + return "picked_up" + bs = self.mon["buckle_steps"] + if bs and t - bs[-1] <= 80: # within 4 s of a buckle + return "buckle" + if t - self.mon["last_robot"][k] <= 30: + return "robot" + return "other" + + def _finalize_monitor(self, vals): + mon = self.mon + t = int(self.sk.n_steps) + for k, raw in vals.items(): + if raw == mon["state"][k]: + continue + mon["state"][k] = raw + if raw: + restored = mon["lost"][k] + e = dict(stage=k, event="restored" if restored else "achieved", step=t, final=True) + if restored: + e["after"] = mon["lost_cause"][k] + mon["lost"][k] = False + mon["ever"][k] = True + mon["events"].append(e) + elif mon["ever"][k]: + cause = self._cause(k, t) + mon["lost"][k] = True + mon["lost_cause"][k] = cause + mon["events"].append(dict(stage=k, event="lost", step=t, cause=cause, final=True)) + + # ------------------------------------------------------------ outcome + def _touching(self): + d = self.env.sim.data + n = d.ncon + if not n: + return False + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + return bool(np.any(((self.owner[g1] >= 0) & (self.part[g2] > 0)) | ((self.owner[g2] >= 0) & (self.part[g1] > 0)))) + + def _static_pos(self): + return {x: self.centre(x).copy() for x in BOXES + [CUP]} + + def outcome(self, inst): + sk = self.sk + sk.hold(10) + p0 = self._static_pos() + touching = False + for _ in range(20): + sk.hold(1) + touching = touching or self._touching() + moved = max(float(np.linalg.norm(self.centre(x) - p0[x])) for x in p0) + static = moved < 0.003 + vals, ch = self.stage_values() + self._finalize_monitor(vals) + mon = self.mon + ev = list(mon["events"]) + held = [COL.get(x, "cup") for x in BOXES + [CUP] if self.held(x)] + success = bool(all(vals.values()) and static and not held and not touching) + buckles = [e for e in ev if e.get("event") == "buckle"] + n_reg = sum(e.get("event") == "lost" and e.get("cause") != "picked_up" for e in ev) + n_res = sum(e.get("event") == "restored" and e.get("after") != "picked_up" for e in ev) + soft = inst["soft"] + buckled_now = bool(self.law is not None and self.law["buckled"]) + cup_fallen = self.cup_tilt() > np.radians(45) + if success: + failure = "none" + elif held: + failure = "held" + elif touching and all(vals.values()): + failure = "touching" + elif not all(vals[c] for c in COLOURS): + if buckles and any(mon["ever"][c] for c in COLOURS): + failure = "collapsed" + elif any(mon["lost"][c] for c in COLOURS): + failure = "regressed" + else: + failure = "not_stacked" + elif not vals["cup"]: + failure = "cup_fallen" if cup_fallen else "cup_not_on_top" + else: + failure = "not_static" + # F2 detail (robot-centric words) + parts = [] + if success: + parts.append("All four boxes are stacked on the mat and the cup stands on top.") + else: + if ch: + parts.append("The pile on the mat is " + " / ".join(COL[b] for b in ch) + " (bottom to top).") + else: + parts.append("There is no box resting flat on the mat.") + mat = np.asarray(inst["mat"]) + for b in BOXES: + if b in ch: + continue + c = COL[b] + if self.held(b): + parts.append(f"The {c} box is still held by the gripper.") + continue + off = self.centre(b)[:2] - mat + pose = ("lies tilted" if self.flat_tilt(b) > TILT_OK else + "is crushed flat" if self.crushed(b) > 0.15 else + f"is bent ({np.degrees(self.kink(b)):.0f} degrees)" if self.kink(b) > KINK_OK else "stands") + parts.append(f"The {c} box {pose} {_fb(off[0])} and {_lr(off[1])} of the mat's centre, not in the pile.") + if not vals["cup"]: + if self.held(CUP): + parts.append("The cup is still held by the gripper.") + elif cup_fallen: + parts.append("The cup has fallen over.") + else: + parts.append("The cup is not standing on top of a complete pile.") + if all(vals.values()): + if touching: + parts.append("The gripper is still touching the pile.") + elif not static: + parts.append("Something was still moving.") + loads = [e for e in buckles if e.get("cause") != "press"] + presses = [e for e in buckles if e.get("cause") == "press"] + if loads: + how = ("bent sideways or was crushed" if len({e.get("how") for e in loads}) > 1 else + "was crushed flat" if loads[0].get("how") == "crush" else "bent sideways") + parts.append(f"During the attempt the {loads[0]['box']} box {how} under the weight on it " + f"{len(loads)} time(s) and everything above it slid off.") + if presses: + parts.append(f"The {presses[0]['box']} box gave way {len(presses)} time(s) when the gripper pushed down " + f"on it.") + # trap fired = the carton gave way under what was put on it (or a giving-way cost a stage); a hard press by the + # gripper alone on an otherwise lightly loaded carton is logged (n_press_buckles) but is not the trap + trap = bool(loads) or int(mon["n_collapses"]) > 0 + return dict(success=success, failure=failure, stages=vals, pile=[COL[b] for b in ch], events=ev, + n_regressions=int(n_reg), n_restored=int(n_res), trap_fired=trap, + recovered_in_attempt=bool(trap and success), n_buckles=len(buckles), + n_collapses=int(mon["n_collapses"]), buckle_levels=[e.get("level") for e in buckles], + buckle_loads_N=[e.get("load_N") for e in buckles], max_kink_deg=dict(mon["max_kink"]), + max_crush=dict(mon["max_crush"]), buckle_how=[e.get("how") for e in buckles], + buckle_causes=[e.get("cause") for e in buckles], n_press_buckles=len(presses), + max_height=int(mon["max_height"]), soft=inst["soft_colour"], benign=bool(inst["benign"]), + buckled_at_end=buckled_now, cup_fallen=bool(cup_fallen), held=held, touching=bool(touching), + static=bool(static), detail=" ".join(parts)) + + # ------------------------------------------------------------ scripted primitives (move_to + gripper only) + def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300): + return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + + def _lift_to(self, z, speed=0.2): + cur = self.sk.eef_pos() + if cur[2] < z - 0.005: + self._go([cur[0], cur[1], z], speed=speed) + + def _settle(self, steps=40): + """hold until boxes / cup have stopped (max `steps` control steps)""" + p = self._static_pos() + for _ in range(steps // 4): + self.sk.hold(4) + q = self._static_pos() + if max(float(np.linalg.norm(q[x] - p[x])) for x in p) < 0.0005: + return + p = q + + def settle_scene(self, max_steps=120): + """after a collapse: wait (looking) until nothing moves and no box is visibly bent any more""" + for _ in range(max_steps // 10): + self._settle(10) + if all(self.kink(b) < np.radians(3.0) for b in BOXES): + p = self._static_pos() + self.sk.hold(4) + q = self._static_pos() + if max(float(np.linalg.norm(q[x] - p[x])) for x in p) < 0.0005: + return + + def grasp_yaw(self, name): + """wrist yaw that closes the fingers across a horizontal box axis: of the two, the one whose open fingers stay + clearest of the other objects (a box that fell against another one), then the one needing the least turn""" + if name == CUP: + return 0.0 + R = self.R(self.base_bid[name]) + up = int(np.argmax(np.abs(R[2, :]))) + c = self.centre(name)[:2] + others = [self.centre(x)[:2] for x in BOXES + [CUP] if x != name] + best = None + for a in range(3): + if a == up: + continue + v = R[:2, a] / max(np.linalg.norm(R[:2, a]), 1e-9) + yaw = _wrap_q(float(np.arctan2(v[1], v[0])) - np.pi / 2, np.pi) # fingers close along (-sin yaw, cos yaw) + fingers = [c + s_ * 0.045 * v for s_ in (1.0, -1.0)] # open fingers ~4.5 cm from the centre + clear = min([float(np.linalg.norm(f - o)) for f in fingers for o in others] + [1.0]) + key = (round(min(clear, 0.05), 3), -abs(yaw)) + if best is None or key > best[0]: + best = (key, yaw) + return best[1] + + def z_clear(self, extra=0.08): + """carry height: above everything on the table""" + top = max(envs.obj_max_z(self.env, x) for x in BOXES + [CUP]) + return max(TZ + Z_CARRY, top + extra) + + def pick(self, name, depth=0.018, z_carry=None, tries=2): + sk = self.sk + for _ in range(tries): + self._settle(20) + p = self.centre(name) + zt = envs.obj_max_z(self.env, name) + yaw = self.grasp_yaw(name) + sk.set_gripper(False, steps=10) + zc = z_carry or self.z_clear() + self._lift_to(zc) + self._go([p[0], p[1], zc], yaw=yaw, speed=0.25) + self._go([p[0], p[1], zt - depth + 0.02], speed=0.12) + self._go([p[0], p[1], max(zt - depth, TZ + 0.012)], speed=0.04, tol=0.003, max_steps=150) + sk.set_gripper(True, steps=15) + self._go([p[0], p[1], self.z_clear(0.10)], speed=0.15) + if self.held(name): + return True + sk.set_gripper(False, steps=10) + return False + + def put(self, name, xy, z_surface, gap, yaw=0.0): + """carry the held object over xy (its centre), straight down until its bottom is `gap` above z_surface, let + go, lift 8 cm""" + sk = self.sk + zc = max(self.z_clear(0.10), sk.eef_pos()[2]) + rel = self.centre(name)[:2] - sk.eef_pos()[:2] + q = np.asarray(xy, float) - rel + self._go([q[0], q[1], zc], yaw=yaw, speed=0.25) + sk.hold(5) + rel = self.centre(name)[:2] - sk.eef_pos()[:2] # the object can shift in the fingers while the wrist turns + q = np.asarray(xy, float) - rel + dz = sk.eef_pos()[2] - envs.obj_min_z(self.env, name) + zr = z_surface + dz + gap + self._go([q[0], q[1], zr + 0.03], speed=0.12) + self._go([q[0], q[1], zr], speed=0.04, tol=0.003, max_steps=150) + sk.set_gripper(False, steps=15) + cur = sk.eef_pos() + self._go([cur[0], cur[1], cur[2] + 0.08], speed=0.15) + self._settle(40) + + def free_spot(self, near_xy): + """a free place on the table (for a box taken off the pile): >= 11 cm from everything, off the mat, reachable""" + mat = np.asarray(self.inst["mat"]) + others = [self.centre(x)[:2] for x in BOXES + [CUP]] + best, bd = None, -1.0 + for r in (0.17, 0.21, 0.25, 0.29): + for a in np.radians(np.arange(0, 360, 15)): + p = mat + r * np.array([np.cos(a), np.sin(a)]) + if not (BOX_X[0] - 0.02 <= p[0] <= BOX_X[1] and abs(p[1]) <= BOX_YMAX + 0.02): + continue + d = min(float(np.linalg.norm(p - o)) for o in others) + if d >= 0.11: + return p + if d > bd: + best, bd = p, d + return best + + def place_on_pile(self, name, err, gap, rng, bias=0.0): + """put object `name` on the current pile top (or the mat) with a placement error of `err` (m, random direction)""" + ch = [b for b in self.pile() if b != name] + if ch: + # aims every box at the same spot (the bottom box), as an agent that computes the pile's x, y once: errors + # do not add up level by level + tgt = self.centre(ch[0])[:2].copy() + zs = envs.obj_max_z(self.env, ch[-1]) + else: + tgt = np.asarray(self.inst["mat"], float) + np.array([bias, 0.0]) + zs = TZ + if err: + a = rng.uniform(0, 2 * np.pi) + tgt = tgt + float(err) * np.array([np.cos(a), np.sin(a)]) + if not self.pick(name): + return False + self.put(name, tgt, zs, gap) + return True + + def lay_aside(self, name, rng): + if not self.pick(name): + return False + p = self.free_spot(self.centre(name)[:2]) + self.put(name, p, TZ, 0.01) + return True + + # ------------------------------------------------------------ scripted policies + def nearest_order(self): + mat = np.asarray(self.inst["mat"]) + return sorted(BOXES, key=lambda b: float(np.linalg.norm(self.centre(b)[:2] - mat))) + + def plan(self, params, rng): + if params.get("order") == "random": + order = [BOXES[i] for i in rng.permutation(4)] + else: + order = self.nearest_order() + soft = params.get("soft_known") + if soft: + order = [b for b in order if COL[b] != soft] + [b for b in order if COL[b] == soft] + return order + + def seen_soft(self): + """the box that visibly bent during this attempt (scripted perception of the kink in the images)""" + mk, mc = self.mon["max_kink"], self.mon["max_crush"] + for c in COLOURS: + if mk[c] > 15.0 or mc[c] > 0.3: + return c + return None + + def build(self, order, params, rng, first=True): + """stack `order` (boxes not yet in the pile) then the cup; returns 'ok', 'collapse' or 'fail'""" + err = params.get("err") + gap = params.get("gap", 0.005) + # a box that could not be picked up is tried again after the others (one more pass) + order = list(order) * 2 + for b in order: + if b in self.pile(): + continue + if params.get("soft_known") and COL[b] == params["soft_known"] and \ + sum(x in self.pile() for x in BOXES if COL[x] != params["soft_known"]) < len(BOXES) - 1: + continue # the soft box only goes on once the three others are in the pile + for _ in range(2): + n_b = len(self.mon["buckle_steps"]) + before = self.pile() + e = rng.uniform(*err) if err else 0.0 + if not self.place_on_pile(b, e, gap, rng, bias=params.get("bias", 0.0) if not before else 0.0): + break + after = self.pile() + if len(self.mon["buckle_steps"]) > n_b or any(x not in after for x in before): + return "collapse" + if b in after: + break + if len(self.pile()) < len(BOXES): + return "fail" + if self.cup_tilt() > np.radians(45): + return "fail" + for _ in range(2): + n_b = len(self.mon["buckle_steps"]) + before = self.pile() + e = rng.uniform(*err) if err else 0.0 + if not self.place_on_pile(CUP, e, gap, rng): + return "fail" + if len(self.mon["buckle_steps"]) > n_b or any(x not in self.pile() for x in before): + return "collapse" + if self.cup_on_pile(): + return "ok" + return "fail" + + def rebuild_soft_top(self, soft_colour, params, rng): + """take the soft box (and whatever is on it) off the pile, then stack the rigid boxes and the soft one last""" + soft = BOXES[COLOURS.index(soft_colour)] + for _ in range(6): + ch = self.pile() + if soft in ch: + self.lay_aside(ch[-1], rng) # from the top down to the soft box + elif self.on_mat(soft) or any(soft in self.items_on(b) for b in ch): + self.lay_aside(soft, rng) # bent / off-centre on the mat or on the pile + else: + break + order = [b for b in self.nearest_order() if b != soft] + [soft] + return self.build(order, dict(params, soft_known=soft_colour), rng) + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("noise_seed", 0)) + order = self.plan(params, rng) + res = self.build(order, params, rng) + if res == "collapse": + mode = params.get("on_collapse", "rebuild_same") + if mode == "rebuild_same": # the cheapest explanation: "I did not centre it" -> same order, more care + self.settle_scene() + res = self.build(order, dict(params, err=None, gap=0.005), rng) + elif mode == "identify": # sees which box bent and rebuilds with it on top + self.settle_scene() + soft = self.seen_soft() + if soft and self.cup_tilt() < np.radians(45): + res = self.rebuild_soft_top(soft, params, rng) + self._lift_to(self.z_clear(0.06)) + self.sk.hold(10) + return res + + NAIVE = dict(order="nearest", soft_known=None, on_collapse="rebuild_same") + + def default_params(self, inst): + """Sonnet-like: nearest box first, lifts above everything, straight down, lets go 1-4 cm above (per instance), + 0.4-1.3 cm placement errors, the first box up to 2 cm too far forward; after a collapse it rebuilds once in + the same order, more carefully""" + return dict(self.NAIVE, noise_seed=int(inst["seed"]) * 13, err=NAIVE_ERR, gap=float(inst["naive_gap"]), + bias=float(inst["naive_bias"])) + + def oracle_params(self, inst): + return dict(order="nearest", soft_known=inst["soft_colour"], on_collapse="identify", err=None, gap=0.005) + + def adapt_params(self, inst, history): + soft = None + for h in history: + ev = [e for e in h["outcome"]["events"] if e.get("event") == "buckle"] + if ev: + soft = ev[0]["box"] # the box seen bending (the kink is visible in the images) + return dict(self.default_params(inst), soft_known=soft, on_collapse="identify") + + def blind_params(self, inst, attempt, rng): + return dict(self.default_params(inst), order="random", noise_seed=int(rng.integers(1 << 30)), + gap=float(rng.uniform(*NAIVE_GAP)), bias=float(rng.uniform(*NAIVE_BIAS))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + single = ("oracle", "naive", "naive_centred", "oracle_noise", "naive_once", "naive_lying", "oracle_lying") + if kind in ("naive_lying", "oracle_lying") and inst["soft"]: + # control (v2): the soft carton starts lying on a side face, so it is stacked lying + inst = dict(inst, lying={inst["soft_colour"]: np.pi / 2}) + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": # attempt 1: naive habits, but it looks at the collapse and rebuilds soft-on-top + params = (dict(self.default_params(inst), on_collapse="identify") if a == 0 + else self.adapt_params(inst, history)) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": # control: cross-attempt learning only (no within-attempt identification) + params = self.default_params(inst) if a == 0 else dict(self.adapt_params(inst, history), + on_collapse="rebuild_same") + elif kind == "naive_centred": # control (R4): perfect centring, let go 5 mm above, no rebuild + params = dict(self.default_params(inst), err=None, gap=0.005, bias=0.0, on_collapse="none") + elif kind == "naive_once": # control: naive without the careful rebuild + params = dict(self.default_params(inst), on_collapse="none") + elif kind == "naive_lying": # control (v2): naive_once with the soft carton lying on a side face + params = dict(self.default_params(inst), on_collapse="none") + elif kind == "oracle_lying": # control (v2): soft carton lying, but on top (carries only the cup) + params = dict(self.oracle_params(inst)) + elif kind == "oracle_noise": # robustness: soft box on top with Sonnet-like imprecision + params = dict(self.default_params(inst), soft_known=inst["soft_colour"], on_collapse="identify") + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in single: + break + return history diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_tray_delivery.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_tray_delivery.py new file mode 100644 index 0000000000000000000000000000000000000000..e36d0bedffbe7e091b3fc8ae3c7c3e9f9508a53c --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_tray_delivery.py @@ -0,0 +1,883 @@ +"""LH tray_delivery v2 (long horizon, state restoration): load three bottles onto a tray in the loading area, then move +the loaded tray over a low threshold strip into the delivery area. Pushing the tray over the strip makes it rock, and +the top-heavy bottles fall; holding the tray by its handle while moving it does not. + +Family: long-horizon tasks in which the agent's own normal later-stage action physically breaks earlier progress +(docs/11). Stages: + S1-S3 stand the red / green / blue bottle upright on the tray while the tray is inside the yellow loading area; + S4 move the tray (with the bottles) over the black threshold strip completely into the purple delivery area. +Success (F1): at the end the tray (board and handle) is completely inside the delivery area, all three bottles stand +upright on it, the gripper does not touch them, the scene is static, AND the event log shows that all three bottles +stood on the tray at the same time while the tray was still completely inside the loading area (load first, then +deliver). Re-standing a fallen bottle on the tray after the move is allowed (counts as a restoration). + +v2 (2026-10-09, after the Sonnet 5.5 pilot lh1, see the task card): v1's 15.6 cm bottles on a 2.2 cm foot were hard to +grasp and to stand, the narrow handle was hard to push straight, "completely inside" needed 2 cm precision, and the +agents pushed at 3-5 cm/s, far below v1's 0.15 m/s topple threshold, so the hidden variable never mattered. Now: +- bottles 10.5 cm tall: 4 x 4 x 7.5 cm square body with a flat bottom + a 2.4 cm round neck (3 cm tall), 0.25 kg; +- T handle, 2.5 cm tall: a 16 cm push bar at the back (push it with the closed gripper) on a 3 cm wide, 5 cm long stem + (grasp it across its width); +- delivery area 28 x 42 cm for the 18.5 x 34 cm tray footprint (4.75 / 4 cm slack per side; v1: 2 / 3 cm); +- a black threshold strip between the areas (a rounded sill 1 cm high, 5.3 cm wide, 46 cm long) that the tray has to + cross. Measured: with stocky bottles speed alone cannot be the lever (on a flat table a top-heavy bottle stayed up in + closed-gripper pushes up to 0.3 m/s; only the controller's top speed, ~0.65 m/s, toppled it). On the sill the tray + first climbs (front up ~5 deg), then rocks over the crest under gravity; when it is pushed, nothing holds its trailing + edge, which jumps up (max tray tilt 7.2-9.3 deg) and the top-heavy bottles fall over the leading edge, + at every push speed tried (2-6 cm/s and the top speed). When the stem is grasped, the hand holds the trailing edge + (max tilt 5.7-7.5 deg) and nothing falls. A hand hovering right over the handle (3 cm handle pushed with the + grasp point ~1 cm above the table) also held it down; hence the 2.5 cm handle. +- failure codes report the first unmet requirement: not_loaded / order / bottle_fallen / bottle_off_tray / + not_delivered / held / not_static. + +Scene: wooden tray = an 11 x 34 x 1.2 cm board, long side running forward / back, with the T handle sticking out of the +middle of the long side that faces away from the delivery area; three bottles (same shape, red / green / blue) standing +in a row on the table on the far side of the loading area; two painted rectangles (no collision): yellow loading area +(tray inside it at the start) and purple delivery area 32-34 cm (centre to centre) to its left or right (random); the +threshold strip lies across the path in the gap between them. The tray travels sideways (the arm's comfortable +workspace is wide in y but short in x). + +Hidden variable (same appearance): each bottle's centre-of-mass height (an invisible internal weight, 85 % of its +mass): "stable" 2.0-3.5 cm, "top-heavy" 6.6-7.6 cm above the bottom; 0 / 1 / 2 top-heavy bottles with p = 0.35 / 0.40 / +0.25. Measured on 28 instances (scripted loading, same loaded state for every move): closed-gripper pushes (2, 3, 4.5, +6 cm/s, top speed, 3 stops, slow approach; agent-style pushes through the tool layer with the grasp point 1.0 / 1.3 / +2.5 cm above the table) toppled 24/24 top-heavy bottles and 0/60 stable ones in every variant; grasp-and-drag at 2 and +4.5 cm/s toppled 0/84. Above a COM of 8 cm falling bottles sometimes land standing on their neck (cannot be stood up +again with yaw-only control without first knocking them over), so the range stops at 7.6 cm. Tray-table friction +0.45-0.60 is a nuisance variable; the sill's own friction (0.4) wins in its contacts (with the tray's 0.85 the tray +jammed at the sill and jumped over it, toppling nothing). +Restoration: a fallen bottle can be stood up again: grasp its round neck (fingers closing across the neck), lift it -- +it swings down and hangs from the neck -- and set it down on the tray. + +Simulation notes (as in v1): COM heights are set at reset through body_ipos / inertia and the bottle's collision BVH is +shifted with it (MuJoCo keeps it in the inertial frame); the tray uses the table's soft contact (solref 0.02); the +bottles' own contacts are stiffer (solref 0.005) so a bottle lowered onto the board by its neck is not pressed through. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +SOFT = 'solimp="0.9 0.95 0.001" solref="0.02 1"' # the LIBERO table's contact parameters + +# bottle: square body with a flat 4 x 4 cm bottom + round neck; body origin at the middle of the total height +BODY = (0.020, 0.020, 0.0375) # half sizes of the body (4 x 4 x 7.5 cm) +NECK_R, NECK_H = 0.012, 0.015 # neck radius, half height (2.4 cm wide, 3 cm tall) -> 10.5 cm in total +BH = BODY[2] + NECK_H # half of the total height +DAMP_BOT = 0.003 # free-joint damping of the bottles (air drag; damps the swing of a bottle hanging from its neck) +BOT_MASS = 0.25 +W_FRAC = 0.85 # share of the mass in the hidden internal weight +MU_BOT = 1.0 +COS_UP = 0.95 # upright: long axis within ~18 deg of vertical +BOT_SOLREF = (0.005, 1.0) # the bottles win in all their contacts (priority 3) +BOT_SOLIMP = (0.95, 0.99, 0.001, 0.5, 2.0) + +# tray: board + T handle (stem + cross bar) sticking out of the middle of the trailing long side (tray frame -x) +PLATE = (0.055, 0.17, 0.006) # 11 x 34 x 1.2 cm board +STEM = (0.025, 0.015, 0.0125) # 5 long x 3 wide x 2.5 cm tall: grasp it across its width +CROSS = (0.0125, 0.08, 0.0125) # 2.5 deep x 16 wide x 2.5 cm tall bar at the back: push it with the closed gripper +# Handle height 2.5 cm (measured on 6 instances x 6 push heights, see the card): the Panda palm reaches ~3-4 cm ahead +# of the fingers and ~2 cm above the grasp point. With a 3 cm handle a hand pushing low (grasp point ~1 cm above the +# table) hovered right over the handle and kept the trailing edge from jumping up on the sill (like a grasp: no topple +# in 3/6); with 2.5 cm every push with the grasp point 1-2.5 cm above the table toppled the top-heavy bottles (36/36). +# A hand pushing at >= 3 cm only touches the handle with its fingertips and can slide over it. +PLATE_TOP = envs.TABLE_Z + 2 * PLATE[2] +BACK_X = -PLATE[0] - 2 * STEM[0] - 2 * CROSS[0] # tray-frame x of the handle's back face (-0.13) +FOOT_DX = (PLATE[0] + BACK_X) / 2 # x of the footprint centre (board + handle) relative to the board centre +# slots 1.5 cm towards the leading edge: a hand grasping the cross bar with its long side along the travel direction +# (palm 10.5 cm ahead of the grasp point) still clears the middle bottle by ~7 mm +SLOT_LX = 0.015 +SLOT_LY = (-0.12, 0.0, 0.12) +MU_HANDLE = 0.6 + +# painted areas (inner half sizes: along travel, along the tray's long side) +LOAD_IN = (0.1125, 0.20) # tray footprint 18.5 x 34 cm -> 2 / 3 cm slack per side +DELIV_IN = (0.14, 0.21) # -> 4.75 / 4 cm slack per side +LINE_W = 0.008 +AREA_DIST = (0.32, 0.34) # centre to centre + +# threshold strip: a capsule lying across the path, sunk into the table so that it sticks out RIDGE_H (a rounded sill +# 2 * sqrt(2 R h - h^2) = 5.3 cm wide) +RIDGE_H = 0.010 +RIDGE_R = 0.040 +RIDGE_HL = 0.23 # half length of the straight part (46 cm: longer than the tray) +MU_RIDGE = 0.4 # wins in its contacts (priority 4) + +BOTTLES = ("bottle_red_1", "bottle_green_1", "bottle_blue_1") +COLOR_OF = {"bottle_red_1": "red", "bottle_green_1": "green", "bottle_blue_1": "blue"} +RGBA = {"red": (0.82, 0.12, 0.10, 1.0), "green": (0.12, 0.60, 0.20, 1.0), "blue": (0.12, 0.30, 0.85, 1.0)} +TRAY = "tray_1" +LOAD, DELIVER, RIDGE = "load_area_1", "deliver_area_1", "threshold_1" + +# hidden COM heights above the bottle's bottom (m); calibration in the task card +HC_STABLE = (0.020, 0.035) +HC_TOPHEAVY = (0.066, 0.076) +N_TOP_P = (0.35, 0.40, 0.25) # P(0 / 1 / 2 top-heavy bottles) +MU_TRAY = (0.45, 0.60) + +DEBOUNCE = 5 # control steps a predicate must keep a new value before an event is recorded (0.25 s) + +# scripted reference moves +V_NAIVE = 0.045 # the pilot agents pushed at 3-6 cm/s +V_CAREFUL = 0.02 # the LA interface's slowest speed +GRASP_TOP = 0.012 # scripted grasp point: on the neck, this far below the bottle's top (the palm is ~2 cm above it) +SAFE_Z = envs.TABLE_Z + 0.17 # scripted transits: fingertips ~5 cm above the tops of bottles standing on the tray +SAFE_Z_HELD = envs.TABLE_Z + 0.25 # ... and with a bottle hanging from the gripper: its bottom ~4 cm above them +PUSH_Z = envs.TABLE_Z + 0.015 # closed-gripper pushes: grasp point 1.5 cm above the table (fingertips ~0.5 cm) +DRAG_Z = envs.TABLE_Z + 0.015 # grasping the stem: finger pads over its whole height + + +def bottle_xml(name, rgba): + zb = -BH + BODY[2] + zn = -BH + 2 * BODY[2] + NECK_H + neck_rgba = tuple(0.8 * c for c in rgba[:3]) + (1.0,) + parts = [("box", zb, _fmt(BODY), rgba), ("cylinder", zn, f"{NECK_R:.5f} {NECK_H:.5f}", neck_rgba)] + gs = [] + for k, (typ, z, size, c) in enumerate(parts): + gs.append(f' ') + gs.append(f' ') + return _wrap(name, "\n".join(gs), BH, float(np.hypot(BODY[0], BODY[1]))) + + +def tray_xml(name, rgba=(0.62, 0.45, 0.27, 1.0)): + hz = -PLATE[2] + STEM[2] # handle bottom flush with the board's bottom + sp = (-PLATE[0] - STEM[0], 0.0, hz) + cp = (-PLATE[0] - 2 * STEM[0] - CROSS[0], 0.0, hz) + hrgba = (0.30, 0.20, 0.12, 1.0) + gs = [] + for k, (p, s, c, mu) in enumerate((((0, 0, 0), PLATE, rgba, 0.6), (sp, STEM, hrgba, MU_HANDLE), + (cp, CROSS, hrgba, MU_HANDLE))): + gs.append(f' ') + gs.append(f' ') + return _wrap(name, "\n".join(gs), PLATE[2], float(np.hypot(PLATE[0] - BACK_X, PLATE[1]))) + + +def area_xml(name, inner, fill, line): + """Flat, visual-only rectangle painted on the table (light fill + dark outline, no collisions).""" + ix, iy = inner + ox, oy = ix + LINE_W, iy + LINE_W + parts = [((0, 0, 0.0004), (ox, oy, 0.0004), fill), + ((0, iy + LINE_W / 2, 0.0010), (ox, LINE_W / 2, 0.0002), line), + ((0, -iy - LINE_W / 2, 0.0010), (ox, LINE_W / 2, 0.0002), line), + ((ix + LINE_W / 2, 0, 0.0010), (LINE_W / 2, oy, 0.0002), line), + ((-ix - LINE_W / 2, 0, 0.0010), (LINE_W / 2, oy, 0.0002), line)] + g = "\n".join(f' ' for p, sz, c in parts) + return _wrap(name, g, 0.0012, float(np.hypot(ox, oy))) + + +def sill_xml(name, rgba=(0.12, 0.12, 0.13, 1.0)): + """the threshold strip: a capsule along the fixture's local y (quat turns z into y), origin on its axis; the + fixture is placed with the axis RIDGE_R - RIDGE_H below the table top (static: no contacts with the table)""" + q = "0.70711 0.70711 0 0" + g = (f' \n' + f' ') + return _wrap(name, g, RIDGE_R, RIDGE_HL + RIDGE_R) + + +def _rotz2(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s], [s, c]]) + + +def _yaw_of(R): + return float(np.arctan2(R[1, 0], R[0, 0])) + + +class TraySkills(Skills): + """Skills whose every control step feeds the task's stage monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class TrayDelivery(LFFTask): + name = "lh_tray_delivery" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Plan") + protocol = "cross" + max_attempts = 3 + # scripted primitives (~ agent commands): careful oracle 37; naive push + same-attempt repair of 1-2 bottles 46-63 + agent_max_steps = 110 + instruction = ("Load the red, green and blue bottles onto the wooden tray: stand each bottle upright on the tray " + "while the tray is still inside the yellow loading area. Only after all three bottles are on the " + "tray, move the tray with the bottles on it over the black threshold strip into the purple " + "delivery area. At the end the whole tray, including its handle, must be inside the purple area " + "with all three bottles standing upright on it.") + instruction_indirect = ("Stand the three bottles up on the wooden board that lies in the yellow rectangle while " + "the board is still there; then bring the board with the bottles on it across the black " + "strip into the purple rectangle. At the end the whole board, including its dark handle, " + "must lie inside the purple rectangle with all three bottles standing on it.") + agent_object_names = ["red bottle", "green bottle", "blue bottle", "wooden tray", "yellow loading area", + "purple delivery area", "black threshold strip"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs = [] + for i, b in enumerate(BOTTLES): + c = COLOR_OF[b] + cat = register_generated(f"LffTdBottle{c.capitalize()}", bottle_xml(f"lff_td_bottle_{c}", RGBA[c])) + x0 = -0.25 + 0.12 * i + objs.append((b, cat, f"bottle_{c}_region", (x0, 0.30, x0 + 0.01, 0.31))) + tray = register_generated("LffTdTray", tray_xml("lff_td_tray")) + objs.append((TRAY, tray, "tray_region", (0.0, -0.05, 0.01, -0.04))) + load = register_generated("LffTdLoadArea", area_xml("lff_td_load_area", LOAD_IN, (0.98, 0.93, 0.55, 1.0), + (0.85, 0.62, 0.05, 1.0)), free=False) + deliv = register_generated("LffTdDeliverArea", area_xml("lff_td_deliver_area", DELIV_IN, + (0.86, 0.78, 0.95, 1.0), (0.45, 0.20, 0.65, 1.0)), + free=False) + sill = register_generated("LffTdThreshold", sill_xml("lff_td_threshold"), free=False) + fx = [(LOAD, load, "load_region", (-0.21, -0.41, -0.20, -0.40)), + (DELIVER, deliv, "deliver_region", (0.15, -0.41, 0.16, -0.40)), + (RIDGE, sill, "threshold_region", (0.15, 0.38, 0.16, 0.39))] + return write_bddl(self.name, self.instruction, objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + env = self.env + m = env.sim.model + self.area_bid = {a: m.body_name2id(env.fixtures_dict[a].root_body) for a in (LOAD, DELIVER, RIDGE)} + self.bid = {n: envs.body_id(env, n) for n in BOTTLES + (TRAY,)} + mm = m._model + self._bvh0 = {} + for b in BOTTLES: # compiled inertial frame + BVH (shifted with the hidden COM at every reset) + bid = self.bid[b] + adr, num = mm.body_bvhadr[bid], mm.body_bvhnum[bid] + self._bvh0[b] = (m.body_ipos[bid].copy(), mm.bvh_aabb[adr:adr + num].copy(), adr, num) + # geom -> object index for the contact checks (0..2 bottles, 3 tray) + self._obj_of = np.full(m.ngeom, -1, int) + for k, n in enumerate(BOTTLES + (TRAY,)): + self._obj_of[envs.obj_geom_ids(env, n)] = k + self._is_robot = np.zeros(m.ngeom, bool) + self._is_robot[envs.robot_geom_ids(env)] = True + sb = self.area_bid[RIDGE] + self._is_sill = np.array([m.geom_bodyid[g] == sb or m.body_parentid[m.geom_bodyid[g]] == sb + for g in range(m.ngeom)], bool) + self._dof = {n: envs.free_joint_addr(env, n)[1] for n in BOTTLES + (TRAY,)} + self.inst = None + self.mon = None + + def sample_instance(self, seed): + """Layout: the tray's long side runs forward / back (world x); it travels sideways (world y) from the loading + area to the delivery area, 32-34 cm centre to centre, to the left or to the right, over the threshold strip in + the middle of the gap between the areas. The bottles stand in a row on the table on the far side of the + loading area. Tray frame: local +x = direction of travel, handle at local -x.""" + rng = np.random.default_rng(seed) + s = 1.0 if rng.random() < 0.5 else -1.0 # +1: the tray travels to the robot's left (+y) + xl, yl = float(rng.uniform(-0.18, -0.15)), float(-s * rng.uniform(0.11, 0.13)) + dist = float(rng.uniform(*AREA_DIST)) + deliver = [xl + float(rng.uniform(-0.01, 0.01)), yl + s * dist] + yaw = s * np.pi / 2 + R = _rotz2(yaw) + g0, g1 = LOAD_IN[0] + LINE_W, dist - DELIV_IN[0] - LINE_W # the gap between the areas, along travel + sill_xy = [(xl + deliver[0]) / 2, float((np.array([xl, yl]) + R @ np.array([(g0 + g1) / 2, 0.0]))[1])] + jit = np.array([rng.uniform(-0.008, 0.008), rng.uniform(-0.005, 0.005)]) # tray frame + tray_xy = (np.array([xl, yl]) + R @ (np.array([-FOOT_DX, 0.0]) + jit)).tolist() + order = [int(i) for i in rng.permutation(3)] # bottle -> position in the start row (along x) + by = yl - s * (LOAD_IN[0] + LINE_W + 0.04) + start = {} + for k, b in enumerate(BOTTLES): + start[b] = [xl + (-0.12, 0.0, 0.12)[order[k]] + float(rng.uniform(-0.008, 0.008)), + by + float(rng.uniform(-0.005, 0.005)), float(rng.uniform(-0.35, 0.35))] + n_top = int(rng.choice(3, p=N_TOP_P)) + top = set(int(i) for i in rng.choice(3, n_top, replace=False)) + hc = {b: float(rng.uniform(*(HC_TOPHEAVY if k in top else HC_STABLE))) for k, b in enumerate(BOTTLES)} + return dict(seed=int(seed), travel="left" if s > 0 else "right", area_yaw=float(yaw), load_xy=[xl, yl], + deliver_xy=deliver, sill_xy=sill_xy, tray_xy=tray_xy, tray_yaw=float(yaw), bottle_start=start, + com_height=hc, top_heavy=[b for k, b in enumerate(BOTTLES) if k in top], + mu_tray=float(rng.uniform(*MU_TRAY))) + + def _set_com(self, b, hc): + """Hidden internal weight: bottle COM at height hc above its bottom (mass and inertia consistent).""" + m = self.env.sim.model + mm = m._model + bid = self.bid[b] + a, c = BODY[0], BODY[2] + vb, vn = 8 * a * a * c, np.pi * NECK_R ** 2 * 2 * NECK_H + zs = ((-BH + c) * vb + (-BH + 2 * c + NECK_H) * vn) / (vb + vn) # shell COM (origin: middle of the height) + ms, mw = BOT_MASS * (1 - W_FRAC), BOT_MASS * W_FRAC + zw = float(np.clip((BOT_MASS * (hc - BH) - ms * zs) / mw, -BH + 0.01, BH - 0.01)) + zc = (ms * zs + mw * zw) / BOT_MASS + ww = 0.025 # the weight is a 2.5 cm cube + Ixx = ms / 3 * (a * a + c * c) + ms * (zs - zc) ** 2 + mw * (zw - zc) ** 2 + mw * ww * ww / 6 + Izz = ms * 2 * a * a / 3 + mw * ww * ww / 6 + m.body_mass[bid] = BOT_MASS + m.body_ipos[bid] = [0.0, 0.0, zc] + m.body_iquat[bid] = [1.0, 0.0, 0.0, 0.0] + m.body_inertia[bid] = [Ixx, Ixx, Izz] + ip0, A0, adr, num = self._bvh0[b] + mm.bvh_aabb[adr:adr + num, :3] = A0[:, :3] - (m.body_ipos[bid] - ip0) # BVH lives in the inertial frame + return zc + BH + + def apply_instance(self, inst): + self.inst = inst + env = self.env + m = env.sim.model + ya = inst["area_yaw"] + qa = [np.cos(ya / 2), 0.0, 0.0, np.sin(ya / 2)] + for a, key in ((LOAD, "load_xy"), (DELIVER, "deliver_xy")): + m.body_pos[self.area_bid[a]] = [inst[key][0], inst[key][1], envs.TABLE_Z + 0.0002] + m.body_quat[self.area_bid[a]] = qa + m.body_pos[self.area_bid[RIDGE]] = [inst["sill_xy"][0], inst["sill_xy"][1], envs.TABLE_Z + RIDGE_H - RIDGE_R] + m.body_quat[self.area_bid[RIDGE]] = qa + for g in np.flatnonzero(self._is_sill): # the sill's friction wins (the tray's would otherwise: priority 2) + m.geom_friction[g] = [MU_RIDGE, 0.005, 0.0001] + m.geom_priority[g] = 4 + envs.set_obj_pose(env, TRAY, [inst["tray_xy"][0], inst["tray_xy"][1], envs.TABLE_Z + PLATE[2] + 0.0005], + yaw=inst["tray_yaw"]) + envs.set_friction(env, TRAY, inst["mu_tray"], priority=2) + for b in BOTTLES: + self._set_com(b, inst["com_height"][b]) + for g in envs.obj_geom_ids(env, b): # bottle params win in all its contacts (tray, table, fingers) + m.geom_friction[g] = [MU_BOT, 0.005, 0.0001] + m.geom_condim[g] = 3 + m.geom_priority[g] = 3 + m.geom_solref[g] = BOT_SOLREF + m.geom_solimp[g] = BOT_SOLIMP + m.dof_damping[self._dof[b]:self._dof[b] + 6] = DAMP_BOT + x, y, yaw = inst["bottle_start"][b] + envs.set_obj_pose(env, b, [x, y, envs.TABLE_Z + BH + 0.0005], yaw=yaw) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = TraySkills(self.env, self, recorder=recorder) + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ geometry / predicates + def tray_pose(self): + d = self.env.sim.data + bid = self.bid[TRAY] + return d.body_xpos[bid].copy(), d.body_xmat[bid].reshape(3, 3).copy() + + def tray_footprint(self): + p, R = self.tray_pose() + loc = np.array([[PLATE[0], PLATE[1]], [PLATE[0], -PLATE[1]], [-PLATE[0], PLATE[1]], [-PLATE[0], -PLATE[1]], + [BACK_X, CROSS[1]], [BACK_X, -CROSS[1]]]) + return p[:2] + loc @ R[:2, :2].T + + @staticmethod + def _word(v): + """robot-centric word for a horizontal world direction""" + if abs(v[0]) >= abs(v[1]): + return "forward" if v[0] > 0 else "back" + return "left" if v[1] > 0 else "right" + + def area_excess(self, key): + """How far the tray footprint sticks out of the area (m, >0 = outside) per edge, keyed by robot-centric word.""" + c = np.asarray(self.inst[key]) + Ra = _rotz2(self.inst["area_yaw"]) + pts = (self.tray_footprint() - c) @ Ra # area frame + inner = LOAD_IN if key == "load_xy" else DELIV_IN + out = {} + for axis, sign in ((0, 1), (0, -1), (1, 1), (1, -1)): + u = np.zeros(2) + u[axis] = sign + out[self._word(Ra @ u)] = float((sign * pts[:, axis]).max() - inner[axis]) + return out + + def tray_inside(self, key): + return max(self.area_excess(key).values()) <= 0.0 + + def _contacts(self): + d = self.env.sim.data + n = d.ncon + if not n: + return np.zeros(0, int), np.zeros(0, int) + return np.asarray(d.contact.geom1)[:n], np.asarray(d.contact.geom2)[:n] + + def robot_touch(self): + """indices (0..2 bottles, 3 tray) of the objects the robot touches now""" + g1, g2 = self._contacts() + hit = np.concatenate([self._obj_of[g2[self._is_robot[g1]]], self._obj_of[g1[self._is_robot[g2]]]]) + return set(int(i) for i in hit[hit >= 0]) + + def tray_on_sill(self): + g1, g2 = self._contacts() + tray = self._obj_of == 3 + return bool(np.any((tray[g1] & self._is_sill[g2]) | (tray[g2] & self._is_sill[g1]))) + + def bottle_state(self, b, touched=False): + d = self.env.sim.data + bid = self.bid[b] + p = d.body_xpos[bid] + up = float(d.body_xmat[bid].reshape(3, 3)[2, 2]) + tp, R = self.tray_pose() + loc = R.T @ (p - tp) + on_xy = abs(loc[0]) <= PLATE[0] and abs(loc[1]) <= PLATE[1] + resting = abs(loc[2] - (PLATE[2] + BH)) < 0.012 + upright = up >= COS_UP + return dict(upright=bool(upright), on_tray=bool(on_xy and resting), touched=bool(touched), + ok=bool(upright and on_xy and resting and not touched), loc=loc, pos=p.copy(), cos=up) + + def predicates(self): + t = self.robot_touch() + st = {b: self.bottle_state(b, k in t)["ok"] for k, b in enumerate(BOTTLES)} + st["tray_in_delivery"] = self.tray_inside("deliver_xy") + st["tray_in_loading"] = self.tray_inside("load_xy") + return st, t + + def _tray_speed(self): + da = self._dof[TRAY] + return float(np.linalg.norm(self.env.sim.data.qvel[da:da + 2])) + + # ------------------------------------------------------------ monitor + def _init_monitor(self): + st, _ = self.predicates() + self.mon = dict(stable=dict(st), cnt={k: 0 for k in st}, ever=set(k for k, v in st.items() if v), + lost=set(), events=[], order_step=None, last_touch={k: -10 ** 6 for k in range(4)}, + last_tray_move=-10 ** 6, last_sill=-10 ** 6, tray_vmax_loaded=0.0, left_unloaded=None, + on_in_loading=set()) + + def monitor_step(self): + mon = self.mon + if mon is None: + return + n = self.sk.n_steps + st, touch = self.predicates() + for k in touch: + mon["last_touch"][k] = n + v = self._tray_speed() + if v > 0.01: + mon["last_tray_move"] = n + if self.tray_on_sill(): + mon["last_sill"] = n + if all(mon["stable"][b] for b in BOTTLES): + mon["tray_vmax_loaded"] = max(mon["tray_vmax_loaded"], v) + for k, val in st.items(): + if val == mon["stable"][k]: + mon["cnt"][k] = 0 + continue + mon["cnt"][k] += 1 + if mon["cnt"][k] < DEBOUNCE: + continue + mon["stable"][k] = val + mon["cnt"][k] = 0 + step = n - DEBOUNCE + 1 + if val: + ev = "restored" if k in mon["lost"] else "achieved" + mon["ever"].add(k) + mon["events"].append(dict(step=step, pred=k, ev=ev)) + else: + mon["lost"].add(k) + e = dict(step=step, pred=k, ev="lost") + if k == "tray_in_loading" and mon["order_step"] is None and mon["left_unloaded"] is None: + mon["left_unloaded"] = step # the tray left the loading area before it was loaded + if k in BOTTLES: + j = BOTTLES.index(k) + moving = n - mon["last_tray_move"] <= 30 + # tray motion first: a bottle toppled by the move often falls against the moving hand + e["cause"] = ("threshold" if moving and n - mon["last_sill"] <= 40 else + "tray_moving" if moving else + "robot" if n - mon["last_touch"][j] <= 20 else "other") + # a bottle taken off (or knocked off by the robot) while the tray is still in the loading area: + # the tray is no longer loaded -> the order latch has to be earned again (unload / reload trick) + if (e["cause"] not in ("threshold", "tray_moving") and mon["stable"]["tray_in_loading"] + and mon["order_step"] is not None): + mon["order_step"] = None + mon["lost"].add("loaded_in_loading_area") + mon["events"].append(e) + e = dict(step=step, pred="loaded_in_loading_area", ev="lost") + mon["events"].append(e) + if mon["stable"]["tray_in_loading"]: + mon["on_in_loading"] |= {b for b in BOTTLES if mon["stable"][b]} + if mon["order_step"] is None and mon["stable"]["tray_in_loading"] and all(mon["stable"][b] for b in BOTTLES): + mon["order_step"] = n + mon["events"].append(dict(step=n, pred="loaded_in_loading_area", + ev="restored" if "loaded_in_loading_area" in mon["lost"] else "achieved")) + + # ------------------------------------------------------------ outcome / F2 + def _static(self): + d = self.env.sim.data + for nm in BOTTLES + (TRAY,): + da = self._dof[nm] + if np.linalg.norm(d.qvel[da:da + 3]) > 0.01 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.15: + return False + return True + + def _where(self, b, bs): + """robot-centric description of where a bottle is (relative to the tray)""" + if bs["on_tray"]: + return "on the tray" + tp, R = self.tray_pose() + lx, ly = R[:2, :2].T @ (bs["pos"][:2] - tp[:2]) + if abs(lx) <= PLATE[0] and abs(ly) <= PLATE[1]: + return "on the tray" + if abs(lx) <= PLATE[0] + 0.04 and abs(ly) <= PLATE[1] + 0.04: + return "partly on the tray" + v = R[:2, 0] * np.sign(lx) if abs(lx) - PLATE[0] >= abs(ly) - PLATE[1] else R[:2, 1] * np.sign(ly) + side = {"forward": "in front of", "back": "behind", "left": "to the left of", + "right": "to the right of"}[self._word(v)] + return f"on the table, {side} the tray" + + @staticmethod + def _names(bs): + cols = [COLOR_OF[b] for b in bs] + if len(cols) == 1: + return f"the {cols[0]} bottle" + return "the " + ", the ".join(cols[:-1]) + f" and the {cols[-1]} bottles" + + def outcome(self, inst): + sk = self.sk + sk.hold(30) # let everything settle (keeps the gripper as it is) + mon = self.mon + touch = self.robot_touch() + bst = {b: self.bottle_state(b, k in touch) for k, b in enumerate(BOTTLES)} + delivered = self.tray_inside("deliver_xy") + static = self._static() + order_ok = mon["order_step"] is not None + all_ok = all(s["ok"] for s in bst.values()) + success = bool(order_ok and delivered and all_ok and static) + ev = mon["events"] + stage_preds = set(BOTTLES) | {"tray_in_delivery"} + n_reg = sum(1 for e in ev if e["ev"] == "lost" and e["pred"] in stage_preds) + n_res = sum(1 for e in ev if e["ev"] == "restored" and e["pred"] in stage_preds) + fell_moving = sorted({e["pred"] for e in ev if e["ev"] == "lost" and e.get("cause") in ("threshold", + "tray_moving")}) + fell_sill = sorted({e["pred"] for e in ev if e["ev"] == "lost" and e.get("cause") == "threshold"}) + fallen = [b for b in BOTTLES if not bst[b]["upright"]] + off = [b for b in BOTTLES if bst[b]["upright"] and not bst[b]["on_tray"]] + held = [b for b in BOTTLES if bst[b]["upright"] and bst[b]["on_tray"] and bst[b]["touched"]] + # failure code = the first unmet requirement, in task order: loading -> order -> bottles -> delivery -> rest + if not order_ok: + failure = "order" if mon["left_unloaded"] is not None else "not_loaded" + elif fallen: + failure = "bottle_fallen" + elif off: + failure = "bottle_off_tray" + elif not delivered: + failure = "not_delivered" + elif held: + failure = "held" + elif not static: + failure = "not_static" + else: + failure = None + # F2 text (robot-centric words, no coordinates); the first sentence names the failure + parts = [] + if failure == "not_loaded": + missing = [b for b in BOTTLES if b not in mon["on_in_loading"]] + parts.append(f"Loading was not completed: {self._names(missing)} never stood on the tray while it was in " + f"the yellow loading area." if missing else + "Loading was not completed: the three bottles never stood on the tray at the same time while " + "it was in the yellow loading area.") + elif failure == "order": + parts.append("The tray left the yellow loading area before all three bottles stood on it (load all three " + "first, then move the loaded tray).") + bottle_txt = [] + for b in BOTTLES: + s, col = bst[b], COLOR_OF[b] + if s["ok"]: + bottle_txt.append(f"The {col} bottle stands upright on the tray.") + elif not s["upright"]: + bottle_txt.append(f"The {col} bottle has fallen over and lies {self._where(b, s)}.") + elif not s["on_tray"]: + bottle_txt.append(f"The {col} bottle stands upright {self._where(b, s)}, not on the tray.") + else: + bottle_txt.append(f"The {col} bottle stands on the tray but the gripper is still touching it.") + if delivered: + tray_txt = "The tray is completely inside the purple delivery area." + else: + ex = self.area_excess("deliver_xy") + out = [f"{max(100 * v, 0.1):.1f} cm beyond its {k} edge" for k, v in ex.items() if v > 0] + tray_txt = "The tray is not completely inside the purple delivery area: it sticks out " + \ + " and ".join(out) + "." + if failure in ("not_delivered",): + parts += [tray_txt] + bottle_txt + else: + parts += bottle_txt + [tray_txt] + if fell_moving: + how = " while the tray crossed the threshold strip" if fell_sill == fell_moving else \ + " while the tray was moving" + txt = self._names(fell_moving) + parts.append(txt[0].upper() + txt[1:] + f" fell over{how}.") + if failure == "not_static": + parts.append("Something was still moving at the end.") + return dict(success=success, failure=failure, + stages={**{COLOR_OF[b]: bool(bst[b]["ok"]) for b in BOTTLES}, "tray_in_delivery": bool(delivered), + "loaded_in_loading_area": bool(order_ok), "static": bool(static)}, + events=list(ev), n_regressions=int(n_reg), n_restored=int(n_res), + order_step=mon["order_step"], left_loading_unloaded=mon["left_unloaded"], + tray_vmax_loaded=round(mon["tray_vmax_loaded"], 3), + fell_while_moving=[COLOR_OF[b] for b in fell_moving], + fell_at_threshold=[COLOR_OF[b] for b in fell_sill], detail=" ".join(parts)) + + # ------------------------------------------------------------ scripted primitives (move_to + gripper only) + def _slot_world(self, j): + tp, R = self.tray_pose() + return tp[:2] + R[:2, :2] @ np.array([SLOT_LX, SLOT_LY[j]]) + + @staticmethod + def _yaw_window(a): + """the gripper-symmetric equivalent of yaw `a` in [-0.5, pi - 0.5) (keeps the last wrist joint off its limit)""" + return float((a + 0.5) % np.pi - 0.5) + + def tray_yaw(self): + return _yaw_of(self.tray_pose()[1]) + + def transit(self, xy, z, yaw=None, z_safe=SAFE_Z): + """up to z_safe (if lower), across, then down to z""" + sk = self.sk + e = sk.eef_pos() + if e[2] < z_safe - 0.01: + sk.move_to([e[0], e[1], z_safe], speed=0.3) + sk.move_to([xy[0], xy[1], z_safe], yaw=None if yaw is None else self._yaw_window(yaw), wrap_yaw=False) + sk.move_to([xy[0], xy[1], z], tol=0.003, max_steps=200) + + def _travel_dir(self): + tp, R = self.tray_pose() + u = R[:2, 0] / np.linalg.norm(R[:2, 0]) + foot = tp[:2] + R[:2, :2] @ np.array([FOOT_DX, 0.0]) + return tp, R, u, float((np.asarray(self.inst["deliver_xy"]) - foot) @ u) + + def push_tray(self, speed, gap=0.03, segments=1, z=PUSH_Z, yaw=None, approach=None): + """the pilot agents' move: closed gripper `gap` behind the handle's cross bar (hand's long side along the bar), + push along the travel direction until the footprint centre is level with the delivery area's centre; + `segments` > 1 stops in between; `approach` (m/s): first creep up to the bar at that speed, stop, then push""" + sk = self.sk + tp, R, u, dist = self._travel_dir() + back = tp[:2] + R[:2, :2] @ np.array([BACK_X, 0.0]) + if yaw is None: # yaw 0 = fingers closing along world y; this yaw puts the hand's long side across u + yaw = float(np.arctan2(u[1], u[0])) + s0 = back - u * (0.012 + gap) # the closed fingers are ~2.4 cm thick along the push + sk.set_gripper(True, steps=8) + self.transit(s0, z, yaw=yaw) + if approach: + s0 = back - u * 0.010 # just touching + sk.move_to([s0[0], s0[1], z], speed=approach, tol=0.003, max_steps=int(gap / approach / 0.05) + 40) + sk.hold(6) + gap = 0.0 + total = gap + dist + for k in range(segments): + e = s0 + u * total * (k + 1) / segments + sk.move_to([e[0], e[1], z], speed=speed, tol=0.004, + max_steps=int(total / segments / speed / 0.05) + 60 if speed else 250) + sk.hold(6) + e = sk.eef_pos()[:2] - u * 0.03 + sk.move_to([e[0], e[1], z], speed=0.1) + sk.move_to([e[0], e[1], z + 0.15], speed=0.25) + + def drag_tray(self, speed, z=DRAG_Z, cross=False): + """the careful move: grasp the handle and move the tray with it (the hand keeps the trailing edge down on the + sill). Default: the stem, fingers closing across its 3 cm width (hand's long side along the tray's long side); + cross=True: the cross bar, fingers closing across its 2.5 cm depth (hand's long side along the travel).""" + sk = self.sk + tp, R, u, dist = self._travel_dir() + lx = -PLATE[0] - 2 * STEM[0] - CROSS[0] if cross else -PLATE[0] - STEM[0] + c = tp[:2] + R[:2, :2] @ np.array([lx, 0.0]) + yaw = float(np.arctan2(u[1], u[0])) + (np.pi / 2 if cross else 0.0) + sk.set_gripper(False, steps=8) + self.transit(c, z, yaw=yaw) + sk.set_gripper(True, steps=15) + e = c + u * dist + sk.move_to([e[0], e[1], z], speed=speed, tol=0.004, + max_steps=int(dist / speed / 0.05) + 80 if speed else 250) + sk.hold(6) + sk.set_gripper(False, steps=12) + e = sk.eef_pos() + sk.move_to([e[0], e[1], e[2] + 0.15], speed=0.25) + + def pick_upright(self, b, jitter=None, yaw=0.0): + """grasp the neck of a standing bottle from above (the palm stays above the bottle's top)""" + sk = self.sk + p = envs.obj_pos(self.env, b) + top = envs.obj_max_z(self.env, b) + xy = p[:2] + (np.zeros(2) if jitter is None else jitter) + sk.set_gripper(False, steps=8) + self.transit(xy, top - GRASP_TOP, yaw) + sk.set_gripper(True, steps=15) + sk.move_to([xy[0], xy[1], SAFE_Z_HELD], speed=0.25) + return sk.eef_pos()[2] - envs.obj_min_z(self.env, b) # grasp height actually held + + def place_at(self, b, xy, held_h, release=0.006): + sk = self.sk + self.transit(xy, PLATE_TOP + release + held_h + 0.03, z_safe=SAFE_Z_HELD) + sk.hold(10) # let a hanging bottle stop swinging + sk.move_to([xy[0], xy[1], PLATE_TOP + release + held_h], speed=0.08, tol=0.003, max_steps=150) + sk.hold(4) + sk.set_gripper(False, steps=12) + sk.move_to([xy[0], xy[1], SAFE_Z], speed=0.25) + + def load_all(self, rng=None): + """every bottle goes to the tray slot on the same side as its start position (a carried bottle never passes + over a standing one); the hand's long side across the row. With `rng`: +-5 mm on every grasp / placement.""" + tp, R = self.tray_pose() + ay = R[:2, 1] + yaw = self.tray_yaw() - np.pi / 2 + by_y = sorted(BOTTLES, key=lambda b: float(np.asarray(self.inst["bottle_start"][b][:2]) @ ay)) + for j, b in enumerate(by_y): + jg, jp = (None, None) if rng is None else (rng.uniform(-0.005, 0.005, 2), rng.uniform(-0.005, 0.005, 2)) + h = self.pick_upright(b, jitter=jg, yaw=yaw) + self.place_at(b, self._slot_world(j) + (0 if jp is None else jp), h) + + def free_slot(self, exclude): + """a tray slot at least 7 cm from every other bottle (standing or lying); among those the one farthest from the + robot; else the emptiest slot""" + tp, R = self.tray_pose() + others = [R[:2, :2].T @ (self.bottle_state(o)["pos"][:2] - tp[:2]) for o in BOTTLES if o not in exclude] + cand = [] + for j, ly in enumerate(SLOT_LY): + dmin = min([np.linalg.norm(np.array([SLOT_LX, ly]) - o) for o in others] + [1.0]) + cand.append((dmin >= 0.07, float(self._slot_world(j)[0]) if dmin >= 0.07 else dmin, j)) + return self._slot_world(max(cand)[2]) + + def restand(self, b): + """a fallen bottle: grasp its neck across (fingers closing across the neck), lift -- it swings down and hangs + from the neck -- and set it down on a free slot. A bottle standing off the tray: pick it up by the neck.""" + sk = self.sk + st = self.bottle_state(b) + if st["upright"]: + h = self.pick_upright(b, yaw=self.tray_yaw() - np.pi / 2) + self.place_at(b, self.free_slot({b}), h) + return + for tries in range(2): + st = self.bottle_state(b) + R = self.env.sim.data.body_xmat[self.bid[b]].reshape(3, 3) + ax = R[:, 2] # bottle axis (bottom -> neck) + u = ax[:2] / max(np.linalg.norm(ax[:2]), 1e-6) + neck = st["pos"] + ax * (BH - GRASP_TOP) + yaw = float(np.arctan2(u[1], u[0])) # fingers close across the neck + sk.set_gripper(False, steps=8) + self.transit(neck[:2], max(neck[2], envs.TABLE_Z + 0.008), yaw) + sk.set_gripper(True, steps=15) + if sk.holding(b) or tries: + break + # a finger landed on the tray's edge next to the neck: slide the bottle 5 cm away from the tray, retry + tp = self.tray_pose()[0] + v = st["pos"][:2] - tp[:2] + v = v / max(np.linalg.norm(v), 1e-6) + sk.set_gripper(False, steps=8) + sk.move_to(sk.eef_pos() + [0.0, 0.0, 0.05], speed=0.1) + self.push_point(st["pos"][:2] - v * 0.015, v, 0.065, speed=0.05, z=PLATE_TOP + 0.012) + sk.move_to([neck[0], neck[1], SAFE_Z_HELD], speed=0.15) + sk.hold(20) + held = sk.eef_pos()[2] - envs.obj_min_z(self.env, b) + self.place_at(b, self.free_slot({b}), held) + + def push_point(self, p, u, dist, speed=0.03, z=None): + """closed gripper: from 3 cm behind point `p` (direction `u`) push `dist` metres along u, back off, lift""" + sk = self.sk + z = PUSH_Z if z is None else z + s0 = np.asarray(p) - u * 0.03 + sk.set_gripper(True, steps=8) + self.transit(s0, z, yaw=float(np.arctan2(u[1], u[0]))) + e = s0 + u * (0.018 + dist) + sk.move_to([e[0], e[1], z], speed=speed, tol=0.003, max_steps=600) + sk.hold(4) + e = sk.eef_pos()[:2] - u * 0.03 + sk.move_to([e[0], e[1], z], speed=0.1) + sk.move_to([e[0], e[1], SAFE_Z], speed=0.25) + + def fix_tray(self, speed=V_CAREFUL): + """straighten the tray by slowly pushing the trailing corner that lags behind, then grasp the handle's stem + and move the tray, without turning it, until its footprint is centred in the delivery area""" + sk = self.sk + y1 = self.inst["area_yaw"] + u1 = _rotz2(y1)[:, 0] + for _ in range(3): + err = (self.tray_yaw() - y1 + np.pi) % (2 * np.pi) - np.pi + if abs(err) < np.radians(3): + break + tp, R = self.tray_pose() + corners = [tp[:2] + R[:2, :2] @ np.array([-PLATE[0], e * (PLATE[1] - 0.02)]) for e in (1.0, -1.0)] + a = [float((c - tp[:2]) @ u1) for c in corners] + k = int(np.argmin(a)) + self.push_point(corners[k], u1, 0.6 * (max(a) - min(a)), speed=speed) + tp, R = self.tray_pose() + h0 = tp[:2] + R[:2, :2] @ np.array([-PLATE[0] - STEM[0], 0.0]) + foot = tp[:2] + R[:2, :2] @ np.array([FOOT_DX, 0.0]) + h1 = h0 + (np.asarray(self.inst["deliver_xy"]) - foot) + d = float(np.linalg.norm(h1 - h0)) + if d < 0.004: + return + sk.set_gripper(False, steps=8) + self.transit(h0, DRAG_Z, yaw=self.tray_yaw()) # fingers close across the stem's width + sk.set_gripper(True, steps=15) + sk.move_to([h1[0], h1[1], DRAG_Z], speed=speed, tol=0.003, max_steps=int(d / speed / 0.05) + 80) + sk.hold(5) + sk.set_gripper(False, steps=12) + e = sk.eef_pos() + sk.move_to([e[0], e[1], SAFE_Z], speed=0.2) + + def check_and_restore(self, rounds=3): + """the final check: bottles not upright on the tray -> stand them up on a free slot (farthest from the robot + first); then, if the tray is not completely in the delivery area, move it there slowly by the handle""" + for _ in range(rounds): + bad = [b for b in BOTTLES if not self.bottle_state(b)["ok"]] + if not bad and self.tray_inside("deliver_xy"): + return + for b in sorted(bad, key=lambda o: -float(self.bottle_state(o)["pos"][0])): + self.restand(b) + self.sk.hold(10) + if not self.tray_inside("deliver_xy"): + self.fix_tray() + self.sk.hold(10) + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("seed")) if params.get("jitter") else None + self.load_all(rng) + if params.get("mode", "push") == "drag": + self.drag_tray(params["speed"]) + else: + self.push_tray(params["speed"], gap=params.get("gap", 0.03), segments=params.get("segments", 1)) + if params.get("check"): + self.check_and_restore() + + def default_params(self, inst): + """naive = the pilot agents' style: load all three, push the handle with the closed gripper at ~4.5 cm/s""" + return dict(speed=V_NAIVE, mode="push", check=False) + + def oracle_params(self, inst): + return dict(speed=V_CAREFUL, mode="drag", check=True) + + def adapt_params(self, inst, history): + return dict(speed=V_CAREFUL, mode="drag", check=True) + + def blind_params(self, inst, attempt, rng): + return dict(speed=float(rng.uniform(0.03, 0.06)), mode="push", segments=int(rng.integers(1, 3)), + check=False, jitter=True, seed=int(rng.integers(1 << 30))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """cross protocol; adaptive = naive + check-and-restore in attempt 1, careful (drag by the handle) + check + afterwards""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_wobbly_table.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_wobbly_table.py new file mode 100644 index 0000000000000000000000000000000000000000..9d7b70f09bae7e0720480903ba087e0a11aed799 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/tasks/lh_wobbly_table.py @@ -0,0 +1,1177 @@ +"""LH lh_wobbly_table (2026-10-16): stand four bottles on the four coloured spots of a small side table -- one of its +legs is 1.5 cm short. Set the heavy bottle down on the corner over that leg while other bottles already stand on the +table and the table rocks down onto the short leg with a knock that throws the tall light bottles over. + +Family: long-horizon self-disturbance ("state_restoration"): four plain pick-and-place stages, but a later stage (the heavy +bottle on the wobbly corner) physically undoes the earlier ones without the robot touching them. The agent has to +notice the fallen bottles and stand them up again (the rocked table is stable, so they stay up), or learn across +attempts to put that bottle down first (the table then rocks while nothing stands on it). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a small wooden side table (free body, 1.1 kg): 28 x 28 x 1.6 cm top, 8.5 cm high, four 1.6 cm square legs at + +-12.5 cm; centre 53-57 cm in front of the robot base, +-4 cm left/right; four coloured spots (7.2 x 6.4 cm, + painted, colours permuted) centred 8 cm from the middle on both axes (one per corner); + * four square glass bottles (red / blue / green / yellow; 3.2 x 3.2 x 10 cm body, 2.4 cm flat foot, shoulder, 1.4 cm + square neck, a thin stem and a 1.2 cm white ball stopper; 14.7 cm tall) standing in a row on the main table in + front of the side table or beside it (random). Three are empty and light (75-90 g, centre of mass 7.2-8.0 cm up: + they tip over beyond ~9 deg); the fourth looks the same but is heavy (0.34-0.38 kg, sand in the bottom, centre of + mass 3.0-3.6 cm up). + +Hidden variables: which leg is short (its collision capsule is 14-16 mm shorter; the visual leg is drawn full length, +so all legs look alike and touch the table) and which bottle is heavy. Coupled by construction: the heavy bottle's spot +is the corner over the short leg. Balanced over seeds: in the scripted naive order (spots farthest from the supply +first, then left first) the heavy bottle's spot comes 1st / 2nd / 3rd / 4th for exactly 5 of every 20 consecutive seeds +(1st = benign for that order: the table rocks while it is empty). + +Physics (measured, scratch scripts t2-t24, see the task card and results/lh_wobbly_table/physics.json): + * The legs' collision geoms are capsules (rounded feet). With flat 1.6 cm box feet the rocking axis moved 1.1 cm + towards the loaded corner and the table's own weight stopped the rock half way (0.5 deg, balanced on two legs). + * The empty table rests level on its three long legs: its centre of mass is 5 mm towards the corner opposite the + short leg (1.1 kg x 5 mm). The light bottles on their own spots (the other three corners) never tip it, also let go + 4 cm above the top with a 2.6 cm error towards the short corner (4/4 seeds); the heavy bottle on the short corner + does (0.36 kg x 11.3 cm), also against a light bottle on the opposite corner. (A light bottle put on the short + corner's spot -- a wrong spot -- also tips the empty table: 85 g x 11.3 cm > 1.1 kg x 5 mm.) Rocked onto the short + leg the table tilts 4.5-5.1 deg and stays there with the heavy bottle on it, also when the light ones are added; + lifting the heavy bottle off, or pressing 1.25 N down near the raised corner, rocks it back (measured). + * The knock topples the light bottles standing on the table: 18/18 with teleported (zero-velocity) placements at gaps + 13-18 mm (12 mm: 8-10/18, 10 mm: 0/18); they fall towards the low corner, some off the table edge. The heavy bottle + stays up. The robot does not touch the bottles that fall (logged per rock). + * Bottle and table-top contacts are overdamped (solref 0.01, damping ratio 3): with stiff critically damped contacts + a light bottle let go 1-4 cm above the ROCKED table landed on its uphill edge and fell over (21/27 at 3.4 deg); + damped, 0/54 at every gap 13-18 mm, so the cross-attempt fix (heavy bottle first) works with the agent's usual + release 1-4 cm above the surface. + * A 22 x 22 cm draft table (spots 15.6 cm apart diagonally, 15.7 cm draft bottles) let the bottle on the opposite corner + fall onto the heavy one and lean on it; its stopper could not be grasped without knocking the heavy bottle over + (after which the table rocks back and forth on every repair step). At 28 cm nothing leans on it. + * Grasps: the Panda hand's collision hull starts 3 cm above the grasp point and the finger pads reach 1.2 cm above + it. Everything above the square neck is narrower than the neck: fingers that overlap the neck (grasp point 0.4-0.9 + cm below its top) close on its flat faces and hold the bottle rigidly (the heavy one stayed in the fingers through + three moves at the controller's top speed 12/12, a light one 11/12); fingers on the ball alone (grasp point at or + above the neck's top) touch it at one point each and the bottle pivots (top-speed carries lost it 6/6). Drafts: a + 1.8 cm ball on a 1.3 cm round neck (the fingers always closed on the ball; the heavy bottle swung out in 5/6 fast + carries and once in the first smoke test), a 1.2 x 2.2 cm cylinder stopper (line contacts: a lying bottle lifted by + it stuck at ~26 deg and fell over when set down). The instruction states which grip is rigid and which swings (as + lh_bystander states its cap). + * Restoring (yaw-only top-down gripper): grasp the ball stopper of a lying bottle from above with the fingers across + its axis (torsional friction 0.0005), lift: it swings down and hangs straight (0.1 deg); lower it onto its spot and + let go. A bottle that fell off onto the main table right beside the small table often cannot be reached this way: + the hand (20 cm wide along the finger axis, 3 cm above the grasp point) would hit the table top. Where the hand, + the open fingers or the forearm would touch a standing bottle, the scripted repair first lifts the fallen bottle by + its body and lays it down in free space. + * Reach: the arm stalls 2-3 cm short of low targets beyond ~0.72 m from the base; every scripted grasp point stays + within 0.70 m. + +Success predicates (evaluated every other control step by a monitor, debounced over 0.5 s): each bottle stands upright +(tilt <= 10 deg from vertical; on the rocked table they stand at ~5.5 deg) on the small table's top with the centre of +its bottom inside its spot shrunk by 6 mm (3.0 cm forward-back, 2.6 cm left-right of the spot's centre), not held. +Success = all four at the end, gripper open and not touching a bottle, scene static, and the small table within 3 cm / +10 deg of where it stood and standing on its legs (tilt <= 8 deg; the rocked tilt counts as standing). The monitor logs +achieved / lost / restored per bottle and table_rocked / table_rocked_back events (the bottle released just before, +the bottles standing at that moment, which of them fell, whether the robot touched them before / while they fell) for +the server log only (F1 gives the agent only success / failure). + +Protocol: cross (reset to the same instance before every attempt), k = 3. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +TZ = envs.TABLE_Z +COLOURS = ["red", "blue", "green", "yellow"] +BOTTLES = [f"bottle_{c}_1" for c in COLOURS] +TABLE = "side_table_1" +RGBA = {"red": (0.80, 0.14, 0.12, 1.0), "blue": (0.15, 0.33, 0.80, 1.0), "green": (0.14, 0.58, 0.24, 1.0), + "yellow": (0.90, 0.74, 0.12, 1.0)} +SPOT_RGBA = {"red": (0.62, 0.12, 0.11, 1.0), "blue": (0.12, 0.22, 0.58, 1.0), "green": (0.10, 0.42, 0.17, 1.0), + "yellow": (0.70, 0.56, 0.08, 1.0)} +CAP_RGBA = (0.93, 0.93, 0.91, 1.0) # white round stopper +WOOD = (0.52, 0.36, 0.22, 1.0) +LEG_RGBA = (0.40, 0.27, 0.16, 1.0) + +# ---------------------------------------------------------------- side table (free body) +TOP_HW = 0.140 # 28 x 28 cm top +TOP_T = 0.016 +TABLE_H = 0.085 # top surface above the main table +LEG_HW = 0.008 # 1.6 x 1.6 cm legs (visual); collision: capsules of radius 8 mm (rounded feet) +LEG_O = 0.125 # leg centre offset from the table centre (x and y) +LEG_L = TABLE_H - TOP_T +TBL_MASS = 1.1 +TBL_SOLREF = 'solimp="0.95 0.99 0.001" solref="0.004 1"' # legs: stiff (a sharp knock when the short leg lands) +TOP_SOLREF = 'solimp="0.95 0.99 0.001" solref="0.01 3"' # top: overdamped like the bottles +LEG_MU = 1.0 +TOP_MU = 0.8 +# corners in the table frame (= world axes; +x forward, +y left): index -> (sx, sy); k and k + 2 are diagonal +CORNERS = [(1, 1), (1, -1), (-1, -1), (-1, 1)] +CORNER_NAME = {(1, 1): "far-left", (1, -1): "far-right", (-1, -1): "near-right", (-1, 1): "near-left"} +SPOT_O = 0.080 # spot centre offset from the table centre (x and y) +SPOT_HX, SPOT_HY = 0.036, 0.032 # spot half sizes (forward-back, left-right): 7.2 x 6.4 cm +SHORT_H = (0.014, 0.016) # hidden: one leg this much shorter (collision only; the visual leg reaches the table) +COM_BIAS = 0.005 # table centre of mass this far towards the leg opposite the short one: the empty table rests level + +# ---------------------------------------------------------------- bottles (square glass bottles with a round stopper) +RB, HB = 0.016, 0.100 # body half width, height (3.2 x 3.2 x 10 cm) +RF, HF = 0.012, 0.005 # foot: flat contact 2.4 x 2.4 cm (rounded glass base) +RS, HS = 0.011, 0.010 # shoulder +RN, HN = 0.007, 0.016 # square neck: 1.4 cm wide, 1.6 cm long (11.0-12.6 cm above the bottom) +RT, HT = 0.0035, 0.010 # thin round stem above it: 0.7 cm wide, 1.0 cm long +RK, CAP_SINK = 0.006, 0.001 # ball stopper: 1.2 cm wide, on the stem (top 14.7 cm above the bottom) +# Why this top (measured, t8_hand.py / t19_slip.py / t22_restand.py): the Panda hand's collision hull starts ~3 cm above +# the grasp point and the finger pads reach 1.2 cm above it. Everything above the square neck is narrower than the +# neck, so fingers that overlap the neck close on its flat faces (several contact points: the bottle is held rigidly), +# and fingers on the ball alone touch it at one point each (low torsional friction: a lying bottle swings down and +# hangs straight). Drafts: a 1.8 cm ball on a 1.3 cm round neck -- the fingers always closed on the ball, the heavy +# bottle pivoted and swung out in 5/6 fast carries; a 1.2 x 2.2 cm cylinder stopper -- line contacts, a lifted lying +# bottle stuck at ~26 deg and fell over when set down (in-attempt repair 6/15). +H_TOT = HB + HS + HN + HT + 2 * RK - CAP_SINK # 14.7 cm +CAP_Z = H_TOT - RK # stopper centre above the bottle's bottom +NECK_Z = (HB + HS, HB + HS + HN) # square neck span above the bottom +BOT_MU = 0.7 +CAP_MU_T = 0.0005 # torsional friction of the stopper (condim 4): held by it, a lying bottle swings down and hangs +BOT_DAMP = 0.003 # free-joint damping of the bottles (damps the swing of a bottle hanging from its stopper) +# overdamped contacts (damping ratio 3): with critically damped stiff contacts a light bottle set down 1-4 cm above a +# table top tilted 3.4 deg landed on its uphill edge and fell over (measured 21/27); damped: 0/54 at tilts up to 5 deg +BOT_SOLREF = 'solimp="0.95 0.99 0.001" solref="0.01 3"' +LIGHT_MASS = (0.075, 0.090) +LIGHT_COM = (0.072, 0.080) # above the bottom (empty glass bottle, thick shoulder) +HEAVY_MASS = (0.34, 0.38) +HEAVY_COM = (0.030, 0.036) # sand in the bottom + +# ---------------------------------------------------------------- predicates / monitor +TILT_OK = np.radians(10.0) # a bottle stands upright (world vertical; the rocked table itself tilts ~4.3 deg) +TOL_X = SPOT_HX - 0.006 # bottle centre within the spot shrunk by 6 mm (3.0 cm forward-back, 2.6 cm left-right) +TOL_Y = SPOT_HY - 0.006 +ON_TOP = 0.006 # the bottle's bottom within this of the table top +HYST = 0.003 +DEBOUNCE = 10 # control steps (0.5 s) +ROCK_ON, ROCK_OFF = np.radians(1.5), np.radians(0.8) # table tilt thresholds of the rock detector +FELL_WINDOW = 40 # control steps after a rock in which lost stages are attributed to it (2 s) +TABLE_MOVE_TOL = 0.03 # success: the table centre within 3 cm of where it stood +TABLE_YAW_TOL = np.radians(10.0) +TABLE_TILT_MAX = np.radians(8.0) + +# ---------------------------------------------------------------- scripted motion +Z_CARRY = 0.40 # grasp point above the main table while carrying (bottle bottom ~27 cm up: clears standing bottles) +Z_HANG = 0.42 # ... carrying a bottle that hangs from its stopper (its bottom 27 cm up) +GRASP_NECK = 0.006 # scripted transport grasp point: this far below the neck's top (pads 1.1 cm on the neck, the hand +# 3 mm above the stopper; measured: 4-9 mm below the top hold rigidly, 4 mm above it close on the ball) +NAIVE_GAP = (0.010, 0.040) # Sonnet releases 1-4 cm above the surface +NAIVE_BIAS = (0.008, 0.020) # systematic forward placement error (lh_nudge_row pilot), per instance +NAIVE_RAND = 0.006 +CAREFUL_GAP = 0.004 + + +def bottle_xml(name, rgba): + """square glass bottle: rounded foot (smaller flat contact), body, shoulder, square neck, round stopper. Collision and + visual geoms separate; the inertial (mass, COM) is replaced per instance.""" + h = H_TOT / 2 + zf, zb = -h + HF / 2, -h + HF + (HB - HF) / 2 + zs, zn = -h + HB + HS / 2, -h + HB + HS + HN / 2 + zt = -h + HB + HS + HN + HT / 2 + zk = -h + HB + HS + HN + HT + RK - CAP_SINK + parts = [("foot", "box", (0, 0, zf), (RF, RF, HF / 2), rgba, f'friction="{BOT_MU} 0.005 0.0001"'), + ("body", "box", (0, 0, zb), (RB, RB, (HB - HF) / 2), rgba, f'friction="{BOT_MU} 0.005 0.0001"'), + ("shoulder", "box", (0, 0, zs), (RS, RS, HS / 2), rgba, f'friction="{BOT_MU} 0.005 0.0001"'), + ("neck", "box", (0, 0, zn), (RN, RN, HN / 2), rgba, f'friction="{BOT_MU} 0.005 0.0001"'), + ("stem", "cylinder", (0, 0, zt), (RT, HT / 2), CAP_RGBA, f'friction="{BOT_MU} 0.005 0.0001"'), + ("cap", "sphere", (0, 0, zk), (RK,), CAP_RGBA, f'friction="1 {CAP_MU_T} 0.0001" condim="4" priority="2"')] + s = [f' '] + for nm, typ, pos, size, c, extra in parts: + s.append(f' ') + s.append(f' ') + # a pale label (visual) so the bottles read as bottles + s.append(f' ') + return _wrap(name, "\n".join(s), h, RB * 1.42) + + +def table_xml(name): + """side table, origin at the centre of the footprint at mid height. Leg k sits under corner CORNERS[k].""" + h = TABLE_H / 2 + zt = h - TOP_T / 2 + zl = -h + LEG_L / 2 + s = [f' ', + f' ', + f' '] + for k, (sx, sy) in enumerate(CORNERS): + p = (sx * LEG_O, sy * LEG_O, zl) + # collision: a capsule inscribed in the square leg -> a rounded, point-like foot (a flat 1.6 cm foot moves the + # rocking axis 1.1 cm towards the loaded corner, and the table's own weight then stops the rock; measured) + s.append(f' ') + s.append(f' ') + for k, (sx, sy) in enumerate(CORNERS): # coloured spots (visual); colours are set per instance + s.append(f' ') + return _wrap(name, "\n".join(s), h, TOP_HW * 1.42) + + +def _fb(d): + return f"{100 * abs(d):.1f} cm {'forward' if d > 0 else 'back'}" + + +def _lr(d): + return f"{100 * abs(d):.1f} cm to the {'left' if d > 0 else 'right'}" + + +def _ang(a): + return float((a + np.pi) % (2 * np.pi) - np.pi) + + +class WobblySkills(Skills): + """Skills that feed the task's per-step monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class WobblyTable(LFFTask): + name = "lh_wobbly_table" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Restore", "Plan") + protocol = "cross" + max_attempts = 3 + # careful: 4 bottles x ~7 commands + standing up to three fallen bottles again x ~9 + looking / corrections + agent_max_steps = 120 + instruction = ("Put each of the four bottles on the spot of its own colour on the small wooden table. At the end " + "every bottle must stand upright on its spot, the gripper must be open and clear of the bottles, and " + "the small table must still stand where it is now. (Each bottle has a square neck with a small round " + "white stopper on top. Gripped on the neck, a bottle stays rigid in the fingers; gripped by the " + "stopper alone, it swings freely and hangs straight down.)") + instruction_indirect = ("Set the four coloured bottles out on the little wooden side table, each on the patch that " + "matches its colour. When you finish, all four have to be standing upright on their patches, " + "the gripper open and away from them, and the side table left where it stands. (Gripped " + "on its square neck a bottle stays rigid; gripped by the round white stopper alone it swings " + "freely and hangs straight down.)") + agent_object_names = ["bottles (red, blue, green, yellow; each with a square neck and a small round white stopper)", + "small wooden side table with four coloured spots (red, blue, green, yellow)"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs = [] + for i, (c, b) in enumerate(zip(COLOURS, BOTTLES)): + cat = register_generated(f"LffLhwBottle{c.capitalize()}", bottle_xml(f"lff_lhw_bottle_{c}", RGBA[c])) + objs.append((b, cat, f"bottle{i}_region", (-0.30 + 0.13 * i, 0.30, -0.29 + 0.13 * i, 0.31))) + cat = register_generated("LffLhwSideTable", table_xml("lff_lhw_table")) + objs.append((TABLE, cat, "table_region", (-0.05, -0.30, -0.04, -0.29))) + return write_bddl(self.name, "Stand each bottle on the spot of its colour on the small table", objs, []) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.tbid = envs.body_id(self.env, TABLE) + pre = f"{TABLE}_lff_lhw_table" + self.leg_gid = [m.geom_name2id(f"{pre}_leg{k}") for k in range(4)] + self.top_gid = m.geom_name2id(f"{pre}_top") + self.leg_size0 = [m.geom_size[g].copy() for g in self.leg_gid] + self.leg_pos0 = [m.geom_pos[g].copy() for g in self.leg_gid] + self.tbl_ipos0 = m.body_ipos[self.tbid].copy() + self.spot_gid = [m.geom_name2id(f"{pre}_spot{k}") for k in range(4)] + self.bbid = {b: envs.body_id(self.env, b) for b in BOTTLES} + self.cap_gid = {b: m.geom_name2id(f"{b}_lff_lhw_bottle_{c}_cap") for c, b in zip(COLOURS, BOTTLES)} + self.dof = {b: envs.free_joint_addr(self.env, b)[1] for b in BOTTLES} + self.tbl_dof = envs.free_joint_addr(self.env, TABLE)[1] + self.bgeoms = {b: envs.obj_geom_ids(self.env, b) for b in BOTTLES} + self.finger_geoms, self.hand_geoms, self.arm_geoms = [], [], [] + for g in envs.robot_geom_ids(self.env): + n = m.geom_id2name(g) or "" + (self.finger_geoms if "finger" in n else self.hand_geoms if n.startswith("gripper0_") + else self.arm_geoms).append(g) + # per-geom lookup tables for the substep contact check: bottle index (-1 none), robot part (1 finger, 2 hand, + # 3 arm), table geom + self.owner = np.full(m.ngeom, -1, int) + for i, b in enumerate(BOTTLES): + self.owner[self.bgeoms[b]] = i + self.part = np.zeros(m.ngeom, int) + self.part[self.finger_geoms] = 1 + self.part[self.hand_geoms] = 2 + self.part[self.arm_geoms] = 3 + self.is_table = np.zeros(m.ngeom, bool) + self.is_table[envs.obj_geom_ids(self.env, TABLE)] = True + self._sub_rob, self._sub_obj, self._sub_tbl = {}, {}, 0 + # contacts are collected after every MuJoCo substep (same technique as lh_nudge_row; wrappers chain) + sim = self.env.sim + if not getattr(sim, "_lhw_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lhw_task", None) + if t is not None and t.mon is not None: + t._substep() + sim.step = step + sim._lhw_wrapped = True + sim._lhw_task = self + self.inst = None + self.mon = None + self.sk = None + self._held_prev = None + + def _substep(self): + d = self.env.sim.data + n = d.ncon + if not n: + return + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + o1, o2 = self.owner[g1], self.owner[g2] + for a, b, pa, pb in zip(g1, g2, o1, o2): + if pa < 0 and pb < 0: + if (self.is_table[a] and self.part[b]) or (self.is_table[b] and self.part[a]): + self._sub_tbl = 1 + continue + if pa >= 0 and pb >= 0: + if pa != pb: + self._sub_obj[int(pa)] = int(pb) + self._sub_obj[int(pb)] = int(pa) + continue + p, o = (pa, b) if pa >= 0 else (pb, a) + part = int(self.part[o]) + if part: + self._sub_rob[int(p)] = min(self._sub_rob.get(int(p), 9), part) + + # ------------------------------------------------------------ instances + @staticmethod + def _supply(side, tx, ty, j): + """slot j (0-3) of the row of bottles on the main table: in front of the side table (robot side) or beside it; + every grasp point stays within 0.70 m (horizontal) of the robot base (the arm stalled 2-3 cm short of low + targets beyond ~0.72 m, measured)""" + if side == "front": + return [tx - 0.215, ty + (j - 1.5) * 0.085] + sg = 1.0 if side == "left" else -1.0 + return [tx - 0.05 + (j - 1.5) * 0.075, ty + sg * 0.22] + + @staticmethod + def _far_first(spot_of, side, tx, ty): + """colours in the order of the scripted naive policy: the spots farthest from the supply first (a careful agent + does not reach over bottles it has already put down), ties broken to the left, then far""" + sup = np.mean([WobblyTable._supply(side, tx, ty, j) for j in range(4)], axis=0) + sc = [] + for c, k in spot_of.items(): + sx, sy = CORNERS[k] + p = np.array([tx + sx * SPOT_O, ty + sy * SPOT_O]) + sc.append((-round(float(np.linalg.norm(p - sup)), 3), -sy, -sx, c)) + return [t[-1] for t in sorted(sc)] + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + tx = float(rng.uniform(-0.13, -0.09)) # side table centre: 53-57 cm in front of the robot base + ty = float(rng.uniform(-0.04, 0.04)) + side = str(rng.choice(["left", "right", "front"])) + perm = [int(v) for v in rng.permutation(4)] # perm[corner] = colour index on that corner's spot + spot_of = {COLOURS[perm[k]]: k for k in range(4)} + # the heavy bottle and the short leg under its spot: balanced over seeds against the scripted naive order (far + # spots first): its spot comes 1st / 2nd / 3rd / 4th in that order for exactly 5 of every 20 consecutive seeds + order = self._far_first(spot_of, side, tx, ty) + pos = int((int(seed) * 7) % 20 // 5) + heavy = order[pos] + short = spot_of[heavy] + slots = [int(v) for v in rng.permutation(4)] + start = {} + for i in range(4): + x, y = self._supply(side, tx, ty, slots[i]) + start[COLOURS[i]] = [x + float(rng.uniform(-0.006, 0.006)), y + float(rng.uniform(-0.006, 0.006))] + mass = {c: float(rng.uniform(*LIGHT_MASS)) for c in COLOURS} + com = {c: float(rng.uniform(*LIGHT_COM)) for c in COLOURS} + mass[heavy] = float(rng.uniform(*HEAVY_MASS)) + com[heavy] = float(rng.uniform(*HEAVY_COM)) + return dict(seed=int(seed), table_xy=[tx, ty], short_leg=int(short), short_corner=CORNER_NAME[CORNERS[short]], + heavy=heavy, heavy_rank_naive=pos + 1, spot_of=spot_of, supply_side=side, start=start, mass=mass, + com=com, short_h=float(rng.uniform(*SHORT_H)), com_bias=COM_BIAS, + yaw0={c: float(rng.uniform(-0.3, 0.3)) for c in COLOURS}, + naive_bias_x=float(rng.uniform(*NAIVE_BIAS))) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + k = inst["short_leg"] + h = float(inst["short_h"]) + for j, g in enumerate(self.leg_gid): + m.geom_size[g] = self.leg_size0[j] + m.geom_pos[g] = self.leg_pos0[j] + g = self.leg_gid[k] + m.geom_size[g][1] = self.leg_size0[k][1] - h / 2 # capsule half length + m.geom_pos[g][2] = self.leg_pos0[k][2] + h / 2 + opp = CORNERS[(k + 2) % 4] + b = float(inst.get("com_bias", COM_BIAS)) / np.sqrt(2) + m.body_ipos[self.tbid] = [opp[0] * b, opp[1] * b, self.tbl_ipos0[2]] + envs.refit_bounds(m, self.tbid) + for c in COLOURS: + m.geom_rgba[self.spot_gid[inst["spot_of"][c]]] = SPOT_RGBA[c] + for c, bot in zip(COLOURS, BOTTLES): + bid = self.bbid[bot] + M, zc = inst["mass"][c], inst["com"][c] + m.body_mass[bid] = M + m.body_ipos[bid] = [0.0, 0.0, -H_TOT / 2 + zc] + # glass shell + internal weight, roughly: radius of gyration ~ 0.35 x height about horizontal axes + ixx = M * ((2 * RB) ** 2 / 12 + (0.35 * H_TOT) ** 2) + m.body_inertia[bid] = [ixx, ixx, M * (2 * RB) ** 2 / 6] + envs.refit_bounds(m, bid) + m.dof_damping[self.dof[bot]:self.dof[bot] + 6] = BOT_DAMP + self.env.sim.forward() + tx, ty = inst["table_xy"] + # yaw pi: the canonical quaternion LIBERO gives generated objects is a 180 deg yaw (envs.canonical_quat); with + # it the table frame is the world frame + envs.place_upright(self.env, TABLE, [tx, ty], yaw=np.pi, clearance=0.0003) + for c, bot in zip(COLOURS, BOTTLES): + envs.place_upright(self.env, bot, inst["start"][c], yaw=inst["yaw0"][c], clearance=0.0005) + self.env.sim.data.qvel[self.tbl_dof:self.tbl_dof + 6] = 0.0 + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = WobblySkills(self.env, self, recorder=recorder) + self._sub_rob, self._sub_obj, self._sub_tbl = {}, {}, 0 + self._held_prev = None + self.table0 = dict(pos=self.table_pos().tolist(), yaw=self.table_yaw()) + n = len(BOTTLES) + self.mon = dict(state=[False] * n, raw_since=[0] * n, ever=[False] * n, lost=[False] * n, events=[], + lost_cause=[None] * n, last_robot=[None] * n, last_obj=[None] * n, last_release=None, + last_table_touch=-10 ** 6, rocked=False, rock_since=0, rocks=[], n_steps=0, + max_table_tilt_deg=0.0) + return self.sk + + # ------------------------------------------------------------ geometry / predicates + def table_R(self): + return self.env.sim.data.body_xmat[self.tbid].reshape(3, 3).copy() + + def table_pos(self): + return self.env.sim.data.body_xpos[self.tbid].copy() + + def table_yaw(self): + R = self.table_R() + return float(np.arctan2(R[1, 0], R[0, 0])) + + def table_tilt(self): + return float(np.arccos(np.clip(self.table_R()[2, 2], -1, 1))) + + def top_point(self, local_xy): + """world position of a point on the table's top surface (table frame xy)""" + return self.table_pos() + self.table_R() @ np.array([local_xy[0], local_xy[1], TABLE_H / 2]) + + def spot_local(self, colour): + sx, sy = CORNERS[self.inst["spot_of"][colour]] + return np.array([sx * SPOT_O, sy * SPOT_O]) + + def spot_world(self, colour): + return self.top_point(self.spot_local(colour)) + + def top_z_at(self, xy): + """z of the table's top plane above world point xy""" + R, p = self.table_R(), self.table_pos() + n = R[:, 2] + c = p + n * TABLE_H / 2 + return float(c[2] - (n[0] * (xy[0] - c[0]) + n[1] * (xy[1] - c[1])) / max(n[2], 1e-6)) + + def over_table(self, xy): + loc = self.table_R().T @ (np.array([xy[0], xy[1], self.table_pos()[2]]) - self.table_pos()) + return abs(loc[0]) < TOP_HW and abs(loc[1]) < TOP_HW + + def bR(self, b): + return self.env.sim.data.body_xmat[self.bbid[b]].reshape(3, 3).copy() + + def bpos(self, b): + return self.env.sim.data.body_xpos[self.bbid[b]].copy() + + def foot(self, b): + """world position of the centre of the bottle's bottom face""" + return self.bpos(b) - self.bR(b)[:, 2] * H_TOT / 2 + + def tilt(self, b): + return float(np.arccos(np.clip(self.bR(b)[2, 2], -1.0, 1.0))) + + def cap_xyz(self, b): + return self.env.sim.data.geom_xpos[self.cap_gid[b]].copy() + + def held(self, b): + return self.sk is not None and self.sk.holding(b) + + def offset(self, i): + """bottle i's foot centre relative to its spot centre, in the table frame (x forward-back, y left-right), and + the height of its bottom above the table top""" + b, c = BOTTLES[i], COLOURS[i] + loc = self.table_R().T @ (self.foot(b) - self.table_pos()) + return loc[:2] - self.spot_local(c), float(loc[2] - TABLE_H / 2) + + def on_spot(self, i, extra=0.0): + b = BOTTLES[i] + if self.tilt(b) > TILT_OK + (np.radians(2.0) if extra else 0.0): + return False + off, dz = self.offset(i) + if abs(off[0]) > TOL_X + extra or abs(off[1]) > TOL_Y + extra or abs(dz) > ON_TOP: + return False + return not self.held(b) + + def stages(self): + return [self.on_spot(i) for i in range(len(BOTTLES))] + + def table_ok(self): + p0 = np.asarray(self.table0["pos"]) + moved = float(np.linalg.norm(self.table_pos()[:2] - p0[:2])) + dyaw = abs(_ang(self.table_yaw() - self.table0["yaw"])) + return bool(moved <= TABLE_MOVE_TOL and dyaw <= TABLE_YAW_TOL and self.table_tilt() <= TABLE_TILT_MAX), moved, dyaw + + def low_corner(self): + """robot-centric name of the table corner that is lowest (after a rock: the corner over the short leg)""" + zs = {k: self.top_point([sx * TOP_HW, sy * TOP_HW])[2] for k, (sx, sy) in enumerate(CORNERS)} + return CORNER_NAME[CORNERS[min(zs, key=zs.get)]] + + # ------------------------------------------------------------ monitor + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + mon["n_steps"] += 1 + t = int(self.sk.n_steps) + rob, obj, tbl = dict(self._sub_rob), dict(self._sub_obj), self._sub_tbl + self._sub_rob, self._sub_obj, self._sub_tbl = {}, {}, 0 + gstate = "open" if self.sk.grip < 0 else "closed" + held_now = None + for c, b in zip(COLOURS, BOTTLES): + if gstate == "closed" and self.held(b): + held_now = c + for i, part in rob.items(): + if COLOURS[i] != held_now: + mon["last_robot"][i] = [{1: "finger", 2: "hand", 3: "arm"}[part], t, gstate] + for i, j in obj.items(): + mon["last_obj"][i] = [COLOURS[j], t] + if tbl: + mon["last_table_touch"] = t + if held_now is None and self._held_prev is not None: # the gripper has just let go of a bottle + mon["last_release"] = [self._held_prev, t] + self._held_prev = held_now + tl = self.table_tilt() + mon["max_table_tilt_deg"] = max(mon["max_table_tilt_deg"], round(float(np.degrees(tl)), 2)) + if mon["n_steps"] % 2: + return + # ---- table rock detector (debounced) + want = tl > ROCK_ON if not mon["rocked"] else tl > ROCK_OFF + if want != mon["rocked"]: + mon["rock_since"] += 2 + if mon["rock_since"] >= 4: + mon["rocked"] = want + mon["rock_since"] = 0 + self._rock_event(want, t - 3) + else: + mon["rock_since"] = 0 + for r in mon["rocks"]: + if not r.get("closed") and t - r["step"] > FELL_WINDOW: + self._close_rock(r) + # ---- stage predicates + for i in range(len(BOTTLES)): + b = BOTTLES[i] + raw = self.on_spot(i, HYST if mon["state"][i] else 0.0) + if raw == mon["state"][i]: + mon["raw_since"][i] = 0 + continue + mon["raw_since"][i] += 2 + if mon["raw_since"][i] < DEBOUNCE: + continue + mon["state"][i] = raw + mon["raw_since"][i] = 0 + t0 = int(t - DEBOUNCE + 1) + if raw: + restored = mon["lost"][i] + e = dict(stage=COLOURS[i], event="restored" if restored else "achieved", step=t0) + if restored: + e["after"] = mon["lost_cause"][i] + mon["events"].append(e) + mon["ever"][i] = True + else: + mon["lost"][i] = True + cause = self._cause(i, t0) + mon["lost_cause"][i] = cause + off, dz = self.offset(i) + mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t0, cause=cause, + tilt_deg=round(float(np.degrees(self.tilt(b))), 1), + offset_cm=[round(100 * float(v), 1) for v in off])) + + def _rock_event(self, down, t): + mon = self.mon + rel = mon["last_release"] + e = dict(event="table_rocked" if down else "table_rocked_back", step=int(t), + table_tilt_deg=round(float(np.degrees(self.table_tilt())), 2), low_corner=self.low_corner(), + released=rel[0] if rel is not None and t - rel[1] <= 40 else None, + robot_touched_table=bool(t - mon["last_table_touch"] <= 20), + standing=[COLOURS[i] for i in range(len(BOTTLES)) if mon["state"][i]]) + # the cheap explanation would be "my hand bumped them": which of the standing bottles did the robot touch in + # the 2 s before the rock (should be none) + e["robot_touched_before"] = [COLOURS[i] for i in range(len(BOTTLES)) if mon["state"][i] and + mon["last_robot"][i] is not None and t - mon["last_robot"][i][1] <= 40] + mon["events"].append(e) + mon["rocks"].append(dict(step=int(t), down=bool(down), standing=list(e["standing"]), event=e)) + + def _close_rock(self, r): + """FELL_WINDOW after a rock: which of the bottles that stood on their spots fell, and did the robot touch any + of them after the rock began (a falling bottle hitting the open fingers)""" + r["closed"] = True + mon = self.mon + fell, touched = [], [] + for c in r["standing"]: + i = COLOURS.index(c) + if self.tilt(BOTTLES[i]) > np.radians(30) or not mon["state"][i]: + fell.append(c) + lr = mon["last_robot"][i] + if lr is not None and lr[1] >= r["step"]: + touched.append(c) + r["event"]["fell"] = fell + r["event"]["robot_touched_while_falling"] = touched + r["fell"] = fell + + def _cause(self, i, t, window=60): + if self.held(BOTTLES[i]): + return "picked_up" + mon = self.mon + for r in reversed(mon["rocks"]): + if 0 <= t - r["step"] <= FELL_WINDOW + 10 and COLOURS[i] in r["standing"]: + return "table_rocked" if r["down"] else "table_rocked_back" + lr, lo = mon["last_robot"][i], mon["last_obj"][i] + cands = [] + if lr is not None and t - lr[1] <= window: + cands.append((lr[1], f"robot_{lr[0]}")) + if lo is not None and t - lo[1] <= window: + cands.append((lo[1] - 30, "bottle:" + lo[0])) + return max(cands)[1] if cands else "other" + + def _finalize_monitor(self, raw): + mon = self.mon + if mon is None: + return + for r in mon["rocks"]: + if not r.get("closed"): + self._close_rock(r) + t = int(self.sk.n_steps) + for i in range(len(BOTTLES)): + if raw[i] == mon["state"][i]: + continue + mon["state"][i] = raw[i] + if raw[i]: + restored = mon["lost"][i] + e = dict(stage=COLOURS[i], event="restored" if restored else "achieved", step=t, final=True) + if restored: + e["after"] = mon["lost_cause"][i] + mon["events"].append(e) + mon["ever"][i] = True + else: + mon["lost"][i] = True + cause = self._cause(i, t, window=10 ** 6) + mon["lost_cause"][i] = cause + mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t, cause=cause, final=True)) + + # ------------------------------------------------------------ outcome + def _touching(self): + d = self.env.sim.data + for j in range(d.ncon): + c = d.contact[j] + if (self.owner[c.geom1] >= 0 and self.part[c.geom2]) or (self.owner[c.geom2] >= 0 and self.part[c.geom1]): + return True + return False + + def outcome(self, inst): + sk = self.sk + sk.hold(10) + p0 = {b: self.bpos(b) for b in BOTTLES} + t0 = self.table_pos() + touching = False + for _ in range(20): + sk.hold(1) + touching = touching or self._touching() + moved = max([float(np.linalg.norm(self.bpos(b) - p0[b])) for b in BOTTLES] + + [float(np.linalg.norm(self.table_pos() - t0))]) + static = moved < 0.003 + raw = self.stages() + self._finalize_monitor(raw) + held = [COLOURS[i] for i, b in enumerate(BOTTLES) if self.held(b)] + tok, tmoved, tyaw = self.table_ok() + mon = self.mon + ev = list(mon["events"]) + rocks = [r for r in mon["rocks"] if r["down"]] + damaging = [r for r in mon["rocks"] if r.get("fell")] + n_reg = sum(e.get("event") == "lost" and e.get("cause") != "picked_up" for e in ev) + n_lost = sum(e.get("event") == "lost" for e in ev) + n_res = sum(e.get("event") == "restored" and e.get("after") != "picked_up" for e in ev) + success = bool(all(raw) and static and not held and not touching and tok) + tilted = [i for i in range(len(BOTTLES)) if self.tilt(BOTTLES[i]) > TILT_OK and COLOURS[i] not in held] + ever = mon["ever"] + fell_by_rock = sorted({c for r in damaging for c in r["fell"]}) + if success: + failure = "none" + elif not tok: + failure = "table_moved" + elif held: + failure = "held" + elif tilted: + failure = "toppled_by_rock" if any(COLOURS[i] in fell_by_rock for i in tilted) else "toppled" + elif not all(raw): + failure = "not_on_spot" + elif touching: + failure = "touching" + else: + failure = "not_static" + parts = [] + if success: + parts.append("Every bottle stands upright on the spot of its colour.") + for i in range(len(BOTTLES)): + if raw[i]: + continue + c, b = COLOURS[i], BOTTLES[i] + if c in held: + parts.append(f"The {c} bottle is still held by the gripper.") + continue + off, dz = self.offset(i) + tl = float(np.degrees(self.tilt(b))) + on_small = abs(dz) < 0.05 and max(abs(off + self.spot_local(c))) < TOP_HW + 0.02 + if tl > np.degrees(TILT_OK): + txt = (f"The {c} bottle lies on its side on the {'small' if on_small else 'big'} table" if tl > 45 else + f"The {c} bottle leans {tl:.0f} degrees") + "." + elif abs(dz) > ON_TOP: + txt = f"The {c} bottle is not on the small table." + else: + txt = f"The {c} bottle stands {_fb(off[0])} and {_lr(off[1])} of its spot's centre, not on its spot." + if ever[i] and c in fell_by_rock: + txt += " It had stood on its spot and fell when the small table rocked." + elif ever[i]: + txt += " It had stood on its spot earlier." + parts.append(txt) + if not tok: + parts.append(f"The small table was moved ({100 * tmoved:.1f} cm, {np.degrees(tyaw):.0f} degrees).") + elif not success and all(raw): + if touching: + parts.append("The gripper is still touching a bottle.") + elif not static: + parts.append("Something was still moving.") + if rocks: + r = rocks[0]["event"] + txt = (f"When the {r['released']} bottle was set down, the small table rocked down onto its " + f"{r['low_corner']} leg" if r.get("released") else + f"The small table rocked down onto its {r['low_corner']} leg") + fl = r.get("fell", []) + txt += (" and the " + " and ".join(fl) + f" bottle{'s' if len(fl) > 1 else ''} standing on it fell over." + if fl else ".") + txt += f" That leg is {100 * float(inst['short_h']):.1f} cm shorter than the other three." + parts.append(txt) + trap = bool(damaging) + return dict(success=success, stages={COLOURS[i]: bool(raw[i]) for i in range(len(BOTTLES))}, events=ev, + n_regressions=int(n_reg), n_lost=int(n_lost), n_restored=int(n_res), n_rocks=len(rocks), + rocked=bool(rocks), trap_fired=trap, recovered_in_attempt=bool(trap and success), + fell_by_rock=fell_by_rock, failure=failure, held=held, touching=bool(touching), + static=bool(static), table_ok=bool(tok), table_moved_cm=round(100 * tmoved, 2), + table_tilt_deg=round(float(np.degrees(self.table_tilt())), 2), + max_table_tilt_deg=mon["max_table_tilt_deg"], + offsets_cm={COLOURS[i]: [round(100 * float(v), 2) for v in self.offset(i)[0]] for i in range(4)}, + tilts_deg={COLOURS[i]: round(float(np.degrees(self.tilt(BOTTLES[i]))), 1) for i in range(4)}, + heavy=inst["heavy"], short_corner=inst["short_corner"], detail=" ".join(parts)) + + # ------------------------------------------------------------ scripted primitives (move_to + gripper only) + def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300): + return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + + def _lift_to(self, z, speed=0.2): + cur = self.sk.eef_pos() + if cur[2] < TZ + z - 0.005: + self._go([cur[0], cur[1], TZ + z], speed=speed) + + def _settle(self, b, max_checks=25): + d = self.env.sim.data + da = self.dof[b] + for _ in range(max_checks): + if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2: + return + self.sk.hold(2) + + def upright(self, b): + return self.tilt(b) < np.radians(20) + + def pick_neck(self, b, z_carry=Z_CARRY, yaw=0.0, v=0.2): + """Sonnet-like top-down pick of a standing bottle: open, over it at carry height, straight down to the upper + neck, close, lift to carry height. Returns True if held.""" + sk = self.sk + self._settle(b) + p = self.foot(b) + zg = p[2] + NECK_Z[1] - GRASP_NECK + sk.set_gripper(False, steps=8) + self._lift_to(z_carry) + self._go([p[0], p[1], TZ + z_carry], yaw=yaw, speed=v) + self._go([p[0], p[1], zg + 0.02], speed=0.12) + self._go([p[0], p[1], zg], speed=0.04, tol=0.003, max_steps=150) + sk.set_gripper(True, steps=15) + self._go([p[0], p[1], TZ + z_carry], speed=0.12) + sk.hold(5) + if not self.held(b): + sk.set_gripper(False, steps=8) + return False + return True + + def put_held(self, b, xy, gap, z_carry=Z_CARRY, yaw=None, v=0.2): + """carry the held bottle so that its foot is over world xy, straight down until its bottom is `gap` above the + surface below, let go, lift""" + sk = self.sk + rel = self.foot(b)[:2] - sk.eef_pos()[:2] + q = np.asarray(xy, float) - rel + self._go([q[0], q[1], TZ + z_carry], yaw=yaw, speed=v) + sk.hold(10) + rel = self.foot(b)[:2] - sk.eef_pos()[:2] # a bottle hanging from its stopper swings while carried + q = np.asarray(xy, float) - rel + surf = self.top_z_at(xy) if self.over_table(xy) else TZ + dz = sk.eef_pos()[2] - self.foot(b)[2] + zr = surf + dz + gap + self._go([q[0], q[1], zr + 0.02], speed=0.10) + self._go([q[0], q[1], zr], speed=0.03, tol=0.003, max_steps=150) + sk.hold(4) + sk.set_gripper(False, steps=12) + cur = sk.eef_pos() + self._go([cur[0], cur[1], cur[2] + 0.06], speed=0.10) + self._go([cur[0], cur[1], TZ + z_carry], speed=0.2) + sk.hold(3) + + def surface_z(self, xy): + return self.top_z_at(xy) if self.over_table(xy) else TZ + + def pick_stopper(self, b, v=0.15): + """grasp a lying (or leaning) bottle by its round stopper from above, fingers across the bottle's axis, lift it + until it hangs free. The fingertips stay >= 4 mm above the surface under the stopper: pressing the raised half + of the rocked table rocks it back (measured), and the knock when it comes down again topples standing bottles. + Returns True if held.""" + sk = self.sk + self._settle(b) + for _ in range(2): + k, zg, yaw = self.stopper_grasp(b) # fingers across the bottle's axis + sk.set_gripper(False, steps=8) + self._lift_to(Z_HANG) + self._go([k[0], k[1], TZ + Z_HANG], yaw=yaw, speed=v) + sk.hold(5) + k, zg, _ = self.stopper_grasp(b) + self._go([k[0], k[1], zg + 0.03], speed=0.10) + self._go([k[0], k[1], zg], speed=0.03, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + if not self.held(b): + sk.set_gripper(False, steps=8) + self._go([k[0], k[1], zg + 0.08], speed=0.1) + continue + self._go([k[0], k[1], zg + 0.05], speed=0.05) + self._go([k[0], k[1], TZ + Z_HANG], speed=0.10) + sk.hold(20) + return True + return False + + # gripper footprint (measured, t8_hand): the hand's collision hull is a slab 20 cm along the finger axis and ~4 cm + # across, from 3 cm above the grasp point up; open fingers 3.9-6.6 cm out along the finger axis, from 1 cm below + # the grasp point to 4.5 cm above it + HAND_U, HAND_V, HAND_Z0 = 0.100, (-0.018, 0.024), 0.03 + FING_U, FING_V, FING_Z = (0.039, 0.066), (-0.009, 0.013), (-0.010, 0.045) + # wrist and forearm (t16_arm, measured at low grasps): lowest point above the grasp point vs the distance from the + # grasp point towards the robot base; they span ~13 cm to either side of that line + ARM_D = (-0.05, 0.05, 0.10, 0.15, 0.20) + ARM_Z = (0.097, 0.100, 0.155, 0.185, 0.31) + ARM_LAT = 0.13 + + def _footprint(self, q, yaw): + """sample points (xy) of the hand slab and of the open fingers for a grasp at q with gripper yaw `yaw`""" + a = np.array([-np.sin(yaw), np.cos(yaw)]) # finger axis + c = np.array([np.cos(yaw), np.sin(yaw)]) + hand = [q + u * a + v * c for u in np.linspace(-self.HAND_U, self.HAND_U, 21) + for v in np.linspace(*self.HAND_V, 5)] + fing = [q + sg * u * a + v * c for sg in (-1, 1) for u in np.linspace(*self.FING_U, 4) + for v in np.linspace(*self.FING_V, 3)] + return np.array(hand), np.array(fing) + + def grasp_clearance(self, q, zg, yaw, ignore=()): + """smallest horizontal clearance (m) between the hand / open fingers of a grasp at (q, zg) and any standing + bottle (other than `ignore`) or the small table; negative = collision""" + q = np.asarray(q, float)[:2] + hand, fing = self._footprint(q, yaw) + best = 1.0 + for b in BOTTLES: + if b in ignore or self.held(b) or self.tilt(b) > np.radians(30): + continue + p = self.foot(b)[:2] + top = self.foot(b)[2] + H_TOT + r = RB * 1.42 + if top > zg + self.HAND_Z0: + best = min(best, float(np.min(np.linalg.norm(hand - p, axis=1))) - r) + best = min(best, float(np.min(np.linalg.norm(fing - p, axis=1))) - r) + # the wrist / forearm sloping back towards the robot base over a tall standing bottle + ub = np.array([-0.66, 0.0]) - q + ub /= max(float(np.linalg.norm(ub)), 1e-6) + along, lat = float((p - q) @ ub), float((p - q) @ np.array([-ub[1], ub[0]])) + if self.ARM_D[0] <= along <= self.ARM_D[-1] and abs(lat) < self.ARM_LAT + r: + if top > zg + float(np.interp(along, self.ARM_D, self.ARM_Z)) - 0.01: + best = min(best, -0.01) + # the small table's top plate (and legs) when the grasp is below its top surface + R, P = self.table_R(), self.table_pos() + ztop = P[2] + TABLE_H / 2 + for pts, z0, z1 in ((hand, zg + self.HAND_Z0, zg + 0.13), (fing, zg + self.FING_Z[0], zg + self.FING_Z[1])): + if z0 > ztop + 0.003: + continue + loc = (pts - P[:2]) @ R[:2, :2] + if z1 > ztop - TOP_T: # the plate's height band + d = np.maximum(np.abs(loc) - TOP_HW, 0.0) + inside = np.all(np.abs(loc) < TOP_HW, axis=1) + dist = np.where(inside, -0.01, np.linalg.norm(d, axis=1)) + best = min(best, float(np.min(dist))) + return best + + def stopper_grasp(self, b): + """(xy, z, yaw) of the stopper grasp of a lying bottle: fingers across its axis, fingertips >= 4 mm above the + surface below""" + k = self.cap_xyz(b) + ax = self.bR(b)[:2, 2] + yaw = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else self.sk.yaw + zg = max(float(k[2]), self.surface_z(k[:2]) + envs.FINGERTIP_BELOW_SITE + 0.004) + return k[:2], zg, yaw + + def body_grasp(self, b, along=None): + """(xy, z, yaw) of a grasp across a lying bottle's body, `along` m from its bottom (default: the middle)""" + R = self.bR(b) + a = HF + (HB - HF) / 2 if along is None else float(along) + c = self.foot(b) + R[:, 2] * a + ax = R[:2, 2] + yaw = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else self.sk.yaw + zg = max(float(c[2]), self.surface_z(c[:2]) + envs.FINGERTIP_BELOW_SITE + 0.004) + return c[:2], zg, yaw + + def staging_spot(self, b): + """a free place on the main table to lay a fallen bottle down: far from the small table and the other bottles, + within the arm's comfortable reach""" + tx, ty = self.table_pos()[:2] + best, bq = -1.0, None + for x in np.arange(tx - 0.30, tx + 0.06, 0.03): + for y in np.arange(ty - 0.30, ty + 0.31, 0.03): + # within reach, and >= 14 cm inside the main table's edges (it spans x, y = +-0.5, +-0.6): a bottle laid + # down too close to the near edge rolled off onto the floor (measured) + if np.hypot(x + 0.66, y) > 0.66 or np.hypot(x + 0.66, y) < 0.33 or x < -0.36 or abs(y) > 0.46: + continue + loc = self.table_R()[:2, :2].T @ (np.array([x, y]) - np.array([tx, ty])) + dt = float(np.linalg.norm(np.maximum(np.abs(loc) - TOP_HW, 0.0))) + if np.all(np.abs(loc) < TOP_HW): + continue + do = min([float(np.linalg.norm(self.foot(o)[:2] - [x, y])) for o in BOTTLES if o != b] + + [float(np.linalg.norm(self.cap_xyz(o)[:2] - [x, y])) for o in BOTTLES if o != b]) + sc = min(dt - 0.10, do - 0.14) # the bottle lies ~16 cm long around the point + if sc > best and min(self.grasp_clearance([x, y], TZ + 0.016, yw, ignore=(b,)) + for yw in (0.0, np.pi / 2)) > 0.01: + best, bq = sc, np.array([x, y]) + return bq + + def stage(self, b, v=0.12): + """the stopper of a fallen bottle cannot be reached: grasp its body at a point where the hand is clear (the + bottle then hangs from the grasp), carry it to free space on the main table, let it down there so that it falls + over away from everything. Returns True if it was moved.""" + sk = self.sk + for along in (0.055, 0.035, 0.075, 0.015, 0.095): + q, zg, yaw = self.body_grasp(b, along) + if self.grasp_clearance(q, zg, yaw, ignore=(b,)) >= 0.004: + break + else: + return False + dst = self.staging_spot(b) + if dst is None: + return False + sk.set_gripper(False, steps=8) + self._lift_to(Z_CARRY) + self._go([q[0], q[1], TZ + Z_CARRY], yaw=yaw, speed=v) + self._go([q[0], q[1], zg + 0.03], speed=0.10) + self._go([q[0], q[1], zg], speed=0.03, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + if not self.held(b): + sk.set_gripper(False, steps=8) + self._go([q[0], q[1], TZ + Z_CARRY], speed=0.1) + return False + self._go([q[0], q[1], zg + 0.04], speed=0.05) + self._go([q[0], q[1], TZ + Z_HANG], speed=0.10) + sk.hold(15) + self._go([dst[0], dst[1], TZ + Z_HANG], speed=0.10) + sk.hold(15) + drop = envs.obj_min_z(self.env, b) - (TZ + 0.012) + cur = sk.eef_pos() + self._go([cur[0], cur[1], cur[2] - drop], speed=0.08) + sk.set_gripper(False, steps=12) + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + Z_HANG], speed=0.15) + self._settle(b, 40) + return True + + def restand(self, i, gap=CAREFUL_GAP, err=None): + """stand bottle i up again on its spot: if the stopper cannot be grasped without the hand touching a standing + bottle or the small table, first lay the bottle down in free space; grasp the stopper, let the bottle hang, + carry it over the spot, lower it until its bottom is `gap` above the table top, let go""" + b, c = BOTTLES[i], COLOURS[i] + q, zg, yaw = self.stopper_grasp(b) + if self.grasp_clearance(q, zg, yaw, ignore=(b,)) < 0.005: + self.stage(b) + if not self.pick_stopper(b): + return False + tgt = self.spot_world(c)[:2] + (np.asarray(err, float) if err is not None else 0.0) + self.put_held(b, tgt, gap, z_carry=Z_HANG, v=0.10) + self._settle(b) + return self.on_spot(i) + + def place(self, i, gap, err=None, z_carry=Z_CARRY, yaw=0.0, v=0.2): + """one stage: pick bottle i (by the neck if it stands, by the stopper if it lies) and put it on its spot""" + b, c = BOTTLES[i], COLOURS[i] + tgt = self.spot_world(c)[:2] + (np.asarray(err, float) if err is not None else 0.0) + if self.upright(b): + if not self.pick_neck(b, z_carry=z_carry, yaw=yaw, v=v) and not self.pick_neck(b, z_carry=z_carry, + yaw=yaw, v=v): + return False + self.put_held(b, tgt, gap, z_carry=z_carry, yaw=yaw, v=v) + else: + if not self.pick_stopper(b): + return False + self.put_held(b, tgt, gap, z_carry=Z_HANG, v=0.10) + self._settle(b) + return True + + def repair_order(self, idx): + """bottles to fix: one standing upright off its spot first (it may be the heavy one: re-placing it rocks the + table), then lying ones whose stopper is easiest to reach""" + def key(j): + b = BOTTLES[j] + if self.upright(b): + return (0, 0.0) + q, zg, yaw = self.stopper_grasp(b) + return (1, -self.grasp_clearance(q, zg, yaw, ignore=(b,))) + return sorted(idx, key=key) + + def fix(self, i, gap=CAREFUL_GAP): + if self.upright(BOTTLES[i]): + self.place(i, gap) + else: + self.restand(i, gap) + + def check_and_repair(self, rounds=3, gap=CAREFUL_GAP): + """look at every bottle; stand up / re-place every one that is not on its spot""" + for _ in range(rounds): + bad = [i for i in range(4) if not self.on_spot(i)] + if not bad: + return True + for i in self.repair_order(bad): + if not self.on_spot(i): + self.fix(i, gap) + return all(self.stages()) + + def order(self, mode, rng=None, first=None): + o = self._far_first(self.inst["spot_of"], self.inst["supply_side"], *self.inst["table_xy"]) + if mode == "near_first": + o = o[::-1] + elif mode == "random": + o = [o[j] for j in rng.permutation(4)] + if first is not None: + o = [first] + [c for c in o if c != first] + return [COLOURS.index(c) for c in o] + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("noise_seed", 0)) + order = self.order(params.get("order", "far_first"), rng, params.get("first")) + gap = params.get("gap") # None: random in NAIVE_GAP per placement + bias = np.array([float(params.get("bias_x", 0.0)), 0.0]) + rand = float(params.get("rand", 0.0)) + for i in order: + g = float(rng.uniform(*NAIVE_GAP)) if gap is None else float(gap) + e = bias + (rng.uniform(-rand, rand, 2) if rand else 0.0) + self.place(i, g, err=e, z_carry=params.get("z_carry", Z_CARRY), v=params.get("v", 0.2)) + if params.get("repair") == "each": # looks at all bottles after every step and stands fallen ones up + for _ in range(2): + bad = [j for j in range(4) if self.mon["ever"][j] and not self.on_spot(j)] + for j in self.repair_order(bad): + if not self.on_spot(j): + self.fix(j) + if params.get("check"): + self.check_and_repair() + self._lift_to(Z_CARRY) + self.sk.hold(10) + + # naive = Sonnet-like habits (lh_nudge_row / lh_bystander pilots): careful, far spots first, carries high, vertical + # descent, releases 1-4 cm above the surface, places ~1-2 cm too far forward +- 0.6 cm, no special plan for the + # table, does not look back at the bottles it has already put down + def default_params(self, inst): + return dict(order="far_first", gap=None, bias_x=float(inst["naive_bias_x"]), rand=NAIVE_RAND, + noise_seed=int(inst["seed"]) * 13, repair=None, check=False) + + def oracle_params(self, inst): + """knows the short leg: puts the heavy bottle on its corner first (the table rocks while nothing stands on it), + sets the others down gently, checks at the end""" + return dict(order="far_first", first=inst["heavy"], gap=CAREFUL_GAP, bias_x=0.0, rand=0.0, repair="each", + check=True) + + def adapt_params(self, inst, history): + """attempt >= 2: the bottle whose placement rocked the table (from the event of the failed attempt) first; the + same imprecise habits otherwise; stands fallen bottles up and checks at the end""" + first = None + for h in history: + for e in h["outcome"].get("events", []): + if e.get("event") == "table_rocked" and e.get("released"): + first = e["released"] + break + if first: + break + return dict(self.default_params(inst), first=first, repair="each", check=True) + + def blind_params(self, inst, attempt, rng): + """the naive behaviour with a random order and random variation, no history, no look back""" + return dict(self.default_params(inst), order="random", noise_seed=int(rng.integers(1 << 30)), + z_carry=float(rng.uniform(0.40, 0.45)), v=float(rng.uniform(0.12, 0.25)), + bias_x=float(rng.uniform(*NAIVE_BIAS))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """oracle / naive: one attempt. adaptive: attempt 1 = naive + stands fallen bottles up after every step and checks + at the end; attempts >= 2: the rocking bottle first. blind: naive with a random order. + Extra kinds (controls): naive_heavy_first (naive habits, 1-4 cm drops, but the heavy bottle first), + naive_repair (= adaptive's first attempt), naive_near_first, switch (order change only, no repair), + oracle_noise (+-5 mm).""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + single = ("oracle", "naive", "naive_heavy_first", "naive_repair", "oracle_noise", "naive_near_first") + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = (dict(self.default_params(inst), repair="each", check=True) if a == 0 else + self.adapt_params(inst, history)) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": + params = (self.default_params(inst) if a == 0 else + dict(self.adapt_params(inst, history), repair=None, check=False)) + elif kind == "naive_heavy_first": + params = dict(self.default_params(inst), first=inst["heavy"]) + elif kind == "naive_repair": + params = dict(self.default_params(inst), repair="each", check=True) + elif kind == "naive_near_first": + params = dict(self.default_params(inst), order="near_first") + elif kind == "oracle_noise": + params = dict(self.oracle_params(inst), rand=0.005, noise_seed=int(seed) * 7 + a) + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in single: + break + return history