diff --git a/leaf/final/episode_000318_wrist_image.png b/leaf/final/episode_000318_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..7b4c830abbcfcebc18f3ddaccf9b4ffbc5acad9f --- /dev/null +++ b/leaf/final/episode_000318_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2b699fef452791c64e1f085df11c2bb3580c889d3552e55797ed5cfd1d52b6a7 +size 31312 diff --git a/leaf/final/episode_000455_wrist_image.png b/leaf/final/episode_000455_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..b8a438247b8ffabaeeacc9647fb83292ab2089cc --- /dev/null +++ b/leaf/final/episode_000455_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cc1589d676d72f3b9d19e80d29c91ae9e25da822417fd1d55ebb6caa2e427c01 +size 26205 diff --git a/leaf/final/episode_000636_image.png b/leaf/final/episode_000636_image.png new file mode 100644 index 0000000000000000000000000000000000000000..34040c24432b69e0fed21a126a39969c45984c4d --- /dev/null +++ b/leaf/final/episode_000636_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:165cf0ae6f72230e4dc9c8f6cf26a1665eb8e6cd56d14921edebc4289fd8071e +size 54236 diff --git a/leaf/final/episode_000715_image.png b/leaf/final/episode_000715_image.png new file mode 100644 index 0000000000000000000000000000000000000000..7e1b1f9413378ae56990b7896689f1d8a8ccbb3a --- /dev/null +++ b/leaf/final/episode_000715_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1ff88d5e4fe44312e56bc09a5bfdb4d5c8230c01575cba9ea63f985f1fc28c30 +size 52556 diff --git a/leaf/final/episode_000916_image.png b/leaf/final/episode_000916_image.png new file mode 100644 index 0000000000000000000000000000000000000000..3c661f5396709621a7c67474a571ec7ec779b7d9 --- /dev/null +++ b/leaf/final/episode_000916_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b14e8045c967d08cc68818385cc79cf0aad69d3253a5ea6216c7f8f865b8e8b7 +size 53610 diff --git a/leaf/final/episode_000935_image.png b/leaf/final/episode_000935_image.png new file mode 100644 index 0000000000000000000000000000000000000000..28b8b885d3e6dbf71289a7747ad9fb3c319f2d1c --- /dev/null +++ b/leaf/final/episode_000935_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:084df638a00bd586fcf18f43c652cfce2f1c8590839c1ee1f179d5e945184461 +size 59758 diff --git a/leaf/final/episode_000994_image.png b/leaf/final/episode_000994_image.png new file mode 100644 index 0000000000000000000000000000000000000000..68303b02459d99034397f729f8da723352374dce --- /dev/null +++ b/leaf/final/episode_000994_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0b7d1194198d5ffd35d1b937d7ac4dd1e5ca49dc1e8d1e981887f399156ce396 +size 53572 diff --git a/leaf/final/episode_001592.npz b/leaf/final/episode_001592.npz new file mode 100644 index 0000000000000000000000000000000000000000..14d6812fe35f5c3e0094bbcd6864fe1ba612e58c --- /dev/null +++ b/leaf/final/episode_001592.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:abf08e591c54ea64b5b88b52e38a6729f48381a014139b65c3b448187aabc996 +size 3838 diff --git a/leaf/final/episode_001702_image.png b/leaf/final/episode_001702_image.png new file mode 100644 index 0000000000000000000000000000000000000000..21af1579754a7658d5219d5768ac663051d1aad0 --- /dev/null +++ b/leaf/final/episode_001702_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:36847c7e5401052c49d9d739e5c9e992fdcf05803035dc255e2751e3197f04a7 +size 55423 diff --git a/leaf/final/episode_001729_wrist_image.png b/leaf/final/episode_001729_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..dfd7ad744d9966b57e838ca4b34c86e3fcb61b57 --- /dev/null +++ b/leaf/final/episode_001729_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1fd8f21c2c1bcd9ce905dbc2c88d28d7bbe4db7168b99b3e332fdaa5855ad9ad +size 29672 diff --git a/leaf/final/episode_001990.npz b/leaf/final/episode_001990.npz new file mode 100644 index 0000000000000000000000000000000000000000..a5c1a47a0bcf8f5de33feb3d228cd64573e86d2d --- /dev/null +++ b/leaf/final/episode_001990.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2e8f25fce6bdec27c9dfbc6c522e9dcb5dda8d2bb7cc0e0843f9e1ff6370810d +size 3750 diff --git a/leaf/final/episode_002254.npz b/leaf/final/episode_002254.npz new file mode 100644 index 0000000000000000000000000000000000000000..c39f1e2d8c4edafe3a565b5918b64641411bbd1c --- /dev/null +++ b/leaf/final/episode_002254.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6f8d33386b60cc3e4ccd768bdff48e79f6115d8f8afa0d987e417fa855fbeb43 +size 3886 diff --git a/leaf/final/episode_002278_image.png b/leaf/final/episode_002278_image.png new file mode 100644 index 0000000000000000000000000000000000000000..f50037f4e28afb64635b4a9188a24d9eaf4052e4 --- /dev/null +++ b/leaf/final/episode_002278_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0269cbb219e85a1d1371fad35aea4643e813ee122783552aa211d863bfcbe448 +size 57673 diff --git a/leaf/final/episode_002635_wrist_image.png b/leaf/final/episode_002635_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..b801f1e9ee0971efc2d1aeead20c07b1d9e3202b --- /dev/null +++ b/leaf/final/episode_002635_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:78ecde02eeb3c8d936960202956d08613bd240ab92bcdd13a6c97dbd22ca9b14 +size 47279 diff --git a/leaf/final/episode_002661_wrist_image.png b/leaf/final/episode_002661_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..b5266fe8ee14890a75f772b674e3d7f18d238777 --- /dev/null +++ b/leaf/final/episode_002661_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:75bb60d6a7358335b1f699dcf4b016b64a43568ea50108ba93832dc94beeef8a +size 40010 diff --git a/leaf/final/episode_002747.npz b/leaf/final/episode_002747.npz new file mode 100644 index 0000000000000000000000000000000000000000..21372d959e9779586d7d043979e5d5a2012a4ef2 --- /dev/null +++ b/leaf/final/episode_002747.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:64cdad6bd6be55b37e2bd07e157be9e1d504c38e38e218f54c61131a0bd141b6 +size 4150 diff --git a/leaf/final/episode_002799_wrist_image.png b/leaf/final/episode_002799_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..2749114df9d228fbf2509dd6b5ed19d8daca79ce --- /dev/null +++ b/leaf/final/episode_002799_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8908326f2c66db152d7114928aded69164b61e439475a4176c808fb786951ca4 +size 41524 diff --git a/leaf/final/episode_003069.npz b/leaf/final/episode_003069.npz new file mode 100644 index 0000000000000000000000000000000000000000..2a1435250c7881f6fd44a05e629393ad13d32e4b --- /dev/null +++ b/leaf/final/episode_003069.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1a7f5dbd07bcecfa4e077908ddde7ce2f2a0684006eafd84eeabf2ef44cb8e5d +size 3630 diff --git a/leaf/final/episode_003240_wrist_image.png b/leaf/final/episode_003240_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..ae11f7937c6ff2720856e3b0747735b26d68ae6c --- /dev/null +++ b/leaf/final/episode_003240_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:24047a637365d8ab055150f374c7a2cfe96ef3cd316fbb33276060aa64a5a147 +size 39728 diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/check_setup.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/check_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..c91b70fc618700ec2c265ebd1f9f21fed24e2420 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/check_setup.py @@ -0,0 +1,175 @@ +"""Check that this machine can run LFF-Bench. Run after `source run_env.sh`: + + python scripts/check_setup.py # Python packages, LIBERO config, simulation + rendering, the agent's shell jail + python scripts/check_setup.py --api # ... plus one tiny text-only request to the model endpoint (OPENAI_API_KEY / + # OPENAI_BASE_URL from the environment or from .env); costs a few tokens + python scripts/check_setup.py --api --model gpt-5.5 --skip-sim --skip-jail + +Exit code 0 when every check that ran passed. +""" +import argparse +import os +import subprocess +import sys +import tempfile +import time + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) +JAIL = "/opt/lffjail/jail_inner.sh" # same path as lffbench/agent/robot_server.py and scripts/gpt_player.py + +results = [] + + +def report(name, ok, detail=""): + results.append(ok) + print(f"[{'ok' if ok else 'FAIL'}] {name}" + (f": {detail}" if detail else ""), flush=True) + return ok + + +def check_packages(): + report("python 3.10", sys.version_info[:2] == (3, 10), sys.version.split()[0]) + from lffbench.agent.backends.base import import_openai + for mod in ("numpy", "mujoco", "robosuite", "libero.libero", "openai", "imageio", "cv2"): + try: + m = import_openai() if mod == "openai" else __import__(mod, fromlist=["_"]) + report(f"import {mod}", True, getattr(m, "__version__", "")) + except Exception as e: # noqa: BLE001 + report(f"import {mod}", False, f"{type(e).__name__}: {e}") + cfg = os.path.join(os.environ.get("LIBERO_CONFIG_PATH", ""), "config.yaml") + if report("LIBERO config", os.path.isfile(cfg), cfg + ("" if os.path.isfile(cfg) else " missing: run setup/install.sh")): + import yaml + assets = yaml.safe_load(open(cfg)).get("assets", "") + report("LIBERO assets", os.path.isdir(assets), assets) + report("rendering backend", bool(os.environ.get("MUJOCO_GL")), f"MUJOCO_GL={os.environ.get('MUJOCO_GL')}") + + +def check_sim(task_name, seed): + import importlib + import pkgutil + + try: + import lffbench.tasks as task_pkg + from lffbench.task_base import TASKS + except Exception as e: # noqa: BLE001 + report("import lffbench", False, f"{type(e).__name__}: {e}") + return + try: + for m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{m.name}") + except Exception as e: # noqa: BLE001 + report("import tasks", False, f"{type(e).__name__}: {e}") + return + report("tasks registered", len(TASKS) >= 20, f"{len(TASKS)} tasks") + t0 = time.time() + try: + task = TASKS[task_name]() + inst = task.sample_instance(seed) + task.reset_instance(inst) + img = task.snapshot() + out = task.outcome(inst) + except Exception as e: # noqa: BLE001 + report(f"simulate + render {task_name}", False, f"{type(e).__name__}: {e}") + return + ok = img.ndim == 3 and img.shape[2] == 3 and float(img.std()) > 1.0 + report(f"simulate + render {task_name}", ok, + f"image {img.shape}, pixel std {img.std():.1f}, untouched scene success={out['success']}, {time.time() - t0:.1f} s") + + +def check_jail(): + if not report("jail installed", os.access(JAIL, os.X_OK) and os.path.isdir("/opt/lffjail/py"), + JAIL if os.path.exists(JAIL) else "missing: sudo bash jail/setup_jail.sh"): + return + probe = r''' +echo "pwd=$(pwd)" +python3 -c "import numpy, scipy, PIL, cv2; print('py=ok')" 2>&1 | tail -1 +echo "mnt_entries=$(ls -A /mnt 2>/dev/null | wc -l) home_entries=$(ls -A /home 2>/dev/null | wc -l)" +python3 -c " +import socket +s = socket.socket(); s.settimeout(3) +try: + s.connect(('1.1.1.1', 443)); print('net=open') +except OSError as e: + print('net=blocked') +" +touch made_in_jail && echo "write=ok" +''' + with tempfile.TemporaryDirectory(prefix="lffjail_check_") as ws: + argv = ["unshare", "--user", "--map-root-user", "--mount", "--net", "--", JAIL, ws, + "timeout", "-k", "5", "60", "bash", "-c", probe] + r = subprocess.run(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=120) + kv = dict(l.split("=", 1) for l in r.stdout.split() if "=" in l) + if r.returncode != 0 and not kv: + hint = "" + if "Operation not permitted" in r.stdout or "uid_map" in r.stdout: + hint = (" | unprivileged user namespaces are blocked; on Ubuntu >= 23.10: " + "sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0") + report("jail runs", False, r.stdout.strip()[-400:] + hint) + return + report("jail runs", True, f"workdir {kv.get('pwd')}") + report("jail python (numpy/scipy/Pillow/OpenCV)", kv.get("py") == "ok", kv.get("py", r.stdout[-300:])) + report("jail hides host data", kv.get("mnt_entries") == "0" and kv.get("home_entries") == "0", + f"/mnt entries {kv.get('mnt_entries')}, /home entries {kv.get('home_entries')}") + report("jail has no network", kv.get("net") == "blocked", kv.get("net", "?")) + report("jail writes the workspace", kv.get("write") == "ok" and os.path.exists(os.path.join(ws, "made_in_jail"))) + + +def load_env_file(): + path = os.environ.get("LFF_ENV_FILE") or os.path.join(ROOT, ".env") + if not os.path.isfile(path): + return None + for line in open(path): + line = line.strip() + if line and not line.startswith("#") and "=" in line: + k, v = line.split("=", 1) + os.environ.setdefault(k.removeprefix("export ").strip(), v.strip().strip("'\"")) + return path + + +def check_api(model, effort): + src = load_env_file() + if not os.environ.get("SSL_CERT_FILE") and os.path.exists("/etc/ssl/certs/ca-certificates.crt"): + os.environ["SSL_CERT_FILE"] = "/etc/ssl/certs/ca-certificates.crt" # same as scripts/gpt_player.py + if not report("OPENAI_API_KEY set", bool(os.environ.get("OPENAI_API_KEY")), + f"from {src}" if src else "from the environment (no .env)"): + return + base = os.environ.get("OPENAI_BASE_URL") or "https://api.openai.com/v1 (default)" + from lffbench.agent.backends.openai_responses import OpenAIResponsesBackend + t0 = time.time() + try: + client = OpenAIResponsesBackend(model=model, reasoning_effort=effort, timeout=120.0, max_retries=1).client() + resp = client.responses.create(model=model, instructions="Reply with exactly the word OK.", input="ping", + reasoning=dict(effort=effort), store=False, max_output_tokens=256) + text = (resp.output_text or "").strip() + u = resp.usage + report(f"API {model} @ {base}", bool(text), f"reply {text[:40]!r}, {time.time() - t0:.1f} s, " + f"tokens in {u.input_tokens} / out {u.output_tokens}") + except Exception as e: # noqa: BLE001 + report(f"API {model} @ {base}", False, f"{type(e).__name__}: {str(e)[:300]}") + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--api", action="store_true", help="also send one tiny request to the model endpoint") + ap.add_argument("--model", default="gpt-6-astra") + ap.add_argument("--effort", default="low") + ap.add_argument("--task", default="l5_slide_to_target") + ap.add_argument("--seed", type=int, default=1000) + ap.add_argument("--skip-sim", action="store_true") + ap.add_argument("--skip-jail", action="store_true") + a = ap.parse_args() + os.environ.setdefault("OMP_NUM_THREADS", "1") + check_packages() + if not a.skip_sim: + check_sim(a.task, a.seed) + if not a.skip_jail: + check_jail() + if a.api: + check_api(a.model, a.effort) + n_bad = results.count(False) + print(f"\n{len(results) - n_bad}/{len(results)} checks passed") + sys.exit(1 if n_bad else 0) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/harnesses/pins/claude_code_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/harnesses/pins/claude_code_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json new file mode 100644 index 0000000000000000000000000000000000000000..2209c4d2440474d612687439a6eed5b95d150712 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/harnesses/pins/claude_code_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json @@ -0,0 +1,15 @@ +{ + "key": "claude_code|2.1.267|0399c793ff571d59|claude-sonnet-5-5|high", + "fingerprint_sha256": "fbf323682711d7010fa8cd2c9036b1082dab2a6cd4cf80983be1adf64e037d7c", + "written": "2026-10-20 02:16:00", + "summary": { + "system_chars": 182, + "tools": [ + "mcp__lff__robot", + "mcp__lff__shell", + "mcp__lff__view_images" + ], + "effort_in_request": "high", + "model_in_request": "claude-sonnet-5-5" + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/harnesses/base.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/harnesses/base.py new file mode 100644 index 0000000000000000000000000000000000000000..76d950990151f8a0f38718909be11e6792cfb431 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/harnesses/base.py @@ -0,0 +1,364 @@ +"""Harness adapter interface (docs/15 §3). + +An adapter runs one episode (one robot_server session) with one agent harness and leaves behind, in the run's log +dir: harness.json (what was launched), trajectory.jsonl (unified trajectory), harness_audit.json (checks + violations). +Budgets, automatic finish and attempt switching are NOT the adapter's business: robot_server and the MCP server / +reference driver enforce them identically for every harness. + + name stable harness name (the "harness" column of a table) + capabilities CapabilityDecl: every item of REQUIRED and FORBIDDEN must be declared, with its evidence source; + a missing item makes the class definition fail (so the import fails) + version() the actual installed version (probed before launch) + prepare(ep, first_message) -> LaunchSpec: one-time dirs, configs, argv / env + launch(spec) fail-closed preflight, then start the process (env exactly the whitelist) -> RunHandle + collect(h) native event stream -> trajectory.jsonl (ATIF-like), usage, exit reason + audit(h) tool list, preset prompt, memory, state left behind, violations +""" +import dataclasses +import json +import os +import secrets +import shutil +import signal +import subprocess +import time + +from . import contract as C + +EVIDENCE = ("launch", "stream", "server", "probe", "preflight") + +REQUIRED = { + "only_benchmark_tools": "the model can call exactly robot / shell / view_images (ours) and nothing else of use", + "images_reach_model": "view_images returns the image bytes to the model unchanged", + "non_persistent_session": "nothing of the session is written to disk for later runs", + "pinned_version": "the harness version (and binary hash) is recorded and pinned", + "machine_readable_events": "a machine-readable event stream of the whole run", + "tool_calls_logged": "every tool call is logged (harness stream + MCP / driver transcript + events.jsonl)", + "model_and_effort": "model and reasoning effort can be set and are visible in the request", +} +FORBIDDEN = { + "persistent_memory": "harness memory across runs (C4: auto-memory, CLAUDE.md / AGENTS.md, memories db)", + "instruction_file_injection": "instruction files picked up from the work / config / home dir", + "web_access": "web search / fetch", + "host_file_read": "reading host files outside the episode workspace", + "builtin_shell": "a shell of the harness itself (outside our jailed shell tool)", + "subagent_delegation": "spawning sub-agents", + "background_execution": "background tasks that outlive a tool call", +} + + +@dataclasses.dataclass(frozen=True) +class Cap: + status: str # REQUIRED items: "yes" | "partial" | "no"; FORBIDDEN items: "absent" | "present" | "partial" + evidence: str # one of EVIDENCE + note: str = "" + + +PROXY_KEYS = ("HTTPS_PROXY", "HTTP_PROXY", "https_proxy", "http_proxy") +NO_PROXY_KEYS = ("NO_PROXY", "no_proxy") +NO_PROXY_LOCAL = "127.0.0.1,localhost,::1" + + +def proxy_env(environ=None): + """The calling environment's HTTP(S) proxy, passed to a native harness so it can reach the model API on machines + that only get out through a proxy. NO_PROXY is loopback only (the preflight's fake API), never the host's list. + Not part of config_sha256 (machine plumbing, not harness configuration).""" + environ = os.environ if environ is None else environ + e = {k: environ[k] for k in PROXY_KEYS if environ.get(k)} + if e: + e.update({k: NO_PROXY_LOCAL for k in NO_PROXY_KEYS}) + return e + + +class CapabilityError(TypeError): + pass + + +def check_capabilities(name, caps): + if not isinstance(caps, dict): + raise CapabilityError(f"{name}: capabilities must be a dict") + missing = [k for k in list(REQUIRED) + list(FORBIDDEN) if k not in caps] + extra = [k for k in caps if k not in REQUIRED and k not in FORBIDDEN] + if missing or extra: + raise CapabilityError(f"{name}: capability declaration incomplete: missing {missing}, unknown {extra}") + for k, c in caps.items(): + if not isinstance(c, Cap) or c.evidence not in EVIDENCE: + raise CapabilityError(f"{name}: capability {k!r} needs a Cap(status, evidence in {EVIDENCE})") + ok = ("yes", "partial", "no") if k in REQUIRED else ("absent", "present", "partial") + if c.status not in ok: + raise CapabilityError(f"{name}: capability {k!r} status must be one of {ok}") + + +class HarnessRefused(RuntimeError): + """Fail-closed: the launch preflight found a tool list / preset prompt that is not the pinned one.""" + + +@dataclasses.dataclass +class EpisodeSpec: + session_path: str + log_dir: str + sandbox: str + port: int + token: str + max_tool_calls: int + model: str + effort: str + provider: str = "" + task: str = "" + seed: int = 0 + extra: dict = dataclasses.field(default_factory=dict) + + @classmethod + def from_session(cls, session_path, model, effort, provider="", **extra): + session_path = os.path.abspath(session_path) + log_dir = os.path.dirname(session_path) + sess = json.load(open(session_path)) + iface = json.load(open(os.path.join(log_dir, "agent_iface.json"))) + st = C.session_start(log_dir) + return cls(session_path=session_path, log_dir=log_dir, sandbox=sess["sandbox"], port=int(sess["port"]), + token=iface["token"], max_tool_calls=int(iface["max_tool_calls"]), model=model, effort=effort, + provider=provider, task=st["task"], seed=int(st["seed"]), extra=extra) + + +@dataclasses.dataclass +class LaunchSpec: + argv: list # full argv (the first message may be one element) + env: dict # the complete environment of the harness process (nothing else is inherited) + cwd: str + run_dir: str = "" # one-time dir tree, removed after audit + state_dirs: dict = dataclasses.field(default_factory=dict) # name -> path (home, config, ...) + first_message: str = "" + config_files: dict = dataclasses.field(default_factory=dict) # name -> path of files the adapter wrote + stdout_path: str = "" + stderr_path: str = "" + redact_argv: dict = dataclasses.field(default_factory=dict) # argv index -> replacement for the log + preflight: dict = dataclasses.field(default_factory=dict) + timeout_s: float = 10800 + + +@dataclasses.dataclass +class RunHandle: + spec: LaunchSpec + ep: EpisodeSpec + proc: object = None + pid: int = 0 + t_start: float = 0.0 + t_end: float = 0.0 + exit_code: int = None + exit_reason: str = "" + env_observed_keys: list = None # read from /proc//environ right after the start + info: dict = dataclasses.field(default_factory=dict) + + +def env_keys_of(pid): + try: + raw = open(f"/proc/{pid}/environ", "rb").read() + except OSError: + return None + return sorted({kv.split(b"=", 1)[0].decode("utf-8", "replace") for kv in raw.split(b"\0") if kv}) + + +def new_run_dir(root="/tmp/lffrun"): + """/tmp/lffrun/<12 hex>: the opaque work dir (its path is shown to the model by some harnesses).""" + os.makedirs(root, exist_ok=True) + while True: + d = os.path.join(root, secrets.token_hex(6)) + try: + os.mkdir(d, 0o700) + return d + except FileExistsError: + continue + + +def binary_info(path): + real = os.path.realpath(path) + return dict(path=path, realpath=real, sha256=C.sha256_file(real) if os.path.exists(real) else None) + + +class HarnessAdapter: + name = None + capabilities = None + uses_mcp = False + uses_gateway = False # harness_run starts the episode's tool gateway (scripts/tool_gateway.py) for + # this adapter: MCP adapters through the MCP server, framework adapters + # (RPent, ...) through lffbench_client with LFF_GATEWAY_URL / LFF_GATEWAY_TOKEN + clean_dirs = () # keys of spec.state_dirs that must be empty at launch + clean_allowed = {} # key of spec.state_dirs -> file names the adapter itself put there (e.g. auth.json) + ancestor_files = () # instruction files that must not exist in the work dir or any ancestor + unsafe_skip_clean_check = False # tests/harness_selfcheck only (probing what the harness would read) + jail = None # lffbench/harnesses/jail.HarnessJail when the adapter runs jailed (docs/15 §3.4) + can_resume = False # resume(): the CLI can continue its session with one more user message + + def clean_state_problems(self, spec): + """Fail-closed: the work dir and the one-time dirs must be empty, and no instruction file may sit in an + ancestor of the work dir (harnesses walk up the tree looking for CLAUDE.md / AGENTS.md).""" + p = [] + if spec.cwd and os.path.isdir(spec.cwd) and os.listdir(spec.cwd): + p.append(f"work dir not empty: {sorted(os.listdir(spec.cwd))[:5]}") + for k in self.clean_dirs: + d = spec.state_dirs.get(k) + left = [n for n in os.listdir(d) if n not in self.clean_allowed.get(k, ())] if d and os.path.isdir(d) else [] + if left: + p.append(f"{k} dir not empty: {sorted(left)[:5]}") + d = spec.cwd + while d and d != "/": + d = os.path.dirname(d) + for f in self.ancestor_files: + if os.path.exists(os.path.join(d, f)): + p.append(f"instruction file in an ancestor of the work dir: {os.path.join(d, f)}") + return p + + def __init_subclass__(cls, **kw): + super().__init_subclass__(**kw) + if cls.name is None: + raise CapabilityError(f"{cls.__name__}: no name") + check_capabilities(cls.name, cls.capabilities) + + # -------------------------------------------------------------------------------------------- interface + def version(self): + raise NotImplementedError + + def prepare(self, ep, first_message): + raise NotImplementedError + + def preflight(self, spec, ep): + """Fail-closed launch check; returns a dict for harness.json, raises HarnessRefused.""" + return dict(skipped=True) + + def collect(self, h): + raise NotImplementedError + + def audit(self, h): + raise NotImplementedError + + # -------------------------------------------------------------------------------------------- shared + def mcp_server_command(self, python, script, args): + """(command, args) of the MCP server entry in the harness config: our server, or, jailed, the relay to it.""" + if self.jail is not None: + return self.jail.mcp_command([python, script] + list(args), env={"PATH": "/usr/bin:/bin"}) + return python, [script] + list(args) + + def jailed_argv(self, argv, env, cwd, dirs): + """argv as started: unchanged, or wrapped into the jail with `dirs` (one-time dirs) mounted back.""" + return self.jail.wrap(argv, env, cwd, dirs) if self.jail is not None else list(argv) + + def jail_info(self): + return self.jail.info() if self.jail is not None else dict(enabled=False) + + def auth_info(self): + """How the harness authenticates to the model API (for harness.json; never a secret).""" + return dict(mode="api_env", keys=sorted(getattr(self, "api_env", {}) or {})) + + def launch(self, spec, ep, skip_preflight=False): + if not self.unsafe_skip_clean_check: + probs = self.clean_state_problems(spec) + if probs: + spec.preflight = dict(problems=probs) + raise HarnessRefused("clean-state check: " + "; ".join(probs)) + spec.preflight = dict(skipped=True, reason="skip_preflight") if skip_preflight else self.preflight(spec, ep) + out = open(spec.stdout_path, "wb") + err = open(spec.stderr_path, "wb") + h = RunHandle(spec=spec, ep=ep, t_start=time.time()) + argv = self.jailed_argv(spec.argv, spec.env, spec.cwd, list(spec.state_dirs.values()) + [spec.run_dir]) + h.proc = subprocess.Popen(argv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=out, + stderr=err, start_new_session=True) + h.pid = h.proc.pid + for _ in range(20): # the exec has happened once /proc//environ differs from ours + keys = env_keys_of(h.pid) + if keys is not None and set(keys) == set(spec.env): + break + time.sleep(0.05) + h.env_observed_keys = env_keys_of(h.pid) + return h + + def resume_argv(self, h, message): + """argv that continues the run's session with one more user message (adapters with can_resume).""" + raise NotImplementedError + + def resume(self, h, message): + """Continue the run's session with one more user message, after the CLI exited before the episode was over + (scripts/harness_run.py sends the reference driver's nudge). Same env, work dir and one-time dirs; the output + is appended to the same stdout / stderr files.""" + spec = h.spec + argv = self.resume_argv(h, message) + out, err = open(spec.stdout_path, "ab"), open(spec.stderr_path, "ab") + jargv = self.jailed_argv(argv, spec.env, spec.cwd, list(spec.state_dirs.values()) + [spec.run_dir]) + h.proc = subprocess.Popen(jargv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=out, + stderr=err, start_new_session=True) + h.pid, h.exit_code, h.exit_reason = h.proc.pid, None, "" + keys = None + for _ in range(20): + keys = env_keys_of(h.pid) + if keys is not None and set(keys) == set(spec.env): + break + time.sleep(0.05) + h.info.setdefault("resumes", []).append(dict(t=time.time(), pid=h.pid, message=message, + argv=[("" if x == message else x) for x in argv], + env_observed_keys=keys)) + return h + + def wait(self, h, timeout=None): + try: + h.exit_code = h.proc.wait(timeout=timeout or h.spec.timeout_s) + h.exit_reason = "exited" if h.exit_code == 0 else f"exit code {h.exit_code}" + except subprocess.TimeoutExpired: + self.kill(h) + h.exit_reason = "timeout" + h.t_end = time.time() + return h + + @staticmethod + def kill(h): + try: + os.killpg(h.proc.pid, signal.SIGTERM) + h.exit_code = h.proc.wait(timeout=20) + except ProcessLookupError: + pass + except subprocess.TimeoutExpired: + os.killpg(h.proc.pid, signal.SIGKILL) + h.exit_code = h.proc.wait() + + def logged_argv(self, spec): + return [spec.redact_argv.get(i, a) for i, a in enumerate(spec.argv)] + + def cleanup(self, spec): + if spec.run_dir and spec.run_dir.startswith(("/tmp/lffrun/", "/tmp/lffstate/")) and os.path.isdir(spec.run_dir): + shutil.rmtree(spec.run_dir, ignore_errors=True) + for d in spec.state_dirs.values(): + if d.startswith(("/tmp/lffrun/", "/tmp/lffstate/")) and os.path.isdir(d): + shutil.rmtree(d, ignore_errors=True) + if self.jail is not None: + self.jail.close() + + +def gateway_env(log_dir): + """{LFF_GATEWAY_URL, LFF_GATEWAY_TOKEN} of the episode's tool gateway, for a framework adapter (uses_gateway) whose + process talks to it through lffbench_client (Session.from_env). harness_run.py starts the gateway right before + launch, so call this in the adapter's launch() and add it to spec.env before the process starts. The token is the + gateway's, never robot_server's.""" + d = json.load(open(os.path.join(log_dir, "gateway.json"))) + return {"LFF_GATEWAY_URL": d["url"], "LFF_GATEWAY_TOKEN": d["token"]} + + +def snapshot_tree(root): + """Relative paths of all files under root (to list what a harness left behind).""" + out = [] + for dp, dn, fn in os.walk(root): + for f in fn: + out.append(os.path.relpath(os.path.join(dp, f), root)) + return sorted(out) + + +def first_message_text(readme, status_json): + """What a native harness gets as its first user message: the reference driver's instructions (preamble + README, + byte-identical) followed by its first user turn (the status report). The reference driver sends the same two + strings as system prompt and first user message; native harnesses keep their own system prompt.""" + from .contract import tool_schemas + _, preamble = tool_schemas() + return preamble + readme + "\n\n" + "Begin. Current status (robot command `status`):\n" + status_json + + +def reference_instructions(readme): + from .contract import tool_schemas + _, preamble = tool_schemas() + return preamble + readme diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-v4.1-flash_high.json b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-v4.1-flash_high.json new file mode 100644 index 0000000000000000000000000000000000000000..c4798ace7f051de8818f09aa5baaed23432f4854 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-v4.1-flash_high.json @@ -0,0 +1,15 @@ +{ + "key": "dsh|0.2.1-rc.5|aa65546cc1f51674|deepseek-v4.1-flash|high", + "fingerprint_sha256": "080d6300858cdfc671e135073ec7f693bcf424eace689ffc480903b40f0e0894", + "written": "2026-10-30 16:02:13", + "summary": { + "system_chars": 114, + "tools": [ + "mcp__lff__robot", + "mcp__lff__shell", + "mcp__lff__view_images" + ], + "effort_in_request": "high", + "model_in_request": "deepseek-v4.1-flash" + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/l1_yaw.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/l1_yaw.py new file mode 100644 index 0000000000000000000000000000000000000000..9bec2a49ccd283ea359cad9dd9b87efbbae7f9ac --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/l1_yaw.py @@ -0,0 +1,439 @@ +"""L1-C yaw_bias: put a long bar into a narrow holder, with an arm whose wrist rotation is miscalibrated. + +Category system_identification (level L1, action fine-tuning): the method (top-down pick across the bar, carry, +line the bar up with the holder, release just above the holder) and the scene understanding are right; only the +robot's own wrist rotation is off. + +Hidden variable: a fixed wrist-yaw calibration offset beta, |beta| ~ U[15, 30] deg with a random sign: every +commanded gripper yaw theta is executed as theta + beta. The robot reports its yaw in its own (miscalibrated) frame, +so the agent's proprioception says "yaw = theta" (implemented by shifting the robot's notion of yaw 0, `Skills.R0`, +by beta: the agent harness computes the reported yaw from R0, so beta never shows up in a reading). At reset the +wrist is turned to the robot's own yaw 0 (true yaw beta), so the first reading is 0. + +Why the prior fails: the bar is 14 cm long and 1.8 cm wide; the holder's opening is 3.2 cm wide (16 cm long). +Commanded to grasp square across the bar, the jaws actually come down rotated by beta; closing turns the bar until it +lies square in the jaws, so the bar ends up rotated by beta relative to where the robot thinks it is. Lined up +"exactly" with the holder, the bar is then beta off the holder's axis; its footprint across the opening +(14 sin beta + 1.8 cos beta >= 5.4 cm for beta >= 15 deg) is wider than the holder (4.4 cm outside), so it comes +down across the walls and stays on top of the holder at an angle -- clearly visible from both cameras. The +alignment tolerance is about +-5 deg (geometry; measured: see the task card). + +What has to be learned: F2 reports by how many degrees, and in which sense, the bar's long axis was rotated from the +holder's long axis when the gripper opened (and how far the jaws were turned from square to the bar when they +closed). That angle is beta itself, so after one failure beta can be estimated and subtracted from every commanded +yaw. +""" +import re + +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import bin_xml, box_xml, register_generated +from ..skills import Skills, _rotz +from ..task_base import LFFTask, register_task + +BAR, HOLDER = "bar_1", "holder_1" +DISTRACTORS = ("cream_cheese_1", "butter_1") +FREE_OBJECTS = (BAR,) + DISTRACTORS +NAMES = {BAR: "blue bar", HOLDER: "holder", "cream_cheese_1": "cream cheese", "butter_1": "butter"} +DESCR = {BAR: "long blue stick", HOLDER: "narrow grey trough", "cream_cheese_1": "flat blue box", + "butter_1": "small orange box"} + +BAR_HALF = (0.070, 0.009, 0.009) # 14 x 1.8 x 1.8 cm, long side along the bar's x axis +HOLDER_IN = (0.080, 0.016) # inner half extents of the holder's opening: 16 x 3.2 cm +WALL_T, FLOOR_T, WALL_H = 0.006, 0.006, 0.030 +HOLDER_HALF_H = (WALL_H + FLOOR_T) / 2 # body origin at mid height +RIM_Z = envs.TABLE_Z + FLOOR_T + WALL_H +MASS = {BAR: 0.070, "cream_cheese_1": 0.227, "butter_1": 0.250} +# Bar friction 0.5 with geom priority, so it is used for all bar contacts (also against the finger pads, mu 2). With +# the pads' mu 2 the jaws pinch a misaligned bar at their corners and it stays skewed in the hand (measured: turned +# 3-13 deg of beta 15-25 deg while closing); with 0.5 the closing jaws square it up (turned = beta, measured). +BAR_MU = 0.5 + +SITE_ABOVE_TABLE = 0.0105 # grasp point 1.05 cm above the table: fingertips ~1 mm above it +Z_CARRY = envs.TABLE_Z + 0.15 +RELEASE_GAP = 0.012 # bar bottom this far above the holder's rim at release +BETA_MIN, BETA_MAX = np.deg2rad(15), np.deg2rad(30) +AXIS_MAX = np.deg2rad(45) # bar / holder long axes within +-45 deg of the forward (x) direction +HOME_XY = np.array([-0.21, 0.0]) +REHOME_STEPS = 40 + + +def wrap_half(a): + """angle modulo pi into [-pi/2, pi/2) (the bar, the holder and the jaws are 180-deg symmetric)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def _yaw_of_xmat(xmat): + return float(np.arctan2(xmat[1, 0], xmat[0, 0])) + + +def _seg_dist(p, a, b): + ab = b - a + u = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0, 1) + return float(np.linalg.norm(a + u * ab - p)) + + +def _q(axis, a): + h = a / 2 + return {"z": np.array([np.cos(h), 0, 0, np.sin(h)])}[axis] + + +def _qmul(a, b): + w1, x1, y1, z1 = a + w2, x2, y2, z2 = b + return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, + w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2]) + + +def dir_words(dx, dy): + """Robot-frame description: +x = forward (away from the robot), +y = the robot's left.""" + parts = [] + if abs(dy) >= 0.0005: + parts.append(f"{100 * abs(dy):.1f} cm to the robot's {'left (+y)' if dy > 0 else 'right (-y)'}") + if abs(dx) >= 0.0005: + parts.append(f"{100 * abs(dx):.1f} cm {'forward (+x, away from the robot)' if dx > 0 else 'backward (-x, toward the robot)'}") + return " and ".join(parts) if parts else "exactly at the position" + + +def rot_words(a): + """Sense of a rotation about the vertical axis. Positive = counter-clockwise seen from above = from forward (+x) + towards the robot's left (+y) = increasing yaw.""" + d = np.degrees(a) + if abs(d) < 0.5: + return "not rotated (within 0.5 deg)" + if d > 0: + return f"rotated {d:.0f} deg counter-clockwise seen from above (from forward towards the robot's left, +yaw)" + return f"rotated {-d:.0f} deg clockwise seen from above (from forward towards the robot's right, -yaw)" + + +class YawSkills(Skills): + """Skills with a miscalibrated wrist: commanded yaw theta is executed as theta + yaw_bias. Implemented by shifting + the robot's notion of yaw 0 (`R0`, which Skills uses to build every orientation target and the agent harness uses + to report the yaw) by yaw_bias; `R0_true` is the real top-down orientation at yaw 0. Also logs what the outcome + measurement needs, whoever drives the skills (scripted policy or agent).""" + + def __init__(self, env, yaw_bias=0.0, recorder=None): + super().__init__(env, bias=None, recorder=recorder) + self.yaw_bias = float(yaw_bias) + self.R0_true = self.R0.copy() + self.R0 = _rotz(self.yaw_bias) @ self.R0_true + self.events = [] + m = env.sim.model + self._finger_geoms = { + side: [m.geom_name2id(g) for g in env.robots[0].gripper.important_geoms[side]] + for side in ("left_finger", "right_finger")} + self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_")] + self._obj_geoms = {n: envs.obj_geom_ids(env, n) for n in FREE_OBJECTS} + self.bar_z0 = float(envs.obj_pos(env, BAR)[2]) + self.bar_zmax = self.bar_z0 + self.bar_ref_yaw = self.bar_yaw() + self.bar_ref = envs.obj_pos(env, BAR) # bar pose before the fingers last touched it + + # ------------------------------------------------------------------ state + def true_yaw(self): + return _yaw_of_xmat(self.eef_mat() @ self.R0_true.T) + + def reported_yaw(self): + """Yaw as the miscalibrated robot believes it to be. Anything shown to the agent must use this.""" + return _yaw_of_xmat(self.eef_mat() @ self.R0.T) + + def bar_yaw(self): + return _yaw_of_xmat(self.env.sim.data.body_xmat[envs.body_id(self.env, BAR)].reshape(3, 3)) + + def touching(self): + return [n for n, gs in self._obj_geoms.items() if envs.contacts_between(self.env, self._grip_geoms, gs)] + + def holding_bar(self): + bg = self._obj_geoms[BAR] + return all(envs.contacts_between(self.env, gs, bg) for gs in self._finger_geoms.values()) + + def holding(self, obj_name): + """The agent harness reports `holding_object` through this; same finger-contact test as the outcome.""" + if obj_name == BAR: + return self.holding_bar() + return super().holding(obj_name) + + def wrap_yaw(self, yaw): + """Like Skills.wrap_yaw (the gripper is symmetric under pi), but the window |yaw| <= YAW_LIMIT is applied + to the TRUE wrist yaw (commanded + yaw_bias): the joint-7 limit is a property of the real wrist. Without + this, a commanded -113 deg with yaw_bias -30 deg drives joint 7 into its limit (measured: stops at true + -137 deg, reported -107 deg).""" + cands = [yaw + k * np.pi for k in range(-3, 4)] + ok = [c for c in cands if abs(c + self.yaw_bias) <= self.YAW_LIMIT] or cands + return float(min(ok, key=lambda c: abs(c - self.yaw))) + + def move_to(self, target, *args, **kwargs): + rep = super().move_to(target, *args, **kwargs) + rep["yaw_reported_deg"] = round(float(np.degrees(self.reported_yaw())), 1) + return rep + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.bar_zmax = max(self.bar_zmax, float(envs.obj_pos(self.env, BAR)[2])) + if self.grip < 0 and not envs.contacts_between(self.env, self._grip_geoms, self._obj_geoms[BAR]): + self.bar_ref_yaw = self.bar_yaw() + self.bar_ref = envs.obj_pos(self.env, BAR) + + def set_gripper(self, close, steps=15): + if close and self.grip < 0: + self.events.append(dict(kind="close", eef=self.eef_pos().tolist(), true_yaw=self.true_yaw(), + bar=envs.obj_pos(self.env, BAR).tolist(), bar_ref_yaw=self.bar_ref_yaw, + bar_ref=np.asarray(self.bar_ref).tolist(), touching=self.touching(), + step=self.n_steps)) + elif not close and self.grip > 0 and self.holding_bar(): + self.events.append(dict(kind="release", eef=self.eef_pos().tolist(), true_yaw=self.true_yaw(), + bar=envs.obj_pos(self.env, BAR).tolist(), bar_yaw=self.bar_yaw(), + step=self.n_steps)) + rep = super().set_gripper(close, steps) + if close and self.events and self.events[-1]["kind"] == "close": + self.events[-1]["bar_yaw_after"] = self.bar_yaw() + return rep + + +@register_task +class YawBias(LFFTask): + name = "l1_yaw_bias" + level = "L1" + category = "system_identification" + capabilities = ("Perceive", "Utilize") + protocol = "cross" + instruction = "Pick up the blue bar and put it into the holder." + instruction_indirect = "Pick up the long blue stick and drop it into the narrow grey trough so that it lies inside." + pick_lift_min = 0.03 + + # ------------------------------------------------------------ scene + def make_bddl(self): + bar = register_generated("LffYbBar", box_xml("lff_yb_bar", BAR_HALF, (0.15, 0.35, 0.85, 1.0), density=1500)) + holder = register_generated("LffYbHolder", bin_xml("lff_yb_holder", HOLDER_IN, WALL_H, wall_t=WALL_T, + floor_t=FLOOR_T, rgba=(0.55, 0.56, 0.60, 1.0), + density=2000), free=False) + objs = [(BAR, bar, "bar_region", (-0.21, -0.26, -0.19, -0.24)), + ("cream_cheese_1", "cream_cheese", "cheese_region", (-0.21, 0.24, -0.19, 0.26)), + ("butter_1", "butter", "butter_region", (0.15, -0.26, 0.17, -0.24))] + fx = [(HOLDER, holder, "holder_region", (0.09, -0.01, 0.11, 0.01))] + return write_bddl(self.name, self.instruction, objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + self._base_quat = {n: envs.obj_quat(self.env, n) for n in FREE_OBJECTS} + m = self.env.sim.model + self._holder_bid = m.body_name2id(self.env.fixtures_dict[HOLDER].root_body) + + def _place(self, name, xy, yaw, z0=envs.TABLE_Z): + q = _qmul(_q("z", yaw), self._base_quat[name]) + envs.set_obj_pose(self.env, name, [xy[0], xy[1], z0 + 0.3], quat_wxyz=q) + self.env.sim.forward() + qa, _ = envs.free_joint_addr(self.env, name) + self.env.sim.data.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (z0 + 0.0005) + self.env.sim.forward() + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + while True: + b = np.array([rng.uniform(-0.16, 0.04), rng.uniform(-0.20, 0.20)]) + h = np.array([rng.uniform(-0.14, 0.06), rng.uniform(-0.22, 0.22)]) + if np.linalg.norm(h - b) < 0.22: + continue + placed = [b, h] + dis = {} + for name in DISTRACTORS: + for _ in range(300): + p = np.array([rng.uniform(-0.22, 0.12), rng.uniform(-0.27, 0.27)]) + if any(np.linalg.norm(p - o) < 0.15 for o in placed): + continue + if any(_seg_dist(p, a, c) < 0.10 for a, c in ((b, h), (HOME_XY, b))): + continue + break + else: + break + placed.append(p) + dis[name] = dict(xy=p.round(5).tolist(), yaw=float(rng.uniform(-np.pi, np.pi))) + if len(dis) == len(DISTRACTORS): + break + bar_yaw = float(rng.uniform(-AXIS_MAX, AXIS_MAX)) + holder_yaw = float(rng.uniform(-AXIS_MAX, AXIS_MAX)) + beta = float(rng.choice([-1.0, 1.0]) * rng.uniform(BETA_MIN, BETA_MAX)) + return dict(seed=int(seed), bar_xy=b.round(5).tolist(), bar_yaw=bar_yaw, holder_xy=h.round(5).tolist(), + holder_yaw=holder_yaw, distractors=dis, yaw_bias=beta, yaw_bias_deg=float(np.degrees(beta))) + + def apply_instance(self, inst): + m = self.env.sim.model + m.body_pos[self._holder_bid] = [inst["holder_xy"][0], inst["holder_xy"][1], envs.TABLE_Z + HOLDER_HALF_H] + m.body_quat[self._holder_bid] = _q("z", inst["holder_yaw"]) + for name, mass in MASS.items(): + envs.scale_mass(self.env, name, mass) + self.env.sim.forward() + self._place(BAR, inst["bar_xy"], inst["bar_yaw"]) + envs.set_friction(self.env, BAR, BAR_MU, priority=3) + for name, v in inst["distractors"].items(): + self._place(name, v["xy"], v["yaw"]) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = YawSkills(self.env, yaw_bias=inst["yaw_bias"], recorder=recorder) + self.sk.hold(REHOME_STEPS) # turn the wrist to the robot's own yaw 0 (true yaw = beta) + self.sk.n_steps = 0 + self.sk.events = [] + self.start_pos = {n: envs.obj_pos(self.env, n) for n in FREE_OBJECTS} + return self.sk + + # ------------------------------------------------------------ outcome + def holder_frame(self, xy): + """xy (world) -> (along, across) in the holder frame, relative to the holder centre""" + c = self.env.sim.model.body_pos[self._holder_bid][:2].copy() + a = self.holder_yaw() + R = np.array([[np.cos(a), np.sin(a)], [-np.sin(a), np.cos(a)]]) + return R @ (np.asarray(xy[:2]) - c) + + def holder_yaw(self): + q = self.env.sim.model.body_quat[self._holder_bid] + return float(2 * np.arctan2(q[3], q[0])) + + def in_holder(self): + p = envs.obj_pos(self.env, BAR) + u, v = self.holder_frame(p) + return bool(abs(u) < HOLDER_IN[0] and abs(v) < HOLDER_IN[1] and p[2] < RIM_Z + and envs.obj_upright_cos(self.env, BAR) > 0.95) + + def outcome(self, inst): + envs.settle(self.env, 40) + sk = self.sk + p = envs.obj_pos(self.env, BAR) + held = sk.holding_bar() + success = bool(self.in_holder() and not held) + picked = sk.bar_zmax > sk.bar_z0 + self.pick_lift_min + closes = [e for e in sk.events if e["kind"] == "close"] + last_close = closes[-1] if closes else None + releases = [e for e in sk.events if e["kind"] == "release" and last_close and e["step"] >= last_close["step"]] + hy = self.holder_yaw() + end_mis = wrap_half(sk.bar_yaw() - hy) + hc = self.env.sim.model.body_pos[self._holder_bid][:2] + out = dict(success=success, picked=bool(picked), held_at_end=bool(held), bar_end=p.round(4).tolist(), + bar_end_misalign_deg=round(float(np.degrees(end_mis)), 1), grasp_misalign=None, + bar_turned_in_grasp=None, release_misalign=None, release_offset=None, touched_at_close=None) + grasp_txt = "" + if last_close is not None: + gm = wrap_half(last_close["true_yaw"] - last_close["bar_ref_yaw"]) + turned = wrap_half(last_close.get("bar_yaw_after", last_close["bar_ref_yaw"]) - last_close["bar_ref_yaw"]) + out["grasp_misalign"] = round(gm, 4) + out["bar_turned_in_grasp"] = round(turned, 4) + out["touched_at_close"] = last_close["touching"] + go = np.array(last_close["eef"][:2]) - np.array(last_close.get("bar_ref", last_close["bar"])[:2]) + a = last_close["bar_ref_yaw"] + along, across = go @ [np.cos(a), np.sin(a)], go @ [-np.sin(a), np.cos(a)] + over_bar = bool(abs(along) <= BAR_HALF[0] and abs(across) <= BAR_HALF[1] + 0.02) + out["grasp_xy_offset"] = go.round(4).tolist() + out["grasp_over_bar"] = over_bar + if over_bar: + grasp_txt = f"When the jaws closed on the blue bar, they were {rot_words(gm)} from square across the bar" + if np.linalg.norm(go) >= 0.015: + grasp_txt += f" (the grasp point was {dir_words(*go)} of the bar's centre)" + else: + grasp_txt = (f"When the jaws closed, the grasp point was {dir_words(*go)} of the blue bar's centre, i.e. " + f"not over the bar, and the jaws were {rot_words(gm)} from square across the bar") + if abs(np.degrees(turned)) >= 2: + grasp_txt += f", and the closing fingers turned the bar by {abs(np.degrees(turned)):.0f} deg" + if releases: + r = releases[-1] + rm = wrap_half(r["bar_yaw"] - hy) + out["release_misalign"] = round(rm, 4) + out["release_offset"] = (np.array(r["bar"][:2]) - hc).round(4).tolist() + if success: + out["failure"] = None + detail = "The blue bar is inside the holder." + if out["release_misalign"] is not None: + detail += (f" When the gripper opened, the bar's long axis was {rot_words(out['release_misalign'])} " + f"from the holder's long axis.") + elif not picked: + out["failure"] = "missed_grasp" + if last_close is None: + detail = "The gripper never closed; the blue bar was not picked up." + else: + detail = f"{grasp_txt}, but the bar was not picked up. It is still on the table." + elif held: + out["failure"] = "not_released" + detail = f"{grasp_txt}. The bar was picked up but it is still in the gripper." + elif releases: + out["failure"] = "missed_place" + if p[2] > RIM_Z - 0.002: + where = (f"The bar came down across the holder's walls instead of dropping in; it is now lying on top " + f"of the holder, its long axis {rot_words(end_mis)} from the holder's long axis.") + else: + where = (f"The bar did not end up inside the holder (its centre is now " + f"{dir_words(*(p[:2] - hc))} of the holder's centre).") + detail = (f"{grasp_txt}. When the gripper opened above the holder, the bar's long axis was " + f"{rot_words(out['release_misalign'])} from the holder's long axis, and the bar's centre was " + f"{dir_words(*out['release_offset'])} of the holder's centre. {where}") + else: + out["failure"] = "dropped" + detail = (f"{grasp_txt}. The bar was lifted but slipped out of the fingers before the gripper opened; it is " + f"now {dir_words(*(p[:2] - hc))} of the holder's centre.") + out["detail"] = detail + ind = detail + for k in sorted(NAMES, key=lambda n: -len(NAMES[n])): + ind = ind.replace(NAMES[k], DESCR[k]) + ind = re.sub(r"\bbar\b", "stick", ind) # the bare noun would give the direct name away + out["detail_indirect"] = ind + return out + + def feedback(self, inst, out, level="F2", indirect=False): + if indirect and level == "F2": + out = dict(out, detail=out.get("detail_indirect", out["detail"])) + return super().feedback(inst, out, level) + + # ------------------------------------------------------------ scripted execution (cross protocol) + def execute(self, inst, params): + """Top-down pick square across the bar at its centre, carry, line the bar up with the holder and release it + just above the holder's rim. params['dyaw'] (rad) is the policy's own yaw correction, added to every + commanded yaw.""" + sk = self.sk + dy = float(params.get("dyaw", 0.0)) + b = envs.obj_pos(self.env, BAR) # perfect perception of the current scene + psi = sk.bar_yaw() + hc = self.env.sim.model.body_pos[self._holder_bid][:2].copy() + phi = self.holder_yaw() + z_grasp = envs.TABLE_Z + SITE_ABOVE_TABLE + z_rel = RIM_Z + RELEASE_GAP + SITE_ABOVE_TABLE + sk.set_gripper(False, steps=8) + sk.move_to([b[0], b[1], Z_CARRY], yaw=wrap_half(psi) + dy) + sk.move_to([b[0], b[1], z_grasp + 0.06], tol=0.002) + sk.move_to([b[0], b[1], z_grasp], tol=0.003, max_steps=80) + sk.set_gripper(True, steps=15) + sk.move_to([b[0], b[1], Z_CARRY], speed=0.3) + if not sk.holding_bar(): # missed: a real controller sees the jaws closed on nothing and stops + return + sk.move_to([hc[0], hc[1], Z_CARRY], yaw=wrap_half(phi) + dy, tol=0.003) + sk.move_to([hc[0], hc[1], z_rel], tol=0.003, max_steps=100) + sk.hold(5) + sk.set_gripper(False, steps=12) + sk.move_to([hc[0], hc[1], Z_CARRY], speed=0.3) + + def default_params(self, inst): + return dict(dyaw=0.0) + + def oracle_params(self, inst): + return dict(dyaw=-float(inst["yaw_bias"])) + + def adapt_params(self, inst, history): + """Scripted F2 learner: the reported angle between the bar and the holder when the gripper opened is the + part of the wrist offset not yet corrected; accumulate it into the correction subtracted from every + commanded yaw. If the bar was never released, use the jaw angle at the grasp instead.""" + last = history[-1] + dy = float(last["params"]["dyaw"]) + o = last["outcome"] + if o.get("release_misalign") is not None: + dy -= o["release_misalign"] + elif o.get("grasp_misalign") is not None: + dy -= o["grasp_misalign"] + return dict(dyaw=round(dy, 4)) + + blind_sigma = np.deg2rad(4.0) + + def blind_params(self, inst, attempt, rng): + """Retry the same plan with a small random perturbation of the commanded yaws; no use of history.""" + return dict(dyaw=round(float(rng.normal(0.0, self.blind_sigma)), 4)) diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/l4_fit.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/l4_fit.py new file mode 100644 index 0000000000000000000000000000000000000000..7465485d3e907ad579bc46be98782eb8c5efad3a --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/l4_fit.py @@ -0,0 +1,574 @@ +"""L4-A fit_container: put the phone flat inside the one box it fits into. + +v3 (2026-10-08, user review of cla2): in v2 the only hidden information was which box is big enough, and box and +phone sizes are visible: all 4 Sonnet runs compared the sizes in the images and chose the right box first time. +v3 makes the phone itself bigger than it looks: it wears clear bumper caps on both ends (collision only, nothing is +rendered), CAP_RANGE = 0.8-0.9 cm each, so it is 1.6-1.8 cm longer than the visible phone. The box sizes are drawn +against the VISIBLE phone so that the boxes that look roomiest are too short for the capped phone: + fit visible margin +2.8..3.2 cm along the phone's length, only +0.8..0.9 cm across (looks tight), + snug +1.15..1.25 cm along, +2.5..3.0 cm across: the most comfortable-looking box, too short with the caps, + short_wide +0.3..0.6 cm along, +3..4 cm across: the biggest box, too short with the caps, + narrow_long +3.5..4.0 cm along but 0.3..0.6 cm too narrow, + small 0.5..1.0 cm too short. +A phone that does not fit lies on the rim of the box (or tips in at one end), visibly not inside, although in the +images it looks shorter than the opening. What has to be learned from that: the phone needs more length than it +appears to (by about the overlap seen) -> the box with the most length to spare. + +The text below is the v2 description (layout, execution, feedback) and still applies, with "phone length" read as +the capped length. v2 is kept in l4_fit.py.bak-20261008-height. + +v2 description: + +Scene: a dark "phone" (14.0 x 6.8 x 1.2 cm) lies in the front row of a 2 x 3 grid of slots; five open +boxes of the same colour and the same height fill the other five slots (inner sizes: see INNER_RANGES): + fit inner = phone + 1.0-1.5 cm in both directions (phone long side along box long side), + short_wide 0.5-1.5 cm too short but 3.5-5 cm wider than the phone (looks biggest), + narrow_long 0.5-1.5 cm too narrow but 2.5-3.5 cm longer than the phone (the longest), + small 0.5-1.2 cm too short and 0.3-0.6 cm too narrow (most phone-like proportions), + short 0.8-2.0 cm too short, as wide as the fitting box. +Each box is either roughly lined up with the phone's current long axis or roughly perpendicular to it +(+-15 deg jitter), independently with p = 0.5 -- so half of the time the fitting box needs the phone to be +turned by ~90 deg. + +Hidden: which box fits (only careful size comparison reveals it -- the boxes look alike), and whether the +fitting box needs the phone rotated. Box sizes are rebuilt per instance by resizing the bin geoms in +sim.model, so a single env serves every instance. + +Prior (naive): take the nearest box and line the phone's long side up with the box's long side (changed +2026-10-06 at the user's request: before, the prior kept the phone's orientation, so half of the first +failures were plain misalignment instead of a size mismatch). F2 feedback after a failed attempt reports where the phone ended up and by how much it is too +long / too wide along the box's long / short side; a learner can then rule out boxes that are not bigger +in that dimension and turn the phone. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, _wrap, bin_xml, register_generated +from ..skills import _rot_err +from ..task_base import LFFTask, register_task + +# phone (local x = long axis); PL is the visible length, the caps add 2 * cap (inst["cap"]) to it +PL, PW, PT = 0.140, 0.068, 0.012 +CAP_RANGE = (0.008, 0.009) # clear bumper cap length per end (hidden) +# boxes (local x = long axis of the opening) +WALL_T, FLOOR_T, WALL_H = 0.006, 0.006, 0.035 +BOX_HALF_H = (WALL_H + FLOOR_T) / 2 # body origin is at mid height +RIM_Z = envs.TABLE_Z + FLOOR_T + WALL_H +N_BOXES = 5 +ROWS_X = (-0.30, -0.08) # back row (near the robot), front row +COLS_Y = (-0.22, 0.0, 0.22) +DROP = 0.012 # phone bottom this far above the rim when released +Z_CARRY = envs.TABLE_Z + 0.15 +PARK = (-0.45, 0.0, envs.TABLE_Z + 0.35) # out of the agentview camera's way +PERC_SIGMA = 0.003 # perception noise (m) of the scripted adaptive policy's box-size estimates +JITTER_DEG = 15.0 +# inner size of each box kind = phone size + uniform(lo, hi) offset (m), (long side, short side). +# The distractors are chosen so that no coarse size heuristic finds the fitting box: the "short_wide" box has +# the largest area and width, "narrow_long" is the longest, "small" has the most phone-like aspect ratio. +# Only comparing both box dimensions with the phone's (or the F2 feedback) singles out the fitting box. +# v3: offsets are relative to the VISIBLE phone (PL x PW); only "fit" takes the capped phone (PL + 2 cap) +BOX_KINDS = ("fit", "snug", "short_wide", "narrow_long", "small") +INNER_RANGES = { + "fit": ((0.028, 0.008), (0.032, 0.009)), # +2.8..3.2 cm along, +0.8..0.9 cm across (looks the tightest) + "snug": ((0.0115, 0.025), (0.0125, 0.030)), # +1.15..1.25 along, +2.5..3.0 across: looks the most comfortable + "short_wide": ((0.003, 0.030), (0.006, 0.040)), # +0.3..0.6 along, +3..4 across: the biggest box + "narrow_long": ((0.035, -0.006), (0.040, -0.003)), # +3.5..4.0 along, 0.3..0.6 cm too narrow + "small": ((-0.010, 0.003), (-0.005, 0.006)), # 0.5..1.0 cm too short +} +VISIBLE_FIT = ("fit", "snug", "short_wide") # kinds that fit the phone as it looks (no caps) +BOX_RGBA = (0.70, 0.60, 0.46, 1.0) + + +def phone_xml(model_name): + hx, hy, hz = PL / 2, PW / 2, PT / 2 + body = (0.13, 0.13, 0.15, 1.0) + screen = (0.02, 0.025, 0.04, 1.0) + g = (f' \n' + f' \n' + f' ') + # v3: clear bumper caps on both ends: collision only, fully transparent, no visual twin (nothing is rendered). + # Resized per instance in apply_instance (inst["cap"]). + c = CAP_RANGE[1] + for k, sx in enumerate((1, -1)): + g += (f'\n ') + return _wrap(model_name, g, hz, float(np.hypot(hx + c, hy))) + + +def wrap_half(a): + """angle modulo pi into [-pi/2, pi/2) (the phone and the boxes are 180-deg symmetric)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def wrap_quarter(a): + """angle modulo pi/2 into [-pi/4, pi/4)""" + return float((a + np.pi / 4) % (np.pi / 2) - np.pi / 4) + + +def fits_some_yaw(a, b, clearance=0.002, length=PL): + """Does the phone's footprint (length x PW) fit inside an a x b opening at any yaw (with `clearance` to spare in + total)?""" + th = np.linspace(0.0, np.pi / 2, 181) + e1 = length * np.cos(th) + PW * np.sin(th) + e2 = length * np.sin(th) + PW * np.cos(th) + return bool(np.any((e1 <= a - clearance) & (e2 <= b - clearance))) + + +def _rect_corners(xy, yaw, half): + c, s = np.cos(yaw), np.sin(yaw) + R = np.array([[c, -s], [s, c]]) + pts = np.array([[1, 1], [1, -1], [-1, -1], [-1, 1]]) * np.asarray(half) + return pts @ R.T + np.asarray(xy) + + +def _rects_overlap(r1, r2): + """separating-axis test for two rotated rectangles given as (xy, yaw, half)""" + c1, c2 = _rect_corners(*r1), _rect_corners(*r2) + for yaw in (r1[1], r1[1] + np.pi / 2, r2[1], r2[1] + np.pi / 2): + ax = np.array([np.cos(yaw), np.sin(yaw)]) + p1, p2 = c1 @ ax, c2 @ ax + if p1.max() < p2.min() or p2.max() < p1.min(): + return False + return True + + +@register_task +class FitContainer(LFFTask): + name = "l4_fit_container" + level = "L4" + category = "geometry_inference" + capabilities = ("Perceive", "Reason") + instruction = "Put the phone flat inside a box that it fits into completely." + instruction_indirect = "Put the black rectangular gadget flat inside a box that it fits into completely." + + # ------------------------------------------------------------ scene + def make_bddl(self): + phone = register_generated("LffFitPhone", phone_xml("lff_fit_phone")) + # one category per box (BDDL lists one object per line; same-category lines would overwrite each + # other). All share the same MJCF; the opening is resized per instance in apply_instance. + cats = [register_generated(f"LffFitBox{c}", bin_xml(f"lff_fit_box_{c.lower()}", (0.075, 0.040), WALL_H, + wall_t=WALL_T, floor_t=FLOOR_T, rgba=BOX_RGBA, + density=3000)) + for c in "ABCDE"] + objs = [("phone_1", phone, "phone_region", (-0.09, -0.01, -0.07, 0.01))] + slots = [(x, y) for x in ROWS_X for y in COLS_Y if not (x == ROWS_X[1] and y == 0.0)] + for i, (x, y) in enumerate(slots): + objs.append((f"box_{i + 1}", cats[i], f"box{i + 1}_region", (x - 0.01, y - 0.01, x + 0.01, y + 0.01))) + return write_bddl(self.name, self.instruction, objs) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + j = np.radians(JITTER_DEG) + for _ in range(500): + col = int(rng.integers(3)) + phone_xy = [ROWS_X[1] + rng.uniform(-0.01, 0.01), COLS_Y[col] + rng.uniform(-0.01, 0.01)] + phone_yaw = float(rng.uniform(-j, j)) + slots = [(x, y) for x in ROWS_X for y in COLS_Y if not (x == ROWS_X[1] and y == COLS_Y[col])] + kinds = [BOX_KINDS[k] for k in rng.permutation(N_BOXES)] + cap = float(rng.uniform(*CAP_RANGE)) + boxes = [] + for i, (kind, (x, y)) in enumerate(zip(kinds, slots)): + lo, hi = INNER_RANGES[kind] + a, b = PL + rng.uniform(lo[0], hi[0]), PW + rng.uniform(lo[1], hi[1]) + assert (kind == "fit") == fits_some_yaw(a, b, length=PL + 2 * cap), (kind, a, b, cap) + assert (kind in VISIBLE_FIT) == fits_some_yaw(a, b), (kind, a, b) + crossed = bool(rng.random() < 0.5) + yaw = wrap_half(phone_yaw + (np.pi / 2 if crossed else 0.0) + rng.uniform(-j, j)) + boxes.append(dict(name=f"box_{i + 1}", kind=kind, crossed=crossed, + xy=[float(x + rng.uniform(-0.01, 0.01)), float(y + rng.uniform(-0.01, 0.01))], + yaw=yaw, inner=[float(a), float(b)])) + rects = [(b["xy"], b["yaw"], (b["inner"][0] / 2 + WALL_T + 0.007, b["inner"][1] / 2 + WALL_T + 0.007)) + for b in boxes] + rects.append((phone_xy, phone_yaw, (PL / 2 + 0.01, PW / 2 + 0.01))) + if not any(_rects_overlap(rects[p], rects[q]) for p in range(len(rects)) for q in range(p)): + break + else: + raise RuntimeError("could not sample a non-overlapping layout") + prng = np.random.default_rng(seed + 7919) + perc = [[float(b["inner"][0] + prng.normal(0, PERC_SIGMA)), float(b["inner"][1] + prng.normal(0, PERC_SIGMA))] + for b in boxes] + return dict(seed=int(seed), phone_xy=[float(v) for v in phone_xy], phone_yaw=phone_yaw, boxes=boxes, + fit=int(kinds.index("fit")), fit_crossed=boxes[kinds.index("fit")]["crossed"], cap=cap, _perc=perc) + + def _reshape_box(self, name, a, b): + ix, iy, H = a / 2, b / 2, BOX_HALF_H + parts = [((0, 0, -H + FLOOR_T / 2), (ix + WALL_T, iy + WALL_T, FLOOR_T / 2)), + ((ix + WALL_T / 2, 0, FLOOR_T / 2), (WALL_T / 2, iy + WALL_T, WALL_H / 2)), + ((-ix - WALL_T / 2, 0, FLOOR_T / 2), (WALL_T / 2, iy + WALL_T, WALL_H / 2)), + ((0, iy + WALL_T / 2, FLOOR_T / 2), (ix, WALL_T / 2, WALL_H / 2)), + ((0, -iy - WALL_T / 2, FLOOR_T / 2), (ix, WALL_T / 2, WALL_H / 2))] + m = self.env.sim.model + o = self.env.objects_dict[name] + for names in (o.contact_geoms, o.visual_geoms): + assert len(names) == len(parts), names + for k, n in enumerate(names): + g = m.geom_name2id(n) + pos, size = parts[k] + m.geom_pos[g] = pos + m.geom_size[g] = size + m.geom_rbound[g] = float(np.linalg.norm(size)) + m.geom_aabb[g] = [0, 0, 0, *size] + + def _set_caps(self, cap): + """resize the two hidden bumper caps to `cap` (m) per end""" + m = self.env.sim.model + if not hasattr(self, "_cap_ids"): + self._cap_ids = [g for g in envs.obj_geom_ids(self.env, "phone_1") + if m.geom_rgba[g][3] == 0.0 and m.geom_contype[g]] + assert len(self._cap_ids) == 2, self._cap_ids + for g in self._cap_ids: + sx = 1.0 if m.geom_pos[g][0] > 0 else -1.0 + size = (cap / 2, PW / 2 - 0.001, PT / 2) + m.geom_pos[g] = (sx * (PL / 2 + cap / 2), 0.0, 0.0) + m.geom_size[g] = size + m.geom_rbound[g] = float(np.linalg.norm(size)) + m.geom_aabb[g] = [0, 0, 0, *size] + + def apply_instance(self, inst): + # walls are moved inwards at run time, out of the compile-time per-body BVH leaf boxes, so the collision + # mid-phase can silently skip them (fingers / phone pass through; found on l4_nest_order 2026-10-07). + # Testing all geom pairs of nearby bodies is exact; the run-time geom_rbound / geom_aabb are set below. + import mujoco + self.env.sim.model._model.opt.disableflags |= int(mujoco.mjtDisableBit.mjDSBL_MIDPHASE) + self._set_caps(inst["cap"]) + for b in inst["boxes"]: + self._reshape_box(b["name"], *b["inner"]) + envs.set_obj_pose(self.env, b["name"], [*b["xy"], envs.TABLE_Z + BOX_HALF_H + 0.0005], yaw=b["yaw"]) + envs.set_obj_pose(self.env, "phone_1", [*inst["phone_xy"], envs.TABLE_Z + PT / 2 + 0.0005], + yaw=inst["phone_yaw"]) + + # ------------------------------------------------------------ outcome + def _pose2d(self, name): + bid = envs.body_id(self.env, name) + R = self.env.sim.data.body_xmat[bid].reshape(3, 3) + p = self.env.sim.data.body_xpos[bid].copy() + return p, float(np.arctan2(R[1, 0], R[0, 0])), float(np.degrees(np.arccos(np.clip(R[2, 2], -1, 1)))) + + def outcome(self, inst): + envs.settle(self.env, 40) + p, yaw, tilt = self._pose2d("phone_1") + held = bool(self.sk is not None and self.sk.holding("phone_1")) + # which box is the phone in / on: smallest distance of the phone centre outside a box opening + best = None + for j, b in enumerate(inst["boxes"]): + c, byaw, btilt = self._pose2d(b["name"]) + d = np.array([[np.cos(byaw), np.sin(byaw)], [-np.sin(byaw), np.cos(byaw)]]) @ (p[:2] - c[:2]) + out = np.maximum(np.abs(d) - np.array(b["inner"]) / 2, 0.0) + dist = float(np.linalg.norm(out)) + if best is None or dist < best[0]: + best = (dist, j, c, byaw, btilt) + dist, j, c, byaw, btilt = best + b = inst["boxes"][j] + a_in, b_in = b["inner"] + floor_top = c[2] - BOX_HALF_H + FLOOR_T + height = float(p[2] - PT / 2 - floor_top) # phone bottom above the box floor + in_opening = dist < 1e-9 + on_floor = height < 0.004 and tilt < 5.0 + success = bool(in_opening and on_floor and not held and btilt < 10.0) + where = self.box_label(inst, j) # relative description only: no absolute coordinates in feedback + # footprint of the phone (as it lies now) against the opening of that box + dl = yaw - byaw + cs, sn = abs(np.cos(dl)), abs(np.sin(dl)) + L = PL + 2 * inst.get("cap", 0.0) # the capped phone + over_long = L * cs + PW * sn - a_in + over_short = L * sn + PW * cs - b_in + along_long = "length" if cs >= sn else "width" + fb = dict(box=j, box_xy=[round(float(c[0]), 2), round(float(c[1]), 2)], along_long=along_long, + over_long_cm=round(100 * over_long, 1) if over_long > 0.001 else None, + over_short_cm=round(100 * over_short, 1) if over_short > 0.001 else None) + res = dict(success=success, box=j, box_kind=b["kind"], height_cm=round(100 * height, 2), + tilt_deg=round(tilt, 1), held=held, phone_xy=[float(p[0]), float(p[1])], feedback=fb) + if held: + res["detail"] = "The phone is still in the gripper." + res["failure"] = "held" + return res + if dist > 0.02 or (not in_opening and p[2] < envs.TABLE_Z + PT / 2 + 0.006): + res["detail"] = (f"The phone is not in any box: it is lying on the table, about {100 * dist:.0f} cm " + f"outside the opening of {where}.") + res["failure"] = "table" + return res + if success: + res["detail"] = f"The phone is lying flat on the bottom of {where}." + res["failure"] = None + return res + pose_txt = ("lying flat on top of the walls" if tilt < 5.0 else + f"tilted about {tilt:.0f} degrees with one end down inside the box") + txt = f"The phone did not go in: it is resting on the walls of {where}, {pose_txt}." + dim_l = "long" if along_long == "length" else "wide" + dim_s = "wide" if along_long == "length" else "long" + if fb["over_long_cm"]: + txt += f" It is about {fb['over_long_cm']:.1f} cm too {dim_l} for that box along the box's long side." + if fb["over_short_cm"]: + txt += f" It is about {fb['over_short_cm']:.1f} cm too {dim_s} for that box along the box's short side." + if not fb["over_long_cm"] and not fb["over_short_cm"]: + txt += " Its footprint is smaller than the opening, but it was not lined up with the box and caught on the rim." + res["detail"] = txt + res["failure"] = "rim" + return res + + @staticmethod + def box_label(inst, j): + """Name box j by its place among the boxes in robot-centric terms (left = +y = the robot's left).""" + ys = [b["xy"][1] for b in inst["boxes"]] + xs = [b["xy"][0] for b in inst["boxes"]] + n = len(ys) + order = sorted(range(n), key=lambda i: -ys[i]) # robot's left first + r = order.index(j) + close = [i for i in range(n) if i != j and abs(ys[i] - ys[j]) < 0.04] + if close: # boxes side by side in y: tell them apart by distance from the robot + nearer = all(xs[j] < xs[i] for i in close) + return f"the box {'nearest to' if nearer else 'farthest from'} the robot among those at the same left-right position" + if r == 0: + return "the box furthest to the robot's left (+y)" + if r == n - 1: + return "the box furthest to the robot's right (-y)" + return "the middle box (between the others, left to right)" + + # ------------------------------------------------------------ execution + def execute(self, inst, params): + """params: box (index into inst['boxes']), place_yaw (world yaw of the phone's long side when released). + Optional (tolerance checks only): dx / dy = release offset of the phone centre from the box centre + along the box's long / short axis (m), drop = height of the phone bottom above the rim (m).""" + sk, env = self.sk, self.env + px, py = inst["phone_xy"] + zc = envs.TABLE_Z + PT / 2 + g0 = wrap_half(inst["phone_yaw"]) # fingers close across the phone's width + sk.set_gripper(False, steps=5) + sk.move_to([px, py, zc + 0.10], yaw=g0) + sk.move_to([px, py, zc + 0.001], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([px, py, Z_CARRY], speed=0.25) + b = inst["boxes"][int(params["box"])] + c, s = np.cos(b["yaw"]), np.sin(b["yaw"]) + dx, dy = params.get("dx", 0.0), params.get("dy", 0.0) + bx, by = b["xy"][0] + c * dx - s * dy, b["xy"][1] + s * dx + c * dy + sk.move_to([bx, by, Z_CARRY], yaw=wrap_half(params["place_yaw"])) + # put the phone's centre (not the gripper's) over the box centre: compensates in-hand slip + off = envs.obj_pos(env, "phone_1") - sk.eef_pos() + drop = params.get("drop", DROP) + sk.move_to([bx - off[0], by - off[1], RIM_Z + max(0.05, drop + 0.01) - off[2]], tol=0.003) + tgt = self._servo_phone([bx, by], RIM_Z + drop) + sk.grip = -1.0 # open while holding the arm at a fixed target (Skills.hold re-anchors and drifts) + self._hold_at(tgt, 12) + sk.move_to([tgt[0], tgt[1], RIM_Z + 0.10]) + sk.move_to(list(PARK), yaw=0.0) + + def _hold_at(self, target, steps): + sk = self.sk + R = sk._R() + for _ in range(steps): + sk._act(np.asarray(target) - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip) + + def _servo_phone(self, xy, z_bottom, max_steps=60, tol=0.0015): + """Closed-loop: move the gripper until the held phone's centre is over xy and its bottom at z_bottom. + Returns the final gripper target.""" + sk = self.sk + R = sk._R() + goal = np.array([xy[0], xy[1], z_bottom + PT / 2]) + tgt = e_prev = sk.eef_pos() + for i in range(max_steps): + ph, e = envs.obj_pos(self.env, "phone_1"), sk.eef_pos() + if i >= 8 and np.linalg.norm(ph - goal) < tol and np.linalg.norm(e - e_prev) < 0.0005: + break + tgt = goal - (ph - e) + sk._act(tgt - e, _rot_err(R, sk.eef_mat()), sk.grip) + e_prev = e + return tgt + + # ------------------------------------------------------------ scripted policies + def _naive_yaw(self, inst, j): + """keep the phone's orientation, only snap it to the nearest axis of box j""" + p = inst["phone_yaw"] + return float(p + wrap_quarter(inst["boxes"][j]["yaw"] - p)) + + def default_params(self, inst): + """v3 prior: careful size comparison against the phone as it looks (exact visible sizes: the prior models the + trap; perception noise is only given to the adaptive learner) -- the box with the most room to spare in its + tighter direction, i.e. "snug" by construction; phone's long side along the box's long side""" + marg = [min(b["inner"][0] - PL, b["inner"][1] - PW) for b in inst["boxes"]] + j = int(np.argmax(marg)) + return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"])) + + def nearest_params(self, inst): + """v2 prior (kept for reference): nearest box, lined up""" + d = [np.hypot(b["xy"][0] - inst["phone_xy"][0], b["xy"][1] - inst["phone_xy"][1]) for b in inst["boxes"]] + j = int(np.argmin(d)) + return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"])) + + def oracle_params(self, inst): + j = inst["fit"] + return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"])) + + def blind_params(self, inst, attempt, rng): + """no history: a random box (may repeat), lined up like the prior""" + j = int(rng.integers(N_BOXES)) + return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"])) + + def naive_keep_yaw_params(self, inst): + """old prior (kept for reference): nearest box, keep the phone's orientation""" + d = [np.hypot(b["xy"][0] - inst["phone_xy"][0], b["xy"][1] - inst["phone_xy"][1]) for b in inst["boxes"]] + j = int(np.argmin(d)) + return dict(box=j, place_yaw=self._naive_yaw(inst, j)) + + def adapt_params(self, inst, history): + """Scripted learner on F2 feedback. + + Sees the boxes with noisy size estimates (inst['_perc'], sigma = PERC_SIGMA) but does not know the + phone's size. Each 'too long / too wide by X along the box's long / short side' message gives an + estimate of the phone's length or width (perceived box dimension + X). It then picks an untried box + that is big enough in every estimated dimension (preferring the biggest in the still-unknown one) and + lines the phone's long side up with the box's long side. + """ + perc = inst["_perc"] + L_est = W_est = None + tried_aligned = set() + for h in history: + o = h["outcome"] + fb = o.get("feedback") or {} + if o.get("failure") != "rim": + continue + j = fb["box"] + a, b = perc[j] + if fb["along_long"] == "length": + if fb["over_long_cm"] or fb["over_short_cm"]: # a size verdict on this box + tried_aligned.add(j) + if fb["over_long_cm"]: + L_est = max(L_est or 0.0, a + fb["over_long_cm"] / 100) + if fb["over_short_cm"]: + W_est = max(W_est or 0.0, b + fb["over_short_cm"] / 100) + else: + if fb["over_short_cm"]: + L_est = max(L_est or 0.0, b + fb["over_short_cm"] / 100) + if fb["over_long_cm"]: + W_est = max(W_est or 0.0, a + fb["over_long_cm"] / 100) + thr = 0.002 + cands = [] + for j, (a, b) in enumerate(perc): + if j in tried_aligned: + continue + mL = None if L_est is None else a - L_est + mW = None if W_est is None else b - W_est + feasible = (mL is None or mL > thr) and (mW is None or mW > thr) + if mL is not None and mW is not None: + key = min(mL, mW) + elif mL is not None: + key = b + elif mW is not None: + key = a + else: + key = a * b + cands.append((feasible, key, j)) + if not cands: + j = int(np.argmax([a * b for a, b in perc])) + else: + j = max(cands)[2] + return dict(box=int(j), place_yaw=float(inst["boxes"][j]["yaw"])) + + def elim_params(self, inst, history, rng): + """sensitivity variant: uses the feedback only to learn the orientation (always lines the phone up + after the first attempt) and to never retry a box that got a size verdict; picks among the remaining + boxes at random, i.e. no size reasoning / perception.""" + bad = set() + for h in history: + fb = h["outcome"].get("feedback") or {} + if h["outcome"].get("failure") == "rim" and fb.get("along_long") == "length" and ( + fb.get("over_long_cm") or fb.get("over_short_cm")): + bad.add(int(fb["box"])) + left = [j for j in range(N_BOXES) if j not in bad] or list(range(N_BOXES)) + j = int(rng.choice(left)) + return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"])) + + EXTRA_KINDS = ("elim",) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + if kind not in self.EXTRA_KINDS: + return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt) + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + if a == 0: + params = self.default_params(inst) + else: + params = self.elim_params(inst, history, rng) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"]: + break + return history + + +# ---------------------------------------------------------------- physical validity checks +def physics_check(seed0=1000, n=20, out=None): + """Every (box, orientation) pair on each instance, released centred from DROP above the rim. + Expect success iff the box is the fitting one and the phone's long side is along the box's long side.""" + import json + task = FitContainer() + rows = [] + for seed in range(seed0, seed0 + n): + inst = task.sample_instance(seed) + for j, b in enumerate(inst["boxes"]): + for orient in ("aligned", "crossed"): + task.reset_instance(inst) + task.execute(inst, dict(box=j, place_yaw=float(b["yaw"] + (0.0 if orient == "aligned" else np.pi / 2)))) + o = task.outcome(inst) + rows.append(dict(seed=seed, box=j, kind=b["kind"], inner_cm=[round(100 * v, 2) for v in b["inner"]], + orient=orient, success=o["success"], expect=bool(j == inst["fit"] and orient == "aligned"), + failure=o["failure"], height_cm=o["height_cm"], tilt_deg=o["tilt_deg"], detail=o["detail"])) + r = rows[-1] + print(f"seed {seed} box {j} {b['kind']:6s} {orient:7s} succ={r['success']} h={r['height_cm']} " + f"tilt={r['tilt_deg']}" + ("" if r["success"] == r["expect"] else " <-- MISMATCH"), flush=True) + if out: + with open(out, "w") as f: + json.dump(rows, f, indent=1) + print("total", len(rows), "mismatches", sum(r["success"] != r["expect"] for r in rows)) + return rows + + +def stress_check(seed=1002, out=None): + """Release errors (offset / yaw / drop height) at the edges of the size ranges: the tightest fitting box + (+1.0 cm in both directions) and boxes only 0.5 cm too short / too narrow.""" + import copy + import json + task = FitContainer() + base = task.sample_instance(seed) + j = base["fit"] + rows = [] + for name, a, b in [("fit_min", PL + 0.010, PW + 0.010), ("short_0.5", PL - 0.005, PW + 0.010), + ("narrow_0.5", PL + 0.010, PW - 0.005)]: + for dx, dy, dyaw, drop in [(0, 0, 0, DROP), (0.004, 0, 0, DROP), (0, 0.004, 0, DROP), (0.007, 0, 0, DROP), + (0, 0, 3, DROP), (0, 0, 6, DROP), (0, 0, 0, 0.05), (0.004, 0.003, 3, 0.05)]: + inst = copy.deepcopy(base) + inst["boxes"][j]["inner"] = [a, b] + task.reset_instance(inst) + task.execute(inst, dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"] + np.radians(dyaw)), + dx=dx, dy=dy, drop=drop)) + o = task.outcome(inst) + rows.append(dict(case=name, inner_cm=[round(a * 100, 2), round(b * 100, 2)], dx_mm=dx * 1000, + dy_mm=dy * 1000, dyaw_deg=dyaw, drop_cm=drop * 100, success=o["success"], + height_cm=o["height_cm"], tilt_deg=o["tilt_deg"], detail=o["detail"])) + print(f"{name:11s} dx={dx * 1000:.0f}mm dy={dy * 1000:.0f}mm dyaw={dyaw}deg drop={drop * 100:.1f}cm -> " + f"succ={o['success']} h={o['height_cm']} tilt={o['tilt_deg']} | {o['detail']}", flush=True) + if out: + with open(out, "w") as f: + json.dump(rows, f, indent=1) + return rows + + +if __name__ == "__main__": + # python -m lffbench.tasks.l4_fit physics results/l4_fit_container/physics_check.json + # python -m lffbench.tasks.l4_fit stress results/l4_fit_container/stress_check.json + import sys + if sys.argv[1] == "physics": + physics_check(out=sys.argv[2] if len(sys.argv) > 2 else None) + elif sys.argv[1] == "stress": + stress_check(out=sys.argv[2] if len(sys.argv) > 2 else None) diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/l5_slippery_lift.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/l5_slippery_lift.py new file mode 100644 index 0000000000000000000000000000000000000000..1a533e41595c29d413eb2287843cbc50afe7d0dc --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/l5_slippery_lift.py @@ -0,0 +1,262 @@ +"""L5-B slippery_lift: pick up a heavy, slippery metal bar and hold it level. + +Category dynamics_adaptation (L5): "figure out how this object moves". + +Scene: one long steel-grey bar (4 x 28 x 4 cm, lying along the robot's left-right axis) on the table. It looks +perfectly uniform, but a heavy slug is hidden inside it at an unknown position, so its centre of mass sits +e = 2.5-7 cm from the bar's midpoint, towards the left or the right end. The bar is heavy (0.8-1.2 kg) and its +surface is slippery (finger friction 0.40-0.60): the two finger pads can hold its weight, but they cannot hold +much torque. + +Why the prior fails. The natural grasp is across the bar at its midpoint. With the centre of mass a few cm to +one side, gravity twists the bar in the pads as soon as it is lifted: the heavy end swings down and the bar +ends up hanging tilted by ~10-50 deg (measured). Slow lifting does not help (the torque is static). + +What has to be learned. Which end sank tells on which side of the grasp the centre of mass lies; the grasp +has to move towards that end until it is within ~1.5 cm of the hidden centre of mass (measured window). The +tilt magnitude saturates, so the distance has to be found by bracketing over a few attempts. + +Measured physics (2026-10-07, `l5dyn/bar_win.py`): mass 0.8-1.2 kg, mu 0.4-0.6, lift 15 cm at 0.15 m/s: +|grasp - COM| <= 1.0 cm -> tilt <= 2 deg; 1.5 cm -> 0-41 deg; >= 2 cm -> mostly 30-50 deg; the tilt does not +creep during a 3 s hold. mu 0.8 gave non-monotone tilts and is not used; mu 0.3 + 1.3 kg slips out entirely. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +BAR = "bar_1" +HALF = (0.02, 0.14, 0.02) # 4 (x) x 28 (y) x 4 (z) cm, long axis along world y +_SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"' +W_FRAC = 0.6 # fraction of the bar's mass in the hidden slug +W_HALF = 0.015 # slug half size (for its inertia) +E_MIN, E_MAX = 0.025, 0.070 # |COM offset| from the bar's midpoint (m) +LIFT_MIN = 0.10 # the bar's lowest point must be this high above the table +TILT_MAX = 8.0 # deg +Z_GRASP = envs.TABLE_Z + HALF[2] # gripper site at the bar's mid height (finger tips 0.7 cm above the table) +Z_LIFT = Z_GRASP + 0.15 +YAW_ACROSS = np.pi / 2 # jaws close along world x, i.e. across the bar + + +def weighted_box_xml(name, half, rgba, mass=1.0, friction=(1.0, 0.005, 0.0001)): + """Box with an explicit inertial. Its pos is off-centre at compile time so MuJoCo keeps + body_sameframe = 0 / body_simple = 0 and honours the per-instance body_ipos set in apply_instance.""" + I = [mass / 3 * (half[1] ** 2 + half[2] ** 2), mass / 3 * (half[0] ** 2 + half[2] ** 2), + mass / 3 * (half[0] ** 2 + half[1] ** 2)] + g = (f' \n' + f' \n' + f' ') + return _wrap(name, g, half[2], float(np.hypot(half[0], half[1]))) + + +def set_hidden_weight(env, obj, half, mass, w_frac, w_pos, w_half=W_HALF): + """Uniform shell of mass (1 - w_frac) * mass plus a hidden cube slug of w_frac * mass at w_pos (body frame). + Sets the body's mass, centre of mass and inertia; returns the centre of mass (body frame).""" + m = env.sim.model + bid = envs.body_id(env, obj) + ms, mw = (1 - w_frac) * mass, w_frac * mass + w_pos = np.asarray(w_pos, float) + c = mw * w_pos / mass + hx, hy, hz = half + + def par(mm, r): # parallel-axis terms (diagonal) + return mm * np.array([r[1] ** 2 + r[2] ** 2, r[0] ** 2 + r[2] ** 2, r[0] ** 2 + r[1] ** 2]) + + I = (ms / 3 * np.array([hy ** 2 + hz ** 2, hx ** 2 + hz ** 2, hx ** 2 + hy ** 2]) + par(ms, -c) + + mw / 6 * (2 * w_half) ** 2 * np.ones(3) + par(mw, w_pos - c)) + m.body_mass[bid] = mass + m.body_ipos[bid] = c + m.body_iquat[bid] = [1.0, 0.0, 0.0, 0.0] + m.body_inertia[bid] = I + envs.refit_bounds(env, bid) # the collision BVH lives in the inertial frame (envs.refit_bounds) + return c + + +def bar_axis(env): + """World direction of the bar's long axis (body y).""" + return env.sim.data.body_xmat[envs.body_id(env, BAR)].reshape(3, 3)[:, 1].copy() + + +def bar_tilt_deg(env): + """Signed tilt of the bar's long axis from horizontal; > 0: the bar's +y end is lower.""" + ax = bar_axis(env) + if ax[1] < 0: # orient the axis towards the robot's left so the sign is about world left/right + ax = -ax + return float(np.degrees(np.arcsin(np.clip(-ax[2], -1.0, 1.0)))) + + +def side_words(sign): + return "left (+y)" if sign > 0 else "right (-y)" + + +class BarSkills(Skills): + """Skills that record where along the bar the jaws closed, whoever drives them (scripted or agent).""" + + def __init__(self, env, bias=None, recorder=None): + super().__init__(env, bias=bias, recorder=recorder) + self.closes = [] + self.zmax = float(envs.obj_pos(env, BAR)[2]) + self.z0 = self.zmax + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.zmax = max(self.zmax, float(envs.obj_pos(self.env, BAR)[2])) + + def set_gripper(self, close, steps=15): + rep = super().set_gripper(close, steps) + if close: + c = envs.obj_pos(self.env, BAR) + ax = bar_axis(self.env) + if ax[1] < 0: + ax = -ax + along = float((self.eef_pos() - c) @ ax) # + : grasp on the left (+y) side of the midpoint + self.closes.append(dict(along=along, holding=self.holding(BAR), step=self.n_steps)) + return rep + + +@register_task +class SlipperyLift(LFFTask): + name = "l5_slippery_lift" + level = "L5" + category = "dynamics_adaptation" + capabilities = ("Perceive", "Reason", "Utilize") + protocol = "cross" + instruction = ("Pick up the metal bar and hold it level (tilted less than 8 degrees), with its lowest point at " + "least 10 cm above the table. Keep holding it when you finish.") + instruction_indirect = ("Pick up the long grey rod lying on the table and hold it horizontal (tilted less than 8 " + "degrees), with its lowest point at least 10 cm above the table. Keep holding it when you " + "finish.") + + # ------------------------------------------------------------ scene + def make_bddl(self): + bar = register_generated("LffSteelBar", weighted_box_xml("lff_steel_bar", HALF, (0.52, 0.55, 0.58, 1.0))) + objs = [(BAR, bar, "bar_region", (-0.11, -0.01, -0.09, 0.01))] + return write_bddl(self.name, "pick up the bar and hold it level", objs) # BDDL cannot parse parentheses + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + e = float(rng.choice([-1.0, 1.0]) * rng.uniform(E_MIN, E_MAX)) + return dict(seed=int(seed), + bar_xy=[float(rng.uniform(-0.12, -0.03)), float(rng.uniform(-0.06, 0.06))], + com_offset=e, # along the bar, + = towards the robot's left (+y) end + mass=float(rng.uniform(0.8, 1.2)), + mu=float(rng.uniform(0.40, 0.60))) + + def apply_instance(self, inst): + x, y = inst["bar_xy"] + envs.set_obj_pose(self.env, BAR, [x, y, envs.TABLE_Z + HALF[2] + 0.001]) + envs.set_friction(self.env, BAR, inst["mu"]) + set_hidden_weight(self.env, BAR, HALF, inst["mass"], W_FRAC, [0.0, inst["com_offset"] / W_FRAC, 0.0]) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = BarSkills(self.env, bias=self.skill_bias(inst), recorder=recorder) + return self.sk + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + sk = self.sk + sk.hold(30) # 1.5 s with the gripper as the agent left it (envs.settle would open the jaws) + held = sk.holding(BAR) + tilt = bar_tilt_deg(self.env) + bottom = envs.obj_min_z(self.env, BAR) - envs.TABLE_Z + lifted = (sk.zmax - sk.z0) > 0.03 + close = next((c for c in reversed(sk.closes) if c["holding"]), sk.closes[-1] if sk.closes else None) + success = bool(held and abs(tilt) <= TILT_MAX and bottom >= LIFT_MIN) + out = dict(success=success, held=bool(held), tilt_deg=round(tilt, 1), bottom_cm=round(100 * bottom, 1), + grasp_along=None if close is None else round(close["along"], 4)) + g = "" + if close is not None and close["holding"]: + a = close["along"] + g = (f" You grasped the bar {100 * abs(a):.1f} cm to the {side_words(a)} of its midpoint." + if abs(a) >= 0.0005 else " You grasped the bar at its midpoint.") + tilt_txt = (f"hangs tilted by {abs(tilt):.0f} degrees, its {side_words(tilt).split()[0]} end lower than its " + f"{side_words(-tilt).split()[0]} end") + if success: + out["failure"] = None + detail = f"The bar is held level (tilt {abs(tilt):.0f} degrees), {100 * bottom:.0f} cm above the table." + g + elif held and abs(tilt) > TILT_MAX: + out["failure"] = "tilted" + detail = ("The bar did not stay level: it rotated in the gripper while it was being lifted and now " + f"{tilt_txt}." + g) + if bottom < LIFT_MIN: + detail += f" Its lowest point is {100 * bottom:.0f} cm above the table." + elif held: + out["failure"] = "too_low" + detail = (f"The bar is held level (tilt {abs(tilt):.0f} degrees) but its lowest point is only " + f"{100 * bottom:.0f} cm above the table." + g) + elif lifted: + out["failure"] = "dropped" + detail = ("The bar was lifted but slipped out of the gripper and fell back onto the table " + f"(it now lies tilted by {abs(tilt):.0f} degrees)." + g) + elif close is None: + out["failure"] = "no_grasp" + detail = "The gripper never closed on the bar; it is still lying on the table." + else: + out["failure"] = "no_grasp" + detail = "The gripper closed but did not catch the bar; it is still lying on the table." + out["detail"] = detail + out["detail_indirect"] = detail.replace("bar", "rod") + return out + + def feedback(self, inst, out, level="F2", indirect=False): + if indirect and level == "F2": + out = dict(out, detail=out.get("detail_indirect", out["detail"])) + return super().feedback(inst, out, level) + + # ------------------------------------------------------------ scripted execution (cross protocol) + def execute(self, inst, params): + """Grasp across the bar at `along` (m from the visible midpoint, + = left / +y) and lift 15 cm.""" + sk = self.sk + c = envs.obj_pos(self.env, BAR) # visible bar pose (perfect perception) + ax = bar_axis(self.env) + if ax[1] < 0: + ax = -ax + g = c + ax * float(params["along"]) + sk.set_gripper(False, steps=5) + sk.move_to([g[0], g[1], Z_GRASP + 0.10], yaw=YAW_ACROSS) + sk.move_to([g[0], g[1], Z_GRASP], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([g[0], g[1], Z_LIFT], speed=0.15, tol=0.004, max_steps=300) + + def default_params(self, inst): + return dict(along=0.0) + + def oracle_params(self, inst): + return dict(along=float(inst["com_offset"])) + + MARGIN = 0.008 # a tilt towards +y at grasp g means COM > g + MARGIN (window is ~+-1.5 cm) + STEP = 0.030 # first step towards the heavy end when only one side is bounded + + def adapt_params(self, inst, history): + """Bracketing on the grasp point: the end that sank is the heavy side of the last grasp.""" + lo, hi = -HALF[1], HALF[1] + lo_set = hi_set = False + for h in history: + o = h["outcome"] + g = o["grasp_along"] if o.get("grasp_along") is not None else h["params"]["along"] + if o.get("failure") == "tilted" or (o.get("failure") == "dropped" and abs(o["tilt_deg"]) > 3): + if o["tilt_deg"] > 0: # left end sank -> COM left of the grasp + lo, lo_set = max(lo, g + self.MARGIN), True + else: + hi, hi_set = min(hi, g - self.MARGIN), True + last = history[-1]["params"]["along"] + if lo_set and hi_set: + a = 0.5 * (lo + hi) + elif lo_set: + a = lo + self.STEP - self.MARGIN + elif hi_set: + a = hi - self.STEP + self.MARGIN + else: # no direction information (e.g. too low): repeat + a = last + return dict(along=float(np.clip(a, -0.12, 0.12))) + + def blind_params(self, inst, attempt, rng): + return dict(along=float(rng.normal(0.0, 0.01))) diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/l6_swap.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/l6_swap.py new file mode 100644 index 0000000000000000000000000000000000000000..1794c23e23f238abf25697524800263760fccea7 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/l6_swap.py @@ -0,0 +1,466 @@ +"""L6-A swap_interrupt: swap two items between identical pads; the second carry is interrupted by a slip. + +Scene: four identical dark round pads (flat markers, no collision). The cream cheese (X) starts on pad A, +the butter (Y) on pad B, pads C and D are empty. Pad positions, which pad is which and the drop spot are +random per seed. Goal: X on B and Y on A. + +Standard procedure: X: A -> C (temporary), Y: B -> A, X: C -> B. During the second carry (whichever item is +carried while the other one has already left its start pad), the carried item "slips": the gripper opens +and the item lands on the table at a hidden spot that is on no pad. Afterwards X sits on C, Y lies on the +table and A, B, D are empty -- the current image no longer shows which empty pad was whose. The information +needed to finish ("what has been done, where did each item start") is only in the agent's own history. + +The drop spot is placed next to a *lure* pad: the spare pad ("spare", 50 %), the carried item's own start pad +("source", 25 %) or its true destination ("dest", 25 %). So "put it on the nearest pad" is usually wrong and +proximity is close to uninformative; a stronger bias towards the start pad would open a memoryless shortcut +(tidy both items onto their nearest pads = undo, then swap again), see the task card. + +Protocol: within (one episode, no reset). Attempt granularity: an attempt is everything the agent does until +it declares the task done; after each attempt the outcome is measured (F1/F2 feedback) and, if it failed, the +agent continues from the current state. The slip is injected once per episode, inside attempt 1 (it is an +in-attempt failure event, reported immediately: see `drain_events`). Scripted references: + + oracle knows the true start layout; after the slip puts Y on A and X on B. + adaptive saves the start layout from its first frame (Save), recalls it after the slip (Retrieve) and + finishes the swap from the right step (Utilize); later attempts fix residual misplacements from + memory + F2 feedback. + naive memoryless continuation (one attempt): after the slip it re-plans from the current frame only -- + the stray item goes to the nearest empty pad, the item that is still on a pad goes to the nearest + remaining empty pad. + blind memoryless restart (k attempts): does not know which step it was at; tidies the stray item onto + the nearest empty pad and then performs the whole swap again from the current frame; every later + attempt again swaps the two items (repeated swap, cf. RMBench). + blind_continue (extra control, not in the acceptance table) attempt 1 = naive, later attempts = swap again. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _wrap, register_generated +from ..task_base import LFFTask, register_task + +N_PADS = 4 +PAD_R = 0.055 # pad radius (11 cm discs); items are 8 x 4.3 x 1.8 cm boxes lying flat +PAD_HALF_T = 0.0008 +PAD_RGBA = (0.22, 0.24, 0.28, 1.0) +SUCC_R = 0.04 # item centre within 4 cm of the pad centre counts as "on that pad" for success +PAD_MIN_DIST = 0.17 +PAD_REGION = (-0.26, 0.04, -0.25, 0.25) # x0, x1, y0, y1 (world) +PAD_REACH = 0.71 # max horizontal distance of a pad centre from the robot base +DROP_REGION = (-0.31, 0.07, -0.30, 0.30) +# beyond ~0.75 m from the base the arm ends up fully stretched (elbow at its joint limit) and the OSC gets stuck +MAX_REACH = 0.73 +DROP_CLEAR = PAD_R + 0.05 # drop centre this far from every pad centre -> item fully off the pads +LURE_MARGIN = 0.03 # the lure pad is nearer to the drop spot than any other pad by at least this much +GRASP_DZ = 0.012 # gripper-site height above the table for a top-down grasp of the flat boxes +LIFT = 0.15 +BASE_X = -0.66 # robot base x (world); base-frame coordinates = (x - BASE_X, y) +LURE_P = (("source", 0.25), ("spare", 0.5), ("dest", 0.25)) + +X, Y = "cream_cheese_1", "butter_1" +NAME = {X: "cream cheese", Y: "butter"} +PADS = [f"pad_{i + 1}" for i in range(N_PADS)] + + +def _pad_xml(model_name): + c = " ".join(f"{v:.3f}" for v in PAD_RGBA) + g = (f' \n' + f' ') + # flat marker without collisions: gravity compensation keeps it from sinking through the table + return _wrap(model_name, g, PAD_HALF_T, PAD_R).replace('', + '') + + +def _yaw_of(env, obj): + R = env.sim.data.body_xmat[envs.body_id(env, obj)].reshape(3, 3) + yaw = float(np.arctan2(R[1, 0], R[0, 0])) # long axis of the boxes = body x + return (yaw + np.pi / 2) % np.pi - np.pi / 2 # boxes are symmetric under pi + + +def drop_spot(pads, src, dest, other_xy, lure, phase, dist): + """Geometry of the injected drop. pads: (N,2); src / dest: start pads of the carried / other item; + other_xy: current xy of the other item. Returns (xy, lure_pad) or (None, None).""" + pads = np.asarray(pads, float) + rest = [i for i in range(len(pads)) if i not in (src, dest)] + # spare = an empty pad that is neither start pad and not the one the other item is parked on + occ = [i for i in rest if np.linalg.norm(pads[i] - other_xy) < PAD_R] + spare_c = [i for i in rest if i not in occ] or rest + spare = max(spare_c, key=lambda i: np.linalg.norm(pads[i] - other_xy)) + lp = {"source": src, "dest": dest, "spare": spare}[lure] + for d in (dist, dist + 0.01, dist - 0.01, dist + 0.02): + for ang in phase + np.linspace(0, 2 * np.pi, 48, endpoint=False): + xy = pads[lp] + d * np.array([np.cos(ang), np.sin(ang)]) + if not (DROP_REGION[0] <= xy[0] <= DROP_REGION[1] and DROP_REGION[2] <= xy[1] <= DROP_REGION[3]): + continue + if np.hypot(xy[0] - BASE_X, xy[1]) > MAX_REACH: + continue + dd = np.linalg.norm(pads - xy, axis=1) + if dd.min() < DROP_CLEAR or np.linalg.norm(xy - other_xy) < 0.12: + continue + if np.any(np.delete(dd, lp) < dd[lp] + LURE_MARGIN): + continue + return xy, int(lp) + return None, None + + +@register_task +class SwapInterrupt(LFFTask): + name = "l6_swap_interrupt" + level = "L6" + category = "procedural_memory" + capabilities = ("Perceive", "Save", "Retrieve", "Utilize") + protocol = "within" + max_attempts = 5 + instruction = ("Swap the positions of the cream cheese and the butter: each must end up on the round pad " + "where the other one started. You may use the empty pads as temporary spots.") + instruction_indirect = ("Swap the positions of the pale blue box with the oval logo and the red-and-yellow " + "box: each must end up on the round pad where the other one started. You may use the " + "empty pads as temporary spots.") + inject = True # set False to run the same scene without the slip (sanity check) + + # ------------------------------------------------------------ scene + def make_bddl(self): + cats = [register_generated(f"LffSwapPad{L}", _pad_xml(f"lff_swap_pad_{L.lower()}")) for L in "ABCD"] + objs = [(X, "cream_cheese", "cc_region", (-0.21, -0.21, -0.19, -0.19)), + (Y, "butter", "bu_region", (-0.21, 0.19, -0.19, 0.21)), + (PADS[0], cats[0], "p1_region", (0.05, -0.21, 0.07, -0.19)), + (PADS[1], cats[1], "p2_region", (0.05, 0.19, 0.07, 0.21)), + (PADS[2], cats[2], "p3_region", (-0.06, -0.01, -0.04, 0.01)), + (PADS[3], cats[3], "p4_region", (-0.31, -0.01, -0.29, 0.01))] + return write_bddl(self.name, self.instruction, objs) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + for _ in range(1000): + pads = [] + while len(pads) < N_PADS: + p = np.array([rng.uniform(*PAD_REGION[:2]), rng.uniform(*PAD_REGION[2:])]) + if np.hypot(p[0] - BASE_X, p[1]) > PAD_REACH: + continue + if all(np.linalg.norm(p - q) >= PAD_MIN_DIST for q in pads): + pads.append(p) + pads = np.array(pads) + x_pad, y_pad = 0, 1 # pad order is already random + u, acc = rng.uniform(), 0.0 + for lure, pr in LURE_P: + acc += pr + if u < acc: + break + phase, dist = float(rng.uniform(0, 2 * np.pi)), float(rng.uniform(0.115, 0.14)) + # canonical execution: X parked on the empty pad nearest to its start pad, then Y is carried + empt = [i for i in range(N_PADS) if i not in (x_pad, y_pad)] + buf = min(empt, key=lambda i: np.linalg.norm(pads[i] - pads[x_pad])) + xy, lp = drop_spot(pads, y_pad, x_pad, pads[buf], lure, phase, dist) + if xy is None: + continue + return dict(seed=int(seed), pads=pads.round(4).tolist(), x_pad=x_pad, y_pad=y_pad, + yaw_x=float(rng.uniform(-0.3, 0.3)), yaw_y=float(rng.uniform(-0.3, 0.3)), + lure=lure, drop_phase=phase, drop_dist=dist, drop_yaw=float(rng.uniform(-1.4, 1.4)), + trigger_dist=float(rng.uniform(0.05, 0.10)), + canonical_buffer=int(buf), canonical_drop_xy=xy.round(4).tolist()) + raise RuntimeError("could not sample a layout") + + def apply_instance(self, inst): + for i, p in enumerate(inst["pads"]): + envs.set_obj_pose(self.env, PADS[i], [p[0], p[1], envs.TABLE_Z + PAD_HALF_T + 0.0001]) + envs.place_upright(self.env, X, inst["pads"][inst["x_pad"]], inst["yaw_x"]) + envs.place_upright(self.env, Y, inst["pads"][inst["y_pad"]], inst["yaw_y"]) + self.env.sim.forward() + self.slip = None + self.events = [] + self._event_cursor = 0 # for drain_events (harness, per tool call) + self._outcome_cursor = 0 # for outcome (per attempt) + self._inst = inst + + def reset_instance(self, inst, recorder=None): + sk = super().reset_instance(inst) + self._user_recorder = recorder + sk.recorder = self._on_step # slip trigger is checked on every control step + sk.record_every = 1 + self._home = sk.eef_pos() + return sk + + def go_home(self): + """Lift the arm out of the camera's way (end of an attempt).""" + p = self.sk.eef_pos() + self.sk.move_to([p[0], p[1], max(p[2], self._home[2])]) + self.sk.move_to(self._home) + + # ------------------------------------------------------------ slip injection (state triggered) + def _on_step(self, env): + if self.inject and self.slip is None: + self._maybe_slip() + if self._user_recorder is not None and self.sk.n_steps % 4 == 0: + self._user_recorder(env) + + def _maybe_slip(self): + """Fires during the first carry of an item while the other item has already left its start pad, + i.e. the second transport of a swap, whatever order the agent chose.""" + inst, env = self._inst, self.env + pads = np.asarray(inst["pads"]) + start = {X: inst["x_pad"], Y: inst["y_pad"]} + for o, other in ((X, Y), (Y, X)): + p = envs.obj_pos(env, o) + if p[2] < envs.TABLE_Z + 0.05: + continue + if np.linalg.norm(p[:2] - pads[start[o]]) < inst["trigger_dist"]: + continue + q = envs.obj_pos(env, other) + if np.linalg.norm(q[:2] - pads[start[other]]) < PAD_R: + continue + if not self.sk.holding(o): + continue + self._do_slip(o, other, q[:2]) + return + + def _do_slip(self, o, other, other_xy): + inst = self._inst + start = {X: inst["x_pad"], Y: inst["y_pad"]} + args = (inst["pads"], start[o], start[other], other_xy) + xy, lp = drop_spot(*args, inst["lure"], inst["drop_phase"], inst["drop_dist"]) + lure = inst["lure"] + for alt in ("source", "spare", "dest"): # fallback (only if the agent did something unusual) + if xy is not None: + break + xy, lp = drop_spot(*args, alt, inst["drop_phase"], inst["drop_dist"]) + lure = alt + if xy is None: + xy, lp, lure = np.asarray(inst["canonical_drop_xy"]), -1, "fallback" + envs.place_upright(self.env, o, xy, inst["drop_yaw"]) + self.sk.grip = -1.0 # the gripper opens + self.env.sim.forward() + text = f"The {NAME[o]} slipped out of the gripper and fell onto the table." + self.slip = dict(obj=o, xy=[float(v) for v in xy], lure=lure, lure_pad=lp, step=int(self.sk.n_steps)) + self.events.append(dict(step=int(self.sk.n_steps), kind="slip", obj=o, text=text)) + + def drain_events(self): + """Event texts since the last call (for the harness: append to the current tool-call report).""" + ev = self.events[self._event_cursor:] + self._event_cursor = len(self.events) + return [e["text"] for e in ev] + + # ------------------------------------------------------------ perception helpers (what an agent can see) + def pad_xy(self): + return np.array([envs.obj_pos(self.env, p)[:2] for p in PADS]) + + def on_pad(self, o, r=PAD_R): + d = np.linalg.norm(self.pad_xy() - envs.obj_pos(self.env, o)[:2], axis=1) + return int(np.argmin(d)) if d.min() < r else None + + def empty_pads(self): + occ = {self.on_pad(X), self.on_pad(Y)} + return [i for i in range(N_PADS) if i not in occ] + + def _nearest(self, cands, xy): + pads = self.pad_xy() + return min(cands, key=lambda i: np.linalg.norm(pads[i] - np.asarray(xy)[:2])) + + @staticmethod + def _bf(xy): + return f"({xy[0] - BASE_X:.2f}, {xy[1]:+.2f})" + + def pad_label(self, i, cur=None): + """Robot-centric name of pad i relative to the other pads (no coordinates in agent feedback).""" + cur = self.pad_xy() if cur is None else cur + c = cur.mean(axis=0) + fb = "far" if cur[i][0] > c[0] else "near" + lr = "left" if cur[i][1] > c[1] else "right" + same = [j for j in range(len(cur)) if ("far" if cur[j][0] > c[0] else "near") == fb + and ("left" if cur[j][1] > c[1] else "right") == lr] + lab = f"the {fb}-{lr} pad" + if len(same) > 1: # two pads in the same quadrant: tell them apart left to right + order = sorted(same, key=lambda j: -cur[j][1]) + side = "more to the robot's left" if order.index(i) == 0 else "more to the robot's right" + lab += f" ({side} of the two)" + return lab + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + envs.settle(self.env, 20) + pads = np.asarray(inst["pads"]) + target = {X: inst["y_pad"], Y: inst["x_pad"]} + res, ok = {}, True + for o in (X, Y): + p = envs.obj_pos(self.env, o) + dt = float(np.linalg.norm(p[:2] - pads[target[o]])) + resting = bool(envs.TABLE_Z - 0.01 < p[2] < envs.TABLE_Z + 0.05 and not self.sk.holding(o)) + res[o] = dict(xy=[float(p[0]), float(p[1])], on_pad=self.on_pad(o), dist_to_target=dt, resting=resting) + ok = ok and resting and dt <= SUCC_R + # F2 detail: only what is observable now + events of this attempt; nothing about the start layout + parts = [] + cur = self.pad_xy() + for o in (X, Y): + r = res[o] + if r["on_pad"] is not None: + parts.append(f"the {NAME[o]} is on {self.pad_label(r['on_pad'], cur)}") + else: + dd = np.linalg.norm(cur - np.asarray(r["xy"]), axis=1) + d = dd.min() - PAD_R + parts.append(f"the {NAME[o]} is on the table, on no pad " + f"({100 * d:.0f} cm from the edge of {self.pad_label(int(dd.argmin()), cur)})") + emp = [self.pad_label(i, cur) for i in self.empty_pads()] + detail = ("Now " + "; ".join(parts) + "; empty: " + (", ".join(emp) if emp else "none") + + " (left/right = the robot's left/right, near/far = toward/away from the robot).") + new_ev = [e["text"] for e in self.events[self._outcome_cursor:]] + self._outcome_cursor = len(self.events) + if new_ev: + detail = "During this attempt: " + " ".join(new_ev) + " " + detail + return dict(success=bool(ok), items={NAME[o]: res[o] for o in (X, Y)}, + slip=self.slip, detail=detail) + + # ------------------------------------------------------------ motion + def _pick(self, o): + sk = self.sk + for _ in range(2): + p = envs.obj_pos(self.env, o) + sk.grasp_at(p[:2], envs.TABLE_Z + GRASP_DZ, yaw=_yaw_of(self.env, o), lift=LIFT) + if sk.holding(o): + return True + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], envs.TABLE_Z + LIFT]) + return False + + def _move(self, o, pad, log): + """Pick item o and put it on pad `pad`. Returns False if the item slipped on the way.""" + n_ev = len(self.events) + frm = self.on_pad(o) + ok = self._pick(o) + rec = dict(obj=NAME[o], from_pad=frm, to_pad=int(pad), grasped=ok) + log.append(rec) + if not ok: + return True + xy = self.pad_xy()[pad] + sk = self.sk + sk.move_to([xy[0], xy[1], envs.TABLE_Z + GRASP_DZ + LIFT]) # carry (the slip may fire here) + if len(self.events) > n_ev: + rec["slipped"] = True + return False + sk.move_to([xy[0], xy[1], envs.TABLE_Z + GRASP_DZ + 0.004], tol=0.004) + sk.set_gripper(False, steps=12) + sk.move_to([xy[0], xy[1], envs.TABLE_Z + GRASP_DZ + 0.10]) + return True + + def _run(self, moves, log): + """moves: list of (item, pad) computed up front (an open-loop plan). Stops at a slip.""" + for o, pad in moves: + if not self._move(o, pad, log): + return False + return True + + def _swap_now(self, log, rng=None): + """The standard swap of the two items' *current* pads via an empty pad (no memory).""" + a, b = self.on_pad(X), self.on_pad(Y) + empt = self.empty_pads() + if a is None or b is None or not empt: + return + buf = int(rng.choice(empt)) if rng is not None else self._nearest(empt, self.pad_xy()[a]) + self._run([(X, buf), (Y, a), (X, b)], log) + + def _tidy_stray(self, log): + for o in (X, Y): + if self.on_pad(o) is None and self.empty_pads(): + self._move(o, self._nearest(self.empty_pads(), envs.obj_pos(self.env, o)), log) + + def _fixup(self, target, log): + """Move items until each is on its target pad (target: item -> pad index).""" + pads = self.pad_xy() + for _ in range(6): + todo = [o for o in (Y, X) if np.linalg.norm(envs.obj_pos(self.env, o)[:2] - pads[target[o]]) > SUCC_R] + if not todo: + return + free = [o for o in todo if self.on_pad({X: Y, Y: X}[o], r=PAD_R) != target[o]] + if free: + self._move(free[0], target[free[0]], log) + else: # the two items block each other: park one on an empty pad that is no one's target + o = todo[0] + spare = [i for i in self.empty_pads() if i not in target.values()] or self.empty_pads() + self._move(o, self._nearest(spare, envs.obj_pos(self.env, o)), log) + + # ------------------------------------------------------------ scripted references (within protocol) + def _memory(self): + """Save: what the agent sees in its first frame -- which pad (by position) each item starts on.""" + return {X: self.pad_xy()[self.on_pad(X)].tolist(), Y: self.pad_xy()[self.on_pad(Y)].tolist()} + + def saved_memory(self, first): + """What the adaptive policy recalls after the slip (identity; patched by the mismatched-memory control).""" + return first + + def _attempt1(self, kind, inst, mem, rng, first): + log = [] + plan = dict(kind=kind, moves=log) + a = self._nearest(range(N_PADS), first[X]) # the open-loop plan is made from the first frame + b = self._nearest(range(N_PADS), first[Y]) + empt = [i for i in range(N_PADS) if i not in (a, b)] + buf = self._nearest(empt, self.pad_xy()[a]) + plan["plan"] = f"X->{buf}, Y->{a}, X->{b}" + if self._run([(X, buf), (Y, a), (X, b)], log): + plan["recovery"] = "none (no slip)" + return plan + # ---- the carry was interrupted by the slip: recover + if kind == "oracle": # privileged: true start layout + plan["recovery"] = "oracle: true layout" + self._fixup({X: inst["y_pad"], Y: inst["x_pad"]}, log) + elif kind == "adaptive": # Retrieve the saved first frame and the step log; finish from the right step + ta = self._nearest(range(N_PADS), mem[X]) + tb = self._nearest(range(N_PADS), mem[Y]) + plan["recovery"] = f"memory: butter -> pad {ta} (cream cheese's start), cream cheese -> pad {tb}" + self._fixup({X: tb, Y: ta}, log) + elif kind in ("naive", "blind_continue"): # memoryless continuation from the current frame + stray = [o for o in (X, Y) if self.on_pad(o) is None] + parked = [o for o in (X, Y) if self.on_pad(o) is not None] + plan["recovery"] = "current frame: stray item -> nearest empty pad; parked item -> nearest empty pad" + for o in stray: + self._move(o, self._nearest(self.empty_pads(), envs.obj_pos(self.env, o)), log) + for o in parked: + if self.empty_pads(): + self._move(o, self._nearest(self.empty_pads(), envs.obj_pos(self.env, o)), log) + elif kind == "blind": # memoryless restart: tidy up, then the whole swap again + plan["recovery"] = "restart: stray item -> nearest empty pad, then swap again" + self._tidy_stray(log) + self._swap_now(log, rng) + else: + raise ValueError(kind) + return plan + + def _retry(self, kind, inst, mem, rng): + log = [] + plan = dict(kind=kind, moves=log) + if kind == "adaptive": + ta = self._nearest(range(N_PADS), mem[X]) + tb = self._nearest(range(N_PADS), mem[Y]) + plan["recovery"] = "memory + F2: fix items not on their targets" + self._fixup({X: tb, Y: ta}, log) + elif kind in ("blind", "blind_continue"): + plan["recovery"] = "no history: tidy, then swap the two items again" + self._tidy_stray(log) + self._swap_now(log, rng) + else: + raise ValueError(kind) + return plan + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + self.reset_instance(inst) + first = self._memory() + mem = self.saved_memory(first) + history = [] + for a in range(k): + plan = self._attempt1(kind, inst, mem, rng, first) if a == 0 else self._retry(kind, inst, mem, rng) + self.go_home() # "done": the agent declares the attempt finished + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=plan, outcome=out)) + if on_attempt: + on_attempt(a, plan, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history + + # cross-protocol hooks are not used by this task + def default_params(self, inst): + return dict(policy="naive") + + def oracle_params(self, inst): + return dict(policy="oracle") diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/lh_drawer_cabinet.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/lh_drawer_cabinet.py new file mode 100644 index 0000000000000000000000000000000000000000..55c3e05f0c97631b61329c3dee47a318c1f3b5f1 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/lh_drawer_cabinet.py @@ -0,0 +1,1273 @@ +"""LH drawer_cabinet (2026-10-16): tidy the table -- stand two tall bottles on top of a small wooden cabinet, put two +cubes into its open drawer and close the drawer. In 14 of every 20 instances the drawer is a self-closing one: pushed +into the last 8 cm, a strong spring snaps it shut, the light cabinet lurches 2.3-4.2 cm towards the robot, and bottles +already standing on its top fall over (away from the robot, onto the gallery rail at the back of the top). + +Family: long-horizon self-disturbance ("state_restoration"): a later, normal action (closing the drawer) physically +undoes an earlier stage (bottles on the cabinet). The instruction lists the bottles first but fixes no order. The agent +has to see the fallen bottles and stand them up again after the drawer is shut (within an attempt), or learn to put +the cubes in and shut the drawer before it puts the bottles on top (across attempts). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a small wooden cabinet (free body, 18 (x) x 22 (y) x 11 cm, centre 53-56 cm in front of the robot base, front facing + the robot) with a 6 cm gallery rail along the back edge of its top, a 4 cm toe plinth under the drawer and a + back-heavy carcass; its single drawer (inside 15.9 x 16.2 cm, 3 cm walls, 1.8 cm overlay front panel with a painted + finger slot, no handle, 0.8 kg) is pulled out 11 cm towards the robot. The agentview camera looks at the cabinet's + back: the drawer is hidden there (wrist camera only), the top and the bottles are in plain view; + * two tall square bottles (green with a yellow ball cap, brown with a blue ball cap; 4 x 4 cm body, 19.4 cm tall, + 0.18 kg, centre of mass 9 cm up, a rounded glass base whose flat contact is 2.2 x 2.2 cm: they tip beyond ~7 deg) + standing on the table 21-24 cm to one side of the cabinet's centre line; + * two 3.2 cm cubes (red, blue, 23 g) 25-29 cm to the other side (picked from nearer, the forearm sweeps over the + cabinet top and knocks bottles standing there: measured feasibility map, task card). + +Hidden variable (same appearance): the drawer's closing mechanism. "self-closing" (14 of every 20 consecutive seeds): +in the last 8 cm of travel a spring pulls the drawer in with 12.5-15 N (no damper); "soft-close" (6 of 20): the same +spring with a damper, the drawer glides in at 4-6 cm/s. Nuisance variables (no effect on the class): carcass mass +0.35-0.45 kg, felt feet (friction on the table 0.15-0.22). + +Mechanism (physics, no teleport; measured, see the task card): the spring is internal to the cabinet, so when it snaps +the drawer in, it also pulls the light carcass (with the bottles on its top) towards the drawer, i.e. towards the robot: +2.3-4.2 cm within ~0.07 s (drawer hitting its stop at 1.9-2.4 m/s relative to the carcass; validate's naive runs), +then the carcass stops dead. A standing bottle's tilt follows a fast displacement of its support as ~ m h dx / I_edge +(~7 rad per metre here), so the bottles tip away from the robot and come to rest leaning on the rail (45-75 deg). The +robot's hand is at the drawer front, below and 10+ cm away from the bottles, and does not touch them (0 of all slams). +Pushing slower does not help (the spring does the closing; 2-10 cm/s and push heights 3-8 cm all toppled, 32/32); +placing the bottles elsewhere on the top does not help (46/46 over six placements). A soft-close drawer moves the +carcass < 3 mm (0/38 bottles fell). Only an uncontrolled full-speed push (~0.6 m/s, not an agent habit) differs: the +hand then shoves the cabinet itself (self-closing 5/8 fell, soft-close 4/4 fell, onto the arm). Placing the bottles after the drawer is shut is safe. Prototype findings that fixed +the numbers: with a light drawer, a heavier carcass or more friction the bottles only rocked (<= 11 deg): the snap's +jerk and the friction stop cancel; a 2 kg carcass held by friction during the snap instead jerked away from the robot +and tipped the bottles towards (onto) the arm. Without the rail, fallen bottles lay with their caps right behind the +cabinet, where the palm (3 cm behind the grasp point) cannot get at them; with the heavy drawer pulled out and no +plinth, ~3 N pressing on the drawer front tipped the cabinet forward. + +Restoring: the cap is a ball with low torsional friction; grasped from above with the fingers across the lying +bottle's axis, the cap turns between the fingers, the lifted bottle swings down and hangs straight, and it can be set +down on the cabinet top (lh_bystander's mechanism; the instruction says that a bottle held by its cap hangs straight). +The neck has torsional friction: a bottle pinched at the neck just under the cap is carried without swinging. + +Success (final state, follows from the instruction): both bottles upright (<= 10 deg) with their whole base on the +cabinet top (inside the rail), not held; both cubes inside the drawer; the drawer closed (<= 5 mm); the cabinet +upright and not moved more than 8 cm (the snap itself moves it 2.3-4.2 cm); the gripper open, holding nothing and +touching no task object; scene static. Per-step monitor (server log only; F1 tells the agent success / failure): stage +achieved / lost / restored (with cause: drawer_slam / robot_hand / robot_arm / bottle / picked_up / other), +drawer_slam (impact speed, carcass jerk, bottles on top, which of them fell, whether the robot had touched them before +they started to fall), bottle_fell, trap_fired (a bottle on top was lost to a slam), recovered_in_attempt. + +Protocol: cross (reset to the same instance before every attempt), k = 3. Once shut, the drawer cannot be opened again +(no handle; the self-closing spring would drag the light carcass along anyway). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +Z = envs.TABLE_Z + +# ---------------------------------------------------------------- cabinet (body frame: front face at -x, origin at the +# centre of the footprint, z = 0 on the table) +CAB = "cabinet_1" +CAB_MODEL = "lff_lhd_cabinet" +CD, CW, CH = 0.18, 0.22, 0.11 # carcass depth (x), width (y), height +CT = 0.010 # board thickness +PF = 0.018 # drawer front panel thickness (overlay: it sits in front of the carcass when closed) +DL = 0.165 # drawer box length (x), measured from the inner face of the front panel +DWT = 0.006 # drawer wall thickness +DWH = 0.030 # drawer wall height above its floor +D_FLOOR = CT + 0.003 # drawer floor bottom above the table +FLOOR_TOP = D_FLOOR + DWT +D_IN_Y = CW / 2 - CT - 0.003 - DWT # drawer inner half width (0.081) +D_IN_X = DL - DWT # inner length (from the front panel to the back wall) +Q_MAX = 0.14 # slide range (opening distance) +Q_OPEN = 0.11 # the drawer starts pulled out this far (exposed inside: 11 x 16.2 cm) +WOOD = (0.66, 0.50, 0.33, 1.0) +WOOD_D = (0.55, 0.40, 0.25, 1.0) +PANEL = (0.76, 0.60, 0.40, 1.0) +INNER = (0.84, 0.72, 0.52, 1.0) +SLOT = (0.18, 0.13, 0.09, 1.0) +DRAWER_MASS = 0.80 +PLINTH = 0.04 # the bottom board reaches this far in front of the carcass, under the drawer: with the heavy drawer +# pulled out, the cabinet would otherwise tip forward under a ~3 N push down on the drawer's front +CAB_COM_X = 0.04 # carcass centre of mass towards the back (back-heavy carcass): same reason +RAIL_H, RAIL_T = 0.060, 0.008 # gallery rail along the back edge of the top: a bottle that tips over backwards comes +# to rest leaning on it (~50 deg) instead of falling off behind the cabinet, where its +# cap would lie against the cabinet's back and the palm could not get at it +SLIDE_FRIC = 1.0 # N, slide frictionloss: the open drawer stays where it is +CARCASS_MASS = (0.35, 0.45) +FEET_MU = (0.15, 0.22) + +# drawer closing mechanism (hidden): spring in the last ZONE of travel, optional damper (soft-close) +ZONE = 0.08 +F_SPRING = (12.5, 15.0) +SOFT_V = (0.04, 0.06) # soft-close glide speed (damping = force / speed) +P_SLAM = 0.70 # 14 of every 20 consecutive seeds self-closing +CLOSED = 0.005 # drawer counts as closed +V_SLAM = 0.30 # m/s: an impact on the stop faster than this is a slam (soft-close: ~0.05) + +# ---------------------------------------------------------------- bottles (square body, shoulder, neck, ball cap) +BOTTLES = ("green_bottle_1", "brown_bottle_1") +B_NAME = {"green_bottle_1": "green", "brown_bottle_1": "brown"} +B_RGBA = {"green_bottle_1": (0.16, 0.48, 0.26, 1.0), "brown_bottle_1": (0.50, 0.26, 0.10, 1.0)} +CAP_RGBA = {"green_bottle_1": (0.92, 0.80, 0.15, 1.0), "brown_bottle_1": (0.15, 0.32, 0.85, 1.0)} +RB, HB = 0.020, 0.115 # body half width, height (incl. the foot) +RF, HF = 0.011, 0.005 # rounded glass base: flat contact 2.2 x 2.2 cm +RS, HS = 0.015, 0.010 # shoulder +RN, HN = 0.009, 0.050 # neck: long enough to be pinched below the cap with the palm clear of the cap +RK = 0.012 # ball cap +CAP_SINK = 0.005 +H_TOT = HB + HS + HN + 2 * RK - CAP_SINK # 0.194 +CAP_Z = H_TOT - RK # cap centre above the bottle's bottom when standing +B_MASS = 0.18 +B_COM = 0.090 # above the bottom +B_MU = 0.8 +CAP_MU_T = 0.0005 # torsional friction of the cap (condim 4): the grasped cap turns freely +NECK_MU_T = 0.01 # torsional friction of the neck (condim 4): a bottle pinched by its neck does not swing +NECK_GRASP = H_TOT - 0.027 # scripted grasp height above the bottom: the palm (3.1 cm above the grasp point between +# the fingers, measured) clears the cap top by 4 mm; the pads hold the neck top and the cap + +# ---------------------------------------------------------------- cubes +CUBES = ("red_cube_1", "blue_cube_1") +CUBE_COLOR = {"red_cube_1": "red", "blue_cube_1": "blue"} +CUBE_RGBA = dict(red=(0.85, 0.10, 0.08, 1.0), yellow=(0.92, 0.76, 0.10, 1.0), blue=(0.15, 0.30, 0.85, 1.0)) +CUBE_E = 0.032 +CUBE_DENS = 700.0 # 23 g + +# ---------------------------------------------------------------- predicates / monitor +UPRIGHT = np.radians(10.0) +TILT_START = np.radians(6.0) # a standing bottle beyond this has started to fall (it tips at ~6.8 deg) +FALLEN = np.radians(40.0) # lying, or leaning on the gallery rail (45-75 deg) +CAB_MOVE_MAX = 0.08 +CAB_TILT_MAX = np.radians(10.0) +DEBOUNCE = 10 # control steps (0.5 s) a predicate change must persist (checked every other step) +WIN_ROBOT = 40 # control steps: a robot contact this recent can explain a loss +WIN_SLAM = 60 + +# ---------------------------------------------------------------- scripted motion +NAIVE_ERR = 0.008 # Sonnet's placement error 0.4-1.3 cm +FINGER_AHEAD = 0.021 # closed fingertips reach this far ahead of the grasp point (yaw 0, +x) -- measured +REACH_MAX = 0.78 # scripted policies: farthest grasp point at table height (horizontal distance from the base) + + +def _box(name, pos, size, rgba, extra, vis=True, vis_rgba=None): + s = [f''] + if vis: + s.append(f'') + return s + + +def cabinet_xml(name): + """free carcass (bottom, top, two sides, back) + a drawer on a slide joint along -x (opening towards the robot). + Carcass geoms contype 2 / conaffinity 1, drawer geoms contype 4 / conaffinity 1: they never collide with each other + but both collide with the robot, the table and the free objects (contype / conaffinity 1). The slide joint comes + first in the object's joint list (robosuite appends the free joint), see DrawerCabinet.__init__.""" + hx, hy = CD / 2, CW / 2 + cg = 'friction="0.8 0.005 0.0001" contype="2" conaffinity="1" solimp="0.95 0.99 0.001" solref="0.004 1"' + carc = [] + carc += _box(f"{name}_bottom", (-PLINTH / 2, 0, CT / 2), (hx + PLINTH / 2, hy, CT / 2), WOOD_D, cg) + carc += _box(f"{name}_top", (0, 0, CH - CT / 2), (hx, hy, CT / 2), WOOD, cg) + carc += _box(f"{name}_side_l", (0, hy - CT / 2, CH / 2), (hx, CT / 2, CH / 2 - CT), WOOD, cg) + carc += _box(f"{name}_side_r", (0, -hy + CT / 2, CH / 2), (hx, CT / 2, CH / 2 - CT), WOOD, cg) + carc += _box(f"{name}_back", (hx - CT / 2, 0, CH / 2), (CT / 2, hy - CT, CH / 2 - CT), WOOD, cg) + carc += _box(f"{name}_rail", (hx - RAIL_T / 2, 0, CH + RAIL_H / 2), (RAIL_T / 2, hy, RAIL_H / 2), WOOD_D, cg) + dg = 'friction="0.8 0.005 0.0001" contype="4" conaffinity="1" solimp="0.95 0.99 0.001" solref="0.004 1"' + x0 = -hx # inner face of the front panel (closed) + zf = D_FLOOR + dr = [] + dr += _box(f"{name}_front", (x0 - PF / 2, 0, (CT + 0.002 + CH - 0.004) / 2), (PF / 2, hy, (CH - 0.006 - CT) / 2), + PANEL, dg) + dr += _box(f"{name}_dfloor", (x0 + DL / 2, 0, zf + DWT / 2), (DL / 2, D_IN_Y + DWT, DWT / 2), INNER, dg) + zw = zf + DWT + DWH / 2 + dr += _box(f"{name}_dside_l", (x0 + DL / 2, D_IN_Y + DWT / 2, zw), (DL / 2, DWT / 2, DWH / 2), INNER, dg) + dr += _box(f"{name}_dside_r", (x0 + DL / 2, -D_IN_Y - DWT / 2, zw), (DL / 2, DWT / 2, DWH / 2), INNER, dg) + dr += _box(f"{name}_dback", (x0 + DL - DWT / 2, 0, zw), (DWT / 2, D_IN_Y, DWH / 2), INNER, dg) + # flush finger pull (visual only): a dark slot near the top of the front panel + dr.append(f'') + m = DRAWER_MASS + ixx, iyy, izz = m * (CW ** 2 + 0.06 ** 2) / 12, m * (DL ** 2 + 0.06 ** 2) / 12, m * (DL ** 2 + CW ** 2) / 12 + drawer = (f'\n' + f' \n' + f' \n' + "\n".join(" " + s for s in dr) + "\n") + m0 = 0.4 + inertial = (f'') + body = "\n ".join([inertial] + carc + drawer.split("\n")) + return f""" + + + + {body} + + + + + + +""" + + +def bottle_xml(name, rgba, cap_rgba): + """square bottle: rounded base (narrow flat foot), body, shoulder, neck, ball cap; origin at mid height""" + h = H_TOT / 2 + zf, zb, zs, zn = -h + HF / 2, -h + HF + (HB - HF) / 2, -h + HB + HS / 2, -h + HB + HS + HN / 2 + zk = -h + HB + HS + HN + RK - CAP_SINK + m = B_MASS + ixx = m * ((2 * RB) ** 2 + H_TOT ** 2) / 14 + izz = m * (2 * (2 * RB) ** 2) / 12 + fr = f'friction="{B_MU} 0.005 0.0001"' + sol = 'solimp="0.95 0.99 0.001" solref="0.005 1"' + parts = [("foot", "box", (0, 0, zf), (RF, RF, HF / 2), rgba, fr + ' priority="2"'), + ("body", "box", (0, 0, zb), (RB, RB, (HB - HF) / 2), rgba, fr), + ("shoulder", "box", (0, 0, zs), (RS, RS, HS / 2), rgba, fr), + ("neck", "cylinder", (0, 0, zn), (RN, HN / 2), rgba, + f'friction="{B_MU} {NECK_MU_T} 0.0001" condim="4" priority="2"'), + ("cap", "sphere", (0, 0, zk), (RK,), cap_rgba, f'friction="1 {CAP_MU_T} 0.0001" condim="4" priority="2"')] + s = [f' '] + for nm, typ, pos, size, c, extra in parts: + s.append(f' ') + if nm != "foot": + s.append(f' ') + # rounded base (visual): a slightly narrower bottom band, and a label + s.append(f' ') + s.append(f' ') + return _wrap(name, "\n".join(s), h, RB * 1.42) + + +def _fb(v): + return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}" + + +def _lr(v): + return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}" + + +def _reach(p): + return float(np.hypot(p[0] + 0.66, p[1])) + + +class DrawerSkills(Skills): + """Skills that feed the task's per-step monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class DrawerCabinet(LFFTask): + name = "lh_drawer_cabinet" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Restore", "Plan") + protocol = "cross" + max_attempts = 3 + # careful: 2 bottles x ~8 commands + 3 cubes x ~6 + closing the drawer ~5 + looking ~15; standing 2 fallen bottles + # up again ~20; + slack + agent_max_steps = 120 + instruction = ("Tidy up the table: stand the green bottle and the brown bottle upright on top of the small wooden " + "cabinet, put the red cube and the blue cube into the cabinet's open drawer (it is pulled " + "out towards the robot), and close the drawer. When you finish, both bottles must stand upright on the cabinet top, both cubes must be in " + "the closed drawer, the cabinet must still stand where it is, and the gripper must be open and not " + "touching anything. (Each bottle has a round cap; held by its cap, a bottle hangs straight down.)") + instruction_indirect = ("Clean up: set the two tall bottles (the green one and the brown one) upright on the little " + "wooden cabinet, drop the two small cubes (red and blue) into its pulled-out drawer and " + "shut the drawer. In the end both bottles stand on top of the cabinet, the cubes are inside the shut drawer, " + "the cabinet stays in its place, and the open gripper touches nothing. (A bottle held by " + "its round cap hangs straight down.)") + agent_object_names = ["green bottle (yellow round cap)", "brown bottle (blue round cap)", "red cube", "blue cube", + "small wooden cabinet with its drawer pulled out (the drawer front faces the robot)"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + cab = register_generated("LffLhdCabinet", cabinet_xml(CAB_MODEL)) + objs = [(CAB, cab, "cabinet_region", (0.10, -0.02, 0.12, 0.0))] + for i, b in enumerate(BOTTLES): + c = B_NAME[b] + cat = register_generated(f"LffLhdBottle{c.title()}", bottle_xml(f"lff_lhd_bottle_{c}", B_RGBA[b], CAP_RGBA[b])) + objs.append((b, cat, f"{c}_bottle_region", (-0.30, 0.20 + 0.13 * i, -0.28, 0.22 + 0.13 * i))) + for i, n in enumerate(CUBES): + c = CUBE_COLOR[n] + cat = register_generated(f"LffLhdCube{c.title()}", + box_xml(f"lff_lhd_cube_{c}", (CUBE_E / 2,) * 3, CUBE_RGBA[c], density=CUBE_DENS, + friction=(0.8, 0.005, 0.0001))) + objs.append((n, cat, f"{c}_cube_region", (-0.30, -0.45 + 0.13 * i, -0.28, -0.43 + 0.13 * i))) + return write_bddl(self.name, "tidy up the table", objs, []) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + pre = f"{CAB}_{CAB_MODEL}" + self.jid = m.joint_name2id(pre + "_slide") + self.qa = int(m.jnt_qposadr[self.jid]) + self.dof = int(m.jnt_dofadr[self.jid]) + self.cab_bid = envs.body_id(self.env, CAB) + self.drawer_bid = m.body_name2id(f"{CAB}_drawer") + # the cabinet's free joint is the LAST of its joints (robosuite appends it after the drawer slide), so + # envs.free_joint_addr / place_upright (joints[0]) must not be used for it + fj = m.joint_name2id(self.env.objects_dict[CAB].joints[-1]) + assert int(m.jnt_type[fj]) == 0 + self.cab_qa, self.cab_da = int(m.jnt_qposadr[fj]), int(m.jnt_dofadr[fj]) + self.feet_gid = m.geom_name2id(pre + "_bottom") + self.cab_gids = {g for g in range(m.ngeom) if m.geom_bodyid[g] in (self.cab_bid, self.drawer_bid) + and m.geom_contype[g] != 0} + self.bottle_gids = {b: set(envs.obj_geom_ids(self.env, b)) for b in BOTTLES} + self.cube_gids = {c: set(envs.obj_geom_ids(self.env, c)) for c in CUBES} + self.cap_gid = {b: m.geom_name2id(f"{b}_lff_lhd_bottle_{B_NAME[b]}_cap") for b in BOTTLES} + # per-geom lookup tables for the substep contact scan + self.part = np.zeros(m.ngeom, int) # 1 = hand / fingers, 2 = arm links + for g in envs.robot_geom_ids(self.env): + n = m.geom_id2name(g) or "" + self.part[g] = 1 if n.startswith("gripper0_") else 2 + self.bidx = np.full(m.ngeom, -1, int) + for i, b in enumerate(BOTTLES): + self.bidx[list(self.bottle_gids[b])] = i + self.task_obj = np.zeros(m.ngeom, bool) + for s in list(self.bottle_gids.values()) + list(self.cube_gids.values()) + [self.cab_gids]: + self.task_obj[list(s)] = True + self.catch = dict(force=0.0, zone=ZONE, damp=0.0) + sim = self.env.sim + if not getattr(sim, "_lhd_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lhd_task", None) + if t is not None: + t._substep() + sim.step = step + sim._lhd_wrapped = True + sim._lhd_task = self + self.inst = None + self.mon = None + self.sk = None + self._sub = {} + + # ------------------------------------------------------------ drawer mechanism (every MuJoCo substep) + def q(self): + return float(self.env.sim.data.qpos[self.qa]) + + def catch_force(self, q, qd): + """generalised force on the slide (positive = opening): inside the last ZONE of travel a constant pull towards + closed (ramped in over 5 mm), plus a damper on closing motion for soft-close drawers""" + c = self.catch + z = c["zone"] + if q >= z or c["force"] <= 0: + return 0.0 + ramp = float(np.clip((z - q) / 0.005, 0.0, 1.0)) + f = -c["force"] * ramp + if qd < 0 and c["damp"] > 0: + f -= c["damp"] * qd * ramp + return f + + def _substep(self): + d = self.env.sim.data + q, qd = float(d.qpos[self.qa]), float(d.qvel[self.dof]) + d.qfrc_applied[self.dof] = self.catch_force(q, qd) + if self.mon is None: + return + sub = self._sub + # slam detection: the closing speed just before the drawer reaches its stop + if q > 0.002: + sub["approach_v"] = -qd + sub["armed"] = True + if q < self.catch["zone"] and sub.get("zone_xy") is None: + sub["zone_xy"] = self.cab_xy().tolist() + elif q > self.catch["zone"] + 0.005: + sub["zone_xy"] = None + elif sub.get("armed"): + sub["armed"] = False + v = float(sub.get("approach_v", 0.0)) + sub.setdefault("impacts", []).append((v, sub.get("zone_xy"))) + sub["zone_xy"] = None + n = d.ncon + if not n: + return + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + for a, b in zip(g1, g2): + ia, ib = self.bidx[a], self.bidx[b] + if ia < 0 and ib < 0: + continue + if ia >= 0 and ib >= 0: + if ia != ib: + sub.setdefault("bb", set()).update((int(ia), int(ib))) + continue + i, o = (ia, b) if ia >= 0 else (ib, a) + p = int(self.part[o]) + if p: + r = sub.setdefault("rob", {}) + r[int(i)] = 2 if (p == 2 or r.get(int(i)) == 2) else 1 + + # ------------------------------------------------------------ instances + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + slam = bool((int(seed) * 7) % 20 < round(20 * P_SLAM)) # balanced: 14 of every 20 consecutive seeds + cx, cy = float(rng.uniform(-0.13, -0.10)), float(rng.uniform(-0.04, 0.04)) + s = 1.0 if rng.random() < 0.5 else -1.0 # bottles on the left (+1) or right (-1), cubes on the other side + bottles = {} + order = rng.permutation(2) + for j, i in enumerate(order): + bx = cx + (-0.05, 0.05)[j] + float(rng.uniform(-0.01, 0.01)) + bottles[BOTTLES[i]] = [bx, cy + s * float(rng.uniform(0.21, 0.24))] + perm = rng.permutation(2) + # cubes 25-29 cm to the side of the cabinet's centre line: picked from nearer, the forearm sweeps over the + # cabinet top and knocks the bottles standing there (measured feasibility map, see the task card) + cubes = {CUBES[i]: [cx + (-0.16, -0.04)[j] + float(rng.uniform(-0.01, 0.01)), + cy - s * float(rng.uniform(0.25, 0.29))] for j, i in enumerate(perm)} + force = float(rng.uniform(*F_SPRING)) + soft_v = float(rng.uniform(*SOFT_V)) + return dict(seed=int(seed), self_closing=slam, drawer="self-closing" if slam else "soft-close", + cab_xy=[cx, cy], bottle_side="left" if s > 0 else "right", bottle_start=bottles, + bottle_yaw={b: float(rng.uniform(-0.3, 0.3)) for b in BOTTLES}, cube_start=cubes, + cube_yaw={c: float(rng.uniform(-0.3, 0.3)) for c in CUBES}, + spring_n=force, damp=0.0 if slam else force / soft_v, + carcass_kg=float(rng.uniform(*CARCASS_MASS)), feet_mu=float(rng.uniform(*FEET_MU)), + naive_noise_seed=int(rng.integers(1 << 30))) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + M = float(inst["carcass_kg"]) + m.body_mass[self.cab_bid] = M + m.body_inertia[self.cab_bid] = [M * (CW ** 2 + CH ** 2) / 12, M * (CD ** 2 + CH ** 2) / 12, + M * (CD ** 2 + CW ** 2) / 12] + m.geom_friction[self.feet_gid] = [float(inst["feet_mu"]), 0.005, 0.0001] + m.geom_priority[self.feet_gid] = 3 + self.catch = dict(force=float(inst["spring_n"]), zone=ZONE, damp=float(inst["damp"])) + self.set_drawer(Q_OPEN) + self.place_cabinet(inst["cab_xy"], 0.0) + for b in BOTTLES: + envs.place_upright(self.env, b, inst["bottle_start"][b], yaw=inst["bottle_yaw"][b], clearance=0.0005) + for c in CUBES: + envs.place_upright(self.env, c, inst["cube_start"][c], yaw=inst["cube_yaw"][c], clearance=0.001) + + def set_drawer(self, q): + d = self.env.sim.data + d.qpos[self.qa] = q + d.qvel[self.dof] = 0.0 + + def place_cabinet(self, xy, yaw=0.0, clearance=0.0005): + d = self.env.sim.data + a, v = self.cab_qa, self.cab_da + d.qpos[a:a + 3] = [xy[0], xy[1], Z + clearance] # body origin = bottom of the carcass + d.qpos[a + 3:a + 7] = [np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)] + d.qvel[v:v + 6] = 0.0 + self.env.sim.forward() + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = DrawerSkills(self.env, self, recorder=recorder) + self._sub = {} + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ geometry helpers (world frame) + def cab_R(self): + return self.env.sim.data.body_xmat[self.cab_bid].reshape(3, 3).copy() + + def cab_origin(self): + return self.env.sim.data.body_xpos[self.cab_bid].copy() + + def cab_xy(self): + return self.cab_origin()[:2] + + def to_cab(self, p): + """world point -> cabinet frame (x forward, origin at the footprint centre on the floor)""" + return self.cab_R().T @ (np.asarray(p, float) - self.cab_origin()) + + def from_cab(self, p): + return self.cab_origin() + self.cab_R() @ np.asarray(p, float) + + def top_z(self): + return float(self.from_cab([0.0, 0.0, CH])[2]) + + def cab_front_x(self): + """world x of the carcass's front face (cabinet assumed close to yaw 0)""" + return float(self.from_cab([-CD / 2, 0.0, 0.0])[0]) + + def drawer_front_x(self): + """world x of the drawer front panel's outer face""" + return self.cab_front_x() - self.q() - PF + + def cab_tilt(self): + return float(np.arccos(np.clip(self.cab_R()[2, 2], -1.0, 1.0))) + + def cab_moved(self): + return float(np.linalg.norm(self.cab_xy() - np.asarray(self.inst["cab_xy"]))) + + def R(self, name): + return self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3).copy() + + def tilt(self, name): + return float(np.arccos(np.clip(self.R(name)[2, 2], -1.0, 1.0))) + + def bottle_base(self, b): + """world position of the centre of the bottle's bottom face""" + return envs.obj_pos(self.env, b) - self.R(b)[:, 2] * H_TOT / 2 + + def cap_xyz(self, b): + return self.env.sim.data.geom_xpos[self.cap_gid[b]].copy() + + def held(self, name): + return self.sk is not None and self.sk.holding(name) + + # ------------------------------------------------------------ stage predicates + def bottle_on_top(self, b, tol=0.0, tilt=UPRIGHT): + if self.tilt(b) > tilt or self.held(b): + return False + c = self.to_cab(self.bottle_base(b)) + if c[0] < -CD / 2 + RF - tol or c[0] > CD / 2 - RAIL_T - RF + tol or abs(c[1]) > CW / 2 - RF + tol: + return False + return bool(-0.006 <= c[2] - CH <= 0.012) + + def cube_in_drawer(self, c): + """cube centre inside the drawer box (drawer frame), its footprint within the walls (+3 mm), resting low enough + to pass under the cabinet top; not held""" + if self.held(c): + return False + d = self.env.sim.data + Rd = d.body_xmat[self.drawer_bid].reshape(3, 3) + p = Rd.T @ (envs.obj_pos(self.env, c) - d.body_xpos[self.drawer_bid]) + x0 = -CD / 2 + e = CUBE_E / 2 * 1.2 # footprint half size (a yawed cube reaches a little farther) + tol = 0.003 + return bool(x0 + e - tol <= p[0] <= x0 + D_IN_X - e + tol and abs(p[1]) <= D_IN_Y - e + tol + and FLOOR_TOP - 0.005 <= p[2] - CUBE_E / 2 <= FLOOR_TOP + DWH + 0.01) + + def drawer_closed(self): + return self.q() <= CLOSED + + def stage_keys(self): + return [f"{B_NAME[b]}_bottle_on_top" for b in BOTTLES] + [f"{CUBE_COLOR[c]}_cube_in_drawer" for c in CUBES] + [ + "drawer_closed"] + + def stage_values(self, hyst=None): + hyst = hyst or {} + v = {} + for b in BOTTLES: + k = f"{B_NAME[b]}_bottle_on_top" + v[k] = self.bottle_on_top(b, 0.003, UPRIGHT + np.radians(3.0)) if hyst.get(k) else self.bottle_on_top(b) + for c in CUBES: + v[f"{CUBE_COLOR[c]}_cube_in_drawer"] = self.cube_in_drawer(c) + v["drawer_closed"] = self.q() <= (CLOSED + 0.003 if hyst.get("drawer_closed") else CLOSED) + return v + + # ------------------------------------------------------------ per-step monitor + def _init_monitor(self): + keys = self.stage_keys() + st = {k: False for k in keys} + self.mon = dict(state=st, ever=[], lost=[], lost_cause={}, events=[], cand={k: 0 for k in keys}, step=0, + last_robot=[None, None], last_bb=None, slams=[], standing_since=[None, None], + fall_start=[None, None], touched_before_fall=[False, False], max_tilt=[0.0, 0.0], + n_fallen=0, fallen=[False, False]) + + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + mon["step"] += 1 + t = int(self.sk.n_steps) + sub, self._sub = self._sub, {k: v for k, v in self._sub.items() if k in ("approach_v", "armed", "zone_xy")} + for i, part in sub.get("rob", {}).items(): + b = BOTTLES[i] + if not self.held(b): + mon["last_robot"][i] = ["hand" if part == 1 else "arm", t, round(float(np.degrees(self.tilt(b))), 1)] + if sub.get("bb"): + mon["last_bb"] = t + for v, zxy in sub.get("impacts", []): + if v >= V_SLAM: + lurch = None + if zxy is not None: + dxy = self.cab_xy() - np.asarray(zxy) + lurch = [round(100 * float(dxy[0]), 2), round(100 * float(dxy[1]), 2)] + on = [B_NAME[b] for b in BOTTLES if mon["state"][f"{B_NAME[b]}_bottle_on_top"]] + e = dict(event="drawer_slam", step=t, speed_mps=round(float(v), 2), cabinet_jerk_cm=lurch, + bottles_on_top=on, bottles_fell=[], robot_touched_before_fall=[]) + mon["events"].append(e) + mon["slams"].append(e) + else: + mon["events"].append(dict(event="drawer_shut", step=t, speed_mps=round(float(v), 3))) + # fall tracking (R4: did the robot touch a bottle before it started to fall?) + for i, b in enumerate(BOTTLES): + tl = self.tilt(b) + mon["max_tilt"][i] = max(mon["max_tilt"][i], float(np.degrees(tl))) + if self.held(b): + mon["standing_since"][i] = None + continue + if tl < np.radians(3.0): + if mon["standing_since"][i] is None: + mon["standing_since"][i] = t + mon["fall_start"][i] = None + elif tl > TILT_START and mon["standing_since"][i] is not None and mon["fall_start"][i] is None: + mon["fall_start"][i] = t + lr = mon["last_robot"][i] + mon["touched_before_fall"][i] = bool(lr is not None and t - lr[1] <= 20 and lr[2] < np.degrees(TILT_START)) + if not mon["fallen"][i] and tl > FALLEN: + mon["fallen"][i] = True + mon["n_fallen"] += 1 + mon["events"].append(dict(event="bottle_fell", bottle=B_NAME[b], step=t, cause=self._cause(i, t), + robot_touched_before_fall=bool(mon["touched_before_fall"][i]), + direction=self._fall_dir(b))) + elif mon["fallen"][i] and tl < UPRIGHT: + mon["fallen"][i] = False + if mon["step"] % 2: + return + vals = self.stage_values(hyst=mon["state"]) + for k, now in vals.items(): + self._check(k, now, t) + + def _fall_dir(self, b): + ax = self.R(b)[:2, 2] + if np.linalg.norm(ax) < 0.2: + return "none" + return ("forward" if ax[0] > 0 else "backward") if abs(ax[0]) >= abs(ax[1]) else ("left" if ax[1] > 0 else "right") + + def _cause(self, i, t): + """why bottle i left the cabinet top""" + b = BOTTLES[i] + mon = self.mon + if self.held(b): + return "picked_up" + lr = mon["last_robot"][i] + robot_recent = lr is not None and t - lr[1] <= WIN_ROBOT + if robot_recent and mon["touched_before_fall"][i]: + return f"robot_{lr[0]}" + if robot_recent and lr[2] < np.degrees(TILT_START): + return f"robot_{lr[0]}" + if mon["slams"] and t - mon["slams"][-1]["step"] <= WIN_SLAM: + return "drawer_slam" + if mon["last_bb"] is not None and t - mon["last_bb"] <= WIN_ROBOT: + return "bottle" + if robot_recent: + return f"robot_{lr[0]}" + return "other" + + def _check(self, key, now, t): + mon = self.mon + if now == mon["state"][key]: + mon["cand"][key] = 0 + return + mon["cand"][key] += 2 + if mon["cand"][key] < DEBOUNCE: + return + mon["cand"][key] = 0 + mon["state"][key] = now + t0 = int(t - DEBOUNCE + 1) + if now: + restored = key in mon["lost"] + e = dict(stage=key, event="restored" if restored else "achieved", step=t0) + if restored: + e["after"] = mon["lost_cause"].get(key) + mon["lost"].remove(key) + if key not in mon["ever"]: + mon["ever"].append(key) + mon["events"].append(e) + return + if key not in mon["ever"]: + return + if key.endswith("bottle_on_top"): + i = [f"{B_NAME[b]}_bottle_on_top" for b in BOTTLES].index(key) + cause = self._cause(i, t) + if cause == "drawer_slam": + s = mon["slams"][-1] + if B_NAME[BOTTLES[i]] not in s["bottles_fell"]: + s["bottles_fell"].append(B_NAME[BOTTLES[i]]) + s["robot_touched_before_fall"].append(bool(mon["touched_before_fall"][i])) + elif key == "drawer_closed": + cause = "opened" + else: + c = CUBES[[f"{CUBE_COLOR[x]}_cube_in_drawer" for x in CUBES].index(key)] + cause = "picked_up" if self.held(c) else "other" + if key not in mon["lost"]: + mon["lost"].append(key) + mon["lost_cause"][key] = cause + mon["events"].append(dict(stage=key, event="lost", step=t0, cause=cause)) + + def _finalize_monitor(self, vals): + """close the event log at finish: a stage the debounced monitor still holds but the final judge does not (or + vice versa) is logged now (final=True)""" + mon = self.mon + t = int(self.sk.n_steps) + for k, now in vals.items(): + if now == mon["state"][k]: + continue + n0 = len(mon["events"]) + mon["cand"][k] = DEBOUNCE # force the transition + self._check(k, now, t + DEBOUNCE - 1) + if len(mon["events"]) > n0: + mon["events"][-1]["final"] = True + + # ------------------------------------------------------------ outcome + def _static(self): + d = self.env.sim.data + for n in BOTTLES + CUBES: + _, da = envs.free_joint_addr(self.env, n) + if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5: + return False + v = self.cab_da + return bool(np.linalg.norm(d.qvel[v:v + 3]) < 0.02 and abs(float(d.qvel[self.dof])) < 0.02) + + def robot_touching(self): + d = self.env.sim.data + out = set() + for j in range(d.ncon): + c = d.contact[j] + for a, b in ((c.geom1, c.geom2), (c.geom2, c.geom1)): + if self.part[a] and self.task_obj[b]: + out.add("a bottle" if self.bidx[b] >= 0 else "the cabinet" if b in self.cab_gids else "a cube") + return sorted(out) + + def outcome(self, inst): + sk = self.sk + sk.hold(10) + touching = set() + for _ in range(20): + sk.hold(1) + touching.update(self.robot_touching()) + touching = sorted(touching) + static = self._static() + vals = self.stage_values() + held = [n for n in BOTTLES + CUBES if self.held(n)] + cab_ok = bool(self.cab_tilt() <= CAB_TILT_MAX and self.cab_moved() <= CAB_MOVE_MAX) + grip_open = bool(sk.grip < 0) + self._finalize_monitor(vals) + mon = self.mon + ev = list(mon["events"]) + success = bool(all(vals.values()) and cab_ok and static and not held and not touching and grip_open) + lost = [e for e in ev if e.get("event") == "lost"] + regress = [e for e in lost if e.get("cause") != "picked_up"] + restored = [e for e in ev if e.get("event") == "restored" and e.get("after") != "picked_up"] + slams = [e for e in ev if e.get("event") == "drawer_slam"] + slam_losses = [e for e in lost if e.get("cause") == "drawer_slam"] + trap = bool(slam_losses) + bkeys = [f"{B_NAME[b]}_bottle_on_top" for b in BOTTLES] + never_bottle = [B_NAME[b] for b, k in zip(BOTTLES, bkeys) if not vals[k] and k not in mon["ever"]] + lost_bottle = [B_NAME[b] for b, k in zip(BOTTLES, bkeys) if not vals[k] and k in mon["ever"]] + cubes_out = [CUBE_COLOR[c] for c in CUBES if not vals[f"{CUBE_COLOR[c]}_cube_in_drawer"]] + if success: + failure = "none" + elif held: + failure = "held" + elif not cab_ok: + failure = "cabinet_moved" + elif lost_bottle: + failure = "bottle_knocked" + elif never_bottle: + failure = "bottle_not_on_top" + elif cubes_out: + failure = "cube_not_in_drawer" + elif not vals["drawer_closed"]: + failure = "drawer_open" + elif touching: + failure = "touching" + elif not grip_open: + failure = "gripper_closed" + else: + failure = "not_static" + detail = self._detail(vals, held, touching, cab_ok, static, grip_open, success, ev) + return dict(success=success, failure=failure, stages=vals, events=ev, n_regressions=len(regress), + n_lost=len(lost), n_restored=len(restored), trap_fired=trap, + recovered_in_attempt=bool(trap and success), n_slams=len(slams), + slam_speeds=[e["speed_mps"] for e in slams], slam_jerk_cm=[e["cabinet_jerk_cm"] for e in slams], + bottles_lost_to_slam=sorted({e["stage"].split("_")[0] for e in slam_losses}), + robot_touched_before_fall=[bool(x) for x in mon["touched_before_fall"]], + bottle_max_tilt_deg=[round(x, 1) for x in mon["max_tilt"]], n_fallen=mon["n_fallen"], + held=held, touching=touching, static=bool(static), gripper_open=grip_open, + drawer_q_cm=round(100 * self.q(), 2), cabinet_moved_cm=round(100 * self.cab_moved(), 2), + cabinet_tilt_deg=round(float(np.degrees(self.cab_tilt())), 1), + bottle_tilts_deg={B_NAME[b]: round(float(np.degrees(self.tilt(b))), 1) for b in BOTTLES}, + self_closing=bool(inst["self_closing"]), detail=detail) + + def _detail(self, vals, held, touching, cab_ok, static, grip_open, success, ev): + parts = [] + if success: + parts.append("Both bottles stand on the cabinet, the two cubes are in the closed drawer.") + top_c = self.from_cab([0.0, 0.0, CH]) + for b in BOTTLES: + k = f"{B_NAME[b]}_bottle_on_top" + if vals[k]: + continue + nm = B_NAME[b] + if b in held: + parts.append(f"The {nm} bottle is still held by the gripper.") + continue + tl = float(np.degrees(self.tilt(b))) + base = self.bottle_base(b) + rel = base - top_c + on_top = abs(float(rel[2])) < 0.03 + ax = self.R(b)[:, 2] + where = f"its base is {_fb(rel[0])} and {_lr(rel[1])} of the centre of the cabinet top" + if tl <= np.degrees(UPRIGHT): + txt = (f"The {nm} bottle stands but not on the cabinet top: {where}." if not on_top else + f"The {nm} bottle stands with part of its base over the edge of the cabinet top: {where}.") + elif on_top and ax[0] > 0.3 and self.to_cab(self.cap_xyz(b))[0] > CD / 2 - RAIL_T: + txt = (f"The {nm} bottle has tipped over forward on the cabinet top and leans {tl:.0f} degrees against " + f"the rail along the top's far edge; {where}.") + elif on_top: + txt = f"The {nm} bottle has tipped over on the cabinet top ({tl:.0f} degrees); {where}." + elif base[2] < Z + 0.03: + txt = f"The {nm} bottle has fallen over and lies on the table; {where}." + else: + txt = f"The {nm} bottle has fallen over and leans {tl:.0f} degrees against something; {where}." + lost = [e for e in ev if e.get("stage") == k and e.get("event") == "lost"] + if lost: + why = lost[-1].get("cause", "other") + txt += {"drawer_slam": " It had stood on the cabinet top; it fell when the drawer snapped shut and the " + "cabinet jerked.", + "robot_hand": " It had stood on the cabinet top; the gripper knocked it.", + "robot_arm": " It had stood on the cabinet top; the robot's arm knocked it.", + "bottle": " It had stood on the cabinet top; the other bottle knocked it."}.get( + why, " It had stood on the cabinet top earlier.") + parts.append(txt) + for c in CUBES: + if vals[f"{CUBE_COLOR[c]}_cube_in_drawer"]: + continue + nm = CUBE_COLOR[c] + if c in held: + parts.append(f"The {nm} cube is still held by the gripper.") + continue + p = envs.obj_pos(self.env, c) + rel = self.to_cab(p) + if abs(rel[0]) < CD / 2 and abs(rel[1]) < CW / 2 and rel[2] > CH - 0.01: + parts.append(f"The {nm} cube lies on the cabinet top, not in the drawer.") + else: + parts.append(f"The {nm} cube is not in the drawer: it is {_fb(rel[0] + CD / 2)} and {_lr(rel[1])} of the " + f"middle of the cabinet's front.") + if not vals["drawer_closed"]: + parts.append(f"The drawer is still {100 * self.q():.1f} cm open.") + if not cab_ok: + if self.cab_tilt() > CAB_TILT_MAX: + parts.append("The cabinet has been knocked over.") + else: + parts.append(f"The cabinet was moved {100 * self.cab_moved():.0f} cm from where it stood.") + if not success and all(vals.values()) and cab_ok: + if touching: + parts.append("The gripper is still touching " + " and ".join(touching) + ".") + elif not grip_open: + parts.append("The gripper is closed.") + elif not static: + parts.append("Something was still moving.") + slams = [e for e in ev if e.get("event") == "drawer_slam" and e.get("bottles_fell")] + if slams and success: + parts.append("(The drawer snapped shut and knocked bottles off the cabinet; they were stood up again.)") + return " ".join(parts) + + # ------------------------------------------------------------ scripted primitives (move_to + gripper only) + def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300): + return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + + def _lift_to(self, z, speed=0.15): + cur = self.sk.eef_pos() + if cur[2] < z - 0.005: + self._go([cur[0], cur[1], z], speed=speed) + + def _settle(self, name, max_checks=25): + d = self.env.sim.data + _, da = envs.free_joint_addr(self.env, name) + for _ in range(max_checks): + if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2: + return + self.sk.hold(2) + + def _box_yaw(self, name): + R = self.R(name) + i = int(np.argmin(np.abs(R[2]))) + yaw = float(np.arctan2(R[1, i], R[0, i])) + y = float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4) + cands = [y + k * np.pi / 2 for k in (-1, 0, 1)] + return min(cands, key=lambda c: abs(c - self.sk.yaw) if abs(c) <= np.pi / 2 else 9.0) + + def pick_bottle(self, b, grasp="neck", z_clear=0.05, yaw=None, v=0.15): + """Sonnet-like pick of a standing bottle from above: over it, straight down, close, lift until its bottom + clears the cabinet top by z_clear. grasp: neck (1 cm below its top; the body cannot be reached from above, the + palm would land on the cap) | cap (the bottle then hangs from a pivot)""" + sk = self.sk + self._settle(b) + p = envs.obj_pos(self.env, b) + bot = self.bottle_base(b)[2] + zg = {"neck": bot + NECK_GRASP, "cap": bot + CAP_Z}[grasp] + yaw = self._box_yaw(b) if yaw is None else yaw + sk.set_gripper(False, steps=8) + top = bot + H_TOT + self.transit(p[:2], top + 0.06, yaw=yaw, v=v) + self._go([p[0], p[1], zg + 0.015], speed=0.1) + self._go([p[0], p[1], zg], speed=0.04, tol=0.003, max_steps=150) + sk.set_gripper(True, steps=15) + lift = self.top_z() + z_clear + (zg - bot) + self._go([p[0], p[1], lift], speed=0.10) + sk.hold(5) + if not self.held(b): + sk.set_gripper(False, steps=8) + return False + return True + + def put_bottle(self, b, xy, gap=0.01, z_clear=0.05, v=0.12, settle=15): + """carry the held bottle over xy (its axis, not the grasp point), straight down until its bottom is `gap` above + the cabinet top, let go, lift""" + sk = self.sk + rel = envs.obj_pos(self.env, b)[:2] - sk.eef_pos()[:2] + q = np.asarray(xy, float) - rel + zc = self.top_z() + z_clear + (sk.eef_pos()[2] - self.bottle_base(b)[2]) + self.transit(q, zc, v=v, carried=b, margin=z_clear) + sk.hold(settle) + rel = envs.obj_pos(self.env, b)[:2] - sk.eef_pos()[:2] + q = np.asarray(xy, float) - rel + dz = sk.eef_pos()[2] - envs.obj_min_z(self.env, b) + zr = self.top_z() + dz + gap + self._go([q[0], q[1], zr + 0.02], speed=0.08) + self._go([q[0], q[1], zr], speed=0.03, tol=0.003, max_steps=150) + sk.hold(5) + sk.set_gripper(False, steps=12) + cur = sk.eef_pos() + self._go([cur[0], cur[1], self.top_z() + H_TOT + 0.06], speed=0.08) + self._settle(b) + + def obstacle_top(self, p0, p1, ignore=(), r=0.09): + """highest top (world z) of standing bottles within r of the straight path p0 -> p1 (xy), and of the cabinet + top if the path passes over it (expanded by 4 cm)""" + a, b = np.asarray(p0, float)[:2], np.asarray(p1, float)[:2] + ab = b - a + L2 = max(float(ab @ ab), 1e-9) + + def dist(q): + u = float(np.clip((q - a) @ ab / L2, 0.0, 1.0)) + return float(np.linalg.norm(a + u * ab - q)) + top = Z + for o in BOTTLES: + if o in ignore or self.held(o): + continue + if dist(envs.obj_pos(self.env, o)[:2]) < r: + top = max(top, envs.obj_max_z(self.env, o)) + for u in np.linspace(0.0, 1.0, 21): + c = self.to_cab(np.r_[a + u * ab, Z]) + if abs(c[0]) < CD / 2 + 0.04 + PF + max(self.q(), 0.0) and abs(c[1]) < CW / 2 + 0.04: + top = max(top, self.top_z() + RAIL_H) + break + return top + + def transit(self, xy, z_min, yaw=None, v=0.15, carried=None, margin=0.06): + """Sonnet-like transit: up (to clear what is in the way), straight across, the caller then goes down""" + sk = self.sk + cur = sk.eef_pos() + obst = self.obstacle_top(cur, xy, ignore=(carried,) if carried else ()) + below = (sk.eef_pos()[2] - envs.obj_min_z(self.env, carried)) if carried else 0.03 + zt = max(cur[2], z_min, obst + margin + below) + if cur[2] < zt - 0.005: + self._go([cur[0], cur[1], zt], speed=v) + self._go([xy[0], xy[1], zt], yaw=yaw, speed=v) + + def pick_cube(self, c, z_carry=0.15, v=0.15): + sk = self.sk + for _ in range(2): + self._settle(c) + p = envs.obj_pos(self.env, c) + yaw = self._box_yaw(c) + sk.set_gripper(False, steps=8) + self.transit(p[:2], Z + z_carry, yaw=yaw, v=v) + self._go([p[0], p[1], p[2] + 0.015], speed=0.1) + self._go([p[0], p[1], p[2]], speed=0.04, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + self._go([p[0], p[1], max(Z + z_carry, sk.eef_pos()[2])], speed=v) + if self.held(c): + return True + sk.set_gripper(False, steps=8) + return False + + def drawer_slot(self, k, noise=None): + """world xy of cube slot k (0..1) in the exposed part of the open drawer: a column along the drawer's middle + (with the wrist at yaw 0 the open fingers, 13.2 cm across, stay clear of the side walls and of the cube + already in; the palm, 3.9 cm ahead of the grasp point, stays clear of the carcass; the far slot first)""" + q = min(self.q(), Q_OPEN) + x = self.cab_front_x() - 0.045 - k * (q - 0.070) + y = self.cab_xy()[1] + out = np.array([x, y]) + return out + (np.asarray(noise, float) if noise is not None else 0.0) + + def put_cube(self, c, xy, gap=0.02, z_carry=0.15, v=0.15): + sk = self.sk + self.transit(xy, Z + z_carry, yaw=0.0, v=v, carried=c, margin=0.04) + zr = Z + FLOOR_TOP + CUBE_E / 2 + gap + self._go([xy[0], xy[1], zr + 0.015], speed=0.1) + self._go([xy[0], xy[1], zr], speed=0.04, tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + self._go([xy[0], xy[1], Z + z_carry], speed=v) + self._settle(c) + + def close_drawer(self, v=0.04, z_push=0.05, overshoot=0.0, y_off=0.0, approach=0.03): + """closed gripper in front of the drawer, then a straight push forward to where the front panel is flush""" + sk = self.sk + y = self.cab_xy()[1] + y_off + xs = self.drawer_front_x() - FINGER_AHEAD - approach + x_end = self.cab_front_x() - PF - FINGER_AHEAD + overshoot + sk.set_gripper(True, steps=10) + cur = sk.eef_pos() + self._go([cur[0], cur[1], max(cur[2], Z + 0.15)], speed=0.15) + self._go([xs, y, Z + 0.15], yaw=0.0, speed=0.15) + self._go([xs, y, Z + z_push], speed=0.1, tol=0.003) + self._go([x_end, y, Z + z_push], speed=v, tol=0.003, max_steps=int(0.25 / max(v, 0.01) / 0.05) + 60) + self.sk.hold(10) + cur = sk.eef_pos() + self._go([cur[0] - 0.06, cur[1], cur[2]], speed=0.08) + self._go([cur[0] - 0.06, cur[1], Z + 0.20], speed=0.15) + sk.hold(10) + + def top_spots(self, mode="pair", noise=None): + """world xy targets on the cabinet top for the two bottles (left one first): side by side across the middle""" + c = self.from_cab([0.0, 0.0, CH])[:2] + spots = [c + np.array([0.0, 0.05]), c + np.array([0.0, -0.05])] + if noise is not None: + spots = [s + np.asarray(n, float) for s, n in zip(spots, noise)] + return spots + + def free_top_spot(self, b, start=None): + """a spot on the cabinet top (cabinet frame candidates) at least 6.5 cm from the other bottle if that one stands + on the top, and -- if `start` (xy the bottle comes from) is given -- whose straight path from `start` passes + farthest from it""" + other = [o for o in BOTTLES if o != b][0] + cands = [np.array([dx, dy]) for dx in (0.0, -0.03, 0.03) for dy in (0.055, -0.055, 0.0)] + ok_other = self.bottle_on_top(other, 0.01, np.radians(20)) + oc = self.to_cab(self.bottle_base(other))[:2] + if not ok_other: + return self.from_cab([cands[0][0], cands[0][1], CH])[:2] if start is None else min( + (self.from_cab([c[0], c[1], CH])[:2] for c in cands[:2]), + key=lambda w: float(np.linalg.norm(w - np.asarray(start)[:2]))) + best, score = None, -1.0 + st = None if start is None else self.to_cab(np.r_[np.asarray(start)[:2], Z])[:2] + for c in cands: + if np.linalg.norm(c - oc) < 0.065: + continue + if st is None: + return self.from_cab([c[0], c[1], CH])[:2] + ab = c - st + u = float(np.clip((oc - st) @ ab / max(float(ab @ ab), 1e-9), 0.0, 1.0)) + clear = float(np.linalg.norm(st + u * ab - oc)) + if clear > score: + best, score = c, clear + if best is None: + best = max(cands, key=lambda c: float(np.linalg.norm(c - oc))) + return self.from_cab([best[0], best[1], CH])[:2] + + def restand_bottle(self, b, xy=None): + """stand a fallen bottle up again on the cabinet top: grasp the ball cap from above (fingers across the lying + bottle's axis), lift until it hangs free with its bottom above the gallery rail, carry it over a free spot, + lower until the bottom is ~3 mm above the top, let go. Returns True if it stands on the top.""" + sk = self.sk + self._settle(b) + for _ in range(2): + if _reach(self.cap_xyz(b)) > REACH_MAX and self.tilt(b) > FALLEN: + self.pull_in_bottle(b) + k = self.cap_xyz(b) + ax = self.R(b)[:2, 2] + yaw = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else sk.yaw # finger axis across it + sk.set_gripper(False, steps=8) + self.transit(k[:2], k[2] + 0.08, yaw=yaw, v=0.15) + sk.hold(5) + k = self.cap_xyz(b) + self._go([k[0], k[1], k[2] + 0.015], speed=0.1) + self._go([k[0], k[1], k[2]], speed=0.04, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + if not self.held(b): + sk.set_gripper(False, steps=8) + self._go([k[0], k[1], k[2] + 0.08], speed=0.1) + continue + zl = self.top_z() + RAIL_H + 0.03 + CAP_Z + self._go([k[0], k[1], zl], speed=0.10) + sk.hold(15) + tx, ty = self.free_top_spot(b, start=k[:2]) if xy is None else xy + self._go([tx, ty, zl], speed=0.10) + sk.hold(30) + self._go([tx, ty, self.top_z() + CAP_Z + 0.015], speed=0.08) + self._go([tx, ty, self.top_z() + CAP_Z + 0.003], speed=0.03, tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + self._go([tx, ty, self.top_z() + H_TOT + 0.04], speed=0.08) + sk.hold(20) + self._settle(b) + if self.bottle_on_top(b): + return True + return self.bottle_on_top(b) + + def pull_in_bottle(self, b): + """the lying bottle's cap is out of reach: grasp the body near its bottom end (fingers across it), lift it + 3 cm, pull it towards the robot until the cap is within reach, set it down""" + sk = self.sk + Rb = self.R(b) + ax = Rb[:, 2] + g = envs.obj_pos(self.env, b) - ax * (H_TOT / 2 - 0.04) + zg = max(float(g[2] - Z), 0.02) + yaw = float(np.arctan2(ax[1], ax[0])) + need = _reach(self.cap_xyz(b)) - (REACH_MAX - 0.05) + to_base = np.array([-0.66, 0.0]) - g[:2] + to_base /= max(np.linalg.norm(to_base), 1e-6) + dst = g[:2] + to_base * need + sk.set_gripper(False, steps=8) + self._go([g[0], g[1], Z + 0.15], yaw=yaw, speed=0.15) + self._go([g[0], g[1], Z + zg + 0.015], speed=0.1) + self._go([g[0], g[1], Z + zg], speed=0.04, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + self._go([g[0], g[1], Z + zg + 0.03], speed=0.08) + self._go([dst[0], dst[1], Z + zg + 0.03], speed=0.08) + self._go([dst[0], dst[1], Z + zg + 0.005], speed=0.04) + sk.set_gripper(False, steps=12) + self._go([dst[0], dst[1], Z + 0.15], speed=0.1) + self._settle(b) + + # ------------------------------------------------------------ scripted policies + def check_and_fix(self, params, rounds=2): + """look at every stage at the end: stand fallen bottles up on the top, put stray cubes into the drawer if it is + still open""" + for _ in range(rounds): + v = self.stage_values() + if all(v.values()): + break + for b in BOTTLES: + if not self.bottle_on_top(b): + if self.tilt(b) > UPRIGHT or self.bottle_base(b)[2] < self.top_z() - 0.03: + if self.tilt(b) > UPRIGHT: + self.restand_bottle(b) + elif self.pick_bottle(b, grasp="neck"): + self.put_bottle(b, self.free_top_spot(b), gap=0.005) + if not self.drawer_closed(): + for k, c in enumerate(CUBES): + if not self.cube_in_drawer(c) and self.pick_cube(c): + self.put_cube(c, self.drawer_slot(k)) + if all(self.cube_in_drawer(c) for c in CUBES): + self.close_drawer(v=params.get("push_v", 0.04), z_push=params.get("push_z", 0.05)) + self._lift_to(self.top_z() + 0.15) + self.sk.set_gripper(False, steps=8) + self.sk.hold(10) + + def do_bottles(self, params, rng): + noise = params.get("noise") + spots = self.top_spots(noise=noise) + side = 1.0 if self.inst["bottle_side"] == "left" else -1.0 + spots = sorted(spots, key=lambda q: side * float(q[1])) # the spot farther from the bottles' side first + order = list(BOTTLES) if params.get("bottle_order", "listed") == "listed" else list(BOTTLES)[::-1] + for b, xy in zip(order, spots): + for _ in range(2): + if self.pick_bottle(b, grasp=params.get("grasp", "neck"), z_clear=params.get("z_clear", 0.05)): + self.put_bottle(b, xy, gap=params.get("gap", 0.02), z_clear=params.get("z_clear", 0.05)) + break + + def do_cubes(self, params, rng): + noise = params.get("cube_noise") or [None] * 3 + for k, c in enumerate(self._cube_order()): + if self.pick_cube(c): + self.put_cube(c, self.drawer_slot(k, noise[k]), gap=params.get("cube_gap", 0.02)) + + def _cube_order(self): + """nearest the drawer first""" + d = np.array([self.cab_front_x() - Q_OPEN / 2, self.cab_xy()[1]]) + return sorted(CUBES, key=lambda c: float(np.linalg.norm(envs.obj_pos(self.env, c)[:2] - d))) + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("noise_seed", 0)) + order = params.get("order", "BCD") # B = bottles on top, C = cubes into the drawer, D = close the drawer + for step in order: + if step == "B": + self.do_bottles(params, rng) + elif step == "C": + self.do_cubes(params, rng) + elif step == "D": + self.close_drawer(v=params.get("push_v", 0.04), z_push=params.get("push_z", 0.05), + overshoot=params.get("overshoot", 0.0)) + if params.get("check"): + self.check_and_fix(params) + else: + self._lift_to(self.top_z() + 0.15) + self.sk.set_gripper(False, steps=8) + self.sk.hold(10) + + def _noise(self, rng, err=NAIVE_ERR): + return dict(noise=[rng.uniform(-err, err, 2).tolist() for _ in BOTTLES], + cube_noise=[rng.uniform(-err, err, 2).tolist() for _ in CUBES]) + + def default_params(self, inst): + """Sonnet-like: the order of the instruction (bottles, cubes, drawer); bottles grasped by the body from above, + lifted until they clear the cabinet top by 5 cm, lowered straight down and let go 1-4 cm above it; cubes into + the drawer; the drawer pushed shut slowly (4 cm/s) with the closed gripper; no final look back""" + rng = np.random.default_rng(inst["naive_noise_seed"]) + p = dict(order="BCD", check=False, grasp="neck", gap=float(rng.uniform(0.01, 0.04)), + push_v=float(rng.uniform(0.03, 0.05)), push_z=float(rng.uniform(0.04, 0.06)), + overshoot=float(rng.uniform(0.0, 0.004)), noise_seed=int(inst["naive_noise_seed"])) + p.update(self._noise(rng)) + return p + + def oracle_params(self, inst): + """knows the drawer: cubes in, drawer shut, then the bottles; checks every stage at the end""" + return dict(order="CDB", check=True, grasp="neck", gap=0.008, push_v=0.04, push_z=0.05, overshoot=0.0) + + def adapt_params(self, inst, history): + """attempt >= 2 (after the bottles fell when the drawer was shut): shut the drawer before the bottles go on + top, and look at every stage at the end""" + return dict(self.default_params(inst), order="CDB", check=True) + + def blind_params(self, inst, attempt, rng): + """the natural behaviour with random variations (order of the three sub-tasks, push speed / height, release + height, placement noise), no history, no final look""" + order = str(rng.choice(["BCD", "CBD", "CDB"], p=[0.5, 0.3, 0.2])) + p = dict(order=order, check=False, grasp=str(rng.choice(["neck", "cap"])), gap=float(rng.uniform(0.01, 0.04)), + push_v=float(rng.uniform(0.02, 0.08)), push_z=float(rng.uniform(0.03, 0.07)), + overshoot=float(rng.uniform(0.0, 0.006)), noise_seed=int(rng.integers(1 << 30))) + p.update(self._noise(rng)) + return p + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """oracle / naive: one attempt; adaptive: attempt 1 = naive + a final look that stands fallen bottles up again, + attempts >= 2 drawer first; blind: naive with random variations. + Extra kinds (not in validate's table): switch (naive, then drawer first without a final look), oracle_noise + (oracle with +-5 mm placement noise), naive_slow (naive pushing at the slowest agent speed, 2 cm/s), + naive_check (naive + final look = adaptive's first attempt)""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + single = ("oracle", "naive", "oracle_noise", "naive_slow", "naive_check", "naive_neck", "naive_cap") + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": + params = self.default_params(inst) if a == 0 else dict(self.default_params(inst), order="CDB") + elif kind == "oracle_noise": + params = dict(self.oracle_params(inst), **self._noise(np.random.default_rng(seed * 7 + a), 0.005)) + elif kind == "naive_slow": + params = dict(self.default_params(inst), push_v=0.02) + elif kind == "naive_check": + params = dict(self.default_params(inst), check=True) + elif kind == "naive_neck": + params = dict(self.default_params(inst), grasp="neck") + elif kind == "naive_cap": + params = dict(self.default_params(inst), grasp="cap") + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in single: + break + return history diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/lh_fence.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/lh_fence.py new file mode 100644 index 0000000000000000000000000000000000000000..bb2b54b80b13295e96084ae9823b99f28f57ef1a --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/lh_fence.py @@ -0,0 +1,1030 @@ +"""LH lh_fence (v2, 2026-10-11): build a small fence -- three square posts on square marks and two flat panels on the +strips between them, end to end in one line. Letting go of a panel with the fingers along the fence line knocks over +the post next to it (when the posts are light); the fallen post must be stood up again before finishing. + +Family: long-horizon self-disturbance ("state_restoration"): every placement is a later stage that can physically +break the earlier ones; the agent has to notice and restore them (within an attempt) or learn to place without +disturbing them (across attempts). + +Why v2 (measured, ../docs/11 sec. 9): in v1 the panels stood like dominoes (thickness along the row) and the hazard was +opening the fingers along the row. Sonnet 5.5 always turned the hand so that its long axis (= the finger axis) lay +along the panel's long horizontal side, which in v1 is across the row = the safe orientation, and it filled the row +from the far end: 3/3 pilot runs succeeded first time with zero disturbances. v2 turns the panels by 90 deg into a real +fence (panels end to end along the line, posts between them), so the same habit now opens the fingers ALONG the +line, towards the posts. + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a straight fence line, left-right or forward-back: 3 dark square marks (posts) alternating with 2 dark strips + (panels), slot pitch (post centre to post centre) w + 2 g + b; + * 3 posts: square b = 1.55-1.65 cm, height = the panels' height, dark wood, ball knob (r 1.0 cm, 10 g) on a 0.8 cm + stem; 2 panels: thickness t 1.4-1.6 cm (across the line), width w 4.0-4.6 cm (along it), height h 7-8 cm, light + wood, same knob. A placed panel leaves a gap g = 1.3-1.5 cm to each post (knob to knob D = w/2 + g + b/2 = + 4.1-4.6 cm); + * the 5 objects stand in a 2 x 3 supply grid (11 cm pitch, 13-15 cm beside the line, shifted towards one end), the + panels with their width along the line (+-9 deg). + +Hidden variable (instance level, consistent across attempts, invisible): the posts' mass distribution. "Light" posts +are plain wood (19-23 g incl. the knob; centre of mass 5.9-7.1 cm up, tips over beyond ~7 deg); "footed" posts carry a +hidden 100-140 g steel foot (centre of mass 1.5-1.8 cm up, tips over beyond 25-28 deg). They look identical. 13 of +every 20 consecutive seeds have light posts ("hazard"), 7 footed ("benign"). + +Disturbance (physics, no teleport): a panel is grasped by its knob; with the fingers along the panel's width (the +natural "hand along the board" grasp, and Sonnet's measured habit) the fingers lie along the fence line at the release +and, opening to 8 cm, sweep ~6 cm out from the grasp point: they hit the knob of each post that already stands next to +the panel (D 3.3-5.4 cm incl. a 0.8 cm placement error) and push it 6-18 deg. A light post falls over (away from the +panel; a middle post often ends up leaning on the panel on its other side); a footed post rocks back. Measured in the +prototype: light posts 16/16 fell for D <= 5.0 cm (2/4 at 5.5, 0/4 at 6.0), posts with a 0.12-0.25 kg foot 0/30 (max +tilt 18 deg); with the fingers across the line (along the panel's thickness) 0/9 contacts. A post set down with its +fingers along the line next to a standing panel tilts the panel <= 15 deg, which rocks back. Validation (seeds +1000-1019): the Sonnet-like naive disturbs 13/13 light-post instances and 0/7 footed ones. + +So the levers are under the agent's control and the hidden weight only decides whether its habit is punished: (1) +release a panel with the fingers across the fence line (Sonnet-like naive with only this change: 19/20), or, only +partly, (2) stand both panels before the posts (15/20: a post released next to a panel with its fingers along the line +rocks the panel, which can knock the new light post). Within an attempt: +look at the fence before finishing and stand fallen posts up again (lifted by its knob a fallen post swings down and +hangs upright; a fallen panel too). + +Implementation notes (found while building v2): MuJoCo keeps each body's bounding-volume hierarchy in the body's +inertial frame, computed at compile time. Changing geom sizes or body_ipos at runtime therefore needs `refit_bvh` +(else contacts are missed: a light post whose centre of mass was moved up sank 2.2 cm into the table; one moved down +never touched the fingers), and runtime body_ipos is ignored altogether when the compiled inertial frame coincides with +the body frame (v1's knob-mass shift of the centre of mass was silently ignored); the generated XML therefore declares +an inertial pos of 1 mm. With the centre of mass right, v1's knob torsional friction (0.0015) held a lifted fallen light +post at 44-61 deg instead of letting it swing down; v2 uses 0.0005 (< 3 deg). + +Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (every mark +carries an upright post, every strip an upright panel lined up with it, nothing held or touched, scene static) plus an +event log of every stage predicate (achieved / lost / restored, with step and cause) for the server log; F1 gives the +agent only success / failure. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +TZ = envs.TABLE_Z +POSTS = [f"post_{c}_1" for c in "abc"] +PANELS = [f"panel_{c}_1" for c in "ab"] +OBJS = POSTS + PANELS +MARKS = [f"postmark_{c}_1" for c in "abc"] +STRIPS = [f"strip_{c}_1" for c in "ab"] +SLOT_KIND = ["post", "panel", "post", "panel", "post"] # along the fence line (-u to +u) +WOOD = [(0.82, 0.66, 0.44, 1.0), (0.76, 0.60, 0.40, 1.0)] +POST_RGBA = [(0.46, 0.30, 0.18, 1.0), (0.44, 0.29, 0.17, 1.0), (0.48, 0.31, 0.19, 1.0)] +KNOB_RGBA = (0.20, 0.11, 0.06, 1.0) +STRIP_RGBA = (0.30, 0.10, 0.12, 1.0) +MARK_RGBA = (0.14, 0.14, 0.16, 1.0) +NOM_T, NOM_W, NOM_H = 0.015, 0.047, 0.075 # nominal panel (resized per instance) +NOM_B = 0.016 # nominal post width +KNOB_R, STEM_L, STEM_R = 0.010, 0.008, 0.0035 +KNOB_MASS = 0.010 +KNOB_MU_T = 0.0005 # torsional friction of the knob (condim 4): damps the swing of a hanging object; 0.0015 (v1) holds a lifted fallen light post at 45-60 deg (measured) +STRIP_W = 0.006 + +# instance ranges +P_HAZARD = 0.65 # 13 of every 20 consecutive seeds: light posts +T_RANGE = (0.014, 0.016) +W_RANGE = (0.040, 0.046) +H_RANGE = (0.070, 0.080) +B_RANGE = (0.0155, 0.0165) +GAP_RANGE = (0.013, 0.015) # panel end to post face; 1.0-1.2 cm: a +-0.8 cm placement error let the panel end touch a light post (2/20 with the safe grasp) +DENS_RANGE = (450.0, 650.0) +MU_RANGE = (0.4, 0.8) +FOOT_RANGE = (0.10, 0.14) # hidden steel foot of a "footed" post (kg) +FOOT_H = 0.015 # height of the foot slug (its centre 7.5 mm above the post's bottom) +SUP_PITCH = (0.105, 0.115) +SUP_D = (0.13, 0.15) +X_FAR = -0.035 + +# success predicate +TOL_U = 0.010 # panel centre within 1 cm of the strip centre along the line, 1.5 cm across; post 1 cm both ways +TOL_V = 0.015 +TOL_POST = 0.010 +TILT_OK = np.radians(5.0) +YAW_TOL = np.radians(15.0) +HYST = 0.004 +DEBOUNCE = 20 # a stage counts as lost / regained only after 1 s (a post or panel that is pushed and rocks back is not a loss) +FALLEN = np.radians(45.0) + +# scripted motion (z = height of the grasp point above the table) +Z_SAFE = 0.25 # careful transit (a hanging object's bottom ~15 cm up) +Z_NAIVE = 0.21 # Sonnet's usual carry height: robot-frame z 0.20 (= 21 cm above the table), measured in lh2_fence +NAIVE_ERR = 0.008 # naive placement error, uniform per axis (Sonnet: 0.4-1.3 cm from the strip centre, lh2_fence) + + +def _wrap_h(a): + """wrap to [-pi/2, pi/2) (panel footprint and gripper are symmetric under 180 deg)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def _yaw_for_axis(a): + """gripper yaw whose finger axis (-sin yaw, cos yaw) is parallel to the horizontal direction a""" + return _wrap_h(float(np.arctan2(-a[0], a[1]))) + + +def _quat2mat(q): + w, x, y, z = q + return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], + [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], + [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]]) + + +def refit_bvh(m, b, margin=0.001): + """Recompute body b's bounding-volume hierarchy after runtime changes of its geoms or body_ipos. MuJoCo stores the + boxes in the body's inertial frame, computed at compile time; stale boxes make it miss contacts (see module doc). + Every node becomes the union of its leaf geoms' boxes (body_iquat must be identity).""" + a = int(m.body_bvhadr[b]) + if a < 0: + return + ipos = np.asarray(m.body_ipos[b], float) + + def rec(i): + g = int(m.bvh_nodeid[i]) + if g >= 0: + R = _quat2mat(m.geom_quat[g]) + c = np.asarray(m.geom_pos[g]) + R @ np.asarray(m.geom_aabb[g, :3]) - ipos + h = np.abs(R) @ np.asarray(m.geom_aabb[g, 3:]) + lo, hi = c - h, c + h + else: + l1, h1 = rec(a + int(m.bvh_child[i][0])) + l2, h2 = rec(a + int(m.bvh_child[i][1])) + lo, hi = np.minimum(l1, l2), np.maximum(h1, h2) + m.bvh_aabb[i] = np.concatenate([(lo + hi) / 2, (hi - lo) / 2 + margin]) + return lo, hi + rec(a) + + +def knobbed_xml(name, half, rgba): + """box + stem + ball knob. The inertial pos is 1 mm (not 0) so that MuJoCo does not mark the inertial frame as + identical to the body frame: then the centre of mass set at runtime (body_ipos) is used.""" + geoms = [("board", "box", (0, 0, 0), half, rgba, 'friction="0.6 0.005 0.0001"'), + ("stem", "cylinder", (0, 0, half[2] + STEM_L / 2), (STEM_R, STEM_L / 2), KNOB_RGBA, + 'friction="1 0.005 0.0001"'), + ("knob", "sphere", (0, 0, half[2] + STEM_L + KNOB_R), (KNOB_R,), KNOB_RGBA, + f'friction="1 {KNOB_MU_T} 0.0001" condim="4" priority="2"')] + s = [' '] + for nm, typ, pos, size, c, extra in geoms: + s.append(f' ') + s.append(f' ') + return _wrap(name, "\n".join(s), half[2], float(np.hypot(half[0], half[1]))) + + +def flat_xml(name, half, rgba): + g = (f' ') + return _wrap(name, g, half[2], float(np.hypot(half[0], half[1]))) + + +class FenceSkills(Skills): + """Skills that feed the task's per-step stage monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class Fence(LFFTask): + name = "lh_fence" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Plan", "Reason", "Restore") + protocol = "cross" + max_attempts = 3 + agent_max_steps = 120 # careful: ~10 commands per object (50) + standing up two fallen posts (~20) + looking + instruction = ("Build a small fence: stand one wooden post upright on each of the dark square marks on the table " + "and one wooden panel upright on each of the dark strips between them, the panel's long bottom edge " + "along its strip, so that posts and panels alternate in one straight line. Every post and panel " + "has a small round knob on top; an object lifted by its knob hangs straight down. At the end every " + "square mark must have one upright post and every strip one upright panel standing on it, with the " + "gripper open and clear of the fence.") + instruction_indirect = ("Put up the little fence: the thin square sticks go upright on the dark squares, the flat " + "boards upright on the dark lines between them, lengthwise along their lines, so that " + "sticks and boards take turns in one straight row. Every piece has a round knob on top; " + "held by its knob a piece hangs straight down. At the end every square must carry one " + "upright stick and every line one upright board, and the gripper must be open and away " + "from the fence.") + agent_object_names = ["wooden fence posts (square, each with a dark knob on top)", + "wooden fence panels (flat boards, each with a dark knob on top)", + "dark square marks and dark strips on the table"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs, fx = [], [] + for i, p in enumerate(POSTS): + c = "abc"[i] + cat = register_generated(f"LffLhfPost{c.upper()}", + knobbed_xml(f"lff_lhf_post_{c}", (NOM_B / 2, NOM_B / 2, NOM_H / 2), POST_RGBA[i])) + objs.append((p, cat, f"post{i}_region", (-0.30 + 0.12 * i, 0.30, -0.29 + 0.12 * i, 0.31))) + for i, p in enumerate(PANELS): + c = "ab"[i] + cat = register_generated(f"LffLhfPanel{c.upper()}", + knobbed_xml(f"lff_lhf_panel_{c}", (NOM_T / 2, NOM_W / 2, NOM_H / 2), WOOD[i])) + objs.append((p, cat, f"panel{i}_region", (-0.30 + 0.12 * i, -0.31, -0.29 + 0.12 * i, -0.30))) + for i, k in enumerate(MARKS): + c = "abc"[i] + cat = register_generated(f"LffLhfPostmark{c.upper()}", + flat_xml(f"lff_lhf_postmark_{c}", (NOM_B / 2 + 0.003, NOM_B / 2 + 0.003, 0.0005), + MARK_RGBA), free=False) + fx.append((k, cat, f"mark{i}_region", (-0.30 + 0.12 * i, 0.10, -0.29 + 0.12 * i, 0.11))) + for i, k in enumerate(STRIPS): + c = "ab"[i] + cat = register_generated(f"LffLhfStrip{c.upper()}", + flat_xml(f"lff_lhf_strip_{c}", (STRIP_W / 2, NOM_W / 2 + 0.005, 0.0005), + STRIP_RGBA), free=False) + fx.append((k, cat, f"strip{i}_region", (-0.30 + 0.12 * i, -0.11, -0.29 + 0.12 * i, -0.10))) + return write_bddl(self.name, "Build a small fence from the posts and panels", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.fix_bid, self.fix_vis = {}, {} + for k in MARKS + STRIPS: + b = m.body_name2id(self.env.fixtures_dict[k].root_body) + self.fix_bid[k] = b + self.fix_vis[k] = [g for g in range(m.ngeom) if m.geom_bodyid[g] in + {b} | {c for c in range(m.nbody) if m.body_parentid[c] == b} and m.geom_type[g] == 6] + self.gid, self.vis, self.pbody = {}, {}, {} + for p in OBJS: + kind, c = p.split("_")[0], p.split("_")[1] + self.gid[p] = {nm: m.geom_name2id(f"{p}_lff_lhf_{kind}_{c}_{nm}") for nm in ("board", "stem", "knob")} + body = int(m.geom_bodyid[self.gid[p]["board"]]) + self.pbody[p] = body + self.vis[p] = [g for g in range(m.ngeom) if m.geom_bodyid[g] == body and m.geom_contype[g] == 0 + and m.geom_conaffinity[g] == 0] + self.geom_owner = {} + for p in OBJS: + for g in self.gid[p].values(): + self.geom_owner[g] = p + self.finger_geoms, self.hand_geoms = set(), set() + for g in envs.robot_geom_ids(self.env): + n = m.geom_id2name(g) or "" + (self.finger_geoms if "finger" in n else self.hand_geoms).add(g) + self.robot_geoms = self.finger_geoms | self.hand_geoms + # per-geom lookup tables for the substep contact check: object index (-1 none), robot part (1 finger, 2 hand) + self.owner = np.full(m.ngeom, -1, int) + for i, p in enumerate(OBJS): + self.owner[list(self.gid[p].values())] = i + self.part = np.zeros(m.ngeom, int) + self.part[list(self.finger_geoms)] = 1 + self.part[list(self.hand_geoms)] = 2 + self._sub_rob, self._sub_obj = {}, {} + # Contacts are collected after every MuJoCo substep: a fast hit (a finger flicking a knob, a hanging object + # sweeping past) can last less than one 25-substep control step (v1, measured). Wrappers chain. + sim = self.env.sim + if not getattr(sim, "_lhf_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lhf_task", None) + if t is not None and t.mon is not None: + t._substep() + sim.step = step + sim._lhf_wrapped = True + sim._lhf_task = self + self.inst = None + self.mon = None + self.sk = None + + def _substep(self): + d = self.env.sim.data + n = d.ncon + if not n: + return + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + o1, o2 = self.owner[g1], self.owner[g2] + for a, b, pa, pb in zip(g1, g2, o1, o2): + if pa < 0 and pb < 0: + continue + if pa >= 0 and pb >= 0: + if pa != pb: + self._sub_obj[int(pa)] = int(pb) + self._sub_obj[int(pb)] = int(pa) + continue + p, o = (pa, b) if pa >= 0 else (pb, a) + part = self.part[o] + if part: + prev = self._sub_rob.get(int(p), 0) + self._sub_rob[int(p)] = 1 if (part == 1 or prev == 1) else 2 + + # ------------------------------------------------------------ instances + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + row = "lr" if rng.random() < 0.5 else "fb" + hazard = bool((int(seed) * 7) % 20 < round(20 * P_HAZARD)) # balanced: 13 of every 20 consecutive seeds + t, w, h = (float(rng.uniform(*T_RANGE)), float(rng.uniform(*W_RANGE)), float(rng.uniform(*H_RANGE))) + b = float(rng.uniform(*B_RANGE)) + gap = float(rng.uniform(*GAP_RANGE)) + dens_panel, dens_post = float(rng.uniform(*DENS_RANGE)), float(rng.uniform(*DENS_RANGE)) + mu = float(rng.uniform(*MU_RANGE)) + foot = 0.0 if hazard else float(rng.uniform(*FOOT_RANGE)) + pitch = w + 2 * gap + b # post centre to post centre + if row == "lr": + c = np.array([rng.uniform(-0.12, -0.06), rng.uniform(-0.05, 0.05)]) + u = np.array([0.0, 1.0]) + v = np.array([-1.0, 0.0]) # supply side: towards the robot + else: + side = 1.0 if rng.random() < 0.5 else -1.0 + c = np.array([rng.uniform(-0.16, -0.10), side * rng.uniform(0.09, 0.13)]) + u = np.array([1.0, 0.0]) + v = np.array([0.0, -side]) # supply side: towards the middle + phi = float(np.arctan2(u[1], u[0])) # direction of the fence line + pyaw = _wrap_h(phi - np.pi / 2) # panel yaw: body y (width) along the line, body x (thickness) across + g = float(rng.uniform(*SUP_PITCH)) + d = float(rng.uniform(*SUP_D)) + shift = float(rng.choice([-1.0, 1.0]) * rng.uniform(0.04, 0.07)) + if row == "fb": # keep the farthest supply slot within ~63 cm of the robot base, the far post within ~66 cm + c[0] -= max(0.0, c[0] + shift + g - X_FAR) + c[0] -= max(0.0, c[0] + pitch - X_FAR - 0.03) + slots = [(c + u * (s - 2) * pitch / 2).tolist() for s in range(5)] + sup = [c + v * (d + j * g) + u * (shift + (k - 1) * g) for j in range(2) for k in range(3)] + pick = rng.permutation(6)[:5] + start = {OBJS[i]: (sup[j] + rng.uniform(-0.008, 0.008, 2)).tolist() for i, j in enumerate(pick)} + yaw0 = {p: pyaw + float(rng.uniform(-0.15, 0.15)) for p in OBJS} + return dict(seed=int(seed), row=row, hazard=hazard, posts="light" if hazard else "footed", foot_mass=foot, + t=t, w=w, h=h, b=b, gap=gap, pitch=pitch, density_panel=dens_panel, density_post=dens_post, mu=mu, + center=c.tolist(), u=u.tolist(), v=v.tolist(), phi=phi, pyaw=pyaw, slots=slots, + knob_dist=w / 2 + gap + b / 2, start=start, yaw0=yaw0, supply_shift=shift, supply_pitch=g, + supply_d=d) + + def _set_body(self, p, half, density, foot=0.0): + """resize p's geoms, set mass / centre of mass / inertia (board + knob + optional hidden foot), refit BVH""" + m = self.env.sim.model + hx, hy, hz = half + spec = {"board": ([hx, hy, hz], [0, 0, 0], [hx, hy, hz]), + "stem": ([STEM_R, STEM_L / 2, 0], [0, 0, hz + STEM_L / 2], [STEM_R, STEM_R, STEM_L / 2]), + "knob": ([KNOB_R, 0, 0], [0, 0, hz + STEM_L + KNOB_R], [KNOB_R, KNOB_R, KNOB_R])} + for nm, g in self.gid[p].items(): + sz, pos, aabb = spec[nm] + m.geom_size[g] = sz + m.geom_pos[g] = pos + m.geom_aabb[g] = [0, 0, 0] + aabb + m.geom_rbound[g] = float(np.linalg.norm(aabb)) + for nm, g in zip(("board", "stem", "knob"), self.vis[p]): + m.geom_size[g] = spec[nm][0] + m.geom_pos[g] = spec[nm][1] + bd = self.pbody[p] + X, Y, Z = 2 * hx, 2 * hy, 2 * hz + mb = density * X * Y * Z + zk = hz + STEM_L + KNOB_R + zf = -hz + FOOT_H / 2 + M = mb + KNOB_MASS + foot + zc = (KNOB_MASS * zk + foot * zf) / M + I = np.array([mb * (Y * Y + Z * Z) / 12, mb * (X * X + Z * Z) / 12, mb * (X * X + Y * Y) / 12]) + if foot: + I += foot * np.array([(Y * Y + FOOT_H ** 2) / 12, (X * X + FOOT_H ** 2) / 12, (X * X + Y * Y) / 12]) + par = mb * zc ** 2 + KNOB_MASS * (zk - zc) ** 2 + foot * (zf - zc) ** 2 + I[:2] += par + m.body_mass[bd] = M + m.body_ipos[bd] = [0, 0, zc] + m.body_iquat[bd] = [1, 0, 0, 0] + m.body_inertia[bd] = I + refit_bvh(m, bd) + return dict(mass=float(M), com_above_bottom=float(zc + hz)) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + self.body_info = {} + for p in POSTS: + self.body_info[p] = self._set_body(p, (inst["b"] / 2, inst["b"] / 2, inst["h"] / 2), inst["density_post"], + inst["foot_mass"]) + for p in PANELS: + self.body_info[p] = self._set_body(p, (inst["t"] / 2, inst["w"] / 2, inst["h"] / 2), + inst["density_panel"]) + for p in OBJS: + envs.set_friction(self.env, p, inst["mu"]) # board / stem / knob sliding friction ... + m.geom_friction[self.gid[p]["knob"]] = [1.0, KNOB_MU_T, 0.0001] # ... except the knob (grip pivot) + m.geom_friction[self.gid[p]["stem"]] = [1.0, 0.005, 0.0001] + m.geom_priority[self.gid[p]["knob"]] = 2 + m.geom_condim[self.gid[p]["knob"]] = 4 + self.env.sim.forward() + q = [np.cos(inst["pyaw"] / 2), 0, 0, np.sin(inst["pyaw"] / 2)] + for s, kind in enumerate(SLOT_KIND): + k = MARKS[s // 2] if kind == "post" else STRIPS[s // 2] + x, y = inst["slots"][s] + m.body_pos[self.fix_bid[k]] = [x, y, TZ + 0.0006] + m.body_quat[self.fix_bid[k]] = q + for g in self.fix_vis[k]: + m.geom_size[g] = ([inst["b"] / 2 + 0.003, inst["b"] / 2 + 0.003, 0.0005] if kind == "post" else + [STRIP_W / 2, inst["w"] / 2 + 0.005, 0.0005]) + for p in OBJS: + envs.place_upright(self.env, p, inst["start"][p], yaw=inst["yaw0"][p], clearance=0.001) + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = FenceSkills(self.env, self, recorder=recorder) + self._sub_rob, self._sub_obj = {}, {} + n = len(SLOT_KIND) + self.mon = dict(state=[False] * n, raw_since=[0] * n, ever=[False] * n, lost=[False] * n, events=[], + last_robot={p: None for p in OBJS}, last_obj={p: None for p in OBJS}, + fallen={p: False for p in OBJS}, occupant=[None] * n, n_steps=0) + return self.sk + + # ------------------------------------------------------------ geometry / predicates + @staticmethod + def kind(p): + return "post" if p.startswith("post") else "panel" + + def R(self, p): + return self.env.sim.data.body_xmat[envs.body_id(self.env, p)].reshape(3, 3).copy() + + def pos(self, p): + return envs.obj_pos(self.env, p) + + def tilt(self, p): + return float(np.arccos(np.clip(self.R(p)[2, 2], -1.0, 1.0))) + + def knob_xyz(self, p): + return self.env.sim.data.geom_xpos[self.gid[p]["knob"]].copy() + + def knob_stand_z(self): + """grasp-point height (world) of a knob centre when its object stands on the table (posts = panel height)""" + return TZ + self.inst["h"] + STEM_L + KNOB_R + + def held(self, p): + return self.sk is not None and self.sk.holding(p) + + def on_slot(self, p, s, extra=0.0): + """object p stands upright on fence slot s (right kind, lined up), resting on the table, not held""" + if self.kind(p) != SLOT_KIND[s]: + return False + R = self.R(p) + if R[2, 2] < np.cos(TILT_OK + (np.radians(1.0) if extra else 0.0)): + return False + rel = self.pos(p)[:2] - np.asarray(self.inst["slots"][s]) + du = abs(rel @ np.asarray(self.inst["u"])) + dv = abs(rel @ np.asarray(self.inst["v"])) + if SLOT_KIND[s] == "post": + if max(du, dv) > TOL_POST + extra: + return False + else: + if du > TOL_U + extra or dv > TOL_V + extra: + return False + yaw = float(np.arctan2(R[1, 0], R[0, 0])) + if abs(_wrap_h(yaw - self.inst["pyaw"])) > YAW_TOL: + return False + if envs.obj_min_z(self.env, p) > TZ + 0.006: + return False + return not self.held(p) + + def slot_occupant(self, s, extra=0.0): + return next((p for p in OBJS if self.on_slot(p, s, extra)), None) + + def slot_filled(self, s, extra=0.0): + return self.slot_occupant(s, extra) is not None + + def stages(self): + return [self.slot_filled(s) for s in range(len(SLOT_KIND))] + + def stage_names(self): + out, kc = [], {"post": 0, "panel": 0} + for kind in SLOT_KIND: + kc[kind] += 1 + out.append(f"{kind}{kc[kind]}") + return out + + # ------------------------------------------------------------ monitor + def _contacts(self): + d = self.env.sim.data + rob, obj = {}, {} + for j in range(d.ncon): + c = d.contact[j] + a, b = c.geom1, c.geom2 + pa, pb = self.geom_owner.get(a), self.geom_owner.get(b) + if pa is not None and pb is not None and pa != pb: + obj[pa], obj[pb] = pb, pa + for p, o in ((pa, b), (pb, a)): + if p is None: + continue + if o in self.finger_geoms: + rob[p] = "finger" + elif o in self.hand_geoms and rob.get(p) != "finger": + rob[p] = "hand" + return rob, obj + + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + mon["n_steps"] += 1 + t = self.sk.n_steps + rob = {OBJS[i]: ("finger" if v == 1 else "hand") for i, v in self._sub_rob.items()} + obj = {OBJS[i]: OBJS[j] for i, j in self._sub_obj.items()} + self._sub_rob, self._sub_obj = {}, {} + held = [p for p in OBJS if self.held(p)] + for p, part in rob.items(): + if p not in held: + mon["last_robot"][p] = (part, t, "open" if self.sk.grip < 0 else "closed") + for p, q in obj.items(): + if p not in held: + mon["last_obj"][p] = (q + (" (held)" if q in held else ""), t) + for p in OBJS: + f = self.tilt(p) > FALLEN + if f != mon["fallen"][p]: + mon["fallen"][p] = f + if f: + mon["events"].append(dict(object=p, event="toppled", step=int(t), cause=self._cause(p, t))) + else: + mon["events"].append(dict(object=p, event="stood_up", step=int(t))) + if mon["n_steps"] % 2: + return + names = self.stage_names() + for s in range(len(SLOT_KIND)): + occ = self.slot_occupant(s, HYST if mon["state"][s] else 0.0) + raw = occ is not None + if raw: + mon["occupant"][s] = occ + if raw == mon["state"][s]: + mon["raw_since"][s] = 0 + continue + mon["raw_since"][s] += 2 + if mon["raw_since"][s] < DEBOUNCE: + continue + mon["state"][s] = raw + mon["raw_since"][s] = 0 + t0 = t - DEBOUNCE + 1 + if raw: + ev = dict(stage=names[s], event="restored" if mon["lost"][s] else "achieved", step=int(t0)) + mon["ever"][s] = True + else: + mon["lost"][s] = True + ev = dict(stage=names[s], event="lost", step=int(t0), cause=self._slot_cause(s, t)) + mon["events"].append(ev) + + def _cause(self, p, t): + if self.held(p): + return "picked_up" + lr, lo = self.mon["last_robot"][p], self.mon["last_obj"][p] + cands = [] + if lr is not None and t - lr[1] <= 60: + cands.append((lr[1], f"robot_{lr[0]}" + ("_opening" if lr[2] == "open" else ""))) + if lo is not None and t - lo[1] <= 60: + cands.append((lo[1] - 30, "object:" + lo[0])) # prefer the robot when both touched it recently + return max(cands)[1] if cands else "other" + + def _slot_cause(self, s, t): + """why slot s lost its object: the cause recorded for the object that last stood on it""" + p = self.mon["occupant"][s] + if p is None: + c = np.asarray(self.inst["slots"][s]) + p = min(OBJS, key=lambda q: float(np.linalg.norm(self.pos(q)[:2] - c))) + return self._cause(p, t) + + # ------------------------------------------------------------ outcome + def _slot_name(self, s): + kind = SLOT_KIND[s] + idx = [i for i in range(len(SLOT_KIND)) if SLOT_KIND[i] == kind] + n = len(idx) + k = idx.index(s) # 0-based along +u + if self.inst["row"] == "lr": # u = +y = robot's left: count from the robot's right + what = "square mark" if kind == "post" else "strip" + return f"{what} {k + 1} of {n} (counting from the robot's right)" + what = "square mark" if kind == "post" else "strip" + u = self.inst["u"] + return f"{what} {k + 1 if u[0] > 0 else n - k} of {n} (counting from the one nearest the robot)" + + def _dir_words(self, d): + parts = [] + if abs(d[0]) >= 0.01: + parts.append(f"{100 * abs(d[0]):.0f} cm {'forward' if d[0] > 0 else 'back'}") + if abs(d[1]) >= 0.01: + parts.append(f"{100 * abs(d[1]):.0f} cm {'left' if d[1] > 0 else 'right'}") + return (" and ".join(parts) + " of") if parts else "right at" + + def placed_objects(self): + return {p for p in OBJS if any(self.on_slot(p, s) for s in range(len(SLOT_KIND)))} + + def outcome(self, inst): + sk = self.sk + sk.hold(10) + p0 = {p: self.pos(p) for p in OBJS} + touching = False + for _ in range(20): + sk.hold(1) + rob, _ = self._contacts() + touching = touching or any(p in rob for p in OBJS) + moved = max(float(np.linalg.norm(self.pos(p) - p0[p])) for p in OBJS) + static = moved < 0.004 + raw = self.stages() + held = [p for p in OBJS if self.held(p)] + mon = self.mon + ev = list(mon["events"]) if mon else [] + n_reg = sum(e["event"] == "lost" for e in ev) + n_res = sum(e["event"] == "restored" for e in ev) + n_top = sum(e["event"] == "toppled" for e in ev) + success = bool(all(raw) and static and not held and not touching) + names = self.stage_names() + parts = [] + ever = mon["ever"] if mon else [False] * len(raw) + if success: + failure = "none" + parts.append("The fence is complete: every square mark carries an upright post and every strip an " + "upright panel lined up with it.") + else: + lost_final = [s for s in range(len(raw)) if not raw[s] and ever[s]] + never = [s for s in range(len(raw)) if not raw[s] and not ever[s]] + if held: + failure = "held" + elif touching: + failure = "touching" + elif lost_final: + failure = "regressed" + elif never: + failure = "incomplete" + else: + failure = "not_static" + placed = self.placed_objects() + described = set() + for s in range(len(raw)): + if raw[s]: + continue + kind = SLOT_KIND[s] + c = np.asarray(inst["slots"][s]) + spare = [q for q in OBJS if self.kind(q) == kind and q not in placed and q not in described] + near = min(spare, key=lambda q: float(np.linalg.norm(self.pos(q)[:2] - c))) if spare else None + dist = float(np.linalg.norm(self.pos(near)[:2] - c)) if near else 1.0 + if near is None or (not ever[s] and dist > 0.06): + txt = f"{self._slot_name(s)} has no {kind} on it (none was put there)." + else: + described.add(near) + tl = np.degrees(self.tilt(near)) + state = ("lies fallen" if tl > 45 else f"leans {tl:.0f} degrees" if tl > np.degrees(TILT_OK) + else "stands") + txt = (f"{self._slot_name(s)} has no upright {kind} on it: the nearest {kind} {state} " + f"{self._dir_words(self.pos(near)[:2] - c)} it.") + if ever[s]: + lost = [e for e in ev if e.get("stage") == names[s] and e["event"] == "lost"] + why = lost[-1]["cause"] if lost else "other" + txt += {"robot_finger_opening": f" The {kind} had stood there; a finger pushed it when the " + f"gripper opened.", + "robot_hand_opening": f" The {kind} had stood there; the hand pushed it.", + }.get(why, f" The {kind} had stood there and was knocked over later." + if why.startswith(("robot", "object")) else f" The {kind} had stood there earlier.") + parts.append(txt) + if all(raw) and held: + parts.append("The gripper still holds an object.") + elif touching: + parts.append("The gripper is still touching the fence.") + elif all(raw) and not static: + parts.append("Something was still moving.") + if n_reg: + parts.append(f"During the attempt objects on the fence line were knocked off {n_reg} time(s) and stood " + f"up again {n_res} time(s).") + if any(w in " ".join(parts) for w in (" forward of", " back of", " back and", " forward and")): + parts.append("(Forward = away from the robot.)") + return dict(success=success, stages={names[s]: bool(raw[s]) for s in range(len(raw))}, events=ev, + n_regressions=int(n_reg), n_restored=int(n_res), n_toppled=int(n_top), failure=failure, + held=held, touching=bool(touching), static=bool(static), + tilts_deg={p: round(float(np.degrees(self.tilt(p))), 1) for p in OBJS}, detail=" ".join(parts)) + + # ------------------------------------------------------------ scripted policies (move_to + gripper only) + def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300): + return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + + def axis(self, p, i): + a = self.R(p)[:2, i] + return a / max(np.linalg.norm(a), 1e-9) + + def grasp_yaw(self, p, mode): + """yaw for a top-down knob grasp. Lying object: fingers across its long axis (it swings up and hangs). + Panel: 'habit' = fingers along its width (hand along the board; along the fence line once placed), + 'thin' = fingers along its thickness (across the line). Post: 'thin' = fingers across the fence line, otherwise + the side direction needing the least rotation (a post's own orientation does not matter: square, round knob).""" + R = self.R(p) + if R[2, 2] < np.cos(np.radians(30)): + ax = R[:2, 2] + if np.linalg.norm(ax) > 1e-3: + return _yaw_for_axis(np.array([-ax[1], ax[0]])) + if self.kind(p) == "panel": + return _yaw_for_axis(self.axis(p, 1) if mode == "habit" else self.axis(p, 0)) + if mode == "thin": # careful: a post's fingers across the fence line too (they reach nothing there) + return _yaw_for_axis(np.asarray(self.inst["v"])) + y0 = _yaw_for_axis(self.axis(p, 0)) + return min((_wrap_h(y0), _wrap_h(y0 + np.pi / 2)), key=lambda y: abs(_wrap_h(y - self.sk.yaw))) + + def obj_yaw(self, p): + R = self.R(p) + return float(np.arctan2(R[1, 0], R[0, 0])) + + def pick(self, p, mode, careful, z_carry=None, noise=None, v=0.15): + """grasp p's knob and lift it; returns (object yaw - gripper yaw) or None if not held""" + sk = self.sk + k = self.knob_xyz(p) + if noise is not None: + k = k + np.array([noise[0], noise[1], 0.0]) + yaw = self.grasp_yaw(p, mode) + zk = max(k[2], TZ + 0.006) + sk.set_gripper(False, steps=8) + if careful: + cur = sk.eef_pos() + if cur[2] < TZ + Z_SAFE - 0.01: + self._go([cur[0], cur[1], TZ + Z_SAFE]) + self._go([k[0], k[1], TZ + Z_SAFE], yaw=yaw, speed=0.3) + self._go([k[0], k[1], zk + 0.04], speed=0.25) + self._go([k[0], k[1], zk], speed=0.1, tol=0.003, max_steps=150) + else: # Sonnet-like: over the knob at carry height, down at 0.1 to 1.5 cm above, last 1.5 cm at 0.04 + zt = TZ + (Z_NAIVE if z_carry is None else z_carry) + cur = sk.eef_pos() + self._go([k[0], k[1], max(cur[2], zt, zk + 0.06)], yaw=yaw, speed=v) + self._go([k[0], k[1], zk + 0.015], speed=0.1) + self._go([k[0], k[1], zk], speed=0.04, tol=0.003, max_steps=150) + sk.set_gripper(True, steps=15) + if careful: + self._go([k[0], k[1], TZ + Z_SAFE], speed=0.25) + else: + self._go([k[0], k[1], TZ + (Z_NAIVE if z_carry is None else z_carry)], speed=0.08) + sk.hold(10) + if not self.held(p): + sk.set_gripper(False, steps=8) # already lifted: the fingers open well above the object + return None + return float(self.obj_yaw(p) - sk.yaw) + + def release_z(self, p): + """grasp-point height at which the held object's bottom is 2 mm above the table (a heavy object's knob can + sit a few mm low in the fingers; pressing it onto the table would squeeze the knob out of the grip)""" + dz = float(self.sk.eef_pos()[2] - self.knob_xyz(p)[2]) if self.held(p) else 0.0 + return self.knob_stand_z() + 0.002 + float(np.clip(dz, -0.005, 0.015)) + + def place_yaw(self, p, offset): + """gripper yaw that lines p up with the fence (panel: width along the line; post: sides along it)""" + if self.kind(p) == "panel": + return _wrap_h(self.inst["pyaw"] - offset) + cands = [_wrap_h(self.inst["pyaw"] + k * np.pi / 2 - offset) for k in range(4)] + return min(cands, key=lambda y: abs(_wrap_h(y - self.sk.yaw))) + + def place(self, p, s, offset, careful, z_carry=None, noise=None, lift=None, v=0.15): + """carry the held object to fence slot s, lined up with the fence; set it down; let go""" + sk = self.sk + xy = np.asarray(self.inst["slots"][s], float) + (np.asarray(noise, float) if noise is not None else 0.0) + yaw = self.place_yaw(p, offset) + zr = self.release_z(p) + if careful: + cur = sk.eef_pos() + if cur[2] < TZ + Z_SAFE - 0.01: + self._go([cur[0], cur[1], TZ + Z_SAFE]) + self._go([xy[0], xy[1], TZ + Z_SAFE], yaw=yaw, speed=0.3) + sk.hold(15) + zr = self.release_z(p) + self._go([xy[0], xy[1], zr + 0.03], speed=0.2) + self._go([xy[0], xy[1], zr], speed=0.06, tol=0.003, max_steps=150) + sk.set_gripper(False, steps=12) + self._go([xy[0], xy[1], zr + 0.04], speed=0.1) + self._go([xy[0], xy[1], TZ + Z_SAFE], speed=0.3) + else: # Sonnet-like: to above the slot at carry height, 0.1 m/s to 1.5 cm above, last 1.5 cm at 0.03, open + zt = TZ + (Z_NAIVE if z_carry is None else z_carry) + cur = sk.eef_pos() + self._go([xy[0], xy[1], max(cur[2], zt)], yaw=yaw, speed=v) + self._go([xy[0], xy[1], zr + 0.015], speed=0.1) + self._go([xy[0], xy[1], zr], speed=0.03, tol=0.003, max_steps=150) + sk.set_gripper(False, steps=12) + self._go([xy[0], xy[1], TZ + (Z_NAIVE if lift is None else lift)], speed=0.15) + sk.hold(5) + + # orders --------------------------------------------------------------- + def supply_center(self): + return np.mean([self.inst["start"][p] for p in OBJS], axis=0) + + def fence_order(self, far_first=True): + """slot indices from the end of the line farthest from the supply to the near end (or reversed)""" + sc = self.supply_center() + first, last = np.asarray(self.inst["slots"][0]), np.asarray(self.inst["slots"][-1]) + idx = list(range(len(SLOT_KIND))) + near_first = idx if np.linalg.norm(first - sc) <= np.linalg.norm(last - sc) else idx[::-1] + return near_first[::-1] if far_first else near_first + + def build(self, order, careful, panel_mode, noise_fn=lambda: None, z_carry=None, lift=None, noise_pick=False, + v=0.15): + """put an object on every slot that has none, in the given slot order; the object for each slot: an unused + one of the right kind, the nearest to the gripper (naive) / to the slot (careful). No looking back.""" + fails = {} + used = set() + for s in order: + if self.slot_filled(s): + continue + for _ in range(2): + cand = [p for p in OBJS if self.kind(p) == SLOT_KIND[s] and p not in used and fails.get(p, 0) < 2 + and p not in self.placed_objects()] + if not cand: + break + ref = np.asarray(self.inst["slots"][s]) if careful else self.sk.eef_pos()[:2] + p = min(cand, key=lambda q: float(np.linalg.norm(self.pos(q)[:2] - ref))) + mode = panel_mode if self.kind(p) == "panel" else ("thin" if careful else "any") + off = self.pick(p, mode, careful, z_carry=z_carry, noise=noise_fn() if noise_pick else None, v=v) + if off is None: + fails[p] = fails.get(p, 0) + 1 + continue + used.add(p) + self.place(p, s, off, careful, z_carry=z_carry, noise=noise_fn(), lift=lift, v=v) + break + + def footprint(self, p): + """sample points of p's collision box projected onto the table (corners, edge and face midpoints) + knob""" + R, c = self.R(p), self.pos(p) + if self.kind(p) == "panel": + h = np.array([self.inst["t"], self.inst["w"], self.inst["h"]]) / 2 + else: + h = np.array([self.inst["b"], self.inst["b"], self.inst["h"]]) / 2 + pts = [c + R @ (h * [a, b, z]) for a in (-1, 0, 1) for b in (-1, 0, 1) for z in (-1, 0, 1)] + pts.append(self.knob_xyz(p)) + return np.array(pts)[:, :2] + + def slot_blocked(self, s, ignore=()): + """an object that is not standing on a slot lies (partly) on slot s or right next to it""" + c = np.asarray(self.inst["slots"][s]) + u, v = np.asarray(self.inst["u"]), np.asarray(self.inst["v"]) + hu = (self.inst["w"] if SLOT_KIND[s] == "panel" else self.inst["b"]) / 2 + 0.003 + hv = (self.inst["t"] if SLOT_KIND[s] == "panel" else self.inst["b"]) / 2 + 0.008 + placed = self.placed_objects() + for q in OBJS: + if q in ignore or self.held(q) or q in placed: # objects standing on their own slots are fine + continue + d = self.footprint(q) - c + if np.any((np.abs(d @ u) < hu) & (np.abs(d @ v) < hv)): + return True + return False + + def fingers_along_width(self, p): + """the held panel's width axis is (nearly) parallel to the finger axis""" + fa = np.array([-np.sin(self.sk.yaw), np.cos(self.sk.yaw)]) + return abs(float(self.axis(p, 1) @ fa)) > 0.7 + + def repair(self, rounds=None): + """look at every slot; stand fallen / misplaced objects up again by their knobs (careful motions, panels + released with the fingers across the line). Order: an object resting on another first, then fallen / leaning + ones from the top of the pile down, then upright ones that are off their slots. A panel lifted with its + fingers along its width (a fallen panel can only be lifted that way) is first set down standing at a free spot + and re-grasped. Returns the number of objects moved.""" + n = len(SLOT_KIND) + moved = 0 + fails, moves = {}, {} + for _ in range(rounds or 16): + if all(self.stages()): + break + ok = self.placed_objects() + loose = [p for p in OBJS if p not in ok and fails.get(p, 0) < 2 and moves.get(p, 0) < 4] + if not loose: + break + on_other = [p for p in loose if envs.obj_min_z(self.env, p) > TZ + 0.006] + down = [p for p in loose if p not in on_other and self.tilt(p) > TILT_OK] + upright = [p for p in loose if p not in on_other and p not in down] + if on_other: + p = max(on_other, key=lambda q: self.knob_xyz(q)[2]) + elif down: + p = max(down, key=lambda q: self.knob_xyz(q)[2]) + else: + fit = {q: [s for s in range(n) if SLOT_KIND[s] == self.kind(q) and not self.slot_filled(s) + and not self.slot_blocked(s, ignore=(q,))] for q in upright} + fit = {q: js for q, js in fit.items() if js} + if not fit: + break + p = min(fit, key=lambda q: min(float(np.linalg.norm(self.pos(q)[:2] - np.asarray( + self.inst["slots"][s]))) for s in fit[q])) + off = self.pick(p, "thin", True) + if off is None: + fails[p] = fails.get(p, 0) + 1 + continue + moved += 1 + moves[p] = moves.get(p, 0) + 1 + if self.kind(p) == "panel" and self.fingers_along_width(p): + self.place_at(p, self.free_spot(), off) + continue + clear = [s for s in range(n) if SLOT_KIND[s] == self.kind(p) and not self.slot_filled(s) + and not self.slot_blocked(s, ignore=(p,))] + if not clear: + self.place_at(p, self.free_spot(), off) + continue + here = self.sk.eef_pos()[:2] + s = min(clear, key=lambda j: float(np.linalg.norm(np.asarray(self.inst["slots"][j]) - here))) + self.place(p, s, off, True) + return moved + + def free_spot(self): + """the reachable table spot (around the fence and the supply) farthest from every object and slot""" + c, v = np.asarray(self.inst["center"]), np.asarray(self.inst["v"]) + u = np.asarray(self.inst["u"]) + best, bc = None, -1.0 + for a in np.linspace(-0.20, 0.20, 9): + for b in (-0.18, -0.12, 0.10, 0.20, 0.32): + q = c + v * b + u * a + if not (-0.40 < q[0] < 0.08 and -0.32 < q[1] < 0.32) or np.hypot(q[0] + 0.66, q[1]) > 0.60: + continue + cl = min(float(np.linalg.norm(self.pos(o)[:2] - q)) for o in OBJS) + cl = min(cl, min(float(np.linalg.norm(np.asarray(sl) - q)) for sl in self.inst["slots"])) + if cl > bc: + best, bc = q, cl + return best + + def place_at(self, p, xy, offset): + """careful: set the held object down standing at a free spot""" + sk = self.sk + zr = self.release_z(p) + cur = sk.eef_pos() + if cur[2] < TZ + Z_SAFE - 0.01: + self._go([cur[0], cur[1], TZ + Z_SAFE]) + self._go([xy[0], xy[1], TZ + Z_SAFE], yaw=self.place_yaw(p, offset), speed=0.3) + sk.hold(15) + zr = self.release_z(p) + self._go([xy[0], xy[1], zr + 0.03], speed=0.2) + self._go([xy[0], xy[1], zr], speed=0.06, tol=0.003, max_steps=200) + sk.set_gripper(False, steps=12) + self._go([xy[0], xy[1], zr + 0.04], speed=0.1) + self._go([xy[0], xy[1], TZ + Z_SAFE], speed=0.3) + + # ------------------------------------------------------------ policies + def execute(self, inst, params): + careful = params["careful"] + noise = params.get("noise", 0.0) + rng = np.random.default_rng(params.get("noise_seed", 0)) + nf = (lambda: rng.uniform(-noise, noise, 2)) if noise else (lambda: None) + if params.get("order") == "panels_first": + fo = self.fence_order(True) + order = [s for s in fo if SLOT_KIND[s] == "panel"] + [s for s in fo if SLOT_KIND[s] == "post"] + elif params.get("order") == "posts_first": + fo = self.fence_order(True) + order = [s for s in fo if SLOT_KIND[s] == "post"] + [s for s in fo if SLOT_KIND[s] == "panel"] + else: + order = self.fence_order(params.get("far_first", True)) + self.build(order, careful, params["panel_mode"], noise_fn=nf, z_carry=params.get("z_carry"), + lift=params.get("lift"), noise_pick=params.get("noise_pick", False), v=params.get("v", 0.15)) + if params.get("check"): + self.repair() + cur = self.sk.eef_pos() + if cur[2] < TZ + 0.20: + self._go([cur[0], cur[1], TZ + 0.20], speed=0.3) + self.sk.hold(10) + + # naive = Sonnet 5.5's habits measured in the lh2_fence pilot: hand (finger axis) along the board's long side, fill + # from the far end, carry 21 cm above the table at 0.15 m/s, slow last 1.5 cm, ~1 cm placement error, no re-check + NAIVE = dict(careful=False, panel_mode="habit", far_first=True, check=False, noise=NAIVE_ERR) + CAREFUL = dict(careful=True, panel_mode="thin", far_first=True, check=True) + V1_NAIVE = dict(careful=False, panel_mode="thin", far_first=False, check=False) # v1's scripted naive habits + + def default_params(self, inst): + return dict(self.NAIVE, noise_seed=int(inst["seed"]) * 11) + + def oracle_params(self, inst): + return dict(self.CAREFUL) + + def adapt_params(self, inst, history): + """from attempt 2 (after a failure): panels released with the fingers across the line, careful, final check""" + return dict(self.CAREFUL) + + def blind_params(self, inst, attempt, rng): + """the naive behaviour with random variations, no history, no check""" + return dict(self.NAIVE, noise_seed=int(rng.integers(1 << 30)), z_carry=float(rng.uniform(0.15, 0.23)), + lift=float(rng.uniform(0.15, 0.23)), v=float(rng.uniform(0.08, 0.25))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + single = ("oracle", "naive", "oracle_noise", "v1_naive", "naive_thin", "naive_panels_first", + "naive_posts_first") + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": # control: cross-attempt learning only (careful from attempt 2), no check + params = self.default_params(inst) if a == 0 else dict(self.CAREFUL, check=False) + elif kind == "oracle_noise": # check: careful with +-5 mm (uniform, per axis) placement noise + params = dict(self.CAREFUL, noise=0.005, noise_seed=int(seed) * 7 + a) + elif kind == "v1_naive": # control: v1's scripted naive (fingers across the line, near end first) + params = dict(self.V1_NAIVE) + elif kind == "naive_thin": # control: Sonnet-like but panels released with the fingers across the line + params = dict(self.default_params(inst), panel_mode="thin") + elif kind == "naive_panels_first": # control: Sonnet-like grasp, both panels before the posts + params = dict(self.default_params(inst), order="panels_first") + elif kind == "naive_posts_first": # control: Sonnet-like grasp, all posts first (how fences are built) + params = dict(self.default_params(inst), order="posts_first") + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in single: + break + return history diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/lh_parts_cart.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/lh_parts_cart.py new file mode 100644 index 0000000000000000000000000000000000000000..e8992d05ab373c966acef42134bb2f87ddec4743 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/lh_parts_cart.py @@ -0,0 +1,253 @@ +"""Composite prototype: physical tool retrieval, loading regression and asymmetric cart transport. + +Not part of main_v1. See task_cards/lh_parts_cart.md for validation status. +Only reset_instance/apply_instance position objects; all reference actions use the public motion skills. +""" +import copy +import numpy as np +from .. import envs +from ..bddl import write_bddl +from ..objects import register_generated, box_xml +from ..task_base import register_task +from .l3_tool import (UnderTableTool, low_table_xml, stick_xml, CUBE_HALF, + HANDLE_HALF, TOP_HALF) +from .l7_offcenter_push import (OffcenterPush, PushSkills, long_box_xml, rect_frame_xml, + HALF, MASS, MU, BOX, _rot) + + +class CartSkills(PushSkills): + def __init__(self,*args,**kwargs): + super().__init__(*args,**kwargs) + self.robot_commands=0 + def move_to(self,*args,**kwargs): + self.robot_commands+=1 + return super().move_to(*args,**kwargs) + def set_gripper(self,*args,**kwargs): + self.robot_commands+=1 + return super().set_gripper(*args,**kwargs) + + +@register_task +class PartsCart(UnderTableTool): + name = 'lh_parts_cart' + level = 'L4' + category = 'geometry_inference' + failure_causes = ('L4', 'L2', 'L5') + capabilities = ('Perceive', 'Reason', 'Plan', 'Restore') + protocol = 'cross' + agent_max_steps = 180 + instruction = ('Use the wooden tool to retrieve the red part from under the low glass table. ' + 'Load the red and blue parts on the two marks on the brown transport platform, ' + 'then push the loaded platform with the closed gripper completely into the green parking area. ' + 'At the end both parts must still be on their marks, and the gripper must be open and clear.') + instruction_indirect = instruction + + def make_bddl(self): + cube = register_generated('LffPartsCartRed', box_xml('lff_parts_cart_red', (CUBE_HALF,)*3,(.85,.12,.12,1), density=300)) + blue = register_generated('LffPartsCartBlue', box_xml('lff_parts_cart_blue', (CUBE_HALF,)*3,(.1,.2,.85,1), density=300)) + stick_xml_text=stick_xml('lff_parts_cart_stick').replace('size="0.00800 0.02500 0.01000"','size="0.00800 0.00800 0.01000"') + stick = register_generated('LffPartsCartStick', stick_xml_text) + table_xml=low_table_xml('lff_parts_cart_table') + # Wider roof with legs outside the blocked cube's x-exit lane. This prevents a panel failure + # trapping the cube against a corner leg, which the existing standalone task did not test in-attempt. + table_xml=table_xml.replace('size="0.06000 0.06000 0.00500"','size="0.06000 0.07500 0.00500"') + for sx in (-.052,.052): + for sy in (-.052,.052): + table_xml=table_xml.replace(f'pos="{sx:.5f} {sy:.5f} 0.03500"',f'pos="{sx:.5f} {np.sign(sy)*.067:.5f} 0.03500"') + table = register_generated('LffPartsCartTable', table_xml, free=False) + xml=long_box_xml('lff_parts_cart_platform') + marks=''.join(f'' for y,color in [(-.03,'.9 .4 .4 1'),(.03,'.4 .5 .9 1')]) + xml=xml.replace(' ',marks+' ',1) + cart = register_generated('LffPartsCartPlatform', xml) + zone = register_generated('LffPartsCartZone', rect_frame_xml('lff_parts_cart_zone'), free=False) + # Inertial/shape match existing off-centre box, with purely visual cargo marks. + objs=[('cube_1',cube,'red_region',(-.31,-.26,-.29,-.24)), + ('blue_1',blue,'blue_region',(-.31,.24,-.29,.26)), + ('stick_1',stick,'stick_region',(-.01,-.36,.01,-.34)), + ('box_1',cart,'cart_region',(.19,.24,.21,.26))] + fx=[('lowtable_1',table,'table_region',(.19,-.11,.21,-.09)), + ('zone_1',zone,'zone_region',(.19,.39,.21,.41))] + return write_bddl(self.name,self.instruction,objs,fx) + + def sample_instance(self, seed): + # Tool geometry is inherited; put transport in the other half of the same tabletop. + rng=np.random.default_rng(seed) + base=super().sample_instance(seed) + base.update(side=-1, pane_side=1, table_xy=[-.08,-.08],cube_xy=[-.08,-.08], + stick_xy=[-.08,-.34],stick_yaw=np.pi/2, + box_xy=[-.25,.24],target_dist=.16, + com_offset=float(rng.choice([-1,1])*rng.uniform(.05,.065)), + traps=dict(L4=True,L2=True,L5=True)) + base['bin_xy']=[-.25,.24] # inherited observe() only; no bin fixture. + return base + + def target_xy(self, inst): + return np.array([inst['box_xy'][0]+inst['target_dist'],inst['box_xy'][1]]) + + def apply_instance(self, inst): + self.inst=inst + m=self.env.sim.model + bid,_=self._fixture('lowtable_1') + m.body_pos[bid]=[*inst['table_xy'],envs.TABLE_Z] + for g,sy in self._panes(): + on=inst['traps']['L4'] and sy==inst['pane_side'] + m.geom_contype[g]=m.geom_conaffinity[g]=int(on) + envs.set_obj_pose(self.env,'cube_1',[*inst['cube_xy'],envs.TABLE_Z+CUBE_HALF+.0005]) + envs.set_obj_pose(self.env,'blue_1',[-.30,.04,envs.TABLE_Z+CUBE_HALF+.0005]) + envs.set_obj_pose(self.env,'stick_1',[*inst['stick_xy'],envs.TABLE_Z+HANDLE_HALF[2]+.0005],yaw=inst['stick_yaw']) + bid=envs.body_id(self.env,BOX) + m.body_mass[bid]=MASS + m.body_ipos[bid]=[0,inst['com_offset'] if inst['traps']['L5'] else 0,0] + for g in range(m.ngeom): + if m.geom_bodyid[g]==bid and (np.allclose(m.geom_rgba[g,:3],[.9,.4,.4]) or np.allclose(m.geom_rgba[g,:3],[.4,.5,.9])): + m.geom_pos[g,1]=np.sign(m.geom_pos[g,1])*(.03 if inst['traps']['L2'] else .07) + envs.refit_bounds(self.env,bid) + envs.set_friction(self.env,BOX,MU) + envs.set_obj_pose(self.env,BOX,[*inst['box_xy'],envs.TABLE_Z+HALF[2]+.001]) + zb=m.body_name2id(self.env.fixtures_dict['zone_1'].root_body) + m.body_pos[zb]=[*self.target_xy(inst),envs.TABLE_Z+.0002] + + def reset_instance(self, inst, recorder=None): + self.loadmon=None + self._mon=None + self.env.reset();self.apply_instance(inst);self.env.sim.forward();envs.settle(self.env,15) + self.sk=CartSkills(self.env,recorder=recorder,target=self.target_xy(inst)) + self._start_monitor() + self.loadmon=dict(states=[False,False],count=[0,0],ever=[False,False],lost=[False,False],events=[],loaded=False,departed_unloaded=False,load_step=None,departure_step=None,last_robot_touch=[-10000,-10000]) + self.ncmd=0;self.budget=None + return self.sk + + def mark(self,i): + p,yaw=self.sk._box_pose() if self.sk else (envs.obj_pos(self.env,BOX),0.) + spacing=.03 if self.inst['traps']['L2'] else .07 + return p[:2]+_rot(yaw)@np.array([0.,(-spacing,spacing)[i]]) + + def cargo_ok(self,i): + obj=('cube_1','blue_1')[i] + p=envs.obj_pos(self.env,obj); bp=envs.obj_pos(self.env,BOX) + return bool(np.linalg.norm(p[:2]-self.mark(i))<.018 and + abs(p[2]-(bp[2]+HALF[2]+CUBE_HALF))<.012 and not self.sk.holding(obj)) + + def _monitor_step(self): + super()._monitor_step() + mon=getattr(self,'loadmon',None) + if mon is None:return + robot=set(envs.robot_geom_ids(self.env)) + for i,obj in enumerate(('cube_1','blue_1')): + geoms=set(envs.obj_geom_ids(self.env,obj)) + for c in self.env.sim.data.contact[:self.env.sim.data.ncon]: + if (c.geom1 in robot and c.geom2 in geoms) or (c.geom2 in robot and c.geom1 in geoms): + mon['last_robot_touch'][i]=self.sk.n_steps + now=self.cargo_ok(i) + if now==mon['states'][i]:mon['count'][i]=0;continue + mon['count'][i]+=1 + if mon['count'][i]<5:continue + mon['count'][i]=0;mon['states'][i]=now + ev='restored' if now and mon['lost'][i] else 'achieved' if now else 'lost' + if now:mon['ever'][i]=True + else: + mon['lost'][i]=True + if np.linalg.norm(envs.obj_pos(self.env,BOX)[:2]-self.inst['box_xy'])<.025: + mon['loaded']=False + mon['load_step']=None + mon['events'].append(dict(step=self.sk.n_steps,pred=('red','blue')[i],event=ev, + cart_displacement=float(np.linalg.norm(envs.obj_pos(self.env,BOX)[:2]-self.inst['box_xy'])), + cause='robot' if self.sk.n_steps-mon['last_robot_touch'][i]<=20 else 'other')) + displacement=np.linalg.norm(envs.obj_pos(self.env,BOX)[:2]-self.inst['box_xy']) + if all(mon['states']) and displacement<.02 and not mon['loaded']: + mon['loaded']=True + mon['load_step']=self.sk.n_steps + if displacement>.03 and mon['departure_step'] is None: + mon['departure_step']=self.sk.n_steps + if not mon['loaded']:mon['departed_unloaded']=True + + def pick_place(self,obj,xy,yaw=0.): + sk=self.sk;p=envs.obj_pos(self.env,obj) + sk.set_gripper(False,steps=10) + sk.move_to([p[0],p[1],envs.TABLE_Z+.18],yaw=0. if obj=='cube_1' and self.under_table(margin=.08) else yaw) + sk.move_to([p[0],p[1],p[2]-.004],speed=.10,tol=.002) + sk.set_gripper(True,steps=15) + held=sk.holding(obj) + sk.move_to([p[0],p[1],envs.TABLE_Z+.20],speed=.15) + if held: + sk.move_to([xy[0],xy[1],envs.TABLE_Z+.20],yaw=yaw) + bp=envs.obj_pos(self.env,BOX) + sk.move_to([xy[0],xy[1],bp[2]+HALF[2]+CUBE_HALF-.003],speed=.06,tol=.002) + sk.set_gripper(False,steps=15) + sk.move_to([xy[0],xy[1],envs.TABLE_Z+.22],speed=.15) + return bool(held) + + def load(self, careful=True): + self.pick_place('cube_1',self.mark(0),np.pi/2) + # Open fingers along y at the adjacent mark can knock the already loaded red cube. + yaw=np.pi/2 if careful else 0. + self.pick_place('blue_1',self.mark(1),yaw) + + def repair_load(self): + for _ in range(3): + for i,o in enumerate(('cube_1','blue_1')): + if not self.cargo_ok(i):self.pick_place(o,self.mark(i),np.pi/2) + + def transport(self,c=0.,repair=False): + # Call existing push controller on this same environment; no independent rollout stitching. + if not repair: + return OffcenterPush.execute(self,self.inst,dict(c=c)) + if repair: + # Original feedback-driven corrector calls self.execute for its initial push. + self._transport_only=True + try:OffcenterPush.adaptive_attempt(self,self.inst,c) + finally:self._transport_only=False + + _cmd=OffcenterPush._cmd + _sim_used=OffcenterPush._sim_used + _push_at=OffcenterPush._push_at + bracket=OffcenterPush.bracket + _front_runup=staticmethod(OffcenterPush._front_runup) + STEP=OffcenterPush.STEP;YAW_OK=OffcenterPush.YAW_OK + GAIN0=OffcenterPush.GAIN0;SAFE_V=OffcenterPush.SAFE_V + + def execute(self,inst,params): + if getattr(self,'_transport_only',False):return OffcenterPush.execute(self,inst,params) + if params.get('front',False):self.tool_push_front() + else:self.tool_push_out() + if self.under_table():return + self.load(params.get('careful',False)) + if params.get('repair',False):self.repair_load() + if all(self.cargo_ok(i) for i in range(2)): + self.transport(params.get('c',0.),params.get('repair',False)) + if params.get('repair',False):self.repair_load() + self.sk.set_gripper(False,steps=10) + p=self.sk.eef_pos();self.sk.move_to([p[0],p[1],envs.TABLE_Z+.24]) + + def default_params(self,inst):return dict(front=False,careful=False,repair=False,c=0.) + def oracle_params(self,inst):return dict(front=True,careful=True,repair=True,c=inst['com_offset'] if inst['traps']['L5'] else 0.) + def adapt_params(self,inst,history): + # The L4 side hit is learned from actual prior outcome, not from inst['pane_side']. + seen_geometry=any(h['outcome']['traps']['L4'] for h in history) + seen_loading=any(h['outcome']['traps']['L2'] for h in history) + pushes=[m for h in history for m in h['outcome']['box_moves']] + return dict(front=seen_geometry,careful=seen_loading,repair=bool(history),c=self.bracket(pushes)) + + def outcome(self,inst): + self.sk.hold(30) + fit=self.sk.fit();cargo=[self.cargo_ok(i) for i in range(2)] + ev=list(self.loadmon['events']) + # Loading regressions count only while cart remains at the loading station. + load_lost=[e for e in ev if e['event']=='lost' and e['cart_displacement']<.025 and e['cause']=='robot'] + loaded=self.loadmon['loaded'] + static=bool(np.max(np.abs(self.env.sim.data.qvel))<.05) + robot=set(envs.robot_geom_ids(self.env)); items=set() + for o in ('cube_1','blue_1',BOX,'stick_1'):items.update(envs.obj_geom_ids(self.env,o)) + touching=any((c.geom1 in robot and c.geom2 in items) or (c.geom2 in robot and c.geom1 in items) + for c in self.env.sim.data.contact[:self.env.sim.data.ncon]) + budget_ok=bool(self.sk.robot_commands<=self.agent_max_steps and self.sk.n_steps*.05<=self.agent_max_steps*3) + success=bool(not self.under_table() and all(cargo) and fit['inside'] and loaded + and not self.loadmon['departed_unloaded'] and static and not touching and budget_ok and self.sk.grip<0 + and self._mon['stick_touched_cube']) + moves=copy.deepcopy(self.sk.box_moves) + return dict(success=success,stages=dict(retrieved=not self.under_table(),red=cargo[0],blue=cargo[1],parked=fit['inside'],loaded=loaded), + static=static,touching=bool(touching),tool_used=bool(self._mon['stick_touched_cube']),load_step=self.loadmon['load_step'],departure_step=self.loadmon['departure_step'],commands=self.sk.robot_commands,budget_ok=budget_ok,departed_unloaded=self.loadmon['departed_unloaded'], + events=ev,n_regressions=len(load_lost),n_restored=sum(e['event']=='restored' for e in ev), + traps=dict(L4=bool(self._mon['cube_hit_pane']),L2=bool(load_lost),L5=any(m['bad'] for m in moves)), + box_moves=moves,cart_pose=[*envs.obj_pos(self.env,BOX).tolist()],cart_fit=fit, + detail=f'Retrieved={not self.under_table()}; cargo on marks={cargo}; platform parked={fit["inside"]}.') diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/lh_tidy_stack.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/lh_tidy_stack.py new file mode 100644 index 0000000000000000000000000000000000000000..7eb80b6f3a418bf965b10bad15f99797241128a5 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/lh_tidy_stack.py @@ -0,0 +1,1260 @@ +"""LH lh_tidy_stack v2 (2026-10-16): tidy the table -- stack the four storage boxes (red, green, blue, yellow; alike, +6 x 6 x 5 cm) into one pile on a grey mat, in any order, then stand the cup on top. In 18 of every 20 instances one box +(random colour) is an empty, soft carton: it carries one thing, but as soon as a second thing comes to rest above it, +it gives way -- standing it folds sideways, lying on a side face it is crushed flat -- and everything above it slides +off the pile: the stage that made the pile two higher destroys the stage before it. + +Family: long-horizon self-disturbance ("state_restoration"): the later stages' ordinary action (putting the next box on) +undoes earlier ones; the agent has to see which box gave way, take it out of the pile and rebuild with it on top (within +an attempt) or remember its colour (across attempts). The cheapest explanation of a toppled pile ("I did not centre the +box", "I let go too high") is wrong: perfectly centred boxes let go 5 mm above the pile topple it just the same +(control naive_centred). + +v1 -> v2 (Sonnet 5.5 pilot np3_lh_tidy_stack, seeds 3000 / 3002 / 3003, k=3; logs measured by the coordinator and +replayed here): in s3002 attempt 2 boxes that had fallen on their sides were restacked lying (a lying box looks the +same: they are nearly cubes); the soft box lay on its side at level 2 under two boxes and the cup, and the v1 law, which +measured the load along the box axis only, saw -0.06 N and never fired -> judged a success. Sonnet also presses what it +puts down 0.5-1.5 cm below contact (its own logs: the gripper stops 0.6-1.5 cm above the commanded release height), and +in s3003 a cup pressed onto the soft box on top -- where it belongs -- crushed it under one item (v1: 2.45 N). v2: + (1) the load is measured along the world vertical, whichever face the carton rests on (`vertical_loads`: the downward + push on its upper side, limited by the support under it); + (2) a carton lying on a side face (seam vertical) cannot fold under gravity, so it is crushed instead: both halves + flatten towards the face they rest on, the upper half by 70 % and the lower by 30 % (runtime geom sizes + + envs.refit_bounds), the top becomes a 2-3 cm step and what is on it tips off; + (3) only what rests on the carton counts, at most with its own weight (+0.3 N for impacts): something the robot still + holds, the robot pushing down through an item it has just let go of, and the fingers pressing the held carton + itself onto something do not count; the robot's own fingers / hand pushing on its top do (a hard press may crush + it: the closed gripper 3 mm onto its top does; logged as cause "press", not counted as the trap unless it costs a + stage); + (4) items weigh 200 g (box and cup; v1 180 / 160 g) and f_crit = 3.45 N: one item 1.96 N, two 3.92 N; + (5) the rigid boxes' joints are stiffer (20 Nm/rad, stiff limit; at 3 Nm/rad Sonnet's cup press on a 4-high pile bent + every box ~4 deg and the pile leaned 10 deg in the replay); after a fold the carton straightens along a rest + shape that moves back to straight over 1.5 s (released at once, a stiff spring flipped it onto its side); + (6) stacking tolerance 3 cm instead of 2.5 (a correctly stacked oracle_noise pile failed at 2.51 cm). +v1 code and results: scratchpad lh_tidy_stack_v1.py, results/_old/lh_tidy_stack_v1/. + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a grey mat (13 x 13 cm, visual only), centre x in [-0.11, -0.05], |y| <= 5 cm; + * four storage boxes (6 x 6 x 5 cm, bright red / green / blue / yellow with a darker lid line, 200 g; friction 0.5) + 15, 18.5, 22 and 25.5 cm (+-1 cm) from the mat centre, at random angles 30-150 deg from forward on its left and right, + yaw +-17 deg, colours shuffled; + * a dark teal cup (5 cm wide, 7 cm tall, 200 g) on the robot's side of the mat, 23-26 cm away. + +Hidden variable: which box is the soft carton (60 g; mass is not observable). Instances come in balanced blocks of 20 +consecutive seeds ((seed x 7) mod 20 = k): k >= 18 benign (no soft box); otherwise the soft box is the one at rank +k mod 4 of the distance to the mat (0 = nearest = the bottom of a nearest-first pile, 3 = the top): 5 / 5 / 4 / 4. +A nearest-first stacker therefore meets it below the top in 14 of 20 instances. + +Mechanism (physics; nothing is teleported). Every box is built alike: a lower half (the root body) and an upper half +joined by a ball joint at mid-height (the seam is invisible). In the three rigid boxes the joint is locked (range +0.003 rad, stiffness 3 Nm/rad). The soft carton follows a load law (`_law_step`, every MuJoCo substep): its compressive +load (above, low-passed with 0.4 s) is compared with f_crit (instance key "f_crit": the fragility knob). Below it the +joint keeps 3 Nm/rad (one box 1.3 cm off-centre tilts it < 1 deg: looks like the rigid boxes). Above it: + * standing or upside down (seam horizontal): the joint stiffness drops to 0.03 Nm/rad -- a column with m g h ~ 0.27 + Nm/rad on it is unstable, centred or not -- and its rest shape bends 12 deg towards a per-instance side: the upper + half folds sideways (38-54 deg measured, joint limit 54 deg) and what is on it slides off; + * lying on a side face (seam vertical): crushed as above within ~0.1 s. +Unloaded (< 0.5 N) for 0.3 s it recovers over ~1.5 s (still visibly bent / flattened in the images of the next one or +two commands). One item on it is carried (a box let go 4 cm above adds < 0.5 N to the filtered load), two are not. So +the pile survives only with the soft box on top (carrying just the cup): soft at level 1 -> it gives way when box 3 +lands (boxes 2 and 3 fall), level 2 -> when box 4 lands, level 3 -> when the cup lands (box 4 and the cup fall; standing, +the cup ends on its side, which a top-down gripper cannot undo, so that attempt cannot be repaired). Measured (v2, naive +without rebuilding, the 14 trap instances of seeds 1000-1019): standing 14/14 folded at exactly that stage, the soft +box stayed upright in the pile 14/14 (fold 37-55 deg), the cup fell 4/4 at level 3; lying (control naive_lying: the +soft box starts on a side face and is stacked lying) crushed at exactly that stage in every trap instance. + +Why not the linear spring of the brief (a ball joint with one fixed stiffness k): the load that k must carry (the cup) +and the load that must topple it (one more box) differ by a factor of ~2-3, and an inverted pendulum close to its +critical load amplifies placement offsets (tilt = W e / (k - m g h)); measured (results/lh_tidy_stack/linear.json, +instance key law="linear"): no k gives both a soft box that carries the cup on top without sagging and a pile that +topples however carefully it is centred (k <= 0.25 Nm/rad: the correct pile fails 5-10/10; k = 0.5: a centred +level-3 soft box carries box + cup, 2/2). A load threshold (walls that +hold until they buckle) keeps the soft box looking and behaving rigid until the second item, independent of centring. + +Success predicate (from the instruction): all four boxes in one chain -- the bottom one on the mat (lowest point <= 8 mm +above the table, centre within 3.5 cm of the mat centre in x and y: its footprint on the 13 cm mat), each next one +resting on the previous (its lowest point within 1 cm of the top of the box below, centres within 3 cm), every box +flat (some face within 10 deg of horizontal: a fallen box cannot be stood up again by a vertical gripper, so a box on +its side counts), not bent (kink <= 10 deg) and not crushed (<= 15 %) --; the cup upright (<= 10 deg) on the top box +(bottom within 1 cm, centre within 3 cm); nothing held, the gripper not touching anything, the scene static (< 3 mm +in 1 s). Tolerance: 3 cm = the box's half width, i.e. the upper box's centre of mass is over the lower box's top face +(physically resting on it; the static check rejects anything that does not stay). Sonnet's measured placement error is +0.4-1.3 cm, so two placements differ by up to 2.6 cm plus a few mm of landing drift (v2: the 2.5 cm of v1 failed one +correctly stacked oracle_noise pile, seed 1008, at 2.51 cm). + +Event monitor (server log only; F1 gives the agent only success / failure): stage predicates red / green / blue / +yellow (box in the pile) and cup (cup on a complete pile), debounced over 0.5 s: achieved / lost (cause buckle / robot +/ picked_up / other) / restored; `buckle` (= trap fired: load, the robot's share of it, fold or crush, lying, level, +items on it), `collapse` (a buckle that cost a stage). Outcome: success, failure (none / held / touching / collapsed / +regressed / not_stacked / cup_fallen / cup_not_on_top / not_static), trap_fired, recovered_in_attempt, n_buckles, +n_collapses, buckle_how, max_kink_deg, max_crush, detail (F2). The law's state rides along in task.mon["law"]; a +crushed carton's geom sizes are restored at every reset. + +Protocol: cross (reset to the same instance before every attempt), k = 3. +""" +import mujoco +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +TZ = envs.TABLE_Z +G = 9.81 +COLOURS = ["red", "green", "blue", "yellow"] +BOXES = [f"box_{c}_1" for c in COLOURS] +COL = dict(zip(BOXES, COLOURS)) +CUP, MAT = "cup_1", "mat_1" +RGBA = {"red": (0.80, 0.16, 0.13, 1.0), "green": (0.17, 0.58, 0.25, 1.0), "blue": (0.16, 0.34, 0.80, 1.0), + "yellow": (0.90, 0.74, 0.14, 1.0)} +CUP_RGBA = (0.10, 0.45, 0.50, 1.0) # dark teal ceramic, darker inside +CUP_INSIDE = (0.20, 0.20, 0.19, 1.0) +MAT_RGBA = (0.45, 0.45, 0.47, 1.0) + +# ---------------------------------------------------------------- boxes (all four built alike: base + upper part) +HX, HY, H = 0.030, 0.030, 0.050 # 6 x 6 x 5 cm (the gripper opens 7.9 cm) +HB = 0.025 # base part height = height of the seam (ball joint) above the bottom: mid-height, so the upper +# half can fold ~56 deg before its edge reaches the surface below +HU = H - HB +BOX_MASS = 0.20 # a filled storage box (v1: 0.18) +SOFT_MASS = 0.06 # the empty carton (mass is not observable by the agent) +BOX_MU = 0.5 +CONTACT = 'solimp="0.95 0.99 0.001" solref="0.01 1"' +# soft-carton law (see SoftLaw): stiff until the compressive load through its walls exceeds F_CRIT, then soft +K_HI = 3.0 # Nm/rad: the intact soft carton (one box 1.3 cm off-centre tilts it ~0.5 deg; a cup pressed onto it +# bends it ~4 deg) +K_RIGID = 20.0 # Nm/rad + a stiff joint limit: the rigid boxes (at 3 Nm/rad a cup pressed onto a 4-high pile bent every +# box 4 deg and the pile leaned 10 deg -- replay of pilot s3003 on v2; at 20 for the soft carton too +# its folds flipped it onto its side 4/14 times) +K_LO = 0.03 # Nm/rad: buckled (one box on it destabilises it: m g h ~ 0.12 Nm/rad) +DAMP = 0.01 +F_CRIT = 3.45 # N, vertical load from above (resting things + whatever the robot pushes or holds onto it): one +# item weighs 1.96 N and a held item pressed onto the carton adds <= ~0.9 N before it slips in the +# fingers (measured, t10_press); two items weigh 3.92 N (v1: 2.45 N with 1.77 / 1.57 N items) +F_REL = 0.5 # N: unloaded below this ... +REL_T = 0.3 # ... for this long -> it springs back +TAU_F = 0.4 # s: low-pass of the load (impacts of a box let go 1-4 cm above do not count) +K_RISE = 1.5 # s: the folded carton straightens along a reference that moves back to straight in this time +BEND_REF = np.radians(12.0) # reference bend of the buckled carton (the weak side; direction per instance) +RANGE_SOFT, RANGE_RIGID = 0.95, 0.003 # rad: kink limit (54 deg) of the soft carton; the rigid boxes are locked +# v2: a carton lying on a side face (its seam vertical) cannot fold under gravity; it is crushed instead: both halves +# flatten towards the surface below, the upper half much more, so the top becomes a 2-3 cm step and what is on it +# tips off (geom sizes changed at runtime + envs.refit_bounds) +CRUSH_ALPHA = (0.30, 0.70) # fraction of the height lost by the base half / the upper half when fully crushed +CRUSH_TAU = (0.08, 0.7) # s: crushing / recovering +FOLD_MIN_UP = 0.7 # |seam normal . vertical| above this: the fold (upright or upside down); below: the crush + +# ---------------------------------------------------------------- cup +CUP_R, CUP_H, CUP_MASS = 0.025, 0.070, 0.20 # v1: 0.16 + +# ---------------------------------------------------------------- mat and layout +MAT_HALF = 0.065 # 13 x 13 cm +MAT_X, MAT_Y = (-0.11, -0.05), (-0.05, 0.05) +BOX_D = (0.15, 0.185, 0.22, 0.255) # distances of the four boxes from the mat centre (+- jitter) +BOX_X = (-0.33, 0.07) # world x range of the box positions (reach) +BOX_YMAX = 0.30 +BOX_YAW = 0.30 +P_BENIGN = 0.10 # 2 of every 20 consecutive seeds: no soft box + +# ---------------------------------------------------------------- predicates +TILT_OK = np.radians(10.0) +KINK_OK = np.radians(10.0) +ON_MAT = 0.035 # bottom box centre within 3.5 cm of the mat centre (x and y): its footprint is on the 13 cm mat +STACK_XY = 0.030 # centre of a box within 3 cm (= the half width) of the centre of the box below: its centre of +# mass is over the lower box's top face (v2; 2.5 cm judged a resting box 2.51 cm off as not stacked) +STACK_Z = 0.010 +CUP_XY = 0.030 +DEBOUNCE = 10 # control steps (0.5 s) + +# ---------------------------------------------------------------- scripted motion +Z_CARRY = 0.18 +NAIVE_ERR = (0.004, 0.013) # Sonnet's placement error 0.4-1.3 cm (random direction) +NAIVE_GAP = (0.010, 0.040) # Sonnet lets go 1-4 cm above the surface +NAIVE_BIAS = (0.0, 0.020) # forward bias of the first box on the mat (oblique camera) + + +def box_xml(name, rgba): + """storage box: base part (root body, 1.6 cm) + upper part (child body) on a ball joint at the seam. Rigid boxes + get a ~0 kink range at reset; the soft carton a 31.5 deg range and the load-dependent stiffness of SoftLaw. + Inertials are replaced per instance (mass).""" + mb, mu = BOX_MASS * HB / H, BOX_MASS * HU / H + zb = -H / 2 + HB / 2 + dark = [0.72 * c for c in rgba[:3]] + [1.0] + g = [f' ', + f' ', + f' ', + f' ', + f' ', + f' ', + f' ', + f' ', + # lid line (visual only): a darker band 8 mm below the top, on all four boxes + f' ', + ' '] + return _wrap(name, "\n".join(g), H / 2, float(np.hypot(HX, HY))) + + +def cup_xml(name): + """open cup, 5 cm wide, 7 cm tall: 12 wall boxes + an octagonal base of two boxes (box contacts; a light MuJoCo + cylinder creeps on a flat surface, lh_nudge_row). Visual: a smooth cylinder with a dark inside.""" + r, h = CUP_R, CUP_H + nseg, wt, bt = 12, 0.004, 0.006 + g = [f' '] + s = r * np.sin(np.pi / nseg) + 0.0008 + rc = r * np.cos(np.pi / nseg) - wt / 2 + for k in range(nseg): + a = 2 * np.pi * k / nseg + q = [np.cos(a / 2), 0, 0, np.sin(a / 2)] + g.append(f' ') + a0 = r * 0.70 + for k, ang in enumerate((0.0, np.pi / 4)): + q = [np.cos(ang / 2), 0, 0, np.sin(ang / 2)] + g.append(f' ') + g.append(f' ') + g.append(f' ') + return _wrap(name, "\n".join(g), h / 2, r) + + +def mat_xml(name): + g = (f' ') + return _wrap(name, g, 0.0005, MAT_HALF * 1.42) + + +def free_adr(env, name): + """(qpos, dof) address of the object's FREE joint. envs.free_joint_addr takes joints[0], which for an object with a + jointed child body is the child's joint (robosuite lists the subtree's joints before the free joint it appends).""" + m = env.sim.model + for jn in env.objects_dict[name].joints: + j = m.joint_name2id(jn) + if int(m.jnt_type[j]) == 0: + return int(m.jnt_qposadr[j]), int(m.jnt_dofadr[j]) + raise KeyError(name) + + +def place(env, name, xy, yaw=0.0, surface_z=TZ, clearance=0.0005, tilt=None): + """teleport upright (yaw about z; `tilt` rad about the object's own x axis first, e.g. pi/2 = lying on a side + face -- controls only), lowest collision point `clearance` above surface_z (reset only)""" + qa, da = free_adr(env, name) + d = env.sim.data + d.qpos[qa:qa + 3] = [xy[0], xy[1], surface_z + 0.3] + q = np.array([np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)]) + if tilt: + w1, z1 = q[0], q[3] + c, s_ = np.cos(tilt / 2), np.sin(tilt / 2) + q = np.array([w1 * c, w1 * s_, z1 * s_, z1 * c]) # q_yaw * q_x(tilt) + d.qpos[qa + 3:qa + 7] = q + d.qvel[da:da + 6] = 0.0 + env.sim.forward() + d.qpos[qa + 2] -= envs.obj_min_z(env, name) - (surface_z + clearance) + env.sim.forward() + + +def _fb(v): + return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}" + + +def _lr(v): + return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}" + + +def _wrap_q(a, period): + """wrap an angle to [-period/2, period/2)""" + return float((a + period / 2) % period - period / 2) + + +class StackSkills(Skills): + """Skills that feed the task's per-step monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class TidyStack(LFFTask): + name = "lh_tidy_stack" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Restore", "Plan") + protocol = "cross" + max_attempts = 3 + # careful: 5 pick-and-places x ~8 commands (40) + a collapse: unstack 1-2 boxes (~16) and rebuild 3-4 (~32) + # + looking / small corrections (~30), with some margin + agent_max_steps = 150 + instruction = ("Tidy up the table: stack the four storage boxes (red, green, blue, yellow) into a single pile on the " + "grey mat, in any order you like, and then put the cup upright on top of the pile. At the end each " + "box must rest flat on the box below it (the bottom one on the mat), the cup must stand on the top " + "box, and the gripper must be open and clear of everything.") + instruction_indirect = ("Clean up the table: pile the four coloured boxes on top of each other on the dark grey " + "square, in whatever order, and finish by standing the teal mug on top of the pile. In the " + "end every box has to sit flat on the one below it (the lowest on the grey square), the mug " + "has to stand on the top box, and the gripper must be open and away from everything.") + agent_object_names = ["storage boxes (red, green, blue, yellow)", "grey mat", "cup"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs = [] + for i, (c, b) in enumerate(zip(COLOURS, BOXES)): + cat = register_generated(f"LffLtsBox{c.capitalize()}", box_xml(f"lff_lts_box_{c}", RGBA[c])) + objs.append((b, cat, f"box{i}_region", (-0.30 + 0.13 * i, 0.28, -0.29 + 0.13 * i, 0.29))) + cat = register_generated("LffLtsCup", cup_xml("lff_lts_cup")) + objs.append((CUP, cat, "cup_region", (-0.30, -0.29, -0.29, -0.28))) + mat = register_generated("LffLtsMat", mat_xml("lff_lts_mat"), free=False) + fx = [(MAT, mat, "mat_region", (0.0, -0.29, 0.01, -0.28))] + return write_bddl(self.name, "Stack the four boxes on the grey mat and put the cup on top", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.mat_bid = m.body_name2id(self.env.fixtures_dict[MAT].root_body) + self.jid, self.base_bid, self.upper_bid, self.base_gid, self.upper_gid = {}, {}, {}, {}, {} + for b in BOXES: + for g in envs.obj_geom_ids(self.env, b): + n = m.geom_id2name(g) + if n.endswith("_upper"): + self.upper_gid[b] = g + elif n.endswith("_base"): + self.base_gid[b] = g + self.upper_bid[b] = int(m.geom_bodyid[self.upper_gid[b]]) + self.base_bid[b] = int(m.geom_bodyid[self.base_gid[b]]) + j = next(m.joint_name2id(jn) for jn in self.env.objects_dict[b].joints if jn.endswith("_kink")) + self.jid[b] = j + # every geom of each half (collision and visual) with its compiled size / pos: the crush rescales them + self.half_geoms = {} + for b in BOXES: + hg = [] + for bid in (self.base_bid[b], self.upper_bid[b]): + gs = [g for g in range(int(m.body_geomadr[bid]), int(m.body_geomadr[bid] + m.body_geomnum[bid])) + if int(m.geom_type[g]) == 6] + hg.append((bid, gs, m.geom_size[gs].copy(), m.geom_pos[gs].copy())) + self.half_geoms[b] = hg + self.cup_gids = list(envs.obj_geom_ids(self.env, CUP)) + self.obj_bodies = {b: [self.base_bid[b], self.upper_bid[b]] for b in BOXES} + self.obj_bodies[CUP] = [envs.body_id(self.env, CUP)] + # per-geom lookup: owner index 0-3 = boxes, 4 = cup, -1 other; robot part 1 = finger, 2 = hand / arm + self.owner = np.full(m.ngeom, -1, int) + for i, b in enumerate(BOXES): + self.owner[[self.base_gid[b], self.upper_gid[b]]] = i + self.owner[self.cup_gids] = 4 + self.part = np.zeros(m.ngeom, int) + for g in envs.robot_geom_ids(self.env): + n = m.geom_id2name(g) or "" + self.part[g] = 1 if "finger" in n else 2 + self.inst = None + self.law = None + self.mon = None + self.sk = None + self._sub_rob = {} + self._held = set() # owner indices (0-3 boxes, 4 cup) held by the gripper, refreshed every control step + self._rest_cap = np.inf # upper bound of the resting load on the soft carton, refreshed every control step + sim = self.env.sim + if not getattr(sim, "_lts_wrapped", False): + orig = sim.step + + def step(*a, **k): + t = getattr(sim, "_lts_task", None) + if t is not None and t.law is not None: + t._law_step() + orig(*a, **k) + if t is not None and t.mon is not None: + t._substep() + sim.step = step + sim._lts_wrapped = True + sim._lts_task = self + + # ------------------------------------------------------------ instances + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + mx, my = float(rng.uniform(*MAT_X)), float(rng.uniform(*MAT_Y)) + ca = np.pi + float(rng.uniform(-0.5, 0.5)) # the cup stands on the robot's side of the mat, 23-26 cm away + cd = float(rng.uniform(0.23, 0.26)) + cup = [mx + cd * np.cos(ca), my + cd * np.sin(ca)] + for _ in range(500): + ds = np.array(BOX_D) + rng.uniform(-0.01, 0.01, 4) + ang = rng.uniform(np.radians(30), np.radians(150), 4) * rng.choice([-1.0, 1.0], 4) + pos = np.stack([mx + ds * np.cos(ang), my + ds * np.sin(ang)], 1) + if not (np.all((pos[:, 0] >= BOX_X[0]) & (pos[:, 0] <= BOX_X[1])) and np.all(np.abs(pos[:, 1]) <= BOX_YMAX)): + continue + dd = np.linalg.norm(pos[:, None] - pos[None], axis=2) + np.eye(4) + if dd.min() < 0.12 or np.linalg.norm(pos - np.asarray(cup), axis=1).min() < 0.14: + continue + break + else: + raise RuntimeError("layout") + perm = rng.permutation(4) + start = {BOXES[i]: [float(v) for v in pos[perm[i]]] for i in range(4)} + yaw = {b: float(rng.uniform(-BOX_YAW, BOX_YAW)) for b in BOXES} + mat = np.array([mx, my]) + near = sorted(BOXES, key=lambda b: float(np.linalg.norm(np.asarray(start[b]) - mat))) + # balanced blocks of 20 consecutive seeds: 2 benign (no soft box); else the soft carton is the box at rank + # r = 0..3 (0 = nearest the mat, i.e. the bottom of a nearest-first pile; 3 = the top): 5 / 5 / 4 / 4 + k = (int(seed) * 7) % 20 + benign = k >= round(20 * (1 - P_BENIGN)) + rank = None if benign else k % 4 + soft = None if benign else near[rank] + return dict(seed=int(seed), mat=[mx, my], cup=cup, start=start, yaw=yaw, cup_yaw=float(rng.uniform(-np.pi, np.pi)), + soft=soft, soft_colour=COL[soft] if soft else None, benign=bool(benign), + soft_rank_nearest=rank, nearest_order=[COL[b] for b in near], + buckle_dir=float(np.pi / 2 if rng.random() < 0.5 else -np.pi / 2), + f_crit=F_CRIT, naive_gap=float(rng.uniform(*NAIVE_GAP)), naive_bias=float(rng.uniform(*NAIVE_BIAS))) + + def apply_instance(self, inst): + self.inst = inst + m, d = self.env.sim.model, self.env.sim.data + m.body_pos[self.mat_bid] = [inst["mat"][0], inst["mat"][1], TZ + 0.0005] + for b in BOXES: + j = self.jid[b] + soft = b == inst["soft"] + M = SOFT_MASS if soft else BOX_MASS + for bid, frac, h in ((self.base_bid[b], HB / H, HB), (self.upper_bid[b], HU / H, HU)): + mm = M * frac + m.body_mass[bid] = mm + m.body_inertia[bid] = [mm * (4 * HY * HY + h * h) / 12, mm * (4 * HX * HX + h * h) / 12, + mm * (4 * HX * HX + 4 * HY * HY) / 12] + m.jnt_range[j] = [0.0, RANGE_SOFT if soft else RANGE_RIGID] + m.jnt_solref[j] = [0.02, 1.0] if soft else [0.004, 1.0] # rigid boxes: a stiff limit + m.jnt_stiffness[j] = K_HI if soft else K_RIGID + qa, da = int(m.jnt_qposadr[j]), int(m.jnt_dofadr[j]) + m.qpos_spring[qa:qa + 4] = [1.0, 0.0, 0.0, 0.0] + d.qpos[qa:qa + 4] = [1.0, 0.0, 0.0, 0.0] + d.qvel[da:da + 3] = 0.0 + self._set_crush(b, 0.0, 2, -1.0) # undo a crush left over from the previous attempt + place(self.env, b, inst["start"][b], yaw=inst["yaw"][b], tilt=inst.get("lying", {}).get(COL[b])) + place(self.env, CUP, inst["cup"], yaw=inst["cup_yaw"]) + self.law = None + if inst["soft"]: + self.law = dict(box=inst["soft"], f=0.0, fmax=0.0, buckled=False, n=0, rel_t=0.0, t=0.0, buckles=[], + f_crit=float(inst.get("f_crit", F_CRIT)), dir=float(inst["buckle_dir"]), + mode=str(inst.get("law", "threshold")), how=None, crush=0.0, crush_set=0.0, + crush_axis=2, crush_sign=-1.0, f_rest=0.0, f_robot=0.0) + if self.law["mode"] == "linear": # control only: the brief's fixed-stiffness spring (no load threshold) + m.jnt_stiffness[self.jid[inst["soft"]]] = float(inst["k_lin"]) + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.law = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = StackSkills(self.env, self, recorder=recorder) + self._sub_rob = {} + self._held = set() + self._rest_cap = np.inf + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ soft-carton law + def _part_axial(self, gid, axis): + """sum of contact forces on geom gid (from any other geom), projected on `axis` (world)""" + m, d = self.env.sim.model, self.env.sim.data + n = d.ncon + if not n: + return 0.0 + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + idx = np.nonzero((g1 == gid) | (g2 == gid))[0] + tot = 0.0 + f6 = np.zeros(6) + for i in idx: + mujoco.mj_contactForce(m._model, d._data, int(i), f6) + fw = d.contact[int(i)].frame.reshape(3, 3).T @ f6[:3] # force on geom2, world frame + tot += float(fw @ axis) * (-1.0 if g1[i] == gid else 1.0) + return tot + + def vertical_loads(self, b): + """vertical contact forces on box b (N), whichever face it rests on: (resting, robot, held, support). + resting = downward push on its upper side (contact point above its centre) from things resting on it; + robot = the same from the robot's own fingers / hand pushing on it (not counted while the robot holds b + itself); held = the same from something the robot holds (pressing it down onto b); support = upward push on + its lower side. Its two halves never touch (parent and child), so only real contacts count.""" + m, d = self.env.sim.model, self.env.sim.data + n = d.ncon + if not n: + return 0.0, 0.0, 0.0, 0.0 + gb, gu = self.base_gid[b], self.upper_gid[b] + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + idx = np.nonzero((g1 == gb) | (g1 == gu) | (g2 == gb) | (g2 == gu))[0] + if not len(idx): + return 0.0, 0.0, 0.0, 0.0 + cz = float(d.xpos[self.base_bid[b]][2]) # the root body sits at the box's centre + held = self._held + b_held = BOXES.index(b) in held + rest = robot = via = sup = 0.0 + f6 = np.zeros(6) + for i in idx: + c = d.contact[int(i)] + mujoco.mj_contactForce(m._model, d._data, int(i), f6) + fz = float(c.frame.reshape(3, 3)[:, 2] @ f6[:3]) # world z of the force on geom2 + mine1 = g1[i] in (gb, gu) + fz = -fz if mine1 else fz # force on box b + other = int(g2[i] if mine1 else g1[i]) + pz = float(c.pos[2]) + if pz > cz + 0.004 and fz < 0.0: + o = self.owner[other] + if self.part[other] > 0: + if not b_held: + robot -= fz + elif o >= 0 and o in held: + via -= fz + else: + rest -= fz + elif pz < cz - 0.004 and fz > 0.0: + sup += fz + # what rests on it pushes at most with its own weight: the robot pressing down through an item it has let go + # of (Sonnet releases with the cup pushed up against the hand, pilot s3003) is not a resting load + rest = min(rest, self._rest_cap) + return rest, robot, via, sup + + def compression(self, b): + """compressive force (N) on the carton, (total, resting): the downward push on its upper side from things + resting on it plus the robot's fingers / hand pushing directly on it, limited by the support under it -- + along the world vertical, whichever face it rests on (v1 measured it along the box axis only: a carton lying + on its side never buckled). Something the robot still holds does not count: Sonnet presses what it puts down + 0.5-1.5 cm below contact (pilot), which must not crush a carton that will carry the item once let go.""" + rest, robot, via, sup = self.vertical_loads(b) + return float(min(rest + robot, sup)), float(min(rest, sup)) + + def _law_step(self): + """per MuJoCo substep: low-pass the compressive load; above f_crit the carton gives way -- standing or upside + down it folds (its kink joint loses its stiffness, its rest shape bends towards its weak side and the load + topples it), lying on a side face it is crushed (both halves flatten, the upper half more); unloaded for + REL_T it slowly recovers its shape""" + law = self.law + b = law["box"] + m = self.env.sim.model + dt = float(m.opt.timestep) + tot, rest = self.compression(b) + law["f"] += (tot - law["f"]) * dt / TAU_F + law["f_rest"] += (rest - law["f_rest"]) * dt / TAU_F + law["fmax"] = max(law["fmax"], law["f"]) + j = self.jid[b] + qa = int(m.jnt_qposadr[j]) + if law["mode"] == "linear": # control: constant stiffness; a "buckle" = the kink passes 15 deg (re-arms < 5) + kk = self.kink(b) + if not law["buckled"] and kk > np.radians(15.0): + law["buckled"] = True + law["n"] += 1 + law["buckles"].append(dict(t=round(law["t"], 3), load_N=round(law["f"], 2))) + self._on_buckle() + elif law["buckled"] and kk < np.radians(5.0): + law["buckled"] = False + law["t"] += dt + return + if not law["buckled"]: + if law["f"] > law["f_crit"]: + law["buckled"] = True + law["n"] += 1 + law["rel_t"] = 0.0 + R = self.env.sim.data.xmat[self.base_bid[b]].reshape(3, 3) + law["unbend_q0"] = None + if abs(R[2, 2]) >= FOLD_MIN_UP: # seam horizontal: fold + law["how"] = "fold" + u = R.T @ np.array([np.cos(law["dir"]), np.sin(law["dir"]), 0.0]) + ax = np.array([-u[1], u[0], 0.0]) + ax /= max(np.linalg.norm(ax), 1e-9) + m.qpos_spring[qa:qa + 4] = [np.cos(BEND_REF / 2), *(np.sin(BEND_REF / 2) * ax)] + else: # seam vertical (lying on a side face): crush towards the face it rests on + law["how"] = "crush" + k = int(np.argmax(np.abs(R[2, :2]))) + law["crush_axis"] = k + law["crush_sign"] = -float(np.sign(R[2, k]) or 1.0) # local direction of "down" along axis k + # cause: "load" = what rests on it is enough by itself (>= 60 % of f_crit, i.e. more than one item); + # "press" = the robot's own push made the difference (a hard press with the gripper) + cause = "load" if law["f_rest"] >= 0.6 * law["f_crit"] else "press" + law["buckles"].append(dict(t=round(law["t"], 3), load_N=round(law["f"], 2), how=law["how"], + resting_N=round(law["f_rest"], 2), cause=cause)) + self._on_buckle() + elif law["f"] < F_REL: + law["rel_t"] += dt + if law["rel_t"] > REL_T: + law["buckled"] = False + # straighten smoothly: the rest shape starts at the current bend and moves back to straight over + # K_RISE (a stiff spring released at once from a 40-50 deg bend flips the light carton over) + q0 = np.array(self.env.sim.data.qpos[qa:qa + 4], float) + q0 = q0 / max(np.linalg.norm(q0), 1e-9) * (1.0 if q0[0] >= 0 else -1.0) + law["unbend_q0"], law["unbend_s"] = q0.tolist(), 0.0 + m.qpos_spring[qa:qa + 4] = q0 + else: + law["rel_t"] = 0.0 + k = float(m.jnt_stiffness[j]) + if law["buckled"] and law["how"] == "fold": + m.jnt_stiffness[j] = k + (K_LO - k) * min(1.0, dt / 0.02) + else: + m.jnt_stiffness[j] = K_HI + if law.get("unbend_q0") is not None: + law["unbend_s"] = min(1.0, law["unbend_s"] + dt / K_RISE) + q = (1.0 - law["unbend_s"]) * np.asarray(law["unbend_q0"]) + law["unbend_s"] * np.array([1.0, 0, 0, 0]) + m.qpos_spring[qa:qa + 4] = q / np.linalg.norm(q) + if law["unbend_s"] >= 1.0: + law["unbend_q0"] = None + target = 1.0 if (law["buckled"] and law["how"] == "crush") else 0.0 + if target or law["crush"] > 0.0: + tau = CRUSH_TAU[0] if target else CRUSH_TAU[1] + law["crush"] += (target - law["crush"]) * min(1.0, dt / tau) + if not target and law["crush"] < 0.002: + law["crush"] = 0.0 + if abs(law["crush"] - law["crush_set"]) > 0.004 or (law["crush"] == 0.0 and law["crush_set"] > 0.0): + self._set_crush(b, law["crush"], law["crush_axis"], law["crush_sign"]) + law["crush_set"] = law["crush"] + law["t"] += dt + + def _set_crush(self, b, c, axis, sign): + """flatten box b's two halves along their local `axis` by c (0..1) x CRUSH_ALPHA, keeping the faces on the + `sign` side (the side facing down) in place; then refresh the collision bounds""" + m = self.env.sim.model + for (bid, gs, size0, pos0), alpha in zip(self.half_geoms[b], CRUSH_ALPHA): + size, pos = size0.copy(), pos0.copy() + if c > 0.0: + s0 = size0[:, axis] + s1 = s0 * (1.0 - alpha * c) + size[:, axis] = s1 + pos[:, axis] = pos0[:, axis] + sign * (s0 - s1) + m.geom_size[gs] = size + m.geom_pos[gs] = pos + envs.refit_bounds(m, [self.half_geoms[b][0][0], self.half_geoms[b][1][0]]) + + def _on_buckle(self): + mon = self.mon + if mon is None: + return + b = self.law["box"] + ch = self.pile() + on = self.items_on(b) + last = self.law["buckles"][-1] if self.law["buckles"] else {} + e = dict(event="buckle", box=COL[b], step=int(self.sk.n_steps) if self.sk else 0, + load_N=round(self.law["f"], 2), level=(ch.index(b) + 1) if b in ch else None, + items_on=[COL.get(x, "cup") for x in on], how=last.get("how"), cause=last.get("cause"), + resting_N=last.get("resting_N"), + lying=bool(abs(self.R(self.base_bid[b])[2, 2]) < FOLD_MIN_UP)) + mon["events"].append(e) + mon["buckle_steps"].append(e["step"]) + mon["pending_collapse"] = dict(step=e["step"], pile=list(ch), cup=self.cup_on_pile(ch)) + + # ------------------------------------------------------------ geometry / predicates + def R(self, bid): + return self.env.sim.data.xmat[bid].reshape(3, 3) + + def centre(self, name): + return envs.obj_pos(self.env, name) + + def flat_tilt(self, b): + """angle (rad) between world vertical and the base part's axis closest to it (a box may lie on any face)""" + R = self.R(self.base_bid[b]) + return float(np.arccos(np.clip(np.max(np.abs(R[2, :])), -1.0, 1.0))) + + def kink(self, b): + """bend of the upper part against the base part (rad)""" + zb = self.R(self.base_bid[b])[:, 2] + zu = self.R(self.upper_bid[b])[:, 2] + return float(np.arccos(np.clip(zb @ zu, -1.0, 1.0))) + + def cup_tilt(self): + return float(np.arccos(np.clip(envs.obj_upright_cos(self.env, CUP), -1.0, 1.0))) + + def held(self, name): + return self.sk is not None and self.sk.holding(name) + + def crushed(self, b): + """how far box b is crushed (0..1; only the soft carton, lying on a side face, can be)""" + law = self.law + return float(law["crush"]) if (law is not None and law["box"] == b) else 0.0 + + def flat(self, b): + return (self.flat_tilt(b) <= TILT_OK and self.kink(b) <= KINK_OK and self.crushed(b) <= 0.15 + and not self.held(b)) + + def rests_on(self, upper, lower): + cu, cl = self.centre(upper), self.centre(lower) + return (np.linalg.norm(cu[:2] - cl[:2]) <= STACK_XY + and abs(envs.obj_min_z(self.env, upper) - envs.obj_max_z(self.env, lower)) <= STACK_Z) + + def on_mat(self, b): + off = self.centre(b)[:2] - np.asarray(self.inst["mat"]) + return bool(np.all(np.abs(off) <= ON_MAT) and envs.obj_min_z(self.env, b) <= TZ + 0.008) + + def pile(self): + """the longest chain of flat boxes: the bottom one on the mat, each next resting on the previous (centres within + 2 cm, faces within 1 cm)""" + flat = [b for b in BOXES if self.flat(b)] + best = [] + for b0 in [b for b in flat if self.on_mat(b)]: + ch = [b0] + while True: + nxt = [b for b in flat if b not in ch and self.rests_on(b, ch[-1])] + if not nxt: + break + ch.append(min(nxt, key=lambda b: float(np.linalg.norm(self.centre(b)[:2] - self.centre(ch[-1])[:2])))) + if len(ch) > len(best): + best = ch + return best + + def cup_on(self, b): + c = self.centre(CUP) + return bool(self.cup_tilt() <= TILT_OK and not self.held(CUP) + and np.linalg.norm(c[:2] - self.centre(b)[:2]) <= CUP_XY + and abs(envs.obj_min_z(self.env, CUP) - envs.obj_max_z(self.env, b)) <= STACK_Z) + + def cup_on_pile(self, ch=None): + ch = self.pile() if ch is None else ch + return bool(len(ch) == len(BOXES) and self.cup_on(ch[-1])) + + def items_on(self, b): + """boxes / cup resting (directly or higher up) on box b, by height and overlap""" + cb = self.centre(b) + top = envs.obj_max_z(self.env, b) + out = [] + for x in BOXES + [CUP]: + if x == b: + continue + c = self.centre(x) + if envs.obj_min_z(self.env, x) > top - 0.015 and np.linalg.norm(c[:2] - cb[:2]) < 0.06: + out.append(x) + return out + + def stage_values(self): + ch = self.pile() + v = {COL[b]: b in ch for b in BOXES} + v["cup"] = self.cup_on_pile(ch) + return v, ch + + # ------------------------------------------------------------ monitor + def _init_monitor(self): + keys = COLOURS + ["cup"] + self.mon = dict(state={k: False for k in keys}, cand={k: 0 for k in keys}, ever={k: False for k in keys}, + lost={k: False for k in keys}, lost_cause={k: None for k in keys}, events=[], n=0, + last_robot={k: -10 ** 6 for k in keys}, buckle_steps=[], pending_collapse=None, + max_kink={COL[b]: 0.0 for b in BOXES}, max_crush={COL[b]: 0.0 for b in BOXES}, + max_height=0, n_collapses=0, + law=self.law) # the carton's law state rides along in the robot server's regression snapshots + + def _substep(self): + d = self.env.sim.data + n = d.ncon + if not n: + return + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + o1, o2 = self.owner[g1], self.owner[g2] + p1, p2 = self.part[g1], self.part[g2] + sel = ((o1 >= 0) & (p2 > 0)) | ((o2 >= 0) & (p1 > 0)) + for i in np.nonzero(sel)[0]: + o = o1[i] if o1[i] >= 0 else o2[i] + self._sub_rob[int(o)] = True + + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + mon["n"] += 1 + t = int(self.sk.n_steps) + self._held = {i for i, x in enumerate(BOXES + [CUP]) if self.held(x)} + if self.law is not None: # weight of the things (not held) on the soft carton, + 0.3 N for impacts + m = self.env.sim.model + self._rest_cap = 0.3 + G * sum(float(np.sum(m.body_mass[self.obj_bodies[x]])) + for x in self.items_on(self.law["box"]) + if (BOXES + [CUP]).index(x) not in self._held) + keys = COLOURS + ["cup"] + for i in list(self._sub_rob): + mon["last_robot"][keys[i]] = t + self._sub_rob = {} + for b in BOXES: + mon["max_kink"][COL[b]] = max(mon["max_kink"][COL[b]], round(float(np.degrees(self.kink(b))), 1)) + mon["max_crush"][COL[b]] = max(mon["max_crush"][COL[b]], round(self.crushed(b), 2)) + if mon["n"] % 2: + return + vals, ch = self.stage_values() + mon["max_height"] = max(mon["max_height"], len(ch)) + for k in keys: + raw = vals[k] + if raw == mon["state"][k]: + mon["cand"][k] = 0 + continue + mon["cand"][k] += 2 + if mon["cand"][k] < DEBOUNCE: + continue + mon["cand"][k] = 0 + mon["state"][k] = raw + t0 = t - DEBOUNCE + 1 + if raw: + restored = mon["lost"][k] + e = dict(stage=k, event="restored" if restored else "achieved", step=t0) + if restored: + e["after"] = mon["lost_cause"][k] + mon["lost"][k] = False + mon["ever"][k] = True + mon["events"].append(e) + elif mon["ever"][k]: + cause = self._cause(k, t) + mon["lost"][k] = True + mon["lost_cause"][k] = cause + mon["events"].append(dict(stage=k, event="lost", step=t0, cause=cause)) + pc = mon["pending_collapse"] + if cause == "buckle" and pc is not None and not pc.get("counted"): + pc["counted"] = True + mon["n_collapses"] += 1 + mon["events"].append(dict(event="collapse", step=t0, buckled=self.inst["soft_colour"], + pile_before=[COL[b] for b in pc["pile"]])) + + def _cause(self, k, t): + name = CUP if k == "cup" else BOXES[COLOURS.index(k)] + if self.held(name): + return "picked_up" + bs = self.mon["buckle_steps"] + if bs and t - bs[-1] <= 80: # within 4 s of a buckle + return "buckle" + if t - self.mon["last_robot"][k] <= 30: + return "robot" + return "other" + + def _finalize_monitor(self, vals): + mon = self.mon + t = int(self.sk.n_steps) + for k, raw in vals.items(): + if raw == mon["state"][k]: + continue + mon["state"][k] = raw + if raw: + restored = mon["lost"][k] + e = dict(stage=k, event="restored" if restored else "achieved", step=t, final=True) + if restored: + e["after"] = mon["lost_cause"][k] + mon["lost"][k] = False + mon["ever"][k] = True + mon["events"].append(e) + elif mon["ever"][k]: + cause = self._cause(k, t) + mon["lost"][k] = True + mon["lost_cause"][k] = cause + mon["events"].append(dict(stage=k, event="lost", step=t, cause=cause, final=True)) + + # ------------------------------------------------------------ outcome + def _touching(self): + d = self.env.sim.data + n = d.ncon + if not n: + return False + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + return bool(np.any(((self.owner[g1] >= 0) & (self.part[g2] > 0)) | ((self.owner[g2] >= 0) & (self.part[g1] > 0)))) + + def _static_pos(self): + return {x: self.centre(x).copy() for x in BOXES + [CUP]} + + def outcome(self, inst): + sk = self.sk + sk.hold(10) + p0 = self._static_pos() + touching = False + for _ in range(20): + sk.hold(1) + touching = touching or self._touching() + moved = max(float(np.linalg.norm(self.centre(x) - p0[x])) for x in p0) + static = moved < 0.003 + vals, ch = self.stage_values() + self._finalize_monitor(vals) + mon = self.mon + ev = list(mon["events"]) + held = [COL.get(x, "cup") for x in BOXES + [CUP] if self.held(x)] + success = bool(all(vals.values()) and static and not held and not touching) + buckles = [e for e in ev if e.get("event") == "buckle"] + n_reg = sum(e.get("event") == "lost" and e.get("cause") != "picked_up" for e in ev) + n_res = sum(e.get("event") == "restored" and e.get("after") != "picked_up" for e in ev) + soft = inst["soft"] + buckled_now = bool(self.law is not None and self.law["buckled"]) + cup_fallen = self.cup_tilt() > np.radians(45) + if success: + failure = "none" + elif held: + failure = "held" + elif touching and all(vals.values()): + failure = "touching" + elif not all(vals[c] for c in COLOURS): + if buckles and any(mon["ever"][c] for c in COLOURS): + failure = "collapsed" + elif any(mon["lost"][c] for c in COLOURS): + failure = "regressed" + else: + failure = "not_stacked" + elif not vals["cup"]: + failure = "cup_fallen" if cup_fallen else "cup_not_on_top" + else: + failure = "not_static" + # F2 detail (robot-centric words) + parts = [] + if success: + parts.append("All four boxes are stacked on the mat and the cup stands on top.") + else: + if ch: + parts.append("The pile on the mat is " + " / ".join(COL[b] for b in ch) + " (bottom to top).") + else: + parts.append("There is no box resting flat on the mat.") + mat = np.asarray(inst["mat"]) + for b in BOXES: + if b in ch: + continue + c = COL[b] + if self.held(b): + parts.append(f"The {c} box is still held by the gripper.") + continue + off = self.centre(b)[:2] - mat + pose = ("lies tilted" if self.flat_tilt(b) > TILT_OK else + "is crushed flat" if self.crushed(b) > 0.15 else + f"is bent ({np.degrees(self.kink(b)):.0f} degrees)" if self.kink(b) > KINK_OK else "stands") + parts.append(f"The {c} box {pose} {_fb(off[0])} and {_lr(off[1])} of the mat's centre, not in the pile.") + if not vals["cup"]: + if self.held(CUP): + parts.append("The cup is still held by the gripper.") + elif cup_fallen: + parts.append("The cup has fallen over.") + else: + parts.append("The cup is not standing on top of a complete pile.") + if all(vals.values()): + if touching: + parts.append("The gripper is still touching the pile.") + elif not static: + parts.append("Something was still moving.") + loads = [e for e in buckles if e.get("cause") != "press"] + presses = [e for e in buckles if e.get("cause") == "press"] + if loads: + how = ("bent sideways or was crushed" if len({e.get("how") for e in loads}) > 1 else + "was crushed flat" if loads[0].get("how") == "crush" else "bent sideways") + parts.append(f"During the attempt the {loads[0]['box']} box {how} under the weight on it " + f"{len(loads)} time(s) and everything above it slid off.") + if presses: + parts.append(f"The {presses[0]['box']} box gave way {len(presses)} time(s) when the gripper pushed down " + f"on it.") + # trap fired = the carton gave way under what was put on it (or a giving-way cost a stage); a hard press by the + # gripper alone on an otherwise lightly loaded carton is logged (n_press_buckles) but is not the trap + trap = bool(loads) or int(mon["n_collapses"]) > 0 + return dict(success=success, failure=failure, stages=vals, pile=[COL[b] for b in ch], events=ev, + n_regressions=int(n_reg), n_restored=int(n_res), trap_fired=trap, + recovered_in_attempt=bool(trap and success), n_buckles=len(buckles), + n_collapses=int(mon["n_collapses"]), buckle_levels=[e.get("level") for e in buckles], + buckle_loads_N=[e.get("load_N") for e in buckles], max_kink_deg=dict(mon["max_kink"]), + max_crush=dict(mon["max_crush"]), buckle_how=[e.get("how") for e in buckles], + buckle_causes=[e.get("cause") for e in buckles], n_press_buckles=len(presses), + max_height=int(mon["max_height"]), soft=inst["soft_colour"], benign=bool(inst["benign"]), + buckled_at_end=buckled_now, cup_fallen=bool(cup_fallen), held=held, touching=bool(touching), + static=bool(static), detail=" ".join(parts)) + + # ------------------------------------------------------------ scripted primitives (move_to + gripper only) + def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300): + return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + + def _lift_to(self, z, speed=0.2): + cur = self.sk.eef_pos() + if cur[2] < z - 0.005: + self._go([cur[0], cur[1], z], speed=speed) + + def _settle(self, steps=40): + """hold until boxes / cup have stopped (max `steps` control steps)""" + p = self._static_pos() + for _ in range(steps // 4): + self.sk.hold(4) + q = self._static_pos() + if max(float(np.linalg.norm(q[x] - p[x])) for x in p) < 0.0005: + return + p = q + + def settle_scene(self, max_steps=120): + """after a collapse: wait (looking) until nothing moves and no box is visibly bent any more""" + for _ in range(max_steps // 10): + self._settle(10) + if all(self.kink(b) < np.radians(3.0) for b in BOXES): + p = self._static_pos() + self.sk.hold(4) + q = self._static_pos() + if max(float(np.linalg.norm(q[x] - p[x])) for x in p) < 0.0005: + return + + def grasp_yaw(self, name): + """wrist yaw that closes the fingers across a horizontal box axis: of the two, the one whose open fingers stay + clearest of the other objects (a box that fell against another one), then the one needing the least turn""" + if name == CUP: + return 0.0 + R = self.R(self.base_bid[name]) + up = int(np.argmax(np.abs(R[2, :]))) + c = self.centre(name)[:2] + others = [self.centre(x)[:2] for x in BOXES + [CUP] if x != name] + best = None + for a in range(3): + if a == up: + continue + v = R[:2, a] / max(np.linalg.norm(R[:2, a]), 1e-9) + yaw = _wrap_q(float(np.arctan2(v[1], v[0])) - np.pi / 2, np.pi) # fingers close along (-sin yaw, cos yaw) + fingers = [c + s_ * 0.045 * v for s_ in (1.0, -1.0)] # open fingers ~4.5 cm from the centre + clear = min([float(np.linalg.norm(f - o)) for f in fingers for o in others] + [1.0]) + key = (round(min(clear, 0.05), 3), -abs(yaw)) + if best is None or key > best[0]: + best = (key, yaw) + return best[1] + + def z_clear(self, extra=0.08): + """carry height: above everything on the table""" + top = max(envs.obj_max_z(self.env, x) for x in BOXES + [CUP]) + return max(TZ + Z_CARRY, top + extra) + + def pick(self, name, depth=0.018, z_carry=None, tries=2): + sk = self.sk + for _ in range(tries): + self._settle(20) + p = self.centre(name) + zt = envs.obj_max_z(self.env, name) + yaw = self.grasp_yaw(name) + sk.set_gripper(False, steps=10) + zc = z_carry or self.z_clear() + self._lift_to(zc) + self._go([p[0], p[1], zc], yaw=yaw, speed=0.25) + self._go([p[0], p[1], zt - depth + 0.02], speed=0.12) + self._go([p[0], p[1], max(zt - depth, TZ + 0.012)], speed=0.04, tol=0.003, max_steps=150) + sk.set_gripper(True, steps=15) + self._go([p[0], p[1], self.z_clear(0.10)], speed=0.15) + if self.held(name): + return True + sk.set_gripper(False, steps=10) + return False + + def put(self, name, xy, z_surface, gap, yaw=0.0): + """carry the held object over xy (its centre), straight down until its bottom is `gap` above z_surface, let + go, lift 8 cm""" + sk = self.sk + zc = max(self.z_clear(0.10), sk.eef_pos()[2]) + rel = self.centre(name)[:2] - sk.eef_pos()[:2] + q = np.asarray(xy, float) - rel + self._go([q[0], q[1], zc], yaw=yaw, speed=0.25) + sk.hold(5) + rel = self.centre(name)[:2] - sk.eef_pos()[:2] # the object can shift in the fingers while the wrist turns + q = np.asarray(xy, float) - rel + dz = sk.eef_pos()[2] - envs.obj_min_z(self.env, name) + zr = z_surface + dz + gap + self._go([q[0], q[1], zr + 0.03], speed=0.12) + self._go([q[0], q[1], zr], speed=0.04, tol=0.003, max_steps=150) + sk.set_gripper(False, steps=15) + cur = sk.eef_pos() + self._go([cur[0], cur[1], cur[2] + 0.08], speed=0.15) + self._settle(40) + + def free_spot(self, near_xy): + """a free place on the table (for a box taken off the pile): >= 11 cm from everything, off the mat, reachable""" + mat = np.asarray(self.inst["mat"]) + others = [self.centre(x)[:2] for x in BOXES + [CUP]] + best, bd = None, -1.0 + for r in (0.17, 0.21, 0.25, 0.29): + for a in np.radians(np.arange(0, 360, 15)): + p = mat + r * np.array([np.cos(a), np.sin(a)]) + if not (BOX_X[0] - 0.02 <= p[0] <= BOX_X[1] and abs(p[1]) <= BOX_YMAX + 0.02): + continue + d = min(float(np.linalg.norm(p - o)) for o in others) + if d >= 0.11: + return p + if d > bd: + best, bd = p, d + return best + + def place_on_pile(self, name, err, gap, rng, bias=0.0): + """put object `name` on the current pile top (or the mat) with a placement error of `err` (m, random direction)""" + ch = [b for b in self.pile() if b != name] + if ch: + # aims every box at the same spot (the bottom box), as an agent that computes the pile's x, y once: errors + # do not add up level by level + tgt = self.centre(ch[0])[:2].copy() + zs = envs.obj_max_z(self.env, ch[-1]) + else: + tgt = np.asarray(self.inst["mat"], float) + np.array([bias, 0.0]) + zs = TZ + if err: + a = rng.uniform(0, 2 * np.pi) + tgt = tgt + float(err) * np.array([np.cos(a), np.sin(a)]) + if not self.pick(name): + return False + self.put(name, tgt, zs, gap) + return True + + def lay_aside(self, name, rng): + if not self.pick(name): + return False + p = self.free_spot(self.centre(name)[:2]) + self.put(name, p, TZ, 0.01) + return True + + # ------------------------------------------------------------ scripted policies + def nearest_order(self): + mat = np.asarray(self.inst["mat"]) + return sorted(BOXES, key=lambda b: float(np.linalg.norm(self.centre(b)[:2] - mat))) + + def plan(self, params, rng): + if params.get("order") == "random": + order = [BOXES[i] for i in rng.permutation(4)] + else: + order = self.nearest_order() + soft = params.get("soft_known") + if soft: + order = [b for b in order if COL[b] != soft] + [b for b in order if COL[b] == soft] + return order + + def seen_soft(self): + """the box that visibly bent during this attempt (scripted perception of the kink in the images)""" + mk, mc = self.mon["max_kink"], self.mon["max_crush"] + for c in COLOURS: + if mk[c] > 15.0 or mc[c] > 0.3: + return c + return None + + def build(self, order, params, rng, first=True): + """stack `order` (boxes not yet in the pile) then the cup; returns 'ok', 'collapse' or 'fail'""" + err = params.get("err") + gap = params.get("gap", 0.005) + # a box that could not be picked up is tried again after the others (one more pass) + order = list(order) * 2 + for b in order: + if b in self.pile(): + continue + if params.get("soft_known") and COL[b] == params["soft_known"] and \ + sum(x in self.pile() for x in BOXES if COL[x] != params["soft_known"]) < len(BOXES) - 1: + continue # the soft box only goes on once the three others are in the pile + for _ in range(2): + n_b = len(self.mon["buckle_steps"]) + before = self.pile() + e = rng.uniform(*err) if err else 0.0 + if not self.place_on_pile(b, e, gap, rng, bias=params.get("bias", 0.0) if not before else 0.0): + break + after = self.pile() + if len(self.mon["buckle_steps"]) > n_b or any(x not in after for x in before): + return "collapse" + if b in after: + break + if len(self.pile()) < len(BOXES): + return "fail" + if self.cup_tilt() > np.radians(45): + return "fail" + for _ in range(2): + n_b = len(self.mon["buckle_steps"]) + before = self.pile() + e = rng.uniform(*err) if err else 0.0 + if not self.place_on_pile(CUP, e, gap, rng): + return "fail" + if len(self.mon["buckle_steps"]) > n_b or any(x not in self.pile() for x in before): + return "collapse" + if self.cup_on_pile(): + return "ok" + return "fail" + + def rebuild_soft_top(self, soft_colour, params, rng): + """take the soft box (and whatever is on it) off the pile, then stack the rigid boxes and the soft one last""" + soft = BOXES[COLOURS.index(soft_colour)] + for _ in range(6): + ch = self.pile() + if soft in ch: + self.lay_aside(ch[-1], rng) # from the top down to the soft box + elif self.on_mat(soft) or any(soft in self.items_on(b) for b in ch): + self.lay_aside(soft, rng) # bent / off-centre on the mat or on the pile + else: + break + order = [b for b in self.nearest_order() if b != soft] + [soft] + return self.build(order, dict(params, soft_known=soft_colour), rng) + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("noise_seed", 0)) + order = self.plan(params, rng) + res = self.build(order, params, rng) + if res == "collapse": + mode = params.get("on_collapse", "rebuild_same") + if mode == "rebuild_same": # the cheapest explanation: "I did not centre it" -> same order, more care + self.settle_scene() + res = self.build(order, dict(params, err=None, gap=0.005), rng) + elif mode == "identify": # sees which box bent and rebuilds with it on top + self.settle_scene() + soft = self.seen_soft() + if soft and self.cup_tilt() < np.radians(45): + res = self.rebuild_soft_top(soft, params, rng) + self._lift_to(self.z_clear(0.06)) + self.sk.hold(10) + return res + + NAIVE = dict(order="nearest", soft_known=None, on_collapse="rebuild_same") + + def default_params(self, inst): + """Sonnet-like: nearest box first, lifts above everything, straight down, lets go 1-4 cm above (per instance), + 0.4-1.3 cm placement errors, the first box up to 2 cm too far forward; after a collapse it rebuilds once in + the same order, more carefully""" + return dict(self.NAIVE, noise_seed=int(inst["seed"]) * 13, err=NAIVE_ERR, gap=float(inst["naive_gap"]), + bias=float(inst["naive_bias"])) + + def oracle_params(self, inst): + return dict(order="nearest", soft_known=inst["soft_colour"], on_collapse="identify", err=None, gap=0.005) + + def adapt_params(self, inst, history): + soft = None + for h in history: + ev = [e for e in h["outcome"]["events"] if e.get("event") == "buckle"] + if ev: + soft = ev[0]["box"] # the box seen bending (the kink is visible in the images) + return dict(self.default_params(inst), soft_known=soft, on_collapse="identify") + + def blind_params(self, inst, attempt, rng): + return dict(self.default_params(inst), order="random", noise_seed=int(rng.integers(1 << 30)), + gap=float(rng.uniform(*NAIVE_GAP)), bias=float(rng.uniform(*NAIVE_BIAS))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + single = ("oracle", "naive", "naive_centred", "oracle_noise", "naive_once", "naive_lying", "oracle_lying") + if kind in ("naive_lying", "oracle_lying") and inst["soft"]: + # control (v2): the soft carton starts lying on a side face, so it is stacked lying + inst = dict(inst, lying={inst["soft_colour"]: np.pi / 2}) + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": # attempt 1: naive habits, but it looks at the collapse and rebuilds soft-on-top + params = (dict(self.default_params(inst), on_collapse="identify") if a == 0 + else self.adapt_params(inst, history)) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": # control: cross-attempt learning only (no within-attempt identification) + params = self.default_params(inst) if a == 0 else dict(self.adapt_params(inst, history), + on_collapse="rebuild_same") + elif kind == "naive_centred": # control (R4): perfect centring, let go 5 mm above, no rebuild + params = dict(self.default_params(inst), err=None, gap=0.005, bias=0.0, on_collapse="none") + elif kind == "naive_once": # control: naive without the careful rebuild + params = dict(self.default_params(inst), on_collapse="none") + elif kind == "naive_lying": # control (v2): naive_once with the soft carton lying on a side face + params = dict(self.default_params(inst), on_collapse="none") + elif kind == "oracle_lying": # control (v2): soft carton lying, but on top (carries only the cup) + params = dict(self.oracle_params(inst)) + elif kind == "oracle_noise": # robustness: soft box on top with Sonnet-like imprecision + params = dict(self.default_params(inst), soft_known=inst["soft_colour"], on_collapse="identify") + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in single: + break + return history diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/audit_subagent.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/audit_subagent.py new file mode 100644 index 0000000000000000000000000000000000000000..a33e2538d6f85688c28ee23a2fa879cd6026ba99 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/audit_subagent.py @@ -0,0 +1,130 @@ +"""Audit an isolated policy subagent: every tool call it made must stay inside its sandbox. + +python scripts/audit_subagent.py [--out audit.json] +Allowed: Bash `cd && ./robot ...` (or `/robot ...`); Read of /README.md or /obs/*. +With --la (LIBERO-Agent-style workspace): also Bash `cd && ./shell ''` / `./shell <<'TAG' ... TAG` (the +command runs inside the jail; anything the OUTER shell would execute or expand is a violation), and Read / Write / Edit +of any file inside . +Everything else is reported as a violation. Prints counts + violations only (the transcript itself is large). +""" +import argparse +import json +import re + + +def tool_uses(obj): + if isinstance(obj, dict): + if obj.get("type") == "tool_use" and "name" in obj: + yield obj + for v in obj.values(): + yield from tool_uses(v) + elif isinstance(obj, list): + for v in obj: + yield from tool_uses(v) + + +def extra_shell_ops(cmd, sb): + """True if the command contains shell operators / substitutions outside quotes, apart from the + allowed leading `cd &&`.""" + import shlex + body = re.sub(r"^\s*cd\s+%s\s*&&\s*" % re.escape(sb), "", cmd) + if "`" in body or "$(" in body: + return True + try: + lex = shlex.shlex(body, posix=True, punctuation_chars=True) + toks = list(lex) + except ValueError: + return True + return any(t in (";", "&&", "||", "|", "&", ">", ">>", "<") for t in toks) + + +def shell_call_ok(cmd, sb): + """la: `cd && ./shell ...` where nothing runs outside the jail: either one heredoc with a QUOTED tag (no outer + expansion) and nothing after it, or plain arguments without outer operators / substitutions.""" + m = re.match(r"^\s*cd\s+%s\s*&&\s*(\./shell|%s/shell)(.*)$" % (re.escape(sb), re.escape(sb)), cmd, re.S) + if not m: + return False + rest = m.group(2) + s = rest.strip() + if rest[:1].isspace() and len(s) >= 2 and s[0] == "'" and s[-1] == "'" and "'" not in s[1:-1]: + return True # one single-quoted argument: the outer shell expands nothing (an inner `<", ">>", "<") for t in toks) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("transcript") + ap.add_argument("sandbox") + ap.add_argument("--out") + ap.add_argument("--la", action="store_true", help="LIBERO-Agent-style workspace: ./shell and workspace files allowed") + a = ap.parse_args() + sb = a.sandbox.rstrip("/") + ok_bash = re.compile(r"^\s*(cd\s+%s\s*&&\s*)?(\./robot|%s/robot)(\s|$)" % (re.escape(sb), re.escape(sb))) + seen, calls, viol = set(), [], [] + injected = [] # context Claude Code attached on its own: the user's memory index / identity + with open(a.transcript) as f: + for line in f: + try: + rec = json.loads(line) + except ValueError: + continue + if rec.get("type") == "attachment": + at = rec.get("attachment", {}) + if at.get("type") == "instructions": + for fi in at.get("files", []): + if "memory" in (fi.get("path") or "").lower() or fi.get("type") == "AutoMem": + injected.append(dict(kind="memory_index", path=fi.get("path"), chars=len(fi.get("content", "")))) + elif at.get("type") == "session_context": + injected.append(dict(kind="session_context", keys=sorted((at.get("context") or {}).keys()))) + for tu in tool_uses(rec): + if tu.get("id") in seen: + continue + seen.add(tu.get("id")) + name, inp = tu["name"], tu.get("input", {}) + calls.append(name) + if name == "SubagentHandback": # the final report back to the orchestrator + continue + if name == "Bash": + cmd = inp.get("command", "") + bad = (not ok_bash.match(cmd)) or extra_shell_ops(cmd, sb) + if bad and a.la and shell_call_ok(cmd, sb): + bad = False + if bad: + viol.append(dict(tool=name, command=cmd)) + elif name in ("Read", "Write", "Edit") and a.la: + import os + p = os.path.normpath(inp.get("file_path", "")) + if not p.startswith(sb + "/"): + viol.append(dict(tool=name, path=inp.get("file_path", ""))) + elif name == "Read": + p = inp.get("file_path", "") + if not (p == f"{sb}/README.md" or p.startswith(f"{sb}/obs/")): + viol.append(dict(tool=name, path=p)) + else: + viol.append(dict(tool=name, input=json.dumps(inp)[:300])) + from collections import Counter + res = dict(n_calls=len(calls), by_tool=dict(Counter(calls)), n_violations=len(viol), violations=viol, + memory_injected=any(i["kind"] == "memory_index" for i in injected), injected=injected) + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + with open(a.out, "w") as f: + json.dump(res, f, indent=1, ensure_ascii=False) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/start_real_session.sh b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/start_real_session.sh new file mode 100644 index 0000000000000000000000000000000000000000..6ef8faf20fc737b7fcdcd0174f100f1d203ab8d4 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/start_real_session.sh @@ -0,0 +1,30 @@ +#!/bin/bash +# Start a REAL-robot server (lffbench/real/session.py) + workspace for one task instance; same output as +# scripts/start_robot_session.sh (SANDBOX=, LOG=, /session.json), so harness_run.py / api_player.py run on it unchanged. +# usage: scripts/start_real_session.sh [instruction direct|indirect] [k] [tag] +# The driver: $LFF_REAL_DRIVER (default http://127.0.0.1:9900, normally an SSH tunnel to the robot PC) and $LFF_DRIVER_TOKEN. +# Blocks until the operator has set up the scene for attempt 1 (up to $LFF_REAL_READY_WAIT s, default 3600). +set -e +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +TASK=$1; SEED=$2; MEM=$3; FB=$4; PORT=$5; INSTR=${6:-direct}; K=${7:-}; TAG=${8:-} +RUN=${TAG:+${TAG}_}${TASK}_s${SEED}_${MEM}_${FB}_${INSTR}_k${K:-d}_$(date +%m%d-%H%M%S)_p${PORT} +SANDBOX=${LFF_SANDBOX_ROOT:-/tmp/robotlab}/$(python3 -c 'import secrets;print(secrets.token_hex(6))') +LOG=${LFF_RUNS_DIR:-$ROOT/runs/real}/$RUN +mkdir -p "$SANDBOX" "$LOG" +cd "$ROOT" && source run_env.sh && export OMP_NUM_THREADS=1 +KARG=""; [ -n "$K" ] && KARG="--k $K" +nohup python -m lffbench.real.session --task "$TASK" --seed "$SEED" --memory "$MEM" --feedback "$FB" \ + --instruction "$INSTR" --port "$PORT" --sandbox "$SANDBOX" --log-dir "$LOG" --run-name "$RUN" ${LFF_EXTRA_ARGS:-} $KARG \ + > "$LOG/server.log" 2>&1 & +echo $! > "$LOG/server.pid" +WAIT=${LFF_REAL_READY_WAIT:-3600} +for i in $(seq 1 "$WAIT"); do + [ -f "$LOG/READY" ] && break + kill -0 "$(cat "$LOG/server.pid")" 2>/dev/null || break + [ $((i % 30)) -eq 0 ] && echo "waiting for the operator to set up the scene ($i s)" >&2 + sleep 1 +done +[ -f "$LOG/READY" ] || { echo "server failed"; tail -20 "$LOG/server.log"; exit 1; } +echo "{\"run\": \"$RUN\", \"sandbox\": \"$SANDBOX\", \"port\": $PORT}" > "$LOG/session.json" +echo "SANDBOX=$SANDBOX" +echo "LOG=$LOG" diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/MANIFEST.md b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/MANIFEST.md new file mode 100644 index 0000000000000000000000000000000000000000..4559d348e1e18fa413cf193f1478535c38eda620 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/MANIFEST.md @@ -0,0 +1,12 @@ +# LFF benchmark replay supplement: clh_20261102_gpt + +Source: completed evaluation runs in /mnt/cpfs/workspace/agentic-robotics/ops/compound_lh_eval_20261102/source/runs/api/clh_20261102_gpt. +Immutable inventory and frozen matching source: /mnt/cpfs/workspace/agentic-robotics/ops/compound_lh_eval_20261102/inventory.json. +Generated with `/mnt/cpfs/workspace/env/libero-cpu/bin/python /mnt/cpfs/workspace/agentic-robotics/ops/compound_lh_eval_20261102/controller.py` (started 2026-11-02 UTC). +LeRobot v3, 20 Hz, Franka Panda simulation, two 256x256 cameras. +Contains 18 runs, 27 episodes, 104451 frames; 2470242145 bytes before manifest. +Success and failure episodes retained; supplemental/ablation batches retain their original condition and dossier metadata. +All admitted runs pass server-code hash, instance, robot-report and outcome replay checks. +LeRobot reader validation: {"codebase_version": "v3.0", "episodes": 27, "frames": 104451, "plan_episodes": 27, "plan_frames": 104451, "samples": 60, "max_state_action_abs_err": 1.1723213644287966e-07, "max_mean_abs_pixel_err": 0.0, "status": "pass"}. +Replay rejections: /mnt/cpfs/workspace/agentic-robotics/ops/compound_lh_eval_20261102/exports/clh_20261102_gpt/replay_rejections.json. Export-plan episode exclusions: /mnt/cpfs/workspace/agentic-robotics/ops/compound_lh_eval_20261102/exports/clh_20261102_gpt/work/plan.json. +Incremental supplement only. Earlier versions remain unchanged. Development smoke/debug/pilot runs excluded. diff --git a/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/evaluation_evidence/inactive_arm_review_20261115.json b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/evaluation_evidence/inactive_arm_review_20261115.json new file mode 100644 index 0000000000000000000000000000000000000000..cccf68ca3c74e6d1488c197795e039682413f7e4 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/evaluation_evidence/inactive_arm_review_20261115.json @@ -0,0 +1,26 @@ +{ + "created_utc": "2026-11-15T06:37:56.538868+00:00", + "reviews": [ + { + "task": "lh_clear_cover", + "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_lh_clear_cover_s3000_full_F1_direct_k3_1114-212525_p31112", + "baseline_log": "/mnt/cpfs/workspace/agentic-robotics/lffbench/runs/api/cx_main1/cx_main1-gpt-6-astra-codex-harness-hidek_lh_clear_cover_s3000_full_F1_direct_k3_1020-042848_p16501", + "exact_contract_match": false, + "semantic_match": true, + "reason": "Only pinned unused intervention-text file added to hash inventory; arm none, session_start identical except time, all existing source hashes identical" + }, + { + "task": "lh_tidy_stack", + "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_lh_tidy_stack_s3000_full_F1_direct_k3_1114-235829_p31110", + "baseline_log": "/mnt/cpfs/workspace/agentic-robotics/lffbench/runs/api/cx_main1/cx_main1-gpt-6-astra-codex-harness-hidek_lh_tidy_stack_s3000_full_F1_direct_k3_1020-100717_p16500", + "exact_contract_match": false, + "semantic_match": true, + "reason": "Only pinned unused intervention-text file added to hash inventory; arm none, session_start identical except time, all existing source hashes identical" + } + ], + "negative_checks": [ + "changed budget rejected", + "active intervention rejected" + ], + "all_original_raw_contracts_preserved": true +} diff --git a/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/agent/camera.py b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/agent/camera.py new file mode 100644 index 0000000000000000000000000000000000000000..e1ce86343d9f718577b0a672ed5cb3202c6fc941 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/agent/camera.py @@ -0,0 +1,100 @@ +"""Camera geometry for the agent tools: pixel -> world back-projection with the rendered depth map. + +Conventions (match the images the agent receives, i.e. `envs.render`, which flips MuJoCo's +bottom-up buffer to an upright image): + u = column index (0 = left edge), v = row index (0 = top edge), both in pixels of a res x res image. +Intrinsics / extrinsics / depth linearisation come from robosuite.utils.camera_utils. +""" +import numpy as np +from robosuite.utils import camera_utils as CU + +from .. import envs + +# agent-facing camera name -> MuJoCo camera name +CAMERAS = {"agentview": "agentview", "wrist": "robot0_eye_in_hand"} + + +def mj_cam(name): + if name in CAMERAS: + return CAMERAS[name] + if name in CAMERAS.values(): + return name + raise KeyError(f"unknown camera {name!r}; use one of {sorted(CAMERAS)}") + + +def intrinsics(env, cam, res): + return CU.get_camera_intrinsic_matrix(env.sim, mj_cam(cam), res, res) + + +def cam_to_world(env, cam): + """4x4 pose of the camera in the world, OpenCV axes (x right, y down, z forward).""" + return CU.get_camera_extrinsic_matrix(env.sim, mj_cam(cam)) + + +def render_depth(env, cam, res): + """Metric depth (distance along the optical axis, metres), upright (res, res).""" + _, d = envs.render(env, mj_cam(cam), res, depth=True) + return CU.get_real_depth_map(env.sim, np.clip(d, 0.0, 1.0)) + + +def world_to_pixel(env, cam, xyz, res): + """Project a world point; returns (u, v) floats (u = column, v = row) and the depth.""" + K = intrinsics(env, cam, res) + T = np.linalg.inv(cam_to_world(env, cam)) + p = T @ np.append(np.asarray(xyz, float), 1.0) + uvw = K @ p[:3] + return float(uvw[0] / uvw[2]), float(uvw[1] / uvw[2]), float(p[2]) + + +def pixel_ray(env, cam, u, v, res): + """Unit ray direction (world) through pixel (u, v) and the camera origin.""" + K = intrinsics(env, cam, res) + E = cam_to_world(env, cam) + d_cam = np.array([(u - K[0, 2]) / K[0, 0], (v - K[1, 2]) / K[1, 1], 1.0]) + d = E[:3, :3] @ d_cam + return E[:3, 3].copy(), d / np.linalg.norm(d) + + +def pixel_to_world(env, cam, u, v, res, depth=None): + """Back-project pixel (u, v) of a res x res image using the depth map. Returns a dict.""" + if depth is None: + depth = render_depth(env, cam, res) + iu, iv = int(round(u)), int(round(v)) + if not (0 <= iu < res and 0 <= iv < res): + raise ValueError(f"pixel ({u}, {v}) outside the {res}x{res} image") + z = float(depth[iv, iu]) + K = intrinsics(env, cam, res) + E = cam_to_world(env, cam) + p_cam = np.array([(u - K[0, 2]) * z / K[0, 0], (v - K[1, 2]) * z / K[1, 1], z, 1.0]) + p = E @ p_cam + far = env.sim.model.vis.map.zfar * env.sim.model.stat.extent + return dict(xyz=p[:3], depth=z, valid=bool(z < 0.98 * far)) + + +def image_axes(env, cam, res, plane_z=envs.TABLE_Z): + """World directions of image-right and image-down at the image centre, projected onto the table + plane (for describing the camera to the agent). Returns two unit 2-vectors (x, y).""" + o, d = pixel_ray(env, cam, res / 2, res / 2, res) + if abs(d[2]) < 1e-6: + return None + t = (plane_z - o[2]) / d[2] + c = o + t * d + out = [] + for du, dv in ((8, 0), (0, 8)): + o2, d2 = pixel_ray(env, cam, res / 2 + du, res / 2 + dv, res) + t2 = (plane_z - o2[2]) / d2[2] + w = (o2 + t2 * d2 - c)[:2] + out.append(w / max(np.linalg.norm(w), 1e-9)) + return out + + +def describe_axes(env, cam, res): + """Human-readable mapping 'image right ~ +y, image down ~ +x' (dominant axis, sign).""" + ax = image_axes(env, cam, res) + if ax is None: + return None + names = [] + for w in ax: + i = int(np.argmax(np.abs(w))) + names.append(("+" if w[i] > 0 else "-") + "xy"[i]) + return dict(right=names[0], down=names[1]) diff --git a/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json new file mode 100644 index 0000000000000000000000000000000000000000..2c0ed07f857e5cd9c72470d4af45bfd541fecea9 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json @@ -0,0 +1,15 @@ +{ + "key": "claude_code_full-oauth|2.1.267|0399c793ff571d59|claude-sonnet-5-5|high", + "fingerprint_sha256": "0f8972223c9bdc90da28633f367aa577ae839f887c2f3f015f8128bb34a7f5b4", + "written": "2026-10-20 02:16:14", + "summary": { + "system_chars": 26736, + "tools": [ + "mcp__lff__robot", + "mcp__lff__shell", + "mcp__lff__view_images" + ], + "effort_in_request": "high", + "model_in_request": "claude-sonnet-5-5" + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/lh_tray_delivery.py b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/lh_tray_delivery.py new file mode 100644 index 0000000000000000000000000000000000000000..e36d0bedffbe7e091b3fc8ae3c7c3e9f9508a53c --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/lh_tray_delivery.py @@ -0,0 +1,883 @@ +"""LH tray_delivery v2 (long horizon, state restoration): load three bottles onto a tray in the loading area, then move +the loaded tray over a low threshold strip into the delivery area. Pushing the tray over the strip makes it rock, and +the top-heavy bottles fall; holding the tray by its handle while moving it does not. + +Family: long-horizon tasks in which the agent's own normal later-stage action physically breaks earlier progress +(docs/11). Stages: + S1-S3 stand the red / green / blue bottle upright on the tray while the tray is inside the yellow loading area; + S4 move the tray (with the bottles) over the black threshold strip completely into the purple delivery area. +Success (F1): at the end the tray (board and handle) is completely inside the delivery area, all three bottles stand +upright on it, the gripper does not touch them, the scene is static, AND the event log shows that all three bottles +stood on the tray at the same time while the tray was still completely inside the loading area (load first, then +deliver). Re-standing a fallen bottle on the tray after the move is allowed (counts as a restoration). + +v2 (2026-10-09, after the Sonnet 5.5 pilot lh1, see the task card): v1's 15.6 cm bottles on a 2.2 cm foot were hard to +grasp and to stand, the narrow handle was hard to push straight, "completely inside" needed 2 cm precision, and the +agents pushed at 3-5 cm/s, far below v1's 0.15 m/s topple threshold, so the hidden variable never mattered. Now: +- bottles 10.5 cm tall: 4 x 4 x 7.5 cm square body with a flat bottom + a 2.4 cm round neck (3 cm tall), 0.25 kg; +- T handle, 2.5 cm tall: a 16 cm push bar at the back (push it with the closed gripper) on a 3 cm wide, 5 cm long stem + (grasp it across its width); +- delivery area 28 x 42 cm for the 18.5 x 34 cm tray footprint (4.75 / 4 cm slack per side; v1: 2 / 3 cm); +- a black threshold strip between the areas (a rounded sill 1 cm high, 5.3 cm wide, 46 cm long) that the tray has to + cross. Measured: with stocky bottles speed alone cannot be the lever (on a flat table a top-heavy bottle stayed up in + closed-gripper pushes up to 0.3 m/s; only the controller's top speed, ~0.65 m/s, toppled it). On the sill the tray + first climbs (front up ~5 deg), then rocks over the crest under gravity; when it is pushed, nothing holds its trailing + edge, which jumps up (max tray tilt 7.2-9.3 deg) and the top-heavy bottles fall over the leading edge, + at every push speed tried (2-6 cm/s and the top speed). When the stem is grasped, the hand holds the trailing edge + (max tilt 5.7-7.5 deg) and nothing falls. A hand hovering right over the handle (3 cm handle pushed with the + grasp point ~1 cm above the table) also held it down; hence the 2.5 cm handle. +- failure codes report the first unmet requirement: not_loaded / order / bottle_fallen / bottle_off_tray / + not_delivered / held / not_static. + +Scene: wooden tray = an 11 x 34 x 1.2 cm board, long side running forward / back, with the T handle sticking out of the +middle of the long side that faces away from the delivery area; three bottles (same shape, red / green / blue) standing +in a row on the table on the far side of the loading area; two painted rectangles (no collision): yellow loading area +(tray inside it at the start) and purple delivery area 32-34 cm (centre to centre) to its left or right (random); the +threshold strip lies across the path in the gap between them. The tray travels sideways (the arm's comfortable +workspace is wide in y but short in x). + +Hidden variable (same appearance): each bottle's centre-of-mass height (an invisible internal weight, 85 % of its +mass): "stable" 2.0-3.5 cm, "top-heavy" 6.6-7.6 cm above the bottom; 0 / 1 / 2 top-heavy bottles with p = 0.35 / 0.40 / +0.25. Measured on 28 instances (scripted loading, same loaded state for every move): closed-gripper pushes (2, 3, 4.5, +6 cm/s, top speed, 3 stops, slow approach; agent-style pushes through the tool layer with the grasp point 1.0 / 1.3 / +2.5 cm above the table) toppled 24/24 top-heavy bottles and 0/60 stable ones in every variant; grasp-and-drag at 2 and +4.5 cm/s toppled 0/84. Above a COM of 8 cm falling bottles sometimes land standing on their neck (cannot be stood up +again with yaw-only control without first knocking them over), so the range stops at 7.6 cm. Tray-table friction +0.45-0.60 is a nuisance variable; the sill's own friction (0.4) wins in its contacts (with the tray's 0.85 the tray +jammed at the sill and jumped over it, toppling nothing). +Restoration: a fallen bottle can be stood up again: grasp its round neck (fingers closing across the neck), lift it -- +it swings down and hangs from the neck -- and set it down on the tray. + +Simulation notes (as in v1): COM heights are set at reset through body_ipos / inertia and the bottle's collision BVH is +shifted with it (MuJoCo keeps it in the inertial frame); the tray uses the table's soft contact (solref 0.02); the +bottles' own contacts are stiffer (solref 0.005) so a bottle lowered onto the board by its neck is not pressed through. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +SOFT = 'solimp="0.9 0.95 0.001" solref="0.02 1"' # the LIBERO table's contact parameters + +# bottle: square body with a flat 4 x 4 cm bottom + round neck; body origin at the middle of the total height +BODY = (0.020, 0.020, 0.0375) # half sizes of the body (4 x 4 x 7.5 cm) +NECK_R, NECK_H = 0.012, 0.015 # neck radius, half height (2.4 cm wide, 3 cm tall) -> 10.5 cm in total +BH = BODY[2] + NECK_H # half of the total height +DAMP_BOT = 0.003 # free-joint damping of the bottles (air drag; damps the swing of a bottle hanging from its neck) +BOT_MASS = 0.25 +W_FRAC = 0.85 # share of the mass in the hidden internal weight +MU_BOT = 1.0 +COS_UP = 0.95 # upright: long axis within ~18 deg of vertical +BOT_SOLREF = (0.005, 1.0) # the bottles win in all their contacts (priority 3) +BOT_SOLIMP = (0.95, 0.99, 0.001, 0.5, 2.0) + +# tray: board + T handle (stem + cross bar) sticking out of the middle of the trailing long side (tray frame -x) +PLATE = (0.055, 0.17, 0.006) # 11 x 34 x 1.2 cm board +STEM = (0.025, 0.015, 0.0125) # 5 long x 3 wide x 2.5 cm tall: grasp it across its width +CROSS = (0.0125, 0.08, 0.0125) # 2.5 deep x 16 wide x 2.5 cm tall bar at the back: push it with the closed gripper +# Handle height 2.5 cm (measured on 6 instances x 6 push heights, see the card): the Panda palm reaches ~3-4 cm ahead +# of the fingers and ~2 cm above the grasp point. With a 3 cm handle a hand pushing low (grasp point ~1 cm above the +# table) hovered right over the handle and kept the trailing edge from jumping up on the sill (like a grasp: no topple +# in 3/6); with 2.5 cm every push with the grasp point 1-2.5 cm above the table toppled the top-heavy bottles (36/36). +# A hand pushing at >= 3 cm only touches the handle with its fingertips and can slide over it. +PLATE_TOP = envs.TABLE_Z + 2 * PLATE[2] +BACK_X = -PLATE[0] - 2 * STEM[0] - 2 * CROSS[0] # tray-frame x of the handle's back face (-0.13) +FOOT_DX = (PLATE[0] + BACK_X) / 2 # x of the footprint centre (board + handle) relative to the board centre +# slots 1.5 cm towards the leading edge: a hand grasping the cross bar with its long side along the travel direction +# (palm 10.5 cm ahead of the grasp point) still clears the middle bottle by ~7 mm +SLOT_LX = 0.015 +SLOT_LY = (-0.12, 0.0, 0.12) +MU_HANDLE = 0.6 + +# painted areas (inner half sizes: along travel, along the tray's long side) +LOAD_IN = (0.1125, 0.20) # tray footprint 18.5 x 34 cm -> 2 / 3 cm slack per side +DELIV_IN = (0.14, 0.21) # -> 4.75 / 4 cm slack per side +LINE_W = 0.008 +AREA_DIST = (0.32, 0.34) # centre to centre + +# threshold strip: a capsule lying across the path, sunk into the table so that it sticks out RIDGE_H (a rounded sill +# 2 * sqrt(2 R h - h^2) = 5.3 cm wide) +RIDGE_H = 0.010 +RIDGE_R = 0.040 +RIDGE_HL = 0.23 # half length of the straight part (46 cm: longer than the tray) +MU_RIDGE = 0.4 # wins in its contacts (priority 4) + +BOTTLES = ("bottle_red_1", "bottle_green_1", "bottle_blue_1") +COLOR_OF = {"bottle_red_1": "red", "bottle_green_1": "green", "bottle_blue_1": "blue"} +RGBA = {"red": (0.82, 0.12, 0.10, 1.0), "green": (0.12, 0.60, 0.20, 1.0), "blue": (0.12, 0.30, 0.85, 1.0)} +TRAY = "tray_1" +LOAD, DELIVER, RIDGE = "load_area_1", "deliver_area_1", "threshold_1" + +# hidden COM heights above the bottle's bottom (m); calibration in the task card +HC_STABLE = (0.020, 0.035) +HC_TOPHEAVY = (0.066, 0.076) +N_TOP_P = (0.35, 0.40, 0.25) # P(0 / 1 / 2 top-heavy bottles) +MU_TRAY = (0.45, 0.60) + +DEBOUNCE = 5 # control steps a predicate must keep a new value before an event is recorded (0.25 s) + +# scripted reference moves +V_NAIVE = 0.045 # the pilot agents pushed at 3-6 cm/s +V_CAREFUL = 0.02 # the LA interface's slowest speed +GRASP_TOP = 0.012 # scripted grasp point: on the neck, this far below the bottle's top (the palm is ~2 cm above it) +SAFE_Z = envs.TABLE_Z + 0.17 # scripted transits: fingertips ~5 cm above the tops of bottles standing on the tray +SAFE_Z_HELD = envs.TABLE_Z + 0.25 # ... and with a bottle hanging from the gripper: its bottom ~4 cm above them +PUSH_Z = envs.TABLE_Z + 0.015 # closed-gripper pushes: grasp point 1.5 cm above the table (fingertips ~0.5 cm) +DRAG_Z = envs.TABLE_Z + 0.015 # grasping the stem: finger pads over its whole height + + +def bottle_xml(name, rgba): + zb = -BH + BODY[2] + zn = -BH + 2 * BODY[2] + NECK_H + neck_rgba = tuple(0.8 * c for c in rgba[:3]) + (1.0,) + parts = [("box", zb, _fmt(BODY), rgba), ("cylinder", zn, f"{NECK_R:.5f} {NECK_H:.5f}", neck_rgba)] + gs = [] + for k, (typ, z, size, c) in enumerate(parts): + gs.append(f' ') + gs.append(f' ') + return _wrap(name, "\n".join(gs), BH, float(np.hypot(BODY[0], BODY[1]))) + + +def tray_xml(name, rgba=(0.62, 0.45, 0.27, 1.0)): + hz = -PLATE[2] + STEM[2] # handle bottom flush with the board's bottom + sp = (-PLATE[0] - STEM[0], 0.0, hz) + cp = (-PLATE[0] - 2 * STEM[0] - CROSS[0], 0.0, hz) + hrgba = (0.30, 0.20, 0.12, 1.0) + gs = [] + for k, (p, s, c, mu) in enumerate((((0, 0, 0), PLATE, rgba, 0.6), (sp, STEM, hrgba, MU_HANDLE), + (cp, CROSS, hrgba, MU_HANDLE))): + gs.append(f' ') + gs.append(f' ') + return _wrap(name, "\n".join(gs), PLATE[2], float(np.hypot(PLATE[0] - BACK_X, PLATE[1]))) + + +def area_xml(name, inner, fill, line): + """Flat, visual-only rectangle painted on the table (light fill + dark outline, no collisions).""" + ix, iy = inner + ox, oy = ix + LINE_W, iy + LINE_W + parts = [((0, 0, 0.0004), (ox, oy, 0.0004), fill), + ((0, iy + LINE_W / 2, 0.0010), (ox, LINE_W / 2, 0.0002), line), + ((0, -iy - LINE_W / 2, 0.0010), (ox, LINE_W / 2, 0.0002), line), + ((ix + LINE_W / 2, 0, 0.0010), (LINE_W / 2, oy, 0.0002), line), + ((-ix - LINE_W / 2, 0, 0.0010), (LINE_W / 2, oy, 0.0002), line)] + g = "\n".join(f' ' for p, sz, c in parts) + return _wrap(name, g, 0.0012, float(np.hypot(ox, oy))) + + +def sill_xml(name, rgba=(0.12, 0.12, 0.13, 1.0)): + """the threshold strip: a capsule along the fixture's local y (quat turns z into y), origin on its axis; the + fixture is placed with the axis RIDGE_R - RIDGE_H below the table top (static: no contacts with the table)""" + q = "0.70711 0.70711 0 0" + g = (f' \n' + f' ') + return _wrap(name, g, RIDGE_R, RIDGE_HL + RIDGE_R) + + +def _rotz2(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s], [s, c]]) + + +def _yaw_of(R): + return float(np.arctan2(R[1, 0], R[0, 0])) + + +class TraySkills(Skills): + """Skills whose every control step feeds the task's stage monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class TrayDelivery(LFFTask): + name = "lh_tray_delivery" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Plan") + protocol = "cross" + max_attempts = 3 + # scripted primitives (~ agent commands): careful oracle 37; naive push + same-attempt repair of 1-2 bottles 46-63 + agent_max_steps = 110 + instruction = ("Load the red, green and blue bottles onto the wooden tray: stand each bottle upright on the tray " + "while the tray is still inside the yellow loading area. Only after all three bottles are on the " + "tray, move the tray with the bottles on it over the black threshold strip into the purple " + "delivery area. At the end the whole tray, including its handle, must be inside the purple area " + "with all three bottles standing upright on it.") + instruction_indirect = ("Stand the three bottles up on the wooden board that lies in the yellow rectangle while " + "the board is still there; then bring the board with the bottles on it across the black " + "strip into the purple rectangle. At the end the whole board, including its dark handle, " + "must lie inside the purple rectangle with all three bottles standing on it.") + agent_object_names = ["red bottle", "green bottle", "blue bottle", "wooden tray", "yellow loading area", + "purple delivery area", "black threshold strip"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs = [] + for i, b in enumerate(BOTTLES): + c = COLOR_OF[b] + cat = register_generated(f"LffTdBottle{c.capitalize()}", bottle_xml(f"lff_td_bottle_{c}", RGBA[c])) + x0 = -0.25 + 0.12 * i + objs.append((b, cat, f"bottle_{c}_region", (x0, 0.30, x0 + 0.01, 0.31))) + tray = register_generated("LffTdTray", tray_xml("lff_td_tray")) + objs.append((TRAY, tray, "tray_region", (0.0, -0.05, 0.01, -0.04))) + load = register_generated("LffTdLoadArea", area_xml("lff_td_load_area", LOAD_IN, (0.98, 0.93, 0.55, 1.0), + (0.85, 0.62, 0.05, 1.0)), free=False) + deliv = register_generated("LffTdDeliverArea", area_xml("lff_td_deliver_area", DELIV_IN, + (0.86, 0.78, 0.95, 1.0), (0.45, 0.20, 0.65, 1.0)), + free=False) + sill = register_generated("LffTdThreshold", sill_xml("lff_td_threshold"), free=False) + fx = [(LOAD, load, "load_region", (-0.21, -0.41, -0.20, -0.40)), + (DELIVER, deliv, "deliver_region", (0.15, -0.41, 0.16, -0.40)), + (RIDGE, sill, "threshold_region", (0.15, 0.38, 0.16, 0.39))] + return write_bddl(self.name, self.instruction, objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + env = self.env + m = env.sim.model + self.area_bid = {a: m.body_name2id(env.fixtures_dict[a].root_body) for a in (LOAD, DELIVER, RIDGE)} + self.bid = {n: envs.body_id(env, n) for n in BOTTLES + (TRAY,)} + mm = m._model + self._bvh0 = {} + for b in BOTTLES: # compiled inertial frame + BVH (shifted with the hidden COM at every reset) + bid = self.bid[b] + adr, num = mm.body_bvhadr[bid], mm.body_bvhnum[bid] + self._bvh0[b] = (m.body_ipos[bid].copy(), mm.bvh_aabb[adr:adr + num].copy(), adr, num) + # geom -> object index for the contact checks (0..2 bottles, 3 tray) + self._obj_of = np.full(m.ngeom, -1, int) + for k, n in enumerate(BOTTLES + (TRAY,)): + self._obj_of[envs.obj_geom_ids(env, n)] = k + self._is_robot = np.zeros(m.ngeom, bool) + self._is_robot[envs.robot_geom_ids(env)] = True + sb = self.area_bid[RIDGE] + self._is_sill = np.array([m.geom_bodyid[g] == sb or m.body_parentid[m.geom_bodyid[g]] == sb + for g in range(m.ngeom)], bool) + self._dof = {n: envs.free_joint_addr(env, n)[1] for n in BOTTLES + (TRAY,)} + self.inst = None + self.mon = None + + def sample_instance(self, seed): + """Layout: the tray's long side runs forward / back (world x); it travels sideways (world y) from the loading + area to the delivery area, 32-34 cm centre to centre, to the left or to the right, over the threshold strip in + the middle of the gap between the areas. The bottles stand in a row on the table on the far side of the + loading area. Tray frame: local +x = direction of travel, handle at local -x.""" + rng = np.random.default_rng(seed) + s = 1.0 if rng.random() < 0.5 else -1.0 # +1: the tray travels to the robot's left (+y) + xl, yl = float(rng.uniform(-0.18, -0.15)), float(-s * rng.uniform(0.11, 0.13)) + dist = float(rng.uniform(*AREA_DIST)) + deliver = [xl + float(rng.uniform(-0.01, 0.01)), yl + s * dist] + yaw = s * np.pi / 2 + R = _rotz2(yaw) + g0, g1 = LOAD_IN[0] + LINE_W, dist - DELIV_IN[0] - LINE_W # the gap between the areas, along travel + sill_xy = [(xl + deliver[0]) / 2, float((np.array([xl, yl]) + R @ np.array([(g0 + g1) / 2, 0.0]))[1])] + jit = np.array([rng.uniform(-0.008, 0.008), rng.uniform(-0.005, 0.005)]) # tray frame + tray_xy = (np.array([xl, yl]) + R @ (np.array([-FOOT_DX, 0.0]) + jit)).tolist() + order = [int(i) for i in rng.permutation(3)] # bottle -> position in the start row (along x) + by = yl - s * (LOAD_IN[0] + LINE_W + 0.04) + start = {} + for k, b in enumerate(BOTTLES): + start[b] = [xl + (-0.12, 0.0, 0.12)[order[k]] + float(rng.uniform(-0.008, 0.008)), + by + float(rng.uniform(-0.005, 0.005)), float(rng.uniform(-0.35, 0.35))] + n_top = int(rng.choice(3, p=N_TOP_P)) + top = set(int(i) for i in rng.choice(3, n_top, replace=False)) + hc = {b: float(rng.uniform(*(HC_TOPHEAVY if k in top else HC_STABLE))) for k, b in enumerate(BOTTLES)} + return dict(seed=int(seed), travel="left" if s > 0 else "right", area_yaw=float(yaw), load_xy=[xl, yl], + deliver_xy=deliver, sill_xy=sill_xy, tray_xy=tray_xy, tray_yaw=float(yaw), bottle_start=start, + com_height=hc, top_heavy=[b for k, b in enumerate(BOTTLES) if k in top], + mu_tray=float(rng.uniform(*MU_TRAY))) + + def _set_com(self, b, hc): + """Hidden internal weight: bottle COM at height hc above its bottom (mass and inertia consistent).""" + m = self.env.sim.model + mm = m._model + bid = self.bid[b] + a, c = BODY[0], BODY[2] + vb, vn = 8 * a * a * c, np.pi * NECK_R ** 2 * 2 * NECK_H + zs = ((-BH + c) * vb + (-BH + 2 * c + NECK_H) * vn) / (vb + vn) # shell COM (origin: middle of the height) + ms, mw = BOT_MASS * (1 - W_FRAC), BOT_MASS * W_FRAC + zw = float(np.clip((BOT_MASS * (hc - BH) - ms * zs) / mw, -BH + 0.01, BH - 0.01)) + zc = (ms * zs + mw * zw) / BOT_MASS + ww = 0.025 # the weight is a 2.5 cm cube + Ixx = ms / 3 * (a * a + c * c) + ms * (zs - zc) ** 2 + mw * (zw - zc) ** 2 + mw * ww * ww / 6 + Izz = ms * 2 * a * a / 3 + mw * ww * ww / 6 + m.body_mass[bid] = BOT_MASS + m.body_ipos[bid] = [0.0, 0.0, zc] + m.body_iquat[bid] = [1.0, 0.0, 0.0, 0.0] + m.body_inertia[bid] = [Ixx, Ixx, Izz] + ip0, A0, adr, num = self._bvh0[b] + mm.bvh_aabb[adr:adr + num, :3] = A0[:, :3] - (m.body_ipos[bid] - ip0) # BVH lives in the inertial frame + return zc + BH + + def apply_instance(self, inst): + self.inst = inst + env = self.env + m = env.sim.model + ya = inst["area_yaw"] + qa = [np.cos(ya / 2), 0.0, 0.0, np.sin(ya / 2)] + for a, key in ((LOAD, "load_xy"), (DELIVER, "deliver_xy")): + m.body_pos[self.area_bid[a]] = [inst[key][0], inst[key][1], envs.TABLE_Z + 0.0002] + m.body_quat[self.area_bid[a]] = qa + m.body_pos[self.area_bid[RIDGE]] = [inst["sill_xy"][0], inst["sill_xy"][1], envs.TABLE_Z + RIDGE_H - RIDGE_R] + m.body_quat[self.area_bid[RIDGE]] = qa + for g in np.flatnonzero(self._is_sill): # the sill's friction wins (the tray's would otherwise: priority 2) + m.geom_friction[g] = [MU_RIDGE, 0.005, 0.0001] + m.geom_priority[g] = 4 + envs.set_obj_pose(env, TRAY, [inst["tray_xy"][0], inst["tray_xy"][1], envs.TABLE_Z + PLATE[2] + 0.0005], + yaw=inst["tray_yaw"]) + envs.set_friction(env, TRAY, inst["mu_tray"], priority=2) + for b in BOTTLES: + self._set_com(b, inst["com_height"][b]) + for g in envs.obj_geom_ids(env, b): # bottle params win in all its contacts (tray, table, fingers) + m.geom_friction[g] = [MU_BOT, 0.005, 0.0001] + m.geom_condim[g] = 3 + m.geom_priority[g] = 3 + m.geom_solref[g] = BOT_SOLREF + m.geom_solimp[g] = BOT_SOLIMP + m.dof_damping[self._dof[b]:self._dof[b] + 6] = DAMP_BOT + x, y, yaw = inst["bottle_start"][b] + envs.set_obj_pose(env, b, [x, y, envs.TABLE_Z + BH + 0.0005], yaw=yaw) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = TraySkills(self.env, self, recorder=recorder) + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ geometry / predicates + def tray_pose(self): + d = self.env.sim.data + bid = self.bid[TRAY] + return d.body_xpos[bid].copy(), d.body_xmat[bid].reshape(3, 3).copy() + + def tray_footprint(self): + p, R = self.tray_pose() + loc = np.array([[PLATE[0], PLATE[1]], [PLATE[0], -PLATE[1]], [-PLATE[0], PLATE[1]], [-PLATE[0], -PLATE[1]], + [BACK_X, CROSS[1]], [BACK_X, -CROSS[1]]]) + return p[:2] + loc @ R[:2, :2].T + + @staticmethod + def _word(v): + """robot-centric word for a horizontal world direction""" + if abs(v[0]) >= abs(v[1]): + return "forward" if v[0] > 0 else "back" + return "left" if v[1] > 0 else "right" + + def area_excess(self, key): + """How far the tray footprint sticks out of the area (m, >0 = outside) per edge, keyed by robot-centric word.""" + c = np.asarray(self.inst[key]) + Ra = _rotz2(self.inst["area_yaw"]) + pts = (self.tray_footprint() - c) @ Ra # area frame + inner = LOAD_IN if key == "load_xy" else DELIV_IN + out = {} + for axis, sign in ((0, 1), (0, -1), (1, 1), (1, -1)): + u = np.zeros(2) + u[axis] = sign + out[self._word(Ra @ u)] = float((sign * pts[:, axis]).max() - inner[axis]) + return out + + def tray_inside(self, key): + return max(self.area_excess(key).values()) <= 0.0 + + def _contacts(self): + d = self.env.sim.data + n = d.ncon + if not n: + return np.zeros(0, int), np.zeros(0, int) + return np.asarray(d.contact.geom1)[:n], np.asarray(d.contact.geom2)[:n] + + def robot_touch(self): + """indices (0..2 bottles, 3 tray) of the objects the robot touches now""" + g1, g2 = self._contacts() + hit = np.concatenate([self._obj_of[g2[self._is_robot[g1]]], self._obj_of[g1[self._is_robot[g2]]]]) + return set(int(i) for i in hit[hit >= 0]) + + def tray_on_sill(self): + g1, g2 = self._contacts() + tray = self._obj_of == 3 + return bool(np.any((tray[g1] & self._is_sill[g2]) | (tray[g2] & self._is_sill[g1]))) + + def bottle_state(self, b, touched=False): + d = self.env.sim.data + bid = self.bid[b] + p = d.body_xpos[bid] + up = float(d.body_xmat[bid].reshape(3, 3)[2, 2]) + tp, R = self.tray_pose() + loc = R.T @ (p - tp) + on_xy = abs(loc[0]) <= PLATE[0] and abs(loc[1]) <= PLATE[1] + resting = abs(loc[2] - (PLATE[2] + BH)) < 0.012 + upright = up >= COS_UP + return dict(upright=bool(upright), on_tray=bool(on_xy and resting), touched=bool(touched), + ok=bool(upright and on_xy and resting and not touched), loc=loc, pos=p.copy(), cos=up) + + def predicates(self): + t = self.robot_touch() + st = {b: self.bottle_state(b, k in t)["ok"] for k, b in enumerate(BOTTLES)} + st["tray_in_delivery"] = self.tray_inside("deliver_xy") + st["tray_in_loading"] = self.tray_inside("load_xy") + return st, t + + def _tray_speed(self): + da = self._dof[TRAY] + return float(np.linalg.norm(self.env.sim.data.qvel[da:da + 2])) + + # ------------------------------------------------------------ monitor + def _init_monitor(self): + st, _ = self.predicates() + self.mon = dict(stable=dict(st), cnt={k: 0 for k in st}, ever=set(k for k, v in st.items() if v), + lost=set(), events=[], order_step=None, last_touch={k: -10 ** 6 for k in range(4)}, + last_tray_move=-10 ** 6, last_sill=-10 ** 6, tray_vmax_loaded=0.0, left_unloaded=None, + on_in_loading=set()) + + def monitor_step(self): + mon = self.mon + if mon is None: + return + n = self.sk.n_steps + st, touch = self.predicates() + for k in touch: + mon["last_touch"][k] = n + v = self._tray_speed() + if v > 0.01: + mon["last_tray_move"] = n + if self.tray_on_sill(): + mon["last_sill"] = n + if all(mon["stable"][b] for b in BOTTLES): + mon["tray_vmax_loaded"] = max(mon["tray_vmax_loaded"], v) + for k, val in st.items(): + if val == mon["stable"][k]: + mon["cnt"][k] = 0 + continue + mon["cnt"][k] += 1 + if mon["cnt"][k] < DEBOUNCE: + continue + mon["stable"][k] = val + mon["cnt"][k] = 0 + step = n - DEBOUNCE + 1 + if val: + ev = "restored" if k in mon["lost"] else "achieved" + mon["ever"].add(k) + mon["events"].append(dict(step=step, pred=k, ev=ev)) + else: + mon["lost"].add(k) + e = dict(step=step, pred=k, ev="lost") + if k == "tray_in_loading" and mon["order_step"] is None and mon["left_unloaded"] is None: + mon["left_unloaded"] = step # the tray left the loading area before it was loaded + if k in BOTTLES: + j = BOTTLES.index(k) + moving = n - mon["last_tray_move"] <= 30 + # tray motion first: a bottle toppled by the move often falls against the moving hand + e["cause"] = ("threshold" if moving and n - mon["last_sill"] <= 40 else + "tray_moving" if moving else + "robot" if n - mon["last_touch"][j] <= 20 else "other") + # a bottle taken off (or knocked off by the robot) while the tray is still in the loading area: + # the tray is no longer loaded -> the order latch has to be earned again (unload / reload trick) + if (e["cause"] not in ("threshold", "tray_moving") and mon["stable"]["tray_in_loading"] + and mon["order_step"] is not None): + mon["order_step"] = None + mon["lost"].add("loaded_in_loading_area") + mon["events"].append(e) + e = dict(step=step, pred="loaded_in_loading_area", ev="lost") + mon["events"].append(e) + if mon["stable"]["tray_in_loading"]: + mon["on_in_loading"] |= {b for b in BOTTLES if mon["stable"][b]} + if mon["order_step"] is None and mon["stable"]["tray_in_loading"] and all(mon["stable"][b] for b in BOTTLES): + mon["order_step"] = n + mon["events"].append(dict(step=n, pred="loaded_in_loading_area", + ev="restored" if "loaded_in_loading_area" in mon["lost"] else "achieved")) + + # ------------------------------------------------------------ outcome / F2 + def _static(self): + d = self.env.sim.data + for nm in BOTTLES + (TRAY,): + da = self._dof[nm] + if np.linalg.norm(d.qvel[da:da + 3]) > 0.01 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.15: + return False + return True + + def _where(self, b, bs): + """robot-centric description of where a bottle is (relative to the tray)""" + if bs["on_tray"]: + return "on the tray" + tp, R = self.tray_pose() + lx, ly = R[:2, :2].T @ (bs["pos"][:2] - tp[:2]) + if abs(lx) <= PLATE[0] and abs(ly) <= PLATE[1]: + return "on the tray" + if abs(lx) <= PLATE[0] + 0.04 and abs(ly) <= PLATE[1] + 0.04: + return "partly on the tray" + v = R[:2, 0] * np.sign(lx) if abs(lx) - PLATE[0] >= abs(ly) - PLATE[1] else R[:2, 1] * np.sign(ly) + side = {"forward": "in front of", "back": "behind", "left": "to the left of", + "right": "to the right of"}[self._word(v)] + return f"on the table, {side} the tray" + + @staticmethod + def _names(bs): + cols = [COLOR_OF[b] for b in bs] + if len(cols) == 1: + return f"the {cols[0]} bottle" + return "the " + ", the ".join(cols[:-1]) + f" and the {cols[-1]} bottles" + + def outcome(self, inst): + sk = self.sk + sk.hold(30) # let everything settle (keeps the gripper as it is) + mon = self.mon + touch = self.robot_touch() + bst = {b: self.bottle_state(b, k in touch) for k, b in enumerate(BOTTLES)} + delivered = self.tray_inside("deliver_xy") + static = self._static() + order_ok = mon["order_step"] is not None + all_ok = all(s["ok"] for s in bst.values()) + success = bool(order_ok and delivered and all_ok and static) + ev = mon["events"] + stage_preds = set(BOTTLES) | {"tray_in_delivery"} + n_reg = sum(1 for e in ev if e["ev"] == "lost" and e["pred"] in stage_preds) + n_res = sum(1 for e in ev if e["ev"] == "restored" and e["pred"] in stage_preds) + fell_moving = sorted({e["pred"] for e in ev if e["ev"] == "lost" and e.get("cause") in ("threshold", + "tray_moving")}) + fell_sill = sorted({e["pred"] for e in ev if e["ev"] == "lost" and e.get("cause") == "threshold"}) + fallen = [b for b in BOTTLES if not bst[b]["upright"]] + off = [b for b in BOTTLES if bst[b]["upright"] and not bst[b]["on_tray"]] + held = [b for b in BOTTLES if bst[b]["upright"] and bst[b]["on_tray"] and bst[b]["touched"]] + # failure code = the first unmet requirement, in task order: loading -> order -> bottles -> delivery -> rest + if not order_ok: + failure = "order" if mon["left_unloaded"] is not None else "not_loaded" + elif fallen: + failure = "bottle_fallen" + elif off: + failure = "bottle_off_tray" + elif not delivered: + failure = "not_delivered" + elif held: + failure = "held" + elif not static: + failure = "not_static" + else: + failure = None + # F2 text (robot-centric words, no coordinates); the first sentence names the failure + parts = [] + if failure == "not_loaded": + missing = [b for b in BOTTLES if b not in mon["on_in_loading"]] + parts.append(f"Loading was not completed: {self._names(missing)} never stood on the tray while it was in " + f"the yellow loading area." if missing else + "Loading was not completed: the three bottles never stood on the tray at the same time while " + "it was in the yellow loading area.") + elif failure == "order": + parts.append("The tray left the yellow loading area before all three bottles stood on it (load all three " + "first, then move the loaded tray).") + bottle_txt = [] + for b in BOTTLES: + s, col = bst[b], COLOR_OF[b] + if s["ok"]: + bottle_txt.append(f"The {col} bottle stands upright on the tray.") + elif not s["upright"]: + bottle_txt.append(f"The {col} bottle has fallen over and lies {self._where(b, s)}.") + elif not s["on_tray"]: + bottle_txt.append(f"The {col} bottle stands upright {self._where(b, s)}, not on the tray.") + else: + bottle_txt.append(f"The {col} bottle stands on the tray but the gripper is still touching it.") + if delivered: + tray_txt = "The tray is completely inside the purple delivery area." + else: + ex = self.area_excess("deliver_xy") + out = [f"{max(100 * v, 0.1):.1f} cm beyond its {k} edge" for k, v in ex.items() if v > 0] + tray_txt = "The tray is not completely inside the purple delivery area: it sticks out " + \ + " and ".join(out) + "." + if failure in ("not_delivered",): + parts += [tray_txt] + bottle_txt + else: + parts += bottle_txt + [tray_txt] + if fell_moving: + how = " while the tray crossed the threshold strip" if fell_sill == fell_moving else \ + " while the tray was moving" + txt = self._names(fell_moving) + parts.append(txt[0].upper() + txt[1:] + f" fell over{how}.") + if failure == "not_static": + parts.append("Something was still moving at the end.") + return dict(success=success, failure=failure, + stages={**{COLOR_OF[b]: bool(bst[b]["ok"]) for b in BOTTLES}, "tray_in_delivery": bool(delivered), + "loaded_in_loading_area": bool(order_ok), "static": bool(static)}, + events=list(ev), n_regressions=int(n_reg), n_restored=int(n_res), + order_step=mon["order_step"], left_loading_unloaded=mon["left_unloaded"], + tray_vmax_loaded=round(mon["tray_vmax_loaded"], 3), + fell_while_moving=[COLOR_OF[b] for b in fell_moving], + fell_at_threshold=[COLOR_OF[b] for b in fell_sill], detail=" ".join(parts)) + + # ------------------------------------------------------------ scripted primitives (move_to + gripper only) + def _slot_world(self, j): + tp, R = self.tray_pose() + return tp[:2] + R[:2, :2] @ np.array([SLOT_LX, SLOT_LY[j]]) + + @staticmethod + def _yaw_window(a): + """the gripper-symmetric equivalent of yaw `a` in [-0.5, pi - 0.5) (keeps the last wrist joint off its limit)""" + return float((a + 0.5) % np.pi - 0.5) + + def tray_yaw(self): + return _yaw_of(self.tray_pose()[1]) + + def transit(self, xy, z, yaw=None, z_safe=SAFE_Z): + """up to z_safe (if lower), across, then down to z""" + sk = self.sk + e = sk.eef_pos() + if e[2] < z_safe - 0.01: + sk.move_to([e[0], e[1], z_safe], speed=0.3) + sk.move_to([xy[0], xy[1], z_safe], yaw=None if yaw is None else self._yaw_window(yaw), wrap_yaw=False) + sk.move_to([xy[0], xy[1], z], tol=0.003, max_steps=200) + + def _travel_dir(self): + tp, R = self.tray_pose() + u = R[:2, 0] / np.linalg.norm(R[:2, 0]) + foot = tp[:2] + R[:2, :2] @ np.array([FOOT_DX, 0.0]) + return tp, R, u, float((np.asarray(self.inst["deliver_xy"]) - foot) @ u) + + def push_tray(self, speed, gap=0.03, segments=1, z=PUSH_Z, yaw=None, approach=None): + """the pilot agents' move: closed gripper `gap` behind the handle's cross bar (hand's long side along the bar), + push along the travel direction until the footprint centre is level with the delivery area's centre; + `segments` > 1 stops in between; `approach` (m/s): first creep up to the bar at that speed, stop, then push""" + sk = self.sk + tp, R, u, dist = self._travel_dir() + back = tp[:2] + R[:2, :2] @ np.array([BACK_X, 0.0]) + if yaw is None: # yaw 0 = fingers closing along world y; this yaw puts the hand's long side across u + yaw = float(np.arctan2(u[1], u[0])) + s0 = back - u * (0.012 + gap) # the closed fingers are ~2.4 cm thick along the push + sk.set_gripper(True, steps=8) + self.transit(s0, z, yaw=yaw) + if approach: + s0 = back - u * 0.010 # just touching + sk.move_to([s0[0], s0[1], z], speed=approach, tol=0.003, max_steps=int(gap / approach / 0.05) + 40) + sk.hold(6) + gap = 0.0 + total = gap + dist + for k in range(segments): + e = s0 + u * total * (k + 1) / segments + sk.move_to([e[0], e[1], z], speed=speed, tol=0.004, + max_steps=int(total / segments / speed / 0.05) + 60 if speed else 250) + sk.hold(6) + e = sk.eef_pos()[:2] - u * 0.03 + sk.move_to([e[0], e[1], z], speed=0.1) + sk.move_to([e[0], e[1], z + 0.15], speed=0.25) + + def drag_tray(self, speed, z=DRAG_Z, cross=False): + """the careful move: grasp the handle and move the tray with it (the hand keeps the trailing edge down on the + sill). Default: the stem, fingers closing across its 3 cm width (hand's long side along the tray's long side); + cross=True: the cross bar, fingers closing across its 2.5 cm depth (hand's long side along the travel).""" + sk = self.sk + tp, R, u, dist = self._travel_dir() + lx = -PLATE[0] - 2 * STEM[0] - CROSS[0] if cross else -PLATE[0] - STEM[0] + c = tp[:2] + R[:2, :2] @ np.array([lx, 0.0]) + yaw = float(np.arctan2(u[1], u[0])) + (np.pi / 2 if cross else 0.0) + sk.set_gripper(False, steps=8) + self.transit(c, z, yaw=yaw) + sk.set_gripper(True, steps=15) + e = c + u * dist + sk.move_to([e[0], e[1], z], speed=speed, tol=0.004, + max_steps=int(dist / speed / 0.05) + 80 if speed else 250) + sk.hold(6) + sk.set_gripper(False, steps=12) + e = sk.eef_pos() + sk.move_to([e[0], e[1], e[2] + 0.15], speed=0.25) + + def pick_upright(self, b, jitter=None, yaw=0.0): + """grasp the neck of a standing bottle from above (the palm stays above the bottle's top)""" + sk = self.sk + p = envs.obj_pos(self.env, b) + top = envs.obj_max_z(self.env, b) + xy = p[:2] + (np.zeros(2) if jitter is None else jitter) + sk.set_gripper(False, steps=8) + self.transit(xy, top - GRASP_TOP, yaw) + sk.set_gripper(True, steps=15) + sk.move_to([xy[0], xy[1], SAFE_Z_HELD], speed=0.25) + return sk.eef_pos()[2] - envs.obj_min_z(self.env, b) # grasp height actually held + + def place_at(self, b, xy, held_h, release=0.006): + sk = self.sk + self.transit(xy, PLATE_TOP + release + held_h + 0.03, z_safe=SAFE_Z_HELD) + sk.hold(10) # let a hanging bottle stop swinging + sk.move_to([xy[0], xy[1], PLATE_TOP + release + held_h], speed=0.08, tol=0.003, max_steps=150) + sk.hold(4) + sk.set_gripper(False, steps=12) + sk.move_to([xy[0], xy[1], SAFE_Z], speed=0.25) + + def load_all(self, rng=None): + """every bottle goes to the tray slot on the same side as its start position (a carried bottle never passes + over a standing one); the hand's long side across the row. With `rng`: +-5 mm on every grasp / placement.""" + tp, R = self.tray_pose() + ay = R[:2, 1] + yaw = self.tray_yaw() - np.pi / 2 + by_y = sorted(BOTTLES, key=lambda b: float(np.asarray(self.inst["bottle_start"][b][:2]) @ ay)) + for j, b in enumerate(by_y): + jg, jp = (None, None) if rng is None else (rng.uniform(-0.005, 0.005, 2), rng.uniform(-0.005, 0.005, 2)) + h = self.pick_upright(b, jitter=jg, yaw=yaw) + self.place_at(b, self._slot_world(j) + (0 if jp is None else jp), h) + + def free_slot(self, exclude): + """a tray slot at least 7 cm from every other bottle (standing or lying); among those the one farthest from the + robot; else the emptiest slot""" + tp, R = self.tray_pose() + others = [R[:2, :2].T @ (self.bottle_state(o)["pos"][:2] - tp[:2]) for o in BOTTLES if o not in exclude] + cand = [] + for j, ly in enumerate(SLOT_LY): + dmin = min([np.linalg.norm(np.array([SLOT_LX, ly]) - o) for o in others] + [1.0]) + cand.append((dmin >= 0.07, float(self._slot_world(j)[0]) if dmin >= 0.07 else dmin, j)) + return self._slot_world(max(cand)[2]) + + def restand(self, b): + """a fallen bottle: grasp its neck across (fingers closing across the neck), lift -- it swings down and hangs + from the neck -- and set it down on a free slot. A bottle standing off the tray: pick it up by the neck.""" + sk = self.sk + st = self.bottle_state(b) + if st["upright"]: + h = self.pick_upright(b, yaw=self.tray_yaw() - np.pi / 2) + self.place_at(b, self.free_slot({b}), h) + return + for tries in range(2): + st = self.bottle_state(b) + R = self.env.sim.data.body_xmat[self.bid[b]].reshape(3, 3) + ax = R[:, 2] # bottle axis (bottom -> neck) + u = ax[:2] / max(np.linalg.norm(ax[:2]), 1e-6) + neck = st["pos"] + ax * (BH - GRASP_TOP) + yaw = float(np.arctan2(u[1], u[0])) # fingers close across the neck + sk.set_gripper(False, steps=8) + self.transit(neck[:2], max(neck[2], envs.TABLE_Z + 0.008), yaw) + sk.set_gripper(True, steps=15) + if sk.holding(b) or tries: + break + # a finger landed on the tray's edge next to the neck: slide the bottle 5 cm away from the tray, retry + tp = self.tray_pose()[0] + v = st["pos"][:2] - tp[:2] + v = v / max(np.linalg.norm(v), 1e-6) + sk.set_gripper(False, steps=8) + sk.move_to(sk.eef_pos() + [0.0, 0.0, 0.05], speed=0.1) + self.push_point(st["pos"][:2] - v * 0.015, v, 0.065, speed=0.05, z=PLATE_TOP + 0.012) + sk.move_to([neck[0], neck[1], SAFE_Z_HELD], speed=0.15) + sk.hold(20) + held = sk.eef_pos()[2] - envs.obj_min_z(self.env, b) + self.place_at(b, self.free_slot({b}), held) + + def push_point(self, p, u, dist, speed=0.03, z=None): + """closed gripper: from 3 cm behind point `p` (direction `u`) push `dist` metres along u, back off, lift""" + sk = self.sk + z = PUSH_Z if z is None else z + s0 = np.asarray(p) - u * 0.03 + sk.set_gripper(True, steps=8) + self.transit(s0, z, yaw=float(np.arctan2(u[1], u[0]))) + e = s0 + u * (0.018 + dist) + sk.move_to([e[0], e[1], z], speed=speed, tol=0.003, max_steps=600) + sk.hold(4) + e = sk.eef_pos()[:2] - u * 0.03 + sk.move_to([e[0], e[1], z], speed=0.1) + sk.move_to([e[0], e[1], SAFE_Z], speed=0.25) + + def fix_tray(self, speed=V_CAREFUL): + """straighten the tray by slowly pushing the trailing corner that lags behind, then grasp the handle's stem + and move the tray, without turning it, until its footprint is centred in the delivery area""" + sk = self.sk + y1 = self.inst["area_yaw"] + u1 = _rotz2(y1)[:, 0] + for _ in range(3): + err = (self.tray_yaw() - y1 + np.pi) % (2 * np.pi) - np.pi + if abs(err) < np.radians(3): + break + tp, R = self.tray_pose() + corners = [tp[:2] + R[:2, :2] @ np.array([-PLATE[0], e * (PLATE[1] - 0.02)]) for e in (1.0, -1.0)] + a = [float((c - tp[:2]) @ u1) for c in corners] + k = int(np.argmin(a)) + self.push_point(corners[k], u1, 0.6 * (max(a) - min(a)), speed=speed) + tp, R = self.tray_pose() + h0 = tp[:2] + R[:2, :2] @ np.array([-PLATE[0] - STEM[0], 0.0]) + foot = tp[:2] + R[:2, :2] @ np.array([FOOT_DX, 0.0]) + h1 = h0 + (np.asarray(self.inst["deliver_xy"]) - foot) + d = float(np.linalg.norm(h1 - h0)) + if d < 0.004: + return + sk.set_gripper(False, steps=8) + self.transit(h0, DRAG_Z, yaw=self.tray_yaw()) # fingers close across the stem's width + sk.set_gripper(True, steps=15) + sk.move_to([h1[0], h1[1], DRAG_Z], speed=speed, tol=0.003, max_steps=int(d / speed / 0.05) + 80) + sk.hold(5) + sk.set_gripper(False, steps=12) + e = sk.eef_pos() + sk.move_to([e[0], e[1], SAFE_Z], speed=0.2) + + def check_and_restore(self, rounds=3): + """the final check: bottles not upright on the tray -> stand them up on a free slot (farthest from the robot + first); then, if the tray is not completely in the delivery area, move it there slowly by the handle""" + for _ in range(rounds): + bad = [b for b in BOTTLES if not self.bottle_state(b)["ok"]] + if not bad and self.tray_inside("deliver_xy"): + return + for b in sorted(bad, key=lambda o: -float(self.bottle_state(o)["pos"][0])): + self.restand(b) + self.sk.hold(10) + if not self.tray_inside("deliver_xy"): + self.fix_tray() + self.sk.hold(10) + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("seed")) if params.get("jitter") else None + self.load_all(rng) + if params.get("mode", "push") == "drag": + self.drag_tray(params["speed"]) + else: + self.push_tray(params["speed"], gap=params.get("gap", 0.03), segments=params.get("segments", 1)) + if params.get("check"): + self.check_and_restore() + + def default_params(self, inst): + """naive = the pilot agents' style: load all three, push the handle with the closed gripper at ~4.5 cm/s""" + return dict(speed=V_NAIVE, mode="push", check=False) + + def oracle_params(self, inst): + return dict(speed=V_CAREFUL, mode="drag", check=True) + + def adapt_params(self, inst, history): + return dict(speed=V_CAREFUL, mode="drag", check=True) + + def blind_params(self, inst, attempt, rng): + return dict(speed=float(rng.uniform(0.03, 0.06)), mode="push", segments=int(rng.integers(1, 3)), + check=False, jitter=True, seed=int(rng.integers(1 << 30))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """cross protocol; adaptive = naive + check-and-restore in attempt 1, careful (drag by the handle) + check + afterwards""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history diff --git a/leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/agent/harness.py b/leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/agent/harness.py new file mode 100644 index 0000000000000000000000000000000000000000..323410f477f3320769635cf01dd368be716d9421 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/agent/harness.py @@ -0,0 +1,300 @@ +"""Protocol controller: runs a backend on task instances, attempt by attempt. + + cross protocol : reset to the same instance (same layout + hidden variables) before every attempt + within protocol: one continuous episode; each `done` call closes a segment ("attempt") that is checked; + the agent continues from the current state if it failed and budget remains +Both protocols pack finished attempts the same way (keyframes <= 4, action summary, feedback F0/F1/F2) and +show them according to the memory mode (none / full / last / mismatched). +""" +import time +from dataclasses import asdict, dataclass, field + +from .context import (FEEDBACK_LEVELS, MEMORY_MODES, AttemptRecord, Conversation, PromptBuilder, StepRecord, + pick_keyframes, select_history, summarize_actions) +from .cost import call_cost, estimate_request_tokens +from .metrics import run_summary +from .backends.base import AttemptInfo, RunInfo + + +@dataclass +class HarnessConfig: + memory: str = "full" + feedback: str = "F2" + k: int = None # attempts (cross) / done calls (within); default task.max_attempts + image_res: int = 512 + keyframe_res: int = None # default = image_res + n_keyframes: int = 4 + cams: tuple = ("agentview", "wrist") + auto_obs: bool = True # send new images after every action tool + max_steps: int = 30 # tool calls per attempt + max_no_tool: int = 3 # consecutive replies without a tool call before the attempt is ended + privileged_locate: bool = False + grasp_report: str = "bool" # "bool" | "name" | "none" + instruction: str = "direct" # "direct" | "indirect" + early_stop: str = "auto" # "auto" (stop at first success unless F0), "yes", "no" + settle_within: int = 20 # control steps held still before checking a within-protocol segment + jpeg_quality: int = 90 + save_images: bool = True + model_for_cost: str = "gpt-6-astra" + extra: dict = field(default_factory=dict) + + def validate(self): + assert self.memory in MEMORY_MODES, self.memory + assert self.feedback in FEEDBACK_LEVELS, self.feedback + assert self.grasp_report in ("bool", "name", "none") + assert self.instruction in ("direct", "indirect") + assert self.early_stop in ("auto", "yes", "no") + assert 1 <= self.n_keyframes <= 4 or self.n_keyframes == 0 + + +def clean_inst(inst): + return {k: v for k, v in inst.items() if not str(k).startswith("_")} + + +class AgentHarness: + def __init__(self, task, backend, cfg: HarnessConfig, logger, payload_probe=None, executor_factory=None, + cam_axes=None): + cfg.validate() + self.task, self.backend, self.cfg, self.log = task, backend, cfg, logger + self.protocol = getattr(task, "protocol", "cross") + self.k = cfg.k or task.max_attempts + self.payload_probe = payload_probe # optional OpenAIResponsesBackend used only to size requests (dry run) + self.executor_factory = executor_factory # tests: build a fake executor instead of ToolExecutor + self._cam_axes = cam_axes + + # ------------------------------------------------------------------ helpers + def instruction(self, inst): + hook = getattr(self.task, "agent_instruction", None) + if hook is not None: + return hook(inst, self.cfg.instruction) + if self.cfg.instruction == "indirect" and getattr(self.task, "instruction_indirect", ""): + return self.task.instruction_indirect + return self.task.instruction + + def feedback(self, inst, out, level): + import inspect + fn = self.task.feedback + if "indirect" in inspect.signature(fn).parameters: # tasks that phrase feedback per instruction variant + return fn(inst, out, level, indirect=self.cfg.instruction == "indirect") + return fn(inst, out, level) + + def early_stop(self): + if self.cfg.early_stop == "auto": + return self.cfg.feedback != "F0" + return self.cfg.early_stop == "yes" + + def terminal(self, out): + hook = getattr(self.task, "is_terminal", None) + if hook is not None: + return bool(hook(out)) + return bool(out.get("terminal") or out.get("overshoot")) + + def _executor(self, inst): + if self.executor_factory is not None: + return self.executor_factory(self, inst) + from .tools import ToolExecutor + return ToolExecutor(self.task, inst, image_res=self.cfg.image_res, cams=self.cfg.cams, + privileged_locate=self.cfg.privileged_locate, grasp_report=self.cfg.grasp_report, + jpeg_quality=self.cfg.jpeg_quality, image_sink=self._sink) + + def _sink(self, ref): + self._img_counter += 1 + rel = f"seed{self._seed}/a{self._attempt}_s{self._step:02d}_{self._img_counter:03d}_{ref.camera}.jpg" + return self.log.save_image(ref, rel) + + def _keyframe(self, ref): + """Separate (possibly smaller) copy of an agentview frame for the history.""" + from .images import ImageRef + kres = self.cfg.keyframe_res or self.cfg.image_res + kf = ImageRef(camera=ref.camera, array=ref.array, label=ref.label) + if kres == self.cfg.image_res: + kf.jpeg, kf.path = ref.jpeg, ref.path + return kf + self._img_counter += 1 + rel = f"seed{self._seed}/a{self._attempt}_key_{self._img_counter:03d}_{ref.camera}.jpg" + return self.log.save_image(kf, rel, res=kres) + + def prompts(self, executor): + if self._cam_axes is None: + from . import camera as C + self._cam_axes = {c: C.describe_axes(self.task.env, c, self.cfg.image_res) for c in C.CAMERAS} + names = getattr(self.task, "agent_object_names", None) or list(self.task.env.objects_dict) + return PromptBuilder(self.task, self.protocol, self.k, self.cfg.memory, self.cfg.feedback, self.cfg.image_res, + self._cam_axes, privileged_locate=self.cfg.privileged_locate, object_names=names, + grasp_report=self.cfg.grasp_report, cams=self.cfg.cams) + + # ------------------------------------------------------------------ run + def run_instance(self, seed, donor=None): + """donor: AttemptRecords of another instance (memory=mismatched). Returns (summary, records).""" + task, cfg = self.task, self.cfg + inst = task.sample_instance(seed) + self._seed, self._attempt, self._step, self._img_counter = seed, 0, 0, 0 + self._llm_calls = [] + t_run = time.time() + sim_wall = 0.0 + info = RunInfo(task=task, inst=inst, seed=seed, k=self.k, protocol=self.protocol, feedback=cfg.feedback, + memory=cfg.memory) + self.backend.begin_run(info) + self.log.event("run_start", seed=seed, inst=clean_inst(inst), task=task.name, protocol=self.protocol, k=self.k, + memory=cfg.memory, feedback=cfg.feedback, donor_seed=donor[0].seed if donor else None) + records, executor, status = [], None, "ok" + for a in range(1, self.k + 1): + self._attempt, self._step = a, 0 + if self.protocol == "cross" or executor is None: + t0 = time.time() + task.reset_instance(inst) + executor = self._executor(inst) + sim_wall += time.time() - t0 + visible = select_history(cfg.memory, records, donor) + rec, attempt_sim = self._attempt_loop(inst, seed, a, visible, executor, + continuing=self.protocol == "within" and a > 1) + sim_wall += attempt_sim + records.append(rec) + if rec.ended_by == "backend_error": + status = "error" + break + if rec.success and self.early_stop(): + break + if self.protocol == "within" and (rec.success or self.terminal(rec.outcome)): + break + self.backend.end_run() + summ = run_summary(seed, records, self.k, status=status, llm_calls=self._llm_calls, + extra=dict(sim_wall_s=round(sim_wall, 2), wall_s=round(time.time() - t_run, 2), + donor_seed=donor[0].seed if donor else None)) + self.log.event("run_end", **summ) + summ["_llm_calls"] = self._llm_calls + return summ, records + + def _attempt_loop(self, inst, seed, a, visible, ex, continuing): + cfg, task, backend = self.cfg, self.task, self.backend + P = self.prompts(ex) + tools = self.tool_specs() + conv = Conversation(P.system_prompt()) + backend.begin_attempt(AttemptInfo(attempt=a, history=visible, continuing=continuing)) + sim_t = 0.0 + t0 = time.time() + obs0 = ex.observe(label="start") + sim_t += time.time() - t0 + conv.add_user(P.history_parts(self.instruction(inst), visible), live=False) + conv.add_user(P.current_parts(a, obs0, ex.proprio(), continuing), live=True) + steps, diagnosis, done_reason, ended_by = [], None, None, None + n_calls, no_tool = 0, 0 + while ended_by is None: + if len(steps) >= cfg.max_steps: + ended_by = "step_budget" + break + try: + resp = backend.act(conv, tools) + except Exception as e: # API failure after retries, crashed scripted policy, ... + self.log.event("llm_error", seed=seed, attempt=a, call=n_calls + 1, error=repr(e)[:4000]) + ended_by = "backend_error" + break + n_calls += 1 + call_rec = self._log_llm_call(seed, a, n_calls, resp, conv, tools) + self._llm_calls.append(call_rec) + if n_calls == 1 and resp.text: + diagnosis = resp.text + conv.add_assistant(resp.text, resp.tool_calls, raw=resp.raw, backend=backend.name) + if not resp.tool_calls: + no_tool += 1 + if no_tool >= cfg.max_no_tool: + ended_by = "no_tool_call" + break + conv.add_user(P.nudge(), live=True) + continue + no_tool = 0 + acted = None + for tc in resp.tool_calls: + self._step = len(steps) + 1 + res = ex.call(tc.name, tc.raw_arguments or tc.arguments) + sim_t += res.wall_s + conv.add_tool_output(tc.id, tc.name, res.text()) + backend.on_tool_result(tc, res) + st = StepRecord(step=self._step, name=tc.name, args=res.args, report=res.report, ok=res.ok, + wall_s=round(res.wall_s, 3), sim_steps=res.sim_steps) + steps.append(st) + if res.images: + conv.add_user(P.observation_parts(f"Images returned by get_observation (step {self._step})", + res.images, ex.proprio()), live=True) + if tc.name in ("move_to", "open_gripper", "close_gripper", "push") and res.ok: + acted = st + self.log.event("tool_call", seed=seed, attempt=a, step=self._step, call_id=tc.id, name=tc.name, + args=res.args, ok=res.ok, report=res.report, wall_s=round(res.wall_s, 3), + sim_steps=res.sim_steps, images=[i.path for i in res.images]) + if res.ended: + done_reason = res.args.get("reason") + ended_by = "done" + break + if len(steps) >= cfg.max_steps: + break + if ended_by is None and acted is not None: + t1 = time.time() + if cfg.auto_obs: + obs = ex.observe(label=f"step{acted.step}") + conv.add_user(P.step_observation(acted.step, acted.name, obs, ex.proprio()), live=True) + acted.frame = next((o for o in obs if o.camera == "agentview"), obs[0]) + else: # still keep an agentview frame for the history keyframes / logs + from .images import ImageRef + acted.frame = self._sink(ImageRef(camera="agentview", array=ex.render("agentview"), + label=f"step{acted.step}")) + sim_t += time.time() - t1 + self.log.event("observation", seed=seed, attempt=a, step=acted.step, + images=[acted.frame.path] if not cfg.auto_obs else [o.path for o in obs], + proprio=ex.proprio()) + meta = backend.end_attempt() or {} + # ------------------------------------------------------------ outcome + packing + t1 = time.time() + home = getattr(task, "go_home", None) # task-defined end-of-attempt motion (e.g. L6: arm out of view) + if home is not None and ended_by != "backend_error": + home() + if self.protocol == "within" and cfg.settle_within: + ex.sk.hold(cfg.settle_within) + out = task.outcome(inst) + from .images import ImageRef + self._step = 99 + final = self._sink(ImageRef(camera="agentview", array=ex.render("agentview", cfg.keyframe_res or cfg.image_res), + label="end")) + sim_t += time.time() - t1 + fb = self.feedback(inst, out, cfg.feedback) + fb_full = self.feedback(inst, out, "F2") + init_frame = next((o for o in obs0 if o.camera == "agentview"), None) + for s in steps: + if s.frame is not None and (cfg.keyframe_res or cfg.image_res) != cfg.image_res: + s.frame = self._keyframe(s.frame) + if init_frame is not None and (cfg.keyframe_res or cfg.image_res) != cfg.image_res: + init_frame = self._keyframe(init_frame) + kfs = pick_keyframes(steps, init_frame, final, cfg.n_keyframes) if cfg.n_keyframes else [] + rec = AttemptRecord(seed=seed, attempt=a, steps=steps, keyframes=kfs, outcome=dict(out), + success=bool(out.get("success")), feedback=fb, done_reason=done_reason, diagnosis=diagnosis, + ended_by=ended_by, backend_meta=meta) + calls = [c for c in self._llm_calls if c["attempt"] == a] + self.log.event("attempt_end", seed=seed, attempt=a, success=rec.success, outcome=out, feedback_shown=fb, + feedback_f2=fb_full, ended_by=ended_by, done_reason=done_reason, diagnosis=diagnosis, + n_steps=len(steps), n_llm_calls=len(calls), backend_meta=meta, + history_shown=[(h.seed, h.attempt) for h in visible], + keyframes=[(c, r.path) for c, r in kfs], action_summary=summarize_actions(steps), + llm_latency_s=round(sum(c["latency_s"] for c in calls), 3), sim_wall_s=round(sim_t, 3)) + return rec, sim_t + + def tool_specs(self): + from .tools import tool_specs + names = getattr(self.task, "agent_object_names", None) or list(self.task.env.objects_dict) + return tool_specs(self.cfg.privileged_locate, names, self.cfg.image_res) + + def _log_llm_call(self, seed, a, n, resp, conv, tools): + rec = dict(seed=seed, attempt=a, call=n, latency_s=round(resp.latency_s, 3), usage=resp.usage, + cost_usd=call_cost(resp.usage, self.cfg.model_for_cost) if resp.usage else None, + status=resp.status, error=resp.error, text=resp.text, reasoning_summary=resp.reasoning_summary, + reasoning_summary_status="recorded" if resp.reasoning_summary else "not_returned", + tool_calls=[dict(id=t.id, name=t.name, arguments=t.arguments) for t in resp.tool_calls], + request=resp.request_stats, conv_images=conv.n_images()) + if self.payload_probe is not None: # dry run: size of the request GPT-6 would have received + stats = self.payload_probe.request_stats(self.payload_probe.build_request(conv, tools)) + stats["est_input_tokens"] = estimate_request_tokens(stats, self.cfg.image_res) + rec["dry_run_request"] = stats + self.log.event("llm_call", **rec) + return rec + + +def config_dict(cfg): + return asdict(cfg) diff --git a/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/l4_nest.py b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/l4_nest.py new file mode 100644 index 0000000000000000000000000000000000000000..1176314e28197c49c48a0dcb3c29ba649f2b2780 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/l4_nest.py @@ -0,0 +1,644 @@ +"""L4-C nest_order: nest three cups one inside another; the tallest cup is not the widest. + +Scene: three open round cups (red, green, blue; 1.5 mm walls leaning outwards by TAPER_DEG = 5 deg, like slightly +flared tumblers) stand apart on the table. Each cup has its own bottom width and its own height (re-drawn per +instance, 3.5-10 cm tall). Cups are resized per instance by editing their geoms in sim.model (wall segments + +floor), so one env serves every instance (same technique as l4_fit_container). + +Trap (common sense): "the bigger cup goes outside", and a cup looks big mostly by its height. On (1 - P_AGREE) of +the instances the tallest cup is the middle one by width: it is at least INV_DH = 3.5 cm taller than the widest cup. +Their openings then differ by only 3-9 mm in diameter, and from the wrist camera at its start height the taller +one's opening is closer to the camera and looks about as big (about half the instances: bigger); from the front +camera the taller one looks clearly bigger. The narrowest cup is the shortest, so the very first move of the naive +order (widest cup into the tallest one) already fails, out on the table. + +A variant where the innermost cup was taller than the middle one (and the widest cup the tallest) was dropped +2026-10-08: its failure (middle cup on the rim of the innermost cup, both inside the outer one) looked like a nest +from both cameras -- the same flaw as the 14-deg version. + +What the failure looks like (the point of this version, user review 2026-10-08): which cup fits into which is +decided by the bottoms (same flare for all cups), and the sizes are drawn so that a cup whose bottom is too wide +does not go in at all -- it stays on the other cup's rim or wedges in the opening, its bottom at most STUCK_MAX += 0.5 cm below the rim. So a wrong placement leaves a cup standing on top of another one, its whole body above the +rim: visible in both cameras without any text feedback. A cup that fits goes down to the floor (centring tolerance +>= TOL_MIN = 7.5 mm thanks to the flare); in the right nest the taller, narrower cups stick out of the shorter, +wider ones, but each stands inside the next. + +Prior (naive): tallest cup outermost, then the next tallest. Learner: a cup that ended up on top of another cup +must go outside it; swap that pair. Feedback F1 (default) says only failed / succeeded; F2 (ablation) describes +which cup stands in / on which, in words, with no sizes or positions. + +Only move_to / open / close are needed: grasp a cup across its upper wall, carry it over the other cup, release it +just above that cup's rim. +""" +import itertools + +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, _wrap, register_generated +from ..skills import _rot_err +from ..task_base import LFFTask, register_task + +N_SEG = 20 # wall segments per cup (regular polygon) +TAN_SEG = float(np.tan(np.pi / N_SEG)) +COS_SEG = float(np.cos(np.pi / N_SEG)) +TAPER_DEG = 5.0 # wall lean (from vertical) +TAPER = float(np.radians(TAPER_DEG)) +TT = float(np.tan(TAPER)) +WALL_T = 0.0015 # wall thickness (normal to the wall) +WALL_TH = WALL_T / float(np.cos(TAPER)) # horizontal wall thickness +FLOOR_T = 0.003 +Z0 = 0.0003 # walls start this far above the cup's underside (the floor disc carries the cup) +H_RANGE = (0.035, 0.100) # total cup height +RB_WIDE = (0.023, 0.030) # bottom outer apothem of the cup with the widest bottom +STEP = (0.0055, 0.0075) # bottom apothem difference between neighbours in the true order +RIM_MAX = 0.033 # outer apothem of the widest opening (gripper opens 7.9 cm) +CLEAR_MIN = 0.003 # radial gap (worst case) of a fitting cup standing on the other cup's floor +TOL_MIN = 0.0075 # a fitting cup goes in if its bottom lands within this of the other cup's axis +STUCK_MAX = 0.005 # a too-wide cup's bottom stops no deeper than this below the other cup's rim (5-deg walls +# self-lock: a cup pressed 1.2 cm into the opening wedged, and the narrow cup tipped over with it) +INV_DH = 0.035 # in the swapped pair the narrower cup is taller by at least this +KEEP_DH = 0.010 # in an unswapped pair the wider cup is taller by at least this +P_AGREE = 0.15 # share of instances whose height order is the right nesting order +SEAT_H = 0.010 # "standing on the floor": bottom less than this above the other cup's floor +SEAT_TILT = 15.0 # deg; a tall cup in a short, wider one can lean a little +WRIST_CAM_H = 0.367 # wrist camera height above the table at the start pose (measured 2026-10-08) +COLORS = {"red": (0.78, 0.22, 0.20, 1.0), "green": (0.28, 0.62, 0.32, 1.0), "blue": (0.22, 0.42, 0.80, 1.0)} +CUP_NAMES = ("cup_1", "cup_2", "cup_3") +DENSITY = 600.0 +# execution +GRASP_BELOW_RIM = 0.012 # gripper site this far below the rim when grasping +Z_CARRY = envs.TABLE_Z + 0.24 +DROP = 0.006 # held cup's bottom this far above the receiving rim at release +FINGER_CLEAR = 0.015 # gripper site at least this far above any rim around the target at release: fingers opened +# inside a taller outer cup press on its wall and carry it away on the way up (seed 1009, 2026-10-08) +PARK = (-0.45, 0.0, envs.TABLE_Z + 0.35) +H_NOISE = 0.03 # relative noise of the blind policy's height judgement + + +# ---------------------------------------------------------------- cup geometry +def _quat_mul(a, b): + w1, x1, y1, z1 = a + w2, x2, y2, z2 = b + return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, + w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2]) + + +def _seg_quat(phi): + """segment frame: about z by phi, then tilted about its own y (tangential) axis by TAPER, so that its local z + (along the wall) leans outwards and its local x is the wall's outward normal""" + qz = np.array([np.cos(phi / 2), 0.0, 0.0, np.sin(phi / 2)]) + qy = np.array([np.cos(TAPER / 2), 0.0, np.sin(TAPER / 2), 0.0]) + return _quat_mul(qz, qy) + + +def seg_half_len(rb, H): + """tangential half length of a wall segment: one polygon side at the rim (+0.2 mm overlap)""" + return (rb + TT * H) * TAN_SEG + 0.0002 + + +def rim_radius(rb, H): + """outer apothem of the opening""" + return rb + TT * H + + +def inner_radius(rb, z): + """inner apothem at height z above the cup's underside""" + return rb + TT * z - WALL_TH + + +def bottom_reach(rb, H): + """largest horizontal radius of the cup's outside at its bottom (the segment tips stick out a little beyond + the polygon because every segment is as wide as a rim-level polygon side)""" + return float(np.hypot(rb + TT * Z0, seg_half_len(rb, H))) + + +def fit_clearance(rb_in, H_in, rb_out): + """radial clearance (worst case over relative yaw) of cup `in` standing on the floor of cup `out`; + negative = does not go down to the floor. The flare is the same for both cups, so the bottom is the tightest + height.""" + return inner_radius(rb_out, FLOOR_T) - bottom_reach(rb_in, H_in) + + +def centring_tol(rb_in, H_in, rb_out, H_out): + """how far (worst case) cup `in`'s bottom centre may be off cup `out`'s axis when it is lowered in at the rim + and still get inside (the flared wall then guides it down)""" + return inner_radius(rb_out, H_out) - bottom_reach(rb_in, H_in) + + +def stop_height(rb_in, rb_out, H_out): + """height (above cup `out`'s underside) where a too-wide cup `in`, lowered centred, stops: where its bottom + meets the sloping inner wall, or on the rim if that is higher than the cup""" + return min((rb_in - rb_out + WALL_TH) / TT, H_out) + + +def _cup_parts(rb, H): + """[(pos, half size, quat)] of the wall segments in the cup body frame (origin at mid height).""" + zc = (Z0 + H) / 2 + hs = (H - Z0) / (2 * np.cos(TAPER)) + rc = rb + TT * zc - WALL_T / 2 * np.cos(TAPER) + zz = zc + WALL_T / 2 * np.sin(TAPER) - H / 2 + hl = seg_half_len(rb, H) + out = [] + for k in range(N_SEG): + phi = 2 * np.pi * k / N_SEG + out.append(((rc * np.cos(phi), rc * np.sin(phi), zz), (WALL_T / 2, hl, hs), _seg_quat(phi))) + return out + + +def _floor_part(rb, H): + return (0.0, 0.0, -H / 2 + FLOOR_T / 2), (rb - 0.0003, FLOOR_T / 2, 0.0), np.array([1.0, 0.0, 0.0, 0.0]) + + +def cup_xml(model_name, rgba): + """Open flared cup: N_SEG tilted wall boxes + a cylinder floor (sizes are overwritten per instance).""" + geoms = [] + rb, H = RB_WIDE[1], H_RANGE[1] + for k, (p, s, q) in enumerate(_cup_parts(rb, H)): + geoms.append(f' ') + geoms.append(f' ') + fp, fs, _ = _floor_part(rb, H) + geoms.append(f' ') + geoms.append(f' ') + return _wrap(model_name, "\n".join(geoms), H / 2, rim_radius(rb, H) / COS_SEG) + + +def disable_midphase(env): + """The cups are resized at run time by editing geom pos / size in sim.model, but MuJoCo's per-body bounding + volume hierarchy (bvh_aabb, used by the collision mid-phase) is computed once at compile time for the registered + maximum size. A resized wall that lies outside its compiled leaf box is silently skipped: the gripper fingers + passed straight through the walls of the smaller cups (found 2026-10-07). Without the mid-phase MuJoCo tests all + geom pairs of two nearby bodies (still filtered by the run-time geom_rbound set in _reshape_cup).""" + import mujoco + m = env.sim.model._model + m.opt.disableflags |= int(mujoco.mjtDisableBit.mjDSBL_MIDPHASE) + + +def kendall(a, b): + """number of pairs ordered differently in the two orders""" + pa, pb = {c: k for k, c in enumerate(a)}, {c: k for k, c in enumerate(b)} + return sum((pa[x] < pa[y]) != (pb[x] < pb[y]) for x, y in itertools.combinations(a, 2)) + + +@register_task +class NestOrder(LFFTask): + name = "l4_nest_order" + level = "L4" + category = "geometry_inference" + capabilities = ("Perceive", "Reason", "Plan") + instruction = "Nest the red, green and blue cups one inside another." + instruction_indirect = "Put the three cups one inside another, like a set of nesting cups." + + # ------------------------------------------------------------ scene + def make_bddl(self): + cats = [register_generated(f"LffNestCup{c.capitalize()}", cup_xml(f"lff_nest_cup_{c}", COLORS[c])) + for c in COLORS] + regions = [(-0.25, -0.15), (-0.05, 0.0), (-0.25, 0.15)] + objs = [(n, cat, f"{n}_region", (x - 0.01, y - 0.01, x + 0.01, y + 0.01)) + for n, cat, (x, y) in zip(CUP_NAMES, cats, regions)] + return write_bddl(self.name, self.instruction, objs) + + @staticmethod + def _heights_ok(case, h): + """h[s] = height of the cup with the s-th narrowest bottom (0 = innermost in the true nest)""" + if case == "agree": # taller = wider: the height order is the nesting order + return h[2] >= h[1] + KEEP_DH and h[1] >= h[0] + KEEP_DH + if case == "swap_wide": # the middle cup is the tallest, the narrowest one the shortest + return h[1] >= h[2] + INV_DH and h[2] >= h[0] + KEEP_DH + raise ValueError(case) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + u = rng.random() + case = "agree" if u < P_AGREE else "swap_wide" + for _ in range(200000): + heights = [float(rng.uniform(*H_RANGE)) for _ in range(3)] # by true size: 0 = narrowest bottom + if not self._heights_ok(case, heights): + continue + rb3 = float(rng.uniform(*RB_WIDE)) + rb2 = rb3 - float(rng.uniform(*STEP)) + rb1 = rb2 - float(rng.uniform(*STEP)) + rbs = [rb1, rb2, rb3] + rims = [rim_radius(rb, h) for rb, h in zip(rbs, heights)] + if max(rims) > RIM_MAX: + continue + ok = True + for p, q in itertools.permutations(range(3), 2): # p into q + if p < q: + ok &= (fit_clearance(rbs[p], heights[p], rbs[q]) >= CLEAR_MIN + and centring_tol(rbs[p], heights[p], rbs[q], heights[q]) >= TOL_MIN) + else: + ok &= heights[q] - stop_height(rbs[p], rbs[q], heights[q]) <= STUCK_MAX + if ok: + break + else: + raise RuntimeError("could not sample cup sizes") + xy = [] + while len(xy) < 3: + xy = [] + for _k in range(3): + for _t in range(200): + p = [float(rng.uniform(-0.27, 0.02)), float(rng.uniform(-0.17, 0.17))] + if all(np.hypot(p[0] - q[0], p[1] - q[1]) >= 0.14 for q in xy): + xy.append(p) + break + # the colour is fixed per object (cup_1 red, cup_2 green, cup_3 blue: one generated class each); shuffle + # which object gets which size / height / position + perm = [int(i) for i in rng.permutation(3)] # perm[size index] = object slot + cups = [None] * 3 + for s in range(3): + cups[perm[s]] = dict(name=CUP_NAMES[perm[s]], color=list(COLORS)[perm[s]], rb=rbs[s], height=heights[s], + rim=rims[s], xy=xy[s], size_rank=s) + order = sorted(range(3), key=lambda j: -cups[j]["rb"]) # outermost first (indices into cups) + naive = sorted(range(3), key=lambda j: -cups[j]["height"]) + assert (naive == order) == (case == "agree"), (seed, case) + by = lambda s: perm[s] # noqa: E731 object index of size rank s + return dict(seed=int(seed), case=case, cups=cups, order=order, naive_order=naive, + bottom_cm=[round(200 * c["rb"], 2) for c in cups], + opening_cm=[round(200 * c["rim"], 2) for c in cups], + height_cm=[round(100 * c["height"], 2) for c in cups], + # relative size of each opening in the wrist camera at its start height (1 = largest) + wrist_apparent=[round(float(v), 3) for v in (lambda a: a / a.max())(np.array( + [c["rim"] / (WRIST_CAM_H - c["height"]) for c in cups]))], + clear_mm=[round(1000 * fit_clearance(rbs[s], heights[s], rbs[s + 1]), 2) for s in range(2)], + tol_mm=[round(1000 * centring_tol(rbs[s], heights[s], rbs[s + 1], heights[s + 1]), 2) + for s in range(2)], + # wrong neighbour pairs: how deep (cm) the wider cup's bottom gets below the narrower cup's rim + stuck_cm={f"{by(s + 1)}in{by(s)}": round(100 * (heights[s] - stop_height( + rbs[s + 1], rbs[s], heights[s])), 2) for s in range(2)}) + + def _reshape_cup(self, name, rb, H): + m = self.env.sim.model + o = self.env.objects_dict[name] + parts = _cup_parts(rb, H) + [_floor_part(rb, H)] + for names in (o.contact_geoms, o.visual_geoms): + assert len(names) == len(parts), (name, len(names)) + for k, n in enumerate(names): + g = m.geom_name2id(n) + pos, size, quat = parts[k] + m.geom_pos[g] = pos + m.geom_size[g] = size + m.geom_quat[g] = quat + if k < N_SEG: + m.geom_rbound[g] = float(np.linalg.norm(size)) + m.geom_aabb[g] = [0, 0, 0, *size] + else: + m.geom_rbound[g] = float(np.hypot(size[0], size[1])) + m.geom_aabb[g] = [0, 0, 0, size[0], size[0], size[1]] + # mass / inertia of the resized cup: conical shell + disc floor + bid = int(m.geom_bodyid[m.geom_name2id(o.contact_geoms[0])]) + slant = (H - Z0) / np.cos(TAPER) + r_mid = rb + TT * (H + Z0) / 2 + wall_m = DENSITY * 2 * np.pi * r_mid * WALL_T * slant + floor_m = DENSITY * np.pi * rb ** 2 * FLOOR_T + mass = wall_m + floor_m + # wall centroid height (from the underside): area-weighted, r grows linearly with z + r0, r1 = rb + TT * Z0, rb + TT * H + z_w = Z0 + (H - Z0) * (r0 + 2 * r1) / (3 * (r0 + r1)) + z_cm = (wall_m * z_w + floor_m * FLOOR_T / 2) / mass + Izz = wall_m * r_mid ** 2 + floor_m * rb ** 2 / 2 + Ixx = (wall_m * (r_mid ** 2 / 2 + (H - Z0) ** 2 / 12 + (z_w - z_cm) ** 2) + + floor_m * (rb ** 2 / 4 + (FLOOR_T / 2 - z_cm) ** 2)) + m.body_mass[bid] = mass + m.body_inertia[bid] = [Ixx, Ixx, Izz] + m.body_ipos[bid] = [0.0, 0.0, z_cm - H / 2] + m.body_iquat[bid] = [1.0, 0.0, 0.0, 0.0] + + def apply_instance(self, inst): + disable_midphase(self.env) + for c in inst["cups"]: + self._reshape_cup(c["name"], c["rb"], c["height"]) + envs.set_obj_pose(self.env, c["name"], [*c["xy"], envs.TABLE_Z + c["height"] / 2 + 0.0005]) + + # ------------------------------------------------------------ state + def _cup_state(self, inst, j): + c = inst["cups"][j] + bid = envs.body_id(self.env, c["name"]) + p = self.env.sim.data.body_xpos[bid].copy() + R = self.env.sim.data.body_xmat[bid].reshape(3, 3) + tilt = float(np.degrees(np.arccos(np.clip(R[2, 2], -1, 1)))) + bottom = p - R[:, 2] * c["height"] / 2 # centre of the floor's underside + rim = p + R[:, 2] * c["height"] / 2 + return dict(p=p, tilt=tilt, bottom=bottom, rim=rim, floor_top=bottom[2] + FLOOR_T * R[2, 2]) + + def relations(self, inst): + """For each cup: which cup it stands in / on (if any), how high, seated or not.""" + st = [self._cup_state(inst, j) for j in range(3)] + rel = [] + for j in range(3): + sj = st[j] + best = None + for i in range(3): + if i == j: + continue + ci, si = inst["cups"][i], st[i] + if si["tilt"] > 45: + continue + d = float(np.hypot(*(sj["bottom"][:2] - si["p"][:2]))) + if d > rim_radius(ci["rb"], ci["height"]) + 0.01: + continue # not above / in cup i + hb = float(sj["bottom"][2] - si["floor_top"]) # j's bottom above i's floor + # (the last test keeps a cup from being reported as standing in the cup it contains) + if hb < -0.004 or hb > ci["height"] + 0.02 or sj["bottom"][2] < si["bottom"][2] + FLOOR_T / 2: + continue + if best is None or hb < best[1]: + best = (i, hb, d) + if best is None: + on_table = sj["bottom"][2] < envs.TABLE_Z + 0.01 and sj["tilt"] < 30 + rel.append(dict(cup=j, on=None, table=bool(on_table), tilt=sj["tilt"], xy=sj["p"][:2].tolist(), + fallen=bool(sj["tilt"] > 45))) + continue + i, hb, d = best + ci = inst["cups"][i] + seated = hb < SEAT_H and sj["tilt"] < SEAT_TILT + on_rim = hb > ci["height"] - FLOOR_T - 0.004 + rel.append(dict(cup=j, on=i, height=hb, seated=bool(seated), on_rim=bool(on_rim), tilt=sj["tilt"], + offset=d, xy=sj["p"][:2].tolist(), fallen=bool(sj["tilt"] > 45))) + return rel + + def outcome(self, inst): + envs.settle(self.env, 40) + cups = inst["cups"] + rel = self.relations(inst) + held = [j for j in range(3) if self.sk is not None and self.sk.holding(cups[j]["name"])] + col = [c["color"] for c in cups] + seated_in = {r["cup"]: r["on"] for r in rel if r.get("on") is not None and r["seated"]} + # success: a chain outer <- mid <- inner, all seated and upright, the outer cup standing on the table + success = False + for a, b, c in itertools.permutations(range(3)): + if seated_in.get(b) == a and seated_in.get(c) == b and _on_table_upright(rel, a): + success = True + success = bool(success and not held) + fb = dict(seated=[[j, i] for j, i in seated_in.items()], blocked=[], offcentre=[], held=held) + lines = [] + res = dict(success=success, relations=rel, feedback=fb) + if held: + lines.append(f"The {col[held[0]]} cup is still in the gripper.") + if success: + a = [j for j in range(3) if j not in seated_in][0] + b = [j for j, i in seated_in.items() if i == a][0] + c = [j for j, i in seated_in.items() if i == b][0] + res["detail"] = (f"All three cups are nested: the {col[c]} cup stands inside the {col[b]} cup, " + f"which stands inside the {col[a]} cup.") + res["failure"] = None + return res + # bottom-up description + st = {r["cup"]: self._cup_state(inst, r["cup"]) for r in rel} + for r in sorted(rel, key=lambda r: st[r["cup"]]["bottom"][2]): + j = r["cup"] + if j in held: + continue + if r.get("on") is None: + if r["fallen"]: + lines.append(f"The {col[j]} cup has fallen over.") + elif r["table"]: + lines.append(f"The {col[j]} cup is standing on the table, not in another cup.") + else: + lines.append(f"The {col[j]} cup is neither standing on the table nor inside another cup.") + continue + i = r["on"] + if r["seated"]: + lines.append(f"The {col[j]} cup is inside the {col[i]} cup, standing on its bottom.") + continue + # did not go in. The text says only what a camera shows (no sizes); the structured field keeps the + # nominal verdict for the scripted learner + tilt = f", tilted about {r['tilt']:.0f} degrees" if r["tilt"] >= 8 else "" + if r["on_rim"]: + lines.append(f"The {col[j]} cup is sitting on the rim of the {col[i]} cup, not inside it{tilt}.") + else: + lines.append(f"The {col[j]} cup is stuck in the opening of the {col[i]} cup, not down inside " + f"it{tilt}.") + over = cups[j]["rb"] - cups[i]["rb"] + if over > 0: + fb["blocked"].append([j, i, round(100 * r["height"], 1)]) + else: + fb["offcentre"].append([j, i, round(100 * r["height"], 1)]) + res["detail"] = " ".join(lines) if lines else "The cups are not nested." + res["failure"] = "blocked" if fb["blocked"] else ("offcentre" if fb["offcentre"] else + ("held" if held else "incomplete")) + return res + + # ------------------------------------------------------------ execution + def execute(self, inst, params): + """params: order = [outer, middle, inner] (indices into inst['cups']). Puts the middle cup into the outer + one; if it went in (judged from the scene, as an agent would see it), puts the inner cup into the middle + one. Optional (robustness checks): dxy = (dx, dy) release offset (m), drop (m), grasp_below (m), + carry_speed (m/s or None = as fast as the controller allows).""" + o, mid, inn = [int(v) for v in params["order"]] + ok = self._move_cup(inst, mid, o, params) + if ok: + self._move_cup(inst, inn, mid, params) + self.sk.move_to(list(PARK), yaw=0.0) + + def _move_cup(self, inst, j, i, params): + sk = self.sk + sj = self._cup_state(inst, j) + x, y = sj["p"][:2] + rim = sj["rim"][2] + sk.set_gripper(False, steps=5) + sk.move_to([x, y, Z_CARRY], yaw=0.0) + sk.move_to([x, y, rim + 0.06], tol=0.004) + sk.move_to([x, y, rim - params.get("grasp_below", GRASP_BELOW_RIM)], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([x, y, Z_CARRY], speed=params.get("carry_speed", 0.3)) + si = self._cup_state(inst, i) + dx, dy = params.get("dxy", (0.0, 0.0)) + tx, ty = si["p"][0] + dx, si["p"][1] + dy + drop = params.get("drop", DROP) + sk.move_to([tx, ty, Z_CARRY], tol=0.004) + off = self._cup_state(inst, j)["bottom"] - sk.eef_pos() + # approach above the highest rim there (the target cup may stand inside a taller one) + top = max(s["rim"][2] for s in (self._cup_state(inst, q) for q in range(3) if q != j) + if np.hypot(s["p"][0] - tx, s["p"][1] - ty) < 0.04) + sk.move_to([tx - off[0], ty - off[1], max(top, si["rim"][2]) + drop + 0.03 - off[2]], tol=0.003) + z_rel = si["rim"][2] + drop + if top > si["rim"][2] + 0.002: # the target stands inside a taller cup: let go above that rim + z_rel = max(z_rel, top + FINGER_CLEAR - (inst["cups"][j]["height"] + - params.get("grasp_below", GRASP_BELOW_RIM))) + tgt = self._servo_cup(inst, j, [tx, ty], z_rel) + sk.grip = -1.0 + self._hold_at(tgt, 12) + sk.move_to([tgt[0], tgt[1], Z_CARRY], speed=0.3) + envs.settle(self.env, 20) + r = [q for q in self.relations(inst) if q["cup"] == j][0] + return bool(r.get("on") == i and r["seated"]) + + def _hold_at(self, target, steps): + sk = self.sk + R = sk._R() + for _ in range(steps): + sk._act(np.asarray(target) - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip) + + def _servo_cup(self, inst, j, xy, z_bottom, max_steps=60, tol=0.0015): + """closed loop on the held cup's bottom centre (scripted policies only). Stops where the cup is held up + (a too-wide cup on / in another cup's rim) instead of pressing on: a person lets go there too, and + pressing on tips the cups over.""" + sk = self.sk + R = sk._R() + goal = np.array([xy[0], xy[1], z_bottom]) + tgt = e_prev = sk.eef_pos() + zs = [] + for k in range(max_steps): + b, e = self._cup_state(inst, j)["bottom"], sk.eef_pos() + if k >= 8 and np.linalg.norm(b - goal) < tol and np.linalg.norm(e - e_prev) < 0.0005: + break + zs.append(b[2]) + if k >= 12 and b[2] - goal[2] > 0.003 and zs[-6] - b[2] < 0.0005: + return e # blocked: release here + tgt = goal - (b - e) + sk._act(tgt - e, _rot_err(R, sk.eef_mat()), sk.grip) + e_prev = e + return tgt + + # ------------------------------------------------------------ scripted policies + def default_params(self, inst): + """prior: the bigger-looking cup goes outside, and the cups look big by their height: tallest outermost""" + return dict(order=list(inst["naive_order"])) + + def oracle_params(self, inst): + return dict(order=list(inst["order"])) + + def blind_params(self, inst, attempt, rng): + """no history: the same height judgement again, with a little noise""" + est = [c["height"] * (1 + rng.normal(0, H_NOISE)) for c in inst["cups"]] + return dict(order=[int(i) for i in np.argsort(est)[::-1]]) + + @staticmethod + def constraints(history): + """pairs (outer, inner) implied by the F2 feedback of earlier attempts""" + pairs = set() + for h in history: + fb = h["outcome"].get("feedback") or {} + for j, i in fb.get("seated", []): + pairs.add((int(i), int(j))) # j sits in i -> i is outside j + for j, i, _ in fb.get("blocked", []): + pairs.add((int(j), int(i))) # j does not fit into i -> j must be outside i + for j, i, _ in fb.get("offcentre", []): + pairs.add((int(i), int(j))) # j would fit into i + return pairs + + def adapt_params(self, inst, history): + """Scripted learner. It does not perceive the bottoms at all; it uses only which cup went into / stayed on + top of which (visible in the camera images; the structured part of the outcome): every such relation gives + an (outer, inner) pair; among the untried orders consistent with all pairs it takes the one closest (fewest + swapped pairs) to its prior, the height order; ties go to the larger height agreement.""" + pairs = self.constraints(history) + rims = [c["height"] for c in inst["cups"]] + prior = list(inst["naive_order"]) + tried = {tuple(h["params"]["order"]) for h in history if (h["outcome"].get("feedback") or {}).get("blocked")} + cands = [] + for order in itertools.permutations(range(3)): + pos = {c: k for k, c in enumerate(order)} + consistent = all(pos[a] < pos[b] for a, b in pairs) + agree = sum(rims[order[k]] - rims[order[k + 1]] for k in range(2)) + cands.append((consistent, tuple(order) not in tried, -kendall(order, prior), agree, order)) + best = max(cands) + return dict(order=list(best[4])) + + def random_order_params(self, inst, history, rng): + """sensitivity variant: a random order each retry, no history""" + return dict(order=[int(i) for i in rng.permutation(3)]) + + EXTRA_KINDS = ("random_order",) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + if kind not in self.EXTRA_KINDS: + return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt) + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + params = self.default_params(inst) if a == 0 else self.random_order_params(inst, history, rng) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"]: + break + return history + + +def _on_table_upright(rel, j): + r = [q for q in rel if q["cup"] == j][0] + return r.get("on") is None and r["table"] and r["tilt"] < 8.0 and not r["fallen"] + + +# ---------------------------------------------------------------- physical validity checks +def physics_check(seed0=1000, n=8, out=None): + """All 6 orders on each instance; expect success iff the order is the true one.""" + import json + task = NestOrder() + rows = [] + for seed in range(seed0, seed0 + n): + inst = task.sample_instance(seed) + for order in itertools.permutations(range(3)): + task.reset_instance(inst) + task.execute(inst, dict(order=list(order))) + o = task.outcome(inst) + expect = list(order) == inst["order"] + # for a cup that did not go in: how far (cm) its bottom is below the other cup's rim + below_rim = [round(100 * (inst["cups"][r["on"]]["height"] - FLOOR_T - r["height"]), 2) + for r in o["relations"] if r.get("on") is not None and not r["seated"]] + rows.append(dict(seed=seed, case=inst["case"], order=list(order), success=o["success"], expect=expect, + failure=o["failure"], detail=o["detail"], below_rim_cm=below_rim, + clear_mm=inst["clear_mm"], tol_mm=inst["tol_mm"], bottom_cm=inst["bottom_cm"], + opening_cm=inst["opening_cm"], height_cm=inst["height_cm"])) + print(f"seed {seed} order {order} succ={o['success']} expect={expect} | {o['detail']}" + + ("" if o["success"] == expect else " <-- MISMATCH"), flush=True) + if out: + with open(out, "w") as f: + json.dump(rows, f, indent=1) + print("total", len(rows), "mismatches", sum(r["success"] != r["expect"] for r in rows)) + return rows + + +def robustness_check(seed0=1000, n=6, out=None): + """True order with execution errors: release off-centre (both moves) by 0-9 mm in a random direction, released + 3 cm above the rim, grasped lower, carried at full controller speed.""" + import json + task = NestOrder() + rows = [] + cases = [("centred", {}), ("off3", dict(off=0.003)), ("off5", dict(off=0.005)), ("off7", dict(off=0.007)), + ("off9", dict(off=0.009)), ("drop3cm", dict(drop=0.03)), ("off4_drop3cm", dict(off=0.004, drop=0.03)), + ("grasp2cm", dict(grasp_below=0.02)), ("fast_carry", dict(carry_speed=None))] + for seed in range(seed0, seed0 + n): + inst = task.sample_instance(seed) + rng = np.random.default_rng(seed) + for name, c in cases: + a = rng.uniform(0, 2 * np.pi) + off = c.get("off", 0.0) + params = dict(order=list(inst["order"]), dxy=(off * np.cos(a), off * np.sin(a))) + params.update({k: v for k, v in c.items() if k != "off"}) + task.reset_instance(inst) + task.execute(inst, params) + o = task.outcome(inst) + rows.append(dict(seed=seed, case=name, success=o["success"], detail=o["detail"], tol_mm=inst["tol_mm"], + height_cm=inst["height_cm"])) + print(f"seed {seed} {name:13s} succ={o['success']} | {o['detail']}", flush=True) + if out: + with open(out, "w") as f: + json.dump(rows, f, indent=1) + for name, _ in cases: + r = [x["success"] for x in rows if x["case"] == name] + print(f"{name:13s} {sum(r)}/{len(r)}") + return rows + + +if __name__ == "__main__": + # python -m lffbench.tasks.l4_nest physics results/l4_nest_order/physics_check.json [n] + # python -m lffbench.tasks.l4_nest robust results/l4_nest_order/robustness_check.json [n] + import sys + n_arg = int(sys.argv[3]) if len(sys.argv) > 3 else None + if sys.argv[1] == "physics": + physics_check(out=sys.argv[2] if len(sys.argv) > 2 else None, n=n_arg or 8) + elif sys.argv[1] == "robust": + robustness_check(out=sys.argv[2] if len(sys.argv) > 2 else None, n=n_arg or 6) diff --git a/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/l5_loaded_beam.py b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/l5_loaded_beam.py new file mode 100644 index 0000000000000000000000000000000000000000..9131ad1abf4810702f25f598a39e4010f47ecaef --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/l5_loaded_beam.py @@ -0,0 +1,598 @@ +"""L5 loaded_beam (2026-10-12): a deepened l5_slippery_lift -- lift a loaded bar level without spilling its load. + +Why (../research_notes/P1P2_加深与常识任务设计.md sec. 1, 2, 3.1): l5_slippery_lift saturated. Sonnet 5.5 (cla4) +grasped the bar's middle, lifted, saw the 45-60 deg tilt, put the bar down and regrasped near the centre of mass, +all inside attempt 1 (both runs succeeded on attempt 1): the tilting lift cost nothing. Rule R3: the first +common-sense interaction must cost something. Here the tilting lift spills the load. + +Scene (world frame, robot base at x = -0.66; "forward" = +x, "left" = +y): the l5_slippery_lift bar (steel grey, +4 x 28 x 4 cm, long axis along the robot's left-right axis, same layout and hidden weight per seed) with two small red +blocks (2.5 cm cubes, 30 g, smooth: friction 0.2, they slide on the steel beyond ~11 deg of tilt) resting on its top +near the ends, 12.5 cm left and right of its middle. + +Hidden variable (same in every attempt, invisible): a slug inside the bar puts its centre of mass e = 2.5-7 cm from +the middle, towards the left or right end (bar 0.8-1.2 kg, finger friction 0.40-0.60; l5_slippery_lift). The blocks +are symmetric, so the centre of mass of bar + blocks sits at M e / (M + 2 m) (2.3-6.7 cm). + +Mechanism (physics, nothing teleported): grasped at its middle and lifted, the bar rotates in the slippery finger +pads and hangs tilted; the block on the low (heavy) end slides off, drops onto the table and, once the bar is set down +again, lies 2-5 cm beyond the bar's end; the other block slides along the bar to the fingers. Measured (20 seeds, +middle grasp): lift 15 cm at 0.1 m/s -> tilt 29-54 deg, spill 20/20; 15 cm at 0.03 m/s -> spill 20/20 (block friction = +the bar's, task card); a 5.5 cm "half lift" -> 20-22 deg, spill 20/20; 3 cm -> 10-11 deg, spill 2/20; 1 / 1.5 cm test +lifts -> 0.6-2.5 / 2.5-4.5 deg, spill 0/20 each (the low end stays on the table). Putting it right is a real repair: +set the bar down, release, pick the fallen block from the table, put it back on the end, move the other block back to +its end, regrasp nearer the heavy end, lift again: 20 commands for the scripted policy (5 for the whole oracle; the +same repair costs 7 commands in l5_slippery_lift, where nothing spills). What helps: a ~1 cm test lift shows the tilt +direction without spilling, or, after the first failure, grasping on the side of the end that sank (the heavy end), +ideally at the combined centre of mass (+-5 mm: 80/80 level lifts, nothing spilled). + +Success: the bar is held (after a 1.5 s hold), tilted <= 8 deg, its lowest point >= 10 cm above the table (the +l5_slippery_lift condition), and both blocks rest on the bar, one within 3 cm of each end position (+-12.5 cm from the +middle; either block may sit on either end). Protocol: cross (reset before every attempt), k = 3. + +Outcome (server log only; the agent gets F1): success / failure code, the bar's tilt and height, final block states, +per-step events (bar_lifted, bar_tilted, load_fell = the trap fired, load_displaced, load_removed, load_restored with +by_robot, bar_set_down), the lifts with their grasp points and maximum tilt, trap_fired, recovered_in_attempt, +first_interaction_ok and an F2-style `detail` in robot-centric words. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import box_xml, register_generated +from ..task_base import register_task +from .l5_slippery_lift import (BAR, HALF, LIFT_MIN, TILT_MAX, YAW_ACROSS, Z_GRASP, BarSkills, SlipperyLift, + bar_tilt_deg, weighted_box_xml) + +TZ = envs.TABLE_Z +LOADS = ("block_1", "block_2") # block_1 starts on the left (+y) end, block_2 on the right (-y) end +LOAD_SIGN = {"block_1": 1.0, "block_2": -1.0} +LOAD_H = 0.0125 # 2.5 cm cubes +LOAD_MASS = 0.030 +LOAD_RGBA = (0.85, 0.20, 0.12, 1.0) +LOAD_MU = 0.20 # block sliding friction (geom priority 3: used against the bar, the table and the fingers): the blocks +# slide on the steel bar beyond ~11 deg of tilt. With the bar's own mu (0.4-0.6, slide beyond 22-31 deg) +# a 5.5 cm "half lift" (20 deg) spilled nothing (0/10) and was a free probe; with 0.2 it spills. +SLOT = 0.125 # block centre this far from the bar's middle (along the bar) +SLOT_TOL = 0.03 # success: within 3 cm of an end position +BAR_TOP = TZ + 2 * HALF[2] +LIFTED = 0.02 # the bar's centre this much higher than at rest (while held) -> "lifted" (a ~1 cm test lift is not) +DOWN = 0.008 # ... and back below this -> "set down" +DEBOUNCE = 5 # control steps a new block state must persist before it counts +SAFE_ALONG = 0.09 # scripted grasps stay within +-9 cm of the middle (the hand must not touch the blocks) + + +class _Budget(Exception): + """the scripted policy used up the agent command budget of the attempt""" + + +def bar_frame(env): + """(centre, along, side, up): `along` = the bar's long axis oriented towards the robot's left (+y); `up` = the + bar's cross-section axis closest to world up (the face the blocks rest on); `side` completes the frame.""" + bid = envs.body_id(env, BAR) + d = env.sim.data + c = d.body_xpos[bid].copy() + R = d.body_xmat[bid].reshape(3, 3) + al = R[:, 1].copy() + if al[1] < 0: + al = -al + up = max((R[:, 0].copy(), R[:, 2].copy()), key=lambda v: abs(v[2])) + if up[2] < 0: + up = -up + side = np.cross(up, al) + return c, al, side, up + + +def _end_word(s): + return "left" if s > 0 else "right" + + +class BeamSkills(BarSkills): + """BarSkills (records where along the bar the jaws closed) + the task's per-step monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class LoadedBeam(SlipperyLift): + name = "l5_loaded_beam" + level = "L5" + category = "dynamics_adaptation" + capabilities = ("Perceive", "Reason", "Plan", "Utilize") + protocol = "cross" + max_attempts = 3 + agent_max_steps = 40 + instruction = ("Lift the metal bar together with the two small red blocks resting near its ends, and hold it level " + "(tilted less than 8 degrees) with its lowest point at least 10 cm above the table. Both blocks must " + "stay on the bar near its ends. Keep holding the bar when you finish.") + instruction_indirect = ("Raise the long grey rod with the two little red cubes sitting near its ends and hold it " + "horizontal (tilted less than 8 degrees), its lowest point at least 10 cm above the table. " + "Both cubes must stay on the rod near its ends. Keep holding the rod when you finish.") + + # ------------------------------------------------------------ scene + def make_bddl(self): + bar = register_generated("LffBeamBar", weighted_box_xml("lff_beam_bar", HALF, (0.52, 0.55, 0.58, 1.0))) + dens = LOAD_MASS / (2 * LOAD_H) ** 3 + la = register_generated("LffBeamBlockA", box_xml("lff_beam_block_a", (LOAD_H,) * 3, LOAD_RGBA, density=dens)) + lb = register_generated("LffBeamBlockB", box_xml("lff_beam_block_b", (LOAD_H,) * 3, LOAD_RGBA, density=dens)) + # LIBERO's sampler puts the bar anywhere within +-13 cm of its region's centre (it "keeps the bar's 14 cm + # radius inside" a 2 cm region) and rejects block placements closer than 14 + 1.8 cm to it: the block regions + # are >= 19 cm from every possible bar position (the first layout, 2 cm beside the bar's range, failed with + # "Cannot place all objects" in 13 of 400 resets, this one 0 of 400). apply_instance moves everything anyway. + objs = [(BAR, bar, "bar_region", (-0.11, -0.01, -0.09, 0.01)), + ("block_1", la, "block1_region", (-0.11, 0.32, -0.09, 0.34)), + ("block_2", lb, "block2_region", (-0.11, -0.34, -0.09, -0.32))] + return write_bddl(self.name, "lift the loaded bar and hold it level", objs) + + def __init__(self, cam_res=None): + self.mon = None + self.budget = None # scripted policies only: command budget of the current attempt + self.ncmd = 0 + super().__init__(cam_res) + + def sample_instance(self, seed): + inst = super().sample_instance(seed) # same bar layout and hidden weight as l5_slippery_lift for this seed + m = inst["mass"] + inst.update(load_mass=LOAD_MASS, slot=SLOT, + com_total=float(m * inst["com_offset"] / (m + 2 * LOAD_MASS))) # bar + both blocks on their ends + return inst + + def apply_instance(self, inst): + super().apply_instance(inst) # bar pose, friction, hidden weight (+ envs.refit_bounds) + x, y = inst["bar_xy"] + for nm in LOADS: + envs.set_obj_pose(self.env, nm, [x, y + LOAD_SIGN[nm] * SLOT, BAR_TOP + LOAD_H + 0.0005]) + if LOAD_MU is not None: + envs.set_friction(self.env, nm, LOAD_MU, priority=3) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.mon = None + self.sk = BeamSkills(self.env, self, recorder=recorder) + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ state + def bar_bottom(self): + return envs.obj_min_z(self.env, BAR) - TZ + + def load_rel(self, nm): + """block centre in the bar frame: (along (+ = towards the bar's left end), side, height above the bar's centre)""" + c, al, side, up = bar_frame(self.env) + r = envs.obj_pos(self.env, nm) - c + return float(r @ al), float(r @ side), float(r @ up) + + def _block_held(self, nm): + sk = self.sk + if sk is None or sk.grip < 0: + return False + if np.linalg.norm(envs.obj_pos(self.env, nm) - sk.eef_pos()) > 0.06: + return False + return sk.holding(nm) + + def load_state(self, nm, tol=SLOT_TOL): + """'slot+' / 'slot-' (on the bar within `tol` of its left / right end position), 'bar' (on the bar + elsewhere), 'held', 'table', 'air' (anything else: falling, resting on the gripper ...)""" + if self._block_held(nm): + return "held" + a, s, u = self.load_rel(nm) + if abs(u - (HALF[2] + LOAD_H)) <= 0.008 and abs(s) <= HALF[0] + 0.003 and abs(a) <= HALF[1] + 0.003: + if abs(a - SLOT) <= tol: + return "slot+" + if abs(a + SLOT) <= tol: + return "slot-" + return "bar" + if envs.obj_pos(self.env, nm)[2] < TZ + 0.027: + return "table" + return "air" + + # ------------------------------------------------------------ monitor + def _init_monitor(self): + st = {nm: self.load_state(nm) for nm in LOADS} + self.mon = dict(stable=dict(st), cand={nm: None for nm in LOADS}, cnt={nm: 0 for nm in LOADS}, + last_on_bar={nm: self.load_rel(nm)[0] for nm in LOADS}, lost=set(), carried=set(), events=[], + lifts=[], + lifted=False, tilted=False, max_tilt=0.0) + + def _event(self, ev, step=None, **kw): + self.mon["events"].append(dict(step=int(self.sk.n_steps if step is None else step), ev=ev, **kw)) + + def _last_grasp(self): + return next((c for c in reversed(self.sk.closes) if c["holding"]), None) + + def monitor_step(self): + mon, sk = self.mon, self.sk + if mon is None or sk is None: + return + n = sk.n_steps + # --- the bar: lifts and tilt + rise = float(envs.obj_pos(self.env, BAR)[2]) - (TZ + HALF[2]) + held = sk.grip > 0 and sk.holding(BAR) + if not mon["lifted"] and held and rise > LIFTED: + g = self._last_grasp() + mon["lifted"], mon["tilted"], mon["max_tilt"] = True, False, 0.0 + mon["lifts"].append(dict(step_up=n, step_down=None, grasp_along=None if g is None else round(g["along"], 4), + max_tilt_deg=0.0, falls=[])) + self._event("bar_lifted", grasp_along=mon["lifts"][-1]["grasp_along"]) + if mon["lifted"]: + t = bar_tilt_deg(self.env) + lift = mon["lifts"][-1] + if abs(t) > abs(lift["max_tilt_deg"]): + lift["max_tilt_deg"] = round(t, 1) + if not mon["tilted"] and abs(t) > TILT_MAX and held: + mon["tilted"] = True + self._event("bar_tilted", tilt_deg=round(t, 1), low_end=_end_word(t)) + if rise < DOWN: + mon["lifted"] = False + lift["step_down"] = n + self._event("bar_set_down", max_tilt_deg=lift["max_tilt_deg"]) + # --- the blocks (debounced state machine) + for nm in LOADS: + # hysteresis: a block that has left its end position must come back within 2 cm of an end to count as + # restored (a block sliding along the tilted bar hovered around the 3 cm limit and flickered) + s = self.load_state(nm, SLOT_TOL - 0.01 if nm in mon["lost"] else SLOT_TOL) + if s in ("slot+", "slot-", "bar"): + mon["last_on_bar"][nm] = self.load_rel(nm)[0] + old = mon["stable"][nm] + if s == old: + mon["cand"][nm], mon["cnt"][nm] = None, 0 + continue + if s != mon["cand"][nm]: + mon["cand"][nm], mon["cnt"][nm] = s, 0 + mon["cnt"][nm] += 1 + if mon["cnt"][nm] < DEBOUNCE: + continue + step = n - DEBOUNCE + 1 + mon["stable"][nm], mon["cand"][nm], mon["cnt"][nm] = s, None, 0 + start = _end_word(LOAD_SIGN[nm]) + if s == "held": + mon["carried"].add(nm) + if s in ("slot+", "slot-"): + if nm in mon["lost"]: + # by_robot: the gripper carried it back (else physics did, e.g. the high-end block sliding back out + # while the bar swings after the other block fell: 3-4 of 59 blind attempts) + mon["lost"].discard(nm) + self._event("load_restored", step, load=nm, start_end=start, end=_end_word(1 if s == "slot+" else -1), + by_robot=nm in mon["carried"]) + mon["carried"].discard(nm) + elif old in ("slot+", "slot-") and s == "bar": + mon["lost"].add(nm) + self._event("load_displaced", step, load=nm, start_end=start, along_cm=round(100 * self.load_rel(nm)[0], 1)) + elif old in ("slot+", "slot-", "bar", "air") and s == "table": + mon["lost"].add(nm) + end = _end_word(mon["last_on_bar"][nm]) + self._event("load_fell", step, load=nm, start_end=start, off_end=end) + if mon["lifted"]: + mon["lifts"][-1]["falls"].append(nm) + elif old == "held" and s == "table": + mon["lost"].add(nm) + self._event("load_removed", step, load=nm, start_end=start) + elif old in ("slot+", "slot-") and s == "held": + mon["lost"].add(nm) # picked up by the agent: counts as lost until it is back on an end + + # ------------------------------------------------------------ outcome / F2 + def _where(self, nm): + """robot-centric description of a block that is not on an end position""" + st = self.load_state(nm) + a, s, u = self.load_rel(nm) + if st == "held": + return "is held in the gripper" + if st == "bar": + e = 1.0 if a >= 0 else -1.0 + return (f"is still on the bar but {100 * (SLOT - abs(a)):.0f} cm in from its {_end_word(e)} end position " + f"({100 * abs(a):.0f} cm {_end_word(e)} of the bar's middle)") + c, al, side, up = bar_frame(self.env) + e = 1.0 if a >= 0 else -1.0 + u = al[:2] / max(np.linalg.norm(al[:2]), 1e-6) # the bar's direction seen from above + end = c[:2] + al[:2] * e * HALF[1] # the end's position seen from above (also while the bar hangs tilted) + r = envs.obj_pos(self.env, nm)[:2] - end + beyond = float(r @ u) * e + lateral = float(r @ np.array([-u[1], u[0]])) + where = "on the table" if st == "table" else "off the bar" + if beyond > 0 and abs(lateral) < 0.04: + return f"lies {where}, {100 * beyond:.0f} cm beyond the bar's {_end_word(e)} end" + fx = f"{100 * abs(r[0]):.0f} cm {'forward' if r[0] > 0 else 'back'}" + fy = f"{100 * abs(r[1]):.0f} cm {'left' if r[1] > 0 else 'right'}" + return f"lies {where}, {fx} and {fy} of the bar's {_end_word(e)} end" + + def outcome(self, inst): + sk, mon = self.sk, self.mon + sk.hold(30) # 1.5 s with the gripper as the agent left it (envs.settle would open the jaws) + held = bool(sk.holding(BAR)) + tilt = bar_tilt_deg(self.env) + bottom = self.bar_bottom() + states = {nm: self.load_state(nm) for nm in LOADS} + on_plus = [nm for nm in LOADS if states[nm] == "slot+"] + on_minus = [nm for nm in LOADS if states[nm] == "slot-"] + loads_ok = len(on_plus) == 1 and len(on_minus) == 1 + level_ok = held and abs(tilt) <= TILT_MAX and bottom >= LIFT_MIN + success = bool(level_ok and loads_ok) + lifted_ever = bool(mon["lifts"]) or (sk.zmax - sk.z0) > 0.03 + g = self._last_grasp() + evs = mon["events"] + falls = [e for e in evs if e["ev"] == "load_fell"] + restored = [e for e in evs if e["ev"] == "load_restored"] + lifts = mon["lifts"] + first_ok = None if not lifts else bool(not lifts[0]["falls"]) # the first lift spilled nothing + # --- text + gtxt = "" + if g is not None: + a = g["along"] + gtxt = (f" You last grasped the bar {100 * abs(a):.1f} cm to the {_end_word(a)} of its middle." + if abs(a) >= 0.0005 else " You last grasped the bar at its middle.") + tilt_txt = (f"hangs tilted by {abs(tilt):.0f} degrees, its {_end_word(tilt)} end lower than its " + f"{_end_word(-tilt)} end") + if success: + failure = None + bar_txt = (f"The bar is held level (tilt {abs(tilt):.0f} degrees), {100 * bottom:.0f} cm above the table, " + "with a block on each end.") + elif held and abs(tilt) > TILT_MAX: + failure = "tilted" + bar_txt = f"The bar did not stay level: it rotated in the gripper and now {tilt_txt}." + if bottom < LIFT_MIN: + bar_txt += f" Its lowest point is {100 * bottom:.0f} cm above the table." + elif held and bottom < LIFT_MIN: + failure = "too_low" + bar_txt = (f"The bar is held level (tilt {abs(tilt):.0f} degrees) but its lowest point is only " + f"{100 * bottom:.0f} cm above the table.") + elif held: + failure = "load_off" + bar_txt = (f"The bar is held level (tilt {abs(tilt):.0f} degrees), {100 * bottom:.0f} cm above the table, " + "but the blocks are not both on its ends.") + elif lifted_ever: + failure = "dropped" + bar_txt = "The bar was lifted but is no longer in the gripper; it lies on the table." + else: + failure = "no_grasp" + bar_txt = ("The gripper never closed on the bar; it is still lying on the table." if not sk.closes else + "The gripper did not catch the bar; it is still lying on the table.") + parts = [bar_txt] + if falls: + f0 = falls[0] + lift = next((l for l in lifts if f0["load"] in l["falls"]), None) + how = (f" while the bar hung tilted by up to {abs(lift['max_tilt_deg']):.0f} degrees with its " + f"{_end_word(lift['max_tilt_deg'])} end lower") if lift and abs(lift["max_tilt_deg"]) > 1 else "" + parts.append(f"The {f0['start_end']} block slid off the bar's {f0['off_end']} end{how}." + + (f" Blocks fell off {len(falls)} times in this attempt." if len(falls) > 1 else "")) + if not loads_ok: + for nm in LOADS: + if states[nm] in ("slot+", "slot-") and (len(on_plus) == 1 or states[nm] != "slot+") and \ + (len(on_minus) == 1 or states[nm] != "slot-"): + continue + parts.append(f"The {_end_word(LOAD_SIGN[nm])} block {self._where(nm)}.") + detail = " ".join(parts) + gtxt + loads = {} + for nm in LOADS: + a, s, u = self.load_rel(nm) + loads[nm] = dict(state=states[nm], along_cm=round(100 * a, 1), side_cm=round(100 * s, 1), + above_bar_centre_cm=round(100 * u, 1)) + out = dict(success=success, failure=failure, held=held, tilt_deg=round(tilt, 1), bottom_cm=round(100 * bottom, 1), + grasp_along=None if g is None else round(g["along"], 4), + stages=dict(bar_held_level_high=bool(level_ok), loads_on_ends=bool(loads_ok)), + loads=loads, loads_on_ends=len(on_plus) + len(on_minus) if loads_ok else + int(len(on_plus) >= 1) + int(len(on_minus) >= 1), + trap_fired=bool(falls), n_load_falls=len(falls), n_restored=len(restored), + n_restored_by_robot=len([e for e in restored if e.get("by_robot")]), + n_regressions=len([e for e in evs if e["ev"] in ("load_fell", "load_displaced")]), + recovered_in_attempt=bool(falls and success), first_interaction_ok=first_ok, + n_lifts=len(lifts), lifts=lifts, events=list(evs), closes=sk.closes, detail=detail) + out["detail_indirect"] = detail.replace("bar", "rod").replace("block", "cube") + return out + + # ------------------------------------------------------------ scripted primitives (agent-command counted) + def _cmd(self, target=None, yaw=None, speed=None, grip=None, tol=0.004, max_steps=250): + """one agent command (move_eef with an optional gripper action, or observe when nothing is given)""" + self.ncmd += 1 + if self.budget is not None and self.ncmd > self.budget: + raise _Budget() + sk = self.sk + if target is not None: + t = np.asarray(target, float).copy() + t[2] = max(t[2], TZ + 0.006) # the agent interface does not go below 0.5 cm above the table + sk.move_to(t, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + if grip is not None: + sk.set_gripper(bool(grip)) + + def grasp_lift(self, along, lift=0.15, speed=0.10, dx=0.0): + """open, above the grasp point (jaws across the bar), descend, close, lift, look: 5 commands""" + c, al, side, up = bar_frame(self.env) + g = c + al * float(along) + np.array([dx, 0.0, 0.0]) + z = max(float(c[2]), Z_GRASP) + self._cmd([g[0], g[1], z + 0.10], yaw=YAW_ACROSS, grip=False) + self._cmd([g[0], g[1], z], tol=0.003) + self._cmd(grip=True) + self._cmd([g[0], g[1], z + lift], speed=speed, max_steps=600) + self._cmd() + + def put_down(self): + """lower the held bar onto the table, release, back up: 2 commands""" + e = self.sk.eef_pos() + self._cmd([e[0], e[1], Z_GRASP + 0.003], speed=0.05, grip=False, max_steps=600) + self._cmd([e[0], e[1], Z_GRASP + 0.12]) + + def _block_yaw(self, nm): + """gripper yaw whose jaws close on two faces of the block, preferring jaws that do not reach towards the bar""" + q = envs.obj_quat(self.env, nm) + w, x, y, z = q + psi = float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))) + c, al, side, up = bar_frame(self.env) + p = envs.obj_pos(self.env, nm) + a = float(np.clip((p - c) @ al, -HALF[1], HALF[1])) + v = (p - (c + al * a))[:2] + v = v / max(np.linalg.norm(v), 1e-6) + best = None + for k in range(2): + ang = psi + k * np.pi / 2 # closing direction candidate (a face normal) + n = np.array([np.cos(ang), np.sin(ang)]) + score = abs(n @ v) + if best is None or score < best[0]: + best = (score, ang) + yaw = best[1] + np.pi / 2 # yaw = closing direction + 90 deg (YAW_ACROSS closes along world x) + return float((yaw + np.pi / 2) % np.pi - np.pi / 2) + + def move_block_to_slot(self, nm, sign, tries=2): + """pick a block (from the table or the bar) and set it on the end position `sign`: 6 commands per try""" + sk = self.sk + for _ in range(tries): + p = envs.obj_pos(self.env, nm) + yaw = self._block_yaw(nm) + zg = max(float(p[2]), TZ + 0.008) + self._cmd([p[0], p[1], zg + 0.08], yaw=yaw, grip=False) + self._cmd([p[0], p[1], zg], tol=0.003, grip=True) + self._cmd([p[0], p[1], BAR_TOP + LOAD_H + 0.07]) + if not sk.holding(nm): + continue + c, al, side, up = bar_frame(self.env) + t = c + al * sign * SLOT + ztop = envs.obj_max_z(self.env, BAR) + self._cmd([t[0], t[1], ztop + LOAD_H + 0.06]) + self._cmd([t[0], t[1], ztop + LOAD_H + 0.004], speed=0.05, grip=False) + self._cmd([t[0], t[1], ztop + LOAD_H + 0.08]) + if self.load_state(nm) == ("slot+" if sign > 0 else "slot-"): + return True + return False + + def restore_loads(self): + """put every block that is not on an end position back onto a free end; True if both ends are taken""" + for _ in range(2): + st = {nm: self.load_state(nm) for nm in LOADS} + free = [s for s in (1.0, -1.0) if not any(v == ("slot+" if s > 0 else "slot-") for v in st.values())] + if not free: + return True + loose = [nm for nm in LOADS if st[nm] not in ("slot+", "slot-")] + for sgn in free: + if not loose: + break + c, al, side, up = bar_frame(self.env) + slot = c + al * sgn * SLOT + nm = min(loose, key=lambda b: np.linalg.norm(envs.obj_pos(self.env, b)[:2] - slot[:2])) + loose.remove(nm) + self.move_block_to_slot(nm, sgn) + self._cmd() # look + st = {nm: self.load_state(nm) for nm in LOADS} + return sorted(st.values()) == ["slot+", "slot-"] + + def judge(self): + """what an agent sees after a lift (perfect perception): (all good, tilt, blocks on their ends)""" + tilt = bar_tilt_deg(self.env) + st = sorted(self.load_state(nm) for nm in LOADS) + ok_loads = st == ["slot+", "slot-"] + good = self.sk.holding(BAR) and abs(tilt) <= TILT_MAX - 2 and self.bar_bottom() >= LIFT_MIN + 0.01 and ok_loads + return bool(good), float(tilt), ok_loads + + # ------------------------------------------------------------ scripted policies + def execute(self, inst, params): + self.grasp_lift(params["along"], params.get("lift", 0.15), params.get("speed", 0.10), params.get("dx", 0.0)) + + def default_params(self, inst): + return dict(along=0.0, lift=0.15, speed=0.10) # Sonnet 5.5 (cla4): middle, up to ~15-18 cm at 0.1 m/s + + def oracle_params(self, inst): + return dict(along=float(inst["com_total"]), lift=0.15, speed=0.10) + + def blind_params(self, inst, attempt, rng): + return dict(along=float(rng.normal(0.0, 0.01)), lift=float(rng.uniform(0.12, 0.18)), + speed=float(rng.uniform(0.05, 0.20))) + + MARGIN = 0.008 # a lift that sank towards +y at grasp g says COM > g + MARGIN + STEP = 0.030 # first move towards the end that sank when only one side is bounded + + def bracket(self, obs): + """grasp point from (grasp_along, tilt) observations: the end that sank is the heavy side of that grasp""" + lo, hi = -SAFE_ALONG, SAFE_ALONG + lo_set = hi_set = False + for g, t in obs: + if t > 0: + lo, lo_set = max(lo, g + self.MARGIN), True + else: + hi, hi_set = min(hi, g - self.MARGIN), True + if lo_set and hi_set: + a = 0.5 * (lo + hi) + elif lo_set: + a = lo + self.STEP - self.MARGIN + elif hi_set: + a = hi - self.STEP + self.MARGIN + else: + a = 0.0 + return float(np.clip(a, -SAFE_ALONG, SAFE_ALONG)) + + def adapt_params(self, inst, history): + obs = [o for h in history for o in h["params"].get("obs", [])] + return dict(along=self.bracket(obs)) + + def adaptive_attempt(self, obs): + """lift at the current estimate; if the bar tilts or a block falls: set the bar down, put the blocks back, + regrasp on the side of the end that sank (bracketing), lift again -- while the command budget allows""" + tried = [] + along = self.bracket(obs) + while True: + tried.append(round(along, 4)) + self.grasp_lift(along) + good, tilt, ok_loads = self.judge() + if good: + return tried + g = self._last_grasp() + if abs(tilt) > 3.0 or not ok_loads: + lift = self.mon["lifts"][-1] if self.mon["lifts"] else None + t = tilt if abs(tilt) > 3.0 else (lift["max_tilt_deg"] if lift else 0.0) + if abs(t) > 1.0: + obs.append((g["along"] if g is not None else along, t)) + # a repair = set down (2) + both blocks back (2 x 6: the fallen one and the one that slid to the fingers) + # + look (1) + regrasp, lift, look (5) = 20 commands; without enough budget keep holding the bar as it is + if self.budget is not None and self.ncmd + 20 > self.budget: + return tried + self.put_down() + if not self.restore_loads(): + return tried + along = self.bracket(obs) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """cross protocol with an agent-like command budget per attempt (agent_max_steps; one move_eef with an optional + gripper action, or one observe, = one command). naive / oracle / blind: one lift, no checking. + adaptive: naive in attempt 1 but checks and repairs inside the attempt (`adaptive_attempt`); later attempts + start from the grasp point learned so far.""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history, obs = [], [] + for a in range(k): + self.reset_instance(inst) + self.ncmd, self.budget = 0, self.agent_max_steps + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "adaptive": + params = dict(obs=[]) + else: + raise ValueError(kind) + n0 = len(obs) + try: + if kind == "adaptive": + params["tried"] = self.adaptive_attempt(obs) + else: + self.execute(inst, params) + except _Budget: + params["budget_used_up"] = True + if kind == "adaptive": + params["obs"] = [[round(g, 4), round(t, 1)] for g, t in obs[n0:]] + self.budget = None + out = self.outcome(inst) + out["commands"] = self.ncmd + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history + diff --git a/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/l5_tablecloth_pull.py b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/l5_tablecloth_pull.py new file mode 100644 index 0000000000000000000000000000000000000000..d80d949cb344b6f76199ae9a4dbdeaa0ca800a66 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/l5_tablecloth_pull.py @@ -0,0 +1,392 @@ +"""L5-C tablecloth_pull: yank a board out from under a cube so that the cube lands inside a band. + +Category dynamics_adaptation (L5): "figure out how this object moves". Replaces l5_tip_threshold, which could not +be built robustly with this robot (see task_cards/l5_tip_threshold.md). + +Scene: a 30 x 8 x 1 cm wooden board lies on the table, pointing away from the robot, with a black handle block +at its near end. A red 4 cm cube stands on the far part of the board. A green band (6 cm deep, across the +table) is painted on the table under the board, a few cm closer to the robot than the cube. The agent may touch +only the board / handle, never the cube. + +Physics. If the board is pulled slowly the cube rides along on it (static friction). If it is yanked, the board +slides out from under the cube; while it slides, friction drags the cube a little towards the robot, so the +cube drops onto the table having moved d towards the robot. d DEcreases with the pull speed (counter-intuitive: +a harder yank moves the cube less) and increases with the cube-board friction mu. + +Hidden variable: the cube's friction mu (0.08-0.15; the cube looks the same for every mu), which shifts the whole +speed -> displacement curve and the speed below which the cube rides along. + +Why the prior fails. The classic tablecloth prior is to yank as fast as possible (0.6 m/s, the arm's top speed); +the band is always placed >= 1.3 cm beyond the displacement such a yank produces, so the cube lands short of it. F2 reports where the cube ended relative to the band (robot-frame words, cm) or that it +rode along; the agent has to infer which way to change the pull speed (faster = less displacement) and by how +much. + +Rule (stated in the instruction and enforced, 2026-10-08): ONE pull. Only one move command may drive the board +(>= PULL_EPS), the cube must still be where it started (<= PRE_TOL, grasp nudges) when that pull begins, and all +other move commands together may drive the board at most STRAY_MAX. Gripper open / close commands never count. +Without it every cla2 success (Sonnet, 4/4) dragged the board slowly first so that the cube rode to the band and the +last pull only added a little (one dragged it 4 cm, then yanked it sideways; one moved it with 11 commands, most +of them open-gripper strikes): the friction never mattered. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +BOARD, CUBE, BAND = "board_1", "cube_1", "band_1" +B_HALF = (0.15, 0.04, 0.005) # 30 x 8 x 1 cm +H_HALF = (0.0125, 0.02, 0.015) # handle 2.5 x 4 x 3 cm on top of the near end +C_HALF = 0.02 # 4 cm cube +LF = 0.05 # cube centre to the board's far edge +BAND_HALF_X = 0.03 # band 6 cm deep: the 4 cm cube must be fully inside -> centre within +-1 cm +BAND_HALF_Y = 0.12 +LINE_W = 0.005 +TOL = BAND_HALF_X - C_HALF +MU_BOARD = 0.3 # board-table friction (fixed) +STROKE = 0.25 # scripted pull length +V_MIN, V_MAX = 0.15, 0.80 +# one-pull rule (2026-10-08). Board motion is the larger of its two ends' 3-D paths and is only counted while the robot +# drives the board (touches it, or it speeds up; a board sliding on its own only slows down), so coasting after a +# strike or a release is not charged to the next command. Measured on the cla2 agent runs and the scripted policy: +# approach moves 0 mm; closing on the handle 0.6-2 mm (agents) / 4.6 mm (script); release after the pull 3-10 mm +# (gripper commands never count as pulls); the loophole drags 13-41 mm per command, open-gripper strikes 11-54 mm. +PULL_EPS = 0.003 # a move command that drives the board this far is a pull +PRE_TOL = 0.01 # the cube may have moved at most this much (grasp nudges) when the pull starts +STRAY_MAX = 0.005 # board motion driven by all the other move commands together (each below PULL_EPS) +ACC_EPS = 0.0002 # board speed-up per control step (m/step) that counts as the robot driving it +_SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"' + + +def board_xml(name): + hp = (-B_HALF[0] + H_HALF[0], 0.0, B_HALF[2] + H_HALF[2]) + wood, black = (0.62, 0.45, 0.28, 1.0), (0.12, 0.12, 0.12, 1.0) + g = (f' \n' + f' \n' + f' \n' + f' \n' + f' ') + # small horizontal radius: only LIBERO's reset-time sampler reads it (the layout is overridden anyway) + return _wrap(name, g, B_HALF[2], 0.03) + + +def band_xml(name, line_rgba=(0.1, 0.55, 0.15, 1.0), fill_rgba=(0.75, 0.92, 0.75, 1.0)): + """Flat visual band across the table (no collisions): light fill + dark lines on its two long edges.""" + hx, hy = BAND_HALF_X, BAND_HALF_Y + parts = [((0, 0, 0.0004), (hx, hy, 0.0004), fill_rgba), + ((hx + LINE_W / 2, 0, 0.0010), (LINE_W / 2, hy, 0.0002), line_rgba), + ((-hx - LINE_W / 2, 0, 0.0010), (LINE_W / 2, hy, 0.0002), line_rgba)] + g = "\n".join(f' ' for p, sz, c in parts) + return _wrap(name, g, 0.0012, 0.03) + + +def d_range(mu): + """Band distances sampled for a given mu (m). Calibrated 2026-10-07 (LF 5 cm, board at x 0.05): the cube + moves d(0.6 m/s) ~ 0.33 * mu - 0.85 cm when yanked at the controller's top speed (mu 0.08 -> 1.8 cm, + 0.10 -> 2.3, 0.12 -> 3.1, 0.15 -> 4.3 cm) and >= 0.5 * mu at a pull ~0.05 m/s above the ride-along speed (0.08 -> 4.1 cm at + 0.35 m/s, 0.15 -> 7.6 cm at 0.45 m/s). The band centre is put ~1.5 cm beyond the top-speed displacement, so + the 'yank as fast as possible' prior always lands the cube short of the band.""" + return 0.33 * mu + 0.0065, 0.50 * mu + + +class ClothSkills(Skills): + """Skills that watch, every control step, whether the robot touches the cube (not allowed) and how each + move_to / gripper command moves the board and the cube (one pull only).""" + + def __init__(self, env, bias=None, recorder=None): + super().__init__(env, bias=bias, recorder=recorder) + m = env.sim.model + self._robot = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith(("gripper0_", "robot0_"))] + self._cube = envs.obj_geom_ids(env, CUBE) + self._board = envs.obj_geom_ids(env, BOARD) + self.touched_cube = False + self.cube0 = envs.obj_pos(env, CUBE) + self._ends = self._board_ends() + self._bstep = 0.0 # board motion in the previous control step + self._seg = None + self.segments = [] # one entry per move_to / set_gripper command + + def _board_ends(self): + """Both ends of the board's long axis (world xyz): their motion also catches turning and tilting.""" + b = envs.obj_pos(self.env, BOARD) + R = self.env.sim.data.body_xmat[envs.body_id(self.env, BOARD)].reshape(3, 3) + return np.stack([b - R[:, 0] * B_HALF[0], b + R[:, 0] * B_HALF[0]]) + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + if not self.touched_cube and envs.contacts_between(self.env, self._robot, self._cube): + self.touched_cube = True + ends = self._board_ends() + step = float(np.max(np.linalg.norm(ends - self._ends, axis=1))) + touch = envs.contacts_between(self.env, self._robot, self._board) + speed_up = step - self._bstep > ACC_EPS + self._ends, self._bstep = ends, step + s = self._seg + if s is not None: + s["path"] += step + s["touch"] += int(touch) + if touch or speed_up: + s["driven"] += step + + def _segment(self, kind, fn, *args, **kwargs): + c0, b0 = envs.obj_pos(self.env, CUBE), envs.obj_pos(self.env, BOARD) + self._seg = dict(kind=kind, step0=self.n_steps, path=0.0, driven=0.0, touch=0) + try: + rep = fn(*args, **kwargs) + finally: + s, self._seg = self._seg, None + c1, b1 = envs.obj_pos(self.env, CUBE), envs.obj_pos(self.env, BOARD) + s.update(steps=self.n_steps - s["step0"], board_dxy=(b1 - b0)[:2].round(4).tolist(), + cube_dxy=(c1 - c0)[:2].round(4).tolist(), cube_from_start=(c0 - self.cube0)[:2].round(4).tolist()) + self.segments.append(s) + return rep + + def move_to(self, target, *args, **kwargs): + return self._segment("move", super().move_to, target, *args, **kwargs) + + def set_gripper(self, close, steps=15): + return self._segment("close" if close else "open", super().set_gripper, close, steps) + + def pull_check(self): + """Pulls (move commands that drove the board >= PULL_EPS), where the cube was when the (first) pull started, + and the board motion driven by the other move commands.""" + moves = [s for s in self.segments if s["kind"] == "move"] + pulls = [s for s in moves if s["driven"] >= PULL_EPS] + stray = sum(s["driven"] for s in moves if s["driven"] < PULL_EPS) + pre = (float(np.linalg.norm(pulls[0]["cube_from_start"])) if pulls + else float(np.linalg.norm((envs.obj_pos(self.env, CUBE) - self.cube0)[:2]))) + return dict(n_pulls=len(pulls), pulls_cm=[round(100 * s["driven"], 1) for s in pulls], + pre_pull_cube_cm=round(100 * pre, 1), stray_cm=round(100 * stray, 2)) + + +@register_task +class TableclothPull(LFFTask): + name = "l5_tablecloth_pull" + level = "L5" + category = "dynamics_adaptation" + capabilities = ("Perceive", "Reason", "Utilize") + protocol = "cross" + instruction = ("Pull the wooden board out from under the red cube so that the cube ends up standing on the table " + "completely inside the green band. Touch only the board and its black handle, never the cube. " + "Only one pull is allowed per attempt: grasp the black handle, pull the board out with ONE move " + "command, then release it. Any other move that drags, pushes or nudges the board, before or after " + "the pull, counts as another pull.") + instruction_indirect = ("Pull the long brown plank out from under the small red block so that the block ends up " + "standing on the table completely inside the green stripe. Touch only the plank and its " + "black handle, never the block. Only one pull is allowed per attempt: grasp the black " + "handle, pull the plank out with ONE move command, then release it. Any other move that " + "drags, pushes or nudges the plank, before or after the pull, counts as another pull.") + + # ------------------------------------------------------------ scene + def make_bddl(self): + board = register_generated("LffClothBoard", board_xml("lff_cloth_board")) + cube = register_generated("LffClothCube", box_xml("lff_cloth_cube", (C_HALF,) * 3, (0.85, 0.15, 0.15, 1.0), + density=2300)) + band = register_generated("LffClothBand", band_xml("lff_cloth_band"), free=False) + objs = [(BOARD, board, "board_region", (0.09, -0.26, 0.11, -0.24)), + (CUBE, cube, "cube_region", (-0.21, 0.24, -0.19, 0.26))] + fixtures = [(BAND, band, "band_region", (-0.31, -0.01, -0.29, 0.01))] + return write_bddl(self.name, "pull the board out from under the cube", objs, fixtures=fixtures) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + mu = float(np.exp(rng.uniform(np.log(0.08), np.log(0.15)))) + lo, hi = d_range(mu) + d = float(rng.uniform(lo, max(lo, hi))) + return dict(seed=int(seed), board_xy=[float(rng.uniform(0.03, 0.08)), float(rng.uniform(-0.08, 0.08))], + mu=mu, band_d=d) + + def cube_start(self, inst): + bx, by = inst["board_xy"] + return np.array([bx + B_HALF[0] - LF, by]) + + def band_center(self, inst): + c = self.cube_start(inst) + return np.array([c[0] - inst["band_d"], c[1]]) + + def apply_instance(self, inst): + m = self.env.sim.model + for g in range(m.ngeom): # the band is a flat marker: no collisions + if (m.geom_id2name(g) or "").startswith(BAND + "_"): + m.geom_contype[g] = 0 + m.geom_conaffinity[g] = 0 + bx, by = inst["board_xy"] + envs.set_obj_pose(self.env, BOARD, [bx, by, envs.TABLE_Z + B_HALF[2] + 0.0005]) + c = self.cube_start(inst) + envs.set_obj_pose(self.env, CUBE, [c[0], c[1], envs.TABLE_Z + 2 * B_HALF[2] + C_HALF + 0.0005]) + envs.set_friction(self.env, BOARD, MU_BOARD, priority=1) + envs.set_friction(self.env, CUBE, inst["mu"], priority=2) # cube-board and cube-table contacts use mu + bid = m.body_name2id(self.env.fixtures_dict[BAND].root_body) + bc = self.band_center(inst) + m.body_pos[bid] = [bc[0], bc[1], envs.TABLE_Z + 0.0002] + m.body_quat[bid] = [1.0, 0.0, 0.0, 0.0] + + def reset_instance(self, inst, recorder=None): + from robosuite.utils.errors import RandomizationError + for _ in range(20): # LIBERO's reset-time placement sampler occasionally fails; the layout is overridden + try: + self.env.reset() + break + except RandomizationError: + continue + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = ClothSkills(self.env, bias=self.skill_bias(inst), recorder=recorder) + return self.sk + + # ------------------------------------------------------------ outcome + def cube_on_board(self): + c = envs.obj_pos(self.env, CUBE) + b = envs.obj_pos(self.env, BOARD) + R = self.env.sim.data.body_xmat[envs.body_id(self.env, BOARD)].reshape(3, 3) + local = R.T @ (c - b) + return bool(abs(local[0]) < B_HALF[0] + 0.005 and abs(local[1]) < B_HALF[1] + 0.005 + and c[2] > envs.TABLE_Z + 2 * B_HALF[2] + C_HALF - 0.004) + + def outcome(self, inst): + sk = self.sk + envs.settle(self.env, 60) + c = envs.obj_pos(self.env, CUBE) + c0 = self.cube_start(inst) + bc = self.band_center(inst) + moved = float(c0[0] - c[0]) # towards the robot + off = c[:2] - bc # + x: cube forward (away from the robot) of the band's centre line + upright = envs.obj_upright_cos(self.env, CUBE) > 0.95 + on_board = self.cube_on_board() + on_table = c[2] < envs.TABLE_Z + C_HALF + 0.004 + in_band = bool(abs(off[0]) <= TOL and abs(off[1]) <= BAND_HALF_Y - C_HALF) + pc = sk.pull_check() + rule = [] + if pc["n_pulls"] > 1: + rule.append(f"The board was moved by {pc['n_pulls']} separate move commands " + f"({', '.join(f'{v:.1f}' for v in pc['pulls_cm'])} cm); only one pull is allowed.") + if pc["n_pulls"] and pc["pre_pull_cube_cm"] > 100 * PRE_TOL: + rule.append(f"When the pull started the cube had already been moved {pc['pre_pull_cube_cm']:.1f} cm by " + f"earlier small moves of the board; only one pull is allowed.") + if pc["stray_cm"] > 100 * STRAY_MAX: + rule.append(f"Besides the pull, other move commands moved the board {pc['stray_cm']:.1f} cm in total; " + f"only one pull is allowed.") + success = bool(in_band and on_table and upright and not on_board and not sk.touched_cube and not rule) + b_moved = float(np.linalg.norm(envs.obj_pos(self.env, BOARD)[:2] - np.asarray(inst["board_xy"]))) + out = dict(success=success, touched_cube=bool(sk.touched_cube), on_board=on_board, upright=bool(upright), + moved_toward_robot=round(moved, 4), band_offset_x=round(float(off[0]), 4), + err=round(float(moved - inst["band_d"]), 4), board_moved=round(b_moved, 4), + one_pull=not rule, **pc) + side = ("forward (+x, away from the robot)" if off[0] > 0 else "backward (-x, toward the robot)") + where = (f"its centre is {100 * abs(off[0]):.1f} cm {side} of the band's centre line" + if abs(off[0]) >= 0.0005 else "its centre is on the band's centre line") + if sk.touched_cube: + out["failure"] = "touched_cube" + detail = "The robot touched the cube, which is not allowed." + elif on_board and b_moved < 0.02: + out["failure"] = "board_not_moved" + detail = "The board was not pulled; the cube is still standing on it." + elif on_board: + out["failure"] = "rode_along" + detail = (f"The board was pulled {100 * b_moved:.0f} cm, but the cube rode along on it: it is still on the " + f"board and moved {100 * moved:.1f} cm toward the robot.") + elif not upright: + out["failure"] = "toppled" + detail = f"The board came out from under the cube, but the cube fell over; {where}." + elif in_band and on_table and upright: + out["failure"] = None + detail = (f"The board came out from under the cube and the cube is standing inside the green band; {where}. " + f"It moved {100 * moved:.1f} cm toward the robot.") + else: + out["failure"] = "missed_band" + detail = (f"The board came out from under the cube and the cube is standing on the table, but not " + f"completely inside the green band: {where}. It moved {100 * moved:.1f} cm toward the robot.") + if rule and not sk.touched_cube: + out["failure"] = "several_pulls" + detail = " ".join(rule) + " " + detail + out["detail"] = detail + out["detail_indirect"] = (detail.replace("board", "plank").replace("cube", "block") + .replace("green band", "green stripe").replace("band's", "stripe's")) + return out + + def feedback(self, inst, out, level="F2", indirect=False): + if indirect and level == "F2": + out = dict(out, detail=out.get("detail_indirect", out["detail"])) + return super().feedback(inst, out, level) + + # ------------------------------------------------------------ scripted execution (cross protocol) + def execute(self, inst, params): + """Grasp the handle (jaws across its 4 cm width) and pull the board STROKE m toward the robot at `speed`.""" + sk = self.sk + b = envs.obj_pos(self.env, BOARD) + hx, hy = b[0] - B_HALF[0] + H_HALF[0], b[1] + zg = envs.TABLE_Z + 2 * B_HALF[2] + H_HALF[2] + sk.set_gripper(False, steps=5) + sk.move_to([hx, hy, zg + 0.08], yaw=0.0) + sk.move_to([hx, hy, zg], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([hx - STROKE, hy, zg], speed=float(np.clip(params["speed"], V_MIN, V_MAX)), tol=0.01, + max_steps=300) + sk.set_gripper(False, steps=8) + sk.move_to([hx - STROKE, hy, zg + 0.10], speed=0.3) + + def default_params(self, inst): + """Prior: the classic tablecloth trick -- yank as fast as the arm can.""" + return dict(speed=0.60) + + def blind_params(self, inst, attempt, rng): + return dict(speed=float(np.clip(0.60 + rng.normal(0, 0.06), V_MIN, V_MAX))) + + def adapt_params(self, inst, history): + """Bracketing search on the pull speed with the signed displacement error (riding along = far too much + displacement). Faster -> less displacement.""" + pts = [] + for h in history: + o = h["outcome"] + if o.get("failure") in ("rode_along", "board_not_moved"): + e = 0.10 + elif o.get("failure") in ("touched_cube", "several_pulls"): + continue + else: + e = o["err"] + pts.append((h["params"]["speed"], e)) + hi_err = [p for p in pts if p[1] > 0] # moved too much -> needs a faster pull + lo_err = [p for p in pts if p[1] < 0] # moved too little -> needs a slower pull + if hi_err and lo_err: + (v0, e0) = max(hi_err, key=lambda p: p[0]) # fastest pull that still moved it too much + (v1, e1) = min(lo_err, key=lambda p: p[0]) # slowest pull that moved it too little + if e0 >= 0.05: # rode along: no usable slope -> bisect + v = 0.5 * (v0 + v1) + else: + v = v0 + (v1 - v0) * e0 / (e0 - e1) + elif hi_err: + v = max(p[0] for p in hi_err) * 1.25 + else: + v = min(p[0] for p in lo_err) * 0.8 + return dict(speed=float(np.clip(v, V_MIN, V_MAX))) + + def oracle_params(self, inst): + """Privileged: bisection on the speed by simulating pulls with the true mu.""" + if "_oracle_speed" in inst: + return dict(speed=inst["_oracle_speed"]) + lo, hi = V_MIN, V_MAX + best = None + for _ in range(10): + mid = 0.5 * (lo + hi) + self.reset_instance(inst) + self.execute(inst, dict(speed=mid)) + o = self.outcome(inst) + e = 0.10 if o["failure"] in ("rode_along", "board_not_moved") else o["err"] + if o["success"]: + best = (mid, e) + break + if best is None or abs(e) < abs(best[1]): + best = (mid, e) + if e > 0: + lo = mid + else: + hi = mid + inst["_oracle_speed"] = best[0] + self.reset_instance(inst) + return dict(speed=best[0]) diff --git a/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/l6_sequence.py b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/l6_sequence.py new file mode 100644 index 0000000000000000000000000000000000000000..3696302999af83efd1782ea6326db1f794452022 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/l6_sequence.py @@ -0,0 +1,513 @@ +"""L6-C sequence_resume: weigh four items one by one in a given order; an emergency stop resets part of the work. + +Scene: four grocery items (cream cheese, butter, chocolate pudding, popcorn -- small flat boxes), each on its +own round pad (four identical dark pads, flat markers), and a scale (grey square platform, static fixture). +Pad / scale positions and the order are random per instance. + +Instruction: weigh the items one at a time in the given order. Weighing = put the item on the scale and let go; +the scale records a reading after the item has rested on it for 0.5 s and beeps. Then the item goes back on its +own pad before the next item is picked up. Every item must be weighed exactly once; the scale log cannot be +edited, so a second reading of an item or a reading out of turn is a terminal failure. + +Interruption ("emergency stop", once per episode, inside attempt 1): while the robot carries an item, the gripper +opens, a safety routine puts that item back on its own pad and the arm returns to its home pose. Hidden: how +many items had been weighed when it happened, w in {1..4} (uniform), and the phase: the carried item was on its +way to the scale (not yet weighed, phase A) or on its way back (already weighed, phase B); w = 4 is always +phase B. After the stop every item sits on its pad and the arm is at home: the picture looks like the start of +the task. Which item comes next (order[w], or "nothing, call done" for w = 4) is only in the agent's own history +(what it carried, whether the scale had beeped). + +Protocol: within (like l6_swap_interrupt). Events reported immediately (`drain_events`): the scale's beep after +every recorded reading, an error beep for a reading out of turn, and the emergency stop. F2 after `done` gives the +verdict, whether the log is complete, and which items are not on their pads (distance only), never how many +items have been weighed. + +Scripted references (perception = simulator state): + oracle privileged scale log: always weighs order[len(log)] next. + adaptive keeps its own record of readings (an item counts as weighed when the scale beeped while it lay on + it); after the stop it resumes from order[len(record)] (redoes the interrupted item in phase A, goes on + with the next one in phase B, calls done when all four are recorded). + naive memoryless continuation (1 attempt): the picture after the stop shows no progress; it guesses how far + it got (uniform over 0..4 items weighed) and continues from there. + blind memoryless restart (k attempts): starts the sequence over from the first item -> a second reading of + an already weighed item (repeated step). +Extra control (not in the acceptance table): `skip` counts items it *started* to weigh (pick-ups) instead of +readings: correct after a phase-B stop, skips the interrupted item after a phase-A stop. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, register_generated +from ..skills import ROT_SCALE, _rot_err +from ..task_base import LFFTask, register_task +from .l6_swap import _pad_xml as _swap_pad_xml + +ITEMS = ["cream_cheese_1", "butter_1", "chocolate_pudding_1", "popcorn_1"] +CATS = {"cream_cheese_1": "cream_cheese", "butter_1": "butter", "chocolate_pudding_1": "chocolate_pudding", + "popcorn_1": "popcorn"} +NAME = {"cream_cheese_1": "cream cheese", "butter_1": "butter", "chocolate_pudding_1": "chocolate pudding", + "popcorn_1": "popcorn"} +DESCR = {"cream_cheese_1": "the pale blue box with the oval logo", "butter_1": "the red box with white lettering", + "chocolate_pudding_1": "the dark brown box", "popcorn_1": "the blue-and-yellow box"} +N_ITEMS = len(ITEMS) +PADS = [f"pad_{i + 1}" for i in range(N_ITEMS)] +PAD_R = 0.055 +PAD_HALF_T = 0.0008 + +SCALE_HALF = 0.06 # platform half size (12 x 12 cm) +SCALE_BASE_HALF = 0.067 +SCALE_TOP = 0.020 # platform top above the table +SCALE_BASE_H = 0.012 +SCALE_RGBA = (0.78, 0.79, 0.80, 1.0) +SCALE_BASE_RGBA = (0.20, 0.20, 0.22, 1.0) + +BASE_X = -0.66 +REGION = (-0.27, 0.05, -0.27, 0.27) +REACH = 0.70 +PAD_MIN = 0.16 +SCALE_MIN = 0.175 +SUCC_R = 0.04 # item centre within 4 cm of its pad centre +GRASP_DZ = 0.012 # gripper-site height above the support surface for a top-down grasp of the flat boxes +Z_CARRY = envs.TABLE_Z + 0.15 +DWELL = 10 # control steps (0.5 s) at rest on the scale before a reading is recorded +LIFTED = 0.04 + + +def scale_xml(model_name): + parts = [((0, 0, SCALE_BASE_H / 2), (SCALE_BASE_HALF, SCALE_BASE_HALF, SCALE_BASE_H / 2), SCALE_BASE_RGBA), + ((0, 0, (SCALE_BASE_H + SCALE_TOP) / 2), (SCALE_HALF, SCALE_HALF, (SCALE_TOP - SCALE_BASE_H) / 2), + SCALE_RGBA)] + g = [] + for k, (pos, half, rgba) in enumerate(parts): + g.append(f' ') + g.append(f' ') + return _wrap(model_name, "\n".join(g), SCALE_TOP / 2, float(np.hypot(SCALE_BASE_HALF, SCALE_BASE_HALF))) + + +def _yaw_of(env, obj): + R = env.sim.data.body_xmat[envs.body_id(env, obj)].reshape(3, 3) + yaw = float(np.arctan2(R[1, 0], R[0, 0])) # long axis of the boxes = body x + return (yaw + np.pi / 2) % np.pi - np.pi / 2 + + +@register_task +class SequenceResume(LFFTask): + name = "l6_sequence_resume" + level = "L6" + category = "procedural_memory" + capabilities = ("Perceive", "Save", "Retrieve", "Utilize") + protocol = "within" + agent_max_steps = 100 # robot commands per attempt for agents (a VLM needs ~60-75) + max_attempts = 5 + _TEMPLATE = ("Weigh the four grocery items one at a time, in this order: {order}. To weigh an item, put it on " + "the grey scale and let go of it; the scale beeps when it has recorded the reading. Then put the " + "item back on its own round pad before you pick up the next item. Weigh every item exactly once: " + "the scale logs every reading, and the log cannot be edited.") + instruction = _TEMPLATE.format(order="(given per instance)") + instruction_indirect = instruction + inject = True + agent_object_names = [NAME[i] for i in ITEMS] + ["scale", "round pads"] + + def agent_instruction(self, inst, variant="direct"): + names = DESCR if variant == "indirect" else NAME + order = [names[o] for o in inst["order"]] + return self._TEMPLATE.format(order=", ".join(order[:-1]) + ", then " + order[-1]) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + self._mon = False + self._latch = None + orig_step = self.env.step + + def step(action): # per-control-step monitor (also for attempts driven by the agent harness) + if self._latch is not None: + action = self._homing_action() + ret = orig_step(action) + if self._mon: + self._monitor() + return ret + + self.env.step = step + + # ------------------------------------------------------------ scene + def make_bddl(self): + pads = [register_generated(f"LffSeqPad{L}", _swap_pad_xml(f"lff_seq_pad_{L.lower()}")) for L in "ABCD"] + scale = register_generated("LffSeqScale", scale_xml("lff_seq_scale"), free=False) + objs = [(o, CATS[o], f"r{i}", (-0.26 + 0.15 * i - 0.01, -0.31, -0.26 + 0.15 * i + 0.01, -0.29)) + for i, o in enumerate(ITEMS)] + objs += [(PADS[i], pads[i], f"p{i}", (-0.26 + 0.15 * i - 0.01, 0.29, -0.26 + 0.15 * i + 0.01, 0.31)) + for i in range(N_ITEMS)] + fx = [("scale_1", scale, "scale_region", (0.19, -0.01, 0.21, 0.01))] + return write_bddl(self.name, "Weigh the four items one at a time in the given order", objs, fx) # no ; in BDDL + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + for _ in range(5000): + pts = [] + while len(pts) < N_ITEMS + 1: + p = np.array([rng.uniform(*REGION[:2]), rng.uniform(*REGION[2:])]) + if np.hypot(p[0] - BASE_X, p[1]) > REACH: + continue + pts.append(p) + scale, pads = pts[0], np.array(pts[1:]) + dp = [np.linalg.norm(pads[i] - pads[j]) for i in range(N_ITEMS) for j in range(i)] + if min(dp) >= PAD_MIN and min(np.linalg.norm(pads - scale, axis=1)) >= SCALE_MIN: + break + else: + raise RuntimeError("could not sample a layout") + order = [ITEMS[i] for i in rng.permutation(N_ITEMS)] + w = int(rng.integers(1, N_ITEMS + 1)) # items weighed when the stop happens + phase = "B" if w == N_ITEMS else str(rng.choice(["A", "B"])) + inst = dict(seed=int(seed), order=order, pads=pads.round(4).tolist(), scale_xy=scale.round(4).tolist(), + item_off=[[float(v) for v in rng.uniform(-0.008, 0.008, 2)] for _ in range(N_ITEMS)], + item_yaw=[float(v) for v in rng.uniform(-0.3, 0.3, N_ITEMS)], + stop_w=w, stop_phase=phase, trigger_dist=float(rng.uniform(0.05, 0.09)), + stop_off=[float(v) for v in rng.uniform(-0.008, 0.008, 2)], + stop_yaw=float(rng.uniform(-0.3, 0.3))) + inst["stop_item"] = order[w] if phase == "A" else order[w - 1] + self.instruction = self.agent_instruction(inst, "direct") # make_video prints task.instruction + self.instruction_indirect = self.agent_instruction(inst, "indirect") + return inst + + def apply_instance(self, inst): + m = self.env.sim.model + for i, p in enumerate(inst["pads"]): + envs.set_obj_pose(self.env, PADS[i], [p[0], p[1], envs.TABLE_Z + PAD_HALF_T + 0.0001]) + bid = m.body_name2id(self.env.fixtures_dict["scale_1"].root_body) + m.body_pos[bid] = [inst["scale_xy"][0], inst["scale_xy"][1], envs.TABLE_Z] + m.body_quat[bid] = [1, 0, 0, 0] + for i, o in enumerate(ITEMS): + p = np.asarray(inst["pads"][i]) + inst["item_off"][i] + envs.place_upright(self.env, o, p, inst["item_yaw"][i]) + self.env.sim.forward() + self._inst = inst + self.pad_of = {o: i for i, o in enumerate(ITEMS)} # item i starts on pad i (pad positions are random) + self.log = [] # scale readings (item names) + self.error = None + self.stop = None + self.events = [] + self._event_cursor = 0 + self._outcome_cursor = 0 + self._dwell = {o: 0 for o in ITEMS} + self._visit = {o: False for o in ITEMS} + self._prev = {} + self._latch = None + self._mon = False + + def reset_instance(self, inst, recorder=None): + self._mon = False + self._latch = None + sk = super().reset_instance(inst, recorder=recorder) + self._home = sk.eef_pos() + self.rest_dz = {o: float(envs.obj_pos(self.env, o)[2] - envs.TABLE_Z) for o in ITEMS} + self._prev = {o: envs.obj_pos(self.env, o) for o in ITEMS} + self._mon = True + return sk + + def go_home(self): + p = self.sk.eef_pos() + self.sk.move_to([p[0], p[1], max(p[2], self._home[2])]) + self.sk.move_to(self._home) + + # ------------------------------------------------------------ helpers + def scale_xy(self): + return np.asarray(self._inst["scale_xy"], float) + + def pad_xy(self, o): + return np.asarray(self._inst["pads"][self.pad_of[o]], float) + + def on_scale(self, o, p=None): + p = envs.obj_pos(self.env, o) if p is None else p + d = np.abs(p[:2] - self.scale_xy()) + return bool(d.max() <= SCALE_HALF and abs(p[2] - (envs.TABLE_Z + SCALE_TOP + self.rest_dz[o])) < 0.008) + + def on_own_pad(self, o): + p = envs.obj_pos(self.env, o) + return bool(np.linalg.norm(p[:2] - self.pad_xy(o)) <= SUCC_R + and abs(p[2] - (envs.TABLE_Z + self.rest_dz[o])) < 0.01 and not self.sk.holding(o)) + + # ------------------------------------------------------------ monitor: scale readings + emergency stop + def _monitor(self): + env = self.env + if self._latch is not None: + if len(self.sk.log) > self._latch and np.linalg.norm(self.sk.eef_pos() - self._home) < 0.01: + self._latch = None + for o in ITEMS: + p = envs.obj_pos(env, o) + still = np.linalg.norm(p - self._prev[o]) < 0.0008 + self._prev[o] = p + if self.on_scale(o, p): + if still and not self.sk.holding(o): + self._dwell[o] += 1 + if self._dwell[o] >= DWELL and not self._visit[o]: + self._visit[o] = True + self._record(o) + else: + self._dwell[o] = 0 + else: + self._dwell[o] = 0 + if np.abs(p[:2] - self.scale_xy()).max() > SCALE_HALF or \ + p[2] > envs.TABLE_Z + SCALE_TOP + self.rest_dz[o] + 0.02: + self._visit[o] = False + if self.inject and self.stop is None: + self._maybe_stop() + + def _record(self, o): + self.log.append(o) + k = len(self.log) + ok = self.log == self._inst["order"][:k] + if ok: + self.events.append(dict(step=int(self.sk.n_steps), kind="beep", obj=o, + text="The scale beeped: reading recorded.")) + else: + if self.error is None: + self.error = dict(item=o, position=k, step=int(self.sk.n_steps), + kind="repeat" if self.log.count(o) > 1 else "out_of_order") + self.events.append(dict(step=int(self.sk.n_steps), kind="error", obj=o, + text="The scale beeped three times: error, this reading does not follow the " + "requested order. The log cannot be edited.")) + + def _maybe_stop(self): + inst = self._inst + o, w = inst["stop_item"], inst["stop_w"] + if self.log != inst["order"][:w]: + return + p = envs.obj_pos(self.env, o) + if inst["stop_phase"] == "A": + if p[2] < envs.TABLE_Z + self.rest_dz[o] + LIFTED: + return + if np.linalg.norm(p[:2] - self.pad_xy(o)) < inst["trigger_dist"]: + return + else: + if p[2] < envs.TABLE_Z + SCALE_TOP + self.rest_dz[o] + LIFTED: + return + if np.linalg.norm(p[:2] - self.scale_xy()) < inst["trigger_dist"]: + return + if not self.sk.holding(o): + return + self._do_stop(o) + + def _do_stop(self, o): + inst = self._inst + xy = self.pad_xy(o) + np.asarray(inst["stop_off"]) + envs.place_upright(self.env, o, xy, inst["stop_yaw"]) + self.sk.grip = -1.0 + self.sk.yaw = 0.0 + self._latch = len(self.sk.log) # drive the arm home until the current primitive has returned + self._prev[o] = envs.obj_pos(self.env, o) + self.env.sim.forward() + text = ("Emergency stop! The gripper opened, the safety routine put the item the robot was holding back on " + "its pad and moved the arm to its home pose. You may continue the task.") + self.stop = dict(item=o, phase=inst["stop_phase"], weighed=len(self.log), step=int(self.sk.n_steps)) + self.events.append(dict(step=int(self.sk.n_steps), kind="stop", obj=o, text=text)) + + def _homing_action(self): + sk = self.sk + a = np.zeros(self.env.action_dim) + a[:3] = np.clip((self._home - sk.eef_pos()) / sk.pos_scale, -1, 1) + a[3:6] = np.clip(_rot_err(sk.R0, sk.eef_mat()) / ROT_SCALE, -1, 1) + a[6] = -1.0 + return a + + def drain_events(self): + ev = self.events[self._event_cursor:] + self._event_cursor = len(self.events) + return [e["text"] for e in ev] + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + envs.settle(self.env, 20) + order = inst["order"] + complete = self.log == order + terminal = self.error is not None + off = [o for o in ITEMS if not self.on_own_pad(o)] + success = bool(complete and not off and not terminal) + if success: + head = "All four items were weighed once, in the requested order, and are back on their pads." + elif terminal: + head = ("The scale log does not follow the requested order (an item was weighed a second time or out " + "of turn). The log cannot be edited, so the task can no longer be completed.") + elif complete: + head = "Every item has been weighed, but not every item is back on its own pad." + else: + head = "Not every item has been weighed yet." + parts = [] + if not success and not terminal: + for o in off: + p = envs.obj_pos(self.env, o) + if self.sk.holding(o): + parts.append(f"the {NAME[o]} is still in the gripper") + elif self.on_scale(o, p): + parts.append(f"the {NAME[o]} is on the scale") + else: + d = np.linalg.norm(p[:2] - self.pad_xy(o)) + parts.append(f"the {NAME[o]} is {100 * d:.0f} cm from the centre of its pad") + detail = head + (" Also: " + "; ".join(parts) + "." if parts else "") + new = [e for e in self.events[self._outcome_cursor:] if e["kind"] == "stop"] + self._outcome_cursor = len(self.events) + if new: + detail = "During this attempt: " + " ".join(e["text"] for e in new) + " " + detail + return dict(success=success, terminal=terminal, log=[NAME[o] for o in self.log], n_weighed=len(self.log), + complete=complete, error=self.error, stop=self.stop, + off_pad=[NAME[o] for o in off], detail=detail) + + # ------------------------------------------------------------ motion (scripted policies) + def _support_z(self, o): + p = envs.obj_pos(self.env, o) + return envs.TABLE_Z + (SCALE_TOP if self.on_scale(o, p) or + (np.abs(p[:2] - self.scale_xy()).max() < SCALE_HALF) else 0.0) + + def _n_stops(self): + return sum(e["kind"] == "stop" for e in self.events) + + def _pick(self, o): + sk = self.sk + for _ in range(2): + p = envs.obj_pos(self.env, o) + sk.grasp_at(p[:2], self._support_z(o) + GRASP_DZ, yaw=_yaw_of(self.env, o), lift=0.12) + if sk.holding(o): + return True + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], self._support_z(o) + GRASP_DZ + 0.12]) + return False + + def _carry_to(self, o, xy, z_support): + """Carry the held item to xy and put it down. Returns False if an emergency stop happened.""" + sk = self.sk + n0 = self._n_stops() + sk.move_to([xy[0], xy[1], Z_CARRY]) + if self._n_stops() > n0: + return False + sk.move_to([xy[0], xy[1], z_support + GRASP_DZ + 0.004], tol=0.004) + sk.set_gripper(False, steps=12) + sk.move_to([xy[0], xy[1], z_support + GRASP_DZ + 0.10]) + return self._n_stops() == n0 + + def _weigh(self, o): + """Weigh one item (pad -> scale -> pad). Returns (status, beeped): status 'ok' / 'stop_A' / 'stop_B' / + 'no_grasp'; beeped = the scale beeped while the item lay on it (what the agent hears).""" + n_beep = sum(e["kind"] in ("beep", "error") for e in self.events) + if not self._pick(o): + return "no_grasp", False + if not self._carry_to(o, self.scale_xy(), envs.TABLE_Z + SCALE_TOP): + return "stop_A", False + self.sk.hold(6) + beeped = sum(e["kind"] in ("beep", "error") for e in self.events) > n_beep + if not self._pick(o): + return "no_grasp", beeped + if not self._carry_to(o, self.pad_xy(o), envs.TABLE_Z): + return "stop_B", beeped + return "ok", beeped + + def _fix_pads(self, log): + for o in ITEMS: + if not self.on_own_pad(o) and not self.on_scale(o): + if self._pick(o): + self._carry_to(o, self.pad_xy(o), envs.TABLE_Z) + log.append((NAME[o], "back to pad")) + + def _run_from(self, k, record, log, stop_on_stop=False): + """Weigh order[k:] in turn, keeping `record` (the policy's own list of readings it heard).""" + order = self._inst["order"] + i = k + guard = 0 + while i < len(order) and guard < 10 and self.error is None: + guard += 1 + o = order[i] + st, beeped = self._weigh(o) + log.append((NAME[o], st, beeped)) + if beeped: + record.append(o) + if st == "no_grasp": + continue + if st.startswith("stop"): + if stop_on_stop: + return "stopped" + i = len(record) # resume from the own record + continue + i += 1 + return "ok" + + # ------------------------------------------------------------ scripted references (within protocol) + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed + 104729) + self.reset_instance(inst) + order = inst["order"] + history = [] + record = [] # adaptive's Save: readings it heard + for a in range(k): + log = [] + plan = dict(kind=kind, steps=log) + if a == 0: + if kind == "oracle": + while len(self.log) < len(order) and self.error is None and len(log) < 12: + o = order[len(self.log)] # privileged scale log + st, _ = self._weigh(o) + log.append((NAME[o], st)) + plan["recovery"] = "oracle: privileged scale log" + elif kind == "adaptive": + self._run_from(0, record, log) + plan["recovery"] = "own record of readings: resume from order[len(record)]" + elif kind == "skip": + started = [] + i = 0 + while i < len(order) and self.error is None and len(log) < 12: + o = order[i] + st, beeped = self._weigh(o) + log.append((NAME[o], st, beeped)) + if st == "no_grasp": + continue + started.append(o) + i = len(started) # counts started items, not readings + plan["recovery"] = "counts items it started to weigh (the interrupted one too)" + else: # memoryless after the stop + r = self._run_from(0, record, log, stop_on_stop=True) + if r == "stopped": + if kind == "naive": + g = int(rng.integers(0, len(order) + 1)) + plan["recovery"] = f"memoryless: guesses {g} items already weighed" + self._run_from(g, [], log) + elif kind == "blind": + plan["recovery"] = "memoryless restart from the first item" + self._run_from(0, [], log) + else: + raise ValueError(kind) + else: + plan["recovery"] = "none (no stop)" + else: + if kind in ("adaptive", "oracle", "skip"): + plan["recovery"] = "memory + F2: put items back on their pads / finish from own record" + if kind == "adaptive" and len(record) < len(order): + self._run_from(len(record), record, log) + if kind == "skip" and not history[-1]["outcome"]["complete"]: + # F2 says the log is incomplete: with memory, the item carried at the stop was not weighed + stopped = [s[0] for h in history for s in h["params"]["steps"] if str(s[1]).startswith("stop")] + if stopped: + o = next(i for i in ITEMS if NAME[i] == stopped[-1]) + st, _ = self._weigh(o) + log.append((NAME[o], st)) + plan["recovery"] = "memory + F2 'not every item weighed': weigh the item carried at the stop" + self._fix_pads(log) + elif kind == "blind": + plan["recovery"] = "memoryless restart from the first item" + self._run_from(0, [], log) + else: + raise ValueError(kind) + self.go_home() + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=plan, outcome=out)) + if on_attempt: + on_attempt(a, plan, out) + if out["success"] or out["terminal"] or kind in ("oracle", "naive"): + break + return history + + def default_params(self, inst): + return dict(policy="naive") + + def oracle_params(self, inst): + return dict(policy="oracle") diff --git a/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/lh_split_calibration.py b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/lh_split_calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..af67f706117835300db6f39fd3f3a38a3933edcc --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/lh_split_calibration.py @@ -0,0 +1,142 @@ +"""Two-workstation packing: calibration transfer, collateral damage, geometric fit. + +A repeatable command-coordinate calibration varies with workstation (sign of y), +not with phase or policy. No object poses are written after reset. Learning a +far-workstation correction and blindly reusing it at the near destination can +undo the earlier placement. A long module must also be aligned with its tray. +""" +import numpy as np +import xml.etree.ElementTree as ET +from .. import envs +from ..bddl import write_bddl +from ..objects import box_xml,bin_xml,register_generated +from ..skills import Skills +from ..task_base import LFFTask,register_task +from .lh_shelf_droop import jar_xml,JAR_H,KNOB_Z +from .lh_lid_box import mark_xml + +RED='module_red_1';BLUE='module_blue_1';HALF=np.array([.045,.012,.012]) +class SplitSkills(Skills): + def __init__(self,env,task,recorder=None): + super().__init__(env,recorder=recorder);self.task=task;self.correction=np.zeros(3) + def move_to(self,target,*a,**kw): + q=np.array(target)-self.correction + self.bias=np.array(self.task.inst['far_bias'] if q[1]>.04 else self.task.inst['near_bias']) + rep=super().move_to(q,*a,**kw);rep['pos']=np.round(self.reported_eef_pos(),4).tolist();return rep + def reported_eef_pos(self):return self.eef_pos()-self.bias + def _act(self,dpos,drot,grip): + super()._act(dpos,drot,grip);self.task.monitor_step() + +@register_task +class SplitCalibration(LFFTask): + name='lh_split_calibration';level='L1';category='system_identification';failure_causes=('L1','L2','L4');failure_types=failure_causes + protocol='cross';max_attempts=5;agent_max_steps=240 + instruction=('Prepare the two modules for handover: stand the red module on its red square, and fit the entire ' + 'long blue module inside the narrow tray. Leave both released and stable, with the gripper open ' + 'and clear. The red module has a graspable top knob. The work areas are on opposite sides of the desk.') + instruction_indirect=('Stand the tall module with the round top on its matching square, and fit the entire elongated module inside the narrow open tray. Leave both released and stable, with the gripper open and clear.');capabilities=('Perceive','Reason','Plan','Restore') + def make_bddl(self): + rr=ET.fromstring(jar_xml('split_red',(.8,.15,.1,1))) + for g in rr.findall('.//geom'): + if g.get('type')=='box': + sz=np.fromstring(g.get('size'),sep=' ');sz[:2]*=.6;g.set('size',' '.join(map(str,sz))) + r=register_generated('LffSplitRed',ET.tostring(rr,encoding='unicode')) + b=register_generated('LffSplitBlue',box_xml('split_blue',HALF,(.1,.3,.85,1),density=1000)) + tray=register_generated('LffSplitTray',bin_xml('split_tray',(.051,.019),.022),free=False) + mark=register_generated('LffSplitMark',mark_xml('split_mark',(.8,.1,.1,1)),free=False) + return write_bddl(self.name,self.instruction,[(RED,r,'red_region',(-.36,-.16,-.35,-.15)),(BLUE,b,'blue_region',(-.17,.23,-.16,.24))], + [('tray_1',tray,'tray_region',(.2,-.3,.21,-.29)),('mark_1',mark,'mark_region',(.2,.3,.21,.31))]) + def sample_instance(self,seed): + rng=np.random.default_rng(seed);v=float(rng.uniform(.053,.057)) + return dict(seed=seed,near_bias=[0,-v,0],far_bias=[0,v,0],red_xy=[-.35,-.12],blue_xy=[-.16,.24],red_goal=[-.22,-.24],blue_goal=[-.21,-.13]) + def apply_instance(self,i): + self.inst=i;m=self.env.sim.model + envs.set_obj_pose(self.env,RED,[*i['red_xy'],envs.TABLE_Z+JAR_H/2+.001]);envs.scale_mass(self.env,RED,.08) + envs.set_obj_pose(self.env,BLUE,[*i['blue_xy'],envs.TABLE_Z+HALF[2]+.001],yaw=np.pi/2) + for name,xy,z in [('tray_1',i['blue_goal'],.914),('mark_1',i['red_goal'],.901)]: + m.body_pos[m.body_name2id(self.env.fixtures_dict[name].root_body)]=[*xy,z] + def reset_instance(self,i,recorder=None): + np.random.seed(i['seed']);self.mon=None;self.env.reset();self.apply_instance(i);self.env.sim.forward();envs.settle(self.env,10) + self.sk=SplitSkills(self.env,self,recorder);self.trace=[];self.phase_hook=None;self.traps={k:False for k in self.failure_causes};self.recovered=self.traps.copy() + self.mon=dict(red_ever=False,red_lost=False,red_restored=False);return self.sk + def red_ok(self): + p=envs.obj_pos(self.env,RED);R=self.env.sim.data.body_xmat[envs.body_id(self.env,RED)].reshape(3,3) + return bool(np.linalg.norm(p[:2]-self.inst['red_goal'])<.022 and R[2,2]>.96 and abs(p[2]-(.9+JAR_H/2))<.008 and not self.sk.holding(RED)) + def blue_ok(self): + p=envs.obj_pos(self.env,BLUE);R=self.env.sim.data.body_xmat[envs.body_id(self.env,BLUE)].reshape(3,3) + corners=np.array([p+R@(HALF*[a,b,c]) for a in (-1,1) for b in (-1,1) for c in (-1,1)]) + return bool(np.all(np.abs(corners[:,:2]-self.inst['blue_goal'])<[.052,.020]) and corners[:,2].max()<.936 and corners[:,2].min()>.903 and not self.sk.holding(BLUE)) + def monitor_step(self): + if self.mon is None:return + ok=self.red_ok() + if ok: + if self.mon['red_lost']:self.mon['red_restored']=True + self.mon['red_ever']=True + elif self.mon['red_ever'] and not self.sk.holding(RED):self.mon['red_lost']=True + def label(self,text): + r=dict(text=text,step=self.sk.n_steps,red_ok=self.red_ok(),blue_ok=self.blue_ok(),red_xyz=envs.obj_pos(self.env,RED).tolist(),blue_xyz=envs.obj_pos(self.env,BLUE).tolist());self.trace.append(r) + if self.phase_hook:self.phase_hook(text,r) + def observe_offset(self,xy): + s=self.sk;q=np.array([*xy,1.18]);s.move_to(q);return (s.eef_pos()-q+s.correction)*[1,1,0] + def pick(self,name,yaw=None): + s=self.sk;p=envs.obj_pos(self.env,name);R=self.env.sim.data.body_xmat[envs.body_id(self.env,name)].reshape(3,3) + if name==RED: + goal=p+R@np.array([0,0,KNOB_Z-JAR_H/2]);yaw=float(np.arctan2(R[1,2],R[0,2])) if R[2,2]<.7 else 0 + else: + goal=p.copy();yaw=float(np.arctan2(R[1,0],R[0,0])) if yaw is None else yaw + s.set_gripper(False,8);s.move_to([*goal[:2],1.20],yaw=yaw);s.move_to(goal,yaw=yaw,speed=.08,max_steps=150);s.set_gripper(True,20) + s.move_to([*goal[:2],1.20],speed=.1);s.hold(20);return bool(s.holding(name)) + def place(self,name,xy,z,yaw): + s=self.sk;off=envs.obj_pos(self.env,name)-s.eef_pos();s.move_to([*s.eef_pos()[:2],1.20],yaw=yaw) + # Update the held offset after rotating the module. + off=envs.obj_pos(self.env,name)-s.eef_pos();goal=np.array([*xy,z])-off + s.move_to([*goal[:2],1.20],yaw=yaw);s.move_to(goal,yaw=yaw,speed=.08,max_steps=160) + s.set_gripper(False,12);s.move_to([*goal[:2],1.23]);s.hold(40) + def execute(self,i,p): + mode=p.get('mode','adaptive');s=self.sk + if mode=='blind':s.correction=np.array(p.get('jitter',[0,0,0])) + self.label('Two workstations: preserve earlier placements') + if mode=='oracle':near=np.array(i['near_bias']) + else: + near=self.observe_offset(i['red_xy']);ok=self.pick(RED);self.traps['L1']=not ok;self.label('L1: near-workstation grasp missed') + if mode in ('naive','blind') and not ok:return + if mode not in ('naive','blind'):s.correction=near + if not self.pick(RED):self.label('Red pickup failed');return + self.recovered['L1']=True;self.place(RED,i['red_goal'],.9+JAR_H/2+.003,0);self.label('Red module placed correctly') + if mode=='oracle':far=np.array(i['far_bias']) + else: + ok=self.pick(BLUE);self.label('L1 transfer: near correction fails at the far workstation') + if mode in ('naive','blind'): + if not ok:return + self.place(BLUE,i['blue_goal'],.922,np.pi/2);return + far=self.observe_offset(i['blue_xy']) + s.correction=far + if not self.pick(BLUE):self.label('Far pickup failed');return + if mode!='oracle': + self.place(BLUE,i['blue_goal'],.922,np.pi/2);self.traps['L2']=bool(not self.red_ok());self.label('L2: reusing far correction disturbed the red module') + s.correction=near + if not self.pick(RED):self.label('Red restoration pickup failed');return + self.place(RED,[-.40,-.28],.9+JAR_H/2+.003,0);self.label('Clear the disturbed red module before recovering the blue module') + if not self.pick(BLUE):self.label('Blue recovery pickup failed');return + self.place(BLUE,i['blue_goal'],.922,np.pi/2);self.traps['L4']=not self.blue_ok();self.label('L4: the long module bridges the narrow tray') + if not self.pick(RED):return + self.place(RED,i['red_goal'],.9+JAR_H/2+.003,0);self.recovered['L2']=self.red_ok();self.label('L2 recovery: restored red using the near-workstation correction') + if not self.pick(BLUE):self.label('Blue alignment pickup failed');return + s.correction=near;self.place(BLUE,i['blue_goal'],.920,0);self.recovered['L4']=self.blue_ok();self.label('Aligned module fits; recheck both completed placements') + if not self.red_ok(): + if self.pick(RED):self.place(RED,i['red_goal'],.9+JAR_H/2+.003,0) + s.set_gripper(False,8);s.move_to([-.40,-.05,1.25]);s.hold(30) + def outcome(self,i): + self.sk.hold(100);stages=dict(red_on_mark=self.red_ok(),blue_in_tray=self.blue_ok(),gripper_open=bool(self.sk.grip<0),gripper_clear=bool(self.sk.eef_pos()[2]>1.13)) + static=all(np.linalg.norm(self.env.sim.data.qvel[envs.free_joint_addr(self.env,n)[1]:envs.free_joint_addr(self.env,n)[1]+6])<.06 for n in (RED,BLUE)) + return dict(success=bool(all(stages.values()) and static),stages=stages,static=bool(static),traps=self.traps.copy(),recovered=self.recovered.copy(),detail=str(stages)) + def default_params(self,i):return {'mode':'naive'} + def oracle_params(self,i):return {'mode':'oracle'} + def adapt_params(self,i,h):return {'mode':'adaptive'} + def run_scripted(self,kind,inst,k=None,seed=0,on_attempt=None): + hist=[] + for n in range((k or 5) if kind=='blind' else 1): + self.reset_instance(inst);params={'mode':kind};self.execute(inst,params);o=self.outcome(inst);hist.append(dict(attempt=n+1,params=params,outcome=o)) + if on_attempt:on_attempt(n+1,self.env,o) + if o['success']:break + return hist diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/batches.json b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/batches.json new file mode 100644 index 0000000000000000000000000000000000000000..d4b38db245deb76e1decea690e0a087085f272f0 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/batches.json @@ -0,0 +1,9 @@ +{ + "remaining_lh_20261103_deepseek": { + "source_manifest": "/mnt/cpfs/workspace/agentic-robotics/ops/remaining_lh_eval_20261103/source/runs/api/remaining_lh_20261103_deepseek/manifest.json", + "supplement": true, + "selected_runs": 25, + "exported_runs": 25, + "note": "Original condition and feedback dossier are in each episode annotation source.evaluation_config." + } +} diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/rejected.json b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/rejected.json new file mode 100644 index 0000000000000000000000000000000000000000..0637a088a01e8ddab3bf3fa98dbe804cbde1a0dc --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/rejected.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/agent/backends/base.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/agent/backends/base.py new file mode 100644 index 0000000000000000000000000000000000000000..214f2e2f1a11942180f655914409b7d43b45723d --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/agent/backends/base.py @@ -0,0 +1,82 @@ +"""Backend interface: a backend maps a conversation (+ tool specs) to the next tool call(s).""" +import os +import sys +from dataclasses import dataclass, field +from typing import Optional + +# Normally the API SDKs (`openai`, `anthropic`, `google-genai`) are installed in the venv (setup/install.sh). +# Optionally they can live in a separate `pip install --target` directory, given by LFF_API_SDK_DIR (older name: +# LFF_OPENAI_SDK_DIR), that is APPENDED to sys.path so every package already in the venv keeps precedence. +API_SDK_DIR = os.environ.get("LFF_API_SDK_DIR") or os.environ.get("LFF_OPENAI_SDK_DIR", "") +OPENAI_SDK_DIR = API_SDK_DIR # old name + + +def import_sdk(module): + """Import an API SDK module ("openai", "anthropic", "google.genai").""" + import importlib + try: + return importlib.import_module(module) + except ImportError: + if API_SDK_DIR and os.path.isdir(API_SDK_DIR) and API_SDK_DIR not in sys.path: + sys.path.append(API_SDK_DIR) + return importlib.import_module(module) + + +def import_openai(): + return import_sdk("openai") + + +@dataclass +class BackendResponse: + tool_calls: list = field(default_factory=list) # [ToolCall] + text: Optional[str] = None # visible assistant text (e.g. the diagnosis) + reasoning_summary: Optional[str] = None + usage: dict = field(default_factory=dict) # input_tokens, cached_tokens, output_tokens, reasoning_tokens + latency_s: float = 0.0 + raw: Optional[list] = None # backend-specific items to replay in later requests (e.g. reasoning items) + request_stats: dict = field(default_factory=dict) # n_images, n_items, bytes, ... + status: str = "ok" + error: Optional[str] = None + + +@dataclass +class RunInfo: + task: object # privileged: only the scripted backend may look at task / inst + inst: dict + seed: int + k: int + protocol: str + feedback: str + memory: str + + +@dataclass +class AttemptInfo: + attempt: int + history: list # AttemptRecords visible to the agent under the memory mode (already selected) + continuing: bool = False # within protocol: continuing after a failed done + + +class Backend: + name = "base" + + def begin_run(self, info: RunInfo): + pass + + def begin_attempt(self, info: AttemptInfo): + pass + + def act(self, conv, tools) -> BackendResponse: + raise NotImplementedError + + def on_tool_result(self, call, result): + pass + + def end_attempt(self) -> dict: + return {} + + def end_run(self): + pass + + def config(self) -> dict: + return dict(name=self.name) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/agent/backends/chat_completions.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/agent/backends/chat_completions.py new file mode 100644 index 0000000000000000000000000000000000000000..ec6c2cebb3976390ef7ed172d4b8edbb870a092f --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/agent/backends/chat_completions.py @@ -0,0 +1,150 @@ +"""OpenAI-compatible Chat Completions backend (function calling), e.g. for a local open-source VLM served +by scripts/qwen_vl_server.py or any vLLM / SGLang endpoint. Same conversation, different wire format. + +Reasoning models on this API (Kimi, DeepSeek, vLLM reasoning parsers) return their thinking as the non-standard +message field `reasoning_content`. It is logged as the reasoning summary and, with replay_reasoning (default), sent +back unchanged on that assistant message, so the model keeps its reasoning across tool calls like the Anthropic and +Responses backends do (Kimi's docs ask for this in multi-step tool use).""" +import json +import os +import time + +from ..context import ToolCall, prune_live_images +from .base import Backend, BackendResponse, import_openai + + +def chat_tools(specs): + return [dict(type="function", function=dict(name=s["name"], description=s["description"], + parameters=s["parameters"])) for s in specs] + + +class ChatCompletionsBackend(Backend): + name = "chat" + + def __init__(self, model="qwen3-vl-8b", base_url=None, api_key=None, temperature=0.0, max_tokens=1024, + max_live_images=4, jpeg_quality=90, timeout=600.0, client=None, extra_body=None, + replay_reasoning=True): + self.model = model + self.base_url = base_url or os.environ.get("LFF_CHAT_BASE_URL", "http://127.0.0.1:8765/v1") + self.api_key = api_key or os.environ.get("LFF_CHAT_API_KEY", "EMPTY") + self.temperature = temperature + self.max_tokens = max_tokens + self.max_live_images = max_live_images + self.jpeg_quality = jpeg_quality + self.timeout = timeout + self.extra_body = extra_body + self.replay_reasoning = replay_reasoning + self._client = client + + def config(self): + return dict(name=self.name, model=self.model, base_url=self.base_url, temperature=self.temperature, + max_tokens=self.max_tokens, max_live_images=self.max_live_images, + replay_reasoning=self.replay_reasoning) + + def client(self): + if self._client is None: + openai = import_openai() + kw = dict(api_key=self.api_key, base_url=self.base_url, timeout=self.timeout, max_retries=1) + if any(h in self.base_url for h in ("://127.0.0.1", "://localhost")): + # local server: ignore the machine's proxy variables (ALL_PROXY=socks5h://... is set here) + kw["http_client"] = openai.DefaultHttpxClient(trust_env=False, timeout=self.timeout) + self._client = openai.OpenAI(**kw) + return self._client + + def build_request(self, conv, tools): + msgs = [dict(role="system", content=conv.system)] + for it in prune_live_images(conv.items, self.max_live_images): + if it["kind"] == "user": + content = [] + for p in it["parts"]: + if p["type"] == "text": + content.append(dict(type="text", text=p["text"])) + else: + content.append(dict(type="image_url", image_url=dict(url=p["image"].data_url(self.jpeg_quality)))) + msgs.append(dict(role="user", content=content)) + elif it["kind"] == "assistant": + if not it.get("text") and not it["tool_calls"]: + # a reasoning-only turn (no text, no tool call; seen with DeepSeek at effort=max): the player still + # counts it and nudges, but OpenAI-compatible APIs reject an assistant message with neither content + # nor tool_calls (DeepSeek: 400 "content or tool_calls must be set"), so it is left out of the request + continue + m = dict(role="assistant", content=it.get("text") or None) + rc = (it.get("raw") or [{}])[0].get("reasoning_content") if it.get("backend") == self.name else None + if rc and self.replay_reasoning: + m["reasoning_content"] = rc + if it["tool_calls"]: + m["tool_calls"] = [dict(id=tc.id, type="function", + function=dict(name=tc.name, + arguments=tc.raw_arguments or json.dumps(tc.arguments))) + for tc in it["tool_calls"]] + msgs.append(m) + elif it["kind"] == "tool_output": + msgs.append(dict(role="tool", tool_call_id=it["call_id"], content=it["text"])) + req = dict(model=self.model, messages=tool_results_first(msgs), tools=chat_tools(tools), tool_choice="auto", + max_tokens=self.max_tokens) + if self.temperature is not None: # None: the endpoint's default (reasoning models may reject a temperature) + req["temperature"] = self.temperature + if self.extra_body: + req["extra_body"] = dict(self.extra_body) + return req + + def act(self, conv, tools): + req = self.build_request(conv, tools) + n_img = sum(1 for m in req["messages"] if isinstance(m.get("content"), list) + for c in m["content"] if c.get("type") == "image_url") + t0 = time.time() + resp = self.client().chat.completions.create(**req) + lat = time.time() - t0 + stats = dict(n_images=n_img, n_messages=len(req["messages"])) + if not getattr(resp, "choices", None): # gateway hiccup: nothing to append, the player asks again + return BackendResponse(latency_s=lat, request_stats=stats, status="incomplete", + error="empty response (no choices)") + msg = resp.choices[0].message + rc = getattr(msg, "reasoning_content", None) or (getattr(msg, "model_extra", None) or {}).get("reasoning_content") + calls = [] + for i, tc in enumerate(msg.tool_calls or []): + raw = tc.function.arguments or "" + try: + args = json.loads(raw) if raw else {} + except json.JSONDecodeError: + args = {} + calls.append(ToolCall(id=tc.id or f"call_{i}", name=tc.function.name, arguments=args, raw_arguments=raw)) + u = resp.usage + ctd = getattr(u, "completion_tokens_details", None) if u else None + usage = dict(input_tokens=getattr(u, "prompt_tokens", 0) or 0, cached_tokens=0, + output_tokens=getattr(u, "completion_tokens", 0) or 0, + reasoning_tokens=(getattr(ctd, "reasoning_tokens", 0) or 0) if ctd else 0) if u else {} + if not calls and not msg.content and not rc and not u: + return BackendResponse(latency_s=lat, request_stats=stats, status="incomplete", + error="empty response (no output, no usage)") + return BackendResponse(tool_calls=calls, text=msg.content or None, reasoning_summary=rc or None, usage=usage, + latency_s=lat, raw=[dict(reasoning_content=rc)] if rc else None, request_stats=stats) + + +def tool_results_first(msgs): + """OpenAI-compatible APIs require every tool_call of an assistant message to be answered by tool messages directly + after it. The player adds the images a tool returned (view_images, robot) as a user message right after that tool's + output, so a turn with several tool calls (e.g. view_images then shell) would put a user message between the tool + messages (DeepSeek: 400 "insufficient tool messages following tool_calls message"). Move such user messages after + the last tool message of the turn; nothing else changes order.""" + out, i = [], 0 + while i < len(msgs): + m = msgs[i] + out.append(m) + i += 1 + if m["role"] != "assistant" or not m.get("tool_calls"): + continue + need = {tc["id"] for tc in m["tool_calls"]} + held = [] + while i < len(msgs) and need: + n = msgs[i] + if n["role"] == "tool" and n.get("tool_call_id") in need: + out.append(n) + need.discard(n["tool_call_id"]) + elif n["role"] == "user": + held.append(n) + else: + break + i += 1 + out.extend(held) + return out diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/fakeapi.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/fakeapi.py new file mode 100644 index 0000000000000000000000000000000000000000..ba9482378574fd6e4fec4b25b958f94103ff4fee --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/fakeapi.py @@ -0,0 +1,188 @@ +"""Local fake model APIs for offline harness checks (no real model, no cost). + +Both servers listen on 127.0.0.1, record every request body (auth headers dropped) and answer from a script, so a +native harness can be driven turn by turn without a model: + FakeAnthropic Anthropic Messages API (streaming SSE), used by Claude Code and by api_player --provider anthropic + FakeResponses OpenAI Responses API (streaming SSE), used by Codex through a custom model provider + +A script is a list of turns; turn i is answered to the request that already holds i assistant turns, so retries get +the same answer. Past the end of the script the server answers with a final text. A turn is a list of steps: + ("tool", name, args) Anthropic: tool_use block (name as given, e.g. "mcp__lff__robot" or "Read") + ("text", s) a text block / assistant message + ("exec", js) Responses: one `exec` custom tool call (Codex code mode) with this JavaScript + ("fcall", name, args) Responses: a plain function call + ("nscall", ns, name, args) Responses: a function call into a tool namespace (Codex without code mode calls our MCP + tools this way: name "robot", namespace "mcp__lff"; measured with 0.163) + + srv = FakeAnthropic(script, record_dir).start(); ... srv.base_url ...; srv.stop() +""" +import itertools +import json +import os +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +DROP_HEADERS = ("x-api-key", "authorization", "cookie", "chatgpt-account-id") + + +class _Base: + final_text = "done" + + def __init__(self, script=None, record_dir=None, port=0): + self.script = list(script or []) + self.record_dir = record_dir + self.port = port + self.lock = threading.Lock() + self.counter = itertools.count(1) + self.requests = [] # (n, path, body) + if record_dir: + os.makedirs(record_dir, exist_ok=True) + + # ------------------------------------------------------------------ plumbing + def start(self): + outer = self + + class H(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *a): + pass + + def _record(self, body): + with outer.lock: + n = next(outer.counter) + outer.requests.append((n, self.path, body)) + if outer.record_dir: + with open(os.path.join(outer.record_dir, f"req_{n:03d}.json"), "w") as f: + json.dump(dict(method=self.command, path=self.path, body=body, + headers={k: v for k, v in self.headers.items() if k.lower() not in DROP_HEADERS}), + f, indent=1, ensure_ascii=False) + return n + + def do_GET(self): + self._record(None) + self._send(404, b"{}", "application/json") + + def do_HEAD(self): + self._send(404, b"", "application/json") + + def do_POST(self): + raw = self.rfile.read(int(self.headers.get("content-length", 0) or 0)) + try: + body = json.loads(raw) + except ValueError: + body = raw[:4000].decode("utf-8", "replace") + n = self._record(body) + outer.handle(self, n, body) + + def _send(self, code, data, ctype): + self.send_response(code) + self.send_header("content-type", ctype) + self.send_header("content-length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + self.httpd = ThreadingHTTPServer(("127.0.0.1", self.port), H) + self.httpd.daemon_threads = True + self.port = self.httpd.server_address[1] + threading.Thread(target=self.httpd.serve_forever, daemon=True).start() + return self + + def stop(self): + self.httpd.shutdown() + self.httpd.server_close() + + def turn(self, i): + return self.script[i] if i < len(self.script) else [("text", self.final_text)] + + @staticmethod + def send_sse(h, events): + data = b"".join(f"event: {ev}\ndata: {json.dumps(d)}\n\n".encode() for ev, d in events) + h._send(200, data, "text/event-stream") + + +class FakeAnthropic(_Base): + @property + def base_url(self): + return f"http://127.0.0.1:{self.port}" + + def handle(self, h, n, body): + if not h.path.startswith("/v1/messages") or "count_tokens" in h.path or not isinstance(body, dict): + h._send(200, json.dumps({"input_tokens": 10}).encode(), "application/json") + return + msgs = body.get("messages", []) + i = sum(1 for m in msgs if m.get("role") == "assistant") + steps = self.turn(i) + blocks = [] + for j, st in enumerate(steps): + if st[0] == "tool": + blocks.append(dict(type="tool_use", id=f"toolu_fake_{i:03d}_{j}", name=st[1], input=st[2])) + else: + blocks.append(dict(type="text", text=st[1])) + stop = "tool_use" if any(b["type"] == "tool_use" for b in blocks) else "end_turn" + model = body.get("model", "fake") + evs = [("message_start", dict(type="message_start", message=dict( + id=f"msg_fake_{n}", type="message", role="assistant", model=model, content=[], stop_reason=None, + stop_sequence=None, usage=dict(input_tokens=100, output_tokens=1))))] + for k, b in enumerate(blocks): + if b["type"] == "tool_use": + evs.append(("content_block_start", dict(type="content_block_start", index=k, content_block=dict( + type="tool_use", id=b["id"], name=b["name"], input={})))) + evs.append(("content_block_delta", dict(type="content_block_delta", index=k, delta=dict( + type="input_json_delta", partial_json=json.dumps(b["input"]))))) + else: + evs.append(("content_block_start", dict(type="content_block_start", index=k, + content_block=dict(type="text", text="")))) + evs.append(("content_block_delta", dict(type="content_block_delta", index=k, + delta=dict(type="text_delta", text=b["text"])))) + evs.append(("content_block_stop", dict(type="content_block_stop", index=k))) + evs.append(("message_delta", dict(type="message_delta", delta=dict(stop_reason=stop, stop_sequence=None), + usage=dict(output_tokens=5)))) + evs.append(("message_stop", dict(type="message_stop"))) + self.send_sse(h, evs) + + def message_requests(self): + return [(n, b) for n, p, b in self.requests if isinstance(b, dict) and p.startswith("/v1/messages") + and "count_tokens" not in p] + + +class FakeResponses(_Base): + @property + def base_url(self): + return f"http://127.0.0.1:{self.port}/v1" + + def handle(self, h, n, body): + if not isinstance(body, dict) or "input" not in body: + h._send(404, b"{}", "application/json") + return + items = body.get("input") or [] + i = sum(1 for it in items if isinstance(it, dict) and it.get("type") in + ("custom_tool_call", "function_call") or (isinstance(it, dict) and it.get("type") == "message" + and it.get("role") == "assistant")) + steps = self.turn(i) + out = [] + for j, st in enumerate(steps): + if st[0] == "exec": + out.append(dict(type="custom_tool_call", id=f"ctc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}", + name="exec", status="completed", input=st[1])) + elif st[0] == "fcall": + out.append(dict(type="function_call", id=f"fc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}", + name=st[1], arguments=json.dumps(st[2]), status="completed")) + elif st[0] == "nscall": + out.append(dict(type="function_call", id=f"fc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}", + namespace=st[1], name=st[2], arguments=json.dumps(st[3]), status="completed")) + else: + out.append(dict(type="message", id=f"msg_fake_{n}_{j}", role="assistant", status="completed", + content=[dict(type="output_text", text=st[1], annotations=[])])) + rid = f"resp_fake_{n}" + evs = [("response.created", dict(type="response.created", response=dict(id=rid, status="in_progress")))] + for k, it in enumerate(out): + evs.append(("response.output_item.done", dict(type="response.output_item.done", output_index=k, item=it))) + evs.append(("response.completed", dict(type="response.completed", response=dict( + id=rid, status="completed", output=out, usage=dict( + input_tokens=100, input_tokens_details=dict(cached_tokens=0), output_tokens=3, + output_tokens_details=dict(reasoning_tokens=0), total_tokens=103))))) + self.send_sse(h, evs) + + def model_requests(self): + return [(n, b) for n, p, b in self.requests if isinstance(b, dict) and "input" in b] diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-opus-5-5_high.json b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-opus-5-5_high.json new file mode 100644 index 0000000000000000000000000000000000000000..790b9765d6166fef8ab1d0980097be6659cdf933 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-opus-5-5_high.json @@ -0,0 +1,15 @@ +{ + "key": "claude_code_full-oauth|2.1.299|2d894a4b1bfaaa9a|claude-opus-5-5|high", + "fingerprint_sha256": "1e12511be3f4985ca25bad34cc2db4a0b317d6565b2d12034672aaac2d97bc85", + "written": "2026-10-21 05:19:32", + "summary": { + "system_chars": 5629, + "tools": [ + "mcp__lff__robot", + "mcp__lff__shell", + "mcp__lff__view_images" + ], + "effort_in_request": "high", + "model_in_request": "claude-opus-5-5" + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_deepseek-v4.1-flash_high.json b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_deepseek-v4.1-flash_high.json new file mode 100644 index 0000000000000000000000000000000000000000..4751a407d1b2c7151d0891509e63b7fbc9a0d4c1 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_deepseek-v4.1-flash_high.json @@ -0,0 +1,15 @@ +{ + "key": "claude_code_full|2.1.267|0399c793ff571d59|deepseek-v4.1-flash|high", + "fingerprint_sha256": "c5305ffa663057875e7ec2ef2900433eb510f1ee6b3fab7fb7acdca3c289cdc6", + "written": "2026-10-30 16:00:21", + "summary": { + "system_chars": 6052, + "tools": [ + "mcp__lff__robot", + "mcp__lff__shell", + "mcp__lff__view_images" + ], + "effort_in_request": "high", + "model_in_request": "deepseek-v4.1-flash" + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json new file mode 100644 index 0000000000000000000000000000000000000000..661033965e55c1f534f4adf686b51ade9ef40886 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json @@ -0,0 +1,23 @@ +{ + "key": "codex-chatgpt-generic|0.163.0|399ff69c431c066e|gpt-6.1-sol|high", + "fingerprint_sha256": "3dc06d7d7d7c5fb03c550905ba2d16faecefde695afc17f1f9f77da16c376e8c", + "written": "2026-10-26 07:02:41", + "summary": { + "developer_chars": 16979, + "top_tools": [ + "list_mcp_resource_templates", + "list_mcp_resources", + "mcp__lff.robot", + "mcp__lff.shell", + "mcp__lff.view_images", + "read_mcp_resource", + "request_user_input" + ], + "effort_in_request": "high", + "model_in_request": "gpt-6.1-sol", + "sandbox": { + "sandbox": "seccomp", + "sandbox_mode": "read-only" + } + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt_0.163.0_399ff69c431c066e_gpt-6-astra_medium.json b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt_0.163.0_399ff69c431c066e_gpt-6-astra_medium.json new file mode 100644 index 0000000000000000000000000000000000000000..319c12842e6a8c0200d9162e9f2cbd67632e7ae0 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt_0.163.0_399ff69c431c066e_gpt-6-astra_medium.json @@ -0,0 +1,36 @@ +{ + "key": "codex-chatgpt|0.163.0|399ff69c431c066e|gpt-6-astra|medium", + "fingerprint_sha256": "034292e12859cda9de8c2481b91f6c3194b83754303be8c40c3ec775bcabf9ad", + "written": "2026-10-19 22:12:31", + "summary": { + "developer_chars": 24091, + "top_tools": [ + "collaboration.followup_task", + "collaboration.interrupt_agent", + "collaboration.list_agents", + "collaboration.send_message", + "collaboration.spawn_agent", + "collaboration.wait_agent", + "functions.exec", + "functions.request_user_input", + "functions.request_user_input_async", + "functions.wait" + ], + "all_tools": [ + "apply_patch", + "clock__curr_time", + "list_mcp_resource_templates", + "list_mcp_resources", + "mcp__lff__robot", + "mcp__lff__shell", + "mcp__lff__view_images", + "read_mcp_resource" + ], + "effort_in_request": "medium", + "model_in_request": "gpt-6-astra", + "sandbox": { + "sandbox": "seccomp", + "sandbox_mode": "read-only" + } + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-v4.1-flash_high.json b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-v4.1-flash_high.json new file mode 100644 index 0000000000000000000000000000000000000000..c4798ace7f051de8818f09aa5baaed23432f4854 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-v4.1-flash_high.json @@ -0,0 +1,15 @@ +{ + "key": "dsh|0.2.1-rc.5|aa65546cc1f51674|deepseek-v4.1-flash|high", + "fingerprint_sha256": "080d6300858cdfc671e135073ec7f693bcf424eace689ffc480903b40f0e0894", + "written": "2026-10-30 16:02:13", + "summary": { + "system_chars": 114, + "tools": [ + "mcp__lff__robot", + "mcp__lff__shell", + "mcp__lff__view_images" + ], + "effort_in_request": "high", + "model_in_request": "deepseek-v4.1-flash" + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json new file mode 100644 index 0000000000000000000000000000000000000000..58b346c1dbe6acac0cb98c0e541c8c6e0ae3bdb4 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json @@ -0,0 +1,18 @@ +{ + "key": "sensenova_codex-generic-2c45c1ca7b3b|0.163.0|399ff69c431c066e|gpt-6.1-sol|high", + "fingerprint_sha256": "4a741aa5b9ff4e51ead5f08944f6bd44f4bfbb79731098fb24d37d32a43fcba9", + "written": "2026-10-25 04:38:49", + "summary": { + "report": "reports/robot_harness_integration_20261025/selfcheck_final/selfcheck.json", + "checks": 10, + "framework": { + "commit": "b513a1c7289ab11eb844856588b64c378705c405", + "patch_sha256": "70b46c683ddd7e18593c9340da272ffb29d7f60708477aea5eed9f021bc9e823", + "tree_sha256": "2c45c1ca7b3bf6182adebd373f7ff15bd6db5f0dd583f5c8113a87a88afee350", + "untracked": [ + "lff_integration/__init__.py", + "lff_integration/run.py" + ] + } + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/real/executor.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/real/executor.py new file mode 100644 index 0000000000000000000000000000000000000000..edb5a9a3932e891684f2a2c17bb8024c994d46dd --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/real/executor.py @@ -0,0 +1,138 @@ +"""RealToolExecutor: the real-robot counterpart of lffbench.agent.tools.ToolExecutor. + +robot_server's LA interface needs only this from its executor: observe(label) -> [ImageRef], proprio() -> dict, and +call("move_to" | "open_gripper" | "close_gripper", args) -> ToolResult. Here every call goes to a robot driver +(lffbench/real/protocol.py) instead of the simulator. + +Calibration bias (L1 tasks), as Skills / ToolExecutor do it in simulation: the driver is sent commanded + bias and +reports the true pose; the agent is told true - bias (what a miscalibrated robot believes). Joint angles are then the +ones that put the grasp point at the believed pose (driver /ik), as robot_server._believed_joints does in simulation. +""" +import math +import time + +import numpy as np + +from ..agent.images import ImageRef +from ..agent.tools import ToolResult, parse_args +from .protocol import CAMERAS, DriverError, square_resize, state_problems + +SPEED_MIN = 0.01 # m/s; below this a straight-line move takes too long to be useful + + +def _r(v, nd=4): + return [round(float(x), nd) for x in v] + + +class RealToolExecutor: + def __init__(self, driver, info, bias=None, image_res=512, cams=CAMERAS): + self.driver, self.info = driver, info + self.bias = np.zeros(3) if bias is None else np.asarray(bias, float) + self.image_res = int(image_res) + self.cams = tuple(cams) + self.n_joints = int(info["n_joints"]) + self.yaw_lo, self.yaw_hi = (float(v) for v in info["yaw_range_deg"]) + self.max_speed = float(info["max_speed"]) + self.motion_s = 0.0 # robot motion time of this executor (= this attempt), as reported by the driver + self.n_calls = 0 + self._state = None + self.grip_closed = False # last gripper command of this attempt (the driver's home pose has it open) + self.yaw_cmd = None # last commanded yaw (degrees), for choosing among the gripper-symmetric equivalents + self.refresh() + self.yaw_cmd = float(self._state["eef_yaw_deg"]) + + # ------------------------------------------------------------------ state + def _set_state(self, st): + prob = state_problems(st, self.n_joints) + if prob: + raise DriverError("driver state: " + "; ".join(prob)) + self._state = st + + def refresh(self): + self._set_state(self.driver.state()) + + def true_eef(self): + return np.asarray(self._state["eef_pos"], float) + + def believed_eef(self): + return self.true_eef() - self.bias + + def proprio(self): + st = self._state + return dict(eef_pos=_r(self.believed_eef()), eef_yaw_deg=round(float(st["eef_yaw_deg"]), 1), + gripper="closed" if self.grip_closed else "open", + gripper_width_m=round(float(st["gripper_width_m"]), 4)) + + def joints(self): + """Joint angles as the robot's encoders would report them under the hidden calibration error.""" + if not np.any(self.bias): + return [float(v) for v in self._state["joint_pos_rad"]] + key = (tuple(self._state["eef_pos"]), float(self._state["eef_yaw_deg"])) + if getattr(self, "_ik_key", None) != key: # one /ik per new state (the server asks several times per command) + self._ik_key = key + self._ik_val = [float(v) for v in self.driver.ik(self.believed_eef(), key[1])] + return list(self._ik_val) + + def observe(self, label=""): + frames, st = self.driver.observe() + self._set_state(st) + return [ImageRef(camera=c, array=square_resize(frames[c], self.image_res), label=f"{label} {c}".strip()) + for c in self.cams] + + # ------------------------------------------------------------------ helpers + def wrap_yaw(self, yaw): + """The two-finger gripper is symmetric: among yaw + k*180 inside the driver's yaw range, use the one closest to + the last commanded yaw (Skills.wrap_yaw does the same with its +-113 deg limit).""" + cands = [yaw + 180.0 * k for k in range(-3, 4)] + ok = [c for c in cands if self.yaw_lo <= c <= self.yaw_hi] or cands + return float(min(ok, key=lambda c: abs(c - self.yaw_cmd))) + + # ------------------------------------------------------------------ dispatch (same signature as ToolExecutor.call) + def call(self, name, raw_args): + t0 = time.time() + self.n_calls += 1 + args = parse_args(raw_args) + fn = getattr(self, f"_t_{name}", None) + if fn is None: + return ToolResult(name, args, False, dict(ok=False, error=f"unknown tool {name!r}"), wall_s=time.time() - t0) + res = fn(**args) + res.args, res.wall_s = args, time.time() - t0 + return res + + def _report(self, name, extra=None): + rep = dict(ok=True, tool=name) + rep.update(extra or {}) + rep.update(self.proprio()) + return rep + + def _t_move_to(self, x, y, z, yaw, speed=None): + tgt = np.array([x, y, z], float) + if not np.all(np.isfinite(tgt)): + return ToolResult("move_to", {}, False, dict(ok=False, error="non-finite coordinates")) + spd = None if speed is None else float(np.clip(float(speed), SPEED_MIN, self.max_speed)) + yaw_used = self.wrap_yaw(float(yaw)) + cmd = tgt + self.bias # the hidden calibration error acts on every commanded position + rep = self.driver.move(cmd[0], cmd[1], cmd[2], yaw_used, spd) + self.motion_s += float(rep.get("motion_s") or 0.0) + self._set_state(rep["state"]) + if not rep["ok"]: # rejected before moving (driver hard limits / no IK solution) + return ToolResult("move_to", {}, False, dict(ok=False, error="target rejected: the arm cannot reach it; " + "the arm did not move", driver_error=rep.get("error", ""))) + self.yaw_cmd = yaw_used + reached = bool(np.linalg.norm(cmd - self.true_eef()) < 0.02) + return ToolResult("move_to", {}, True, self._report("move_to", dict(reached=reached, + yaw_used_deg=round(yaw_used, 1)))) + + def _gripper(self, close): + rep = self.driver.gripper(close) + self.grip_closed = bool(close) + self.motion_s += float(rep.get("motion_s") or 0.0) + self._set_state(rep["state"]) + name = "close_gripper" if close else "open_gripper" + return ToolResult(name, {}, True, self._report(name)) + + def _t_open_gripper(self): + return self._gripper(False) + + def _t_close_gripper(self): + return self._gripper(True) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/l1_bias.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/l1_bias.py new file mode 100644 index 0000000000000000000000000000000000000000..a5743522e389d8640257a0cbab03aa8e7df7dd86 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/l1_bias.py @@ -0,0 +1,390 @@ +"""L1-A bias_place: pick up the cream cheese and put it into the bowl, with a miscalibrated arm. + +Level L1 (action fine-tuning): the method (top-down pick across the cheese's short side, carry, release +above the bowl) and the scene understanding are right; only execution precision is off. + +Hidden variable: a fixed calibration offset b = r (cos th, sin th, 0), r ~ U[R_MIN, R_MAX], th ~ U[0, 2 pi), +added to every commanded gripper position (`Skills(bias=b)`). The agent never sees b; positions reported +back to it must be in the commanded frame (`TrackedSkills.reported_eef_pos`), otherwise b leaks. + +Robot: the gripper is a short-stroke parallel gripper (max opening GRIPPER_MAX_OPEN = 5.0 cm, e.g. a +Robotiq Hand-E; implemented by narrowing the Panda finger actuators' ctrlrange). The cream cheese is +4.27 cm wide, so the open fingers clear it by ~3.5 mm per side. + +Why the prior fails. Sent to the true cheese position, the gripper arrives b away. If the component of b +across the cheese (jaw-closing direction) exceeds ~0.7-1.0 cm (measured), a finger comes down on top of the +cheese, the hand stops ~1.5 cm too high and the jaws close above it -> missed grasp, visible in both +cameras. With the stock 8 cm Panda stroke the measured tolerance is ~2.4 cm, so most r in [2, 4] cm would +not fail; that is why the stroke is reduced. The component of b along the cheese does not matter much +(the finger pads can grip anywhere along its 8.1 cm length, and the in-hand offset cancels at the place +because the same b is added there), and the bowl is forgiving. + +What has to be learned: the F2 feedback reports where the gripper closed relative to the cheese's centre +(forward/backward, left/right in the robot frame). That offset is b itself, so after one failure b can be +estimated and subtracted from every commanded position (pick and place alike). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..skills import Skills +from ..task_base import LFFTask, register_task + +CHEESE, BOWL = "cream_cheese_1", "akita_black_bowl_1" +JUICE = "orange_juice_1" +DISTRACTORS = ("butter_1", "chocolate_pudding_1", JUICE) +ALL = (CHEESE, BOWL) + DISTRACTORS +NAMES = {CHEESE: "cream cheese", BOWL: "bowl", "butter_1": "butter", "chocolate_pudding_1": "chocolate pudding", + JUICE: "orange juice carton"} +# descriptive names for the indirect variant (same wording as l2_knock_restore where objects overlap) +DESCR = {CHEESE: "blue box", BOWL: "grey bowl", "butter_1": "small orange box", "chocolate_pudding_1": "brown box", + JUICE: "tall juice carton"} +# Cream cheese collision box: 8.12 x 4.27 x 1.79 cm, lying flat, long side along its x axis. +# Realistic masses (LIBERO's are 5-10 g): a 6 g cheese is shoved aside by a finger landing on its edge. +MASS = {CHEESE: 0.227, "butter_1": 0.250, "chocolate_pudding_1": 0.200, BOWL: 0.300} + +# finger tips (0.97 cm below the gripper site) just clear the table; the pads cover 0.6-1.8 cm of the cheese +Z_GRASP = envs.TABLE_Z + 0.0105 +Z_CARRY = envs.TABLE_Z + 0.20 # clears the 13 cm juice carton with the cheese hanging below the fingers +BOWL_RIM = 0.0505 # rim height of the akita bowl above its lowest point +BOWL_R_IN = 0.046 # inner radius of the bowl at the rim +RELEASE_ABOVE_RIM = 0.012 # gripper site above the rim at release (finger pads clear the rim) + +R_MIN, R_MAX = 0.025, 0.040 # bias magnitude range (m) +GRIPPER_MAX_OPEN = 0.050 # short-stroke gripper: max finger gap (m); the cheese is 4.27 cm wide +CHEESE_YAW_MAX = np.deg2rad(10) + + +HOME_XY = np.array([-0.21, 0.0]) # gripper xy at reset + + +def _seg_dist(p, a, b): + """distance from point p to segment ab (2-D)""" + ab = b - a + u = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0, 1) + return float(np.linalg.norm(a + u * ab - p)) + + +def _q(axis, a): + h = a / 2 + return {"y": np.array([np.cos(h), 0, np.sin(h), 0]), "z": np.array([np.cos(h), 0, 0, np.sin(h)])}[axis] + + +def _qmul(a, b): + """wxyz quaternion product a*b""" + w1, x1, y1, z1 = a + w2, x2, y2, z2 = b + return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, + w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2]) + + +def set_gripper_stroke(env, max_open): + """Limit the jaw opening: each finger's position actuator gets the range [0, max_open/2] (robosuite maps + the open/close command onto the actuator ctrlrange, so "open" now means max_open). The pad faces sit + 0.5 mm inside the joint position, hence the small correction.""" + m = env.sim.model + half = max_open / 2 + 0.0005 + a1, a2 = [m.actuator_name2id(a) for a in env.robots[0].gripper.actuators] + m.actuator_ctrlrange[a1] = [0.0, half] + m.actuator_ctrlrange[a2] = [-half, 0.0] + + +def dir_words(dx, dy): + """Robot-frame description: +x = forward (away from the robot), +y = the robot's left.""" + parts = [] + if abs(dy) >= 0.0005: + parts.append(f"{100 * abs(dy):.1f} cm to the robot's {'left (+y)' if dy > 0 else 'right (-y)'}") + if abs(dx) >= 0.0005: + parts.append(f"{100 * abs(dx):.1f} cm {'forward (+x, away from the robot)' if dx > 0 else 'backward (-x, toward the robot)'}") + return " and ".join(parts) if parts else "exactly at the position" + + +class TrackedSkills(Skills): + """Skills that log what the outcome measurement needs, whoever drives them (scripted policy or agent): + where the gripper was and what the fingers touched when the jaws closed, and where the cheese was when + the jaws opened while holding it.""" + + def __init__(self, env, bias=None, recorder=None): + super().__init__(env, bias=bias, recorder=recorder) + self.events = [] + self.cheese_z0 = float(envs.obj_pos(env, CHEESE)[2]) + self.cheese_zmax = self.cheese_z0 + m = env.sim.model + self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_")] + self._obj_geoms = {n: envs.obj_geom_ids(env, n) for n in ALL} + # where the cheese was before the gripper last touched it (the reference for the grasp offset, so that + # a finger shoving the cheese aside on the way down does not corrupt the measurement) + self.cheese_ref = envs.obj_pos(env, CHEESE) + + def reported_eef_pos(self): + """End-effector position as the miscalibrated robot believes it to be (commanded frame). Anything + shown to the agent must use this, never eef_pos(), which is the true position and reveals b.""" + return self.eef_pos() - self.bias + + def move_to(self, target, *args, **kwargs): + rep = super().move_to(target, *args, **kwargs) + rep["pos"] = np.round(self.reported_eef_pos(), 4).tolist() # do not leak b through the report + return rep + + def touching(self): + """Objects the gripper is in contact with right now.""" + return [n for n, gs in self._obj_geoms.items() if envs.contacts_between(self.env, self._grip_geoms, gs)] + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.cheese_zmax = max(self.cheese_zmax, float(envs.obj_pos(self.env, CHEESE)[2])) + if self.grip < 0 and not envs.contacts_between(self.env, self._grip_geoms, self._obj_geoms[CHEESE]): + self.cheese_ref = envs.obj_pos(self.env, CHEESE) + + def set_gripper(self, close, steps=15): + if close and self.grip < 0: + self.events.append(dict(kind="close", eef=self.eef_pos().tolist(), + cheese=envs.obj_pos(self.env, CHEESE).tolist(), + cheese_ref=np.asarray(self.cheese_ref).tolist(), touching=self.touching(), + cheese_top=envs.obj_max_z(self.env, CHEESE), step=self.n_steps)) + elif not close and self.grip > 0 and self.holding(CHEESE): + self.events.append(dict(kind="release", eef=self.eef_pos().tolist(), + cheese=envs.obj_pos(self.env, CHEESE).tolist(), + bowl=envs.obj_pos(self.env, BOWL).tolist(), step=self.n_steps)) + return super().set_gripper(close, steps) + + +@register_task +class BiasPlace(LFFTask): + name = "l1_bias_place" + level = "L1" + category = "system_identification" + capabilities = ("Perceive", "Utilize") + protocol = "cross" + # LIBERO calls the bowl "akita black bowl", but under our renderer it looks silver-grey with a gold rim, so + # the colour is not used in the direct instruction (there is only one bowl). + instruction = "Pick up the cream cheese and put it into the bowl." + instruction_indirect = "Pick up the flat blue box with the white oval label and put it into the round grey bowl." + pick_lift_min = 0.03 # cheese counted as picked up if it rose this much + + # ------------------------------------------------------------ scene + def make_bddl(self): + # regions are only used by LIBERO's reset-time sampler (the layout is overridden in apply_instance) + objs = [(CHEESE, "cream_cheese", "cheese_region", (-0.16, -0.22, -0.14, -0.20)), + (BOWL, "akita_black_bowl", "bowl_region", (-0.01, 0.15, 0.01, 0.17)), + ("butter_1", "butter", "butter_region", (-0.16, 0.10, -0.14, 0.12)), + ("chocolate_pudding_1", "chocolate_pudding", "pudding_region", (0.04, -0.17, 0.06, -0.15)), + (JUICE, "orange_juice", "juice_region", (-0.15, -0.03, -0.13, -0.01))] + return write_bddl(self.name, self.instruction, objs) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + # LIBERO's own upright orientation of every object, read off the reset state + self._base_quat = {n: envs.obj_quat(self.env, n) for n in ALL} + + def _place(self, name, xy, yaw): + q = _qmul(_q("z", yaw), self._base_quat[name]) + envs.set_obj_pose(self.env, name, [xy[0], xy[1], envs.TABLE_Z + 0.3], quat_wxyz=q) + self.env.sim.forward() + qa, _ = envs.free_joint_addr(self.env, name) + self.env.sim.data.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (envs.TABLE_Z + 0.0005) + self.env.sim.forward() + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + while True: + c = np.array([rng.uniform(-0.16, 0.04), rng.uniform(-0.20, 0.20)]) + bowl = np.array([rng.uniform(-0.15, 0.08), rng.uniform(-0.24, 0.24)]) + if np.linalg.norm(bowl - c) < 0.20: + continue + placed = [c, bowl] + dis = {} + for name in DISTRACTORS: + for _ in range(300): + p = np.array([rng.uniform(-0.22, 0.10), rng.uniform(-0.27, 0.27)]) + if any(np.linalg.norm(p - o) < (0.13 if k < 2 else 0.11) for k, o in enumerate(placed)): + continue + if name == JUICE: + # the 13 cm carton is taller than the hand when it grasps / releases: the Panda hand spans + # +-10.5 cm across the jaws, so keep the carton >= 17 cm from the cheese and the bowl; + # it must also not hide them from the front camera, and must stay >= 10 cm off the + # straight paths home->cheese, home->bowl and cheese->bowl + if np.linalg.norm(p - c) < 0.17 or np.linalg.norm(p - bowl) < 0.17: + continue + if any(p[0] > t[0] - 0.03 and abs(p[1] - t[1]) < 0.14 for t in (c, bowl)): + continue + if any(_seg_dist(p, a, b) < 0.10 for a, b in ((c, bowl), (HOME_XY, c), (HOME_XY, bowl))): + continue + break + else: + break + placed.append(p) + dis[name] = dict(xy=p.round(5).tolist(), yaw=float(rng.uniform(-np.pi, np.pi))) + if len(dis) == len(DISTRACTORS): + break + psi = float(rng.uniform(-CHEESE_YAW_MAX, CHEESE_YAW_MAX)) + n = np.array([-np.sin(psi), np.cos(psi)]) # jaw-closing direction for a grasp across the cheese + l = np.array([np.cos(psi), np.sin(psi)]) + r = rng.uniform(R_MIN, R_MAX) + th = rng.uniform(0, 2 * np.pi) + b = np.array([r * np.cos(th), r * np.sin(th)]) + return dict(seed=int(seed), cheese_xy=c.round(5).tolist(), cheese_yaw=psi, bowl_xy=bowl.round(5).tolist(), + distractors=dis, bias=[float(b[0]), float(b[1]), 0.0], bias_r=float(r), bias_theta=float(th), + bias_across=float(b @ n), bias_along=float(b @ l)) + + def apply_instance(self, inst): + set_gripper_stroke(self.env, GRIPPER_MAX_OPEN) + for name, mass in MASS.items(): + envs.scale_mass(self.env, name, mass) + self._place(CHEESE, inst["cheese_xy"], inst["cheese_yaw"]) + self._place(BOWL, inst["bowl_xy"], 0.0) + for name, v in inst["distractors"].items(): + self._place(name, v["xy"], v["yaw"]) + + def skill_bias(self, inst): + return np.array(inst["bias"], float) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = TrackedSkills(self.env, bias=self.skill_bias(inst), recorder=recorder) + self.start_pos = {n: envs.obj_pos(self.env, n) for n in ALL} + return self.sk + + # ------------------------------------------------------------ outcome + def in_bowl(self): + k = envs.obj_pos(self.env, BOWL) + c = envs.obj_pos(self.env, CHEESE) + base = envs.obj_min_z(self.env, BOWL) + return bool(np.linalg.norm(c[:2] - k[:2]) < BOWL_R_IN and c[2] < base + BOWL_RIM + and envs.obj_upright_cos(self.env, BOWL) > 0.9 and base < envs.TABLE_Z + 0.01) + + def outcome(self, inst): + envs.settle(self.env, 40) + sk = self.sk + k = envs.obj_pos(self.env, BOWL) + c = envs.obj_pos(self.env, CHEESE) + held = sk.holding(CHEESE) + success = bool(self.in_bowl() and not held) + picked = sk.cheese_zmax > sk.cheese_z0 + self.pick_lift_min + closes = [e for e in sk.events if e["kind"] == "close"] + last_close = closes[-1] if closes else None + releases = [e for e in sk.events if e["kind"] == "release" and last_close and e["step"] >= last_close["step"]] + end_off = c[:2] - k[:2] + moved = {n: float(np.linalg.norm(envs.obj_pos(self.env, n)[:2] - self.start_pos[n][:2])) + for n in DISTRACTORS} + out = dict(success=success, picked=bool(picked), held_at_end=bool(held), + cheese_end=c.round(4).tolist(), bowl_end=k.round(4).tolist(), end_offset=end_off.round(4).tolist(), + grasp_offset=None, release_offset=None, touched_at_close=None, + distractors_moved_cm={n: round(100 * v, 1) for n, v in moved.items()}) + grasp_txt = "" + if last_close is not None: + go = np.array(last_close["eef"][:2]) - np.array(last_close["cheese_ref"][:2]) + out["grasp_offset"] = go.round(4).tolist() + out["touched_at_close"] = last_close["touching"] + out["cheese_pushed_cm"] = round(100 * float(np.linalg.norm( + np.array(last_close["cheese"][:2]) - np.array(last_close["cheese_ref"][:2]))), 1) + grasp_txt = (f"The gripper closed {dir_words(*go)} of the centre of the cream cheese (measured where " + f"the cheese was before the fingers touched it)") + if releases: + r = releases[-1] + out["release_offset"] = (np.array(r["cheese"][:2]) - np.array(r["bowl"][:2])).round(4).tolist() + if success: + out["failure"] = None + detail = "The cream cheese is in the bowl." + if grasp_txt: + detail += f" {grasp_txt}." + elif not picked: + out["failure"] = "missed_grasp" + if last_close is None: + detail = "The gripper never closed; the cream cheese was not picked up." + else: + on = [NAMES[n] for n in last_close["touching"] if n != CHEESE] + why = "" + if on: + why = (f" A finger landed on top of the {' and the '.join(on)} instead of going down beside the " + f"cheese, so the jaws closed above the cheese.") + elif CHEESE in last_close["touching"] and not sk.holding(CHEESE): + why = " A finger came down on top of the cream cheese instead of beside it." + elif not last_close["touching"] and last_close.get("cheese_top") is not None: + above = last_close["eef"][2] - envs.FINGERTIP_BELOW_SITE - last_close["cheese_top"] + if above > 0.002: # closed in the air, entirely above the cheese + why = (f" The fingers closed in the air without touching anything: the fingertips were " + f"{100 * above:.1f} cm above the top of the cream cheese.") + detail = f"{grasp_txt} and did not pick it up.{why} The cream cheese is still on the table." + elif held: + out["failure"] = "not_released" + detail = f"{grasp_txt} and picked it up, but the cream cheese is still in the gripper." + elif releases: + out["failure"] = "missed_place" + detail = (f"{grasp_txt} and picked it up. When the gripper opened, the cream cheese was " + f"{dir_words(*out['release_offset'])} of the bowl's centre; it did not end up in the bowl " + f"(it is now {dir_words(*end_off)} of the bowl's centre).") + else: + out["failure"] = "dropped" + detail = (f"{grasp_txt} and picked it up, but it slipped out of the gripper before it was released; " + f"it is now {dir_words(*end_off)} of the bowl's centre.") + out["detail"] = detail + ind = detail + for k in (JUICE, "chocolate_pudding_1", "butter_1", CHEESE, BOWL): # longest names first + ind = ind.replace(NAMES[k], DESCR[k]) + out["detail_indirect"] = ind + return out + + def feedback(self, inst, out, level="F2", indirect=False): + """F0: nothing, F1: success flag, F2: measured offsets. `indirect` uses descriptive object names.""" + if indirect and level == "F2": + out = dict(out, detail=out.get("detail_indirect", out["detail"])) + return super().feedback(inst, out, level) + + # ------------------------------------------------------------ scripted execution (cross protocol) + def execute(self, inst, params): + """Top-down pick across the cheese's short side, carry, release above the bowl. + params['offset'] (xy) is the policy's own correction, added to every commanded position.""" + sk = self.sk + off = np.array(params.get("offset", [0.0, 0.0]), float) + c = envs.obj_pos(self.env, CHEESE) # perfect perception of the current scene + yaw = self.grasp_yaw() + k = envs.obj_pos(self.env, BOWL) + z_rel = envs.obj_min_z(self.env, BOWL) + BOWL_RIM + RELEASE_ABOVE_RIM + g, p = c[:2] + off, k[:2] + off + sk.set_gripper(False, steps=8) + sk.move_to([g[0], g[1], Z_CARRY], yaw=yaw) # approach from above, clear of the 13 cm carton + sk.move_to([g[0], g[1], Z_GRASP + 0.08], tol=0.002) + sk.move_to([g[0], g[1], Z_GRASP], tol=0.003, max_steps=80) + sk.set_gripper(True, steps=15) + sk.move_to([g[0], g[1], Z_CARRY], speed=0.3) + if not sk.holding(CHEESE): # missed: a real controller sees the jaws closed on nothing and stops + return + sk.move_to([p[0], p[1], Z_CARRY], tol=0.003) + sk.move_to([p[0], p[1], z_rel], tol=0.003, max_steps=100) + sk.set_gripper(False, steps=12) + sk.move_to([p[0], p[1], Z_CARRY], speed=0.3) + + def grasp_yaw(self): + """Gripper yaw that closes the jaws across the cheese's short side (yaw 0 closes along world y).""" + xmat = self.env.sim.data.body_xmat[envs.body_id(self.env, CHEESE)].reshape(3, 3) + a = np.arctan2(xmat[1, 0], xmat[0, 0]) # direction of the cheese's long (x) axis + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + def default_params(self, inst): + return dict(offset=[0.0, 0.0]) + + def oracle_params(self, inst): + return dict(offset=(-np.array(inst["bias"][:2])).tolist()) + + def adapt_params(self, inst, history): + """Scripted F2 learner: the reported grasp offset (where the gripper closed relative to the cheese's + centre) measures the calibration offset; accumulate it into the correction subtracted from every + commanded position. If the gripper never closed, fall back to the release offset.""" + last = history[-1] + off = np.array(last["params"]["offset"], float) + o = last["outcome"] + if o.get("grasp_offset") is not None: + off = off - np.array(o["grasp_offset"]) + elif o.get("release_offset") is not None: + off = off - np.array(o["release_offset"]) + return dict(offset=off.round(4).tolist()) + + blind_sigma = 0.005 + + def blind_params(self, inst, attempt, rng): + """Retry the same plan with a small random perturbation of the targets; no use of history.""" + return dict(offset=rng.normal(0.0, self.blind_sigma, 2).round(4).tolist()) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/l2_restore_layout.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/l2_restore_layout.py new file mode 100644 index 0000000000000000000000000000000000000000..d926c362024dece29de84cdc1074180f7b196ceb --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/l2_restore_layout.py @@ -0,0 +1,502 @@ +"""L2-B restore_layout: put the ketchup into the basket; every other item must stay exactly where it was. + +Scene: the ketchup (upright) and three flat boxes (cream cheese, butter, chocolate pudding) stand on the bare +table in an irregular layout (random positions and yaws, no tray, no markers, no grid), the basket on the +robot's left. Nothing in the scene marks where an item "belongs": its original pose exists only in the +first frame. + +Constructed L2 event (physical, continuous): the first time the ketchup is grasped and lifted 3 cm, the +neighbouring box (the "victim", a hidden variable) is knocked: it receives a velocity impulse away from the +ketchup (+-35 deg) and a spin, slides 9-14 cm over the table and comes to rest turned by 45-80 deg. It is +real MuJoCo motion over ~0.2 s (no teleport), so a video shows it sliding away. The main task itself still +succeeds; an agent that stops after it fails. To repair the side effect the agent has to put the victim +back where it was -- within 3 cm and 25 deg (mod 180, the boxes are symmetric) -- and that pose is only in +its memory of the start of the episode (the F2 text says *which* item is out of place, never where it was). + +Protocol: within (one episode, no reset). Attempt 1 = the main task, every later attempt = one corrective +round chosen by the policy; the outcome (success + F2 text) is computed after each round. + +Scripted references + oracle knows the victim: right after the main task it puts the victim back at its saved start pose. + naive main task, then done. + adaptive saves the start layout from the first frame (Save); after a failure reads from F2 which items are + out of place (Retrieve their saved poses) and puts them back (Utilize). + blind no history, no feedback: every later round redoes the main task (lifts the ketchup out of the + basket and puts it back, grasp jittered by 5 mm), like l2_knock_restore's blind. + nomem (extra control, not in the acceptance table) gets the F2 text but has no start frame: it knows + which box is out of place and guesses where to put it (random free spot within 15 cm, random yaw). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..task_base import LFFTask, register_task + +TARGET = "ketchup_1" +BOXES = ("cream_cheese_1", "butter_1", "chocolate_pudding_1") +BASKET = "basket_1" +ITEMS = (TARGET,) + BOXES + +# LIBERO basket (body frame = world frame at yaw 0), measured by the l2_knock_restore developer +BASKET_IN = 0.060 # half size of the inner floor +BASKET_RIM = 0.150 # rim height above the basket's lowest point +BASKET_FLOOR = 0.017 # floor top above the basket's lowest point +BASKET_OUT = 0.11 # conservative half size of the outer footprint (keep-out radius for the layout) + +POS_TOL = 0.03 # success: box centre within 3 cm of its start +YAW_TOL = np.radians(25.0) # ... and long axis within 25 deg of its start (mod 180) +STILL_TOL = 0.02 # the knock only fires if the victim is still within 2 cm of its start + +REGION = (-0.26, 0.06, -0.27, 0.10) # x0, x1, y0, y1 (world) for item centres +KNOCK_REGION = (-0.28, 0.08, -0.29, 0.12) # where the victim may come to rest +MAX_REACH = 0.70 # max horizontal distance of an item centre from the robot base +BASE_X = -0.66 +R_BOX, R_KETCHUP = 0.046, 0.034 # footprint circumradii (boxes 8 x 4.3 cm; ketchup 5.7 x 3.7 cm) +GAP = 0.03 # free space between footprints (finger room) +SLIDE_K = 0.0522 # measured: slide distance [m] = SLIDE_K * v0^2 [m/s] for these boxes on the table +SPIN_W = 40.0 # rad/s, applied each control step until the target turn is reached + +NAMES = {"ketchup_1": "ketchup", "cream_cheese_1": "cream cheese", "butter_1": "butter", + "chocolate_pudding_1": "chocolate pudding", BASKET: "basket"} +DESCR = {"ketchup_1": "red bottle", "cream_cheese_1": "blue box", "butter_1": "small orange box", + "chocolate_pudding_1": "brown box", BASKET: "wicker basket"} + + +def _qz(a): + return np.array([np.cos(a / 2), 0.0, 0.0, np.sin(a / 2)]) + + +def _wrap_half(a): + """wrap an angle to [-pi/2, pi/2) (boxes and parallel grippers are symmetric under 180 deg)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def _seg_dist(p, a, b): + """distance from point p to segment a-b (2D)""" + p, a, b = (np.asarray(v, float) for v in (p, a, b)) + ab = b - a + t = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0.0, 1.0) + return float(np.linalg.norm(p - (a + t * ab))) + + +def _in_rect(xy, r): + return r[0] <= xy[0] <= r[1] and r[2] <= xy[1] <= r[3] + + +def _reach_ok(xy): + return np.hypot(xy[0] - BASE_X, xy[1]) <= MAX_REACH + + +@register_task +class RestoreLayout(LFFTask): + name = "l2_restore_layout" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Save", "Retrieve", "Utilize") + protocol = "within" + max_attempts = 5 + instruction = ("Put the ketchup into the basket. Every other item on the table must stay exactly where it " + "is now, in the same position and orientation.") + instruction_indirect = ("Put the red bottle into the wicker basket. Every other item on the table must stay " + "exactly where it is now, in the same position and orientation.") + knock_lift = 0.03 # trigger: ketchup grasped and lifted this far above its resting height + + def __init__(self, cam_res=None): + super().__init__(cam_res) + # upright orientations (wxyz), fixed like in l2_knock_restore: the ketchup mesh is modelled lying down; + # basket and boxes are upright in their mesh frame + self.q_up = {n: np.array([1.0, 0.0, 0.0, 0.0]) for n in self.env.objects_dict} + self.q_up[TARGET] = np.array([0.5, 0.5, 0.5, 0.5]) + self._inj = None + self.start = {} + self._home = None + # per-control-step monitor on env.step: also sees attempts driven by the agent harness + orig_step = self.env.step + + def step(action): + ret = orig_step(action) + if self._inj is not None: + self._knock_step() + return ret + + self.env.step = step + + # ------------------------------------------------------------ scene + def make_bddl(self): + names = [*ITEMS, BASKET] + objs = [] + for i, n in enumerate(names): # layout is overridden in apply_instance; regions only need to be valid + x0 = -0.30 + 0.13 * (i % 3) + y0 = -0.25 + 0.25 * (i // 3) + objs.append((n, n[:-2], f"r_{i}", (x0, y0, x0 + 0.02, y0 + 0.02))) + return write_bddl(self.name, self.instruction, objs) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + for _ in range(5000): + basket = np.array([rng.uniform(-0.08, 0.0), rng.uniform(0.25, 0.27)]) + k = np.array([rng.uniform(-0.17, -0.03), rng.uniform(-0.14, -0.02)]) + victim = str(rng.choice(BOXES)) + others = [b for b in BOXES if b != victim] + a_v = rng.uniform(0, 2 * np.pi) + r_v = rng.uniform(R_BOX + R_KETCHUP + GAP, R_BOX + R_KETCHUP + GAP + 0.02) + pos = {TARGET: k, victim: k + r_v * np.array([np.cos(a_v), np.sin(a_v)])} + ok = _in_rect(pos[victim], REGION) and _reach_ok(pos[victim]) + for o in others: + if not ok: + break + for _ in range(200): + p = np.array([rng.uniform(*REGION[:2]), rng.uniform(*REGION[2:])]) + if not _reach_ok(p): + continue + if np.linalg.norm(p - k) < R_BOX + R_KETCHUP + GAP: + continue + if any(np.linalg.norm(p - pos[q]) < 2 * R_BOX + GAP for q in pos if q != TARGET): + continue + pos[o] = p + break + else: + ok = False + if not ok: + continue + if any(np.linalg.norm(pos[n] - basket) < BASKET_OUT + R_BOX + 0.02 for n in ITEMS): + continue + # the knock: away from the ketchup +-35 deg, 9-14 cm, turn 45-80 deg (random sign) + ang = a_v + rng.uniform(-np.radians(35), np.radians(35)) + dist = rng.uniform(0.09, 0.14) + u = np.array([np.cos(ang), np.sin(ang)]) + end = pos[victim] + dist * u + if not (_in_rect(end, KNOCK_REGION) and _reach_ok(end)): + continue + if np.linalg.norm(end - basket) < BASKET_OUT + R_BOX + 0.03: + continue + # the path and the resting spot keep clear of the other boxes (finger room around the victim too) + if any(_seg_dist(pos[o], pos[victim], end) < 2 * R_BOX + 0.01 for o in others): + continue + if any(np.linalg.norm(end - pos[o]) < 2 * R_BOX + GAP for o in others): + continue + if np.linalg.norm(end - k) < R_BOX + R_KETCHUP + GAP: + continue + turn = float(rng.choice([-1, 1]) * rng.uniform(np.radians(45), np.radians(80))) + return dict(seed=int(seed), + basket_xy=basket.round(4).tolist(), + xy={n: pos[n].round(4).tolist() for n in ITEMS}, + yaw={**{b: float(rng.uniform(-np.pi / 2, np.pi / 2)) for b in BOXES}, + TARGET: float(np.pi / 2 + rng.uniform(-0.3, 0.3))}, + # hidden variables of the injected failure + victim=victim, knock_dir=float(ang), knock_dist=float(dist), knock_turn=turn, + knock_end=end.round(4).tolist()) + raise RuntimeError("could not sample a layout") + + def place(self, name, xy, yaw, surface_z=envs.TABLE_Z): + """Teleport an object upright (yaw about world z) with its lowest point 2 mm above surface_z (reset only).""" + q = envs._quat_mul(_qz(yaw), self.q_up[name]) + envs.set_obj_pose(self.env, name, [xy[0], xy[1], surface_z + 0.3], quat_wxyz=q) + self.env.sim.forward() + dz = envs.obj_min_z(self.env, name) - (surface_z + 0.002) + qa, _ = envs.free_joint_addr(self.env, name) + self.env.sim.data.qpos[qa + 2] -= dz + self.env.sim.forward() + + def apply_instance(self, inst): + envs.scale_mass(self.env, BASKET, 2.0) # heavy enough not to be dragged by the gripper (as in l2_knock) + self.place(BASKET, inst["basket_xy"], 0.0) + for n in ITEMS: + self.place(n, inst["xy"][n], inst["yaw"][n]) + self.env.sim.forward() + + def reset_instance(self, inst, recorder=None): + self._inj = None + sk = super().reset_instance(inst, recorder) + self.start = {n: self.footprint(n) for n in ITEMS} + self._inj = dict(inst=inst, done=False, knocked=False, step=None, spin_left=0.0, spin_steps=0) + self._home = sk.eef_pos() + return sk + + # ------------------------------------------------------------ measurements + def footprint(self, name): + """Measured pose summary: AABB centre, yaw of the long horizontal axis, half sizes, z range. + Scripted policies use it as a stand-in for perception.""" + m, d = self.env.sim.model, self.env.sim.data + lo, hi = np.full(3, np.inf), np.full(3, -np.inf) + best = None + for g in envs.obj_geom_ids(self.env, name): + R = d.geom_xmat[g].reshape(3, 3) + c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3] + e = np.abs(R) @ m.geom_aabb[g, 3:] + lo, hi = np.minimum(lo, c - e), np.maximum(hi, c + e) + vol = float(np.prod(m.geom_aabb[g, 3:])) + if best is None or vol > best[0]: + best = (vol, R, m.geom_aabb[g, 3:]) + _, R, half = best + horiz = sorted([(half[k], R[:, k]) for k in range(3) if abs(R[2, k]) < 0.5], key=lambda t: -t[0]) + ax = horiz[0][1] if horiz else np.array([1.0, 0.0, 0.0]) + return dict(center=[float(v) for v in (lo + hi) / 2], yaw=float(np.arctan2(ax[1], ax[0])), + half_xy=[float(v) for v in ((hi - lo) / 2)[:2]], zmin=float(lo[2]), zmax=float(hi[2])) + + def body_yaw(self, name): + R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3) + return float(np.arctan2(R[1, 0], R[0, 0])) + + # ------------------------------------------------------------ failure injection (physical knock) + def _knock_step(self): + st = self._inj + if st["done"]: + if st["spin_steps"] > 0: # keep spinning until the target turn is reached (<= 6 control steps) + self._spin(st) + return + if self.sk is None: + return + if envs.obj_min_z(self.env, TARGET) < self.start[TARGET]["zmin"] + self.knock_lift: + return + if not self.sk.holding(TARGET): + return + st["done"] = True + inst = st["inst"] + v = inst["victim"] + if np.linalg.norm(np.array(self.footprint(v)["center"][:2]) - np.array(self.start[v]["center"][:2])) > STILL_TOL: + return # the victim was moved beforehand: nothing happens + qa, da = envs.free_joint_addr(self.env, v) + v0 = np.sqrt(inst["knock_dist"] / SLIDE_K) + dvec = np.array([np.cos(inst["knock_dir"]), np.sin(inst["knock_dir"])]) + d = self.env.sim.data + d.qvel[da:da + 3] = [v0 * dvec[0], v0 * dvec[1], 0.0] + st.update(knocked=True, step=int(self.sk.n_steps), yaw0=self.body_yaw(v), spin_left=inst["knock_turn"], + spin_steps=6) + self._spin(st) + + def _spin(self, st): + v = st["inst"]["victim"] + _, da = envs.free_joint_addr(self.env, v) + turned = _wrap_half(self.body_yaw(v) - st["yaw0"]) if abs(st["spin_left"]) < np.pi / 2 else 0.0 + rest = st["spin_left"] - turned + st["spin_steps"] -= 1 + if abs(rest) < np.radians(4) or np.sign(rest) != np.sign(st["spin_left"]): + st["spin_steps"] = 0 + return + # measured: one control step at w rad/s turns these boxes by ~0.35-0.8 deg per rad/s; aim a bit short + w = float(np.clip(np.degrees(abs(rest)) / 0.6, 5.0, SPIN_W)) + self.env.sim.data.qvel[da + 5] = np.sign(rest) * w + + # ------------------------------------------------------------ outcome + def where_target(self): + """'basket', 'gripper', 'table' or 'other' for the ketchup.""" + f = self.footprint(TARGET) + c = np.array(f["center"]) + if self.sk is not None and self.sk.holding(TARGET) and f["zmin"] > envs.TABLE_Z + 0.02: + return "gripper", f + bp = envs.obj_pos(self.env, BASKET) + if np.all(np.abs(c[:2] - bp[:2]) <= BASKET_IN + 0.01) and f["zmin"] < envs.obj_min_z(self.env, BASKET) + BASKET_RIM: + return "basket", f + if f["zmin"] < envs.TABLE_Z + 0.01: + return "table", f + return "other", f + + def box_state(self, name): + """Pose error of a box w.r.t. its start pose and where it is.""" + f = self.footprint(name) + s = self.start[name] + c, c0 = np.array(f["center"][:2]), np.array(s["center"][:2]) + dpos = float(np.linalg.norm(c - c0)) + dyaw = _wrap_half(f["yaw"] - s["yaw"]) + held = bool(self.sk is not None and self.sk.holding(name)) + upright = envs.obj_upright_cos(self.env, name) > 0.9 + on_table = f["zmin"] < envs.TABLE_Z + 0.01 + bp = envs.obj_pos(self.env, BASKET) + loc = ("gripper" if held else + "basket" if np.all(np.abs(c - bp[:2]) <= BASKET_IN + 0.02) and not on_table else + "table" if on_table and upright else + "table_tipped" if on_table else "other") + ok = bool(loc == "table" and dpos <= POS_TOL and abs(dyaw) <= YAW_TOL) + return dict(ok=ok, loc=loc, dpos=dpos, dyaw=float(dyaw), center=f["center"], yaw=f["yaw"], + offset=(c - c0).tolist()) + + @staticmethod + def _offset_words(off, dyaw): + """robot-centric words for a displacement (current - start) and turn (for the offset tier only)""" + parts = [] + if abs(off[0]) >= 0.005: + parts.append(f"{100 * abs(off[0]):.0f} cm {'forward' if off[0] > 0 else 'backward'}") + if abs(off[1]) >= 0.005: + parts.append(f"{100 * abs(off[1]):.0f} cm to the {'left' if off[1] > 0 else 'right'}") + s = (" and ".join(parts) + " of its starting spot") if parts else "at its starting spot" + if abs(dyaw) >= np.radians(3): + s += f", turned {abs(np.degrees(dyaw)):.0f} deg {'counter-clockwise' if dyaw > 0 else 'clockwise'} (seen from above)" + return s + + def _describe(self, tloc, boxes, names, offset=False): + tn = names[TARGET] + msgs = [] + if tloc != "basket": + msgs.append({"gripper": f"The {tn} is still in the gripper, not in the basket.", + "table": f"The {tn} is on the table, not in the basket."} + .get(tloc, f"The {tn} is not in the basket.")) + for n in BOXES: + b = boxes[n] + if b["ok"]: + continue + if b["loc"] == "gripper": + msgs.append(f"The {names[n]} is in the gripper; it must be back where it was at the start.") + continue + if b["loc"] == "basket": + msgs.append(f"The {names[n]} is in the basket; it must be back where it was at the start.") + continue + if b["loc"] == "table_tipped": + msgs.append(f"The {names[n]} has tipped over and is not where it was at the start.") + continue + if b["loc"] != "table": + msgs.append(f"The {names[n]} is not where it was at the start.") + continue + what = [] + if b["dpos"] > POS_TOL: + what.append("position") + if abs(b["dyaw"]) > YAW_TOL: + what.append("orientation") + m = f"The {names[n]} is not where it was at the start ({' and '.join(what)} changed)." + if offset: + m += f" It is {self._offset_words(b['offset'], b['dyaw'])}." + msgs.append(m) + if not msgs: + msgs.append(f"The {tn} is in the basket and every other item is where it was at the start.") + return " ".join(msgs) + + def outcome(self, inst): + envs.settle(self.env, 30) + tloc, tf = self.where_target() + boxes = {n: self.box_state(n) for n in BOXES} + moved = [n for n in BOXES if not boxes[n]["ok"]] + success = bool(tloc == "basket" and not moved) + return dict(success=success, target_loc=tloc, moved=moved, + boxes={n: dict(ok=b["ok"], loc=b["loc"], dpos=round(b["dpos"], 4), + dyaw_deg=round(float(np.degrees(b["dyaw"])), 1)) for n, b in boxes.items()}, + knocked=bool(self._inj and self._inj["knocked"]), + detail=self._describe(tloc, boxes, NAMES), + detail_indirect=self._describe(tloc, boxes, DESCR), + detail_offset=self._describe(tloc, boxes, NAMES, offset=True)) + + def feedback(self, inst, out, level="F2", indirect=False, offset=False): + """F0: nothing, F1: success flag, F2: which item is out of place (never where it was). + offset=True (ablation tier 'F2+offset'): also the displacement from the start pose in robot-centric + words -- this externalises the memory and is not the default.""" + if level == "F2": + key = "detail_offset" if offset else ("detail_indirect" if indirect else "detail") + out = dict(out, detail=out.get(key, out["detail"])) + return super().feedback(inst, out, level) + + # ------------------------------------------------------------ scripted motions (Skills.move_to / set_gripper only) + def go_home(self): + """End of an attempt: lift the arm out of the camera's way.""" + sk = self.sk + p = sk.eef_pos() + sk.move_to([p[0], p[1], max(p[2], self._home[2])]) + sk.move_to(self._home) + + def pick_place(self, name, dest_xy, support_z, dest_yaw=None, carry_z=1.10, clearance=0.006, fp=None, + travel_z=1.15): + """Top-down pick of `name` at its (measured) footprint, carry at eef height `carry_z`, release with the + object bottom `clearance` above `support_z` at dest_xy; `dest_yaw` = desired yaw of the long axis.""" + sk = self.sk + f = fp or self.footprint(name) + c = np.array(f["center"]) + h = f["zmax"] - f["zmin"] + gyaw = _wrap_half(f["yaw"]) # fingers close along eef y (= world y at yaw 0): across the short side + if name == TARGET: + zg = f["zmax"] - 0.035 + else: + zg = max(f["zmin"] + 0.5 * h, f["zmin"] + 0.0145) # finger tips reach ~1.3 cm below the grip site + sk.set_gripper(False, steps=6) + p = sk.eef_pos() + if p[2] < travel_z - 0.02: + sk.move_to([p[0], p[1], travel_z]) + sk.move_to([c[0], c[1], travel_z], yaw=gyaw) + sk.move_to([c[0], c[1], f["zmax"] + 0.03], speed=0.4) + sk.move_to([c[0], c[1], zg], tol=0.003, max_steps=80) + sk.set_gripper(True, steps=12) + sk.move_to([c[0], c[1], carry_z], speed=0.3) + gyaw2 = gyaw if dest_yaw is None else gyaw + _wrap_half(dest_yaw - f["yaw"]) + sk.move_to([dest_xy[0], dest_xy[1], carry_z], yaw=gyaw2) + sk.move_to([dest_xy[0], dest_xy[1], support_z + (zg - f["zmin"]) + clearance], tol=0.003, speed=0.2, + max_steps=150) + sk.hold(4) + sk.set_gripper(False, steps=10) + sk.move_to([dest_xy[0], dest_xy[1], travel_z], speed=0.4) + + def main_task(self, fp=None): + """Ketchup -> basket (the instruction, as an agent without failure knowledge would do it).""" + b = envs.obj_pos(self.env, BASKET) + floor = envs.obj_min_z(self.env, BASKET) + BASKET_FLOOR + self.pick_place(TARGET, b[:2], floor, carry_z=1.27, clearance=0.006, fp=fp) + + def restore(self, name, pose): + """Put box `name` back at `pose` (a remembered footprint: centre xy + long-axis yaw).""" + self.pick_place(name, pose["center"][:2], envs.TABLE_Z, dest_yaw=pose["yaw"], carry_z=1.05, + clearance=0.004) + + def do(self, actions, inst): + for act in actions: + if act[0] == "ketchup_to_basket": + self.main_task(fp=act[1] if len(act) > 1 else None) + elif act[0] == "restore": # ["restore", name, pose] + self.restore(act[1], act[2]) + else: + raise ValueError(act) + + # ------------------------------------------------------------ scripted reference policies + def _guess_pose(self, name, rng): + """nomem control: a random free spot within 15 cm of where the box is now, random yaw.""" + cur = np.array(self.footprint(name)["center"][:2]) + others = [np.array(self.footprint(o)["center"][:2]) for o in BOXES if o != name] + for _ in range(200): + r, a = rng.uniform(0.03, 0.15), rng.uniform(0, 2 * np.pi) + p = cur + r * np.array([np.cos(a), np.sin(a)]) + if _in_rect(p, KNOCK_REGION) and _reach_ok(p) and all(np.linalg.norm(p - o) > 2 * R_BOX + 0.01 for o in others): + return dict(center=[float(p[0]), float(p[1]), 0.0], yaw=float(rng.uniform(-np.pi / 2, np.pi / 2))) + return dict(center=[float(cur[0]), float(cur[1]), 0.0], yaw=float(rng.uniform(-np.pi / 2, np.pi / 2))) + + def _plan(self, kind, inst, a, history, rng, memory): + """Actions of one round: ["ketchup_to_basket"] / ["restore", name, pose].""" + if kind == "naive" or (a == 0 and kind in ("adaptive", "blind", "nomem")): + return [["ketchup_to_basket"]] + if kind == "oracle": # knows the victim: restores it right after the main task (start pose from memory) + return [["ketchup_to_basket"], ["restore", inst["victim"], memory[inst["victim"]]]] + last = history[-1]["outcome"] + if kind == "adaptive": # F2 says which items are out of place; the saved first frame says where they were + acts = [] if last["target_loc"] == "basket" else [["ketchup_to_basket"]] + return acts + [["restore", n, memory[n]] for n in last["moved"]] + if kind == "nomem": # F2 but no start frame: guesses + acts = [] if last["target_loc"] == "basket" else [["ketchup_to_basket"]] + return acts + [["restore", n, self._guess_pose(n, rng)] for n in last["moved"]] + if kind == "blind": # ignores the outcome: redoes the main task (ketchup wherever it is now, jittered grasp) + fp = self.footprint(TARGET) + fp["center"] = (np.array(fp["center"]) + np.r_[rng.normal(0, 0.005, 2), 0.0]).tolist() + return [["ketchup_to_basket", fp]] + raise ValueError(kind) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """Within-episode protocol: one reset, attempt 1 = main task, attempts 2..k = corrective rounds.""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + self.reset_instance(inst) + memory = {n: dict(center=self.start[n]["center"], yaw=self.start[n]["yaw"]) for n in BOXES} # Save + for a in range(k): + actions = self._plan(kind, inst, a, history, rng, memory) + self.do(actions, inst) + self.go_home() + out = self.outcome(inst) + params = dict(actions=[x[:1] if x[0] == "ketchup_to_basket" else + [x[0], x[1], [round(v, 3) for v in x[2]["center"][:2]], round(float(x[2]["yaw"]), 3)] + for x in actions]) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history + + # cross-protocol hooks are not used by this task + def default_params(self, inst): + return dict(policy="naive") + + def oracle_params(self, inst): + return dict(policy="oracle") diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/l6_swap.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/l6_swap.py new file mode 100644 index 0000000000000000000000000000000000000000..1794c23e23f238abf25697524800263760fccea7 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/l6_swap.py @@ -0,0 +1,466 @@ +"""L6-A swap_interrupt: swap two items between identical pads; the second carry is interrupted by a slip. + +Scene: four identical dark round pads (flat markers, no collision). The cream cheese (X) starts on pad A, +the butter (Y) on pad B, pads C and D are empty. Pad positions, which pad is which and the drop spot are +random per seed. Goal: X on B and Y on A. + +Standard procedure: X: A -> C (temporary), Y: B -> A, X: C -> B. During the second carry (whichever item is +carried while the other one has already left its start pad), the carried item "slips": the gripper opens +and the item lands on the table at a hidden spot that is on no pad. Afterwards X sits on C, Y lies on the +table and A, B, D are empty -- the current image no longer shows which empty pad was whose. The information +needed to finish ("what has been done, where did each item start") is only in the agent's own history. + +The drop spot is placed next to a *lure* pad: the spare pad ("spare", 50 %), the carried item's own start pad +("source", 25 %) or its true destination ("dest", 25 %). So "put it on the nearest pad" is usually wrong and +proximity is close to uninformative; a stronger bias towards the start pad would open a memoryless shortcut +(tidy both items onto their nearest pads = undo, then swap again), see the task card. + +Protocol: within (one episode, no reset). Attempt granularity: an attempt is everything the agent does until +it declares the task done; after each attempt the outcome is measured (F1/F2 feedback) and, if it failed, the +agent continues from the current state. The slip is injected once per episode, inside attempt 1 (it is an +in-attempt failure event, reported immediately: see `drain_events`). Scripted references: + + oracle knows the true start layout; after the slip puts Y on A and X on B. + adaptive saves the start layout from its first frame (Save), recalls it after the slip (Retrieve) and + finishes the swap from the right step (Utilize); later attempts fix residual misplacements from + memory + F2 feedback. + naive memoryless continuation (one attempt): after the slip it re-plans from the current frame only -- + the stray item goes to the nearest empty pad, the item that is still on a pad goes to the nearest + remaining empty pad. + blind memoryless restart (k attempts): does not know which step it was at; tidies the stray item onto + the nearest empty pad and then performs the whole swap again from the current frame; every later + attempt again swaps the two items (repeated swap, cf. RMBench). + blind_continue (extra control, not in the acceptance table) attempt 1 = naive, later attempts = swap again. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _wrap, register_generated +from ..task_base import LFFTask, register_task + +N_PADS = 4 +PAD_R = 0.055 # pad radius (11 cm discs); items are 8 x 4.3 x 1.8 cm boxes lying flat +PAD_HALF_T = 0.0008 +PAD_RGBA = (0.22, 0.24, 0.28, 1.0) +SUCC_R = 0.04 # item centre within 4 cm of the pad centre counts as "on that pad" for success +PAD_MIN_DIST = 0.17 +PAD_REGION = (-0.26, 0.04, -0.25, 0.25) # x0, x1, y0, y1 (world) +PAD_REACH = 0.71 # max horizontal distance of a pad centre from the robot base +DROP_REGION = (-0.31, 0.07, -0.30, 0.30) +# beyond ~0.75 m from the base the arm ends up fully stretched (elbow at its joint limit) and the OSC gets stuck +MAX_REACH = 0.73 +DROP_CLEAR = PAD_R + 0.05 # drop centre this far from every pad centre -> item fully off the pads +LURE_MARGIN = 0.03 # the lure pad is nearer to the drop spot than any other pad by at least this much +GRASP_DZ = 0.012 # gripper-site height above the table for a top-down grasp of the flat boxes +LIFT = 0.15 +BASE_X = -0.66 # robot base x (world); base-frame coordinates = (x - BASE_X, y) +LURE_P = (("source", 0.25), ("spare", 0.5), ("dest", 0.25)) + +X, Y = "cream_cheese_1", "butter_1" +NAME = {X: "cream cheese", Y: "butter"} +PADS = [f"pad_{i + 1}" for i in range(N_PADS)] + + +def _pad_xml(model_name): + c = " ".join(f"{v:.3f}" for v in PAD_RGBA) + g = (f' \n' + f' ') + # flat marker without collisions: gravity compensation keeps it from sinking through the table + return _wrap(model_name, g, PAD_HALF_T, PAD_R).replace('', + '') + + +def _yaw_of(env, obj): + R = env.sim.data.body_xmat[envs.body_id(env, obj)].reshape(3, 3) + yaw = float(np.arctan2(R[1, 0], R[0, 0])) # long axis of the boxes = body x + return (yaw + np.pi / 2) % np.pi - np.pi / 2 # boxes are symmetric under pi + + +def drop_spot(pads, src, dest, other_xy, lure, phase, dist): + """Geometry of the injected drop. pads: (N,2); src / dest: start pads of the carried / other item; + other_xy: current xy of the other item. Returns (xy, lure_pad) or (None, None).""" + pads = np.asarray(pads, float) + rest = [i for i in range(len(pads)) if i not in (src, dest)] + # spare = an empty pad that is neither start pad and not the one the other item is parked on + occ = [i for i in rest if np.linalg.norm(pads[i] - other_xy) < PAD_R] + spare_c = [i for i in rest if i not in occ] or rest + spare = max(spare_c, key=lambda i: np.linalg.norm(pads[i] - other_xy)) + lp = {"source": src, "dest": dest, "spare": spare}[lure] + for d in (dist, dist + 0.01, dist - 0.01, dist + 0.02): + for ang in phase + np.linspace(0, 2 * np.pi, 48, endpoint=False): + xy = pads[lp] + d * np.array([np.cos(ang), np.sin(ang)]) + if not (DROP_REGION[0] <= xy[0] <= DROP_REGION[1] and DROP_REGION[2] <= xy[1] <= DROP_REGION[3]): + continue + if np.hypot(xy[0] - BASE_X, xy[1]) > MAX_REACH: + continue + dd = np.linalg.norm(pads - xy, axis=1) + if dd.min() < DROP_CLEAR or np.linalg.norm(xy - other_xy) < 0.12: + continue + if np.any(np.delete(dd, lp) < dd[lp] + LURE_MARGIN): + continue + return xy, int(lp) + return None, None + + +@register_task +class SwapInterrupt(LFFTask): + name = "l6_swap_interrupt" + level = "L6" + category = "procedural_memory" + capabilities = ("Perceive", "Save", "Retrieve", "Utilize") + protocol = "within" + max_attempts = 5 + instruction = ("Swap the positions of the cream cheese and the butter: each must end up on the round pad " + "where the other one started. You may use the empty pads as temporary spots.") + instruction_indirect = ("Swap the positions of the pale blue box with the oval logo and the red-and-yellow " + "box: each must end up on the round pad where the other one started. You may use the " + "empty pads as temporary spots.") + inject = True # set False to run the same scene without the slip (sanity check) + + # ------------------------------------------------------------ scene + def make_bddl(self): + cats = [register_generated(f"LffSwapPad{L}", _pad_xml(f"lff_swap_pad_{L.lower()}")) for L in "ABCD"] + objs = [(X, "cream_cheese", "cc_region", (-0.21, -0.21, -0.19, -0.19)), + (Y, "butter", "bu_region", (-0.21, 0.19, -0.19, 0.21)), + (PADS[0], cats[0], "p1_region", (0.05, -0.21, 0.07, -0.19)), + (PADS[1], cats[1], "p2_region", (0.05, 0.19, 0.07, 0.21)), + (PADS[2], cats[2], "p3_region", (-0.06, -0.01, -0.04, 0.01)), + (PADS[3], cats[3], "p4_region", (-0.31, -0.01, -0.29, 0.01))] + return write_bddl(self.name, self.instruction, objs) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + for _ in range(1000): + pads = [] + while len(pads) < N_PADS: + p = np.array([rng.uniform(*PAD_REGION[:2]), rng.uniform(*PAD_REGION[2:])]) + if np.hypot(p[0] - BASE_X, p[1]) > PAD_REACH: + continue + if all(np.linalg.norm(p - q) >= PAD_MIN_DIST for q in pads): + pads.append(p) + pads = np.array(pads) + x_pad, y_pad = 0, 1 # pad order is already random + u, acc = rng.uniform(), 0.0 + for lure, pr in LURE_P: + acc += pr + if u < acc: + break + phase, dist = float(rng.uniform(0, 2 * np.pi)), float(rng.uniform(0.115, 0.14)) + # canonical execution: X parked on the empty pad nearest to its start pad, then Y is carried + empt = [i for i in range(N_PADS) if i not in (x_pad, y_pad)] + buf = min(empt, key=lambda i: np.linalg.norm(pads[i] - pads[x_pad])) + xy, lp = drop_spot(pads, y_pad, x_pad, pads[buf], lure, phase, dist) + if xy is None: + continue + return dict(seed=int(seed), pads=pads.round(4).tolist(), x_pad=x_pad, y_pad=y_pad, + yaw_x=float(rng.uniform(-0.3, 0.3)), yaw_y=float(rng.uniform(-0.3, 0.3)), + lure=lure, drop_phase=phase, drop_dist=dist, drop_yaw=float(rng.uniform(-1.4, 1.4)), + trigger_dist=float(rng.uniform(0.05, 0.10)), + canonical_buffer=int(buf), canonical_drop_xy=xy.round(4).tolist()) + raise RuntimeError("could not sample a layout") + + def apply_instance(self, inst): + for i, p in enumerate(inst["pads"]): + envs.set_obj_pose(self.env, PADS[i], [p[0], p[1], envs.TABLE_Z + PAD_HALF_T + 0.0001]) + envs.place_upright(self.env, X, inst["pads"][inst["x_pad"]], inst["yaw_x"]) + envs.place_upright(self.env, Y, inst["pads"][inst["y_pad"]], inst["yaw_y"]) + self.env.sim.forward() + self.slip = None + self.events = [] + self._event_cursor = 0 # for drain_events (harness, per tool call) + self._outcome_cursor = 0 # for outcome (per attempt) + self._inst = inst + + def reset_instance(self, inst, recorder=None): + sk = super().reset_instance(inst) + self._user_recorder = recorder + sk.recorder = self._on_step # slip trigger is checked on every control step + sk.record_every = 1 + self._home = sk.eef_pos() + return sk + + def go_home(self): + """Lift the arm out of the camera's way (end of an attempt).""" + p = self.sk.eef_pos() + self.sk.move_to([p[0], p[1], max(p[2], self._home[2])]) + self.sk.move_to(self._home) + + # ------------------------------------------------------------ slip injection (state triggered) + def _on_step(self, env): + if self.inject and self.slip is None: + self._maybe_slip() + if self._user_recorder is not None and self.sk.n_steps % 4 == 0: + self._user_recorder(env) + + def _maybe_slip(self): + """Fires during the first carry of an item while the other item has already left its start pad, + i.e. the second transport of a swap, whatever order the agent chose.""" + inst, env = self._inst, self.env + pads = np.asarray(inst["pads"]) + start = {X: inst["x_pad"], Y: inst["y_pad"]} + for o, other in ((X, Y), (Y, X)): + p = envs.obj_pos(env, o) + if p[2] < envs.TABLE_Z + 0.05: + continue + if np.linalg.norm(p[:2] - pads[start[o]]) < inst["trigger_dist"]: + continue + q = envs.obj_pos(env, other) + if np.linalg.norm(q[:2] - pads[start[other]]) < PAD_R: + continue + if not self.sk.holding(o): + continue + self._do_slip(o, other, q[:2]) + return + + def _do_slip(self, o, other, other_xy): + inst = self._inst + start = {X: inst["x_pad"], Y: inst["y_pad"]} + args = (inst["pads"], start[o], start[other], other_xy) + xy, lp = drop_spot(*args, inst["lure"], inst["drop_phase"], inst["drop_dist"]) + lure = inst["lure"] + for alt in ("source", "spare", "dest"): # fallback (only if the agent did something unusual) + if xy is not None: + break + xy, lp = drop_spot(*args, alt, inst["drop_phase"], inst["drop_dist"]) + lure = alt + if xy is None: + xy, lp, lure = np.asarray(inst["canonical_drop_xy"]), -1, "fallback" + envs.place_upright(self.env, o, xy, inst["drop_yaw"]) + self.sk.grip = -1.0 # the gripper opens + self.env.sim.forward() + text = f"The {NAME[o]} slipped out of the gripper and fell onto the table." + self.slip = dict(obj=o, xy=[float(v) for v in xy], lure=lure, lure_pad=lp, step=int(self.sk.n_steps)) + self.events.append(dict(step=int(self.sk.n_steps), kind="slip", obj=o, text=text)) + + def drain_events(self): + """Event texts since the last call (for the harness: append to the current tool-call report).""" + ev = self.events[self._event_cursor:] + self._event_cursor = len(self.events) + return [e["text"] for e in ev] + + # ------------------------------------------------------------ perception helpers (what an agent can see) + def pad_xy(self): + return np.array([envs.obj_pos(self.env, p)[:2] for p in PADS]) + + def on_pad(self, o, r=PAD_R): + d = np.linalg.norm(self.pad_xy() - envs.obj_pos(self.env, o)[:2], axis=1) + return int(np.argmin(d)) if d.min() < r else None + + def empty_pads(self): + occ = {self.on_pad(X), self.on_pad(Y)} + return [i for i in range(N_PADS) if i not in occ] + + def _nearest(self, cands, xy): + pads = self.pad_xy() + return min(cands, key=lambda i: np.linalg.norm(pads[i] - np.asarray(xy)[:2])) + + @staticmethod + def _bf(xy): + return f"({xy[0] - BASE_X:.2f}, {xy[1]:+.2f})" + + def pad_label(self, i, cur=None): + """Robot-centric name of pad i relative to the other pads (no coordinates in agent feedback).""" + cur = self.pad_xy() if cur is None else cur + c = cur.mean(axis=0) + fb = "far" if cur[i][0] > c[0] else "near" + lr = "left" if cur[i][1] > c[1] else "right" + same = [j for j in range(len(cur)) if ("far" if cur[j][0] > c[0] else "near") == fb + and ("left" if cur[j][1] > c[1] else "right") == lr] + lab = f"the {fb}-{lr} pad" + if len(same) > 1: # two pads in the same quadrant: tell them apart left to right + order = sorted(same, key=lambda j: -cur[j][1]) + side = "more to the robot's left" if order.index(i) == 0 else "more to the robot's right" + lab += f" ({side} of the two)" + return lab + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + envs.settle(self.env, 20) + pads = np.asarray(inst["pads"]) + target = {X: inst["y_pad"], Y: inst["x_pad"]} + res, ok = {}, True + for o in (X, Y): + p = envs.obj_pos(self.env, o) + dt = float(np.linalg.norm(p[:2] - pads[target[o]])) + resting = bool(envs.TABLE_Z - 0.01 < p[2] < envs.TABLE_Z + 0.05 and not self.sk.holding(o)) + res[o] = dict(xy=[float(p[0]), float(p[1])], on_pad=self.on_pad(o), dist_to_target=dt, resting=resting) + ok = ok and resting and dt <= SUCC_R + # F2 detail: only what is observable now + events of this attempt; nothing about the start layout + parts = [] + cur = self.pad_xy() + for o in (X, Y): + r = res[o] + if r["on_pad"] is not None: + parts.append(f"the {NAME[o]} is on {self.pad_label(r['on_pad'], cur)}") + else: + dd = np.linalg.norm(cur - np.asarray(r["xy"]), axis=1) + d = dd.min() - PAD_R + parts.append(f"the {NAME[o]} is on the table, on no pad " + f"({100 * d:.0f} cm from the edge of {self.pad_label(int(dd.argmin()), cur)})") + emp = [self.pad_label(i, cur) for i in self.empty_pads()] + detail = ("Now " + "; ".join(parts) + "; empty: " + (", ".join(emp) if emp else "none") + + " (left/right = the robot's left/right, near/far = toward/away from the robot).") + new_ev = [e["text"] for e in self.events[self._outcome_cursor:]] + self._outcome_cursor = len(self.events) + if new_ev: + detail = "During this attempt: " + " ".join(new_ev) + " " + detail + return dict(success=bool(ok), items={NAME[o]: res[o] for o in (X, Y)}, + slip=self.slip, detail=detail) + + # ------------------------------------------------------------ motion + def _pick(self, o): + sk = self.sk + for _ in range(2): + p = envs.obj_pos(self.env, o) + sk.grasp_at(p[:2], envs.TABLE_Z + GRASP_DZ, yaw=_yaw_of(self.env, o), lift=LIFT) + if sk.holding(o): + return True + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], envs.TABLE_Z + LIFT]) + return False + + def _move(self, o, pad, log): + """Pick item o and put it on pad `pad`. Returns False if the item slipped on the way.""" + n_ev = len(self.events) + frm = self.on_pad(o) + ok = self._pick(o) + rec = dict(obj=NAME[o], from_pad=frm, to_pad=int(pad), grasped=ok) + log.append(rec) + if not ok: + return True + xy = self.pad_xy()[pad] + sk = self.sk + sk.move_to([xy[0], xy[1], envs.TABLE_Z + GRASP_DZ + LIFT]) # carry (the slip may fire here) + if len(self.events) > n_ev: + rec["slipped"] = True + return False + sk.move_to([xy[0], xy[1], envs.TABLE_Z + GRASP_DZ + 0.004], tol=0.004) + sk.set_gripper(False, steps=12) + sk.move_to([xy[0], xy[1], envs.TABLE_Z + GRASP_DZ + 0.10]) + return True + + def _run(self, moves, log): + """moves: list of (item, pad) computed up front (an open-loop plan). Stops at a slip.""" + for o, pad in moves: + if not self._move(o, pad, log): + return False + return True + + def _swap_now(self, log, rng=None): + """The standard swap of the two items' *current* pads via an empty pad (no memory).""" + a, b = self.on_pad(X), self.on_pad(Y) + empt = self.empty_pads() + if a is None or b is None or not empt: + return + buf = int(rng.choice(empt)) if rng is not None else self._nearest(empt, self.pad_xy()[a]) + self._run([(X, buf), (Y, a), (X, b)], log) + + def _tidy_stray(self, log): + for o in (X, Y): + if self.on_pad(o) is None and self.empty_pads(): + self._move(o, self._nearest(self.empty_pads(), envs.obj_pos(self.env, o)), log) + + def _fixup(self, target, log): + """Move items until each is on its target pad (target: item -> pad index).""" + pads = self.pad_xy() + for _ in range(6): + todo = [o for o in (Y, X) if np.linalg.norm(envs.obj_pos(self.env, o)[:2] - pads[target[o]]) > SUCC_R] + if not todo: + return + free = [o for o in todo if self.on_pad({X: Y, Y: X}[o], r=PAD_R) != target[o]] + if free: + self._move(free[0], target[free[0]], log) + else: # the two items block each other: park one on an empty pad that is no one's target + o = todo[0] + spare = [i for i in self.empty_pads() if i not in target.values()] or self.empty_pads() + self._move(o, self._nearest(spare, envs.obj_pos(self.env, o)), log) + + # ------------------------------------------------------------ scripted references (within protocol) + def _memory(self): + """Save: what the agent sees in its first frame -- which pad (by position) each item starts on.""" + return {X: self.pad_xy()[self.on_pad(X)].tolist(), Y: self.pad_xy()[self.on_pad(Y)].tolist()} + + def saved_memory(self, first): + """What the adaptive policy recalls after the slip (identity; patched by the mismatched-memory control).""" + return first + + def _attempt1(self, kind, inst, mem, rng, first): + log = [] + plan = dict(kind=kind, moves=log) + a = self._nearest(range(N_PADS), first[X]) # the open-loop plan is made from the first frame + b = self._nearest(range(N_PADS), first[Y]) + empt = [i for i in range(N_PADS) if i not in (a, b)] + buf = self._nearest(empt, self.pad_xy()[a]) + plan["plan"] = f"X->{buf}, Y->{a}, X->{b}" + if self._run([(X, buf), (Y, a), (X, b)], log): + plan["recovery"] = "none (no slip)" + return plan + # ---- the carry was interrupted by the slip: recover + if kind == "oracle": # privileged: true start layout + plan["recovery"] = "oracle: true layout" + self._fixup({X: inst["y_pad"], Y: inst["x_pad"]}, log) + elif kind == "adaptive": # Retrieve the saved first frame and the step log; finish from the right step + ta = self._nearest(range(N_PADS), mem[X]) + tb = self._nearest(range(N_PADS), mem[Y]) + plan["recovery"] = f"memory: butter -> pad {ta} (cream cheese's start), cream cheese -> pad {tb}" + self._fixup({X: tb, Y: ta}, log) + elif kind in ("naive", "blind_continue"): # memoryless continuation from the current frame + stray = [o for o in (X, Y) if self.on_pad(o) is None] + parked = [o for o in (X, Y) if self.on_pad(o) is not None] + plan["recovery"] = "current frame: stray item -> nearest empty pad; parked item -> nearest empty pad" + for o in stray: + self._move(o, self._nearest(self.empty_pads(), envs.obj_pos(self.env, o)), log) + for o in parked: + if self.empty_pads(): + self._move(o, self._nearest(self.empty_pads(), envs.obj_pos(self.env, o)), log) + elif kind == "blind": # memoryless restart: tidy up, then the whole swap again + plan["recovery"] = "restart: stray item -> nearest empty pad, then swap again" + self._tidy_stray(log) + self._swap_now(log, rng) + else: + raise ValueError(kind) + return plan + + def _retry(self, kind, inst, mem, rng): + log = [] + plan = dict(kind=kind, moves=log) + if kind == "adaptive": + ta = self._nearest(range(N_PADS), mem[X]) + tb = self._nearest(range(N_PADS), mem[Y]) + plan["recovery"] = "memory + F2: fix items not on their targets" + self._fixup({X: tb, Y: ta}, log) + elif kind in ("blind", "blind_continue"): + plan["recovery"] = "no history: tidy, then swap the two items again" + self._tidy_stray(log) + self._swap_now(log, rng) + else: + raise ValueError(kind) + return plan + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + self.reset_instance(inst) + first = self._memory() + mem = self.saved_memory(first) + history = [] + for a in range(k): + plan = self._attempt1(kind, inst, mem, rng, first) if a == 0 else self._retry(kind, inst, mem, rng) + self.go_home() # "done": the agent declares the attempt finished + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=plan, outcome=out)) + if on_attempt: + on_attempt(a, plan, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history + + # cross-protocol hooks are not used by this task + def default_params(self, inst): + return dict(policy="naive") + + def oracle_params(self, inst): + return dict(policy="oracle") diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/lh_clear_cover.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/lh_clear_cover.py new file mode 100644 index 0000000000000000000000000000000000000000..542d519109d1f085f749fe2db4dd0c20b51281b5 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/lh_clear_cover.py @@ -0,0 +1,657 @@ +"""LH clear_cover: sort four cubes into two open boxes by colour -- but in half of the instances one box is covered by a +loose clear acrylic lid. A cube carried over that box and released stops on the lid at rim height; it is not in the box. + +Family: long-horizon self-disturbance / common sense ("state_restoration"; design P2-2 in +research_notes/P1P2_加深与常识任务设计.md): four pick-and-place stages that are each easy for a frontier model; the +trap is a commonsense one -- "a box can have a transparent lid" -- and the failure is only visible from the right +viewpoint: from the side (agentview) the cube visibly sits on top of the box, at rim height, with the box floor visible +below it; from straight above (the wrist camera) it lies inside the box's outline and looks almost the same as a cube +that is inside (design rule R5: a top-down view hides height differences). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * two open boxes (fixtures; inside 12 x 12 cm, walls 5 cm high and 8 mm thick, rim 5.6 cm above the table, light + floor) with red and with blue walls, centres at x in [-0.14, -0.08], y = +-(0.12-0.14) (24-28 cm apart); which + colour is on the left is random. The instruction names the boxes by colour, not "left / right" (the design draft's + wording), so that no failure comes from whose left is meant; + * four 4 cm cubes (38 g), two red and two blue, in a row in front of the boxes (x = -0.33, near the robot; 14 cm + apart, shuffled, yaw +-23 deg); + * the clear lid (covered instances only): a loose 13.4 x 13.4 cm, 8 mm clear plate lying on one box's walls, + 1 mm inside their outer faces (no overhang). v2 (2026-10-13, after the Sonnet pilot np_lh_clear_cover): rendered + nearly invisible -- alpha 0.03, matte (no specular glint), no edge highlight (v1: alpha 0.10 + bright edges, and the + pilot agent named "the transparent lid" from the first images); heavy (1 kg; mass is not visible) with friction 1.0 + and priority for all its contacts and medium-stiff contacts, so incidental contact by the hand does not knock it off + (v1, 0.12 kg / mu 0.3 / 6 mm overhang / very stiff contacts: a probe descent between the boxes knocked it off in the + pilot's very first motions). Transparent geoms do not write MuJoCo's depth buffer: in the depth maps + (--perception rgbd) the lid is not there at all. In uncovered instances the lid is parked on the floor far outside + the workspace and the cameras' view. + +Hidden variable: whether a box is covered and which one. Exactly 10 of every 20 consecutive seeds are covered (5 red / +5 blue box): (seed * 7) mod 20 < 10, like lh_lid_box's balanced blocks. + +Why the natural plan fails: carry each cube over its box and release it a few cm above the rim. Over the covered box the +cube lands on the lid and stays there (v2, measured: drops of 1-8 cm, 48/48 stay on the lid, the lid does not move; +pressing a held cube down towards the box floor stops the arm 4.2 cm above the target, the lid moves <= 0.8 mm, 12/12 +still covering). After the release the cube visibly sits on top of the box in agentview (its bottom 0.8 cm above the +rim, the box floor visible below it); checking only from above it looks as if it were in the box (~1.3x bigger). +What must be learned: look from the side / compare heights before finishing, notice the cubes resting at rim height, +remove the lid (push its edge horizontally with the closed gripper, fingertips between the rim and the lid's top face -- +what the pilot agent did when it saw the v1 lid) and put the cubes in (within the attempt), or check for a lid and +remove it before placing anything (across attempts). Pressing the fingertips onto the lid and dragging no longer moves +it (v2: hand friction = rim friction, by design, because a hand landing on the lid while moving sideways is exactly +what knocked the v1 lid off). +Measured, 2 covered instances x 86 Sonnet-like incidental motions (probe descents to 2-5 cm next to / between the +boxes, transits at 11-20 cm over the covered box, low lateral moves next to the boxes): the box got uncovered 1/172 +(v1: 57/172), the lid moved > 2 cm 20/172 (v1: 97/172); a crash sweep through the boxes at 3 cm still knocks it (1/2). +Deliberate edge push, agent-style commands: fingertip target 2-10 mm below the lid's top face 10/10 (+ 8/8 in the +parameter sweep), at the top face 1/2, above it 0/2. + +Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (every cube in the +cavity of the box of its colour -- centre inside the cavity, lowest point below the rim --, nothing held, the lid not on +a box, scene static) plus a per-step event log (cube stages achieved / lost / restored, rested_on_cover, left_cover, +cover_removed, cover_on_box, in_wrong_box) for the server log; F1 gives the agent only success / failure. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, _wrap, box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +Z = envs.TABLE_Z +TIP = envs.FINGERTIP_BELOW_SITE +# ---------------------------------------------------------------- geometry / physics +CUBE_E = 0.04 +CUBE_DENS = 600.0 # -> 38 g +BOX_IN = 0.06 # inner half width (12 x 12 cm cavity) +WALL_T, FLOOR_T, WALL_H = 0.008, 0.006, 0.05 +BOX_OUT = BOX_IN + WALL_T +RIM = FLOOR_T + WALL_H # rim height above the table +WALL_MU = 0.3 # walls (cube contacts; the lid's own friction has priority in its contacts) +LID_T = 0.008 # thick enough that a horizontal push at 'lid height' finds its edge (v1 draft: 4 mm, see the card) +LID_HALF = BOX_OUT - 0.001 # v2: no overhang (1 mm inside the walls' outer faces): a hand landing on its edge cannot tip it +LID_MASS = 1.0 # v2: heavy (a thick glass-like plate; mass is not visible): incidental bumps move it much less +LID_MU = 1.0 # v2: with priority, used for ALL lid contacts (rim, hand, fingers, cubes): pressing on the lid and moving +# sideways cannot drag it (hand friction == rim friction, and the rim also carries the lid's weight) +LID_SOLREF = (0.005, 1.0) # v2: medium-stiff contacts (v1 used _SOLID: a finger that caught the lid's edge while the +LID_SOLIMP = (0.95, 0.99, 0.001) # arm pressed on could squeeze it against the wall and launch it 16-37 cm) +LID_TOP = RIM + LID_T # lid top surface above the table when it lies on a box +LID_RGBA = (0.85, 0.90, 0.95, 0.03) # v2: near-invisible, no edge highlight, no specular (material below) +PARK = (0.0, 1.4) # lid parked on the floor (world z = 0), out of reach and out of view (uncovered instances) + +COLORS = ("red", "blue") +CUBE_RGBA = dict(red=(0.88, 0.10, 0.08, 1.0), blue=(0.10, 0.25, 0.88, 1.0)) +WALL_RGBA = dict(red=(0.72, 0.26, 0.22, 1.0), blue=(0.22, 0.34, 0.72, 1.0)) +FLOOR_RGBA = (0.86, 0.85, 0.82, 1.0) +CUBES = [f"{c}_cube_{i}" for c in COLORS for i in (1, 2)] +BOXES = {c: f"{c}_box_1" for c in COLORS} +LID = "clear_lid_1" + +IN_MARGIN = 0.010 # a cube counts as in a box if its centre is within BOX_IN - IN_MARGIN of the box centre (each axis) +BELOW_RIM = 0.005 # ... and its lowest point is at least this far below the rim +Z_CARRY = 0.15 # scripted transit height of the grasp point above the table (Sonnet: 11-20 cm) +DROP = 0.04 # scripted release: cube bottom this far above the rim (Sonnet-like 3-5 cm) +SLOT = 0.028 # two cubes per box: +-2.8 cm from the centre along y +PUSH_DEPTH = 0.004 # scripted edge push: fingertips this far below the lid's top face (lid 8 mm thick) +PUSH_SPEED = 0.06 + + +def _color(name): + return name.split("_")[0] + + +def _fb(v): + return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}" + + +def _lr(v): + return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}" + + +def box_xml_cc(name, wall_rgba): + """open-top box, body origin at the centre of its footprint on the table (z = 0 = table top)""" + o = BOX_OUT + parts = [((0, 0, FLOOR_T / 2), (o, o, FLOOR_T / 2), FLOOR_RGBA, 1.0), + ((BOX_IN + WALL_T / 2, 0, RIM / 2), (WALL_T / 2, o, RIM / 2), wall_rgba, WALL_MU), + ((-BOX_IN - WALL_T / 2, 0, RIM / 2), (WALL_T / 2, o, RIM / 2), wall_rgba, WALL_MU), + ((0, BOX_IN + WALL_T / 2, RIM / 2), (BOX_IN, WALL_T / 2, RIM / 2), wall_rgba, WALL_MU), + ((0, -BOX_IN - WALL_T / 2, RIM / 2), (BOX_IN, WALL_T / 2, RIM / 2), wall_rgba, WALL_MU)] + g = [] + for k, (p, s, c, mu) in enumerate(parts): + g.append(f' ') + g.append(f' ') + return f""" + + + +{chr(10).join(g)} + + + + + + +""" + + +def lid_xml(name): + """clear plate: one collision box + a near-invisible visual twin with a matte material (no specular glint)""" + h, t = LID_HALF, LID_T / 2 + g = [f' ', + f' '] + xml = _wrap(name, "\n".join(g), t, float(np.hypot(h, h))) + mat = (f' \n \n \n') + return xml.replace(" ", mat + " ", 1) + + +class CoverSkills(Skills): + """Skills that feed the task's per-step monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class ClearCover(LFFTask): + name = "lh_clear_cover" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Plan", "Utilize") + protocol = "cross" + max_attempts = 3 + # careful oracle: 4 pick-and-places (~7 commands each = 28) + pushing the lid off (~5) + looking around (~15); + # one recovery: pushing the lid off + re-placing the cubes that were on it (~5 + 2 x 7) -> ~70; Sonnet looks after + # every step and calibrates the wrist camera (cla4: 10+ observe / probe commands) + agent_max_steps = 110 + instruction = "Put the two red cubes into the red box and the two blue cubes into the blue box." + instruction_indirect = "Sort the four small cubes by colour: each cube goes into the box whose walls have its colour." + agent_object_names = ["red cube", "red cube", "blue cube", "blue cube", "red box", "blue box"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs, fx = [], [] + for j, c in enumerate(COLORS): + bx = register_generated(f"LffCc{c.title()}Box", box_xml_cc(f"lff_cc_{c}_box", WALL_RGBA[c]), free=False) + fx.append((BOXES[c], bx, f"{c}_box_region", (-0.12, 0.12 - 0.26 * j, -0.10, 0.14 - 0.26 * j))) + k = 0 + for c in COLORS: + for i in (1, 2): + ab = "AB"[i - 1] + cat = register_generated(f"LffCc{c.title()}Cube{ab}", + box_xml(f"lff_cc_{c}_cube_{ab.lower()}", (CUBE_E / 2,) * 3, CUBE_RGBA[c], + density=CUBE_DENS)) + objs.append((f"{c}_cube_{i}", cat, f"{c}_cube_{i}_region", + (-0.34, -0.22 + 0.14 * k, -0.32, -0.20 + 0.14 * k))) + k += 1 + lid = register_generated("LffCc2ClearLid", lid_xml("lff_cc2_clear_lid")) + objs.append((LID, lid, "lid_region", (0.20, -0.01, 0.22, 0.01))) + return write_bddl(self.name, "put the cubes into the boxes of their colour", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.box_bid = {c: m.body_name2id(self.env.fixtures_dict[BOXES[c]].root_body) for c in COLORS} + self.lid_gids = set(envs.obj_geom_ids(self.env, LID)) + self.cube_gids = {n: set(envs.obj_geom_ids(self.env, n)) for n in CUBES} + self.robot_gids = set(envs.robot_geom_ids(self.env)) + self.inst = None + self.mon = None + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + bx = float(rng.uniform(-0.13, -0.09)) + left = str(rng.choice(COLORS)) + boxes = {} + for c in COLORS: + s = 1.0 if c == left else -1.0 + boxes[c] = [bx + float(rng.uniform(-0.01, 0.01)), s * float(rng.uniform(0.12, 0.14))] + slots = [-0.21, -0.07, 0.07, 0.21] + perm = rng.permutation(4) + start = {CUBES[i]: [float(-0.33 + rng.uniform(-0.01, 0.01)), float(slots[j] + rng.uniform(-0.01, 0.01))] + for j, i in enumerate(perm)} + # balanced like lh_lid_box: exactly 10 of every 20 consecutive seeds covered (5 red box, 5 blue box) + r = (int(seed) * 7) % 20 + cover = "red" if r < 5 else ("blue" if r < 10 else None) + return dict(seed=int(seed), boxes=boxes, left_box=left, start=start, + start_yaw={k: float(rng.uniform(-0.4, 0.4)) for k in CUBES}, cover=cover, + cover_side=(None if cover is None else ("left" if cover == left else "right")), + lid_off=[float(v) for v in rng.uniform(-0.004, 0.004, 2)], lid_yaw=float(rng.uniform(-0.05, 0.05))) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + for c in COLORS: + m.body_pos[self.box_bid[c]] = [inst["boxes"][c][0], inst["boxes"][c][1], Z] + m.body_quat[self.box_bid[c]] = [1.0, 0.0, 0.0, 0.0] + for name, xy in inst["start"].items(): + envs.place_upright(self.env, name, xy, yaw=inst["start_yaw"][name]) + if inst["cover"]: + b = inst["boxes"][inst["cover"]] + envs.set_obj_pose(self.env, LID, [b[0] + inst["lid_off"][0], b[1] + inst["lid_off"][1], + Z + RIM + LID_T / 2 + 0.0005], yaw=inst["lid_yaw"]) + else: + envs.set_obj_pose(self.env, LID, [PARK[0], PARK[1], LID_T / 2 + 0.002]) + envs.set_friction(self.env, LID, LID_MU, priority=2) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.mon = None + self.sk = CoverSkills(self.env, self, recorder=recorder) + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ state helpers + def held(self, name): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name])) + + def cube_rel(self, name, color): + return envs.obj_pos(self.env, name)[:2] - np.asarray(self.inst["boxes"][color]) + + def in_box(self, name, color, margin=IN_MARGIN): + """centre inside the cavity (per axis), lowest point below the rim, not held""" + rel = self.cube_rel(name, color) + return bool(np.max(np.abs(rel)) <= BOX_IN - margin and envs.obj_min_z(self.env, name) < Z + RIM - BELOW_RIM + and not self.held(name)) + + def where_box(self, name): + for c in COLORS: + if self.in_box(name, c): + return c + return None + + def lid_pos(self): + return envs.obj_pos(self.env, LID) + + def covering(self): + """colour of the box the lid lies on (centre within the box's outer footprint + 1 cm, above the floor), or None""" + p = self.lid_pos() + for c in COLORS: + rel = np.abs(p[:2] - np.asarray(self.inst["boxes"][c])) + if rel[0] <= BOX_OUT + 0.01 and rel[1] <= BOX_OUT + 0.01 and p[2] > Z + 0.02: + return c + return None + + def _touching(self, gids_a, gids_b): + return envs.contacts_between(self.env, gids_a, gids_b) + + def on_cover(self, name, moving_ok=False): + """the cube rests on the lid while the lid lies on a box (contact, not held, slow -- unless `moving_ok`: the + monitor keeps a cube that came to rest on the lid "on" while it rides along with the lid being pushed)""" + if self.covering() is None or self.held(name): + return False + if not self._touching(self.cube_gids[name], self.lid_gids): + return False + if moving_ok: + return True + _, da = envs.free_joint_addr(self.env, name) + return bool(np.linalg.norm(self.env.sim.data.qvel[da:da + 3]) < 0.05) + + def stage_values(self): + v = {f"{n}_in_box": self.in_box(n, _color(n)) for n in CUBES} + v["cover_off_boxes"] = self.covering() is None + return v + + # ------------------------------------------------------------ per-step monitor + def _init_monitor(self): + self.mon = dict(step=0, state={f"{n}_in_box": False for n in CUBES}, ever=set(), lost=set(), events=[], + on_cover={n: False for n in CUBES}, cover=self.covering(), wrong={n: None for n in CUBES}, + last_touch={n: None for n in CUBES}, rested=[], cover_removed_step=None) + + def _touches(self): + d = self.env.sim.data + out = {} + for i in range(d.ncon): + c = d.contact[i] + for n, g in self.cube_gids.items(): + other = c.geom2 if c.geom1 in g else (c.geom1 if c.geom2 in g else None) + if other is None: + continue + if other in self.robot_gids: + out[n] = "robot" + elif other in self.lid_gids and out.get(n) != "robot": + out[n] = "lid" + return out + + def monitor_step(self): + mon = self.mon + if mon is None: + return + mon["step"] += 1 + step = self.sk.n_steps if self.sk is not None else mon["step"] + for n, who in self._touches().items(): + if who == "robot": + mon["last_touch"][n] = step + if mon["step"] % 2: + return # predicates every other control step (0.1 s) + cov = self.covering() + if cov != mon["cover"]: + if mon["cover"] is not None and cov is None: + mon["events"].append(dict(step=step, pred="cover", ev="cover_removed", box=mon["cover"])) + mon["cover_removed_step"] = step + elif cov is not None: + mon["events"].append(dict(step=step, pred="cover", ev="cover_on_box", box=cov)) + mon["cover"] = cov + for n in CUBES: + oc = self.on_cover(n, moving_ok=mon["on_cover"][n]) + if oc != mon["on_cover"][n]: + mon["on_cover"][n] = oc + if oc: + mon["rested"].append(dict(step=step, cube=n)) + mon["events"].append(dict(step=step, pred=f"{n}_on_cover", ev="rested_on_cover" if oc else "left_cover", + cube=n, box=cov)) + key = f"{n}_in_box" + was = mon["state"][key] + now = self.in_box(n, _color(n), IN_MARGIN if not was else IN_MARGIN - 0.005) + if now != was: + self._event(key, now, step, n) + other = [c for c in COLORS if c != _color(n)][0] + wr = other if self.in_box(n, other) else None + if wr != mon["wrong"][n]: + mon["wrong"][n] = wr + if wr: + mon["events"].append(dict(step=step, pred=key, ev="in_wrong_box", cube=n, box=wr)) + + def _event(self, key, now, step, n): + mon = self.mon + mon["state"][key] = now + if now: + ev = "restored" if key in mon["lost"] else "achieved" + mon["ever"].add(key) + mon["lost"].discard(key) + mon["events"].append(dict(step=step, pred=key, ev=ev)) + return + if self.held(n): + cause = "picked_up" + else: + lt = mon["last_touch"][n] + cause = "robot" if lt is not None and step - lt <= 60 else "other" + mon["lost"].add(key) + mon["events"].append(dict(step=step, pred=key, ev="lost", cause=cause)) + + # ------------------------------------------------------------ outcome + def _static(self): + d = self.env.sim.data + for name in CUBES + [LID]: + _, da = envs.free_joint_addr(self.env, name) + if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5: + return False + return True + + def outcome(self, inst): + envs.settle(self.env, 30) + mon = self.mon + vals = self.stage_values() + static = self._static() + held = [n for n in CUBES if self.held(n)] + on_cover = [n for n in CUBES if self.on_cover(n)] + wrong = [n for n in CUBES if not vals[f"{n}_in_box"] and self.where_box(n) is not None] + missing = [n for n in CUBES if not vals[f"{n}_in_box"]] + cov = self.covering() + success = bool(all(vals.values()) and static and not held) + failure = None + if not success: + failure = ("held" if held else "cube_on_cover" if on_cover else "wrong_box" if wrong else + "cube_not_in_box" if missing else "cover_on_box" if cov is not None else "not_static") + regress = [e for e in mon["events"] if e["ev"] == "lost"] + restored = [e for e in mon["events"] if e["ev"] == "restored"] + rested_cubes = sorted({r["cube"] for r in mon["rested"]}) + parts = [] + if success: + parts.append("All four cubes are in the boxes of their colour.") + for n in missing: + c = _color(n) + txt = f"A {c} cube is not in the {c} box: " + if n in held: + parts.append(txt + "it is still held by the gripper.") + continue + p = envs.obj_pos(self.env, n) + rel = self.cube_rel(n, c) + if n in on_cover: + txt += (f"it rests on a clear acrylic lid that lies on the {cov} box, " + f"{100 * (envs.obj_min_z(self.env, n) - Z - FLOOR_T):.1f} cm above the box floor") + elif self.where_box(n) is not None: + txt += f"it is in the {self.where_box(n)} box" + else: + h = envs.obj_min_z(self.env, n) - Z + txt += ("it lies on the table" if h < 0.005 else f"it lies {100 * h:.1f} cm above the table") + txt += f", its centre {_fb(rel[0])} and {_lr(rel[1])} of the {c} box's centre" + if n in rested_cubes and n not in on_cover: + txt += " (it had come to rest on the clear lid earlier)" + parts.append(txt + ".") + if cov is not None: + parts.append(f"A clear acrylic lid lies on the {cov} box.") + if not static and all(vals.values()) and not held: + parts.append("Something was still moving at the end.") + if mon["cover_removed_step"] is not None and cov is None: + parts.append("The clear lid was pushed off its box.") + out = dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, + events=mon["events"], n_regressions=len(regress), n_restored=len(restored), + covered=inst["cover"], trap_fired=bool(mon["rested"]), n_rested_on_cover=len(mon["rested"]), + rested_cubes=rested_cubes, cover_removed=mon["cover_removed_step"] is not None, + cover_removed_step=mon["cover_removed_step"], cover_final=cov, on_cover_final=on_cover, + recovered_in_attempt=bool(mon["rested"]) and success, + cube_offsets_cm={n: (100 * self.cube_rel(n, _color(n))).round(1).tolist() for n in CUBES}, + detail=" ".join(parts)) + return out + + # ------------------------------------------------------------ scripted policies (perfect perception) + def _grasp_yaw(self, name): + R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3) + i = int(np.argmin(np.abs(R[2]))) # the most horizontal body axis (works whichever face the cube rests on) + yaw = float(np.arctan2(R[1, i], R[0, i])) + return float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4) + + def _finger_axis(self, yaw): + """world xy direction along which the fingers close at gripper yaw `yaw` (Skills: yaw 0 = fingers along y)""" + return np.array([-np.sin(yaw), np.cos(yaw)]) + + def _clear_yaw(self, name, room=0.04): + """grasp yaw of the cube: the smallest wrist turn (within +-45 deg) unless one of the open fingertips (4.5 cm + either side) would come down within `room` of another cube's centre (cubes put side by side or pushed off on + the lid stand 1.5-2.5 cm apart); then the 90-deg turned grasp if it has more room""" + p = envs.obj_pos(self.env, name)[:2] + others = [envs.obj_pos(self.env, n)[:2] for n in CUBES if n != name] + + def dmin(yaw): + a = self._finger_axis(yaw) + return min([np.linalg.norm(t - o) for t in (p + a * 0.045, p - a * 0.045) for o in others] or [1.0]) + + y0 = self._grasp_yaw(name) + if dmin(y0) >= room: + return y0 + y1 = float((y0 + np.pi / 2 + np.pi / 2) % np.pi - np.pi / 2) + return y1 if dmin(y1) > dmin(y0) else y0 + + def pick(self, name, z_carry=Z_CARRY): + sk = self.sk + p = envs.obj_pos(self.env, name) + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], Z + max(z_carry, p[2] - Z + 0.06)], yaw=self._clear_yaw(name)) + sk.move_to([p[0], p[1], p[2]], tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + sk.move_to([p[0], p[1], Z + z_carry], speed=0.3) + if not self.held(name): + sk.set_gripper(False, steps=8) + return False + return True + + def place_in(self, name, slot, drop=DROP, z_carry=Z_CARRY, noise=None): + """carry the held cube over its box (slot -1 / +1: 2.8 cm right / left of the centre) and release it with its + bottom `drop` above the rim""" + sk = self.sk + b = np.asarray(self.inst["boxes"][_color(name)], float) + d = b + [0.0, SLOT * slot] + (np.asarray(noise, float) if noise is not None else 0.0) + z_rel = Z + RIM + drop + CUBE_E / 2 + sk.move_to([d[0], d[1], Z + z_carry], yaw=0.0) + sk.move_to([d[0], d[1], z_rel], tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + sk.move_to([d[0], d[1], Z + z_carry]) + + def pick_place(self, name, slot, drop=DROP, noise=None): + if self.pick(name): + self.place_in(name, slot, drop=drop, noise=noise) + return True + return False + + def remove_cover(self, direction=None, depth=PUSH_DEPTH, mode="edge"): + """push the lid off its box: closed gripper, fingertips `depth` below the lid's top face, start 3 cm outside + its near edge (mode "edge") or 3 cm inside it, pressing on the lid (mode "press": press and drag -- v2: does not + move the lid any more, see the module docstring), sweep + straight on until the lid has cleared the box (default: sideways, away from the other box), lift""" + cov = self.covering() + if cov is None: + return False + sk = self.sk + lp = self.lid_pos() + b = np.asarray(self.inst["boxes"][cov], float) + if direction is None: + o = np.asarray(self.inst["boxes"][[c for c in COLORS if c != cov][0]], float) + direction = (0.0, float(np.sign(b[1] - o[1]))) + d = np.asarray(direction, float) / np.linalg.norm(direction) + back = LID_HALF + 0.03 if mode == "edge" else LID_HALF - 0.03 + s = lp[:2] - d * back + top = lp[2] + LID_T / 2 + z = top - depth + TIP + sk.set_gripper(True, steps=8) + sk.move_to([s[0], s[1], z + 0.08], yaw=float(np.arctan2(d[1], d[0]) - np.pi / 2)) + sk.move_to([s[0], s[1], z], tol=0.003, max_steps=80) + # sweep until the lid's near edge is 3 cm beyond the box's far wall + need = float((b - lp[:2]) @ d) + BOX_OUT + back + 0.03 + e = s + d * need + sk.move_to([e[0], e[1], z], speed=PUSH_SPEED, tol=0.006, max_steps=int(need / PUSH_SPEED / 0.05) + 80) + sk.move_to([e[0], e[1], z + 0.10], speed=0.2) + sk.set_gripper(False, steps=8) + sk.hold(10) + return self.covering() is None + + def slots(self, order): + """slot of each cube: the first cube of a colour goes right of the centre, the second left""" + seen, out = {c: 0 for c in COLORS}, {} + for n in order: + out[n] = (-1, 1)[seen[_color(n)] % 2] + seen[_color(n)] += 1 + return out + + def wrist_fix(self, rounds=1): + """what a top-down check can see: cubes whose centre is not over the right box's outline (on the table, in + the other box, still held) get placed again; heights are not judged""" + for _ in range(rounds): + bad = [] + for n in CUBES: + rel = self.cube_rel(n, _color(n)) + if self.held(n) or np.max(np.abs(rel)) > BOX_OUT: + bad.append(n) + if not bad: + return + for n in bad: + if self.held(n): + self.sk.set_gripper(False, steps=12) + continue + self.pick_place(n, -1 if self.cube_rel(n, _color(n))[1] < 0 else 1) + + def set_aside(self, name): + """pick the cube (e.g. off the lid) and put it down on the table where it started (that spot is free)""" + if not self.pick(name): + return False + sk = self.sk + x, y = self.inst["start"][name] + sk.move_to([x, y, Z + Z_CARRY], yaw=0.0) + sk.move_to([x, y, Z + CUBE_E / 2 + 0.004], tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + sk.move_to([x, y, Z + Z_CARRY]) + return True + + def side_fix(self, rounds=2): + """the careful check (agentview / heights): every cube must be inside its box, below the rim; if cubes rest on + a lid (or a lid lies on a box): take the cubes off the lid (v2: the heavy lid cannot be pushed off with cubes + standing on it -- the hand runs into them), push the lid off; then place every cube that is not in its box""" + for _ in range(rounds): + v = self.stage_values() + if all(v.values()): + return True + if not v["cover_off_boxes"]: + for n in CUBES: + if self.on_cover(n) or (self.covering() is not None and self._touching(self.cube_gids[n], self.lid_gids)): + self.set_aside(n) + self.remove_cover() + for n in CUBES: + if not self.in_box(n, _color(n)): + if self.held(n): + self.sk.set_gripper(False, steps=12) + continue + others = [m for m in CUBES if m != n and _color(m) == _color(n)] + rel_o = self.cube_rel(others[0], _color(n)) if others else np.zeros(2) + self.pick_place(n, 1 if rel_o[1] < 0 else -1) + return all(self.stage_values().values()) + + def execute(self, inst, params): + order = params.get("order") or list(CUBES) + noise = params.get("noise") or {} + drops = params.get("drops") or {} + if params["plan"] == "lid_first": + self.remove_cover(params.get("push_dir"), params.get("push_depth", PUSH_DEPTH), params.get("push_mode", "edge")) + sl = self.slots(order) + for n in order: + self.pick_place(n, sl[n], drop=drops.get(n, DROP), noise=noise.get(n)) + if params.get("check") == "side": + self.side_fix() + elif params.get("check") == "wrist": + self.wrist_fix() + self.sk.hold(10) + + def default_params(self, inst): + return dict(plan="naive", check="wrist") + + def oracle_params(self, inst): + return dict(plan="lid_first", check="side") + + def adapt_params(self, inst, history): + """from attempt 2 on: look for a lid and push it off first, then place, then check from the side""" + return dict(plan="lid_first", check="side") + + def blind_params(self, inst, attempt, rng): + """the natural plan again with small random variations (order, 5 mm placement noise, 3-5 cm drop), no history""" + order = [CUBES[i] for i in rng.permutation(len(CUBES))] + return dict(plan="naive", check="wrist", order=order, + noise={n: rng.uniform(-0.005, 0.005, 2).tolist() for n in CUBES}, + drops={n: float(rng.uniform(0.03, 0.05)) for n in CUBES}) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = dict(plan="naive", check="side") if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": # extra control (not in validate's table): cross-attempt learning only, no side check + params = self.default_params(inst) if a == 0 else dict(plan="lid_first", check="wrist") + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/lh_drawer_cabinet.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/lh_drawer_cabinet.py new file mode 100644 index 0000000000000000000000000000000000000000..55c3e05f0c97631b61329c3dee47a318c1f3b5f1 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/lh_drawer_cabinet.py @@ -0,0 +1,1273 @@ +"""LH drawer_cabinet (2026-10-16): tidy the table -- stand two tall bottles on top of a small wooden cabinet, put two +cubes into its open drawer and close the drawer. In 14 of every 20 instances the drawer is a self-closing one: pushed +into the last 8 cm, a strong spring snaps it shut, the light cabinet lurches 2.3-4.2 cm towards the robot, and bottles +already standing on its top fall over (away from the robot, onto the gallery rail at the back of the top). + +Family: long-horizon self-disturbance ("state_restoration"): a later, normal action (closing the drawer) physically +undoes an earlier stage (bottles on the cabinet). The instruction lists the bottles first but fixes no order. The agent +has to see the fallen bottles and stand them up again after the drawer is shut (within an attempt), or learn to put +the cubes in and shut the drawer before it puts the bottles on top (across attempts). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a small wooden cabinet (free body, 18 (x) x 22 (y) x 11 cm, centre 53-56 cm in front of the robot base, front facing + the robot) with a 6 cm gallery rail along the back edge of its top, a 4 cm toe plinth under the drawer and a + back-heavy carcass; its single drawer (inside 15.9 x 16.2 cm, 3 cm walls, 1.8 cm overlay front panel with a painted + finger slot, no handle, 0.8 kg) is pulled out 11 cm towards the robot. The agentview camera looks at the cabinet's + back: the drawer is hidden there (wrist camera only), the top and the bottles are in plain view; + * two tall square bottles (green with a yellow ball cap, brown with a blue ball cap; 4 x 4 cm body, 19.4 cm tall, + 0.18 kg, centre of mass 9 cm up, a rounded glass base whose flat contact is 2.2 x 2.2 cm: they tip beyond ~7 deg) + standing on the table 21-24 cm to one side of the cabinet's centre line; + * two 3.2 cm cubes (red, blue, 23 g) 25-29 cm to the other side (picked from nearer, the forearm sweeps over the + cabinet top and knocks bottles standing there: measured feasibility map, task card). + +Hidden variable (same appearance): the drawer's closing mechanism. "self-closing" (14 of every 20 consecutive seeds): +in the last 8 cm of travel a spring pulls the drawer in with 12.5-15 N (no damper); "soft-close" (6 of 20): the same +spring with a damper, the drawer glides in at 4-6 cm/s. Nuisance variables (no effect on the class): carcass mass +0.35-0.45 kg, felt feet (friction on the table 0.15-0.22). + +Mechanism (physics, no teleport; measured, see the task card): the spring is internal to the cabinet, so when it snaps +the drawer in, it also pulls the light carcass (with the bottles on its top) towards the drawer, i.e. towards the robot: +2.3-4.2 cm within ~0.07 s (drawer hitting its stop at 1.9-2.4 m/s relative to the carcass; validate's naive runs), +then the carcass stops dead. A standing bottle's tilt follows a fast displacement of its support as ~ m h dx / I_edge +(~7 rad per metre here), so the bottles tip away from the robot and come to rest leaning on the rail (45-75 deg). The +robot's hand is at the drawer front, below and 10+ cm away from the bottles, and does not touch them (0 of all slams). +Pushing slower does not help (the spring does the closing; 2-10 cm/s and push heights 3-8 cm all toppled, 32/32); +placing the bottles elsewhere on the top does not help (46/46 over six placements). A soft-close drawer moves the +carcass < 3 mm (0/38 bottles fell). Only an uncontrolled full-speed push (~0.6 m/s, not an agent habit) differs: the +hand then shoves the cabinet itself (self-closing 5/8 fell, soft-close 4/4 fell, onto the arm). Placing the bottles after the drawer is shut is safe. Prototype findings that fixed +the numbers: with a light drawer, a heavier carcass or more friction the bottles only rocked (<= 11 deg): the snap's +jerk and the friction stop cancel; a 2 kg carcass held by friction during the snap instead jerked away from the robot +and tipped the bottles towards (onto) the arm. Without the rail, fallen bottles lay with their caps right behind the +cabinet, where the palm (3 cm behind the grasp point) cannot get at them; with the heavy drawer pulled out and no +plinth, ~3 N pressing on the drawer front tipped the cabinet forward. + +Restoring: the cap is a ball with low torsional friction; grasped from above with the fingers across the lying +bottle's axis, the cap turns between the fingers, the lifted bottle swings down and hangs straight, and it can be set +down on the cabinet top (lh_bystander's mechanism; the instruction says that a bottle held by its cap hangs straight). +The neck has torsional friction: a bottle pinched at the neck just under the cap is carried without swinging. + +Success (final state, follows from the instruction): both bottles upright (<= 10 deg) with their whole base on the +cabinet top (inside the rail), not held; both cubes inside the drawer; the drawer closed (<= 5 mm); the cabinet +upright and not moved more than 8 cm (the snap itself moves it 2.3-4.2 cm); the gripper open, holding nothing and +touching no task object; scene static. Per-step monitor (server log only; F1 tells the agent success / failure): stage +achieved / lost / restored (with cause: drawer_slam / robot_hand / robot_arm / bottle / picked_up / other), +drawer_slam (impact speed, carcass jerk, bottles on top, which of them fell, whether the robot had touched them before +they started to fall), bottle_fell, trap_fired (a bottle on top was lost to a slam), recovered_in_attempt. + +Protocol: cross (reset to the same instance before every attempt), k = 3. Once shut, the drawer cannot be opened again +(no handle; the self-closing spring would drag the light carcass along anyway). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +Z = envs.TABLE_Z + +# ---------------------------------------------------------------- cabinet (body frame: front face at -x, origin at the +# centre of the footprint, z = 0 on the table) +CAB = "cabinet_1" +CAB_MODEL = "lff_lhd_cabinet" +CD, CW, CH = 0.18, 0.22, 0.11 # carcass depth (x), width (y), height +CT = 0.010 # board thickness +PF = 0.018 # drawer front panel thickness (overlay: it sits in front of the carcass when closed) +DL = 0.165 # drawer box length (x), measured from the inner face of the front panel +DWT = 0.006 # drawer wall thickness +DWH = 0.030 # drawer wall height above its floor +D_FLOOR = CT + 0.003 # drawer floor bottom above the table +FLOOR_TOP = D_FLOOR + DWT +D_IN_Y = CW / 2 - CT - 0.003 - DWT # drawer inner half width (0.081) +D_IN_X = DL - DWT # inner length (from the front panel to the back wall) +Q_MAX = 0.14 # slide range (opening distance) +Q_OPEN = 0.11 # the drawer starts pulled out this far (exposed inside: 11 x 16.2 cm) +WOOD = (0.66, 0.50, 0.33, 1.0) +WOOD_D = (0.55, 0.40, 0.25, 1.0) +PANEL = (0.76, 0.60, 0.40, 1.0) +INNER = (0.84, 0.72, 0.52, 1.0) +SLOT = (0.18, 0.13, 0.09, 1.0) +DRAWER_MASS = 0.80 +PLINTH = 0.04 # the bottom board reaches this far in front of the carcass, under the drawer: with the heavy drawer +# pulled out, the cabinet would otherwise tip forward under a ~3 N push down on the drawer's front +CAB_COM_X = 0.04 # carcass centre of mass towards the back (back-heavy carcass): same reason +RAIL_H, RAIL_T = 0.060, 0.008 # gallery rail along the back edge of the top: a bottle that tips over backwards comes +# to rest leaning on it (~50 deg) instead of falling off behind the cabinet, where its +# cap would lie against the cabinet's back and the palm could not get at it +SLIDE_FRIC = 1.0 # N, slide frictionloss: the open drawer stays where it is +CARCASS_MASS = (0.35, 0.45) +FEET_MU = (0.15, 0.22) + +# drawer closing mechanism (hidden): spring in the last ZONE of travel, optional damper (soft-close) +ZONE = 0.08 +F_SPRING = (12.5, 15.0) +SOFT_V = (0.04, 0.06) # soft-close glide speed (damping = force / speed) +P_SLAM = 0.70 # 14 of every 20 consecutive seeds self-closing +CLOSED = 0.005 # drawer counts as closed +V_SLAM = 0.30 # m/s: an impact on the stop faster than this is a slam (soft-close: ~0.05) + +# ---------------------------------------------------------------- bottles (square body, shoulder, neck, ball cap) +BOTTLES = ("green_bottle_1", "brown_bottle_1") +B_NAME = {"green_bottle_1": "green", "brown_bottle_1": "brown"} +B_RGBA = {"green_bottle_1": (0.16, 0.48, 0.26, 1.0), "brown_bottle_1": (0.50, 0.26, 0.10, 1.0)} +CAP_RGBA = {"green_bottle_1": (0.92, 0.80, 0.15, 1.0), "brown_bottle_1": (0.15, 0.32, 0.85, 1.0)} +RB, HB = 0.020, 0.115 # body half width, height (incl. the foot) +RF, HF = 0.011, 0.005 # rounded glass base: flat contact 2.2 x 2.2 cm +RS, HS = 0.015, 0.010 # shoulder +RN, HN = 0.009, 0.050 # neck: long enough to be pinched below the cap with the palm clear of the cap +RK = 0.012 # ball cap +CAP_SINK = 0.005 +H_TOT = HB + HS + HN + 2 * RK - CAP_SINK # 0.194 +CAP_Z = H_TOT - RK # cap centre above the bottle's bottom when standing +B_MASS = 0.18 +B_COM = 0.090 # above the bottom +B_MU = 0.8 +CAP_MU_T = 0.0005 # torsional friction of the cap (condim 4): the grasped cap turns freely +NECK_MU_T = 0.01 # torsional friction of the neck (condim 4): a bottle pinched by its neck does not swing +NECK_GRASP = H_TOT - 0.027 # scripted grasp height above the bottom: the palm (3.1 cm above the grasp point between +# the fingers, measured) clears the cap top by 4 mm; the pads hold the neck top and the cap + +# ---------------------------------------------------------------- cubes +CUBES = ("red_cube_1", "blue_cube_1") +CUBE_COLOR = {"red_cube_1": "red", "blue_cube_1": "blue"} +CUBE_RGBA = dict(red=(0.85, 0.10, 0.08, 1.0), yellow=(0.92, 0.76, 0.10, 1.0), blue=(0.15, 0.30, 0.85, 1.0)) +CUBE_E = 0.032 +CUBE_DENS = 700.0 # 23 g + +# ---------------------------------------------------------------- predicates / monitor +UPRIGHT = np.radians(10.0) +TILT_START = np.radians(6.0) # a standing bottle beyond this has started to fall (it tips at ~6.8 deg) +FALLEN = np.radians(40.0) # lying, or leaning on the gallery rail (45-75 deg) +CAB_MOVE_MAX = 0.08 +CAB_TILT_MAX = np.radians(10.0) +DEBOUNCE = 10 # control steps (0.5 s) a predicate change must persist (checked every other step) +WIN_ROBOT = 40 # control steps: a robot contact this recent can explain a loss +WIN_SLAM = 60 + +# ---------------------------------------------------------------- scripted motion +NAIVE_ERR = 0.008 # Sonnet's placement error 0.4-1.3 cm +FINGER_AHEAD = 0.021 # closed fingertips reach this far ahead of the grasp point (yaw 0, +x) -- measured +REACH_MAX = 0.78 # scripted policies: farthest grasp point at table height (horizontal distance from the base) + + +def _box(name, pos, size, rgba, extra, vis=True, vis_rgba=None): + s = [f''] + if vis: + s.append(f'') + return s + + +def cabinet_xml(name): + """free carcass (bottom, top, two sides, back) + a drawer on a slide joint along -x (opening towards the robot). + Carcass geoms contype 2 / conaffinity 1, drawer geoms contype 4 / conaffinity 1: they never collide with each other + but both collide with the robot, the table and the free objects (contype / conaffinity 1). The slide joint comes + first in the object's joint list (robosuite appends the free joint), see DrawerCabinet.__init__.""" + hx, hy = CD / 2, CW / 2 + cg = 'friction="0.8 0.005 0.0001" contype="2" conaffinity="1" solimp="0.95 0.99 0.001" solref="0.004 1"' + carc = [] + carc += _box(f"{name}_bottom", (-PLINTH / 2, 0, CT / 2), (hx + PLINTH / 2, hy, CT / 2), WOOD_D, cg) + carc += _box(f"{name}_top", (0, 0, CH - CT / 2), (hx, hy, CT / 2), WOOD, cg) + carc += _box(f"{name}_side_l", (0, hy - CT / 2, CH / 2), (hx, CT / 2, CH / 2 - CT), WOOD, cg) + carc += _box(f"{name}_side_r", (0, -hy + CT / 2, CH / 2), (hx, CT / 2, CH / 2 - CT), WOOD, cg) + carc += _box(f"{name}_back", (hx - CT / 2, 0, CH / 2), (CT / 2, hy - CT, CH / 2 - CT), WOOD, cg) + carc += _box(f"{name}_rail", (hx - RAIL_T / 2, 0, CH + RAIL_H / 2), (RAIL_T / 2, hy, RAIL_H / 2), WOOD_D, cg) + dg = 'friction="0.8 0.005 0.0001" contype="4" conaffinity="1" solimp="0.95 0.99 0.001" solref="0.004 1"' + x0 = -hx # inner face of the front panel (closed) + zf = D_FLOOR + dr = [] + dr += _box(f"{name}_front", (x0 - PF / 2, 0, (CT + 0.002 + CH - 0.004) / 2), (PF / 2, hy, (CH - 0.006 - CT) / 2), + PANEL, dg) + dr += _box(f"{name}_dfloor", (x0 + DL / 2, 0, zf + DWT / 2), (DL / 2, D_IN_Y + DWT, DWT / 2), INNER, dg) + zw = zf + DWT + DWH / 2 + dr += _box(f"{name}_dside_l", (x0 + DL / 2, D_IN_Y + DWT / 2, zw), (DL / 2, DWT / 2, DWH / 2), INNER, dg) + dr += _box(f"{name}_dside_r", (x0 + DL / 2, -D_IN_Y - DWT / 2, zw), (DL / 2, DWT / 2, DWH / 2), INNER, dg) + dr += _box(f"{name}_dback", (x0 + DL - DWT / 2, 0, zw), (DWT / 2, D_IN_Y, DWH / 2), INNER, dg) + # flush finger pull (visual only): a dark slot near the top of the front panel + dr.append(f'') + m = DRAWER_MASS + ixx, iyy, izz = m * (CW ** 2 + 0.06 ** 2) / 12, m * (DL ** 2 + 0.06 ** 2) / 12, m * (DL ** 2 + CW ** 2) / 12 + drawer = (f'\n' + f' \n' + f' \n' + "\n".join(" " + s for s in dr) + "\n") + m0 = 0.4 + inertial = (f'') + body = "\n ".join([inertial] + carc + drawer.split("\n")) + return f""" + + + + {body} + + + + + + +""" + + +def bottle_xml(name, rgba, cap_rgba): + """square bottle: rounded base (narrow flat foot), body, shoulder, neck, ball cap; origin at mid height""" + h = H_TOT / 2 + zf, zb, zs, zn = -h + HF / 2, -h + HF + (HB - HF) / 2, -h + HB + HS / 2, -h + HB + HS + HN / 2 + zk = -h + HB + HS + HN + RK - CAP_SINK + m = B_MASS + ixx = m * ((2 * RB) ** 2 + H_TOT ** 2) / 14 + izz = m * (2 * (2 * RB) ** 2) / 12 + fr = f'friction="{B_MU} 0.005 0.0001"' + sol = 'solimp="0.95 0.99 0.001" solref="0.005 1"' + parts = [("foot", "box", (0, 0, zf), (RF, RF, HF / 2), rgba, fr + ' priority="2"'), + ("body", "box", (0, 0, zb), (RB, RB, (HB - HF) / 2), rgba, fr), + ("shoulder", "box", (0, 0, zs), (RS, RS, HS / 2), rgba, fr), + ("neck", "cylinder", (0, 0, zn), (RN, HN / 2), rgba, + f'friction="{B_MU} {NECK_MU_T} 0.0001" condim="4" priority="2"'), + ("cap", "sphere", (0, 0, zk), (RK,), cap_rgba, f'friction="1 {CAP_MU_T} 0.0001" condim="4" priority="2"')] + s = [f' '] + for nm, typ, pos, size, c, extra in parts: + s.append(f' ') + if nm != "foot": + s.append(f' ') + # rounded base (visual): a slightly narrower bottom band, and a label + s.append(f' ') + s.append(f' ') + return _wrap(name, "\n".join(s), h, RB * 1.42) + + +def _fb(v): + return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}" + + +def _lr(v): + return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}" + + +def _reach(p): + return float(np.hypot(p[0] + 0.66, p[1])) + + +class DrawerSkills(Skills): + """Skills that feed the task's per-step monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class DrawerCabinet(LFFTask): + name = "lh_drawer_cabinet" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Restore", "Plan") + protocol = "cross" + max_attempts = 3 + # careful: 2 bottles x ~8 commands + 3 cubes x ~6 + closing the drawer ~5 + looking ~15; standing 2 fallen bottles + # up again ~20; + slack + agent_max_steps = 120 + instruction = ("Tidy up the table: stand the green bottle and the brown bottle upright on top of the small wooden " + "cabinet, put the red cube and the blue cube into the cabinet's open drawer (it is pulled " + "out towards the robot), and close the drawer. When you finish, both bottles must stand upright on the cabinet top, both cubes must be in " + "the closed drawer, the cabinet must still stand where it is, and the gripper must be open and not " + "touching anything. (Each bottle has a round cap; held by its cap, a bottle hangs straight down.)") + instruction_indirect = ("Clean up: set the two tall bottles (the green one and the brown one) upright on the little " + "wooden cabinet, drop the two small cubes (red and blue) into its pulled-out drawer and " + "shut the drawer. In the end both bottles stand on top of the cabinet, the cubes are inside the shut drawer, " + "the cabinet stays in its place, and the open gripper touches nothing. (A bottle held by " + "its round cap hangs straight down.)") + agent_object_names = ["green bottle (yellow round cap)", "brown bottle (blue round cap)", "red cube", "blue cube", + "small wooden cabinet with its drawer pulled out (the drawer front faces the robot)"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + cab = register_generated("LffLhdCabinet", cabinet_xml(CAB_MODEL)) + objs = [(CAB, cab, "cabinet_region", (0.10, -0.02, 0.12, 0.0))] + for i, b in enumerate(BOTTLES): + c = B_NAME[b] + cat = register_generated(f"LffLhdBottle{c.title()}", bottle_xml(f"lff_lhd_bottle_{c}", B_RGBA[b], CAP_RGBA[b])) + objs.append((b, cat, f"{c}_bottle_region", (-0.30, 0.20 + 0.13 * i, -0.28, 0.22 + 0.13 * i))) + for i, n in enumerate(CUBES): + c = CUBE_COLOR[n] + cat = register_generated(f"LffLhdCube{c.title()}", + box_xml(f"lff_lhd_cube_{c}", (CUBE_E / 2,) * 3, CUBE_RGBA[c], density=CUBE_DENS, + friction=(0.8, 0.005, 0.0001))) + objs.append((n, cat, f"{c}_cube_region", (-0.30, -0.45 + 0.13 * i, -0.28, -0.43 + 0.13 * i))) + return write_bddl(self.name, "tidy up the table", objs, []) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + pre = f"{CAB}_{CAB_MODEL}" + self.jid = m.joint_name2id(pre + "_slide") + self.qa = int(m.jnt_qposadr[self.jid]) + self.dof = int(m.jnt_dofadr[self.jid]) + self.cab_bid = envs.body_id(self.env, CAB) + self.drawer_bid = m.body_name2id(f"{CAB}_drawer") + # the cabinet's free joint is the LAST of its joints (robosuite appends it after the drawer slide), so + # envs.free_joint_addr / place_upright (joints[0]) must not be used for it + fj = m.joint_name2id(self.env.objects_dict[CAB].joints[-1]) + assert int(m.jnt_type[fj]) == 0 + self.cab_qa, self.cab_da = int(m.jnt_qposadr[fj]), int(m.jnt_dofadr[fj]) + self.feet_gid = m.geom_name2id(pre + "_bottom") + self.cab_gids = {g for g in range(m.ngeom) if m.geom_bodyid[g] in (self.cab_bid, self.drawer_bid) + and m.geom_contype[g] != 0} + self.bottle_gids = {b: set(envs.obj_geom_ids(self.env, b)) for b in BOTTLES} + self.cube_gids = {c: set(envs.obj_geom_ids(self.env, c)) for c in CUBES} + self.cap_gid = {b: m.geom_name2id(f"{b}_lff_lhd_bottle_{B_NAME[b]}_cap") for b in BOTTLES} + # per-geom lookup tables for the substep contact scan + self.part = np.zeros(m.ngeom, int) # 1 = hand / fingers, 2 = arm links + for g in envs.robot_geom_ids(self.env): + n = m.geom_id2name(g) or "" + self.part[g] = 1 if n.startswith("gripper0_") else 2 + self.bidx = np.full(m.ngeom, -1, int) + for i, b in enumerate(BOTTLES): + self.bidx[list(self.bottle_gids[b])] = i + self.task_obj = np.zeros(m.ngeom, bool) + for s in list(self.bottle_gids.values()) + list(self.cube_gids.values()) + [self.cab_gids]: + self.task_obj[list(s)] = True + self.catch = dict(force=0.0, zone=ZONE, damp=0.0) + sim = self.env.sim + if not getattr(sim, "_lhd_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lhd_task", None) + if t is not None: + t._substep() + sim.step = step + sim._lhd_wrapped = True + sim._lhd_task = self + self.inst = None + self.mon = None + self.sk = None + self._sub = {} + + # ------------------------------------------------------------ drawer mechanism (every MuJoCo substep) + def q(self): + return float(self.env.sim.data.qpos[self.qa]) + + def catch_force(self, q, qd): + """generalised force on the slide (positive = opening): inside the last ZONE of travel a constant pull towards + closed (ramped in over 5 mm), plus a damper on closing motion for soft-close drawers""" + c = self.catch + z = c["zone"] + if q >= z or c["force"] <= 0: + return 0.0 + ramp = float(np.clip((z - q) / 0.005, 0.0, 1.0)) + f = -c["force"] * ramp + if qd < 0 and c["damp"] > 0: + f -= c["damp"] * qd * ramp + return f + + def _substep(self): + d = self.env.sim.data + q, qd = float(d.qpos[self.qa]), float(d.qvel[self.dof]) + d.qfrc_applied[self.dof] = self.catch_force(q, qd) + if self.mon is None: + return + sub = self._sub + # slam detection: the closing speed just before the drawer reaches its stop + if q > 0.002: + sub["approach_v"] = -qd + sub["armed"] = True + if q < self.catch["zone"] and sub.get("zone_xy") is None: + sub["zone_xy"] = self.cab_xy().tolist() + elif q > self.catch["zone"] + 0.005: + sub["zone_xy"] = None + elif sub.get("armed"): + sub["armed"] = False + v = float(sub.get("approach_v", 0.0)) + sub.setdefault("impacts", []).append((v, sub.get("zone_xy"))) + sub["zone_xy"] = None + n = d.ncon + if not n: + return + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + for a, b in zip(g1, g2): + ia, ib = self.bidx[a], self.bidx[b] + if ia < 0 and ib < 0: + continue + if ia >= 0 and ib >= 0: + if ia != ib: + sub.setdefault("bb", set()).update((int(ia), int(ib))) + continue + i, o = (ia, b) if ia >= 0 else (ib, a) + p = int(self.part[o]) + if p: + r = sub.setdefault("rob", {}) + r[int(i)] = 2 if (p == 2 or r.get(int(i)) == 2) else 1 + + # ------------------------------------------------------------ instances + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + slam = bool((int(seed) * 7) % 20 < round(20 * P_SLAM)) # balanced: 14 of every 20 consecutive seeds + cx, cy = float(rng.uniform(-0.13, -0.10)), float(rng.uniform(-0.04, 0.04)) + s = 1.0 if rng.random() < 0.5 else -1.0 # bottles on the left (+1) or right (-1), cubes on the other side + bottles = {} + order = rng.permutation(2) + for j, i in enumerate(order): + bx = cx + (-0.05, 0.05)[j] + float(rng.uniform(-0.01, 0.01)) + bottles[BOTTLES[i]] = [bx, cy + s * float(rng.uniform(0.21, 0.24))] + perm = rng.permutation(2) + # cubes 25-29 cm to the side of the cabinet's centre line: picked from nearer, the forearm sweeps over the + # cabinet top and knocks the bottles standing there (measured feasibility map, see the task card) + cubes = {CUBES[i]: [cx + (-0.16, -0.04)[j] + float(rng.uniform(-0.01, 0.01)), + cy - s * float(rng.uniform(0.25, 0.29))] for j, i in enumerate(perm)} + force = float(rng.uniform(*F_SPRING)) + soft_v = float(rng.uniform(*SOFT_V)) + return dict(seed=int(seed), self_closing=slam, drawer="self-closing" if slam else "soft-close", + cab_xy=[cx, cy], bottle_side="left" if s > 0 else "right", bottle_start=bottles, + bottle_yaw={b: float(rng.uniform(-0.3, 0.3)) for b in BOTTLES}, cube_start=cubes, + cube_yaw={c: float(rng.uniform(-0.3, 0.3)) for c in CUBES}, + spring_n=force, damp=0.0 if slam else force / soft_v, + carcass_kg=float(rng.uniform(*CARCASS_MASS)), feet_mu=float(rng.uniform(*FEET_MU)), + naive_noise_seed=int(rng.integers(1 << 30))) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + M = float(inst["carcass_kg"]) + m.body_mass[self.cab_bid] = M + m.body_inertia[self.cab_bid] = [M * (CW ** 2 + CH ** 2) / 12, M * (CD ** 2 + CH ** 2) / 12, + M * (CD ** 2 + CW ** 2) / 12] + m.geom_friction[self.feet_gid] = [float(inst["feet_mu"]), 0.005, 0.0001] + m.geom_priority[self.feet_gid] = 3 + self.catch = dict(force=float(inst["spring_n"]), zone=ZONE, damp=float(inst["damp"])) + self.set_drawer(Q_OPEN) + self.place_cabinet(inst["cab_xy"], 0.0) + for b in BOTTLES: + envs.place_upright(self.env, b, inst["bottle_start"][b], yaw=inst["bottle_yaw"][b], clearance=0.0005) + for c in CUBES: + envs.place_upright(self.env, c, inst["cube_start"][c], yaw=inst["cube_yaw"][c], clearance=0.001) + + def set_drawer(self, q): + d = self.env.sim.data + d.qpos[self.qa] = q + d.qvel[self.dof] = 0.0 + + def place_cabinet(self, xy, yaw=0.0, clearance=0.0005): + d = self.env.sim.data + a, v = self.cab_qa, self.cab_da + d.qpos[a:a + 3] = [xy[0], xy[1], Z + clearance] # body origin = bottom of the carcass + d.qpos[a + 3:a + 7] = [np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)] + d.qvel[v:v + 6] = 0.0 + self.env.sim.forward() + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = DrawerSkills(self.env, self, recorder=recorder) + self._sub = {} + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ geometry helpers (world frame) + def cab_R(self): + return self.env.sim.data.body_xmat[self.cab_bid].reshape(3, 3).copy() + + def cab_origin(self): + return self.env.sim.data.body_xpos[self.cab_bid].copy() + + def cab_xy(self): + return self.cab_origin()[:2] + + def to_cab(self, p): + """world point -> cabinet frame (x forward, origin at the footprint centre on the floor)""" + return self.cab_R().T @ (np.asarray(p, float) - self.cab_origin()) + + def from_cab(self, p): + return self.cab_origin() + self.cab_R() @ np.asarray(p, float) + + def top_z(self): + return float(self.from_cab([0.0, 0.0, CH])[2]) + + def cab_front_x(self): + """world x of the carcass's front face (cabinet assumed close to yaw 0)""" + return float(self.from_cab([-CD / 2, 0.0, 0.0])[0]) + + def drawer_front_x(self): + """world x of the drawer front panel's outer face""" + return self.cab_front_x() - self.q() - PF + + def cab_tilt(self): + return float(np.arccos(np.clip(self.cab_R()[2, 2], -1.0, 1.0))) + + def cab_moved(self): + return float(np.linalg.norm(self.cab_xy() - np.asarray(self.inst["cab_xy"]))) + + def R(self, name): + return self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3).copy() + + def tilt(self, name): + return float(np.arccos(np.clip(self.R(name)[2, 2], -1.0, 1.0))) + + def bottle_base(self, b): + """world position of the centre of the bottle's bottom face""" + return envs.obj_pos(self.env, b) - self.R(b)[:, 2] * H_TOT / 2 + + def cap_xyz(self, b): + return self.env.sim.data.geom_xpos[self.cap_gid[b]].copy() + + def held(self, name): + return self.sk is not None and self.sk.holding(name) + + # ------------------------------------------------------------ stage predicates + def bottle_on_top(self, b, tol=0.0, tilt=UPRIGHT): + if self.tilt(b) > tilt or self.held(b): + return False + c = self.to_cab(self.bottle_base(b)) + if c[0] < -CD / 2 + RF - tol or c[0] > CD / 2 - RAIL_T - RF + tol or abs(c[1]) > CW / 2 - RF + tol: + return False + return bool(-0.006 <= c[2] - CH <= 0.012) + + def cube_in_drawer(self, c): + """cube centre inside the drawer box (drawer frame), its footprint within the walls (+3 mm), resting low enough + to pass under the cabinet top; not held""" + if self.held(c): + return False + d = self.env.sim.data + Rd = d.body_xmat[self.drawer_bid].reshape(3, 3) + p = Rd.T @ (envs.obj_pos(self.env, c) - d.body_xpos[self.drawer_bid]) + x0 = -CD / 2 + e = CUBE_E / 2 * 1.2 # footprint half size (a yawed cube reaches a little farther) + tol = 0.003 + return bool(x0 + e - tol <= p[0] <= x0 + D_IN_X - e + tol and abs(p[1]) <= D_IN_Y - e + tol + and FLOOR_TOP - 0.005 <= p[2] - CUBE_E / 2 <= FLOOR_TOP + DWH + 0.01) + + def drawer_closed(self): + return self.q() <= CLOSED + + def stage_keys(self): + return [f"{B_NAME[b]}_bottle_on_top" for b in BOTTLES] + [f"{CUBE_COLOR[c]}_cube_in_drawer" for c in CUBES] + [ + "drawer_closed"] + + def stage_values(self, hyst=None): + hyst = hyst or {} + v = {} + for b in BOTTLES: + k = f"{B_NAME[b]}_bottle_on_top" + v[k] = self.bottle_on_top(b, 0.003, UPRIGHT + np.radians(3.0)) if hyst.get(k) else self.bottle_on_top(b) + for c in CUBES: + v[f"{CUBE_COLOR[c]}_cube_in_drawer"] = self.cube_in_drawer(c) + v["drawer_closed"] = self.q() <= (CLOSED + 0.003 if hyst.get("drawer_closed") else CLOSED) + return v + + # ------------------------------------------------------------ per-step monitor + def _init_monitor(self): + keys = self.stage_keys() + st = {k: False for k in keys} + self.mon = dict(state=st, ever=[], lost=[], lost_cause={}, events=[], cand={k: 0 for k in keys}, step=0, + last_robot=[None, None], last_bb=None, slams=[], standing_since=[None, None], + fall_start=[None, None], touched_before_fall=[False, False], max_tilt=[0.0, 0.0], + n_fallen=0, fallen=[False, False]) + + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + mon["step"] += 1 + t = int(self.sk.n_steps) + sub, self._sub = self._sub, {k: v for k, v in self._sub.items() if k in ("approach_v", "armed", "zone_xy")} + for i, part in sub.get("rob", {}).items(): + b = BOTTLES[i] + if not self.held(b): + mon["last_robot"][i] = ["hand" if part == 1 else "arm", t, round(float(np.degrees(self.tilt(b))), 1)] + if sub.get("bb"): + mon["last_bb"] = t + for v, zxy in sub.get("impacts", []): + if v >= V_SLAM: + lurch = None + if zxy is not None: + dxy = self.cab_xy() - np.asarray(zxy) + lurch = [round(100 * float(dxy[0]), 2), round(100 * float(dxy[1]), 2)] + on = [B_NAME[b] for b in BOTTLES if mon["state"][f"{B_NAME[b]}_bottle_on_top"]] + e = dict(event="drawer_slam", step=t, speed_mps=round(float(v), 2), cabinet_jerk_cm=lurch, + bottles_on_top=on, bottles_fell=[], robot_touched_before_fall=[]) + mon["events"].append(e) + mon["slams"].append(e) + else: + mon["events"].append(dict(event="drawer_shut", step=t, speed_mps=round(float(v), 3))) + # fall tracking (R4: did the robot touch a bottle before it started to fall?) + for i, b in enumerate(BOTTLES): + tl = self.tilt(b) + mon["max_tilt"][i] = max(mon["max_tilt"][i], float(np.degrees(tl))) + if self.held(b): + mon["standing_since"][i] = None + continue + if tl < np.radians(3.0): + if mon["standing_since"][i] is None: + mon["standing_since"][i] = t + mon["fall_start"][i] = None + elif tl > TILT_START and mon["standing_since"][i] is not None and mon["fall_start"][i] is None: + mon["fall_start"][i] = t + lr = mon["last_robot"][i] + mon["touched_before_fall"][i] = bool(lr is not None and t - lr[1] <= 20 and lr[2] < np.degrees(TILT_START)) + if not mon["fallen"][i] and tl > FALLEN: + mon["fallen"][i] = True + mon["n_fallen"] += 1 + mon["events"].append(dict(event="bottle_fell", bottle=B_NAME[b], step=t, cause=self._cause(i, t), + robot_touched_before_fall=bool(mon["touched_before_fall"][i]), + direction=self._fall_dir(b))) + elif mon["fallen"][i] and tl < UPRIGHT: + mon["fallen"][i] = False + if mon["step"] % 2: + return + vals = self.stage_values(hyst=mon["state"]) + for k, now in vals.items(): + self._check(k, now, t) + + def _fall_dir(self, b): + ax = self.R(b)[:2, 2] + if np.linalg.norm(ax) < 0.2: + return "none" + return ("forward" if ax[0] > 0 else "backward") if abs(ax[0]) >= abs(ax[1]) else ("left" if ax[1] > 0 else "right") + + def _cause(self, i, t): + """why bottle i left the cabinet top""" + b = BOTTLES[i] + mon = self.mon + if self.held(b): + return "picked_up" + lr = mon["last_robot"][i] + robot_recent = lr is not None and t - lr[1] <= WIN_ROBOT + if robot_recent and mon["touched_before_fall"][i]: + return f"robot_{lr[0]}" + if robot_recent and lr[2] < np.degrees(TILT_START): + return f"robot_{lr[0]}" + if mon["slams"] and t - mon["slams"][-1]["step"] <= WIN_SLAM: + return "drawer_slam" + if mon["last_bb"] is not None and t - mon["last_bb"] <= WIN_ROBOT: + return "bottle" + if robot_recent: + return f"robot_{lr[0]}" + return "other" + + def _check(self, key, now, t): + mon = self.mon + if now == mon["state"][key]: + mon["cand"][key] = 0 + return + mon["cand"][key] += 2 + if mon["cand"][key] < DEBOUNCE: + return + mon["cand"][key] = 0 + mon["state"][key] = now + t0 = int(t - DEBOUNCE + 1) + if now: + restored = key in mon["lost"] + e = dict(stage=key, event="restored" if restored else "achieved", step=t0) + if restored: + e["after"] = mon["lost_cause"].get(key) + mon["lost"].remove(key) + if key not in mon["ever"]: + mon["ever"].append(key) + mon["events"].append(e) + return + if key not in mon["ever"]: + return + if key.endswith("bottle_on_top"): + i = [f"{B_NAME[b]}_bottle_on_top" for b in BOTTLES].index(key) + cause = self._cause(i, t) + if cause == "drawer_slam": + s = mon["slams"][-1] + if B_NAME[BOTTLES[i]] not in s["bottles_fell"]: + s["bottles_fell"].append(B_NAME[BOTTLES[i]]) + s["robot_touched_before_fall"].append(bool(mon["touched_before_fall"][i])) + elif key == "drawer_closed": + cause = "opened" + else: + c = CUBES[[f"{CUBE_COLOR[x]}_cube_in_drawer" for x in CUBES].index(key)] + cause = "picked_up" if self.held(c) else "other" + if key not in mon["lost"]: + mon["lost"].append(key) + mon["lost_cause"][key] = cause + mon["events"].append(dict(stage=key, event="lost", step=t0, cause=cause)) + + def _finalize_monitor(self, vals): + """close the event log at finish: a stage the debounced monitor still holds but the final judge does not (or + vice versa) is logged now (final=True)""" + mon = self.mon + t = int(self.sk.n_steps) + for k, now in vals.items(): + if now == mon["state"][k]: + continue + n0 = len(mon["events"]) + mon["cand"][k] = DEBOUNCE # force the transition + self._check(k, now, t + DEBOUNCE - 1) + if len(mon["events"]) > n0: + mon["events"][-1]["final"] = True + + # ------------------------------------------------------------ outcome + def _static(self): + d = self.env.sim.data + for n in BOTTLES + CUBES: + _, da = envs.free_joint_addr(self.env, n) + if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5: + return False + v = self.cab_da + return bool(np.linalg.norm(d.qvel[v:v + 3]) < 0.02 and abs(float(d.qvel[self.dof])) < 0.02) + + def robot_touching(self): + d = self.env.sim.data + out = set() + for j in range(d.ncon): + c = d.contact[j] + for a, b in ((c.geom1, c.geom2), (c.geom2, c.geom1)): + if self.part[a] and self.task_obj[b]: + out.add("a bottle" if self.bidx[b] >= 0 else "the cabinet" if b in self.cab_gids else "a cube") + return sorted(out) + + def outcome(self, inst): + sk = self.sk + sk.hold(10) + touching = set() + for _ in range(20): + sk.hold(1) + touching.update(self.robot_touching()) + touching = sorted(touching) + static = self._static() + vals = self.stage_values() + held = [n for n in BOTTLES + CUBES if self.held(n)] + cab_ok = bool(self.cab_tilt() <= CAB_TILT_MAX and self.cab_moved() <= CAB_MOVE_MAX) + grip_open = bool(sk.grip < 0) + self._finalize_monitor(vals) + mon = self.mon + ev = list(mon["events"]) + success = bool(all(vals.values()) and cab_ok and static and not held and not touching and grip_open) + lost = [e for e in ev if e.get("event") == "lost"] + regress = [e for e in lost if e.get("cause") != "picked_up"] + restored = [e for e in ev if e.get("event") == "restored" and e.get("after") != "picked_up"] + slams = [e for e in ev if e.get("event") == "drawer_slam"] + slam_losses = [e for e in lost if e.get("cause") == "drawer_slam"] + trap = bool(slam_losses) + bkeys = [f"{B_NAME[b]}_bottle_on_top" for b in BOTTLES] + never_bottle = [B_NAME[b] for b, k in zip(BOTTLES, bkeys) if not vals[k] and k not in mon["ever"]] + lost_bottle = [B_NAME[b] for b, k in zip(BOTTLES, bkeys) if not vals[k] and k in mon["ever"]] + cubes_out = [CUBE_COLOR[c] for c in CUBES if not vals[f"{CUBE_COLOR[c]}_cube_in_drawer"]] + if success: + failure = "none" + elif held: + failure = "held" + elif not cab_ok: + failure = "cabinet_moved" + elif lost_bottle: + failure = "bottle_knocked" + elif never_bottle: + failure = "bottle_not_on_top" + elif cubes_out: + failure = "cube_not_in_drawer" + elif not vals["drawer_closed"]: + failure = "drawer_open" + elif touching: + failure = "touching" + elif not grip_open: + failure = "gripper_closed" + else: + failure = "not_static" + detail = self._detail(vals, held, touching, cab_ok, static, grip_open, success, ev) + return dict(success=success, failure=failure, stages=vals, events=ev, n_regressions=len(regress), + n_lost=len(lost), n_restored=len(restored), trap_fired=trap, + recovered_in_attempt=bool(trap and success), n_slams=len(slams), + slam_speeds=[e["speed_mps"] for e in slams], slam_jerk_cm=[e["cabinet_jerk_cm"] for e in slams], + bottles_lost_to_slam=sorted({e["stage"].split("_")[0] for e in slam_losses}), + robot_touched_before_fall=[bool(x) for x in mon["touched_before_fall"]], + bottle_max_tilt_deg=[round(x, 1) for x in mon["max_tilt"]], n_fallen=mon["n_fallen"], + held=held, touching=touching, static=bool(static), gripper_open=grip_open, + drawer_q_cm=round(100 * self.q(), 2), cabinet_moved_cm=round(100 * self.cab_moved(), 2), + cabinet_tilt_deg=round(float(np.degrees(self.cab_tilt())), 1), + bottle_tilts_deg={B_NAME[b]: round(float(np.degrees(self.tilt(b))), 1) for b in BOTTLES}, + self_closing=bool(inst["self_closing"]), detail=detail) + + def _detail(self, vals, held, touching, cab_ok, static, grip_open, success, ev): + parts = [] + if success: + parts.append("Both bottles stand on the cabinet, the two cubes are in the closed drawer.") + top_c = self.from_cab([0.0, 0.0, CH]) + for b in BOTTLES: + k = f"{B_NAME[b]}_bottle_on_top" + if vals[k]: + continue + nm = B_NAME[b] + if b in held: + parts.append(f"The {nm} bottle is still held by the gripper.") + continue + tl = float(np.degrees(self.tilt(b))) + base = self.bottle_base(b) + rel = base - top_c + on_top = abs(float(rel[2])) < 0.03 + ax = self.R(b)[:, 2] + where = f"its base is {_fb(rel[0])} and {_lr(rel[1])} of the centre of the cabinet top" + if tl <= np.degrees(UPRIGHT): + txt = (f"The {nm} bottle stands but not on the cabinet top: {where}." if not on_top else + f"The {nm} bottle stands with part of its base over the edge of the cabinet top: {where}.") + elif on_top and ax[0] > 0.3 and self.to_cab(self.cap_xyz(b))[0] > CD / 2 - RAIL_T: + txt = (f"The {nm} bottle has tipped over forward on the cabinet top and leans {tl:.0f} degrees against " + f"the rail along the top's far edge; {where}.") + elif on_top: + txt = f"The {nm} bottle has tipped over on the cabinet top ({tl:.0f} degrees); {where}." + elif base[2] < Z + 0.03: + txt = f"The {nm} bottle has fallen over and lies on the table; {where}." + else: + txt = f"The {nm} bottle has fallen over and leans {tl:.0f} degrees against something; {where}." + lost = [e for e in ev if e.get("stage") == k and e.get("event") == "lost"] + if lost: + why = lost[-1].get("cause", "other") + txt += {"drawer_slam": " It had stood on the cabinet top; it fell when the drawer snapped shut and the " + "cabinet jerked.", + "robot_hand": " It had stood on the cabinet top; the gripper knocked it.", + "robot_arm": " It had stood on the cabinet top; the robot's arm knocked it.", + "bottle": " It had stood on the cabinet top; the other bottle knocked it."}.get( + why, " It had stood on the cabinet top earlier.") + parts.append(txt) + for c in CUBES: + if vals[f"{CUBE_COLOR[c]}_cube_in_drawer"]: + continue + nm = CUBE_COLOR[c] + if c in held: + parts.append(f"The {nm} cube is still held by the gripper.") + continue + p = envs.obj_pos(self.env, c) + rel = self.to_cab(p) + if abs(rel[0]) < CD / 2 and abs(rel[1]) < CW / 2 and rel[2] > CH - 0.01: + parts.append(f"The {nm} cube lies on the cabinet top, not in the drawer.") + else: + parts.append(f"The {nm} cube is not in the drawer: it is {_fb(rel[0] + CD / 2)} and {_lr(rel[1])} of the " + f"middle of the cabinet's front.") + if not vals["drawer_closed"]: + parts.append(f"The drawer is still {100 * self.q():.1f} cm open.") + if not cab_ok: + if self.cab_tilt() > CAB_TILT_MAX: + parts.append("The cabinet has been knocked over.") + else: + parts.append(f"The cabinet was moved {100 * self.cab_moved():.0f} cm from where it stood.") + if not success and all(vals.values()) and cab_ok: + if touching: + parts.append("The gripper is still touching " + " and ".join(touching) + ".") + elif not grip_open: + parts.append("The gripper is closed.") + elif not static: + parts.append("Something was still moving.") + slams = [e for e in ev if e.get("event") == "drawer_slam" and e.get("bottles_fell")] + if slams and success: + parts.append("(The drawer snapped shut and knocked bottles off the cabinet; they were stood up again.)") + return " ".join(parts) + + # ------------------------------------------------------------ scripted primitives (move_to + gripper only) + def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300): + return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + + def _lift_to(self, z, speed=0.15): + cur = self.sk.eef_pos() + if cur[2] < z - 0.005: + self._go([cur[0], cur[1], z], speed=speed) + + def _settle(self, name, max_checks=25): + d = self.env.sim.data + _, da = envs.free_joint_addr(self.env, name) + for _ in range(max_checks): + if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2: + return + self.sk.hold(2) + + def _box_yaw(self, name): + R = self.R(name) + i = int(np.argmin(np.abs(R[2]))) + yaw = float(np.arctan2(R[1, i], R[0, i])) + y = float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4) + cands = [y + k * np.pi / 2 for k in (-1, 0, 1)] + return min(cands, key=lambda c: abs(c - self.sk.yaw) if abs(c) <= np.pi / 2 else 9.0) + + def pick_bottle(self, b, grasp="neck", z_clear=0.05, yaw=None, v=0.15): + """Sonnet-like pick of a standing bottle from above: over it, straight down, close, lift until its bottom + clears the cabinet top by z_clear. grasp: neck (1 cm below its top; the body cannot be reached from above, the + palm would land on the cap) | cap (the bottle then hangs from a pivot)""" + sk = self.sk + self._settle(b) + p = envs.obj_pos(self.env, b) + bot = self.bottle_base(b)[2] + zg = {"neck": bot + NECK_GRASP, "cap": bot + CAP_Z}[grasp] + yaw = self._box_yaw(b) if yaw is None else yaw + sk.set_gripper(False, steps=8) + top = bot + H_TOT + self.transit(p[:2], top + 0.06, yaw=yaw, v=v) + self._go([p[0], p[1], zg + 0.015], speed=0.1) + self._go([p[0], p[1], zg], speed=0.04, tol=0.003, max_steps=150) + sk.set_gripper(True, steps=15) + lift = self.top_z() + z_clear + (zg - bot) + self._go([p[0], p[1], lift], speed=0.10) + sk.hold(5) + if not self.held(b): + sk.set_gripper(False, steps=8) + return False + return True + + def put_bottle(self, b, xy, gap=0.01, z_clear=0.05, v=0.12, settle=15): + """carry the held bottle over xy (its axis, not the grasp point), straight down until its bottom is `gap` above + the cabinet top, let go, lift""" + sk = self.sk + rel = envs.obj_pos(self.env, b)[:2] - sk.eef_pos()[:2] + q = np.asarray(xy, float) - rel + zc = self.top_z() + z_clear + (sk.eef_pos()[2] - self.bottle_base(b)[2]) + self.transit(q, zc, v=v, carried=b, margin=z_clear) + sk.hold(settle) + rel = envs.obj_pos(self.env, b)[:2] - sk.eef_pos()[:2] + q = np.asarray(xy, float) - rel + dz = sk.eef_pos()[2] - envs.obj_min_z(self.env, b) + zr = self.top_z() + dz + gap + self._go([q[0], q[1], zr + 0.02], speed=0.08) + self._go([q[0], q[1], zr], speed=0.03, tol=0.003, max_steps=150) + sk.hold(5) + sk.set_gripper(False, steps=12) + cur = sk.eef_pos() + self._go([cur[0], cur[1], self.top_z() + H_TOT + 0.06], speed=0.08) + self._settle(b) + + def obstacle_top(self, p0, p1, ignore=(), r=0.09): + """highest top (world z) of standing bottles within r of the straight path p0 -> p1 (xy), and of the cabinet + top if the path passes over it (expanded by 4 cm)""" + a, b = np.asarray(p0, float)[:2], np.asarray(p1, float)[:2] + ab = b - a + L2 = max(float(ab @ ab), 1e-9) + + def dist(q): + u = float(np.clip((q - a) @ ab / L2, 0.0, 1.0)) + return float(np.linalg.norm(a + u * ab - q)) + top = Z + for o in BOTTLES: + if o in ignore or self.held(o): + continue + if dist(envs.obj_pos(self.env, o)[:2]) < r: + top = max(top, envs.obj_max_z(self.env, o)) + for u in np.linspace(0.0, 1.0, 21): + c = self.to_cab(np.r_[a + u * ab, Z]) + if abs(c[0]) < CD / 2 + 0.04 + PF + max(self.q(), 0.0) and abs(c[1]) < CW / 2 + 0.04: + top = max(top, self.top_z() + RAIL_H) + break + return top + + def transit(self, xy, z_min, yaw=None, v=0.15, carried=None, margin=0.06): + """Sonnet-like transit: up (to clear what is in the way), straight across, the caller then goes down""" + sk = self.sk + cur = sk.eef_pos() + obst = self.obstacle_top(cur, xy, ignore=(carried,) if carried else ()) + below = (sk.eef_pos()[2] - envs.obj_min_z(self.env, carried)) if carried else 0.03 + zt = max(cur[2], z_min, obst + margin + below) + if cur[2] < zt - 0.005: + self._go([cur[0], cur[1], zt], speed=v) + self._go([xy[0], xy[1], zt], yaw=yaw, speed=v) + + def pick_cube(self, c, z_carry=0.15, v=0.15): + sk = self.sk + for _ in range(2): + self._settle(c) + p = envs.obj_pos(self.env, c) + yaw = self._box_yaw(c) + sk.set_gripper(False, steps=8) + self.transit(p[:2], Z + z_carry, yaw=yaw, v=v) + self._go([p[0], p[1], p[2] + 0.015], speed=0.1) + self._go([p[0], p[1], p[2]], speed=0.04, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + self._go([p[0], p[1], max(Z + z_carry, sk.eef_pos()[2])], speed=v) + if self.held(c): + return True + sk.set_gripper(False, steps=8) + return False + + def drawer_slot(self, k, noise=None): + """world xy of cube slot k (0..1) in the exposed part of the open drawer: a column along the drawer's middle + (with the wrist at yaw 0 the open fingers, 13.2 cm across, stay clear of the side walls and of the cube + already in; the palm, 3.9 cm ahead of the grasp point, stays clear of the carcass; the far slot first)""" + q = min(self.q(), Q_OPEN) + x = self.cab_front_x() - 0.045 - k * (q - 0.070) + y = self.cab_xy()[1] + out = np.array([x, y]) + return out + (np.asarray(noise, float) if noise is not None else 0.0) + + def put_cube(self, c, xy, gap=0.02, z_carry=0.15, v=0.15): + sk = self.sk + self.transit(xy, Z + z_carry, yaw=0.0, v=v, carried=c, margin=0.04) + zr = Z + FLOOR_TOP + CUBE_E / 2 + gap + self._go([xy[0], xy[1], zr + 0.015], speed=0.1) + self._go([xy[0], xy[1], zr], speed=0.04, tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + self._go([xy[0], xy[1], Z + z_carry], speed=v) + self._settle(c) + + def close_drawer(self, v=0.04, z_push=0.05, overshoot=0.0, y_off=0.0, approach=0.03): + """closed gripper in front of the drawer, then a straight push forward to where the front panel is flush""" + sk = self.sk + y = self.cab_xy()[1] + y_off + xs = self.drawer_front_x() - FINGER_AHEAD - approach + x_end = self.cab_front_x() - PF - FINGER_AHEAD + overshoot + sk.set_gripper(True, steps=10) + cur = sk.eef_pos() + self._go([cur[0], cur[1], max(cur[2], Z + 0.15)], speed=0.15) + self._go([xs, y, Z + 0.15], yaw=0.0, speed=0.15) + self._go([xs, y, Z + z_push], speed=0.1, tol=0.003) + self._go([x_end, y, Z + z_push], speed=v, tol=0.003, max_steps=int(0.25 / max(v, 0.01) / 0.05) + 60) + self.sk.hold(10) + cur = sk.eef_pos() + self._go([cur[0] - 0.06, cur[1], cur[2]], speed=0.08) + self._go([cur[0] - 0.06, cur[1], Z + 0.20], speed=0.15) + sk.hold(10) + + def top_spots(self, mode="pair", noise=None): + """world xy targets on the cabinet top for the two bottles (left one first): side by side across the middle""" + c = self.from_cab([0.0, 0.0, CH])[:2] + spots = [c + np.array([0.0, 0.05]), c + np.array([0.0, -0.05])] + if noise is not None: + spots = [s + np.asarray(n, float) for s, n in zip(spots, noise)] + return spots + + def free_top_spot(self, b, start=None): + """a spot on the cabinet top (cabinet frame candidates) at least 6.5 cm from the other bottle if that one stands + on the top, and -- if `start` (xy the bottle comes from) is given -- whose straight path from `start` passes + farthest from it""" + other = [o for o in BOTTLES if o != b][0] + cands = [np.array([dx, dy]) for dx in (0.0, -0.03, 0.03) for dy in (0.055, -0.055, 0.0)] + ok_other = self.bottle_on_top(other, 0.01, np.radians(20)) + oc = self.to_cab(self.bottle_base(other))[:2] + if not ok_other: + return self.from_cab([cands[0][0], cands[0][1], CH])[:2] if start is None else min( + (self.from_cab([c[0], c[1], CH])[:2] for c in cands[:2]), + key=lambda w: float(np.linalg.norm(w - np.asarray(start)[:2]))) + best, score = None, -1.0 + st = None if start is None else self.to_cab(np.r_[np.asarray(start)[:2], Z])[:2] + for c in cands: + if np.linalg.norm(c - oc) < 0.065: + continue + if st is None: + return self.from_cab([c[0], c[1], CH])[:2] + ab = c - st + u = float(np.clip((oc - st) @ ab / max(float(ab @ ab), 1e-9), 0.0, 1.0)) + clear = float(np.linalg.norm(st + u * ab - oc)) + if clear > score: + best, score = c, clear + if best is None: + best = max(cands, key=lambda c: float(np.linalg.norm(c - oc))) + return self.from_cab([best[0], best[1], CH])[:2] + + def restand_bottle(self, b, xy=None): + """stand a fallen bottle up again on the cabinet top: grasp the ball cap from above (fingers across the lying + bottle's axis), lift until it hangs free with its bottom above the gallery rail, carry it over a free spot, + lower until the bottom is ~3 mm above the top, let go. Returns True if it stands on the top.""" + sk = self.sk + self._settle(b) + for _ in range(2): + if _reach(self.cap_xyz(b)) > REACH_MAX and self.tilt(b) > FALLEN: + self.pull_in_bottle(b) + k = self.cap_xyz(b) + ax = self.R(b)[:2, 2] + yaw = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else sk.yaw # finger axis across it + sk.set_gripper(False, steps=8) + self.transit(k[:2], k[2] + 0.08, yaw=yaw, v=0.15) + sk.hold(5) + k = self.cap_xyz(b) + self._go([k[0], k[1], k[2] + 0.015], speed=0.1) + self._go([k[0], k[1], k[2]], speed=0.04, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + if not self.held(b): + sk.set_gripper(False, steps=8) + self._go([k[0], k[1], k[2] + 0.08], speed=0.1) + continue + zl = self.top_z() + RAIL_H + 0.03 + CAP_Z + self._go([k[0], k[1], zl], speed=0.10) + sk.hold(15) + tx, ty = self.free_top_spot(b, start=k[:2]) if xy is None else xy + self._go([tx, ty, zl], speed=0.10) + sk.hold(30) + self._go([tx, ty, self.top_z() + CAP_Z + 0.015], speed=0.08) + self._go([tx, ty, self.top_z() + CAP_Z + 0.003], speed=0.03, tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + self._go([tx, ty, self.top_z() + H_TOT + 0.04], speed=0.08) + sk.hold(20) + self._settle(b) + if self.bottle_on_top(b): + return True + return self.bottle_on_top(b) + + def pull_in_bottle(self, b): + """the lying bottle's cap is out of reach: grasp the body near its bottom end (fingers across it), lift it + 3 cm, pull it towards the robot until the cap is within reach, set it down""" + sk = self.sk + Rb = self.R(b) + ax = Rb[:, 2] + g = envs.obj_pos(self.env, b) - ax * (H_TOT / 2 - 0.04) + zg = max(float(g[2] - Z), 0.02) + yaw = float(np.arctan2(ax[1], ax[0])) + need = _reach(self.cap_xyz(b)) - (REACH_MAX - 0.05) + to_base = np.array([-0.66, 0.0]) - g[:2] + to_base /= max(np.linalg.norm(to_base), 1e-6) + dst = g[:2] + to_base * need + sk.set_gripper(False, steps=8) + self._go([g[0], g[1], Z + 0.15], yaw=yaw, speed=0.15) + self._go([g[0], g[1], Z + zg + 0.015], speed=0.1) + self._go([g[0], g[1], Z + zg], speed=0.04, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + self._go([g[0], g[1], Z + zg + 0.03], speed=0.08) + self._go([dst[0], dst[1], Z + zg + 0.03], speed=0.08) + self._go([dst[0], dst[1], Z + zg + 0.005], speed=0.04) + sk.set_gripper(False, steps=12) + self._go([dst[0], dst[1], Z + 0.15], speed=0.1) + self._settle(b) + + # ------------------------------------------------------------ scripted policies + def check_and_fix(self, params, rounds=2): + """look at every stage at the end: stand fallen bottles up on the top, put stray cubes into the drawer if it is + still open""" + for _ in range(rounds): + v = self.stage_values() + if all(v.values()): + break + for b in BOTTLES: + if not self.bottle_on_top(b): + if self.tilt(b) > UPRIGHT or self.bottle_base(b)[2] < self.top_z() - 0.03: + if self.tilt(b) > UPRIGHT: + self.restand_bottle(b) + elif self.pick_bottle(b, grasp="neck"): + self.put_bottle(b, self.free_top_spot(b), gap=0.005) + if not self.drawer_closed(): + for k, c in enumerate(CUBES): + if not self.cube_in_drawer(c) and self.pick_cube(c): + self.put_cube(c, self.drawer_slot(k)) + if all(self.cube_in_drawer(c) for c in CUBES): + self.close_drawer(v=params.get("push_v", 0.04), z_push=params.get("push_z", 0.05)) + self._lift_to(self.top_z() + 0.15) + self.sk.set_gripper(False, steps=8) + self.sk.hold(10) + + def do_bottles(self, params, rng): + noise = params.get("noise") + spots = self.top_spots(noise=noise) + side = 1.0 if self.inst["bottle_side"] == "left" else -1.0 + spots = sorted(spots, key=lambda q: side * float(q[1])) # the spot farther from the bottles' side first + order = list(BOTTLES) if params.get("bottle_order", "listed") == "listed" else list(BOTTLES)[::-1] + for b, xy in zip(order, spots): + for _ in range(2): + if self.pick_bottle(b, grasp=params.get("grasp", "neck"), z_clear=params.get("z_clear", 0.05)): + self.put_bottle(b, xy, gap=params.get("gap", 0.02), z_clear=params.get("z_clear", 0.05)) + break + + def do_cubes(self, params, rng): + noise = params.get("cube_noise") or [None] * 3 + for k, c in enumerate(self._cube_order()): + if self.pick_cube(c): + self.put_cube(c, self.drawer_slot(k, noise[k]), gap=params.get("cube_gap", 0.02)) + + def _cube_order(self): + """nearest the drawer first""" + d = np.array([self.cab_front_x() - Q_OPEN / 2, self.cab_xy()[1]]) + return sorted(CUBES, key=lambda c: float(np.linalg.norm(envs.obj_pos(self.env, c)[:2] - d))) + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("noise_seed", 0)) + order = params.get("order", "BCD") # B = bottles on top, C = cubes into the drawer, D = close the drawer + for step in order: + if step == "B": + self.do_bottles(params, rng) + elif step == "C": + self.do_cubes(params, rng) + elif step == "D": + self.close_drawer(v=params.get("push_v", 0.04), z_push=params.get("push_z", 0.05), + overshoot=params.get("overshoot", 0.0)) + if params.get("check"): + self.check_and_fix(params) + else: + self._lift_to(self.top_z() + 0.15) + self.sk.set_gripper(False, steps=8) + self.sk.hold(10) + + def _noise(self, rng, err=NAIVE_ERR): + return dict(noise=[rng.uniform(-err, err, 2).tolist() for _ in BOTTLES], + cube_noise=[rng.uniform(-err, err, 2).tolist() for _ in CUBES]) + + def default_params(self, inst): + """Sonnet-like: the order of the instruction (bottles, cubes, drawer); bottles grasped by the body from above, + lifted until they clear the cabinet top by 5 cm, lowered straight down and let go 1-4 cm above it; cubes into + the drawer; the drawer pushed shut slowly (4 cm/s) with the closed gripper; no final look back""" + rng = np.random.default_rng(inst["naive_noise_seed"]) + p = dict(order="BCD", check=False, grasp="neck", gap=float(rng.uniform(0.01, 0.04)), + push_v=float(rng.uniform(0.03, 0.05)), push_z=float(rng.uniform(0.04, 0.06)), + overshoot=float(rng.uniform(0.0, 0.004)), noise_seed=int(inst["naive_noise_seed"])) + p.update(self._noise(rng)) + return p + + def oracle_params(self, inst): + """knows the drawer: cubes in, drawer shut, then the bottles; checks every stage at the end""" + return dict(order="CDB", check=True, grasp="neck", gap=0.008, push_v=0.04, push_z=0.05, overshoot=0.0) + + def adapt_params(self, inst, history): + """attempt >= 2 (after the bottles fell when the drawer was shut): shut the drawer before the bottles go on + top, and look at every stage at the end""" + return dict(self.default_params(inst), order="CDB", check=True) + + def blind_params(self, inst, attempt, rng): + """the natural behaviour with random variations (order of the three sub-tasks, push speed / height, release + height, placement noise), no history, no final look""" + order = str(rng.choice(["BCD", "CBD", "CDB"], p=[0.5, 0.3, 0.2])) + p = dict(order=order, check=False, grasp=str(rng.choice(["neck", "cap"])), gap=float(rng.uniform(0.01, 0.04)), + push_v=float(rng.uniform(0.02, 0.08)), push_z=float(rng.uniform(0.03, 0.07)), + overshoot=float(rng.uniform(0.0, 0.006)), noise_seed=int(rng.integers(1 << 30))) + p.update(self._noise(rng)) + return p + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """oracle / naive: one attempt; adaptive: attempt 1 = naive + a final look that stands fallen bottles up again, + attempts >= 2 drawer first; blind: naive with random variations. + Extra kinds (not in validate's table): switch (naive, then drawer first without a final look), oracle_noise + (oracle with +-5 mm placement noise), naive_slow (naive pushing at the slowest agent speed, 2 cm/s), + naive_check (naive + final look = adaptive's first attempt)""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + single = ("oracle", "naive", "oracle_noise", "naive_slow", "naive_check", "naive_neck", "naive_cap") + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": + params = self.default_params(inst) if a == 0 else dict(self.default_params(inst), order="CDB") + elif kind == "oracle_noise": + params = dict(self.oracle_params(inst), **self._noise(np.random.default_rng(seed * 7 + a), 0.005)) + elif kind == "naive_slow": + params = dict(self.default_params(inst), push_v=0.02) + elif kind == "naive_check": + params = dict(self.default_params(inst), check=True) + elif kind == "naive_neck": + params = dict(self.default_params(inst), grasp="neck") + elif kind == "naive_cap": + params = dict(self.default_params(inst), grasp="cap") + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in single: + break + return history diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/lh_false_bottom_lid.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/lh_false_bottom_lid.py new file mode 100644 index 0000000000000000000000000000000000000000..c5314a649314f9885d502ac3c6c8fb213a78e227 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/lh_false_bottom_lid.py @@ -0,0 +1,954 @@ +"""LH false_bottom_lid: open a lidded wooden box, put a tall red block and two blue cubes in, close the lid -- in half +of the boxes a hidden false bottom makes the box too shallow for the block standing upright, so the lid comes down on +the block and stays open; the block must be laid on its side. + +Family: long-horizon common sense + self-disturbance ("state_restoration"): the agent's own normal action (placing the +block upright, as it was found) makes the last stage (lid closed) impossible; it has to notice the blocked lid, take +the block out again, lay it down and close the lid (within an attempt), or lay the block down from the start in this +box (across attempts). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a wooden box (fixture): outer 20.6 cm (forward-back) x 13.6 cm (left-right) x 9 cm high, walls 0.8 cm; the + inside is pure black and matte (walls' inner faces, floor and false bottom). The lid (0.6 cm, wood, 0.15 kg) is + hinged along the box's left or right long edge; a black ball knob sticks out of the middle of the opposite edge. + Opened past upright the lid falls over to the hinge side and hangs on its stop (182-192 deg) just below + horizontal beside the box, below every transit; + * a red block 4 x 4 x 7.5 cm standing upright and two 4 cm blue cubes, in a row in front of the box (robot side), + on 3 of 4 slots 16 cm apart. + +Hidden variable: the box's inner depth. With a false bottom (10 of every 20 consecutive seeds) the floor is 4.5 cm +below the rim instead of 8.4 cm. The outside is identical and the inside is dark: from above (wrist camera) and from +the far camera the floor height is not readable (measured: renders of the open, empty box with and without the false +bottom are pixel-identical in both cameras). The Panda hand (21 cm along the finger axis) cannot go below the rim, +so the fingertips cannot touch the false bottom either. Upright the block is 7.5 cm tall: it fits the deep box (top 0.9 cm +below the rim) but stands 3 cm above the rim on the false bottom; lying down (4 cm) it fits both. + +Why the natural action fails: the block is found standing; carried top-down by a gripper that can only turn about the +vertical, it is naturally put in standing. On a false bottom the closing lid then comes down on the block's top and +stays open at ~28-41 deg (measured; clearly visible in both cameras). What must be +learned: take the block out, lay it on its side (tip it over on the table by pushing its upper part with the closed +fingers, then pick it up lying) and put it in lying (within the attempt), or lay it down before putting it in (across +attempts). + +Lid mechanics for agents (inherited from lh_lid_box's `LidSkills`, generalized to a hinge axis along x): while the +knob is held, a commanded straight move is projected onto the knob's circle around the hinge (at most 1 cm per control +step), so "up, then over the hinge, release" opens the lid and "up, then away from the hinge, release" closes it. + +Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (lid closed, all +three items inside the box below the rim, nothing held, scene static) plus an event log for the server log +(per-item in_box achieved / lost / restored, lid opened / closed / blocked, red block laid down / stood up); F1 gives +the agent only success / failure. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task +from .lh_lid_box import SMAX, LidSkills, _fb, _lr + +# ---------------------------------------------------------------- geometry / physics (box frame: hinge along local y +# at the local +x edge; the box is turned by +-90 deg so that the hinge runs forward-back on the left or right side) +BOX = "box_1" +BOX_MODEL = "lff_fbl_box" +S_IN, L_IN = 0.120, 0.190 # inner cavity across the hinge (local x -> world y) and along it (local y -> world x); +# roomy enough that closed fingers (~4 cm out from a held 4 cm item) stay off the walls +WALL_T, WALL_H, FLOOR_T = 0.008, 0.090, 0.006 +FB_DEPTH = 0.045 # inner depth with the false bottom (floor 4.5 cm above the table) +LX, LY = S_IN + 2 * WALL_T, L_IN + 2 * WALL_T +LID_T, LID_MASS = 0.006, 0.15 +KNOB_R, STEM_L = 0.013, 0.032 +HINGE_DAMP, HINGE_FRIC = 0.002, 0.002 +LID_SOLREF, LID_SOLIMP = "0.005 1", "0.99 0.998 0.001" +BACKOFF = 0.003 # m per control step: a hand pressing on a lid that rests on an item yields +STOP = (182.0, 192.0) # lid opening stop (deg, uniform): opened, the lid hangs just below horizontal beside the box +# (free end 6.5-7 cm up), below every transit; at < 180 deg its free end and knob rise to 12-14 cm +# and a carried item sweeps into them (measured) +WOOD = (0.55, 0.38, 0.22, 1.0) +LID_RGBA = (0.70, 0.52, 0.32, 1.0) +DARK = (0.0, 0.0, 0.0, 1.0) # pure black, matte (no specular): every lit shade is 0, so the floor height is invisible +KNOB_RGBA = (0.10, 0.10, 0.11, 1.0) + +RED = "red_block_1" +BLUES = ("blue_cube_1", "blue_cube_2") +ITEMS = (RED,) + BLUES +RED_W, RED_H = 0.040, 0.075 +CUBE_E = 0.040 +RED_DENS, CUBE_DENS = 600.0, 500.0 # 72 g, 32 g +ITEM_MU = 0.8 +P_FB = 0.5 + +IN_TOL = 0.004 # an item's footprint corners may reach this far past the inner walls (an item leaning on a wall +# touches it; measured: a cube dropped into the deep box ended tilted 52 deg against the front wall) +RIM_TOL = 0.004 # item top at most this far above the rim +LID_CLOSED = np.radians(5.0) +DEBOUNCE = 6 # predicate checks (every 0.1 s) +UPRIGHT_COS, LYING_COS = np.cos(np.radians(25.0)), np.cos(np.radians(65.0)) + +Z_CARRY = 0.16 # scripted transit height of the grasp point above the table when carrying an item (Sonnet: 11-20 cm) +Z_HAND_MIN = WALL_H - 0.024 + 0.006 # lowest grasp point over the box: the Panda hand (2.4 cm above the grasp point, 21 cm +# along the finger axis) must stay above the rim +# scripted in-box slots along the box's long axis (u, forward-back, box centre = 0), all at v = 0 (centre line). +# The lying red block lies across the box (axis left-right) and is held with the fingers closing forward-back, so its +# slot is 1 cm further in: fingers 4 cm out from its centre stay 1 cm off the back wall (measured: at the upright +# slot the back finger caught the wall and dropped the block) +SLOT_U = {"red_upright": -0.0575, "red_lying": -0.0475, "blue_cube_1": 0.005, "blue_cube_2": 0.055} +START_Y = (-0.24, -0.08, 0.08, 0.24) +START_X = -0.34 + + +def fb_box_xml(name): + hx, hy = LX / 2, LY / 2 + col = [((0, 0, FLOOR_T / 2), (hx, hy, FLOOR_T / 2)), + ((hx - WALL_T / 2, 0, WALL_H / 2), (WALL_T / 2, hy, WALL_H / 2)), + ((-hx + WALL_T / 2, 0, WALL_H / 2), (WALL_T / 2, hy, WALL_H / 2)), + ((0, hy - WALL_T / 2, WALL_H / 2), (hx - WALL_T, WALL_T / 2, WALL_H / 2)), + ((0, -hy + WALL_T / 2, WALL_H / 2), (hx - WALL_T, WALL_T / 2, WALL_H / 2))] + g = [] + # box: contype 2 / conaffinity 1, lid: contype 4 / conaffinity 1 -> the lid never collides with its own box (the + # hinge limit holds it closed) but both collide with the robot, the table and the free items (as in lh_lid_box) + for k, (pos, s) in enumerate(col): + g.append(f'') + fb_top = WALL_H - FB_DEPTH + fbh = (fb_top - FLOOR_T) / 2 + fb_pos, fb_size = (0, 0, FLOOR_T + fbh), (hx - WALL_T, hy - WALL_T, fbh) + # the false bottom: always compiled, its collision switched on / off per instance (contype / conaffinity), so no + # geom moves at runtime and the compiled bounding volumes stay valid (see lh_fence's refit_bvh note) + g.append(f'') + th = WALL_T / 2 + vis = [((hx - th / 2, 0, WALL_H / 2), (th / 2, hy, WALL_H / 2), WOOD), + ((hx - WALL_T + th / 2, 0, WALL_H / 2), (th / 2, hy - th, WALL_H / 2), DARK), + ((-hx + th / 2, 0, WALL_H / 2), (th / 2, hy, WALL_H / 2), WOOD), + ((-hx + WALL_T - th / 2, 0, WALL_H / 2), (th / 2, hy - th, WALL_H / 2), DARK), + ((0, hy - th / 2, WALL_H / 2), (hx - th, th / 2, WALL_H / 2), WOOD), + ((0, hy - WALL_T + th / 2, WALL_H / 2), (hx - WALL_T, th / 2, WALL_H / 2), DARK), + ((0, -hy + th / 2, WALL_H / 2), (hx - th, th / 2, WALL_H / 2), WOOD), + ((0, -hy + WALL_T - th / 2, WALL_H / 2), (hx - WALL_T, th / 2, WALL_H / 2), DARK), + ((0, 0, FLOOR_T / 2), (hx, hy, FLOOR_T / 2), WOOD), + ((0, 0, FLOOR_T + 0.0005), (hx - WALL_T, hy - WALL_T, 0.0005), DARK)] + for p, s, c in vis: + mat = f' material="{name}_dark"' if c == DARK else "" + g.append(f'') + g.append(f'') + m, L = LID_MASS, LX + lid_c = (-L / 2, 0, LID_T / 2) + lid_s = (L / 2, hy, LID_T / 2) + stem = (-L - STEM_L / 2, 0, LID_T / 2) + ball = (-L - STEM_L - KNOB_R * 0.7, 0, LID_T / 2) + lid = [f'', + f'', + # stiffer contacts for the lid plate, and solmix so that they win against the items' (default, soft) ones: + # with soft contacts an arm pressing the lid down onto the 72 g block pushed the lid through it (measured) + f'', + f'', + f'', + f'', + f'', + f''] + shell = "\n ".join(g) + lid_xml = "\n ".join(lid) + # matte near-black inside (no specular highlight): the floor height is not readable from above + return f""" + + + + + + + {shell} + + {lid_xml} + + + + + + + +""" + + +class FBLidSkills(LidSkills): + """LidSkills with the hinge axis in any horizontal direction (here forward-back), plus the task's per-step + monitor. While the knob is held, the commanded displacement is projected onto the tangent of the knob's circle + about the hinge (<= SMAX per control step), with radial and axial corrections.""" + + def _hinge_frame(self, e): + h, a = self.task.hinge_point(), self.task.hinge_axis() + v = e - h + al = float(v @ a) + r = v - al * a + return a, al, r, max(float(np.linalg.norm(r)), 1e-6) + + def _act(self, dpos, drot, grip): + if self.latched: + e = self.eef_pos() + if self.grip < 0 or np.linalg.norm(e - self.task.knob_xyz()) > 0.035: + self.latched = False # opened, or the knob slipped out of the fingers + else: + a, al, r, rn = self._hinge_frame(e) + t_open = np.cross(self.env.sim.data.xaxis[self.task.jid], r) / rn # knob motion for an opening lid + s = float(np.clip(np.asarray(dpos) @ t_open, -SMAX, SMAX)) + if s < 0 and self.task.lid_contacts(): + s = 0.0 # compliant wrist: it does not force the lid down onto an item (else the lid tunnels through it) + dpos = s * t_open + (self.rad0 - rn) * r / rn + (self.y0 - al) * a + self.knob_steps += 1 + else: + p = self.task.robot_lid_contact() + if p is not None and self.task.lid_contacts(): + # the same limit for a hand pressing on the lid itself: no push towards closing while the lid rests on + # an item (measured without it: pressing 5 cm "into" a lid lying on the block left the block poking + # through the lid) + _, _, r, rn = self._hinge_frame(p) + t_open = np.cross(self.env.sim.data.xaxis[self.task.jid], r) / rn + sc = float(np.asarray(dpos) @ t_open) + if sc < 0: # drop the closing component and yield a little (a force-limited arm gives way) + dpos = np.asarray(dpos) + (BACKOFF - sc) * t_open + Skills._act(self, dpos, drot, grip) + self.task.monitor_step() + + def set_gripper(self, close, steps=15): + rep = Skills.set_gripper(self, close, steps) + if close and self.holding_knob(): + _, al, _, rn = self._hinge_frame(self.eef_pos()) + self.latched, self.rad0, self.y0 = True, rn, al + self.knob_grasps += 1 + elif not close: + self.latched = False + return rep + + +def _rot(yaw): + c, s = np.cos(yaw), np.sin(yaw) + return np.array([[c, -s], [s, c]]) + + +@register_task +class FalseBottomLid(LFFTask): + name = "lh_false_bottom_lid" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Plan", "Restore") + protocol = "cross" + max_attempts = 3 + agent_max_steps = 120 # careful: lid 2 x ~6 + 3 items x ~7 = ~35 commands; laying the block down (tip + pick) ~8; + # fixing a blocked lid in place (reopen, take out, tip, pick, put in, close) ~30; + looking + instruction = ("Put the red block and the two blue cubes into the wooden box and close its lid. The lid opens by " + "lifting the black knob on its edge.") + instruction_indirect = ("Pack the tall red piece and both small blue cubes into the wooden chest and shut it " + "(the lid lifts by the black ball on its edge).") + agent_object_names = ["red block", "blue cube", "blue cube", "wooden box", "lid knob"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + box = register_generated("LffFblBox", fb_box_xml(BOX_MODEL), free=False) + red = register_generated("LffFblRedBlock", box_xml("lff_fbl_red_block", (RED_W / 2, RED_W / 2, RED_H / 2), + (0.85, 0.10, 0.08, 1.0), density=RED_DENS, + friction=(ITEM_MU, 0.005, 0.0001)).replace(_SOLID, "").replace( + 'group="0" />', 'condim="4" group="0" />')) + objs = [(RED, red, "red_region", (-0.35, -0.25, -0.33, -0.23))] + for i, n in enumerate(BLUES): + cat = register_generated(f"LffFblBlueCube{'AB'[i]}", + box_xml(f"lff_fbl_blue_cube_{'ab'[i]}", (CUBE_E / 2,) * 3, (0.15, 0.30, 0.85, 1.0), + density=CUBE_DENS, friction=(ITEM_MU, 0.005, 0.0001)).replace(_SOLID, "").replace( + 'group="0" />', 'condim="4" group="0" />')) + objs.append((n, cat, f"blue_{'ab'[i]}_region", (-0.35, -0.09 + 0.16 * i, -0.33, -0.07 + 0.16 * i))) + fx = [(BOX, box, "box_region", (-0.16, -0.01, -0.14, 0.01))] + return write_bddl(self.name, "put the red block and the blue cubes into the box and close the lid", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + pre = f"{BOX}_{BOX_MODEL}" + self.jid = m.joint_name2id(pre + "_hinge") + self.qa = m.jnt_qposadr[self.jid] + self.dof = m.jnt_dofadr[self.jid] + self.box_bid = m.body_name2id(self.env.fixtures_dict[BOX].root_body) + self.knob_geom_name = pre + "_knob" + self.knob_geom_names = [pre + "_knob", pre + "_stem"] + self.knob_gid = m.geom_name2id(self.knob_geom_name) + self.lid_gids = {m.geom_name2id(pre + s) for s in ("_lid", "_stem", "_knob")} + self.fb_gid = m.geom_name2id(pre + "_fb") + self.fbvis_gid = m.geom_name2id(pre + "_fbvis") + self.robot_gids = set(envs.robot_geom_ids(self.env)) + self.item_gids = {n: set(envs.obj_geom_ids(self.env, n)) for n in ITEMS} + self.inst = None + self.mon = None + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + bx, by = float(rng.uniform(-0.17, -0.14)), float(rng.uniform(-0.02, 0.02)) + hinge = "left" if rng.random() < 0.5 else "right" + stop = float(rng.uniform(*STOP)) + perm = rng.permutation(len(START_Y)) + start = {n: [float(START_X + rng.uniform(-0.01, 0.01)), float(START_Y[perm[j]] + rng.uniform(-0.01, 0.01))] + for j, n in enumerate(ITEMS)} + start_yaw = {n: float(rng.uniform(-0.3, 0.3)) for n in ITEMS} + # balanced blocks like lh_lid_box: exactly 10 of every 20 consecutive seeds have the false bottom + fb = bool((int(seed) * 7) % 20 < round(20 * P_FB)) + return dict(seed=int(seed), box_xy=[bx, by], hinge=hinge, stop_deg=stop, false_bottom=fb, + inner_depth_cm=round(100 * (FB_DEPTH if fb else WALL_H - FLOOR_T), 1), start=start, + start_yaw=start_yaw) + + def box_yaw(self, inst=None): + inst = inst or self.inst + return np.pi / 2 if inst["hinge"] == "left" else -np.pi / 2 # local +x (hinge edge) -> world +y / -y + + def apply_instance(self, inst): + self.inst = inst + m, d = self.env.sim.model, self.env.sim.data + bx, by = inst["box_xy"] + yaw = self.box_yaw(inst) + m.body_pos[self.box_bid] = [bx, by, envs.TABLE_Z] + m.body_quat[self.box_bid] = [np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)] + m.jnt_range[self.jid] = [0.0, np.radians(inst["stop_deg"])] + m.jnt_solref[self.jid] = [0.01, 1.0] + fb = bool(inst["false_bottom"]) + m.geom_contype[self.fb_gid] = 2 if fb else 0 + m.geom_conaffinity[self.fb_gid] = 1 if fb else 0 + m.geom_rgba[self.fbvis_gid, 3] = 1.0 if fb else 0.0 + d.qpos[self.qa] = 0.0 + d.qvel[self.dof] = 0.0 + for n, xy in inst["start"].items(): + envs.place_upright(self.env, n, xy, yaw=inst["start_yaw"][n]) + for n in ITEMS: + envs.set_friction(self.env, n, ITEM_MU) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.mon = None + self.sk = FBLidSkills(self.env, self, recorder=recorder) + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ geometry helpers + def floor_z(self): + """height of the surface items rest on inside the box (world z)""" + return envs.TABLE_Z + ((WALL_H - FB_DEPTH) if self.inst["false_bottom"] else FLOOR_T) + + def rim_z(self): + return envs.TABLE_Z + WALL_H + + def long_axis(self): + """unit vector (world xy) along the box's long side (= the hinge axis), pointing forward""" + return np.array([1.0, 0.0]) + + def to_box(self, xy): + """world xy -> box frame (u along the long side / forward, v across / left)""" + return np.asarray(xy, float)[:2] - np.asarray(self.inst["box_xy"]) + + def from_box(self, uv): + return np.asarray(self.inst["box_xy"]) + np.asarray(uv, float) + + def hinge_sign(self): + return 1.0 if self.inst["hinge"] == "left" else -1.0 + + def hinge_point(self): + bx, by = self.inst["box_xy"] + return np.array([bx, by + self.hinge_sign() * LX / 2, envs.TABLE_Z + WALL_H]) + + def hinge_axis(self): + return np.array([1.0, 0.0, 0.0]) + + def lid_q(self): + return float(self.env.sim.data.qpos[self.qa]) + + def lid_deg(self): + return float(np.degrees(self.lid_q())) + + def knob_xyz(self): + return self.env.sim.data.geom_xpos[self.knob_gid].copy() + + def held(self, name): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name])) + + def item_axis(self, name): + """body z axis in world (the red block's long axis)""" + return self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3)[:, 2].copy() + + def red_pose(self): + c = abs(float(self.item_axis(RED)[2])) + return "upright" if c >= UPRIGHT_COS else "lying" if c <= LYING_COS else "tilted" + + def in_cavity_xy(self, name): + """the item's whole footprint (its collision box corners, also when tilted) inside the inner walls""" + m, d = self.env.sim.model, self.env.sim.data + g = next(iter(self.item_gids[name])) + R = d.geom_xmat[g].reshape(3, 3) + half = m.geom_size[g][:3] + c = self.to_box(d.geom_xpos[g][:2]) + ext = np.abs(R[:2, :]) @ half # world-axis half extents of the footprint + lim = np.array([L_IN / 2, S_IN / 2]) + IN_TOL + return bool(np.all(np.abs(c) + ext <= lim)) + + def in_box(self, name): + return bool(self.in_cavity_xy(name) and envs.obj_max_z(self.env, name) <= self.rim_z() + RIM_TOL + and envs.obj_min_z(self.env, name) >= envs.TABLE_Z + FLOOR_T - 0.005 and not self.held(name)) + + def over_box(self, name): + """centre above the cavity (in it, or standing in it but sticking out)""" + c = self.to_box(envs.obj_pos(self.env, name)[:2]) + return bool(abs(c[0]) <= L_IN / 2 and abs(c[1]) <= S_IN / 2) + + def lid_closed(self): + return self.lid_q() <= LID_CLOSED + + def lid_contacts(self): + """items the lid touches now""" + d = self.env.sim.data + out = set() + for i in range(d.ncon): + c = d.contact[i] + for n in ITEMS: + g = self.item_gids[n] + if (c.geom1 in g and c.geom2 in self.lid_gids) or (c.geom2 in g and c.geom1 in self.lid_gids): + out.add(n) + return out + + def robot_lid_contact(self): + """world position of a robot-lid contact (None if the robot does not touch the lid)""" + d = self.env.sim.data + for i in range(d.ncon): + c = d.contact[i] + if (c.geom1 in self.robot_gids and c.geom2 in self.lid_gids) or (c.geom2 in self.robot_gids + and c.geom1 in self.lid_gids): + return np.array(c.pos, float) + return None + + def robot_touching(self): + """'lid' / item names the robot is in contact with now (finishing while pressing the lid down does not count)""" + d = self.env.sim.data + out = set() + for i in range(d.ncon): + c = d.contact[i] + g1, g2 = c.geom1, c.geom2 + for a, b in ((g1, g2), (g2, g1)): + if a in self.robot_gids: + if b in self.lid_gids: + out.add("lid") + for n in ITEMS: + if b in self.item_gids[n]: + out.add("red block" if n == RED else "blue cube") + return sorted(out) + + def stage_values(self): + v = {f"{n}_in_box": self.in_box(n) for n in ITEMS} + v["lid_closed"] = self.lid_closed() + return v + + # ------------------------------------------------------------ per-step monitor + def _init_monitor(self): + self.mon = dict(state={f"{n}_in_box": False for n in ITEMS}, ever=set(), lost=set(), events=[], + last_touch={n: None for n in ITEMS}, step=0, lid_opened=False, lid_open_max=0.0, + lid_prev=0.0, lid_still=0, blocked_now=False, n_blocked=0, blocked_max_deg=0.0, + red_pose=self.red_pose(), red_pose_cand=None, red_pose_n=0, red_up_in_box=False, + red_relaid=0, closes=0, cand={f"{n}_in_box": 0 for n in ITEMS}) + + def _touches(self): + d = self.env.sim.data + out = {} + for i in range(d.ncon): + c = d.contact[i] + for n in ITEMS: + g = self.item_gids[n] + other = c.geom2 if c.geom1 in g else (c.geom1 if c.geom2 in g else None) + if other is None: + continue + if other in self.lid_gids: + out[n] = "lid" + elif other in self.robot_gids and out.get(n) != "lid": + out[n] = "robot" + return out + + def monitor_step(self): + mon = self.mon + if mon is None: + return + mon["step"] += 1 + step = self.sk.n_steps if self.sk is not None else mon["step"] + for n, who in self._touches().items(): + mon["last_touch"][n] = (who, step) + q = self.lid_deg() + mon["lid_open_max"] = max(mon["lid_open_max"], q) + if not mon["lid_opened"] and q > 90.0: + mon["lid_opened"] = True + mon["blocked_now"] = False + mon["events"].append(dict(step=step, pred="lid", ev="opened_past_vertical")) + elif mon["lid_opened"] and q <= np.degrees(LID_CLOSED): + mon["lid_opened"] = False + mon["closes"] += 1 + mon["events"].append(dict(step=step, pred="lid", ev="closed")) + # lid blocked: it came down from past vertical and rests (not held) on an item at 5-80 deg for 1 s + if abs(q - mon["lid_prev"]) < 0.05: + mon["lid_still"] += 1 + else: + mon["lid_still"] = 0 + mon["lid_prev"] = q + if mon["lid_opened"] and not mon["blocked_now"] and 5.0 < q < 80.0 and mon["lid_still"] >= 20 \ + and not self.sk.latched: + on = sorted(self.lid_contacts()) + if on: + mon["blocked_now"] = True + mon["n_blocked"] += 1 + mon["blocked_max_deg"] = max(mon["blocked_max_deg"], q) + mon["events"].append(dict(step=step, pred="lid", ev="lid_blocked", lid_deg=round(q, 1), on=on, + red_pose=self.red_pose())) + if mon["blocked_now"] and q > 90.0: + mon["blocked_now"] = False + if mon["step"] % 2: + return # predicates every other control step (0.1 s) + # red block pose (debounced 1 s): upright <-> lying + p = self.red_pose() + if p != "tilted" and p != mon["red_pose"]: + if mon["red_pose_cand"] == p: + mon["red_pose_n"] += 1 + else: + mon["red_pose_cand"], mon["red_pose_n"] = p, 1 + if mon["red_pose_n"] >= 10 and not self.held(RED): + where = "box" if self.over_box(RED) else "table" + lt = mon["last_touch"][RED] + cause = lt[0] if lt is not None and step - lt[1] <= 60 else "other" + ev = "item_relaid" if p == "lying" else "stood_up" + if p == "lying": + mon["red_relaid"] += 1 + mon["events"].append(dict(step=step, pred="red_pose", ev=ev, where=where, cause=cause)) + mon["red_pose"] = p + mon["red_pose_cand"] = None + else: + mon["red_pose_cand"] = None + if not mon["red_up_in_box"] and mon["red_pose"] == "upright" and self.over_box(RED) and not self.held(RED) \ + and envs.obj_min_z(self.env, RED) < self.rim_z(): + mon["red_up_in_box"] = True + top = envs.obj_max_z(self.env, RED) - self.rim_z() + mon["events"].append(dict(step=step, pred="red_pose", ev="placed_upright_in_box", + top_above_rim_cm=round(100 * top, 1))) + for n in ITEMS: # debounced: a change counts after it held for DEBOUNCE checks (fingers rubbing a released item) + key = f"{n}_in_box" + now = self.in_box(n) + if now == mon["state"][key]: + mon["cand"][key] = 0 + continue + mon["cand"][key] += 1 + if mon["cand"][key] >= DEBOUNCE: + mon["cand"][key] = 0 + self._event(key, now, step, n) + + def _event(self, key, now, step, name): + mon = self.mon + mon["state"][key] = now + if now: + ev = "restored" if key in mon["lost"] else "achieved" + mon["ever"].add(key) + mon["lost"].discard(key) + e = dict(step=step, pred=key, ev=ev) + if name == RED: + e["red_pose"] = self.red_pose() + mon["events"].append(e) + return + if key not in mon["ever"]: + return # never achieved: nothing lost + cause = "other" + if self.held(name): + cause = "picked_up" + else: + lt = mon["last_touch"][name] + if lt is not None and step - lt[1] <= 60: + cause = lt[0] + mon["lost"].add(key) + mon["events"].append(dict(step=step, pred=key, ev="lost", cause=cause, lid_deg=round(self.lid_deg(), 1))) + + # ------------------------------------------------------------ outcome + def _static(self): + d = self.env.sim.data + for n in ITEMS: + _, da = envs.free_joint_addr(self.env, n) + if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5: + return False + return abs(float(d.qvel[self.dof])) < 0.2 + + def _where(self, name): + """F2-style location of an item relative to the box, robot-centric words""" + rel = self.to_box(envs.obj_pos(self.env, name)[:2]) + return f"{_fb(rel[0])} and {_lr(rel[1])} of the box's centre" + + def outcome(self, inst): + envs.settle(self.env, 30) + mon = self.mon + vals = self.stage_values() + static = self._static() + held = [n for n in ITEMS if self.held(n)] + touching = self.robot_touching() + success = bool(all(vals.values()) and static and not held and not touching) + regress = [e for e in mon["events"] if e["ev"] == "lost"] + restored = [e for e in mon["events"] if e["ev"] == "restored"] + on = sorted(self.lid_contacts()) + red_top = envs.obj_max_z(self.env, RED) - self.rim_z() + parts = [] + failure = None + if success: + parts.append("The red block and both blue cubes are inside the box and the lid is closed.") + else: + out_items = [n for n in ITEMS if not vals[f"{n}_in_box"]] + if not vals["lid_closed"] and on: + failure = "lid_blocked" + elif held: + failure = "held" + elif touching and all(vals.values()): + failure = "robot_touching" + elif out_items: + failure = ("red_sticks_out" if out_items == [RED] and self.over_box(RED) and red_top > RIM_TOL + else "item_not_in_box") + elif not vals["lid_closed"]: + failure = "lid_open" + else: + failure = "not_static" + if not vals["lid_closed"]: + txt = f"The lid is not closed (open {self.lid_deg():.0f} degrees)" + if on: + names = " and ".join("the red block" if n == RED else "a blue cube" for n in on) + txt += f": it rests on {names}" + parts.append(txt + ".") + for n in out_items: + nm = "The red block" if n == RED else "A blue cube" + if self.held(n): + parts.append(f"{nm} is still held by the gripper.") + elif self.over_box(n) and envs.obj_max_z(self.env, n) > self.rim_z() + RIM_TOL: + top = envs.obj_max_z(self.env, n) - self.rim_z() + pose = self.red_pose() if n == RED else "resting" + parts.append(f"{nm} is in the box but sticks out {100 * top:.1f} cm above the rim ({pose}).") + else: + parts.append(f"{nm} is not in the box: its centre is {self._where(n)}.") + if touching and all(vals.values()): + parts.append("The robot was still pressing on the " + " and ".join(touching) + " at the end.") + if not static and all(vals.values()): + parts.append("Something was still moving at the end.") + if mon["n_blocked"]: + parts.append(f"The lid came down on an item {mon['n_blocked']} time(s) during the attempt.") + out = dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, touching=touching, + events=mon["events"], n_regressions=len(regress), n_restored=len(restored), + false_bottom=bool(inst["false_bottom"]), n_lid_blocked=mon["n_blocked"], + lid_blocked_max_deg=round(mon["blocked_max_deg"], 1), red_relaid=mon["red_relaid"], + red_placed_upright_in_box=mon["red_up_in_box"], red_pose=self.red_pose(), + red_top_above_rim_cm=round(100 * red_top, 1), lid_on=on, + lid_open_max=round(mon["lid_open_max"], 1), lid_final_deg=round(self.lid_deg(), 1), + lid_closes=mon["closes"], knob_grasps=self.sk.knob_grasps, knob_steps=self.sk.knob_steps, + detail=" ".join(parts)) + return out + + # ------------------------------------------------------------ scripted primitives (perfect perception) + def _settle_item(self, name, max_checks=20): + """keep the arm still until `name` has stopped moving (a tipped block rolls on for a moment)""" + d = self.env.sim.data + _, da = envs.free_joint_addr(self.env, name) + for _ in range(max_checks): + if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2: + return + self.sk.hold(2) + + def _grasp_yaw(self, name): + """fingers across a 4 cm side: for the lying red block across its long axis, else yaw mod 90 deg""" + R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3) + if name == RED and self.red_pose() != "upright": + ax = R[:, 2] + yaw = float(np.arctan2(ax[1], ax[0])) # closing direction (-sin, cos) is then across the long axis + return float((yaw + np.pi / 2) % np.pi - np.pi / 2) + i = int(np.argmin(np.abs(R[2]))) + yaw = float(np.arctan2(R[1, i], R[0, i])) + return float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4) + + def _grasp_z(self, name): + """grasp point height above the table for a top-down grasp of `name` where it is""" + zmin = envs.obj_min_z(self.env, name) - envs.TABLE_Z + zmax = envs.obj_max_z(self.env, name) - envs.TABLE_Z + if name == RED and self.red_pose() == "upright": + z = zmin + 0.0425 # 4.25 cm up the 7.5 cm block (0.5 cm above its centre) + else: + z = (zmin + zmax) / 2 + if self.over_box(name): # the hand (2.4 cm above the grasp point) stays above the rim + z = max(z, Z_HAND_MIN, WALL_H + 0.016 if zmax > WALL_H + 0.02 else 0.0) + z = min(z, zmax - 0.004) + return z + + def pick(self, name, z_carry=Z_CARRY, tries=2): + """top-down grasp of `name` where it is, lift to z_carry (a missed grasp is retried once, as anyone would); + returns the grasp point's height above the item's bottom, or None if the grasp failed""" + sk = self.sk + Z = envs.TABLE_Z + for _ in range(tries): + self._settle_item(name) + p = envs.obj_pos(self.env, name) + yaw = self._grasp_yaw(name) + zg = self._grasp_z(name) + zbot = envs.obj_min_z(self.env, name) - Z + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], Z + max(z_carry, zg + 0.06)], yaw=yaw) + sk.hold(8) # let a large wrist turn settle before going down (else the hand drifts ~1 cm near the table) + sk.move_to([p[0], p[1], Z + zg], tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + sk.move_to([p[0], p[1], Z + z_carry], speed=0.3) + if self.held(name): + return zg - zbot + sk.set_gripper(False, steps=8) + return None + + def place(self, dest_xy, z_rel, yaw, z_carry=Z_CARRY): + """carry to above dest at z_carry, lower to z_rel (or until the item / hand rests on something), release, lift""" + sk = self.sk + Z = envs.TABLE_Z + sk.move_to([dest_xy[0], dest_xy[1], Z + z_carry], yaw=yaw) + sk.move_to([dest_xy[0], dest_xy[1], Z + z_rel], tol=0.003, max_steps=80) + sk.set_gripper(False, steps=12) + sk.move_to([dest_xy[0], dest_xy[1], Z + z_carry]) + + def put_in_box(self, name, u, v=0.0, noise=None, z_carry=Z_CARRY): + """pick `name` as it is (the red block upright or lying) and lower it into the box at (u, v) (box frame) as if + the box were deep (the hand stops above the rim), release. The lying red block is turned across the box.""" + off = self.pick(name, z_carry=z_carry) + if off is None: + return False + yaw = np.pi / 2 if name == RED and self.red_pose() == "lying" else self.sk.yaw + d = self.from_box([u, v]) + (np.asarray(noise, float) if noise is not None else 0.0) + self.place(d, max(Z_HAND_MIN, FLOOR_T + off + 0.005), yaw, z_carry=z_carry) + return True + + def red_slot(self): + return SLOT_U["red_lying"] if self.red_pose() == "lying" else SLOT_U["red_upright"] + + def tip_over(self, name, direction, z_push=0.055, speed=0.10): + """push the standing item's upper part with the closed fingers along `direction` (xy) so that it falls over""" + sk = self.sk + Z = envs.TABLE_Z + d = np.asarray(direction, float) + d = d / np.linalg.norm(d) + p = envs.obj_pos(self.env, name) + s = p[:2] - d * 0.06 + e = p[:2] + d * 0.035 + yaw = float(np.arctan2(d[1], d[0])) - np.pi / 2 # finger closing direction along the push + sk.set_gripper(True, steps=8) + sk.move_to([s[0], s[1], Z + 0.13], yaw=yaw) + sk.move_to([s[0], s[1], Z + z_push], tol=0.004) + sk.move_to([e[0], e[1], Z + z_push], speed=speed, tol=0.006) + sk.move_to([e[0], e[1], Z + 0.13], speed=0.3) + self._settle_item(name) + return self.red_pose() if name == RED else None + + def _tip_direction(self, name): + """outward along y (away from the other items, which stand 16 cm apart in a row)""" + y = envs.obj_pos(self.env, name)[1] + return np.array([0.0, 1.0 if y >= 0 else -1.0]) + + def lay_down(self, name=RED, **kw): + """tip the standing block over on the table (up to two pushes); True if it lies""" + for _ in range(2): + if self.red_pose() == "lying": + return True + self.tip_over(name, self._tip_direction(name), **kw) + return self.red_pose() == "lying" + + def take_out_red(self): + """pick the red block out of the box and stand it on its start spot""" + off = self.pick(RED) + if off is None: + return False + self.place(self.inst["start"][RED], off + 0.004, self.sk.yaw) + self._settle_item(RED) + return True + + def _grasp_knob(self, yaw=-np.pi / 2): + """open the fingers, come down on the knob at wrist yaw -90 deg (fingers across the stem), close. Always -90 + (not its gripper-symmetric twin +90): with the lid hanging on its stop beside the box the arm reached the knob + at -90 in every instance, but at +90 it stopped 2-3 cm short against the lid (validate seed 1004: the lying + block's grasp yaw had landed on +90 by numerical chance and the final close missed the knob twice). A 180 deg + wrist turn is avoided by passing through yaw 0 (see Skills.wrap_yaw).""" + sk = self.sk + k = self.knob_xyz() + for attempt in range(2): + sk.set_gripper(False, steps=8) + if abs(sk.yaw - yaw) > np.pi / 2 + 0.1: + sk.move_to([k[0], k[1], k[2] + 0.08], yaw=0.0, wrap_yaw=False) + sk.move_to([k[0], k[1], k[2] + 0.08], yaw=yaw, wrap_yaw=False) + sk.hold(5) + sk.move_to([k[0], k[1], k[2]], tol=0.003) + sk.set_gripper(True, steps=15) + if sk.holding_knob() or attempt: + break + # missed (measured once in 40 validation attempts: after a long sequence of wrist turns the arm's posture + # had drifted and it stopped 3-4 cm short of the knob hanging far to the side): open, go back to a neutral + # pose over the box at yaw 0 (the OSC's null-space term straightens the arm there) and try once more + sk.set_gripper(False, steps=8) + e = sk.eef_pos() + sk.move_to([e[0], e[1], e[2] + 0.10]) + c = self.from_box([0.0, 0.0]) + sk.move_to([c[0], c[1], envs.TABLE_Z + 0.28], yaw=0.0, wrap_yaw=False) + sk.hold(10) + return k + + def open_lid(self, over=0.04, up=0.16): + """grasp the knob (fingers across its stem); straight up 10 cm; straight to `over` m beyond the hinge, `up` m + above it; release; lift""" + sk = self.sk + k = self._grasp_knob() + h = self.hinge_point() + sg = self.hinge_sign() + sk.move_to([k[0], k[1], k[2] + 0.10]) + sk.move_to([h[0], h[1] + sg * over, h[2] + up]) + sk.set_gripper(False, steps=10) + e = sk.eef_pos() + sk.move_to([e[0], e[1] - sg * 0.04, e[2] + 0.05]) + sk.hold(25) + + def close_lid(self, away=0.08, up=0.10): + """grasp the knob where it is; straight up 10 cm; straight to `away` m on the knob side of the hinge; release""" + sk = self.sk + k = self._grasp_knob() + h = self.hinge_point() + sg = self.hinge_sign() + sk.move_to([k[0], k[1], k[2] + up]) + sk.move_to([h[0], h[1] - sg * away, max(k[2], h[2]) + up]) + sk.set_gripper(False, steps=10) + e = sk.eef_pos() + sk.move_to([e[0], e[1], e[2] + 0.06]) + sk.hold(30) + + def press_lid(self): + """the natural retry when the lid did not shut: grasp the knob where it is and push it down towards closed""" + sk = self.sk + k = self._grasp_knob() + h = self.hinge_point() + sg = self.hinge_sign() + sk.move_to([k[0], h[1] - sg * (LX + 0.01), h[2] - 0.01], speed=0.1) + sk.set_gripper(False, steps=10) + e = sk.eef_pos() + sk.move_to([e[0], e[1], e[2] + 0.08]) + sk.hold(30) + + def _fallen(self): + """items that ended up outside the box (not merely sticking out of it)""" + return [n for n in ITEMS if not self.in_box(n) and not self.over_box(n) and not self.held(n)] + + def _replace_fallen(self, done, noise=None, z_carry=Z_CARRY): + for n in [n for n in self._fallen() if n in done]: + self.put_in_box(n, self.red_slot() if n == RED else SLOT_U[n], noise=(noise or {}).get(n), z_carry=z_carry) + + # ------------------------------------------------------------ scripted policies + def execute(self, inst, params): + noise = params.get("noise") or {} + zc = params.get("z_carry", Z_CARRY) + self.open_lid(**params.get("open", {})) + done = [] + for n in ITEMS: + if n == RED and params.get("lay_first"): + self.lay_down(RED) + self.put_in_box(n, self.red_slot() if n == RED else SLOT_U[n], noise=noise.get(n), z_carry=zc) + done.append(n) + self._replace_fallen(done, noise, zc) # looks after every step: re-places an item that fell outside + self.close_lid(**params.get("close", {})) + if params.get("check") == "naive": + self.naive_check(noise, zc) + elif params.get("check") == "fix": + self.check_and_fix() + self.sk.hold(10) + + def naive_check(self, noise=None, z_carry=Z_CARRY): + """Sonnet-like look before finishing, without the insight: a lid that did not shut is pushed down once (re-closed + if it is still open past upright); an item outside the box is put back as it is (the red block upright)""" + if not self.lid_closed(): + if self.lid_deg() > 90: + self.close_lid() + else: + self.press_lid() + if self._fallen(): + if self.lid_deg() < 90: + self.open_lid() + self._replace_fallen(list(ITEMS), noise, z_carry) + self.close_lid() + + def check_and_fix(self, rounds=2): + """look at every stage; if the red block is not inside below the rim (it stands up out of a shallow box and + holds the lid open), take it out, lay it down on the table and put it in lying; re-place anything outside the + box; close the lid""" + for _ in range(rounds): + v = self.stage_values() + if all(v.values()) and not any(self.held(n) for n in ITEMS): + return True + bad = [n for n in ITEMS if not v[f"{n}_in_box"]] + if self.lid_deg() < 90 and (bad or self.lid_contacts()): + self.open_lid() + for n in bad: + if n == RED and self.red_pose() != "lying": + if self.over_box(RED): + self.take_out_red() + self.lay_down(RED) + self.put_in_box(n, self.red_slot() if n == RED else SLOT_U[n]) + if self.lid_deg() > 90 or not self.lid_closed(): + self.close_lid() + return all(self.stage_values().values()) + + def default_params(self, inst): + """Sonnet-like: open the lid, items in the listed order, each put in as found (the block upright), carried + 16 cm up, looks after every step (re-places an item that fell outside), closes the lid, pushes a lid that did + not shut down once, finishes""" + return dict(lay_first=False, check="naive") + + def oracle_params(self, inst): + """knows the inner depth: lays the block down first in a shallow box; checks every stage at the end""" + return dict(lay_first=bool(inst["false_bottom"]), check="fix") + + def adapt_params(self, inst, history): + """attempt >= 2 (after a failure): lay the block down before putting it in, then check and fix""" + return dict(lay_first=True, check="fix") + + def blind_params(self, inst, attempt, rng): + """the natural behaviour again with small random variations, no history""" + return dict(lay_first=False, check="naive", + noise={n: rng.uniform(-0.005, 0.005, 2).tolist() for n in ITEMS}, + z_carry=float(rng.uniform(0.13, 0.19)), + open=dict(over=float(rng.uniform(0.02, 0.06)), up=float(rng.uniform(0.14, 0.18))), + close=dict(away=float(rng.uniform(0.06, 0.10)))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """oracle / naive: one attempt; adaptive: attempt 1 = the natural placement plus a real check and fix (takes the + block out and lays it down when the lid is blocked), later attempts lay it down first; blind: natural with + random variations; switch (extra control): natural, then lay it down first from attempt 2, no real check""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = dict(lay_first=False, check="fix") if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": + params = self.default_params(inst) if a == 0 else dict(lay_first=True, check="naive") + elif kind == "oracle_noise": # robustness check: oracle with +-5 mm placement noise + params = dict(self.oracle_params(inst), noise={n: rng.uniform(-0.005, 0.005, 2).tolist() for n in ITEMS}) + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive", "oracle_noise"): + break + return history diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/lh_order_dispatch.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/lh_order_dispatch.py new file mode 100644 index 0000000000000000000000000000000000000000..4fbca418828c2aec9e5a248d17a51db00760bef0 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/lh_order_dispatch.py @@ -0,0 +1,242 @@ +"""Development composite: physically load two products and a card, then steer a weighted shipping tray. +L1 fixed calibration bias, L3 card edge strategy, L5 off-centre loaded push. Not in the main set. +""" +import numpy as np +import copy +import xml.etree.ElementTree as ET +from .. import envs +from ..bddl import write_bddl +from ..objects import box_xml, register_generated +from ..task_base import LFFTask, register_task +from .l3_card_edge import CardEdge, card_xml, BOARD_HALF, BOARD_TOP, CARD_HALF, GRASP_OUT +from .l7_offcenter_push import (OffcenterPush, PushSkills, long_box_xml, rect_frame_xml, HALF, + MASS, MU, box_fit, box_corners, _yaw, _rot) + +PRODUCTS = ('product_red_1', 'product_blue_1') +CARGO = PRODUCTS + ('card_1',) +PH = .014 + + +def shipping_xml(): + xml = long_box_xml('lff_dispatch_box') + parts=[] + for k,(p,h) in enumerate([((.042,0,.025),(.003,.11,.005)),((-.042,0,.025),(.003,.11,.005)), + ((0,.107,.032),(.039,.003,.012)),((0,-.107,.032),(.039,.003,.012))]): + parts.append(f'') + return xml.replace(' ', '\n'.join(parts)+'\n ',1) + + +class DispatchSkills(PushSkills): + def __init__(self, env, task, bias, recorder=None): + super().__init__(env,bias=bias,recorder=recorder,target=task.target_xy(task.inst)) + self.task=task + self.closes=[] + self.correction=np.zeros(3) + self.n_commands=0 + def reported_eef_pos(self): + return self.eef_pos()-self.bias + def move_to(self,target,*args,**kwargs): + self.n_commands+=1 + if self.n_commands>self.task.agent_max_steps:raise RuntimeError("dispatch command budget exceeded") + rep=super().move_to(np.asarray(target)-self.correction,*args,**kwargs) + rep['pos']=np.round(self.reported_eef_pos(),4).tolist() + return rep + def _act(self,dpos,drot,grip): + super()._act(dpos,drot,grip) + self.task.monitor_step() + if self.n_steps*.05>=3*self.task.agent_max_steps:raise RuntimeError('dispatch simulation budget exceeded') + def set_gripper(self,close,steps=15): + self.n_commands+=1 + if self.n_commands>self.task.agent_max_steps:raise RuntimeError("dispatch command budget exceeded") + ctx=self.task.close_context() if close and self.grip<0 else None + rep=super().set_gripper(close,steps) + if ctx is not None: + ctx.update(held=self.holding('card_1'),width=round(self.gripper_width(),4)) + self.closes.append(ctx) + return rep + + +@register_task +class OrderDispatch(CardEdge,OffcenterPush): + name='lh_order_dispatch' + level='L1' + failure_causes=('L1','L3','L5') + failure_types=failure_causes + category='system_identification' + capabilities=('Perceive','Reason','Plan','Restore') + protocol='cross' + max_attempts=5 + agent_max_steps=180 + instruction=('Load both small products and the red order card into the brown shipping tray, while it is in ' + 'the yellow loading rectangle. Then push the loaded tray with the closed gripper completely inside the green ' + 'delivery rectangle. All three items must remain inside the tray, with the gripper open and clear.') + instruction_indirect=('Pack the two small coloured cubes and the thin red rectangle into the long brown ' + 'container while the container is at its starting position, then push the loaded container with the closed ' + 'gripper completely into the green marked area. Keep every item inside, and finish with the ' + 'gripper open and clear.') + def make_bddl(self): + card=register_generated('LffDispatchCard',card_xml('lff_dispatch_card')) + board=register_generated('LffDispatchBoard',box_xml('lff_dispatch_board',BOARD_HALF,(.62,.45,.27,1),friction=(.3,.005,.0001)),free=False) + box=register_generated('LffDispatchBox',shipping_xml()) + zone_xml=ET.fromstring(rect_frame_xml('lff_dispatch_zone')) + load_xml=ET.fromstring(rect_frame_xml('lff_dispatch_loading',inner_half=(.10,.15),line_rgba=(.8,.6,.05,1),fill_rgba=(.95,.88,.55,1))) + body=zone_xml.find('worldbody/body/body') + for geom in load_xml.find('worldbody/body/body'): + q=np.fromstring(geom.get('pos','0 0 0'),sep=' ');q[0]-=.11;geom.set('pos',' '.join(map(str,q)));body.append(geom) + zone=register_generated('LffDispatchZone',ET.tostring(zone_xml,encoding='unicode'),free=False) + objs=[('card_1',card,'card_region',(-.305,.395,-.295,.405)),('box_1',box,'box_region',(-.255,-.005,-.245,.005))] + for k,o in enumerate(PRODUCTS): + cat=register_generated('LffDispatchProduct'+('Red' if k==0 else 'Blue'),box_xml('lff_dispatch_product_'+str(k),(PH,PH,PH),((.9,.1,.1,1) if k==0 else (.1,.2,.9,1)),density=500)) + objs.append((o,cat,'prod_region'+str(k),(-.305+.25*k,-.405,-.295+.25*k,-.395))) + return write_bddl(self.name,self.instruction,objs,[('board_1',board,'board_region',(.295,.345,.305,.355)),('zone_1',zone,'zone_region',(.295,-.355,.305,-.345))]) + def __init__(self,cam_res=None): + LFFTask.__init__(self,cam_res) + self.board_bid=self.env.sim.model.body_name2id(self.env.fixtures_dict['board_1'].root_body) + self.inst=None;self.mon=None + def sample_instance(self,seed): + rng=np.random.default_rng(seed) + bx=-.18;by=.20 + return dict(seed=int(seed),board_xy=[bx,by],card_xy=[bx,by],card_yaw=0.,card_along='x', + bin_xy=[-.21,-.08],box_xy=[-.21,-.08],target_dist=.11, + bias=[0.,float(rng.choice([-1,1])*.055),0.],com_offset=float(rng.choice([-1,1])*.06), + mechanisms={'L1':True,'L3':True,'L5':True}) + def apply_instance(self,inst): + self.inst=inst + OffcenterPush.apply_instance(self,inst) + m=self.env.sim.model + m.body_pos[self.board_bid]=[*inst['board_xy'],envs.TABLE_Z+BOARD_HALF[2]] + m.body_quat[self.board_bid]=[1,0,0,0] + envs.set_obj_pose(self.env,'card_1',[*inst['card_xy'],BOARD_TOP+CARD_HALF[2]+.0003],yaw=inst['card_yaw']) + for k,o in enumerate(PRODUCTS): + envs.set_obj_pose(self.env,o,[-.25+.14*k,-.31,envs.TABLE_Z+PH+.001]) + bid=envs.body_id(self.env,'box_1') + if not inst['mechanisms']['L5']:m.body_ipos[bid]=[0,0,0];envs.refit_bounds(self.env,bid) + if not inst['mechanisms']['L3']: + # Initial overhang removes the flat-card obstruction; reset-time placement only. + envs.set_obj_pose(self.env,'card_1',[inst['board_xy'][0]-BOARD_HALF[0]+CARD_HALF[0]-.03,inst['board_xy'][1],BOARD_TOP+CARD_HALF[2]+.0003]) + def reset_instance(self,inst,recorder=None): + self.mon=None;self.env.reset();self.apply_instance(inst);self.env.sim.forward();envs.settle(self.env,15) + self.sk=DispatchSkills(self.env,self,np.array(inst['bias']) if inst['mechanisms']['L1'] else np.zeros(3),recorder) + self.mon=dict(start_xy=self.card_pose()['xy'].copy(),max_lift=0.,max_overhang=0.,fell=False, + loaded=False,load_step=None,departed_unloaded=False,events=[],states={o:False for o in CARGO},l1_attempts=[]) + self.sim0=0;self.ncmd=0;self.budget=None + return self.sk + def in_cargo(self,o,require_support=True): + p=envs.obj_pos(self.env,o);b=envs.obj_pos(self.env,'box_1');R=_rot(_yaw(envs.obj_quat(self.env,'box_1'))) + rel=R.T@(p[:2]-b[:2]);half=PH if o in PRODUCTS else 0. + # Full footprint containment, including card corners. + if o=='card_1': + rels=(self.card_corners()[:,:2]-b[:2])@R + footprint=bool(np.all(np.abs(rels[:,0])<.039) and np.all(np.abs(rels[:,1])<.104)) + else: + rot=self.env.sim.data.body_xmat[envs.body_id(self.env,o)].reshape(3,3) + corners=np.array([p+rot@np.array([a*PH,b*PH,c*PH]) for a in (-1,1) for b in (-1,1) for c in (-1,1)]) + rels=(corners[:,:2]-b[:2])@R + footprint=bool(np.all(np.abs(rels[:,0])<.039) and np.all(np.abs(rels[:,1])<.104)) + support=any(envs.contacts_between(self.env,envs.obj_geom_ids(self.env,o),envs.obj_geom_ids(self.env,q)) for q in CARGO+('box_1',) if q!=o) + return bool(footprint and (support or not require_support) and b[2]+.015=0 else -1. + grasp=p['xy']+sign*.034*axis + floor=b[2]+HALF[2] + return self.grasp_and_bin(grasp,p['yaw'],floor-.003) + def load_product(self,o,k): + sk=self.sk;p=envs.obj_pos(self.env,o).copy();sk.set_gripper(False,8) + sk.move_to([p[0],p[1],envs.TABLE_Z+.18],yaw=0) + approach_offset=(sk.eef_pos()[:2]-p[:2]).tolist() + sk.move_to([p[0],p[1],p[2]+.003],tol=.002,max_steps=120) + offset=(sk.eef_pos()[:2]-p[:2]).tolist() + sk.set_gripper(True,15);sk.move_to([p[0],p[1],envs.TABLE_Z+.19]) + held=sk.holding(o) + self.mon['l1_attempts'].append(dict(item=o,offset=offset,approach_offset=approach_offset,correction=self.sk.correction.tolist(),held=bool(held),step=sk.n_steps)) + if not held:sk.set_gripper(False,8);return False + b=envs.obj_pos(self.env,'box_1');xy=[b[0],b[1]+(-.075 if k==0 else .075)] + sk.move_to([*xy,envs.TABLE_Z+.20]);sk.move_to([*xy,envs.TABLE_Z+.058],speed=.1) + sk.set_gripper(False,12);sk.move_to([*xy,envs.TABLE_Z+.22]);return self.in_cargo(o) + def execute(self,inst,params): + if 'mode' not in params: + return OffcenterPush.execute(self,inst,params) + mode=params['mode'];self.sk.correction=np.asarray(params.get('correction',[0,0,0]),dtype=float) + for k,o in enumerate(PRODUCTS): + if not self.load_product(o,k):return + if mode=='adaptive': + self.sk.correction+=np.array([*self.mon['l1_attempts'][-1]['approach_offset'],0.]) + if mode=='naive': + CardEdge.execute(self,inst,dict(mode='grasp')) + else: + CardEdge.execute(self,inst,dict(mode='edge',overhang=.03)) + self.sk.hold(10) + if not all(self.in_cargo(o) for o in CARGO):return + if mode=='adaptive': + OffcenterPush.adaptive_attempt(self,inst,params.get('c',0.)) + if not self.in_cargo('card_1'):self.repair_card() + else:OffcenterPush.execute(self,inst,dict(c=params.get('c',0.))) + p=self.sk.eef_pos();self.sk.move_to([p[0],p[1],envs.TABLE_Z+.23]);self.sk.set_gripper(False,8) + def outcome(self,inst): + self.sk.hold(30) + p=envs.obj_pos(self.env,'box_1');yaw=_yaw(envs.obj_quat(self.env,'box_1'));fit=box_fit(p[:2],yaw,self.target_xy(inst)) + cargo={o:self.in_cargo(o) for o in CARGO} + velocities=[] + for o in CARGO+('box_1',): + adr=self.env.sim.model.jnt_dofadr[self.env.sim.model.joint_name2id(self.env.objects_dict[o].joints[0])] + velocities.append(self.env.sim.data.qvel[adr:adr+6].copy()) + static=all(np.linalg.norm(v[:3])<.01 and np.linalg.norm(v[3:])<.15 for v in velocities) + m=self.env.sim.model + robot=[g for g in range(m.ngeom) if (m.geom_id2name(g) or '').startswith(('robot0_','gripper0_'))] + touching=any(envs.contacts_between(self.env,robot,envs.obj_geom_ids(self.env,o)) for o in CARGO+('box_1',)) + upright=envs.obj_upright_cos(self.env,'box_1')>.95 + success=bool(all(cargo.values()) and self.mon['loaded'] and not self.mon['departed_unloaded'] and fit['inside'] and static and upright and not touching and self.sk.grip<0) + bad=[m for m in self.sk.box_moves if m.get('bad') and not m.get('gripper_open') and self.mon['load_step'] is not None and m['step']>=self.mon['load_step']] + return copy.deepcopy(dict(success=success,cargo=cargo,loaded_in_start=bool(self.mon['loaded']),load_step=self.mon['load_step'],departed_unloaded=self.mon['departed_unloaded'],inside=fit['inside'],static=bool(static), + failure=None if success else 'cargo' if not all(cargo.values()) else 'loading_order' if not self.mon['loaded'] else 'delivery', + stages={**cargo,'loaded_in_start':self.mon['loaded'],'delivery':fit['inside']},events=self.mon['events'], + l1_attempts=self.mon['l1_attempts'],card_closes=self.sk.closes,card_lift=self.mon['max_lift'], + box_moves=self.sk.box_moves,l5_triggered=bool(bad),yaw_deg=float(np.degrees(yaw)), + sim_s=self.sk.n_steps*.05,commands=self.sk.n_commands,touching=bool(touching),upright=bool(upright), + detail='Cargo in tray: '+str(cargo)+'; tray inside delivery rectangle: '+str(fit['inside'])+'.')) + def default_params(self,inst):return dict(mode='naive') + def oracle_params(self,inst):return dict(mode='oracle',correction=(inst['bias'] if inst['mechanisms']['L1'] else [0,0,0]),c=inst['com_offset'] if inst['mechanisms']['L5'] else 0.) + def adapt_params(self,inst,history): + # Calibration estimate from the measured failed grasp, not hidden bias. + offsets=[x['offset'] for h in history for x in h['outcome']['l1_attempts']] + calibrations=[np.array(x.get('correction',h['params'].get('correction',[0,0,0])))+np.array([*x.get('approach_offset',x['offset']),0.]) for h in history for x in h['outcome']['l1_attempts']] + corr=np.mean(calibrations[-2:],axis=0).tolist() if calibrations else history[-1]['params'].get('correction',[0,0,0]) + moves=[m for h in history for m in h['outcome']['box_moves']] + return dict(mode='adaptive',correction=corr,c=self.bracket(moves)) + def blind_params(self,inst,attempt,rng):return dict(mode='naive',correction=[*rng.normal(0,.005,2),0.]) + def run_scripted(self,*args,**kwargs):return LFFTask.run_scripted(self,*args,**kwargs) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/lh_pantry_relatch.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/lh_pantry_relatch.py new file mode 100644 index 0000000000000000000000000000000000000000..7369d4e23432eed637a47131d7c8f988e5eca7f0 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/lh_pantry_relatch.py @@ -0,0 +1,468 @@ +"""LH pantry_relatch: breakfast prep. Take the bread out of a hinged pantry box and put it on the plate, then put the +butter into the (now empty) box and close it. + +New mechanism (not a repeat of lh_lid_box / lh_shelf_droop / lh_false_bottom_lid): the box's closing catch is not a +static per-instance draw, it is a counter of how many times the box has already been closed in this attempt. A weak +spring (`OPEN_BIAS`) constantly nudges the lid open; a catch (`qfrc_applied`, same idiom as lh_shelf_droop's bracket) +counters it near the closed angle. The FIRST close always holds (LATCH0 beats the spring) even with a quick swing-and +-release. After one full open/close cycle the catch's holding strength is reduced (`DECAY`); a second quick-release +close is no longer enough and the lid creeps back open by itself during the mandatory settle window, with nothing +else touching it. The fix is not "close it again the same way" (that decays again); it is a firm press-and-hold +(`dwell`) at the closed angle before letting go, which engages a separate, non-decaying friction seat +(`SEAT_LATCH`) regardless of cycle count. + +Geometry/skills are reused unmodified from lh_lid_box.py (box_lid_xml, LidSkills): only the hinge's spring/latch +torques and the Python cycle counter are new. Protocol: cross, k = 5. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import box_xml, register_generated +from ..task_base import LFFTask, register_task +from .lh_lid_box import (BOX_D, BOX_W, WALL_H, WALL_T, FLOOR_T, LID_T, LID_MASS, IN_X, IN_Y, HINGE_DAMP, box_lid_xml, + LidSkills) + +G = 9.81 +BOX = "box_1" +BOX_MODEL = "lff_pantry_box" + +BREAD_HALF = (0.032, 0.022, 0.011) # 6.4 x 4.4 x 2.2 cm flat loaf, fits the 3.2 cm interior height +BUTTER_HALF = (0.013, 0.013, 0.013) # 2.6 cm cube +BREAD_DENS, BUTTER_DENS = 400.0, 600.0 + +# ---------------------------------------------------------------- latch-fatigue mechanism +CLOSE_DEG = 4.0 # lid angle (deg) counted as "closed" for the final judge +BAND_DEG = 100.0 # angle range (deg) over which gravity is cancelled and the open bias/catch act (wide, so +# an unlatched lid drifts smoothly all the way open instead of sticking at a cutoff edge) +OPEN_BIAS = 0.05 # N*m: net torque pushing the lid open within the band, once gravity is cancelled +LATCH0 = 0.14 # N*m: catch strength on the FIRST close (always beats OPEN_BIAS) +DECAY = 0.30 # catch strength multiplier from the SECOND close on, if not seated +SEAT_LATCH = 0.18 # N*m: non-decaying strength if the close was seated (dwell-pressed) +DWELL_MIN = 20 # control steps (closed, knob held, no further motion) needed to seat a close +EXTRA_DAMP = 0.12 # N*m*s/rad added to the hinge dof so an unlatched drift takes a few seconds, not instant +GRAVITY_LEVER = BOX_D / 2 # lid's centre of mass offset from the hinge (box_lid_xml convention) +T_GRAV0 = LID_MASS * G * GRAVITY_LEVER + +SETTLE_MIN, SETTLE_MAX = 300, 600 # 15-30 s simulated, same convention as lh_shelf_droop + + +def _fb(v): + return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}" + + +def _lr(v): + return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}" + + +class RelatchSkills(LidSkills): + """LidSkills plus a dwell counter: control steps spent holding the knob still at the closed angle while latched. + `monitor_step` (run every control step via LidSkills._act, before this class's own _act resets the counter) + reads it at the instant the gripper opens near the closed angle to decide whether this close is 'seated'.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, task, recorder=recorder) + self.dwell = 0 + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) # LidSkills._act calls self.task.monitor_step() before returning here + if self.latched: + # the agent (or scripted policy) is actively holding the knob: never let the artificial drift fight + # that grasp (it caused the knob to wander off mid-regrasp during prototyping). + self.task.drift_active = False + if self.task.lid_deg() < CLOSE_DEG: + self.dwell += 1 + else: + self.dwell = 0 + else: + self.dwell = 0 + + +@register_task +class PantryRelatch(LFFTask): + name = "lh_pantry_relatch" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Plan", "Restore") + protocol = "cross" + max_attempts = 5 + agent_max_steps = 130 + instruction = ("Open the lid of the wooden pantry box (lift it by the black knob) and take the bread out; put it " + "on the plate. Then open the box again, put the butter inside it, and close the lid. At the end " + "the bread must be on the plate, the butter inside the box, the lid closed, the gripper open and " + "clear, and the scene still.") + instruction_indirect = ("Lift the lid of the flat wooden case by its black ball knob and take out the little " + "loaf; set it on the round plate. Then open the case again, put the small pale cube " + "inside it, and shut the lid. Finish with the loaf on the plate, the cube inside the " + "case, the lid down, the gripper open, and nothing moving.") + agent_object_names = ["bread (small loaf)", "butter (small pale cube)", "wooden pantry box", "lid knob", "plate"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + box = register_generated("LffPantryBox", box_lid_xml(BOX_MODEL), free=False) + bread = register_generated("LffPantryBread", box_xml("lff_pantry_bread", BREAD_HALF, (0.74, 0.52, 0.22, 1.0), + density=BREAD_DENS, friction=(0.7, 0.005, 0.0001))) + butter = register_generated("LffPantryButter", box_xml("lff_pantry_butter", BUTTER_HALF, (0.95, 0.92, 0.70, 1.0), + density=BUTTER_DENS, friction=(0.5, 0.005, 0.0001))) + objs = [("bread_1", bread, "bread_region", (-0.31, -0.01, -0.29, 0.01)), + ("butter_1", butter, "butter_region", (-0.31, 0.24, -0.29, 0.26)), + ("plate_1", "plate", "plate_region", (0.02, -0.26, 0.04, -0.24))] + fx = [(BOX, box, "box_region", (-0.18, -0.01, -0.16, 0.01))] + return write_bddl(self.name, "take the bread out, put it on the plate, put the butter in the box, close it", + objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + pre = f"{BOX}_{BOX_MODEL}" + self.jid = m.joint_name2id(pre + "_hinge") + self.qa = int(m.jnt_qposadr[self.jid]) + self.dof = int(m.jnt_dofadr[self.jid]) + self.box_bid = m.body_name2id(self.env.fixtures_dict[BOX].root_body) + self.knob_geom_name = pre + "_knob" + self.knob_geom_names = [pre + "_knob", pre + "_stem"] + self.knob_gid = m.geom_name2id(self.knob_geom_name) + sim = self.env.sim + if not getattr(sim, "_lhpr_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lhpr_task", None) + if t is not None: + t._bracket() + + sim.step = step + sim._lhpr_wrapped = True + sim._lhpr_task = self + self.inst = None + self.mon = None + self.active_latch = LATCH0 + self.closes_done = 0 + self.drift_active = False + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + bx, by = float(rng.uniform(-0.19, -0.15)), float(rng.uniform(-0.03, 0.03)) + plate_xy = [float(rng.uniform(0.0, 0.06)), float(rng.uniform(-0.27, -0.23))] + bread_xy = [bx + float(rng.uniform(-0.01, 0.01)), by + float(rng.uniform(-0.01, 0.01))] + butter_xy = [float(rng.uniform(-0.32, -0.28)), float(rng.uniform(0.22, 0.28))] + return dict(seed=int(seed), box_xy=[bx, by], plate_xy=plate_xy, bread_xy=bread_xy, butter_xy=butter_xy, + bread_yaw=float(rng.uniform(-0.2, 0.2)), latch=True) + + def apply_instance(self, inst): + self.inst = inst + m, d = self.env.sim.model, self.env.sim.data + bx, by = inst["box_xy"] + m.body_pos[self.box_bid] = [bx, by, envs.TABLE_Z] + m.body_quat[self.box_bid] = [1.0, 0.0, 0.0, 0.0] + m.jnt_range[self.jid] = [0.0, np.radians(150.0)] + d.qpos[self.qa] = 0.0 + d.qvel[self.dof] = 0.0 + d.qfrc_applied[self.dof] = 0.0 + m.dof_damping[self.dof] = HINGE_DAMP + EXTRA_DAMP # absolute, not cumulative across repeated resets + self._move_keep_orientation("plate_1", inst["plate_xy"]) + envs.set_obj_pose(self.env, "bread_1", [bx, by, envs.TABLE_Z + FLOOR_T + BREAD_HALF[2] + 0.001], + yaw=inst["bread_yaw"]) + envs.set_obj_pose(self.env, "butter_1", [*inst["butter_xy"], envs.TABLE_Z + BUTTER_HALF[2] + 0.0005]) + self.closes_done = 0 + self.active_latch = LATCH0 + self.drift_active = False + + def _move_keep_orientation(self, name, xy, clearance=0.002): + qa, da = envs.free_joint_addr(self.env, name) + d = self.env.sim.data + d.qpos[qa:qa + 2] = xy + d.qvel[da:da + 6] = 0.0 + self.env.sim.forward() + d.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (envs.TABLE_Z + clearance) + self.env.sim.forward() + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.mon = dict(events=[], lid_open_max=0.0, armed=False) + self.sk = RelatchSkills(self.env, self, recorder=recorder) + return self.sk + + # ------------------------------------------------------------ latch physics + def lid_q(self): + return float(self.env.sim.data.qpos[self.qa]) + + def lid_deg(self): + return float(np.degrees(self.lid_q())) + + def knob_xyz(self): + return self.env.sim.data.geom_xpos[self.knob_gid].copy() + + def hinge_xz(self): + return self.inst["box_xy"][0] + BOX_D / 2, envs.TABLE_Z + WALL_H + + def _bracket(self): + """Every MuJoCo substep. Only active between a just-finished, under-latched close and the next time the + agent actually grasps the knob again (self.drift_active, cleared the instant the knob is latched -- see + RelatchSkills._act): within BAND_DEG of closed, cancel gravity's closing pull and add a small constant + opening bias, net positive because the catch is too weak (self.active_latch < OPEN_BIAS whenever + drift_active is set True in the first place). A held-firmly close needs no artificial force at all: plain + gravity already keeps box_lid_xml's lid shut on its own, same as lh_lid_box.""" + d = self.env.sim.data + if not self.inst.get("latch", True) or not self.drift_active: + d.qfrc_applied[self.dof] = 0.0 # never leave a stale value applied once the drift is no longer armed + return + th = float(d.qpos[self.qa]) + # the closed rest angle overshoots the joint limit by a hair (contact softness), so the lower edge of the + # band must tolerate a small negative theta -- a strict "th >= 0" guard left qfrc_applied permanently 0 at + # the resting pose and the catch never engaged at all (measured during prototyping). + if np.radians(-3.0) <= th < np.radians(BAND_DEG): + grav = T_GRAV0 * max(np.cos(th), 0.0) + d.qfrc_applied[self.dof] = grav + OPEN_BIAS - self.active_latch + else: + d.qfrc_applied[self.dof] = 0.0 + + def _register_close(self, seated): + """Called once a close-then-release is detected. Decides the catch strength that will apply to THIS closed + state from now on (until the lid is reopened and closed again), and whether the artificial drift-open force + is armed (only when the catch is too weak to hold on its own).""" + if self.closes_done == 0: + self.active_latch = LATCH0 + elif seated: + self.active_latch = SEAT_LATCH + else: + self.active_latch = LATCH0 * DECAY + self.closes_done += 1 + self.drift_active = self.active_latch < OPEN_BIAS + self.mon["events"].append(dict(ev="closed", n=self.closes_done, seated=bool(seated), + active_latch=round(self.active_latch, 4), drift_armed=self.drift_active)) + + def monitor_step(self): + """Runs every control step (via LidSkills._act, for the scripted policies below and for a real agent's own + move_to/set_gripper calls alike). One-shot edge detector: 'armed' once the lid has been meaningfully open + (> 20 deg); the first step afterwards where it is back near closed AND the gripper is open counts as a + close event, scored seated/unseated from the dwell counter at that exact instant (before RelatchSkills._act + resets it for this same step -- see the call order note there).""" + mon = self.mon + if mon is None: + return + q = self.lid_deg() + mon["lid_open_max"] = max(mon["lid_open_max"], q) + if q > 20.0: + mon["armed"] = True + if mon.get("armed") and q <= CLOSE_DEG and self.sk.grip < 0: + mon["armed"] = False + self._register_close(self.sk.dwell >= DWELL_MIN) + + # ------------------------------------------------------------ predicates + def held(self, name): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name])) + + def bread_on_plate(self): + p = envs.obj_pos(self.env, "bread_1") + d = np.linalg.norm(p[:2] - np.asarray(self.inst["plate_xy"])) + return bool(d < 0.05 and p[2] < envs.TABLE_Z + 0.06 and not self.held("bread_1")) + + def butter_in_box(self): + p = envs.obj_pos(self.env, "butter_1") + rel = p[:2] - np.asarray(self.inst["box_xy"]) + return bool(abs(rel[0]) <= IN_X - 0.004 and abs(rel[1]) <= IN_Y - 0.004 and p[2] < envs.TABLE_Z + WALL_H + and not self.held("butter_1")) + + def lid_closed(self): + return self.lid_q() <= np.radians(CLOSE_DEG) + + def stage_values(self): + return dict(bread_on_plate=self.bread_on_plate(), butter_in_box=self.butter_in_box(), lid_closed=self.lid_closed()) + + # ------------------------------------------------------------ scripted primitives + def pick_place(self, name, dest_xy, z_rel, z_carry=0.14, dest_yaw=0.0): + sk = self.sk + Z = envs.TABLE_Z + p = envs.obj_pos(self.env, name) + zg = p[2] - Z + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], Z + max(z_carry, zg + 0.06)], yaw=0.0) + sk.move_to([p[0], p[1], Z + zg], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([p[0], p[1], Z + z_carry], speed=0.3) + self.monitor_step() + if not self.held(name): + sk.set_gripper(False, steps=8) + return False + sk.move_to([dest_xy[0], dest_xy[1], Z + z_carry], yaw=dest_yaw) + sk.move_to([dest_xy[0], dest_xy[1], Z + z_rel], tol=0.003) + sk.set_gripper(False, steps=12) + sk.move_to([dest_xy[0], dest_xy[1], Z + z_carry]) + self.monitor_step() + return True + + def take_bread(self): + return self.pick_place("bread_1", self.inst["plate_xy"], BREAD_HALF[2] + 0.004) + + def put_butter(self): + # placed closer to the hinge side and off to one side of the box centre, clear of where the far (knob) end + # of the lid sweeps most when re-opened for a repair (measured during prototyping: a butter cube resting + # under the box centre was occasionally grazed by that swing). + bx, by = self.inst["box_xy"] + target = [bx + 0.6 * IN_X, by + 0.5 * IN_Y] + return self.pick_place("butter_1", target, FLOOR_T + BUTTER_HALF[2] + 0.006, z_carry=0.12) + + def _grasp_knob(self): + sk = self.sk + k = self.knob_xyz() + sk.set_gripper(False, steps=8) + sk.move_to([k[0], k[1], k[2] + 0.08], yaw=0.0) + sk.move_to([k[0], k[1], k[2]], tol=0.003) + sk.set_gripper(True, steps=15) + return k + + def open_lid(self, back=0.03, up=0.16): + sk = self.sk + k = self._grasp_knob() + hx, hz = self.hinge_xz() + sk.move_to([k[0], k[1], k[2] + 0.10]) + sk.move_to([hx + back, k[1], hz + up]) + sk.set_gripper(False, steps=10) + e = sk.eef_pos() + sk.move_to([e[0] - 0.03, e[1], e[2] + 0.06]) + sk.hold(20) + self.monitor_step() + + def close_lid(self, dwell=False): + """grasp the knob, carry it down the hinge's arc to the closed angle (the compliant knob-hold mechanism + clamps the physical joint limit at 0 deg, so a target far past closed just drives it fully shut); if dwell, + hold there (gripper still closed on the knob) for DWELL_MIN+ steps before releasing (seats the friction + catch); otherwise release immediately.""" + sk = self.sk + k = self._grasp_knob() + hx, hz = self.hinge_xz() + sk.move_to([k[0], k[1], k[2] + 0.10]) + far_x = hx - (BOX_D + 0.20) + low_z = envs.TABLE_Z + 0.02 + for _ in range(4): + if self.lid_deg() <= CLOSE_DEG: + break + sk.move_to([far_x, sk.eef_pos()[1], low_z], tol=0.01, max_steps=150) + if dwell: + sk.hold(DWELL_MIN + 8) + sk.set_gripper(False, steps=10) + e = sk.eef_pos() + sk.move_to([e[0], e[1], e[2] + 0.06]) + sk.hold(20) + self.monitor_step() + + # ------------------------------------------------------------ outcome + def _static(self): + d = self.env.sim.data + for name in ("bread_1", "butter_1"): + _, da = envs.free_joint_addr(self.env, name) + if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5: + return False + return abs(float(d.qvel[self.dof])) < 0.2 + + def outcome(self, inst): + sk = self.sk + n = 0 + while n < SETTLE_MAX: + sk.hold(10) + n += 10 + if n >= SETTLE_MIN and self._static(): + break + vals = self.stage_values() + held = [n for n in ("bread_1", "butter_1") if self.held(n)] + static = self._static() + success = bool(all(vals.values()) and static and not held) + if success: + failure = None + detail = "Bread is on the plate, butter is in the box, and the lid is closed." + else: + failure = ("bread" if not vals["bread_on_plate"] else "butter" if not vals["butter_in_box"] else + "lid_open" if not vals["lid_closed"] else "held" if held else "not_static") + parts = [] + if not vals["bread_on_plate"]: + p = envs.obj_pos(self.env, "bread_1") + rel = p[:2] - np.asarray(inst["plate_xy"]) + parts.append("The bread is still held." if self.held("bread_1") else + f"The bread is not on the plate: {_fb(rel[0])} and {_lr(rel[1])} of the plate's centre.") + if not vals["butter_in_box"]: + p = envs.obj_pos(self.env, "butter_1") + rel = p[:2] - np.asarray(inst["box_xy"]) + parts.append("The butter is still held." if self.held("butter_1") else + f"The butter is not in the box: {_fb(rel[0])} and {_lr(rel[1])} of the box's centre.") + if not vals["lid_closed"]: + parts.append(f"The lid is not closed (open {self.lid_deg():.0f} degrees). It had been closed " + f"{self.closes_done} time(s) in this attempt; it did not stay shut on its own.") + if held: + parts.append(f"Still held: {', '.join(held)}.") + if not static and all(vals.values()): + parts.append("Something was still moving.") + detail = " ".join(parts) + return dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, + lid_final_deg=round(self.lid_deg(), 1), lid_open_max=round(self.mon["lid_open_max"], 1), + closes_done=self.closes_done, active_latch=round(self.active_latch, 4), + events=list(self.mon["events"]), detail=detail) + + # ------------------------------------------------------------ execution + scripted policies + def execute(self, inst, params): + self.open_lid() + if not self.take_bread(): + return + self.close_lid(dwell=params.get("dwell1", False)) + self.open_lid() + if not self.put_butter(): + return + self.close_lid(dwell=params.get("dwell2", False)) + if params.get("check", False): + # look back before finishing: wait long enough (same order as the final settle window) for an + # under-latched close to reveal itself, then fix it with a firm dwell close if it did -- a genuine + # same-attempt recovery, not just a cross-attempt change of technique. + n = 0 + while n < SETTLE_MIN and self.lid_closed(): + self.sk.hold(10) + n += 10 + if not self.lid_closed(): + self.open_lid() + self.close_lid(dwell=True) + self.sk.hold(5) + + def default_params(self, inst): + return dict(dwell1=False, dwell2=False, check=False) + + def oracle_params(self, inst): + return dict(dwell1=False, dwell2=True, check=False) + + def adapt_params(self, inst, history): + """From attempt 2 on (if attempt 1's own same-attempt check-and-repair somehow still fell short): close + every time with a firm dwell from the start, and keep checking before finishing.""" + return dict(dwell1=True, dwell2=True, check=True) + + def blind_params(self, inst, attempt, rng): + return dict(dwell1=False, dwell2=bool(rng.random() < 0.5), check=False) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + # attempt 1: naive technique plus a final look-back-and-repair (genuine same-attempt recovery); + # only if that still were not enough would later attempts switch technique from the start. + params = (dict(self.default_params(inst), check=True) if a == 0 + else self.adapt_params(inst, history)) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/lh_tidy_stack.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/lh_tidy_stack.py new file mode 100644 index 0000000000000000000000000000000000000000..7eb80b6f3a418bf965b10bad15f99797241128a5 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/lh_tidy_stack.py @@ -0,0 +1,1260 @@ +"""LH lh_tidy_stack v2 (2026-10-16): tidy the table -- stack the four storage boxes (red, green, blue, yellow; alike, +6 x 6 x 5 cm) into one pile on a grey mat, in any order, then stand the cup on top. In 18 of every 20 instances one box +(random colour) is an empty, soft carton: it carries one thing, but as soon as a second thing comes to rest above it, +it gives way -- standing it folds sideways, lying on a side face it is crushed flat -- and everything above it slides +off the pile: the stage that made the pile two higher destroys the stage before it. + +Family: long-horizon self-disturbance ("state_restoration"): the later stages' ordinary action (putting the next box on) +undoes earlier ones; the agent has to see which box gave way, take it out of the pile and rebuild with it on top (within +an attempt) or remember its colour (across attempts). The cheapest explanation of a toppled pile ("I did not centre the +box", "I let go too high") is wrong: perfectly centred boxes let go 5 mm above the pile topple it just the same +(control naive_centred). + +v1 -> v2 (Sonnet 5.5 pilot np3_lh_tidy_stack, seeds 3000 / 3002 / 3003, k=3; logs measured by the coordinator and +replayed here): in s3002 attempt 2 boxes that had fallen on their sides were restacked lying (a lying box looks the +same: they are nearly cubes); the soft box lay on its side at level 2 under two boxes and the cup, and the v1 law, which +measured the load along the box axis only, saw -0.06 N and never fired -> judged a success. Sonnet also presses what it +puts down 0.5-1.5 cm below contact (its own logs: the gripper stops 0.6-1.5 cm above the commanded release height), and +in s3003 a cup pressed onto the soft box on top -- where it belongs -- crushed it under one item (v1: 2.45 N). v2: + (1) the load is measured along the world vertical, whichever face the carton rests on (`vertical_loads`: the downward + push on its upper side, limited by the support under it); + (2) a carton lying on a side face (seam vertical) cannot fold under gravity, so it is crushed instead: both halves + flatten towards the face they rest on, the upper half by 70 % and the lower by 30 % (runtime geom sizes + + envs.refit_bounds), the top becomes a 2-3 cm step and what is on it tips off; + (3) only what rests on the carton counts, at most with its own weight (+0.3 N for impacts): something the robot still + holds, the robot pushing down through an item it has just let go of, and the fingers pressing the held carton + itself onto something do not count; the robot's own fingers / hand pushing on its top do (a hard press may crush + it: the closed gripper 3 mm onto its top does; logged as cause "press", not counted as the trap unless it costs a + stage); + (4) items weigh 200 g (box and cup; v1 180 / 160 g) and f_crit = 3.45 N: one item 1.96 N, two 3.92 N; + (5) the rigid boxes' joints are stiffer (20 Nm/rad, stiff limit; at 3 Nm/rad Sonnet's cup press on a 4-high pile bent + every box ~4 deg and the pile leaned 10 deg in the replay); after a fold the carton straightens along a rest + shape that moves back to straight over 1.5 s (released at once, a stiff spring flipped it onto its side); + (6) stacking tolerance 3 cm instead of 2.5 (a correctly stacked oracle_noise pile failed at 2.51 cm). +v1 code and results: scratchpad lh_tidy_stack_v1.py, results/_old/lh_tidy_stack_v1/. + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a grey mat (13 x 13 cm, visual only), centre x in [-0.11, -0.05], |y| <= 5 cm; + * four storage boxes (6 x 6 x 5 cm, bright red / green / blue / yellow with a darker lid line, 200 g; friction 0.5) + 15, 18.5, 22 and 25.5 cm (+-1 cm) from the mat centre, at random angles 30-150 deg from forward on its left and right, + yaw +-17 deg, colours shuffled; + * a dark teal cup (5 cm wide, 7 cm tall, 200 g) on the robot's side of the mat, 23-26 cm away. + +Hidden variable: which box is the soft carton (60 g; mass is not observable). Instances come in balanced blocks of 20 +consecutive seeds ((seed x 7) mod 20 = k): k >= 18 benign (no soft box); otherwise the soft box is the one at rank +k mod 4 of the distance to the mat (0 = nearest = the bottom of a nearest-first pile, 3 = the top): 5 / 5 / 4 / 4. +A nearest-first stacker therefore meets it below the top in 14 of 20 instances. + +Mechanism (physics; nothing is teleported). Every box is built alike: a lower half (the root body) and an upper half +joined by a ball joint at mid-height (the seam is invisible). In the three rigid boxes the joint is locked (range +0.003 rad, stiffness 3 Nm/rad). The soft carton follows a load law (`_law_step`, every MuJoCo substep): its compressive +load (above, low-passed with 0.4 s) is compared with f_crit (instance key "f_crit": the fragility knob). Below it the +joint keeps 3 Nm/rad (one box 1.3 cm off-centre tilts it < 1 deg: looks like the rigid boxes). Above it: + * standing or upside down (seam horizontal): the joint stiffness drops to 0.03 Nm/rad -- a column with m g h ~ 0.27 + Nm/rad on it is unstable, centred or not -- and its rest shape bends 12 deg towards a per-instance side: the upper + half folds sideways (38-54 deg measured, joint limit 54 deg) and what is on it slides off; + * lying on a side face (seam vertical): crushed as above within ~0.1 s. +Unloaded (< 0.5 N) for 0.3 s it recovers over ~1.5 s (still visibly bent / flattened in the images of the next one or +two commands). One item on it is carried (a box let go 4 cm above adds < 0.5 N to the filtered load), two are not. So +the pile survives only with the soft box on top (carrying just the cup): soft at level 1 -> it gives way when box 3 +lands (boxes 2 and 3 fall), level 2 -> when box 4 lands, level 3 -> when the cup lands (box 4 and the cup fall; standing, +the cup ends on its side, which a top-down gripper cannot undo, so that attempt cannot be repaired). Measured (v2, naive +without rebuilding, the 14 trap instances of seeds 1000-1019): standing 14/14 folded at exactly that stage, the soft +box stayed upright in the pile 14/14 (fold 37-55 deg), the cup fell 4/4 at level 3; lying (control naive_lying: the +soft box starts on a side face and is stacked lying) crushed at exactly that stage in every trap instance. + +Why not the linear spring of the brief (a ball joint with one fixed stiffness k): the load that k must carry (the cup) +and the load that must topple it (one more box) differ by a factor of ~2-3, and an inverted pendulum close to its +critical load amplifies placement offsets (tilt = W e / (k - m g h)); measured (results/lh_tidy_stack/linear.json, +instance key law="linear"): no k gives both a soft box that carries the cup on top without sagging and a pile that +topples however carefully it is centred (k <= 0.25 Nm/rad: the correct pile fails 5-10/10; k = 0.5: a centred +level-3 soft box carries box + cup, 2/2). A load threshold (walls that +hold until they buckle) keeps the soft box looking and behaving rigid until the second item, independent of centring. + +Success predicate (from the instruction): all four boxes in one chain -- the bottom one on the mat (lowest point <= 8 mm +above the table, centre within 3.5 cm of the mat centre in x and y: its footprint on the 13 cm mat), each next one +resting on the previous (its lowest point within 1 cm of the top of the box below, centres within 3 cm), every box +flat (some face within 10 deg of horizontal: a fallen box cannot be stood up again by a vertical gripper, so a box on +its side counts), not bent (kink <= 10 deg) and not crushed (<= 15 %) --; the cup upright (<= 10 deg) on the top box +(bottom within 1 cm, centre within 3 cm); nothing held, the gripper not touching anything, the scene static (< 3 mm +in 1 s). Tolerance: 3 cm = the box's half width, i.e. the upper box's centre of mass is over the lower box's top face +(physically resting on it; the static check rejects anything that does not stay). Sonnet's measured placement error is +0.4-1.3 cm, so two placements differ by up to 2.6 cm plus a few mm of landing drift (v2: the 2.5 cm of v1 failed one +correctly stacked oracle_noise pile, seed 1008, at 2.51 cm). + +Event monitor (server log only; F1 gives the agent only success / failure): stage predicates red / green / blue / +yellow (box in the pile) and cup (cup on a complete pile), debounced over 0.5 s: achieved / lost (cause buckle / robot +/ picked_up / other) / restored; `buckle` (= trap fired: load, the robot's share of it, fold or crush, lying, level, +items on it), `collapse` (a buckle that cost a stage). Outcome: success, failure (none / held / touching / collapsed / +regressed / not_stacked / cup_fallen / cup_not_on_top / not_static), trap_fired, recovered_in_attempt, n_buckles, +n_collapses, buckle_how, max_kink_deg, max_crush, detail (F2). The law's state rides along in task.mon["law"]; a +crushed carton's geom sizes are restored at every reset. + +Protocol: cross (reset to the same instance before every attempt), k = 3. +""" +import mujoco +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +TZ = envs.TABLE_Z +G = 9.81 +COLOURS = ["red", "green", "blue", "yellow"] +BOXES = [f"box_{c}_1" for c in COLOURS] +COL = dict(zip(BOXES, COLOURS)) +CUP, MAT = "cup_1", "mat_1" +RGBA = {"red": (0.80, 0.16, 0.13, 1.0), "green": (0.17, 0.58, 0.25, 1.0), "blue": (0.16, 0.34, 0.80, 1.0), + "yellow": (0.90, 0.74, 0.14, 1.0)} +CUP_RGBA = (0.10, 0.45, 0.50, 1.0) # dark teal ceramic, darker inside +CUP_INSIDE = (0.20, 0.20, 0.19, 1.0) +MAT_RGBA = (0.45, 0.45, 0.47, 1.0) + +# ---------------------------------------------------------------- boxes (all four built alike: base + upper part) +HX, HY, H = 0.030, 0.030, 0.050 # 6 x 6 x 5 cm (the gripper opens 7.9 cm) +HB = 0.025 # base part height = height of the seam (ball joint) above the bottom: mid-height, so the upper +# half can fold ~56 deg before its edge reaches the surface below +HU = H - HB +BOX_MASS = 0.20 # a filled storage box (v1: 0.18) +SOFT_MASS = 0.06 # the empty carton (mass is not observable by the agent) +BOX_MU = 0.5 +CONTACT = 'solimp="0.95 0.99 0.001" solref="0.01 1"' +# soft-carton law (see SoftLaw): stiff until the compressive load through its walls exceeds F_CRIT, then soft +K_HI = 3.0 # Nm/rad: the intact soft carton (one box 1.3 cm off-centre tilts it ~0.5 deg; a cup pressed onto it +# bends it ~4 deg) +K_RIGID = 20.0 # Nm/rad + a stiff joint limit: the rigid boxes (at 3 Nm/rad a cup pressed onto a 4-high pile bent every +# box 4 deg and the pile leaned 10 deg -- replay of pilot s3003 on v2; at 20 for the soft carton too +# its folds flipped it onto its side 4/14 times) +K_LO = 0.03 # Nm/rad: buckled (one box on it destabilises it: m g h ~ 0.12 Nm/rad) +DAMP = 0.01 +F_CRIT = 3.45 # N, vertical load from above (resting things + whatever the robot pushes or holds onto it): one +# item weighs 1.96 N and a held item pressed onto the carton adds <= ~0.9 N before it slips in the +# fingers (measured, t10_press); two items weigh 3.92 N (v1: 2.45 N with 1.77 / 1.57 N items) +F_REL = 0.5 # N: unloaded below this ... +REL_T = 0.3 # ... for this long -> it springs back +TAU_F = 0.4 # s: low-pass of the load (impacts of a box let go 1-4 cm above do not count) +K_RISE = 1.5 # s: the folded carton straightens along a reference that moves back to straight in this time +BEND_REF = np.radians(12.0) # reference bend of the buckled carton (the weak side; direction per instance) +RANGE_SOFT, RANGE_RIGID = 0.95, 0.003 # rad: kink limit (54 deg) of the soft carton; the rigid boxes are locked +# v2: a carton lying on a side face (its seam vertical) cannot fold under gravity; it is crushed instead: both halves +# flatten towards the surface below, the upper half much more, so the top becomes a 2-3 cm step and what is on it +# tips off (geom sizes changed at runtime + envs.refit_bounds) +CRUSH_ALPHA = (0.30, 0.70) # fraction of the height lost by the base half / the upper half when fully crushed +CRUSH_TAU = (0.08, 0.7) # s: crushing / recovering +FOLD_MIN_UP = 0.7 # |seam normal . vertical| above this: the fold (upright or upside down); below: the crush + +# ---------------------------------------------------------------- cup +CUP_R, CUP_H, CUP_MASS = 0.025, 0.070, 0.20 # v1: 0.16 + +# ---------------------------------------------------------------- mat and layout +MAT_HALF = 0.065 # 13 x 13 cm +MAT_X, MAT_Y = (-0.11, -0.05), (-0.05, 0.05) +BOX_D = (0.15, 0.185, 0.22, 0.255) # distances of the four boxes from the mat centre (+- jitter) +BOX_X = (-0.33, 0.07) # world x range of the box positions (reach) +BOX_YMAX = 0.30 +BOX_YAW = 0.30 +P_BENIGN = 0.10 # 2 of every 20 consecutive seeds: no soft box + +# ---------------------------------------------------------------- predicates +TILT_OK = np.radians(10.0) +KINK_OK = np.radians(10.0) +ON_MAT = 0.035 # bottom box centre within 3.5 cm of the mat centre (x and y): its footprint is on the 13 cm mat +STACK_XY = 0.030 # centre of a box within 3 cm (= the half width) of the centre of the box below: its centre of +# mass is over the lower box's top face (v2; 2.5 cm judged a resting box 2.51 cm off as not stacked) +STACK_Z = 0.010 +CUP_XY = 0.030 +DEBOUNCE = 10 # control steps (0.5 s) + +# ---------------------------------------------------------------- scripted motion +Z_CARRY = 0.18 +NAIVE_ERR = (0.004, 0.013) # Sonnet's placement error 0.4-1.3 cm (random direction) +NAIVE_GAP = (0.010, 0.040) # Sonnet lets go 1-4 cm above the surface +NAIVE_BIAS = (0.0, 0.020) # forward bias of the first box on the mat (oblique camera) + + +def box_xml(name, rgba): + """storage box: base part (root body, 1.6 cm) + upper part (child body) on a ball joint at the seam. Rigid boxes + get a ~0 kink range at reset; the soft carton a 31.5 deg range and the load-dependent stiffness of SoftLaw. + Inertials are replaced per instance (mass).""" + mb, mu = BOX_MASS * HB / H, BOX_MASS * HU / H + zb = -H / 2 + HB / 2 + dark = [0.72 * c for c in rgba[:3]] + [1.0] + g = [f' ', + f' ', + f' ', + f' ', + f' ', + f' ', + f' ', + f' ', + # lid line (visual only): a darker band 8 mm below the top, on all four boxes + f' ', + ' '] + return _wrap(name, "\n".join(g), H / 2, float(np.hypot(HX, HY))) + + +def cup_xml(name): + """open cup, 5 cm wide, 7 cm tall: 12 wall boxes + an octagonal base of two boxes (box contacts; a light MuJoCo + cylinder creeps on a flat surface, lh_nudge_row). Visual: a smooth cylinder with a dark inside.""" + r, h = CUP_R, CUP_H + nseg, wt, bt = 12, 0.004, 0.006 + g = [f' '] + s = r * np.sin(np.pi / nseg) + 0.0008 + rc = r * np.cos(np.pi / nseg) - wt / 2 + for k in range(nseg): + a = 2 * np.pi * k / nseg + q = [np.cos(a / 2), 0, 0, np.sin(a / 2)] + g.append(f' ') + a0 = r * 0.70 + for k, ang in enumerate((0.0, np.pi / 4)): + q = [np.cos(ang / 2), 0, 0, np.sin(ang / 2)] + g.append(f' ') + g.append(f' ') + g.append(f' ') + return _wrap(name, "\n".join(g), h / 2, r) + + +def mat_xml(name): + g = (f' ') + return _wrap(name, g, 0.0005, MAT_HALF * 1.42) + + +def free_adr(env, name): + """(qpos, dof) address of the object's FREE joint. envs.free_joint_addr takes joints[0], which for an object with a + jointed child body is the child's joint (robosuite lists the subtree's joints before the free joint it appends).""" + m = env.sim.model + for jn in env.objects_dict[name].joints: + j = m.joint_name2id(jn) + if int(m.jnt_type[j]) == 0: + return int(m.jnt_qposadr[j]), int(m.jnt_dofadr[j]) + raise KeyError(name) + + +def place(env, name, xy, yaw=0.0, surface_z=TZ, clearance=0.0005, tilt=None): + """teleport upright (yaw about z; `tilt` rad about the object's own x axis first, e.g. pi/2 = lying on a side + face -- controls only), lowest collision point `clearance` above surface_z (reset only)""" + qa, da = free_adr(env, name) + d = env.sim.data + d.qpos[qa:qa + 3] = [xy[0], xy[1], surface_z + 0.3] + q = np.array([np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)]) + if tilt: + w1, z1 = q[0], q[3] + c, s_ = np.cos(tilt / 2), np.sin(tilt / 2) + q = np.array([w1 * c, w1 * s_, z1 * s_, z1 * c]) # q_yaw * q_x(tilt) + d.qpos[qa + 3:qa + 7] = q + d.qvel[da:da + 6] = 0.0 + env.sim.forward() + d.qpos[qa + 2] -= envs.obj_min_z(env, name) - (surface_z + clearance) + env.sim.forward() + + +def _fb(v): + return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}" + + +def _lr(v): + return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}" + + +def _wrap_q(a, period): + """wrap an angle to [-period/2, period/2)""" + return float((a + period / 2) % period - period / 2) + + +class StackSkills(Skills): + """Skills that feed the task's per-step monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class TidyStack(LFFTask): + name = "lh_tidy_stack" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Restore", "Plan") + protocol = "cross" + max_attempts = 3 + # careful: 5 pick-and-places x ~8 commands (40) + a collapse: unstack 1-2 boxes (~16) and rebuild 3-4 (~32) + # + looking / small corrections (~30), with some margin + agent_max_steps = 150 + instruction = ("Tidy up the table: stack the four storage boxes (red, green, blue, yellow) into a single pile on the " + "grey mat, in any order you like, and then put the cup upright on top of the pile. At the end each " + "box must rest flat on the box below it (the bottom one on the mat), the cup must stand on the top " + "box, and the gripper must be open and clear of everything.") + instruction_indirect = ("Clean up the table: pile the four coloured boxes on top of each other on the dark grey " + "square, in whatever order, and finish by standing the teal mug on top of the pile. In the " + "end every box has to sit flat on the one below it (the lowest on the grey square), the mug " + "has to stand on the top box, and the gripper must be open and away from everything.") + agent_object_names = ["storage boxes (red, green, blue, yellow)", "grey mat", "cup"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs = [] + for i, (c, b) in enumerate(zip(COLOURS, BOXES)): + cat = register_generated(f"LffLtsBox{c.capitalize()}", box_xml(f"lff_lts_box_{c}", RGBA[c])) + objs.append((b, cat, f"box{i}_region", (-0.30 + 0.13 * i, 0.28, -0.29 + 0.13 * i, 0.29))) + cat = register_generated("LffLtsCup", cup_xml("lff_lts_cup")) + objs.append((CUP, cat, "cup_region", (-0.30, -0.29, -0.29, -0.28))) + mat = register_generated("LffLtsMat", mat_xml("lff_lts_mat"), free=False) + fx = [(MAT, mat, "mat_region", (0.0, -0.29, 0.01, -0.28))] + return write_bddl(self.name, "Stack the four boxes on the grey mat and put the cup on top", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.mat_bid = m.body_name2id(self.env.fixtures_dict[MAT].root_body) + self.jid, self.base_bid, self.upper_bid, self.base_gid, self.upper_gid = {}, {}, {}, {}, {} + for b in BOXES: + for g in envs.obj_geom_ids(self.env, b): + n = m.geom_id2name(g) + if n.endswith("_upper"): + self.upper_gid[b] = g + elif n.endswith("_base"): + self.base_gid[b] = g + self.upper_bid[b] = int(m.geom_bodyid[self.upper_gid[b]]) + self.base_bid[b] = int(m.geom_bodyid[self.base_gid[b]]) + j = next(m.joint_name2id(jn) for jn in self.env.objects_dict[b].joints if jn.endswith("_kink")) + self.jid[b] = j + # every geom of each half (collision and visual) with its compiled size / pos: the crush rescales them + self.half_geoms = {} + for b in BOXES: + hg = [] + for bid in (self.base_bid[b], self.upper_bid[b]): + gs = [g for g in range(int(m.body_geomadr[bid]), int(m.body_geomadr[bid] + m.body_geomnum[bid])) + if int(m.geom_type[g]) == 6] + hg.append((bid, gs, m.geom_size[gs].copy(), m.geom_pos[gs].copy())) + self.half_geoms[b] = hg + self.cup_gids = list(envs.obj_geom_ids(self.env, CUP)) + self.obj_bodies = {b: [self.base_bid[b], self.upper_bid[b]] for b in BOXES} + self.obj_bodies[CUP] = [envs.body_id(self.env, CUP)] + # per-geom lookup: owner index 0-3 = boxes, 4 = cup, -1 other; robot part 1 = finger, 2 = hand / arm + self.owner = np.full(m.ngeom, -1, int) + for i, b in enumerate(BOXES): + self.owner[[self.base_gid[b], self.upper_gid[b]]] = i + self.owner[self.cup_gids] = 4 + self.part = np.zeros(m.ngeom, int) + for g in envs.robot_geom_ids(self.env): + n = m.geom_id2name(g) or "" + self.part[g] = 1 if "finger" in n else 2 + self.inst = None + self.law = None + self.mon = None + self.sk = None + self._sub_rob = {} + self._held = set() # owner indices (0-3 boxes, 4 cup) held by the gripper, refreshed every control step + self._rest_cap = np.inf # upper bound of the resting load on the soft carton, refreshed every control step + sim = self.env.sim + if not getattr(sim, "_lts_wrapped", False): + orig = sim.step + + def step(*a, **k): + t = getattr(sim, "_lts_task", None) + if t is not None and t.law is not None: + t._law_step() + orig(*a, **k) + if t is not None and t.mon is not None: + t._substep() + sim.step = step + sim._lts_wrapped = True + sim._lts_task = self + + # ------------------------------------------------------------ instances + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + mx, my = float(rng.uniform(*MAT_X)), float(rng.uniform(*MAT_Y)) + ca = np.pi + float(rng.uniform(-0.5, 0.5)) # the cup stands on the robot's side of the mat, 23-26 cm away + cd = float(rng.uniform(0.23, 0.26)) + cup = [mx + cd * np.cos(ca), my + cd * np.sin(ca)] + for _ in range(500): + ds = np.array(BOX_D) + rng.uniform(-0.01, 0.01, 4) + ang = rng.uniform(np.radians(30), np.radians(150), 4) * rng.choice([-1.0, 1.0], 4) + pos = np.stack([mx + ds * np.cos(ang), my + ds * np.sin(ang)], 1) + if not (np.all((pos[:, 0] >= BOX_X[0]) & (pos[:, 0] <= BOX_X[1])) and np.all(np.abs(pos[:, 1]) <= BOX_YMAX)): + continue + dd = np.linalg.norm(pos[:, None] - pos[None], axis=2) + np.eye(4) + if dd.min() < 0.12 or np.linalg.norm(pos - np.asarray(cup), axis=1).min() < 0.14: + continue + break + else: + raise RuntimeError("layout") + perm = rng.permutation(4) + start = {BOXES[i]: [float(v) for v in pos[perm[i]]] for i in range(4)} + yaw = {b: float(rng.uniform(-BOX_YAW, BOX_YAW)) for b in BOXES} + mat = np.array([mx, my]) + near = sorted(BOXES, key=lambda b: float(np.linalg.norm(np.asarray(start[b]) - mat))) + # balanced blocks of 20 consecutive seeds: 2 benign (no soft box); else the soft carton is the box at rank + # r = 0..3 (0 = nearest the mat, i.e. the bottom of a nearest-first pile; 3 = the top): 5 / 5 / 4 / 4 + k = (int(seed) * 7) % 20 + benign = k >= round(20 * (1 - P_BENIGN)) + rank = None if benign else k % 4 + soft = None if benign else near[rank] + return dict(seed=int(seed), mat=[mx, my], cup=cup, start=start, yaw=yaw, cup_yaw=float(rng.uniform(-np.pi, np.pi)), + soft=soft, soft_colour=COL[soft] if soft else None, benign=bool(benign), + soft_rank_nearest=rank, nearest_order=[COL[b] for b in near], + buckle_dir=float(np.pi / 2 if rng.random() < 0.5 else -np.pi / 2), + f_crit=F_CRIT, naive_gap=float(rng.uniform(*NAIVE_GAP)), naive_bias=float(rng.uniform(*NAIVE_BIAS))) + + def apply_instance(self, inst): + self.inst = inst + m, d = self.env.sim.model, self.env.sim.data + m.body_pos[self.mat_bid] = [inst["mat"][0], inst["mat"][1], TZ + 0.0005] + for b in BOXES: + j = self.jid[b] + soft = b == inst["soft"] + M = SOFT_MASS if soft else BOX_MASS + for bid, frac, h in ((self.base_bid[b], HB / H, HB), (self.upper_bid[b], HU / H, HU)): + mm = M * frac + m.body_mass[bid] = mm + m.body_inertia[bid] = [mm * (4 * HY * HY + h * h) / 12, mm * (4 * HX * HX + h * h) / 12, + mm * (4 * HX * HX + 4 * HY * HY) / 12] + m.jnt_range[j] = [0.0, RANGE_SOFT if soft else RANGE_RIGID] + m.jnt_solref[j] = [0.02, 1.0] if soft else [0.004, 1.0] # rigid boxes: a stiff limit + m.jnt_stiffness[j] = K_HI if soft else K_RIGID + qa, da = int(m.jnt_qposadr[j]), int(m.jnt_dofadr[j]) + m.qpos_spring[qa:qa + 4] = [1.0, 0.0, 0.0, 0.0] + d.qpos[qa:qa + 4] = [1.0, 0.0, 0.0, 0.0] + d.qvel[da:da + 3] = 0.0 + self._set_crush(b, 0.0, 2, -1.0) # undo a crush left over from the previous attempt + place(self.env, b, inst["start"][b], yaw=inst["yaw"][b], tilt=inst.get("lying", {}).get(COL[b])) + place(self.env, CUP, inst["cup"], yaw=inst["cup_yaw"]) + self.law = None + if inst["soft"]: + self.law = dict(box=inst["soft"], f=0.0, fmax=0.0, buckled=False, n=0, rel_t=0.0, t=0.0, buckles=[], + f_crit=float(inst.get("f_crit", F_CRIT)), dir=float(inst["buckle_dir"]), + mode=str(inst.get("law", "threshold")), how=None, crush=0.0, crush_set=0.0, + crush_axis=2, crush_sign=-1.0, f_rest=0.0, f_robot=0.0) + if self.law["mode"] == "linear": # control only: the brief's fixed-stiffness spring (no load threshold) + m.jnt_stiffness[self.jid[inst["soft"]]] = float(inst["k_lin"]) + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.law = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = StackSkills(self.env, self, recorder=recorder) + self._sub_rob = {} + self._held = set() + self._rest_cap = np.inf + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ soft-carton law + def _part_axial(self, gid, axis): + """sum of contact forces on geom gid (from any other geom), projected on `axis` (world)""" + m, d = self.env.sim.model, self.env.sim.data + n = d.ncon + if not n: + return 0.0 + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + idx = np.nonzero((g1 == gid) | (g2 == gid))[0] + tot = 0.0 + f6 = np.zeros(6) + for i in idx: + mujoco.mj_contactForce(m._model, d._data, int(i), f6) + fw = d.contact[int(i)].frame.reshape(3, 3).T @ f6[:3] # force on geom2, world frame + tot += float(fw @ axis) * (-1.0 if g1[i] == gid else 1.0) + return tot + + def vertical_loads(self, b): + """vertical contact forces on box b (N), whichever face it rests on: (resting, robot, held, support). + resting = downward push on its upper side (contact point above its centre) from things resting on it; + robot = the same from the robot's own fingers / hand pushing on it (not counted while the robot holds b + itself); held = the same from something the robot holds (pressing it down onto b); support = upward push on + its lower side. Its two halves never touch (parent and child), so only real contacts count.""" + m, d = self.env.sim.model, self.env.sim.data + n = d.ncon + if not n: + return 0.0, 0.0, 0.0, 0.0 + gb, gu = self.base_gid[b], self.upper_gid[b] + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + idx = np.nonzero((g1 == gb) | (g1 == gu) | (g2 == gb) | (g2 == gu))[0] + if not len(idx): + return 0.0, 0.0, 0.0, 0.0 + cz = float(d.xpos[self.base_bid[b]][2]) # the root body sits at the box's centre + held = self._held + b_held = BOXES.index(b) in held + rest = robot = via = sup = 0.0 + f6 = np.zeros(6) + for i in idx: + c = d.contact[int(i)] + mujoco.mj_contactForce(m._model, d._data, int(i), f6) + fz = float(c.frame.reshape(3, 3)[:, 2] @ f6[:3]) # world z of the force on geom2 + mine1 = g1[i] in (gb, gu) + fz = -fz if mine1 else fz # force on box b + other = int(g2[i] if mine1 else g1[i]) + pz = float(c.pos[2]) + if pz > cz + 0.004 and fz < 0.0: + o = self.owner[other] + if self.part[other] > 0: + if not b_held: + robot -= fz + elif o >= 0 and o in held: + via -= fz + else: + rest -= fz + elif pz < cz - 0.004 and fz > 0.0: + sup += fz + # what rests on it pushes at most with its own weight: the robot pressing down through an item it has let go + # of (Sonnet releases with the cup pushed up against the hand, pilot s3003) is not a resting load + rest = min(rest, self._rest_cap) + return rest, robot, via, sup + + def compression(self, b): + """compressive force (N) on the carton, (total, resting): the downward push on its upper side from things + resting on it plus the robot's fingers / hand pushing directly on it, limited by the support under it -- + along the world vertical, whichever face it rests on (v1 measured it along the box axis only: a carton lying + on its side never buckled). Something the robot still holds does not count: Sonnet presses what it puts down + 0.5-1.5 cm below contact (pilot), which must not crush a carton that will carry the item once let go.""" + rest, robot, via, sup = self.vertical_loads(b) + return float(min(rest + robot, sup)), float(min(rest, sup)) + + def _law_step(self): + """per MuJoCo substep: low-pass the compressive load; above f_crit the carton gives way -- standing or upside + down it folds (its kink joint loses its stiffness, its rest shape bends towards its weak side and the load + topples it), lying on a side face it is crushed (both halves flatten, the upper half more); unloaded for + REL_T it slowly recovers its shape""" + law = self.law + b = law["box"] + m = self.env.sim.model + dt = float(m.opt.timestep) + tot, rest = self.compression(b) + law["f"] += (tot - law["f"]) * dt / TAU_F + law["f_rest"] += (rest - law["f_rest"]) * dt / TAU_F + law["fmax"] = max(law["fmax"], law["f"]) + j = self.jid[b] + qa = int(m.jnt_qposadr[j]) + if law["mode"] == "linear": # control: constant stiffness; a "buckle" = the kink passes 15 deg (re-arms < 5) + kk = self.kink(b) + if not law["buckled"] and kk > np.radians(15.0): + law["buckled"] = True + law["n"] += 1 + law["buckles"].append(dict(t=round(law["t"], 3), load_N=round(law["f"], 2))) + self._on_buckle() + elif law["buckled"] and kk < np.radians(5.0): + law["buckled"] = False + law["t"] += dt + return + if not law["buckled"]: + if law["f"] > law["f_crit"]: + law["buckled"] = True + law["n"] += 1 + law["rel_t"] = 0.0 + R = self.env.sim.data.xmat[self.base_bid[b]].reshape(3, 3) + law["unbend_q0"] = None + if abs(R[2, 2]) >= FOLD_MIN_UP: # seam horizontal: fold + law["how"] = "fold" + u = R.T @ np.array([np.cos(law["dir"]), np.sin(law["dir"]), 0.0]) + ax = np.array([-u[1], u[0], 0.0]) + ax /= max(np.linalg.norm(ax), 1e-9) + m.qpos_spring[qa:qa + 4] = [np.cos(BEND_REF / 2), *(np.sin(BEND_REF / 2) * ax)] + else: # seam vertical (lying on a side face): crush towards the face it rests on + law["how"] = "crush" + k = int(np.argmax(np.abs(R[2, :2]))) + law["crush_axis"] = k + law["crush_sign"] = -float(np.sign(R[2, k]) or 1.0) # local direction of "down" along axis k + # cause: "load" = what rests on it is enough by itself (>= 60 % of f_crit, i.e. more than one item); + # "press" = the robot's own push made the difference (a hard press with the gripper) + cause = "load" if law["f_rest"] >= 0.6 * law["f_crit"] else "press" + law["buckles"].append(dict(t=round(law["t"], 3), load_N=round(law["f"], 2), how=law["how"], + resting_N=round(law["f_rest"], 2), cause=cause)) + self._on_buckle() + elif law["f"] < F_REL: + law["rel_t"] += dt + if law["rel_t"] > REL_T: + law["buckled"] = False + # straighten smoothly: the rest shape starts at the current bend and moves back to straight over + # K_RISE (a stiff spring released at once from a 40-50 deg bend flips the light carton over) + q0 = np.array(self.env.sim.data.qpos[qa:qa + 4], float) + q0 = q0 / max(np.linalg.norm(q0), 1e-9) * (1.0 if q0[0] >= 0 else -1.0) + law["unbend_q0"], law["unbend_s"] = q0.tolist(), 0.0 + m.qpos_spring[qa:qa + 4] = q0 + else: + law["rel_t"] = 0.0 + k = float(m.jnt_stiffness[j]) + if law["buckled"] and law["how"] == "fold": + m.jnt_stiffness[j] = k + (K_LO - k) * min(1.0, dt / 0.02) + else: + m.jnt_stiffness[j] = K_HI + if law.get("unbend_q0") is not None: + law["unbend_s"] = min(1.0, law["unbend_s"] + dt / K_RISE) + q = (1.0 - law["unbend_s"]) * np.asarray(law["unbend_q0"]) + law["unbend_s"] * np.array([1.0, 0, 0, 0]) + m.qpos_spring[qa:qa + 4] = q / np.linalg.norm(q) + if law["unbend_s"] >= 1.0: + law["unbend_q0"] = None + target = 1.0 if (law["buckled"] and law["how"] == "crush") else 0.0 + if target or law["crush"] > 0.0: + tau = CRUSH_TAU[0] if target else CRUSH_TAU[1] + law["crush"] += (target - law["crush"]) * min(1.0, dt / tau) + if not target and law["crush"] < 0.002: + law["crush"] = 0.0 + if abs(law["crush"] - law["crush_set"]) > 0.004 or (law["crush"] == 0.0 and law["crush_set"] > 0.0): + self._set_crush(b, law["crush"], law["crush_axis"], law["crush_sign"]) + law["crush_set"] = law["crush"] + law["t"] += dt + + def _set_crush(self, b, c, axis, sign): + """flatten box b's two halves along their local `axis` by c (0..1) x CRUSH_ALPHA, keeping the faces on the + `sign` side (the side facing down) in place; then refresh the collision bounds""" + m = self.env.sim.model + for (bid, gs, size0, pos0), alpha in zip(self.half_geoms[b], CRUSH_ALPHA): + size, pos = size0.copy(), pos0.copy() + if c > 0.0: + s0 = size0[:, axis] + s1 = s0 * (1.0 - alpha * c) + size[:, axis] = s1 + pos[:, axis] = pos0[:, axis] + sign * (s0 - s1) + m.geom_size[gs] = size + m.geom_pos[gs] = pos + envs.refit_bounds(m, [self.half_geoms[b][0][0], self.half_geoms[b][1][0]]) + + def _on_buckle(self): + mon = self.mon + if mon is None: + return + b = self.law["box"] + ch = self.pile() + on = self.items_on(b) + last = self.law["buckles"][-1] if self.law["buckles"] else {} + e = dict(event="buckle", box=COL[b], step=int(self.sk.n_steps) if self.sk else 0, + load_N=round(self.law["f"], 2), level=(ch.index(b) + 1) if b in ch else None, + items_on=[COL.get(x, "cup") for x in on], how=last.get("how"), cause=last.get("cause"), + resting_N=last.get("resting_N"), + lying=bool(abs(self.R(self.base_bid[b])[2, 2]) < FOLD_MIN_UP)) + mon["events"].append(e) + mon["buckle_steps"].append(e["step"]) + mon["pending_collapse"] = dict(step=e["step"], pile=list(ch), cup=self.cup_on_pile(ch)) + + # ------------------------------------------------------------ geometry / predicates + def R(self, bid): + return self.env.sim.data.xmat[bid].reshape(3, 3) + + def centre(self, name): + return envs.obj_pos(self.env, name) + + def flat_tilt(self, b): + """angle (rad) between world vertical and the base part's axis closest to it (a box may lie on any face)""" + R = self.R(self.base_bid[b]) + return float(np.arccos(np.clip(np.max(np.abs(R[2, :])), -1.0, 1.0))) + + def kink(self, b): + """bend of the upper part against the base part (rad)""" + zb = self.R(self.base_bid[b])[:, 2] + zu = self.R(self.upper_bid[b])[:, 2] + return float(np.arccos(np.clip(zb @ zu, -1.0, 1.0))) + + def cup_tilt(self): + return float(np.arccos(np.clip(envs.obj_upright_cos(self.env, CUP), -1.0, 1.0))) + + def held(self, name): + return self.sk is not None and self.sk.holding(name) + + def crushed(self, b): + """how far box b is crushed (0..1; only the soft carton, lying on a side face, can be)""" + law = self.law + return float(law["crush"]) if (law is not None and law["box"] == b) else 0.0 + + def flat(self, b): + return (self.flat_tilt(b) <= TILT_OK and self.kink(b) <= KINK_OK and self.crushed(b) <= 0.15 + and not self.held(b)) + + def rests_on(self, upper, lower): + cu, cl = self.centre(upper), self.centre(lower) + return (np.linalg.norm(cu[:2] - cl[:2]) <= STACK_XY + and abs(envs.obj_min_z(self.env, upper) - envs.obj_max_z(self.env, lower)) <= STACK_Z) + + def on_mat(self, b): + off = self.centre(b)[:2] - np.asarray(self.inst["mat"]) + return bool(np.all(np.abs(off) <= ON_MAT) and envs.obj_min_z(self.env, b) <= TZ + 0.008) + + def pile(self): + """the longest chain of flat boxes: the bottom one on the mat, each next resting on the previous (centres within + 2 cm, faces within 1 cm)""" + flat = [b for b in BOXES if self.flat(b)] + best = [] + for b0 in [b for b in flat if self.on_mat(b)]: + ch = [b0] + while True: + nxt = [b for b in flat if b not in ch and self.rests_on(b, ch[-1])] + if not nxt: + break + ch.append(min(nxt, key=lambda b: float(np.linalg.norm(self.centre(b)[:2] - self.centre(ch[-1])[:2])))) + if len(ch) > len(best): + best = ch + return best + + def cup_on(self, b): + c = self.centre(CUP) + return bool(self.cup_tilt() <= TILT_OK and not self.held(CUP) + and np.linalg.norm(c[:2] - self.centre(b)[:2]) <= CUP_XY + and abs(envs.obj_min_z(self.env, CUP) - envs.obj_max_z(self.env, b)) <= STACK_Z) + + def cup_on_pile(self, ch=None): + ch = self.pile() if ch is None else ch + return bool(len(ch) == len(BOXES) and self.cup_on(ch[-1])) + + def items_on(self, b): + """boxes / cup resting (directly or higher up) on box b, by height and overlap""" + cb = self.centre(b) + top = envs.obj_max_z(self.env, b) + out = [] + for x in BOXES + [CUP]: + if x == b: + continue + c = self.centre(x) + if envs.obj_min_z(self.env, x) > top - 0.015 and np.linalg.norm(c[:2] - cb[:2]) < 0.06: + out.append(x) + return out + + def stage_values(self): + ch = self.pile() + v = {COL[b]: b in ch for b in BOXES} + v["cup"] = self.cup_on_pile(ch) + return v, ch + + # ------------------------------------------------------------ monitor + def _init_monitor(self): + keys = COLOURS + ["cup"] + self.mon = dict(state={k: False for k in keys}, cand={k: 0 for k in keys}, ever={k: False for k in keys}, + lost={k: False for k in keys}, lost_cause={k: None for k in keys}, events=[], n=0, + last_robot={k: -10 ** 6 for k in keys}, buckle_steps=[], pending_collapse=None, + max_kink={COL[b]: 0.0 for b in BOXES}, max_crush={COL[b]: 0.0 for b in BOXES}, + max_height=0, n_collapses=0, + law=self.law) # the carton's law state rides along in the robot server's regression snapshots + + def _substep(self): + d = self.env.sim.data + n = d.ncon + if not n: + return + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + o1, o2 = self.owner[g1], self.owner[g2] + p1, p2 = self.part[g1], self.part[g2] + sel = ((o1 >= 0) & (p2 > 0)) | ((o2 >= 0) & (p1 > 0)) + for i in np.nonzero(sel)[0]: + o = o1[i] if o1[i] >= 0 else o2[i] + self._sub_rob[int(o)] = True + + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + mon["n"] += 1 + t = int(self.sk.n_steps) + self._held = {i for i, x in enumerate(BOXES + [CUP]) if self.held(x)} + if self.law is not None: # weight of the things (not held) on the soft carton, + 0.3 N for impacts + m = self.env.sim.model + self._rest_cap = 0.3 + G * sum(float(np.sum(m.body_mass[self.obj_bodies[x]])) + for x in self.items_on(self.law["box"]) + if (BOXES + [CUP]).index(x) not in self._held) + keys = COLOURS + ["cup"] + for i in list(self._sub_rob): + mon["last_robot"][keys[i]] = t + self._sub_rob = {} + for b in BOXES: + mon["max_kink"][COL[b]] = max(mon["max_kink"][COL[b]], round(float(np.degrees(self.kink(b))), 1)) + mon["max_crush"][COL[b]] = max(mon["max_crush"][COL[b]], round(self.crushed(b), 2)) + if mon["n"] % 2: + return + vals, ch = self.stage_values() + mon["max_height"] = max(mon["max_height"], len(ch)) + for k in keys: + raw = vals[k] + if raw == mon["state"][k]: + mon["cand"][k] = 0 + continue + mon["cand"][k] += 2 + if mon["cand"][k] < DEBOUNCE: + continue + mon["cand"][k] = 0 + mon["state"][k] = raw + t0 = t - DEBOUNCE + 1 + if raw: + restored = mon["lost"][k] + e = dict(stage=k, event="restored" if restored else "achieved", step=t0) + if restored: + e["after"] = mon["lost_cause"][k] + mon["lost"][k] = False + mon["ever"][k] = True + mon["events"].append(e) + elif mon["ever"][k]: + cause = self._cause(k, t) + mon["lost"][k] = True + mon["lost_cause"][k] = cause + mon["events"].append(dict(stage=k, event="lost", step=t0, cause=cause)) + pc = mon["pending_collapse"] + if cause == "buckle" and pc is not None and not pc.get("counted"): + pc["counted"] = True + mon["n_collapses"] += 1 + mon["events"].append(dict(event="collapse", step=t0, buckled=self.inst["soft_colour"], + pile_before=[COL[b] for b in pc["pile"]])) + + def _cause(self, k, t): + name = CUP if k == "cup" else BOXES[COLOURS.index(k)] + if self.held(name): + return "picked_up" + bs = self.mon["buckle_steps"] + if bs and t - bs[-1] <= 80: # within 4 s of a buckle + return "buckle" + if t - self.mon["last_robot"][k] <= 30: + return "robot" + return "other" + + def _finalize_monitor(self, vals): + mon = self.mon + t = int(self.sk.n_steps) + for k, raw in vals.items(): + if raw == mon["state"][k]: + continue + mon["state"][k] = raw + if raw: + restored = mon["lost"][k] + e = dict(stage=k, event="restored" if restored else "achieved", step=t, final=True) + if restored: + e["after"] = mon["lost_cause"][k] + mon["lost"][k] = False + mon["ever"][k] = True + mon["events"].append(e) + elif mon["ever"][k]: + cause = self._cause(k, t) + mon["lost"][k] = True + mon["lost_cause"][k] = cause + mon["events"].append(dict(stage=k, event="lost", step=t, cause=cause, final=True)) + + # ------------------------------------------------------------ outcome + def _touching(self): + d = self.env.sim.data + n = d.ncon + if not n: + return False + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + return bool(np.any(((self.owner[g1] >= 0) & (self.part[g2] > 0)) | ((self.owner[g2] >= 0) & (self.part[g1] > 0)))) + + def _static_pos(self): + return {x: self.centre(x).copy() for x in BOXES + [CUP]} + + def outcome(self, inst): + sk = self.sk + sk.hold(10) + p0 = self._static_pos() + touching = False + for _ in range(20): + sk.hold(1) + touching = touching or self._touching() + moved = max(float(np.linalg.norm(self.centre(x) - p0[x])) for x in p0) + static = moved < 0.003 + vals, ch = self.stage_values() + self._finalize_monitor(vals) + mon = self.mon + ev = list(mon["events"]) + held = [COL.get(x, "cup") for x in BOXES + [CUP] if self.held(x)] + success = bool(all(vals.values()) and static and not held and not touching) + buckles = [e for e in ev if e.get("event") == "buckle"] + n_reg = sum(e.get("event") == "lost" and e.get("cause") != "picked_up" for e in ev) + n_res = sum(e.get("event") == "restored" and e.get("after") != "picked_up" for e in ev) + soft = inst["soft"] + buckled_now = bool(self.law is not None and self.law["buckled"]) + cup_fallen = self.cup_tilt() > np.radians(45) + if success: + failure = "none" + elif held: + failure = "held" + elif touching and all(vals.values()): + failure = "touching" + elif not all(vals[c] for c in COLOURS): + if buckles and any(mon["ever"][c] for c in COLOURS): + failure = "collapsed" + elif any(mon["lost"][c] for c in COLOURS): + failure = "regressed" + else: + failure = "not_stacked" + elif not vals["cup"]: + failure = "cup_fallen" if cup_fallen else "cup_not_on_top" + else: + failure = "not_static" + # F2 detail (robot-centric words) + parts = [] + if success: + parts.append("All four boxes are stacked on the mat and the cup stands on top.") + else: + if ch: + parts.append("The pile on the mat is " + " / ".join(COL[b] for b in ch) + " (bottom to top).") + else: + parts.append("There is no box resting flat on the mat.") + mat = np.asarray(inst["mat"]) + for b in BOXES: + if b in ch: + continue + c = COL[b] + if self.held(b): + parts.append(f"The {c} box is still held by the gripper.") + continue + off = self.centre(b)[:2] - mat + pose = ("lies tilted" if self.flat_tilt(b) > TILT_OK else + "is crushed flat" if self.crushed(b) > 0.15 else + f"is bent ({np.degrees(self.kink(b)):.0f} degrees)" if self.kink(b) > KINK_OK else "stands") + parts.append(f"The {c} box {pose} {_fb(off[0])} and {_lr(off[1])} of the mat's centre, not in the pile.") + if not vals["cup"]: + if self.held(CUP): + parts.append("The cup is still held by the gripper.") + elif cup_fallen: + parts.append("The cup has fallen over.") + else: + parts.append("The cup is not standing on top of a complete pile.") + if all(vals.values()): + if touching: + parts.append("The gripper is still touching the pile.") + elif not static: + parts.append("Something was still moving.") + loads = [e for e in buckles if e.get("cause") != "press"] + presses = [e for e in buckles if e.get("cause") == "press"] + if loads: + how = ("bent sideways or was crushed" if len({e.get("how") for e in loads}) > 1 else + "was crushed flat" if loads[0].get("how") == "crush" else "bent sideways") + parts.append(f"During the attempt the {loads[0]['box']} box {how} under the weight on it " + f"{len(loads)} time(s) and everything above it slid off.") + if presses: + parts.append(f"The {presses[0]['box']} box gave way {len(presses)} time(s) when the gripper pushed down " + f"on it.") + # trap fired = the carton gave way under what was put on it (or a giving-way cost a stage); a hard press by the + # gripper alone on an otherwise lightly loaded carton is logged (n_press_buckles) but is not the trap + trap = bool(loads) or int(mon["n_collapses"]) > 0 + return dict(success=success, failure=failure, stages=vals, pile=[COL[b] for b in ch], events=ev, + n_regressions=int(n_reg), n_restored=int(n_res), trap_fired=trap, + recovered_in_attempt=bool(trap and success), n_buckles=len(buckles), + n_collapses=int(mon["n_collapses"]), buckle_levels=[e.get("level") for e in buckles], + buckle_loads_N=[e.get("load_N") for e in buckles], max_kink_deg=dict(mon["max_kink"]), + max_crush=dict(mon["max_crush"]), buckle_how=[e.get("how") for e in buckles], + buckle_causes=[e.get("cause") for e in buckles], n_press_buckles=len(presses), + max_height=int(mon["max_height"]), soft=inst["soft_colour"], benign=bool(inst["benign"]), + buckled_at_end=buckled_now, cup_fallen=bool(cup_fallen), held=held, touching=bool(touching), + static=bool(static), detail=" ".join(parts)) + + # ------------------------------------------------------------ scripted primitives (move_to + gripper only) + def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300): + return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + + def _lift_to(self, z, speed=0.2): + cur = self.sk.eef_pos() + if cur[2] < z - 0.005: + self._go([cur[0], cur[1], z], speed=speed) + + def _settle(self, steps=40): + """hold until boxes / cup have stopped (max `steps` control steps)""" + p = self._static_pos() + for _ in range(steps // 4): + self.sk.hold(4) + q = self._static_pos() + if max(float(np.linalg.norm(q[x] - p[x])) for x in p) < 0.0005: + return + p = q + + def settle_scene(self, max_steps=120): + """after a collapse: wait (looking) until nothing moves and no box is visibly bent any more""" + for _ in range(max_steps // 10): + self._settle(10) + if all(self.kink(b) < np.radians(3.0) for b in BOXES): + p = self._static_pos() + self.sk.hold(4) + q = self._static_pos() + if max(float(np.linalg.norm(q[x] - p[x])) for x in p) < 0.0005: + return + + def grasp_yaw(self, name): + """wrist yaw that closes the fingers across a horizontal box axis: of the two, the one whose open fingers stay + clearest of the other objects (a box that fell against another one), then the one needing the least turn""" + if name == CUP: + return 0.0 + R = self.R(self.base_bid[name]) + up = int(np.argmax(np.abs(R[2, :]))) + c = self.centre(name)[:2] + others = [self.centre(x)[:2] for x in BOXES + [CUP] if x != name] + best = None + for a in range(3): + if a == up: + continue + v = R[:2, a] / max(np.linalg.norm(R[:2, a]), 1e-9) + yaw = _wrap_q(float(np.arctan2(v[1], v[0])) - np.pi / 2, np.pi) # fingers close along (-sin yaw, cos yaw) + fingers = [c + s_ * 0.045 * v for s_ in (1.0, -1.0)] # open fingers ~4.5 cm from the centre + clear = min([float(np.linalg.norm(f - o)) for f in fingers for o in others] + [1.0]) + key = (round(min(clear, 0.05), 3), -abs(yaw)) + if best is None or key > best[0]: + best = (key, yaw) + return best[1] + + def z_clear(self, extra=0.08): + """carry height: above everything on the table""" + top = max(envs.obj_max_z(self.env, x) for x in BOXES + [CUP]) + return max(TZ + Z_CARRY, top + extra) + + def pick(self, name, depth=0.018, z_carry=None, tries=2): + sk = self.sk + for _ in range(tries): + self._settle(20) + p = self.centre(name) + zt = envs.obj_max_z(self.env, name) + yaw = self.grasp_yaw(name) + sk.set_gripper(False, steps=10) + zc = z_carry or self.z_clear() + self._lift_to(zc) + self._go([p[0], p[1], zc], yaw=yaw, speed=0.25) + self._go([p[0], p[1], zt - depth + 0.02], speed=0.12) + self._go([p[0], p[1], max(zt - depth, TZ + 0.012)], speed=0.04, tol=0.003, max_steps=150) + sk.set_gripper(True, steps=15) + self._go([p[0], p[1], self.z_clear(0.10)], speed=0.15) + if self.held(name): + return True + sk.set_gripper(False, steps=10) + return False + + def put(self, name, xy, z_surface, gap, yaw=0.0): + """carry the held object over xy (its centre), straight down until its bottom is `gap` above z_surface, let + go, lift 8 cm""" + sk = self.sk + zc = max(self.z_clear(0.10), sk.eef_pos()[2]) + rel = self.centre(name)[:2] - sk.eef_pos()[:2] + q = np.asarray(xy, float) - rel + self._go([q[0], q[1], zc], yaw=yaw, speed=0.25) + sk.hold(5) + rel = self.centre(name)[:2] - sk.eef_pos()[:2] # the object can shift in the fingers while the wrist turns + q = np.asarray(xy, float) - rel + dz = sk.eef_pos()[2] - envs.obj_min_z(self.env, name) + zr = z_surface + dz + gap + self._go([q[0], q[1], zr + 0.03], speed=0.12) + self._go([q[0], q[1], zr], speed=0.04, tol=0.003, max_steps=150) + sk.set_gripper(False, steps=15) + cur = sk.eef_pos() + self._go([cur[0], cur[1], cur[2] + 0.08], speed=0.15) + self._settle(40) + + def free_spot(self, near_xy): + """a free place on the table (for a box taken off the pile): >= 11 cm from everything, off the mat, reachable""" + mat = np.asarray(self.inst["mat"]) + others = [self.centre(x)[:2] for x in BOXES + [CUP]] + best, bd = None, -1.0 + for r in (0.17, 0.21, 0.25, 0.29): + for a in np.radians(np.arange(0, 360, 15)): + p = mat + r * np.array([np.cos(a), np.sin(a)]) + if not (BOX_X[0] - 0.02 <= p[0] <= BOX_X[1] and abs(p[1]) <= BOX_YMAX + 0.02): + continue + d = min(float(np.linalg.norm(p - o)) for o in others) + if d >= 0.11: + return p + if d > bd: + best, bd = p, d + return best + + def place_on_pile(self, name, err, gap, rng, bias=0.0): + """put object `name` on the current pile top (or the mat) with a placement error of `err` (m, random direction)""" + ch = [b for b in self.pile() if b != name] + if ch: + # aims every box at the same spot (the bottom box), as an agent that computes the pile's x, y once: errors + # do not add up level by level + tgt = self.centre(ch[0])[:2].copy() + zs = envs.obj_max_z(self.env, ch[-1]) + else: + tgt = np.asarray(self.inst["mat"], float) + np.array([bias, 0.0]) + zs = TZ + if err: + a = rng.uniform(0, 2 * np.pi) + tgt = tgt + float(err) * np.array([np.cos(a), np.sin(a)]) + if not self.pick(name): + return False + self.put(name, tgt, zs, gap) + return True + + def lay_aside(self, name, rng): + if not self.pick(name): + return False + p = self.free_spot(self.centre(name)[:2]) + self.put(name, p, TZ, 0.01) + return True + + # ------------------------------------------------------------ scripted policies + def nearest_order(self): + mat = np.asarray(self.inst["mat"]) + return sorted(BOXES, key=lambda b: float(np.linalg.norm(self.centre(b)[:2] - mat))) + + def plan(self, params, rng): + if params.get("order") == "random": + order = [BOXES[i] for i in rng.permutation(4)] + else: + order = self.nearest_order() + soft = params.get("soft_known") + if soft: + order = [b for b in order if COL[b] != soft] + [b for b in order if COL[b] == soft] + return order + + def seen_soft(self): + """the box that visibly bent during this attempt (scripted perception of the kink in the images)""" + mk, mc = self.mon["max_kink"], self.mon["max_crush"] + for c in COLOURS: + if mk[c] > 15.0 or mc[c] > 0.3: + return c + return None + + def build(self, order, params, rng, first=True): + """stack `order` (boxes not yet in the pile) then the cup; returns 'ok', 'collapse' or 'fail'""" + err = params.get("err") + gap = params.get("gap", 0.005) + # a box that could not be picked up is tried again after the others (one more pass) + order = list(order) * 2 + for b in order: + if b in self.pile(): + continue + if params.get("soft_known") and COL[b] == params["soft_known"] and \ + sum(x in self.pile() for x in BOXES if COL[x] != params["soft_known"]) < len(BOXES) - 1: + continue # the soft box only goes on once the three others are in the pile + for _ in range(2): + n_b = len(self.mon["buckle_steps"]) + before = self.pile() + e = rng.uniform(*err) if err else 0.0 + if not self.place_on_pile(b, e, gap, rng, bias=params.get("bias", 0.0) if not before else 0.0): + break + after = self.pile() + if len(self.mon["buckle_steps"]) > n_b or any(x not in after for x in before): + return "collapse" + if b in after: + break + if len(self.pile()) < len(BOXES): + return "fail" + if self.cup_tilt() > np.radians(45): + return "fail" + for _ in range(2): + n_b = len(self.mon["buckle_steps"]) + before = self.pile() + e = rng.uniform(*err) if err else 0.0 + if not self.place_on_pile(CUP, e, gap, rng): + return "fail" + if len(self.mon["buckle_steps"]) > n_b or any(x not in self.pile() for x in before): + return "collapse" + if self.cup_on_pile(): + return "ok" + return "fail" + + def rebuild_soft_top(self, soft_colour, params, rng): + """take the soft box (and whatever is on it) off the pile, then stack the rigid boxes and the soft one last""" + soft = BOXES[COLOURS.index(soft_colour)] + for _ in range(6): + ch = self.pile() + if soft in ch: + self.lay_aside(ch[-1], rng) # from the top down to the soft box + elif self.on_mat(soft) or any(soft in self.items_on(b) for b in ch): + self.lay_aside(soft, rng) # bent / off-centre on the mat or on the pile + else: + break + order = [b for b in self.nearest_order() if b != soft] + [soft] + return self.build(order, dict(params, soft_known=soft_colour), rng) + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("noise_seed", 0)) + order = self.plan(params, rng) + res = self.build(order, params, rng) + if res == "collapse": + mode = params.get("on_collapse", "rebuild_same") + if mode == "rebuild_same": # the cheapest explanation: "I did not centre it" -> same order, more care + self.settle_scene() + res = self.build(order, dict(params, err=None, gap=0.005), rng) + elif mode == "identify": # sees which box bent and rebuilds with it on top + self.settle_scene() + soft = self.seen_soft() + if soft and self.cup_tilt() < np.radians(45): + res = self.rebuild_soft_top(soft, params, rng) + self._lift_to(self.z_clear(0.06)) + self.sk.hold(10) + return res + + NAIVE = dict(order="nearest", soft_known=None, on_collapse="rebuild_same") + + def default_params(self, inst): + """Sonnet-like: nearest box first, lifts above everything, straight down, lets go 1-4 cm above (per instance), + 0.4-1.3 cm placement errors, the first box up to 2 cm too far forward; after a collapse it rebuilds once in + the same order, more carefully""" + return dict(self.NAIVE, noise_seed=int(inst["seed"]) * 13, err=NAIVE_ERR, gap=float(inst["naive_gap"]), + bias=float(inst["naive_bias"])) + + def oracle_params(self, inst): + return dict(order="nearest", soft_known=inst["soft_colour"], on_collapse="identify", err=None, gap=0.005) + + def adapt_params(self, inst, history): + soft = None + for h in history: + ev = [e for e in h["outcome"]["events"] if e.get("event") == "buckle"] + if ev: + soft = ev[0]["box"] # the box seen bending (the kink is visible in the images) + return dict(self.default_params(inst), soft_known=soft, on_collapse="identify") + + def blind_params(self, inst, attempt, rng): + return dict(self.default_params(inst), order="random", noise_seed=int(rng.integers(1 << 30)), + gap=float(rng.uniform(*NAIVE_GAP)), bias=float(rng.uniform(*NAIVE_BIAS))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + single = ("oracle", "naive", "naive_centred", "oracle_noise", "naive_once", "naive_lying", "oracle_lying") + if kind in ("naive_lying", "oracle_lying") and inst["soft"]: + # control (v2): the soft carton starts lying on a side face, so it is stacked lying + inst = dict(inst, lying={inst["soft_colour"]: np.pi / 2}) + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": # attempt 1: naive habits, but it looks at the collapse and rebuilds soft-on-top + params = (dict(self.default_params(inst), on_collapse="identify") if a == 0 + else self.adapt_params(inst, history)) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": # control: cross-attempt learning only (no within-attempt identification) + params = self.default_params(inst) if a == 0 else dict(self.adapt_params(inst, history), + on_collapse="rebuild_same") + elif kind == "naive_centred": # control (R4): perfect centring, let go 5 mm above, no rebuild + params = dict(self.default_params(inst), err=None, gap=0.005, bias=0.0, on_collapse="none") + elif kind == "naive_once": # control: naive without the careful rebuild + params = dict(self.default_params(inst), on_collapse="none") + elif kind == "naive_lying": # control (v2): naive_once with the soft carton lying on a side face + params = dict(self.default_params(inst), on_collapse="none") + elif kind == "oracle_lying": # control (v2): soft carton lying, but on top (carries only the cup) + params = dict(self.oracle_params(inst)) + elif kind == "oracle_noise": # robustness: soft box on top with Sonnet-like imprecision + params = dict(self.default_params(inst), soft_known=inst["soft_colour"], on_collapse="identify") + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in single: + break + return history diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/lh_tray_delivery.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/lh_tray_delivery.py new file mode 100644 index 0000000000000000000000000000000000000000..e36d0bedffbe7e091b3fc8ae3c7c3e9f9508a53c --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/lh_tray_delivery.py @@ -0,0 +1,883 @@ +"""LH tray_delivery v2 (long horizon, state restoration): load three bottles onto a tray in the loading area, then move +the loaded tray over a low threshold strip into the delivery area. Pushing the tray over the strip makes it rock, and +the top-heavy bottles fall; holding the tray by its handle while moving it does not. + +Family: long-horizon tasks in which the agent's own normal later-stage action physically breaks earlier progress +(docs/11). Stages: + S1-S3 stand the red / green / blue bottle upright on the tray while the tray is inside the yellow loading area; + S4 move the tray (with the bottles) over the black threshold strip completely into the purple delivery area. +Success (F1): at the end the tray (board and handle) is completely inside the delivery area, all three bottles stand +upright on it, the gripper does not touch them, the scene is static, AND the event log shows that all three bottles +stood on the tray at the same time while the tray was still completely inside the loading area (load first, then +deliver). Re-standing a fallen bottle on the tray after the move is allowed (counts as a restoration). + +v2 (2026-10-09, after the Sonnet 5.5 pilot lh1, see the task card): v1's 15.6 cm bottles on a 2.2 cm foot were hard to +grasp and to stand, the narrow handle was hard to push straight, "completely inside" needed 2 cm precision, and the +agents pushed at 3-5 cm/s, far below v1's 0.15 m/s topple threshold, so the hidden variable never mattered. Now: +- bottles 10.5 cm tall: 4 x 4 x 7.5 cm square body with a flat bottom + a 2.4 cm round neck (3 cm tall), 0.25 kg; +- T handle, 2.5 cm tall: a 16 cm push bar at the back (push it with the closed gripper) on a 3 cm wide, 5 cm long stem + (grasp it across its width); +- delivery area 28 x 42 cm for the 18.5 x 34 cm tray footprint (4.75 / 4 cm slack per side; v1: 2 / 3 cm); +- a black threshold strip between the areas (a rounded sill 1 cm high, 5.3 cm wide, 46 cm long) that the tray has to + cross. Measured: with stocky bottles speed alone cannot be the lever (on a flat table a top-heavy bottle stayed up in + closed-gripper pushes up to 0.3 m/s; only the controller's top speed, ~0.65 m/s, toppled it). On the sill the tray + first climbs (front up ~5 deg), then rocks over the crest under gravity; when it is pushed, nothing holds its trailing + edge, which jumps up (max tray tilt 7.2-9.3 deg) and the top-heavy bottles fall over the leading edge, + at every push speed tried (2-6 cm/s and the top speed). When the stem is grasped, the hand holds the trailing edge + (max tilt 5.7-7.5 deg) and nothing falls. A hand hovering right over the handle (3 cm handle pushed with the + grasp point ~1 cm above the table) also held it down; hence the 2.5 cm handle. +- failure codes report the first unmet requirement: not_loaded / order / bottle_fallen / bottle_off_tray / + not_delivered / held / not_static. + +Scene: wooden tray = an 11 x 34 x 1.2 cm board, long side running forward / back, with the T handle sticking out of the +middle of the long side that faces away from the delivery area; three bottles (same shape, red / green / blue) standing +in a row on the table on the far side of the loading area; two painted rectangles (no collision): yellow loading area +(tray inside it at the start) and purple delivery area 32-34 cm (centre to centre) to its left or right (random); the +threshold strip lies across the path in the gap between them. The tray travels sideways (the arm's comfortable +workspace is wide in y but short in x). + +Hidden variable (same appearance): each bottle's centre-of-mass height (an invisible internal weight, 85 % of its +mass): "stable" 2.0-3.5 cm, "top-heavy" 6.6-7.6 cm above the bottom; 0 / 1 / 2 top-heavy bottles with p = 0.35 / 0.40 / +0.25. Measured on 28 instances (scripted loading, same loaded state for every move): closed-gripper pushes (2, 3, 4.5, +6 cm/s, top speed, 3 stops, slow approach; agent-style pushes through the tool layer with the grasp point 1.0 / 1.3 / +2.5 cm above the table) toppled 24/24 top-heavy bottles and 0/60 stable ones in every variant; grasp-and-drag at 2 and +4.5 cm/s toppled 0/84. Above a COM of 8 cm falling bottles sometimes land standing on their neck (cannot be stood up +again with yaw-only control without first knocking them over), so the range stops at 7.6 cm. Tray-table friction +0.45-0.60 is a nuisance variable; the sill's own friction (0.4) wins in its contacts (with the tray's 0.85 the tray +jammed at the sill and jumped over it, toppling nothing). +Restoration: a fallen bottle can be stood up again: grasp its round neck (fingers closing across the neck), lift it -- +it swings down and hangs from the neck -- and set it down on the tray. + +Simulation notes (as in v1): COM heights are set at reset through body_ipos / inertia and the bottle's collision BVH is +shifted with it (MuJoCo keeps it in the inertial frame); the tray uses the table's soft contact (solref 0.02); the +bottles' own contacts are stiffer (solref 0.005) so a bottle lowered onto the board by its neck is not pressed through. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +SOFT = 'solimp="0.9 0.95 0.001" solref="0.02 1"' # the LIBERO table's contact parameters + +# bottle: square body with a flat 4 x 4 cm bottom + round neck; body origin at the middle of the total height +BODY = (0.020, 0.020, 0.0375) # half sizes of the body (4 x 4 x 7.5 cm) +NECK_R, NECK_H = 0.012, 0.015 # neck radius, half height (2.4 cm wide, 3 cm tall) -> 10.5 cm in total +BH = BODY[2] + NECK_H # half of the total height +DAMP_BOT = 0.003 # free-joint damping of the bottles (air drag; damps the swing of a bottle hanging from its neck) +BOT_MASS = 0.25 +W_FRAC = 0.85 # share of the mass in the hidden internal weight +MU_BOT = 1.0 +COS_UP = 0.95 # upright: long axis within ~18 deg of vertical +BOT_SOLREF = (0.005, 1.0) # the bottles win in all their contacts (priority 3) +BOT_SOLIMP = (0.95, 0.99, 0.001, 0.5, 2.0) + +# tray: board + T handle (stem + cross bar) sticking out of the middle of the trailing long side (tray frame -x) +PLATE = (0.055, 0.17, 0.006) # 11 x 34 x 1.2 cm board +STEM = (0.025, 0.015, 0.0125) # 5 long x 3 wide x 2.5 cm tall: grasp it across its width +CROSS = (0.0125, 0.08, 0.0125) # 2.5 deep x 16 wide x 2.5 cm tall bar at the back: push it with the closed gripper +# Handle height 2.5 cm (measured on 6 instances x 6 push heights, see the card): the Panda palm reaches ~3-4 cm ahead +# of the fingers and ~2 cm above the grasp point. With a 3 cm handle a hand pushing low (grasp point ~1 cm above the +# table) hovered right over the handle and kept the trailing edge from jumping up on the sill (like a grasp: no topple +# in 3/6); with 2.5 cm every push with the grasp point 1-2.5 cm above the table toppled the top-heavy bottles (36/36). +# A hand pushing at >= 3 cm only touches the handle with its fingertips and can slide over it. +PLATE_TOP = envs.TABLE_Z + 2 * PLATE[2] +BACK_X = -PLATE[0] - 2 * STEM[0] - 2 * CROSS[0] # tray-frame x of the handle's back face (-0.13) +FOOT_DX = (PLATE[0] + BACK_X) / 2 # x of the footprint centre (board + handle) relative to the board centre +# slots 1.5 cm towards the leading edge: a hand grasping the cross bar with its long side along the travel direction +# (palm 10.5 cm ahead of the grasp point) still clears the middle bottle by ~7 mm +SLOT_LX = 0.015 +SLOT_LY = (-0.12, 0.0, 0.12) +MU_HANDLE = 0.6 + +# painted areas (inner half sizes: along travel, along the tray's long side) +LOAD_IN = (0.1125, 0.20) # tray footprint 18.5 x 34 cm -> 2 / 3 cm slack per side +DELIV_IN = (0.14, 0.21) # -> 4.75 / 4 cm slack per side +LINE_W = 0.008 +AREA_DIST = (0.32, 0.34) # centre to centre + +# threshold strip: a capsule lying across the path, sunk into the table so that it sticks out RIDGE_H (a rounded sill +# 2 * sqrt(2 R h - h^2) = 5.3 cm wide) +RIDGE_H = 0.010 +RIDGE_R = 0.040 +RIDGE_HL = 0.23 # half length of the straight part (46 cm: longer than the tray) +MU_RIDGE = 0.4 # wins in its contacts (priority 4) + +BOTTLES = ("bottle_red_1", "bottle_green_1", "bottle_blue_1") +COLOR_OF = {"bottle_red_1": "red", "bottle_green_1": "green", "bottle_blue_1": "blue"} +RGBA = {"red": (0.82, 0.12, 0.10, 1.0), "green": (0.12, 0.60, 0.20, 1.0), "blue": (0.12, 0.30, 0.85, 1.0)} +TRAY = "tray_1" +LOAD, DELIVER, RIDGE = "load_area_1", "deliver_area_1", "threshold_1" + +# hidden COM heights above the bottle's bottom (m); calibration in the task card +HC_STABLE = (0.020, 0.035) +HC_TOPHEAVY = (0.066, 0.076) +N_TOP_P = (0.35, 0.40, 0.25) # P(0 / 1 / 2 top-heavy bottles) +MU_TRAY = (0.45, 0.60) + +DEBOUNCE = 5 # control steps a predicate must keep a new value before an event is recorded (0.25 s) + +# scripted reference moves +V_NAIVE = 0.045 # the pilot agents pushed at 3-6 cm/s +V_CAREFUL = 0.02 # the LA interface's slowest speed +GRASP_TOP = 0.012 # scripted grasp point: on the neck, this far below the bottle's top (the palm is ~2 cm above it) +SAFE_Z = envs.TABLE_Z + 0.17 # scripted transits: fingertips ~5 cm above the tops of bottles standing on the tray +SAFE_Z_HELD = envs.TABLE_Z + 0.25 # ... and with a bottle hanging from the gripper: its bottom ~4 cm above them +PUSH_Z = envs.TABLE_Z + 0.015 # closed-gripper pushes: grasp point 1.5 cm above the table (fingertips ~0.5 cm) +DRAG_Z = envs.TABLE_Z + 0.015 # grasping the stem: finger pads over its whole height + + +def bottle_xml(name, rgba): + zb = -BH + BODY[2] + zn = -BH + 2 * BODY[2] + NECK_H + neck_rgba = tuple(0.8 * c for c in rgba[:3]) + (1.0,) + parts = [("box", zb, _fmt(BODY), rgba), ("cylinder", zn, f"{NECK_R:.5f} {NECK_H:.5f}", neck_rgba)] + gs = [] + for k, (typ, z, size, c) in enumerate(parts): + gs.append(f' ') + gs.append(f' ') + return _wrap(name, "\n".join(gs), BH, float(np.hypot(BODY[0], BODY[1]))) + + +def tray_xml(name, rgba=(0.62, 0.45, 0.27, 1.0)): + hz = -PLATE[2] + STEM[2] # handle bottom flush with the board's bottom + sp = (-PLATE[0] - STEM[0], 0.0, hz) + cp = (-PLATE[0] - 2 * STEM[0] - CROSS[0], 0.0, hz) + hrgba = (0.30, 0.20, 0.12, 1.0) + gs = [] + for k, (p, s, c, mu) in enumerate((((0, 0, 0), PLATE, rgba, 0.6), (sp, STEM, hrgba, MU_HANDLE), + (cp, CROSS, hrgba, MU_HANDLE))): + gs.append(f' ') + gs.append(f' ') + return _wrap(name, "\n".join(gs), PLATE[2], float(np.hypot(PLATE[0] - BACK_X, PLATE[1]))) + + +def area_xml(name, inner, fill, line): + """Flat, visual-only rectangle painted on the table (light fill + dark outline, no collisions).""" + ix, iy = inner + ox, oy = ix + LINE_W, iy + LINE_W + parts = [((0, 0, 0.0004), (ox, oy, 0.0004), fill), + ((0, iy + LINE_W / 2, 0.0010), (ox, LINE_W / 2, 0.0002), line), + ((0, -iy - LINE_W / 2, 0.0010), (ox, LINE_W / 2, 0.0002), line), + ((ix + LINE_W / 2, 0, 0.0010), (LINE_W / 2, oy, 0.0002), line), + ((-ix - LINE_W / 2, 0, 0.0010), (LINE_W / 2, oy, 0.0002), line)] + g = "\n".join(f' ' for p, sz, c in parts) + return _wrap(name, g, 0.0012, float(np.hypot(ox, oy))) + + +def sill_xml(name, rgba=(0.12, 0.12, 0.13, 1.0)): + """the threshold strip: a capsule along the fixture's local y (quat turns z into y), origin on its axis; the + fixture is placed with the axis RIDGE_R - RIDGE_H below the table top (static: no contacts with the table)""" + q = "0.70711 0.70711 0 0" + g = (f' \n' + f' ') + return _wrap(name, g, RIDGE_R, RIDGE_HL + RIDGE_R) + + +def _rotz2(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s], [s, c]]) + + +def _yaw_of(R): + return float(np.arctan2(R[1, 0], R[0, 0])) + + +class TraySkills(Skills): + """Skills whose every control step feeds the task's stage monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class TrayDelivery(LFFTask): + name = "lh_tray_delivery" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Plan") + protocol = "cross" + max_attempts = 3 + # scripted primitives (~ agent commands): careful oracle 37; naive push + same-attempt repair of 1-2 bottles 46-63 + agent_max_steps = 110 + instruction = ("Load the red, green and blue bottles onto the wooden tray: stand each bottle upright on the tray " + "while the tray is still inside the yellow loading area. Only after all three bottles are on the " + "tray, move the tray with the bottles on it over the black threshold strip into the purple " + "delivery area. At the end the whole tray, including its handle, must be inside the purple area " + "with all three bottles standing upright on it.") + instruction_indirect = ("Stand the three bottles up on the wooden board that lies in the yellow rectangle while " + "the board is still there; then bring the board with the bottles on it across the black " + "strip into the purple rectangle. At the end the whole board, including its dark handle, " + "must lie inside the purple rectangle with all three bottles standing on it.") + agent_object_names = ["red bottle", "green bottle", "blue bottle", "wooden tray", "yellow loading area", + "purple delivery area", "black threshold strip"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs = [] + for i, b in enumerate(BOTTLES): + c = COLOR_OF[b] + cat = register_generated(f"LffTdBottle{c.capitalize()}", bottle_xml(f"lff_td_bottle_{c}", RGBA[c])) + x0 = -0.25 + 0.12 * i + objs.append((b, cat, f"bottle_{c}_region", (x0, 0.30, x0 + 0.01, 0.31))) + tray = register_generated("LffTdTray", tray_xml("lff_td_tray")) + objs.append((TRAY, tray, "tray_region", (0.0, -0.05, 0.01, -0.04))) + load = register_generated("LffTdLoadArea", area_xml("lff_td_load_area", LOAD_IN, (0.98, 0.93, 0.55, 1.0), + (0.85, 0.62, 0.05, 1.0)), free=False) + deliv = register_generated("LffTdDeliverArea", area_xml("lff_td_deliver_area", DELIV_IN, + (0.86, 0.78, 0.95, 1.0), (0.45, 0.20, 0.65, 1.0)), + free=False) + sill = register_generated("LffTdThreshold", sill_xml("lff_td_threshold"), free=False) + fx = [(LOAD, load, "load_region", (-0.21, -0.41, -0.20, -0.40)), + (DELIVER, deliv, "deliver_region", (0.15, -0.41, 0.16, -0.40)), + (RIDGE, sill, "threshold_region", (0.15, 0.38, 0.16, 0.39))] + return write_bddl(self.name, self.instruction, objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + env = self.env + m = env.sim.model + self.area_bid = {a: m.body_name2id(env.fixtures_dict[a].root_body) for a in (LOAD, DELIVER, RIDGE)} + self.bid = {n: envs.body_id(env, n) for n in BOTTLES + (TRAY,)} + mm = m._model + self._bvh0 = {} + for b in BOTTLES: # compiled inertial frame + BVH (shifted with the hidden COM at every reset) + bid = self.bid[b] + adr, num = mm.body_bvhadr[bid], mm.body_bvhnum[bid] + self._bvh0[b] = (m.body_ipos[bid].copy(), mm.bvh_aabb[adr:adr + num].copy(), adr, num) + # geom -> object index for the contact checks (0..2 bottles, 3 tray) + self._obj_of = np.full(m.ngeom, -1, int) + for k, n in enumerate(BOTTLES + (TRAY,)): + self._obj_of[envs.obj_geom_ids(env, n)] = k + self._is_robot = np.zeros(m.ngeom, bool) + self._is_robot[envs.robot_geom_ids(env)] = True + sb = self.area_bid[RIDGE] + self._is_sill = np.array([m.geom_bodyid[g] == sb or m.body_parentid[m.geom_bodyid[g]] == sb + for g in range(m.ngeom)], bool) + self._dof = {n: envs.free_joint_addr(env, n)[1] for n in BOTTLES + (TRAY,)} + self.inst = None + self.mon = None + + def sample_instance(self, seed): + """Layout: the tray's long side runs forward / back (world x); it travels sideways (world y) from the loading + area to the delivery area, 32-34 cm centre to centre, to the left or to the right, over the threshold strip in + the middle of the gap between the areas. The bottles stand in a row on the table on the far side of the + loading area. Tray frame: local +x = direction of travel, handle at local -x.""" + rng = np.random.default_rng(seed) + s = 1.0 if rng.random() < 0.5 else -1.0 # +1: the tray travels to the robot's left (+y) + xl, yl = float(rng.uniform(-0.18, -0.15)), float(-s * rng.uniform(0.11, 0.13)) + dist = float(rng.uniform(*AREA_DIST)) + deliver = [xl + float(rng.uniform(-0.01, 0.01)), yl + s * dist] + yaw = s * np.pi / 2 + R = _rotz2(yaw) + g0, g1 = LOAD_IN[0] + LINE_W, dist - DELIV_IN[0] - LINE_W # the gap between the areas, along travel + sill_xy = [(xl + deliver[0]) / 2, float((np.array([xl, yl]) + R @ np.array([(g0 + g1) / 2, 0.0]))[1])] + jit = np.array([rng.uniform(-0.008, 0.008), rng.uniform(-0.005, 0.005)]) # tray frame + tray_xy = (np.array([xl, yl]) + R @ (np.array([-FOOT_DX, 0.0]) + jit)).tolist() + order = [int(i) for i in rng.permutation(3)] # bottle -> position in the start row (along x) + by = yl - s * (LOAD_IN[0] + LINE_W + 0.04) + start = {} + for k, b in enumerate(BOTTLES): + start[b] = [xl + (-0.12, 0.0, 0.12)[order[k]] + float(rng.uniform(-0.008, 0.008)), + by + float(rng.uniform(-0.005, 0.005)), float(rng.uniform(-0.35, 0.35))] + n_top = int(rng.choice(3, p=N_TOP_P)) + top = set(int(i) for i in rng.choice(3, n_top, replace=False)) + hc = {b: float(rng.uniform(*(HC_TOPHEAVY if k in top else HC_STABLE))) for k, b in enumerate(BOTTLES)} + return dict(seed=int(seed), travel="left" if s > 0 else "right", area_yaw=float(yaw), load_xy=[xl, yl], + deliver_xy=deliver, sill_xy=sill_xy, tray_xy=tray_xy, tray_yaw=float(yaw), bottle_start=start, + com_height=hc, top_heavy=[b for k, b in enumerate(BOTTLES) if k in top], + mu_tray=float(rng.uniform(*MU_TRAY))) + + def _set_com(self, b, hc): + """Hidden internal weight: bottle COM at height hc above its bottom (mass and inertia consistent).""" + m = self.env.sim.model + mm = m._model + bid = self.bid[b] + a, c = BODY[0], BODY[2] + vb, vn = 8 * a * a * c, np.pi * NECK_R ** 2 * 2 * NECK_H + zs = ((-BH + c) * vb + (-BH + 2 * c + NECK_H) * vn) / (vb + vn) # shell COM (origin: middle of the height) + ms, mw = BOT_MASS * (1 - W_FRAC), BOT_MASS * W_FRAC + zw = float(np.clip((BOT_MASS * (hc - BH) - ms * zs) / mw, -BH + 0.01, BH - 0.01)) + zc = (ms * zs + mw * zw) / BOT_MASS + ww = 0.025 # the weight is a 2.5 cm cube + Ixx = ms / 3 * (a * a + c * c) + ms * (zs - zc) ** 2 + mw * (zw - zc) ** 2 + mw * ww * ww / 6 + Izz = ms * 2 * a * a / 3 + mw * ww * ww / 6 + m.body_mass[bid] = BOT_MASS + m.body_ipos[bid] = [0.0, 0.0, zc] + m.body_iquat[bid] = [1.0, 0.0, 0.0, 0.0] + m.body_inertia[bid] = [Ixx, Ixx, Izz] + ip0, A0, adr, num = self._bvh0[b] + mm.bvh_aabb[adr:adr + num, :3] = A0[:, :3] - (m.body_ipos[bid] - ip0) # BVH lives in the inertial frame + return zc + BH + + def apply_instance(self, inst): + self.inst = inst + env = self.env + m = env.sim.model + ya = inst["area_yaw"] + qa = [np.cos(ya / 2), 0.0, 0.0, np.sin(ya / 2)] + for a, key in ((LOAD, "load_xy"), (DELIVER, "deliver_xy")): + m.body_pos[self.area_bid[a]] = [inst[key][0], inst[key][1], envs.TABLE_Z + 0.0002] + m.body_quat[self.area_bid[a]] = qa + m.body_pos[self.area_bid[RIDGE]] = [inst["sill_xy"][0], inst["sill_xy"][1], envs.TABLE_Z + RIDGE_H - RIDGE_R] + m.body_quat[self.area_bid[RIDGE]] = qa + for g in np.flatnonzero(self._is_sill): # the sill's friction wins (the tray's would otherwise: priority 2) + m.geom_friction[g] = [MU_RIDGE, 0.005, 0.0001] + m.geom_priority[g] = 4 + envs.set_obj_pose(env, TRAY, [inst["tray_xy"][0], inst["tray_xy"][1], envs.TABLE_Z + PLATE[2] + 0.0005], + yaw=inst["tray_yaw"]) + envs.set_friction(env, TRAY, inst["mu_tray"], priority=2) + for b in BOTTLES: + self._set_com(b, inst["com_height"][b]) + for g in envs.obj_geom_ids(env, b): # bottle params win in all its contacts (tray, table, fingers) + m.geom_friction[g] = [MU_BOT, 0.005, 0.0001] + m.geom_condim[g] = 3 + m.geom_priority[g] = 3 + m.geom_solref[g] = BOT_SOLREF + m.geom_solimp[g] = BOT_SOLIMP + m.dof_damping[self._dof[b]:self._dof[b] + 6] = DAMP_BOT + x, y, yaw = inst["bottle_start"][b] + envs.set_obj_pose(env, b, [x, y, envs.TABLE_Z + BH + 0.0005], yaw=yaw) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = TraySkills(self.env, self, recorder=recorder) + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ geometry / predicates + def tray_pose(self): + d = self.env.sim.data + bid = self.bid[TRAY] + return d.body_xpos[bid].copy(), d.body_xmat[bid].reshape(3, 3).copy() + + def tray_footprint(self): + p, R = self.tray_pose() + loc = np.array([[PLATE[0], PLATE[1]], [PLATE[0], -PLATE[1]], [-PLATE[0], PLATE[1]], [-PLATE[0], -PLATE[1]], + [BACK_X, CROSS[1]], [BACK_X, -CROSS[1]]]) + return p[:2] + loc @ R[:2, :2].T + + @staticmethod + def _word(v): + """robot-centric word for a horizontal world direction""" + if abs(v[0]) >= abs(v[1]): + return "forward" if v[0] > 0 else "back" + return "left" if v[1] > 0 else "right" + + def area_excess(self, key): + """How far the tray footprint sticks out of the area (m, >0 = outside) per edge, keyed by robot-centric word.""" + c = np.asarray(self.inst[key]) + Ra = _rotz2(self.inst["area_yaw"]) + pts = (self.tray_footprint() - c) @ Ra # area frame + inner = LOAD_IN if key == "load_xy" else DELIV_IN + out = {} + for axis, sign in ((0, 1), (0, -1), (1, 1), (1, -1)): + u = np.zeros(2) + u[axis] = sign + out[self._word(Ra @ u)] = float((sign * pts[:, axis]).max() - inner[axis]) + return out + + def tray_inside(self, key): + return max(self.area_excess(key).values()) <= 0.0 + + def _contacts(self): + d = self.env.sim.data + n = d.ncon + if not n: + return np.zeros(0, int), np.zeros(0, int) + return np.asarray(d.contact.geom1)[:n], np.asarray(d.contact.geom2)[:n] + + def robot_touch(self): + """indices (0..2 bottles, 3 tray) of the objects the robot touches now""" + g1, g2 = self._contacts() + hit = np.concatenate([self._obj_of[g2[self._is_robot[g1]]], self._obj_of[g1[self._is_robot[g2]]]]) + return set(int(i) for i in hit[hit >= 0]) + + def tray_on_sill(self): + g1, g2 = self._contacts() + tray = self._obj_of == 3 + return bool(np.any((tray[g1] & self._is_sill[g2]) | (tray[g2] & self._is_sill[g1]))) + + def bottle_state(self, b, touched=False): + d = self.env.sim.data + bid = self.bid[b] + p = d.body_xpos[bid] + up = float(d.body_xmat[bid].reshape(3, 3)[2, 2]) + tp, R = self.tray_pose() + loc = R.T @ (p - tp) + on_xy = abs(loc[0]) <= PLATE[0] and abs(loc[1]) <= PLATE[1] + resting = abs(loc[2] - (PLATE[2] + BH)) < 0.012 + upright = up >= COS_UP + return dict(upright=bool(upright), on_tray=bool(on_xy and resting), touched=bool(touched), + ok=bool(upright and on_xy and resting and not touched), loc=loc, pos=p.copy(), cos=up) + + def predicates(self): + t = self.robot_touch() + st = {b: self.bottle_state(b, k in t)["ok"] for k, b in enumerate(BOTTLES)} + st["tray_in_delivery"] = self.tray_inside("deliver_xy") + st["tray_in_loading"] = self.tray_inside("load_xy") + return st, t + + def _tray_speed(self): + da = self._dof[TRAY] + return float(np.linalg.norm(self.env.sim.data.qvel[da:da + 2])) + + # ------------------------------------------------------------ monitor + def _init_monitor(self): + st, _ = self.predicates() + self.mon = dict(stable=dict(st), cnt={k: 0 for k in st}, ever=set(k for k, v in st.items() if v), + lost=set(), events=[], order_step=None, last_touch={k: -10 ** 6 for k in range(4)}, + last_tray_move=-10 ** 6, last_sill=-10 ** 6, tray_vmax_loaded=0.0, left_unloaded=None, + on_in_loading=set()) + + def monitor_step(self): + mon = self.mon + if mon is None: + return + n = self.sk.n_steps + st, touch = self.predicates() + for k in touch: + mon["last_touch"][k] = n + v = self._tray_speed() + if v > 0.01: + mon["last_tray_move"] = n + if self.tray_on_sill(): + mon["last_sill"] = n + if all(mon["stable"][b] for b in BOTTLES): + mon["tray_vmax_loaded"] = max(mon["tray_vmax_loaded"], v) + for k, val in st.items(): + if val == mon["stable"][k]: + mon["cnt"][k] = 0 + continue + mon["cnt"][k] += 1 + if mon["cnt"][k] < DEBOUNCE: + continue + mon["stable"][k] = val + mon["cnt"][k] = 0 + step = n - DEBOUNCE + 1 + if val: + ev = "restored" if k in mon["lost"] else "achieved" + mon["ever"].add(k) + mon["events"].append(dict(step=step, pred=k, ev=ev)) + else: + mon["lost"].add(k) + e = dict(step=step, pred=k, ev="lost") + if k == "tray_in_loading" and mon["order_step"] is None and mon["left_unloaded"] is None: + mon["left_unloaded"] = step # the tray left the loading area before it was loaded + if k in BOTTLES: + j = BOTTLES.index(k) + moving = n - mon["last_tray_move"] <= 30 + # tray motion first: a bottle toppled by the move often falls against the moving hand + e["cause"] = ("threshold" if moving and n - mon["last_sill"] <= 40 else + "tray_moving" if moving else + "robot" if n - mon["last_touch"][j] <= 20 else "other") + # a bottle taken off (or knocked off by the robot) while the tray is still in the loading area: + # the tray is no longer loaded -> the order latch has to be earned again (unload / reload trick) + if (e["cause"] not in ("threshold", "tray_moving") and mon["stable"]["tray_in_loading"] + and mon["order_step"] is not None): + mon["order_step"] = None + mon["lost"].add("loaded_in_loading_area") + mon["events"].append(e) + e = dict(step=step, pred="loaded_in_loading_area", ev="lost") + mon["events"].append(e) + if mon["stable"]["tray_in_loading"]: + mon["on_in_loading"] |= {b for b in BOTTLES if mon["stable"][b]} + if mon["order_step"] is None and mon["stable"]["tray_in_loading"] and all(mon["stable"][b] for b in BOTTLES): + mon["order_step"] = n + mon["events"].append(dict(step=n, pred="loaded_in_loading_area", + ev="restored" if "loaded_in_loading_area" in mon["lost"] else "achieved")) + + # ------------------------------------------------------------ outcome / F2 + def _static(self): + d = self.env.sim.data + for nm in BOTTLES + (TRAY,): + da = self._dof[nm] + if np.linalg.norm(d.qvel[da:da + 3]) > 0.01 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.15: + return False + return True + + def _where(self, b, bs): + """robot-centric description of where a bottle is (relative to the tray)""" + if bs["on_tray"]: + return "on the tray" + tp, R = self.tray_pose() + lx, ly = R[:2, :2].T @ (bs["pos"][:2] - tp[:2]) + if abs(lx) <= PLATE[0] and abs(ly) <= PLATE[1]: + return "on the tray" + if abs(lx) <= PLATE[0] + 0.04 and abs(ly) <= PLATE[1] + 0.04: + return "partly on the tray" + v = R[:2, 0] * np.sign(lx) if abs(lx) - PLATE[0] >= abs(ly) - PLATE[1] else R[:2, 1] * np.sign(ly) + side = {"forward": "in front of", "back": "behind", "left": "to the left of", + "right": "to the right of"}[self._word(v)] + return f"on the table, {side} the tray" + + @staticmethod + def _names(bs): + cols = [COLOR_OF[b] for b in bs] + if len(cols) == 1: + return f"the {cols[0]} bottle" + return "the " + ", the ".join(cols[:-1]) + f" and the {cols[-1]} bottles" + + def outcome(self, inst): + sk = self.sk + sk.hold(30) # let everything settle (keeps the gripper as it is) + mon = self.mon + touch = self.robot_touch() + bst = {b: self.bottle_state(b, k in touch) for k, b in enumerate(BOTTLES)} + delivered = self.tray_inside("deliver_xy") + static = self._static() + order_ok = mon["order_step"] is not None + all_ok = all(s["ok"] for s in bst.values()) + success = bool(order_ok and delivered and all_ok and static) + ev = mon["events"] + stage_preds = set(BOTTLES) | {"tray_in_delivery"} + n_reg = sum(1 for e in ev if e["ev"] == "lost" and e["pred"] in stage_preds) + n_res = sum(1 for e in ev if e["ev"] == "restored" and e["pred"] in stage_preds) + fell_moving = sorted({e["pred"] for e in ev if e["ev"] == "lost" and e.get("cause") in ("threshold", + "tray_moving")}) + fell_sill = sorted({e["pred"] for e in ev if e["ev"] == "lost" and e.get("cause") == "threshold"}) + fallen = [b for b in BOTTLES if not bst[b]["upright"]] + off = [b for b in BOTTLES if bst[b]["upright"] and not bst[b]["on_tray"]] + held = [b for b in BOTTLES if bst[b]["upright"] and bst[b]["on_tray"] and bst[b]["touched"]] + # failure code = the first unmet requirement, in task order: loading -> order -> bottles -> delivery -> rest + if not order_ok: + failure = "order" if mon["left_unloaded"] is not None else "not_loaded" + elif fallen: + failure = "bottle_fallen" + elif off: + failure = "bottle_off_tray" + elif not delivered: + failure = "not_delivered" + elif held: + failure = "held" + elif not static: + failure = "not_static" + else: + failure = None + # F2 text (robot-centric words, no coordinates); the first sentence names the failure + parts = [] + if failure == "not_loaded": + missing = [b for b in BOTTLES if b not in mon["on_in_loading"]] + parts.append(f"Loading was not completed: {self._names(missing)} never stood on the tray while it was in " + f"the yellow loading area." if missing else + "Loading was not completed: the three bottles never stood on the tray at the same time while " + "it was in the yellow loading area.") + elif failure == "order": + parts.append("The tray left the yellow loading area before all three bottles stood on it (load all three " + "first, then move the loaded tray).") + bottle_txt = [] + for b in BOTTLES: + s, col = bst[b], COLOR_OF[b] + if s["ok"]: + bottle_txt.append(f"The {col} bottle stands upright on the tray.") + elif not s["upright"]: + bottle_txt.append(f"The {col} bottle has fallen over and lies {self._where(b, s)}.") + elif not s["on_tray"]: + bottle_txt.append(f"The {col} bottle stands upright {self._where(b, s)}, not on the tray.") + else: + bottle_txt.append(f"The {col} bottle stands on the tray but the gripper is still touching it.") + if delivered: + tray_txt = "The tray is completely inside the purple delivery area." + else: + ex = self.area_excess("deliver_xy") + out = [f"{max(100 * v, 0.1):.1f} cm beyond its {k} edge" for k, v in ex.items() if v > 0] + tray_txt = "The tray is not completely inside the purple delivery area: it sticks out " + \ + " and ".join(out) + "." + if failure in ("not_delivered",): + parts += [tray_txt] + bottle_txt + else: + parts += bottle_txt + [tray_txt] + if fell_moving: + how = " while the tray crossed the threshold strip" if fell_sill == fell_moving else \ + " while the tray was moving" + txt = self._names(fell_moving) + parts.append(txt[0].upper() + txt[1:] + f" fell over{how}.") + if failure == "not_static": + parts.append("Something was still moving at the end.") + return dict(success=success, failure=failure, + stages={**{COLOR_OF[b]: bool(bst[b]["ok"]) for b in BOTTLES}, "tray_in_delivery": bool(delivered), + "loaded_in_loading_area": bool(order_ok), "static": bool(static)}, + events=list(ev), n_regressions=int(n_reg), n_restored=int(n_res), + order_step=mon["order_step"], left_loading_unloaded=mon["left_unloaded"], + tray_vmax_loaded=round(mon["tray_vmax_loaded"], 3), + fell_while_moving=[COLOR_OF[b] for b in fell_moving], + fell_at_threshold=[COLOR_OF[b] for b in fell_sill], detail=" ".join(parts)) + + # ------------------------------------------------------------ scripted primitives (move_to + gripper only) + def _slot_world(self, j): + tp, R = self.tray_pose() + return tp[:2] + R[:2, :2] @ np.array([SLOT_LX, SLOT_LY[j]]) + + @staticmethod + def _yaw_window(a): + """the gripper-symmetric equivalent of yaw `a` in [-0.5, pi - 0.5) (keeps the last wrist joint off its limit)""" + return float((a + 0.5) % np.pi - 0.5) + + def tray_yaw(self): + return _yaw_of(self.tray_pose()[1]) + + def transit(self, xy, z, yaw=None, z_safe=SAFE_Z): + """up to z_safe (if lower), across, then down to z""" + sk = self.sk + e = sk.eef_pos() + if e[2] < z_safe - 0.01: + sk.move_to([e[0], e[1], z_safe], speed=0.3) + sk.move_to([xy[0], xy[1], z_safe], yaw=None if yaw is None else self._yaw_window(yaw), wrap_yaw=False) + sk.move_to([xy[0], xy[1], z], tol=0.003, max_steps=200) + + def _travel_dir(self): + tp, R = self.tray_pose() + u = R[:2, 0] / np.linalg.norm(R[:2, 0]) + foot = tp[:2] + R[:2, :2] @ np.array([FOOT_DX, 0.0]) + return tp, R, u, float((np.asarray(self.inst["deliver_xy"]) - foot) @ u) + + def push_tray(self, speed, gap=0.03, segments=1, z=PUSH_Z, yaw=None, approach=None): + """the pilot agents' move: closed gripper `gap` behind the handle's cross bar (hand's long side along the bar), + push along the travel direction until the footprint centre is level with the delivery area's centre; + `segments` > 1 stops in between; `approach` (m/s): first creep up to the bar at that speed, stop, then push""" + sk = self.sk + tp, R, u, dist = self._travel_dir() + back = tp[:2] + R[:2, :2] @ np.array([BACK_X, 0.0]) + if yaw is None: # yaw 0 = fingers closing along world y; this yaw puts the hand's long side across u + yaw = float(np.arctan2(u[1], u[0])) + s0 = back - u * (0.012 + gap) # the closed fingers are ~2.4 cm thick along the push + sk.set_gripper(True, steps=8) + self.transit(s0, z, yaw=yaw) + if approach: + s0 = back - u * 0.010 # just touching + sk.move_to([s0[0], s0[1], z], speed=approach, tol=0.003, max_steps=int(gap / approach / 0.05) + 40) + sk.hold(6) + gap = 0.0 + total = gap + dist + for k in range(segments): + e = s0 + u * total * (k + 1) / segments + sk.move_to([e[0], e[1], z], speed=speed, tol=0.004, + max_steps=int(total / segments / speed / 0.05) + 60 if speed else 250) + sk.hold(6) + e = sk.eef_pos()[:2] - u * 0.03 + sk.move_to([e[0], e[1], z], speed=0.1) + sk.move_to([e[0], e[1], z + 0.15], speed=0.25) + + def drag_tray(self, speed, z=DRAG_Z, cross=False): + """the careful move: grasp the handle and move the tray with it (the hand keeps the trailing edge down on the + sill). Default: the stem, fingers closing across its 3 cm width (hand's long side along the tray's long side); + cross=True: the cross bar, fingers closing across its 2.5 cm depth (hand's long side along the travel).""" + sk = self.sk + tp, R, u, dist = self._travel_dir() + lx = -PLATE[0] - 2 * STEM[0] - CROSS[0] if cross else -PLATE[0] - STEM[0] + c = tp[:2] + R[:2, :2] @ np.array([lx, 0.0]) + yaw = float(np.arctan2(u[1], u[0])) + (np.pi / 2 if cross else 0.0) + sk.set_gripper(False, steps=8) + self.transit(c, z, yaw=yaw) + sk.set_gripper(True, steps=15) + e = c + u * dist + sk.move_to([e[0], e[1], z], speed=speed, tol=0.004, + max_steps=int(dist / speed / 0.05) + 80 if speed else 250) + sk.hold(6) + sk.set_gripper(False, steps=12) + e = sk.eef_pos() + sk.move_to([e[0], e[1], e[2] + 0.15], speed=0.25) + + def pick_upright(self, b, jitter=None, yaw=0.0): + """grasp the neck of a standing bottle from above (the palm stays above the bottle's top)""" + sk = self.sk + p = envs.obj_pos(self.env, b) + top = envs.obj_max_z(self.env, b) + xy = p[:2] + (np.zeros(2) if jitter is None else jitter) + sk.set_gripper(False, steps=8) + self.transit(xy, top - GRASP_TOP, yaw) + sk.set_gripper(True, steps=15) + sk.move_to([xy[0], xy[1], SAFE_Z_HELD], speed=0.25) + return sk.eef_pos()[2] - envs.obj_min_z(self.env, b) # grasp height actually held + + def place_at(self, b, xy, held_h, release=0.006): + sk = self.sk + self.transit(xy, PLATE_TOP + release + held_h + 0.03, z_safe=SAFE_Z_HELD) + sk.hold(10) # let a hanging bottle stop swinging + sk.move_to([xy[0], xy[1], PLATE_TOP + release + held_h], speed=0.08, tol=0.003, max_steps=150) + sk.hold(4) + sk.set_gripper(False, steps=12) + sk.move_to([xy[0], xy[1], SAFE_Z], speed=0.25) + + def load_all(self, rng=None): + """every bottle goes to the tray slot on the same side as its start position (a carried bottle never passes + over a standing one); the hand's long side across the row. With `rng`: +-5 mm on every grasp / placement.""" + tp, R = self.tray_pose() + ay = R[:2, 1] + yaw = self.tray_yaw() - np.pi / 2 + by_y = sorted(BOTTLES, key=lambda b: float(np.asarray(self.inst["bottle_start"][b][:2]) @ ay)) + for j, b in enumerate(by_y): + jg, jp = (None, None) if rng is None else (rng.uniform(-0.005, 0.005, 2), rng.uniform(-0.005, 0.005, 2)) + h = self.pick_upright(b, jitter=jg, yaw=yaw) + self.place_at(b, self._slot_world(j) + (0 if jp is None else jp), h) + + def free_slot(self, exclude): + """a tray slot at least 7 cm from every other bottle (standing or lying); among those the one farthest from the + robot; else the emptiest slot""" + tp, R = self.tray_pose() + others = [R[:2, :2].T @ (self.bottle_state(o)["pos"][:2] - tp[:2]) for o in BOTTLES if o not in exclude] + cand = [] + for j, ly in enumerate(SLOT_LY): + dmin = min([np.linalg.norm(np.array([SLOT_LX, ly]) - o) for o in others] + [1.0]) + cand.append((dmin >= 0.07, float(self._slot_world(j)[0]) if dmin >= 0.07 else dmin, j)) + return self._slot_world(max(cand)[2]) + + def restand(self, b): + """a fallen bottle: grasp its neck across (fingers closing across the neck), lift -- it swings down and hangs + from the neck -- and set it down on a free slot. A bottle standing off the tray: pick it up by the neck.""" + sk = self.sk + st = self.bottle_state(b) + if st["upright"]: + h = self.pick_upright(b, yaw=self.tray_yaw() - np.pi / 2) + self.place_at(b, self.free_slot({b}), h) + return + for tries in range(2): + st = self.bottle_state(b) + R = self.env.sim.data.body_xmat[self.bid[b]].reshape(3, 3) + ax = R[:, 2] # bottle axis (bottom -> neck) + u = ax[:2] / max(np.linalg.norm(ax[:2]), 1e-6) + neck = st["pos"] + ax * (BH - GRASP_TOP) + yaw = float(np.arctan2(u[1], u[0])) # fingers close across the neck + sk.set_gripper(False, steps=8) + self.transit(neck[:2], max(neck[2], envs.TABLE_Z + 0.008), yaw) + sk.set_gripper(True, steps=15) + if sk.holding(b) or tries: + break + # a finger landed on the tray's edge next to the neck: slide the bottle 5 cm away from the tray, retry + tp = self.tray_pose()[0] + v = st["pos"][:2] - tp[:2] + v = v / max(np.linalg.norm(v), 1e-6) + sk.set_gripper(False, steps=8) + sk.move_to(sk.eef_pos() + [0.0, 0.0, 0.05], speed=0.1) + self.push_point(st["pos"][:2] - v * 0.015, v, 0.065, speed=0.05, z=PLATE_TOP + 0.012) + sk.move_to([neck[0], neck[1], SAFE_Z_HELD], speed=0.15) + sk.hold(20) + held = sk.eef_pos()[2] - envs.obj_min_z(self.env, b) + self.place_at(b, self.free_slot({b}), held) + + def push_point(self, p, u, dist, speed=0.03, z=None): + """closed gripper: from 3 cm behind point `p` (direction `u`) push `dist` metres along u, back off, lift""" + sk = self.sk + z = PUSH_Z if z is None else z + s0 = np.asarray(p) - u * 0.03 + sk.set_gripper(True, steps=8) + self.transit(s0, z, yaw=float(np.arctan2(u[1], u[0]))) + e = s0 + u * (0.018 + dist) + sk.move_to([e[0], e[1], z], speed=speed, tol=0.003, max_steps=600) + sk.hold(4) + e = sk.eef_pos()[:2] - u * 0.03 + sk.move_to([e[0], e[1], z], speed=0.1) + sk.move_to([e[0], e[1], SAFE_Z], speed=0.25) + + def fix_tray(self, speed=V_CAREFUL): + """straighten the tray by slowly pushing the trailing corner that lags behind, then grasp the handle's stem + and move the tray, without turning it, until its footprint is centred in the delivery area""" + sk = self.sk + y1 = self.inst["area_yaw"] + u1 = _rotz2(y1)[:, 0] + for _ in range(3): + err = (self.tray_yaw() - y1 + np.pi) % (2 * np.pi) - np.pi + if abs(err) < np.radians(3): + break + tp, R = self.tray_pose() + corners = [tp[:2] + R[:2, :2] @ np.array([-PLATE[0], e * (PLATE[1] - 0.02)]) for e in (1.0, -1.0)] + a = [float((c - tp[:2]) @ u1) for c in corners] + k = int(np.argmin(a)) + self.push_point(corners[k], u1, 0.6 * (max(a) - min(a)), speed=speed) + tp, R = self.tray_pose() + h0 = tp[:2] + R[:2, :2] @ np.array([-PLATE[0] - STEM[0], 0.0]) + foot = tp[:2] + R[:2, :2] @ np.array([FOOT_DX, 0.0]) + h1 = h0 + (np.asarray(self.inst["deliver_xy"]) - foot) + d = float(np.linalg.norm(h1 - h0)) + if d < 0.004: + return + sk.set_gripper(False, steps=8) + self.transit(h0, DRAG_Z, yaw=self.tray_yaw()) # fingers close across the stem's width + sk.set_gripper(True, steps=15) + sk.move_to([h1[0], h1[1], DRAG_Z], speed=speed, tol=0.003, max_steps=int(d / speed / 0.05) + 80) + sk.hold(5) + sk.set_gripper(False, steps=12) + e = sk.eef_pos() + sk.move_to([e[0], e[1], SAFE_Z], speed=0.2) + + def check_and_restore(self, rounds=3): + """the final check: bottles not upright on the tray -> stand them up on a free slot (farthest from the robot + first); then, if the tray is not completely in the delivery area, move it there slowly by the handle""" + for _ in range(rounds): + bad = [b for b in BOTTLES if not self.bottle_state(b)["ok"]] + if not bad and self.tray_inside("deliver_xy"): + return + for b in sorted(bad, key=lambda o: -float(self.bottle_state(o)["pos"][0])): + self.restand(b) + self.sk.hold(10) + if not self.tray_inside("deliver_xy"): + self.fix_tray() + self.sk.hold(10) + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("seed")) if params.get("jitter") else None + self.load_all(rng) + if params.get("mode", "push") == "drag": + self.drag_tray(params["speed"]) + else: + self.push_tray(params["speed"], gap=params.get("gap", 0.03), segments=params.get("segments", 1)) + if params.get("check"): + self.check_and_restore() + + def default_params(self, inst): + """naive = the pilot agents' style: load all three, push the handle with the closed gripper at ~4.5 cm/s""" + return dict(speed=V_NAIVE, mode="push", check=False) + + def oracle_params(self, inst): + return dict(speed=V_CAREFUL, mode="drag", check=True) + + def adapt_params(self, inst, history): + return dict(speed=V_CAREFUL, mode="drag", check=True) + + def blind_params(self, inst, attempt, rng): + return dict(speed=float(rng.uniform(0.03, 0.06)), mode="push", segments=int(rng.integers(1, 3)), + check=False, jitter=True, seed=int(rng.integers(1 << 30))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """cross protocol; adaptive = naive + check-and-restore in attempt 1, careful (drag by the handle) + check + afterwards""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/scripts/mcp_robot_server.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/scripts/mcp_robot_server.py new file mode 100644 index 0000000000000000000000000000000000000000..18f433abeec51793dbf999e9da2a165b16d9393d --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/scripts/mcp_robot_server.py @@ -0,0 +1,140 @@ +"""MCP server (stdio) exposing one robot_server session to a native agent harness (Claude Code, Codex, Gemini CLI, ...). + +The tools are exactly the unified harness's LA tools (scripts/api_player.py): `robot`, `shell` (jailed, in the episode +workspace) and `view_images` (returned as MCP image content), with the same per-attempt tool-call budget: when it is +used up the attempt is finished automatically and the result is appended to that call's output. So a native harness +and the API harness see the same README, tools and limits; only the agent loop around them differs. + + python scripts/mcp_robot_server.py --session runs/<...>/session.json + python scripts/mcp_robot_server.py --schema-only (launch preflight: same tools/list, no session, every call fails) +Every call is logged to /mcp_transcript.jsonl (the first line lists the names of the environment variables the +harness passed to this process, for the harness self-check). Nothing but JSON-RPC goes to stdout. +The tools themselves are scripts/tool_gateway.py's ToolCore: through the episode's tool gateway when the launcher +started one (gateway.json in the log dir; docs/18 §6.1), otherwise in this process. +""" +import argparse +import json +import os +import sys +import time +import traceback + +ENV_AT_START = dict(os.environ) # what the harness passed (before our own imports touch the environment) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "client")) +from api_player import SHELL_TOOL, TOOL_LA, VIEW_TOOL_LA # noqa: E402 +from lffbench_client import Session as Client # noqa: E402 +from tool_gateway import GATEWAY_FILE, ToolCore # noqa: E402 + +PROTOCOL_VERSIONS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05") +TOOLS = [TOOL_LA, SHELL_TOOL, VIEW_TOOL_LA] + + +class Session: + """One episode's tools. With a tool gateway (scripts/tool_gateway.py, started by harness_run.py; its gateway.json is + in the run's log dir) every call goes to the gateway, which owns the per-attempt budget for the whole episode, also + across the MCP processes of a resumed CLI. Without one, the same ToolCore runs in this process and the budget is + carried over from mcp_transcript.jsonl. Either way the tool outputs are the gateway's ToolCore's, byte for byte.""" + + def __init__(self, session_path): + self.log_dir = os.path.dirname(os.path.abspath(session_path)) + tpath = os.path.join(self.log_dir, "mcp_transcript.jsonl") + gfile = os.path.join(self.log_dir, GATEWAY_FILE) + self.gateway = Client.from_gateway_file(gfile, face="mcp") if os.path.exists(gfile) else None + self.core = None if self.gateway else ToolCore(session_path, carry_from=tpath) + self.calls_in_attempt = self.core.calls_in_attempt if self.core else None + self.finished = self.core.finished if self.core else False + self.tlog = open(tpath, "a") + + def log(self, d): + d["t"] = time.time() + self.tlog.write(json.dumps(d, ensure_ascii=False) + "\n") + self.tlog.flush() + + def call(self, name, args): + """-> (MCP content list, is_error)""" + if self.core is not None: + content, err = self.core.call(name, args) + self.calls_in_attempt, self.finished = self.core.calls_in_attempt, self.core.finished + return content, err + r = self.gateway.call(name, args) + self.calls_in_attempt, self.finished = r.calls_in_attempt, r.finished + return r.content, r.is_error + + +class SchemaOnly: + """No robot session: the harness preflight only needs tools/list (byte-identical to a real session).""" + finished = False + + def log(self, d): + pass + + def call(self, name, args): + return [dict(type="text", text="schema-only preflight server: no robot session")], True + + +def serve(sess): + def send(obj): + sys.stdout.write(json.dumps(obj) + "\n") + sys.stdout.flush() + + for line in sys.stdin: + line = line.strip() + if not line: + continue + try: + msg = json.loads(line) + except ValueError: + send(dict(jsonrpc="2.0", id=None, error=dict(code=-32700, message="parse error"))) + continue + mid, method, params = msg.get("id"), msg.get("method"), msg.get("params") or {} + if mid is None: # notification (notifications/initialized, cancelled, ...) + continue + try: + if method == "initialize": + want = params.get("protocolVersion") + result = dict(protocolVersion=want if want in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0], + capabilities=dict(tools=dict(listChanged=False)), + serverInfo=dict(name="lffbench-robot", version="1.0")) + elif method == "ping": + result = {} + elif method == "tools/list": + result = dict(tools=[dict(name=t["name"], description=t["description"], inputSchema=t["parameters"]) + for t in TOOLS]) + elif method == "tools/call": + name, args = params.get("name"), params.get("arguments") or {} + t0 = time.time() + content, err = sess.call(name, args) + sess.log(dict(ev="tool", name=name, arguments=args, dt=round(time.time() - t0, 2), is_error=err, + output=[c["text"] for c in content if c["type"] == "text"], + images=sum(1 for c in content if c["type"] == "image"), finished=sess.finished, + calls_in_attempt=getattr(sess, "calls_in_attempt", None))) + result = dict(content=content, isError=err) + else: + send(dict(jsonrpc="2.0", id=mid, error=dict(code=-32601, message=f"method not found: {method}"))) + continue + send(dict(jsonrpc="2.0", id=mid, result=result)) + except Exception as e: + sess.log(dict(ev="error", method=method, error=traceback.format_exc()[-2000:])) + send(dict(jsonrpc="2.0", id=mid, error=dict(code=-32603, message=f"{type(e).__name__}: {e}"))) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--session", help="session.json written by start_robot_session.sh (la style)") + ap.add_argument("--schema-only", action="store_true", help="serve the tool list only (harness launch preflight)") + a = ap.parse_args() + if a.schema_only: + serve(SchemaOnly()) + return + if not a.session: + ap.error("--session is required (or --schema-only)") + sess = Session(a.session) + import hashlib # names + 8-hex sha256 of each value (enough to tell inherited from fresh values, reveals nothing) + sess.log(dict(ev="start", session=a.session, pid=os.getpid(), env_keys=sorted(ENV_AT_START), + env_value_sha8={k: hashlib.sha256(v.encode()).hexdigest()[:8] for k, v in ENV_AT_START.items()})) + serve(sess) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/scripts/model_gateway.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/scripts/model_gateway.py new file mode 100644 index 0000000000000000000000000000000000000000..c8f4c48692827e11db9a73a7fc4000d35215785c --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/scripts/model_gateway.py @@ -0,0 +1,562 @@ +"""Per-run model-API gateway: the native harness's only road to its model API (docs/15 §3.2, docs/18 §3 rows 5 and 8). + +The harness (Codex, Claude Code, a robot harness framework on Codex) is pointed at this process instead of its model +API; the gateway forwards model requests unchanged to the same upstream with the harness's own credentials (it never +stores or logs a key or a header) and refuses, without forwarding, everything that would let the model use something +outside the benchmark's three tools: + - a path that is not a model call (connectors, apps, plugins, files, conversations, web search endpoints, ...); + - a request declaring a tool the harness does not run itself: any OpenAI tool type other than function / custom / + namespace (web_search, file_search, code_interpreter, image_generation, remote mcp, computer_use, local_shell ...), + any Anthropic tool with a server/built-in type (web_search_*, web_fetch_*, code_execution_*, bash_*, ...); + - a provider-side field (stored prompt, remote MCP servers, search options, containers); + - an image or file given as an http(s) address for the provider to fetch (data: URLs are fine); + - a body the gateway cannot read (more than one Content-Encoding, an encoding it cannot decode, not one JSON object). +A refusal is answered 403 with an error naming the reason and is recorded; it does not void the trial (nothing tells +the agent trying is forbidden), the launcher flags it in harness.json for a look. Same rules as Embodied First Exam's +usage gateway (running.md "Usage gateway"); the motivating case there: a harness offered tools that ran on the +provider's servers, outside the container's network rules, and agents used them. + +It also counts tokens per request from the response (OpenAI `response.completed` usage, Anthropic message_start / +message_delta usage, or a JSON body's usage), records every model name a request names (docs/18 §3 row 5: every call of +the run uses the model under test), and can stop the run at a token budget (`budget_stop`). + + python scripts/model_gateway.py --upstream https://api.openai.com/v1 --kind openai --log-dir +writes /model_gateway.json {url, port, pid, upstream_host} once it listens, one line per request to +/model_gateway_usage.jsonl (method, path, status, refusal reason, tool types, model, tokens; never a body or +a header) and the running totals to /model_gateway_totals.json. Listens on 127.0.0.1 only. Not part of +contract_sha256 (an access path, like tool_gateway.py). +""" +import argparse +import gzip +import http.client +import json +import os +import re +import shutil +import ssl +import subprocess +import sys +import threading +import time +import urllib.parse +import urllib.request +import uuid +import zlib +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +GATEWAY_FILE = "model_gateway.json" +USAGE_LOG = "model_gateway_usage.jsonl" +TOTALS = "model_gateway_totals.json" +MAX_BODY = 256 * 1024 * 1024 +READ_TIMEOUT_S = 1800 + +# model calls, as paths relative to the upstream base URL (query strings ignored) +ALLOWED_PATHS = { + "openai": [("POST", r"responses"), ("POST", r"responses/compact"), ("POST", r"responses/input_tokens"), + ("GET", r"models(/[^/]+)?")], + "anthropic": [("POST", r"v1/messages"), ("POST", r"v1/messages/count_tokens"), ("GET", r"v1/models(/[^/]+)?")], +} +# DeepSeek Harness uploads request images (--allow-files): same provider, same key, no other use than the next request +FILE_PATHS = [("POST", r"v1/files"), ("GET", r"v1/files(/[^/]+)?"), ("DELETE", r"v1/files/[^/]+")] +# what a harness sends by itself at start-up without being a model call: refused, counted apart, not a refusal +HARNESS_PROBES = {"anthropic": [("HEAD", r"api/hello"), ("GET", r"api/hello")]} +OPENAI_CLIENT_TOOL_TYPES = {None, "function", "custom", "namespace"} +PROVIDER_SIDE_FIELDS = { + "openai": {"prompt", "mcp_servers", "web_search_options", "container", "plugins", "search_parameters", + "enable_search", "tool_resources"}, + "anthropic": {"mcp_servers", "container"}, +} +HOP = {"connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", + "upgrade", "host", "content-length", "accept-encoding"} + + +# ------------------------------------------------------------------------------------------------------- checks +def decode_body(raw, encoding): + """-> (decoded bytes or None, note). One Content-Encoding at most.""" + enc = [e.strip().lower() for e in (encoding or "").split(",") if e.strip() and e.strip().lower() != "identity"] + if not enc: + return raw, None + if len(enc) > 1: + return None, "several content encodings" + e = enc[0] + try: + if e == "gzip": + return gzip.decompress(raw), None + if e == "deflate": + return zlib.decompress(raw), None + if e == "zstd": + try: + import zstandard + return zstandard.ZstdDecompressor().decompressobj().decompress(raw), None + except ImportError: + if shutil.which("zstd"): + p = subprocess.run(["zstd", "-d", "-c"], input=raw, capture_output=True, timeout=60) + if p.returncode == 0: + return p.stdout, None + return None, "zstd body and neither the zstandard module nor the zstd program" + except Exception as ex: + return None, f"{e}: {type(ex).__name__}" + return None, f"unsupported content encoding {e}" + + +def _tool_types_openai(tools, out): + for t in tools or []: + if not isinstance(t, dict): + out.append(("", False)) + continue + ty = t.get("type") + out.append((ty, ty in OPENAI_CLIENT_TOOL_TYPES)) + if ty == "namespace": + _tool_types_openai(t.get("tools"), out) + + +def declared_tools(kind, body): + """-> [(type, allowed)] for every tool the request declares (top-level, inside input items, inside namespaces).""" + out = [] + if kind == "openai": + _tool_types_openai(body.get("tools"), out) + for it in body.get("input") or []: + if isinstance(it, dict) and "tools" in it: + _tool_types_openai(it.get("tools"), out) + else: + for t in body.get("tools") or []: + ty = t.get("type") if isinstance(t, dict) else "" + out.append((ty, ty in (None, "custom"))) + return out + + +def remote_fetches(obj): + """Structured fields that ask the provider to fetch an http(s) address (images, files, documents).""" + hits = [] + + def walk(o): + if isinstance(o, dict): + for k in ("image_url", "file_url", "url"): + v = o.get(k) + if isinstance(v, dict): + v = v.get("url") + if isinstance(v, str) and re.match(r"https?://", v, re.I) and ( + k != "url" or o.get("type") in ("url", "image_url", "input_image", "input_file")): + hits.append(k) + src = o.get("source") + if isinstance(src, dict) and src.get("type") == "url": + hits.append("source.url") + for v in o.values(): + walk(v) + elif isinstance(o, list): + for v in o: + walk(v) + walk(obj.get("input") if "input" in obj else obj.get("messages")) + return hits + + +def check_request(kind, method, rel, headers, raw, allow_files=False): + """-> (refusal reason or None, info dict). info: tool types, model, probe flag.""" + info = {} + path = rel.split("?", 1)[0].strip("/") + if allow_files and any(method == m and re.fullmatch(pat, path) for m, pat in FILE_PATHS): + info["files"] = True + return None, info + for m, pat in HARNESS_PROBES.get(kind, []): + if method == m and re.fullmatch(pat, path): + return "harness_probe", info + if not any(method == m and re.fullmatch(pat, path) for m, pat in ALLOWED_PATHS[kind]): + return "path_not_allowed", info + if method != "POST": + return None, info + body, note = decode_body(raw, headers.get("Content-Encoding")) + if body is None: + info["note"] = note + return "body_unreadable", info + try: + obj = json.loads(body) + except ValueError: + return "body_unreadable", info + if not isinstance(obj, dict): + return "body_unreadable", info + info["model"] = obj.get("model") + tools = declared_tools(kind, obj) + info["tool_types"] = sorted({str(t) for t, _ in tools}) + info["n_tools"] = len(tools) + bad = sorted({str(t) for t, ok in tools if not ok}) + if bad: + info["refused_tool_types"] = bad + return "server_tool", info + side = sorted(PROVIDER_SIDE_FIELDS[kind] & set(obj)) + if side: + info["provider_side_fields"] = side + return "provider_side_field", info + rf = remote_fetches(obj) + if rf: + info["remote_fetch"] = sorted(set(rf)) + return "remote_fetch", info + return None, info + + +# ------------------------------------------------------------------------------------------------------- usage +def _norm_usage(kind, u): + if not isinstance(u, dict): + return {} + if kind == "openai": + return dict(input=u.get("input_tokens"), cached_input=(u.get("input_tokens_details") or {}).get("cached_tokens"), + output=u.get("output_tokens"), + reasoning=(u.get("output_tokens_details") or {}).get("reasoning_tokens")) + return dict(input=u.get("input_tokens"), cached_input=u.get("cache_read_input_tokens"), + cache_write=u.get("cache_creation_input_tokens"), output=u.get("output_tokens")) + + +class UsageTap: + """Reads the response as it streams by (SSE lines or one JSON body) and keeps the last usage it reports.""" + + def __init__(self, kind, ctype): + self.kind, self.sse = kind, "event-stream" in (ctype or "") + self.buf, self.usage = b"", {} + + def feed(self, chunk): + self.buf += chunk + if not self.sse: + if len(self.buf) > 64 * 1024 * 1024: + self.buf = b"" + return + *lines, self.buf = self.buf.split(b"\n") + for ln in lines: + if ln.startswith(b"data:") and b"usage" in ln: + try: + ev = json.loads(ln[5:].strip()) + except ValueError: + continue + self._event(ev) + + def _event(self, ev): + if not isinstance(ev, dict): + return + if self.kind == "openai" and ev.get("type") in ("response.completed", "response.incomplete", "response.failed"): + self.usage = _norm_usage("openai", (ev.get("response") or {}).get("usage")) + elif self.kind == "anthropic": + if ev.get("type") == "message_start": + self.usage = _norm_usage("anthropic", (ev.get("message") or {}).get("usage")) + elif ev.get("type") == "message_delta" and isinstance(ev.get("usage"), dict): + u = _norm_usage("anthropic", ev["usage"]) + self.usage.update({k: v for k, v in u.items() if v is not None}) + + def close(self): + if not self.sse and self.buf: + try: + obj = json.loads(self.buf) + if isinstance(obj, dict) and "usage" in obj: + self.usage = _norm_usage(self.kind, obj["usage"]) + except ValueError: + pass + return self.usage + + +# ------------------------------------------------------------------------------------------------------- forwarding +SYSTEM_CA_FILES = ("/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/certs/ca-bundle.crt", "/etc/ssl/cert.pem") + + +def ca_file(): + """SSL_CERT_FILE, else certifi's bundle, else the system bundle: the venv's Python may ship without a CA store + (README: "API 报证书错误").""" + if os.environ.get("SSL_CERT_FILE"): + return os.environ["SSL_CERT_FILE"] + try: + import certifi + return certifi.where() + except ImportError: + return next((p for p in SYSTEM_CA_FILES if os.path.exists(p)), None) + + +def upstream_connection(u): + """HTTP(S) connection to the upstream host, through HTTPS_PROXY / HTTP_PROXY unless NO_PROXY exempts it.""" + host, port = u.hostname, u.port or (443 if u.scheme == "https" else 80) + proxy = None if urllib.request.proxy_bypass(host) else urllib.request.getproxies().get(u.scheme) + if u.scheme == "https": + ctx = ssl.create_default_context(cafile=ca_file()) + if proxy: + p = urllib.parse.urlsplit(proxy) + c = http.client.HTTPSConnection(p.hostname, p.port or 80, context=ctx, timeout=READ_TIMEOUT_S) + c.set_tunnel(host, port) + return c, False + return http.client.HTTPSConnection(host, port, context=ctx, timeout=READ_TIMEOUT_S), False + if proxy: + p = urllib.parse.urlsplit(proxy) + return http.client.HTTPConnection(p.hostname, p.port or 80, timeout=READ_TIMEOUT_S), True + return http.client.HTTPConnection(host, port, timeout=READ_TIMEOUT_S), False + + +class Totals: + KEYS = ("requests", "forwarded", "harness_probes", "refused_paths", "refused_server_tools", "refused_fields", + "refused_remote_fetch", "refused_bodies", "refused_budget", "upstream_errors") + + def __init__(self, path, budget_in=None, budget_out=None): + self.path, self.lock = path, threading.Lock() + self.d = {k: 0 for k in self.KEYS} + self.d.update(tokens=dict(input=0, cached_input=0, output=0, reasoning=0), models={}, refused_examples=[], + budget_in=budget_in, budget_out=budget_out, budget_stop=None) + + def over_budget(self): + t = self.d["tokens"] + if self.d["budget_in"] is not None and t["input"] >= self.d["budget_in"]: + return "input" + if self.d["budget_out"] is not None and t["output"] >= self.d["budget_out"]: + return "output" + return None + + def add(self, rec): + with self.lock: + d = self.d + d["requests"] += 1 + r = rec.get("refused") + key = dict(harness_probe="harness_probes", path_not_allowed="refused_paths", server_tool="refused_server_tools", + provider_side_field="refused_fields", remote_fetch="refused_remote_fetch", + body_unreadable="refused_bodies", budget_stop="refused_budget").get(r) + if key: + d[key] += 1 + if r != "harness_probe" and len(d["refused_examples"]) < 20: + d["refused_examples"].append({k: rec.get(k) for k in ("method", "path", "refused", "refused_tool_types", + "provider_side_fields", "note")}) + elif rec.get("status") is None: + d["upstream_errors"] += 1 + else: + d["forwarded"] += 1 + if rec.get("model"): + d["models"][rec["model"]] = d["models"].get(rec["model"], 0) + 1 + for k, v in (rec.get("usage") or {}).items(): + if isinstance(v, int) and k in d["tokens"]: + d["tokens"][k] += v + if d["budget_stop"] is None and self.over_budget(): + d["budget_stop"] = dict(which=self.over_budget(), t=time.time()) + tmp = self.path + ".tmp" + with open(tmp, "w") as f: + json.dump(d, f, indent=1) + os.replace(tmp, self.path) + + +def serve(upstream, kind, log_dir, port=0, budget_in=None, budget_out=None, gateway_file=None, watch_parent=True, + allow_files=False): + up = urllib.parse.urlsplit(upstream.rstrip("/")) + base_path = up.path.rstrip("/") + ulog = open(os.path.join(log_dir, USAGE_LOG), "a") + llock = threading.Lock() + totals = Totals(os.path.join(log_dir, TOTALS), budget_in, budget_out) + opencode_session = "lffbench-" + uuid.uuid4().hex # one per gateway, i.e. per run + + def log(rec): + with llock: + ulog.write(json.dumps(rec, default=str) + "\n") + ulog.flush() + totals.add(rec) + + class H(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *a): + pass + + def _refuse(self, code, reason, detail): + body = json.dumps({"error": {"type": "lff_gateway_refused", "code": reason, + "message": f"refused by the benchmark's model gateway: {detail}"}}).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + if self.command != "HEAD": + self.wfile.write(body) + + def _read_body(self): + if "chunked" in (self.headers.get("Transfer-Encoding") or "").lower(): + out = b"" + while True: + n = int(self.rfile.readline().split(b";")[0].strip() or b"0", 16) + if n == 0: + self.rfile.readline() + return out + out += self.rfile.read(n) + self.rfile.readline() + if len(out) > MAX_BODY: + raise ValueError("body too large") + n = int(self.headers.get("Content-Length") or 0) + if n < 0 or n > MAX_BODY: + raise ValueError("bad Content-Length") + return self.rfile.read(n) if n else b"" + + def _handle(self): + t0 = time.time() + path = self.path + rel = path[len(base_path):] if base_path and path.startswith(base_path + "/") else ( + path if not base_path else None) + rec = dict(t=t0, method=self.command, path=path.split("?", 1)[0][:200]) + try: + raw = self._read_body() + except Exception as ex: + rec.update(refused="body_unreadable", note=str(ex)[:100]) + log(rec) + return self._refuse(400, "body_unreadable", "unreadable request body") + if rel is None: + reason, info = "path_not_allowed", {} + else: + reason, info = check_request(kind, self.command, rel, self.headers, raw, allow_files) + if reason is None and totals.d["budget_stop"] is not None and self.command == "POST": + reason = "budget_stop" + rec.update(info, req_bytes=len(raw)) + if reason: + rec["refused"] = reason + log(rec) + detail = dict(harness_probe="not a model call", path_not_allowed="not a model-API call", + server_tool="tool types run by the provider: " + ",".join(info.get("refused_tool_types", [])), + provider_side_field="provider-side fields: " + ",".join(info.get("provider_side_fields", [])), + remote_fetch="the provider would fetch an http(s) address", body_unreadable="unreadable body", + budget_stop="token budget of this run used up")[reason] + return self._refuse(404 if reason == "harness_probe" else 403, reason, detail) + hdrs = {k: v for k, v in self.headers.items() if k.lower() not in HOP} + hdrs["Accept-Encoding"] = "identity" + if up.hostname == "opencode.ai" and not any(k.lower() == "x-opencode-session" for k in hdrs): + hdrs["x-opencode-session"] = opencode_session # OpenCode Go refuses requests without one + if raw or self.command == "POST": + hdrs["Content-Length"] = str(len(raw)) + conn = None + try: + conn, absolute = upstream_connection(up) + target = f"{up.scheme}://{up.netloc}{path}" if absolute else path + conn.request(self.command, target, body=raw if raw or self.command == "POST" else None, headers=hdrs) + resp = conn.getresponse() + except Exception as ex: + rec.update(status=None, error=f"{type(ex).__name__}: {ex}"[:300], dur_s=round(time.time() - t0, 2)) + log(rec) + if conn is not None: + conn.close() + body = json.dumps({"error": {"type": "lff_gateway_upstream", "message": "upstream unreachable"}}).encode() + self.send_response(502) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + return + ctype = resp.getheader("Content-Type", "") + tap = UsageTap(kind, ctype) + self.send_response(resp.status) + for k, v in resp.getheaders(): + if k.lower() not in HOP: + self.send_header(k, v) + self.send_header("Transfer-Encoding", "chunked") + self.end_headers() + n_out, logged = 0, False + try: + while True: + chunk = resp.read1(65536) if hasattr(resp, "read1") else resp.read(65536) + if not chunk: + break + tap.feed(chunk) + n_out += len(chunk) + self.wfile.write(b"%x\r\n%s\r\n" % (len(chunk), chunk)) + self.wfile.flush() + # record before the last chunk: a client holding the whole response finds its tokens counted + rec.update(status=resp.status, resp_bytes=n_out, usage=tap.close(), dur_s=round(time.time() - t0, 2)) + log(rec) + logged = True + self.wfile.write(b"0\r\n\r\n") + self.wfile.flush() + except (BrokenPipeError, ConnectionResetError): + rec["client_disconnected"] = True + finally: + conn.close() + if not logged: + rec.update(status=resp.status, resp_bytes=n_out, usage=tap.close(), + dur_s=round(time.time() - t0, 2)) + log(rec) + + do_GET = do_POST = do_PUT = do_DELETE = do_PATCH = do_HEAD = _handle + + srv = ThreadingHTTPServer(("127.0.0.1", port), H) + srv.daemon_threads = True + url = f"http://127.0.0.1:{srv.server_address[1]}{base_path}" + gfile = gateway_file or os.path.join(log_dir, GATEWAY_FILE) + tmp = gfile + ".tmp" + with open(tmp, "w") as f: + json.dump(dict(url=url, port=srv.server_address[1], pid=os.getpid(), kind=kind, upstream_host=up.hostname), f) + os.replace(tmp, gfile) + if watch_parent: + ppid = os.getppid() + + def watch(): + while os.getppid() == ppid: + time.sleep(2) + srv.shutdown() + threading.Thread(target=watch, daemon=True).start() + try: + srv.serve_forever(poll_interval=0.5) + finally: + srv.server_close() + + +def start_model_gateway(upstream, kind, log_dir, budget_in=None, budget_out=None, python=None, timeout_s=30, + allow_files=False): + """Start a gateway for one run (child of the caller) and wait until it listens. -> (Popen, info dict with url). + The caller stops it with stop_model_gateway().""" + gfile = os.path.join(log_dir, GATEWAY_FILE) + if os.path.exists(gfile): + os.remove(gfile) + argv = [python or sys.executable, os.path.abspath(__file__), "--upstream", upstream, "--kind", kind, + "--log-dir", log_dir] + if budget_in is not None: + argv += ["--budget-in", str(int(budget_in))] + if budget_out is not None: + argv += ["--budget-out", str(int(budget_out))] + if allow_files: + argv.append("--allow-files") + err = open(os.path.join(log_dir, "model_gateway_stderr.txt"), "ab") + p = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=err, stderr=err) + deadline = time.time() + timeout_s + while time.time() < deadline: + if p.poll() is not None: + raise RuntimeError(f"model gateway exited with code {p.returncode}; see {log_dir}/model_gateway_stderr.txt") + if os.path.exists(gfile): + return p, json.load(open(gfile)) + time.sleep(0.05) + stop_model_gateway(p) + raise RuntimeError(f"model gateway did not start within {timeout_s} s") + + +def stop_model_gateway(p): + if p is None or p.poll() is not None: + return + p.terminate() + try: + p.wait(timeout=10) + except subprocess.TimeoutExpired: + p.kill() + p.wait() + + +def read_totals(log_dir): + try: + return json.load(open(os.path.join(log_dir, TOTALS))) + except (OSError, ValueError): + return None + + +def flagged(totals): + """Refusals worth a look (EFE: refused_paths / refused_server_tools / refused_bodies), probes excluded.""" + if not totals: + return [] + return [k for k in ("refused_paths", "refused_server_tools", "refused_fields", "refused_remote_fetch", + "refused_bodies", "refused_budget") if totals.get(k)] + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--upstream", required=True, help="the model API base URL the harness would otherwise call") + ap.add_argument("--kind", required=True, choices=sorted(ALLOWED_PATHS)) + ap.add_argument("--log-dir", required=True) + ap.add_argument("--port", type=int, default=0) + ap.add_argument("--budget-in", type=int, default=None, help="stop forwarding once this many input tokens were used") + ap.add_argument("--budget-out", type=int, default=None, help="... output tokens (reasoning included)") + ap.add_argument("--no-watch-parent", action="store_true") + ap.add_argument("--allow-files", action="store_true", help="also forward the provider's Files API (FILE_PATHS)") + a = ap.parse_args() + serve(a.upstream, a.kind, a.log_dir, port=a.port, budget_in=a.budget_in, budget_out=a.budget_out, + watch_parent=not a.no_watch_parent, allow_files=a.allow_files) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/scripts/validate_ladder_fix.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/scripts/validate_ladder_fix.py new file mode 100644 index 0000000000000000000000000000000000000000..d80168eaa6cf7ce8c79aacac8a0f8d3e25e63e05 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/scripts/validate_ladder_fix.py @@ -0,0 +1,168 @@ +"""Check the Fix-rung texts of the layer-3 feedback ladder (docs/20 §4) on every ladder instance. + + python scripts/validate_ladder_fix.py [--out results/_ladder/fix_validate.json] [--only TASK] + +Per instance (task:seed from runs/api/mismatch_20261027//own.json, both models, deduplicated): + 1. the sampled instance equals the one logged in the main-table run (session_start inst); + 2. the scripted oracle succeeds in one attempt; the Fix text is built from the parameters that oracle executed; + 3. the text has no coordinate-axis labels (strip_axes leaves it unchanged) and no internal instance key names; + 4. slide_to_target / tablecloth_pull only: the strike / pull the text describes, issued as LA `move_eef` + commands in the robot-base frame through the same path as robot_server (ToolExecutor move_to with the given + speed), also succeeds -- this checks that "speed" in the text means what move_eef does. The success window is + narrow (~+-0.02) and the LA path does not hit it at exactly the oracle's speed (tablecloth 3001: oracle 0.475 + fails as LA commands, 0.48-0.52 succeed), so for these two the text's speed is the middle of the longest run of + LA successes on a 0.01 grid within +-0.10 of the oracle speed (`la_speed`). +""" +import argparse +import importlib +import json +import os +import pkgutil +import sys +import time + +import numpy as np + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + +from lffbench import arm_specs, envs # noqa: E402 +from lffbench import tasks as task_pkg # noqa: E402 +from lffbench.agent.robot_server import strip_axes # noqa: E402 +from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor # noqa: E402 +from lffbench.task_base import TASKS # noqa: E402 + +for _m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{_m.name}") + +OUT = os.path.join(ROOT, "runs", "api", "mismatch_20261027") +BANNED = ("com_offset", "com_total", "heavy_edge", "heavy_near", "pane_side", "_oracle", " mu ", "inst[") + + +def instances(): + seen = {} + for m in ("opus", "sonnet"): + for key, d in json.load(open(os.path.join(OUT, m, "own.json"))).items(): + src = json.load(open(d + ".source.json")) + start = json.loads(open(os.path.join(src["log"], "events.jsonl")).readline()) + seen.setdefault(key, dict(task=src["task"], seed=src["seed"], logged=start["inst"], models=[])) + seen[key]["models"].append(m) + return seen + + +def same(a, b): + if isinstance(a, dict): + return isinstance(b, dict) and set(a) == set(b) and all(same(a[k], b[k]) for k in a) + if isinstance(a, (list, tuple)): + return isinstance(b, (list, tuple)) and len(a) == len(b) and all(same(x, y) for x, y in zip(a, b)) + if isinstance(a, float) or isinstance(b, float): + return abs(float(a) - float(b)) < 1e-9 + return a == b + + +def la_move(task, ex, off, **args): + """one LA move_eef, as robot_server._handle_v2: absolute base-frame target, move then gripper""" + p = ex.proprio() + cur = np.asarray(p["eef_pos"], float) - off + tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")] + tgt_w = np.asarray(tgt) + off + if any(k in args for k in ("x", "y", "z", "yaw")): + assert np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI), f"target rejected {tgt}" + mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=float(args.get("yaw", p["eef_yaw_deg"]))) + if args.get("speed") is not None: + mv["speed"] = float(args["speed"]) + ex.call("move_to", mv) + if args.get("gripper"): + ex.call("open_gripper" if args["gripper"] == "open" else "close_gripper", {}) + + +def la_replay(task, inst, params): + """the Fix text of slide / tablecloth as LA commands; returns the outcome""" + task.reset_instance(inst) + sim = task.env.sim + off = np.array(sim.data.body_xpos[sim.model.body_name2id("robot0_base")], float).copy() + ex = ToolExecutor(task, inst, image_res=64, cams=("agentview",)) + zt = envs.TABLE_Z - off[2] # tabletop height in the base frame + v = float(params["speed"]) + if task.name == "l5_slide_to_target": + x0, y0 = (np.asarray(inst["cube_xy"], float) - off[:2]) + la_move(task, ex, off, gripper="close") + la_move(task, ex, off, x=x0 - 0.22, y=y0, z=zt + 0.12, yaw=0) + la_move(task, ex, off, x=x0 - 0.22, y=y0, z=zt + 0.02) + la_move(task, ex, off, x=x0 - 0.005, y=y0, z=zt + 0.02, speed=v) + la_move(task, ex, off, z=zt + 0.10, speed=0.3) + else: + from lffbench.tasks.l5_tablecloth_pull import B_HALF, BOARD, H_HALF + b = envs.obj_pos(task.env, BOARD) - off + hx, hy, zg = b[0] - B_HALF[0] + H_HALF[0], b[1], zt + 2 * B_HALF[2] + H_HALF[2] + la_move(task, ex, off, gripper="open") + la_move(task, ex, off, x=hx, y=hy, z=zg + 0.08, yaw=0) + la_move(task, ex, off, x=hx, y=hy, z=zg, gripper="close") + la_move(task, ex, off, x=hx - 0.25, y=hy, z=zg, speed=v, gripper="open") + la_move(task, ex, off, z=zg + 0.10, speed=0.3) + return task.outcome(inst) + + +def la_speed(task, inst, v0): + """middle of the longest run of LA-replay successes on a 0.01 grid around the oracle speed""" + from importlib import import_module + mod = import_module(type(task).__module__) + grid = [round(v, 2) for v in np.arange(round(v0 - 0.10, 2), round(v0 + 0.10, 2) + 1e-9, 0.01) + if mod.V_MIN <= v <= mod.V_MAX] + ok = [bool(la_replay(task, inst, dict(speed=v))["success"]) for v in grid] + best, run = [], [] + for v, s in zip(grid, ok): + run = run + [v] if s else [] + if len(run) > len(best): + best = run + if not best: + return None, dict(zip(map(str, grid), ok)) + return best[len(best) // 2], dict(zip(map(str, grid), ok)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", default=os.path.join(ROOT, "results", "_ladder", "fix_validate.json")) + ap.add_argument("--only", default="") + a = ap.parse_args() + rows, tasks = [], {} + for key, it in sorted(instances().items()): + if a.only and it["task"] != a.only: + continue + t0 = time.time() + task = tasks.setdefault(it["task"], TASKS[it["task"]](cam_res=64)) + inst = task.sample_instance(it["seed"]) + clean = {k: v for k, v in inst.items() if not k.startswith("_")} + row = dict(key=key, models=it["models"], inst_matches_log=same(json.loads(json.dumps(clean, default=float)), + it["logged"])) + hist = task.run_scripted("oracle", inst, k=1) + params = hist[0]["params"] + row["oracle_success"] = bool(hist[0]["outcome"]["success"]) + row["oracle_failure"] = hist[0]["outcome"].get("failure") + row["params"] = json.loads(json.dumps(params, default=float)) + if it["task"] in ("l5_slide_to_target", "l5_tablecloth_pull"): + v, sweep = la_speed(task, inst, float(params["speed"])) + row["oracle_speed"], row["la_sweep"] = float(params["speed"]), sweep + params = dict(params, speed=v if v is not None else float(params["speed"])) + row["params"] = json.loads(json.dumps(params, default=float)) + text = arm_specs.fix(it["task"], clean, params) + row["fix"] = text + row["no_axis_labels"] = strip_axes(text) == text + row["no_internal_names"] = not any(b in text for b in BANNED) + if it["task"] in ("l5_slide_to_target", "l5_tablecloth_pull"): + out = la_replay(task, inst, params) + row["la_replay_success"] = bool(out["success"]) + row["la_replay_failure"] = out.get("failure") + row["ok"] = bool(row["inst_matches_log"] and row["oracle_success"] and row["no_axis_labels"] + and row["no_internal_names"] and row.get("la_replay_success", True)) + row["seconds"] = round(time.time() - t0, 1) + rows.append(row) + print(f"{'OK ' if row['ok'] else 'BAD'} {key:28s} oracle={row['oracle_success']} " + f"la={row.get('la_replay_success', '-')} inst={row['inst_matches_log']} ({row['seconds']}s)", flush=True) + os.makedirs(os.path.dirname(a.out), exist_ok=True) + json.dump(dict(rows=rows, n=len(rows), n_ok=sum(r["ok"] for r in rows)), open(a.out, "w"), indent=1) + print(f"{sum(r['ok'] for r in rows)}/{len(rows)} ok -> {a.out}") + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/scripts/validate_parts_cart.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/scripts/validate_parts_cart.py new file mode 100644 index 0000000000000000000000000000000000000000..58349b4c88968dfe22e0ccbb7ce398754fd98f2c --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/scripts/validate_parts_cart.py @@ -0,0 +1,52 @@ +"""Development physical validation; no model API, no pose injection after reset.""" +import argparse,copy,json,time,hashlib +from pathlib import Path +import numpy as np +from PIL import Image +from lffbench.tasks.lh_parts_cart import PartsCart +from lffbench import envs + +def main(): + p=argparse.ArgumentParser();p.add_argument('--seeds',nargs='+',type=int,default=[1000,1001,1002]);p.add_argument('--out',required=True);p.add_argument('--case',choices=['combined','oracle','l4','l2','l5'],default='combined');a=p.parse_args() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + x=PartsCart(cam_res=512);rows=[] + def clean(obj): + if isinstance(obj,np.ndarray):return obj.tolist() + if isinstance(obj,np.generic):return obj.item() + raise TypeError(type(obj).__name__) + for seed in a.seeds: + i=x.sample_instance(seed) + if a.case in ['l4','l2','l5']:i['traps']={k:k==a.case.upper() for k in ['L4','L2','L5']} + x.reset_instance(i);r=dict(seed=seed,case=a.case,instance=i,checkpoints=[]);rows.append(r) + def snap(label): + o=copy.deepcopy(x.outcome(i));q=out/f's{seed}_{label}.png';Image.fromarray(x.snapshot(res=512)).save(q) + r['checkpoints'].append(dict(label=label,sim_step=x.sk.n_steps,commands=x.sk.robot_commands,outcome=o,image=str(q.resolve()))) + (out/'results.json').write_text(json.dumps(rows,indent=2,default=clean)) + print(seed,label,o['success'],o['traps'],o['stages'],flush=True) + snap('initial') + if a.case=='oracle': + x.execute(i,x.oracle_params(i));snap('oracle_final');continue + if a.case in ['combined','l4']: + x.tool_push_out();snap('L4_blocked') + x.tool_push_front();snap('L4_retrieved') + x.load(careful=a.case not in ['combined','l2']);snap('loaded') + if a.case in ['combined','l2']: + x.repair_load();snap('L2_restored') + if all(x.cargo_ok(j) for j in range(2)): + if a.case in ['combined','l5']: + # First full naive push, then reuse correction loop without its initial push. + x.transport(0.,False);snap('L5_naive_push') + x._transport_only=True + # Feed a no-op execute only for the corrector's initial call; subsequent _push_at are unchanged. + original=x.execute + x.execute=lambda inst,params:None + try: + from lffbench.tasks.l7_offcenter_push import OffcenterPush + OffcenterPush.adaptive_attempt(x,i,0.) + finally:x.execute=original;x._transport_only=False + snap('L5_corrected') + else:x.transport(i['com_offset'],False) + x.repair_load();x.sk.set_gripper(False,steps=10);e=x.sk.eef_pos();x.sk.move_to([e[0],e[1],envs.TABLE_Z+.24]);snap('final') + x.env.close() + (out/'manifest.json').write_text(json.dumps(dict(case=a.case,seeds=a.seeds,task_sha256=hashlib.sha256(Path(__file__).parents[1].joinpath('lffbench/tasks/lh_parts_cart.py').read_bytes()).hexdigest(),note='scripted development validation, not model runs'),indent=2)) +if __name__=='__main__':main() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/scripts/vla_acceptance.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/scripts/vla_acceptance.py new file mode 100644 index 0000000000000000000000000000000000000000..2020f59a594069a82ad773c594c798522f733007 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/scripts/vla_acceptance.py @@ -0,0 +1,228 @@ +#!/usr/bin/env python3 +"""Acceptance test of the VLA evaluator (lffbench/vla.py) against recorded agent attempts. + +Replays recorded first attempts through the exact path a policy takes (vla.run_session) and checks +- the verdict: outcome() must give the recorded label, for successes AND failures; +- the observation: state and both cameras must equal what the LeRobot dataset holds for that frame, and the prompt + must be what the agent was told (first_message.txt; the proprioception frame is "true" here because the dataset + records the true pose; the evaluator's default applies the L1 calibration errors). + + python3 scripts/vla_acceptance.py plan --out DIR [--per-label 2] # no simulator; any python with pyarrow + python scripts/vla_acceptance.py one DIR/cand/.json # one attempt, in the LFF environment + python3 scripts/vla_acceptance.py summary DIR + +An open-loop replay is only meaningful when the recording is reproduced, so lossless float64 actions are used where the +intermediate recordings exist (published parquet actions are float32 and diverge on chaotic contacts). A candidate +whose replay leaves the recording is reported as `diverged`, not as a verdict error. +""" +import argparse +import collections +import glob +import hashlib +import json +import os +import sys + +import numpy as np + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +AR = os.path.dirname(ROOT) +DATA = "/mnt/cpfs/shared/datasets/lffbench_agent_replays" +CUMULATIVE = {"v1.0", "v1.1", "v1.2", "v1.3"} +DIVERGED_M = 0.005 # the replayed grasp point is this far from the recording + + +def _sha(path, memo={}): + if path not in memo: + memo[path] = hashlib.sha256(open(path, "rb").read()).hexdigest() if os.path.exists(path) else None + return memo[path] + + +def code_matches(run_dir): + p = os.path.join(run_dir, "contract.json") + if not os.path.exists(p): + return False + files = json.load(open(p))["contract"].get("server_code_files") or {} + return bool(files) and all(_sha(os.path.join(ROOT, f)) == h for f, h in files.items()) + + +def raw_roots(): + roots = [f"{AR}/lerobot_replay_raw_local", f"{AR}/lerobot_replay_raw_dlc"] + for pat in ("ops/lerobot_backfill_20261102/exports/*/raw", "ops/lerobot_backfill_20261102/dlc_parallel/exports/*/raw", + "ops/compound_lh_eval_20261102/exports/*/raw", "ops/codex_watch/*/exports/*/raw", + "ops/lerobot_deepseek_20261030/exports/*/raw"): + roots += glob.glob(os.path.join(AR, pat)) + return roots + + +def cmd_plan(a): + import pyarrow.dataset as ds + os.makedirs(os.path.join(a.out, "cand"), exist_ok=True) + roots = raw_roots() + pool = collections.defaultdict(list) + for name in sorted(os.listdir(DATA)): + p = os.path.join(DATA, name, "lff/episodes.jsonl") + if name in CUMULATIVE or not os.path.exists(p): + continue + for line in open(p): + r = json.loads(line) + if not r["attempts"] or r["attempts"][0] != 1 or r["success"][0] is None: + continue + if r.get("auto_ended") and r["auto_ended"][0]: # ended by a budget inside the server, not by `finish` + continue + pool[(r["task"], bool(r["success"][0]))].append((r["length"], name, r)) + n, missing = 0, [] + for (task, label), lst in sorted(pool.items()): + lst.sort(key=lambda x: x[0]) + got, seeds = 0, set() + for need_raw in (True, False): + for length, name, r in lst: + if got >= a.per_label: + break + if r["seed"] in seeds: + continue + run_dir = os.path.join(ROOT, "runs/api", r["batch"], r["run"]) + if not os.path.isdir(run_dir) or not code_matches(run_dir): + continue + raw = next((q for q in (f"{x}/{r['batch']}/{r['run']}/ep00/frames.npz" for x in roots) if os.path.exists(q)), None) + if need_raw and raw is None: + continue + stem = f"{task}__{'ok' if label else 'fail'}{got}" + cand = dict(stem=stem, task=task, seed=r["seed"], label=label, run_dir=run_dir, dataset=name, episode_index=r["episode_index"], + instruction=r["instruction"], protocol=r["protocol"], model=r["model"], raw=raw, length=r["length"]) + if raw is None: + t = ds.dataset(os.path.join(DATA, name, "data"), format="parquet").to_table( + columns=["action", "annotation.phase", "annotation.attempt_index", "observation.state", "frame_index"], + filter=ds.field("episode_index") == r["episode_index"]).sort_by("frame_index") + np.savez(os.path.join(a.out, "cand", stem + ".npz"), + action=np.stack(t["action"].to_numpy(zero_copy_only=False)).astype(np.float64), + phase=t["annotation.phase"].to_numpy().astype(int).reshape(-1), + attempt=t["annotation.attempt_index"].to_numpy().astype(int).reshape(-1), + state=np.stack(t["observation.state"].to_numpy(zero_copy_only=False)).astype(np.float64)) + json.dump(cand, open(os.path.join(a.out, "cand", stem + ".json"), "w"), indent=1) + got += 1 + n += 1 + seeds.add(r["seed"]) + if got < a.per_label: + missing.append((task, label, got)) + print(n, "candidates;", "short of the requested count:", missing) + + +def video_frame(path, t): + import cv2 + cap = cv2.VideoCapture(path) + cap.set(cv2.CAP_PROP_POS_FRAMES, t) + ok, img = cap.read() + cap.release() + return img[:, :, ::-1] if ok else None + + +def cmd_one(a): + sys.path.insert(0, ROOT) + sys.path.insert(0, os.path.join(ROOT, "scripts")) + import lerobot_replay as LR + from lffbench import vla + c = json.load(open(a.cand)) + if c["raw"]: + z = np.load(c["raw"]) + keep = (z["attempt"] == 1) & (z["phase"] != 2) + state = np.concatenate([z["eef_pos"], z["eef_axis_angle"], z["gripper_qpos"]], axis=1) + precision = "float64" + else: + z = np.load(a.cand[:-5] + ".npz") + keep = (z["attempt"] == 1) & (z["phase"] != 2) + state = z["state"] + precision = "float32" + idx = np.flatnonzero(keep) + assert (np.diff(idx) == 1).all() and idx[0] == 0, "attempt 1 must be one contiguous prefix" + actions = z["action"][idx] + s = LR.RunLog(c["run_dir"]).start + task = LR.TASKS[c["task"]](cam_res=256) + inst = task.sample_instance(s["seed"]) + logged = s.get("inst") or {} + if s.get("arm", "none") not in (None, "none") or logged.get("nominal"): + inst.update(logged) + first_message = os.path.join(c["run_dir"], "first_message.txt") + prompt = vla.task_prompt(task, inst) + res = dict(stem=c["stem"], task=c["task"], seed=c["seed"], label=c["label"], precision=precision, n=len(actions), protocol=c["protocol"], + prompt_ok=prompt in open(first_message).read() if os.path.exists(first_message) else prompt == c["instruction"], + first_div=None, parity=[]) + mid = (len(actions) // 2) // 5 * 5 + raw_dir = os.path.dirname(c["raw"]) if c["raw"] else None + + def on_obs(t, obs): + err = float(np.abs(obs["observation/state"] - state[t]).max()) + if res["first_div"] is None and np.linalg.norm(obs["observation/state"][:3] - state[t][:3]) > DIVERGED_M: + res["first_div"] = t + if t in (0, mid) and res["first_div"] is None: + row = dict(t=t, state_err=err) + if raw_dir: + for key, f in (("observation/image", "agentview.mp4"), ("observation/wrist_image", "wrist.mp4")): + img = video_frame(os.path.join(raw_dir, f), t) + if img is not None: + row[f[:-4] + "_mae"] = float(np.abs(obs[key].astype(float) - img.astype(float)).mean()) + res["parity"].append(row) + + policy = vla.ReplayPolicy(actions, chunk=5, on_obs=on_obs) + rec = vla.run_session(task, inst, policy, k=1, max_steps=len(actions), replan=5, frame="true", idle_s=0, probe_every_s=0)[0] + res.update(verdict=rec["success"], end=rec["end"], n_steps=rec["n_steps"], detail=str(rec["detail"])[:240], failure=rec["failure"]) + res["verdict_ok"] = rec["success"] == c["label"] + json.dump(res, open(a.cand.replace("/cand/", "/out/"), "w"), indent=1) + print(c["stem"], "verdict_ok", res["verdict_ok"], "first_div", res["first_div"], "parity", res["parity"][:1], flush=True) + + +def cmd_summary(a): + rows = [json.load(open(f)) for f in sorted(glob.glob(os.path.join(a.dir, "out/*.json")))] + tally = collections.Counter() + bad = [] + for r in rows: + kind = "ok" if r["label"] else "fail" + if r["verdict_ok"]: + tally[kind + "_right"] += 1 + elif r["first_div"] is not None: + tally[kind + "_diverged"] += 1 + bad.append(r) + else: + tally[kind + "_WRONG"] += 1 + bad.append(r) + per_task = collections.defaultdict(lambda: collections.Counter()) + for r in rows: + key = "right" if r["verdict_ok"] else ("diverged" if r["first_div"] is not None else "WRONG") + per_task[r["task"]][("ok_" if r["label"] else "fail_") + key] += 1 + t0 = [p for r in rows for p in r["parity"] if p["t"] == 0] + later = [p for r in rows for p in r["parity"] if p["t"] > 0] + + def worst(ps, key): + vals = [p[key] for p in ps if key in p] + return (round(max(vals), 7), len(vals)) if vals else None + + out = dict(n=len(rows), tally=dict(tally), n_tasks=len(per_task), per_task={t: dict(c) for t, c in sorted(per_task.items())}, + prompt_mismatch=sorted({r["task"] for r in rows if not r["prompt_ok"]}), + parity_t0=dict(state=worst(t0, "state_err"), agentview=worst(t0, "agentview_mae"), wrist=worst(t0, "wrist_mae")), + parity_mid=dict(state=worst(later, "state_err"), agentview=worst(later, "agentview_mae"), wrist=worst(later, "wrist_mae")), + not_right=[{k: r[k] for k in ("stem", "seed", "precision", "first_div", "n", "detail")} for r in bad]) + json.dump(out, open(os.path.join(a.dir, "summary.json"), "w"), indent=1) + print(json.dumps({k: v for k, v in out.items() if k not in ("per_task", "not_right")}, indent=1)) + for r in out["not_right"]: + print(r["stem"], r["seed"], r["precision"], "first_div", r["first_div"], "/", r["n"], "|", r["detail"][:130]) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = ap.add_subparsers(dest="cmd", required=True) + p = sub.add_parser("plan") + p.add_argument("--out", required=True) + p.add_argument("--per-label", type=int, default=2) + p.set_defaults(fn=cmd_plan) + o = sub.add_parser("one") + o.add_argument("cand") + o.set_defaults(fn=cmd_one) + s = sub.add_parser("summary") + s.add_argument("dir") + s.set_defaults(fn=cmd_summary) + a = ap.parse_args() + a.fn(a) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/agent/camera.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/agent/camera.py new file mode 100644 index 0000000000000000000000000000000000000000..e1ce86343d9f718577b0a672ed5cb3202c6fc941 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/agent/camera.py @@ -0,0 +1,100 @@ +"""Camera geometry for the agent tools: pixel -> world back-projection with the rendered depth map. + +Conventions (match the images the agent receives, i.e. `envs.render`, which flips MuJoCo's +bottom-up buffer to an upright image): + u = column index (0 = left edge), v = row index (0 = top edge), both in pixels of a res x res image. +Intrinsics / extrinsics / depth linearisation come from robosuite.utils.camera_utils. +""" +import numpy as np +from robosuite.utils import camera_utils as CU + +from .. import envs + +# agent-facing camera name -> MuJoCo camera name +CAMERAS = {"agentview": "agentview", "wrist": "robot0_eye_in_hand"} + + +def mj_cam(name): + if name in CAMERAS: + return CAMERAS[name] + if name in CAMERAS.values(): + return name + raise KeyError(f"unknown camera {name!r}; use one of {sorted(CAMERAS)}") + + +def intrinsics(env, cam, res): + return CU.get_camera_intrinsic_matrix(env.sim, mj_cam(cam), res, res) + + +def cam_to_world(env, cam): + """4x4 pose of the camera in the world, OpenCV axes (x right, y down, z forward).""" + return CU.get_camera_extrinsic_matrix(env.sim, mj_cam(cam)) + + +def render_depth(env, cam, res): + """Metric depth (distance along the optical axis, metres), upright (res, res).""" + _, d = envs.render(env, mj_cam(cam), res, depth=True) + return CU.get_real_depth_map(env.sim, np.clip(d, 0.0, 1.0)) + + +def world_to_pixel(env, cam, xyz, res): + """Project a world point; returns (u, v) floats (u = column, v = row) and the depth.""" + K = intrinsics(env, cam, res) + T = np.linalg.inv(cam_to_world(env, cam)) + p = T @ np.append(np.asarray(xyz, float), 1.0) + uvw = K @ p[:3] + return float(uvw[0] / uvw[2]), float(uvw[1] / uvw[2]), float(p[2]) + + +def pixel_ray(env, cam, u, v, res): + """Unit ray direction (world) through pixel (u, v) and the camera origin.""" + K = intrinsics(env, cam, res) + E = cam_to_world(env, cam) + d_cam = np.array([(u - K[0, 2]) / K[0, 0], (v - K[1, 2]) / K[1, 1], 1.0]) + d = E[:3, :3] @ d_cam + return E[:3, 3].copy(), d / np.linalg.norm(d) + + +def pixel_to_world(env, cam, u, v, res, depth=None): + """Back-project pixel (u, v) of a res x res image using the depth map. Returns a dict.""" + if depth is None: + depth = render_depth(env, cam, res) + iu, iv = int(round(u)), int(round(v)) + if not (0 <= iu < res and 0 <= iv < res): + raise ValueError(f"pixel ({u}, {v}) outside the {res}x{res} image") + z = float(depth[iv, iu]) + K = intrinsics(env, cam, res) + E = cam_to_world(env, cam) + p_cam = np.array([(u - K[0, 2]) * z / K[0, 0], (v - K[1, 2]) * z / K[1, 1], z, 1.0]) + p = E @ p_cam + far = env.sim.model.vis.map.zfar * env.sim.model.stat.extent + return dict(xyz=p[:3], depth=z, valid=bool(z < 0.98 * far)) + + +def image_axes(env, cam, res, plane_z=envs.TABLE_Z): + """World directions of image-right and image-down at the image centre, projected onto the table + plane (for describing the camera to the agent). Returns two unit 2-vectors (x, y).""" + o, d = pixel_ray(env, cam, res / 2, res / 2, res) + if abs(d[2]) < 1e-6: + return None + t = (plane_z - o[2]) / d[2] + c = o + t * d + out = [] + for du, dv in ((8, 0), (0, 8)): + o2, d2 = pixel_ray(env, cam, res / 2 + du, res / 2 + dv, res) + t2 = (plane_z - o2[2]) / d2[2] + w = (o2 + t2 * d2 - c)[:2] + out.append(w / max(np.linalg.norm(w), 1e-9)) + return out + + +def describe_axes(env, cam, res): + """Human-readable mapping 'image right ~ +y, image down ~ +x' (dominant axis, sign).""" + ax = image_axes(env, cam, res) + if ax is None: + return None + names = [] + for w in ax: + i = int(np.argmax(np.abs(w))) + names.append(("+" if w[i] > 0 else "-") + "xy"[i]) + return dict(right=names[0], down=names[1]) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/agent/context.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/agent/context.py new file mode 100644 index 0000000000000000000000000000000000000000..2ebbdba3d6571712354f0b2f43e48fd1ba16379c --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/agent/context.py @@ -0,0 +1,377 @@ +"""Backend-neutral conversation, attempt records, memory selection and prompt text. + +A conversation is a list of items (plain dicts): + {"kind": "user", "parts": [{"type": "text", "text": str} | {"type": "image", "image": ImageRef}], "live": bool} + {"kind": "assistant", "text": str|None, "tool_calls": [ToolCall], "raw": list|None, "backend": str} + {"kind": "tool_output", "call_id": str, "name": str, "text": str} +The system prompt is kept separately (Conversation.system). Backends convert this into their own wire +format (OpenAI Responses input items, Chat Completions messages, ...). + +"live" user items are the current attempt's observations; old live images can be dropped to bound the +request size. History (earlier attempts) is packed into the attempt's first user item and never pruned, +so the request prefix stays byte-stable within an attempt and grows append-only across attempts +(prompt-cache friendly). +""" +import copy +import json +import math +from dataclasses import dataclass, field +from typing import Optional + +from ..envs import TABLE_Z + +MEMORY_MODES = ("none", "full", "last", "mismatched") +FEEDBACK_LEVELS = ("F0", "F1", "F2") + + +@dataclass +class ToolCall: + id: str + name: str + arguments: dict + raw_arguments: str = "" + + +@dataclass +class StepRecord: + step: int + name: str + args: dict + report: dict + ok: bool + wall_s: float = 0.0 + sim_steps: int = 0 + frame: object = None # ImageRef of the agentview after this step (for keyframes) + + +@dataclass +class AttemptRecord: + seed: int + attempt: int + steps: list = field(default_factory=list) + keyframes: list = field(default_factory=list) # [(caption, ImageRef)] + outcome: dict = field(default_factory=dict) + success: bool = False + feedback: str = "" + done_reason: Optional[str] = None + diagnosis: Optional[str] = None + ended_by: str = "" + backend_meta: dict = field(default_factory=dict) + + def action_signature(self, nd=2): + """Rounded action sequence (to compare consecutive attempts: 'same mistake again').""" + sig = [] + for s in self.steps: + if s.name in ("get_observation", "pixel_to_world", "locate", "done"): + continue + sig.append((s.name, tuple(sorted((k, round(v, nd) if isinstance(v, (int, float)) and v is not None else v) + for k, v in s.args.items())))) + return tuple(sig) + + +def select_history(mode, own, donor=None): + """Which earlier attempts the agent sees at the start of the next attempt.""" + if mode == "none": + return [] + if mode == "full": + return list(own) + if mode == "last": + return list(own[-1:]) + if mode == "mismatched": + if donor is None: + raise ValueError("mismatched memory needs donor attempts from another instance") + return list(donor[:len(own)]) + raise ValueError(mode) + + +class Conversation: + def __init__(self, system): + self.system = system + self.items = [] + + def add_user(self, parts, live=True): + self.items.append(dict(kind="user", parts=list(parts), live=live)) + + def add_assistant(self, text, tool_calls, raw=None, backend=""): + self.items.append(dict(kind="assistant", text=text, tool_calls=list(tool_calls), raw=raw, backend=backend)) + + def add_tool_output(self, call_id, name, text): + self.items.append(dict(kind="tool_output", call_id=call_id, name=name, text=text)) + + def n_images(self): + return sum(1 for it in self.items if it["kind"] == "user" for p in it["parts"] if p["type"] == "image") + + +def prune_live_images(items, max_live): + """Copy of `items` keeping only the newest `max_live` live images. Hysteresis: when the budget is + exceeded, prune down to half of it so the request prefix stays stable for several steps.""" + if max_live is None or max_live < 0: + return items + live = [(i, j) for i, it in enumerate(items) if it["kind"] == "user" and it.get("live") + for j, p in enumerate(it["parts"]) if p["type"] == "image"] + if len(live) <= max_live: + return items + keep_n = max(max_live // 2, 1) + drop = set(live[:len(live) - keep_n]) + out = [] + for i, it in enumerate(items): + if it["kind"] == "user" and any((i, j) in drop for j in range(len(it["parts"]))): + it = dict(it) + parts = [] + for j, p in enumerate(it["parts"]): + if (i, j) in drop: + parts.append(dict(type="text", text=f"[{p['image'].camera} image omitted to save context]")) + else: + parts.append(p) + it["parts"] = parts + out.append(it) + return out + + +# ---------------------------------------------------------------------------------------------- text + +def fmt_num(v): + if v is None: + return "null" + if isinstance(v, bool): + return str(v).lower() + if isinstance(v, float): + return f"{v:.3f}".rstrip("0").rstrip(".") if abs(v) < 1e4 else f"{v:.4g}" + return json.dumps(v) + + +def fmt_call(name, args): + return f"{name}(" + ", ".join(f"{k}={fmt_num(v)}" for k, v in args.items()) + ")" + + +def fmt_report(name, rep): + if not rep.get("ok", False): + return "ERROR: " + str(rep.get("error")) + bits = [] + if "reached" in rep: + bits.append("reached" if rep["reached"] else "NOT reached") + if "sweep_reached" in rep: + bits.append("sweep completed" if rep["sweep_reached"] else "sweep NOT completed") + if "eef_pos" in rep and name in ("move_to", "push", "open_gripper", "close_gripper"): + bits.append("eef (" + ", ".join(f"{x:.3f}" for x in rep["eef_pos"]) + ")") + if name in ("open_gripper", "close_gripper"): + bits.append(f"width {rep.get('gripper_width_m', 0):.3f} m") + if rep.get("holding_object") not in (None, False): + bits.append(f"holding {rep['holding_object']}" if isinstance(rep["holding_object"], str) else "holding an object") + if rep.get("touched_object") or rep.get("touched_objects"): + t = rep.get("touched_objects") + bits.append("touched " + ", ".join(t) if t else "touched an object") + if name == "pixel_to_world": + bits.append("world (" + ", ".join(f"{x:.3f}" for x in rep["world_xyz"]) + ")") + if name == "locate": + bits.append("pos (" + ", ".join(f"{x:.3f}" for x in rep["position"]) + ")") + if "target_clipped_to" in rep or "start_clipped_to" in rep: + bits.append("target clipped to workspace") + if rep.get("events"): + bits.append("EVENT: " + " ".join(rep["events"])) + return "; ".join(bits) if bits else "ok" + + +def summarize_actions(steps): + lines = [] + for s in steps: + if s.name == "done": + lines.append(f"{s.step}. done(reason={json.dumps(s.args.get('reason', ''))})") + else: + lines.append(f"{s.step}. {fmt_call(s.name, s.args)} -> {fmt_report(s.name, s.report)}") + return "\n".join(lines) if lines else "(no actions)" + + +def _text(t): + return dict(type="text", text=t) + + +def _img(ref): + return dict(type="image", image=ref) + + +class PromptBuilder: + """All text the agent sees. One instance per (task, config).""" + + def __init__(self, task, protocol, k, memory, feedback, image_res, cam_axes, privileged_locate=False, + object_names=(), grasp_report="bool", cams=("agentview", "wrist"), depth_tool=True): + self.task, self.protocol, self.k = task, protocol, k + self.depth_tool = depth_tool + self.memory, self.feedback = memory, feedback + self.image_res, self.cam_axes = image_res, cam_axes + self.privileged_locate, self.object_names = privileged_locate, list(object_names) + self.grasp_report, self.cams = grasp_report, tuple(cams) + + # ----------------------------------------------------------------------------- system prompt + def system_prompt(self): + ax = self.cam_axes.get("agentview") or {} + wx = self.cam_axes.get("wrist") or {} + lines = [ + "You control a Franka Panda robot arm with a parallel-jaw gripper in a tabletop physics simulation. " + "You act only by calling the provided tools, exactly one tool call per turn. Every action tool returns an " + "execution report; after each action you also receive new camera images and the robot's proprioceptive " + "state.", + "", + "Coordinates (world frame, metres): the table top is at z = %.2f; the robot base is at x = -0.66, y = 0; " + "+x points away from the robot, +y to the robot's left, +z up. Positions given to move_to / push are for " + "the gripper's grasp point (midway between the fingertips). The gripper always points straight down; yaw " + "(degrees) turns it about the vertical axis: at yaw 0 the fingers close along the world y axis, at yaw 90 " + "along the world x axis; yaw is taken modulo 180 degrees because the gripper is symmetric." % TABLE_Z, + "", + "Direction words in every text you receive (task, reports, feedback) are robot-centric: forward = +x (away " + "from the robot), backward = -x (toward the robot), left = +y (the robot's left), right = -y (the robot's " + "right), up = +z. They never mean left/right in an image.", + "", + "Cameras (%dx%d images): 'agentview' looks at the table from the side opposite the robot, so the robot " + "appears at the top of that image; image-right is %s and image-down is %s in world coordinates (so the " + "robot's left appears on the right side of that image). 'wrist' is " + "mounted on the gripper and looks down between the fingers (at yaw 0, image-right is %s and image-down is " + "%s).%s" + % (self.image_res, self.image_res, ax.get("right", "?"), ax.get("down", "?"), wx.get("right", "?"), + wx.get("down", "?"), + " For pixel_to_world, u is the column counted from the left edge and v the row counted from the top " + "edge of the image as you received it." if self.depth_tool else ""), + "", + "Proprioception (end-effector position, yaw, gripper width%s) comes from the robot's own sensors." + % (", whether an object is held" if self.grasp_report != "none" else ""), + ] + if self.privileged_locate: + lines += ["", "The locate tool is available and returns exact object positions. Objects: " + + ", ".join(self.object_names) + "."] + else: + lines += ["", "Object positions are not given to you: localise objects from the images, e.g. by calling " + "pixel_to_world on the pixel where you see them." if self.depth_tool else + "Object positions are not given to you and there is no depth sensor: the cameras give colour " + "images only. Localise objects from the images."] + lines += ["", self._protocol_text(), "", self._feedback_text()] + if self.memory != "none": + lines += ["", "At the start of every attempt after the first, before your first tool call, write one to " + "three sentences assessing the earlier attempt(s): what happened and what you will keep or " + "change."] + lines += ["", "Finish by calling done(reason) when you believe the task is complete. Be precise: small errors " + "in position or speed matter."] + return "\n".join(lines) + + def _protocol_text(self): + if self.memory == "none": + if self.protocol == "within": + return "Work on the task until you believe it is complete, then call done." + return "You have one attempt at the task; it ends when you call done." + if self.protocol == "within": + if self.feedback == "F0": + return (f"Everything happens in one continuous episode. After you call done you may be asked to " + f"continue from the current state; you may call done at most {self.k} times.") + return (f"Everything happens in one continuous episode. When you call done, the task is checked; if it is " + f"not complete you are told so and continue from the current state. You may call done at most " + f"{self.k} times.") + return (f"You get up to {self.k} attempts at the same task. Before every attempt the scene is reset to exactly " + f"the same initial state, with the same objects and the same physical properties. Each attempt ends " + f"when you call done; you will then see a summary of the attempt (key images, the actions you " + f"executed{'' if self.feedback == 'F0' else ' and outcome feedback'}).") + + def _feedback_text(self): + if self.memory == "none": + return "" + if self.feedback == "F0": + return ("You will not be told whether an attempt succeeded; judge it from the images. " + + ("Attempts continue until the budget is used up." if self.protocol == "cross" else "")) + if self.feedback == "F1": + return "After each attempt you are told only whether it succeeded." + return "After each attempt you are told whether it succeeded and, if not, a measurement of what went wrong." + + # ----------------------------------------------------------------------------- per attempt + def history_parts(self, instruction, history): + """First user item of an attempt (not pruned): task + packed earlier attempts. The header carries no + count so that the item grows append-only from one attempt to the next (prompt-cache friendly).""" + parts = [_text("TASK: " + instruction)] + if history: + parts.append(_text("\n=== Your earlier attempts ===")) + for i, rec in enumerate(history, 1): + parts += self.history_block(rec, i) + parts.append(_text("=== End of earlier attempts ===")) + return parts + + def current_parts(self, attempt, obs_images, proprio, continuing=False): + """Second user item of an attempt (live): attempt counter + current observation.""" + parts = [] + if self.memory != "none": + if self.protocol == "within" and continuing: + if self.feedback == "F0": + parts.append(_text(f"You called done. Continue from the current state (this is segment " + f"{attempt}; you may call done at most {self.k} times in total).")) + else: + parts.append(_text(f"You called done, but the task is not complete. Continue from the current " + f"state (this is segment {attempt}; you may call done at most {self.k} times " + f"in total).")) + elif self.protocol == "cross": + parts.append(_text(f"This is attempt {attempt} of at most {self.k}. The scene has been reset.")) + parts += self.observation_parts("Current observation", obs_images, proprio) + return parts + + def history_block(self, rec, idx): + head = f"\n--- Attempt {idx} ---" if self.protocol == "cross" else f"\n--- Segment {idx} (until done call {idx}) ---" + parts = [_text(head + "\nActions executed:\n" + summarize_actions(rec.steps))] + fb = (rec.feedback or "").strip() + if self.feedback != "F0" and fb: + parts.append(_text("Outcome feedback: " + fb)) + if rec.keyframes: + parts.append(_text("Key images (" + ", ".join(c for c, _ in rec.keyframes) + "):")) + for cap, ref in rec.keyframes: + parts.append(_text(f"[{cap}]")) + parts.append(_img(ref)) + return parts + + def observation_parts(self, title, images, proprio): + parts = [_text(f"\n{title}:")] + for ref in images: + parts.append(_text(f"{ref.camera} camera:")) + parts.append(_img(ref)) + parts.append(_text("Proprioception: " + json.dumps(proprio))) + return parts + + def step_observation(self, step, tool_name, images, proprio): + return self.observation_parts(f"Observation after step {step} ({tool_name})", images, proprio) + + @staticmethod + def nudge(): + return [_text("Please continue by calling exactly one tool (call done if you are finished).")] + + +def pick_keyframes(steps, initial, final, n=4): + """<= n agentview keyframes: start, up to n-2 informative intermediate frames, end (after settling).""" + out = [("start of attempt", initial)] if initial is not None and n >= 2 else [] + budget = n - len(out) - (1 if final is not None else 0) + cands = [s for s in steps if s.frame is not None] + if budget > 0 and cands: + events = [s for s in cands if s.name in ("push", "close_gripper", "open_gripper") + or s.report.get("touched_object") or s.report.get("touched_objects")] + pool = events if len(events) >= budget else cands + if len(pool) > budget: + idx = [round(i * (len(pool) - 1) / max(budget - 1, 1)) for i in range(budget)] if budget > 1 \ + else [len(pool) - 1] + pool = [pool[i] for i in sorted(set(idx))] + for s in sorted(pool, key=lambda s: s.step)[:budget]: + out.append((f"after step {s.step} ({s.name})", s.frame)) + if final is not None: + out.append(("end of attempt, after objects settled", final)) + return out[:n] + + +def wilson(k, n, z=1.96): + if n == 0: + return (float("nan"), float("nan")) + p = k / n + d = 1 + z * z / n + c = (p + z * z / (2 * n)) / d + h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d + return (max(0.0, c - h), min(1.0, c + h)) + + +def deep_strip_images(obj): + """JSON-friendly copy of conversation items (images -> paths).""" + obj = copy.copy(obj) + if isinstance(obj, dict): + return {k: (v.path if k == "image" else deep_strip_images(v)) for k, v in obj.items()} + if isinstance(obj, list): + return [deep_strip_images(v) for v in obj] + return obj diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/agent/runlog.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/agent/runlog.py new file mode 100644 index 0000000000000000000000000000000000000000..bf014446cedd7fef48c65010cd38ff23b6e3b9b0 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/agent/runlog.py @@ -0,0 +1,62 @@ +"""Run directory: config.json, events.jsonl (one JSON object per line), images/, summary.json.""" +import json +import os +import time + +import numpy as np + +from .images import encode_jpeg, resize + + +def _default(o): + if isinstance(o, np.ndarray): + return o.tolist() + if isinstance(o, (np.floating,)): + return float(o) + if isinstance(o, (np.integer,)): + return int(o) + if isinstance(o, (np.bool_,)): + return bool(o) + if hasattr(o, "__dataclass_fields__"): + return {k: getattr(o, k) for k in o.__dataclass_fields__} + return str(o) + + +def dumps(obj): + return json.dumps(obj, default=_default) + + +class RunLogger: + def __init__(self, run_dir, save_images=True, jpeg_quality=90): + self.run_dir = run_dir + self.save_images = save_images + self.jpeg_quality = jpeg_quality + os.makedirs(os.path.join(run_dir, "images"), exist_ok=True) + self.f = open(os.path.join(run_dir, "events.jsonl"), "a") + self.t0 = time.time() + + def event(self, type, **fields): + rec = dict(type=type, t=round(time.time() - self.t0, 3), **fields) + self.f.write(dumps(rec) + "\n") + self.f.flush() + return rec + + def write_json(self, name, obj): + with open(os.path.join(self.run_dir, name), "w") as f: + json.dump(obj, f, indent=1, default=_default) + + def save_image(self, ref, rel, res=None): + """Encode once (this exact JPEG is what the model receives) and save it under images/.""" + if res is not None: + ref.array = resize(ref.array, res) + ref.jpeg = encode_jpeg(ref.array, self.jpeg_quality) + if self.save_images: + path = os.path.join(self.run_dir, "images", rel) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "wb") as f: + f.write(ref.jpeg) + ref.path = os.path.relpath(path, self.run_dir) + return ref + + def close(self): + self.f.close() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/arm_specs/l3_card_shelf.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/arm_specs/l3_card_shelf.py new file mode 100644 index 0000000000000000000000000000000000000000..7e45931d7094d6260a85d4faa1791ad3e9d072c7 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/arm_specs/l3_card_shelf.py @@ -0,0 +1,65 @@ +"""Controlled arms for l3_card_shelf (2026-10-12, docs/14 sec. 6). + +Hidden variable: which end of the (symmetric-looking) card holds the 8 g weight. The centre of mass is compiled into +the card's MJCF along its local +x, so the heavy end is chosen purely by `card_yaw` (heavy end direction = yaw); +`heavy_near` / `heavy_edge` are bookkeeping only (nothing in reset / outcome / policies reads them), kept consistent. +No override changes geometry, mass or inertia, so no bounding-volume refit is involved. + +h0 : the same card turned end for end (yaw + 180 deg): identical pose and footprint, the weight now in the FAR end, + so the common-sense "slide the nearest end out" slides the light end and succeeds. +twin : the trap stays (the heavy end is the nearest end) but it points to the OPPOSITE shelf edge: the card is mirrored + through the shelf centre along its long axis (near gap, side offset, jitter mirrored) and keeps its weight in + the end that is now nearest. The right correction (slide the other, light end) is then over the opposite + edge. For an x-card this makes the near end the BACKWARD one, which the task's own sampler avoids because a + card tipping off the backward edge lands behind the shelf (agentview shows the shelf empty, not the card); + see the arm validation (results/l3_card_shelf/arms/). For an instance whose heavy end is already the far end + (naive succeeds there) the twin keeps the pose and turns the card end for end, so the weight is in the near + end and the heavy edge is again the opposite one. +reveal: which shelf edge the heavy end points to, in the F2 feedback's edge words. +""" +import numpy as np + +HIDDEN_KEYS = ("card_yaw", "heavy_near", "heavy_edge") + +OPPOSITE = {"forward": "backward", "backward": "forward", "left": "right", "right": "left"} +GLOSS = {"forward": "away from the robot", "backward": "towards the robot", "left": "on the robot's left", + "right": "on the robot's right"} + + +def _wrap(a): + return float((a + np.pi) % (2 * np.pi) - np.pi) + + +def h0(inst): + if not inst["heavy_near"]: + return {} # already the ordinary case for the naive habit (weight away from the end that gets slid out) + return dict(card_yaw=_wrap(inst["card_yaw"] + np.pi), heavy_near=False, heavy_edge=inst["far_edge"]) + + +def twin(inst): + if not inst["heavy_near"]: + return dict(card_yaw=_wrap(inst["card_yaw"] + np.pi), heavy_near=True, heavy_edge=inst["near_edge"]) + a = 0 if inst["card_along"] == "x" else 1 # world axis of the card's long side + c = list(inst["card_xy"]) + c[a] = 2.0 * inst["shelf_xy"][a] - c[a] + yaw = inst["card_yaw"] + yaw = np.pi - yaw if a == 0 else -yaw # reflection x -> -x (resp. y -> -y) of the card's heading + return dict(card_xy=[float(c[0]), float(c[1])], card_yaw=_wrap(yaw), near_edge=OPPOSITE[inst["near_edge"]], + far_edge=OPPOSITE[inst["far_edge"]], heavy_edge=OPPOSITE[inst["heavy_edge"]]) + + +def reveal(inst): + e = inst["heavy_edge"] + 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 " + f"{e} edge ({GLOSS[e]}), so its centre of mass is 2.8 cm from the card's middle towards that end.") + + +def fix(inst, params): + """Ladder Fix rung (docs/20): slide the light end out (two strokes to 2 and 3 cm), grasp the overhang, bin.""" + light = OPPOSITE[inst["heavy_edge"]] + return (f"A way to succeed: slide the light end out, not the heavy one. The light end is the one pointing towards " + f"the shelf's {light} edge ({GLOSS[light]}). With the gripper closed, press the fingertips lightly on the " + f"middle of the card and drag it slowly (speed about 0.08) along its long side towards that edge, in two " + f"strokes: first until that end sticks out about 2 cm beyond the edge, look, then until it sticks out " + f"about 3 cm. Then open the gripper, grasp the part that sticks out about 2 cm beyond the edge, at the " + f"card's height, lift it and drop the card into the bin.") diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/bddl.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/bddl.py new file mode 100644 index 0000000000000000000000000000000000000000..005b9e68143ff0e20a14f317587b78746b95311d --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/bddl.py @@ -0,0 +1,66 @@ +"""Tiny BDDL writer for tabletop problems. Layout is overridden at reset by the task, so the +regions here only need to be valid placement areas.""" +import os + +from .objects import GEN_DIR + + +def region(name, x0, y0, x1, y1, yaw=None): + s = f""" ({name} + (:target main_table) + (:ranges ( + ({x0} {y0} {x1} {y1}) + ) + )""" + if yaw is not None: + s += f""" + (:yaw_rotation ( + ({yaw} {yaw}) + ) + )""" + return s + "\n )\n" + + +def write_bddl(task_name, language, objects, fixtures=(), extra_regions="", goal="(And)"): + """objects / fixtures: list of (instance_name, category, region_name, (x0,y0,x1,y1)).""" + regs = "" + for inst, cat, rname, box in list(objects) + list(fixtures): + regs += region(rname, *box) + regs += extra_regions + fx = "\n".join(f" {i} - {c}" for i, c, _, _ in fixtures) + ob = "\n".join(f" {i} - {c}" for i, c, _, _ in objects) + init = "\n".join(f" (On {i} main_table_{r})" for i, _, r, _ in list(objects) + list(fixtures)) + text = f"""(define (problem LIBERO_Tabletop_Manipulation) + (:domain robosuite) + (:language {language}) + (:regions +{regs} ) + + (:fixtures + main_table - table +{fx} + ) + + (:objects +{ob} + ) + + (:obj_of_interest + ) + + (:init +{init} + ) + + (:goal + {goal} + ) + +) +""" + path = os.path.join(GEN_DIR, f"{task_name}.bddl") + tmp = f"{path}.{os.getpid()}.tmp" # atomic: concurrent builders must never read a half-written file + with open(tmp, "w") as f: + f.write(text) + os.replace(tmp, path) + return path diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/harnesses/framework_codex.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/harnesses/framework_codex.py new file mode 100644 index 0000000000000000000000000000000000000000..68a8d7d09835f053760d9d0ca718cd79959b97e4 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/harnesses/framework_codex.py @@ -0,0 +1,542 @@ +"""Shared launcher for robot frameworks using a native Codex backend. + +The external integration contract is Session.first_message(), Session.tool_specs(), +and Session.call(name, arguments). This launcher owns isolation, model configuration, +pins, trajectory collection and audits; framework plugins own their native loop. +Based on the validated RPent launcher; RPent's historical launcher remains frozen. +""" +import hashlib +import json +import os +import shutil +import subprocess +import time + +from . import contract as C +from . import pins +from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info, + gateway_env, new_run_dir, proxy_env, snapshot_tree) +from .codex import (AUTH_FILE, Codex, CATALOG_FILE, CATALOGS, DISABLE, EXPECTED_TOP_GENERIC, OFFICIAL_API, codex_bin, model_catalog, + request_fingerprint, toml_str) +from .fakeapi import FakeResponses +from .trajectory import TrajWriter + +ROOT = C.ROOT +JAIL_FRAMEWORK_DIR = "/opt/lffjail/hjail/framework" +BASE_PATH = "/usr/bin:/bin" +MCP_SERVER = "lff" +MCP_TOOLS = ["robot", "shell", "view_images"] +TREE_SKIP = {".git", "__pycache__", ".pytest_cache", ".ruff_cache", ".mypy_cache", "docs", "tests", ".github"} + + + +def tree_sha256(root, skip=TREE_SKIP): + """sha256 over (relative path, file sha256 / symlink target) of every file under root, skipping `skip` dirs.""" + h = hashlib.sha256() + for dp, dn, fn in os.walk(root): + dn[:] = sorted(d for d in dn if d not in skip) + for f in sorted(fn): + if f.endswith(".pyc"): + continue + p = os.path.join(dp, f) + rel = os.path.relpath(p, root) + if os.path.islink(p): + h.update(f"L {rel} {os.readlink(p)}\n".encode()) + else: + h.update(f"F {rel} {C.sha256_file(p)}\n".encode()) + return h.hexdigest() + + +def runtime_info(home): + """The robot framework runtime: upstream commit, our patch on top, and the tree hash of src + venv.""" + src, venv = os.path.join(home, "src"), os.path.join(home, "venv") + for d in (src, venv): + if not os.path.isdir(d): + raise HarnessRefused(f"robot framework runtime incomplete: {d} missing (run the selected framework setup script under integrations/)") + + def git(*a): + r = subprocess.run(["git", "-C", src] + list(a), capture_output=True, text=True, timeout=60) + return r.stdout.strip() if r.returncode == 0 else None + commit = git("rev-parse", "HEAD") + patch = subprocess.run(["git", "-C", src, "diff", "HEAD"], capture_output=True, timeout=60).stdout + untracked = (git("ls-files", "--others", "--exclude-standard") or "").split() + return dict(home=home, commit=commit, patch_sha256=hashlib.sha256(patch).hexdigest(), + untracked=sorted(u for u in untracked if "__pycache__" not in u), + tree_sha256=hashlib.sha256((tree_sha256(src) + tree_sha256(venv)).encode()).hexdigest()) + + +def jail_runtime_copy(home, tree): + """A verified read-only copy of the runtime under /opt/lffjail/hjail/framework (visible in the jail; /mnt is not).""" + dst = os.path.join(JAIL_FRAMEWORK_DIR, f"framework-{tree[:12]}") + stamp = os.path.join(dst, ".tree_sha256") + if os.path.exists(stamp) and open(stamp).read().strip() == tree: + return dst + os.makedirs(JAIL_FRAMEWORK_DIR, mode=0o755, exist_ok=True) + tmp = dst + ".tmp-" + os.urandom(3).hex() + shutil.copytree(os.path.join(home, "src"), os.path.join(tmp, "src"), symlinks=True, + ignore=shutil.ignore_patterns(".git", "__pycache__", "*.pyc")) + shutil.copytree(os.path.join(home, "venv"), os.path.join(tmp, "venv"), symlinks=True, + ignore=shutil.ignore_patterns("__pycache__", "*.pyc")) + got = hashlib.sha256((tree_sha256(os.path.join(tmp, "src")) + tree_sha256(os.path.join(tmp, "venv"))).encode() + ).hexdigest() + if got != tree: + shutil.rmtree(tmp, ignore_errors=True) + raise HarnessRefused(f"copy of the robot framework runtime does not match its tree hash ({got[:12]} != {tree[:12]})") + for dp, dn, fn in os.walk(tmp): + os.chmod(dp, 0o755) + for f in fn: + p = os.path.join(dp, f) + if not os.path.islink(p): + os.chmod(p, os.stat(p).st_mode | 0o444) + with open(os.path.join(tmp, ".tree_sha256"), "w") as f: + f.write(tree) + if os.path.exists(dst): + shutil.rmtree(dst) + os.rename(tmp, dst) + return dst + + +def codex_overrides(effort, catalog_path): + """The main table's Codex configuration (lffbench/harnesses/codex.py Codex.config_args / --disable), as -c + overrides for robot framework's planner; the provider and the MCP server URL are robot framework's own (CODEX_BASE_URL, in-process).""" + return (["model_reasoning_effort=" + toml_str(effort), + "include_permissions_instructions=false", "include_environment_context=false", + "include_collaboration_mode_instructions=false", "skills.include_instructions=false", + "skills.bundled.enabled=false", 'web_search="disabled"', + f"mcp_servers.{MCP_SERVER}.enabled_tools=" + json.dumps(MCP_TOOLS), + f'mcp_servers.{MCP_SERVER}.default_tools_approval_mode="approve"', + f"mcp_servers.{MCP_SERVER}.required=true", f"mcp_servers.{MCP_SERVER}.startup_timeout_sec=60", + f"mcp_servers.{MCP_SERVER}.tool_timeout_sec=900", + "model_catalog_json=" + toml_str(catalog_path)] + + [f"features.{f}=false" for f in DISABLE]) + + +def _items(stream_path): + """Codex app-server notifications of one robot framework session (robot framework writes them as JSONL).""" + out = [] + if not os.path.exists(stream_path): + return out + for line in open(stream_path, encoding="utf-8", errors="replace"): + try: + out.append(json.loads(line)) + except ValueError: + continue + return out + + +def _item_of(ev): + it = (ev.get("payload") or {}).get("item") or {} + return it.get("root", it) if isinstance(it, dict) else {} + + +class RobotFrameworkCodex(HarnessAdapter): + name = "framework_codex" + runtime_home = "/nonexistent" + runtime_module = "lff_integration.run" + default_steps = 500 + uses_mcp = False + uses_gateway = True + can_resume = False + clean_dirs = ("home", "codex_home", "tmp", "out") + clean_allowed = {"codex_home": (CATALOG_FILE,)} + ancestor_files = ("AGENTS.md", "AGENTS.override.md", ".codex") + capabilities = dict( + only_benchmark_tools=Cap("partial", "preflight", "Codex generic catalog (as the main table): our 3 tools as " + "mcp__lff functions + residual resource×3 / request_user_input; robot framework registers " + "no tool of its own (no file tools, no finish)"), + images_reach_model=Cap("yes", "probe", "gateway content blocks preserved by the framework bridge, " + "JPEG with its own MIME type"), + non_persistent_session=Cap("yes", "probe", "robot framework's threads only in the one-time CODEX_HOME, removed after the " + "run; no preloaded or cross-episode framework memory"), + pinned_version=Cap("yes", "launch", "codex binary sha256 + robot framework commit / patch / tree hash (src + venv) in " + "harness.json; pin per version and tree"), + machine_readable_events=Cap("yes", "stream", "Codex app-server notifications per robot framework session " + "(codex.out.stream.jsonl) + robot framework run.json"), + tool_calls_logged=Cap("yes", "stream", "mcpToolCall items + gateway_transcript (named framework face) + events.jsonl"), + model_and_effort=Cap("yes", "preflight", "model and effort in the request checked"), + persistent_memory=Cap("absent", "probe", "memories feature off; empty one-time CODEX_HOME; robot framework memory not " + "constructed"), + instruction_file_injection=Cap("absent", "probe", "project_doc_max_bytes=0, empty CODEX_HOME, no skills"), + web_access=Cap("absent", "preflight", "web_search disabled (not in the tool list)"), + host_file_read=Cap("absent", "preflight", "no file tools; the only shell is the gateway's jailed shell"), + builtin_shell=Cap("absent", "preflight", "shell_tool and unified_exec disabled (not in the tool list)"), + subagent_delegation=Cap("absent", "preflight", "multi_agent disabled; no collaboration tools in the request"), + background_execution=Cap("absent", "preflight", "no background tool in the request"), + ) + + def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False, + jail=False, auth="apikey", catalog="generic", sessions=1, attempts_per_session=0, max_turns=500, + home=None, provider=None, auth_home=None): + """Common controlled Codex SDK launcher. + + The plugin entrypoint interprets its declared loop options. For SenseNova, + max_turns is the upstream SDK-step limit, not a provider-response count. + Robot commands, simulation time and tool budgets are always server-owned. + """ + if auth not in ("apikey", "chatgpt"): + raise ValueError("framework_codex auth must be apikey or chatgpt") + if catalog not in CATALOGS: + raise ValueError(f"catalog must be one of {CATALOGS}") + self.auth, self.catalog = auth, catalog + self._auth_manager = Codex(auth=auth, auth_home=auth_home, api_env=api_env, base_url=base_url, catalog=catalog) + self.api_env = self._auth_manager.api_env + self.base_url = self._auth_manager.base_url + self.clean_allowed = {"codex_home": ((AUTH_FILE,) if auth == "chatgpt" else ()) + (CATALOG_FILE,)} + self.timeout_s, self.pins_dir, self.allow_unpinned = timeout_s, pins_dir, allow_unpinned + self.sessions, self.attempts_per_session, self.max_turns = int(sessions), int(attempts_per_session), \ + int(max_turns) + self.home = home or os.environ.get("LFF_FRAMEWORK_HOME") or self.runtime_home + self.proxy = proxy_env() + self._version = None + self._runtime = None + self.runtime_dir = self.home + if jail: + from .jail import HarnessJail + self.jail = HarnessJail(codex_bin(), proc="static") + + # ------------------------------------------------------------------------------------------------ identity + def runtime(self): + if self._runtime is None: + self._runtime = runtime_info(self.home) + if self.jail is not None: + self.runtime_dir = jail_runtime_copy(self.home, self._runtime["tree_sha256"]) + return self._runtime + + def version(self): + if self._version is None: + b = codex_bin() + out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent", + CODEX_HOME="/nonexistent"), + capture_output=True, text=True, timeout=60) + v = (out.stdout.strip().split() or ["?"])[-1] + rt = self.runtime() + self._version = dict(version=v, binary=binary_info(b), + framework=dict(commit=rt["commit"], patch_sha256=rt["patch_sha256"], + tree_sha256=rt["tree_sha256"], untracked=rt["untracked"])) + return self._version + + def pin_key(self, ep): + v = self.version() + mode = "" if self.auth == "apikey" else "-chatgpt" + name = f"{self.name}{mode}-{self.catalog}-{v['framework']['tree_sha256'][:12]}" + return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort) + + def anchor_pin_key(self, ep): + """The main table's codex pin for the same model / effort (apikey, same catalog).""" + v = self.version() + name = "codex" + ("" if self.auth == "apikey" else "-chatgpt") + ("" if self.catalog == "native" else f"-{self.catalog}") + return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort) + + def auth_info(self): + if self.auth == "chatgpt": + return self._auth_manager.auth_info() + return dict(mode="apikey", credential_var="CODEX_API_KEY", credential_set=bool(self.api_env.get( + "OPENAI_API_KEY")), keys=["CODEX_API_KEY"]) + + def config_info(self): + return dict(auth=self.auth, catalog=self.catalog, sessions=self.sessions, attempts_per_session=self.attempts_per_session, + max_turns=self.max_turns, framework=self.version()["framework"]) + + # ------------------------------------------------------------------------------------------------ prepare + def _state_dirs(self, hexname=None): + root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate") + os.makedirs(root, exist_ok=True) + state = dict(state=root, **{k: os.path.join(root, k) for k in ("home", "codex_home", "tmp", "out")}) + for k in ("home", "codex_home", "tmp", "out"): + os.makedirs(state[k], exist_ok=True) + return state + + def _install_catalog(self, codex_home, ep): + cat, src = model_catalog(self.catalog, self.version()["version"], ep.model, None, ep.effort) + path = os.path.join(codex_home, CATALOG_FILE) + with open(path, "w") as f: + json.dump(cat, f) + return path, C.sha256_file(path), os.path.relpath(src, ROOT) + + def argv(self, ep, out_dir, sessions=None, preflight=False): + py = os.path.join(self.runtime_dir, "venv", "bin", "python") + return [py, "-m", self.runtime_module, "--model", ep.model, "--effort", ep.effort, "--out", out_dir, + "--sessions", str(sessions or self.sessions), "--attempts-per-session", str(self.attempts_per_session), + "--max-turns", str(self.max_turns), "--timeout-s", str(int(self.timeout_s) - 60)] \ + + (["--no-continue"] if preflight else []) + + def env(self, state, ep, base_url, work): + e = dict(PATH=BASE_PATH, HOME=state["home"], TMPDIR=state["tmp"], CODEX_HOME=state["codex_home"], + CODEX_BIN=(self.jail.binary_jailed if self.jail is not None else codex_bin()), + CODEX_BASE_URL=base_url, FRAMEWORK_CODEX_SANDBOX="read_only", FRAMEWORK_MCP_SERVER_NAME=MCP_SERVER, + FRAMEWORK_CODEX_CONFIG_OVERRIDES=json.dumps(codex_overrides( + ep.effort, os.path.join(state["codex_home"], CATALOG_FILE))), + FRAMEWORK_REPO_ROOT=work, LFF_FRAMEWORK_FACE=self.name, PYTHONPATH=os.path.join(self.runtime_dir, "src"), + PYTHONDONTWRITEBYTECODE="1", PYTHONUNBUFFERED="1", LANG="C.UTF-8") + if self.auth == "chatgpt": + # The native API provider declares env_key. Codex app-server still requires that + # variable even with requires_openai_auth=true, so select a separate provider + # with no env_key. Do not inject a dummy key or modify the upstream runtime. + provider_id = "lffsubscription" + overrides = json.loads(e["FRAMEWORK_CODEX_CONFIG_OVERRIDES"]) + overrides += ["model_provider=" + toml_str(provider_id), + f"model_providers.{provider_id}.name=" + toml_str(provider_id), + f"model_providers.{provider_id}.wire_api=\"responses\"", + f"model_providers.{provider_id}.base_url=" + toml_str(base_url), + f"model_providers.{provider_id}.requires_openai_auth=true"] + e["FRAMEWORK_CODEX_CONFIG_OVERRIDES"] = json.dumps(overrides) + e.update(self.proxy) + if self.api_env.get("OPENAI_API_KEY"): + e["CODEX_API_KEY"] = self.api_env["OPENAI_API_KEY"] + return e + + def prepare(self, ep, first_message, reuse_state=None): + self.version() + work = new_run_dir("/tmp/lffrun") + state = reuse_state or self._state_dirs(os.path.basename(work)) + if self.jail is not None: + self.jail.stderr_dir = ep.log_dir + if not reuse_state and os.listdir(state["codex_home"]): + raise HarnessRefused("CODEX_HOME is not empty") + cat_path, cat_sha, cat_src = self._install_catalog(state["codex_home"], ep) + return LaunchSpec(argv=self.argv(ep, state["out"]), env=self.env(state, ep, self.base_url, work), cwd=work, + run_dir=work, state_dirs=state, first_message=first_message, + stdout_path=os.path.join(ep.log_dir, "framework_stdout.txt"), + stderr_path=os.path.join(ep.log_dir, "framework_stderr.txt"), + config_files=dict(model_catalog_json=dict(path=cat_path, sha256=cat_sha, source=cat_src, + catalog=self.catalog, code_mode=False)), + timeout_s=self.timeout_s) + + def config_sha256(self, spec, ep): + argv = [a.replace(spec.state_dirs["out"], "").replace(self.runtime_dir, "") + for a in spec.argv] + hidden = ("HOME", "TMPDIR", "CODEX_HOME", "CODEX_BIN", "CODEX_API_KEY", "FRAMEWORK_REPO_ROOT", "PYTHONPATH", + "LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") + PROXY_KEYS + NO_PROXY_KEYS + env = {k: v for k, v in spec.env.items() if k not in hidden} + env["FRAMEWORK_CODEX_CONFIG_OVERRIDES"] = env.get("FRAMEWORK_CODEX_CONFIG_OVERRIDES", "").replace( + spec.state_dirs["codex_home"], "") + cat = (spec.config_files.get("model_catalog_json") or {}).get("sha256") + return C.sha256_json(dict(argv=argv, env=env, model_catalog_sha256=cat, + framework_tree_sha256=self.version()["framework"]["tree_sha256"])) + + # ------------------------------------------------------------------------------------------------ launch + def launch(self, spec, ep, skip_preflight=False): + """harness_run starts the gateway after prepare(), right before launch: hand its address to the process.""" + self._auth_manager._install_auth(spec.state_dirs["codex_home"]) + spec.env.update(gateway_env(ep.log_dir)) + return super().launch(spec, ep, skip_preflight=skip_preflight) + + def cleanup(self, spec): + self._auth_manager._sync_auth_back(spec.state_dirs.get("codex_home", "")) + super().cleanup(spec) + + def preflight(self, spec, ep, record_dir=None): + """The same framework process, one session, against a local fake Responses server that answers with text + only: no tool call reaches the gateway. Checks the first request (tools, developer message, parameters, + sandbox, robot framework's prefix + our first message) against the pins.""" + t0 = time.time() + fake = FakeResponses([[("text", "preflight ok")]], record_dir=record_dir).start() + pre = self._state_dirs() + try: + self._auth_manager._install_auth(pre["codex_home"]) + self._install_catalog(pre["codex_home"], ep) + env = self.env(pre, ep, fake.base_url, spec.cwd) + if self.auth == "apikey": + env["CODEX_API_KEY"] = "sk-preflight-not-a-key" + env.update({k: spec.env[k] for k in ("LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") if k in spec.env}) + argv = self.argv(ep, pre["out"], sessions=1, preflight=True) # no status call on the episode + r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd, + stdin=subprocess.DEVNULL, capture_output=True, timeout=300) + reqs = fake.model_requests() + if not reqs: + # Native planners may record failures only in run.json, with empty stdout/stderr. + record = os.path.join(pre["out"], "run.json") + detail = "" + if os.path.isfile(record): + with open(record) as f: + failed_run = json.load(f) + detail = "; ".join(str(s.get("error")) for s in failed_run.get("sessions", []) if s.get("error")) + raise HarnessRefused(f"preflight: no model request (rc={r.returncode}): " + f"{(r.stdout + r.stderr).decode('utf-8', 'replace')[-1200:]} {detail[-1200:]}") + body = reqs[0][1] + fp, problems = request_fingerprint(body, spec.cwd, spec.first_message, EXPECTED_TOP_GENERIC) + problems = [p for p in problems if not p.startswith("user input is not exactly our first message")] + users = [c.get("text") for it in body.get("input") or [] if it.get("type") == "message" + and it.get("role") == "user" for c in it.get("content") or []] + prefix = None + if len(users) != 1 or not users[0].endswith(spec.first_message): + problems.append(f"the first user message does not end with our first message ({len(users)} blocks)") + else: + prefix = users[0][:-len(spec.first_message)] + effort = (fp["params"].get("reasoning") or {}).get("effort") + if effort != ep.effort: + problems.append(f"reasoning.effort in request {effort!r} != {ep.effort!r}") + if fp["params"].get("model") != ep.model: + problems.append(f"model in request {fp['params'].get('model')!r} != {ep.model!r}") + if os.listdir(spec.cwd): + problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}") + mid_sha = C.sha256_json(fp) + full = dict(middle=fp, framework_prefix=prefix) + fp_sha = C.sha256_json(full) + anchor = pins.load(self.anchor_pin_key(ep), self.pins_dir) + out = dict(fingerprint_sha256=fp_sha, middle_fingerprint_sha256=mid_sha, + framework_prefix_sha256=C.sha256_text(prefix) if prefix is not None else None, + framework_prefix_chars=len(prefix) if prefix is not None else None, + developer_chars=fp["developer_chars"], n_requests=len(reqs), + top_tools=[t["name"] for t in fp["tools"]], catalog=self.catalog, effort_in_request=effort, + model_in_request=fp["params"].get("model"), sandbox=fp["sandbox"], + dt_s=round(time.time() - t0, 1), problems=problems, + anchor_pin=anchor and dict(key=anchor["key"], fingerprint_sha256=anchor["fingerprint_sha256"])) + if anchor is None: + out["anchor_status"] = "no main-table pin for this model / effort" + elif anchor["fingerprint_sha256"] != mid_sha: + problems.append(f"Codex request {mid_sha[:12]} != main-table pin {anchor['fingerprint_sha256'][:12]} " + f"({anchor['key']}): the middle layer is not the main table's") + else: + out["anchor_status"] = "match" + pin = pins.load(self.pin_key(ep), self.pins_dir) + out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"]) + out["fingerprint"] = full + if problems: + raise HarnessRefused("preflight: " + "; ".join(problems)) + if pin is None: + if not self.allow_unpinned: + raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck " + f"with --write-pins after the self-check passes)") + out["pin_status"] = "unpinned (allowed)" + elif pin["fingerprint_sha256"] != fp_sha: + raise HarnessRefused(f"preflight: fingerprint {fp_sha[:12]} != pinned {pin['fingerprint_sha256'][:12]} " + f"({pin['key']})") + else: + out["pin_status"] = "match" + return out + finally: + fake.stop() + self._auth_manager._sync_auth_back(pre["codex_home"]) + shutil.rmtree(pre["state"], ignore_errors=True) + + # ------------------------------------------------------------------------------------------------ collect + def collect(self, h): + spec, ep = h.spec, h.ep + dst = os.path.join(ep.log_dir, "framework") + if os.path.isdir(spec.state_dirs["out"]): + shutil.copytree(spec.state_dirs["out"], dst, dirs_exist_ok=True) + run = {} + if os.path.exists(os.path.join(dst, "run.json")): + run = json.load(open(os.path.join(dst, "run.json"))) + tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl")) + usage = dict(input=0, cached=0, output=0, reasoning=0) + items, threads, errors = [], [], [] + for sdir in sorted(os.listdir(os.path.join(dst, "sessions"))) if os.path.isdir(os.path.join(dst, "sessions")) \ + else []: + last = None + for ev in _items(os.path.join(dst, "sessions", sdir, "codex.out.stream.jsonl")): + m = ev.get("method") or ev.get("type") + p = ev.get("payload") or {} + if m == "thread/tokenUsage/updated": + last = (p.get("token_usage") or {}).get("total") or last + if p.get("thread_id") and p["thread_id"] not in threads: + threads.append(p["thread_id"]) + elif m in ("error", "fatal", "timeout"): + errors.append(ev) + elif m == "item/completed": + it = _item_of(ev) + t = it.get("type") + items.append(t) + if t == "agentMessage": + tw.add_step("agent", message=it.get("text", "")) + elif t == "reasoning": + tw.add_step("agent", reasoning=json.dumps(it.get("summary") or it.get("content") or "")) + elif t in ("mcpToolCall", "dynamicToolCall", "commandExecution", "fileChange"): + name = it.get("tool") or t + tw.add_step("agent", tool_calls=[dict(tool_call_id=it.get("id"), function_name=name, + native_name=f"{it.get('server', '')}.{name}", + item_type=t, arguments=it.get("arguments"), + session=sdir)]) + res = it.get("result") or {} + texts = [c.get("text", "") for c in res.get("content") or [] if c.get("type") == "text"] + imgs = sum(1 for c in res.get("content") or [] if c.get("type") == "image") + tw.add_result(it.get("id"), "\n".join(texts) if texts else json.dumps(it.get("error")), + bool(it.get("error")) or it.get("status") == "failed", imgs) + if last: + usage["input"] += last.get("input_tokens") or 0 + usage["cached"] += last.get("cached_input_tokens") or 0 + usage["output"] += last.get("output_tokens") or 0 + usage["reasoning"] += last.get("reasoning_output_tokens") or 0 + # Framework close-out uses the same counted gateway shell, outside + # the model stream. Keep it visible in trajectories and tool totals. + session_record = next((s for s in run.get("sessions", []) + if sdir == f"session_{s['number']:03d}"), {}) + handoff = session_record.get("handoff") or {} + if handoff: + call_id = f"framework-handoff-{sdir}" + tw.add_step("framework", tool_calls=[dict( + tool_call_id=call_id, function_name="shell", native_name=f"{MCP_SERVER}.shell", + item_type="frameworkToolCall", arguments=handoff["arguments"], session=sdir)]) + tw.add_result(call_id, "\n".join(c.get("text", "") for c in handoff["content"] + if c.get("type") == "text")) + v = self.version() + tw.set_header(session_id=",".join(threads), source="framework/sessions/*/codex.out.stream.jsonl", + agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort, + framework=v["framework"]), tools=EXPECTED_TOP_GENERIC) + tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], item_types=sorted(set(items)), + run={k: run.get(k) for k in ("stop", "finished", + "attempts_failed", "tool_calls")}, + sessions=len(run.get("sessions") or [])), + total_prompt_tokens=usage["input"], total_completion_tokens=usage["output"], + total_cached_tokens=usage["cached"], total_cost_usd=None, reasoning_tokens=usage["reasoning"]) + tw.write() + h.info.update(items=items, traj=tw, threads=threads, errors=errors, run=run) + return tw + + # ------------------------------------------------------------------------------------------------ audit + def audit(self, h): + spec, ep = h.spec, h.ep + v, notes = [], [] + items = h.info.get("items") or [] + bad = sorted({i for i in items if i not in ("userMessage", "agentMessage", "reasoning", "mcpToolCall", + "plan", "hookPrompt")}) + if bad: + v.append(f"items other than messages / reasoning / MCP calls: {bad}") + residual = [] + tw = h.info.get("traj") + for st in (tw.steps if tw else []): + for tc in st["tool_calls"]: + if tc["native_name"] == f"{MCP_SERVER}.{tc['function_name']}" and tc["function_name"] in MCP_TOOLS: + continue + if tc["function_name"] in ("list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"): + residual.append(tc["function_name"]) + else: + v.append(f"unexpected tool call {tc['native_name']}") + if residual: + notes.append(f"residual MCP-resource tool calls (empty): {residual}") + if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env): + v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}") + run = h.info.get("run") or {} + nsess = len(run.get("sessions") or []) + if len(h.info.get("threads") or []) > max(1, nsess): + v.append(f"{len(h.info['threads'])} Codex threads for {nsess} robot framework sessions") + if nsess > 1: + notes.append(f"{nsess} robot framework sessions (handoff after a session ended before the episode was over)") + if run.get("stop") not in (None, "episode over"): + notes.append(f"robot framework stopped: {run.get('stop')}") + left = dict(codex_home=snapshot_tree(spec.state_dirs["codex_home"]), home=snapshot_tree(spec.state_dirs["home"]), + work=snapshot_tree(spec.cwd)) + if left["work"]: + v.append(f"files in the work dir: {left['work']}") + foreign = [f for f in left["codex_home"] if f.startswith(("sessions/", "archived_sessions/")) + and not any(t in f for t in (h.info.get("threads") or []))] + if foreign: + v.append(f"session files other than this run's threads: {foreign}") + gt = os.path.join(ep.log_dir, "gateway_transcript.jsonl") + faces = set() + if os.path.exists(gt): + for line in open(gt): + try: + d = json.loads(line) + except ValueError: + continue + if d.get("ev") == "tool" and d.get("face"): + faces.add(d["face"]) + if faces - {self.name}: + v.append(f"gateway calls from other access paths: {sorted(faces)}") + out = dict(harness=self.name, violations=v, notes=notes, files_left=left, gateway_faces=sorted(faces), + item_types=sorted(set(items)), errors=h.info.get("errors"), run_stop=run.get("stop"), ok=not v) + with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f: + json.dump(out, f, indent=1) + return out diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/harnesses/reference.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/harnesses/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..93a7ecef47a9e0f879e60d8521618b4378658db2 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/harnesses/reference.py @@ -0,0 +1,143 @@ +"""The reference driver scripts/api_player.py wrapped as an adapter ("ours", the main table's harness). + +Nothing about the driver changes: it is started exactly as api_batch.py always started it (--style la), it makes its +own first `status` call, keeps its own transcript.jsonl and enforces the tool-call budget itself. The adapter only +adds harness.json, trajectory.jsonl (converted from transcript.jsonl) and harness_audit.json, like for every harness. +""" +import json +import os +import sys + +from . import contract as C +from .base import Cap, HarnessAdapter, LaunchSpec, reference_instructions +from .trajectory import TrajWriter + +ROOT = C.ROOT +PLAYER = os.path.join(ROOT, "scripts", "api_player.py") +DRIVER_FILES = ["scripts/api_player.py", "lffbench/agent/context.py", "lffbench/agent/backends/base.py", + "lffbench/agent/backends/anthropic_messages.py", "lffbench/agent/backends/openai_responses.py", + "lffbench/agent/backends/gemini.py", "lffbench/agent/backends/chat_completions.py"] + + +class Reference(HarnessAdapter): + name = "ours" + capabilities = dict( + only_benchmark_tools=Cap("yes", "launch", "the driver sends exactly TOOL_LA / SHELL_TOOL / VIEW_TOOL_LA"), + images_reach_model=Cap("yes", "probe", "FileImage sends the JPEG bytes the server wrote"), + non_persistent_session=Cap("yes", "launch", "no state outside the run's log dir"), + pinned_version=Cap("yes", "launch", "sha256 of the driver + backend sources"), + machine_readable_events=Cap("yes", "stream", "transcript.jsonl"), + tool_calls_logged=Cap("yes", "stream", "transcript.jsonl tool events + events.jsonl"), + model_and_effort=Cap("yes", "launch", "--model / --effort mapped per provider (docs/12 §2)"), + persistent_memory=Cap("absent", "launch", "strictly append-only context within the run only"), + instruction_file_injection=Cap("absent", "launch", "only README.md of the sandbox"), + web_access=Cap("absent", "launch", "no such tool"), + host_file_read=Cap("absent", "probe", "shell jailed, view_images confined to the workspace"), + builtin_shell=Cap("absent", "launch", "only the jailed shell tool"), + subagent_delegation=Cap("absent", "launch", "no such tool"), + background_execution=Cap("absent", "launch", "no such tool"), + ) + + def __init__(self, provider="anthropic", env=None, timeout_s=10800, python=None, **_): + self.provider = provider + self.base_env = dict(env if env is not None else os.environ) + self.timeout_s = timeout_s + self.python = python or sys.executable + + def version(self): + per = {f: C.sha256_file(os.path.join(ROOT, f)) for f in DRIVER_FILES if os.path.exists(os.path.join(ROOT, f))} + sha = C.sha256_json(per) + return dict(version=f"api_player@{sha[:12]}", sources_sha256=sha, binary=dict(path=PLAYER, sha256=per.get( + "scripts/api_player.py"))) + + def prepare(self, ep, first_message=None): + argv = [self.python, PLAYER, "--session", ep.session_path, "--provider", ep.provider or self.provider, + "--model", ep.model, "--effort", ep.effort, "--style", "la"] + return LaunchSpec(argv=argv, env=self.base_env, cwd=ROOT, first_message="", + stdout_path=os.path.join(ep.log_dir, "api_player.log"), + stderr_path=os.path.join(ep.log_dir, "api_player.log"), timeout_s=self.timeout_s) + + def config_sha256(self, spec, ep): + return C.sha256_json(dict(argv=[a.replace(ep.session_path, "") for a in spec.argv[1:]])) + + def launch(self, spec, ep, skip_preflight=True): + # stdout and stderr go to the same api_player.log (as before the adapter layer) + import subprocess + import time + from .base import RunHandle, env_keys_of + spec.preflight = dict(skipped=True, reason="reference driver: tools and instructions are our own code") + log = open(spec.stdout_path, "ab") + h = RunHandle(spec=spec, ep=ep, t_start=time.time()) + h.proc = subprocess.Popen(spec.argv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=log, + stderr=subprocess.STDOUT, start_new_session=True) + h.pid = h.proc.pid + time.sleep(0.2) + h.env_observed_keys = env_keys_of(h.pid) + return h + + def collect(self, h): + ep = h.ep + tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl")) + p = os.path.join(ep.log_dir, "transcript.jsonl") + start, end, first_user, tot = None, None, None, dict(inp=0, out=0, cached=0) + last_agent = None + for line in (open(p) if os.path.exists(p) else []): + d = json.loads(line) + e = d.get("ev") + if e == "start": + start = d + elif e == "user": + if first_user is None: + first_user = d.get("text") + tw.add_step("user", message=d.get("text", ""), timestamp=d.get("t")) + elif e == "assistant": + u = d.get("usage") or {} + tot["inp"] += u.get("input_tokens", 0) + tot["out"] += u.get("output_tokens", 0) + tot["cached"] += u.get("cached_tokens", 0) + last_agent = tw.add_step("agent", message=d.get("text") or "", reasoning=d.get("reasoning_summary") or "", + timestamp=d.get("t"), tool_calls=[dict(tool_call_id=c["id"], + function_name=c["name"], + native_name=c["name"], + arguments=c["arguments"]) + for c in d.get("tool_calls") or []], + metrics=dict(prompt_tokens=u.get("input_tokens"), + completion_tokens=u.get("output_tokens"), + cached_tokens=u.get("cached_tokens"))) + elif e == "tool" and last_agent is not None: + pending = [tc for tc in last_agent["tool_calls"] + if not any(r["source_call_id"] == tc["tool_call_id"] + for r in last_agent["observation"]["results"])] + if pending: + tw.add_result(pending[0]["tool_call_id"], d.get("output", ""), False, len(d.get("images") or [])) + elif e in ("end", "abort"): + end = d + tw.set_header(session_id=os.path.basename(ep.log_dir), source="transcript.jsonl", + agent=dict(name=self.name, version=self.version()["version"], model_name=ep.model, + effort=ep.effort, provider=ep.provider or self.provider), + tools=[t["name"] for t in (start or {}).get("tools") or []]) + tw.set_final(h.exit_reason if not end or end.get("ev") == "end" else "abort: " + str(end.get("reason")), + native_result=end, total_prompt_tokens=tot["inp"], total_completion_tokens=tot["out"], + total_cached_tokens=tot["cached"]) + tw.write() + h.info.update(traj=tw, start=start, first_user=first_user) + if start and first_user is not None: # the same string a native harness gets as its first message + readme = open(os.path.join(ep.sandbox, "README.md")).read() + h.info["instructions_match_readme"] = start.get("instructions") == reference_instructions(readme) + # the same composition as base.first_message_text: identical sha256 for the same instance + h.spec.first_message = start.get("instructions", "") + "\n\n" + first_user + return tw + + def audit(self, h): + ep = h.ep + start = h.info.get("start") or {} + tools, _ = C.tool_schemas() + v = [] + if start and start.get("tools") != tools: + v.append("driver tools differ from the contract's tool schemas") + if h.info.get("instructions_match_readme") is False: + v.append("driver instructions != preamble + README") + out = dict(harness=self.name, violations=v, ok=not v, notes=["reference driver: no preflight needed"]) + with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f: + json.dump(out, f, indent=1) + return out diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/__init__.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/l5_slide.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/l5_slide.py new file mode 100644 index 0000000000000000000000000000000000000000..6ee239b7ba2793288aeaaa5e5d4f0a5b11c835f5 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/l5_slide.py @@ -0,0 +1,577 @@ +"""L5-A slide_to_target: strike the cube so that it slides on its own and comes to rest inside the target zone. + +Hidden variable: cube-table sliding friction mu (log-uniform in [0.035, 0.10]) -- the cube looks the +same for every mu. With the default push speed the cube overshoots on slippery instances and stops +short on grippy ones; the only way to get it right is to infer from where the cube stopped how hard +to push next time (cf. MemMimic push_cube, iterative pushing). + +Strikes per attempt: not limited (2026-10-19, user). From 2026-10-08 the instruction allowed ONE strike per attempt +(one move command pushing the cube, the gripper advancing at most 4 cm after the first touch), to stop slow pushes that +carry the cube to the target so that friction never matters (exp1 / cla1 Claude, la2 GPT: 0.05 m/s pushes). That rule +also moved within-attempt correction (overshot -> fetch the cube back -> strike again) to the next attempt. The +loophole is now closed by the success rule instead: + +Success: when the attempt ends the cube is at rest, on the table, in the square (see "Target" below), AND it got there +by a free slide of at least D_MIN: from the last moment the robot touched it (any robot or gripper geom, contacts +checked at every 2 ms physics substep; holding it counts as touching) to its final position the cube slid >= D_MIN with +nothing touching it. A touch that leaves a resting cube where it was (< 1 mm) is ignored. This fails a quasi-static push +into the square (free slide 0-1.2 cm measured), placing the cube there with the gripper (0 cm) and putting it just in +front of the square and tapping it (< D_MIN); see the task card for the adversarial checks and why D_MIN = 3 cm. + +Error events: every strike (a robot contact that moved the cube followed by a free slide of >= STRIKE_MIN) is logged +when the cube comes to rest; it is "missed" if the cube then lies outside the square (past / short / beside). +`n_missed_strikes`, `trap_fired` (>= 1 missed strike) and `recovered_in_attempt` (trap fired and the attempt then +succeeded) are in the outcome, as in l7_key_turn; `irrecoverable` = the cube fell off the table or lies outside the +arm's reach (the attempt is not ended for it). + +Observation fix (2026-10-19): a strike used to return while the cube was still sliding, and `observe` does not advance +the simulation, so agents saw the cube half-way (cla2: "2.2 cm short", it then slid to 7.0 cm past the centre). +SlideSkills.move_to / set_gripper now hold the arm still after the motion until the cube is at rest (or WAIT_MAX), +so every reply and image shows the cube where it stopped. The waiting time counts as simulated motion time. + +Target (2026-10-19, user; before: completely inside the square on all four sides, centre within +-1 cm): the agentview +camera looks at the square from the far side (the cube is pushed towards it), and a cube that sticks out past the far +edge by up to ~1 cm covers the far green line but shows < 2 px of red beyond it in the 512 x 512 image, which looks like +"inside / on the line" (self-test: 0.8 cm past the inner edge looked inside). So on the far side the cube may now lie on +the far green line: the instruction says it must not stick out beyond that line; judged, its centre may be up to +TOL_PAST = 2.0 cm past the square's centre (front face <= 4 mm beyond the line's outer edge). From 2.0 cm on, every one +of 25 measured instances shows >= 2 px of red beyond the line (task card). The near side and the sides stay "completely +inside" (+-1 cm): the near-side band cannot be made visible in the agentview by any tolerance (the cube's own body hides +the near line), and relaxing it would let the 0.30 m/s strike pass on short-stopping instances (task card). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, box_xml, register_generated +from ..skills import DT, Skills, _rot_err +from ..task_base import LFFTask, register_task + +CUBE = "cube_1" +CUBE_HALF = 0.02 +D_MIN = 0.03 # the cube's last free slide (after its last contact with the robot) must be at least this long +STRIKE_MIN = 0.01 # a contact that moved the cube, followed by a free slide of >= 1 cm, counts as a strike +TOUCH_MOVE = 0.001 # a contact episode moved the cube if the cube ends >= 1 mm (3-D) from where it was at its start +EP_GAP = 25 # physics substeps (one control step, 50 ms) without robot contact end a contact episode +V_REST, W_REST = 0.003, 0.05 # cube at rest: linear speed below 3 mm/s and angular speed below 0.05 rad/s ... +REST_SUB = 25 # ... for 25 consecutive substeps (50 ms) +WAIT_MAX = 100 # control steps (5 s) a command may hold the arm waiting for the cube to come to rest +ON_TABLE = 0.005 # cube resting on the table: centre within 5 mm of TABLE_Z + CUBE_HALF +OFF_TABLE_Z = envs.TABLE_Z - 0.05 # cube centre below this: it fell off the table +REACH_MARGIN = 0.03 # cube centre this close to the commanded-target limits (agent/tools.py WS_LO / WS_HI): unreachable + + +class CubeWatch: + """Follows the cube at every physics substep (installed on env.sim by reset_instance; outcome() reads it). + + contact episode: substeps with a robot-cube contact, merged across gaps shorter than EP_GAP substeps. Closed + EP_GAP substeps after its last contact; it "moved" the cube if the cube is then >= TOUCH_MOVE from where it was + when the episode began, or still moving. + release: the cube's xy at the last contact of the last episode that moved it, i.e. where its current free slide + began (None while the robot has never moved the cube). + strike: an episode that moved the cube followed by a free slide of >= STRIKE_MIN, logged when the cube comes to + rest (or when the robot touches it again before that: result "interrupted").""" + + def __init__(self, env, target_xy, tol_short, tol_past, tol_across): + m = env.sim.model + self.env = env + self.is_robot = np.zeros(m.ngeom, bool) + self.is_robot[envs.robot_geom_ids(env)] = True + self.is_cube = np.zeros(m.ngeom, bool) + self.is_cube[envs.obj_geom_ids(env, CUBE)] = True + self.qa, self.da = envs.free_joint_addr(env, CUBE) + self.target = np.asarray(target_xy, float) + self.tol = (float(tol_short), float(tol_past), float(tol_across)) # centre offsets: short of / past / beside + self.n_sub = 0 + self.ep = None # open contact episode + self.gap = 0 + self.quiet = 0 # consecutive substeps at rest + self.release = None + self.slide = None # free slide in progress: where it started (cube at the episode start) and was released + self.moves = [] # closed contact episodes that moved the cube + self.strikes = [] + + # ------------------------------------------------------------ state + def pos(self): + return self.env.sim.data.qpos[self.qa:self.qa + 3].copy() + + def at_rest(self): + qv = self.env.sim.data.qvel[self.da:self.da + 6] + return bool(np.linalg.norm(qv[:3]) < V_REST and np.linalg.norm(qv[3:]) < W_REST) + + def judge(self, p): + """Where a cube at p lies relative to the square: (along, across, in / past / short / beside / off). + in = centre at most tol_short short of / tol_past past the square's centre and within tol_across beside it.""" + along, across = float(p[0] - self.target[0]), float(p[1] - self.target[1]) + if abs(p[2] - (envs.TABLE_Z + CUBE_HALF)) > ON_TABLE: + return along, across, "off" + short, past, beside = self.tol + if -short <= along <= past and abs(across) <= beside: + return along, across, "in" + if along > past: + return along, across, "past" + if along < -short: + return along, across, "short" + return along, across, "beside" + + # ------------------------------------------------------------ per substep + def substep(self): + d = self.env.sim.data + n = d.ncon + touch = False + if n: + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + touch = bool(np.any((self.is_robot[g1] & self.is_cube[g2]) | (self.is_robot[g2] & self.is_cube[g1]))) + self.n_sub += 1 + p = self.pos() + rest = self.at_rest() + self.quiet = self.quiet + 1 if rest else 0 + if touch: + if self.ep is None: + if self.slide is not None: + self._end_slide(p, interrupted=not rest) + self.ep = dict(start=p, sub0=self.n_sub) + self.ep["last"] = p + self.ep["sub1"] = self.n_sub + self.gap = 0 + elif self.ep is not None: + self.gap += 1 + if self.gap >= EP_GAP: + self._close(p, rest) + if self.ep is None and self.slide is not None and self.quiet >= REST_SUB: + self._end_slide(p, interrupted=False) + + def _close(self, p, rest): + ep, self.ep = self.ep, None + if np.linalg.norm(p - ep["start"]) < TOUCH_MOVE and rest: + return # touched a resting cube and left it where it was + self.release = ep["last"][:2].copy() + self.moves.append(dict(sub0=ep["sub0"], sub1=ep["sub1"], start=ep["start"].round(4).tolist(), + release=ep["last"].round(4).tolist())) + self.slide = dict(start=ep["start"], release=ep["last"], sub=ep["sub1"]) + + def _end_slide(self, p, interrupted): + s, self.slide = self.slide, None + free = float(np.linalg.norm(p[:2] - s["release"][:2])) + if free < STRIKE_MIN: + return # a push or a put-down, not a strike + along, across, res = self.judge(p) + self.strikes.append(dict(sub=int(s["sub"]), start=s["start"].round(4).tolist(), + release=s["release"].round(4).tolist(), rest=p.round(4).tolist(), + pushed_cm=round(100 * float(np.linalg.norm(s["release"][:2] - s["start"][:2])), 2), + free_slide_cm=round(100 * free, 2), along_err_cm=round(100 * along, 2), + across_err_cm=round(100 * across, 2), + result="interrupted" if interrupted else res, + missed=bool(not interrupted and res != "in"))) + + def flush(self): + """End of attempt: settle the bookkeeping. Returns True if the robot is touching the cube now and that contact + has moved it (then the cube's current free slide is 0).""" + p = self.pos() + if self.ep is not None: + if np.linalg.norm(p - self.ep["start"]) >= TOUCH_MOVE or not self.at_rest(): + self.release = p[:2].copy() + self.slide = None + return True + return False + if self.slide is not None and self.at_rest(): + self._end_slide(p, interrupted=False) + return False + + +def _install_watch(sim, watch): + """Call watch.substep() after every MuJoCo step of this sim (one wrapper per sim, like agent/tools.ContactTracker; + it only reads the state). A fast strike touches the cube for 3-16 substeps (6-32 ms, measured), less than one + control step, so contact checks at control steps alone would miss it.""" + if not getattr(sim, "_lff_slide_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + w = getattr(sim, "_lff_slide_watch", None) + if w is not None: + w.substep() + sim.step = step + sim._lff_slide_wrapped = True + sim._lff_slide_watch = watch + + +class SlideSkills(Skills): + """Skills whose motion commands return only once the cube has come to rest (see the module docstring).""" + + def __init__(self, env, bias=None, recorder=None): + super().__init__(env, bias=bias, recorder=recorder) + self._qa, self._da = envs.free_joint_addr(env, CUBE) + self.waits = [] # (control step, steps waited) for every command that had to wait + + def cube_moving(self): + qv = self.env.sim.data.qvel[self._da:self._da + 6] + return bool(np.linalg.norm(qv[:3]) >= V_REST or np.linalg.norm(qv[3:]) >= W_REST) + + def wait_cube_rest(self): + """Hold the arm where it is until the cube is at rest (two control steps in a row) or WAIT_MAX steps passed. + No wait if the cube is already at rest or is held (it then moves with the arm).""" + if not self.cube_moving() or self.holding(CUBE): + return 0 + p, R = self.eef_pos(), self._R() + quiet = 0 + for k in range(WAIT_MAX): + self._act(p - self.eef_pos(), _rot_err(R, self.eef_mat()), self.grip) + quiet = 0 if self.cube_moving() else quiet + 1 + if quiet >= 2: + break + self.waits.append((self.n_steps, k + 1)) + return k + 1 + + def move_to(self, target, *args, **kwargs): + rep = super().move_to(target, *args, **kwargs) + n = self.wait_cube_rest() + if n: + rep["waited_s"] = round(n * DT, 2) + return rep + + def set_gripper(self, close, steps=15): + rep = super().set_gripper(close, steps) + n = self.wait_cube_rest() + if n: + rep["waited_s"] = round(n * DT, 2) + return rep + + +INNER_HALF = 0.03 # 6 cm square target (inner edge of the outline): near side and sides, the cube's centre within 1 cm +LINE_W = 0.006 +# Far side (away from the robot, facing the agentview camera): the cube may lie on the far line. Instruction: no part of +# it beyond the line's outer edge (centre <= INNER_HALF + LINE_W - CUBE_HALF = 1.6 cm past the centre); judged: centre +# <= 2.0 cm past it, i.e. the front face up to 4 mm beyond the line, which in the 512 x 512 agentview is < 2 px of red +# beyond the line (from 2.0 cm on >= 2 px on all 25 measured instances, task card 2026-10-19). +TOL_PAST = 0.020 + + +def square_frame_xml(model_name, inner_half=INNER_HALF, line_w=LINE_W, + line_rgba=(0.1, 0.55, 0.15, 1.0), fill_rgba=(0.75, 0.92, 0.75, 1.0)): + """Flat, visual-only square drawn on the table: a light fill plus a dark outline (no collisions).""" + o = inner_half + line_w + parts = [((0, 0, 0.0004), (o, o, 0.0004), fill_rgba), + ((0, inner_half + line_w / 2, 0.0010), (o, line_w / 2, 0.0002), line_rgba), + ((0, -inner_half - line_w / 2, 0.0010), (o, line_w / 2, 0.0002), line_rgba), + ((inner_half + line_w / 2, 0, 0.0010), (line_w / 2, o, 0.0002), line_rgba), + ((-inner_half - line_w / 2, 0, 0.0010), (line_w / 2, o, 0.0002), line_rgba)] + g = "\n".join(f' ' for p, sz, c in parts) + return _wrap(model_name, g, 0.0012, o) + + +Z_PUSH = envs.TABLE_Z + 0.02 +V_MIN, V_MAX = 0.12, 0.60 +Z_GRASP = envs.TABLE_Z + CUBE_HALF # grasp point at the cube's centre height (fingertips ~1 cm above the table) + + +@register_task +class SlideToTarget(LFFTask): + name = "l5_slide_to_target" + level = "L5" + category = "dynamics_adaptation" + capabilities = ("Reason", "Utilize") + # no parentheses or semicolons: the instruction is also the BDDL :language string (';' starts a comment there) + instruction = ("Push the red cube straight away from the robot so that it slides and comes to rest in the green " + "square marked on the table. On the side of the square nearest the robot and on its left and " + "right, no part of the cube may lie on or beyond the green border line. On the far side, away from " + "the robot, the cube may lie on the border line, but no part of it may stick out beyond that line. " + "The cube must slide the last part of the way on its own: after it leaves the gripper it has to " + f"slide at least {100 * D_MIN:.0f} cm, with nothing touching it, before it comes to rest in the " + "square.") + instruction_indirect = instruction + tol_along = INNER_HALF - CUBE_HALF # short of the centre (near side): completely inside the square (1.0 cm) + tol_past = TOL_PAST # past the centre (far side): may lie on the far line (2.0 cm, see TOL_PAST) + runup = 0.22 # long run-up so the gripper reaches the commanded speed before contact + tol_across = INNER_HALF - CUBE_HALF + + def make_bddl(self): + cube = register_generated("LffRedCube", box_xml("lff_red_cube", (CUBE_HALF,) * 3, (0.85, 0.15, 0.15, 1), + density=1000)) + # static fixture (no joint): a free body without collisions would fall through the table + zone = register_generated("LffTargetSquare", square_frame_xml("lff_target_square"), free=False) + objs = [("cube_1", cube, "cube_region", (-0.21, -0.01, -0.19, 0.01))] + fixtures = [("zone_1", zone, "zone_region", (-0.11, -0.01, -0.09, 0.01))] + return write_bddl(self.name, self.instruction, objs, fixtures=fixtures) + + def apply_instance(self, inst): + m = self.env.sim.model + zone = self.env.fixtures_dict["zone_1"] + # the target zone is a flat marker: no collisions + for g in range(m.ngeom): + if (m.geom_id2name(g) or "").startswith("zone_1_"): + m.geom_contype[g] = 0 + m.geom_conaffinity[g] = 0 + x0, y0 = inst["cube_xy"] + envs.set_obj_pose(self.env, "cube_1", [x0, y0, envs.TABLE_Z + CUBE_HALF + 0.001]) + bid = m.body_name2id(zone.root_body) + m.body_pos[bid] = [x0 + inst["target_dist"], y0, envs.TABLE_Z + 0.0002] + m.body_quat[bid] = [1.0, 0.0, 0.0, 0.0] + envs.set_friction(self.env, "cube_1", inst["mu"]) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + x0, y0 = inst["cube_xy"] + self.watch = CubeWatch(self.env, (x0 + inst["target_dist"], y0), self.tol_along, self.tol_past, + self.tol_across) + _install_watch(self.env.sim, self.watch) + self.sk = SlideSkills(self.env, recorder=recorder) + return self.sk + + @staticmethod + def max_reach(mu): + """Approximate slide distance at the top speed, fitted to a sweep (runup 0.22 m): + mu 0.04 -> 20.8 cm, 0.06 -> 14.8, 0.08 -> 11.8, 0.10 -> 10.1 cm.""" + return 0.0103 / mu ** 0.95 + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + while True: # reject instances the top speed cannot reach (keeps every instance solvable) + inst = dict(seed=int(seed), + cube_xy=[float(rng.uniform(-0.23, -0.17)), float(rng.uniform(-0.10, 0.10))], + target_dist=float(rng.uniform(0.05, 0.12)), + mu=float(np.exp(rng.uniform(np.log(0.035), np.log(0.10))))) + if inst["target_dist"] <= 0.85 * self.max_reach(inst["mu"]): + return inst + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + envs.settle(self.env, 40) + w = self.watch + for _ in range(12): # still moving (e.g. a budget ended the attempt mid-slide): let it come to rest + if w.at_rest(): + break + envs.settle(self.env, 5) + touching = w.flush() + x0, y0 = inst["cube_xy"] + c = envs.obj_pos(self.env, CUBE) + along = (c[0] - x0) - inst["target_dist"] + across = c[1] - y0 + _, _, where = w.judge(w.pos()) + inside = where == "in" + at_rest = w.at_rest() + free = float(np.linalg.norm(c[:2] - w.release)) if w.release is not None else 0.0 + slid = bool(w.release is not None and not touching and free >= D_MIN) + success = bool(inside and at_rest and slid) + strikes = w.strikes + n_missed = sum(s["missed"] for s in strikes) + from ..agent.tools import WS_HI, WS_LO + reach = bool(np.all(c[:2] >= WS_LO[:2] + REACH_MARGIN) and np.all(c[:2] <= WS_HI[:2] - REACH_MARGIN)) + irrecoverable = bool(c[2] < OFF_TABLE_Z or not reach) + + parts = [] + if w.release is None and np.linalg.norm(c[:2] - np.asarray(inst["cube_xy"])) < STRIKE_MIN: + parts.append("The cube was not pushed.") + if c[2] < OFF_TABLE_Z: + parts.append("The cube fell off the table.") + else: + state = {"in": "in the square", "past": "it sticks out beyond the far green line", + "short": "it sticks out past the edge of the square nearest the robot"}.get(where, + "not in the square") + if along > 0: + parts.append(f"The cube stopped {100 * along:.1f} cm past the centre of the green square ({state}).") + else: + parts.append(f"The cube stopped {100 * -along:.1f} cm short of the centre of the green square " + f"({state}).") + if abs(across) > self.tol_across: + parts.append(f"It also drifted {100 * abs(across):.1f} cm to the {'left' if across > 0 else 'right'} " + f"(robot's view).") + if where == "off" and c[2] > OFF_TABLE_Z: + parts.append("It is not resting on the table.") + if inside and not at_rest: + parts.append("It was still moving when the attempt ended.") + if touching: + parts.append("The gripper was still touching (or holding) the cube when the attempt ended.") + elif inside and w.release is not None and free < D_MIN: + parts.append(f"After it last left the gripper it slid only {100 * free:.1f} cm on its own; it has to slide " + f"at least {100 * D_MIN:.0f} cm.") + if success: + failure = None + elif w.release is None and not inside: + failure = "not_touched" + elif not inside: + failure = "position" + elif not at_rest: + failure = "not_at_rest" + else: + failure = "slide_too_short" + out = dict(success=success, along_err=float(along), across_err=float(across), detail=" ".join(parts), + inside=inside, at_rest=at_rest, free_slide_cm=round(100 * free, 2), + release_xy=None if w.release is None else w.release.round(4).tolist(), + touching_at_end=bool(touching), n_moves=len(w.moves), n_strikes=len(strikes), + n_missed_strikes=int(n_missed), trap_fired=n_missed > 0, + recovered_in_attempt=bool(n_missed and success), irrecoverable=irrecoverable, + strikes=strikes, waits=len(getattr(self.sk, "waits", [])), failure=failure) + return out + + # ------------------------------------------------------------ execution + def execute(self, inst, params): + """One straight strike from the cube's initial position: closed gripper, 22 cm run-up, stop 1.5 cm past the + point of contact, lift (the move returns once the cube has come to rest).""" + x0, y0 = inst["cube_xy"] + sk = self.sk + sk.set_gripper(True, steps=5) + sk.move_to([x0 - self.runup, y0, Z_PUSH + 0.10], yaw=0.0) + sk.move_to([x0 - self.runup, y0, Z_PUSH], tol=0.003) + sk.move_to([x0 - CUBE_HALF + 0.015, y0, Z_PUSH], speed=float(np.clip(params["speed"], V_MIN, V_MAX)), + tol=0.01, max_steps=80) + sk.move_to([x0 - CUBE_HALF + 0.015, y0, Z_PUSH + 0.08], speed=0.3) + + def default_params(self, inst): + return dict(speed=0.30) + + def blind_params(self, inst, attempt, rng): + return dict(speed=float(np.clip(0.30 + rng.normal(0, 0.05), V_MIN, V_MAX))) + + def adapt_params(self, inst, history): + """Cross-attempt learner (one strike per attempt; used by the scripted agent backend): bracketing secant search + on speed using the signed stopping error. validate.py's adaptive policy is run_scripted (within the attempt).""" + pts = sorted((h["params"]["speed"], h["outcome"]["along_err"]) for h in history) + lo = [p for p in pts if p[1] < 0] + hi = [p for p in pts if p[1] > 0] + if lo and hi: + (v0, e0), (v1, e1) = max(lo, key=lambda p: p[0]), min(hi, key=lambda p: p[0]) + v = v0 + (v1 - v0) * (-e0) / (e1 - e0) + elif hi: # always overshooting: slow down + v = min(p[0] for p in hi) * 0.7 + else: # always short: speed up + v = max(p[0] for p in lo) * 1.35 + return dict(speed=float(np.clip(v, V_MIN, V_MAX))) + + def oracle_params(self, inst): + """Privileged: bisection on speed by simulating pushes (uses the true mu).""" + if "_oracle_speed" in inst: + return dict(speed=inst["_oracle_speed"]) + lo, hi = V_MIN, V_MAX + best = None + for _ in range(9): + mid = 0.5 * (lo + hi) + self.reset_instance(inst) + self.execute(inst, dict(speed=mid)) + e = self.outcome(inst)["along_err"] + if best is None or abs(e) < abs(best[1]): + best = (mid, e) + if e > 0: + hi = mid + else: + lo = mid + inst["_oracle_speed"] = best[0] + self.reset_instance(inst) + return dict(speed=best[0]) + + # ------------------------------------------------------------ scripted within-attempt correction + AGENT_CMDS = 40 # robot_server default per-attempt budget (no agent_max_steps here): 40 commands ... + AGENT_SIM_S = 3.0 * AGENT_CMDS # ... and 3 s of simulated motion per command + RESTRIKE_MARGIN = 0.02 # strike again from where the cube stopped only if it is >= D_MIN + this short + + def _strike_here(self, speed): + """Strike the cube where it lies (perfect perception), straight towards +x. 4 agent commands: above the run-up + point + close, down, strike (returns at rest), lift.""" + c = envs.obj_pos(self.env, CUBE) + sk = self.sk + sk.move_to([c[0] - self.runup, c[1], Z_PUSH + 0.10], yaw=0.0) + sk.set_gripper(True, steps=5) + sk.move_to([c[0] - self.runup, c[1], Z_PUSH], tol=0.003) + sk.move_to([c[0] - CUBE_HALF + 0.015, c[1], Z_PUSH], speed=float(np.clip(speed, V_MIN, V_MAX)), tol=0.01, + max_steps=80) + sk.move_to([c[0] - CUBE_HALF + 0.015, c[1], Z_PUSH + 0.08], speed=0.3) + return 4 + + def _carry_back(self, inst): + """Grasp the cube from above, carry it back to its initial position and put it down. 6 agent commands: + above it + open, down + close, lift, carry, down + open, lift.""" + c = envs.obj_pos(self.env, CUBE) + x0, y0 = inst["cube_xy"] + sk = self.sk + sk.move_to([c[0], c[1], Z_GRASP + 0.10], yaw=0.0) + sk.set_gripper(False, steps=10) + sk.move_to([c[0], c[1], Z_GRASP], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([c[0], c[1], Z_GRASP + 0.06]) + sk.move_to([x0, y0, Z_GRASP + 0.06]) + sk.move_to([x0, y0, Z_GRASP + 0.003], tol=0.003) + sk.set_gripper(False, steps=12) + sk.move_to([x0, y0, Z_GRASP + 0.10]) + return 6 + + @staticmethod + def _plan_speed(want, pts): + """Speed for a slide of `want` m from strikes seen so far, pts = [(speed, slide)]: none -> the 0.30 m/s + prior; one -> slide ~ speed^2 through it; several -> log-log interpolation between the bracketing strikes + (or extrapolation from the two nearest, exponent clipped to [0.5, 3]).""" + pts = sorted((v, d) for v, d in pts if d > 0.002) + if not pts: + return 0.30 + if len(pts) == 1: + v, d = pts[0] + return float(np.clip(v * (want / d) ** 0.5, V_MIN, V_MAX)) + lo = [p for p in pts if p[1] <= want] + hi = [p for p in pts if p[1] > want] + if lo and hi: + (v0, d0), (v1, d1) = max(lo, key=lambda p: p[1]), min(hi, key=lambda p: p[1]) + else: + (v0, d0), (v1, d1) = sorted(pts, key=lambda p: abs(np.log(p[1] / want)))[:2] + if abs(np.log(d1 / d0)) < 1e-6 or abs(np.log(v1 / v0)) < 1e-6: + return float(np.clip(v0 * (want / d0) ** 0.5, V_MIN, V_MAX)) + k = float(np.clip(np.log(d1 / d0) / np.log(v1 / v0), 0.5, 3.0)) + return float(np.clip(v0 * (want / d0) ** (1.0 / k), V_MIN, V_MAX)) + + def _adaptive_attempt(self, inst, pts): + """One attempt of the scripted within-attempt learner: strike; look where the cube stopped (perfect + perception, as on the images); if short by >= D_MIN + 2 cm strike again from there, otherwise (overshot, + a little short, or drifted sideways) carry it back to its initial position and strike again, with the speed + planned from every strike seen so far (`pts`, also from earlier attempts). Stops when the cube is in the square + or the next correction would not fit in the agent's command / motion budget.""" + x0, y0 = inst["cube_xy"] + tx = x0 + inst["target_dist"] + sk = self.sk + n0 = sk.n_steps + n_cmd, speeds, path = 0, [], [] + while True: + c = envs.obj_pos(self.env, CUBE) + want = tx - c[0] + near_start = np.linalg.norm(c[:2] - np.asarray(inst["cube_xy"])) < 0.01 + local = [(v, d) for v, d, s in pts if s == near_start] or [(v, d) for v, d, _ in pts] + speed = self._plan_speed(want, local) + n_cmd += self._strike_here(speed) + c1 = envs.obj_pos(self.env, CUBE) + pts.append((speed, float(c1[0] - c[0]), near_start)) + speeds.append(round(speed, 4)) + err, across = float(c1[0] - tx), float(c1[1] - y0) + path.append("strike") + if -self.tol_along <= err <= self.tol_past and abs(across) <= self.tol_across: + break + used_s = (sk.n_steps - n0) * DT + if err < 0 and -err >= D_MIN + self.RESTRIKE_MARGIN and abs(across) < 0.005: + if n_cmd + 4 > self.AGENT_CMDS or used_s + 12.0 > self.AGENT_SIM_S: + break + continue + if n_cmd + 10 > self.AGENT_CMDS or used_s + 30.0 > self.AGENT_SIM_S: + break + n_cmd += self._carry_back(inst) + path.append("carry_back") + return dict(speed=speeds[0], speeds=speeds, path=path, n_commands=n_cmd, + sim_s=round((sk.n_steps - n0) * DT, 1)) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """oracle / naive / blind: one strike per attempt (LFFTask.run_scripted, cross protocol). adaptive: corrects + within the attempt (_adaptive_attempt) and carries what it saw into the next attempt.""" + if kind != "adaptive": + return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt) + k = k or self.max_attempts + history, pts = [], [] + for a in range(k): + self.reset_instance(inst) + params = self._adaptive_attempt(inst, pts) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"]: + break + return history diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/l6_sequence.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/l6_sequence.py new file mode 100644 index 0000000000000000000000000000000000000000..3696302999af83efd1782ea6326db1f794452022 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/l6_sequence.py @@ -0,0 +1,513 @@ +"""L6-C sequence_resume: weigh four items one by one in a given order; an emergency stop resets part of the work. + +Scene: four grocery items (cream cheese, butter, chocolate pudding, popcorn -- small flat boxes), each on its +own round pad (four identical dark pads, flat markers), and a scale (grey square platform, static fixture). +Pad / scale positions and the order are random per instance. + +Instruction: weigh the items one at a time in the given order. Weighing = put the item on the scale and let go; +the scale records a reading after the item has rested on it for 0.5 s and beeps. Then the item goes back on its +own pad before the next item is picked up. Every item must be weighed exactly once; the scale log cannot be +edited, so a second reading of an item or a reading out of turn is a terminal failure. + +Interruption ("emergency stop", once per episode, inside attempt 1): while the robot carries an item, the gripper +opens, a safety routine puts that item back on its own pad and the arm returns to its home pose. Hidden: how +many items had been weighed when it happened, w in {1..4} (uniform), and the phase: the carried item was on its +way to the scale (not yet weighed, phase A) or on its way back (already weighed, phase B); w = 4 is always +phase B. After the stop every item sits on its pad and the arm is at home: the picture looks like the start of +the task. Which item comes next (order[w], or "nothing, call done" for w = 4) is only in the agent's own history +(what it carried, whether the scale had beeped). + +Protocol: within (like l6_swap_interrupt). Events reported immediately (`drain_events`): the scale's beep after +every recorded reading, an error beep for a reading out of turn, and the emergency stop. F2 after `done` gives the +verdict, whether the log is complete, and which items are not on their pads (distance only), never how many +items have been weighed. + +Scripted references (perception = simulator state): + oracle privileged scale log: always weighs order[len(log)] next. + adaptive keeps its own record of readings (an item counts as weighed when the scale beeped while it lay on + it); after the stop it resumes from order[len(record)] (redoes the interrupted item in phase A, goes on + with the next one in phase B, calls done when all four are recorded). + naive memoryless continuation (1 attempt): the picture after the stop shows no progress; it guesses how far + it got (uniform over 0..4 items weighed) and continues from there. + blind memoryless restart (k attempts): starts the sequence over from the first item -> a second reading of + an already weighed item (repeated step). +Extra control (not in the acceptance table): `skip` counts items it *started* to weigh (pick-ups) instead of +readings: correct after a phase-B stop, skips the interrupted item after a phase-A stop. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, register_generated +from ..skills import ROT_SCALE, _rot_err +from ..task_base import LFFTask, register_task +from .l6_swap import _pad_xml as _swap_pad_xml + +ITEMS = ["cream_cheese_1", "butter_1", "chocolate_pudding_1", "popcorn_1"] +CATS = {"cream_cheese_1": "cream_cheese", "butter_1": "butter", "chocolate_pudding_1": "chocolate_pudding", + "popcorn_1": "popcorn"} +NAME = {"cream_cheese_1": "cream cheese", "butter_1": "butter", "chocolate_pudding_1": "chocolate pudding", + "popcorn_1": "popcorn"} +DESCR = {"cream_cheese_1": "the pale blue box with the oval logo", "butter_1": "the red box with white lettering", + "chocolate_pudding_1": "the dark brown box", "popcorn_1": "the blue-and-yellow box"} +N_ITEMS = len(ITEMS) +PADS = [f"pad_{i + 1}" for i in range(N_ITEMS)] +PAD_R = 0.055 +PAD_HALF_T = 0.0008 + +SCALE_HALF = 0.06 # platform half size (12 x 12 cm) +SCALE_BASE_HALF = 0.067 +SCALE_TOP = 0.020 # platform top above the table +SCALE_BASE_H = 0.012 +SCALE_RGBA = (0.78, 0.79, 0.80, 1.0) +SCALE_BASE_RGBA = (0.20, 0.20, 0.22, 1.0) + +BASE_X = -0.66 +REGION = (-0.27, 0.05, -0.27, 0.27) +REACH = 0.70 +PAD_MIN = 0.16 +SCALE_MIN = 0.175 +SUCC_R = 0.04 # item centre within 4 cm of its pad centre +GRASP_DZ = 0.012 # gripper-site height above the support surface for a top-down grasp of the flat boxes +Z_CARRY = envs.TABLE_Z + 0.15 +DWELL = 10 # control steps (0.5 s) at rest on the scale before a reading is recorded +LIFTED = 0.04 + + +def scale_xml(model_name): + parts = [((0, 0, SCALE_BASE_H / 2), (SCALE_BASE_HALF, SCALE_BASE_HALF, SCALE_BASE_H / 2), SCALE_BASE_RGBA), + ((0, 0, (SCALE_BASE_H + SCALE_TOP) / 2), (SCALE_HALF, SCALE_HALF, (SCALE_TOP - SCALE_BASE_H) / 2), + SCALE_RGBA)] + g = [] + for k, (pos, half, rgba) in enumerate(parts): + g.append(f' ') + g.append(f' ') + return _wrap(model_name, "\n".join(g), SCALE_TOP / 2, float(np.hypot(SCALE_BASE_HALF, SCALE_BASE_HALF))) + + +def _yaw_of(env, obj): + R = env.sim.data.body_xmat[envs.body_id(env, obj)].reshape(3, 3) + yaw = float(np.arctan2(R[1, 0], R[0, 0])) # long axis of the boxes = body x + return (yaw + np.pi / 2) % np.pi - np.pi / 2 + + +@register_task +class SequenceResume(LFFTask): + name = "l6_sequence_resume" + level = "L6" + category = "procedural_memory" + capabilities = ("Perceive", "Save", "Retrieve", "Utilize") + protocol = "within" + agent_max_steps = 100 # robot commands per attempt for agents (a VLM needs ~60-75) + max_attempts = 5 + _TEMPLATE = ("Weigh the four grocery items one at a time, in this order: {order}. To weigh an item, put it on " + "the grey scale and let go of it; the scale beeps when it has recorded the reading. Then put the " + "item back on its own round pad before you pick up the next item. Weigh every item exactly once: " + "the scale logs every reading, and the log cannot be edited.") + instruction = _TEMPLATE.format(order="(given per instance)") + instruction_indirect = instruction + inject = True + agent_object_names = [NAME[i] for i in ITEMS] + ["scale", "round pads"] + + def agent_instruction(self, inst, variant="direct"): + names = DESCR if variant == "indirect" else NAME + order = [names[o] for o in inst["order"]] + return self._TEMPLATE.format(order=", ".join(order[:-1]) + ", then " + order[-1]) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + self._mon = False + self._latch = None + orig_step = self.env.step + + def step(action): # per-control-step monitor (also for attempts driven by the agent harness) + if self._latch is not None: + action = self._homing_action() + ret = orig_step(action) + if self._mon: + self._monitor() + return ret + + self.env.step = step + + # ------------------------------------------------------------ scene + def make_bddl(self): + pads = [register_generated(f"LffSeqPad{L}", _swap_pad_xml(f"lff_seq_pad_{L.lower()}")) for L in "ABCD"] + scale = register_generated("LffSeqScale", scale_xml("lff_seq_scale"), free=False) + objs = [(o, CATS[o], f"r{i}", (-0.26 + 0.15 * i - 0.01, -0.31, -0.26 + 0.15 * i + 0.01, -0.29)) + for i, o in enumerate(ITEMS)] + objs += [(PADS[i], pads[i], f"p{i}", (-0.26 + 0.15 * i - 0.01, 0.29, -0.26 + 0.15 * i + 0.01, 0.31)) + for i in range(N_ITEMS)] + fx = [("scale_1", scale, "scale_region", (0.19, -0.01, 0.21, 0.01))] + return write_bddl(self.name, "Weigh the four items one at a time in the given order", objs, fx) # no ; in BDDL + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + for _ in range(5000): + pts = [] + while len(pts) < N_ITEMS + 1: + p = np.array([rng.uniform(*REGION[:2]), rng.uniform(*REGION[2:])]) + if np.hypot(p[0] - BASE_X, p[1]) > REACH: + continue + pts.append(p) + scale, pads = pts[0], np.array(pts[1:]) + dp = [np.linalg.norm(pads[i] - pads[j]) for i in range(N_ITEMS) for j in range(i)] + if min(dp) >= PAD_MIN and min(np.linalg.norm(pads - scale, axis=1)) >= SCALE_MIN: + break + else: + raise RuntimeError("could not sample a layout") + order = [ITEMS[i] for i in rng.permutation(N_ITEMS)] + w = int(rng.integers(1, N_ITEMS + 1)) # items weighed when the stop happens + phase = "B" if w == N_ITEMS else str(rng.choice(["A", "B"])) + inst = dict(seed=int(seed), order=order, pads=pads.round(4).tolist(), scale_xy=scale.round(4).tolist(), + item_off=[[float(v) for v in rng.uniform(-0.008, 0.008, 2)] for _ in range(N_ITEMS)], + item_yaw=[float(v) for v in rng.uniform(-0.3, 0.3, N_ITEMS)], + stop_w=w, stop_phase=phase, trigger_dist=float(rng.uniform(0.05, 0.09)), + stop_off=[float(v) for v in rng.uniform(-0.008, 0.008, 2)], + stop_yaw=float(rng.uniform(-0.3, 0.3))) + inst["stop_item"] = order[w] if phase == "A" else order[w - 1] + self.instruction = self.agent_instruction(inst, "direct") # make_video prints task.instruction + self.instruction_indirect = self.agent_instruction(inst, "indirect") + return inst + + def apply_instance(self, inst): + m = self.env.sim.model + for i, p in enumerate(inst["pads"]): + envs.set_obj_pose(self.env, PADS[i], [p[0], p[1], envs.TABLE_Z + PAD_HALF_T + 0.0001]) + bid = m.body_name2id(self.env.fixtures_dict["scale_1"].root_body) + m.body_pos[bid] = [inst["scale_xy"][0], inst["scale_xy"][1], envs.TABLE_Z] + m.body_quat[bid] = [1, 0, 0, 0] + for i, o in enumerate(ITEMS): + p = np.asarray(inst["pads"][i]) + inst["item_off"][i] + envs.place_upright(self.env, o, p, inst["item_yaw"][i]) + self.env.sim.forward() + self._inst = inst + self.pad_of = {o: i for i, o in enumerate(ITEMS)} # item i starts on pad i (pad positions are random) + self.log = [] # scale readings (item names) + self.error = None + self.stop = None + self.events = [] + self._event_cursor = 0 + self._outcome_cursor = 0 + self._dwell = {o: 0 for o in ITEMS} + self._visit = {o: False for o in ITEMS} + self._prev = {} + self._latch = None + self._mon = False + + def reset_instance(self, inst, recorder=None): + self._mon = False + self._latch = None + sk = super().reset_instance(inst, recorder=recorder) + self._home = sk.eef_pos() + self.rest_dz = {o: float(envs.obj_pos(self.env, o)[2] - envs.TABLE_Z) for o in ITEMS} + self._prev = {o: envs.obj_pos(self.env, o) for o in ITEMS} + self._mon = True + return sk + + def go_home(self): + p = self.sk.eef_pos() + self.sk.move_to([p[0], p[1], max(p[2], self._home[2])]) + self.sk.move_to(self._home) + + # ------------------------------------------------------------ helpers + def scale_xy(self): + return np.asarray(self._inst["scale_xy"], float) + + def pad_xy(self, o): + return np.asarray(self._inst["pads"][self.pad_of[o]], float) + + def on_scale(self, o, p=None): + p = envs.obj_pos(self.env, o) if p is None else p + d = np.abs(p[:2] - self.scale_xy()) + return bool(d.max() <= SCALE_HALF and abs(p[2] - (envs.TABLE_Z + SCALE_TOP + self.rest_dz[o])) < 0.008) + + def on_own_pad(self, o): + p = envs.obj_pos(self.env, o) + return bool(np.linalg.norm(p[:2] - self.pad_xy(o)) <= SUCC_R + and abs(p[2] - (envs.TABLE_Z + self.rest_dz[o])) < 0.01 and not self.sk.holding(o)) + + # ------------------------------------------------------------ monitor: scale readings + emergency stop + def _monitor(self): + env = self.env + if self._latch is not None: + if len(self.sk.log) > self._latch and np.linalg.norm(self.sk.eef_pos() - self._home) < 0.01: + self._latch = None + for o in ITEMS: + p = envs.obj_pos(env, o) + still = np.linalg.norm(p - self._prev[o]) < 0.0008 + self._prev[o] = p + if self.on_scale(o, p): + if still and not self.sk.holding(o): + self._dwell[o] += 1 + if self._dwell[o] >= DWELL and not self._visit[o]: + self._visit[o] = True + self._record(o) + else: + self._dwell[o] = 0 + else: + self._dwell[o] = 0 + if np.abs(p[:2] - self.scale_xy()).max() > SCALE_HALF or \ + p[2] > envs.TABLE_Z + SCALE_TOP + self.rest_dz[o] + 0.02: + self._visit[o] = False + if self.inject and self.stop is None: + self._maybe_stop() + + def _record(self, o): + self.log.append(o) + k = len(self.log) + ok = self.log == self._inst["order"][:k] + if ok: + self.events.append(dict(step=int(self.sk.n_steps), kind="beep", obj=o, + text="The scale beeped: reading recorded.")) + else: + if self.error is None: + self.error = dict(item=o, position=k, step=int(self.sk.n_steps), + kind="repeat" if self.log.count(o) > 1 else "out_of_order") + self.events.append(dict(step=int(self.sk.n_steps), kind="error", obj=o, + text="The scale beeped three times: error, this reading does not follow the " + "requested order. The log cannot be edited.")) + + def _maybe_stop(self): + inst = self._inst + o, w = inst["stop_item"], inst["stop_w"] + if self.log != inst["order"][:w]: + return + p = envs.obj_pos(self.env, o) + if inst["stop_phase"] == "A": + if p[2] < envs.TABLE_Z + self.rest_dz[o] + LIFTED: + return + if np.linalg.norm(p[:2] - self.pad_xy(o)) < inst["trigger_dist"]: + return + else: + if p[2] < envs.TABLE_Z + SCALE_TOP + self.rest_dz[o] + LIFTED: + return + if np.linalg.norm(p[:2] - self.scale_xy()) < inst["trigger_dist"]: + return + if not self.sk.holding(o): + return + self._do_stop(o) + + def _do_stop(self, o): + inst = self._inst + xy = self.pad_xy(o) + np.asarray(inst["stop_off"]) + envs.place_upright(self.env, o, xy, inst["stop_yaw"]) + self.sk.grip = -1.0 + self.sk.yaw = 0.0 + self._latch = len(self.sk.log) # drive the arm home until the current primitive has returned + self._prev[o] = envs.obj_pos(self.env, o) + self.env.sim.forward() + text = ("Emergency stop! The gripper opened, the safety routine put the item the robot was holding back on " + "its pad and moved the arm to its home pose. You may continue the task.") + self.stop = dict(item=o, phase=inst["stop_phase"], weighed=len(self.log), step=int(self.sk.n_steps)) + self.events.append(dict(step=int(self.sk.n_steps), kind="stop", obj=o, text=text)) + + def _homing_action(self): + sk = self.sk + a = np.zeros(self.env.action_dim) + a[:3] = np.clip((self._home - sk.eef_pos()) / sk.pos_scale, -1, 1) + a[3:6] = np.clip(_rot_err(sk.R0, sk.eef_mat()) / ROT_SCALE, -1, 1) + a[6] = -1.0 + return a + + def drain_events(self): + ev = self.events[self._event_cursor:] + self._event_cursor = len(self.events) + return [e["text"] for e in ev] + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + envs.settle(self.env, 20) + order = inst["order"] + complete = self.log == order + terminal = self.error is not None + off = [o for o in ITEMS if not self.on_own_pad(o)] + success = bool(complete and not off and not terminal) + if success: + head = "All four items were weighed once, in the requested order, and are back on their pads." + elif terminal: + head = ("The scale log does not follow the requested order (an item was weighed a second time or out " + "of turn). The log cannot be edited, so the task can no longer be completed.") + elif complete: + head = "Every item has been weighed, but not every item is back on its own pad." + else: + head = "Not every item has been weighed yet." + parts = [] + if not success and not terminal: + for o in off: + p = envs.obj_pos(self.env, o) + if self.sk.holding(o): + parts.append(f"the {NAME[o]} is still in the gripper") + elif self.on_scale(o, p): + parts.append(f"the {NAME[o]} is on the scale") + else: + d = np.linalg.norm(p[:2] - self.pad_xy(o)) + parts.append(f"the {NAME[o]} is {100 * d:.0f} cm from the centre of its pad") + detail = head + (" Also: " + "; ".join(parts) + "." if parts else "") + new = [e for e in self.events[self._outcome_cursor:] if e["kind"] == "stop"] + self._outcome_cursor = len(self.events) + if new: + detail = "During this attempt: " + " ".join(e["text"] for e in new) + " " + detail + return dict(success=success, terminal=terminal, log=[NAME[o] for o in self.log], n_weighed=len(self.log), + complete=complete, error=self.error, stop=self.stop, + off_pad=[NAME[o] for o in off], detail=detail) + + # ------------------------------------------------------------ motion (scripted policies) + def _support_z(self, o): + p = envs.obj_pos(self.env, o) + return envs.TABLE_Z + (SCALE_TOP if self.on_scale(o, p) or + (np.abs(p[:2] - self.scale_xy()).max() < SCALE_HALF) else 0.0) + + def _n_stops(self): + return sum(e["kind"] == "stop" for e in self.events) + + def _pick(self, o): + sk = self.sk + for _ in range(2): + p = envs.obj_pos(self.env, o) + sk.grasp_at(p[:2], self._support_z(o) + GRASP_DZ, yaw=_yaw_of(self.env, o), lift=0.12) + if sk.holding(o): + return True + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], self._support_z(o) + GRASP_DZ + 0.12]) + return False + + def _carry_to(self, o, xy, z_support): + """Carry the held item to xy and put it down. Returns False if an emergency stop happened.""" + sk = self.sk + n0 = self._n_stops() + sk.move_to([xy[0], xy[1], Z_CARRY]) + if self._n_stops() > n0: + return False + sk.move_to([xy[0], xy[1], z_support + GRASP_DZ + 0.004], tol=0.004) + sk.set_gripper(False, steps=12) + sk.move_to([xy[0], xy[1], z_support + GRASP_DZ + 0.10]) + return self._n_stops() == n0 + + def _weigh(self, o): + """Weigh one item (pad -> scale -> pad). Returns (status, beeped): status 'ok' / 'stop_A' / 'stop_B' / + 'no_grasp'; beeped = the scale beeped while the item lay on it (what the agent hears).""" + n_beep = sum(e["kind"] in ("beep", "error") for e in self.events) + if not self._pick(o): + return "no_grasp", False + if not self._carry_to(o, self.scale_xy(), envs.TABLE_Z + SCALE_TOP): + return "stop_A", False + self.sk.hold(6) + beeped = sum(e["kind"] in ("beep", "error") for e in self.events) > n_beep + if not self._pick(o): + return "no_grasp", beeped + if not self._carry_to(o, self.pad_xy(o), envs.TABLE_Z): + return "stop_B", beeped + return "ok", beeped + + def _fix_pads(self, log): + for o in ITEMS: + if not self.on_own_pad(o) and not self.on_scale(o): + if self._pick(o): + self._carry_to(o, self.pad_xy(o), envs.TABLE_Z) + log.append((NAME[o], "back to pad")) + + def _run_from(self, k, record, log, stop_on_stop=False): + """Weigh order[k:] in turn, keeping `record` (the policy's own list of readings it heard).""" + order = self._inst["order"] + i = k + guard = 0 + while i < len(order) and guard < 10 and self.error is None: + guard += 1 + o = order[i] + st, beeped = self._weigh(o) + log.append((NAME[o], st, beeped)) + if beeped: + record.append(o) + if st == "no_grasp": + continue + if st.startswith("stop"): + if stop_on_stop: + return "stopped" + i = len(record) # resume from the own record + continue + i += 1 + return "ok" + + # ------------------------------------------------------------ scripted references (within protocol) + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed + 104729) + self.reset_instance(inst) + order = inst["order"] + history = [] + record = [] # adaptive's Save: readings it heard + for a in range(k): + log = [] + plan = dict(kind=kind, steps=log) + if a == 0: + if kind == "oracle": + while len(self.log) < len(order) and self.error is None and len(log) < 12: + o = order[len(self.log)] # privileged scale log + st, _ = self._weigh(o) + log.append((NAME[o], st)) + plan["recovery"] = "oracle: privileged scale log" + elif kind == "adaptive": + self._run_from(0, record, log) + plan["recovery"] = "own record of readings: resume from order[len(record)]" + elif kind == "skip": + started = [] + i = 0 + while i < len(order) and self.error is None and len(log) < 12: + o = order[i] + st, beeped = self._weigh(o) + log.append((NAME[o], st, beeped)) + if st == "no_grasp": + continue + started.append(o) + i = len(started) # counts started items, not readings + plan["recovery"] = "counts items it started to weigh (the interrupted one too)" + else: # memoryless after the stop + r = self._run_from(0, record, log, stop_on_stop=True) + if r == "stopped": + if kind == "naive": + g = int(rng.integers(0, len(order) + 1)) + plan["recovery"] = f"memoryless: guesses {g} items already weighed" + self._run_from(g, [], log) + elif kind == "blind": + plan["recovery"] = "memoryless restart from the first item" + self._run_from(0, [], log) + else: + raise ValueError(kind) + else: + plan["recovery"] = "none (no stop)" + else: + if kind in ("adaptive", "oracle", "skip"): + plan["recovery"] = "memory + F2: put items back on their pads / finish from own record" + if kind == "adaptive" and len(record) < len(order): + self._run_from(len(record), record, log) + if kind == "skip" and not history[-1]["outcome"]["complete"]: + # F2 says the log is incomplete: with memory, the item carried at the stop was not weighed + stopped = [s[0] for h in history for s in h["params"]["steps"] if str(s[1]).startswith("stop")] + if stopped: + o = next(i for i in ITEMS if NAME[i] == stopped[-1]) + st, _ = self._weigh(o) + log.append((NAME[o], st)) + plan["recovery"] = "memory + F2 'not every item weighed': weigh the item carried at the stop" + self._fix_pads(log) + elif kind == "blind": + plan["recovery"] = "memoryless restart from the first item" + self._run_from(0, [], log) + else: + raise ValueError(kind) + self.go_home() + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=plan, outcome=out)) + if on_attempt: + on_attempt(a, plan, out) + if out["success"] or out["terminal"] or kind in ("oracle", "naive"): + break + return history + + def default_params(self, inst): + return dict(policy="naive") + + def oracle_params(self, inst): + return dict(policy="oracle") diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/l7_hidden_mechanism.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/l7_hidden_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..234475804ed6b6684aa8fc69a813d1332eb3a2d0 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/l7_hidden_mechanism.py @@ -0,0 +1,398 @@ +"""L7 hidden_mechanism: open a small cabinet door whose opening mechanism is hidden. + +Category: failed_interaction_inference ("why did this contact not do what I expected?"). + +Scene: a small wooden cabinet (14 x 24 x 10 cm) whose door faces away from the robot (towards the front +camera), with a black knob post in the middle of the door. The robot reaches over the cabinet, grasps the +knob from above and pulls. + +Hidden variable: the door's mechanism, one of four (uniform): swings on a hinge at its left edge (HL) or at +its right edge (HR), or slides to the left (SL) or to the right (SR). The door, the knob and the cabinet look +exactly the same for all four (hinge pins and slide rails are not modelled visually). + +Rule (stated in the instruction and enforced): one pull per attempt -- grasp the knob, ONE straight move_to +while holding it, release. A "pull" is any move_to that starts with the knob held, moves the door, or pushes +against the door / knob sideways. Without this rule an agent could probe the door with small wiggles inside +one attempt and the task would no longer test what is learnt across attempts. + +Why the prior fails (measured): the natural pull is straight out from the door (forward, +x), 12 cm. + hinged: the knob has to follow a circle around the hinge; the door swings open 31-36 deg and the knob is + pulled out of the fingers. The knob ends ~6 cm forward and ~4.5 cm towards the hinge side. + sliding: nothing moves; the fingers slide off the knob. +Success needs >= 60 deg (hinged) or >= 12 cm (sliding). + +What must be learned: from how the knob / door moved (F2 gives the knob's displacement relative to where it +started, plus the images) -> which mechanism -> the pull direction that opens it: + hinged on the left: pull forward-left (~55 deg from forward), ~22 cm -> 70-88 deg (measured) + hinged on the right: pull forward-right -> 70-88 deg + sliding: pull sideways ~18 cm (18 cm); after "nothing moved" the side is not observable, + so a learner needs one more attempt in the worst case (left fails -> right). +Straight pulls at 30 / 45 deg towards the hinge give 44 / ~62 deg; diagonal pulls on a slider give 2-4 cm. +""" +import mujoco +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +CAB = "cab_1" +MODEL = "lff_l7_mech_cabinet" +# cabinet frame: origin at the centre of the footprint, z = 0 on the table; the open side faces +x +D, W, H, T = 0.14, 0.24, 0.10, 0.01 # depth (x), width (y), height, wall thickness +DW, DH, DT = 0.232, 0.09, 0.012 # door width, height, thickness +GAP = 0.002 +KZ = 0.045 # knob stem height above the table +STEM_L, STEM_R = 0.032, 0.005 +POST_R, POST_H = 0.009, 0.038 +POST_TOP = KZ - 0.006 + POST_H # 7.7 cm above the table +Z_GRIP = envs.TABLE_Z + 0.075 # grasp-point height for grasping the knob (verified across cabinet positions) +MECHS = ("HL", "HR", "SL", "SR") +HINGE_OK = np.radians(60.0) +SLIDE_OK = 0.12 +SLIDE_RANGE = 0.22 +PULL_SPEED = 0.10 + + +def cabinet_xml(name, rgba=(0.45, 0.32, 0.22, 1.0), door_rgba=(0.80, 0.70, 0.55, 1.0), knob_rgba=(0.12, 0.12, 0.13, 1.0)): + hx, hy = D / 2, W / 2 + shell = [((-hx + T / 2, 0, H / 2), (T / 2, hy, H / 2)), ((0, hy - T / 2, H / 2), (hx, T / 2, H / 2)), + ((0, -hy + T / 2, H / 2), (hx, T / 2, H / 2)), ((0, 0, H - T / 2), (hx, hy, T / 2)), + ((0, 0, T / 2), (hx, hy, T / 2))] + g = [] + for k, (p, s) in enumerate(shell): + g.append(f'') + g.append(f'') + dx = hx + GAP + DT / 2 + dz = 0.005 + DH / 2 + door = [f'', + # placeholder joint: type, axis, anchor and range are set per instance (apply_instance) + f'', + f'', + f''] + sz = KZ - dz + stem_p = (DT / 2 + STEM_L / 2, 0, sz) + post_p = (DT / 2 + STEM_L, 0, sz - 0.006 + POST_H / 2) + for tag, typ, p, s in (("stem", "box", stem_p, (STEM_L / 2 + 0.002, STEM_R, STEM_R)), + ("post", "cylinder", post_p, (POST_R, POST_H / 2))): + door.append(f'') + door.append(f'') + body = ("\n ".join(g) + f'\n \n ' + + "\n ".join(door) + "\n ") + return f""" + + + + {body} + + + + + + +""" + + +def _lr(v): + return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}" + + +def _fb(v): + return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}" + + +class MechSkills(Skills): + """Skills that log, for whoever drives them (scripted policy or agent): door pulls, the first grasp of the + knob, and how the knob moved during the first pull.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + m = env.sim.model + self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith(("gripper0_", "robot0_"))] + self._door_geoms = task.door_geom_ids + self.knob0 = task.knob_xyz() + self.pulls = [] # one entry per move_to that counts as a pull + self.closes = [] # close_gripper events: gripper centre relative to the knob, held afterwards? + self._touch = False + self.touch_since_report = False + + def holding_knob(self): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.task.knob_geom_names)) + + def _touching_door(self): + d = self.env.sim.data + g = set(self._grip_geoms) + dg = set(self._door_geoms) + for i in range(d.ncon): + c = d.contact[i] + if (c.geom1 in g and c.geom2 in dg) or (c.geom2 in g and c.geom1 in dg): + return True + return False + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + if self._touching_door(): + self._touch = True # per move_to (pull detection) + self.touch_since_report = True # per agent command (report field) + + def move_to(self, target, *args, **kwargs): + q0 = self.task.door_q() + hold0 = self.holding_knob() + p0 = self.eef_pos() + k0 = self.task.knob_xyz() + self._touch = False + rep = super().move_to(target, *args, **kwargs) + dq = abs(self.task.door_q() - q0) + moved = dq > (np.radians(1.0) if self.task.hinged else 0.003) + horiz = float(np.linalg.norm(np.asarray(target, float)[:2] - p0[:2])) + if hold0 or moved or (self._touch and horiz >= 0.015): + k1 = self.task.knob_xyz() + self.pulls.append(dict(step=self.n_steps, held_at_start=bool(hold0), held_at_end=self.holding_knob(), + knob_start=k0.tolist(), knob_end=k1.tolist(), door_moved=bool(moved), + gripper_move=(np.asarray(target, float)[:2] - p0[:2]).round(4).tolist())) + return rep + + def set_gripper(self, close, steps=15): + was_open = self.grip < 0 + rep = super().set_gripper(close, steps) + if close and was_open: + off = self.eef_pos() - self.task.knob_xyz() + self.closes.append(dict(step=self.n_steps, offset=off.round(4).tolist(), held=self.holding_knob(), + width=round(self.gripper_width(), 4))) + return rep + + +@register_task +class HiddenMechanism(LFFTask): + name = "l7_hidden_mechanism" + level = "L7" + category = "failed_interaction_inference" + capabilities = ("Perceive", "Reason", "Plan") + protocol = "cross" + instruction = ("Open the door of the small wooden cabinet wide (a door that swings must end at least 60 degrees " + "open, a door that slides at least 12 cm). The door faces away from you; grasp its black knob from " + "above. Only one pull is allowed per attempt: grasp the knob, move the gripper with ONE straight " + "move command while holding it, then release it. Pushing the door or the knob counts as a pull " + "too.") + instruction_indirect = ("Open the front panel of the small brown box wide (a panel that swings must end at least 60 " + "degrees open, a panel that slides at least 12 cm). The panel faces away from you; grasp the " + "small black handle on it from above. Only one pull is allowed per attempt: grasp the handle, " + "move the gripper with ONE straight move command while holding it, then release it. " + "Pushing the panel or the handle counts as a pull too.") + + # ------------------------------------------------------------ scene + def make_bddl(self): + cab = register_generated("LffL7MechCabinet", cabinet_xml(MODEL), free=False) + return write_bddl(self.name, "open the cabinet door", [], + fixtures=[(CAB, cab, "cab_region", (-0.14, -0.01, -0.12, 0.01))]) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + pre = f"{CAB}_{MODEL}" + self.jid = m.joint_name2id(pre + "_door_joint") + self.dof = m.jnt_dofadr[self.jid] + self.qa = m.jnt_qposadr[self.jid] + self.cab_bid = m.body_name2id(self.env.fixtures_dict[CAB].root_body) + self.post_gid = m.geom_name2id(pre + "_post") + self.knob_geom_names = [pre + "_post", pre + "_stem"] + self.door_geom_ids = [m.geom_name2id(pre + s) for s in ("_post", "_stem", "_panel")] + self.hinged = True + + # agent-facing hooks ------------------------------------------------------- + def on_agent_tool(self, inst, name, args, report): + """The cabinet is a fixture, so the harness's `holding_object` / `touched_object` (movable objects only) never + see the knob or the door; add an explicit `holding_knob` field and count door contacts as touches.""" + if self.sk is None or not isinstance(report, dict): + return + touched = self.sk.touch_since_report + self.sk.touch_since_report = False + if report.get("ok") and name in ("move_to", "open_gripper", "close_gripper", "push"): + report["holding_knob"] = self.sk.holding_knob() + if touched and "touched_object" in report: + report["touched_object"] = True + + # ------------------------------------------------------------ state helpers + def door_q(self): + return float(self.env.sim.data.qpos[self.qa]) + + def knob_xyz(self): + return self.env.sim.data.geom_xpos[self.post_gid].copy() + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + return dict(seed=int(seed), mech=MECHS[int(rng.integers(4))], + cab_xy=[float(rng.uniform(-0.15, -0.10)), float(rng.uniform(-0.07, 0.07))]) + + def apply_instance(self, inst): + m, d = self.env.sim.model, self.env.sim.data + cx, cy = inst["cab_xy"] + m.body_pos[self.cab_bid] = [cx, cy, envs.TABLE_Z] + m.body_quat[self.cab_bid] = [1.0, 0.0, 0.0, 0.0] + mech = inst["mech"] + jid, dof = self.jid, self.dof + self.hinged = mech in ("HL", "HR") + if self.hinged: + s = 1 if mech == "HL" else -1 + m.jnt_type[jid] = mujoco.mjtJoint.mjJNT_HINGE + m.jnt_axis[jid] = [0, 0, 1] + m.jnt_pos[jid] = [-DT / 2, s * DW / 2, 0] # back face of the door, at its left / right edge + m.jnt_range[jid] = [0.0, 1.9] if s > 0 else [-1.9, 0.0] + m.dof_damping[dof] = 0.05 + m.dof_frictionloss[dof] = 0.03 + else: + s = 1 if mech == "SL" else -1 + m.jnt_type[jid] = mujoco.mjtJoint.mjJNT_SLIDE + m.jnt_axis[jid] = [0, s, 0] + m.jnt_pos[jid] = [0, 0, 0] + m.jnt_range[jid] = [0.0, SLIDE_RANGE] + m.dof_damping[dof] = 2.0 + m.dof_frictionloss[dof] = 0.5 + # MuJoCo scales constraint softness (here: the joint limits) with dof_invweight0, computed once at compile + # time for the placeholder hinge through the door's centre. Changing the joint type without updating it + # made the slide limit ~200x too soft: a slider pulled the wrong way moved 17 cm past its stop (measured). + door_mass, door_izz = 0.35, 0.0016 + m.dof_invweight0[dof] = (1.0 / (door_izz + door_mass * (DW / 2) ** 2)) if self.hinged else 1.0 / door_mass + m.jnt_solref[jid] = [0.004, 1.0] # stiff stops (default 0.02 let a hard pull push a slider 8 mm past its stop) + d.qpos[self.qa] = 0.0 + d.qvel[dof] = 0.0 + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = MechSkills(self.env, self, recorder=recorder) + return self.sk + + def opening(self): + """Hinge: degrees open (>= 0); slide: cm open (>= 0).""" + q = abs(self.door_q()) + return float(np.degrees(q)) if self.hinged else 100.0 * q + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + envs.settle(self.env, 20) + sk = self.sk + q = abs(self.door_q()) + is_open = q >= (HINGE_OK if self.hinged else SLIDE_OK) + n_pulls = len(sk.pulls) + success = bool(is_open and n_pulls <= 1) + kd = self.knob_xyz() - sk.knob0 + out = dict(success=success, door_open=bool(is_open), opening=round(self.opening(), 1), n_pulls=n_pulls, + knob_disp=kd.round(4).tolist(), pulls=sk.pulls, closes=sk.closes, first_pull_disp=None, + lost_hold=None) + parts = [] + grasp_txt = "" + if sk.closes: + c = sk.closes[0] + o = c["offset"] + below = (envs.TABLE_Z + POST_TOP) - (o[2] + sk.knob0[2]) # knob top minus gripper centre height + grasp_txt = (f"When the gripper first closed, its centre was {_fb(o[0])} and {_lr(o[1])} of the knob's " + f"centre and {100 * below:.1f} cm below the top of the knob; it " + + ("was holding the knob." if c["held"] else "did not get hold of the knob.")) + if success: + out["failure"] = None + parts.append("The door is open wide.") + elif n_pulls == 0: + out["failure"] = "no_pull" + parts.append("The door did not open: the knob was never pulled.") + else: + out["failure"] = "several_pulls" if n_pulls > 1 else "not_open" + if n_pulls > 1: + parts.append(f"The door or knob was pulled or pushed in {n_pulls} separate moves; only one pull is " + f"allowed per attempt, so this attempt failed.") + elif is_open: + parts.append("The door is open wide.") + else: + parts.append("The door did not open wide enough.") + p = sk.pulls[0] + # net effect of the first pull once things came to rest: up to the start of the next pull, or now + k_after = np.array(sk.pulls[1]["knob_start"]) if n_pulls > 1 else self.knob_xyz() + disp = k_after - np.array(p["knob_start"]) + out["first_pull_disp"] = disp.round(4).tolist() + out["lost_hold"] = bool(p["held_at_start"] and not p["held_at_end"]) + if np.linalg.norm(disp[:2]) < 0.003: + txt = "During your (first) pull the knob did not move at all (less than 0.3 cm)" + else: + txt = f"During your (first) pull the knob moved {_fb(disp[0])} and {_lr(disp[1])}" + if p["held_at_start"]: + txt += ("; the gripper lost hold of the knob during the pull." if out["lost_hold"] + else "; the gripper still held the knob at the end of the pull.") + else: + txt += "; the gripper was not holding the knob when that move started." + parts.append(txt) + if grasp_txt and not success: + parts.append(grasp_txt) + out["detail"] = " ".join(parts) + return out + + # ------------------------------------------------------------ scripted execution (cross protocol) + def execute(self, inst, params): + """Grasp the knob from above (yaw 0), one straight pull in direction `alpha` (deg from forward, + = left) + over `dist` metres, release, lift.""" + sk = self.sk + p = self.knob_xyz() # perfect perception of the current scene + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], Z_GRIP + 0.08], yaw=0.0) + sk.move_to([p[0], p[1], Z_GRIP], tol=0.003) + sk.set_gripper(True, steps=15) + a = np.radians(float(params["alpha"])) + dist = float(params["dist"]) + sk.move_to([p[0] + dist * np.cos(a), p[1] + dist * np.sin(a), Z_GRIP], speed=PULL_SPEED, tol=0.004, + max_steps=300) + sk.set_gripper(False, steps=8) + e = sk.eef_pos() + sk.move_to([e[0], e[1], Z_GRIP + 0.10]) + + def default_params(self, inst): + return dict(alpha=0.0, dist=0.12) + + ORACLE = dict(HL=(55.0, 0.22), HR=(-55.0, 0.22), SL=(90.0, 0.18), SR=(-90.0, 0.18)) + + def oracle_params(self, inst): + a, dist = self.ORACLE[inst["mech"]] + return dict(alpha=a, dist=dist) + + def adapt_params(self, inst, history): + """Scripted F2 learner using the knob's displacement during the (first) pull of each earlier attempt: + moved forward and sideways -> it swings on a hinge on that side -> pull ~55 deg towards that side + (more if a hinge pull already fell short) + moved only sideways -> it slides that way -> pull sideways + did not move -> not a hinge; it must slide: try left, then right.""" + hinge_side, slide_side = 0, 0 + tried_still = set() # pull directions (sign of alpha, only for sideways pulls) after which nothing moved + hinge_tries = 0 + for h in history: + o = h["outcome"] + d = o.get("first_pull_disp") + a = h["params"]["alpha"] + if d is None: + continue + dx, dy = d[0], d[1] + if dx >= 0.01 and abs(dy) >= 0.01: + hinge_side = int(np.sign(dy)) + if abs(a) >= 50: + hinge_tries += 1 + elif abs(dy) >= 0.01: + slide_side = int(np.sign(dy)) + elif abs(a) >= 80: + tried_still.add(int(np.sign(a))) + if hinge_side: + a = 55.0 + 5.0 * min(hinge_tries, 2) + return dict(alpha=hinge_side * a, dist=0.22 + 0.02 * min(hinge_tries, 2)) + if slide_side: + return dict(alpha=90.0 * slide_side, dist=0.18) + side = 1 if 1 not in tried_still else -1 + return dict(alpha=90.0 * side, dist=0.18) + + def blind_params(self, inst, attempt, rng): + """Same plan (pull straight out) with small random variation; no history.""" + return dict(alpha=float(rng.normal(0.0, 8.0)), dist=float(np.clip(rng.normal(0.12, 0.02), 0.06, 0.2))) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/lh_balance_board.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/lh_balance_board.py new file mode 100644 index 0000000000000000000000000000000000000000..0e4ceaea2c011176291dd2723cc94d344f23d991 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/lh_balance_board.py @@ -0,0 +1,817 @@ +"""LH balance_board: put four look-alike cubes on their marks on a plank that rests loose across a narrow block (a +seesaw); loading it in the wrong order tips the plank, and every cube already on it slides down to the low end. + +Family: long-horizon self-disturbance ("state_restoration"): each stage is a plain pick-and-place of a cube onto its +mark, but a later placement can tip the plank, which sends the cubes placed before it (earlier progress) sliding off +their marks. The agent has to notice it, re-level the plank and re-place them before finishing (within an attempt), and +learn a loading order that keeps the plank level (across attempts; the final-state judge does not enforce an order). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a grey support (fixture: two 1.5 cm blocks with a 1 cm slot between them, together 4 cm along the plank x 10 cm x + 6 cm high, flat tops) under the middle of + * a dark wooden plank (free body, 46 cm long, pointing away from the robot, 8 cm wide, 1.5 cm thick, 0.5 kg) lying + loose on it, level, with a 2 cm lip across each end. A thin keel under the plank's middle hangs in the slot and keeps + the plank from wandering along the support (+-3 mm); nothing holds it down. It stays level while the combined centre + of mass of plank + cubes is above the support's 4 cm top; otherwise it tips until its low end touches the table + (about 17 degrees); + * four marks (5.8 cm squares, outline + light fill) on the plank, two on each side of the block: an inner one + (8.5-9.5 cm from the middle) and an outer one (15.5-16.5 cm); the colour of each mark is random; + * four 4.5 cm cubes (red, green, blue, yellow) on the table, two left and two right of the plank (random places). + They look alike except for the colour. Cube and plank surfaces are slick (friction 0.2 < tan 17 deg): on a tipped + plank every cube slides down to the lip at the low end. +Why along x with lips (measured, see the task card): with the plank left-right and open ends, the cubes slid off the +ends onto the table 0-11 cm past them, and a default top-down grasp there (fingers left-right, the Panda hand is 21 cm +wide along them) pressed the plank's end down and tipped it again -- restoring became a loop. Along x the default grasp +is across the plank, and the lips keep the cubes on the plank within reach. + +Hidden variable: the cube masses. "Hazard" instances (13 of every 20 consecutive seeds): the two cubes that belong on +the inner marks are heavy (stone, 0.19-0.24 kg), the two for the outer marks are light (48-56 g); the final layout is +balanced. A heavy cube alone on its inner mark tips the plank (1.28-1.43 x the tipping moment); a light one alone on its +outer mark does not (0.72-0.78 x); in the zig-zag order below no step exceeds 0.72-0.81 x. So the only safe loading +orders are "an outer cube, then the inner cube on the OTHER side, then the other inner cube, then the last outer cube" +(zig-zag); end-to-end, alternating outer-first (outer, outer, inner, inner) and inner-first orders all tip it. +"Benign" instances: all four cubes light (26-34 g); no order tips (worst step 0.63-0.75 x). + +Why the natural order fails: nothing in the image shows which cubes are heavy. Any natural order (nearest cube first, +the marks from one end to the other, or the cautious "alternate sides, outer marks first") tips the plank in a hazard +instance; the cubes on it slide to the low end and keep it tipped. A natural plan then keeps going and finishes with +cubes off their marks. What must be learned: check the marks after each placement / before finishing, unload the low +end and re-place (within the attempt), and use the tip to infer which cubes are heavy (an inner cube tipped it; the +layout must balance in the end, so the other inner cube is heavy too) and load in the zig-zag order (across attempts). + +Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (every cube on its +mark, plank level within 3 degrees and still on its support (10-11), nothing held, scene static) plus an event log of every stage predicate (achieved / +lost / restored, with step and cause) and every tip (which end went down, the cube released just before) for the server +log; F1 gives the agent only success / failure. +""" +import itertools + +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +TZ = envs.TABLE_Z + +# ---------------------------------------------------------------- geometry / physics +# plank frame: y along the plank (+y = the end toward the robot), x across it, z up. The plank and the block are +# yawed 90 deg, so plank +y = world -x. +PL_HL, PL_HW, PL_HT = 0.23, 0.04, 0.0075 # plank half length, half width, half thickness +LIP_T, LIP_H = 0.008, 0.02 # lip across each end (inside the 46 cm), height above the plank's top +PLANK_MASS = 0.50 +PLANK_ROT_DAMP = 0.01 # N m s / rad on the plank's rotation: after its low end is unloaded it swings over to ~10 deg +# and is calm in ~1.5 s (no damping: ~13 deg and ~2.7 s); the tip itself is not slowed (measured) +PLANK_YAW = np.pi / 2 +RIDGE_HW, RIDGE_HX, RIDGE_H = 0.02, 0.05, 0.06 # support: half width along the plank (s), half depth, height +SLOT_HW = 0.005 # the support is two blocks with a 1 cm slot between them +KEEL_HW, KEEL_H = 0.002, 0.010 # keel under the plank's middle (4 mm x 8 cm x 1 cm) hanging in the slot +CUBE_E = 0.045 +MU = 0.20 # cubes and plank: the cube-plank contact slides above 11 deg; ridge (1.0), table (0.6), finger pads (2.0) win +MU_RIDGE = 1.0 +MARK_HALF, MARK_LINE = 0.029, 0.004 +WOOD = (0.42, 0.27, 0.15, 1.0) # dark walnut: contrasts with the light table, so the tilt reads in the images + +COLORS = ("red", "green", "blue", "yellow") +RGBA = dict(red=(0.85, 0.12, 0.10, 1.0), green=(0.10, 0.62, 0.20, 1.0), blue=(0.15, 0.30, 0.88, 1.0), + yellow=(0.93, 0.78, 0.10, 1.0)) +CUBES = {c: f"{c}_cube_1" for c in COLORS} +PLANK, RIDGE = "plank_1", "ridge_1" +PLANK_MODEL = "lff_lh_bb_plank" +# mark slots in plank-frame order (+y first): the robot's end outer / inner, then the far end inner / outer +SLOTS = ("near_outer", "near_inner", "far_inner", "far_outer") +END_WORD = dict(near="the end nearer the robot", far="the far end") + +# ---------------------------------------------------------------- instances / hidden variable +D_INNER = (0.085, 0.095) # |y| of the inner marks from the plank's middle +D_OUTER = (0.155, 0.165) # the lip stops a cube 19.95 cm out: a cube on a low-side outer mark ends >= 3.5 cm off it +P_HAZARD = 0.65 # fraction of hazard instances, balanced per 20 consecutive seeds (13 / 7) +R_HEAVY = (1.30, 1.40) # hazard: lone heavy cube on its inner mark, moment / tipping moment +R_LIGHT = (0.72, 0.78) # hazard: lone light cube on its outer mark +LIGHT_BENIGN = (0.026, 0.034) # benign: every cube (kg) +H_EST, L_EST = 0.21, 0.04 # nominal masses the adaptive script uses for its hypotheses (it never sees the true ones) + +# ---------------------------------------------------------------- judging +TOL = 0.020 # cube centre within 2 cm of its mark centre (per plank axis) +TOL_LOSE = 0.025 # hysteresis for the monitor +LEVEL_DEG = 3.0 +TIP_DEG = 8.0 # the monitor records a tip when |tilt| exceeds this (a real tip reaches ~17 deg) +LEVEL_DEBOUNCE = 4 # monitor evaluations (0.1 s each) before plank_level changes +FLAT_COS = np.cos(np.radians(15.0)) +SUPPORT_XY = 0.02 # plank on its support: its middle within 2 cm (horizontally) of the support's centre ... +SUPPORT_DZ = 0.02 # ... and not more than 2 cm below its starting height (a tip lowers it ~0.6 cm; off the block ~6 cm) + +# ---------------------------------------------------------------- scripted motion +Z_CARRY = 0.17 # careful / adaptive: grasp point above the table while carrying (cube bottom 14.75 cm) +Z_CARRY_NAIVE = 0.15 # naive: just above the cubes already on the plank (their tops at 12 cm) +REL_GAP = 0.004 # release with the cube's bottom this far above the plank + + +def plank_xml(name): + """Board + end lips + keel (collision) and per colour a mark (5 visual-only geoms, moved per instance). + Long axis = body y.""" + g = [] + + def box(nm, pos, size, rgba): + g.append(f'') + g.append(f'') + + dark = (0.25, 0.16, 0.09, 1.0) + box(f"{name}_board", (0, 0, 0), (PL_HW, PL_HL, PL_HT), WOOD) + for k, s in enumerate((1, -1)): + box(f"{name}_lip{k}", (0, s * (PL_HL - LIP_T / 2), PL_HT + LIP_H / 2), (PL_HW, LIP_T / 2, LIP_H / 2), dark) + box(f"{name}_keel", (0, 0, -PL_HT - KEEL_H / 2), (PL_HW, KEEL_HW, KEEL_H / 2), dark) + for c in COLORS: + rgba = RGBA[c] + fill = tuple(0.55 + 0.45 * v for v in rgba[:3]) + (1.0,) + o, i, w = MARK_HALF, MARK_HALF - MARK_LINE, MARK_LINE + parts = [((0, 0, PL_HT + 0.0003), (o, o, 0.0003), fill), + ((0, i + w / 2, PL_HT + 0.0008), (o, w / 2, 0.0003), rgba), + ((0, -i - w / 2, PL_HT + 0.0008), (o, w / 2, 0.0003), rgba), + ((i + w / 2, 0, PL_HT + 0.0008), (w / 2, o, 0.0003), rgba), + ((-i - w / 2, 0, PL_HT + 0.0008), (w / 2, o, 0.0003), rgba)] + for k, (p, sz, col) in enumerate(parts): + g.append(f'') + return _wrap(name, "\n ".join(g), PL_HT, float(np.hypot(PL_HL, PL_HW))) + + +def ridge_xml(name): + """Split support: two 1.5 cm blocks with a 1 cm slot between them; the plank rests on both and pivots on their outer + top edges (a 4 cm flat top). The plank's keel hangs in the slot, so the plank cannot wander along its length by + more than +-3 mm (it stays engaged at the full tip angle).""" + rgba = (0.35, 0.35, 0.38, 1.0) + bh = (RIDGE_HW - SLOT_HW) / 2 + g = [] + for k, sy in enumerate((1, -1)): + p, sz = (0, sy * (SLOT_HW + bh), RIDGE_H / 2), (RIDGE_HX, bh, RIDGE_H / 2) + g.append(f'') + g.append(f'') + g = "\n ".join(g) + return f""" + + + + {g} + + + + + + +""" + + +def tip_ratio(items, plank_mass=PLANK_MASS, s=RIDGE_HW): + """Static model of a loose plank on a flat-topped block: |sum m y| / ((M_plank + sum m) s); the plank tips when + this exceeds 1 (the combined centre of mass leaves the block's top). items: [(mass, y from the middle)].""" + if not items: + return 0.0 + mom = sum(m * y for m, y in items) + return abs(mom) / ((plank_mass + sum(m for m, _ in items)) * s) + + +def _side(y): + return "near" if y > 0 else "far" + + +def _along(v): + """plank-frame y offset in robot-centric words (+y = toward the robot)""" + return f"{100 * abs(v):.1f} cm from its mark toward {'the robot' if v > 0 else 'the far end'}" + + +class BoardSkills(Skills): + """Skills that feed the task's per-step monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class BalanceBoard(LFFTask): + name = "lh_balance_board" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Plan", "Restore") + protocol = "cross" + max_attempts = 3 + agent_max_steps = 120 # careful zig-zag ~30-36 commands + re-placing four cubes (~30) + looking around + instruction = ("Put each coloured cube on the square mark of the same colour on the long plank. The plank lies loose " + "across a narrow block under its middle. At the end all four cubes must be on their marks and the " + "plank must still rest level on the block.") + instruction_indirect = ("Set the four coloured cubes onto the outlined squares of matching colour on the wooden " + "board that rests across the small grey block. When you are done, every cube must sit on " + "its square and the board must still rest level on the block.") + agent_object_names = ["red cube", "green cube", "blue cube", "yellow cube", "plank", "support block", + "red mark", "green mark", "blue mark", "yellow mark"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + pl = register_generated("LffLhBbPlank", plank_xml(PLANK_MODEL)) + rg = register_generated("LffLhBbRidge", ridge_xml("lff_lh_bb_ridge"), free=False) + objs = [(PLANK, pl, "plank_region", (0.18, -0.01, 0.20, 0.01))] + e = CUBE_E / 2 + for i, c in enumerate(COLORS): + cat = register_generated(f"LffLhBbCube{c.title()}", + box_xml(f"lff_lh_bb_cube_{c}", (e, e, e), RGBA[c], density=500.0, + friction=(MU, 0.005, 0.0001)).replace( + 'solimp="0.998 0.998 0.001" solref="0.001 1"', "")) + objs.append((CUBES[c], cat, f"{c}_cube_region", (-0.32, -0.33 + 0.2 * i, -0.30, -0.31 + 0.2 * i))) + fx = [(RIDGE, rg, "ridge_region", (-0.12, 0.30, -0.10, 0.32))] + return write_bddl(self.name, "put each cube on its mark on the plank and keep the plank level", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.ridge_bid = m.body_name2id(self.env.fixtures_dict[RIDGE].root_body) + self.plank_bid = envs.body_id(self.env, PLANK) + pre = f"{PLANK}_{PLANK_MODEL}" + self.mark_gids = {c: [m.geom_name2id(f"{pre}_mk_{c}_{k}") for k in range(5)] for c in COLORS} + self.mark_pos0 = {c: [m.geom_pos[g].copy() for g in self.mark_gids[c]] for c in COLORS} + self.cube_gids = {c: set(envs.obj_geom_ids(self.env, CUBES[c])) for c in COLORS} + self.plank_gids = set(envs.obj_geom_ids(self.env, PLANK)) + self.robot_gids = set(envs.robot_geom_ids(self.env)) + self.inst = None + self.mon = None + self.obs = [] # adaptive script: (configuration, tipped) observations, kept across the attempts of one run + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + x0, y0 = float(rng.uniform(-0.18, -0.14)), float(rng.uniform(-0.03, 0.03)) + perm = [str(c) for c in rng.permutation(COLORS)] # colour of the mark in SLOTS order + slot_of = {c: s for c, s in zip(perm, SLOTS)} + dist = dict(near_outer=float(rng.uniform(*D_OUTER)), near_inner=float(rng.uniform(*D_INNER)), + far_inner=-float(rng.uniform(*D_INNER)), far_outer=-float(rng.uniform(*D_OUTER))) + marks = {c: dist[slot_of[c]] for c in COLORS} # plank-frame y of each mark (+ = toward the robot) + hazard = bool((int(seed) * 7) % 20 < round(20 * P_HAZARD)) # balanced like l7_key_turn / lh_lid_box + r_h, r_l = float(rng.uniform(*R_HEAVY)), float(rng.uniform(*R_LIGHT)) + light = {c: float(rng.uniform(*LIGHT_BENIGN)) for c in COLORS} + s, pm = RIDGE_HW, PLANK_MASS + if hazard: + # equal moments on both sides -> the finished layout is exactly balanced + dn, do = dist["near_inner"], dist["near_outer"] + y_h = r_h * pm * s / (dn - r_h * s) * dn # heavy on the near inner mark: moment r_h x tipping moment + x_l = r_l * pm * s / (do - r_l * s) * do + mass = {c: (y_h if "inner" in slot_of[c] else x_l) / abs(dist[slot_of[c]]) for c in COLORS} + else: + mass = light + # start: two cubes left and two right of the plank, 17-19 cm from its axis, at two depths (random places) + spots = [(dx, sy) for sy in (1.0, -1.0) for dx in (-0.08, 0.08)] + order = rng.permutation(4) + start = {c: [x0 + spots[j][0] + float(rng.uniform(-0.01, 0.01)), + y0 + spots[j][1] * float(rng.uniform(0.17, 0.19))] for c, j in zip(COLORS, order)} + start_yaw = {c: float(rng.uniform(-0.3, 0.3)) for c in COLORS} + heavy = sorted(c for c in COLORS if mass[c] > 0.1) + return dict(seed=int(seed), plank_xy=[x0, y0], marks=marks, slot_of=slot_of, hazard=hazard, mass=mass, + heavy=heavy, r_heavy=r_h if hazard else None, r_light=r_l if hazard else None, start=start, + start_yaw=start_yaw) + + def apply_instance(self, inst): + self.inst = inst + env = self.env + m = env.sim.model + x0, y0 = inst["plank_xy"] + q = [np.cos(PLANK_YAW / 2), 0.0, 0.0, np.sin(PLANK_YAW / 2)] + m.body_pos[self.ridge_bid] = [x0, y0, TZ] + m.body_quat[self.ridge_bid] = q + envs.scale_mass(env, PLANK, PLANK_MASS) + _, da = envs.free_joint_addr(env, PLANK) + m.dof_damping[da + 3:da + 6] = PLANK_ROT_DAMP + for c in COLORS: + for g, p0 in zip(self.mark_gids[c], self.mark_pos0[c]): + m.geom_pos[g] = p0 + np.array([0.0, inst["marks"][c], 0.0]) + envs.scale_mass(env, CUBES[c], inst["mass"][c]) + envs.set_obj_pose(env, PLANK, [x0, y0, TZ + RIDGE_H + PL_HT + 0.0005], quat_wxyz=np.array(q)) + for c in COLORS: + envs.place_upright(env, CUBES[c], inst["start"][c], yaw=inst["start_yaw"][c]) + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.plank_z0 = float(self.plank_pos()[2]) + self.sk = BoardSkills(self.env, self, recorder=recorder) + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ state helpers + def plank_R(self): + return self.env.sim.data.body_xmat[self.plank_bid].reshape(3, 3).copy() + + def plank_pos(self): + return self.env.sim.data.body_xpos[self.plank_bid].copy() + + def tilt_deg(self): + """+ = the plank's end toward the robot is up""" + return float(np.degrees(np.arcsin(np.clip(self.plank_R()[2, 1], -1.0, 1.0)))) + + def is_level(self, deg=LEVEL_DEG): + return abs(self.tilt_deg()) <= deg + + def on_support(self): + """the plank still rests on the support block (10-11: Sonnet lh2 s3001 pushed it off onto the table, where it + lies level, and loaded the cubes there; 'level' alone accepted that)""" + p, r = self.plank_pos(), self.env.sim.data.body_xpos[self.ridge_bid] + return bool(np.linalg.norm(p[:2] - r[:2]) <= SUPPORT_XY and p[2] >= self.plank_z0 - SUPPORT_DZ) + + def in_plank(self, p): + """world point -> plank frame (x across, y along from the middle, z above the plank's mid-plane)""" + return self.plank_R().T @ (np.asarray(p, float) - self.plank_pos()) + + def mark_world(self, c): + return self.plank_pos() + self.plank_R() @ np.array([0.0, self.inst["marks"][c], PL_HT]) + + def cube_pos(self, c): + return envs.obj_pos(self.env, CUBES[c]) + + def held(self, c): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, + object_geoms=self.env.objects_dict[CUBES[c]])) + + def on_plank(self, c): + """resting on the plank's top (plank frame), anywhere along it""" + q = self.in_plank(self.cube_pos(c)) + return bool(abs(q[0]) <= PL_HW + 0.01 and abs(q[1]) <= PL_HL and abs(q[2] - PL_HT - CUBE_E / 2) <= 0.012) + + def mark_offset(self, c): + q = self.in_plank(self.cube_pos(c)) + return np.array([q[0], q[1] - self.inst["marks"][c]]) + + def _flat(self, c): + Rc = self.env.sim.data.body_xmat[envs.body_id(self.env, CUBES[c])].reshape(3, 3) + return bool(np.max(np.abs(self.plank_R()[:, 2] @ Rc)) >= FLAT_COS) + + def on_mark(self, c, tol=TOL): + if not self.on_plank(c): + return False + o = self.mark_offset(c) + return bool(np.max(np.abs(o)) <= tol and self._flat(c) and not self.held(c)) + + def stage_values(self): + v = {f"{c}_on_mark": self.on_mark(c) for c in COLORS} + v["plank_level"] = self.is_level() + v["plank_on_support"] = self.on_support() + return v + + # ------------------------------------------------------------ per-step monitor (server log only) + def _init_monitor(self): + self.mon = dict(state={f"{c}_on_mark": False for c in COLORS} | {"plank_level": True, "plank_on_support": True}, ever=set(), + lost=set(), events=[], step=0, last_touch={c: None for c in COLORS}, + held_prev={c: False for c in COLORS}, last_release=None, tipping=False, tips=[], + level_cnt=0, calm=0, tilt_max=0.0, win_max=0.0) + + def _robot_touches(self): + """cubes touched by the robot or by a cube the robot is carrying, in this control step""" + d = self.env.sim.data + out = set() + carried = [c for c in COLORS if self.mon["held_prev"][c]] + hit = {c: self.robot_gids.union(*[self.cube_gids[h] for h in carried if h != c]) for c in COLORS} + for i in range(d.ncon): + con = d.contact[i] + for c in COLORS: + g = self.cube_gids[c] + if (con.geom1 in g and con.geom2 in hit[c]) or (con.geom2 in g and con.geom1 in hit[c]): + out.add(c) + return out + + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + mon["step"] += 1 + step = self.sk.n_steps + for c in self._robot_touches(): + mon["last_touch"][c] = step + tilt = self.tilt_deg() + mon["tilt_max"] = max(mon["tilt_max"], abs(tilt)) + mon["win_max"] = max(mon["win_max"], abs(tilt)) + if not mon["tipping"] and abs(tilt) > TIP_DEG: + # one tip episode = from |tilt| > 8 deg until the plank has stayed level for 1 s (the swing back and any + # rocking belong to the same episode) + mon["tipping"] = True + mon["calm"] = 0 + rel = mon["last_release"] + tip = dict(step=step, down="near" if tilt < 0 else "far", + after_release=(rel[0] if rel is not None and step - rel[1] <= 60 else None), + on_plank=[c for c in COLORS if self.on_plank(c)], + on_mark=[c for c in COLORS if mon["state"][f"{c}_on_mark"]]) + mon["tips"].append(tip) + mon["events"].append(dict(step=step, pred="plank", ev="tipped", down=tip["down"], + after_release=tip["after_release"], on_mark=tip["on_mark"])) + elif mon["tipping"]: + mon["calm"] = mon["calm"] + 1 if abs(tilt) < LEVEL_DEG else 0 + if mon["calm"] >= 20: + mon["tipping"] = False + if mon["step"] % 2: + return # predicates every other control step (0.1 s) + for c in COLORS: + h = self.held(c) + if mon["held_prev"][c] and not h: + mon["last_release"] = (c, step) + mon["held_prev"][c] = h + key = f"{c}_on_mark" + was = mon["state"][key] + now = self.on_mark(c, TOL if not was else TOL_LOSE) + if now != was: + self._event(key, now, step, c) + lv = self.is_level() + if lv != mon["state"]["plank_level"]: + mon["level_cnt"] += 1 + if mon["level_cnt"] >= LEVEL_DEBOUNCE: + mon["level_cnt"] = 0 + self._event("plank_level", lv, step, None) + else: + mon["level_cnt"] = 0 + sup = self.on_support() + if sup != mon["state"]["plank_on_support"]: + self._event("plank_on_support", sup, step, None) + + def _event(self, key, now, step, color): + mon = self.mon + mon["state"][key] = now + if now: + ev = "restored" if key in mon["lost"] else "achieved" + mon["ever"].add(key) + mon["lost"].discard(key) + mon["events"].append(dict(step=step, pred=key, ev=ev)) + return + cause = "other" + recent_tip = bool(mon["tips"]) and (mon["tipping"] or step - mon["tips"][-1]["step"] <= 60) + if color is None: + cause = "tip" if recent_tip else "other" + elif self.held(color): + cause = "picked_up" + elif recent_tip: + cause = "tip" + elif mon["last_touch"][color] is not None and step - mon["last_touch"][color] <= 60: + cause = "robot" + mon["lost"].add(key) + mon["events"].append(dict(step=step, pred=key, ev="lost", cause=cause, tilt=round(self.tilt_deg(), 1))) + + # ------------------------------------------------------------ outcome + def _static(self): + d = self.env.sim.data + for name in [CUBES[c] for c in COLORS] + [PLANK]: + _, da = envs.free_joint_addr(self.env, name) + if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.3: + return False + return True + + def _where(self, c): + """robot-centric description of where a cube that is not on its mark is""" + if self.held(c): + return "is still held by the gripper" + if self.on_plank(c): + o = self.mark_offset(c) + return f"lies on the plank, {_along(o[1])}" + p = self.cube_pos(c) + if np.linalg.norm(p[:2] - np.asarray(self.inst["start"][c])) < 0.02: + return "is still where it started on the table" + q = self.in_plank(p) + if abs(q[1]) > PL_HL: + return f"lies on the table beyond {END_WORD[_side(q[1])]} of the plank" + return "lies on the table beside the plank" + + def outcome(self, inst): + envs.settle(self.env, 30) + mon = self.mon + vals = self.stage_values() + static = self._static() + held = [c for c in COLORS if self.held(c)] + success = bool(all(vals.values()) and static and not held) + regress = [e for e in mon["events"] if e["ev"] == "lost"] + restored = [e for e in mon["events"] if e["ev"] == "restored"] + parts = [] + off = [c for c in COLORS if not vals[f"{c}_on_mark"]] + if success: + failure = None + parts.append("All four cubes are on their marks and the plank is level.") + else: + lost_final = [c for c in off if f"{c}_on_mark" in mon["ever"]] + failure = ("held" if held else "plank_off_support" if not vals["plank_on_support"] else + "regressed" if lost_final else "incomplete" if off else + "not_level" if not vals["plank_level"] else "not_static") + for c in off: + txt = f"The {c} cube is not on its mark: it {self._where(c)}" + if f"{c}_on_mark" in mon["ever"]: + why = [e for e in regress if e["pred"] == f"{c}_on_mark"] + cause = why[-1].get("cause") if why else None + txt += {"tip": " (it had been on its mark; it slid off when the plank tipped).", + "robot": " (it had been on its mark; the robot knocked it off).", + "picked_up": " (it had been on its mark; it was picked up again)."}.get( + cause, " (it had been on its mark earlier).") + else: + txt += " (it was never on its mark)." + parts.append(txt) + if not vals["plank_on_support"]: + parts.append("The plank no longer rests on the support block: it was pushed or knocked off it.") + if not vals["plank_level"]: + t = self.tilt_deg() + parts.append(f"The plank is not level: it is tilted {abs(t):.0f} degrees, " + f"{END_WORD['near' if t < 0 else 'far']} down.") + if not static and all(vals.values()): + parts.append("Something was still moving at the end.") + if mon["tips"]: + descr = [] + for tp in mon["tips"]: + d = f"{END_WORD[tp['down']]} down" + if tp["after_release"]: + d += f" right after the {tp['after_release']} cube was set down" + descr.append(d) + parts.append(f"During the attempt the plank tipped {len(mon['tips'])} time(s): " + "; ".join(descr) + ".") + return dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, + events=mon["events"], n_regressions=len(regress), n_restored=len(restored), + n_tips=len(mon["tips"]), tips=mon["tips"], tilt_max=round(mon["tilt_max"], 1), + tilt_final=round(self.tilt_deg(), 1), hazard=bool(inst["hazard"]), + mark_offsets_cm={c: (100 * self.mark_offset(c)).round(1).tolist() for c in COLORS}, + on_plank={c: self.on_plank(c) for c in COLORS}, detail=" ".join(parts)) + + # ------------------------------------------------------------ scripted policies (perfect perception) + def _grasp_yaw(self, c): + R = self.env.sim.data.body_xmat[envs.body_id(self.env, CUBES[c])].reshape(3, 3) + i = int(np.argmin(np.abs(R[2]))) + yaw = float(np.arctan2(R[1, i], R[0, i])) + return float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4) + + def _y_on_plank(self): + """cubes resting on the plank now -> their position along it""" + return {c: float(self.in_plank(self.cube_pos(c))[1]) for c in COLORS if self.on_plank(c) and not self.held(c)} + + def plank_calm(self): + _, da = envs.free_joint_addr(self.env, PLANK) + return abs(self.tilt_deg()) < 1.0 and float(np.linalg.norm(self.env.sim.data.qvel[da + 3:da + 6])) < 0.05 + + def wait_calm(self, max_steps=60): + """hold the arm still until the plank has stopped swinging (a careful agent looks before it acts)""" + n = 0 + for _ in range(max_steps): + if self.plank_calm(): + n += 1 + if n >= 5: + return True + else: + n = 0 + self.sk.hold(1) + return False + + def pick(self, c, z_carry): + sk = self.sk + p = self.cube_pos(c) + yaw = self._grasp_yaw(c) + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], max(TZ + z_carry, p[2] + 0.06)], yaw=yaw) + sk.move_to([p[0], p[1], p[2]], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([p[0], p[1], TZ + z_carry], speed=0.3) + if not self.held(c): + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], TZ + z_carry]) + return False + return True + + def put(self, c, z_carry=Z_CARRY, noise=None, record=False, careful=False): + """Pick cube c wherever it is and put it on its mark: carry it over the mark, lower it until its bottom is + REL_GAP above the plank, release, lift. Returns whether the plank tipped (|tilt| > TIP_DEG) during the + placement, or None if the cube could not be picked. record=True appends the observation (cubes on the plank + right before the release + this one on its mark, tipped?) for the adaptive script.""" + for _ in range(2): + if self.pick(c, z_carry): + break + else: + return None + sk = self.sk + d = self.mark_world(c) + if noise is not None: + d = d + np.array([noise[0], noise[1], 0.0]) + sk.move_to([d[0], d[1], TZ + z_carry], yaw=0.0) + if careful: + self.wait_calm() + d = self.mark_world(c) + (np.array([noise[0], noise[1], 0.0]) if noise is not None else 0.0) + sk.move_to([d[0], d[1], d[2] + CUBE_E / 2 + REL_GAP], tol=0.003) + was_level = self.plank_calm() + conf = self._y_on_plank() + conf[c] = float(self.inst["marks"][c]) + self.mon["win_max"] = abs(self.tilt_deg()) + sk.set_gripper(False, steps=12) + sk.move_to([d[0], d[1], TZ + z_carry]) + sk.hold(12) + tipped = self.mon["win_max"] > TIP_DEG + if tipped: + envs.settle(self.env, 30) # let the cubes slide down + if record and was_level: + self.obs.append(dict(conf=conf, tipped=bool(tipped), after=c)) + return tipped + + def park(self, c): + """take cube c off the plank and set it on a free spot of the table beside the plank""" + x0, y0 = self.inst["plank_xy"] + others = [self.cube_pos(o)[:2] for o in COLORS if o != c] + cands = [np.array([x0 + dx, y0 + sy * dy]) for sy in (1, -1) for dy in (0.18, 0.25) + for dx in (-0.12, -0.04, 0.04, 0.12)] + best = max(cands, key=lambda q: min(np.linalg.norm(q - o) for o in others)) + if not self.pick(c, Z_CARRY): + return False + sk = self.sk + sk.move_to([best[0], best[1], TZ + Z_CARRY], yaw=0.0) + sk.move_to([best[0], best[1], TZ + CUBE_E / 2 + 0.004], tol=0.003) + sk.set_gripper(False, steps=12) + sk.move_to([best[0], best[1], TZ + Z_CARRY]) + return True + + # ---- planning with the static model + def plan(self, todo, hyps): + """Best order to (re)place the cubes in `todo`, given the cubes now on the plank, minimising the worst tip ratio + over the mass hypotheses `hyps` (list of {colour: kg}). A cube that is on the plank off its mark is lifted + (its moment removed) and then set on its mark. Returns (order, worst ratio).""" + cur0 = self._y_on_plank() + best, best_w = list(todo), np.inf + for order in itertools.permutations(todo): + w = 0.0 + for mass in hyps: + cur = dict(cur0) + for c in order: + if c in cur: + del cur[c] + w = max(w, tip_ratio([(mass[o], y) for o, y in cur.items()])) + cur[c] = self.inst["marks"][c] + w = max(w, tip_ratio([(mass[o], y) for o, y in cur.items()])) + if w < best_w - 1e-9: + best, best_w = list(order), w + return best, best_w + + def hypotheses(self, use_obs=True): + """Heavy / light assignments (nominal masses) that (1) leave the finished layout balanced, (2) admit a loading + order that never tips the plank (the task is solvable) and (3) agree with every observed placement (tipped or + not, with a +-10 % band in which either outcome counts as consistent). Falls back to (1)+(2) if no assignment + agrees with all observations.""" + marks = self.inst["marks"] + prior = [] + for k in range(5): + for heavy in itertools.combinations(COLORS, k): + mass = {c: (H_EST if c in heavy else L_EST) for c in COLORS} + if tip_ratio([(mass[c], marks[c]) for c in COLORS]) > 0.6: + continue + for order in itertools.permutations(COLORS): + cur, w = [], 0.0 + for c in order: + cur.append((mass[c], marks[c])) + w = max(w, tip_ratio(cur)) + if w <= 0.9: + prior.append(mass) + break + if not use_obs: + return prior + post = [] + for mass in prior: + if all(not ((ob["tipped"] and r < 0.9) or (not ob["tipped"] and r > 1.1)) + for ob in self.obs for r in [tip_ratio([(mass[o], y) for o, y in ob["conf"].items()])]): + post.append(mass) + return post or prior + + def unload_until_level(self, max_moves=4): + """while the plank is tipped: take the cube farthest out on its low side off the plank""" + for _ in range(max_moves): + envs.settle(self.env, 20) + self.wait_calm() + if self.is_level(): + return True + t = self.tilt_deg() + yo = self._y_on_plank() + low = [c for c, y in yo.items() if (y > 0) == (t < 0)] + if not low: + return self.is_level() + self.park(min(low, key=lambda o: abs(yo[o]))) # the top of the pile first: the hand clears the others + envs.settle(self.env, 20) + self.wait_calm() + return self.is_level() + + def restore(self, hyps_fn, rounds=3, record=False): + """Check every stage; if something is wrong: unload the low end if the plank is tipped, then (re)place every + cube that is not on its mark in the order the static model rates safest under the current mass hypotheses; + start over after a tip. Up to `rounds` passes.""" + for _ in range(rounds): + envs.settle(self.env, 20) + if all(self.stage_values().values()): + return True + self.unload_until_level() + todo = [c for c in COLORS if not self.on_mark(c)] + if not todo: + continue + hyps = hyps_fn() + order, worst = self.plan(todo, hyps) + if worst > 0.9: # cubes left on the plank make every order risky: clear it and start from empty + for c in [c for c in COLORS if self.on_plank(c)]: + self.park(c) + order, worst = self.plan(list(COLORS), hyps) + for c in order: + if self.on_mark(c): + continue + if self.put(c, Z_CARRY, record=record, careful=True): + break # tipped: look again + envs.settle(self.env, 20) + return all(self.stage_values().values()) + + def naive_order(self, noise_sd=0.0, rng=None): + """nearest cube first, starting from the gripper's position and then from each mark just loaded""" + p = self.sk.eef_pos()[:2] + left, order = list(COLORS), [] + while left: + dist = {c: np.linalg.norm(self.cube_pos(c)[:2] - p) + (rng.normal(0, noise_sd) if rng is not None else 0.0) + for c in left} + c = min(left, key=dist.get) + order.append(c) + left.remove(c) + p = self.mark_world(c)[:2] + return order + + def slot_order(self, kind): + so = {s: c for c, s in self.inst["slot_of"].items()} + seq = dict(end2end=SLOTS, alt_outer=("near_outer", "far_outer", "near_inner", "far_inner"), + alt_inner=("near_inner", "far_inner", "near_outer", "far_outer"))[kind] + return [so[s] for s in seq] + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("seed", 0)) + mode = params["mode"] + if mode == "plan": + hyps = [dict(inst["mass"])] if params.get("true_masses") else self.hypotheses() + order, _ = self.plan(list(COLORS), hyps) + elif mode in ("end2end", "alt_outer", "alt_inner"): + order = self.slot_order(mode) + else: # nearest first (naive / blind) + order = self.naive_order(params.get("order_noise", 0.0), rng) + noise = params.get("noise", 0.0) + z_carry = Z_CARRY if params.get("careful") else Z_CARRY_NAIVE + for c in order: + nz = rng.uniform(-noise, noise, 2) if noise else None + tipped = self.put(c, z_carry, noise=nz, record=params.get("record", False), careful=params.get("careful", False)) + if tipped and params.get("check_each"): + break # look at what happened, then restore below + if params.get("check"): + hyps_fn = (lambda: [dict(inst["mass"])]) if params.get("true_masses") else self.hypotheses + self.restore(hyps_fn, record=params.get("record", False)) + self.sk.hold(10) + return order + + def default_params(self, inst): + return dict(mode="nearest", check=False) + + def oracle_params(self, inst): + return dict(mode="plan", true_masses=True, careful=True, check=True) + + def adapt_params(self, inst, history): + """from attempt 2: load in the order the observations of earlier attempts make safest, check after every + placement and restore at the end""" + return dict(mode="plan", careful=True, check=True, check_each=True, record=True) + + def blind_params(self, inst, attempt, rng): + """nearest-first again with small random variation (order noise, 4 mm placement noise), no history, no check""" + return dict(mode="nearest", check=False, order_noise=0.03, noise=0.004, seed=int(rng.integers(1 << 30))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + self.obs = [] + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": # attempt 1: natural order, but look after every placement and restore + params = (dict(mode="nearest", check=True, check_each=True, record=True) if a == 0 else + self.adapt_params(inst, history)) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind in ("end2end", "alt_outer", "alt_inner"): # extra controls: other natural orders, no check + params = dict(mode=kind, check=False) + elif kind == "oracle_noise": # extra control: the oracle with +-5 mm (uniform) placement noise + params = dict(self.oracle_params(inst), noise=0.005, seed=int(rng.integers(1 << 30))) + elif kind == "switch": # extra control: no in-attempt repair, learn the order across attempts only + params = (dict(mode="nearest", check=False, record=True) if a == 0 else + dict(mode="plan", careful=True, check=False, record=True)) + else: + raise ValueError(kind) + order = self.execute(inst, params) + out = self.outcome(inst) + out["order"] = order + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "oracle_noise", "naive", "end2end", "alt_outer", "alt_inner"): + break + return history diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/lh_nudge_row.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/lh_nudge_row.py new file mode 100644 index 0000000000000000000000000000000000000000..e681fb7e676fcda50cc393a648311f31083de9f9 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/lh_nudge_row.py @@ -0,0 +1,821 @@ +"""LH lh_nudge_row v2 (2026-10-14): stand four small cups, one by one, on the four coloured mats of their colours; the +mats lie in two rows of two, and in 7 of 10 instances the two mats of a row touch. Letting go of a cup with the fingers +opening towards the cup already standing on the next mat pushes that cup 1.5-3.4 cm sideways, half off its mat -- it +stays upright, so the damage is small but visible (a near miss that has to be noticed and undone before finishing). + +Family: long-horizon self-disturbance ("state_restoration"): every placement is a later stage that can physically undo an +earlier one; the agent has to look back at all cups before finishing (within an attempt) or learn to let go without +pushing (across attempts). + +v1 -> v2 (Sonnet 5.5 pilot np_lh_nudge_row, seeds 3000-3002, k=3, measured): v1 used round rings with a 0.8 cm +tolerance. Sonnet put the cups 0.8-2.2 cm too far forward (+x, away from the robot) in almost every attempt and could not +see it (the oblique agentview camera looks along x; a tall cup hides the ring behind it), so 5 of 7 attempts failed +without any nudge (one was a calibration attempt), and the one clear nudge (s3000) left the cup 0.83 cm off -- +invisible. Its left-right errors were <= 0.7 cm, its releases in attempt 1 almost all at wrist yaw ~0 (fingers opening +left-right), and it learned yaw 45 for the last cup after the nudge. v2 therefore (1) replaces the rings by mats 9 cm long (forward-back, tolerance 3 cm: a 2 cm forward bias +passes) and 4.6 cm wide (left-right, tolerance 1.3 cm), (2) puts the two mats of a row edge to edge so that a yaw-0 +release pushes the neighbour sideways, where the camera resolves it, off its mat onto the table, and (3) uses slimmer cups +(2 x 5 cm instead of 4 x 6 cm): the open finger reaches farther past them, so the push is 1.5-3.4 cm instead of 0.3-2.3. +Code and results of v1: lh_nudge_row.py.bak-20261014-v1, results/_old/lh_nudge_row_v1/. + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * four coloured mats (dark red, blue, green, ochre; flat, visual only), each 9.0 cm (forward-back) x 4.6 cm, in two rows + (far and near, 1.5 cm apart); block centre 53-59 cm in front of the robot base. Tight block (14 of every 20 + consecutive seeds): the two mats of a row touch. Spaced block (6 of 20): they are 4-5 cm apart and no open finger + reaches the neighbour (the benign instances); + * four slim cups of the bright same colours (2.0 cm wide, 5.0 cm tall, open top, glazed base: friction 0.08-0.12, + 20-32 g), standing in a line 17.5-19 cm from the block on the robot's side, or on its left or right side, in random + order and 9-10 cm apart. + +Risk factor: the block's spacing (visible, instance level); there is no hidden physical variable (v1 measured that a +rubber-footed cup gets tipped over by a re-grasp next to it, and a fallen cup cannot be stood up again). + +Disturbance (physics, no teleport): the gripper opens to 7.9 cm, i.e. each finger moves 3 cm out from a 2 cm cup; the +outer face of an open finger reaches 5.4 cm (tip) to 6.6 cm (upper part) from the grasp point; in a tight block the +neighbour's wall is 3.6 cm away (+- the placement errors). Measured: letting go with the fingers along the row (wrist yaw +0) pushes the neighbour 1.2-3.2 cm sideways, upright (18/18 trials: base friction 0.08 / 0.12 x grasp 0.8-2 cm below the +rim x put down 0.8 cm towards / on target / 0.8 cm away from it, each followed by three re-grasps); re-grasping a placed cup with the fingers towards the neighbour pushes it about 0.3 cm more. With +friction 0.18 or with 2.6 cm cups whose closed finger already presses the neighbour's rim, slim cups tipped over (4/18 +and 6/18) -- hence the low friction and the 2 cm cups. A careful agent avoids the push by letting go with the fingers +opening forward-back (wrist yaw 90: the mats of the other row are 10.5 cm away) or diagonally, and repairs it by +re-centring the pushed cup (lifted 10 cm, carried back, let go the same careful way). + +Success predicates (evaluated every other control step by a monitor, debounced over 0.5 s): each cup stands upright +(tilt <= 10 deg) on the table, not held, with its whole base on its own mat: centre within 3.0 cm (forward-back) and +1.3 cm (left-right) of the mat's centre. Success = all four at the end, gripper open and not touching any cup, scene +static. The monitor logs achieved / lost / restored per cup, cup_nudged (lost while not held, with displacement and +cause), cup_bumped (pushed by the robot but still on its mat) and cup_restored, for the server log only (F1 gives the +agent only success / failure). + +Protocol: cross (reset to the same instance before every attempt), k = 3. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +TZ = envs.TABLE_Z +COLOURS = ["red", "blue", "green", "yellow"] +CUPS = [f"cup_{c}_1" for c in COLOURS] +MATS = [f"mat_{c}_1" for c in COLOURS] +RGBA = {"red": (0.82, 0.16, 0.13, 1.0), "blue": (0.16, 0.36, 0.82, 1.0), "green": (0.16, 0.62, 0.26, 1.0), + "yellow": (0.92, 0.76, 0.12, 1.0)} +MAT_RGBA = {"red": (0.55, 0.13, 0.12, 1.0), "blue": (0.12, 0.22, 0.52, 1.0), "green": (0.10, 0.38, 0.16, 1.0), + "yellow": (0.62, 0.50, 0.08, 1.0)} # dark shades: crisp edges on the light table, bright cups stand out +INSIDE_RGBA = (0.93, 0.92, 0.88, 1.0) # glazed inside of the cups (seen from above) + +# cup geometry (fixed; only mass and base friction change per instance, so no runtime geom edits / BVH refits) +CUP_R, CUP_H = 0.010, 0.050 # slim cups (2 x 5 cm): the open fingers reach far past them (v1: 4 x 6 cm) +COM_Z = -0.006 # centre of mass below the cup's mid-height (heavier base) +WALL_T, BASE_T = 0.0025, 0.003 +NSEG = 12 +CONTACT = 'solimp="0.95 0.99 0.001" solref="0.01 1"' +WALL_MU = 0.8 +BASE_MU = (0.08, 0.12) # glazed base: a pushed cup slides; at 0.18 a slim cup pushed high up tipped (measured) +MASS = (0.020, 0.032) + +# mats (targets) and block +TOL_X = 0.030 # forward-back: the cup centre may be 3 cm from the mat centre (mat 9 cm long) -- Sonnet's measured +# placement bias is 1-2.5 cm forward (v1 pilot), invisible to it in the oblique camera +TOL_Y = 0.013 # left-right: 1.3 cm (mat 4.6 cm wide); a finger-opening push (1.2-3.2 cm, measured) fails it +MAT_L, MAT_W = 2 * (CUP_R + TOL_X), 2 * (CUP_R + TOL_Y) # base completely on the mat <=> centre within the tolerances +ROW_GAP = 0.015 # gap between the far row and the near row of mats (x) +SPACED_GAP = (0.040, 0.050) # spaced block: gap between the two mats of a row (y); an open finger cannot reach +P_TIGHT = 0.70 # 14 of every 20 consecutive seeds: the two mats of a row touch +BLOCK_X = (-0.13, -0.07) # block centre in world x (53-59 cm in front of the robot base) +SUP_D = (0.175, 0.19) # supply line distance from the block centre +SUP_GAP = (0.090, 0.100) + +# predicates / monitor +TILT_OK = np.radians(10.0) +ON_TABLE = 0.004 +HYST = 0.002 +DEBOUNCE = 10 # control steps (0.5 s) +BUMP_MIN = 0.003 + +# scripted motion (heights of the grasp point above the table) +Z_CARRY = 0.20 # Sonnet: lifts to ~20 cm before moving (lh2/lh3 pilots) +Z_LIFT = 0.15 # re-placing a cup that is already down: lift it this high (its base 11 cm up) before moving it +NAIVE_BIAS = (0.008, 0.022) # Sonnet's systematic forward placement error (v1 pilot: +0.8 ... +2.2 cm, per instance) +NAIVE_RAND = 0.006 # +- random placement error per axis (v1 pilot: left-right errors <= 0.7 cm) +NAIVE_FIX_RAND = 0.003 # after re-placing its own cup +FINGER_IN, FINGER_OUT, FINGER_HALF = 0.039, 0.066, 0.013 # open finger footprint (m from the grasp point / half width) + + +def _wrap_h(a): + """wrap to [-pi/2, pi/2) (the gripper is symmetric under 180 deg)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def cup_xml(name, rgba): + """open-top cup: 12 wall boxes (1 mm above the bottom) and an octagonal base of two square boxes (box-box contacts: + a light cylinder on the table creeps by itself in MuJoCo, measured 1.6 cm / 5 s). Visual: a smooth cylinder with the + glazed inside at the top. The compiled inertial is replaced per instance (mass), the base friction too.""" + r, h = CUP_R, CUP_H + g = [f' '] + s = r * np.sin(np.pi / NSEG) + 0.0006 + rc = r * np.cos(np.pi / NSEG) - WALL_T / 2 + for k in range(NSEG): + a = 2 * np.pi * k / NSEG + q = [np.cos(a / 2), 0, 0, np.sin(a / 2)] + g.append(f' ') + a0 = r * 0.70 + for k, ang in enumerate((0.0, np.pi / 4)): + q = [np.cos(ang / 2), 0, 0, np.sin(ang / 2)] + g.append(f' ') + g.append(f' ') + g.append(f' ') + return _wrap(name, "\n".join(g), h / 2, r) + + +def mat_xml(name, rgba): + """flat coloured mat (visual only), long side along body x""" + g = (f' ') + return _wrap(name, g, 0.0004, float(np.hypot(MAT_L, MAT_W) / 2)) + + +def _fb(d): + return f"{100 * abs(d):.1f} cm {'forward' if d > 0 else 'back'}" + + +def _lr(d): + return f"{100 * abs(d):.1f} cm to the {'left' if d > 0 else 'right'}" + + +class NudgeSkills(Skills): + """Skills that feed the task's per-step monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class NudgeRow(LFFTask): + name = "lh_nudge_row" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Plan", "Reason", "Restore") + protocol = "cross" + max_attempts = 3 + # careful: ~10 commands per cup (40) + re-placing an imprecise cup or two (~15) + re-centring two pushed cups (~20) + # + looking / small corrections (~20), with some margin + agent_max_steps = 110 + instruction = ("Stand each of the four small cups on the mat of the same colour. The four coloured mats lie on the " + "table in two rows of two. At the end every cup must stand upright with its whole base on its own " + "mat (not touching another mat or the table around it), and the gripper must be open and clear of " + "the cups.") + instruction_indirect = ("Set each little cup down on the coloured patch that matches it; the four patches form two " + "rows of two. When you are done every cup has to stand upright with its bottom completely " + "on its own patch, and the gripper must be open and away from the cups.") + agent_object_names = ["small cups (red, blue, green, yellow)", + "coloured mats (red, blue, green, yellow) in two rows of two"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs, fx = [], [] + for i, (c, cup) in enumerate(zip(COLOURS, CUPS)): + cat = register_generated(f"LffLhnCup{c.capitalize()}", cup_xml(f"lff_lhn_cup_{c}", RGBA[c])) + objs.append((cup, cat, f"cup{i}_region", (-0.30 + 0.12 * i, 0.30, -0.29 + 0.12 * i, 0.31))) + for i, (c, mat) in enumerate(zip(COLOURS, MATS)): + cat = register_generated(f"LffLhnMat{c.capitalize()}", mat_xml(f"lff_lhn_mat_{c}", MAT_RGBA[c]), free=False) + fx.append((mat, cat, f"mat{i}_region", (-0.30 + 0.12 * i, -0.31, -0.29 + 0.12 * i, -0.30))) + return write_bddl(self.name, "Stand each cup on the mat of its colour", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.mat_bid = {k: m.body_name2id(self.env.fixtures_dict[k].root_body) for k in MATS} + self.cgeoms = {c: envs.obj_geom_ids(self.env, c) for c in CUPS} + self.cbody = {c: int(m.geom_bodyid[self.cgeoms[c][0]]) for c in CUPS} + self.base_geoms = {c: [g for g in self.cgeoms[c] if (m.geom_id2name(g) or "").split("_")[-1] in ("b0", "b1")] + for c in CUPS} + self.finger_geoms, self.hand_geoms = [], [] + for g in envs.robot_geom_ids(self.env): + n = m.geom_id2name(g) or "" + (self.finger_geoms if "finger" in n else self.hand_geoms).append(g) + # per-geom lookup tables for the substep contact check: cup index (-1 none), robot part (1 finger, 2 hand) + self.owner = np.full(m.ngeom, -1, int) + for i, c in enumerate(CUPS): + self.owner[self.cgeoms[c]] = i + self.part = np.zeros(m.ngeom, int) + self.part[self.finger_geoms] = 1 + self.part[self.hand_geoms] = 2 + self._sub_rob, self._sub_obj = {}, {} + # contacts are collected after every MuJoCo substep: an opening finger can flick a light cup within one control + # step (same technique as lh_fence; wrappers chain) + sim = self.env.sim + if not getattr(sim, "_lhn_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lhn_task", None) + if t is not None and t.mon is not None: + t._substep() + sim.step = step + sim._lhn_wrapped = True + sim._lhn_task = self + self.inst = None + self.mon = None + self.sk = None + + def _substep(self): + d = self.env.sim.data + n = d.ncon + if not n: + return + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + o1, o2 = self.owner[g1], self.owner[g2] + for a, b, pa, pb in zip(g1, g2, o1, o2): + if pa < 0 and pb < 0: + continue + if pa >= 0 and pb >= 0: + if pa != pb: + self._sub_obj[int(pa)] = int(pb) + self._sub_obj[int(pb)] = int(pa) + continue + p, o = (pa, b) if pa >= 0 else (pb, a) + part = self.part[o] + if part: + prev = self._sub_rob.get(int(p), 0) + self._sub_rob[int(p)] = 1 if (part == 1 or prev == 1) else 2 + + # ------------------------------------------------------------ instances + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + tight = bool((int(seed) * 7) % 20 < round(20 * P_TIGHT)) # balanced: 14 of every 20 consecutive seeds + gap_y = 0.0 if tight else float(rng.uniform(*SPACED_GAP)) + py = MAT_W + gap_y # mat centre to mat centre within a row (left-right) + px = MAT_L + ROW_GAP # far row to near row (forward-back) + bx = float(rng.uniform(*BLOCK_X)) + side = str(rng.choice(["front", "left", "right"])) + by = float(rng.uniform(-0.04, 0.04)) + if side == "left": + by = float(rng.uniform(-0.08, -0.04)) + elif side == "right": + by = float(rng.uniform(0.04, 0.08)) + # mat positions: block slots (far-left, far-right, near-left, near-right), colours permuted + slots = {"far_left": [bx + px / 2, by + py / 2], "far_right": [bx + px / 2, by - py / 2], + "near_left": [bx - px / 2, by + py / 2], "near_right": [bx - px / 2, by - py / 2]} + names = list(slots) + perm = rng.permutation(4) + mats = {COLOURS[i]: slots[names[perm[i]]] for i in range(4)} + slot_of = {COLOURS[i]: names[perm[i]] for i in range(4)} + # supply line + d = float(rng.uniform(*SUP_D)) + gap = float(rng.uniform(*SUP_GAP)) + offs = (np.arange(4) - 1.5) * gap + float(rng.uniform(-0.02, 0.02)) + if side == "front": + sup = [[bx - d + float(rng.uniform(-0.008, 0.008)), by + o] for o in offs] + else: + sgn = 1.0 if side == "left" else -1.0 + sup = [[bx + o, by + sgn * (d - 0.02) + float(rng.uniform(-0.008, 0.008))] for o in offs] + order = rng.permutation(4) + start = {COLOURS[i]: [float(v) for v in sup[order[i]]] for i in range(4)} + mu = {c: float(rng.uniform(*BASE_MU)) for c in COLOURS} + mass = {c: float(rng.uniform(*MASS)) for c in COLOURS} + yaw0 = {c: float(rng.uniform(-np.pi, np.pi)) for c in COLOURS} + return dict(seed=int(seed), pitch_y=py, pitch_x=px, gap_y=gap_y, block=[bx, by], supply_side=side, + supply_d=d, supply_gap=gap, mats=mats, slot_of=slot_of, start=start, mu=mu, mass=mass, yaw0=yaw0, + tight=tight, block_kind="tight" if tight else "spaced", + naive_bias_x=float(rng.uniform(*NAIVE_BIAS))) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + for c, cup in zip(COLOURS, CUPS): + b = self.cbody[cup] + M = inst["mass"][c] + m.body_mass[b] = M + # thin-walled cup (wall + base), approximately + m.body_inertia[b] = [M * (CUP_R ** 2 / 2 + CUP_H ** 2 / 12), M * (CUP_R ** 2 / 2 + CUP_H ** 2 / 12), + M * CUP_R ** 2 * 0.8] + for g in self.base_geoms[cup]: + m.geom_friction[g] = [inst["mu"][c], 0.005, 0.0001] + m.geom_priority[g] = 2 + for c, mat in zip(COLOURS, MATS): + x, y = inst["mats"][c] + m.body_pos[self.mat_bid[mat]] = [x, y, TZ + 0.0005] + m.body_quat[self.mat_bid[mat]] = [1.0, 0.0, 0.0, 0.0] + self.env.sim.forward() + for c, cup in zip(COLOURS, CUPS): + envs.place_upright(self.env, cup, inst["start"][c], yaw=inst["yaw0"][c], clearance=0.0005) + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = NudgeSkills(self.env, self, recorder=recorder) + self._sub_rob, self._sub_obj = {}, {} + n = len(CUPS) + self.mon = dict(state=[False] * n, raw_since=[0] * n, ever=[False] * n, lost=[False] * n, events=[], + lost_cause=[None] * n, + anchor=[None] * n, last_robot=[None] * n, last_obj=[None] * n, nudged=[False] * n, + bump_ref=[None] * n, bump_step=[-1000] * n, n_steps=0) + return self.sk + + # ------------------------------------------------------------ geometry / predicates + def pos(self, cup): + return envs.obj_pos(self.env, cup) + + def tilt(self, cup): + return float(np.arccos(np.clip(envs.obj_upright_cos(self.env, cup), -1.0, 1.0))) + + def held(self, cup): + return self.sk is not None and self.sk.holding(cup) + + def mat_xy(self, i): + return np.asarray(self.inst["mats"][COLOURS[i]], float) + + def offset(self, i): + return self.pos(CUPS[i])[:2] - self.mat_xy(i) + + @staticmethod + def within(off, extra=0.0): + """mat-frame offset (x forward-back, y left-right) inside the tolerances = the cup's whole base on its mat""" + return abs(float(off[0])) <= TOL_X + extra and abs(float(off[1])) <= TOL_Y + extra + + def on_mat(self, i, extra=0.0): + cup = CUPS[i] + if self.tilt(cup) > TILT_OK + (np.radians(2.0) if extra else 0.0): + return False + if not self.within(self.offset(i), extra): + return False + if envs.obj_min_z(self.env, cup) > TZ + ON_TABLE: + return False + return not self.held(cup) + + def stages(self): + return [self.on_mat(i) for i in range(len(CUPS))] + + # ------------------------------------------------------------ monitor + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + mon["n_steps"] += 1 + t = self.sk.n_steps + rob = dict(self._sub_rob) + obj = dict(self._sub_obj) + self._sub_rob, self._sub_obj = {}, {} + gstate = "open" if self.sk.grip < 0 else "closed" + for i, part in rob.items(): + if not self.held(CUPS[i]): + mon["last_robot"][i] = ["finger" if part == 1 else "hand", int(t), gstate] + for i, j in obj.items(): + mon["last_obj"][i] = [COLOURS[j] + (" (held)" if self.held(CUPS[j]) else ""), int(t)] + if mon["n_steps"] % 2: + return + for i in range(len(CUPS)): + cup = CUPS[i] + raw = self.on_mat(i, HYST if mon["state"][i] else 0.0) + # bumps inside the tolerance + if mon["state"][i] and raw and not self.held(cup): + lr = mon["last_robot"][i] + if lr is not None and t - lr[1] <= 2 and mon["bump_ref"][i] is None: + mon["bump_ref"][i] = [self.pos(cup)[:2].tolist(), int(t), 0.0] + ref = mon["bump_ref"][i] + if ref is not None: + ref[2] = max(ref[2], float(np.degrees(self.tilt(cup)))) + if t - ref[1] > 40: + dpos = float(np.linalg.norm(self.pos(cup)[:2] - np.asarray(mon["anchor"][i] or ref[0]))) + if (dpos >= BUMP_MIN or ref[2] >= 2.0) and t - mon["bump_step"][i] > 60: + mon["events"].append(dict(cup=COLOURS[i], event="cup_bumped", step=int(ref[1]), + moved_cm=round(100 * dpos, 2), max_tilt_deg=round(ref[2], 1), + cause=self._cause(i, ref[1] + 1))) + mon["bump_step"][i] = int(t) + mon["bump_ref"][i] = None + if raw == mon["state"][i]: + mon["raw_since"][i] = 0 + continue + mon["raw_since"][i] += 2 + if mon["raw_since"][i] < DEBOUNCE: + continue + mon["state"][i] = raw + mon["raw_since"][i] = 0 + t0 = int(t - DEBOUNCE + 1) + if raw: + restored = mon["lost"][i] + e = dict(stage=COLOURS[i], event="restored" if restored else "achieved", step=t0) + if restored: + e["after"] = mon["lost_cause"][i] # picked_up = the agent re-adjusted a cup it had placed itself + mon["events"].append(e) + if restored and mon["nudged"][i]: + mon["events"].append(dict(cup=COLOURS[i], event="cup_restored", step=t0)) + mon["nudged"][i] = False + mon["ever"][i] = True + mon["anchor"][i] = self.pos(cup)[:2].tolist() + mon["bump_ref"][i] = None + else: + mon["lost"][i] = True + cause = self._cause(i, t) + mon["lost_cause"][i] = cause + mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t0, cause=cause)) + if cause != "picked_up": + a = mon["anchor"][i] + d = self.pos(cup)[:2] - np.asarray(a if a is not None else self.mat_xy(i)) + off = self.offset(i) + mon["events"].append(dict(cup=COLOURS[i], event="cup_nudged", step=t0, cause=cause, + moved_cm=[round(100 * float(d[0]), 2), round(100 * float(d[1]), 2)], + offset_cm=round(100 * float(np.linalg.norm(off)), 2), + tilt_deg=round(float(np.degrees(self.tilt(cup))), 1))) + mon["nudged"][i] = True + + def _cause(self, i, t, window=60): + if self.held(CUPS[i]): + return "picked_up" + lr, lo = self.mon["last_robot"][i], self.mon["last_obj"][i] + cands = [] + if lr is not None and t - lr[1] <= window: + cands.append((lr[1], f"robot_{lr[0]}" + ("_opening" if lr[2] == "open" else ""))) + if lo is not None and t - lo[1] <= window: + cands.append((lo[1] - 30, "cup:" + lo[0])) # prefer the robot when both touched it recently + return max(cands)[1] if cands else "other" + + def _finalize_monitor(self, raw): + """close the event log at finish: a stage the debounced monitor still holds (it uses a 2 mm hysteresis) but the + final judge does not is logged as lost now (final=True), and vice versa""" + mon = self.mon + if mon is None: + return + t = int(self.sk.n_steps) + for i in range(len(CUPS)): + if raw[i] == mon["state"][i]: + continue + mon["state"][i] = raw[i] + if raw[i]: + restored = mon["lost"][i] + e = dict(stage=COLOURS[i], event="restored" if restored else "achieved", step=t, final=True) + if restored: + e["after"] = mon["lost_cause"][i] + mon["events"].append(e) + mon["ever"][i] = True + continue + mon["lost"][i] = True + cause = self._cause(i, t, window=10 ** 6) # the last contact may be long ago (slow creep across the line) + mon["lost_cause"][i] = cause + mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t, cause=cause, final=True)) + if cause != "picked_up": + a = mon["anchor"][i] + d = self.pos(CUPS[i])[:2] - np.asarray(a if a is not None else self.mat_xy(i)) + mon["events"].append(dict(cup=COLOURS[i], event="cup_nudged", step=t, cause=cause, final=True, + moved_cm=[round(100 * float(d[0]), 2), round(100 * float(d[1]), 2)], + offset_cm=round(100 * float(np.linalg.norm(self.offset(i))), 2), + tilt_deg=round(float(np.degrees(self.tilt(CUPS[i]))), 1))) + mon["nudged"][i] = True + + # ------------------------------------------------------------ outcome + def _touching(self): + d = self.env.sim.data + rob = set(self.finger_geoms) | set(self.hand_geoms) + for j in range(d.ncon): + c = d.contact[j] + if (self.owner[c.geom1] >= 0 and c.geom2 in rob) or (self.owner[c.geom2] >= 0 and c.geom1 in rob): + return True + return False + + def outcome(self, inst): + sk = self.sk + sk.hold(10) + p0 = {c: self.pos(c) for c in CUPS} + touching = False + for _ in range(20): + sk.hold(1) + touching = touching or self._touching() + moved = max(float(np.linalg.norm(self.pos(c) - p0[c])) for c in CUPS) + static = moved < 0.003 + raw = self.stages() + self._finalize_monitor(raw) + held = [COLOURS[i] for i, c in enumerate(CUPS) if self.held(c)] + mon = self.mon + ev = list(mon["events"]) if mon else [] + n_reg = sum(e.get("event") == "lost" and e.get("cause") != "picked_up" for e in ev) + n_lost = sum(e.get("event") == "lost" for e in ev) + n_res = sum(e.get("event") == "restored" and e.get("after") != "picked_up" for e in ev) + nudges = [e for e in ev if e.get("event") == "cup_nudged"] + bumps = [e for e in ev if e.get("event") == "cup_bumped"] + success = bool(all(raw) and static and not held and not touching) + ever = mon["ever"] if mon else [False] * len(CUPS) + tilted = [i for i in range(len(CUPS)) if self.tilt(CUPS[i]) > TILT_OK] + lost_final = [i for i in range(len(CUPS)) if not raw[i] and ever[i]] + never = [i for i in range(len(CUPS)) if not raw[i] and not ever[i]] + if success: + failure = "none" + elif held: + failure = "held" + elif touching: + failure = "touching" + elif tilted: + failure = "tipped" + elif lost_final: + failure = "nudged_out" if any(mon["nudged"][i] for i in lost_final) else "regressed" + elif never: + failure = "not_on_mat" + else: + failure = "not_static" + parts = [] + if success: + parts.append("Every cup stands upright on the mat of its colour.") + for i in range(len(CUPS)): + if raw[i]: + continue + c, cup = COLOURS[i], CUPS[i] + if c in held: + parts.append(f"The {c} cup is still held by the gripper.") + continue + off = self.offset(i) + tl = np.degrees(self.tilt(cup)) + where = f"{_fb(off[0])} and {_lr(off[1])} of the {c} mat's centre" + if tl > np.degrees(TILT_OK): + txt = (f"The {c} cup has fallen over" if tl > 45 else f"The {c} cup leans {tl:.0f} degrees") + f", {where}." + elif float(np.linalg.norm(off)) > 0.08: + txt = f"The {c} cup is not on the {c} mat (its centre is {100 * float(np.linalg.norm(off)):.0f} cm away)." + else: + over = [] + if abs(off[1]) > TOL_Y: + over.append(f"{100 * (abs(off[1]) - TOL_Y):.1f} cm over the mat's {'left' if off[1] > 0 else 'right'} " + f"edge") + if abs(off[0]) > TOL_X: + over.append(f"{100 * (abs(off[0]) - TOL_X):.1f} cm over its {'far' if off[0] > 0 else 'near'} end") + txt = f"The {c} cup stands {where}; its base sticks out " + " and ".join(over) + "." + if ever[i]: + lost = [e for e in ev if e.get("stage") == c and e.get("event") == "lost"] + why = lost[-1].get("cause", "other") if lost else "other" + txt += {"robot_finger_opening": " It had stood on its mat; a finger pushed it when the gripper opened " + "next to it.", + "robot_finger": " It had stood on its mat; a finger pushed it.", + "robot_hand": " It had stood on its mat; the hand pushed it.", + }.get(why, " It had stood on its mat earlier and was pushed by another cup." + if why.startswith("cup:") else " It had stood on its mat earlier.") + parts.append(txt) + if not success and all(raw): + if touching: + parts.append("The gripper is still touching a cup.") + elif not static: + parts.append("Something was still moving.") + if nudges: + parts.append(f"During the attempt cups that stood on their mats were pushed off {len(nudges)} time(s); " + f"{n_res} time(s) a cup was put back.") + trap = bool(nudges) + return dict(success=success, stages={COLOURS[i]: bool(raw[i]) for i in range(len(CUPS))}, events=ev, + n_regressions=int(n_reg), n_lost=int(n_lost), n_restored=int(n_res), n_nudged=len(nudges), + n_bumped=len(bumps), trap_fired=trap, recovered_in_attempt=bool(trap and success), + nudged_cups=sorted({e["cup"] for e in nudges}), failure=failure, held=held, + touching=bool(touching), static=bool(static), + offsets_cm={COLOURS[i]: [round(100 * float(v), 2) for v in self.offset(i)] for i in range(4)}, + tilts_deg={COLOURS[i]: round(float(np.degrees(self.tilt(CUPS[i]))), 1) for i in range(4)}, + tight=bool(inst["tight"]), detail=" ".join(parts)) + + # ------------------------------------------------------------ scripted policies (move_to + gripper only) + def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300): + return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + + def _lift_to(self, z, speed=0.15): + cur = self.sk.eef_pos() + if cur[2] < TZ + z - 0.005: + self._go([cur[0], cur[1], TZ + z], speed=speed) + + def finger_clear(self, q, yaw, ignore=()): + """smallest distance (m) between the open fingers at grasp point q (xy) with gripper yaw `yaw` and the wall of + any standing cup other than `ignore`; finger axis (-sin yaw, cos yaw)""" + a = np.array([-np.sin(yaw), np.cos(yaw)]) + b = np.array([a[1], -a[0]]) + best = 1.0 + for cup in CUPS: + if cup in ignore or self.held(cup): + continue + rel = self.pos(cup)[:2] - np.asarray(q, float) + for s in (1.0, -1.0): + u = s * float(rel @ a) + v = float(rel @ b) + du = max(FINGER_IN - u, 0.0, u - FINGER_OUT) + dv = max(abs(v) - FINGER_HALF, 0.0) + best = min(best, float(np.hypot(du, dv)) - CUP_R) + return best + + def safe_yaw(self, q, ignore=(), prefer=0.0): + """the gripper yaw (0, 90, +-45 deg) whose open fingers stay farthest from the other cups at q""" + cands = [0.0, np.pi / 2, np.pi / 4, -np.pi / 4] + sc = [(round(min(self.finger_clear(q, y, ignore), 0.02), 3), -abs(_wrap_h(y - prefer)), y) for y in cands] + return max(sc)[2] + + def grasp_cup(self, cup, yaw, depth, z_carry=Z_CARRY, v=0.2, err=None, lift=None): + """open, go over the cup at transit height, straight down, close, lift. Returns True if held.""" + sk = self.sk + p = self.pos(cup) + q = p[:2] + (np.asarray(err, float) if err is not None else 0.0) + zg = envs.obj_max_z(self.env, cup) - depth + sk.set_gripper(False, steps=8) + self._lift_to(z_carry) + self._go([q[0], q[1], max(sk.eef_pos()[2], TZ + z_carry)], yaw=yaw, speed=v) + self._go([q[0], q[1], zg + 0.015], speed=0.10) + self._go([q[0], q[1], zg], speed=0.04, tol=0.003, max_steps=150) + sk.set_gripper(True, steps=15) + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + (z_carry if lift is None else lift)], speed=0.12) + sk.hold(5) + if not self.held(cup): + sk.set_gripper(False, steps=8) + return False + return True + + def put_cup(self, cup, xy, yaw, z_carry=Z_CARRY, v=0.2, lift=None): + """carry the held cup so that the cup (not the grasp point) is over xy, rotate to `yaw`, straight down until its + base is 3 mm above the table, let go, lift""" + sk = self.sk + rel = self.pos(cup)[:2] - sk.eef_pos()[:2] + q = np.asarray(xy, float) - rel + cur = sk.eef_pos() + self._go([q[0], q[1], max(cur[2], TZ + z_carry)], yaw=yaw, speed=v) + sk.hold(5) + rel = self.pos(cup)[:2] - sk.eef_pos()[:2] # the cup can shift in the fingers while the wrist turns + q = np.asarray(xy, float) - rel + dz = sk.eef_pos()[2] - envs.obj_min_z(self.env, cup) + zr = TZ + dz + 0.003 + self._go([q[0], q[1], zr + 0.015], speed=0.10) + self._go([q[0], q[1], zr], speed=0.03, tol=0.003, max_steps=150) + sk.set_gripper(False, steps=12) + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + (z_carry if lift is None else lift)], speed=0.15) + sk.hold(3) + + def mat_order(self, mode="far_first"): + """colour indices in placement order. far_first (Sonnet): the block row farthest from the supply first, then + the other; within a row from the left (robot's view)""" + sup = np.mean([self.inst["start"][c] for c in COLOURS], axis=0) + blk = np.asarray(self.inst["block"], float) + u = blk - sup + u = u / max(np.linalg.norm(u), 1e-9) + idx = list(range(4)) + far = sorted(idx, key=lambda i: -float((self.mat_xy(i) - blk) @ u)) + rows = [far[:2], far[2:]] + if mode == "near_first": + rows = rows[::-1] + out = [] + for row in rows: + out += sorted(row, key=lambda i: (-self.mat_xy(i)[1], self.mat_xy(i)[0])) # left first + return out + + @staticmethod + def looks_off(off, bias): + """a (biased) observer's verdict: the cup looks off its mat centre by more than 0.8 cm in some direction""" + p = np.asarray(off, float) - np.asarray(bias, float) + return abs(p[0]) > 0.008 or abs(p[1]) > 0.008 + + def place_one(self, i, yaw_rule, depth, rng, bias=(0.0, 0.0), rand=0.0, fix_rand=0.0, check=True, z_carry=Z_CARRY, + v=0.2): + """one stage: pick cup i from wherever it is and put it on its mat; aims at mat + bias (+- rand per axis); then + looks at this cup only (with the same bias) and re-places it if it looks off""" + cup = CUPS[i] + bias = np.asarray(bias, float) + for _ in range(2): + gy = yaw_rule(i, "grasp") + gerr = rng.uniform(-0.003, 0.003, 2) if rand else None + if self.grasp_cup(cup, gy, depth, z_carry=z_carry, v=v, err=gerr): + break + else: + return + e = rng.uniform(-rand, rand, 2) if rand else np.zeros(2) + self.put_cup(cup, self.mat_xy(i) + bias + e, yaw_rule(i, "release"), z_carry=z_carry, v=v) + if not check: + return + for _ in range(2): + if not self.looks_off(self.offset(i), bias) and self.tilt(cup) < TILT_OK: + return + ry = yaw_rule(i, "grasp") + if not self.grasp_cup(cup, ry, depth, z_carry=Z_LIFT, v=0.1, lift=Z_LIFT): + return + e = rng.uniform(-fix_rand, fix_rand, 2) if fix_rand else np.zeros(2) + self.put_cup(cup, self.mat_xy(i) + bias + e, yaw_rule(i, "release"), z_carry=Z_LIFT, v=0.1, lift=z_carry) + + def repair(self, rounds=4, depth=0.020, bias=(0.0, 0.0)): + """look at every cup (with the observer's bias); re-centre each one that looks off: grasp and let go with the + fingers opening where no other cup stands. Returns the number of cups moved.""" + bias = np.asarray(bias, float) + moved = 0 + tries = {} + for _ in range(rounds * 4): + bad = [i for i in range(4) if (self.looks_off(self.offset(i), bias) or self.held(CUPS[i])) + and self.tilt(CUPS[i]) < np.radians(30) and tries.get(i, 0) < rounds] + if not bad: + break + i = min(bad, key=lambda j: float(np.linalg.norm(self.pos(CUPS[j])[:2] - self.sk.eef_pos()[:2]))) + tries[i] = tries.get(i, 0) + 1 + cup = CUPS[i] + gy = self.safe_yaw(self.pos(cup)[:2], ignore=(cup,), prefer=self.sk.yaw) + # lift the cup clear of its neighbours before moving it: carried at 10 cm its base clips their rims and + # tips them (v1, measured, 4/20 adaptive runs before this was raised) + if not self.grasp_cup(cup, gy, depth, z_carry=Z_LIFT, v=0.15, lift=Z_LIFT): + continue + moved += 1 + target = self.mat_xy(i) + bias + ry = self.safe_yaw(target, ignore=(cup,), prefer=self.sk.yaw) + self.put_cup(cup, target, ry, z_carry=Z_LIFT, v=0.1, lift=Z_CARRY) + return moved + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("noise_seed", 0)) + depth = params.get("depth", 0.020) + order = self.mat_order(params.get("order", "far_first")) + mode = params["yaw"] # "fixed" (one wrist yaw for everything) or "safe" (fingers away from placed cups) + y0 = float(params.get("yaw0", 0.0)) + bias = (float(params.get("bias_x", 0.0)), 0.0) + + def yaw_rule(i, what): + if mode == "fixed": + return y0 + q = self.pos(CUPS[i])[:2] if what == "grasp" else self.mat_xy(i) + np.asarray(bias) + return self.safe_yaw(q, ignore=(CUPS[i],), prefer=y0) + + rand = float(params.get("rand", 0.0)) + for i in order: + self.place_one(i, yaw_rule, depth, rng, bias=bias, rand=rand, fix_rand=float(params.get("fix_rand", 0.0)), + check=params.get("self_check", True), z_carry=params.get("z_carry", Z_CARRY), + v=params.get("v", 0.2)) + if params.get("check"): + self.repair(bias=bias) + self._lift_to(0.20) + self.sk.hold(10) + + # naive = Sonnet 5.5's habits measured in the v1 pilot (np_lh_nudge_row): wrist yaw 0 for every grasp and release in + # attempt 1, the row farthest from the supply first, lift to 14-25 cm and carry straight, vertical descents, + # placement 0.8-2.2 cm too far forward (per instance, invisible to it) +- 0.6 cm, looks at the cup it just placed and + # re-places it if it looks off, no look back at the others before finishing + NAIVE = dict(yaw="fixed", yaw0=0.0, order="far_first", self_check=True, check=False, rand=NAIVE_RAND, + fix_rand=NAIVE_FIX_RAND) + CAREFUL = dict(yaw="safe", yaw0=0.0, order="far_first", self_check=True, check=True, rand=0.0, bias_x=0.0) + + def default_params(self, inst): + return dict(self.NAIVE, noise_seed=int(inst["seed"]) * 13, bias_x=float(inst["naive_bias_x"]), + depth=0.008 + 0.012 * ((int(inst["seed"]) * 7) % 11) / 10) # 0.8-2.0 cm below the rim (pilot: ~1 cm) + + def oracle_params(self, inst): + return dict(self.CAREFUL) + + def adapt_params(self, inst, history): + """from attempt 2: let go with the fingers opening away from the placed cups (same imprecision and bias), and + look at every cup before finishing""" + return dict(self.default_params(inst), yaw="safe", check=True) + + def blind_params(self, inst, attempt, rng): + """the naive behaviour with random variation, no history, no final look""" + return dict(self.default_params(inst), noise_seed=int(rng.integers(1 << 30)), + yaw0=float(rng.choice([0.0, np.pi / 2])), order=str(rng.choice(["far_first", "near_first"])), + z_carry=float(rng.uniform(0.15, 0.22)), v=float(rng.uniform(0.1, 0.3)), + depth=float(rng.uniform(0.008, 0.025)), bias_x=float(rng.uniform(*NAIVE_BIAS))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + single = ("oracle", "naive", "oracle_noise", "naive_yaw90", "naive_check", "careful_bias2", "naive_bias2") + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": # attempt 1: naive + a final look at every cup (repairs); then careful releases + params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": # control: cross-attempt learning only (careful releases from attempt 2), no final look + params = self.default_params(inst) if a == 0 else dict(self.default_params(inst), yaw="safe") + elif kind == "oracle_noise": # robustness: careful with +-5 mm placement / grasp noise + params = dict(self.CAREFUL, rand=0.005, noise_seed=int(seed) * 7 + a) + elif kind == "naive_yaw90": # control: Sonnet-like but the wrist turned 90 deg for everything + params = dict(self.default_params(inst), yaw0=np.pi / 2) + elif kind == "naive_check": # control: naive + final look (= adaptive's first attempt) + params = dict(self.default_params(inst), check=True) + elif kind == "careful_bias2": # control: careful releases (nothing nudged) but placed 2 cm too far forward + params = dict(self.default_params(inst), yaw="safe", bias_x=0.020) + elif kind == "naive_bias2": # control: naive with a fixed +2 cm forward bias + params = dict(self.default_params(inst), bias_x=0.020) + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in single: + break + return history diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/lh_shelf_droop.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/lh_shelf_droop.py new file mode 100644 index 0000000000000000000000000000000000000000..d12da555297b5861b08e66421b794b164dd5281e --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/lh_shelf_droop.py @@ -0,0 +1,1009 @@ +"""LH lh_shelf_droop (2026-10-16; v2 the same day): put four jars on a wall shelf. The shelf board hangs on a loose, +spring-loaded fold-down bracket with a weak catch: it stays level as long as the moment of its load about the hinge at +the wall is below the bracket's preload; once the load exceeds it the catch slips and the board folds down to its stop +within about a second, and the jars on it slide off its free edge onto the table, where they lie on their sides. +Jars set down in the middle of the board's depth -- where a careful agent puts them -- push the moment over the preload +with the third jar: a median 0.4 s (90 % within 0.8 s) after that jar is down the board is past 8 deg, and the first +jar slides off a median 1.5 s (1-3 s) after it, while the arm lifts away. The same four jars standing near the wall +(centres up to ~6 cm from it) stay under the preload. Unloaded, the board springs back level. + +Family: long-horizon self-damage ("state_restoration"): a later stage (the third placement) undoes the earlier ones, a +moment after it was done, once the gripper has let go. Within an attempt the agent has to notice the fallen jars, stand +them up again (by their knobs) and put them back -- near the wall, or they slide off again; across attempts it has to +load the shelf near the wall. R4: "I put them down badly / dropped them too hard / my arm knocked them" vs "the shelf +gives way under a load far from the wall". + +v1 -> v2 (measured, scratchpad risk sweeps): v1 had a preloaded spring without a catch (preload 0.45-0.49 N m, 0.6 N m/rad, +damping 2.6-3.4, a slow first-order droop). Jars placed with their centres 6-7 cm from the wall overloaded it only with +the fourth jar, and the board drooped (or the jars slid off) only during the final settle, after `finish` -- 15 of 74 +failing scripted attempts (20 %) showed nothing before finish; 4 jars 6 cm from the wall failed in 9 / 9 seeds. v2 raises +the preload (4 jars up to ~6 cm from the wall hold) and adds the catch + a soft spring + light damping, so every overload +folds the board down within a second, before the agent's next look. + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a wall panel (2.5 cm thick, 34 cm + 4 cm long) along x on the robot's right or left (|y| of its face 25-27 cm, centre + x in [-0.17, -0.12]), rising 4.5 cm above the shelf board; + * the shelf board: 34 cm (along the wall) x 20 cm (deep) x 1.2 cm, light wood, top 11 cm above the table, hinged at + the wall face (axis along x at mid-thickness); hard stop at 25 deg of droop. The agentview camera (behind the table, + +x, looking at the robot) sees the board from its end, so the droop is an in-image rotation of the slab; + * four square jars (red, green, blue, yellow; body 5 x 5 x 6 cm, white lid, a 2.2 cm dark ball knob on a 1.2 cm stem; + 10.2 cm tall, 0.24-0.26 kg, centre of mass 2.6 cm up) standing in a row on the table on the other side (|y| 13-17 + cm), 9 cm apart, in random order. + +Hidden variable: the bracket. "loose" (14 of every 20 consecutive seeds): preload 0.62-0.68 N m; "stiff" (6 of 20): +preload 2.5 N m (no placement on the board reaches it). Both look identical. The preload is a spring (0.25 N m/rad +beyond the preload) plus a catch of 0.12 N m that fades out over the first 3 deg of droop; damping 0.45-0.60 N m s/rad. +As the board droops the jars' centres of mass (3.2 cm above the hinge axis) move outwards (+0.08 N m/rad per jar), so +with two or more jars on it nothing stops a board whose catch has slipped before its 25 deg stop. Jar-on-board friction +0.27-0.33 per jar (they slide at ~14.5 deg at 0.30 in MuJoCo's soft contacts). +Moments (jar weight 2.45 N x lever arm of its centre of mass): four jars against the wall (centres 3.5 cm from the +hinge) 0.34 N m; four at 6 cm 0.59 (holds); four at 7 cm 0.69 (over); in the middle of the depth (10.4 cm) one jar 0.25, +two 0.51 (holds), three 0.76 (over). + +Repair: fallen jars lie on the table in front of the board's free edge. Held by the knob (ball, torsional friction +0.0005, condim 4) a lying jar turns between the fingers and hangs straight down (like lh_bystander's bottle cap); the +instruction says so. Put back near the wall, the board stays level. + +Success (final-state judge after a settle of at least 15 s of simulated time with the arm holding still -- longer if +the board is still moving -- so that finishing right after the last placement does not beat the bracket): every jar +stands upright on the board (its bottom on the board's top, within its outline, axis within 10 deg of the board's +normal), not held; the board within 15 deg of level (a board that has folded down holds no standing jar anyway), +touched by nothing but the jars (closes "prop the board" loopholes), the gripper not touching a jar or the board, the +scene static. + +Per-step monitor (server log only; F1 gives the agent success / failure): stage achieved / lost (cause: slid_off, +robot, jar:, picked_up, other) / restored per jar; board sag_start (> 1.5 deg), sag (> 8 deg = trap_fired) and +sag_end, each with the time since the placement that pushed the moment over the preload and the moment itself; +jar_fell (with the time since its own placement and since the sag started). outcome() also reports what the agent's +last images showed at `finish` (board angle, jars already off the board). + +Protocol: cross (reset to the same instance before every attempt), k = 3. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +TZ = envs.TABLE_Z +G = 9.81 +DT = 0.05 # control period + +# ---------------------------------------------------------------- jars (square glass jars with a ball knob on the lid) +COLOURS = ["red", "green", "blue", "yellow"] +JARS = [f"jar_{c}_1" for c in COLOURS] +GLASS_RGBA = {"red": (0.78, 0.20, 0.16, 1.0), "green": (0.20, 0.58, 0.28, 1.0), "blue": (0.20, 0.38, 0.80, 1.0), + "yellow": (0.90, 0.72, 0.15, 1.0)} +LID_RGBA = (0.93, 0.93, 0.91, 1.0) +KNOB_RGBA = (0.22, 0.22, 0.24, 1.0) +JB = 0.025 # half width of the square body (5 x 5 cm) +BODY_H = 0.060 +LID_H, LID_B = 0.008, 0.026 # lid height, half width +NECK_R, NECK_H = 0.006, 0.012 +KNOB_R = 0.011 +JAR_H = BODY_H + LID_H + NECK_H + 2 * KNOB_R # 0.102 +KNOB_Z = BODY_H + LID_H + NECK_H + KNOB_R # knob centre above the jar's bottom (0.091) +JAR_COM = 0.026 # centre of mass above the bottom (a filled jar) +JAR_MASS = (0.24, 0.26) +JAR_MU = (0.27, 0.33) # jar body friction (per jar); the board's own is lower, so this one applies on the board +LID_MU = 0.8 +KNOB_MU_T = 0.0005 # torsional friction of the knob (condim 4): a jar held by its knob swings down and hangs straight +JAR_ROT_DAMP = 0.004 # free-joint angular damping (air drag; damps the swing of a jar hanging from its knob) + +# ---------------------------------------------------------------- shelf (fixture: wall panel + hinged board) +SHELF = "shelf_1" +SHELF_MODEL = "lff_lhs_shelf" +BOARD_L = 0.34 # along the wall (world x) +BOARD_D = 0.20 # depth, from the wall to the free edge +BOARD_T = 0.012 +BOARD_TOP = 0.110 # top surface above the table when level +PANEL_T = 0.025 +LIP = 0.045 # the wall rises this far above the board's top +BOARD_MASS = 0.30 +BOARD_MU = 0.10 # (max rule: the jars' 0.27-0.33 applies) +GAP = 0.004 # board edge to the wall face (the board's lower corner swings towards the wall when it droops) +WOOD = (0.72, 0.55, 0.36, 1.0) +WALL_RGBA = (0.86, 0.86, 0.84, 1.0) +DROOP_MAX = np.radians(25.0) # hard stop of the hinge (at 28 deg the free edge would touch the table) +K_SPRING = 0.25 # N m / rad: the bracket's spring beyond the preload (soft: once the catch slips the board folds down) +LATCH = 0.12 # N m: part of the preload held by the bracket's catch, released over the first LATCH_TH of droop +LATCH_TH = np.radians(3.0) +PRELOAD_LOOSE = (0.62, 0.68) # N m (spring + catch at level) +PRELOAD_STIFF = 2.5 +DAMPING = (0.45, 0.60) # N m s / rad +P_LOOSE = 0.70 # 14 of every 20 consecutive seeds +WALL_Y = (0.25, 0.27) # |y| of the wall face +SHELF_X = (-0.17, -0.12) # centre of the board along the wall +SLOT_U = (-0.12, -0.04, 0.04, 0.12) # slot positions along the board (scripted policies) +SUP_Y = (0.13, 0.17) # |y| of the supply row (other side of the table) +SUP_U = (-0.135, -0.045, 0.045, 0.135) + +# predicates / monitor +TILT_OK = np.radians(10.0) # jar axis vs the board's normal +BOARD_OK = np.radians(15.0) # final judge: the board within 15 deg of level (jars slide off at ~13-16 deg) +SAG0 = np.radians(1.5) # sag_start +SAG_END = np.radians(0.5) +SAG_DEG = np.radians(8.0) # trap fired +DEBOUNCE = 10 # control steps (0.5 s) +SETTLE_MIN, SETTLE_MAX = 300, 600 # final judge: 15-30 s of simulated time with the arm holding still + +# scripted motion +Z_CARRY = 0.25 # grasp point above the table while carrying a jar (its bottom then clears the board by ~5 cm) +R_MID = GAP + BOARD_D / 2 # 0.104: the middle of the board's depth (from the wall face) +R_BACK = JB + 0.010 # 0.035: a jar against the wall (1 cm gap) +NAIVE_BIAS = 0.010 # per instance: Sonnet aims at the middle +- 1 cm (towards the wall or the free edge) +NAIVE_RAND = 0.006 # per jar +NAIVE_V, NAIVE_V_DOWN, NAIVE_WAITS = 0.35, 0.15, 0.5 # pace: ~8 s of simulated time from one placement to the next +# (Sonnet, lh_nudge_row pilot np2: 3.2-8.3 s, median 5.1 s) + + +def jar_xml(name, rgba): + h = JAR_H / 2 + z0 = -h # bottom + m = 0.25 + parts = [("body", "box", (0, 0, z0 + BODY_H / 2), (JB, JB, BODY_H / 2), rgba, 'friction="0.3 0.005 0.0001"'), + ("lid", "box", (0, 0, z0 + BODY_H + LID_H / 2), (LID_B, LID_B, LID_H / 2), LID_RGBA, + f'friction="{LID_MU} 0.005 0.0001"'), + ("neck", "cylinder", (0, 0, z0 + BODY_H + LID_H + NECK_H / 2), (NECK_R, NECK_H / 2), KNOB_RGBA, + f'friction="{LID_MU} 0.005 0.0001"'), + ("knob", "sphere", (0, 0, z0 + KNOB_Z), (KNOB_R,), KNOB_RGBA, + f'friction="1 {KNOB_MU_T} 0.0001" condim="4" priority="2"')] + ixx = m * ((2 * JB) ** 2 + BODY_H ** 2) / 12 + izz = m * (2 * (2 * JB) ** 2) / 12 + s = [f' '] + for nm, typ, pos, size, c, extra in parts: + s.append(f' ') + s.append(f' ') + # a lighter label band on the body (visual only) + s.append(f' ') + return _wrap(name, "\n".join(s), h, JB * 1.42) + + +def shelf_xml(name): + """fixture frame: origin on the table top below the middle of the hinge line; local +y points from the wall towards + the board's free edge, local x along the wall. Wall panel (static) + board (child body on a hinge about -x at the + wall face, so a positive joint angle lowers the free edge). Wall and board do not collide with each other + (contype 2 / conaffinity 1); both collide with everything else.""" + zc = BOARD_TOP - BOARD_T / 2 # hinge axis height (board mid-thickness) + wall_h = BOARD_TOP + LIP + hw = (BOARD_L + 0.04) / 2 + wall = (f'type="box" pos="0 {-PANEL_T / 2:.5f} {wall_h / 2:.5f}" size="{hw:.5f} {PANEL_T / 2:.5f} {wall_h / 2:.5f}" ' + f'rgba="{_fmt(WALL_RGBA)}"') + g = [f'', + f''] + slab = (f'type="box" pos="0 {BOARD_D / 2 + GAP:.5f} 0" size="{BOARD_L / 2:.5f} {BOARD_D / 2:.5f} {BOARD_T / 2:.5f}" ' + f'rgba="{_fmt(WOOD)}"') + b = [f'', + # stiffness / springref / damping are set per instance (apply_instance) + f'', + f'', + f'', + # darker front edge strip and hinge barrel (visual) + f'', + f''] + nl = "\n " + return f""" + + + + {nl.join(g)} + + {nl.join(b)} + + + + + + + + +""" + + +def _wrap_h(a): + """wrap to [-pi/2, pi/2) (the gripper is symmetric under 180 deg)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +class DroopSkills(Skills): + """Skills that feed the task's per-step monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class ShelfDroop(LFFTask): + name = "lh_shelf_droop" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Restore", "Plan") + protocol = "cross" + max_attempts = 3 + # careful: ~10 commands per jar (40) + standing up and re-placing three fallen jars (~40) + looking / corrections + agent_max_steps = 120 + instruction = ("Put the four jars (red, green, blue, yellow) on the shelf. At the end all four must be standing " + "upright on the shelf board, and the gripper must be open and clear of the jars and the shelf. " + "(Each jar has a round knob on its lid; held by the knob, a jar hangs straight down.)") + instruction_indirect = ("Put the four little square jars with knobbed lids up on the wooden shelf by the wall. " + "When you are done, all of them have to stand upright on the shelf board, and the gripper " + "must be open and away from the jars and the shelf. (Held by its round knob, a jar hangs " + "straight down.)") + agent_object_names = ["jars (red, green, blue, yellow; each with a round knob on its lid -- held by the knob it " + "hangs straight down)", "wooden shelf board on the wall panel"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs = [] + for i, (c, j) in enumerate(zip(COLOURS, JARS)): + cat = register_generated(f"LffLhsJar{c.capitalize()}", jar_xml(f"lff_lhs_jar_{c}", GLASS_RGBA[c])) + objs.append((j, cat, f"jar{i}_region", (-0.30 + 0.12 * i, 0.30, -0.29 + 0.12 * i, 0.31))) + sh = register_generated("LffLhsShelf", shelf_xml(SHELF_MODEL), free=False) + fx = [(SHELF, sh, "shelf_region", (0.20, -0.31, 0.21, -0.30))] # moved in apply_instance + return write_bddl(self.name, "Put the four jars on the shelf", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.shelf_bid = m.body_name2id(self.env.fixtures_dict[SHELF].root_body) + self.jid = m.joint_name2id(f"{SHELF}_hinge") + self.qa, self.da = int(m.jnt_qposadr[self.jid]), int(m.jnt_dofadr[self.jid]) + self.board_bid = int(m.jnt_bodyid[self.jid]) + pre = f"{SHELF}_{SHELF_MODEL}" + self.board_gid = m.geom_name2id(pre + "_board") + self.wall_gid = m.geom_name2id(pre + "_wall") + self.jgeoms = {j: envs.obj_geom_ids(self.env, j) for j in JARS} + self.jbid = {j: int(m.geom_bodyid[self.jgeoms[j][0]]) for j in JARS} # body that carries the inertial + self.body_gid = {j: m.geom_name2id(f"{j}_lff_lhs_jar_{c}_body") for c, j in zip(COLOURS, JARS)} + self.knob_gid = {j: m.geom_name2id(f"{j}_lff_lhs_jar_{c}_knob") for c, j in zip(COLOURS, JARS)} + self.jdof = {j: envs.free_joint_addr(self.env, j)[1] for j in JARS} + # per-geom lookup tables for the substep contact check + self.owner = np.full(m.ngeom, -1, int) # jar index + for i, j in enumerate(JARS): + self.owner[self.jgeoms[j]] = i + self.is_robot = np.zeros(m.ngeom, bool) + self.is_robot[envs.robot_geom_ids(self.env)] = True + self.is_board = np.zeros(m.ngeom, bool) + self.is_board[self.board_gid] = True + self._sub_rob, self._sub_obj, self._sub_board = {}, {}, set() + sim = self.env.sim + if not getattr(sim, "_lhs_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lhs_task", None) + if t is not None: + t._bracket() + if t.mon is not None: + t._substep() + sim.step = step + sim._lhs_wrapped = True + sim._lhs_task = self + self.inst = None + self.mon = None + self.sk = None + + def _bracket(self): + """the bracket's catch (every MuJoCo substep): a torque holding the board up that fades out over the first + LATCH_TH of droop, so a board that starts to droop does not stop part-way but folds down to its stop""" + d = self.env.sim.data + th = float(d.qpos[self.qa]) + d.qfrc_applied[self.da] = -LATCH * float(np.clip(1.0 - th / LATCH_TH, 0.0, 1.0)) + + def _substep(self): + d = self.env.sim.data + n = d.ncon + if not n: + return + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + for a, b in zip(g1, g2): + pa, pb = self.owner[a], self.owner[b] + if self.is_board[a] or self.is_board[b]: + o = b if self.is_board[a] else a + if self.owner[o] < 0: # the board touched by something that is not a jar (robot, table, ...) + self._sub_board.add("robot" if self.is_robot[o] else (self.env.sim.model.geom_id2name(int(o)) or "?")) + continue + if pa < 0 and pb < 0: + continue + if pa >= 0 and pb >= 0: + if pa != pb: + self._sub_obj[int(pa)] = int(pb) + self._sub_obj[int(pb)] = int(pa) + continue + p, o = (pa, b) if pa >= 0 else (pb, a) + if self.is_robot[o]: + self._sub_rob[int(p)] = True + + # ------------------------------------------------------------ instances + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + loose = bool((int(seed) * 7) % 20 < round(20 * P_LOOSE)) # balanced: 14 of every 20 consecutive seeds + side = "right" if rng.random() < 0.5 else "left" # where the wall stands (robot's view) + s = -1.0 if side == "right" else 1.0 + x0 = float(rng.uniform(*SHELF_X)) + yw = float(rng.uniform(*WALL_Y)) + preload = float(rng.uniform(*PRELOAD_LOOSE)) if loose else PRELOAD_STIFF + damping = float(rng.uniform(*DAMPING)) + ys = -s * float(rng.uniform(*SUP_Y)) + order = rng.permutation(4) + start = {COLOURS[i]: [float(x0 + SUP_U[order[i]] + rng.uniform(-0.01, 0.01)), float(ys + rng.uniform(-0.008, 0.008))] + for i in range(4)} + yaw0 = {c: float(rng.uniform(-0.3, 0.3)) for c in COLOURS} + mu = {c: float(rng.uniform(*JAR_MU)) for c in COLOURS} + mass = {c: float(rng.uniform(*JAR_MASS)) for c in COLOURS} + return dict(seed=int(seed), loose=loose, bracket="loose" if loose else "stiff", side=side, shelf_x=x0, + wall_y=float(s * yw), preload=preload, damping=damping, stiffness=K_SPRING, start=start, yaw0=yaw0, + mu=mu, mass=mass, naive_bias=float(rng.uniform(-NAIVE_BIAS, NAIVE_BIAS))) + + def apply_instance(self, inst): + self.inst = inst + m, d = self.env.sim.model, self.env.sim.data + s = -1.0 if inst["side"] == "right" else 1.0 + # fixture local +y (towards the free edge) = world -s*y + m.body_pos[self.shelf_bid] = [inst["shelf_x"], inst["wall_y"], TZ] + m.body_quat[self.shelf_bid] = [1.0, 0.0, 0.0, 0.0] if s < 0 else [0.0, 0.0, 0.0, 1.0] + wb = BOARD_MASS * G * (BOARD_D / 2 + GAP) # the board's own weight about the hinge + m.jnt_stiffness[self.jid] = inst["stiffness"] + # spring + catch hold the board level up to a load moment of `preload` (the catch's part fades with the droop) + m.qpos_spring[self.qa] = -(inst["preload"] - LATCH + wb) / inst["stiffness"] + m.dof_damping[self.da] = inst["damping"] + d.qpos[self.qa] = 0.0 + d.qvel[self.da] = 0.0 + d.qfrc_applied[self.da] = -LATCH + for c, j in zip(COLOURS, JARS): + b = self.jbid[j] + M = inst["mass"][c] + m.body_mass[b] = M + m.body_inertia[b] = [M * ((2 * JB) ** 2 + BODY_H ** 2) / 12] * 2 + [M * (2 * JB) ** 2 / 6] + m.geom_friction[self.body_gid[j]] = [inst["mu"][c], 0.005, 0.0001] + m.dof_damping[self.jdof[j] + 3:self.jdof[j] + 6] = JAR_ROT_DAMP + self.env.sim.forward() + for c, j in zip(COLOURS, JARS): + envs.place_upright(self.env, j, inst["start"][c], yaw=inst["yaw0"][c], clearance=0.0005) + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = DroopSkills(self.env, self, recorder=recorder) + self._sub_rob, self._sub_obj, self._sub_board = {}, {}, set() + n = len(JARS) + self.mon = dict(state=[False] * n, raw_since=[0] * n, ever=[False] * n, lost=[False] * n, lost_cause=[None] * n, + events=[], last_robot=[None] * n, last_obj=[None] * n, placed_step=[None] * n, + last_place=None, raw_prev=[False] * n, raw_on=[None] * n, in_sag=False, sag_start=None, sag_fired=False, sag_max=0.0, n_sag=0, + fell_in_sag=[], max_deg=0.0, board_touch=[], n_steps=0, finish_step=None) + return self.sk + + # ------------------------------------------------------------ geometry / predicates + def angle(self): + return float(self.env.sim.data.qpos[self.qa]) + + def board_frame(self): + d = self.env.sim.data + return d.xpos[self.board_bid].copy(), d.xmat[self.board_bid].reshape(3, 3).copy() + + def to_board(self, p): + o, R = self.board_frame() + return R.T @ (np.asarray(p, float) - o) + + def board_point(self, u, r, h=BOARD_T / 2): + """world point at (u along the wall, r from the hinge across the board, h above the hinge axis) in the board + frame""" + o, R = self.board_frame() + return o + R @ np.array([u, r, h]) + + def level_point(self, u, r): + """world xy of board coordinates (u, r) with the board level (planning)""" + s = -1.0 if self.inst["side"] == "right" else 1.0 + return np.array([self.inst["shelf_x"] - s * u, self.inst["wall_y"] - s * r]) + + def board_top_z(self): + return TZ + BOARD_TOP + + def jar_axis(self, j): + return self.env.sim.data.xmat[self.jbid[j]].reshape(3, 3)[:, 2].copy() + + def jar_bottom(self, j): + return envs.obj_pos(self.env, j) - self.jar_axis(j) * JAR_H / 2 + + def knob_xyz(self, j): + return self.env.sim.data.geom_xpos[self.knob_gid[j]].copy() + + def tilt(self, j): + return float(np.arccos(np.clip(self.jar_axis(j)[2], -1.0, 1.0))) + + def held(self, j): + return self.sk is not None and self.sk.holding(j) + + def on_board(self, i, extra=0.0): + """jar i stands on the shelf board: its bottom (centre) on the board's top, within the board's outline, its + axis within 10 deg of the board's normal, not held""" + j = JARS[i] + o, R = self.board_frame() + ax = R.T @ self.jar_axis(j) + if ax[2] < np.cos(TILT_OK + extra * 5): + return False + bc = R.T @ (self.jar_bottom(j) - o) + if not (BOARD_T / 2 - 0.004 <= bc[2] <= BOARD_T / 2 + 0.005 + extra): + return False + if abs(bc[0]) > BOARD_L / 2 + extra or not (GAP - extra <= bc[1] <= GAP + BOARD_D + extra): + return False + return not self.held(j) + + def stages(self): + return [self.on_board(i) for i in range(len(JARS))] + + def lever(self, j): + """horizontal distance (m) of the jar's centre of mass from the hinge line, towards the free edge""" + o, R = self.board_frame() + n = R[:, 1].copy() + n[2] = 0.0 + n /= max(np.linalg.norm(n), 1e-9) + return float((self.env.sim.data.xipos[self.jbid[j]] - o) @ n) + + def moment(self, only_state=True): + """load moment (N m) of the jars standing on the board about the hinge""" + mon = self.mon + tot = 0.0 + for i, j in enumerate(JARS): + on = mon["state"][i] if (only_state and mon is not None) else self.on_board(i) + if on: + tot += self.inst["mass"][COLOURS[i]] * G * self.lever(j) + return float(tot) + + def r_cm(self, i): + """distance of jar i's bottom centre from the wall face (cm), in the board frame""" + return 100 * float(self.to_board(self.jar_bottom(JARS[i]))[1]) + + # ------------------------------------------------------------ monitor + def _t(self): + return int(self.sk.n_steps) if self.sk is not None else 0 + + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + mon["n_steps"] += 1 + t = self._t() + rob, obj, brd = dict(self._sub_rob), dict(self._sub_obj), set(self._sub_board) + self._sub_rob, self._sub_obj, self._sub_board = {}, {}, set() + for i in rob: + if not self.held(JARS[i]): + mon["last_robot"][i] = int(t) + for i, k in obj.items(): + mon["last_obj"][i] = [COLOURS[k], int(t)] + for b in brd: + if b not in mon["board_touch"]: + mon["board_touch"].append(b) + mon["_board_touch_now"] = sorted(brd) + th = self.angle() + mon["max_deg"] = max(mon["max_deg"], float(np.degrees(th))) + if th > np.radians(5.0): + mon["droop_t"] = int(t) # last step with the board drooped > 5 deg (it springs back once the jars are off) + self._sag(th, t) + if mon["n_steps"] % 2: + return + for i in range(len(JARS)): + raw = self.on_board(i, 0.002 if mon["state"][i] else 0.0) + if raw and not mon["raw_prev"][i]: + mon["raw_on"][i] = int(t) # set down on the board (raw; the stage event below is debounced) + mon["raw_prev"][i] = raw + if raw == mon["state"][i]: + mon["raw_since"][i] = 0 + continue + mon["raw_since"][i] += 2 + if mon["raw_since"][i] < DEBOUNCE: + continue + mon["state"][i] = raw + mon["raw_since"][i] = 0 + t0 = int(t - DEBOUNCE + 1) + c = COLOURS[i] + if raw: + restored = mon["lost"][i] + e = dict(stage=c, event="restored" if restored else "achieved", step=t0, + r_cm=round(self.r_cm(i), 1), moment_Nm=round(self.moment(), 3)) + if restored: + e["after"] = mon["lost_cause"][i] + mon["events"].append(e) + mon["ever"][i] = True + mon["placed_step"][i] = t0 + mon["last_place"] = (c, t0) + else: + mon["lost"][i] = True + cause = self._cause(i, t) + mon["lost_cause"][i] = cause + e = dict(stage=c, event="lost", step=t0, cause=cause, board_deg=round(float(np.degrees(th)), 1)) + mon["events"].append(e) + if cause == "slid_off": + ps = mon["placed_step"][i] + ss = mon["sag_start"]["step"] if mon["sag_start"] else None + sc = mon.get("sag_cause") + mon["events"].append(dict(jar=c, event="jar_fell", step=t0, + dt_since_placed_s=None if ps is None else round((t0 - ps) * DT, 2), + dt_since_sag_start_s=None if ss is None else round((t0 - ss) * DT, 2), + after_placing=None if sc is None else sc[0], + dt_since_cause_s=None if sc is None else round((t0 - sc[1]) * DT, 2), + in_final_settle=mon["finish_step"] is not None, + board_deg=round(float(np.degrees(th)), 1))) + mon["fell_in_sag"].append(c) + + def _sag(self, th, t): + mon = self.mon + if not mon["in_sag"]: + if th > SAG0: + mon["in_sag"] = True + mon["sag_fired"] = False + mon["sag_max"] = th + mon["fell_in_sag"] = [] + lp = self._last_set_down(t) + mon["sag_cause"] = lp + e = dict(event="sag_start", step=int(t), board_deg=round(float(np.degrees(th)), 2), + moment_Nm=round(self.moment(only_state=False), 3), + preload_Nm=round(float(self.inst["preload"]), 3), + after_placing=None if lp is None else lp[0], + dt_since_placement_s=None if lp is None else round((t - lp[1]) * DT, 2), + n_on_board=int(sum(self.on_board(i) for i in range(len(JARS))))) + mon["sag_start"] = e + mon["events"].append(e) + return + mon["sag_max"] = max(mon["sag_max"], th) + if not mon["sag_fired"] and th > SAG_DEG: + mon["sag_fired"] = True + mon["n_sag"] += 1 + ss = mon["sag_start"] + lp = self._last_set_down(t) # the placement that drove the board past 8 deg (sag_start may be earlier: + mon["sag_cause"] = lp # two jars in the middle already make it creep a few degrees) + mon["events"].append(dict(event="sag", step=int(t), board_deg=round(float(np.degrees(th)), 2), + moment_Nm=round(self.moment(only_state=False), 3), + after_placing=None if lp is None else lp[0], + sag_start_after=ss["after_placing"], + dt_since_placement_s=None if lp is None else round((t - lp[1]) * DT, 2), + dt_since_sag_start_s=round((t - ss["step"]) * DT, 2), + in_final_settle=mon["finish_step"] is not None)) + mon["below"] = mon.get("below", 0) + 1 if th < SAG_END else 0 + if mon["below"] >= 2 * DEBOUNCE: # back level for 1 s (the jars that slid off have been registered) + mon["in_sag"] = False + mon["below"] = 0 + mon["events"].append(dict(event="sag_end", step=int(t), max_deg=round(float(np.degrees(mon["sag_max"])), 1), + fell=list(mon["fell_in_sag"]), + duration_s=round((t - mon["sag_start"]["step"]) * DT, 2))) + + def _last_set_down(self, t): + """(colour, step) of the jar most recently set down on the board (raw predicate) that still stands on it""" + mon = self.mon + cands = [(mon["raw_on"][i], COLOURS[i]) for i in range(len(JARS)) + if mon["raw_on"][i] is not None and mon["raw_prev"][i] and mon["raw_on"][i] <= t] + if not cands: + return None + st, c = max(cands) + return (c, st) + + def _cause(self, i, t, window=60): + mon = self.mon + if self.held(JARS[i]): + return "picked_up" + if (mon["in_sag"] and mon["sag_max"] > np.radians(5.0)) or (mon.get("droop_t") is not None + and t - mon["droop_t"] <= window): + return "slid_off" + lr, lo = mon["last_robot"][i], mon["last_obj"][i] + if lr is not None and t - lr <= window: + return "robot" + if lo is not None and t - lo[1] <= window: + return "jar:" + lo[0] + return "other" + + def _finalize_monitor(self, raw): + mon = self.mon + t = self._t() + for i in range(len(JARS)): + if raw[i] == mon["state"][i]: + continue + mon["state"][i] = raw[i] + c = COLOURS[i] + if raw[i]: + restored = mon["lost"][i] + e = dict(stage=c, event="restored" if restored else "achieved", step=t, final=True) + if restored: + e["after"] = mon["lost_cause"][i] + mon["events"].append(e) + mon["ever"][i] = True + else: + mon["lost"][i] = True + cause = self._cause(i, t, window=10 ** 6) + mon["lost_cause"][i] = cause + mon["events"].append(dict(stage=c, event="lost", step=t, cause=cause, final=True)) + + # ------------------------------------------------------------ outcome + def _touching(self): + d = self.env.sim.data + jar_touch, board_touch = False, False + for k in range(d.ncon): + c = d.contact[k] + a, b = c.geom1, c.geom2 + if (self.is_robot[a] and self.owner[b] >= 0) or (self.is_robot[b] and self.owner[a] >= 0): + jar_touch = True + if (self.is_robot[a] and self.is_board[b]) or (self.is_robot[b] and self.is_board[a]): + board_touch = True + return jar_touch, board_touch + + def _moving(self): + d = self.env.sim.data + if abs(float(d.qvel[self.da])) > np.radians(0.3): + return True + for j in JARS: + da = self.jdof[j] + if np.linalg.norm(d.qvel[da:da + 3]) > 0.01 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.3: + return True + return False + + def outcome(self, inst): + sk = self.sk + mon = self.mon + mon["finish_step"] = self._t() + # what the agent's last images show (finish returns no image): board angle and the jars already off the board + th_fin = self.angle() + off_fin = [COLOURS[i] for i in range(4) if mon["ever"][i] and not self.on_board(i) and not self.held(JARS[i])] + max_fin = float(mon["max_deg"]) + # settle with the arm holding still: >= 15 s of simulated time, up to 30 s while the board or a jar still moves + # (the droop is slow: finishing right after the last placement must not beat it) + n = 0 + while n < SETTLE_MAX: + sk.hold(10) + n += 10 + if n >= SETTLE_MIN and not self._moving() and not mon["in_sag"]: + break + settle_s = n * DT + p0 = {j: envs.obj_pos(self.env, j) for j in JARS} + th0 = self.angle() + jar_touch = board_touch = False + board_other = set() + for _ in range(20): + sk.hold(1) + jt, bt = self._touching() + jar_touch, board_touch = jar_touch or jt, board_touch or bt + board_other |= {b for b in mon.get("_board_touch_now", []) if b != "robot"} + moved = max(float(np.linalg.norm(envs.obj_pos(self.env, j) - p0[j])) for j in JARS) + static = moved < 0.003 and abs(self.angle() - th0) < np.radians(0.3) + raw = self.stages() + self._finalize_monitor(raw) + th = self.angle() + held = [COLOURS[i] for i, j in enumerate(JARS) if self.held(j)] + level = th <= BOARD_OK + propped = sorted(board_other) + success = bool(all(raw) and level and static and not held and not jar_touch and not board_touch and not propped) + ev = list(mon["events"]) + n_reg = sum(e.get("event") == "lost" and e.get("cause") != "picked_up" for e in ev) + n_lost = sum(e.get("event") == "lost" for e in ev) + n_res = sum(e.get("event") == "restored" and e.get("after") != "picked_up" for e in ev) + fell = [e for e in ev if e.get("event") == "jar_fell"] + sags = [e for e in ev if e.get("event") == "sag"] + sag_vis = [e for e in sags if not e.get("in_final_settle")] + starts = [e for e in ev if e.get("event") == "sag_start"] + ever = mon["ever"] + lost_final = [i for i in range(4) if not raw[i] and ever[i]] + never = [i for i in range(4) if not raw[i] and not ever[i]] + if success: + failure = "none" + elif held: + failure = "held" + elif propped or board_touch: + failure = "propped" + elif jar_touch: + failure = "touching" + elif lost_final: + causes = {mon["lost_cause"][i] for i in lost_final} + failure = ("slid_off" if "slid_off" in causes else "knocked_off" if "robot" in causes else "regressed") + elif never: + failure = "not_on_shelf" + elif not level: + failure = "board_drooped" + else: + failure = "not_static" + # ---- F2 text + parts = [] + if success: + parts.append("All four jars stand upright on the shelf board.") + for i in range(4): + if raw[i]: + continue + c, j = COLOURS[i], JARS[i] + if c in held: + parts.append(f"The {c} jar is still held by the gripper.") + continue + pb = self.to_board(self.jar_bottom(j)) + lying = self.tilt(j) > np.radians(45) + if pb[2] < -0.02: # below the board: on the table + where = "lies on its side on the table" if lying else "stands on the table" + dist = 100 * float(pb[1] - (GAP + BOARD_D)) + txt = f"The {c} jar {where}" + (f", {dist:.0f} cm out from the shelf's front edge." if dist > 0 + else ", under the shelf.") + elif lying: + txt = f"The {c} jar lies on its side on the shelf board." + else: + txt = f"The {c} jar is not standing on the shelf board." + if ever[i]: + why = mon["lost_cause"][i] + txt += {"slid_off": " It had stood on the shelf; it slid off when the shelf board drooped under the load.", + "robot": " It had stood on the shelf; the robot knocked it off.", + }.get(why, " It had stood on the shelf earlier.") + parts.append(txt) + if all(raw) and not success: + if not level: + parts.append(f"The shelf board droops by {np.degrees(th):.0f} degrees.") + if held: + pass + elif jar_touch or board_touch: + parts.append("The gripper is still touching " + ("a jar." if jar_touch else "the shelf board.")) + elif propped: + parts.append("The shelf board rests on something below it.") + elif not static: + parts.append("Something was still moving.") + if sags: + parts.append(f"During the attempt the shelf board drooped {len(sags)} time(s) (down to {mon['max_deg']:.0f} " + f"degrees) and {len(fell)} time(s) a jar slid off; {n_res} time(s) a jar was put back.") + trap = bool(sags) + lp = lambda e: e.get("dt_since_placement_s") # noqa: E731 + return dict(success=success, stages={COLOURS[i]: bool(raw[i]) for i in range(4)}, events=ev, + n_regressions=int(n_reg), n_lost=int(n_lost), n_restored=int(n_res), n_fell=len(fell), + n_sag=len(sags), trap_fired=trap, sag_visible=bool(sag_vis), + recovered_in_attempt=bool(trap and success), + first_sag_dt_s=lp(sags[0]) if sags else None, + first_sag_start_dt_s=lp(starts[0]) if starts else None, + first_sag_after=sags[0].get("after_placing") if sags else None, + first_fall_dt_s=fell[0].get("dt_since_cause_s") if fell else None, + fell_before_finish=bool([e for e in fell if not e.get("in_final_settle")]), + board_deg_at_finish=round(float(np.degrees(th_fin)), 1), off_at_finish=off_fin, + max_droop_before_finish_deg=round(max_fin, 1), + visible_before_finish=bool(sag_vis or off_fin or max_fin > np.degrees(SAG_DEG)), + fell_jars=sorted({e["jar"] for e in fell}), failure=failure, held=held, touching=bool(jar_touch), + board_touched=bool(board_touch), propped=propped, static=bool(static), + board_deg=round(float(np.degrees(th)), 2), max_droop_deg=round(mon["max_deg"], 1), + r_cm={COLOURS[i]: round(self.r_cm(i), 1) for i in range(4)}, + moment_Nm=round(self.moment(only_state=False), 3), preload_Nm=round(float(inst["preload"]), 3), + loose=bool(inst["loose"]), settle_s=settle_s, finish_step=mon["finish_step"], + detail=" ".join(parts)) + + # ------------------------------------------------------------ scripted primitives (move_to + gripper only) + def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300): + return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + + def _lift_to(self, z, speed=0.15): + cur = self.sk.eef_pos() + if cur[2] < TZ + z - 0.005: + self._go([cur[0], cur[1], TZ + z], speed=speed) + + def _settle_jar(self, j, max_checks=30): + d = self.env.sim.data + da = self.jdof[j] + for _ in range(max_checks): + if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2: + return + self.sk.hold(2) + + def wait_board(self, max_steps=200): + """wait (arm still) until the board stops moving""" + for _ in range(max_steps // 5): + if abs(float(self.env.sim.data.qvel[self.da])) < np.radians(0.3) and not self.mon["in_sag"]: + return + self.sk.hold(5) + + def lying(self, j): + return self.tilt(j) > np.radians(45) + + def pick(self, j, z_carry=Z_CARRY, yaw=0.0, v=0.2, err=None, tries=2, v_down=0.10, waits=1.0): + """grasp the jar by its knob and lift it to carry height. Standing jar: from above, wrist yaw `yaw`. Lying jar: + fingers across its axis; lifted, it turns between the fingers and hangs straight down.""" + sk = self.sk + for _ in range(tries): + self._settle_jar(j) + lying = self.lying(j) + k = self.knob_xyz(j) + if lying: + ax = self.jar_axis(j)[:2] + gy = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else sk.yaw + else: + gy = yaw + q = k[:2] + (np.asarray(err, float) if err is not None else 0.0) + sk.set_gripper(False, steps=8) + cur = sk.eef_pos() + self._go([cur[0], cur[1], max(cur[2], TZ + min(z_carry, 0.22))], speed=0.15) + self._go([q[0], q[1], max(k[2] + 0.06, TZ + min(z_carry, 0.22))], yaw=gy, speed=v) + sk.hold(max(1, int(4 * waits))) + k = self.knob_xyz(j) + q = k[:2] + (np.asarray(err, float) if err is not None else 0.0) + self._go([q[0], q[1], k[2] + 0.015], speed=v_down) + self._go([q[0], q[1], k[2]], speed=0.04, tol=0.003, max_steps=150) + sk.set_gripper(True, steps=15) + if lying: # lift slowly until it hangs free, let the swing die down + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + KNOB_Z + 0.04], speed=0.08) + sk.hold(20) + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + z_carry], speed=max(0.12, v_down)) + sk.hold(max(1, int(5 * waits))) + if self.held(j): + return True + sk.set_gripper(False, steps=8) + cur = sk.eef_pos() + self._go([cur[0], cur[1], cur[2] + 0.05], speed=0.1) + return False + + def put(self, j, u, r, z_carry=Z_CARRY, h_rel=0.010, v=0.2, yaw=0.0, v_down=0.10, waits=1.0): + """carry the held jar over board point (u, r) (planned with the board level), straight down until its bottom is + h_rel above the board top, let go, lift back to carry height""" + sk = self.sk + xy = self.level_point(u, r) + rel = self.jar_bottom(j)[:2] - sk.eef_pos()[:2] + q = xy - rel + cur = sk.eef_pos() + self._go([q[0], q[1], max(cur[2], TZ + z_carry)], yaw=yaw, speed=v) + sk.hold(max(1, int(12 * waits))) # let the hanging jar stop swinging + rel = self.jar_bottom(j)[:2] - sk.eef_pos()[:2] + q = xy - rel + dz = sk.eef_pos()[2] - envs.obj_min_z(self.env, j) + zr = self.board_top_z() + dz + h_rel + self._go([q[0], q[1], zr + 0.02], speed=v_down) + self._go([q[0], q[1], zr], speed=0.03, tol=0.003, max_steps=150) + sk.set_gripper(False, steps=12) + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + z_carry], speed=max(0.15, v_down)) + sk.hold(3) + + def place(self, i, u, r, p, rng, rand=0.0): + """one stage: pick jar i from wherever it is and put it on the board at (u, r) +- rand""" + j = JARS[i] + e = rng.uniform(-rand, rand, 2) if rand else np.zeros(2) + gerr = rng.uniform(-0.002, 0.002, 2) if rand else None + kw = dict(z_carry=p.get("z_carry", Z_CARRY), v=p.get("v", 0.2), v_down=p.get("v_down", 0.10), + waits=p.get("waits", 1.0)) + if not self.pick(j, err=gerr, **kw): + return False + self.put(j, u + e[0], r + e[1], h_rel=p.get("h_rel", 0.010), **kw) + self._settle_jar(j) + return True + + def supply_order(self): + """jar indices by their supply position: the one whose slot is farthest from the robot first (Sonnet fills a + row from the far end)""" + return sorted(range(4), key=lambda i: -self.inst["start"][COLOURS[i]][0]) + + def slot_u(self, k): + """board u of slot k (k = 0 farthest from the robot)""" + s = -1.0 if self.inst["side"] == "right" else 1.0 + # u runs along local x = -s * world x -> farthest (largest world x) first + return -s * SLOT_U[3 - k] + + def fallen(self): + return [i for i in range(4) if self.mon["ever"][i] and not self.on_board(i) and not self.held(JARS[i])] + + def repair(self, r_target, rng, p, rand=0.0, used=None): + """move every jar on the board to depth r_target (same slot), then stand up the fallen ones and put them into the + free slots at r_target""" + sk = self.sk + self.wait_board() + slots = dict(used or {}) + for i in range(4): + if self.on_board(i) and abs(self.r_cm(i) / 100 - r_target) > 0.02: + self.place(i, slots.get(i, self.slot_u(0)), r_target, p, rng, rand) + self.wait_board() + for i in self.fallen(): + free = [k for k in range(4) if self.slot_u(k) not in slots.values()] or [0] + u = slots.get(i, self.slot_u(free[0])) + slots[i] = u + self.place(i, u, r_target, p, rng, rand) + self.wait_board() + sk.hold(5) + return slots + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("noise_seed", 0)) + r = float(params["r"]) + rand = float(params.get("rand", 0.0)) + order = params.get("order") or self.supply_order() + used = {} + mode_back = False + for k, i in enumerate(order): + u = self.slot_u(k) + used[i] = u + rr = R_BACK + params.get("back_off", 0.0) if mode_back else r + self.place(i, u, rr, params, rng, rand) + # looks at the jar it just placed (Sonnet): re-places it if it is not standing on the board + if not self.on_board(i) and params.get("self_check", True): + self.place(i, u, rr, params, rng, rand) + if params.get("look_back") and (self.fallen() or self.angle() > np.radians(3.0)): + # the shelf sags / jars fell: from now on load it near the wall, and move what is on it there too + mode_back = True + used = self.repair(R_BACK + params.get("back_off", 0.0), rng, params, rand, used) + if params.get("final_check"): + for _ in range(2): + if all(self.stages()): + break + rr = R_BACK + params.get("back_off", 0.0) if (mode_back or params.get("look_back")) else r + used = self.repair(rr, rng, params, rand, used) + if not params.get("fast_finish"): + self._lift_to(Z_CARRY) + self.sk.hold(5) + + # naive = Sonnet-like (DESIGN_INSIGHTS §3; lh_nudge_row / lh_bystander pilots): careful top-down pick and place, jars + # set down in the visual middle of the shelf's depth, released ~1-4 cm above, wrist yaw 0, looks at the jar it just + # placed, no look back at the others before finishing + def default_params(self, inst): + sd = int(inst["seed"]) + return dict(r=R_MID + float(inst["naive_bias"]), rand=NAIVE_RAND, noise_seed=sd * 13, + h_rel=0.010 + 0.030 * ((sd * 7) % 11) / 10, z_carry=Z_CARRY, look_back=False, final_check=False, + v=NAIVE_V, v_down=NAIVE_V_DOWN, waits=NAIVE_WAITS) + + def oracle_params(self, inst): + return dict(r=R_BACK, rand=0.0, h_rel=0.005, z_carry=Z_CARRY, look_back=True, final_check=True) + + def adapt_params(self, inst, history): + """from attempt 2: load the shelf near the wall (same imprecision), look back after every jar and at the end""" + return dict(self.default_params(inst), r=R_BACK + 0.008, look_back=True, final_check=True) + + def blind_params(self, inst, attempt, rng): + """the naive behaviour with random variation (depth on the board, order, heights), no history, no look back""" + order = [int(x) for x in rng.permutation(4)] + return dict(self.default_params(inst), noise_seed=int(rng.integers(1 << 30)), r=float(rng.uniform(0.06, 0.15)), + order=order, z_carry=float(rng.uniform(0.24, 0.28)), h_rel=float(rng.uniform(0.005, 0.04)), + v=float(rng.uniform(0.12, 0.3))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + single = ("oracle", "naive", "oracle_noise", "naive_front", "naive_back", "naive_check_mid", "naive_fast") + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": # attempt 1: naive + looks back after every jar; repairs near the wall + params = (dict(self.default_params(inst), look_back=True, final_check=True, back_off=0.008) if a == 0 + else self.adapt_params(inst, history)) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": # control: cross-attempt learning only (near the wall from attempt 2), no repair + params = (self.default_params(inst) if a == 0 else + dict(self.default_params(inst), r=R_BACK + 0.008)) + elif kind == "oracle_noise": + params = dict(self.oracle_params(inst), rand=0.005, noise_seed=int(seed) * 7 + a) + elif kind == "naive_front": # control: naive, but jars set down near the free edge + params = dict(self.default_params(inst), r=GAP + BOARD_D - JB - 0.015) + elif kind == "naive_back": # control: naive pace and imprecision, jars against the wall -> no droop + params = dict(self.default_params(inst), r=R_BACK + 0.008) + elif kind == "naive_check_mid": # control: looks back and repairs, but puts the jars back in the middle + params = dict(self.default_params(inst), final_check=True) + elif kind == "naive_fast": # control: naive at the fastest pace, finishing right after the last jar + params = dict(self.default_params(inst), v=0.6, v_down=0.3, waits=0.1, h_rel=0.03, fast_finish=True) + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in single: + break + return history diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/lh_split_calibration.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/lh_split_calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..af67f706117835300db6f39fd3f3a38a3933edcc --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/lh_split_calibration.py @@ -0,0 +1,142 @@ +"""Two-workstation packing: calibration transfer, collateral damage, geometric fit. + +A repeatable command-coordinate calibration varies with workstation (sign of y), +not with phase or policy. No object poses are written after reset. Learning a +far-workstation correction and blindly reusing it at the near destination can +undo the earlier placement. A long module must also be aligned with its tray. +""" +import numpy as np +import xml.etree.ElementTree as ET +from .. import envs +from ..bddl import write_bddl +from ..objects import box_xml,bin_xml,register_generated +from ..skills import Skills +from ..task_base import LFFTask,register_task +from .lh_shelf_droop import jar_xml,JAR_H,KNOB_Z +from .lh_lid_box import mark_xml + +RED='module_red_1';BLUE='module_blue_1';HALF=np.array([.045,.012,.012]) +class SplitSkills(Skills): + def __init__(self,env,task,recorder=None): + super().__init__(env,recorder=recorder);self.task=task;self.correction=np.zeros(3) + def move_to(self,target,*a,**kw): + q=np.array(target)-self.correction + self.bias=np.array(self.task.inst['far_bias'] if q[1]>.04 else self.task.inst['near_bias']) + rep=super().move_to(q,*a,**kw);rep['pos']=np.round(self.reported_eef_pos(),4).tolist();return rep + def reported_eef_pos(self):return self.eef_pos()-self.bias + def _act(self,dpos,drot,grip): + super()._act(dpos,drot,grip);self.task.monitor_step() + +@register_task +class SplitCalibration(LFFTask): + name='lh_split_calibration';level='L1';category='system_identification';failure_causes=('L1','L2','L4');failure_types=failure_causes + protocol='cross';max_attempts=5;agent_max_steps=240 + instruction=('Prepare the two modules for handover: stand the red module on its red square, and fit the entire ' + 'long blue module inside the narrow tray. Leave both released and stable, with the gripper open ' + 'and clear. The red module has a graspable top knob. The work areas are on opposite sides of the desk.') + instruction_indirect=('Stand the tall module with the round top on its matching square, and fit the entire elongated module inside the narrow open tray. Leave both released and stable, with the gripper open and clear.');capabilities=('Perceive','Reason','Plan','Restore') + def make_bddl(self): + rr=ET.fromstring(jar_xml('split_red',(.8,.15,.1,1))) + for g in rr.findall('.//geom'): + if g.get('type')=='box': + sz=np.fromstring(g.get('size'),sep=' ');sz[:2]*=.6;g.set('size',' '.join(map(str,sz))) + r=register_generated('LffSplitRed',ET.tostring(rr,encoding='unicode')) + b=register_generated('LffSplitBlue',box_xml('split_blue',HALF,(.1,.3,.85,1),density=1000)) + tray=register_generated('LffSplitTray',bin_xml('split_tray',(.051,.019),.022),free=False) + mark=register_generated('LffSplitMark',mark_xml('split_mark',(.8,.1,.1,1)),free=False) + return write_bddl(self.name,self.instruction,[(RED,r,'red_region',(-.36,-.16,-.35,-.15)),(BLUE,b,'blue_region',(-.17,.23,-.16,.24))], + [('tray_1',tray,'tray_region',(.2,-.3,.21,-.29)),('mark_1',mark,'mark_region',(.2,.3,.21,.31))]) + def sample_instance(self,seed): + rng=np.random.default_rng(seed);v=float(rng.uniform(.053,.057)) + return dict(seed=seed,near_bias=[0,-v,0],far_bias=[0,v,0],red_xy=[-.35,-.12],blue_xy=[-.16,.24],red_goal=[-.22,-.24],blue_goal=[-.21,-.13]) + def apply_instance(self,i): + self.inst=i;m=self.env.sim.model + envs.set_obj_pose(self.env,RED,[*i['red_xy'],envs.TABLE_Z+JAR_H/2+.001]);envs.scale_mass(self.env,RED,.08) + envs.set_obj_pose(self.env,BLUE,[*i['blue_xy'],envs.TABLE_Z+HALF[2]+.001],yaw=np.pi/2) + for name,xy,z in [('tray_1',i['blue_goal'],.914),('mark_1',i['red_goal'],.901)]: + m.body_pos[m.body_name2id(self.env.fixtures_dict[name].root_body)]=[*xy,z] + def reset_instance(self,i,recorder=None): + np.random.seed(i['seed']);self.mon=None;self.env.reset();self.apply_instance(i);self.env.sim.forward();envs.settle(self.env,10) + self.sk=SplitSkills(self.env,self,recorder);self.trace=[];self.phase_hook=None;self.traps={k:False for k in self.failure_causes};self.recovered=self.traps.copy() + self.mon=dict(red_ever=False,red_lost=False,red_restored=False);return self.sk + def red_ok(self): + p=envs.obj_pos(self.env,RED);R=self.env.sim.data.body_xmat[envs.body_id(self.env,RED)].reshape(3,3) + return bool(np.linalg.norm(p[:2]-self.inst['red_goal'])<.022 and R[2,2]>.96 and abs(p[2]-(.9+JAR_H/2))<.008 and not self.sk.holding(RED)) + def blue_ok(self): + p=envs.obj_pos(self.env,BLUE);R=self.env.sim.data.body_xmat[envs.body_id(self.env,BLUE)].reshape(3,3) + corners=np.array([p+R@(HALF*[a,b,c]) for a in (-1,1) for b in (-1,1) for c in (-1,1)]) + return bool(np.all(np.abs(corners[:,:2]-self.inst['blue_goal'])<[.052,.020]) and corners[:,2].max()<.936 and corners[:,2].min()>.903 and not self.sk.holding(BLUE)) + def monitor_step(self): + if self.mon is None:return + ok=self.red_ok() + if ok: + if self.mon['red_lost']:self.mon['red_restored']=True + self.mon['red_ever']=True + elif self.mon['red_ever'] and not self.sk.holding(RED):self.mon['red_lost']=True + def label(self,text): + r=dict(text=text,step=self.sk.n_steps,red_ok=self.red_ok(),blue_ok=self.blue_ok(),red_xyz=envs.obj_pos(self.env,RED).tolist(),blue_xyz=envs.obj_pos(self.env,BLUE).tolist());self.trace.append(r) + if self.phase_hook:self.phase_hook(text,r) + def observe_offset(self,xy): + s=self.sk;q=np.array([*xy,1.18]);s.move_to(q);return (s.eef_pos()-q+s.correction)*[1,1,0] + def pick(self,name,yaw=None): + s=self.sk;p=envs.obj_pos(self.env,name);R=self.env.sim.data.body_xmat[envs.body_id(self.env,name)].reshape(3,3) + if name==RED: + goal=p+R@np.array([0,0,KNOB_Z-JAR_H/2]);yaw=float(np.arctan2(R[1,2],R[0,2])) if R[2,2]<.7 else 0 + else: + goal=p.copy();yaw=float(np.arctan2(R[1,0],R[0,0])) if yaw is None else yaw + s.set_gripper(False,8);s.move_to([*goal[:2],1.20],yaw=yaw);s.move_to(goal,yaw=yaw,speed=.08,max_steps=150);s.set_gripper(True,20) + s.move_to([*goal[:2],1.20],speed=.1);s.hold(20);return bool(s.holding(name)) + def place(self,name,xy,z,yaw): + s=self.sk;off=envs.obj_pos(self.env,name)-s.eef_pos();s.move_to([*s.eef_pos()[:2],1.20],yaw=yaw) + # Update the held offset after rotating the module. + off=envs.obj_pos(self.env,name)-s.eef_pos();goal=np.array([*xy,z])-off + s.move_to([*goal[:2],1.20],yaw=yaw);s.move_to(goal,yaw=yaw,speed=.08,max_steps=160) + s.set_gripper(False,12);s.move_to([*goal[:2],1.23]);s.hold(40) + def execute(self,i,p): + mode=p.get('mode','adaptive');s=self.sk + if mode=='blind':s.correction=np.array(p.get('jitter',[0,0,0])) + self.label('Two workstations: preserve earlier placements') + if mode=='oracle':near=np.array(i['near_bias']) + else: + near=self.observe_offset(i['red_xy']);ok=self.pick(RED);self.traps['L1']=not ok;self.label('L1: near-workstation grasp missed') + if mode in ('naive','blind') and not ok:return + if mode not in ('naive','blind'):s.correction=near + if not self.pick(RED):self.label('Red pickup failed');return + self.recovered['L1']=True;self.place(RED,i['red_goal'],.9+JAR_H/2+.003,0);self.label('Red module placed correctly') + if mode=='oracle':far=np.array(i['far_bias']) + else: + ok=self.pick(BLUE);self.label('L1 transfer: near correction fails at the far workstation') + if mode in ('naive','blind'): + if not ok:return + self.place(BLUE,i['blue_goal'],.922,np.pi/2);return + far=self.observe_offset(i['blue_xy']) + s.correction=far + if not self.pick(BLUE):self.label('Far pickup failed');return + if mode!='oracle': + self.place(BLUE,i['blue_goal'],.922,np.pi/2);self.traps['L2']=bool(not self.red_ok());self.label('L2: reusing far correction disturbed the red module') + s.correction=near + if not self.pick(RED):self.label('Red restoration pickup failed');return + self.place(RED,[-.40,-.28],.9+JAR_H/2+.003,0);self.label('Clear the disturbed red module before recovering the blue module') + if not self.pick(BLUE):self.label('Blue recovery pickup failed');return + self.place(BLUE,i['blue_goal'],.922,np.pi/2);self.traps['L4']=not self.blue_ok();self.label('L4: the long module bridges the narrow tray') + if not self.pick(RED):return + self.place(RED,i['red_goal'],.9+JAR_H/2+.003,0);self.recovered['L2']=self.red_ok();self.label('L2 recovery: restored red using the near-workstation correction') + if not self.pick(BLUE):self.label('Blue alignment pickup failed');return + s.correction=near;self.place(BLUE,i['blue_goal'],.920,0);self.recovered['L4']=self.blue_ok();self.label('Aligned module fits; recheck both completed placements') + if not self.red_ok(): + if self.pick(RED):self.place(RED,i['red_goal'],.9+JAR_H/2+.003,0) + s.set_gripper(False,8);s.move_to([-.40,-.05,1.25]);s.hold(30) + def outcome(self,i): + self.sk.hold(100);stages=dict(red_on_mark=self.red_ok(),blue_in_tray=self.blue_ok(),gripper_open=bool(self.sk.grip<0),gripper_clear=bool(self.sk.eef_pos()[2]>1.13)) + static=all(np.linalg.norm(self.env.sim.data.qvel[envs.free_joint_addr(self.env,n)[1]:envs.free_joint_addr(self.env,n)[1]+6])<.06 for n in (RED,BLUE)) + return dict(success=bool(all(stages.values()) and static),stages=stages,static=bool(static),traps=self.traps.copy(),recovered=self.recovered.copy(),detail=str(stages)) + def default_params(self,i):return {'mode':'naive'} + def oracle_params(self,i):return {'mode':'oracle'} + def adapt_params(self,i,h):return {'mode':'adaptive'} + def run_scripted(self,kind,inst,k=None,seed=0,on_attempt=None): + hist=[] + for n in range((k or 5) if kind=='blind' else 1): + self.reset_instance(inst);params={'mode':kind};self.execute(inst,params);o=self.outcome(inst);hist.append(dict(attempt=n+1,params=params,outcome=o)) + if on_attempt:on_attempt(n+1,self.env,o) + if o['success']:break + return hist diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/scripts/cs_ir_report.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/scripts/cs_ir_report.py new file mode 100644 index 0000000000000000000000000000000000000000..681580fd2dab576a4f9ac1747508e03873147f59 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/scripts/cs_ir_report.py @@ -0,0 +1,87 @@ +"""Reproduce the CS/IR audit tables from read-only manifests and hash-bound evidence.""" +import argparse +import json +from pathlib import Path + +import api_batch +import outcomes +from outcome_audit import load_audit, sha256 + +GROUPS = {"GPT": ["cx_main1"], "Sonnet": ["cc_main1"], "Opus": ["cc_opus1"], + "DeepSeek": ["ds_cx1", "ds_cx1b"]} + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--runs-root", required=True) + parser.add_argument("--audit", required=True) + parser.add_argument("--out", required=True) + args = parser.parse_args() + api_batch.RUNS = str(Path(args.runs_root).resolve()) + audit = load_audit(args.audit) + output = Path(args.out) + output.mkdir(parents=True, exist_ok=True) + all_rows, models, manifests, coverage = [], {}, {}, {} + for model, batches in GROUPS.items(): + old, new = [], [] + for batch in batches: + manifest = api_batch.load(batch) + manifests[batch] = sha256(api_batch.mpath(batch)) + old += outcomes.instance_rows(manifest, batch=batch) + new += outcomes.instance_rows(manifest, audit=audit, batch=batch) + for run in manifest["runs"]: + if not (run["cond"] == "harness" and run.get("followup") and run["status"] == "done"): + continue + attempts = outcomes.attempts(run["log"]) + if attempts: + coverage.setdefault(run["task"], set()).update( + k for k in outcomes.ERROR_FLAGS + outcomes.ERROR_COUNTS if k in attempts[0][2]) + before, after = outcomes.summary(old), outcomes.summary(new) + for key in ("n", "A1", "A3", "XR", "F", "n_paired", "A3_paired", "passk_paired", "delta_paired"): + assert before[key] == after[key], f"Audit unexpectedly changed {model} {key}" + assert len({(r["task"], r["seed"]) for r in new}) == len(new), "duplicate model/task/seed" + models[model] = dict(before=before, after=after) + all_rows += [dict(r, model=model) for r in new] + payload = dict(schema="lff-cs-ir-report-1", source_manifests_sha256=manifests, + audit_sha256=sha256(args.audit), models=models, rows=all_rows, + legacy_counter_coverage={k: sorted(v) for k, v in coverage.items()}) + (output / "summary.json").write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n") + lines = ["# CS / IR 证据审计表(2026-10-24)", "", + "本表由 `scripts/cs_ir_report.py` 生成;定义、局限、合并说明见同目录 `README.md`。", + "旧口径是 task counter heuristic;新口径是逐 run 的物理失败 + 主动修复证据审计。", + "A1、A3、XR、F、配对样本及 Δ_hist 均逐项断言保持不变。", "", + "| 模型 | 旧 CS / IR / S? | 审计 CS / IR / S? | 原 S? 已补 | A1 | A3 |", + "|---|---|---|---|---|---|"] + for model, pair in models.items(): + b, a = pair["before"], pair["after"] + resolved = sum(r["model"] == model and r["legacy_cls"] == "S?" and r["cls"] != "S?" for r in all_rows) + lines.append(f"| {model} | {b['CS']} / {b['IR']} / {b['S?']} | {a['CS']} / {a['IR']} / {a['S?']} | " + f"{resolved}/{b['S?']} | {a['A1']}/{a['n']} | {a['A3']}/{a['n']} |") + lines += ["", "## 每任务新旧分类与原统一字段覆盖", "", + "`旧→新`;只有一个标签表示未变。`缺失` 不是没有错误;有字段也不代表覆盖抓空/掉落等全部失败。", "", + "| 任务 | GPT | Sonnet | Opus | DeepSeek | 原统一错误字段 |", "|---|---|---|---|---|---|"] + for task, counters in coverage.items(): + cells = [] + for model in GROUPS: + row = next(r for r in all_rows if r["model"] == model and r["task"] == task) + cells.append(row["cls"] if row["cls"] == row["legacy_cls"] else f"{row['legacy_cls']}→{row['cls']}") + lines.append("| " + " | ".join([task] + cells + [", ".join(sorted(counters)) or "缺失"]) + " |") + lines += ["", "## 首次成功的证据链", "", "行号均指原 run 文件,E 为 events.jsonl,T 为 trajectory.jsonl;s 为机器人命令序号。", ""] + for row in all_rows: + if not row["a1"]: + continue + entry = audit.get((row["batch"], row["run_id"])) + manifest = api_batch.load(row["batch"]) + run = next(r for r in manifest["runs"] if r["id"] == row["run_id"]) + lines += [f"### {row['model']} · {row['task']} · {row['legacy_cls']} → {row['cls']}", "", + row["audit_basis"], "", f"[原 events.jsonl]({run['log']}/events.jsonl) · " + f"[原 trajectory.jsonl]({run['log']}/trajectory.jsonl)", ""] + if entry: + lines += [f"证据索引:{entry.get('evidence', '')}", "", + f"归因范围:`{entry.get('failure_scope', 'not_adjudicated')}`。", ""] + (output / "TABLES.md").write_text("\n".join(lines) + "\n") + print(json.dumps(models, ensure_ascii=False, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/scripts/l6_controls.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/scripts/l6_controls.py new file mode 100644 index 0000000000000000000000000000000000000000..41114f4bea52b74c5426c220b1d554cade09f1ad --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/scripts/l6_controls.py @@ -0,0 +1,92 @@ +"""python scripts/l6_controls.py [n] + +Extra controls for the two L6 tasks: thumbnails right after the interruption, extra scripted policies, +no-injection sanity check, analytic memoryless baselines. Writes results//controls.json.""" +import sys, json, os, time +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) +import numpy as np, imageio +from lffbench import envs +import lffbench.tasks.l6_count, lffbench.tasks.l6_sequence # noqa +from lffbench.task_base import TASKS +name = sys.argv[1] +n = int(sys.argv[2]) if len(sys.argv) > 2 else 20 +out_dir = os.path.join(ROOT, "results", name) +os.makedirs(out_dir, exist_ok=True) +task = TASKS[name](cam_res=384) +extra = ["skip", "inc1"] if name == "l6_count_into_box" else ["skip"] +res = dict(task=name, n=n, seeds=list(range(1000, 1000 + n)), extra={}, no_inject={}, analytic={}) +t0 = time.time() + +# 1) frames right after the interruption (what the agent sees next), seeds 1000-1002, adaptive policy +def interrupted(): + return (task.slip if name == "l6_count_into_box" else task.stop) is not None + + +for seed in range(1000, 1003): + inst = task.sample_instance(seed) + shot = {} + orig_step = task.env.step + + def step(a, _o=orig_step): + r = _o(a) + if "f" not in shot and interrupted(): + shot["cnt"] = shot.get("cnt", 0) + 1 + if shot["cnt"] >= (4 if name == "l6_count_into_box" else 60): # count: 0.2 s; sequence: arm back home + shot["f"] = np.concatenate([envs.render(task.env, "agentview", 384), + envs.render(task.env, "robot0_eye_in_hand", 384)], 1) + return r + task.env.step = step + task.run_scripted("adaptive", inst, k=5, seed=seed) + task.env.step = orig_step + if "f" in shot: + imageio.imwrite(os.path.join(out_dir, f"interrupt_{seed}.png"), shot["f"]) +print("thumbs", f"{time.time()-t0:.0f}s", flush=True) + +# 2) extra scripted policies +for kind in extra: + fs = [] + for i in range(n): + seed = 1000 + i + inst = task.sample_instance(seed) + h = task.run_scripted(kind, inst, k=5, seed=seed) + s = next((x["attempt"] for x in h if x["outcome"]["success"]), None) + fs.append(s) + res["extra"][kind] = dict(first_success=fs, succ_at_k=[float(np.mean([s is not None and s <= j for s in fs])) for j in range(1, 6)]) + print(kind, res["extra"][kind]["succ_at_k"], f"{time.time()-t0:.0f}s", flush=True) + +# 3) no-injection sanity (oracle + naive, first 10 seeds) +task.inject = False +for kind in ("adaptive", "naive"): + fs = [] + for i in range(10): + seed = 1000 + i + inst = task.sample_instance(seed) + h = task.run_scripted(kind, inst, k=1, seed=seed) + fs.append(bool(h[0]["outcome"]["success"])) + res["no_inject"][kind] = float(np.mean(fs)) + print("no inject", kind, res["no_inject"][kind], flush=True) +task.inject = True + +# 4) analytic memoryless baselines over the same seeds (perfect execution assumed) +if name == "l6_count_into_box": + insts = [task.sample_instance(1000 + i) for i in range(n)] + res["analytic"]["uniform_guess_0..N-1@1"] = float(np.mean([1 / x["n_target"] for x in insts])) + best = max(range(0, 6), key=lambda g: np.mean([x["n_target"] - x["p"] == g for x in insts])) + res["analytic"]["best_fixed_number_to_add@1"] = dict(add=best, rate=float(np.mean([x["n_target"] - x["p"] == best for x in insts]))) + res["analytic"]["p_hist"] = {str(v): int(sum(x["p"] == v for x in insts)) for v in range(1, 6)} + res["analytic"]["N_hist"] = {str(v): int(sum(x["n_target"] == v for x in insts)) for v in (4, 5)} + big = [task.sample_instance(5000 + i) for i in range(2000)] + res["analytic"]["uniform_guess@1_2000inst"] = float(np.mean([1 / x["n_target"] for x in big])) + res["analytic"]["best_fixed_add@1_2000inst"] = float(max(np.mean([x["n_target"] - x["p"] == g for x in big]) for g in range(1, 5))) +else: + insts = [task.sample_instance(1000 + i) for i in range(n)] + res["analytic"]["w_hist"] = {str(v): int(sum(x["stop_w"] == v for x in insts)) for v in range(1, 5)} + res["analytic"]["phase_hist"] = {p: int(sum(x["stop_phase"] == p for x in insts)) for p in "AB"} + res["analytic"]["uniform_guess_0..4@1"] = 0.2 + big = [task.sample_instance(5000 + i) for i in range(2000)] + res["analytic"]["best_fixed_guess@1_2000inst"] = float(max(np.mean([x["stop_w"] == g for x in big]) for g in range(0, 5))) + res["analytic"]["skip_expected"] = float(np.mean([x["stop_phase"] == "B" or x["stop_w"] == 3 for x in big])) +res["seconds"] = time.time() - t0 +json.dump(res, open(os.path.join(out_dir, "controls.json"), "w"), indent=1) +print(json.dumps(res["analytic"])) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/scripts/mcp_robot_server.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/scripts/mcp_robot_server.py new file mode 100644 index 0000000000000000000000000000000000000000..18f433abeec51793dbf999e9da2a165b16d9393d --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/scripts/mcp_robot_server.py @@ -0,0 +1,140 @@ +"""MCP server (stdio) exposing one robot_server session to a native agent harness (Claude Code, Codex, Gemini CLI, ...). + +The tools are exactly the unified harness's LA tools (scripts/api_player.py): `robot`, `shell` (jailed, in the episode +workspace) and `view_images` (returned as MCP image content), with the same per-attempt tool-call budget: when it is +used up the attempt is finished automatically and the result is appended to that call's output. So a native harness +and the API harness see the same README, tools and limits; only the agent loop around them differs. + + python scripts/mcp_robot_server.py --session runs/<...>/session.json + python scripts/mcp_robot_server.py --schema-only (launch preflight: same tools/list, no session, every call fails) +Every call is logged to /mcp_transcript.jsonl (the first line lists the names of the environment variables the +harness passed to this process, for the harness self-check). Nothing but JSON-RPC goes to stdout. +The tools themselves are scripts/tool_gateway.py's ToolCore: through the episode's tool gateway when the launcher +started one (gateway.json in the log dir; docs/18 §6.1), otherwise in this process. +""" +import argparse +import json +import os +import sys +import time +import traceback + +ENV_AT_START = dict(os.environ) # what the harness passed (before our own imports touch the environment) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "client")) +from api_player import SHELL_TOOL, TOOL_LA, VIEW_TOOL_LA # noqa: E402 +from lffbench_client import Session as Client # noqa: E402 +from tool_gateway import GATEWAY_FILE, ToolCore # noqa: E402 + +PROTOCOL_VERSIONS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05") +TOOLS = [TOOL_LA, SHELL_TOOL, VIEW_TOOL_LA] + + +class Session: + """One episode's tools. With a tool gateway (scripts/tool_gateway.py, started by harness_run.py; its gateway.json is + in the run's log dir) every call goes to the gateway, which owns the per-attempt budget for the whole episode, also + across the MCP processes of a resumed CLI. Without one, the same ToolCore runs in this process and the budget is + carried over from mcp_transcript.jsonl. Either way the tool outputs are the gateway's ToolCore's, byte for byte.""" + + def __init__(self, session_path): + self.log_dir = os.path.dirname(os.path.abspath(session_path)) + tpath = os.path.join(self.log_dir, "mcp_transcript.jsonl") + gfile = os.path.join(self.log_dir, GATEWAY_FILE) + self.gateway = Client.from_gateway_file(gfile, face="mcp") if os.path.exists(gfile) else None + self.core = None if self.gateway else ToolCore(session_path, carry_from=tpath) + self.calls_in_attempt = self.core.calls_in_attempt if self.core else None + self.finished = self.core.finished if self.core else False + self.tlog = open(tpath, "a") + + def log(self, d): + d["t"] = time.time() + self.tlog.write(json.dumps(d, ensure_ascii=False) + "\n") + self.tlog.flush() + + def call(self, name, args): + """-> (MCP content list, is_error)""" + if self.core is not None: + content, err = self.core.call(name, args) + self.calls_in_attempt, self.finished = self.core.calls_in_attempt, self.core.finished + return content, err + r = self.gateway.call(name, args) + self.calls_in_attempt, self.finished = r.calls_in_attempt, r.finished + return r.content, r.is_error + + +class SchemaOnly: + """No robot session: the harness preflight only needs tools/list (byte-identical to a real session).""" + finished = False + + def log(self, d): + pass + + def call(self, name, args): + return [dict(type="text", text="schema-only preflight server: no robot session")], True + + +def serve(sess): + def send(obj): + sys.stdout.write(json.dumps(obj) + "\n") + sys.stdout.flush() + + for line in sys.stdin: + line = line.strip() + if not line: + continue + try: + msg = json.loads(line) + except ValueError: + send(dict(jsonrpc="2.0", id=None, error=dict(code=-32700, message="parse error"))) + continue + mid, method, params = msg.get("id"), msg.get("method"), msg.get("params") or {} + if mid is None: # notification (notifications/initialized, cancelled, ...) + continue + try: + if method == "initialize": + want = params.get("protocolVersion") + result = dict(protocolVersion=want if want in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0], + capabilities=dict(tools=dict(listChanged=False)), + serverInfo=dict(name="lffbench-robot", version="1.0")) + elif method == "ping": + result = {} + elif method == "tools/list": + result = dict(tools=[dict(name=t["name"], description=t["description"], inputSchema=t["parameters"]) + for t in TOOLS]) + elif method == "tools/call": + name, args = params.get("name"), params.get("arguments") or {} + t0 = time.time() + content, err = sess.call(name, args) + sess.log(dict(ev="tool", name=name, arguments=args, dt=round(time.time() - t0, 2), is_error=err, + output=[c["text"] for c in content if c["type"] == "text"], + images=sum(1 for c in content if c["type"] == "image"), finished=sess.finished, + calls_in_attempt=getattr(sess, "calls_in_attempt", None))) + result = dict(content=content, isError=err) + else: + send(dict(jsonrpc="2.0", id=mid, error=dict(code=-32601, message=f"method not found: {method}"))) + continue + send(dict(jsonrpc="2.0", id=mid, result=result)) + except Exception as e: + sess.log(dict(ev="error", method=method, error=traceback.format_exc()[-2000:])) + send(dict(jsonrpc="2.0", id=mid, error=dict(code=-32603, message=f"{type(e).__name__}: {e}"))) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--session", help="session.json written by start_robot_session.sh (la style)") + ap.add_argument("--schema-only", action="store_true", help="serve the tool list only (harness launch preflight)") + a = ap.parse_args() + if a.schema_only: + serve(SchemaOnly()) + return + if not a.session: + ap.error("--session is required (or --schema-only)") + sess = Session(a.session) + import hashlib # names + 8-hex sha256 of each value (enough to tell inherited from fresh values, reveals nothing) + sess.log(dict(ev="start", session=a.session, pid=os.getpid(), env_keys=sorted(ENV_AT_START), + env_value_sha8={k: hashlib.sha256(v.encode()).hexdigest()[:8] for k, v in ENV_AT_START.items()})) + serve(sess) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/scripts/model_gateway.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/scripts/model_gateway.py new file mode 100644 index 0000000000000000000000000000000000000000..c8f4c48692827e11db9a73a7fc4000d35215785c --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/scripts/model_gateway.py @@ -0,0 +1,562 @@ +"""Per-run model-API gateway: the native harness's only road to its model API (docs/15 §3.2, docs/18 §3 rows 5 and 8). + +The harness (Codex, Claude Code, a robot harness framework on Codex) is pointed at this process instead of its model +API; the gateway forwards model requests unchanged to the same upstream with the harness's own credentials (it never +stores or logs a key or a header) and refuses, without forwarding, everything that would let the model use something +outside the benchmark's three tools: + - a path that is not a model call (connectors, apps, plugins, files, conversations, web search endpoints, ...); + - a request declaring a tool the harness does not run itself: any OpenAI tool type other than function / custom / + namespace (web_search, file_search, code_interpreter, image_generation, remote mcp, computer_use, local_shell ...), + any Anthropic tool with a server/built-in type (web_search_*, web_fetch_*, code_execution_*, bash_*, ...); + - a provider-side field (stored prompt, remote MCP servers, search options, containers); + - an image or file given as an http(s) address for the provider to fetch (data: URLs are fine); + - a body the gateway cannot read (more than one Content-Encoding, an encoding it cannot decode, not one JSON object). +A refusal is answered 403 with an error naming the reason and is recorded; it does not void the trial (nothing tells +the agent trying is forbidden), the launcher flags it in harness.json for a look. Same rules as Embodied First Exam's +usage gateway (running.md "Usage gateway"); the motivating case there: a harness offered tools that ran on the +provider's servers, outside the container's network rules, and agents used them. + +It also counts tokens per request from the response (OpenAI `response.completed` usage, Anthropic message_start / +message_delta usage, or a JSON body's usage), records every model name a request names (docs/18 §3 row 5: every call of +the run uses the model under test), and can stop the run at a token budget (`budget_stop`). + + python scripts/model_gateway.py --upstream https://api.openai.com/v1 --kind openai --log-dir +writes /model_gateway.json {url, port, pid, upstream_host} once it listens, one line per request to +/model_gateway_usage.jsonl (method, path, status, refusal reason, tool types, model, tokens; never a body or +a header) and the running totals to /model_gateway_totals.json. Listens on 127.0.0.1 only. Not part of +contract_sha256 (an access path, like tool_gateway.py). +""" +import argparse +import gzip +import http.client +import json +import os +import re +import shutil +import ssl +import subprocess +import sys +import threading +import time +import urllib.parse +import urllib.request +import uuid +import zlib +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +GATEWAY_FILE = "model_gateway.json" +USAGE_LOG = "model_gateway_usage.jsonl" +TOTALS = "model_gateway_totals.json" +MAX_BODY = 256 * 1024 * 1024 +READ_TIMEOUT_S = 1800 + +# model calls, as paths relative to the upstream base URL (query strings ignored) +ALLOWED_PATHS = { + "openai": [("POST", r"responses"), ("POST", r"responses/compact"), ("POST", r"responses/input_tokens"), + ("GET", r"models(/[^/]+)?")], + "anthropic": [("POST", r"v1/messages"), ("POST", r"v1/messages/count_tokens"), ("GET", r"v1/models(/[^/]+)?")], +} +# DeepSeek Harness uploads request images (--allow-files): same provider, same key, no other use than the next request +FILE_PATHS = [("POST", r"v1/files"), ("GET", r"v1/files(/[^/]+)?"), ("DELETE", r"v1/files/[^/]+")] +# what a harness sends by itself at start-up without being a model call: refused, counted apart, not a refusal +HARNESS_PROBES = {"anthropic": [("HEAD", r"api/hello"), ("GET", r"api/hello")]} +OPENAI_CLIENT_TOOL_TYPES = {None, "function", "custom", "namespace"} +PROVIDER_SIDE_FIELDS = { + "openai": {"prompt", "mcp_servers", "web_search_options", "container", "plugins", "search_parameters", + "enable_search", "tool_resources"}, + "anthropic": {"mcp_servers", "container"}, +} +HOP = {"connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", + "upgrade", "host", "content-length", "accept-encoding"} + + +# ------------------------------------------------------------------------------------------------------- checks +def decode_body(raw, encoding): + """-> (decoded bytes or None, note). One Content-Encoding at most.""" + enc = [e.strip().lower() for e in (encoding or "").split(",") if e.strip() and e.strip().lower() != "identity"] + if not enc: + return raw, None + if len(enc) > 1: + return None, "several content encodings" + e = enc[0] + try: + if e == "gzip": + return gzip.decompress(raw), None + if e == "deflate": + return zlib.decompress(raw), None + if e == "zstd": + try: + import zstandard + return zstandard.ZstdDecompressor().decompressobj().decompress(raw), None + except ImportError: + if shutil.which("zstd"): + p = subprocess.run(["zstd", "-d", "-c"], input=raw, capture_output=True, timeout=60) + if p.returncode == 0: + return p.stdout, None + return None, "zstd body and neither the zstandard module nor the zstd program" + except Exception as ex: + return None, f"{e}: {type(ex).__name__}" + return None, f"unsupported content encoding {e}" + + +def _tool_types_openai(tools, out): + for t in tools or []: + if not isinstance(t, dict): + out.append(("", False)) + continue + ty = t.get("type") + out.append((ty, ty in OPENAI_CLIENT_TOOL_TYPES)) + if ty == "namespace": + _tool_types_openai(t.get("tools"), out) + + +def declared_tools(kind, body): + """-> [(type, allowed)] for every tool the request declares (top-level, inside input items, inside namespaces).""" + out = [] + if kind == "openai": + _tool_types_openai(body.get("tools"), out) + for it in body.get("input") or []: + if isinstance(it, dict) and "tools" in it: + _tool_types_openai(it.get("tools"), out) + else: + for t in body.get("tools") or []: + ty = t.get("type") if isinstance(t, dict) else "" + out.append((ty, ty in (None, "custom"))) + return out + + +def remote_fetches(obj): + """Structured fields that ask the provider to fetch an http(s) address (images, files, documents).""" + hits = [] + + def walk(o): + if isinstance(o, dict): + for k in ("image_url", "file_url", "url"): + v = o.get(k) + if isinstance(v, dict): + v = v.get("url") + if isinstance(v, str) and re.match(r"https?://", v, re.I) and ( + k != "url" or o.get("type") in ("url", "image_url", "input_image", "input_file")): + hits.append(k) + src = o.get("source") + if isinstance(src, dict) and src.get("type") == "url": + hits.append("source.url") + for v in o.values(): + walk(v) + elif isinstance(o, list): + for v in o: + walk(v) + walk(obj.get("input") if "input" in obj else obj.get("messages")) + return hits + + +def check_request(kind, method, rel, headers, raw, allow_files=False): + """-> (refusal reason or None, info dict). info: tool types, model, probe flag.""" + info = {} + path = rel.split("?", 1)[0].strip("/") + if allow_files and any(method == m and re.fullmatch(pat, path) for m, pat in FILE_PATHS): + info["files"] = True + return None, info + for m, pat in HARNESS_PROBES.get(kind, []): + if method == m and re.fullmatch(pat, path): + return "harness_probe", info + if not any(method == m and re.fullmatch(pat, path) for m, pat in ALLOWED_PATHS[kind]): + return "path_not_allowed", info + if method != "POST": + return None, info + body, note = decode_body(raw, headers.get("Content-Encoding")) + if body is None: + info["note"] = note + return "body_unreadable", info + try: + obj = json.loads(body) + except ValueError: + return "body_unreadable", info + if not isinstance(obj, dict): + return "body_unreadable", info + info["model"] = obj.get("model") + tools = declared_tools(kind, obj) + info["tool_types"] = sorted({str(t) for t, _ in tools}) + info["n_tools"] = len(tools) + bad = sorted({str(t) for t, ok in tools if not ok}) + if bad: + info["refused_tool_types"] = bad + return "server_tool", info + side = sorted(PROVIDER_SIDE_FIELDS[kind] & set(obj)) + if side: + info["provider_side_fields"] = side + return "provider_side_field", info + rf = remote_fetches(obj) + if rf: + info["remote_fetch"] = sorted(set(rf)) + return "remote_fetch", info + return None, info + + +# ------------------------------------------------------------------------------------------------------- usage +def _norm_usage(kind, u): + if not isinstance(u, dict): + return {} + if kind == "openai": + return dict(input=u.get("input_tokens"), cached_input=(u.get("input_tokens_details") or {}).get("cached_tokens"), + output=u.get("output_tokens"), + reasoning=(u.get("output_tokens_details") or {}).get("reasoning_tokens")) + return dict(input=u.get("input_tokens"), cached_input=u.get("cache_read_input_tokens"), + cache_write=u.get("cache_creation_input_tokens"), output=u.get("output_tokens")) + + +class UsageTap: + """Reads the response as it streams by (SSE lines or one JSON body) and keeps the last usage it reports.""" + + def __init__(self, kind, ctype): + self.kind, self.sse = kind, "event-stream" in (ctype or "") + self.buf, self.usage = b"", {} + + def feed(self, chunk): + self.buf += chunk + if not self.sse: + if len(self.buf) > 64 * 1024 * 1024: + self.buf = b"" + return + *lines, self.buf = self.buf.split(b"\n") + for ln in lines: + if ln.startswith(b"data:") and b"usage" in ln: + try: + ev = json.loads(ln[5:].strip()) + except ValueError: + continue + self._event(ev) + + def _event(self, ev): + if not isinstance(ev, dict): + return + if self.kind == "openai" and ev.get("type") in ("response.completed", "response.incomplete", "response.failed"): + self.usage = _norm_usage("openai", (ev.get("response") or {}).get("usage")) + elif self.kind == "anthropic": + if ev.get("type") == "message_start": + self.usage = _norm_usage("anthropic", (ev.get("message") or {}).get("usage")) + elif ev.get("type") == "message_delta" and isinstance(ev.get("usage"), dict): + u = _norm_usage("anthropic", ev["usage"]) + self.usage.update({k: v for k, v in u.items() if v is not None}) + + def close(self): + if not self.sse and self.buf: + try: + obj = json.loads(self.buf) + if isinstance(obj, dict) and "usage" in obj: + self.usage = _norm_usage(self.kind, obj["usage"]) + except ValueError: + pass + return self.usage + + +# ------------------------------------------------------------------------------------------------------- forwarding +SYSTEM_CA_FILES = ("/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/certs/ca-bundle.crt", "/etc/ssl/cert.pem") + + +def ca_file(): + """SSL_CERT_FILE, else certifi's bundle, else the system bundle: the venv's Python may ship without a CA store + (README: "API 报证书错误").""" + if os.environ.get("SSL_CERT_FILE"): + return os.environ["SSL_CERT_FILE"] + try: + import certifi + return certifi.where() + except ImportError: + return next((p for p in SYSTEM_CA_FILES if os.path.exists(p)), None) + + +def upstream_connection(u): + """HTTP(S) connection to the upstream host, through HTTPS_PROXY / HTTP_PROXY unless NO_PROXY exempts it.""" + host, port = u.hostname, u.port or (443 if u.scheme == "https" else 80) + proxy = None if urllib.request.proxy_bypass(host) else urllib.request.getproxies().get(u.scheme) + if u.scheme == "https": + ctx = ssl.create_default_context(cafile=ca_file()) + if proxy: + p = urllib.parse.urlsplit(proxy) + c = http.client.HTTPSConnection(p.hostname, p.port or 80, context=ctx, timeout=READ_TIMEOUT_S) + c.set_tunnel(host, port) + return c, False + return http.client.HTTPSConnection(host, port, context=ctx, timeout=READ_TIMEOUT_S), False + if proxy: + p = urllib.parse.urlsplit(proxy) + return http.client.HTTPConnection(p.hostname, p.port or 80, timeout=READ_TIMEOUT_S), True + return http.client.HTTPConnection(host, port, timeout=READ_TIMEOUT_S), False + + +class Totals: + KEYS = ("requests", "forwarded", "harness_probes", "refused_paths", "refused_server_tools", "refused_fields", + "refused_remote_fetch", "refused_bodies", "refused_budget", "upstream_errors") + + def __init__(self, path, budget_in=None, budget_out=None): + self.path, self.lock = path, threading.Lock() + self.d = {k: 0 for k in self.KEYS} + self.d.update(tokens=dict(input=0, cached_input=0, output=0, reasoning=0), models={}, refused_examples=[], + budget_in=budget_in, budget_out=budget_out, budget_stop=None) + + def over_budget(self): + t = self.d["tokens"] + if self.d["budget_in"] is not None and t["input"] >= self.d["budget_in"]: + return "input" + if self.d["budget_out"] is not None and t["output"] >= self.d["budget_out"]: + return "output" + return None + + def add(self, rec): + with self.lock: + d = self.d + d["requests"] += 1 + r = rec.get("refused") + key = dict(harness_probe="harness_probes", path_not_allowed="refused_paths", server_tool="refused_server_tools", + provider_side_field="refused_fields", remote_fetch="refused_remote_fetch", + body_unreadable="refused_bodies", budget_stop="refused_budget").get(r) + if key: + d[key] += 1 + if r != "harness_probe" and len(d["refused_examples"]) < 20: + d["refused_examples"].append({k: rec.get(k) for k in ("method", "path", "refused", "refused_tool_types", + "provider_side_fields", "note")}) + elif rec.get("status") is None: + d["upstream_errors"] += 1 + else: + d["forwarded"] += 1 + if rec.get("model"): + d["models"][rec["model"]] = d["models"].get(rec["model"], 0) + 1 + for k, v in (rec.get("usage") or {}).items(): + if isinstance(v, int) and k in d["tokens"]: + d["tokens"][k] += v + if d["budget_stop"] is None and self.over_budget(): + d["budget_stop"] = dict(which=self.over_budget(), t=time.time()) + tmp = self.path + ".tmp" + with open(tmp, "w") as f: + json.dump(d, f, indent=1) + os.replace(tmp, self.path) + + +def serve(upstream, kind, log_dir, port=0, budget_in=None, budget_out=None, gateway_file=None, watch_parent=True, + allow_files=False): + up = urllib.parse.urlsplit(upstream.rstrip("/")) + base_path = up.path.rstrip("/") + ulog = open(os.path.join(log_dir, USAGE_LOG), "a") + llock = threading.Lock() + totals = Totals(os.path.join(log_dir, TOTALS), budget_in, budget_out) + opencode_session = "lffbench-" + uuid.uuid4().hex # one per gateway, i.e. per run + + def log(rec): + with llock: + ulog.write(json.dumps(rec, default=str) + "\n") + ulog.flush() + totals.add(rec) + + class H(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *a): + pass + + def _refuse(self, code, reason, detail): + body = json.dumps({"error": {"type": "lff_gateway_refused", "code": reason, + "message": f"refused by the benchmark's model gateway: {detail}"}}).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + if self.command != "HEAD": + self.wfile.write(body) + + def _read_body(self): + if "chunked" in (self.headers.get("Transfer-Encoding") or "").lower(): + out = b"" + while True: + n = int(self.rfile.readline().split(b";")[0].strip() or b"0", 16) + if n == 0: + self.rfile.readline() + return out + out += self.rfile.read(n) + self.rfile.readline() + if len(out) > MAX_BODY: + raise ValueError("body too large") + n = int(self.headers.get("Content-Length") or 0) + if n < 0 or n > MAX_BODY: + raise ValueError("bad Content-Length") + return self.rfile.read(n) if n else b"" + + def _handle(self): + t0 = time.time() + path = self.path + rel = path[len(base_path):] if base_path and path.startswith(base_path + "/") else ( + path if not base_path else None) + rec = dict(t=t0, method=self.command, path=path.split("?", 1)[0][:200]) + try: + raw = self._read_body() + except Exception as ex: + rec.update(refused="body_unreadable", note=str(ex)[:100]) + log(rec) + return self._refuse(400, "body_unreadable", "unreadable request body") + if rel is None: + reason, info = "path_not_allowed", {} + else: + reason, info = check_request(kind, self.command, rel, self.headers, raw, allow_files) + if reason is None and totals.d["budget_stop"] is not None and self.command == "POST": + reason = "budget_stop" + rec.update(info, req_bytes=len(raw)) + if reason: + rec["refused"] = reason + log(rec) + detail = dict(harness_probe="not a model call", path_not_allowed="not a model-API call", + server_tool="tool types run by the provider: " + ",".join(info.get("refused_tool_types", [])), + provider_side_field="provider-side fields: " + ",".join(info.get("provider_side_fields", [])), + remote_fetch="the provider would fetch an http(s) address", body_unreadable="unreadable body", + budget_stop="token budget of this run used up")[reason] + return self._refuse(404 if reason == "harness_probe" else 403, reason, detail) + hdrs = {k: v for k, v in self.headers.items() if k.lower() not in HOP} + hdrs["Accept-Encoding"] = "identity" + if up.hostname == "opencode.ai" and not any(k.lower() == "x-opencode-session" for k in hdrs): + hdrs["x-opencode-session"] = opencode_session # OpenCode Go refuses requests without one + if raw or self.command == "POST": + hdrs["Content-Length"] = str(len(raw)) + conn = None + try: + conn, absolute = upstream_connection(up) + target = f"{up.scheme}://{up.netloc}{path}" if absolute else path + conn.request(self.command, target, body=raw if raw or self.command == "POST" else None, headers=hdrs) + resp = conn.getresponse() + except Exception as ex: + rec.update(status=None, error=f"{type(ex).__name__}: {ex}"[:300], dur_s=round(time.time() - t0, 2)) + log(rec) + if conn is not None: + conn.close() + body = json.dumps({"error": {"type": "lff_gateway_upstream", "message": "upstream unreachable"}}).encode() + self.send_response(502) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + return + ctype = resp.getheader("Content-Type", "") + tap = UsageTap(kind, ctype) + self.send_response(resp.status) + for k, v in resp.getheaders(): + if k.lower() not in HOP: + self.send_header(k, v) + self.send_header("Transfer-Encoding", "chunked") + self.end_headers() + n_out, logged = 0, False + try: + while True: + chunk = resp.read1(65536) if hasattr(resp, "read1") else resp.read(65536) + if not chunk: + break + tap.feed(chunk) + n_out += len(chunk) + self.wfile.write(b"%x\r\n%s\r\n" % (len(chunk), chunk)) + self.wfile.flush() + # record before the last chunk: a client holding the whole response finds its tokens counted + rec.update(status=resp.status, resp_bytes=n_out, usage=tap.close(), dur_s=round(time.time() - t0, 2)) + log(rec) + logged = True + self.wfile.write(b"0\r\n\r\n") + self.wfile.flush() + except (BrokenPipeError, ConnectionResetError): + rec["client_disconnected"] = True + finally: + conn.close() + if not logged: + rec.update(status=resp.status, resp_bytes=n_out, usage=tap.close(), + dur_s=round(time.time() - t0, 2)) + log(rec) + + do_GET = do_POST = do_PUT = do_DELETE = do_PATCH = do_HEAD = _handle + + srv = ThreadingHTTPServer(("127.0.0.1", port), H) + srv.daemon_threads = True + url = f"http://127.0.0.1:{srv.server_address[1]}{base_path}" + gfile = gateway_file or os.path.join(log_dir, GATEWAY_FILE) + tmp = gfile + ".tmp" + with open(tmp, "w") as f: + json.dump(dict(url=url, port=srv.server_address[1], pid=os.getpid(), kind=kind, upstream_host=up.hostname), f) + os.replace(tmp, gfile) + if watch_parent: + ppid = os.getppid() + + def watch(): + while os.getppid() == ppid: + time.sleep(2) + srv.shutdown() + threading.Thread(target=watch, daemon=True).start() + try: + srv.serve_forever(poll_interval=0.5) + finally: + srv.server_close() + + +def start_model_gateway(upstream, kind, log_dir, budget_in=None, budget_out=None, python=None, timeout_s=30, + allow_files=False): + """Start a gateway for one run (child of the caller) and wait until it listens. -> (Popen, info dict with url). + The caller stops it with stop_model_gateway().""" + gfile = os.path.join(log_dir, GATEWAY_FILE) + if os.path.exists(gfile): + os.remove(gfile) + argv = [python or sys.executable, os.path.abspath(__file__), "--upstream", upstream, "--kind", kind, + "--log-dir", log_dir] + if budget_in is not None: + argv += ["--budget-in", str(int(budget_in))] + if budget_out is not None: + argv += ["--budget-out", str(int(budget_out))] + if allow_files: + argv.append("--allow-files") + err = open(os.path.join(log_dir, "model_gateway_stderr.txt"), "ab") + p = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=err, stderr=err) + deadline = time.time() + timeout_s + while time.time() < deadline: + if p.poll() is not None: + raise RuntimeError(f"model gateway exited with code {p.returncode}; see {log_dir}/model_gateway_stderr.txt") + if os.path.exists(gfile): + return p, json.load(open(gfile)) + time.sleep(0.05) + stop_model_gateway(p) + raise RuntimeError(f"model gateway did not start within {timeout_s} s") + + +def stop_model_gateway(p): + if p is None or p.poll() is not None: + return + p.terminate() + try: + p.wait(timeout=10) + except subprocess.TimeoutExpired: + p.kill() + p.wait() + + +def read_totals(log_dir): + try: + return json.load(open(os.path.join(log_dir, TOTALS))) + except (OSError, ValueError): + return None + + +def flagged(totals): + """Refusals worth a look (EFE: refused_paths / refused_server_tools / refused_bodies), probes excluded.""" + if not totals: + return [] + return [k for k in ("refused_paths", "refused_server_tools", "refused_fields", "refused_remote_fetch", + "refused_bodies", "refused_budget") if totals.get(k)] + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--upstream", required=True, help="the model API base URL the harness would otherwise call") + ap.add_argument("--kind", required=True, choices=sorted(ALLOWED_PATHS)) + ap.add_argument("--log-dir", required=True) + ap.add_argument("--port", type=int, default=0) + ap.add_argument("--budget-in", type=int, default=None, help="stop forwarding once this many input tokens were used") + ap.add_argument("--budget-out", type=int, default=None, help="... output tokens (reasoning included)") + ap.add_argument("--no-watch-parent", action="store_true") + ap.add_argument("--allow-files", action="store_true", help="also forward the provider's Files API (FILE_PATHS)") + a = ap.parse_args() + serve(a.upstream, a.kind, a.log_dir, port=a.port, budget_in=a.budget_in, budget_out=a.budget_out, + watch_parent=not a.no_watch_parent, allow_files=a.allow_files) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/scripts/trace_html.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/scripts/trace_html.py new file mode 100644 index 0000000000000000000000000000000000000000..651afc43f8b160358a4388c58659fa478c4b71f0 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/scripts/trace_html.py @@ -0,0 +1,148 @@ +"""Render one player-subagent run as a self-contained HTML trace: everything the agent received, +every command it ran, every result and image it saw, its own text, plus the server-side ground truth. + +python scripts/trace_html.py --batch exp1 --sandbox --out traces/.html +""" +import argparse +import base64 +import html +import json +import os +from datetime import datetime + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TRANSCRIPTS = os.environ.get("CLAUDE_TASKS_DIR", "") # the Claude Code session's tasks/ dir (.output files) + +CSS = """ +:root{--bg:#fafaf9;--fg:#1c1917;--mut:#57534e;--card:#fff;--bd:#e7e5e4;--acc:#2563eb;--tool:#f5f5f4;--ok:#15803d;--bad:#b91c1c;--th:#7c3aed} +@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){--bg:#1c1917;--fg:#e7e5e4;--mut:#a8a29e;--card:#292524;--bd:#44403c;--acc:#60a5fa;--tool:#231f1d;--ok:#4ade80;--bad:#f87171;--th:#c4b5fd}} +body{background:var(--bg);color:var(--fg);font:14px/1.55 system-ui,-apple-system,"PingFang SC","Microsoft YaHei",sans-serif;margin:0;padding:16px;max-width:1100px;margin:auto} +h1{font-size:20px}h2{font-size:17px;margin-top:28px;border-bottom:1px solid var(--bd);padding-bottom:4px} +.card{background:var(--card);border:1px solid var(--bd);border-radius:8px;padding:10px 12px;margin:8px 0} +pre{white-space:pre-wrap;word-break:break-word;background:var(--tool);border:1px solid var(--bd);border-radius:6px;padding:8px;font:12px/1.45 ui-monospace,Menlo,monospace;margin:4px 0;max-height:420px;overflow:auto} +.lbl{font-size:12px;color:var(--mut);font-weight:600;text-transform:uppercase;letter-spacing:.03em} +.cmd{color:var(--acc)}.think{color:var(--th)}.ok{color:var(--ok);font-weight:600}.bad{color:var(--bad);font-weight:600} +img{max-width:256px;border-radius:4px;border:1px solid var(--bd);margin:2px} +details>summary{cursor:pointer;color:var(--mut)} +table{border-collapse:collapse}td,th{border:1px solid var(--bd);padding:3px 8px;text-align:left;font-size:13px} +.step{display:flex;gap:8px}.n{color:var(--mut);min-width:34px;font-variant-numeric:tabular-nums} +""" + + +def esc(s): + return html.escape(str(s)) + + +def ts(x): + return datetime.fromisoformat(x.replace("Z", "+00:00")).timestamp() + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--batch", default="exp1") + ap.add_argument("--sandbox", required=True, help="sandbox hex id") + ap.add_argument("--out", required=True) + ap.add_argument("--title", default="") + a = ap.parse_args() + m = json.load(open(os.path.join(ROOT, "runs", "claude", a.batch, "manifest.json"))) + run = next(r for r in m["runs"] if r["sandbox"].endswith(a.sandbox)) + tr = [json.loads(l) for l in open(os.path.join(TRANSCRIPTS, f"{run['agent']}.output"))] + ev = [json.loads(l) for l in open(os.path.join(run["log"], "events.jsonl"))] + start = next(e for e in ev if e["ev"] == "session_start") + dones = [e for e in ev if e["ev"] == "done"] + http = [e for e in ev if e["ev"] == "http"] + think = [h["think_s"] for h in http if h.get("think_s")] + srv = [h["server_s"] for h in http] + + out = [f"{esc(a.title or 'Agent trace')}"] + out.append(f"

{esc(a.title or run['run'])}

") + out.append("
") + rows = [("任务", run["task"]), ("种子", run["seed"]), ("模型", run["model"]), ("条件", run["cond"] + f"(k={run['k']})"), + ("沙箱", run["sandbox"]), ("服务端 run 名", run["run"]), + ("结果", ";".join(f"第{d['attempt']}次 {'成功' if d['success'] else '失败'}" for d in dones)), + ("命令数 / 模型思考总时长 / 仿真执行总时长", f"{sum(1 for e in ev if e['ev']=='call')} / {sum(think):.0f} s / {sum(srv):.0f} s"), + ("子代理墙钟", f"{(ts(tr[-1]['timestamp']) - ts(tr[0]['timestamp'])) / 60:.1f} min")] + for k, v in rows: + out.append(f"") + out.append("
{esc(k)}{esc(v)}
") + inst = {k: v for k, v in start["inst"].items()} + out.append("
服务端真值(agent 从未看到)
" + esc(json.dumps(inst, indent=1, ensure_ascii=False)[:3000]) + "
") + + # ---------------------------------------------------------------- what the agent received + out.append("

1. agent 收到的上下文

") + out.append("
Claude Code 内置的系统提示和工具定义不在对话记录里(由 Claude Code 注入,这里看不到原文)。下面是记录里能看到的全部注入内容和我的提示。
") + for d in tr: + if d["type"] != "attachment": + continue + at = d["attachment"] + t = at.get("type") + if t == "instructions": + for f in at.get("files", []): + out.append(f"
注入附件:{esc(f.get('type'))} — {esc(f.get('path'))}({len(f.get('content',''))} 字符)
{esc(f.get('content',''))}
") + elif t in ("environment", "model", "date", "session_context", "skill_listing", "deferred_tools_delta", "credential_org"): + body = json.dumps({k: v for k, v in at.items() if k != "type"}, ensure_ascii=False, indent=1) + out.append(f"
注入附件:{esc(t)}({len(body)} 字符)
{esc(body[:6000])}
") + first_user = next(d for d in tr if d["type"] == "user") + out.append("
我给 agent 的提示(原文)
" + esc(first_user["message"]["content"]) + "
") + + # ---------------------------------------------------------------- timeline + out.append("

2. 逐步过程(agent 的文字、执行的命令、收到的结果和图像)

") + n = 0 + results = {} + for d in tr: + if d["type"] == "user" and isinstance(d["message"].get("content"), list): + for c in d["message"]["content"]: + if c.get("type") == "tool_result": + results[c["tool_use_id"]] = c + t0 = ts(tr[0]["timestamp"]) + for d in tr: + if d["type"] != "assistant": + continue + for c in d["message"].get("content", []): + ct = c.get("type") + tt = f"+{ts(d['timestamp']) - t0:6.0f}s" + if ct == "thinking" and c.get("thinking"): + out.append(f"
{tt} 思考
{esc(c['thinking'])}
") + elif ct == "text" and c.get("text", "").strip(): + out.append(f"
{tt} agent 文字
{esc(c['text'])}
") + elif ct == "tool_use": + n += 1 + inp = c.get("input", {}) + if c["name"] == "Bash": + head = f"Bash: {esc(inp.get('command',''))}" + elif c["name"] == "Read": + head = f"Read: {esc(inp.get('file_path',''))}" + elif c["name"] == "SubagentHandback": + head = "最终报告(SubagentHandback)" + else: + head = f"{esc(c['name'])}: {esc(json.dumps(inp, ensure_ascii=False)[:300])}" + block = [f"
{tt} #{n} 工具调用 {head}"] + if c["name"] == "SubagentHandback": + block.append(f"
{esc(inp.get('message',''))}
") + r = results.get(c["id"]) + if r is not None: + rc = r.get("content") + if isinstance(rc, str): + rc = [{"type": "text", "text": rc}] + for part in rc or []: + if part.get("type") == "text": + txt = part["text"] + block.append(f"
返回({len(txt)} 字符)
{esc(txt)}
") + elif part.get("type") == "image": + src = part.get("source", {}) + if src.get("type") == "base64": + block.append(f"") + block.append("
") + out.extend(block) + out.append("

3. 服务端每次 done 的判定

") + for e in dones: + out.append(f"
第 {e['attempt']} 次:{'成功' if e['success'] else '失败'}
{esc(e.get('feedback',''))}
") + out.append("") + os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True) + with open(a.out, "w") as f: + f.write("\n".join(out)) + print(a.out, os.path.getsize(a.out), "bytes; tool calls", n) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/arm_specs/__init__.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/arm_specs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..22365defb89a4a645913280cccf372f1ca7bd219 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/arm_specs/__init__.py @@ -0,0 +1,53 @@ +"""Per-task specs for the controlled arms of full5 (2026-10-12, docs/14 §6). + +One module per task, named exactly like the task (lffbench/arm_specs/.py), defining: + + HIDDEN_KEYS : tuple of instance keys that carry the hidden variable(s) + h0(inst) -> dict overrides for the H0 twin: same layout, hidden variable at its "ordinary" value, so the + common-sense first attempt succeeds (scripted naive succeeds) + twin(inst) -> dict overrides for the mismatched-history source: same layout, the trap is still active (scripted + naive still fails, visibly) but the right correction is different from the original instance's, + ideally opposite (e.g. centre of mass on the other side) + reveal(inst)-> str H+ text appended to the task instruction: the hidden variable stated plainly in robot-frame + words a careful human could act on, without prescribing the solution + +All three take the ORIGINAL sampled instance and return only the keys to change (JSON-serialisable). The server +applies them with dict.update() after sample_instance(); reset_instance() must honour them. +""" +import importlib + + +def load(task_name): + """The spec module for task_name, or None if the task has no controlled-arm spec.""" + try: + return importlib.import_module(f"{__name__}.{task_name}") + except ModuleNotFoundError as e: + if e.name == f"{__name__}.{task_name}": + return None + raise + + +def overrides(task_name, arm, inst): + """Instance overrides for arm in (h0, twin); {} for other arms.""" + if arm not in ("h0", "twin"): + return {} + spec = load(task_name) + if spec is None: + raise SystemExit(f"--arm {arm}: no spec in lffbench/arm_specs/{task_name}.py") + return getattr(spec, arm)(inst) + + +def reveal(task_name, inst): + spec = load(task_name) + if spec is None: + raise SystemExit(f"--arm hplus: no spec in lffbench/arm_specs/{task_name}.py") + return spec.reveal(inst) + + +def fix(task_name, inst, params): + """Fix-rung text of the layer-3 feedback ladder (docs/20): how to succeed on this instance, in robot-frame words, + built from the task's oracle parameters `params` (task.oracle_params(inst), computed by the caller with the sim).""" + spec = load(task_name) + if spec is None or not hasattr(spec, "fix"): + raise SystemExit(f"ladder fix: no fix() in lffbench/arm_specs/{task_name}.py") + return spec.fix(inst, params) diff --git a/leaf/release/source_packages/v1.5/lff/release/backfill_terminal_status.json b/leaf/release/source_packages/v1.5/lff/release/backfill_terminal_status.json new file mode 100644 index 0000000000000000000000000000000000000000..f9f21ced05e73e689cd2e055dc1d35f2e5a9fb4a --- /dev/null +++ b/leaf/release/source_packages/v1.5/lff/release/backfill_terminal_status.json @@ -0,0 +1,960 @@ +{ + "status": "finished_with_errors", + "pid": 1566366, + "started": 1793600313.669674, + "total_runs": 780, + "batch_order": [ + "lf1_gpt", + "lf2_gpt", + "lhp_gpt", + "lfx_gpt", + "cc_opus_s3", + "cc_sonnet_s3", + "ds41_cc_s2", + "ds41_dsh_s2", + "cc_fable1", + "dm_opus", + "dm_sonnet", + "do_opus", + "do_sonnet", + "ds_cx1", + "l4i_f1_test", + "l4i_first", + "l4i_fx_test", + "l4i_hp_test", + "l4i_v_test", + "lf1_opus_r2", + "lf1_sonnet_r2", + "lf2_opus", + "lf2_opus_r2", + "lf2_sonnet", + "lf2_sonnet_r2", + "lfx_opus", + "lfx_opus_r2", + "lfx_sonnet", + "lfx_sonnet_r2", + "lhp_opus", + "lhp_opus_r2", + "lhp_sonnet", + "lhp_sonnet_r2", + "tw2_opus", + "tw2_sonnet", + "tw_opus", + "tw_sonnet" + ], + "results": { + "lf1_gpt": { + "batch": "lf1_gpt", + "status": "complete", + "pid": 1566366, + "started": 1793600313.7147295, + "total_runs": 14, + "recorded": 14, + "accepted": 14, + "finished": 1793601576.2675502, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-lf1_gpt", + "validation": { + "codebase_version": "v3.0", + "episodes": 14, + "frames": 19317, + "plan_episodes": 14, + "plan_frames": 19317, + "samples": 60, + "max_state_action_abs_err": 1.1724506343568919e-07, + "max_mean_abs_pixel_err": 2.191, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 14, + "complete_coverage": true + }, + "lf2_gpt": { + "batch": "lf2_gpt", + "status": "complete", + "pid": 1566366, + "started": 1793601578.0195405, + "total_runs": 14, + "recorded": 14, + "accepted": 14, + "finished": 1793602627.5550525, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-lf2_gpt", + "validation": { + "codebase_version": "v3.0", + "episodes": 14, + "frames": 16375, + "plan_episodes": 14, + "plan_frames": 16375, + "samples": 60, + "max_state_action_abs_err": 1.1913010844466498e-07, + "max_mean_abs_pixel_err": 2.455, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 14, + "complete_coverage": true + }, + "lhp_gpt": { + "batch": "lhp_gpt", + "status": "complete", + "pid": 1566366, + "started": 1793602629.083984, + "total_runs": 14, + "recorded": 14, + "accepted": 14, + "finished": 1793603407.8407047, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-lhp_gpt", + "validation": { + "codebase_version": "v3.0", + "episodes": 14, + "frames": 11703, + "plan_episodes": 14, + "plan_frames": 11703, + "samples": 60, + "max_state_action_abs_err": 1.1903838181837045e-07, + "max_mean_abs_pixel_err": 2.055, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 14, + "complete_coverage": true + }, + "lfx_gpt": { + "batch": "lfx_gpt", + "status": "complete", + "pid": 1566366, + "started": 1793603409.2950618, + "total_runs": 14, + "recorded": 14, + "accepted": 14, + "finished": 1793604118.345863, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-lfx_gpt", + "validation": { + "codebase_version": "v3.0", + "episodes": 14, + "frames": 12036, + "plan_episodes": 14, + "plan_frames": 12036, + "samples": 60, + "max_state_action_abs_err": 1.1860115600725862e-07, + "max_mean_abs_pixel_err": 2.126, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 14, + "complete_coverage": true + }, + "cc_opus_s3": { + "batch": "cc_opus_s3", + "status": "complete", + "pid": 1566366, + "started": 1793604119.904843, + "total_runs": 61, + "recorded": 61, + "accepted": 61, + "finished": 1793609756.8337307, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-cc_opus_s3", + "validation": { + "codebase_version": "v3.0", + "episodes": 84, + "frames": 103411, + "plan_episodes": 84, + "plan_frames": 103411, + "samples": 60, + "max_state_action_abs_err": 1.1916465636474527e-07, + "max_mean_abs_pixel_err": 2.607, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 61, + "complete_coverage": true + }, + "cc_sonnet_s3": { + "batch": "cc_sonnet_s3", + "status": "complete", + "pid": 1566366, + "started": 1793609766.696507, + "total_runs": 54, + "recorded": 54, + "accepted": 48, + "finished": 1793615170.0615594, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-cc_sonnet_s3", + "validation": { + "codebase_version": "v3.0", + "episodes": 61, + "frames": 85266, + "plan_episodes": 61, + "plan_frames": 85266, + "samples": 60, + "max_state_action_abs_err": 1.1889436102308082e-07, + "max_mean_abs_pixel_err": 2.183, + "status": "pass" + }, + "rejected_runs": 6, + "exported_runs": 48, + "complete_coverage": false + }, + "ds41_cc_s2": { + "batch": "ds41_cc_s2", + "status": "complete", + "pid": 1566366, + "started": 1793615175.740563, + "total_runs": 82, + "recorded": 82, + "accepted": 80, + "finished": 1793626901.0030243, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-ds41_cc_s2", + "validation": { + "codebase_version": "v3.0", + "episodes": 126, + "frames": 208012, + "plan_episodes": 126, + "plan_frames": 208012, + "samples": 60, + "max_state_action_abs_err": 1.184606701620794e-07, + "max_mean_abs_pixel_err": 2.317, + "status": "pass" + }, + "rejected_runs": 2, + "exported_runs": 80, + "complete_coverage": false + }, + "ds41_dsh_s2": { + "batch": "ds41_dsh_s2", + "status": "complete", + "pid": 1566366, + "started": 1793626913.310161, + "total_runs": 83, + "recorded": 83, + "accepted": 82, + "finished": 1793639705.4001992, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-ds41_dsh_s2", + "validation": { + "codebase_version": "v3.0", + "episodes": 128, + "frames": 233138, + "plan_episodes": 128, + "plan_frames": 233138, + "samples": 60, + "max_state_action_abs_err": 1.1603973781859622e-07, + "max_mean_abs_pixel_err": 2.292, + "status": "pass" + }, + "rejected_runs": 1, + "exported_runs": 82, + "complete_coverage": false + }, + "cc_fable1": { + "batch": "cc_fable1", + "status": "complete", + "pid": 1566366, + "started": 1793639719.6236918, + "total_runs": 10, + "recorded": 10, + "accepted": 10, + "finished": 1793641052.2563536, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-cc_fable1", + "validation": { + "codebase_version": "v3.0", + "episodes": 14, + "frames": 18669, + "plan_episodes": 14, + "plan_frames": 18669, + "samples": 60, + "max_state_action_abs_err": 1.1831884449975405e-07, + "max_mean_abs_pixel_err": 2.965, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 10, + "complete_coverage": true + }, + "dm_opus": { + "batch": "dm_opus", + "status": "complete", + "pid": 1566366, + "started": 1793641054.3109798, + "total_runs": 15, + "recorded": 15, + "accepted": 15, + "finished": 1793642267.1286335, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-dm_opus", + "validation": { + "codebase_version": "v3.0", + "episodes": 15, + "frames": 18923, + "plan_episodes": 15, + "plan_frames": 18923, + "samples": 60, + "max_state_action_abs_err": 1.18263469239821e-07, + "max_mean_abs_pixel_err": 2.43, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 15, + "complete_coverage": true + }, + "dm_sonnet": { + "batch": "dm_sonnet", + "status": "complete", + "pid": 1566366, + "started": 1793642268.8987703, + "total_runs": 21, + "recorded": 21, + "accepted": 20, + "finished": 1793643504.0787046, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-dm_sonnet", + "validation": { + "codebase_version": "v3.0", + "episodes": 20, + "frames": 20084, + "plan_episodes": 20, + "plan_frames": 20084, + "samples": 60, + "max_state_action_abs_err": 1.1545366795928658e-07, + "max_mean_abs_pixel_err": 2.574, + "status": "pass" + }, + "rejected_runs": 1, + "exported_runs": 20, + "complete_coverage": false + }, + "do_opus": { + "batch": "do_opus", + "status": "complete", + "pid": 1566366, + "started": 1793643506.2366982, + "total_runs": 18, + "recorded": 18, + "accepted": 18, + "finished": 1793644656.2918403, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-do_opus", + "validation": { + "codebase_version": "v3.0", + "episodes": 18, + "frames": 18243, + "plan_episodes": 18, + "plan_frames": 18243, + "samples": 60, + "max_state_action_abs_err": 1.1915391029404532e-07, + "max_mean_abs_pixel_err": 2.192, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 18, + "complete_coverage": true + }, + "do_sonnet": { + "batch": "do_sonnet", + "status": "complete", + "pid": 1566366, + "started": 1793644657.9921644, + "total_runs": 21, + "recorded": 21, + "accepted": 21, + "finished": 1793645931.5812206, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-do_sonnet", + "validation": { + "codebase_version": "v3.0", + "episodes": 21, + "frames": 20650, + "plan_episodes": 21, + "plan_frames": 20650, + "samples": 60, + "max_state_action_abs_err": 1.1847645220441905e-07, + "max_mean_abs_pixel_err": 2.264, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 21, + "complete_coverage": true + }, + "ds_cx1": { + "batch": "ds_cx1", + "status": "failed", + "pid": 1566366, + "started": 1793645933.6093023, + "total_runs": 1, + "recorded": 1, + "accepted": 0, + "error": "Traceback (most recent call last):\n File \"/mnt/cpfs/workspace/agentic-robotics/ops/lerobot_backfill_20261102/run.py\", line 75, in export_batch\n plan=read(work/'plan.json');assert plan['episodes'],'no accepted episodes'\n ~~~~^^^^^^^^^^^^\nAssertionError: no accepted episodes\n", + "finished": 1793646073.0796149 + }, + "l4i_f1_test": { + "batch": "l4i_f1_test", + "status": "complete", + "pid": 1566366, + "started": 1793646073.1204603, + "total_runs": 8, + "recorded": 8, + "accepted": 8, + "finished": 1793647819.2159672, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-l4i_f1_test", + "validation": { + "codebase_version": "v3.0", + "episodes": 8, + "frames": 24520, + "plan_episodes": 8, + "plan_frames": 24520, + "samples": 60, + "max_state_action_abs_err": 1.1686053991155632e-07, + "max_mean_abs_pixel_err": 2.633, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 8, + "complete_coverage": true + }, + "l4i_first": { + "batch": "l4i_first", + "status": "complete", + "pid": 1566366, + "started": 1793647820.5433233, + "total_runs": 8, + "recorded": 8, + "accepted": 8, + "finished": 1793648638.6686633, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-l4i_first", + "validation": { + "codebase_version": "v3.0", + "episodes": 8, + "frames": 11365, + "plan_episodes": 8, + "plan_frames": 11365, + "samples": 60, + "max_state_action_abs_err": 1.1180616743544647e-07, + "max_mean_abs_pixel_err": 2.49, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 8, + "complete_coverage": true + }, + "l4i_fx_test": { + "batch": "l4i_fx_test", + "status": "complete", + "pid": 1566366, + "started": 1793648639.6361263, + "total_runs": 8, + "recorded": 8, + "accepted": 8, + "finished": 1793649218.1244133, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-l4i_fx_test", + "validation": { + "codebase_version": "v3.0", + "episodes": 8, + "frames": 7500, + "plan_episodes": 8, + "plan_frames": 7500, + "samples": 60, + "max_state_action_abs_err": 1.1768071805917657e-07, + "max_mean_abs_pixel_err": 2.725, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 8, + "complete_coverage": true + }, + "l4i_hp_test": { + "batch": "l4i_hp_test", + "status": "complete", + "pid": 1566366, + "started": 1793649219.3410845, + "total_runs": 8, + "recorded": 8, + "accepted": 8, + "finished": 1793649974.971643, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-l4i_hp_test", + "validation": { + "codebase_version": "v3.0", + "episodes": 8, + "frames": 12477, + "plan_episodes": 8, + "plan_frames": 12477, + "samples": 60, + "max_state_action_abs_err": 1.1577036973520194e-07, + "max_mean_abs_pixel_err": 2.114, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 8, + "complete_coverage": true + }, + "l4i_v_test": { + "batch": "l4i_v_test", + "status": "complete", + "pid": 1566366, + "started": 1793649976.0384119, + "total_runs": 8, + "recorded": 8, + "accepted": 8, + "finished": 1793650885.9047408, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-l4i_v_test", + "validation": { + "codebase_version": "v3.0", + "episodes": 8, + "frames": 13870, + "plan_episodes": 8, + "plan_frames": 13870, + "samples": 60, + "max_state_action_abs_err": 1.1890581808060574e-07, + "max_mean_abs_pixel_err": 2.417, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 8, + "complete_coverage": true + }, + "lf1_opus_r2": { + "batch": "lf1_opus_r2", + "status": "complete", + "pid": 1566366, + "started": 1793650887.1944373, + "total_runs": 18, + "recorded": 18, + "accepted": 18, + "finished": 1793652209.5657122, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-lf1_opus_r2", + "validation": { + "codebase_version": "v3.0", + "episodes": 18, + "frames": 17581, + "plan_episodes": 18, + "plan_frames": 17581, + "samples": 60, + "max_state_action_abs_err": 1.1792150500511411e-07, + "max_mean_abs_pixel_err": 2.715, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 18, + "complete_coverage": true + }, + "lf1_sonnet_r2": { + "batch": "lf1_sonnet_r2", + "status": "complete", + "pid": 1566366, + "started": 1793652211.298982, + "total_runs": 21, + "recorded": 21, + "accepted": 20, + "finished": 1793653707.6208901, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-lf1_sonnet_r2", + "validation": { + "codebase_version": "v3.0", + "episodes": 20, + "frames": 21587, + "plan_episodes": 20, + "plan_frames": 21587, + "samples": 60, + "max_state_action_abs_err": 1.189713518812141e-07, + "max_mean_abs_pixel_err": 2.139, + "status": "pass" + }, + "rejected_runs": 1, + "exported_runs": 20, + "complete_coverage": false + }, + "lf2_opus": { + "batch": "lf2_opus", + "status": "complete", + "pid": 1566366, + "started": 1793651677.0854275, + "total_runs": 18, + "recorded": 18, + "accepted": 18, + "finished": 1793653818.669584, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-lf2_opus", + "validation": { + "codebase_version": "v3.0", + "episodes": 18, + "frames": 18128, + "plan_episodes": 18, + "plan_frames": 18128, + "samples": 60, + "max_state_action_abs_err": 1.1807034283606299e-07, + "max_mean_abs_pixel_err": 2.276, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 18, + "complete_coverage": true + }, + "lf2_opus_r2": { + "batch": "lf2_opus_r2", + "status": "complete", + "pid": 1566366, + "started": 1793651581.982084, + "total_runs": 18, + "recorded": 18, + "accepted": 18, + "finished": 1793653926.0870295, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-lf2_opus_r2", + "validation": { + "codebase_version": "v3.0", + "episodes": 18, + "frames": 19100, + "plan_episodes": 18, + "plan_frames": 19100, + "samples": 60, + "max_state_action_abs_err": 1.1825047607771921e-07, + "max_mean_abs_pixel_err": 2.336, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 18, + "complete_coverage": true + }, + "lf2_sonnet": { + "batch": "lf2_sonnet", + "status": "complete", + "pid": 1566366, + "started": 1793651436.200448, + "total_runs": 21, + "recorded": 21, + "accepted": 21, + "finished": 1793654017.7480464, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-lf2_sonnet", + "validation": { + "codebase_version": "v3.0", + "episodes": 21, + "frames": 22758, + "plan_episodes": 21, + "plan_frames": 22758, + "samples": 60, + "max_state_action_abs_err": 1.1914825881476077e-07, + "max_mean_abs_pixel_err": 2.018, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 21, + "complete_coverage": true + }, + "lf2_sonnet_r2": { + "batch": "lf2_sonnet_r2", + "status": "complete", + "pid": 1566366, + "started": 1793651413.7165208, + "total_runs": 21, + "recorded": 21, + "accepted": 21, + "finished": 1793654097.8493671, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-lf2_sonnet_r2", + "validation": { + "codebase_version": "v3.0", + "episodes": 21, + "frames": 18108, + "plan_episodes": 21, + "plan_frames": 18108, + "samples": 60, + "max_state_action_abs_err": 1.1734161198262427e-07, + "max_mean_abs_pixel_err": 2.557, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 21, + "complete_coverage": true + }, + "lfx_opus": { + "batch": "lfx_opus", + "status": "complete", + "pid": 1566366, + "started": 1793651355.6752522, + "total_runs": 18, + "recorded": 18, + "accepted": 18, + "finished": 1793654183.9035606, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-lfx_opus", + "validation": { + "codebase_version": "v3.0", + "episodes": 18, + "frames": 18136, + "plan_episodes": 18, + "plan_frames": 18136, + "samples": 60, + "max_state_action_abs_err": 1.1799878807394748e-07, + "max_mean_abs_pixel_err": 2.492, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 18, + "complete_coverage": true + }, + "lfx_opus_r2": { + "batch": "lfx_opus_r2", + "status": "complete", + "pid": 1566366, + "started": 1793651225.3645833, + "total_runs": 18, + "recorded": 18, + "accepted": 18, + "finished": 1793654264.575927, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-lfx_opus_r2", + "validation": { + "codebase_version": "v3.0", + "episodes": 18, + "frames": 15633, + "plan_episodes": 18, + "plan_frames": 15633, + "samples": 60, + "max_state_action_abs_err": 1.1870812910430573e-07, + "max_mean_abs_pixel_err": 2.199, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 18, + "complete_coverage": true + }, + "lfx_sonnet": { + "batch": "lfx_sonnet", + "status": "complete", + "pid": 1566366, + "started": 1793651132.9554276, + "total_runs": 21, + "recorded": 21, + "accepted": 21, + "finished": 1793654336.6110673, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-lfx_sonnet", + "validation": { + "codebase_version": "v3.0", + "episodes": 21, + "frames": 15837, + "plan_episodes": 21, + "plan_frames": 15837, + "samples": 60, + "max_state_action_abs_err": 1.1737579530546327e-07, + "max_mean_abs_pixel_err": 2.153, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 21, + "complete_coverage": true + }, + "lfx_sonnet_r2": { + "batch": "lfx_sonnet_r2", + "status": "complete", + "pid": 1566366, + "started": 1793650841.7943683, + "total_runs": 21, + "recorded": 21, + "accepted": 21, + "finished": 1793654422.7024949, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-lfx_sonnet_r2", + "validation": { + "codebase_version": "v3.0", + "episodes": 21, + "frames": 18611, + "plan_episodes": 21, + "plan_frames": 18611, + "samples": 60, + "max_state_action_abs_err": 1.1764796825630697e-07, + "max_mean_abs_pixel_err": 2.44, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 21, + "complete_coverage": true + }, + "lhp_opus": { + "batch": "lhp_opus", + "status": "complete", + "pid": 1566366, + "started": 1793650785.40539, + "total_runs": 18, + "recorded": 18, + "accepted": 18, + "finished": 1793654632.5387642, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-lhp_opus", + "validation": { + "codebase_version": "v3.0", + "episodes": 18, + "frames": 13205, + "plan_episodes": 18, + "plan_frames": 13205, + "samples": 60, + "max_state_action_abs_err": 1.1858898085748137e-07, + "max_mean_abs_pixel_err": 1.988, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 18, + "complete_coverage": true + }, + "lhp_opus_r2": { + "batch": "lhp_opus_r2", + "status": "complete", + "pid": 1566366, + "started": 1793650785.400976, + "total_runs": 18, + "recorded": 18, + "accepted": 18, + "finished": 1793654847.3859386, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-lhp_opus_r2", + "validation": { + "codebase_version": "v3.0", + "episodes": 18, + "frames": 15364, + "plan_episodes": 18, + "plan_frames": 15364, + "samples": 60, + "max_state_action_abs_err": 1.1756869788825952e-07, + "max_mean_abs_pixel_err": 2.112, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 18, + "complete_coverage": true + }, + "lhp_sonnet": { + "batch": "lhp_sonnet", + "status": "complete", + "pid": 1566366, + "started": 1793650785.4029303, + "total_runs": 21, + "recorded": 21, + "accepted": 21, + "finished": 1793655065.9577096, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-lhp_sonnet", + "validation": { + "codebase_version": "v3.0", + "episodes": 21, + "frames": 23240, + "plan_episodes": 21, + "plan_frames": 23240, + "samples": 60, + "max_state_action_abs_err": 1.189473035623223e-07, + "max_mean_abs_pixel_err": 2.377, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 21, + "complete_coverage": true + }, + "lhp_sonnet_r2": { + "batch": "lhp_sonnet_r2", + "status": "complete", + "pid": 1566366, + "started": 1793655076.3171856, + "total_runs": 21, + "recorded": 21, + "accepted": 20, + "finished": 1793656766.637546, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-lhp_sonnet_r2", + "validation": { + "codebase_version": "v3.0", + "episodes": 20, + "frames": 19940, + "plan_episodes": 20, + "plan_frames": 19940, + "samples": 60, + "max_state_action_abs_err": 1.1917774411784876e-07, + "max_mean_abs_pixel_err": 2.014, + "status": "pass" + }, + "rejected_runs": 1, + "exported_runs": 20, + "complete_coverage": false + }, + "tw2_opus": { + "batch": "tw2_opus", + "status": "complete", + "pid": 1566366, + "started": 1793650785.3943248, + "total_runs": 5, + "recorded": 5, + "accepted": 5, + "finished": 1793656876.3889265, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-tw2_opus", + "validation": { + "codebase_version": "v3.0", + "episodes": 5, + "frames": 5124, + "plan_episodes": 5, + "plan_frames": 5124, + "samples": 60, + "max_state_action_abs_err": 1.1803604316185101e-07, + "max_mean_abs_pixel_err": 2.224, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 5, + "complete_coverage": true + }, + "tw2_sonnet": { + "batch": "tw2_sonnet", + "status": "complete", + "pid": 1566366, + "started": 1793650785.395043, + "total_runs": 1, + "recorded": 1, + "accepted": 1, + "finished": 1793656917.4415257, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-tw2_sonnet", + "validation": { + "codebase_version": "v3.0", + "episodes": 1, + "frames": 176, + "plan_episodes": 1, + "plan_frames": 176, + "samples": 60, + "max_state_action_abs_err": 1.184661573283563e-07, + "max_mean_abs_pixel_err": 2.058, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 1, + "complete_coverage": true + }, + "tw_opus": { + "batch": "tw_opus", + "status": "complete", + "pid": 1566366, + "started": 1793650785.3987782, + "total_runs": 18, + "recorded": 18, + "accepted": 18, + "finished": 1793657052.5833802, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-tw_opus", + "validation": { + "codebase_version": "v3.0", + "episodes": 18, + "frames": 28237, + "plan_episodes": 18, + "plan_frames": 28237, + "samples": 60, + "max_state_action_abs_err": 1.1910573505247157e-07, + "max_mean_abs_pixel_err": 2.368, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 18, + "complete_coverage": true + }, + "tw_sonnet": { + "batch": "tw_sonnet", + "status": "complete", + "pid": 1566366, + "started": 1793657054.7900257, + "total_runs": 21, + "recorded": 21, + "accepted": 20, + "finished": 1793659085.931022, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/backfill-20261102-tw_sonnet", + "validation": { + "codebase_version": "v3.0", + "episodes": 20, + "frames": 23807, + "plan_episodes": 20, + "plan_frames": 23807, + "samples": 60, + "max_state_action_abs_err": 1.1913980957345416e-07, + "max_mean_abs_pixel_err": 2.277, + "status": "pass" + }, + "rejected_runs": 1, + "exported_runs": 20, + "complete_coverage": false + } + }, + "current_batch": "tw_sonnet", + "finished": 1793659089.8985596 +} diff --git a/leaf/release/source_packages/v1.5/lff/release/validate_release.py b/leaf/release/source_packages/v1.5/lff/release/validate_release.py new file mode 100644 index 0000000000000000000000000000000000000000..ca1e37d14e3941fa3809edbd4f9c3dd61f1d89b1 --- /dev/null +++ b/leaf/release/source_packages/v1.5/lff/release/validate_release.py @@ -0,0 +1,155 @@ +"""Validate remapping, every numeric row and copied file, plus real LeRobot reads.""" +import argparse +import collections +from concurrent.futures import ThreadPoolExecutor +import json +from pathlib import Path +import random +import re +import time + +import av +import numpy as np +import pandas as pd +import pyarrow as pa +import pyarrow.compute as pc +import pyarrow.parquet as pq +from release import SHARED,read,rows,write,sha,utc + +def scalar_array(column): + c=column.combine_chunks() + return c.values.to_numpy().reshape(len(c),-1) if pa.types.is_list(c.type) else c.to_numpy() + +def read_video(path,timestamp): + with av.open(str(path)) as c: + s=c.streams.video[0];c.seek(max(0,int(timestamp/s.time_base)),stream=s,backward=True) + for f in c.decode(video=0): + if abs(float(f.time)-timestamp)<.024:return f.to_ndarray(format='rgb24') + if float(f.time)>timestamp+.025:raise AssertionError((path,timestamp,float(f.time))) + raise AssertionError(('Missing video frame',path,timestamp)) + +def validate(root,max_samples=160): + t0=time.time();root=Path(root) + if not (root/'lff/release/image_stats.json').exists(): + from refresh_image_stats import refresh + refresh(root) + image_stats=read(root/'lff/release/image_stats.json');assert image_stats['status']=='pass' + info=read(root/'meta/info.json');eps=rows(root/'lff/episodes.jsonl');runs=rows(root/'lff/runs.jsonl');maps=rows(root/'lff/release/file_mapping.jsonl') + assert len(eps)==info['total_episodes'] and sum(e['length'] for e in eps)==info['total_frames'] + assert len({(e['batch'],e['run'],tuple(e['attempts'])) for e in eps})==len(eps) + assert [e['episode_index'] for e in eps]==list(range(len(eps))) + meta=pq.read_table(root/'meta/episodes/chunk-000/file-000.parquet').to_pylist() + assert len(meta)==len(eps) + offset=0 + for e,m in zip(eps,meta): + assert e['dataset_from_index']==m['dataset_from_index']==offset + assert e['length']==m['length'];offset+=e['length'];assert e['dataset_to_index']==m['dataset_to_index']==offset + assert m['tasks']==[e['instruction']],('metadata task instruction mismatch',e['episode_index']) + a=read(root/f"lff/annotations/episode_{e['episode_index']:06d}.json") + assert a['source']['release_episode_index']==e['episode_index'] + assert a['task']['canonical_cause']==e['paper_cause'] in ['L1','L2','L3','L4','L5'] + assert a['run_outcome']['outcome_class']==e['run_outcome_class'] + assert a['run_outcome']['outcome_class_status']==e['run_outcome_class_status'] + assert a['task']['instruction']==e['instruction'] + assert [t['success'] for t in a['attempts']]==e['success'] + assert np.load(root/f"lff/sim_state/episode_{e['episode_index']:06d}.npy",mmap_mode='r').shape[0]==e['length'] + for k in ['observation.images.image','observation.images.wrist_image']: + start=m[f'videos/{k}/from_timestamp'];end=m[f'videos/{k}/to_timestamp'] + assert abs((end-start)*20-e['length'])<.01 + print('metadata and annotation structure pass',flush=True) + numeric_rows=0 + for fm in maps: + if fm['kind']!='data':continue + src=pq.read_table(SHARED/fm['source_dataset']/fm['source']);dst=pq.read_table(root/fm['target']) + assert src.column_names==dst.column_names and len(src)==len(dst) + for key in src.column_names: + expected=src[key] + if key=='episode_index':expected=pc.add(expected,fm['episode_offset']) + elif key=='index':expected=pc.add(expected,fm['index_offset']) + elif key=='task_index': + remapped=np.array(fm['episode_task_indices'])[src['episode_index'].to_numpy()] if 'episode_task_indices' in fm else np.array(fm['task_remap'])[expected.to_numpy()] + expected=pa.chunked_array([pa.array(remapped,type=pa.int64())]) + assert expected.equals(dst[key]),(fm['target'],key,'numeric content changed') + idx=dst['index'].to_numpy();assert np.all(np.diff(idx)==1) + epidx=dst['episode_index'].to_numpy();frames=dst['frame_index'].to_numpy();att=dst['annotation.attempt_index'].to_numpy();su=dst['annotation.attempt_success'].to_numpy() + assert set(np.unique(dst['annotation.phase'].to_numpy()))<={0,1,2} + for i in np.unique(epidx): + e=eps[int(i)];sel=epidx==i + assert np.array_equal(frames[sel],np.arange(e['length'])) + assert idx[sel][0]==e['dataset_from_index'] and idx[sel][-1]+1==e['dataset_to_index'] + assert set(np.unique(att[sel]))<=set(e['attempts']) + for ai,success in zip(e['attempts'],e['success']): + vals=su[sel & (att==ai)];assert len(vals) and np.all(vals==int(success)),(i,ai) + numeric_rows+=len(dst) + assert numeric_rows==info['total_frames'] + print('all numeric rows preserved and dense labels consistent',numeric_rows,flush=True) + binaries=[m for m in maps if m['kind']!='data'] + def check(fm): + src=SHARED/fm['source_dataset']/fm['source'];dst=root/fm['target'] + assert src.stat().st_size==dst.stat().st_size and sha(src)==sha(dst),fm + return dst.stat().st_size + with ThreadPoolExecutor(max_workers=4) as pool:binary_bytes=sum(pool.map(check,binaries)) + print('all copied media/physics hashes match',len(binaries),binary_bytes,flush=True) + video_frames=collections.Counter() + for fm in maps: + if fm['kind']!='video':continue + p=root/fm['target'];cam=p.parts[-3] + with av.open(str(p)) as c: + s=c.streams.video[0];assert s.width==256 and s.height==256 and float(s.average_rate)==20 and s.frames>0 + video_frames[cam]+=s.frames + assert all(n==info['total_frames'] for n in video_frames.values()),video_frames + lookup={(r['batch'],r['run']):r for r in runs};outside=[] + for r in runs: + parent=(r['batch'],r.get('memory_free_chain_of_run')) + if r.get('memory_free_chain_of'): + if parent in lookup: + p=lookup[parent];assert p['condition']=='with_history' and (p['task'],p['seed'])==(r['task'],r['seed']) + assert r['run'] in p['memory_free_retries'] + else:outside.append(r['run']) + for e in r['episodes']: + row=eps[e['episode_index']];assert row['run']==r['run'];assert e['success']==row['success'][row['attempts'].index(e['attempt'])] + # Deterministically cover every source package, task and physical video file. + pick=set();seen_tasks=set();seen_files=set();by_source=collections.defaultdict(list) + for e,m in zip(eps,meta): + by_source[e['source_dataset']].append(e['episode_index']) + if e['task'] not in seen_tasks:pick.add((e['episode_index'],e['length']//2));seen_tasks.add(e['task']) + vf=(m['videos/observation.images.image/chunk_index'],m['videos/observation.images.image/file_index']) + if vf not in seen_files:pick.add((e['episode_index'],0));seen_files.add(vf) + for ids in by_source.values():pick.add((ids[0],0));pick.add((ids[-1],eps[ids[-1]]['length']-1)) + rng=random.Random(15) + target=min(max(max_samples,len(pick)),info['total_frames']) + while len(pick)