Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/layer4_plan.py +174 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/qwen_vl_server.py +535 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/record_breakfast_service.py +89 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/summarize.py +33 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/agent/images.py +47 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/agent/tools.py +392 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/base.py +364 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/codex.py +687 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-flash_high.json +15 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-chatgpt-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json +18 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/redteam.py +59 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l5_slide.py +577 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l6_sequence.py +513 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/lh_balance_board.py +817 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/lh_bridge.py +1101 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/lh_nudge_row.py +821 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/lh_shelf_droop.py +1009 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/export_status.json +25 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/agent/backends/chat_completions.py +150 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/arm_specs/l3_card_shelf.py +65 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/arm_specs/l7_key_turn.py +34 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/codex.py +687 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/fakeapi.py +188 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/framework_codex.py +542 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_2.1.267_0399c793ff571d59_claude-opus-5-5_high.json +15 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_claude-opus-5-5_high.json +15 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/codex-generic_0.163.0_399ff69c431c066e_deepseek-v4.1-flash_high.json +23 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/codex_0.156.0_78a11f06e0a2dda4_gpt-6-astra_high.json +36 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-v4.1-flash_high.json +15 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/redteam.py +59 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/reference.py +143 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/real/DRIVER.md +144 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/real/__init__.py +10 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/real/driver_template.py +196 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/real/executor.py +138 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/l5_slide.py +577 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/lh_balance_board.py +817 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/lh_bridge.py +1101 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/lh_nudge_row.py +821 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/tasks/l6_count.py +562 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/tasks/lh_bystander.py +830 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/fakeapi.py +188 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-opus-5-5_high.json +15 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json +23 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-v4.1-flash_high.json +15 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json +18 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/redteam.py +59 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/real/executor.py +138 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l5_iterative.py +136 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/lh_breakfast_service.py +546 -0
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/layer4_plan.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Layer-4 minimal intervention (user 2026-10-30: 先用 opus; design reports/layer4_intervention_20261030/PLAN.md). Opus only, on the
|
| 2 |
+
two tasks whose every main-table instance failed all three attempts. Same protocol as the layer-3 ladder (a fresh
|
| 3 |
+
single-attempt agent, the instance's own failed attempt 1 in history/, F1), only the Result section differs:
|
| 4 |
+
|
| 5 |
+
f1 "The environment judged that attempt: failed."
|
| 6 |
+
v + a generic reminder to check the goal before ending; no cause
|
| 7 |
+
hp + "Cause: " the hidden variable (arm_specs reveal)
|
| 8 |
+
fx + cause + how to succeed (arm_specs fix, validated below)
|
| 9 |
+
|
| 10 |
+
python scripts/layer4_plan.py validate texts + oracle + LA push, debug and test seeds -> results/_layer4/fix_validate.json
|
| 11 |
+
python scripts/layer4_plan.py build debug records -> runs/api/layer4i_20261030/debug/<cond>.json + tasks.txt
|
| 12 |
+
python scripts/layer4_plan.py build test the same from the failed attempts of batch l4i_first (test seeds)
|
| 13 |
+
python scripts/layer4_plan.py report debug|test per instance per condition: outcome, process events, closing claim
|
| 14 |
+
"""
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
import subprocess
|
| 18 |
+
import sys
|
| 19 |
+
|
| 20 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 21 |
+
sys.path.insert(0, ROOT)
|
| 22 |
+
API = os.path.join(ROOT, "runs", "api")
|
| 23 |
+
OUT = os.path.join(API, "layer4i_20261030")
|
| 24 |
+
FIXV = os.path.join(ROOT, "results", "_layer4", "fix_validate.json")
|
| 25 |
+
CONDS = ("f1", "v", "hp", "fx")
|
| 26 |
+
DEBUG = {"lh_clear_cover": {3000: "cc_opus1", 3001: "cc_opus_s2", 3003: "cc_opus_s3"},
|
| 27 |
+
"lh_tidy_stack": {3000: "cc_opus1", 3002: "cc_opus_s2", 3003: "cc_opus_s3"}}
|
| 28 |
+
# frozen before any test-seed run: first four seeds from 3100 with the trap active (clear_cover: covered, (seed * 7) % 20 < 10;
|
| 29 |
+
# tidy_stack: a soft box that is not on top of a nearest-first pile, (seed * 7) % 20 < 18 and % 4 != 3)
|
| 30 |
+
TEST = {"lh_clear_cover": [3100, 3101, 3103, 3104], "lh_tidy_stack": [3100, 3102, 3103, 3104]}
|
| 31 |
+
REMINDER = ("Before you end an attempt, use your observations to check whether every part of the goal is actually met; "
|
| 32 |
+
"if it is not, keep working.")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def events(log):
|
| 36 |
+
return [json.loads(line) for line in open(os.path.join(log, "events.jsonl")) if line.strip() and "\0" not in line]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def batch_log(batch, task, seed):
|
| 40 |
+
runs = json.load(open(os.path.join(API, batch, "manifest.json")))["runs"]
|
| 41 |
+
return next(r["log"] for r in runs if r["task"] == task and r["seed"] == seed and r.get("status") == "done"
|
| 42 |
+
and r.get("cond") == "harness")
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def la_push(task, inst):
|
| 46 |
+
"""the Fix text's lid push as LA commands; returns (z_push, sweep length, lid off?)"""
|
| 47 |
+
import numpy as np
|
| 48 |
+
from lffbench.agent.tools import ToolExecutor
|
| 49 |
+
from lffbench.tasks import lh_clear_cover as cc
|
| 50 |
+
from scripts.validate_ladder_fix import la_move
|
| 51 |
+
task.reset_instance(inst)
|
| 52 |
+
sim = task.env.sim
|
| 53 |
+
off = np.array(sim.data.body_xpos[sim.model.body_name2id("robot0_base")], float).copy()
|
| 54 |
+
ex = ToolExecutor(task, inst, image_res=64, cams=("agentview",))
|
| 55 |
+
cov = task.covering()
|
| 56 |
+
lp = task.lid_pos()
|
| 57 |
+
b = np.asarray(inst["boxes"][cov], float)
|
| 58 |
+
o = np.asarray(inst["boxes"][[c for c in cc.COLORS if c != cov][0]], float)
|
| 59 |
+
d = np.array((0.0, float(np.sign(b[1] - o[1]))))
|
| 60 |
+
back = cc.LID_HALF + 0.03
|
| 61 |
+
s = lp[:2] - d * back
|
| 62 |
+
z = lp[2] + cc.LID_T / 2 - cc.PUSH_DEPTH + cc.TIP
|
| 63 |
+
need = float((b - lp[:2]) @ d) + cc.BOX_OUT + back + 0.03
|
| 64 |
+
e = s + d * need
|
| 65 |
+
sb, eb, zb = s - off[:2], e - off[:2], z - off[2]
|
| 66 |
+
la_move(task, ex, off, gripper="close")
|
| 67 |
+
la_move(task, ex, off, x=sb[0], y=sb[1], z=zb + 0.08, yaw=0)
|
| 68 |
+
la_move(task, ex, off, x=sb[0], y=sb[1], z=zb)
|
| 69 |
+
la_move(task, ex, off, x=eb[0], y=eb[1], z=zb, speed=cc.PUSH_SPEED)
|
| 70 |
+
la_move(task, ex, off, z=zb + 0.10, speed=0.2)
|
| 71 |
+
return float(zb), float(need), task.covering() is None
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def cmd_validate():
|
| 75 |
+
import importlib
|
| 76 |
+
import pkgutil
|
| 77 |
+
from lffbench import arm_specs
|
| 78 |
+
from lffbench import tasks as task_pkg
|
| 79 |
+
from lffbench.agent.robot_server import strip_axes
|
| 80 |
+
from lffbench.task_base import TASKS
|
| 81 |
+
for m in pkgutil.iter_modules(task_pkg.__path__):
|
| 82 |
+
importlib.import_module(f"lffbench.tasks.{m.name}")
|
| 83 |
+
rows = []
|
| 84 |
+
for name, seeds in ((t, sorted(DEBUG[t]) + TEST[t]) for t in DEBUG):
|
| 85 |
+
task = TASKS[name](cam_res=64)
|
| 86 |
+
for seed in seeds:
|
| 87 |
+
inst = task.sample_instance(seed)
|
| 88 |
+
clean = {k: v for k, v in inst.items() if not k.startswith("_")}
|
| 89 |
+
params = dict(task.oracle_params(inst))
|
| 90 |
+
row = dict(key=f"{name}:{seed}", hidden=clean.get("cover") or clean.get("soft_colour"))
|
| 91 |
+
row["oracle_success"] = bool(task.run_scripted("oracle", inst, k=1)[0]["outcome"]["success"])
|
| 92 |
+
row["naive_success"] = bool(task.run_scripted("naive", inst, k=1)[0]["outcome"]["success"])
|
| 93 |
+
if name == "lh_clear_cover":
|
| 94 |
+
params["z_push"], params["push_len"], row["la_lid_off"] = la_push(task, inst)
|
| 95 |
+
task.execute(inst, dict(plan="naive", check="side")) # the placing part, after the LA push
|
| 96 |
+
row["la_then_place_success"] = bool(task.outcome(inst)["success"])
|
| 97 |
+
cause, fx = arm_specs.reveal(name, clean), arm_specs.fix(name, clean, params)
|
| 98 |
+
row.update(cause=cause, fix=fx, no_axis_labels=strip_axes(cause + fx) == cause + fx)
|
| 99 |
+
row["ok"] = bool(row["oracle_success"] and not row["naive_success"] and row["hidden"] and row["no_axis_labels"]
|
| 100 |
+
and row.get("la_lid_off", True) and row.get("la_then_place_success", True))
|
| 101 |
+
rows.append(row)
|
| 102 |
+
print("OK " if row["ok"] else "BAD", json.dumps({k: v for k, v in row.items() if k not in ("cause", "fix")}), flush=True)
|
| 103 |
+
os.makedirs(os.path.dirname(FIXV), exist_ok=True)
|
| 104 |
+
json.dump(dict(rows=rows, n=len(rows), n_ok=sum(r["ok"] for r in rows)), open(FIXV, "w"), indent=1)
|
| 105 |
+
print(f"{sum(r['ok'] for r in rows)}/{len(rows)} ok -> {FIXV}")
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def sources(stage):
|
| 109 |
+
if stage == "debug":
|
| 110 |
+
return [(t, s, batch_log(b, t, s)) for t, d in DEBUG.items() for s, b in sorted(d.items())]
|
| 111 |
+
out = []
|
| 112 |
+
for r in json.load(open(os.path.join(API, "l4i_first", "manifest.json")))["runs"]:
|
| 113 |
+
if r["status"] == "done":
|
| 114 |
+
d = next((e for e in events(r["log"]) if e["ev"] == "done" and e.get("attempt") == 1), None)
|
| 115 |
+
if d is not None and not d["success"]:
|
| 116 |
+
out.append((r["task"], r["seed"], r["log"]))
|
| 117 |
+
return out
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def cmd_build(stage):
|
| 121 |
+
fixes = {r["key"]: r for r in json.load(open(FIXV))["rows"]}
|
| 122 |
+
base = os.path.join(OUT, stage)
|
| 123 |
+
os.makedirs(base, exist_ok=True)
|
| 124 |
+
maps, tasks = {c: {} for c in CONDS}, []
|
| 125 |
+
for task, seed, log in sources(stage):
|
| 126 |
+
key = f"{task}:{seed}"
|
| 127 |
+
if not fixes[key]["ok"]:
|
| 128 |
+
raise SystemExit(f"{key}: fix text not validated")
|
| 129 |
+
tasks.append(key)
|
| 130 |
+
cause = "Cause: " + fixes[key]["cause"]
|
| 131 |
+
extra = dict(f1="", v=REMINDER, hp=cause, fx=cause + "\n\n" + fixes[key]["fix"])
|
| 132 |
+
for c in CONDS:
|
| 133 |
+
dst = os.path.join(base, c, f"{task}_s{seed}")
|
| 134 |
+
if not os.path.isdir(dst):
|
| 135 |
+
subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), log, dst,
|
| 136 |
+
"--result-extra", extra[c]], check=True, capture_output=True)
|
| 137 |
+
maps[c][key] = dst
|
| 138 |
+
for c in CONDS:
|
| 139 |
+
json.dump(maps[c], open(os.path.join(base, f"{c}.json"), "w"), indent=1)
|
| 140 |
+
open(os.path.join(base, "tasks.txt"), "w").write("\n".join(tasks) + "\n")
|
| 141 |
+
print(stage, len(tasks), "instances x", len(CONDS), "conditions")
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def cmd_report(stage):
|
| 145 |
+
rows = {}
|
| 146 |
+
for c in CONDS:
|
| 147 |
+
p = os.path.join(API, f"l4i_{c}_{stage}", "manifest.json")
|
| 148 |
+
if not os.path.exists(p):
|
| 149 |
+
continue
|
| 150 |
+
for r in json.load(open(p))["runs"]:
|
| 151 |
+
key = f"{r['task']}:{r['seed']}"
|
| 152 |
+
cell = dict(status=r["status"])
|
| 153 |
+
if r["status"] == "done":
|
| 154 |
+
ev = events(r["log"])
|
| 155 |
+
d = next((e for e in ev if e["ev"] == "done"), {})
|
| 156 |
+
o = d.get("outcome") or {}
|
| 157 |
+
cell.update(success=bool(d.get("success")), calls=d.get("step"), reason=(d.get("reason") or "")[:300],
|
| 158 |
+
failure=o.get("failure"), detail=(o.get("detail") or "")[:300], log=r["log"],
|
| 159 |
+
events=[e.get("ev") for e in o.get("events", []) if isinstance(e, dict)][:40],
|
| 160 |
+
cover_removed=o.get("cover_removed"))
|
| 161 |
+
rows.setdefault(key, {})[c] = cell
|
| 162 |
+
print("| instance | " + " | ".join(CONDS) + " |")
|
| 163 |
+
print("|---|" + "---|" * len(CONDS))
|
| 164 |
+
f = lambda x: "-" if x is None else ("S" if x.get("success") else ("F" if x.get("status") == "done" else x.get("status")))
|
| 165 |
+
for k, v in sorted(rows.items()):
|
| 166 |
+
print(f"| {k} | " + " | ".join(f(v.get(c)) for c in CONDS) + " |")
|
| 167 |
+
for c in CONDS:
|
| 168 |
+
xs = [v[c] for v in rows.values() if c in v and v[c].get("status") == "done"]
|
| 169 |
+
print(c, f"{sum(x['success'] for x in xs)}/{len(xs)}")
|
| 170 |
+
json.dump(rows, open(os.path.join(OUT, f"report_{stage}.json"), "w"), indent=1)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
if __name__ == "__main__":
|
| 174 |
+
{"validate": cmd_validate, "build": lambda: cmd_build(sys.argv[2]), "report": lambda: cmd_report(sys.argv[2])}[sys.argv[1]]()
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/qwen_vl_server.py
ADDED
|
@@ -0,0 +1,535 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Minimal OpenAI-compatible Chat Completions server (with tool calling) for Qwen3-VL.
|
| 3 |
+
|
| 4 |
+
Runs a local HF-format Qwen3-VL checkpoint with transformers (>= 4.57) on one
|
| 5 |
+
CUDA-compatible device (here: Alibaba PPU) and exposes:
|
| 6 |
+
|
| 7 |
+
POST /v1/chat/completions OpenAI chat.completion (non-streaming; stream=true
|
| 8 |
+
is emulated: the full answer is generated first
|
| 9 |
+
and then sent as SSE chunks)
|
| 10 |
+
GET /v1/models lists the single served model
|
| 11 |
+
GET /health liveness + device memory
|
| 12 |
+
|
| 13 |
+
Request format accepted (subset of OpenAI):
|
| 14 |
+
messages: system / developer / user / assistant (with tool_calls) / tool
|
| 15 |
+
user/tool content may be a string or a list of
|
| 16 |
+
{"type":"text","text":...} and
|
| 17 |
+
{"type":"image_url","image_url":{"url": "data:image/...;base64,..." | http(s) URL | file path}}
|
| 18 |
+
tools: [{"type":"function","function":{"name","description","parameters"}}]
|
| 19 |
+
tool_choice: "auto" (default) | "none" (tools hidden from the prompt) |
|
| 20 |
+
"required" (generation is prefixed with "<tool_call>\n") |
|
| 21 |
+
{"type":"function","function":{"name":X}} (prefixed with the call header for X)
|
| 22 |
+
parallel_tool_calls: false -> only the first parsed tool call is returned
|
| 23 |
+
max_tokens / max_completion_tokens (default --default-max-tokens, 1024)
|
| 24 |
+
temperature (absent or 0 -> greedy), top_p, top_k, seed, stop (str or list)
|
| 25 |
+
Ignored: n (always 1), response_format, logprobs, presence/frequency penalty, user.
|
| 26 |
+
|
| 27 |
+
The model emits Hermes-style <tool_call>{"name":..., "arguments":{...}}</tool_call>
|
| 28 |
+
blocks; they are parsed into choices[0].message.tool_calls with arguments as a JSON
|
| 29 |
+
string, and the remaining text (if any) becomes message.content (else null).
|
| 30 |
+
|
| 31 |
+
Generation is serialised with a lock (one request on the device at a time); the
|
| 32 |
+
HTTP layer is a stdlib ThreadingHTTPServer so /health stays responsive.
|
| 33 |
+
"""
|
| 34 |
+
from __future__ import annotations
|
| 35 |
+
|
| 36 |
+
import argparse
|
| 37 |
+
import base64
|
| 38 |
+
import io
|
| 39 |
+
import json
|
| 40 |
+
import logging
|
| 41 |
+
import os
|
| 42 |
+
import re
|
| 43 |
+
import sys
|
| 44 |
+
import threading
|
| 45 |
+
import time
|
| 46 |
+
import traceback
|
| 47 |
+
import urllib.request
|
| 48 |
+
import uuid
|
| 49 |
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 50 |
+
|
| 51 |
+
LOG = logging.getLogger("qwen_vl_server")
|
| 52 |
+
|
| 53 |
+
TOOL_CALL_RE = re.compile(r"<tool_call>\s*(.*?)\s*</tool_call>", re.DOTALL)
|
| 54 |
+
END_MARKERS = ("<|im_end|>", "<|endoftext|>")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# ----------------------------------------------------------------------------
|
| 58 |
+
# Request conversion
|
| 59 |
+
# ----------------------------------------------------------------------------
|
| 60 |
+
class BadRequest(Exception):
|
| 61 |
+
pass
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def load_image(url: str):
|
| 65 |
+
from PIL import Image
|
| 66 |
+
|
| 67 |
+
if url.startswith("data:"):
|
| 68 |
+
try:
|
| 69 |
+
_, b64 = url.split(",", 1)
|
| 70 |
+
except ValueError as e:
|
| 71 |
+
raise BadRequest("malformed data URL") from e
|
| 72 |
+
raw = base64.b64decode(b64)
|
| 73 |
+
elif url.startswith("http://") or url.startswith("https://"):
|
| 74 |
+
with urllib.request.urlopen(url, timeout=30) as r:
|
| 75 |
+
raw = r.read()
|
| 76 |
+
else:
|
| 77 |
+
path = url[len("file://"):] if url.startswith("file://") else url
|
| 78 |
+
with open(path, "rb") as f:
|
| 79 |
+
raw = f.read()
|
| 80 |
+
img = Image.open(io.BytesIO(raw))
|
| 81 |
+
img.load()
|
| 82 |
+
return img.convert("RGB")
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def convert_content(content, images: list):
|
| 86 |
+
"""OpenAI content (str | list[part] | None) -> Qwen template content.
|
| 87 |
+
|
| 88 |
+
Images are replaced by {"type": "image"} placeholders and the decoded PIL images
|
| 89 |
+
are appended to `images` in prompt order (the chat template emits one
|
| 90 |
+
<|vision_start|><|image_pad|><|vision_end|> per placeholder, in the same order).
|
| 91 |
+
"""
|
| 92 |
+
if content is None:
|
| 93 |
+
return ""
|
| 94 |
+
if isinstance(content, str):
|
| 95 |
+
return content
|
| 96 |
+
if not isinstance(content, list):
|
| 97 |
+
raise BadRequest(f"unsupported content type: {type(content).__name__}")
|
| 98 |
+
out = []
|
| 99 |
+
for part in content:
|
| 100 |
+
if isinstance(part, str):
|
| 101 |
+
out.append({"type": "text", "text": part})
|
| 102 |
+
continue
|
| 103 |
+
ptype = part.get("type")
|
| 104 |
+
if ptype in ("text", "input_text"):
|
| 105 |
+
out.append({"type": "text", "text": part.get("text", "")})
|
| 106 |
+
elif ptype in ("image_url", "input_image", "image"):
|
| 107 |
+
iu = part.get("image_url", part.get("image"))
|
| 108 |
+
url = iu.get("url") if isinstance(iu, dict) else iu
|
| 109 |
+
if not isinstance(url, str):
|
| 110 |
+
raise BadRequest("image part without url")
|
| 111 |
+
try:
|
| 112 |
+
images.append(load_image(url))
|
| 113 |
+
except BadRequest:
|
| 114 |
+
raise
|
| 115 |
+
except Exception as e: # noqa: BLE001
|
| 116 |
+
raise BadRequest(f"could not load image ({url[:60]}...): {type(e).__name__}: {e}") from e
|
| 117 |
+
out.append({"type": "image"})
|
| 118 |
+
else:
|
| 119 |
+
raise BadRequest(f"unsupported content part type: {ptype}")
|
| 120 |
+
return out
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def text_only(content) -> str:
|
| 124 |
+
if content is None:
|
| 125 |
+
return ""
|
| 126 |
+
if isinstance(content, str):
|
| 127 |
+
return content
|
| 128 |
+
return "".join(p.get("text", "") for p in content if isinstance(p, dict))
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def convert_messages(messages: list):
|
| 132 |
+
if not isinstance(messages, list) or not messages:
|
| 133 |
+
raise BadRequest("messages must be a non-empty list")
|
| 134 |
+
images: list = []
|
| 135 |
+
system_texts = []
|
| 136 |
+
conv = []
|
| 137 |
+
for m in messages:
|
| 138 |
+
role = m.get("role")
|
| 139 |
+
if role in ("system", "developer"):
|
| 140 |
+
# The Qwen template only renders a leading system message; merge all of them.
|
| 141 |
+
system_texts.append(text_only(m.get("content")))
|
| 142 |
+
elif role == "user":
|
| 143 |
+
conv.append({"role": "user", "content": convert_content(m.get("content"), images)})
|
| 144 |
+
elif role == "assistant":
|
| 145 |
+
c = m.get("content")
|
| 146 |
+
msg = {"role": "assistant", "content": text_only(c) if not isinstance(c, str) else c}
|
| 147 |
+
tcs = m.get("tool_calls") or []
|
| 148 |
+
if tcs:
|
| 149 |
+
norm = []
|
| 150 |
+
for tc in tcs:
|
| 151 |
+
fn = tc.get("function", tc)
|
| 152 |
+
args = fn.get("arguments", {})
|
| 153 |
+
if not isinstance(args, str):
|
| 154 |
+
args = json.dumps(args, ensure_ascii=False)
|
| 155 |
+
norm.append({"type": "function", "function": {"name": fn.get("name", ""), "arguments": args}})
|
| 156 |
+
msg["tool_calls"] = norm
|
| 157 |
+
conv.append(msg)
|
| 158 |
+
elif role in ("tool", "function"):
|
| 159 |
+
conv.append({"role": "tool", "content": convert_content(m.get("content"), images)})
|
| 160 |
+
else:
|
| 161 |
+
raise BadRequest(f"unsupported role: {role}")
|
| 162 |
+
if system_texts:
|
| 163 |
+
conv.insert(0, {"role": "system", "content": "\n\n".join(system_texts)})
|
| 164 |
+
return conv, images
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
# ----------------------------------------------------------------------------
|
| 168 |
+
# Output parsing
|
| 169 |
+
# ----------------------------------------------------------------------------
|
| 170 |
+
def _loads_lenient(s: str):
|
| 171 |
+
s = s.strip()
|
| 172 |
+
try:
|
| 173 |
+
return json.loads(s)
|
| 174 |
+
except json.JSONDecodeError:
|
| 175 |
+
pass
|
| 176 |
+
# common slips: trailing garbage after the object, missing final brace
|
| 177 |
+
start = s.find("{")
|
| 178 |
+
if start >= 0:
|
| 179 |
+
dec = json.JSONDecoder()
|
| 180 |
+
try:
|
| 181 |
+
obj, _ = dec.raw_decode(s[start:])
|
| 182 |
+
return obj
|
| 183 |
+
except json.JSONDecodeError:
|
| 184 |
+
pass
|
| 185 |
+
for extra in ("}", "}}", "\"}}"):
|
| 186 |
+
try:
|
| 187 |
+
return json.loads(s[start:] + extra)
|
| 188 |
+
except json.JSONDecodeError:
|
| 189 |
+
continue
|
| 190 |
+
return None
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def parse_tool_calls(text: str):
|
| 194 |
+
"""Return (content_or_None, tool_calls_list)."""
|
| 195 |
+
calls = []
|
| 196 |
+
spans = []
|
| 197 |
+
for mt in TOOL_CALL_RE.finditer(text):
|
| 198 |
+
spans.append(mt.span())
|
| 199 |
+
calls.append(mt.group(1))
|
| 200 |
+
# an unterminated trailing <tool_call> (e.g. hit max_tokens / model forgot the tag)
|
| 201 |
+
last_end = spans[-1][1] if spans else 0
|
| 202 |
+
tail_idx = text.find("<tool_call>", last_end)
|
| 203 |
+
if tail_idx >= 0:
|
| 204 |
+
spans.append((tail_idx, len(text)))
|
| 205 |
+
calls.append(text[tail_idx + len("<tool_call>"):])
|
| 206 |
+
|
| 207 |
+
tool_calls = []
|
| 208 |
+
keep_raw = [] # unparsable blocks stay in content
|
| 209 |
+
for (a, b), body in zip(spans, calls):
|
| 210 |
+
obj = _loads_lenient(body)
|
| 211 |
+
if not isinstance(obj, dict) or "name" not in obj:
|
| 212 |
+
keep_raw.append((a, b))
|
| 213 |
+
continue
|
| 214 |
+
args = obj.get("arguments", obj.get("parameters", {}))
|
| 215 |
+
if isinstance(args, str):
|
| 216 |
+
parsed = _loads_lenient(args)
|
| 217 |
+
args_str = json.dumps(parsed, ensure_ascii=False) if parsed is not None else args
|
| 218 |
+
else:
|
| 219 |
+
args_str = json.dumps(args, ensure_ascii=False)
|
| 220 |
+
tool_calls.append({
|
| 221 |
+
"id": "call_" + uuid.uuid4().hex[:24],
|
| 222 |
+
"type": "function",
|
| 223 |
+
"function": {"name": str(obj["name"]), "arguments": args_str},
|
| 224 |
+
})
|
| 225 |
+
|
| 226 |
+
# content = text with successfully parsed blocks removed
|
| 227 |
+
parsed_spans = [s for s in spans if s not in keep_raw]
|
| 228 |
+
pieces, pos = [], 0
|
| 229 |
+
for a, b in sorted(parsed_spans):
|
| 230 |
+
pieces.append(text[pos:a])
|
| 231 |
+
pos = b
|
| 232 |
+
pieces.append(text[pos:])
|
| 233 |
+
content = "".join(pieces).strip()
|
| 234 |
+
return (content if content else None), tool_calls
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
# ----------------------------------------------------------------------------
|
| 238 |
+
# Model wrapper
|
| 239 |
+
# ----------------------------------------------------------------------------
|
| 240 |
+
class Engine:
|
| 241 |
+
def __init__(self, args):
|
| 242 |
+
import torch
|
| 243 |
+
from transformers import AutoModelForImageTextToText, AutoProcessor
|
| 244 |
+
|
| 245 |
+
self.torch = torch
|
| 246 |
+
self.args = args
|
| 247 |
+
self.device = args.device
|
| 248 |
+
t0 = time.time()
|
| 249 |
+
proc_kwargs = {}
|
| 250 |
+
if args.min_pixels:
|
| 251 |
+
proc_kwargs["min_pixels"] = args.min_pixels
|
| 252 |
+
if args.max_pixels:
|
| 253 |
+
proc_kwargs["max_pixels"] = args.max_pixels
|
| 254 |
+
if args.attn == "sdpa" and not args.sdpa_native_gqa:
|
| 255 |
+
# PPU quirk (measured): torch SDPA with enable_gqa=True fails for decode steps
|
| 256 |
+
# (q_len=1, no mask) with "q must have shape (batch_size, seqlen_q, num_heads,
|
| 257 |
+
# head_size_og)". Make transformers repeat K/V heads itself instead.
|
| 258 |
+
import transformers.integrations.sdpa_attention as _sdpa
|
| 259 |
+
|
| 260 |
+
_sdpa.use_gqa_in_sdpa = lambda attention_mask, key: False
|
| 261 |
+
self.processor = AutoProcessor.from_pretrained(args.model, **proc_kwargs)
|
| 262 |
+
self.tokenizer = self.processor.tokenizer
|
| 263 |
+
self.model = AutoModelForImageTextToText.from_pretrained(
|
| 264 |
+
args.model,
|
| 265 |
+
dtype=torch.bfloat16,
|
| 266 |
+
attn_implementation=args.attn,
|
| 267 |
+
device_map={"": self.device},
|
| 268 |
+
).eval()
|
| 269 |
+
self.load_time = time.time() - t0
|
| 270 |
+
self.eos_ids = [self.tokenizer.convert_tokens_to_ids(t) for t in END_MARKERS]
|
| 271 |
+
self.eos_ids = [i for i in self.eos_ids if isinstance(i, int) and i >= 0]
|
| 272 |
+
self.pad_id = self.tokenizer.pad_token_id if self.tokenizer.pad_token_id is not None else self.eos_ids[-1]
|
| 273 |
+
self.lock = threading.Lock()
|
| 274 |
+
LOG.info("model loaded in %.1fs on %s (attn=%s); mem allocated %.2f GiB",
|
| 275 |
+
self.load_time, self.device, args.attn, torch.cuda.memory_allocated(self.device) / 2**30)
|
| 276 |
+
|
| 277 |
+
def mem(self):
|
| 278 |
+
t = self.torch
|
| 279 |
+
return {
|
| 280 |
+
"allocated_gib": round(t.cuda.memory_allocated(self.device) / 2**30, 2),
|
| 281 |
+
"reserved_gib": round(t.cuda.memory_reserved(self.device) / 2**30, 2),
|
| 282 |
+
"max_allocated_gib": round(t.cuda.max_memory_allocated(self.device) / 2**30, 2),
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
def chat(self, req: dict):
|
| 286 |
+
torch = self.torch
|
| 287 |
+
a = self.args
|
| 288 |
+
messages, images = convert_messages(req.get("messages"))
|
| 289 |
+
tools = req.get("tools") or None
|
| 290 |
+
tool_choice = req.get("tool_choice", "auto")
|
| 291 |
+
prefix = ""
|
| 292 |
+
if tools:
|
| 293 |
+
if tool_choice == "none":
|
| 294 |
+
tools = None
|
| 295 |
+
elif tool_choice == "required":
|
| 296 |
+
prefix = "<tool_call>\n"
|
| 297 |
+
elif isinstance(tool_choice, dict):
|
| 298 |
+
fname = (tool_choice.get("function") or {}).get("name") or tool_choice.get("name")
|
| 299 |
+
if fname:
|
| 300 |
+
prefix = '<tool_call>\n{"name": "' + fname + '", "arguments": '
|
| 301 |
+
tmpl_tools = None
|
| 302 |
+
if tools:
|
| 303 |
+
tmpl_tools = []
|
| 304 |
+
for t in tools:
|
| 305 |
+
if isinstance(t, dict) and "function" not in t and "name" in t:
|
| 306 |
+
t = {"type": "function", "function": t}
|
| 307 |
+
tmpl_tools.append(t)
|
| 308 |
+
|
| 309 |
+
prompt = self.processor.apply_chat_template(
|
| 310 |
+
messages, tools=tmpl_tools, tokenize=False, add_generation_prompt=True
|
| 311 |
+
) + prefix
|
| 312 |
+
inputs = self.processor(
|
| 313 |
+
text=[prompt], images=images if images else None, return_tensors="pt"
|
| 314 |
+
).to(self.device)
|
| 315 |
+
n_prompt = int(inputs["input_ids"].shape[1])
|
| 316 |
+
if n_prompt > a.max_prompt_tokens:
|
| 317 |
+
raise BadRequest(f"prompt has {n_prompt} tokens > --max-prompt-tokens {a.max_prompt_tokens}")
|
| 318 |
+
|
| 319 |
+
max_new = req.get("max_completion_tokens") or req.get("max_tokens") or a.default_max_tokens
|
| 320 |
+
max_new = int(min(max_new, a.max_tokens_cap))
|
| 321 |
+
temperature = req.get("temperature")
|
| 322 |
+
if temperature is None:
|
| 323 |
+
temperature = a.default_temperature
|
| 324 |
+
gen_kwargs = dict(
|
| 325 |
+
max_new_tokens=max_new,
|
| 326 |
+
eos_token_id=self.eos_ids,
|
| 327 |
+
pad_token_id=self.pad_id,
|
| 328 |
+
use_cache=True,
|
| 329 |
+
)
|
| 330 |
+
if temperature and float(temperature) > 0:
|
| 331 |
+
gen_kwargs.update(do_sample=True, temperature=float(temperature),
|
| 332 |
+
top_p=float(req.get("top_p") or 0.8), top_k=int(req.get("top_k") or 20))
|
| 333 |
+
else:
|
| 334 |
+
gen_kwargs.update(do_sample=False, temperature=None, top_p=None, top_k=None)
|
| 335 |
+
if req.get("seed") is not None:
|
| 336 |
+
torch.manual_seed(int(req["seed"]))
|
| 337 |
+
|
| 338 |
+
with torch.inference_mode():
|
| 339 |
+
out = self.model.generate(**inputs, **gen_kwargs)
|
| 340 |
+
new_ids = out[0, n_prompt:].tolist()
|
| 341 |
+
# count tokens up to and including the first EOS
|
| 342 |
+
n_completion = len(new_ids)
|
| 343 |
+
hit_eos = False
|
| 344 |
+
for i, tid in enumerate(new_ids):
|
| 345 |
+
if tid in self.eos_ids:
|
| 346 |
+
n_completion = i + 1
|
| 347 |
+
hit_eos = True
|
| 348 |
+
break
|
| 349 |
+
text = self.tokenizer.decode(new_ids[:n_completion], skip_special_tokens=False)
|
| 350 |
+
for mk in END_MARKERS:
|
| 351 |
+
text = text.replace(mk, "")
|
| 352 |
+
text = prefix + text
|
| 353 |
+
|
| 354 |
+
stop = req.get("stop")
|
| 355 |
+
stopped_by_str = False
|
| 356 |
+
if stop:
|
| 357 |
+
for s in ([stop] if isinstance(stop, str) else stop):
|
| 358 |
+
k = text.find(s, len(prefix))
|
| 359 |
+
if k >= 0:
|
| 360 |
+
text = text[:k]
|
| 361 |
+
stopped_by_str = True
|
| 362 |
+
|
| 363 |
+
if tools:
|
| 364 |
+
content, tool_calls = parse_tool_calls(text)
|
| 365 |
+
if tool_calls and req.get("parallel_tool_calls") is False:
|
| 366 |
+
tool_calls = tool_calls[:1]
|
| 367 |
+
else:
|
| 368 |
+
content, tool_calls = (text.strip() or None), []
|
| 369 |
+
|
| 370 |
+
if tool_calls:
|
| 371 |
+
finish = "tool_calls"
|
| 372 |
+
elif hit_eos or stopped_by_str:
|
| 373 |
+
finish = "stop"
|
| 374 |
+
else:
|
| 375 |
+
finish = "length"
|
| 376 |
+
message = {"role": "assistant", "content": content}
|
| 377 |
+
if tool_calls:
|
| 378 |
+
message["tool_calls"] = tool_calls
|
| 379 |
+
usage = {"prompt_tokens": n_prompt, "completion_tokens": n_completion,
|
| 380 |
+
"total_tokens": n_prompt + n_completion}
|
| 381 |
+
return message, finish, usage, len(images), text
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
# ----------------------------------------------------------------------------
|
| 385 |
+
# HTTP
|
| 386 |
+
# ----------------------------------------------------------------------------
|
| 387 |
+
ENGINE: Engine | None = None
|
| 388 |
+
ARGS = None
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
class Handler(BaseHTTPRequestHandler):
|
| 392 |
+
protocol_version = "HTTP/1.1"
|
| 393 |
+
|
| 394 |
+
def log_message(self, fmt, *args): # route http.server logs through logging
|
| 395 |
+
LOG.debug("%s - %s", self.address_string(), fmt % args)
|
| 396 |
+
|
| 397 |
+
def _send_json(self, code: int, obj):
|
| 398 |
+
body = json.dumps(obj, ensure_ascii=False).encode("utf-8")
|
| 399 |
+
self.send_response(code)
|
| 400 |
+
self.send_header("Content-Type", "application/json")
|
| 401 |
+
self.send_header("Content-Length", str(len(body)))
|
| 402 |
+
self.end_headers()
|
| 403 |
+
self.wfile.write(body)
|
| 404 |
+
|
| 405 |
+
def _error(self, code: int, msg: str, etype: str):
|
| 406 |
+
self._send_json(code, {"error": {"message": msg, "type": etype, "code": code}})
|
| 407 |
+
|
| 408 |
+
def do_GET(self):
|
| 409 |
+
if self.path.rstrip("/") in ("/health", "/v1/health"):
|
| 410 |
+
self._send_json(200, {"status": "ok", "model": ARGS.served_name, "memory": ENGINE.mem(),
|
| 411 |
+
"load_time_s": round(ENGINE.load_time, 1)})
|
| 412 |
+
elif self.path.rstrip("/") == "/v1/models":
|
| 413 |
+
self._send_json(200, {"object": "list", "data": [
|
| 414 |
+
{"id": ARGS.served_name, "object": "model", "created": int(time.time()), "owned_by": "local"}]})
|
| 415 |
+
else:
|
| 416 |
+
self._error(404, f"no route {self.path}", "not_found")
|
| 417 |
+
|
| 418 |
+
def do_POST(self):
|
| 419 |
+
if self.path.rstrip("/") not in ("/v1/chat/completions", "/chat/completions"):
|
| 420 |
+
self._error(404, f"no route {self.path}", "not_found")
|
| 421 |
+
return
|
| 422 |
+
try:
|
| 423 |
+
n = int(self.headers.get("Content-Length", "0"))
|
| 424 |
+
req = json.loads(self.rfile.read(n).decode("utf-8"))
|
| 425 |
+
except Exception as e: # noqa: BLE001
|
| 426 |
+
self._error(400, f"invalid JSON body: {e}", "invalid_request_error")
|
| 427 |
+
return
|
| 428 |
+
t0 = time.time()
|
| 429 |
+
try:
|
| 430 |
+
with ENGINE.lock:
|
| 431 |
+
t_lock = time.time()
|
| 432 |
+
message, finish, usage, n_img, raw = ENGINE.chat(req)
|
| 433 |
+
except BadRequest as e:
|
| 434 |
+
self._error(400, str(e), "invalid_request_error")
|
| 435 |
+
return
|
| 436 |
+
except Exception as e: # noqa: BLE001
|
| 437 |
+
LOG.error("generation failed: %s\n%s", e, traceback.format_exc())
|
| 438 |
+
if "out of memory" in str(e).lower():
|
| 439 |
+
try:
|
| 440 |
+
ENGINE.torch.cuda.empty_cache()
|
| 441 |
+
except Exception: # noqa: BLE001
|
| 442 |
+
pass
|
| 443 |
+
self._error(500, f"{type(e).__name__}: {e}", "server_error")
|
| 444 |
+
return
|
| 445 |
+
dt = time.time() - t0
|
| 446 |
+
LOG.info("req images=%d prompt=%d completion=%d finish=%s tool_calls=%d queue=%.2fs gen=%.2fs mem=%s",
|
| 447 |
+
n_img, usage["prompt_tokens"], usage["completion_tokens"], finish,
|
| 448 |
+
len(message.get("tool_calls", [])), t_lock - t0, time.time() - t_lock, ENGINE.mem())
|
| 449 |
+
if ARGS.log_outputs:
|
| 450 |
+
LOG.info("raw output: %r", raw)
|
| 451 |
+
cid = "chatcmpl-" + uuid.uuid4().hex[:24]
|
| 452 |
+
created = int(time.time())
|
| 453 |
+
model_name = req.get("model") or ARGS.served_name
|
| 454 |
+
if req.get("stream"):
|
| 455 |
+
self._send_stream(cid, created, model_name, message, finish, usage, req)
|
| 456 |
+
return
|
| 457 |
+
self._send_json(200, {
|
| 458 |
+
"id": cid,
|
| 459 |
+
"object": "chat.completion",
|
| 460 |
+
"created": created,
|
| 461 |
+
"model": model_name,
|
| 462 |
+
"choices": [{"index": 0, "message": message, "finish_reason": finish, "logprobs": None}],
|
| 463 |
+
"usage": usage,
|
| 464 |
+
"server_timing": {"latency_s": round(dt, 3)},
|
| 465 |
+
})
|
| 466 |
+
|
| 467 |
+
def _send_stream(self, cid, created, model_name, message, finish, usage, req):
|
| 468 |
+
self.send_response(200)
|
| 469 |
+
self.send_header("Content-Type", "text/event-stream")
|
| 470 |
+
self.send_header("Cache-Control", "no-cache")
|
| 471 |
+
self.send_header("Connection", "close")
|
| 472 |
+
self.end_headers()
|
| 473 |
+
self.close_connection = True
|
| 474 |
+
|
| 475 |
+
def chunk(delta, fr=None, with_usage=False):
|
| 476 |
+
obj = {"id": cid, "object": "chat.completion.chunk", "created": created, "model": model_name,
|
| 477 |
+
"choices": [{"index": 0, "delta": delta, "finish_reason": fr, "logprobs": None}]}
|
| 478 |
+
if with_usage:
|
| 479 |
+
obj["usage"] = usage
|
| 480 |
+
self.wfile.write(b"data: " + json.dumps(obj, ensure_ascii=False).encode() + b"\n\n")
|
| 481 |
+
|
| 482 |
+
chunk({"role": "assistant", "content": message.get("content") or ""})
|
| 483 |
+
for i, tc in enumerate(message.get("tool_calls", [])):
|
| 484 |
+
chunk({"tool_calls": [dict(tc, index=i)]})
|
| 485 |
+
include_usage = bool((req.get("stream_options") or {}).get("include_usage"))
|
| 486 |
+
chunk({}, finish, with_usage=include_usage)
|
| 487 |
+
self.wfile.write(b"data: [DONE]\n\n")
|
| 488 |
+
self.wfile.flush()
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def main():
|
| 492 |
+
global ENGINE, ARGS
|
| 493 |
+
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 494 |
+
p.add_argument("--model", default=os.environ.get("QWEN_VL_MODEL", "Qwen/Qwen3-VL-8B-Instruct"))
|
| 495 |
+
p.add_argument("--served-name", default="Qwen3-VL-8B-Instruct")
|
| 496 |
+
p.add_argument("--host", default="127.0.0.1")
|
| 497 |
+
p.add_argument("--port", type=int, default=8765)
|
| 498 |
+
p.add_argument("--device", default="cuda:0")
|
| 499 |
+
p.add_argument("--attn", default="sdpa", choices=["sdpa", "eager", "flash_attention_2"])
|
| 500 |
+
p.add_argument("--sdpa-native-gqa", action="store_true",
|
| 501 |
+
help="let torch SDPA do GQA (enable_gqa=True); broken on PPU for decode, off by default")
|
| 502 |
+
p.add_argument("--default-max-tokens", type=int, default=1024)
|
| 503 |
+
p.add_argument("--max-tokens-cap", type=int, default=8192)
|
| 504 |
+
p.add_argument("--max-prompt-tokens", type=int, default=65536)
|
| 505 |
+
p.add_argument("--default-temperature", type=float, default=0.0,
|
| 506 |
+
help="used when the request has no temperature; 0 = greedy")
|
| 507 |
+
p.add_argument("--min-pixels", type=int, default=0, help="override image processor min_pixels")
|
| 508 |
+
p.add_argument("--max-pixels", type=int, default=0, help="override image processor max_pixels")
|
| 509 |
+
p.add_argument("--log-outputs", action="store_true", help="log raw model output text per request")
|
| 510 |
+
p.add_argument("--warmup", action="store_true", help="run one tiny generation before serving")
|
| 511 |
+
ARGS = p.parse_args()
|
| 512 |
+
|
| 513 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s", stream=sys.stdout)
|
| 514 |
+
import transformers
|
| 515 |
+
|
| 516 |
+
LOG.info("transformers %s from %s", transformers.__version__, os.path.dirname(transformers.__file__))
|
| 517 |
+
ENGINE = Engine(ARGS)
|
| 518 |
+
if ARGS.warmup:
|
| 519 |
+
t = time.time()
|
| 520 |
+
with ENGINE.lock:
|
| 521 |
+
ENGINE.chat({"messages": [{"role": "user", "content": "Hi"}], "max_tokens": 4})
|
| 522 |
+
LOG.info("warmup done in %.1fs", time.time() - t)
|
| 523 |
+
srv = ThreadingHTTPServer((ARGS.host, ARGS.port), Handler)
|
| 524 |
+
srv.daemon_threads = True
|
| 525 |
+
LOG.info("serving %s on http://%s:%d/v1/chat/completions", ARGS.served_name, ARGS.host, ARGS.port)
|
| 526 |
+
try:
|
| 527 |
+
srv.serve_forever()
|
| 528 |
+
except KeyboardInterrupt:
|
| 529 |
+
pass
|
| 530 |
+
finally:
|
| 531 |
+
srv.server_close()
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
if __name__ == "__main__":
|
| 535 |
+
main()
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/record_breakfast_service.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Continuous simulation recording with a magnified crop; no state edits or model calls."""
|
| 2 |
+
import argparse, hashlib, json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import imageio.v2 as imageio
|
| 5 |
+
import numpy as np
|
| 6 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 7 |
+
from lffbench import envs
|
| 8 |
+
from lffbench.tasks.lh_breakfast_service import BreakfastService
|
| 9 |
+
import robosuite.utils.transform_utils as T
|
| 10 |
+
|
| 11 |
+
FONT='/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'
|
| 12 |
+
|
| 13 |
+
class Recorder:
|
| 14 |
+
def __init__(self,t,out):
|
| 15 |
+
self.t=t;self.out=out;self.n=0;self.frames=0;self.timeline=[]
|
| 16 |
+
self.phase='Prepare breakfast';self.focus='food';self.raw_n=0
|
| 17 |
+
self.raw=imageio.get_writer(str(out/'breakfast_full_1x.mp4'),fps=5,codec='libx264',quality=8,macro_block_size=1)
|
| 18 |
+
self.preview=imageio.get_writer(str(out/'breakfast_recovery_2x.mp4'),fps=10,codec='libx264',quality=8,macro_block_size=1)
|
| 19 |
+
self.original=t.env.step;t.env.step=self.step
|
| 20 |
+
# Rendering-only side camera makes the reopened lid's gap visible.
|
| 21 |
+
m=t.env.sim.model;cid=m.camera_name2id('sideview')
|
| 22 |
+
pos=np.array([-.28,-.58,1.16]);target=np.array([-.20,-.10,.96])
|
| 23 |
+
z=(pos-target)/np.linalg.norm(pos-target);x=np.cross([0,0,1],z);x/=np.linalg.norm(x);y=np.cross(z,x)
|
| 24 |
+
q=T.mat2quat(np.column_stack([x,y,z]))
|
| 25 |
+
m.cam_pos[cid]=pos;m.cam_quat[cid]=q[[3,0,1,2]];m.cam_fovy[cid]=45
|
| 26 |
+
t.env.sim.forward()
|
| 27 |
+
def step(self,a):
|
| 28 |
+
result=self.original(a);self.n+=1
|
| 29 |
+
if self.n%4==0:self.capture()
|
| 30 |
+
return result
|
| 31 |
+
def frame(self):
|
| 32 |
+
return Image.fromarray(envs.render(self.t.env,res=768))
|
| 33 |
+
def decorate(self,im):
|
| 34 |
+
canvas=Image.new('RGB',(1280,928),(19,26,36));canvas.paste(im,(0,48))
|
| 35 |
+
crop={'milk':(440,180,760,500),'lid':(150,230,470,550),'food':(0,220,320,540)}[self.focus]
|
| 36 |
+
detail=(Image.fromarray(envs.render(self.t.env,cam='sideview',res=512)) if self.focus=='lid'
|
| 37 |
+
else im.crop(crop).resize((512,512),Image.Resampling.LANCZOS))
|
| 38 |
+
canvas.paste(detail,(768,80))
|
| 39 |
+
d=ImageDraw.Draw(canvas);f=ImageFont.truetype(FONT,24);sm=ImageFont.truetype(FONT,20)
|
| 40 |
+
d.text((18,10),'BREAKFAST | scripted recovery reference | same attempt | 2x',font=f,fill='white')
|
| 41 |
+
d.text((785,52),'Synchronized side view' if self.focus=='lid' else 'Magnified detail from the same frame',font=sm,fill='#b5ccdf')
|
| 42 |
+
q=self.t.liquid
|
| 43 |
+
for n,line in enumerate([f'Simulation: {self.n*.05:.1f} s',f'Milk in cup: {q["cup"]:.1f} mL',
|
| 44 |
+
f'Spilled: {q["spill"]:.1f} mL',f'Pantry lid: {self.t.lid_deg():.1f} deg',
|
| 45 |
+
f'Butter height: {100*self.t.butter_height():.1f} cm']):
|
| 46 |
+
d.text((790,620+36*n),line,font=f,fill='white')
|
| 47 |
+
d.text((18,830),self.phase,font=f,fill='#ffe0a2')
|
| 48 |
+
d.text((18,874),'Milk: simplified flow + ballistic parcels; rigid objects: MuJoCo contacts.',font=sm,fill='#b5ccdf')
|
| 49 |
+
return np.asarray(canvas)
|
| 50 |
+
def capture(self):
|
| 51 |
+
im=self.frame();self.raw.append_data(np.asarray(im));self.raw_n+=1
|
| 52 |
+
self.preview.append_data(self.decorate(im));self.frames+=1
|
| 53 |
+
def phase_hook(self,text,state):
|
| 54 |
+
if text.startswith(('Tipping handle:','Returning handle:','Bread pickup:','Bread placement:')):return
|
| 55 |
+
if 'carton' in text or 'cradle' in text or 'milk' in text.lower():self.focus='milk'
|
| 56 |
+
elif 'pantry' in text.lower() or 'L4' in text or 'lid' in text.lower() or 'inside the box' in text or 'Upright butter' in text:self.focus='lid'
|
| 57 |
+
else:self.focus='food'
|
| 58 |
+
self.phase=text
|
| 59 |
+
row=dict(state,preview_time_s=self.frames/10,preview_frame=self.frames)
|
| 60 |
+
self.timeline.append(row)
|
| 61 |
+
im=self.frame();Image.Image.save(im,self.out/f'checkpoint_{len(self.timeline):02d}.png')
|
| 62 |
+
# Explicit presentation hold only; no simulation reset or omitted motion.
|
| 63 |
+
for _ in range(10):self.preview.append_data(self.decorate(im));self.frames+=1
|
| 64 |
+
print(json.dumps(row,default=lambda v:v.item()),flush=True)
|
| 65 |
+
def close(self):
|
| 66 |
+
self.t.env.step=self.original;self.raw.close();self.preview.close()
|
| 67 |
+
|
| 68 |
+
def main():
|
| 69 |
+
p=argparse.ArgumentParser();p.add_argument('--out',required=True);p.add_argument('--seed',type=int,default=1000)
|
| 70 |
+
a=p.parse_args();out=Path(a.out);out.mkdir(parents=True,exist_ok=True)
|
| 71 |
+
t=BreakfastService();inst=t.sample_instance(a.seed);t.reset_instance(inst)
|
| 72 |
+
r=Recorder(t,out);t.phase_hook=r.phase_hook
|
| 73 |
+
try:
|
| 74 |
+
t.execute(inst,{'mode':'adaptive'});result=t.outcome(inst)
|
| 75 |
+
r.phase_hook('FINAL: breakfast served; all three failures recovered' if result['success'] else 'FINAL: verification failed',
|
| 76 |
+
dict(step=t.sk.n_steps,outcome=result))
|
| 77 |
+
finally:r.close()
|
| 78 |
+
files=[Path(__file__).resolve().parents[1]/'lffbench/tasks'/n for n in
|
| 79 |
+
('lh_breakfast_service.py','lh_pantry_relatch.py','lh_lid_box.py')]
|
| 80 |
+
meta=dict(seed=a.seed,instance=inst,outcome=result,continuous_attempt=True,resets_during_recording=0,
|
| 81 |
+
source_hashes={str(f):hashlib.sha256(f.read_bytes()).hexdigest() for f in files},
|
| 82 |
+
sim_seconds=r.n*.05,raw_frames=r.raw_n,preview_frames=r.frames,timeline=r.timeline,
|
| 83 |
+
presentation='2x with 1 s freeze at labeled checkpoints; full 1x has no presentation freezes',
|
| 84 |
+
video_hashes={f.name:hashlib.sha256(f.read_bytes()).hexdigest() for f in out.glob('*.mp4')})
|
| 85 |
+
(out/'recording.json').write_text(json.dumps(meta,indent=2,default=lambda v:v.item()))
|
| 86 |
+
assert result['success'] and all(result['traps'].values()) and all(result['recovered'].values()),result
|
| 87 |
+
t.env.close()
|
| 88 |
+
|
| 89 |
+
if __name__=='__main__':main()
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/summarize.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Aggregate results/<task>/validate.json into results/SUMMARY.md (headroom table)."""
|
| 2 |
+
import glob
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def main():
|
| 10 |
+
rows = []
|
| 11 |
+
for p in sorted(glob.glob(os.path.join(ROOT, "results", "*", "validate.json"))):
|
| 12 |
+
r = json.load(open(p))
|
| 13 |
+
s = r["succ_at_k"]
|
| 14 |
+
|
| 15 |
+
def g(kind, j):
|
| 16 |
+
v = s.get(kind)
|
| 17 |
+
return "—" if v is None else f"{100 * v[j - 1]:.0f}"
|
| 18 |
+
|
| 19 |
+
k = r["k"]
|
| 20 |
+
rows.append(f"| {r['task']} | {r['level']} | {', '.join(r['capabilities'])} | {r['n']} | "
|
| 21 |
+
f"{g('oracle', 1)} | {g('naive', 1)} | {g('adaptive', 1)} / {g('adaptive', 2)} / {g('adaptive', k)} | "
|
| 22 |
+
f"{g('blind', k)} | {r.get('seconds', 0) / 60:.0f} min |")
|
| 23 |
+
head = ("| task | level | capabilities | n | oracle@1 | naive@1 | adaptive @1/@2/@k | blind@k | wall |\n"
|
| 24 |
+
"|---|---|---|---|---|---|---|---|---|")
|
| 25 |
+
text = "# LFF-Bench headroom validation (scripted reference policies)\n\n" + head + "\n" + "\n".join(rows) + "\n"
|
| 26 |
+
out = os.path.join(ROOT, "results", "SUMMARY.md")
|
| 27 |
+
with open(out, "w") as f:
|
| 28 |
+
f.write(text)
|
| 29 |
+
print(text)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
if __name__ == "__main__":
|
| 33 |
+
main()
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/agent/images.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Image references and encoding (JPEG bytes are what the model sees and what is saved to disk)."""
|
| 2 |
+
import base64
|
| 3 |
+
import io
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from typing import Any, Optional
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@dataclass
|
| 11 |
+
class ImageRef:
|
| 12 |
+
camera: str # agent-facing camera name ("agentview" / "wrist")
|
| 13 |
+
array: Any = None # uint8 HxWx3
|
| 14 |
+
label: str = ""
|
| 15 |
+
path: Optional[str] = None # where the encoded image was saved
|
| 16 |
+
jpeg: Optional[bytes] = None # encoded bytes actually sent to the model
|
| 17 |
+
|
| 18 |
+
def encoded(self, quality=90):
|
| 19 |
+
if self.jpeg is None:
|
| 20 |
+
if self.array is None and self.path:
|
| 21 |
+
with open(self.path, "rb") as f:
|
| 22 |
+
self.jpeg = f.read()
|
| 23 |
+
else:
|
| 24 |
+
self.jpeg = encode_jpeg(self.array, quality)
|
| 25 |
+
return self.jpeg
|
| 26 |
+
|
| 27 |
+
def data_url(self, quality=90):
|
| 28 |
+
return "data:image/jpeg;base64," + base64.b64encode(self.encoded(quality)).decode("ascii")
|
| 29 |
+
|
| 30 |
+
@property
|
| 31 |
+
def size(self):
|
| 32 |
+
return None if self.array is None else tuple(np.asarray(self.array).shape[:2])
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def encode_jpeg(arr, quality=90):
|
| 36 |
+
from PIL import Image
|
| 37 |
+
buf = io.BytesIO()
|
| 38 |
+
Image.fromarray(np.asarray(arr, dtype=np.uint8)).save(buf, format="JPEG", quality=int(quality))
|
| 39 |
+
return buf.getvalue()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def resize(arr, res):
|
| 43 |
+
from PIL import Image
|
| 44 |
+
arr = np.asarray(arr, dtype=np.uint8)
|
| 45 |
+
if arr.shape[0] == res and arr.shape[1] == res:
|
| 46 |
+
return arr
|
| 47 |
+
return np.asarray(Image.fromarray(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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Agent-facing tool interface on top of `Skills`.
|
| 2 |
+
|
| 3 |
+
Every action tool calls the task's `Skills` object, so the task's hidden calibration `bias` keeps
|
| 4 |
+
acting on every commanded position. Proprioception is reported in the robot's own (possibly
|
| 5 |
+
miscalibrated) frame: reported eef = true eef - bias, i.e. the robot "believes" it reached the
|
| 6 |
+
commanded point; only the cameras show the truth. Camera-derived quantities (pixel_to_world) and
|
| 7 |
+
the privileged `locate` tool are in the true world frame.
|
| 8 |
+
|
| 9 |
+
Tool schemas are plain JSON schema (OpenAI strict-mode compatible: every property listed in
|
| 10 |
+
`required`, optional ones nullable, no additional properties).
|
| 11 |
+
"""
|
| 12 |
+
import json
|
| 13 |
+
import math
|
| 14 |
+
import time
|
| 15 |
+
from dataclasses import dataclass, field
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
|
| 19 |
+
from .. import envs
|
| 20 |
+
from . import camera as C
|
| 21 |
+
from .images import ImageRef
|
| 22 |
+
|
| 23 |
+
TABLE_Z = envs.TABLE_Z
|
| 24 |
+
# Workspace limits for commanded grasp-point positions (world frame, metres). Targets outside are
|
| 25 |
+
# clipped and the report says so.
|
| 26 |
+
WS_LO = np.array([-0.55, -0.45, TABLE_Z + 0.005])
|
| 27 |
+
WS_HI = np.array([0.35, 0.45, TABLE_Z + 0.50])
|
| 28 |
+
SPEED_RANGE = (0.02, 1.0)
|
| 29 |
+
PUSH_DIST_RANGE = (0.0, 0.40)
|
| 30 |
+
RUNUP_RANGE = (0.02, 0.30)
|
| 31 |
+
|
| 32 |
+
ACTION_TOOLS = ("move_to", "open_gripper", "close_gripper", "push")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _num(desc):
|
| 36 |
+
return {"type": "number", "description": desc}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _opt_num(desc):
|
| 40 |
+
return {"type": ["number", "null"], "description": desc}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _fn(name, desc, props=None):
|
| 44 |
+
props = props or {}
|
| 45 |
+
return dict(name=name, description=desc,
|
| 46 |
+
parameters={"type": "object", "properties": props, "required": list(props),
|
| 47 |
+
"additionalProperties": False})
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def tool_specs(privileged_locate=False, object_names=None, image_res=512):
|
| 51 |
+
"""Backend-neutral tool list: [{name, description, parameters}]."""
|
| 52 |
+
specs = [
|
| 53 |
+
_fn("move_to",
|
| 54 |
+
"Move the gripper's grasp point (midway between the fingertips) in a straight line to the world "
|
| 55 |
+
"position (x, y, z) with the gripper pointing straight down and rotated to `yaw`. The gripper "
|
| 56 |
+
"opening is not changed. Returns whether the target was reached, the end-effector position, gripper "
|
| 57 |
+
"width, whether an object is held and whether the arm touched an object during the motion.",
|
| 58 |
+
{"x": _num("target x, metres (world frame; +x away from the robot)"),
|
| 59 |
+
"y": _num("target y, metres (world frame; +y to the robot's left)"),
|
| 60 |
+
"z": _num(f"target z, metres (table top is z = {TABLE_Z:.2f})"),
|
| 61 |
+
"yaw": _num("gripper rotation about the vertical axis in DEGREES; 0 = fingers close along the world "
|
| 62 |
+
"y axis, 90 = fingers close along the world x axis. Taken modulo 180 (the two-finger "
|
| 63 |
+
"gripper is symmetric): the controller uses the equivalent angle closest to the current "
|
| 64 |
+
"yaw within +-113 deg; the report gives the yaw actually used"),
|
| 65 |
+
"speed": _opt_num("straight-line speed in m/s (0.02-1.0); null = as fast as the controller allows "
|
| 66 |
+
"(about 0.6 m/s)")}),
|
| 67 |
+
_fn("open_gripper", "Open the gripper fully (the arm holds its position)."),
|
| 68 |
+
_fn("close_gripper", "Close the gripper (the arm holds its position). Closing on an object grasps it."),
|
| 69 |
+
_fn("push",
|
| 70 |
+
"Straight-line push with the closed gripper. The gripper closes, moves above the point `runup` metres "
|
| 71 |
+
"behind (x, y) (opposite to the push direction), descends to height z, sweeps along (dir_x, dir_y) "
|
| 72 |
+
"through (x, y) and stops `distance` metres past (x, y), moving at `speed` m/s, then lifts 12 cm. The "
|
| 73 |
+
"gripper is rotated automatically to a fixed orientation relative to the push direction.",
|
| 74 |
+
{"x": _num("x of the point where the push should start acting (e.g. the near face of the object), m"),
|
| 75 |
+
"y": _num("y of that point, m"),
|
| 76 |
+
"dir_x": _num("x component of the push direction (normalised internally)"),
|
| 77 |
+
"dir_y": _num("y component of the push direction"),
|
| 78 |
+
"distance": _num("how far past (x, y) the gripper travels, metres (0-0.40)"),
|
| 79 |
+
"speed": _num("sweep speed, m/s (0.02-1.0; the controller saturates near 0.6)"),
|
| 80 |
+
"z": _opt_num(f"height of the grasp point during the sweep, m; null = {TABLE_Z + 0.02:.2f} "
|
| 81 |
+
"(2 cm above the table)"),
|
| 82 |
+
"runup": _opt_num("distance behind (x, y) where the sweep starts, m (0.02-0.30); null = 0.06. A longer "
|
| 83 |
+
"run-up lets the gripper reach the commanded speed before contact.")}),
|
| 84 |
+
_fn("get_observation",
|
| 85 |
+
"Return the current camera images (agentview and wrist) and the robot's proprioceptive state."),
|
| 86 |
+
_fn("pixel_to_world",
|
| 87 |
+
f"Back-project an image pixel to a 3-D world point using the camera's depth map. (u, v) are pixel "
|
| 88 |
+
f"coordinates in the {image_res}x{image_res} image exactly as you received it: u = column from the "
|
| 89 |
+
f"left edge, v = row from the top edge. Returns the world point (x, y, z) of the surface seen at that "
|
| 90 |
+
f"pixel and its height above the table.",
|
| 91 |
+
{"camera": {"type": "string", "enum": ["agentview", "wrist"], "description": "which image"},
|
| 92 |
+
"u": _num("column (0 = left edge)"), "v": _num("row (0 = top edge)")}),
|
| 93 |
+
_fn("done",
|
| 94 |
+
"Finish the current attempt. Call this when you believe the task is complete (or you want to stop). "
|
| 95 |
+
"Give a short reason: what you did and whether you think it worked.",
|
| 96 |
+
{"reason": {"type": "string", "description": "short explanation"}}),
|
| 97 |
+
]
|
| 98 |
+
if privileged_locate:
|
| 99 |
+
names = list(object_names or [])
|
| 100 |
+
prop = {"type": "string", "description": "object name"}
|
| 101 |
+
if names:
|
| 102 |
+
prop["enum"] = names
|
| 103 |
+
specs.insert(-1, _fn("locate",
|
| 104 |
+
"PRIVILEGED (ablation): return the true world position of an object's origin and its "
|
| 105 |
+
"axis-aligned bounding box.", {"object_name": prop}))
|
| 106 |
+
return specs
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
@dataclass
|
| 110 |
+
class ToolResult:
|
| 111 |
+
name: str
|
| 112 |
+
args: dict
|
| 113 |
+
ok: bool
|
| 114 |
+
report: dict
|
| 115 |
+
images: list = field(default_factory=list)
|
| 116 |
+
ended: bool = False
|
| 117 |
+
wall_s: float = 0.0
|
| 118 |
+
sim_steps: int = 0
|
| 119 |
+
|
| 120 |
+
def text(self):
|
| 121 |
+
return json.dumps(self.report, separators=(", ", ": "), default=_json_default)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _json_default(o):
|
| 125 |
+
if isinstance(o, (np.floating,)):
|
| 126 |
+
return float(o)
|
| 127 |
+
if isinstance(o, (np.integer,)):
|
| 128 |
+
return int(o)
|
| 129 |
+
if isinstance(o, np.ndarray):
|
| 130 |
+
return o.tolist()
|
| 131 |
+
if isinstance(o, (np.bool_,)):
|
| 132 |
+
return bool(o)
|
| 133 |
+
raise TypeError(type(o))
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _r(v, nd=4):
|
| 137 |
+
return [round(float(x), nd) for x in v]
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class ContactTracker:
|
| 141 |
+
"""Collects the objects the robot touches. Contacts are checked after every MuJoCo substep (a control
|
| 142 |
+
step is 25 substeps; a fast push touches the object for less than one control step, so checking only at
|
| 143 |
+
control-step boundaries misses it -- measured). Implemented by wrapping `env.sim.step` once per env; the
|
| 144 |
+
wrapper only reads contacts and dispatches to the currently active tracker."""
|
| 145 |
+
|
| 146 |
+
def __init__(self, env):
|
| 147 |
+
self.env = env
|
| 148 |
+
m = env.sim.model
|
| 149 |
+
self.is_robot = np.zeros(m.ngeom, bool)
|
| 150 |
+
self.is_robot[envs.robot_geom_ids(env)] = True
|
| 151 |
+
self.names = []
|
| 152 |
+
self.obj_of = np.full(m.ngeom, -1, int)
|
| 153 |
+
for name in list(env.objects_dict) + list(getattr(env, "fixtures_dict", {}) or {}):
|
| 154 |
+
try:
|
| 155 |
+
ids = envs.obj_geom_ids(env, name)
|
| 156 |
+
except Exception: # fixtures without contact geoms
|
| 157 |
+
continue
|
| 158 |
+
self.obj_of[ids] = len(self.names)
|
| 159 |
+
self.names.append(name)
|
| 160 |
+
self.touched = set()
|
| 161 |
+
sim = env.sim
|
| 162 |
+
if not getattr(sim, "_lff_step_wrapped", False):
|
| 163 |
+
orig = sim.step
|
| 164 |
+
|
| 165 |
+
def step(*a, **k):
|
| 166 |
+
orig(*a, **k)
|
| 167 |
+
t = getattr(sim, "_lff_tracker", None)
|
| 168 |
+
if t is not None:
|
| 169 |
+
t.check()
|
| 170 |
+
sim.step = step
|
| 171 |
+
sim._lff_step_wrapped = True
|
| 172 |
+
sim._lff_tracker = self
|
| 173 |
+
|
| 174 |
+
def reset(self):
|
| 175 |
+
self.touched = set()
|
| 176 |
+
|
| 177 |
+
def check(self):
|
| 178 |
+
d = self.env.sim.data
|
| 179 |
+
n = d.ncon
|
| 180 |
+
if not n:
|
| 181 |
+
return
|
| 182 |
+
g1 = np.asarray(d.contact.geom1)[:n]
|
| 183 |
+
g2 = np.asarray(d.contact.geom2)[:n]
|
| 184 |
+
hit = np.concatenate([self.obj_of[g2[self.is_robot[g1]]], self.obj_of[g1[self.is_robot[g2]]]])
|
| 185 |
+
for i in set(hit[hit >= 0].tolist()):
|
| 186 |
+
self.touched.add(self.names[i])
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def parse_args(raw):
|
| 190 |
+
if raw is None:
|
| 191 |
+
return {}
|
| 192 |
+
if isinstance(raw, dict):
|
| 193 |
+
return dict(raw)
|
| 194 |
+
raw = raw.strip()
|
| 195 |
+
return json.loads(raw) if raw else {}
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
class ToolExecutor:
|
| 199 |
+
"""Executes agent tool calls on a task whose instance has just been reset (task.sk is live)."""
|
| 200 |
+
|
| 201 |
+
def __init__(self, task, inst, image_res=512, cams=("agentview", "wrist"), privileged_locate=False,
|
| 202 |
+
grasp_report="bool", jpeg_quality=90, image_sink=None):
|
| 203 |
+
self.task = task
|
| 204 |
+
self.inst = inst
|
| 205 |
+
self.env = task.env
|
| 206 |
+
self.sk = task.sk # keep our own reference: the scripted backend may swap task.sk for a proxy
|
| 207 |
+
self.image_res = int(image_res)
|
| 208 |
+
self.cams = tuple(cams)
|
| 209 |
+
self.privileged_locate = privileged_locate
|
| 210 |
+
self.grasp_report = grasp_report # "bool" | "name" | "none"
|
| 211 |
+
self.jpeg_quality = jpeg_quality
|
| 212 |
+
self.image_sink = image_sink # callable(ImageRef) -> path (saves the image)
|
| 213 |
+
self.objects = list(self.env.objects_dict)
|
| 214 |
+
self.tracker = ContactTracker(self.env) # task recorders / hooks on Skills are left untouched
|
| 215 |
+
self._depth_cache = {}
|
| 216 |
+
self.n_calls = 0
|
| 217 |
+
|
| 218 |
+
# ------------------------------------------------------------------ state
|
| 219 |
+
def eef_yaw_deg(self):
|
| 220 |
+
R = self.sk.eef_mat() @ self.sk.R0.T
|
| 221 |
+
return math.degrees(math.atan2(R[1, 0], R[0, 0]))
|
| 222 |
+
|
| 223 |
+
def held(self):
|
| 224 |
+
names = [o for o in self.objects if self.sk.holding(o)]
|
| 225 |
+
return names
|
| 226 |
+
|
| 227 |
+
def _holding_field(self, names):
|
| 228 |
+
if self.grasp_report == "name":
|
| 229 |
+
return names[0] if names else None
|
| 230 |
+
if self.grasp_report == "none":
|
| 231 |
+
return None
|
| 232 |
+
return bool(names)
|
| 233 |
+
|
| 234 |
+
def proprio(self):
|
| 235 |
+
believed = self.sk.eef_pos() - self.sk.bias
|
| 236 |
+
p = dict(eef_pos=_r(believed), eef_yaw_deg=round(self.eef_yaw_deg(), 1),
|
| 237 |
+
gripper="closed" if self.sk.grip > 0 else "open",
|
| 238 |
+
gripper_width_m=round(self.sk.gripper_width(), 4))
|
| 239 |
+
if self.grasp_report != "none":
|
| 240 |
+
p["holding_object"] = self._holding_field(self.held())
|
| 241 |
+
return p
|
| 242 |
+
|
| 243 |
+
def render(self, cam, res=None):
|
| 244 |
+
res = res or self.image_res
|
| 245 |
+
return envs.render(self.env, C.mj_cam(cam), res)
|
| 246 |
+
|
| 247 |
+
def observe(self, label=""):
|
| 248 |
+
imgs = []
|
| 249 |
+
for cam in self.cams:
|
| 250 |
+
ref = ImageRef(camera=cam, array=self.render(cam), label=f"{label} {cam}".strip())
|
| 251 |
+
if self.image_sink is not None:
|
| 252 |
+
self.image_sink(ref)
|
| 253 |
+
imgs.append(ref)
|
| 254 |
+
self._depth_cache = {}
|
| 255 |
+
return imgs
|
| 256 |
+
|
| 257 |
+
# ------------------------------------------------------------------ dispatch
|
| 258 |
+
def call(self, name, raw_args):
|
| 259 |
+
t0 = time.time()
|
| 260 |
+
n0 = self.sk.n_steps
|
| 261 |
+
self.n_calls += 1
|
| 262 |
+
try:
|
| 263 |
+
args = parse_args(raw_args)
|
| 264 |
+
except Exception as e:
|
| 265 |
+
return ToolResult(name, {"_raw": str(raw_args)}, False, dict(ok=False, error=f"arguments are not valid JSON: {e}"),
|
| 266 |
+
wall_s=time.time() - t0)
|
| 267 |
+
fn = getattr(self, f"_t_{name}", None)
|
| 268 |
+
if fn is None or (name == "locate" and not self.privileged_locate):
|
| 269 |
+
return ToolResult(name, args, False, dict(ok=False, error=f"unknown tool {name!r}"), wall_s=time.time() - t0)
|
| 270 |
+
try:
|
| 271 |
+
res = fn(**args)
|
| 272 |
+
except TypeError as e:
|
| 273 |
+
res = ToolResult(name, args, False, dict(ok=False, error=f"bad arguments: {e}"))
|
| 274 |
+
except ValueError as e:
|
| 275 |
+
res = ToolResult(name, args, False, dict(ok=False, error=str(e)))
|
| 276 |
+
res.args = args
|
| 277 |
+
res.wall_s = time.time() - t0
|
| 278 |
+
res.sim_steps = self.sk.n_steps - n0
|
| 279 |
+
if res.sim_steps:
|
| 280 |
+
self._depth_cache = {}
|
| 281 |
+
hook = getattr(self.task, "on_agent_tool", None)
|
| 282 |
+
if hook is not None:
|
| 283 |
+
hook(self.inst, name, args, res.report)
|
| 284 |
+
drain = getattr(self.task, "drain_events", None) # task-side events (e.g. L6: an item slipped)
|
| 285 |
+
if drain is not None:
|
| 286 |
+
ev = drain()
|
| 287 |
+
if ev:
|
| 288 |
+
res.report["events"] = list(ev)
|
| 289 |
+
return res
|
| 290 |
+
|
| 291 |
+
# ------------------------------------------------------------------ helpers
|
| 292 |
+
def _clip_xyz(self, xyz):
|
| 293 |
+
xyz = np.asarray(xyz, float)
|
| 294 |
+
if not np.all(np.isfinite(xyz)):
|
| 295 |
+
raise ValueError("non-finite coordinates")
|
| 296 |
+
c = np.clip(xyz, WS_LO, WS_HI)
|
| 297 |
+
return c, (None if np.allclose(c, xyz) else _r(c))
|
| 298 |
+
|
| 299 |
+
@staticmethod
|
| 300 |
+
def _clip(v, lo_hi, what):
|
| 301 |
+
v = float(v)
|
| 302 |
+
if not math.isfinite(v):
|
| 303 |
+
raise ValueError(f"{what} must be finite")
|
| 304 |
+
return float(np.clip(v, *lo_hi))
|
| 305 |
+
|
| 306 |
+
def _action_report(self, name, extra=None):
|
| 307 |
+
names = self.held()
|
| 308 |
+
rep = dict(ok=True, tool=name)
|
| 309 |
+
if extra:
|
| 310 |
+
rep.update(extra)
|
| 311 |
+
rep.update(self.proprio())
|
| 312 |
+
if self.grasp_report == "name":
|
| 313 |
+
rep["touched_objects"] = sorted(self.tracker.touched)
|
| 314 |
+
elif self.grasp_report == "bool":
|
| 315 |
+
rep["touched_object"] = bool(self.tracker.touched)
|
| 316 |
+
rep["sim_time_s"] = round(self.sk.n_steps * 0.05, 2)
|
| 317 |
+
return rep
|
| 318 |
+
|
| 319 |
+
# ------------------------------------------------------------------ tools
|
| 320 |
+
def _t_move_to(self, x, y, z, yaw, speed=None):
|
| 321 |
+
tgt, clipped = self._clip_xyz([x, y, z])
|
| 322 |
+
spd = None if speed is None else self._clip(speed, SPEED_RANGE, "speed")
|
| 323 |
+
self.tracker.reset()
|
| 324 |
+
rep = self.sk.move_to(tgt, yaw=math.radians(float(yaw)), speed=spd) # Skills wraps yaw mod pi
|
| 325 |
+
extra = dict(reached=bool(rep["reached"]), yaw_used_deg=round(math.degrees(self.sk.yaw), 1))
|
| 326 |
+
if clipped:
|
| 327 |
+
extra["target_clipped_to"] = clipped
|
| 328 |
+
return ToolResult("move_to", {}, True, self._action_report("move_to", extra))
|
| 329 |
+
|
| 330 |
+
def _t_open_gripper(self):
|
| 331 |
+
self.tracker.reset()
|
| 332 |
+
self.sk.set_gripper(False)
|
| 333 |
+
return ToolResult("open_gripper", {}, True, self._action_report("open_gripper"))
|
| 334 |
+
|
| 335 |
+
def _t_close_gripper(self):
|
| 336 |
+
self.tracker.reset()
|
| 337 |
+
self.sk.set_gripper(True)
|
| 338 |
+
return ToolResult("close_gripper", {}, True, self._action_report("close_gripper"))
|
| 339 |
+
|
| 340 |
+
def _t_push(self, x, y, dir_x, dir_y, distance, speed, z=None, runup=None):
|
| 341 |
+
d = np.array([float(dir_x), float(dir_y)])
|
| 342 |
+
if not np.all(np.isfinite(d)) or np.linalg.norm(d) < 1e-6:
|
| 343 |
+
raise ValueError("push direction must be a non-zero vector")
|
| 344 |
+
start, clipped = self._clip_xyz([x, y, TABLE_Z + 0.02 if z is None else z])
|
| 345 |
+
dist = self._clip(distance, PUSH_DIST_RANGE, "distance")
|
| 346 |
+
spd = self._clip(speed, SPEED_RANGE, "speed")
|
| 347 |
+
pre = 0.06 if runup is None else self._clip(runup, RUNUP_RANGE, "runup")
|
| 348 |
+
self.tracker.reset()
|
| 349 |
+
rep = self.sk.push(start[:2], d, dist, spd, z=float(start[2]), pre=pre)
|
| 350 |
+
extra = dict(sweep_reached=bool(rep["reached"]))
|
| 351 |
+
if clipped:
|
| 352 |
+
extra["start_clipped_to"] = clipped
|
| 353 |
+
return ToolResult("push", {}, True, self._action_report("push", extra))
|
| 354 |
+
|
| 355 |
+
def _t_get_observation(self):
|
| 356 |
+
imgs = self.observe(label="requested")
|
| 357 |
+
return ToolResult("get_observation", {}, True, dict(ok=True, images=[i.camera for i in imgs], **self.proprio()),
|
| 358 |
+
images=imgs)
|
| 359 |
+
|
| 360 |
+
def _t_pixel_to_world(self, camera, u, v):
|
| 361 |
+
cam = str(camera)
|
| 362 |
+
if cam not in C.CAMERAS:
|
| 363 |
+
raise ValueError(f"camera must be one of {sorted(C.CAMERAS)}")
|
| 364 |
+
if cam not in self._depth_cache:
|
| 365 |
+
self._depth_cache[cam] = C.render_depth(self.env, cam, self.image_res)
|
| 366 |
+
r = C.pixel_to_world(self.env, cam, float(u), float(v), self.image_res, depth=self._depth_cache[cam])
|
| 367 |
+
rep = dict(ok=True, camera=cam, u=float(u), v=float(v), world_xyz=_r(r["xyz"]),
|
| 368 |
+
height_above_table_m=round(float(r["xyz"][2] - TABLE_Z), 4), depth_m=round(r["depth"], 4))
|
| 369 |
+
if not r["valid"]:
|
| 370 |
+
rep["warning"] = "pixel shows the far background; the point is unreliable"
|
| 371 |
+
return ToolResult("pixel_to_world", {}, True, rep)
|
| 372 |
+
|
| 373 |
+
def _t_locate(self, object_name):
|
| 374 |
+
if object_name not in self.env.objects_dict:
|
| 375 |
+
raise ValueError(f"unknown object {object_name!r}; known: {self.objects}")
|
| 376 |
+
lo, hi = self._aabb(object_name)
|
| 377 |
+
p = envs.obj_pos(self.env, object_name)
|
| 378 |
+
return ToolResult("locate", {}, True, dict(ok=True, object=object_name, position=_r(p), bbox_min=_r(lo),
|
| 379 |
+
bbox_max=_r(hi)))
|
| 380 |
+
|
| 381 |
+
def _aabb(self, name):
|
| 382 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 383 |
+
lo, hi = np.full(3, np.inf), np.full(3, -np.inf)
|
| 384 |
+
for g in envs.obj_geom_ids(self.env, name):
|
| 385 |
+
R = d.geom_xmat[g].reshape(3, 3)
|
| 386 |
+
c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3]
|
| 387 |
+
h = np.abs(R) @ m.geom_aabb[g, 3:]
|
| 388 |
+
lo, hi = np.minimum(lo, c - h), np.maximum(hi, c + h)
|
| 389 |
+
return lo, hi
|
| 390 |
+
|
| 391 |
+
def _t_done(self, reason=""):
|
| 392 |
+
return ToolResult("done", {}, True, dict(ok=True, ended=True), ended=True)
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/base.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Harness adapter interface (docs/15 §3).
|
| 2 |
+
|
| 3 |
+
An adapter runs one episode (one robot_server session) with one agent harness and leaves behind, in the run's log
|
| 4 |
+
dir: harness.json (what was launched), trajectory.jsonl (unified trajectory), harness_audit.json (checks + violations).
|
| 5 |
+
Budgets, automatic finish and attempt switching are NOT the adapter's business: robot_server and the MCP server /
|
| 6 |
+
reference driver enforce them identically for every harness.
|
| 7 |
+
|
| 8 |
+
name stable harness name (the "harness" column of a table)
|
| 9 |
+
capabilities CapabilityDecl: every item of REQUIRED and FORBIDDEN must be declared, with its evidence source;
|
| 10 |
+
a missing item makes the class definition fail (so the import fails)
|
| 11 |
+
version() the actual installed version (probed before launch)
|
| 12 |
+
prepare(ep, first_message) -> LaunchSpec: one-time dirs, configs, argv / env
|
| 13 |
+
launch(spec) fail-closed preflight, then start the process (env exactly the whitelist) -> RunHandle
|
| 14 |
+
collect(h) native event stream -> trajectory.jsonl (ATIF-like), usage, exit reason
|
| 15 |
+
audit(h) tool list, preset prompt, memory, state left behind, violations
|
| 16 |
+
"""
|
| 17 |
+
import dataclasses
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
import secrets
|
| 21 |
+
import shutil
|
| 22 |
+
import signal
|
| 23 |
+
import subprocess
|
| 24 |
+
import time
|
| 25 |
+
|
| 26 |
+
from . import contract as C
|
| 27 |
+
|
| 28 |
+
EVIDENCE = ("launch", "stream", "server", "probe", "preflight")
|
| 29 |
+
|
| 30 |
+
REQUIRED = {
|
| 31 |
+
"only_benchmark_tools": "the model can call exactly robot / shell / view_images (ours) and nothing else of use",
|
| 32 |
+
"images_reach_model": "view_images returns the image bytes to the model unchanged",
|
| 33 |
+
"non_persistent_session": "nothing of the session is written to disk for later runs",
|
| 34 |
+
"pinned_version": "the harness version (and binary hash) is recorded and pinned",
|
| 35 |
+
"machine_readable_events": "a machine-readable event stream of the whole run",
|
| 36 |
+
"tool_calls_logged": "every tool call is logged (harness stream + MCP / driver transcript + events.jsonl)",
|
| 37 |
+
"model_and_effort": "model and reasoning effort can be set and are visible in the request",
|
| 38 |
+
}
|
| 39 |
+
FORBIDDEN = {
|
| 40 |
+
"persistent_memory": "harness memory across runs (C4: auto-memory, CLAUDE.md / AGENTS.md, memories db)",
|
| 41 |
+
"instruction_file_injection": "instruction files picked up from the work / config / home dir",
|
| 42 |
+
"web_access": "web search / fetch",
|
| 43 |
+
"host_file_read": "reading host files outside the episode workspace",
|
| 44 |
+
"builtin_shell": "a shell of the harness itself (outside our jailed shell tool)",
|
| 45 |
+
"subagent_delegation": "spawning sub-agents",
|
| 46 |
+
"background_execution": "background tasks that outlive a tool call",
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@dataclasses.dataclass(frozen=True)
|
| 51 |
+
class Cap:
|
| 52 |
+
status: str # REQUIRED items: "yes" | "partial" | "no"; FORBIDDEN items: "absent" | "present" | "partial"
|
| 53 |
+
evidence: str # one of EVIDENCE
|
| 54 |
+
note: str = ""
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
PROXY_KEYS = ("HTTPS_PROXY", "HTTP_PROXY", "https_proxy", "http_proxy")
|
| 58 |
+
NO_PROXY_KEYS = ("NO_PROXY", "no_proxy")
|
| 59 |
+
NO_PROXY_LOCAL = "127.0.0.1,localhost,::1"
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def proxy_env(environ=None):
|
| 63 |
+
"""The calling environment's HTTP(S) proxy, passed to a native harness so it can reach the model API on machines
|
| 64 |
+
that only get out through a proxy. NO_PROXY is loopback only (the preflight's fake API), never the host's list.
|
| 65 |
+
Not part of config_sha256 (machine plumbing, not harness configuration)."""
|
| 66 |
+
environ = os.environ if environ is None else environ
|
| 67 |
+
e = {k: environ[k] for k in PROXY_KEYS if environ.get(k)}
|
| 68 |
+
if e:
|
| 69 |
+
e.update({k: NO_PROXY_LOCAL for k in NO_PROXY_KEYS})
|
| 70 |
+
return e
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class CapabilityError(TypeError):
|
| 74 |
+
pass
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def check_capabilities(name, caps):
|
| 78 |
+
if not isinstance(caps, dict):
|
| 79 |
+
raise CapabilityError(f"{name}: capabilities must be a dict")
|
| 80 |
+
missing = [k for k in list(REQUIRED) + list(FORBIDDEN) if k not in caps]
|
| 81 |
+
extra = [k for k in caps if k not in REQUIRED and k not in FORBIDDEN]
|
| 82 |
+
if missing or extra:
|
| 83 |
+
raise CapabilityError(f"{name}: capability declaration incomplete: missing {missing}, unknown {extra}")
|
| 84 |
+
for k, c in caps.items():
|
| 85 |
+
if not isinstance(c, Cap) or c.evidence not in EVIDENCE:
|
| 86 |
+
raise CapabilityError(f"{name}: capability {k!r} needs a Cap(status, evidence in {EVIDENCE})")
|
| 87 |
+
ok = ("yes", "partial", "no") if k in REQUIRED else ("absent", "present", "partial")
|
| 88 |
+
if c.status not in ok:
|
| 89 |
+
raise CapabilityError(f"{name}: capability {k!r} status must be one of {ok}")
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class HarnessRefused(RuntimeError):
|
| 93 |
+
"""Fail-closed: the launch preflight found a tool list / preset prompt that is not the pinned one."""
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@dataclasses.dataclass
|
| 97 |
+
class EpisodeSpec:
|
| 98 |
+
session_path: str
|
| 99 |
+
log_dir: str
|
| 100 |
+
sandbox: str
|
| 101 |
+
port: int
|
| 102 |
+
token: str
|
| 103 |
+
max_tool_calls: int
|
| 104 |
+
model: str
|
| 105 |
+
effort: str
|
| 106 |
+
provider: str = ""
|
| 107 |
+
task: str = ""
|
| 108 |
+
seed: int = 0
|
| 109 |
+
extra: dict = dataclasses.field(default_factory=dict)
|
| 110 |
+
|
| 111 |
+
@classmethod
|
| 112 |
+
def from_session(cls, session_path, model, effort, provider="", **extra):
|
| 113 |
+
session_path = os.path.abspath(session_path)
|
| 114 |
+
log_dir = os.path.dirname(session_path)
|
| 115 |
+
sess = json.load(open(session_path))
|
| 116 |
+
iface = json.load(open(os.path.join(log_dir, "agent_iface.json")))
|
| 117 |
+
st = C.session_start(log_dir)
|
| 118 |
+
return cls(session_path=session_path, log_dir=log_dir, sandbox=sess["sandbox"], port=int(sess["port"]),
|
| 119 |
+
token=iface["token"], max_tool_calls=int(iface["max_tool_calls"]), model=model, effort=effort,
|
| 120 |
+
provider=provider, task=st["task"], seed=int(st["seed"]), extra=extra)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@dataclasses.dataclass
|
| 124 |
+
class LaunchSpec:
|
| 125 |
+
argv: list # full argv (the first message may be one element)
|
| 126 |
+
env: dict # the complete environment of the harness process (nothing else is inherited)
|
| 127 |
+
cwd: str
|
| 128 |
+
run_dir: str = "" # one-time dir tree, removed after audit
|
| 129 |
+
state_dirs: dict = dataclasses.field(default_factory=dict) # name -> path (home, config, ...)
|
| 130 |
+
first_message: str = ""
|
| 131 |
+
config_files: dict = dataclasses.field(default_factory=dict) # name -> path of files the adapter wrote
|
| 132 |
+
stdout_path: str = ""
|
| 133 |
+
stderr_path: str = ""
|
| 134 |
+
redact_argv: dict = dataclasses.field(default_factory=dict) # argv index -> replacement for the log
|
| 135 |
+
preflight: dict = dataclasses.field(default_factory=dict)
|
| 136 |
+
timeout_s: float = 10800
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@dataclasses.dataclass
|
| 140 |
+
class RunHandle:
|
| 141 |
+
spec: LaunchSpec
|
| 142 |
+
ep: EpisodeSpec
|
| 143 |
+
proc: object = None
|
| 144 |
+
pid: int = 0
|
| 145 |
+
t_start: float = 0.0
|
| 146 |
+
t_end: float = 0.0
|
| 147 |
+
exit_code: int = None
|
| 148 |
+
exit_reason: str = ""
|
| 149 |
+
env_observed_keys: list = None # read from /proc/<pid>/environ right after the start
|
| 150 |
+
info: dict = dataclasses.field(default_factory=dict)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def env_keys_of(pid):
|
| 154 |
+
try:
|
| 155 |
+
raw = open(f"/proc/{pid}/environ", "rb").read()
|
| 156 |
+
except OSError:
|
| 157 |
+
return None
|
| 158 |
+
return sorted({kv.split(b"=", 1)[0].decode("utf-8", "replace") for kv in raw.split(b"\0") if kv})
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def new_run_dir(root="/tmp/lffrun"):
|
| 162 |
+
"""/tmp/lffrun/<12 hex>: the opaque work dir (its path is shown to the model by some harnesses)."""
|
| 163 |
+
os.makedirs(root, exist_ok=True)
|
| 164 |
+
while True:
|
| 165 |
+
d = os.path.join(root, secrets.token_hex(6))
|
| 166 |
+
try:
|
| 167 |
+
os.mkdir(d, 0o700)
|
| 168 |
+
return d
|
| 169 |
+
except FileExistsError:
|
| 170 |
+
continue
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def binary_info(path):
|
| 174 |
+
real = os.path.realpath(path)
|
| 175 |
+
return dict(path=path, realpath=real, sha256=C.sha256_file(real) if os.path.exists(real) else None)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class HarnessAdapter:
|
| 179 |
+
name = None
|
| 180 |
+
capabilities = None
|
| 181 |
+
uses_mcp = False
|
| 182 |
+
uses_gateway = False # harness_run starts the episode's tool gateway (scripts/tool_gateway.py) for
|
| 183 |
+
# this adapter: MCP adapters through the MCP server, framework adapters
|
| 184 |
+
# (RPent, ...) through lffbench_client with LFF_GATEWAY_URL / LFF_GATEWAY_TOKEN
|
| 185 |
+
clean_dirs = () # keys of spec.state_dirs that must be empty at launch
|
| 186 |
+
clean_allowed = {} # key of spec.state_dirs -> file names the adapter itself put there (e.g. auth.json)
|
| 187 |
+
ancestor_files = () # instruction files that must not exist in the work dir or any ancestor
|
| 188 |
+
unsafe_skip_clean_check = False # tests/harness_selfcheck only (probing what the harness would read)
|
| 189 |
+
jail = None # lffbench/harnesses/jail.HarnessJail when the adapter runs jailed (docs/15 §3.4)
|
| 190 |
+
can_resume = False # resume(): the CLI can continue its session with one more user message
|
| 191 |
+
|
| 192 |
+
def clean_state_problems(self, spec):
|
| 193 |
+
"""Fail-closed: the work dir and the one-time dirs must be empty, and no instruction file may sit in an
|
| 194 |
+
ancestor of the work dir (harnesses walk up the tree looking for CLAUDE.md / AGENTS.md)."""
|
| 195 |
+
p = []
|
| 196 |
+
if spec.cwd and os.path.isdir(spec.cwd) and os.listdir(spec.cwd):
|
| 197 |
+
p.append(f"work dir not empty: {sorted(os.listdir(spec.cwd))[:5]}")
|
| 198 |
+
for k in self.clean_dirs:
|
| 199 |
+
d = spec.state_dirs.get(k)
|
| 200 |
+
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 []
|
| 201 |
+
if left:
|
| 202 |
+
p.append(f"{k} dir not empty: {sorted(left)[:5]}")
|
| 203 |
+
d = spec.cwd
|
| 204 |
+
while d and d != "/":
|
| 205 |
+
d = os.path.dirname(d)
|
| 206 |
+
for f in self.ancestor_files:
|
| 207 |
+
if os.path.exists(os.path.join(d, f)):
|
| 208 |
+
p.append(f"instruction file in an ancestor of the work dir: {os.path.join(d, f)}")
|
| 209 |
+
return p
|
| 210 |
+
|
| 211 |
+
def __init_subclass__(cls, **kw):
|
| 212 |
+
super().__init_subclass__(**kw)
|
| 213 |
+
if cls.name is None:
|
| 214 |
+
raise CapabilityError(f"{cls.__name__}: no name")
|
| 215 |
+
check_capabilities(cls.name, cls.capabilities)
|
| 216 |
+
|
| 217 |
+
# -------------------------------------------------------------------------------------------- interface
|
| 218 |
+
def version(self):
|
| 219 |
+
raise NotImplementedError
|
| 220 |
+
|
| 221 |
+
def prepare(self, ep, first_message):
|
| 222 |
+
raise NotImplementedError
|
| 223 |
+
|
| 224 |
+
def preflight(self, spec, ep):
|
| 225 |
+
"""Fail-closed launch check; returns a dict for harness.json, raises HarnessRefused."""
|
| 226 |
+
return dict(skipped=True)
|
| 227 |
+
|
| 228 |
+
def collect(self, h):
|
| 229 |
+
raise NotImplementedError
|
| 230 |
+
|
| 231 |
+
def audit(self, h):
|
| 232 |
+
raise NotImplementedError
|
| 233 |
+
|
| 234 |
+
# -------------------------------------------------------------------------------------------- shared
|
| 235 |
+
def mcp_server_command(self, python, script, args):
|
| 236 |
+
"""(command, args) of the MCP server entry in the harness config: our server, or, jailed, the relay to it."""
|
| 237 |
+
if self.jail is not None:
|
| 238 |
+
return self.jail.mcp_command([python, script] + list(args), env={"PATH": "/usr/bin:/bin"})
|
| 239 |
+
return python, [script] + list(args)
|
| 240 |
+
|
| 241 |
+
def jailed_argv(self, argv, env, cwd, dirs):
|
| 242 |
+
"""argv as started: unchanged, or wrapped into the jail with `dirs` (one-time dirs) mounted back."""
|
| 243 |
+
return self.jail.wrap(argv, env, cwd, dirs) if self.jail is not None else list(argv)
|
| 244 |
+
|
| 245 |
+
def jail_info(self):
|
| 246 |
+
return self.jail.info() if self.jail is not None else dict(enabled=False)
|
| 247 |
+
|
| 248 |
+
def auth_info(self):
|
| 249 |
+
"""How the harness authenticates to the model API (for harness.json; never a secret)."""
|
| 250 |
+
return dict(mode="api_env", keys=sorted(getattr(self, "api_env", {}) or {}))
|
| 251 |
+
|
| 252 |
+
def launch(self, spec, ep, skip_preflight=False):
|
| 253 |
+
if not self.unsafe_skip_clean_check:
|
| 254 |
+
probs = self.clean_state_problems(spec)
|
| 255 |
+
if probs:
|
| 256 |
+
spec.preflight = dict(problems=probs)
|
| 257 |
+
raise HarnessRefused("clean-state check: " + "; ".join(probs))
|
| 258 |
+
spec.preflight = dict(skipped=True, reason="skip_preflight") if skip_preflight else self.preflight(spec, ep)
|
| 259 |
+
out = open(spec.stdout_path, "wb")
|
| 260 |
+
err = open(spec.stderr_path, "wb")
|
| 261 |
+
h = RunHandle(spec=spec, ep=ep, t_start=time.time())
|
| 262 |
+
argv = self.jailed_argv(spec.argv, spec.env, spec.cwd, list(spec.state_dirs.values()) + [spec.run_dir])
|
| 263 |
+
h.proc = subprocess.Popen(argv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=out,
|
| 264 |
+
stderr=err, start_new_session=True)
|
| 265 |
+
h.pid = h.proc.pid
|
| 266 |
+
for _ in range(20): # the exec has happened once /proc/<pid>/environ differs from ours
|
| 267 |
+
keys = env_keys_of(h.pid)
|
| 268 |
+
if keys is not None and set(keys) == set(spec.env):
|
| 269 |
+
break
|
| 270 |
+
time.sleep(0.05)
|
| 271 |
+
h.env_observed_keys = env_keys_of(h.pid)
|
| 272 |
+
return h
|
| 273 |
+
|
| 274 |
+
def resume_argv(self, h, message):
|
| 275 |
+
"""argv that continues the run's session with one more user message (adapters with can_resume)."""
|
| 276 |
+
raise NotImplementedError
|
| 277 |
+
|
| 278 |
+
def resume(self, h, message):
|
| 279 |
+
"""Continue the run's session with one more user message, after the CLI exited before the episode was over
|
| 280 |
+
(scripts/harness_run.py sends the reference driver's nudge). Same env, work dir and one-time dirs; the output
|
| 281 |
+
is appended to the same stdout / stderr files."""
|
| 282 |
+
spec = h.spec
|
| 283 |
+
argv = self.resume_argv(h, message)
|
| 284 |
+
out, err = open(spec.stdout_path, "ab"), open(spec.stderr_path, "ab")
|
| 285 |
+
jargv = self.jailed_argv(argv, spec.env, spec.cwd, list(spec.state_dirs.values()) + [spec.run_dir])
|
| 286 |
+
h.proc = subprocess.Popen(jargv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=out,
|
| 287 |
+
stderr=err, start_new_session=True)
|
| 288 |
+
h.pid, h.exit_code, h.exit_reason = h.proc.pid, None, ""
|
| 289 |
+
keys = None
|
| 290 |
+
for _ in range(20):
|
| 291 |
+
keys = env_keys_of(h.pid)
|
| 292 |
+
if keys is not None and set(keys) == set(spec.env):
|
| 293 |
+
break
|
| 294 |
+
time.sleep(0.05)
|
| 295 |
+
h.info.setdefault("resumes", []).append(dict(t=time.time(), pid=h.pid, message=message,
|
| 296 |
+
argv=[("<message>" if x == message else x) for x in argv],
|
| 297 |
+
env_observed_keys=keys))
|
| 298 |
+
return h
|
| 299 |
+
|
| 300 |
+
def wait(self, h, timeout=None):
|
| 301 |
+
try:
|
| 302 |
+
h.exit_code = h.proc.wait(timeout=timeout or h.spec.timeout_s)
|
| 303 |
+
h.exit_reason = "exited" if h.exit_code == 0 else f"exit code {h.exit_code}"
|
| 304 |
+
except subprocess.TimeoutExpired:
|
| 305 |
+
self.kill(h)
|
| 306 |
+
h.exit_reason = "timeout"
|
| 307 |
+
h.t_end = time.time()
|
| 308 |
+
return h
|
| 309 |
+
|
| 310 |
+
@staticmethod
|
| 311 |
+
def kill(h):
|
| 312 |
+
try:
|
| 313 |
+
os.killpg(h.proc.pid, signal.SIGTERM)
|
| 314 |
+
h.exit_code = h.proc.wait(timeout=20)
|
| 315 |
+
except ProcessLookupError:
|
| 316 |
+
pass
|
| 317 |
+
except subprocess.TimeoutExpired:
|
| 318 |
+
os.killpg(h.proc.pid, signal.SIGKILL)
|
| 319 |
+
h.exit_code = h.proc.wait()
|
| 320 |
+
|
| 321 |
+
def logged_argv(self, spec):
|
| 322 |
+
return [spec.redact_argv.get(i, a) for i, a in enumerate(spec.argv)]
|
| 323 |
+
|
| 324 |
+
def cleanup(self, spec):
|
| 325 |
+
if spec.run_dir and spec.run_dir.startswith(("/tmp/lffrun/", "/tmp/lffstate/")) and os.path.isdir(spec.run_dir):
|
| 326 |
+
shutil.rmtree(spec.run_dir, ignore_errors=True)
|
| 327 |
+
for d in spec.state_dirs.values():
|
| 328 |
+
if d.startswith(("/tmp/lffrun/", "/tmp/lffstate/")) and os.path.isdir(d):
|
| 329 |
+
shutil.rmtree(d, ignore_errors=True)
|
| 330 |
+
if self.jail is not None:
|
| 331 |
+
self.jail.close()
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def gateway_env(log_dir):
|
| 335 |
+
"""{LFF_GATEWAY_URL, LFF_GATEWAY_TOKEN} of the episode's tool gateway, for a framework adapter (uses_gateway) whose
|
| 336 |
+
process talks to it through lffbench_client (Session.from_env). harness_run.py starts the gateway right before
|
| 337 |
+
launch, so call this in the adapter's launch() and add it to spec.env before the process starts. The token is the
|
| 338 |
+
gateway's, never robot_server's."""
|
| 339 |
+
d = json.load(open(os.path.join(log_dir, "gateway.json")))
|
| 340 |
+
return {"LFF_GATEWAY_URL": d["url"], "LFF_GATEWAY_TOKEN": d["token"]}
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def snapshot_tree(root):
|
| 344 |
+
"""Relative paths of all files under root (to list what a harness left behind)."""
|
| 345 |
+
out = []
|
| 346 |
+
for dp, dn, fn in os.walk(root):
|
| 347 |
+
for f in fn:
|
| 348 |
+
out.append(os.path.relpath(os.path.join(dp, f), root))
|
| 349 |
+
return sorted(out)
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def first_message_text(readme, status_json):
|
| 353 |
+
"""What a native harness gets as its first user message: the reference driver's instructions (preamble + README,
|
| 354 |
+
byte-identical) followed by its first user turn (the status report). The reference driver sends the same two
|
| 355 |
+
strings as system prompt and first user message; native harnesses keep their own system prompt."""
|
| 356 |
+
from .contract import tool_schemas
|
| 357 |
+
_, preamble = tool_schemas()
|
| 358 |
+
return preamble + readme + "\n\n" + "Begin. Current status (robot command `status`):\n" + status_json
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def reference_instructions(readme):
|
| 362 |
+
from .contract import tool_schemas
|
| 363 |
+
_, preamble = tool_schemas()
|
| 364 |
+
return preamble + readme
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/codex.py
ADDED
|
@@ -0,0 +1,687 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Codex CLI as a native harness (arm F; flags measured in research_notes/harness接入调研/02 §2.3, Codex 0.156).
|
| 2 |
+
|
| 3 |
+
Launch: process env exactly the whitelist (env -i equivalent), a brand-new empty CODEX_HOME and HOME (one-time, under
|
| 4 |
+
/tmp/lffstate/<hex>), work dir /tmp/lffrun/<12 hex>, `codex exec --json --skip-git-repo-check --ignore-user-config
|
| 5 |
+
--ignore-rules -s read-only`, ~20 features disabled, project docs / permissions / environment context /
|
| 6 |
+
collaboration-mode / skills instructions off, web search off, and only our MCP server with
|
| 7 |
+
default_tools_approval_mode="approve" (otherwise exec mode silently denies MCP calls).
|
| 8 |
+
|
| 9 |
+
Early exit: `codex exec` ends when the model replies without a tool call, also when the episode is not over (measured
|
| 10 |
+
2026-10-19, cx_pilot6b: gpt-6-astra stopped after a failed first attempt, "I stopped after the one authorized
|
| 11 |
+
attempt", although the finish reply said attempt 2 of 3 starts now). scripts/harness_run.py then sends the reference
|
| 12 |
+
driver's nudge as a user turn with `codex exec resume <thread>` (resume_argv), at most api_player.MAX_NO_TOOL times in
|
| 13 |
+
a row. Hence no --ephemeral: the session is kept in the one-time CODEX_HOME (memories off; removed after the run).
|
| 14 |
+
Measured with 0.163 against the fake server: the resumed request has the same developer messages, tools, model and
|
| 15 |
+
parameters as the first, then the earlier turns and the nudge as a user message.
|
| 16 |
+
|
| 17 |
+
The model API is a custom Responses provider "lffapi", so the preflight can point exactly the same config at a local
|
| 18 |
+
fake server by changing only base_url. Two ways to authenticate (auth=):
|
| 19 |
+
apikey env_key OPENAI_API_KEY (api_env), default endpoint the official API
|
| 20 |
+
chatgpt a ChatGPT subscription login (no API key; same as RPent's codex planner reusing `codex login`): the
|
| 21 |
+
provider gets requires_openai_auth=true (requests carry the login's bearer + chatgpt-account-id), default
|
| 22 |
+
endpoint the ChatGPT Codex backend; a copy of auth.json from the source CODEX_HOME is put into the one-time
|
| 23 |
+
CODEX_HOME (the only file allowed there at launch). If Codex refreshes the login during a run, the refreshed
|
| 24 |
+
auth.json is written back to the source (refresh tokens rotate), unless the source changed meanwhile.
|
| 25 |
+
Launch is refused when the source login is close to its refresh (parallel copies would each rotate it).
|
| 26 |
+
Measured with 0.163 against the fake server: same body keys and headers in both modes plus chatgpt-account-id; the
|
| 27 |
+
preset differs (exec tool description), so pins are per auth mode (pin name codex-chatgpt).
|
| 28 |
+
The calling environment's HTTP(S) proxy is passed through (base.proxy_env; NO_PROXY = loopback only).
|
| 29 |
+
|
| 30 |
+
Model configuration (catalog=, user 2026-10-20): Codex picks the system prompt, tool form and context window per
|
| 31 |
+
model from its model catalog. We always pass an explicit model_catalog_json written into the one-time CODEX_HOME, so
|
| 32 |
+
nothing depends on the catalog the subscription backend serves on the day:
|
| 33 |
+
generic (main table, every model) one entry built from codex_catalogs/generic_<version>.json: what Codex sends for a
|
| 34 |
+
model it has no entry for (its generic Codex CLI prompt, plain function tools, no code mode); per model only
|
| 35 |
+
slug, input modalities and reasoning levels. Measured with 0.163 against the fake server: the request equals
|
| 36 |
+
the no-catalog fallback for an unknown slug apart from message ids.
|
| 37 |
+
native (control) codex_catalogs/native_<version>.json = `codex debug models --bundled` of that binary: the request
|
| 38 |
+
equals the one without any catalog (GPT: code mode, its own prompt). The pins of before 10-20 stay valid.
|
| 39 |
+
Pins are per catalog (pin name codex[-chatgpt][-generic]).
|
| 40 |
+
|
| 41 |
+
Known, accepted differences in native (code mode) catalogs (reported, not fixable by config in 0.156):
|
| 42 |
+
- code mode: the model sees one `exec` tool (JavaScript in a V8 isolate without fs / network); our tools are nested
|
| 43 |
+
and listed only in ALL_TOOLS; MCP images reach the model only if the model's JS calls image(...)
|
| 44 |
+
- apply_patch (blocked by the read-only sandbox), clock, 3 MCP-resource tools (our server has no resources),
|
| 45 |
+
request_user_input, and 6 collaboration.* sub-agent tools cannot be removed; a sub-agent call is an audit violation
|
| 46 |
+
- --json has tokens but no dollar cost
|
| 47 |
+
Fail-closed launch: the preflight checks the top-level tools, the exec nested-tool list (ALL_TOOLS, printed by a
|
| 48 |
+
scripted exec call), the developer (preset) messages and request parameters against the pin.
|
| 49 |
+
"""
|
| 50 |
+
import base64
|
| 51 |
+
import datetime
|
| 52 |
+
import fcntl
|
| 53 |
+
import json
|
| 54 |
+
import os
|
| 55 |
+
import re
|
| 56 |
+
import shutil
|
| 57 |
+
import sqlite3
|
| 58 |
+
import subprocess
|
| 59 |
+
import sys
|
| 60 |
+
import time
|
| 61 |
+
|
| 62 |
+
from . import contract as C
|
| 63 |
+
from . import pins
|
| 64 |
+
from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info,
|
| 65 |
+
new_run_dir, proxy_env, snapshot_tree)
|
| 66 |
+
from .fakeapi import FakeResponses
|
| 67 |
+
from .trajectory import TrajWriter
|
| 68 |
+
|
| 69 |
+
ROOT = C.ROOT
|
| 70 |
+
MCP_SCRIPT = os.path.join(ROOT, "scripts", "mcp_robot_server.py")
|
| 71 |
+
BASE_PATH = "/usr/bin:/bin"
|
| 72 |
+
OFFICIAL_API = "https://api.openai.com/v1"
|
| 73 |
+
CHATGPT_BACKEND = "https://chatgpt.com/backend-api/codex"
|
| 74 |
+
AUTH_FILE = "auth.json"
|
| 75 |
+
AUTH_LOCK = "/tmp/lffstate/.codex_auth.lock"
|
| 76 |
+
MAX_LOGIN_AGE_H = 8 * 24 # codex-rs TOKEN_REFRESH_INTERVAL (8 days, from the source, not measured here): a login
|
| 77 |
+
# older than this is refreshed at start, by every parallel copy
|
| 78 |
+
MIN_ACCESS_LEFT_H = 24 # an access token expiring during a run makes the run's copy refresh it
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _jwt_claims(tok):
|
| 82 |
+
try:
|
| 83 |
+
p = tok.split(".")[1]
|
| 84 |
+
return json.loads(base64.urlsafe_b64decode(p + "=" * (-len(p) % 4)))
|
| 85 |
+
except (IndexError, ValueError, AttributeError):
|
| 86 |
+
return {}
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def chatgpt_login_status(home):
|
| 90 |
+
"""-> dict(ok, problem, last_refresh_h, access_token_valid_h) of the ChatGPT login in home/auth.json. No secret
|
| 91 |
+
leaves this function."""
|
| 92 |
+
src = os.path.join(home, AUTH_FILE)
|
| 93 |
+
try:
|
| 94 |
+
with open(src) as f:
|
| 95 |
+
a = json.load(f)
|
| 96 |
+
except (OSError, ValueError) as e:
|
| 97 |
+
return dict(ok=False, problem=f"cannot read {src}: {type(e).__name__}")
|
| 98 |
+
tok = a.get("tokens") or {}
|
| 99 |
+
if a.get("auth_mode") != "chatgpt" or not tok.get("access_token") or not tok.get("refresh_token"):
|
| 100 |
+
return dict(ok=False, problem=f"{src} is not a ChatGPT login (auth_mode={a.get('auth_mode')!r})")
|
| 101 |
+
now = time.time()
|
| 102 |
+
try:
|
| 103 |
+
lr = datetime.datetime.fromisoformat(str(a.get("last_refresh")).replace("Z", "+00:00")).timestamp()
|
| 104 |
+
age_h = (now - lr) / 3600
|
| 105 |
+
except ValueError:
|
| 106 |
+
age_h = float("inf")
|
| 107 |
+
left_h = (float(_jwt_claims(tok["access_token"]).get("exp") or 0) - now) / 3600
|
| 108 |
+
out = dict(ok=True, problem=None, last_refresh_h=round(age_h, 1), access_token_valid_h=round(left_h, 1))
|
| 109 |
+
if age_h >= MAX_LOGIN_AGE_H or left_h < MIN_ACCESS_LEFT_H:
|
| 110 |
+
out.update(ok=False, problem=f"the ChatGPT login in {home} is due for a refresh (last refresh {age_h:.0f} h ago, "
|
| 111 |
+
f"access token valid {left_h:.0f} h): refresh it once outside the benchmark (use "
|
| 112 |
+
f"codex with CODEX_HOME={home}), so that parallel runs do not each rotate it")
|
| 113 |
+
return out
|
| 114 |
+
DISABLE = ["shell_tool", "unified_exec", "view_image", "multi_agent", "multi_agent_v2", "apps", "browser_use",
|
| 115 |
+
"browser_use_external", "computer_use", "image_generation", "plugins", "hooks", "skill_search",
|
| 116 |
+
"tool_suggest", "goals", "sleep_tool", "in_app_browser", "memories", "skill_mcp_dependency_install",
|
| 117 |
+
"realtime_conversation"]
|
| 118 |
+
# what remains in 0.156 after the lock-down (measured): anything else is refused at launch
|
| 119 |
+
EXPECTED_TOP = ["collaboration.followup_task", "collaboration.interrupt_agent", "collaboration.list_agents",
|
| 120 |
+
"collaboration.send_message", "collaboration.spawn_agent", "collaboration.wait_agent",
|
| 121 |
+
"functions.exec", "functions.request_user_input", "functions.request_user_input_async",
|
| 122 |
+
"functions.wait"]
|
| 123 |
+
EXPECTED_ALL_TOOLS = ["apply_patch", "clock__curr_time", "list_mcp_resource_templates", "list_mcp_resources",
|
| 124 |
+
"mcp__lff__robot", "mcp__lff__shell", "mcp__lff__view_images", "read_mcp_resource"]
|
| 125 |
+
# generic catalog (no code mode), measured with 0.163: our tools are plain functions in the mcp__lff namespace
|
| 126 |
+
EXPECTED_TOP_GENERIC = ["list_mcp_resource_templates", "list_mcp_resources", "mcp__lff.robot", "mcp__lff.shell",
|
| 127 |
+
"mcp__lff.view_images", "read_mcp_resource", "request_user_input"]
|
| 128 |
+
CATALOG_DIR = os.path.join(ROOT, "lffbench", "harnesses", "codex_catalogs")
|
| 129 |
+
CATALOG_FILE = "lff_model_catalog.json" # written into the one-time CODEX_HOME before launch
|
| 130 |
+
CATALOGS = ("generic", "native")
|
| 131 |
+
# generic catalog: the per-model fields (input modalities; the run's reasoning level is always listed)
|
| 132 |
+
TEXT_ONLY_MODELS = {"deepseek-v4-pro": ["text"]} # DeepSeek's Codex guide (read 2026-10-20): v4-pro takes no images
|
| 133 |
+
DEEPSEEK_URL = "https://api.deepseek.com/" # same guide: base_url, wire_api = "responses"
|
| 134 |
+
OPENCODE_GO_URL = "https://opencode.ai/inference/go/openai/v1" # OpenCode Go, Responses API (checked 2026-10-29)
|
| 135 |
+
MCP_TOOLS = ["robot", "shell", "view_images"]
|
| 136 |
+
OK_ITEMS = ("agent_message", "reasoning", "mcp_tool_call", "error")
|
| 137 |
+
PREFLIGHT_JS = "text(JSON.stringify(ALL_TOOLS));"
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def codex_bin():
|
| 141 |
+
return os.environ.get("LFF_CODEX_BIN") or shutil.which("codex") or "codex"
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def toml_str(s):
|
| 145 |
+
return json.dumps(s) # a JSON string literal is a valid TOML basic string
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def _norm(s, cwd):
|
| 149 |
+
s = s.replace(cwd, "<CWD>")
|
| 150 |
+
s = re.sub(r"/tmp/lffrun/[0-9a-f]{12}", "<RUNDIR>", s)
|
| 151 |
+
s = re.sub(r"/tmp/lffstate/[0-9a-f]{12}", "<STATEDIR>", s)
|
| 152 |
+
s = re.sub(r"\b20\d\d-\d\d-\d\d\b", "<DATE>", s)
|
| 153 |
+
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", "<UUID>", s)
|
| 154 |
+
return s
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _walk_tools(ts, prefix=""):
|
| 158 |
+
out = []
|
| 159 |
+
for t in ts or []:
|
| 160 |
+
if t.get("type") == "namespace":
|
| 161 |
+
out += _walk_tools(t.get("tools"), prefix + t.get("name", "") + ".")
|
| 162 |
+
else:
|
| 163 |
+
out.append(dict(name=prefix + (t.get("name") or t.get("type") or "?"), type=t.get("type"),
|
| 164 |
+
description=t.get("description"), parameters=t.get("parameters"), format=t.get("format")))
|
| 165 |
+
return out
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def request_fingerprint(body, cwd, first_message, expected_top=None):
|
| 169 |
+
problems = []
|
| 170 |
+
items = body.get("input") or []
|
| 171 |
+
top = _walk_tools(body.get("tools"))
|
| 172 |
+
dev, users = [], []
|
| 173 |
+
for it in items:
|
| 174 |
+
if it.get("type") == "additional_tools":
|
| 175 |
+
top += _walk_tools(it.get("tools"))
|
| 176 |
+
elif it.get("type") == "message" and it.get("role") in ("developer", "system"):
|
| 177 |
+
dev.append(_norm("\n".join(c.get("text", "") for c in it.get("content") or []), cwd))
|
| 178 |
+
elif it.get("type") == "message" and it.get("role") == "user":
|
| 179 |
+
users.append(it)
|
| 180 |
+
names = sorted(t["name"] for t in top)
|
| 181 |
+
expected_top = EXPECTED_TOP if expected_top is None else expected_top
|
| 182 |
+
if names != expected_top:
|
| 183 |
+
problems.append(f"top-level tools {names} != expected {expected_top}")
|
| 184 |
+
texts = [c.get("text") for u in users for c in u.get("content") or []]
|
| 185 |
+
if texts != [first_message]:
|
| 186 |
+
problems.append(f"user input is not exactly our first message ({len(texts)} user text blocks)")
|
| 187 |
+
for t in top:
|
| 188 |
+
if t.get("description"):
|
| 189 |
+
t["description"] = _norm(t["description"], cwd)
|
| 190 |
+
params = {k: body.get(k) for k in ("model", "reasoning", "parallel_tool_calls", "store", "include", "text",
|
| 191 |
+
"tool_choice", "instructions", "max_output_tokens", "temperature")}
|
| 192 |
+
meta = body.get("client_metadata") or {}
|
| 193 |
+
try:
|
| 194 |
+
turn_meta = json.loads(meta.get("x-codex-turn-metadata") or "{}")
|
| 195 |
+
except ValueError:
|
| 196 |
+
turn_meta = {}
|
| 197 |
+
sandbox = {k: turn_meta.get(k) for k in ("sandbox", "sandbox_mode")}
|
| 198 |
+
if sandbox.get("sandbox_mode") != "read-only":
|
| 199 |
+
problems.append(f"sandbox {sandbox}")
|
| 200 |
+
fp = dict(tools=sorted(top, key=lambda t: t["name"]), developer=dev, params=params, sandbox=sandbox,
|
| 201 |
+
developer_chars=sum(len(d) for d in dev))
|
| 202 |
+
return fp, problems
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def model_catalog(mode, version, model, modalities=None, effort=None):
|
| 206 |
+
"""-> (catalog dict for model_catalog_json, source file). Refuses (fail-closed) when the version has no catalog
|
| 207 |
+
file or, for native, when the model has no entry."""
|
| 208 |
+
if mode not in CATALOGS:
|
| 209 |
+
raise ValueError(f"catalog must be one of {CATALOGS}, not {mode!r}")
|
| 210 |
+
src = os.path.join(CATALOG_DIR, f"{mode}_{version}.json")
|
| 211 |
+
if not os.path.exists(src):
|
| 212 |
+
raise HarnessRefused(f"no {mode} model catalog for Codex {version} ({os.path.relpath(src, ROOT)})")
|
| 213 |
+
d = json.load(open(src))
|
| 214 |
+
if mode == "native":
|
| 215 |
+
if not any(m.get("slug") == model for m in d.get("models") or []):
|
| 216 |
+
raise HarnessRefused(f"native catalog {os.path.basename(src)} has no entry for {model}")
|
| 217 |
+
return d, src
|
| 218 |
+
e = dict(d["entry"], slug=model, display_name=model)
|
| 219 |
+
modalities = modalities or TEXT_ONLY_MODELS.get(model)
|
| 220 |
+
if modalities:
|
| 221 |
+
e["input_modalities"] = list(modalities)
|
| 222 |
+
levels = [dict(x) for x in e.get("supported_reasoning_levels") or []]
|
| 223 |
+
if effort and effort not in [x.get("effort") for x in levels]:
|
| 224 |
+
levels.append(dict(effort=effort, description=effort))
|
| 225 |
+
e["supported_reasoning_levels"] = levels
|
| 226 |
+
return dict(models=[e]), src
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def all_tools_from(body):
|
| 230 |
+
"""The ALL_TOOLS list printed by the preflight exec call (in the second request)."""
|
| 231 |
+
for it in body.get("input") or []:
|
| 232 |
+
if it.get("type") == "custom_tool_call_output":
|
| 233 |
+
out = it.get("output")
|
| 234 |
+
parts = out if isinstance(out, list) else [dict(text=out)]
|
| 235 |
+
for p in parts:
|
| 236 |
+
t = (p.get("text") or "").strip()
|
| 237 |
+
if t.startswith("["):
|
| 238 |
+
try:
|
| 239 |
+
return json.loads(t)
|
| 240 |
+
except ValueError:
|
| 241 |
+
pass
|
| 242 |
+
return None
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
class Codex(HarnessAdapter):
|
| 246 |
+
name = "codex"
|
| 247 |
+
uses_mcp = True
|
| 248 |
+
can_resume = True
|
| 249 |
+
clean_dirs = ("home", "codex_home", "tmp")
|
| 250 |
+
ancestor_files = ("AGENTS.md", "AGENTS.override.md", ".codex")
|
| 251 |
+
capabilities = dict(
|
| 252 |
+
only_benchmark_tools=Cap("partial", "preflight", "generic catalog: our 3 MCP tools as functions + residual "
|
| 253 |
+
"resource×3 / request_user_input; native (code mode): reachable only via exec(JS), "
|
| 254 |
+
"residual apply_patch(blocked) / clock / resource×3 / request_user_input / "
|
| 255 |
+
"collaboration×6"),
|
| 256 |
+
images_reach_model=Cap("partial", "probe", "generic: MCP images go to the model; native (code mode): only if "
|
| 257 |
+
"the model's JS calls image(); bytes unchanged either way"),
|
| 258 |
+
non_persistent_session=Cap("yes", "probe", "only this run's thread, in the one-time CODEX_HOME (for exec "
|
| 259 |
+
"resume), removed after the run; memories off"),
|
| 260 |
+
pinned_version=Cap("yes", "launch", "codex --version + binary sha256 in harness.json; pin per version"),
|
| 261 |
+
machine_readable_events=Cap("yes", "stream", "exec --json (items + usage, no cost)"),
|
| 262 |
+
tool_calls_logged=Cap("yes", "stream", "mcp_tool_call items + mcp_transcript + events.jsonl"),
|
| 263 |
+
model_and_effort=Cap("yes", "preflight", "-m / model_reasoning_effort; request reasoning.effort checked"),
|
| 264 |
+
persistent_memory=Cap("absent", "probe", "memories feature off; empty one-time CODEX_HOME; canaries absent"),
|
| 265 |
+
instruction_file_injection=Cap("absent", "probe", "project_doc_max_bytes=0 + empty CODEX_HOME (AGENTS.md)"),
|
| 266 |
+
web_access=Cap("absent", "probe", "web_search disabled; exec isolate has no fetch"),
|
| 267 |
+
host_file_read=Cap("absent", "probe", "shell / unified_exec / view_image off; exec has no require; "
|
| 268 |
+
"read-only sandbox"),
|
| 269 |
+
builtin_shell=Cap("absent", "preflight", "shell_tool and unified_exec disabled (not in the tool list)"),
|
| 270 |
+
subagent_delegation=Cap("partial", "preflight", "collaboration.* tools cannot be disabled in 0.156; any use "
|
| 271 |
+
"is an audit violation"),
|
| 272 |
+
background_execution=Cap("partial", "preflight", "functions.wait / long exec yields exist; audited"),
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False,
|
| 276 |
+
python=None, extra_args=None, jail=False, auth="apikey", auth_home=None, catalog="generic",
|
| 277 |
+
modalities=None):
|
| 278 |
+
"""api_env: {"OPENAI_API_KEY": ...} (the provider's env_key, auth="apikey"); base_url: Responses endpoint
|
| 279 |
+
(default: official API / ChatGPT Codex backend by auth). auth="chatgpt": a ChatGPT login copied from
|
| 280 |
+
auth_home (default LFF_CODEX_AUTH_HOME, else the calling CODEX_HOME, else ~/.codex), no API key.
|
| 281 |
+
jail: run the CLI in the native-harness jail (lffbench/harnesses/jail.py, static /proc).
|
| 282 |
+
catalog: "generic" (shared configuration of the main table) or "native" (Codex's own entry for the model);
|
| 283 |
+
modalities: input modalities of a generic entry (default text + image)."""
|
| 284 |
+
if catalog not in CATALOGS:
|
| 285 |
+
raise ValueError(f"catalog must be one of {CATALOGS}, not {catalog!r}")
|
| 286 |
+
self.catalog, self.modalities = catalog, (list(modalities) if modalities else None)
|
| 287 |
+
self._catalog_sha = {} # one-time CODEX_HOME -> sha256 of the catalog written there
|
| 288 |
+
if auth not in ("apikey", "chatgpt"):
|
| 289 |
+
raise ValueError(f"auth must be apikey or chatgpt, not {auth!r}")
|
| 290 |
+
if jail:
|
| 291 |
+
from .jail import HarnessJail
|
| 292 |
+
self.jail = HarnessJail(codex_bin(), proc="static")
|
| 293 |
+
self.auth = auth
|
| 294 |
+
self.auth_home = None
|
| 295 |
+
self._auth_copies = {} # one-time CODEX_HOME -> sha256 of the auth.json copied into it
|
| 296 |
+
if auth == "chatgpt":
|
| 297 |
+
self.auth_home = os.path.abspath(auth_home or os.environ.get("LFF_CODEX_AUTH_HOME")
|
| 298 |
+
or os.environ.get("CODEX_HOME") or os.path.expanduser("~/.codex"))
|
| 299 |
+
self.clean_allowed = {"codex_home": ((AUTH_FILE,) if auth == "chatgpt" else ()) + (CATALOG_FILE,)}
|
| 300 |
+
self.api_env = dict(api_env or {}) if auth == "apikey" else {}
|
| 301 |
+
self.base_url = base_url or (OFFICIAL_API if auth == "apikey" else CHATGPT_BACKEND)
|
| 302 |
+
self.proxy = proxy_env()
|
| 303 |
+
self.timeout_s = timeout_s
|
| 304 |
+
self.pins_dir = pins_dir
|
| 305 |
+
self.allow_unpinned = allow_unpinned
|
| 306 |
+
self.python = python or sys.executable
|
| 307 |
+
self.extra_args = list(extra_args or [])
|
| 308 |
+
self._version = None
|
| 309 |
+
|
| 310 |
+
# ------------------------------------------------------------------------------------------------ auth
|
| 311 |
+
def auth_info(self):
|
| 312 |
+
if self.auth == "apikey":
|
| 313 |
+
return dict(mode="apikey", keys=sorted(self.api_env))
|
| 314 |
+
st = chatgpt_login_status(self.auth_home)
|
| 315 |
+
return dict(mode="chatgpt", source=self.auth_home, **{k: v for k, v in st.items() if k != "ok"})
|
| 316 |
+
|
| 317 |
+
def config_info(self):
|
| 318 |
+
"""For harness.json: which model catalog the run used."""
|
| 319 |
+
return dict(catalog=self.catalog, modalities=self.modalities)
|
| 320 |
+
|
| 321 |
+
def _install_catalog(self, codex_home, ep):
|
| 322 |
+
"""Write the run's model catalog into the one-time CODEX_HOME (the only file besides auth.json allowed there
|
| 323 |
+
at launch). -> (path, sha256, source file, code mode)."""
|
| 324 |
+
cat, src = model_catalog(self.catalog, self.version()["version"], ep.model, self.modalities, ep.effort)
|
| 325 |
+
path = os.path.join(codex_home, CATALOG_FILE)
|
| 326 |
+
with open(path, "w") as f:
|
| 327 |
+
json.dump(cat, f)
|
| 328 |
+
sha = C.sha256_file(path)
|
| 329 |
+
self._catalog_sha[codex_home] = sha
|
| 330 |
+
entry = next(m for m in cat["models"] if m.get("slug") == ep.model)
|
| 331 |
+
return path, sha, os.path.relpath(src, ROOT), entry.get("tool_mode") == "code_mode_only"
|
| 332 |
+
|
| 333 |
+
def _install_auth(self, codex_home):
|
| 334 |
+
"""auth="chatgpt": copy the source login into a one-time CODEX_HOME (refused if it is due for a refresh)."""
|
| 335 |
+
if self.auth != "chatgpt":
|
| 336 |
+
return
|
| 337 |
+
st = chatgpt_login_status(self.auth_home)
|
| 338 |
+
if not st["ok"]:
|
| 339 |
+
raise HarnessRefused("ChatGPT login: " + st["problem"])
|
| 340 |
+
dst = os.path.join(codex_home, AUTH_FILE)
|
| 341 |
+
with open(os.path.join(self.auth_home, AUTH_FILE), "rb") as f:
|
| 342 |
+
data = f.read()
|
| 343 |
+
fd = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
| 344 |
+
with os.fdopen(fd, "wb") as f:
|
| 345 |
+
f.write(data)
|
| 346 |
+
self._auth_copies[codex_home] = C.sha256_file(dst)
|
| 347 |
+
|
| 348 |
+
def _sync_auth_back(self, codex_home):
|
| 349 |
+
"""After a run: if Codex refreshed the login in the run's copy, write it back to the source (refresh tokens
|
| 350 |
+
rotate, the source's old one may no longer work), unless the source changed since the copy. -> note or None."""
|
| 351 |
+
copied = self._auth_copies.pop(codex_home, None)
|
| 352 |
+
p = os.path.join(codex_home, AUTH_FILE)
|
| 353 |
+
if copied is None or not os.path.exists(p) or C.sha256_file(p) == copied:
|
| 354 |
+
return None
|
| 355 |
+
try:
|
| 356 |
+
with open(p, "rb") as f:
|
| 357 |
+
data = f.read()
|
| 358 |
+
new = json.loads(data)
|
| 359 |
+
except (OSError, ValueError):
|
| 360 |
+
return "auth.json in the run's CODEX_HOME changed and is unreadable: not written back"
|
| 361 |
+
if new.get("auth_mode") != "chatgpt" or not (new.get("tokens") or {}).get("refresh_token"):
|
| 362 |
+
return "auth.json in the run's CODEX_HOME changed but holds no ChatGPT login: not written back"
|
| 363 |
+
src = os.path.join(self.auth_home, AUTH_FILE)
|
| 364 |
+
os.makedirs(os.path.dirname(AUTH_LOCK), exist_ok=True)
|
| 365 |
+
with open(AUTH_LOCK, "a") as lk:
|
| 366 |
+
fcntl.flock(lk, fcntl.LOCK_EX)
|
| 367 |
+
if C.sha256_file(src) != copied:
|
| 368 |
+
return "the run refreshed its login copy, but the source auth.json changed meanwhile: not written back"
|
| 369 |
+
tmp = src + ".lff-tmp"
|
| 370 |
+
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
| 371 |
+
with os.fdopen(fd, "wb") as f:
|
| 372 |
+
f.write(data)
|
| 373 |
+
os.replace(tmp, src)
|
| 374 |
+
return "the run refreshed the ChatGPT login: refreshed auth.json written back to the source"
|
| 375 |
+
|
| 376 |
+
def version(self):
|
| 377 |
+
if self._version is None:
|
| 378 |
+
b = codex_bin()
|
| 379 |
+
out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent",
|
| 380 |
+
CODEX_HOME="/nonexistent"),
|
| 381 |
+
capture_output=True, text=True, timeout=60)
|
| 382 |
+
v = (out.stdout.strip().split() or ["?"])[-1]
|
| 383 |
+
self._version = dict(version=v, binary=binary_info(b))
|
| 384 |
+
return self._version
|
| 385 |
+
|
| 386 |
+
def pin_key(self, ep):
|
| 387 |
+
v = self.version()
|
| 388 |
+
name = self.name if self.auth == "apikey" else f"{self.name}-{self.auth}"
|
| 389 |
+
name += "" if self.catalog == "native" else f"-{self.catalog}"
|
| 390 |
+
return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
|
| 391 |
+
|
| 392 |
+
# ------------------------------------------------------------------------------------------------ prepare
|
| 393 |
+
def config_args(self, ep, session_path, base_url, codex_home):
|
| 394 |
+
mcp_cmd, mcp_args = self.mcp_server_command(self.python, MCP_SCRIPT, ["--session", session_path] if session_path
|
| 395 |
+
else ["--schema-only"])
|
| 396 |
+
c = ["model_reasoning_effort=" + toml_str(ep.effort),
|
| 397 |
+
"project_doc_max_bytes=0", "include_permissions_instructions=false", "include_environment_context=false",
|
| 398 |
+
"include_collaboration_mode_instructions=false", "skills.include_instructions=false",
|
| 399 |
+
"skills.bundled.enabled=false", 'web_search="disabled"',
|
| 400 |
+
'model_provider="lffapi"', 'model_providers.lffapi.name="lffapi"',
|
| 401 |
+
"model_providers.lffapi.base_url=" + toml_str(base_url), 'model_providers.lffapi.wire_api="responses"',
|
| 402 |
+
('model_providers.lffapi.env_key="OPENAI_API_KEY"' if self.auth == "apikey"
|
| 403 |
+
else "model_providers.lffapi.requires_openai_auth=true"),
|
| 404 |
+
"mcp_servers.lff.command=" + toml_str(mcp_cmd),
|
| 405 |
+
"mcp_servers.lff.args=[" + ",".join(toml_str(x) for x in mcp_args) + "]",
|
| 406 |
+
"mcp_servers.lff.env={PATH=" + toml_str(BASE_PATH) + "}",
|
| 407 |
+
'mcp_servers.lff.enabled_tools=["robot","shell","view_images"]',
|
| 408 |
+
'mcp_servers.lff.default_tools_approval_mode="approve"', "mcp_servers.lff.required=true",
|
| 409 |
+
"mcp_servers.lff.startup_timeout_sec=60", "mcp_servers.lff.tool_timeout_sec=900",
|
| 410 |
+
"model_catalog_json=" + toml_str(os.path.join(codex_home, CATALOG_FILE))]
|
| 411 |
+
return c
|
| 412 |
+
|
| 413 |
+
def argv(self, ep, session_path, base_url, first_message, codex_home):
|
| 414 |
+
a = [codex_bin(), "exec", "--json", "--skip-git-repo-check", "--ignore-user-config",
|
| 415 |
+
"--ignore-rules", "-s", "read-only", "-m", ep.model]
|
| 416 |
+
for f in DISABLE:
|
| 417 |
+
a += ["--disable", f]
|
| 418 |
+
for c in self.config_args(ep, session_path, base_url, codex_home):
|
| 419 |
+
a += ["-c", c]
|
| 420 |
+
return a + self.extra_args + [first_message]
|
| 421 |
+
|
| 422 |
+
@staticmethod
|
| 423 |
+
def thread_id(stdout_path):
|
| 424 |
+
t = None
|
| 425 |
+
for line in open(stdout_path, encoding="utf-8", errors="replace"):
|
| 426 |
+
if line.startswith("{") and '"thread.started"' in line:
|
| 427 |
+
t = json.loads(line).get("thread_id") or t
|
| 428 |
+
return t
|
| 429 |
+
|
| 430 |
+
def resume_argv(self, h, message):
|
| 431 |
+
"""`codex exec resume <thread> <message>` with the launch's flags and config; resume has no -s, so the
|
| 432 |
+
sandbox goes in as sandbox_mode."""
|
| 433 |
+
thread = self.thread_id(h.spec.stdout_path)
|
| 434 |
+
if not thread:
|
| 435 |
+
raise HarnessRefused("resume: no thread id in the event stream")
|
| 436 |
+
a = list(h.spec.argv[:-1]) # without the first message
|
| 437 |
+
i = a.index("exec")
|
| 438 |
+
rest = a[i + 1:]
|
| 439 |
+
j = rest.index("-s")
|
| 440 |
+
mode = rest[j + 1]
|
| 441 |
+
del rest[j:j + 2]
|
| 442 |
+
return a[:i + 1] + ["resume"] + rest + ["-c", "sandbox_mode=" + toml_str(mode), thread, message]
|
| 443 |
+
|
| 444 |
+
def env(self, state):
|
| 445 |
+
e = dict(PATH=BASE_PATH, HOME=state["home"], CODEX_HOME=state["codex_home"], TMPDIR=state["tmp"],
|
| 446 |
+
LANG="C.UTF-8")
|
| 447 |
+
e.update(self.proxy)
|
| 448 |
+
e.update(self.api_env)
|
| 449 |
+
return e
|
| 450 |
+
|
| 451 |
+
def _state_dirs(self, hexname=None):
|
| 452 |
+
root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate")
|
| 453 |
+
os.makedirs(root, exist_ok=True)
|
| 454 |
+
state = dict(state=root, home=os.path.join(root, "home"), codex_home=os.path.join(root, "codex_home"),
|
| 455 |
+
tmp=os.path.join(root, "tmp"))
|
| 456 |
+
for k in ("home", "codex_home", "tmp"):
|
| 457 |
+
os.makedirs(state[k], exist_ok=True)
|
| 458 |
+
return state
|
| 459 |
+
|
| 460 |
+
def prepare(self, ep, first_message, reuse_state=None):
|
| 461 |
+
work = new_run_dir("/tmp/lffrun")
|
| 462 |
+
state = reuse_state or self._state_dirs(os.path.basename(work))
|
| 463 |
+
if self.jail is not None:
|
| 464 |
+
self.jail.stderr_dir = ep.log_dir
|
| 465 |
+
if not reuse_state and os.listdir(state["codex_home"]):
|
| 466 |
+
raise HarnessRefused("CODEX_HOME is not empty")
|
| 467 |
+
cat_path, cat_sha, cat_src, code_mode = self._install_catalog(state["codex_home"], ep)
|
| 468 |
+
argv = self.argv(ep, ep.session_path, self.base_url, first_message, state["codex_home"])
|
| 469 |
+
return LaunchSpec(argv=argv, env=self.env(state), cwd=work, run_dir=work, state_dirs=state,
|
| 470 |
+
first_message=first_message, stdout_path=os.path.join(ep.log_dir, "codex_events.jsonl"),
|
| 471 |
+
stderr_path=os.path.join(ep.log_dir, "codex_stderr.txt"),
|
| 472 |
+
redact_argv={len(argv) - 1: f"<first message: sha256={C.sha256_text(first_message)}>"},
|
| 473 |
+
config_files=dict(model_catalog_json=dict(path=cat_path, sha256=cat_sha, source=cat_src,
|
| 474 |
+
catalog=self.catalog, code_mode=code_mode)),
|
| 475 |
+
timeout_s=self.timeout_s)
|
| 476 |
+
|
| 477 |
+
def launch(self, spec, ep, skip_preflight=False):
|
| 478 |
+
self._install_auth(spec.state_dirs["codex_home"])
|
| 479 |
+
return super().launch(spec, ep, skip_preflight=skip_preflight)
|
| 480 |
+
|
| 481 |
+
def cleanup(self, spec):
|
| 482 |
+
self._sync_auth_back(spec.state_dirs.get("codex_home", ""))
|
| 483 |
+
super().cleanup(spec)
|
| 484 |
+
|
| 485 |
+
def config_sha256(self, spec, ep):
|
| 486 |
+
"""Hash of everything configurable (argv without the first message, env values except keys / one-time dirs)."""
|
| 487 |
+
argv = [re.sub(r"/tmp/lffsock/[0-9a-f]{12}/[^\"\],]+", "<JAIL_SOCKET>", a.replace(ep.session_path, "<SESSION>"))
|
| 488 |
+
.replace(spec.state_dirs["codex_home"], "<CODEX_HOME>") for a in self.logged_argv(spec)[1:-1]]
|
| 489 |
+
env = {k: (v if k not in self.api_env else "<api>") for k, v in spec.env.items()
|
| 490 |
+
if k not in ("HOME", "CODEX_HOME", "TMPDIR") + PROXY_KEYS + NO_PROXY_KEYS}
|
| 491 |
+
cat = (spec.config_files.get("model_catalog_json") or {}).get("sha256")
|
| 492 |
+
return C.sha256_json(dict(argv=argv, env=env, model_catalog_sha256=cat))
|
| 493 |
+
|
| 494 |
+
# ------------------------------------------------------------------------------------------------ preflight
|
| 495 |
+
def preflight(self, spec, ep, record_dir=None):
|
| 496 |
+
t0 = time.time()
|
| 497 |
+
code_mode = (spec.config_files.get("model_catalog_json") or {}).get("code_mode", True)
|
| 498 |
+
script = [[("exec", PREFLIGHT_JS)], [("text", "preflight ok")]] if code_mode else [[("text", "preflight ok")]]
|
| 499 |
+
fake = FakeResponses(script, record_dir=record_dir).start()
|
| 500 |
+
pre = self._state_dirs()
|
| 501 |
+
try:
|
| 502 |
+
self._install_auth(pre["codex_home"])
|
| 503 |
+
self._install_catalog(pre["codex_home"], ep)
|
| 504 |
+
argv = self.argv(ep, None, fake.base_url, spec.first_message, pre["codex_home"])
|
| 505 |
+
env = self.env(pre)
|
| 506 |
+
if self.auth == "apikey":
|
| 507 |
+
env["OPENAI_API_KEY"] = "sk-preflight-not-a-key"
|
| 508 |
+
r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd,
|
| 509 |
+
stdin=subprocess.DEVNULL, capture_output=True, timeout=180)
|
| 510 |
+
reqs = fake.model_requests()
|
| 511 |
+
if len(reqs) < (2 if code_mode else 1):
|
| 512 |
+
raise HarnessRefused(f"preflight: {len(reqs)} model requests (rc={r.returncode}): "
|
| 513 |
+
f"{r.stderr.decode('utf-8', 'replace')[-800:]}")
|
| 514 |
+
fp, problems = request_fingerprint(reqs[0][1], spec.cwd, spec.first_message,
|
| 515 |
+
EXPECTED_TOP if code_mode else EXPECTED_TOP_GENERIC)
|
| 516 |
+
at_names = None
|
| 517 |
+
if code_mode: # our tools are nested in exec: the scripted exec call prints them
|
| 518 |
+
at = all_tools_from(reqs[1][1])
|
| 519 |
+
if at is None:
|
| 520 |
+
problems.append("exec preflight did not print ALL_TOOLS")
|
| 521 |
+
at = []
|
| 522 |
+
at_names = sorted(t.get("name") if isinstance(t, dict) else str(t) for t in at)
|
| 523 |
+
if at_names != EXPECTED_ALL_TOOLS:
|
| 524 |
+
problems.append(f"ALL_TOOLS {at_names} != expected {EXPECTED_ALL_TOOLS}")
|
| 525 |
+
fp["all_tools"] = [({k: (_norm(v, spec.cwd) if isinstance(v, str) else v) for k, v in t.items()}
|
| 526 |
+
if isinstance(t, dict) else t) for t in sorted(at, key=lambda t: json.dumps(t))]
|
| 527 |
+
effort = (fp["params"].get("reasoning") or {}).get("effort")
|
| 528 |
+
if effort != ep.effort:
|
| 529 |
+
problems.append(f"reasoning.effort in request {effort!r} != {ep.effort!r}")
|
| 530 |
+
if os.listdir(spec.cwd):
|
| 531 |
+
problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}")
|
| 532 |
+
fp_sha = C.sha256_json(fp)
|
| 533 |
+
out = dict(fingerprint_sha256=fp_sha, developer_chars=fp["developer_chars"], n_requests=len(reqs),
|
| 534 |
+
top_tools=[t["name"] for t in fp["tools"]], all_tools=at_names, code_mode=code_mode,
|
| 535 |
+
catalog=self.catalog, effort_in_request=effort,
|
| 536 |
+
model_in_request=fp["params"].get("model"), sandbox=fp["sandbox"], dt_s=round(time.time() - t0, 1),
|
| 537 |
+
problems=problems)
|
| 538 |
+
pin = pins.load(self.pin_key(ep), self.pins_dir)
|
| 539 |
+
out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"])
|
| 540 |
+
out["fingerprint"] = fp
|
| 541 |
+
if problems:
|
| 542 |
+
raise HarnessRefused("preflight: " + "; ".join(problems))
|
| 543 |
+
if pin is None:
|
| 544 |
+
if not self.allow_unpinned:
|
| 545 |
+
raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck "
|
| 546 |
+
f"with --write-pins after the self-check passes)")
|
| 547 |
+
out["pin_status"] = "unpinned (allowed)"
|
| 548 |
+
elif pin["fingerprint_sha256"] != fp_sha:
|
| 549 |
+
raise HarnessRefused(f"preflight: preset prompt / tools fingerprint {fp_sha[:12]} != pinned "
|
| 550 |
+
f"{pin['fingerprint_sha256'][:12]} ({pin['key']})")
|
| 551 |
+
else:
|
| 552 |
+
out["pin_status"] = "match"
|
| 553 |
+
return out
|
| 554 |
+
finally:
|
| 555 |
+
fake.stop()
|
| 556 |
+
self._sync_auth_back(pre["codex_home"])
|
| 557 |
+
shutil.rmtree(pre["state"], ignore_errors=True)
|
| 558 |
+
|
| 559 |
+
# ------------------------------------------------------------------------------------------------ collect
|
| 560 |
+
def collect(self, h):
|
| 561 |
+
spec, ep = h.spec, h.ep
|
| 562 |
+
tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
|
| 563 |
+
thread, usage, items, errors = None, dict(input=0, cached=0, output=0, reasoning=0), [], []
|
| 564 |
+
for line in open(spec.stdout_path, encoding="utf-8", errors="replace"):
|
| 565 |
+
if not line.startswith("{"):
|
| 566 |
+
continue
|
| 567 |
+
d = json.loads(line)
|
| 568 |
+
t = d.get("type")
|
| 569 |
+
if t == "thread.started":
|
| 570 |
+
thread = d.get("thread_id")
|
| 571 |
+
elif t == "turn.completed":
|
| 572 |
+
u = d.get("usage") or {}
|
| 573 |
+
usage["input"] += u.get("input_tokens") or 0
|
| 574 |
+
usage["cached"] += u.get("cached_input_tokens") or 0
|
| 575 |
+
usage["output"] += u.get("output_tokens") or 0
|
| 576 |
+
usage["reasoning"] += u.get("reasoning_output_tokens") or 0
|
| 577 |
+
elif t in ("error", "turn.failed"):
|
| 578 |
+
errors.append(d)
|
| 579 |
+
elif t == "item.completed":
|
| 580 |
+
it = d.get("item") or {}
|
| 581 |
+
items.append(it.get("type"))
|
| 582 |
+
if it.get("type") == "agent_message":
|
| 583 |
+
tw.add_step("agent", message=it.get("text", ""))
|
| 584 |
+
elif it.get("type") == "reasoning":
|
| 585 |
+
tw.add_step("agent", reasoning=it.get("text", ""))
|
| 586 |
+
else:
|
| 587 |
+
name = it.get("tool") if it.get("type") == "mcp_tool_call" else it.get("type")
|
| 588 |
+
args = it.get("arguments") if it.get("type") == "mcp_tool_call" else {
|
| 589 |
+
k: v for k, v in it.items() if k not in ("id", "type", "status")}
|
| 590 |
+
st = tw.add_step("agent", tool_calls=[dict(tool_call_id=it.get("id"), function_name=name,
|
| 591 |
+
native_name=f"{it.get('server', '')}.{name}"
|
| 592 |
+
if it.get("type") == "mcp_tool_call" else name,
|
| 593 |
+
item_type=it.get("type"), arguments=args)])
|
| 594 |
+
res = it.get("result") or {}
|
| 595 |
+
texts = [c.get("text", "") for c in res.get("content") or [] if c.get("type") == "text"]
|
| 596 |
+
imgs = sum(1 for c in res.get("content") or [] if c.get("type") == "image")
|
| 597 |
+
tw.add_result(it.get("id"), "\n".join(texts) if texts else json.dumps(it.get("error")),
|
| 598 |
+
bool(it.get("error")) or it.get("status") == "failed", imgs)
|
| 599 |
+
del st
|
| 600 |
+
v = self.version()
|
| 601 |
+
tw.set_header(session_id=thread, source=os.path.basename(spec.stdout_path),
|
| 602 |
+
agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort),
|
| 603 |
+
tools=EXPECTED_ALL_TOOLS if (spec.config_files.get("model_catalog_json") or {}).get(
|
| 604 |
+
"code_mode", True) else EXPECTED_TOP_GENERIC)
|
| 605 |
+
tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], item_types=sorted(set(items))),
|
| 606 |
+
total_prompt_tokens=usage["input"], total_completion_tokens=usage["output"],
|
| 607 |
+
total_cached_tokens=usage["cached"], total_cost_usd=None, reasoning_tokens=usage["reasoning"])
|
| 608 |
+
tw.write()
|
| 609 |
+
h.info.update(items=items, traj=tw, thread=thread, errors=errors)
|
| 610 |
+
return tw
|
| 611 |
+
|
| 612 |
+
# ------------------------------------------------------------------------------------------------ audit
|
| 613 |
+
@staticmethod
|
| 614 |
+
def sqlite_rows(path, table):
|
| 615 |
+
"""Row count of `table`, read from a copy (the db may be in WAL mode and still open)."""
|
| 616 |
+
import tempfile
|
| 617 |
+
try:
|
| 618 |
+
with tempfile.TemporaryDirectory() as td:
|
| 619 |
+
for suf in ("", "-wal", "-shm"):
|
| 620 |
+
if os.path.exists(path + suf):
|
| 621 |
+
shutil.copy(path + suf, os.path.join(td, "db.sqlite" + suf))
|
| 622 |
+
con = sqlite3.connect(os.path.join(td, "db.sqlite"))
|
| 623 |
+
n = con.execute(f"select count(*) from {table}").fetchone()[0]
|
| 624 |
+
con.close()
|
| 625 |
+
return n
|
| 626 |
+
except (sqlite3.Error, OSError) as e:
|
| 627 |
+
return f"n/a ({e})"
|
| 628 |
+
|
| 629 |
+
def audit(self, h):
|
| 630 |
+
spec, ep = h.spec, h.ep
|
| 631 |
+
v, notes = [], []
|
| 632 |
+
items = h.info.get("items") or []
|
| 633 |
+
bad = sorted({i for i in items if i not in OK_ITEMS})
|
| 634 |
+
if bad:
|
| 635 |
+
v.append(f"non-MCP items in the event stream: {bad}")
|
| 636 |
+
tw = h.info.get("traj")
|
| 637 |
+
residual = []
|
| 638 |
+
for st in (tw.steps if tw else []):
|
| 639 |
+
for tc in st["tool_calls"]:
|
| 640 |
+
if tc.get("item_type") != "mcp_tool_call":
|
| 641 |
+
continue
|
| 642 |
+
if tc["native_name"].startswith("lff.") and tc["function_name"] in MCP_TOOLS:
|
| 643 |
+
continue
|
| 644 |
+
if tc["function_name"] in ("list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"):
|
| 645 |
+
residual.append(tc["function_name"]) # our server has no resources: always empty
|
| 646 |
+
else:
|
| 647 |
+
v.append(f"unexpected MCP call {tc['native_name']}")
|
| 648 |
+
if residual:
|
| 649 |
+
notes.append(f"residual MCP-resource tool calls (empty, our server has no resources): {residual}")
|
| 650 |
+
if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env):
|
| 651 |
+
v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}")
|
| 652 |
+
ch = spec.state_dirs["codex_home"]
|
| 653 |
+
note = self._sync_auth_back(ch)
|
| 654 |
+
if note:
|
| 655 |
+
notes.append(note)
|
| 656 |
+
left = dict(codex_home=snapshot_tree(ch), home=snapshot_tree(spec.state_dirs["home"]),
|
| 657 |
+
work=snapshot_tree(spec.cwd))
|
| 658 |
+
threads = None
|
| 659 |
+
for f in left["codex_home"]:
|
| 660 |
+
if re.match(r"state_\d+\.sqlite$", f):
|
| 661 |
+
threads = self.sqlite_rows(os.path.join(ch, f), "threads")
|
| 662 |
+
if isinstance(threads, int) and threads > 1:
|
| 663 |
+
v.append(f"{threads} threads persisted in CODEX_HOME (only this run's one is expected)")
|
| 664 |
+
thread = h.info.get("thread")
|
| 665 |
+
sessions = [f for f in left["codex_home"] if f.startswith(("sessions/", "archived_sessions/"))]
|
| 666 |
+
foreign = [f for f in sessions if not (thread and f.startswith("sessions/") and f.endswith(f"-{thread}.jsonl"))]
|
| 667 |
+
if foreign:
|
| 668 |
+
v.append(f"session files other than this run's thread: {foreign}")
|
| 669 |
+
if h.info.get("resumes"):
|
| 670 |
+
notes.append(f"resumed {len(h.info['resumes'])}x with the reference driver's nudge (CLI exited before the "
|
| 671 |
+
f"episode was over)")
|
| 672 |
+
if left["work"]:
|
| 673 |
+
v.append(f"files in the work dir: {left['work']}")
|
| 674 |
+
if (spec.config_files.get("model_catalog_json") or {}).get("code_mode", True):
|
| 675 |
+
notes.append("image forwarding (model calls image()) is not visible in --json; needs the model proxy (P1)")
|
| 676 |
+
mcp_env = None
|
| 677 |
+
mt = os.path.join(ep.log_dir, "mcp_transcript.jsonl")
|
| 678 |
+
if os.path.exists(mt):
|
| 679 |
+
for line in open(mt):
|
| 680 |
+
d = json.loads(line)
|
| 681 |
+
if d.get("ev") == "start" and "env_keys" in d:
|
| 682 |
+
mcp_env = d["env_keys"]
|
| 683 |
+
out = dict(harness=self.name, violations=v, notes=notes, files_left=left, threads_rows=threads,
|
| 684 |
+
mcp_server_env_keys=mcp_env, item_types=sorted(set(items)), errors=h.info.get("errors"), ok=not v)
|
| 685 |
+
with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
|
| 686 |
+
json.dump(out, f, indent=1)
|
| 687 |
+
return out
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-flash_high.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "dsh|0.2.1-rc.5|aa65546cc1f51674|deepseek-flash|high",
|
| 3 |
+
"fingerprint_sha256": "18044f5deb7b4d0d662d620fce120e85e3f94103fa2699346221fa46d093fc8f",
|
| 4 |
+
"written": "2026-10-31 06:05:50",
|
| 5 |
+
"summary": {
|
| 6 |
+
"system_chars": 109,
|
| 7 |
+
"tools": [
|
| 8 |
+
"mcp__lff__robot",
|
| 9 |
+
"mcp__lff__shell",
|
| 10 |
+
"mcp__lff__view_images"
|
| 11 |
+
],
|
| 12 |
+
"effort_in_request": "high",
|
| 13 |
+
"model_in_request": "deepseek-flash"
|
| 14 |
+
}
|
| 15 |
+
}
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-chatgpt-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "sensenova_codex-chatgpt-generic-2c45c1ca7b3b|0.163.0|399ff69c431c066e|gpt-6.1-sol|high",
|
| 3 |
+
"fingerprint_sha256": "4a741aa5b9ff4e51ead5f08944f6bd44f4bfbb79731098fb24d37d32a43fcba9",
|
| 4 |
+
"written": "2026-10-26 07:08:06",
|
| 5 |
+
"summary": {
|
| 6 |
+
"report": "/mnt/cpfs/workspace/agentic-robotics/reports/robot_harness_subscription_resume_20261026/selfcheck_verified/selfcheck.json",
|
| 7 |
+
"checks": 10,
|
| 8 |
+
"framework": {
|
| 9 |
+
"commit": "b513a1c7289ab11eb844856588b64c378705c405",
|
| 10 |
+
"patch_sha256": "70b46c683ddd7e18593c9340da272ffb29d7f60708477aea5eed9f021bc9e823",
|
| 11 |
+
"tree_sha256": "2c45c1ca7b3bf6182adebd373f7ff15bd6db5f0dd583f5c8113a87a88afee350",
|
| 12 |
+
"untracked": [
|
| 13 |
+
"lff_integration/__init__.py",
|
| 14 |
+
"lff_integration/run.py"
|
| 15 |
+
]
|
| 16 |
+
}
|
| 17 |
+
}
|
| 18 |
+
}
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/redteam.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Adversarial acceptance (red-team) runs: an agent told to get "Attempt succeeded." without doing the task.
|
| 2 |
+
|
| 3 |
+
Embodied First Exam merges a benchmark only after such a trial scored 0 on its tasks (PROTOCOL Appendix H.1). Here a
|
| 4 |
+
red-team run is an ordinary native-harness run whose first message starts with RED_TEAM_TEXT; everything else (task,
|
| 5 |
+
instance, tools, budgets, jail, model gateway) is unchanged. harness_run.py --red-team writes the marker file
|
| 6 |
+
red_team.json into the run's log dir before the contract is built, and contract.build_contract adds the key
|
| 7 |
+
"red_team" only for such runs, so their contract_sha256 never equals a normal run's and no table can mix them
|
| 8 |
+
(normal contracts are unchanged). scripts/redteam_report.py lists every success and every flag for a human look: a
|
| 9 |
+
success is either a hole in the success check / the sandbox (fix the task, bump its version) or the agent solving
|
| 10 |
+
the task anyway (legitimate; noted).
|
| 11 |
+
"""
|
| 12 |
+
import hashlib
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
|
| 16 |
+
RED_TEAM_VERSION = "rt1"
|
| 17 |
+
MARKER = "red_team.json"
|
| 18 |
+
RED_TEAM_TEXT = """\
|
| 19 |
+
[ADVERSARIAL ACCEPTANCE TEST - read this first]
|
| 20 |
+
This episode is a red-team test of the benchmark itself, not an evaluation of you. Your goal is to make the \
|
| 21 |
+
environment report "Attempt succeeded." WITHOUT doing the task the way the instructions below intend. Look for any \
|
| 22 |
+
way the success check, the simulator or the tools can be fooled, for example:
|
| 23 |
+
- end states that satisfy the letter of the success condition but not its intent (objects knocked, pushed off \
|
| 24 |
+
supports or wedged so that a measured quantity reads as "done"; partial work that the check counts as complete);
|
| 25 |
+
- physics glitches (objects tunnelling, launching, jittering into place) or moving objects with something other \
|
| 26 |
+
than the intended contact;
|
| 27 |
+
- command or protocol tricks (malformed or extreme arguments, sequences the robot interface does not expect, \
|
| 28 |
+
finishing at an unusual moment);
|
| 29 |
+
- information you are not meant to have (files, environment variables, processes, network ports, logs or source \
|
| 30 |
+
code reachable from the shell; anything that reveals the hidden properties of the scene or the success check).
|
| 31 |
+
Do not damage the machine and do not try to reach the internet. Do everything through the tools you have. Whenever \
|
| 32 |
+
an attempt ends, write what you tried and what happened into the file redteam_notes.md in your workspace. At the \
|
| 33 |
+
end, reply with a report that starts with "RED-TEAM REPORT:" and lists every trick you tried, whether the \
|
| 34 |
+
environment reported success for it, and anything you found that a benchmark maintainer should fix. If you solve \
|
| 35 |
+
the task in the ordinary way, say so explicitly: that is not a finding.
|
| 36 |
+
[END OF TEST NOTICE - the ordinary instructions of the episode follow]
|
| 37 |
+
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def text_sha256():
|
| 42 |
+
return hashlib.sha256(RED_TEAM_TEXT.encode("utf-8")).hexdigest()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def mark(log_dir):
|
| 46 |
+
"""Write the marker before contract.write_contract runs."""
|
| 47 |
+
with open(os.path.join(log_dir, MARKER), "w") as f:
|
| 48 |
+
json.dump(dict(version=RED_TEAM_VERSION, text_sha256=text_sha256()), f)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def marker(log_dir):
|
| 52 |
+
try:
|
| 53 |
+
return json.load(open(os.path.join(log_dir, MARKER)))
|
| 54 |
+
except (OSError, ValueError):
|
| 55 |
+
return None
|
| 56 |
+
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L5-A slide_to_target: strike the cube so that it slides on its own and comes to rest inside the target zone.
|
| 2 |
+
|
| 3 |
+
Hidden variable: cube-table sliding friction mu (log-uniform in [0.035, 0.10]) -- the cube looks the
|
| 4 |
+
same for every mu. With the default push speed the cube overshoots on slippery instances and stops
|
| 5 |
+
short on grippy ones; the only way to get it right is to infer from where the cube stopped how hard
|
| 6 |
+
to push next time (cf. MemMimic push_cube, iterative pushing).
|
| 7 |
+
|
| 8 |
+
Strikes per attempt: not limited (2026-10-19, user). From 2026-10-08 the instruction allowed ONE strike per attempt
|
| 9 |
+
(one move command pushing the cube, the gripper advancing at most 4 cm after the first touch), to stop slow pushes that
|
| 10 |
+
carry the cube to the target so that friction never matters (exp1 / cla1 Claude, la2 GPT: 0.05 m/s pushes). That rule
|
| 11 |
+
also moved within-attempt correction (overshot -> fetch the cube back -> strike again) to the next attempt. The
|
| 12 |
+
loophole is now closed by the success rule instead:
|
| 13 |
+
|
| 14 |
+
Success: when the attempt ends the cube is at rest, on the table, in the square (see "Target" below), AND it got there
|
| 15 |
+
by a free slide of at least D_MIN: from the last moment the robot touched it (any robot or gripper geom, contacts
|
| 16 |
+
checked at every 2 ms physics substep; holding it counts as touching) to its final position the cube slid >= D_MIN with
|
| 17 |
+
nothing touching it. A touch that leaves a resting cube where it was (< 1 mm) is ignored. This fails a quasi-static push
|
| 18 |
+
into the square (free slide 0-1.2 cm measured), placing the cube there with the gripper (0 cm) and putting it just in
|
| 19 |
+
front of the square and tapping it (< D_MIN); see the task card for the adversarial checks and why D_MIN = 3 cm.
|
| 20 |
+
|
| 21 |
+
Error events: every strike (a robot contact that moved the cube followed by a free slide of >= STRIKE_MIN) is logged
|
| 22 |
+
when the cube comes to rest; it is "missed" if the cube then lies outside the square (past / short / beside).
|
| 23 |
+
`n_missed_strikes`, `trap_fired` (>= 1 missed strike) and `recovered_in_attempt` (trap fired and the attempt then
|
| 24 |
+
succeeded) are in the outcome, as in l7_key_turn; `irrecoverable` = the cube fell off the table or lies outside the
|
| 25 |
+
arm's reach (the attempt is not ended for it).
|
| 26 |
+
|
| 27 |
+
Observation fix (2026-10-19): a strike used to return while the cube was still sliding, and `observe` does not advance
|
| 28 |
+
the simulation, so agents saw the cube half-way (cla2: "2.2 cm short", it then slid to 7.0 cm past the centre).
|
| 29 |
+
SlideSkills.move_to / set_gripper now hold the arm still after the motion until the cube is at rest (or WAIT_MAX),
|
| 30 |
+
so every reply and image shows the cube where it stopped. The waiting time counts as simulated motion time.
|
| 31 |
+
|
| 32 |
+
Target (2026-10-19, user; before: completely inside the square on all four sides, centre within +-1 cm): the agentview
|
| 33 |
+
camera looks at the square from the far side (the cube is pushed towards it), and a cube that sticks out past the far
|
| 34 |
+
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
|
| 35 |
+
"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
|
| 36 |
+
the far green line: the instruction says it must not stick out beyond that line; judged, its centre may be up to
|
| 37 |
+
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
|
| 38 |
+
of 25 measured instances shows >= 2 px of red beyond the line (task card). The near side and the sides stay "completely
|
| 39 |
+
inside" (+-1 cm): the near-side band cannot be made visible in the agentview by any tolerance (the cube's own body hides
|
| 40 |
+
the near line), and relaxing it would let the 0.30 m/s strike pass on short-stopping instances (task card).
|
| 41 |
+
"""
|
| 42 |
+
import numpy as np
|
| 43 |
+
|
| 44 |
+
from .. import envs
|
| 45 |
+
from ..bddl import write_bddl
|
| 46 |
+
from ..objects import _fmt, _wrap, box_xml, register_generated
|
| 47 |
+
from ..skills import DT, Skills, _rot_err
|
| 48 |
+
from ..task_base import LFFTask, register_task
|
| 49 |
+
|
| 50 |
+
CUBE = "cube_1"
|
| 51 |
+
CUBE_HALF = 0.02
|
| 52 |
+
D_MIN = 0.03 # the cube's last free slide (after its last contact with the robot) must be at least this long
|
| 53 |
+
STRIKE_MIN = 0.01 # a contact that moved the cube, followed by a free slide of >= 1 cm, counts as a strike
|
| 54 |
+
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
|
| 55 |
+
EP_GAP = 25 # physics substeps (one control step, 50 ms) without robot contact end a contact episode
|
| 56 |
+
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 ...
|
| 57 |
+
REST_SUB = 25 # ... for 25 consecutive substeps (50 ms)
|
| 58 |
+
WAIT_MAX = 100 # control steps (5 s) a command may hold the arm waiting for the cube to come to rest
|
| 59 |
+
ON_TABLE = 0.005 # cube resting on the table: centre within 5 mm of TABLE_Z + CUBE_HALF
|
| 60 |
+
OFF_TABLE_Z = envs.TABLE_Z - 0.05 # cube centre below this: it fell off the table
|
| 61 |
+
REACH_MARGIN = 0.03 # cube centre this close to the commanded-target limits (agent/tools.py WS_LO / WS_HI): unreachable
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class CubeWatch:
|
| 65 |
+
"""Follows the cube at every physics substep (installed on env.sim by reset_instance; outcome() reads it).
|
| 66 |
+
|
| 67 |
+
contact episode: substeps with a robot-cube contact, merged across gaps shorter than EP_GAP substeps. Closed
|
| 68 |
+
EP_GAP substeps after its last contact; it "moved" the cube if the cube is then >= TOUCH_MOVE from where it was
|
| 69 |
+
when the episode began, or still moving.
|
| 70 |
+
release: the cube's xy at the last contact of the last episode that moved it, i.e. where its current free slide
|
| 71 |
+
began (None while the robot has never moved the cube).
|
| 72 |
+
strike: an episode that moved the cube followed by a free slide of >= STRIKE_MIN, logged when the cube comes to
|
| 73 |
+
rest (or when the robot touches it again before that: result "interrupted")."""
|
| 74 |
+
|
| 75 |
+
def __init__(self, env, target_xy, tol_short, tol_past, tol_across):
|
| 76 |
+
m = env.sim.model
|
| 77 |
+
self.env = env
|
| 78 |
+
self.is_robot = np.zeros(m.ngeom, bool)
|
| 79 |
+
self.is_robot[envs.robot_geom_ids(env)] = True
|
| 80 |
+
self.is_cube = np.zeros(m.ngeom, bool)
|
| 81 |
+
self.is_cube[envs.obj_geom_ids(env, CUBE)] = True
|
| 82 |
+
self.qa, self.da = envs.free_joint_addr(env, CUBE)
|
| 83 |
+
self.target = np.asarray(target_xy, float)
|
| 84 |
+
self.tol = (float(tol_short), float(tol_past), float(tol_across)) # centre offsets: short of / past / beside
|
| 85 |
+
self.n_sub = 0
|
| 86 |
+
self.ep = None # open contact episode
|
| 87 |
+
self.gap = 0
|
| 88 |
+
self.quiet = 0 # consecutive substeps at rest
|
| 89 |
+
self.release = None
|
| 90 |
+
self.slide = None # free slide in progress: where it started (cube at the episode start) and was released
|
| 91 |
+
self.moves = [] # closed contact episodes that moved the cube
|
| 92 |
+
self.strikes = []
|
| 93 |
+
|
| 94 |
+
# ------------------------------------------------------------ state
|
| 95 |
+
def pos(self):
|
| 96 |
+
return self.env.sim.data.qpos[self.qa:self.qa + 3].copy()
|
| 97 |
+
|
| 98 |
+
def at_rest(self):
|
| 99 |
+
qv = self.env.sim.data.qvel[self.da:self.da + 6]
|
| 100 |
+
return bool(np.linalg.norm(qv[:3]) < V_REST and np.linalg.norm(qv[3:]) < W_REST)
|
| 101 |
+
|
| 102 |
+
def judge(self, p):
|
| 103 |
+
"""Where a cube at p lies relative to the square: (along, across, in / past / short / beside / off).
|
| 104 |
+
in = centre at most tol_short short of / tol_past past the square's centre and within tol_across beside it."""
|
| 105 |
+
along, across = float(p[0] - self.target[0]), float(p[1] - self.target[1])
|
| 106 |
+
if abs(p[2] - (envs.TABLE_Z + CUBE_HALF)) > ON_TABLE:
|
| 107 |
+
return along, across, "off"
|
| 108 |
+
short, past, beside = self.tol
|
| 109 |
+
if -short <= along <= past and abs(across) <= beside:
|
| 110 |
+
return along, across, "in"
|
| 111 |
+
if along > past:
|
| 112 |
+
return along, across, "past"
|
| 113 |
+
if along < -short:
|
| 114 |
+
return along, across, "short"
|
| 115 |
+
return along, across, "beside"
|
| 116 |
+
|
| 117 |
+
# ------------------------------------------------------------ per substep
|
| 118 |
+
def substep(self):
|
| 119 |
+
d = self.env.sim.data
|
| 120 |
+
n = d.ncon
|
| 121 |
+
touch = False
|
| 122 |
+
if n:
|
| 123 |
+
g1 = np.asarray(d.contact.geom1)[:n]
|
| 124 |
+
g2 = np.asarray(d.contact.geom2)[:n]
|
| 125 |
+
touch = bool(np.any((self.is_robot[g1] & self.is_cube[g2]) | (self.is_robot[g2] & self.is_cube[g1])))
|
| 126 |
+
self.n_sub += 1
|
| 127 |
+
p = self.pos()
|
| 128 |
+
rest = self.at_rest()
|
| 129 |
+
self.quiet = self.quiet + 1 if rest else 0
|
| 130 |
+
if touch:
|
| 131 |
+
if self.ep is None:
|
| 132 |
+
if self.slide is not None:
|
| 133 |
+
self._end_slide(p, interrupted=not rest)
|
| 134 |
+
self.ep = dict(start=p, sub0=self.n_sub)
|
| 135 |
+
self.ep["last"] = p
|
| 136 |
+
self.ep["sub1"] = self.n_sub
|
| 137 |
+
self.gap = 0
|
| 138 |
+
elif self.ep is not None:
|
| 139 |
+
self.gap += 1
|
| 140 |
+
if self.gap >= EP_GAP:
|
| 141 |
+
self._close(p, rest)
|
| 142 |
+
if self.ep is None and self.slide is not None and self.quiet >= REST_SUB:
|
| 143 |
+
self._end_slide(p, interrupted=False)
|
| 144 |
+
|
| 145 |
+
def _close(self, p, rest):
|
| 146 |
+
ep, self.ep = self.ep, None
|
| 147 |
+
if np.linalg.norm(p - ep["start"]) < TOUCH_MOVE and rest:
|
| 148 |
+
return # touched a resting cube and left it where it was
|
| 149 |
+
self.release = ep["last"][:2].copy()
|
| 150 |
+
self.moves.append(dict(sub0=ep["sub0"], sub1=ep["sub1"], start=ep["start"].round(4).tolist(),
|
| 151 |
+
release=ep["last"].round(4).tolist()))
|
| 152 |
+
self.slide = dict(start=ep["start"], release=ep["last"], sub=ep["sub1"])
|
| 153 |
+
|
| 154 |
+
def _end_slide(self, p, interrupted):
|
| 155 |
+
s, self.slide = self.slide, None
|
| 156 |
+
free = float(np.linalg.norm(p[:2] - s["release"][:2]))
|
| 157 |
+
if free < STRIKE_MIN:
|
| 158 |
+
return # a push or a put-down, not a strike
|
| 159 |
+
along, across, res = self.judge(p)
|
| 160 |
+
self.strikes.append(dict(sub=int(s["sub"]), start=s["start"].round(4).tolist(),
|
| 161 |
+
release=s["release"].round(4).tolist(), rest=p.round(4).tolist(),
|
| 162 |
+
pushed_cm=round(100 * float(np.linalg.norm(s["release"][:2] - s["start"][:2])), 2),
|
| 163 |
+
free_slide_cm=round(100 * free, 2), along_err_cm=round(100 * along, 2),
|
| 164 |
+
across_err_cm=round(100 * across, 2),
|
| 165 |
+
result="interrupted" if interrupted else res,
|
| 166 |
+
missed=bool(not interrupted and res != "in")))
|
| 167 |
+
|
| 168 |
+
def flush(self):
|
| 169 |
+
"""End of attempt: settle the bookkeeping. Returns True if the robot is touching the cube now and that contact
|
| 170 |
+
has moved it (then the cube's current free slide is 0)."""
|
| 171 |
+
p = self.pos()
|
| 172 |
+
if self.ep is not None:
|
| 173 |
+
if np.linalg.norm(p - self.ep["start"]) >= TOUCH_MOVE or not self.at_rest():
|
| 174 |
+
self.release = p[:2].copy()
|
| 175 |
+
self.slide = None
|
| 176 |
+
return True
|
| 177 |
+
return False
|
| 178 |
+
if self.slide is not None and self.at_rest():
|
| 179 |
+
self._end_slide(p, interrupted=False)
|
| 180 |
+
return False
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def _install_watch(sim, watch):
|
| 184 |
+
"""Call watch.substep() after every MuJoCo step of this sim (one wrapper per sim, like agent/tools.ContactTracker;
|
| 185 |
+
it only reads the state). A fast strike touches the cube for 3-16 substeps (6-32 ms, measured), less than one
|
| 186 |
+
control step, so contact checks at control steps alone would miss it."""
|
| 187 |
+
if not getattr(sim, "_lff_slide_wrapped", False):
|
| 188 |
+
orig = sim.step
|
| 189 |
+
|
| 190 |
+
def step(*a, **k):
|
| 191 |
+
orig(*a, **k)
|
| 192 |
+
w = getattr(sim, "_lff_slide_watch", None)
|
| 193 |
+
if w is not None:
|
| 194 |
+
w.substep()
|
| 195 |
+
sim.step = step
|
| 196 |
+
sim._lff_slide_wrapped = True
|
| 197 |
+
sim._lff_slide_watch = watch
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class SlideSkills(Skills):
|
| 201 |
+
"""Skills whose motion commands return only once the cube has come to rest (see the module docstring)."""
|
| 202 |
+
|
| 203 |
+
def __init__(self, env, bias=None, recorder=None):
|
| 204 |
+
super().__init__(env, bias=bias, recorder=recorder)
|
| 205 |
+
self._qa, self._da = envs.free_joint_addr(env, CUBE)
|
| 206 |
+
self.waits = [] # (control step, steps waited) for every command that had to wait
|
| 207 |
+
|
| 208 |
+
def cube_moving(self):
|
| 209 |
+
qv = self.env.sim.data.qvel[self._da:self._da + 6]
|
| 210 |
+
return bool(np.linalg.norm(qv[:3]) >= V_REST or np.linalg.norm(qv[3:]) >= W_REST)
|
| 211 |
+
|
| 212 |
+
def wait_cube_rest(self):
|
| 213 |
+
"""Hold the arm where it is until the cube is at rest (two control steps in a row) or WAIT_MAX steps passed.
|
| 214 |
+
No wait if the cube is already at rest or is held (it then moves with the arm)."""
|
| 215 |
+
if not self.cube_moving() or self.holding(CUBE):
|
| 216 |
+
return 0
|
| 217 |
+
p, R = self.eef_pos(), self._R()
|
| 218 |
+
quiet = 0
|
| 219 |
+
for k in range(WAIT_MAX):
|
| 220 |
+
self._act(p - self.eef_pos(), _rot_err(R, self.eef_mat()), self.grip)
|
| 221 |
+
quiet = 0 if self.cube_moving() else quiet + 1
|
| 222 |
+
if quiet >= 2:
|
| 223 |
+
break
|
| 224 |
+
self.waits.append((self.n_steps, k + 1))
|
| 225 |
+
return k + 1
|
| 226 |
+
|
| 227 |
+
def move_to(self, target, *args, **kwargs):
|
| 228 |
+
rep = super().move_to(target, *args, **kwargs)
|
| 229 |
+
n = self.wait_cube_rest()
|
| 230 |
+
if n:
|
| 231 |
+
rep["waited_s"] = round(n * DT, 2)
|
| 232 |
+
return rep
|
| 233 |
+
|
| 234 |
+
def set_gripper(self, close, steps=15):
|
| 235 |
+
rep = super().set_gripper(close, steps)
|
| 236 |
+
n = self.wait_cube_rest()
|
| 237 |
+
if n:
|
| 238 |
+
rep["waited_s"] = round(n * DT, 2)
|
| 239 |
+
return rep
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
INNER_HALF = 0.03 # 6 cm square target (inner edge of the outline): near side and sides, the cube's centre within 1 cm
|
| 243 |
+
LINE_W = 0.006
|
| 244 |
+
# Far side (away from the robot, facing the agentview camera): the cube may lie on the far line. Instruction: no part of
|
| 245 |
+
# it beyond the line's outer edge (centre <= INNER_HALF + LINE_W - CUBE_HALF = 1.6 cm past the centre); judged: centre
|
| 246 |
+
# <= 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
|
| 247 |
+
# beyond the line (from 2.0 cm on >= 2 px on all 25 measured instances, task card 2026-10-19).
|
| 248 |
+
TOL_PAST = 0.020
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def square_frame_xml(model_name, inner_half=INNER_HALF, line_w=LINE_W,
|
| 252 |
+
line_rgba=(0.1, 0.55, 0.15, 1.0), fill_rgba=(0.75, 0.92, 0.75, 1.0)):
|
| 253 |
+
"""Flat, visual-only square drawn on the table: a light fill plus a dark outline (no collisions)."""
|
| 254 |
+
o = inner_half + line_w
|
| 255 |
+
parts = [((0, 0, 0.0004), (o, o, 0.0004), fill_rgba),
|
| 256 |
+
((0, inner_half + line_w / 2, 0.0010), (o, line_w / 2, 0.0002), line_rgba),
|
| 257 |
+
((0, -inner_half - line_w / 2, 0.0010), (o, line_w / 2, 0.0002), line_rgba),
|
| 258 |
+
((inner_half + line_w / 2, 0, 0.0010), (line_w / 2, o, 0.0002), line_rgba),
|
| 259 |
+
((-inner_half - line_w / 2, 0, 0.0010), (line_w / 2, o, 0.0002), line_rgba)]
|
| 260 |
+
g = "\n".join(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(c)}" '
|
| 261 |
+
f'contype="0" conaffinity="0" group="1" />' for p, sz, c in parts)
|
| 262 |
+
return _wrap(model_name, g, 0.0012, o)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
Z_PUSH = envs.TABLE_Z + 0.02
|
| 266 |
+
V_MIN, V_MAX = 0.12, 0.60
|
| 267 |
+
Z_GRASP = envs.TABLE_Z + CUBE_HALF # grasp point at the cube's centre height (fingertips ~1 cm above the table)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
@register_task
|
| 271 |
+
class SlideToTarget(LFFTask):
|
| 272 |
+
name = "l5_slide_to_target"
|
| 273 |
+
level = "L5"
|
| 274 |
+
category = "dynamics_adaptation"
|
| 275 |
+
capabilities = ("Reason", "Utilize")
|
| 276 |
+
# no parentheses or semicolons: the instruction is also the BDDL :language string (';' starts a comment there)
|
| 277 |
+
instruction = ("Push the red cube straight away from the robot so that it slides and comes to rest in the green "
|
| 278 |
+
"square marked on the table. On the side of the square nearest the robot and on its left and "
|
| 279 |
+
"right, no part of the cube may lie on or beyond the green border line. On the far side, away from "
|
| 280 |
+
"the robot, the cube may lie on the border line, but no part of it may stick out beyond that line. "
|
| 281 |
+
"The cube must slide the last part of the way on its own: after it leaves the gripper it has to "
|
| 282 |
+
f"slide at least {100 * D_MIN:.0f} cm, with nothing touching it, before it comes to rest in the "
|
| 283 |
+
"square.")
|
| 284 |
+
instruction_indirect = instruction
|
| 285 |
+
tol_along = INNER_HALF - CUBE_HALF # short of the centre (near side): completely inside the square (1.0 cm)
|
| 286 |
+
tol_past = TOL_PAST # past the centre (far side): may lie on the far line (2.0 cm, see TOL_PAST)
|
| 287 |
+
runup = 0.22 # long run-up so the gripper reaches the commanded speed before contact
|
| 288 |
+
tol_across = INNER_HALF - CUBE_HALF
|
| 289 |
+
|
| 290 |
+
def make_bddl(self):
|
| 291 |
+
cube = register_generated("LffRedCube", box_xml("lff_red_cube", (CUBE_HALF,) * 3, (0.85, 0.15, 0.15, 1),
|
| 292 |
+
density=1000))
|
| 293 |
+
# static fixture (no joint): a free body without collisions would fall through the table
|
| 294 |
+
zone = register_generated("LffTargetSquare", square_frame_xml("lff_target_square"), free=False)
|
| 295 |
+
objs = [("cube_1", cube, "cube_region", (-0.21, -0.01, -0.19, 0.01))]
|
| 296 |
+
fixtures = [("zone_1", zone, "zone_region", (-0.11, -0.01, -0.09, 0.01))]
|
| 297 |
+
return write_bddl(self.name, self.instruction, objs, fixtures=fixtures)
|
| 298 |
+
|
| 299 |
+
def apply_instance(self, inst):
|
| 300 |
+
m = self.env.sim.model
|
| 301 |
+
zone = self.env.fixtures_dict["zone_1"]
|
| 302 |
+
# the target zone is a flat marker: no collisions
|
| 303 |
+
for g in range(m.ngeom):
|
| 304 |
+
if (m.geom_id2name(g) or "").startswith("zone_1_"):
|
| 305 |
+
m.geom_contype[g] = 0
|
| 306 |
+
m.geom_conaffinity[g] = 0
|
| 307 |
+
x0, y0 = inst["cube_xy"]
|
| 308 |
+
envs.set_obj_pose(self.env, "cube_1", [x0, y0, envs.TABLE_Z + CUBE_HALF + 0.001])
|
| 309 |
+
bid = m.body_name2id(zone.root_body)
|
| 310 |
+
m.body_pos[bid] = [x0 + inst["target_dist"], y0, envs.TABLE_Z + 0.0002]
|
| 311 |
+
m.body_quat[bid] = [1.0, 0.0, 0.0, 0.0]
|
| 312 |
+
envs.set_friction(self.env, "cube_1", inst["mu"])
|
| 313 |
+
|
| 314 |
+
def reset_instance(self, inst, recorder=None):
|
| 315 |
+
self.env.reset()
|
| 316 |
+
self.apply_instance(inst)
|
| 317 |
+
self.env.sim.forward()
|
| 318 |
+
envs.settle(self.env, 10)
|
| 319 |
+
x0, y0 = inst["cube_xy"]
|
| 320 |
+
self.watch = CubeWatch(self.env, (x0 + inst["target_dist"], y0), self.tol_along, self.tol_past,
|
| 321 |
+
self.tol_across)
|
| 322 |
+
_install_watch(self.env.sim, self.watch)
|
| 323 |
+
self.sk = SlideSkills(self.env, recorder=recorder)
|
| 324 |
+
return self.sk
|
| 325 |
+
|
| 326 |
+
@staticmethod
|
| 327 |
+
def max_reach(mu):
|
| 328 |
+
"""Approximate slide distance at the top speed, fitted to a sweep (runup 0.22 m):
|
| 329 |
+
mu 0.04 -> 20.8 cm, 0.06 -> 14.8, 0.08 -> 11.8, 0.10 -> 10.1 cm."""
|
| 330 |
+
return 0.0103 / mu ** 0.95
|
| 331 |
+
|
| 332 |
+
def sample_instance(self, seed):
|
| 333 |
+
rng = np.random.default_rng(seed)
|
| 334 |
+
while True: # reject instances the top speed cannot reach (keeps every instance solvable)
|
| 335 |
+
inst = dict(seed=int(seed),
|
| 336 |
+
cube_xy=[float(rng.uniform(-0.23, -0.17)), float(rng.uniform(-0.10, 0.10))],
|
| 337 |
+
target_dist=float(rng.uniform(0.05, 0.12)),
|
| 338 |
+
mu=float(np.exp(rng.uniform(np.log(0.035), np.log(0.10)))))
|
| 339 |
+
if inst["target_dist"] <= 0.85 * self.max_reach(inst["mu"]):
|
| 340 |
+
return inst
|
| 341 |
+
|
| 342 |
+
# ------------------------------------------------------------ outcome
|
| 343 |
+
def outcome(self, inst):
|
| 344 |
+
envs.settle(self.env, 40)
|
| 345 |
+
w = self.watch
|
| 346 |
+
for _ in range(12): # still moving (e.g. a budget ended the attempt mid-slide): let it come to rest
|
| 347 |
+
if w.at_rest():
|
| 348 |
+
break
|
| 349 |
+
envs.settle(self.env, 5)
|
| 350 |
+
touching = w.flush()
|
| 351 |
+
x0, y0 = inst["cube_xy"]
|
| 352 |
+
c = envs.obj_pos(self.env, CUBE)
|
| 353 |
+
along = (c[0] - x0) - inst["target_dist"]
|
| 354 |
+
across = c[1] - y0
|
| 355 |
+
_, _, where = w.judge(w.pos())
|
| 356 |
+
inside = where == "in"
|
| 357 |
+
at_rest = w.at_rest()
|
| 358 |
+
free = float(np.linalg.norm(c[:2] - w.release)) if w.release is not None else 0.0
|
| 359 |
+
slid = bool(w.release is not None and not touching and free >= D_MIN)
|
| 360 |
+
success = bool(inside and at_rest and slid)
|
| 361 |
+
strikes = w.strikes
|
| 362 |
+
n_missed = sum(s["missed"] for s in strikes)
|
| 363 |
+
from ..agent.tools import WS_HI, WS_LO
|
| 364 |
+
reach = bool(np.all(c[:2] >= WS_LO[:2] + REACH_MARGIN) and np.all(c[:2] <= WS_HI[:2] - REACH_MARGIN))
|
| 365 |
+
irrecoverable = bool(c[2] < OFF_TABLE_Z or not reach)
|
| 366 |
+
|
| 367 |
+
parts = []
|
| 368 |
+
if w.release is None and np.linalg.norm(c[:2] - np.asarray(inst["cube_xy"])) < STRIKE_MIN:
|
| 369 |
+
parts.append("The cube was not pushed.")
|
| 370 |
+
if c[2] < OFF_TABLE_Z:
|
| 371 |
+
parts.append("The cube fell off the table.")
|
| 372 |
+
else:
|
| 373 |
+
state = {"in": "in the square", "past": "it sticks out beyond the far green line",
|
| 374 |
+
"short": "it sticks out past the edge of the square nearest the robot"}.get(where,
|
| 375 |
+
"not in the square")
|
| 376 |
+
if along > 0:
|
| 377 |
+
parts.append(f"The cube stopped {100 * along:.1f} cm past the centre of the green square ({state}).")
|
| 378 |
+
else:
|
| 379 |
+
parts.append(f"The cube stopped {100 * -along:.1f} cm short of the centre of the green square "
|
| 380 |
+
f"({state}).")
|
| 381 |
+
if abs(across) > self.tol_across:
|
| 382 |
+
parts.append(f"It also drifted {100 * abs(across):.1f} cm to the {'left' if across > 0 else 'right'} "
|
| 383 |
+
f"(robot's view).")
|
| 384 |
+
if where == "off" and c[2] > OFF_TABLE_Z:
|
| 385 |
+
parts.append("It is not resting on the table.")
|
| 386 |
+
if inside and not at_rest:
|
| 387 |
+
parts.append("It was still moving when the attempt ended.")
|
| 388 |
+
if touching:
|
| 389 |
+
parts.append("The gripper was still touching (or holding) the cube when the attempt ended.")
|
| 390 |
+
elif inside and w.release is not None and free < D_MIN:
|
| 391 |
+
parts.append(f"After it last left the gripper it slid only {100 * free:.1f} cm on its own; it has to slide "
|
| 392 |
+
f"at least {100 * D_MIN:.0f} cm.")
|
| 393 |
+
if success:
|
| 394 |
+
failure = None
|
| 395 |
+
elif w.release is None and not inside:
|
| 396 |
+
failure = "not_touched"
|
| 397 |
+
elif not inside:
|
| 398 |
+
failure = "position"
|
| 399 |
+
elif not at_rest:
|
| 400 |
+
failure = "not_at_rest"
|
| 401 |
+
else:
|
| 402 |
+
failure = "slide_too_short"
|
| 403 |
+
out = dict(success=success, along_err=float(along), across_err=float(across), detail=" ".join(parts),
|
| 404 |
+
inside=inside, at_rest=at_rest, free_slide_cm=round(100 * free, 2),
|
| 405 |
+
release_xy=None if w.release is None else w.release.round(4).tolist(),
|
| 406 |
+
touching_at_end=bool(touching), n_moves=len(w.moves), n_strikes=len(strikes),
|
| 407 |
+
n_missed_strikes=int(n_missed), trap_fired=n_missed > 0,
|
| 408 |
+
recovered_in_attempt=bool(n_missed and success), irrecoverable=irrecoverable,
|
| 409 |
+
strikes=strikes, waits=len(getattr(self.sk, "waits", [])), failure=failure)
|
| 410 |
+
return out
|
| 411 |
+
|
| 412 |
+
# ------------------------------------------------------------ execution
|
| 413 |
+
def execute(self, inst, params):
|
| 414 |
+
"""One straight strike from the cube's initial position: closed gripper, 22 cm run-up, stop 1.5 cm past the
|
| 415 |
+
point of contact, lift (the move returns once the cube has come to rest)."""
|
| 416 |
+
x0, y0 = inst["cube_xy"]
|
| 417 |
+
sk = self.sk
|
| 418 |
+
sk.set_gripper(True, steps=5)
|
| 419 |
+
sk.move_to([x0 - self.runup, y0, Z_PUSH + 0.10], yaw=0.0)
|
| 420 |
+
sk.move_to([x0 - self.runup, y0, Z_PUSH], tol=0.003)
|
| 421 |
+
sk.move_to([x0 - CUBE_HALF + 0.015, y0, Z_PUSH], speed=float(np.clip(params["speed"], V_MIN, V_MAX)),
|
| 422 |
+
tol=0.01, max_steps=80)
|
| 423 |
+
sk.move_to([x0 - CUBE_HALF + 0.015, y0, Z_PUSH + 0.08], speed=0.3)
|
| 424 |
+
|
| 425 |
+
def default_params(self, inst):
|
| 426 |
+
return dict(speed=0.30)
|
| 427 |
+
|
| 428 |
+
def blind_params(self, inst, attempt, rng):
|
| 429 |
+
return dict(speed=float(np.clip(0.30 + rng.normal(0, 0.05), V_MIN, V_MAX)))
|
| 430 |
+
|
| 431 |
+
def adapt_params(self, inst, history):
|
| 432 |
+
"""Cross-attempt learner (one strike per attempt; used by the scripted agent backend): bracketing secant search
|
| 433 |
+
on speed using the signed stopping error. validate.py's adaptive policy is run_scripted (within the attempt)."""
|
| 434 |
+
pts = sorted((h["params"]["speed"], h["outcome"]["along_err"]) for h in history)
|
| 435 |
+
lo = [p for p in pts if p[1] < 0]
|
| 436 |
+
hi = [p for p in pts if p[1] > 0]
|
| 437 |
+
if lo and hi:
|
| 438 |
+
(v0, e0), (v1, e1) = max(lo, key=lambda p: p[0]), min(hi, key=lambda p: p[0])
|
| 439 |
+
v = v0 + (v1 - v0) * (-e0) / (e1 - e0)
|
| 440 |
+
elif hi: # always overshooting: slow down
|
| 441 |
+
v = min(p[0] for p in hi) * 0.7
|
| 442 |
+
else: # always short: speed up
|
| 443 |
+
v = max(p[0] for p in lo) * 1.35
|
| 444 |
+
return dict(speed=float(np.clip(v, V_MIN, V_MAX)))
|
| 445 |
+
|
| 446 |
+
def oracle_params(self, inst):
|
| 447 |
+
"""Privileged: bisection on speed by simulating pushes (uses the true mu)."""
|
| 448 |
+
if "_oracle_speed" in inst:
|
| 449 |
+
return dict(speed=inst["_oracle_speed"])
|
| 450 |
+
lo, hi = V_MIN, V_MAX
|
| 451 |
+
best = None
|
| 452 |
+
for _ in range(9):
|
| 453 |
+
mid = 0.5 * (lo + hi)
|
| 454 |
+
self.reset_instance(inst)
|
| 455 |
+
self.execute(inst, dict(speed=mid))
|
| 456 |
+
e = self.outcome(inst)["along_err"]
|
| 457 |
+
if best is None or abs(e) < abs(best[1]):
|
| 458 |
+
best = (mid, e)
|
| 459 |
+
if e > 0:
|
| 460 |
+
hi = mid
|
| 461 |
+
else:
|
| 462 |
+
lo = mid
|
| 463 |
+
inst["_oracle_speed"] = best[0]
|
| 464 |
+
self.reset_instance(inst)
|
| 465 |
+
return dict(speed=best[0])
|
| 466 |
+
|
| 467 |
+
# ------------------------------------------------------------ scripted within-attempt correction
|
| 468 |
+
AGENT_CMDS = 40 # robot_server default per-attempt budget (no agent_max_steps here): 40 commands ...
|
| 469 |
+
AGENT_SIM_S = 3.0 * AGENT_CMDS # ... and 3 s of simulated motion per command
|
| 470 |
+
RESTRIKE_MARGIN = 0.02 # strike again from where the cube stopped only if it is >= D_MIN + this short
|
| 471 |
+
|
| 472 |
+
def _strike_here(self, speed):
|
| 473 |
+
"""Strike the cube where it lies (perfect perception), straight towards +x. 4 agent commands: above the run-up
|
| 474 |
+
point + close, down, strike (returns at rest), lift."""
|
| 475 |
+
c = envs.obj_pos(self.env, CUBE)
|
| 476 |
+
sk = self.sk
|
| 477 |
+
sk.move_to([c[0] - self.runup, c[1], Z_PUSH + 0.10], yaw=0.0)
|
| 478 |
+
sk.set_gripper(True, steps=5)
|
| 479 |
+
sk.move_to([c[0] - self.runup, c[1], Z_PUSH], tol=0.003)
|
| 480 |
+
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,
|
| 481 |
+
max_steps=80)
|
| 482 |
+
sk.move_to([c[0] - CUBE_HALF + 0.015, c[1], Z_PUSH + 0.08], speed=0.3)
|
| 483 |
+
return 4
|
| 484 |
+
|
| 485 |
+
def _carry_back(self, inst):
|
| 486 |
+
"""Grasp the cube from above, carry it back to its initial position and put it down. 6 agent commands:
|
| 487 |
+
above it + open, down + close, lift, carry, down + open, lift."""
|
| 488 |
+
c = envs.obj_pos(self.env, CUBE)
|
| 489 |
+
x0, y0 = inst["cube_xy"]
|
| 490 |
+
sk = self.sk
|
| 491 |
+
sk.move_to([c[0], c[1], Z_GRASP + 0.10], yaw=0.0)
|
| 492 |
+
sk.set_gripper(False, steps=10)
|
| 493 |
+
sk.move_to([c[0], c[1], Z_GRASP], tol=0.003)
|
| 494 |
+
sk.set_gripper(True, steps=15)
|
| 495 |
+
sk.move_to([c[0], c[1], Z_GRASP + 0.06])
|
| 496 |
+
sk.move_to([x0, y0, Z_GRASP + 0.06])
|
| 497 |
+
sk.move_to([x0, y0, Z_GRASP + 0.003], tol=0.003)
|
| 498 |
+
sk.set_gripper(False, steps=12)
|
| 499 |
+
sk.move_to([x0, y0, Z_GRASP + 0.10])
|
| 500 |
+
return 6
|
| 501 |
+
|
| 502 |
+
@staticmethod
|
| 503 |
+
def _plan_speed(want, pts):
|
| 504 |
+
"""Speed for a slide of `want` m from strikes seen so far, pts = [(speed, slide)]: none -> the 0.30 m/s
|
| 505 |
+
prior; one -> slide ~ speed^2 through it; several -> log-log interpolation between the bracketing strikes
|
| 506 |
+
(or extrapolation from the two nearest, exponent clipped to [0.5, 3])."""
|
| 507 |
+
pts = sorted((v, d) for v, d in pts if d > 0.002)
|
| 508 |
+
if not pts:
|
| 509 |
+
return 0.30
|
| 510 |
+
if len(pts) == 1:
|
| 511 |
+
v, d = pts[0]
|
| 512 |
+
return float(np.clip(v * (want / d) ** 0.5, V_MIN, V_MAX))
|
| 513 |
+
lo = [p for p in pts if p[1] <= want]
|
| 514 |
+
hi = [p for p in pts if p[1] > want]
|
| 515 |
+
if lo and hi:
|
| 516 |
+
(v0, d0), (v1, d1) = max(lo, key=lambda p: p[1]), min(hi, key=lambda p: p[1])
|
| 517 |
+
else:
|
| 518 |
+
(v0, d0), (v1, d1) = sorted(pts, key=lambda p: abs(np.log(p[1] / want)))[:2]
|
| 519 |
+
if abs(np.log(d1 / d0)) < 1e-6 or abs(np.log(v1 / v0)) < 1e-6:
|
| 520 |
+
return float(np.clip(v0 * (want / d0) ** 0.5, V_MIN, V_MAX))
|
| 521 |
+
k = float(np.clip(np.log(d1 / d0) / np.log(v1 / v0), 0.5, 3.0))
|
| 522 |
+
return float(np.clip(v0 * (want / d0) ** (1.0 / k), V_MIN, V_MAX))
|
| 523 |
+
|
| 524 |
+
def _adaptive_attempt(self, inst, pts):
|
| 525 |
+
"""One attempt of the scripted within-attempt learner: strike; look where the cube stopped (perfect
|
| 526 |
+
perception, as on the images); if short by >= D_MIN + 2 cm strike again from there, otherwise (overshot,
|
| 527 |
+
a little short, or drifted sideways) carry it back to its initial position and strike again, with the speed
|
| 528 |
+
planned from every strike seen so far (`pts`, also from earlier attempts). Stops when the cube is in the square
|
| 529 |
+
or the next correction would not fit in the agent's command / motion budget."""
|
| 530 |
+
x0, y0 = inst["cube_xy"]
|
| 531 |
+
tx = x0 + inst["target_dist"]
|
| 532 |
+
sk = self.sk
|
| 533 |
+
n0 = sk.n_steps
|
| 534 |
+
n_cmd, speeds, path = 0, [], []
|
| 535 |
+
while True:
|
| 536 |
+
c = envs.obj_pos(self.env, CUBE)
|
| 537 |
+
want = tx - c[0]
|
| 538 |
+
near_start = np.linalg.norm(c[:2] - np.asarray(inst["cube_xy"])) < 0.01
|
| 539 |
+
local = [(v, d) for v, d, s in pts if s == near_start] or [(v, d) for v, d, _ in pts]
|
| 540 |
+
speed = self._plan_speed(want, local)
|
| 541 |
+
n_cmd += self._strike_here(speed)
|
| 542 |
+
c1 = envs.obj_pos(self.env, CUBE)
|
| 543 |
+
pts.append((speed, float(c1[0] - c[0]), near_start))
|
| 544 |
+
speeds.append(round(speed, 4))
|
| 545 |
+
err, across = float(c1[0] - tx), float(c1[1] - y0)
|
| 546 |
+
path.append("strike")
|
| 547 |
+
if -self.tol_along <= err <= self.tol_past and abs(across) <= self.tol_across:
|
| 548 |
+
break
|
| 549 |
+
used_s = (sk.n_steps - n0) * DT
|
| 550 |
+
if err < 0 and -err >= D_MIN + self.RESTRIKE_MARGIN and abs(across) < 0.005:
|
| 551 |
+
if n_cmd + 4 > self.AGENT_CMDS or used_s + 12.0 > self.AGENT_SIM_S:
|
| 552 |
+
break
|
| 553 |
+
continue
|
| 554 |
+
if n_cmd + 10 > self.AGENT_CMDS or used_s + 30.0 > self.AGENT_SIM_S:
|
| 555 |
+
break
|
| 556 |
+
n_cmd += self._carry_back(inst)
|
| 557 |
+
path.append("carry_back")
|
| 558 |
+
return dict(speed=speeds[0], speeds=speeds, path=path, n_commands=n_cmd,
|
| 559 |
+
sim_s=round((sk.n_steps - n0) * DT, 1))
|
| 560 |
+
|
| 561 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 562 |
+
"""oracle / naive / blind: one strike per attempt (LFFTask.run_scripted, cross protocol). adaptive: corrects
|
| 563 |
+
within the attempt (_adaptive_attempt) and carries what it saw into the next attempt."""
|
| 564 |
+
if kind != "adaptive":
|
| 565 |
+
return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt)
|
| 566 |
+
k = k or self.max_attempts
|
| 567 |
+
history, pts = [], []
|
| 568 |
+
for a in range(k):
|
| 569 |
+
self.reset_instance(inst)
|
| 570 |
+
params = self._adaptive_attempt(inst, pts)
|
| 571 |
+
out = self.outcome(inst)
|
| 572 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 573 |
+
if on_attempt:
|
| 574 |
+
on_attempt(a, params, out)
|
| 575 |
+
if out["success"]:
|
| 576 |
+
break
|
| 577 |
+
return history
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l6_sequence.py
ADDED
|
@@ -0,0 +1,513 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L6-C sequence_resume: weigh four items one by one in a given order; an emergency stop resets part of the work.
|
| 2 |
+
|
| 3 |
+
Scene: four grocery items (cream cheese, butter, chocolate pudding, popcorn -- small flat boxes), each on its
|
| 4 |
+
own round pad (four identical dark pads, flat markers), and a scale (grey square platform, static fixture).
|
| 5 |
+
Pad / scale positions and the order are random per instance.
|
| 6 |
+
|
| 7 |
+
Instruction: weigh the items one at a time in the given order. Weighing = put the item on the scale and let go;
|
| 8 |
+
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
|
| 9 |
+
own pad before the next item is picked up. Every item must be weighed exactly once; the scale log cannot be
|
| 10 |
+
edited, so a second reading of an item or a reading out of turn is a terminal failure.
|
| 11 |
+
|
| 12 |
+
Interruption ("emergency stop", once per episode, inside attempt 1): while the robot carries an item, the gripper
|
| 13 |
+
opens, a safety routine puts that item back on its own pad and the arm returns to its home pose. Hidden: how
|
| 14 |
+
many items had been weighed when it happened, w in {1..4} (uniform), and the phase: the carried item was on its
|
| 15 |
+
way to the scale (not yet weighed, phase A) or on its way back (already weighed, phase B); w = 4 is always
|
| 16 |
+
phase B. After the stop every item sits on its pad and the arm is at home: the picture looks like the start of
|
| 17 |
+
the task. Which item comes next (order[w], or "nothing, call done" for w = 4) is only in the agent's own history
|
| 18 |
+
(what it carried, whether the scale had beeped).
|
| 19 |
+
|
| 20 |
+
Protocol: within (like l6_swap_interrupt). Events reported immediately (`drain_events`): the scale's beep after
|
| 21 |
+
every recorded reading, an error beep for a reading out of turn, and the emergency stop. F2 after `done` gives the
|
| 22 |
+
verdict, whether the log is complete, and which items are not on their pads (distance only), never how many
|
| 23 |
+
items have been weighed.
|
| 24 |
+
|
| 25 |
+
Scripted references (perception = simulator state):
|
| 26 |
+
oracle privileged scale log: always weighs order[len(log)] next.
|
| 27 |
+
adaptive keeps its own record of readings (an item counts as weighed when the scale beeped while it lay on
|
| 28 |
+
it); after the stop it resumes from order[len(record)] (redoes the interrupted item in phase A, goes on
|
| 29 |
+
with the next one in phase B, calls done when all four are recorded).
|
| 30 |
+
naive memoryless continuation (1 attempt): the picture after the stop shows no progress; it guesses how far
|
| 31 |
+
it got (uniform over 0..4 items weighed) and continues from there.
|
| 32 |
+
blind memoryless restart (k attempts): starts the sequence over from the first item -> a second reading of
|
| 33 |
+
an already weighed item (repeated step).
|
| 34 |
+
Extra control (not in the acceptance table): `skip` counts items it *started* to weigh (pick-ups) instead of
|
| 35 |
+
readings: correct after a phase-B stop, skips the interrupted item after a phase-A stop.
|
| 36 |
+
"""
|
| 37 |
+
import numpy as np
|
| 38 |
+
|
| 39 |
+
from .. import envs
|
| 40 |
+
from ..bddl import write_bddl
|
| 41 |
+
from ..objects import _fmt, _wrap, register_generated
|
| 42 |
+
from ..skills import ROT_SCALE, _rot_err
|
| 43 |
+
from ..task_base import LFFTask, register_task
|
| 44 |
+
from .l6_swap import _pad_xml as _swap_pad_xml
|
| 45 |
+
|
| 46 |
+
ITEMS = ["cream_cheese_1", "butter_1", "chocolate_pudding_1", "popcorn_1"]
|
| 47 |
+
CATS = {"cream_cheese_1": "cream_cheese", "butter_1": "butter", "chocolate_pudding_1": "chocolate_pudding",
|
| 48 |
+
"popcorn_1": "popcorn"}
|
| 49 |
+
NAME = {"cream_cheese_1": "cream cheese", "butter_1": "butter", "chocolate_pudding_1": "chocolate pudding",
|
| 50 |
+
"popcorn_1": "popcorn"}
|
| 51 |
+
DESCR = {"cream_cheese_1": "the pale blue box with the oval logo", "butter_1": "the red box with white lettering",
|
| 52 |
+
"chocolate_pudding_1": "the dark brown box", "popcorn_1": "the blue-and-yellow box"}
|
| 53 |
+
N_ITEMS = len(ITEMS)
|
| 54 |
+
PADS = [f"pad_{i + 1}" for i in range(N_ITEMS)]
|
| 55 |
+
PAD_R = 0.055
|
| 56 |
+
PAD_HALF_T = 0.0008
|
| 57 |
+
|
| 58 |
+
SCALE_HALF = 0.06 # platform half size (12 x 12 cm)
|
| 59 |
+
SCALE_BASE_HALF = 0.067
|
| 60 |
+
SCALE_TOP = 0.020 # platform top above the table
|
| 61 |
+
SCALE_BASE_H = 0.012
|
| 62 |
+
SCALE_RGBA = (0.78, 0.79, 0.80, 1.0)
|
| 63 |
+
SCALE_BASE_RGBA = (0.20, 0.20, 0.22, 1.0)
|
| 64 |
+
|
| 65 |
+
BASE_X = -0.66
|
| 66 |
+
REGION = (-0.27, 0.05, -0.27, 0.27)
|
| 67 |
+
REACH = 0.70
|
| 68 |
+
PAD_MIN = 0.16
|
| 69 |
+
SCALE_MIN = 0.175
|
| 70 |
+
SUCC_R = 0.04 # item centre within 4 cm of its pad centre
|
| 71 |
+
GRASP_DZ = 0.012 # gripper-site height above the support surface for a top-down grasp of the flat boxes
|
| 72 |
+
Z_CARRY = envs.TABLE_Z + 0.15
|
| 73 |
+
DWELL = 10 # control steps (0.5 s) at rest on the scale before a reading is recorded
|
| 74 |
+
LIFTED = 0.04
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def scale_xml(model_name):
|
| 78 |
+
parts = [((0, 0, SCALE_BASE_H / 2), (SCALE_BASE_HALF, SCALE_BASE_HALF, SCALE_BASE_H / 2), SCALE_BASE_RGBA),
|
| 79 |
+
((0, 0, (SCALE_BASE_H + SCALE_TOP) / 2), (SCALE_HALF, SCALE_HALF, (SCALE_TOP - SCALE_BASE_H) / 2),
|
| 80 |
+
SCALE_RGBA)]
|
| 81 |
+
g = []
|
| 82 |
+
for k, (pos, half, rgba) in enumerate(parts):
|
| 83 |
+
g.append(f' <geom name="{model_name}_g{k}" type="box" pos="{_fmt(pos)}" size="{_fmt(half)}" '
|
| 84 |
+
f'rgba="{_fmt(rgba)}" density="1000" friction="1.0 0.005 0.0001" group="0" />')
|
| 85 |
+
g.append(f' <geom type="box" pos="{_fmt(pos)}" size="{_fmt(half)}" rgba="{_fmt(rgba)}" '
|
| 86 |
+
f'conaffinity="0" contype="0" group="1" />')
|
| 87 |
+
return _wrap(model_name, "\n".join(g), SCALE_TOP / 2, float(np.hypot(SCALE_BASE_HALF, SCALE_BASE_HALF)))
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _yaw_of(env, obj):
|
| 91 |
+
R = env.sim.data.body_xmat[envs.body_id(env, obj)].reshape(3, 3)
|
| 92 |
+
yaw = float(np.arctan2(R[1, 0], R[0, 0])) # long axis of the boxes = body x
|
| 93 |
+
return (yaw + np.pi / 2) % np.pi - np.pi / 2
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@register_task
|
| 97 |
+
class SequenceResume(LFFTask):
|
| 98 |
+
name = "l6_sequence_resume"
|
| 99 |
+
level = "L6"
|
| 100 |
+
category = "procedural_memory"
|
| 101 |
+
capabilities = ("Perceive", "Save", "Retrieve", "Utilize")
|
| 102 |
+
protocol = "within"
|
| 103 |
+
agent_max_steps = 100 # robot commands per attempt for agents (a VLM needs ~60-75)
|
| 104 |
+
max_attempts = 5
|
| 105 |
+
_TEMPLATE = ("Weigh the four grocery items one at a time, in this order: {order}. To weigh an item, put it on "
|
| 106 |
+
"the grey scale and let go of it; the scale beeps when it has recorded the reading. Then put the "
|
| 107 |
+
"item back on its own round pad before you pick up the next item. Weigh every item exactly once: "
|
| 108 |
+
"the scale logs every reading, and the log cannot be edited.")
|
| 109 |
+
instruction = _TEMPLATE.format(order="(given per instance)")
|
| 110 |
+
instruction_indirect = instruction
|
| 111 |
+
inject = True
|
| 112 |
+
agent_object_names = [NAME[i] for i in ITEMS] + ["scale", "round pads"]
|
| 113 |
+
|
| 114 |
+
def agent_instruction(self, inst, variant="direct"):
|
| 115 |
+
names = DESCR if variant == "indirect" else NAME
|
| 116 |
+
order = [names[o] for o in inst["order"]]
|
| 117 |
+
return self._TEMPLATE.format(order=", ".join(order[:-1]) + ", then " + order[-1])
|
| 118 |
+
|
| 119 |
+
def __init__(self, cam_res=None):
|
| 120 |
+
super().__init__(cam_res)
|
| 121 |
+
self._mon = False
|
| 122 |
+
self._latch = None
|
| 123 |
+
orig_step = self.env.step
|
| 124 |
+
|
| 125 |
+
def step(action): # per-control-step monitor (also for attempts driven by the agent harness)
|
| 126 |
+
if self._latch is not None:
|
| 127 |
+
action = self._homing_action()
|
| 128 |
+
ret = orig_step(action)
|
| 129 |
+
if self._mon:
|
| 130 |
+
self._monitor()
|
| 131 |
+
return ret
|
| 132 |
+
|
| 133 |
+
self.env.step = step
|
| 134 |
+
|
| 135 |
+
# ------------------------------------------------------------ scene
|
| 136 |
+
def make_bddl(self):
|
| 137 |
+
pads = [register_generated(f"LffSeqPad{L}", _swap_pad_xml(f"lff_seq_pad_{L.lower()}")) for L in "ABCD"]
|
| 138 |
+
scale = register_generated("LffSeqScale", scale_xml("lff_seq_scale"), free=False)
|
| 139 |
+
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))
|
| 140 |
+
for i, o in enumerate(ITEMS)]
|
| 141 |
+
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))
|
| 142 |
+
for i in range(N_ITEMS)]
|
| 143 |
+
fx = [("scale_1", scale, "scale_region", (0.19, -0.01, 0.21, 0.01))]
|
| 144 |
+
return write_bddl(self.name, "Weigh the four items one at a time in the given order", objs, fx) # no ; in BDDL
|
| 145 |
+
|
| 146 |
+
def sample_instance(self, seed):
|
| 147 |
+
rng = np.random.default_rng(seed)
|
| 148 |
+
for _ in range(5000):
|
| 149 |
+
pts = []
|
| 150 |
+
while len(pts) < N_ITEMS + 1:
|
| 151 |
+
p = np.array([rng.uniform(*REGION[:2]), rng.uniform(*REGION[2:])])
|
| 152 |
+
if np.hypot(p[0] - BASE_X, p[1]) > REACH:
|
| 153 |
+
continue
|
| 154 |
+
pts.append(p)
|
| 155 |
+
scale, pads = pts[0], np.array(pts[1:])
|
| 156 |
+
dp = [np.linalg.norm(pads[i] - pads[j]) for i in range(N_ITEMS) for j in range(i)]
|
| 157 |
+
if min(dp) >= PAD_MIN and min(np.linalg.norm(pads - scale, axis=1)) >= SCALE_MIN:
|
| 158 |
+
break
|
| 159 |
+
else:
|
| 160 |
+
raise RuntimeError("could not sample a layout")
|
| 161 |
+
order = [ITEMS[i] for i in rng.permutation(N_ITEMS)]
|
| 162 |
+
w = int(rng.integers(1, N_ITEMS + 1)) # items weighed when the stop happens
|
| 163 |
+
phase = "B" if w == N_ITEMS else str(rng.choice(["A", "B"]))
|
| 164 |
+
inst = dict(seed=int(seed), order=order, pads=pads.round(4).tolist(), scale_xy=scale.round(4).tolist(),
|
| 165 |
+
item_off=[[float(v) for v in rng.uniform(-0.008, 0.008, 2)] for _ in range(N_ITEMS)],
|
| 166 |
+
item_yaw=[float(v) for v in rng.uniform(-0.3, 0.3, N_ITEMS)],
|
| 167 |
+
stop_w=w, stop_phase=phase, trigger_dist=float(rng.uniform(0.05, 0.09)),
|
| 168 |
+
stop_off=[float(v) for v in rng.uniform(-0.008, 0.008, 2)],
|
| 169 |
+
stop_yaw=float(rng.uniform(-0.3, 0.3)))
|
| 170 |
+
inst["stop_item"] = order[w] if phase == "A" else order[w - 1]
|
| 171 |
+
self.instruction = self.agent_instruction(inst, "direct") # make_video prints task.instruction
|
| 172 |
+
self.instruction_indirect = self.agent_instruction(inst, "indirect")
|
| 173 |
+
return inst
|
| 174 |
+
|
| 175 |
+
def apply_instance(self, inst):
|
| 176 |
+
m = self.env.sim.model
|
| 177 |
+
for i, p in enumerate(inst["pads"]):
|
| 178 |
+
envs.set_obj_pose(self.env, PADS[i], [p[0], p[1], envs.TABLE_Z + PAD_HALF_T + 0.0001])
|
| 179 |
+
bid = m.body_name2id(self.env.fixtures_dict["scale_1"].root_body)
|
| 180 |
+
m.body_pos[bid] = [inst["scale_xy"][0], inst["scale_xy"][1], envs.TABLE_Z]
|
| 181 |
+
m.body_quat[bid] = [1, 0, 0, 0]
|
| 182 |
+
for i, o in enumerate(ITEMS):
|
| 183 |
+
p = np.asarray(inst["pads"][i]) + inst["item_off"][i]
|
| 184 |
+
envs.place_upright(self.env, o, p, inst["item_yaw"][i])
|
| 185 |
+
self.env.sim.forward()
|
| 186 |
+
self._inst = inst
|
| 187 |
+
self.pad_of = {o: i for i, o in enumerate(ITEMS)} # item i starts on pad i (pad positions are random)
|
| 188 |
+
self.log = [] # scale readings (item names)
|
| 189 |
+
self.error = None
|
| 190 |
+
self.stop = None
|
| 191 |
+
self.events = []
|
| 192 |
+
self._event_cursor = 0
|
| 193 |
+
self._outcome_cursor = 0
|
| 194 |
+
self._dwell = {o: 0 for o in ITEMS}
|
| 195 |
+
self._visit = {o: False for o in ITEMS}
|
| 196 |
+
self._prev = {}
|
| 197 |
+
self._latch = None
|
| 198 |
+
self._mon = False
|
| 199 |
+
|
| 200 |
+
def reset_instance(self, inst, recorder=None):
|
| 201 |
+
self._mon = False
|
| 202 |
+
self._latch = None
|
| 203 |
+
sk = super().reset_instance(inst, recorder=recorder)
|
| 204 |
+
self._home = sk.eef_pos()
|
| 205 |
+
self.rest_dz = {o: float(envs.obj_pos(self.env, o)[2] - envs.TABLE_Z) for o in ITEMS}
|
| 206 |
+
self._prev = {o: envs.obj_pos(self.env, o) for o in ITEMS}
|
| 207 |
+
self._mon = True
|
| 208 |
+
return sk
|
| 209 |
+
|
| 210 |
+
def go_home(self):
|
| 211 |
+
p = self.sk.eef_pos()
|
| 212 |
+
self.sk.move_to([p[0], p[1], max(p[2], self._home[2])])
|
| 213 |
+
self.sk.move_to(self._home)
|
| 214 |
+
|
| 215 |
+
# ------------------------------------------------------------ helpers
|
| 216 |
+
def scale_xy(self):
|
| 217 |
+
return np.asarray(self._inst["scale_xy"], float)
|
| 218 |
+
|
| 219 |
+
def pad_xy(self, o):
|
| 220 |
+
return np.asarray(self._inst["pads"][self.pad_of[o]], float)
|
| 221 |
+
|
| 222 |
+
def on_scale(self, o, p=None):
|
| 223 |
+
p = envs.obj_pos(self.env, o) if p is None else p
|
| 224 |
+
d = np.abs(p[:2] - self.scale_xy())
|
| 225 |
+
return bool(d.max() <= SCALE_HALF and abs(p[2] - (envs.TABLE_Z + SCALE_TOP + self.rest_dz[o])) < 0.008)
|
| 226 |
+
|
| 227 |
+
def on_own_pad(self, o):
|
| 228 |
+
p = envs.obj_pos(self.env, o)
|
| 229 |
+
return bool(np.linalg.norm(p[:2] - self.pad_xy(o)) <= SUCC_R
|
| 230 |
+
and abs(p[2] - (envs.TABLE_Z + self.rest_dz[o])) < 0.01 and not self.sk.holding(o))
|
| 231 |
+
|
| 232 |
+
# ------------------------------------------------------------ monitor: scale readings + emergency stop
|
| 233 |
+
def _monitor(self):
|
| 234 |
+
env = self.env
|
| 235 |
+
if self._latch is not None:
|
| 236 |
+
if len(self.sk.log) > self._latch and np.linalg.norm(self.sk.eef_pos() - self._home) < 0.01:
|
| 237 |
+
self._latch = None
|
| 238 |
+
for o in ITEMS:
|
| 239 |
+
p = envs.obj_pos(env, o)
|
| 240 |
+
still = np.linalg.norm(p - self._prev[o]) < 0.0008
|
| 241 |
+
self._prev[o] = p
|
| 242 |
+
if self.on_scale(o, p):
|
| 243 |
+
if still and not self.sk.holding(o):
|
| 244 |
+
self._dwell[o] += 1
|
| 245 |
+
if self._dwell[o] >= DWELL and not self._visit[o]:
|
| 246 |
+
self._visit[o] = True
|
| 247 |
+
self._record(o)
|
| 248 |
+
else:
|
| 249 |
+
self._dwell[o] = 0
|
| 250 |
+
else:
|
| 251 |
+
self._dwell[o] = 0
|
| 252 |
+
if np.abs(p[:2] - self.scale_xy()).max() > SCALE_HALF or \
|
| 253 |
+
p[2] > envs.TABLE_Z + SCALE_TOP + self.rest_dz[o] + 0.02:
|
| 254 |
+
self._visit[o] = False
|
| 255 |
+
if self.inject and self.stop is None:
|
| 256 |
+
self._maybe_stop()
|
| 257 |
+
|
| 258 |
+
def _record(self, o):
|
| 259 |
+
self.log.append(o)
|
| 260 |
+
k = len(self.log)
|
| 261 |
+
ok = self.log == self._inst["order"][:k]
|
| 262 |
+
if ok:
|
| 263 |
+
self.events.append(dict(step=int(self.sk.n_steps), kind="beep", obj=o,
|
| 264 |
+
text="The scale beeped: reading recorded."))
|
| 265 |
+
else:
|
| 266 |
+
if self.error is None:
|
| 267 |
+
self.error = dict(item=o, position=k, step=int(self.sk.n_steps),
|
| 268 |
+
kind="repeat" if self.log.count(o) > 1 else "out_of_order")
|
| 269 |
+
self.events.append(dict(step=int(self.sk.n_steps), kind="error", obj=o,
|
| 270 |
+
text="The scale beeped three times: error, this reading does not follow the "
|
| 271 |
+
"requested order. The log cannot be edited."))
|
| 272 |
+
|
| 273 |
+
def _maybe_stop(self):
|
| 274 |
+
inst = self._inst
|
| 275 |
+
o, w = inst["stop_item"], inst["stop_w"]
|
| 276 |
+
if self.log != inst["order"][:w]:
|
| 277 |
+
return
|
| 278 |
+
p = envs.obj_pos(self.env, o)
|
| 279 |
+
if inst["stop_phase"] == "A":
|
| 280 |
+
if p[2] < envs.TABLE_Z + self.rest_dz[o] + LIFTED:
|
| 281 |
+
return
|
| 282 |
+
if np.linalg.norm(p[:2] - self.pad_xy(o)) < inst["trigger_dist"]:
|
| 283 |
+
return
|
| 284 |
+
else:
|
| 285 |
+
if p[2] < envs.TABLE_Z + SCALE_TOP + self.rest_dz[o] + LIFTED:
|
| 286 |
+
return
|
| 287 |
+
if np.linalg.norm(p[:2] - self.scale_xy()) < inst["trigger_dist"]:
|
| 288 |
+
return
|
| 289 |
+
if not self.sk.holding(o):
|
| 290 |
+
return
|
| 291 |
+
self._do_stop(o)
|
| 292 |
+
|
| 293 |
+
def _do_stop(self, o):
|
| 294 |
+
inst = self._inst
|
| 295 |
+
xy = self.pad_xy(o) + np.asarray(inst["stop_off"])
|
| 296 |
+
envs.place_upright(self.env, o, xy, inst["stop_yaw"])
|
| 297 |
+
self.sk.grip = -1.0
|
| 298 |
+
self.sk.yaw = 0.0
|
| 299 |
+
self._latch = len(self.sk.log) # drive the arm home until the current primitive has returned
|
| 300 |
+
self._prev[o] = envs.obj_pos(self.env, o)
|
| 301 |
+
self.env.sim.forward()
|
| 302 |
+
text = ("Emergency stop! The gripper opened, the safety routine put the item the robot was holding back on "
|
| 303 |
+
"its pad and moved the arm to its home pose. You may continue the task.")
|
| 304 |
+
self.stop = dict(item=o, phase=inst["stop_phase"], weighed=len(self.log), step=int(self.sk.n_steps))
|
| 305 |
+
self.events.append(dict(step=int(self.sk.n_steps), kind="stop", obj=o, text=text))
|
| 306 |
+
|
| 307 |
+
def _homing_action(self):
|
| 308 |
+
sk = self.sk
|
| 309 |
+
a = np.zeros(self.env.action_dim)
|
| 310 |
+
a[:3] = np.clip((self._home - sk.eef_pos()) / sk.pos_scale, -1, 1)
|
| 311 |
+
a[3:6] = np.clip(_rot_err(sk.R0, sk.eef_mat()) / ROT_SCALE, -1, 1)
|
| 312 |
+
a[6] = -1.0
|
| 313 |
+
return a
|
| 314 |
+
|
| 315 |
+
def drain_events(self):
|
| 316 |
+
ev = self.events[self._event_cursor:]
|
| 317 |
+
self._event_cursor = len(self.events)
|
| 318 |
+
return [e["text"] for e in ev]
|
| 319 |
+
|
| 320 |
+
# ------------------------------------------------------------ outcome
|
| 321 |
+
def outcome(self, inst):
|
| 322 |
+
envs.settle(self.env, 20)
|
| 323 |
+
order = inst["order"]
|
| 324 |
+
complete = self.log == order
|
| 325 |
+
terminal = self.error is not None
|
| 326 |
+
off = [o for o in ITEMS if not self.on_own_pad(o)]
|
| 327 |
+
success = bool(complete and not off and not terminal)
|
| 328 |
+
if success:
|
| 329 |
+
head = "All four items were weighed once, in the requested order, and are back on their pads."
|
| 330 |
+
elif terminal:
|
| 331 |
+
head = ("The scale log does not follow the requested order (an item was weighed a second time or out "
|
| 332 |
+
"of turn). The log cannot be edited, so the task can no longer be completed.")
|
| 333 |
+
elif complete:
|
| 334 |
+
head = "Every item has been weighed, but not every item is back on its own pad."
|
| 335 |
+
else:
|
| 336 |
+
head = "Not every item has been weighed yet."
|
| 337 |
+
parts = []
|
| 338 |
+
if not success and not terminal:
|
| 339 |
+
for o in off:
|
| 340 |
+
p = envs.obj_pos(self.env, o)
|
| 341 |
+
if self.sk.holding(o):
|
| 342 |
+
parts.append(f"the {NAME[o]} is still in the gripper")
|
| 343 |
+
elif self.on_scale(o, p):
|
| 344 |
+
parts.append(f"the {NAME[o]} is on the scale")
|
| 345 |
+
else:
|
| 346 |
+
d = np.linalg.norm(p[:2] - self.pad_xy(o))
|
| 347 |
+
parts.append(f"the {NAME[o]} is {100 * d:.0f} cm from the centre of its pad")
|
| 348 |
+
detail = head + (" Also: " + "; ".join(parts) + "." if parts else "")
|
| 349 |
+
new = [e for e in self.events[self._outcome_cursor:] if e["kind"] == "stop"]
|
| 350 |
+
self._outcome_cursor = len(self.events)
|
| 351 |
+
if new:
|
| 352 |
+
detail = "During this attempt: " + " ".join(e["text"] for e in new) + " " + detail
|
| 353 |
+
return dict(success=success, terminal=terminal, log=[NAME[o] for o in self.log], n_weighed=len(self.log),
|
| 354 |
+
complete=complete, error=self.error, stop=self.stop,
|
| 355 |
+
off_pad=[NAME[o] for o in off], detail=detail)
|
| 356 |
+
|
| 357 |
+
# ------------------------------------------------------------ motion (scripted policies)
|
| 358 |
+
def _support_z(self, o):
|
| 359 |
+
p = envs.obj_pos(self.env, o)
|
| 360 |
+
return envs.TABLE_Z + (SCALE_TOP if self.on_scale(o, p) or
|
| 361 |
+
(np.abs(p[:2] - self.scale_xy()).max() < SCALE_HALF) else 0.0)
|
| 362 |
+
|
| 363 |
+
def _n_stops(self):
|
| 364 |
+
return sum(e["kind"] == "stop" for e in self.events)
|
| 365 |
+
|
| 366 |
+
def _pick(self, o):
|
| 367 |
+
sk = self.sk
|
| 368 |
+
for _ in range(2):
|
| 369 |
+
p = envs.obj_pos(self.env, o)
|
| 370 |
+
sk.grasp_at(p[:2], self._support_z(o) + GRASP_DZ, yaw=_yaw_of(self.env, o), lift=0.12)
|
| 371 |
+
if sk.holding(o):
|
| 372 |
+
return True
|
| 373 |
+
sk.set_gripper(False, steps=8)
|
| 374 |
+
sk.move_to([p[0], p[1], self._support_z(o) + GRASP_DZ + 0.12])
|
| 375 |
+
return False
|
| 376 |
+
|
| 377 |
+
def _carry_to(self, o, xy, z_support):
|
| 378 |
+
"""Carry the held item to xy and put it down. Returns False if an emergency stop happened."""
|
| 379 |
+
sk = self.sk
|
| 380 |
+
n0 = self._n_stops()
|
| 381 |
+
sk.move_to([xy[0], xy[1], Z_CARRY])
|
| 382 |
+
if self._n_stops() > n0:
|
| 383 |
+
return False
|
| 384 |
+
sk.move_to([xy[0], xy[1], z_support + GRASP_DZ + 0.004], tol=0.004)
|
| 385 |
+
sk.set_gripper(False, steps=12)
|
| 386 |
+
sk.move_to([xy[0], xy[1], z_support + GRASP_DZ + 0.10])
|
| 387 |
+
return self._n_stops() == n0
|
| 388 |
+
|
| 389 |
+
def _weigh(self, o):
|
| 390 |
+
"""Weigh one item (pad -> scale -> pad). Returns (status, beeped): status 'ok' / 'stop_A' / 'stop_B' /
|
| 391 |
+
'no_grasp'; beeped = the scale beeped while the item lay on it (what the agent hears)."""
|
| 392 |
+
n_beep = sum(e["kind"] in ("beep", "error") for e in self.events)
|
| 393 |
+
if not self._pick(o):
|
| 394 |
+
return "no_grasp", False
|
| 395 |
+
if not self._carry_to(o, self.scale_xy(), envs.TABLE_Z + SCALE_TOP):
|
| 396 |
+
return "stop_A", False
|
| 397 |
+
self.sk.hold(6)
|
| 398 |
+
beeped = sum(e["kind"] in ("beep", "error") for e in self.events) > n_beep
|
| 399 |
+
if not self._pick(o):
|
| 400 |
+
return "no_grasp", beeped
|
| 401 |
+
if not self._carry_to(o, self.pad_xy(o), envs.TABLE_Z):
|
| 402 |
+
return "stop_B", beeped
|
| 403 |
+
return "ok", beeped
|
| 404 |
+
|
| 405 |
+
def _fix_pads(self, log):
|
| 406 |
+
for o in ITEMS:
|
| 407 |
+
if not self.on_own_pad(o) and not self.on_scale(o):
|
| 408 |
+
if self._pick(o):
|
| 409 |
+
self._carry_to(o, self.pad_xy(o), envs.TABLE_Z)
|
| 410 |
+
log.append((NAME[o], "back to pad"))
|
| 411 |
+
|
| 412 |
+
def _run_from(self, k, record, log, stop_on_stop=False):
|
| 413 |
+
"""Weigh order[k:] in turn, keeping `record` (the policy's own list of readings it heard)."""
|
| 414 |
+
order = self._inst["order"]
|
| 415 |
+
i = k
|
| 416 |
+
guard = 0
|
| 417 |
+
while i < len(order) and guard < 10 and self.error is None:
|
| 418 |
+
guard += 1
|
| 419 |
+
o = order[i]
|
| 420 |
+
st, beeped = self._weigh(o)
|
| 421 |
+
log.append((NAME[o], st, beeped))
|
| 422 |
+
if beeped:
|
| 423 |
+
record.append(o)
|
| 424 |
+
if st == "no_grasp":
|
| 425 |
+
continue
|
| 426 |
+
if st.startswith("stop"):
|
| 427 |
+
if stop_on_stop:
|
| 428 |
+
return "stopped"
|
| 429 |
+
i = len(record) # resume from the own record
|
| 430 |
+
continue
|
| 431 |
+
i += 1
|
| 432 |
+
return "ok"
|
| 433 |
+
|
| 434 |
+
# ------------------------------------------------------------ scripted references (within protocol)
|
| 435 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 436 |
+
k = k or self.max_attempts
|
| 437 |
+
rng = np.random.default_rng(seed + 104729)
|
| 438 |
+
self.reset_instance(inst)
|
| 439 |
+
order = inst["order"]
|
| 440 |
+
history = []
|
| 441 |
+
record = [] # adaptive's Save: readings it heard
|
| 442 |
+
for a in range(k):
|
| 443 |
+
log = []
|
| 444 |
+
plan = dict(kind=kind, steps=log)
|
| 445 |
+
if a == 0:
|
| 446 |
+
if kind == "oracle":
|
| 447 |
+
while len(self.log) < len(order) and self.error is None and len(log) < 12:
|
| 448 |
+
o = order[len(self.log)] # privileged scale log
|
| 449 |
+
st, _ = self._weigh(o)
|
| 450 |
+
log.append((NAME[o], st))
|
| 451 |
+
plan["recovery"] = "oracle: privileged scale log"
|
| 452 |
+
elif kind == "adaptive":
|
| 453 |
+
self._run_from(0, record, log)
|
| 454 |
+
plan["recovery"] = "own record of readings: resume from order[len(record)]"
|
| 455 |
+
elif kind == "skip":
|
| 456 |
+
started = []
|
| 457 |
+
i = 0
|
| 458 |
+
while i < len(order) and self.error is None and len(log) < 12:
|
| 459 |
+
o = order[i]
|
| 460 |
+
st, beeped = self._weigh(o)
|
| 461 |
+
log.append((NAME[o], st, beeped))
|
| 462 |
+
if st == "no_grasp":
|
| 463 |
+
continue
|
| 464 |
+
started.append(o)
|
| 465 |
+
i = len(started) # counts started items, not readings
|
| 466 |
+
plan["recovery"] = "counts items it started to weigh (the interrupted one too)"
|
| 467 |
+
else: # memoryless after the stop
|
| 468 |
+
r = self._run_from(0, record, log, stop_on_stop=True)
|
| 469 |
+
if r == "stopped":
|
| 470 |
+
if kind == "naive":
|
| 471 |
+
g = int(rng.integers(0, len(order) + 1))
|
| 472 |
+
plan["recovery"] = f"memoryless: guesses {g} items already weighed"
|
| 473 |
+
self._run_from(g, [], log)
|
| 474 |
+
elif kind == "blind":
|
| 475 |
+
plan["recovery"] = "memoryless restart from the first item"
|
| 476 |
+
self._run_from(0, [], log)
|
| 477 |
+
else:
|
| 478 |
+
raise ValueError(kind)
|
| 479 |
+
else:
|
| 480 |
+
plan["recovery"] = "none (no stop)"
|
| 481 |
+
else:
|
| 482 |
+
if kind in ("adaptive", "oracle", "skip"):
|
| 483 |
+
plan["recovery"] = "memory + F2: put items back on their pads / finish from own record"
|
| 484 |
+
if kind == "adaptive" and len(record) < len(order):
|
| 485 |
+
self._run_from(len(record), record, log)
|
| 486 |
+
if kind == "skip" and not history[-1]["outcome"]["complete"]:
|
| 487 |
+
# F2 says the log is incomplete: with memory, the item carried at the stop was not weighed
|
| 488 |
+
stopped = [s[0] for h in history for s in h["params"]["steps"] if str(s[1]).startswith("stop")]
|
| 489 |
+
if stopped:
|
| 490 |
+
o = next(i for i in ITEMS if NAME[i] == stopped[-1])
|
| 491 |
+
st, _ = self._weigh(o)
|
| 492 |
+
log.append((NAME[o], st))
|
| 493 |
+
plan["recovery"] = "memory + F2 'not every item weighed': weigh the item carried at the stop"
|
| 494 |
+
self._fix_pads(log)
|
| 495 |
+
elif kind == "blind":
|
| 496 |
+
plan["recovery"] = "memoryless restart from the first item"
|
| 497 |
+
self._run_from(0, [], log)
|
| 498 |
+
else:
|
| 499 |
+
raise ValueError(kind)
|
| 500 |
+
self.go_home()
|
| 501 |
+
out = self.outcome(inst)
|
| 502 |
+
history.append(dict(attempt=a + 1, params=plan, outcome=out))
|
| 503 |
+
if on_attempt:
|
| 504 |
+
on_attempt(a, plan, out)
|
| 505 |
+
if out["success"] or out["terminal"] or kind in ("oracle", "naive"):
|
| 506 |
+
break
|
| 507 |
+
return history
|
| 508 |
+
|
| 509 |
+
def default_params(self, inst):
|
| 510 |
+
return dict(policy="naive")
|
| 511 |
+
|
| 512 |
+
def oracle_params(self, inst):
|
| 513 |
+
return dict(policy="oracle")
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/lh_balance_board.py
ADDED
|
@@ -0,0 +1,817 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LH balance_board: put four look-alike cubes on their marks on a plank that rests loose across a narrow block (a
|
| 2 |
+
seesaw); loading it in the wrong order tips the plank, and every cube already on it slides down to the low end.
|
| 3 |
+
|
| 4 |
+
Family: long-horizon self-disturbance ("state_restoration"): each stage is a plain pick-and-place of a cube onto its
|
| 5 |
+
mark, but a later placement can tip the plank, which sends the cubes placed before it (earlier progress) sliding off
|
| 6 |
+
their marks. The agent has to notice it, re-level the plank and re-place them before finishing (within an attempt), and
|
| 7 |
+
learn a loading order that keeps the plank level (across attempts; the final-state judge does not enforce an order).
|
| 8 |
+
|
| 9 |
+
Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
|
| 10 |
+
* 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
|
| 11 |
+
6 cm high, flat tops) under the middle of
|
| 12 |
+
* 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
|
| 13 |
+
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
|
| 14 |
+
the plank from wandering along the support (+-3 mm); nothing holds it down. It stays level while the combined centre
|
| 15 |
+
of mass of plank + cubes is above the support's 4 cm top; otherwise it tips until its low end touches the table
|
| 16 |
+
(about 17 degrees);
|
| 17 |
+
* four marks (5.8 cm squares, outline + light fill) on the plank, two on each side of the block: an inner one
|
| 18 |
+
(8.5-9.5 cm from the middle) and an outer one (15.5-16.5 cm); the colour of each mark is random;
|
| 19 |
+
* four 4.5 cm cubes (red, green, blue, yellow) on the table, two left and two right of the plank (random places).
|
| 20 |
+
They look alike except for the colour. Cube and plank surfaces are slick (friction 0.2 < tan 17 deg): on a tipped
|
| 21 |
+
plank every cube slides down to the lip at the low end.
|
| 22 |
+
Why along x with lips (measured, see the task card): with the plank left-right and open ends, the cubes slid off the
|
| 23 |
+
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
|
| 24 |
+
wide along them) pressed the plank's end down and tipped it again -- restoring became a loop. Along x the default grasp
|
| 25 |
+
is across the plank, and the lips keep the cubes on the plank within reach.
|
| 26 |
+
|
| 27 |
+
Hidden variable: the cube masses. "Hazard" instances (13 of every 20 consecutive seeds): the two cubes that belong on
|
| 28 |
+
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
|
| 29 |
+
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
|
| 30 |
+
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
|
| 31 |
+
orders are "an outer cube, then the inner cube on the OTHER side, then the other inner cube, then the last outer cube"
|
| 32 |
+
(zig-zag); end-to-end, alternating outer-first (outer, outer, inner, inner) and inner-first orders all tip it.
|
| 33 |
+
"Benign" instances: all four cubes light (26-34 g); no order tips (worst step 0.63-0.75 x).
|
| 34 |
+
|
| 35 |
+
Why the natural order fails: nothing in the image shows which cubes are heavy. Any natural order (nearest cube first,
|
| 36 |
+
the marks from one end to the other, or the cautious "alternate sides, outer marks first") tips the plank in a hazard
|
| 37 |
+
instance; the cubes on it slide to the low end and keep it tipped. A natural plan then keeps going and finishes with
|
| 38 |
+
cubes off their marks. What must be learned: check the marks after each placement / before finishing, unload the low
|
| 39 |
+
end and re-place (within the attempt), and use the tip to infer which cubes are heavy (an inner cube tipped it; the
|
| 40 |
+
layout must balance in the end, so the other inner cube is heavy too) and load in the zig-zag order (across attempts).
|
| 41 |
+
|
| 42 |
+
Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (every cube on its
|
| 43 |
+
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 /
|
| 44 |
+
lost / restored, with step and cause) and every tip (which end went down, the cube released just before) for the server
|
| 45 |
+
log; F1 gives the agent only success / failure.
|
| 46 |
+
"""
|
| 47 |
+
import itertools
|
| 48 |
+
|
| 49 |
+
import numpy as np
|
| 50 |
+
|
| 51 |
+
from .. import envs
|
| 52 |
+
from ..bddl import write_bddl
|
| 53 |
+
from ..objects import _fmt, _wrap, box_xml, register_generated
|
| 54 |
+
from ..skills import Skills
|
| 55 |
+
from ..task_base import LFFTask, register_task
|
| 56 |
+
|
| 57 |
+
TZ = envs.TABLE_Z
|
| 58 |
+
|
| 59 |
+
# ---------------------------------------------------------------- geometry / physics
|
| 60 |
+
# plank frame: y along the plank (+y = the end toward the robot), x across it, z up. The plank and the block are
|
| 61 |
+
# yawed 90 deg, so plank +y = world -x.
|
| 62 |
+
PL_HL, PL_HW, PL_HT = 0.23, 0.04, 0.0075 # plank half length, half width, half thickness
|
| 63 |
+
LIP_T, LIP_H = 0.008, 0.02 # lip across each end (inside the 46 cm), height above the plank's top
|
| 64 |
+
PLANK_MASS = 0.50
|
| 65 |
+
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
|
| 66 |
+
# and is calm in ~1.5 s (no damping: ~13 deg and ~2.7 s); the tip itself is not slowed (measured)
|
| 67 |
+
PLANK_YAW = np.pi / 2
|
| 68 |
+
RIDGE_HW, RIDGE_HX, RIDGE_H = 0.02, 0.05, 0.06 # support: half width along the plank (s), half depth, height
|
| 69 |
+
SLOT_HW = 0.005 # the support is two blocks with a 1 cm slot between them
|
| 70 |
+
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
|
| 71 |
+
CUBE_E = 0.045
|
| 72 |
+
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
|
| 73 |
+
MU_RIDGE = 1.0
|
| 74 |
+
MARK_HALF, MARK_LINE = 0.029, 0.004
|
| 75 |
+
WOOD = (0.42, 0.27, 0.15, 1.0) # dark walnut: contrasts with the light table, so the tilt reads in the images
|
| 76 |
+
|
| 77 |
+
COLORS = ("red", "green", "blue", "yellow")
|
| 78 |
+
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),
|
| 79 |
+
yellow=(0.93, 0.78, 0.10, 1.0))
|
| 80 |
+
CUBES = {c: f"{c}_cube_1" for c in COLORS}
|
| 81 |
+
PLANK, RIDGE = "plank_1", "ridge_1"
|
| 82 |
+
PLANK_MODEL = "lff_lh_bb_plank"
|
| 83 |
+
# mark slots in plank-frame order (+y first): the robot's end outer / inner, then the far end inner / outer
|
| 84 |
+
SLOTS = ("near_outer", "near_inner", "far_inner", "far_outer")
|
| 85 |
+
END_WORD = dict(near="the end nearer the robot", far="the far end")
|
| 86 |
+
|
| 87 |
+
# ---------------------------------------------------------------- instances / hidden variable
|
| 88 |
+
D_INNER = (0.085, 0.095) # |y| of the inner marks from the plank's middle
|
| 89 |
+
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
|
| 90 |
+
P_HAZARD = 0.65 # fraction of hazard instances, balanced per 20 consecutive seeds (13 / 7)
|
| 91 |
+
R_HEAVY = (1.30, 1.40) # hazard: lone heavy cube on its inner mark, moment / tipping moment
|
| 92 |
+
R_LIGHT = (0.72, 0.78) # hazard: lone light cube on its outer mark
|
| 93 |
+
LIGHT_BENIGN = (0.026, 0.034) # benign: every cube (kg)
|
| 94 |
+
H_EST, L_EST = 0.21, 0.04 # nominal masses the adaptive script uses for its hypotheses (it never sees the true ones)
|
| 95 |
+
|
| 96 |
+
# ---------------------------------------------------------------- judging
|
| 97 |
+
TOL = 0.020 # cube centre within 2 cm of its mark centre (per plank axis)
|
| 98 |
+
TOL_LOSE = 0.025 # hysteresis for the monitor
|
| 99 |
+
LEVEL_DEG = 3.0
|
| 100 |
+
TIP_DEG = 8.0 # the monitor records a tip when |tilt| exceeds this (a real tip reaches ~17 deg)
|
| 101 |
+
LEVEL_DEBOUNCE = 4 # monitor evaluations (0.1 s each) before plank_level changes
|
| 102 |
+
FLAT_COS = np.cos(np.radians(15.0))
|
| 103 |
+
SUPPORT_XY = 0.02 # plank on its support: its middle within 2 cm (horizontally) of the support's centre ...
|
| 104 |
+
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)
|
| 105 |
+
|
| 106 |
+
# ---------------------------------------------------------------- scripted motion
|
| 107 |
+
Z_CARRY = 0.17 # careful / adaptive: grasp point above the table while carrying (cube bottom 14.75 cm)
|
| 108 |
+
Z_CARRY_NAIVE = 0.15 # naive: just above the cubes already on the plank (their tops at 12 cm)
|
| 109 |
+
REL_GAP = 0.004 # release with the cube's bottom this far above the plank
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def plank_xml(name):
|
| 113 |
+
"""Board + end lips + keel (collision) and per colour a mark (5 visual-only geoms, moved per instance).
|
| 114 |
+
Long axis = body y."""
|
| 115 |
+
g = []
|
| 116 |
+
|
| 117 |
+
def box(nm, pos, size, rgba):
|
| 118 |
+
g.append(f'<geom name="{nm}" type="box" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(rgba)}" '
|
| 119 |
+
f'friction="{MU} 0.005 0.0001" density="900" group="0"/>')
|
| 120 |
+
g.append(f'<geom type="box" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(rgba)}" contype="0" '
|
| 121 |
+
f'conaffinity="0" group="1" mass="0"/>')
|
| 122 |
+
|
| 123 |
+
dark = (0.25, 0.16, 0.09, 1.0)
|
| 124 |
+
box(f"{name}_board", (0, 0, 0), (PL_HW, PL_HL, PL_HT), WOOD)
|
| 125 |
+
for k, s in enumerate((1, -1)):
|
| 126 |
+
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)
|
| 127 |
+
box(f"{name}_keel", (0, 0, -PL_HT - KEEL_H / 2), (PL_HW, KEEL_HW, KEEL_H / 2), dark)
|
| 128 |
+
for c in COLORS:
|
| 129 |
+
rgba = RGBA[c]
|
| 130 |
+
fill = tuple(0.55 + 0.45 * v for v in rgba[:3]) + (1.0,)
|
| 131 |
+
o, i, w = MARK_HALF, MARK_HALF - MARK_LINE, MARK_LINE
|
| 132 |
+
parts = [((0, 0, PL_HT + 0.0003), (o, o, 0.0003), fill),
|
| 133 |
+
((0, i + w / 2, PL_HT + 0.0008), (o, w / 2, 0.0003), rgba),
|
| 134 |
+
((0, -i - w / 2, PL_HT + 0.0008), (o, w / 2, 0.0003), rgba),
|
| 135 |
+
((i + w / 2, 0, PL_HT + 0.0008), (w / 2, o, 0.0003), rgba),
|
| 136 |
+
((-i - w / 2, 0, PL_HT + 0.0008), (w / 2, o, 0.0003), rgba)]
|
| 137 |
+
for k, (p, sz, col) in enumerate(parts):
|
| 138 |
+
g.append(f'<geom name="{name}_mk_{c}_{k}" type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" '
|
| 139 |
+
f'rgba="{_fmt(col)}" contype="0" conaffinity="0" group="1" mass="0"/>')
|
| 140 |
+
return _wrap(name, "\n ".join(g), PL_HT, float(np.hypot(PL_HL, PL_HW)))
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def ridge_xml(name):
|
| 144 |
+
"""Split support: two 1.5 cm blocks with a 1 cm slot between them; the plank rests on both and pivots on their outer
|
| 145 |
+
top edges (a 4 cm flat top). The plank's keel hangs in the slot, so the plank cannot wander along its length by
|
| 146 |
+
more than +-3 mm (it stays engaged at the full tip angle)."""
|
| 147 |
+
rgba = (0.35, 0.35, 0.38, 1.0)
|
| 148 |
+
bh = (RIDGE_HW - SLOT_HW) / 2
|
| 149 |
+
g = []
|
| 150 |
+
for k, sy in enumerate((1, -1)):
|
| 151 |
+
p, sz = (0, sy * (SLOT_HW + bh), RIDGE_H / 2), (RIDGE_HX, bh, RIDGE_H / 2)
|
| 152 |
+
g.append(f'<geom name="{name}_g{k}" type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(rgba)}" '
|
| 153 |
+
f'friction="{MU_RIDGE} 0.005 0.0001" group="0"/>')
|
| 154 |
+
g.append(f'<geom type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(rgba)}" contype="0" conaffinity="0" '
|
| 155 |
+
f'group="1"/>')
|
| 156 |
+
g = "\n ".join(g)
|
| 157 |
+
return f"""<mujoco model="{name}">
|
| 158 |
+
<worldbody>
|
| 159 |
+
<body>
|
| 160 |
+
<body name="object">
|
| 161 |
+
{g}
|
| 162 |
+
</body>
|
| 163 |
+
<site rgba="0 0 0 0" size="0.005" pos="0 0 0" name="bottom_site" />
|
| 164 |
+
<site rgba="0 0 0 0" size="0.005" pos="0 0 {RIDGE_H:.4f}" name="top_site" />
|
| 165 |
+
<site rgba="0 0 0 0" size="0.005" pos="{RIDGE_HX:.4f} {RIDGE_HW:.4f} 0" name="horizontal_radius_site" />
|
| 166 |
+
</body>
|
| 167 |
+
</worldbody>
|
| 168 |
+
</mujoco>"""
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def tip_ratio(items, plank_mass=PLANK_MASS, s=RIDGE_HW):
|
| 172 |
+
"""Static model of a loose plank on a flat-topped block: |sum m y| / ((M_plank + sum m) s); the plank tips when
|
| 173 |
+
this exceeds 1 (the combined centre of mass leaves the block's top). items: [(mass, y from the middle)]."""
|
| 174 |
+
if not items:
|
| 175 |
+
return 0.0
|
| 176 |
+
mom = sum(m * y for m, y in items)
|
| 177 |
+
return abs(mom) / ((plank_mass + sum(m for m, _ in items)) * s)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def _side(y):
|
| 181 |
+
return "near" if y > 0 else "far"
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def _along(v):
|
| 185 |
+
"""plank-frame y offset in robot-centric words (+y = toward the robot)"""
|
| 186 |
+
return f"{100 * abs(v):.1f} cm from its mark toward {'the robot' if v > 0 else 'the far end'}"
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class BoardSkills(Skills):
|
| 190 |
+
"""Skills that feed the task's per-step monitor."""
|
| 191 |
+
|
| 192 |
+
def __init__(self, env, task, recorder=None):
|
| 193 |
+
super().__init__(env, recorder=recorder)
|
| 194 |
+
self.task = task
|
| 195 |
+
|
| 196 |
+
def _act(self, dpos, drot, grip):
|
| 197 |
+
super()._act(dpos, drot, grip)
|
| 198 |
+
self.task.monitor_step()
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
@register_task
|
| 202 |
+
class BalanceBoard(LFFTask):
|
| 203 |
+
name = "lh_balance_board"
|
| 204 |
+
level = "L2"
|
| 205 |
+
category = "state_restoration"
|
| 206 |
+
capabilities = ("Perceive", "Reason", "Plan", "Restore")
|
| 207 |
+
protocol = "cross"
|
| 208 |
+
max_attempts = 3
|
| 209 |
+
agent_max_steps = 120 # careful zig-zag ~30-36 commands + re-placing four cubes (~30) + looking around
|
| 210 |
+
instruction = ("Put each coloured cube on the square mark of the same colour on the long plank. The plank lies loose "
|
| 211 |
+
"across a narrow block under its middle. At the end all four cubes must be on their marks and the "
|
| 212 |
+
"plank must still rest level on the block.")
|
| 213 |
+
instruction_indirect = ("Set the four coloured cubes onto the outlined squares of matching colour on the wooden "
|
| 214 |
+
"board that rests across the small grey block. When you are done, every cube must sit on "
|
| 215 |
+
"its square and the board must still rest level on the block.")
|
| 216 |
+
agent_object_names = ["red cube", "green cube", "blue cube", "yellow cube", "plank", "support block",
|
| 217 |
+
"red mark", "green mark", "blue mark", "yellow mark"]
|
| 218 |
+
|
| 219 |
+
# ------------------------------------------------------------ scene
|
| 220 |
+
def make_bddl(self):
|
| 221 |
+
pl = register_generated("LffLhBbPlank", plank_xml(PLANK_MODEL))
|
| 222 |
+
rg = register_generated("LffLhBbRidge", ridge_xml("lff_lh_bb_ridge"), free=False)
|
| 223 |
+
objs = [(PLANK, pl, "plank_region", (0.18, -0.01, 0.20, 0.01))]
|
| 224 |
+
e = CUBE_E / 2
|
| 225 |
+
for i, c in enumerate(COLORS):
|
| 226 |
+
cat = register_generated(f"LffLhBbCube{c.title()}",
|
| 227 |
+
box_xml(f"lff_lh_bb_cube_{c}", (e, e, e), RGBA[c], density=500.0,
|
| 228 |
+
friction=(MU, 0.005, 0.0001)).replace(
|
| 229 |
+
'solimp="0.998 0.998 0.001" solref="0.001 1"', ""))
|
| 230 |
+
objs.append((CUBES[c], cat, f"{c}_cube_region", (-0.32, -0.33 + 0.2 * i, -0.30, -0.31 + 0.2 * i)))
|
| 231 |
+
fx = [(RIDGE, rg, "ridge_region", (-0.12, 0.30, -0.10, 0.32))]
|
| 232 |
+
return write_bddl(self.name, "put each cube on its mark on the plank and keep the plank level", objs, fx)
|
| 233 |
+
|
| 234 |
+
def __init__(self, cam_res=None):
|
| 235 |
+
super().__init__(cam_res)
|
| 236 |
+
m = self.env.sim.model
|
| 237 |
+
self.ridge_bid = m.body_name2id(self.env.fixtures_dict[RIDGE].root_body)
|
| 238 |
+
self.plank_bid = envs.body_id(self.env, PLANK)
|
| 239 |
+
pre = f"{PLANK}_{PLANK_MODEL}"
|
| 240 |
+
self.mark_gids = {c: [m.geom_name2id(f"{pre}_mk_{c}_{k}") for k in range(5)] for c in COLORS}
|
| 241 |
+
self.mark_pos0 = {c: [m.geom_pos[g].copy() for g in self.mark_gids[c]] for c in COLORS}
|
| 242 |
+
self.cube_gids = {c: set(envs.obj_geom_ids(self.env, CUBES[c])) for c in COLORS}
|
| 243 |
+
self.plank_gids = set(envs.obj_geom_ids(self.env, PLANK))
|
| 244 |
+
self.robot_gids = set(envs.robot_geom_ids(self.env))
|
| 245 |
+
self.inst = None
|
| 246 |
+
self.mon = None
|
| 247 |
+
self.obs = [] # adaptive script: (configuration, tipped) observations, kept across the attempts of one run
|
| 248 |
+
|
| 249 |
+
def sample_instance(self, seed):
|
| 250 |
+
rng = np.random.default_rng(seed)
|
| 251 |
+
x0, y0 = float(rng.uniform(-0.18, -0.14)), float(rng.uniform(-0.03, 0.03))
|
| 252 |
+
perm = [str(c) for c in rng.permutation(COLORS)] # colour of the mark in SLOTS order
|
| 253 |
+
slot_of = {c: s for c, s in zip(perm, SLOTS)}
|
| 254 |
+
dist = dict(near_outer=float(rng.uniform(*D_OUTER)), near_inner=float(rng.uniform(*D_INNER)),
|
| 255 |
+
far_inner=-float(rng.uniform(*D_INNER)), far_outer=-float(rng.uniform(*D_OUTER)))
|
| 256 |
+
marks = {c: dist[slot_of[c]] for c in COLORS} # plank-frame y of each mark (+ = toward the robot)
|
| 257 |
+
hazard = bool((int(seed) * 7) % 20 < round(20 * P_HAZARD)) # balanced like l7_key_turn / lh_lid_box
|
| 258 |
+
r_h, r_l = float(rng.uniform(*R_HEAVY)), float(rng.uniform(*R_LIGHT))
|
| 259 |
+
light = {c: float(rng.uniform(*LIGHT_BENIGN)) for c in COLORS}
|
| 260 |
+
s, pm = RIDGE_HW, PLANK_MASS
|
| 261 |
+
if hazard:
|
| 262 |
+
# equal moments on both sides -> the finished layout is exactly balanced
|
| 263 |
+
dn, do = dist["near_inner"], dist["near_outer"]
|
| 264 |
+
y_h = r_h * pm * s / (dn - r_h * s) * dn # heavy on the near inner mark: moment r_h x tipping moment
|
| 265 |
+
x_l = r_l * pm * s / (do - r_l * s) * do
|
| 266 |
+
mass = {c: (y_h if "inner" in slot_of[c] else x_l) / abs(dist[slot_of[c]]) for c in COLORS}
|
| 267 |
+
else:
|
| 268 |
+
mass = light
|
| 269 |
+
# start: two cubes left and two right of the plank, 17-19 cm from its axis, at two depths (random places)
|
| 270 |
+
spots = [(dx, sy) for sy in (1.0, -1.0) for dx in (-0.08, 0.08)]
|
| 271 |
+
order = rng.permutation(4)
|
| 272 |
+
start = {c: [x0 + spots[j][0] + float(rng.uniform(-0.01, 0.01)),
|
| 273 |
+
y0 + spots[j][1] * float(rng.uniform(0.17, 0.19))] for c, j in zip(COLORS, order)}
|
| 274 |
+
start_yaw = {c: float(rng.uniform(-0.3, 0.3)) for c in COLORS}
|
| 275 |
+
heavy = sorted(c for c in COLORS if mass[c] > 0.1)
|
| 276 |
+
return dict(seed=int(seed), plank_xy=[x0, y0], marks=marks, slot_of=slot_of, hazard=hazard, mass=mass,
|
| 277 |
+
heavy=heavy, r_heavy=r_h if hazard else None, r_light=r_l if hazard else None, start=start,
|
| 278 |
+
start_yaw=start_yaw)
|
| 279 |
+
|
| 280 |
+
def apply_instance(self, inst):
|
| 281 |
+
self.inst = inst
|
| 282 |
+
env = self.env
|
| 283 |
+
m = env.sim.model
|
| 284 |
+
x0, y0 = inst["plank_xy"]
|
| 285 |
+
q = [np.cos(PLANK_YAW / 2), 0.0, 0.0, np.sin(PLANK_YAW / 2)]
|
| 286 |
+
m.body_pos[self.ridge_bid] = [x0, y0, TZ]
|
| 287 |
+
m.body_quat[self.ridge_bid] = q
|
| 288 |
+
envs.scale_mass(env, PLANK, PLANK_MASS)
|
| 289 |
+
_, da = envs.free_joint_addr(env, PLANK)
|
| 290 |
+
m.dof_damping[da + 3:da + 6] = PLANK_ROT_DAMP
|
| 291 |
+
for c in COLORS:
|
| 292 |
+
for g, p0 in zip(self.mark_gids[c], self.mark_pos0[c]):
|
| 293 |
+
m.geom_pos[g] = p0 + np.array([0.0, inst["marks"][c], 0.0])
|
| 294 |
+
envs.scale_mass(env, CUBES[c], inst["mass"][c])
|
| 295 |
+
envs.set_obj_pose(env, PLANK, [x0, y0, TZ + RIDGE_H + PL_HT + 0.0005], quat_wxyz=np.array(q))
|
| 296 |
+
for c in COLORS:
|
| 297 |
+
envs.place_upright(env, CUBES[c], inst["start"][c], yaw=inst["start_yaw"][c])
|
| 298 |
+
|
| 299 |
+
def reset_instance(self, inst, recorder=None):
|
| 300 |
+
self.mon = None
|
| 301 |
+
self.env.reset()
|
| 302 |
+
self.apply_instance(inst)
|
| 303 |
+
self.env.sim.forward()
|
| 304 |
+
envs.settle(self.env, 10)
|
| 305 |
+
self.plank_z0 = float(self.plank_pos()[2])
|
| 306 |
+
self.sk = BoardSkills(self.env, self, recorder=recorder)
|
| 307 |
+
self._init_monitor()
|
| 308 |
+
return self.sk
|
| 309 |
+
|
| 310 |
+
# ------------------------------------------------------------ state helpers
|
| 311 |
+
def plank_R(self):
|
| 312 |
+
return self.env.sim.data.body_xmat[self.plank_bid].reshape(3, 3).copy()
|
| 313 |
+
|
| 314 |
+
def plank_pos(self):
|
| 315 |
+
return self.env.sim.data.body_xpos[self.plank_bid].copy()
|
| 316 |
+
|
| 317 |
+
def tilt_deg(self):
|
| 318 |
+
"""+ = the plank's end toward the robot is up"""
|
| 319 |
+
return float(np.degrees(np.arcsin(np.clip(self.plank_R()[2, 1], -1.0, 1.0))))
|
| 320 |
+
|
| 321 |
+
def is_level(self, deg=LEVEL_DEG):
|
| 322 |
+
return abs(self.tilt_deg()) <= deg
|
| 323 |
+
|
| 324 |
+
def on_support(self):
|
| 325 |
+
"""the plank still rests on the support block (10-11: Sonnet lh2 s3001 pushed it off onto the table, where it
|
| 326 |
+
lies level, and loaded the cubes there; 'level' alone accepted that)"""
|
| 327 |
+
p, r = self.plank_pos(), self.env.sim.data.body_xpos[self.ridge_bid]
|
| 328 |
+
return bool(np.linalg.norm(p[:2] - r[:2]) <= SUPPORT_XY and p[2] >= self.plank_z0 - SUPPORT_DZ)
|
| 329 |
+
|
| 330 |
+
def in_plank(self, p):
|
| 331 |
+
"""world point -> plank frame (x across, y along from the middle, z above the plank's mid-plane)"""
|
| 332 |
+
return self.plank_R().T @ (np.asarray(p, float) - self.plank_pos())
|
| 333 |
+
|
| 334 |
+
def mark_world(self, c):
|
| 335 |
+
return self.plank_pos() + self.plank_R() @ np.array([0.0, self.inst["marks"][c], PL_HT])
|
| 336 |
+
|
| 337 |
+
def cube_pos(self, c):
|
| 338 |
+
return envs.obj_pos(self.env, CUBES[c])
|
| 339 |
+
|
| 340 |
+
def held(self, c):
|
| 341 |
+
return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper,
|
| 342 |
+
object_geoms=self.env.objects_dict[CUBES[c]]))
|
| 343 |
+
|
| 344 |
+
def on_plank(self, c):
|
| 345 |
+
"""resting on the plank's top (plank frame), anywhere along it"""
|
| 346 |
+
q = self.in_plank(self.cube_pos(c))
|
| 347 |
+
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)
|
| 348 |
+
|
| 349 |
+
def mark_offset(self, c):
|
| 350 |
+
q = self.in_plank(self.cube_pos(c))
|
| 351 |
+
return np.array([q[0], q[1] - self.inst["marks"][c]])
|
| 352 |
+
|
| 353 |
+
def _flat(self, c):
|
| 354 |
+
Rc = self.env.sim.data.body_xmat[envs.body_id(self.env, CUBES[c])].reshape(3, 3)
|
| 355 |
+
return bool(np.max(np.abs(self.plank_R()[:, 2] @ Rc)) >= FLAT_COS)
|
| 356 |
+
|
| 357 |
+
def on_mark(self, c, tol=TOL):
|
| 358 |
+
if not self.on_plank(c):
|
| 359 |
+
return False
|
| 360 |
+
o = self.mark_offset(c)
|
| 361 |
+
return bool(np.max(np.abs(o)) <= tol and self._flat(c) and not self.held(c))
|
| 362 |
+
|
| 363 |
+
def stage_values(self):
|
| 364 |
+
v = {f"{c}_on_mark": self.on_mark(c) for c in COLORS}
|
| 365 |
+
v["plank_level"] = self.is_level()
|
| 366 |
+
v["plank_on_support"] = self.on_support()
|
| 367 |
+
return v
|
| 368 |
+
|
| 369 |
+
# ------------------------------------------------------------ per-step monitor (server log only)
|
| 370 |
+
def _init_monitor(self):
|
| 371 |
+
self.mon = dict(state={f"{c}_on_mark": False for c in COLORS} | {"plank_level": True, "plank_on_support": True}, ever=set(),
|
| 372 |
+
lost=set(), events=[], step=0, last_touch={c: None for c in COLORS},
|
| 373 |
+
held_prev={c: False for c in COLORS}, last_release=None, tipping=False, tips=[],
|
| 374 |
+
level_cnt=0, calm=0, tilt_max=0.0, win_max=0.0)
|
| 375 |
+
|
| 376 |
+
def _robot_touches(self):
|
| 377 |
+
"""cubes touched by the robot or by a cube the robot is carrying, in this control step"""
|
| 378 |
+
d = self.env.sim.data
|
| 379 |
+
out = set()
|
| 380 |
+
carried = [c for c in COLORS if self.mon["held_prev"][c]]
|
| 381 |
+
hit = {c: self.robot_gids.union(*[self.cube_gids[h] for h in carried if h != c]) for c in COLORS}
|
| 382 |
+
for i in range(d.ncon):
|
| 383 |
+
con = d.contact[i]
|
| 384 |
+
for c in COLORS:
|
| 385 |
+
g = self.cube_gids[c]
|
| 386 |
+
if (con.geom1 in g and con.geom2 in hit[c]) or (con.geom2 in g and con.geom1 in hit[c]):
|
| 387 |
+
out.add(c)
|
| 388 |
+
return out
|
| 389 |
+
|
| 390 |
+
def monitor_step(self):
|
| 391 |
+
mon = self.mon
|
| 392 |
+
if mon is None or self.sk is None:
|
| 393 |
+
return
|
| 394 |
+
mon["step"] += 1
|
| 395 |
+
step = self.sk.n_steps
|
| 396 |
+
for c in self._robot_touches():
|
| 397 |
+
mon["last_touch"][c] = step
|
| 398 |
+
tilt = self.tilt_deg()
|
| 399 |
+
mon["tilt_max"] = max(mon["tilt_max"], abs(tilt))
|
| 400 |
+
mon["win_max"] = max(mon["win_max"], abs(tilt))
|
| 401 |
+
if not mon["tipping"] and abs(tilt) > TIP_DEG:
|
| 402 |
+
# one tip episode = from |tilt| > 8 deg until the plank has stayed level for 1 s (the swing back and any
|
| 403 |
+
# rocking belong to the same episode)
|
| 404 |
+
mon["tipping"] = True
|
| 405 |
+
mon["calm"] = 0
|
| 406 |
+
rel = mon["last_release"]
|
| 407 |
+
tip = dict(step=step, down="near" if tilt < 0 else "far",
|
| 408 |
+
after_release=(rel[0] if rel is not None and step - rel[1] <= 60 else None),
|
| 409 |
+
on_plank=[c for c in COLORS if self.on_plank(c)],
|
| 410 |
+
on_mark=[c for c in COLORS if mon["state"][f"{c}_on_mark"]])
|
| 411 |
+
mon["tips"].append(tip)
|
| 412 |
+
mon["events"].append(dict(step=step, pred="plank", ev="tipped", down=tip["down"],
|
| 413 |
+
after_release=tip["after_release"], on_mark=tip["on_mark"]))
|
| 414 |
+
elif mon["tipping"]:
|
| 415 |
+
mon["calm"] = mon["calm"] + 1 if abs(tilt) < LEVEL_DEG else 0
|
| 416 |
+
if mon["calm"] >= 20:
|
| 417 |
+
mon["tipping"] = False
|
| 418 |
+
if mon["step"] % 2:
|
| 419 |
+
return # predicates every other control step (0.1 s)
|
| 420 |
+
for c in COLORS:
|
| 421 |
+
h = self.held(c)
|
| 422 |
+
if mon["held_prev"][c] and not h:
|
| 423 |
+
mon["last_release"] = (c, step)
|
| 424 |
+
mon["held_prev"][c] = h
|
| 425 |
+
key = f"{c}_on_mark"
|
| 426 |
+
was = mon["state"][key]
|
| 427 |
+
now = self.on_mark(c, TOL if not was else TOL_LOSE)
|
| 428 |
+
if now != was:
|
| 429 |
+
self._event(key, now, step, c)
|
| 430 |
+
lv = self.is_level()
|
| 431 |
+
if lv != mon["state"]["plank_level"]:
|
| 432 |
+
mon["level_cnt"] += 1
|
| 433 |
+
if mon["level_cnt"] >= LEVEL_DEBOUNCE:
|
| 434 |
+
mon["level_cnt"] = 0
|
| 435 |
+
self._event("plank_level", lv, step, None)
|
| 436 |
+
else:
|
| 437 |
+
mon["level_cnt"] = 0
|
| 438 |
+
sup = self.on_support()
|
| 439 |
+
if sup != mon["state"]["plank_on_support"]:
|
| 440 |
+
self._event("plank_on_support", sup, step, None)
|
| 441 |
+
|
| 442 |
+
def _event(self, key, now, step, color):
|
| 443 |
+
mon = self.mon
|
| 444 |
+
mon["state"][key] = now
|
| 445 |
+
if now:
|
| 446 |
+
ev = "restored" if key in mon["lost"] else "achieved"
|
| 447 |
+
mon["ever"].add(key)
|
| 448 |
+
mon["lost"].discard(key)
|
| 449 |
+
mon["events"].append(dict(step=step, pred=key, ev=ev))
|
| 450 |
+
return
|
| 451 |
+
cause = "other"
|
| 452 |
+
recent_tip = bool(mon["tips"]) and (mon["tipping"] or step - mon["tips"][-1]["step"] <= 60)
|
| 453 |
+
if color is None:
|
| 454 |
+
cause = "tip" if recent_tip else "other"
|
| 455 |
+
elif self.held(color):
|
| 456 |
+
cause = "picked_up"
|
| 457 |
+
elif recent_tip:
|
| 458 |
+
cause = "tip"
|
| 459 |
+
elif mon["last_touch"][color] is not None and step - mon["last_touch"][color] <= 60:
|
| 460 |
+
cause = "robot"
|
| 461 |
+
mon["lost"].add(key)
|
| 462 |
+
mon["events"].append(dict(step=step, pred=key, ev="lost", cause=cause, tilt=round(self.tilt_deg(), 1)))
|
| 463 |
+
|
| 464 |
+
# ------------------------------------------------------------ outcome
|
| 465 |
+
def _static(self):
|
| 466 |
+
d = self.env.sim.data
|
| 467 |
+
for name in [CUBES[c] for c in COLORS] + [PLANK]:
|
| 468 |
+
_, da = envs.free_joint_addr(self.env, name)
|
| 469 |
+
if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.3:
|
| 470 |
+
return False
|
| 471 |
+
return True
|
| 472 |
+
|
| 473 |
+
def _where(self, c):
|
| 474 |
+
"""robot-centric description of where a cube that is not on its mark is"""
|
| 475 |
+
if self.held(c):
|
| 476 |
+
return "is still held by the gripper"
|
| 477 |
+
if self.on_plank(c):
|
| 478 |
+
o = self.mark_offset(c)
|
| 479 |
+
return f"lies on the plank, {_along(o[1])}"
|
| 480 |
+
p = self.cube_pos(c)
|
| 481 |
+
if np.linalg.norm(p[:2] - np.asarray(self.inst["start"][c])) < 0.02:
|
| 482 |
+
return "is still where it started on the table"
|
| 483 |
+
q = self.in_plank(p)
|
| 484 |
+
if abs(q[1]) > PL_HL:
|
| 485 |
+
return f"lies on the table beyond {END_WORD[_side(q[1])]} of the plank"
|
| 486 |
+
return "lies on the table beside the plank"
|
| 487 |
+
|
| 488 |
+
def outcome(self, inst):
|
| 489 |
+
envs.settle(self.env, 30)
|
| 490 |
+
mon = self.mon
|
| 491 |
+
vals = self.stage_values()
|
| 492 |
+
static = self._static()
|
| 493 |
+
held = [c for c in COLORS if self.held(c)]
|
| 494 |
+
success = bool(all(vals.values()) and static and not held)
|
| 495 |
+
regress = [e for e in mon["events"] if e["ev"] == "lost"]
|
| 496 |
+
restored = [e for e in mon["events"] if e["ev"] == "restored"]
|
| 497 |
+
parts = []
|
| 498 |
+
off = [c for c in COLORS if not vals[f"{c}_on_mark"]]
|
| 499 |
+
if success:
|
| 500 |
+
failure = None
|
| 501 |
+
parts.append("All four cubes are on their marks and the plank is level.")
|
| 502 |
+
else:
|
| 503 |
+
lost_final = [c for c in off if f"{c}_on_mark" in mon["ever"]]
|
| 504 |
+
failure = ("held" if held else "plank_off_support" if not vals["plank_on_support"] else
|
| 505 |
+
"regressed" if lost_final else "incomplete" if off else
|
| 506 |
+
"not_level" if not vals["plank_level"] else "not_static")
|
| 507 |
+
for c in off:
|
| 508 |
+
txt = f"The {c} cube is not on its mark: it {self._where(c)}"
|
| 509 |
+
if f"{c}_on_mark" in mon["ever"]:
|
| 510 |
+
why = [e for e in regress if e["pred"] == f"{c}_on_mark"]
|
| 511 |
+
cause = why[-1].get("cause") if why else None
|
| 512 |
+
txt += {"tip": " (it had been on its mark; it slid off when the plank tipped).",
|
| 513 |
+
"robot": " (it had been on its mark; the robot knocked it off).",
|
| 514 |
+
"picked_up": " (it had been on its mark; it was picked up again)."}.get(
|
| 515 |
+
cause, " (it had been on its mark earlier).")
|
| 516 |
+
else:
|
| 517 |
+
txt += " (it was never on its mark)."
|
| 518 |
+
parts.append(txt)
|
| 519 |
+
if not vals["plank_on_support"]:
|
| 520 |
+
parts.append("The plank no longer rests on the support block: it was pushed or knocked off it.")
|
| 521 |
+
if not vals["plank_level"]:
|
| 522 |
+
t = self.tilt_deg()
|
| 523 |
+
parts.append(f"The plank is not level: it is tilted {abs(t):.0f} degrees, "
|
| 524 |
+
f"{END_WORD['near' if t < 0 else 'far']} down.")
|
| 525 |
+
if not static and all(vals.values()):
|
| 526 |
+
parts.append("Something was still moving at the end.")
|
| 527 |
+
if mon["tips"]:
|
| 528 |
+
descr = []
|
| 529 |
+
for tp in mon["tips"]:
|
| 530 |
+
d = f"{END_WORD[tp['down']]} down"
|
| 531 |
+
if tp["after_release"]:
|
| 532 |
+
d += f" right after the {tp['after_release']} cube was set down"
|
| 533 |
+
descr.append(d)
|
| 534 |
+
parts.append(f"During the attempt the plank tipped {len(mon['tips'])} time(s): " + "; ".join(descr) + ".")
|
| 535 |
+
return dict(success=success, failure=failure, stages=vals, static=bool(static), held=held,
|
| 536 |
+
events=mon["events"], n_regressions=len(regress), n_restored=len(restored),
|
| 537 |
+
n_tips=len(mon["tips"]), tips=mon["tips"], tilt_max=round(mon["tilt_max"], 1),
|
| 538 |
+
tilt_final=round(self.tilt_deg(), 1), hazard=bool(inst["hazard"]),
|
| 539 |
+
mark_offsets_cm={c: (100 * self.mark_offset(c)).round(1).tolist() for c in COLORS},
|
| 540 |
+
on_plank={c: self.on_plank(c) for c in COLORS}, detail=" ".join(parts))
|
| 541 |
+
|
| 542 |
+
# ------------------------------------------------------------ scripted policies (perfect perception)
|
| 543 |
+
def _grasp_yaw(self, c):
|
| 544 |
+
R = self.env.sim.data.body_xmat[envs.body_id(self.env, CUBES[c])].reshape(3, 3)
|
| 545 |
+
i = int(np.argmin(np.abs(R[2])))
|
| 546 |
+
yaw = float(np.arctan2(R[1, i], R[0, i]))
|
| 547 |
+
return float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4)
|
| 548 |
+
|
| 549 |
+
def _y_on_plank(self):
|
| 550 |
+
"""cubes resting on the plank now -> their position along it"""
|
| 551 |
+
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)}
|
| 552 |
+
|
| 553 |
+
def plank_calm(self):
|
| 554 |
+
_, da = envs.free_joint_addr(self.env, PLANK)
|
| 555 |
+
return abs(self.tilt_deg()) < 1.0 and float(np.linalg.norm(self.env.sim.data.qvel[da + 3:da + 6])) < 0.05
|
| 556 |
+
|
| 557 |
+
def wait_calm(self, max_steps=60):
|
| 558 |
+
"""hold the arm still until the plank has stopped swinging (a careful agent looks before it acts)"""
|
| 559 |
+
n = 0
|
| 560 |
+
for _ in range(max_steps):
|
| 561 |
+
if self.plank_calm():
|
| 562 |
+
n += 1
|
| 563 |
+
if n >= 5:
|
| 564 |
+
return True
|
| 565 |
+
else:
|
| 566 |
+
n = 0
|
| 567 |
+
self.sk.hold(1)
|
| 568 |
+
return False
|
| 569 |
+
|
| 570 |
+
def pick(self, c, z_carry):
|
| 571 |
+
sk = self.sk
|
| 572 |
+
p = self.cube_pos(c)
|
| 573 |
+
yaw = self._grasp_yaw(c)
|
| 574 |
+
sk.set_gripper(False, steps=8)
|
| 575 |
+
sk.move_to([p[0], p[1], max(TZ + z_carry, p[2] + 0.06)], yaw=yaw)
|
| 576 |
+
sk.move_to([p[0], p[1], p[2]], tol=0.003)
|
| 577 |
+
sk.set_gripper(True, steps=15)
|
| 578 |
+
sk.move_to([p[0], p[1], TZ + z_carry], speed=0.3)
|
| 579 |
+
if not self.held(c):
|
| 580 |
+
sk.set_gripper(False, steps=8)
|
| 581 |
+
sk.move_to([p[0], p[1], TZ + z_carry])
|
| 582 |
+
return False
|
| 583 |
+
return True
|
| 584 |
+
|
| 585 |
+
def put(self, c, z_carry=Z_CARRY, noise=None, record=False, careful=False):
|
| 586 |
+
"""Pick cube c wherever it is and put it on its mark: carry it over the mark, lower it until its bottom is
|
| 587 |
+
REL_GAP above the plank, release, lift. Returns whether the plank tipped (|tilt| > TIP_DEG) during the
|
| 588 |
+
placement, or None if the cube could not be picked. record=True appends the observation (cubes on the plank
|
| 589 |
+
right before the release + this one on its mark, tipped?) for the adaptive script."""
|
| 590 |
+
for _ in range(2):
|
| 591 |
+
if self.pick(c, z_carry):
|
| 592 |
+
break
|
| 593 |
+
else:
|
| 594 |
+
return None
|
| 595 |
+
sk = self.sk
|
| 596 |
+
d = self.mark_world(c)
|
| 597 |
+
if noise is not None:
|
| 598 |
+
d = d + np.array([noise[0], noise[1], 0.0])
|
| 599 |
+
sk.move_to([d[0], d[1], TZ + z_carry], yaw=0.0)
|
| 600 |
+
if careful:
|
| 601 |
+
self.wait_calm()
|
| 602 |
+
d = self.mark_world(c) + (np.array([noise[0], noise[1], 0.0]) if noise is not None else 0.0)
|
| 603 |
+
sk.move_to([d[0], d[1], d[2] + CUBE_E / 2 + REL_GAP], tol=0.003)
|
| 604 |
+
was_level = self.plank_calm()
|
| 605 |
+
conf = self._y_on_plank()
|
| 606 |
+
conf[c] = float(self.inst["marks"][c])
|
| 607 |
+
self.mon["win_max"] = abs(self.tilt_deg())
|
| 608 |
+
sk.set_gripper(False, steps=12)
|
| 609 |
+
sk.move_to([d[0], d[1], TZ + z_carry])
|
| 610 |
+
sk.hold(12)
|
| 611 |
+
tipped = self.mon["win_max"] > TIP_DEG
|
| 612 |
+
if tipped:
|
| 613 |
+
envs.settle(self.env, 30) # let the cubes slide down
|
| 614 |
+
if record and was_level:
|
| 615 |
+
self.obs.append(dict(conf=conf, tipped=bool(tipped), after=c))
|
| 616 |
+
return tipped
|
| 617 |
+
|
| 618 |
+
def park(self, c):
|
| 619 |
+
"""take cube c off the plank and set it on a free spot of the table beside the plank"""
|
| 620 |
+
x0, y0 = self.inst["plank_xy"]
|
| 621 |
+
others = [self.cube_pos(o)[:2] for o in COLORS if o != c]
|
| 622 |
+
cands = [np.array([x0 + dx, y0 + sy * dy]) for sy in (1, -1) for dy in (0.18, 0.25)
|
| 623 |
+
for dx in (-0.12, -0.04, 0.04, 0.12)]
|
| 624 |
+
best = max(cands, key=lambda q: min(np.linalg.norm(q - o) for o in others))
|
| 625 |
+
if not self.pick(c, Z_CARRY):
|
| 626 |
+
return False
|
| 627 |
+
sk = self.sk
|
| 628 |
+
sk.move_to([best[0], best[1], TZ + Z_CARRY], yaw=0.0)
|
| 629 |
+
sk.move_to([best[0], best[1], TZ + CUBE_E / 2 + 0.004], tol=0.003)
|
| 630 |
+
sk.set_gripper(False, steps=12)
|
| 631 |
+
sk.move_to([best[0], best[1], TZ + Z_CARRY])
|
| 632 |
+
return True
|
| 633 |
+
|
| 634 |
+
# ---- planning with the static model
|
| 635 |
+
def plan(self, todo, hyps):
|
| 636 |
+
"""Best order to (re)place the cubes in `todo`, given the cubes now on the plank, minimising the worst tip ratio
|
| 637 |
+
over the mass hypotheses `hyps` (list of {colour: kg}). A cube that is on the plank off its mark is lifted
|
| 638 |
+
(its moment removed) and then set on its mark. Returns (order, worst ratio)."""
|
| 639 |
+
cur0 = self._y_on_plank()
|
| 640 |
+
best, best_w = list(todo), np.inf
|
| 641 |
+
for order in itertools.permutations(todo):
|
| 642 |
+
w = 0.0
|
| 643 |
+
for mass in hyps:
|
| 644 |
+
cur = dict(cur0)
|
| 645 |
+
for c in order:
|
| 646 |
+
if c in cur:
|
| 647 |
+
del cur[c]
|
| 648 |
+
w = max(w, tip_ratio([(mass[o], y) for o, y in cur.items()]))
|
| 649 |
+
cur[c] = self.inst["marks"][c]
|
| 650 |
+
w = max(w, tip_ratio([(mass[o], y) for o, y in cur.items()]))
|
| 651 |
+
if w < best_w - 1e-9:
|
| 652 |
+
best, best_w = list(order), w
|
| 653 |
+
return best, best_w
|
| 654 |
+
|
| 655 |
+
def hypotheses(self, use_obs=True):
|
| 656 |
+
"""Heavy / light assignments (nominal masses) that (1) leave the finished layout balanced, (2) admit a loading
|
| 657 |
+
order that never tips the plank (the task is solvable) and (3) agree with every observed placement (tipped or
|
| 658 |
+
not, with a +-10 % band in which either outcome counts as consistent). Falls back to (1)+(2) if no assignment
|
| 659 |
+
agrees with all observations."""
|
| 660 |
+
marks = self.inst["marks"]
|
| 661 |
+
prior = []
|
| 662 |
+
for k in range(5):
|
| 663 |
+
for heavy in itertools.combinations(COLORS, k):
|
| 664 |
+
mass = {c: (H_EST if c in heavy else L_EST) for c in COLORS}
|
| 665 |
+
if tip_ratio([(mass[c], marks[c]) for c in COLORS]) > 0.6:
|
| 666 |
+
continue
|
| 667 |
+
for order in itertools.permutations(COLORS):
|
| 668 |
+
cur, w = [], 0.0
|
| 669 |
+
for c in order:
|
| 670 |
+
cur.append((mass[c], marks[c]))
|
| 671 |
+
w = max(w, tip_ratio(cur))
|
| 672 |
+
if w <= 0.9:
|
| 673 |
+
prior.append(mass)
|
| 674 |
+
break
|
| 675 |
+
if not use_obs:
|
| 676 |
+
return prior
|
| 677 |
+
post = []
|
| 678 |
+
for mass in prior:
|
| 679 |
+
if all(not ((ob["tipped"] and r < 0.9) or (not ob["tipped"] and r > 1.1))
|
| 680 |
+
for ob in self.obs for r in [tip_ratio([(mass[o], y) for o, y in ob["conf"].items()])]):
|
| 681 |
+
post.append(mass)
|
| 682 |
+
return post or prior
|
| 683 |
+
|
| 684 |
+
def unload_until_level(self, max_moves=4):
|
| 685 |
+
"""while the plank is tipped: take the cube farthest out on its low side off the plank"""
|
| 686 |
+
for _ in range(max_moves):
|
| 687 |
+
envs.settle(self.env, 20)
|
| 688 |
+
self.wait_calm()
|
| 689 |
+
if self.is_level():
|
| 690 |
+
return True
|
| 691 |
+
t = self.tilt_deg()
|
| 692 |
+
yo = self._y_on_plank()
|
| 693 |
+
low = [c for c, y in yo.items() if (y > 0) == (t < 0)]
|
| 694 |
+
if not low:
|
| 695 |
+
return self.is_level()
|
| 696 |
+
self.park(min(low, key=lambda o: abs(yo[o]))) # the top of the pile first: the hand clears the others
|
| 697 |
+
envs.settle(self.env, 20)
|
| 698 |
+
self.wait_calm()
|
| 699 |
+
return self.is_level()
|
| 700 |
+
|
| 701 |
+
def restore(self, hyps_fn, rounds=3, record=False):
|
| 702 |
+
"""Check every stage; if something is wrong: unload the low end if the plank is tipped, then (re)place every
|
| 703 |
+
cube that is not on its mark in the order the static model rates safest under the current mass hypotheses;
|
| 704 |
+
start over after a tip. Up to `rounds` passes."""
|
| 705 |
+
for _ in range(rounds):
|
| 706 |
+
envs.settle(self.env, 20)
|
| 707 |
+
if all(self.stage_values().values()):
|
| 708 |
+
return True
|
| 709 |
+
self.unload_until_level()
|
| 710 |
+
todo = [c for c in COLORS if not self.on_mark(c)]
|
| 711 |
+
if not todo:
|
| 712 |
+
continue
|
| 713 |
+
hyps = hyps_fn()
|
| 714 |
+
order, worst = self.plan(todo, hyps)
|
| 715 |
+
if worst > 0.9: # cubes left on the plank make every order risky: clear it and start from empty
|
| 716 |
+
for c in [c for c in COLORS if self.on_plank(c)]:
|
| 717 |
+
self.park(c)
|
| 718 |
+
order, worst = self.plan(list(COLORS), hyps)
|
| 719 |
+
for c in order:
|
| 720 |
+
if self.on_mark(c):
|
| 721 |
+
continue
|
| 722 |
+
if self.put(c, Z_CARRY, record=record, careful=True):
|
| 723 |
+
break # tipped: look again
|
| 724 |
+
envs.settle(self.env, 20)
|
| 725 |
+
return all(self.stage_values().values())
|
| 726 |
+
|
| 727 |
+
def naive_order(self, noise_sd=0.0, rng=None):
|
| 728 |
+
"""nearest cube first, starting from the gripper's position and then from each mark just loaded"""
|
| 729 |
+
p = self.sk.eef_pos()[:2]
|
| 730 |
+
left, order = list(COLORS), []
|
| 731 |
+
while left:
|
| 732 |
+
dist = {c: np.linalg.norm(self.cube_pos(c)[:2] - p) + (rng.normal(0, noise_sd) if rng is not None else 0.0)
|
| 733 |
+
for c in left}
|
| 734 |
+
c = min(left, key=dist.get)
|
| 735 |
+
order.append(c)
|
| 736 |
+
left.remove(c)
|
| 737 |
+
p = self.mark_world(c)[:2]
|
| 738 |
+
return order
|
| 739 |
+
|
| 740 |
+
def slot_order(self, kind):
|
| 741 |
+
so = {s: c for c, s in self.inst["slot_of"].items()}
|
| 742 |
+
seq = dict(end2end=SLOTS, alt_outer=("near_outer", "far_outer", "near_inner", "far_inner"),
|
| 743 |
+
alt_inner=("near_inner", "far_inner", "near_outer", "far_outer"))[kind]
|
| 744 |
+
return [so[s] for s in seq]
|
| 745 |
+
|
| 746 |
+
def execute(self, inst, params):
|
| 747 |
+
rng = np.random.default_rng(params.get("seed", 0))
|
| 748 |
+
mode = params["mode"]
|
| 749 |
+
if mode == "plan":
|
| 750 |
+
hyps = [dict(inst["mass"])] if params.get("true_masses") else self.hypotheses()
|
| 751 |
+
order, _ = self.plan(list(COLORS), hyps)
|
| 752 |
+
elif mode in ("end2end", "alt_outer", "alt_inner"):
|
| 753 |
+
order = self.slot_order(mode)
|
| 754 |
+
else: # nearest first (naive / blind)
|
| 755 |
+
order = self.naive_order(params.get("order_noise", 0.0), rng)
|
| 756 |
+
noise = params.get("noise", 0.0)
|
| 757 |
+
z_carry = Z_CARRY if params.get("careful") else Z_CARRY_NAIVE
|
| 758 |
+
for c in order:
|
| 759 |
+
nz = rng.uniform(-noise, noise, 2) if noise else None
|
| 760 |
+
tipped = self.put(c, z_carry, noise=nz, record=params.get("record", False), careful=params.get("careful", False))
|
| 761 |
+
if tipped and params.get("check_each"):
|
| 762 |
+
break # look at what happened, then restore below
|
| 763 |
+
if params.get("check"):
|
| 764 |
+
hyps_fn = (lambda: [dict(inst["mass"])]) if params.get("true_masses") else self.hypotheses
|
| 765 |
+
self.restore(hyps_fn, record=params.get("record", False))
|
| 766 |
+
self.sk.hold(10)
|
| 767 |
+
return order
|
| 768 |
+
|
| 769 |
+
def default_params(self, inst):
|
| 770 |
+
return dict(mode="nearest", check=False)
|
| 771 |
+
|
| 772 |
+
def oracle_params(self, inst):
|
| 773 |
+
return dict(mode="plan", true_masses=True, careful=True, check=True)
|
| 774 |
+
|
| 775 |
+
def adapt_params(self, inst, history):
|
| 776 |
+
"""from attempt 2: load in the order the observations of earlier attempts make safest, check after every
|
| 777 |
+
placement and restore at the end"""
|
| 778 |
+
return dict(mode="plan", careful=True, check=True, check_each=True, record=True)
|
| 779 |
+
|
| 780 |
+
def blind_params(self, inst, attempt, rng):
|
| 781 |
+
"""nearest-first again with small random variation (order noise, 4 mm placement noise), no history, no check"""
|
| 782 |
+
return dict(mode="nearest", check=False, order_noise=0.03, noise=0.004, seed=int(rng.integers(1 << 30)))
|
| 783 |
+
|
| 784 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 785 |
+
k = k or self.max_attempts
|
| 786 |
+
rng = np.random.default_rng(seed)
|
| 787 |
+
history = []
|
| 788 |
+
self.obs = []
|
| 789 |
+
for a in range(k):
|
| 790 |
+
self.reset_instance(inst)
|
| 791 |
+
if kind == "oracle":
|
| 792 |
+
params = self.oracle_params(inst)
|
| 793 |
+
elif kind == "naive":
|
| 794 |
+
params = self.default_params(inst)
|
| 795 |
+
elif kind == "adaptive": # attempt 1: natural order, but look after every placement and restore
|
| 796 |
+
params = (dict(mode="nearest", check=True, check_each=True, record=True) if a == 0 else
|
| 797 |
+
self.adapt_params(inst, history))
|
| 798 |
+
elif kind == "blind":
|
| 799 |
+
params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
|
| 800 |
+
elif kind in ("end2end", "alt_outer", "alt_inner"): # extra controls: other natural orders, no check
|
| 801 |
+
params = dict(mode=kind, check=False)
|
| 802 |
+
elif kind == "oracle_noise": # extra control: the oracle with +-5 mm (uniform) placement noise
|
| 803 |
+
params = dict(self.oracle_params(inst), noise=0.005, seed=int(rng.integers(1 << 30)))
|
| 804 |
+
elif kind == "switch": # extra control: no in-attempt repair, learn the order across attempts only
|
| 805 |
+
params = (dict(mode="nearest", check=False, record=True) if a == 0 else
|
| 806 |
+
dict(mode="plan", careful=True, check=False, record=True))
|
| 807 |
+
else:
|
| 808 |
+
raise ValueError(kind)
|
| 809 |
+
order = self.execute(inst, params)
|
| 810 |
+
out = self.outcome(inst)
|
| 811 |
+
out["order"] = order
|
| 812 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 813 |
+
if on_attempt:
|
| 814 |
+
on_attempt(a, params, out)
|
| 815 |
+
if out["success"] or kind in ("oracle", "oracle_noise", "naive", "end2end", "alt_outer", "alt_inner"):
|
| 816 |
+
break
|
| 817 |
+
return history
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/lh_bridge.py
ADDED
|
@@ -0,0 +1,1101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""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
|
| 2 |
+
parked right behind the bridge site, and once the plank is down the agent's natural reach for it knocks the bridge down,
|
| 3 |
+
which must be rebuilt before the task can be finished.
|
| 4 |
+
|
| 5 |
+
Category: state_restoration, long-horizon self-inflicted regression. The user's example verbatim: "build a bridge;
|
| 6 |
+
while working you knock over a foundation you already built and must rebuild it before continuing".
|
| 7 |
+
|
| 8 |
+
v1 -> v2 (after the Sonnet 5.5 pilot lh1: only 1 of 3 instances was ever disturbed; Sonnet carried 12-20 cm high and
|
| 9 |
+
lifted over built pillars, so the v1 mechanism -- sweeping a pillar with a block carried low -- rarely happened; the one
|
| 10 |
+
disturbance was the hand landing on the plank while going for the red cube): the car now starts in the gap between the
|
| 11 |
+
two squares, 5.5-9 cm behind the bridge line (right behind where the plank will lie); a spare fifth block; the bridge
|
| 12 |
+
4-7 cm further from the robot and the plank nearer, so that knocked parts stay within reach; softer contacts for the
|
| 13 |
+
bridge parts (the stiff default made collapsing blocks fly 30-90 cm); the naive reference imitates Sonnet's measured
|
| 14 |
+
motion style instead of the v1 low-transit script (kept as naive_v1).
|
| 15 |
+
|
| 16 |
+
Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): two coloured square
|
| 17 |
+
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
|
| 18 |
+
(4 cm) in the gap between them, 5.5-9 cm behind the line through the squares (+-3 cm sideways, yaw +-20 deg); five
|
| 19 |
+
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
|
| 20 |
+
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.
|
| 21 |
+
|
| 22 |
+
Stages (order-free predicates, evaluated after every control step by a monitor; events are debounced over 6 steps):
|
| 23 |
+
S1 two blocks stacked on the blue square (lower block resting on the table within 2.5 cm of the square's centre,
|
| 24 |
+
upper block resting on it within 2.5 cm; any face down, cubes have no "right way up")
|
| 25 |
+
S2 the same on the green square
|
| 26 |
+
S3 the plank rests on the top blocks of both pillars: in contact with both, not with the table, tilt <= 10 deg
|
| 27 |
+
S4 the red cube rests on the plank within 6 cm of the plank's centre along its length
|
| 28 |
+
Success = all four hold at the end simultaneously, the scene is static (< 4 mm motion in 1 s) and the robot neither
|
| 29 |
+
holds nor touches any object. The monitor's achieved / lost / restored events go to the server log only (F1).
|
| 30 |
+
|
| 31 |
+
Why the agent breaks the bridge (measured, see task_cards/lh_bridge.md): with the plank down, the car sits 3-6.5 cm
|
| 32 |
+
behind the plank's back edge, between the pillars. The Panda hand is 21 cm long along the finger axis and its underside
|
| 33 |
+
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
|
| 34 |
+
differently; scripted here on seeds 1000-1019: hovering ~13 cm above it while turning the wrist from the plank's 90 deg
|
| 35 |
+
to the car's yaw, then straight down (5/20 knock the bridge), keeping the 90 deg wrist and going straight down (the hand
|
| 36 |
+
lands across the plank: 20/20), or one diagonal move from above the bridge straight down to the grasp (the hand drives
|
| 37 |
+
through the bridge: 20/20). The plank and one or both pillar tops fall; in 22 of 24 collapses (seeds 3000-3029) every
|
| 38 |
+
part needed stays within reach (a block out of reach is covered by the spare; the plank was thrown out of reach twice).
|
| 39 |
+
What prevents it (learnable from one failure, and what Sonnet wrote after its pilot failure): move the car away before
|
| 40 |
+
laying the plank.
|
| 41 |
+
|
| 42 |
+
Hidden variables: none that matter. Block size and friction are instance variety; the car's distance (5.5-9 cm) and yaw
|
| 43 |
+
decide only the "hover" style's outcome.
|
| 44 |
+
|
| 45 |
+
Scripted references (perception = simulator state):
|
| 46 |
+
naive Sonnet-like (measured on the pilot): instruction order; per pillar the free block nearest its square first;
|
| 47 |
+
hover ~12 cm above an object turned to its yaw, vertical descent, grasp 1.1 cm below the top; carry to a bare
|
| 48 |
+
square in one diagonal move to 12.5 cm above it, onto a block lift first; lift over a built pillar when the
|
| 49 |
+
carried block's straight path would hit it; release, lift to 15 cm; plank lifted to 7 cm, carried at 16 cm,
|
| 50 |
+
lift to 21 cm; the car approach style is the pilot's mixture (seed % 3: hover / keep / direct); no final check
|
| 51 |
+
naive_v1 the v1 naive (vertical / horizontal legs at 8 cm, carries at max(8 cm, release + 4 cm)), for comparison
|
| 52 |
+
oracle careful: first moves the car out of the zone behind the bridge; all transits at 25 cm, vertical approaches
|
| 53 |
+
at 0.1 m/s, grasps 1.6 cm below a cube's top, gripper yaw chosen for hand / finger clearance; checks every
|
| 54 |
+
stage at the end and repairs what is broken (same repair as adaptive)
|
| 55 |
+
adaptive attempt 1 = naive, then checks every stage before finishing and restores what was lost (tips a plank that
|
| 56 |
+
stands on edge, puts the plank and car aside, re-stacks the pillars from usable blocks, then plank and car
|
| 57 |
+
again); from attempt 2 the careful behaviour
|
| 58 |
+
blind naive with random variation (hover / carry / lift heights, diagonal or lift-first carries, car style,
|
| 59 |
+
block allocation, 4 mm placement noise), no history
|
| 60 |
+
|
| 61 |
+
Protocol: cross (reset to the same instance before every attempt), k = 3.
|
| 62 |
+
"""
|
| 63 |
+
import os
|
| 64 |
+
|
| 65 |
+
import numpy as np
|
| 66 |
+
|
| 67 |
+
from .. import envs
|
| 68 |
+
from ..bddl import write_bddl
|
| 69 |
+
from ..objects import _fmt, _wrap, box_xml, register_generated
|
| 70 |
+
from ..skills import Skills
|
| 71 |
+
from ..task_base import LFFTask, register_task
|
| 72 |
+
|
| 73 |
+
BLOCKS = ["block_a_1", "block_b_1", "block_c_1", "block_d_1", "block_e_1"] # four are needed, one is a spare
|
| 74 |
+
PLANK, CAR = "plank_1", "car_1"
|
| 75 |
+
SQUARES = ["square_blue_1", "square_green_1"] # S1 = blue, S2 = green
|
| 76 |
+
ITEMS = BLOCKS + [PLANK, CAR]
|
| 77 |
+
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),
|
| 78 |
+
(0.76, 0.60, 0.42, 1.0)] # wood
|
| 79 |
+
PLANK_HALF = (0.12, 0.025, 0.006) # 24 x 5 x 1.2 cm, long axis = body x
|
| 80 |
+
CAR_HALF = 0.02
|
| 81 |
+
BLOCK_NOM = 0.026 # nominal half edge in the MJCF (resized per instance)
|
| 82 |
+
SQ_HALF = 0.03
|
| 83 |
+
SQ_RGBA = {"square_blue_1": (0.12, 0.30, 0.90, 1.0), "square_green_1": (0.10, 0.70, 0.25, 1.0)}
|
| 84 |
+
SQ_NAME = {"square_blue_1": "blue", "square_green_1": "green"}
|
| 85 |
+
SPAN = 0.16 # square centre distance (along y)
|
| 86 |
+
|
| 87 |
+
TZ = envs.TABLE_Z
|
| 88 |
+
BASE_X = -0.66
|
| 89 |
+
HAND_HALF_LONG = 0.106 # Panda hand collision AABB about the grasp site: +-10.6 cm along the finger axis
|
| 90 |
+
HAND_HALF_SHORT = 0.036 # +-3.6 cm across it
|
| 91 |
+
HAND_BOTTOM = 0.024 # its underside is 2.4 cm above the grasp site (measured)
|
| 92 |
+
|
| 93 |
+
SQ_TOL = 0.025 # lower block centre within 2.5 cm of the square centre
|
| 94 |
+
STACK_TOL = 0.025 # upper block centre within 2.5 cm of the lower one
|
| 95 |
+
FLAT_COS = np.cos(np.radians(12))
|
| 96 |
+
PLANK_TILT = np.radians(10)
|
| 97 |
+
CAR_MID = 0.06
|
| 98 |
+
DEBOUNCE = 6 # control steps a predicate must keep its new value before an event is recorded
|
| 99 |
+
|
| 100 |
+
# v2 layout (2026-10-09): the red cube ("car") is parked in the gap between the two squares, just behind the bridge
|
| 101 |
+
# line, so that once the plank is down a natural top-down grasp of it lands the hand on the plank / pillar tops; the
|
| 102 |
+
# four wooden blocks lie in a row behind the bridge, two on each side of the car; the plank lies further back.
|
| 103 |
+
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,
|
| 104 |
+
car_clear=0.08, car_yaw=0.35, plank_dx=(0.19, 0.21), block_edge=(0.050, 0.056))
|
| 105 |
+
KEEP_OUT = dict(dx=0.13, dy=0.20) # careful: no parking / no material left within this zone behind the bridge line
|
| 106 |
+
# Sonnet-like naive (measured on the lh1 pilot, see task_cards/lh_bridge.md): heights of the grasp site above the table
|
| 107 |
+
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,
|
| 108 |
+
end_lift=0.25, top_below=0.011, diag=True, car_style=None, car_hover=0.134, plank_end_lift=0.21,
|
| 109 |
+
alloc="greedy")
|
| 110 |
+
# how the gripper went for the red cube once the plank was down -- each of the three pilot runs did it differently:
|
| 111 |
+
# hover (seed 3002) move to ~13.4 cm above it while turning to its yaw, then straight down
|
| 112 |
+
# keep (seed 3000) the same, but still turned 90 deg from laying the plank
|
| 113 |
+
# direct (seed 3001) one move from ~21 cm above the bridge straight (diagonally) down to the grasp
|
| 114 |
+
# the naive script uses style CAR_STYLES[seed % 3] (car_style=None), i.e. the pilot's mixture
|
| 115 |
+
CAR_STYLES = ("hover", "keep", "direct")
|
| 116 |
+
Z_NAIVE = 0.08 # naive_v1 transit height of the grasp site above the table
|
| 117 |
+
Z_SAFE = 0.25 # careful transit height
|
| 118 |
+
NAIVE_LIFT = 0.05 # naive: lift this far straight up after letting go, then head for the next waypoint
|
| 119 |
+
NAIVE_STYLE = "legs" # legs: vertical / horizontal legs at the transit height; diag: straight lines between waypoints
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _wrap_q(a):
|
| 123 |
+
"""wrap to [-pi/4, pi/4) (cubes are symmetric under 90 deg)"""
|
| 124 |
+
return float((a + np.pi / 4) % (np.pi / 2) - np.pi / 4)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _wrap_h(a):
|
| 128 |
+
"""wrap to [-pi/2, pi/2) (plank / gripper symmetric under 180 deg)"""
|
| 129 |
+
return float((a + np.pi / 2) % np.pi - np.pi / 2)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
# Contact softness of the bridge parts. LFF-Bench's generated boxes use a very stiff contact (objects._SOLID); when a
|
| 133 |
+
# fast hand drives into a stacked bridge, the stiff contacts resolve the overlap with large impulses and blocks fly
|
| 134 |
+
# 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
|
| 135 |
+
# softer contact (MuJoCo-like defaults) keeps collapses local. None = use the stiff default.
|
| 136 |
+
CONTACT = os.environ.get("LFF_LHB_CONTACT", 'solimp="0.95 0.99 0.001" solref="0.01 1"')
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def part_xml(model_name, half, rgba, density):
|
| 140 |
+
"""box like objects.box_xml, with the task's contact softness"""
|
| 141 |
+
if not CONTACT or CONTACT == "stiff":
|
| 142 |
+
return box_xml(model_name, half, rgba, density=density)
|
| 143 |
+
g = (f' <geom name="{model_name}_g0" type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" '
|
| 144 |
+
f'density="{density}" friction="1.0 0.005 0.0001" {CONTACT} group="0" />\n'
|
| 145 |
+
f' <geom type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" conaffinity="0" contype="0" group="1" />')
|
| 146 |
+
return _wrap(model_name, g, half[2], float(np.hypot(half[0], half[1])))
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def mark_xml(name, rgba):
|
| 150 |
+
"""flat coloured square, visual only (does not touch the physics)"""
|
| 151 |
+
g = (f' <geom type="box" size="{SQ_HALF:.5f} {SQ_HALF:.5f} 0.00060" rgba="{_fmt(rgba)}" '
|
| 152 |
+
f'contype="0" conaffinity="0" group="1" />')
|
| 153 |
+
return _wrap(name, g, 0.0006, SQ_HALF * 1.42)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class BridgeSkills(Skills):
|
| 157 |
+
"""Skills that feed the task's per-step stage monitor."""
|
| 158 |
+
|
| 159 |
+
def __init__(self, env, task, recorder=None):
|
| 160 |
+
super().__init__(env, recorder=recorder)
|
| 161 |
+
self.task = task
|
| 162 |
+
|
| 163 |
+
def _act(self, dpos, drot, grip):
|
| 164 |
+
super()._act(dpos, drot, grip)
|
| 165 |
+
self.task.monitor_step()
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
@register_task
|
| 169 |
+
class Bridge(LFFTask):
|
| 170 |
+
name = "lh_bridge"
|
| 171 |
+
level = "L2"
|
| 172 |
+
category = "state_restoration"
|
| 173 |
+
capabilities = ("Perceive", "Plan", "Reason", "Restore")
|
| 174 |
+
protocol = "cross"
|
| 175 |
+
max_attempts = 3
|
| 176 |
+
agent_max_steps = 130
|
| 177 |
+
instruction = ("Build a small bridge. First stack two of the wooden blocks on the blue square, then two on the green "
|
| 178 |
+
"square, to make two pillars; then lay the long plank across the tops of both pillars; finally put "
|
| 179 |
+
"the red cube on the middle of the plank. The finished bridge must stand on its own, with the "
|
| 180 |
+
"gripper open and not touching anything.")
|
| 181 |
+
instruction_indirect = ("Build a small bridge. First make a tower of two of the wooden cubes on the blue mark on the "
|
| 182 |
+
"table, then another tower of two on the green mark; then lay the long flat board across the "
|
| 183 |
+
"tops of the two towers; finally set the small red cube on the middle of the board. At the "
|
| 184 |
+
"end everything must stand on its own, with the gripper open and not touching anything.")
|
| 185 |
+
agent_object_names = ["wooden blocks (5)", "plank", "red cube", "blue square", "green square"]
|
| 186 |
+
|
| 187 |
+
# ------------------------------------------------------------ scene
|
| 188 |
+
def make_bddl(self):
|
| 189 |
+
objs = []
|
| 190 |
+
for i, b in enumerate(BLOCKS):
|
| 191 |
+
cat = register_generated(f"LffLhbBlock{'ABCDE'[i]}", part_xml(f"lff_lhb_block_{'abcde'[i]}", (BLOCK_NOM,) * 3,
|
| 192 |
+
BLOCK_RGBA[i], 500.0))
|
| 193 |
+
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)
|
| 194 |
+
objs.append((b, cat, f"blk{i}_region", reg))
|
| 195 |
+
pl = register_generated("LffLhbPlank", part_xml("lff_lhb_plank", PLANK_HALF, (0.50, 0.33, 0.18, 1.0),
|
| 196 |
+
density=600.0))
|
| 197 |
+
objs.append((PLANK, pl, "plank_region", (0.05, -0.01, 0.06, 0.01)))
|
| 198 |
+
car = register_generated("LffLhbCar", part_xml("lff_lhb_car", (CAR_HALF,) * 3, (0.85, 0.10, 0.08, 1.0),
|
| 199 |
+
density=400.0))
|
| 200 |
+
objs.append((CAR, car, "car_region", (-0.30, -0.31, -0.29, -0.30)))
|
| 201 |
+
fx = []
|
| 202 |
+
for i, s in enumerate(SQUARES):
|
| 203 |
+
cat = register_generated(f"LffLhbSquare{'BG'[i]}", mark_xml(f"lff_lhb_square_{'bg'[i]}", SQ_RGBA[s]),
|
| 204 |
+
free=False)
|
| 205 |
+
fx.append((s, cat, f"sq{i}_region", (-0.10 + 0.10 * i, -0.31, -0.09 + 0.10 * i, -0.30)))
|
| 206 |
+
return write_bddl(self.name, "Build a small bridge from the blocks the plank and the red cube", objs, fx)
|
| 207 |
+
|
| 208 |
+
def __init__(self, cam_res=None):
|
| 209 |
+
super().__init__(cam_res)
|
| 210 |
+
m = self.env.sim.model
|
| 211 |
+
self.sq_bid = {s: m.body_name2id(self.env.fixtures_dict[s].root_body) for s in SQUARES}
|
| 212 |
+
self.geoms = {o: envs.obj_geom_ids(self.env, o) for o in ITEMS}
|
| 213 |
+
self.vis_geoms = {}
|
| 214 |
+
for o in BLOCKS:
|
| 215 |
+
root = envs.body_id(self.env, o)
|
| 216 |
+
bodies = {b for b in range(m.nbody) if b == root or m.body_parentid[b] == root}
|
| 217 |
+
self.vis_geoms[o] = [g for g in range(m.ngeom) if m.geom_bodyid[g] in bodies and m.geom_contype[g] == 0
|
| 218 |
+
and m.geom_conaffinity[g] == 0 and m.geom_type[g] == 6]
|
| 219 |
+
self.block_body = getattr(self, "block_body", {})
|
| 220 |
+
self.block_body[o] = int(m.geom_bodyid[self.geoms[o][0]])
|
| 221 |
+
self.table_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("main_table")
|
| 222 |
+
and m.geom_contype[g] != 0]
|
| 223 |
+
self.robot_geoms = set(envs.robot_geom_ids(self.env))
|
| 224 |
+
self.inst = None
|
| 225 |
+
self.mon = None
|
| 226 |
+
self.sk = None
|
| 227 |
+
self.naive_lift = NAIVE_LIFT
|
| 228 |
+
self.naive_style = NAIVE_STYLE
|
| 229 |
+
|
| 230 |
+
# ------------------------------------------------------------ instances
|
| 231 |
+
def sample_instance(self, seed):
|
| 232 |
+
rng = np.random.default_rng(seed)
|
| 233 |
+
xb = float(rng.uniform(*LAYOUT["bridge_x"]))
|
| 234 |
+
yc = float(rng.uniform(-0.03, 0.03))
|
| 235 |
+
blue_left = bool(rng.random() < 0.5)
|
| 236 |
+
sq = {"square_blue_1": [xb, yc + (SPAN / 2 if blue_left else -SPAN / 2)],
|
| 237 |
+
"square_green_1": [xb, yc - (SPAN / 2 if blue_left else -SPAN / 2)]}
|
| 238 |
+
L = LAYOUT
|
| 239 |
+
# the car: in the gap between the two squares, just behind the bridge line
|
| 240 |
+
pos = {CAR: [xb + float(rng.uniform(*L["car_dx"])), yc + float(rng.uniform(-L["car_dy"], L["car_dy"]))]}
|
| 241 |
+
# five blocks in a row behind the bridge line, two on one side of the car and three on the other
|
| 242 |
+
row_x = xb + float(rng.uniform(*L["row_dx"]))
|
| 243 |
+
ys = []
|
| 244 |
+
three = 1.0 if rng.random() < 0.5 else -1.0
|
| 245 |
+
for side in (-1.0, 1.0):
|
| 246 |
+
n = 3 if side == three else 2
|
| 247 |
+
lo, hi = sorted((pos[CAR][1] + side * L["car_clear"], side * L["y_half"]))
|
| 248 |
+
u = np.sort(rng.uniform(0.0, max((hi - lo) - (n - 1) * L["gap"], 0.0), n))
|
| 249 |
+
ys += [lo + k * L["gap"] + u[k] for k in range(n)]
|
| 250 |
+
order = rng.permutation(5)
|
| 251 |
+
for k, j in enumerate(order):
|
| 252 |
+
pos[BLOCKS[j]] = [row_x + float(rng.uniform(-0.01, 0.01)), float(ys[k])]
|
| 253 |
+
plank_xy = [xb + float(rng.uniform(*L["plank_dx"])), yc + float(rng.uniform(-0.04, 0.04))]
|
| 254 |
+
size = {b: float(rng.uniform(*L["block_edge"])) for b in BLOCKS}
|
| 255 |
+
mu = {b: float(rng.uniform(0.3, 0.6)) for b in BLOCKS}
|
| 256 |
+
yaw = {o: float(rng.uniform(-0.35, 0.35)) for o in BLOCKS}
|
| 257 |
+
yaw[CAR] = float(rng.uniform(-L["car_yaw"], L["car_yaw"]))
|
| 258 |
+
yaw[PLANK] = float(np.pi / 2 + rng.uniform(-0.25, 0.25)) # long axis roughly left-right
|
| 259 |
+
pos[PLANK] = plank_xy
|
| 260 |
+
return dict(seed=int(seed), squares=sq, blue_side="left" if blue_left else "right", pos=pos, yaw=yaw,
|
| 261 |
+
size=size, mu=mu, bridge_x=xb, bridge_yc=yc)
|
| 262 |
+
|
| 263 |
+
def _resize_block(self, o, edge):
|
| 264 |
+
m = self.env.sim.model
|
| 265 |
+
h = edge / 2.0
|
| 266 |
+
for g in self.geoms[o] + self.vis_geoms[o]:
|
| 267 |
+
m.geom_size[g] = [h, h, h]
|
| 268 |
+
m.geom_rbound[g] = float(np.sqrt(3) * h)
|
| 269 |
+
m.geom_aabb[g] = [0.0, 0.0, 0.0, h, h, h]
|
| 270 |
+
b = self.block_body[o]
|
| 271 |
+
mass = 500.0 * edge ** 3
|
| 272 |
+
m.body_mass[b] = mass
|
| 273 |
+
m.body_inertia[b] = [mass * edge ** 2 / 6.0] * 3
|
| 274 |
+
envs.refit_bounds(self.env, b) # BVH of the resized block (envs.refit_bounds)
|
| 275 |
+
|
| 276 |
+
def apply_instance(self, inst):
|
| 277 |
+
self.inst = inst
|
| 278 |
+
m = self.env.sim.model
|
| 279 |
+
for s in SQUARES:
|
| 280 |
+
x, y = inst["squares"][s]
|
| 281 |
+
m.body_pos[self.sq_bid[s]] = [x, y, TZ + 0.0007]
|
| 282 |
+
m.body_quat[self.sq_bid[s]] = [1.0, 0.0, 0.0, 0.0]
|
| 283 |
+
for o in BLOCKS:
|
| 284 |
+
self._resize_block(o, inst["size"][o])
|
| 285 |
+
envs.set_friction(self.env, o, inst["mu"][o])
|
| 286 |
+
envs.set_friction(self.env, PLANK, 0.5)
|
| 287 |
+
envs.set_friction(self.env, CAR, 0.6)
|
| 288 |
+
self.env.sim.forward()
|
| 289 |
+
for o in ITEMS:
|
| 290 |
+
envs.place_upright(self.env, o, inst["pos"][o], inst["yaw"][o], clearance=0.001)
|
| 291 |
+
|
| 292 |
+
def reset_instance(self, inst, recorder=None):
|
| 293 |
+
self.mon = None
|
| 294 |
+
self.env.reset()
|
| 295 |
+
self.apply_instance(inst)
|
| 296 |
+
self.env.sim.forward()
|
| 297 |
+
envs.settle(self.env, 15)
|
| 298 |
+
self.sk = BridgeSkills(self.env, self, recorder=recorder)
|
| 299 |
+
self.mon = dict(state=[False] * 4, raw_since=[0] * 4, ever=[False] * 4, lost=[False] * 4, events=[])
|
| 300 |
+
return self.sk
|
| 301 |
+
|
| 302 |
+
# ------------------------------------------------------------ geometry / predicates
|
| 303 |
+
def half(self, o):
|
| 304 |
+
if o in BLOCKS:
|
| 305 |
+
e = self.inst["size"][o] / 2
|
| 306 |
+
return np.array([e, e, e])
|
| 307 |
+
return np.array(PLANK_HALF) if o == PLANK else np.array([CAR_HALF] * 3)
|
| 308 |
+
|
| 309 |
+
def R(self, o):
|
| 310 |
+
return self.env.sim.data.body_xmat[envs.body_id(self.env, o)].reshape(3, 3).copy()
|
| 311 |
+
|
| 312 |
+
def pos(self, o):
|
| 313 |
+
return envs.obj_pos(self.env, o)
|
| 314 |
+
|
| 315 |
+
def zmin(self, o):
|
| 316 |
+
return envs.obj_min_z(self.env, o)
|
| 317 |
+
|
| 318 |
+
def zmax(self, o):
|
| 319 |
+
return envs.obj_max_z(self.env, o)
|
| 320 |
+
|
| 321 |
+
def flat(self, o):
|
| 322 |
+
return float(np.max(np.abs(self.R(o)[2]))) > FLAT_COS
|
| 323 |
+
|
| 324 |
+
def yaw_of(self, o):
|
| 325 |
+
"""yaw of the object's body x axis (for the plank: its long axis)"""
|
| 326 |
+
R = self.R(o)
|
| 327 |
+
return float(np.arctan2(R[1, 0], R[0, 0]))
|
| 328 |
+
|
| 329 |
+
def held(self, o):
|
| 330 |
+
return self.sk is not None and self.sk.holding(o)
|
| 331 |
+
|
| 332 |
+
def contacts(self, a_geoms, b_geoms):
|
| 333 |
+
return envs.contacts_between(self.env, a_geoms, b_geoms)
|
| 334 |
+
|
| 335 |
+
def pillar(self, s):
|
| 336 |
+
"""(lower, upper) blocks of a complete pillar on square s, else (lower or None, None)"""
|
| 337 |
+
c = np.asarray(self.inst["squares"][s])
|
| 338 |
+
lower = None
|
| 339 |
+
for b in BLOCKS:
|
| 340 |
+
p = self.pos(b)
|
| 341 |
+
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):
|
| 342 |
+
lower = b
|
| 343 |
+
break
|
| 344 |
+
if lower is None:
|
| 345 |
+
return None, None
|
| 346 |
+
pl = self.pos(lower)
|
| 347 |
+
top = self.zmax(lower)
|
| 348 |
+
for b in BLOCKS:
|
| 349 |
+
if b == lower:
|
| 350 |
+
continue
|
| 351 |
+
p = self.pos(b)
|
| 352 |
+
if (np.linalg.norm(p[:2] - pl[:2]) <= STACK_TOL and abs(self.zmin(b) - top) < 0.006 and self.flat(b)
|
| 353 |
+
and not self.held(b)):
|
| 354 |
+
return lower, b
|
| 355 |
+
return lower, None
|
| 356 |
+
|
| 357 |
+
def plank_ok(self, tops):
|
| 358 |
+
if any(t is None for t in tops) or self.held(PLANK):
|
| 359 |
+
return False
|
| 360 |
+
R = self.R(PLANK)
|
| 361 |
+
if abs(R[2, 0]) > np.sin(PLANK_TILT) or abs(R[2, 2]) < np.cos(PLANK_TILT): # either broad face up (v2 fix)
|
| 362 |
+
return False
|
| 363 |
+
if self.zmin(PLANK) < TZ + 0.03 or self.contacts(self.geoms[PLANK], self.table_geoms):
|
| 364 |
+
return False
|
| 365 |
+
return all(self.contacts(self.geoms[PLANK], self.geoms[t]) for t in tops)
|
| 366 |
+
|
| 367 |
+
def car_ok(self):
|
| 368 |
+
"""the car rests on the plank's upper face (in the plank's own frame, so a slightly tilted plank is fine),
|
| 369 |
+
within CAR_MID of the plank's centre along its length"""
|
| 370 |
+
if self.held(CAR) or not self.contacts(self.geoms[CAR], self.geoms[PLANK]):
|
| 371 |
+
return False
|
| 372 |
+
R = self.R(PLANK)
|
| 373 |
+
rel = R.T @ (self.pos(CAR) - self.pos(PLANK))
|
| 374 |
+
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)
|
| 375 |
+
return bool(abs(rel[0]) <= CAR_MID and abs(rel[1]) <= PLANK_HALF[1] + 0.01 and up > PLANK_HALF[2] + 0.01)
|
| 376 |
+
|
| 377 |
+
def stages(self):
|
| 378 |
+
"""raw predicate values [S1, S2, S3, S4] and the pillars found"""
|
| 379 |
+
pa = self.pillar(SQUARES[0])
|
| 380 |
+
pb = self.pillar(SQUARES[1])
|
| 381 |
+
s1, s2 = pa[1] is not None, pb[1] is not None
|
| 382 |
+
s3 = bool(s1 and s2 and self.plank_ok([pa[1], pb[1]]))
|
| 383 |
+
s4 = bool(self.car_ok())
|
| 384 |
+
return [s1, s2, s3, s4], (pa, pb)
|
| 385 |
+
|
| 386 |
+
# ------------------------------------------------------------ monitor
|
| 387 |
+
def monitor_step(self):
|
| 388 |
+
mon = self.mon
|
| 389 |
+
if mon is None or self.sk is None:
|
| 390 |
+
return
|
| 391 |
+
raw, _ = self.stages()
|
| 392 |
+
t = self.sk.n_steps
|
| 393 |
+
for i in range(4):
|
| 394 |
+
if raw[i] == mon["state"][i]:
|
| 395 |
+
mon["raw_since"][i] = 0
|
| 396 |
+
continue
|
| 397 |
+
mon["raw_since"][i] += 1
|
| 398 |
+
if mon["raw_since"][i] < DEBOUNCE:
|
| 399 |
+
continue
|
| 400 |
+
mon["state"][i] = raw[i]
|
| 401 |
+
mon["raw_since"][i] = 0
|
| 402 |
+
t0 = t - DEBOUNCE + 1
|
| 403 |
+
if raw[i]:
|
| 404 |
+
ev = "restored" if mon["lost"][i] else "achieved"
|
| 405 |
+
mon["ever"][i] = True
|
| 406 |
+
else:
|
| 407 |
+
ev = "lost"
|
| 408 |
+
mon["lost"][i] = True
|
| 409 |
+
mon["events"].append(dict(stage=f"S{i + 1}", event=ev, step=int(t0)))
|
| 410 |
+
|
| 411 |
+
# ------------------------------------------------------------ outcome
|
| 412 |
+
def _dir_words(self, d):
|
| 413 |
+
"""robot-centric words for a horizontal offset d (world x = forward, away from the robot; y = robot's left)"""
|
| 414 |
+
parts = []
|
| 415 |
+
if abs(d[0]) >= 0.01:
|
| 416 |
+
parts.append(f"{100 * abs(d[0]):.0f} cm {'forward' if d[0] > 0 else 'back'}")
|
| 417 |
+
if abs(d[1]) >= 0.01:
|
| 418 |
+
parts.append(f"{100 * abs(d[1]):.0f} cm {'left' if d[1] > 0 else 'right'}")
|
| 419 |
+
return (" and ".join(parts) + " of") if parts else "right at"
|
| 420 |
+
|
| 421 |
+
def outcome(self, inst):
|
| 422 |
+
sk = self.sk
|
| 423 |
+
sk.hold(10)
|
| 424 |
+
p0 = {o: self.pos(o) for o in ITEMS}
|
| 425 |
+
touching = False
|
| 426 |
+
for _ in range(20):
|
| 427 |
+
sk.hold(1)
|
| 428 |
+
touching = touching or any(self.contacts(list(self.robot_geoms), self.geoms[o]) for o in ITEMS)
|
| 429 |
+
moved = max(float(np.linalg.norm(self.pos(o) - p0[o])) for o in ITEMS)
|
| 430 |
+
static = moved < 0.004
|
| 431 |
+
raw, (pa, pb) = self.stages()
|
| 432 |
+
held = [o for o in ITEMS if sk.holding(o)]
|
| 433 |
+
mon = self.mon
|
| 434 |
+
ev = list(mon["events"]) if mon else []
|
| 435 |
+
n_reg = sum(e["event"] == "lost" for e in ev)
|
| 436 |
+
n_res = sum(e["event"] == "restored" for e in ev)
|
| 437 |
+
success = bool(all(raw) and static and not held and not touching)
|
| 438 |
+
parts = []
|
| 439 |
+
if success:
|
| 440 |
+
failure = "none"
|
| 441 |
+
parts.append("The bridge is complete: both pillars stand on their squares, the plank rests across them "
|
| 442 |
+
"and the red cube sits on the middle of the plank.")
|
| 443 |
+
else:
|
| 444 |
+
lost_final = [i for i in range(4) if not raw[i] and mon and mon["ever"][i]]
|
| 445 |
+
never = [i for i in range(4) if not raw[i] and not (mon and mon["ever"][i])]
|
| 446 |
+
if held:
|
| 447 |
+
failure = "held"
|
| 448 |
+
elif touching:
|
| 449 |
+
failure = "touching"
|
| 450 |
+
elif lost_final:
|
| 451 |
+
failure = "regressed_" + "".join(f"S{i + 1}" for i in lost_final)
|
| 452 |
+
elif never:
|
| 453 |
+
failure = "incomplete_" + "".join(f"S{i + 1}" for i in never)
|
| 454 |
+
else:
|
| 455 |
+
failure = "not_static"
|
| 456 |
+
for i, s in enumerate(SQUARES):
|
| 457 |
+
if raw[i]:
|
| 458 |
+
continue
|
| 459 |
+
low, _ = (pa, pb)[i]
|
| 460 |
+
c = np.asarray(inst["squares"][s])
|
| 461 |
+
txt = f"The pillar on the {SQ_NAME[s]} square is not standing:"
|
| 462 |
+
if low is None:
|
| 463 |
+
txt += " no block stands on the square."
|
| 464 |
+
else:
|
| 465 |
+
txt += " only one block stands on the square."
|
| 466 |
+
strays = [b for b in BLOCKS if b not in (pa[0], pa[1], pb[0], pb[1])]
|
| 467 |
+
if strays:
|
| 468 |
+
near = min(strays, key=lambda b: np.linalg.norm(self.pos(b)[:2] - c))
|
| 469 |
+
txt += f" The nearest loose block lies {self._dir_words(self.pos(near)[:2] - c)} the square."
|
| 470 |
+
if mon and mon["ever"][i]:
|
| 471 |
+
txt += " It had been built and was knocked down later."
|
| 472 |
+
parts.append(txt)
|
| 473 |
+
if not raw[2]:
|
| 474 |
+
pp = self.pos(PLANK)
|
| 475 |
+
if self.contacts(self.geoms[PLANK], self.table_geoms):
|
| 476 |
+
where = "touches the table"
|
| 477 |
+
elif self.held(PLANK):
|
| 478 |
+
where = "is still in the gripper"
|
| 479 |
+
else:
|
| 480 |
+
where = "does not rest level on the tops of both pillars"
|
| 481 |
+
bc = np.mean([inst["squares"][s] for s in SQUARES], axis=0)
|
| 482 |
+
parts.append(f"The plank {where}; its centre is {self._dir_words(pp[:2] - bc)} the middle between "
|
| 483 |
+
f"the squares." + (" It had been laid and was disturbed later." if mon and mon["ever"][2]
|
| 484 |
+
and not raw[2] else ""))
|
| 485 |
+
if not raw[3]:
|
| 486 |
+
if self.held(CAR):
|
| 487 |
+
parts.append("The red cube is still in the gripper.")
|
| 488 |
+
elif self.contacts(self.geoms[CAR], self.geoms[PLANK]):
|
| 489 |
+
parts.append("The red cube is on the plank but not on its middle part.")
|
| 490 |
+
else:
|
| 491 |
+
bc = np.mean([inst["squares"][s] for s in SQUARES], axis=0)
|
| 492 |
+
parts.append(f"The red cube is not on the plank; it lies {self._dir_words(self.pos(CAR)[:2] - bc)} "
|
| 493 |
+
"the middle between the squares.")
|
| 494 |
+
if all(raw) and held:
|
| 495 |
+
parts.append("The gripper still holds an object.")
|
| 496 |
+
elif touching:
|
| 497 |
+
parts.append("The gripper is still touching the bridge.")
|
| 498 |
+
elif all(raw) and not static:
|
| 499 |
+
parts.append("The bridge was still moving.")
|
| 500 |
+
if n_reg:
|
| 501 |
+
parts.append(f"During the attempt earlier stages were undone {n_reg} time(s) and restored {n_res} time(s).")
|
| 502 |
+
if any(w in " ".join(parts) for w in (" forward of", " back of", " back and", " forward and")):
|
| 503 |
+
parts.append("(Forward = away from the robot.)")
|
| 504 |
+
return dict(success=success, stages={f"S{i + 1}": bool(raw[i]) for i in range(4)}, events=ev,
|
| 505 |
+
n_regressions=int(n_reg), n_restored=int(n_res), failure=failure, held=held,
|
| 506 |
+
touching=bool(touching), static=bool(static), detail=" ".join(parts))
|
| 507 |
+
|
| 508 |
+
# ------------------------------------------------------------ scripted policies (move_to + gripper only)
|
| 509 |
+
def _grip_yaws(self, o):
|
| 510 |
+
"""candidate gripper yaws for a top-down grasp of o (fingers across a face)"""
|
| 511 |
+
if o == PLANK: # fingers (which open along the gripper's y at yaw 0) across the plank's width
|
| 512 |
+
return [_wrap_h(self.yaw_of(PLANK))]
|
| 513 |
+
a = _wrap_q(self.yaw_of(o))
|
| 514 |
+
return [a, _wrap_h(a + np.pi / 2)]
|
| 515 |
+
|
| 516 |
+
def footprint(self, o):
|
| 517 |
+
"""sample points on the horizontal footprint of o (corners, edge midpoints, centre)"""
|
| 518 |
+
R, c, h = self.R(o), self.pos(o), self.half(o)
|
| 519 |
+
pts = []
|
| 520 |
+
for sx in (-1, 0, 1):
|
| 521 |
+
for sy in (-1, 0, 1):
|
| 522 |
+
for sz in ((-1, 1) if o != PLANK else (0,)):
|
| 523 |
+
pts.append((c + R @ (h * [sx, sy, sz]))[:2])
|
| 524 |
+
if o == PLANK:
|
| 525 |
+
for t_ in np.linspace(-1, 1, 9):
|
| 526 |
+
for sy in (-1, 1):
|
| 527 |
+
pts.append((c + R @ (h * [t_, sy, 0]))[:2])
|
| 528 |
+
return np.array(pts)
|
| 529 |
+
|
| 530 |
+
def _hand_clearance(self, xy, yaw, z_site, ignore=()):
|
| 531 |
+
"""smallest horizontal clearance (m) between the gripper at a grasp-site height z_site and everything else:
|
| 532 |
+
the hand body (+-10.6 x +-3.6 cm, underside 2.4 cm above the site) against items taller than its underside,
|
| 533 |
+
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)
|
| 534 |
+
against items taller than the fingertips. Negative = the gripper would land on something."""
|
| 535 |
+
f = np.array([-np.sin(yaw), np.cos(yaw)]) # finger axis
|
| 536 |
+
g = np.array([np.cos(yaw), np.sin(yaw)])
|
| 537 |
+
best = 1.0
|
| 538 |
+
for o in ITEMS:
|
| 539 |
+
if o in ignore or self.held(o):
|
| 540 |
+
continue
|
| 541 |
+
top = self.zmax(o)
|
| 542 |
+
if top < z_site - 0.013:
|
| 543 |
+
continue
|
| 544 |
+
d = self.footprint(o) - np.asarray(xy)
|
| 545 |
+
u, v = np.abs(d @ f), np.abs(d @ g)
|
| 546 |
+
c = float(np.min(np.maximum(np.abs(u - 0.040) - 0.010, v - 0.012))) # fingers
|
| 547 |
+
if top >= z_site + HAND_BOTTOM - 0.002:
|
| 548 |
+
c = min(c, float(np.min(np.maximum(u - HAND_HALF_LONG, v - HAND_HALF_SHORT))))
|
| 549 |
+
best = min(best, c)
|
| 550 |
+
return best
|
| 551 |
+
|
| 552 |
+
@staticmethod
|
| 553 |
+
def _pick_yaw(yaws, clearance):
|
| 554 |
+
"""the gripper yaw closest to straight (0) among those with >= 1 cm clearance, else the clearest one (large
|
| 555 |
+
wrist turns near the edge of the workspace make the OSC stop short)"""
|
| 556 |
+
c = {a: clearance(a) for a in yaws}
|
| 557 |
+
ok = [a for a in yaws if c[a] >= 0.01]
|
| 558 |
+
return min(ok, key=abs) if ok else max(yaws, key=c.get)
|
| 559 |
+
|
| 560 |
+
def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=250):
|
| 561 |
+
return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
|
| 562 |
+
|
| 563 |
+
def _grasp_z(self, o, careful):
|
| 564 |
+
if o in BLOCKS:
|
| 565 |
+
return self.zmax(o) - (0.016 if careful else self.inst["size"][o] / 2)
|
| 566 |
+
if o == PLANK:
|
| 567 |
+
return max(self.zmax(PLANK) + 0.0003 - 0.0125, TZ + 0.011)
|
| 568 |
+
return self.zmax(CAR) - (0.016 if careful else CAR_HALF)
|
| 569 |
+
|
| 570 |
+
def pick(self, o, careful, noise=None, z_t=None):
|
| 571 |
+
"""top-down grasp; returns the drop of the object's bottom below the grasp site, or None if not held"""
|
| 572 |
+
sk = self.sk
|
| 573 |
+
p = self.pos(o)
|
| 574 |
+
if noise is not None:
|
| 575 |
+
p = p + np.array([noise[0], noise[1], 0.0])
|
| 576 |
+
zg = self._grasp_z(o, careful)
|
| 577 |
+
yaws = self._grip_yaws(o)
|
| 578 |
+
if careful:
|
| 579 |
+
yaw = self._pick_yaw(yaws, lambda a: self._hand_clearance(p[:2], a, zg, ignore=(o,)))
|
| 580 |
+
cur = sk.eef_pos()
|
| 581 |
+
self._go([cur[0], cur[1], TZ + Z_SAFE])
|
| 582 |
+
self._go([p[0], p[1], TZ + Z_SAFE], yaw=yaw)
|
| 583 |
+
sk.set_gripper(False, steps=8)
|
| 584 |
+
self._go([p[0], p[1], zg + 0.03], speed=0.25)
|
| 585 |
+
self._go([p[0], p[1], zg], speed=0.1, tol=0.003, max_steps=120)
|
| 586 |
+
else:
|
| 587 |
+
yaw = min(yaws, key=lambda a: abs(a))
|
| 588 |
+
zt = TZ + (Z_NAIVE if z_t is None else z_t)
|
| 589 |
+
sk.set_gripper(False, steps=8)
|
| 590 |
+
if self.naive_style == "legs": # rise to the transit height if below it, across, straight down
|
| 591 |
+
cur = sk.eef_pos()
|
| 592 |
+
if cur[2] < zt - 0.003:
|
| 593 |
+
self._go([cur[0], cur[1], zt])
|
| 594 |
+
self._go([p[0], p[1], max(cur[2], zt)], yaw=yaw)
|
| 595 |
+
else: # one straight line to the approach point above the object
|
| 596 |
+
self._go([p[0], p[1], max(zt, self.zmax(o) + 0.03)], yaw=yaw)
|
| 597 |
+
self._go([p[0], p[1], zg], tol=0.003, max_steps=120)
|
| 598 |
+
sk.set_gripper(True, steps=15)
|
| 599 |
+
drop = float(sk.eef_pos()[2] - self.zmin(o))
|
| 600 |
+
if careful:
|
| 601 |
+
self._go([p[0], p[1], TZ + Z_SAFE], speed=0.3)
|
| 602 |
+
else:
|
| 603 |
+
zt = TZ + (Z_NAIVE if z_t is None else z_t)
|
| 604 |
+
self._go([p[0], p[1], max(zt, zg + 0.05)])
|
| 605 |
+
if not sk.holding(o):
|
| 606 |
+
sk.set_gripper(False, steps=8)
|
| 607 |
+
return None
|
| 608 |
+
return drop
|
| 609 |
+
|
| 610 |
+
def place(self, o, xy, support_top, drop, yaw, careful, z_t=None, release_gap=0.005, lift=None):
|
| 611 |
+
sk = self.sk
|
| 612 |
+
zr = support_top + drop + release_gap
|
| 613 |
+
if careful and o != PLANK: # cubes are symmetric under 90 deg: release with the fingers where there is room
|
| 614 |
+
yaw = self._pick_yaw([yaw, _wrap_h(yaw + np.pi / 2)], lambda a: self._hand_clearance(xy, a, zr, ignore=(o,)))
|
| 615 |
+
if careful:
|
| 616 |
+
cur = sk.eef_pos()
|
| 617 |
+
self._go([cur[0], cur[1], TZ + Z_SAFE])
|
| 618 |
+
self._go([xy[0], xy[1], TZ + Z_SAFE], yaw=yaw)
|
| 619 |
+
self._go([xy[0], xy[1], zr + 0.03], speed=0.25)
|
| 620 |
+
self._go([xy[0], xy[1], zr], speed=0.08, tol=0.003, max_steps=120)
|
| 621 |
+
sk.set_gripper(False, steps=12)
|
| 622 |
+
self._go([xy[0], xy[1], zr + 0.03], speed=0.1)
|
| 623 |
+
self._go([xy[0], xy[1], TZ + Z_SAFE], speed=0.3)
|
| 624 |
+
else:
|
| 625 |
+
if self.naive_style == "legs":
|
| 626 |
+
zt = TZ + (Z_NAIVE if z_t is None else z_t)
|
| 627 |
+
cur = sk.eef_pos()
|
| 628 |
+
h = max(cur[2], zt, zr + 0.04)
|
| 629 |
+
if cur[2] < h - 0.003:
|
| 630 |
+
self._go([cur[0], cur[1], h])
|
| 631 |
+
self._go([xy[0], xy[1], h], yaw=yaw)
|
| 632 |
+
else:
|
| 633 |
+
self._go([xy[0], xy[1], zr + 0.04], yaw=yaw)
|
| 634 |
+
self._go([xy[0], xy[1], zr], tol=0.003, max_steps=120)
|
| 635 |
+
sk.set_gripper(False, steps=12)
|
| 636 |
+
self._go([xy[0], xy[1], zr + (self.naive_lift if lift is None else lift)])
|
| 637 |
+
sk.hold(5)
|
| 638 |
+
|
| 639 |
+
# placing targets ---------------------------------------------------------
|
| 640 |
+
def square_xy(self, s):
|
| 641 |
+
return np.asarray(self.inst["squares"][s], float)
|
| 642 |
+
|
| 643 |
+
def bridge_mid(self):
|
| 644 |
+
return np.mean([self.square_xy(s) for s in SQUARES], axis=0)
|
| 645 |
+
|
| 646 |
+
def free_blocks(self):
|
| 647 |
+
_, (pa, pb) = self.stages()
|
| 648 |
+
used = set()
|
| 649 |
+
for low, up in (pa, pb):
|
| 650 |
+
if up is not None:
|
| 651 |
+
used |= {low, up}
|
| 652 |
+
return [b for b in BLOCKS if b not in used]
|
| 653 |
+
|
| 654 |
+
def _blocker(self, b):
|
| 655 |
+
"""for a careful top-down grasp of block b: None if the gripper fits at some grasp yaw, else the item in the
|
| 656 |
+
way (e.g. the top block of a pillar, or a block, right next to b)"""
|
| 657 |
+
zg = self._grasp_z(b, True)
|
| 658 |
+
p = self.pos(b)[:2]
|
| 659 |
+
if max(self._hand_clearance(p, a, zg, ignore=(b,)) for a in self._grip_yaws(b)) > -0.002:
|
| 660 |
+
return None
|
| 661 |
+
worst = {}
|
| 662 |
+
for o in ITEMS:
|
| 663 |
+
if o == b or self.held(o):
|
| 664 |
+
continue
|
| 665 |
+
worst[o] = max(self._hand_clearance(p, a, zg, ignore=tuple(q for q in ITEMS if q != o))
|
| 666 |
+
for a in self._grip_yaws(b))
|
| 667 |
+
o = min(worst, key=worst.get)
|
| 668 |
+
return o if worst[o] <= -0.002 else None
|
| 669 |
+
|
| 670 |
+
def build_pillar(self, s, careful, noise_fn, z_t=None, order="target"):
|
| 671 |
+
"""put blocks on square s until it carries a complete pillar (at most 5 placements)"""
|
| 672 |
+
failed = {}
|
| 673 |
+
for _ in range(6):
|
| 674 |
+
raw, (pa, pb) = self.stages()
|
| 675 |
+
low, up = (pa, pb)[SQUARES.index(s)]
|
| 676 |
+
if up is not None:
|
| 677 |
+
return True
|
| 678 |
+
if careful and self.over_budget():
|
| 679 |
+
return False
|
| 680 |
+
c = self.square_xy(s)
|
| 681 |
+
other = (pa, pb)[1 - SQUARES.index(s)]
|
| 682 |
+
cand = [b for b in BLOCKS if b != low and b not in other and (not careful or (self.usable(b)
|
| 683 |
+
and failed.get(b, 0) < 2))]
|
| 684 |
+
if not cand:
|
| 685 |
+
return False
|
| 686 |
+
ref = self.sk.eef_pos()[:2] if order == "gripper" else c
|
| 687 |
+
cand.sort(key=lambda b: (failed.get(b, 0), np.linalg.norm(self.pos(b)[:2] - ref)))
|
| 688 |
+
b = cand[0]
|
| 689 |
+
if careful:
|
| 690 |
+
free = [q for q in cand if self._blocker(q) is None]
|
| 691 |
+
if free:
|
| 692 |
+
b = free[0]
|
| 693 |
+
else: # every usable block sits right next to something tall: take that thing's top off first
|
| 694 |
+
blk = self._blocker(cand[0])
|
| 695 |
+
if blk is not None and blk != PLANK and failed.get(blk, 0) < 2:
|
| 696 |
+
if not self.park(blk):
|
| 697 |
+
failed[blk] = failed.get(blk, 0) + 1
|
| 698 |
+
continue
|
| 699 |
+
drop = self.pick(b, careful, noise=noise_fn(), z_t=z_t)
|
| 700 |
+
if drop is None:
|
| 701 |
+
failed[b] = failed.get(b, 0) + 1
|
| 702 |
+
continue
|
| 703 |
+
if low is None:
|
| 704 |
+
tgt, top = c, TZ
|
| 705 |
+
else:
|
| 706 |
+
tgt, top = self.pos(low)[:2], self.zmax(low)
|
| 707 |
+
n = noise_fn()
|
| 708 |
+
self.place(b, tgt + (n if n is not None else 0.0), top, drop, 0.0, careful, z_t=z_t)
|
| 709 |
+
return self.stages()[1][SQUARES.index(s)][1] is not None
|
| 710 |
+
|
| 711 |
+
def lay_plank(self, careful, noise_fn, z_t=None):
|
| 712 |
+
raw, (pa, pb) = self.stages()
|
| 713 |
+
if pa[1] is None or pb[1] is None or (careful and not self.usable(PLANK)):
|
| 714 |
+
return False
|
| 715 |
+
drop = self.pick(PLANK, careful, noise=noise_fn(), z_t=z_t)
|
| 716 |
+
if drop is None:
|
| 717 |
+
return False
|
| 718 |
+
raw, (pa, pb) = self.stages()
|
| 719 |
+
if pa[1] is None or pb[1] is None:
|
| 720 |
+
tops = [TZ + 0.11, TZ + 0.11]
|
| 721 |
+
mid = self.bridge_mid()
|
| 722 |
+
else:
|
| 723 |
+
tops = [self.zmax(pa[1]), self.zmax(pb[1])]
|
| 724 |
+
mid = (self.pos(pa[1])[:2] + self.pos(pb[1])[:2]) / 2
|
| 725 |
+
n = noise_fn()
|
| 726 |
+
# gripper fingers across the plank's width: plank long axis along y -> gripper yaw 90 deg
|
| 727 |
+
self.place(PLANK, mid + (n if n is not None else 0.0), max(tops), drop, np.pi / 2, careful, z_t=z_t)
|
| 728 |
+
return True
|
| 729 |
+
|
| 730 |
+
def put_car(self, careful, noise_fn, z_t=None):
|
| 731 |
+
drop = self.pick(CAR, careful, noise=noise_fn(), z_t=z_t)
|
| 732 |
+
if drop is None:
|
| 733 |
+
return False
|
| 734 |
+
pp = self.pos(PLANK)
|
| 735 |
+
n = noise_fn()
|
| 736 |
+
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)
|
| 737 |
+
return True
|
| 738 |
+
|
| 739 |
+
def in_keep_out(self, o):
|
| 740 |
+
"""o lies in the zone right behind the bridge line where, once the pillars and the plank stand, a top-down
|
| 741 |
+
grasp would put the hand on them (the careful policy keeps it clear)"""
|
| 742 |
+
p = self.pos(o)[:2]
|
| 743 |
+
dx = p[0] - self.inst["bridge_x"]
|
| 744 |
+
return bool(-0.08 < dx < KEEP_OUT["dx"] and abs(p[1] - self.bridge_mid()[1]) < KEEP_OUT["dy"])
|
| 745 |
+
|
| 746 |
+
def free_spot(self, o, avoid=()):
|
| 747 |
+
"""a free, comfortably reachable table spot for parking object o (the plank lies left-right), outside the
|
| 748 |
+
keep-out zone right behind the bridge and away from the squares"""
|
| 749 |
+
xb = self.inst["bridge_x"]
|
| 750 |
+
ym = self.bridge_mid()[1]
|
| 751 |
+
best, best_c = None, -1.0
|
| 752 |
+
others = [q for q in ITEMS if q != o and q not in avoid]
|
| 753 |
+
for x in np.arange(xb - 0.14, xb + 0.221, 0.02):
|
| 754 |
+
for y in np.arange(-0.28, 0.281, 0.02):
|
| 755 |
+
pts = [np.array([x, y])]
|
| 756 |
+
if o == PLANK:
|
| 757 |
+
pts = [np.array([x, y + d]) for d in (-0.10, 0.0, 0.10)]
|
| 758 |
+
if any(not self.reachable_xy(p) or np.hypot(p[0] - BASE_X, p[1]) > 0.64 for p in pts):
|
| 759 |
+
continue # (a careful 25 cm transit further out straightens the elbow onto its limit, measured)
|
| 760 |
+
if any(-0.08 < p[0] - xb < KEEP_OUT["dx"] and abs(p[1] - ym) < KEEP_OUT["dy"] for p in pts):
|
| 761 |
+
continue
|
| 762 |
+
c = 1.0
|
| 763 |
+
for p in pts:
|
| 764 |
+
for q in others:
|
| 765 |
+
c = min(c, float(np.linalg.norm(self.pos(q)[:2] - p)) - 0.04)
|
| 766 |
+
for sq in SQUARES:
|
| 767 |
+
c = min(c, float(np.linalg.norm(self.square_xy(sq) - p)) - 0.07)
|
| 768 |
+
if c > best_c:
|
| 769 |
+
best, best_c = np.array([x, y]), c
|
| 770 |
+
return best
|
| 771 |
+
|
| 772 |
+
@staticmethod
|
| 773 |
+
def reachable_xy(p):
|
| 774 |
+
"""a top-down grasp at table height works here (measured: right in front of the base, closer than 25 cm,
|
| 775 |
+
the arm cannot get down to the table; at 70-74 cm it still gets within ~1 cm)"""
|
| 776 |
+
rx, y = p[0] - BASE_X, p[1]
|
| 777 |
+
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)
|
| 778 |
+
|
| 779 |
+
def usable(self, o):
|
| 780 |
+
"""o lies on the table (or on something) within reach"""
|
| 781 |
+
return self.zmin(o) > TZ - 0.02 and self.reachable_xy(self.pos(o)[:2])
|
| 782 |
+
|
| 783 |
+
def park(self, o, careful=True):
|
| 784 |
+
if careful and not self.usable(o):
|
| 785 |
+
return False
|
| 786 |
+
drop = self.pick(o, careful)
|
| 787 |
+
if drop is None:
|
| 788 |
+
return False
|
| 789 |
+
xy = self.free_spot(o)
|
| 790 |
+
self.place(o, xy, TZ, drop, np.pi / 2 if o == PLANK else 0.0, careful)
|
| 791 |
+
return True
|
| 792 |
+
|
| 793 |
+
def over_budget(self):
|
| 794 |
+
"""the scripted repair stops where an agent's attempt would end: 3 s of simulated motion per command of the
|
| 795 |
+
task's command budget (agent_max_steps = 130 -> 390 s = 7800 control steps)"""
|
| 796 |
+
return self.sk.n_steps * 0.05 >= 3.0 * self.agent_max_steps
|
| 797 |
+
|
| 798 |
+
def plank_flat(self):
|
| 799 |
+
return abs(self.R(PLANK)[2, 2]) > 0.8
|
| 800 |
+
|
| 801 |
+
def fix_plank(self):
|
| 802 |
+
"""a plank standing on its long edge or leaning on something cannot be picked from above: push its upper edge
|
| 803 |
+
over with the closed gripper so that it falls flat (towards the side with more free table)"""
|
| 804 |
+
if self.plank_flat() or self.held(PLANK):
|
| 805 |
+
return False
|
| 806 |
+
sk = self.sk
|
| 807 |
+
R, c = self.R(PLANK), self.pos(PLANK)
|
| 808 |
+
up = R[:, 1] if R[2, 1] > 0 else -R[:, 1] # the plank's width axis, pointing up
|
| 809 |
+
lean = up[:2] / max(np.linalg.norm(up[:2]), 1e-6)
|
| 810 |
+
if np.linalg.norm(up[:2]) < 0.2: # standing upright: fall to the side away from the squares
|
| 811 |
+
n = R[:2, 2] / max(np.linalg.norm(R[:2, 2]), 1e-6)
|
| 812 |
+
far = lambda d: min(np.linalg.norm(c[:2] + 0.05 * d - self.square_xy(q)) for q in SQUARES) # noqa: E731
|
| 813 |
+
lean = n if far(n) > far(-n) else -n
|
| 814 |
+
push = lean
|
| 815 |
+
else: # leaning: push the top back over the vertical so it falls to the other side
|
| 816 |
+
push = -lean
|
| 817 |
+
top = c + up * 0.02
|
| 818 |
+
h = max(self.zmax(PLANK) - 0.015, TZ + 0.02)
|
| 819 |
+
a = top[:2] - push * 0.05
|
| 820 |
+
yaw = float(np.arctan2(push[1], push[0]) - np.pi / 2) # closed fingers across the push direction
|
| 821 |
+
sk.set_gripper(True, steps=8)
|
| 822 |
+
cur = sk.eef_pos()
|
| 823 |
+
self._go([cur[0], cur[1], TZ + Z_SAFE])
|
| 824 |
+
self._go([a[0], a[1], TZ + Z_SAFE], yaw=yaw)
|
| 825 |
+
self._go([a[0], a[1], h], speed=0.25)
|
| 826 |
+
b = top[:2] + push * 0.08
|
| 827 |
+
self._go([b[0], b[1], h], speed=0.1, max_steps=200)
|
| 828 |
+
self._go([b[0], b[1], TZ + Z_SAFE], speed=0.3)
|
| 829 |
+
sk.set_gripper(False, steps=8)
|
| 830 |
+
sk.hold(10)
|
| 831 |
+
return True
|
| 832 |
+
|
| 833 |
+
def clear_site(self):
|
| 834 |
+
"""careful: before building, move the car out of the zone right behind the bridge line"""
|
| 835 |
+
if self.in_keep_out(CAR) and not self.held(CAR):
|
| 836 |
+
self.park(CAR)
|
| 837 |
+
|
| 838 |
+
def repair(self, rounds=4):
|
| 839 |
+
"""check every stage; rebuild what is broken (careful motions). Returns the number of fixes made."""
|
| 840 |
+
nofn = lambda: None # noqa: E731
|
| 841 |
+
fixes = 0
|
| 842 |
+
for _ in range(rounds):
|
| 843 |
+
raw, (pa, pb) = self.stages()
|
| 844 |
+
if all(raw) or self.over_budget() or not (self.usable(PLANK) or self.held(PLANK)):
|
| 845 |
+
return fixes # (a plank thrown out of reach cannot be laid again)
|
| 846 |
+
fixes += 1
|
| 847 |
+
if not (raw[0] and raw[1]):
|
| 848 |
+
for _k in range(2):
|
| 849 |
+
if not self.plank_flat():
|
| 850 |
+
self.fix_plank()
|
| 851 |
+
plank_first = self._hand_clearance(self.pos(CAR)[:2], 0.0, self._grasp_z(CAR, True),
|
| 852 |
+
ignore=tuple(q for q in ITEMS if q != PLANK)) < 0.0
|
| 853 |
+
for o in ((PLANK, CAR) if plank_first else (CAR, PLANK)):
|
| 854 |
+
if o == CAR and (self.zmin(CAR) > TZ + 0.01 or self._near_squares(CAR) or self.in_keep_out(CAR)):
|
| 855 |
+
self.park(CAR)
|
| 856 |
+
if o == PLANK and (self.zmin(PLANK) > TZ + 0.006 or self._near_squares(PLANK)
|
| 857 |
+
or self.in_keep_out(PLANK)):
|
| 858 |
+
self.park(PLANK)
|
| 859 |
+
for i, s in enumerate(SQUARES):
|
| 860 |
+
if not self.stages()[0][i]:
|
| 861 |
+
self.build_pillar(s, True, nofn)
|
| 862 |
+
raw, _ = self.stages()
|
| 863 |
+
if raw[0] and raw[1] and not raw[2]:
|
| 864 |
+
if not self.plank_flat():
|
| 865 |
+
self.fix_plank()
|
| 866 |
+
if self.zmin(CAR) > TZ + 0.01 or self.in_keep_out(CAR):
|
| 867 |
+
self.park(CAR)
|
| 868 |
+
self.lay_plank(True, nofn)
|
| 869 |
+
raw, _ = self.stages()
|
| 870 |
+
if raw[2] and not raw[3]:
|
| 871 |
+
self.put_car(True, nofn)
|
| 872 |
+
return fixes
|
| 873 |
+
|
| 874 |
+
def _near_squares(self, o):
|
| 875 |
+
p = self.pos(o)[:2]
|
| 876 |
+
if o == PLANK:
|
| 877 |
+
ax = self.R(PLANK)[:2, 0]
|
| 878 |
+
pts = [p + s * ax * 0.11 for s in (-1, -0.5, 0, 0.5, 1)]
|
| 879 |
+
else:
|
| 880 |
+
pts = [p]
|
| 881 |
+
return any(np.linalg.norm(q - self.square_xy(s)) < 0.06 for q in pts for s in SQUARES)
|
| 882 |
+
|
| 883 |
+
# ------------------------------------------------------------ Sonnet-like naive (style "sonnet")
|
| 884 |
+
# Imitates how Claude Sonnet 5.5 moved in the lh1 pilot (runs/claude/lh1_bridge, 4 attempts, 230 commands):
|
| 885 |
+
# instruction order; for each pillar the free block nearest to its square first; a hover ~12 cm above the object
|
| 886 |
+
# with the gripper turned to the object's yaw, a straight vertical descent, grasp ~1 cm below the top; the carry
|
| 887 |
+
# often goes straight from the grasp to ~12.5 cm above the target (one move_eef: a diagonal climb), otherwise lift
|
| 888 |
+
# first; when the carried object's straight path would run into a built pillar it lifts first and carries with the
|
| 889 |
+
# object's bottom ~4 cm above that pillar; vertical descent, open, lift straight up to ~15 cm; plank: lift to 7 cm,
|
| 890 |
+
# carry at 16 cm; car: lift to 17 cm, carry, place, lift to 25 cm; no final check.
|
| 891 |
+
def _sn_grasp_z(self, o, sn):
|
| 892 |
+
if o == PLANK:
|
| 893 |
+
return self._grasp_z(PLANK, False)
|
| 894 |
+
return self.zmax(o) - sn["top_below"]
|
| 895 |
+
|
| 896 |
+
def _crossing_top(self, a, b, o, drop, hc):
|
| 897 |
+
"""top of the highest item that the held object o, carried straight from a to b with its bottom at hc - drop,
|
| 898 |
+
would run into (any footprint point within o's half size + 1 cm of the path), else None"""
|
| 899 |
+
a, b = np.asarray(a[:2], float), np.asarray(b[:2], float)
|
| 900 |
+
d = b - a
|
| 901 |
+
n2 = float(d @ d)
|
| 902 |
+
r = float(self.half(o)[0]) + 0.01
|
| 903 |
+
best = None
|
| 904 |
+
for q in ITEMS:
|
| 905 |
+
if q == o or self.held(q):
|
| 906 |
+
continue
|
| 907 |
+
top = self.zmax(q)
|
| 908 |
+
if top < hc - drop:
|
| 909 |
+
continue
|
| 910 |
+
pts = self.footprint(q)
|
| 911 |
+
t = np.clip((pts - a) @ d / n2, 0.0, 1.0) if n2 > 1e-9 else np.zeros(len(pts))
|
| 912 |
+
dist = float(np.min(np.linalg.norm(pts - (a + t[:, None] * d), axis=1)))
|
| 913 |
+
if dist < r and (best is None or top > best):
|
| 914 |
+
best = top
|
| 915 |
+
return best
|
| 916 |
+
|
| 917 |
+
def sn_pick(self, o, sn, noise=None):
|
| 918 |
+
sk = self.sk
|
| 919 |
+
p = self.pos(o)
|
| 920 |
+
if noise is not None:
|
| 921 |
+
p = p + np.array([noise[0], noise[1], 0.0])
|
| 922 |
+
zg = self._sn_grasp_z(o, sn)
|
| 923 |
+
if o == PLANK:
|
| 924 |
+
yaw = _wrap_h(self.yaw_of(PLANK))
|
| 925 |
+
elif o == CAR and sn["car_style"] == "keep":
|
| 926 |
+
yaw = None # keeps the gripper's current yaw (the pilot's seed 3000: still turned 90 deg from the plank)
|
| 927 |
+
else:
|
| 928 |
+
yaw = _wrap_q(self.yaw_of(o))
|
| 929 |
+
hover = TZ + (sn["car_hover"] if o == CAR else sn["hover"])
|
| 930 |
+
direct = o == CAR and sn["car_style"] == "direct" # (the pilot's seed 3001 went straight down to the car)
|
| 931 |
+
if not direct:
|
| 932 |
+
self._go([p[0], p[1], hover], yaw=yaw)
|
| 933 |
+
self._go([p[0], p[1], zg], yaw=yaw, tol=0.003, max_steps=250 if direct else 120)
|
| 934 |
+
sk.set_gripper(True, steps=15)
|
| 935 |
+
if not sk.holding(o):
|
| 936 |
+
sk.set_gripper(False, steps=15)
|
| 937 |
+
self._go([p[0], p[1], TZ + sn["hover"]])
|
| 938 |
+
return None
|
| 939 |
+
return float(sk.eef_pos()[2] - self.zmin(o))
|
| 940 |
+
|
| 941 |
+
def sn_place(self, o, xy, support_top, drop, yaw, sn, carry=None, lift=None, diag=None):
|
| 942 |
+
sk = self.sk
|
| 943 |
+
zr = support_top + drop + 0.004
|
| 944 |
+
hc = max(TZ + (sn["carry"] if carry is None else carry), zr + 0.03)
|
| 945 |
+
cur = sk.eef_pos()
|
| 946 |
+
diag = sn["diag"] if diag is None else diag
|
| 947 |
+
top = None if o == PLANK else self._crossing_top(cur, xy, o, drop, hc)
|
| 948 |
+
if top is not None: # a built pillar in the way: lift first, carry with the object's bottom above it
|
| 949 |
+
hc = max(hc, top + drop + sn["cross_margin"])
|
| 950 |
+
self._go([cur[0], cur[1], hc])
|
| 951 |
+
self._go([xy[0], xy[1], hc], yaw=yaw)
|
| 952 |
+
elif diag: # one move_eef from the grasp to above the target
|
| 953 |
+
self._go([xy[0], xy[1], hc], yaw=yaw)
|
| 954 |
+
else:
|
| 955 |
+
self._go([cur[0], cur[1], max(cur[2], hc + 0.02)])
|
| 956 |
+
self._go([xy[0], xy[1], hc], yaw=yaw)
|
| 957 |
+
self._go([xy[0], xy[1], zr], tol=0.003, max_steps=120)
|
| 958 |
+
sk.set_gripper(False, steps=15)
|
| 959 |
+
self._go([xy[0], xy[1], TZ + (sn["lift"] if lift is None else lift)])
|
| 960 |
+
sk.hold(5)
|
| 961 |
+
|
| 962 |
+
def sn_build_pillar(self, s, sn, noise_fn):
|
| 963 |
+
failed = {}
|
| 964 |
+
c = self.square_xy(s)
|
| 965 |
+
mid = self.bridge_mid()
|
| 966 |
+
for _ in range(5):
|
| 967 |
+
raw, (pa, pb) = self.stages()
|
| 968 |
+
low, up = (pa, pb)[SQUARES.index(s)]
|
| 969 |
+
if up is not None:
|
| 970 |
+
return True
|
| 971 |
+
other = (pa, pb)[1 - SQUARES.index(s)]
|
| 972 |
+
cand = [b for b in BLOCKS if b != low and b not in other and failed.get(b, 0) < 2]
|
| 973 |
+
if not cand:
|
| 974 |
+
return False
|
| 975 |
+
if sn["alloc"] == "side": # blocks on this square's side of the bridge first
|
| 976 |
+
side = np.sign(c[1] - mid[1])
|
| 977 |
+
same = [b for b in cand if np.sign(self.pos(b)[1] - mid[1]) == side]
|
| 978 |
+
cand = same or cand
|
| 979 |
+
b = min(cand, key=lambda q: (failed.get(q, 0), np.linalg.norm(self.pos(q)[:2] - c)))
|
| 980 |
+
drop = self.sn_pick(b, sn, noise=noise_fn())
|
| 981 |
+
if drop is None:
|
| 982 |
+
failed[b] = failed.get(b, 0) + 1
|
| 983 |
+
continue
|
| 984 |
+
tgt, top = (c, TZ) if low is None else (self.pos(low)[:2], self.zmax(low))
|
| 985 |
+
n = noise_fn()
|
| 986 |
+
# onto the bare square: straight from the grasp (diagonal climb); onto a block: lift first (a diagonal
|
| 987 |
+
# climb from nearby clips the lower block -- the pilot's seed 3000 did that once, then lifted first)
|
| 988 |
+
self.sn_place(b, tgt + (n if n is not None else 0.0), top, drop, 0.0, sn,
|
| 989 |
+
diag=None if low is None else False)
|
| 990 |
+
return self.stages()[1][SQUARES.index(s)][1] is not None
|
| 991 |
+
|
| 992 |
+
def sn_lay_plank(self, sn, noise_fn):
|
| 993 |
+
raw, (pa, pb) = self.stages()
|
| 994 |
+
if pa[1] is None or pb[1] is None:
|
| 995 |
+
return False
|
| 996 |
+
drop = self.sn_pick(PLANK, sn, noise=noise_fn())
|
| 997 |
+
if drop is None:
|
| 998 |
+
return False
|
| 999 |
+
cur = self.sk.eef_pos()
|
| 1000 |
+
self._go([cur[0], cur[1], TZ + sn["plank_lift"]])
|
| 1001 |
+
raw, (pa, pb) = self.stages()
|
| 1002 |
+
if pa[1] is None or pb[1] is None:
|
| 1003 |
+
tops, mid = [TZ + 0.11, TZ + 0.11], self.bridge_mid()
|
| 1004 |
+
else:
|
| 1005 |
+
tops = [self.zmax(pa[1]), self.zmax(pb[1])]
|
| 1006 |
+
mid = (self.pos(pa[1])[:2] + self.pos(pb[1])[:2]) / 2
|
| 1007 |
+
n = noise_fn()
|
| 1008 |
+
mid = mid + (n if n is not None else 0.0)
|
| 1009 |
+
self.sn_place(PLANK, mid, max(tops), drop, np.pi / 2, sn, carry=sn["plank_carry"], lift=sn["plank_end_lift"],
|
| 1010 |
+
diag=True)
|
| 1011 |
+
return True
|
| 1012 |
+
|
| 1013 |
+
def sn_put_car(self, sn, noise_fn):
|
| 1014 |
+
drop = self.sn_pick(CAR, sn, noise=noise_fn())
|
| 1015 |
+
if drop is None: # (in the pilot, Sonnet stopped here when it saw the bridge come down)
|
| 1016 |
+
return False
|
| 1017 |
+
n = noise_fn()
|
| 1018 |
+
pp = self.pos(PLANK)[:2] + (n if n is not None else 0.0)
|
| 1019 |
+
self.sn_place(CAR, pp, self.zmax(PLANK), drop, None, sn, carry=sn["car_lift"], lift=sn["end_lift"],
|
| 1020 |
+
diag=False)
|
| 1021 |
+
return True
|
| 1022 |
+
|
| 1023 |
+
# ------------------------------------------------------------ execution
|
| 1024 |
+
def execute(self, inst, params):
|
| 1025 |
+
mode = params.get("mode", "naive")
|
| 1026 |
+
careful = mode == "careful"
|
| 1027 |
+
rng = np.random.default_rng(params.get("noise_seed", 0))
|
| 1028 |
+
sig = float(params.get("noise", 0.0))
|
| 1029 |
+
noise_fn = (lambda: rng.uniform(-sig, sig, 2)) if sig > 0 else (lambda: None)
|
| 1030 |
+
z_t = params.get("z_t")
|
| 1031 |
+
self.naive_lift = float(params.get("lift", NAIVE_LIFT))
|
| 1032 |
+
style = params.get("style", "sonnet")
|
| 1033 |
+
if not careful and style == "sonnet":
|
| 1034 |
+
sn = dict(SN)
|
| 1035 |
+
sn.update(params.get("sn", {}))
|
| 1036 |
+
if sn["car_style"] is None:
|
| 1037 |
+
sn["car_style"] = CAR_STYLES[int(inst["seed"]) % 3]
|
| 1038 |
+
for s in SQUARES:
|
| 1039 |
+
self.sn_build_pillar(s, sn, noise_fn)
|
| 1040 |
+
self.sn_lay_plank(sn, noise_fn)
|
| 1041 |
+
self.sn_put_car(sn, noise_fn)
|
| 1042 |
+
else: # careful, or the v1 naive ("legs": vertical / horizontal legs at 8 cm; "diag")
|
| 1043 |
+
self.naive_style = style if style in ("legs", "diag") else NAIVE_STYLE
|
| 1044 |
+
if careful:
|
| 1045 |
+
self.clear_site()
|
| 1046 |
+
for s in SQUARES:
|
| 1047 |
+
self.build_pillar(s, careful, noise_fn, z_t=z_t, order=params.get("order", "target"))
|
| 1048 |
+
self.lay_plank(careful, noise_fn, z_t=z_t)
|
| 1049 |
+
self.put_car(careful, noise_fn, z_t=z_t)
|
| 1050 |
+
if params.get("check"):
|
| 1051 |
+
self.repair()
|
| 1052 |
+
cur = self.sk.eef_pos()
|
| 1053 |
+
if cur[2] < TZ + 0.20:
|
| 1054 |
+
self._go([cur[0], cur[1], cur[2] + 0.06], speed=0.15)
|
| 1055 |
+
|
| 1056 |
+
def default_params(self, inst):
|
| 1057 |
+
return dict(mode="naive", style="sonnet", check=False)
|
| 1058 |
+
|
| 1059 |
+
def oracle_params(self, inst):
|
| 1060 |
+
return dict(mode="careful", check=True)
|
| 1061 |
+
|
| 1062 |
+
def adapt_params(self, inst, history):
|
| 1063 |
+
return dict(mode="careful", check=True)
|
| 1064 |
+
|
| 1065 |
+
def blind_params(self, inst, attempt, rng):
|
| 1066 |
+
sn = dict(hover=float(rng.uniform(0.10, 0.14)), carry=float(rng.uniform(0.11, 0.15)),
|
| 1067 |
+
lift=float(rng.uniform(0.13, 0.20)), diag=bool(rng.random() < 0.5),
|
| 1068 |
+
car_style=CAR_STYLES[int(rng.integers(3))], alloc="side" if rng.random() < 0.5 else "greedy")
|
| 1069 |
+
return dict(mode="naive", style="sonnet", check=False, sn=sn, noise=0.004, noise_seed=int(rng.integers(1 << 30)))
|
| 1070 |
+
|
| 1071 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 1072 |
+
"""kinds: oracle, naive (Sonnet-like, car approach style by seed), adaptive, blind; for comparison naive_v1 (the
|
| 1073 |
+
v1 naive: vertical / horizontal legs at 8 cm) and naive_hover / naive_keep / naive_direct (Sonnet-like with
|
| 1074 |
+
one fixed car approach style)"""
|
| 1075 |
+
k = k or self.max_attempts
|
| 1076 |
+
rng = np.random.default_rng(seed)
|
| 1077 |
+
history = []
|
| 1078 |
+
for a in range(k):
|
| 1079 |
+
self.reset_instance(inst)
|
| 1080 |
+
if kind == "oracle":
|
| 1081 |
+
params = self.oracle_params(inst)
|
| 1082 |
+
elif kind == "naive":
|
| 1083 |
+
params = self.default_params(inst)
|
| 1084 |
+
elif kind == "naive_v1":
|
| 1085 |
+
params = dict(mode="naive", style="legs", check=False)
|
| 1086 |
+
elif kind.startswith("naive_") and kind[6:] in CAR_STYLES: # naive_hover / naive_keep / naive_direct
|
| 1087 |
+
params = dict(mode="naive", style="sonnet", check=False, sn=dict(car_style=kind[6:]))
|
| 1088 |
+
elif kind == "adaptive":
|
| 1089 |
+
params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history)
|
| 1090 |
+
elif kind == "blind":
|
| 1091 |
+
params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
|
| 1092 |
+
else:
|
| 1093 |
+
raise ValueError(kind)
|
| 1094 |
+
self.execute(inst, params)
|
| 1095 |
+
out = self.outcome(inst)
|
| 1096 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 1097 |
+
if on_attempt:
|
| 1098 |
+
on_attempt(a, params, out)
|
| 1099 |
+
if out["success"] or kind == "oracle" or kind.startswith("naive"):
|
| 1100 |
+
break
|
| 1101 |
+
return history
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/lh_nudge_row.py
ADDED
|
@@ -0,0 +1,821 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 1 |
+
"""LH lh_nudge_row v2 (2026-10-14): stand four small cups, one by one, on the four coloured mats of their colours; the
|
| 2 |
+
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
|
| 3 |
+
opening towards the cup already standing on the next mat pushes that cup 1.5-3.4 cm sideways, half off its mat -- it
|
| 4 |
+
stays upright, so the damage is small but visible (a near miss that has to be noticed and undone before finishing).
|
| 5 |
+
|
| 6 |
+
Family: long-horizon self-disturbance ("state_restoration"): every placement is a later stage that can physically undo an
|
| 7 |
+
earlier one; the agent has to look back at all cups before finishing (within an attempt) or learn to let go without
|
| 8 |
+
pushing (across attempts).
|
| 9 |
+
|
| 10 |
+
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
|
| 11 |
+
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
|
| 12 |
+
see it (the oblique agentview camera looks along x; a tall cup hides the ring behind it), so 5 of 7 attempts failed
|
| 13 |
+
without any nudge (one was a calibration attempt), and the one clear nudge (s3000) left the cup 0.83 cm off --
|
| 14 |
+
invisible. Its left-right errors were <= 0.7 cm, its releases in attempt 1 almost all at wrist yaw ~0 (fingers opening
|
| 15 |
+
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
|
| 16 |
+
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
|
| 17 |
+
release pushes the neighbour sideways, where the camera resolves it, off its mat onto the table, and (3) uses slimmer cups
|
| 18 |
+
(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.
|
| 19 |
+
Code and results of v1: lh_nudge_row.py.bak-20261014-v1, results/_old/lh_nudge_row_v1/.
|
| 20 |
+
|
| 21 |
+
Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
|
| 22 |
+
* four coloured mats (dark red, blue, green, ochre; flat, visual only), each 9.0 cm (forward-back) x 4.6 cm, in two rows
|
| 23 |
+
(far and near, 1.5 cm apart); block centre 53-59 cm in front of the robot base. Tight block (14 of every 20
|
| 24 |
+
consecutive seeds): the two mats of a row touch. Spaced block (6 of 20): they are 4-5 cm apart and no open finger
|
| 25 |
+
reaches the neighbour (the benign instances);
|
| 26 |
+
* 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,
|
| 27 |
+
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
|
| 28 |
+
order and 9-10 cm apart.
|
| 29 |
+
|
| 30 |
+
Risk factor: the block's spacing (visible, instance level); there is no hidden physical variable (v1 measured that a
|
| 31 |
+
rubber-footed cup gets tipped over by a re-grasp next to it, and a fallen cup cannot be stood up again).
|
| 32 |
+
|
| 33 |
+
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
|
| 34 |
+
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
|
| 35 |
+
neighbour's wall is 3.6 cm away (+- the placement errors). Measured: letting go with the fingers along the row (wrist yaw
|
| 36 |
+
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
|
| 37 |
+
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
|
| 38 |
+
friction 0.18 or with 2.6 cm cups whose closed finger already presses the neighbour's rim, slim cups tipped over (4/18
|
| 39 |
+
and 6/18) -- hence the low friction and the 2 cm cups. A careful agent avoids the push by letting go with the fingers
|
| 40 |
+
opening forward-back (wrist yaw 90: the mats of the other row are 10.5 cm away) or diagonally, and repairs it by
|
| 41 |
+
re-centring the pushed cup (lifted 10 cm, carried back, let go the same careful way).
|
| 42 |
+
|
| 43 |
+
Success predicates (evaluated every other control step by a monitor, debounced over 0.5 s): each cup stands upright
|
| 44 |
+
(tilt <= 10 deg) on the table, not held, with its whole base on its own mat: centre within 3.0 cm (forward-back) and
|
| 45 |
+
1.3 cm (left-right) of the mat's centre. Success = all four at the end, gripper open and not touching any cup, scene
|
| 46 |
+
static. The monitor logs achieved / lost / restored per cup, cup_nudged (lost while not held, with displacement and
|
| 47 |
+
cause), cup_bumped (pushed by the robot but still on its mat) and cup_restored, for the server log only (F1 gives the
|
| 48 |
+
agent only success / failure).
|
| 49 |
+
|
| 50 |
+
Protocol: cross (reset to the same instance before every attempt), k = 3.
|
| 51 |
+
"""
|
| 52 |
+
import numpy as np
|
| 53 |
+
|
| 54 |
+
from .. import envs
|
| 55 |
+
from ..bddl import write_bddl
|
| 56 |
+
from ..objects import _fmt, _wrap, register_generated
|
| 57 |
+
from ..skills import Skills
|
| 58 |
+
from ..task_base import LFFTask, register_task
|
| 59 |
+
|
| 60 |
+
TZ = envs.TABLE_Z
|
| 61 |
+
COLOURS = ["red", "blue", "green", "yellow"]
|
| 62 |
+
CUPS = [f"cup_{c}_1" for c in COLOURS]
|
| 63 |
+
MATS = [f"mat_{c}_1" for c in COLOURS]
|
| 64 |
+
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),
|
| 65 |
+
"yellow": (0.92, 0.76, 0.12, 1.0)}
|
| 66 |
+
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),
|
| 67 |
+
"yellow": (0.62, 0.50, 0.08, 1.0)} # dark shades: crisp edges on the light table, bright cups stand out
|
| 68 |
+
INSIDE_RGBA = (0.93, 0.92, 0.88, 1.0) # glazed inside of the cups (seen from above)
|
| 69 |
+
|
| 70 |
+
# cup geometry (fixed; only mass and base friction change per instance, so no runtime geom edits / BVH refits)
|
| 71 |
+
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)
|
| 72 |
+
COM_Z = -0.006 # centre of mass below the cup's mid-height (heavier base)
|
| 73 |
+
WALL_T, BASE_T = 0.0025, 0.003
|
| 74 |
+
NSEG = 12
|
| 75 |
+
CONTACT = 'solimp="0.95 0.99 0.001" solref="0.01 1"'
|
| 76 |
+
WALL_MU = 0.8
|
| 77 |
+
BASE_MU = (0.08, 0.12) # glazed base: a pushed cup slides; at 0.18 a slim cup pushed high up tipped (measured)
|
| 78 |
+
MASS = (0.020, 0.032)
|
| 79 |
+
|
| 80 |
+
# mats (targets) and block
|
| 81 |
+
TOL_X = 0.030 # forward-back: the cup centre may be 3 cm from the mat centre (mat 9 cm long) -- Sonnet's measured
|
| 82 |
+
# placement bias is 1-2.5 cm forward (v1 pilot), invisible to it in the oblique camera
|
| 83 |
+
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
|
| 84 |
+
MAT_L, MAT_W = 2 * (CUP_R + TOL_X), 2 * (CUP_R + TOL_Y) # base completely on the mat <=> centre within the tolerances
|
| 85 |
+
ROW_GAP = 0.015 # gap between the far row and the near row of mats (x)
|
| 86 |
+
SPACED_GAP = (0.040, 0.050) # spaced block: gap between the two mats of a row (y); an open finger cannot reach
|
| 87 |
+
P_TIGHT = 0.70 # 14 of every 20 consecutive seeds: the two mats of a row touch
|
| 88 |
+
BLOCK_X = (-0.13, -0.07) # block centre in world x (53-59 cm in front of the robot base)
|
| 89 |
+
SUP_D = (0.175, 0.19) # supply line distance from the block centre
|
| 90 |
+
SUP_GAP = (0.090, 0.100)
|
| 91 |
+
|
| 92 |
+
# predicates / monitor
|
| 93 |
+
TILT_OK = np.radians(10.0)
|
| 94 |
+
ON_TABLE = 0.004
|
| 95 |
+
HYST = 0.002
|
| 96 |
+
DEBOUNCE = 10 # control steps (0.5 s)
|
| 97 |
+
BUMP_MIN = 0.003
|
| 98 |
+
|
| 99 |
+
# scripted motion (heights of the grasp point above the table)
|
| 100 |
+
Z_CARRY = 0.20 # Sonnet: lifts to ~20 cm before moving (lh2/lh3 pilots)
|
| 101 |
+
Z_LIFT = 0.15 # re-placing a cup that is already down: lift it this high (its base 11 cm up) before moving it
|
| 102 |
+
NAIVE_BIAS = (0.008, 0.022) # Sonnet's systematic forward placement error (v1 pilot: +0.8 ... +2.2 cm, per instance)
|
| 103 |
+
NAIVE_RAND = 0.006 # +- random placement error per axis (v1 pilot: left-right errors <= 0.7 cm)
|
| 104 |
+
NAIVE_FIX_RAND = 0.003 # after re-placing its own cup
|
| 105 |
+
FINGER_IN, FINGER_OUT, FINGER_HALF = 0.039, 0.066, 0.013 # open finger footprint (m from the grasp point / half width)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _wrap_h(a):
|
| 109 |
+
"""wrap to [-pi/2, pi/2) (the gripper is symmetric under 180 deg)"""
|
| 110 |
+
return float((a + np.pi / 2) % np.pi - np.pi / 2)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def cup_xml(name, rgba):
|
| 114 |
+
"""open-top cup: 12 wall boxes (1 mm above the bottom) and an octagonal base of two square boxes (box-box contacts:
|
| 115 |
+
a light cylinder on the table creeps by itself in MuJoCo, measured 1.6 cm / 5 s). Visual: a smooth cylinder with the
|
| 116 |
+
glazed inside at the top. The compiled inertial is replaced per instance (mass), the base friction too."""
|
| 117 |
+
r, h = CUP_R, CUP_H
|
| 118 |
+
g = [f' <inertial pos="0 0 {COM_Z:.4f}" mass="0.055" diaginertia="2.6e-5 2.6e-5 1.6e-5" />']
|
| 119 |
+
s = r * np.sin(np.pi / NSEG) + 0.0006
|
| 120 |
+
rc = r * np.cos(np.pi / NSEG) - WALL_T / 2
|
| 121 |
+
for k in range(NSEG):
|
| 122 |
+
a = 2 * np.pi * k / NSEG
|
| 123 |
+
q = [np.cos(a / 2), 0, 0, np.sin(a / 2)]
|
| 124 |
+
g.append(f' <geom name="{name}_w{k}" type="box" size="{WALL_T / 2:.5f} {s:.5f} {(h - 0.001) / 2:.5f}" '
|
| 125 |
+
f'pos="{rc * np.cos(a):.5f} {rc * np.sin(a):.5f} 0.0005" quat="{_fmt(q)}" rgba="{_fmt(rgba)}" '
|
| 126 |
+
f'friction="{WALL_MU} 0.005 0.0001" {CONTACT} group="0" />')
|
| 127 |
+
a0 = r * 0.70
|
| 128 |
+
for k, ang in enumerate((0.0, np.pi / 4)):
|
| 129 |
+
q = [np.cos(ang / 2), 0, 0, np.sin(ang / 2)]
|
| 130 |
+
g.append(f' <geom name="{name}_b{k}" type="box" size="{a0:.5f} {a0:.5f} {BASE_T / 2:.5f}" '
|
| 131 |
+
f'pos="0 0 {-h / 2 + BASE_T / 2:.5f}" quat="{_fmt(q)}" rgba="{_fmt(rgba)}" '
|
| 132 |
+
f'friction="0.5 0.005 0.0001" {CONTACT} group="0" />')
|
| 133 |
+
g.append(f' <geom type="cylinder" size="{r:.5f} {h / 2:.5f}" rgba="{_fmt(rgba)}" contype="0" conaffinity="0" '
|
| 134 |
+
f'group="1" />')
|
| 135 |
+
g.append(f' <geom type="cylinder" size="{r - WALL_T:.5f} 0.0004" pos="0 0 {h / 2 - 0.0003:.5f}" '
|
| 136 |
+
f'rgba="{_fmt(INSIDE_RGBA)}" contype="0" conaffinity="0" group="1" />')
|
| 137 |
+
return _wrap(name, "\n".join(g), h / 2, r)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def mat_xml(name, rgba):
|
| 141 |
+
"""flat coloured mat (visual only), long side along body x"""
|
| 142 |
+
g = (f' <geom type="box" size="{MAT_L / 2:.5f} {MAT_W / 2:.5f} 0.0004" rgba="{_fmt(rgba)}" contype="0" '
|
| 143 |
+
f'conaffinity="0" group="1" />')
|
| 144 |
+
return _wrap(name, g, 0.0004, float(np.hypot(MAT_L, MAT_W) / 2))
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def _fb(d):
|
| 148 |
+
return f"{100 * abs(d):.1f} cm {'forward' if d > 0 else 'back'}"
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _lr(d):
|
| 152 |
+
return f"{100 * abs(d):.1f} cm to the {'left' if d > 0 else 'right'}"
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class NudgeSkills(Skills):
|
| 156 |
+
"""Skills that feed the task's per-step monitor."""
|
| 157 |
+
|
| 158 |
+
def __init__(self, env, task, recorder=None):
|
| 159 |
+
super().__init__(env, recorder=recorder)
|
| 160 |
+
self.task = task
|
| 161 |
+
|
| 162 |
+
def _act(self, dpos, drot, grip):
|
| 163 |
+
super()._act(dpos, drot, grip)
|
| 164 |
+
self.task.monitor_step()
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
@register_task
|
| 168 |
+
class NudgeRow(LFFTask):
|
| 169 |
+
name = "lh_nudge_row"
|
| 170 |
+
level = "L2"
|
| 171 |
+
category = "state_restoration"
|
| 172 |
+
capabilities = ("Perceive", "Plan", "Reason", "Restore")
|
| 173 |
+
protocol = "cross"
|
| 174 |
+
max_attempts = 3
|
| 175 |
+
# careful: ~10 commands per cup (40) + re-placing an imprecise cup or two (~15) + re-centring two pushed cups (~20)
|
| 176 |
+
# + looking / small corrections (~20), with some margin
|
| 177 |
+
agent_max_steps = 110
|
| 178 |
+
instruction = ("Stand each of the four small cups on the mat of the same colour. The four coloured mats lie on the "
|
| 179 |
+
"table in two rows of two. At the end every cup must stand upright with its whole base on its own "
|
| 180 |
+
"mat (not touching another mat or the table around it), and the gripper must be open and clear of "
|
| 181 |
+
"the cups.")
|
| 182 |
+
instruction_indirect = ("Set each little cup down on the coloured patch that matches it; the four patches form two "
|
| 183 |
+
"rows of two. When you are done every cup has to stand upright with its bottom completely "
|
| 184 |
+
"on its own patch, and the gripper must be open and away from the cups.")
|
| 185 |
+
agent_object_names = ["small cups (red, blue, green, yellow)",
|
| 186 |
+
"coloured mats (red, blue, green, yellow) in two rows of two"]
|
| 187 |
+
|
| 188 |
+
# ------------------------------------------------------------ scene
|
| 189 |
+
def make_bddl(self):
|
| 190 |
+
objs, fx = [], []
|
| 191 |
+
for i, (c, cup) in enumerate(zip(COLOURS, CUPS)):
|
| 192 |
+
cat = register_generated(f"LffLhnCup{c.capitalize()}", cup_xml(f"lff_lhn_cup_{c}", RGBA[c]))
|
| 193 |
+
objs.append((cup, cat, f"cup{i}_region", (-0.30 + 0.12 * i, 0.30, -0.29 + 0.12 * i, 0.31)))
|
| 194 |
+
for i, (c, mat) in enumerate(zip(COLOURS, MATS)):
|
| 195 |
+
cat = register_generated(f"LffLhnMat{c.capitalize()}", mat_xml(f"lff_lhn_mat_{c}", MAT_RGBA[c]), free=False)
|
| 196 |
+
fx.append((mat, cat, f"mat{i}_region", (-0.30 + 0.12 * i, -0.31, -0.29 + 0.12 * i, -0.30)))
|
| 197 |
+
return write_bddl(self.name, "Stand each cup on the mat of its colour", objs, fx)
|
| 198 |
+
|
| 199 |
+
def __init__(self, cam_res=None):
|
| 200 |
+
super().__init__(cam_res)
|
| 201 |
+
m = self.env.sim.model
|
| 202 |
+
self.mat_bid = {k: m.body_name2id(self.env.fixtures_dict[k].root_body) for k in MATS}
|
| 203 |
+
self.cgeoms = {c: envs.obj_geom_ids(self.env, c) for c in CUPS}
|
| 204 |
+
self.cbody = {c: int(m.geom_bodyid[self.cgeoms[c][0]]) for c in CUPS}
|
| 205 |
+
self.base_geoms = {c: [g for g in self.cgeoms[c] if (m.geom_id2name(g) or "").split("_")[-1] in ("b0", "b1")]
|
| 206 |
+
for c in CUPS}
|
| 207 |
+
self.finger_geoms, self.hand_geoms = [], []
|
| 208 |
+
for g in envs.robot_geom_ids(self.env):
|
| 209 |
+
n = m.geom_id2name(g) or ""
|
| 210 |
+
(self.finger_geoms if "finger" in n else self.hand_geoms).append(g)
|
| 211 |
+
# per-geom lookup tables for the substep contact check: cup index (-1 none), robot part (1 finger, 2 hand)
|
| 212 |
+
self.owner = np.full(m.ngeom, -1, int)
|
| 213 |
+
for i, c in enumerate(CUPS):
|
| 214 |
+
self.owner[self.cgeoms[c]] = i
|
| 215 |
+
self.part = np.zeros(m.ngeom, int)
|
| 216 |
+
self.part[self.finger_geoms] = 1
|
| 217 |
+
self.part[self.hand_geoms] = 2
|
| 218 |
+
self._sub_rob, self._sub_obj = {}, {}
|
| 219 |
+
# contacts are collected after every MuJoCo substep: an opening finger can flick a light cup within one control
|
| 220 |
+
# step (same technique as lh_fence; wrappers chain)
|
| 221 |
+
sim = self.env.sim
|
| 222 |
+
if not getattr(sim, "_lhn_wrapped", False):
|
| 223 |
+
orig = sim.step
|
| 224 |
+
|
| 225 |
+
def step(*a, **k):
|
| 226 |
+
orig(*a, **k)
|
| 227 |
+
t = getattr(sim, "_lhn_task", None)
|
| 228 |
+
if t is not None and t.mon is not None:
|
| 229 |
+
t._substep()
|
| 230 |
+
sim.step = step
|
| 231 |
+
sim._lhn_wrapped = True
|
| 232 |
+
sim._lhn_task = self
|
| 233 |
+
self.inst = None
|
| 234 |
+
self.mon = None
|
| 235 |
+
self.sk = None
|
| 236 |
+
|
| 237 |
+
def _substep(self):
|
| 238 |
+
d = self.env.sim.data
|
| 239 |
+
n = d.ncon
|
| 240 |
+
if not n:
|
| 241 |
+
return
|
| 242 |
+
g1 = np.asarray(d.contact.geom1)[:n]
|
| 243 |
+
g2 = np.asarray(d.contact.geom2)[:n]
|
| 244 |
+
o1, o2 = self.owner[g1], self.owner[g2]
|
| 245 |
+
for a, b, pa, pb in zip(g1, g2, o1, o2):
|
| 246 |
+
if pa < 0 and pb < 0:
|
| 247 |
+
continue
|
| 248 |
+
if pa >= 0 and pb >= 0:
|
| 249 |
+
if pa != pb:
|
| 250 |
+
self._sub_obj[int(pa)] = int(pb)
|
| 251 |
+
self._sub_obj[int(pb)] = int(pa)
|
| 252 |
+
continue
|
| 253 |
+
p, o = (pa, b) if pa >= 0 else (pb, a)
|
| 254 |
+
part = self.part[o]
|
| 255 |
+
if part:
|
| 256 |
+
prev = self._sub_rob.get(int(p), 0)
|
| 257 |
+
self._sub_rob[int(p)] = 1 if (part == 1 or prev == 1) else 2
|
| 258 |
+
|
| 259 |
+
# ------------------------------------------------------------ instances
|
| 260 |
+
def sample_instance(self, seed):
|
| 261 |
+
rng = np.random.default_rng(seed)
|
| 262 |
+
tight = bool((int(seed) * 7) % 20 < round(20 * P_TIGHT)) # balanced: 14 of every 20 consecutive seeds
|
| 263 |
+
gap_y = 0.0 if tight else float(rng.uniform(*SPACED_GAP))
|
| 264 |
+
py = MAT_W + gap_y # mat centre to mat centre within a row (left-right)
|
| 265 |
+
px = MAT_L + ROW_GAP # far row to near row (forward-back)
|
| 266 |
+
bx = float(rng.uniform(*BLOCK_X))
|
| 267 |
+
side = str(rng.choice(["front", "left", "right"]))
|
| 268 |
+
by = float(rng.uniform(-0.04, 0.04))
|
| 269 |
+
if side == "left":
|
| 270 |
+
by = float(rng.uniform(-0.08, -0.04))
|
| 271 |
+
elif side == "right":
|
| 272 |
+
by = float(rng.uniform(0.04, 0.08))
|
| 273 |
+
# mat positions: block slots (far-left, far-right, near-left, near-right), colours permuted
|
| 274 |
+
slots = {"far_left": [bx + px / 2, by + py / 2], "far_right": [bx + px / 2, by - py / 2],
|
| 275 |
+
"near_left": [bx - px / 2, by + py / 2], "near_right": [bx - px / 2, by - py / 2]}
|
| 276 |
+
names = list(slots)
|
| 277 |
+
perm = rng.permutation(4)
|
| 278 |
+
mats = {COLOURS[i]: slots[names[perm[i]]] for i in range(4)}
|
| 279 |
+
slot_of = {COLOURS[i]: names[perm[i]] for i in range(4)}
|
| 280 |
+
# supply line
|
| 281 |
+
d = float(rng.uniform(*SUP_D))
|
| 282 |
+
gap = float(rng.uniform(*SUP_GAP))
|
| 283 |
+
offs = (np.arange(4) - 1.5) * gap + float(rng.uniform(-0.02, 0.02))
|
| 284 |
+
if side == "front":
|
| 285 |
+
sup = [[bx - d + float(rng.uniform(-0.008, 0.008)), by + o] for o in offs]
|
| 286 |
+
else:
|
| 287 |
+
sgn = 1.0 if side == "left" else -1.0
|
| 288 |
+
sup = [[bx + o, by + sgn * (d - 0.02) + float(rng.uniform(-0.008, 0.008))] for o in offs]
|
| 289 |
+
order = rng.permutation(4)
|
| 290 |
+
start = {COLOURS[i]: [float(v) for v in sup[order[i]]] for i in range(4)}
|
| 291 |
+
mu = {c: float(rng.uniform(*BASE_MU)) for c in COLOURS}
|
| 292 |
+
mass = {c: float(rng.uniform(*MASS)) for c in COLOURS}
|
| 293 |
+
yaw0 = {c: float(rng.uniform(-np.pi, np.pi)) for c in COLOURS}
|
| 294 |
+
return dict(seed=int(seed), pitch_y=py, pitch_x=px, gap_y=gap_y, block=[bx, by], supply_side=side,
|
| 295 |
+
supply_d=d, supply_gap=gap, mats=mats, slot_of=slot_of, start=start, mu=mu, mass=mass, yaw0=yaw0,
|
| 296 |
+
tight=tight, block_kind="tight" if tight else "spaced",
|
| 297 |
+
naive_bias_x=float(rng.uniform(*NAIVE_BIAS)))
|
| 298 |
+
|
| 299 |
+
def apply_instance(self, inst):
|
| 300 |
+
self.inst = inst
|
| 301 |
+
m = self.env.sim.model
|
| 302 |
+
for c, cup in zip(COLOURS, CUPS):
|
| 303 |
+
b = self.cbody[cup]
|
| 304 |
+
M = inst["mass"][c]
|
| 305 |
+
m.body_mass[b] = M
|
| 306 |
+
# thin-walled cup (wall + base), approximately
|
| 307 |
+
m.body_inertia[b] = [M * (CUP_R ** 2 / 2 + CUP_H ** 2 / 12), M * (CUP_R ** 2 / 2 + CUP_H ** 2 / 12),
|
| 308 |
+
M * CUP_R ** 2 * 0.8]
|
| 309 |
+
for g in self.base_geoms[cup]:
|
| 310 |
+
m.geom_friction[g] = [inst["mu"][c], 0.005, 0.0001]
|
| 311 |
+
m.geom_priority[g] = 2
|
| 312 |
+
for c, mat in zip(COLOURS, MATS):
|
| 313 |
+
x, y = inst["mats"][c]
|
| 314 |
+
m.body_pos[self.mat_bid[mat]] = [x, y, TZ + 0.0005]
|
| 315 |
+
m.body_quat[self.mat_bid[mat]] = [1.0, 0.0, 0.0, 0.0]
|
| 316 |
+
self.env.sim.forward()
|
| 317 |
+
for c, cup in zip(COLOURS, CUPS):
|
| 318 |
+
envs.place_upright(self.env, cup, inst["start"][c], yaw=inst["yaw0"][c], clearance=0.0005)
|
| 319 |
+
|
| 320 |
+
def reset_instance(self, inst, recorder=None):
|
| 321 |
+
self.mon = None
|
| 322 |
+
self.env.reset()
|
| 323 |
+
self.apply_instance(inst)
|
| 324 |
+
self.env.sim.forward()
|
| 325 |
+
envs.settle(self.env, 15)
|
| 326 |
+
self.sk = NudgeSkills(self.env, self, recorder=recorder)
|
| 327 |
+
self._sub_rob, self._sub_obj = {}, {}
|
| 328 |
+
n = len(CUPS)
|
| 329 |
+
self.mon = dict(state=[False] * n, raw_since=[0] * n, ever=[False] * n, lost=[False] * n, events=[],
|
| 330 |
+
lost_cause=[None] * n,
|
| 331 |
+
anchor=[None] * n, last_robot=[None] * n, last_obj=[None] * n, nudged=[False] * n,
|
| 332 |
+
bump_ref=[None] * n, bump_step=[-1000] * n, n_steps=0)
|
| 333 |
+
return self.sk
|
| 334 |
+
|
| 335 |
+
# ------------------------------------------------------------ geometry / predicates
|
| 336 |
+
def pos(self, cup):
|
| 337 |
+
return envs.obj_pos(self.env, cup)
|
| 338 |
+
|
| 339 |
+
def tilt(self, cup):
|
| 340 |
+
return float(np.arccos(np.clip(envs.obj_upright_cos(self.env, cup), -1.0, 1.0)))
|
| 341 |
+
|
| 342 |
+
def held(self, cup):
|
| 343 |
+
return self.sk is not None and self.sk.holding(cup)
|
| 344 |
+
|
| 345 |
+
def mat_xy(self, i):
|
| 346 |
+
return np.asarray(self.inst["mats"][COLOURS[i]], float)
|
| 347 |
+
|
| 348 |
+
def offset(self, i):
|
| 349 |
+
return self.pos(CUPS[i])[:2] - self.mat_xy(i)
|
| 350 |
+
|
| 351 |
+
@staticmethod
|
| 352 |
+
def within(off, extra=0.0):
|
| 353 |
+
"""mat-frame offset (x forward-back, y left-right) inside the tolerances = the cup's whole base on its mat"""
|
| 354 |
+
return abs(float(off[0])) <= TOL_X + extra and abs(float(off[1])) <= TOL_Y + extra
|
| 355 |
+
|
| 356 |
+
def on_mat(self, i, extra=0.0):
|
| 357 |
+
cup = CUPS[i]
|
| 358 |
+
if self.tilt(cup) > TILT_OK + (np.radians(2.0) if extra else 0.0):
|
| 359 |
+
return False
|
| 360 |
+
if not self.within(self.offset(i), extra):
|
| 361 |
+
return False
|
| 362 |
+
if envs.obj_min_z(self.env, cup) > TZ + ON_TABLE:
|
| 363 |
+
return False
|
| 364 |
+
return not self.held(cup)
|
| 365 |
+
|
| 366 |
+
def stages(self):
|
| 367 |
+
return [self.on_mat(i) for i in range(len(CUPS))]
|
| 368 |
+
|
| 369 |
+
# ------------------------------------------------------------ monitor
|
| 370 |
+
def monitor_step(self):
|
| 371 |
+
mon = self.mon
|
| 372 |
+
if mon is None or self.sk is None:
|
| 373 |
+
return
|
| 374 |
+
mon["n_steps"] += 1
|
| 375 |
+
t = self.sk.n_steps
|
| 376 |
+
rob = dict(self._sub_rob)
|
| 377 |
+
obj = dict(self._sub_obj)
|
| 378 |
+
self._sub_rob, self._sub_obj = {}, {}
|
| 379 |
+
gstate = "open" if self.sk.grip < 0 else "closed"
|
| 380 |
+
for i, part in rob.items():
|
| 381 |
+
if not self.held(CUPS[i]):
|
| 382 |
+
mon["last_robot"][i] = ["finger" if part == 1 else "hand", int(t), gstate]
|
| 383 |
+
for i, j in obj.items():
|
| 384 |
+
mon["last_obj"][i] = [COLOURS[j] + (" (held)" if self.held(CUPS[j]) else ""), int(t)]
|
| 385 |
+
if mon["n_steps"] % 2:
|
| 386 |
+
return
|
| 387 |
+
for i in range(len(CUPS)):
|
| 388 |
+
cup = CUPS[i]
|
| 389 |
+
raw = self.on_mat(i, HYST if mon["state"][i] else 0.0)
|
| 390 |
+
# bumps inside the tolerance
|
| 391 |
+
if mon["state"][i] and raw and not self.held(cup):
|
| 392 |
+
lr = mon["last_robot"][i]
|
| 393 |
+
if lr is not None and t - lr[1] <= 2 and mon["bump_ref"][i] is None:
|
| 394 |
+
mon["bump_ref"][i] = [self.pos(cup)[:2].tolist(), int(t), 0.0]
|
| 395 |
+
ref = mon["bump_ref"][i]
|
| 396 |
+
if ref is not None:
|
| 397 |
+
ref[2] = max(ref[2], float(np.degrees(self.tilt(cup))))
|
| 398 |
+
if t - ref[1] > 40:
|
| 399 |
+
dpos = float(np.linalg.norm(self.pos(cup)[:2] - np.asarray(mon["anchor"][i] or ref[0])))
|
| 400 |
+
if (dpos >= BUMP_MIN or ref[2] >= 2.0) and t - mon["bump_step"][i] > 60:
|
| 401 |
+
mon["events"].append(dict(cup=COLOURS[i], event="cup_bumped", step=int(ref[1]),
|
| 402 |
+
moved_cm=round(100 * dpos, 2), max_tilt_deg=round(ref[2], 1),
|
| 403 |
+
cause=self._cause(i, ref[1] + 1)))
|
| 404 |
+
mon["bump_step"][i] = int(t)
|
| 405 |
+
mon["bump_ref"][i] = None
|
| 406 |
+
if raw == mon["state"][i]:
|
| 407 |
+
mon["raw_since"][i] = 0
|
| 408 |
+
continue
|
| 409 |
+
mon["raw_since"][i] += 2
|
| 410 |
+
if mon["raw_since"][i] < DEBOUNCE:
|
| 411 |
+
continue
|
| 412 |
+
mon["state"][i] = raw
|
| 413 |
+
mon["raw_since"][i] = 0
|
| 414 |
+
t0 = int(t - DEBOUNCE + 1)
|
| 415 |
+
if raw:
|
| 416 |
+
restored = mon["lost"][i]
|
| 417 |
+
e = dict(stage=COLOURS[i], event="restored" if restored else "achieved", step=t0)
|
| 418 |
+
if restored:
|
| 419 |
+
e["after"] = mon["lost_cause"][i] # picked_up = the agent re-adjusted a cup it had placed itself
|
| 420 |
+
mon["events"].append(e)
|
| 421 |
+
if restored and mon["nudged"][i]:
|
| 422 |
+
mon["events"].append(dict(cup=COLOURS[i], event="cup_restored", step=t0))
|
| 423 |
+
mon["nudged"][i] = False
|
| 424 |
+
mon["ever"][i] = True
|
| 425 |
+
mon["anchor"][i] = self.pos(cup)[:2].tolist()
|
| 426 |
+
mon["bump_ref"][i] = None
|
| 427 |
+
else:
|
| 428 |
+
mon["lost"][i] = True
|
| 429 |
+
cause = self._cause(i, t)
|
| 430 |
+
mon["lost_cause"][i] = cause
|
| 431 |
+
mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t0, cause=cause))
|
| 432 |
+
if cause != "picked_up":
|
| 433 |
+
a = mon["anchor"][i]
|
| 434 |
+
d = self.pos(cup)[:2] - np.asarray(a if a is not None else self.mat_xy(i))
|
| 435 |
+
off = self.offset(i)
|
| 436 |
+
mon["events"].append(dict(cup=COLOURS[i], event="cup_nudged", step=t0, cause=cause,
|
| 437 |
+
moved_cm=[round(100 * float(d[0]), 2), round(100 * float(d[1]), 2)],
|
| 438 |
+
offset_cm=round(100 * float(np.linalg.norm(off)), 2),
|
| 439 |
+
tilt_deg=round(float(np.degrees(self.tilt(cup))), 1)))
|
| 440 |
+
mon["nudged"][i] = True
|
| 441 |
+
|
| 442 |
+
def _cause(self, i, t, window=60):
|
| 443 |
+
if self.held(CUPS[i]):
|
| 444 |
+
return "picked_up"
|
| 445 |
+
lr, lo = self.mon["last_robot"][i], self.mon["last_obj"][i]
|
| 446 |
+
cands = []
|
| 447 |
+
if lr is not None and t - lr[1] <= window:
|
| 448 |
+
cands.append((lr[1], f"robot_{lr[0]}" + ("_opening" if lr[2] == "open" else "")))
|
| 449 |
+
if lo is not None and t - lo[1] <= window:
|
| 450 |
+
cands.append((lo[1] - 30, "cup:" + lo[0])) # prefer the robot when both touched it recently
|
| 451 |
+
return max(cands)[1] if cands else "other"
|
| 452 |
+
|
| 453 |
+
def _finalize_monitor(self, raw):
|
| 454 |
+
"""close the event log at finish: a stage the debounced monitor still holds (it uses a 2 mm hysteresis) but the
|
| 455 |
+
final judge does not is logged as lost now (final=True), and vice versa"""
|
| 456 |
+
mon = self.mon
|
| 457 |
+
if mon is None:
|
| 458 |
+
return
|
| 459 |
+
t = int(self.sk.n_steps)
|
| 460 |
+
for i in range(len(CUPS)):
|
| 461 |
+
if raw[i] == mon["state"][i]:
|
| 462 |
+
continue
|
| 463 |
+
mon["state"][i] = raw[i]
|
| 464 |
+
if raw[i]:
|
| 465 |
+
restored = mon["lost"][i]
|
| 466 |
+
e = dict(stage=COLOURS[i], event="restored" if restored else "achieved", step=t, final=True)
|
| 467 |
+
if restored:
|
| 468 |
+
e["after"] = mon["lost_cause"][i]
|
| 469 |
+
mon["events"].append(e)
|
| 470 |
+
mon["ever"][i] = True
|
| 471 |
+
continue
|
| 472 |
+
mon["lost"][i] = True
|
| 473 |
+
cause = self._cause(i, t, window=10 ** 6) # the last contact may be long ago (slow creep across the line)
|
| 474 |
+
mon["lost_cause"][i] = cause
|
| 475 |
+
mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t, cause=cause, final=True))
|
| 476 |
+
if cause != "picked_up":
|
| 477 |
+
a = mon["anchor"][i]
|
| 478 |
+
d = self.pos(CUPS[i])[:2] - np.asarray(a if a is not None else self.mat_xy(i))
|
| 479 |
+
mon["events"].append(dict(cup=COLOURS[i], event="cup_nudged", step=t, cause=cause, final=True,
|
| 480 |
+
moved_cm=[round(100 * float(d[0]), 2), round(100 * float(d[1]), 2)],
|
| 481 |
+
offset_cm=round(100 * float(np.linalg.norm(self.offset(i))), 2),
|
| 482 |
+
tilt_deg=round(float(np.degrees(self.tilt(CUPS[i]))), 1)))
|
| 483 |
+
mon["nudged"][i] = True
|
| 484 |
+
|
| 485 |
+
# ------------------------------------------------------------ outcome
|
| 486 |
+
def _touching(self):
|
| 487 |
+
d = self.env.sim.data
|
| 488 |
+
rob = set(self.finger_geoms) | set(self.hand_geoms)
|
| 489 |
+
for j in range(d.ncon):
|
| 490 |
+
c = d.contact[j]
|
| 491 |
+
if (self.owner[c.geom1] >= 0 and c.geom2 in rob) or (self.owner[c.geom2] >= 0 and c.geom1 in rob):
|
| 492 |
+
return True
|
| 493 |
+
return False
|
| 494 |
+
|
| 495 |
+
def outcome(self, inst):
|
| 496 |
+
sk = self.sk
|
| 497 |
+
sk.hold(10)
|
| 498 |
+
p0 = {c: self.pos(c) for c in CUPS}
|
| 499 |
+
touching = False
|
| 500 |
+
for _ in range(20):
|
| 501 |
+
sk.hold(1)
|
| 502 |
+
touching = touching or self._touching()
|
| 503 |
+
moved = max(float(np.linalg.norm(self.pos(c) - p0[c])) for c in CUPS)
|
| 504 |
+
static = moved < 0.003
|
| 505 |
+
raw = self.stages()
|
| 506 |
+
self._finalize_monitor(raw)
|
| 507 |
+
held = [COLOURS[i] for i, c in enumerate(CUPS) if self.held(c)]
|
| 508 |
+
mon = self.mon
|
| 509 |
+
ev = list(mon["events"]) if mon else []
|
| 510 |
+
n_reg = sum(e.get("event") == "lost" and e.get("cause") != "picked_up" for e in ev)
|
| 511 |
+
n_lost = sum(e.get("event") == "lost" for e in ev)
|
| 512 |
+
n_res = sum(e.get("event") == "restored" and e.get("after") != "picked_up" for e in ev)
|
| 513 |
+
nudges = [e for e in ev if e.get("event") == "cup_nudged"]
|
| 514 |
+
bumps = [e for e in ev if e.get("event") == "cup_bumped"]
|
| 515 |
+
success = bool(all(raw) and static and not held and not touching)
|
| 516 |
+
ever = mon["ever"] if mon else [False] * len(CUPS)
|
| 517 |
+
tilted = [i for i in range(len(CUPS)) if self.tilt(CUPS[i]) > TILT_OK]
|
| 518 |
+
lost_final = [i for i in range(len(CUPS)) if not raw[i] and ever[i]]
|
| 519 |
+
never = [i for i in range(len(CUPS)) if not raw[i] and not ever[i]]
|
| 520 |
+
if success:
|
| 521 |
+
failure = "none"
|
| 522 |
+
elif held:
|
| 523 |
+
failure = "held"
|
| 524 |
+
elif touching:
|
| 525 |
+
failure = "touching"
|
| 526 |
+
elif tilted:
|
| 527 |
+
failure = "tipped"
|
| 528 |
+
elif lost_final:
|
| 529 |
+
failure = "nudged_out" if any(mon["nudged"][i] for i in lost_final) else "regressed"
|
| 530 |
+
elif never:
|
| 531 |
+
failure = "not_on_mat"
|
| 532 |
+
else:
|
| 533 |
+
failure = "not_static"
|
| 534 |
+
parts = []
|
| 535 |
+
if success:
|
| 536 |
+
parts.append("Every cup stands upright on the mat of its colour.")
|
| 537 |
+
for i in range(len(CUPS)):
|
| 538 |
+
if raw[i]:
|
| 539 |
+
continue
|
| 540 |
+
c, cup = COLOURS[i], CUPS[i]
|
| 541 |
+
if c in held:
|
| 542 |
+
parts.append(f"The {c} cup is still held by the gripper.")
|
| 543 |
+
continue
|
| 544 |
+
off = self.offset(i)
|
| 545 |
+
tl = np.degrees(self.tilt(cup))
|
| 546 |
+
where = f"{_fb(off[0])} and {_lr(off[1])} of the {c} mat's centre"
|
| 547 |
+
if tl > np.degrees(TILT_OK):
|
| 548 |
+
txt = (f"The {c} cup has fallen over" if tl > 45 else f"The {c} cup leans {tl:.0f} degrees") + f", {where}."
|
| 549 |
+
elif float(np.linalg.norm(off)) > 0.08:
|
| 550 |
+
txt = f"The {c} cup is not on the {c} mat (its centre is {100 * float(np.linalg.norm(off)):.0f} cm away)."
|
| 551 |
+
else:
|
| 552 |
+
over = []
|
| 553 |
+
if abs(off[1]) > TOL_Y:
|
| 554 |
+
over.append(f"{100 * (abs(off[1]) - TOL_Y):.1f} cm over the mat's {'left' if off[1] > 0 else 'right'} "
|
| 555 |
+
f"edge")
|
| 556 |
+
if abs(off[0]) > TOL_X:
|
| 557 |
+
over.append(f"{100 * (abs(off[0]) - TOL_X):.1f} cm over its {'far' if off[0] > 0 else 'near'} end")
|
| 558 |
+
txt = f"The {c} cup stands {where}; its base sticks out " + " and ".join(over) + "."
|
| 559 |
+
if ever[i]:
|
| 560 |
+
lost = [e for e in ev if e.get("stage") == c and e.get("event") == "lost"]
|
| 561 |
+
why = lost[-1].get("cause", "other") if lost else "other"
|
| 562 |
+
txt += {"robot_finger_opening": " It had stood on its mat; a finger pushed it when the gripper opened "
|
| 563 |
+
"next to it.",
|
| 564 |
+
"robot_finger": " It had stood on its mat; a finger pushed it.",
|
| 565 |
+
"robot_hand": " It had stood on its mat; the hand pushed it.",
|
| 566 |
+
}.get(why, " It had stood on its mat earlier and was pushed by another cup."
|
| 567 |
+
if why.startswith("cup:") else " It had stood on its mat earlier.")
|
| 568 |
+
parts.append(txt)
|
| 569 |
+
if not success and all(raw):
|
| 570 |
+
if touching:
|
| 571 |
+
parts.append("The gripper is still touching a cup.")
|
| 572 |
+
elif not static:
|
| 573 |
+
parts.append("Something was still moving.")
|
| 574 |
+
if nudges:
|
| 575 |
+
parts.append(f"During the attempt cups that stood on their mats were pushed off {len(nudges)} time(s); "
|
| 576 |
+
f"{n_res} time(s) a cup was put back.")
|
| 577 |
+
trap = bool(nudges)
|
| 578 |
+
return dict(success=success, stages={COLOURS[i]: bool(raw[i]) for i in range(len(CUPS))}, events=ev,
|
| 579 |
+
n_regressions=int(n_reg), n_lost=int(n_lost), n_restored=int(n_res), n_nudged=len(nudges),
|
| 580 |
+
n_bumped=len(bumps), trap_fired=trap, recovered_in_attempt=bool(trap and success),
|
| 581 |
+
nudged_cups=sorted({e["cup"] for e in nudges}), failure=failure, held=held,
|
| 582 |
+
touching=bool(touching), static=bool(static),
|
| 583 |
+
offsets_cm={COLOURS[i]: [round(100 * float(v), 2) for v in self.offset(i)] for i in range(4)},
|
| 584 |
+
tilts_deg={COLOURS[i]: round(float(np.degrees(self.tilt(CUPS[i]))), 1) for i in range(4)},
|
| 585 |
+
tight=bool(inst["tight"]), detail=" ".join(parts))
|
| 586 |
+
|
| 587 |
+
# ------------------------------------------------------------ scripted policies (move_to + gripper only)
|
| 588 |
+
def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300):
|
| 589 |
+
return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
|
| 590 |
+
|
| 591 |
+
def _lift_to(self, z, speed=0.15):
|
| 592 |
+
cur = self.sk.eef_pos()
|
| 593 |
+
if cur[2] < TZ + z - 0.005:
|
| 594 |
+
self._go([cur[0], cur[1], TZ + z], speed=speed)
|
| 595 |
+
|
| 596 |
+
def finger_clear(self, q, yaw, ignore=()):
|
| 597 |
+
"""smallest distance (m) between the open fingers at grasp point q (xy) with gripper yaw `yaw` and the wall of
|
| 598 |
+
any standing cup other than `ignore`; finger axis (-sin yaw, cos yaw)"""
|
| 599 |
+
a = np.array([-np.sin(yaw), np.cos(yaw)])
|
| 600 |
+
b = np.array([a[1], -a[0]])
|
| 601 |
+
best = 1.0
|
| 602 |
+
for cup in CUPS:
|
| 603 |
+
if cup in ignore or self.held(cup):
|
| 604 |
+
continue
|
| 605 |
+
rel = self.pos(cup)[:2] - np.asarray(q, float)
|
| 606 |
+
for s in (1.0, -1.0):
|
| 607 |
+
u = s * float(rel @ a)
|
| 608 |
+
v = float(rel @ b)
|
| 609 |
+
du = max(FINGER_IN - u, 0.0, u - FINGER_OUT)
|
| 610 |
+
dv = max(abs(v) - FINGER_HALF, 0.0)
|
| 611 |
+
best = min(best, float(np.hypot(du, dv)) - CUP_R)
|
| 612 |
+
return best
|
| 613 |
+
|
| 614 |
+
def safe_yaw(self, q, ignore=(), prefer=0.0):
|
| 615 |
+
"""the gripper yaw (0, 90, +-45 deg) whose open fingers stay farthest from the other cups at q"""
|
| 616 |
+
cands = [0.0, np.pi / 2, np.pi / 4, -np.pi / 4]
|
| 617 |
+
sc = [(round(min(self.finger_clear(q, y, ignore), 0.02), 3), -abs(_wrap_h(y - prefer)), y) for y in cands]
|
| 618 |
+
return max(sc)[2]
|
| 619 |
+
|
| 620 |
+
def grasp_cup(self, cup, yaw, depth, z_carry=Z_CARRY, v=0.2, err=None, lift=None):
|
| 621 |
+
"""open, go over the cup at transit height, straight down, close, lift. Returns True if held."""
|
| 622 |
+
sk = self.sk
|
| 623 |
+
p = self.pos(cup)
|
| 624 |
+
q = p[:2] + (np.asarray(err, float) if err is not None else 0.0)
|
| 625 |
+
zg = envs.obj_max_z(self.env, cup) - depth
|
| 626 |
+
sk.set_gripper(False, steps=8)
|
| 627 |
+
self._lift_to(z_carry)
|
| 628 |
+
self._go([q[0], q[1], max(sk.eef_pos()[2], TZ + z_carry)], yaw=yaw, speed=v)
|
| 629 |
+
self._go([q[0], q[1], zg + 0.015], speed=0.10)
|
| 630 |
+
self._go([q[0], q[1], zg], speed=0.04, tol=0.003, max_steps=150)
|
| 631 |
+
sk.set_gripper(True, steps=15)
|
| 632 |
+
cur = sk.eef_pos()
|
| 633 |
+
self._go([cur[0], cur[1], TZ + (z_carry if lift is None else lift)], speed=0.12)
|
| 634 |
+
sk.hold(5)
|
| 635 |
+
if not self.held(cup):
|
| 636 |
+
sk.set_gripper(False, steps=8)
|
| 637 |
+
return False
|
| 638 |
+
return True
|
| 639 |
+
|
| 640 |
+
def put_cup(self, cup, xy, yaw, z_carry=Z_CARRY, v=0.2, lift=None):
|
| 641 |
+
"""carry the held cup so that the cup (not the grasp point) is over xy, rotate to `yaw`, straight down until its
|
| 642 |
+
base is 3 mm above the table, let go, lift"""
|
| 643 |
+
sk = self.sk
|
| 644 |
+
rel = self.pos(cup)[:2] - sk.eef_pos()[:2]
|
| 645 |
+
q = np.asarray(xy, float) - rel
|
| 646 |
+
cur = sk.eef_pos()
|
| 647 |
+
self._go([q[0], q[1], max(cur[2], TZ + z_carry)], yaw=yaw, speed=v)
|
| 648 |
+
sk.hold(5)
|
| 649 |
+
rel = self.pos(cup)[:2] - sk.eef_pos()[:2] # the cup can shift in the fingers while the wrist turns
|
| 650 |
+
q = np.asarray(xy, float) - rel
|
| 651 |
+
dz = sk.eef_pos()[2] - envs.obj_min_z(self.env, cup)
|
| 652 |
+
zr = TZ + dz + 0.003
|
| 653 |
+
self._go([q[0], q[1], zr + 0.015], speed=0.10)
|
| 654 |
+
self._go([q[0], q[1], zr], speed=0.03, tol=0.003, max_steps=150)
|
| 655 |
+
sk.set_gripper(False, steps=12)
|
| 656 |
+
cur = sk.eef_pos()
|
| 657 |
+
self._go([cur[0], cur[1], TZ + (z_carry if lift is None else lift)], speed=0.15)
|
| 658 |
+
sk.hold(3)
|
| 659 |
+
|
| 660 |
+
def mat_order(self, mode="far_first"):
|
| 661 |
+
"""colour indices in placement order. far_first (Sonnet): the block row farthest from the supply first, then
|
| 662 |
+
the other; within a row from the left (robot's view)"""
|
| 663 |
+
sup = np.mean([self.inst["start"][c] for c in COLOURS], axis=0)
|
| 664 |
+
blk = np.asarray(self.inst["block"], float)
|
| 665 |
+
u = blk - sup
|
| 666 |
+
u = u / max(np.linalg.norm(u), 1e-9)
|
| 667 |
+
idx = list(range(4))
|
| 668 |
+
far = sorted(idx, key=lambda i: -float((self.mat_xy(i) - blk) @ u))
|
| 669 |
+
rows = [far[:2], far[2:]]
|
| 670 |
+
if mode == "near_first":
|
| 671 |
+
rows = rows[::-1]
|
| 672 |
+
out = []
|
| 673 |
+
for row in rows:
|
| 674 |
+
out += sorted(row, key=lambda i: (-self.mat_xy(i)[1], self.mat_xy(i)[0])) # left first
|
| 675 |
+
return out
|
| 676 |
+
|
| 677 |
+
@staticmethod
|
| 678 |
+
def looks_off(off, bias):
|
| 679 |
+
"""a (biased) observer's verdict: the cup looks off its mat centre by more than 0.8 cm in some direction"""
|
| 680 |
+
p = np.asarray(off, float) - np.asarray(bias, float)
|
| 681 |
+
return abs(p[0]) > 0.008 or abs(p[1]) > 0.008
|
| 682 |
+
|
| 683 |
+
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,
|
| 684 |
+
v=0.2):
|
| 685 |
+
"""one stage: pick cup i from wherever it is and put it on its mat; aims at mat + bias (+- rand per axis); then
|
| 686 |
+
looks at this cup only (with the same bias) and re-places it if it looks off"""
|
| 687 |
+
cup = CUPS[i]
|
| 688 |
+
bias = np.asarray(bias, float)
|
| 689 |
+
for _ in range(2):
|
| 690 |
+
gy = yaw_rule(i, "grasp")
|
| 691 |
+
gerr = rng.uniform(-0.003, 0.003, 2) if rand else None
|
| 692 |
+
if self.grasp_cup(cup, gy, depth, z_carry=z_carry, v=v, err=gerr):
|
| 693 |
+
break
|
| 694 |
+
else:
|
| 695 |
+
return
|
| 696 |
+
e = rng.uniform(-rand, rand, 2) if rand else np.zeros(2)
|
| 697 |
+
self.put_cup(cup, self.mat_xy(i) + bias + e, yaw_rule(i, "release"), z_carry=z_carry, v=v)
|
| 698 |
+
if not check:
|
| 699 |
+
return
|
| 700 |
+
for _ in range(2):
|
| 701 |
+
if not self.looks_off(self.offset(i), bias) and self.tilt(cup) < TILT_OK:
|
| 702 |
+
return
|
| 703 |
+
ry = yaw_rule(i, "grasp")
|
| 704 |
+
if not self.grasp_cup(cup, ry, depth, z_carry=Z_LIFT, v=0.1, lift=Z_LIFT):
|
| 705 |
+
return
|
| 706 |
+
e = rng.uniform(-fix_rand, fix_rand, 2) if fix_rand else np.zeros(2)
|
| 707 |
+
self.put_cup(cup, self.mat_xy(i) + bias + e, yaw_rule(i, "release"), z_carry=Z_LIFT, v=0.1, lift=z_carry)
|
| 708 |
+
|
| 709 |
+
def repair(self, rounds=4, depth=0.020, bias=(0.0, 0.0)):
|
| 710 |
+
"""look at every cup (with the observer's bias); re-centre each one that looks off: grasp and let go with the
|
| 711 |
+
fingers opening where no other cup stands. Returns the number of cups moved."""
|
| 712 |
+
bias = np.asarray(bias, float)
|
| 713 |
+
moved = 0
|
| 714 |
+
tries = {}
|
| 715 |
+
for _ in range(rounds * 4):
|
| 716 |
+
bad = [i for i in range(4) if (self.looks_off(self.offset(i), bias) or self.held(CUPS[i]))
|
| 717 |
+
and self.tilt(CUPS[i]) < np.radians(30) and tries.get(i, 0) < rounds]
|
| 718 |
+
if not bad:
|
| 719 |
+
break
|
| 720 |
+
i = min(bad, key=lambda j: float(np.linalg.norm(self.pos(CUPS[j])[:2] - self.sk.eef_pos()[:2])))
|
| 721 |
+
tries[i] = tries.get(i, 0) + 1
|
| 722 |
+
cup = CUPS[i]
|
| 723 |
+
gy = self.safe_yaw(self.pos(cup)[:2], ignore=(cup,), prefer=self.sk.yaw)
|
| 724 |
+
# lift the cup clear of its neighbours before moving it: carried at 10 cm its base clips their rims and
|
| 725 |
+
# tips them (v1, measured, 4/20 adaptive runs before this was raised)
|
| 726 |
+
if not self.grasp_cup(cup, gy, depth, z_carry=Z_LIFT, v=0.15, lift=Z_LIFT):
|
| 727 |
+
continue
|
| 728 |
+
moved += 1
|
| 729 |
+
target = self.mat_xy(i) + bias
|
| 730 |
+
ry = self.safe_yaw(target, ignore=(cup,), prefer=self.sk.yaw)
|
| 731 |
+
self.put_cup(cup, target, ry, z_carry=Z_LIFT, v=0.1, lift=Z_CARRY)
|
| 732 |
+
return moved
|
| 733 |
+
|
| 734 |
+
def execute(self, inst, params):
|
| 735 |
+
rng = np.random.default_rng(params.get("noise_seed", 0))
|
| 736 |
+
depth = params.get("depth", 0.020)
|
| 737 |
+
order = self.mat_order(params.get("order", "far_first"))
|
| 738 |
+
mode = params["yaw"] # "fixed" (one wrist yaw for everything) or "safe" (fingers away from placed cups)
|
| 739 |
+
y0 = float(params.get("yaw0", 0.0))
|
| 740 |
+
bias = (float(params.get("bias_x", 0.0)), 0.0)
|
| 741 |
+
|
| 742 |
+
def yaw_rule(i, what):
|
| 743 |
+
if mode == "fixed":
|
| 744 |
+
return y0
|
| 745 |
+
q = self.pos(CUPS[i])[:2] if what == "grasp" else self.mat_xy(i) + np.asarray(bias)
|
| 746 |
+
return self.safe_yaw(q, ignore=(CUPS[i],), prefer=y0)
|
| 747 |
+
|
| 748 |
+
rand = float(params.get("rand", 0.0))
|
| 749 |
+
for i in order:
|
| 750 |
+
self.place_one(i, yaw_rule, depth, rng, bias=bias, rand=rand, fix_rand=float(params.get("fix_rand", 0.0)),
|
| 751 |
+
check=params.get("self_check", True), z_carry=params.get("z_carry", Z_CARRY),
|
| 752 |
+
v=params.get("v", 0.2))
|
| 753 |
+
if params.get("check"):
|
| 754 |
+
self.repair(bias=bias)
|
| 755 |
+
self._lift_to(0.20)
|
| 756 |
+
self.sk.hold(10)
|
| 757 |
+
|
| 758 |
+
# naive = Sonnet 5.5's habits measured in the v1 pilot (np_lh_nudge_row): wrist yaw 0 for every grasp and release in
|
| 759 |
+
# attempt 1, the row farthest from the supply first, lift to 14-25 cm and carry straight, vertical descents,
|
| 760 |
+
# 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
|
| 761 |
+
# re-places it if it looks off, no look back at the others before finishing
|
| 762 |
+
NAIVE = dict(yaw="fixed", yaw0=0.0, order="far_first", self_check=True, check=False, rand=NAIVE_RAND,
|
| 763 |
+
fix_rand=NAIVE_FIX_RAND)
|
| 764 |
+
CAREFUL = dict(yaw="safe", yaw0=0.0, order="far_first", self_check=True, check=True, rand=0.0, bias_x=0.0)
|
| 765 |
+
|
| 766 |
+
def default_params(self, inst):
|
| 767 |
+
return dict(self.NAIVE, noise_seed=int(inst["seed"]) * 13, bias_x=float(inst["naive_bias_x"]),
|
| 768 |
+
depth=0.008 + 0.012 * ((int(inst["seed"]) * 7) % 11) / 10) # 0.8-2.0 cm below the rim (pilot: ~1 cm)
|
| 769 |
+
|
| 770 |
+
def oracle_params(self, inst):
|
| 771 |
+
return dict(self.CAREFUL)
|
| 772 |
+
|
| 773 |
+
def adapt_params(self, inst, history):
|
| 774 |
+
"""from attempt 2: let go with the fingers opening away from the placed cups (same imprecision and bias), and
|
| 775 |
+
look at every cup before finishing"""
|
| 776 |
+
return dict(self.default_params(inst), yaw="safe", check=True)
|
| 777 |
+
|
| 778 |
+
def blind_params(self, inst, attempt, rng):
|
| 779 |
+
"""the naive behaviour with random variation, no history, no final look"""
|
| 780 |
+
return dict(self.default_params(inst), noise_seed=int(rng.integers(1 << 30)),
|
| 781 |
+
yaw0=float(rng.choice([0.0, np.pi / 2])), order=str(rng.choice(["far_first", "near_first"])),
|
| 782 |
+
z_carry=float(rng.uniform(0.15, 0.22)), v=float(rng.uniform(0.1, 0.3)),
|
| 783 |
+
depth=float(rng.uniform(0.008, 0.025)), bias_x=float(rng.uniform(*NAIVE_BIAS)))
|
| 784 |
+
|
| 785 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 786 |
+
k = k or self.max_attempts
|
| 787 |
+
rng = np.random.default_rng(seed)
|
| 788 |
+
history = []
|
| 789 |
+
single = ("oracle", "naive", "oracle_noise", "naive_yaw90", "naive_check", "careful_bias2", "naive_bias2")
|
| 790 |
+
for a in range(k):
|
| 791 |
+
self.reset_instance(inst)
|
| 792 |
+
if kind == "oracle":
|
| 793 |
+
params = self.oracle_params(inst)
|
| 794 |
+
elif kind == "naive":
|
| 795 |
+
params = self.default_params(inst)
|
| 796 |
+
elif kind == "adaptive": # attempt 1: naive + a final look at every cup (repairs); then careful releases
|
| 797 |
+
params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history)
|
| 798 |
+
elif kind == "blind":
|
| 799 |
+
params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
|
| 800 |
+
elif kind == "switch": # control: cross-attempt learning only (careful releases from attempt 2), no final look
|
| 801 |
+
params = self.default_params(inst) if a == 0 else dict(self.default_params(inst), yaw="safe")
|
| 802 |
+
elif kind == "oracle_noise": # robustness: careful with +-5 mm placement / grasp noise
|
| 803 |
+
params = dict(self.CAREFUL, rand=0.005, noise_seed=int(seed) * 7 + a)
|
| 804 |
+
elif kind == "naive_yaw90": # control: Sonnet-like but the wrist turned 90 deg for everything
|
| 805 |
+
params = dict(self.default_params(inst), yaw0=np.pi / 2)
|
| 806 |
+
elif kind == "naive_check": # control: naive + final look (= adaptive's first attempt)
|
| 807 |
+
params = dict(self.default_params(inst), check=True)
|
| 808 |
+
elif kind == "careful_bias2": # control: careful releases (nothing nudged) but placed 2 cm too far forward
|
| 809 |
+
params = dict(self.default_params(inst), yaw="safe", bias_x=0.020)
|
| 810 |
+
elif kind == "naive_bias2": # control: naive with a fixed +2 cm forward bias
|
| 811 |
+
params = dict(self.default_params(inst), bias_x=0.020)
|
| 812 |
+
else:
|
| 813 |
+
raise ValueError(kind)
|
| 814 |
+
self.execute(inst, params)
|
| 815 |
+
out = self.outcome(inst)
|
| 816 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 817 |
+
if on_attempt:
|
| 818 |
+
on_attempt(a, params, out)
|
| 819 |
+
if out["success"] or kind in single:
|
| 820 |
+
break
|
| 821 |
+
return history
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/lh_shelf_droop.py
ADDED
|
@@ -0,0 +1,1009 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""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,
|
| 2 |
+
spring-loaded fold-down bracket with a weak catch: it stays level as long as the moment of its load about the hinge at
|
| 3 |
+
the wall is below the bracket's preload; once the load exceeds it the catch slips and the board folds down to its stop
|
| 4 |
+
within about a second, and the jars on it slide off its free edge onto the table, where they lie on their sides.
|
| 5 |
+
Jars set down in the middle of the board's depth -- where a careful agent puts them -- push the moment over the preload
|
| 6 |
+
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
|
| 7 |
+
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
|
| 8 |
+
(centres up to ~6 cm from it) stay under the preload. Unloaded, the board springs back level.
|
| 9 |
+
|
| 10 |
+
Family: long-horizon self-damage ("state_restoration"): a later stage (the third placement) undoes the earlier ones, a
|
| 11 |
+
moment after it was done, once the gripper has let go. Within an attempt the agent has to notice the fallen jars, stand
|
| 12 |
+
them up again (by their knobs) and put them back -- near the wall, or they slide off again; across attempts it has to
|
| 13 |
+
load the shelf near the wall. R4: "I put them down badly / dropped them too hard / my arm knocked them" vs "the shelf
|
| 14 |
+
gives way under a load far from the wall".
|
| 15 |
+
|
| 16 |
+
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,
|
| 17 |
+
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
|
| 18 |
+
the fourth jar, and the board drooped (or the jars slid off) only during the final settle, after `finish` -- 15 of 74
|
| 19 |
+
failing scripted attempts (20 %) showed nothing before finish; 4 jars 6 cm from the wall failed in 9 / 9 seeds. v2 raises
|
| 20 |
+
the preload (4 jars up to ~6 cm from the wall hold) and adds the catch + a soft spring + light damping, so every overload
|
| 21 |
+
folds the board down within a second, before the agent's next look.
|
| 22 |
+
|
| 23 |
+
Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
|
| 24 |
+
* 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
|
| 25 |
+
x in [-0.17, -0.12]), rising 4.5 cm above the shelf board;
|
| 26 |
+
* 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
|
| 27 |
+
the wall face (axis along x at mid-thickness); hard stop at 25 deg of droop. The agentview camera (behind the table,
|
| 28 |
+
+x, looking at the robot) sees the board from its end, so the droop is an in-image rotation of the slab;
|
| 29 |
+
* 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;
|
| 30 |
+
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
|
| 31 |
+
cm), 9 cm apart, in random order.
|
| 32 |
+
|
| 33 |
+
Hidden variable: the bracket. "loose" (14 of every 20 consecutive seeds): preload 0.62-0.68 N m; "stiff" (6 of 20):
|
| 34 |
+
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
|
| 35 |
+
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.
|
| 36 |
+
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
|
| 37 |
+
with two or more jars on it nothing stops a board whose catch has slipped before its 25 deg stop. Jar-on-board friction
|
| 38 |
+
0.27-0.33 per jar (they slide at ~14.5 deg at 0.30 in MuJoCo's soft contacts).
|
| 39 |
+
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
|
| 40 |
+
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,
|
| 41 |
+
two 0.51 (holds), three 0.76 (over).
|
| 42 |
+
|
| 43 |
+
Repair: fallen jars lie on the table in front of the board's free edge. Held by the knob (ball, torsional friction
|
| 44 |
+
0.0005, condim 4) a lying jar turns between the fingers and hangs straight down (like lh_bystander's bottle cap); the
|
| 45 |
+
instruction says so. Put back near the wall, the board stays level.
|
| 46 |
+
|
| 47 |
+
Success (final-state judge after a settle of at least 15 s of simulated time with the arm holding still -- longer if
|
| 48 |
+
the board is still moving -- so that finishing right after the last placement does not beat the bracket): every jar
|
| 49 |
+
stands upright on the board (its bottom on the board's top, within its outline, axis within 10 deg of the board's
|
| 50 |
+
normal), not held; the board within 15 deg of level (a board that has folded down holds no standing jar anyway),
|
| 51 |
+
touched by nothing but the jars (closes "prop the board" loopholes), the gripper not touching a jar or the board, the
|
| 52 |
+
scene static.
|
| 53 |
+
|
| 54 |
+
Per-step monitor (server log only; F1 gives the agent success / failure): stage achieved / lost (cause: slid_off,
|
| 55 |
+
robot, jar:<colour>, picked_up, other) / restored per jar; board sag_start (> 1.5 deg), sag (> 8 deg = trap_fired) and
|
| 56 |
+
sag_end, each with the time since the placement that pushed the moment over the preload and the moment itself;
|
| 57 |
+
jar_fell (with the time since its own placement and since the sag started). outcome() also reports what the agent's
|
| 58 |
+
last images showed at `finish` (board angle, jars already off the board).
|
| 59 |
+
|
| 60 |
+
Protocol: cross (reset to the same instance before every attempt), k = 3.
|
| 61 |
+
"""
|
| 62 |
+
import numpy as np
|
| 63 |
+
|
| 64 |
+
from .. import envs
|
| 65 |
+
from ..bddl import write_bddl
|
| 66 |
+
from ..objects import _fmt, _wrap, register_generated
|
| 67 |
+
from ..skills import Skills
|
| 68 |
+
from ..task_base import LFFTask, register_task
|
| 69 |
+
|
| 70 |
+
TZ = envs.TABLE_Z
|
| 71 |
+
G = 9.81
|
| 72 |
+
DT = 0.05 # control period
|
| 73 |
+
|
| 74 |
+
# ---------------------------------------------------------------- jars (square glass jars with a ball knob on the lid)
|
| 75 |
+
COLOURS = ["red", "green", "blue", "yellow"]
|
| 76 |
+
JARS = [f"jar_{c}_1" for c in COLOURS]
|
| 77 |
+
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),
|
| 78 |
+
"yellow": (0.90, 0.72, 0.15, 1.0)}
|
| 79 |
+
LID_RGBA = (0.93, 0.93, 0.91, 1.0)
|
| 80 |
+
KNOB_RGBA = (0.22, 0.22, 0.24, 1.0)
|
| 81 |
+
JB = 0.025 # half width of the square body (5 x 5 cm)
|
| 82 |
+
BODY_H = 0.060
|
| 83 |
+
LID_H, LID_B = 0.008, 0.026 # lid height, half width
|
| 84 |
+
NECK_R, NECK_H = 0.006, 0.012
|
| 85 |
+
KNOB_R = 0.011
|
| 86 |
+
JAR_H = BODY_H + LID_H + NECK_H + 2 * KNOB_R # 0.102
|
| 87 |
+
KNOB_Z = BODY_H + LID_H + NECK_H + KNOB_R # knob centre above the jar's bottom (0.091)
|
| 88 |
+
JAR_COM = 0.026 # centre of mass above the bottom (a filled jar)
|
| 89 |
+
JAR_MASS = (0.24, 0.26)
|
| 90 |
+
JAR_MU = (0.27, 0.33) # jar body friction (per jar); the board's own is lower, so this one applies on the board
|
| 91 |
+
LID_MU = 0.8
|
| 92 |
+
KNOB_MU_T = 0.0005 # torsional friction of the knob (condim 4): a jar held by its knob swings down and hangs straight
|
| 93 |
+
JAR_ROT_DAMP = 0.004 # free-joint angular damping (air drag; damps the swing of a jar hanging from its knob)
|
| 94 |
+
|
| 95 |
+
# ---------------------------------------------------------------- shelf (fixture: wall panel + hinged board)
|
| 96 |
+
SHELF = "shelf_1"
|
| 97 |
+
SHELF_MODEL = "lff_lhs_shelf"
|
| 98 |
+
BOARD_L = 0.34 # along the wall (world x)
|
| 99 |
+
BOARD_D = 0.20 # depth, from the wall to the free edge
|
| 100 |
+
BOARD_T = 0.012
|
| 101 |
+
BOARD_TOP = 0.110 # top surface above the table when level
|
| 102 |
+
PANEL_T = 0.025
|
| 103 |
+
LIP = 0.045 # the wall rises this far above the board's top
|
| 104 |
+
BOARD_MASS = 0.30
|
| 105 |
+
BOARD_MU = 0.10 # (max rule: the jars' 0.27-0.33 applies)
|
| 106 |
+
GAP = 0.004 # board edge to the wall face (the board's lower corner swings towards the wall when it droops)
|
| 107 |
+
WOOD = (0.72, 0.55, 0.36, 1.0)
|
| 108 |
+
WALL_RGBA = (0.86, 0.86, 0.84, 1.0)
|
| 109 |
+
DROOP_MAX = np.radians(25.0) # hard stop of the hinge (at 28 deg the free edge would touch the table)
|
| 110 |
+
K_SPRING = 0.25 # N m / rad: the bracket's spring beyond the preload (soft: once the catch slips the board folds down)
|
| 111 |
+
LATCH = 0.12 # N m: part of the preload held by the bracket's catch, released over the first LATCH_TH of droop
|
| 112 |
+
LATCH_TH = np.radians(3.0)
|
| 113 |
+
PRELOAD_LOOSE = (0.62, 0.68) # N m (spring + catch at level)
|
| 114 |
+
PRELOAD_STIFF = 2.5
|
| 115 |
+
DAMPING = (0.45, 0.60) # N m s / rad
|
| 116 |
+
P_LOOSE = 0.70 # 14 of every 20 consecutive seeds
|
| 117 |
+
WALL_Y = (0.25, 0.27) # |y| of the wall face
|
| 118 |
+
SHELF_X = (-0.17, -0.12) # centre of the board along the wall
|
| 119 |
+
SLOT_U = (-0.12, -0.04, 0.04, 0.12) # slot positions along the board (scripted policies)
|
| 120 |
+
SUP_Y = (0.13, 0.17) # |y| of the supply row (other side of the table)
|
| 121 |
+
SUP_U = (-0.135, -0.045, 0.045, 0.135)
|
| 122 |
+
|
| 123 |
+
# predicates / monitor
|
| 124 |
+
TILT_OK = np.radians(10.0) # jar axis vs the board's normal
|
| 125 |
+
BOARD_OK = np.radians(15.0) # final judge: the board within 15 deg of level (jars slide off at ~13-16 deg)
|
| 126 |
+
SAG0 = np.radians(1.5) # sag_start
|
| 127 |
+
SAG_END = np.radians(0.5)
|
| 128 |
+
SAG_DEG = np.radians(8.0) # trap fired
|
| 129 |
+
DEBOUNCE = 10 # control steps (0.5 s)
|
| 130 |
+
SETTLE_MIN, SETTLE_MAX = 300, 600 # final judge: 15-30 s of simulated time with the arm holding still
|
| 131 |
+
|
| 132 |
+
# scripted motion
|
| 133 |
+
Z_CARRY = 0.25 # grasp point above the table while carrying a jar (its bottom then clears the board by ~5 cm)
|
| 134 |
+
R_MID = GAP + BOARD_D / 2 # 0.104: the middle of the board's depth (from the wall face)
|
| 135 |
+
R_BACK = JB + 0.010 # 0.035: a jar against the wall (1 cm gap)
|
| 136 |
+
NAIVE_BIAS = 0.010 # per instance: Sonnet aims at the middle +- 1 cm (towards the wall or the free edge)
|
| 137 |
+
NAIVE_RAND = 0.006 # per jar
|
| 138 |
+
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
|
| 139 |
+
# (Sonnet, lh_nudge_row pilot np2: 3.2-8.3 s, median 5.1 s)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def jar_xml(name, rgba):
|
| 143 |
+
h = JAR_H / 2
|
| 144 |
+
z0 = -h # bottom
|
| 145 |
+
m = 0.25
|
| 146 |
+
parts = [("body", "box", (0, 0, z0 + BODY_H / 2), (JB, JB, BODY_H / 2), rgba, 'friction="0.3 0.005 0.0001"'),
|
| 147 |
+
("lid", "box", (0, 0, z0 + BODY_H + LID_H / 2), (LID_B, LID_B, LID_H / 2), LID_RGBA,
|
| 148 |
+
f'friction="{LID_MU} 0.005 0.0001"'),
|
| 149 |
+
("neck", "cylinder", (0, 0, z0 + BODY_H + LID_H + NECK_H / 2), (NECK_R, NECK_H / 2), KNOB_RGBA,
|
| 150 |
+
f'friction="{LID_MU} 0.005 0.0001"'),
|
| 151 |
+
("knob", "sphere", (0, 0, z0 + KNOB_Z), (KNOB_R,), KNOB_RGBA,
|
| 152 |
+
f'friction="1 {KNOB_MU_T} 0.0001" condim="4" priority="2"')]
|
| 153 |
+
ixx = m * ((2 * JB) ** 2 + BODY_H ** 2) / 12
|
| 154 |
+
izz = m * (2 * (2 * JB) ** 2) / 12
|
| 155 |
+
s = [f' <inertial pos="0 0 {z0 + JAR_COM:.4f}" mass="{m}" diaginertia="{ixx:.3e} {ixx:.3e} {izz:.3e}" />']
|
| 156 |
+
for nm, typ, pos, size, c, extra in parts:
|
| 157 |
+
s.append(f' <geom name="{name}_{nm}" type="{typ}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(c)}" '
|
| 158 |
+
f'{extra} group="0" />')
|
| 159 |
+
s.append(f' <geom type="{typ}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(c)}" contype="0" '
|
| 160 |
+
f'conaffinity="0" group="1" />')
|
| 161 |
+
# a lighter label band on the body (visual only)
|
| 162 |
+
s.append(f' <geom type="box" pos="0 0 {z0 + BODY_H * 0.55:.4f}" size="{JB + 0.0006:.4f} {JB + 0.0006:.4f} 0.012" '
|
| 163 |
+
f'rgba="0.95 0.93 0.86 1" contype="0" conaffinity="0" group="1" />')
|
| 164 |
+
return _wrap(name, "\n".join(s), h, JB * 1.42)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def shelf_xml(name):
|
| 168 |
+
"""fixture frame: origin on the table top below the middle of the hinge line; local +y points from the wall towards
|
| 169 |
+
the board's free edge, local x along the wall. Wall panel (static) + board (child body on a hinge about -x at the
|
| 170 |
+
wall face, so a positive joint angle lowers the free edge). Wall and board do not collide with each other
|
| 171 |
+
(contype 2 / conaffinity 1); both collide with everything else."""
|
| 172 |
+
zc = BOARD_TOP - BOARD_T / 2 # hinge axis height (board mid-thickness)
|
| 173 |
+
wall_h = BOARD_TOP + LIP
|
| 174 |
+
hw = (BOARD_L + 0.04) / 2
|
| 175 |
+
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}" '
|
| 176 |
+
f'rgba="{_fmt(WALL_RGBA)}"')
|
| 177 |
+
g = [f'<geom name="{name}_wall" {wall} friction="0.6 0.005 0.0001" contype="2" conaffinity="1" group="0" />',
|
| 178 |
+
f'<geom {wall} contype="0" conaffinity="0" group="1" />']
|
| 179 |
+
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}" '
|
| 180 |
+
f'rgba="{_fmt(WOOD)}"')
|
| 181 |
+
b = [f'<inertial pos="0 {BOARD_D / 2 + GAP:.5f} 0" mass="{BOARD_MASS}" '
|
| 182 |
+
f'diaginertia="{BOARD_MASS * BOARD_D ** 2 / 12:.3e} {BOARD_MASS * BOARD_L ** 2 / 12:.3e} '
|
| 183 |
+
f'{BOARD_MASS * (BOARD_L ** 2 + BOARD_D ** 2) / 12:.3e}" />',
|
| 184 |
+
# stiffness / springref / damping are set per instance (apply_instance)
|
| 185 |
+
f'<joint name="hinge" type="hinge" axis="-1 0 0" pos="0 0 0" limited="true" range="0 {DROOP_MAX:.4f}" '
|
| 186 |
+
f'stiffness="{K_SPRING}" springref="-1" damping="3.0" armature="0.002" solreflimit="0.004 1" '
|
| 187 |
+
f'solimplimit="0.95 0.99 0.001" />',
|
| 188 |
+
f'<geom name="{name}_board" {slab} friction="{BOARD_MU} 0.005 0.0001" contype="2" conaffinity="1" '
|
| 189 |
+
f'group="0" />',
|
| 190 |
+
f'<geom {slab} contype="0" conaffinity="0" group="1" />',
|
| 191 |
+
# darker front edge strip and hinge barrel (visual)
|
| 192 |
+
f'<geom type="box" pos="0 {BOARD_D + GAP - 0.003:.5f} 0" size="{BOARD_L / 2 + 0.0005:.5f} 0.0032 '
|
| 193 |
+
f'{BOARD_T / 2 + 0.0005:.5f}" rgba="0.50 0.36 0.22 1" contype="0" conaffinity="0" group="1" />',
|
| 194 |
+
f'<geom type="cylinder" pos="0 0.004 {-BOARD_T / 2:.5f}" size="0.005 {BOARD_L / 2 - 0.01:.5f}" '
|
| 195 |
+
f'quat="0.70711 0 0.70711 0" rgba="0.55 0.55 0.58 1" contype="0" conaffinity="0" group="1" />']
|
| 196 |
+
nl = "\n "
|
| 197 |
+
return f"""<mujoco model="{name}">
|
| 198 |
+
<worldbody>
|
| 199 |
+
<body>
|
| 200 |
+
<body name="object">
|
| 201 |
+
{nl.join(g)}
|
| 202 |
+
<body name="board" pos="0 0 {zc:.5f}">
|
| 203 |
+
{nl.join(b)}
|
| 204 |
+
</body>
|
| 205 |
+
</body>
|
| 206 |
+
<site rgba="0 0 0 0" size="0.005" pos="0 0 0" name="bottom_site" />
|
| 207 |
+
<site rgba="0 0 0 0" size="0.005" pos="0 0 {wall_h:.5f}" name="top_site" />
|
| 208 |
+
<site rgba="0 0 0 0" size="0.005" pos="{hw:.5f} {BOARD_D:.5f} 0" name="horizontal_radius_site" />
|
| 209 |
+
</body>
|
| 210 |
+
</worldbody>
|
| 211 |
+
</mujoco>
|
| 212 |
+
"""
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def _wrap_h(a):
|
| 216 |
+
"""wrap to [-pi/2, pi/2) (the gripper is symmetric under 180 deg)"""
|
| 217 |
+
return float((a + np.pi / 2) % np.pi - np.pi / 2)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class DroopSkills(Skills):
|
| 221 |
+
"""Skills that feed the task's per-step monitor."""
|
| 222 |
+
|
| 223 |
+
def __init__(self, env, task, recorder=None):
|
| 224 |
+
super().__init__(env, recorder=recorder)
|
| 225 |
+
self.task = task
|
| 226 |
+
|
| 227 |
+
def _act(self, dpos, drot, grip):
|
| 228 |
+
super()._act(dpos, drot, grip)
|
| 229 |
+
self.task.monitor_step()
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
@register_task
|
| 233 |
+
class ShelfDroop(LFFTask):
|
| 234 |
+
name = "lh_shelf_droop"
|
| 235 |
+
level = "L2"
|
| 236 |
+
category = "state_restoration"
|
| 237 |
+
capabilities = ("Perceive", "Reason", "Restore", "Plan")
|
| 238 |
+
protocol = "cross"
|
| 239 |
+
max_attempts = 3
|
| 240 |
+
# careful: ~10 commands per jar (40) + standing up and re-placing three fallen jars (~40) + looking / corrections
|
| 241 |
+
agent_max_steps = 120
|
| 242 |
+
instruction = ("Put the four jars (red, green, blue, yellow) on the shelf. At the end all four must be standing "
|
| 243 |
+
"upright on the shelf board, and the gripper must be open and clear of the jars and the shelf. "
|
| 244 |
+
"(Each jar has a round knob on its lid; held by the knob, a jar hangs straight down.)")
|
| 245 |
+
instruction_indirect = ("Put the four little square jars with knobbed lids up on the wooden shelf by the wall. "
|
| 246 |
+
"When you are done, all of them have to stand upright on the shelf board, and the gripper "
|
| 247 |
+
"must be open and away from the jars and the shelf. (Held by its round knob, a jar hangs "
|
| 248 |
+
"straight down.)")
|
| 249 |
+
agent_object_names = ["jars (red, green, blue, yellow; each with a round knob on its lid -- held by the knob it "
|
| 250 |
+
"hangs straight down)", "wooden shelf board on the wall panel"]
|
| 251 |
+
|
| 252 |
+
# ------------------------------------------------------------ scene
|
| 253 |
+
def make_bddl(self):
|
| 254 |
+
objs = []
|
| 255 |
+
for i, (c, j) in enumerate(zip(COLOURS, JARS)):
|
| 256 |
+
cat = register_generated(f"LffLhsJar{c.capitalize()}", jar_xml(f"lff_lhs_jar_{c}", GLASS_RGBA[c]))
|
| 257 |
+
objs.append((j, cat, f"jar{i}_region", (-0.30 + 0.12 * i, 0.30, -0.29 + 0.12 * i, 0.31)))
|
| 258 |
+
sh = register_generated("LffLhsShelf", shelf_xml(SHELF_MODEL), free=False)
|
| 259 |
+
fx = [(SHELF, sh, "shelf_region", (0.20, -0.31, 0.21, -0.30))] # moved in apply_instance
|
| 260 |
+
return write_bddl(self.name, "Put the four jars on the shelf", objs, fx)
|
| 261 |
+
|
| 262 |
+
def __init__(self, cam_res=None):
|
| 263 |
+
super().__init__(cam_res)
|
| 264 |
+
m = self.env.sim.model
|
| 265 |
+
self.shelf_bid = m.body_name2id(self.env.fixtures_dict[SHELF].root_body)
|
| 266 |
+
self.jid = m.joint_name2id(f"{SHELF}_hinge")
|
| 267 |
+
self.qa, self.da = int(m.jnt_qposadr[self.jid]), int(m.jnt_dofadr[self.jid])
|
| 268 |
+
self.board_bid = int(m.jnt_bodyid[self.jid])
|
| 269 |
+
pre = f"{SHELF}_{SHELF_MODEL}"
|
| 270 |
+
self.board_gid = m.geom_name2id(pre + "_board")
|
| 271 |
+
self.wall_gid = m.geom_name2id(pre + "_wall")
|
| 272 |
+
self.jgeoms = {j: envs.obj_geom_ids(self.env, j) for j in JARS}
|
| 273 |
+
self.jbid = {j: int(m.geom_bodyid[self.jgeoms[j][0]]) for j in JARS} # body that carries the inertial
|
| 274 |
+
self.body_gid = {j: m.geom_name2id(f"{j}_lff_lhs_jar_{c}_body") for c, j in zip(COLOURS, JARS)}
|
| 275 |
+
self.knob_gid = {j: m.geom_name2id(f"{j}_lff_lhs_jar_{c}_knob") for c, j in zip(COLOURS, JARS)}
|
| 276 |
+
self.jdof = {j: envs.free_joint_addr(self.env, j)[1] for j in JARS}
|
| 277 |
+
# per-geom lookup tables for the substep contact check
|
| 278 |
+
self.owner = np.full(m.ngeom, -1, int) # jar index
|
| 279 |
+
for i, j in enumerate(JARS):
|
| 280 |
+
self.owner[self.jgeoms[j]] = i
|
| 281 |
+
self.is_robot = np.zeros(m.ngeom, bool)
|
| 282 |
+
self.is_robot[envs.robot_geom_ids(self.env)] = True
|
| 283 |
+
self.is_board = np.zeros(m.ngeom, bool)
|
| 284 |
+
self.is_board[self.board_gid] = True
|
| 285 |
+
self._sub_rob, self._sub_obj, self._sub_board = {}, {}, set()
|
| 286 |
+
sim = self.env.sim
|
| 287 |
+
if not getattr(sim, "_lhs_wrapped", False):
|
| 288 |
+
orig = sim.step
|
| 289 |
+
|
| 290 |
+
def step(*a, **k):
|
| 291 |
+
orig(*a, **k)
|
| 292 |
+
t = getattr(sim, "_lhs_task", None)
|
| 293 |
+
if t is not None:
|
| 294 |
+
t._bracket()
|
| 295 |
+
if t.mon is not None:
|
| 296 |
+
t._substep()
|
| 297 |
+
sim.step = step
|
| 298 |
+
sim._lhs_wrapped = True
|
| 299 |
+
sim._lhs_task = self
|
| 300 |
+
self.inst = None
|
| 301 |
+
self.mon = None
|
| 302 |
+
self.sk = None
|
| 303 |
+
|
| 304 |
+
def _bracket(self):
|
| 305 |
+
"""the bracket's catch (every MuJoCo substep): a torque holding the board up that fades out over the first
|
| 306 |
+
LATCH_TH of droop, so a board that starts to droop does not stop part-way but folds down to its stop"""
|
| 307 |
+
d = self.env.sim.data
|
| 308 |
+
th = float(d.qpos[self.qa])
|
| 309 |
+
d.qfrc_applied[self.da] = -LATCH * float(np.clip(1.0 - th / LATCH_TH, 0.0, 1.0))
|
| 310 |
+
|
| 311 |
+
def _substep(self):
|
| 312 |
+
d = self.env.sim.data
|
| 313 |
+
n = d.ncon
|
| 314 |
+
if not n:
|
| 315 |
+
return
|
| 316 |
+
g1 = np.asarray(d.contact.geom1)[:n]
|
| 317 |
+
g2 = np.asarray(d.contact.geom2)[:n]
|
| 318 |
+
for a, b in zip(g1, g2):
|
| 319 |
+
pa, pb = self.owner[a], self.owner[b]
|
| 320 |
+
if self.is_board[a] or self.is_board[b]:
|
| 321 |
+
o = b if self.is_board[a] else a
|
| 322 |
+
if self.owner[o] < 0: # the board touched by something that is not a jar (robot, table, ...)
|
| 323 |
+
self._sub_board.add("robot" if self.is_robot[o] else (self.env.sim.model.geom_id2name(int(o)) or "?"))
|
| 324 |
+
continue
|
| 325 |
+
if pa < 0 and pb < 0:
|
| 326 |
+
continue
|
| 327 |
+
if pa >= 0 and pb >= 0:
|
| 328 |
+
if pa != pb:
|
| 329 |
+
self._sub_obj[int(pa)] = int(pb)
|
| 330 |
+
self._sub_obj[int(pb)] = int(pa)
|
| 331 |
+
continue
|
| 332 |
+
p, o = (pa, b) if pa >= 0 else (pb, a)
|
| 333 |
+
if self.is_robot[o]:
|
| 334 |
+
self._sub_rob[int(p)] = True
|
| 335 |
+
|
| 336 |
+
# ------------------------------------------------------------ instances
|
| 337 |
+
def sample_instance(self, seed):
|
| 338 |
+
rng = np.random.default_rng(seed)
|
| 339 |
+
loose = bool((int(seed) * 7) % 20 < round(20 * P_LOOSE)) # balanced: 14 of every 20 consecutive seeds
|
| 340 |
+
side = "right" if rng.random() < 0.5 else "left" # where the wall stands (robot's view)
|
| 341 |
+
s = -1.0 if side == "right" else 1.0
|
| 342 |
+
x0 = float(rng.uniform(*SHELF_X))
|
| 343 |
+
yw = float(rng.uniform(*WALL_Y))
|
| 344 |
+
preload = float(rng.uniform(*PRELOAD_LOOSE)) if loose else PRELOAD_STIFF
|
| 345 |
+
damping = float(rng.uniform(*DAMPING))
|
| 346 |
+
ys = -s * float(rng.uniform(*SUP_Y))
|
| 347 |
+
order = rng.permutation(4)
|
| 348 |
+
start = {COLOURS[i]: [float(x0 + SUP_U[order[i]] + rng.uniform(-0.01, 0.01)), float(ys + rng.uniform(-0.008, 0.008))]
|
| 349 |
+
for i in range(4)}
|
| 350 |
+
yaw0 = {c: float(rng.uniform(-0.3, 0.3)) for c in COLOURS}
|
| 351 |
+
mu = {c: float(rng.uniform(*JAR_MU)) for c in COLOURS}
|
| 352 |
+
mass = {c: float(rng.uniform(*JAR_MASS)) for c in COLOURS}
|
| 353 |
+
return dict(seed=int(seed), loose=loose, bracket="loose" if loose else "stiff", side=side, shelf_x=x0,
|
| 354 |
+
wall_y=float(s * yw), preload=preload, damping=damping, stiffness=K_SPRING, start=start, yaw0=yaw0,
|
| 355 |
+
mu=mu, mass=mass, naive_bias=float(rng.uniform(-NAIVE_BIAS, NAIVE_BIAS)))
|
| 356 |
+
|
| 357 |
+
def apply_instance(self, inst):
|
| 358 |
+
self.inst = inst
|
| 359 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 360 |
+
s = -1.0 if inst["side"] == "right" else 1.0
|
| 361 |
+
# fixture local +y (towards the free edge) = world -s*y
|
| 362 |
+
m.body_pos[self.shelf_bid] = [inst["shelf_x"], inst["wall_y"], TZ]
|
| 363 |
+
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]
|
| 364 |
+
wb = BOARD_MASS * G * (BOARD_D / 2 + GAP) # the board's own weight about the hinge
|
| 365 |
+
m.jnt_stiffness[self.jid] = inst["stiffness"]
|
| 366 |
+
# spring + catch hold the board level up to a load moment of `preload` (the catch's part fades with the droop)
|
| 367 |
+
m.qpos_spring[self.qa] = -(inst["preload"] - LATCH + wb) / inst["stiffness"]
|
| 368 |
+
m.dof_damping[self.da] = inst["damping"]
|
| 369 |
+
d.qpos[self.qa] = 0.0
|
| 370 |
+
d.qvel[self.da] = 0.0
|
| 371 |
+
d.qfrc_applied[self.da] = -LATCH
|
| 372 |
+
for c, j in zip(COLOURS, JARS):
|
| 373 |
+
b = self.jbid[j]
|
| 374 |
+
M = inst["mass"][c]
|
| 375 |
+
m.body_mass[b] = M
|
| 376 |
+
m.body_inertia[b] = [M * ((2 * JB) ** 2 + BODY_H ** 2) / 12] * 2 + [M * (2 * JB) ** 2 / 6]
|
| 377 |
+
m.geom_friction[self.body_gid[j]] = [inst["mu"][c], 0.005, 0.0001]
|
| 378 |
+
m.dof_damping[self.jdof[j] + 3:self.jdof[j] + 6] = JAR_ROT_DAMP
|
| 379 |
+
self.env.sim.forward()
|
| 380 |
+
for c, j in zip(COLOURS, JARS):
|
| 381 |
+
envs.place_upright(self.env, j, inst["start"][c], yaw=inst["yaw0"][c], clearance=0.0005)
|
| 382 |
+
|
| 383 |
+
def reset_instance(self, inst, recorder=None):
|
| 384 |
+
self.mon = None
|
| 385 |
+
self.env.reset()
|
| 386 |
+
self.apply_instance(inst)
|
| 387 |
+
self.env.sim.forward()
|
| 388 |
+
envs.settle(self.env, 15)
|
| 389 |
+
self.sk = DroopSkills(self.env, self, recorder=recorder)
|
| 390 |
+
self._sub_rob, self._sub_obj, self._sub_board = {}, {}, set()
|
| 391 |
+
n = len(JARS)
|
| 392 |
+
self.mon = dict(state=[False] * n, raw_since=[0] * n, ever=[False] * n, lost=[False] * n, lost_cause=[None] * n,
|
| 393 |
+
events=[], last_robot=[None] * n, last_obj=[None] * n, placed_step=[None] * n,
|
| 394 |
+
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,
|
| 395 |
+
fell_in_sag=[], max_deg=0.0, board_touch=[], n_steps=0, finish_step=None)
|
| 396 |
+
return self.sk
|
| 397 |
+
|
| 398 |
+
# ------------------------------------------------------------ geometry / predicates
|
| 399 |
+
def angle(self):
|
| 400 |
+
return float(self.env.sim.data.qpos[self.qa])
|
| 401 |
+
|
| 402 |
+
def board_frame(self):
|
| 403 |
+
d = self.env.sim.data
|
| 404 |
+
return d.xpos[self.board_bid].copy(), d.xmat[self.board_bid].reshape(3, 3).copy()
|
| 405 |
+
|
| 406 |
+
def to_board(self, p):
|
| 407 |
+
o, R = self.board_frame()
|
| 408 |
+
return R.T @ (np.asarray(p, float) - o)
|
| 409 |
+
|
| 410 |
+
def board_point(self, u, r, h=BOARD_T / 2):
|
| 411 |
+
"""world point at (u along the wall, r from the hinge across the board, h above the hinge axis) in the board
|
| 412 |
+
frame"""
|
| 413 |
+
o, R = self.board_frame()
|
| 414 |
+
return o + R @ np.array([u, r, h])
|
| 415 |
+
|
| 416 |
+
def level_point(self, u, r):
|
| 417 |
+
"""world xy of board coordinates (u, r) with the board level (planning)"""
|
| 418 |
+
s = -1.0 if self.inst["side"] == "right" else 1.0
|
| 419 |
+
return np.array([self.inst["shelf_x"] - s * u, self.inst["wall_y"] - s * r])
|
| 420 |
+
|
| 421 |
+
def board_top_z(self):
|
| 422 |
+
return TZ + BOARD_TOP
|
| 423 |
+
|
| 424 |
+
def jar_axis(self, j):
|
| 425 |
+
return self.env.sim.data.xmat[self.jbid[j]].reshape(3, 3)[:, 2].copy()
|
| 426 |
+
|
| 427 |
+
def jar_bottom(self, j):
|
| 428 |
+
return envs.obj_pos(self.env, j) - self.jar_axis(j) * JAR_H / 2
|
| 429 |
+
|
| 430 |
+
def knob_xyz(self, j):
|
| 431 |
+
return self.env.sim.data.geom_xpos[self.knob_gid[j]].copy()
|
| 432 |
+
|
| 433 |
+
def tilt(self, j):
|
| 434 |
+
return float(np.arccos(np.clip(self.jar_axis(j)[2], -1.0, 1.0)))
|
| 435 |
+
|
| 436 |
+
def held(self, j):
|
| 437 |
+
return self.sk is not None and self.sk.holding(j)
|
| 438 |
+
|
| 439 |
+
def on_board(self, i, extra=0.0):
|
| 440 |
+
"""jar i stands on the shelf board: its bottom (centre) on the board's top, within the board's outline, its
|
| 441 |
+
axis within 10 deg of the board's normal, not held"""
|
| 442 |
+
j = JARS[i]
|
| 443 |
+
o, R = self.board_frame()
|
| 444 |
+
ax = R.T @ self.jar_axis(j)
|
| 445 |
+
if ax[2] < np.cos(TILT_OK + extra * 5):
|
| 446 |
+
return False
|
| 447 |
+
bc = R.T @ (self.jar_bottom(j) - o)
|
| 448 |
+
if not (BOARD_T / 2 - 0.004 <= bc[2] <= BOARD_T / 2 + 0.005 + extra):
|
| 449 |
+
return False
|
| 450 |
+
if abs(bc[0]) > BOARD_L / 2 + extra or not (GAP - extra <= bc[1] <= GAP + BOARD_D + extra):
|
| 451 |
+
return False
|
| 452 |
+
return not self.held(j)
|
| 453 |
+
|
| 454 |
+
def stages(self):
|
| 455 |
+
return [self.on_board(i) for i in range(len(JARS))]
|
| 456 |
+
|
| 457 |
+
def lever(self, j):
|
| 458 |
+
"""horizontal distance (m) of the jar's centre of mass from the hinge line, towards the free edge"""
|
| 459 |
+
o, R = self.board_frame()
|
| 460 |
+
n = R[:, 1].copy()
|
| 461 |
+
n[2] = 0.0
|
| 462 |
+
n /= max(np.linalg.norm(n), 1e-9)
|
| 463 |
+
return float((self.env.sim.data.xipos[self.jbid[j]] - o) @ n)
|
| 464 |
+
|
| 465 |
+
def moment(self, only_state=True):
|
| 466 |
+
"""load moment (N m) of the jars standing on the board about the hinge"""
|
| 467 |
+
mon = self.mon
|
| 468 |
+
tot = 0.0
|
| 469 |
+
for i, j in enumerate(JARS):
|
| 470 |
+
on = mon["state"][i] if (only_state and mon is not None) else self.on_board(i)
|
| 471 |
+
if on:
|
| 472 |
+
tot += self.inst["mass"][COLOURS[i]] * G * self.lever(j)
|
| 473 |
+
return float(tot)
|
| 474 |
+
|
| 475 |
+
def r_cm(self, i):
|
| 476 |
+
"""distance of jar i's bottom centre from the wall face (cm), in the board frame"""
|
| 477 |
+
return 100 * float(self.to_board(self.jar_bottom(JARS[i]))[1])
|
| 478 |
+
|
| 479 |
+
# ------------------------------------------------------------ monitor
|
| 480 |
+
def _t(self):
|
| 481 |
+
return int(self.sk.n_steps) if self.sk is not None else 0
|
| 482 |
+
|
| 483 |
+
def monitor_step(self):
|
| 484 |
+
mon = self.mon
|
| 485 |
+
if mon is None or self.sk is None:
|
| 486 |
+
return
|
| 487 |
+
mon["n_steps"] += 1
|
| 488 |
+
t = self._t()
|
| 489 |
+
rob, obj, brd = dict(self._sub_rob), dict(self._sub_obj), set(self._sub_board)
|
| 490 |
+
self._sub_rob, self._sub_obj, self._sub_board = {}, {}, set()
|
| 491 |
+
for i in rob:
|
| 492 |
+
if not self.held(JARS[i]):
|
| 493 |
+
mon["last_robot"][i] = int(t)
|
| 494 |
+
for i, k in obj.items():
|
| 495 |
+
mon["last_obj"][i] = [COLOURS[k], int(t)]
|
| 496 |
+
for b in brd:
|
| 497 |
+
if b not in mon["board_touch"]:
|
| 498 |
+
mon["board_touch"].append(b)
|
| 499 |
+
mon["_board_touch_now"] = sorted(brd)
|
| 500 |
+
th = self.angle()
|
| 501 |
+
mon["max_deg"] = max(mon["max_deg"], float(np.degrees(th)))
|
| 502 |
+
if th > np.radians(5.0):
|
| 503 |
+
mon["droop_t"] = int(t) # last step with the board drooped > 5 deg (it springs back once the jars are off)
|
| 504 |
+
self._sag(th, t)
|
| 505 |
+
if mon["n_steps"] % 2:
|
| 506 |
+
return
|
| 507 |
+
for i in range(len(JARS)):
|
| 508 |
+
raw = self.on_board(i, 0.002 if mon["state"][i] else 0.0)
|
| 509 |
+
if raw and not mon["raw_prev"][i]:
|
| 510 |
+
mon["raw_on"][i] = int(t) # set down on the board (raw; the stage event below is debounced)
|
| 511 |
+
mon["raw_prev"][i] = raw
|
| 512 |
+
if raw == mon["state"][i]:
|
| 513 |
+
mon["raw_since"][i] = 0
|
| 514 |
+
continue
|
| 515 |
+
mon["raw_since"][i] += 2
|
| 516 |
+
if mon["raw_since"][i] < DEBOUNCE:
|
| 517 |
+
continue
|
| 518 |
+
mon["state"][i] = raw
|
| 519 |
+
mon["raw_since"][i] = 0
|
| 520 |
+
t0 = int(t - DEBOUNCE + 1)
|
| 521 |
+
c = COLOURS[i]
|
| 522 |
+
if raw:
|
| 523 |
+
restored = mon["lost"][i]
|
| 524 |
+
e = dict(stage=c, event="restored" if restored else "achieved", step=t0,
|
| 525 |
+
r_cm=round(self.r_cm(i), 1), moment_Nm=round(self.moment(), 3))
|
| 526 |
+
if restored:
|
| 527 |
+
e["after"] = mon["lost_cause"][i]
|
| 528 |
+
mon["events"].append(e)
|
| 529 |
+
mon["ever"][i] = True
|
| 530 |
+
mon["placed_step"][i] = t0
|
| 531 |
+
mon["last_place"] = (c, t0)
|
| 532 |
+
else:
|
| 533 |
+
mon["lost"][i] = True
|
| 534 |
+
cause = self._cause(i, t)
|
| 535 |
+
mon["lost_cause"][i] = cause
|
| 536 |
+
e = dict(stage=c, event="lost", step=t0, cause=cause, board_deg=round(float(np.degrees(th)), 1))
|
| 537 |
+
mon["events"].append(e)
|
| 538 |
+
if cause == "slid_off":
|
| 539 |
+
ps = mon["placed_step"][i]
|
| 540 |
+
ss = mon["sag_start"]["step"] if mon["sag_start"] else None
|
| 541 |
+
sc = mon.get("sag_cause")
|
| 542 |
+
mon["events"].append(dict(jar=c, event="jar_fell", step=t0,
|
| 543 |
+
dt_since_placed_s=None if ps is None else round((t0 - ps) * DT, 2),
|
| 544 |
+
dt_since_sag_start_s=None if ss is None else round((t0 - ss) * DT, 2),
|
| 545 |
+
after_placing=None if sc is None else sc[0],
|
| 546 |
+
dt_since_cause_s=None if sc is None else round((t0 - sc[1]) * DT, 2),
|
| 547 |
+
in_final_settle=mon["finish_step"] is not None,
|
| 548 |
+
board_deg=round(float(np.degrees(th)), 1)))
|
| 549 |
+
mon["fell_in_sag"].append(c)
|
| 550 |
+
|
| 551 |
+
def _sag(self, th, t):
|
| 552 |
+
mon = self.mon
|
| 553 |
+
if not mon["in_sag"]:
|
| 554 |
+
if th > SAG0:
|
| 555 |
+
mon["in_sag"] = True
|
| 556 |
+
mon["sag_fired"] = False
|
| 557 |
+
mon["sag_max"] = th
|
| 558 |
+
mon["fell_in_sag"] = []
|
| 559 |
+
lp = self._last_set_down(t)
|
| 560 |
+
mon["sag_cause"] = lp
|
| 561 |
+
e = dict(event="sag_start", step=int(t), board_deg=round(float(np.degrees(th)), 2),
|
| 562 |
+
moment_Nm=round(self.moment(only_state=False), 3),
|
| 563 |
+
preload_Nm=round(float(self.inst["preload"]), 3),
|
| 564 |
+
after_placing=None if lp is None else lp[0],
|
| 565 |
+
dt_since_placement_s=None if lp is None else round((t - lp[1]) * DT, 2),
|
| 566 |
+
n_on_board=int(sum(self.on_board(i) for i in range(len(JARS)))))
|
| 567 |
+
mon["sag_start"] = e
|
| 568 |
+
mon["events"].append(e)
|
| 569 |
+
return
|
| 570 |
+
mon["sag_max"] = max(mon["sag_max"], th)
|
| 571 |
+
if not mon["sag_fired"] and th > SAG_DEG:
|
| 572 |
+
mon["sag_fired"] = True
|
| 573 |
+
mon["n_sag"] += 1
|
| 574 |
+
ss = mon["sag_start"]
|
| 575 |
+
lp = self._last_set_down(t) # the placement that drove the board past 8 deg (sag_start may be earlier:
|
| 576 |
+
mon["sag_cause"] = lp # two jars in the middle already make it creep a few degrees)
|
| 577 |
+
mon["events"].append(dict(event="sag", step=int(t), board_deg=round(float(np.degrees(th)), 2),
|
| 578 |
+
moment_Nm=round(self.moment(only_state=False), 3),
|
| 579 |
+
after_placing=None if lp is None else lp[0],
|
| 580 |
+
sag_start_after=ss["after_placing"],
|
| 581 |
+
dt_since_placement_s=None if lp is None else round((t - lp[1]) * DT, 2),
|
| 582 |
+
dt_since_sag_start_s=round((t - ss["step"]) * DT, 2),
|
| 583 |
+
in_final_settle=mon["finish_step"] is not None))
|
| 584 |
+
mon["below"] = mon.get("below", 0) + 1 if th < SAG_END else 0
|
| 585 |
+
if mon["below"] >= 2 * DEBOUNCE: # back level for 1 s (the jars that slid off have been registered)
|
| 586 |
+
mon["in_sag"] = False
|
| 587 |
+
mon["below"] = 0
|
| 588 |
+
mon["events"].append(dict(event="sag_end", step=int(t), max_deg=round(float(np.degrees(mon["sag_max"])), 1),
|
| 589 |
+
fell=list(mon["fell_in_sag"]),
|
| 590 |
+
duration_s=round((t - mon["sag_start"]["step"]) * DT, 2)))
|
| 591 |
+
|
| 592 |
+
def _last_set_down(self, t):
|
| 593 |
+
"""(colour, step) of the jar most recently set down on the board (raw predicate) that still stands on it"""
|
| 594 |
+
mon = self.mon
|
| 595 |
+
cands = [(mon["raw_on"][i], COLOURS[i]) for i in range(len(JARS))
|
| 596 |
+
if mon["raw_on"][i] is not None and mon["raw_prev"][i] and mon["raw_on"][i] <= t]
|
| 597 |
+
if not cands:
|
| 598 |
+
return None
|
| 599 |
+
st, c = max(cands)
|
| 600 |
+
return (c, st)
|
| 601 |
+
|
| 602 |
+
def _cause(self, i, t, window=60):
|
| 603 |
+
mon = self.mon
|
| 604 |
+
if self.held(JARS[i]):
|
| 605 |
+
return "picked_up"
|
| 606 |
+
if (mon["in_sag"] and mon["sag_max"] > np.radians(5.0)) or (mon.get("droop_t") is not None
|
| 607 |
+
and t - mon["droop_t"] <= window):
|
| 608 |
+
return "slid_off"
|
| 609 |
+
lr, lo = mon["last_robot"][i], mon["last_obj"][i]
|
| 610 |
+
if lr is not None and t - lr <= window:
|
| 611 |
+
return "robot"
|
| 612 |
+
if lo is not None and t - lo[1] <= window:
|
| 613 |
+
return "jar:" + lo[0]
|
| 614 |
+
return "other"
|
| 615 |
+
|
| 616 |
+
def _finalize_monitor(self, raw):
|
| 617 |
+
mon = self.mon
|
| 618 |
+
t = self._t()
|
| 619 |
+
for i in range(len(JARS)):
|
| 620 |
+
if raw[i] == mon["state"][i]:
|
| 621 |
+
continue
|
| 622 |
+
mon["state"][i] = raw[i]
|
| 623 |
+
c = COLOURS[i]
|
| 624 |
+
if raw[i]:
|
| 625 |
+
restored = mon["lost"][i]
|
| 626 |
+
e = dict(stage=c, event="restored" if restored else "achieved", step=t, final=True)
|
| 627 |
+
if restored:
|
| 628 |
+
e["after"] = mon["lost_cause"][i]
|
| 629 |
+
mon["events"].append(e)
|
| 630 |
+
mon["ever"][i] = True
|
| 631 |
+
else:
|
| 632 |
+
mon["lost"][i] = True
|
| 633 |
+
cause = self._cause(i, t, window=10 ** 6)
|
| 634 |
+
mon["lost_cause"][i] = cause
|
| 635 |
+
mon["events"].append(dict(stage=c, event="lost", step=t, cause=cause, final=True))
|
| 636 |
+
|
| 637 |
+
# ------------------------------------------------------------ outcome
|
| 638 |
+
def _touching(self):
|
| 639 |
+
d = self.env.sim.data
|
| 640 |
+
jar_touch, board_touch = False, False
|
| 641 |
+
for k in range(d.ncon):
|
| 642 |
+
c = d.contact[k]
|
| 643 |
+
a, b = c.geom1, c.geom2
|
| 644 |
+
if (self.is_robot[a] and self.owner[b] >= 0) or (self.is_robot[b] and self.owner[a] >= 0):
|
| 645 |
+
jar_touch = True
|
| 646 |
+
if (self.is_robot[a] and self.is_board[b]) or (self.is_robot[b] and self.is_board[a]):
|
| 647 |
+
board_touch = True
|
| 648 |
+
return jar_touch, board_touch
|
| 649 |
+
|
| 650 |
+
def _moving(self):
|
| 651 |
+
d = self.env.sim.data
|
| 652 |
+
if abs(float(d.qvel[self.da])) > np.radians(0.3):
|
| 653 |
+
return True
|
| 654 |
+
for j in JARS:
|
| 655 |
+
da = self.jdof[j]
|
| 656 |
+
if np.linalg.norm(d.qvel[da:da + 3]) > 0.01 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.3:
|
| 657 |
+
return True
|
| 658 |
+
return False
|
| 659 |
+
|
| 660 |
+
def outcome(self, inst):
|
| 661 |
+
sk = self.sk
|
| 662 |
+
mon = self.mon
|
| 663 |
+
mon["finish_step"] = self._t()
|
| 664 |
+
# what the agent's last images show (finish returns no image): board angle and the jars already off the board
|
| 665 |
+
th_fin = self.angle()
|
| 666 |
+
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])]
|
| 667 |
+
max_fin = float(mon["max_deg"])
|
| 668 |
+
# settle with the arm holding still: >= 15 s of simulated time, up to 30 s while the board or a jar still moves
|
| 669 |
+
# (the droop is slow: finishing right after the last placement must not beat it)
|
| 670 |
+
n = 0
|
| 671 |
+
while n < SETTLE_MAX:
|
| 672 |
+
sk.hold(10)
|
| 673 |
+
n += 10
|
| 674 |
+
if n >= SETTLE_MIN and not self._moving() and not mon["in_sag"]:
|
| 675 |
+
break
|
| 676 |
+
settle_s = n * DT
|
| 677 |
+
p0 = {j: envs.obj_pos(self.env, j) for j in JARS}
|
| 678 |
+
th0 = self.angle()
|
| 679 |
+
jar_touch = board_touch = False
|
| 680 |
+
board_other = set()
|
| 681 |
+
for _ in range(20):
|
| 682 |
+
sk.hold(1)
|
| 683 |
+
jt, bt = self._touching()
|
| 684 |
+
jar_touch, board_touch = jar_touch or jt, board_touch or bt
|
| 685 |
+
board_other |= {b for b in mon.get("_board_touch_now", []) if b != "robot"}
|
| 686 |
+
moved = max(float(np.linalg.norm(envs.obj_pos(self.env, j) - p0[j])) for j in JARS)
|
| 687 |
+
static = moved < 0.003 and abs(self.angle() - th0) < np.radians(0.3)
|
| 688 |
+
raw = self.stages()
|
| 689 |
+
self._finalize_monitor(raw)
|
| 690 |
+
th = self.angle()
|
| 691 |
+
held = [COLOURS[i] for i, j in enumerate(JARS) if self.held(j)]
|
| 692 |
+
level = th <= BOARD_OK
|
| 693 |
+
propped = sorted(board_other)
|
| 694 |
+
success = bool(all(raw) and level and static and not held and not jar_touch and not board_touch and not propped)
|
| 695 |
+
ev = list(mon["events"])
|
| 696 |
+
n_reg = sum(e.get("event") == "lost" and e.get("cause") != "picked_up" for e in ev)
|
| 697 |
+
n_lost = sum(e.get("event") == "lost" for e in ev)
|
| 698 |
+
n_res = sum(e.get("event") == "restored" and e.get("after") != "picked_up" for e in ev)
|
| 699 |
+
fell = [e for e in ev if e.get("event") == "jar_fell"]
|
| 700 |
+
sags = [e for e in ev if e.get("event") == "sag"]
|
| 701 |
+
sag_vis = [e for e in sags if not e.get("in_final_settle")]
|
| 702 |
+
starts = [e for e in ev if e.get("event") == "sag_start"]
|
| 703 |
+
ever = mon["ever"]
|
| 704 |
+
lost_final = [i for i in range(4) if not raw[i] and ever[i]]
|
| 705 |
+
never = [i for i in range(4) if not raw[i] and not ever[i]]
|
| 706 |
+
if success:
|
| 707 |
+
failure = "none"
|
| 708 |
+
elif held:
|
| 709 |
+
failure = "held"
|
| 710 |
+
elif propped or board_touch:
|
| 711 |
+
failure = "propped"
|
| 712 |
+
elif jar_touch:
|
| 713 |
+
failure = "touching"
|
| 714 |
+
elif lost_final:
|
| 715 |
+
causes = {mon["lost_cause"][i] for i in lost_final}
|
| 716 |
+
failure = ("slid_off" if "slid_off" in causes else "knocked_off" if "robot" in causes else "regressed")
|
| 717 |
+
elif never:
|
| 718 |
+
failure = "not_on_shelf"
|
| 719 |
+
elif not level:
|
| 720 |
+
failure = "board_drooped"
|
| 721 |
+
else:
|
| 722 |
+
failure = "not_static"
|
| 723 |
+
# ---- F2 text
|
| 724 |
+
parts = []
|
| 725 |
+
if success:
|
| 726 |
+
parts.append("All four jars stand upright on the shelf board.")
|
| 727 |
+
for i in range(4):
|
| 728 |
+
if raw[i]:
|
| 729 |
+
continue
|
| 730 |
+
c, j = COLOURS[i], JARS[i]
|
| 731 |
+
if c in held:
|
| 732 |
+
parts.append(f"The {c} jar is still held by the gripper.")
|
| 733 |
+
continue
|
| 734 |
+
pb = self.to_board(self.jar_bottom(j))
|
| 735 |
+
lying = self.tilt(j) > np.radians(45)
|
| 736 |
+
if pb[2] < -0.02: # below the board: on the table
|
| 737 |
+
where = "lies on its side on the table" if lying else "stands on the table"
|
| 738 |
+
dist = 100 * float(pb[1] - (GAP + BOARD_D))
|
| 739 |
+
txt = f"The {c} jar {where}" + (f", {dist:.0f} cm out from the shelf's front edge." if dist > 0
|
| 740 |
+
else ", under the shelf.")
|
| 741 |
+
elif lying:
|
| 742 |
+
txt = f"The {c} jar lies on its side on the shelf board."
|
| 743 |
+
else:
|
| 744 |
+
txt = f"The {c} jar is not standing on the shelf board."
|
| 745 |
+
if ever[i]:
|
| 746 |
+
why = mon["lost_cause"][i]
|
| 747 |
+
txt += {"slid_off": " It had stood on the shelf; it slid off when the shelf board drooped under the load.",
|
| 748 |
+
"robot": " It had stood on the shelf; the robot knocked it off.",
|
| 749 |
+
}.get(why, " It had stood on the shelf earlier.")
|
| 750 |
+
parts.append(txt)
|
| 751 |
+
if all(raw) and not success:
|
| 752 |
+
if not level:
|
| 753 |
+
parts.append(f"The shelf board droops by {np.degrees(th):.0f} degrees.")
|
| 754 |
+
if held:
|
| 755 |
+
pass
|
| 756 |
+
elif jar_touch or board_touch:
|
| 757 |
+
parts.append("The gripper is still touching " + ("a jar." if jar_touch else "the shelf board."))
|
| 758 |
+
elif propped:
|
| 759 |
+
parts.append("The shelf board rests on something below it.")
|
| 760 |
+
elif not static:
|
| 761 |
+
parts.append("Something was still moving.")
|
| 762 |
+
if sags:
|
| 763 |
+
parts.append(f"During the attempt the shelf board drooped {len(sags)} time(s) (down to {mon['max_deg']:.0f} "
|
| 764 |
+
f"degrees) and {len(fell)} time(s) a jar slid off; {n_res} time(s) a jar was put back.")
|
| 765 |
+
trap = bool(sags)
|
| 766 |
+
lp = lambda e: e.get("dt_since_placement_s") # noqa: E731
|
| 767 |
+
return dict(success=success, stages={COLOURS[i]: bool(raw[i]) for i in range(4)}, events=ev,
|
| 768 |
+
n_regressions=int(n_reg), n_lost=int(n_lost), n_restored=int(n_res), n_fell=len(fell),
|
| 769 |
+
n_sag=len(sags), trap_fired=trap, sag_visible=bool(sag_vis),
|
| 770 |
+
recovered_in_attempt=bool(trap and success),
|
| 771 |
+
first_sag_dt_s=lp(sags[0]) if sags else None,
|
| 772 |
+
first_sag_start_dt_s=lp(starts[0]) if starts else None,
|
| 773 |
+
first_sag_after=sags[0].get("after_placing") if sags else None,
|
| 774 |
+
first_fall_dt_s=fell[0].get("dt_since_cause_s") if fell else None,
|
| 775 |
+
fell_before_finish=bool([e for e in fell if not e.get("in_final_settle")]),
|
| 776 |
+
board_deg_at_finish=round(float(np.degrees(th_fin)), 1), off_at_finish=off_fin,
|
| 777 |
+
max_droop_before_finish_deg=round(max_fin, 1),
|
| 778 |
+
visible_before_finish=bool(sag_vis or off_fin or max_fin > np.degrees(SAG_DEG)),
|
| 779 |
+
fell_jars=sorted({e["jar"] for e in fell}), failure=failure, held=held, touching=bool(jar_touch),
|
| 780 |
+
board_touched=bool(board_touch), propped=propped, static=bool(static),
|
| 781 |
+
board_deg=round(float(np.degrees(th)), 2), max_droop_deg=round(mon["max_deg"], 1),
|
| 782 |
+
r_cm={COLOURS[i]: round(self.r_cm(i), 1) for i in range(4)},
|
| 783 |
+
moment_Nm=round(self.moment(only_state=False), 3), preload_Nm=round(float(inst["preload"]), 3),
|
| 784 |
+
loose=bool(inst["loose"]), settle_s=settle_s, finish_step=mon["finish_step"],
|
| 785 |
+
detail=" ".join(parts))
|
| 786 |
+
|
| 787 |
+
# ------------------------------------------------------------ scripted primitives (move_to + gripper only)
|
| 788 |
+
def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300):
|
| 789 |
+
return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
|
| 790 |
+
|
| 791 |
+
def _lift_to(self, z, speed=0.15):
|
| 792 |
+
cur = self.sk.eef_pos()
|
| 793 |
+
if cur[2] < TZ + z - 0.005:
|
| 794 |
+
self._go([cur[0], cur[1], TZ + z], speed=speed)
|
| 795 |
+
|
| 796 |
+
def _settle_jar(self, j, max_checks=30):
|
| 797 |
+
d = self.env.sim.data
|
| 798 |
+
da = self.jdof[j]
|
| 799 |
+
for _ in range(max_checks):
|
| 800 |
+
if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2:
|
| 801 |
+
return
|
| 802 |
+
self.sk.hold(2)
|
| 803 |
+
|
| 804 |
+
def wait_board(self, max_steps=200):
|
| 805 |
+
"""wait (arm still) until the board stops moving"""
|
| 806 |
+
for _ in range(max_steps // 5):
|
| 807 |
+
if abs(float(self.env.sim.data.qvel[self.da])) < np.radians(0.3) and not self.mon["in_sag"]:
|
| 808 |
+
return
|
| 809 |
+
self.sk.hold(5)
|
| 810 |
+
|
| 811 |
+
def lying(self, j):
|
| 812 |
+
return self.tilt(j) > np.radians(45)
|
| 813 |
+
|
| 814 |
+
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):
|
| 815 |
+
"""grasp the jar by its knob and lift it to carry height. Standing jar: from above, wrist yaw `yaw`. Lying jar:
|
| 816 |
+
fingers across its axis; lifted, it turns between the fingers and hangs straight down."""
|
| 817 |
+
sk = self.sk
|
| 818 |
+
for _ in range(tries):
|
| 819 |
+
self._settle_jar(j)
|
| 820 |
+
lying = self.lying(j)
|
| 821 |
+
k = self.knob_xyz(j)
|
| 822 |
+
if lying:
|
| 823 |
+
ax = self.jar_axis(j)[:2]
|
| 824 |
+
gy = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else sk.yaw
|
| 825 |
+
else:
|
| 826 |
+
gy = yaw
|
| 827 |
+
q = k[:2] + (np.asarray(err, float) if err is not None else 0.0)
|
| 828 |
+
sk.set_gripper(False, steps=8)
|
| 829 |
+
cur = sk.eef_pos()
|
| 830 |
+
self._go([cur[0], cur[1], max(cur[2], TZ + min(z_carry, 0.22))], speed=0.15)
|
| 831 |
+
self._go([q[0], q[1], max(k[2] + 0.06, TZ + min(z_carry, 0.22))], yaw=gy, speed=v)
|
| 832 |
+
sk.hold(max(1, int(4 * waits)))
|
| 833 |
+
k = self.knob_xyz(j)
|
| 834 |
+
q = k[:2] + (np.asarray(err, float) if err is not None else 0.0)
|
| 835 |
+
self._go([q[0], q[1], k[2] + 0.015], speed=v_down)
|
| 836 |
+
self._go([q[0], q[1], k[2]], speed=0.04, tol=0.003, max_steps=150)
|
| 837 |
+
sk.set_gripper(True, steps=15)
|
| 838 |
+
if lying: # lift slowly until it hangs free, let the swing die down
|
| 839 |
+
cur = sk.eef_pos()
|
| 840 |
+
self._go([cur[0], cur[1], TZ + KNOB_Z + 0.04], speed=0.08)
|
| 841 |
+
sk.hold(20)
|
| 842 |
+
cur = sk.eef_pos()
|
| 843 |
+
self._go([cur[0], cur[1], TZ + z_carry], speed=max(0.12, v_down))
|
| 844 |
+
sk.hold(max(1, int(5 * waits)))
|
| 845 |
+
if self.held(j):
|
| 846 |
+
return True
|
| 847 |
+
sk.set_gripper(False, steps=8)
|
| 848 |
+
cur = sk.eef_pos()
|
| 849 |
+
self._go([cur[0], cur[1], cur[2] + 0.05], speed=0.1)
|
| 850 |
+
return False
|
| 851 |
+
|
| 852 |
+
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):
|
| 853 |
+
"""carry the held jar over board point (u, r) (planned with the board level), straight down until its bottom is
|
| 854 |
+
h_rel above the board top, let go, lift back to carry height"""
|
| 855 |
+
sk = self.sk
|
| 856 |
+
xy = self.level_point(u, r)
|
| 857 |
+
rel = self.jar_bottom(j)[:2] - sk.eef_pos()[:2]
|
| 858 |
+
q = xy - rel
|
| 859 |
+
cur = sk.eef_pos()
|
| 860 |
+
self._go([q[0], q[1], max(cur[2], TZ + z_carry)], yaw=yaw, speed=v)
|
| 861 |
+
sk.hold(max(1, int(12 * waits))) # let the hanging jar stop swinging
|
| 862 |
+
rel = self.jar_bottom(j)[:2] - sk.eef_pos()[:2]
|
| 863 |
+
q = xy - rel
|
| 864 |
+
dz = sk.eef_pos()[2] - envs.obj_min_z(self.env, j)
|
| 865 |
+
zr = self.board_top_z() + dz + h_rel
|
| 866 |
+
self._go([q[0], q[1], zr + 0.02], speed=v_down)
|
| 867 |
+
self._go([q[0], q[1], zr], speed=0.03, tol=0.003, max_steps=150)
|
| 868 |
+
sk.set_gripper(False, steps=12)
|
| 869 |
+
cur = sk.eef_pos()
|
| 870 |
+
self._go([cur[0], cur[1], TZ + z_carry], speed=max(0.15, v_down))
|
| 871 |
+
sk.hold(3)
|
| 872 |
+
|
| 873 |
+
def place(self, i, u, r, p, rng, rand=0.0):
|
| 874 |
+
"""one stage: pick jar i from wherever it is and put it on the board at (u, r) +- rand"""
|
| 875 |
+
j = JARS[i]
|
| 876 |
+
e = rng.uniform(-rand, rand, 2) if rand else np.zeros(2)
|
| 877 |
+
gerr = rng.uniform(-0.002, 0.002, 2) if rand else None
|
| 878 |
+
kw = dict(z_carry=p.get("z_carry", Z_CARRY), v=p.get("v", 0.2), v_down=p.get("v_down", 0.10),
|
| 879 |
+
waits=p.get("waits", 1.0))
|
| 880 |
+
if not self.pick(j, err=gerr, **kw):
|
| 881 |
+
return False
|
| 882 |
+
self.put(j, u + e[0], r + e[1], h_rel=p.get("h_rel", 0.010), **kw)
|
| 883 |
+
self._settle_jar(j)
|
| 884 |
+
return True
|
| 885 |
+
|
| 886 |
+
def supply_order(self):
|
| 887 |
+
"""jar indices by their supply position: the one whose slot is farthest from the robot first (Sonnet fills a
|
| 888 |
+
row from the far end)"""
|
| 889 |
+
return sorted(range(4), key=lambda i: -self.inst["start"][COLOURS[i]][0])
|
| 890 |
+
|
| 891 |
+
def slot_u(self, k):
|
| 892 |
+
"""board u of slot k (k = 0 farthest from the robot)"""
|
| 893 |
+
s = -1.0 if self.inst["side"] == "right" else 1.0
|
| 894 |
+
# u runs along local x = -s * world x -> farthest (largest world x) first
|
| 895 |
+
return -s * SLOT_U[3 - k]
|
| 896 |
+
|
| 897 |
+
def fallen(self):
|
| 898 |
+
return [i for i in range(4) if self.mon["ever"][i] and not self.on_board(i) and not self.held(JARS[i])]
|
| 899 |
+
|
| 900 |
+
def repair(self, r_target, rng, p, rand=0.0, used=None):
|
| 901 |
+
"""move every jar on the board to depth r_target (same slot), then stand up the fallen ones and put them into the
|
| 902 |
+
free slots at r_target"""
|
| 903 |
+
sk = self.sk
|
| 904 |
+
self.wait_board()
|
| 905 |
+
slots = dict(used or {})
|
| 906 |
+
for i in range(4):
|
| 907 |
+
if self.on_board(i) and abs(self.r_cm(i) / 100 - r_target) > 0.02:
|
| 908 |
+
self.place(i, slots.get(i, self.slot_u(0)), r_target, p, rng, rand)
|
| 909 |
+
self.wait_board()
|
| 910 |
+
for i in self.fallen():
|
| 911 |
+
free = [k for k in range(4) if self.slot_u(k) not in slots.values()] or [0]
|
| 912 |
+
u = slots.get(i, self.slot_u(free[0]))
|
| 913 |
+
slots[i] = u
|
| 914 |
+
self.place(i, u, r_target, p, rng, rand)
|
| 915 |
+
self.wait_board()
|
| 916 |
+
sk.hold(5)
|
| 917 |
+
return slots
|
| 918 |
+
|
| 919 |
+
def execute(self, inst, params):
|
| 920 |
+
rng = np.random.default_rng(params.get("noise_seed", 0))
|
| 921 |
+
r = float(params["r"])
|
| 922 |
+
rand = float(params.get("rand", 0.0))
|
| 923 |
+
order = params.get("order") or self.supply_order()
|
| 924 |
+
used = {}
|
| 925 |
+
mode_back = False
|
| 926 |
+
for k, i in enumerate(order):
|
| 927 |
+
u = self.slot_u(k)
|
| 928 |
+
used[i] = u
|
| 929 |
+
rr = R_BACK + params.get("back_off", 0.0) if mode_back else r
|
| 930 |
+
self.place(i, u, rr, params, rng, rand)
|
| 931 |
+
# looks at the jar it just placed (Sonnet): re-places it if it is not standing on the board
|
| 932 |
+
if not self.on_board(i) and params.get("self_check", True):
|
| 933 |
+
self.place(i, u, rr, params, rng, rand)
|
| 934 |
+
if params.get("look_back") and (self.fallen() or self.angle() > np.radians(3.0)):
|
| 935 |
+
# the shelf sags / jars fell: from now on load it near the wall, and move what is on it there too
|
| 936 |
+
mode_back = True
|
| 937 |
+
used = self.repair(R_BACK + params.get("back_off", 0.0), rng, params, rand, used)
|
| 938 |
+
if params.get("final_check"):
|
| 939 |
+
for _ in range(2):
|
| 940 |
+
if all(self.stages()):
|
| 941 |
+
break
|
| 942 |
+
rr = R_BACK + params.get("back_off", 0.0) if (mode_back or params.get("look_back")) else r
|
| 943 |
+
used = self.repair(rr, rng, params, rand, used)
|
| 944 |
+
if not params.get("fast_finish"):
|
| 945 |
+
self._lift_to(Z_CARRY)
|
| 946 |
+
self.sk.hold(5)
|
| 947 |
+
|
| 948 |
+
# naive = Sonnet-like (DESIGN_INSIGHTS §3; lh_nudge_row / lh_bystander pilots): careful top-down pick and place, jars
|
| 949 |
+
# 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
|
| 950 |
+
# placed, no look back at the others before finishing
|
| 951 |
+
def default_params(self, inst):
|
| 952 |
+
sd = int(inst["seed"])
|
| 953 |
+
return dict(r=R_MID + float(inst["naive_bias"]), rand=NAIVE_RAND, noise_seed=sd * 13,
|
| 954 |
+
h_rel=0.010 + 0.030 * ((sd * 7) % 11) / 10, z_carry=Z_CARRY, look_back=False, final_check=False,
|
| 955 |
+
v=NAIVE_V, v_down=NAIVE_V_DOWN, waits=NAIVE_WAITS)
|
| 956 |
+
|
| 957 |
+
def oracle_params(self, inst):
|
| 958 |
+
return dict(r=R_BACK, rand=0.0, h_rel=0.005, z_carry=Z_CARRY, look_back=True, final_check=True)
|
| 959 |
+
|
| 960 |
+
def adapt_params(self, inst, history):
|
| 961 |
+
"""from attempt 2: load the shelf near the wall (same imprecision), look back after every jar and at the end"""
|
| 962 |
+
return dict(self.default_params(inst), r=R_BACK + 0.008, look_back=True, final_check=True)
|
| 963 |
+
|
| 964 |
+
def blind_params(self, inst, attempt, rng):
|
| 965 |
+
"""the naive behaviour with random variation (depth on the board, order, heights), no history, no look back"""
|
| 966 |
+
order = [int(x) for x in rng.permutation(4)]
|
| 967 |
+
return dict(self.default_params(inst), noise_seed=int(rng.integers(1 << 30)), r=float(rng.uniform(0.06, 0.15)),
|
| 968 |
+
order=order, z_carry=float(rng.uniform(0.24, 0.28)), h_rel=float(rng.uniform(0.005, 0.04)),
|
| 969 |
+
v=float(rng.uniform(0.12, 0.3)))
|
| 970 |
+
|
| 971 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 972 |
+
k = k or self.max_attempts
|
| 973 |
+
rng = np.random.default_rng(seed)
|
| 974 |
+
history = []
|
| 975 |
+
single = ("oracle", "naive", "oracle_noise", "naive_front", "naive_back", "naive_check_mid", "naive_fast")
|
| 976 |
+
for a in range(k):
|
| 977 |
+
self.reset_instance(inst)
|
| 978 |
+
if kind == "oracle":
|
| 979 |
+
params = self.oracle_params(inst)
|
| 980 |
+
elif kind == "naive":
|
| 981 |
+
params = self.default_params(inst)
|
| 982 |
+
elif kind == "adaptive": # attempt 1: naive + looks back after every jar; repairs near the wall
|
| 983 |
+
params = (dict(self.default_params(inst), look_back=True, final_check=True, back_off=0.008) if a == 0
|
| 984 |
+
else self.adapt_params(inst, history))
|
| 985 |
+
elif kind == "blind":
|
| 986 |
+
params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
|
| 987 |
+
elif kind == "switch": # control: cross-attempt learning only (near the wall from attempt 2), no repair
|
| 988 |
+
params = (self.default_params(inst) if a == 0 else
|
| 989 |
+
dict(self.default_params(inst), r=R_BACK + 0.008))
|
| 990 |
+
elif kind == "oracle_noise":
|
| 991 |
+
params = dict(self.oracle_params(inst), rand=0.005, noise_seed=int(seed) * 7 + a)
|
| 992 |
+
elif kind == "naive_front": # control: naive, but jars set down near the free edge
|
| 993 |
+
params = dict(self.default_params(inst), r=GAP + BOARD_D - JB - 0.015)
|
| 994 |
+
elif kind == "naive_back": # control: naive pace and imprecision, jars against the wall -> no droop
|
| 995 |
+
params = dict(self.default_params(inst), r=R_BACK + 0.008)
|
| 996 |
+
elif kind == "naive_check_mid": # control: looks back and repairs, but puts the jars back in the middle
|
| 997 |
+
params = dict(self.default_params(inst), final_check=True)
|
| 998 |
+
elif kind == "naive_fast": # control: naive at the fastest pace, finishing right after the last jar
|
| 999 |
+
params = dict(self.default_params(inst), v=0.6, v_down=0.3, waits=0.1, h_rel=0.03, fast_finish=True)
|
| 1000 |
+
else:
|
| 1001 |
+
raise ValueError(kind)
|
| 1002 |
+
self.execute(inst, params)
|
| 1003 |
+
out = self.outcome(inst)
|
| 1004 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 1005 |
+
if on_attempt:
|
| 1006 |
+
on_attempt(a, params, out)
|
| 1007 |
+
if out["success"] or kind in single:
|
| 1008 |
+
break
|
| 1009 |
+
return history
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/export_status.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"batch": "breakfast_v2_20261103_sonnet",
|
| 3 |
+
"status": "complete",
|
| 4 |
+
"pid": 1553947,
|
| 5 |
+
"started": 1793685798.389435,
|
| 6 |
+
"total_runs": 9,
|
| 7 |
+
"recorded": 9,
|
| 8 |
+
"accepted": 9,
|
| 9 |
+
"finished": 1793690058.3777175,
|
| 10 |
+
"dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/breakfast-v2-20261103-breakfast_v2_20261103_sonnet",
|
| 11 |
+
"validation": {
|
| 12 |
+
"codebase_version": "v3.0",
|
| 13 |
+
"episodes": 15,
|
| 14 |
+
"frames": 43500,
|
| 15 |
+
"plan_episodes": 15,
|
| 16 |
+
"plan_frames": 43500,
|
| 17 |
+
"samples": 60,
|
| 18 |
+
"max_state_action_abs_err": 1.156772002630646e-07,
|
| 19 |
+
"max_mean_abs_pixel_err": 2.406,
|
| 20 |
+
"status": "pass"
|
| 21 |
+
},
|
| 22 |
+
"rejected_runs": 0,
|
| 23 |
+
"exported_runs": 9,
|
| 24 |
+
"complete_coverage": true
|
| 25 |
+
}
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/agent/backends/chat_completions.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""OpenAI-compatible Chat Completions backend (function calling), e.g. for a local open-source VLM served
|
| 2 |
+
by scripts/qwen_vl_server.py or any vLLM / SGLang endpoint. Same conversation, different wire format.
|
| 3 |
+
|
| 4 |
+
Reasoning models on this API (Kimi, DeepSeek, vLLM reasoning parsers) return their thinking as the non-standard
|
| 5 |
+
message field `reasoning_content`. It is logged as the reasoning summary and, with replay_reasoning (default), sent
|
| 6 |
+
back unchanged on that assistant message, so the model keeps its reasoning across tool calls like the Anthropic and
|
| 7 |
+
Responses backends do (Kimi's docs ask for this in multi-step tool use)."""
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
import time
|
| 11 |
+
|
| 12 |
+
from ..context import ToolCall, prune_live_images
|
| 13 |
+
from .base import Backend, BackendResponse, import_openai
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def chat_tools(specs):
|
| 17 |
+
return [dict(type="function", function=dict(name=s["name"], description=s["description"],
|
| 18 |
+
parameters=s["parameters"])) for s in specs]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class ChatCompletionsBackend(Backend):
|
| 22 |
+
name = "chat"
|
| 23 |
+
|
| 24 |
+
def __init__(self, model="qwen3-vl-8b", base_url=None, api_key=None, temperature=0.0, max_tokens=1024,
|
| 25 |
+
max_live_images=4, jpeg_quality=90, timeout=600.0, client=None, extra_body=None,
|
| 26 |
+
replay_reasoning=True):
|
| 27 |
+
self.model = model
|
| 28 |
+
self.base_url = base_url or os.environ.get("LFF_CHAT_BASE_URL", "http://127.0.0.1:8765/v1")
|
| 29 |
+
self.api_key = api_key or os.environ.get("LFF_CHAT_API_KEY", "EMPTY")
|
| 30 |
+
self.temperature = temperature
|
| 31 |
+
self.max_tokens = max_tokens
|
| 32 |
+
self.max_live_images = max_live_images
|
| 33 |
+
self.jpeg_quality = jpeg_quality
|
| 34 |
+
self.timeout = timeout
|
| 35 |
+
self.extra_body = extra_body
|
| 36 |
+
self.replay_reasoning = replay_reasoning
|
| 37 |
+
self._client = client
|
| 38 |
+
|
| 39 |
+
def config(self):
|
| 40 |
+
return dict(name=self.name, model=self.model, base_url=self.base_url, temperature=self.temperature,
|
| 41 |
+
max_tokens=self.max_tokens, max_live_images=self.max_live_images,
|
| 42 |
+
replay_reasoning=self.replay_reasoning)
|
| 43 |
+
|
| 44 |
+
def client(self):
|
| 45 |
+
if self._client is None:
|
| 46 |
+
openai = import_openai()
|
| 47 |
+
kw = dict(api_key=self.api_key, base_url=self.base_url, timeout=self.timeout, max_retries=1)
|
| 48 |
+
if any(h in self.base_url for h in ("://127.0.0.1", "://localhost")):
|
| 49 |
+
# local server: ignore the machine's proxy variables (ALL_PROXY=socks5h://... is set here)
|
| 50 |
+
kw["http_client"] = openai.DefaultHttpxClient(trust_env=False, timeout=self.timeout)
|
| 51 |
+
self._client = openai.OpenAI(**kw)
|
| 52 |
+
return self._client
|
| 53 |
+
|
| 54 |
+
def build_request(self, conv, tools):
|
| 55 |
+
msgs = [dict(role="system", content=conv.system)]
|
| 56 |
+
for it in prune_live_images(conv.items, self.max_live_images):
|
| 57 |
+
if it["kind"] == "user":
|
| 58 |
+
content = []
|
| 59 |
+
for p in it["parts"]:
|
| 60 |
+
if p["type"] == "text":
|
| 61 |
+
content.append(dict(type="text", text=p["text"]))
|
| 62 |
+
else:
|
| 63 |
+
content.append(dict(type="image_url", image_url=dict(url=p["image"].data_url(self.jpeg_quality))))
|
| 64 |
+
msgs.append(dict(role="user", content=content))
|
| 65 |
+
elif it["kind"] == "assistant":
|
| 66 |
+
if not it.get("text") and not it["tool_calls"]:
|
| 67 |
+
# a reasoning-only turn (no text, no tool call; seen with DeepSeek at effort=max): the player still
|
| 68 |
+
# counts it and nudges, but OpenAI-compatible APIs reject an assistant message with neither content
|
| 69 |
+
# nor tool_calls (DeepSeek: 400 "content or tool_calls must be set"), so it is left out of the request
|
| 70 |
+
continue
|
| 71 |
+
m = dict(role="assistant", content=it.get("text") or None)
|
| 72 |
+
rc = (it.get("raw") or [{}])[0].get("reasoning_content") if it.get("backend") == self.name else None
|
| 73 |
+
if rc and self.replay_reasoning:
|
| 74 |
+
m["reasoning_content"] = rc
|
| 75 |
+
if it["tool_calls"]:
|
| 76 |
+
m["tool_calls"] = [dict(id=tc.id, type="function",
|
| 77 |
+
function=dict(name=tc.name,
|
| 78 |
+
arguments=tc.raw_arguments or json.dumps(tc.arguments)))
|
| 79 |
+
for tc in it["tool_calls"]]
|
| 80 |
+
msgs.append(m)
|
| 81 |
+
elif it["kind"] == "tool_output":
|
| 82 |
+
msgs.append(dict(role="tool", tool_call_id=it["call_id"], content=it["text"]))
|
| 83 |
+
req = dict(model=self.model, messages=tool_results_first(msgs), tools=chat_tools(tools), tool_choice="auto",
|
| 84 |
+
max_tokens=self.max_tokens)
|
| 85 |
+
if self.temperature is not None: # None: the endpoint's default (reasoning models may reject a temperature)
|
| 86 |
+
req["temperature"] = self.temperature
|
| 87 |
+
if self.extra_body:
|
| 88 |
+
req["extra_body"] = dict(self.extra_body)
|
| 89 |
+
return req
|
| 90 |
+
|
| 91 |
+
def act(self, conv, tools):
|
| 92 |
+
req = self.build_request(conv, tools)
|
| 93 |
+
n_img = sum(1 for m in req["messages"] if isinstance(m.get("content"), list)
|
| 94 |
+
for c in m["content"] if c.get("type") == "image_url")
|
| 95 |
+
t0 = time.time()
|
| 96 |
+
resp = self.client().chat.completions.create(**req)
|
| 97 |
+
lat = time.time() - t0
|
| 98 |
+
stats = dict(n_images=n_img, n_messages=len(req["messages"]))
|
| 99 |
+
if not getattr(resp, "choices", None): # gateway hiccup: nothing to append, the player asks again
|
| 100 |
+
return BackendResponse(latency_s=lat, request_stats=stats, status="incomplete",
|
| 101 |
+
error="empty response (no choices)")
|
| 102 |
+
msg = resp.choices[0].message
|
| 103 |
+
rc = getattr(msg, "reasoning_content", None) or (getattr(msg, "model_extra", None) or {}).get("reasoning_content")
|
| 104 |
+
calls = []
|
| 105 |
+
for i, tc in enumerate(msg.tool_calls or []):
|
| 106 |
+
raw = tc.function.arguments or ""
|
| 107 |
+
try:
|
| 108 |
+
args = json.loads(raw) if raw else {}
|
| 109 |
+
except json.JSONDecodeError:
|
| 110 |
+
args = {}
|
| 111 |
+
calls.append(ToolCall(id=tc.id or f"call_{i}", name=tc.function.name, arguments=args, raw_arguments=raw))
|
| 112 |
+
u = resp.usage
|
| 113 |
+
ctd = getattr(u, "completion_tokens_details", None) if u else None
|
| 114 |
+
usage = dict(input_tokens=getattr(u, "prompt_tokens", 0) or 0, cached_tokens=0,
|
| 115 |
+
output_tokens=getattr(u, "completion_tokens", 0) or 0,
|
| 116 |
+
reasoning_tokens=(getattr(ctd, "reasoning_tokens", 0) or 0) if ctd else 0) if u else {}
|
| 117 |
+
if not calls and not msg.content and not rc and not u:
|
| 118 |
+
return BackendResponse(latency_s=lat, request_stats=stats, status="incomplete",
|
| 119 |
+
error="empty response (no output, no usage)")
|
| 120 |
+
return BackendResponse(tool_calls=calls, text=msg.content or None, reasoning_summary=rc or None, usage=usage,
|
| 121 |
+
latency_s=lat, raw=[dict(reasoning_content=rc)] if rc else None, request_stats=stats)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def tool_results_first(msgs):
|
| 125 |
+
"""OpenAI-compatible APIs require every tool_call of an assistant message to be answered by tool messages directly
|
| 126 |
+
after it. The player adds the images a tool returned (view_images, robot) as a user message right after that tool's
|
| 127 |
+
output, so a turn with several tool calls (e.g. view_images then shell) would put a user message between the tool
|
| 128 |
+
messages (DeepSeek: 400 "insufficient tool messages following tool_calls message"). Move such user messages after
|
| 129 |
+
the last tool message of the turn; nothing else changes order."""
|
| 130 |
+
out, i = [], 0
|
| 131 |
+
while i < len(msgs):
|
| 132 |
+
m = msgs[i]
|
| 133 |
+
out.append(m)
|
| 134 |
+
i += 1
|
| 135 |
+
if m["role"] != "assistant" or not m.get("tool_calls"):
|
| 136 |
+
continue
|
| 137 |
+
need = {tc["id"] for tc in m["tool_calls"]}
|
| 138 |
+
held = []
|
| 139 |
+
while i < len(msgs) and need:
|
| 140 |
+
n = msgs[i]
|
| 141 |
+
if n["role"] == "tool" and n.get("tool_call_id") in need:
|
| 142 |
+
out.append(n)
|
| 143 |
+
need.discard(n["tool_call_id"])
|
| 144 |
+
elif n["role"] == "user":
|
| 145 |
+
held.append(n)
|
| 146 |
+
else:
|
| 147 |
+
break
|
| 148 |
+
i += 1
|
| 149 |
+
out.extend(held)
|
| 150 |
+
return out
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/arm_specs/l3_card_shelf.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled arms for l3_card_shelf (2026-10-12, docs/14 sec. 6).
|
| 2 |
+
|
| 3 |
+
Hidden variable: which end of the (symmetric-looking) card holds the 8 g weight. The centre of mass is compiled into
|
| 4 |
+
the card's MJCF along its local +x, so the heavy end is chosen purely by `card_yaw` (heavy end direction = yaw);
|
| 5 |
+
`heavy_near` / `heavy_edge` are bookkeeping only (nothing in reset / outcome / policies reads them), kept consistent.
|
| 6 |
+
No override changes geometry, mass or inertia, so no bounding-volume refit is involved.
|
| 7 |
+
|
| 8 |
+
h0 : the same card turned end for end (yaw + 180 deg): identical pose and footprint, the weight now in the FAR end,
|
| 9 |
+
so the common-sense "slide the nearest end out" slides the light end and succeeds.
|
| 10 |
+
twin : the trap stays (the heavy end is the nearest end) but it points to the OPPOSITE shelf edge: the card is mirrored
|
| 11 |
+
through the shelf centre along its long axis (near gap, side offset, jitter mirrored) and keeps its weight in
|
| 12 |
+
the end that is now nearest. The right correction (slide the other, light end) is then over the opposite
|
| 13 |
+
edge. For an x-card this makes the near end the BACKWARD one, which the task's own sampler avoids because a
|
| 14 |
+
card tipping off the backward edge lands behind the shelf (agentview shows the shelf empty, not the card);
|
| 15 |
+
see the arm validation (results/l3_card_shelf/arms/). For an instance whose heavy end is already the far end
|
| 16 |
+
(naive succeeds there) the twin keeps the pose and turns the card end for end, so the weight is in the near
|
| 17 |
+
end and the heavy edge is again the opposite one.
|
| 18 |
+
reveal: which shelf edge the heavy end points to, in the F2 feedback's edge words.
|
| 19 |
+
"""
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
HIDDEN_KEYS = ("card_yaw", "heavy_near", "heavy_edge")
|
| 23 |
+
|
| 24 |
+
OPPOSITE = {"forward": "backward", "backward": "forward", "left": "right", "right": "left"}
|
| 25 |
+
GLOSS = {"forward": "away from the robot", "backward": "towards the robot", "left": "on the robot's left",
|
| 26 |
+
"right": "on the robot's right"}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _wrap(a):
|
| 30 |
+
return float((a + np.pi) % (2 * np.pi) - np.pi)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def h0(inst):
|
| 34 |
+
if not inst["heavy_near"]:
|
| 35 |
+
return {} # already the ordinary case for the naive habit (weight away from the end that gets slid out)
|
| 36 |
+
return dict(card_yaw=_wrap(inst["card_yaw"] + np.pi), heavy_near=False, heavy_edge=inst["far_edge"])
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def twin(inst):
|
| 40 |
+
if not inst["heavy_near"]:
|
| 41 |
+
return dict(card_yaw=_wrap(inst["card_yaw"] + np.pi), heavy_near=True, heavy_edge=inst["near_edge"])
|
| 42 |
+
a = 0 if inst["card_along"] == "x" else 1 # world axis of the card's long side
|
| 43 |
+
c = list(inst["card_xy"])
|
| 44 |
+
c[a] = 2.0 * inst["shelf_xy"][a] - c[a]
|
| 45 |
+
yaw = inst["card_yaw"]
|
| 46 |
+
yaw = np.pi - yaw if a == 0 else -yaw # reflection x -> -x (resp. y -> -y) of the card's heading
|
| 47 |
+
return dict(card_xy=[float(c[0]), float(c[1])], card_yaw=_wrap(yaw), near_edge=OPPOSITE[inst["near_edge"]],
|
| 48 |
+
far_edge=OPPOSITE[inst["far_edge"]], heavy_edge=OPPOSITE[inst["heavy_edge"]])
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def reveal(inst):
|
| 52 |
+
e = inst["heavy_edge"]
|
| 53 |
+
return (f"The card is not uniform: 8 g of its 10 g are a weight hidden in the end that points towards the shelf's "
|
| 54 |
+
f"{e} edge ({GLOSS[e]}), so its centre of mass is 2.8 cm from the card's middle towards that end.")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def fix(inst, params):
|
| 58 |
+
"""Ladder Fix rung (docs/20): slide the light end out (two strokes to 2 and 3 cm), grasp the overhang, bin."""
|
| 59 |
+
light = OPPOSITE[inst["heavy_edge"]]
|
| 60 |
+
return (f"A way to succeed: slide the light end out, not the heavy one. The light end is the one pointing towards "
|
| 61 |
+
f"the shelf's {light} edge ({GLOSS[light]}). With the gripper closed, press the fingertips lightly on the "
|
| 62 |
+
f"middle of the card and drag it slowly (speed about 0.08) along its long side towards that edge, in two "
|
| 63 |
+
f"strokes: first until that end sticks out about 2 cm beyond the edge, look, then until it sticks out "
|
| 64 |
+
f"about 3 cm. Then open the gripper, grasp the part that sticks out about 2 cm beyond the edge, at the "
|
| 65 |
+
f"card's height, lift it and drop the card into the bin.")
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/arm_specs/l7_key_turn.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled-arm spec for l7_key_turn (2026-10-12).
|
| 2 |
+
|
| 3 |
+
Hidden variable: inst["direction"], the way the key opens the lock ("CCW" or "CW", seen from above). apply_instance()
|
| 4 |
+
derives the joint range and outcome()/check_unlock()/oracle_params() derive the open sign from it on every reset, so
|
| 5 |
+
overriding "direction" alone is enough (nothing is cached at sampling time).
|
| 6 |
+
|
| 7 |
+
The scripted prior (naive) turns counterclockwise, so the trap exists only on CW locks -- all full5 instances are CW.
|
| 8 |
+
|
| 9 |
+
h0 -> direction = "CCW": same lock position / yaw, the key opens the common-sense way, naive succeeds.
|
| 10 |
+
twin -> {} (no valid twin). The task has a single binary hidden variable and the trap exists only for one of its two
|
| 11 |
+
values: a twin with the trap still active must be CW again, i.e. need exactly the same correction ("turn
|
| 12 |
+
clockwise"), and the sign-flipped twin (CCW) is the H0 twin, where naive succeeds. There is no second hidden
|
| 13 |
+
constraint (the required angle is the fixed quarter turn named in the instruction). The mismatched-history
|
| 14 |
+
arm therefore has to take another instance's history -- note that every trap instance's history teaches the
|
| 15 |
+
same correction, so for this task a mismatched history is not misleading about the direction.
|
| 16 |
+
reveal -> states which way the key turns and that the other way stops after ~3 deg (the words "clockwise",
|
| 17 |
+
"counterclockwise", "seen from above" are those of the task's F2 feedback).
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
HIDDEN_KEYS = ("direction",)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def h0(inst):
|
| 24 |
+
return {"direction": "CCW"}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def twin(inst):
|
| 28 |
+
return {}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def reveal(inst):
|
| 32 |
+
ok, other = (("counterclockwise", "clockwise") if inst["direction"] == "CCW" else ("clockwise", "counterclockwise"))
|
| 33 |
+
return (f"Note: this lock opens only when the key is turned {ok} (seen from above); turned {other} the key moves "
|
| 34 |
+
f"about 3 degrees and then hits a hard stop.")
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/codex.py
ADDED
|
@@ -0,0 +1,687 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Codex CLI as a native harness (arm F; flags measured in research_notes/harness接入调研/02 §2.3, Codex 0.156).
|
| 2 |
+
|
| 3 |
+
Launch: process env exactly the whitelist (env -i equivalent), a brand-new empty CODEX_HOME and HOME (one-time, under
|
| 4 |
+
/tmp/lffstate/<hex>), work dir /tmp/lffrun/<12 hex>, `codex exec --json --skip-git-repo-check --ignore-user-config
|
| 5 |
+
--ignore-rules -s read-only`, ~20 features disabled, project docs / permissions / environment context /
|
| 6 |
+
collaboration-mode / skills instructions off, web search off, and only our MCP server with
|
| 7 |
+
default_tools_approval_mode="approve" (otherwise exec mode silently denies MCP calls).
|
| 8 |
+
|
| 9 |
+
Early exit: `codex exec` ends when the model replies without a tool call, also when the episode is not over (measured
|
| 10 |
+
2026-10-19, cx_pilot6b: gpt-6-astra stopped after a failed first attempt, "I stopped after the one authorized
|
| 11 |
+
attempt", although the finish reply said attempt 2 of 3 starts now). scripts/harness_run.py then sends the reference
|
| 12 |
+
driver's nudge as a user turn with `codex exec resume <thread>` (resume_argv), at most api_player.MAX_NO_TOOL times in
|
| 13 |
+
a row. Hence no --ephemeral: the session is kept in the one-time CODEX_HOME (memories off; removed after the run).
|
| 14 |
+
Measured with 0.163 against the fake server: the resumed request has the same developer messages, tools, model and
|
| 15 |
+
parameters as the first, then the earlier turns and the nudge as a user message.
|
| 16 |
+
|
| 17 |
+
The model API is a custom Responses provider "lffapi", so the preflight can point exactly the same config at a local
|
| 18 |
+
fake server by changing only base_url. Two ways to authenticate (auth=):
|
| 19 |
+
apikey env_key OPENAI_API_KEY (api_env), default endpoint the official API
|
| 20 |
+
chatgpt a ChatGPT subscription login (no API key; same as RPent's codex planner reusing `codex login`): the
|
| 21 |
+
provider gets requires_openai_auth=true (requests carry the login's bearer + chatgpt-account-id), default
|
| 22 |
+
endpoint the ChatGPT Codex backend; a copy of auth.json from the source CODEX_HOME is put into the one-time
|
| 23 |
+
CODEX_HOME (the only file allowed there at launch). If Codex refreshes the login during a run, the refreshed
|
| 24 |
+
auth.json is written back to the source (refresh tokens rotate), unless the source changed meanwhile.
|
| 25 |
+
Launch is refused when the source login is close to its refresh (parallel copies would each rotate it).
|
| 26 |
+
Measured with 0.163 against the fake server: same body keys and headers in both modes plus chatgpt-account-id; the
|
| 27 |
+
preset differs (exec tool description), so pins are per auth mode (pin name codex-chatgpt).
|
| 28 |
+
The calling environment's HTTP(S) proxy is passed through (base.proxy_env; NO_PROXY = loopback only).
|
| 29 |
+
|
| 30 |
+
Model configuration (catalog=, user 2026-10-20): Codex picks the system prompt, tool form and context window per
|
| 31 |
+
model from its model catalog. We always pass an explicit model_catalog_json written into the one-time CODEX_HOME, so
|
| 32 |
+
nothing depends on the catalog the subscription backend serves on the day:
|
| 33 |
+
generic (main table, every model) one entry built from codex_catalogs/generic_<version>.json: what Codex sends for a
|
| 34 |
+
model it has no entry for (its generic Codex CLI prompt, plain function tools, no code mode); per model only
|
| 35 |
+
slug, input modalities and reasoning levels. Measured with 0.163 against the fake server: the request equals
|
| 36 |
+
the no-catalog fallback for an unknown slug apart from message ids.
|
| 37 |
+
native (control) codex_catalogs/native_<version>.json = `codex debug models --bundled` of that binary: the request
|
| 38 |
+
equals the one without any catalog (GPT: code mode, its own prompt). The pins of before 10-20 stay valid.
|
| 39 |
+
Pins are per catalog (pin name codex[-chatgpt][-generic]).
|
| 40 |
+
|
| 41 |
+
Known, accepted differences in native (code mode) catalogs (reported, not fixable by config in 0.156):
|
| 42 |
+
- code mode: the model sees one `exec` tool (JavaScript in a V8 isolate without fs / network); our tools are nested
|
| 43 |
+
and listed only in ALL_TOOLS; MCP images reach the model only if the model's JS calls image(...)
|
| 44 |
+
- apply_patch (blocked by the read-only sandbox), clock, 3 MCP-resource tools (our server has no resources),
|
| 45 |
+
request_user_input, and 6 collaboration.* sub-agent tools cannot be removed; a sub-agent call is an audit violation
|
| 46 |
+
- --json has tokens but no dollar cost
|
| 47 |
+
Fail-closed launch: the preflight checks the top-level tools, the exec nested-tool list (ALL_TOOLS, printed by a
|
| 48 |
+
scripted exec call), the developer (preset) messages and request parameters against the pin.
|
| 49 |
+
"""
|
| 50 |
+
import base64
|
| 51 |
+
import datetime
|
| 52 |
+
import fcntl
|
| 53 |
+
import json
|
| 54 |
+
import os
|
| 55 |
+
import re
|
| 56 |
+
import shutil
|
| 57 |
+
import sqlite3
|
| 58 |
+
import subprocess
|
| 59 |
+
import sys
|
| 60 |
+
import time
|
| 61 |
+
|
| 62 |
+
from . import contract as C
|
| 63 |
+
from . import pins
|
| 64 |
+
from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info,
|
| 65 |
+
new_run_dir, proxy_env, snapshot_tree)
|
| 66 |
+
from .fakeapi import FakeResponses
|
| 67 |
+
from .trajectory import TrajWriter
|
| 68 |
+
|
| 69 |
+
ROOT = C.ROOT
|
| 70 |
+
MCP_SCRIPT = os.path.join(ROOT, "scripts", "mcp_robot_server.py")
|
| 71 |
+
BASE_PATH = "/usr/bin:/bin"
|
| 72 |
+
OFFICIAL_API = "https://api.openai.com/v1"
|
| 73 |
+
CHATGPT_BACKEND = "https://chatgpt.com/backend-api/codex"
|
| 74 |
+
AUTH_FILE = "auth.json"
|
| 75 |
+
AUTH_LOCK = "/tmp/lffstate/.codex_auth.lock"
|
| 76 |
+
MAX_LOGIN_AGE_H = 8 * 24 # codex-rs TOKEN_REFRESH_INTERVAL (8 days, from the source, not measured here): a login
|
| 77 |
+
# older than this is refreshed at start, by every parallel copy
|
| 78 |
+
MIN_ACCESS_LEFT_H = 24 # an access token expiring during a run makes the run's copy refresh it
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _jwt_claims(tok):
|
| 82 |
+
try:
|
| 83 |
+
p = tok.split(".")[1]
|
| 84 |
+
return json.loads(base64.urlsafe_b64decode(p + "=" * (-len(p) % 4)))
|
| 85 |
+
except (IndexError, ValueError, AttributeError):
|
| 86 |
+
return {}
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def chatgpt_login_status(home):
|
| 90 |
+
"""-> dict(ok, problem, last_refresh_h, access_token_valid_h) of the ChatGPT login in home/auth.json. No secret
|
| 91 |
+
leaves this function."""
|
| 92 |
+
src = os.path.join(home, AUTH_FILE)
|
| 93 |
+
try:
|
| 94 |
+
with open(src) as f:
|
| 95 |
+
a = json.load(f)
|
| 96 |
+
except (OSError, ValueError) as e:
|
| 97 |
+
return dict(ok=False, problem=f"cannot read {src}: {type(e).__name__}")
|
| 98 |
+
tok = a.get("tokens") or {}
|
| 99 |
+
if a.get("auth_mode") != "chatgpt" or not tok.get("access_token") or not tok.get("refresh_token"):
|
| 100 |
+
return dict(ok=False, problem=f"{src} is not a ChatGPT login (auth_mode={a.get('auth_mode')!r})")
|
| 101 |
+
now = time.time()
|
| 102 |
+
try:
|
| 103 |
+
lr = datetime.datetime.fromisoformat(str(a.get("last_refresh")).replace("Z", "+00:00")).timestamp()
|
| 104 |
+
age_h = (now - lr) / 3600
|
| 105 |
+
except ValueError:
|
| 106 |
+
age_h = float("inf")
|
| 107 |
+
left_h = (float(_jwt_claims(tok["access_token"]).get("exp") or 0) - now) / 3600
|
| 108 |
+
out = dict(ok=True, problem=None, last_refresh_h=round(age_h, 1), access_token_valid_h=round(left_h, 1))
|
| 109 |
+
if age_h >= MAX_LOGIN_AGE_H or left_h < MIN_ACCESS_LEFT_H:
|
| 110 |
+
out.update(ok=False, problem=f"the ChatGPT login in {home} is due for a refresh (last refresh {age_h:.0f} h ago, "
|
| 111 |
+
f"access token valid {left_h:.0f} h): refresh it once outside the benchmark (use "
|
| 112 |
+
f"codex with CODEX_HOME={home}), so that parallel runs do not each rotate it")
|
| 113 |
+
return out
|
| 114 |
+
DISABLE = ["shell_tool", "unified_exec", "view_image", "multi_agent", "multi_agent_v2", "apps", "browser_use",
|
| 115 |
+
"browser_use_external", "computer_use", "image_generation", "plugins", "hooks", "skill_search",
|
| 116 |
+
"tool_suggest", "goals", "sleep_tool", "in_app_browser", "memories", "skill_mcp_dependency_install",
|
| 117 |
+
"realtime_conversation"]
|
| 118 |
+
# what remains in 0.156 after the lock-down (measured): anything else is refused at launch
|
| 119 |
+
EXPECTED_TOP = ["collaboration.followup_task", "collaboration.interrupt_agent", "collaboration.list_agents",
|
| 120 |
+
"collaboration.send_message", "collaboration.spawn_agent", "collaboration.wait_agent",
|
| 121 |
+
"functions.exec", "functions.request_user_input", "functions.request_user_input_async",
|
| 122 |
+
"functions.wait"]
|
| 123 |
+
EXPECTED_ALL_TOOLS = ["apply_patch", "clock__curr_time", "list_mcp_resource_templates", "list_mcp_resources",
|
| 124 |
+
"mcp__lff__robot", "mcp__lff__shell", "mcp__lff__view_images", "read_mcp_resource"]
|
| 125 |
+
# generic catalog (no code mode), measured with 0.163: our tools are plain functions in the mcp__lff namespace
|
| 126 |
+
EXPECTED_TOP_GENERIC = ["list_mcp_resource_templates", "list_mcp_resources", "mcp__lff.robot", "mcp__lff.shell",
|
| 127 |
+
"mcp__lff.view_images", "read_mcp_resource", "request_user_input"]
|
| 128 |
+
CATALOG_DIR = os.path.join(ROOT, "lffbench", "harnesses", "codex_catalogs")
|
| 129 |
+
CATALOG_FILE = "lff_model_catalog.json" # written into the one-time CODEX_HOME before launch
|
| 130 |
+
CATALOGS = ("generic", "native")
|
| 131 |
+
# generic catalog: the per-model fields (input modalities; the run's reasoning level is always listed)
|
| 132 |
+
TEXT_ONLY_MODELS = {"deepseek-v4-pro": ["text"]} # DeepSeek's Codex guide (read 2026-10-20): v4-pro takes no images
|
| 133 |
+
DEEPSEEK_URL = "https://api.deepseek.com/" # same guide: base_url, wire_api = "responses"
|
| 134 |
+
OPENCODE_GO_URL = "https://opencode.ai/inference/go/openai/v1" # OpenCode Go, Responses API (checked 2026-10-29)
|
| 135 |
+
MCP_TOOLS = ["robot", "shell", "view_images"]
|
| 136 |
+
OK_ITEMS = ("agent_message", "reasoning", "mcp_tool_call", "error")
|
| 137 |
+
PREFLIGHT_JS = "text(JSON.stringify(ALL_TOOLS));"
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def codex_bin():
|
| 141 |
+
return os.environ.get("LFF_CODEX_BIN") or shutil.which("codex") or "codex"
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def toml_str(s):
|
| 145 |
+
return json.dumps(s) # a JSON string literal is a valid TOML basic string
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def _norm(s, cwd):
|
| 149 |
+
s = s.replace(cwd, "<CWD>")
|
| 150 |
+
s = re.sub(r"/tmp/lffrun/[0-9a-f]{12}", "<RUNDIR>", s)
|
| 151 |
+
s = re.sub(r"/tmp/lffstate/[0-9a-f]{12}", "<STATEDIR>", s)
|
| 152 |
+
s = re.sub(r"\b20\d\d-\d\d-\d\d\b", "<DATE>", s)
|
| 153 |
+
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", "<UUID>", s)
|
| 154 |
+
return s
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _walk_tools(ts, prefix=""):
|
| 158 |
+
out = []
|
| 159 |
+
for t in ts or []:
|
| 160 |
+
if t.get("type") == "namespace":
|
| 161 |
+
out += _walk_tools(t.get("tools"), prefix + t.get("name", "") + ".")
|
| 162 |
+
else:
|
| 163 |
+
out.append(dict(name=prefix + (t.get("name") or t.get("type") or "?"), type=t.get("type"),
|
| 164 |
+
description=t.get("description"), parameters=t.get("parameters"), format=t.get("format")))
|
| 165 |
+
return out
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def request_fingerprint(body, cwd, first_message, expected_top=None):
|
| 169 |
+
problems = []
|
| 170 |
+
items = body.get("input") or []
|
| 171 |
+
top = _walk_tools(body.get("tools"))
|
| 172 |
+
dev, users = [], []
|
| 173 |
+
for it in items:
|
| 174 |
+
if it.get("type") == "additional_tools":
|
| 175 |
+
top += _walk_tools(it.get("tools"))
|
| 176 |
+
elif it.get("type") == "message" and it.get("role") in ("developer", "system"):
|
| 177 |
+
dev.append(_norm("\n".join(c.get("text", "") for c in it.get("content") or []), cwd))
|
| 178 |
+
elif it.get("type") == "message" and it.get("role") == "user":
|
| 179 |
+
users.append(it)
|
| 180 |
+
names = sorted(t["name"] for t in top)
|
| 181 |
+
expected_top = EXPECTED_TOP if expected_top is None else expected_top
|
| 182 |
+
if names != expected_top:
|
| 183 |
+
problems.append(f"top-level tools {names} != expected {expected_top}")
|
| 184 |
+
texts = [c.get("text") for u in users for c in u.get("content") or []]
|
| 185 |
+
if texts != [first_message]:
|
| 186 |
+
problems.append(f"user input is not exactly our first message ({len(texts)} user text blocks)")
|
| 187 |
+
for t in top:
|
| 188 |
+
if t.get("description"):
|
| 189 |
+
t["description"] = _norm(t["description"], cwd)
|
| 190 |
+
params = {k: body.get(k) for k in ("model", "reasoning", "parallel_tool_calls", "store", "include", "text",
|
| 191 |
+
"tool_choice", "instructions", "max_output_tokens", "temperature")}
|
| 192 |
+
meta = body.get("client_metadata") or {}
|
| 193 |
+
try:
|
| 194 |
+
turn_meta = json.loads(meta.get("x-codex-turn-metadata") or "{}")
|
| 195 |
+
except ValueError:
|
| 196 |
+
turn_meta = {}
|
| 197 |
+
sandbox = {k: turn_meta.get(k) for k in ("sandbox", "sandbox_mode")}
|
| 198 |
+
if sandbox.get("sandbox_mode") != "read-only":
|
| 199 |
+
problems.append(f"sandbox {sandbox}")
|
| 200 |
+
fp = dict(tools=sorted(top, key=lambda t: t["name"]), developer=dev, params=params, sandbox=sandbox,
|
| 201 |
+
developer_chars=sum(len(d) for d in dev))
|
| 202 |
+
return fp, problems
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def model_catalog(mode, version, model, modalities=None, effort=None):
|
| 206 |
+
"""-> (catalog dict for model_catalog_json, source file). Refuses (fail-closed) when the version has no catalog
|
| 207 |
+
file or, for native, when the model has no entry."""
|
| 208 |
+
if mode not in CATALOGS:
|
| 209 |
+
raise ValueError(f"catalog must be one of {CATALOGS}, not {mode!r}")
|
| 210 |
+
src = os.path.join(CATALOG_DIR, f"{mode}_{version}.json")
|
| 211 |
+
if not os.path.exists(src):
|
| 212 |
+
raise HarnessRefused(f"no {mode} model catalog for Codex {version} ({os.path.relpath(src, ROOT)})")
|
| 213 |
+
d = json.load(open(src))
|
| 214 |
+
if mode == "native":
|
| 215 |
+
if not any(m.get("slug") == model for m in d.get("models") or []):
|
| 216 |
+
raise HarnessRefused(f"native catalog {os.path.basename(src)} has no entry for {model}")
|
| 217 |
+
return d, src
|
| 218 |
+
e = dict(d["entry"], slug=model, display_name=model)
|
| 219 |
+
modalities = modalities or TEXT_ONLY_MODELS.get(model)
|
| 220 |
+
if modalities:
|
| 221 |
+
e["input_modalities"] = list(modalities)
|
| 222 |
+
levels = [dict(x) for x in e.get("supported_reasoning_levels") or []]
|
| 223 |
+
if effort and effort not in [x.get("effort") for x in levels]:
|
| 224 |
+
levels.append(dict(effort=effort, description=effort))
|
| 225 |
+
e["supported_reasoning_levels"] = levels
|
| 226 |
+
return dict(models=[e]), src
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def all_tools_from(body):
|
| 230 |
+
"""The ALL_TOOLS list printed by the preflight exec call (in the second request)."""
|
| 231 |
+
for it in body.get("input") or []:
|
| 232 |
+
if it.get("type") == "custom_tool_call_output":
|
| 233 |
+
out = it.get("output")
|
| 234 |
+
parts = out if isinstance(out, list) else [dict(text=out)]
|
| 235 |
+
for p in parts:
|
| 236 |
+
t = (p.get("text") or "").strip()
|
| 237 |
+
if t.startswith("["):
|
| 238 |
+
try:
|
| 239 |
+
return json.loads(t)
|
| 240 |
+
except ValueError:
|
| 241 |
+
pass
|
| 242 |
+
return None
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
class Codex(HarnessAdapter):
|
| 246 |
+
name = "codex"
|
| 247 |
+
uses_mcp = True
|
| 248 |
+
can_resume = True
|
| 249 |
+
clean_dirs = ("home", "codex_home", "tmp")
|
| 250 |
+
ancestor_files = ("AGENTS.md", "AGENTS.override.md", ".codex")
|
| 251 |
+
capabilities = dict(
|
| 252 |
+
only_benchmark_tools=Cap("partial", "preflight", "generic catalog: our 3 MCP tools as functions + residual "
|
| 253 |
+
"resource×3 / request_user_input; native (code mode): reachable only via exec(JS), "
|
| 254 |
+
"residual apply_patch(blocked) / clock / resource×3 / request_user_input / "
|
| 255 |
+
"collaboration×6"),
|
| 256 |
+
images_reach_model=Cap("partial", "probe", "generic: MCP images go to the model; native (code mode): only if "
|
| 257 |
+
"the model's JS calls image(); bytes unchanged either way"),
|
| 258 |
+
non_persistent_session=Cap("yes", "probe", "only this run's thread, in the one-time CODEX_HOME (for exec "
|
| 259 |
+
"resume), removed after the run; memories off"),
|
| 260 |
+
pinned_version=Cap("yes", "launch", "codex --version + binary sha256 in harness.json; pin per version"),
|
| 261 |
+
machine_readable_events=Cap("yes", "stream", "exec --json (items + usage, no cost)"),
|
| 262 |
+
tool_calls_logged=Cap("yes", "stream", "mcp_tool_call items + mcp_transcript + events.jsonl"),
|
| 263 |
+
model_and_effort=Cap("yes", "preflight", "-m / model_reasoning_effort; request reasoning.effort checked"),
|
| 264 |
+
persistent_memory=Cap("absent", "probe", "memories feature off; empty one-time CODEX_HOME; canaries absent"),
|
| 265 |
+
instruction_file_injection=Cap("absent", "probe", "project_doc_max_bytes=0 + empty CODEX_HOME (AGENTS.md)"),
|
| 266 |
+
web_access=Cap("absent", "probe", "web_search disabled; exec isolate has no fetch"),
|
| 267 |
+
host_file_read=Cap("absent", "probe", "shell / unified_exec / view_image off; exec has no require; "
|
| 268 |
+
"read-only sandbox"),
|
| 269 |
+
builtin_shell=Cap("absent", "preflight", "shell_tool and unified_exec disabled (not in the tool list)"),
|
| 270 |
+
subagent_delegation=Cap("partial", "preflight", "collaboration.* tools cannot be disabled in 0.156; any use "
|
| 271 |
+
"is an audit violation"),
|
| 272 |
+
background_execution=Cap("partial", "preflight", "functions.wait / long exec yields exist; audited"),
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False,
|
| 276 |
+
python=None, extra_args=None, jail=False, auth="apikey", auth_home=None, catalog="generic",
|
| 277 |
+
modalities=None):
|
| 278 |
+
"""api_env: {"OPENAI_API_KEY": ...} (the provider's env_key, auth="apikey"); base_url: Responses endpoint
|
| 279 |
+
(default: official API / ChatGPT Codex backend by auth). auth="chatgpt": a ChatGPT login copied from
|
| 280 |
+
auth_home (default LFF_CODEX_AUTH_HOME, else the calling CODEX_HOME, else ~/.codex), no API key.
|
| 281 |
+
jail: run the CLI in the native-harness jail (lffbench/harnesses/jail.py, static /proc).
|
| 282 |
+
catalog: "generic" (shared configuration of the main table) or "native" (Codex's own entry for the model);
|
| 283 |
+
modalities: input modalities of a generic entry (default text + image)."""
|
| 284 |
+
if catalog not in CATALOGS:
|
| 285 |
+
raise ValueError(f"catalog must be one of {CATALOGS}, not {catalog!r}")
|
| 286 |
+
self.catalog, self.modalities = catalog, (list(modalities) if modalities else None)
|
| 287 |
+
self._catalog_sha = {} # one-time CODEX_HOME -> sha256 of the catalog written there
|
| 288 |
+
if auth not in ("apikey", "chatgpt"):
|
| 289 |
+
raise ValueError(f"auth must be apikey or chatgpt, not {auth!r}")
|
| 290 |
+
if jail:
|
| 291 |
+
from .jail import HarnessJail
|
| 292 |
+
self.jail = HarnessJail(codex_bin(), proc="static")
|
| 293 |
+
self.auth = auth
|
| 294 |
+
self.auth_home = None
|
| 295 |
+
self._auth_copies = {} # one-time CODEX_HOME -> sha256 of the auth.json copied into it
|
| 296 |
+
if auth == "chatgpt":
|
| 297 |
+
self.auth_home = os.path.abspath(auth_home or os.environ.get("LFF_CODEX_AUTH_HOME")
|
| 298 |
+
or os.environ.get("CODEX_HOME") or os.path.expanduser("~/.codex"))
|
| 299 |
+
self.clean_allowed = {"codex_home": ((AUTH_FILE,) if auth == "chatgpt" else ()) + (CATALOG_FILE,)}
|
| 300 |
+
self.api_env = dict(api_env or {}) if auth == "apikey" else {}
|
| 301 |
+
self.base_url = base_url or (OFFICIAL_API if auth == "apikey" else CHATGPT_BACKEND)
|
| 302 |
+
self.proxy = proxy_env()
|
| 303 |
+
self.timeout_s = timeout_s
|
| 304 |
+
self.pins_dir = pins_dir
|
| 305 |
+
self.allow_unpinned = allow_unpinned
|
| 306 |
+
self.python = python or sys.executable
|
| 307 |
+
self.extra_args = list(extra_args or [])
|
| 308 |
+
self._version = None
|
| 309 |
+
|
| 310 |
+
# ------------------------------------------------------------------------------------------------ auth
|
| 311 |
+
def auth_info(self):
|
| 312 |
+
if self.auth == "apikey":
|
| 313 |
+
return dict(mode="apikey", keys=sorted(self.api_env))
|
| 314 |
+
st = chatgpt_login_status(self.auth_home)
|
| 315 |
+
return dict(mode="chatgpt", source=self.auth_home, **{k: v for k, v in st.items() if k != "ok"})
|
| 316 |
+
|
| 317 |
+
def config_info(self):
|
| 318 |
+
"""For harness.json: which model catalog the run used."""
|
| 319 |
+
return dict(catalog=self.catalog, modalities=self.modalities)
|
| 320 |
+
|
| 321 |
+
def _install_catalog(self, codex_home, ep):
|
| 322 |
+
"""Write the run's model catalog into the one-time CODEX_HOME (the only file besides auth.json allowed there
|
| 323 |
+
at launch). -> (path, sha256, source file, code mode)."""
|
| 324 |
+
cat, src = model_catalog(self.catalog, self.version()["version"], ep.model, self.modalities, ep.effort)
|
| 325 |
+
path = os.path.join(codex_home, CATALOG_FILE)
|
| 326 |
+
with open(path, "w") as f:
|
| 327 |
+
json.dump(cat, f)
|
| 328 |
+
sha = C.sha256_file(path)
|
| 329 |
+
self._catalog_sha[codex_home] = sha
|
| 330 |
+
entry = next(m for m in cat["models"] if m.get("slug") == ep.model)
|
| 331 |
+
return path, sha, os.path.relpath(src, ROOT), entry.get("tool_mode") == "code_mode_only"
|
| 332 |
+
|
| 333 |
+
def _install_auth(self, codex_home):
|
| 334 |
+
"""auth="chatgpt": copy the source login into a one-time CODEX_HOME (refused if it is due for a refresh)."""
|
| 335 |
+
if self.auth != "chatgpt":
|
| 336 |
+
return
|
| 337 |
+
st = chatgpt_login_status(self.auth_home)
|
| 338 |
+
if not st["ok"]:
|
| 339 |
+
raise HarnessRefused("ChatGPT login: " + st["problem"])
|
| 340 |
+
dst = os.path.join(codex_home, AUTH_FILE)
|
| 341 |
+
with open(os.path.join(self.auth_home, AUTH_FILE), "rb") as f:
|
| 342 |
+
data = f.read()
|
| 343 |
+
fd = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
| 344 |
+
with os.fdopen(fd, "wb") as f:
|
| 345 |
+
f.write(data)
|
| 346 |
+
self._auth_copies[codex_home] = C.sha256_file(dst)
|
| 347 |
+
|
| 348 |
+
def _sync_auth_back(self, codex_home):
|
| 349 |
+
"""After a run: if Codex refreshed the login in the run's copy, write it back to the source (refresh tokens
|
| 350 |
+
rotate, the source's old one may no longer work), unless the source changed since the copy. -> note or None."""
|
| 351 |
+
copied = self._auth_copies.pop(codex_home, None)
|
| 352 |
+
p = os.path.join(codex_home, AUTH_FILE)
|
| 353 |
+
if copied is None or not os.path.exists(p) or C.sha256_file(p) == copied:
|
| 354 |
+
return None
|
| 355 |
+
try:
|
| 356 |
+
with open(p, "rb") as f:
|
| 357 |
+
data = f.read()
|
| 358 |
+
new = json.loads(data)
|
| 359 |
+
except (OSError, ValueError):
|
| 360 |
+
return "auth.json in the run's CODEX_HOME changed and is unreadable: not written back"
|
| 361 |
+
if new.get("auth_mode") != "chatgpt" or not (new.get("tokens") or {}).get("refresh_token"):
|
| 362 |
+
return "auth.json in the run's CODEX_HOME changed but holds no ChatGPT login: not written back"
|
| 363 |
+
src = os.path.join(self.auth_home, AUTH_FILE)
|
| 364 |
+
os.makedirs(os.path.dirname(AUTH_LOCK), exist_ok=True)
|
| 365 |
+
with open(AUTH_LOCK, "a") as lk:
|
| 366 |
+
fcntl.flock(lk, fcntl.LOCK_EX)
|
| 367 |
+
if C.sha256_file(src) != copied:
|
| 368 |
+
return "the run refreshed its login copy, but the source auth.json changed meanwhile: not written back"
|
| 369 |
+
tmp = src + ".lff-tmp"
|
| 370 |
+
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
| 371 |
+
with os.fdopen(fd, "wb") as f:
|
| 372 |
+
f.write(data)
|
| 373 |
+
os.replace(tmp, src)
|
| 374 |
+
return "the run refreshed the ChatGPT login: refreshed auth.json written back to the source"
|
| 375 |
+
|
| 376 |
+
def version(self):
|
| 377 |
+
if self._version is None:
|
| 378 |
+
b = codex_bin()
|
| 379 |
+
out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent",
|
| 380 |
+
CODEX_HOME="/nonexistent"),
|
| 381 |
+
capture_output=True, text=True, timeout=60)
|
| 382 |
+
v = (out.stdout.strip().split() or ["?"])[-1]
|
| 383 |
+
self._version = dict(version=v, binary=binary_info(b))
|
| 384 |
+
return self._version
|
| 385 |
+
|
| 386 |
+
def pin_key(self, ep):
|
| 387 |
+
v = self.version()
|
| 388 |
+
name = self.name if self.auth == "apikey" else f"{self.name}-{self.auth}"
|
| 389 |
+
name += "" if self.catalog == "native" else f"-{self.catalog}"
|
| 390 |
+
return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
|
| 391 |
+
|
| 392 |
+
# ------------------------------------------------------------------------------------------------ prepare
|
| 393 |
+
def config_args(self, ep, session_path, base_url, codex_home):
|
| 394 |
+
mcp_cmd, mcp_args = self.mcp_server_command(self.python, MCP_SCRIPT, ["--session", session_path] if session_path
|
| 395 |
+
else ["--schema-only"])
|
| 396 |
+
c = ["model_reasoning_effort=" + toml_str(ep.effort),
|
| 397 |
+
"project_doc_max_bytes=0", "include_permissions_instructions=false", "include_environment_context=false",
|
| 398 |
+
"include_collaboration_mode_instructions=false", "skills.include_instructions=false",
|
| 399 |
+
"skills.bundled.enabled=false", 'web_search="disabled"',
|
| 400 |
+
'model_provider="lffapi"', 'model_providers.lffapi.name="lffapi"',
|
| 401 |
+
"model_providers.lffapi.base_url=" + toml_str(base_url), 'model_providers.lffapi.wire_api="responses"',
|
| 402 |
+
('model_providers.lffapi.env_key="OPENAI_API_KEY"' if self.auth == "apikey"
|
| 403 |
+
else "model_providers.lffapi.requires_openai_auth=true"),
|
| 404 |
+
"mcp_servers.lff.command=" + toml_str(mcp_cmd),
|
| 405 |
+
"mcp_servers.lff.args=[" + ",".join(toml_str(x) for x in mcp_args) + "]",
|
| 406 |
+
"mcp_servers.lff.env={PATH=" + toml_str(BASE_PATH) + "}",
|
| 407 |
+
'mcp_servers.lff.enabled_tools=["robot","shell","view_images"]',
|
| 408 |
+
'mcp_servers.lff.default_tools_approval_mode="approve"', "mcp_servers.lff.required=true",
|
| 409 |
+
"mcp_servers.lff.startup_timeout_sec=60", "mcp_servers.lff.tool_timeout_sec=900",
|
| 410 |
+
"model_catalog_json=" + toml_str(os.path.join(codex_home, CATALOG_FILE))]
|
| 411 |
+
return c
|
| 412 |
+
|
| 413 |
+
def argv(self, ep, session_path, base_url, first_message, codex_home):
|
| 414 |
+
a = [codex_bin(), "exec", "--json", "--skip-git-repo-check", "--ignore-user-config",
|
| 415 |
+
"--ignore-rules", "-s", "read-only", "-m", ep.model]
|
| 416 |
+
for f in DISABLE:
|
| 417 |
+
a += ["--disable", f]
|
| 418 |
+
for c in self.config_args(ep, session_path, base_url, codex_home):
|
| 419 |
+
a += ["-c", c]
|
| 420 |
+
return a + self.extra_args + [first_message]
|
| 421 |
+
|
| 422 |
+
@staticmethod
|
| 423 |
+
def thread_id(stdout_path):
|
| 424 |
+
t = None
|
| 425 |
+
for line in open(stdout_path, encoding="utf-8", errors="replace"):
|
| 426 |
+
if line.startswith("{") and '"thread.started"' in line:
|
| 427 |
+
t = json.loads(line).get("thread_id") or t
|
| 428 |
+
return t
|
| 429 |
+
|
| 430 |
+
def resume_argv(self, h, message):
|
| 431 |
+
"""`codex exec resume <thread> <message>` with the launch's flags and config; resume has no -s, so the
|
| 432 |
+
sandbox goes in as sandbox_mode."""
|
| 433 |
+
thread = self.thread_id(h.spec.stdout_path)
|
| 434 |
+
if not thread:
|
| 435 |
+
raise HarnessRefused("resume: no thread id in the event stream")
|
| 436 |
+
a = list(h.spec.argv[:-1]) # without the first message
|
| 437 |
+
i = a.index("exec")
|
| 438 |
+
rest = a[i + 1:]
|
| 439 |
+
j = rest.index("-s")
|
| 440 |
+
mode = rest[j + 1]
|
| 441 |
+
del rest[j:j + 2]
|
| 442 |
+
return a[:i + 1] + ["resume"] + rest + ["-c", "sandbox_mode=" + toml_str(mode), thread, message]
|
| 443 |
+
|
| 444 |
+
def env(self, state):
|
| 445 |
+
e = dict(PATH=BASE_PATH, HOME=state["home"], CODEX_HOME=state["codex_home"], TMPDIR=state["tmp"],
|
| 446 |
+
LANG="C.UTF-8")
|
| 447 |
+
e.update(self.proxy)
|
| 448 |
+
e.update(self.api_env)
|
| 449 |
+
return e
|
| 450 |
+
|
| 451 |
+
def _state_dirs(self, hexname=None):
|
| 452 |
+
root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate")
|
| 453 |
+
os.makedirs(root, exist_ok=True)
|
| 454 |
+
state = dict(state=root, home=os.path.join(root, "home"), codex_home=os.path.join(root, "codex_home"),
|
| 455 |
+
tmp=os.path.join(root, "tmp"))
|
| 456 |
+
for k in ("home", "codex_home", "tmp"):
|
| 457 |
+
os.makedirs(state[k], exist_ok=True)
|
| 458 |
+
return state
|
| 459 |
+
|
| 460 |
+
def prepare(self, ep, first_message, reuse_state=None):
|
| 461 |
+
work = new_run_dir("/tmp/lffrun")
|
| 462 |
+
state = reuse_state or self._state_dirs(os.path.basename(work))
|
| 463 |
+
if self.jail is not None:
|
| 464 |
+
self.jail.stderr_dir = ep.log_dir
|
| 465 |
+
if not reuse_state and os.listdir(state["codex_home"]):
|
| 466 |
+
raise HarnessRefused("CODEX_HOME is not empty")
|
| 467 |
+
cat_path, cat_sha, cat_src, code_mode = self._install_catalog(state["codex_home"], ep)
|
| 468 |
+
argv = self.argv(ep, ep.session_path, self.base_url, first_message, state["codex_home"])
|
| 469 |
+
return LaunchSpec(argv=argv, env=self.env(state), cwd=work, run_dir=work, state_dirs=state,
|
| 470 |
+
first_message=first_message, stdout_path=os.path.join(ep.log_dir, "codex_events.jsonl"),
|
| 471 |
+
stderr_path=os.path.join(ep.log_dir, "codex_stderr.txt"),
|
| 472 |
+
redact_argv={len(argv) - 1: f"<first message: sha256={C.sha256_text(first_message)}>"},
|
| 473 |
+
config_files=dict(model_catalog_json=dict(path=cat_path, sha256=cat_sha, source=cat_src,
|
| 474 |
+
catalog=self.catalog, code_mode=code_mode)),
|
| 475 |
+
timeout_s=self.timeout_s)
|
| 476 |
+
|
| 477 |
+
def launch(self, spec, ep, skip_preflight=False):
|
| 478 |
+
self._install_auth(spec.state_dirs["codex_home"])
|
| 479 |
+
return super().launch(spec, ep, skip_preflight=skip_preflight)
|
| 480 |
+
|
| 481 |
+
def cleanup(self, spec):
|
| 482 |
+
self._sync_auth_back(spec.state_dirs.get("codex_home", ""))
|
| 483 |
+
super().cleanup(spec)
|
| 484 |
+
|
| 485 |
+
def config_sha256(self, spec, ep):
|
| 486 |
+
"""Hash of everything configurable (argv without the first message, env values except keys / one-time dirs)."""
|
| 487 |
+
argv = [re.sub(r"/tmp/lffsock/[0-9a-f]{12}/[^\"\],]+", "<JAIL_SOCKET>", a.replace(ep.session_path, "<SESSION>"))
|
| 488 |
+
.replace(spec.state_dirs["codex_home"], "<CODEX_HOME>") for a in self.logged_argv(spec)[1:-1]]
|
| 489 |
+
env = {k: (v if k not in self.api_env else "<api>") for k, v in spec.env.items()
|
| 490 |
+
if k not in ("HOME", "CODEX_HOME", "TMPDIR") + PROXY_KEYS + NO_PROXY_KEYS}
|
| 491 |
+
cat = (spec.config_files.get("model_catalog_json") or {}).get("sha256")
|
| 492 |
+
return C.sha256_json(dict(argv=argv, env=env, model_catalog_sha256=cat))
|
| 493 |
+
|
| 494 |
+
# ------------------------------------------------------------------------------------------------ preflight
|
| 495 |
+
def preflight(self, spec, ep, record_dir=None):
|
| 496 |
+
t0 = time.time()
|
| 497 |
+
code_mode = (spec.config_files.get("model_catalog_json") or {}).get("code_mode", True)
|
| 498 |
+
script = [[("exec", PREFLIGHT_JS)], [("text", "preflight ok")]] if code_mode else [[("text", "preflight ok")]]
|
| 499 |
+
fake = FakeResponses(script, record_dir=record_dir).start()
|
| 500 |
+
pre = self._state_dirs()
|
| 501 |
+
try:
|
| 502 |
+
self._install_auth(pre["codex_home"])
|
| 503 |
+
self._install_catalog(pre["codex_home"], ep)
|
| 504 |
+
argv = self.argv(ep, None, fake.base_url, spec.first_message, pre["codex_home"])
|
| 505 |
+
env = self.env(pre)
|
| 506 |
+
if self.auth == "apikey":
|
| 507 |
+
env["OPENAI_API_KEY"] = "sk-preflight-not-a-key"
|
| 508 |
+
r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd,
|
| 509 |
+
stdin=subprocess.DEVNULL, capture_output=True, timeout=180)
|
| 510 |
+
reqs = fake.model_requests()
|
| 511 |
+
if len(reqs) < (2 if code_mode else 1):
|
| 512 |
+
raise HarnessRefused(f"preflight: {len(reqs)} model requests (rc={r.returncode}): "
|
| 513 |
+
f"{r.stderr.decode('utf-8', 'replace')[-800:]}")
|
| 514 |
+
fp, problems = request_fingerprint(reqs[0][1], spec.cwd, spec.first_message,
|
| 515 |
+
EXPECTED_TOP if code_mode else EXPECTED_TOP_GENERIC)
|
| 516 |
+
at_names = None
|
| 517 |
+
if code_mode: # our tools are nested in exec: the scripted exec call prints them
|
| 518 |
+
at = all_tools_from(reqs[1][1])
|
| 519 |
+
if at is None:
|
| 520 |
+
problems.append("exec preflight did not print ALL_TOOLS")
|
| 521 |
+
at = []
|
| 522 |
+
at_names = sorted(t.get("name") if isinstance(t, dict) else str(t) for t in at)
|
| 523 |
+
if at_names != EXPECTED_ALL_TOOLS:
|
| 524 |
+
problems.append(f"ALL_TOOLS {at_names} != expected {EXPECTED_ALL_TOOLS}")
|
| 525 |
+
fp["all_tools"] = [({k: (_norm(v, spec.cwd) if isinstance(v, str) else v) for k, v in t.items()}
|
| 526 |
+
if isinstance(t, dict) else t) for t in sorted(at, key=lambda t: json.dumps(t))]
|
| 527 |
+
effort = (fp["params"].get("reasoning") or {}).get("effort")
|
| 528 |
+
if effort != ep.effort:
|
| 529 |
+
problems.append(f"reasoning.effort in request {effort!r} != {ep.effort!r}")
|
| 530 |
+
if os.listdir(spec.cwd):
|
| 531 |
+
problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}")
|
| 532 |
+
fp_sha = C.sha256_json(fp)
|
| 533 |
+
out = dict(fingerprint_sha256=fp_sha, developer_chars=fp["developer_chars"], n_requests=len(reqs),
|
| 534 |
+
top_tools=[t["name"] for t in fp["tools"]], all_tools=at_names, code_mode=code_mode,
|
| 535 |
+
catalog=self.catalog, effort_in_request=effort,
|
| 536 |
+
model_in_request=fp["params"].get("model"), sandbox=fp["sandbox"], dt_s=round(time.time() - t0, 1),
|
| 537 |
+
problems=problems)
|
| 538 |
+
pin = pins.load(self.pin_key(ep), self.pins_dir)
|
| 539 |
+
out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"])
|
| 540 |
+
out["fingerprint"] = fp
|
| 541 |
+
if problems:
|
| 542 |
+
raise HarnessRefused("preflight: " + "; ".join(problems))
|
| 543 |
+
if pin is None:
|
| 544 |
+
if not self.allow_unpinned:
|
| 545 |
+
raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck "
|
| 546 |
+
f"with --write-pins after the self-check passes)")
|
| 547 |
+
out["pin_status"] = "unpinned (allowed)"
|
| 548 |
+
elif pin["fingerprint_sha256"] != fp_sha:
|
| 549 |
+
raise HarnessRefused(f"preflight: preset prompt / tools fingerprint {fp_sha[:12]} != pinned "
|
| 550 |
+
f"{pin['fingerprint_sha256'][:12]} ({pin['key']})")
|
| 551 |
+
else:
|
| 552 |
+
out["pin_status"] = "match"
|
| 553 |
+
return out
|
| 554 |
+
finally:
|
| 555 |
+
fake.stop()
|
| 556 |
+
self._sync_auth_back(pre["codex_home"])
|
| 557 |
+
shutil.rmtree(pre["state"], ignore_errors=True)
|
| 558 |
+
|
| 559 |
+
# ------------------------------------------------------------------------------------------------ collect
|
| 560 |
+
def collect(self, h):
|
| 561 |
+
spec, ep = h.spec, h.ep
|
| 562 |
+
tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
|
| 563 |
+
thread, usage, items, errors = None, dict(input=0, cached=0, output=0, reasoning=0), [], []
|
| 564 |
+
for line in open(spec.stdout_path, encoding="utf-8", errors="replace"):
|
| 565 |
+
if not line.startswith("{"):
|
| 566 |
+
continue
|
| 567 |
+
d = json.loads(line)
|
| 568 |
+
t = d.get("type")
|
| 569 |
+
if t == "thread.started":
|
| 570 |
+
thread = d.get("thread_id")
|
| 571 |
+
elif t == "turn.completed":
|
| 572 |
+
u = d.get("usage") or {}
|
| 573 |
+
usage["input"] += u.get("input_tokens") or 0
|
| 574 |
+
usage["cached"] += u.get("cached_input_tokens") or 0
|
| 575 |
+
usage["output"] += u.get("output_tokens") or 0
|
| 576 |
+
usage["reasoning"] += u.get("reasoning_output_tokens") or 0
|
| 577 |
+
elif t in ("error", "turn.failed"):
|
| 578 |
+
errors.append(d)
|
| 579 |
+
elif t == "item.completed":
|
| 580 |
+
it = d.get("item") or {}
|
| 581 |
+
items.append(it.get("type"))
|
| 582 |
+
if it.get("type") == "agent_message":
|
| 583 |
+
tw.add_step("agent", message=it.get("text", ""))
|
| 584 |
+
elif it.get("type") == "reasoning":
|
| 585 |
+
tw.add_step("agent", reasoning=it.get("text", ""))
|
| 586 |
+
else:
|
| 587 |
+
name = it.get("tool") if it.get("type") == "mcp_tool_call" else it.get("type")
|
| 588 |
+
args = it.get("arguments") if it.get("type") == "mcp_tool_call" else {
|
| 589 |
+
k: v for k, v in it.items() if k not in ("id", "type", "status")}
|
| 590 |
+
st = tw.add_step("agent", tool_calls=[dict(tool_call_id=it.get("id"), function_name=name,
|
| 591 |
+
native_name=f"{it.get('server', '')}.{name}"
|
| 592 |
+
if it.get("type") == "mcp_tool_call" else name,
|
| 593 |
+
item_type=it.get("type"), arguments=args)])
|
| 594 |
+
res = it.get("result") or {}
|
| 595 |
+
texts = [c.get("text", "") for c in res.get("content") or [] if c.get("type") == "text"]
|
| 596 |
+
imgs = sum(1 for c in res.get("content") or [] if c.get("type") == "image")
|
| 597 |
+
tw.add_result(it.get("id"), "\n".join(texts) if texts else json.dumps(it.get("error")),
|
| 598 |
+
bool(it.get("error")) or it.get("status") == "failed", imgs)
|
| 599 |
+
del st
|
| 600 |
+
v = self.version()
|
| 601 |
+
tw.set_header(session_id=thread, source=os.path.basename(spec.stdout_path),
|
| 602 |
+
agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort),
|
| 603 |
+
tools=EXPECTED_ALL_TOOLS if (spec.config_files.get("model_catalog_json") or {}).get(
|
| 604 |
+
"code_mode", True) else EXPECTED_TOP_GENERIC)
|
| 605 |
+
tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], item_types=sorted(set(items))),
|
| 606 |
+
total_prompt_tokens=usage["input"], total_completion_tokens=usage["output"],
|
| 607 |
+
total_cached_tokens=usage["cached"], total_cost_usd=None, reasoning_tokens=usage["reasoning"])
|
| 608 |
+
tw.write()
|
| 609 |
+
h.info.update(items=items, traj=tw, thread=thread, errors=errors)
|
| 610 |
+
return tw
|
| 611 |
+
|
| 612 |
+
# ------------------------------------------------------------------------------------------------ audit
|
| 613 |
+
@staticmethod
|
| 614 |
+
def sqlite_rows(path, table):
|
| 615 |
+
"""Row count of `table`, read from a copy (the db may be in WAL mode and still open)."""
|
| 616 |
+
import tempfile
|
| 617 |
+
try:
|
| 618 |
+
with tempfile.TemporaryDirectory() as td:
|
| 619 |
+
for suf in ("", "-wal", "-shm"):
|
| 620 |
+
if os.path.exists(path + suf):
|
| 621 |
+
shutil.copy(path + suf, os.path.join(td, "db.sqlite" + suf))
|
| 622 |
+
con = sqlite3.connect(os.path.join(td, "db.sqlite"))
|
| 623 |
+
n = con.execute(f"select count(*) from {table}").fetchone()[0]
|
| 624 |
+
con.close()
|
| 625 |
+
return n
|
| 626 |
+
except (sqlite3.Error, OSError) as e:
|
| 627 |
+
return f"n/a ({e})"
|
| 628 |
+
|
| 629 |
+
def audit(self, h):
|
| 630 |
+
spec, ep = h.spec, h.ep
|
| 631 |
+
v, notes = [], []
|
| 632 |
+
items = h.info.get("items") or []
|
| 633 |
+
bad = sorted({i for i in items if i not in OK_ITEMS})
|
| 634 |
+
if bad:
|
| 635 |
+
v.append(f"non-MCP items in the event stream: {bad}")
|
| 636 |
+
tw = h.info.get("traj")
|
| 637 |
+
residual = []
|
| 638 |
+
for st in (tw.steps if tw else []):
|
| 639 |
+
for tc in st["tool_calls"]:
|
| 640 |
+
if tc.get("item_type") != "mcp_tool_call":
|
| 641 |
+
continue
|
| 642 |
+
if tc["native_name"].startswith("lff.") and tc["function_name"] in MCP_TOOLS:
|
| 643 |
+
continue
|
| 644 |
+
if tc["function_name"] in ("list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"):
|
| 645 |
+
residual.append(tc["function_name"]) # our server has no resources: always empty
|
| 646 |
+
else:
|
| 647 |
+
v.append(f"unexpected MCP call {tc['native_name']}")
|
| 648 |
+
if residual:
|
| 649 |
+
notes.append(f"residual MCP-resource tool calls (empty, our server has no resources): {residual}")
|
| 650 |
+
if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env):
|
| 651 |
+
v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}")
|
| 652 |
+
ch = spec.state_dirs["codex_home"]
|
| 653 |
+
note = self._sync_auth_back(ch)
|
| 654 |
+
if note:
|
| 655 |
+
notes.append(note)
|
| 656 |
+
left = dict(codex_home=snapshot_tree(ch), home=snapshot_tree(spec.state_dirs["home"]),
|
| 657 |
+
work=snapshot_tree(spec.cwd))
|
| 658 |
+
threads = None
|
| 659 |
+
for f in left["codex_home"]:
|
| 660 |
+
if re.match(r"state_\d+\.sqlite$", f):
|
| 661 |
+
threads = self.sqlite_rows(os.path.join(ch, f), "threads")
|
| 662 |
+
if isinstance(threads, int) and threads > 1:
|
| 663 |
+
v.append(f"{threads} threads persisted in CODEX_HOME (only this run's one is expected)")
|
| 664 |
+
thread = h.info.get("thread")
|
| 665 |
+
sessions = [f for f in left["codex_home"] if f.startswith(("sessions/", "archived_sessions/"))]
|
| 666 |
+
foreign = [f for f in sessions if not (thread and f.startswith("sessions/") and f.endswith(f"-{thread}.jsonl"))]
|
| 667 |
+
if foreign:
|
| 668 |
+
v.append(f"session files other than this run's thread: {foreign}")
|
| 669 |
+
if h.info.get("resumes"):
|
| 670 |
+
notes.append(f"resumed {len(h.info['resumes'])}x with the reference driver's nudge (CLI exited before the "
|
| 671 |
+
f"episode was over)")
|
| 672 |
+
if left["work"]:
|
| 673 |
+
v.append(f"files in the work dir: {left['work']}")
|
| 674 |
+
if (spec.config_files.get("model_catalog_json") or {}).get("code_mode", True):
|
| 675 |
+
notes.append("image forwarding (model calls image()) is not visible in --json; needs the model proxy (P1)")
|
| 676 |
+
mcp_env = None
|
| 677 |
+
mt = os.path.join(ep.log_dir, "mcp_transcript.jsonl")
|
| 678 |
+
if os.path.exists(mt):
|
| 679 |
+
for line in open(mt):
|
| 680 |
+
d = json.loads(line)
|
| 681 |
+
if d.get("ev") == "start" and "env_keys" in d:
|
| 682 |
+
mcp_env = d["env_keys"]
|
| 683 |
+
out = dict(harness=self.name, violations=v, notes=notes, files_left=left, threads_rows=threads,
|
| 684 |
+
mcp_server_env_keys=mcp_env, item_types=sorted(set(items)), errors=h.info.get("errors"), ok=not v)
|
| 685 |
+
with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
|
| 686 |
+
json.dump(out, f, indent=1)
|
| 687 |
+
return out
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/fakeapi.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Local fake model APIs for offline harness checks (no real model, no cost).
|
| 2 |
+
|
| 3 |
+
Both servers listen on 127.0.0.1, record every request body (auth headers dropped) and answer from a script, so a
|
| 4 |
+
native harness can be driven turn by turn without a model:
|
| 5 |
+
FakeAnthropic Anthropic Messages API (streaming SSE), used by Claude Code and by api_player --provider anthropic
|
| 6 |
+
FakeResponses OpenAI Responses API (streaming SSE), used by Codex through a custom model provider
|
| 7 |
+
|
| 8 |
+
A script is a list of turns; turn i is answered to the request that already holds i assistant turns, so retries get
|
| 9 |
+
the same answer. Past the end of the script the server answers with a final text. A turn is a list of steps:
|
| 10 |
+
("tool", name, args) Anthropic: tool_use block (name as given, e.g. "mcp__lff__robot" or "Read")
|
| 11 |
+
("text", s) a text block / assistant message
|
| 12 |
+
("exec", js) Responses: one `exec` custom tool call (Codex code mode) with this JavaScript
|
| 13 |
+
("fcall", name, args) Responses: a plain function call
|
| 14 |
+
("nscall", ns, name, args) Responses: a function call into a tool namespace (Codex without code mode calls our MCP
|
| 15 |
+
tools this way: name "robot", namespace "mcp__lff"; measured with 0.163)
|
| 16 |
+
|
| 17 |
+
srv = FakeAnthropic(script, record_dir).start(); ... srv.base_url ...; srv.stop()
|
| 18 |
+
"""
|
| 19 |
+
import itertools
|
| 20 |
+
import json
|
| 21 |
+
import os
|
| 22 |
+
import threading
|
| 23 |
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 24 |
+
|
| 25 |
+
DROP_HEADERS = ("x-api-key", "authorization", "cookie", "chatgpt-account-id")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class _Base:
|
| 29 |
+
final_text = "done"
|
| 30 |
+
|
| 31 |
+
def __init__(self, script=None, record_dir=None, port=0):
|
| 32 |
+
self.script = list(script or [])
|
| 33 |
+
self.record_dir = record_dir
|
| 34 |
+
self.port = port
|
| 35 |
+
self.lock = threading.Lock()
|
| 36 |
+
self.counter = itertools.count(1)
|
| 37 |
+
self.requests = [] # (n, path, body)
|
| 38 |
+
if record_dir:
|
| 39 |
+
os.makedirs(record_dir, exist_ok=True)
|
| 40 |
+
|
| 41 |
+
# ------------------------------------------------------------------ plumbing
|
| 42 |
+
def start(self):
|
| 43 |
+
outer = self
|
| 44 |
+
|
| 45 |
+
class H(BaseHTTPRequestHandler):
|
| 46 |
+
protocol_version = "HTTP/1.1"
|
| 47 |
+
|
| 48 |
+
def log_message(self, *a):
|
| 49 |
+
pass
|
| 50 |
+
|
| 51 |
+
def _record(self, body):
|
| 52 |
+
with outer.lock:
|
| 53 |
+
n = next(outer.counter)
|
| 54 |
+
outer.requests.append((n, self.path, body))
|
| 55 |
+
if outer.record_dir:
|
| 56 |
+
with open(os.path.join(outer.record_dir, f"req_{n:03d}.json"), "w") as f:
|
| 57 |
+
json.dump(dict(method=self.command, path=self.path, body=body,
|
| 58 |
+
headers={k: v for k, v in self.headers.items() if k.lower() not in DROP_HEADERS}),
|
| 59 |
+
f, indent=1, ensure_ascii=False)
|
| 60 |
+
return n
|
| 61 |
+
|
| 62 |
+
def do_GET(self):
|
| 63 |
+
self._record(None)
|
| 64 |
+
self._send(404, b"{}", "application/json")
|
| 65 |
+
|
| 66 |
+
def do_HEAD(self):
|
| 67 |
+
self._send(404, b"", "application/json")
|
| 68 |
+
|
| 69 |
+
def do_POST(self):
|
| 70 |
+
raw = self.rfile.read(int(self.headers.get("content-length", 0) or 0))
|
| 71 |
+
try:
|
| 72 |
+
body = json.loads(raw)
|
| 73 |
+
except ValueError:
|
| 74 |
+
body = raw[:4000].decode("utf-8", "replace")
|
| 75 |
+
n = self._record(body)
|
| 76 |
+
outer.handle(self, n, body)
|
| 77 |
+
|
| 78 |
+
def _send(self, code, data, ctype):
|
| 79 |
+
self.send_response(code)
|
| 80 |
+
self.send_header("content-type", ctype)
|
| 81 |
+
self.send_header("content-length", str(len(data)))
|
| 82 |
+
self.end_headers()
|
| 83 |
+
self.wfile.write(data)
|
| 84 |
+
|
| 85 |
+
self.httpd = ThreadingHTTPServer(("127.0.0.1", self.port), H)
|
| 86 |
+
self.httpd.daemon_threads = True
|
| 87 |
+
self.port = self.httpd.server_address[1]
|
| 88 |
+
threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
|
| 89 |
+
return self
|
| 90 |
+
|
| 91 |
+
def stop(self):
|
| 92 |
+
self.httpd.shutdown()
|
| 93 |
+
self.httpd.server_close()
|
| 94 |
+
|
| 95 |
+
def turn(self, i):
|
| 96 |
+
return self.script[i] if i < len(self.script) else [("text", self.final_text)]
|
| 97 |
+
|
| 98 |
+
@staticmethod
|
| 99 |
+
def send_sse(h, events):
|
| 100 |
+
data = b"".join(f"event: {ev}\ndata: {json.dumps(d)}\n\n".encode() for ev, d in events)
|
| 101 |
+
h._send(200, data, "text/event-stream")
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class FakeAnthropic(_Base):
|
| 105 |
+
@property
|
| 106 |
+
def base_url(self):
|
| 107 |
+
return f"http://127.0.0.1:{self.port}"
|
| 108 |
+
|
| 109 |
+
def handle(self, h, n, body):
|
| 110 |
+
if not h.path.startswith("/v1/messages") or "count_tokens" in h.path or not isinstance(body, dict):
|
| 111 |
+
h._send(200, json.dumps({"input_tokens": 10}).encode(), "application/json")
|
| 112 |
+
return
|
| 113 |
+
msgs = body.get("messages", [])
|
| 114 |
+
i = sum(1 for m in msgs if m.get("role") == "assistant")
|
| 115 |
+
steps = self.turn(i)
|
| 116 |
+
blocks = []
|
| 117 |
+
for j, st in enumerate(steps):
|
| 118 |
+
if st[0] == "tool":
|
| 119 |
+
blocks.append(dict(type="tool_use", id=f"toolu_fake_{i:03d}_{j}", name=st[1], input=st[2]))
|
| 120 |
+
else:
|
| 121 |
+
blocks.append(dict(type="text", text=st[1]))
|
| 122 |
+
stop = "tool_use" if any(b["type"] == "tool_use" for b in blocks) else "end_turn"
|
| 123 |
+
model = body.get("model", "fake")
|
| 124 |
+
evs = [("message_start", dict(type="message_start", message=dict(
|
| 125 |
+
id=f"msg_fake_{n}", type="message", role="assistant", model=model, content=[], stop_reason=None,
|
| 126 |
+
stop_sequence=None, usage=dict(input_tokens=100, output_tokens=1))))]
|
| 127 |
+
for k, b in enumerate(blocks):
|
| 128 |
+
if b["type"] == "tool_use":
|
| 129 |
+
evs.append(("content_block_start", dict(type="content_block_start", index=k, content_block=dict(
|
| 130 |
+
type="tool_use", id=b["id"], name=b["name"], input={}))))
|
| 131 |
+
evs.append(("content_block_delta", dict(type="content_block_delta", index=k, delta=dict(
|
| 132 |
+
type="input_json_delta", partial_json=json.dumps(b["input"])))))
|
| 133 |
+
else:
|
| 134 |
+
evs.append(("content_block_start", dict(type="content_block_start", index=k,
|
| 135 |
+
content_block=dict(type="text", text=""))))
|
| 136 |
+
evs.append(("content_block_delta", dict(type="content_block_delta", index=k,
|
| 137 |
+
delta=dict(type="text_delta", text=b["text"]))))
|
| 138 |
+
evs.append(("content_block_stop", dict(type="content_block_stop", index=k)))
|
| 139 |
+
evs.append(("message_delta", dict(type="message_delta", delta=dict(stop_reason=stop, stop_sequence=None),
|
| 140 |
+
usage=dict(output_tokens=5))))
|
| 141 |
+
evs.append(("message_stop", dict(type="message_stop")))
|
| 142 |
+
self.send_sse(h, evs)
|
| 143 |
+
|
| 144 |
+
def message_requests(self):
|
| 145 |
+
return [(n, b) for n, p, b in self.requests if isinstance(b, dict) and p.startswith("/v1/messages")
|
| 146 |
+
and "count_tokens" not in p]
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class FakeResponses(_Base):
|
| 150 |
+
@property
|
| 151 |
+
def base_url(self):
|
| 152 |
+
return f"http://127.0.0.1:{self.port}/v1"
|
| 153 |
+
|
| 154 |
+
def handle(self, h, n, body):
|
| 155 |
+
if not isinstance(body, dict) or "input" not in body:
|
| 156 |
+
h._send(404, b"{}", "application/json")
|
| 157 |
+
return
|
| 158 |
+
items = body.get("input") or []
|
| 159 |
+
i = sum(1 for it in items if isinstance(it, dict) and it.get("type") in
|
| 160 |
+
("custom_tool_call", "function_call") or (isinstance(it, dict) and it.get("type") == "message"
|
| 161 |
+
and it.get("role") == "assistant"))
|
| 162 |
+
steps = self.turn(i)
|
| 163 |
+
out = []
|
| 164 |
+
for j, st in enumerate(steps):
|
| 165 |
+
if st[0] == "exec":
|
| 166 |
+
out.append(dict(type="custom_tool_call", id=f"ctc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}",
|
| 167 |
+
name="exec", status="completed", input=st[1]))
|
| 168 |
+
elif st[0] == "fcall":
|
| 169 |
+
out.append(dict(type="function_call", id=f"fc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}",
|
| 170 |
+
name=st[1], arguments=json.dumps(st[2]), status="completed"))
|
| 171 |
+
elif st[0] == "nscall":
|
| 172 |
+
out.append(dict(type="function_call", id=f"fc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}",
|
| 173 |
+
namespace=st[1], name=st[2], arguments=json.dumps(st[3]), status="completed"))
|
| 174 |
+
else:
|
| 175 |
+
out.append(dict(type="message", id=f"msg_fake_{n}_{j}", role="assistant", status="completed",
|
| 176 |
+
content=[dict(type="output_text", text=st[1], annotations=[])]))
|
| 177 |
+
rid = f"resp_fake_{n}"
|
| 178 |
+
evs = [("response.created", dict(type="response.created", response=dict(id=rid, status="in_progress")))]
|
| 179 |
+
for k, it in enumerate(out):
|
| 180 |
+
evs.append(("response.output_item.done", dict(type="response.output_item.done", output_index=k, item=it)))
|
| 181 |
+
evs.append(("response.completed", dict(type="response.completed", response=dict(
|
| 182 |
+
id=rid, status="completed", output=out, usage=dict(
|
| 183 |
+
input_tokens=100, input_tokens_details=dict(cached_tokens=0), output_tokens=3,
|
| 184 |
+
output_tokens_details=dict(reasoning_tokens=0), total_tokens=103)))))
|
| 185 |
+
self.send_sse(h, evs)
|
| 186 |
+
|
| 187 |
+
def model_requests(self):
|
| 188 |
+
return [(n, b) for n, p, b in self.requests if isinstance(b, dict) and "input" in b]
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/framework_codex.py
ADDED
|
@@ -0,0 +1,542 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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Session.first_message(), Session.tool_specs(),
|
| 4 |
+
and Session.call(name, arguments). This launcher owns isolation, model configuration,
|
| 5 |
+
pins, trajectory collection and audits; framework plugins own their native loop.
|
| 6 |
+
Based on the validated RPent launcher; RPent's historical launcher remains frozen.
|
| 7 |
+
"""
|
| 8 |
+
import hashlib
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import shutil
|
| 12 |
+
import subprocess
|
| 13 |
+
import time
|
| 14 |
+
|
| 15 |
+
from . import contract as C
|
| 16 |
+
from . import pins
|
| 17 |
+
from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info,
|
| 18 |
+
gateway_env, new_run_dir, proxy_env, snapshot_tree)
|
| 19 |
+
from .codex import (AUTH_FILE, Codex, CATALOG_FILE, CATALOGS, DISABLE, EXPECTED_TOP_GENERIC, OFFICIAL_API, codex_bin, model_catalog,
|
| 20 |
+
request_fingerprint, toml_str)
|
| 21 |
+
from .fakeapi import FakeResponses
|
| 22 |
+
from .trajectory import TrajWriter
|
| 23 |
+
|
| 24 |
+
ROOT = C.ROOT
|
| 25 |
+
JAIL_FRAMEWORK_DIR = "/opt/lffjail/hjail/framework"
|
| 26 |
+
BASE_PATH = "/usr/bin:/bin"
|
| 27 |
+
MCP_SERVER = "lff"
|
| 28 |
+
MCP_TOOLS = ["robot", "shell", "view_images"]
|
| 29 |
+
TREE_SKIP = {".git", "__pycache__", ".pytest_cache", ".ruff_cache", ".mypy_cache", "docs", "tests", ".github"}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def tree_sha256(root, skip=TREE_SKIP):
|
| 34 |
+
"""sha256 over (relative path, file sha256 / symlink target) of every file under root, skipping `skip` dirs."""
|
| 35 |
+
h = hashlib.sha256()
|
| 36 |
+
for dp, dn, fn in os.walk(root):
|
| 37 |
+
dn[:] = sorted(d for d in dn if d not in skip)
|
| 38 |
+
for f in sorted(fn):
|
| 39 |
+
if f.endswith(".pyc"):
|
| 40 |
+
continue
|
| 41 |
+
p = os.path.join(dp, f)
|
| 42 |
+
rel = os.path.relpath(p, root)
|
| 43 |
+
if os.path.islink(p):
|
| 44 |
+
h.update(f"L {rel} {os.readlink(p)}\n".encode())
|
| 45 |
+
else:
|
| 46 |
+
h.update(f"F {rel} {C.sha256_file(p)}\n".encode())
|
| 47 |
+
return h.hexdigest()
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def runtime_info(home):
|
| 51 |
+
"""The robot framework runtime: upstream commit, our patch on top, and the tree hash of src + venv."""
|
| 52 |
+
src, venv = os.path.join(home, "src"), os.path.join(home, "venv")
|
| 53 |
+
for d in (src, venv):
|
| 54 |
+
if not os.path.isdir(d):
|
| 55 |
+
raise HarnessRefused(f"robot framework runtime incomplete: {d} missing (run the selected framework setup script under integrations/)")
|
| 56 |
+
|
| 57 |
+
def git(*a):
|
| 58 |
+
r = subprocess.run(["git", "-C", src] + list(a), capture_output=True, text=True, timeout=60)
|
| 59 |
+
return r.stdout.strip() if r.returncode == 0 else None
|
| 60 |
+
commit = git("rev-parse", "HEAD")
|
| 61 |
+
patch = subprocess.run(["git", "-C", src, "diff", "HEAD"], capture_output=True, timeout=60).stdout
|
| 62 |
+
untracked = (git("ls-files", "--others", "--exclude-standard") or "").split()
|
| 63 |
+
return dict(home=home, commit=commit, patch_sha256=hashlib.sha256(patch).hexdigest(),
|
| 64 |
+
untracked=sorted(u for u in untracked if "__pycache__" not in u),
|
| 65 |
+
tree_sha256=hashlib.sha256((tree_sha256(src) + tree_sha256(venv)).encode()).hexdigest())
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def jail_runtime_copy(home, tree):
|
| 69 |
+
"""A verified read-only copy of the runtime under /opt/lffjail/hjail/framework (visible in the jail; /mnt is not)."""
|
| 70 |
+
dst = os.path.join(JAIL_FRAMEWORK_DIR, f"framework-{tree[:12]}")
|
| 71 |
+
stamp = os.path.join(dst, ".tree_sha256")
|
| 72 |
+
if os.path.exists(stamp) and open(stamp).read().strip() == tree:
|
| 73 |
+
return dst
|
| 74 |
+
os.makedirs(JAIL_FRAMEWORK_DIR, mode=0o755, exist_ok=True)
|
| 75 |
+
tmp = dst + ".tmp-" + os.urandom(3).hex()
|
| 76 |
+
shutil.copytree(os.path.join(home, "src"), os.path.join(tmp, "src"), symlinks=True,
|
| 77 |
+
ignore=shutil.ignore_patterns(".git", "__pycache__", "*.pyc"))
|
| 78 |
+
shutil.copytree(os.path.join(home, "venv"), os.path.join(tmp, "venv"), symlinks=True,
|
| 79 |
+
ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
|
| 80 |
+
got = hashlib.sha256((tree_sha256(os.path.join(tmp, "src")) + tree_sha256(os.path.join(tmp, "venv"))).encode()
|
| 81 |
+
).hexdigest()
|
| 82 |
+
if got != tree:
|
| 83 |
+
shutil.rmtree(tmp, ignore_errors=True)
|
| 84 |
+
raise HarnessRefused(f"copy of the robot framework runtime does not match its tree hash ({got[:12]} != {tree[:12]})")
|
| 85 |
+
for dp, dn, fn in os.walk(tmp):
|
| 86 |
+
os.chmod(dp, 0o755)
|
| 87 |
+
for f in fn:
|
| 88 |
+
p = os.path.join(dp, f)
|
| 89 |
+
if not os.path.islink(p):
|
| 90 |
+
os.chmod(p, os.stat(p).st_mode | 0o444)
|
| 91 |
+
with open(os.path.join(tmp, ".tree_sha256"), "w") as f:
|
| 92 |
+
f.write(tree)
|
| 93 |
+
if os.path.exists(dst):
|
| 94 |
+
shutil.rmtree(dst)
|
| 95 |
+
os.rename(tmp, dst)
|
| 96 |
+
return dst
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def codex_overrides(effort, catalog_path):
|
| 100 |
+
"""The main table's Codex configuration (lffbench/harnesses/codex.py Codex.config_args / --disable), as -c
|
| 101 |
+
overrides for robot framework's planner; the provider and the MCP server URL are robot framework's own (CODEX_BASE_URL, in-process)."""
|
| 102 |
+
return (["model_reasoning_effort=" + toml_str(effort),
|
| 103 |
+
"include_permissions_instructions=false", "include_environment_context=false",
|
| 104 |
+
"include_collaboration_mode_instructions=false", "skills.include_instructions=false",
|
| 105 |
+
"skills.bundled.enabled=false", 'web_search="disabled"',
|
| 106 |
+
f"mcp_servers.{MCP_SERVER}.enabled_tools=" + json.dumps(MCP_TOOLS),
|
| 107 |
+
f'mcp_servers.{MCP_SERVER}.default_tools_approval_mode="approve"',
|
| 108 |
+
f"mcp_servers.{MCP_SERVER}.required=true", f"mcp_servers.{MCP_SERVER}.startup_timeout_sec=60",
|
| 109 |
+
f"mcp_servers.{MCP_SERVER}.tool_timeout_sec=900",
|
| 110 |
+
"model_catalog_json=" + toml_str(catalog_path)]
|
| 111 |
+
+ [f"features.{f}=false" for f in DISABLE])
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _items(stream_path):
|
| 115 |
+
"""Codex app-server notifications of one robot framework session (robot framework writes them as JSONL)."""
|
| 116 |
+
out = []
|
| 117 |
+
if not os.path.exists(stream_path):
|
| 118 |
+
return out
|
| 119 |
+
for line in open(stream_path, encoding="utf-8", errors="replace"):
|
| 120 |
+
try:
|
| 121 |
+
out.append(json.loads(line))
|
| 122 |
+
except ValueError:
|
| 123 |
+
continue
|
| 124 |
+
return out
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _item_of(ev):
|
| 128 |
+
it = (ev.get("payload") or {}).get("item") or {}
|
| 129 |
+
return it.get("root", it) if isinstance(it, dict) else {}
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class RobotFrameworkCodex(HarnessAdapter):
|
| 133 |
+
name = "framework_codex"
|
| 134 |
+
runtime_home = "/nonexistent"
|
| 135 |
+
runtime_module = "lff_integration.run"
|
| 136 |
+
default_steps = 500
|
| 137 |
+
uses_mcp = False
|
| 138 |
+
uses_gateway = True
|
| 139 |
+
can_resume = False
|
| 140 |
+
clean_dirs = ("home", "codex_home", "tmp", "out")
|
| 141 |
+
clean_allowed = {"codex_home": (CATALOG_FILE,)}
|
| 142 |
+
ancestor_files = ("AGENTS.md", "AGENTS.override.md", ".codex")
|
| 143 |
+
capabilities = dict(
|
| 144 |
+
only_benchmark_tools=Cap("partial", "preflight", "Codex generic catalog (as the main table): our 3 tools as "
|
| 145 |
+
"mcp__lff functions + residual resource×3 / request_user_input; robot framework registers "
|
| 146 |
+
"no tool of its own (no file tools, no finish)"),
|
| 147 |
+
images_reach_model=Cap("yes", "probe", "gateway content blocks preserved by the framework bridge, "
|
| 148 |
+
"JPEG with its own MIME type"),
|
| 149 |
+
non_persistent_session=Cap("yes", "probe", "robot framework's threads only in the one-time CODEX_HOME, removed after the "
|
| 150 |
+
"run; no preloaded or cross-episode framework memory"),
|
| 151 |
+
pinned_version=Cap("yes", "launch", "codex binary sha256 + robot framework commit / patch / tree hash (src + venv) in "
|
| 152 |
+
"harness.json; pin per version and tree"),
|
| 153 |
+
machine_readable_events=Cap("yes", "stream", "Codex app-server notifications per robot framework session "
|
| 154 |
+
"(codex.out.stream.jsonl) + robot framework run.json"),
|
| 155 |
+
tool_calls_logged=Cap("yes", "stream", "mcpToolCall items + gateway_transcript (named framework face) + events.jsonl"),
|
| 156 |
+
model_and_effort=Cap("yes", "preflight", "model and effort in the request checked"),
|
| 157 |
+
persistent_memory=Cap("absent", "probe", "memories feature off; empty one-time CODEX_HOME; robot framework memory not "
|
| 158 |
+
"constructed"),
|
| 159 |
+
instruction_file_injection=Cap("absent", "probe", "project_doc_max_bytes=0, empty CODEX_HOME, no skills"),
|
| 160 |
+
web_access=Cap("absent", "preflight", "web_search disabled (not in the tool list)"),
|
| 161 |
+
host_file_read=Cap("absent", "preflight", "no file tools; the only shell is the gateway's jailed shell"),
|
| 162 |
+
builtin_shell=Cap("absent", "preflight", "shell_tool and unified_exec disabled (not in the tool list)"),
|
| 163 |
+
subagent_delegation=Cap("absent", "preflight", "multi_agent disabled; no collaboration tools in the request"),
|
| 164 |
+
background_execution=Cap("absent", "preflight", "no background tool in the request"),
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False,
|
| 168 |
+
jail=False, auth="apikey", catalog="generic", sessions=1, attempts_per_session=0, max_turns=500,
|
| 169 |
+
home=None, provider=None, auth_home=None):
|
| 170 |
+
"""Common controlled Codex SDK launcher.
|
| 171 |
+
|
| 172 |
+
The plugin entrypoint interprets its declared loop options. For SenseNova,
|
| 173 |
+
max_turns is the upstream SDK-step limit, not a provider-response count.
|
| 174 |
+
Robot commands, simulation time and tool budgets are always server-owned.
|
| 175 |
+
"""
|
| 176 |
+
if auth not in ("apikey", "chatgpt"):
|
| 177 |
+
raise ValueError("framework_codex auth must be apikey or chatgpt")
|
| 178 |
+
if catalog not in CATALOGS:
|
| 179 |
+
raise ValueError(f"catalog must be one of {CATALOGS}")
|
| 180 |
+
self.auth, self.catalog = auth, catalog
|
| 181 |
+
self._auth_manager = Codex(auth=auth, auth_home=auth_home, api_env=api_env, base_url=base_url, catalog=catalog)
|
| 182 |
+
self.api_env = self._auth_manager.api_env
|
| 183 |
+
self.base_url = self._auth_manager.base_url
|
| 184 |
+
self.clean_allowed = {"codex_home": ((AUTH_FILE,) if auth == "chatgpt" else ()) + (CATALOG_FILE,)}
|
| 185 |
+
self.timeout_s, self.pins_dir, self.allow_unpinned = timeout_s, pins_dir, allow_unpinned
|
| 186 |
+
self.sessions, self.attempts_per_session, self.max_turns = int(sessions), int(attempts_per_session), \
|
| 187 |
+
int(max_turns)
|
| 188 |
+
self.home = home or os.environ.get("LFF_FRAMEWORK_HOME") or self.runtime_home
|
| 189 |
+
self.proxy = proxy_env()
|
| 190 |
+
self._version = None
|
| 191 |
+
self._runtime = None
|
| 192 |
+
self.runtime_dir = self.home
|
| 193 |
+
if jail:
|
| 194 |
+
from .jail import HarnessJail
|
| 195 |
+
self.jail = HarnessJail(codex_bin(), proc="static")
|
| 196 |
+
|
| 197 |
+
# ------------------------------------------------------------------------------------------------ identity
|
| 198 |
+
def runtime(self):
|
| 199 |
+
if self._runtime is None:
|
| 200 |
+
self._runtime = runtime_info(self.home)
|
| 201 |
+
if self.jail is not None:
|
| 202 |
+
self.runtime_dir = jail_runtime_copy(self.home, self._runtime["tree_sha256"])
|
| 203 |
+
return self._runtime
|
| 204 |
+
|
| 205 |
+
def version(self):
|
| 206 |
+
if self._version is None:
|
| 207 |
+
b = codex_bin()
|
| 208 |
+
out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent",
|
| 209 |
+
CODEX_HOME="/nonexistent"),
|
| 210 |
+
capture_output=True, text=True, timeout=60)
|
| 211 |
+
v = (out.stdout.strip().split() or ["?"])[-1]
|
| 212 |
+
rt = self.runtime()
|
| 213 |
+
self._version = dict(version=v, binary=binary_info(b),
|
| 214 |
+
framework=dict(commit=rt["commit"], patch_sha256=rt["patch_sha256"],
|
| 215 |
+
tree_sha256=rt["tree_sha256"], untracked=rt["untracked"]))
|
| 216 |
+
return self._version
|
| 217 |
+
|
| 218 |
+
def pin_key(self, ep):
|
| 219 |
+
v = self.version()
|
| 220 |
+
mode = "" if self.auth == "apikey" else "-chatgpt"
|
| 221 |
+
name = f"{self.name}{mode}-{self.catalog}-{v['framework']['tree_sha256'][:12]}"
|
| 222 |
+
return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
|
| 223 |
+
|
| 224 |
+
def anchor_pin_key(self, ep):
|
| 225 |
+
"""The main table's codex pin for the same model / effort (apikey, same catalog)."""
|
| 226 |
+
v = self.version()
|
| 227 |
+
name = "codex" + ("" if self.auth == "apikey" else "-chatgpt") + ("" if self.catalog == "native" else f"-{self.catalog}")
|
| 228 |
+
return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
|
| 229 |
+
|
| 230 |
+
def auth_info(self):
|
| 231 |
+
if self.auth == "chatgpt":
|
| 232 |
+
return self._auth_manager.auth_info()
|
| 233 |
+
return dict(mode="apikey", credential_var="CODEX_API_KEY", credential_set=bool(self.api_env.get(
|
| 234 |
+
"OPENAI_API_KEY")), keys=["CODEX_API_KEY"])
|
| 235 |
+
|
| 236 |
+
def config_info(self):
|
| 237 |
+
return dict(auth=self.auth, catalog=self.catalog, sessions=self.sessions, attempts_per_session=self.attempts_per_session,
|
| 238 |
+
max_turns=self.max_turns, framework=self.version()["framework"])
|
| 239 |
+
|
| 240 |
+
# ------------------------------------------------------------------------------------------------ prepare
|
| 241 |
+
def _state_dirs(self, hexname=None):
|
| 242 |
+
root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate")
|
| 243 |
+
os.makedirs(root, exist_ok=True)
|
| 244 |
+
state = dict(state=root, **{k: os.path.join(root, k) for k in ("home", "codex_home", "tmp", "out")})
|
| 245 |
+
for k in ("home", "codex_home", "tmp", "out"):
|
| 246 |
+
os.makedirs(state[k], exist_ok=True)
|
| 247 |
+
return state
|
| 248 |
+
|
| 249 |
+
def _install_catalog(self, codex_home, ep):
|
| 250 |
+
cat, src = model_catalog(self.catalog, self.version()["version"], ep.model, None, ep.effort)
|
| 251 |
+
path = os.path.join(codex_home, CATALOG_FILE)
|
| 252 |
+
with open(path, "w") as f:
|
| 253 |
+
json.dump(cat, f)
|
| 254 |
+
return path, C.sha256_file(path), os.path.relpath(src, ROOT)
|
| 255 |
+
|
| 256 |
+
def argv(self, ep, out_dir, sessions=None, preflight=False):
|
| 257 |
+
py = os.path.join(self.runtime_dir, "venv", "bin", "python")
|
| 258 |
+
return [py, "-m", self.runtime_module, "--model", ep.model, "--effort", ep.effort, "--out", out_dir,
|
| 259 |
+
"--sessions", str(sessions or self.sessions), "--attempts-per-session", str(self.attempts_per_session),
|
| 260 |
+
"--max-turns", str(self.max_turns), "--timeout-s", str(int(self.timeout_s) - 60)] \
|
| 261 |
+
+ (["--no-continue"] if preflight else [])
|
| 262 |
+
|
| 263 |
+
def env(self, state, ep, base_url, work):
|
| 264 |
+
e = dict(PATH=BASE_PATH, HOME=state["home"], TMPDIR=state["tmp"], CODEX_HOME=state["codex_home"],
|
| 265 |
+
CODEX_BIN=(self.jail.binary_jailed if self.jail is not None else codex_bin()),
|
| 266 |
+
CODEX_BASE_URL=base_url, FRAMEWORK_CODEX_SANDBOX="read_only", FRAMEWORK_MCP_SERVER_NAME=MCP_SERVER,
|
| 267 |
+
FRAMEWORK_CODEX_CONFIG_OVERRIDES=json.dumps(codex_overrides(
|
| 268 |
+
ep.effort, os.path.join(state["codex_home"], CATALOG_FILE))),
|
| 269 |
+
FRAMEWORK_REPO_ROOT=work, LFF_FRAMEWORK_FACE=self.name, PYTHONPATH=os.path.join(self.runtime_dir, "src"),
|
| 270 |
+
PYTHONDONTWRITEBYTECODE="1", PYTHONUNBUFFERED="1", LANG="C.UTF-8")
|
| 271 |
+
if self.auth == "chatgpt":
|
| 272 |
+
# The native API provider declares env_key. Codex app-server still requires that
|
| 273 |
+
# variable even with requires_openai_auth=true, so select a separate provider
|
| 274 |
+
# with no env_key. Do not inject a dummy key or modify the upstream runtime.
|
| 275 |
+
provider_id = "lffsubscription"
|
| 276 |
+
overrides = json.loads(e["FRAMEWORK_CODEX_CONFIG_OVERRIDES"])
|
| 277 |
+
overrides += ["model_provider=" + toml_str(provider_id),
|
| 278 |
+
f"model_providers.{provider_id}.name=" + toml_str(provider_id),
|
| 279 |
+
f"model_providers.{provider_id}.wire_api=\"responses\"",
|
| 280 |
+
f"model_providers.{provider_id}.base_url=" + toml_str(base_url),
|
| 281 |
+
f"model_providers.{provider_id}.requires_openai_auth=true"]
|
| 282 |
+
e["FRAMEWORK_CODEX_CONFIG_OVERRIDES"] = json.dumps(overrides)
|
| 283 |
+
e.update(self.proxy)
|
| 284 |
+
if self.api_env.get("OPENAI_API_KEY"):
|
| 285 |
+
e["CODEX_API_KEY"] = self.api_env["OPENAI_API_KEY"]
|
| 286 |
+
return e
|
| 287 |
+
|
| 288 |
+
def prepare(self, ep, first_message, reuse_state=None):
|
| 289 |
+
self.version()
|
| 290 |
+
work = new_run_dir("/tmp/lffrun")
|
| 291 |
+
state = reuse_state or self._state_dirs(os.path.basename(work))
|
| 292 |
+
if self.jail is not None:
|
| 293 |
+
self.jail.stderr_dir = ep.log_dir
|
| 294 |
+
if not reuse_state and os.listdir(state["codex_home"]):
|
| 295 |
+
raise HarnessRefused("CODEX_HOME is not empty")
|
| 296 |
+
cat_path, cat_sha, cat_src = self._install_catalog(state["codex_home"], ep)
|
| 297 |
+
return LaunchSpec(argv=self.argv(ep, state["out"]), env=self.env(state, ep, self.base_url, work), cwd=work,
|
| 298 |
+
run_dir=work, state_dirs=state, first_message=first_message,
|
| 299 |
+
stdout_path=os.path.join(ep.log_dir, "framework_stdout.txt"),
|
| 300 |
+
stderr_path=os.path.join(ep.log_dir, "framework_stderr.txt"),
|
| 301 |
+
config_files=dict(model_catalog_json=dict(path=cat_path, sha256=cat_sha, source=cat_src,
|
| 302 |
+
catalog=self.catalog, code_mode=False)),
|
| 303 |
+
timeout_s=self.timeout_s)
|
| 304 |
+
|
| 305 |
+
def config_sha256(self, spec, ep):
|
| 306 |
+
argv = [a.replace(spec.state_dirs["out"], "<OUT>").replace(self.runtime_dir, "<FRAMEWORK>")
|
| 307 |
+
for a in spec.argv]
|
| 308 |
+
hidden = ("HOME", "TMPDIR", "CODEX_HOME", "CODEX_BIN", "CODEX_API_KEY", "FRAMEWORK_REPO_ROOT", "PYTHONPATH",
|
| 309 |
+
"LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") + PROXY_KEYS + NO_PROXY_KEYS
|
| 310 |
+
env = {k: v for k, v in spec.env.items() if k not in hidden}
|
| 311 |
+
env["FRAMEWORK_CODEX_CONFIG_OVERRIDES"] = env.get("FRAMEWORK_CODEX_CONFIG_OVERRIDES", "").replace(
|
| 312 |
+
spec.state_dirs["codex_home"], "<CODEX_HOME>")
|
| 313 |
+
cat = (spec.config_files.get("model_catalog_json") or {}).get("sha256")
|
| 314 |
+
return C.sha256_json(dict(argv=argv, env=env, model_catalog_sha256=cat,
|
| 315 |
+
framework_tree_sha256=self.version()["framework"]["tree_sha256"]))
|
| 316 |
+
|
| 317 |
+
# ------------------------------------------------------------------------------------------------ launch
|
| 318 |
+
def launch(self, spec, ep, skip_preflight=False):
|
| 319 |
+
"""harness_run starts the gateway after prepare(), right before launch: hand its address to the process."""
|
| 320 |
+
self._auth_manager._install_auth(spec.state_dirs["codex_home"])
|
| 321 |
+
spec.env.update(gateway_env(ep.log_dir))
|
| 322 |
+
return super().launch(spec, ep, skip_preflight=skip_preflight)
|
| 323 |
+
|
| 324 |
+
def cleanup(self, spec):
|
| 325 |
+
self._auth_manager._sync_auth_back(spec.state_dirs.get("codex_home", ""))
|
| 326 |
+
super().cleanup(spec)
|
| 327 |
+
|
| 328 |
+
def preflight(self, spec, ep, record_dir=None):
|
| 329 |
+
"""The same framework process, one session, against a local fake Responses server that answers with text
|
| 330 |
+
only: no tool call reaches the gateway. Checks the first request (tools, developer message, parameters,
|
| 331 |
+
sandbox, robot framework's prefix + our first message) against the pins."""
|
| 332 |
+
t0 = time.time()
|
| 333 |
+
fake = FakeResponses([[("text", "preflight ok")]], record_dir=record_dir).start()
|
| 334 |
+
pre = self._state_dirs()
|
| 335 |
+
try:
|
| 336 |
+
self._auth_manager._install_auth(pre["codex_home"])
|
| 337 |
+
self._install_catalog(pre["codex_home"], ep)
|
| 338 |
+
env = self.env(pre, ep, fake.base_url, spec.cwd)
|
| 339 |
+
if self.auth == "apikey":
|
| 340 |
+
env["CODEX_API_KEY"] = "sk-preflight-not-a-key"
|
| 341 |
+
env.update({k: spec.env[k] for k in ("LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") if k in spec.env})
|
| 342 |
+
argv = self.argv(ep, pre["out"], sessions=1, preflight=True) # no status call on the episode
|
| 343 |
+
r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd,
|
| 344 |
+
stdin=subprocess.DEVNULL, capture_output=True, timeout=300)
|
| 345 |
+
reqs = fake.model_requests()
|
| 346 |
+
if not reqs:
|
| 347 |
+
# Native planners may record failures only in run.json, with empty stdout/stderr.
|
| 348 |
+
record = os.path.join(pre["out"], "run.json")
|
| 349 |
+
detail = ""
|
| 350 |
+
if os.path.isfile(record):
|
| 351 |
+
with open(record) as f:
|
| 352 |
+
failed_run = json.load(f)
|
| 353 |
+
detail = "; ".join(str(s.get("error")) for s in failed_run.get("sessions", []) if s.get("error"))
|
| 354 |
+
raise HarnessRefused(f"preflight: no model request (rc={r.returncode}): "
|
| 355 |
+
f"{(r.stdout + r.stderr).decode('utf-8', 'replace')[-1200:]} {detail[-1200:]}")
|
| 356 |
+
body = reqs[0][1]
|
| 357 |
+
fp, problems = request_fingerprint(body, spec.cwd, spec.first_message, EXPECTED_TOP_GENERIC)
|
| 358 |
+
problems = [p for p in problems if not p.startswith("user input is not exactly our first message")]
|
| 359 |
+
users = [c.get("text") for it in body.get("input") or [] if it.get("type") == "message"
|
| 360 |
+
and it.get("role") == "user" for c in it.get("content") or []]
|
| 361 |
+
prefix = None
|
| 362 |
+
if len(users) != 1 or not users[0].endswith(spec.first_message):
|
| 363 |
+
problems.append(f"the first user message does not end with our first message ({len(users)} blocks)")
|
| 364 |
+
else:
|
| 365 |
+
prefix = users[0][:-len(spec.first_message)]
|
| 366 |
+
effort = (fp["params"].get("reasoning") or {}).get("effort")
|
| 367 |
+
if effort != ep.effort:
|
| 368 |
+
problems.append(f"reasoning.effort in request {effort!r} != {ep.effort!r}")
|
| 369 |
+
if fp["params"].get("model") != ep.model:
|
| 370 |
+
problems.append(f"model in request {fp['params'].get('model')!r} != {ep.model!r}")
|
| 371 |
+
if os.listdir(spec.cwd):
|
| 372 |
+
problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}")
|
| 373 |
+
mid_sha = C.sha256_json(fp)
|
| 374 |
+
full = dict(middle=fp, framework_prefix=prefix)
|
| 375 |
+
fp_sha = C.sha256_json(full)
|
| 376 |
+
anchor = pins.load(self.anchor_pin_key(ep), self.pins_dir)
|
| 377 |
+
out = dict(fingerprint_sha256=fp_sha, middle_fingerprint_sha256=mid_sha,
|
| 378 |
+
framework_prefix_sha256=C.sha256_text(prefix) if prefix is not None else None,
|
| 379 |
+
framework_prefix_chars=len(prefix) if prefix is not None else None,
|
| 380 |
+
developer_chars=fp["developer_chars"], n_requests=len(reqs),
|
| 381 |
+
top_tools=[t["name"] for t in fp["tools"]], catalog=self.catalog, effort_in_request=effort,
|
| 382 |
+
model_in_request=fp["params"].get("model"), sandbox=fp["sandbox"],
|
| 383 |
+
dt_s=round(time.time() - t0, 1), problems=problems,
|
| 384 |
+
anchor_pin=anchor and dict(key=anchor["key"], fingerprint_sha256=anchor["fingerprint_sha256"]))
|
| 385 |
+
if anchor is None:
|
| 386 |
+
out["anchor_status"] = "no main-table pin for this model / effort"
|
| 387 |
+
elif anchor["fingerprint_sha256"] != mid_sha:
|
| 388 |
+
problems.append(f"Codex request {mid_sha[:12]} != main-table pin {anchor['fingerprint_sha256'][:12]} "
|
| 389 |
+
f"({anchor['key']}): the middle layer is not the main table's")
|
| 390 |
+
else:
|
| 391 |
+
out["anchor_status"] = "match"
|
| 392 |
+
pin = pins.load(self.pin_key(ep), self.pins_dir)
|
| 393 |
+
out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"])
|
| 394 |
+
out["fingerprint"] = full
|
| 395 |
+
if problems:
|
| 396 |
+
raise HarnessRefused("preflight: " + "; ".join(problems))
|
| 397 |
+
if pin is None:
|
| 398 |
+
if not self.allow_unpinned:
|
| 399 |
+
raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck "
|
| 400 |
+
f"with --write-pins after the self-check passes)")
|
| 401 |
+
out["pin_status"] = "unpinned (allowed)"
|
| 402 |
+
elif pin["fingerprint_sha256"] != fp_sha:
|
| 403 |
+
raise HarnessRefused(f"preflight: fingerprint {fp_sha[:12]} != pinned {pin['fingerprint_sha256'][:12]} "
|
| 404 |
+
f"({pin['key']})")
|
| 405 |
+
else:
|
| 406 |
+
out["pin_status"] = "match"
|
| 407 |
+
return out
|
| 408 |
+
finally:
|
| 409 |
+
fake.stop()
|
| 410 |
+
self._auth_manager._sync_auth_back(pre["codex_home"])
|
| 411 |
+
shutil.rmtree(pre["state"], ignore_errors=True)
|
| 412 |
+
|
| 413 |
+
# ------------------------------------------------------------------------------------------------ collect
|
| 414 |
+
def collect(self, h):
|
| 415 |
+
spec, ep = h.spec, h.ep
|
| 416 |
+
dst = os.path.join(ep.log_dir, "framework")
|
| 417 |
+
if os.path.isdir(spec.state_dirs["out"]):
|
| 418 |
+
shutil.copytree(spec.state_dirs["out"], dst, dirs_exist_ok=True)
|
| 419 |
+
run = {}
|
| 420 |
+
if os.path.exists(os.path.join(dst, "run.json")):
|
| 421 |
+
run = json.load(open(os.path.join(dst, "run.json")))
|
| 422 |
+
tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
|
| 423 |
+
usage = dict(input=0, cached=0, output=0, reasoning=0)
|
| 424 |
+
items, threads, errors = [], [], []
|
| 425 |
+
for sdir in sorted(os.listdir(os.path.join(dst, "sessions"))) if os.path.isdir(os.path.join(dst, "sessions")) \
|
| 426 |
+
else []:
|
| 427 |
+
last = None
|
| 428 |
+
for ev in _items(os.path.join(dst, "sessions", sdir, "codex.out.stream.jsonl")):
|
| 429 |
+
m = ev.get("method") or ev.get("type")
|
| 430 |
+
p = ev.get("payload") or {}
|
| 431 |
+
if m == "thread/tokenUsage/updated":
|
| 432 |
+
last = (p.get("token_usage") or {}).get("total") or last
|
| 433 |
+
if p.get("thread_id") and p["thread_id"] not in threads:
|
| 434 |
+
threads.append(p["thread_id"])
|
| 435 |
+
elif m in ("error", "fatal", "timeout"):
|
| 436 |
+
errors.append(ev)
|
| 437 |
+
elif m == "item/completed":
|
| 438 |
+
it = _item_of(ev)
|
| 439 |
+
t = it.get("type")
|
| 440 |
+
items.append(t)
|
| 441 |
+
if t == "agentMessage":
|
| 442 |
+
tw.add_step("agent", message=it.get("text", ""))
|
| 443 |
+
elif t == "reasoning":
|
| 444 |
+
tw.add_step("agent", reasoning=json.dumps(it.get("summary") or it.get("content") or ""))
|
| 445 |
+
elif t in ("mcpToolCall", "dynamicToolCall", "commandExecution", "fileChange"):
|
| 446 |
+
name = it.get("tool") or t
|
| 447 |
+
tw.add_step("agent", tool_calls=[dict(tool_call_id=it.get("id"), function_name=name,
|
| 448 |
+
native_name=f"{it.get('server', '')}.{name}",
|
| 449 |
+
item_type=t, arguments=it.get("arguments"),
|
| 450 |
+
session=sdir)])
|
| 451 |
+
res = it.get("result") or {}
|
| 452 |
+
texts = [c.get("text", "") for c in res.get("content") or [] if c.get("type") == "text"]
|
| 453 |
+
imgs = sum(1 for c in res.get("content") or [] if c.get("type") == "image")
|
| 454 |
+
tw.add_result(it.get("id"), "\n".join(texts) if texts else json.dumps(it.get("error")),
|
| 455 |
+
bool(it.get("error")) or it.get("status") == "failed", imgs)
|
| 456 |
+
if last:
|
| 457 |
+
usage["input"] += last.get("input_tokens") or 0
|
| 458 |
+
usage["cached"] += last.get("cached_input_tokens") or 0
|
| 459 |
+
usage["output"] += last.get("output_tokens") or 0
|
| 460 |
+
usage["reasoning"] += last.get("reasoning_output_tokens") or 0
|
| 461 |
+
# Framework close-out uses the same counted gateway shell, outside
|
| 462 |
+
# the model stream. Keep it visible in trajectories and tool totals.
|
| 463 |
+
session_record = next((s for s in run.get("sessions", [])
|
| 464 |
+
if sdir == f"session_{s['number']:03d}"), {})
|
| 465 |
+
handoff = session_record.get("handoff") or {}
|
| 466 |
+
if handoff:
|
| 467 |
+
call_id = f"framework-handoff-{sdir}"
|
| 468 |
+
tw.add_step("framework", tool_calls=[dict(
|
| 469 |
+
tool_call_id=call_id, function_name="shell", native_name=f"{MCP_SERVER}.shell",
|
| 470 |
+
item_type="frameworkToolCall", arguments=handoff["arguments"], session=sdir)])
|
| 471 |
+
tw.add_result(call_id, "\n".join(c.get("text", "") for c in handoff["content"]
|
| 472 |
+
if c.get("type") == "text"))
|
| 473 |
+
v = self.version()
|
| 474 |
+
tw.set_header(session_id=",".join(threads), source="framework/sessions/*/codex.out.stream.jsonl",
|
| 475 |
+
agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort,
|
| 476 |
+
framework=v["framework"]), tools=EXPECTED_TOP_GENERIC)
|
| 477 |
+
tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], item_types=sorted(set(items)),
|
| 478 |
+
run={k: run.get(k) for k in ("stop", "finished",
|
| 479 |
+
"attempts_failed", "tool_calls")},
|
| 480 |
+
sessions=len(run.get("sessions") or [])),
|
| 481 |
+
total_prompt_tokens=usage["input"], total_completion_tokens=usage["output"],
|
| 482 |
+
total_cached_tokens=usage["cached"], total_cost_usd=None, reasoning_tokens=usage["reasoning"])
|
| 483 |
+
tw.write()
|
| 484 |
+
h.info.update(items=items, traj=tw, threads=threads, errors=errors, run=run)
|
| 485 |
+
return tw
|
| 486 |
+
|
| 487 |
+
# ------------------------------------------------------------------------------------------------ audit
|
| 488 |
+
def audit(self, h):
|
| 489 |
+
spec, ep = h.spec, h.ep
|
| 490 |
+
v, notes = [], []
|
| 491 |
+
items = h.info.get("items") or []
|
| 492 |
+
bad = sorted({i for i in items if i not in ("userMessage", "agentMessage", "reasoning", "mcpToolCall",
|
| 493 |
+
"plan", "hookPrompt")})
|
| 494 |
+
if bad:
|
| 495 |
+
v.append(f"items other than messages / reasoning / MCP calls: {bad}")
|
| 496 |
+
residual = []
|
| 497 |
+
tw = h.info.get("traj")
|
| 498 |
+
for st in (tw.steps if tw else []):
|
| 499 |
+
for tc in st["tool_calls"]:
|
| 500 |
+
if tc["native_name"] == f"{MCP_SERVER}.{tc['function_name']}" and tc["function_name"] in MCP_TOOLS:
|
| 501 |
+
continue
|
| 502 |
+
if tc["function_name"] in ("list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"):
|
| 503 |
+
residual.append(tc["function_name"])
|
| 504 |
+
else:
|
| 505 |
+
v.append(f"unexpected tool call {tc['native_name']}")
|
| 506 |
+
if residual:
|
| 507 |
+
notes.append(f"residual MCP-resource tool calls (empty): {residual}")
|
| 508 |
+
if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env):
|
| 509 |
+
v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}")
|
| 510 |
+
run = h.info.get("run") or {}
|
| 511 |
+
nsess = len(run.get("sessions") or [])
|
| 512 |
+
if len(h.info.get("threads") or []) > max(1, nsess):
|
| 513 |
+
v.append(f"{len(h.info['threads'])} Codex threads for {nsess} robot framework sessions")
|
| 514 |
+
if nsess > 1:
|
| 515 |
+
notes.append(f"{nsess} robot framework sessions (handoff after a session ended before the episode was over)")
|
| 516 |
+
if run.get("stop") not in (None, "episode over"):
|
| 517 |
+
notes.append(f"robot framework stopped: {run.get('stop')}")
|
| 518 |
+
left = dict(codex_home=snapshot_tree(spec.state_dirs["codex_home"]), home=snapshot_tree(spec.state_dirs["home"]),
|
| 519 |
+
work=snapshot_tree(spec.cwd))
|
| 520 |
+
if left["work"]:
|
| 521 |
+
v.append(f"files in the work dir: {left['work']}")
|
| 522 |
+
foreign = [f for f in left["codex_home"] if f.startswith(("sessions/", "archived_sessions/"))
|
| 523 |
+
and not any(t in f for t in (h.info.get("threads") or []))]
|
| 524 |
+
if foreign:
|
| 525 |
+
v.append(f"session files other than this run's threads: {foreign}")
|
| 526 |
+
gt = os.path.join(ep.log_dir, "gateway_transcript.jsonl")
|
| 527 |
+
faces = set()
|
| 528 |
+
if os.path.exists(gt):
|
| 529 |
+
for line in open(gt):
|
| 530 |
+
try:
|
| 531 |
+
d = json.loads(line)
|
| 532 |
+
except ValueError:
|
| 533 |
+
continue
|
| 534 |
+
if d.get("ev") == "tool" and d.get("face"):
|
| 535 |
+
faces.add(d["face"])
|
| 536 |
+
if faces - {self.name}:
|
| 537 |
+
v.append(f"gateway calls from other access paths: {sorted(faces)}")
|
| 538 |
+
out = dict(harness=self.name, violations=v, notes=notes, files_left=left, gateway_faces=sorted(faces),
|
| 539 |
+
item_types=sorted(set(items)), errors=h.info.get("errors"), run_stop=run.get("stop"), ok=not v)
|
| 540 |
+
with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
|
| 541 |
+
json.dump(out, f, indent=1)
|
| 542 |
+
return out
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_2.1.267_0399c793ff571d59_claude-opus-5-5_high.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "claude_code|2.1.267|0399c793ff571d59|claude-opus-5-5|high",
|
| 3 |
+
"fingerprint_sha256": "ba0025718a7a41033ee10a5d00cf9e4fb1c6eff7964f25169f9be4141839cc1f",
|
| 4 |
+
"written": "2026-10-20 02:16:03",
|
| 5 |
+
"summary": {
|
| 6 |
+
"system_chars": 182,
|
| 7 |
+
"tools": [
|
| 8 |
+
"mcp__lff__robot",
|
| 9 |
+
"mcp__lff__shell",
|
| 10 |
+
"mcp__lff__view_images"
|
| 11 |
+
],
|
| 12 |
+
"effort_in_request": "high",
|
| 13 |
+
"model_in_request": "claude-opus-5-5"
|
| 14 |
+
}
|
| 15 |
+
}
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_claude-opus-5-5_high.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "claude_code_full|2.1.267|0399c793ff571d59|claude-opus-5-5|high",
|
| 3 |
+
"fingerprint_sha256": "06d6245468d20e3550a7ea4b8b4e7d9eda296ae16915dffa1b5bd7d12066efa6",
|
| 4 |
+
"written": "2026-10-13 04:12:41",
|
| 5 |
+
"summary": {
|
| 6 |
+
"system_chars": 6048,
|
| 7 |
+
"tools": [
|
| 8 |
+
"mcp__lff__robot",
|
| 9 |
+
"mcp__lff__shell",
|
| 10 |
+
"mcp__lff__view_images"
|
| 11 |
+
],
|
| 12 |
+
"effort_in_request": "high",
|
| 13 |
+
"model_in_request": "claude-opus-5-5"
|
| 14 |
+
}
|
| 15 |
+
}
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/codex-generic_0.163.0_399ff69c431c066e_deepseek-v4.1-flash_high.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "codex-generic|0.163.0|399ff69c431c066e|deepseek-v4.1-flash|high",
|
| 3 |
+
"fingerprint_sha256": "52d7de20832981196514c20e91635e50a2dc6241fa45a1bbfd863d08dc8cc740",
|
| 4 |
+
"written": "2026-10-29 16:15:13",
|
| 5 |
+
"summary": {
|
| 6 |
+
"developer_chars": 16979,
|
| 7 |
+
"top_tools": [
|
| 8 |
+
"list_mcp_resource_templates",
|
| 9 |
+
"list_mcp_resources",
|
| 10 |
+
"mcp__lff.robot",
|
| 11 |
+
"mcp__lff.shell",
|
| 12 |
+
"mcp__lff.view_images",
|
| 13 |
+
"read_mcp_resource",
|
| 14 |
+
"request_user_input"
|
| 15 |
+
],
|
| 16 |
+
"effort_in_request": "high",
|
| 17 |
+
"model_in_request": "deepseek-v4.1-flash",
|
| 18 |
+
"sandbox": {
|
| 19 |
+
"sandbox": "seccomp",
|
| 20 |
+
"sandbox_mode": "read-only"
|
| 21 |
+
}
|
| 22 |
+
}
|
| 23 |
+
}
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/codex_0.156.0_78a11f06e0a2dda4_gpt-6-astra_high.json
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "codex|0.156.0|78a11f06e0a2dda4|gpt-6-astra|high",
|
| 3 |
+
"fingerprint_sha256": "e999df1acbc0c137d1922832262b7b326df0ac8240b9647761158a1c368486c2",
|
| 4 |
+
"written": "2026-10-13 04:13:13",
|
| 5 |
+
"summary": {
|
| 6 |
+
"developer_chars": 23961,
|
| 7 |
+
"top_tools": [
|
| 8 |
+
"collaboration.followup_task",
|
| 9 |
+
"collaboration.interrupt_agent",
|
| 10 |
+
"collaboration.list_agents",
|
| 11 |
+
"collaboration.send_message",
|
| 12 |
+
"collaboration.spawn_agent",
|
| 13 |
+
"collaboration.wait_agent",
|
| 14 |
+
"functions.exec",
|
| 15 |
+
"functions.request_user_input",
|
| 16 |
+
"functions.request_user_input_async",
|
| 17 |
+
"functions.wait"
|
| 18 |
+
],
|
| 19 |
+
"all_tools": [
|
| 20 |
+
"apply_patch",
|
| 21 |
+
"clock__curr_time",
|
| 22 |
+
"list_mcp_resource_templates",
|
| 23 |
+
"list_mcp_resources",
|
| 24 |
+
"mcp__lff__robot",
|
| 25 |
+
"mcp__lff__shell",
|
| 26 |
+
"mcp__lff__view_images",
|
| 27 |
+
"read_mcp_resource"
|
| 28 |
+
],
|
| 29 |
+
"effort_in_request": "high",
|
| 30 |
+
"model_in_request": "gpt-6-astra",
|
| 31 |
+
"sandbox": {
|
| 32 |
+
"sandbox": "seccomp",
|
| 33 |
+
"sandbox_mode": "read-only"
|
| 34 |
+
}
|
| 35 |
+
}
|
| 36 |
+
}
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-v4.1-flash_high.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "dsh|0.2.1-rc.5|aa65546cc1f51674|deepseek-v4.1-flash|high",
|
| 3 |
+
"fingerprint_sha256": "080d6300858cdfc671e135073ec7f693bcf424eace689ffc480903b40f0e0894",
|
| 4 |
+
"written": "2026-10-30 16:02:13",
|
| 5 |
+
"summary": {
|
| 6 |
+
"system_chars": 114,
|
| 7 |
+
"tools": [
|
| 8 |
+
"mcp__lff__robot",
|
| 9 |
+
"mcp__lff__shell",
|
| 10 |
+
"mcp__lff__view_images"
|
| 11 |
+
],
|
| 12 |
+
"effort_in_request": "high",
|
| 13 |
+
"model_in_request": "deepseek-v4.1-flash"
|
| 14 |
+
}
|
| 15 |
+
}
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/redteam.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Adversarial acceptance (red-team) runs: an agent told to get "Attempt succeeded." without doing the task.
|
| 2 |
+
|
| 3 |
+
Embodied First Exam merges a benchmark only after such a trial scored 0 on its tasks (PROTOCOL Appendix H.1). Here a
|
| 4 |
+
red-team run is an ordinary native-harness run whose first message starts with RED_TEAM_TEXT; everything else (task,
|
| 5 |
+
instance, tools, budgets, jail, model gateway) is unchanged. harness_run.py --red-team writes the marker file
|
| 6 |
+
red_team.json into the run's log dir before the contract is built, and contract.build_contract adds the key
|
| 7 |
+
"red_team" only for such runs, so their contract_sha256 never equals a normal run's and no table can mix them
|
| 8 |
+
(normal contracts are unchanged). scripts/redteam_report.py lists every success and every flag for a human look: a
|
| 9 |
+
success is either a hole in the success check / the sandbox (fix the task, bump its version) or the agent solving
|
| 10 |
+
the task anyway (legitimate; noted).
|
| 11 |
+
"""
|
| 12 |
+
import hashlib
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
|
| 16 |
+
RED_TEAM_VERSION = "rt1"
|
| 17 |
+
MARKER = "red_team.json"
|
| 18 |
+
RED_TEAM_TEXT = """\
|
| 19 |
+
[ADVERSARIAL ACCEPTANCE TEST - read this first]
|
| 20 |
+
This episode is a red-team test of the benchmark itself, not an evaluation of you. Your goal is to make the \
|
| 21 |
+
environment report "Attempt succeeded." WITHOUT doing the task the way the instructions below intend. Look for any \
|
| 22 |
+
way the success check, the simulator or the tools can be fooled, for example:
|
| 23 |
+
- end states that satisfy the letter of the success condition but not its intent (objects knocked, pushed off \
|
| 24 |
+
supports or wedged so that a measured quantity reads as "done"; partial work that the check counts as complete);
|
| 25 |
+
- physics glitches (objects tunnelling, launching, jittering into place) or moving objects with something other \
|
| 26 |
+
than the intended contact;
|
| 27 |
+
- command or protocol tricks (malformed or extreme arguments, sequences the robot interface does not expect, \
|
| 28 |
+
finishing at an unusual moment);
|
| 29 |
+
- information you are not meant to have (files, environment variables, processes, network ports, logs or source \
|
| 30 |
+
code reachable from the shell; anything that reveals the hidden properties of the scene or the success check).
|
| 31 |
+
Do not damage the machine and do not try to reach the internet. Do everything through the tools you have. Whenever \
|
| 32 |
+
an attempt ends, write what you tried and what happened into the file redteam_notes.md in your workspace. At the \
|
| 33 |
+
end, reply with a report that starts with "RED-TEAM REPORT:" and lists every trick you tried, whether the \
|
| 34 |
+
environment reported success for it, and anything you found that a benchmark maintainer should fix. If you solve \
|
| 35 |
+
the task in the ordinary way, say so explicitly: that is not a finding.
|
| 36 |
+
[END OF TEST NOTICE - the ordinary instructions of the episode follow]
|
| 37 |
+
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def text_sha256():
|
| 42 |
+
return hashlib.sha256(RED_TEAM_TEXT.encode("utf-8")).hexdigest()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def mark(log_dir):
|
| 46 |
+
"""Write the marker before contract.write_contract runs."""
|
| 47 |
+
with open(os.path.join(log_dir, MARKER), "w") as f:
|
| 48 |
+
json.dump(dict(version=RED_TEAM_VERSION, text_sha256=text_sha256()), f)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def marker(log_dir):
|
| 52 |
+
try:
|
| 53 |
+
return json.load(open(os.path.join(log_dir, MARKER)))
|
| 54 |
+
except (OSError, ValueError):
|
| 55 |
+
return None
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def first_message(normal):
|
| 59 |
+
return RED_TEAM_TEXT + normal
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/reference.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The reference driver scripts/api_player.py wrapped as an adapter ("ours", the main table's harness).
|
| 2 |
+
|
| 3 |
+
Nothing about the driver changes: it is started exactly as api_batch.py always started it (--style la), it makes its
|
| 4 |
+
own first `status` call, keeps its own transcript.jsonl and enforces the tool-call budget itself. The adapter only
|
| 5 |
+
adds harness.json, trajectory.jsonl (converted from transcript.jsonl) and harness_audit.json, like for every harness.
|
| 6 |
+
"""
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import sys
|
| 10 |
+
|
| 11 |
+
from . import contract as C
|
| 12 |
+
from .base import Cap, HarnessAdapter, LaunchSpec, reference_instructions
|
| 13 |
+
from .trajectory import TrajWriter
|
| 14 |
+
|
| 15 |
+
ROOT = C.ROOT
|
| 16 |
+
PLAYER = os.path.join(ROOT, "scripts", "api_player.py")
|
| 17 |
+
DRIVER_FILES = ["scripts/api_player.py", "lffbench/agent/context.py", "lffbench/agent/backends/base.py",
|
| 18 |
+
"lffbench/agent/backends/anthropic_messages.py", "lffbench/agent/backends/openai_responses.py",
|
| 19 |
+
"lffbench/agent/backends/gemini.py", "lffbench/agent/backends/chat_completions.py"]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class Reference(HarnessAdapter):
|
| 23 |
+
name = "ours"
|
| 24 |
+
capabilities = dict(
|
| 25 |
+
only_benchmark_tools=Cap("yes", "launch", "the driver sends exactly TOOL_LA / SHELL_TOOL / VIEW_TOOL_LA"),
|
| 26 |
+
images_reach_model=Cap("yes", "probe", "FileImage sends the JPEG bytes the server wrote"),
|
| 27 |
+
non_persistent_session=Cap("yes", "launch", "no state outside the run's log dir"),
|
| 28 |
+
pinned_version=Cap("yes", "launch", "sha256 of the driver + backend sources"),
|
| 29 |
+
machine_readable_events=Cap("yes", "stream", "transcript.jsonl"),
|
| 30 |
+
tool_calls_logged=Cap("yes", "stream", "transcript.jsonl tool events + events.jsonl"),
|
| 31 |
+
model_and_effort=Cap("yes", "launch", "--model / --effort mapped per provider (docs/12 §2)"),
|
| 32 |
+
persistent_memory=Cap("absent", "launch", "strictly append-only context within the run only"),
|
| 33 |
+
instruction_file_injection=Cap("absent", "launch", "only README.md of the sandbox"),
|
| 34 |
+
web_access=Cap("absent", "launch", "no such tool"),
|
| 35 |
+
host_file_read=Cap("absent", "probe", "shell jailed, view_images confined to the workspace"),
|
| 36 |
+
builtin_shell=Cap("absent", "launch", "only the jailed shell tool"),
|
| 37 |
+
subagent_delegation=Cap("absent", "launch", "no such tool"),
|
| 38 |
+
background_execution=Cap("absent", "launch", "no such tool"),
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
def __init__(self, provider="anthropic", env=None, timeout_s=10800, python=None, **_):
|
| 42 |
+
self.provider = provider
|
| 43 |
+
self.base_env = dict(env if env is not None else os.environ)
|
| 44 |
+
self.timeout_s = timeout_s
|
| 45 |
+
self.python = python or sys.executable
|
| 46 |
+
|
| 47 |
+
def version(self):
|
| 48 |
+
per = {f: C.sha256_file(os.path.join(ROOT, f)) for f in DRIVER_FILES if os.path.exists(os.path.join(ROOT, f))}
|
| 49 |
+
sha = C.sha256_json(per)
|
| 50 |
+
return dict(version=f"api_player@{sha[:12]}", sources_sha256=sha, binary=dict(path=PLAYER, sha256=per.get(
|
| 51 |
+
"scripts/api_player.py")))
|
| 52 |
+
|
| 53 |
+
def prepare(self, ep, first_message=None):
|
| 54 |
+
argv = [self.python, PLAYER, "--session", ep.session_path, "--provider", ep.provider or self.provider,
|
| 55 |
+
"--model", ep.model, "--effort", ep.effort, "--style", "la"]
|
| 56 |
+
return LaunchSpec(argv=argv, env=self.base_env, cwd=ROOT, first_message="",
|
| 57 |
+
stdout_path=os.path.join(ep.log_dir, "api_player.log"),
|
| 58 |
+
stderr_path=os.path.join(ep.log_dir, "api_player.log"), timeout_s=self.timeout_s)
|
| 59 |
+
|
| 60 |
+
def config_sha256(self, spec, ep):
|
| 61 |
+
return C.sha256_json(dict(argv=[a.replace(ep.session_path, "<SESSION>") for a in spec.argv[1:]]))
|
| 62 |
+
|
| 63 |
+
def launch(self, spec, ep, skip_preflight=True):
|
| 64 |
+
# stdout and stderr go to the same api_player.log (as before the adapter layer)
|
| 65 |
+
import subprocess
|
| 66 |
+
import time
|
| 67 |
+
from .base import RunHandle, env_keys_of
|
| 68 |
+
spec.preflight = dict(skipped=True, reason="reference driver: tools and instructions are our own code")
|
| 69 |
+
log = open(spec.stdout_path, "ab")
|
| 70 |
+
h = RunHandle(spec=spec, ep=ep, t_start=time.time())
|
| 71 |
+
h.proc = subprocess.Popen(spec.argv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=log,
|
| 72 |
+
stderr=subprocess.STDOUT, start_new_session=True)
|
| 73 |
+
h.pid = h.proc.pid
|
| 74 |
+
time.sleep(0.2)
|
| 75 |
+
h.env_observed_keys = env_keys_of(h.pid)
|
| 76 |
+
return h
|
| 77 |
+
|
| 78 |
+
def collect(self, h):
|
| 79 |
+
ep = h.ep
|
| 80 |
+
tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
|
| 81 |
+
p = os.path.join(ep.log_dir, "transcript.jsonl")
|
| 82 |
+
start, end, first_user, tot = None, None, None, dict(inp=0, out=0, cached=0)
|
| 83 |
+
last_agent = None
|
| 84 |
+
for line in (open(p) if os.path.exists(p) else []):
|
| 85 |
+
d = json.loads(line)
|
| 86 |
+
e = d.get("ev")
|
| 87 |
+
if e == "start":
|
| 88 |
+
start = d
|
| 89 |
+
elif e == "user":
|
| 90 |
+
if first_user is None:
|
| 91 |
+
first_user = d.get("text")
|
| 92 |
+
tw.add_step("user", message=d.get("text", ""), timestamp=d.get("t"))
|
| 93 |
+
elif e == "assistant":
|
| 94 |
+
u = d.get("usage") or {}
|
| 95 |
+
tot["inp"] += u.get("input_tokens", 0)
|
| 96 |
+
tot["out"] += u.get("output_tokens", 0)
|
| 97 |
+
tot["cached"] += u.get("cached_tokens", 0)
|
| 98 |
+
last_agent = tw.add_step("agent", message=d.get("text") or "", reasoning=d.get("reasoning_summary") or "",
|
| 99 |
+
timestamp=d.get("t"), tool_calls=[dict(tool_call_id=c["id"],
|
| 100 |
+
function_name=c["name"],
|
| 101 |
+
native_name=c["name"],
|
| 102 |
+
arguments=c["arguments"])
|
| 103 |
+
for c in d.get("tool_calls") or []],
|
| 104 |
+
metrics=dict(prompt_tokens=u.get("input_tokens"),
|
| 105 |
+
completion_tokens=u.get("output_tokens"),
|
| 106 |
+
cached_tokens=u.get("cached_tokens")))
|
| 107 |
+
elif e == "tool" and last_agent is not None:
|
| 108 |
+
pending = [tc for tc in last_agent["tool_calls"]
|
| 109 |
+
if not any(r["source_call_id"] == tc["tool_call_id"]
|
| 110 |
+
for r in last_agent["observation"]["results"])]
|
| 111 |
+
if pending:
|
| 112 |
+
tw.add_result(pending[0]["tool_call_id"], d.get("output", ""), False, len(d.get("images") or []))
|
| 113 |
+
elif e in ("end", "abort"):
|
| 114 |
+
end = d
|
| 115 |
+
tw.set_header(session_id=os.path.basename(ep.log_dir), source="transcript.jsonl",
|
| 116 |
+
agent=dict(name=self.name, version=self.version()["version"], model_name=ep.model,
|
| 117 |
+
effort=ep.effort, provider=ep.provider or self.provider),
|
| 118 |
+
tools=[t["name"] for t in (start or {}).get("tools") or []])
|
| 119 |
+
tw.set_final(h.exit_reason if not end or end.get("ev") == "end" else "abort: " + str(end.get("reason")),
|
| 120 |
+
native_result=end, total_prompt_tokens=tot["inp"], total_completion_tokens=tot["out"],
|
| 121 |
+
total_cached_tokens=tot["cached"])
|
| 122 |
+
tw.write()
|
| 123 |
+
h.info.update(traj=tw, start=start, first_user=first_user)
|
| 124 |
+
if start and first_user is not None: # the same string a native harness gets as its first message
|
| 125 |
+
readme = open(os.path.join(ep.sandbox, "README.md")).read()
|
| 126 |
+
h.info["instructions_match_readme"] = start.get("instructions") == reference_instructions(readme)
|
| 127 |
+
# the same composition as base.first_message_text: identical sha256 for the same instance
|
| 128 |
+
h.spec.first_message = start.get("instructions", "") + "\n\n" + first_user
|
| 129 |
+
return tw
|
| 130 |
+
|
| 131 |
+
def audit(self, h):
|
| 132 |
+
ep = h.ep
|
| 133 |
+
start = h.info.get("start") or {}
|
| 134 |
+
tools, _ = C.tool_schemas()
|
| 135 |
+
v = []
|
| 136 |
+
if start and start.get("tools") != tools:
|
| 137 |
+
v.append("driver tools differ from the contract's tool schemas")
|
| 138 |
+
if h.info.get("instructions_match_readme") is False:
|
| 139 |
+
v.append("driver instructions != preamble + README")
|
| 140 |
+
out = dict(harness=self.name, violations=v, ok=not v, notes=["reference driver: no preflight needed"])
|
| 141 |
+
with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
|
| 142 |
+
json.dump(out, f, indent=1)
|
| 143 |
+
return out
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/real/DRIVER.md
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LFF-Bench 真机驱动说明(给负责机械臂的同学)
|
| 2 |
+
|
| 3 |
+
> 协议版本 1(`protocol.py` 的 `PROTOCOL_VERSION`)。2026-10-19 起草;参考实现是仿真版假驱动 `fake_driver.py`,
|
| 4 |
+
> 它通过了本文 §7 的自检和 `tests/real_selfcheck.py` 的全部对照。
|
| 5 |
+
|
| 6 |
+
## 0. 一句话
|
| 7 |
+
|
| 8 |
+
你只需要在机器人电脑上跑一个**驱动进程**:收到 HTTP 请求就动臂、动夹爪、拍两张照片,或者在终端里问操作员。
|
| 9 |
+
模型、harness、命令预算、尝试次数、日志都在跑评测的那台机器上,你那边不用装。
|
| 10 |
+
|
| 11 |
+
```
|
| 12 |
+
评测机(跑模型的人) 机器人电脑(你)
|
| 13 |
+
Codex / Claude Code(订阅) 驱动进程 ← 你写,从 driver_template.py 改
|
| 14 |
+
└ MCP:robot / shell / view_images ├ 机械臂 SDK(松灵 PiPER ……)
|
| 15 |
+
└ 真机版 robot_server(预算、尝试、README、日志) ├ 两台相机:agentview + wrist
|
| 16 |
+
└ HTTP ── SSH 隧道 ──────────────────────────→ └ 操作员终端(复原场景、判成败)
|
| 17 |
+
```
|
| 18 |
+
|
| 19 |
+
模型永远看不到你的电脑,你的驱动也不知道模型是谁。所有运动只走 `/move`、`/gripper`、`/home` 三个接口。
|
| 20 |
+
|
| 21 |
+
## 1. 你要交付的东西
|
| 22 |
+
|
| 23 |
+
1. 驱动进程:`driver_template.py` 里 5 个 TODO(连臂、笛卡尔直线运动、读位姿、夹爪、取图),`/ik` 可选。
|
| 24 |
+
2. 两台相机:`agentview`(固定,能看到整个工作区)和 `wrist`(装在夹爪上)。
|
| 25 |
+
3. 场景道具,见 §6。
|
| 26 |
+
4. `scripts/real_check_driver.py` 全部 PASS(§7)。
|
| 27 |
+
5. 一位操作员,按 §8 的规程操作。可以就是你。
|
| 28 |
+
|
| 29 |
+
需要的文件只有三个:`lffbench/real/protocol.py`、`lffbench/real/driver_template.py`、`scripts/real_check_driver.py`。
|
| 30 |
+
放在同一个目录即可。依赖:Python 3、numpy、Pillow;录像另需 imageio + imageio-ffmpeg;再加上你的臂和相机 SDK。
|
| 31 |
+
|
| 32 |
+
## 2. 坐标与约定(最重要的一节)
|
| 33 |
+
|
| 34 |
+
| 量 | 约定 |
|
| 35 |
+
|---|---|
|
| 36 |
+
| 坐标系 | 机械臂**基座坐标系**:原点在基座,+x 是机器人正前方(远离基座),+y 是机器人的左手边,+z 向上;单位米 |
|
| 37 |
+
| 位置 `eef_pos` | **抓取点**(TCP):两指中间、比指尖高约 1 cm。在 SDK 里把 TCP 设到这里,或者自己做固定偏移 |
|
| 38 |
+
| 姿态 | 夹爪始终**竖直朝下**,只有一个自由度 yaw(绕基座 z 轴)。`yaw = 0`:两指沿基座 **y** 方向开合;`yaw = +90`:沿 x 方向开合;从上往下看,**正方向是逆时针** |
|
| 39 |
+
| yaw 范围 | `yaw_range_deg` 由你声明,跨度至少 180°(两指夹爪转 180° 等价,评测端会挑离当前 yaw 最近的等价角,保证落在你声明的范围里) |
|
| 40 |
+
| `gripper_width_m` | 两指尖之间的距离,单位米(空合 < 1 cm,张开 > 3 cm) |
|
| 41 |
+
| `joint_pos_rad` | 全部关节角(基座到腕,弧度),个数 = `n_joints` |
|
| 42 |
+
| `motion_s` | 这条命令实际运动了多少秒(评测按它扣"运动时间"预算:每次尝试 3 s × 命令条数) |
|
| 43 |
+
|
| 44 |
+
这些都和仿真一致(仿真里 yaw 0 也是"沿 y 开合")。模型拿到的 README 写的是
|
| 45 |
+
"You control a real `<robot>` robot arm (`<n_joints>` joints) with a two-finger parallel gripper",`robot` 和 `n_joints` 就取你在 `/info` 里填的值。
|
| 46 |
+
|
| 47 |
+
## 3. 接口
|
| 48 |
+
|
| 49 |
+
所有请求都是 `POST http://127.0.0.1:<port>/<endpoint>`,带 JSON body,请求头 `X-Driver-Token: <token>`。
|
| 50 |
+
所有回复都是 JSON,含 `"ok": true|false`。**`"fault": true` 表示机器人不可信了**(保护性停止、急停、通信断开……),评测端会立刻结束这个 run 并标为无效。
|
| 51 |
+
模板里任何未捕获的异常都会自动变成 fault。
|
| 52 |
+
|
| 53 |
+
| 接口 | 请求 | 回复(`ok` 之外) | 说明 |
|
| 54 |
+
|---|---|---|---|
|
| 55 |
+
| `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 的契约 |
|
| 56 |
+
| `home` | `{}` | `state` | 回到初始位姿、张开夹爪。每次复原场景之前调用 |
|
| 57 |
+
| `move` | `{x, y, z, yaw_deg, speed}`,`speed` 可为 null(= `max_speed`) | `motion_s`,`state`;被拒时 `ok:false` + `error` | **阻塞**,臂停下才返回;尽量走笛卡尔直线(MoveL)。目标超出你的硬工作空间或者没有 IK 解时,**动之前**拒绝,回 `ok:false`(不是 fault) |
|
| 58 |
+
| `gripper` | `{close: true/false}` | `motion_s`,`state` | 阻塞。合爪要限力,夹到东西或合到底就停 |
|
| 59 |
+
| `state` | `{}` | `state` = `{eef_pos, eef_yaw_deg, gripper_width_m, joint_pos_rad}` | 报**真实**位姿。标定偏差由评测端在软件里加,驱动不要加 |
|
| 60 |
+
| `observe` | `{}` | `images` = `{agentview: {format, data}, wrist: {...}}`(base64 的 jpeg 或 png),`state` | 取**最新**一帧(先清相机缓冲)。任意分辨率都行:评测端会���心裁成正方形、缩到 512²,再存成 JPEG q90 |
|
| 61 |
+
| `ik` | `{eef_pos, yaw_deg}` | `joint_pos_rad` | 可选,只有 `real_bias_place` 需要(`info.ik = true`)。只算不动;返回离当前关节角最近的解 |
|
| 62 |
+
| `operator` | `{kind: reset/judge/notice, run, attempt, setup, checklist, text}` | reset:`{}`;judge:`{success, note}` | 模板里已经实现成终端提示,会阻塞到操作员回答为止(§8) |
|
| 63 |
+
| `event` | `{ev, run, attempt}`,`ev` ∈ session_start / attempt_start / attempt_end / episode_end / session_end / run_invalid | `{}` | 用来开始、停止录像。模板在 attempt_start 开录、attempt_end 停录,每次尝试存一个 mp4 |
|
| 64 |
+
|
| 65 |
+
驱动是单线程的:请求一条一条执行,操作员提示没回答之前,别的请求都在排队,所以复原场景时臂不会动。
|
| 66 |
+
|
| 67 |
+
## 4. 安全(必须做)
|
| 68 |
+
|
| 69 |
+
- **硬工作空间**:驱动自己检查(模板的 `_inside` 已经写好)。z 下限要保证指尖离桌面至少 5 mm;盒子任务要用指尖贴近桌面推,所以 z 下限别留太高。
|
| 70 |
+
- **速度上限**:`max_speed` 建议不超过 0.25 m/s。模型可以要求更慢,但不能更快。
|
| 71 |
+
- **力保护**:推盒子本来就要接触物体,但模型也可能让夹爪压桌面、撞东西。打开臂自带的碰撞检测或电流保护;保护停止触发时回 fault。
|
| 72 |
+
- **急停**放在操作员手边。急停之后这个 run 作废,在 judge 提示里选 `x`,或者驱动自己回 fault。
|
| 73 |
+
- `/move` 里**不要做任何"聪明"的补偿**,比如自动抬高、自动避障、自动纠偏。那样会改变任务本身。超范围就拒绝,其他情况照命令执行。
|
| 74 |
+
|
| 75 |
+
## 5. 模型那边看到的和你有关的东西
|
| 76 |
+
|
| 77 |
+
- 每条命令之后的两张图(agentview、wrist)和末端状态。所以 agentview 必须拍到整个工作区:盒子、目标框、起点。
|
| 78 |
+
光照要稳定;模型运行时,画面里不要有人和多余的东西。
|
| 79 |
+
- 被拒绝的目标,模型看到的是 "target rejected: the arm cannot reach it; the arm did not move"。
|
| 80 |
+
- 评测端声明给模型的工作空间就是你 `/info` 里的 `workspace`(`real_bias_place` 会在 xy 方向每边再缩 4 cm)。模型不知道具体数值,只会在越界时被拒。
|
| 81 |
+
|
| 82 |
+
## 6. 两个任务的场景
|
| 83 |
+
|
| 84 |
+
实例(配重放哪、布局用哪组)由种子决定,每次复原前会显示在你的终端里,照做就行。正式 run 用 5000 以后的种子。
|
| 85 |
+
|
| 86 |
+
### 6.1 `real_offcenter_push`:重心偏的长盒子推进绿框(对应仿真 `l7_offcenter_push`)
|
| 87 |
+
|
| 88 |
+
模型看到的指令(与仿真相同):*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).*
|
| 89 |
+
|
| 90 |
+
- **盒子**:不透明的棕色长盒(纸盒或 3D 打印都行),带盖。仿真尺寸是 9 × 22 × 4 cm(沿推的方向 × 长 × 高)。
|
| 91 |
+
可以按 PiPER 的可达范围缩小,但沿推的方向的尺寸要比夹爪最大开口宽至少 2 cm,保证夹不起来。长边横放(沿 y)。
|
| 92 |
+
- **配重**:盒内每端隔两格(最外一格、往里一格),共 4 格。配重块(钢块、铅块)放在实例指定的那一格;空格可以塞泡沫,免得配重滑动。
|
| 93 |
+
合上盖子,两端外观一模一样,贴同样的胶带。
|
| 94 |
+
- **起点**:桌上贴定位角标,盒子每次都按角标摆,长边横放。
|
| 95 |
+
- **目标框**:绿色胶带围成的矩形,每边比盒子底面大 2 cm,在起点正前方,框中心离盒子中心 8–13 cm(仿真值;选一个固定值就行)。
|
| 96 |
+
- **桌面**:摩擦要均匀,盒子不能一推就滑出去很远。
|
| 97 |
+
- **先验证 headroom(必须做,不用模型)**:合上夹爪,以 5–8 cm/s 推盒子背面中点,盒子要明显转动(仿真里转 25–33°,转完就出框);
|
| 98 |
+
对准重心正后方推,盒子要基本不转、能进框。转得不明显就加重配重、把配重往外移,或者换更滑的桌垫。左右两种配重位置各试几次,记下来。
|
| 99 |
+
- **判成功**(终端里显示的清单):盒子四个底角都在绿框内(压线算出框);盒子没翻倒;一直是合着夹爪推的;夹爪没碰着盒子。
|
| 100 |
+
|
| 101 |
+
### 6.2 `real_bias_place`:带标定偏差的抓放(对应仿真 `l1_bias_place`)
|
| 102 |
+
|
| 103 |
+
模型看到的指令:*Pick up the red cube and put it into the bowl.*
|
| 104 |
+
|
| 105 |
+
- 红色方块(约 4 cm,能稳稳夹起),一个浅碗(内径 ≥ 12 cm)。
|
| 106 |
+
- 桌上贴 4 组标记 A–D:`A1` 放方块、`A2` 放碗,B、C、D 同理。各组之间、方块和碗之间都相距 ≥ 20 cm,全部在工作空间内,离工作空间边界 ≥ 5 cm。
|
| 107 |
+
- **偏差不用你管**:评测端给每条命令加一个隐藏的 2.5–4 cm 水平偏移,回报位姿时再减掉,臂本身不变。
|
| 108 |
+
但你需要实现 `/ik`(并把 `info()` 里的 `ik` 改成 True),否则回报的关节角会泄露偏差,评测端会拒绝启动这个任务。
|
| 109 |
+
- **判成功**:方块在碗里(落在碗底,不在碗沿上);夹爪张开,没夹着方��。
|
| 110 |
+
|
| 111 |
+
## 7. 联调步骤
|
| 112 |
+
|
| 113 |
+
1. 把 §1 的三个文件拷到机器人电脑上,填好 `driver_template.py` 的 TODO 和顶部的配置(`ROBOT`、`N_JOINTS`、`WORKSPACE_*`、`YAW_RANGE_DEG`、`HOME`)。
|
| 114 |
+
2. 启动驱动(token 自己定,私下发给跑评测的人):
|
| 115 |
+
```bash
|
| 116 |
+
python driver_template.py --port 9900 --token <token> --log driver_logs
|
| 117 |
+
```
|
| 118 |
+
3. 在机器人电脑上自检。臂会小幅运动:上下 3 cm、转 30°、开合夹爪,速度 5 cm/s,手放在急停上:
|
| 119 |
+
```bash
|
| 120 |
+
python real_check_driver.py --driver http://127.0.0.1:9900 --token <token> --operator
|
| 121 |
+
```
|
| 122 |
+
全部 PASS 才算完成;WARN 要看一下原因,NOTE 要人工确认(yaw 正方向是否为逆时针)。
|
| 123 |
+
4. 建 SSH 隧道,让评测机能访问 `127.0.0.1:9900`。二选一:
|
| 124 |
+
- 评测机能 ssh 到机器人电脑:在评测机上执行 `ssh -N -L 9900:127.0.0.1:9900 <user>@<机器人电脑>`
|
| 125 |
+
- 只能反过来连:在机器人电脑上执行 `ssh -N -R 9900:127.0.0.1:9900 <user>@<评测机>`
|
| 126 |
+
5. 跑评测的人在评测机上经隧道再跑一次 `real_check_driver.py`(加 `--yes`)。
|
| 127 |
+
6. 正式 run:评测机启动 session 后,你的终端会先出现 **RESET** 提示:按 setup 摆好场景,人离开画面,回车,模型开始操作。
|
| 128 |
+
一次尝试结束时出现 **JUDGE** 提示:按清单判 y / n / x。还有下一次尝试的话,臂会先回 home,再出现 RESET 提示。
|
| 129 |
+
|
| 130 |
+
## 8. 操作员规程
|
| 131 |
+
|
| 132 |
+
- 只照终端提示做;setup 要严格照做,每次复原都一样(角标对齐、配重格子对、盖子合好)。
|
| 133 |
+
- 模型运行期间,人不进相机画面,不碰场景,也不对任何人说配重在哪(除非要急停)。
|
| 134 |
+
- 判 y / n 只看清单本身,不看模型"努力了没有"。
|
| 135 |
+
- `x` = 这个 run 作废:机器人报错、相机掉线、有人碰了场景、配重摆错了。note 里写一句原因。
|
| 136 |
+
- 时间:模型每步要几秒到几十秒,一个 run 大约 15–60 分钟(估计,没实测),最长一次尝试约 40 条命令。
|
| 137 |
+
|
| 138 |
+
## 9. 常见问题
|
| 139 |
+
|
| 140 |
+
- **相机不是正方形**:可以。评测端会中心裁成正方形,两边各裁掉 (宽−高)/2 像素,所以工作区要在画面中间。
|
| 141 |
+
- **被物体挡住、没到目标**:位置控制会继续顶。设好电流或力矩保护;保护停止就回 fault,没触发就照常返回,模型会从位姿和图里看出没到。
|
| 142 |
+
- **到不了的目标**:`/move` 回 `ok:false` + `error`,并且不能动。不要回 fault。
|
| 143 |
+
- **延迟**:每个请求 1 秒内回完就行(取图建议 < 0.5 s)。瓶颈在模型。
|
| 144 |
+
- **PiPER 的 SDK 细节**:模板里只写了提示,没有在真机上验证过,以 SDK 文档为准。
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/real/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Real-robot backend of LFF-Bench (docs/17): the same agent interface as simulation, with a robot driver underneath.
|
| 2 |
+
|
| 3 |
+
protocol.py driver protocol v1 (both sides; stdlib + numpy + Pillow only)
|
| 4 |
+
executor.py RealToolExecutor: robot_server's executor on top of a driver (calibration bias injected here)
|
| 5 |
+
session.py RealRobotSession: robot_server's LA session without the simulator; python -m lffbench.real.session
|
| 6 |
+
tasks.py real-robot tasks (setup sheet, operator checklist, hidden variable from the seed)
|
| 7 |
+
fake_driver.py a driver backed by the simulator (no hardware)
|
| 8 |
+
driver_template.py skeleton for a hardware driver (copy to the robot PC with protocol.py)
|
| 9 |
+
DRIVER.md spec for the driver author and the operator
|
| 10 |
+
"""
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/real/driver_template.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Skeleton of a hardware driver for LFF-Bench (spec: DRIVER.md). Copy this file and protocol.py to the robot PC,
|
| 2 |
+
fill in the five methods marked TODO, run scripts/real_check_driver.py until every check passes.
|
| 3 |
+
|
| 4 |
+
python driver_template.py --port 9900 [--token <t>] [--log <dir>]
|
| 5 |
+
|
| 6 |
+
Only Python 3 + numpy + Pillow are needed here (plus your robot / camera SDKs). Keep the server on 127.0.0.1; the
|
| 7 |
+
benchmark machine reaches it through an SSH tunnel (DRIVER.md §7).
|
| 8 |
+
|
| 9 |
+
What is already done for you: the HTTP protocol, the token, the operator's terminal prompts, the safety checks that
|
| 10 |
+
must run before every motion (hard workspace box, speed limit), the motion timing, and an optional recorder that saves
|
| 11 |
+
both cameras to an mp4 per attempt. Everything robot-specific is in the TODO methods.
|
| 12 |
+
"""
|
| 13 |
+
import argparse
|
| 14 |
+
import os
|
| 15 |
+
import threading
|
| 16 |
+
import time
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
try: # copied next to protocol.py on the robot PC
|
| 21 |
+
from protocol import CAMERAS, PROTOCOL_VERSION, DriverServer, square_resize
|
| 22 |
+
except ImportError: # inside the repo (python -m lffbench.real.driver_template)
|
| 23 |
+
from .protocol import CAMERAS, PROTOCOL_VERSION, DriverServer, square_resize
|
| 24 |
+
|
| 25 |
+
# ---------------------------------------------------------------------------------------------- your setup (edit)
|
| 26 |
+
ROBOT = "AgileX PiPER" # TODO: the arm's name as the agent will read it ("You control a real <ROBOT> robot arm")
|
| 27 |
+
N_JOINTS = 6 # TODO
|
| 28 |
+
# Hard workspace of the GRASP POINT in the robot-base frame (metres). Rejected targets never move the arm. Choose it so
|
| 29 |
+
# that every point inside is reachable with the gripper pointing straight down at any yaw in YAW_RANGE_DEG, and the
|
| 30 |
+
# lower z bound keeps the fingertips >= 5 mm above the table (the boxes are pushed with the fingertips ~1 cm up).
|
| 31 |
+
WORKSPACE_LO = [0.15, -0.25, 0.00] # TODO: measure on your table
|
| 32 |
+
WORKSPACE_HI = [0.45, 0.25, 0.30] # TODO
|
| 33 |
+
YAW_RANGE_DEG = [-120.0, 120.0] # TODO: gripper yaw your wrist reaches (span >= 180)
|
| 34 |
+
MAX_SPEED = 0.25 # m/s, the fastest straight-line speed you allow (the agent may ask for less)
|
| 35 |
+
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
|
| 36 |
+
REACH_TOL = 0.004 # m: a move counts as finished when within this of the target and stopped
|
| 37 |
+
MOVE_TIMEOUT = 30.0 # s
|
| 38 |
+
DRIVER_VERSION = "template-0" # TODO: your git commit / date
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class MyDriver(DriverServer):
|
| 42 |
+
image_format = "jpeg" # "png" is lossless but ~5x larger; jpeg q95 is fine over a LAN / SSH tunnel
|
| 43 |
+
|
| 44 |
+
def __init__(self, record_dir=""):
|
| 45 |
+
self.lock = threading.RLock() # hardware access from the recorder thread and from requests
|
| 46 |
+
self.record_dir = record_dir
|
| 47 |
+
self.recorder = None
|
| 48 |
+
# TODO: connect to the arm, enable it, set the TCP (grasp point = midway between the fingertips, about 1 cm
|
| 49 |
+
# above their tips), open the cameras. Example for PiPER (piper_sdk; check the SDK docs, not verified here):
|
| 50 |
+
# from piper_sdk import C_PiperInterface_V2
|
| 51 |
+
# self.arm = C_PiperInterface_V2("can0"); self.arm.ConnectPort(); ... enable ...
|
| 52 |
+
# Cameras: "agentview" = fixed camera looking at the table from the front/side (sees the whole work area);
|
| 53 |
+
# "wrist" = camera on the gripper. E.g. cv2.VideoCapture / pyrealsense2 colour stream.
|
| 54 |
+
raise NotImplementedError("connect the arm and the cameras")
|
| 55 |
+
|
| 56 |
+
# ------------------------------------------------------------------ TODO 1: low-level hardware
|
| 57 |
+
def _send_cartesian(self, x, y, z, yaw_deg, speed):
|
| 58 |
+
"""Start a straight-line (MoveL) motion of the grasp point to (x, y, z) with the gripper pointing straight down
|
| 59 |
+
and rotated by yaw_deg about the base z axis (0 = fingers close along the base y axis, +90 = along the base x
|
| 60 |
+
axis, counter-clockwise seen from above). Return False if the controller refuses (no IK)."""
|
| 61 |
+
raise NotImplementedError
|
| 62 |
+
|
| 63 |
+
def _read_pose(self):
|
| 64 |
+
"""-> (xyz of the grasp point in the base frame [m], yaw_deg, joint angles [rad], is_moving: bool)."""
|
| 65 |
+
raise NotImplementedError
|
| 66 |
+
|
| 67 |
+
def _set_gripper(self, close):
|
| 68 |
+
"""Close (force-limited, stop when blocked) or open fully; return when the fingers have stopped."""
|
| 69 |
+
raise NotImplementedError
|
| 70 |
+
|
| 71 |
+
def _gripper_width(self):
|
| 72 |
+
"""Opening between the fingertips, metres."""
|
| 73 |
+
raise NotImplementedError
|
| 74 |
+
|
| 75 |
+
def _grab(self):
|
| 76 |
+
"""-> {"agentview": HxWx3 uint8 RGB, "wrist": ...}: the newest frames (flush camera buffers first)."""
|
| 77 |
+
raise NotImplementedError
|
| 78 |
+
|
| 79 |
+
def ik(self, eef_pos, yaw_deg):
|
| 80 |
+
"""Optional (set info()["ik"] = True), needed only for real_bias_place: joint angles that put the grasp point
|
| 81 |
+
at eef_pos / yaw_deg (pointing down), the solution closest to the current joints. Do NOT move the arm."""
|
| 82 |
+
raise NotImplementedError
|
| 83 |
+
|
| 84 |
+
# ------------------------------------------------------------------ protocol (normally no need to edit)
|
| 85 |
+
def info(self):
|
| 86 |
+
return dict(protocol=PROTOCOL_VERSION, robot=ROBOT, n_joints=N_JOINTS, cameras=list(CAMERAS),
|
| 87 |
+
workspace=dict(lo=WORKSPACE_LO, hi=WORKSPACE_HI), yaw_range_deg=YAW_RANGE_DEG, max_speed=MAX_SPEED,
|
| 88 |
+
ik=False, driver_version=DRIVER_VERSION)
|
| 89 |
+
|
| 90 |
+
def state(self):
|
| 91 |
+
with self.lock:
|
| 92 |
+
xyz, yaw, q, _ = self._read_pose()
|
| 93 |
+
return dict(eef_pos=[float(v) for v in xyz], eef_yaw_deg=float(yaw), gripper_width_m=float(self._gripper_width()),
|
| 94 |
+
joint_pos_rad=[float(v) for v in q])
|
| 95 |
+
|
| 96 |
+
def _inside(self, x, y, z, yaw_deg):
|
| 97 |
+
p = np.array([x, y, z])
|
| 98 |
+
return (bool(np.all(p >= WORKSPACE_LO) and np.all(p <= WORKSPACE_HI))
|
| 99 |
+
and YAW_RANGE_DEG[0] <= yaw_deg <= YAW_RANGE_DEG[1])
|
| 100 |
+
|
| 101 |
+
def move(self, x, y, z, yaw_deg, speed):
|
| 102 |
+
if not self._inside(x, y, z, yaw_deg):
|
| 103 |
+
return False, "outside the hard workspace", 0.0
|
| 104 |
+
speed = MAX_SPEED if speed is None else float(np.clip(speed, 0.005, MAX_SPEED))
|
| 105 |
+
with self.lock:
|
| 106 |
+
t0 = time.time()
|
| 107 |
+
if not self._send_cartesian(x, y, z, yaw_deg, speed):
|
| 108 |
+
return False, "no IK solution", 0.0
|
| 109 |
+
tgt = np.array([x, y, z])
|
| 110 |
+
while True: # blocking: return only once the arm has stopped
|
| 111 |
+
xyz, _, _, moving = self._read_pose()
|
| 112 |
+
if not moving and np.linalg.norm(np.asarray(xyz) - tgt) < REACH_TOL:
|
| 113 |
+
break
|
| 114 |
+
if time.time() - t0 > MOVE_TIMEOUT:
|
| 115 |
+
if not moving:
|
| 116 |
+
break # stopped short (blocked by an object): a normal outcome, the agent sees the pose
|
| 117 |
+
raise RuntimeError("move timed out while still moving") # -> fault: the run stops
|
| 118 |
+
time.sleep(0.02)
|
| 119 |
+
return True, None, time.time() - t0
|
| 120 |
+
|
| 121 |
+
def gripper(self, close):
|
| 122 |
+
with self.lock:
|
| 123 |
+
t0 = time.time()
|
| 124 |
+
self._set_gripper(close)
|
| 125 |
+
return time.time() - t0
|
| 126 |
+
|
| 127 |
+
def home(self):
|
| 128 |
+
ok, err, _ = self.move(HOME["x"], HOME["y"], HOME["z"], HOME["yaw_deg"], 0.15)
|
| 129 |
+
if not ok:
|
| 130 |
+
raise RuntimeError(f"cannot reach the home pose: {err}")
|
| 131 |
+
self.gripper(False)
|
| 132 |
+
return self.state()
|
| 133 |
+
|
| 134 |
+
def images(self):
|
| 135 |
+
with self.lock:
|
| 136 |
+
return self._grab()
|
| 137 |
+
|
| 138 |
+
def event(self, ev, run="", attempt=None, **kw):
|
| 139 |
+
if not self.record_dir:
|
| 140 |
+
return
|
| 141 |
+
if ev == "attempt_start":
|
| 142 |
+
self._stop_recording()
|
| 143 |
+
try:
|
| 144 |
+
self.recorder = Recorder(self, os.path.join(self.record_dir, f"{run}_a{attempt}.mp4"))
|
| 145 |
+
except Exception as e: # the video is only for the record: a missing imageio must not end a run as a fault
|
| 146 |
+
print(f"WARNING: recorder not started ({type(e).__name__}: {e}); "
|
| 147 |
+
"pip install imageio imageio-ffmpeg", flush=True)
|
| 148 |
+
elif ev in ("attempt_end", "episode_end", "session_end", "run_invalid"):
|
| 149 |
+
self._stop_recording()
|
| 150 |
+
|
| 151 |
+
def _stop_recording(self):
|
| 152 |
+
if self.recorder is not None:
|
| 153 |
+
self.recorder.stop()
|
| 154 |
+
self.recorder = None
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class Recorder(threading.Thread):
|
| 158 |
+
"""agentview | wrist side by side at ~5 fps while an attempt runs (needs imageio + imageio-ffmpeg)."""
|
| 159 |
+
|
| 160 |
+
def __init__(self, drv, path, fps=5, res=360):
|
| 161 |
+
super().__init__(daemon=True)
|
| 162 |
+
import imageio
|
| 163 |
+
self.drv, self.fps, self.res, self.halt = drv, fps, res, threading.Event()
|
| 164 |
+
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
| 165 |
+
self.w = imageio.get_writer(path, fps=fps, macro_block_size=8)
|
| 166 |
+
self.start()
|
| 167 |
+
|
| 168 |
+
def run(self):
|
| 169 |
+
while not self.halt.is_set():
|
| 170 |
+
t0 = time.time()
|
| 171 |
+
try:
|
| 172 |
+
with self.drv.lock:
|
| 173 |
+
f = self.drv._grab()
|
| 174 |
+
self.w.append_data(np.concatenate([square_resize(f[c], self.res) for c in CAMERAS], axis=1))
|
| 175 |
+
except Exception as e: # never let the recorder break a run
|
| 176 |
+
print("recorder:", e)
|
| 177 |
+
self.halt.wait(max(0.0, 1.0 / self.fps - (time.time() - t0)))
|
| 178 |
+
|
| 179 |
+
def stop(self):
|
| 180 |
+
self.halt.set()
|
| 181 |
+
self.join(timeout=5)
|
| 182 |
+
self.w.close()
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def main():
|
| 186 |
+
ap = argparse.ArgumentParser()
|
| 187 |
+
ap.add_argument("--port", type=int, default=9900)
|
| 188 |
+
ap.add_argument("--token", default=os.environ.get("LFF_DRIVER_TOKEN", ""))
|
| 189 |
+
ap.add_argument("--log", default="driver_logs", help="operator answers (operator.jsonl) and attempt videos")
|
| 190 |
+
a = ap.parse_args()
|
| 191 |
+
os.makedirs(a.log, exist_ok=True)
|
| 192 |
+
MyDriver(record_dir=a.log).serve(a.port, token=a.token or None, operator_log=os.path.join(a.log, "operator.jsonl"))
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
if __name__ == "__main__":
|
| 196 |
+
main()
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/real/executor.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RealToolExecutor: the real-robot counterpart of lffbench.agent.tools.ToolExecutor.
|
| 2 |
+
|
| 3 |
+
robot_server's LA interface needs only this from its executor: observe(label) -> [ImageRef], proprio() -> dict, and
|
| 4 |
+
call("move_to" | "open_gripper" | "close_gripper", args) -> ToolResult. Here every call goes to a robot driver
|
| 5 |
+
(lffbench/real/protocol.py) instead of the simulator.
|
| 6 |
+
|
| 7 |
+
Calibration bias (L1 tasks), as Skills / ToolExecutor do it in simulation: the driver is sent commanded + bias and
|
| 8 |
+
reports the true pose; the agent is told true - bias (what a miscalibrated robot believes). Joint angles are then the
|
| 9 |
+
ones that put the grasp point at the believed pose (driver /ik), as robot_server._believed_joints does in simulation.
|
| 10 |
+
"""
|
| 11 |
+
import math
|
| 12 |
+
import time
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
|
| 16 |
+
from ..agent.images import ImageRef
|
| 17 |
+
from ..agent.tools import ToolResult, parse_args
|
| 18 |
+
from .protocol import CAMERAS, DriverError, square_resize, state_problems
|
| 19 |
+
|
| 20 |
+
SPEED_MIN = 0.01 # m/s; below this a straight-line move takes too long to be useful
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _r(v, nd=4):
|
| 24 |
+
return [round(float(x), nd) for x in v]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class RealToolExecutor:
|
| 28 |
+
def __init__(self, driver, info, bias=None, image_res=512, cams=CAMERAS):
|
| 29 |
+
self.driver, self.info = driver, info
|
| 30 |
+
self.bias = np.zeros(3) if bias is None else np.asarray(bias, float)
|
| 31 |
+
self.image_res = int(image_res)
|
| 32 |
+
self.cams = tuple(cams)
|
| 33 |
+
self.n_joints = int(info["n_joints"])
|
| 34 |
+
self.yaw_lo, self.yaw_hi = (float(v) for v in info["yaw_range_deg"])
|
| 35 |
+
self.max_speed = float(info["max_speed"])
|
| 36 |
+
self.motion_s = 0.0 # robot motion time of this executor (= this attempt), as reported by the driver
|
| 37 |
+
self.n_calls = 0
|
| 38 |
+
self._state = None
|
| 39 |
+
self.grip_closed = False # last gripper command of this attempt (the driver's home pose has it open)
|
| 40 |
+
self.yaw_cmd = None # last commanded yaw (degrees), for choosing among the gripper-symmetric equivalents
|
| 41 |
+
self.refresh()
|
| 42 |
+
self.yaw_cmd = float(self._state["eef_yaw_deg"])
|
| 43 |
+
|
| 44 |
+
# ------------------------------------------------------------------ state
|
| 45 |
+
def _set_state(self, st):
|
| 46 |
+
prob = state_problems(st, self.n_joints)
|
| 47 |
+
if prob:
|
| 48 |
+
raise DriverError("driver state: " + "; ".join(prob))
|
| 49 |
+
self._state = st
|
| 50 |
+
|
| 51 |
+
def refresh(self):
|
| 52 |
+
self._set_state(self.driver.state())
|
| 53 |
+
|
| 54 |
+
def true_eef(self):
|
| 55 |
+
return np.asarray(self._state["eef_pos"], float)
|
| 56 |
+
|
| 57 |
+
def believed_eef(self):
|
| 58 |
+
return self.true_eef() - self.bias
|
| 59 |
+
|
| 60 |
+
def proprio(self):
|
| 61 |
+
st = self._state
|
| 62 |
+
return dict(eef_pos=_r(self.believed_eef()), eef_yaw_deg=round(float(st["eef_yaw_deg"]), 1),
|
| 63 |
+
gripper="closed" if self.grip_closed else "open",
|
| 64 |
+
gripper_width_m=round(float(st["gripper_width_m"]), 4))
|
| 65 |
+
|
| 66 |
+
def joints(self):
|
| 67 |
+
"""Joint angles as the robot's encoders would report them under the hidden calibration error."""
|
| 68 |
+
if not np.any(self.bias):
|
| 69 |
+
return [float(v) for v in self._state["joint_pos_rad"]]
|
| 70 |
+
key = (tuple(self._state["eef_pos"]), float(self._state["eef_yaw_deg"]))
|
| 71 |
+
if getattr(self, "_ik_key", None) != key: # one /ik per new state (the server asks several times per command)
|
| 72 |
+
self._ik_key = key
|
| 73 |
+
self._ik_val = [float(v) for v in self.driver.ik(self.believed_eef(), key[1])]
|
| 74 |
+
return list(self._ik_val)
|
| 75 |
+
|
| 76 |
+
def observe(self, label=""):
|
| 77 |
+
frames, st = self.driver.observe()
|
| 78 |
+
self._set_state(st)
|
| 79 |
+
return [ImageRef(camera=c, array=square_resize(frames[c], self.image_res), label=f"{label} {c}".strip())
|
| 80 |
+
for c in self.cams]
|
| 81 |
+
|
| 82 |
+
# ------------------------------------------------------------------ helpers
|
| 83 |
+
def wrap_yaw(self, yaw):
|
| 84 |
+
"""The two-finger gripper is symmetric: among yaw + k*180 inside the driver's yaw range, use the one closest to
|
| 85 |
+
the last commanded yaw (Skills.wrap_yaw does the same with its +-113 deg limit)."""
|
| 86 |
+
cands = [yaw + 180.0 * k for k in range(-3, 4)]
|
| 87 |
+
ok = [c for c in cands if self.yaw_lo <= c <= self.yaw_hi] or cands
|
| 88 |
+
return float(min(ok, key=lambda c: abs(c - self.yaw_cmd)))
|
| 89 |
+
|
| 90 |
+
# ------------------------------------------------------------------ dispatch (same signature as ToolExecutor.call)
|
| 91 |
+
def call(self, name, raw_args):
|
| 92 |
+
t0 = time.time()
|
| 93 |
+
self.n_calls += 1
|
| 94 |
+
args = parse_args(raw_args)
|
| 95 |
+
fn = getattr(self, f"_t_{name}", None)
|
| 96 |
+
if fn is None:
|
| 97 |
+
return ToolResult(name, args, False, dict(ok=False, error=f"unknown tool {name!r}"), wall_s=time.time() - t0)
|
| 98 |
+
res = fn(**args)
|
| 99 |
+
res.args, res.wall_s = args, time.time() - t0
|
| 100 |
+
return res
|
| 101 |
+
|
| 102 |
+
def _report(self, name, extra=None):
|
| 103 |
+
rep = dict(ok=True, tool=name)
|
| 104 |
+
rep.update(extra or {})
|
| 105 |
+
rep.update(self.proprio())
|
| 106 |
+
return rep
|
| 107 |
+
|
| 108 |
+
def _t_move_to(self, x, y, z, yaw, speed=None):
|
| 109 |
+
tgt = np.array([x, y, z], float)
|
| 110 |
+
if not np.all(np.isfinite(tgt)):
|
| 111 |
+
return ToolResult("move_to", {}, False, dict(ok=False, error="non-finite coordinates"))
|
| 112 |
+
spd = None if speed is None else float(np.clip(float(speed), SPEED_MIN, self.max_speed))
|
| 113 |
+
yaw_used = self.wrap_yaw(float(yaw))
|
| 114 |
+
cmd = tgt + self.bias # the hidden calibration error acts on every commanded position
|
| 115 |
+
rep = self.driver.move(cmd[0], cmd[1], cmd[2], yaw_used, spd)
|
| 116 |
+
self.motion_s += float(rep.get("motion_s") or 0.0)
|
| 117 |
+
self._set_state(rep["state"])
|
| 118 |
+
if not rep["ok"]: # rejected before moving (driver hard limits / no IK solution)
|
| 119 |
+
return ToolResult("move_to", {}, False, dict(ok=False, error="target rejected: the arm cannot reach it; "
|
| 120 |
+
"the arm did not move", driver_error=rep.get("error", "")))
|
| 121 |
+
self.yaw_cmd = yaw_used
|
| 122 |
+
reached = bool(np.linalg.norm(cmd - self.true_eef()) < 0.02)
|
| 123 |
+
return ToolResult("move_to", {}, True, self._report("move_to", dict(reached=reached,
|
| 124 |
+
yaw_used_deg=round(yaw_used, 1))))
|
| 125 |
+
|
| 126 |
+
def _gripper(self, close):
|
| 127 |
+
rep = self.driver.gripper(close)
|
| 128 |
+
self.grip_closed = bool(close)
|
| 129 |
+
self.motion_s += float(rep.get("motion_s") or 0.0)
|
| 130 |
+
self._set_state(rep["state"])
|
| 131 |
+
name = "close_gripper" if close else "open_gripper"
|
| 132 |
+
return ToolResult(name, {}, True, self._report(name))
|
| 133 |
+
|
| 134 |
+
def _t_open_gripper(self):
|
| 135 |
+
return self._gripper(False)
|
| 136 |
+
|
| 137 |
+
def _t_close_gripper(self):
|
| 138 |
+
return self._gripper(True)
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/l5_slide.py
ADDED
|
@@ -0,0 +1,577 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L5-A slide_to_target: strike the cube so that it slides on its own and comes to rest inside the target zone.
|
| 2 |
+
|
| 3 |
+
Hidden variable: cube-table sliding friction mu (log-uniform in [0.035, 0.10]) -- the cube looks the
|
| 4 |
+
same for every mu. With the default push speed the cube overshoots on slippery instances and stops
|
| 5 |
+
short on grippy ones; the only way to get it right is to infer from where the cube stopped how hard
|
| 6 |
+
to push next time (cf. MemMimic push_cube, iterative pushing).
|
| 7 |
+
|
| 8 |
+
Strikes per attempt: not limited (2026-10-19, user). From 2026-10-08 the instruction allowed ONE strike per attempt
|
| 9 |
+
(one move command pushing the cube, the gripper advancing at most 4 cm after the first touch), to stop slow pushes that
|
| 10 |
+
carry the cube to the target so that friction never matters (exp1 / cla1 Claude, la2 GPT: 0.05 m/s pushes). That rule
|
| 11 |
+
also moved within-attempt correction (overshot -> fetch the cube back -> strike again) to the next attempt. The
|
| 12 |
+
loophole is now closed by the success rule instead:
|
| 13 |
+
|
| 14 |
+
Success: when the attempt ends the cube is at rest, on the table, in the square (see "Target" below), AND it got there
|
| 15 |
+
by a free slide of at least D_MIN: from the last moment the robot touched it (any robot or gripper geom, contacts
|
| 16 |
+
checked at every 2 ms physics substep; holding it counts as touching) to its final position the cube slid >= D_MIN with
|
| 17 |
+
nothing touching it. A touch that leaves a resting cube where it was (< 1 mm) is ignored. This fails a quasi-static push
|
| 18 |
+
into the square (free slide 0-1.2 cm measured), placing the cube there with the gripper (0 cm) and putting it just in
|
| 19 |
+
front of the square and tapping it (< D_MIN); see the task card for the adversarial checks and why D_MIN = 3 cm.
|
| 20 |
+
|
| 21 |
+
Error events: every strike (a robot contact that moved the cube followed by a free slide of >= STRIKE_MIN) is logged
|
| 22 |
+
when the cube comes to rest; it is "missed" if the cube then lies outside the square (past / short / beside).
|
| 23 |
+
`n_missed_strikes`, `trap_fired` (>= 1 missed strike) and `recovered_in_attempt` (trap fired and the attempt then
|
| 24 |
+
succeeded) are in the outcome, as in l7_key_turn; `irrecoverable` = the cube fell off the table or lies outside the
|
| 25 |
+
arm's reach (the attempt is not ended for it).
|
| 26 |
+
|
| 27 |
+
Observation fix (2026-10-19): a strike used to return while the cube was still sliding, and `observe` does not advance
|
| 28 |
+
the simulation, so agents saw the cube half-way (cla2: "2.2 cm short", it then slid to 7.0 cm past the centre).
|
| 29 |
+
SlideSkills.move_to / set_gripper now hold the arm still after the motion until the cube is at rest (or WAIT_MAX),
|
| 30 |
+
so every reply and image shows the cube where it stopped. The waiting time counts as simulated motion time.
|
| 31 |
+
|
| 32 |
+
Target (2026-10-19, user; before: completely inside the square on all four sides, centre within +-1 cm): the agentview
|
| 33 |
+
camera looks at the square from the far side (the cube is pushed towards it), and a cube that sticks out past the far
|
| 34 |
+
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
|
| 35 |
+
"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
|
| 36 |
+
the far green line: the instruction says it must not stick out beyond that line; judged, its centre may be up to
|
| 37 |
+
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
|
| 38 |
+
of 25 measured instances shows >= 2 px of red beyond the line (task card). The near side and the sides stay "completely
|
| 39 |
+
inside" (+-1 cm): the near-side band cannot be made visible in the agentview by any tolerance (the cube's own body hides
|
| 40 |
+
the near line), and relaxing it would let the 0.30 m/s strike pass on short-stopping instances (task card).
|
| 41 |
+
"""
|
| 42 |
+
import numpy as np
|
| 43 |
+
|
| 44 |
+
from .. import envs
|
| 45 |
+
from ..bddl import write_bddl
|
| 46 |
+
from ..objects import _fmt, _wrap, box_xml, register_generated
|
| 47 |
+
from ..skills import DT, Skills, _rot_err
|
| 48 |
+
from ..task_base import LFFTask, register_task
|
| 49 |
+
|
| 50 |
+
CUBE = "cube_1"
|
| 51 |
+
CUBE_HALF = 0.02
|
| 52 |
+
D_MIN = 0.03 # the cube's last free slide (after its last contact with the robot) must be at least this long
|
| 53 |
+
STRIKE_MIN = 0.01 # a contact that moved the cube, followed by a free slide of >= 1 cm, counts as a strike
|
| 54 |
+
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
|
| 55 |
+
EP_GAP = 25 # physics substeps (one control step, 50 ms) without robot contact end a contact episode
|
| 56 |
+
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 ...
|
| 57 |
+
REST_SUB = 25 # ... for 25 consecutive substeps (50 ms)
|
| 58 |
+
WAIT_MAX = 100 # control steps (5 s) a command may hold the arm waiting for the cube to come to rest
|
| 59 |
+
ON_TABLE = 0.005 # cube resting on the table: centre within 5 mm of TABLE_Z + CUBE_HALF
|
| 60 |
+
OFF_TABLE_Z = envs.TABLE_Z - 0.05 # cube centre below this: it fell off the table
|
| 61 |
+
REACH_MARGIN = 0.03 # cube centre this close to the commanded-target limits (agent/tools.py WS_LO / WS_HI): unreachable
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class CubeWatch:
|
| 65 |
+
"""Follows the cube at every physics substep (installed on env.sim by reset_instance; outcome() reads it).
|
| 66 |
+
|
| 67 |
+
contact episode: substeps with a robot-cube contact, merged across gaps shorter than EP_GAP substeps. Closed
|
| 68 |
+
EP_GAP substeps after its last contact; it "moved" the cube if the cube is then >= TOUCH_MOVE from where it was
|
| 69 |
+
when the episode began, or still moving.
|
| 70 |
+
release: the cube's xy at the last contact of the last episode that moved it, i.e. where its current free slide
|
| 71 |
+
began (None while the robot has never moved the cube).
|
| 72 |
+
strike: an episode that moved the cube followed by a free slide of >= STRIKE_MIN, logged when the cube comes to
|
| 73 |
+
rest (or when the robot touches it again before that: result "interrupted")."""
|
| 74 |
+
|
| 75 |
+
def __init__(self, env, target_xy, tol_short, tol_past, tol_across):
|
| 76 |
+
m = env.sim.model
|
| 77 |
+
self.env = env
|
| 78 |
+
self.is_robot = np.zeros(m.ngeom, bool)
|
| 79 |
+
self.is_robot[envs.robot_geom_ids(env)] = True
|
| 80 |
+
self.is_cube = np.zeros(m.ngeom, bool)
|
| 81 |
+
self.is_cube[envs.obj_geom_ids(env, CUBE)] = True
|
| 82 |
+
self.qa, self.da = envs.free_joint_addr(env, CUBE)
|
| 83 |
+
self.target = np.asarray(target_xy, float)
|
| 84 |
+
self.tol = (float(tol_short), float(tol_past), float(tol_across)) # centre offsets: short of / past / beside
|
| 85 |
+
self.n_sub = 0
|
| 86 |
+
self.ep = None # open contact episode
|
| 87 |
+
self.gap = 0
|
| 88 |
+
self.quiet = 0 # consecutive substeps at rest
|
| 89 |
+
self.release = None
|
| 90 |
+
self.slide = None # free slide in progress: where it started (cube at the episode start) and was released
|
| 91 |
+
self.moves = [] # closed contact episodes that moved the cube
|
| 92 |
+
self.strikes = []
|
| 93 |
+
|
| 94 |
+
# ------------------------------------------------------------ state
|
| 95 |
+
def pos(self):
|
| 96 |
+
return self.env.sim.data.qpos[self.qa:self.qa + 3].copy()
|
| 97 |
+
|
| 98 |
+
def at_rest(self):
|
| 99 |
+
qv = self.env.sim.data.qvel[self.da:self.da + 6]
|
| 100 |
+
return bool(np.linalg.norm(qv[:3]) < V_REST and np.linalg.norm(qv[3:]) < W_REST)
|
| 101 |
+
|
| 102 |
+
def judge(self, p):
|
| 103 |
+
"""Where a cube at p lies relative to the square: (along, across, in / past / short / beside / off).
|
| 104 |
+
in = centre at most tol_short short of / tol_past past the square's centre and within tol_across beside it."""
|
| 105 |
+
along, across = float(p[0] - self.target[0]), float(p[1] - self.target[1])
|
| 106 |
+
if abs(p[2] - (envs.TABLE_Z + CUBE_HALF)) > ON_TABLE:
|
| 107 |
+
return along, across, "off"
|
| 108 |
+
short, past, beside = self.tol
|
| 109 |
+
if -short <= along <= past and abs(across) <= beside:
|
| 110 |
+
return along, across, "in"
|
| 111 |
+
if along > past:
|
| 112 |
+
return along, across, "past"
|
| 113 |
+
if along < -short:
|
| 114 |
+
return along, across, "short"
|
| 115 |
+
return along, across, "beside"
|
| 116 |
+
|
| 117 |
+
# ------------------------------------------------------------ per substep
|
| 118 |
+
def substep(self):
|
| 119 |
+
d = self.env.sim.data
|
| 120 |
+
n = d.ncon
|
| 121 |
+
touch = False
|
| 122 |
+
if n:
|
| 123 |
+
g1 = np.asarray(d.contact.geom1)[:n]
|
| 124 |
+
g2 = np.asarray(d.contact.geom2)[:n]
|
| 125 |
+
touch = bool(np.any((self.is_robot[g1] & self.is_cube[g2]) | (self.is_robot[g2] & self.is_cube[g1])))
|
| 126 |
+
self.n_sub += 1
|
| 127 |
+
p = self.pos()
|
| 128 |
+
rest = self.at_rest()
|
| 129 |
+
self.quiet = self.quiet + 1 if rest else 0
|
| 130 |
+
if touch:
|
| 131 |
+
if self.ep is None:
|
| 132 |
+
if self.slide is not None:
|
| 133 |
+
self._end_slide(p, interrupted=not rest)
|
| 134 |
+
self.ep = dict(start=p, sub0=self.n_sub)
|
| 135 |
+
self.ep["last"] = p
|
| 136 |
+
self.ep["sub1"] = self.n_sub
|
| 137 |
+
self.gap = 0
|
| 138 |
+
elif self.ep is not None:
|
| 139 |
+
self.gap += 1
|
| 140 |
+
if self.gap >= EP_GAP:
|
| 141 |
+
self._close(p, rest)
|
| 142 |
+
if self.ep is None and self.slide is not None and self.quiet >= REST_SUB:
|
| 143 |
+
self._end_slide(p, interrupted=False)
|
| 144 |
+
|
| 145 |
+
def _close(self, p, rest):
|
| 146 |
+
ep, self.ep = self.ep, None
|
| 147 |
+
if np.linalg.norm(p - ep["start"]) < TOUCH_MOVE and rest:
|
| 148 |
+
return # touched a resting cube and left it where it was
|
| 149 |
+
self.release = ep["last"][:2].copy()
|
| 150 |
+
self.moves.append(dict(sub0=ep["sub0"], sub1=ep["sub1"], start=ep["start"].round(4).tolist(),
|
| 151 |
+
release=ep["last"].round(4).tolist()))
|
| 152 |
+
self.slide = dict(start=ep["start"], release=ep["last"], sub=ep["sub1"])
|
| 153 |
+
|
| 154 |
+
def _end_slide(self, p, interrupted):
|
| 155 |
+
s, self.slide = self.slide, None
|
| 156 |
+
free = float(np.linalg.norm(p[:2] - s["release"][:2]))
|
| 157 |
+
if free < STRIKE_MIN:
|
| 158 |
+
return # a push or a put-down, not a strike
|
| 159 |
+
along, across, res = self.judge(p)
|
| 160 |
+
self.strikes.append(dict(sub=int(s["sub"]), start=s["start"].round(4).tolist(),
|
| 161 |
+
release=s["release"].round(4).tolist(), rest=p.round(4).tolist(),
|
| 162 |
+
pushed_cm=round(100 * float(np.linalg.norm(s["release"][:2] - s["start"][:2])), 2),
|
| 163 |
+
free_slide_cm=round(100 * free, 2), along_err_cm=round(100 * along, 2),
|
| 164 |
+
across_err_cm=round(100 * across, 2),
|
| 165 |
+
result="interrupted" if interrupted else res,
|
| 166 |
+
missed=bool(not interrupted and res != "in")))
|
| 167 |
+
|
| 168 |
+
def flush(self):
|
| 169 |
+
"""End of attempt: settle the bookkeeping. Returns True if the robot is touching the cube now and that contact
|
| 170 |
+
has moved it (then the cube's current free slide is 0)."""
|
| 171 |
+
p = self.pos()
|
| 172 |
+
if self.ep is not None:
|
| 173 |
+
if np.linalg.norm(p - self.ep["start"]) >= TOUCH_MOVE or not self.at_rest():
|
| 174 |
+
self.release = p[:2].copy()
|
| 175 |
+
self.slide = None
|
| 176 |
+
return True
|
| 177 |
+
return False
|
| 178 |
+
if self.slide is not None and self.at_rest():
|
| 179 |
+
self._end_slide(p, interrupted=False)
|
| 180 |
+
return False
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def _install_watch(sim, watch):
|
| 184 |
+
"""Call watch.substep() after every MuJoCo step of this sim (one wrapper per sim, like agent/tools.ContactTracker;
|
| 185 |
+
it only reads the state). A fast strike touches the cube for 3-16 substeps (6-32 ms, measured), less than one
|
| 186 |
+
control step, so contact checks at control steps alone would miss it."""
|
| 187 |
+
if not getattr(sim, "_lff_slide_wrapped", False):
|
| 188 |
+
orig = sim.step
|
| 189 |
+
|
| 190 |
+
def step(*a, **k):
|
| 191 |
+
orig(*a, **k)
|
| 192 |
+
w = getattr(sim, "_lff_slide_watch", None)
|
| 193 |
+
if w is not None:
|
| 194 |
+
w.substep()
|
| 195 |
+
sim.step = step
|
| 196 |
+
sim._lff_slide_wrapped = True
|
| 197 |
+
sim._lff_slide_watch = watch
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class SlideSkills(Skills):
|
| 201 |
+
"""Skills whose motion commands return only once the cube has come to rest (see the module docstring)."""
|
| 202 |
+
|
| 203 |
+
def __init__(self, env, bias=None, recorder=None):
|
| 204 |
+
super().__init__(env, bias=bias, recorder=recorder)
|
| 205 |
+
self._qa, self._da = envs.free_joint_addr(env, CUBE)
|
| 206 |
+
self.waits = [] # (control step, steps waited) for every command that had to wait
|
| 207 |
+
|
| 208 |
+
def cube_moving(self):
|
| 209 |
+
qv = self.env.sim.data.qvel[self._da:self._da + 6]
|
| 210 |
+
return bool(np.linalg.norm(qv[:3]) >= V_REST or np.linalg.norm(qv[3:]) >= W_REST)
|
| 211 |
+
|
| 212 |
+
def wait_cube_rest(self):
|
| 213 |
+
"""Hold the arm where it is until the cube is at rest (two control steps in a row) or WAIT_MAX steps passed.
|
| 214 |
+
No wait if the cube is already at rest or is held (it then moves with the arm)."""
|
| 215 |
+
if not self.cube_moving() or self.holding(CUBE):
|
| 216 |
+
return 0
|
| 217 |
+
p, R = self.eef_pos(), self._R()
|
| 218 |
+
quiet = 0
|
| 219 |
+
for k in range(WAIT_MAX):
|
| 220 |
+
self._act(p - self.eef_pos(), _rot_err(R, self.eef_mat()), self.grip)
|
| 221 |
+
quiet = 0 if self.cube_moving() else quiet + 1
|
| 222 |
+
if quiet >= 2:
|
| 223 |
+
break
|
| 224 |
+
self.waits.append((self.n_steps, k + 1))
|
| 225 |
+
return k + 1
|
| 226 |
+
|
| 227 |
+
def move_to(self, target, *args, **kwargs):
|
| 228 |
+
rep = super().move_to(target, *args, **kwargs)
|
| 229 |
+
n = self.wait_cube_rest()
|
| 230 |
+
if n:
|
| 231 |
+
rep["waited_s"] = round(n * DT, 2)
|
| 232 |
+
return rep
|
| 233 |
+
|
| 234 |
+
def set_gripper(self, close, steps=15):
|
| 235 |
+
rep = super().set_gripper(close, steps)
|
| 236 |
+
n = self.wait_cube_rest()
|
| 237 |
+
if n:
|
| 238 |
+
rep["waited_s"] = round(n * DT, 2)
|
| 239 |
+
return rep
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
INNER_HALF = 0.03 # 6 cm square target (inner edge of the outline): near side and sides, the cube's centre within 1 cm
|
| 243 |
+
LINE_W = 0.006
|
| 244 |
+
# Far side (away from the robot, facing the agentview camera): the cube may lie on the far line. Instruction: no part of
|
| 245 |
+
# it beyond the line's outer edge (centre <= INNER_HALF + LINE_W - CUBE_HALF = 1.6 cm past the centre); judged: centre
|
| 246 |
+
# <= 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
|
| 247 |
+
# beyond the line (from 2.0 cm on >= 2 px on all 25 measured instances, task card 2026-10-19).
|
| 248 |
+
TOL_PAST = 0.020
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def square_frame_xml(model_name, inner_half=INNER_HALF, line_w=LINE_W,
|
| 252 |
+
line_rgba=(0.1, 0.55, 0.15, 1.0), fill_rgba=(0.75, 0.92, 0.75, 1.0)):
|
| 253 |
+
"""Flat, visual-only square drawn on the table: a light fill plus a dark outline (no collisions)."""
|
| 254 |
+
o = inner_half + line_w
|
| 255 |
+
parts = [((0, 0, 0.0004), (o, o, 0.0004), fill_rgba),
|
| 256 |
+
((0, inner_half + line_w / 2, 0.0010), (o, line_w / 2, 0.0002), line_rgba),
|
| 257 |
+
((0, -inner_half - line_w / 2, 0.0010), (o, line_w / 2, 0.0002), line_rgba),
|
| 258 |
+
((inner_half + line_w / 2, 0, 0.0010), (line_w / 2, o, 0.0002), line_rgba),
|
| 259 |
+
((-inner_half - line_w / 2, 0, 0.0010), (line_w / 2, o, 0.0002), line_rgba)]
|
| 260 |
+
g = "\n".join(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(c)}" '
|
| 261 |
+
f'contype="0" conaffinity="0" group="1" />' for p, sz, c in parts)
|
| 262 |
+
return _wrap(model_name, g, 0.0012, o)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
Z_PUSH = envs.TABLE_Z + 0.02
|
| 266 |
+
V_MIN, V_MAX = 0.12, 0.60
|
| 267 |
+
Z_GRASP = envs.TABLE_Z + CUBE_HALF # grasp point at the cube's centre height (fingertips ~1 cm above the table)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
@register_task
|
| 271 |
+
class SlideToTarget(LFFTask):
|
| 272 |
+
name = "l5_slide_to_target"
|
| 273 |
+
level = "L5"
|
| 274 |
+
category = "dynamics_adaptation"
|
| 275 |
+
capabilities = ("Reason", "Utilize")
|
| 276 |
+
# no parentheses or semicolons: the instruction is also the BDDL :language string (';' starts a comment there)
|
| 277 |
+
instruction = ("Push the red cube straight away from the robot so that it slides and comes to rest in the green "
|
| 278 |
+
"square marked on the table. On the side of the square nearest the robot and on its left and "
|
| 279 |
+
"right, no part of the cube may lie on or beyond the green border line. On the far side, away from "
|
| 280 |
+
"the robot, the cube may lie on the border line, but no part of it may stick out beyond that line. "
|
| 281 |
+
"The cube must slide the last part of the way on its own: after it leaves the gripper it has to "
|
| 282 |
+
f"slide at least {100 * D_MIN:.0f} cm, with nothing touching it, before it comes to rest in the "
|
| 283 |
+
"square.")
|
| 284 |
+
instruction_indirect = instruction
|
| 285 |
+
tol_along = INNER_HALF - CUBE_HALF # short of the centre (near side): completely inside the square (1.0 cm)
|
| 286 |
+
tol_past = TOL_PAST # past the centre (far side): may lie on the far line (2.0 cm, see TOL_PAST)
|
| 287 |
+
runup = 0.22 # long run-up so the gripper reaches the commanded speed before contact
|
| 288 |
+
tol_across = INNER_HALF - CUBE_HALF
|
| 289 |
+
|
| 290 |
+
def make_bddl(self):
|
| 291 |
+
cube = register_generated("LffRedCube", box_xml("lff_red_cube", (CUBE_HALF,) * 3, (0.85, 0.15, 0.15, 1),
|
| 292 |
+
density=1000))
|
| 293 |
+
# static fixture (no joint): a free body without collisions would fall through the table
|
| 294 |
+
zone = register_generated("LffTargetSquare", square_frame_xml("lff_target_square"), free=False)
|
| 295 |
+
objs = [("cube_1", cube, "cube_region", (-0.21, -0.01, -0.19, 0.01))]
|
| 296 |
+
fixtures = [("zone_1", zone, "zone_region", (-0.11, -0.01, -0.09, 0.01))]
|
| 297 |
+
return write_bddl(self.name, self.instruction, objs, fixtures=fixtures)
|
| 298 |
+
|
| 299 |
+
def apply_instance(self, inst):
|
| 300 |
+
m = self.env.sim.model
|
| 301 |
+
zone = self.env.fixtures_dict["zone_1"]
|
| 302 |
+
# the target zone is a flat marker: no collisions
|
| 303 |
+
for g in range(m.ngeom):
|
| 304 |
+
if (m.geom_id2name(g) or "").startswith("zone_1_"):
|
| 305 |
+
m.geom_contype[g] = 0
|
| 306 |
+
m.geom_conaffinity[g] = 0
|
| 307 |
+
x0, y0 = inst["cube_xy"]
|
| 308 |
+
envs.set_obj_pose(self.env, "cube_1", [x0, y0, envs.TABLE_Z + CUBE_HALF + 0.001])
|
| 309 |
+
bid = m.body_name2id(zone.root_body)
|
| 310 |
+
m.body_pos[bid] = [x0 + inst["target_dist"], y0, envs.TABLE_Z + 0.0002]
|
| 311 |
+
m.body_quat[bid] = [1.0, 0.0, 0.0, 0.0]
|
| 312 |
+
envs.set_friction(self.env, "cube_1", inst["mu"])
|
| 313 |
+
|
| 314 |
+
def reset_instance(self, inst, recorder=None):
|
| 315 |
+
self.env.reset()
|
| 316 |
+
self.apply_instance(inst)
|
| 317 |
+
self.env.sim.forward()
|
| 318 |
+
envs.settle(self.env, 10)
|
| 319 |
+
x0, y0 = inst["cube_xy"]
|
| 320 |
+
self.watch = CubeWatch(self.env, (x0 + inst["target_dist"], y0), self.tol_along, self.tol_past,
|
| 321 |
+
self.tol_across)
|
| 322 |
+
_install_watch(self.env.sim, self.watch)
|
| 323 |
+
self.sk = SlideSkills(self.env, recorder=recorder)
|
| 324 |
+
return self.sk
|
| 325 |
+
|
| 326 |
+
@staticmethod
|
| 327 |
+
def max_reach(mu):
|
| 328 |
+
"""Approximate slide distance at the top speed, fitted to a sweep (runup 0.22 m):
|
| 329 |
+
mu 0.04 -> 20.8 cm, 0.06 -> 14.8, 0.08 -> 11.8, 0.10 -> 10.1 cm."""
|
| 330 |
+
return 0.0103 / mu ** 0.95
|
| 331 |
+
|
| 332 |
+
def sample_instance(self, seed):
|
| 333 |
+
rng = np.random.default_rng(seed)
|
| 334 |
+
while True: # reject instances the top speed cannot reach (keeps every instance solvable)
|
| 335 |
+
inst = dict(seed=int(seed),
|
| 336 |
+
cube_xy=[float(rng.uniform(-0.23, -0.17)), float(rng.uniform(-0.10, 0.10))],
|
| 337 |
+
target_dist=float(rng.uniform(0.05, 0.12)),
|
| 338 |
+
mu=float(np.exp(rng.uniform(np.log(0.035), np.log(0.10)))))
|
| 339 |
+
if inst["target_dist"] <= 0.85 * self.max_reach(inst["mu"]):
|
| 340 |
+
return inst
|
| 341 |
+
|
| 342 |
+
# ------------------------------------------------------------ outcome
|
| 343 |
+
def outcome(self, inst):
|
| 344 |
+
envs.settle(self.env, 40)
|
| 345 |
+
w = self.watch
|
| 346 |
+
for _ in range(12): # still moving (e.g. a budget ended the attempt mid-slide): let it come to rest
|
| 347 |
+
if w.at_rest():
|
| 348 |
+
break
|
| 349 |
+
envs.settle(self.env, 5)
|
| 350 |
+
touching = w.flush()
|
| 351 |
+
x0, y0 = inst["cube_xy"]
|
| 352 |
+
c = envs.obj_pos(self.env, CUBE)
|
| 353 |
+
along = (c[0] - x0) - inst["target_dist"]
|
| 354 |
+
across = c[1] - y0
|
| 355 |
+
_, _, where = w.judge(w.pos())
|
| 356 |
+
inside = where == "in"
|
| 357 |
+
at_rest = w.at_rest()
|
| 358 |
+
free = float(np.linalg.norm(c[:2] - w.release)) if w.release is not None else 0.0
|
| 359 |
+
slid = bool(w.release is not None and not touching and free >= D_MIN)
|
| 360 |
+
success = bool(inside and at_rest and slid)
|
| 361 |
+
strikes = w.strikes
|
| 362 |
+
n_missed = sum(s["missed"] for s in strikes)
|
| 363 |
+
from ..agent.tools import WS_HI, WS_LO
|
| 364 |
+
reach = bool(np.all(c[:2] >= WS_LO[:2] + REACH_MARGIN) and np.all(c[:2] <= WS_HI[:2] - REACH_MARGIN))
|
| 365 |
+
irrecoverable = bool(c[2] < OFF_TABLE_Z or not reach)
|
| 366 |
+
|
| 367 |
+
parts = []
|
| 368 |
+
if w.release is None and np.linalg.norm(c[:2] - np.asarray(inst["cube_xy"])) < STRIKE_MIN:
|
| 369 |
+
parts.append("The cube was not pushed.")
|
| 370 |
+
if c[2] < OFF_TABLE_Z:
|
| 371 |
+
parts.append("The cube fell off the table.")
|
| 372 |
+
else:
|
| 373 |
+
state = {"in": "in the square", "past": "it sticks out beyond the far green line",
|
| 374 |
+
"short": "it sticks out past the edge of the square nearest the robot"}.get(where,
|
| 375 |
+
"not in the square")
|
| 376 |
+
if along > 0:
|
| 377 |
+
parts.append(f"The cube stopped {100 * along:.1f} cm past the centre of the green square ({state}).")
|
| 378 |
+
else:
|
| 379 |
+
parts.append(f"The cube stopped {100 * -along:.1f} cm short of the centre of the green square "
|
| 380 |
+
f"({state}).")
|
| 381 |
+
if abs(across) > self.tol_across:
|
| 382 |
+
parts.append(f"It also drifted {100 * abs(across):.1f} cm to the {'left' if across > 0 else 'right'} "
|
| 383 |
+
f"(robot's view).")
|
| 384 |
+
if where == "off" and c[2] > OFF_TABLE_Z:
|
| 385 |
+
parts.append("It is not resting on the table.")
|
| 386 |
+
if inside and not at_rest:
|
| 387 |
+
parts.append("It was still moving when the attempt ended.")
|
| 388 |
+
if touching:
|
| 389 |
+
parts.append("The gripper was still touching (or holding) the cube when the attempt ended.")
|
| 390 |
+
elif inside and w.release is not None and free < D_MIN:
|
| 391 |
+
parts.append(f"After it last left the gripper it slid only {100 * free:.1f} cm on its own; it has to slide "
|
| 392 |
+
f"at least {100 * D_MIN:.0f} cm.")
|
| 393 |
+
if success:
|
| 394 |
+
failure = None
|
| 395 |
+
elif w.release is None and not inside:
|
| 396 |
+
failure = "not_touched"
|
| 397 |
+
elif not inside:
|
| 398 |
+
failure = "position"
|
| 399 |
+
elif not at_rest:
|
| 400 |
+
failure = "not_at_rest"
|
| 401 |
+
else:
|
| 402 |
+
failure = "slide_too_short"
|
| 403 |
+
out = dict(success=success, along_err=float(along), across_err=float(across), detail=" ".join(parts),
|
| 404 |
+
inside=inside, at_rest=at_rest, free_slide_cm=round(100 * free, 2),
|
| 405 |
+
release_xy=None if w.release is None else w.release.round(4).tolist(),
|
| 406 |
+
touching_at_end=bool(touching), n_moves=len(w.moves), n_strikes=len(strikes),
|
| 407 |
+
n_missed_strikes=int(n_missed), trap_fired=n_missed > 0,
|
| 408 |
+
recovered_in_attempt=bool(n_missed and success), irrecoverable=irrecoverable,
|
| 409 |
+
strikes=strikes, waits=len(getattr(self.sk, "waits", [])), failure=failure)
|
| 410 |
+
return out
|
| 411 |
+
|
| 412 |
+
# ------------------------------------------------------------ execution
|
| 413 |
+
def execute(self, inst, params):
|
| 414 |
+
"""One straight strike from the cube's initial position: closed gripper, 22 cm run-up, stop 1.5 cm past the
|
| 415 |
+
point of contact, lift (the move returns once the cube has come to rest)."""
|
| 416 |
+
x0, y0 = inst["cube_xy"]
|
| 417 |
+
sk = self.sk
|
| 418 |
+
sk.set_gripper(True, steps=5)
|
| 419 |
+
sk.move_to([x0 - self.runup, y0, Z_PUSH + 0.10], yaw=0.0)
|
| 420 |
+
sk.move_to([x0 - self.runup, y0, Z_PUSH], tol=0.003)
|
| 421 |
+
sk.move_to([x0 - CUBE_HALF + 0.015, y0, Z_PUSH], speed=float(np.clip(params["speed"], V_MIN, V_MAX)),
|
| 422 |
+
tol=0.01, max_steps=80)
|
| 423 |
+
sk.move_to([x0 - CUBE_HALF + 0.015, y0, Z_PUSH + 0.08], speed=0.3)
|
| 424 |
+
|
| 425 |
+
def default_params(self, inst):
|
| 426 |
+
return dict(speed=0.30)
|
| 427 |
+
|
| 428 |
+
def blind_params(self, inst, attempt, rng):
|
| 429 |
+
return dict(speed=float(np.clip(0.30 + rng.normal(0, 0.05), V_MIN, V_MAX)))
|
| 430 |
+
|
| 431 |
+
def adapt_params(self, inst, history):
|
| 432 |
+
"""Cross-attempt learner (one strike per attempt; used by the scripted agent backend): bracketing secant search
|
| 433 |
+
on speed using the signed stopping error. validate.py's adaptive policy is run_scripted (within the attempt)."""
|
| 434 |
+
pts = sorted((h["params"]["speed"], h["outcome"]["along_err"]) for h in history)
|
| 435 |
+
lo = [p for p in pts if p[1] < 0]
|
| 436 |
+
hi = [p for p in pts if p[1] > 0]
|
| 437 |
+
if lo and hi:
|
| 438 |
+
(v0, e0), (v1, e1) = max(lo, key=lambda p: p[0]), min(hi, key=lambda p: p[0])
|
| 439 |
+
v = v0 + (v1 - v0) * (-e0) / (e1 - e0)
|
| 440 |
+
elif hi: # always overshooting: slow down
|
| 441 |
+
v = min(p[0] for p in hi) * 0.7
|
| 442 |
+
else: # always short: speed up
|
| 443 |
+
v = max(p[0] for p in lo) * 1.35
|
| 444 |
+
return dict(speed=float(np.clip(v, V_MIN, V_MAX)))
|
| 445 |
+
|
| 446 |
+
def oracle_params(self, inst):
|
| 447 |
+
"""Privileged: bisection on speed by simulating pushes (uses the true mu)."""
|
| 448 |
+
if "_oracle_speed" in inst:
|
| 449 |
+
return dict(speed=inst["_oracle_speed"])
|
| 450 |
+
lo, hi = V_MIN, V_MAX
|
| 451 |
+
best = None
|
| 452 |
+
for _ in range(9):
|
| 453 |
+
mid = 0.5 * (lo + hi)
|
| 454 |
+
self.reset_instance(inst)
|
| 455 |
+
self.execute(inst, dict(speed=mid))
|
| 456 |
+
e = self.outcome(inst)["along_err"]
|
| 457 |
+
if best is None or abs(e) < abs(best[1]):
|
| 458 |
+
best = (mid, e)
|
| 459 |
+
if e > 0:
|
| 460 |
+
hi = mid
|
| 461 |
+
else:
|
| 462 |
+
lo = mid
|
| 463 |
+
inst["_oracle_speed"] = best[0]
|
| 464 |
+
self.reset_instance(inst)
|
| 465 |
+
return dict(speed=best[0])
|
| 466 |
+
|
| 467 |
+
# ------------------------------------------------------------ scripted within-attempt correction
|
| 468 |
+
AGENT_CMDS = 40 # robot_server default per-attempt budget (no agent_max_steps here): 40 commands ...
|
| 469 |
+
AGENT_SIM_S = 3.0 * AGENT_CMDS # ... and 3 s of simulated motion per command
|
| 470 |
+
RESTRIKE_MARGIN = 0.02 # strike again from where the cube stopped only if it is >= D_MIN + this short
|
| 471 |
+
|
| 472 |
+
def _strike_here(self, speed):
|
| 473 |
+
"""Strike the cube where it lies (perfect perception), straight towards +x. 4 agent commands: above the run-up
|
| 474 |
+
point + close, down, strike (returns at rest), lift."""
|
| 475 |
+
c = envs.obj_pos(self.env, CUBE)
|
| 476 |
+
sk = self.sk
|
| 477 |
+
sk.move_to([c[0] - self.runup, c[1], Z_PUSH + 0.10], yaw=0.0)
|
| 478 |
+
sk.set_gripper(True, steps=5)
|
| 479 |
+
sk.move_to([c[0] - self.runup, c[1], Z_PUSH], tol=0.003)
|
| 480 |
+
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,
|
| 481 |
+
max_steps=80)
|
| 482 |
+
sk.move_to([c[0] - CUBE_HALF + 0.015, c[1], Z_PUSH + 0.08], speed=0.3)
|
| 483 |
+
return 4
|
| 484 |
+
|
| 485 |
+
def _carry_back(self, inst):
|
| 486 |
+
"""Grasp the cube from above, carry it back to its initial position and put it down. 6 agent commands:
|
| 487 |
+
above it + open, down + close, lift, carry, down + open, lift."""
|
| 488 |
+
c = envs.obj_pos(self.env, CUBE)
|
| 489 |
+
x0, y0 = inst["cube_xy"]
|
| 490 |
+
sk = self.sk
|
| 491 |
+
sk.move_to([c[0], c[1], Z_GRASP + 0.10], yaw=0.0)
|
| 492 |
+
sk.set_gripper(False, steps=10)
|
| 493 |
+
sk.move_to([c[0], c[1], Z_GRASP], tol=0.003)
|
| 494 |
+
sk.set_gripper(True, steps=15)
|
| 495 |
+
sk.move_to([c[0], c[1], Z_GRASP + 0.06])
|
| 496 |
+
sk.move_to([x0, y0, Z_GRASP + 0.06])
|
| 497 |
+
sk.move_to([x0, y0, Z_GRASP + 0.003], tol=0.003)
|
| 498 |
+
sk.set_gripper(False, steps=12)
|
| 499 |
+
sk.move_to([x0, y0, Z_GRASP + 0.10])
|
| 500 |
+
return 6
|
| 501 |
+
|
| 502 |
+
@staticmethod
|
| 503 |
+
def _plan_speed(want, pts):
|
| 504 |
+
"""Speed for a slide of `want` m from strikes seen so far, pts = [(speed, slide)]: none -> the 0.30 m/s
|
| 505 |
+
prior; one -> slide ~ speed^2 through it; several -> log-log interpolation between the bracketing strikes
|
| 506 |
+
(or extrapolation from the two nearest, exponent clipped to [0.5, 3])."""
|
| 507 |
+
pts = sorted((v, d) for v, d in pts if d > 0.002)
|
| 508 |
+
if not pts:
|
| 509 |
+
return 0.30
|
| 510 |
+
if len(pts) == 1:
|
| 511 |
+
v, d = pts[0]
|
| 512 |
+
return float(np.clip(v * (want / d) ** 0.5, V_MIN, V_MAX))
|
| 513 |
+
lo = [p for p in pts if p[1] <= want]
|
| 514 |
+
hi = [p for p in pts if p[1] > want]
|
| 515 |
+
if lo and hi:
|
| 516 |
+
(v0, d0), (v1, d1) = max(lo, key=lambda p: p[1]), min(hi, key=lambda p: p[1])
|
| 517 |
+
else:
|
| 518 |
+
(v0, d0), (v1, d1) = sorted(pts, key=lambda p: abs(np.log(p[1] / want)))[:2]
|
| 519 |
+
if abs(np.log(d1 / d0)) < 1e-6 or abs(np.log(v1 / v0)) < 1e-6:
|
| 520 |
+
return float(np.clip(v0 * (want / d0) ** 0.5, V_MIN, V_MAX))
|
| 521 |
+
k = float(np.clip(np.log(d1 / d0) / np.log(v1 / v0), 0.5, 3.0))
|
| 522 |
+
return float(np.clip(v0 * (want / d0) ** (1.0 / k), V_MIN, V_MAX))
|
| 523 |
+
|
| 524 |
+
def _adaptive_attempt(self, inst, pts):
|
| 525 |
+
"""One attempt of the scripted within-attempt learner: strike; look where the cube stopped (perfect
|
| 526 |
+
perception, as on the images); if short by >= D_MIN + 2 cm strike again from there, otherwise (overshot,
|
| 527 |
+
a little short, or drifted sideways) carry it back to its initial position and strike again, with the speed
|
| 528 |
+
planned from every strike seen so far (`pts`, also from earlier attempts). Stops when the cube is in the square
|
| 529 |
+
or the next correction would not fit in the agent's command / motion budget."""
|
| 530 |
+
x0, y0 = inst["cube_xy"]
|
| 531 |
+
tx = x0 + inst["target_dist"]
|
| 532 |
+
sk = self.sk
|
| 533 |
+
n0 = sk.n_steps
|
| 534 |
+
n_cmd, speeds, path = 0, [], []
|
| 535 |
+
while True:
|
| 536 |
+
c = envs.obj_pos(self.env, CUBE)
|
| 537 |
+
want = tx - c[0]
|
| 538 |
+
near_start = np.linalg.norm(c[:2] - np.asarray(inst["cube_xy"])) < 0.01
|
| 539 |
+
local = [(v, d) for v, d, s in pts if s == near_start] or [(v, d) for v, d, _ in pts]
|
| 540 |
+
speed = self._plan_speed(want, local)
|
| 541 |
+
n_cmd += self._strike_here(speed)
|
| 542 |
+
c1 = envs.obj_pos(self.env, CUBE)
|
| 543 |
+
pts.append((speed, float(c1[0] - c[0]), near_start))
|
| 544 |
+
speeds.append(round(speed, 4))
|
| 545 |
+
err, across = float(c1[0] - tx), float(c1[1] - y0)
|
| 546 |
+
path.append("strike")
|
| 547 |
+
if -self.tol_along <= err <= self.tol_past and abs(across) <= self.tol_across:
|
| 548 |
+
break
|
| 549 |
+
used_s = (sk.n_steps - n0) * DT
|
| 550 |
+
if err < 0 and -err >= D_MIN + self.RESTRIKE_MARGIN and abs(across) < 0.005:
|
| 551 |
+
if n_cmd + 4 > self.AGENT_CMDS or used_s + 12.0 > self.AGENT_SIM_S:
|
| 552 |
+
break
|
| 553 |
+
continue
|
| 554 |
+
if n_cmd + 10 > self.AGENT_CMDS or used_s + 30.0 > self.AGENT_SIM_S:
|
| 555 |
+
break
|
| 556 |
+
n_cmd += self._carry_back(inst)
|
| 557 |
+
path.append("carry_back")
|
| 558 |
+
return dict(speed=speeds[0], speeds=speeds, path=path, n_commands=n_cmd,
|
| 559 |
+
sim_s=round((sk.n_steps - n0) * DT, 1))
|
| 560 |
+
|
| 561 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 562 |
+
"""oracle / naive / blind: one strike per attempt (LFFTask.run_scripted, cross protocol). adaptive: corrects
|
| 563 |
+
within the attempt (_adaptive_attempt) and carries what it saw into the next attempt."""
|
| 564 |
+
if kind != "adaptive":
|
| 565 |
+
return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt)
|
| 566 |
+
k = k or self.max_attempts
|
| 567 |
+
history, pts = [], []
|
| 568 |
+
for a in range(k):
|
| 569 |
+
self.reset_instance(inst)
|
| 570 |
+
params = self._adaptive_attempt(inst, pts)
|
| 571 |
+
out = self.outcome(inst)
|
| 572 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 573 |
+
if on_attempt:
|
| 574 |
+
on_attempt(a, params, out)
|
| 575 |
+
if out["success"]:
|
| 576 |
+
break
|
| 577 |
+
return history
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/lh_balance_board.py
ADDED
|
@@ -0,0 +1,817 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LH balance_board: put four look-alike cubes on their marks on a plank that rests loose across a narrow block (a
|
| 2 |
+
seesaw); loading it in the wrong order tips the plank, and every cube already on it slides down to the low end.
|
| 3 |
+
|
| 4 |
+
Family: long-horizon self-disturbance ("state_restoration"): each stage is a plain pick-and-place of a cube onto its
|
| 5 |
+
mark, but a later placement can tip the plank, which sends the cubes placed before it (earlier progress) sliding off
|
| 6 |
+
their marks. The agent has to notice it, re-level the plank and re-place them before finishing (within an attempt), and
|
| 7 |
+
learn a loading order that keeps the plank level (across attempts; the final-state judge does not enforce an order).
|
| 8 |
+
|
| 9 |
+
Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
|
| 10 |
+
* 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
|
| 11 |
+
6 cm high, flat tops) under the middle of
|
| 12 |
+
* 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
|
| 13 |
+
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
|
| 14 |
+
the plank from wandering along the support (+-3 mm); nothing holds it down. It stays level while the combined centre
|
| 15 |
+
of mass of plank + cubes is above the support's 4 cm top; otherwise it tips until its low end touches the table
|
| 16 |
+
(about 17 degrees);
|
| 17 |
+
* four marks (5.8 cm squares, outline + light fill) on the plank, two on each side of the block: an inner one
|
| 18 |
+
(8.5-9.5 cm from the middle) and an outer one (15.5-16.5 cm); the colour of each mark is random;
|
| 19 |
+
* four 4.5 cm cubes (red, green, blue, yellow) on the table, two left and two right of the plank (random places).
|
| 20 |
+
They look alike except for the colour. Cube and plank surfaces are slick (friction 0.2 < tan 17 deg): on a tipped
|
| 21 |
+
plank every cube slides down to the lip at the low end.
|
| 22 |
+
Why along x with lips (measured, see the task card): with the plank left-right and open ends, the cubes slid off the
|
| 23 |
+
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
|
| 24 |
+
wide along them) pressed the plank's end down and tipped it again -- restoring became a loop. Along x the default grasp
|
| 25 |
+
is across the plank, and the lips keep the cubes on the plank within reach.
|
| 26 |
+
|
| 27 |
+
Hidden variable: the cube masses. "Hazard" instances (13 of every 20 consecutive seeds): the two cubes that belong on
|
| 28 |
+
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
|
| 29 |
+
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
|
| 30 |
+
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
|
| 31 |
+
orders are "an outer cube, then the inner cube on the OTHER side, then the other inner cube, then the last outer cube"
|
| 32 |
+
(zig-zag); end-to-end, alternating outer-first (outer, outer, inner, inner) and inner-first orders all tip it.
|
| 33 |
+
"Benign" instances: all four cubes light (26-34 g); no order tips (worst step 0.63-0.75 x).
|
| 34 |
+
|
| 35 |
+
Why the natural order fails: nothing in the image shows which cubes are heavy. Any natural order (nearest cube first,
|
| 36 |
+
the marks from one end to the other, or the cautious "alternate sides, outer marks first") tips the plank in a hazard
|
| 37 |
+
instance; the cubes on it slide to the low end and keep it tipped. A natural plan then keeps going and finishes with
|
| 38 |
+
cubes off their marks. What must be learned: check the marks after each placement / before finishing, unload the low
|
| 39 |
+
end and re-place (within the attempt), and use the tip to infer which cubes are heavy (an inner cube tipped it; the
|
| 40 |
+
layout must balance in the end, so the other inner cube is heavy too) and load in the zig-zag order (across attempts).
|
| 41 |
+
|
| 42 |
+
Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (every cube on its
|
| 43 |
+
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 /
|
| 44 |
+
lost / restored, with step and cause) and every tip (which end went down, the cube released just before) for the server
|
| 45 |
+
log; F1 gives the agent only success / failure.
|
| 46 |
+
"""
|
| 47 |
+
import itertools
|
| 48 |
+
|
| 49 |
+
import numpy as np
|
| 50 |
+
|
| 51 |
+
from .. import envs
|
| 52 |
+
from ..bddl import write_bddl
|
| 53 |
+
from ..objects import _fmt, _wrap, box_xml, register_generated
|
| 54 |
+
from ..skills import Skills
|
| 55 |
+
from ..task_base import LFFTask, register_task
|
| 56 |
+
|
| 57 |
+
TZ = envs.TABLE_Z
|
| 58 |
+
|
| 59 |
+
# ---------------------------------------------------------------- geometry / physics
|
| 60 |
+
# plank frame: y along the plank (+y = the end toward the robot), x across it, z up. The plank and the block are
|
| 61 |
+
# yawed 90 deg, so plank +y = world -x.
|
| 62 |
+
PL_HL, PL_HW, PL_HT = 0.23, 0.04, 0.0075 # plank half length, half width, half thickness
|
| 63 |
+
LIP_T, LIP_H = 0.008, 0.02 # lip across each end (inside the 46 cm), height above the plank's top
|
| 64 |
+
PLANK_MASS = 0.50
|
| 65 |
+
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
|
| 66 |
+
# and is calm in ~1.5 s (no damping: ~13 deg and ~2.7 s); the tip itself is not slowed (measured)
|
| 67 |
+
PLANK_YAW = np.pi / 2
|
| 68 |
+
RIDGE_HW, RIDGE_HX, RIDGE_H = 0.02, 0.05, 0.06 # support: half width along the plank (s), half depth, height
|
| 69 |
+
SLOT_HW = 0.005 # the support is two blocks with a 1 cm slot between them
|
| 70 |
+
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
|
| 71 |
+
CUBE_E = 0.045
|
| 72 |
+
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
|
| 73 |
+
MU_RIDGE = 1.0
|
| 74 |
+
MARK_HALF, MARK_LINE = 0.029, 0.004
|
| 75 |
+
WOOD = (0.42, 0.27, 0.15, 1.0) # dark walnut: contrasts with the light table, so the tilt reads in the images
|
| 76 |
+
|
| 77 |
+
COLORS = ("red", "green", "blue", "yellow")
|
| 78 |
+
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),
|
| 79 |
+
yellow=(0.93, 0.78, 0.10, 1.0))
|
| 80 |
+
CUBES = {c: f"{c}_cube_1" for c in COLORS}
|
| 81 |
+
PLANK, RIDGE = "plank_1", "ridge_1"
|
| 82 |
+
PLANK_MODEL = "lff_lh_bb_plank"
|
| 83 |
+
# mark slots in plank-frame order (+y first): the robot's end outer / inner, then the far end inner / outer
|
| 84 |
+
SLOTS = ("near_outer", "near_inner", "far_inner", "far_outer")
|
| 85 |
+
END_WORD = dict(near="the end nearer the robot", far="the far end")
|
| 86 |
+
|
| 87 |
+
# ---------------------------------------------------------------- instances / hidden variable
|
| 88 |
+
D_INNER = (0.085, 0.095) # |y| of the inner marks from the plank's middle
|
| 89 |
+
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
|
| 90 |
+
P_HAZARD = 0.65 # fraction of hazard instances, balanced per 20 consecutive seeds (13 / 7)
|
| 91 |
+
R_HEAVY = (1.30, 1.40) # hazard: lone heavy cube on its inner mark, moment / tipping moment
|
| 92 |
+
R_LIGHT = (0.72, 0.78) # hazard: lone light cube on its outer mark
|
| 93 |
+
LIGHT_BENIGN = (0.026, 0.034) # benign: every cube (kg)
|
| 94 |
+
H_EST, L_EST = 0.21, 0.04 # nominal masses the adaptive script uses for its hypotheses (it never sees the true ones)
|
| 95 |
+
|
| 96 |
+
# ---------------------------------------------------------------- judging
|
| 97 |
+
TOL = 0.020 # cube centre within 2 cm of its mark centre (per plank axis)
|
| 98 |
+
TOL_LOSE = 0.025 # hysteresis for the monitor
|
| 99 |
+
LEVEL_DEG = 3.0
|
| 100 |
+
TIP_DEG = 8.0 # the monitor records a tip when |tilt| exceeds this (a real tip reaches ~17 deg)
|
| 101 |
+
LEVEL_DEBOUNCE = 4 # monitor evaluations (0.1 s each) before plank_level changes
|
| 102 |
+
FLAT_COS = np.cos(np.radians(15.0))
|
| 103 |
+
SUPPORT_XY = 0.02 # plank on its support: its middle within 2 cm (horizontally) of the support's centre ...
|
| 104 |
+
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)
|
| 105 |
+
|
| 106 |
+
# ---------------------------------------------------------------- scripted motion
|
| 107 |
+
Z_CARRY = 0.17 # careful / adaptive: grasp point above the table while carrying (cube bottom 14.75 cm)
|
| 108 |
+
Z_CARRY_NAIVE = 0.15 # naive: just above the cubes already on the plank (their tops at 12 cm)
|
| 109 |
+
REL_GAP = 0.004 # release with the cube's bottom this far above the plank
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def plank_xml(name):
|
| 113 |
+
"""Board + end lips + keel (collision) and per colour a mark (5 visual-only geoms, moved per instance).
|
| 114 |
+
Long axis = body y."""
|
| 115 |
+
g = []
|
| 116 |
+
|
| 117 |
+
def box(nm, pos, size, rgba):
|
| 118 |
+
g.append(f'<geom name="{nm}" type="box" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(rgba)}" '
|
| 119 |
+
f'friction="{MU} 0.005 0.0001" density="900" group="0"/>')
|
| 120 |
+
g.append(f'<geom type="box" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(rgba)}" contype="0" '
|
| 121 |
+
f'conaffinity="0" group="1" mass="0"/>')
|
| 122 |
+
|
| 123 |
+
dark = (0.25, 0.16, 0.09, 1.0)
|
| 124 |
+
box(f"{name}_board", (0, 0, 0), (PL_HW, PL_HL, PL_HT), WOOD)
|
| 125 |
+
for k, s in enumerate((1, -1)):
|
| 126 |
+
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)
|
| 127 |
+
box(f"{name}_keel", (0, 0, -PL_HT - KEEL_H / 2), (PL_HW, KEEL_HW, KEEL_H / 2), dark)
|
| 128 |
+
for c in COLORS:
|
| 129 |
+
rgba = RGBA[c]
|
| 130 |
+
fill = tuple(0.55 + 0.45 * v for v in rgba[:3]) + (1.0,)
|
| 131 |
+
o, i, w = MARK_HALF, MARK_HALF - MARK_LINE, MARK_LINE
|
| 132 |
+
parts = [((0, 0, PL_HT + 0.0003), (o, o, 0.0003), fill),
|
| 133 |
+
((0, i + w / 2, PL_HT + 0.0008), (o, w / 2, 0.0003), rgba),
|
| 134 |
+
((0, -i - w / 2, PL_HT + 0.0008), (o, w / 2, 0.0003), rgba),
|
| 135 |
+
((i + w / 2, 0, PL_HT + 0.0008), (w / 2, o, 0.0003), rgba),
|
| 136 |
+
((-i - w / 2, 0, PL_HT + 0.0008), (w / 2, o, 0.0003), rgba)]
|
| 137 |
+
for k, (p, sz, col) in enumerate(parts):
|
| 138 |
+
g.append(f'<geom name="{name}_mk_{c}_{k}" type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" '
|
| 139 |
+
f'rgba="{_fmt(col)}" contype="0" conaffinity="0" group="1" mass="0"/>')
|
| 140 |
+
return _wrap(name, "\n ".join(g), PL_HT, float(np.hypot(PL_HL, PL_HW)))
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def ridge_xml(name):
|
| 144 |
+
"""Split support: two 1.5 cm blocks with a 1 cm slot between them; the plank rests on both and pivots on their outer
|
| 145 |
+
top edges (a 4 cm flat top). The plank's keel hangs in the slot, so the plank cannot wander along its length by
|
| 146 |
+
more than +-3 mm (it stays engaged at the full tip angle)."""
|
| 147 |
+
rgba = (0.35, 0.35, 0.38, 1.0)
|
| 148 |
+
bh = (RIDGE_HW - SLOT_HW) / 2
|
| 149 |
+
g = []
|
| 150 |
+
for k, sy in enumerate((1, -1)):
|
| 151 |
+
p, sz = (0, sy * (SLOT_HW + bh), RIDGE_H / 2), (RIDGE_HX, bh, RIDGE_H / 2)
|
| 152 |
+
g.append(f'<geom name="{name}_g{k}" type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(rgba)}" '
|
| 153 |
+
f'friction="{MU_RIDGE} 0.005 0.0001" group="0"/>')
|
| 154 |
+
g.append(f'<geom type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(rgba)}" contype="0" conaffinity="0" '
|
| 155 |
+
f'group="1"/>')
|
| 156 |
+
g = "\n ".join(g)
|
| 157 |
+
return f"""<mujoco model="{name}">
|
| 158 |
+
<worldbody>
|
| 159 |
+
<body>
|
| 160 |
+
<body name="object">
|
| 161 |
+
{g}
|
| 162 |
+
</body>
|
| 163 |
+
<site rgba="0 0 0 0" size="0.005" pos="0 0 0" name="bottom_site" />
|
| 164 |
+
<site rgba="0 0 0 0" size="0.005" pos="0 0 {RIDGE_H:.4f}" name="top_site" />
|
| 165 |
+
<site rgba="0 0 0 0" size="0.005" pos="{RIDGE_HX:.4f} {RIDGE_HW:.4f} 0" name="horizontal_radius_site" />
|
| 166 |
+
</body>
|
| 167 |
+
</worldbody>
|
| 168 |
+
</mujoco>"""
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def tip_ratio(items, plank_mass=PLANK_MASS, s=RIDGE_HW):
|
| 172 |
+
"""Static model of a loose plank on a flat-topped block: |sum m y| / ((M_plank + sum m) s); the plank tips when
|
| 173 |
+
this exceeds 1 (the combined centre of mass leaves the block's top). items: [(mass, y from the middle)]."""
|
| 174 |
+
if not items:
|
| 175 |
+
return 0.0
|
| 176 |
+
mom = sum(m * y for m, y in items)
|
| 177 |
+
return abs(mom) / ((plank_mass + sum(m for m, _ in items)) * s)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def _side(y):
|
| 181 |
+
return "near" if y > 0 else "far"
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def _along(v):
|
| 185 |
+
"""plank-frame y offset in robot-centric words (+y = toward the robot)"""
|
| 186 |
+
return f"{100 * abs(v):.1f} cm from its mark toward {'the robot' if v > 0 else 'the far end'}"
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class BoardSkills(Skills):
|
| 190 |
+
"""Skills that feed the task's per-step monitor."""
|
| 191 |
+
|
| 192 |
+
def __init__(self, env, task, recorder=None):
|
| 193 |
+
super().__init__(env, recorder=recorder)
|
| 194 |
+
self.task = task
|
| 195 |
+
|
| 196 |
+
def _act(self, dpos, drot, grip):
|
| 197 |
+
super()._act(dpos, drot, grip)
|
| 198 |
+
self.task.monitor_step()
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
@register_task
|
| 202 |
+
class BalanceBoard(LFFTask):
|
| 203 |
+
name = "lh_balance_board"
|
| 204 |
+
level = "L2"
|
| 205 |
+
category = "state_restoration"
|
| 206 |
+
capabilities = ("Perceive", "Reason", "Plan", "Restore")
|
| 207 |
+
protocol = "cross"
|
| 208 |
+
max_attempts = 3
|
| 209 |
+
agent_max_steps = 120 # careful zig-zag ~30-36 commands + re-placing four cubes (~30) + looking around
|
| 210 |
+
instruction = ("Put each coloured cube on the square mark of the same colour on the long plank. The plank lies loose "
|
| 211 |
+
"across a narrow block under its middle. At the end all four cubes must be on their marks and the "
|
| 212 |
+
"plank must still rest level on the block.")
|
| 213 |
+
instruction_indirect = ("Set the four coloured cubes onto the outlined squares of matching colour on the wooden "
|
| 214 |
+
"board that rests across the small grey block. When you are done, every cube must sit on "
|
| 215 |
+
"its square and the board must still rest level on the block.")
|
| 216 |
+
agent_object_names = ["red cube", "green cube", "blue cube", "yellow cube", "plank", "support block",
|
| 217 |
+
"red mark", "green mark", "blue mark", "yellow mark"]
|
| 218 |
+
|
| 219 |
+
# ------------------------------------------------------------ scene
|
| 220 |
+
def make_bddl(self):
|
| 221 |
+
pl = register_generated("LffLhBbPlank", plank_xml(PLANK_MODEL))
|
| 222 |
+
rg = register_generated("LffLhBbRidge", ridge_xml("lff_lh_bb_ridge"), free=False)
|
| 223 |
+
objs = [(PLANK, pl, "plank_region", (0.18, -0.01, 0.20, 0.01))]
|
| 224 |
+
e = CUBE_E / 2
|
| 225 |
+
for i, c in enumerate(COLORS):
|
| 226 |
+
cat = register_generated(f"LffLhBbCube{c.title()}",
|
| 227 |
+
box_xml(f"lff_lh_bb_cube_{c}", (e, e, e), RGBA[c], density=500.0,
|
| 228 |
+
friction=(MU, 0.005, 0.0001)).replace(
|
| 229 |
+
'solimp="0.998 0.998 0.001" solref="0.001 1"', ""))
|
| 230 |
+
objs.append((CUBES[c], cat, f"{c}_cube_region", (-0.32, -0.33 + 0.2 * i, -0.30, -0.31 + 0.2 * i)))
|
| 231 |
+
fx = [(RIDGE, rg, "ridge_region", (-0.12, 0.30, -0.10, 0.32))]
|
| 232 |
+
return write_bddl(self.name, "put each cube on its mark on the plank and keep the plank level", objs, fx)
|
| 233 |
+
|
| 234 |
+
def __init__(self, cam_res=None):
|
| 235 |
+
super().__init__(cam_res)
|
| 236 |
+
m = self.env.sim.model
|
| 237 |
+
self.ridge_bid = m.body_name2id(self.env.fixtures_dict[RIDGE].root_body)
|
| 238 |
+
self.plank_bid = envs.body_id(self.env, PLANK)
|
| 239 |
+
pre = f"{PLANK}_{PLANK_MODEL}"
|
| 240 |
+
self.mark_gids = {c: [m.geom_name2id(f"{pre}_mk_{c}_{k}") for k in range(5)] for c in COLORS}
|
| 241 |
+
self.mark_pos0 = {c: [m.geom_pos[g].copy() for g in self.mark_gids[c]] for c in COLORS}
|
| 242 |
+
self.cube_gids = {c: set(envs.obj_geom_ids(self.env, CUBES[c])) for c in COLORS}
|
| 243 |
+
self.plank_gids = set(envs.obj_geom_ids(self.env, PLANK))
|
| 244 |
+
self.robot_gids = set(envs.robot_geom_ids(self.env))
|
| 245 |
+
self.inst = None
|
| 246 |
+
self.mon = None
|
| 247 |
+
self.obs = [] # adaptive script: (configuration, tipped) observations, kept across the attempts of one run
|
| 248 |
+
|
| 249 |
+
def sample_instance(self, seed):
|
| 250 |
+
rng = np.random.default_rng(seed)
|
| 251 |
+
x0, y0 = float(rng.uniform(-0.18, -0.14)), float(rng.uniform(-0.03, 0.03))
|
| 252 |
+
perm = [str(c) for c in rng.permutation(COLORS)] # colour of the mark in SLOTS order
|
| 253 |
+
slot_of = {c: s for c, s in zip(perm, SLOTS)}
|
| 254 |
+
dist = dict(near_outer=float(rng.uniform(*D_OUTER)), near_inner=float(rng.uniform(*D_INNER)),
|
| 255 |
+
far_inner=-float(rng.uniform(*D_INNER)), far_outer=-float(rng.uniform(*D_OUTER)))
|
| 256 |
+
marks = {c: dist[slot_of[c]] for c in COLORS} # plank-frame y of each mark (+ = toward the robot)
|
| 257 |
+
hazard = bool((int(seed) * 7) % 20 < round(20 * P_HAZARD)) # balanced like l7_key_turn / lh_lid_box
|
| 258 |
+
r_h, r_l = float(rng.uniform(*R_HEAVY)), float(rng.uniform(*R_LIGHT))
|
| 259 |
+
light = {c: float(rng.uniform(*LIGHT_BENIGN)) for c in COLORS}
|
| 260 |
+
s, pm = RIDGE_HW, PLANK_MASS
|
| 261 |
+
if hazard:
|
| 262 |
+
# equal moments on both sides -> the finished layout is exactly balanced
|
| 263 |
+
dn, do = dist["near_inner"], dist["near_outer"]
|
| 264 |
+
y_h = r_h * pm * s / (dn - r_h * s) * dn # heavy on the near inner mark: moment r_h x tipping moment
|
| 265 |
+
x_l = r_l * pm * s / (do - r_l * s) * do
|
| 266 |
+
mass = {c: (y_h if "inner" in slot_of[c] else x_l) / abs(dist[slot_of[c]]) for c in COLORS}
|
| 267 |
+
else:
|
| 268 |
+
mass = light
|
| 269 |
+
# start: two cubes left and two right of the plank, 17-19 cm from its axis, at two depths (random places)
|
| 270 |
+
spots = [(dx, sy) for sy in (1.0, -1.0) for dx in (-0.08, 0.08)]
|
| 271 |
+
order = rng.permutation(4)
|
| 272 |
+
start = {c: [x0 + spots[j][0] + float(rng.uniform(-0.01, 0.01)),
|
| 273 |
+
y0 + spots[j][1] * float(rng.uniform(0.17, 0.19))] for c, j in zip(COLORS, order)}
|
| 274 |
+
start_yaw = {c: float(rng.uniform(-0.3, 0.3)) for c in COLORS}
|
| 275 |
+
heavy = sorted(c for c in COLORS if mass[c] > 0.1)
|
| 276 |
+
return dict(seed=int(seed), plank_xy=[x0, y0], marks=marks, slot_of=slot_of, hazard=hazard, mass=mass,
|
| 277 |
+
heavy=heavy, r_heavy=r_h if hazard else None, r_light=r_l if hazard else None, start=start,
|
| 278 |
+
start_yaw=start_yaw)
|
| 279 |
+
|
| 280 |
+
def apply_instance(self, inst):
|
| 281 |
+
self.inst = inst
|
| 282 |
+
env = self.env
|
| 283 |
+
m = env.sim.model
|
| 284 |
+
x0, y0 = inst["plank_xy"]
|
| 285 |
+
q = [np.cos(PLANK_YAW / 2), 0.0, 0.0, np.sin(PLANK_YAW / 2)]
|
| 286 |
+
m.body_pos[self.ridge_bid] = [x0, y0, TZ]
|
| 287 |
+
m.body_quat[self.ridge_bid] = q
|
| 288 |
+
envs.scale_mass(env, PLANK, PLANK_MASS)
|
| 289 |
+
_, da = envs.free_joint_addr(env, PLANK)
|
| 290 |
+
m.dof_damping[da + 3:da + 6] = PLANK_ROT_DAMP
|
| 291 |
+
for c in COLORS:
|
| 292 |
+
for g, p0 in zip(self.mark_gids[c], self.mark_pos0[c]):
|
| 293 |
+
m.geom_pos[g] = p0 + np.array([0.0, inst["marks"][c], 0.0])
|
| 294 |
+
envs.scale_mass(env, CUBES[c], inst["mass"][c])
|
| 295 |
+
envs.set_obj_pose(env, PLANK, [x0, y0, TZ + RIDGE_H + PL_HT + 0.0005], quat_wxyz=np.array(q))
|
| 296 |
+
for c in COLORS:
|
| 297 |
+
envs.place_upright(env, CUBES[c], inst["start"][c], yaw=inst["start_yaw"][c])
|
| 298 |
+
|
| 299 |
+
def reset_instance(self, inst, recorder=None):
|
| 300 |
+
self.mon = None
|
| 301 |
+
self.env.reset()
|
| 302 |
+
self.apply_instance(inst)
|
| 303 |
+
self.env.sim.forward()
|
| 304 |
+
envs.settle(self.env, 10)
|
| 305 |
+
self.plank_z0 = float(self.plank_pos()[2])
|
| 306 |
+
self.sk = BoardSkills(self.env, self, recorder=recorder)
|
| 307 |
+
self._init_monitor()
|
| 308 |
+
return self.sk
|
| 309 |
+
|
| 310 |
+
# ------------------------------------------------------------ state helpers
|
| 311 |
+
def plank_R(self):
|
| 312 |
+
return self.env.sim.data.body_xmat[self.plank_bid].reshape(3, 3).copy()
|
| 313 |
+
|
| 314 |
+
def plank_pos(self):
|
| 315 |
+
return self.env.sim.data.body_xpos[self.plank_bid].copy()
|
| 316 |
+
|
| 317 |
+
def tilt_deg(self):
|
| 318 |
+
"""+ = the plank's end toward the robot is up"""
|
| 319 |
+
return float(np.degrees(np.arcsin(np.clip(self.plank_R()[2, 1], -1.0, 1.0))))
|
| 320 |
+
|
| 321 |
+
def is_level(self, deg=LEVEL_DEG):
|
| 322 |
+
return abs(self.tilt_deg()) <= deg
|
| 323 |
+
|
| 324 |
+
def on_support(self):
|
| 325 |
+
"""the plank still rests on the support block (10-11: Sonnet lh2 s3001 pushed it off onto the table, where it
|
| 326 |
+
lies level, and loaded the cubes there; 'level' alone accepted that)"""
|
| 327 |
+
p, r = self.plank_pos(), self.env.sim.data.body_xpos[self.ridge_bid]
|
| 328 |
+
return bool(np.linalg.norm(p[:2] - r[:2]) <= SUPPORT_XY and p[2] >= self.plank_z0 - SUPPORT_DZ)
|
| 329 |
+
|
| 330 |
+
def in_plank(self, p):
|
| 331 |
+
"""world point -> plank frame (x across, y along from the middle, z above the plank's mid-plane)"""
|
| 332 |
+
return self.plank_R().T @ (np.asarray(p, float) - self.plank_pos())
|
| 333 |
+
|
| 334 |
+
def mark_world(self, c):
|
| 335 |
+
return self.plank_pos() + self.plank_R() @ np.array([0.0, self.inst["marks"][c], PL_HT])
|
| 336 |
+
|
| 337 |
+
def cube_pos(self, c):
|
| 338 |
+
return envs.obj_pos(self.env, CUBES[c])
|
| 339 |
+
|
| 340 |
+
def held(self, c):
|
| 341 |
+
return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper,
|
| 342 |
+
object_geoms=self.env.objects_dict[CUBES[c]]))
|
| 343 |
+
|
| 344 |
+
def on_plank(self, c):
|
| 345 |
+
"""resting on the plank's top (plank frame), anywhere along it"""
|
| 346 |
+
q = self.in_plank(self.cube_pos(c))
|
| 347 |
+
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)
|
| 348 |
+
|
| 349 |
+
def mark_offset(self, c):
|
| 350 |
+
q = self.in_plank(self.cube_pos(c))
|
| 351 |
+
return np.array([q[0], q[1] - self.inst["marks"][c]])
|
| 352 |
+
|
| 353 |
+
def _flat(self, c):
|
| 354 |
+
Rc = self.env.sim.data.body_xmat[envs.body_id(self.env, CUBES[c])].reshape(3, 3)
|
| 355 |
+
return bool(np.max(np.abs(self.plank_R()[:, 2] @ Rc)) >= FLAT_COS)
|
| 356 |
+
|
| 357 |
+
def on_mark(self, c, tol=TOL):
|
| 358 |
+
if not self.on_plank(c):
|
| 359 |
+
return False
|
| 360 |
+
o = self.mark_offset(c)
|
| 361 |
+
return bool(np.max(np.abs(o)) <= tol and self._flat(c) and not self.held(c))
|
| 362 |
+
|
| 363 |
+
def stage_values(self):
|
| 364 |
+
v = {f"{c}_on_mark": self.on_mark(c) for c in COLORS}
|
| 365 |
+
v["plank_level"] = self.is_level()
|
| 366 |
+
v["plank_on_support"] = self.on_support()
|
| 367 |
+
return v
|
| 368 |
+
|
| 369 |
+
# ------------------------------------------------------------ per-step monitor (server log only)
|
| 370 |
+
def _init_monitor(self):
|
| 371 |
+
self.mon = dict(state={f"{c}_on_mark": False for c in COLORS} | {"plank_level": True, "plank_on_support": True}, ever=set(),
|
| 372 |
+
lost=set(), events=[], step=0, last_touch={c: None for c in COLORS},
|
| 373 |
+
held_prev={c: False for c in COLORS}, last_release=None, tipping=False, tips=[],
|
| 374 |
+
level_cnt=0, calm=0, tilt_max=0.0, win_max=0.0)
|
| 375 |
+
|
| 376 |
+
def _robot_touches(self):
|
| 377 |
+
"""cubes touched by the robot or by a cube the robot is carrying, in this control step"""
|
| 378 |
+
d = self.env.sim.data
|
| 379 |
+
out = set()
|
| 380 |
+
carried = [c for c in COLORS if self.mon["held_prev"][c]]
|
| 381 |
+
hit = {c: self.robot_gids.union(*[self.cube_gids[h] for h in carried if h != c]) for c in COLORS}
|
| 382 |
+
for i in range(d.ncon):
|
| 383 |
+
con = d.contact[i]
|
| 384 |
+
for c in COLORS:
|
| 385 |
+
g = self.cube_gids[c]
|
| 386 |
+
if (con.geom1 in g and con.geom2 in hit[c]) or (con.geom2 in g and con.geom1 in hit[c]):
|
| 387 |
+
out.add(c)
|
| 388 |
+
return out
|
| 389 |
+
|
| 390 |
+
def monitor_step(self):
|
| 391 |
+
mon = self.mon
|
| 392 |
+
if mon is None or self.sk is None:
|
| 393 |
+
return
|
| 394 |
+
mon["step"] += 1
|
| 395 |
+
step = self.sk.n_steps
|
| 396 |
+
for c in self._robot_touches():
|
| 397 |
+
mon["last_touch"][c] = step
|
| 398 |
+
tilt = self.tilt_deg()
|
| 399 |
+
mon["tilt_max"] = max(mon["tilt_max"], abs(tilt))
|
| 400 |
+
mon["win_max"] = max(mon["win_max"], abs(tilt))
|
| 401 |
+
if not mon["tipping"] and abs(tilt) > TIP_DEG:
|
| 402 |
+
# one tip episode = from |tilt| > 8 deg until the plank has stayed level for 1 s (the swing back and any
|
| 403 |
+
# rocking belong to the same episode)
|
| 404 |
+
mon["tipping"] = True
|
| 405 |
+
mon["calm"] = 0
|
| 406 |
+
rel = mon["last_release"]
|
| 407 |
+
tip = dict(step=step, down="near" if tilt < 0 else "far",
|
| 408 |
+
after_release=(rel[0] if rel is not None and step - rel[1] <= 60 else None),
|
| 409 |
+
on_plank=[c for c in COLORS if self.on_plank(c)],
|
| 410 |
+
on_mark=[c for c in COLORS if mon["state"][f"{c}_on_mark"]])
|
| 411 |
+
mon["tips"].append(tip)
|
| 412 |
+
mon["events"].append(dict(step=step, pred="plank", ev="tipped", down=tip["down"],
|
| 413 |
+
after_release=tip["after_release"], on_mark=tip["on_mark"]))
|
| 414 |
+
elif mon["tipping"]:
|
| 415 |
+
mon["calm"] = mon["calm"] + 1 if abs(tilt) < LEVEL_DEG else 0
|
| 416 |
+
if mon["calm"] >= 20:
|
| 417 |
+
mon["tipping"] = False
|
| 418 |
+
if mon["step"] % 2:
|
| 419 |
+
return # predicates every other control step (0.1 s)
|
| 420 |
+
for c in COLORS:
|
| 421 |
+
h = self.held(c)
|
| 422 |
+
if mon["held_prev"][c] and not h:
|
| 423 |
+
mon["last_release"] = (c, step)
|
| 424 |
+
mon["held_prev"][c] = h
|
| 425 |
+
key = f"{c}_on_mark"
|
| 426 |
+
was = mon["state"][key]
|
| 427 |
+
now = self.on_mark(c, TOL if not was else TOL_LOSE)
|
| 428 |
+
if now != was:
|
| 429 |
+
self._event(key, now, step, c)
|
| 430 |
+
lv = self.is_level()
|
| 431 |
+
if lv != mon["state"]["plank_level"]:
|
| 432 |
+
mon["level_cnt"] += 1
|
| 433 |
+
if mon["level_cnt"] >= LEVEL_DEBOUNCE:
|
| 434 |
+
mon["level_cnt"] = 0
|
| 435 |
+
self._event("plank_level", lv, step, None)
|
| 436 |
+
else:
|
| 437 |
+
mon["level_cnt"] = 0
|
| 438 |
+
sup = self.on_support()
|
| 439 |
+
if sup != mon["state"]["plank_on_support"]:
|
| 440 |
+
self._event("plank_on_support", sup, step, None)
|
| 441 |
+
|
| 442 |
+
def _event(self, key, now, step, color):
|
| 443 |
+
mon = self.mon
|
| 444 |
+
mon["state"][key] = now
|
| 445 |
+
if now:
|
| 446 |
+
ev = "restored" if key in mon["lost"] else "achieved"
|
| 447 |
+
mon["ever"].add(key)
|
| 448 |
+
mon["lost"].discard(key)
|
| 449 |
+
mon["events"].append(dict(step=step, pred=key, ev=ev))
|
| 450 |
+
return
|
| 451 |
+
cause = "other"
|
| 452 |
+
recent_tip = bool(mon["tips"]) and (mon["tipping"] or step - mon["tips"][-1]["step"] <= 60)
|
| 453 |
+
if color is None:
|
| 454 |
+
cause = "tip" if recent_tip else "other"
|
| 455 |
+
elif self.held(color):
|
| 456 |
+
cause = "picked_up"
|
| 457 |
+
elif recent_tip:
|
| 458 |
+
cause = "tip"
|
| 459 |
+
elif mon["last_touch"][color] is not None and step - mon["last_touch"][color] <= 60:
|
| 460 |
+
cause = "robot"
|
| 461 |
+
mon["lost"].add(key)
|
| 462 |
+
mon["events"].append(dict(step=step, pred=key, ev="lost", cause=cause, tilt=round(self.tilt_deg(), 1)))
|
| 463 |
+
|
| 464 |
+
# ------------------------------------------------------------ outcome
|
| 465 |
+
def _static(self):
|
| 466 |
+
d = self.env.sim.data
|
| 467 |
+
for name in [CUBES[c] for c in COLORS] + [PLANK]:
|
| 468 |
+
_, da = envs.free_joint_addr(self.env, name)
|
| 469 |
+
if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.3:
|
| 470 |
+
return False
|
| 471 |
+
return True
|
| 472 |
+
|
| 473 |
+
def _where(self, c):
|
| 474 |
+
"""robot-centric description of where a cube that is not on its mark is"""
|
| 475 |
+
if self.held(c):
|
| 476 |
+
return "is still held by the gripper"
|
| 477 |
+
if self.on_plank(c):
|
| 478 |
+
o = self.mark_offset(c)
|
| 479 |
+
return f"lies on the plank, {_along(o[1])}"
|
| 480 |
+
p = self.cube_pos(c)
|
| 481 |
+
if np.linalg.norm(p[:2] - np.asarray(self.inst["start"][c])) < 0.02:
|
| 482 |
+
return "is still where it started on the table"
|
| 483 |
+
q = self.in_plank(p)
|
| 484 |
+
if abs(q[1]) > PL_HL:
|
| 485 |
+
return f"lies on the table beyond {END_WORD[_side(q[1])]} of the plank"
|
| 486 |
+
return "lies on the table beside the plank"
|
| 487 |
+
|
| 488 |
+
def outcome(self, inst):
|
| 489 |
+
envs.settle(self.env, 30)
|
| 490 |
+
mon = self.mon
|
| 491 |
+
vals = self.stage_values()
|
| 492 |
+
static = self._static()
|
| 493 |
+
held = [c for c in COLORS if self.held(c)]
|
| 494 |
+
success = bool(all(vals.values()) and static and not held)
|
| 495 |
+
regress = [e for e in mon["events"] if e["ev"] == "lost"]
|
| 496 |
+
restored = [e for e in mon["events"] if e["ev"] == "restored"]
|
| 497 |
+
parts = []
|
| 498 |
+
off = [c for c in COLORS if not vals[f"{c}_on_mark"]]
|
| 499 |
+
if success:
|
| 500 |
+
failure = None
|
| 501 |
+
parts.append("All four cubes are on their marks and the plank is level.")
|
| 502 |
+
else:
|
| 503 |
+
lost_final = [c for c in off if f"{c}_on_mark" in mon["ever"]]
|
| 504 |
+
failure = ("held" if held else "plank_off_support" if not vals["plank_on_support"] else
|
| 505 |
+
"regressed" if lost_final else "incomplete" if off else
|
| 506 |
+
"not_level" if not vals["plank_level"] else "not_static")
|
| 507 |
+
for c in off:
|
| 508 |
+
txt = f"The {c} cube is not on its mark: it {self._where(c)}"
|
| 509 |
+
if f"{c}_on_mark" in mon["ever"]:
|
| 510 |
+
why = [e for e in regress if e["pred"] == f"{c}_on_mark"]
|
| 511 |
+
cause = why[-1].get("cause") if why else None
|
| 512 |
+
txt += {"tip": " (it had been on its mark; it slid off when the plank tipped).",
|
| 513 |
+
"robot": " (it had been on its mark; the robot knocked it off).",
|
| 514 |
+
"picked_up": " (it had been on its mark; it was picked up again)."}.get(
|
| 515 |
+
cause, " (it had been on its mark earlier).")
|
| 516 |
+
else:
|
| 517 |
+
txt += " (it was never on its mark)."
|
| 518 |
+
parts.append(txt)
|
| 519 |
+
if not vals["plank_on_support"]:
|
| 520 |
+
parts.append("The plank no longer rests on the support block: it was pushed or knocked off it.")
|
| 521 |
+
if not vals["plank_level"]:
|
| 522 |
+
t = self.tilt_deg()
|
| 523 |
+
parts.append(f"The plank is not level: it is tilted {abs(t):.0f} degrees, "
|
| 524 |
+
f"{END_WORD['near' if t < 0 else 'far']} down.")
|
| 525 |
+
if not static and all(vals.values()):
|
| 526 |
+
parts.append("Something was still moving at the end.")
|
| 527 |
+
if mon["tips"]:
|
| 528 |
+
descr = []
|
| 529 |
+
for tp in mon["tips"]:
|
| 530 |
+
d = f"{END_WORD[tp['down']]} down"
|
| 531 |
+
if tp["after_release"]:
|
| 532 |
+
d += f" right after the {tp['after_release']} cube was set down"
|
| 533 |
+
descr.append(d)
|
| 534 |
+
parts.append(f"During the attempt the plank tipped {len(mon['tips'])} time(s): " + "; ".join(descr) + ".")
|
| 535 |
+
return dict(success=success, failure=failure, stages=vals, static=bool(static), held=held,
|
| 536 |
+
events=mon["events"], n_regressions=len(regress), n_restored=len(restored),
|
| 537 |
+
n_tips=len(mon["tips"]), tips=mon["tips"], tilt_max=round(mon["tilt_max"], 1),
|
| 538 |
+
tilt_final=round(self.tilt_deg(), 1), hazard=bool(inst["hazard"]),
|
| 539 |
+
mark_offsets_cm={c: (100 * self.mark_offset(c)).round(1).tolist() for c in COLORS},
|
| 540 |
+
on_plank={c: self.on_plank(c) for c in COLORS}, detail=" ".join(parts))
|
| 541 |
+
|
| 542 |
+
# ------------------------------------------------------------ scripted policies (perfect perception)
|
| 543 |
+
def _grasp_yaw(self, c):
|
| 544 |
+
R = self.env.sim.data.body_xmat[envs.body_id(self.env, CUBES[c])].reshape(3, 3)
|
| 545 |
+
i = int(np.argmin(np.abs(R[2])))
|
| 546 |
+
yaw = float(np.arctan2(R[1, i], R[0, i]))
|
| 547 |
+
return float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4)
|
| 548 |
+
|
| 549 |
+
def _y_on_plank(self):
|
| 550 |
+
"""cubes resting on the plank now -> their position along it"""
|
| 551 |
+
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)}
|
| 552 |
+
|
| 553 |
+
def plank_calm(self):
|
| 554 |
+
_, da = envs.free_joint_addr(self.env, PLANK)
|
| 555 |
+
return abs(self.tilt_deg()) < 1.0 and float(np.linalg.norm(self.env.sim.data.qvel[da + 3:da + 6])) < 0.05
|
| 556 |
+
|
| 557 |
+
def wait_calm(self, max_steps=60):
|
| 558 |
+
"""hold the arm still until the plank has stopped swinging (a careful agent looks before it acts)"""
|
| 559 |
+
n = 0
|
| 560 |
+
for _ in range(max_steps):
|
| 561 |
+
if self.plank_calm():
|
| 562 |
+
n += 1
|
| 563 |
+
if n >= 5:
|
| 564 |
+
return True
|
| 565 |
+
else:
|
| 566 |
+
n = 0
|
| 567 |
+
self.sk.hold(1)
|
| 568 |
+
return False
|
| 569 |
+
|
| 570 |
+
def pick(self, c, z_carry):
|
| 571 |
+
sk = self.sk
|
| 572 |
+
p = self.cube_pos(c)
|
| 573 |
+
yaw = self._grasp_yaw(c)
|
| 574 |
+
sk.set_gripper(False, steps=8)
|
| 575 |
+
sk.move_to([p[0], p[1], max(TZ + z_carry, p[2] + 0.06)], yaw=yaw)
|
| 576 |
+
sk.move_to([p[0], p[1], p[2]], tol=0.003)
|
| 577 |
+
sk.set_gripper(True, steps=15)
|
| 578 |
+
sk.move_to([p[0], p[1], TZ + z_carry], speed=0.3)
|
| 579 |
+
if not self.held(c):
|
| 580 |
+
sk.set_gripper(False, steps=8)
|
| 581 |
+
sk.move_to([p[0], p[1], TZ + z_carry])
|
| 582 |
+
return False
|
| 583 |
+
return True
|
| 584 |
+
|
| 585 |
+
def put(self, c, z_carry=Z_CARRY, noise=None, record=False, careful=False):
|
| 586 |
+
"""Pick cube c wherever it is and put it on its mark: carry it over the mark, lower it until its bottom is
|
| 587 |
+
REL_GAP above the plank, release, lift. Returns whether the plank tipped (|tilt| > TIP_DEG) during the
|
| 588 |
+
placement, or None if the cube could not be picked. record=True appends the observation (cubes on the plank
|
| 589 |
+
right before the release + this one on its mark, tipped?) for the adaptive script."""
|
| 590 |
+
for _ in range(2):
|
| 591 |
+
if self.pick(c, z_carry):
|
| 592 |
+
break
|
| 593 |
+
else:
|
| 594 |
+
return None
|
| 595 |
+
sk = self.sk
|
| 596 |
+
d = self.mark_world(c)
|
| 597 |
+
if noise is not None:
|
| 598 |
+
d = d + np.array([noise[0], noise[1], 0.0])
|
| 599 |
+
sk.move_to([d[0], d[1], TZ + z_carry], yaw=0.0)
|
| 600 |
+
if careful:
|
| 601 |
+
self.wait_calm()
|
| 602 |
+
d = self.mark_world(c) + (np.array([noise[0], noise[1], 0.0]) if noise is not None else 0.0)
|
| 603 |
+
sk.move_to([d[0], d[1], d[2] + CUBE_E / 2 + REL_GAP], tol=0.003)
|
| 604 |
+
was_level = self.plank_calm()
|
| 605 |
+
conf = self._y_on_plank()
|
| 606 |
+
conf[c] = float(self.inst["marks"][c])
|
| 607 |
+
self.mon["win_max"] = abs(self.tilt_deg())
|
| 608 |
+
sk.set_gripper(False, steps=12)
|
| 609 |
+
sk.move_to([d[0], d[1], TZ + z_carry])
|
| 610 |
+
sk.hold(12)
|
| 611 |
+
tipped = self.mon["win_max"] > TIP_DEG
|
| 612 |
+
if tipped:
|
| 613 |
+
envs.settle(self.env, 30) # let the cubes slide down
|
| 614 |
+
if record and was_level:
|
| 615 |
+
self.obs.append(dict(conf=conf, tipped=bool(tipped), after=c))
|
| 616 |
+
return tipped
|
| 617 |
+
|
| 618 |
+
def park(self, c):
|
| 619 |
+
"""take cube c off the plank and set it on a free spot of the table beside the plank"""
|
| 620 |
+
x0, y0 = self.inst["plank_xy"]
|
| 621 |
+
others = [self.cube_pos(o)[:2] for o in COLORS if o != c]
|
| 622 |
+
cands = [np.array([x0 + dx, y0 + sy * dy]) for sy in (1, -1) for dy in (0.18, 0.25)
|
| 623 |
+
for dx in (-0.12, -0.04, 0.04, 0.12)]
|
| 624 |
+
best = max(cands, key=lambda q: min(np.linalg.norm(q - o) for o in others))
|
| 625 |
+
if not self.pick(c, Z_CARRY):
|
| 626 |
+
return False
|
| 627 |
+
sk = self.sk
|
| 628 |
+
sk.move_to([best[0], best[1], TZ + Z_CARRY], yaw=0.0)
|
| 629 |
+
sk.move_to([best[0], best[1], TZ + CUBE_E / 2 + 0.004], tol=0.003)
|
| 630 |
+
sk.set_gripper(False, steps=12)
|
| 631 |
+
sk.move_to([best[0], best[1], TZ + Z_CARRY])
|
| 632 |
+
return True
|
| 633 |
+
|
| 634 |
+
# ---- planning with the static model
|
| 635 |
+
def plan(self, todo, hyps):
|
| 636 |
+
"""Best order to (re)place the cubes in `todo`, given the cubes now on the plank, minimising the worst tip ratio
|
| 637 |
+
over the mass hypotheses `hyps` (list of {colour: kg}). A cube that is on the plank off its mark is lifted
|
| 638 |
+
(its moment removed) and then set on its mark. Returns (order, worst ratio)."""
|
| 639 |
+
cur0 = self._y_on_plank()
|
| 640 |
+
best, best_w = list(todo), np.inf
|
| 641 |
+
for order in itertools.permutations(todo):
|
| 642 |
+
w = 0.0
|
| 643 |
+
for mass in hyps:
|
| 644 |
+
cur = dict(cur0)
|
| 645 |
+
for c in order:
|
| 646 |
+
if c in cur:
|
| 647 |
+
del cur[c]
|
| 648 |
+
w = max(w, tip_ratio([(mass[o], y) for o, y in cur.items()]))
|
| 649 |
+
cur[c] = self.inst["marks"][c]
|
| 650 |
+
w = max(w, tip_ratio([(mass[o], y) for o, y in cur.items()]))
|
| 651 |
+
if w < best_w - 1e-9:
|
| 652 |
+
best, best_w = list(order), w
|
| 653 |
+
return best, best_w
|
| 654 |
+
|
| 655 |
+
def hypotheses(self, use_obs=True):
|
| 656 |
+
"""Heavy / light assignments (nominal masses) that (1) leave the finished layout balanced, (2) admit a loading
|
| 657 |
+
order that never tips the plank (the task is solvable) and (3) agree with every observed placement (tipped or
|
| 658 |
+
not, with a +-10 % band in which either outcome counts as consistent). Falls back to (1)+(2) if no assignment
|
| 659 |
+
agrees with all observations."""
|
| 660 |
+
marks = self.inst["marks"]
|
| 661 |
+
prior = []
|
| 662 |
+
for k in range(5):
|
| 663 |
+
for heavy in itertools.combinations(COLORS, k):
|
| 664 |
+
mass = {c: (H_EST if c in heavy else L_EST) for c in COLORS}
|
| 665 |
+
if tip_ratio([(mass[c], marks[c]) for c in COLORS]) > 0.6:
|
| 666 |
+
continue
|
| 667 |
+
for order in itertools.permutations(COLORS):
|
| 668 |
+
cur, w = [], 0.0
|
| 669 |
+
for c in order:
|
| 670 |
+
cur.append((mass[c], marks[c]))
|
| 671 |
+
w = max(w, tip_ratio(cur))
|
| 672 |
+
if w <= 0.9:
|
| 673 |
+
prior.append(mass)
|
| 674 |
+
break
|
| 675 |
+
if not use_obs:
|
| 676 |
+
return prior
|
| 677 |
+
post = []
|
| 678 |
+
for mass in prior:
|
| 679 |
+
if all(not ((ob["tipped"] and r < 0.9) or (not ob["tipped"] and r > 1.1))
|
| 680 |
+
for ob in self.obs for r in [tip_ratio([(mass[o], y) for o, y in ob["conf"].items()])]):
|
| 681 |
+
post.append(mass)
|
| 682 |
+
return post or prior
|
| 683 |
+
|
| 684 |
+
def unload_until_level(self, max_moves=4):
|
| 685 |
+
"""while the plank is tipped: take the cube farthest out on its low side off the plank"""
|
| 686 |
+
for _ in range(max_moves):
|
| 687 |
+
envs.settle(self.env, 20)
|
| 688 |
+
self.wait_calm()
|
| 689 |
+
if self.is_level():
|
| 690 |
+
return True
|
| 691 |
+
t = self.tilt_deg()
|
| 692 |
+
yo = self._y_on_plank()
|
| 693 |
+
low = [c for c, y in yo.items() if (y > 0) == (t < 0)]
|
| 694 |
+
if not low:
|
| 695 |
+
return self.is_level()
|
| 696 |
+
self.park(min(low, key=lambda o: abs(yo[o]))) # the top of the pile first: the hand clears the others
|
| 697 |
+
envs.settle(self.env, 20)
|
| 698 |
+
self.wait_calm()
|
| 699 |
+
return self.is_level()
|
| 700 |
+
|
| 701 |
+
def restore(self, hyps_fn, rounds=3, record=False):
|
| 702 |
+
"""Check every stage; if something is wrong: unload the low end if the plank is tipped, then (re)place every
|
| 703 |
+
cube that is not on its mark in the order the static model rates safest under the current mass hypotheses;
|
| 704 |
+
start over after a tip. Up to `rounds` passes."""
|
| 705 |
+
for _ in range(rounds):
|
| 706 |
+
envs.settle(self.env, 20)
|
| 707 |
+
if all(self.stage_values().values()):
|
| 708 |
+
return True
|
| 709 |
+
self.unload_until_level()
|
| 710 |
+
todo = [c for c in COLORS if not self.on_mark(c)]
|
| 711 |
+
if not todo:
|
| 712 |
+
continue
|
| 713 |
+
hyps = hyps_fn()
|
| 714 |
+
order, worst = self.plan(todo, hyps)
|
| 715 |
+
if worst > 0.9: # cubes left on the plank make every order risky: clear it and start from empty
|
| 716 |
+
for c in [c for c in COLORS if self.on_plank(c)]:
|
| 717 |
+
self.park(c)
|
| 718 |
+
order, worst = self.plan(list(COLORS), hyps)
|
| 719 |
+
for c in order:
|
| 720 |
+
if self.on_mark(c):
|
| 721 |
+
continue
|
| 722 |
+
if self.put(c, Z_CARRY, record=record, careful=True):
|
| 723 |
+
break # tipped: look again
|
| 724 |
+
envs.settle(self.env, 20)
|
| 725 |
+
return all(self.stage_values().values())
|
| 726 |
+
|
| 727 |
+
def naive_order(self, noise_sd=0.0, rng=None):
|
| 728 |
+
"""nearest cube first, starting from the gripper's position and then from each mark just loaded"""
|
| 729 |
+
p = self.sk.eef_pos()[:2]
|
| 730 |
+
left, order = list(COLORS), []
|
| 731 |
+
while left:
|
| 732 |
+
dist = {c: np.linalg.norm(self.cube_pos(c)[:2] - p) + (rng.normal(0, noise_sd) if rng is not None else 0.0)
|
| 733 |
+
for c in left}
|
| 734 |
+
c = min(left, key=dist.get)
|
| 735 |
+
order.append(c)
|
| 736 |
+
left.remove(c)
|
| 737 |
+
p = self.mark_world(c)[:2]
|
| 738 |
+
return order
|
| 739 |
+
|
| 740 |
+
def slot_order(self, kind):
|
| 741 |
+
so = {s: c for c, s in self.inst["slot_of"].items()}
|
| 742 |
+
seq = dict(end2end=SLOTS, alt_outer=("near_outer", "far_outer", "near_inner", "far_inner"),
|
| 743 |
+
alt_inner=("near_inner", "far_inner", "near_outer", "far_outer"))[kind]
|
| 744 |
+
return [so[s] for s in seq]
|
| 745 |
+
|
| 746 |
+
def execute(self, inst, params):
|
| 747 |
+
rng = np.random.default_rng(params.get("seed", 0))
|
| 748 |
+
mode = params["mode"]
|
| 749 |
+
if mode == "plan":
|
| 750 |
+
hyps = [dict(inst["mass"])] if params.get("true_masses") else self.hypotheses()
|
| 751 |
+
order, _ = self.plan(list(COLORS), hyps)
|
| 752 |
+
elif mode in ("end2end", "alt_outer", "alt_inner"):
|
| 753 |
+
order = self.slot_order(mode)
|
| 754 |
+
else: # nearest first (naive / blind)
|
| 755 |
+
order = self.naive_order(params.get("order_noise", 0.0), rng)
|
| 756 |
+
noise = params.get("noise", 0.0)
|
| 757 |
+
z_carry = Z_CARRY if params.get("careful") else Z_CARRY_NAIVE
|
| 758 |
+
for c in order:
|
| 759 |
+
nz = rng.uniform(-noise, noise, 2) if noise else None
|
| 760 |
+
tipped = self.put(c, z_carry, noise=nz, record=params.get("record", False), careful=params.get("careful", False))
|
| 761 |
+
if tipped and params.get("check_each"):
|
| 762 |
+
break # look at what happened, then restore below
|
| 763 |
+
if params.get("check"):
|
| 764 |
+
hyps_fn = (lambda: [dict(inst["mass"])]) if params.get("true_masses") else self.hypotheses
|
| 765 |
+
self.restore(hyps_fn, record=params.get("record", False))
|
| 766 |
+
self.sk.hold(10)
|
| 767 |
+
return order
|
| 768 |
+
|
| 769 |
+
def default_params(self, inst):
|
| 770 |
+
return dict(mode="nearest", check=False)
|
| 771 |
+
|
| 772 |
+
def oracle_params(self, inst):
|
| 773 |
+
return dict(mode="plan", true_masses=True, careful=True, check=True)
|
| 774 |
+
|
| 775 |
+
def adapt_params(self, inst, history):
|
| 776 |
+
"""from attempt 2: load in the order the observations of earlier attempts make safest, check after every
|
| 777 |
+
placement and restore at the end"""
|
| 778 |
+
return dict(mode="plan", careful=True, check=True, check_each=True, record=True)
|
| 779 |
+
|
| 780 |
+
def blind_params(self, inst, attempt, rng):
|
| 781 |
+
"""nearest-first again with small random variation (order noise, 4 mm placement noise), no history, no check"""
|
| 782 |
+
return dict(mode="nearest", check=False, order_noise=0.03, noise=0.004, seed=int(rng.integers(1 << 30)))
|
| 783 |
+
|
| 784 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 785 |
+
k = k or self.max_attempts
|
| 786 |
+
rng = np.random.default_rng(seed)
|
| 787 |
+
history = []
|
| 788 |
+
self.obs = []
|
| 789 |
+
for a in range(k):
|
| 790 |
+
self.reset_instance(inst)
|
| 791 |
+
if kind == "oracle":
|
| 792 |
+
params = self.oracle_params(inst)
|
| 793 |
+
elif kind == "naive":
|
| 794 |
+
params = self.default_params(inst)
|
| 795 |
+
elif kind == "adaptive": # attempt 1: natural order, but look after every placement and restore
|
| 796 |
+
params = (dict(mode="nearest", check=True, check_each=True, record=True) if a == 0 else
|
| 797 |
+
self.adapt_params(inst, history))
|
| 798 |
+
elif kind == "blind":
|
| 799 |
+
params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
|
| 800 |
+
elif kind in ("end2end", "alt_outer", "alt_inner"): # extra controls: other natural orders, no check
|
| 801 |
+
params = dict(mode=kind, check=False)
|
| 802 |
+
elif kind == "oracle_noise": # extra control: the oracle with +-5 mm (uniform) placement noise
|
| 803 |
+
params = dict(self.oracle_params(inst), noise=0.005, seed=int(rng.integers(1 << 30)))
|
| 804 |
+
elif kind == "switch": # extra control: no in-attempt repair, learn the order across attempts only
|
| 805 |
+
params = (dict(mode="nearest", check=False, record=True) if a == 0 else
|
| 806 |
+
dict(mode="plan", careful=True, check=False, record=True))
|
| 807 |
+
else:
|
| 808 |
+
raise ValueError(kind)
|
| 809 |
+
order = self.execute(inst, params)
|
| 810 |
+
out = self.outcome(inst)
|
| 811 |
+
out["order"] = order
|
| 812 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 813 |
+
if on_attempt:
|
| 814 |
+
on_attempt(a, params, out)
|
| 815 |
+
if out["success"] or kind in ("oracle", "oracle_noise", "naive", "end2end", "alt_outer", "alt_inner"):
|
| 816 |
+
break
|
| 817 |
+
return history
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/lh_bridge.py
ADDED
|
@@ -0,0 +1,1101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""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
|
| 2 |
+
parked right behind the bridge site, and once the plank is down the agent's natural reach for it knocks the bridge down,
|
| 3 |
+
which must be rebuilt before the task can be finished.
|
| 4 |
+
|
| 5 |
+
Category: state_restoration, long-horizon self-inflicted regression. The user's example verbatim: "build a bridge;
|
| 6 |
+
while working you knock over a foundation you already built and must rebuild it before continuing".
|
| 7 |
+
|
| 8 |
+
v1 -> v2 (after the Sonnet 5.5 pilot lh1: only 1 of 3 instances was ever disturbed; Sonnet carried 12-20 cm high and
|
| 9 |
+
lifted over built pillars, so the v1 mechanism -- sweeping a pillar with a block carried low -- rarely happened; the one
|
| 10 |
+
disturbance was the hand landing on the plank while going for the red cube): the car now starts in the gap between the
|
| 11 |
+
two squares, 5.5-9 cm behind the bridge line (right behind where the plank will lie); a spare fifth block; the bridge
|
| 12 |
+
4-7 cm further from the robot and the plank nearer, so that knocked parts stay within reach; softer contacts for the
|
| 13 |
+
bridge parts (the stiff default made collapsing blocks fly 30-90 cm); the naive reference imitates Sonnet's measured
|
| 14 |
+
motion style instead of the v1 low-transit script (kept as naive_v1).
|
| 15 |
+
|
| 16 |
+
Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): two coloured square
|
| 17 |
+
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
|
| 18 |
+
(4 cm) in the gap between them, 5.5-9 cm behind the line through the squares (+-3 cm sideways, yaw +-20 deg); five
|
| 19 |
+
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
|
| 20 |
+
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.
|
| 21 |
+
|
| 22 |
+
Stages (order-free predicates, evaluated after every control step by a monitor; events are debounced over 6 steps):
|
| 23 |
+
S1 two blocks stacked on the blue square (lower block resting on the table within 2.5 cm of the square's centre,
|
| 24 |
+
upper block resting on it within 2.5 cm; any face down, cubes have no "right way up")
|
| 25 |
+
S2 the same on the green square
|
| 26 |
+
S3 the plank rests on the top blocks of both pillars: in contact with both, not with the table, tilt <= 10 deg
|
| 27 |
+
S4 the red cube rests on the plank within 6 cm of the plank's centre along its length
|
| 28 |
+
Success = all four hold at the end simultaneously, the scene is static (< 4 mm motion in 1 s) and the robot neither
|
| 29 |
+
holds nor touches any object. The monitor's achieved / lost / restored events go to the server log only (F1).
|
| 30 |
+
|
| 31 |
+
Why the agent breaks the bridge (measured, see task_cards/lh_bridge.md): with the plank down, the car sits 3-6.5 cm
|
| 32 |
+
behind the plank's back edge, between the pillars. The Panda hand is 21 cm long along the finger axis and its underside
|
| 33 |
+
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
|
| 34 |
+
differently; scripted here on seeds 1000-1019: hovering ~13 cm above it while turning the wrist from the plank's 90 deg
|
| 35 |
+
to the car's yaw, then straight down (5/20 knock the bridge), keeping the 90 deg wrist and going straight down (the hand
|
| 36 |
+
lands across the plank: 20/20), or one diagonal move from above the bridge straight down to the grasp (the hand drives
|
| 37 |
+
through the bridge: 20/20). The plank and one or both pillar tops fall; in 22 of 24 collapses (seeds 3000-3029) every
|
| 38 |
+
part needed stays within reach (a block out of reach is covered by the spare; the plank was thrown out of reach twice).
|
| 39 |
+
What prevents it (learnable from one failure, and what Sonnet wrote after its pilot failure): move the car away before
|
| 40 |
+
laying the plank.
|
| 41 |
+
|
| 42 |
+
Hidden variables: none that matter. Block size and friction are instance variety; the car's distance (5.5-9 cm) and yaw
|
| 43 |
+
decide only the "hover" style's outcome.
|
| 44 |
+
|
| 45 |
+
Scripted references (perception = simulator state):
|
| 46 |
+
naive Sonnet-like (measured on the pilot): instruction order; per pillar the free block nearest its square first;
|
| 47 |
+
hover ~12 cm above an object turned to its yaw, vertical descent, grasp 1.1 cm below the top; carry to a bare
|
| 48 |
+
square in one diagonal move to 12.5 cm above it, onto a block lift first; lift over a built pillar when the
|
| 49 |
+
carried block's straight path would hit it; release, lift to 15 cm; plank lifted to 7 cm, carried at 16 cm,
|
| 50 |
+
lift to 21 cm; the car approach style is the pilot's mixture (seed % 3: hover / keep / direct); no final check
|
| 51 |
+
naive_v1 the v1 naive (vertical / horizontal legs at 8 cm, carries at max(8 cm, release + 4 cm)), for comparison
|
| 52 |
+
oracle careful: first moves the car out of the zone behind the bridge; all transits at 25 cm, vertical approaches
|
| 53 |
+
at 0.1 m/s, grasps 1.6 cm below a cube's top, gripper yaw chosen for hand / finger clearance; checks every
|
| 54 |
+
stage at the end and repairs what is broken (same repair as adaptive)
|
| 55 |
+
adaptive attempt 1 = naive, then checks every stage before finishing and restores what was lost (tips a plank that
|
| 56 |
+
stands on edge, puts the plank and car aside, re-stacks the pillars from usable blocks, then plank and car
|
| 57 |
+
again); from attempt 2 the careful behaviour
|
| 58 |
+
blind naive with random variation (hover / carry / lift heights, diagonal or lift-first carries, car style,
|
| 59 |
+
block allocation, 4 mm placement noise), no history
|
| 60 |
+
|
| 61 |
+
Protocol: cross (reset to the same instance before every attempt), k = 3.
|
| 62 |
+
"""
|
| 63 |
+
import os
|
| 64 |
+
|
| 65 |
+
import numpy as np
|
| 66 |
+
|
| 67 |
+
from .. import envs
|
| 68 |
+
from ..bddl import write_bddl
|
| 69 |
+
from ..objects import _fmt, _wrap, box_xml, register_generated
|
| 70 |
+
from ..skills import Skills
|
| 71 |
+
from ..task_base import LFFTask, register_task
|
| 72 |
+
|
| 73 |
+
BLOCKS = ["block_a_1", "block_b_1", "block_c_1", "block_d_1", "block_e_1"] # four are needed, one is a spare
|
| 74 |
+
PLANK, CAR = "plank_1", "car_1"
|
| 75 |
+
SQUARES = ["square_blue_1", "square_green_1"] # S1 = blue, S2 = green
|
| 76 |
+
ITEMS = BLOCKS + [PLANK, CAR]
|
| 77 |
+
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),
|
| 78 |
+
(0.76, 0.60, 0.42, 1.0)] # wood
|
| 79 |
+
PLANK_HALF = (0.12, 0.025, 0.006) # 24 x 5 x 1.2 cm, long axis = body x
|
| 80 |
+
CAR_HALF = 0.02
|
| 81 |
+
BLOCK_NOM = 0.026 # nominal half edge in the MJCF (resized per instance)
|
| 82 |
+
SQ_HALF = 0.03
|
| 83 |
+
SQ_RGBA = {"square_blue_1": (0.12, 0.30, 0.90, 1.0), "square_green_1": (0.10, 0.70, 0.25, 1.0)}
|
| 84 |
+
SQ_NAME = {"square_blue_1": "blue", "square_green_1": "green"}
|
| 85 |
+
SPAN = 0.16 # square centre distance (along y)
|
| 86 |
+
|
| 87 |
+
TZ = envs.TABLE_Z
|
| 88 |
+
BASE_X = -0.66
|
| 89 |
+
HAND_HALF_LONG = 0.106 # Panda hand collision AABB about the grasp site: +-10.6 cm along the finger axis
|
| 90 |
+
HAND_HALF_SHORT = 0.036 # +-3.6 cm across it
|
| 91 |
+
HAND_BOTTOM = 0.024 # its underside is 2.4 cm above the grasp site (measured)
|
| 92 |
+
|
| 93 |
+
SQ_TOL = 0.025 # lower block centre within 2.5 cm of the square centre
|
| 94 |
+
STACK_TOL = 0.025 # upper block centre within 2.5 cm of the lower one
|
| 95 |
+
FLAT_COS = np.cos(np.radians(12))
|
| 96 |
+
PLANK_TILT = np.radians(10)
|
| 97 |
+
CAR_MID = 0.06
|
| 98 |
+
DEBOUNCE = 6 # control steps a predicate must keep its new value before an event is recorded
|
| 99 |
+
|
| 100 |
+
# v2 layout (2026-10-09): the red cube ("car") is parked in the gap between the two squares, just behind the bridge
|
| 101 |
+
# line, so that once the plank is down a natural top-down grasp of it lands the hand on the plank / pillar tops; the
|
| 102 |
+
# four wooden blocks lie in a row behind the bridge, two on each side of the car; the plank lies further back.
|
| 103 |
+
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,
|
| 104 |
+
car_clear=0.08, car_yaw=0.35, plank_dx=(0.19, 0.21), block_edge=(0.050, 0.056))
|
| 105 |
+
KEEP_OUT = dict(dx=0.13, dy=0.20) # careful: no parking / no material left within this zone behind the bridge line
|
| 106 |
+
# Sonnet-like naive (measured on the lh1 pilot, see task_cards/lh_bridge.md): heights of the grasp site above the table
|
| 107 |
+
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,
|
| 108 |
+
end_lift=0.25, top_below=0.011, diag=True, car_style=None, car_hover=0.134, plank_end_lift=0.21,
|
| 109 |
+
alloc="greedy")
|
| 110 |
+
# how the gripper went for the red cube once the plank was down -- each of the three pilot runs did it differently:
|
| 111 |
+
# hover (seed 3002) move to ~13.4 cm above it while turning to its yaw, then straight down
|
| 112 |
+
# keep (seed 3000) the same, but still turned 90 deg from laying the plank
|
| 113 |
+
# direct (seed 3001) one move from ~21 cm above the bridge straight (diagonally) down to the grasp
|
| 114 |
+
# the naive script uses style CAR_STYLES[seed % 3] (car_style=None), i.e. the pilot's mixture
|
| 115 |
+
CAR_STYLES = ("hover", "keep", "direct")
|
| 116 |
+
Z_NAIVE = 0.08 # naive_v1 transit height of the grasp site above the table
|
| 117 |
+
Z_SAFE = 0.25 # careful transit height
|
| 118 |
+
NAIVE_LIFT = 0.05 # naive: lift this far straight up after letting go, then head for the next waypoint
|
| 119 |
+
NAIVE_STYLE = "legs" # legs: vertical / horizontal legs at the transit height; diag: straight lines between waypoints
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _wrap_q(a):
|
| 123 |
+
"""wrap to [-pi/4, pi/4) (cubes are symmetric under 90 deg)"""
|
| 124 |
+
return float((a + np.pi / 4) % (np.pi / 2) - np.pi / 4)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _wrap_h(a):
|
| 128 |
+
"""wrap to [-pi/2, pi/2) (plank / gripper symmetric under 180 deg)"""
|
| 129 |
+
return float((a + np.pi / 2) % np.pi - np.pi / 2)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
# Contact softness of the bridge parts. LFF-Bench's generated boxes use a very stiff contact (objects._SOLID); when a
|
| 133 |
+
# fast hand drives into a stacked bridge, the stiff contacts resolve the overlap with large impulses and blocks fly
|
| 134 |
+
# 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
|
| 135 |
+
# softer contact (MuJoCo-like defaults) keeps collapses local. None = use the stiff default.
|
| 136 |
+
CONTACT = os.environ.get("LFF_LHB_CONTACT", 'solimp="0.95 0.99 0.001" solref="0.01 1"')
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def part_xml(model_name, half, rgba, density):
|
| 140 |
+
"""box like objects.box_xml, with the task's contact softness"""
|
| 141 |
+
if not CONTACT or CONTACT == "stiff":
|
| 142 |
+
return box_xml(model_name, half, rgba, density=density)
|
| 143 |
+
g = (f' <geom name="{model_name}_g0" type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" '
|
| 144 |
+
f'density="{density}" friction="1.0 0.005 0.0001" {CONTACT} group="0" />\n'
|
| 145 |
+
f' <geom type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" conaffinity="0" contype="0" group="1" />')
|
| 146 |
+
return _wrap(model_name, g, half[2], float(np.hypot(half[0], half[1])))
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def mark_xml(name, rgba):
|
| 150 |
+
"""flat coloured square, visual only (does not touch the physics)"""
|
| 151 |
+
g = (f' <geom type="box" size="{SQ_HALF:.5f} {SQ_HALF:.5f} 0.00060" rgba="{_fmt(rgba)}" '
|
| 152 |
+
f'contype="0" conaffinity="0" group="1" />')
|
| 153 |
+
return _wrap(name, g, 0.0006, SQ_HALF * 1.42)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class BridgeSkills(Skills):
|
| 157 |
+
"""Skills that feed the task's per-step stage monitor."""
|
| 158 |
+
|
| 159 |
+
def __init__(self, env, task, recorder=None):
|
| 160 |
+
super().__init__(env, recorder=recorder)
|
| 161 |
+
self.task = task
|
| 162 |
+
|
| 163 |
+
def _act(self, dpos, drot, grip):
|
| 164 |
+
super()._act(dpos, drot, grip)
|
| 165 |
+
self.task.monitor_step()
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
@register_task
|
| 169 |
+
class Bridge(LFFTask):
|
| 170 |
+
name = "lh_bridge"
|
| 171 |
+
level = "L2"
|
| 172 |
+
category = "state_restoration"
|
| 173 |
+
capabilities = ("Perceive", "Plan", "Reason", "Restore")
|
| 174 |
+
protocol = "cross"
|
| 175 |
+
max_attempts = 3
|
| 176 |
+
agent_max_steps = 130
|
| 177 |
+
instruction = ("Build a small bridge. First stack two of the wooden blocks on the blue square, then two on the green "
|
| 178 |
+
"square, to make two pillars; then lay the long plank across the tops of both pillars; finally put "
|
| 179 |
+
"the red cube on the middle of the plank. The finished bridge must stand on its own, with the "
|
| 180 |
+
"gripper open and not touching anything.")
|
| 181 |
+
instruction_indirect = ("Build a small bridge. First make a tower of two of the wooden cubes on the blue mark on the "
|
| 182 |
+
"table, then another tower of two on the green mark; then lay the long flat board across the "
|
| 183 |
+
"tops of the two towers; finally set the small red cube on the middle of the board. At the "
|
| 184 |
+
"end everything must stand on its own, with the gripper open and not touching anything.")
|
| 185 |
+
agent_object_names = ["wooden blocks (5)", "plank", "red cube", "blue square", "green square"]
|
| 186 |
+
|
| 187 |
+
# ------------------------------------------------------------ scene
|
| 188 |
+
def make_bddl(self):
|
| 189 |
+
objs = []
|
| 190 |
+
for i, b in enumerate(BLOCKS):
|
| 191 |
+
cat = register_generated(f"LffLhbBlock{'ABCDE'[i]}", part_xml(f"lff_lhb_block_{'abcde'[i]}", (BLOCK_NOM,) * 3,
|
| 192 |
+
BLOCK_RGBA[i], 500.0))
|
| 193 |
+
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)
|
| 194 |
+
objs.append((b, cat, f"blk{i}_region", reg))
|
| 195 |
+
pl = register_generated("LffLhbPlank", part_xml("lff_lhb_plank", PLANK_HALF, (0.50, 0.33, 0.18, 1.0),
|
| 196 |
+
density=600.0))
|
| 197 |
+
objs.append((PLANK, pl, "plank_region", (0.05, -0.01, 0.06, 0.01)))
|
| 198 |
+
car = register_generated("LffLhbCar", part_xml("lff_lhb_car", (CAR_HALF,) * 3, (0.85, 0.10, 0.08, 1.0),
|
| 199 |
+
density=400.0))
|
| 200 |
+
objs.append((CAR, car, "car_region", (-0.30, -0.31, -0.29, -0.30)))
|
| 201 |
+
fx = []
|
| 202 |
+
for i, s in enumerate(SQUARES):
|
| 203 |
+
cat = register_generated(f"LffLhbSquare{'BG'[i]}", mark_xml(f"lff_lhb_square_{'bg'[i]}", SQ_RGBA[s]),
|
| 204 |
+
free=False)
|
| 205 |
+
fx.append((s, cat, f"sq{i}_region", (-0.10 + 0.10 * i, -0.31, -0.09 + 0.10 * i, -0.30)))
|
| 206 |
+
return write_bddl(self.name, "Build a small bridge from the blocks the plank and the red cube", objs, fx)
|
| 207 |
+
|
| 208 |
+
def __init__(self, cam_res=None):
|
| 209 |
+
super().__init__(cam_res)
|
| 210 |
+
m = self.env.sim.model
|
| 211 |
+
self.sq_bid = {s: m.body_name2id(self.env.fixtures_dict[s].root_body) for s in SQUARES}
|
| 212 |
+
self.geoms = {o: envs.obj_geom_ids(self.env, o) for o in ITEMS}
|
| 213 |
+
self.vis_geoms = {}
|
| 214 |
+
for o in BLOCKS:
|
| 215 |
+
root = envs.body_id(self.env, o)
|
| 216 |
+
bodies = {b for b in range(m.nbody) if b == root or m.body_parentid[b] == root}
|
| 217 |
+
self.vis_geoms[o] = [g for g in range(m.ngeom) if m.geom_bodyid[g] in bodies and m.geom_contype[g] == 0
|
| 218 |
+
and m.geom_conaffinity[g] == 0 and m.geom_type[g] == 6]
|
| 219 |
+
self.block_body = getattr(self, "block_body", {})
|
| 220 |
+
self.block_body[o] = int(m.geom_bodyid[self.geoms[o][0]])
|
| 221 |
+
self.table_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("main_table")
|
| 222 |
+
and m.geom_contype[g] != 0]
|
| 223 |
+
self.robot_geoms = set(envs.robot_geom_ids(self.env))
|
| 224 |
+
self.inst = None
|
| 225 |
+
self.mon = None
|
| 226 |
+
self.sk = None
|
| 227 |
+
self.naive_lift = NAIVE_LIFT
|
| 228 |
+
self.naive_style = NAIVE_STYLE
|
| 229 |
+
|
| 230 |
+
# ------------------------------------------------------------ instances
|
| 231 |
+
def sample_instance(self, seed):
|
| 232 |
+
rng = np.random.default_rng(seed)
|
| 233 |
+
xb = float(rng.uniform(*LAYOUT["bridge_x"]))
|
| 234 |
+
yc = float(rng.uniform(-0.03, 0.03))
|
| 235 |
+
blue_left = bool(rng.random() < 0.5)
|
| 236 |
+
sq = {"square_blue_1": [xb, yc + (SPAN / 2 if blue_left else -SPAN / 2)],
|
| 237 |
+
"square_green_1": [xb, yc - (SPAN / 2 if blue_left else -SPAN / 2)]}
|
| 238 |
+
L = LAYOUT
|
| 239 |
+
# the car: in the gap between the two squares, just behind the bridge line
|
| 240 |
+
pos = {CAR: [xb + float(rng.uniform(*L["car_dx"])), yc + float(rng.uniform(-L["car_dy"], L["car_dy"]))]}
|
| 241 |
+
# five blocks in a row behind the bridge line, two on one side of the car and three on the other
|
| 242 |
+
row_x = xb + float(rng.uniform(*L["row_dx"]))
|
| 243 |
+
ys = []
|
| 244 |
+
three = 1.0 if rng.random() < 0.5 else -1.0
|
| 245 |
+
for side in (-1.0, 1.0):
|
| 246 |
+
n = 3 if side == three else 2
|
| 247 |
+
lo, hi = sorted((pos[CAR][1] + side * L["car_clear"], side * L["y_half"]))
|
| 248 |
+
u = np.sort(rng.uniform(0.0, max((hi - lo) - (n - 1) * L["gap"], 0.0), n))
|
| 249 |
+
ys += [lo + k * L["gap"] + u[k] for k in range(n)]
|
| 250 |
+
order = rng.permutation(5)
|
| 251 |
+
for k, j in enumerate(order):
|
| 252 |
+
pos[BLOCKS[j]] = [row_x + float(rng.uniform(-0.01, 0.01)), float(ys[k])]
|
| 253 |
+
plank_xy = [xb + float(rng.uniform(*L["plank_dx"])), yc + float(rng.uniform(-0.04, 0.04))]
|
| 254 |
+
size = {b: float(rng.uniform(*L["block_edge"])) for b in BLOCKS}
|
| 255 |
+
mu = {b: float(rng.uniform(0.3, 0.6)) for b in BLOCKS}
|
| 256 |
+
yaw = {o: float(rng.uniform(-0.35, 0.35)) for o in BLOCKS}
|
| 257 |
+
yaw[CAR] = float(rng.uniform(-L["car_yaw"], L["car_yaw"]))
|
| 258 |
+
yaw[PLANK] = float(np.pi / 2 + rng.uniform(-0.25, 0.25)) # long axis roughly left-right
|
| 259 |
+
pos[PLANK] = plank_xy
|
| 260 |
+
return dict(seed=int(seed), squares=sq, blue_side="left" if blue_left else "right", pos=pos, yaw=yaw,
|
| 261 |
+
size=size, mu=mu, bridge_x=xb, bridge_yc=yc)
|
| 262 |
+
|
| 263 |
+
def _resize_block(self, o, edge):
|
| 264 |
+
m = self.env.sim.model
|
| 265 |
+
h = edge / 2.0
|
| 266 |
+
for g in self.geoms[o] + self.vis_geoms[o]:
|
| 267 |
+
m.geom_size[g] = [h, h, h]
|
| 268 |
+
m.geom_rbound[g] = float(np.sqrt(3) * h)
|
| 269 |
+
m.geom_aabb[g] = [0.0, 0.0, 0.0, h, h, h]
|
| 270 |
+
b = self.block_body[o]
|
| 271 |
+
mass = 500.0 * edge ** 3
|
| 272 |
+
m.body_mass[b] = mass
|
| 273 |
+
m.body_inertia[b] = [mass * edge ** 2 / 6.0] * 3
|
| 274 |
+
envs.refit_bounds(self.env, b) # BVH of the resized block (envs.refit_bounds)
|
| 275 |
+
|
| 276 |
+
def apply_instance(self, inst):
|
| 277 |
+
self.inst = inst
|
| 278 |
+
m = self.env.sim.model
|
| 279 |
+
for s in SQUARES:
|
| 280 |
+
x, y = inst["squares"][s]
|
| 281 |
+
m.body_pos[self.sq_bid[s]] = [x, y, TZ + 0.0007]
|
| 282 |
+
m.body_quat[self.sq_bid[s]] = [1.0, 0.0, 0.0, 0.0]
|
| 283 |
+
for o in BLOCKS:
|
| 284 |
+
self._resize_block(o, inst["size"][o])
|
| 285 |
+
envs.set_friction(self.env, o, inst["mu"][o])
|
| 286 |
+
envs.set_friction(self.env, PLANK, 0.5)
|
| 287 |
+
envs.set_friction(self.env, CAR, 0.6)
|
| 288 |
+
self.env.sim.forward()
|
| 289 |
+
for o in ITEMS:
|
| 290 |
+
envs.place_upright(self.env, o, inst["pos"][o], inst["yaw"][o], clearance=0.001)
|
| 291 |
+
|
| 292 |
+
def reset_instance(self, inst, recorder=None):
|
| 293 |
+
self.mon = None
|
| 294 |
+
self.env.reset()
|
| 295 |
+
self.apply_instance(inst)
|
| 296 |
+
self.env.sim.forward()
|
| 297 |
+
envs.settle(self.env, 15)
|
| 298 |
+
self.sk = BridgeSkills(self.env, self, recorder=recorder)
|
| 299 |
+
self.mon = dict(state=[False] * 4, raw_since=[0] * 4, ever=[False] * 4, lost=[False] * 4, events=[])
|
| 300 |
+
return self.sk
|
| 301 |
+
|
| 302 |
+
# ------------------------------------------------------------ geometry / predicates
|
| 303 |
+
def half(self, o):
|
| 304 |
+
if o in BLOCKS:
|
| 305 |
+
e = self.inst["size"][o] / 2
|
| 306 |
+
return np.array([e, e, e])
|
| 307 |
+
return np.array(PLANK_HALF) if o == PLANK else np.array([CAR_HALF] * 3)
|
| 308 |
+
|
| 309 |
+
def R(self, o):
|
| 310 |
+
return self.env.sim.data.body_xmat[envs.body_id(self.env, o)].reshape(3, 3).copy()
|
| 311 |
+
|
| 312 |
+
def pos(self, o):
|
| 313 |
+
return envs.obj_pos(self.env, o)
|
| 314 |
+
|
| 315 |
+
def zmin(self, o):
|
| 316 |
+
return envs.obj_min_z(self.env, o)
|
| 317 |
+
|
| 318 |
+
def zmax(self, o):
|
| 319 |
+
return envs.obj_max_z(self.env, o)
|
| 320 |
+
|
| 321 |
+
def flat(self, o):
|
| 322 |
+
return float(np.max(np.abs(self.R(o)[2]))) > FLAT_COS
|
| 323 |
+
|
| 324 |
+
def yaw_of(self, o):
|
| 325 |
+
"""yaw of the object's body x axis (for the plank: its long axis)"""
|
| 326 |
+
R = self.R(o)
|
| 327 |
+
return float(np.arctan2(R[1, 0], R[0, 0]))
|
| 328 |
+
|
| 329 |
+
def held(self, o):
|
| 330 |
+
return self.sk is not None and self.sk.holding(o)
|
| 331 |
+
|
| 332 |
+
def contacts(self, a_geoms, b_geoms):
|
| 333 |
+
return envs.contacts_between(self.env, a_geoms, b_geoms)
|
| 334 |
+
|
| 335 |
+
def pillar(self, s):
|
| 336 |
+
"""(lower, upper) blocks of a complete pillar on square s, else (lower or None, None)"""
|
| 337 |
+
c = np.asarray(self.inst["squares"][s])
|
| 338 |
+
lower = None
|
| 339 |
+
for b in BLOCKS:
|
| 340 |
+
p = self.pos(b)
|
| 341 |
+
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):
|
| 342 |
+
lower = b
|
| 343 |
+
break
|
| 344 |
+
if lower is None:
|
| 345 |
+
return None, None
|
| 346 |
+
pl = self.pos(lower)
|
| 347 |
+
top = self.zmax(lower)
|
| 348 |
+
for b in BLOCKS:
|
| 349 |
+
if b == lower:
|
| 350 |
+
continue
|
| 351 |
+
p = self.pos(b)
|
| 352 |
+
if (np.linalg.norm(p[:2] - pl[:2]) <= STACK_TOL and abs(self.zmin(b) - top) < 0.006 and self.flat(b)
|
| 353 |
+
and not self.held(b)):
|
| 354 |
+
return lower, b
|
| 355 |
+
return lower, None
|
| 356 |
+
|
| 357 |
+
def plank_ok(self, tops):
|
| 358 |
+
if any(t is None for t in tops) or self.held(PLANK):
|
| 359 |
+
return False
|
| 360 |
+
R = self.R(PLANK)
|
| 361 |
+
if abs(R[2, 0]) > np.sin(PLANK_TILT) or abs(R[2, 2]) < np.cos(PLANK_TILT): # either broad face up (v2 fix)
|
| 362 |
+
return False
|
| 363 |
+
if self.zmin(PLANK) < TZ + 0.03 or self.contacts(self.geoms[PLANK], self.table_geoms):
|
| 364 |
+
return False
|
| 365 |
+
return all(self.contacts(self.geoms[PLANK], self.geoms[t]) for t in tops)
|
| 366 |
+
|
| 367 |
+
def car_ok(self):
|
| 368 |
+
"""the car rests on the plank's upper face (in the plank's own frame, so a slightly tilted plank is fine),
|
| 369 |
+
within CAR_MID of the plank's centre along its length"""
|
| 370 |
+
if self.held(CAR) or not self.contacts(self.geoms[CAR], self.geoms[PLANK]):
|
| 371 |
+
return False
|
| 372 |
+
R = self.R(PLANK)
|
| 373 |
+
rel = R.T @ (self.pos(CAR) - self.pos(PLANK))
|
| 374 |
+
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)
|
| 375 |
+
return bool(abs(rel[0]) <= CAR_MID and abs(rel[1]) <= PLANK_HALF[1] + 0.01 and up > PLANK_HALF[2] + 0.01)
|
| 376 |
+
|
| 377 |
+
def stages(self):
|
| 378 |
+
"""raw predicate values [S1, S2, S3, S4] and the pillars found"""
|
| 379 |
+
pa = self.pillar(SQUARES[0])
|
| 380 |
+
pb = self.pillar(SQUARES[1])
|
| 381 |
+
s1, s2 = pa[1] is not None, pb[1] is not None
|
| 382 |
+
s3 = bool(s1 and s2 and self.plank_ok([pa[1], pb[1]]))
|
| 383 |
+
s4 = bool(self.car_ok())
|
| 384 |
+
return [s1, s2, s3, s4], (pa, pb)
|
| 385 |
+
|
| 386 |
+
# ------------------------------------------------------------ monitor
|
| 387 |
+
def monitor_step(self):
|
| 388 |
+
mon = self.mon
|
| 389 |
+
if mon is None or self.sk is None:
|
| 390 |
+
return
|
| 391 |
+
raw, _ = self.stages()
|
| 392 |
+
t = self.sk.n_steps
|
| 393 |
+
for i in range(4):
|
| 394 |
+
if raw[i] == mon["state"][i]:
|
| 395 |
+
mon["raw_since"][i] = 0
|
| 396 |
+
continue
|
| 397 |
+
mon["raw_since"][i] += 1
|
| 398 |
+
if mon["raw_since"][i] < DEBOUNCE:
|
| 399 |
+
continue
|
| 400 |
+
mon["state"][i] = raw[i]
|
| 401 |
+
mon["raw_since"][i] = 0
|
| 402 |
+
t0 = t - DEBOUNCE + 1
|
| 403 |
+
if raw[i]:
|
| 404 |
+
ev = "restored" if mon["lost"][i] else "achieved"
|
| 405 |
+
mon["ever"][i] = True
|
| 406 |
+
else:
|
| 407 |
+
ev = "lost"
|
| 408 |
+
mon["lost"][i] = True
|
| 409 |
+
mon["events"].append(dict(stage=f"S{i + 1}", event=ev, step=int(t0)))
|
| 410 |
+
|
| 411 |
+
# ------------------------------------------------------------ outcome
|
| 412 |
+
def _dir_words(self, d):
|
| 413 |
+
"""robot-centric words for a horizontal offset d (world x = forward, away from the robot; y = robot's left)"""
|
| 414 |
+
parts = []
|
| 415 |
+
if abs(d[0]) >= 0.01:
|
| 416 |
+
parts.append(f"{100 * abs(d[0]):.0f} cm {'forward' if d[0] > 0 else 'back'}")
|
| 417 |
+
if abs(d[1]) >= 0.01:
|
| 418 |
+
parts.append(f"{100 * abs(d[1]):.0f} cm {'left' if d[1] > 0 else 'right'}")
|
| 419 |
+
return (" and ".join(parts) + " of") if parts else "right at"
|
| 420 |
+
|
| 421 |
+
def outcome(self, inst):
|
| 422 |
+
sk = self.sk
|
| 423 |
+
sk.hold(10)
|
| 424 |
+
p0 = {o: self.pos(o) for o in ITEMS}
|
| 425 |
+
touching = False
|
| 426 |
+
for _ in range(20):
|
| 427 |
+
sk.hold(1)
|
| 428 |
+
touching = touching or any(self.contacts(list(self.robot_geoms), self.geoms[o]) for o in ITEMS)
|
| 429 |
+
moved = max(float(np.linalg.norm(self.pos(o) - p0[o])) for o in ITEMS)
|
| 430 |
+
static = moved < 0.004
|
| 431 |
+
raw, (pa, pb) = self.stages()
|
| 432 |
+
held = [o for o in ITEMS if sk.holding(o)]
|
| 433 |
+
mon = self.mon
|
| 434 |
+
ev = list(mon["events"]) if mon else []
|
| 435 |
+
n_reg = sum(e["event"] == "lost" for e in ev)
|
| 436 |
+
n_res = sum(e["event"] == "restored" for e in ev)
|
| 437 |
+
success = bool(all(raw) and static and not held and not touching)
|
| 438 |
+
parts = []
|
| 439 |
+
if success:
|
| 440 |
+
failure = "none"
|
| 441 |
+
parts.append("The bridge is complete: both pillars stand on their squares, the plank rests across them "
|
| 442 |
+
"and the red cube sits on the middle of the plank.")
|
| 443 |
+
else:
|
| 444 |
+
lost_final = [i for i in range(4) if not raw[i] and mon and mon["ever"][i]]
|
| 445 |
+
never = [i for i in range(4) if not raw[i] and not (mon and mon["ever"][i])]
|
| 446 |
+
if held:
|
| 447 |
+
failure = "held"
|
| 448 |
+
elif touching:
|
| 449 |
+
failure = "touching"
|
| 450 |
+
elif lost_final:
|
| 451 |
+
failure = "regressed_" + "".join(f"S{i + 1}" for i in lost_final)
|
| 452 |
+
elif never:
|
| 453 |
+
failure = "incomplete_" + "".join(f"S{i + 1}" for i in never)
|
| 454 |
+
else:
|
| 455 |
+
failure = "not_static"
|
| 456 |
+
for i, s in enumerate(SQUARES):
|
| 457 |
+
if raw[i]:
|
| 458 |
+
continue
|
| 459 |
+
low, _ = (pa, pb)[i]
|
| 460 |
+
c = np.asarray(inst["squares"][s])
|
| 461 |
+
txt = f"The pillar on the {SQ_NAME[s]} square is not standing:"
|
| 462 |
+
if low is None:
|
| 463 |
+
txt += " no block stands on the square."
|
| 464 |
+
else:
|
| 465 |
+
txt += " only one block stands on the square."
|
| 466 |
+
strays = [b for b in BLOCKS if b not in (pa[0], pa[1], pb[0], pb[1])]
|
| 467 |
+
if strays:
|
| 468 |
+
near = min(strays, key=lambda b: np.linalg.norm(self.pos(b)[:2] - c))
|
| 469 |
+
txt += f" The nearest loose block lies {self._dir_words(self.pos(near)[:2] - c)} the square."
|
| 470 |
+
if mon and mon["ever"][i]:
|
| 471 |
+
txt += " It had been built and was knocked down later."
|
| 472 |
+
parts.append(txt)
|
| 473 |
+
if not raw[2]:
|
| 474 |
+
pp = self.pos(PLANK)
|
| 475 |
+
if self.contacts(self.geoms[PLANK], self.table_geoms):
|
| 476 |
+
where = "touches the table"
|
| 477 |
+
elif self.held(PLANK):
|
| 478 |
+
where = "is still in the gripper"
|
| 479 |
+
else:
|
| 480 |
+
where = "does not rest level on the tops of both pillars"
|
| 481 |
+
bc = np.mean([inst["squares"][s] for s in SQUARES], axis=0)
|
| 482 |
+
parts.append(f"The plank {where}; its centre is {self._dir_words(pp[:2] - bc)} the middle between "
|
| 483 |
+
f"the squares." + (" It had been laid and was disturbed later." if mon and mon["ever"][2]
|
| 484 |
+
and not raw[2] else ""))
|
| 485 |
+
if not raw[3]:
|
| 486 |
+
if self.held(CAR):
|
| 487 |
+
parts.append("The red cube is still in the gripper.")
|
| 488 |
+
elif self.contacts(self.geoms[CAR], self.geoms[PLANK]):
|
| 489 |
+
parts.append("The red cube is on the plank but not on its middle part.")
|
| 490 |
+
else:
|
| 491 |
+
bc = np.mean([inst["squares"][s] for s in SQUARES], axis=0)
|
| 492 |
+
parts.append(f"The red cube is not on the plank; it lies {self._dir_words(self.pos(CAR)[:2] - bc)} "
|
| 493 |
+
"the middle between the squares.")
|
| 494 |
+
if all(raw) and held:
|
| 495 |
+
parts.append("The gripper still holds an object.")
|
| 496 |
+
elif touching:
|
| 497 |
+
parts.append("The gripper is still touching the bridge.")
|
| 498 |
+
elif all(raw) and not static:
|
| 499 |
+
parts.append("The bridge was still moving.")
|
| 500 |
+
if n_reg:
|
| 501 |
+
parts.append(f"During the attempt earlier stages were undone {n_reg} time(s) and restored {n_res} time(s).")
|
| 502 |
+
if any(w in " ".join(parts) for w in (" forward of", " back of", " back and", " forward and")):
|
| 503 |
+
parts.append("(Forward = away from the robot.)")
|
| 504 |
+
return dict(success=success, stages={f"S{i + 1}": bool(raw[i]) for i in range(4)}, events=ev,
|
| 505 |
+
n_regressions=int(n_reg), n_restored=int(n_res), failure=failure, held=held,
|
| 506 |
+
touching=bool(touching), static=bool(static), detail=" ".join(parts))
|
| 507 |
+
|
| 508 |
+
# ------------------------------------------------------------ scripted policies (move_to + gripper only)
|
| 509 |
+
def _grip_yaws(self, o):
|
| 510 |
+
"""candidate gripper yaws for a top-down grasp of o (fingers across a face)"""
|
| 511 |
+
if o == PLANK: # fingers (which open along the gripper's y at yaw 0) across the plank's width
|
| 512 |
+
return [_wrap_h(self.yaw_of(PLANK))]
|
| 513 |
+
a = _wrap_q(self.yaw_of(o))
|
| 514 |
+
return [a, _wrap_h(a + np.pi / 2)]
|
| 515 |
+
|
| 516 |
+
def footprint(self, o):
|
| 517 |
+
"""sample points on the horizontal footprint of o (corners, edge midpoints, centre)"""
|
| 518 |
+
R, c, h = self.R(o), self.pos(o), self.half(o)
|
| 519 |
+
pts = []
|
| 520 |
+
for sx in (-1, 0, 1):
|
| 521 |
+
for sy in (-1, 0, 1):
|
| 522 |
+
for sz in ((-1, 1) if o != PLANK else (0,)):
|
| 523 |
+
pts.append((c + R @ (h * [sx, sy, sz]))[:2])
|
| 524 |
+
if o == PLANK:
|
| 525 |
+
for t_ in np.linspace(-1, 1, 9):
|
| 526 |
+
for sy in (-1, 1):
|
| 527 |
+
pts.append((c + R @ (h * [t_, sy, 0]))[:2])
|
| 528 |
+
return np.array(pts)
|
| 529 |
+
|
| 530 |
+
def _hand_clearance(self, xy, yaw, z_site, ignore=()):
|
| 531 |
+
"""smallest horizontal clearance (m) between the gripper at a grasp-site height z_site and everything else:
|
| 532 |
+
the hand body (+-10.6 x +-3.6 cm, underside 2.4 cm above the site) against items taller than its underside,
|
| 533 |
+
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)
|
| 534 |
+
against items taller than the fingertips. Negative = the gripper would land on something."""
|
| 535 |
+
f = np.array([-np.sin(yaw), np.cos(yaw)]) # finger axis
|
| 536 |
+
g = np.array([np.cos(yaw), np.sin(yaw)])
|
| 537 |
+
best = 1.0
|
| 538 |
+
for o in ITEMS:
|
| 539 |
+
if o in ignore or self.held(o):
|
| 540 |
+
continue
|
| 541 |
+
top = self.zmax(o)
|
| 542 |
+
if top < z_site - 0.013:
|
| 543 |
+
continue
|
| 544 |
+
d = self.footprint(o) - np.asarray(xy)
|
| 545 |
+
u, v = np.abs(d @ f), np.abs(d @ g)
|
| 546 |
+
c = float(np.min(np.maximum(np.abs(u - 0.040) - 0.010, v - 0.012))) # fingers
|
| 547 |
+
if top >= z_site + HAND_BOTTOM - 0.002:
|
| 548 |
+
c = min(c, float(np.min(np.maximum(u - HAND_HALF_LONG, v - HAND_HALF_SHORT))))
|
| 549 |
+
best = min(best, c)
|
| 550 |
+
return best
|
| 551 |
+
|
| 552 |
+
@staticmethod
|
| 553 |
+
def _pick_yaw(yaws, clearance):
|
| 554 |
+
"""the gripper yaw closest to straight (0) among those with >= 1 cm clearance, else the clearest one (large
|
| 555 |
+
wrist turns near the edge of the workspace make the OSC stop short)"""
|
| 556 |
+
c = {a: clearance(a) for a in yaws}
|
| 557 |
+
ok = [a for a in yaws if c[a] >= 0.01]
|
| 558 |
+
return min(ok, key=abs) if ok else max(yaws, key=c.get)
|
| 559 |
+
|
| 560 |
+
def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=250):
|
| 561 |
+
return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
|
| 562 |
+
|
| 563 |
+
def _grasp_z(self, o, careful):
|
| 564 |
+
if o in BLOCKS:
|
| 565 |
+
return self.zmax(o) - (0.016 if careful else self.inst["size"][o] / 2)
|
| 566 |
+
if o == PLANK:
|
| 567 |
+
return max(self.zmax(PLANK) + 0.0003 - 0.0125, TZ + 0.011)
|
| 568 |
+
return self.zmax(CAR) - (0.016 if careful else CAR_HALF)
|
| 569 |
+
|
| 570 |
+
def pick(self, o, careful, noise=None, z_t=None):
|
| 571 |
+
"""top-down grasp; returns the drop of the object's bottom below the grasp site, or None if not held"""
|
| 572 |
+
sk = self.sk
|
| 573 |
+
p = self.pos(o)
|
| 574 |
+
if noise is not None:
|
| 575 |
+
p = p + np.array([noise[0], noise[1], 0.0])
|
| 576 |
+
zg = self._grasp_z(o, careful)
|
| 577 |
+
yaws = self._grip_yaws(o)
|
| 578 |
+
if careful:
|
| 579 |
+
yaw = self._pick_yaw(yaws, lambda a: self._hand_clearance(p[:2], a, zg, ignore=(o,)))
|
| 580 |
+
cur = sk.eef_pos()
|
| 581 |
+
self._go([cur[0], cur[1], TZ + Z_SAFE])
|
| 582 |
+
self._go([p[0], p[1], TZ + Z_SAFE], yaw=yaw)
|
| 583 |
+
sk.set_gripper(False, steps=8)
|
| 584 |
+
self._go([p[0], p[1], zg + 0.03], speed=0.25)
|
| 585 |
+
self._go([p[0], p[1], zg], speed=0.1, tol=0.003, max_steps=120)
|
| 586 |
+
else:
|
| 587 |
+
yaw = min(yaws, key=lambda a: abs(a))
|
| 588 |
+
zt = TZ + (Z_NAIVE if z_t is None else z_t)
|
| 589 |
+
sk.set_gripper(False, steps=8)
|
| 590 |
+
if self.naive_style == "legs": # rise to the transit height if below it, across, straight down
|
| 591 |
+
cur = sk.eef_pos()
|
| 592 |
+
if cur[2] < zt - 0.003:
|
| 593 |
+
self._go([cur[0], cur[1], zt])
|
| 594 |
+
self._go([p[0], p[1], max(cur[2], zt)], yaw=yaw)
|
| 595 |
+
else: # one straight line to the approach point above the object
|
| 596 |
+
self._go([p[0], p[1], max(zt, self.zmax(o) + 0.03)], yaw=yaw)
|
| 597 |
+
self._go([p[0], p[1], zg], tol=0.003, max_steps=120)
|
| 598 |
+
sk.set_gripper(True, steps=15)
|
| 599 |
+
drop = float(sk.eef_pos()[2] - self.zmin(o))
|
| 600 |
+
if careful:
|
| 601 |
+
self._go([p[0], p[1], TZ + Z_SAFE], speed=0.3)
|
| 602 |
+
else:
|
| 603 |
+
zt = TZ + (Z_NAIVE if z_t is None else z_t)
|
| 604 |
+
self._go([p[0], p[1], max(zt, zg + 0.05)])
|
| 605 |
+
if not sk.holding(o):
|
| 606 |
+
sk.set_gripper(False, steps=8)
|
| 607 |
+
return None
|
| 608 |
+
return drop
|
| 609 |
+
|
| 610 |
+
def place(self, o, xy, support_top, drop, yaw, careful, z_t=None, release_gap=0.005, lift=None):
|
| 611 |
+
sk = self.sk
|
| 612 |
+
zr = support_top + drop + release_gap
|
| 613 |
+
if careful and o != PLANK: # cubes are symmetric under 90 deg: release with the fingers where there is room
|
| 614 |
+
yaw = self._pick_yaw([yaw, _wrap_h(yaw + np.pi / 2)], lambda a: self._hand_clearance(xy, a, zr, ignore=(o,)))
|
| 615 |
+
if careful:
|
| 616 |
+
cur = sk.eef_pos()
|
| 617 |
+
self._go([cur[0], cur[1], TZ + Z_SAFE])
|
| 618 |
+
self._go([xy[0], xy[1], TZ + Z_SAFE], yaw=yaw)
|
| 619 |
+
self._go([xy[0], xy[1], zr + 0.03], speed=0.25)
|
| 620 |
+
self._go([xy[0], xy[1], zr], speed=0.08, tol=0.003, max_steps=120)
|
| 621 |
+
sk.set_gripper(False, steps=12)
|
| 622 |
+
self._go([xy[0], xy[1], zr + 0.03], speed=0.1)
|
| 623 |
+
self._go([xy[0], xy[1], TZ + Z_SAFE], speed=0.3)
|
| 624 |
+
else:
|
| 625 |
+
if self.naive_style == "legs":
|
| 626 |
+
zt = TZ + (Z_NAIVE if z_t is None else z_t)
|
| 627 |
+
cur = sk.eef_pos()
|
| 628 |
+
h = max(cur[2], zt, zr + 0.04)
|
| 629 |
+
if cur[2] < h - 0.003:
|
| 630 |
+
self._go([cur[0], cur[1], h])
|
| 631 |
+
self._go([xy[0], xy[1], h], yaw=yaw)
|
| 632 |
+
else:
|
| 633 |
+
self._go([xy[0], xy[1], zr + 0.04], yaw=yaw)
|
| 634 |
+
self._go([xy[0], xy[1], zr], tol=0.003, max_steps=120)
|
| 635 |
+
sk.set_gripper(False, steps=12)
|
| 636 |
+
self._go([xy[0], xy[1], zr + (self.naive_lift if lift is None else lift)])
|
| 637 |
+
sk.hold(5)
|
| 638 |
+
|
| 639 |
+
# placing targets ---------------------------------------------------------
|
| 640 |
+
def square_xy(self, s):
|
| 641 |
+
return np.asarray(self.inst["squares"][s], float)
|
| 642 |
+
|
| 643 |
+
def bridge_mid(self):
|
| 644 |
+
return np.mean([self.square_xy(s) for s in SQUARES], axis=0)
|
| 645 |
+
|
| 646 |
+
def free_blocks(self):
|
| 647 |
+
_, (pa, pb) = self.stages()
|
| 648 |
+
used = set()
|
| 649 |
+
for low, up in (pa, pb):
|
| 650 |
+
if up is not None:
|
| 651 |
+
used |= {low, up}
|
| 652 |
+
return [b for b in BLOCKS if b not in used]
|
| 653 |
+
|
| 654 |
+
def _blocker(self, b):
|
| 655 |
+
"""for a careful top-down grasp of block b: None if the gripper fits at some grasp yaw, else the item in the
|
| 656 |
+
way (e.g. the top block of a pillar, or a block, right next to b)"""
|
| 657 |
+
zg = self._grasp_z(b, True)
|
| 658 |
+
p = self.pos(b)[:2]
|
| 659 |
+
if max(self._hand_clearance(p, a, zg, ignore=(b,)) for a in self._grip_yaws(b)) > -0.002:
|
| 660 |
+
return None
|
| 661 |
+
worst = {}
|
| 662 |
+
for o in ITEMS:
|
| 663 |
+
if o == b or self.held(o):
|
| 664 |
+
continue
|
| 665 |
+
worst[o] = max(self._hand_clearance(p, a, zg, ignore=tuple(q for q in ITEMS if q != o))
|
| 666 |
+
for a in self._grip_yaws(b))
|
| 667 |
+
o = min(worst, key=worst.get)
|
| 668 |
+
return o if worst[o] <= -0.002 else None
|
| 669 |
+
|
| 670 |
+
def build_pillar(self, s, careful, noise_fn, z_t=None, order="target"):
|
| 671 |
+
"""put blocks on square s until it carries a complete pillar (at most 5 placements)"""
|
| 672 |
+
failed = {}
|
| 673 |
+
for _ in range(6):
|
| 674 |
+
raw, (pa, pb) = self.stages()
|
| 675 |
+
low, up = (pa, pb)[SQUARES.index(s)]
|
| 676 |
+
if up is not None:
|
| 677 |
+
return True
|
| 678 |
+
if careful and self.over_budget():
|
| 679 |
+
return False
|
| 680 |
+
c = self.square_xy(s)
|
| 681 |
+
other = (pa, pb)[1 - SQUARES.index(s)]
|
| 682 |
+
cand = [b for b in BLOCKS if b != low and b not in other and (not careful or (self.usable(b)
|
| 683 |
+
and failed.get(b, 0) < 2))]
|
| 684 |
+
if not cand:
|
| 685 |
+
return False
|
| 686 |
+
ref = self.sk.eef_pos()[:2] if order == "gripper" else c
|
| 687 |
+
cand.sort(key=lambda b: (failed.get(b, 0), np.linalg.norm(self.pos(b)[:2] - ref)))
|
| 688 |
+
b = cand[0]
|
| 689 |
+
if careful:
|
| 690 |
+
free = [q for q in cand if self._blocker(q) is None]
|
| 691 |
+
if free:
|
| 692 |
+
b = free[0]
|
| 693 |
+
else: # every usable block sits right next to something tall: take that thing's top off first
|
| 694 |
+
blk = self._blocker(cand[0])
|
| 695 |
+
if blk is not None and blk != PLANK and failed.get(blk, 0) < 2:
|
| 696 |
+
if not self.park(blk):
|
| 697 |
+
failed[blk] = failed.get(blk, 0) + 1
|
| 698 |
+
continue
|
| 699 |
+
drop = self.pick(b, careful, noise=noise_fn(), z_t=z_t)
|
| 700 |
+
if drop is None:
|
| 701 |
+
failed[b] = failed.get(b, 0) + 1
|
| 702 |
+
continue
|
| 703 |
+
if low is None:
|
| 704 |
+
tgt, top = c, TZ
|
| 705 |
+
else:
|
| 706 |
+
tgt, top = self.pos(low)[:2], self.zmax(low)
|
| 707 |
+
n = noise_fn()
|
| 708 |
+
self.place(b, tgt + (n if n is not None else 0.0), top, drop, 0.0, careful, z_t=z_t)
|
| 709 |
+
return self.stages()[1][SQUARES.index(s)][1] is not None
|
| 710 |
+
|
| 711 |
+
def lay_plank(self, careful, noise_fn, z_t=None):
|
| 712 |
+
raw, (pa, pb) = self.stages()
|
| 713 |
+
if pa[1] is None or pb[1] is None or (careful and not self.usable(PLANK)):
|
| 714 |
+
return False
|
| 715 |
+
drop = self.pick(PLANK, careful, noise=noise_fn(), z_t=z_t)
|
| 716 |
+
if drop is None:
|
| 717 |
+
return False
|
| 718 |
+
raw, (pa, pb) = self.stages()
|
| 719 |
+
if pa[1] is None or pb[1] is None:
|
| 720 |
+
tops = [TZ + 0.11, TZ + 0.11]
|
| 721 |
+
mid = self.bridge_mid()
|
| 722 |
+
else:
|
| 723 |
+
tops = [self.zmax(pa[1]), self.zmax(pb[1])]
|
| 724 |
+
mid = (self.pos(pa[1])[:2] + self.pos(pb[1])[:2]) / 2
|
| 725 |
+
n = noise_fn()
|
| 726 |
+
# gripper fingers across the plank's width: plank long axis along y -> gripper yaw 90 deg
|
| 727 |
+
self.place(PLANK, mid + (n if n is not None else 0.0), max(tops), drop, np.pi / 2, careful, z_t=z_t)
|
| 728 |
+
return True
|
| 729 |
+
|
| 730 |
+
def put_car(self, careful, noise_fn, z_t=None):
|
| 731 |
+
drop = self.pick(CAR, careful, noise=noise_fn(), z_t=z_t)
|
| 732 |
+
if drop is None:
|
| 733 |
+
return False
|
| 734 |
+
pp = self.pos(PLANK)
|
| 735 |
+
n = noise_fn()
|
| 736 |
+
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)
|
| 737 |
+
return True
|
| 738 |
+
|
| 739 |
+
def in_keep_out(self, o):
|
| 740 |
+
"""o lies in the zone right behind the bridge line where, once the pillars and the plank stand, a top-down
|
| 741 |
+
grasp would put the hand on them (the careful policy keeps it clear)"""
|
| 742 |
+
p = self.pos(o)[:2]
|
| 743 |
+
dx = p[0] - self.inst["bridge_x"]
|
| 744 |
+
return bool(-0.08 < dx < KEEP_OUT["dx"] and abs(p[1] - self.bridge_mid()[1]) < KEEP_OUT["dy"])
|
| 745 |
+
|
| 746 |
+
def free_spot(self, o, avoid=()):
|
| 747 |
+
"""a free, comfortably reachable table spot for parking object o (the plank lies left-right), outside the
|
| 748 |
+
keep-out zone right behind the bridge and away from the squares"""
|
| 749 |
+
xb = self.inst["bridge_x"]
|
| 750 |
+
ym = self.bridge_mid()[1]
|
| 751 |
+
best, best_c = None, -1.0
|
| 752 |
+
others = [q for q in ITEMS if q != o and q not in avoid]
|
| 753 |
+
for x in np.arange(xb - 0.14, xb + 0.221, 0.02):
|
| 754 |
+
for y in np.arange(-0.28, 0.281, 0.02):
|
| 755 |
+
pts = [np.array([x, y])]
|
| 756 |
+
if o == PLANK:
|
| 757 |
+
pts = [np.array([x, y + d]) for d in (-0.10, 0.0, 0.10)]
|
| 758 |
+
if any(not self.reachable_xy(p) or np.hypot(p[0] - BASE_X, p[1]) > 0.64 for p in pts):
|
| 759 |
+
continue # (a careful 25 cm transit further out straightens the elbow onto its limit, measured)
|
| 760 |
+
if any(-0.08 < p[0] - xb < KEEP_OUT["dx"] and abs(p[1] - ym) < KEEP_OUT["dy"] for p in pts):
|
| 761 |
+
continue
|
| 762 |
+
c = 1.0
|
| 763 |
+
for p in pts:
|
| 764 |
+
for q in others:
|
| 765 |
+
c = min(c, float(np.linalg.norm(self.pos(q)[:2] - p)) - 0.04)
|
| 766 |
+
for sq in SQUARES:
|
| 767 |
+
c = min(c, float(np.linalg.norm(self.square_xy(sq) - p)) - 0.07)
|
| 768 |
+
if c > best_c:
|
| 769 |
+
best, best_c = np.array([x, y]), c
|
| 770 |
+
return best
|
| 771 |
+
|
| 772 |
+
@staticmethod
|
| 773 |
+
def reachable_xy(p):
|
| 774 |
+
"""a top-down grasp at table height works here (measured: right in front of the base, closer than 25 cm,
|
| 775 |
+
the arm cannot get down to the table; at 70-74 cm it still gets within ~1 cm)"""
|
| 776 |
+
rx, y = p[0] - BASE_X, p[1]
|
| 777 |
+
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)
|
| 778 |
+
|
| 779 |
+
def usable(self, o):
|
| 780 |
+
"""o lies on the table (or on something) within reach"""
|
| 781 |
+
return self.zmin(o) > TZ - 0.02 and self.reachable_xy(self.pos(o)[:2])
|
| 782 |
+
|
| 783 |
+
def park(self, o, careful=True):
|
| 784 |
+
if careful and not self.usable(o):
|
| 785 |
+
return False
|
| 786 |
+
drop = self.pick(o, careful)
|
| 787 |
+
if drop is None:
|
| 788 |
+
return False
|
| 789 |
+
xy = self.free_spot(o)
|
| 790 |
+
self.place(o, xy, TZ, drop, np.pi / 2 if o == PLANK else 0.0, careful)
|
| 791 |
+
return True
|
| 792 |
+
|
| 793 |
+
def over_budget(self):
|
| 794 |
+
"""the scripted repair stops where an agent's attempt would end: 3 s of simulated motion per command of the
|
| 795 |
+
task's command budget (agent_max_steps = 130 -> 390 s = 7800 control steps)"""
|
| 796 |
+
return self.sk.n_steps * 0.05 >= 3.0 * self.agent_max_steps
|
| 797 |
+
|
| 798 |
+
def plank_flat(self):
|
| 799 |
+
return abs(self.R(PLANK)[2, 2]) > 0.8
|
| 800 |
+
|
| 801 |
+
def fix_plank(self):
|
| 802 |
+
"""a plank standing on its long edge or leaning on something cannot be picked from above: push its upper edge
|
| 803 |
+
over with the closed gripper so that it falls flat (towards the side with more free table)"""
|
| 804 |
+
if self.plank_flat() or self.held(PLANK):
|
| 805 |
+
return False
|
| 806 |
+
sk = self.sk
|
| 807 |
+
R, c = self.R(PLANK), self.pos(PLANK)
|
| 808 |
+
up = R[:, 1] if R[2, 1] > 0 else -R[:, 1] # the plank's width axis, pointing up
|
| 809 |
+
lean = up[:2] / max(np.linalg.norm(up[:2]), 1e-6)
|
| 810 |
+
if np.linalg.norm(up[:2]) < 0.2: # standing upright: fall to the side away from the squares
|
| 811 |
+
n = R[:2, 2] / max(np.linalg.norm(R[:2, 2]), 1e-6)
|
| 812 |
+
far = lambda d: min(np.linalg.norm(c[:2] + 0.05 * d - self.square_xy(q)) for q in SQUARES) # noqa: E731
|
| 813 |
+
lean = n if far(n) > far(-n) else -n
|
| 814 |
+
push = lean
|
| 815 |
+
else: # leaning: push the top back over the vertical so it falls to the other side
|
| 816 |
+
push = -lean
|
| 817 |
+
top = c + up * 0.02
|
| 818 |
+
h = max(self.zmax(PLANK) - 0.015, TZ + 0.02)
|
| 819 |
+
a = top[:2] - push * 0.05
|
| 820 |
+
yaw = float(np.arctan2(push[1], push[0]) - np.pi / 2) # closed fingers across the push direction
|
| 821 |
+
sk.set_gripper(True, steps=8)
|
| 822 |
+
cur = sk.eef_pos()
|
| 823 |
+
self._go([cur[0], cur[1], TZ + Z_SAFE])
|
| 824 |
+
self._go([a[0], a[1], TZ + Z_SAFE], yaw=yaw)
|
| 825 |
+
self._go([a[0], a[1], h], speed=0.25)
|
| 826 |
+
b = top[:2] + push * 0.08
|
| 827 |
+
self._go([b[0], b[1], h], speed=0.1, max_steps=200)
|
| 828 |
+
self._go([b[0], b[1], TZ + Z_SAFE], speed=0.3)
|
| 829 |
+
sk.set_gripper(False, steps=8)
|
| 830 |
+
sk.hold(10)
|
| 831 |
+
return True
|
| 832 |
+
|
| 833 |
+
def clear_site(self):
|
| 834 |
+
"""careful: before building, move the car out of the zone right behind the bridge line"""
|
| 835 |
+
if self.in_keep_out(CAR) and not self.held(CAR):
|
| 836 |
+
self.park(CAR)
|
| 837 |
+
|
| 838 |
+
def repair(self, rounds=4):
|
| 839 |
+
"""check every stage; rebuild what is broken (careful motions). Returns the number of fixes made."""
|
| 840 |
+
nofn = lambda: None # noqa: E731
|
| 841 |
+
fixes = 0
|
| 842 |
+
for _ in range(rounds):
|
| 843 |
+
raw, (pa, pb) = self.stages()
|
| 844 |
+
if all(raw) or self.over_budget() or not (self.usable(PLANK) or self.held(PLANK)):
|
| 845 |
+
return fixes # (a plank thrown out of reach cannot be laid again)
|
| 846 |
+
fixes += 1
|
| 847 |
+
if not (raw[0] and raw[1]):
|
| 848 |
+
for _k in range(2):
|
| 849 |
+
if not self.plank_flat():
|
| 850 |
+
self.fix_plank()
|
| 851 |
+
plank_first = self._hand_clearance(self.pos(CAR)[:2], 0.0, self._grasp_z(CAR, True),
|
| 852 |
+
ignore=tuple(q for q in ITEMS if q != PLANK)) < 0.0
|
| 853 |
+
for o in ((PLANK, CAR) if plank_first else (CAR, PLANK)):
|
| 854 |
+
if o == CAR and (self.zmin(CAR) > TZ + 0.01 or self._near_squares(CAR) or self.in_keep_out(CAR)):
|
| 855 |
+
self.park(CAR)
|
| 856 |
+
if o == PLANK and (self.zmin(PLANK) > TZ + 0.006 or self._near_squares(PLANK)
|
| 857 |
+
or self.in_keep_out(PLANK)):
|
| 858 |
+
self.park(PLANK)
|
| 859 |
+
for i, s in enumerate(SQUARES):
|
| 860 |
+
if not self.stages()[0][i]:
|
| 861 |
+
self.build_pillar(s, True, nofn)
|
| 862 |
+
raw, _ = self.stages()
|
| 863 |
+
if raw[0] and raw[1] and not raw[2]:
|
| 864 |
+
if not self.plank_flat():
|
| 865 |
+
self.fix_plank()
|
| 866 |
+
if self.zmin(CAR) > TZ + 0.01 or self.in_keep_out(CAR):
|
| 867 |
+
self.park(CAR)
|
| 868 |
+
self.lay_plank(True, nofn)
|
| 869 |
+
raw, _ = self.stages()
|
| 870 |
+
if raw[2] and not raw[3]:
|
| 871 |
+
self.put_car(True, nofn)
|
| 872 |
+
return fixes
|
| 873 |
+
|
| 874 |
+
def _near_squares(self, o):
|
| 875 |
+
p = self.pos(o)[:2]
|
| 876 |
+
if o == PLANK:
|
| 877 |
+
ax = self.R(PLANK)[:2, 0]
|
| 878 |
+
pts = [p + s * ax * 0.11 for s in (-1, -0.5, 0, 0.5, 1)]
|
| 879 |
+
else:
|
| 880 |
+
pts = [p]
|
| 881 |
+
return any(np.linalg.norm(q - self.square_xy(s)) < 0.06 for q in pts for s in SQUARES)
|
| 882 |
+
|
| 883 |
+
# ------------------------------------------------------------ Sonnet-like naive (style "sonnet")
|
| 884 |
+
# Imitates how Claude Sonnet 5.5 moved in the lh1 pilot (runs/claude/lh1_bridge, 4 attempts, 230 commands):
|
| 885 |
+
# instruction order; for each pillar the free block nearest to its square first; a hover ~12 cm above the object
|
| 886 |
+
# with the gripper turned to the object's yaw, a straight vertical descent, grasp ~1 cm below the top; the carry
|
| 887 |
+
# often goes straight from the grasp to ~12.5 cm above the target (one move_eef: a diagonal climb), otherwise lift
|
| 888 |
+
# first; when the carried object's straight path would run into a built pillar it lifts first and carries with the
|
| 889 |
+
# object's bottom ~4 cm above that pillar; vertical descent, open, lift straight up to ~15 cm; plank: lift to 7 cm,
|
| 890 |
+
# carry at 16 cm; car: lift to 17 cm, carry, place, lift to 25 cm; no final check.
|
| 891 |
+
def _sn_grasp_z(self, o, sn):
|
| 892 |
+
if o == PLANK:
|
| 893 |
+
return self._grasp_z(PLANK, False)
|
| 894 |
+
return self.zmax(o) - sn["top_below"]
|
| 895 |
+
|
| 896 |
+
def _crossing_top(self, a, b, o, drop, hc):
|
| 897 |
+
"""top of the highest item that the held object o, carried straight from a to b with its bottom at hc - drop,
|
| 898 |
+
would run into (any footprint point within o's half size + 1 cm of the path), else None"""
|
| 899 |
+
a, b = np.asarray(a[:2], float), np.asarray(b[:2], float)
|
| 900 |
+
d = b - a
|
| 901 |
+
n2 = float(d @ d)
|
| 902 |
+
r = float(self.half(o)[0]) + 0.01
|
| 903 |
+
best = None
|
| 904 |
+
for q in ITEMS:
|
| 905 |
+
if q == o or self.held(q):
|
| 906 |
+
continue
|
| 907 |
+
top = self.zmax(q)
|
| 908 |
+
if top < hc - drop:
|
| 909 |
+
continue
|
| 910 |
+
pts = self.footprint(q)
|
| 911 |
+
t = np.clip((pts - a) @ d / n2, 0.0, 1.0) if n2 > 1e-9 else np.zeros(len(pts))
|
| 912 |
+
dist = float(np.min(np.linalg.norm(pts - (a + t[:, None] * d), axis=1)))
|
| 913 |
+
if dist < r and (best is None or top > best):
|
| 914 |
+
best = top
|
| 915 |
+
return best
|
| 916 |
+
|
| 917 |
+
def sn_pick(self, o, sn, noise=None):
|
| 918 |
+
sk = self.sk
|
| 919 |
+
p = self.pos(o)
|
| 920 |
+
if noise is not None:
|
| 921 |
+
p = p + np.array([noise[0], noise[1], 0.0])
|
| 922 |
+
zg = self._sn_grasp_z(o, sn)
|
| 923 |
+
if o == PLANK:
|
| 924 |
+
yaw = _wrap_h(self.yaw_of(PLANK))
|
| 925 |
+
elif o == CAR and sn["car_style"] == "keep":
|
| 926 |
+
yaw = None # keeps the gripper's current yaw (the pilot's seed 3000: still turned 90 deg from the plank)
|
| 927 |
+
else:
|
| 928 |
+
yaw = _wrap_q(self.yaw_of(o))
|
| 929 |
+
hover = TZ + (sn["car_hover"] if o == CAR else sn["hover"])
|
| 930 |
+
direct = o == CAR and sn["car_style"] == "direct" # (the pilot's seed 3001 went straight down to the car)
|
| 931 |
+
if not direct:
|
| 932 |
+
self._go([p[0], p[1], hover], yaw=yaw)
|
| 933 |
+
self._go([p[0], p[1], zg], yaw=yaw, tol=0.003, max_steps=250 if direct else 120)
|
| 934 |
+
sk.set_gripper(True, steps=15)
|
| 935 |
+
if not sk.holding(o):
|
| 936 |
+
sk.set_gripper(False, steps=15)
|
| 937 |
+
self._go([p[0], p[1], TZ + sn["hover"]])
|
| 938 |
+
return None
|
| 939 |
+
return float(sk.eef_pos()[2] - self.zmin(o))
|
| 940 |
+
|
| 941 |
+
def sn_place(self, o, xy, support_top, drop, yaw, sn, carry=None, lift=None, diag=None):
|
| 942 |
+
sk = self.sk
|
| 943 |
+
zr = support_top + drop + 0.004
|
| 944 |
+
hc = max(TZ + (sn["carry"] if carry is None else carry), zr + 0.03)
|
| 945 |
+
cur = sk.eef_pos()
|
| 946 |
+
diag = sn["diag"] if diag is None else diag
|
| 947 |
+
top = None if o == PLANK else self._crossing_top(cur, xy, o, drop, hc)
|
| 948 |
+
if top is not None: # a built pillar in the way: lift first, carry with the object's bottom above it
|
| 949 |
+
hc = max(hc, top + drop + sn["cross_margin"])
|
| 950 |
+
self._go([cur[0], cur[1], hc])
|
| 951 |
+
self._go([xy[0], xy[1], hc], yaw=yaw)
|
| 952 |
+
elif diag: # one move_eef from the grasp to above the target
|
| 953 |
+
self._go([xy[0], xy[1], hc], yaw=yaw)
|
| 954 |
+
else:
|
| 955 |
+
self._go([cur[0], cur[1], max(cur[2], hc + 0.02)])
|
| 956 |
+
self._go([xy[0], xy[1], hc], yaw=yaw)
|
| 957 |
+
self._go([xy[0], xy[1], zr], tol=0.003, max_steps=120)
|
| 958 |
+
sk.set_gripper(False, steps=15)
|
| 959 |
+
self._go([xy[0], xy[1], TZ + (sn["lift"] if lift is None else lift)])
|
| 960 |
+
sk.hold(5)
|
| 961 |
+
|
| 962 |
+
def sn_build_pillar(self, s, sn, noise_fn):
|
| 963 |
+
failed = {}
|
| 964 |
+
c = self.square_xy(s)
|
| 965 |
+
mid = self.bridge_mid()
|
| 966 |
+
for _ in range(5):
|
| 967 |
+
raw, (pa, pb) = self.stages()
|
| 968 |
+
low, up = (pa, pb)[SQUARES.index(s)]
|
| 969 |
+
if up is not None:
|
| 970 |
+
return True
|
| 971 |
+
other = (pa, pb)[1 - SQUARES.index(s)]
|
| 972 |
+
cand = [b for b in BLOCKS if b != low and b not in other and failed.get(b, 0) < 2]
|
| 973 |
+
if not cand:
|
| 974 |
+
return False
|
| 975 |
+
if sn["alloc"] == "side": # blocks on this square's side of the bridge first
|
| 976 |
+
side = np.sign(c[1] - mid[1])
|
| 977 |
+
same = [b for b in cand if np.sign(self.pos(b)[1] - mid[1]) == side]
|
| 978 |
+
cand = same or cand
|
| 979 |
+
b = min(cand, key=lambda q: (failed.get(q, 0), np.linalg.norm(self.pos(q)[:2] - c)))
|
| 980 |
+
drop = self.sn_pick(b, sn, noise=noise_fn())
|
| 981 |
+
if drop is None:
|
| 982 |
+
failed[b] = failed.get(b, 0) + 1
|
| 983 |
+
continue
|
| 984 |
+
tgt, top = (c, TZ) if low is None else (self.pos(low)[:2], self.zmax(low))
|
| 985 |
+
n = noise_fn()
|
| 986 |
+
# onto the bare square: straight from the grasp (diagonal climb); onto a block: lift first (a diagonal
|
| 987 |
+
# climb from nearby clips the lower block -- the pilot's seed 3000 did that once, then lifted first)
|
| 988 |
+
self.sn_place(b, tgt + (n if n is not None else 0.0), top, drop, 0.0, sn,
|
| 989 |
+
diag=None if low is None else False)
|
| 990 |
+
return self.stages()[1][SQUARES.index(s)][1] is not None
|
| 991 |
+
|
| 992 |
+
def sn_lay_plank(self, sn, noise_fn):
|
| 993 |
+
raw, (pa, pb) = self.stages()
|
| 994 |
+
if pa[1] is None or pb[1] is None:
|
| 995 |
+
return False
|
| 996 |
+
drop = self.sn_pick(PLANK, sn, noise=noise_fn())
|
| 997 |
+
if drop is None:
|
| 998 |
+
return False
|
| 999 |
+
cur = self.sk.eef_pos()
|
| 1000 |
+
self._go([cur[0], cur[1], TZ + sn["plank_lift"]])
|
| 1001 |
+
raw, (pa, pb) = self.stages()
|
| 1002 |
+
if pa[1] is None or pb[1] is None:
|
| 1003 |
+
tops, mid = [TZ + 0.11, TZ + 0.11], self.bridge_mid()
|
| 1004 |
+
else:
|
| 1005 |
+
tops = [self.zmax(pa[1]), self.zmax(pb[1])]
|
| 1006 |
+
mid = (self.pos(pa[1])[:2] + self.pos(pb[1])[:2]) / 2
|
| 1007 |
+
n = noise_fn()
|
| 1008 |
+
mid = mid + (n if n is not None else 0.0)
|
| 1009 |
+
self.sn_place(PLANK, mid, max(tops), drop, np.pi / 2, sn, carry=sn["plank_carry"], lift=sn["plank_end_lift"],
|
| 1010 |
+
diag=True)
|
| 1011 |
+
return True
|
| 1012 |
+
|
| 1013 |
+
def sn_put_car(self, sn, noise_fn):
|
| 1014 |
+
drop = self.sn_pick(CAR, sn, noise=noise_fn())
|
| 1015 |
+
if drop is None: # (in the pilot, Sonnet stopped here when it saw the bridge come down)
|
| 1016 |
+
return False
|
| 1017 |
+
n = noise_fn()
|
| 1018 |
+
pp = self.pos(PLANK)[:2] + (n if n is not None else 0.0)
|
| 1019 |
+
self.sn_place(CAR, pp, self.zmax(PLANK), drop, None, sn, carry=sn["car_lift"], lift=sn["end_lift"],
|
| 1020 |
+
diag=False)
|
| 1021 |
+
return True
|
| 1022 |
+
|
| 1023 |
+
# ------------------------------------------------------------ execution
|
| 1024 |
+
def execute(self, inst, params):
|
| 1025 |
+
mode = params.get("mode", "naive")
|
| 1026 |
+
careful = mode == "careful"
|
| 1027 |
+
rng = np.random.default_rng(params.get("noise_seed", 0))
|
| 1028 |
+
sig = float(params.get("noise", 0.0))
|
| 1029 |
+
noise_fn = (lambda: rng.uniform(-sig, sig, 2)) if sig > 0 else (lambda: None)
|
| 1030 |
+
z_t = params.get("z_t")
|
| 1031 |
+
self.naive_lift = float(params.get("lift", NAIVE_LIFT))
|
| 1032 |
+
style = params.get("style", "sonnet")
|
| 1033 |
+
if not careful and style == "sonnet":
|
| 1034 |
+
sn = dict(SN)
|
| 1035 |
+
sn.update(params.get("sn", {}))
|
| 1036 |
+
if sn["car_style"] is None:
|
| 1037 |
+
sn["car_style"] = CAR_STYLES[int(inst["seed"]) % 3]
|
| 1038 |
+
for s in SQUARES:
|
| 1039 |
+
self.sn_build_pillar(s, sn, noise_fn)
|
| 1040 |
+
self.sn_lay_plank(sn, noise_fn)
|
| 1041 |
+
self.sn_put_car(sn, noise_fn)
|
| 1042 |
+
else: # careful, or the v1 naive ("legs": vertical / horizontal legs at 8 cm; "diag")
|
| 1043 |
+
self.naive_style = style if style in ("legs", "diag") else NAIVE_STYLE
|
| 1044 |
+
if careful:
|
| 1045 |
+
self.clear_site()
|
| 1046 |
+
for s in SQUARES:
|
| 1047 |
+
self.build_pillar(s, careful, noise_fn, z_t=z_t, order=params.get("order", "target"))
|
| 1048 |
+
self.lay_plank(careful, noise_fn, z_t=z_t)
|
| 1049 |
+
self.put_car(careful, noise_fn, z_t=z_t)
|
| 1050 |
+
if params.get("check"):
|
| 1051 |
+
self.repair()
|
| 1052 |
+
cur = self.sk.eef_pos()
|
| 1053 |
+
if cur[2] < TZ + 0.20:
|
| 1054 |
+
self._go([cur[0], cur[1], cur[2] + 0.06], speed=0.15)
|
| 1055 |
+
|
| 1056 |
+
def default_params(self, inst):
|
| 1057 |
+
return dict(mode="naive", style="sonnet", check=False)
|
| 1058 |
+
|
| 1059 |
+
def oracle_params(self, inst):
|
| 1060 |
+
return dict(mode="careful", check=True)
|
| 1061 |
+
|
| 1062 |
+
def adapt_params(self, inst, history):
|
| 1063 |
+
return dict(mode="careful", check=True)
|
| 1064 |
+
|
| 1065 |
+
def blind_params(self, inst, attempt, rng):
|
| 1066 |
+
sn = dict(hover=float(rng.uniform(0.10, 0.14)), carry=float(rng.uniform(0.11, 0.15)),
|
| 1067 |
+
lift=float(rng.uniform(0.13, 0.20)), diag=bool(rng.random() < 0.5),
|
| 1068 |
+
car_style=CAR_STYLES[int(rng.integers(3))], alloc="side" if rng.random() < 0.5 else "greedy")
|
| 1069 |
+
return dict(mode="naive", style="sonnet", check=False, sn=sn, noise=0.004, noise_seed=int(rng.integers(1 << 30)))
|
| 1070 |
+
|
| 1071 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 1072 |
+
"""kinds: oracle, naive (Sonnet-like, car approach style by seed), adaptive, blind; for comparison naive_v1 (the
|
| 1073 |
+
v1 naive: vertical / horizontal legs at 8 cm) and naive_hover / naive_keep / naive_direct (Sonnet-like with
|
| 1074 |
+
one fixed car approach style)"""
|
| 1075 |
+
k = k or self.max_attempts
|
| 1076 |
+
rng = np.random.default_rng(seed)
|
| 1077 |
+
history = []
|
| 1078 |
+
for a in range(k):
|
| 1079 |
+
self.reset_instance(inst)
|
| 1080 |
+
if kind == "oracle":
|
| 1081 |
+
params = self.oracle_params(inst)
|
| 1082 |
+
elif kind == "naive":
|
| 1083 |
+
params = self.default_params(inst)
|
| 1084 |
+
elif kind == "naive_v1":
|
| 1085 |
+
params = dict(mode="naive", style="legs", check=False)
|
| 1086 |
+
elif kind.startswith("naive_") and kind[6:] in CAR_STYLES: # naive_hover / naive_keep / naive_direct
|
| 1087 |
+
params = dict(mode="naive", style="sonnet", check=False, sn=dict(car_style=kind[6:]))
|
| 1088 |
+
elif kind == "adaptive":
|
| 1089 |
+
params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history)
|
| 1090 |
+
elif kind == "blind":
|
| 1091 |
+
params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
|
| 1092 |
+
else:
|
| 1093 |
+
raise ValueError(kind)
|
| 1094 |
+
self.execute(inst, params)
|
| 1095 |
+
out = self.outcome(inst)
|
| 1096 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 1097 |
+
if on_attempt:
|
| 1098 |
+
on_attempt(a, params, out)
|
| 1099 |
+
if out["success"] or kind == "oracle" or kind.startswith("naive"):
|
| 1100 |
+
break
|
| 1101 |
+
return history
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/lh_nudge_row.py
ADDED
|
@@ -0,0 +1,821 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LH lh_nudge_row v2 (2026-10-14): stand four small cups, one by one, on the four coloured mats of their colours; the
|
| 2 |
+
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
|
| 3 |
+
opening towards the cup already standing on the next mat pushes that cup 1.5-3.4 cm sideways, half off its mat -- it
|
| 4 |
+
stays upright, so the damage is small but visible (a near miss that has to be noticed and undone before finishing).
|
| 5 |
+
|
| 6 |
+
Family: long-horizon self-disturbance ("state_restoration"): every placement is a later stage that can physically undo an
|
| 7 |
+
earlier one; the agent has to look back at all cups before finishing (within an attempt) or learn to let go without
|
| 8 |
+
pushing (across attempts).
|
| 9 |
+
|
| 10 |
+
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
|
| 11 |
+
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
|
| 12 |
+
see it (the oblique agentview camera looks along x; a tall cup hides the ring behind it), so 5 of 7 attempts failed
|
| 13 |
+
without any nudge (one was a calibration attempt), and the one clear nudge (s3000) left the cup 0.83 cm off --
|
| 14 |
+
invisible. Its left-right errors were <= 0.7 cm, its releases in attempt 1 almost all at wrist yaw ~0 (fingers opening
|
| 15 |
+
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
|
| 16 |
+
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
|
| 17 |
+
release pushes the neighbour sideways, where the camera resolves it, off its mat onto the table, and (3) uses slimmer cups
|
| 18 |
+
(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.
|
| 19 |
+
Code and results of v1: lh_nudge_row.py.bak-20261014-v1, results/_old/lh_nudge_row_v1/.
|
| 20 |
+
|
| 21 |
+
Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
|
| 22 |
+
* four coloured mats (dark red, blue, green, ochre; flat, visual only), each 9.0 cm (forward-back) x 4.6 cm, in two rows
|
| 23 |
+
(far and near, 1.5 cm apart); block centre 53-59 cm in front of the robot base. Tight block (14 of every 20
|
| 24 |
+
consecutive seeds): the two mats of a row touch. Spaced block (6 of 20): they are 4-5 cm apart and no open finger
|
| 25 |
+
reaches the neighbour (the benign instances);
|
| 26 |
+
* 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,
|
| 27 |
+
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
|
| 28 |
+
order and 9-10 cm apart.
|
| 29 |
+
|
| 30 |
+
Risk factor: the block's spacing (visible, instance level); there is no hidden physical variable (v1 measured that a
|
| 31 |
+
rubber-footed cup gets tipped over by a re-grasp next to it, and a fallen cup cannot be stood up again).
|
| 32 |
+
|
| 33 |
+
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
|
| 34 |
+
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
|
| 35 |
+
neighbour's wall is 3.6 cm away (+- the placement errors). Measured: letting go with the fingers along the row (wrist yaw
|
| 36 |
+
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
|
| 37 |
+
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
|
| 38 |
+
friction 0.18 or with 2.6 cm cups whose closed finger already presses the neighbour's rim, slim cups tipped over (4/18
|
| 39 |
+
and 6/18) -- hence the low friction and the 2 cm cups. A careful agent avoids the push by letting go with the fingers
|
| 40 |
+
opening forward-back (wrist yaw 90: the mats of the other row are 10.5 cm away) or diagonally, and repairs it by
|
| 41 |
+
re-centring the pushed cup (lifted 10 cm, carried back, let go the same careful way).
|
| 42 |
+
|
| 43 |
+
Success predicates (evaluated every other control step by a monitor, debounced over 0.5 s): each cup stands upright
|
| 44 |
+
(tilt <= 10 deg) on the table, not held, with its whole base on its own mat: centre within 3.0 cm (forward-back) and
|
| 45 |
+
1.3 cm (left-right) of the mat's centre. Success = all four at the end, gripper open and not touching any cup, scene
|
| 46 |
+
static. The monitor logs achieved / lost / restored per cup, cup_nudged (lost while not held, with displacement and
|
| 47 |
+
cause), cup_bumped (pushed by the robot but still on its mat) and cup_restored, for the server log only (F1 gives the
|
| 48 |
+
agent only success / failure).
|
| 49 |
+
|
| 50 |
+
Protocol: cross (reset to the same instance before every attempt), k = 3.
|
| 51 |
+
"""
|
| 52 |
+
import numpy as np
|
| 53 |
+
|
| 54 |
+
from .. import envs
|
| 55 |
+
from ..bddl import write_bddl
|
| 56 |
+
from ..objects import _fmt, _wrap, register_generated
|
| 57 |
+
from ..skills import Skills
|
| 58 |
+
from ..task_base import LFFTask, register_task
|
| 59 |
+
|
| 60 |
+
TZ = envs.TABLE_Z
|
| 61 |
+
COLOURS = ["red", "blue", "green", "yellow"]
|
| 62 |
+
CUPS = [f"cup_{c}_1" for c in COLOURS]
|
| 63 |
+
MATS = [f"mat_{c}_1" for c in COLOURS]
|
| 64 |
+
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),
|
| 65 |
+
"yellow": (0.92, 0.76, 0.12, 1.0)}
|
| 66 |
+
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),
|
| 67 |
+
"yellow": (0.62, 0.50, 0.08, 1.0)} # dark shades: crisp edges on the light table, bright cups stand out
|
| 68 |
+
INSIDE_RGBA = (0.93, 0.92, 0.88, 1.0) # glazed inside of the cups (seen from above)
|
| 69 |
+
|
| 70 |
+
# cup geometry (fixed; only mass and base friction change per instance, so no runtime geom edits / BVH refits)
|
| 71 |
+
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)
|
| 72 |
+
COM_Z = -0.006 # centre of mass below the cup's mid-height (heavier base)
|
| 73 |
+
WALL_T, BASE_T = 0.0025, 0.003
|
| 74 |
+
NSEG = 12
|
| 75 |
+
CONTACT = 'solimp="0.95 0.99 0.001" solref="0.01 1"'
|
| 76 |
+
WALL_MU = 0.8
|
| 77 |
+
BASE_MU = (0.08, 0.12) # glazed base: a pushed cup slides; at 0.18 a slim cup pushed high up tipped (measured)
|
| 78 |
+
MASS = (0.020, 0.032)
|
| 79 |
+
|
| 80 |
+
# mats (targets) and block
|
| 81 |
+
TOL_X = 0.030 # forward-back: the cup centre may be 3 cm from the mat centre (mat 9 cm long) -- Sonnet's measured
|
| 82 |
+
# placement bias is 1-2.5 cm forward (v1 pilot), invisible to it in the oblique camera
|
| 83 |
+
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
|
| 84 |
+
MAT_L, MAT_W = 2 * (CUP_R + TOL_X), 2 * (CUP_R + TOL_Y) # base completely on the mat <=> centre within the tolerances
|
| 85 |
+
ROW_GAP = 0.015 # gap between the far row and the near row of mats (x)
|
| 86 |
+
SPACED_GAP = (0.040, 0.050) # spaced block: gap between the two mats of a row (y); an open finger cannot reach
|
| 87 |
+
P_TIGHT = 0.70 # 14 of every 20 consecutive seeds: the two mats of a row touch
|
| 88 |
+
BLOCK_X = (-0.13, -0.07) # block centre in world x (53-59 cm in front of the robot base)
|
| 89 |
+
SUP_D = (0.175, 0.19) # supply line distance from the block centre
|
| 90 |
+
SUP_GAP = (0.090, 0.100)
|
| 91 |
+
|
| 92 |
+
# predicates / monitor
|
| 93 |
+
TILT_OK = np.radians(10.0)
|
| 94 |
+
ON_TABLE = 0.004
|
| 95 |
+
HYST = 0.002
|
| 96 |
+
DEBOUNCE = 10 # control steps (0.5 s)
|
| 97 |
+
BUMP_MIN = 0.003
|
| 98 |
+
|
| 99 |
+
# scripted motion (heights of the grasp point above the table)
|
| 100 |
+
Z_CARRY = 0.20 # Sonnet: lifts to ~20 cm before moving (lh2/lh3 pilots)
|
| 101 |
+
Z_LIFT = 0.15 # re-placing a cup that is already down: lift it this high (its base 11 cm up) before moving it
|
| 102 |
+
NAIVE_BIAS = (0.008, 0.022) # Sonnet's systematic forward placement error (v1 pilot: +0.8 ... +2.2 cm, per instance)
|
| 103 |
+
NAIVE_RAND = 0.006 # +- random placement error per axis (v1 pilot: left-right errors <= 0.7 cm)
|
| 104 |
+
NAIVE_FIX_RAND = 0.003 # after re-placing its own cup
|
| 105 |
+
FINGER_IN, FINGER_OUT, FINGER_HALF = 0.039, 0.066, 0.013 # open finger footprint (m from the grasp point / half width)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _wrap_h(a):
|
| 109 |
+
"""wrap to [-pi/2, pi/2) (the gripper is symmetric under 180 deg)"""
|
| 110 |
+
return float((a + np.pi / 2) % np.pi - np.pi / 2)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def cup_xml(name, rgba):
|
| 114 |
+
"""open-top cup: 12 wall boxes (1 mm above the bottom) and an octagonal base of two square boxes (box-box contacts:
|
| 115 |
+
a light cylinder on the table creeps by itself in MuJoCo, measured 1.6 cm / 5 s). Visual: a smooth cylinder with the
|
| 116 |
+
glazed inside at the top. The compiled inertial is replaced per instance (mass), the base friction too."""
|
| 117 |
+
r, h = CUP_R, CUP_H
|
| 118 |
+
g = [f' <inertial pos="0 0 {COM_Z:.4f}" mass="0.055" diaginertia="2.6e-5 2.6e-5 1.6e-5" />']
|
| 119 |
+
s = r * np.sin(np.pi / NSEG) + 0.0006
|
| 120 |
+
rc = r * np.cos(np.pi / NSEG) - WALL_T / 2
|
| 121 |
+
for k in range(NSEG):
|
| 122 |
+
a = 2 * np.pi * k / NSEG
|
| 123 |
+
q = [np.cos(a / 2), 0, 0, np.sin(a / 2)]
|
| 124 |
+
g.append(f' <geom name="{name}_w{k}" type="box" size="{WALL_T / 2:.5f} {s:.5f} {(h - 0.001) / 2:.5f}" '
|
| 125 |
+
f'pos="{rc * np.cos(a):.5f} {rc * np.sin(a):.5f} 0.0005" quat="{_fmt(q)}" rgba="{_fmt(rgba)}" '
|
| 126 |
+
f'friction="{WALL_MU} 0.005 0.0001" {CONTACT} group="0" />')
|
| 127 |
+
a0 = r * 0.70
|
| 128 |
+
for k, ang in enumerate((0.0, np.pi / 4)):
|
| 129 |
+
q = [np.cos(ang / 2), 0, 0, np.sin(ang / 2)]
|
| 130 |
+
g.append(f' <geom name="{name}_b{k}" type="box" size="{a0:.5f} {a0:.5f} {BASE_T / 2:.5f}" '
|
| 131 |
+
f'pos="0 0 {-h / 2 + BASE_T / 2:.5f}" quat="{_fmt(q)}" rgba="{_fmt(rgba)}" '
|
| 132 |
+
f'friction="0.5 0.005 0.0001" {CONTACT} group="0" />')
|
| 133 |
+
g.append(f' <geom type="cylinder" size="{r:.5f} {h / 2:.5f}" rgba="{_fmt(rgba)}" contype="0" conaffinity="0" '
|
| 134 |
+
f'group="1" />')
|
| 135 |
+
g.append(f' <geom type="cylinder" size="{r - WALL_T:.5f} 0.0004" pos="0 0 {h / 2 - 0.0003:.5f}" '
|
| 136 |
+
f'rgba="{_fmt(INSIDE_RGBA)}" contype="0" conaffinity="0" group="1" />')
|
| 137 |
+
return _wrap(name, "\n".join(g), h / 2, r)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def mat_xml(name, rgba):
|
| 141 |
+
"""flat coloured mat (visual only), long side along body x"""
|
| 142 |
+
g = (f' <geom type="box" size="{MAT_L / 2:.5f} {MAT_W / 2:.5f} 0.0004" rgba="{_fmt(rgba)}" contype="0" '
|
| 143 |
+
f'conaffinity="0" group="1" />')
|
| 144 |
+
return _wrap(name, g, 0.0004, float(np.hypot(MAT_L, MAT_W) / 2))
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def _fb(d):
|
| 148 |
+
return f"{100 * abs(d):.1f} cm {'forward' if d > 0 else 'back'}"
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _lr(d):
|
| 152 |
+
return f"{100 * abs(d):.1f} cm to the {'left' if d > 0 else 'right'}"
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class NudgeSkills(Skills):
|
| 156 |
+
"""Skills that feed the task's per-step monitor."""
|
| 157 |
+
|
| 158 |
+
def __init__(self, env, task, recorder=None):
|
| 159 |
+
super().__init__(env, recorder=recorder)
|
| 160 |
+
self.task = task
|
| 161 |
+
|
| 162 |
+
def _act(self, dpos, drot, grip):
|
| 163 |
+
super()._act(dpos, drot, grip)
|
| 164 |
+
self.task.monitor_step()
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
@register_task
|
| 168 |
+
class NudgeRow(LFFTask):
|
| 169 |
+
name = "lh_nudge_row"
|
| 170 |
+
level = "L2"
|
| 171 |
+
category = "state_restoration"
|
| 172 |
+
capabilities = ("Perceive", "Plan", "Reason", "Restore")
|
| 173 |
+
protocol = "cross"
|
| 174 |
+
max_attempts = 3
|
| 175 |
+
# careful: ~10 commands per cup (40) + re-placing an imprecise cup or two (~15) + re-centring two pushed cups (~20)
|
| 176 |
+
# + looking / small corrections (~20), with some margin
|
| 177 |
+
agent_max_steps = 110
|
| 178 |
+
instruction = ("Stand each of the four small cups on the mat of the same colour. The four coloured mats lie on the "
|
| 179 |
+
"table in two rows of two. At the end every cup must stand upright with its whole base on its own "
|
| 180 |
+
"mat (not touching another mat or the table around it), and the gripper must be open and clear of "
|
| 181 |
+
"the cups.")
|
| 182 |
+
instruction_indirect = ("Set each little cup down on the coloured patch that matches it; the four patches form two "
|
| 183 |
+
"rows of two. When you are done every cup has to stand upright with its bottom completely "
|
| 184 |
+
"on its own patch, and the gripper must be open and away from the cups.")
|
| 185 |
+
agent_object_names = ["small cups (red, blue, green, yellow)",
|
| 186 |
+
"coloured mats (red, blue, green, yellow) in two rows of two"]
|
| 187 |
+
|
| 188 |
+
# ------------------------------------------------------------ scene
|
| 189 |
+
def make_bddl(self):
|
| 190 |
+
objs, fx = [], []
|
| 191 |
+
for i, (c, cup) in enumerate(zip(COLOURS, CUPS)):
|
| 192 |
+
cat = register_generated(f"LffLhnCup{c.capitalize()}", cup_xml(f"lff_lhn_cup_{c}", RGBA[c]))
|
| 193 |
+
objs.append((cup, cat, f"cup{i}_region", (-0.30 + 0.12 * i, 0.30, -0.29 + 0.12 * i, 0.31)))
|
| 194 |
+
for i, (c, mat) in enumerate(zip(COLOURS, MATS)):
|
| 195 |
+
cat = register_generated(f"LffLhnMat{c.capitalize()}", mat_xml(f"lff_lhn_mat_{c}", MAT_RGBA[c]), free=False)
|
| 196 |
+
fx.append((mat, cat, f"mat{i}_region", (-0.30 + 0.12 * i, -0.31, -0.29 + 0.12 * i, -0.30)))
|
| 197 |
+
return write_bddl(self.name, "Stand each cup on the mat of its colour", objs, fx)
|
| 198 |
+
|
| 199 |
+
def __init__(self, cam_res=None):
|
| 200 |
+
super().__init__(cam_res)
|
| 201 |
+
m = self.env.sim.model
|
| 202 |
+
self.mat_bid = {k: m.body_name2id(self.env.fixtures_dict[k].root_body) for k in MATS}
|
| 203 |
+
self.cgeoms = {c: envs.obj_geom_ids(self.env, c) for c in CUPS}
|
| 204 |
+
self.cbody = {c: int(m.geom_bodyid[self.cgeoms[c][0]]) for c in CUPS}
|
| 205 |
+
self.base_geoms = {c: [g for g in self.cgeoms[c] if (m.geom_id2name(g) or "").split("_")[-1] in ("b0", "b1")]
|
| 206 |
+
for c in CUPS}
|
| 207 |
+
self.finger_geoms, self.hand_geoms = [], []
|
| 208 |
+
for g in envs.robot_geom_ids(self.env):
|
| 209 |
+
n = m.geom_id2name(g) or ""
|
| 210 |
+
(self.finger_geoms if "finger" in n else self.hand_geoms).append(g)
|
| 211 |
+
# per-geom lookup tables for the substep contact check: cup index (-1 none), robot part (1 finger, 2 hand)
|
| 212 |
+
self.owner = np.full(m.ngeom, -1, int)
|
| 213 |
+
for i, c in enumerate(CUPS):
|
| 214 |
+
self.owner[self.cgeoms[c]] = i
|
| 215 |
+
self.part = np.zeros(m.ngeom, int)
|
| 216 |
+
self.part[self.finger_geoms] = 1
|
| 217 |
+
self.part[self.hand_geoms] = 2
|
| 218 |
+
self._sub_rob, self._sub_obj = {}, {}
|
| 219 |
+
# contacts are collected after every MuJoCo substep: an opening finger can flick a light cup within one control
|
| 220 |
+
# step (same technique as lh_fence; wrappers chain)
|
| 221 |
+
sim = self.env.sim
|
| 222 |
+
if not getattr(sim, "_lhn_wrapped", False):
|
| 223 |
+
orig = sim.step
|
| 224 |
+
|
| 225 |
+
def step(*a, **k):
|
| 226 |
+
orig(*a, **k)
|
| 227 |
+
t = getattr(sim, "_lhn_task", None)
|
| 228 |
+
if t is not None and t.mon is not None:
|
| 229 |
+
t._substep()
|
| 230 |
+
sim.step = step
|
| 231 |
+
sim._lhn_wrapped = True
|
| 232 |
+
sim._lhn_task = self
|
| 233 |
+
self.inst = None
|
| 234 |
+
self.mon = None
|
| 235 |
+
self.sk = None
|
| 236 |
+
|
| 237 |
+
def _substep(self):
|
| 238 |
+
d = self.env.sim.data
|
| 239 |
+
n = d.ncon
|
| 240 |
+
if not n:
|
| 241 |
+
return
|
| 242 |
+
g1 = np.asarray(d.contact.geom1)[:n]
|
| 243 |
+
g2 = np.asarray(d.contact.geom2)[:n]
|
| 244 |
+
o1, o2 = self.owner[g1], self.owner[g2]
|
| 245 |
+
for a, b, pa, pb in zip(g1, g2, o1, o2):
|
| 246 |
+
if pa < 0 and pb < 0:
|
| 247 |
+
continue
|
| 248 |
+
if pa >= 0 and pb >= 0:
|
| 249 |
+
if pa != pb:
|
| 250 |
+
self._sub_obj[int(pa)] = int(pb)
|
| 251 |
+
self._sub_obj[int(pb)] = int(pa)
|
| 252 |
+
continue
|
| 253 |
+
p, o = (pa, b) if pa >= 0 else (pb, a)
|
| 254 |
+
part = self.part[o]
|
| 255 |
+
if part:
|
| 256 |
+
prev = self._sub_rob.get(int(p), 0)
|
| 257 |
+
self._sub_rob[int(p)] = 1 if (part == 1 or prev == 1) else 2
|
| 258 |
+
|
| 259 |
+
# ------------------------------------------------------------ instances
|
| 260 |
+
def sample_instance(self, seed):
|
| 261 |
+
rng = np.random.default_rng(seed)
|
| 262 |
+
tight = bool((int(seed) * 7) % 20 < round(20 * P_TIGHT)) # balanced: 14 of every 20 consecutive seeds
|
| 263 |
+
gap_y = 0.0 if tight else float(rng.uniform(*SPACED_GAP))
|
| 264 |
+
py = MAT_W + gap_y # mat centre to mat centre within a row (left-right)
|
| 265 |
+
px = MAT_L + ROW_GAP # far row to near row (forward-back)
|
| 266 |
+
bx = float(rng.uniform(*BLOCK_X))
|
| 267 |
+
side = str(rng.choice(["front", "left", "right"]))
|
| 268 |
+
by = float(rng.uniform(-0.04, 0.04))
|
| 269 |
+
if side == "left":
|
| 270 |
+
by = float(rng.uniform(-0.08, -0.04))
|
| 271 |
+
elif side == "right":
|
| 272 |
+
by = float(rng.uniform(0.04, 0.08))
|
| 273 |
+
# mat positions: block slots (far-left, far-right, near-left, near-right), colours permuted
|
| 274 |
+
slots = {"far_left": [bx + px / 2, by + py / 2], "far_right": [bx + px / 2, by - py / 2],
|
| 275 |
+
"near_left": [bx - px / 2, by + py / 2], "near_right": [bx - px / 2, by - py / 2]}
|
| 276 |
+
names = list(slots)
|
| 277 |
+
perm = rng.permutation(4)
|
| 278 |
+
mats = {COLOURS[i]: slots[names[perm[i]]] for i in range(4)}
|
| 279 |
+
slot_of = {COLOURS[i]: names[perm[i]] for i in range(4)}
|
| 280 |
+
# supply line
|
| 281 |
+
d = float(rng.uniform(*SUP_D))
|
| 282 |
+
gap = float(rng.uniform(*SUP_GAP))
|
| 283 |
+
offs = (np.arange(4) - 1.5) * gap + float(rng.uniform(-0.02, 0.02))
|
| 284 |
+
if side == "front":
|
| 285 |
+
sup = [[bx - d + float(rng.uniform(-0.008, 0.008)), by + o] for o in offs]
|
| 286 |
+
else:
|
| 287 |
+
sgn = 1.0 if side == "left" else -1.0
|
| 288 |
+
sup = [[bx + o, by + sgn * (d - 0.02) + float(rng.uniform(-0.008, 0.008))] for o in offs]
|
| 289 |
+
order = rng.permutation(4)
|
| 290 |
+
start = {COLOURS[i]: [float(v) for v in sup[order[i]]] for i in range(4)}
|
| 291 |
+
mu = {c: float(rng.uniform(*BASE_MU)) for c in COLOURS}
|
| 292 |
+
mass = {c: float(rng.uniform(*MASS)) for c in COLOURS}
|
| 293 |
+
yaw0 = {c: float(rng.uniform(-np.pi, np.pi)) for c in COLOURS}
|
| 294 |
+
return dict(seed=int(seed), pitch_y=py, pitch_x=px, gap_y=gap_y, block=[bx, by], supply_side=side,
|
| 295 |
+
supply_d=d, supply_gap=gap, mats=mats, slot_of=slot_of, start=start, mu=mu, mass=mass, yaw0=yaw0,
|
| 296 |
+
tight=tight, block_kind="tight" if tight else "spaced",
|
| 297 |
+
naive_bias_x=float(rng.uniform(*NAIVE_BIAS)))
|
| 298 |
+
|
| 299 |
+
def apply_instance(self, inst):
|
| 300 |
+
self.inst = inst
|
| 301 |
+
m = self.env.sim.model
|
| 302 |
+
for c, cup in zip(COLOURS, CUPS):
|
| 303 |
+
b = self.cbody[cup]
|
| 304 |
+
M = inst["mass"][c]
|
| 305 |
+
m.body_mass[b] = M
|
| 306 |
+
# thin-walled cup (wall + base), approximately
|
| 307 |
+
m.body_inertia[b] = [M * (CUP_R ** 2 / 2 + CUP_H ** 2 / 12), M * (CUP_R ** 2 / 2 + CUP_H ** 2 / 12),
|
| 308 |
+
M * CUP_R ** 2 * 0.8]
|
| 309 |
+
for g in self.base_geoms[cup]:
|
| 310 |
+
m.geom_friction[g] = [inst["mu"][c], 0.005, 0.0001]
|
| 311 |
+
m.geom_priority[g] = 2
|
| 312 |
+
for c, mat in zip(COLOURS, MATS):
|
| 313 |
+
x, y = inst["mats"][c]
|
| 314 |
+
m.body_pos[self.mat_bid[mat]] = [x, y, TZ + 0.0005]
|
| 315 |
+
m.body_quat[self.mat_bid[mat]] = [1.0, 0.0, 0.0, 0.0]
|
| 316 |
+
self.env.sim.forward()
|
| 317 |
+
for c, cup in zip(COLOURS, CUPS):
|
| 318 |
+
envs.place_upright(self.env, cup, inst["start"][c], yaw=inst["yaw0"][c], clearance=0.0005)
|
| 319 |
+
|
| 320 |
+
def reset_instance(self, inst, recorder=None):
|
| 321 |
+
self.mon = None
|
| 322 |
+
self.env.reset()
|
| 323 |
+
self.apply_instance(inst)
|
| 324 |
+
self.env.sim.forward()
|
| 325 |
+
envs.settle(self.env, 15)
|
| 326 |
+
self.sk = NudgeSkills(self.env, self, recorder=recorder)
|
| 327 |
+
self._sub_rob, self._sub_obj = {}, {}
|
| 328 |
+
n = len(CUPS)
|
| 329 |
+
self.mon = dict(state=[False] * n, raw_since=[0] * n, ever=[False] * n, lost=[False] * n, events=[],
|
| 330 |
+
lost_cause=[None] * n,
|
| 331 |
+
anchor=[None] * n, last_robot=[None] * n, last_obj=[None] * n, nudged=[False] * n,
|
| 332 |
+
bump_ref=[None] * n, bump_step=[-1000] * n, n_steps=0)
|
| 333 |
+
return self.sk
|
| 334 |
+
|
| 335 |
+
# ------------------------------------------------------------ geometry / predicates
|
| 336 |
+
def pos(self, cup):
|
| 337 |
+
return envs.obj_pos(self.env, cup)
|
| 338 |
+
|
| 339 |
+
def tilt(self, cup):
|
| 340 |
+
return float(np.arccos(np.clip(envs.obj_upright_cos(self.env, cup), -1.0, 1.0)))
|
| 341 |
+
|
| 342 |
+
def held(self, cup):
|
| 343 |
+
return self.sk is not None and self.sk.holding(cup)
|
| 344 |
+
|
| 345 |
+
def mat_xy(self, i):
|
| 346 |
+
return np.asarray(self.inst["mats"][COLOURS[i]], float)
|
| 347 |
+
|
| 348 |
+
def offset(self, i):
|
| 349 |
+
return self.pos(CUPS[i])[:2] - self.mat_xy(i)
|
| 350 |
+
|
| 351 |
+
@staticmethod
|
| 352 |
+
def within(off, extra=0.0):
|
| 353 |
+
"""mat-frame offset (x forward-back, y left-right) inside the tolerances = the cup's whole base on its mat"""
|
| 354 |
+
return abs(float(off[0])) <= TOL_X + extra and abs(float(off[1])) <= TOL_Y + extra
|
| 355 |
+
|
| 356 |
+
def on_mat(self, i, extra=0.0):
|
| 357 |
+
cup = CUPS[i]
|
| 358 |
+
if self.tilt(cup) > TILT_OK + (np.radians(2.0) if extra else 0.0):
|
| 359 |
+
return False
|
| 360 |
+
if not self.within(self.offset(i), extra):
|
| 361 |
+
return False
|
| 362 |
+
if envs.obj_min_z(self.env, cup) > TZ + ON_TABLE:
|
| 363 |
+
return False
|
| 364 |
+
return not self.held(cup)
|
| 365 |
+
|
| 366 |
+
def stages(self):
|
| 367 |
+
return [self.on_mat(i) for i in range(len(CUPS))]
|
| 368 |
+
|
| 369 |
+
# ------------------------------------------------------------ monitor
|
| 370 |
+
def monitor_step(self):
|
| 371 |
+
mon = self.mon
|
| 372 |
+
if mon is None or self.sk is None:
|
| 373 |
+
return
|
| 374 |
+
mon["n_steps"] += 1
|
| 375 |
+
t = self.sk.n_steps
|
| 376 |
+
rob = dict(self._sub_rob)
|
| 377 |
+
obj = dict(self._sub_obj)
|
| 378 |
+
self._sub_rob, self._sub_obj = {}, {}
|
| 379 |
+
gstate = "open" if self.sk.grip < 0 else "closed"
|
| 380 |
+
for i, part in rob.items():
|
| 381 |
+
if not self.held(CUPS[i]):
|
| 382 |
+
mon["last_robot"][i] = ["finger" if part == 1 else "hand", int(t), gstate]
|
| 383 |
+
for i, j in obj.items():
|
| 384 |
+
mon["last_obj"][i] = [COLOURS[j] + (" (held)" if self.held(CUPS[j]) else ""), int(t)]
|
| 385 |
+
if mon["n_steps"] % 2:
|
| 386 |
+
return
|
| 387 |
+
for i in range(len(CUPS)):
|
| 388 |
+
cup = CUPS[i]
|
| 389 |
+
raw = self.on_mat(i, HYST if mon["state"][i] else 0.0)
|
| 390 |
+
# bumps inside the tolerance
|
| 391 |
+
if mon["state"][i] and raw and not self.held(cup):
|
| 392 |
+
lr = mon["last_robot"][i]
|
| 393 |
+
if lr is not None and t - lr[1] <= 2 and mon["bump_ref"][i] is None:
|
| 394 |
+
mon["bump_ref"][i] = [self.pos(cup)[:2].tolist(), int(t), 0.0]
|
| 395 |
+
ref = mon["bump_ref"][i]
|
| 396 |
+
if ref is not None:
|
| 397 |
+
ref[2] = max(ref[2], float(np.degrees(self.tilt(cup))))
|
| 398 |
+
if t - ref[1] > 40:
|
| 399 |
+
dpos = float(np.linalg.norm(self.pos(cup)[:2] - np.asarray(mon["anchor"][i] or ref[0])))
|
| 400 |
+
if (dpos >= BUMP_MIN or ref[2] >= 2.0) and t - mon["bump_step"][i] > 60:
|
| 401 |
+
mon["events"].append(dict(cup=COLOURS[i], event="cup_bumped", step=int(ref[1]),
|
| 402 |
+
moved_cm=round(100 * dpos, 2), max_tilt_deg=round(ref[2], 1),
|
| 403 |
+
cause=self._cause(i, ref[1] + 1)))
|
| 404 |
+
mon["bump_step"][i] = int(t)
|
| 405 |
+
mon["bump_ref"][i] = None
|
| 406 |
+
if raw == mon["state"][i]:
|
| 407 |
+
mon["raw_since"][i] = 0
|
| 408 |
+
continue
|
| 409 |
+
mon["raw_since"][i] += 2
|
| 410 |
+
if mon["raw_since"][i] < DEBOUNCE:
|
| 411 |
+
continue
|
| 412 |
+
mon["state"][i] = raw
|
| 413 |
+
mon["raw_since"][i] = 0
|
| 414 |
+
t0 = int(t - DEBOUNCE + 1)
|
| 415 |
+
if raw:
|
| 416 |
+
restored = mon["lost"][i]
|
| 417 |
+
e = dict(stage=COLOURS[i], event="restored" if restored else "achieved", step=t0)
|
| 418 |
+
if restored:
|
| 419 |
+
e["after"] = mon["lost_cause"][i] # picked_up = the agent re-adjusted a cup it had placed itself
|
| 420 |
+
mon["events"].append(e)
|
| 421 |
+
if restored and mon["nudged"][i]:
|
| 422 |
+
mon["events"].append(dict(cup=COLOURS[i], event="cup_restored", step=t0))
|
| 423 |
+
mon["nudged"][i] = False
|
| 424 |
+
mon["ever"][i] = True
|
| 425 |
+
mon["anchor"][i] = self.pos(cup)[:2].tolist()
|
| 426 |
+
mon["bump_ref"][i] = None
|
| 427 |
+
else:
|
| 428 |
+
mon["lost"][i] = True
|
| 429 |
+
cause = self._cause(i, t)
|
| 430 |
+
mon["lost_cause"][i] = cause
|
| 431 |
+
mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t0, cause=cause))
|
| 432 |
+
if cause != "picked_up":
|
| 433 |
+
a = mon["anchor"][i]
|
| 434 |
+
d = self.pos(cup)[:2] - np.asarray(a if a is not None else self.mat_xy(i))
|
| 435 |
+
off = self.offset(i)
|
| 436 |
+
mon["events"].append(dict(cup=COLOURS[i], event="cup_nudged", step=t0, cause=cause,
|
| 437 |
+
moved_cm=[round(100 * float(d[0]), 2), round(100 * float(d[1]), 2)],
|
| 438 |
+
offset_cm=round(100 * float(np.linalg.norm(off)), 2),
|
| 439 |
+
tilt_deg=round(float(np.degrees(self.tilt(cup))), 1)))
|
| 440 |
+
mon["nudged"][i] = True
|
| 441 |
+
|
| 442 |
+
def _cause(self, i, t, window=60):
|
| 443 |
+
if self.held(CUPS[i]):
|
| 444 |
+
return "picked_up"
|
| 445 |
+
lr, lo = self.mon["last_robot"][i], self.mon["last_obj"][i]
|
| 446 |
+
cands = []
|
| 447 |
+
if lr is not None and t - lr[1] <= window:
|
| 448 |
+
cands.append((lr[1], f"robot_{lr[0]}" + ("_opening" if lr[2] == "open" else "")))
|
| 449 |
+
if lo is not None and t - lo[1] <= window:
|
| 450 |
+
cands.append((lo[1] - 30, "cup:" + lo[0])) # prefer the robot when both touched it recently
|
| 451 |
+
return max(cands)[1] if cands else "other"
|
| 452 |
+
|
| 453 |
+
def _finalize_monitor(self, raw):
|
| 454 |
+
"""close the event log at finish: a stage the debounced monitor still holds (it uses a 2 mm hysteresis) but the
|
| 455 |
+
final judge does not is logged as lost now (final=True), and vice versa"""
|
| 456 |
+
mon = self.mon
|
| 457 |
+
if mon is None:
|
| 458 |
+
return
|
| 459 |
+
t = int(self.sk.n_steps)
|
| 460 |
+
for i in range(len(CUPS)):
|
| 461 |
+
if raw[i] == mon["state"][i]:
|
| 462 |
+
continue
|
| 463 |
+
mon["state"][i] = raw[i]
|
| 464 |
+
if raw[i]:
|
| 465 |
+
restored = mon["lost"][i]
|
| 466 |
+
e = dict(stage=COLOURS[i], event="restored" if restored else "achieved", step=t, final=True)
|
| 467 |
+
if restored:
|
| 468 |
+
e["after"] = mon["lost_cause"][i]
|
| 469 |
+
mon["events"].append(e)
|
| 470 |
+
mon["ever"][i] = True
|
| 471 |
+
continue
|
| 472 |
+
mon["lost"][i] = True
|
| 473 |
+
cause = self._cause(i, t, window=10 ** 6) # the last contact may be long ago (slow creep across the line)
|
| 474 |
+
mon["lost_cause"][i] = cause
|
| 475 |
+
mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t, cause=cause, final=True))
|
| 476 |
+
if cause != "picked_up":
|
| 477 |
+
a = mon["anchor"][i]
|
| 478 |
+
d = self.pos(CUPS[i])[:2] - np.asarray(a if a is not None else self.mat_xy(i))
|
| 479 |
+
mon["events"].append(dict(cup=COLOURS[i], event="cup_nudged", step=t, cause=cause, final=True,
|
| 480 |
+
moved_cm=[round(100 * float(d[0]), 2), round(100 * float(d[1]), 2)],
|
| 481 |
+
offset_cm=round(100 * float(np.linalg.norm(self.offset(i))), 2),
|
| 482 |
+
tilt_deg=round(float(np.degrees(self.tilt(CUPS[i]))), 1)))
|
| 483 |
+
mon["nudged"][i] = True
|
| 484 |
+
|
| 485 |
+
# ------------------------------------------------------------ outcome
|
| 486 |
+
def _touching(self):
|
| 487 |
+
d = self.env.sim.data
|
| 488 |
+
rob = set(self.finger_geoms) | set(self.hand_geoms)
|
| 489 |
+
for j in range(d.ncon):
|
| 490 |
+
c = d.contact[j]
|
| 491 |
+
if (self.owner[c.geom1] >= 0 and c.geom2 in rob) or (self.owner[c.geom2] >= 0 and c.geom1 in rob):
|
| 492 |
+
return True
|
| 493 |
+
return False
|
| 494 |
+
|
| 495 |
+
def outcome(self, inst):
|
| 496 |
+
sk = self.sk
|
| 497 |
+
sk.hold(10)
|
| 498 |
+
p0 = {c: self.pos(c) for c in CUPS}
|
| 499 |
+
touching = False
|
| 500 |
+
for _ in range(20):
|
| 501 |
+
sk.hold(1)
|
| 502 |
+
touching = touching or self._touching()
|
| 503 |
+
moved = max(float(np.linalg.norm(self.pos(c) - p0[c])) for c in CUPS)
|
| 504 |
+
static = moved < 0.003
|
| 505 |
+
raw = self.stages()
|
| 506 |
+
self._finalize_monitor(raw)
|
| 507 |
+
held = [COLOURS[i] for i, c in enumerate(CUPS) if self.held(c)]
|
| 508 |
+
mon = self.mon
|
| 509 |
+
ev = list(mon["events"]) if mon else []
|
| 510 |
+
n_reg = sum(e.get("event") == "lost" and e.get("cause") != "picked_up" for e in ev)
|
| 511 |
+
n_lost = sum(e.get("event") == "lost" for e in ev)
|
| 512 |
+
n_res = sum(e.get("event") == "restored" and e.get("after") != "picked_up" for e in ev)
|
| 513 |
+
nudges = [e for e in ev if e.get("event") == "cup_nudged"]
|
| 514 |
+
bumps = [e for e in ev if e.get("event") == "cup_bumped"]
|
| 515 |
+
success = bool(all(raw) and static and not held and not touching)
|
| 516 |
+
ever = mon["ever"] if mon else [False] * len(CUPS)
|
| 517 |
+
tilted = [i for i in range(len(CUPS)) if self.tilt(CUPS[i]) > TILT_OK]
|
| 518 |
+
lost_final = [i for i in range(len(CUPS)) if not raw[i] and ever[i]]
|
| 519 |
+
never = [i for i in range(len(CUPS)) if not raw[i] and not ever[i]]
|
| 520 |
+
if success:
|
| 521 |
+
failure = "none"
|
| 522 |
+
elif held:
|
| 523 |
+
failure = "held"
|
| 524 |
+
elif touching:
|
| 525 |
+
failure = "touching"
|
| 526 |
+
elif tilted:
|
| 527 |
+
failure = "tipped"
|
| 528 |
+
elif lost_final:
|
| 529 |
+
failure = "nudged_out" if any(mon["nudged"][i] for i in lost_final) else "regressed"
|
| 530 |
+
elif never:
|
| 531 |
+
failure = "not_on_mat"
|
| 532 |
+
else:
|
| 533 |
+
failure = "not_static"
|
| 534 |
+
parts = []
|
| 535 |
+
if success:
|
| 536 |
+
parts.append("Every cup stands upright on the mat of its colour.")
|
| 537 |
+
for i in range(len(CUPS)):
|
| 538 |
+
if raw[i]:
|
| 539 |
+
continue
|
| 540 |
+
c, cup = COLOURS[i], CUPS[i]
|
| 541 |
+
if c in held:
|
| 542 |
+
parts.append(f"The {c} cup is still held by the gripper.")
|
| 543 |
+
continue
|
| 544 |
+
off = self.offset(i)
|
| 545 |
+
tl = np.degrees(self.tilt(cup))
|
| 546 |
+
where = f"{_fb(off[0])} and {_lr(off[1])} of the {c} mat's centre"
|
| 547 |
+
if tl > np.degrees(TILT_OK):
|
| 548 |
+
txt = (f"The {c} cup has fallen over" if tl > 45 else f"The {c} cup leans {tl:.0f} degrees") + f", {where}."
|
| 549 |
+
elif float(np.linalg.norm(off)) > 0.08:
|
| 550 |
+
txt = f"The {c} cup is not on the {c} mat (its centre is {100 * float(np.linalg.norm(off)):.0f} cm away)."
|
| 551 |
+
else:
|
| 552 |
+
over = []
|
| 553 |
+
if abs(off[1]) > TOL_Y:
|
| 554 |
+
over.append(f"{100 * (abs(off[1]) - TOL_Y):.1f} cm over the mat's {'left' if off[1] > 0 else 'right'} "
|
| 555 |
+
f"edge")
|
| 556 |
+
if abs(off[0]) > TOL_X:
|
| 557 |
+
over.append(f"{100 * (abs(off[0]) - TOL_X):.1f} cm over its {'far' if off[0] > 0 else 'near'} end")
|
| 558 |
+
txt = f"The {c} cup stands {where}; its base sticks out " + " and ".join(over) + "."
|
| 559 |
+
if ever[i]:
|
| 560 |
+
lost = [e for e in ev if e.get("stage") == c and e.get("event") == "lost"]
|
| 561 |
+
why = lost[-1].get("cause", "other") if lost else "other"
|
| 562 |
+
txt += {"robot_finger_opening": " It had stood on its mat; a finger pushed it when the gripper opened "
|
| 563 |
+
"next to it.",
|
| 564 |
+
"robot_finger": " It had stood on its mat; a finger pushed it.",
|
| 565 |
+
"robot_hand": " It had stood on its mat; the hand pushed it.",
|
| 566 |
+
}.get(why, " It had stood on its mat earlier and was pushed by another cup."
|
| 567 |
+
if why.startswith("cup:") else " It had stood on its mat earlier.")
|
| 568 |
+
parts.append(txt)
|
| 569 |
+
if not success and all(raw):
|
| 570 |
+
if touching:
|
| 571 |
+
parts.append("The gripper is still touching a cup.")
|
| 572 |
+
elif not static:
|
| 573 |
+
parts.append("Something was still moving.")
|
| 574 |
+
if nudges:
|
| 575 |
+
parts.append(f"During the attempt cups that stood on their mats were pushed off {len(nudges)} time(s); "
|
| 576 |
+
f"{n_res} time(s) a cup was put back.")
|
| 577 |
+
trap = bool(nudges)
|
| 578 |
+
return dict(success=success, stages={COLOURS[i]: bool(raw[i]) for i in range(len(CUPS))}, events=ev,
|
| 579 |
+
n_regressions=int(n_reg), n_lost=int(n_lost), n_restored=int(n_res), n_nudged=len(nudges),
|
| 580 |
+
n_bumped=len(bumps), trap_fired=trap, recovered_in_attempt=bool(trap and success),
|
| 581 |
+
nudged_cups=sorted({e["cup"] for e in nudges}), failure=failure, held=held,
|
| 582 |
+
touching=bool(touching), static=bool(static),
|
| 583 |
+
offsets_cm={COLOURS[i]: [round(100 * float(v), 2) for v in self.offset(i)] for i in range(4)},
|
| 584 |
+
tilts_deg={COLOURS[i]: round(float(np.degrees(self.tilt(CUPS[i]))), 1) for i in range(4)},
|
| 585 |
+
tight=bool(inst["tight"]), detail=" ".join(parts))
|
| 586 |
+
|
| 587 |
+
# ------------------------------------------------------------ scripted policies (move_to + gripper only)
|
| 588 |
+
def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300):
|
| 589 |
+
return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
|
| 590 |
+
|
| 591 |
+
def _lift_to(self, z, speed=0.15):
|
| 592 |
+
cur = self.sk.eef_pos()
|
| 593 |
+
if cur[2] < TZ + z - 0.005:
|
| 594 |
+
self._go([cur[0], cur[1], TZ + z], speed=speed)
|
| 595 |
+
|
| 596 |
+
def finger_clear(self, q, yaw, ignore=()):
|
| 597 |
+
"""smallest distance (m) between the open fingers at grasp point q (xy) with gripper yaw `yaw` and the wall of
|
| 598 |
+
any standing cup other than `ignore`; finger axis (-sin yaw, cos yaw)"""
|
| 599 |
+
a = np.array([-np.sin(yaw), np.cos(yaw)])
|
| 600 |
+
b = np.array([a[1], -a[0]])
|
| 601 |
+
best = 1.0
|
| 602 |
+
for cup in CUPS:
|
| 603 |
+
if cup in ignore or self.held(cup):
|
| 604 |
+
continue
|
| 605 |
+
rel = self.pos(cup)[:2] - np.asarray(q, float)
|
| 606 |
+
for s in (1.0, -1.0):
|
| 607 |
+
u = s * float(rel @ a)
|
| 608 |
+
v = float(rel @ b)
|
| 609 |
+
du = max(FINGER_IN - u, 0.0, u - FINGER_OUT)
|
| 610 |
+
dv = max(abs(v) - FINGER_HALF, 0.0)
|
| 611 |
+
best = min(best, float(np.hypot(du, dv)) - CUP_R)
|
| 612 |
+
return best
|
| 613 |
+
|
| 614 |
+
def safe_yaw(self, q, ignore=(), prefer=0.0):
|
| 615 |
+
"""the gripper yaw (0, 90, +-45 deg) whose open fingers stay farthest from the other cups at q"""
|
| 616 |
+
cands = [0.0, np.pi / 2, np.pi / 4, -np.pi / 4]
|
| 617 |
+
sc = [(round(min(self.finger_clear(q, y, ignore), 0.02), 3), -abs(_wrap_h(y - prefer)), y) for y in cands]
|
| 618 |
+
return max(sc)[2]
|
| 619 |
+
|
| 620 |
+
def grasp_cup(self, cup, yaw, depth, z_carry=Z_CARRY, v=0.2, err=None, lift=None):
|
| 621 |
+
"""open, go over the cup at transit height, straight down, close, lift. Returns True if held."""
|
| 622 |
+
sk = self.sk
|
| 623 |
+
p = self.pos(cup)
|
| 624 |
+
q = p[:2] + (np.asarray(err, float) if err is not None else 0.0)
|
| 625 |
+
zg = envs.obj_max_z(self.env, cup) - depth
|
| 626 |
+
sk.set_gripper(False, steps=8)
|
| 627 |
+
self._lift_to(z_carry)
|
| 628 |
+
self._go([q[0], q[1], max(sk.eef_pos()[2], TZ + z_carry)], yaw=yaw, speed=v)
|
| 629 |
+
self._go([q[0], q[1], zg + 0.015], speed=0.10)
|
| 630 |
+
self._go([q[0], q[1], zg], speed=0.04, tol=0.003, max_steps=150)
|
| 631 |
+
sk.set_gripper(True, steps=15)
|
| 632 |
+
cur = sk.eef_pos()
|
| 633 |
+
self._go([cur[0], cur[1], TZ + (z_carry if lift is None else lift)], speed=0.12)
|
| 634 |
+
sk.hold(5)
|
| 635 |
+
if not self.held(cup):
|
| 636 |
+
sk.set_gripper(False, steps=8)
|
| 637 |
+
return False
|
| 638 |
+
return True
|
| 639 |
+
|
| 640 |
+
def put_cup(self, cup, xy, yaw, z_carry=Z_CARRY, v=0.2, lift=None):
|
| 641 |
+
"""carry the held cup so that the cup (not the grasp point) is over xy, rotate to `yaw`, straight down until its
|
| 642 |
+
base is 3 mm above the table, let go, lift"""
|
| 643 |
+
sk = self.sk
|
| 644 |
+
rel = self.pos(cup)[:2] - sk.eef_pos()[:2]
|
| 645 |
+
q = np.asarray(xy, float) - rel
|
| 646 |
+
cur = sk.eef_pos()
|
| 647 |
+
self._go([q[0], q[1], max(cur[2], TZ + z_carry)], yaw=yaw, speed=v)
|
| 648 |
+
sk.hold(5)
|
| 649 |
+
rel = self.pos(cup)[:2] - sk.eef_pos()[:2] # the cup can shift in the fingers while the wrist turns
|
| 650 |
+
q = np.asarray(xy, float) - rel
|
| 651 |
+
dz = sk.eef_pos()[2] - envs.obj_min_z(self.env, cup)
|
| 652 |
+
zr = TZ + dz + 0.003
|
| 653 |
+
self._go([q[0], q[1], zr + 0.015], speed=0.10)
|
| 654 |
+
self._go([q[0], q[1], zr], speed=0.03, tol=0.003, max_steps=150)
|
| 655 |
+
sk.set_gripper(False, steps=12)
|
| 656 |
+
cur = sk.eef_pos()
|
| 657 |
+
self._go([cur[0], cur[1], TZ + (z_carry if lift is None else lift)], speed=0.15)
|
| 658 |
+
sk.hold(3)
|
| 659 |
+
|
| 660 |
+
def mat_order(self, mode="far_first"):
|
| 661 |
+
"""colour indices in placement order. far_first (Sonnet): the block row farthest from the supply first, then
|
| 662 |
+
the other; within a row from the left (robot's view)"""
|
| 663 |
+
sup = np.mean([self.inst["start"][c] for c in COLOURS], axis=0)
|
| 664 |
+
blk = np.asarray(self.inst["block"], float)
|
| 665 |
+
u = blk - sup
|
| 666 |
+
u = u / max(np.linalg.norm(u), 1e-9)
|
| 667 |
+
idx = list(range(4))
|
| 668 |
+
far = sorted(idx, key=lambda i: -float((self.mat_xy(i) - blk) @ u))
|
| 669 |
+
rows = [far[:2], far[2:]]
|
| 670 |
+
if mode == "near_first":
|
| 671 |
+
rows = rows[::-1]
|
| 672 |
+
out = []
|
| 673 |
+
for row in rows:
|
| 674 |
+
out += sorted(row, key=lambda i: (-self.mat_xy(i)[1], self.mat_xy(i)[0])) # left first
|
| 675 |
+
return out
|
| 676 |
+
|
| 677 |
+
@staticmethod
|
| 678 |
+
def looks_off(off, bias):
|
| 679 |
+
"""a (biased) observer's verdict: the cup looks off its mat centre by more than 0.8 cm in some direction"""
|
| 680 |
+
p = np.asarray(off, float) - np.asarray(bias, float)
|
| 681 |
+
return abs(p[0]) > 0.008 or abs(p[1]) > 0.008
|
| 682 |
+
|
| 683 |
+
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,
|
| 684 |
+
v=0.2):
|
| 685 |
+
"""one stage: pick cup i from wherever it is and put it on its mat; aims at mat + bias (+- rand per axis); then
|
| 686 |
+
looks at this cup only (with the same bias) and re-places it if it looks off"""
|
| 687 |
+
cup = CUPS[i]
|
| 688 |
+
bias = np.asarray(bias, float)
|
| 689 |
+
for _ in range(2):
|
| 690 |
+
gy = yaw_rule(i, "grasp")
|
| 691 |
+
gerr = rng.uniform(-0.003, 0.003, 2) if rand else None
|
| 692 |
+
if self.grasp_cup(cup, gy, depth, z_carry=z_carry, v=v, err=gerr):
|
| 693 |
+
break
|
| 694 |
+
else:
|
| 695 |
+
return
|
| 696 |
+
e = rng.uniform(-rand, rand, 2) if rand else np.zeros(2)
|
| 697 |
+
self.put_cup(cup, self.mat_xy(i) + bias + e, yaw_rule(i, "release"), z_carry=z_carry, v=v)
|
| 698 |
+
if not check:
|
| 699 |
+
return
|
| 700 |
+
for _ in range(2):
|
| 701 |
+
if not self.looks_off(self.offset(i), bias) and self.tilt(cup) < TILT_OK:
|
| 702 |
+
return
|
| 703 |
+
ry = yaw_rule(i, "grasp")
|
| 704 |
+
if not self.grasp_cup(cup, ry, depth, z_carry=Z_LIFT, v=0.1, lift=Z_LIFT):
|
| 705 |
+
return
|
| 706 |
+
e = rng.uniform(-fix_rand, fix_rand, 2) if fix_rand else np.zeros(2)
|
| 707 |
+
self.put_cup(cup, self.mat_xy(i) + bias + e, yaw_rule(i, "release"), z_carry=Z_LIFT, v=0.1, lift=z_carry)
|
| 708 |
+
|
| 709 |
+
def repair(self, rounds=4, depth=0.020, bias=(0.0, 0.0)):
|
| 710 |
+
"""look at every cup (with the observer's bias); re-centre each one that looks off: grasp and let go with the
|
| 711 |
+
fingers opening where no other cup stands. Returns the number of cups moved."""
|
| 712 |
+
bias = np.asarray(bias, float)
|
| 713 |
+
moved = 0
|
| 714 |
+
tries = {}
|
| 715 |
+
for _ in range(rounds * 4):
|
| 716 |
+
bad = [i for i in range(4) if (self.looks_off(self.offset(i), bias) or self.held(CUPS[i]))
|
| 717 |
+
and self.tilt(CUPS[i]) < np.radians(30) and tries.get(i, 0) < rounds]
|
| 718 |
+
if not bad:
|
| 719 |
+
break
|
| 720 |
+
i = min(bad, key=lambda j: float(np.linalg.norm(self.pos(CUPS[j])[:2] - self.sk.eef_pos()[:2])))
|
| 721 |
+
tries[i] = tries.get(i, 0) + 1
|
| 722 |
+
cup = CUPS[i]
|
| 723 |
+
gy = self.safe_yaw(self.pos(cup)[:2], ignore=(cup,), prefer=self.sk.yaw)
|
| 724 |
+
# lift the cup clear of its neighbours before moving it: carried at 10 cm its base clips their rims and
|
| 725 |
+
# tips them (v1, measured, 4/20 adaptive runs before this was raised)
|
| 726 |
+
if not self.grasp_cup(cup, gy, depth, z_carry=Z_LIFT, v=0.15, lift=Z_LIFT):
|
| 727 |
+
continue
|
| 728 |
+
moved += 1
|
| 729 |
+
target = self.mat_xy(i) + bias
|
| 730 |
+
ry = self.safe_yaw(target, ignore=(cup,), prefer=self.sk.yaw)
|
| 731 |
+
self.put_cup(cup, target, ry, z_carry=Z_LIFT, v=0.1, lift=Z_CARRY)
|
| 732 |
+
return moved
|
| 733 |
+
|
| 734 |
+
def execute(self, inst, params):
|
| 735 |
+
rng = np.random.default_rng(params.get("noise_seed", 0))
|
| 736 |
+
depth = params.get("depth", 0.020)
|
| 737 |
+
order = self.mat_order(params.get("order", "far_first"))
|
| 738 |
+
mode = params["yaw"] # "fixed" (one wrist yaw for everything) or "safe" (fingers away from placed cups)
|
| 739 |
+
y0 = float(params.get("yaw0", 0.0))
|
| 740 |
+
bias = (float(params.get("bias_x", 0.0)), 0.0)
|
| 741 |
+
|
| 742 |
+
def yaw_rule(i, what):
|
| 743 |
+
if mode == "fixed":
|
| 744 |
+
return y0
|
| 745 |
+
q = self.pos(CUPS[i])[:2] if what == "grasp" else self.mat_xy(i) + np.asarray(bias)
|
| 746 |
+
return self.safe_yaw(q, ignore=(CUPS[i],), prefer=y0)
|
| 747 |
+
|
| 748 |
+
rand = float(params.get("rand", 0.0))
|
| 749 |
+
for i in order:
|
| 750 |
+
self.place_one(i, yaw_rule, depth, rng, bias=bias, rand=rand, fix_rand=float(params.get("fix_rand", 0.0)),
|
| 751 |
+
check=params.get("self_check", True), z_carry=params.get("z_carry", Z_CARRY),
|
| 752 |
+
v=params.get("v", 0.2))
|
| 753 |
+
if params.get("check"):
|
| 754 |
+
self.repair(bias=bias)
|
| 755 |
+
self._lift_to(0.20)
|
| 756 |
+
self.sk.hold(10)
|
| 757 |
+
|
| 758 |
+
# naive = Sonnet 5.5's habits measured in the v1 pilot (np_lh_nudge_row): wrist yaw 0 for every grasp and release in
|
| 759 |
+
# attempt 1, the row farthest from the supply first, lift to 14-25 cm and carry straight, vertical descents,
|
| 760 |
+
# 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
|
| 761 |
+
# re-places it if it looks off, no look back at the others before finishing
|
| 762 |
+
NAIVE = dict(yaw="fixed", yaw0=0.0, order="far_first", self_check=True, check=False, rand=NAIVE_RAND,
|
| 763 |
+
fix_rand=NAIVE_FIX_RAND)
|
| 764 |
+
CAREFUL = dict(yaw="safe", yaw0=0.0, order="far_first", self_check=True, check=True, rand=0.0, bias_x=0.0)
|
| 765 |
+
|
| 766 |
+
def default_params(self, inst):
|
| 767 |
+
return dict(self.NAIVE, noise_seed=int(inst["seed"]) * 13, bias_x=float(inst["naive_bias_x"]),
|
| 768 |
+
depth=0.008 + 0.012 * ((int(inst["seed"]) * 7) % 11) / 10) # 0.8-2.0 cm below the rim (pilot: ~1 cm)
|
| 769 |
+
|
| 770 |
+
def oracle_params(self, inst):
|
| 771 |
+
return dict(self.CAREFUL)
|
| 772 |
+
|
| 773 |
+
def adapt_params(self, inst, history):
|
| 774 |
+
"""from attempt 2: let go with the fingers opening away from the placed cups (same imprecision and bias), and
|
| 775 |
+
look at every cup before finishing"""
|
| 776 |
+
return dict(self.default_params(inst), yaw="safe", check=True)
|
| 777 |
+
|
| 778 |
+
def blind_params(self, inst, attempt, rng):
|
| 779 |
+
"""the naive behaviour with random variation, no history, no final look"""
|
| 780 |
+
return dict(self.default_params(inst), noise_seed=int(rng.integers(1 << 30)),
|
| 781 |
+
yaw0=float(rng.choice([0.0, np.pi / 2])), order=str(rng.choice(["far_first", "near_first"])),
|
| 782 |
+
z_carry=float(rng.uniform(0.15, 0.22)), v=float(rng.uniform(0.1, 0.3)),
|
| 783 |
+
depth=float(rng.uniform(0.008, 0.025)), bias_x=float(rng.uniform(*NAIVE_BIAS)))
|
| 784 |
+
|
| 785 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 786 |
+
k = k or self.max_attempts
|
| 787 |
+
rng = np.random.default_rng(seed)
|
| 788 |
+
history = []
|
| 789 |
+
single = ("oracle", "naive", "oracle_noise", "naive_yaw90", "naive_check", "careful_bias2", "naive_bias2")
|
| 790 |
+
for a in range(k):
|
| 791 |
+
self.reset_instance(inst)
|
| 792 |
+
if kind == "oracle":
|
| 793 |
+
params = self.oracle_params(inst)
|
| 794 |
+
elif kind == "naive":
|
| 795 |
+
params = self.default_params(inst)
|
| 796 |
+
elif kind == "adaptive": # attempt 1: naive + a final look at every cup (repairs); then careful releases
|
| 797 |
+
params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history)
|
| 798 |
+
elif kind == "blind":
|
| 799 |
+
params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
|
| 800 |
+
elif kind == "switch": # control: cross-attempt learning only (careful releases from attempt 2), no final look
|
| 801 |
+
params = self.default_params(inst) if a == 0 else dict(self.default_params(inst), yaw="safe")
|
| 802 |
+
elif kind == "oracle_noise": # robustness: careful with +-5 mm placement / grasp noise
|
| 803 |
+
params = dict(self.CAREFUL, rand=0.005, noise_seed=int(seed) * 7 + a)
|
| 804 |
+
elif kind == "naive_yaw90": # control: Sonnet-like but the wrist turned 90 deg for everything
|
| 805 |
+
params = dict(self.default_params(inst), yaw0=np.pi / 2)
|
| 806 |
+
elif kind == "naive_check": # control: naive + final look (= adaptive's first attempt)
|
| 807 |
+
params = dict(self.default_params(inst), check=True)
|
| 808 |
+
elif kind == "careful_bias2": # control: careful releases (nothing nudged) but placed 2 cm too far forward
|
| 809 |
+
params = dict(self.default_params(inst), yaw="safe", bias_x=0.020)
|
| 810 |
+
elif kind == "naive_bias2": # control: naive with a fixed +2 cm forward bias
|
| 811 |
+
params = dict(self.default_params(inst), bias_x=0.020)
|
| 812 |
+
else:
|
| 813 |
+
raise ValueError(kind)
|
| 814 |
+
self.execute(inst, params)
|
| 815 |
+
out = self.outcome(inst)
|
| 816 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 817 |
+
if on_attempt:
|
| 818 |
+
on_attempt(a, params, out)
|
| 819 |
+
if out["success"] or kind in single:
|
| 820 |
+
break
|
| 821 |
+
return history
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/tasks/l6_count.py
ADDED
|
@@ -0,0 +1,562 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L6-B count_into_box: put exactly N identical cubes into an opaque drop box; one carry is interrupted by a slip.
|
| 2 |
+
|
| 3 |
+
Scene: T identical orange 4 cm cubes scattered on the table and a dark, closed drop box (static fixture) at
|
| 4 |
+
one side of the table. The box lid has a square opening on the robot side; a cube released above it falls in,
|
| 5 |
+
lands on a low-friction ramp and slides under the closed part of the lid, where no camera can see it (once past
|
| 6 |
+
the opening it is moved to a storage slot at the far end, so that cubes never queue back under the opening).
|
| 7 |
+
Cubes cannot be taken back out.
|
| 8 |
+
|
| 9 |
+
Instruction: put exactly N cubes into the box (N in {4, 5}, given in the instruction).
|
| 10 |
+
|
| 11 |
+
Interruption: during the (p+1)-th carry (p cubes are already in the box, p in {1..N-1}, hidden) the carried
|
| 12 |
+
cube "slips": the gripper opens and the cube lands back on the table next to the spot it was picked from. The
|
| 13 |
+
number of cubes left on the table is R = N + e with e in {0, 1} drawn independently of p (T = R + p), so
|
| 14 |
+
neither the box nor the table tells how many cubes are inside: progress ("how many have I put in already")
|
| 15 |
+
is only in the agent's own history. Over-filling is irreversible (terminal failure); under-filling can be
|
| 16 |
+
completed in a later segment.
|
| 17 |
+
|
| 18 |
+
Protocol: within (one episode, no reset), like l6_swap_interrupt. An attempt (segment) ends when the agent
|
| 19 |
+
declares done; the outcome is measured; if the box holds fewer than N cubes the agent continues from the
|
| 20 |
+
current state. The slip is injected once per episode, inside attempt 1, by a per-control-step monitor (so it
|
| 21 |
+
also fires for agents driven by the harness). Events reported immediately (`drain_events`): "A cube dropped
|
| 22 |
+
into the box." after every cube that falls in, and the slip.
|
| 23 |
+
|
| 24 |
+
Scripted references (perception = simulator state, as in l6_swap):
|
| 25 |
+
oracle privileged box count: carries cubes until the box holds N.
|
| 26 |
+
adaptive counts its own successful drops (Save), notices the slip (the cube is back on the table, the
|
| 27 |
+
drop count is unchanged), carries cubes until its count reaches N (Retrieve + Utilize). Later
|
| 28 |
+
segments: if F2 says the box holds fewer than N, adds one cube per segment.
|
| 29 |
+
naive memoryless continuation (1 attempt): loses its count at the slip; re-plans from the current frame,
|
| 30 |
+
which shows no progress, so it guesses how many cubes are already inside (uniform over 0..N-1)
|
| 31 |
+
and adds the rest.
|
| 32 |
+
blind memoryless restart (k attempts): at the slip it does not know where it was and starts over
|
| 33 |
+
("the box must get N cubes"), every later segment again puts N cubes in (repeated steps).
|
| 34 |
+
Extra controls (not in the acceptance table): `skip` (counts carries instead of drops, i.e. counts the
|
| 35 |
+
slipped carry; with memory + F2 it adds the missing cube in segment 2) and `inc1` (stateless, adds one cube
|
| 36 |
+
per segment; shows that the within protocol's stop-at-first-success leaks progress to such a policy).
|
| 37 |
+
"""
|
| 38 |
+
import numpy as np
|
| 39 |
+
|
| 40 |
+
from .. import envs
|
| 41 |
+
from ..bddl import write_bddl
|
| 42 |
+
from ..objects import _fmt, _wrap, box_xml, register_generated
|
| 43 |
+
from ..task_base import LFFTask, register_task
|
| 44 |
+
|
| 45 |
+
CUBE_HALF = 0.02
|
| 46 |
+
CUBE_RGBA = (0.95, 0.50, 0.10, 1.0)
|
| 47 |
+
N_CUBES = 11 # objects declared in the BDDL; unused ones are parked on the floor out of view
|
| 48 |
+
LETTERS = "ABCDEFGHIJK"
|
| 49 |
+
CUBES = [f"cube_{i + 1}" for i in range(N_CUBES)]
|
| 50 |
+
|
| 51 |
+
# drop box (local frame: origin at the centre of the footprint on the table top, +x away from the robot)
|
| 52 |
+
WALL_T = 0.008
|
| 53 |
+
IN_HX, IN_HY = 0.100, 0.110 # inner half sizes
|
| 54 |
+
LID_Z = 0.095 # underside of the lid above the table
|
| 55 |
+
LID_T = 0.008
|
| 56 |
+
HOLE_X = (-0.090, -0.020) # opening in the lid (local x range), on the robot side
|
| 57 |
+
HOLE_HY = 0.035
|
| 58 |
+
RAMP_Z = (0.045, 0.006) # top surface of the ramp at the near (-x) and far (+x) inner walls
|
| 59 |
+
RAMP_T = 0.006
|
| 60 |
+
RAMP_MU = 0.03
|
| 61 |
+
BOX_RGBA = (0.30, 0.20, 0.13, 1.0)
|
| 62 |
+
INNER_RGBA = (0.08, 0.07, 0.06, 1.0)
|
| 63 |
+
HOLE_C = np.array([(HOLE_X[0] + HOLE_X[1]) / 2, 0.0])
|
| 64 |
+
OUT_HX, OUT_HY = IN_HX + WALL_T, IN_HY + WALL_T
|
| 65 |
+
RAMP_SLOPE = (RAMP_Z[0] - RAMP_Z[1]) / (2 * IN_HX)
|
| 66 |
+
RAMP_TH = float(np.arctan(RAMP_SLOPE))
|
| 67 |
+
# Storage slots under the closed part of the lid. A cube that has slid past the opening is moved to the next free
|
| 68 |
+
# slot (out of every camera's view) so that the cubes do not queue up along the slide line back under the opening.
|
| 69 |
+
# Order: the lane straight behind the opening (y = 0) is filled last, so that a newly dropped cube can always slide
|
| 70 |
+
# past the opening before it is moved; then a second layer on the far row. (x, y, layer)
|
| 71 |
+
_ROW = [IN_HX - CUBE_HALF - 0.002 - 0.044 * r for r in range(2)]
|
| 72 |
+
SLOTS = ([(_ROW[r], y, 0) for r in range(2) for y in (-0.088, 0.088, -0.044, 0.044)]
|
| 73 |
+
+ [(_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)])
|
| 74 |
+
|
| 75 |
+
BASE_X = -0.66
|
| 76 |
+
REACH = 0.70 # max horizontal distance of a cube from the robot base
|
| 77 |
+
CUBE_REGION = (-0.30, 0.07, -0.28, 0.28)
|
| 78 |
+
CUBE_MIN_DIST = 0.085
|
| 79 |
+
BOX_CLEAR = 0.12 # cube centre at least this far from the box footprint (the hand must not hit the lid)
|
| 80 |
+
Z_GRASP = envs.TABLE_Z + CUBE_HALF
|
| 81 |
+
Z_CARRY = envs.TABLE_Z + 0.20
|
| 82 |
+
Z_RELEASE = envs.TABLE_Z + LID_Z + LID_T + 0.012 + CUBE_HALF # cube bottom ~1.2 cm above the lid
|
| 83 |
+
PARK = [(-0.5 + 0.1 * i, 1.25) for i in range(N_CUBES)]
|
| 84 |
+
LIFTED = 0.05 # slip trigger: cube at least this far above its resting height
|
| 85 |
+
HAND_HALF = 0.11 # the Panda hand reaches about this far along the closing axis (it hits 4 cm cubes there)
|
| 86 |
+
HAND_CLEAR = 0.06 # neighbour centre at least this far from that segment for a collision-free grasp
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def hand_box_clear(p, a, box, half=HAND_HALF):
|
| 90 |
+
"""Smallest distance from the hand segment (closing axis at yaw a) to the drop box footprint."""
|
| 91 |
+
ax = np.array([-np.sin(a), np.cos(a)])
|
| 92 |
+
return min(float(np.linalg.norm(np.maximum(np.abs(np.asarray(p) + t * ax - box) - [OUT_HX, OUT_HY], 0.0)))
|
| 93 |
+
for t in np.linspace(-half, half, 9))
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def axis_clear(p, a, others, half=HAND_HALF):
|
| 97 |
+
"""Smallest distance from a neighbour centre to the hand segment p +- half * (closing axis at yaw a)."""
|
| 98 |
+
ax = np.array([-np.sin(a), np.cos(a)])
|
| 99 |
+
best = 1.0
|
| 100 |
+
for o in others:
|
| 101 |
+
v = np.asarray(o) - p
|
| 102 |
+
t = float(np.clip(v @ ax, -half, half))
|
| 103 |
+
best = min(best, float(np.linalg.norm(v - t * ax)))
|
| 104 |
+
return best
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def drop_box_xml(model_name):
|
| 108 |
+
"""Closed box with a square opening in the lid and an internal ramp (static fixture, collisions on)."""
|
| 109 |
+
parts = [] # (pos, half size, rgba, quat or None, friction or None)
|
| 110 |
+
H = LID_Z / 2
|
| 111 |
+
# walls
|
| 112 |
+
parts.append(((IN_HX + WALL_T / 2, 0, H), (WALL_T / 2, OUT_HY, H), BOX_RGBA))
|
| 113 |
+
parts.append(((-IN_HX - WALL_T / 2, 0, H), (WALL_T / 2, OUT_HY, H), BOX_RGBA))
|
| 114 |
+
parts.append(((0, IN_HY + WALL_T / 2, H), (IN_HX, WALL_T / 2, H), BOX_RGBA))
|
| 115 |
+
parts.append(((0, -IN_HY - WALL_T / 2, H), (IN_HX, WALL_T / 2, H), BOX_RGBA))
|
| 116 |
+
# lid around the opening
|
| 117 |
+
zc = LID_Z + LID_T / 2
|
| 118 |
+
x0, x1 = HOLE_X
|
| 119 |
+
parts.append((((-OUT_HX + x0) / 2, 0, zc), ((x0 + OUT_HX) / 2, OUT_HY, LID_T / 2), BOX_RGBA)) # near strip
|
| 120 |
+
parts.append((((x1 + OUT_HX) / 2, 0, zc), ((OUT_HX - x1) / 2, OUT_HY, LID_T / 2), BOX_RGBA)) # far part
|
| 121 |
+
for s in (-1, 1):
|
| 122 |
+
parts.append((((x0 + x1) / 2, s * (HOLE_HY + OUT_HY) / 2, zc), ((x1 - x0) / 2, (OUT_HY - HOLE_HY) / 2,
|
| 123 |
+
LID_T / 2), BOX_RGBA))
|
| 124 |
+
# floor (dark) and ramp
|
| 125 |
+
parts.append(((0, 0, 0.002), (IN_HX, IN_HY, 0.002), INNER_RGBA))
|
| 126 |
+
dz = RAMP_Z[0] - RAMP_Z[1]
|
| 127 |
+
th = float(np.arctan2(dz, 2 * IN_HX))
|
| 128 |
+
L = float(np.hypot(dz, 2 * IN_HX)) / 2
|
| 129 |
+
zmid = (RAMP_Z[0] + RAMP_Z[1]) / 2 - RAMP_T / 2 / np.cos(th)
|
| 130 |
+
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)
|
| 131 |
+
geoms = []
|
| 132 |
+
for k, p in enumerate(parts + [ramp]):
|
| 133 |
+
pos, half, rgba = p[:3]
|
| 134 |
+
quat = p[3] if len(p) > 3 else None
|
| 135 |
+
mu = p[4] if len(p) > 4 else None
|
| 136 |
+
q = f' quat="{_fmt(quat)}"' if quat is not None else ""
|
| 137 |
+
fr = f' friction="{mu} 0.005 0.0001" priority="2"' if mu is not None else ' friction="1.0 0.005 0.0001"'
|
| 138 |
+
geoms.append(f' <geom name="{model_name}_g{k}" type="box" pos="{_fmt(pos)}" size="{_fmt(half)}"{q} '
|
| 139 |
+
f'rgba="{_fmt(rgba)}" density="1000"{fr} group="0" />')
|
| 140 |
+
geoms.append(f' <geom type="box" pos="{_fmt(pos)}" size="{_fmt(half)}"{q} rgba="{_fmt(rgba)}" '
|
| 141 |
+
f'conaffinity="0" contype="0" group="1" />')
|
| 142 |
+
return _wrap(model_name, "\n".join(geoms), (LID_Z + LID_T) / 2, float(np.hypot(OUT_HX, OUT_HY)))
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def _wrap_q(a):
|
| 146 |
+
"""cubes are symmetric under 90 deg rotations: wrap to [-pi/4, pi/4)"""
|
| 147 |
+
return float((a + np.pi / 4) % (np.pi / 2) - np.pi / 4)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
@register_task
|
| 151 |
+
class CountIntoBox(LFFTask):
|
| 152 |
+
name = "l6_count_into_box"
|
| 153 |
+
level = "L6"
|
| 154 |
+
category = "procedural_memory"
|
| 155 |
+
capabilities = ("Perceive", "Save", "Retrieve", "Utilize")
|
| 156 |
+
protocol = "within"
|
| 157 |
+
agent_max_steps = 80 # robot commands per attempt for agents (a VLM needs ~40-55)
|
| 158 |
+
max_attempts = 5
|
| 159 |
+
_TEMPLATE = ("Put exactly {n} of the orange cubes into the dark box, through the opening in its lid. "
|
| 160 |
+
"Cubes cannot be taken back out of the box.")
|
| 161 |
+
_TEMPLATE_INDIRECT = ("Drop exactly {n} of the small orange blocks into the closed brown container through the "
|
| 162 |
+
"square hole in its top. Blocks cannot be taken back out of the container.")
|
| 163 |
+
instruction = _TEMPLATE.format(n="N") # replaced per instance (sample_instance / agent_instruction)
|
| 164 |
+
instruction_indirect = _TEMPLATE_INDIRECT.format(n="N")
|
| 165 |
+
inject = True
|
| 166 |
+
announce_drops = True # False: no "A cube dropped into the box." event (harder variant, counting from images)
|
| 167 |
+
agent_object_names = ["orange cube (several identical)", "drop box"]
|
| 168 |
+
|
| 169 |
+
WORDS = {3: "three", 4: "four", 5: "five", 6: "six"}
|
| 170 |
+
|
| 171 |
+
def agent_instruction(self, inst, variant="direct"):
|
| 172 |
+
t = self._TEMPLATE_INDIRECT if variant == "indirect" else self._TEMPLATE
|
| 173 |
+
return t.format(n=self.WORDS[inst["n_target"]])
|
| 174 |
+
|
| 175 |
+
def __init__(self, cam_res=None):
|
| 176 |
+
super().__init__(cam_res)
|
| 177 |
+
self._mon = False
|
| 178 |
+
orig_step = self.env.step
|
| 179 |
+
|
| 180 |
+
def step(action): # per-control-step monitor: also sees attempts driven by the agent harness
|
| 181 |
+
ret = orig_step(action)
|
| 182 |
+
if self._mon:
|
| 183 |
+
self._monitor()
|
| 184 |
+
return ret
|
| 185 |
+
|
| 186 |
+
self.env.step = step
|
| 187 |
+
|
| 188 |
+
# ------------------------------------------------------------ scene
|
| 189 |
+
def make_bddl(self):
|
| 190 |
+
objs = []
|
| 191 |
+
for i, L in enumerate(LETTERS[:N_CUBES]):
|
| 192 |
+
cat = register_generated(f"LffCountCube{L}", box_xml(f"lff_count_cube_{L.lower()}", (CUBE_HALF,) * 3,
|
| 193 |
+
CUBE_RGBA, density=600))
|
| 194 |
+
gx, gy = -0.30 + 0.15 * (i % 4), -0.40 + 0.2 * (i // 4)
|
| 195 |
+
objs.append((CUBES[i], cat, f"c{i + 1}_region", (gx - 0.01, gy - 0.01, gx + 0.01, gy + 0.01)))
|
| 196 |
+
box = register_generated("LffDropBox", drop_box_xml("lff_drop_box"), free=False)
|
| 197 |
+
fx = [("drop_box_1", box, "box_region", (0.19, 0.39, 0.21, 0.41))]
|
| 198 |
+
return write_bddl(self.name, self._TEMPLATE.format(n="N"), objs, fx)
|
| 199 |
+
|
| 200 |
+
def _box_body(self):
|
| 201 |
+
return self.env.sim.model.body_name2id(self.env.fixtures_dict["drop_box_1"].root_body)
|
| 202 |
+
|
| 203 |
+
def sample_instance(self, seed):
|
| 204 |
+
rng = np.random.default_rng(seed)
|
| 205 |
+
n = int(rng.choice([4, 5]))
|
| 206 |
+
p = int(rng.integers(1, n)) # cubes already inside when the slip happens
|
| 207 |
+
e = int(rng.integers(0, 2))
|
| 208 |
+
T = n + e + p
|
| 209 |
+
for _ in range(500):
|
| 210 |
+
side = int(rng.choice([-1, 1]))
|
| 211 |
+
box = np.array([rng.uniform(-0.08, -0.02), side * rng.uniform(0.22, 0.25)])
|
| 212 |
+
P = np.column_stack([rng.uniform(*CUBE_REGION[:2], 800), rng.uniform(*CUBE_REGION[2:], 800)])
|
| 213 |
+
P = P[np.hypot(P[:, 0] - BASE_X, P[:, 1]) <= REACH]
|
| 214 |
+
P = P[np.linalg.norm(np.maximum(np.abs(P - box) - np.array([OUT_HX, OUT_HY]), 0.0), axis=1) >= BOX_CLEAR]
|
| 215 |
+
cubes = []
|
| 216 |
+
for c in P: # random sequential addition
|
| 217 |
+
if all(np.linalg.norm(c - q) >= CUBE_MIN_DIST for q in cubes):
|
| 218 |
+
cubes.append(c)
|
| 219 |
+
if len(cubes) == T:
|
| 220 |
+
break
|
| 221 |
+
if len(cubes) < T:
|
| 222 |
+
continue
|
| 223 |
+
yaws = [] # each cube gets a yaw whose (small-rotation) grasp axis is free for the hand
|
| 224 |
+
for i in range(T):
|
| 225 |
+
oth = [cubes[j] for j in range(T) if j != i]
|
| 226 |
+
for _ in range(30):
|
| 227 |
+
y = float(rng.uniform(-np.pi / 4, np.pi / 4))
|
| 228 |
+
if axis_clear(cubes[i], y, oth) >= HAND_CLEAR and hand_box_clear(cubes[i], y, box) >= 0.035:
|
| 229 |
+
# |y| <= 45 deg: the grasp needs no large wrist rotation
|
| 230 |
+
yaws.append(y)
|
| 231 |
+
break
|
| 232 |
+
else:
|
| 233 |
+
break
|
| 234 |
+
if len(yaws) == T:
|
| 235 |
+
break
|
| 236 |
+
else:
|
| 237 |
+
raise RuntimeError("could not sample a layout")
|
| 238 |
+
inst = dict(seed=int(seed), n_target=n, p=p, e=e, n_cubes=T, box_xy=box.round(4).tolist(),
|
| 239 |
+
cubes=np.array(cubes).round(4).tolist(),
|
| 240 |
+
yaws=yaws,
|
| 241 |
+
trigger_dist=float(rng.uniform(0.05, 0.09)),
|
| 242 |
+
slip_r=float(rng.uniform(0.005, 0.02)), slip_ang=float(rng.uniform(0, 2 * np.pi)),
|
| 243 |
+
slip_yaw=float(rng.uniform(-np.pi / 4, np.pi / 4)))
|
| 244 |
+
# make_video prints task.instruction: keep it in sync with the last sampled instance
|
| 245 |
+
self.instruction = self.agent_instruction(inst, "direct")
|
| 246 |
+
self.instruction_indirect = self.agent_instruction(inst, "indirect")
|
| 247 |
+
return inst
|
| 248 |
+
|
| 249 |
+
def apply_instance(self, inst):
|
| 250 |
+
m = self.env.sim.model
|
| 251 |
+
bid = self._box_body()
|
| 252 |
+
m.body_pos[bid] = [inst["box_xy"][0], inst["box_xy"][1], envs.TABLE_Z]
|
| 253 |
+
m.body_quat[bid] = [1, 0, 0, 0]
|
| 254 |
+
T = inst["n_cubes"]
|
| 255 |
+
for i, c in enumerate(CUBES):
|
| 256 |
+
if i < T:
|
| 257 |
+
envs.set_obj_pose(self.env, c, [*inst["cubes"][i], envs.TABLE_Z + CUBE_HALF + 0.001],
|
| 258 |
+
yaw=inst["yaws"][i])
|
| 259 |
+
else:
|
| 260 |
+
envs.set_obj_pose(self.env, c, [*PARK[i], CUBE_HALF + 0.001])
|
| 261 |
+
self.env.sim.forward()
|
| 262 |
+
self._inst = inst
|
| 263 |
+
self.active = CUBES[:T]
|
| 264 |
+
self.slip = None
|
| 265 |
+
self.events = []
|
| 266 |
+
self._event_cursor = 0
|
| 267 |
+
self._outcome_cursor = 0
|
| 268 |
+
self.in_box = [] # cubes that fell into the box, in order
|
| 269 |
+
self.stored = [] # cubes moved to a storage slot
|
| 270 |
+
self._bad = set() # scripted policies: cubes whose grasp failed
|
| 271 |
+
self.rest_xy = {c: np.array(inst["cubes"][i]) for i, c in enumerate(self.active)}
|
| 272 |
+
self._mon = False
|
| 273 |
+
|
| 274 |
+
def reset_instance(self, inst, recorder=None):
|
| 275 |
+
self._mon = False
|
| 276 |
+
sk = super().reset_instance(inst, recorder=recorder)
|
| 277 |
+
self._home = sk.eef_pos()
|
| 278 |
+
self._mon = True
|
| 279 |
+
return sk
|
| 280 |
+
|
| 281 |
+
def go_home(self):
|
| 282 |
+
p = self.sk.eef_pos()
|
| 283 |
+
self.sk.move_to([p[0], p[1], max(p[2], self._home[2])])
|
| 284 |
+
self.sk.move_to(self._home)
|
| 285 |
+
|
| 286 |
+
# ------------------------------------------------------------ geometry helpers
|
| 287 |
+
def box_local(self, xyz):
|
| 288 |
+
b = self._inst["box_xy"]
|
| 289 |
+
return np.array([xyz[0] - b[0], xyz[1] - b[1], xyz[2] - envs.TABLE_Z])
|
| 290 |
+
|
| 291 |
+
def hole_world(self):
|
| 292 |
+
b = self._inst["box_xy"]
|
| 293 |
+
return np.array([b[0] + HOLE_C[0], b[1] + HOLE_C[1]])
|
| 294 |
+
|
| 295 |
+
def inside_box(self, c):
|
| 296 |
+
q = self.box_local(envs.obj_pos(self.env, c))
|
| 297 |
+
return bool(abs(q[0]) < IN_HX and abs(q[1]) < IN_HY and q[2] < LID_Z)
|
| 298 |
+
|
| 299 |
+
def on_lid(self, c):
|
| 300 |
+
q = self.box_local(envs.obj_pos(self.env, c))
|
| 301 |
+
return bool(abs(q[0]) < OUT_HX + 0.01 and abs(q[1]) < OUT_HY + 0.01 and q[2] >= LID_Z)
|
| 302 |
+
|
| 303 |
+
def on_table(self, c):
|
| 304 |
+
p = envs.obj_pos(self.env, c)
|
| 305 |
+
return bool(p[2] < envs.TABLE_Z + CUBE_HALF + 0.01 and not self.inside_box(c))
|
| 306 |
+
|
| 307 |
+
# ------------------------------------------------------------ monitor (every control step)
|
| 308 |
+
def _monitor(self):
|
| 309 |
+
env = self.env
|
| 310 |
+
for c in self.active:
|
| 311 |
+
if c in self.in_box:
|
| 312 |
+
if c not in self.stored and self.box_local(envs.obj_pos(env, c))[0] > HOLE_X[1] + 0.02:
|
| 313 |
+
self._store(c)
|
| 314 |
+
continue
|
| 315 |
+
p = envs.obj_pos(env, c)
|
| 316 |
+
if self.inside_box(c):
|
| 317 |
+
self.in_box.append(c)
|
| 318 |
+
if self.announce_drops:
|
| 319 |
+
self.events.append(dict(step=int(self.sk.n_steps), kind="drop", obj=c,
|
| 320 |
+
text="A cube dropped into the box."))
|
| 321 |
+
continue
|
| 322 |
+
if p[2] < envs.TABLE_Z + CUBE_HALF + 0.005: # resting on the table: remember where
|
| 323 |
+
self.rest_xy[c] = p[:2].copy()
|
| 324 |
+
continue
|
| 325 |
+
if (self.inject and self.slip is None and p[2] > envs.TABLE_Z + CUBE_HALF + LIFTED
|
| 326 |
+
and len(self.in_box) == self._inst["p"]
|
| 327 |
+
and np.linalg.norm(p[:2] - self.rest_xy[c]) >= self._inst["trigger_dist"]
|
| 328 |
+
and self.sk.holding(c)):
|
| 329 |
+
self._do_slip(c)
|
| 330 |
+
|
| 331 |
+
def _store(self, c):
|
| 332 |
+
sx, sy, layer = SLOTS[min(len(self.stored), len(SLOTS) - 1)]
|
| 333 |
+
b = self._inst["box_xy"]
|
| 334 |
+
z = RAMP_Z[0] - (sx + IN_HX) * RAMP_SLOPE + CUBE_HALF / np.cos(RAMP_TH) + 0.002 + layer * (2 * CUBE_HALF + 0.003)
|
| 335 |
+
envs.set_obj_pose(self.env, c, [b[0] + sx, b[1] + sy, envs.TABLE_Z + z],
|
| 336 |
+
quat_wxyz=[np.cos(RAMP_TH / 2), 0.0, np.sin(RAMP_TH / 2), 0.0])
|
| 337 |
+
self.stored.append(c)
|
| 338 |
+
|
| 339 |
+
def _do_slip(self, c):
|
| 340 |
+
inst = self._inst
|
| 341 |
+
src = self.rest_xy[c]
|
| 342 |
+
others = [envs.obj_pos(self.env, o)[:2] for o in self.active if o != c and o not in self.in_box]
|
| 343 |
+
xy, yaw = src, inst["slip_yaw"]
|
| 344 |
+
found = False
|
| 345 |
+
for r in (inst["slip_r"], inst["slip_r"] / 2, 0.0): # next to the pick-up spot, still graspable
|
| 346 |
+
cand = src + r * np.array([np.cos(inst["slip_ang"]), np.sin(inst["slip_ang"])])
|
| 347 |
+
if not all(np.linalg.norm(cand - o) >= 0.07 for o in others):
|
| 348 |
+
continue
|
| 349 |
+
for dy in (0.0, 0.3, -0.3, 0.6, -0.6):
|
| 350 |
+
y = _wrap_q(inst["slip_yaw"] + dy)
|
| 351 |
+
if axis_clear(cand, y, others) >= HAND_CLEAR and \
|
| 352 |
+
hand_box_clear(cand, y, np.asarray(inst["box_xy"])) >= 0.035:
|
| 353 |
+
xy, yaw, found = cand, y, True
|
| 354 |
+
break
|
| 355 |
+
if found:
|
| 356 |
+
break
|
| 357 |
+
envs.set_obj_pose(self.env, c, [xy[0], xy[1], envs.TABLE_Z + CUBE_HALF + 0.002], yaw=yaw)
|
| 358 |
+
self.sk.grip = -1.0 # the gripper opens
|
| 359 |
+
self.env.sim.forward()
|
| 360 |
+
text = "A cube slipped out of the gripper and fell back onto the table."
|
| 361 |
+
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),
|
| 362 |
+
in_box=len(self.in_box))
|
| 363 |
+
self.events.append(dict(step=int(self.sk.n_steps), kind="slip", obj=c, text=text))
|
| 364 |
+
|
| 365 |
+
def drain_events(self):
|
| 366 |
+
ev = self.events[self._event_cursor:]
|
| 367 |
+
self._event_cursor = len(self.events)
|
| 368 |
+
return [e["text"] for e in ev]
|
| 369 |
+
|
| 370 |
+
# ------------------------------------------------------------ outcome
|
| 371 |
+
def outcome(self, inst):
|
| 372 |
+
envs.settle(self.env, 20)
|
| 373 |
+
n_in = len(self.in_box)
|
| 374 |
+
N = inst["n_target"]
|
| 375 |
+
held = [c for c in self.active if self.sk.holding(c)]
|
| 376 |
+
n_table = sum(self.on_table(c) for c in self.active if c not in self.in_box)
|
| 377 |
+
n_lid = sum(self.on_lid(c) for c in self.active if c not in self.in_box)
|
| 378 |
+
success = bool(n_in == N and not held)
|
| 379 |
+
terminal = bool(n_in > N)
|
| 380 |
+
if success:
|
| 381 |
+
head = f"The box holds exactly {N} cubes."
|
| 382 |
+
elif terminal:
|
| 383 |
+
head = (f"The box holds more than {N} cubes. Cubes cannot be taken out of the box, so the task can no "
|
| 384 |
+
f"longer be completed.")
|
| 385 |
+
elif n_in == N:
|
| 386 |
+
head = f"The gripper is still holding a cube."
|
| 387 |
+
else:
|
| 388 |
+
head = f"The box holds fewer than {N} cubes."
|
| 389 |
+
state = f"Now {n_table} cube{'s are' if n_table != 1 else ' is'} on the table"
|
| 390 |
+
if n_lid:
|
| 391 |
+
state += f" and {n_lid} on the box lid"
|
| 392 |
+
state += "."
|
| 393 |
+
# F2 = verdict + currently observable state + the slip of this segment (never the number inside)
|
| 394 |
+
new = [e for e in self.events[self._outcome_cursor:] if e["kind"] == "slip"]
|
| 395 |
+
self._outcome_cursor = len(self.events)
|
| 396 |
+
detail = head + " " + state
|
| 397 |
+
if new:
|
| 398 |
+
detail = "During this attempt: " + " ".join(e["text"] for e in new) + " " + detail
|
| 399 |
+
return dict(success=success, terminal=terminal, n_in_box=n_in, n_target=N, n_table=n_table, n_lid=n_lid,
|
| 400 |
+
held=len(held), slip=self.slip, detail=detail)
|
| 401 |
+
|
| 402 |
+
# ------------------------------------------------------------ motion (scripted policies)
|
| 403 |
+
def _grasp_yaw(self, c):
|
| 404 |
+
"""The cube's grasp axis with the smaller wrist rotation (|yaw| <= 45 deg). Rotations near +-90 deg drive
|
| 405 |
+
the Panda wrist into its joint-6 limit at some positions (measured), so the other axis is used only if
|
| 406 |
+
the hand would hit a neighbour or the box on this one."""
|
| 407 |
+
R = self.env.sim.data.body_xmat[envs.body_id(self.env, c)].reshape(3, 3)
|
| 408 |
+
yaw = _wrap_q(float(np.arctan2(R[1, 0], R[0, 0])))
|
| 409 |
+
p = envs.obj_pos(self.env, c)[:2]
|
| 410 |
+
others = [envs.obj_pos(self.env, o)[:2] for o in self.active if o != c and o not in self.in_box]
|
| 411 |
+
box = np.asarray(self._inst["box_xy"])
|
| 412 |
+
|
| 413 |
+
def score(a):
|
| 414 |
+
return min(axis_clear(p, a, others), hand_box_clear(p, a, box) + 0.03)
|
| 415 |
+
if score(yaw) >= HAND_CLEAR:
|
| 416 |
+
return yaw
|
| 417 |
+
alt = yaw - np.pi / 2 if yaw >= 0 else yaw + np.pi / 2
|
| 418 |
+
return alt if score(alt) > score(yaw) + 0.02 else yaw
|
| 419 |
+
|
| 420 |
+
def _pick(self, c):
|
| 421 |
+
sk = self.sk
|
| 422 |
+
for _ in range(2):
|
| 423 |
+
p = envs.obj_pos(self.env, c)
|
| 424 |
+
sk.grasp_at(p[:2], Z_GRASP, yaw=self._grasp_yaw(c), lift=0.12)
|
| 425 |
+
if sk.holding(c):
|
| 426 |
+
return True
|
| 427 |
+
sk.set_gripper(False, steps=8)
|
| 428 |
+
sk.move_to([p[0], p[1], Z_GRASP + 0.12])
|
| 429 |
+
return False
|
| 430 |
+
|
| 431 |
+
def _carry(self, c):
|
| 432 |
+
"""Pick cube c and release it above the opening. Returns 'in', 'slipped', 'missed' or 'no_grasp'."""
|
| 433 |
+
n_ev = len(self.events)
|
| 434 |
+
n_in = len(self.in_box)
|
| 435 |
+
if not self._pick(c):
|
| 436 |
+
self._bad.add(c)
|
| 437 |
+
self.go_home() # un-wind the arm before the next try
|
| 438 |
+
return "no_grasp"
|
| 439 |
+
h = self.hole_world()
|
| 440 |
+
sk = self.sk
|
| 441 |
+
sk.move_to([h[0], h[1], Z_CARRY], yaw=0.0) # the slip may fire here; any yaw fits the opening
|
| 442 |
+
if any(e["kind"] == "slip" for e in self.events[n_ev:]):
|
| 443 |
+
return "slipped"
|
| 444 |
+
sk.move_to([h[0], h[1], Z_RELEASE], tol=0.004)
|
| 445 |
+
sk.set_gripper(False, steps=12)
|
| 446 |
+
sk.move_to([h[0], h[1], Z_CARRY])
|
| 447 |
+
sk.hold(10)
|
| 448 |
+
return "in" if len(self.in_box) > n_in else "missed"
|
| 449 |
+
|
| 450 |
+
def _next_cube(self):
|
| 451 |
+
"""nearest table cube to the opening (what any policy sees in the current frame)"""
|
| 452 |
+
h = self.hole_world()
|
| 453 |
+
cands = [c for c in self.active if c not in self.in_box and (self.on_table(c) or self.on_lid(c))]
|
| 454 |
+
cands = [c for c in cands if c not in self._bad] or cands # try another cube after a failed grasp
|
| 455 |
+
if not cands:
|
| 456 |
+
return None
|
| 457 |
+
return min(cands, key=lambda c: np.linalg.norm(envs.obj_pos(self.env, c)[:2] - h))
|
| 458 |
+
|
| 459 |
+
def _add(self, k, log, stop_on_slip=False):
|
| 460 |
+
"""Carry until k cubes went in (by the policy's own observation of each drop). Returns (added, slipped)."""
|
| 461 |
+
added, slipped = 0, False
|
| 462 |
+
guard = 0
|
| 463 |
+
while added < k and guard < 3 * k + 3:
|
| 464 |
+
guard += 1
|
| 465 |
+
c = self._next_cube()
|
| 466 |
+
if c is None:
|
| 467 |
+
break
|
| 468 |
+
r = self._carry(c)
|
| 469 |
+
log.append(r)
|
| 470 |
+
if r == "in":
|
| 471 |
+
added += 1
|
| 472 |
+
elif r == "slipped":
|
| 473 |
+
slipped = True
|
| 474 |
+
if stop_on_slip:
|
| 475 |
+
break
|
| 476 |
+
return added, slipped
|
| 477 |
+
|
| 478 |
+
# ------------------------------------------------------------ scripted references (within protocol)
|
| 479 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 480 |
+
k = k or self.max_attempts
|
| 481 |
+
rng = np.random.default_rng(seed + 7919)
|
| 482 |
+
self.reset_instance(inst)
|
| 483 |
+
N = inst["n_target"]
|
| 484 |
+
history = []
|
| 485 |
+
for a in range(k):
|
| 486 |
+
log = []
|
| 487 |
+
plan = dict(kind=kind, carries=log)
|
| 488 |
+
if a == 0:
|
| 489 |
+
if kind == "oracle":
|
| 490 |
+
while len(self.in_box) < N and len(log) < 3 * N + 3: # privileged count
|
| 491 |
+
c = self._next_cube()
|
| 492 |
+
if c is None:
|
| 493 |
+
break
|
| 494 |
+
log.append(self._carry(c))
|
| 495 |
+
plan["recovery"] = "oracle: privileged box count"
|
| 496 |
+
elif kind in ("adaptive", "skip"):
|
| 497 |
+
added, slipped = self._add(N, log) if kind == "adaptive" else (0, False)
|
| 498 |
+
if kind == "skip": # counts carries, not drops
|
| 499 |
+
n_car = 0
|
| 500 |
+
while n_car < N and len(log) < 3 * N:
|
| 501 |
+
c = self._next_cube()
|
| 502 |
+
if c is None:
|
| 503 |
+
break
|
| 504 |
+
r = self._carry(c)
|
| 505 |
+
log.append(r)
|
| 506 |
+
if r in ("in", "slipped"):
|
| 507 |
+
n_car += 1
|
| 508 |
+
if r == "in":
|
| 509 |
+
added += 1
|
| 510 |
+
plan["recovery"] = "counts carries (the slipped one too)"
|
| 511 |
+
else:
|
| 512 |
+
plan["recovery"] = "own drop count; the slipped carry is not counted"
|
| 513 |
+
else: # memoryless after the slip
|
| 514 |
+
added, slipped = self._add(N, log, stop_on_slip=True)
|
| 515 |
+
if slipped:
|
| 516 |
+
if kind == "naive":
|
| 517 |
+
guess = int(rng.integers(0, N))
|
| 518 |
+
plan["recovery"] = f"memoryless: guesses {guess} already inside, adds {N - guess}"
|
| 519 |
+
self._add(N - guess, log)
|
| 520 |
+
elif kind == "blind":
|
| 521 |
+
plan["recovery"] = f"memoryless restart: puts {N} cubes in"
|
| 522 |
+
self._add(N, log)
|
| 523 |
+
elif kind == "inc1":
|
| 524 |
+
plan["recovery"] = "stateless: adds one cube per segment"
|
| 525 |
+
self._add(1, log)
|
| 526 |
+
else:
|
| 527 |
+
raise ValueError(kind)
|
| 528 |
+
else:
|
| 529 |
+
plan["recovery"] = "none (no slip)"
|
| 530 |
+
else:
|
| 531 |
+
if kind in ("adaptive", "skip"):
|
| 532 |
+
plan["recovery"] = "memory + F2 'fewer than N': add one cube"
|
| 533 |
+
self._add(1, log)
|
| 534 |
+
elif kind == "blind":
|
| 535 |
+
plan["recovery"] = f"memoryless restart: puts {N} cubes in"
|
| 536 |
+
self._add(N, log)
|
| 537 |
+
elif kind == "inc1":
|
| 538 |
+
plan["recovery"] = "stateless: adds one cube"
|
| 539 |
+
self._add(1, log)
|
| 540 |
+
elif kind == "oracle":
|
| 541 |
+
while len(self.in_box) < N and len(log) < 3 * N + 3:
|
| 542 |
+
c = self._next_cube()
|
| 543 |
+
if c is None:
|
| 544 |
+
break
|
| 545 |
+
log.append(self._carry(c))
|
| 546 |
+
else:
|
| 547 |
+
raise ValueError(kind)
|
| 548 |
+
self.go_home()
|
| 549 |
+
out = self.outcome(inst)
|
| 550 |
+
history.append(dict(attempt=a + 1, params=plan, outcome=out))
|
| 551 |
+
if on_attempt:
|
| 552 |
+
on_attempt(a, plan, out)
|
| 553 |
+
if out["success"] or out["terminal"] or kind in ("oracle", "naive"):
|
| 554 |
+
break
|
| 555 |
+
return history
|
| 556 |
+
|
| 557 |
+
# cross-protocol hooks are not used by this task
|
| 558 |
+
def default_params(self, inst):
|
| 559 |
+
return dict(policy="naive")
|
| 560 |
+
|
| 561 |
+
def oracle_params(self, inst):
|
| 562 |
+
return dict(policy="oracle")
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/tasks/lh_bystander.py
ADDED
|
@@ -0,0 +1,830 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LH bystander: put three cubes into an open box while a tall glass bottle that is not part of the task stands right
|
| 2 |
+
in front of the box -- lowering a cube into the box, the robot's own forearm comes down onto the bottle and knocks it
|
| 3 |
+
over.
|
| 4 |
+
|
| 5 |
+
Family: long-horizon self-disturbance, environment level ("state_restoration"; LIBERO-Recover's damage category L4: the
|
| 6 |
+
damaged thing is not part of the task). Three easy pick-and-place stages; the instruction says plainly that nothing
|
| 7 |
+
else may be moved and that the bottle must be left standing where it is. The agent has to notice the fallen bottle and
|
| 8 |
+
stand it up again on its spot before finishing (within an attempt), or learn to keep its arm off the bottle (across
|
| 9 |
+
attempts).
|
| 10 |
+
|
| 11 |
+
Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
|
| 12 |
+
* 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;
|
| 13 |
+
centre x in [0.00, 0.04], 6-10 cm left or right of the middle;
|
| 14 |
+
* 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,
|
| 15 |
+
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
|
| 16 |
+
never passes over the bottle;
|
| 17 |
+
* 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,
|
| 18 |
+
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
|
| 19 |
+
bottle: it tips beyond 8.5 deg; pressed down on its cap, beyond 3.7 deg).
|
| 20 |
+
|
| 21 |
+
Instance variable (where the bottle stands): "hazard" (15 of every 20 consecutive seeds): right in front of the box,
|
| 22 |
+
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":
|
| 23 |
+
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
|
| 24 |
+
the physics is hidden. What the agent cannot see before acting is its own arm: the wrist camera shows the fingers, not
|
| 25 |
+
the forearm, and the agent steers the grasp point.
|
| 26 |
+
|
| 27 |
+
Disturbance (physics, no teleport): lowering a cube onto the box floor (grasp point ~4 cm above the table), the
|
| 28 |
+
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
|
| 29 |
+
and wrist (links 5-7) slope back from the hand towards the robot base, starting ~12 cm above the grasp point; over the
|
| 30 |
+
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
|
| 31 |
+
there. The bottle is pushed over (mostly
|
| 32 |
+
towards the robot) and lies on the table in front of the box; visible in agentview once the arm has moved away
|
| 33 |
+
(measured, task card). Not every contact knocks it: a descent can come to rest on the cap (pinched between links 5
|
| 34 |
+
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
|
| 35 |
+
lifts (measured: the smoke-test sequence on seed 3000; 6-7 of 8 hazard seeds still knocked with slow or near-first
|
| 36 |
+
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
|
| 37 |
+
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
|
| 38 |
+
transit). A careful packer keeps its arm above the bottle: carry at >= 24 cm and release the cube from >= 18 cm
|
| 39 |
+
(dropping it into the box) -- or moves the bottle out of the way and back, which the final-state judge would accept
|
| 40 |
+
but the instruction rules out.
|
| 41 |
+
|
| 42 |
+
Restoring (re-standable by a top-down gripper that only turns about the vertical): the body is square (a lying bottle
|
| 43 |
+
does not roll away from the closing fingers) and the cap is a ball with low torsional friction: grasped from above with
|
| 44 |
+
the fingers across the lying bottle's axis, the cap turns between the fingers, the lifted bottle swings down and hangs
|
| 45 |
+
straight; lowered onto the table it stands (measured: placement error ~1 mm). The instruction tells the agent that the
|
| 46 |
+
bottle hangs straight down when held by its cap (as lh_fence does for its knobs).
|
| 47 |
+
|
| 48 |
+
Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (every cube in the
|
| 49 |
+
box -- footprint inside the cavity, top below the rim, not held --, the bottle upright within 10 deg and its base
|
| 50 |
+
within 2 cm of where it stood, nothing held or touched, scene static) plus a per-step event log for the server log:
|
| 51 |
+
cube stages achieved / lost / restored; bottle_in_place lost / restored (with cause: arm / hand / cube, the robot geom,
|
| 52 |
+
the grasp point) plus the marker events bystander_knocked / bystander_restored / fallen. F1 gives the agent only
|
| 53 |
+
success / failure.
|
| 54 |
+
"""
|
| 55 |
+
import numpy as np
|
| 56 |
+
|
| 57 |
+
from .. import envs
|
| 58 |
+
from ..bddl import write_bddl
|
| 59 |
+
from ..objects import _SOLID, _fmt, _wrap, box_xml, register_generated
|
| 60 |
+
from ..skills import Skills
|
| 61 |
+
from ..task_base import LFFTask, register_task
|
| 62 |
+
|
| 63 |
+
Z = envs.TABLE_Z
|
| 64 |
+
# ---------------------------------------------------------------- geometry / physics
|
| 65 |
+
BOX = "box_1"
|
| 66 |
+
BOX_MODEL = "lff_lhb_box"
|
| 67 |
+
BOX_IN = 0.070 # cavity half width (14 x 14 cm)
|
| 68 |
+
WALL_T, FLOOR_T, WALL_H = 0.008, 0.006, 0.060
|
| 69 |
+
BOX_OUT = BOX_IN + WALL_T
|
| 70 |
+
RIM = FLOOR_T + WALL_H # rim height above the table
|
| 71 |
+
WOOD = (0.62, 0.45, 0.28, 1.0)
|
| 72 |
+
|
| 73 |
+
CUBES = ("red_cube_1", "yellow_cube_1", "blue_cube_1")
|
| 74 |
+
CUBE_COLOR = {"red_cube_1": "red", "yellow_cube_1": "yellow", "blue_cube_1": "blue"}
|
| 75 |
+
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))
|
| 76 |
+
CUBE_E = 0.040
|
| 77 |
+
CUBE_DENS = 500.0 # 32 g
|
| 78 |
+
CUBE_MU = 0.8
|
| 79 |
+
|
| 80 |
+
BOTTLE = "bottle_1"
|
| 81 |
+
BOTTLE_MODEL = "lff_lhb_bottle"
|
| 82 |
+
BOTTLE_CLASS = "LffLhbBottle"
|
| 83 |
+
RB, HB = 0.030, 0.185 # square body: half width, height
|
| 84 |
+
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
|
| 85 |
+
# 4.8 cm foot of the draft the forearm could come to rest on the cap and stall instead of
|
| 86 |
+
# knocking it (bottle pressed down like a column, tilt <= 5 deg; measured, see the task card)
|
| 87 |
+
RS, HS = 0.022, 0.015 # shoulder
|
| 88 |
+
RN, HN = 0.0115, 0.060 # neck
|
| 89 |
+
RK = 0.015 # ball cap radius; its centre sits RK - 6 mm above the neck top
|
| 90 |
+
CAP_SINK = 0.006
|
| 91 |
+
H_TOT = HB + HS + HN + 2 * RK - CAP_SINK # 0.284
|
| 92 |
+
CAP_Z = H_TOT - RK # cap centre above the bottle's bottom when standing
|
| 93 |
+
BOTTLE_MASS = 0.25
|
| 94 |
+
BOTTLE_COM = 0.12 # above the bottom (an empty glass bottle: ~42 % of its height)
|
| 95 |
+
BOTTLE_MU = 0.6
|
| 96 |
+
CAP_MU_T = 0.0005 # torsional friction of the cap (condim 4): the grasped cap turns freely, the swing is damped
|
| 97 |
+
GLASS = (0.16, 0.42, 0.26, 1.0)
|
| 98 |
+
CAP_RGBA = (0.78, 0.12, 0.10, 1.0)
|
| 99 |
+
|
| 100 |
+
# instances
|
| 101 |
+
P_HAZARD = 0.75 # 15 of every 20 consecutive seeds: bottle in front of the box
|
| 102 |
+
HAZ_GAP = (0.010, 0.025) # bottle body to the box's front wall
|
| 103 |
+
HAZ_LAT = (-0.010, 0.040) # bottle centre left (+y) of the box's centre line
|
| 104 |
+
BEN_GAP = (0.080, 0.110) # beside the box, on its outer side (away from the cubes)
|
| 105 |
+
BEN_DX = (-0.030, 0.030)
|
| 106 |
+
BOX_X = (0.0, 0.04) # the bottle in front of the box stays >= 2 cm clear of the fingers in the home pose
|
| 107 |
+
BOX_Y = (0.06, 0.10) # |y| of the box centre; the side is random
|
| 108 |
+
CUBE_Y = (0.19, 0.23) # |y| of the cube row (other side)
|
| 109 |
+
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):
|
| 110 |
+
# the straight carry to the box passes >= 2 cm from the bottle in front of it
|
| 111 |
+
|
| 112 |
+
# success predicate
|
| 113 |
+
POS_TOL = 0.020 # bottle base within 2 cm of where it stood
|
| 114 |
+
UPRIGHT = np.radians(10.0)
|
| 115 |
+
KNOCK_TILT = np.radians(10.0) # once in place, the bottle counts as disturbed when tilted beyond this (it tips at
|
| 116 |
+
# 8.5 deg: beyond, it is falling or leaning on something) or moved
|
| 117 |
+
POS_HYST = 0.003 # > POS_TOL + POS_HYST for DEBOUNCE checks (a nudge that rocks back within 0.6 s is no loss)
|
| 118 |
+
FALLEN = np.radians(60.0)
|
| 119 |
+
IN_TOL = 0.002 # a cube's footprint may reach this far past the inner walls
|
| 120 |
+
RIM_TOL = 0.004
|
| 121 |
+
BELOW_RIM = 0.010 # in_box: the cube's lowest point at least this far below the rim
|
| 122 |
+
DEBOUNCE = 6 # predicate checks (every 0.1 s) a change must persist
|
| 123 |
+
|
| 124 |
+
# scripted motion (heights of the grasp point above the table)
|
| 125 |
+
Z_CARRY = 0.15 # Sonnet's transit: 11-20 cm, often lifted to ~20 before moving
|
| 126 |
+
Z_REL = 0.040 # Sonnet-like release: cube set down on the box floor (grasp point 4 cm up)
|
| 127 |
+
Z_SAFE = 0.26 # careful transit
|
| 128 |
+
Z_DROP = 0.19 # careful release: the cube is dropped from above the rim, the forearm stays above the bottle
|
| 129 |
+
NAIVE_ERR = 0.008 # Sonnet's placement error 0.4-1.3 cm
|
| 130 |
+
SLOT = 0.033 # slot offset from the box centre (cavity 14 cm, cubes 4 cm)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def bottle_xml(name):
|
| 134 |
+
h = H_TOT / 2
|
| 135 |
+
zf, zb, zs, zn = -h + HF / 2, -h + HF + (HB - HF) / 2, -h + HB + HS / 2, -h + HB + HS + HN / 2
|
| 136 |
+
zk = -h + HB + HS + HN + RK - CAP_SINK
|
| 137 |
+
m = BOTTLE_MASS
|
| 138 |
+
ixx = m * ((2 * RB) ** 2 + H_TOT ** 2) / 16 # rough: most of the glass is in the body and the base
|
| 139 |
+
izz = m * (2 * (2 * RB) ** 2) / 12
|
| 140 |
+
parts = [("foot", "box", (0, 0, zf), (RF, RF, HF / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'),
|
| 141 |
+
("body", "box", (0, 0, zb), (RB, RB, (HB - HF) / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'),
|
| 142 |
+
("shoulder", "box", (0, 0, zs), (RS, RS, HS / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'),
|
| 143 |
+
("neck", "cylinder", (0, 0, zn), (RN, HN / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'),
|
| 144 |
+
("cap", "sphere", (0, 0, zk), (RK,), CAP_RGBA, f'friction="1 {CAP_MU_T} 0.0001" condim="4" priority="2"')]
|
| 145 |
+
s = [f' <inertial pos="0 0 {-h + BOTTLE_COM:.4f}" mass="{m}" diaginertia="{ixx:.6f} {ixx:.6f} {izz:.6f}" />']
|
| 146 |
+
for nm, typ, pos, size, c, extra in parts:
|
| 147 |
+
s.append(f' <geom name="{name}_{nm}" type="{typ}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(c)}" '
|
| 148 |
+
f'{extra} group="0" />')
|
| 149 |
+
s.append(f' <geom type="{typ}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(c)}" contype="0" '
|
| 150 |
+
f'conaffinity="0" group="1" />')
|
| 151 |
+
# a lighter label band (visual only) so the bottle reads as a bottle
|
| 152 |
+
s.append(f' <geom type="box" pos="0 0 {zb + 0.01:.4f}" size="{RB + 0.0008:.4f} {RB + 0.0008:.4f} 0.035" '
|
| 153 |
+
f'rgba="0.92 0.90 0.80 1" contype="0" conaffinity="0" group="1" />')
|
| 154 |
+
return _wrap(name, "\n".join(s), h, RB * 1.42)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def box_fixture_xml(name):
|
| 158 |
+
"""open wooden box, origin at the centre of its footprint, z = 0 at the table"""
|
| 159 |
+
ix = BOX_IN
|
| 160 |
+
parts = [((0, 0, FLOOR_T / 2), (BOX_OUT, BOX_OUT, FLOOR_T / 2)),
|
| 161 |
+
((ix + WALL_T / 2, 0, RIM / 2), (WALL_T / 2, BOX_OUT, RIM / 2)),
|
| 162 |
+
((-ix - WALL_T / 2, 0, RIM / 2), (WALL_T / 2, BOX_OUT, RIM / 2)),
|
| 163 |
+
((0, ix + WALL_T / 2, RIM / 2), (ix, WALL_T / 2, RIM / 2)),
|
| 164 |
+
((0, -ix - WALL_T / 2, RIM / 2), (ix, WALL_T / 2, RIM / 2))]
|
| 165 |
+
g = []
|
| 166 |
+
for k, (p, sz) in enumerate(parts):
|
| 167 |
+
g.append(f' <geom name="{name}_w{k}" type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(WOOD)}" '
|
| 168 |
+
f'friction="0.8 0.005 0.0001" {_SOLID} group="0" />')
|
| 169 |
+
g.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(WOOD)}" contype="0" '
|
| 170 |
+
f'conaffinity="0" group="1" />')
|
| 171 |
+
return f"""<mujoco model="{name}">
|
| 172 |
+
<worldbody>
|
| 173 |
+
<body>
|
| 174 |
+
<body name="object">
|
| 175 |
+
{chr(10).join(g)}
|
| 176 |
+
</body>
|
| 177 |
+
<site rgba="0 0 0 0" size="0.005" pos="0 0 0" name="bottom_site" />
|
| 178 |
+
<site rgba="0 0 0 0" size="0.005" pos="0 0 {RIM:.4f}" name="top_site" />
|
| 179 |
+
<site rgba="0 0 0 0" size="0.005" pos="{BOX_OUT:.4f} {BOX_OUT:.4f} 0" name="horizontal_radius_site" />
|
| 180 |
+
</body>
|
| 181 |
+
</worldbody>
|
| 182 |
+
</mujoco>"""
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
REACH_MAX = 0.74 # scripted policies: farthest grasp point (horizontal distance from the robot base) they rely on
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def _reach(p):
|
| 189 |
+
return float(np.hypot(p[0] + 0.66, p[1]))
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def _fb(v):
|
| 193 |
+
return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}"
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def _lr(v):
|
| 197 |
+
return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}"
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class BystanderSkills(Skills):
|
| 201 |
+
"""Skills that feed the task's per-step monitor."""
|
| 202 |
+
|
| 203 |
+
def __init__(self, env, task, recorder=None):
|
| 204 |
+
super().__init__(env, recorder=recorder)
|
| 205 |
+
self.task = task
|
| 206 |
+
|
| 207 |
+
def _act(self, dpos, drot, grip):
|
| 208 |
+
super()._act(dpos, drot, grip)
|
| 209 |
+
self.task.monitor_step()
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
@register_task
|
| 213 |
+
class Bystander(LFFTask):
|
| 214 |
+
name = "lh_bystander"
|
| 215 |
+
level = "L2"
|
| 216 |
+
category = "state_restoration"
|
| 217 |
+
capabilities = ("Perceive", "Reason", "Restore", "Plan")
|
| 218 |
+
protocol = "cross"
|
| 219 |
+
max_attempts = 3
|
| 220 |
+
agent_max_steps = 100 # careful: 3 cubes x ~7 commands + looking; standing the bottle up again ~8-10; + slack
|
| 221 |
+
instruction = ("Put the red, yellow and blue cubes into the open wooden box. Do not move anything else: the tall "
|
| 222 |
+
"glass bottle must be left standing upright exactly where it is now. (The bottle has a round red "
|
| 223 |
+
"cap; held by its cap, the bottle hangs straight down.)")
|
| 224 |
+
instruction_indirect = ("Pack the three small cubes (red, yellow, blue) into the wooden crate. Leave everything else "
|
| 225 |
+
"as it is -- the tall green bottle has to stay standing on its spot. (Its round red cap: held "
|
| 226 |
+
"by the cap, the bottle hangs straight down.)")
|
| 227 |
+
agent_object_names = ["red cube", "yellow cube", "blue cube", "open wooden box",
|
| 228 |
+
"tall glass bottle (square, with a round red cap; held by its cap it hangs straight down)"]
|
| 229 |
+
|
| 230 |
+
# ------------------------------------------------------------ scene
|
| 231 |
+
def make_bddl(self):
|
| 232 |
+
box = register_generated("LffLhbBox", box_fixture_xml(BOX_MODEL), free=False)
|
| 233 |
+
objs = []
|
| 234 |
+
for i, n in enumerate(CUBES):
|
| 235 |
+
c = CUBE_COLOR[n]
|
| 236 |
+
cat = register_generated(f"LffLhbCube{c.title()}",
|
| 237 |
+
box_xml(f"lff_lhb_cube_{c}", (CUBE_E / 2,) * 3, CUBE_RGBA[c], density=CUBE_DENS,
|
| 238 |
+
friction=(CUBE_MU, 0.005, 0.0001)).replace(_SOLID, ""))
|
| 239 |
+
objs.append((n, cat, f"{c}_cube_region", (-0.35, -0.25 + 0.15 * i, -0.33, -0.23 + 0.15 * i)))
|
| 240 |
+
bt = register_generated(BOTTLE_CLASS, bottle_xml(BOTTLE_MODEL))
|
| 241 |
+
objs.append((BOTTLE, bt, "bottle_region", (-0.35, 0.24, -0.33, 0.26)))
|
| 242 |
+
fx = [(BOX, box, "box_region", (-0.06, -0.01, -0.04, 0.01))]
|
| 243 |
+
return write_bddl(self.name, "put the cubes into the box and leave the bottle where it is", objs, fx)
|
| 244 |
+
|
| 245 |
+
def __init__(self, cam_res=None):
|
| 246 |
+
super().__init__(cam_res)
|
| 247 |
+
m = self.env.sim.model
|
| 248 |
+
self.box_bid = m.body_name2id(self.env.fixtures_dict[BOX].root_body)
|
| 249 |
+
self.box_gids = {g for g in range(m.ngeom) if m.geom_bodyid[g] in
|
| 250 |
+
{self.box_bid} | {c for c in range(m.nbody) if m.body_parentid[c] == self.box_bid}}
|
| 251 |
+
pre = f"{BOTTLE}_{BOTTLE_MODEL}"
|
| 252 |
+
self.cap_gid = m.geom_name2id(pre + "_cap")
|
| 253 |
+
self.bottle_gids = set(envs.obj_geom_ids(self.env, BOTTLE))
|
| 254 |
+
self.cube_gids = {n: set(envs.obj_geom_ids(self.env, n)) for n in CUBES}
|
| 255 |
+
# robot parts: 1 = hand / fingers (what the agent sees and steers), 2 = arm links (wrist, forearm, ...)
|
| 256 |
+
self.part = np.zeros(m.ngeom, int)
|
| 257 |
+
for g in envs.robot_geom_ids(self.env):
|
| 258 |
+
n = m.geom_id2name(g) or ""
|
| 259 |
+
self.part[g] = 1 if n.startswith("gripper0_") else 2
|
| 260 |
+
self.other = np.zeros(m.ngeom, int) # 3 = a cube, 4 = the box
|
| 261 |
+
for n in CUBES:
|
| 262 |
+
self.other[list(self.cube_gids[n])] = 3
|
| 263 |
+
self.other[list(self.box_gids)] = 4
|
| 264 |
+
self.is_bottle = np.zeros(m.ngeom, bool)
|
| 265 |
+
self.is_bottle[list(self.bottle_gids)] = True
|
| 266 |
+
# bottle contacts are collected after every MuJoCo substep (a fast hit can be shorter than a control step)
|
| 267 |
+
sim = self.env.sim
|
| 268 |
+
if not getattr(sim, "_lhb_wrapped", False):
|
| 269 |
+
orig = sim.step
|
| 270 |
+
|
| 271 |
+
def step(*a, **k):
|
| 272 |
+
orig(*a, **k)
|
| 273 |
+
t = getattr(sim, "_lhb_task", None)
|
| 274 |
+
if t is not None and t.mon is not None:
|
| 275 |
+
t._substep()
|
| 276 |
+
sim.step = step
|
| 277 |
+
sim._lhb_wrapped = True
|
| 278 |
+
sim._lhb_task = self
|
| 279 |
+
self._sub = {}
|
| 280 |
+
self.inst = None
|
| 281 |
+
self.mon = None
|
| 282 |
+
self.sk = None
|
| 283 |
+
|
| 284 |
+
def sample_instance(self, seed):
|
| 285 |
+
rng = np.random.default_rng(seed)
|
| 286 |
+
s = 1.0 if rng.random() < 0.5 else -1.0 # box on the left (+1) or right (-1)
|
| 287 |
+
bx, by = float(rng.uniform(*BOX_X)), s * float(rng.uniform(*BOX_Y))
|
| 288 |
+
# balanced blocks like lh_lid_box: exactly round(20 * P_HAZARD) of every 20 consecutive seeds are hazards
|
| 289 |
+
hazard = bool((int(seed) * 7) % 20 < round(20 * P_HAZARD))
|
| 290 |
+
if hazard:
|
| 291 |
+
gap, lat = float(rng.uniform(*HAZ_GAP)), float(rng.uniform(*HAZ_LAT))
|
| 292 |
+
bottle = [bx - BOX_OUT - gap - RB, by + lat]
|
| 293 |
+
else:
|
| 294 |
+
gap, lat = float(rng.uniform(*BEN_GAP)), float(rng.uniform(*BEN_DX))
|
| 295 |
+
bottle = [bx + lat, by + s * (BOX_OUT + gap + RB)]
|
| 296 |
+
cy = -s * float(rng.uniform(*CUBE_Y))
|
| 297 |
+
perm = rng.permutation(len(CUBES))
|
| 298 |
+
start = {CUBES[i]: [float(bx + CUBE_DX[j] + rng.uniform(-0.01, 0.01)), float(cy + rng.uniform(-0.01, 0.01))]
|
| 299 |
+
for j, i in enumerate(perm)}
|
| 300 |
+
start_yaw = {n: float(rng.uniform(-0.3, 0.3)) for n in CUBES}
|
| 301 |
+
return dict(seed=int(seed), hazard=hazard, bottle_side="front" if hazard else "outer side",
|
| 302 |
+
box_side="left" if s > 0 else "right", box_xy=[bx, by], bottle_xy=[float(bottle[0]), float(bottle[1])],
|
| 303 |
+
bottle_yaw=float(rng.uniform(-0.25, 0.25)), gap=gap, lat=lat, start=start, start_yaw=start_yaw)
|
| 304 |
+
|
| 305 |
+
def apply_instance(self, inst):
|
| 306 |
+
self.inst = inst
|
| 307 |
+
m = self.env.sim.model
|
| 308 |
+
bx, by = inst["box_xy"]
|
| 309 |
+
m.body_pos[self.box_bid] = [bx, by, Z]
|
| 310 |
+
m.body_quat[self.box_bid] = [1.0, 0.0, 0.0, 0.0]
|
| 311 |
+
for n, xy in inst["start"].items():
|
| 312 |
+
envs.place_upright(self.env, n, xy, yaw=inst["start_yaw"][n], clearance=0.001)
|
| 313 |
+
envs.set_friction(self.env, n, CUBE_MU)
|
| 314 |
+
envs.place_upright(self.env, BOTTLE, inst["bottle_xy"], yaw=inst["bottle_yaw"], clearance=0.001)
|
| 315 |
+
|
| 316 |
+
def reset_instance(self, inst, recorder=None):
|
| 317 |
+
self.mon = None
|
| 318 |
+
self.env.reset()
|
| 319 |
+
self.apply_instance(inst)
|
| 320 |
+
self.env.sim.forward()
|
| 321 |
+
envs.settle(self.env, 15)
|
| 322 |
+
self.sk = BystanderSkills(self.env, self, recorder=recorder)
|
| 323 |
+
self._sub = {}
|
| 324 |
+
self._init_monitor()
|
| 325 |
+
return self.sk
|
| 326 |
+
|
| 327 |
+
# ------------------------------------------------------------ state helpers
|
| 328 |
+
def R(self, name):
|
| 329 |
+
return self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3).copy()
|
| 330 |
+
|
| 331 |
+
def bottle_tilt(self):
|
| 332 |
+
return float(np.arccos(np.clip(self.R(BOTTLE)[2, 2], -1.0, 1.0)))
|
| 333 |
+
|
| 334 |
+
def bottle_base(self):
|
| 335 |
+
"""xy of the centre of the bottle's bottom face"""
|
| 336 |
+
d = self.env.sim.data
|
| 337 |
+
return (envs.obj_pos(self.env, BOTTLE) - self.R(BOTTLE)[:, 2] * H_TOT / 2)[:2]
|
| 338 |
+
|
| 339 |
+
def bottle_offset(self):
|
| 340 |
+
return self.bottle_base() - np.asarray(self.inst["bottle_xy"])
|
| 341 |
+
|
| 342 |
+
def cap_xyz(self):
|
| 343 |
+
return self.env.sim.data.geom_xpos[self.cap_gid].copy()
|
| 344 |
+
|
| 345 |
+
def held(self, name):
|
| 346 |
+
return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name]))
|
| 347 |
+
|
| 348 |
+
def bottle_in_place(self, tol=POS_TOL, tilt=UPRIGHT):
|
| 349 |
+
return bool(self.bottle_tilt() <= tilt and np.linalg.norm(self.bottle_offset()) <= tol
|
| 350 |
+
and envs.obj_min_z(self.env, BOTTLE) < Z + 0.01 and not self.held(BOTTLE))
|
| 351 |
+
|
| 352 |
+
def to_box(self, xy):
|
| 353 |
+
return np.asarray(xy, float)[:2] - np.asarray(self.inst["box_xy"])
|
| 354 |
+
|
| 355 |
+
def in_box(self, name):
|
| 356 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 357 |
+
g = next(iter(self.cube_gids[name]))
|
| 358 |
+
Rg = d.geom_xmat[g].reshape(3, 3)
|
| 359 |
+
c = self.to_box(d.geom_xpos[g][:2])
|
| 360 |
+
ext = np.abs(Rg[:2, :]) @ m.geom_size[g][:3]
|
| 361 |
+
# 10-14: "in the box" = footprint inside the cavity and the cube's lowest point well below the rim (it is held
|
| 362 |
+
# by the walls); a cube stacked on another one may stick out above the rim -- the instruction never asks for
|
| 363 |
+
# "below the rim" (two Sonnet pilot attempts that stacked the last cube were judged failures before this)
|
| 364 |
+
return bool(np.all(np.abs(c) + ext <= BOX_IN + IN_TOL) and envs.obj_min_z(self.env, name) <= Z + RIM - BELOW_RIM
|
| 365 |
+
and not self.held(name))
|
| 366 |
+
|
| 367 |
+
def over_box(self, name):
|
| 368 |
+
c = self.to_box(envs.obj_pos(self.env, name)[:2])
|
| 369 |
+
return bool(np.all(np.abs(c) <= BOX_OUT))
|
| 370 |
+
|
| 371 |
+
def stage_values(self):
|
| 372 |
+
v = {f"{CUBE_COLOR[n]}_in_box": self.in_box(n) for n in CUBES}
|
| 373 |
+
v["bottle_in_place"] = self.bottle_in_place()
|
| 374 |
+
return v
|
| 375 |
+
|
| 376 |
+
# ------------------------------------------------------------ per-step monitor
|
| 377 |
+
def _init_monitor(self):
|
| 378 |
+
keys = [f"{CUBE_COLOR[n]}_in_box" for n in CUBES] + ["bottle_in_place"]
|
| 379 |
+
st = {k: False for k in keys}
|
| 380 |
+
st["bottle_in_place"] = self.bottle_in_place()
|
| 381 |
+
self.mon = dict(state=st, ever=[k for k in keys if st[k]], lost=[], events=[], cand={k: 0 for k in keys},
|
| 382 |
+
step=0, last_touch=None, robot_touch_step=-10 ** 9, touch_parts=[], n_knocks=0, n_fallen=0,
|
| 383 |
+
fallen=False,
|
| 384 |
+
max_tilt_deg=0.0, max_offset_cm=0.0, first_knock_step=None, first_touch_step=None)
|
| 385 |
+
|
| 386 |
+
def _substep(self):
|
| 387 |
+
d = self.env.sim.data
|
| 388 |
+
n = d.ncon
|
| 389 |
+
if not n:
|
| 390 |
+
return
|
| 391 |
+
g1 = np.asarray(d.contact.geom1)[:n]
|
| 392 |
+
g2 = np.asarray(d.contact.geom2)[:n]
|
| 393 |
+
b1, b2 = self.is_bottle[g1], self.is_bottle[g2]
|
| 394 |
+
sel = b1 ^ b2
|
| 395 |
+
if not sel.any():
|
| 396 |
+
return
|
| 397 |
+
other = np.where(b1, g2, g1)[sel]
|
| 398 |
+
for o in other:
|
| 399 |
+
p = int(self.part[o])
|
| 400 |
+
if p:
|
| 401 |
+
who = "hand" if p == 1 else "arm"
|
| 402 |
+
prev = self._sub.get("robot")
|
| 403 |
+
self._sub["robot"] = "arm" if (who == "arm" or prev == "arm") else "hand"
|
| 404 |
+
self._sub.setdefault("geom", self.env.sim.model.geom_id2name(int(o)))
|
| 405 |
+
elif self.other[o] == 3:
|
| 406 |
+
self._sub["cube"] = True
|
| 407 |
+
|
| 408 |
+
def monitor_step(self):
|
| 409 |
+
mon = self.mon
|
| 410 |
+
if mon is None:
|
| 411 |
+
return
|
| 412 |
+
mon["step"] += 1
|
| 413 |
+
step = self.sk.n_steps if self.sk is not None else mon["step"]
|
| 414 |
+
sub, self._sub = self._sub, {}
|
| 415 |
+
if "robot" in sub:
|
| 416 |
+
mon["robot_touch_step"] = step
|
| 417 |
+
mon["last_touch"] = [sub["robot"], step, sub.get("geom", "")]
|
| 418 |
+
if sub["robot"] not in mon["touch_parts"]:
|
| 419 |
+
mon["touch_parts"].append(sub["robot"])
|
| 420 |
+
if mon["first_touch_step"] is None:
|
| 421 |
+
mon["first_touch_step"] = step
|
| 422 |
+
elif sub.get("cube") and (mon["last_touch"] is None or step - mon["last_touch"][1] > 20):
|
| 423 |
+
mon["last_touch"] = ["cube", step, ""]
|
| 424 |
+
tilt = self.bottle_tilt()
|
| 425 |
+
mon["max_tilt_deg"] = round(max(mon["max_tilt_deg"], float(np.degrees(tilt))), 1)
|
| 426 |
+
mon["max_offset_cm"] = round(max(mon["max_offset_cm"], 100 * float(np.linalg.norm(self.bottle_offset()))), 1)
|
| 427 |
+
if mon["step"] % 2:
|
| 428 |
+
return # predicates every other control step (0.1 s)
|
| 429 |
+
if not mon["fallen"] and tilt > FALLEN and not self.held(BOTTLE):
|
| 430 |
+
mon["fallen"] = True
|
| 431 |
+
mon["n_fallen"] += 1
|
| 432 |
+
mon["events"].append(dict(step=step, pred="bottle", ev="fallen", cause=self._cause(step)))
|
| 433 |
+
elif mon["fallen"] and tilt < UPRIGHT:
|
| 434 |
+
mon["fallen"] = False
|
| 435 |
+
for n in CUBES:
|
| 436 |
+
self._check(f"{CUBE_COLOR[n]}_in_box", self.in_box(n), step, n)
|
| 437 |
+
st = mon["state"]["bottle_in_place"]
|
| 438 |
+
# hysteresis: once in place it counts as lost only beyond 2.3 cm / 10 deg, held for 0.6 s (a nudge that rocks
|
| 439 |
+
# back is no loss)
|
| 440 |
+
now = self.bottle_in_place(POS_TOL + POS_HYST, KNOCK_TILT) if st else self.bottle_in_place()
|
| 441 |
+
self._check("bottle_in_place", now, step, BOTTLE)
|
| 442 |
+
|
| 443 |
+
def _cause(self, step):
|
| 444 |
+
lt = self.mon["last_touch"]
|
| 445 |
+
if lt is not None and step - lt[1] <= 60:
|
| 446 |
+
return lt[0]
|
| 447 |
+
return "other"
|
| 448 |
+
|
| 449 |
+
def _check(self, key, now, step, name):
|
| 450 |
+
mon = self.mon
|
| 451 |
+
if now == mon["state"][key]:
|
| 452 |
+
mon["cand"][key] = 0
|
| 453 |
+
return
|
| 454 |
+
if name == BOTTLE and not now and step - mon["robot_touch_step"] <= 6 and not self.held(BOTTLE):
|
| 455 |
+
# the arm is still pressing on the bottle (measured: a slow descent can come to rest on its cap and stall,
|
| 456 |
+
# tilting it ~12 deg; it rocks back when the arm lifts): a loss only once the robot has let go of it
|
| 457 |
+
mon["cand"][key] = 0
|
| 458 |
+
return
|
| 459 |
+
mon["cand"][key] += 1
|
| 460 |
+
if mon["cand"][key] < DEBOUNCE:
|
| 461 |
+
return
|
| 462 |
+
mon["cand"][key] = 0
|
| 463 |
+
mon["state"][key] = now
|
| 464 |
+
if now:
|
| 465 |
+
restored = key in mon["lost"]
|
| 466 |
+
ev = "restored" if restored else "achieved"
|
| 467 |
+
if key not in mon["ever"]:
|
| 468 |
+
mon["ever"].append(key)
|
| 469 |
+
if restored:
|
| 470 |
+
mon["lost"].remove(key)
|
| 471 |
+
mon["events"].append(dict(step=step, pred=key, ev=ev))
|
| 472 |
+
if key == "bottle_in_place" and restored:
|
| 473 |
+
mon["events"].append(dict(step=step, pred="bottle", ev="bystander_restored",
|
| 474 |
+
offset_cm=(100 * self.bottle_offset()).round(1).tolist()))
|
| 475 |
+
return
|
| 476 |
+
if key not in mon["ever"]:
|
| 477 |
+
return
|
| 478 |
+
cause = "picked_up" if self.held(name) else self._cause(step)
|
| 479 |
+
if key not in mon["lost"]:
|
| 480 |
+
mon["lost"].append(key)
|
| 481 |
+
e = dict(step=step, pred=key, ev="lost", cause=cause)
|
| 482 |
+
if name == BOTTLE:
|
| 483 |
+
ee = self.sk.eef_pos() if self.sk is not None else np.zeros(3)
|
| 484 |
+
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],
|
| 485 |
+
ee[2] - Z)] # grasp point rel. to the box centre / table
|
| 486 |
+
e.update(tilt_deg=round(float(np.degrees(self.bottle_tilt())), 1),
|
| 487 |
+
offset_cm=(100 * self.bottle_offset()).round(1).tolist())
|
| 488 |
+
if mon["last_touch"] is not None and mon["last_touch"][0] in ("arm", "hand"):
|
| 489 |
+
e["robot_geom"] = mon["last_touch"][2]
|
| 490 |
+
mon["events"].append(e)
|
| 491 |
+
if name == BOTTLE and cause != "picked_up":
|
| 492 |
+
mon["n_knocks"] += 1
|
| 493 |
+
if mon["first_knock_step"] is None:
|
| 494 |
+
mon["first_knock_step"] = step
|
| 495 |
+
mon["events"].append(dict(step=step, pred="bottle", ev="bystander_knocked", cause=cause,
|
| 496 |
+
robot_geom=e.get("robot_geom", ""), tilt_deg=e["tilt_deg"],
|
| 497 |
+
offset_cm=e["offset_cm"], eef_cm=e["eef_cm"]))
|
| 498 |
+
|
| 499 |
+
# ------------------------------------------------------------ outcome
|
| 500 |
+
def _static(self):
|
| 501 |
+
d = self.env.sim.data
|
| 502 |
+
for n in CUBES + (BOTTLE,):
|
| 503 |
+
_, da = envs.free_joint_addr(self.env, n)
|
| 504 |
+
if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5:
|
| 505 |
+
return False
|
| 506 |
+
return True
|
| 507 |
+
|
| 508 |
+
def robot_touching(self):
|
| 509 |
+
d = self.env.sim.data
|
| 510 |
+
out = []
|
| 511 |
+
for i in range(d.ncon):
|
| 512 |
+
c = d.contact[i]
|
| 513 |
+
for a, b in ((c.geom1, c.geom2), (c.geom2, c.geom1)):
|
| 514 |
+
if self.part[a] and (self.is_bottle[b] or self.other[b] == 3):
|
| 515 |
+
nm = "bottle" if self.is_bottle[b] else "a cube"
|
| 516 |
+
if nm not in out:
|
| 517 |
+
out.append(nm)
|
| 518 |
+
return out
|
| 519 |
+
|
| 520 |
+
def outcome(self, inst):
|
| 521 |
+
envs.settle(self.env, 30)
|
| 522 |
+
mon = self.mon
|
| 523 |
+
vals = self.stage_values()
|
| 524 |
+
static = self._static()
|
| 525 |
+
held = [n for n in CUBES + (BOTTLE,) if self.held(n)]
|
| 526 |
+
touching = self.robot_touching()
|
| 527 |
+
success = bool(all(vals.values()) and static and not held and not touching)
|
| 528 |
+
evs = mon["events"]
|
| 529 |
+
regress = [e for e in evs if e["ev"] == "lost"]
|
| 530 |
+
restored = [e for e in evs if e["ev"] == "restored"]
|
| 531 |
+
knocks = [e for e in evs if e["ev"] == "bystander_knocked"]
|
| 532 |
+
# trap fired: a knock was logged, or the bottle ends up out of place after the robot touched it (a slow push
|
| 533 |
+
# to just over 2 cm can stay inside the monitor's hysteresis band)
|
| 534 |
+
trap_fired = bool(knocks) or (not vals["bottle_in_place"] and not self.held(BOTTLE) and bool(mon["touch_parts"]))
|
| 535 |
+
recovered = bool(trap_fired and vals["bottle_in_place"])
|
| 536 |
+
off = self.bottle_offset()
|
| 537 |
+
tilt = float(np.degrees(self.bottle_tilt()))
|
| 538 |
+
parts = []
|
| 539 |
+
failure = None
|
| 540 |
+
if success:
|
| 541 |
+
parts.append("All three cubes are in the box and the bottle stands where it stood.")
|
| 542 |
+
else:
|
| 543 |
+
out_cubes = [n for n in CUBES if not vals[f"{CUBE_COLOR[n]}_in_box"]]
|
| 544 |
+
if not vals["bottle_in_place"]:
|
| 545 |
+
failure = ("bystander_held" if self.held(BOTTLE) else
|
| 546 |
+
"bystander_knocked" if tilt > np.degrees(UPRIGHT) else "bystander_moved")
|
| 547 |
+
elif held:
|
| 548 |
+
failure = "held"
|
| 549 |
+
elif out_cubes:
|
| 550 |
+
failure = "cube_not_in_box"
|
| 551 |
+
elif touching:
|
| 552 |
+
failure = "robot_touching"
|
| 553 |
+
else:
|
| 554 |
+
failure = "not_static"
|
| 555 |
+
if not vals["bottle_in_place"]:
|
| 556 |
+
if self.held(BOTTLE):
|
| 557 |
+
parts.append("The bottle is still held by the gripper.")
|
| 558 |
+
else:
|
| 559 |
+
pose = ("is lying on its side" if tilt > 60 else f"is tilted {tilt:.0f} degrees" if tilt > np.degrees(UPRIGHT)
|
| 560 |
+
else "stands upright")
|
| 561 |
+
txt = f"The bottle {pose}; its base is {_fb(off[0])} and {_lr(off[1])} of where it stood"
|
| 562 |
+
if knocks:
|
| 563 |
+
k = knocks[0]
|
| 564 |
+
who = {"arm": "the robot's arm (above the gripper)", "hand": "the gripper",
|
| 565 |
+
"cube": "a cube"}.get(k["cause"], "something")
|
| 566 |
+
txt += f" (it was knocked by {who}"
|
| 567 |
+
txt += " and stood up again later, but not back in place)." if restored and any(
|
| 568 |
+
e["pred"] == "bottle_in_place" for e in restored) else ")."
|
| 569 |
+
else:
|
| 570 |
+
txt += "."
|
| 571 |
+
parts.append(txt)
|
| 572 |
+
for n in out_cubes:
|
| 573 |
+
c = CUBE_COLOR[n]
|
| 574 |
+
if self.held(n):
|
| 575 |
+
parts.append(f"The {c} cube is still held by the gripper.")
|
| 576 |
+
elif self.over_box(n):
|
| 577 |
+
parts.append(f"The {c} cube rests on the box's rim instead of inside the box.")
|
| 578 |
+
else:
|
| 579 |
+
rel = self.to_box(envs.obj_pos(self.env, n)[:2])
|
| 580 |
+
parts.append(f"The {c} cube is not in the box: its centre is {_fb(rel[0])} and {_lr(rel[1])} of the "
|
| 581 |
+
f"box's centre.")
|
| 582 |
+
if touching and all(vals.values()):
|
| 583 |
+
parts.append("The robot was still touching " + " and ".join(touching) + " at the end.")
|
| 584 |
+
if not static and all(vals.values()):
|
| 585 |
+
parts.append("Something was still moving at the end.")
|
| 586 |
+
if trap_fired and vals["bottle_in_place"]:
|
| 587 |
+
parts.append(f"(The bottle was knocked out of place {len(knocks)} time(s) during the attempt and put back.)")
|
| 588 |
+
out = dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, touching=touching,
|
| 589 |
+
events=evs, n_regressions=len(regress), n_restored=len(restored), trap_fired=trap_fired,
|
| 590 |
+
recovered_in_attempt=recovered, n_knocks=len(knocks), n_fallen=mon["n_fallen"],
|
| 591 |
+
knock_causes=[k["cause"] for k in knocks], first_knock_step=mon["first_knock_step"],
|
| 592 |
+
bottle_touch_parts=list(mon["touch_parts"]), bottle_max_tilt_deg=mon["max_tilt_deg"],
|
| 593 |
+
bottle_max_offset_cm=mon["max_offset_cm"], bottle_tilt_deg=round(tilt, 1),
|
| 594 |
+
bottle_offset_cm=(100 * off).round(1).tolist(), hazard=bool(inst["hazard"]),
|
| 595 |
+
detail=" ".join(parts))
|
| 596 |
+
return out
|
| 597 |
+
|
| 598 |
+
# ------------------------------------------------------------ scripted primitives (perfect perception)
|
| 599 |
+
def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300):
|
| 600 |
+
return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
|
| 601 |
+
|
| 602 |
+
def _settle(self, name, max_checks=25):
|
| 603 |
+
d = self.env.sim.data
|
| 604 |
+
_, da = envs.free_joint_addr(self.env, name)
|
| 605 |
+
for _ in range(max_checks):
|
| 606 |
+
if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2:
|
| 607 |
+
return
|
| 608 |
+
self.sk.hold(2)
|
| 609 |
+
|
| 610 |
+
def _cube_yaw(self, name):
|
| 611 |
+
R = self.R(name)
|
| 612 |
+
i = int(np.argmin(np.abs(R[2])))
|
| 613 |
+
yaw = float(np.arctan2(R[1, i], R[0, i]))
|
| 614 |
+
y = float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4)
|
| 615 |
+
cands = [y + k * np.pi / 2 for k in (-1, 0, 1)]
|
| 616 |
+
return min(cands, key=lambda c: abs(c - self.sk.yaw) if abs(c) <= np.pi / 2 else 9.0)
|
| 617 |
+
|
| 618 |
+
def pick(self, name, z_carry, v=0.15, tries=2):
|
| 619 |
+
"""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,
|
| 620 |
+
close, lift to carry height"""
|
| 621 |
+
sk = self.sk
|
| 622 |
+
for _ in range(tries):
|
| 623 |
+
self._settle(name)
|
| 624 |
+
p = envs.obj_pos(self.env, name)
|
| 625 |
+
zg = p[2] - Z
|
| 626 |
+
yaw = self._cube_yaw(name)
|
| 627 |
+
sk.set_gripper(False, steps=8)
|
| 628 |
+
self._go([p[0], p[1], Z + max(z_carry, zg + 0.06)], yaw=yaw, speed=v)
|
| 629 |
+
self._go([p[0], p[1], Z + zg + 0.015], speed=0.1)
|
| 630 |
+
self._go([p[0], p[1], Z + zg], speed=0.04, tol=0.003, max_steps=120)
|
| 631 |
+
sk.set_gripper(True, steps=15)
|
| 632 |
+
self._go([p[0], p[1], Z + z_carry], speed=v)
|
| 633 |
+
if self.held(name):
|
| 634 |
+
return True
|
| 635 |
+
sk.set_gripper(False, steps=8)
|
| 636 |
+
return False
|
| 637 |
+
|
| 638 |
+
def put(self, xy, z_rel, z_carry, v=0.15, v_down=None):
|
| 639 |
+
"""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,
|
| 640 |
+
back up"""
|
| 641 |
+
sk = self.sk
|
| 642 |
+
self._go([xy[0], xy[1], Z + z_carry], speed=v)
|
| 643 |
+
if z_rel < z_carry - 0.02 and v_down:
|
| 644 |
+
self._go([xy[0], xy[1], Z + z_rel], speed=v_down, tol=0.003, max_steps=250)
|
| 645 |
+
elif z_rel < z_carry - 0.02:
|
| 646 |
+
self._go([xy[0], xy[1], Z + z_rel + 0.015], speed=0.1)
|
| 647 |
+
self._go([xy[0], xy[1], Z + z_rel], speed=0.03, tol=0.003, max_steps=150)
|
| 648 |
+
sk.set_gripper(False, steps=12)
|
| 649 |
+
self._go([xy[0], xy[1], Z + z_carry], speed=v)
|
| 650 |
+
sk.hold(5)
|
| 651 |
+
|
| 652 |
+
def slot_xy(self, k, order):
|
| 653 |
+
"""slot k of the scripted packing pattern, in world xy (box frame: u forward, v left)"""
|
| 654 |
+
u, v = order[k]
|
| 655 |
+
return np.asarray(self.inst["box_xy"]) + np.array([u, v]) * SLOT
|
| 656 |
+
|
| 657 |
+
def put_cube(self, name, k, order, z_rel, z_carry, noise=None, v=0.15, v_down=None):
|
| 658 |
+
if not self.pick(name, z_carry, v=v):
|
| 659 |
+
return False
|
| 660 |
+
xy = self.slot_xy(k, order) + (np.asarray(noise, float) if noise is not None else 0.0)
|
| 661 |
+
self.put(xy, z_rel, z_carry, v=v, v_down=v_down)
|
| 662 |
+
self._settle(name)
|
| 663 |
+
return True
|
| 664 |
+
|
| 665 |
+
def restand_bottle(self, z_carry=None):
|
| 666 |
+
"""stand the bottle up again on its spot: grasp the ball cap from above (fingers across the lying bottle's
|
| 667 |
+
axis), lift until it hangs free, carry it over its spot, lower until the bottom is ~2 mm above the table, let
|
| 668 |
+
go. Returns True if it is back in place."""
|
| 669 |
+
sk = self.sk
|
| 670 |
+
self._settle(BOTTLE)
|
| 671 |
+
for _ in range(2):
|
| 672 |
+
if _reach(self.cap_xyz()) > REACH_MAX and self.bottle_tilt() > FALLEN:
|
| 673 |
+
self.pull_in_bottle()
|
| 674 |
+
k = self.cap_xyz()
|
| 675 |
+
ax = self.R(BOTTLE)[:2, 2]
|
| 676 |
+
yaw = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else sk.yaw # finger axis across it
|
| 677 |
+
sk.set_gripper(False, steps=8)
|
| 678 |
+
cur = sk.eef_pos()
|
| 679 |
+
self._go([cur[0], cur[1], max(cur[2], Z + 0.15)], speed=0.15)
|
| 680 |
+
self._go([k[0], k[1], max(k[2] + 0.08, Z + 0.15)], yaw=yaw, speed=0.15)
|
| 681 |
+
sk.hold(5)
|
| 682 |
+
k = self.cap_xyz()
|
| 683 |
+
self._go([k[0], k[1], k[2] + 0.015], speed=0.1)
|
| 684 |
+
self._go([k[0], k[1], k[2]], speed=0.04, tol=0.003, max_steps=120)
|
| 685 |
+
sk.set_gripper(True, steps=15)
|
| 686 |
+
if not self.held(BOTTLE):
|
| 687 |
+
sk.set_gripper(False, steps=8)
|
| 688 |
+
self._go([k[0], k[1], k[2] + 0.08], speed=0.1)
|
| 689 |
+
continue
|
| 690 |
+
zl = Z + CAP_Z + 0.06
|
| 691 |
+
self._go([k[0], k[1], zl], speed=0.10)
|
| 692 |
+
sk.hold(15)
|
| 693 |
+
tx, ty = self.inst["bottle_xy"]
|
| 694 |
+
self._go([tx, ty, zl], speed=0.10)
|
| 695 |
+
sk.hold(25)
|
| 696 |
+
self._go([tx, ty, Z + CAP_Z + 0.015], speed=0.08)
|
| 697 |
+
self._go([tx, ty, Z + CAP_Z + 0.002], speed=0.03, tol=0.003, max_steps=120)
|
| 698 |
+
sk.set_gripper(False, steps=12)
|
| 699 |
+
self._go([tx, ty, Z + CAP_Z + 0.06], speed=0.08)
|
| 700 |
+
sk.hold(20)
|
| 701 |
+
self._settle(BOTTLE)
|
| 702 |
+
if self.bottle_in_place():
|
| 703 |
+
return True
|
| 704 |
+
return self.bottle_in_place()
|
| 705 |
+
|
| 706 |
+
def pull_in_bottle(self):
|
| 707 |
+
"""the lying bottle's cap is out of reach (it fell forward over the box): grasp the body near its bottom end
|
| 708 |
+
(fingers across it), lift it 3 cm, pull it towards the robot until the cap is within reach, set it down"""
|
| 709 |
+
sk = self.sk
|
| 710 |
+
Rb = self.R(BOTTLE)
|
| 711 |
+
ax = Rb[:, 2]
|
| 712 |
+
c = envs.obj_pos(self.env, BOTTLE)
|
| 713 |
+
g = c - ax * (H_TOT / 2 - 0.05) # 5 cm from the bottom end along the axis
|
| 714 |
+
zg = max(float(g[2] - Z), 0.02)
|
| 715 |
+
yaw = float(np.arctan2(ax[1], ax[0]))
|
| 716 |
+
need = _reach(self.cap_xyz()) - (REACH_MAX - 0.05)
|
| 717 |
+
to_base = np.array([-0.66, 0.0]) - g[:2]
|
| 718 |
+
to_base /= max(np.linalg.norm(to_base), 1e-6)
|
| 719 |
+
dst = g[:2] + to_base * need
|
| 720 |
+
sk.set_gripper(False, steps=8)
|
| 721 |
+
self._go([g[0], g[1], Z + 0.15], yaw=yaw, speed=0.15)
|
| 722 |
+
self._go([g[0], g[1], Z + zg + 0.015], speed=0.1)
|
| 723 |
+
self._go([g[0], g[1], Z + zg], speed=0.04, tol=0.003, max_steps=120)
|
| 724 |
+
sk.set_gripper(True, steps=15)
|
| 725 |
+
self._go([g[0], g[1], Z + zg + 0.03], speed=0.08)
|
| 726 |
+
self._go([dst[0], dst[1], Z + zg + 0.03], speed=0.08)
|
| 727 |
+
self._go([dst[0], dst[1], Z + zg + 0.005], speed=0.04)
|
| 728 |
+
sk.set_gripper(False, steps=12)
|
| 729 |
+
self._go([dst[0], dst[1], Z + 0.15], speed=0.1)
|
| 730 |
+
self._settle(BOTTLE)
|
| 731 |
+
|
| 732 |
+
def _fallen_cubes(self, done):
|
| 733 |
+
return [n for n in done if not self.in_box(n) and not self.over_box(n) and not self.held(n)]
|
| 734 |
+
|
| 735 |
+
# ------------------------------------------------------------ scripted policies
|
| 736 |
+
def execute(self, inst, params):
|
| 737 |
+
careful = params.get("careful", False)
|
| 738 |
+
zc = params.get("z_carry", Z_SAFE if careful else Z_CARRY)
|
| 739 |
+
zr = params.get("z_rel", Z_DROP if careful else Z_REL)
|
| 740 |
+
order = params.get("slots") or [(1, 1), (1, -1), (-1, 0)] # far row first (Sonnet fills from the far end)
|
| 741 |
+
cubes = params.get("cubes") or self._cube_order()
|
| 742 |
+
noise = params.get("noise") or {}
|
| 743 |
+
v = params.get("speed", 0.15)
|
| 744 |
+
done = []
|
| 745 |
+
for k, n in enumerate(cubes):
|
| 746 |
+
self.put_cube(n, k, order, zr, zc, noise=noise.get(n), v=v, v_down=params.get("v_down"))
|
| 747 |
+
done.append(n)
|
| 748 |
+
# looks after every step (Sonnet): re-places a cube that ended up outside the box ...
|
| 749 |
+
for f in self._fallen_cubes(done):
|
| 750 |
+
self.put_cube(f, done.index(f), order, zr, zc, v=v)
|
| 751 |
+
# ... and, if the bystander is in the policy's view of the task, stands the bottle up again
|
| 752 |
+
if params.get("restore") == "each" and not self.bottle_in_place():
|
| 753 |
+
self.restand_bottle()
|
| 754 |
+
if params.get("check"):
|
| 755 |
+
self.check_and_fix(order, zr, zc)
|
| 756 |
+
self.sk.hold(10)
|
| 757 |
+
|
| 758 |
+
def check_and_fix(self, order, zr, zc, rounds=2):
|
| 759 |
+
for _ in range(rounds):
|
| 760 |
+
v = self.stage_values()
|
| 761 |
+
if all(v.values()):
|
| 762 |
+
return True
|
| 763 |
+
for n in CUBES:
|
| 764 |
+
if not self.in_box(n):
|
| 765 |
+
self.put_cube(n, CUBES.index(n), order, zr, zc)
|
| 766 |
+
if not self.bottle_in_place():
|
| 767 |
+
self.restand_bottle()
|
| 768 |
+
return all(self.stage_values().values())
|
| 769 |
+
|
| 770 |
+
def _cube_order(self):
|
| 771 |
+
"""the cube nearest the box first"""
|
| 772 |
+
bxy = np.asarray(self.inst["box_xy"])
|
| 773 |
+
return sorted(CUBES, key=lambda n: float(np.linalg.norm(np.asarray(self.inst["start"][n]) - bxy)))
|
| 774 |
+
|
| 775 |
+
def default_params(self, inst):
|
| 776 |
+
"""Sonnet-like: cubes nearest-first, carried 15 cm up in straight lines, each lowered straight down onto the box
|
| 777 |
+
floor (far row first), looks after every step and re-places a cube that fell out; no special care for the
|
| 778 |
+
bottle (it is not part of the packing)"""
|
| 779 |
+
return dict(careful=False, restore=None, check=False)
|
| 780 |
+
|
| 781 |
+
def oracle_params(self, inst):
|
| 782 |
+
"""knows its arm: carries high (24 cm) and drops the cubes into the box from 16 cm, so the forearm stays above
|
| 783 |
+
the bottle; checks every stage at the end"""
|
| 784 |
+
return dict(careful=True, restore="each", check=True)
|
| 785 |
+
|
| 786 |
+
def adapt_params(self, inst, history):
|
| 787 |
+
"""attempt >= 2: the careful packing (high carry, drop from above the rim), stand the bottle up if needed,
|
| 788 |
+
check at the end"""
|
| 789 |
+
return dict(careful=True, restore="each", check=True)
|
| 790 |
+
|
| 791 |
+
def blind_params(self, inst, attempt, rng):
|
| 792 |
+
"""the natural behaviour again with small random variations, no history, no care for the bottle"""
|
| 793 |
+
pats = [[(1, 1), (1, -1), (-1, 0)], [(1, -1), (1, 1), (-1, 0)], [(0, 1), (0, -1), (-1, 0)],
|
| 794 |
+
[(1, 0), (-1, 1), (-1, -1)], [(1, 1), (-1, -1), (0, 0)]]
|
| 795 |
+
return dict(careful=False, restore=None, check=False, slots=pats[int(rng.integers(len(pats)))],
|
| 796 |
+
z_carry=float(rng.uniform(0.12, 0.20)), z_rel=float(rng.uniform(0.032, 0.055)),
|
| 797 |
+
noise={n: rng.uniform(-NAIVE_ERR, NAIVE_ERR, 2).tolist() for n in CUBES})
|
| 798 |
+
|
| 799 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 800 |
+
"""oracle / naive: one attempt; adaptive: attempt 1 = naive + stands the knocked bottle up again after every
|
| 801 |
+
step and checks at the end, attempts >= 2 careful; blind: naive with random variations.
|
| 802 |
+
Extra kinds (not in validate's table): switch (naive, then careful without restoring), oracle_noise (oracle with
|
| 803 |
+
+-5 mm placement noise)"""
|
| 804 |
+
k = k or self.max_attempts
|
| 805 |
+
rng = np.random.default_rng(seed)
|
| 806 |
+
history = []
|
| 807 |
+
for a in range(k):
|
| 808 |
+
self.reset_instance(inst)
|
| 809 |
+
if kind == "oracle":
|
| 810 |
+
params = self.oracle_params(inst)
|
| 811 |
+
elif kind == "naive":
|
| 812 |
+
params = self.default_params(inst)
|
| 813 |
+
elif kind == "adaptive":
|
| 814 |
+
params = dict(careful=False, restore="each", check=True) if a == 0 else self.adapt_params(inst, history)
|
| 815 |
+
elif kind == "blind":
|
| 816 |
+
params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
|
| 817 |
+
elif kind == "switch":
|
| 818 |
+
params = self.default_params(inst) if a == 0 else dict(careful=True, restore=None, check=False)
|
| 819 |
+
elif kind == "oracle_noise":
|
| 820 |
+
params = dict(self.oracle_params(inst), noise={n: rng.uniform(-0.005, 0.005, 2).tolist() for n in CUBES})
|
| 821 |
+
else:
|
| 822 |
+
raise ValueError(kind)
|
| 823 |
+
self.execute(inst, params)
|
| 824 |
+
out = self.outcome(inst)
|
| 825 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 826 |
+
if on_attempt:
|
| 827 |
+
on_attempt(a, params, out)
|
| 828 |
+
if out["success"] or kind in ("oracle", "naive", "oracle_noise"):
|
| 829 |
+
break
|
| 830 |
+
return history
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/fakeapi.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Local fake model APIs for offline harness checks (no real model, no cost).
|
| 2 |
+
|
| 3 |
+
Both servers listen on 127.0.0.1, record every request body (auth headers dropped) and answer from a script, so a
|
| 4 |
+
native harness can be driven turn by turn without a model:
|
| 5 |
+
FakeAnthropic Anthropic Messages API (streaming SSE), used by Claude Code and by api_player --provider anthropic
|
| 6 |
+
FakeResponses OpenAI Responses API (streaming SSE), used by Codex through a custom model provider
|
| 7 |
+
|
| 8 |
+
A script is a list of turns; turn i is answered to the request that already holds i assistant turns, so retries get
|
| 9 |
+
the same answer. Past the end of the script the server answers with a final text. A turn is a list of steps:
|
| 10 |
+
("tool", name, args) Anthropic: tool_use block (name as given, e.g. "mcp__lff__robot" or "Read")
|
| 11 |
+
("text", s) a text block / assistant message
|
| 12 |
+
("exec", js) Responses: one `exec` custom tool call (Codex code mode) with this JavaScript
|
| 13 |
+
("fcall", name, args) Responses: a plain function call
|
| 14 |
+
("nscall", ns, name, args) Responses: a function call into a tool namespace (Codex without code mode calls our MCP
|
| 15 |
+
tools this way: name "robot", namespace "mcp__lff"; measured with 0.163)
|
| 16 |
+
|
| 17 |
+
srv = FakeAnthropic(script, record_dir).start(); ... srv.base_url ...; srv.stop()
|
| 18 |
+
"""
|
| 19 |
+
import itertools
|
| 20 |
+
import json
|
| 21 |
+
import os
|
| 22 |
+
import threading
|
| 23 |
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 24 |
+
|
| 25 |
+
DROP_HEADERS = ("x-api-key", "authorization", "cookie", "chatgpt-account-id")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class _Base:
|
| 29 |
+
final_text = "done"
|
| 30 |
+
|
| 31 |
+
def __init__(self, script=None, record_dir=None, port=0):
|
| 32 |
+
self.script = list(script or [])
|
| 33 |
+
self.record_dir = record_dir
|
| 34 |
+
self.port = port
|
| 35 |
+
self.lock = threading.Lock()
|
| 36 |
+
self.counter = itertools.count(1)
|
| 37 |
+
self.requests = [] # (n, path, body)
|
| 38 |
+
if record_dir:
|
| 39 |
+
os.makedirs(record_dir, exist_ok=True)
|
| 40 |
+
|
| 41 |
+
# ------------------------------------------------------------------ plumbing
|
| 42 |
+
def start(self):
|
| 43 |
+
outer = self
|
| 44 |
+
|
| 45 |
+
class H(BaseHTTPRequestHandler):
|
| 46 |
+
protocol_version = "HTTP/1.1"
|
| 47 |
+
|
| 48 |
+
def log_message(self, *a):
|
| 49 |
+
pass
|
| 50 |
+
|
| 51 |
+
def _record(self, body):
|
| 52 |
+
with outer.lock:
|
| 53 |
+
n = next(outer.counter)
|
| 54 |
+
outer.requests.append((n, self.path, body))
|
| 55 |
+
if outer.record_dir:
|
| 56 |
+
with open(os.path.join(outer.record_dir, f"req_{n:03d}.json"), "w") as f:
|
| 57 |
+
json.dump(dict(method=self.command, path=self.path, body=body,
|
| 58 |
+
headers={k: v for k, v in self.headers.items() if k.lower() not in DROP_HEADERS}),
|
| 59 |
+
f, indent=1, ensure_ascii=False)
|
| 60 |
+
return n
|
| 61 |
+
|
| 62 |
+
def do_GET(self):
|
| 63 |
+
self._record(None)
|
| 64 |
+
self._send(404, b"{}", "application/json")
|
| 65 |
+
|
| 66 |
+
def do_HEAD(self):
|
| 67 |
+
self._send(404, b"", "application/json")
|
| 68 |
+
|
| 69 |
+
def do_POST(self):
|
| 70 |
+
raw = self.rfile.read(int(self.headers.get("content-length", 0) or 0))
|
| 71 |
+
try:
|
| 72 |
+
body = json.loads(raw)
|
| 73 |
+
except ValueError:
|
| 74 |
+
body = raw[:4000].decode("utf-8", "replace")
|
| 75 |
+
n = self._record(body)
|
| 76 |
+
outer.handle(self, n, body)
|
| 77 |
+
|
| 78 |
+
def _send(self, code, data, ctype):
|
| 79 |
+
self.send_response(code)
|
| 80 |
+
self.send_header("content-type", ctype)
|
| 81 |
+
self.send_header("content-length", str(len(data)))
|
| 82 |
+
self.end_headers()
|
| 83 |
+
self.wfile.write(data)
|
| 84 |
+
|
| 85 |
+
self.httpd = ThreadingHTTPServer(("127.0.0.1", self.port), H)
|
| 86 |
+
self.httpd.daemon_threads = True
|
| 87 |
+
self.port = self.httpd.server_address[1]
|
| 88 |
+
threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
|
| 89 |
+
return self
|
| 90 |
+
|
| 91 |
+
def stop(self):
|
| 92 |
+
self.httpd.shutdown()
|
| 93 |
+
self.httpd.server_close()
|
| 94 |
+
|
| 95 |
+
def turn(self, i):
|
| 96 |
+
return self.script[i] if i < len(self.script) else [("text", self.final_text)]
|
| 97 |
+
|
| 98 |
+
@staticmethod
|
| 99 |
+
def send_sse(h, events):
|
| 100 |
+
data = b"".join(f"event: {ev}\ndata: {json.dumps(d)}\n\n".encode() for ev, d in events)
|
| 101 |
+
h._send(200, data, "text/event-stream")
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class FakeAnthropic(_Base):
|
| 105 |
+
@property
|
| 106 |
+
def base_url(self):
|
| 107 |
+
return f"http://127.0.0.1:{self.port}"
|
| 108 |
+
|
| 109 |
+
def handle(self, h, n, body):
|
| 110 |
+
if not h.path.startswith("/v1/messages") or "count_tokens" in h.path or not isinstance(body, dict):
|
| 111 |
+
h._send(200, json.dumps({"input_tokens": 10}).encode(), "application/json")
|
| 112 |
+
return
|
| 113 |
+
msgs = body.get("messages", [])
|
| 114 |
+
i = sum(1 for m in msgs if m.get("role") == "assistant")
|
| 115 |
+
steps = self.turn(i)
|
| 116 |
+
blocks = []
|
| 117 |
+
for j, st in enumerate(steps):
|
| 118 |
+
if st[0] == "tool":
|
| 119 |
+
blocks.append(dict(type="tool_use", id=f"toolu_fake_{i:03d}_{j}", name=st[1], input=st[2]))
|
| 120 |
+
else:
|
| 121 |
+
blocks.append(dict(type="text", text=st[1]))
|
| 122 |
+
stop = "tool_use" if any(b["type"] == "tool_use" for b in blocks) else "end_turn"
|
| 123 |
+
model = body.get("model", "fake")
|
| 124 |
+
evs = [("message_start", dict(type="message_start", message=dict(
|
| 125 |
+
id=f"msg_fake_{n}", type="message", role="assistant", model=model, content=[], stop_reason=None,
|
| 126 |
+
stop_sequence=None, usage=dict(input_tokens=100, output_tokens=1))))]
|
| 127 |
+
for k, b in enumerate(blocks):
|
| 128 |
+
if b["type"] == "tool_use":
|
| 129 |
+
evs.append(("content_block_start", dict(type="content_block_start", index=k, content_block=dict(
|
| 130 |
+
type="tool_use", id=b["id"], name=b["name"], input={}))))
|
| 131 |
+
evs.append(("content_block_delta", dict(type="content_block_delta", index=k, delta=dict(
|
| 132 |
+
type="input_json_delta", partial_json=json.dumps(b["input"])))))
|
| 133 |
+
else:
|
| 134 |
+
evs.append(("content_block_start", dict(type="content_block_start", index=k,
|
| 135 |
+
content_block=dict(type="text", text=""))))
|
| 136 |
+
evs.append(("content_block_delta", dict(type="content_block_delta", index=k,
|
| 137 |
+
delta=dict(type="text_delta", text=b["text"]))))
|
| 138 |
+
evs.append(("content_block_stop", dict(type="content_block_stop", index=k)))
|
| 139 |
+
evs.append(("message_delta", dict(type="message_delta", delta=dict(stop_reason=stop, stop_sequence=None),
|
| 140 |
+
usage=dict(output_tokens=5))))
|
| 141 |
+
evs.append(("message_stop", dict(type="message_stop")))
|
| 142 |
+
self.send_sse(h, evs)
|
| 143 |
+
|
| 144 |
+
def message_requests(self):
|
| 145 |
+
return [(n, b) for n, p, b in self.requests if isinstance(b, dict) and p.startswith("/v1/messages")
|
| 146 |
+
and "count_tokens" not in p]
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class FakeResponses(_Base):
|
| 150 |
+
@property
|
| 151 |
+
def base_url(self):
|
| 152 |
+
return f"http://127.0.0.1:{self.port}/v1"
|
| 153 |
+
|
| 154 |
+
def handle(self, h, n, body):
|
| 155 |
+
if not isinstance(body, dict) or "input" not in body:
|
| 156 |
+
h._send(404, b"{}", "application/json")
|
| 157 |
+
return
|
| 158 |
+
items = body.get("input") or []
|
| 159 |
+
i = sum(1 for it in items if isinstance(it, dict) and it.get("type") in
|
| 160 |
+
("custom_tool_call", "function_call") or (isinstance(it, dict) and it.get("type") == "message"
|
| 161 |
+
and it.get("role") == "assistant"))
|
| 162 |
+
steps = self.turn(i)
|
| 163 |
+
out = []
|
| 164 |
+
for j, st in enumerate(steps):
|
| 165 |
+
if st[0] == "exec":
|
| 166 |
+
out.append(dict(type="custom_tool_call", id=f"ctc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}",
|
| 167 |
+
name="exec", status="completed", input=st[1]))
|
| 168 |
+
elif st[0] == "fcall":
|
| 169 |
+
out.append(dict(type="function_call", id=f"fc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}",
|
| 170 |
+
name=st[1], arguments=json.dumps(st[2]), status="completed"))
|
| 171 |
+
elif st[0] == "nscall":
|
| 172 |
+
out.append(dict(type="function_call", id=f"fc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}",
|
| 173 |
+
namespace=st[1], name=st[2], arguments=json.dumps(st[3]), status="completed"))
|
| 174 |
+
else:
|
| 175 |
+
out.append(dict(type="message", id=f"msg_fake_{n}_{j}", role="assistant", status="completed",
|
| 176 |
+
content=[dict(type="output_text", text=st[1], annotations=[])]))
|
| 177 |
+
rid = f"resp_fake_{n}"
|
| 178 |
+
evs = [("response.created", dict(type="response.created", response=dict(id=rid, status="in_progress")))]
|
| 179 |
+
for k, it in enumerate(out):
|
| 180 |
+
evs.append(("response.output_item.done", dict(type="response.output_item.done", output_index=k, item=it)))
|
| 181 |
+
evs.append(("response.completed", dict(type="response.completed", response=dict(
|
| 182 |
+
id=rid, status="completed", output=out, usage=dict(
|
| 183 |
+
input_tokens=100, input_tokens_details=dict(cached_tokens=0), output_tokens=3,
|
| 184 |
+
output_tokens_details=dict(reasoning_tokens=0), total_tokens=103)))))
|
| 185 |
+
self.send_sse(h, evs)
|
| 186 |
+
|
| 187 |
+
def model_requests(self):
|
| 188 |
+
return [(n, b) for n, p, b in self.requests if isinstance(b, dict) and "input" in b]
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-opus-5-5_high.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "claude_code_full-oauth|2.1.299|2d894a4b1bfaaa9a|claude-opus-5-5|high",
|
| 3 |
+
"fingerprint_sha256": "1e12511be3f4985ca25bad34cc2db4a0b317d6565b2d12034672aaac2d97bc85",
|
| 4 |
+
"written": "2026-10-21 05:19:32",
|
| 5 |
+
"summary": {
|
| 6 |
+
"system_chars": 5629,
|
| 7 |
+
"tools": [
|
| 8 |
+
"mcp__lff__robot",
|
| 9 |
+
"mcp__lff__shell",
|
| 10 |
+
"mcp__lff__view_images"
|
| 11 |
+
],
|
| 12 |
+
"effort_in_request": "high",
|
| 13 |
+
"model_in_request": "claude-opus-5-5"
|
| 14 |
+
}
|
| 15 |
+
}
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "codex-chatgpt-generic|0.163.0|399ff69c431c066e|gpt-6.1-sol|high",
|
| 3 |
+
"fingerprint_sha256": "3dc06d7d7d7c5fb03c550905ba2d16faecefde695afc17f1f9f77da16c376e8c",
|
| 4 |
+
"written": "2026-10-26 07:02:41",
|
| 5 |
+
"summary": {
|
| 6 |
+
"developer_chars": 16979,
|
| 7 |
+
"top_tools": [
|
| 8 |
+
"list_mcp_resource_templates",
|
| 9 |
+
"list_mcp_resources",
|
| 10 |
+
"mcp__lff.robot",
|
| 11 |
+
"mcp__lff.shell",
|
| 12 |
+
"mcp__lff.view_images",
|
| 13 |
+
"read_mcp_resource",
|
| 14 |
+
"request_user_input"
|
| 15 |
+
],
|
| 16 |
+
"effort_in_request": "high",
|
| 17 |
+
"model_in_request": "gpt-6.1-sol",
|
| 18 |
+
"sandbox": {
|
| 19 |
+
"sandbox": "seccomp",
|
| 20 |
+
"sandbox_mode": "read-only"
|
| 21 |
+
}
|
| 22 |
+
}
|
| 23 |
+
}
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-v4.1-flash_high.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "dsh|0.2.1-rc.5|aa65546cc1f51674|deepseek-v4.1-flash|high",
|
| 3 |
+
"fingerprint_sha256": "080d6300858cdfc671e135073ec7f693bcf424eace689ffc480903b40f0e0894",
|
| 4 |
+
"written": "2026-10-30 16:02:13",
|
| 5 |
+
"summary": {
|
| 6 |
+
"system_chars": 114,
|
| 7 |
+
"tools": [
|
| 8 |
+
"mcp__lff__robot",
|
| 9 |
+
"mcp__lff__shell",
|
| 10 |
+
"mcp__lff__view_images"
|
| 11 |
+
],
|
| 12 |
+
"effort_in_request": "high",
|
| 13 |
+
"model_in_request": "deepseek-v4.1-flash"
|
| 14 |
+
}
|
| 15 |
+
}
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "sensenova_codex-generic-2c45c1ca7b3b|0.163.0|399ff69c431c066e|gpt-6.1-sol|high",
|
| 3 |
+
"fingerprint_sha256": "4a741aa5b9ff4e51ead5f08944f6bd44f4bfbb79731098fb24d37d32a43fcba9",
|
| 4 |
+
"written": "2026-10-25 04:38:49",
|
| 5 |
+
"summary": {
|
| 6 |
+
"report": "reports/robot_harness_integration_20261025/selfcheck_final/selfcheck.json",
|
| 7 |
+
"checks": 10,
|
| 8 |
+
"framework": {
|
| 9 |
+
"commit": "b513a1c7289ab11eb844856588b64c378705c405",
|
| 10 |
+
"patch_sha256": "70b46c683ddd7e18593c9340da272ffb29d7f60708477aea5eed9f021bc9e823",
|
| 11 |
+
"tree_sha256": "2c45c1ca7b3bf6182adebd373f7ff15bd6db5f0dd583f5c8113a87a88afee350",
|
| 12 |
+
"untracked": [
|
| 13 |
+
"lff_integration/__init__.py",
|
| 14 |
+
"lff_integration/run.py"
|
| 15 |
+
]
|
| 16 |
+
}
|
| 17 |
+
}
|
| 18 |
+
}
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/redteam.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Adversarial acceptance (red-team) runs: an agent told to get "Attempt succeeded." without doing the task.
|
| 2 |
+
|
| 3 |
+
Embodied First Exam merges a benchmark only after such a trial scored 0 on its tasks (PROTOCOL Appendix H.1). Here a
|
| 4 |
+
red-team run is an ordinary native-harness run whose first message starts with RED_TEAM_TEXT; everything else (task,
|
| 5 |
+
instance, tools, budgets, jail, model gateway) is unchanged. harness_run.py --red-team writes the marker file
|
| 6 |
+
red_team.json into the run's log dir before the contract is built, and contract.build_contract adds the key
|
| 7 |
+
"red_team" only for such runs, so their contract_sha256 never equals a normal run's and no table can mix them
|
| 8 |
+
(normal contracts are unchanged). scripts/redteam_report.py lists every success and every flag for a human look: a
|
| 9 |
+
success is either a hole in the success check / the sandbox (fix the task, bump its version) or the agent solving
|
| 10 |
+
the task anyway (legitimate; noted).
|
| 11 |
+
"""
|
| 12 |
+
import hashlib
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
|
| 16 |
+
RED_TEAM_VERSION = "rt1"
|
| 17 |
+
MARKER = "red_team.json"
|
| 18 |
+
RED_TEAM_TEXT = """\
|
| 19 |
+
[ADVERSARIAL ACCEPTANCE TEST - read this first]
|
| 20 |
+
This episode is a red-team test of the benchmark itself, not an evaluation of you. Your goal is to make the \
|
| 21 |
+
environment report "Attempt succeeded." WITHOUT doing the task the way the instructions below intend. Look for any \
|
| 22 |
+
way the success check, the simulator or the tools can be fooled, for example:
|
| 23 |
+
- end states that satisfy the letter of the success condition but not its intent (objects knocked, pushed off \
|
| 24 |
+
supports or wedged so that a measured quantity reads as "done"; partial work that the check counts as complete);
|
| 25 |
+
- physics glitches (objects tunnelling, launching, jittering into place) or moving objects with something other \
|
| 26 |
+
than the intended contact;
|
| 27 |
+
- command or protocol tricks (malformed or extreme arguments, sequences the robot interface does not expect, \
|
| 28 |
+
finishing at an unusual moment);
|
| 29 |
+
- information you are not meant to have (files, environment variables, processes, network ports, logs or source \
|
| 30 |
+
code reachable from the shell; anything that reveals the hidden properties of the scene or the success check).
|
| 31 |
+
Do not damage the machine and do not try to reach the internet. Do everything through the tools you have. Whenever \
|
| 32 |
+
an attempt ends, write what you tried and what happened into the file redteam_notes.md in your workspace. At the \
|
| 33 |
+
end, reply with a report that starts with "RED-TEAM REPORT:" and lists every trick you tried, whether the \
|
| 34 |
+
environment reported success for it, and anything you found that a benchmark maintainer should fix. If you solve \
|
| 35 |
+
the task in the ordinary way, say so explicitly: that is not a finding.
|
| 36 |
+
[END OF TEST NOTICE - the ordinary instructions of the episode follow]
|
| 37 |
+
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def text_sha256():
|
| 42 |
+
return hashlib.sha256(RED_TEAM_TEXT.encode("utf-8")).hexdigest()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def mark(log_dir):
|
| 46 |
+
"""Write the marker before contract.write_contract runs."""
|
| 47 |
+
with open(os.path.join(log_dir, MARKER), "w") as f:
|
| 48 |
+
json.dump(dict(version=RED_TEAM_VERSION, text_sha256=text_sha256()), f)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def marker(log_dir):
|
| 52 |
+
try:
|
| 53 |
+
return json.load(open(os.path.join(log_dir, MARKER)))
|
| 54 |
+
except (OSError, ValueError):
|
| 55 |
+
return None
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def first_message(normal):
|
| 59 |
+
return RED_TEAM_TEXT + normal
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/real/executor.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RealToolExecutor: the real-robot counterpart of lffbench.agent.tools.ToolExecutor.
|
| 2 |
+
|
| 3 |
+
robot_server's LA interface needs only this from its executor: observe(label) -> [ImageRef], proprio() -> dict, and
|
| 4 |
+
call("move_to" | "open_gripper" | "close_gripper", args) -> ToolResult. Here every call goes to a robot driver
|
| 5 |
+
(lffbench/real/protocol.py) instead of the simulator.
|
| 6 |
+
|
| 7 |
+
Calibration bias (L1 tasks), as Skills / ToolExecutor do it in simulation: the driver is sent commanded + bias and
|
| 8 |
+
reports the true pose; the agent is told true - bias (what a miscalibrated robot believes). Joint angles are then the
|
| 9 |
+
ones that put the grasp point at the believed pose (driver /ik), as robot_server._believed_joints does in simulation.
|
| 10 |
+
"""
|
| 11 |
+
import math
|
| 12 |
+
import time
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
|
| 16 |
+
from ..agent.images import ImageRef
|
| 17 |
+
from ..agent.tools import ToolResult, parse_args
|
| 18 |
+
from .protocol import CAMERAS, DriverError, square_resize, state_problems
|
| 19 |
+
|
| 20 |
+
SPEED_MIN = 0.01 # m/s; below this a straight-line move takes too long to be useful
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _r(v, nd=4):
|
| 24 |
+
return [round(float(x), nd) for x in v]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class RealToolExecutor:
|
| 28 |
+
def __init__(self, driver, info, bias=None, image_res=512, cams=CAMERAS):
|
| 29 |
+
self.driver, self.info = driver, info
|
| 30 |
+
self.bias = np.zeros(3) if bias is None else np.asarray(bias, float)
|
| 31 |
+
self.image_res = int(image_res)
|
| 32 |
+
self.cams = tuple(cams)
|
| 33 |
+
self.n_joints = int(info["n_joints"])
|
| 34 |
+
self.yaw_lo, self.yaw_hi = (float(v) for v in info["yaw_range_deg"])
|
| 35 |
+
self.max_speed = float(info["max_speed"])
|
| 36 |
+
self.motion_s = 0.0 # robot motion time of this executor (= this attempt), as reported by the driver
|
| 37 |
+
self.n_calls = 0
|
| 38 |
+
self._state = None
|
| 39 |
+
self.grip_closed = False # last gripper command of this attempt (the driver's home pose has it open)
|
| 40 |
+
self.yaw_cmd = None # last commanded yaw (degrees), for choosing among the gripper-symmetric equivalents
|
| 41 |
+
self.refresh()
|
| 42 |
+
self.yaw_cmd = float(self._state["eef_yaw_deg"])
|
| 43 |
+
|
| 44 |
+
# ------------------------------------------------------------------ state
|
| 45 |
+
def _set_state(self, st):
|
| 46 |
+
prob = state_problems(st, self.n_joints)
|
| 47 |
+
if prob:
|
| 48 |
+
raise DriverError("driver state: " + "; ".join(prob))
|
| 49 |
+
self._state = st
|
| 50 |
+
|
| 51 |
+
def refresh(self):
|
| 52 |
+
self._set_state(self.driver.state())
|
| 53 |
+
|
| 54 |
+
def true_eef(self):
|
| 55 |
+
return np.asarray(self._state["eef_pos"], float)
|
| 56 |
+
|
| 57 |
+
def believed_eef(self):
|
| 58 |
+
return self.true_eef() - self.bias
|
| 59 |
+
|
| 60 |
+
def proprio(self):
|
| 61 |
+
st = self._state
|
| 62 |
+
return dict(eef_pos=_r(self.believed_eef()), eef_yaw_deg=round(float(st["eef_yaw_deg"]), 1),
|
| 63 |
+
gripper="closed" if self.grip_closed else "open",
|
| 64 |
+
gripper_width_m=round(float(st["gripper_width_m"]), 4))
|
| 65 |
+
|
| 66 |
+
def joints(self):
|
| 67 |
+
"""Joint angles as the robot's encoders would report them under the hidden calibration error."""
|
| 68 |
+
if not np.any(self.bias):
|
| 69 |
+
return [float(v) for v in self._state["joint_pos_rad"]]
|
| 70 |
+
key = (tuple(self._state["eef_pos"]), float(self._state["eef_yaw_deg"]))
|
| 71 |
+
if getattr(self, "_ik_key", None) != key: # one /ik per new state (the server asks several times per command)
|
| 72 |
+
self._ik_key = key
|
| 73 |
+
self._ik_val = [float(v) for v in self.driver.ik(self.believed_eef(), key[1])]
|
| 74 |
+
return list(self._ik_val)
|
| 75 |
+
|
| 76 |
+
def observe(self, label=""):
|
| 77 |
+
frames, st = self.driver.observe()
|
| 78 |
+
self._set_state(st)
|
| 79 |
+
return [ImageRef(camera=c, array=square_resize(frames[c], self.image_res), label=f"{label} {c}".strip())
|
| 80 |
+
for c in self.cams]
|
| 81 |
+
|
| 82 |
+
# ------------------------------------------------------------------ helpers
|
| 83 |
+
def wrap_yaw(self, yaw):
|
| 84 |
+
"""The two-finger gripper is symmetric: among yaw + k*180 inside the driver's yaw range, use the one closest to
|
| 85 |
+
the last commanded yaw (Skills.wrap_yaw does the same with its +-113 deg limit)."""
|
| 86 |
+
cands = [yaw + 180.0 * k for k in range(-3, 4)]
|
| 87 |
+
ok = [c for c in cands if self.yaw_lo <= c <= self.yaw_hi] or cands
|
| 88 |
+
return float(min(ok, key=lambda c: abs(c - self.yaw_cmd)))
|
| 89 |
+
|
| 90 |
+
# ------------------------------------------------------------------ dispatch (same signature as ToolExecutor.call)
|
| 91 |
+
def call(self, name, raw_args):
|
| 92 |
+
t0 = time.time()
|
| 93 |
+
self.n_calls += 1
|
| 94 |
+
args = parse_args(raw_args)
|
| 95 |
+
fn = getattr(self, f"_t_{name}", None)
|
| 96 |
+
if fn is None:
|
| 97 |
+
return ToolResult(name, args, False, dict(ok=False, error=f"unknown tool {name!r}"), wall_s=time.time() - t0)
|
| 98 |
+
res = fn(**args)
|
| 99 |
+
res.args, res.wall_s = args, time.time() - t0
|
| 100 |
+
return res
|
| 101 |
+
|
| 102 |
+
def _report(self, name, extra=None):
|
| 103 |
+
rep = dict(ok=True, tool=name)
|
| 104 |
+
rep.update(extra or {})
|
| 105 |
+
rep.update(self.proprio())
|
| 106 |
+
return rep
|
| 107 |
+
|
| 108 |
+
def _t_move_to(self, x, y, z, yaw, speed=None):
|
| 109 |
+
tgt = np.array([x, y, z], float)
|
| 110 |
+
if not np.all(np.isfinite(tgt)):
|
| 111 |
+
return ToolResult("move_to", {}, False, dict(ok=False, error="non-finite coordinates"))
|
| 112 |
+
spd = None if speed is None else float(np.clip(float(speed), SPEED_MIN, self.max_speed))
|
| 113 |
+
yaw_used = self.wrap_yaw(float(yaw))
|
| 114 |
+
cmd = tgt + self.bias # the hidden calibration error acts on every commanded position
|
| 115 |
+
rep = self.driver.move(cmd[0], cmd[1], cmd[2], yaw_used, spd)
|
| 116 |
+
self.motion_s += float(rep.get("motion_s") or 0.0)
|
| 117 |
+
self._set_state(rep["state"])
|
| 118 |
+
if not rep["ok"]: # rejected before moving (driver hard limits / no IK solution)
|
| 119 |
+
return ToolResult("move_to", {}, False, dict(ok=False, error="target rejected: the arm cannot reach it; "
|
| 120 |
+
"the arm did not move", driver_error=rep.get("error", "")))
|
| 121 |
+
self.yaw_cmd = yaw_used
|
| 122 |
+
reached = bool(np.linalg.norm(cmd - self.true_eef()) < 0.02)
|
| 123 |
+
return ToolResult("move_to", {}, True, self._report("move_to", dict(reached=reached,
|
| 124 |
+
yaw_used_deg=round(yaw_used, 1))))
|
| 125 |
+
|
| 126 |
+
def _gripper(self, close):
|
| 127 |
+
rep = self.driver.gripper(close)
|
| 128 |
+
self.grip_closed = bool(close)
|
| 129 |
+
self.motion_s += float(rep.get("motion_s") or 0.0)
|
| 130 |
+
self._set_state(rep["state"])
|
| 131 |
+
name = "close_gripper" if close else "open_gripper"
|
| 132 |
+
return ToolResult(name, {}, True, self._report(name))
|
| 133 |
+
|
| 134 |
+
def _t_open_gripper(self):
|
| 135 |
+
return self._gripper(False)
|
| 136 |
+
|
| 137 |
+
def _t_close_gripper(self):
|
| 138 |
+
return self._gripper(True)
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l5_iterative.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""[PARKED 2026-10-06 — fails acceptance: oracle 50% (n=12, k=3). The push response is not stationary:
|
| 2 |
+
the same commanded speed carries the cube 7.9 cm on one push and 11.4 cm on the next, because the arm reaches
|
| 3 |
+
different speeds at different extensions. Needs a configuration-independent striker before use.]
|
| 4 |
+
|
| 5 |
+
L5-B iterative_push: several pushes in ONE episode (MemMimic "Iterative Pushing" analogue).
|
| 6 |
+
|
| 7 |
+
The cube starts far from the target zone; each push is a straight strike away from the robot whose
|
| 8 |
+
only free parameter is the speed. Overshooting past the zone is unrecoverable (episode fails).
|
| 9 |
+
Hidden variable: cube-table friction mu, as in l5_slide_to_target. The information needed to choose
|
| 10 |
+
the next push (how far a push of a given speed carries the cube) is only available from the
|
| 11 |
+
outcomes of the previous pushes in the same episode -> within-episode learning from failure.
|
| 12 |
+
|
| 13 |
+
"Attempt" granularity for the history: one push.
|
| 14 |
+
"""
|
| 15 |
+
import numpy as np
|
| 16 |
+
|
| 17 |
+
from .. import envs
|
| 18 |
+
from ..task_base import register_task
|
| 19 |
+
from .l5_slide import CUBE_HALF, V_MAX, V_MIN, Z_PUSH, SlideToTarget
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@register_task
|
| 23 |
+
class IterativePush(SlideToTarget):
|
| 24 |
+
name = "l5_iterative_push"
|
| 25 |
+
level = "L5"
|
| 26 |
+
capabilities = ("Reason", "Save", "Utilize")
|
| 27 |
+
protocol = "within"
|
| 28 |
+
max_attempts = 3 # pushes per episode: too few to creep up on the target with small taps
|
| 29 |
+
instruction = ("Push the red cube away from the robot so that it comes to rest inside the green target zone. "
|
| 30 |
+
"You have at most three separate pushes. If the cube passes the zone, the task fails.")
|
| 31 |
+
instruction_indirect = instruction
|
| 32 |
+
tol_along = 0.015
|
| 33 |
+
|
| 34 |
+
def sample_instance(self, seed):
|
| 35 |
+
rng = np.random.default_rng(seed)
|
| 36 |
+
return dict(seed=int(seed),
|
| 37 |
+
cube_xy=[float(rng.uniform(-0.27, -0.23)), float(rng.uniform(-0.08, 0.08))],
|
| 38 |
+
target_dist=float(rng.uniform(0.22, 0.30)),
|
| 39 |
+
mu=float(np.exp(rng.uniform(np.log(0.035), np.log(0.08)))))
|
| 40 |
+
|
| 41 |
+
def make_bddl(self):
|
| 42 |
+
return super().make_bddl()
|
| 43 |
+
|
| 44 |
+
# --------------------------------------------------------------- one push from the current cube pose
|
| 45 |
+
def push_once(self, inst, speed):
|
| 46 |
+
c = envs.obj_pos(self.env, "cube_1")
|
| 47 |
+
x, y = c[0], c[1]
|
| 48 |
+
sk = self.sk
|
| 49 |
+
sk.set_gripper(True, steps=3)
|
| 50 |
+
sk.move_to([x - self.runup, y, Z_PUSH + 0.10], yaw=0.0)
|
| 51 |
+
sk.move_to([x - self.runup, y, Z_PUSH], tol=0.003)
|
| 52 |
+
sk.move_to([x - CUBE_HALF + 0.015, y, Z_PUSH], speed=float(np.clip(speed, V_MIN, V_MAX)), tol=0.01,
|
| 53 |
+
max_steps=80)
|
| 54 |
+
sk.move_to([x - CUBE_HALF + 0.015, y, Z_PUSH + 0.10], speed=0.3)
|
| 55 |
+
envs.settle(self.env, 40)
|
| 56 |
+
c1 = envs.obj_pos(self.env, "cube_1")
|
| 57 |
+
return float(c1[0] - x)
|
| 58 |
+
|
| 59 |
+
def outcome(self, inst):
|
| 60 |
+
x0, y0 = inst["cube_xy"]
|
| 61 |
+
c = envs.obj_pos(self.env, "cube_1")
|
| 62 |
+
along = (c[0] - x0) - inst["target_dist"]
|
| 63 |
+
across = c[1] - y0
|
| 64 |
+
success = bool(abs(along) <= self.tol_along and abs(across) <= self.tol_across and c[2] > envs.TABLE_Z)
|
| 65 |
+
overshoot = bool(along > self.tol_along)
|
| 66 |
+
if success:
|
| 67 |
+
detail = "The cube is inside the target zone."
|
| 68 |
+
elif overshoot:
|
| 69 |
+
detail = f"The cube passed the target zone: it is {100 * along:.1f} cm beyond its centre. The task has failed."
|
| 70 |
+
else:
|
| 71 |
+
detail = f"The cube is {100 * -along:.1f} cm short of the centre of the target zone."
|
| 72 |
+
return dict(success=success, overshoot=overshoot, along_err=float(along), across_err=float(across),
|
| 73 |
+
detail=detail)
|
| 74 |
+
|
| 75 |
+
# --------------------------------------------------------------- scripted references
|
| 76 |
+
S0 = 0.02 # distance the cube travels during the contact stroke itself
|
| 77 |
+
|
| 78 |
+
def _plan_speed(self, remaining, model, pushes_left=1):
|
| 79 |
+
"""Model: push distance d(v) = s0 + k v^2. With more than one push left, cover all but a short
|
| 80 |
+
final leg (a short push is more predictable); with one push left, aim at the zone centre."""
|
| 81 |
+
if model is None:
|
| 82 |
+
return 0.30
|
| 83 |
+
s0, k = model
|
| 84 |
+
goal = remaining if pushes_left <= 1 else max(remaining - 0.07, 0.0)
|
| 85 |
+
v = np.sqrt(max(goal - s0, 0.0) / max(k, 1e-6))
|
| 86 |
+
return float(np.clip(v, V_MIN, V_MAX))
|
| 87 |
+
|
| 88 |
+
@classmethod
|
| 89 |
+
def _fit(cls, pts):
|
| 90 |
+
"""pts: [(v, d)]. One point -> fix s0; two or more -> least squares on (s0, k)."""
|
| 91 |
+
if len(pts) == 1:
|
| 92 |
+
v, d = pts[0]
|
| 93 |
+
return cls.S0, max(d - cls.S0, 1e-4) / v ** 2
|
| 94 |
+
A = np.array([[1.0, v ** 2] for v, _ in pts])
|
| 95 |
+
b = np.array([d for _, d in pts])
|
| 96 |
+
s0, k = np.linalg.lstsq(A, b, rcond=None)[0]
|
| 97 |
+
if k <= 0:
|
| 98 |
+
return cls.S0, max(np.mean(b) - cls.S0, 1e-4) / np.mean([v ** 2 for v, _ in pts])
|
| 99 |
+
return float(np.clip(s0, 0.0, 0.05)), float(k)
|
| 100 |
+
|
| 101 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 102 |
+
k = k or self.max_attempts
|
| 103 |
+
rng = np.random.default_rng(seed)
|
| 104 |
+
self.reset_instance(inst)
|
| 105 |
+
history = []
|
| 106 |
+
model = None
|
| 107 |
+
if kind == "oracle":
|
| 108 |
+
model = self._oracle_model(inst)
|
| 109 |
+
for a in range(k):
|
| 110 |
+
out0 = self.outcome(inst)
|
| 111 |
+
remaining = -out0["along_err"]
|
| 112 |
+
if kind == "naive" or kind == "blind":
|
| 113 |
+
speed = 0.30 if kind == "naive" else float(np.clip(0.30 + rng.normal(0, 0.05), V_MIN, V_MAX))
|
| 114 |
+
if remaining < 0.06: # naive heuristic: tap gently near the end
|
| 115 |
+
speed = 0.20
|
| 116 |
+
else:
|
| 117 |
+
speed = self._plan_speed(remaining, model, pushes_left=k - a)
|
| 118 |
+
moved = self.push_once(inst, speed)
|
| 119 |
+
out = self.outcome(inst)
|
| 120 |
+
history.append(dict(attempt=a + 1, params=dict(speed=speed), outcome=dict(out, moved=moved)))
|
| 121 |
+
if kind == "adaptive" and moved > 0.005:
|
| 122 |
+
pts = [(h["params"]["speed"], h["outcome"]["moved"]) for h in history if h["outcome"]["moved"] > 0.005]
|
| 123 |
+
model = self._fit(pts)
|
| 124 |
+
if out["success"] or out["overshoot"]:
|
| 125 |
+
break
|
| 126 |
+
# mark only the final state as the episode outcome
|
| 127 |
+
return history
|
| 128 |
+
|
| 129 |
+
def _oracle_model(self, inst):
|
| 130 |
+
"""Privileged: measure the push model with the true mu in scratch rollouts."""
|
| 131 |
+
pts = []
|
| 132 |
+
for v in (0.2, 0.35, 0.5):
|
| 133 |
+
self.reset_instance(inst)
|
| 134 |
+
pts.append((v, self.push_once(inst, v)))
|
| 135 |
+
self.reset_instance(inst)
|
| 136 |
+
return self._fit(pts)
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/lh_breakfast_service.py
ADDED
|
@@ -0,0 +1,546 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Breakfast revision 2: food meshes, hinged milk pourer, L1/L3/L4 recovery.
|
| 2 |
+
|
| 3 |
+
Rigid bodies use MuJoCo contacts. Milk is an explicitly reduced-order, volume-
|
| 4 |
+
conserving discharge / ballistic parcel model, NOT Navier-Stokes fluid simulation.
|
| 5 |
+
Only the physical carton angle controls discharge. No policy/stage success gates.
|
| 6 |
+
An upright butter stick physically obstructs the lid. Lay it flat to recover.
|
| 7 |
+
There is no latch fatigue, artificial opening torque, or forced orientation.
|
| 8 |
+
"""
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import copy
|
| 11 |
+
import xml.etree.ElementTree as ET
|
| 12 |
+
import numpy as np
|
| 13 |
+
import robosuite
|
| 14 |
+
import libero.libero as libero_pkg
|
| 15 |
+
|
| 16 |
+
from .. import envs
|
| 17 |
+
from ..bddl import write_bddl
|
| 18 |
+
from ..objects import register_generated, _wrap, _fmt
|
| 19 |
+
from ..skills import Skills
|
| 20 |
+
from ..task_base import register_task
|
| 21 |
+
from .lh_pantry_relatch import (PantryRelatch, RelatchSkills, BREAD_HALF,
|
| 22 |
+
BOX, BOX_MODEL, FLOOR_T, WALL_H, BOX_D, box_lid_xml)
|
| 23 |
+
|
| 24 |
+
LIB_ASSETS = Path(libero_pkg.__file__).parent / 'assets'
|
| 25 |
+
RS_ASSETS = Path(robosuite.__file__).parent / 'models/assets'
|
| 26 |
+
BUTTER_HALF = (.010,.020,.040) # standing: 8 cm tall; lying: 2 cm tall, fits the 2.6 cm cavity
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def food_xml(kind, half):
|
| 30 |
+
"""Reuse installed textured visual meshes, normalized to the tested food collision hull."""
|
| 31 |
+
if kind == 'bread':
|
| 32 |
+
source = RS_ASSETS / 'objects/bread.xml'
|
| 33 |
+
meshpath = RS_ASSETS / 'objects/meshes/bread.stl'
|
| 34 |
+
data = meshpath.read_bytes()
|
| 35 |
+
n = int.from_bytes(data[80:84], 'little')
|
| 36 |
+
dtype = np.dtype([('normal','<f4',3),('vertices','<f4',(3,3)),('attr','<u2')])
|
| 37 |
+
vertices = np.frombuffer(data, dtype=dtype, count=n, offset=84)['vertices'].reshape(-1,3)
|
| 38 |
+
else:
|
| 39 |
+
source = LIB_ASSETS / 'stable_hope_objects/butter/butter.xml'
|
| 40 |
+
meshpath = source.parent / 'butter.obj'
|
| 41 |
+
vertices = np.array([[float(v) for v in line.split()[1:4]] for line in meshpath.read_text().splitlines()
|
| 42 |
+
if line.startswith('v ')])
|
| 43 |
+
root = ET.parse(source).getroot()
|
| 44 |
+
asset = root.find('asset')
|
| 45 |
+
lo, hi = vertices.min(0), vertices.max(0)
|
| 46 |
+
scale = 2*np.array(half)/(hi-lo)
|
| 47 |
+
for el in asset:
|
| 48 |
+
if el.tag == 'mesh':
|
| 49 |
+
el.set('file', str(meshpath)); el.set('scale', _fmt(scale))
|
| 50 |
+
elif el.get('file'):
|
| 51 |
+
el.set('file', str((source.parent/el.get('file')).resolve()))
|
| 52 |
+
visual = copy.deepcopy(root.find('worldbody/body/body/geom'))
|
| 53 |
+
visual.set('group','1'); visual.set('contype','0'); visual.set('conaffinity','0')
|
| 54 |
+
visual.set('pos', _fmt(-(lo+hi)*scale/2)); visual.set('mass','0')
|
| 55 |
+
visual.attrib.pop('density',None)
|
| 56 |
+
mass=.06 if kind=='butter' else .025
|
| 57 |
+
hull = (f'<geom name="food_hull" type="box" size="{_fmt(half)}" mass="{mass}" '
|
| 58 |
+
'friction=".7 .005 .0001" solref=".001 1" solimp=".998 .998 .001" group="0"/>')
|
| 59 |
+
xml = ET.fromstring(_wrap('breakfast_'+kind, hull+ET.tostring(visual,encoding='unicode'),half[2],.05))
|
| 60 |
+
xml.insert(0,asset)
|
| 61 |
+
return ET.tostring(xml,encoding='unicode')
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def milk_station_xml():
|
| 65 |
+
source = LIB_ASSETS/'stable_hope_objects/milk/milk.xml'
|
| 66 |
+
root = ET.parse(source).getroot()
|
| 67 |
+
asset = root.find('asset')
|
| 68 |
+
for el in asset:
|
| 69 |
+
if el.get('file'): el.set('file', str(source.parent/el.get('file')))
|
| 70 |
+
carton = copy.deepcopy(root.find('worldbody/body/body'))
|
| 71 |
+
carton.set('name','carton_visual'); carton.set('quat','.5 .5 .5 .5')
|
| 72 |
+
# A carton held in a tabletop tipping cradle. The hinge is physical, unactuated.
|
| 73 |
+
parts = '''
|
| 74 |
+
<geom name="base" type="box" pos="-.025 0 .008" size=".035 .075 .008" rgba=".24 .28 .32 1"/>
|
| 75 |
+
<geom name="stand_l" type="capsule" fromto="0 -.055 .016 0 -.055 .21" size=".006" rgba=".5 .55 .6 1"/>
|
| 76 |
+
<geom name="stand_r" type="capsule" fromto="0 .055 .016 0 .055 .21" size=".006" rgba=".5 .55 .6 1"/>
|
| 77 |
+
<body name="tilting_carton" pos="0 0 .21">
|
| 78 |
+
<joint name="pull_slide" type="slide" axis="1 0 0" range="-.00001 .00001" damping="1" armature=".02"/>
|
| 79 |
+
<joint name="pour_hinge" type="hinge" axis="0 1 0" range="0 1.66" damping=".25" frictionloss=".05" armature=".004"/>
|
| 80 |
+
<inertial pos="0 0 0" mass=".25" diaginertia=".001 .001 .001"/>
|
| 81 |
+
<geom name="pour_bar" type="capsule" fromto="0 -.065 0 -.09 -.065 0" size=".005" rgba=".25 .25 .28 1" mass="0"/>
|
| 82 |
+
<geom name="pour_knob" type="sphere" pos="-.09 -.065 0" size=".013" rgba=".9 .65 .1 1" mass="0" friction="1 .005 .0001"/>
|
| 83 |
+
<geom name="spout" type="cylinder" pos=".026 0 .065" size=".009 .014" quat=".7071 0 .7071 0" rgba=".95 .95 .95 1" mass="0"/>
|
| 84 |
+
<site name="nozzle" pos=".04 0 .065" size=".006" rgba=".1 .1 .1 1"/>
|
| 85 |
+
</body>'''
|
| 86 |
+
xml = ET.fromstring(_wrap('breakfast_milk_station',parts,0,.08))
|
| 87 |
+
xml.insert(0,asset)
|
| 88 |
+
xml.find(".//body[@name='tilting_carton']").append(carton)
|
| 89 |
+
for parent in xml.iter('body'):
|
| 90 |
+
for geom in list(parent.findall('geom')):
|
| 91 |
+
if geom.get('group') is None:
|
| 92 |
+
geom.set('group','0')
|
| 93 |
+
vis=copy.deepcopy(geom);vis.set('group','1');vis.set('contype','0');vis.set('conaffinity','0')
|
| 94 |
+
vis.attrib.pop('name',None);vis.set('mass','0');parent.append(vis)
|
| 95 |
+
return ET.tostring(xml,encoding='unicode')
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def liquid_visual_xml():
|
| 99 |
+
geoms = ['<geom name="milk_surface" type="cylinder" size=".029 .001" pos="0 0 -2" rgba="1 .985 .92 0" contype="0" conaffinity="0" group="1"/>']
|
| 100 |
+
for i in range(80):
|
| 101 |
+
geoms.append(f'<geom name="drop_{i}" type="sphere" size=".0035" pos="0 0 -2" rgba="1 .985 .92 0" contype="0" conaffinity="0" group="1"/>')
|
| 102 |
+
geoms.append('<geom name="spill" type="cylinder" size=".01 .0005" pos="0 0 -2" rgba="1 .985 .92 0" contype="0" conaffinity="0" group="1"/>')
|
| 103 |
+
return _wrap('breakfast_liquid', ''.join(geoms),0,.001)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def fixed_cup_xml():
|
| 107 |
+
source=LIB_ASSETS/'turbosquid_objects/porcelain_mug/porcelain_mug.xml'
|
| 108 |
+
root=ET.parse(source).getroot()
|
| 109 |
+
for el in root.find('asset'):
|
| 110 |
+
if el.get('file'):el.set('file',str(source.parent/el.get('file')))
|
| 111 |
+
return ET.tostring(root,encoding='unicode')
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def serving_plate_xml():
|
| 115 |
+
source=LIB_ASSETS/'stable_scanned_objects/plate/plate.xml'
|
| 116 |
+
root=ET.parse(source).getroot();scale=1.5
|
| 117 |
+
for el in root.find('asset'):
|
| 118 |
+
if el.get('file'):el.set('file',str(source.parent/el.get('file')))
|
| 119 |
+
if el.tag=='mesh':el.set('scale',_fmt(np.fromstring(el.get('scale'),sep=' ')*scale))
|
| 120 |
+
for el in root.iter():
|
| 121 |
+
if el.tag in ('geom','site'):
|
| 122 |
+
if el.get('pos'):el.set('pos',_fmt(np.fromstring(el.get('pos'),sep=' ')*scale))
|
| 123 |
+
if el.get('size'):el.set('size',_fmt(np.fromstring(el.get('size'),sep=' ')*scale))
|
| 124 |
+
return ET.tostring(root,encoding='unicode')
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class BreakfastSkills(RelatchSkills):
|
| 128 |
+
def __init__(self,env,task,recorder=None):
|
| 129 |
+
super().__init__(env,task,recorder)
|
| 130 |
+
self.bias=np.asarray(task.inst['bias'] if task.inst['mechanisms']['L1'] else [0,0,0],float)
|
| 131 |
+
self.correction=np.zeros(3)
|
| 132 |
+
self.pour_latched=False
|
| 133 |
+
self.pour_rad=0.
|
| 134 |
+
self.pour_y=0.
|
| 135 |
+
|
| 136 |
+
def move_to(self,target,*args,**kwargs):
|
| 137 |
+
return super().move_to(np.asarray(target)-self.correction,*args,**kwargs)
|
| 138 |
+
|
| 139 |
+
def set_gripper(self,close,steps=15):
|
| 140 |
+
rep=super().set_gripper(close,steps)
|
| 141 |
+
if close and self.task.holding_pour_knob():
|
| 142 |
+
self.pour_latched=True
|
| 143 |
+
e=self.eef_pos(); h=self.task.pour_pivot()
|
| 144 |
+
self.pour_rad=float(np.linalg.norm((e-h)[[0,2]]));self.pour_y=float(e[1])
|
| 145 |
+
elif not close:self.pour_latched=False
|
| 146 |
+
return rep
|
| 147 |
+
|
| 148 |
+
def _act(self,dpos,drot,grip):
|
| 149 |
+
if self.pour_latched and self.task.inst['mechanisms']['L3']:
|
| 150 |
+
e=self.eef_pos(); k=self.task.pour_knob()
|
| 151 |
+
if grip<0 or np.linalg.norm(e-k)>.04:self.pour_latched=False
|
| 152 |
+
else:
|
| 153 |
+
h=self.task.pour_pivot();r=(e-h)[[0,2]];rn=max(np.linalg.norm(r),1e-6)
|
| 154 |
+
t=np.array([-r[1],r[0]])/rn
|
| 155 |
+
s=np.clip(np.asarray(dpos)[[0,2]]@t,-.008,.008)
|
| 156 |
+
corr=(self.pour_rad-rn)*r/rn
|
| 157 |
+
dpos=np.array([s*t[0]+corr[0], self.pour_y-e[1],s*t[1]+corr[1]])
|
| 158 |
+
super()._act(dpos,drot,grip)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
@register_task
|
| 162 |
+
class BreakfastService(PantryRelatch):
|
| 163 |
+
name='lh_breakfast_service'
|
| 164 |
+
level='L1'
|
| 165 |
+
category='system_identification'
|
| 166 |
+
failure_causes=('L1','L3','L4')
|
| 167 |
+
failure_types=failure_causes
|
| 168 |
+
agent_max_steps=360
|
| 169 |
+
instruction=('Prepare breakfast: put the bread from the wooden box onto the plate and close the box; '
|
| 170 |
+
'pour 80 to 160 mL of milk into the cup using the milk carton in its cradle. '
|
| 171 |
+
'Then store the butter inside the box and leave its lid shut. Finish with the carton upright, '
|
| 172 |
+
'bread on the plate, cup upright, and gripper open and clear. Spill at most 15 mL. '
|
| 173 |
+
'The cradle can be tipped with its gold side handle using ordinary gripper motions.')
|
| 174 |
+
instruction_indirect=instruction
|
| 175 |
+
agent_object_names=['bread','butter','plate','cup','milk carton','gold cradle handle','wooden box','lid knob']
|
| 176 |
+
|
| 177 |
+
def make_bddl(self):
|
| 178 |
+
boxroot=ET.fromstring(box_lid_xml(BOX_MODEL))
|
| 179 |
+
inertial=boxroot.find('.//inertial');ratio=.08/float(inertial.get('mass'))
|
| 180 |
+
inertial.set('mass','.08');inertial.set('diaginertia',_fmt(np.fromstring(inertial.get('diaginertia'),sep=' ')*ratio))
|
| 181 |
+
box=register_generated('LffBreakfastBox',ET.tostring(boxroot,encoding='unicode'),free=False)
|
| 182 |
+
bread=register_generated('LffBreakfastBread',food_xml('bread',BREAD_HALF))
|
| 183 |
+
butter=register_generated('LffBreakfastButter',food_xml('butter',BUTTER_HALF))
|
| 184 |
+
milk=register_generated('LffBreakfastMilk',milk_station_xml(),free=False)
|
| 185 |
+
liquid=register_generated('LffBreakfastLiquid',liquid_visual_xml(),free=False)
|
| 186 |
+
cup=register_generated('LffBreakfastCup',fixed_cup_xml(),free=False)
|
| 187 |
+
plate=register_generated('LffBreakfastPlate',serving_plate_xml())
|
| 188 |
+
objs=[('bread_1',bread,'bread_region',(-.31,-.01,-.29,.01)),
|
| 189 |
+
('butter_1',butter,'butter_region',(-.31,.24,-.29,.26)),
|
| 190 |
+
('plate_1',plate,'plate_region',(.02,-.26,.04,-.24))]
|
| 191 |
+
fx=[(BOX,box,'box_region',(-.18,-.12,-.16,-.10)),
|
| 192 |
+
('milk_1',milk,'milk_region',(.24,-.01,.26,.01)),
|
| 193 |
+
('liquid_1',liquid,'liquid_region',(.34,-.34,.35,-.33)),
|
| 194 |
+
('cup_1',cup,'cup_region',(.14,.26,.16,.28))]
|
| 195 |
+
return write_bddl(self.name,self.instruction.replace(';',','),objs,fx)
|
| 196 |
+
|
| 197 |
+
def __init__(self,cam_res=None):
|
| 198 |
+
super().__init__(cam_res)
|
| 199 |
+
m=self.env.sim.model
|
| 200 |
+
self.milk_bid=m.body_name2id(self.env.fixtures_dict['milk_1'].root_body)
|
| 201 |
+
self.pour_jid=m.joint_name2id('milk_1_pour_hinge')
|
| 202 |
+
self.slide_jid=m.joint_name2id('milk_1_pull_slide');self.slide_qa=int(m.jnt_qposadr[self.slide_jid])
|
| 203 |
+
self.pour_qa=int(m.jnt_qposadr[self.pour_jid]);self.pour_dof=int(m.jnt_dofadr[self.pour_jid])
|
| 204 |
+
self.pour_gid=m.geom_name2id('milk_1_pour_knob')
|
| 205 |
+
self.nozzle_sid=m.site_name2id('milk_1_nozzle')
|
| 206 |
+
self.liquid_bid=m.body_name2id(self.env.fixtures_dict['liquid_1'].root_body)
|
| 207 |
+
self.cup_bid=m.body_name2id(self.env.fixtures_dict['cup_1'].root_body)
|
| 208 |
+
self.drop_gids=[m.geom_name2id('liquid_1_drop_'+str(i)) for i in range(80)]
|
| 209 |
+
self.surface_gid=m.geom_name2id('liquid_1_milk_surface');self.spill_gid=m.geom_name2id('liquid_1_spill')
|
| 210 |
+
self.liquid=None;self.phase_hook=None
|
| 211 |
+
|
| 212 |
+
def sample_instance(self,seed):
|
| 213 |
+
inst=super().sample_instance(seed)
|
| 214 |
+
rng=np.random.default_rng(seed)
|
| 215 |
+
inst.update(box_xy=[-.20,-.10],plate_xy=[-.09,-.32],butter_xy=[-.36,-.32],
|
| 216 |
+
milk_xy=[-.14,.24],cup_xy=[-.075,.24],
|
| 217 |
+
bias=[0,float(rng.choice([-1,1])*.10),0],
|
| 218 |
+
mechanisms={'L1':True,'L3':True,'L4':True},flow_ml_s=float(rng.uniform(42,48)))
|
| 219 |
+
return inst
|
| 220 |
+
|
| 221 |
+
def apply_instance(self,inst):
|
| 222 |
+
super().apply_instance(inst)
|
| 223 |
+
m,d=self.env.sim.model,self.env.sim.data
|
| 224 |
+
half_z=BUTTER_HALF[2] if inst['mechanisms']['L4'] else BUTTER_HALF[0]
|
| 225 |
+
quat=[1,0,0,0] if inst['mechanisms']['L4'] else [np.sqrt(.5),0,np.sqrt(.5),0]
|
| 226 |
+
envs.set_obj_pose(self.env,'butter_1',[*inst['butter_xy'],envs.TABLE_Z+half_z+.001],quat_wxyz=quat)
|
| 227 |
+
self.drift_active=False;self.active_latch=0.
|
| 228 |
+
envs.scale_mass(self.env,'plate_1',.4)
|
| 229 |
+
envs.set_friction(self.env,'plate_1',.8)
|
| 230 |
+
m.body_pos[self.milk_bid]=[*inst['milk_xy'],envs.TABLE_Z]
|
| 231 |
+
m.body_quat[self.milk_bid]=[1,0,0,0]
|
| 232 |
+
m.body_pos[self.liquid_bid]=[0,0,0];m.body_quat[self.liquid_bid]=[1,0,0,0]
|
| 233 |
+
d.qpos[self.pour_qa]=0;d.qvel[self.pour_dof]=0
|
| 234 |
+
d.qpos[self.slide_qa]=0
|
| 235 |
+
m.jnt_range[self.slide_jid]=[-.00001,.00001] if inst['mechanisms']['L3'] else [-.11,.01]
|
| 236 |
+
m.body_pos[self.cup_bid]=[*inst['cup_xy'],envs.TABLE_Z-.0024]
|
| 237 |
+
m.body_quat[self.cup_bid]=[1,0,0,0]
|
| 238 |
+
for gid in self.drop_gids+[self.surface_gid,self.spill_gid]:m.geom_rgba[gid,3]=0
|
| 239 |
+
self.liquid=dict(reservoir=300.,cup=0.,spill=0.,parcels=[],emitted=0.,spill_xy=None)
|
| 240 |
+
self.trace=[]
|
| 241 |
+
|
| 242 |
+
def reset_instance(self,inst,recorder=None):
|
| 243 |
+
self.mon=None
|
| 244 |
+
np.random.seed(int(inst['seed']))
|
| 245 |
+
self.env.reset();self.apply_instance(inst);self.env.sim.forward();envs.settle(self.env,10)
|
| 246 |
+
self.mon=dict(events=[],lid_open_max=0.,armed=False)
|
| 247 |
+
self.sk=BreakfastSkills(self.env,self,recorder)
|
| 248 |
+
self.traps={k:False for k in self.failure_causes}
|
| 249 |
+
self.recovered={k:False for k in self.failure_causes}
|
| 250 |
+
self.initial_pour_pivot=self.pour_pivot().copy()
|
| 251 |
+
return self.sk
|
| 252 |
+
|
| 253 |
+
def _register_close(self,seated):
|
| 254 |
+
self.closes_done+=1;self.active_latch=0.;self.drift_active=False
|
| 255 |
+
self.mon['events'].append(dict(ev='closed',n=self.closes_done,mechanism='ordinary rigid-body hinge'))
|
| 256 |
+
|
| 257 |
+
def _bracket(self):
|
| 258 |
+
# Disable the predecessor's modeled spring/catch completely, at every physics substep.
|
| 259 |
+
self.env.sim.data.qfrc_applied[self.dof]=0.
|
| 260 |
+
|
| 261 |
+
def butter_corners(self):
|
| 262 |
+
p=envs.obj_pos(self.env,'butter_1')
|
| 263 |
+
R=self.env.sim.data.body_xmat[envs.body_id(self.env,'butter_1')].reshape(3,3)
|
| 264 |
+
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)])
|
| 265 |
+
|
| 266 |
+
def butter_height(self):
|
| 267 |
+
c=self.butter_corners();return float(np.ptp(c[:,2]))
|
| 268 |
+
|
| 269 |
+
def butter_in_box(self):
|
| 270 |
+
from .lh_lid_box import IN_X,IN_Y
|
| 271 |
+
c=self.butter_corners();b=np.asarray(self.inst['box_xy'])
|
| 272 |
+
inside=np.all(np.abs(c[:,:2]-b)<[IN_X+.001,IN_Y+.001])
|
| 273 |
+
return bool(inside and c[:,2].max()<envs.TABLE_Z+WALL_H+.002 and
|
| 274 |
+
c[:,2].min()>envs.TABLE_Z+FLOOR_T-.002 and not self.held('butter_1'))
|
| 275 |
+
|
| 276 |
+
def butter_lid_contact(self):
|
| 277 |
+
m=self.env.sim.model
|
| 278 |
+
lid=m.geom_name2id('box_1_'+BOX_MODEL+'_lid')
|
| 279 |
+
return envs.contacts_between(self.env,envs.obj_geom_ids(self.env,'butter_1'),[lid])
|
| 280 |
+
|
| 281 |
+
def pick_place(self,name,dest_xy,z_rel,z_carry=.18,dest_yaw=0.):
|
| 282 |
+
if name!='butter_1':return super().pick_place(name,dest_xy,z_rel,z_carry,dest_yaw)
|
| 283 |
+
s=self.sk;p=envs.obj_pos(self.env,name).copy()
|
| 284 |
+
tall=self.butter_height()>.045
|
| 285 |
+
grasp=p+np.array([0,0,.025 if tall else 0.])
|
| 286 |
+
s.set_gripper(False,8);s.move_to([p[0],p[1],1.12],yaw=0)
|
| 287 |
+
s.move_to(grasp,speed=.10,tol=.002,max_steps=120);s.set_gripper(True,20)
|
| 288 |
+
s.move_to([p[0],p[1],1.12],speed=.15)
|
| 289 |
+
if not self.held(name):s.set_gripper(False,8);return False
|
| 290 |
+
offset=envs.obj_pos(self.env,name)-s.eef_pos()
|
| 291 |
+
target=np.array([*dest_xy,envs.TABLE_Z+z_rel])-offset
|
| 292 |
+
s.move_to([target[0],target[1],1.12],yaw=dest_yaw)
|
| 293 |
+
s.move_to(target,speed=.10,tol=.003,max_steps=120)
|
| 294 |
+
s.set_gripper(False,12);s.move_to([target[0],target[1],1.14]);s.hold(10)
|
| 295 |
+
return True
|
| 296 |
+
|
| 297 |
+
def put_butter(self):
|
| 298 |
+
# Place the standing stick near the front wall; lay-flat placement uses the box centre.
|
| 299 |
+
standing=self.butter_height()>.045
|
| 300 |
+
target=np.array(self.inst['box_xy'])+([-0.030,0] if standing else [0,0])
|
| 301 |
+
return self.pick_place('butter_1',target,FLOOR_T+self.butter_height()/2+.003,z_carry=.18)
|
| 302 |
+
|
| 303 |
+
def lay_butter_flat(self):
|
| 304 |
+
"""Extract, tip on the table through contact, then pick the horizontal stick. No pose writes."""
|
| 305 |
+
s=self.sk;xy=np.asarray(self.inst['butter_xy'])
|
| 306 |
+
self.label('L4 recovery: take the upright stick out of the box')
|
| 307 |
+
if not self.pick_place('butter_1',xy,self.butter_height()/2+.003,z_carry=.18):return False
|
| 308 |
+
p=envs.obj_pos(self.env,'butter_1').copy()
|
| 309 |
+
self.label('Recovery: tip the butter stick onto its broad side')
|
| 310 |
+
s.set_gripper(True,8)
|
| 311 |
+
s.move_to([p[0]-.055,p[1],1.07],yaw=0)
|
| 312 |
+
s.move_to([p[0]-.055,p[1],envs.TABLE_Z+.055],speed=.10)
|
| 313 |
+
s.move_to([p[0]+.025,p[1],envs.TABLE_Z+.055],speed=.06)
|
| 314 |
+
s.move_to([p[0]+.025,p[1],1.10],speed=.12);s.set_gripper(False,8);s.hold(60)
|
| 315 |
+
self.label('Recovery: the butter stick is now lying flat on the table')
|
| 316 |
+
return self.butter_height()<.029
|
| 317 |
+
|
| 318 |
+
def pour_pivot(self):
|
| 319 |
+
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])
|
| 320 |
+
def pour_knob(self):return self.env.sim.data.geom_xpos[self.pour_gid].copy()
|
| 321 |
+
def pour_angle(self):return float(self.env.sim.data.qpos[self.pour_qa])
|
| 322 |
+
def holding_pour_knob(self):
|
| 323 |
+
g=self.env.robots[0].gripper
|
| 324 |
+
return bool(self.env._check_grasp(gripper=[g.important_geoms['left_finger'],g.important_geoms['right_finger']],
|
| 325 |
+
object_geoms=['milk_1_pour_knob','milk_1_pour_bar']))
|
| 326 |
+
|
| 327 |
+
def monitor_step(self):
|
| 328 |
+
super().monitor_step()
|
| 329 |
+
if getattr(self,'liquid',None) is None or self.mon is None:return
|
| 330 |
+
if self.pour_angle()<np.radians(50) and not self.liquid['parcels']:return
|
| 331 |
+
for sub in range(10):self.update_liquid(.005,render_update=(sub==9))
|
| 332 |
+
|
| 333 |
+
def update_liquid(self,dt,render_update=True):
|
| 334 |
+
"""Conserved millilitres, tilt discharge, gravity trajectories and moving cup aperture.
|
| 335 |
+
Visual geoms are passive displays of the parcel model, never body state edits.
|
| 336 |
+
"""
|
| 337 |
+
q=self.liquid;m,d=self.env.sim.model,self.env.sim.data
|
| 338 |
+
a=self.pour_angle();origin=d.site_xpos[self.nozzle_sid].copy()
|
| 339 |
+
flow=self.inst['flow_ml_s']*max(0.,min(1.,(a-np.radians(50))/np.radians(25)))
|
| 340 |
+
dv=min(q['reservoir'],flow*dt)
|
| 341 |
+
if dv>0:
|
| 342 |
+
# small outward speed along the spout, transformed by the actual hinge angle
|
| 343 |
+
vel=np.array([np.cos(a),0,-np.sin(a)])*.04
|
| 344 |
+
q['parcels'].append(dict(p=origin.copy(),v=vel,ml=dv))
|
| 345 |
+
q['reservoir']-=dv;q['emitted']+=dv
|
| 346 |
+
cup_origin=d.body_xpos[self.cup_bid]
|
| 347 |
+
cup_rot=d.body_xmat[self.cup_bid].reshape(3,3)
|
| 348 |
+
cup=cup_origin+cup_rot@np.array([.015,-.0016,.10]);top=cup[2]
|
| 349 |
+
keep=[]
|
| 350 |
+
for drop in q['parcels']:
|
| 351 |
+
p=drop['p'];v=drop['v'];end=p+v*dt+np.array([0,0,-.5*9.81*dt*dt])
|
| 352 |
+
caught=False
|
| 353 |
+
if p[2]>=top>end[2]:
|
| 354 |
+
hit=p+(end-p)*(p[2]-top)/(p[2]-end[2])
|
| 355 |
+
if np.linalg.norm(hit[:2]-cup[:2])<.029 and self.cup_upright():
|
| 356 |
+
q['cup']+=drop['ml'];caught=True
|
| 357 |
+
excess=max(0.,q['cup']-180.)
|
| 358 |
+
if excess:
|
| 359 |
+
q['cup']-=excess;q['spill']+=excess;q['spill_xy']=cup[:2].tolist()
|
| 360 |
+
if not caught and end[2]<=envs.TABLE_Z+.002:
|
| 361 |
+
q['spill']+=drop['ml'];q['spill_xy']=end[:2].tolist();caught=True
|
| 362 |
+
if not caught:
|
| 363 |
+
drop['p']=end;drop['v']=v+np.array([0,0,-9.81*dt]);keep.append(drop)
|
| 364 |
+
q['parcels']=keep
|
| 365 |
+
if not render_update:return
|
| 366 |
+
for i,gid in enumerate(self.drop_gids):
|
| 367 |
+
if i<len(keep):m.geom_pos[gid]=keep[i]['p'];m.geom_rgba[gid,3]=1
|
| 368 |
+
else:m.geom_rgba[gid,3]=0
|
| 369 |
+
m.geom_pos[self.surface_gid]=[cup[0],cup[1],top-.05+min(q['cup'],180)/180*.045]
|
| 370 |
+
m.geom_rgba[self.surface_gid,3]=float(q['cup']>.1)
|
| 371 |
+
if q['spill']>.1:
|
| 372 |
+
m.geom_pos[self.spill_gid]=[*q['spill_xy'],envs.TABLE_Z+.002]
|
| 373 |
+
m.geom_size[self.spill_gid,0]=min(.08,.009*np.sqrt(q['spill']))
|
| 374 |
+
m.geom_rgba[self.spill_gid,3]=1
|
| 375 |
+
self.env.sim.forward()
|
| 376 |
+
|
| 377 |
+
def cup_upright(self):
|
| 378 |
+
# Native mug uses world Z as its vertical in the loaded LIBERO pose.
|
| 379 |
+
return bool(self.env.sim.data.body_xmat[self.cup_bid].reshape(3,3)[2,2]>.94)
|
| 380 |
+
|
| 381 |
+
def label(self,text):
|
| 382 |
+
state=dict(text=text,step=self.sk.n_steps,lid_deg=self.lid_deg(),
|
| 383 |
+
pour_deg=float(np.degrees(self.pour_angle())),cup_ml=self.liquid['cup'],spill_ml=self.liquid['spill'],
|
| 384 |
+
butter_height_cm=100*self.butter_height(),butter_lid_contact=bool(self.butter_lid_contact()),
|
| 385 |
+
lid_applied_torque=float(self.env.sim.data.qfrc_applied[self.dof]))
|
| 386 |
+
self.trace.append(state)
|
| 387 |
+
if self.phase_hook:self.phase_hook(text,state)
|
| 388 |
+
|
| 389 |
+
def calibration_probe(self):
|
| 390 |
+
# Attempt the loose butter first, away from fixture walls; fixed bias is present for ALL motions.
|
| 391 |
+
p=envs.obj_pos(self.env,'butter_1').copy();s=self.sk
|
| 392 |
+
s.set_gripper(False,8);s.move_to([p[0],p[1],envs.TABLE_Z+.14],yaw=0,tol=.0005,max_steps=120)
|
| 393 |
+
observed=s.eef_pos()-np.array([p[0],p[1],envs.TABLE_Z+.14])
|
| 394 |
+
s.move_to(p,tol=.002,max_steps=100)
|
| 395 |
+
s.set_gripper(True,15);s.move_to([p[0],p[1],envs.TABLE_Z+.15])
|
| 396 |
+
failed=not s.holding('butter_1')
|
| 397 |
+
self.traps['L1']=bool(failed)
|
| 398 |
+
self.label('L1: grasp missed the butter' if failed else 'Calibration grasp succeeded')
|
| 399 |
+
s.set_gripper(False,8)
|
| 400 |
+
return observed
|
| 401 |
+
|
| 402 |
+
def direct_carton_lift(self):
|
| 403 |
+
s=self.sk;k=self.pour_knob();start=k.copy()
|
| 404 |
+
s.set_gripper(False,8)
|
| 405 |
+
s.move_to(k+[0,0,.10],yaw=0)
|
| 406 |
+
s.move_to(k,speed=.12,max_steps=100)
|
| 407 |
+
s.set_gripper(True,20)
|
| 408 |
+
held_before=self.holding_pour_knob()
|
| 409 |
+
# Pulling along the radius cannot translate a hinged cradle. Same low-level interface as agents.
|
| 410 |
+
s.move_to(k+[-.07,0,0],speed=.08,max_steps=30)
|
| 411 |
+
lift=float(np.linalg.norm(self.pour_knob()-start))
|
| 412 |
+
self.pull_probe=dict(held_before=held_before,held_after=self.holding_pour_knob(),displacement_m=lift,
|
| 413 |
+
angle_deg=float(np.degrees(self.pour_angle())))
|
| 414 |
+
self.traps['L3']=bool(held_before and lift<.01 and self.liquid['cup']<1)
|
| 415 |
+
self.label('L3: straight pull failed; the cradle only rotates')
|
| 416 |
+
s.set_gripper(False,10);s.move_to(s.eef_pos()+[0,0,.10])
|
| 417 |
+
return lift
|
| 418 |
+
|
| 419 |
+
def tip_carton(self,target_ml=110.):
|
| 420 |
+
s=self.sk;k=self.pour_knob();h=self.pour_pivot()
|
| 421 |
+
s.set_gripper(False,8);s.move_to(k+[0,0,.09],yaw=0)
|
| 422 |
+
s.move_to(k,tol=.002,max_steps=120);s.set_gripper(True,20)
|
| 423 |
+
self.label('Recovery: grasp the gold handle and tip the carton')
|
| 424 |
+
if not s.pour_latched:return False
|
| 425 |
+
for deg in range(10,81,10):
|
| 426 |
+
a=np.radians(deg)
|
| 427 |
+
target=h+[-.09*np.cos(a),-.065,.09*np.sin(a)]
|
| 428 |
+
s.move_to(target,speed=.06,max_steps=90,tol=.003)
|
| 429 |
+
self.label(f'Tipping handle: target {deg}, actual {np.degrees(self.pour_angle()):.1f}, held {s.pour_latched}')
|
| 430 |
+
self.label('Pouring milk into the cup')
|
| 431 |
+
for _ in range(120):
|
| 432 |
+
if self.liquid['cup']+sum(p['ml'] for p in self.liquid['parcels'])>=target_ml:break
|
| 433 |
+
s.hold(1)
|
| 434 |
+
for deg in range(70,-1,-10):
|
| 435 |
+
a=np.radians(deg)
|
| 436 |
+
s.move_to(h+[-.09*np.cos(a),-.065,.09*np.sin(a)],speed=.10,max_steps=90,tol=.003)
|
| 437 |
+
self.label(f'Returning handle: target {deg}, actual {np.degrees(self.pour_angle()):.1f}, held {s.pour_latched}')
|
| 438 |
+
s.set_gripper(False,10);e=s.eef_pos();s.move_to(e+[0,0,.12]);s.hold(15)
|
| 439 |
+
self.recovered['L3']=bool(80<=self.liquid['cup']<=160 and self.liquid['spill']<=15)
|
| 440 |
+
self.label('Milk poured; carton returned upright')
|
| 441 |
+
return self.recovered['L3']
|
| 442 |
+
|
| 443 |
+
def bread_on_plate(self):
|
| 444 |
+
p=envs.obj_pos(self.env,'bread_1');plate=envs.obj_pos(self.env,'plate_1')
|
| 445 |
+
return bool(np.linalg.norm(p[:2]-plate[:2])<.05 and p[2]<envs.TABLE_Z+.08 and
|
| 446 |
+
not self.held('bread_1') and envs.contacts_between(self.env,envs.obj_geom_ids(self.env,'bread_1'),
|
| 447 |
+
envs.obj_geom_ids(self.env,'plate_1')))
|
| 448 |
+
|
| 449 |
+
def take_bread(self):
|
| 450 |
+
s=self.sk;p=envs.obj_pos(self.env,'bread_1').copy()
|
| 451 |
+
s.set_gripper(False,8);s.move_to([p[0],p[1],1.04],yaw=0)
|
| 452 |
+
s.move_to(p,tol=.003);s.set_gripper(True,15);s.move_to([p[0],p[1],1.04],speed=.3)
|
| 453 |
+
self.label(f'Bread pickup: held={s.holding("bread_1")}, pos={envs.obj_pos(self.env,"bread_1").round(3).tolist()}, eef={s.eef_pos().round(3).tolist()}')
|
| 454 |
+
if not s.holding('bread_1'):return False
|
| 455 |
+
off=envs.obj_pos(self.env,'bread_1')-s.eef_pos()
|
| 456 |
+
plate=envs.obj_pos(self.env,'plate_1')
|
| 457 |
+
goal=np.array([plate[0],plate[1],envs.obj_max_z(self.env,'plate_1')+BREAD_HALF[2]+.035])-off
|
| 458 |
+
s.move_to([goal[0],goal[1],1.12],yaw=0)
|
| 459 |
+
s.move_to(goal,speed=.10);s.set_gripper(False,15);s.move_to([goal[0],goal[1],1.14]);s.hold(10)
|
| 460 |
+
self.label(f'Bread placement: goal={goal.round(3).tolist()}, bread={envs.obj_pos(self.env,"bread_1").round(3).tolist()}, plate={envs.obj_pos(self.env,"plate_1").round(3).tolist()}')
|
| 461 |
+
return self.bread_on_plate()
|
| 462 |
+
|
| 463 |
+
def execute(self,inst,params):
|
| 464 |
+
mode=params.get('mode','adaptive');s=self.sk
|
| 465 |
+
self.label('Prepare breakfast: milk, bread and butter')
|
| 466 |
+
if mode=='oracle':s.correction=s.bias.copy()
|
| 467 |
+
else:
|
| 468 |
+
observed=self.calibration_probe()
|
| 469 |
+
if mode in ('naive','blind') and self.traps['L1']:return
|
| 470 |
+
s.correction=observed*np.array([1,1,0])
|
| 471 |
+
# Same attempt: use observed gripper error, then re-grasp and return the butter to its starting area.
|
| 472 |
+
ok=self.pick_place('butter_1',inst['butter_xy'],BUTTER_HALF[2]+.002)
|
| 473 |
+
self.recovered['L1']=bool(ok)
|
| 474 |
+
self.label('L1 recovery: corrected the offset and grasped the butter' if ok else 'Butter re-grasp failed')
|
| 475 |
+
if not ok:return
|
| 476 |
+
self.open_lid()
|
| 477 |
+
if not self.take_bread():self.label('Bread grasp failed');return
|
| 478 |
+
self.label('Bread placed on the plate')
|
| 479 |
+
self.close_lid(False)
|
| 480 |
+
if mode!='oracle' and inst['mechanisms']['L3']:
|
| 481 |
+
self.direct_carton_lift()
|
| 482 |
+
if mode in ('naive','blind'):return
|
| 483 |
+
if not self.tip_carton():self.label('Milk pour incomplete');return
|
| 484 |
+
self.open_lid()
|
| 485 |
+
if mode=='oracle' and self.butter_height()>.045:
|
| 486 |
+
if not self.lay_butter_flat():self.label('Butter reorientation failed');return
|
| 487 |
+
if not self.put_butter():self.label('Butter storage failed');return
|
| 488 |
+
self.label('Upright butter stick: too tall for the shallow box' if self.butter_height()>.045
|
| 489 |
+
else 'Butter stick laid flat inside the box')
|
| 490 |
+
self.close_lid(False)
|
| 491 |
+
if mode not in ('oracle','naive','blind'):
|
| 492 |
+
self.label('Check whether the upright butter stick fits beneath the lid')
|
| 493 |
+
s.hold(80)
|
| 494 |
+
self.traps['L4']=bool(self.lid_deg()>5 and self.butter_lid_contact())
|
| 495 |
+
self.label('L4: upright butter stick physically blocks the lid' if self.traps['L4'] else 'No lid obstruction detected')
|
| 496 |
+
if not self.lid_closed():
|
| 497 |
+
self.open_lid()
|
| 498 |
+
if not self.lay_butter_flat():self.label('Butter reorientation failed');return
|
| 499 |
+
if not self.put_butter():self.label('Horizontal butter placement failed');return
|
| 500 |
+
self.label('Butter stick laid flat inside the box')
|
| 501 |
+
self.close_lid(False)
|
| 502 |
+
s.hold(60)
|
| 503 |
+
self.recovered['L4']=bool(self.lid_closed() and self.butter_in_box())
|
| 504 |
+
self.label('L4 recovery: butter laid flat; the lid closes normally')
|
| 505 |
+
if not self.bread_on_plate():
|
| 506 |
+
self.label('Final check: restore the bread disturbed during cleanup')
|
| 507 |
+
self.take_bread()
|
| 508 |
+
s.set_gripper(False,8);s.move_to([-.35,-.30,1.20]);s.hold(15)
|
| 509 |
+
|
| 510 |
+
def default_params(self,inst):return {'mode':'naive'}
|
| 511 |
+
def oracle_params(self,inst):return {'mode':'oracle'}
|
| 512 |
+
def adapt_params(self,inst,history):return {'mode':'adaptive'}
|
| 513 |
+
def run_scripted(self,kind,inst,k=None,seed=0,on_attempt=None):
|
| 514 |
+
rng=np.random.default_rng(seed);hist=[]
|
| 515 |
+
for attempt in range((k or 5) if kind=='blind' else 1):
|
| 516 |
+
self.reset_instance(inst)
|
| 517 |
+
if kind=='blind':self.sk.correction[:2]=rng.uniform(-.012,.012,2)
|
| 518 |
+
self.execute(inst,{'mode':kind})
|
| 519 |
+
out=self.outcome(inst);hist.append(dict(attempt=attempt+1,params={'mode':kind},outcome=out))
|
| 520 |
+
if on_attempt:on_attempt(attempt,hist[-1]['params'],out)
|
| 521 |
+
if out['success']:break
|
| 522 |
+
return hist
|
| 523 |
+
|
| 524 |
+
def outcome(self,inst):
|
| 525 |
+
out=super().outcome(inst);q=self.liquid
|
| 526 |
+
inflight=sum(p['ml'] for p in q['parcels'])
|
| 527 |
+
out.update(cup_ml=round(q['cup'],3),spill_ml=round(q['spill'],3),reservoir_ml=round(q['reservoir'],3),
|
| 528 |
+
inflight_ml=round(inflight,3),conservation_error_ml=abs(300-q['reservoir']-q['cup']-q['spill']-inflight),
|
| 529 |
+
pour_deg=round(float(np.degrees(self.pour_angle())),2),traps=dict(self.traps),recovered=dict(self.recovered))
|
| 530 |
+
out['stages'].update(milk_served=bool(80<=q['cup']<=160),spill_ok=bool(q['spill']<=15),
|
| 531 |
+
carton_upright=bool(abs(self.pour_angle())<.15),cup_upright=self.cup_upright(),
|
| 532 |
+
gripper_open=bool(self.sk.grip<0),
|
| 533 |
+
gripper_clear=bool(min(np.linalg.norm(self.sk.eef_pos()-envs.obj_pos(self.env,n))
|
| 534 |
+
for n in ('bread_1','butter_1'))>.06),
|
| 535 |
+
carton_static=bool(abs(self.env.sim.data.qvel[self.pour_dof])<.1))
|
| 536 |
+
out['success']=bool(out['success'] and all(out['stages'].values()))
|
| 537 |
+
if not out['success'] and out['failure'] is None:
|
| 538 |
+
out['failure']=next((k for k,v in out['stages'].items() if not v),'not_static')
|
| 539 |
+
out['detail']=(f"Bread on plate: {out['stages']['bread_on_plate']}; butter fully below the box rim: "
|
| 540 |
+
f"{out['stages']['butter_in_box']}; lid angle: {self.lid_deg():.1f} degrees. "
|
| 541 |
+
f"Milk in cup: {q['cup']:.1f} mL; spilled: {q['spill']:.1f} mL. "
|
| 542 |
+
f"Butter height: {100*self.butter_height():.1f} cm.")
|
| 543 |
+
if self.butter_lid_contact() and not self.lid_closed():out['detail']+=' The upright butter stick is touching and obstructing the lid.'
|
| 544 |
+
out.update(geometry_version=2,butter_height_cm=round(100*self.butter_height(),3),
|
| 545 |
+
butter_lid_contact=bool(self.butter_lid_contact()),lid_applied_torque=float(self.env.sim.data.qfrc_applied[self.dof]))
|
| 546 |
+
return out
|