Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- leaf/final/episode_000318_wrist_image.png +3 -0
- leaf/final/episode_000455_wrist_image.png +3 -0
- leaf/final/episode_000636_image.png +3 -0
- leaf/final/episode_000715_image.png +3 -0
- leaf/final/episode_000916_image.png +3 -0
- leaf/final/episode_000935_image.png +3 -0
- leaf/final/episode_000994_image.png +3 -0
- leaf/final/episode_001592.npz +3 -0
- leaf/final/episode_001702_image.png +3 -0
- leaf/final/episode_001729_wrist_image.png +3 -0
- leaf/final/episode_001990.npz +3 -0
- leaf/final/episode_002254.npz +3 -0
- leaf/final/episode_002278_image.png +3 -0
- leaf/final/episode_002635_wrist_image.png +3 -0
- leaf/final/episode_002661_wrist_image.png +3 -0
- leaf/final/episode_002747.npz +3 -0
- leaf/final/episode_002799_wrist_image.png +3 -0
- leaf/final/episode_003069.npz +3 -0
- leaf/final/episode_003240_wrist_image.png +3 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/check_setup.py +175 -0
- 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 +15 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/harnesses/base.py +364 -0
- 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 +15 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/l1_yaw.py +439 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/l4_fit.py +574 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/l5_slippery_lift.py +262 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/l6_swap.py +466 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/lh_drawer_cabinet.py +1273 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/lh_fence.py +1030 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/lh_parts_cart.py +253 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/lh_tidy_stack.py +1260 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/audit_subagent.py +130 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/start_real_session.sh +30 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/MANIFEST.md +12 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/evaluation_evidence/inactive_arm_review_20261115.json +26 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/agent/camera.py +100 -0
- 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 +15 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/lh_tray_delivery.py +883 -0
- leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/agent/harness.py +300 -0
- leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/l4_nest.py +644 -0
- leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/l5_loaded_beam.py +598 -0
- leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/l5_tablecloth_pull.py +392 -0
- leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/l6_sequence.py +513 -0
- leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/lh_split_calibration.py +142 -0
- leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/batches.json +9 -0
- leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/rejected.json +1 -0
- leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/agent/backends/base.py +82 -0
- leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/agent/backends/chat_completions.py +150 -0
- leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/fakeapi.py +188 -0
- 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 +15 -0
leaf/final/episode_000318_wrist_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_000455_wrist_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_000636_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_000715_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_000916_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_000935_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_000994_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_001592.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:abf08e591c54ea64b5b88b52e38a6729f48381a014139b65c3b448187aabc996
|
| 3 |
+
size 3838
|
leaf/final/episode_001702_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_001729_wrist_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_001990.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2e8f25fce6bdec27c9dfbc6c522e9dcb5dda8d2bb7cc0e0843f9e1ff6370810d
|
| 3 |
+
size 3750
|
leaf/final/episode_002254.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6f8d33386b60cc3e4ccd768bdff48e79f6115d8f8afa0d987e417fa855fbeb43
|
| 3 |
+
size 3886
|
leaf/final/episode_002278_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_002635_wrist_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_002661_wrist_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_002747.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:64cdad6bd6be55b37e2bd07e157be9e1d504c38e38e218f54c61131a0bd141b6
|
| 3 |
+
size 4150
|
leaf/final/episode_002799_wrist_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_003069.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1a7f5dbd07bcecfa4e077908ddde7ce2f2a0684006eafd84eeabf2ef44cb8e5d
|
| 3 |
+
size 3630
|
leaf/final/episode_003240_wrist_image.png
ADDED
|
Git LFS Details
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/check_setup.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
|
| 3 |
+
python scripts/check_setup.py # Python packages, LIBERO config, simulation + rendering, the agent's shell jail
|
| 4 |
+
python scripts/check_setup.py --api # ... plus one tiny text-only request to the model endpoint (OPENAI_API_KEY /
|
| 5 |
+
# OPENAI_BASE_URL from the environment or from .env); costs a few tokens
|
| 6 |
+
python scripts/check_setup.py --api --model gpt-5.5 --skip-sim --skip-jail
|
| 7 |
+
|
| 8 |
+
Exit code 0 when every check that ran passed.
|
| 9 |
+
"""
|
| 10 |
+
import argparse
|
| 11 |
+
import os
|
| 12 |
+
import subprocess
|
| 13 |
+
import sys
|
| 14 |
+
import tempfile
|
| 15 |
+
import time
|
| 16 |
+
|
| 17 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 18 |
+
sys.path.insert(0, ROOT)
|
| 19 |
+
JAIL = "/opt/lffjail/jail_inner.sh" # same path as lffbench/agent/robot_server.py and scripts/gpt_player.py
|
| 20 |
+
|
| 21 |
+
results = []
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def report(name, ok, detail=""):
|
| 25 |
+
results.append(ok)
|
| 26 |
+
print(f"[{'ok' if ok else 'FAIL'}] {name}" + (f": {detail}" if detail else ""), flush=True)
|
| 27 |
+
return ok
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def check_packages():
|
| 31 |
+
report("python 3.10", sys.version_info[:2] == (3, 10), sys.version.split()[0])
|
| 32 |
+
from lffbench.agent.backends.base import import_openai
|
| 33 |
+
for mod in ("numpy", "mujoco", "robosuite", "libero.libero", "openai", "imageio", "cv2"):
|
| 34 |
+
try:
|
| 35 |
+
m = import_openai() if mod == "openai" else __import__(mod, fromlist=["_"])
|
| 36 |
+
report(f"import {mod}", True, getattr(m, "__version__", ""))
|
| 37 |
+
except Exception as e: # noqa: BLE001
|
| 38 |
+
report(f"import {mod}", False, f"{type(e).__name__}: {e}")
|
| 39 |
+
cfg = os.path.join(os.environ.get("LIBERO_CONFIG_PATH", ""), "config.yaml")
|
| 40 |
+
if report("LIBERO config", os.path.isfile(cfg), cfg + ("" if os.path.isfile(cfg) else " missing: run setup/install.sh")):
|
| 41 |
+
import yaml
|
| 42 |
+
assets = yaml.safe_load(open(cfg)).get("assets", "")
|
| 43 |
+
report("LIBERO assets", os.path.isdir(assets), assets)
|
| 44 |
+
report("rendering backend", bool(os.environ.get("MUJOCO_GL")), f"MUJOCO_GL={os.environ.get('MUJOCO_GL')}")
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def check_sim(task_name, seed):
|
| 48 |
+
import importlib
|
| 49 |
+
import pkgutil
|
| 50 |
+
|
| 51 |
+
try:
|
| 52 |
+
import lffbench.tasks as task_pkg
|
| 53 |
+
from lffbench.task_base import TASKS
|
| 54 |
+
except Exception as e: # noqa: BLE001
|
| 55 |
+
report("import lffbench", False, f"{type(e).__name__}: {e}")
|
| 56 |
+
return
|
| 57 |
+
try:
|
| 58 |
+
for m in pkgutil.iter_modules(task_pkg.__path__):
|
| 59 |
+
importlib.import_module(f"lffbench.tasks.{m.name}")
|
| 60 |
+
except Exception as e: # noqa: BLE001
|
| 61 |
+
report("import tasks", False, f"{type(e).__name__}: {e}")
|
| 62 |
+
return
|
| 63 |
+
report("tasks registered", len(TASKS) >= 20, f"{len(TASKS)} tasks")
|
| 64 |
+
t0 = time.time()
|
| 65 |
+
try:
|
| 66 |
+
task = TASKS[task_name]()
|
| 67 |
+
inst = task.sample_instance(seed)
|
| 68 |
+
task.reset_instance(inst)
|
| 69 |
+
img = task.snapshot()
|
| 70 |
+
out = task.outcome(inst)
|
| 71 |
+
except Exception as e: # noqa: BLE001
|
| 72 |
+
report(f"simulate + render {task_name}", False, f"{type(e).__name__}: {e}")
|
| 73 |
+
return
|
| 74 |
+
ok = img.ndim == 3 and img.shape[2] == 3 and float(img.std()) > 1.0
|
| 75 |
+
report(f"simulate + render {task_name}", ok,
|
| 76 |
+
f"image {img.shape}, pixel std {img.std():.1f}, untouched scene success={out['success']}, {time.time() - t0:.1f} s")
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def check_jail():
|
| 80 |
+
if not report("jail installed", os.access(JAIL, os.X_OK) and os.path.isdir("/opt/lffjail/py"),
|
| 81 |
+
JAIL if os.path.exists(JAIL) else "missing: sudo bash jail/setup_jail.sh"):
|
| 82 |
+
return
|
| 83 |
+
probe = r'''
|
| 84 |
+
echo "pwd=$(pwd)"
|
| 85 |
+
python3 -c "import numpy, scipy, PIL, cv2; print('py=ok')" 2>&1 | tail -1
|
| 86 |
+
echo "mnt_entries=$(ls -A /mnt 2>/dev/null | wc -l) home_entries=$(ls -A /home 2>/dev/null | wc -l)"
|
| 87 |
+
python3 -c "
|
| 88 |
+
import socket
|
| 89 |
+
s = socket.socket(); s.settimeout(3)
|
| 90 |
+
try:
|
| 91 |
+
s.connect(('1.1.1.1', 443)); print('net=open')
|
| 92 |
+
except OSError as e:
|
| 93 |
+
print('net=blocked')
|
| 94 |
+
"
|
| 95 |
+
touch made_in_jail && echo "write=ok"
|
| 96 |
+
'''
|
| 97 |
+
with tempfile.TemporaryDirectory(prefix="lffjail_check_") as ws:
|
| 98 |
+
argv = ["unshare", "--user", "--map-root-user", "--mount", "--net", "--", JAIL, ws,
|
| 99 |
+
"timeout", "-k", "5", "60", "bash", "-c", probe]
|
| 100 |
+
r = subprocess.run(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=120)
|
| 101 |
+
kv = dict(l.split("=", 1) for l in r.stdout.split() if "=" in l)
|
| 102 |
+
if r.returncode != 0 and not kv:
|
| 103 |
+
hint = ""
|
| 104 |
+
if "Operation not permitted" in r.stdout or "uid_map" in r.stdout:
|
| 105 |
+
hint = (" | unprivileged user namespaces are blocked; on Ubuntu >= 23.10: "
|
| 106 |
+
"sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0")
|
| 107 |
+
report("jail runs", False, r.stdout.strip()[-400:] + hint)
|
| 108 |
+
return
|
| 109 |
+
report("jail runs", True, f"workdir {kv.get('pwd')}")
|
| 110 |
+
report("jail python (numpy/scipy/Pillow/OpenCV)", kv.get("py") == "ok", kv.get("py", r.stdout[-300:]))
|
| 111 |
+
report("jail hides host data", kv.get("mnt_entries") == "0" and kv.get("home_entries") == "0",
|
| 112 |
+
f"/mnt entries {kv.get('mnt_entries')}, /home entries {kv.get('home_entries')}")
|
| 113 |
+
report("jail has no network", kv.get("net") == "blocked", kv.get("net", "?"))
|
| 114 |
+
report("jail writes the workspace", kv.get("write") == "ok" and os.path.exists(os.path.join(ws, "made_in_jail")))
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def load_env_file():
|
| 118 |
+
path = os.environ.get("LFF_ENV_FILE") or os.path.join(ROOT, ".env")
|
| 119 |
+
if not os.path.isfile(path):
|
| 120 |
+
return None
|
| 121 |
+
for line in open(path):
|
| 122 |
+
line = line.strip()
|
| 123 |
+
if line and not line.startswith("#") and "=" in line:
|
| 124 |
+
k, v = line.split("=", 1)
|
| 125 |
+
os.environ.setdefault(k.removeprefix("export ").strip(), v.strip().strip("'\""))
|
| 126 |
+
return path
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def check_api(model, effort):
|
| 130 |
+
src = load_env_file()
|
| 131 |
+
if not os.environ.get("SSL_CERT_FILE") and os.path.exists("/etc/ssl/certs/ca-certificates.crt"):
|
| 132 |
+
os.environ["SSL_CERT_FILE"] = "/etc/ssl/certs/ca-certificates.crt" # same as scripts/gpt_player.py
|
| 133 |
+
if not report("OPENAI_API_KEY set", bool(os.environ.get("OPENAI_API_KEY")),
|
| 134 |
+
f"from {src}" if src else "from the environment (no .env)"):
|
| 135 |
+
return
|
| 136 |
+
base = os.environ.get("OPENAI_BASE_URL") or "https://api.openai.com/v1 (default)"
|
| 137 |
+
from lffbench.agent.backends.openai_responses import OpenAIResponsesBackend
|
| 138 |
+
t0 = time.time()
|
| 139 |
+
try:
|
| 140 |
+
client = OpenAIResponsesBackend(model=model, reasoning_effort=effort, timeout=120.0, max_retries=1).client()
|
| 141 |
+
resp = client.responses.create(model=model, instructions="Reply with exactly the word OK.", input="ping",
|
| 142 |
+
reasoning=dict(effort=effort), store=False, max_output_tokens=256)
|
| 143 |
+
text = (resp.output_text or "").strip()
|
| 144 |
+
u = resp.usage
|
| 145 |
+
report(f"API {model} @ {base}", bool(text), f"reply {text[:40]!r}, {time.time() - t0:.1f} s, "
|
| 146 |
+
f"tokens in {u.input_tokens} / out {u.output_tokens}")
|
| 147 |
+
except Exception as e: # noqa: BLE001
|
| 148 |
+
report(f"API {model} @ {base}", False, f"{type(e).__name__}: {str(e)[:300]}")
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def main():
|
| 152 |
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 153 |
+
ap.add_argument("--api", action="store_true", help="also send one tiny request to the model endpoint")
|
| 154 |
+
ap.add_argument("--model", default="gpt-6-astra")
|
| 155 |
+
ap.add_argument("--effort", default="low")
|
| 156 |
+
ap.add_argument("--task", default="l5_slide_to_target")
|
| 157 |
+
ap.add_argument("--seed", type=int, default=1000)
|
| 158 |
+
ap.add_argument("--skip-sim", action="store_true")
|
| 159 |
+
ap.add_argument("--skip-jail", action="store_true")
|
| 160 |
+
a = ap.parse_args()
|
| 161 |
+
os.environ.setdefault("OMP_NUM_THREADS", "1")
|
| 162 |
+
check_packages()
|
| 163 |
+
if not a.skip_sim:
|
| 164 |
+
check_sim(a.task, a.seed)
|
| 165 |
+
if not a.skip_jail:
|
| 166 |
+
check_jail()
|
| 167 |
+
if a.api:
|
| 168 |
+
check_api(a.model, a.effort)
|
| 169 |
+
n_bad = results.count(False)
|
| 170 |
+
print(f"\n{len(results) - n_bad}/{len(results)} checks passed")
|
| 171 |
+
sys.exit(1 if n_bad else 0)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
if __name__ == "__main__":
|
| 175 |
+
main()
|
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
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "claude_code|2.1.267|0399c793ff571d59|claude-sonnet-5-5|high",
|
| 3 |
+
"fingerprint_sha256": "fbf323682711d7010fa8cd2c9036b1082dab2a6cd4cf80983be1adf64e037d7c",
|
| 4 |
+
"written": "2026-10-20 02:16:00",
|
| 5 |
+
"summary": {
|
| 6 |
+
"system_chars": 182,
|
| 7 |
+
"tools": [
|
| 8 |
+
"mcp__lff__robot",
|
| 9 |
+
"mcp__lff__shell",
|
| 10 |
+
"mcp__lff__view_images"
|
| 11 |
+
],
|
| 12 |
+
"effort_in_request": "high",
|
| 13 |
+
"model_in_request": "claude-sonnet-5-5"
|
| 14 |
+
}
|
| 15 |
+
}
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/harnesses/base.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Harness adapter interface (docs/15 §3).
|
| 2 |
+
|
| 3 |
+
An adapter runs one episode (one robot_server session) with one agent harness and leaves behind, in the run's log
|
| 4 |
+
dir: harness.json (what was launched), trajectory.jsonl (unified trajectory), harness_audit.json (checks + violations).
|
| 5 |
+
Budgets, automatic finish and attempt switching are NOT the adapter's business: robot_server and the MCP server /
|
| 6 |
+
reference driver enforce them identically for every harness.
|
| 7 |
+
|
| 8 |
+
name stable harness name (the "harness" column of a table)
|
| 9 |
+
capabilities CapabilityDecl: every item of REQUIRED and FORBIDDEN must be declared, with its evidence source;
|
| 10 |
+
a missing item makes the class definition fail (so the import fails)
|
| 11 |
+
version() the actual installed version (probed before launch)
|
| 12 |
+
prepare(ep, first_message) -> LaunchSpec: one-time dirs, configs, argv / env
|
| 13 |
+
launch(spec) fail-closed preflight, then start the process (env exactly the whitelist) -> RunHandle
|
| 14 |
+
collect(h) native event stream -> trajectory.jsonl (ATIF-like), usage, exit reason
|
| 15 |
+
audit(h) tool list, preset prompt, memory, state left behind, violations
|
| 16 |
+
"""
|
| 17 |
+
import dataclasses
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
import secrets
|
| 21 |
+
import shutil
|
| 22 |
+
import signal
|
| 23 |
+
import subprocess
|
| 24 |
+
import time
|
| 25 |
+
|
| 26 |
+
from . import contract as C
|
| 27 |
+
|
| 28 |
+
EVIDENCE = ("launch", "stream", "server", "probe", "preflight")
|
| 29 |
+
|
| 30 |
+
REQUIRED = {
|
| 31 |
+
"only_benchmark_tools": "the model can call exactly robot / shell / view_images (ours) and nothing else of use",
|
| 32 |
+
"images_reach_model": "view_images returns the image bytes to the model unchanged",
|
| 33 |
+
"non_persistent_session": "nothing of the session is written to disk for later runs",
|
| 34 |
+
"pinned_version": "the harness version (and binary hash) is recorded and pinned",
|
| 35 |
+
"machine_readable_events": "a machine-readable event stream of the whole run",
|
| 36 |
+
"tool_calls_logged": "every tool call is logged (harness stream + MCP / driver transcript + events.jsonl)",
|
| 37 |
+
"model_and_effort": "model and reasoning effort can be set and are visible in the request",
|
| 38 |
+
}
|
| 39 |
+
FORBIDDEN = {
|
| 40 |
+
"persistent_memory": "harness memory across runs (C4: auto-memory, CLAUDE.md / AGENTS.md, memories db)",
|
| 41 |
+
"instruction_file_injection": "instruction files picked up from the work / config / home dir",
|
| 42 |
+
"web_access": "web search / fetch",
|
| 43 |
+
"host_file_read": "reading host files outside the episode workspace",
|
| 44 |
+
"builtin_shell": "a shell of the harness itself (outside our jailed shell tool)",
|
| 45 |
+
"subagent_delegation": "spawning sub-agents",
|
| 46 |
+
"background_execution": "background tasks that outlive a tool call",
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@dataclasses.dataclass(frozen=True)
|
| 51 |
+
class Cap:
|
| 52 |
+
status: str # REQUIRED items: "yes" | "partial" | "no"; FORBIDDEN items: "absent" | "present" | "partial"
|
| 53 |
+
evidence: str # one of EVIDENCE
|
| 54 |
+
note: str = ""
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
PROXY_KEYS = ("HTTPS_PROXY", "HTTP_PROXY", "https_proxy", "http_proxy")
|
| 58 |
+
NO_PROXY_KEYS = ("NO_PROXY", "no_proxy")
|
| 59 |
+
NO_PROXY_LOCAL = "127.0.0.1,localhost,::1"
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def proxy_env(environ=None):
|
| 63 |
+
"""The calling environment's HTTP(S) proxy, passed to a native harness so it can reach the model API on machines
|
| 64 |
+
that only get out through a proxy. NO_PROXY is loopback only (the preflight's fake API), never the host's list.
|
| 65 |
+
Not part of config_sha256 (machine plumbing, not harness configuration)."""
|
| 66 |
+
environ = os.environ if environ is None else environ
|
| 67 |
+
e = {k: environ[k] for k in PROXY_KEYS if environ.get(k)}
|
| 68 |
+
if e:
|
| 69 |
+
e.update({k: NO_PROXY_LOCAL for k in NO_PROXY_KEYS})
|
| 70 |
+
return e
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class CapabilityError(TypeError):
|
| 74 |
+
pass
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def check_capabilities(name, caps):
|
| 78 |
+
if not isinstance(caps, dict):
|
| 79 |
+
raise CapabilityError(f"{name}: capabilities must be a dict")
|
| 80 |
+
missing = [k for k in list(REQUIRED) + list(FORBIDDEN) if k not in caps]
|
| 81 |
+
extra = [k for k in caps if k not in REQUIRED and k not in FORBIDDEN]
|
| 82 |
+
if missing or extra:
|
| 83 |
+
raise CapabilityError(f"{name}: capability declaration incomplete: missing {missing}, unknown {extra}")
|
| 84 |
+
for k, c in caps.items():
|
| 85 |
+
if not isinstance(c, Cap) or c.evidence not in EVIDENCE:
|
| 86 |
+
raise CapabilityError(f"{name}: capability {k!r} needs a Cap(status, evidence in {EVIDENCE})")
|
| 87 |
+
ok = ("yes", "partial", "no") if k in REQUIRED else ("absent", "present", "partial")
|
| 88 |
+
if c.status not in ok:
|
| 89 |
+
raise CapabilityError(f"{name}: capability {k!r} status must be one of {ok}")
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class HarnessRefused(RuntimeError):
|
| 93 |
+
"""Fail-closed: the launch preflight found a tool list / preset prompt that is not the pinned one."""
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@dataclasses.dataclass
|
| 97 |
+
class EpisodeSpec:
|
| 98 |
+
session_path: str
|
| 99 |
+
log_dir: str
|
| 100 |
+
sandbox: str
|
| 101 |
+
port: int
|
| 102 |
+
token: str
|
| 103 |
+
max_tool_calls: int
|
| 104 |
+
model: str
|
| 105 |
+
effort: str
|
| 106 |
+
provider: str = ""
|
| 107 |
+
task: str = ""
|
| 108 |
+
seed: int = 0
|
| 109 |
+
extra: dict = dataclasses.field(default_factory=dict)
|
| 110 |
+
|
| 111 |
+
@classmethod
|
| 112 |
+
def from_session(cls, session_path, model, effort, provider="", **extra):
|
| 113 |
+
session_path = os.path.abspath(session_path)
|
| 114 |
+
log_dir = os.path.dirname(session_path)
|
| 115 |
+
sess = json.load(open(session_path))
|
| 116 |
+
iface = json.load(open(os.path.join(log_dir, "agent_iface.json")))
|
| 117 |
+
st = C.session_start(log_dir)
|
| 118 |
+
return cls(session_path=session_path, log_dir=log_dir, sandbox=sess["sandbox"], port=int(sess["port"]),
|
| 119 |
+
token=iface["token"], max_tool_calls=int(iface["max_tool_calls"]), model=model, effort=effort,
|
| 120 |
+
provider=provider, task=st["task"], seed=int(st["seed"]), extra=extra)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@dataclasses.dataclass
|
| 124 |
+
class LaunchSpec:
|
| 125 |
+
argv: list # full argv (the first message may be one element)
|
| 126 |
+
env: dict # the complete environment of the harness process (nothing else is inherited)
|
| 127 |
+
cwd: str
|
| 128 |
+
run_dir: str = "" # one-time dir tree, removed after audit
|
| 129 |
+
state_dirs: dict = dataclasses.field(default_factory=dict) # name -> path (home, config, ...)
|
| 130 |
+
first_message: str = ""
|
| 131 |
+
config_files: dict = dataclasses.field(default_factory=dict) # name -> path of files the adapter wrote
|
| 132 |
+
stdout_path: str = ""
|
| 133 |
+
stderr_path: str = ""
|
| 134 |
+
redact_argv: dict = dataclasses.field(default_factory=dict) # argv index -> replacement for the log
|
| 135 |
+
preflight: dict = dataclasses.field(default_factory=dict)
|
| 136 |
+
timeout_s: float = 10800
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@dataclasses.dataclass
|
| 140 |
+
class RunHandle:
|
| 141 |
+
spec: LaunchSpec
|
| 142 |
+
ep: EpisodeSpec
|
| 143 |
+
proc: object = None
|
| 144 |
+
pid: int = 0
|
| 145 |
+
t_start: float = 0.0
|
| 146 |
+
t_end: float = 0.0
|
| 147 |
+
exit_code: int = None
|
| 148 |
+
exit_reason: str = ""
|
| 149 |
+
env_observed_keys: list = None # read from /proc/<pid>/environ right after the start
|
| 150 |
+
info: dict = dataclasses.field(default_factory=dict)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def env_keys_of(pid):
|
| 154 |
+
try:
|
| 155 |
+
raw = open(f"/proc/{pid}/environ", "rb").read()
|
| 156 |
+
except OSError:
|
| 157 |
+
return None
|
| 158 |
+
return sorted({kv.split(b"=", 1)[0].decode("utf-8", "replace") for kv in raw.split(b"\0") if kv})
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def new_run_dir(root="/tmp/lffrun"):
|
| 162 |
+
"""/tmp/lffrun/<12 hex>: the opaque work dir (its path is shown to the model by some harnesses)."""
|
| 163 |
+
os.makedirs(root, exist_ok=True)
|
| 164 |
+
while True:
|
| 165 |
+
d = os.path.join(root, secrets.token_hex(6))
|
| 166 |
+
try:
|
| 167 |
+
os.mkdir(d, 0o700)
|
| 168 |
+
return d
|
| 169 |
+
except FileExistsError:
|
| 170 |
+
continue
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def binary_info(path):
|
| 174 |
+
real = os.path.realpath(path)
|
| 175 |
+
return dict(path=path, realpath=real, sha256=C.sha256_file(real) if os.path.exists(real) else None)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class HarnessAdapter:
|
| 179 |
+
name = None
|
| 180 |
+
capabilities = None
|
| 181 |
+
uses_mcp = False
|
| 182 |
+
uses_gateway = False # harness_run starts the episode's tool gateway (scripts/tool_gateway.py) for
|
| 183 |
+
# this adapter: MCP adapters through the MCP server, framework adapters
|
| 184 |
+
# (RPent, ...) through lffbench_client with LFF_GATEWAY_URL / LFF_GATEWAY_TOKEN
|
| 185 |
+
clean_dirs = () # keys of spec.state_dirs that must be empty at launch
|
| 186 |
+
clean_allowed = {} # key of spec.state_dirs -> file names the adapter itself put there (e.g. auth.json)
|
| 187 |
+
ancestor_files = () # instruction files that must not exist in the work dir or any ancestor
|
| 188 |
+
unsafe_skip_clean_check = False # tests/harness_selfcheck only (probing what the harness would read)
|
| 189 |
+
jail = None # lffbench/harnesses/jail.HarnessJail when the adapter runs jailed (docs/15 §3.4)
|
| 190 |
+
can_resume = False # resume(): the CLI can continue its session with one more user message
|
| 191 |
+
|
| 192 |
+
def clean_state_problems(self, spec):
|
| 193 |
+
"""Fail-closed: the work dir and the one-time dirs must be empty, and no instruction file may sit in an
|
| 194 |
+
ancestor of the work dir (harnesses walk up the tree looking for CLAUDE.md / AGENTS.md)."""
|
| 195 |
+
p = []
|
| 196 |
+
if spec.cwd and os.path.isdir(spec.cwd) and os.listdir(spec.cwd):
|
| 197 |
+
p.append(f"work dir not empty: {sorted(os.listdir(spec.cwd))[:5]}")
|
| 198 |
+
for k in self.clean_dirs:
|
| 199 |
+
d = spec.state_dirs.get(k)
|
| 200 |
+
left = [n for n in os.listdir(d) if n not in self.clean_allowed.get(k, ())] if d and os.path.isdir(d) else []
|
| 201 |
+
if left:
|
| 202 |
+
p.append(f"{k} dir not empty: {sorted(left)[:5]}")
|
| 203 |
+
d = spec.cwd
|
| 204 |
+
while d and d != "/":
|
| 205 |
+
d = os.path.dirname(d)
|
| 206 |
+
for f in self.ancestor_files:
|
| 207 |
+
if os.path.exists(os.path.join(d, f)):
|
| 208 |
+
p.append(f"instruction file in an ancestor of the work dir: {os.path.join(d, f)}")
|
| 209 |
+
return p
|
| 210 |
+
|
| 211 |
+
def __init_subclass__(cls, **kw):
|
| 212 |
+
super().__init_subclass__(**kw)
|
| 213 |
+
if cls.name is None:
|
| 214 |
+
raise CapabilityError(f"{cls.__name__}: no name")
|
| 215 |
+
check_capabilities(cls.name, cls.capabilities)
|
| 216 |
+
|
| 217 |
+
# -------------------------------------------------------------------------------------------- interface
|
| 218 |
+
def version(self):
|
| 219 |
+
raise NotImplementedError
|
| 220 |
+
|
| 221 |
+
def prepare(self, ep, first_message):
|
| 222 |
+
raise NotImplementedError
|
| 223 |
+
|
| 224 |
+
def preflight(self, spec, ep):
|
| 225 |
+
"""Fail-closed launch check; returns a dict for harness.json, raises HarnessRefused."""
|
| 226 |
+
return dict(skipped=True)
|
| 227 |
+
|
| 228 |
+
def collect(self, h):
|
| 229 |
+
raise NotImplementedError
|
| 230 |
+
|
| 231 |
+
def audit(self, h):
|
| 232 |
+
raise NotImplementedError
|
| 233 |
+
|
| 234 |
+
# -------------------------------------------------------------------------------------------- shared
|
| 235 |
+
def mcp_server_command(self, python, script, args):
|
| 236 |
+
"""(command, args) of the MCP server entry in the harness config: our server, or, jailed, the relay to it."""
|
| 237 |
+
if self.jail is not None:
|
| 238 |
+
return self.jail.mcp_command([python, script] + list(args), env={"PATH": "/usr/bin:/bin"})
|
| 239 |
+
return python, [script] + list(args)
|
| 240 |
+
|
| 241 |
+
def jailed_argv(self, argv, env, cwd, dirs):
|
| 242 |
+
"""argv as started: unchanged, or wrapped into the jail with `dirs` (one-time dirs) mounted back."""
|
| 243 |
+
return self.jail.wrap(argv, env, cwd, dirs) if self.jail is not None else list(argv)
|
| 244 |
+
|
| 245 |
+
def jail_info(self):
|
| 246 |
+
return self.jail.info() if self.jail is not None else dict(enabled=False)
|
| 247 |
+
|
| 248 |
+
def auth_info(self):
|
| 249 |
+
"""How the harness authenticates to the model API (for harness.json; never a secret)."""
|
| 250 |
+
return dict(mode="api_env", keys=sorted(getattr(self, "api_env", {}) or {}))
|
| 251 |
+
|
| 252 |
+
def launch(self, spec, ep, skip_preflight=False):
|
| 253 |
+
if not self.unsafe_skip_clean_check:
|
| 254 |
+
probs = self.clean_state_problems(spec)
|
| 255 |
+
if probs:
|
| 256 |
+
spec.preflight = dict(problems=probs)
|
| 257 |
+
raise HarnessRefused("clean-state check: " + "; ".join(probs))
|
| 258 |
+
spec.preflight = dict(skipped=True, reason="skip_preflight") if skip_preflight else self.preflight(spec, ep)
|
| 259 |
+
out = open(spec.stdout_path, "wb")
|
| 260 |
+
err = open(spec.stderr_path, "wb")
|
| 261 |
+
h = RunHandle(spec=spec, ep=ep, t_start=time.time())
|
| 262 |
+
argv = self.jailed_argv(spec.argv, spec.env, spec.cwd, list(spec.state_dirs.values()) + [spec.run_dir])
|
| 263 |
+
h.proc = subprocess.Popen(argv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=out,
|
| 264 |
+
stderr=err, start_new_session=True)
|
| 265 |
+
h.pid = h.proc.pid
|
| 266 |
+
for _ in range(20): # the exec has happened once /proc/<pid>/environ differs from ours
|
| 267 |
+
keys = env_keys_of(h.pid)
|
| 268 |
+
if keys is not None and set(keys) == set(spec.env):
|
| 269 |
+
break
|
| 270 |
+
time.sleep(0.05)
|
| 271 |
+
h.env_observed_keys = env_keys_of(h.pid)
|
| 272 |
+
return h
|
| 273 |
+
|
| 274 |
+
def resume_argv(self, h, message):
|
| 275 |
+
"""argv that continues the run's session with one more user message (adapters with can_resume)."""
|
| 276 |
+
raise NotImplementedError
|
| 277 |
+
|
| 278 |
+
def resume(self, h, message):
|
| 279 |
+
"""Continue the run's session with one more user message, after the CLI exited before the episode was over
|
| 280 |
+
(scripts/harness_run.py sends the reference driver's nudge). Same env, work dir and one-time dirs; the output
|
| 281 |
+
is appended to the same stdout / stderr files."""
|
| 282 |
+
spec = h.spec
|
| 283 |
+
argv = self.resume_argv(h, message)
|
| 284 |
+
out, err = open(spec.stdout_path, "ab"), open(spec.stderr_path, "ab")
|
| 285 |
+
jargv = self.jailed_argv(argv, spec.env, spec.cwd, list(spec.state_dirs.values()) + [spec.run_dir])
|
| 286 |
+
h.proc = subprocess.Popen(jargv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=out,
|
| 287 |
+
stderr=err, start_new_session=True)
|
| 288 |
+
h.pid, h.exit_code, h.exit_reason = h.proc.pid, None, ""
|
| 289 |
+
keys = None
|
| 290 |
+
for _ in range(20):
|
| 291 |
+
keys = env_keys_of(h.pid)
|
| 292 |
+
if keys is not None and set(keys) == set(spec.env):
|
| 293 |
+
break
|
| 294 |
+
time.sleep(0.05)
|
| 295 |
+
h.info.setdefault("resumes", []).append(dict(t=time.time(), pid=h.pid, message=message,
|
| 296 |
+
argv=[("<message>" if x == message else x) for x in argv],
|
| 297 |
+
env_observed_keys=keys))
|
| 298 |
+
return h
|
| 299 |
+
|
| 300 |
+
def wait(self, h, timeout=None):
|
| 301 |
+
try:
|
| 302 |
+
h.exit_code = h.proc.wait(timeout=timeout or h.spec.timeout_s)
|
| 303 |
+
h.exit_reason = "exited" if h.exit_code == 0 else f"exit code {h.exit_code}"
|
| 304 |
+
except subprocess.TimeoutExpired:
|
| 305 |
+
self.kill(h)
|
| 306 |
+
h.exit_reason = "timeout"
|
| 307 |
+
h.t_end = time.time()
|
| 308 |
+
return h
|
| 309 |
+
|
| 310 |
+
@staticmethod
|
| 311 |
+
def kill(h):
|
| 312 |
+
try:
|
| 313 |
+
os.killpg(h.proc.pid, signal.SIGTERM)
|
| 314 |
+
h.exit_code = h.proc.wait(timeout=20)
|
| 315 |
+
except ProcessLookupError:
|
| 316 |
+
pass
|
| 317 |
+
except subprocess.TimeoutExpired:
|
| 318 |
+
os.killpg(h.proc.pid, signal.SIGKILL)
|
| 319 |
+
h.exit_code = h.proc.wait()
|
| 320 |
+
|
| 321 |
+
def logged_argv(self, spec):
|
| 322 |
+
return [spec.redact_argv.get(i, a) for i, a in enumerate(spec.argv)]
|
| 323 |
+
|
| 324 |
+
def cleanup(self, spec):
|
| 325 |
+
if spec.run_dir and spec.run_dir.startswith(("/tmp/lffrun/", "/tmp/lffstate/")) and os.path.isdir(spec.run_dir):
|
| 326 |
+
shutil.rmtree(spec.run_dir, ignore_errors=True)
|
| 327 |
+
for d in spec.state_dirs.values():
|
| 328 |
+
if d.startswith(("/tmp/lffrun/", "/tmp/lffstate/")) and os.path.isdir(d):
|
| 329 |
+
shutil.rmtree(d, ignore_errors=True)
|
| 330 |
+
if self.jail is not None:
|
| 331 |
+
self.jail.close()
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def gateway_env(log_dir):
|
| 335 |
+
"""{LFF_GATEWAY_URL, LFF_GATEWAY_TOKEN} of the episode's tool gateway, for a framework adapter (uses_gateway) whose
|
| 336 |
+
process talks to it through lffbench_client (Session.from_env). harness_run.py starts the gateway right before
|
| 337 |
+
launch, so call this in the adapter's launch() and add it to spec.env before the process starts. The token is the
|
| 338 |
+
gateway's, never robot_server's."""
|
| 339 |
+
d = json.load(open(os.path.join(log_dir, "gateway.json")))
|
| 340 |
+
return {"LFF_GATEWAY_URL": d["url"], "LFF_GATEWAY_TOKEN": d["token"]}
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def snapshot_tree(root):
|
| 344 |
+
"""Relative paths of all files under root (to list what a harness left behind)."""
|
| 345 |
+
out = []
|
| 346 |
+
for dp, dn, fn in os.walk(root):
|
| 347 |
+
for f in fn:
|
| 348 |
+
out.append(os.path.relpath(os.path.join(dp, f), root))
|
| 349 |
+
return sorted(out)
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def first_message_text(readme, status_json):
|
| 353 |
+
"""What a native harness gets as its first user message: the reference driver's instructions (preamble + README,
|
| 354 |
+
byte-identical) followed by its first user turn (the status report). The reference driver sends the same two
|
| 355 |
+
strings as system prompt and first user message; native harnesses keep their own system prompt."""
|
| 356 |
+
from .contract import tool_schemas
|
| 357 |
+
_, preamble = tool_schemas()
|
| 358 |
+
return preamble + readme + "\n\n" + "Begin. Current status (robot command `status`):\n" + status_json
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def reference_instructions(readme):
|
| 362 |
+
from .contract import tool_schemas
|
| 363 |
+
_, preamble = tool_schemas()
|
| 364 |
+
return preamble + readme
|
leaf/release/source_packages/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
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "dsh|0.2.1-rc.5|aa65546cc1f51674|deepseek-v4.1-flash|high",
|
| 3 |
+
"fingerprint_sha256": "080d6300858cdfc671e135073ec7f693bcf424eace689ffc480903b40f0e0894",
|
| 4 |
+
"written": "2026-10-30 16:02:13",
|
| 5 |
+
"summary": {
|
| 6 |
+
"system_chars": 114,
|
| 7 |
+
"tools": [
|
| 8 |
+
"mcp__lff__robot",
|
| 9 |
+
"mcp__lff__shell",
|
| 10 |
+
"mcp__lff__view_images"
|
| 11 |
+
],
|
| 12 |
+
"effort_in_request": "high",
|
| 13 |
+
"model_in_request": "deepseek-v4.1-flash"
|
| 14 |
+
}
|
| 15 |
+
}
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/l1_ya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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L1-C yaw_bias: put a long bar into a narrow holder, with an arm whose wrist rotation is miscalibrated.
|
| 2 |
+
|
| 3 |
+
Category system_identification (level L1, action fine-tuning): the method (top-down pick across the bar, carry,
|
| 4 |
+
line the bar up with the holder, release just above the holder) and the scene understanding are right; only the
|
| 5 |
+
robot's own wrist rotation is off.
|
| 6 |
+
|
| 7 |
+
Hidden variable: a fixed wrist-yaw calibration offset beta, |beta| ~ U[15, 30] deg with a random sign: every
|
| 8 |
+
commanded gripper yaw theta is executed as theta + beta. The robot reports its yaw in its own (miscalibrated) frame,
|
| 9 |
+
so the agent's proprioception says "yaw = theta" (implemented by shifting the robot's notion of yaw 0, `Skills.R0`,
|
| 10 |
+
by beta: the agent harness computes the reported yaw from R0, so beta never shows up in a reading). At reset the
|
| 11 |
+
wrist is turned to the robot's own yaw 0 (true yaw beta), so the first reading is 0.
|
| 12 |
+
|
| 13 |
+
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).
|
| 14 |
+
Commanded to grasp square across the bar, the jaws actually come down rotated by beta; closing turns the bar until it
|
| 15 |
+
lies square in the jaws, so the bar ends up rotated by beta relative to where the robot thinks it is. Lined up
|
| 16 |
+
"exactly" with the holder, the bar is then beta off the holder's axis; its footprint across the opening
|
| 17 |
+
(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
|
| 18 |
+
down across the walls and stays on top of the holder at an angle -- clearly visible from both cameras. The
|
| 19 |
+
alignment tolerance is about +-5 deg (geometry; measured: see the task card).
|
| 20 |
+
|
| 21 |
+
What has to be learned: F2 reports by how many degrees, and in which sense, the bar's long axis was rotated from the
|
| 22 |
+
holder's long axis when the gripper opened (and how far the jaws were turned from square to the bar when they
|
| 23 |
+
closed). That angle is beta itself, so after one failure beta can be estimated and subtracted from every commanded
|
| 24 |
+
yaw.
|
| 25 |
+
"""
|
| 26 |
+
import re
|
| 27 |
+
|
| 28 |
+
import numpy as np
|
| 29 |
+
|
| 30 |
+
from .. import envs
|
| 31 |
+
from ..bddl import write_bddl
|
| 32 |
+
from ..objects import bin_xml, box_xml, register_generated
|
| 33 |
+
from ..skills import Skills, _rotz
|
| 34 |
+
from ..task_base import LFFTask, register_task
|
| 35 |
+
|
| 36 |
+
BAR, HOLDER = "bar_1", "holder_1"
|
| 37 |
+
DISTRACTORS = ("cream_cheese_1", "butter_1")
|
| 38 |
+
FREE_OBJECTS = (BAR,) + DISTRACTORS
|
| 39 |
+
NAMES = {BAR: "blue bar", HOLDER: "holder", "cream_cheese_1": "cream cheese", "butter_1": "butter"}
|
| 40 |
+
DESCR = {BAR: "long blue stick", HOLDER: "narrow grey trough", "cream_cheese_1": "flat blue box",
|
| 41 |
+
"butter_1": "small orange box"}
|
| 42 |
+
|
| 43 |
+
BAR_HALF = (0.070, 0.009, 0.009) # 14 x 1.8 x 1.8 cm, long side along the bar's x axis
|
| 44 |
+
HOLDER_IN = (0.080, 0.016) # inner half extents of the holder's opening: 16 x 3.2 cm
|
| 45 |
+
WALL_T, FLOOR_T, WALL_H = 0.006, 0.006, 0.030
|
| 46 |
+
HOLDER_HALF_H = (WALL_H + FLOOR_T) / 2 # body origin at mid height
|
| 47 |
+
RIM_Z = envs.TABLE_Z + FLOOR_T + WALL_H
|
| 48 |
+
MASS = {BAR: 0.070, "cream_cheese_1": 0.227, "butter_1": 0.250}
|
| 49 |
+
# Bar friction 0.5 with geom priority, so it is used for all bar contacts (also against the finger pads, mu 2). With
|
| 50 |
+
# the pads' mu 2 the jaws pinch a misaligned bar at their corners and it stays skewed in the hand (measured: turned
|
| 51 |
+
# 3-13 deg of beta 15-25 deg while closing); with 0.5 the closing jaws square it up (turned = beta, measured).
|
| 52 |
+
BAR_MU = 0.5
|
| 53 |
+
|
| 54 |
+
SITE_ABOVE_TABLE = 0.0105 # grasp point 1.05 cm above the table: fingertips ~1 mm above it
|
| 55 |
+
Z_CARRY = envs.TABLE_Z + 0.15
|
| 56 |
+
RELEASE_GAP = 0.012 # bar bottom this far above the holder's rim at release
|
| 57 |
+
BETA_MIN, BETA_MAX = np.deg2rad(15), np.deg2rad(30)
|
| 58 |
+
AXIS_MAX = np.deg2rad(45) # bar / holder long axes within +-45 deg of the forward (x) direction
|
| 59 |
+
HOME_XY = np.array([-0.21, 0.0])
|
| 60 |
+
REHOME_STEPS = 40
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def wrap_half(a):
|
| 64 |
+
"""angle modulo pi into [-pi/2, pi/2) (the bar, the holder and the jaws are 180-deg symmetric)"""
|
| 65 |
+
return float((a + np.pi / 2) % np.pi - np.pi / 2)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _yaw_of_xmat(xmat):
|
| 69 |
+
return float(np.arctan2(xmat[1, 0], xmat[0, 0]))
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _seg_dist(p, a, b):
|
| 73 |
+
ab = b - a
|
| 74 |
+
u = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0, 1)
|
| 75 |
+
return float(np.linalg.norm(a + u * ab - p))
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _q(axis, a):
|
| 79 |
+
h = a / 2
|
| 80 |
+
return {"z": np.array([np.cos(h), 0, 0, np.sin(h)])}[axis]
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _qmul(a, b):
|
| 84 |
+
w1, x1, y1, z1 = a
|
| 85 |
+
w2, x2, y2, z2 = b
|
| 86 |
+
return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
|
| 87 |
+
w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2])
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def dir_words(dx, dy):
|
| 91 |
+
"""Robot-frame description: +x = forward (away from the robot), +y = the robot's left."""
|
| 92 |
+
parts = []
|
| 93 |
+
if abs(dy) >= 0.0005:
|
| 94 |
+
parts.append(f"{100 * abs(dy):.1f} cm to the robot's {'left (+y)' if dy > 0 else 'right (-y)'}")
|
| 95 |
+
if abs(dx) >= 0.0005:
|
| 96 |
+
parts.append(f"{100 * abs(dx):.1f} cm {'forward (+x, away from the robot)' if dx > 0 else 'backward (-x, toward the robot)'}")
|
| 97 |
+
return " and ".join(parts) if parts else "exactly at the position"
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def rot_words(a):
|
| 101 |
+
"""Sense of a rotation about the vertical axis. Positive = counter-clockwise seen from above = from forward (+x)
|
| 102 |
+
towards the robot's left (+y) = increasing yaw."""
|
| 103 |
+
d = np.degrees(a)
|
| 104 |
+
if abs(d) < 0.5:
|
| 105 |
+
return "not rotated (within 0.5 deg)"
|
| 106 |
+
if d > 0:
|
| 107 |
+
return f"rotated {d:.0f} deg counter-clockwise seen from above (from forward towards the robot's left, +yaw)"
|
| 108 |
+
return f"rotated {-d:.0f} deg clockwise seen from above (from forward towards the robot's right, -yaw)"
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class YawSkills(Skills):
|
| 112 |
+
"""Skills with a miscalibrated wrist: commanded yaw theta is executed as theta + yaw_bias. Implemented by shifting
|
| 113 |
+
the robot's notion of yaw 0 (`R0`, which Skills uses to build every orientation target and the agent harness uses
|
| 114 |
+
to report the yaw) by yaw_bias; `R0_true` is the real top-down orientation at yaw 0. Also logs what the outcome
|
| 115 |
+
measurement needs, whoever drives the skills (scripted policy or agent)."""
|
| 116 |
+
|
| 117 |
+
def __init__(self, env, yaw_bias=0.0, recorder=None):
|
| 118 |
+
super().__init__(env, bias=None, recorder=recorder)
|
| 119 |
+
self.yaw_bias = float(yaw_bias)
|
| 120 |
+
self.R0_true = self.R0.copy()
|
| 121 |
+
self.R0 = _rotz(self.yaw_bias) @ self.R0_true
|
| 122 |
+
self.events = []
|
| 123 |
+
m = env.sim.model
|
| 124 |
+
self._finger_geoms = {
|
| 125 |
+
side: [m.geom_name2id(g) for g in env.robots[0].gripper.important_geoms[side]]
|
| 126 |
+
for side in ("left_finger", "right_finger")}
|
| 127 |
+
self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_")]
|
| 128 |
+
self._obj_geoms = {n: envs.obj_geom_ids(env, n) for n in FREE_OBJECTS}
|
| 129 |
+
self.bar_z0 = float(envs.obj_pos(env, BAR)[2])
|
| 130 |
+
self.bar_zmax = self.bar_z0
|
| 131 |
+
self.bar_ref_yaw = self.bar_yaw()
|
| 132 |
+
self.bar_ref = envs.obj_pos(env, BAR) # bar pose before the fingers last touched it
|
| 133 |
+
|
| 134 |
+
# ------------------------------------------------------------------ state
|
| 135 |
+
def true_yaw(self):
|
| 136 |
+
return _yaw_of_xmat(self.eef_mat() @ self.R0_true.T)
|
| 137 |
+
|
| 138 |
+
def reported_yaw(self):
|
| 139 |
+
"""Yaw as the miscalibrated robot believes it to be. Anything shown to the agent must use this."""
|
| 140 |
+
return _yaw_of_xmat(self.eef_mat() @ self.R0.T)
|
| 141 |
+
|
| 142 |
+
def bar_yaw(self):
|
| 143 |
+
return _yaw_of_xmat(self.env.sim.data.body_xmat[envs.body_id(self.env, BAR)].reshape(3, 3))
|
| 144 |
+
|
| 145 |
+
def touching(self):
|
| 146 |
+
return [n for n, gs in self._obj_geoms.items() if envs.contacts_between(self.env, self._grip_geoms, gs)]
|
| 147 |
+
|
| 148 |
+
def holding_bar(self):
|
| 149 |
+
bg = self._obj_geoms[BAR]
|
| 150 |
+
return all(envs.contacts_between(self.env, gs, bg) for gs in self._finger_geoms.values())
|
| 151 |
+
|
| 152 |
+
def holding(self, obj_name):
|
| 153 |
+
"""The agent harness reports `holding_object` through this; same finger-contact test as the outcome."""
|
| 154 |
+
if obj_name == BAR:
|
| 155 |
+
return self.holding_bar()
|
| 156 |
+
return super().holding(obj_name)
|
| 157 |
+
|
| 158 |
+
def wrap_yaw(self, yaw):
|
| 159 |
+
"""Like Skills.wrap_yaw (the gripper is symmetric under pi), but the window |yaw| <= YAW_LIMIT is applied
|
| 160 |
+
to the TRUE wrist yaw (commanded + yaw_bias): the joint-7 limit is a property of the real wrist. Without
|
| 161 |
+
this, a commanded -113 deg with yaw_bias -30 deg drives joint 7 into its limit (measured: stops at true
|
| 162 |
+
-137 deg, reported -107 deg)."""
|
| 163 |
+
cands = [yaw + k * np.pi for k in range(-3, 4)]
|
| 164 |
+
ok = [c for c in cands if abs(c + self.yaw_bias) <= self.YAW_LIMIT] or cands
|
| 165 |
+
return float(min(ok, key=lambda c: abs(c - self.yaw)))
|
| 166 |
+
|
| 167 |
+
def move_to(self, target, *args, **kwargs):
|
| 168 |
+
rep = super().move_to(target, *args, **kwargs)
|
| 169 |
+
rep["yaw_reported_deg"] = round(float(np.degrees(self.reported_yaw())), 1)
|
| 170 |
+
return rep
|
| 171 |
+
|
| 172 |
+
def _act(self, dpos, drot, grip):
|
| 173 |
+
super()._act(dpos, drot, grip)
|
| 174 |
+
self.bar_zmax = max(self.bar_zmax, float(envs.obj_pos(self.env, BAR)[2]))
|
| 175 |
+
if self.grip < 0 and not envs.contacts_between(self.env, self._grip_geoms, self._obj_geoms[BAR]):
|
| 176 |
+
self.bar_ref_yaw = self.bar_yaw()
|
| 177 |
+
self.bar_ref = envs.obj_pos(self.env, BAR)
|
| 178 |
+
|
| 179 |
+
def set_gripper(self, close, steps=15):
|
| 180 |
+
if close and self.grip < 0:
|
| 181 |
+
self.events.append(dict(kind="close", eef=self.eef_pos().tolist(), true_yaw=self.true_yaw(),
|
| 182 |
+
bar=envs.obj_pos(self.env, BAR).tolist(), bar_ref_yaw=self.bar_ref_yaw,
|
| 183 |
+
bar_ref=np.asarray(self.bar_ref).tolist(), touching=self.touching(),
|
| 184 |
+
step=self.n_steps))
|
| 185 |
+
elif not close and self.grip > 0 and self.holding_bar():
|
| 186 |
+
self.events.append(dict(kind="release", eef=self.eef_pos().tolist(), true_yaw=self.true_yaw(),
|
| 187 |
+
bar=envs.obj_pos(self.env, BAR).tolist(), bar_yaw=self.bar_yaw(),
|
| 188 |
+
step=self.n_steps))
|
| 189 |
+
rep = super().set_gripper(close, steps)
|
| 190 |
+
if close and self.events and self.events[-1]["kind"] == "close":
|
| 191 |
+
self.events[-1]["bar_yaw_after"] = self.bar_yaw()
|
| 192 |
+
return rep
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
@register_task
|
| 196 |
+
class YawBias(LFFTask):
|
| 197 |
+
name = "l1_yaw_bias"
|
| 198 |
+
level = "L1"
|
| 199 |
+
category = "system_identification"
|
| 200 |
+
capabilities = ("Perceive", "Utilize")
|
| 201 |
+
protocol = "cross"
|
| 202 |
+
instruction = "Pick up the blue bar and put it into the holder."
|
| 203 |
+
instruction_indirect = "Pick up the long blue stick and drop it into the narrow grey trough so that it lies inside."
|
| 204 |
+
pick_lift_min = 0.03
|
| 205 |
+
|
| 206 |
+
# ------------------------------------------------------------ scene
|
| 207 |
+
def make_bddl(self):
|
| 208 |
+
bar = register_generated("LffYbBar", box_xml("lff_yb_bar", BAR_HALF, (0.15, 0.35, 0.85, 1.0), density=1500))
|
| 209 |
+
holder = register_generated("LffYbHolder", bin_xml("lff_yb_holder", HOLDER_IN, WALL_H, wall_t=WALL_T,
|
| 210 |
+
floor_t=FLOOR_T, rgba=(0.55, 0.56, 0.60, 1.0),
|
| 211 |
+
density=2000), free=False)
|
| 212 |
+
objs = [(BAR, bar, "bar_region", (-0.21, -0.26, -0.19, -0.24)),
|
| 213 |
+
("cream_cheese_1", "cream_cheese", "cheese_region", (-0.21, 0.24, -0.19, 0.26)),
|
| 214 |
+
("butter_1", "butter", "butter_region", (0.15, -0.26, 0.17, -0.24))]
|
| 215 |
+
fx = [(HOLDER, holder, "holder_region", (0.09, -0.01, 0.11, 0.01))]
|
| 216 |
+
return write_bddl(self.name, self.instruction, objs, fx)
|
| 217 |
+
|
| 218 |
+
def __init__(self, cam_res=None):
|
| 219 |
+
super().__init__(cam_res)
|
| 220 |
+
self._base_quat = {n: envs.obj_quat(self.env, n) for n in FREE_OBJECTS}
|
| 221 |
+
m = self.env.sim.model
|
| 222 |
+
self._holder_bid = m.body_name2id(self.env.fixtures_dict[HOLDER].root_body)
|
| 223 |
+
|
| 224 |
+
def _place(self, name, xy, yaw, z0=envs.TABLE_Z):
|
| 225 |
+
q = _qmul(_q("z", yaw), self._base_quat[name])
|
| 226 |
+
envs.set_obj_pose(self.env, name, [xy[0], xy[1], z0 + 0.3], quat_wxyz=q)
|
| 227 |
+
self.env.sim.forward()
|
| 228 |
+
qa, _ = envs.free_joint_addr(self.env, name)
|
| 229 |
+
self.env.sim.data.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (z0 + 0.0005)
|
| 230 |
+
self.env.sim.forward()
|
| 231 |
+
|
| 232 |
+
def sample_instance(self, seed):
|
| 233 |
+
rng = np.random.default_rng(seed)
|
| 234 |
+
while True:
|
| 235 |
+
b = np.array([rng.uniform(-0.16, 0.04), rng.uniform(-0.20, 0.20)])
|
| 236 |
+
h = np.array([rng.uniform(-0.14, 0.06), rng.uniform(-0.22, 0.22)])
|
| 237 |
+
if np.linalg.norm(h - b) < 0.22:
|
| 238 |
+
continue
|
| 239 |
+
placed = [b, h]
|
| 240 |
+
dis = {}
|
| 241 |
+
for name in DISTRACTORS:
|
| 242 |
+
for _ in range(300):
|
| 243 |
+
p = np.array([rng.uniform(-0.22, 0.12), rng.uniform(-0.27, 0.27)])
|
| 244 |
+
if any(np.linalg.norm(p - o) < 0.15 for o in placed):
|
| 245 |
+
continue
|
| 246 |
+
if any(_seg_dist(p, a, c) < 0.10 for a, c in ((b, h), (HOME_XY, b))):
|
| 247 |
+
continue
|
| 248 |
+
break
|
| 249 |
+
else:
|
| 250 |
+
break
|
| 251 |
+
placed.append(p)
|
| 252 |
+
dis[name] = dict(xy=p.round(5).tolist(), yaw=float(rng.uniform(-np.pi, np.pi)))
|
| 253 |
+
if len(dis) == len(DISTRACTORS):
|
| 254 |
+
break
|
| 255 |
+
bar_yaw = float(rng.uniform(-AXIS_MAX, AXIS_MAX))
|
| 256 |
+
holder_yaw = float(rng.uniform(-AXIS_MAX, AXIS_MAX))
|
| 257 |
+
beta = float(rng.choice([-1.0, 1.0]) * rng.uniform(BETA_MIN, BETA_MAX))
|
| 258 |
+
return dict(seed=int(seed), bar_xy=b.round(5).tolist(), bar_yaw=bar_yaw, holder_xy=h.round(5).tolist(),
|
| 259 |
+
holder_yaw=holder_yaw, distractors=dis, yaw_bias=beta, yaw_bias_deg=float(np.degrees(beta)))
|
| 260 |
+
|
| 261 |
+
def apply_instance(self, inst):
|
| 262 |
+
m = self.env.sim.model
|
| 263 |
+
m.body_pos[self._holder_bid] = [inst["holder_xy"][0], inst["holder_xy"][1], envs.TABLE_Z + HOLDER_HALF_H]
|
| 264 |
+
m.body_quat[self._holder_bid] = _q("z", inst["holder_yaw"])
|
| 265 |
+
for name, mass in MASS.items():
|
| 266 |
+
envs.scale_mass(self.env, name, mass)
|
| 267 |
+
self.env.sim.forward()
|
| 268 |
+
self._place(BAR, inst["bar_xy"], inst["bar_yaw"])
|
| 269 |
+
envs.set_friction(self.env, BAR, BAR_MU, priority=3)
|
| 270 |
+
for name, v in inst["distractors"].items():
|
| 271 |
+
self._place(name, v["xy"], v["yaw"])
|
| 272 |
+
|
| 273 |
+
def reset_instance(self, inst, recorder=None):
|
| 274 |
+
self.env.reset()
|
| 275 |
+
self.apply_instance(inst)
|
| 276 |
+
self.env.sim.forward()
|
| 277 |
+
envs.settle(self.env, 10)
|
| 278 |
+
self.sk = YawSkills(self.env, yaw_bias=inst["yaw_bias"], recorder=recorder)
|
| 279 |
+
self.sk.hold(REHOME_STEPS) # turn the wrist to the robot's own yaw 0 (true yaw = beta)
|
| 280 |
+
self.sk.n_steps = 0
|
| 281 |
+
self.sk.events = []
|
| 282 |
+
self.start_pos = {n: envs.obj_pos(self.env, n) for n in FREE_OBJECTS}
|
| 283 |
+
return self.sk
|
| 284 |
+
|
| 285 |
+
# ------------------------------------------------------------ outcome
|
| 286 |
+
def holder_frame(self, xy):
|
| 287 |
+
"""xy (world) -> (along, across) in the holder frame, relative to the holder centre"""
|
| 288 |
+
c = self.env.sim.model.body_pos[self._holder_bid][:2].copy()
|
| 289 |
+
a = self.holder_yaw()
|
| 290 |
+
R = np.array([[np.cos(a), np.sin(a)], [-np.sin(a), np.cos(a)]])
|
| 291 |
+
return R @ (np.asarray(xy[:2]) - c)
|
| 292 |
+
|
| 293 |
+
def holder_yaw(self):
|
| 294 |
+
q = self.env.sim.model.body_quat[self._holder_bid]
|
| 295 |
+
return float(2 * np.arctan2(q[3], q[0]))
|
| 296 |
+
|
| 297 |
+
def in_holder(self):
|
| 298 |
+
p = envs.obj_pos(self.env, BAR)
|
| 299 |
+
u, v = self.holder_frame(p)
|
| 300 |
+
return bool(abs(u) < HOLDER_IN[0] and abs(v) < HOLDER_IN[1] and p[2] < RIM_Z
|
| 301 |
+
and envs.obj_upright_cos(self.env, BAR) > 0.95)
|
| 302 |
+
|
| 303 |
+
def outcome(self, inst):
|
| 304 |
+
envs.settle(self.env, 40)
|
| 305 |
+
sk = self.sk
|
| 306 |
+
p = envs.obj_pos(self.env, BAR)
|
| 307 |
+
held = sk.holding_bar()
|
| 308 |
+
success = bool(self.in_holder() and not held)
|
| 309 |
+
picked = sk.bar_zmax > sk.bar_z0 + self.pick_lift_min
|
| 310 |
+
closes = [e for e in sk.events if e["kind"] == "close"]
|
| 311 |
+
last_close = closes[-1] if closes else None
|
| 312 |
+
releases = [e for e in sk.events if e["kind"] == "release" and last_close and e["step"] >= last_close["step"]]
|
| 313 |
+
hy = self.holder_yaw()
|
| 314 |
+
end_mis = wrap_half(sk.bar_yaw() - hy)
|
| 315 |
+
hc = self.env.sim.model.body_pos[self._holder_bid][:2]
|
| 316 |
+
out = dict(success=success, picked=bool(picked), held_at_end=bool(held), bar_end=p.round(4).tolist(),
|
| 317 |
+
bar_end_misalign_deg=round(float(np.degrees(end_mis)), 1), grasp_misalign=None,
|
| 318 |
+
bar_turned_in_grasp=None, release_misalign=None, release_offset=None, touched_at_close=None)
|
| 319 |
+
grasp_txt = ""
|
| 320 |
+
if last_close is not None:
|
| 321 |
+
gm = wrap_half(last_close["true_yaw"] - last_close["bar_ref_yaw"])
|
| 322 |
+
turned = wrap_half(last_close.get("bar_yaw_after", last_close["bar_ref_yaw"]) - last_close["bar_ref_yaw"])
|
| 323 |
+
out["grasp_misalign"] = round(gm, 4)
|
| 324 |
+
out["bar_turned_in_grasp"] = round(turned, 4)
|
| 325 |
+
out["touched_at_close"] = last_close["touching"]
|
| 326 |
+
go = np.array(last_close["eef"][:2]) - np.array(last_close.get("bar_ref", last_close["bar"])[:2])
|
| 327 |
+
a = last_close["bar_ref_yaw"]
|
| 328 |
+
along, across = go @ [np.cos(a), np.sin(a)], go @ [-np.sin(a), np.cos(a)]
|
| 329 |
+
over_bar = bool(abs(along) <= BAR_HALF[0] and abs(across) <= BAR_HALF[1] + 0.02)
|
| 330 |
+
out["grasp_xy_offset"] = go.round(4).tolist()
|
| 331 |
+
out["grasp_over_bar"] = over_bar
|
| 332 |
+
if over_bar:
|
| 333 |
+
grasp_txt = f"When the jaws closed on the blue bar, they were {rot_words(gm)} from square across the bar"
|
| 334 |
+
if np.linalg.norm(go) >= 0.015:
|
| 335 |
+
grasp_txt += f" (the grasp point was {dir_words(*go)} of the bar's centre)"
|
| 336 |
+
else:
|
| 337 |
+
grasp_txt = (f"When the jaws closed, the grasp point was {dir_words(*go)} of the blue bar's centre, i.e. "
|
| 338 |
+
f"not over the bar, and the jaws were {rot_words(gm)} from square across the bar")
|
| 339 |
+
if abs(np.degrees(turned)) >= 2:
|
| 340 |
+
grasp_txt += f", and the closing fingers turned the bar by {abs(np.degrees(turned)):.0f} deg"
|
| 341 |
+
if releases:
|
| 342 |
+
r = releases[-1]
|
| 343 |
+
rm = wrap_half(r["bar_yaw"] - hy)
|
| 344 |
+
out["release_misalign"] = round(rm, 4)
|
| 345 |
+
out["release_offset"] = (np.array(r["bar"][:2]) - hc).round(4).tolist()
|
| 346 |
+
if success:
|
| 347 |
+
out["failure"] = None
|
| 348 |
+
detail = "The blue bar is inside the holder."
|
| 349 |
+
if out["release_misalign"] is not None:
|
| 350 |
+
detail += (f" When the gripper opened, the bar's long axis was {rot_words(out['release_misalign'])} "
|
| 351 |
+
f"from the holder's long axis.")
|
| 352 |
+
elif not picked:
|
| 353 |
+
out["failure"] = "missed_grasp"
|
| 354 |
+
if last_close is None:
|
| 355 |
+
detail = "The gripper never closed; the blue bar was not picked up."
|
| 356 |
+
else:
|
| 357 |
+
detail = f"{grasp_txt}, but the bar was not picked up. It is still on the table."
|
| 358 |
+
elif held:
|
| 359 |
+
out["failure"] = "not_released"
|
| 360 |
+
detail = f"{grasp_txt}. The bar was picked up but it is still in the gripper."
|
| 361 |
+
elif releases:
|
| 362 |
+
out["failure"] = "missed_place"
|
| 363 |
+
if p[2] > RIM_Z - 0.002:
|
| 364 |
+
where = (f"The bar came down across the holder's walls instead of dropping in; it is now lying on top "
|
| 365 |
+
f"of the holder, its long axis {rot_words(end_mis)} from the holder's long axis.")
|
| 366 |
+
else:
|
| 367 |
+
where = (f"The bar did not end up inside the holder (its centre is now "
|
| 368 |
+
f"{dir_words(*(p[:2] - hc))} of the holder's centre).")
|
| 369 |
+
detail = (f"{grasp_txt}. When the gripper opened above the holder, the bar's long axis was "
|
| 370 |
+
f"{rot_words(out['release_misalign'])} from the holder's long axis, and the bar's centre was "
|
| 371 |
+
f"{dir_words(*out['release_offset'])} of the holder's centre. {where}")
|
| 372 |
+
else:
|
| 373 |
+
out["failure"] = "dropped"
|
| 374 |
+
detail = (f"{grasp_txt}. The bar was lifted but slipped out of the fingers before the gripper opened; it is "
|
| 375 |
+
f"now {dir_words(*(p[:2] - hc))} of the holder's centre.")
|
| 376 |
+
out["detail"] = detail
|
| 377 |
+
ind = detail
|
| 378 |
+
for k in sorted(NAMES, key=lambda n: -len(NAMES[n])):
|
| 379 |
+
ind = ind.replace(NAMES[k], DESCR[k])
|
| 380 |
+
ind = re.sub(r"\bbar\b", "stick", ind) # the bare noun would give the direct name away
|
| 381 |
+
out["detail_indirect"] = ind
|
| 382 |
+
return out
|
| 383 |
+
|
| 384 |
+
def feedback(self, inst, out, level="F2", indirect=False):
|
| 385 |
+
if indirect and level == "F2":
|
| 386 |
+
out = dict(out, detail=out.get("detail_indirect", out["detail"]))
|
| 387 |
+
return super().feedback(inst, out, level)
|
| 388 |
+
|
| 389 |
+
# ------------------------------------------------------------ scripted execution (cross protocol)
|
| 390 |
+
def execute(self, inst, params):
|
| 391 |
+
"""Top-down pick square across the bar at its centre, carry, line the bar up with the holder and release it
|
| 392 |
+
just above the holder's rim. params['dyaw'] (rad) is the policy's own yaw correction, added to every
|
| 393 |
+
commanded yaw."""
|
| 394 |
+
sk = self.sk
|
| 395 |
+
dy = float(params.get("dyaw", 0.0))
|
| 396 |
+
b = envs.obj_pos(self.env, BAR) # perfect perception of the current scene
|
| 397 |
+
psi = sk.bar_yaw()
|
| 398 |
+
hc = self.env.sim.model.body_pos[self._holder_bid][:2].copy()
|
| 399 |
+
phi = self.holder_yaw()
|
| 400 |
+
z_grasp = envs.TABLE_Z + SITE_ABOVE_TABLE
|
| 401 |
+
z_rel = RIM_Z + RELEASE_GAP + SITE_ABOVE_TABLE
|
| 402 |
+
sk.set_gripper(False, steps=8)
|
| 403 |
+
sk.move_to([b[0], b[1], Z_CARRY], yaw=wrap_half(psi) + dy)
|
| 404 |
+
sk.move_to([b[0], b[1], z_grasp + 0.06], tol=0.002)
|
| 405 |
+
sk.move_to([b[0], b[1], z_grasp], tol=0.003, max_steps=80)
|
| 406 |
+
sk.set_gripper(True, steps=15)
|
| 407 |
+
sk.move_to([b[0], b[1], Z_CARRY], speed=0.3)
|
| 408 |
+
if not sk.holding_bar(): # missed: a real controller sees the jaws closed on nothing and stops
|
| 409 |
+
return
|
| 410 |
+
sk.move_to([hc[0], hc[1], Z_CARRY], yaw=wrap_half(phi) + dy, tol=0.003)
|
| 411 |
+
sk.move_to([hc[0], hc[1], z_rel], tol=0.003, max_steps=100)
|
| 412 |
+
sk.hold(5)
|
| 413 |
+
sk.set_gripper(False, steps=12)
|
| 414 |
+
sk.move_to([hc[0], hc[1], Z_CARRY], speed=0.3)
|
| 415 |
+
|
| 416 |
+
def default_params(self, inst):
|
| 417 |
+
return dict(dyaw=0.0)
|
| 418 |
+
|
| 419 |
+
def oracle_params(self, inst):
|
| 420 |
+
return dict(dyaw=-float(inst["yaw_bias"]))
|
| 421 |
+
|
| 422 |
+
def adapt_params(self, inst, history):
|
| 423 |
+
"""Scripted F2 learner: the reported angle between the bar and the holder when the gripper opened is the
|
| 424 |
+
part of the wrist offset not yet corrected; accumulate it into the correction subtracted from every
|
| 425 |
+
commanded yaw. If the bar was never released, use the jaw angle at the grasp instead."""
|
| 426 |
+
last = history[-1]
|
| 427 |
+
dy = float(last["params"]["dyaw"])
|
| 428 |
+
o = last["outcome"]
|
| 429 |
+
if o.get("release_misalign") is not None:
|
| 430 |
+
dy -= o["release_misalign"]
|
| 431 |
+
elif o.get("grasp_misalign") is not None:
|
| 432 |
+
dy -= o["grasp_misalign"]
|
| 433 |
+
return dict(dyaw=round(dy, 4))
|
| 434 |
+
|
| 435 |
+
blind_sigma = np.deg2rad(4.0)
|
| 436 |
+
|
| 437 |
+
def blind_params(self, inst, attempt, rng):
|
| 438 |
+
"""Retry the same plan with a small random perturbation of the commanded yaws; no use of history."""
|
| 439 |
+
return dict(dyaw=round(float(rng.normal(0.0, self.blind_sigma)), 4))
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/l4_fit.py
ADDED
|
@@ -0,0 +1,574 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L4-A fit_container: put the phone flat inside the one box it fits into.
|
| 2 |
+
|
| 3 |
+
v3 (2026-10-08, user review of cla2): in v2 the only hidden information was which box is big enough, and box and
|
| 4 |
+
phone sizes are visible: all 4 Sonnet runs compared the sizes in the images and chose the right box first time.
|
| 5 |
+
v3 makes the phone itself bigger than it looks: it wears clear bumper caps on both ends (collision only, nothing is
|
| 6 |
+
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
|
| 7 |
+
against the VISIBLE phone so that the boxes that look roomiest are too short for the capped phone:
|
| 8 |
+
fit visible margin +2.8..3.2 cm along the phone's length, only +0.8..0.9 cm across (looks tight),
|
| 9 |
+
snug +1.15..1.25 cm along, +2.5..3.0 cm across: the most comfortable-looking box, too short with the caps,
|
| 10 |
+
short_wide +0.3..0.6 cm along, +3..4 cm across: the biggest box, too short with the caps,
|
| 11 |
+
narrow_long +3.5..4.0 cm along but 0.3..0.6 cm too narrow,
|
| 12 |
+
small 0.5..1.0 cm too short.
|
| 13 |
+
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
|
| 14 |
+
images it looks shorter than the opening. What has to be learned from that: the phone needs more length than it
|
| 15 |
+
appears to (by about the overlap seen) -> the box with the most length to spare.
|
| 16 |
+
|
| 17 |
+
The text below is the v2 description (layout, execution, feedback) and still applies, with "phone length" read as
|
| 18 |
+
the capped length. v2 is kept in l4_fit.py.bak-20261008-height.
|
| 19 |
+
|
| 20 |
+
v2 description:
|
| 21 |
+
|
| 22 |
+
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
|
| 23 |
+
boxes of the same colour and the same height fill the other five slots (inner sizes: see INNER_RANGES):
|
| 24 |
+
fit inner = phone + 1.0-1.5 cm in both directions (phone long side along box long side),
|
| 25 |
+
short_wide 0.5-1.5 cm too short but 3.5-5 cm wider than the phone (looks biggest),
|
| 26 |
+
narrow_long 0.5-1.5 cm too narrow but 2.5-3.5 cm longer than the phone (the longest),
|
| 27 |
+
small 0.5-1.2 cm too short and 0.3-0.6 cm too narrow (most phone-like proportions),
|
| 28 |
+
short 0.8-2.0 cm too short, as wide as the fitting box.
|
| 29 |
+
Each box is either roughly lined up with the phone's current long axis or roughly perpendicular to it
|
| 30 |
+
(+-15 deg jitter), independently with p = 0.5 -- so half of the time the fitting box needs the phone to be
|
| 31 |
+
turned by ~90 deg.
|
| 32 |
+
|
| 33 |
+
Hidden: which box fits (only careful size comparison reveals it -- the boxes look alike), and whether the
|
| 34 |
+
fitting box needs the phone rotated. Box sizes are rebuilt per instance by resizing the bin geoms in
|
| 35 |
+
sim.model, so a single env serves every instance.
|
| 36 |
+
|
| 37 |
+
Prior (naive): take the nearest box and line the phone's long side up with the box's long side (changed
|
| 38 |
+
2026-10-06 at the user's request: before, the prior kept the phone's orientation, so half of the first
|
| 39 |
+
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
|
| 40 |
+
long / too wide along the box's long / short side; a learner can then rule out boxes that are not bigger
|
| 41 |
+
in that dimension and turn the phone.
|
| 42 |
+
"""
|
| 43 |
+
import numpy as np
|
| 44 |
+
|
| 45 |
+
from .. import envs
|
| 46 |
+
from ..bddl import write_bddl
|
| 47 |
+
from ..objects import _SOLID, _fmt, _wrap, bin_xml, register_generated
|
| 48 |
+
from ..skills import _rot_err
|
| 49 |
+
from ..task_base import LFFTask, register_task
|
| 50 |
+
|
| 51 |
+
# phone (local x = long axis); PL is the visible length, the caps add 2 * cap (inst["cap"]) to it
|
| 52 |
+
PL, PW, PT = 0.140, 0.068, 0.012
|
| 53 |
+
CAP_RANGE = (0.008, 0.009) # clear bumper cap length per end (hidden)
|
| 54 |
+
# boxes (local x = long axis of the opening)
|
| 55 |
+
WALL_T, FLOOR_T, WALL_H = 0.006, 0.006, 0.035
|
| 56 |
+
BOX_HALF_H = (WALL_H + FLOOR_T) / 2 # body origin is at mid height
|
| 57 |
+
RIM_Z = envs.TABLE_Z + FLOOR_T + WALL_H
|
| 58 |
+
N_BOXES = 5
|
| 59 |
+
ROWS_X = (-0.30, -0.08) # back row (near the robot), front row
|
| 60 |
+
COLS_Y = (-0.22, 0.0, 0.22)
|
| 61 |
+
DROP = 0.012 # phone bottom this far above the rim when released
|
| 62 |
+
Z_CARRY = envs.TABLE_Z + 0.15
|
| 63 |
+
PARK = (-0.45, 0.0, envs.TABLE_Z + 0.35) # out of the agentview camera's way
|
| 64 |
+
PERC_SIGMA = 0.003 # perception noise (m) of the scripted adaptive policy's box-size estimates
|
| 65 |
+
JITTER_DEG = 15.0
|
| 66 |
+
# inner size of each box kind = phone size + uniform(lo, hi) offset (m), (long side, short side).
|
| 67 |
+
# The distractors are chosen so that no coarse size heuristic finds the fitting box: the "short_wide" box has
|
| 68 |
+
# the largest area and width, "narrow_long" is the longest, "small" has the most phone-like aspect ratio.
|
| 69 |
+
# Only comparing both box dimensions with the phone's (or the F2 feedback) singles out the fitting box.
|
| 70 |
+
# v3: offsets are relative to the VISIBLE phone (PL x PW); only "fit" takes the capped phone (PL + 2 cap)
|
| 71 |
+
BOX_KINDS = ("fit", "snug", "short_wide", "narrow_long", "small")
|
| 72 |
+
INNER_RANGES = {
|
| 73 |
+
"fit": ((0.028, 0.008), (0.032, 0.009)), # +2.8..3.2 cm along, +0.8..0.9 cm across (looks the tightest)
|
| 74 |
+
"snug": ((0.0115, 0.025), (0.0125, 0.030)), # +1.15..1.25 along, +2.5..3.0 across: looks the most comfortable
|
| 75 |
+
"short_wide": ((0.003, 0.030), (0.006, 0.040)), # +0.3..0.6 along, +3..4 across: the biggest box
|
| 76 |
+
"narrow_long": ((0.035, -0.006), (0.040, -0.003)), # +3.5..4.0 along, 0.3..0.6 cm too narrow
|
| 77 |
+
"small": ((-0.010, 0.003), (-0.005, 0.006)), # 0.5..1.0 cm too short
|
| 78 |
+
}
|
| 79 |
+
VISIBLE_FIT = ("fit", "snug", "short_wide") # kinds that fit the phone as it looks (no caps)
|
| 80 |
+
BOX_RGBA = (0.70, 0.60, 0.46, 1.0)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def phone_xml(model_name):
|
| 84 |
+
hx, hy, hz = PL / 2, PW / 2, PT / 2
|
| 85 |
+
body = (0.13, 0.13, 0.15, 1.0)
|
| 86 |
+
screen = (0.02, 0.025, 0.04, 1.0)
|
| 87 |
+
g = (f' <geom name="{model_name}_g0" type="box" size="{_fmt((hx, hy, hz))}" rgba="{_fmt(body)}" '
|
| 88 |
+
f'density="1500" friction="1.0 0.005 0.0001" {_SOLID} group="0" />\n'
|
| 89 |
+
f' <geom type="box" size="{_fmt((hx, hy, hz))}" rgba="{_fmt(body)}" conaffinity="0" contype="0" '
|
| 90 |
+
f'group="1" />\n'
|
| 91 |
+
f' <geom type="box" pos="0 0 {hz:.5f}" size="{_fmt((hx - 0.004, hy - 0.003, 0.0003))}" '
|
| 92 |
+
f'rgba="{_fmt(screen)}" conaffinity="0" contype="0" group="1" />')
|
| 93 |
+
# v3: clear bumper caps on both ends: collision only, fully transparent, no visual twin (nothing is rendered).
|
| 94 |
+
# Resized per instance in apply_instance (inst["cap"]).
|
| 95 |
+
c = CAP_RANGE[1]
|
| 96 |
+
for k, sx in enumerate((1, -1)):
|
| 97 |
+
g += (f'\n <geom name="{model_name}_cap{k}" type="box" pos="{_fmt((sx * (hx + c / 2), 0, 0))}" '
|
| 98 |
+
f'size="{_fmt((c / 2, hy - 0.001, hz))}" rgba="1 1 1 0" density="400" friction="1.0 0.005 0.0001" '
|
| 99 |
+
f'{_SOLID} group="0" />')
|
| 100 |
+
return _wrap(model_name, g, hz, float(np.hypot(hx + c, hy)))
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def wrap_half(a):
|
| 104 |
+
"""angle modulo pi into [-pi/2, pi/2) (the phone and the boxes are 180-deg symmetric)"""
|
| 105 |
+
return float((a + np.pi / 2) % np.pi - np.pi / 2)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def wrap_quarter(a):
|
| 109 |
+
"""angle modulo pi/2 into [-pi/4, pi/4)"""
|
| 110 |
+
return float((a + np.pi / 4) % (np.pi / 2) - np.pi / 4)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def fits_some_yaw(a, b, clearance=0.002, length=PL):
|
| 114 |
+
"""Does the phone's footprint (length x PW) fit inside an a x b opening at any yaw (with `clearance` to spare in
|
| 115 |
+
total)?"""
|
| 116 |
+
th = np.linspace(0.0, np.pi / 2, 181)
|
| 117 |
+
e1 = length * np.cos(th) + PW * np.sin(th)
|
| 118 |
+
e2 = length * np.sin(th) + PW * np.cos(th)
|
| 119 |
+
return bool(np.any((e1 <= a - clearance) & (e2 <= b - clearance)))
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _rect_corners(xy, yaw, half):
|
| 123 |
+
c, s = np.cos(yaw), np.sin(yaw)
|
| 124 |
+
R = np.array([[c, -s], [s, c]])
|
| 125 |
+
pts = np.array([[1, 1], [1, -1], [-1, -1], [-1, 1]]) * np.asarray(half)
|
| 126 |
+
return pts @ R.T + np.asarray(xy)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _rects_overlap(r1, r2):
|
| 130 |
+
"""separating-axis test for two rotated rectangles given as (xy, yaw, half)"""
|
| 131 |
+
c1, c2 = _rect_corners(*r1), _rect_corners(*r2)
|
| 132 |
+
for yaw in (r1[1], r1[1] + np.pi / 2, r2[1], r2[1] + np.pi / 2):
|
| 133 |
+
ax = np.array([np.cos(yaw), np.sin(yaw)])
|
| 134 |
+
p1, p2 = c1 @ ax, c2 @ ax
|
| 135 |
+
if p1.max() < p2.min() or p2.max() < p1.min():
|
| 136 |
+
return False
|
| 137 |
+
return True
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
@register_task
|
| 141 |
+
class FitContainer(LFFTask):
|
| 142 |
+
name = "l4_fit_container"
|
| 143 |
+
level = "L4"
|
| 144 |
+
category = "geometry_inference"
|
| 145 |
+
capabilities = ("Perceive", "Reason")
|
| 146 |
+
instruction = "Put the phone flat inside a box that it fits into completely."
|
| 147 |
+
instruction_indirect = "Put the black rectangular gadget flat inside a box that it fits into completely."
|
| 148 |
+
|
| 149 |
+
# ------------------------------------------------------------ scene
|
| 150 |
+
def make_bddl(self):
|
| 151 |
+
phone = register_generated("LffFitPhone", phone_xml("lff_fit_phone"))
|
| 152 |
+
# one category per box (BDDL lists one object per line; same-category lines would overwrite each
|
| 153 |
+
# other). All share the same MJCF; the opening is resized per instance in apply_instance.
|
| 154 |
+
cats = [register_generated(f"LffFitBox{c}", bin_xml(f"lff_fit_box_{c.lower()}", (0.075, 0.040), WALL_H,
|
| 155 |
+
wall_t=WALL_T, floor_t=FLOOR_T, rgba=BOX_RGBA,
|
| 156 |
+
density=3000))
|
| 157 |
+
for c in "ABCDE"]
|
| 158 |
+
objs = [("phone_1", phone, "phone_region", (-0.09, -0.01, -0.07, 0.01))]
|
| 159 |
+
slots = [(x, y) for x in ROWS_X for y in COLS_Y if not (x == ROWS_X[1] and y == 0.0)]
|
| 160 |
+
for i, (x, y) in enumerate(slots):
|
| 161 |
+
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)))
|
| 162 |
+
return write_bddl(self.name, self.instruction, objs)
|
| 163 |
+
|
| 164 |
+
def sample_instance(self, seed):
|
| 165 |
+
rng = np.random.default_rng(seed)
|
| 166 |
+
j = np.radians(JITTER_DEG)
|
| 167 |
+
for _ in range(500):
|
| 168 |
+
col = int(rng.integers(3))
|
| 169 |
+
phone_xy = [ROWS_X[1] + rng.uniform(-0.01, 0.01), COLS_Y[col] + rng.uniform(-0.01, 0.01)]
|
| 170 |
+
phone_yaw = float(rng.uniform(-j, j))
|
| 171 |
+
slots = [(x, y) for x in ROWS_X for y in COLS_Y if not (x == ROWS_X[1] and y == COLS_Y[col])]
|
| 172 |
+
kinds = [BOX_KINDS[k] for k in rng.permutation(N_BOXES)]
|
| 173 |
+
cap = float(rng.uniform(*CAP_RANGE))
|
| 174 |
+
boxes = []
|
| 175 |
+
for i, (kind, (x, y)) in enumerate(zip(kinds, slots)):
|
| 176 |
+
lo, hi = INNER_RANGES[kind]
|
| 177 |
+
a, b = PL + rng.uniform(lo[0], hi[0]), PW + rng.uniform(lo[1], hi[1])
|
| 178 |
+
assert (kind == "fit") == fits_some_yaw(a, b, length=PL + 2 * cap), (kind, a, b, cap)
|
| 179 |
+
assert (kind in VISIBLE_FIT) == fits_some_yaw(a, b), (kind, a, b)
|
| 180 |
+
crossed = bool(rng.random() < 0.5)
|
| 181 |
+
yaw = wrap_half(phone_yaw + (np.pi / 2 if crossed else 0.0) + rng.uniform(-j, j))
|
| 182 |
+
boxes.append(dict(name=f"box_{i + 1}", kind=kind, crossed=crossed,
|
| 183 |
+
xy=[float(x + rng.uniform(-0.01, 0.01)), float(y + rng.uniform(-0.01, 0.01))],
|
| 184 |
+
yaw=yaw, inner=[float(a), float(b)]))
|
| 185 |
+
rects = [(b["xy"], b["yaw"], (b["inner"][0] / 2 + WALL_T + 0.007, b["inner"][1] / 2 + WALL_T + 0.007))
|
| 186 |
+
for b in boxes]
|
| 187 |
+
rects.append((phone_xy, phone_yaw, (PL / 2 + 0.01, PW / 2 + 0.01)))
|
| 188 |
+
if not any(_rects_overlap(rects[p], rects[q]) for p in range(len(rects)) for q in range(p)):
|
| 189 |
+
break
|
| 190 |
+
else:
|
| 191 |
+
raise RuntimeError("could not sample a non-overlapping layout")
|
| 192 |
+
prng = np.random.default_rng(seed + 7919)
|
| 193 |
+
perc = [[float(b["inner"][0] + prng.normal(0, PERC_SIGMA)), float(b["inner"][1] + prng.normal(0, PERC_SIGMA))]
|
| 194 |
+
for b in boxes]
|
| 195 |
+
return dict(seed=int(seed), phone_xy=[float(v) for v in phone_xy], phone_yaw=phone_yaw, boxes=boxes,
|
| 196 |
+
fit=int(kinds.index("fit")), fit_crossed=boxes[kinds.index("fit")]["crossed"], cap=cap, _perc=perc)
|
| 197 |
+
|
| 198 |
+
def _reshape_box(self, name, a, b):
|
| 199 |
+
ix, iy, H = a / 2, b / 2, BOX_HALF_H
|
| 200 |
+
parts = [((0, 0, -H + FLOOR_T / 2), (ix + WALL_T, iy + WALL_T, FLOOR_T / 2)),
|
| 201 |
+
((ix + WALL_T / 2, 0, FLOOR_T / 2), (WALL_T / 2, iy + WALL_T, WALL_H / 2)),
|
| 202 |
+
((-ix - WALL_T / 2, 0, FLOOR_T / 2), (WALL_T / 2, iy + WALL_T, WALL_H / 2)),
|
| 203 |
+
((0, iy + WALL_T / 2, FLOOR_T / 2), (ix, WALL_T / 2, WALL_H / 2)),
|
| 204 |
+
((0, -iy - WALL_T / 2, FLOOR_T / 2), (ix, WALL_T / 2, WALL_H / 2))]
|
| 205 |
+
m = self.env.sim.model
|
| 206 |
+
o = self.env.objects_dict[name]
|
| 207 |
+
for names in (o.contact_geoms, o.visual_geoms):
|
| 208 |
+
assert len(names) == len(parts), names
|
| 209 |
+
for k, n in enumerate(names):
|
| 210 |
+
g = m.geom_name2id(n)
|
| 211 |
+
pos, size = parts[k]
|
| 212 |
+
m.geom_pos[g] = pos
|
| 213 |
+
m.geom_size[g] = size
|
| 214 |
+
m.geom_rbound[g] = float(np.linalg.norm(size))
|
| 215 |
+
m.geom_aabb[g] = [0, 0, 0, *size]
|
| 216 |
+
|
| 217 |
+
def _set_caps(self, cap):
|
| 218 |
+
"""resize the two hidden bumper caps to `cap` (m) per end"""
|
| 219 |
+
m = self.env.sim.model
|
| 220 |
+
if not hasattr(self, "_cap_ids"):
|
| 221 |
+
self._cap_ids = [g for g in envs.obj_geom_ids(self.env, "phone_1")
|
| 222 |
+
if m.geom_rgba[g][3] == 0.0 and m.geom_contype[g]]
|
| 223 |
+
assert len(self._cap_ids) == 2, self._cap_ids
|
| 224 |
+
for g in self._cap_ids:
|
| 225 |
+
sx = 1.0 if m.geom_pos[g][0] > 0 else -1.0
|
| 226 |
+
size = (cap / 2, PW / 2 - 0.001, PT / 2)
|
| 227 |
+
m.geom_pos[g] = (sx * (PL / 2 + cap / 2), 0.0, 0.0)
|
| 228 |
+
m.geom_size[g] = size
|
| 229 |
+
m.geom_rbound[g] = float(np.linalg.norm(size))
|
| 230 |
+
m.geom_aabb[g] = [0, 0, 0, *size]
|
| 231 |
+
|
| 232 |
+
def apply_instance(self, inst):
|
| 233 |
+
# walls are moved inwards at run time, out of the compile-time per-body BVH leaf boxes, so the collision
|
| 234 |
+
# mid-phase can silently skip them (fingers / phone pass through; found on l4_nest_order 2026-10-07).
|
| 235 |
+
# Testing all geom pairs of nearby bodies is exact; the run-time geom_rbound / geom_aabb are set below.
|
| 236 |
+
import mujoco
|
| 237 |
+
self.env.sim.model._model.opt.disableflags |= int(mujoco.mjtDisableBit.mjDSBL_MIDPHASE)
|
| 238 |
+
self._set_caps(inst["cap"])
|
| 239 |
+
for b in inst["boxes"]:
|
| 240 |
+
self._reshape_box(b["name"], *b["inner"])
|
| 241 |
+
envs.set_obj_pose(self.env, b["name"], [*b["xy"], envs.TABLE_Z + BOX_HALF_H + 0.0005], yaw=b["yaw"])
|
| 242 |
+
envs.set_obj_pose(self.env, "phone_1", [*inst["phone_xy"], envs.TABLE_Z + PT / 2 + 0.0005],
|
| 243 |
+
yaw=inst["phone_yaw"])
|
| 244 |
+
|
| 245 |
+
# ------------------------------------------------------------ outcome
|
| 246 |
+
def _pose2d(self, name):
|
| 247 |
+
bid = envs.body_id(self.env, name)
|
| 248 |
+
R = self.env.sim.data.body_xmat[bid].reshape(3, 3)
|
| 249 |
+
p = self.env.sim.data.body_xpos[bid].copy()
|
| 250 |
+
return p, float(np.arctan2(R[1, 0], R[0, 0])), float(np.degrees(np.arccos(np.clip(R[2, 2], -1, 1))))
|
| 251 |
+
|
| 252 |
+
def outcome(self, inst):
|
| 253 |
+
envs.settle(self.env, 40)
|
| 254 |
+
p, yaw, tilt = self._pose2d("phone_1")
|
| 255 |
+
held = bool(self.sk is not None and self.sk.holding("phone_1"))
|
| 256 |
+
# which box is the phone in / on: smallest distance of the phone centre outside a box opening
|
| 257 |
+
best = None
|
| 258 |
+
for j, b in enumerate(inst["boxes"]):
|
| 259 |
+
c, byaw, btilt = self._pose2d(b["name"])
|
| 260 |
+
d = np.array([[np.cos(byaw), np.sin(byaw)], [-np.sin(byaw), np.cos(byaw)]]) @ (p[:2] - c[:2])
|
| 261 |
+
out = np.maximum(np.abs(d) - np.array(b["inner"]) / 2, 0.0)
|
| 262 |
+
dist = float(np.linalg.norm(out))
|
| 263 |
+
if best is None or dist < best[0]:
|
| 264 |
+
best = (dist, j, c, byaw, btilt)
|
| 265 |
+
dist, j, c, byaw, btilt = best
|
| 266 |
+
b = inst["boxes"][j]
|
| 267 |
+
a_in, b_in = b["inner"]
|
| 268 |
+
floor_top = c[2] - BOX_HALF_H + FLOOR_T
|
| 269 |
+
height = float(p[2] - PT / 2 - floor_top) # phone bottom above the box floor
|
| 270 |
+
in_opening = dist < 1e-9
|
| 271 |
+
on_floor = height < 0.004 and tilt < 5.0
|
| 272 |
+
success = bool(in_opening and on_floor and not held and btilt < 10.0)
|
| 273 |
+
where = self.box_label(inst, j) # relative description only: no absolute coordinates in feedback
|
| 274 |
+
# footprint of the phone (as it lies now) against the opening of that box
|
| 275 |
+
dl = yaw - byaw
|
| 276 |
+
cs, sn = abs(np.cos(dl)), abs(np.sin(dl))
|
| 277 |
+
L = PL + 2 * inst.get("cap", 0.0) # the capped phone
|
| 278 |
+
over_long = L * cs + PW * sn - a_in
|
| 279 |
+
over_short = L * sn + PW * cs - b_in
|
| 280 |
+
along_long = "length" if cs >= sn else "width"
|
| 281 |
+
fb = dict(box=j, box_xy=[round(float(c[0]), 2), round(float(c[1]), 2)], along_long=along_long,
|
| 282 |
+
over_long_cm=round(100 * over_long, 1) if over_long > 0.001 else None,
|
| 283 |
+
over_short_cm=round(100 * over_short, 1) if over_short > 0.001 else None)
|
| 284 |
+
res = dict(success=success, box=j, box_kind=b["kind"], height_cm=round(100 * height, 2),
|
| 285 |
+
tilt_deg=round(tilt, 1), held=held, phone_xy=[float(p[0]), float(p[1])], feedback=fb)
|
| 286 |
+
if held:
|
| 287 |
+
res["detail"] = "The phone is still in the gripper."
|
| 288 |
+
res["failure"] = "held"
|
| 289 |
+
return res
|
| 290 |
+
if dist > 0.02 or (not in_opening and p[2] < envs.TABLE_Z + PT / 2 + 0.006):
|
| 291 |
+
res["detail"] = (f"The phone is not in any box: it is lying on the table, about {100 * dist:.0f} cm "
|
| 292 |
+
f"outside the opening of {where}.")
|
| 293 |
+
res["failure"] = "table"
|
| 294 |
+
return res
|
| 295 |
+
if success:
|
| 296 |
+
res["detail"] = f"The phone is lying flat on the bottom of {where}."
|
| 297 |
+
res["failure"] = None
|
| 298 |
+
return res
|
| 299 |
+
pose_txt = ("lying flat on top of the walls" if tilt < 5.0 else
|
| 300 |
+
f"tilted about {tilt:.0f} degrees with one end down inside the box")
|
| 301 |
+
txt = f"The phone did not go in: it is resting on the walls of {where}, {pose_txt}."
|
| 302 |
+
dim_l = "long" if along_long == "length" else "wide"
|
| 303 |
+
dim_s = "wide" if along_long == "length" else "long"
|
| 304 |
+
if fb["over_long_cm"]:
|
| 305 |
+
txt += f" It is about {fb['over_long_cm']:.1f} cm too {dim_l} for that box along the box's long side."
|
| 306 |
+
if fb["over_short_cm"]:
|
| 307 |
+
txt += f" It is about {fb['over_short_cm']:.1f} cm too {dim_s} for that box along the box's short side."
|
| 308 |
+
if not fb["over_long_cm"] and not fb["over_short_cm"]:
|
| 309 |
+
txt += " Its footprint is smaller than the opening, but it was not lined up with the box and caught on the rim."
|
| 310 |
+
res["detail"] = txt
|
| 311 |
+
res["failure"] = "rim"
|
| 312 |
+
return res
|
| 313 |
+
|
| 314 |
+
@staticmethod
|
| 315 |
+
def box_label(inst, j):
|
| 316 |
+
"""Name box j by its place among the boxes in robot-centric terms (left = +y = the robot's left)."""
|
| 317 |
+
ys = [b["xy"][1] for b in inst["boxes"]]
|
| 318 |
+
xs = [b["xy"][0] for b in inst["boxes"]]
|
| 319 |
+
n = len(ys)
|
| 320 |
+
order = sorted(range(n), key=lambda i: -ys[i]) # robot's left first
|
| 321 |
+
r = order.index(j)
|
| 322 |
+
close = [i for i in range(n) if i != j and abs(ys[i] - ys[j]) < 0.04]
|
| 323 |
+
if close: # boxes side by side in y: tell them apart by distance from the robot
|
| 324 |
+
nearer = all(xs[j] < xs[i] for i in close)
|
| 325 |
+
return f"the box {'nearest to' if nearer else 'farthest from'} the robot among those at the same left-right position"
|
| 326 |
+
if r == 0:
|
| 327 |
+
return "the box furthest to the robot's left (+y)"
|
| 328 |
+
if r == n - 1:
|
| 329 |
+
return "the box furthest to the robot's right (-y)"
|
| 330 |
+
return "the middle box (between the others, left to right)"
|
| 331 |
+
|
| 332 |
+
# ------------------------------------------------------------ execution
|
| 333 |
+
def execute(self, inst, params):
|
| 334 |
+
"""params: box (index into inst['boxes']), place_yaw (world yaw of the phone's long side when released).
|
| 335 |
+
Optional (tolerance checks only): dx / dy = release offset of the phone centre from the box centre
|
| 336 |
+
along the box's long / short axis (m), drop = height of the phone bottom above the rim (m)."""
|
| 337 |
+
sk, env = self.sk, self.env
|
| 338 |
+
px, py = inst["phone_xy"]
|
| 339 |
+
zc = envs.TABLE_Z + PT / 2
|
| 340 |
+
g0 = wrap_half(inst["phone_yaw"]) # fingers close across the phone's width
|
| 341 |
+
sk.set_gripper(False, steps=5)
|
| 342 |
+
sk.move_to([px, py, zc + 0.10], yaw=g0)
|
| 343 |
+
sk.move_to([px, py, zc + 0.001], tol=0.003)
|
| 344 |
+
sk.set_gripper(True, steps=15)
|
| 345 |
+
sk.move_to([px, py, Z_CARRY], speed=0.25)
|
| 346 |
+
b = inst["boxes"][int(params["box"])]
|
| 347 |
+
c, s = np.cos(b["yaw"]), np.sin(b["yaw"])
|
| 348 |
+
dx, dy = params.get("dx", 0.0), params.get("dy", 0.0)
|
| 349 |
+
bx, by = b["xy"][0] + c * dx - s * dy, b["xy"][1] + s * dx + c * dy
|
| 350 |
+
sk.move_to([bx, by, Z_CARRY], yaw=wrap_half(params["place_yaw"]))
|
| 351 |
+
# put the phone's centre (not the gripper's) over the box centre: compensates in-hand slip
|
| 352 |
+
off = envs.obj_pos(env, "phone_1") - sk.eef_pos()
|
| 353 |
+
drop = params.get("drop", DROP)
|
| 354 |
+
sk.move_to([bx - off[0], by - off[1], RIM_Z + max(0.05, drop + 0.01) - off[2]], tol=0.003)
|
| 355 |
+
tgt = self._servo_phone([bx, by], RIM_Z + drop)
|
| 356 |
+
sk.grip = -1.0 # open while holding the arm at a fixed target (Skills.hold re-anchors and drifts)
|
| 357 |
+
self._hold_at(tgt, 12)
|
| 358 |
+
sk.move_to([tgt[0], tgt[1], RIM_Z + 0.10])
|
| 359 |
+
sk.move_to(list(PARK), yaw=0.0)
|
| 360 |
+
|
| 361 |
+
def _hold_at(self, target, steps):
|
| 362 |
+
sk = self.sk
|
| 363 |
+
R = sk._R()
|
| 364 |
+
for _ in range(steps):
|
| 365 |
+
sk._act(np.asarray(target) - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip)
|
| 366 |
+
|
| 367 |
+
def _servo_phone(self, xy, z_bottom, max_steps=60, tol=0.0015):
|
| 368 |
+
"""Closed-loop: move the gripper until the held phone's centre is over xy and its bottom at z_bottom.
|
| 369 |
+
Returns the final gripper target."""
|
| 370 |
+
sk = self.sk
|
| 371 |
+
R = sk._R()
|
| 372 |
+
goal = np.array([xy[0], xy[1], z_bottom + PT / 2])
|
| 373 |
+
tgt = e_prev = sk.eef_pos()
|
| 374 |
+
for i in range(max_steps):
|
| 375 |
+
ph, e = envs.obj_pos(self.env, "phone_1"), sk.eef_pos()
|
| 376 |
+
if i >= 8 and np.linalg.norm(ph - goal) < tol and np.linalg.norm(e - e_prev) < 0.0005:
|
| 377 |
+
break
|
| 378 |
+
tgt = goal - (ph - e)
|
| 379 |
+
sk._act(tgt - e, _rot_err(R, sk.eef_mat()), sk.grip)
|
| 380 |
+
e_prev = e
|
| 381 |
+
return tgt
|
| 382 |
+
|
| 383 |
+
# ------------------------------------------------------------ scripted policies
|
| 384 |
+
def _naive_yaw(self, inst, j):
|
| 385 |
+
"""keep the phone's orientation, only snap it to the nearest axis of box j"""
|
| 386 |
+
p = inst["phone_yaw"]
|
| 387 |
+
return float(p + wrap_quarter(inst["boxes"][j]["yaw"] - p))
|
| 388 |
+
|
| 389 |
+
def default_params(self, inst):
|
| 390 |
+
"""v3 prior: careful size comparison against the phone as it looks (exact visible sizes: the prior models the
|
| 391 |
+
trap; perception noise is only given to the adaptive learner) -- the box with the most room to spare in its
|
| 392 |
+
tighter direction, i.e. "snug" by construction; phone's long side along the box's long side"""
|
| 393 |
+
marg = [min(b["inner"][0] - PL, b["inner"][1] - PW) for b in inst["boxes"]]
|
| 394 |
+
j = int(np.argmax(marg))
|
| 395 |
+
return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"]))
|
| 396 |
+
|
| 397 |
+
def nearest_params(self, inst):
|
| 398 |
+
"""v2 prior (kept for reference): nearest box, lined up"""
|
| 399 |
+
d = [np.hypot(b["xy"][0] - inst["phone_xy"][0], b["xy"][1] - inst["phone_xy"][1]) for b in inst["boxes"]]
|
| 400 |
+
j = int(np.argmin(d))
|
| 401 |
+
return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"]))
|
| 402 |
+
|
| 403 |
+
def oracle_params(self, inst):
|
| 404 |
+
j = inst["fit"]
|
| 405 |
+
return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"]))
|
| 406 |
+
|
| 407 |
+
def blind_params(self, inst, attempt, rng):
|
| 408 |
+
"""no history: a random box (may repeat), lined up like the prior"""
|
| 409 |
+
j = int(rng.integers(N_BOXES))
|
| 410 |
+
return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"]))
|
| 411 |
+
|
| 412 |
+
def naive_keep_yaw_params(self, inst):
|
| 413 |
+
"""old prior (kept for reference): nearest box, keep the phone's orientation"""
|
| 414 |
+
d = [np.hypot(b["xy"][0] - inst["phone_xy"][0], b["xy"][1] - inst["phone_xy"][1]) for b in inst["boxes"]]
|
| 415 |
+
j = int(np.argmin(d))
|
| 416 |
+
return dict(box=j, place_yaw=self._naive_yaw(inst, j))
|
| 417 |
+
|
| 418 |
+
def adapt_params(self, inst, history):
|
| 419 |
+
"""Scripted learner on F2 feedback.
|
| 420 |
+
|
| 421 |
+
Sees the boxes with noisy size estimates (inst['_perc'], sigma = PERC_SIGMA) but does not know the
|
| 422 |
+
phone's size. Each 'too long / too wide by X along the box's long / short side' message gives an
|
| 423 |
+
estimate of the phone's length or width (perceived box dimension + X). It then picks an untried box
|
| 424 |
+
that is big enough in every estimated dimension (preferring the biggest in the still-unknown one) and
|
| 425 |
+
lines the phone's long side up with the box's long side.
|
| 426 |
+
"""
|
| 427 |
+
perc = inst["_perc"]
|
| 428 |
+
L_est = W_est = None
|
| 429 |
+
tried_aligned = set()
|
| 430 |
+
for h in history:
|
| 431 |
+
o = h["outcome"]
|
| 432 |
+
fb = o.get("feedback") or {}
|
| 433 |
+
if o.get("failure") != "rim":
|
| 434 |
+
continue
|
| 435 |
+
j = fb["box"]
|
| 436 |
+
a, b = perc[j]
|
| 437 |
+
if fb["along_long"] == "length":
|
| 438 |
+
if fb["over_long_cm"] or fb["over_short_cm"]: # a size verdict on this box
|
| 439 |
+
tried_aligned.add(j)
|
| 440 |
+
if fb["over_long_cm"]:
|
| 441 |
+
L_est = max(L_est or 0.0, a + fb["over_long_cm"] / 100)
|
| 442 |
+
if fb["over_short_cm"]:
|
| 443 |
+
W_est = max(W_est or 0.0, b + fb["over_short_cm"] / 100)
|
| 444 |
+
else:
|
| 445 |
+
if fb["over_short_cm"]:
|
| 446 |
+
L_est = max(L_est or 0.0, b + fb["over_short_cm"] / 100)
|
| 447 |
+
if fb["over_long_cm"]:
|
| 448 |
+
W_est = max(W_est or 0.0, a + fb["over_long_cm"] / 100)
|
| 449 |
+
thr = 0.002
|
| 450 |
+
cands = []
|
| 451 |
+
for j, (a, b) in enumerate(perc):
|
| 452 |
+
if j in tried_aligned:
|
| 453 |
+
continue
|
| 454 |
+
mL = None if L_est is None else a - L_est
|
| 455 |
+
mW = None if W_est is None else b - W_est
|
| 456 |
+
feasible = (mL is None or mL > thr) and (mW is None or mW > thr)
|
| 457 |
+
if mL is not None and mW is not None:
|
| 458 |
+
key = min(mL, mW)
|
| 459 |
+
elif mL is not None:
|
| 460 |
+
key = b
|
| 461 |
+
elif mW is not None:
|
| 462 |
+
key = a
|
| 463 |
+
else:
|
| 464 |
+
key = a * b
|
| 465 |
+
cands.append((feasible, key, j))
|
| 466 |
+
if not cands:
|
| 467 |
+
j = int(np.argmax([a * b for a, b in perc]))
|
| 468 |
+
else:
|
| 469 |
+
j = max(cands)[2]
|
| 470 |
+
return dict(box=int(j), place_yaw=float(inst["boxes"][j]["yaw"]))
|
| 471 |
+
|
| 472 |
+
def elim_params(self, inst, history, rng):
|
| 473 |
+
"""sensitivity variant: uses the feedback only to learn the orientation (always lines the phone up
|
| 474 |
+
after the first attempt) and to never retry a box that got a size verdict; picks among the remaining
|
| 475 |
+
boxes at random, i.e. no size reasoning / perception."""
|
| 476 |
+
bad = set()
|
| 477 |
+
for h in history:
|
| 478 |
+
fb = h["outcome"].get("feedback") or {}
|
| 479 |
+
if h["outcome"].get("failure") == "rim" and fb.get("along_long") == "length" and (
|
| 480 |
+
fb.get("over_long_cm") or fb.get("over_short_cm")):
|
| 481 |
+
bad.add(int(fb["box"]))
|
| 482 |
+
left = [j for j in range(N_BOXES) if j not in bad] or list(range(N_BOXES))
|
| 483 |
+
j = int(rng.choice(left))
|
| 484 |
+
return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"]))
|
| 485 |
+
|
| 486 |
+
EXTRA_KINDS = ("elim",)
|
| 487 |
+
|
| 488 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 489 |
+
if kind not in self.EXTRA_KINDS:
|
| 490 |
+
return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt)
|
| 491 |
+
k = k or self.max_attempts
|
| 492 |
+
rng = np.random.default_rng(seed)
|
| 493 |
+
history = []
|
| 494 |
+
for a in range(k):
|
| 495 |
+
self.reset_instance(inst)
|
| 496 |
+
if a == 0:
|
| 497 |
+
params = self.default_params(inst)
|
| 498 |
+
else:
|
| 499 |
+
params = self.elim_params(inst, history, rng)
|
| 500 |
+
self.execute(inst, params)
|
| 501 |
+
out = self.outcome(inst)
|
| 502 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 503 |
+
if on_attempt:
|
| 504 |
+
on_attempt(a, params, out)
|
| 505 |
+
if out["success"]:
|
| 506 |
+
break
|
| 507 |
+
return history
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
# ---------------------------------------------------------------- physical validity checks
|
| 511 |
+
def physics_check(seed0=1000, n=20, out=None):
|
| 512 |
+
"""Every (box, orientation) pair on each instance, released centred from DROP above the rim.
|
| 513 |
+
Expect success iff the box is the fitting one and the phone's long side is along the box's long side."""
|
| 514 |
+
import json
|
| 515 |
+
task = FitContainer()
|
| 516 |
+
rows = []
|
| 517 |
+
for seed in range(seed0, seed0 + n):
|
| 518 |
+
inst = task.sample_instance(seed)
|
| 519 |
+
for j, b in enumerate(inst["boxes"]):
|
| 520 |
+
for orient in ("aligned", "crossed"):
|
| 521 |
+
task.reset_instance(inst)
|
| 522 |
+
task.execute(inst, dict(box=j, place_yaw=float(b["yaw"] + (0.0 if orient == "aligned" else np.pi / 2))))
|
| 523 |
+
o = task.outcome(inst)
|
| 524 |
+
rows.append(dict(seed=seed, box=j, kind=b["kind"], inner_cm=[round(100 * v, 2) for v in b["inner"]],
|
| 525 |
+
orient=orient, success=o["success"], expect=bool(j == inst["fit"] and orient == "aligned"),
|
| 526 |
+
failure=o["failure"], height_cm=o["height_cm"], tilt_deg=o["tilt_deg"], detail=o["detail"]))
|
| 527 |
+
r = rows[-1]
|
| 528 |
+
print(f"seed {seed} box {j} {b['kind']:6s} {orient:7s} succ={r['success']} h={r['height_cm']} "
|
| 529 |
+
f"tilt={r['tilt_deg']}" + ("" if r["success"] == r["expect"] else " <-- MISMATCH"), flush=True)
|
| 530 |
+
if out:
|
| 531 |
+
with open(out, "w") as f:
|
| 532 |
+
json.dump(rows, f, indent=1)
|
| 533 |
+
print("total", len(rows), "mismatches", sum(r["success"] != r["expect"] for r in rows))
|
| 534 |
+
return rows
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def stress_check(seed=1002, out=None):
|
| 538 |
+
"""Release errors (offset / yaw / drop height) at the edges of the size ranges: the tightest fitting box
|
| 539 |
+
(+1.0 cm in both directions) and boxes only 0.5 cm too short / too narrow."""
|
| 540 |
+
import copy
|
| 541 |
+
import json
|
| 542 |
+
task = FitContainer()
|
| 543 |
+
base = task.sample_instance(seed)
|
| 544 |
+
j = base["fit"]
|
| 545 |
+
rows = []
|
| 546 |
+
for name, a, b in [("fit_min", PL + 0.010, PW + 0.010), ("short_0.5", PL - 0.005, PW + 0.010),
|
| 547 |
+
("narrow_0.5", PL + 0.010, PW - 0.005)]:
|
| 548 |
+
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),
|
| 549 |
+
(0, 0, 3, DROP), (0, 0, 6, DROP), (0, 0, 0, 0.05), (0.004, 0.003, 3, 0.05)]:
|
| 550 |
+
inst = copy.deepcopy(base)
|
| 551 |
+
inst["boxes"][j]["inner"] = [a, b]
|
| 552 |
+
task.reset_instance(inst)
|
| 553 |
+
task.execute(inst, dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"] + np.radians(dyaw)),
|
| 554 |
+
dx=dx, dy=dy, drop=drop))
|
| 555 |
+
o = task.outcome(inst)
|
| 556 |
+
rows.append(dict(case=name, inner_cm=[round(a * 100, 2), round(b * 100, 2)], dx_mm=dx * 1000,
|
| 557 |
+
dy_mm=dy * 1000, dyaw_deg=dyaw, drop_cm=drop * 100, success=o["success"],
|
| 558 |
+
height_cm=o["height_cm"], tilt_deg=o["tilt_deg"], detail=o["detail"]))
|
| 559 |
+
print(f"{name:11s} dx={dx * 1000:.0f}mm dy={dy * 1000:.0f}mm dyaw={dyaw}deg drop={drop * 100:.1f}cm -> "
|
| 560 |
+
f"succ={o['success']} h={o['height_cm']} tilt={o['tilt_deg']} | {o['detail']}", flush=True)
|
| 561 |
+
if out:
|
| 562 |
+
with open(out, "w") as f:
|
| 563 |
+
json.dump(rows, f, indent=1)
|
| 564 |
+
return rows
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
if __name__ == "__main__":
|
| 568 |
+
# python -m lffbench.tasks.l4_fit physics results/l4_fit_container/physics_check.json
|
| 569 |
+
# python -m lffbench.tasks.l4_fit stress results/l4_fit_container/stress_check.json
|
| 570 |
+
import sys
|
| 571 |
+
if sys.argv[1] == "physics":
|
| 572 |
+
physics_check(out=sys.argv[2] if len(sys.argv) > 2 else None)
|
| 573 |
+
elif sys.argv[1] == "stress":
|
| 574 |
+
stress_check(out=sys.argv[2] if len(sys.argv) > 2 else None)
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/l5_slippery_lift.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 2 |
+
|
| 3 |
+
Category dynamics_adaptation (L5): "figure out how this object moves".
|
| 4 |
+
|
| 5 |
+
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
|
| 6 |
+
perfectly uniform, but a heavy slug is hidden inside it at an unknown position, so its centre of mass sits
|
| 7 |
+
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
|
| 8 |
+
surface is slippery (finger friction 0.40-0.60): the two finger pads can hold its weight, but they cannot hold
|
| 9 |
+
much torque.
|
| 10 |
+
|
| 11 |
+
Why the prior fails. The natural grasp is across the bar at its midpoint. With the centre of mass a few cm to
|
| 12 |
+
one side, gravity twists the bar in the pads as soon as it is lifted: the heavy end swings down and the bar
|
| 13 |
+
ends up hanging tilted by ~10-50 deg (measured). Slow lifting does not help (the torque is static).
|
| 14 |
+
|
| 15 |
+
What has to be learned. Which end sank tells on which side of the grasp the centre of mass lies; the grasp
|
| 16 |
+
has to move towards that end until it is within ~1.5 cm of the hidden centre of mass (measured window). The
|
| 17 |
+
tilt magnitude saturates, so the distance has to be found by bracketing over a few attempts.
|
| 18 |
+
|
| 19 |
+
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:
|
| 20 |
+
|grasp - COM| <= 1.0 cm -> tilt <= 2 deg; 1.5 cm -> 0-41 deg; >= 2 cm -> mostly 30-50 deg; the tilt does not
|
| 21 |
+
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.
|
| 22 |
+
"""
|
| 23 |
+
import numpy as np
|
| 24 |
+
|
| 25 |
+
from .. import envs
|
| 26 |
+
from ..bddl import write_bddl
|
| 27 |
+
from ..objects import _fmt, _wrap, register_generated
|
| 28 |
+
from ..skills import Skills
|
| 29 |
+
from ..task_base import LFFTask, register_task
|
| 30 |
+
|
| 31 |
+
BAR = "bar_1"
|
| 32 |
+
HALF = (0.02, 0.14, 0.02) # 4 (x) x 28 (y) x 4 (z) cm, long axis along world y
|
| 33 |
+
_SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"'
|
| 34 |
+
W_FRAC = 0.6 # fraction of the bar's mass in the hidden slug
|
| 35 |
+
W_HALF = 0.015 # slug half size (for its inertia)
|
| 36 |
+
E_MIN, E_MAX = 0.025, 0.070 # |COM offset| from the bar's midpoint (m)
|
| 37 |
+
LIFT_MIN = 0.10 # the bar's lowest point must be this high above the table
|
| 38 |
+
TILT_MAX = 8.0 # deg
|
| 39 |
+
Z_GRASP = envs.TABLE_Z + HALF[2] # gripper site at the bar's mid height (finger tips 0.7 cm above the table)
|
| 40 |
+
Z_LIFT = Z_GRASP + 0.15
|
| 41 |
+
YAW_ACROSS = np.pi / 2 # jaws close along world x, i.e. across the bar
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def weighted_box_xml(name, half, rgba, mass=1.0, friction=(1.0, 0.005, 0.0001)):
|
| 45 |
+
"""Box with an explicit inertial. Its pos is off-centre at compile time so MuJoCo keeps
|
| 46 |
+
body_sameframe = 0 / body_simple = 0 and honours the per-instance body_ipos set in apply_instance."""
|
| 47 |
+
I = [mass / 3 * (half[1] ** 2 + half[2] ** 2), mass / 3 * (half[0] ** 2 + half[2] ** 2),
|
| 48 |
+
mass / 3 * (half[0] ** 2 + half[1] ** 2)]
|
| 49 |
+
g = (f' <inertial pos="0 0.001 0.001" mass="{mass}" diaginertia="{_fmt(I)}" />\n'
|
| 50 |
+
f' <geom name="{name}_g0" type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" '
|
| 51 |
+
f'friction="{_fmt(friction)}" {_SOLID} group="0" />\n'
|
| 52 |
+
f' <geom type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" conaffinity="0" contype="0" group="1" />')
|
| 53 |
+
return _wrap(name, g, half[2], float(np.hypot(half[0], half[1])))
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def set_hidden_weight(env, obj, half, mass, w_frac, w_pos, w_half=W_HALF):
|
| 57 |
+
"""Uniform shell of mass (1 - w_frac) * mass plus a hidden cube slug of w_frac * mass at w_pos (body frame).
|
| 58 |
+
Sets the body's mass, centre of mass and inertia; returns the centre of mass (body frame)."""
|
| 59 |
+
m = env.sim.model
|
| 60 |
+
bid = envs.body_id(env, obj)
|
| 61 |
+
ms, mw = (1 - w_frac) * mass, w_frac * mass
|
| 62 |
+
w_pos = np.asarray(w_pos, float)
|
| 63 |
+
c = mw * w_pos / mass
|
| 64 |
+
hx, hy, hz = half
|
| 65 |
+
|
| 66 |
+
def par(mm, r): # parallel-axis terms (diagonal)
|
| 67 |
+
return mm * np.array([r[1] ** 2 + r[2] ** 2, r[0] ** 2 + r[2] ** 2, r[0] ** 2 + r[1] ** 2])
|
| 68 |
+
|
| 69 |
+
I = (ms / 3 * np.array([hy ** 2 + hz ** 2, hx ** 2 + hz ** 2, hx ** 2 + hy ** 2]) + par(ms, -c)
|
| 70 |
+
+ mw / 6 * (2 * w_half) ** 2 * np.ones(3) + par(mw, w_pos - c))
|
| 71 |
+
m.body_mass[bid] = mass
|
| 72 |
+
m.body_ipos[bid] = c
|
| 73 |
+
m.body_iquat[bid] = [1.0, 0.0, 0.0, 0.0]
|
| 74 |
+
m.body_inertia[bid] = I
|
| 75 |
+
envs.refit_bounds(env, bid) # the collision BVH lives in the inertial frame (envs.refit_bounds)
|
| 76 |
+
return c
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def bar_axis(env):
|
| 80 |
+
"""World direction of the bar's long axis (body y)."""
|
| 81 |
+
return env.sim.data.body_xmat[envs.body_id(env, BAR)].reshape(3, 3)[:, 1].copy()
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def bar_tilt_deg(env):
|
| 85 |
+
"""Signed tilt of the bar's long axis from horizontal; > 0: the bar's +y end is lower."""
|
| 86 |
+
ax = bar_axis(env)
|
| 87 |
+
if ax[1] < 0: # orient the axis towards the robot's left so the sign is about world left/right
|
| 88 |
+
ax = -ax
|
| 89 |
+
return float(np.degrees(np.arcsin(np.clip(-ax[2], -1.0, 1.0))))
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def side_words(sign):
|
| 93 |
+
return "left (+y)" if sign > 0 else "right (-y)"
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class BarSkills(Skills):
|
| 97 |
+
"""Skills that record where along the bar the jaws closed, whoever drives them (scripted or agent)."""
|
| 98 |
+
|
| 99 |
+
def __init__(self, env, bias=None, recorder=None):
|
| 100 |
+
super().__init__(env, bias=bias, recorder=recorder)
|
| 101 |
+
self.closes = []
|
| 102 |
+
self.zmax = float(envs.obj_pos(env, BAR)[2])
|
| 103 |
+
self.z0 = self.zmax
|
| 104 |
+
|
| 105 |
+
def _act(self, dpos, drot, grip):
|
| 106 |
+
super()._act(dpos, drot, grip)
|
| 107 |
+
self.zmax = max(self.zmax, float(envs.obj_pos(self.env, BAR)[2]))
|
| 108 |
+
|
| 109 |
+
def set_gripper(self, close, steps=15):
|
| 110 |
+
rep = super().set_gripper(close, steps)
|
| 111 |
+
if close:
|
| 112 |
+
c = envs.obj_pos(self.env, BAR)
|
| 113 |
+
ax = bar_axis(self.env)
|
| 114 |
+
if ax[1] < 0:
|
| 115 |
+
ax = -ax
|
| 116 |
+
along = float((self.eef_pos() - c) @ ax) # + : grasp on the left (+y) side of the midpoint
|
| 117 |
+
self.closes.append(dict(along=along, holding=self.holding(BAR), step=self.n_steps))
|
| 118 |
+
return rep
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@register_task
|
| 122 |
+
class SlipperyLift(LFFTask):
|
| 123 |
+
name = "l5_slippery_lift"
|
| 124 |
+
level = "L5"
|
| 125 |
+
category = "dynamics_adaptation"
|
| 126 |
+
capabilities = ("Perceive", "Reason", "Utilize")
|
| 127 |
+
protocol = "cross"
|
| 128 |
+
instruction = ("Pick up the metal bar and hold it level (tilted less than 8 degrees), with its lowest point at "
|
| 129 |
+
"least 10 cm above the table. Keep holding it when you finish.")
|
| 130 |
+
instruction_indirect = ("Pick up the long grey rod lying on the table and hold it horizontal (tilted less than 8 "
|
| 131 |
+
"degrees), with its lowest point at least 10 cm above the table. Keep holding it when you "
|
| 132 |
+
"finish.")
|
| 133 |
+
|
| 134 |
+
# ------------------------------------------------------------ scene
|
| 135 |
+
def make_bddl(self):
|
| 136 |
+
bar = register_generated("LffSteelBar", weighted_box_xml("lff_steel_bar", HALF, (0.52, 0.55, 0.58, 1.0)))
|
| 137 |
+
objs = [(BAR, bar, "bar_region", (-0.11, -0.01, -0.09, 0.01))]
|
| 138 |
+
return write_bddl(self.name, "pick up the bar and hold it level", objs) # BDDL cannot parse parentheses
|
| 139 |
+
|
| 140 |
+
def sample_instance(self, seed):
|
| 141 |
+
rng = np.random.default_rng(seed)
|
| 142 |
+
e = float(rng.choice([-1.0, 1.0]) * rng.uniform(E_MIN, E_MAX))
|
| 143 |
+
return dict(seed=int(seed),
|
| 144 |
+
bar_xy=[float(rng.uniform(-0.12, -0.03)), float(rng.uniform(-0.06, 0.06))],
|
| 145 |
+
com_offset=e, # along the bar, + = towards the robot's left (+y) end
|
| 146 |
+
mass=float(rng.uniform(0.8, 1.2)),
|
| 147 |
+
mu=float(rng.uniform(0.40, 0.60)))
|
| 148 |
+
|
| 149 |
+
def apply_instance(self, inst):
|
| 150 |
+
x, y = inst["bar_xy"]
|
| 151 |
+
envs.set_obj_pose(self.env, BAR, [x, y, envs.TABLE_Z + HALF[2] + 0.001])
|
| 152 |
+
envs.set_friction(self.env, BAR, inst["mu"])
|
| 153 |
+
set_hidden_weight(self.env, BAR, HALF, inst["mass"], W_FRAC, [0.0, inst["com_offset"] / W_FRAC, 0.0])
|
| 154 |
+
|
| 155 |
+
def reset_instance(self, inst, recorder=None):
|
| 156 |
+
self.env.reset()
|
| 157 |
+
self.apply_instance(inst)
|
| 158 |
+
self.env.sim.forward()
|
| 159 |
+
envs.settle(self.env, 10)
|
| 160 |
+
self.sk = BarSkills(self.env, bias=self.skill_bias(inst), recorder=recorder)
|
| 161 |
+
return self.sk
|
| 162 |
+
|
| 163 |
+
# ------------------------------------------------------------ outcome
|
| 164 |
+
def outcome(self, inst):
|
| 165 |
+
sk = self.sk
|
| 166 |
+
sk.hold(30) # 1.5 s with the gripper as the agent left it (envs.settle would open the jaws)
|
| 167 |
+
held = sk.holding(BAR)
|
| 168 |
+
tilt = bar_tilt_deg(self.env)
|
| 169 |
+
bottom = envs.obj_min_z(self.env, BAR) - envs.TABLE_Z
|
| 170 |
+
lifted = (sk.zmax - sk.z0) > 0.03
|
| 171 |
+
close = next((c for c in reversed(sk.closes) if c["holding"]), sk.closes[-1] if sk.closes else None)
|
| 172 |
+
success = bool(held and abs(tilt) <= TILT_MAX and bottom >= LIFT_MIN)
|
| 173 |
+
out = dict(success=success, held=bool(held), tilt_deg=round(tilt, 1), bottom_cm=round(100 * bottom, 1),
|
| 174 |
+
grasp_along=None if close is None else round(close["along"], 4))
|
| 175 |
+
g = ""
|
| 176 |
+
if close is not None and close["holding"]:
|
| 177 |
+
a = close["along"]
|
| 178 |
+
g = (f" You grasped the bar {100 * abs(a):.1f} cm to the {side_words(a)} of its midpoint."
|
| 179 |
+
if abs(a) >= 0.0005 else " You grasped the bar at its midpoint.")
|
| 180 |
+
tilt_txt = (f"hangs tilted by {abs(tilt):.0f} degrees, its {side_words(tilt).split()[0]} end lower than its "
|
| 181 |
+
f"{side_words(-tilt).split()[0]} end")
|
| 182 |
+
if success:
|
| 183 |
+
out["failure"] = None
|
| 184 |
+
detail = f"The bar is held level (tilt {abs(tilt):.0f} degrees), {100 * bottom:.0f} cm above the table." + g
|
| 185 |
+
elif held and abs(tilt) > TILT_MAX:
|
| 186 |
+
out["failure"] = "tilted"
|
| 187 |
+
detail = ("The bar did not stay level: it rotated in the gripper while it was being lifted and now "
|
| 188 |
+
f"{tilt_txt}." + g)
|
| 189 |
+
if bottom < LIFT_MIN:
|
| 190 |
+
detail += f" Its lowest point is {100 * bottom:.0f} cm above the table."
|
| 191 |
+
elif held:
|
| 192 |
+
out["failure"] = "too_low"
|
| 193 |
+
detail = (f"The bar is held level (tilt {abs(tilt):.0f} degrees) but its lowest point is only "
|
| 194 |
+
f"{100 * bottom:.0f} cm above the table." + g)
|
| 195 |
+
elif lifted:
|
| 196 |
+
out["failure"] = "dropped"
|
| 197 |
+
detail = ("The bar was lifted but slipped out of the gripper and fell back onto the table "
|
| 198 |
+
f"(it now lies tilted by {abs(tilt):.0f} degrees)." + g)
|
| 199 |
+
elif close is None:
|
| 200 |
+
out["failure"] = "no_grasp"
|
| 201 |
+
detail = "The gripper never closed on the bar; it is still lying on the table."
|
| 202 |
+
else:
|
| 203 |
+
out["failure"] = "no_grasp"
|
| 204 |
+
detail = "The gripper closed but did not catch the bar; it is still lying on the table."
|
| 205 |
+
out["detail"] = detail
|
| 206 |
+
out["detail_indirect"] = detail.replace("bar", "rod")
|
| 207 |
+
return out
|
| 208 |
+
|
| 209 |
+
def feedback(self, inst, out, level="F2", indirect=False):
|
| 210 |
+
if indirect and level == "F2":
|
| 211 |
+
out = dict(out, detail=out.get("detail_indirect", out["detail"]))
|
| 212 |
+
return super().feedback(inst, out, level)
|
| 213 |
+
|
| 214 |
+
# ------------------------------------------------------------ scripted execution (cross protocol)
|
| 215 |
+
def execute(self, inst, params):
|
| 216 |
+
"""Grasp across the bar at `along` (m from the visible midpoint, + = left / +y) and lift 15 cm."""
|
| 217 |
+
sk = self.sk
|
| 218 |
+
c = envs.obj_pos(self.env, BAR) # visible bar pose (perfect perception)
|
| 219 |
+
ax = bar_axis(self.env)
|
| 220 |
+
if ax[1] < 0:
|
| 221 |
+
ax = -ax
|
| 222 |
+
g = c + ax * float(params["along"])
|
| 223 |
+
sk.set_gripper(False, steps=5)
|
| 224 |
+
sk.move_to([g[0], g[1], Z_GRASP + 0.10], yaw=YAW_ACROSS)
|
| 225 |
+
sk.move_to([g[0], g[1], Z_GRASP], tol=0.003)
|
| 226 |
+
sk.set_gripper(True, steps=15)
|
| 227 |
+
sk.move_to([g[0], g[1], Z_LIFT], speed=0.15, tol=0.004, max_steps=300)
|
| 228 |
+
|
| 229 |
+
def default_params(self, inst):
|
| 230 |
+
return dict(along=0.0)
|
| 231 |
+
|
| 232 |
+
def oracle_params(self, inst):
|
| 233 |
+
return dict(along=float(inst["com_offset"]))
|
| 234 |
+
|
| 235 |
+
MARGIN = 0.008 # a tilt towards +y at grasp g means COM > g + MARGIN (window is ~+-1.5 cm)
|
| 236 |
+
STEP = 0.030 # first step towards the heavy end when only one side is bounded
|
| 237 |
+
|
| 238 |
+
def adapt_params(self, inst, history):
|
| 239 |
+
"""Bracketing on the grasp point: the end that sank is the heavy side of the last grasp."""
|
| 240 |
+
lo, hi = -HALF[1], HALF[1]
|
| 241 |
+
lo_set = hi_set = False
|
| 242 |
+
for h in history:
|
| 243 |
+
o = h["outcome"]
|
| 244 |
+
g = o["grasp_along"] if o.get("grasp_along") is not None else h["params"]["along"]
|
| 245 |
+
if o.get("failure") == "tilted" or (o.get("failure") == "dropped" and abs(o["tilt_deg"]) > 3):
|
| 246 |
+
if o["tilt_deg"] > 0: # left end sank -> COM left of the grasp
|
| 247 |
+
lo, lo_set = max(lo, g + self.MARGIN), True
|
| 248 |
+
else:
|
| 249 |
+
hi, hi_set = min(hi, g - self.MARGIN), True
|
| 250 |
+
last = history[-1]["params"]["along"]
|
| 251 |
+
if lo_set and hi_set:
|
| 252 |
+
a = 0.5 * (lo + hi)
|
| 253 |
+
elif lo_set:
|
| 254 |
+
a = lo + self.STEP - self.MARGIN
|
| 255 |
+
elif hi_set:
|
| 256 |
+
a = hi - self.STEP + self.MARGIN
|
| 257 |
+
else: # no direction information (e.g. too low): repeat
|
| 258 |
+
a = last
|
| 259 |
+
return dict(along=float(np.clip(a, -0.12, 0.12)))
|
| 260 |
+
|
| 261 |
+
def blind_params(self, inst, attempt, rng):
|
| 262 |
+
return dict(along=float(rng.normal(0.0, 0.01)))
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L6-A swap_interrupt: swap two items between identical pads; the second carry is interrupted by a slip.
|
| 2 |
+
|
| 3 |
+
Scene: four identical dark round pads (flat markers, no collision). The cream cheese (X) starts on pad A,
|
| 4 |
+
the butter (Y) on pad B, pads C and D are empty. Pad positions, which pad is which and the drop spot are
|
| 5 |
+
random per seed. Goal: X on B and Y on A.
|
| 6 |
+
|
| 7 |
+
Standard procedure: X: A -> C (temporary), Y: B -> A, X: C -> B. During the second carry (whichever item is
|
| 8 |
+
carried while the other one has already left its start pad), the carried item "slips": the gripper opens
|
| 9 |
+
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
|
| 10 |
+
table and A, B, D are empty -- the current image no longer shows which empty pad was whose. The information
|
| 11 |
+
needed to finish ("what has been done, where did each item start") is only in the agent's own history.
|
| 12 |
+
|
| 13 |
+
The drop spot is placed next to a *lure* pad: the spare pad ("spare", 50 %), the carried item's own start pad
|
| 14 |
+
("source", 25 %) or its true destination ("dest", 25 %). So "put it on the nearest pad" is usually wrong and
|
| 15 |
+
proximity is close to uninformative; a stronger bias towards the start pad would open a memoryless shortcut
|
| 16 |
+
(tidy both items onto their nearest pads = undo, then swap again), see the task card.
|
| 17 |
+
|
| 18 |
+
Protocol: within (one episode, no reset). Attempt granularity: an attempt is everything the agent does until
|
| 19 |
+
it declares the task done; after each attempt the outcome is measured (F1/F2 feedback) and, if it failed, the
|
| 20 |
+
agent continues from the current state. The slip is injected once per episode, inside attempt 1 (it is an
|
| 21 |
+
in-attempt failure event, reported immediately: see `drain_events`). Scripted references:
|
| 22 |
+
|
| 23 |
+
oracle knows the true start layout; after the slip puts Y on A and X on B.
|
| 24 |
+
adaptive saves the start layout from its first frame (Save), recalls it after the slip (Retrieve) and
|
| 25 |
+
finishes the swap from the right step (Utilize); later attempts fix residual misplacements from
|
| 26 |
+
memory + F2 feedback.
|
| 27 |
+
naive memoryless continuation (one attempt): after the slip it re-plans from the current frame only --
|
| 28 |
+
the stray item goes to the nearest empty pad, the item that is still on a pad goes to the nearest
|
| 29 |
+
remaining empty pad.
|
| 30 |
+
blind memoryless restart (k attempts): does not know which step it was at; tidies the stray item onto
|
| 31 |
+
the nearest empty pad and then performs the whole swap again from the current frame; every later
|
| 32 |
+
attempt again swaps the two items (repeated swap, cf. RMBench).
|
| 33 |
+
blind_continue (extra control, not in the acceptance table) attempt 1 = naive, later attempts = swap again.
|
| 34 |
+
"""
|
| 35 |
+
import numpy as np
|
| 36 |
+
|
| 37 |
+
from .. import envs
|
| 38 |
+
from ..bddl import write_bddl
|
| 39 |
+
from ..objects import _wrap, register_generated
|
| 40 |
+
from ..task_base import LFFTask, register_task
|
| 41 |
+
|
| 42 |
+
N_PADS = 4
|
| 43 |
+
PAD_R = 0.055 # pad radius (11 cm discs); items are 8 x 4.3 x 1.8 cm boxes lying flat
|
| 44 |
+
PAD_HALF_T = 0.0008
|
| 45 |
+
PAD_RGBA = (0.22, 0.24, 0.28, 1.0)
|
| 46 |
+
SUCC_R = 0.04 # item centre within 4 cm of the pad centre counts as "on that pad" for success
|
| 47 |
+
PAD_MIN_DIST = 0.17
|
| 48 |
+
PAD_REGION = (-0.26, 0.04, -0.25, 0.25) # x0, x1, y0, y1 (world)
|
| 49 |
+
PAD_REACH = 0.71 # max horizontal distance of a pad centre from the robot base
|
| 50 |
+
DROP_REGION = (-0.31, 0.07, -0.30, 0.30)
|
| 51 |
+
# beyond ~0.75 m from the base the arm ends up fully stretched (elbow at its joint limit) and the OSC gets stuck
|
| 52 |
+
MAX_REACH = 0.73
|
| 53 |
+
DROP_CLEAR = PAD_R + 0.05 # drop centre this far from every pad centre -> item fully off the pads
|
| 54 |
+
LURE_MARGIN = 0.03 # the lure pad is nearer to the drop spot than any other pad by at least this much
|
| 55 |
+
GRASP_DZ = 0.012 # gripper-site height above the table for a top-down grasp of the flat boxes
|
| 56 |
+
LIFT = 0.15
|
| 57 |
+
BASE_X = -0.66 # robot base x (world); base-frame coordinates = (x - BASE_X, y)
|
| 58 |
+
LURE_P = (("source", 0.25), ("spare", 0.5), ("dest", 0.25))
|
| 59 |
+
|
| 60 |
+
X, Y = "cream_cheese_1", "butter_1"
|
| 61 |
+
NAME = {X: "cream cheese", Y: "butter"}
|
| 62 |
+
PADS = [f"pad_{i + 1}" for i in range(N_PADS)]
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _pad_xml(model_name):
|
| 66 |
+
c = " ".join(f"{v:.3f}" for v in PAD_RGBA)
|
| 67 |
+
g = (f' <geom name="{model_name}_g0" type="cylinder" size="{PAD_R:.4f} {PAD_HALF_T:.4f}" rgba="{c}" '
|
| 68 |
+
f'density="10" contype="0" conaffinity="0" group="0" />\n'
|
| 69 |
+
f' <geom type="cylinder" size="{PAD_R:.4f} {PAD_HALF_T:.4f}" rgba="{c}" conaffinity="0" '
|
| 70 |
+
f'contype="0" group="1" />')
|
| 71 |
+
# flat marker without collisions: gravity compensation keeps it from sinking through the table
|
| 72 |
+
return _wrap(model_name, g, PAD_HALF_T, PAD_R).replace('<body name="object">',
|
| 73 |
+
'<body name="object" gravcomp="1">')
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _yaw_of(env, obj):
|
| 77 |
+
R = env.sim.data.body_xmat[envs.body_id(env, obj)].reshape(3, 3)
|
| 78 |
+
yaw = float(np.arctan2(R[1, 0], R[0, 0])) # long axis of the boxes = body x
|
| 79 |
+
return (yaw + np.pi / 2) % np.pi - np.pi / 2 # boxes are symmetric under pi
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def drop_spot(pads, src, dest, other_xy, lure, phase, dist):
|
| 83 |
+
"""Geometry of the injected drop. pads: (N,2); src / dest: start pads of the carried / other item;
|
| 84 |
+
other_xy: current xy of the other item. Returns (xy, lure_pad) or (None, None)."""
|
| 85 |
+
pads = np.asarray(pads, float)
|
| 86 |
+
rest = [i for i in range(len(pads)) if i not in (src, dest)]
|
| 87 |
+
# spare = an empty pad that is neither start pad and not the one the other item is parked on
|
| 88 |
+
occ = [i for i in rest if np.linalg.norm(pads[i] - other_xy) < PAD_R]
|
| 89 |
+
spare_c = [i for i in rest if i not in occ] or rest
|
| 90 |
+
spare = max(spare_c, key=lambda i: np.linalg.norm(pads[i] - other_xy))
|
| 91 |
+
lp = {"source": src, "dest": dest, "spare": spare}[lure]
|
| 92 |
+
for d in (dist, dist + 0.01, dist - 0.01, dist + 0.02):
|
| 93 |
+
for ang in phase + np.linspace(0, 2 * np.pi, 48, endpoint=False):
|
| 94 |
+
xy = pads[lp] + d * np.array([np.cos(ang), np.sin(ang)])
|
| 95 |
+
if not (DROP_REGION[0] <= xy[0] <= DROP_REGION[1] and DROP_REGION[2] <= xy[1] <= DROP_REGION[3]):
|
| 96 |
+
continue
|
| 97 |
+
if np.hypot(xy[0] - BASE_X, xy[1]) > MAX_REACH:
|
| 98 |
+
continue
|
| 99 |
+
dd = np.linalg.norm(pads - xy, axis=1)
|
| 100 |
+
if dd.min() < DROP_CLEAR or np.linalg.norm(xy - other_xy) < 0.12:
|
| 101 |
+
continue
|
| 102 |
+
if np.any(np.delete(dd, lp) < dd[lp] + LURE_MARGIN):
|
| 103 |
+
continue
|
| 104 |
+
return xy, int(lp)
|
| 105 |
+
return None, None
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
@register_task
|
| 109 |
+
class SwapInterrupt(LFFTask):
|
| 110 |
+
name = "l6_swap_interrupt"
|
| 111 |
+
level = "L6"
|
| 112 |
+
category = "procedural_memory"
|
| 113 |
+
capabilities = ("Perceive", "Save", "Retrieve", "Utilize")
|
| 114 |
+
protocol = "within"
|
| 115 |
+
max_attempts = 5
|
| 116 |
+
instruction = ("Swap the positions of the cream cheese and the butter: each must end up on the round pad "
|
| 117 |
+
"where the other one started. You may use the empty pads as temporary spots.")
|
| 118 |
+
instruction_indirect = ("Swap the positions of the pale blue box with the oval logo and the red-and-yellow "
|
| 119 |
+
"box: each must end up on the round pad where the other one started. You may use the "
|
| 120 |
+
"empty pads as temporary spots.")
|
| 121 |
+
inject = True # set False to run the same scene without the slip (sanity check)
|
| 122 |
+
|
| 123 |
+
# ------------------------------------------------------------ scene
|
| 124 |
+
def make_bddl(self):
|
| 125 |
+
cats = [register_generated(f"LffSwapPad{L}", _pad_xml(f"lff_swap_pad_{L.lower()}")) for L in "ABCD"]
|
| 126 |
+
objs = [(X, "cream_cheese", "cc_region", (-0.21, -0.21, -0.19, -0.19)),
|
| 127 |
+
(Y, "butter", "bu_region", (-0.21, 0.19, -0.19, 0.21)),
|
| 128 |
+
(PADS[0], cats[0], "p1_region", (0.05, -0.21, 0.07, -0.19)),
|
| 129 |
+
(PADS[1], cats[1], "p2_region", (0.05, 0.19, 0.07, 0.21)),
|
| 130 |
+
(PADS[2], cats[2], "p3_region", (-0.06, -0.01, -0.04, 0.01)),
|
| 131 |
+
(PADS[3], cats[3], "p4_region", (-0.31, -0.01, -0.29, 0.01))]
|
| 132 |
+
return write_bddl(self.name, self.instruction, objs)
|
| 133 |
+
|
| 134 |
+
def sample_instance(self, seed):
|
| 135 |
+
rng = np.random.default_rng(seed)
|
| 136 |
+
for _ in range(1000):
|
| 137 |
+
pads = []
|
| 138 |
+
while len(pads) < N_PADS:
|
| 139 |
+
p = np.array([rng.uniform(*PAD_REGION[:2]), rng.uniform(*PAD_REGION[2:])])
|
| 140 |
+
if np.hypot(p[0] - BASE_X, p[1]) > PAD_REACH:
|
| 141 |
+
continue
|
| 142 |
+
if all(np.linalg.norm(p - q) >= PAD_MIN_DIST for q in pads):
|
| 143 |
+
pads.append(p)
|
| 144 |
+
pads = np.array(pads)
|
| 145 |
+
x_pad, y_pad = 0, 1 # pad order is already random
|
| 146 |
+
u, acc = rng.uniform(), 0.0
|
| 147 |
+
for lure, pr in LURE_P:
|
| 148 |
+
acc += pr
|
| 149 |
+
if u < acc:
|
| 150 |
+
break
|
| 151 |
+
phase, dist = float(rng.uniform(0, 2 * np.pi)), float(rng.uniform(0.115, 0.14))
|
| 152 |
+
# canonical execution: X parked on the empty pad nearest to its start pad, then Y is carried
|
| 153 |
+
empt = [i for i in range(N_PADS) if i not in (x_pad, y_pad)]
|
| 154 |
+
buf = min(empt, key=lambda i: np.linalg.norm(pads[i] - pads[x_pad]))
|
| 155 |
+
xy, lp = drop_spot(pads, y_pad, x_pad, pads[buf], lure, phase, dist)
|
| 156 |
+
if xy is None:
|
| 157 |
+
continue
|
| 158 |
+
return dict(seed=int(seed), pads=pads.round(4).tolist(), x_pad=x_pad, y_pad=y_pad,
|
| 159 |
+
yaw_x=float(rng.uniform(-0.3, 0.3)), yaw_y=float(rng.uniform(-0.3, 0.3)),
|
| 160 |
+
lure=lure, drop_phase=phase, drop_dist=dist, drop_yaw=float(rng.uniform(-1.4, 1.4)),
|
| 161 |
+
trigger_dist=float(rng.uniform(0.05, 0.10)),
|
| 162 |
+
canonical_buffer=int(buf), canonical_drop_xy=xy.round(4).tolist())
|
| 163 |
+
raise RuntimeError("could not sample a layout")
|
| 164 |
+
|
| 165 |
+
def apply_instance(self, inst):
|
| 166 |
+
for i, p in enumerate(inst["pads"]):
|
| 167 |
+
envs.set_obj_pose(self.env, PADS[i], [p[0], p[1], envs.TABLE_Z + PAD_HALF_T + 0.0001])
|
| 168 |
+
envs.place_upright(self.env, X, inst["pads"][inst["x_pad"]], inst["yaw_x"])
|
| 169 |
+
envs.place_upright(self.env, Y, inst["pads"][inst["y_pad"]], inst["yaw_y"])
|
| 170 |
+
self.env.sim.forward()
|
| 171 |
+
self.slip = None
|
| 172 |
+
self.events = []
|
| 173 |
+
self._event_cursor = 0 # for drain_events (harness, per tool call)
|
| 174 |
+
self._outcome_cursor = 0 # for outcome (per attempt)
|
| 175 |
+
self._inst = inst
|
| 176 |
+
|
| 177 |
+
def reset_instance(self, inst, recorder=None):
|
| 178 |
+
sk = super().reset_instance(inst)
|
| 179 |
+
self._user_recorder = recorder
|
| 180 |
+
sk.recorder = self._on_step # slip trigger is checked on every control step
|
| 181 |
+
sk.record_every = 1
|
| 182 |
+
self._home = sk.eef_pos()
|
| 183 |
+
return sk
|
| 184 |
+
|
| 185 |
+
def go_home(self):
|
| 186 |
+
"""Lift the arm out of the camera's way (end of an attempt)."""
|
| 187 |
+
p = self.sk.eef_pos()
|
| 188 |
+
self.sk.move_to([p[0], p[1], max(p[2], self._home[2])])
|
| 189 |
+
self.sk.move_to(self._home)
|
| 190 |
+
|
| 191 |
+
# ------------------------------------------------------------ slip injection (state triggered)
|
| 192 |
+
def _on_step(self, env):
|
| 193 |
+
if self.inject and self.slip is None:
|
| 194 |
+
self._maybe_slip()
|
| 195 |
+
if self._user_recorder is not None and self.sk.n_steps % 4 == 0:
|
| 196 |
+
self._user_recorder(env)
|
| 197 |
+
|
| 198 |
+
def _maybe_slip(self):
|
| 199 |
+
"""Fires during the first carry of an item while the other item has already left its start pad,
|
| 200 |
+
i.e. the second transport of a swap, whatever order the agent chose."""
|
| 201 |
+
inst, env = self._inst, self.env
|
| 202 |
+
pads = np.asarray(inst["pads"])
|
| 203 |
+
start = {X: inst["x_pad"], Y: inst["y_pad"]}
|
| 204 |
+
for o, other in ((X, Y), (Y, X)):
|
| 205 |
+
p = envs.obj_pos(env, o)
|
| 206 |
+
if p[2] < envs.TABLE_Z + 0.05:
|
| 207 |
+
continue
|
| 208 |
+
if np.linalg.norm(p[:2] - pads[start[o]]) < inst["trigger_dist"]:
|
| 209 |
+
continue
|
| 210 |
+
q = envs.obj_pos(env, other)
|
| 211 |
+
if np.linalg.norm(q[:2] - pads[start[other]]) < PAD_R:
|
| 212 |
+
continue
|
| 213 |
+
if not self.sk.holding(o):
|
| 214 |
+
continue
|
| 215 |
+
self._do_slip(o, other, q[:2])
|
| 216 |
+
return
|
| 217 |
+
|
| 218 |
+
def _do_slip(self, o, other, other_xy):
|
| 219 |
+
inst = self._inst
|
| 220 |
+
start = {X: inst["x_pad"], Y: inst["y_pad"]}
|
| 221 |
+
args = (inst["pads"], start[o], start[other], other_xy)
|
| 222 |
+
xy, lp = drop_spot(*args, inst["lure"], inst["drop_phase"], inst["drop_dist"])
|
| 223 |
+
lure = inst["lure"]
|
| 224 |
+
for alt in ("source", "spare", "dest"): # fallback (only if the agent did something unusual)
|
| 225 |
+
if xy is not None:
|
| 226 |
+
break
|
| 227 |
+
xy, lp = drop_spot(*args, alt, inst["drop_phase"], inst["drop_dist"])
|
| 228 |
+
lure = alt
|
| 229 |
+
if xy is None:
|
| 230 |
+
xy, lp, lure = np.asarray(inst["canonical_drop_xy"]), -1, "fallback"
|
| 231 |
+
envs.place_upright(self.env, o, xy, inst["drop_yaw"])
|
| 232 |
+
self.sk.grip = -1.0 # the gripper opens
|
| 233 |
+
self.env.sim.forward()
|
| 234 |
+
text = f"The {NAME[o]} slipped out of the gripper and fell onto the table."
|
| 235 |
+
self.slip = dict(obj=o, xy=[float(v) for v in xy], lure=lure, lure_pad=lp, step=int(self.sk.n_steps))
|
| 236 |
+
self.events.append(dict(step=int(self.sk.n_steps), kind="slip", obj=o, text=text))
|
| 237 |
+
|
| 238 |
+
def drain_events(self):
|
| 239 |
+
"""Event texts since the last call (for the harness: append to the current tool-call report)."""
|
| 240 |
+
ev = self.events[self._event_cursor:]
|
| 241 |
+
self._event_cursor = len(self.events)
|
| 242 |
+
return [e["text"] for e in ev]
|
| 243 |
+
|
| 244 |
+
# ------------------------------------------------------------ perception helpers (what an agent can see)
|
| 245 |
+
def pad_xy(self):
|
| 246 |
+
return np.array([envs.obj_pos(self.env, p)[:2] for p in PADS])
|
| 247 |
+
|
| 248 |
+
def on_pad(self, o, r=PAD_R):
|
| 249 |
+
d = np.linalg.norm(self.pad_xy() - envs.obj_pos(self.env, o)[:2], axis=1)
|
| 250 |
+
return int(np.argmin(d)) if d.min() < r else None
|
| 251 |
+
|
| 252 |
+
def empty_pads(self):
|
| 253 |
+
occ = {self.on_pad(X), self.on_pad(Y)}
|
| 254 |
+
return [i for i in range(N_PADS) if i not in occ]
|
| 255 |
+
|
| 256 |
+
def _nearest(self, cands, xy):
|
| 257 |
+
pads = self.pad_xy()
|
| 258 |
+
return min(cands, key=lambda i: np.linalg.norm(pads[i] - np.asarray(xy)[:2]))
|
| 259 |
+
|
| 260 |
+
@staticmethod
|
| 261 |
+
def _bf(xy):
|
| 262 |
+
return f"({xy[0] - BASE_X:.2f}, {xy[1]:+.2f})"
|
| 263 |
+
|
| 264 |
+
def pad_label(self, i, cur=None):
|
| 265 |
+
"""Robot-centric name of pad i relative to the other pads (no coordinates in agent feedback)."""
|
| 266 |
+
cur = self.pad_xy() if cur is None else cur
|
| 267 |
+
c = cur.mean(axis=0)
|
| 268 |
+
fb = "far" if cur[i][0] > c[0] else "near"
|
| 269 |
+
lr = "left" if cur[i][1] > c[1] else "right"
|
| 270 |
+
same = [j for j in range(len(cur)) if ("far" if cur[j][0] > c[0] else "near") == fb
|
| 271 |
+
and ("left" if cur[j][1] > c[1] else "right") == lr]
|
| 272 |
+
lab = f"the {fb}-{lr} pad"
|
| 273 |
+
if len(same) > 1: # two pads in the same quadrant: tell them apart left to right
|
| 274 |
+
order = sorted(same, key=lambda j: -cur[j][1])
|
| 275 |
+
side = "more to the robot's left" if order.index(i) == 0 else "more to the robot's right"
|
| 276 |
+
lab += f" ({side} of the two)"
|
| 277 |
+
return lab
|
| 278 |
+
|
| 279 |
+
# ------------------------------------------------------------ outcome
|
| 280 |
+
def outcome(self, inst):
|
| 281 |
+
envs.settle(self.env, 20)
|
| 282 |
+
pads = np.asarray(inst["pads"])
|
| 283 |
+
target = {X: inst["y_pad"], Y: inst["x_pad"]}
|
| 284 |
+
res, ok = {}, True
|
| 285 |
+
for o in (X, Y):
|
| 286 |
+
p = envs.obj_pos(self.env, o)
|
| 287 |
+
dt = float(np.linalg.norm(p[:2] - pads[target[o]]))
|
| 288 |
+
resting = bool(envs.TABLE_Z - 0.01 < p[2] < envs.TABLE_Z + 0.05 and not self.sk.holding(o))
|
| 289 |
+
res[o] = dict(xy=[float(p[0]), float(p[1])], on_pad=self.on_pad(o), dist_to_target=dt, resting=resting)
|
| 290 |
+
ok = ok and resting and dt <= SUCC_R
|
| 291 |
+
# F2 detail: only what is observable now + events of this attempt; nothing about the start layout
|
| 292 |
+
parts = []
|
| 293 |
+
cur = self.pad_xy()
|
| 294 |
+
for o in (X, Y):
|
| 295 |
+
r = res[o]
|
| 296 |
+
if r["on_pad"] is not None:
|
| 297 |
+
parts.append(f"the {NAME[o]} is on {self.pad_label(r['on_pad'], cur)}")
|
| 298 |
+
else:
|
| 299 |
+
dd = np.linalg.norm(cur - np.asarray(r["xy"]), axis=1)
|
| 300 |
+
d = dd.min() - PAD_R
|
| 301 |
+
parts.append(f"the {NAME[o]} is on the table, on no pad "
|
| 302 |
+
f"({100 * d:.0f} cm from the edge of {self.pad_label(int(dd.argmin()), cur)})")
|
| 303 |
+
emp = [self.pad_label(i, cur) for i in self.empty_pads()]
|
| 304 |
+
detail = ("Now " + "; ".join(parts) + "; empty: " + (", ".join(emp) if emp else "none")
|
| 305 |
+
+ " (left/right = the robot's left/right, near/far = toward/away from the robot).")
|
| 306 |
+
new_ev = [e["text"] for e in self.events[self._outcome_cursor:]]
|
| 307 |
+
self._outcome_cursor = len(self.events)
|
| 308 |
+
if new_ev:
|
| 309 |
+
detail = "During this attempt: " + " ".join(new_ev) + " " + detail
|
| 310 |
+
return dict(success=bool(ok), items={NAME[o]: res[o] for o in (X, Y)},
|
| 311 |
+
slip=self.slip, detail=detail)
|
| 312 |
+
|
| 313 |
+
# ------------------------------------------------------------ motion
|
| 314 |
+
def _pick(self, o):
|
| 315 |
+
sk = self.sk
|
| 316 |
+
for _ in range(2):
|
| 317 |
+
p = envs.obj_pos(self.env, o)
|
| 318 |
+
sk.grasp_at(p[:2], envs.TABLE_Z + GRASP_DZ, yaw=_yaw_of(self.env, o), lift=LIFT)
|
| 319 |
+
if sk.holding(o):
|
| 320 |
+
return True
|
| 321 |
+
sk.set_gripper(False, steps=8)
|
| 322 |
+
sk.move_to([p[0], p[1], envs.TABLE_Z + LIFT])
|
| 323 |
+
return False
|
| 324 |
+
|
| 325 |
+
def _move(self, o, pad, log):
|
| 326 |
+
"""Pick item o and put it on pad `pad`. Returns False if the item slipped on the way."""
|
| 327 |
+
n_ev = len(self.events)
|
| 328 |
+
frm = self.on_pad(o)
|
| 329 |
+
ok = self._pick(o)
|
| 330 |
+
rec = dict(obj=NAME[o], from_pad=frm, to_pad=int(pad), grasped=ok)
|
| 331 |
+
log.append(rec)
|
| 332 |
+
if not ok:
|
| 333 |
+
return True
|
| 334 |
+
xy = self.pad_xy()[pad]
|
| 335 |
+
sk = self.sk
|
| 336 |
+
sk.move_to([xy[0], xy[1], envs.TABLE_Z + GRASP_DZ + LIFT]) # carry (the slip may fire here)
|
| 337 |
+
if len(self.events) > n_ev:
|
| 338 |
+
rec["slipped"] = True
|
| 339 |
+
return False
|
| 340 |
+
sk.move_to([xy[0], xy[1], envs.TABLE_Z + GRASP_DZ + 0.004], tol=0.004)
|
| 341 |
+
sk.set_gripper(False, steps=12)
|
| 342 |
+
sk.move_to([xy[0], xy[1], envs.TABLE_Z + GRASP_DZ + 0.10])
|
| 343 |
+
return True
|
| 344 |
+
|
| 345 |
+
def _run(self, moves, log):
|
| 346 |
+
"""moves: list of (item, pad) computed up front (an open-loop plan). Stops at a slip."""
|
| 347 |
+
for o, pad in moves:
|
| 348 |
+
if not self._move(o, pad, log):
|
| 349 |
+
return False
|
| 350 |
+
return True
|
| 351 |
+
|
| 352 |
+
def _swap_now(self, log, rng=None):
|
| 353 |
+
"""The standard swap of the two items' *current* pads via an empty pad (no memory)."""
|
| 354 |
+
a, b = self.on_pad(X), self.on_pad(Y)
|
| 355 |
+
empt = self.empty_pads()
|
| 356 |
+
if a is None or b is None or not empt:
|
| 357 |
+
return
|
| 358 |
+
buf = int(rng.choice(empt)) if rng is not None else self._nearest(empt, self.pad_xy()[a])
|
| 359 |
+
self._run([(X, buf), (Y, a), (X, b)], log)
|
| 360 |
+
|
| 361 |
+
def _tidy_stray(self, log):
|
| 362 |
+
for o in (X, Y):
|
| 363 |
+
if self.on_pad(o) is None and self.empty_pads():
|
| 364 |
+
self._move(o, self._nearest(self.empty_pads(), envs.obj_pos(self.env, o)), log)
|
| 365 |
+
|
| 366 |
+
def _fixup(self, target, log):
|
| 367 |
+
"""Move items until each is on its target pad (target: item -> pad index)."""
|
| 368 |
+
pads = self.pad_xy()
|
| 369 |
+
for _ in range(6):
|
| 370 |
+
todo = [o for o in (Y, X) if np.linalg.norm(envs.obj_pos(self.env, o)[:2] - pads[target[o]]) > SUCC_R]
|
| 371 |
+
if not todo:
|
| 372 |
+
return
|
| 373 |
+
free = [o for o in todo if self.on_pad({X: Y, Y: X}[o], r=PAD_R) != target[o]]
|
| 374 |
+
if free:
|
| 375 |
+
self._move(free[0], target[free[0]], log)
|
| 376 |
+
else: # the two items block each other: park one on an empty pad that is no one's target
|
| 377 |
+
o = todo[0]
|
| 378 |
+
spare = [i for i in self.empty_pads() if i not in target.values()] or self.empty_pads()
|
| 379 |
+
self._move(o, self._nearest(spare, envs.obj_pos(self.env, o)), log)
|
| 380 |
+
|
| 381 |
+
# ------------------------------------------------------------ scripted references (within protocol)
|
| 382 |
+
def _memory(self):
|
| 383 |
+
"""Save: what the agent sees in its first frame -- which pad (by position) each item starts on."""
|
| 384 |
+
return {X: self.pad_xy()[self.on_pad(X)].tolist(), Y: self.pad_xy()[self.on_pad(Y)].tolist()}
|
| 385 |
+
|
| 386 |
+
def saved_memory(self, first):
|
| 387 |
+
"""What the adaptive policy recalls after the slip (identity; patched by the mismatched-memory control)."""
|
| 388 |
+
return first
|
| 389 |
+
|
| 390 |
+
def _attempt1(self, kind, inst, mem, rng, first):
|
| 391 |
+
log = []
|
| 392 |
+
plan = dict(kind=kind, moves=log)
|
| 393 |
+
a = self._nearest(range(N_PADS), first[X]) # the open-loop plan is made from the first frame
|
| 394 |
+
b = self._nearest(range(N_PADS), first[Y])
|
| 395 |
+
empt = [i for i in range(N_PADS) if i not in (a, b)]
|
| 396 |
+
buf = self._nearest(empt, self.pad_xy()[a])
|
| 397 |
+
plan["plan"] = f"X->{buf}, Y->{a}, X->{b}"
|
| 398 |
+
if self._run([(X, buf), (Y, a), (X, b)], log):
|
| 399 |
+
plan["recovery"] = "none (no slip)"
|
| 400 |
+
return plan
|
| 401 |
+
# ---- the carry was interrupted by the slip: recover
|
| 402 |
+
if kind == "oracle": # privileged: true start layout
|
| 403 |
+
plan["recovery"] = "oracle: true layout"
|
| 404 |
+
self._fixup({X: inst["y_pad"], Y: inst["x_pad"]}, log)
|
| 405 |
+
elif kind == "adaptive": # Retrieve the saved first frame and the step log; finish from the right step
|
| 406 |
+
ta = self._nearest(range(N_PADS), mem[X])
|
| 407 |
+
tb = self._nearest(range(N_PADS), mem[Y])
|
| 408 |
+
plan["recovery"] = f"memory: butter -> pad {ta} (cream cheese's start), cream cheese -> pad {tb}"
|
| 409 |
+
self._fixup({X: tb, Y: ta}, log)
|
| 410 |
+
elif kind in ("naive", "blind_continue"): # memoryless continuation from the current frame
|
| 411 |
+
stray = [o for o in (X, Y) if self.on_pad(o) is None]
|
| 412 |
+
parked = [o for o in (X, Y) if self.on_pad(o) is not None]
|
| 413 |
+
plan["recovery"] = "current frame: stray item -> nearest empty pad; parked item -> nearest empty pad"
|
| 414 |
+
for o in stray:
|
| 415 |
+
self._move(o, self._nearest(self.empty_pads(), envs.obj_pos(self.env, o)), log)
|
| 416 |
+
for o in parked:
|
| 417 |
+
if self.empty_pads():
|
| 418 |
+
self._move(o, self._nearest(self.empty_pads(), envs.obj_pos(self.env, o)), log)
|
| 419 |
+
elif kind == "blind": # memoryless restart: tidy up, then the whole swap again
|
| 420 |
+
plan["recovery"] = "restart: stray item -> nearest empty pad, then swap again"
|
| 421 |
+
self._tidy_stray(log)
|
| 422 |
+
self._swap_now(log, rng)
|
| 423 |
+
else:
|
| 424 |
+
raise ValueError(kind)
|
| 425 |
+
return plan
|
| 426 |
+
|
| 427 |
+
def _retry(self, kind, inst, mem, rng):
|
| 428 |
+
log = []
|
| 429 |
+
plan = dict(kind=kind, moves=log)
|
| 430 |
+
if kind == "adaptive":
|
| 431 |
+
ta = self._nearest(range(N_PADS), mem[X])
|
| 432 |
+
tb = self._nearest(range(N_PADS), mem[Y])
|
| 433 |
+
plan["recovery"] = "memory + F2: fix items not on their targets"
|
| 434 |
+
self._fixup({X: tb, Y: ta}, log)
|
| 435 |
+
elif kind in ("blind", "blind_continue"):
|
| 436 |
+
plan["recovery"] = "no history: tidy, then swap the two items again"
|
| 437 |
+
self._tidy_stray(log)
|
| 438 |
+
self._swap_now(log, rng)
|
| 439 |
+
else:
|
| 440 |
+
raise ValueError(kind)
|
| 441 |
+
return plan
|
| 442 |
+
|
| 443 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 444 |
+
k = k or self.max_attempts
|
| 445 |
+
rng = np.random.default_rng(seed)
|
| 446 |
+
self.reset_instance(inst)
|
| 447 |
+
first = self._memory()
|
| 448 |
+
mem = self.saved_memory(first)
|
| 449 |
+
history = []
|
| 450 |
+
for a in range(k):
|
| 451 |
+
plan = self._attempt1(kind, inst, mem, rng, first) if a == 0 else self._retry(kind, inst, mem, rng)
|
| 452 |
+
self.go_home() # "done": the agent declares the attempt finished
|
| 453 |
+
out = self.outcome(inst)
|
| 454 |
+
history.append(dict(attempt=a + 1, params=plan, outcome=out))
|
| 455 |
+
if on_attempt:
|
| 456 |
+
on_attempt(a, plan, out)
|
| 457 |
+
if out["success"] or kind in ("oracle", "naive"):
|
| 458 |
+
break
|
| 459 |
+
return history
|
| 460 |
+
|
| 461 |
+
# cross-protocol hooks are not used by this task
|
| 462 |
+
def default_params(self, inst):
|
| 463 |
+
return dict(policy="naive")
|
| 464 |
+
|
| 465 |
+
def oracle_params(self, inst):
|
| 466 |
+
return dict(policy="oracle")
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/lh_drawer_cabinet.py
ADDED
|
@@ -0,0 +1,1273 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LH drawer_cabinet (2026-10-16): tidy the table -- stand two tall bottles on top of a small wooden cabinet, put two
|
| 2 |
+
cubes into its open drawer and close the drawer. In 14 of every 20 instances the drawer is a self-closing one: pushed
|
| 3 |
+
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
|
| 4 |
+
already standing on its top fall over (away from the robot, onto the gallery rail at the back of the top).
|
| 5 |
+
|
| 6 |
+
Family: long-horizon self-disturbance ("state_restoration"): a later, normal action (closing the drawer) physically
|
| 7 |
+
undoes an earlier stage (bottles on the cabinet). The instruction lists the bottles first but fixes no order. The agent
|
| 8 |
+
has to see the fallen bottles and stand them up again after the drawer is shut (within an attempt), or learn to put
|
| 9 |
+
the cubes in and shut the drawer before it puts the bottles on top (across attempts).
|
| 10 |
+
|
| 11 |
+
Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
|
| 12 |
+
* 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
|
| 13 |
+
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
|
| 14 |
+
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
|
| 15 |
+
finger slot, no handle, 0.8 kg) is pulled out 11 cm towards the robot. The agentview camera looks at the cabinet's
|
| 16 |
+
back: the drawer is hidden there (wrist camera only), the top and the bottles are in plain view;
|
| 17 |
+
* 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,
|
| 18 |
+
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)
|
| 19 |
+
standing on the table 21-24 cm to one side of the cabinet's centre line;
|
| 20 |
+
* two 3.2 cm cubes (red, blue, 23 g) 25-29 cm to the other side (picked from nearer, the forearm sweeps over the
|
| 21 |
+
cabinet top and knocks bottles standing there: measured feasibility map, task card).
|
| 22 |
+
|
| 23 |
+
Hidden variable (same appearance): the drawer's closing mechanism. "self-closing" (14 of every 20 consecutive seeds):
|
| 24 |
+
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
|
| 25 |
+
spring with a damper, the drawer glides in at 4-6 cm/s. Nuisance variables (no effect on the class): carcass mass
|
| 26 |
+
0.35-0.45 kg, felt feet (friction on the table 0.15-0.22).
|
| 27 |
+
|
| 28 |
+
Mechanism (physics, no teleport; measured, see the task card): the spring is internal to the cabinet, so when it snaps
|
| 29 |
+
the drawer in, it also pulls the light carcass (with the bottles on its top) towards the drawer, i.e. towards the robot:
|
| 30 |
+
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),
|
| 31 |
+
then the carcass stops dead. A standing bottle's tilt follows a fast displacement of its support as ~ m h dx / I_edge
|
| 32 |
+
(~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
|
| 33 |
+
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).
|
| 34 |
+
Pushing slower does not help (the spring does the closing; 2-10 cm/s and push heights 3-8 cm all toppled, 32/32);
|
| 35 |
+
placing the bottles elsewhere on the top does not help (46/46 over six placements). A soft-close drawer moves the
|
| 36 |
+
carcass < 3 mm (0/38 bottles fell). Only an uncontrolled full-speed push (~0.6 m/s, not an agent habit) differs: the
|
| 37 |
+
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
|
| 38 |
+
the numbers: with a light drawer, a heavier carcass or more friction the bottles only rocked (<= 11 deg): the snap's
|
| 39 |
+
jerk and the friction stop cancel; a 2 kg carcass held by friction during the snap instead jerked away from the robot
|
| 40 |
+
and tipped the bottles towards (onto) the arm. Without the rail, fallen bottles lay with their caps right behind the
|
| 41 |
+
cabinet, where the palm (3 cm behind the grasp point) cannot get at them; with the heavy drawer pulled out and no
|
| 42 |
+
plinth, ~3 N pressing on the drawer front tipped the cabinet forward.
|
| 43 |
+
|
| 44 |
+
Restoring: the cap is a ball with low torsional friction; grasped from above with the fingers across the lying
|
| 45 |
+
bottle's axis, the cap turns between the fingers, the lifted bottle swings down and hangs straight, and it can be set
|
| 46 |
+
down on the cabinet top (lh_bystander's mechanism; the instruction says that a bottle held by its cap hangs straight).
|
| 47 |
+
The neck has torsional friction: a bottle pinched at the neck just under the cap is carried without swinging.
|
| 48 |
+
|
| 49 |
+
Success (final state, follows from the instruction): both bottles upright (<= 10 deg) with their whole base on the
|
| 50 |
+
cabinet top (inside the rail), not held; both cubes inside the drawer; the drawer closed (<= 5 mm); the cabinet
|
| 51 |
+
upright and not moved more than 8 cm (the snap itself moves it 2.3-4.2 cm); the gripper open, holding nothing and
|
| 52 |
+
touching no task object; scene static. Per-step monitor (server log only; F1 tells the agent success / failure): stage
|
| 53 |
+
achieved / lost / restored (with cause: drawer_slam / robot_hand / robot_arm / bottle / picked_up / other),
|
| 54 |
+
drawer_slam (impact speed, carcass jerk, bottles on top, which of them fell, whether the robot had touched them before
|
| 55 |
+
they started to fall), bottle_fell, trap_fired (a bottle on top was lost to a slam), recovered_in_attempt.
|
| 56 |
+
|
| 57 |
+
Protocol: cross (reset to the same instance before every attempt), k = 3. Once shut, the drawer cannot be opened again
|
| 58 |
+
(no handle; the self-closing spring would drag the light carcass along anyway).
|
| 59 |
+
"""
|
| 60 |
+
import numpy as np
|
| 61 |
+
|
| 62 |
+
from .. import envs
|
| 63 |
+
from ..bddl import write_bddl
|
| 64 |
+
from ..objects import _fmt, _wrap, box_xml, register_generated
|
| 65 |
+
from ..skills import Skills
|
| 66 |
+
from ..task_base import LFFTask, register_task
|
| 67 |
+
|
| 68 |
+
Z = envs.TABLE_Z
|
| 69 |
+
|
| 70 |
+
# ---------------------------------------------------------------- cabinet (body frame: front face at -x, origin at the
|
| 71 |
+
# centre of the footprint, z = 0 on the table)
|
| 72 |
+
CAB = "cabinet_1"
|
| 73 |
+
CAB_MODEL = "lff_lhd_cabinet"
|
| 74 |
+
CD, CW, CH = 0.18, 0.22, 0.11 # carcass depth (x), width (y), height
|
| 75 |
+
CT = 0.010 # board thickness
|
| 76 |
+
PF = 0.018 # drawer front panel thickness (overlay: it sits in front of the carcass when closed)
|
| 77 |
+
DL = 0.165 # drawer box length (x), measured from the inner face of the front panel
|
| 78 |
+
DWT = 0.006 # drawer wall thickness
|
| 79 |
+
DWH = 0.030 # drawer wall height above its floor
|
| 80 |
+
D_FLOOR = CT + 0.003 # drawer floor bottom above the table
|
| 81 |
+
FLOOR_TOP = D_FLOOR + DWT
|
| 82 |
+
D_IN_Y = CW / 2 - CT - 0.003 - DWT # drawer inner half width (0.081)
|
| 83 |
+
D_IN_X = DL - DWT # inner length (from the front panel to the back wall)
|
| 84 |
+
Q_MAX = 0.14 # slide range (opening distance)
|
| 85 |
+
Q_OPEN = 0.11 # the drawer starts pulled out this far (exposed inside: 11 x 16.2 cm)
|
| 86 |
+
WOOD = (0.66, 0.50, 0.33, 1.0)
|
| 87 |
+
WOOD_D = (0.55, 0.40, 0.25, 1.0)
|
| 88 |
+
PANEL = (0.76, 0.60, 0.40, 1.0)
|
| 89 |
+
INNER = (0.84, 0.72, 0.52, 1.0)
|
| 90 |
+
SLOT = (0.18, 0.13, 0.09, 1.0)
|
| 91 |
+
DRAWER_MASS = 0.80
|
| 92 |
+
PLINTH = 0.04 # the bottom board reaches this far in front of the carcass, under the drawer: with the heavy drawer
|
| 93 |
+
# pulled out, the cabinet would otherwise tip forward under a ~3 N push down on the drawer's front
|
| 94 |
+
CAB_COM_X = 0.04 # carcass centre of mass towards the back (back-heavy carcass): same reason
|
| 95 |
+
RAIL_H, RAIL_T = 0.060, 0.008 # gallery rail along the back edge of the top: a bottle that tips over backwards comes
|
| 96 |
+
# to rest leaning on it (~50 deg) instead of falling off behind the cabinet, where its
|
| 97 |
+
# cap would lie against the cabinet's back and the palm could not get at it
|
| 98 |
+
SLIDE_FRIC = 1.0 # N, slide frictionloss: the open drawer stays where it is
|
| 99 |
+
CARCASS_MASS = (0.35, 0.45)
|
| 100 |
+
FEET_MU = (0.15, 0.22)
|
| 101 |
+
|
| 102 |
+
# drawer closing mechanism (hidden): spring in the last ZONE of travel, optional damper (soft-close)
|
| 103 |
+
ZONE = 0.08
|
| 104 |
+
F_SPRING = (12.5, 15.0)
|
| 105 |
+
SOFT_V = (0.04, 0.06) # soft-close glide speed (damping = force / speed)
|
| 106 |
+
P_SLAM = 0.70 # 14 of every 20 consecutive seeds self-closing
|
| 107 |
+
CLOSED = 0.005 # drawer counts as closed
|
| 108 |
+
V_SLAM = 0.30 # m/s: an impact on the stop faster than this is a slam (soft-close: ~0.05)
|
| 109 |
+
|
| 110 |
+
# ---------------------------------------------------------------- bottles (square body, shoulder, neck, ball cap)
|
| 111 |
+
BOTTLES = ("green_bottle_1", "brown_bottle_1")
|
| 112 |
+
B_NAME = {"green_bottle_1": "green", "brown_bottle_1": "brown"}
|
| 113 |
+
B_RGBA = {"green_bottle_1": (0.16, 0.48, 0.26, 1.0), "brown_bottle_1": (0.50, 0.26, 0.10, 1.0)}
|
| 114 |
+
CAP_RGBA = {"green_bottle_1": (0.92, 0.80, 0.15, 1.0), "brown_bottle_1": (0.15, 0.32, 0.85, 1.0)}
|
| 115 |
+
RB, HB = 0.020, 0.115 # body half width, height (incl. the foot)
|
| 116 |
+
RF, HF = 0.011, 0.005 # rounded glass base: flat contact 2.2 x 2.2 cm
|
| 117 |
+
RS, HS = 0.015, 0.010 # shoulder
|
| 118 |
+
RN, HN = 0.009, 0.050 # neck: long enough to be pinched below the cap with the palm clear of the cap
|
| 119 |
+
RK = 0.012 # ball cap
|
| 120 |
+
CAP_SINK = 0.005
|
| 121 |
+
H_TOT = HB + HS + HN + 2 * RK - CAP_SINK # 0.194
|
| 122 |
+
CAP_Z = H_TOT - RK # cap centre above the bottle's bottom when standing
|
| 123 |
+
B_MASS = 0.18
|
| 124 |
+
B_COM = 0.090 # above the bottom
|
| 125 |
+
B_MU = 0.8
|
| 126 |
+
CAP_MU_T = 0.0005 # torsional friction of the cap (condim 4): the grasped cap turns freely
|
| 127 |
+
NECK_MU_T = 0.01 # torsional friction of the neck (condim 4): a bottle pinched by its neck does not swing
|
| 128 |
+
NECK_GRASP = H_TOT - 0.027 # scripted grasp height above the bottom: the palm (3.1 cm above the grasp point between
|
| 129 |
+
# the fingers, measured) clears the cap top by 4 mm; the pads hold the neck top and the cap
|
| 130 |
+
|
| 131 |
+
# ---------------------------------------------------------------- cubes
|
| 132 |
+
CUBES = ("red_cube_1", "blue_cube_1")
|
| 133 |
+
CUBE_COLOR = {"red_cube_1": "red", "blue_cube_1": "blue"}
|
| 134 |
+
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))
|
| 135 |
+
CUBE_E = 0.032
|
| 136 |
+
CUBE_DENS = 700.0 # 23 g
|
| 137 |
+
|
| 138 |
+
# ---------------------------------------------------------------- predicates / monitor
|
| 139 |
+
UPRIGHT = np.radians(10.0)
|
| 140 |
+
TILT_START = np.radians(6.0) # a standing bottle beyond this has started to fall (it tips at ~6.8 deg)
|
| 141 |
+
FALLEN = np.radians(40.0) # lying, or leaning on the gallery rail (45-75 deg)
|
| 142 |
+
CAB_MOVE_MAX = 0.08
|
| 143 |
+
CAB_TILT_MAX = np.radians(10.0)
|
| 144 |
+
DEBOUNCE = 10 # control steps (0.5 s) a predicate change must persist (checked every other step)
|
| 145 |
+
WIN_ROBOT = 40 # control steps: a robot contact this recent can explain a loss
|
| 146 |
+
WIN_SLAM = 60
|
| 147 |
+
|
| 148 |
+
# ---------------------------------------------------------------- scripted motion
|
| 149 |
+
NAIVE_ERR = 0.008 # Sonnet's placement error 0.4-1.3 cm
|
| 150 |
+
FINGER_AHEAD = 0.021 # closed fingertips reach this far ahead of the grasp point (yaw 0, +x) -- measured
|
| 151 |
+
REACH_MAX = 0.78 # scripted policies: farthest grasp point at table height (horizontal distance from the base)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def _box(name, pos, size, rgba, extra, vis=True, vis_rgba=None):
|
| 155 |
+
s = [f'<geom name="{name}" type="box" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(rgba)}" {extra} group="0"/>']
|
| 156 |
+
if vis:
|
| 157 |
+
s.append(f'<geom type="box" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(vis_rgba or rgba)}" contype="0" '
|
| 158 |
+
f'conaffinity="0" group="1"/>')
|
| 159 |
+
return s
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def cabinet_xml(name):
|
| 163 |
+
"""free carcass (bottom, top, two sides, back) + a drawer on a slide joint along -x (opening towards the robot).
|
| 164 |
+
Carcass geoms contype 2 / conaffinity 1, drawer geoms contype 4 / conaffinity 1: they never collide with each other
|
| 165 |
+
but both collide with the robot, the table and the free objects (contype / conaffinity 1). The slide joint comes
|
| 166 |
+
first in the object's joint list (robosuite appends the free joint), see DrawerCabinet.__init__."""
|
| 167 |
+
hx, hy = CD / 2, CW / 2
|
| 168 |
+
cg = 'friction="0.8 0.005 0.0001" contype="2" conaffinity="1" solimp="0.95 0.99 0.001" solref="0.004 1"'
|
| 169 |
+
carc = []
|
| 170 |
+
carc += _box(f"{name}_bottom", (-PLINTH / 2, 0, CT / 2), (hx + PLINTH / 2, hy, CT / 2), WOOD_D, cg)
|
| 171 |
+
carc += _box(f"{name}_top", (0, 0, CH - CT / 2), (hx, hy, CT / 2), WOOD, cg)
|
| 172 |
+
carc += _box(f"{name}_side_l", (0, hy - CT / 2, CH / 2), (hx, CT / 2, CH / 2 - CT), WOOD, cg)
|
| 173 |
+
carc += _box(f"{name}_side_r", (0, -hy + CT / 2, CH / 2), (hx, CT / 2, CH / 2 - CT), WOOD, cg)
|
| 174 |
+
carc += _box(f"{name}_back", (hx - CT / 2, 0, CH / 2), (CT / 2, hy - CT, CH / 2 - CT), WOOD, cg)
|
| 175 |
+
carc += _box(f"{name}_rail", (hx - RAIL_T / 2, 0, CH + RAIL_H / 2), (RAIL_T / 2, hy, RAIL_H / 2), WOOD_D, cg)
|
| 176 |
+
dg = 'friction="0.8 0.005 0.0001" contype="4" conaffinity="1" solimp="0.95 0.99 0.001" solref="0.004 1"'
|
| 177 |
+
x0 = -hx # inner face of the front panel (closed)
|
| 178 |
+
zf = D_FLOOR
|
| 179 |
+
dr = []
|
| 180 |
+
dr += _box(f"{name}_front", (x0 - PF / 2, 0, (CT + 0.002 + CH - 0.004) / 2), (PF / 2, hy, (CH - 0.006 - CT) / 2),
|
| 181 |
+
PANEL, dg)
|
| 182 |
+
dr += _box(f"{name}_dfloor", (x0 + DL / 2, 0, zf + DWT / 2), (DL / 2, D_IN_Y + DWT, DWT / 2), INNER, dg)
|
| 183 |
+
zw = zf + DWT + DWH / 2
|
| 184 |
+
dr += _box(f"{name}_dside_l", (x0 + DL / 2, D_IN_Y + DWT / 2, zw), (DL / 2, DWT / 2, DWH / 2), INNER, dg)
|
| 185 |
+
dr += _box(f"{name}_dside_r", (x0 + DL / 2, -D_IN_Y - DWT / 2, zw), (DL / 2, DWT / 2, DWH / 2), INNER, dg)
|
| 186 |
+
dr += _box(f"{name}_dback", (x0 + DL - DWT / 2, 0, zw), (DWT / 2, D_IN_Y, DWH / 2), INNER, dg)
|
| 187 |
+
# flush finger pull (visual only): a dark slot near the top of the front panel
|
| 188 |
+
dr.append(f'<geom type="box" pos="{_fmt((x0 - PF - 0.0005, 0, CH - 0.022))}" size="0.0008 0.035 0.006" '
|
| 189 |
+
f'rgba="{_fmt(SLOT)}" contype="0" conaffinity="0" group="1"/>')
|
| 190 |
+
m = DRAWER_MASS
|
| 191 |
+
ixx, iyy, izz = m * (CW ** 2 + 0.06 ** 2) / 12, m * (DL ** 2 + 0.06 ** 2) / 12, m * (DL ** 2 + CW ** 2) / 12
|
| 192 |
+
drawer = (f'<body name="drawer" pos="0 0 0">\n'
|
| 193 |
+
f' <inertial pos="{x0 + DL * 0.4:.4f} 0 0.04" mass="{m}" diaginertia="{ixx:.6f} {iyy:.6f} {izz:.6f}"/>\n'
|
| 194 |
+
f' <joint name="{name}_slide" type="slide" axis="-1 0 0" pos="0 0 0" limited="true" range="0 {Q_MAX}" '
|
| 195 |
+
f'frictionloss="{SLIDE_FRIC}" damping="0.3" armature="0.01" solreflimit="0.004 1" '
|
| 196 |
+
f'solimplimit="0.95 0.99 0.001"/>\n' + "\n".join(" " + s for s in dr) + "\n</body>")
|
| 197 |
+
m0 = 0.4
|
| 198 |
+
inertial = (f'<inertial pos="{CAB_COM_X:.4f} 0 {CH * 0.5:.4f}" mass="{m0}" diaginertia="{m0 * (CW ** 2 + CH ** 2) / 12:.6f} '
|
| 199 |
+
f'{m0 * (CD ** 2 + CH ** 2) / 12:.6f} {m0 * (CD ** 2 + CW ** 2) / 12:.6f}"/>')
|
| 200 |
+
body = "\n ".join([inertial] + carc + drawer.split("\n"))
|
| 201 |
+
return f"""<mujoco model="{name}">
|
| 202 |
+
<worldbody>
|
| 203 |
+
<body>
|
| 204 |
+
<body name="object">
|
| 205 |
+
{body}
|
| 206 |
+
</body>
|
| 207 |
+
<site rgba="0 0 0 0" size="0.005" pos="0 0 0" name="bottom_site" />
|
| 208 |
+
<site rgba="0 0 0 0" size="0.005" pos="0 0 {CH:.4f}" name="top_site" />
|
| 209 |
+
<site rgba="0 0 0 0" size="0.005" pos="{CD / 2:.4f} {CW / 2:.4f} 0" name="horizontal_radius_site" />
|
| 210 |
+
</body>
|
| 211 |
+
</worldbody>
|
| 212 |
+
</mujoco>"""
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def bottle_xml(name, rgba, cap_rgba):
|
| 216 |
+
"""square bottle: rounded base (narrow flat foot), body, shoulder, neck, ball cap; origin at mid height"""
|
| 217 |
+
h = H_TOT / 2
|
| 218 |
+
zf, zb, zs, zn = -h + HF / 2, -h + HF + (HB - HF) / 2, -h + HB + HS / 2, -h + HB + HS + HN / 2
|
| 219 |
+
zk = -h + HB + HS + HN + RK - CAP_SINK
|
| 220 |
+
m = B_MASS
|
| 221 |
+
ixx = m * ((2 * RB) ** 2 + H_TOT ** 2) / 14
|
| 222 |
+
izz = m * (2 * (2 * RB) ** 2) / 12
|
| 223 |
+
fr = f'friction="{B_MU} 0.005 0.0001"'
|
| 224 |
+
sol = 'solimp="0.95 0.99 0.001" solref="0.005 1"'
|
| 225 |
+
parts = [("foot", "box", (0, 0, zf), (RF, RF, HF / 2), rgba, fr + ' priority="2"'),
|
| 226 |
+
("body", "box", (0, 0, zb), (RB, RB, (HB - HF) / 2), rgba, fr),
|
| 227 |
+
("shoulder", "box", (0, 0, zs), (RS, RS, HS / 2), rgba, fr),
|
| 228 |
+
("neck", "cylinder", (0, 0, zn), (RN, HN / 2), rgba,
|
| 229 |
+
f'friction="{B_MU} {NECK_MU_T} 0.0001" condim="4" priority="2"'),
|
| 230 |
+
("cap", "sphere", (0, 0, zk), (RK,), cap_rgba, f'friction="1 {CAP_MU_T} 0.0001" condim="4" priority="2"')]
|
| 231 |
+
s = [f' <inertial pos="0 0 {-h + B_COM:.4f}" mass="{m}" diaginertia="{ixx:.6f} {ixx:.6f} {izz:.6f}" />']
|
| 232 |
+
for nm, typ, pos, size, c, extra in parts:
|
| 233 |
+
s.append(f' <geom name="{name}_{nm}" type="{typ}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(c)}" '
|
| 234 |
+
f'{extra} {sol} group="0" />')
|
| 235 |
+
if nm != "foot":
|
| 236 |
+
s.append(f' <geom type="{typ}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(c)}" contype="0" '
|
| 237 |
+
f'conaffinity="0" group="1" />')
|
| 238 |
+
# rounded base (visual): a slightly narrower bottom band, and a label
|
| 239 |
+
s.append(f' <geom type="box" pos="0 0 {zf:.4f}" size="{RB - 0.004:.4f} {RB - 0.004:.4f} {HF / 2:.4f}" '
|
| 240 |
+
f'rgba="{_fmt(rgba)}" contype="0" conaffinity="0" group="1" />')
|
| 241 |
+
s.append(f' <geom type="box" pos="0 0 {zb + 0.005:.4f}" size="{RB + 0.0008:.4f} {RB + 0.0008:.4f} 0.028" '
|
| 242 |
+
f'rgba="0.92 0.90 0.80 1" contype="0" conaffinity="0" group="1" />')
|
| 243 |
+
return _wrap(name, "\n".join(s), h, RB * 1.42)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def _fb(v):
|
| 247 |
+
return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}"
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def _lr(v):
|
| 251 |
+
return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}"
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def _reach(p):
|
| 255 |
+
return float(np.hypot(p[0] + 0.66, p[1]))
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
class DrawerSkills(Skills):
|
| 259 |
+
"""Skills that feed the task's per-step monitor."""
|
| 260 |
+
|
| 261 |
+
def __init__(self, env, task, recorder=None):
|
| 262 |
+
super().__init__(env, recorder=recorder)
|
| 263 |
+
self.task = task
|
| 264 |
+
|
| 265 |
+
def _act(self, dpos, drot, grip):
|
| 266 |
+
super()._act(dpos, drot, grip)
|
| 267 |
+
self.task.monitor_step()
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
@register_task
|
| 271 |
+
class DrawerCabinet(LFFTask):
|
| 272 |
+
name = "lh_drawer_cabinet"
|
| 273 |
+
level = "L2"
|
| 274 |
+
category = "state_restoration"
|
| 275 |
+
capabilities = ("Perceive", "Reason", "Restore", "Plan")
|
| 276 |
+
protocol = "cross"
|
| 277 |
+
max_attempts = 3
|
| 278 |
+
# careful: 2 bottles x ~8 commands + 3 cubes x ~6 + closing the drawer ~5 + looking ~15; standing 2 fallen bottles
|
| 279 |
+
# up again ~20; + slack
|
| 280 |
+
agent_max_steps = 120
|
| 281 |
+
instruction = ("Tidy up the table: stand the green bottle and the brown bottle upright on top of the small wooden "
|
| 282 |
+
"cabinet, put the red cube and the blue cube into the cabinet's open drawer (it is pulled "
|
| 283 |
+
"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 "
|
| 284 |
+
"the closed drawer, the cabinet must still stand where it is, and the gripper must be open and not "
|
| 285 |
+
"touching anything. (Each bottle has a round cap; held by its cap, a bottle hangs straight down.)")
|
| 286 |
+
instruction_indirect = ("Clean up: set the two tall bottles (the green one and the brown one) upright on the little "
|
| 287 |
+
"wooden cabinet, drop the two small cubes (red and blue) into its pulled-out drawer and "
|
| 288 |
+
"shut the drawer. In the end both bottles stand on top of the cabinet, the cubes are inside the shut drawer, "
|
| 289 |
+
"the cabinet stays in its place, and the open gripper touches nothing. (A bottle held by "
|
| 290 |
+
"its round cap hangs straight down.)")
|
| 291 |
+
agent_object_names = ["green bottle (yellow round cap)", "brown bottle (blue round cap)", "red cube", "blue cube",
|
| 292 |
+
"small wooden cabinet with its drawer pulled out (the drawer front faces the robot)"]
|
| 293 |
+
|
| 294 |
+
# ------------------------------------------------------------ scene
|
| 295 |
+
def make_bddl(self):
|
| 296 |
+
cab = register_generated("LffLhdCabinet", cabinet_xml(CAB_MODEL))
|
| 297 |
+
objs = [(CAB, cab, "cabinet_region", (0.10, -0.02, 0.12, 0.0))]
|
| 298 |
+
for i, b in enumerate(BOTTLES):
|
| 299 |
+
c = B_NAME[b]
|
| 300 |
+
cat = register_generated(f"LffLhdBottle{c.title()}", bottle_xml(f"lff_lhd_bottle_{c}", B_RGBA[b], CAP_RGBA[b]))
|
| 301 |
+
objs.append((b, cat, f"{c}_bottle_region", (-0.30, 0.20 + 0.13 * i, -0.28, 0.22 + 0.13 * i)))
|
| 302 |
+
for i, n in enumerate(CUBES):
|
| 303 |
+
c = CUBE_COLOR[n]
|
| 304 |
+
cat = register_generated(f"LffLhdCube{c.title()}",
|
| 305 |
+
box_xml(f"lff_lhd_cube_{c}", (CUBE_E / 2,) * 3, CUBE_RGBA[c], density=CUBE_DENS,
|
| 306 |
+
friction=(0.8, 0.005, 0.0001)))
|
| 307 |
+
objs.append((n, cat, f"{c}_cube_region", (-0.30, -0.45 + 0.13 * i, -0.28, -0.43 + 0.13 * i)))
|
| 308 |
+
return write_bddl(self.name, "tidy up the table", objs, [])
|
| 309 |
+
|
| 310 |
+
def __init__(self, cam_res=None):
|
| 311 |
+
super().__init__(cam_res)
|
| 312 |
+
m = self.env.sim.model
|
| 313 |
+
pre = f"{CAB}_{CAB_MODEL}"
|
| 314 |
+
self.jid = m.joint_name2id(pre + "_slide")
|
| 315 |
+
self.qa = int(m.jnt_qposadr[self.jid])
|
| 316 |
+
self.dof = int(m.jnt_dofadr[self.jid])
|
| 317 |
+
self.cab_bid = envs.body_id(self.env, CAB)
|
| 318 |
+
self.drawer_bid = m.body_name2id(f"{CAB}_drawer")
|
| 319 |
+
# the cabinet's free joint is the LAST of its joints (robosuite appends it after the drawer slide), so
|
| 320 |
+
# envs.free_joint_addr / place_upright (joints[0]) must not be used for it
|
| 321 |
+
fj = m.joint_name2id(self.env.objects_dict[CAB].joints[-1])
|
| 322 |
+
assert int(m.jnt_type[fj]) == 0
|
| 323 |
+
self.cab_qa, self.cab_da = int(m.jnt_qposadr[fj]), int(m.jnt_dofadr[fj])
|
| 324 |
+
self.feet_gid = m.geom_name2id(pre + "_bottom")
|
| 325 |
+
self.cab_gids = {g for g in range(m.ngeom) if m.geom_bodyid[g] in (self.cab_bid, self.drawer_bid)
|
| 326 |
+
and m.geom_contype[g] != 0}
|
| 327 |
+
self.bottle_gids = {b: set(envs.obj_geom_ids(self.env, b)) for b in BOTTLES}
|
| 328 |
+
self.cube_gids = {c: set(envs.obj_geom_ids(self.env, c)) for c in CUBES}
|
| 329 |
+
self.cap_gid = {b: m.geom_name2id(f"{b}_lff_lhd_bottle_{B_NAME[b]}_cap") for b in BOTTLES}
|
| 330 |
+
# per-geom lookup tables for the substep contact scan
|
| 331 |
+
self.part = np.zeros(m.ngeom, int) # 1 = hand / fingers, 2 = arm links
|
| 332 |
+
for g in envs.robot_geom_ids(self.env):
|
| 333 |
+
n = m.geom_id2name(g) or ""
|
| 334 |
+
self.part[g] = 1 if n.startswith("gripper0_") else 2
|
| 335 |
+
self.bidx = np.full(m.ngeom, -1, int)
|
| 336 |
+
for i, b in enumerate(BOTTLES):
|
| 337 |
+
self.bidx[list(self.bottle_gids[b])] = i
|
| 338 |
+
self.task_obj = np.zeros(m.ngeom, bool)
|
| 339 |
+
for s in list(self.bottle_gids.values()) + list(self.cube_gids.values()) + [self.cab_gids]:
|
| 340 |
+
self.task_obj[list(s)] = True
|
| 341 |
+
self.catch = dict(force=0.0, zone=ZONE, damp=0.0)
|
| 342 |
+
sim = self.env.sim
|
| 343 |
+
if not getattr(sim, "_lhd_wrapped", False):
|
| 344 |
+
orig = sim.step
|
| 345 |
+
|
| 346 |
+
def step(*a, **k):
|
| 347 |
+
orig(*a, **k)
|
| 348 |
+
t = getattr(sim, "_lhd_task", None)
|
| 349 |
+
if t is not None:
|
| 350 |
+
t._substep()
|
| 351 |
+
sim.step = step
|
| 352 |
+
sim._lhd_wrapped = True
|
| 353 |
+
sim._lhd_task = self
|
| 354 |
+
self.inst = None
|
| 355 |
+
self.mon = None
|
| 356 |
+
self.sk = None
|
| 357 |
+
self._sub = {}
|
| 358 |
+
|
| 359 |
+
# ------------------------------------------------------------ drawer mechanism (every MuJoCo substep)
|
| 360 |
+
def q(self):
|
| 361 |
+
return float(self.env.sim.data.qpos[self.qa])
|
| 362 |
+
|
| 363 |
+
def catch_force(self, q, qd):
|
| 364 |
+
"""generalised force on the slide (positive = opening): inside the last ZONE of travel a constant pull towards
|
| 365 |
+
closed (ramped in over 5 mm), plus a damper on closing motion for soft-close drawers"""
|
| 366 |
+
c = self.catch
|
| 367 |
+
z = c["zone"]
|
| 368 |
+
if q >= z or c["force"] <= 0:
|
| 369 |
+
return 0.0
|
| 370 |
+
ramp = float(np.clip((z - q) / 0.005, 0.0, 1.0))
|
| 371 |
+
f = -c["force"] * ramp
|
| 372 |
+
if qd < 0 and c["damp"] > 0:
|
| 373 |
+
f -= c["damp"] * qd * ramp
|
| 374 |
+
return f
|
| 375 |
+
|
| 376 |
+
def _substep(self):
|
| 377 |
+
d = self.env.sim.data
|
| 378 |
+
q, qd = float(d.qpos[self.qa]), float(d.qvel[self.dof])
|
| 379 |
+
d.qfrc_applied[self.dof] = self.catch_force(q, qd)
|
| 380 |
+
if self.mon is None:
|
| 381 |
+
return
|
| 382 |
+
sub = self._sub
|
| 383 |
+
# slam detection: the closing speed just before the drawer reaches its stop
|
| 384 |
+
if q > 0.002:
|
| 385 |
+
sub["approach_v"] = -qd
|
| 386 |
+
sub["armed"] = True
|
| 387 |
+
if q < self.catch["zone"] and sub.get("zone_xy") is None:
|
| 388 |
+
sub["zone_xy"] = self.cab_xy().tolist()
|
| 389 |
+
elif q > self.catch["zone"] + 0.005:
|
| 390 |
+
sub["zone_xy"] = None
|
| 391 |
+
elif sub.get("armed"):
|
| 392 |
+
sub["armed"] = False
|
| 393 |
+
v = float(sub.get("approach_v", 0.0))
|
| 394 |
+
sub.setdefault("impacts", []).append((v, sub.get("zone_xy")))
|
| 395 |
+
sub["zone_xy"] = None
|
| 396 |
+
n = d.ncon
|
| 397 |
+
if not n:
|
| 398 |
+
return
|
| 399 |
+
g1 = np.asarray(d.contact.geom1)[:n]
|
| 400 |
+
g2 = np.asarray(d.contact.geom2)[:n]
|
| 401 |
+
for a, b in zip(g1, g2):
|
| 402 |
+
ia, ib = self.bidx[a], self.bidx[b]
|
| 403 |
+
if ia < 0 and ib < 0:
|
| 404 |
+
continue
|
| 405 |
+
if ia >= 0 and ib >= 0:
|
| 406 |
+
if ia != ib:
|
| 407 |
+
sub.setdefault("bb", set()).update((int(ia), int(ib)))
|
| 408 |
+
continue
|
| 409 |
+
i, o = (ia, b) if ia >= 0 else (ib, a)
|
| 410 |
+
p = int(self.part[o])
|
| 411 |
+
if p:
|
| 412 |
+
r = sub.setdefault("rob", {})
|
| 413 |
+
r[int(i)] = 2 if (p == 2 or r.get(int(i)) == 2) else 1
|
| 414 |
+
|
| 415 |
+
# ------------------------------------------------------------ instances
|
| 416 |
+
def sample_instance(self, seed):
|
| 417 |
+
rng = np.random.default_rng(seed)
|
| 418 |
+
slam = bool((int(seed) * 7) % 20 < round(20 * P_SLAM)) # balanced: 14 of every 20 consecutive seeds
|
| 419 |
+
cx, cy = float(rng.uniform(-0.13, -0.10)), float(rng.uniform(-0.04, 0.04))
|
| 420 |
+
s = 1.0 if rng.random() < 0.5 else -1.0 # bottles on the left (+1) or right (-1), cubes on the other side
|
| 421 |
+
bottles = {}
|
| 422 |
+
order = rng.permutation(2)
|
| 423 |
+
for j, i in enumerate(order):
|
| 424 |
+
bx = cx + (-0.05, 0.05)[j] + float(rng.uniform(-0.01, 0.01))
|
| 425 |
+
bottles[BOTTLES[i]] = [bx, cy + s * float(rng.uniform(0.21, 0.24))]
|
| 426 |
+
perm = rng.permutation(2)
|
| 427 |
+
# cubes 25-29 cm to the side of the cabinet's centre line: picked from nearer, the forearm sweeps over the
|
| 428 |
+
# cabinet top and knocks the bottles standing there (measured feasibility map, see the task card)
|
| 429 |
+
cubes = {CUBES[i]: [cx + (-0.16, -0.04)[j] + float(rng.uniform(-0.01, 0.01)),
|
| 430 |
+
cy - s * float(rng.uniform(0.25, 0.29))] for j, i in enumerate(perm)}
|
| 431 |
+
force = float(rng.uniform(*F_SPRING))
|
| 432 |
+
soft_v = float(rng.uniform(*SOFT_V))
|
| 433 |
+
return dict(seed=int(seed), self_closing=slam, drawer="self-closing" if slam else "soft-close",
|
| 434 |
+
cab_xy=[cx, cy], bottle_side="left" if s > 0 else "right", bottle_start=bottles,
|
| 435 |
+
bottle_yaw={b: float(rng.uniform(-0.3, 0.3)) for b in BOTTLES}, cube_start=cubes,
|
| 436 |
+
cube_yaw={c: float(rng.uniform(-0.3, 0.3)) for c in CUBES},
|
| 437 |
+
spring_n=force, damp=0.0 if slam else force / soft_v,
|
| 438 |
+
carcass_kg=float(rng.uniform(*CARCASS_MASS)), feet_mu=float(rng.uniform(*FEET_MU)),
|
| 439 |
+
naive_noise_seed=int(rng.integers(1 << 30)))
|
| 440 |
+
|
| 441 |
+
def apply_instance(self, inst):
|
| 442 |
+
self.inst = inst
|
| 443 |
+
m = self.env.sim.model
|
| 444 |
+
M = float(inst["carcass_kg"])
|
| 445 |
+
m.body_mass[self.cab_bid] = M
|
| 446 |
+
m.body_inertia[self.cab_bid] = [M * (CW ** 2 + CH ** 2) / 12, M * (CD ** 2 + CH ** 2) / 12,
|
| 447 |
+
M * (CD ** 2 + CW ** 2) / 12]
|
| 448 |
+
m.geom_friction[self.feet_gid] = [float(inst["feet_mu"]), 0.005, 0.0001]
|
| 449 |
+
m.geom_priority[self.feet_gid] = 3
|
| 450 |
+
self.catch = dict(force=float(inst["spring_n"]), zone=ZONE, damp=float(inst["damp"]))
|
| 451 |
+
self.set_drawer(Q_OPEN)
|
| 452 |
+
self.place_cabinet(inst["cab_xy"], 0.0)
|
| 453 |
+
for b in BOTTLES:
|
| 454 |
+
envs.place_upright(self.env, b, inst["bottle_start"][b], yaw=inst["bottle_yaw"][b], clearance=0.0005)
|
| 455 |
+
for c in CUBES:
|
| 456 |
+
envs.place_upright(self.env, c, inst["cube_start"][c], yaw=inst["cube_yaw"][c], clearance=0.001)
|
| 457 |
+
|
| 458 |
+
def set_drawer(self, q):
|
| 459 |
+
d = self.env.sim.data
|
| 460 |
+
d.qpos[self.qa] = q
|
| 461 |
+
d.qvel[self.dof] = 0.0
|
| 462 |
+
|
| 463 |
+
def place_cabinet(self, xy, yaw=0.0, clearance=0.0005):
|
| 464 |
+
d = self.env.sim.data
|
| 465 |
+
a, v = self.cab_qa, self.cab_da
|
| 466 |
+
d.qpos[a:a + 3] = [xy[0], xy[1], Z + clearance] # body origin = bottom of the carcass
|
| 467 |
+
d.qpos[a + 3:a + 7] = [np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)]
|
| 468 |
+
d.qvel[v:v + 6] = 0.0
|
| 469 |
+
self.env.sim.forward()
|
| 470 |
+
|
| 471 |
+
def reset_instance(self, inst, recorder=None):
|
| 472 |
+
self.mon = None
|
| 473 |
+
self.env.reset()
|
| 474 |
+
self.apply_instance(inst)
|
| 475 |
+
self.env.sim.forward()
|
| 476 |
+
envs.settle(self.env, 15)
|
| 477 |
+
self.sk = DrawerSkills(self.env, self, recorder=recorder)
|
| 478 |
+
self._sub = {}
|
| 479 |
+
self._init_monitor()
|
| 480 |
+
return self.sk
|
| 481 |
+
|
| 482 |
+
# ------------------------------------------------------------ geometry helpers (world frame)
|
| 483 |
+
def cab_R(self):
|
| 484 |
+
return self.env.sim.data.body_xmat[self.cab_bid].reshape(3, 3).copy()
|
| 485 |
+
|
| 486 |
+
def cab_origin(self):
|
| 487 |
+
return self.env.sim.data.body_xpos[self.cab_bid].copy()
|
| 488 |
+
|
| 489 |
+
def cab_xy(self):
|
| 490 |
+
return self.cab_origin()[:2]
|
| 491 |
+
|
| 492 |
+
def to_cab(self, p):
|
| 493 |
+
"""world point -> cabinet frame (x forward, origin at the footprint centre on the floor)"""
|
| 494 |
+
return self.cab_R().T @ (np.asarray(p, float) - self.cab_origin())
|
| 495 |
+
|
| 496 |
+
def from_cab(self, p):
|
| 497 |
+
return self.cab_origin() + self.cab_R() @ np.asarray(p, float)
|
| 498 |
+
|
| 499 |
+
def top_z(self):
|
| 500 |
+
return float(self.from_cab([0.0, 0.0, CH])[2])
|
| 501 |
+
|
| 502 |
+
def cab_front_x(self):
|
| 503 |
+
"""world x of the carcass's front face (cabinet assumed close to yaw 0)"""
|
| 504 |
+
return float(self.from_cab([-CD / 2, 0.0, 0.0])[0])
|
| 505 |
+
|
| 506 |
+
def drawer_front_x(self):
|
| 507 |
+
"""world x of the drawer front panel's outer face"""
|
| 508 |
+
return self.cab_front_x() - self.q() - PF
|
| 509 |
+
|
| 510 |
+
def cab_tilt(self):
|
| 511 |
+
return float(np.arccos(np.clip(self.cab_R()[2, 2], -1.0, 1.0)))
|
| 512 |
+
|
| 513 |
+
def cab_moved(self):
|
| 514 |
+
return float(np.linalg.norm(self.cab_xy() - np.asarray(self.inst["cab_xy"])))
|
| 515 |
+
|
| 516 |
+
def R(self, name):
|
| 517 |
+
return self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3).copy()
|
| 518 |
+
|
| 519 |
+
def tilt(self, name):
|
| 520 |
+
return float(np.arccos(np.clip(self.R(name)[2, 2], -1.0, 1.0)))
|
| 521 |
+
|
| 522 |
+
def bottle_base(self, b):
|
| 523 |
+
"""world position of the centre of the bottle's bottom face"""
|
| 524 |
+
return envs.obj_pos(self.env, b) - self.R(b)[:, 2] * H_TOT / 2
|
| 525 |
+
|
| 526 |
+
def cap_xyz(self, b):
|
| 527 |
+
return self.env.sim.data.geom_xpos[self.cap_gid[b]].copy()
|
| 528 |
+
|
| 529 |
+
def held(self, name):
|
| 530 |
+
return self.sk is not None and self.sk.holding(name)
|
| 531 |
+
|
| 532 |
+
# ------------------------------------------------------------ stage predicates
|
| 533 |
+
def bottle_on_top(self, b, tol=0.0, tilt=UPRIGHT):
|
| 534 |
+
if self.tilt(b) > tilt or self.held(b):
|
| 535 |
+
return False
|
| 536 |
+
c = self.to_cab(self.bottle_base(b))
|
| 537 |
+
if c[0] < -CD / 2 + RF - tol or c[0] > CD / 2 - RAIL_T - RF + tol or abs(c[1]) > CW / 2 - RF + tol:
|
| 538 |
+
return False
|
| 539 |
+
return bool(-0.006 <= c[2] - CH <= 0.012)
|
| 540 |
+
|
| 541 |
+
def cube_in_drawer(self, c):
|
| 542 |
+
"""cube centre inside the drawer box (drawer frame), its footprint within the walls (+3 mm), resting low enough
|
| 543 |
+
to pass under the cabinet top; not held"""
|
| 544 |
+
if self.held(c):
|
| 545 |
+
return False
|
| 546 |
+
d = self.env.sim.data
|
| 547 |
+
Rd = d.body_xmat[self.drawer_bid].reshape(3, 3)
|
| 548 |
+
p = Rd.T @ (envs.obj_pos(self.env, c) - d.body_xpos[self.drawer_bid])
|
| 549 |
+
x0 = -CD / 2
|
| 550 |
+
e = CUBE_E / 2 * 1.2 # footprint half size (a yawed cube reaches a little farther)
|
| 551 |
+
tol = 0.003
|
| 552 |
+
return bool(x0 + e - tol <= p[0] <= x0 + D_IN_X - e + tol and abs(p[1]) <= D_IN_Y - e + tol
|
| 553 |
+
and FLOOR_TOP - 0.005 <= p[2] - CUBE_E / 2 <= FLOOR_TOP + DWH + 0.01)
|
| 554 |
+
|
| 555 |
+
def drawer_closed(self):
|
| 556 |
+
return self.q() <= CLOSED
|
| 557 |
+
|
| 558 |
+
def stage_keys(self):
|
| 559 |
+
return [f"{B_NAME[b]}_bottle_on_top" for b in BOTTLES] + [f"{CUBE_COLOR[c]}_cube_in_drawer" for c in CUBES] + [
|
| 560 |
+
"drawer_closed"]
|
| 561 |
+
|
| 562 |
+
def stage_values(self, hyst=None):
|
| 563 |
+
hyst = hyst or {}
|
| 564 |
+
v = {}
|
| 565 |
+
for b in BOTTLES:
|
| 566 |
+
k = f"{B_NAME[b]}_bottle_on_top"
|
| 567 |
+
v[k] = self.bottle_on_top(b, 0.003, UPRIGHT + np.radians(3.0)) if hyst.get(k) else self.bottle_on_top(b)
|
| 568 |
+
for c in CUBES:
|
| 569 |
+
v[f"{CUBE_COLOR[c]}_cube_in_drawer"] = self.cube_in_drawer(c)
|
| 570 |
+
v["drawer_closed"] = self.q() <= (CLOSED + 0.003 if hyst.get("drawer_closed") else CLOSED)
|
| 571 |
+
return v
|
| 572 |
+
|
| 573 |
+
# ------------------------------------------------------------ per-step monitor
|
| 574 |
+
def _init_monitor(self):
|
| 575 |
+
keys = self.stage_keys()
|
| 576 |
+
st = {k: False for k in keys}
|
| 577 |
+
self.mon = dict(state=st, ever=[], lost=[], lost_cause={}, events=[], cand={k: 0 for k in keys}, step=0,
|
| 578 |
+
last_robot=[None, None], last_bb=None, slams=[], standing_since=[None, None],
|
| 579 |
+
fall_start=[None, None], touched_before_fall=[False, False], max_tilt=[0.0, 0.0],
|
| 580 |
+
n_fallen=0, fallen=[False, False])
|
| 581 |
+
|
| 582 |
+
def monitor_step(self):
|
| 583 |
+
mon = self.mon
|
| 584 |
+
if mon is None or self.sk is None:
|
| 585 |
+
return
|
| 586 |
+
mon["step"] += 1
|
| 587 |
+
t = int(self.sk.n_steps)
|
| 588 |
+
sub, self._sub = self._sub, {k: v for k, v in self._sub.items() if k in ("approach_v", "armed", "zone_xy")}
|
| 589 |
+
for i, part in sub.get("rob", {}).items():
|
| 590 |
+
b = BOTTLES[i]
|
| 591 |
+
if not self.held(b):
|
| 592 |
+
mon["last_robot"][i] = ["hand" if part == 1 else "arm", t, round(float(np.degrees(self.tilt(b))), 1)]
|
| 593 |
+
if sub.get("bb"):
|
| 594 |
+
mon["last_bb"] = t
|
| 595 |
+
for v, zxy in sub.get("impacts", []):
|
| 596 |
+
if v >= V_SLAM:
|
| 597 |
+
lurch = None
|
| 598 |
+
if zxy is not None:
|
| 599 |
+
dxy = self.cab_xy() - np.asarray(zxy)
|
| 600 |
+
lurch = [round(100 * float(dxy[0]), 2), round(100 * float(dxy[1]), 2)]
|
| 601 |
+
on = [B_NAME[b] for b in BOTTLES if mon["state"][f"{B_NAME[b]}_bottle_on_top"]]
|
| 602 |
+
e = dict(event="drawer_slam", step=t, speed_mps=round(float(v), 2), cabinet_jerk_cm=lurch,
|
| 603 |
+
bottles_on_top=on, bottles_fell=[], robot_touched_before_fall=[])
|
| 604 |
+
mon["events"].append(e)
|
| 605 |
+
mon["slams"].append(e)
|
| 606 |
+
else:
|
| 607 |
+
mon["events"].append(dict(event="drawer_shut", step=t, speed_mps=round(float(v), 3)))
|
| 608 |
+
# fall tracking (R4: did the robot touch a bottle before it started to fall?)
|
| 609 |
+
for i, b in enumerate(BOTTLES):
|
| 610 |
+
tl = self.tilt(b)
|
| 611 |
+
mon["max_tilt"][i] = max(mon["max_tilt"][i], float(np.degrees(tl)))
|
| 612 |
+
if self.held(b):
|
| 613 |
+
mon["standing_since"][i] = None
|
| 614 |
+
continue
|
| 615 |
+
if tl < np.radians(3.0):
|
| 616 |
+
if mon["standing_since"][i] is None:
|
| 617 |
+
mon["standing_since"][i] = t
|
| 618 |
+
mon["fall_start"][i] = None
|
| 619 |
+
elif tl > TILT_START and mon["standing_since"][i] is not None and mon["fall_start"][i] is None:
|
| 620 |
+
mon["fall_start"][i] = t
|
| 621 |
+
lr = mon["last_robot"][i]
|
| 622 |
+
mon["touched_before_fall"][i] = bool(lr is not None and t - lr[1] <= 20 and lr[2] < np.degrees(TILT_START))
|
| 623 |
+
if not mon["fallen"][i] and tl > FALLEN:
|
| 624 |
+
mon["fallen"][i] = True
|
| 625 |
+
mon["n_fallen"] += 1
|
| 626 |
+
mon["events"].append(dict(event="bottle_fell", bottle=B_NAME[b], step=t, cause=self._cause(i, t),
|
| 627 |
+
robot_touched_before_fall=bool(mon["touched_before_fall"][i]),
|
| 628 |
+
direction=self._fall_dir(b)))
|
| 629 |
+
elif mon["fallen"][i] and tl < UPRIGHT:
|
| 630 |
+
mon["fallen"][i] = False
|
| 631 |
+
if mon["step"] % 2:
|
| 632 |
+
return
|
| 633 |
+
vals = self.stage_values(hyst=mon["state"])
|
| 634 |
+
for k, now in vals.items():
|
| 635 |
+
self._check(k, now, t)
|
| 636 |
+
|
| 637 |
+
def _fall_dir(self, b):
|
| 638 |
+
ax = self.R(b)[:2, 2]
|
| 639 |
+
if np.linalg.norm(ax) < 0.2:
|
| 640 |
+
return "none"
|
| 641 |
+
return ("forward" if ax[0] > 0 else "backward") if abs(ax[0]) >= abs(ax[1]) else ("left" if ax[1] > 0 else "right")
|
| 642 |
+
|
| 643 |
+
def _cause(self, i, t):
|
| 644 |
+
"""why bottle i left the cabinet top"""
|
| 645 |
+
b = BOTTLES[i]
|
| 646 |
+
mon = self.mon
|
| 647 |
+
if self.held(b):
|
| 648 |
+
return "picked_up"
|
| 649 |
+
lr = mon["last_robot"][i]
|
| 650 |
+
robot_recent = lr is not None and t - lr[1] <= WIN_ROBOT
|
| 651 |
+
if robot_recent and mon["touched_before_fall"][i]:
|
| 652 |
+
return f"robot_{lr[0]}"
|
| 653 |
+
if robot_recent and lr[2] < np.degrees(TILT_START):
|
| 654 |
+
return f"robot_{lr[0]}"
|
| 655 |
+
if mon["slams"] and t - mon["slams"][-1]["step"] <= WIN_SLAM:
|
| 656 |
+
return "drawer_slam"
|
| 657 |
+
if mon["last_bb"] is not None and t - mon["last_bb"] <= WIN_ROBOT:
|
| 658 |
+
return "bottle"
|
| 659 |
+
if robot_recent:
|
| 660 |
+
return f"robot_{lr[0]}"
|
| 661 |
+
return "other"
|
| 662 |
+
|
| 663 |
+
def _check(self, key, now, t):
|
| 664 |
+
mon = self.mon
|
| 665 |
+
if now == mon["state"][key]:
|
| 666 |
+
mon["cand"][key] = 0
|
| 667 |
+
return
|
| 668 |
+
mon["cand"][key] += 2
|
| 669 |
+
if mon["cand"][key] < DEBOUNCE:
|
| 670 |
+
return
|
| 671 |
+
mon["cand"][key] = 0
|
| 672 |
+
mon["state"][key] = now
|
| 673 |
+
t0 = int(t - DEBOUNCE + 1)
|
| 674 |
+
if now:
|
| 675 |
+
restored = key in mon["lost"]
|
| 676 |
+
e = dict(stage=key, event="restored" if restored else "achieved", step=t0)
|
| 677 |
+
if restored:
|
| 678 |
+
e["after"] = mon["lost_cause"].get(key)
|
| 679 |
+
mon["lost"].remove(key)
|
| 680 |
+
if key not in mon["ever"]:
|
| 681 |
+
mon["ever"].append(key)
|
| 682 |
+
mon["events"].append(e)
|
| 683 |
+
return
|
| 684 |
+
if key not in mon["ever"]:
|
| 685 |
+
return
|
| 686 |
+
if key.endswith("bottle_on_top"):
|
| 687 |
+
i = [f"{B_NAME[b]}_bottle_on_top" for b in BOTTLES].index(key)
|
| 688 |
+
cause = self._cause(i, t)
|
| 689 |
+
if cause == "drawer_slam":
|
| 690 |
+
s = mon["slams"][-1]
|
| 691 |
+
if B_NAME[BOTTLES[i]] not in s["bottles_fell"]:
|
| 692 |
+
s["bottles_fell"].append(B_NAME[BOTTLES[i]])
|
| 693 |
+
s["robot_touched_before_fall"].append(bool(mon["touched_before_fall"][i]))
|
| 694 |
+
elif key == "drawer_closed":
|
| 695 |
+
cause = "opened"
|
| 696 |
+
else:
|
| 697 |
+
c = CUBES[[f"{CUBE_COLOR[x]}_cube_in_drawer" for x in CUBES].index(key)]
|
| 698 |
+
cause = "picked_up" if self.held(c) else "other"
|
| 699 |
+
if key not in mon["lost"]:
|
| 700 |
+
mon["lost"].append(key)
|
| 701 |
+
mon["lost_cause"][key] = cause
|
| 702 |
+
mon["events"].append(dict(stage=key, event="lost", step=t0, cause=cause))
|
| 703 |
+
|
| 704 |
+
def _finalize_monitor(self, vals):
|
| 705 |
+
"""close the event log at finish: a stage the debounced monitor still holds but the final judge does not (or
|
| 706 |
+
vice versa) is logged now (final=True)"""
|
| 707 |
+
mon = self.mon
|
| 708 |
+
t = int(self.sk.n_steps)
|
| 709 |
+
for k, now in vals.items():
|
| 710 |
+
if now == mon["state"][k]:
|
| 711 |
+
continue
|
| 712 |
+
n0 = len(mon["events"])
|
| 713 |
+
mon["cand"][k] = DEBOUNCE # force the transition
|
| 714 |
+
self._check(k, now, t + DEBOUNCE - 1)
|
| 715 |
+
if len(mon["events"]) > n0:
|
| 716 |
+
mon["events"][-1]["final"] = True
|
| 717 |
+
|
| 718 |
+
# ------------------------------------------------------------ outcome
|
| 719 |
+
def _static(self):
|
| 720 |
+
d = self.env.sim.data
|
| 721 |
+
for n in BOTTLES + CUBES:
|
| 722 |
+
_, da = envs.free_joint_addr(self.env, n)
|
| 723 |
+
if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5:
|
| 724 |
+
return False
|
| 725 |
+
v = self.cab_da
|
| 726 |
+
return bool(np.linalg.norm(d.qvel[v:v + 3]) < 0.02 and abs(float(d.qvel[self.dof])) < 0.02)
|
| 727 |
+
|
| 728 |
+
def robot_touching(self):
|
| 729 |
+
d = self.env.sim.data
|
| 730 |
+
out = set()
|
| 731 |
+
for j in range(d.ncon):
|
| 732 |
+
c = d.contact[j]
|
| 733 |
+
for a, b in ((c.geom1, c.geom2), (c.geom2, c.geom1)):
|
| 734 |
+
if self.part[a] and self.task_obj[b]:
|
| 735 |
+
out.add("a bottle" if self.bidx[b] >= 0 else "the cabinet" if b in self.cab_gids else "a cube")
|
| 736 |
+
return sorted(out)
|
| 737 |
+
|
| 738 |
+
def outcome(self, inst):
|
| 739 |
+
sk = self.sk
|
| 740 |
+
sk.hold(10)
|
| 741 |
+
touching = set()
|
| 742 |
+
for _ in range(20):
|
| 743 |
+
sk.hold(1)
|
| 744 |
+
touching.update(self.robot_touching())
|
| 745 |
+
touching = sorted(touching)
|
| 746 |
+
static = self._static()
|
| 747 |
+
vals = self.stage_values()
|
| 748 |
+
held = [n for n in BOTTLES + CUBES if self.held(n)]
|
| 749 |
+
cab_ok = bool(self.cab_tilt() <= CAB_TILT_MAX and self.cab_moved() <= CAB_MOVE_MAX)
|
| 750 |
+
grip_open = bool(sk.grip < 0)
|
| 751 |
+
self._finalize_monitor(vals)
|
| 752 |
+
mon = self.mon
|
| 753 |
+
ev = list(mon["events"])
|
| 754 |
+
success = bool(all(vals.values()) and cab_ok and static and not held and not touching and grip_open)
|
| 755 |
+
lost = [e for e in ev if e.get("event") == "lost"]
|
| 756 |
+
regress = [e for e in lost if e.get("cause") != "picked_up"]
|
| 757 |
+
restored = [e for e in ev if e.get("event") == "restored" and e.get("after") != "picked_up"]
|
| 758 |
+
slams = [e for e in ev if e.get("event") == "drawer_slam"]
|
| 759 |
+
slam_losses = [e for e in lost if e.get("cause") == "drawer_slam"]
|
| 760 |
+
trap = bool(slam_losses)
|
| 761 |
+
bkeys = [f"{B_NAME[b]}_bottle_on_top" for b in BOTTLES]
|
| 762 |
+
never_bottle = [B_NAME[b] for b, k in zip(BOTTLES, bkeys) if not vals[k] and k not in mon["ever"]]
|
| 763 |
+
lost_bottle = [B_NAME[b] for b, k in zip(BOTTLES, bkeys) if not vals[k] and k in mon["ever"]]
|
| 764 |
+
cubes_out = [CUBE_COLOR[c] for c in CUBES if not vals[f"{CUBE_COLOR[c]}_cube_in_drawer"]]
|
| 765 |
+
if success:
|
| 766 |
+
failure = "none"
|
| 767 |
+
elif held:
|
| 768 |
+
failure = "held"
|
| 769 |
+
elif not cab_ok:
|
| 770 |
+
failure = "cabinet_moved"
|
| 771 |
+
elif lost_bottle:
|
| 772 |
+
failure = "bottle_knocked"
|
| 773 |
+
elif never_bottle:
|
| 774 |
+
failure = "bottle_not_on_top"
|
| 775 |
+
elif cubes_out:
|
| 776 |
+
failure = "cube_not_in_drawer"
|
| 777 |
+
elif not vals["drawer_closed"]:
|
| 778 |
+
failure = "drawer_open"
|
| 779 |
+
elif touching:
|
| 780 |
+
failure = "touching"
|
| 781 |
+
elif not grip_open:
|
| 782 |
+
failure = "gripper_closed"
|
| 783 |
+
else:
|
| 784 |
+
failure = "not_static"
|
| 785 |
+
detail = self._detail(vals, held, touching, cab_ok, static, grip_open, success, ev)
|
| 786 |
+
return dict(success=success, failure=failure, stages=vals, events=ev, n_regressions=len(regress),
|
| 787 |
+
n_lost=len(lost), n_restored=len(restored), trap_fired=trap,
|
| 788 |
+
recovered_in_attempt=bool(trap and success), n_slams=len(slams),
|
| 789 |
+
slam_speeds=[e["speed_mps"] for e in slams], slam_jerk_cm=[e["cabinet_jerk_cm"] for e in slams],
|
| 790 |
+
bottles_lost_to_slam=sorted({e["stage"].split("_")[0] for e in slam_losses}),
|
| 791 |
+
robot_touched_before_fall=[bool(x) for x in mon["touched_before_fall"]],
|
| 792 |
+
bottle_max_tilt_deg=[round(x, 1) for x in mon["max_tilt"]], n_fallen=mon["n_fallen"],
|
| 793 |
+
held=held, touching=touching, static=bool(static), gripper_open=grip_open,
|
| 794 |
+
drawer_q_cm=round(100 * self.q(), 2), cabinet_moved_cm=round(100 * self.cab_moved(), 2),
|
| 795 |
+
cabinet_tilt_deg=round(float(np.degrees(self.cab_tilt())), 1),
|
| 796 |
+
bottle_tilts_deg={B_NAME[b]: round(float(np.degrees(self.tilt(b))), 1) for b in BOTTLES},
|
| 797 |
+
self_closing=bool(inst["self_closing"]), detail=detail)
|
| 798 |
+
|
| 799 |
+
def _detail(self, vals, held, touching, cab_ok, static, grip_open, success, ev):
|
| 800 |
+
parts = []
|
| 801 |
+
if success:
|
| 802 |
+
parts.append("Both bottles stand on the cabinet, the two cubes are in the closed drawer.")
|
| 803 |
+
top_c = self.from_cab([0.0, 0.0, CH])
|
| 804 |
+
for b in BOTTLES:
|
| 805 |
+
k = f"{B_NAME[b]}_bottle_on_top"
|
| 806 |
+
if vals[k]:
|
| 807 |
+
continue
|
| 808 |
+
nm = B_NAME[b]
|
| 809 |
+
if b in held:
|
| 810 |
+
parts.append(f"The {nm} bottle is still held by the gripper.")
|
| 811 |
+
continue
|
| 812 |
+
tl = float(np.degrees(self.tilt(b)))
|
| 813 |
+
base = self.bottle_base(b)
|
| 814 |
+
rel = base - top_c
|
| 815 |
+
on_top = abs(float(rel[2])) < 0.03
|
| 816 |
+
ax = self.R(b)[:, 2]
|
| 817 |
+
where = f"its base is {_fb(rel[0])} and {_lr(rel[1])} of the centre of the cabinet top"
|
| 818 |
+
if tl <= np.degrees(UPRIGHT):
|
| 819 |
+
txt = (f"The {nm} bottle stands but not on the cabinet top: {where}." if not on_top else
|
| 820 |
+
f"The {nm} bottle stands with part of its base over the edge of the cabinet top: {where}.")
|
| 821 |
+
elif on_top and ax[0] > 0.3 and self.to_cab(self.cap_xyz(b))[0] > CD / 2 - RAIL_T:
|
| 822 |
+
txt = (f"The {nm} bottle has tipped over forward on the cabinet top and leans {tl:.0f} degrees against "
|
| 823 |
+
f"the rail along the top's far edge; {where}.")
|
| 824 |
+
elif on_top:
|
| 825 |
+
txt = f"The {nm} bottle has tipped over on the cabinet top ({tl:.0f} degrees); {where}."
|
| 826 |
+
elif base[2] < Z + 0.03:
|
| 827 |
+
txt = f"The {nm} bottle has fallen over and lies on the table; {where}."
|
| 828 |
+
else:
|
| 829 |
+
txt = f"The {nm} bottle has fallen over and leans {tl:.0f} degrees against something; {where}."
|
| 830 |
+
lost = [e for e in ev if e.get("stage") == k and e.get("event") == "lost"]
|
| 831 |
+
if lost:
|
| 832 |
+
why = lost[-1].get("cause", "other")
|
| 833 |
+
txt += {"drawer_slam": " It had stood on the cabinet top; it fell when the drawer snapped shut and the "
|
| 834 |
+
"cabinet jerked.",
|
| 835 |
+
"robot_hand": " It had stood on the cabinet top; the gripper knocked it.",
|
| 836 |
+
"robot_arm": " It had stood on the cabinet top; the robot's arm knocked it.",
|
| 837 |
+
"bottle": " It had stood on the cabinet top; the other bottle knocked it."}.get(
|
| 838 |
+
why, " It had stood on the cabinet top earlier.")
|
| 839 |
+
parts.append(txt)
|
| 840 |
+
for c in CUBES:
|
| 841 |
+
if vals[f"{CUBE_COLOR[c]}_cube_in_drawer"]:
|
| 842 |
+
continue
|
| 843 |
+
nm = CUBE_COLOR[c]
|
| 844 |
+
if c in held:
|
| 845 |
+
parts.append(f"The {nm} cube is still held by the gripper.")
|
| 846 |
+
continue
|
| 847 |
+
p = envs.obj_pos(self.env, c)
|
| 848 |
+
rel = self.to_cab(p)
|
| 849 |
+
if abs(rel[0]) < CD / 2 and abs(rel[1]) < CW / 2 and rel[2] > CH - 0.01:
|
| 850 |
+
parts.append(f"The {nm} cube lies on the cabinet top, not in the drawer.")
|
| 851 |
+
else:
|
| 852 |
+
parts.append(f"The {nm} cube is not in the drawer: it is {_fb(rel[0] + CD / 2)} and {_lr(rel[1])} of the "
|
| 853 |
+
f"middle of the cabinet's front.")
|
| 854 |
+
if not vals["drawer_closed"]:
|
| 855 |
+
parts.append(f"The drawer is still {100 * self.q():.1f} cm open.")
|
| 856 |
+
if not cab_ok:
|
| 857 |
+
if self.cab_tilt() > CAB_TILT_MAX:
|
| 858 |
+
parts.append("The cabinet has been knocked over.")
|
| 859 |
+
else:
|
| 860 |
+
parts.append(f"The cabinet was moved {100 * self.cab_moved():.0f} cm from where it stood.")
|
| 861 |
+
if not success and all(vals.values()) and cab_ok:
|
| 862 |
+
if touching:
|
| 863 |
+
parts.append("The gripper is still touching " + " and ".join(touching) + ".")
|
| 864 |
+
elif not grip_open:
|
| 865 |
+
parts.append("The gripper is closed.")
|
| 866 |
+
elif not static:
|
| 867 |
+
parts.append("Something was still moving.")
|
| 868 |
+
slams = [e for e in ev if e.get("event") == "drawer_slam" and e.get("bottles_fell")]
|
| 869 |
+
if slams and success:
|
| 870 |
+
parts.append("(The drawer snapped shut and knocked bottles off the cabinet; they were stood up again.)")
|
| 871 |
+
return " ".join(parts)
|
| 872 |
+
|
| 873 |
+
# ------------------------------------------------------------ scripted primitives (move_to + gripper only)
|
| 874 |
+
def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300):
|
| 875 |
+
return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
|
| 876 |
+
|
| 877 |
+
def _lift_to(self, z, speed=0.15):
|
| 878 |
+
cur = self.sk.eef_pos()
|
| 879 |
+
if cur[2] < z - 0.005:
|
| 880 |
+
self._go([cur[0], cur[1], z], speed=speed)
|
| 881 |
+
|
| 882 |
+
def _settle(self, name, max_checks=25):
|
| 883 |
+
d = self.env.sim.data
|
| 884 |
+
_, da = envs.free_joint_addr(self.env, name)
|
| 885 |
+
for _ in range(max_checks):
|
| 886 |
+
if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2:
|
| 887 |
+
return
|
| 888 |
+
self.sk.hold(2)
|
| 889 |
+
|
| 890 |
+
def _box_yaw(self, name):
|
| 891 |
+
R = self.R(name)
|
| 892 |
+
i = int(np.argmin(np.abs(R[2])))
|
| 893 |
+
yaw = float(np.arctan2(R[1, i], R[0, i]))
|
| 894 |
+
y = float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4)
|
| 895 |
+
cands = [y + k * np.pi / 2 for k in (-1, 0, 1)]
|
| 896 |
+
return min(cands, key=lambda c: abs(c - self.sk.yaw) if abs(c) <= np.pi / 2 else 9.0)
|
| 897 |
+
|
| 898 |
+
def pick_bottle(self, b, grasp="neck", z_clear=0.05, yaw=None, v=0.15):
|
| 899 |
+
"""Sonnet-like pick of a standing bottle from above: over it, straight down, close, lift until its bottom
|
| 900 |
+
clears the cabinet top by z_clear. grasp: neck (1 cm below its top; the body cannot be reached from above, the
|
| 901 |
+
palm would land on the cap) | cap (the bottle then hangs from a pivot)"""
|
| 902 |
+
sk = self.sk
|
| 903 |
+
self._settle(b)
|
| 904 |
+
p = envs.obj_pos(self.env, b)
|
| 905 |
+
bot = self.bottle_base(b)[2]
|
| 906 |
+
zg = {"neck": bot + NECK_GRASP, "cap": bot + CAP_Z}[grasp]
|
| 907 |
+
yaw = self._box_yaw(b) if yaw is None else yaw
|
| 908 |
+
sk.set_gripper(False, steps=8)
|
| 909 |
+
top = bot + H_TOT
|
| 910 |
+
self.transit(p[:2], top + 0.06, yaw=yaw, v=v)
|
| 911 |
+
self._go([p[0], p[1], zg + 0.015], speed=0.1)
|
| 912 |
+
self._go([p[0], p[1], zg], speed=0.04, tol=0.003, max_steps=150)
|
| 913 |
+
sk.set_gripper(True, steps=15)
|
| 914 |
+
lift = self.top_z() + z_clear + (zg - bot)
|
| 915 |
+
self._go([p[0], p[1], lift], speed=0.10)
|
| 916 |
+
sk.hold(5)
|
| 917 |
+
if not self.held(b):
|
| 918 |
+
sk.set_gripper(False, steps=8)
|
| 919 |
+
return False
|
| 920 |
+
return True
|
| 921 |
+
|
| 922 |
+
def put_bottle(self, b, xy, gap=0.01, z_clear=0.05, v=0.12, settle=15):
|
| 923 |
+
"""carry the held bottle over xy (its axis, not the grasp point), straight down until its bottom is `gap` above
|
| 924 |
+
the cabinet top, let go, lift"""
|
| 925 |
+
sk = self.sk
|
| 926 |
+
rel = envs.obj_pos(self.env, b)[:2] - sk.eef_pos()[:2]
|
| 927 |
+
q = np.asarray(xy, float) - rel
|
| 928 |
+
zc = self.top_z() + z_clear + (sk.eef_pos()[2] - self.bottle_base(b)[2])
|
| 929 |
+
self.transit(q, zc, v=v, carried=b, margin=z_clear)
|
| 930 |
+
sk.hold(settle)
|
| 931 |
+
rel = envs.obj_pos(self.env, b)[:2] - sk.eef_pos()[:2]
|
| 932 |
+
q = np.asarray(xy, float) - rel
|
| 933 |
+
dz = sk.eef_pos()[2] - envs.obj_min_z(self.env, b)
|
| 934 |
+
zr = self.top_z() + dz + gap
|
| 935 |
+
self._go([q[0], q[1], zr + 0.02], speed=0.08)
|
| 936 |
+
self._go([q[0], q[1], zr], speed=0.03, tol=0.003, max_steps=150)
|
| 937 |
+
sk.hold(5)
|
| 938 |
+
sk.set_gripper(False, steps=12)
|
| 939 |
+
cur = sk.eef_pos()
|
| 940 |
+
self._go([cur[0], cur[1], self.top_z() + H_TOT + 0.06], speed=0.08)
|
| 941 |
+
self._settle(b)
|
| 942 |
+
|
| 943 |
+
def obstacle_top(self, p0, p1, ignore=(), r=0.09):
|
| 944 |
+
"""highest top (world z) of standing bottles within r of the straight path p0 -> p1 (xy), and of the cabinet
|
| 945 |
+
top if the path passes over it (expanded by 4 cm)"""
|
| 946 |
+
a, b = np.asarray(p0, float)[:2], np.asarray(p1, float)[:2]
|
| 947 |
+
ab = b - a
|
| 948 |
+
L2 = max(float(ab @ ab), 1e-9)
|
| 949 |
+
|
| 950 |
+
def dist(q):
|
| 951 |
+
u = float(np.clip((q - a) @ ab / L2, 0.0, 1.0))
|
| 952 |
+
return float(np.linalg.norm(a + u * ab - q))
|
| 953 |
+
top = Z
|
| 954 |
+
for o in BOTTLES:
|
| 955 |
+
if o in ignore or self.held(o):
|
| 956 |
+
continue
|
| 957 |
+
if dist(envs.obj_pos(self.env, o)[:2]) < r:
|
| 958 |
+
top = max(top, envs.obj_max_z(self.env, o))
|
| 959 |
+
for u in np.linspace(0.0, 1.0, 21):
|
| 960 |
+
c = self.to_cab(np.r_[a + u * ab, Z])
|
| 961 |
+
if abs(c[0]) < CD / 2 + 0.04 + PF + max(self.q(), 0.0) and abs(c[1]) < CW / 2 + 0.04:
|
| 962 |
+
top = max(top, self.top_z() + RAIL_H)
|
| 963 |
+
break
|
| 964 |
+
return top
|
| 965 |
+
|
| 966 |
+
def transit(self, xy, z_min, yaw=None, v=0.15, carried=None, margin=0.06):
|
| 967 |
+
"""Sonnet-like transit: up (to clear what is in the way), straight across, the caller then goes down"""
|
| 968 |
+
sk = self.sk
|
| 969 |
+
cur = sk.eef_pos()
|
| 970 |
+
obst = self.obstacle_top(cur, xy, ignore=(carried,) if carried else ())
|
| 971 |
+
below = (sk.eef_pos()[2] - envs.obj_min_z(self.env, carried)) if carried else 0.03
|
| 972 |
+
zt = max(cur[2], z_min, obst + margin + below)
|
| 973 |
+
if cur[2] < zt - 0.005:
|
| 974 |
+
self._go([cur[0], cur[1], zt], speed=v)
|
| 975 |
+
self._go([xy[0], xy[1], zt], yaw=yaw, speed=v)
|
| 976 |
+
|
| 977 |
+
def pick_cube(self, c, z_carry=0.15, v=0.15):
|
| 978 |
+
sk = self.sk
|
| 979 |
+
for _ in range(2):
|
| 980 |
+
self._settle(c)
|
| 981 |
+
p = envs.obj_pos(self.env, c)
|
| 982 |
+
yaw = self._box_yaw(c)
|
| 983 |
+
sk.set_gripper(False, steps=8)
|
| 984 |
+
self.transit(p[:2], Z + z_carry, yaw=yaw, v=v)
|
| 985 |
+
self._go([p[0], p[1], p[2] + 0.015], speed=0.1)
|
| 986 |
+
self._go([p[0], p[1], p[2]], speed=0.04, tol=0.003, max_steps=120)
|
| 987 |
+
sk.set_gripper(True, steps=15)
|
| 988 |
+
self._go([p[0], p[1], max(Z + z_carry, sk.eef_pos()[2])], speed=v)
|
| 989 |
+
if self.held(c):
|
| 990 |
+
return True
|
| 991 |
+
sk.set_gripper(False, steps=8)
|
| 992 |
+
return False
|
| 993 |
+
|
| 994 |
+
def drawer_slot(self, k, noise=None):
|
| 995 |
+
"""world xy of cube slot k (0..1) in the exposed part of the open drawer: a column along the drawer's middle
|
| 996 |
+
(with the wrist at yaw 0 the open fingers, 13.2 cm across, stay clear of the side walls and of the cube
|
| 997 |
+
already in; the palm, 3.9 cm ahead of the grasp point, stays clear of the carcass; the far slot first)"""
|
| 998 |
+
q = min(self.q(), Q_OPEN)
|
| 999 |
+
x = self.cab_front_x() - 0.045 - k * (q - 0.070)
|
| 1000 |
+
y = self.cab_xy()[1]
|
| 1001 |
+
out = np.array([x, y])
|
| 1002 |
+
return out + (np.asarray(noise, float) if noise is not None else 0.0)
|
| 1003 |
+
|
| 1004 |
+
def put_cube(self, c, xy, gap=0.02, z_carry=0.15, v=0.15):
|
| 1005 |
+
sk = self.sk
|
| 1006 |
+
self.transit(xy, Z + z_carry, yaw=0.0, v=v, carried=c, margin=0.04)
|
| 1007 |
+
zr = Z + FLOOR_TOP + CUBE_E / 2 + gap
|
| 1008 |
+
self._go([xy[0], xy[1], zr + 0.015], speed=0.1)
|
| 1009 |
+
self._go([xy[0], xy[1], zr], speed=0.04, tol=0.003, max_steps=120)
|
| 1010 |
+
sk.set_gripper(False, steps=12)
|
| 1011 |
+
self._go([xy[0], xy[1], Z + z_carry], speed=v)
|
| 1012 |
+
self._settle(c)
|
| 1013 |
+
|
| 1014 |
+
def close_drawer(self, v=0.04, z_push=0.05, overshoot=0.0, y_off=0.0, approach=0.03):
|
| 1015 |
+
"""closed gripper in front of the drawer, then a straight push forward to where the front panel is flush"""
|
| 1016 |
+
sk = self.sk
|
| 1017 |
+
y = self.cab_xy()[1] + y_off
|
| 1018 |
+
xs = self.drawer_front_x() - FINGER_AHEAD - approach
|
| 1019 |
+
x_end = self.cab_front_x() - PF - FINGER_AHEAD + overshoot
|
| 1020 |
+
sk.set_gripper(True, steps=10)
|
| 1021 |
+
cur = sk.eef_pos()
|
| 1022 |
+
self._go([cur[0], cur[1], max(cur[2], Z + 0.15)], speed=0.15)
|
| 1023 |
+
self._go([xs, y, Z + 0.15], yaw=0.0, speed=0.15)
|
| 1024 |
+
self._go([xs, y, Z + z_push], speed=0.1, tol=0.003)
|
| 1025 |
+
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)
|
| 1026 |
+
self.sk.hold(10)
|
| 1027 |
+
cur = sk.eef_pos()
|
| 1028 |
+
self._go([cur[0] - 0.06, cur[1], cur[2]], speed=0.08)
|
| 1029 |
+
self._go([cur[0] - 0.06, cur[1], Z + 0.20], speed=0.15)
|
| 1030 |
+
sk.hold(10)
|
| 1031 |
+
|
| 1032 |
+
def top_spots(self, mode="pair", noise=None):
|
| 1033 |
+
"""world xy targets on the cabinet top for the two bottles (left one first): side by side across the middle"""
|
| 1034 |
+
c = self.from_cab([0.0, 0.0, CH])[:2]
|
| 1035 |
+
spots = [c + np.array([0.0, 0.05]), c + np.array([0.0, -0.05])]
|
| 1036 |
+
if noise is not None:
|
| 1037 |
+
spots = [s + np.asarray(n, float) for s, n in zip(spots, noise)]
|
| 1038 |
+
return spots
|
| 1039 |
+
|
| 1040 |
+
def free_top_spot(self, b, start=None):
|
| 1041 |
+
"""a spot on the cabinet top (cabinet frame candidates) at least 6.5 cm from the other bottle if that one stands
|
| 1042 |
+
on the top, and -- if `start` (xy the bottle comes from) is given -- whose straight path from `start` passes
|
| 1043 |
+
farthest from it"""
|
| 1044 |
+
other = [o for o in BOTTLES if o != b][0]
|
| 1045 |
+
cands = [np.array([dx, dy]) for dx in (0.0, -0.03, 0.03) for dy in (0.055, -0.055, 0.0)]
|
| 1046 |
+
ok_other = self.bottle_on_top(other, 0.01, np.radians(20))
|
| 1047 |
+
oc = self.to_cab(self.bottle_base(other))[:2]
|
| 1048 |
+
if not ok_other:
|
| 1049 |
+
return self.from_cab([cands[0][0], cands[0][1], CH])[:2] if start is None else min(
|
| 1050 |
+
(self.from_cab([c[0], c[1], CH])[:2] for c in cands[:2]),
|
| 1051 |
+
key=lambda w: float(np.linalg.norm(w - np.asarray(start)[:2])))
|
| 1052 |
+
best, score = None, -1.0
|
| 1053 |
+
st = None if start is None else self.to_cab(np.r_[np.asarray(start)[:2], Z])[:2]
|
| 1054 |
+
for c in cands:
|
| 1055 |
+
if np.linalg.norm(c - oc) < 0.065:
|
| 1056 |
+
continue
|
| 1057 |
+
if st is None:
|
| 1058 |
+
return self.from_cab([c[0], c[1], CH])[:2]
|
| 1059 |
+
ab = c - st
|
| 1060 |
+
u = float(np.clip((oc - st) @ ab / max(float(ab @ ab), 1e-9), 0.0, 1.0))
|
| 1061 |
+
clear = float(np.linalg.norm(st + u * ab - oc))
|
| 1062 |
+
if clear > score:
|
| 1063 |
+
best, score = c, clear
|
| 1064 |
+
if best is None:
|
| 1065 |
+
best = max(cands, key=lambda c: float(np.linalg.norm(c - oc)))
|
| 1066 |
+
return self.from_cab([best[0], best[1], CH])[:2]
|
| 1067 |
+
|
| 1068 |
+
def restand_bottle(self, b, xy=None):
|
| 1069 |
+
"""stand a fallen bottle up again on the cabinet top: grasp the ball cap from above (fingers across the lying
|
| 1070 |
+
bottle's axis), lift until it hangs free with its bottom above the gallery rail, carry it over a free spot,
|
| 1071 |
+
lower until the bottom is ~3 mm above the top, let go. Returns True if it stands on the top."""
|
| 1072 |
+
sk = self.sk
|
| 1073 |
+
self._settle(b)
|
| 1074 |
+
for _ in range(2):
|
| 1075 |
+
if _reach(self.cap_xyz(b)) > REACH_MAX and self.tilt(b) > FALLEN:
|
| 1076 |
+
self.pull_in_bottle(b)
|
| 1077 |
+
k = self.cap_xyz(b)
|
| 1078 |
+
ax = self.R(b)[:2, 2]
|
| 1079 |
+
yaw = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else sk.yaw # finger axis across it
|
| 1080 |
+
sk.set_gripper(False, steps=8)
|
| 1081 |
+
self.transit(k[:2], k[2] + 0.08, yaw=yaw, v=0.15)
|
| 1082 |
+
sk.hold(5)
|
| 1083 |
+
k = self.cap_xyz(b)
|
| 1084 |
+
self._go([k[0], k[1], k[2] + 0.015], speed=0.1)
|
| 1085 |
+
self._go([k[0], k[1], k[2]], speed=0.04, tol=0.003, max_steps=120)
|
| 1086 |
+
sk.set_gripper(True, steps=15)
|
| 1087 |
+
if not self.held(b):
|
| 1088 |
+
sk.set_gripper(False, steps=8)
|
| 1089 |
+
self._go([k[0], k[1], k[2] + 0.08], speed=0.1)
|
| 1090 |
+
continue
|
| 1091 |
+
zl = self.top_z() + RAIL_H + 0.03 + CAP_Z
|
| 1092 |
+
self._go([k[0], k[1], zl], speed=0.10)
|
| 1093 |
+
sk.hold(15)
|
| 1094 |
+
tx, ty = self.free_top_spot(b, start=k[:2]) if xy is None else xy
|
| 1095 |
+
self._go([tx, ty, zl], speed=0.10)
|
| 1096 |
+
sk.hold(30)
|
| 1097 |
+
self._go([tx, ty, self.top_z() + CAP_Z + 0.015], speed=0.08)
|
| 1098 |
+
self._go([tx, ty, self.top_z() + CAP_Z + 0.003], speed=0.03, tol=0.003, max_steps=120)
|
| 1099 |
+
sk.set_gripper(False, steps=12)
|
| 1100 |
+
self._go([tx, ty, self.top_z() + H_TOT + 0.04], speed=0.08)
|
| 1101 |
+
sk.hold(20)
|
| 1102 |
+
self._settle(b)
|
| 1103 |
+
if self.bottle_on_top(b):
|
| 1104 |
+
return True
|
| 1105 |
+
return self.bottle_on_top(b)
|
| 1106 |
+
|
| 1107 |
+
def pull_in_bottle(self, b):
|
| 1108 |
+
"""the lying bottle's cap is out of reach: grasp the body near its bottom end (fingers across it), lift it
|
| 1109 |
+
3 cm, pull it towards the robot until the cap is within reach, set it down"""
|
| 1110 |
+
sk = self.sk
|
| 1111 |
+
Rb = self.R(b)
|
| 1112 |
+
ax = Rb[:, 2]
|
| 1113 |
+
g = envs.obj_pos(self.env, b) - ax * (H_TOT / 2 - 0.04)
|
| 1114 |
+
zg = max(float(g[2] - Z), 0.02)
|
| 1115 |
+
yaw = float(np.arctan2(ax[1], ax[0]))
|
| 1116 |
+
need = _reach(self.cap_xyz(b)) - (REACH_MAX - 0.05)
|
| 1117 |
+
to_base = np.array([-0.66, 0.0]) - g[:2]
|
| 1118 |
+
to_base /= max(np.linalg.norm(to_base), 1e-6)
|
| 1119 |
+
dst = g[:2] + to_base * need
|
| 1120 |
+
sk.set_gripper(False, steps=8)
|
| 1121 |
+
self._go([g[0], g[1], Z + 0.15], yaw=yaw, speed=0.15)
|
| 1122 |
+
self._go([g[0], g[1], Z + zg + 0.015], speed=0.1)
|
| 1123 |
+
self._go([g[0], g[1], Z + zg], speed=0.04, tol=0.003, max_steps=120)
|
| 1124 |
+
sk.set_gripper(True, steps=15)
|
| 1125 |
+
self._go([g[0], g[1], Z + zg + 0.03], speed=0.08)
|
| 1126 |
+
self._go([dst[0], dst[1], Z + zg + 0.03], speed=0.08)
|
| 1127 |
+
self._go([dst[0], dst[1], Z + zg + 0.005], speed=0.04)
|
| 1128 |
+
sk.set_gripper(False, steps=12)
|
| 1129 |
+
self._go([dst[0], dst[1], Z + 0.15], speed=0.1)
|
| 1130 |
+
self._settle(b)
|
| 1131 |
+
|
| 1132 |
+
# ------------------------------------------------------------ scripted policies
|
| 1133 |
+
def check_and_fix(self, params, rounds=2):
|
| 1134 |
+
"""look at every stage at the end: stand fallen bottles up on the top, put stray cubes into the drawer if it is
|
| 1135 |
+
still open"""
|
| 1136 |
+
for _ in range(rounds):
|
| 1137 |
+
v = self.stage_values()
|
| 1138 |
+
if all(v.values()):
|
| 1139 |
+
break
|
| 1140 |
+
for b in BOTTLES:
|
| 1141 |
+
if not self.bottle_on_top(b):
|
| 1142 |
+
if self.tilt(b) > UPRIGHT or self.bottle_base(b)[2] < self.top_z() - 0.03:
|
| 1143 |
+
if self.tilt(b) > UPRIGHT:
|
| 1144 |
+
self.restand_bottle(b)
|
| 1145 |
+
elif self.pick_bottle(b, grasp="neck"):
|
| 1146 |
+
self.put_bottle(b, self.free_top_spot(b), gap=0.005)
|
| 1147 |
+
if not self.drawer_closed():
|
| 1148 |
+
for k, c in enumerate(CUBES):
|
| 1149 |
+
if not self.cube_in_drawer(c) and self.pick_cube(c):
|
| 1150 |
+
self.put_cube(c, self.drawer_slot(k))
|
| 1151 |
+
if all(self.cube_in_drawer(c) for c in CUBES):
|
| 1152 |
+
self.close_drawer(v=params.get("push_v", 0.04), z_push=params.get("push_z", 0.05))
|
| 1153 |
+
self._lift_to(self.top_z() + 0.15)
|
| 1154 |
+
self.sk.set_gripper(False, steps=8)
|
| 1155 |
+
self.sk.hold(10)
|
| 1156 |
+
|
| 1157 |
+
def do_bottles(self, params, rng):
|
| 1158 |
+
noise = params.get("noise")
|
| 1159 |
+
spots = self.top_spots(noise=noise)
|
| 1160 |
+
side = 1.0 if self.inst["bottle_side"] == "left" else -1.0
|
| 1161 |
+
spots = sorted(spots, key=lambda q: side * float(q[1])) # the spot farther from the bottles' side first
|
| 1162 |
+
order = list(BOTTLES) if params.get("bottle_order", "listed") == "listed" else list(BOTTLES)[::-1]
|
| 1163 |
+
for b, xy in zip(order, spots):
|
| 1164 |
+
for _ in range(2):
|
| 1165 |
+
if self.pick_bottle(b, grasp=params.get("grasp", "neck"), z_clear=params.get("z_clear", 0.05)):
|
| 1166 |
+
self.put_bottle(b, xy, gap=params.get("gap", 0.02), z_clear=params.get("z_clear", 0.05))
|
| 1167 |
+
break
|
| 1168 |
+
|
| 1169 |
+
def do_cubes(self, params, rng):
|
| 1170 |
+
noise = params.get("cube_noise") or [None] * 3
|
| 1171 |
+
for k, c in enumerate(self._cube_order()):
|
| 1172 |
+
if self.pick_cube(c):
|
| 1173 |
+
self.put_cube(c, self.drawer_slot(k, noise[k]), gap=params.get("cube_gap", 0.02))
|
| 1174 |
+
|
| 1175 |
+
def _cube_order(self):
|
| 1176 |
+
"""nearest the drawer first"""
|
| 1177 |
+
d = np.array([self.cab_front_x() - Q_OPEN / 2, self.cab_xy()[1]])
|
| 1178 |
+
return sorted(CUBES, key=lambda c: float(np.linalg.norm(envs.obj_pos(self.env, c)[:2] - d)))
|
| 1179 |
+
|
| 1180 |
+
def execute(self, inst, params):
|
| 1181 |
+
rng = np.random.default_rng(params.get("noise_seed", 0))
|
| 1182 |
+
order = params.get("order", "BCD") # B = bottles on top, C = cubes into the drawer, D = close the drawer
|
| 1183 |
+
for step in order:
|
| 1184 |
+
if step == "B":
|
| 1185 |
+
self.do_bottles(params, rng)
|
| 1186 |
+
elif step == "C":
|
| 1187 |
+
self.do_cubes(params, rng)
|
| 1188 |
+
elif step == "D":
|
| 1189 |
+
self.close_drawer(v=params.get("push_v", 0.04), z_push=params.get("push_z", 0.05),
|
| 1190 |
+
overshoot=params.get("overshoot", 0.0))
|
| 1191 |
+
if params.get("check"):
|
| 1192 |
+
self.check_and_fix(params)
|
| 1193 |
+
else:
|
| 1194 |
+
self._lift_to(self.top_z() + 0.15)
|
| 1195 |
+
self.sk.set_gripper(False, steps=8)
|
| 1196 |
+
self.sk.hold(10)
|
| 1197 |
+
|
| 1198 |
+
def _noise(self, rng, err=NAIVE_ERR):
|
| 1199 |
+
return dict(noise=[rng.uniform(-err, err, 2).tolist() for _ in BOTTLES],
|
| 1200 |
+
cube_noise=[rng.uniform(-err, err, 2).tolist() for _ in CUBES])
|
| 1201 |
+
|
| 1202 |
+
def default_params(self, inst):
|
| 1203 |
+
"""Sonnet-like: the order of the instruction (bottles, cubes, drawer); bottles grasped by the body from above,
|
| 1204 |
+
lifted until they clear the cabinet top by 5 cm, lowered straight down and let go 1-4 cm above it; cubes into
|
| 1205 |
+
the drawer; the drawer pushed shut slowly (4 cm/s) with the closed gripper; no final look back"""
|
| 1206 |
+
rng = np.random.default_rng(inst["naive_noise_seed"])
|
| 1207 |
+
p = dict(order="BCD", check=False, grasp="neck", gap=float(rng.uniform(0.01, 0.04)),
|
| 1208 |
+
push_v=float(rng.uniform(0.03, 0.05)), push_z=float(rng.uniform(0.04, 0.06)),
|
| 1209 |
+
overshoot=float(rng.uniform(0.0, 0.004)), noise_seed=int(inst["naive_noise_seed"]))
|
| 1210 |
+
p.update(self._noise(rng))
|
| 1211 |
+
return p
|
| 1212 |
+
|
| 1213 |
+
def oracle_params(self, inst):
|
| 1214 |
+
"""knows the drawer: cubes in, drawer shut, then the bottles; checks every stage at the end"""
|
| 1215 |
+
return dict(order="CDB", check=True, grasp="neck", gap=0.008, push_v=0.04, push_z=0.05, overshoot=0.0)
|
| 1216 |
+
|
| 1217 |
+
def adapt_params(self, inst, history):
|
| 1218 |
+
"""attempt >= 2 (after the bottles fell when the drawer was shut): shut the drawer before the bottles go on
|
| 1219 |
+
top, and look at every stage at the end"""
|
| 1220 |
+
return dict(self.default_params(inst), order="CDB", check=True)
|
| 1221 |
+
|
| 1222 |
+
def blind_params(self, inst, attempt, rng):
|
| 1223 |
+
"""the natural behaviour with random variations (order of the three sub-tasks, push speed / height, release
|
| 1224 |
+
height, placement noise), no history, no final look"""
|
| 1225 |
+
order = str(rng.choice(["BCD", "CBD", "CDB"], p=[0.5, 0.3, 0.2]))
|
| 1226 |
+
p = dict(order=order, check=False, grasp=str(rng.choice(["neck", "cap"])), gap=float(rng.uniform(0.01, 0.04)),
|
| 1227 |
+
push_v=float(rng.uniform(0.02, 0.08)), push_z=float(rng.uniform(0.03, 0.07)),
|
| 1228 |
+
overshoot=float(rng.uniform(0.0, 0.006)), noise_seed=int(rng.integers(1 << 30)))
|
| 1229 |
+
p.update(self._noise(rng))
|
| 1230 |
+
return p
|
| 1231 |
+
|
| 1232 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 1233 |
+
"""oracle / naive: one attempt; adaptive: attempt 1 = naive + a final look that stands fallen bottles up again,
|
| 1234 |
+
attempts >= 2 drawer first; blind: naive with random variations.
|
| 1235 |
+
Extra kinds (not in validate's table): switch (naive, then drawer first without a final look), oracle_noise
|
| 1236 |
+
(oracle with +-5 mm placement noise), naive_slow (naive pushing at the slowest agent speed, 2 cm/s),
|
| 1237 |
+
naive_check (naive + final look = adaptive's first attempt)"""
|
| 1238 |
+
k = k or self.max_attempts
|
| 1239 |
+
rng = np.random.default_rng(seed)
|
| 1240 |
+
history = []
|
| 1241 |
+
single = ("oracle", "naive", "oracle_noise", "naive_slow", "naive_check", "naive_neck", "naive_cap")
|
| 1242 |
+
for a in range(k):
|
| 1243 |
+
self.reset_instance(inst)
|
| 1244 |
+
if kind == "oracle":
|
| 1245 |
+
params = self.oracle_params(inst)
|
| 1246 |
+
elif kind == "naive":
|
| 1247 |
+
params = self.default_params(inst)
|
| 1248 |
+
elif kind == "adaptive":
|
| 1249 |
+
params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history)
|
| 1250 |
+
elif kind == "blind":
|
| 1251 |
+
params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
|
| 1252 |
+
elif kind == "switch":
|
| 1253 |
+
params = self.default_params(inst) if a == 0 else dict(self.default_params(inst), order="CDB")
|
| 1254 |
+
elif kind == "oracle_noise":
|
| 1255 |
+
params = dict(self.oracle_params(inst), **self._noise(np.random.default_rng(seed * 7 + a), 0.005))
|
| 1256 |
+
elif kind == "naive_slow":
|
| 1257 |
+
params = dict(self.default_params(inst), push_v=0.02)
|
| 1258 |
+
elif kind == "naive_check":
|
| 1259 |
+
params = dict(self.default_params(inst), check=True)
|
| 1260 |
+
elif kind == "naive_neck":
|
| 1261 |
+
params = dict(self.default_params(inst), grasp="neck")
|
| 1262 |
+
elif kind == "naive_cap":
|
| 1263 |
+
params = dict(self.default_params(inst), grasp="cap")
|
| 1264 |
+
else:
|
| 1265 |
+
raise ValueError(kind)
|
| 1266 |
+
self.execute(inst, params)
|
| 1267 |
+
out = self.outcome(inst)
|
| 1268 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 1269 |
+
if on_attempt:
|
| 1270 |
+
on_attempt(a, params, out)
|
| 1271 |
+
if out["success"] or kind in single:
|
| 1272 |
+
break
|
| 1273 |
+
return history
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/lh_fence.py
ADDED
|
@@ -0,0 +1,1030 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LH lh_fence (v2, 2026-10-11): build a small fence -- three square posts on square marks and two flat panels on the
|
| 2 |
+
strips between them, end to end in one line. Letting go of a panel with the fingers along the fence line knocks over
|
| 3 |
+
the post next to it (when the posts are light); the fallen post must be stood up again before finishing.
|
| 4 |
+
|
| 5 |
+
Family: long-horizon self-disturbance ("state_restoration"): every placement is a later stage that can physically
|
| 6 |
+
break the earlier ones; the agent has to notice and restore them (within an attempt) or learn to place without
|
| 7 |
+
disturbing them (across attempts).
|
| 8 |
+
|
| 9 |
+
Why v2 (measured, ../docs/11 sec. 9): in v1 the panels stood like dominoes (thickness along the row) and the hazard was
|
| 10 |
+
opening the fingers along the row. Sonnet 5.5 always turned the hand so that its long axis (= the finger axis) lay
|
| 11 |
+
along the panel's long horizontal side, which in v1 is across the row = the safe orientation, and it filled the row
|
| 12 |
+
from the far end: 3/3 pilot runs succeeded first time with zero disturbances. v2 turns the panels by 90 deg into a real
|
| 13 |
+
fence (panels end to end along the line, posts between them), so the same habit now opens the fingers ALONG the
|
| 14 |
+
line, towards the posts.
|
| 15 |
+
|
| 16 |
+
Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
|
| 17 |
+
* a straight fence line, left-right or forward-back: 3 dark square marks (posts) alternating with 2 dark strips
|
| 18 |
+
(panels), slot pitch (post centre to post centre) w + 2 g + b;
|
| 19 |
+
* 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
|
| 20 |
+
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
|
| 21 |
+
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 =
|
| 22 |
+
4.1-4.6 cm);
|
| 23 |
+
* 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
|
| 24 |
+
panels with their width along the line (+-9 deg).
|
| 25 |
+
|
| 26 |
+
Hidden variable (instance level, consistent across attempts, invisible): the posts' mass distribution. "Light" posts
|
| 27 |
+
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
|
| 28 |
+
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
|
| 29 |
+
every 20 consecutive seeds have light posts ("hazard"), 7 footed ("benign").
|
| 30 |
+
|
| 31 |
+
Disturbance (physics, no teleport): a panel is grasped by its knob; with the fingers along the panel's width (the
|
| 32 |
+
natural "hand along the board" grasp, and Sonnet's measured habit) the fingers lie along the fence line at the release
|
| 33 |
+
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
|
| 34 |
+
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
|
| 35 |
+
panel; a middle post often ends up leaning on the panel on its other side); a footed post rocks back. Measured in the
|
| 36 |
+
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
|
| 37 |
+
tilt 18 deg); with the fingers across the line (along the panel's thickness) 0/9 contacts. A post set down with its
|
| 38 |
+
fingers along the line next to a standing panel tilts the panel <= 15 deg, which rocks back. Validation (seeds
|
| 39 |
+
1000-1019): the Sonnet-like naive disturbs 13/13 light-post instances and 0/7 footed ones.
|
| 40 |
+
|
| 41 |
+
So the levers are under the agent's control and the hidden weight only decides whether its habit is punished: (1)
|
| 42 |
+
release a panel with the fingers across the fence line (Sonnet-like naive with only this change: 19/20), or, only
|
| 43 |
+
partly, (2) stand both panels before the posts (15/20: a post released next to a panel with its fingers along the line
|
| 44 |
+
rocks the panel, which can knock the new light post). Within an attempt:
|
| 45 |
+
look at the fence before finishing and stand fallen posts up again (lifted by its knob a fallen post swings down and
|
| 46 |
+
hangs upright; a fallen panel too).
|
| 47 |
+
|
| 48 |
+
Implementation notes (found while building v2): MuJoCo keeps each body's bounding-volume hierarchy in the body's
|
| 49 |
+
inertial frame, computed at compile time. Changing geom sizes or body_ipos at runtime therefore needs `refit_bvh`
|
| 50 |
+
(else contacts are missed: a light post whose centre of mass was moved up sank 2.2 cm into the table; one moved down
|
| 51 |
+
never touched the fingers), and runtime body_ipos is ignored altogether when the compiled inertial frame coincides with
|
| 52 |
+
the body frame (v1's knob-mass shift of the centre of mass was silently ignored); the generated XML therefore declares
|
| 53 |
+
an inertial pos of 1 mm. With the centre of mass right, v1's knob torsional friction (0.0015) held a lifted fallen light
|
| 54 |
+
post at 44-61 deg instead of letting it swing down; v2 uses 0.0005 (< 3 deg).
|
| 55 |
+
|
| 56 |
+
Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (every mark
|
| 57 |
+
carries an upright post, every strip an upright panel lined up with it, nothing held or touched, scene static) plus an
|
| 58 |
+
event log of every stage predicate (achieved / lost / restored, with step and cause) for the server log; F1 gives the
|
| 59 |
+
agent only success / failure.
|
| 60 |
+
"""
|
| 61 |
+
import numpy as np
|
| 62 |
+
|
| 63 |
+
from .. import envs
|
| 64 |
+
from ..bddl import write_bddl
|
| 65 |
+
from ..objects import _fmt, _wrap, register_generated
|
| 66 |
+
from ..skills import Skills
|
| 67 |
+
from ..task_base import LFFTask, register_task
|
| 68 |
+
|
| 69 |
+
TZ = envs.TABLE_Z
|
| 70 |
+
POSTS = [f"post_{c}_1" for c in "abc"]
|
| 71 |
+
PANELS = [f"panel_{c}_1" for c in "ab"]
|
| 72 |
+
OBJS = POSTS + PANELS
|
| 73 |
+
MARKS = [f"postmark_{c}_1" for c in "abc"]
|
| 74 |
+
STRIPS = [f"strip_{c}_1" for c in "ab"]
|
| 75 |
+
SLOT_KIND = ["post", "panel", "post", "panel", "post"] # along the fence line (-u to +u)
|
| 76 |
+
WOOD = [(0.82, 0.66, 0.44, 1.0), (0.76, 0.60, 0.40, 1.0)]
|
| 77 |
+
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)]
|
| 78 |
+
KNOB_RGBA = (0.20, 0.11, 0.06, 1.0)
|
| 79 |
+
STRIP_RGBA = (0.30, 0.10, 0.12, 1.0)
|
| 80 |
+
MARK_RGBA = (0.14, 0.14, 0.16, 1.0)
|
| 81 |
+
NOM_T, NOM_W, NOM_H = 0.015, 0.047, 0.075 # nominal panel (resized per instance)
|
| 82 |
+
NOM_B = 0.016 # nominal post width
|
| 83 |
+
KNOB_R, STEM_L, STEM_R = 0.010, 0.008, 0.0035
|
| 84 |
+
KNOB_MASS = 0.010
|
| 85 |
+
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)
|
| 86 |
+
STRIP_W = 0.006
|
| 87 |
+
|
| 88 |
+
# instance ranges
|
| 89 |
+
P_HAZARD = 0.65 # 13 of every 20 consecutive seeds: light posts
|
| 90 |
+
T_RANGE = (0.014, 0.016)
|
| 91 |
+
W_RANGE = (0.040, 0.046)
|
| 92 |
+
H_RANGE = (0.070, 0.080)
|
| 93 |
+
B_RANGE = (0.0155, 0.0165)
|
| 94 |
+
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)
|
| 95 |
+
DENS_RANGE = (450.0, 650.0)
|
| 96 |
+
MU_RANGE = (0.4, 0.8)
|
| 97 |
+
FOOT_RANGE = (0.10, 0.14) # hidden steel foot of a "footed" post (kg)
|
| 98 |
+
FOOT_H = 0.015 # height of the foot slug (its centre 7.5 mm above the post's bottom)
|
| 99 |
+
SUP_PITCH = (0.105, 0.115)
|
| 100 |
+
SUP_D = (0.13, 0.15)
|
| 101 |
+
X_FAR = -0.035
|
| 102 |
+
|
| 103 |
+
# success predicate
|
| 104 |
+
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
|
| 105 |
+
TOL_V = 0.015
|
| 106 |
+
TOL_POST = 0.010
|
| 107 |
+
TILT_OK = np.radians(5.0)
|
| 108 |
+
YAW_TOL = np.radians(15.0)
|
| 109 |
+
HYST = 0.004
|
| 110 |
+
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)
|
| 111 |
+
FALLEN = np.radians(45.0)
|
| 112 |
+
|
| 113 |
+
# scripted motion (z = height of the grasp point above the table)
|
| 114 |
+
Z_SAFE = 0.25 # careful transit (a hanging object's bottom ~15 cm up)
|
| 115 |
+
Z_NAIVE = 0.21 # Sonnet's usual carry height: robot-frame z 0.20 (= 21 cm above the table), measured in lh2_fence
|
| 116 |
+
NAIVE_ERR = 0.008 # naive placement error, uniform per axis (Sonnet: 0.4-1.3 cm from the strip centre, lh2_fence)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def _wrap_h(a):
|
| 120 |
+
"""wrap to [-pi/2, pi/2) (panel footprint and gripper are symmetric under 180 deg)"""
|
| 121 |
+
return float((a + np.pi / 2) % np.pi - np.pi / 2)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _yaw_for_axis(a):
|
| 125 |
+
"""gripper yaw whose finger axis (-sin yaw, cos yaw) is parallel to the horizontal direction a"""
|
| 126 |
+
return _wrap_h(float(np.arctan2(-a[0], a[1])))
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _quat2mat(q):
|
| 130 |
+
w, x, y, z = q
|
| 131 |
+
return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
|
| 132 |
+
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
|
| 133 |
+
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]])
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def refit_bvh(m, b, margin=0.001):
|
| 137 |
+
"""Recompute body b's bounding-volume hierarchy after runtime changes of its geoms or body_ipos. MuJoCo stores the
|
| 138 |
+
boxes in the body's inertial frame, computed at compile time; stale boxes make it miss contacts (see module doc).
|
| 139 |
+
Every node becomes the union of its leaf geoms' boxes (body_iquat must be identity)."""
|
| 140 |
+
a = int(m.body_bvhadr[b])
|
| 141 |
+
if a < 0:
|
| 142 |
+
return
|
| 143 |
+
ipos = np.asarray(m.body_ipos[b], float)
|
| 144 |
+
|
| 145 |
+
def rec(i):
|
| 146 |
+
g = int(m.bvh_nodeid[i])
|
| 147 |
+
if g >= 0:
|
| 148 |
+
R = _quat2mat(m.geom_quat[g])
|
| 149 |
+
c = np.asarray(m.geom_pos[g]) + R @ np.asarray(m.geom_aabb[g, :3]) - ipos
|
| 150 |
+
h = np.abs(R) @ np.asarray(m.geom_aabb[g, 3:])
|
| 151 |
+
lo, hi = c - h, c + h
|
| 152 |
+
else:
|
| 153 |
+
l1, h1 = rec(a + int(m.bvh_child[i][0]))
|
| 154 |
+
l2, h2 = rec(a + int(m.bvh_child[i][1]))
|
| 155 |
+
lo, hi = np.minimum(l1, l2), np.maximum(h1, h2)
|
| 156 |
+
m.bvh_aabb[i] = np.concatenate([(lo + hi) / 2, (hi - lo) / 2 + margin])
|
| 157 |
+
return lo, hi
|
| 158 |
+
rec(a)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def knobbed_xml(name, half, rgba):
|
| 162 |
+
"""box + stem + ball knob. The inertial pos is 1 mm (not 0) so that MuJoCo does not mark the inertial frame as
|
| 163 |
+
identical to the body frame: then the centre of mass set at runtime (body_ipos) is used."""
|
| 164 |
+
geoms = [("board", "box", (0, 0, 0), half, rgba, 'friction="0.6 0.005 0.0001"'),
|
| 165 |
+
("stem", "cylinder", (0, 0, half[2] + STEM_L / 2), (STEM_R, STEM_L / 2), KNOB_RGBA,
|
| 166 |
+
'friction="1 0.005 0.0001"'),
|
| 167 |
+
("knob", "sphere", (0, 0, half[2] + STEM_L + KNOB_R), (KNOB_R,), KNOB_RGBA,
|
| 168 |
+
f'friction="1 {KNOB_MU_T} 0.0001" condim="4" priority="2"')]
|
| 169 |
+
s = [' <inertial pos="0 0 0.001" mass="0.05" diaginertia="2e-5 2e-5 1e-5" />']
|
| 170 |
+
for nm, typ, pos, size, c, extra in geoms:
|
| 171 |
+
s.append(f' <geom name="{name}_{nm}" type="{typ}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(c)}" '
|
| 172 |
+
f'{extra} group="0" />')
|
| 173 |
+
s.append(f' <geom type="{typ}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(c)}" contype="0" '
|
| 174 |
+
f'conaffinity="0" group="1" />')
|
| 175 |
+
return _wrap(name, "\n".join(s), half[2], float(np.hypot(half[0], half[1])))
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def flat_xml(name, half, rgba):
|
| 179 |
+
g = (f' <geom type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" contype="0" conaffinity="0" group="1" />')
|
| 180 |
+
return _wrap(name, g, half[2], float(np.hypot(half[0], half[1])))
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
class FenceSkills(Skills):
|
| 184 |
+
"""Skills that feed the task's per-step stage monitor."""
|
| 185 |
+
|
| 186 |
+
def __init__(self, env, task, recorder=None):
|
| 187 |
+
super().__init__(env, recorder=recorder)
|
| 188 |
+
self.task = task
|
| 189 |
+
|
| 190 |
+
def _act(self, dpos, drot, grip):
|
| 191 |
+
super()._act(dpos, drot, grip)
|
| 192 |
+
self.task.monitor_step()
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
@register_task
|
| 196 |
+
class Fence(LFFTask):
|
| 197 |
+
name = "lh_fence"
|
| 198 |
+
level = "L2"
|
| 199 |
+
category = "state_restoration"
|
| 200 |
+
capabilities = ("Perceive", "Plan", "Reason", "Restore")
|
| 201 |
+
protocol = "cross"
|
| 202 |
+
max_attempts = 3
|
| 203 |
+
agent_max_steps = 120 # careful: ~10 commands per object (50) + standing up two fallen posts (~20) + looking
|
| 204 |
+
instruction = ("Build a small fence: stand one wooden post upright on each of the dark square marks on the table "
|
| 205 |
+
"and one wooden panel upright on each of the dark strips between them, the panel's long bottom edge "
|
| 206 |
+
"along its strip, so that posts and panels alternate in one straight line. Every post and panel "
|
| 207 |
+
"has a small round knob on top; an object lifted by its knob hangs straight down. At the end every "
|
| 208 |
+
"square mark must have one upright post and every strip one upright panel standing on it, with the "
|
| 209 |
+
"gripper open and clear of the fence.")
|
| 210 |
+
instruction_indirect = ("Put up the little fence: the thin square sticks go upright on the dark squares, the flat "
|
| 211 |
+
"boards upright on the dark lines between them, lengthwise along their lines, so that "
|
| 212 |
+
"sticks and boards take turns in one straight row. Every piece has a round knob on top; "
|
| 213 |
+
"held by its knob a piece hangs straight down. At the end every square must carry one "
|
| 214 |
+
"upright stick and every line one upright board, and the gripper must be open and away "
|
| 215 |
+
"from the fence.")
|
| 216 |
+
agent_object_names = ["wooden fence posts (square, each with a dark knob on top)",
|
| 217 |
+
"wooden fence panels (flat boards, each with a dark knob on top)",
|
| 218 |
+
"dark square marks and dark strips on the table"]
|
| 219 |
+
|
| 220 |
+
# ------------------------------------------------------------ scene
|
| 221 |
+
def make_bddl(self):
|
| 222 |
+
objs, fx = [], []
|
| 223 |
+
for i, p in enumerate(POSTS):
|
| 224 |
+
c = "abc"[i]
|
| 225 |
+
cat = register_generated(f"LffLhfPost{c.upper()}",
|
| 226 |
+
knobbed_xml(f"lff_lhf_post_{c}", (NOM_B / 2, NOM_B / 2, NOM_H / 2), POST_RGBA[i]))
|
| 227 |
+
objs.append((p, cat, f"post{i}_region", (-0.30 + 0.12 * i, 0.30, -0.29 + 0.12 * i, 0.31)))
|
| 228 |
+
for i, p in enumerate(PANELS):
|
| 229 |
+
c = "ab"[i]
|
| 230 |
+
cat = register_generated(f"LffLhfPanel{c.upper()}",
|
| 231 |
+
knobbed_xml(f"lff_lhf_panel_{c}", (NOM_T / 2, NOM_W / 2, NOM_H / 2), WOOD[i]))
|
| 232 |
+
objs.append((p, cat, f"panel{i}_region", (-0.30 + 0.12 * i, -0.31, -0.29 + 0.12 * i, -0.30)))
|
| 233 |
+
for i, k in enumerate(MARKS):
|
| 234 |
+
c = "abc"[i]
|
| 235 |
+
cat = register_generated(f"LffLhfPostmark{c.upper()}",
|
| 236 |
+
flat_xml(f"lff_lhf_postmark_{c}", (NOM_B / 2 + 0.003, NOM_B / 2 + 0.003, 0.0005),
|
| 237 |
+
MARK_RGBA), free=False)
|
| 238 |
+
fx.append((k, cat, f"mark{i}_region", (-0.30 + 0.12 * i, 0.10, -0.29 + 0.12 * i, 0.11)))
|
| 239 |
+
for i, k in enumerate(STRIPS):
|
| 240 |
+
c = "ab"[i]
|
| 241 |
+
cat = register_generated(f"LffLhfStrip{c.upper()}",
|
| 242 |
+
flat_xml(f"lff_lhf_strip_{c}", (STRIP_W / 2, NOM_W / 2 + 0.005, 0.0005),
|
| 243 |
+
STRIP_RGBA), free=False)
|
| 244 |
+
fx.append((k, cat, f"strip{i}_region", (-0.30 + 0.12 * i, -0.11, -0.29 + 0.12 * i, -0.10)))
|
| 245 |
+
return write_bddl(self.name, "Build a small fence from the posts and panels", objs, fx)
|
| 246 |
+
|
| 247 |
+
def __init__(self, cam_res=None):
|
| 248 |
+
super().__init__(cam_res)
|
| 249 |
+
m = self.env.sim.model
|
| 250 |
+
self.fix_bid, self.fix_vis = {}, {}
|
| 251 |
+
for k in MARKS + STRIPS:
|
| 252 |
+
b = m.body_name2id(self.env.fixtures_dict[k].root_body)
|
| 253 |
+
self.fix_bid[k] = b
|
| 254 |
+
self.fix_vis[k] = [g for g in range(m.ngeom) if m.geom_bodyid[g] in
|
| 255 |
+
{b} | {c for c in range(m.nbody) if m.body_parentid[c] == b} and m.geom_type[g] == 6]
|
| 256 |
+
self.gid, self.vis, self.pbody = {}, {}, {}
|
| 257 |
+
for p in OBJS:
|
| 258 |
+
kind, c = p.split("_")[0], p.split("_")[1]
|
| 259 |
+
self.gid[p] = {nm: m.geom_name2id(f"{p}_lff_lhf_{kind}_{c}_{nm}") for nm in ("board", "stem", "knob")}
|
| 260 |
+
body = int(m.geom_bodyid[self.gid[p]["board"]])
|
| 261 |
+
self.pbody[p] = body
|
| 262 |
+
self.vis[p] = [g for g in range(m.ngeom) if m.geom_bodyid[g] == body and m.geom_contype[g] == 0
|
| 263 |
+
and m.geom_conaffinity[g] == 0]
|
| 264 |
+
self.geom_owner = {}
|
| 265 |
+
for p in OBJS:
|
| 266 |
+
for g in self.gid[p].values():
|
| 267 |
+
self.geom_owner[g] = p
|
| 268 |
+
self.finger_geoms, self.hand_geoms = set(), set()
|
| 269 |
+
for g in envs.robot_geom_ids(self.env):
|
| 270 |
+
n = m.geom_id2name(g) or ""
|
| 271 |
+
(self.finger_geoms if "finger" in n else self.hand_geoms).add(g)
|
| 272 |
+
self.robot_geoms = self.finger_geoms | self.hand_geoms
|
| 273 |
+
# per-geom lookup tables for the substep contact check: object index (-1 none), robot part (1 finger, 2 hand)
|
| 274 |
+
self.owner = np.full(m.ngeom, -1, int)
|
| 275 |
+
for i, p in enumerate(OBJS):
|
| 276 |
+
self.owner[list(self.gid[p].values())] = i
|
| 277 |
+
self.part = np.zeros(m.ngeom, int)
|
| 278 |
+
self.part[list(self.finger_geoms)] = 1
|
| 279 |
+
self.part[list(self.hand_geoms)] = 2
|
| 280 |
+
self._sub_rob, self._sub_obj = {}, {}
|
| 281 |
+
# Contacts are collected after every MuJoCo substep: a fast hit (a finger flicking a knob, a hanging object
|
| 282 |
+
# sweeping past) can last less than one 25-substep control step (v1, measured). Wrappers chain.
|
| 283 |
+
sim = self.env.sim
|
| 284 |
+
if not getattr(sim, "_lhf_wrapped", False):
|
| 285 |
+
orig = sim.step
|
| 286 |
+
|
| 287 |
+
def step(*a, **k):
|
| 288 |
+
orig(*a, **k)
|
| 289 |
+
t = getattr(sim, "_lhf_task", None)
|
| 290 |
+
if t is not None and t.mon is not None:
|
| 291 |
+
t._substep()
|
| 292 |
+
sim.step = step
|
| 293 |
+
sim._lhf_wrapped = True
|
| 294 |
+
sim._lhf_task = self
|
| 295 |
+
self.inst = None
|
| 296 |
+
self.mon = None
|
| 297 |
+
self.sk = None
|
| 298 |
+
|
| 299 |
+
def _substep(self):
|
| 300 |
+
d = self.env.sim.data
|
| 301 |
+
n = d.ncon
|
| 302 |
+
if not n:
|
| 303 |
+
return
|
| 304 |
+
g1 = np.asarray(d.contact.geom1)[:n]
|
| 305 |
+
g2 = np.asarray(d.contact.geom2)[:n]
|
| 306 |
+
o1, o2 = self.owner[g1], self.owner[g2]
|
| 307 |
+
for a, b, pa, pb in zip(g1, g2, o1, o2):
|
| 308 |
+
if pa < 0 and pb < 0:
|
| 309 |
+
continue
|
| 310 |
+
if pa >= 0 and pb >= 0:
|
| 311 |
+
if pa != pb:
|
| 312 |
+
self._sub_obj[int(pa)] = int(pb)
|
| 313 |
+
self._sub_obj[int(pb)] = int(pa)
|
| 314 |
+
continue
|
| 315 |
+
p, o = (pa, b) if pa >= 0 else (pb, a)
|
| 316 |
+
part = self.part[o]
|
| 317 |
+
if part:
|
| 318 |
+
prev = self._sub_rob.get(int(p), 0)
|
| 319 |
+
self._sub_rob[int(p)] = 1 if (part == 1 or prev == 1) else 2
|
| 320 |
+
|
| 321 |
+
# ------------------------------------------------------------ instances
|
| 322 |
+
def sample_instance(self, seed):
|
| 323 |
+
rng = np.random.default_rng(seed)
|
| 324 |
+
row = "lr" if rng.random() < 0.5 else "fb"
|
| 325 |
+
hazard = bool((int(seed) * 7) % 20 < round(20 * P_HAZARD)) # balanced: 13 of every 20 consecutive seeds
|
| 326 |
+
t, w, h = (float(rng.uniform(*T_RANGE)), float(rng.uniform(*W_RANGE)), float(rng.uniform(*H_RANGE)))
|
| 327 |
+
b = float(rng.uniform(*B_RANGE))
|
| 328 |
+
gap = float(rng.uniform(*GAP_RANGE))
|
| 329 |
+
dens_panel, dens_post = float(rng.uniform(*DENS_RANGE)), float(rng.uniform(*DENS_RANGE))
|
| 330 |
+
mu = float(rng.uniform(*MU_RANGE))
|
| 331 |
+
foot = 0.0 if hazard else float(rng.uniform(*FOOT_RANGE))
|
| 332 |
+
pitch = w + 2 * gap + b # post centre to post centre
|
| 333 |
+
if row == "lr":
|
| 334 |
+
c = np.array([rng.uniform(-0.12, -0.06), rng.uniform(-0.05, 0.05)])
|
| 335 |
+
u = np.array([0.0, 1.0])
|
| 336 |
+
v = np.array([-1.0, 0.0]) # supply side: towards the robot
|
| 337 |
+
else:
|
| 338 |
+
side = 1.0 if rng.random() < 0.5 else -1.0
|
| 339 |
+
c = np.array([rng.uniform(-0.16, -0.10), side * rng.uniform(0.09, 0.13)])
|
| 340 |
+
u = np.array([1.0, 0.0])
|
| 341 |
+
v = np.array([0.0, -side]) # supply side: towards the middle
|
| 342 |
+
phi = float(np.arctan2(u[1], u[0])) # direction of the fence line
|
| 343 |
+
pyaw = _wrap_h(phi - np.pi / 2) # panel yaw: body y (width) along the line, body x (thickness) across
|
| 344 |
+
g = float(rng.uniform(*SUP_PITCH))
|
| 345 |
+
d = float(rng.uniform(*SUP_D))
|
| 346 |
+
shift = float(rng.choice([-1.0, 1.0]) * rng.uniform(0.04, 0.07))
|
| 347 |
+
if row == "fb": # keep the farthest supply slot within ~63 cm of the robot base, the far post within ~66 cm
|
| 348 |
+
c[0] -= max(0.0, c[0] + shift + g - X_FAR)
|
| 349 |
+
c[0] -= max(0.0, c[0] + pitch - X_FAR - 0.03)
|
| 350 |
+
slots = [(c + u * (s - 2) * pitch / 2).tolist() for s in range(5)]
|
| 351 |
+
sup = [c + v * (d + j * g) + u * (shift + (k - 1) * g) for j in range(2) for k in range(3)]
|
| 352 |
+
pick = rng.permutation(6)[:5]
|
| 353 |
+
start = {OBJS[i]: (sup[j] + rng.uniform(-0.008, 0.008, 2)).tolist() for i, j in enumerate(pick)}
|
| 354 |
+
yaw0 = {p: pyaw + float(rng.uniform(-0.15, 0.15)) for p in OBJS}
|
| 355 |
+
return dict(seed=int(seed), row=row, hazard=hazard, posts="light" if hazard else "footed", foot_mass=foot,
|
| 356 |
+
t=t, w=w, h=h, b=b, gap=gap, pitch=pitch, density_panel=dens_panel, density_post=dens_post, mu=mu,
|
| 357 |
+
center=c.tolist(), u=u.tolist(), v=v.tolist(), phi=phi, pyaw=pyaw, slots=slots,
|
| 358 |
+
knob_dist=w / 2 + gap + b / 2, start=start, yaw0=yaw0, supply_shift=shift, supply_pitch=g,
|
| 359 |
+
supply_d=d)
|
| 360 |
+
|
| 361 |
+
def _set_body(self, p, half, density, foot=0.0):
|
| 362 |
+
"""resize p's geoms, set mass / centre of mass / inertia (board + knob + optional hidden foot), refit BVH"""
|
| 363 |
+
m = self.env.sim.model
|
| 364 |
+
hx, hy, hz = half
|
| 365 |
+
spec = {"board": ([hx, hy, hz], [0, 0, 0], [hx, hy, hz]),
|
| 366 |
+
"stem": ([STEM_R, STEM_L / 2, 0], [0, 0, hz + STEM_L / 2], [STEM_R, STEM_R, STEM_L / 2]),
|
| 367 |
+
"knob": ([KNOB_R, 0, 0], [0, 0, hz + STEM_L + KNOB_R], [KNOB_R, KNOB_R, KNOB_R])}
|
| 368 |
+
for nm, g in self.gid[p].items():
|
| 369 |
+
sz, pos, aabb = spec[nm]
|
| 370 |
+
m.geom_size[g] = sz
|
| 371 |
+
m.geom_pos[g] = pos
|
| 372 |
+
m.geom_aabb[g] = [0, 0, 0] + aabb
|
| 373 |
+
m.geom_rbound[g] = float(np.linalg.norm(aabb))
|
| 374 |
+
for nm, g in zip(("board", "stem", "knob"), self.vis[p]):
|
| 375 |
+
m.geom_size[g] = spec[nm][0]
|
| 376 |
+
m.geom_pos[g] = spec[nm][1]
|
| 377 |
+
bd = self.pbody[p]
|
| 378 |
+
X, Y, Z = 2 * hx, 2 * hy, 2 * hz
|
| 379 |
+
mb = density * X * Y * Z
|
| 380 |
+
zk = hz + STEM_L + KNOB_R
|
| 381 |
+
zf = -hz + FOOT_H / 2
|
| 382 |
+
M = mb + KNOB_MASS + foot
|
| 383 |
+
zc = (KNOB_MASS * zk + foot * zf) / M
|
| 384 |
+
I = np.array([mb * (Y * Y + Z * Z) / 12, mb * (X * X + Z * Z) / 12, mb * (X * X + Y * Y) / 12])
|
| 385 |
+
if foot:
|
| 386 |
+
I += foot * np.array([(Y * Y + FOOT_H ** 2) / 12, (X * X + FOOT_H ** 2) / 12, (X * X + Y * Y) / 12])
|
| 387 |
+
par = mb * zc ** 2 + KNOB_MASS * (zk - zc) ** 2 + foot * (zf - zc) ** 2
|
| 388 |
+
I[:2] += par
|
| 389 |
+
m.body_mass[bd] = M
|
| 390 |
+
m.body_ipos[bd] = [0, 0, zc]
|
| 391 |
+
m.body_iquat[bd] = [1, 0, 0, 0]
|
| 392 |
+
m.body_inertia[bd] = I
|
| 393 |
+
refit_bvh(m, bd)
|
| 394 |
+
return dict(mass=float(M), com_above_bottom=float(zc + hz))
|
| 395 |
+
|
| 396 |
+
def apply_instance(self, inst):
|
| 397 |
+
self.inst = inst
|
| 398 |
+
m = self.env.sim.model
|
| 399 |
+
self.body_info = {}
|
| 400 |
+
for p in POSTS:
|
| 401 |
+
self.body_info[p] = self._set_body(p, (inst["b"] / 2, inst["b"] / 2, inst["h"] / 2), inst["density_post"],
|
| 402 |
+
inst["foot_mass"])
|
| 403 |
+
for p in PANELS:
|
| 404 |
+
self.body_info[p] = self._set_body(p, (inst["t"] / 2, inst["w"] / 2, inst["h"] / 2),
|
| 405 |
+
inst["density_panel"])
|
| 406 |
+
for p in OBJS:
|
| 407 |
+
envs.set_friction(self.env, p, inst["mu"]) # board / stem / knob sliding friction ...
|
| 408 |
+
m.geom_friction[self.gid[p]["knob"]] = [1.0, KNOB_MU_T, 0.0001] # ... except the knob (grip pivot)
|
| 409 |
+
m.geom_friction[self.gid[p]["stem"]] = [1.0, 0.005, 0.0001]
|
| 410 |
+
m.geom_priority[self.gid[p]["knob"]] = 2
|
| 411 |
+
m.geom_condim[self.gid[p]["knob"]] = 4
|
| 412 |
+
self.env.sim.forward()
|
| 413 |
+
q = [np.cos(inst["pyaw"] / 2), 0, 0, np.sin(inst["pyaw"] / 2)]
|
| 414 |
+
for s, kind in enumerate(SLOT_KIND):
|
| 415 |
+
k = MARKS[s // 2] if kind == "post" else STRIPS[s // 2]
|
| 416 |
+
x, y = inst["slots"][s]
|
| 417 |
+
m.body_pos[self.fix_bid[k]] = [x, y, TZ + 0.0006]
|
| 418 |
+
m.body_quat[self.fix_bid[k]] = q
|
| 419 |
+
for g in self.fix_vis[k]:
|
| 420 |
+
m.geom_size[g] = ([inst["b"] / 2 + 0.003, inst["b"] / 2 + 0.003, 0.0005] if kind == "post" else
|
| 421 |
+
[STRIP_W / 2, inst["w"] / 2 + 0.005, 0.0005])
|
| 422 |
+
for p in OBJS:
|
| 423 |
+
envs.place_upright(self.env, p, inst["start"][p], yaw=inst["yaw0"][p], clearance=0.001)
|
| 424 |
+
|
| 425 |
+
def reset_instance(self, inst, recorder=None):
|
| 426 |
+
self.mon = None
|
| 427 |
+
self.env.reset()
|
| 428 |
+
self.apply_instance(inst)
|
| 429 |
+
self.env.sim.forward()
|
| 430 |
+
envs.settle(self.env, 15)
|
| 431 |
+
self.sk = FenceSkills(self.env, self, recorder=recorder)
|
| 432 |
+
self._sub_rob, self._sub_obj = {}, {}
|
| 433 |
+
n = len(SLOT_KIND)
|
| 434 |
+
self.mon = dict(state=[False] * n, raw_since=[0] * n, ever=[False] * n, lost=[False] * n, events=[],
|
| 435 |
+
last_robot={p: None for p in OBJS}, last_obj={p: None for p in OBJS},
|
| 436 |
+
fallen={p: False for p in OBJS}, occupant=[None] * n, n_steps=0)
|
| 437 |
+
return self.sk
|
| 438 |
+
|
| 439 |
+
# ------------------------------------------------------------ geometry / predicates
|
| 440 |
+
@staticmethod
|
| 441 |
+
def kind(p):
|
| 442 |
+
return "post" if p.startswith("post") else "panel"
|
| 443 |
+
|
| 444 |
+
def R(self, p):
|
| 445 |
+
return self.env.sim.data.body_xmat[envs.body_id(self.env, p)].reshape(3, 3).copy()
|
| 446 |
+
|
| 447 |
+
def pos(self, p):
|
| 448 |
+
return envs.obj_pos(self.env, p)
|
| 449 |
+
|
| 450 |
+
def tilt(self, p):
|
| 451 |
+
return float(np.arccos(np.clip(self.R(p)[2, 2], -1.0, 1.0)))
|
| 452 |
+
|
| 453 |
+
def knob_xyz(self, p):
|
| 454 |
+
return self.env.sim.data.geom_xpos[self.gid[p]["knob"]].copy()
|
| 455 |
+
|
| 456 |
+
def knob_stand_z(self):
|
| 457 |
+
"""grasp-point height (world) of a knob centre when its object stands on the table (posts = panel height)"""
|
| 458 |
+
return TZ + self.inst["h"] + STEM_L + KNOB_R
|
| 459 |
+
|
| 460 |
+
def held(self, p):
|
| 461 |
+
return self.sk is not None and self.sk.holding(p)
|
| 462 |
+
|
| 463 |
+
def on_slot(self, p, s, extra=0.0):
|
| 464 |
+
"""object p stands upright on fence slot s (right kind, lined up), resting on the table, not held"""
|
| 465 |
+
if self.kind(p) != SLOT_KIND[s]:
|
| 466 |
+
return False
|
| 467 |
+
R = self.R(p)
|
| 468 |
+
if R[2, 2] < np.cos(TILT_OK + (np.radians(1.0) if extra else 0.0)):
|
| 469 |
+
return False
|
| 470 |
+
rel = self.pos(p)[:2] - np.asarray(self.inst["slots"][s])
|
| 471 |
+
du = abs(rel @ np.asarray(self.inst["u"]))
|
| 472 |
+
dv = abs(rel @ np.asarray(self.inst["v"]))
|
| 473 |
+
if SLOT_KIND[s] == "post":
|
| 474 |
+
if max(du, dv) > TOL_POST + extra:
|
| 475 |
+
return False
|
| 476 |
+
else:
|
| 477 |
+
if du > TOL_U + extra or dv > TOL_V + extra:
|
| 478 |
+
return False
|
| 479 |
+
yaw = float(np.arctan2(R[1, 0], R[0, 0]))
|
| 480 |
+
if abs(_wrap_h(yaw - self.inst["pyaw"])) > YAW_TOL:
|
| 481 |
+
return False
|
| 482 |
+
if envs.obj_min_z(self.env, p) > TZ + 0.006:
|
| 483 |
+
return False
|
| 484 |
+
return not self.held(p)
|
| 485 |
+
|
| 486 |
+
def slot_occupant(self, s, extra=0.0):
|
| 487 |
+
return next((p for p in OBJS if self.on_slot(p, s, extra)), None)
|
| 488 |
+
|
| 489 |
+
def slot_filled(self, s, extra=0.0):
|
| 490 |
+
return self.slot_occupant(s, extra) is not None
|
| 491 |
+
|
| 492 |
+
def stages(self):
|
| 493 |
+
return [self.slot_filled(s) for s in range(len(SLOT_KIND))]
|
| 494 |
+
|
| 495 |
+
def stage_names(self):
|
| 496 |
+
out, kc = [], {"post": 0, "panel": 0}
|
| 497 |
+
for kind in SLOT_KIND:
|
| 498 |
+
kc[kind] += 1
|
| 499 |
+
out.append(f"{kind}{kc[kind]}")
|
| 500 |
+
return out
|
| 501 |
+
|
| 502 |
+
# ------------------------------------------------------------ monitor
|
| 503 |
+
def _contacts(self):
|
| 504 |
+
d = self.env.sim.data
|
| 505 |
+
rob, obj = {}, {}
|
| 506 |
+
for j in range(d.ncon):
|
| 507 |
+
c = d.contact[j]
|
| 508 |
+
a, b = c.geom1, c.geom2
|
| 509 |
+
pa, pb = self.geom_owner.get(a), self.geom_owner.get(b)
|
| 510 |
+
if pa is not None and pb is not None and pa != pb:
|
| 511 |
+
obj[pa], obj[pb] = pb, pa
|
| 512 |
+
for p, o in ((pa, b), (pb, a)):
|
| 513 |
+
if p is None:
|
| 514 |
+
continue
|
| 515 |
+
if o in self.finger_geoms:
|
| 516 |
+
rob[p] = "finger"
|
| 517 |
+
elif o in self.hand_geoms and rob.get(p) != "finger":
|
| 518 |
+
rob[p] = "hand"
|
| 519 |
+
return rob, obj
|
| 520 |
+
|
| 521 |
+
def monitor_step(self):
|
| 522 |
+
mon = self.mon
|
| 523 |
+
if mon is None or self.sk is None:
|
| 524 |
+
return
|
| 525 |
+
mon["n_steps"] += 1
|
| 526 |
+
t = self.sk.n_steps
|
| 527 |
+
rob = {OBJS[i]: ("finger" if v == 1 else "hand") for i, v in self._sub_rob.items()}
|
| 528 |
+
obj = {OBJS[i]: OBJS[j] for i, j in self._sub_obj.items()}
|
| 529 |
+
self._sub_rob, self._sub_obj = {}, {}
|
| 530 |
+
held = [p for p in OBJS if self.held(p)]
|
| 531 |
+
for p, part in rob.items():
|
| 532 |
+
if p not in held:
|
| 533 |
+
mon["last_robot"][p] = (part, t, "open" if self.sk.grip < 0 else "closed")
|
| 534 |
+
for p, q in obj.items():
|
| 535 |
+
if p not in held:
|
| 536 |
+
mon["last_obj"][p] = (q + (" (held)" if q in held else ""), t)
|
| 537 |
+
for p in OBJS:
|
| 538 |
+
f = self.tilt(p) > FALLEN
|
| 539 |
+
if f != mon["fallen"][p]:
|
| 540 |
+
mon["fallen"][p] = f
|
| 541 |
+
if f:
|
| 542 |
+
mon["events"].append(dict(object=p, event="toppled", step=int(t), cause=self._cause(p, t)))
|
| 543 |
+
else:
|
| 544 |
+
mon["events"].append(dict(object=p, event="stood_up", step=int(t)))
|
| 545 |
+
if mon["n_steps"] % 2:
|
| 546 |
+
return
|
| 547 |
+
names = self.stage_names()
|
| 548 |
+
for s in range(len(SLOT_KIND)):
|
| 549 |
+
occ = self.slot_occupant(s, HYST if mon["state"][s] else 0.0)
|
| 550 |
+
raw = occ is not None
|
| 551 |
+
if raw:
|
| 552 |
+
mon["occupant"][s] = occ
|
| 553 |
+
if raw == mon["state"][s]:
|
| 554 |
+
mon["raw_since"][s] = 0
|
| 555 |
+
continue
|
| 556 |
+
mon["raw_since"][s] += 2
|
| 557 |
+
if mon["raw_since"][s] < DEBOUNCE:
|
| 558 |
+
continue
|
| 559 |
+
mon["state"][s] = raw
|
| 560 |
+
mon["raw_since"][s] = 0
|
| 561 |
+
t0 = t - DEBOUNCE + 1
|
| 562 |
+
if raw:
|
| 563 |
+
ev = dict(stage=names[s], event="restored" if mon["lost"][s] else "achieved", step=int(t0))
|
| 564 |
+
mon["ever"][s] = True
|
| 565 |
+
else:
|
| 566 |
+
mon["lost"][s] = True
|
| 567 |
+
ev = dict(stage=names[s], event="lost", step=int(t0), cause=self._slot_cause(s, t))
|
| 568 |
+
mon["events"].append(ev)
|
| 569 |
+
|
| 570 |
+
def _cause(self, p, t):
|
| 571 |
+
if self.held(p):
|
| 572 |
+
return "picked_up"
|
| 573 |
+
lr, lo = self.mon["last_robot"][p], self.mon["last_obj"][p]
|
| 574 |
+
cands = []
|
| 575 |
+
if lr is not None and t - lr[1] <= 60:
|
| 576 |
+
cands.append((lr[1], f"robot_{lr[0]}" + ("_opening" if lr[2] == "open" else "")))
|
| 577 |
+
if lo is not None and t - lo[1] <= 60:
|
| 578 |
+
cands.append((lo[1] - 30, "object:" + lo[0])) # prefer the robot when both touched it recently
|
| 579 |
+
return max(cands)[1] if cands else "other"
|
| 580 |
+
|
| 581 |
+
def _slot_cause(self, s, t):
|
| 582 |
+
"""why slot s lost its object: the cause recorded for the object that last stood on it"""
|
| 583 |
+
p = self.mon["occupant"][s]
|
| 584 |
+
if p is None:
|
| 585 |
+
c = np.asarray(self.inst["slots"][s])
|
| 586 |
+
p = min(OBJS, key=lambda q: float(np.linalg.norm(self.pos(q)[:2] - c)))
|
| 587 |
+
return self._cause(p, t)
|
| 588 |
+
|
| 589 |
+
# ------------------------------------------------------------ outcome
|
| 590 |
+
def _slot_name(self, s):
|
| 591 |
+
kind = SLOT_KIND[s]
|
| 592 |
+
idx = [i for i in range(len(SLOT_KIND)) if SLOT_KIND[i] == kind]
|
| 593 |
+
n = len(idx)
|
| 594 |
+
k = idx.index(s) # 0-based along +u
|
| 595 |
+
if self.inst["row"] == "lr": # u = +y = robot's left: count from the robot's right
|
| 596 |
+
what = "square mark" if kind == "post" else "strip"
|
| 597 |
+
return f"{what} {k + 1} of {n} (counting from the robot's right)"
|
| 598 |
+
what = "square mark" if kind == "post" else "strip"
|
| 599 |
+
u = self.inst["u"]
|
| 600 |
+
return f"{what} {k + 1 if u[0] > 0 else n - k} of {n} (counting from the one nearest the robot)"
|
| 601 |
+
|
| 602 |
+
def _dir_words(self, d):
|
| 603 |
+
parts = []
|
| 604 |
+
if abs(d[0]) >= 0.01:
|
| 605 |
+
parts.append(f"{100 * abs(d[0]):.0f} cm {'forward' if d[0] > 0 else 'back'}")
|
| 606 |
+
if abs(d[1]) >= 0.01:
|
| 607 |
+
parts.append(f"{100 * abs(d[1]):.0f} cm {'left' if d[1] > 0 else 'right'}")
|
| 608 |
+
return (" and ".join(parts) + " of") if parts else "right at"
|
| 609 |
+
|
| 610 |
+
def placed_objects(self):
|
| 611 |
+
return {p for p in OBJS if any(self.on_slot(p, s) for s in range(len(SLOT_KIND)))}
|
| 612 |
+
|
| 613 |
+
def outcome(self, inst):
|
| 614 |
+
sk = self.sk
|
| 615 |
+
sk.hold(10)
|
| 616 |
+
p0 = {p: self.pos(p) for p in OBJS}
|
| 617 |
+
touching = False
|
| 618 |
+
for _ in range(20):
|
| 619 |
+
sk.hold(1)
|
| 620 |
+
rob, _ = self._contacts()
|
| 621 |
+
touching = touching or any(p in rob for p in OBJS)
|
| 622 |
+
moved = max(float(np.linalg.norm(self.pos(p) - p0[p])) for p in OBJS)
|
| 623 |
+
static = moved < 0.004
|
| 624 |
+
raw = self.stages()
|
| 625 |
+
held = [p for p in OBJS if self.held(p)]
|
| 626 |
+
mon = self.mon
|
| 627 |
+
ev = list(mon["events"]) if mon else []
|
| 628 |
+
n_reg = sum(e["event"] == "lost" for e in ev)
|
| 629 |
+
n_res = sum(e["event"] == "restored" for e in ev)
|
| 630 |
+
n_top = sum(e["event"] == "toppled" for e in ev)
|
| 631 |
+
success = bool(all(raw) and static and not held and not touching)
|
| 632 |
+
names = self.stage_names()
|
| 633 |
+
parts = []
|
| 634 |
+
ever = mon["ever"] if mon else [False] * len(raw)
|
| 635 |
+
if success:
|
| 636 |
+
failure = "none"
|
| 637 |
+
parts.append("The fence is complete: every square mark carries an upright post and every strip an "
|
| 638 |
+
"upright panel lined up with it.")
|
| 639 |
+
else:
|
| 640 |
+
lost_final = [s for s in range(len(raw)) if not raw[s] and ever[s]]
|
| 641 |
+
never = [s for s in range(len(raw)) if not raw[s] and not ever[s]]
|
| 642 |
+
if held:
|
| 643 |
+
failure = "held"
|
| 644 |
+
elif touching:
|
| 645 |
+
failure = "touching"
|
| 646 |
+
elif lost_final:
|
| 647 |
+
failure = "regressed"
|
| 648 |
+
elif never:
|
| 649 |
+
failure = "incomplete"
|
| 650 |
+
else:
|
| 651 |
+
failure = "not_static"
|
| 652 |
+
placed = self.placed_objects()
|
| 653 |
+
described = set()
|
| 654 |
+
for s in range(len(raw)):
|
| 655 |
+
if raw[s]:
|
| 656 |
+
continue
|
| 657 |
+
kind = SLOT_KIND[s]
|
| 658 |
+
c = np.asarray(inst["slots"][s])
|
| 659 |
+
spare = [q for q in OBJS if self.kind(q) == kind and q not in placed and q not in described]
|
| 660 |
+
near = min(spare, key=lambda q: float(np.linalg.norm(self.pos(q)[:2] - c))) if spare else None
|
| 661 |
+
dist = float(np.linalg.norm(self.pos(near)[:2] - c)) if near else 1.0
|
| 662 |
+
if near is None or (not ever[s] and dist > 0.06):
|
| 663 |
+
txt = f"{self._slot_name(s)} has no {kind} on it (none was put there)."
|
| 664 |
+
else:
|
| 665 |
+
described.add(near)
|
| 666 |
+
tl = np.degrees(self.tilt(near))
|
| 667 |
+
state = ("lies fallen" if tl > 45 else f"leans {tl:.0f} degrees" if tl > np.degrees(TILT_OK)
|
| 668 |
+
else "stands")
|
| 669 |
+
txt = (f"{self._slot_name(s)} has no upright {kind} on it: the nearest {kind} {state} "
|
| 670 |
+
f"{self._dir_words(self.pos(near)[:2] - c)} it.")
|
| 671 |
+
if ever[s]:
|
| 672 |
+
lost = [e for e in ev if e.get("stage") == names[s] and e["event"] == "lost"]
|
| 673 |
+
why = lost[-1]["cause"] if lost else "other"
|
| 674 |
+
txt += {"robot_finger_opening": f" The {kind} had stood there; a finger pushed it when the "
|
| 675 |
+
f"gripper opened.",
|
| 676 |
+
"robot_hand_opening": f" The {kind} had stood there; the hand pushed it.",
|
| 677 |
+
}.get(why, f" The {kind} had stood there and was knocked over later."
|
| 678 |
+
if why.startswith(("robot", "object")) else f" The {kind} had stood there earlier.")
|
| 679 |
+
parts.append(txt)
|
| 680 |
+
if all(raw) and held:
|
| 681 |
+
parts.append("The gripper still holds an object.")
|
| 682 |
+
elif touching:
|
| 683 |
+
parts.append("The gripper is still touching the fence.")
|
| 684 |
+
elif all(raw) and not static:
|
| 685 |
+
parts.append("Something was still moving.")
|
| 686 |
+
if n_reg:
|
| 687 |
+
parts.append(f"During the attempt objects on the fence line were knocked off {n_reg} time(s) and stood "
|
| 688 |
+
f"up again {n_res} time(s).")
|
| 689 |
+
if any(w in " ".join(parts) for w in (" forward of", " back of", " back and", " forward and")):
|
| 690 |
+
parts.append("(Forward = away from the robot.)")
|
| 691 |
+
return dict(success=success, stages={names[s]: bool(raw[s]) for s in range(len(raw))}, events=ev,
|
| 692 |
+
n_regressions=int(n_reg), n_restored=int(n_res), n_toppled=int(n_top), failure=failure,
|
| 693 |
+
held=held, touching=bool(touching), static=bool(static),
|
| 694 |
+
tilts_deg={p: round(float(np.degrees(self.tilt(p))), 1) for p in OBJS}, detail=" ".join(parts))
|
| 695 |
+
|
| 696 |
+
# ------------------------------------------------------------ scripted policies (move_to + gripper only)
|
| 697 |
+
def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300):
|
| 698 |
+
return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
|
| 699 |
+
|
| 700 |
+
def axis(self, p, i):
|
| 701 |
+
a = self.R(p)[:2, i]
|
| 702 |
+
return a / max(np.linalg.norm(a), 1e-9)
|
| 703 |
+
|
| 704 |
+
def grasp_yaw(self, p, mode):
|
| 705 |
+
"""yaw for a top-down knob grasp. Lying object: fingers across its long axis (it swings up and hangs).
|
| 706 |
+
Panel: 'habit' = fingers along its width (hand along the board; along the fence line once placed),
|
| 707 |
+
'thin' = fingers along its thickness (across the line). Post: 'thin' = fingers across the fence line, otherwise
|
| 708 |
+
the side direction needing the least rotation (a post's own orientation does not matter: square, round knob)."""
|
| 709 |
+
R = self.R(p)
|
| 710 |
+
if R[2, 2] < np.cos(np.radians(30)):
|
| 711 |
+
ax = R[:2, 2]
|
| 712 |
+
if np.linalg.norm(ax) > 1e-3:
|
| 713 |
+
return _yaw_for_axis(np.array([-ax[1], ax[0]]))
|
| 714 |
+
if self.kind(p) == "panel":
|
| 715 |
+
return _yaw_for_axis(self.axis(p, 1) if mode == "habit" else self.axis(p, 0))
|
| 716 |
+
if mode == "thin": # careful: a post's fingers across the fence line too (they reach nothing there)
|
| 717 |
+
return _yaw_for_axis(np.asarray(self.inst["v"]))
|
| 718 |
+
y0 = _yaw_for_axis(self.axis(p, 0))
|
| 719 |
+
return min((_wrap_h(y0), _wrap_h(y0 + np.pi / 2)), key=lambda y: abs(_wrap_h(y - self.sk.yaw)))
|
| 720 |
+
|
| 721 |
+
def obj_yaw(self, p):
|
| 722 |
+
R = self.R(p)
|
| 723 |
+
return float(np.arctan2(R[1, 0], R[0, 0]))
|
| 724 |
+
|
| 725 |
+
def pick(self, p, mode, careful, z_carry=None, noise=None, v=0.15):
|
| 726 |
+
"""grasp p's knob and lift it; returns (object yaw - gripper yaw) or None if not held"""
|
| 727 |
+
sk = self.sk
|
| 728 |
+
k = self.knob_xyz(p)
|
| 729 |
+
if noise is not None:
|
| 730 |
+
k = k + np.array([noise[0], noise[1], 0.0])
|
| 731 |
+
yaw = self.grasp_yaw(p, mode)
|
| 732 |
+
zk = max(k[2], TZ + 0.006)
|
| 733 |
+
sk.set_gripper(False, steps=8)
|
| 734 |
+
if careful:
|
| 735 |
+
cur = sk.eef_pos()
|
| 736 |
+
if cur[2] < TZ + Z_SAFE - 0.01:
|
| 737 |
+
self._go([cur[0], cur[1], TZ + Z_SAFE])
|
| 738 |
+
self._go([k[0], k[1], TZ + Z_SAFE], yaw=yaw, speed=0.3)
|
| 739 |
+
self._go([k[0], k[1], zk + 0.04], speed=0.25)
|
| 740 |
+
self._go([k[0], k[1], zk], speed=0.1, tol=0.003, max_steps=150)
|
| 741 |
+
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
|
| 742 |
+
zt = TZ + (Z_NAIVE if z_carry is None else z_carry)
|
| 743 |
+
cur = sk.eef_pos()
|
| 744 |
+
self._go([k[0], k[1], max(cur[2], zt, zk + 0.06)], yaw=yaw, speed=v)
|
| 745 |
+
self._go([k[0], k[1], zk + 0.015], speed=0.1)
|
| 746 |
+
self._go([k[0], k[1], zk], speed=0.04, tol=0.003, max_steps=150)
|
| 747 |
+
sk.set_gripper(True, steps=15)
|
| 748 |
+
if careful:
|
| 749 |
+
self._go([k[0], k[1], TZ + Z_SAFE], speed=0.25)
|
| 750 |
+
else:
|
| 751 |
+
self._go([k[0], k[1], TZ + (Z_NAIVE if z_carry is None else z_carry)], speed=0.08)
|
| 752 |
+
sk.hold(10)
|
| 753 |
+
if not self.held(p):
|
| 754 |
+
sk.set_gripper(False, steps=8) # already lifted: the fingers open well above the object
|
| 755 |
+
return None
|
| 756 |
+
return float(self.obj_yaw(p) - sk.yaw)
|
| 757 |
+
|
| 758 |
+
def release_z(self, p):
|
| 759 |
+
"""grasp-point height at which the held object's bottom is 2 mm above the table (a heavy object's knob can
|
| 760 |
+
sit a few mm low in the fingers; pressing it onto the table would squeeze the knob out of the grip)"""
|
| 761 |
+
dz = float(self.sk.eef_pos()[2] - self.knob_xyz(p)[2]) if self.held(p) else 0.0
|
| 762 |
+
return self.knob_stand_z() + 0.002 + float(np.clip(dz, -0.005, 0.015))
|
| 763 |
+
|
| 764 |
+
def place_yaw(self, p, offset):
|
| 765 |
+
"""gripper yaw that lines p up with the fence (panel: width along the line; post: sides along it)"""
|
| 766 |
+
if self.kind(p) == "panel":
|
| 767 |
+
return _wrap_h(self.inst["pyaw"] - offset)
|
| 768 |
+
cands = [_wrap_h(self.inst["pyaw"] + k * np.pi / 2 - offset) for k in range(4)]
|
| 769 |
+
return min(cands, key=lambda y: abs(_wrap_h(y - self.sk.yaw)))
|
| 770 |
+
|
| 771 |
+
def place(self, p, s, offset, careful, z_carry=None, noise=None, lift=None, v=0.15):
|
| 772 |
+
"""carry the held object to fence slot s, lined up with the fence; set it down; let go"""
|
| 773 |
+
sk = self.sk
|
| 774 |
+
xy = np.asarray(self.inst["slots"][s], float) + (np.asarray(noise, float) if noise is not None else 0.0)
|
| 775 |
+
yaw = self.place_yaw(p, offset)
|
| 776 |
+
zr = self.release_z(p)
|
| 777 |
+
if careful:
|
| 778 |
+
cur = sk.eef_pos()
|
| 779 |
+
if cur[2] < TZ + Z_SAFE - 0.01:
|
| 780 |
+
self._go([cur[0], cur[1], TZ + Z_SAFE])
|
| 781 |
+
self._go([xy[0], xy[1], TZ + Z_SAFE], yaw=yaw, speed=0.3)
|
| 782 |
+
sk.hold(15)
|
| 783 |
+
zr = self.release_z(p)
|
| 784 |
+
self._go([xy[0], xy[1], zr + 0.03], speed=0.2)
|
| 785 |
+
self._go([xy[0], xy[1], zr], speed=0.06, tol=0.003, max_steps=150)
|
| 786 |
+
sk.set_gripper(False, steps=12)
|
| 787 |
+
self._go([xy[0], xy[1], zr + 0.04], speed=0.1)
|
| 788 |
+
self._go([xy[0], xy[1], TZ + Z_SAFE], speed=0.3)
|
| 789 |
+
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
|
| 790 |
+
zt = TZ + (Z_NAIVE if z_carry is None else z_carry)
|
| 791 |
+
cur = sk.eef_pos()
|
| 792 |
+
self._go([xy[0], xy[1], max(cur[2], zt)], yaw=yaw, speed=v)
|
| 793 |
+
self._go([xy[0], xy[1], zr + 0.015], speed=0.1)
|
| 794 |
+
self._go([xy[0], xy[1], zr], speed=0.03, tol=0.003, max_steps=150)
|
| 795 |
+
sk.set_gripper(False, steps=12)
|
| 796 |
+
self._go([xy[0], xy[1], TZ + (Z_NAIVE if lift is None else lift)], speed=0.15)
|
| 797 |
+
sk.hold(5)
|
| 798 |
+
|
| 799 |
+
# orders ---------------------------------------------------------------
|
| 800 |
+
def supply_center(self):
|
| 801 |
+
return np.mean([self.inst["start"][p] for p in OBJS], axis=0)
|
| 802 |
+
|
| 803 |
+
def fence_order(self, far_first=True):
|
| 804 |
+
"""slot indices from the end of the line farthest from the supply to the near end (or reversed)"""
|
| 805 |
+
sc = self.supply_center()
|
| 806 |
+
first, last = np.asarray(self.inst["slots"][0]), np.asarray(self.inst["slots"][-1])
|
| 807 |
+
idx = list(range(len(SLOT_KIND)))
|
| 808 |
+
near_first = idx if np.linalg.norm(first - sc) <= np.linalg.norm(last - sc) else idx[::-1]
|
| 809 |
+
return near_first[::-1] if far_first else near_first
|
| 810 |
+
|
| 811 |
+
def build(self, order, careful, panel_mode, noise_fn=lambda: None, z_carry=None, lift=None, noise_pick=False,
|
| 812 |
+
v=0.15):
|
| 813 |
+
"""put an object on every slot that has none, in the given slot order; the object for each slot: an unused
|
| 814 |
+
one of the right kind, the nearest to the gripper (naive) / to the slot (careful). No looking back."""
|
| 815 |
+
fails = {}
|
| 816 |
+
used = set()
|
| 817 |
+
for s in order:
|
| 818 |
+
if self.slot_filled(s):
|
| 819 |
+
continue
|
| 820 |
+
for _ in range(2):
|
| 821 |
+
cand = [p for p in OBJS if self.kind(p) == SLOT_KIND[s] and p not in used and fails.get(p, 0) < 2
|
| 822 |
+
and p not in self.placed_objects()]
|
| 823 |
+
if not cand:
|
| 824 |
+
break
|
| 825 |
+
ref = np.asarray(self.inst["slots"][s]) if careful else self.sk.eef_pos()[:2]
|
| 826 |
+
p = min(cand, key=lambda q: float(np.linalg.norm(self.pos(q)[:2] - ref)))
|
| 827 |
+
mode = panel_mode if self.kind(p) == "panel" else ("thin" if careful else "any")
|
| 828 |
+
off = self.pick(p, mode, careful, z_carry=z_carry, noise=noise_fn() if noise_pick else None, v=v)
|
| 829 |
+
if off is None:
|
| 830 |
+
fails[p] = fails.get(p, 0) + 1
|
| 831 |
+
continue
|
| 832 |
+
used.add(p)
|
| 833 |
+
self.place(p, s, off, careful, z_carry=z_carry, noise=noise_fn(), lift=lift, v=v)
|
| 834 |
+
break
|
| 835 |
+
|
| 836 |
+
def footprint(self, p):
|
| 837 |
+
"""sample points of p's collision box projected onto the table (corners, edge and face midpoints) + knob"""
|
| 838 |
+
R, c = self.R(p), self.pos(p)
|
| 839 |
+
if self.kind(p) == "panel":
|
| 840 |
+
h = np.array([self.inst["t"], self.inst["w"], self.inst["h"]]) / 2
|
| 841 |
+
else:
|
| 842 |
+
h = np.array([self.inst["b"], self.inst["b"], self.inst["h"]]) / 2
|
| 843 |
+
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)]
|
| 844 |
+
pts.append(self.knob_xyz(p))
|
| 845 |
+
return np.array(pts)[:, :2]
|
| 846 |
+
|
| 847 |
+
def slot_blocked(self, s, ignore=()):
|
| 848 |
+
"""an object that is not standing on a slot lies (partly) on slot s or right next to it"""
|
| 849 |
+
c = np.asarray(self.inst["slots"][s])
|
| 850 |
+
u, v = np.asarray(self.inst["u"]), np.asarray(self.inst["v"])
|
| 851 |
+
hu = (self.inst["w"] if SLOT_KIND[s] == "panel" else self.inst["b"]) / 2 + 0.003
|
| 852 |
+
hv = (self.inst["t"] if SLOT_KIND[s] == "panel" else self.inst["b"]) / 2 + 0.008
|
| 853 |
+
placed = self.placed_objects()
|
| 854 |
+
for q in OBJS:
|
| 855 |
+
if q in ignore or self.held(q) or q in placed: # objects standing on their own slots are fine
|
| 856 |
+
continue
|
| 857 |
+
d = self.footprint(q) - c
|
| 858 |
+
if np.any((np.abs(d @ u) < hu) & (np.abs(d @ v) < hv)):
|
| 859 |
+
return True
|
| 860 |
+
return False
|
| 861 |
+
|
| 862 |
+
def fingers_along_width(self, p):
|
| 863 |
+
"""the held panel's width axis is (nearly) parallel to the finger axis"""
|
| 864 |
+
fa = np.array([-np.sin(self.sk.yaw), np.cos(self.sk.yaw)])
|
| 865 |
+
return abs(float(self.axis(p, 1) @ fa)) > 0.7
|
| 866 |
+
|
| 867 |
+
def repair(self, rounds=None):
|
| 868 |
+
"""look at every slot; stand fallen / misplaced objects up again by their knobs (careful motions, panels
|
| 869 |
+
released with the fingers across the line). Order: an object resting on another first, then fallen / leaning
|
| 870 |
+
ones from the top of the pile down, then upright ones that are off their slots. A panel lifted with its
|
| 871 |
+
fingers along its width (a fallen panel can only be lifted that way) is first set down standing at a free spot
|
| 872 |
+
and re-grasped. Returns the number of objects moved."""
|
| 873 |
+
n = len(SLOT_KIND)
|
| 874 |
+
moved = 0
|
| 875 |
+
fails, moves = {}, {}
|
| 876 |
+
for _ in range(rounds or 16):
|
| 877 |
+
if all(self.stages()):
|
| 878 |
+
break
|
| 879 |
+
ok = self.placed_objects()
|
| 880 |
+
loose = [p for p in OBJS if p not in ok and fails.get(p, 0) < 2 and moves.get(p, 0) < 4]
|
| 881 |
+
if not loose:
|
| 882 |
+
break
|
| 883 |
+
on_other = [p for p in loose if envs.obj_min_z(self.env, p) > TZ + 0.006]
|
| 884 |
+
down = [p for p in loose if p not in on_other and self.tilt(p) > TILT_OK]
|
| 885 |
+
upright = [p for p in loose if p not in on_other and p not in down]
|
| 886 |
+
if on_other:
|
| 887 |
+
p = max(on_other, key=lambda q: self.knob_xyz(q)[2])
|
| 888 |
+
elif down:
|
| 889 |
+
p = max(down, key=lambda q: self.knob_xyz(q)[2])
|
| 890 |
+
else:
|
| 891 |
+
fit = {q: [s for s in range(n) if SLOT_KIND[s] == self.kind(q) and not self.slot_filled(s)
|
| 892 |
+
and not self.slot_blocked(s, ignore=(q,))] for q in upright}
|
| 893 |
+
fit = {q: js for q, js in fit.items() if js}
|
| 894 |
+
if not fit:
|
| 895 |
+
break
|
| 896 |
+
p = min(fit, key=lambda q: min(float(np.linalg.norm(self.pos(q)[:2] - np.asarray(
|
| 897 |
+
self.inst["slots"][s]))) for s in fit[q]))
|
| 898 |
+
off = self.pick(p, "thin", True)
|
| 899 |
+
if off is None:
|
| 900 |
+
fails[p] = fails.get(p, 0) + 1
|
| 901 |
+
continue
|
| 902 |
+
moved += 1
|
| 903 |
+
moves[p] = moves.get(p, 0) + 1
|
| 904 |
+
if self.kind(p) == "panel" and self.fingers_along_width(p):
|
| 905 |
+
self.place_at(p, self.free_spot(), off)
|
| 906 |
+
continue
|
| 907 |
+
clear = [s for s in range(n) if SLOT_KIND[s] == self.kind(p) and not self.slot_filled(s)
|
| 908 |
+
and not self.slot_blocked(s, ignore=(p,))]
|
| 909 |
+
if not clear:
|
| 910 |
+
self.place_at(p, self.free_spot(), off)
|
| 911 |
+
continue
|
| 912 |
+
here = self.sk.eef_pos()[:2]
|
| 913 |
+
s = min(clear, key=lambda j: float(np.linalg.norm(np.asarray(self.inst["slots"][j]) - here)))
|
| 914 |
+
self.place(p, s, off, True)
|
| 915 |
+
return moved
|
| 916 |
+
|
| 917 |
+
def free_spot(self):
|
| 918 |
+
"""the reachable table spot (around the fence and the supply) farthest from every object and slot"""
|
| 919 |
+
c, v = np.asarray(self.inst["center"]), np.asarray(self.inst["v"])
|
| 920 |
+
u = np.asarray(self.inst["u"])
|
| 921 |
+
best, bc = None, -1.0
|
| 922 |
+
for a in np.linspace(-0.20, 0.20, 9):
|
| 923 |
+
for b in (-0.18, -0.12, 0.10, 0.20, 0.32):
|
| 924 |
+
q = c + v * b + u * a
|
| 925 |
+
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:
|
| 926 |
+
continue
|
| 927 |
+
cl = min(float(np.linalg.norm(self.pos(o)[:2] - q)) for o in OBJS)
|
| 928 |
+
cl = min(cl, min(float(np.linalg.norm(np.asarray(sl) - q)) for sl in self.inst["slots"]))
|
| 929 |
+
if cl > bc:
|
| 930 |
+
best, bc = q, cl
|
| 931 |
+
return best
|
| 932 |
+
|
| 933 |
+
def place_at(self, p, xy, offset):
|
| 934 |
+
"""careful: set the held object down standing at a free spot"""
|
| 935 |
+
sk = self.sk
|
| 936 |
+
zr = self.release_z(p)
|
| 937 |
+
cur = sk.eef_pos()
|
| 938 |
+
if cur[2] < TZ + Z_SAFE - 0.01:
|
| 939 |
+
self._go([cur[0], cur[1], TZ + Z_SAFE])
|
| 940 |
+
self._go([xy[0], xy[1], TZ + Z_SAFE], yaw=self.place_yaw(p, offset), speed=0.3)
|
| 941 |
+
sk.hold(15)
|
| 942 |
+
zr = self.release_z(p)
|
| 943 |
+
self._go([xy[0], xy[1], zr + 0.03], speed=0.2)
|
| 944 |
+
self._go([xy[0], xy[1], zr], speed=0.06, tol=0.003, max_steps=200)
|
| 945 |
+
sk.set_gripper(False, steps=12)
|
| 946 |
+
self._go([xy[0], xy[1], zr + 0.04], speed=0.1)
|
| 947 |
+
self._go([xy[0], xy[1], TZ + Z_SAFE], speed=0.3)
|
| 948 |
+
|
| 949 |
+
# ------------------------------------------------------------ policies
|
| 950 |
+
def execute(self, inst, params):
|
| 951 |
+
careful = params["careful"]
|
| 952 |
+
noise = params.get("noise", 0.0)
|
| 953 |
+
rng = np.random.default_rng(params.get("noise_seed", 0))
|
| 954 |
+
nf = (lambda: rng.uniform(-noise, noise, 2)) if noise else (lambda: None)
|
| 955 |
+
if params.get("order") == "panels_first":
|
| 956 |
+
fo = self.fence_order(True)
|
| 957 |
+
order = [s for s in fo if SLOT_KIND[s] == "panel"] + [s for s in fo if SLOT_KIND[s] == "post"]
|
| 958 |
+
elif params.get("order") == "posts_first":
|
| 959 |
+
fo = self.fence_order(True)
|
| 960 |
+
order = [s for s in fo if SLOT_KIND[s] == "post"] + [s for s in fo if SLOT_KIND[s] == "panel"]
|
| 961 |
+
else:
|
| 962 |
+
order = self.fence_order(params.get("far_first", True))
|
| 963 |
+
self.build(order, careful, params["panel_mode"], noise_fn=nf, z_carry=params.get("z_carry"),
|
| 964 |
+
lift=params.get("lift"), noise_pick=params.get("noise_pick", False), v=params.get("v", 0.15))
|
| 965 |
+
if params.get("check"):
|
| 966 |
+
self.repair()
|
| 967 |
+
cur = self.sk.eef_pos()
|
| 968 |
+
if cur[2] < TZ + 0.20:
|
| 969 |
+
self._go([cur[0], cur[1], TZ + 0.20], speed=0.3)
|
| 970 |
+
self.sk.hold(10)
|
| 971 |
+
|
| 972 |
+
# naive = Sonnet 5.5's habits measured in the lh2_fence pilot: hand (finger axis) along the board's long side, fill
|
| 973 |
+
# 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
|
| 974 |
+
NAIVE = dict(careful=False, panel_mode="habit", far_first=True, check=False, noise=NAIVE_ERR)
|
| 975 |
+
CAREFUL = dict(careful=True, panel_mode="thin", far_first=True, check=True)
|
| 976 |
+
V1_NAIVE = dict(careful=False, panel_mode="thin", far_first=False, check=False) # v1's scripted naive habits
|
| 977 |
+
|
| 978 |
+
def default_params(self, inst):
|
| 979 |
+
return dict(self.NAIVE, noise_seed=int(inst["seed"]) * 11)
|
| 980 |
+
|
| 981 |
+
def oracle_params(self, inst):
|
| 982 |
+
return dict(self.CAREFUL)
|
| 983 |
+
|
| 984 |
+
def adapt_params(self, inst, history):
|
| 985 |
+
"""from attempt 2 (after a failure): panels released with the fingers across the line, careful, final check"""
|
| 986 |
+
return dict(self.CAREFUL)
|
| 987 |
+
|
| 988 |
+
def blind_params(self, inst, attempt, rng):
|
| 989 |
+
"""the naive behaviour with random variations, no history, no check"""
|
| 990 |
+
return dict(self.NAIVE, noise_seed=int(rng.integers(1 << 30)), z_carry=float(rng.uniform(0.15, 0.23)),
|
| 991 |
+
lift=float(rng.uniform(0.15, 0.23)), v=float(rng.uniform(0.08, 0.25)))
|
| 992 |
+
|
| 993 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 994 |
+
k = k or self.max_attempts
|
| 995 |
+
rng = np.random.default_rng(seed)
|
| 996 |
+
history = []
|
| 997 |
+
single = ("oracle", "naive", "oracle_noise", "v1_naive", "naive_thin", "naive_panels_first",
|
| 998 |
+
"naive_posts_first")
|
| 999 |
+
for a in range(k):
|
| 1000 |
+
self.reset_instance(inst)
|
| 1001 |
+
if kind == "oracle":
|
| 1002 |
+
params = self.oracle_params(inst)
|
| 1003 |
+
elif kind == "naive":
|
| 1004 |
+
params = self.default_params(inst)
|
| 1005 |
+
elif kind == "adaptive":
|
| 1006 |
+
params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history)
|
| 1007 |
+
elif kind == "blind":
|
| 1008 |
+
params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
|
| 1009 |
+
elif kind == "switch": # control: cross-attempt learning only (careful from attempt 2), no check
|
| 1010 |
+
params = self.default_params(inst) if a == 0 else dict(self.CAREFUL, check=False)
|
| 1011 |
+
elif kind == "oracle_noise": # check: careful with +-5 mm (uniform, per axis) placement noise
|
| 1012 |
+
params = dict(self.CAREFUL, noise=0.005, noise_seed=int(seed) * 7 + a)
|
| 1013 |
+
elif kind == "v1_naive": # control: v1's scripted naive (fingers across the line, near end first)
|
| 1014 |
+
params = dict(self.V1_NAIVE)
|
| 1015 |
+
elif kind == "naive_thin": # control: Sonnet-like but panels released with the fingers across the line
|
| 1016 |
+
params = dict(self.default_params(inst), panel_mode="thin")
|
| 1017 |
+
elif kind == "naive_panels_first": # control: Sonnet-like grasp, both panels before the posts
|
| 1018 |
+
params = dict(self.default_params(inst), order="panels_first")
|
| 1019 |
+
elif kind == "naive_posts_first": # control: Sonnet-like grasp, all posts first (how fences are built)
|
| 1020 |
+
params = dict(self.default_params(inst), order="posts_first")
|
| 1021 |
+
else:
|
| 1022 |
+
raise ValueError(kind)
|
| 1023 |
+
self.execute(inst, params)
|
| 1024 |
+
out = self.outcome(inst)
|
| 1025 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 1026 |
+
if on_attempt:
|
| 1027 |
+
on_attempt(a, params, out)
|
| 1028 |
+
if out["success"] or kind in single:
|
| 1029 |
+
break
|
| 1030 |
+
return history
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/lh_parts_cart.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Composite prototype: physical tool retrieval, loading regression and asymmetric cart transport.
|
| 2 |
+
|
| 3 |
+
Not part of main_v1. See task_cards/lh_parts_cart.md for validation status.
|
| 4 |
+
Only reset_instance/apply_instance position objects; all reference actions use the public motion skills.
|
| 5 |
+
"""
|
| 6 |
+
import copy
|
| 7 |
+
import numpy as np
|
| 8 |
+
from .. import envs
|
| 9 |
+
from ..bddl import write_bddl
|
| 10 |
+
from ..objects import register_generated, box_xml
|
| 11 |
+
from ..task_base import register_task
|
| 12 |
+
from .l3_tool import (UnderTableTool, low_table_xml, stick_xml, CUBE_HALF,
|
| 13 |
+
HANDLE_HALF, TOP_HALF)
|
| 14 |
+
from .l7_offcenter_push import (OffcenterPush, PushSkills, long_box_xml, rect_frame_xml,
|
| 15 |
+
HALF, MASS, MU, BOX, _rot)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class CartSkills(PushSkills):
|
| 19 |
+
def __init__(self,*args,**kwargs):
|
| 20 |
+
super().__init__(*args,**kwargs)
|
| 21 |
+
self.robot_commands=0
|
| 22 |
+
def move_to(self,*args,**kwargs):
|
| 23 |
+
self.robot_commands+=1
|
| 24 |
+
return super().move_to(*args,**kwargs)
|
| 25 |
+
def set_gripper(self,*args,**kwargs):
|
| 26 |
+
self.robot_commands+=1
|
| 27 |
+
return super().set_gripper(*args,**kwargs)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@register_task
|
| 31 |
+
class PartsCart(UnderTableTool):
|
| 32 |
+
name = 'lh_parts_cart'
|
| 33 |
+
level = 'L4'
|
| 34 |
+
category = 'geometry_inference'
|
| 35 |
+
failure_causes = ('L4', 'L2', 'L5')
|
| 36 |
+
capabilities = ('Perceive', 'Reason', 'Plan', 'Restore')
|
| 37 |
+
protocol = 'cross'
|
| 38 |
+
agent_max_steps = 180
|
| 39 |
+
instruction = ('Use the wooden tool to retrieve the red part from under the low glass table. '
|
| 40 |
+
'Load the red and blue parts on the two marks on the brown transport platform, '
|
| 41 |
+
'then push the loaded platform with the closed gripper completely into the green parking area. '
|
| 42 |
+
'At the end both parts must still be on their marks, and the gripper must be open and clear.')
|
| 43 |
+
instruction_indirect = instruction
|
| 44 |
+
|
| 45 |
+
def make_bddl(self):
|
| 46 |
+
cube = register_generated('LffPartsCartRed', box_xml('lff_parts_cart_red', (CUBE_HALF,)*3,(.85,.12,.12,1), density=300))
|
| 47 |
+
blue = register_generated('LffPartsCartBlue', box_xml('lff_parts_cart_blue', (CUBE_HALF,)*3,(.1,.2,.85,1), density=300))
|
| 48 |
+
stick_xml_text=stick_xml('lff_parts_cart_stick').replace('size="0.00800 0.02500 0.01000"','size="0.00800 0.00800 0.01000"')
|
| 49 |
+
stick = register_generated('LffPartsCartStick', stick_xml_text)
|
| 50 |
+
table_xml=low_table_xml('lff_parts_cart_table')
|
| 51 |
+
# Wider roof with legs outside the blocked cube's x-exit lane. This prevents a panel failure
|
| 52 |
+
# trapping the cube against a corner leg, which the existing standalone task did not test in-attempt.
|
| 53 |
+
table_xml=table_xml.replace('size="0.06000 0.06000 0.00500"','size="0.06000 0.07500 0.00500"')
|
| 54 |
+
for sx in (-.052,.052):
|
| 55 |
+
for sy in (-.052,.052):
|
| 56 |
+
table_xml=table_xml.replace(f'pos="{sx:.5f} {sy:.5f} 0.03500"',f'pos="{sx:.5f} {np.sign(sy)*.067:.5f} 0.03500"')
|
| 57 |
+
table = register_generated('LffPartsCartTable', table_xml, free=False)
|
| 58 |
+
xml=long_box_xml('lff_parts_cart_platform')
|
| 59 |
+
marks=''.join(f'<geom type="box" pos="0 {y} {HALF[2]+.0006}" size=".022 .022 .0003" rgba="{color}" contype="0" conaffinity="0" group="1" />' for y,color in [(-.03,'.9 .4 .4 1'),(.03,'.4 .5 .9 1')])
|
| 60 |
+
xml=xml.replace(' </body>',marks+' </body>',1)
|
| 61 |
+
cart = register_generated('LffPartsCartPlatform', xml)
|
| 62 |
+
zone = register_generated('LffPartsCartZone', rect_frame_xml('lff_parts_cart_zone'), free=False)
|
| 63 |
+
# Inertial/shape match existing off-centre box, with purely visual cargo marks.
|
| 64 |
+
objs=[('cube_1',cube,'red_region',(-.31,-.26,-.29,-.24)),
|
| 65 |
+
('blue_1',blue,'blue_region',(-.31,.24,-.29,.26)),
|
| 66 |
+
('stick_1',stick,'stick_region',(-.01,-.36,.01,-.34)),
|
| 67 |
+
('box_1',cart,'cart_region',(.19,.24,.21,.26))]
|
| 68 |
+
fx=[('lowtable_1',table,'table_region',(.19,-.11,.21,-.09)),
|
| 69 |
+
('zone_1',zone,'zone_region',(.19,.39,.21,.41))]
|
| 70 |
+
return write_bddl(self.name,self.instruction,objs,fx)
|
| 71 |
+
|
| 72 |
+
def sample_instance(self, seed):
|
| 73 |
+
# Tool geometry is inherited; put transport in the other half of the same tabletop.
|
| 74 |
+
rng=np.random.default_rng(seed)
|
| 75 |
+
base=super().sample_instance(seed)
|
| 76 |
+
base.update(side=-1, pane_side=1, table_xy=[-.08,-.08],cube_xy=[-.08,-.08],
|
| 77 |
+
stick_xy=[-.08,-.34],stick_yaw=np.pi/2,
|
| 78 |
+
box_xy=[-.25,.24],target_dist=.16,
|
| 79 |
+
com_offset=float(rng.choice([-1,1])*rng.uniform(.05,.065)),
|
| 80 |
+
traps=dict(L4=True,L2=True,L5=True))
|
| 81 |
+
base['bin_xy']=[-.25,.24] # inherited observe() only; no bin fixture.
|
| 82 |
+
return base
|
| 83 |
+
|
| 84 |
+
def target_xy(self, inst):
|
| 85 |
+
return np.array([inst['box_xy'][0]+inst['target_dist'],inst['box_xy'][1]])
|
| 86 |
+
|
| 87 |
+
def apply_instance(self, inst):
|
| 88 |
+
self.inst=inst
|
| 89 |
+
m=self.env.sim.model
|
| 90 |
+
bid,_=self._fixture('lowtable_1')
|
| 91 |
+
m.body_pos[bid]=[*inst['table_xy'],envs.TABLE_Z]
|
| 92 |
+
for g,sy in self._panes():
|
| 93 |
+
on=inst['traps']['L4'] and sy==inst['pane_side']
|
| 94 |
+
m.geom_contype[g]=m.geom_conaffinity[g]=int(on)
|
| 95 |
+
envs.set_obj_pose(self.env,'cube_1',[*inst['cube_xy'],envs.TABLE_Z+CUBE_HALF+.0005])
|
| 96 |
+
envs.set_obj_pose(self.env,'blue_1',[-.30,.04,envs.TABLE_Z+CUBE_HALF+.0005])
|
| 97 |
+
envs.set_obj_pose(self.env,'stick_1',[*inst['stick_xy'],envs.TABLE_Z+HANDLE_HALF[2]+.0005],yaw=inst['stick_yaw'])
|
| 98 |
+
bid=envs.body_id(self.env,BOX)
|
| 99 |
+
m.body_mass[bid]=MASS
|
| 100 |
+
m.body_ipos[bid]=[0,inst['com_offset'] if inst['traps']['L5'] else 0,0]
|
| 101 |
+
for g in range(m.ngeom):
|
| 102 |
+
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])):
|
| 103 |
+
m.geom_pos[g,1]=np.sign(m.geom_pos[g,1])*(.03 if inst['traps']['L2'] else .07)
|
| 104 |
+
envs.refit_bounds(self.env,bid)
|
| 105 |
+
envs.set_friction(self.env,BOX,MU)
|
| 106 |
+
envs.set_obj_pose(self.env,BOX,[*inst['box_xy'],envs.TABLE_Z+HALF[2]+.001])
|
| 107 |
+
zb=m.body_name2id(self.env.fixtures_dict['zone_1'].root_body)
|
| 108 |
+
m.body_pos[zb]=[*self.target_xy(inst),envs.TABLE_Z+.0002]
|
| 109 |
+
|
| 110 |
+
def reset_instance(self, inst, recorder=None):
|
| 111 |
+
self.loadmon=None
|
| 112 |
+
self._mon=None
|
| 113 |
+
self.env.reset();self.apply_instance(inst);self.env.sim.forward();envs.settle(self.env,15)
|
| 114 |
+
self.sk=CartSkills(self.env,recorder=recorder,target=self.target_xy(inst))
|
| 115 |
+
self._start_monitor()
|
| 116 |
+
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])
|
| 117 |
+
self.ncmd=0;self.budget=None
|
| 118 |
+
return self.sk
|
| 119 |
+
|
| 120 |
+
def mark(self,i):
|
| 121 |
+
p,yaw=self.sk._box_pose() if self.sk else (envs.obj_pos(self.env,BOX),0.)
|
| 122 |
+
spacing=.03 if self.inst['traps']['L2'] else .07
|
| 123 |
+
return p[:2]+_rot(yaw)@np.array([0.,(-spacing,spacing)[i]])
|
| 124 |
+
|
| 125 |
+
def cargo_ok(self,i):
|
| 126 |
+
obj=('cube_1','blue_1')[i]
|
| 127 |
+
p=envs.obj_pos(self.env,obj); bp=envs.obj_pos(self.env,BOX)
|
| 128 |
+
return bool(np.linalg.norm(p[:2]-self.mark(i))<.018 and
|
| 129 |
+
abs(p[2]-(bp[2]+HALF[2]+CUBE_HALF))<.012 and not self.sk.holding(obj))
|
| 130 |
+
|
| 131 |
+
def _monitor_step(self):
|
| 132 |
+
super()._monitor_step()
|
| 133 |
+
mon=getattr(self,'loadmon',None)
|
| 134 |
+
if mon is None:return
|
| 135 |
+
robot=set(envs.robot_geom_ids(self.env))
|
| 136 |
+
for i,obj in enumerate(('cube_1','blue_1')):
|
| 137 |
+
geoms=set(envs.obj_geom_ids(self.env,obj))
|
| 138 |
+
for c in self.env.sim.data.contact[:self.env.sim.data.ncon]:
|
| 139 |
+
if (c.geom1 in robot and c.geom2 in geoms) or (c.geom2 in robot and c.geom1 in geoms):
|
| 140 |
+
mon['last_robot_touch'][i]=self.sk.n_steps
|
| 141 |
+
now=self.cargo_ok(i)
|
| 142 |
+
if now==mon['states'][i]:mon['count'][i]=0;continue
|
| 143 |
+
mon['count'][i]+=1
|
| 144 |
+
if mon['count'][i]<5:continue
|
| 145 |
+
mon['count'][i]=0;mon['states'][i]=now
|
| 146 |
+
ev='restored' if now and mon['lost'][i] else 'achieved' if now else 'lost'
|
| 147 |
+
if now:mon['ever'][i]=True
|
| 148 |
+
else:
|
| 149 |
+
mon['lost'][i]=True
|
| 150 |
+
if np.linalg.norm(envs.obj_pos(self.env,BOX)[:2]-self.inst['box_xy'])<.025:
|
| 151 |
+
mon['loaded']=False
|
| 152 |
+
mon['load_step']=None
|
| 153 |
+
mon['events'].append(dict(step=self.sk.n_steps,pred=('red','blue')[i],event=ev,
|
| 154 |
+
cart_displacement=float(np.linalg.norm(envs.obj_pos(self.env,BOX)[:2]-self.inst['box_xy'])),
|
| 155 |
+
cause='robot' if self.sk.n_steps-mon['last_robot_touch'][i]<=20 else 'other'))
|
| 156 |
+
displacement=np.linalg.norm(envs.obj_pos(self.env,BOX)[:2]-self.inst['box_xy'])
|
| 157 |
+
if all(mon['states']) and displacement<.02 and not mon['loaded']:
|
| 158 |
+
mon['loaded']=True
|
| 159 |
+
mon['load_step']=self.sk.n_steps
|
| 160 |
+
if displacement>.03 and mon['departure_step'] is None:
|
| 161 |
+
mon['departure_step']=self.sk.n_steps
|
| 162 |
+
if not mon['loaded']:mon['departed_unloaded']=True
|
| 163 |
+
|
| 164 |
+
def pick_place(self,obj,xy,yaw=0.):
|
| 165 |
+
sk=self.sk;p=envs.obj_pos(self.env,obj)
|
| 166 |
+
sk.set_gripper(False,steps=10)
|
| 167 |
+
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)
|
| 168 |
+
sk.move_to([p[0],p[1],p[2]-.004],speed=.10,tol=.002)
|
| 169 |
+
sk.set_gripper(True,steps=15)
|
| 170 |
+
held=sk.holding(obj)
|
| 171 |
+
sk.move_to([p[0],p[1],envs.TABLE_Z+.20],speed=.15)
|
| 172 |
+
if held:
|
| 173 |
+
sk.move_to([xy[0],xy[1],envs.TABLE_Z+.20],yaw=yaw)
|
| 174 |
+
bp=envs.obj_pos(self.env,BOX)
|
| 175 |
+
sk.move_to([xy[0],xy[1],bp[2]+HALF[2]+CUBE_HALF-.003],speed=.06,tol=.002)
|
| 176 |
+
sk.set_gripper(False,steps=15)
|
| 177 |
+
sk.move_to([xy[0],xy[1],envs.TABLE_Z+.22],speed=.15)
|
| 178 |
+
return bool(held)
|
| 179 |
+
|
| 180 |
+
def load(self, careful=True):
|
| 181 |
+
self.pick_place('cube_1',self.mark(0),np.pi/2)
|
| 182 |
+
# Open fingers along y at the adjacent mark can knock the already loaded red cube.
|
| 183 |
+
yaw=np.pi/2 if careful else 0.
|
| 184 |
+
self.pick_place('blue_1',self.mark(1),yaw)
|
| 185 |
+
|
| 186 |
+
def repair_load(self):
|
| 187 |
+
for _ in range(3):
|
| 188 |
+
for i,o in enumerate(('cube_1','blue_1')):
|
| 189 |
+
if not self.cargo_ok(i):self.pick_place(o,self.mark(i),np.pi/2)
|
| 190 |
+
|
| 191 |
+
def transport(self,c=0.,repair=False):
|
| 192 |
+
# Call existing push controller on this same environment; no independent rollout stitching.
|
| 193 |
+
if not repair:
|
| 194 |
+
return OffcenterPush.execute(self,self.inst,dict(c=c))
|
| 195 |
+
if repair:
|
| 196 |
+
# Original feedback-driven corrector calls self.execute for its initial push.
|
| 197 |
+
self._transport_only=True
|
| 198 |
+
try:OffcenterPush.adaptive_attempt(self,self.inst,c)
|
| 199 |
+
finally:self._transport_only=False
|
| 200 |
+
|
| 201 |
+
_cmd=OffcenterPush._cmd
|
| 202 |
+
_sim_used=OffcenterPush._sim_used
|
| 203 |
+
_push_at=OffcenterPush._push_at
|
| 204 |
+
bracket=OffcenterPush.bracket
|
| 205 |
+
_front_runup=staticmethod(OffcenterPush._front_runup)
|
| 206 |
+
STEP=OffcenterPush.STEP;YAW_OK=OffcenterPush.YAW_OK
|
| 207 |
+
GAIN0=OffcenterPush.GAIN0;SAFE_V=OffcenterPush.SAFE_V
|
| 208 |
+
|
| 209 |
+
def execute(self,inst,params):
|
| 210 |
+
if getattr(self,'_transport_only',False):return OffcenterPush.execute(self,inst,params)
|
| 211 |
+
if params.get('front',False):self.tool_push_front()
|
| 212 |
+
else:self.tool_push_out()
|
| 213 |
+
if self.under_table():return
|
| 214 |
+
self.load(params.get('careful',False))
|
| 215 |
+
if params.get('repair',False):self.repair_load()
|
| 216 |
+
if all(self.cargo_ok(i) for i in range(2)):
|
| 217 |
+
self.transport(params.get('c',0.),params.get('repair',False))
|
| 218 |
+
if params.get('repair',False):self.repair_load()
|
| 219 |
+
self.sk.set_gripper(False,steps=10)
|
| 220 |
+
p=self.sk.eef_pos();self.sk.move_to([p[0],p[1],envs.TABLE_Z+.24])
|
| 221 |
+
|
| 222 |
+
def default_params(self,inst):return dict(front=False,careful=False,repair=False,c=0.)
|
| 223 |
+
def oracle_params(self,inst):return dict(front=True,careful=True,repair=True,c=inst['com_offset'] if inst['traps']['L5'] else 0.)
|
| 224 |
+
def adapt_params(self,inst,history):
|
| 225 |
+
# The L4 side hit is learned from actual prior outcome, not from inst['pane_side'].
|
| 226 |
+
seen_geometry=any(h['outcome']['traps']['L4'] for h in history)
|
| 227 |
+
seen_loading=any(h['outcome']['traps']['L2'] for h in history)
|
| 228 |
+
pushes=[m for h in history for m in h['outcome']['box_moves']]
|
| 229 |
+
return dict(front=seen_geometry,careful=seen_loading,repair=bool(history),c=self.bracket(pushes))
|
| 230 |
+
|
| 231 |
+
def outcome(self,inst):
|
| 232 |
+
self.sk.hold(30)
|
| 233 |
+
fit=self.sk.fit();cargo=[self.cargo_ok(i) for i in range(2)]
|
| 234 |
+
ev=list(self.loadmon['events'])
|
| 235 |
+
# Loading regressions count only while cart remains at the loading station.
|
| 236 |
+
load_lost=[e for e in ev if e['event']=='lost' and e['cart_displacement']<.025 and e['cause']=='robot']
|
| 237 |
+
loaded=self.loadmon['loaded']
|
| 238 |
+
static=bool(np.max(np.abs(self.env.sim.data.qvel))<.05)
|
| 239 |
+
robot=set(envs.robot_geom_ids(self.env)); items=set()
|
| 240 |
+
for o in ('cube_1','blue_1',BOX,'stick_1'):items.update(envs.obj_geom_ids(self.env,o))
|
| 241 |
+
touching=any((c.geom1 in robot and c.geom2 in items) or (c.geom2 in robot and c.geom1 in items)
|
| 242 |
+
for c in self.env.sim.data.contact[:self.env.sim.data.ncon])
|
| 243 |
+
budget_ok=bool(self.sk.robot_commands<=self.agent_max_steps and self.sk.n_steps*.05<=self.agent_max_steps*3)
|
| 244 |
+
success=bool(not self.under_table() and all(cargo) and fit['inside'] and loaded
|
| 245 |
+
and not self.loadmon['departed_unloaded'] and static and not touching and budget_ok and self.sk.grip<0
|
| 246 |
+
and self._mon['stick_touched_cube'])
|
| 247 |
+
moves=copy.deepcopy(self.sk.box_moves)
|
| 248 |
+
return dict(success=success,stages=dict(retrieved=not self.under_table(),red=cargo[0],blue=cargo[1],parked=fit['inside'],loaded=loaded),
|
| 249 |
+
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'],
|
| 250 |
+
events=ev,n_regressions=len(load_lost),n_restored=sum(e['event']=='restored' for e in ev),
|
| 251 |
+
traps=dict(L4=bool(self._mon['cube_hit_pane']),L2=bool(load_lost),L5=any(m['bad'] for m in moves)),
|
| 252 |
+
box_moves=moves,cart_pose=[*envs.obj_pos(self.env,BOX).tolist()],cart_fit=fit,
|
| 253 |
+
detail=f'Retrieved={not self.under_table()}; cargo on marks={cargo}; platform parked={fit["inside"]}.')
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/lh_tidy_stack.py
ADDED
|
@@ -0,0 +1,1260 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LH lh_tidy_stack v2 (2026-10-16): tidy the table -- stack the four storage boxes (red, green, blue, yellow; alike,
|
| 2 |
+
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
|
| 3 |
+
(random colour) is an empty, soft carton: it carries one thing, but as soon as a second thing comes to rest above it,
|
| 4 |
+
it gives way -- standing it folds sideways, lying on a side face it is crushed flat -- and everything above it slides
|
| 5 |
+
off the pile: the stage that made the pile two higher destroys the stage before it.
|
| 6 |
+
|
| 7 |
+
Family: long-horizon self-disturbance ("state_restoration"): the later stages' ordinary action (putting the next box on)
|
| 8 |
+
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
|
| 9 |
+
an attempt) or remember its colour (across attempts). The cheapest explanation of a toppled pile ("I did not centre the
|
| 10 |
+
box", "I let go too high") is wrong: perfectly centred boxes let go 5 mm above the pile topple it just the same
|
| 11 |
+
(control naive_centred).
|
| 12 |
+
|
| 13 |
+
v1 -> v2 (Sonnet 5.5 pilot np3_lh_tidy_stack, seeds 3000 / 3002 / 3003, k=3; logs measured by the coordinator and
|
| 14 |
+
replayed here): in s3002 attempt 2 boxes that had fallen on their sides were restacked lying (a lying box looks the
|
| 15 |
+
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
|
| 16 |
+
measured the load along the box axis only, saw -0.06 N and never fired -> judged a success. Sonnet also presses what it
|
| 17 |
+
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
|
| 18 |
+
in s3003 a cup pressed onto the soft box on top -- where it belongs -- crushed it under one item (v1: 2.45 N). v2:
|
| 19 |
+
(1) the load is measured along the world vertical, whichever face the carton rests on (`vertical_loads`: the downward
|
| 20 |
+
push on its upper side, limited by the support under it);
|
| 21 |
+
(2) a carton lying on a side face (seam vertical) cannot fold under gravity, so it is crushed instead: both halves
|
| 22 |
+
flatten towards the face they rest on, the upper half by 70 % and the lower by 30 % (runtime geom sizes +
|
| 23 |
+
envs.refit_bounds), the top becomes a 2-3 cm step and what is on it tips off;
|
| 24 |
+
(3) only what rests on the carton counts, at most with its own weight (+0.3 N for impacts): something the robot still
|
| 25 |
+
holds, the robot pushing down through an item it has just let go of, and the fingers pressing the held carton
|
| 26 |
+
itself onto something do not count; the robot's own fingers / hand pushing on its top do (a hard press may crush
|
| 27 |
+
it: the closed gripper 3 mm onto its top does; logged as cause "press", not counted as the trap unless it costs a
|
| 28 |
+
stage);
|
| 29 |
+
(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;
|
| 30 |
+
(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
|
| 31 |
+
every box ~4 deg and the pile leaned 10 deg in the replay); after a fold the carton straightens along a rest
|
| 32 |
+
shape that moves back to straight over 1.5 s (released at once, a stiff spring flipped it onto its side);
|
| 33 |
+
(6) stacking tolerance 3 cm instead of 2.5 (a correctly stacked oracle_noise pile failed at 2.51 cm).
|
| 34 |
+
v1 code and results: scratchpad lh_tidy_stack_v1.py, results/_old/lh_tidy_stack_v1/.
|
| 35 |
+
|
| 36 |
+
Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
|
| 37 |
+
* a grey mat (13 x 13 cm, visual only), centre x in [-0.11, -0.05], |y| <= 5 cm;
|
| 38 |
+
* four storage boxes (6 x 6 x 5 cm, bright red / green / blue / yellow with a darker lid line, 200 g; friction 0.5)
|
| 39 |
+
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,
|
| 40 |
+
yaw +-17 deg, colours shuffled;
|
| 41 |
+
* a dark teal cup (5 cm wide, 7 cm tall, 200 g) on the robot's side of the mat, 23-26 cm away.
|
| 42 |
+
|
| 43 |
+
Hidden variable: which box is the soft carton (60 g; mass is not observable). Instances come in balanced blocks of 20
|
| 44 |
+
consecutive seeds ((seed x 7) mod 20 = k): k >= 18 benign (no soft box); otherwise the soft box is the one at rank
|
| 45 |
+
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.
|
| 46 |
+
A nearest-first stacker therefore meets it below the top in 14 of 20 instances.
|
| 47 |
+
|
| 48 |
+
Mechanism (physics; nothing is teleported). Every box is built alike: a lower half (the root body) and an upper half
|
| 49 |
+
joined by a ball joint at mid-height (the seam is invisible). In the three rigid boxes the joint is locked (range
|
| 50 |
+
0.003 rad, stiffness 3 Nm/rad). The soft carton follows a load law (`_law_step`, every MuJoCo substep): its compressive
|
| 51 |
+
load (above, low-passed with 0.4 s) is compared with f_crit (instance key "f_crit": the fragility knob). Below it the
|
| 52 |
+
joint keeps 3 Nm/rad (one box 1.3 cm off-centre tilts it < 1 deg: looks like the rigid boxes). Above it:
|
| 53 |
+
* standing or upside down (seam horizontal): the joint stiffness drops to 0.03 Nm/rad -- a column with m g h ~ 0.27
|
| 54 |
+
Nm/rad on it is unstable, centred or not -- and its rest shape bends 12 deg towards a per-instance side: the upper
|
| 55 |
+
half folds sideways (38-54 deg measured, joint limit 54 deg) and what is on it slides off;
|
| 56 |
+
* lying on a side face (seam vertical): crushed as above within ~0.1 s.
|
| 57 |
+
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
|
| 58 |
+
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
|
| 59 |
+
the pile survives only with the soft box on top (carrying just the cup): soft at level 1 -> it gives way when box 3
|
| 60 |
+
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,
|
| 61 |
+
the cup ends on its side, which a top-down gripper cannot undo, so that attempt cannot be repaired). Measured (v2, naive
|
| 62 |
+
without rebuilding, the 14 trap instances of seeds 1000-1019): standing 14/14 folded at exactly that stage, the soft
|
| 63 |
+
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
|
| 64 |
+
soft box starts on a side face and is stacked lying) crushed at exactly that stage in every trap instance.
|
| 65 |
+
|
| 66 |
+
Why not the linear spring of the brief (a ball joint with one fixed stiffness k): the load that k must carry (the cup)
|
| 67 |
+
and the load that must topple it (one more box) differ by a factor of ~2-3, and an inverted pendulum close to its
|
| 68 |
+
critical load amplifies placement offsets (tilt = W e / (k - m g h)); measured (results/lh_tidy_stack/linear.json,
|
| 69 |
+
instance key law="linear"): no k gives both a soft box that carries the cup on top without sagging and a pile that
|
| 70 |
+
topples however carefully it is centred (k <= 0.25 Nm/rad: the correct pile fails 5-10/10; k = 0.5: a centred
|
| 71 |
+
level-3 soft box carries box + cup, 2/2). A load threshold (walls that
|
| 72 |
+
hold until they buckle) keeps the soft box looking and behaving rigid until the second item, independent of centring.
|
| 73 |
+
|
| 74 |
+
Success predicate (from the instruction): all four boxes in one chain -- the bottom one on the mat (lowest point <= 8 mm
|
| 75 |
+
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
|
| 76 |
+
resting on the previous (its lowest point within 1 cm of the top of the box below, centres within 3 cm), every box
|
| 77 |
+
flat (some face within 10 deg of horizontal: a fallen box cannot be stood up again by a vertical gripper, so a box on
|
| 78 |
+
its side counts), not bent (kink <= 10 deg) and not crushed (<= 15 %) --; the cup upright (<= 10 deg) on the top box
|
| 79 |
+
(bottom within 1 cm, centre within 3 cm); nothing held, the gripper not touching anything, the scene static (< 3 mm
|
| 80 |
+
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
|
| 81 |
+
(physically resting on it; the static check rejects anything that does not stay). Sonnet's measured placement error is
|
| 82 |
+
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
|
| 83 |
+
correctly stacked oracle_noise pile, seed 1008, at 2.51 cm).
|
| 84 |
+
|
| 85 |
+
Event monitor (server log only; F1 gives the agent only success / failure): stage predicates red / green / blue /
|
| 86 |
+
yellow (box in the pile) and cup (cup on a complete pile), debounced over 0.5 s: achieved / lost (cause buckle / robot
|
| 87 |
+
/ picked_up / other) / restored; `buckle` (= trap fired: load, the robot's share of it, fold or crush, lying, level,
|
| 88 |
+
items on it), `collapse` (a buckle that cost a stage). Outcome: success, failure (none / held / touching / collapsed /
|
| 89 |
+
regressed / not_stacked / cup_fallen / cup_not_on_top / not_static), trap_fired, recovered_in_attempt, n_buckles,
|
| 90 |
+
n_collapses, buckle_how, max_kink_deg, max_crush, detail (F2). The law's state rides along in task.mon["law"]; a
|
| 91 |
+
crushed carton's geom sizes are restored at every reset.
|
| 92 |
+
|
| 93 |
+
Protocol: cross (reset to the same instance before every attempt), k = 3.
|
| 94 |
+
"""
|
| 95 |
+
import mujoco
|
| 96 |
+
import numpy as np
|
| 97 |
+
|
| 98 |
+
from .. import envs
|
| 99 |
+
from ..bddl import write_bddl
|
| 100 |
+
from ..objects import _fmt, _wrap, register_generated
|
| 101 |
+
from ..skills import Skills
|
| 102 |
+
from ..task_base import LFFTask, register_task
|
| 103 |
+
|
| 104 |
+
TZ = envs.TABLE_Z
|
| 105 |
+
G = 9.81
|
| 106 |
+
COLOURS = ["red", "green", "blue", "yellow"]
|
| 107 |
+
BOXES = [f"box_{c}_1" for c in COLOURS]
|
| 108 |
+
COL = dict(zip(BOXES, COLOURS))
|
| 109 |
+
CUP, MAT = "cup_1", "mat_1"
|
| 110 |
+
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),
|
| 111 |
+
"yellow": (0.90, 0.74, 0.14, 1.0)}
|
| 112 |
+
CUP_RGBA = (0.10, 0.45, 0.50, 1.0) # dark teal ceramic, darker inside
|
| 113 |
+
CUP_INSIDE = (0.20, 0.20, 0.19, 1.0)
|
| 114 |
+
MAT_RGBA = (0.45, 0.45, 0.47, 1.0)
|
| 115 |
+
|
| 116 |
+
# ---------------------------------------------------------------- boxes (all four built alike: base + upper part)
|
| 117 |
+
HX, HY, H = 0.030, 0.030, 0.050 # 6 x 6 x 5 cm (the gripper opens 7.9 cm)
|
| 118 |
+
HB = 0.025 # base part height = height of the seam (ball joint) above the bottom: mid-height, so the upper
|
| 119 |
+
# half can fold ~56 deg before its edge reaches the surface below
|
| 120 |
+
HU = H - HB
|
| 121 |
+
BOX_MASS = 0.20 # a filled storage box (v1: 0.18)
|
| 122 |
+
SOFT_MASS = 0.06 # the empty carton (mass is not observable by the agent)
|
| 123 |
+
BOX_MU = 0.5
|
| 124 |
+
CONTACT = 'solimp="0.95 0.99 0.001" solref="0.01 1"'
|
| 125 |
+
# soft-carton law (see SoftLaw): stiff until the compressive load through its walls exceeds F_CRIT, then soft
|
| 126 |
+
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
|
| 127 |
+
# bends it ~4 deg)
|
| 128 |
+
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
|
| 129 |
+
# box 4 deg and the pile leaned 10 deg -- replay of pilot s3003 on v2; at 20 for the soft carton too
|
| 130 |
+
# its folds flipped it onto its side 4/14 times)
|
| 131 |
+
K_LO = 0.03 # Nm/rad: buckled (one box on it destabilises it: m g h ~ 0.12 Nm/rad)
|
| 132 |
+
DAMP = 0.01
|
| 133 |
+
F_CRIT = 3.45 # N, vertical load from above (resting things + whatever the robot pushes or holds onto it): one
|
| 134 |
+
# item weighs 1.96 N and a held item pressed onto the carton adds <= ~0.9 N before it slips in the
|
| 135 |
+
# fingers (measured, t10_press); two items weigh 3.92 N (v1: 2.45 N with 1.77 / 1.57 N items)
|
| 136 |
+
F_REL = 0.5 # N: unloaded below this ...
|
| 137 |
+
REL_T = 0.3 # ... for this long -> it springs back
|
| 138 |
+
TAU_F = 0.4 # s: low-pass of the load (impacts of a box let go 1-4 cm above do not count)
|
| 139 |
+
K_RISE = 1.5 # s: the folded carton straightens along a reference that moves back to straight in this time
|
| 140 |
+
BEND_REF = np.radians(12.0) # reference bend of the buckled carton (the weak side; direction per instance)
|
| 141 |
+
RANGE_SOFT, RANGE_RIGID = 0.95, 0.003 # rad: kink limit (54 deg) of the soft carton; the rigid boxes are locked
|
| 142 |
+
# v2: a carton lying on a side face (its seam vertical) cannot fold under gravity; it is crushed instead: both halves
|
| 143 |
+
# flatten towards the surface below, the upper half much more, so the top becomes a 2-3 cm step and what is on it
|
| 144 |
+
# tips off (geom sizes changed at runtime + envs.refit_bounds)
|
| 145 |
+
CRUSH_ALPHA = (0.30, 0.70) # fraction of the height lost by the base half / the upper half when fully crushed
|
| 146 |
+
CRUSH_TAU = (0.08, 0.7) # s: crushing / recovering
|
| 147 |
+
FOLD_MIN_UP = 0.7 # |seam normal . vertical| above this: the fold (upright or upside down); below: the crush
|
| 148 |
+
|
| 149 |
+
# ---------------------------------------------------------------- cup
|
| 150 |
+
CUP_R, CUP_H, CUP_MASS = 0.025, 0.070, 0.20 # v1: 0.16
|
| 151 |
+
|
| 152 |
+
# ---------------------------------------------------------------- mat and layout
|
| 153 |
+
MAT_HALF = 0.065 # 13 x 13 cm
|
| 154 |
+
MAT_X, MAT_Y = (-0.11, -0.05), (-0.05, 0.05)
|
| 155 |
+
BOX_D = (0.15, 0.185, 0.22, 0.255) # distances of the four boxes from the mat centre (+- jitter)
|
| 156 |
+
BOX_X = (-0.33, 0.07) # world x range of the box positions (reach)
|
| 157 |
+
BOX_YMAX = 0.30
|
| 158 |
+
BOX_YAW = 0.30
|
| 159 |
+
P_BENIGN = 0.10 # 2 of every 20 consecutive seeds: no soft box
|
| 160 |
+
|
| 161 |
+
# ---------------------------------------------------------------- predicates
|
| 162 |
+
TILT_OK = np.radians(10.0)
|
| 163 |
+
KINK_OK = np.radians(10.0)
|
| 164 |
+
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
|
| 165 |
+
STACK_XY = 0.030 # centre of a box within 3 cm (= the half width) of the centre of the box below: its centre of
|
| 166 |
+
# mass is over the lower box's top face (v2; 2.5 cm judged a resting box 2.51 cm off as not stacked)
|
| 167 |
+
STACK_Z = 0.010
|
| 168 |
+
CUP_XY = 0.030
|
| 169 |
+
DEBOUNCE = 10 # control steps (0.5 s)
|
| 170 |
+
|
| 171 |
+
# ---------------------------------------------------------------- scripted motion
|
| 172 |
+
Z_CARRY = 0.18
|
| 173 |
+
NAIVE_ERR = (0.004, 0.013) # Sonnet's placement error 0.4-1.3 cm (random direction)
|
| 174 |
+
NAIVE_GAP = (0.010, 0.040) # Sonnet lets go 1-4 cm above the surface
|
| 175 |
+
NAIVE_BIAS = (0.0, 0.020) # forward bias of the first box on the mat (oblique camera)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def box_xml(name, rgba):
|
| 179 |
+
"""storage box: base part (root body, 1.6 cm) + upper part (child body) on a ball joint at the seam. Rigid boxes
|
| 180 |
+
get a ~0 kink range at reset; the soft carton a 31.5 deg range and the load-dependent stiffness of SoftLaw.
|
| 181 |
+
Inertials are replaced per instance (mass)."""
|
| 182 |
+
mb, mu = BOX_MASS * HB / H, BOX_MASS * HU / H
|
| 183 |
+
zb = -H / 2 + HB / 2
|
| 184 |
+
dark = [0.72 * c for c in rgba[:3]] + [1.0]
|
| 185 |
+
g = [f' <inertial pos="0 0 {zb:.5f}" mass="{mb:.5f}" diaginertia="1e-5 1e-5 1e-5" />',
|
| 186 |
+
f' <geom name="{name}_base" type="box" size="{HX:.5f} {HY:.5f} {HB / 2:.5f}" pos="0 0 {zb:.5f}" '
|
| 187 |
+
f'rgba="{_fmt(rgba)}" friction="{BOX_MU} 0.005 0.0001" {CONTACT} group="0" />',
|
| 188 |
+
f' <geom type="box" size="{HX:.5f} {HY:.5f} {HB / 2:.5f}" pos="0 0 {zb:.5f}" rgba="{_fmt(rgba)}" '
|
| 189 |
+
f'contype="0" conaffinity="0" group="1" />',
|
| 190 |
+
f' <body name="{name}_upper" pos="0 0 {-H / 2 + HB:.5f}">',
|
| 191 |
+
f' <joint name="{name}_kink" type="ball" pos="0 0 0" range="0 {RANGE_SOFT}" stiffness="{K_HI}" '
|
| 192 |
+
f'damping="{DAMP}" armature="0.0001" />',
|
| 193 |
+
f' <inertial pos="0 0 {HU / 2:.5f}" mass="{mu:.5f}" diaginertia="1e-5 1e-5 1e-5" />',
|
| 194 |
+
f' <geom name="{name}_upper" type="box" size="{HX:.5f} {HY:.5f} {HU / 2:.5f}" pos="0 0 {HU / 2:.5f}" '
|
| 195 |
+
f'rgba="{_fmt(rgba)}" friction="{BOX_MU} 0.005 0.0001" {CONTACT} group="0" />',
|
| 196 |
+
f' <geom type="box" size="{HX:.5f} {HY:.5f} {HU / 2:.5f}" pos="0 0 {HU / 2:.5f}" rgba="{_fmt(rgba)}" '
|
| 197 |
+
f'contype="0" conaffinity="0" group="1" />',
|
| 198 |
+
# lid line (visual only): a darker band 8 mm below the top, on all four boxes
|
| 199 |
+
f' <geom type="box" size="{HX + 0.0006:.5f} {HY + 0.0006:.5f} 0.0012" pos="0 0 {HU - 0.008:.5f}" '
|
| 200 |
+
f'rgba="{_fmt(dark)}" contype="0" conaffinity="0" group="1" />',
|
| 201 |
+
' </body>']
|
| 202 |
+
return _wrap(name, "\n".join(g), H / 2, float(np.hypot(HX, HY)))
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def cup_xml(name):
|
| 206 |
+
"""open cup, 5 cm wide, 7 cm tall: 12 wall boxes + an octagonal base of two boxes (box contacts; a light MuJoCo
|
| 207 |
+
cylinder creeps on a flat surface, lh_nudge_row). Visual: a smooth cylinder with a dark inside."""
|
| 208 |
+
r, h = CUP_R, CUP_H
|
| 209 |
+
nseg, wt, bt = 12, 0.004, 0.006
|
| 210 |
+
g = [f' <inertial pos="0 0 {-h / 2 + 0.022:.4f}" mass="{CUP_MASS}" diaginertia="1.5e-4 1.5e-4 1.0e-4" />']
|
| 211 |
+
s = r * np.sin(np.pi / nseg) + 0.0008
|
| 212 |
+
rc = r * np.cos(np.pi / nseg) - wt / 2
|
| 213 |
+
for k in range(nseg):
|
| 214 |
+
a = 2 * np.pi * k / nseg
|
| 215 |
+
q = [np.cos(a / 2), 0, 0, np.sin(a / 2)]
|
| 216 |
+
g.append(f' <geom name="{name}_w{k}" type="box" size="{wt / 2:.5f} {s:.5f} {(h - 0.001) / 2:.5f}" '
|
| 217 |
+
f'pos="{rc * np.cos(a):.5f} {rc * np.sin(a):.5f} 0.0005" quat="{_fmt(q)}" rgba="{_fmt(CUP_RGBA)}" '
|
| 218 |
+
f'friction="0.8 0.005 0.0001" {CONTACT} group="0" />')
|
| 219 |
+
a0 = r * 0.70
|
| 220 |
+
for k, ang in enumerate((0.0, np.pi / 4)):
|
| 221 |
+
q = [np.cos(ang / 2), 0, 0, np.sin(ang / 2)]
|
| 222 |
+
g.append(f' <geom name="{name}_b{k}" type="box" size="{a0:.5f} {a0:.5f} {bt / 2:.5f}" '
|
| 223 |
+
f'pos="0 0 {-h / 2 + bt / 2:.5f}" quat="{_fmt(q)}" rgba="{_fmt(CUP_RGBA)}" '
|
| 224 |
+
f'friction="0.6 0.005 0.0001" {CONTACT} group="0" />')
|
| 225 |
+
g.append(f' <geom type="cylinder" size="{r:.5f} {h / 2:.5f}" rgba="{_fmt(CUP_RGBA)}" contype="0" '
|
| 226 |
+
f'conaffinity="0" group="1" />')
|
| 227 |
+
g.append(f' <geom type="cylinder" size="{r - wt:.5f} 0.0005" pos="0 0 {h / 2 - 0.0004:.5f}" '
|
| 228 |
+
f'rgba="{_fmt(CUP_INSIDE)}" contype="0" conaffinity="0" group="1" />')
|
| 229 |
+
return _wrap(name, "\n".join(g), h / 2, r)
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def mat_xml(name):
|
| 233 |
+
g = (f' <geom type="box" size="{MAT_HALF:.5f} {MAT_HALF:.5f} 0.0005" rgba="{_fmt(MAT_RGBA)}" contype="0" '
|
| 234 |
+
f'conaffinity="0" group="1" />')
|
| 235 |
+
return _wrap(name, g, 0.0005, MAT_HALF * 1.42)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def free_adr(env, name):
|
| 239 |
+
"""(qpos, dof) address of the object's FREE joint. envs.free_joint_addr takes joints[0], which for an object with a
|
| 240 |
+
jointed child body is the child's joint (robosuite lists the subtree's joints before the free joint it appends)."""
|
| 241 |
+
m = env.sim.model
|
| 242 |
+
for jn in env.objects_dict[name].joints:
|
| 243 |
+
j = m.joint_name2id(jn)
|
| 244 |
+
if int(m.jnt_type[j]) == 0:
|
| 245 |
+
return int(m.jnt_qposadr[j]), int(m.jnt_dofadr[j])
|
| 246 |
+
raise KeyError(name)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def place(env, name, xy, yaw=0.0, surface_z=TZ, clearance=0.0005, tilt=None):
|
| 250 |
+
"""teleport upright (yaw about z; `tilt` rad about the object's own x axis first, e.g. pi/2 = lying on a side
|
| 251 |
+
face -- controls only), lowest collision point `clearance` above surface_z (reset only)"""
|
| 252 |
+
qa, da = free_adr(env, name)
|
| 253 |
+
d = env.sim.data
|
| 254 |
+
d.qpos[qa:qa + 3] = [xy[0], xy[1], surface_z + 0.3]
|
| 255 |
+
q = np.array([np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)])
|
| 256 |
+
if tilt:
|
| 257 |
+
w1, z1 = q[0], q[3]
|
| 258 |
+
c, s_ = np.cos(tilt / 2), np.sin(tilt / 2)
|
| 259 |
+
q = np.array([w1 * c, w1 * s_, z1 * s_, z1 * c]) # q_yaw * q_x(tilt)
|
| 260 |
+
d.qpos[qa + 3:qa + 7] = q
|
| 261 |
+
d.qvel[da:da + 6] = 0.0
|
| 262 |
+
env.sim.forward()
|
| 263 |
+
d.qpos[qa + 2] -= envs.obj_min_z(env, name) - (surface_z + clearance)
|
| 264 |
+
env.sim.forward()
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def _fb(v):
|
| 268 |
+
return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}"
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def _lr(v):
|
| 272 |
+
return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}"
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def _wrap_q(a, period):
|
| 276 |
+
"""wrap an angle to [-period/2, period/2)"""
|
| 277 |
+
return float((a + period / 2) % period - period / 2)
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
class StackSkills(Skills):
|
| 281 |
+
"""Skills that feed the task's per-step monitor."""
|
| 282 |
+
|
| 283 |
+
def __init__(self, env, task, recorder=None):
|
| 284 |
+
super().__init__(env, recorder=recorder)
|
| 285 |
+
self.task = task
|
| 286 |
+
|
| 287 |
+
def _act(self, dpos, drot, grip):
|
| 288 |
+
super()._act(dpos, drot, grip)
|
| 289 |
+
self.task.monitor_step()
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
@register_task
|
| 293 |
+
class TidyStack(LFFTask):
|
| 294 |
+
name = "lh_tidy_stack"
|
| 295 |
+
level = "L2"
|
| 296 |
+
category = "state_restoration"
|
| 297 |
+
capabilities = ("Perceive", "Reason", "Restore", "Plan")
|
| 298 |
+
protocol = "cross"
|
| 299 |
+
max_attempts = 3
|
| 300 |
+
# careful: 5 pick-and-places x ~8 commands (40) + a collapse: unstack 1-2 boxes (~16) and rebuild 3-4 (~32)
|
| 301 |
+
# + looking / small corrections (~30), with some margin
|
| 302 |
+
agent_max_steps = 150
|
| 303 |
+
instruction = ("Tidy up the table: stack the four storage boxes (red, green, blue, yellow) into a single pile on the "
|
| 304 |
+
"grey mat, in any order you like, and then put the cup upright on top of the pile. At the end each "
|
| 305 |
+
"box must rest flat on the box below it (the bottom one on the mat), the cup must stand on the top "
|
| 306 |
+
"box, and the gripper must be open and clear of everything.")
|
| 307 |
+
instruction_indirect = ("Clean up the table: pile the four coloured boxes on top of each other on the dark grey "
|
| 308 |
+
"square, in whatever order, and finish by standing the teal mug on top of the pile. In the "
|
| 309 |
+
"end every box has to sit flat on the one below it (the lowest on the grey square), the mug "
|
| 310 |
+
"has to stand on the top box, and the gripper must be open and away from everything.")
|
| 311 |
+
agent_object_names = ["storage boxes (red, green, blue, yellow)", "grey mat", "cup"]
|
| 312 |
+
|
| 313 |
+
# ------------------------------------------------------------ scene
|
| 314 |
+
def make_bddl(self):
|
| 315 |
+
objs = []
|
| 316 |
+
for i, (c, b) in enumerate(zip(COLOURS, BOXES)):
|
| 317 |
+
cat = register_generated(f"LffLtsBox{c.capitalize()}", box_xml(f"lff_lts_box_{c}", RGBA[c]))
|
| 318 |
+
objs.append((b, cat, f"box{i}_region", (-0.30 + 0.13 * i, 0.28, -0.29 + 0.13 * i, 0.29)))
|
| 319 |
+
cat = register_generated("LffLtsCup", cup_xml("lff_lts_cup"))
|
| 320 |
+
objs.append((CUP, cat, "cup_region", (-0.30, -0.29, -0.29, -0.28)))
|
| 321 |
+
mat = register_generated("LffLtsMat", mat_xml("lff_lts_mat"), free=False)
|
| 322 |
+
fx = [(MAT, mat, "mat_region", (0.0, -0.29, 0.01, -0.28))]
|
| 323 |
+
return write_bddl(self.name, "Stack the four boxes on the grey mat and put the cup on top", objs, fx)
|
| 324 |
+
|
| 325 |
+
def __init__(self, cam_res=None):
|
| 326 |
+
super().__init__(cam_res)
|
| 327 |
+
m = self.env.sim.model
|
| 328 |
+
self.mat_bid = m.body_name2id(self.env.fixtures_dict[MAT].root_body)
|
| 329 |
+
self.jid, self.base_bid, self.upper_bid, self.base_gid, self.upper_gid = {}, {}, {}, {}, {}
|
| 330 |
+
for b in BOXES:
|
| 331 |
+
for g in envs.obj_geom_ids(self.env, b):
|
| 332 |
+
n = m.geom_id2name(g)
|
| 333 |
+
if n.endswith("_upper"):
|
| 334 |
+
self.upper_gid[b] = g
|
| 335 |
+
elif n.endswith("_base"):
|
| 336 |
+
self.base_gid[b] = g
|
| 337 |
+
self.upper_bid[b] = int(m.geom_bodyid[self.upper_gid[b]])
|
| 338 |
+
self.base_bid[b] = int(m.geom_bodyid[self.base_gid[b]])
|
| 339 |
+
j = next(m.joint_name2id(jn) for jn in self.env.objects_dict[b].joints if jn.endswith("_kink"))
|
| 340 |
+
self.jid[b] = j
|
| 341 |
+
# every geom of each half (collision and visual) with its compiled size / pos: the crush rescales them
|
| 342 |
+
self.half_geoms = {}
|
| 343 |
+
for b in BOXES:
|
| 344 |
+
hg = []
|
| 345 |
+
for bid in (self.base_bid[b], self.upper_bid[b]):
|
| 346 |
+
gs = [g for g in range(int(m.body_geomadr[bid]), int(m.body_geomadr[bid] + m.body_geomnum[bid]))
|
| 347 |
+
if int(m.geom_type[g]) == 6]
|
| 348 |
+
hg.append((bid, gs, m.geom_size[gs].copy(), m.geom_pos[gs].copy()))
|
| 349 |
+
self.half_geoms[b] = hg
|
| 350 |
+
self.cup_gids = list(envs.obj_geom_ids(self.env, CUP))
|
| 351 |
+
self.obj_bodies = {b: [self.base_bid[b], self.upper_bid[b]] for b in BOXES}
|
| 352 |
+
self.obj_bodies[CUP] = [envs.body_id(self.env, CUP)]
|
| 353 |
+
# per-geom lookup: owner index 0-3 = boxes, 4 = cup, -1 other; robot part 1 = finger, 2 = hand / arm
|
| 354 |
+
self.owner = np.full(m.ngeom, -1, int)
|
| 355 |
+
for i, b in enumerate(BOXES):
|
| 356 |
+
self.owner[[self.base_gid[b], self.upper_gid[b]]] = i
|
| 357 |
+
self.owner[self.cup_gids] = 4
|
| 358 |
+
self.part = np.zeros(m.ngeom, int)
|
| 359 |
+
for g in envs.robot_geom_ids(self.env):
|
| 360 |
+
n = m.geom_id2name(g) or ""
|
| 361 |
+
self.part[g] = 1 if "finger" in n else 2
|
| 362 |
+
self.inst = None
|
| 363 |
+
self.law = None
|
| 364 |
+
self.mon = None
|
| 365 |
+
self.sk = None
|
| 366 |
+
self._sub_rob = {}
|
| 367 |
+
self._held = set() # owner indices (0-3 boxes, 4 cup) held by the gripper, refreshed every control step
|
| 368 |
+
self._rest_cap = np.inf # upper bound of the resting load on the soft carton, refreshed every control step
|
| 369 |
+
sim = self.env.sim
|
| 370 |
+
if not getattr(sim, "_lts_wrapped", False):
|
| 371 |
+
orig = sim.step
|
| 372 |
+
|
| 373 |
+
def step(*a, **k):
|
| 374 |
+
t = getattr(sim, "_lts_task", None)
|
| 375 |
+
if t is not None and t.law is not None:
|
| 376 |
+
t._law_step()
|
| 377 |
+
orig(*a, **k)
|
| 378 |
+
if t is not None and t.mon is not None:
|
| 379 |
+
t._substep()
|
| 380 |
+
sim.step = step
|
| 381 |
+
sim._lts_wrapped = True
|
| 382 |
+
sim._lts_task = self
|
| 383 |
+
|
| 384 |
+
# ------------------------------------------------------------ instances
|
| 385 |
+
def sample_instance(self, seed):
|
| 386 |
+
rng = np.random.default_rng(seed)
|
| 387 |
+
mx, my = float(rng.uniform(*MAT_X)), float(rng.uniform(*MAT_Y))
|
| 388 |
+
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
|
| 389 |
+
cd = float(rng.uniform(0.23, 0.26))
|
| 390 |
+
cup = [mx + cd * np.cos(ca), my + cd * np.sin(ca)]
|
| 391 |
+
for _ in range(500):
|
| 392 |
+
ds = np.array(BOX_D) + rng.uniform(-0.01, 0.01, 4)
|
| 393 |
+
ang = rng.uniform(np.radians(30), np.radians(150), 4) * rng.choice([-1.0, 1.0], 4)
|
| 394 |
+
pos = np.stack([mx + ds * np.cos(ang), my + ds * np.sin(ang)], 1)
|
| 395 |
+
if not (np.all((pos[:, 0] >= BOX_X[0]) & (pos[:, 0] <= BOX_X[1])) and np.all(np.abs(pos[:, 1]) <= BOX_YMAX)):
|
| 396 |
+
continue
|
| 397 |
+
dd = np.linalg.norm(pos[:, None] - pos[None], axis=2) + np.eye(4)
|
| 398 |
+
if dd.min() < 0.12 or np.linalg.norm(pos - np.asarray(cup), axis=1).min() < 0.14:
|
| 399 |
+
continue
|
| 400 |
+
break
|
| 401 |
+
else:
|
| 402 |
+
raise RuntimeError("layout")
|
| 403 |
+
perm = rng.permutation(4)
|
| 404 |
+
start = {BOXES[i]: [float(v) for v in pos[perm[i]]] for i in range(4)}
|
| 405 |
+
yaw = {b: float(rng.uniform(-BOX_YAW, BOX_YAW)) for b in BOXES}
|
| 406 |
+
mat = np.array([mx, my])
|
| 407 |
+
near = sorted(BOXES, key=lambda b: float(np.linalg.norm(np.asarray(start[b]) - mat)))
|
| 408 |
+
# balanced blocks of 20 consecutive seeds: 2 benign (no soft box); else the soft carton is the box at rank
|
| 409 |
+
# r = 0..3 (0 = nearest the mat, i.e. the bottom of a nearest-first pile; 3 = the top): 5 / 5 / 4 / 4
|
| 410 |
+
k = (int(seed) * 7) % 20
|
| 411 |
+
benign = k >= round(20 * (1 - P_BENIGN))
|
| 412 |
+
rank = None if benign else k % 4
|
| 413 |
+
soft = None if benign else near[rank]
|
| 414 |
+
return dict(seed=int(seed), mat=[mx, my], cup=cup, start=start, yaw=yaw, cup_yaw=float(rng.uniform(-np.pi, np.pi)),
|
| 415 |
+
soft=soft, soft_colour=COL[soft] if soft else None, benign=bool(benign),
|
| 416 |
+
soft_rank_nearest=rank, nearest_order=[COL[b] for b in near],
|
| 417 |
+
buckle_dir=float(np.pi / 2 if rng.random() < 0.5 else -np.pi / 2),
|
| 418 |
+
f_crit=F_CRIT, naive_gap=float(rng.uniform(*NAIVE_GAP)), naive_bias=float(rng.uniform(*NAIVE_BIAS)))
|
| 419 |
+
|
| 420 |
+
def apply_instance(self, inst):
|
| 421 |
+
self.inst = inst
|
| 422 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 423 |
+
m.body_pos[self.mat_bid] = [inst["mat"][0], inst["mat"][1], TZ + 0.0005]
|
| 424 |
+
for b in BOXES:
|
| 425 |
+
j = self.jid[b]
|
| 426 |
+
soft = b == inst["soft"]
|
| 427 |
+
M = SOFT_MASS if soft else BOX_MASS
|
| 428 |
+
for bid, frac, h in ((self.base_bid[b], HB / H, HB), (self.upper_bid[b], HU / H, HU)):
|
| 429 |
+
mm = M * frac
|
| 430 |
+
m.body_mass[bid] = mm
|
| 431 |
+
m.body_inertia[bid] = [mm * (4 * HY * HY + h * h) / 12, mm * (4 * HX * HX + h * h) / 12,
|
| 432 |
+
mm * (4 * HX * HX + 4 * HY * HY) / 12]
|
| 433 |
+
m.jnt_range[j] = [0.0, RANGE_SOFT if soft else RANGE_RIGID]
|
| 434 |
+
m.jnt_solref[j] = [0.02, 1.0] if soft else [0.004, 1.0] # rigid boxes: a stiff limit
|
| 435 |
+
m.jnt_stiffness[j] = K_HI if soft else K_RIGID
|
| 436 |
+
qa, da = int(m.jnt_qposadr[j]), int(m.jnt_dofadr[j])
|
| 437 |
+
m.qpos_spring[qa:qa + 4] = [1.0, 0.0, 0.0, 0.0]
|
| 438 |
+
d.qpos[qa:qa + 4] = [1.0, 0.0, 0.0, 0.0]
|
| 439 |
+
d.qvel[da:da + 3] = 0.0
|
| 440 |
+
self._set_crush(b, 0.0, 2, -1.0) # undo a crush left over from the previous attempt
|
| 441 |
+
place(self.env, b, inst["start"][b], yaw=inst["yaw"][b], tilt=inst.get("lying", {}).get(COL[b]))
|
| 442 |
+
place(self.env, CUP, inst["cup"], yaw=inst["cup_yaw"])
|
| 443 |
+
self.law = None
|
| 444 |
+
if inst["soft"]:
|
| 445 |
+
self.law = dict(box=inst["soft"], f=0.0, fmax=0.0, buckled=False, n=0, rel_t=0.0, t=0.0, buckles=[],
|
| 446 |
+
f_crit=float(inst.get("f_crit", F_CRIT)), dir=float(inst["buckle_dir"]),
|
| 447 |
+
mode=str(inst.get("law", "threshold")), how=None, crush=0.0, crush_set=0.0,
|
| 448 |
+
crush_axis=2, crush_sign=-1.0, f_rest=0.0, f_robot=0.0)
|
| 449 |
+
if self.law["mode"] == "linear": # control only: the brief's fixed-stiffness spring (no load threshold)
|
| 450 |
+
m.jnt_stiffness[self.jid[inst["soft"]]] = float(inst["k_lin"])
|
| 451 |
+
|
| 452 |
+
def reset_instance(self, inst, recorder=None):
|
| 453 |
+
self.mon = None
|
| 454 |
+
self.law = None
|
| 455 |
+
self.env.reset()
|
| 456 |
+
self.apply_instance(inst)
|
| 457 |
+
self.env.sim.forward()
|
| 458 |
+
envs.settle(self.env, 15)
|
| 459 |
+
self.sk = StackSkills(self.env, self, recorder=recorder)
|
| 460 |
+
self._sub_rob = {}
|
| 461 |
+
self._held = set()
|
| 462 |
+
self._rest_cap = np.inf
|
| 463 |
+
self._init_monitor()
|
| 464 |
+
return self.sk
|
| 465 |
+
|
| 466 |
+
# ------------------------------------------------------------ soft-carton law
|
| 467 |
+
def _part_axial(self, gid, axis):
|
| 468 |
+
"""sum of contact forces on geom gid (from any other geom), projected on `axis` (world)"""
|
| 469 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 470 |
+
n = d.ncon
|
| 471 |
+
if not n:
|
| 472 |
+
return 0.0
|
| 473 |
+
g1 = np.asarray(d.contact.geom1)[:n]
|
| 474 |
+
g2 = np.asarray(d.contact.geom2)[:n]
|
| 475 |
+
idx = np.nonzero((g1 == gid) | (g2 == gid))[0]
|
| 476 |
+
tot = 0.0
|
| 477 |
+
f6 = np.zeros(6)
|
| 478 |
+
for i in idx:
|
| 479 |
+
mujoco.mj_contactForce(m._model, d._data, int(i), f6)
|
| 480 |
+
fw = d.contact[int(i)].frame.reshape(3, 3).T @ f6[:3] # force on geom2, world frame
|
| 481 |
+
tot += float(fw @ axis) * (-1.0 if g1[i] == gid else 1.0)
|
| 482 |
+
return tot
|
| 483 |
+
|
| 484 |
+
def vertical_loads(self, b):
|
| 485 |
+
"""vertical contact forces on box b (N), whichever face it rests on: (resting, robot, held, support).
|
| 486 |
+
resting = downward push on its upper side (contact point above its centre) from things resting on it;
|
| 487 |
+
robot = the same from the robot's own fingers / hand pushing on it (not counted while the robot holds b
|
| 488 |
+
itself); held = the same from something the robot holds (pressing it down onto b); support = upward push on
|
| 489 |
+
its lower side. Its two halves never touch (parent and child), so only real contacts count."""
|
| 490 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 491 |
+
n = d.ncon
|
| 492 |
+
if not n:
|
| 493 |
+
return 0.0, 0.0, 0.0, 0.0
|
| 494 |
+
gb, gu = self.base_gid[b], self.upper_gid[b]
|
| 495 |
+
g1 = np.asarray(d.contact.geom1)[:n]
|
| 496 |
+
g2 = np.asarray(d.contact.geom2)[:n]
|
| 497 |
+
idx = np.nonzero((g1 == gb) | (g1 == gu) | (g2 == gb) | (g2 == gu))[0]
|
| 498 |
+
if not len(idx):
|
| 499 |
+
return 0.0, 0.0, 0.0, 0.0
|
| 500 |
+
cz = float(d.xpos[self.base_bid[b]][2]) # the root body sits at the box's centre
|
| 501 |
+
held = self._held
|
| 502 |
+
b_held = BOXES.index(b) in held
|
| 503 |
+
rest = robot = via = sup = 0.0
|
| 504 |
+
f6 = np.zeros(6)
|
| 505 |
+
for i in idx:
|
| 506 |
+
c = d.contact[int(i)]
|
| 507 |
+
mujoco.mj_contactForce(m._model, d._data, int(i), f6)
|
| 508 |
+
fz = float(c.frame.reshape(3, 3)[:, 2] @ f6[:3]) # world z of the force on geom2
|
| 509 |
+
mine1 = g1[i] in (gb, gu)
|
| 510 |
+
fz = -fz if mine1 else fz # force on box b
|
| 511 |
+
other = int(g2[i] if mine1 else g1[i])
|
| 512 |
+
pz = float(c.pos[2])
|
| 513 |
+
if pz > cz + 0.004 and fz < 0.0:
|
| 514 |
+
o = self.owner[other]
|
| 515 |
+
if self.part[other] > 0:
|
| 516 |
+
if not b_held:
|
| 517 |
+
robot -= fz
|
| 518 |
+
elif o >= 0 and o in held:
|
| 519 |
+
via -= fz
|
| 520 |
+
else:
|
| 521 |
+
rest -= fz
|
| 522 |
+
elif pz < cz - 0.004 and fz > 0.0:
|
| 523 |
+
sup += fz
|
| 524 |
+
# what rests on it pushes at most with its own weight: the robot pressing down through an item it has let go
|
| 525 |
+
# of (Sonnet releases with the cup pushed up against the hand, pilot s3003) is not a resting load
|
| 526 |
+
rest = min(rest, self._rest_cap)
|
| 527 |
+
return rest, robot, via, sup
|
| 528 |
+
|
| 529 |
+
def compression(self, b):
|
| 530 |
+
"""compressive force (N) on the carton, (total, resting): the downward push on its upper side from things
|
| 531 |
+
resting on it plus the robot's fingers / hand pushing directly on it, limited by the support under it --
|
| 532 |
+
along the world vertical, whichever face it rests on (v1 measured it along the box axis only: a carton lying
|
| 533 |
+
on its side never buckled). Something the robot still holds does not count: Sonnet presses what it puts down
|
| 534 |
+
0.5-1.5 cm below contact (pilot), which must not crush a carton that will carry the item once let go."""
|
| 535 |
+
rest, robot, via, sup = self.vertical_loads(b)
|
| 536 |
+
return float(min(rest + robot, sup)), float(min(rest, sup))
|
| 537 |
+
|
| 538 |
+
def _law_step(self):
|
| 539 |
+
"""per MuJoCo substep: low-pass the compressive load; above f_crit the carton gives way -- standing or upside
|
| 540 |
+
down it folds (its kink joint loses its stiffness, its rest shape bends towards its weak side and the load
|
| 541 |
+
topples it), lying on a side face it is crushed (both halves flatten, the upper half more); unloaded for
|
| 542 |
+
REL_T it slowly recovers its shape"""
|
| 543 |
+
law = self.law
|
| 544 |
+
b = law["box"]
|
| 545 |
+
m = self.env.sim.model
|
| 546 |
+
dt = float(m.opt.timestep)
|
| 547 |
+
tot, rest = self.compression(b)
|
| 548 |
+
law["f"] += (tot - law["f"]) * dt / TAU_F
|
| 549 |
+
law["f_rest"] += (rest - law["f_rest"]) * dt / TAU_F
|
| 550 |
+
law["fmax"] = max(law["fmax"], law["f"])
|
| 551 |
+
j = self.jid[b]
|
| 552 |
+
qa = int(m.jnt_qposadr[j])
|
| 553 |
+
if law["mode"] == "linear": # control: constant stiffness; a "buckle" = the kink passes 15 deg (re-arms < 5)
|
| 554 |
+
kk = self.kink(b)
|
| 555 |
+
if not law["buckled"] and kk > np.radians(15.0):
|
| 556 |
+
law["buckled"] = True
|
| 557 |
+
law["n"] += 1
|
| 558 |
+
law["buckles"].append(dict(t=round(law["t"], 3), load_N=round(law["f"], 2)))
|
| 559 |
+
self._on_buckle()
|
| 560 |
+
elif law["buckled"] and kk < np.radians(5.0):
|
| 561 |
+
law["buckled"] = False
|
| 562 |
+
law["t"] += dt
|
| 563 |
+
return
|
| 564 |
+
if not law["buckled"]:
|
| 565 |
+
if law["f"] > law["f_crit"]:
|
| 566 |
+
law["buckled"] = True
|
| 567 |
+
law["n"] += 1
|
| 568 |
+
law["rel_t"] = 0.0
|
| 569 |
+
R = self.env.sim.data.xmat[self.base_bid[b]].reshape(3, 3)
|
| 570 |
+
law["unbend_q0"] = None
|
| 571 |
+
if abs(R[2, 2]) >= FOLD_MIN_UP: # seam horizontal: fold
|
| 572 |
+
law["how"] = "fold"
|
| 573 |
+
u = R.T @ np.array([np.cos(law["dir"]), np.sin(law["dir"]), 0.0])
|
| 574 |
+
ax = np.array([-u[1], u[0], 0.0])
|
| 575 |
+
ax /= max(np.linalg.norm(ax), 1e-9)
|
| 576 |
+
m.qpos_spring[qa:qa + 4] = [np.cos(BEND_REF / 2), *(np.sin(BEND_REF / 2) * ax)]
|
| 577 |
+
else: # seam vertical (lying on a side face): crush towards the face it rests on
|
| 578 |
+
law["how"] = "crush"
|
| 579 |
+
k = int(np.argmax(np.abs(R[2, :2])))
|
| 580 |
+
law["crush_axis"] = k
|
| 581 |
+
law["crush_sign"] = -float(np.sign(R[2, k]) or 1.0) # local direction of "down" along axis k
|
| 582 |
+
# cause: "load" = what rests on it is enough by itself (>= 60 % of f_crit, i.e. more than one item);
|
| 583 |
+
# "press" = the robot's own push made the difference (a hard press with the gripper)
|
| 584 |
+
cause = "load" if law["f_rest"] >= 0.6 * law["f_crit"] else "press"
|
| 585 |
+
law["buckles"].append(dict(t=round(law["t"], 3), load_N=round(law["f"], 2), how=law["how"],
|
| 586 |
+
resting_N=round(law["f_rest"], 2), cause=cause))
|
| 587 |
+
self._on_buckle()
|
| 588 |
+
elif law["f"] < F_REL:
|
| 589 |
+
law["rel_t"] += dt
|
| 590 |
+
if law["rel_t"] > REL_T:
|
| 591 |
+
law["buckled"] = False
|
| 592 |
+
# straighten smoothly: the rest shape starts at the current bend and moves back to straight over
|
| 593 |
+
# K_RISE (a stiff spring released at once from a 40-50 deg bend flips the light carton over)
|
| 594 |
+
q0 = np.array(self.env.sim.data.qpos[qa:qa + 4], float)
|
| 595 |
+
q0 = q0 / max(np.linalg.norm(q0), 1e-9) * (1.0 if q0[0] >= 0 else -1.0)
|
| 596 |
+
law["unbend_q0"], law["unbend_s"] = q0.tolist(), 0.0
|
| 597 |
+
m.qpos_spring[qa:qa + 4] = q0
|
| 598 |
+
else:
|
| 599 |
+
law["rel_t"] = 0.0
|
| 600 |
+
k = float(m.jnt_stiffness[j])
|
| 601 |
+
if law["buckled"] and law["how"] == "fold":
|
| 602 |
+
m.jnt_stiffness[j] = k + (K_LO - k) * min(1.0, dt / 0.02)
|
| 603 |
+
else:
|
| 604 |
+
m.jnt_stiffness[j] = K_HI
|
| 605 |
+
if law.get("unbend_q0") is not None:
|
| 606 |
+
law["unbend_s"] = min(1.0, law["unbend_s"] + dt / K_RISE)
|
| 607 |
+
q = (1.0 - law["unbend_s"]) * np.asarray(law["unbend_q0"]) + law["unbend_s"] * np.array([1.0, 0, 0, 0])
|
| 608 |
+
m.qpos_spring[qa:qa + 4] = q / np.linalg.norm(q)
|
| 609 |
+
if law["unbend_s"] >= 1.0:
|
| 610 |
+
law["unbend_q0"] = None
|
| 611 |
+
target = 1.0 if (law["buckled"] and law["how"] == "crush") else 0.0
|
| 612 |
+
if target or law["crush"] > 0.0:
|
| 613 |
+
tau = CRUSH_TAU[0] if target else CRUSH_TAU[1]
|
| 614 |
+
law["crush"] += (target - law["crush"]) * min(1.0, dt / tau)
|
| 615 |
+
if not target and law["crush"] < 0.002:
|
| 616 |
+
law["crush"] = 0.0
|
| 617 |
+
if abs(law["crush"] - law["crush_set"]) > 0.004 or (law["crush"] == 0.0 and law["crush_set"] > 0.0):
|
| 618 |
+
self._set_crush(b, law["crush"], law["crush_axis"], law["crush_sign"])
|
| 619 |
+
law["crush_set"] = law["crush"]
|
| 620 |
+
law["t"] += dt
|
| 621 |
+
|
| 622 |
+
def _set_crush(self, b, c, axis, sign):
|
| 623 |
+
"""flatten box b's two halves along their local `axis` by c (0..1) x CRUSH_ALPHA, keeping the faces on the
|
| 624 |
+
`sign` side (the side facing down) in place; then refresh the collision bounds"""
|
| 625 |
+
m = self.env.sim.model
|
| 626 |
+
for (bid, gs, size0, pos0), alpha in zip(self.half_geoms[b], CRUSH_ALPHA):
|
| 627 |
+
size, pos = size0.copy(), pos0.copy()
|
| 628 |
+
if c > 0.0:
|
| 629 |
+
s0 = size0[:, axis]
|
| 630 |
+
s1 = s0 * (1.0 - alpha * c)
|
| 631 |
+
size[:, axis] = s1
|
| 632 |
+
pos[:, axis] = pos0[:, axis] + sign * (s0 - s1)
|
| 633 |
+
m.geom_size[gs] = size
|
| 634 |
+
m.geom_pos[gs] = pos
|
| 635 |
+
envs.refit_bounds(m, [self.half_geoms[b][0][0], self.half_geoms[b][1][0]])
|
| 636 |
+
|
| 637 |
+
def _on_buckle(self):
|
| 638 |
+
mon = self.mon
|
| 639 |
+
if mon is None:
|
| 640 |
+
return
|
| 641 |
+
b = self.law["box"]
|
| 642 |
+
ch = self.pile()
|
| 643 |
+
on = self.items_on(b)
|
| 644 |
+
last = self.law["buckles"][-1] if self.law["buckles"] else {}
|
| 645 |
+
e = dict(event="buckle", box=COL[b], step=int(self.sk.n_steps) if self.sk else 0,
|
| 646 |
+
load_N=round(self.law["f"], 2), level=(ch.index(b) + 1) if b in ch else None,
|
| 647 |
+
items_on=[COL.get(x, "cup") for x in on], how=last.get("how"), cause=last.get("cause"),
|
| 648 |
+
resting_N=last.get("resting_N"),
|
| 649 |
+
lying=bool(abs(self.R(self.base_bid[b])[2, 2]) < FOLD_MIN_UP))
|
| 650 |
+
mon["events"].append(e)
|
| 651 |
+
mon["buckle_steps"].append(e["step"])
|
| 652 |
+
mon["pending_collapse"] = dict(step=e["step"], pile=list(ch), cup=self.cup_on_pile(ch))
|
| 653 |
+
|
| 654 |
+
# ------------------------------------------------------------ geometry / predicates
|
| 655 |
+
def R(self, bid):
|
| 656 |
+
return self.env.sim.data.xmat[bid].reshape(3, 3)
|
| 657 |
+
|
| 658 |
+
def centre(self, name):
|
| 659 |
+
return envs.obj_pos(self.env, name)
|
| 660 |
+
|
| 661 |
+
def flat_tilt(self, b):
|
| 662 |
+
"""angle (rad) between world vertical and the base part's axis closest to it (a box may lie on any face)"""
|
| 663 |
+
R = self.R(self.base_bid[b])
|
| 664 |
+
return float(np.arccos(np.clip(np.max(np.abs(R[2, :])), -1.0, 1.0)))
|
| 665 |
+
|
| 666 |
+
def kink(self, b):
|
| 667 |
+
"""bend of the upper part against the base part (rad)"""
|
| 668 |
+
zb = self.R(self.base_bid[b])[:, 2]
|
| 669 |
+
zu = self.R(self.upper_bid[b])[:, 2]
|
| 670 |
+
return float(np.arccos(np.clip(zb @ zu, -1.0, 1.0)))
|
| 671 |
+
|
| 672 |
+
def cup_tilt(self):
|
| 673 |
+
return float(np.arccos(np.clip(envs.obj_upright_cos(self.env, CUP), -1.0, 1.0)))
|
| 674 |
+
|
| 675 |
+
def held(self, name):
|
| 676 |
+
return self.sk is not None and self.sk.holding(name)
|
| 677 |
+
|
| 678 |
+
def crushed(self, b):
|
| 679 |
+
"""how far box b is crushed (0..1; only the soft carton, lying on a side face, can be)"""
|
| 680 |
+
law = self.law
|
| 681 |
+
return float(law["crush"]) if (law is not None and law["box"] == b) else 0.0
|
| 682 |
+
|
| 683 |
+
def flat(self, b):
|
| 684 |
+
return (self.flat_tilt(b) <= TILT_OK and self.kink(b) <= KINK_OK and self.crushed(b) <= 0.15
|
| 685 |
+
and not self.held(b))
|
| 686 |
+
|
| 687 |
+
def rests_on(self, upper, lower):
|
| 688 |
+
cu, cl = self.centre(upper), self.centre(lower)
|
| 689 |
+
return (np.linalg.norm(cu[:2] - cl[:2]) <= STACK_XY
|
| 690 |
+
and abs(envs.obj_min_z(self.env, upper) - envs.obj_max_z(self.env, lower)) <= STACK_Z)
|
| 691 |
+
|
| 692 |
+
def on_mat(self, b):
|
| 693 |
+
off = self.centre(b)[:2] - np.asarray(self.inst["mat"])
|
| 694 |
+
return bool(np.all(np.abs(off) <= ON_MAT) and envs.obj_min_z(self.env, b) <= TZ + 0.008)
|
| 695 |
+
|
| 696 |
+
def pile(self):
|
| 697 |
+
"""the longest chain of flat boxes: the bottom one on the mat, each next resting on the previous (centres within
|
| 698 |
+
2 cm, faces within 1 cm)"""
|
| 699 |
+
flat = [b for b in BOXES if self.flat(b)]
|
| 700 |
+
best = []
|
| 701 |
+
for b0 in [b for b in flat if self.on_mat(b)]:
|
| 702 |
+
ch = [b0]
|
| 703 |
+
while True:
|
| 704 |
+
nxt = [b for b in flat if b not in ch and self.rests_on(b, ch[-1])]
|
| 705 |
+
if not nxt:
|
| 706 |
+
break
|
| 707 |
+
ch.append(min(nxt, key=lambda b: float(np.linalg.norm(self.centre(b)[:2] - self.centre(ch[-1])[:2]))))
|
| 708 |
+
if len(ch) > len(best):
|
| 709 |
+
best = ch
|
| 710 |
+
return best
|
| 711 |
+
|
| 712 |
+
def cup_on(self, b):
|
| 713 |
+
c = self.centre(CUP)
|
| 714 |
+
return bool(self.cup_tilt() <= TILT_OK and not self.held(CUP)
|
| 715 |
+
and np.linalg.norm(c[:2] - self.centre(b)[:2]) <= CUP_XY
|
| 716 |
+
and abs(envs.obj_min_z(self.env, CUP) - envs.obj_max_z(self.env, b)) <= STACK_Z)
|
| 717 |
+
|
| 718 |
+
def cup_on_pile(self, ch=None):
|
| 719 |
+
ch = self.pile() if ch is None else ch
|
| 720 |
+
return bool(len(ch) == len(BOXES) and self.cup_on(ch[-1]))
|
| 721 |
+
|
| 722 |
+
def items_on(self, b):
|
| 723 |
+
"""boxes / cup resting (directly or higher up) on box b, by height and overlap"""
|
| 724 |
+
cb = self.centre(b)
|
| 725 |
+
top = envs.obj_max_z(self.env, b)
|
| 726 |
+
out = []
|
| 727 |
+
for x in BOXES + [CUP]:
|
| 728 |
+
if x == b:
|
| 729 |
+
continue
|
| 730 |
+
c = self.centre(x)
|
| 731 |
+
if envs.obj_min_z(self.env, x) > top - 0.015 and np.linalg.norm(c[:2] - cb[:2]) < 0.06:
|
| 732 |
+
out.append(x)
|
| 733 |
+
return out
|
| 734 |
+
|
| 735 |
+
def stage_values(self):
|
| 736 |
+
ch = self.pile()
|
| 737 |
+
v = {COL[b]: b in ch for b in BOXES}
|
| 738 |
+
v["cup"] = self.cup_on_pile(ch)
|
| 739 |
+
return v, ch
|
| 740 |
+
|
| 741 |
+
# ------------------------------------------------------------ monitor
|
| 742 |
+
def _init_monitor(self):
|
| 743 |
+
keys = COLOURS + ["cup"]
|
| 744 |
+
self.mon = dict(state={k: False for k in keys}, cand={k: 0 for k in keys}, ever={k: False for k in keys},
|
| 745 |
+
lost={k: False for k in keys}, lost_cause={k: None for k in keys}, events=[], n=0,
|
| 746 |
+
last_robot={k: -10 ** 6 for k in keys}, buckle_steps=[], pending_collapse=None,
|
| 747 |
+
max_kink={COL[b]: 0.0 for b in BOXES}, max_crush={COL[b]: 0.0 for b in BOXES},
|
| 748 |
+
max_height=0, n_collapses=0,
|
| 749 |
+
law=self.law) # the carton's law state rides along in the robot server's regression snapshots
|
| 750 |
+
|
| 751 |
+
def _substep(self):
|
| 752 |
+
d = self.env.sim.data
|
| 753 |
+
n = d.ncon
|
| 754 |
+
if not n:
|
| 755 |
+
return
|
| 756 |
+
g1 = np.asarray(d.contact.geom1)[:n]
|
| 757 |
+
g2 = np.asarray(d.contact.geom2)[:n]
|
| 758 |
+
o1, o2 = self.owner[g1], self.owner[g2]
|
| 759 |
+
p1, p2 = self.part[g1], self.part[g2]
|
| 760 |
+
sel = ((o1 >= 0) & (p2 > 0)) | ((o2 >= 0) & (p1 > 0))
|
| 761 |
+
for i in np.nonzero(sel)[0]:
|
| 762 |
+
o = o1[i] if o1[i] >= 0 else o2[i]
|
| 763 |
+
self._sub_rob[int(o)] = True
|
| 764 |
+
|
| 765 |
+
def monitor_step(self):
|
| 766 |
+
mon = self.mon
|
| 767 |
+
if mon is None or self.sk is None:
|
| 768 |
+
return
|
| 769 |
+
mon["n"] += 1
|
| 770 |
+
t = int(self.sk.n_steps)
|
| 771 |
+
self._held = {i for i, x in enumerate(BOXES + [CUP]) if self.held(x)}
|
| 772 |
+
if self.law is not None: # weight of the things (not held) on the soft carton, + 0.3 N for impacts
|
| 773 |
+
m = self.env.sim.model
|
| 774 |
+
self._rest_cap = 0.3 + G * sum(float(np.sum(m.body_mass[self.obj_bodies[x]]))
|
| 775 |
+
for x in self.items_on(self.law["box"])
|
| 776 |
+
if (BOXES + [CUP]).index(x) not in self._held)
|
| 777 |
+
keys = COLOURS + ["cup"]
|
| 778 |
+
for i in list(self._sub_rob):
|
| 779 |
+
mon["last_robot"][keys[i]] = t
|
| 780 |
+
self._sub_rob = {}
|
| 781 |
+
for b in BOXES:
|
| 782 |
+
mon["max_kink"][COL[b]] = max(mon["max_kink"][COL[b]], round(float(np.degrees(self.kink(b))), 1))
|
| 783 |
+
mon["max_crush"][COL[b]] = max(mon["max_crush"][COL[b]], round(self.crushed(b), 2))
|
| 784 |
+
if mon["n"] % 2:
|
| 785 |
+
return
|
| 786 |
+
vals, ch = self.stage_values()
|
| 787 |
+
mon["max_height"] = max(mon["max_height"], len(ch))
|
| 788 |
+
for k in keys:
|
| 789 |
+
raw = vals[k]
|
| 790 |
+
if raw == mon["state"][k]:
|
| 791 |
+
mon["cand"][k] = 0
|
| 792 |
+
continue
|
| 793 |
+
mon["cand"][k] += 2
|
| 794 |
+
if mon["cand"][k] < DEBOUNCE:
|
| 795 |
+
continue
|
| 796 |
+
mon["cand"][k] = 0
|
| 797 |
+
mon["state"][k] = raw
|
| 798 |
+
t0 = t - DEBOUNCE + 1
|
| 799 |
+
if raw:
|
| 800 |
+
restored = mon["lost"][k]
|
| 801 |
+
e = dict(stage=k, event="restored" if restored else "achieved", step=t0)
|
| 802 |
+
if restored:
|
| 803 |
+
e["after"] = mon["lost_cause"][k]
|
| 804 |
+
mon["lost"][k] = False
|
| 805 |
+
mon["ever"][k] = True
|
| 806 |
+
mon["events"].append(e)
|
| 807 |
+
elif mon["ever"][k]:
|
| 808 |
+
cause = self._cause(k, t)
|
| 809 |
+
mon["lost"][k] = True
|
| 810 |
+
mon["lost_cause"][k] = cause
|
| 811 |
+
mon["events"].append(dict(stage=k, event="lost", step=t0, cause=cause))
|
| 812 |
+
pc = mon["pending_collapse"]
|
| 813 |
+
if cause == "buckle" and pc is not None and not pc.get("counted"):
|
| 814 |
+
pc["counted"] = True
|
| 815 |
+
mon["n_collapses"] += 1
|
| 816 |
+
mon["events"].append(dict(event="collapse", step=t0, buckled=self.inst["soft_colour"],
|
| 817 |
+
pile_before=[COL[b] for b in pc["pile"]]))
|
| 818 |
+
|
| 819 |
+
def _cause(self, k, t):
|
| 820 |
+
name = CUP if k == "cup" else BOXES[COLOURS.index(k)]
|
| 821 |
+
if self.held(name):
|
| 822 |
+
return "picked_up"
|
| 823 |
+
bs = self.mon["buckle_steps"]
|
| 824 |
+
if bs and t - bs[-1] <= 80: # within 4 s of a buckle
|
| 825 |
+
return "buckle"
|
| 826 |
+
if t - self.mon["last_robot"][k] <= 30:
|
| 827 |
+
return "robot"
|
| 828 |
+
return "other"
|
| 829 |
+
|
| 830 |
+
def _finalize_monitor(self, vals):
|
| 831 |
+
mon = self.mon
|
| 832 |
+
t = int(self.sk.n_steps)
|
| 833 |
+
for k, raw in vals.items():
|
| 834 |
+
if raw == mon["state"][k]:
|
| 835 |
+
continue
|
| 836 |
+
mon["state"][k] = raw
|
| 837 |
+
if raw:
|
| 838 |
+
restored = mon["lost"][k]
|
| 839 |
+
e = dict(stage=k, event="restored" if restored else "achieved", step=t, final=True)
|
| 840 |
+
if restored:
|
| 841 |
+
e["after"] = mon["lost_cause"][k]
|
| 842 |
+
mon["lost"][k] = False
|
| 843 |
+
mon["ever"][k] = True
|
| 844 |
+
mon["events"].append(e)
|
| 845 |
+
elif mon["ever"][k]:
|
| 846 |
+
cause = self._cause(k, t)
|
| 847 |
+
mon["lost"][k] = True
|
| 848 |
+
mon["lost_cause"][k] = cause
|
| 849 |
+
mon["events"].append(dict(stage=k, event="lost", step=t, cause=cause, final=True))
|
| 850 |
+
|
| 851 |
+
# ------------------------------------------------------------ outcome
|
| 852 |
+
def _touching(self):
|
| 853 |
+
d = self.env.sim.data
|
| 854 |
+
n = d.ncon
|
| 855 |
+
if not n:
|
| 856 |
+
return False
|
| 857 |
+
g1 = np.asarray(d.contact.geom1)[:n]
|
| 858 |
+
g2 = np.asarray(d.contact.geom2)[:n]
|
| 859 |
+
return bool(np.any(((self.owner[g1] >= 0) & (self.part[g2] > 0)) | ((self.owner[g2] >= 0) & (self.part[g1] > 0))))
|
| 860 |
+
|
| 861 |
+
def _static_pos(self):
|
| 862 |
+
return {x: self.centre(x).copy() for x in BOXES + [CUP]}
|
| 863 |
+
|
| 864 |
+
def outcome(self, inst):
|
| 865 |
+
sk = self.sk
|
| 866 |
+
sk.hold(10)
|
| 867 |
+
p0 = self._static_pos()
|
| 868 |
+
touching = False
|
| 869 |
+
for _ in range(20):
|
| 870 |
+
sk.hold(1)
|
| 871 |
+
touching = touching or self._touching()
|
| 872 |
+
moved = max(float(np.linalg.norm(self.centre(x) - p0[x])) for x in p0)
|
| 873 |
+
static = moved < 0.003
|
| 874 |
+
vals, ch = self.stage_values()
|
| 875 |
+
self._finalize_monitor(vals)
|
| 876 |
+
mon = self.mon
|
| 877 |
+
ev = list(mon["events"])
|
| 878 |
+
held = [COL.get(x, "cup") for x in BOXES + [CUP] if self.held(x)]
|
| 879 |
+
success = bool(all(vals.values()) and static and not held and not touching)
|
| 880 |
+
buckles = [e for e in ev if e.get("event") == "buckle"]
|
| 881 |
+
n_reg = sum(e.get("event") == "lost" and e.get("cause") != "picked_up" for e in ev)
|
| 882 |
+
n_res = sum(e.get("event") == "restored" and e.get("after") != "picked_up" for e in ev)
|
| 883 |
+
soft = inst["soft"]
|
| 884 |
+
buckled_now = bool(self.law is not None and self.law["buckled"])
|
| 885 |
+
cup_fallen = self.cup_tilt() > np.radians(45)
|
| 886 |
+
if success:
|
| 887 |
+
failure = "none"
|
| 888 |
+
elif held:
|
| 889 |
+
failure = "held"
|
| 890 |
+
elif touching and all(vals.values()):
|
| 891 |
+
failure = "touching"
|
| 892 |
+
elif not all(vals[c] for c in COLOURS):
|
| 893 |
+
if buckles and any(mon["ever"][c] for c in COLOURS):
|
| 894 |
+
failure = "collapsed"
|
| 895 |
+
elif any(mon["lost"][c] for c in COLOURS):
|
| 896 |
+
failure = "regressed"
|
| 897 |
+
else:
|
| 898 |
+
failure = "not_stacked"
|
| 899 |
+
elif not vals["cup"]:
|
| 900 |
+
failure = "cup_fallen" if cup_fallen else "cup_not_on_top"
|
| 901 |
+
else:
|
| 902 |
+
failure = "not_static"
|
| 903 |
+
# F2 detail (robot-centric words)
|
| 904 |
+
parts = []
|
| 905 |
+
if success:
|
| 906 |
+
parts.append("All four boxes are stacked on the mat and the cup stands on top.")
|
| 907 |
+
else:
|
| 908 |
+
if ch:
|
| 909 |
+
parts.append("The pile on the mat is " + " / ".join(COL[b] for b in ch) + " (bottom to top).")
|
| 910 |
+
else:
|
| 911 |
+
parts.append("There is no box resting flat on the mat.")
|
| 912 |
+
mat = np.asarray(inst["mat"])
|
| 913 |
+
for b in BOXES:
|
| 914 |
+
if b in ch:
|
| 915 |
+
continue
|
| 916 |
+
c = COL[b]
|
| 917 |
+
if self.held(b):
|
| 918 |
+
parts.append(f"The {c} box is still held by the gripper.")
|
| 919 |
+
continue
|
| 920 |
+
off = self.centre(b)[:2] - mat
|
| 921 |
+
pose = ("lies tilted" if self.flat_tilt(b) > TILT_OK else
|
| 922 |
+
"is crushed flat" if self.crushed(b) > 0.15 else
|
| 923 |
+
f"is bent ({np.degrees(self.kink(b)):.0f} degrees)" if self.kink(b) > KINK_OK else "stands")
|
| 924 |
+
parts.append(f"The {c} box {pose} {_fb(off[0])} and {_lr(off[1])} of the mat's centre, not in the pile.")
|
| 925 |
+
if not vals["cup"]:
|
| 926 |
+
if self.held(CUP):
|
| 927 |
+
parts.append("The cup is still held by the gripper.")
|
| 928 |
+
elif cup_fallen:
|
| 929 |
+
parts.append("The cup has fallen over.")
|
| 930 |
+
else:
|
| 931 |
+
parts.append("The cup is not standing on top of a complete pile.")
|
| 932 |
+
if all(vals.values()):
|
| 933 |
+
if touching:
|
| 934 |
+
parts.append("The gripper is still touching the pile.")
|
| 935 |
+
elif not static:
|
| 936 |
+
parts.append("Something was still moving.")
|
| 937 |
+
loads = [e for e in buckles if e.get("cause") != "press"]
|
| 938 |
+
presses = [e for e in buckles if e.get("cause") == "press"]
|
| 939 |
+
if loads:
|
| 940 |
+
how = ("bent sideways or was crushed" if len({e.get("how") for e in loads}) > 1 else
|
| 941 |
+
"was crushed flat" if loads[0].get("how") == "crush" else "bent sideways")
|
| 942 |
+
parts.append(f"During the attempt the {loads[0]['box']} box {how} under the weight on it "
|
| 943 |
+
f"{len(loads)} time(s) and everything above it slid off.")
|
| 944 |
+
if presses:
|
| 945 |
+
parts.append(f"The {presses[0]['box']} box gave way {len(presses)} time(s) when the gripper pushed down "
|
| 946 |
+
f"on it.")
|
| 947 |
+
# trap fired = the carton gave way under what was put on it (or a giving-way cost a stage); a hard press by the
|
| 948 |
+
# gripper alone on an otherwise lightly loaded carton is logged (n_press_buckles) but is not the trap
|
| 949 |
+
trap = bool(loads) or int(mon["n_collapses"]) > 0
|
| 950 |
+
return dict(success=success, failure=failure, stages=vals, pile=[COL[b] for b in ch], events=ev,
|
| 951 |
+
n_regressions=int(n_reg), n_restored=int(n_res), trap_fired=trap,
|
| 952 |
+
recovered_in_attempt=bool(trap and success), n_buckles=len(buckles),
|
| 953 |
+
n_collapses=int(mon["n_collapses"]), buckle_levels=[e.get("level") for e in buckles],
|
| 954 |
+
buckle_loads_N=[e.get("load_N") for e in buckles], max_kink_deg=dict(mon["max_kink"]),
|
| 955 |
+
max_crush=dict(mon["max_crush"]), buckle_how=[e.get("how") for e in buckles],
|
| 956 |
+
buckle_causes=[e.get("cause") for e in buckles], n_press_buckles=len(presses),
|
| 957 |
+
max_height=int(mon["max_height"]), soft=inst["soft_colour"], benign=bool(inst["benign"]),
|
| 958 |
+
buckled_at_end=buckled_now, cup_fallen=bool(cup_fallen), held=held, touching=bool(touching),
|
| 959 |
+
static=bool(static), detail=" ".join(parts))
|
| 960 |
+
|
| 961 |
+
# ------------------------------------------------------------ scripted primitives (move_to + gripper only)
|
| 962 |
+
def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300):
|
| 963 |
+
return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
|
| 964 |
+
|
| 965 |
+
def _lift_to(self, z, speed=0.2):
|
| 966 |
+
cur = self.sk.eef_pos()
|
| 967 |
+
if cur[2] < z - 0.005:
|
| 968 |
+
self._go([cur[0], cur[1], z], speed=speed)
|
| 969 |
+
|
| 970 |
+
def _settle(self, steps=40):
|
| 971 |
+
"""hold until boxes / cup have stopped (max `steps` control steps)"""
|
| 972 |
+
p = self._static_pos()
|
| 973 |
+
for _ in range(steps // 4):
|
| 974 |
+
self.sk.hold(4)
|
| 975 |
+
q = self._static_pos()
|
| 976 |
+
if max(float(np.linalg.norm(q[x] - p[x])) for x in p) < 0.0005:
|
| 977 |
+
return
|
| 978 |
+
p = q
|
| 979 |
+
|
| 980 |
+
def settle_scene(self, max_steps=120):
|
| 981 |
+
"""after a collapse: wait (looking) until nothing moves and no box is visibly bent any more"""
|
| 982 |
+
for _ in range(max_steps // 10):
|
| 983 |
+
self._settle(10)
|
| 984 |
+
if all(self.kink(b) < np.radians(3.0) for b in BOXES):
|
| 985 |
+
p = self._static_pos()
|
| 986 |
+
self.sk.hold(4)
|
| 987 |
+
q = self._static_pos()
|
| 988 |
+
if max(float(np.linalg.norm(q[x] - p[x])) for x in p) < 0.0005:
|
| 989 |
+
return
|
| 990 |
+
|
| 991 |
+
def grasp_yaw(self, name):
|
| 992 |
+
"""wrist yaw that closes the fingers across a horizontal box axis: of the two, the one whose open fingers stay
|
| 993 |
+
clearest of the other objects (a box that fell against another one), then the one needing the least turn"""
|
| 994 |
+
if name == CUP:
|
| 995 |
+
return 0.0
|
| 996 |
+
R = self.R(self.base_bid[name])
|
| 997 |
+
up = int(np.argmax(np.abs(R[2, :])))
|
| 998 |
+
c = self.centre(name)[:2]
|
| 999 |
+
others = [self.centre(x)[:2] for x in BOXES + [CUP] if x != name]
|
| 1000 |
+
best = None
|
| 1001 |
+
for a in range(3):
|
| 1002 |
+
if a == up:
|
| 1003 |
+
continue
|
| 1004 |
+
v = R[:2, a] / max(np.linalg.norm(R[:2, a]), 1e-9)
|
| 1005 |
+
yaw = _wrap_q(float(np.arctan2(v[1], v[0])) - np.pi / 2, np.pi) # fingers close along (-sin yaw, cos yaw)
|
| 1006 |
+
fingers = [c + s_ * 0.045 * v for s_ in (1.0, -1.0)] # open fingers ~4.5 cm from the centre
|
| 1007 |
+
clear = min([float(np.linalg.norm(f - o)) for f in fingers for o in others] + [1.0])
|
| 1008 |
+
key = (round(min(clear, 0.05), 3), -abs(yaw))
|
| 1009 |
+
if best is None or key > best[0]:
|
| 1010 |
+
best = (key, yaw)
|
| 1011 |
+
return best[1]
|
| 1012 |
+
|
| 1013 |
+
def z_clear(self, extra=0.08):
|
| 1014 |
+
"""carry height: above everything on the table"""
|
| 1015 |
+
top = max(envs.obj_max_z(self.env, x) for x in BOXES + [CUP])
|
| 1016 |
+
return max(TZ + Z_CARRY, top + extra)
|
| 1017 |
+
|
| 1018 |
+
def pick(self, name, depth=0.018, z_carry=None, tries=2):
|
| 1019 |
+
sk = self.sk
|
| 1020 |
+
for _ in range(tries):
|
| 1021 |
+
self._settle(20)
|
| 1022 |
+
p = self.centre(name)
|
| 1023 |
+
zt = envs.obj_max_z(self.env, name)
|
| 1024 |
+
yaw = self.grasp_yaw(name)
|
| 1025 |
+
sk.set_gripper(False, steps=10)
|
| 1026 |
+
zc = z_carry or self.z_clear()
|
| 1027 |
+
self._lift_to(zc)
|
| 1028 |
+
self._go([p[0], p[1], zc], yaw=yaw, speed=0.25)
|
| 1029 |
+
self._go([p[0], p[1], zt - depth + 0.02], speed=0.12)
|
| 1030 |
+
self._go([p[0], p[1], max(zt - depth, TZ + 0.012)], speed=0.04, tol=0.003, max_steps=150)
|
| 1031 |
+
sk.set_gripper(True, steps=15)
|
| 1032 |
+
self._go([p[0], p[1], self.z_clear(0.10)], speed=0.15)
|
| 1033 |
+
if self.held(name):
|
| 1034 |
+
return True
|
| 1035 |
+
sk.set_gripper(False, steps=10)
|
| 1036 |
+
return False
|
| 1037 |
+
|
| 1038 |
+
def put(self, name, xy, z_surface, gap, yaw=0.0):
|
| 1039 |
+
"""carry the held object over xy (its centre), straight down until its bottom is `gap` above z_surface, let
|
| 1040 |
+
go, lift 8 cm"""
|
| 1041 |
+
sk = self.sk
|
| 1042 |
+
zc = max(self.z_clear(0.10), sk.eef_pos()[2])
|
| 1043 |
+
rel = self.centre(name)[:2] - sk.eef_pos()[:2]
|
| 1044 |
+
q = np.asarray(xy, float) - rel
|
| 1045 |
+
self._go([q[0], q[1], zc], yaw=yaw, speed=0.25)
|
| 1046 |
+
sk.hold(5)
|
| 1047 |
+
rel = self.centre(name)[:2] - sk.eef_pos()[:2] # the object can shift in the fingers while the wrist turns
|
| 1048 |
+
q = np.asarray(xy, float) - rel
|
| 1049 |
+
dz = sk.eef_pos()[2] - envs.obj_min_z(self.env, name)
|
| 1050 |
+
zr = z_surface + dz + gap
|
| 1051 |
+
self._go([q[0], q[1], zr + 0.03], speed=0.12)
|
| 1052 |
+
self._go([q[0], q[1], zr], speed=0.04, tol=0.003, max_steps=150)
|
| 1053 |
+
sk.set_gripper(False, steps=15)
|
| 1054 |
+
cur = sk.eef_pos()
|
| 1055 |
+
self._go([cur[0], cur[1], cur[2] + 0.08], speed=0.15)
|
| 1056 |
+
self._settle(40)
|
| 1057 |
+
|
| 1058 |
+
def free_spot(self, near_xy):
|
| 1059 |
+
"""a free place on the table (for a box taken off the pile): >= 11 cm from everything, off the mat, reachable"""
|
| 1060 |
+
mat = np.asarray(self.inst["mat"])
|
| 1061 |
+
others = [self.centre(x)[:2] for x in BOXES + [CUP]]
|
| 1062 |
+
best, bd = None, -1.0
|
| 1063 |
+
for r in (0.17, 0.21, 0.25, 0.29):
|
| 1064 |
+
for a in np.radians(np.arange(0, 360, 15)):
|
| 1065 |
+
p = mat + r * np.array([np.cos(a), np.sin(a)])
|
| 1066 |
+
if not (BOX_X[0] - 0.02 <= p[0] <= BOX_X[1] and abs(p[1]) <= BOX_YMAX + 0.02):
|
| 1067 |
+
continue
|
| 1068 |
+
d = min(float(np.linalg.norm(p - o)) for o in others)
|
| 1069 |
+
if d >= 0.11:
|
| 1070 |
+
return p
|
| 1071 |
+
if d > bd:
|
| 1072 |
+
best, bd = p, d
|
| 1073 |
+
return best
|
| 1074 |
+
|
| 1075 |
+
def place_on_pile(self, name, err, gap, rng, bias=0.0):
|
| 1076 |
+
"""put object `name` on the current pile top (or the mat) with a placement error of `err` (m, random direction)"""
|
| 1077 |
+
ch = [b for b in self.pile() if b != name]
|
| 1078 |
+
if ch:
|
| 1079 |
+
# aims every box at the same spot (the bottom box), as an agent that computes the pile's x, y once: errors
|
| 1080 |
+
# do not add up level by level
|
| 1081 |
+
tgt = self.centre(ch[0])[:2].copy()
|
| 1082 |
+
zs = envs.obj_max_z(self.env, ch[-1])
|
| 1083 |
+
else:
|
| 1084 |
+
tgt = np.asarray(self.inst["mat"], float) + np.array([bias, 0.0])
|
| 1085 |
+
zs = TZ
|
| 1086 |
+
if err:
|
| 1087 |
+
a = rng.uniform(0, 2 * np.pi)
|
| 1088 |
+
tgt = tgt + float(err) * np.array([np.cos(a), np.sin(a)])
|
| 1089 |
+
if not self.pick(name):
|
| 1090 |
+
return False
|
| 1091 |
+
self.put(name, tgt, zs, gap)
|
| 1092 |
+
return True
|
| 1093 |
+
|
| 1094 |
+
def lay_aside(self, name, rng):
|
| 1095 |
+
if not self.pick(name):
|
| 1096 |
+
return False
|
| 1097 |
+
p = self.free_spot(self.centre(name)[:2])
|
| 1098 |
+
self.put(name, p, TZ, 0.01)
|
| 1099 |
+
return True
|
| 1100 |
+
|
| 1101 |
+
# ------------------------------------------------------------ scripted policies
|
| 1102 |
+
def nearest_order(self):
|
| 1103 |
+
mat = np.asarray(self.inst["mat"])
|
| 1104 |
+
return sorted(BOXES, key=lambda b: float(np.linalg.norm(self.centre(b)[:2] - mat)))
|
| 1105 |
+
|
| 1106 |
+
def plan(self, params, rng):
|
| 1107 |
+
if params.get("order") == "random":
|
| 1108 |
+
order = [BOXES[i] for i in rng.permutation(4)]
|
| 1109 |
+
else:
|
| 1110 |
+
order = self.nearest_order()
|
| 1111 |
+
soft = params.get("soft_known")
|
| 1112 |
+
if soft:
|
| 1113 |
+
order = [b for b in order if COL[b] != soft] + [b for b in order if COL[b] == soft]
|
| 1114 |
+
return order
|
| 1115 |
+
|
| 1116 |
+
def seen_soft(self):
|
| 1117 |
+
"""the box that visibly bent during this attempt (scripted perception of the kink in the images)"""
|
| 1118 |
+
mk, mc = self.mon["max_kink"], self.mon["max_crush"]
|
| 1119 |
+
for c in COLOURS:
|
| 1120 |
+
if mk[c] > 15.0 or mc[c] > 0.3:
|
| 1121 |
+
return c
|
| 1122 |
+
return None
|
| 1123 |
+
|
| 1124 |
+
def build(self, order, params, rng, first=True):
|
| 1125 |
+
"""stack `order` (boxes not yet in the pile) then the cup; returns 'ok', 'collapse' or 'fail'"""
|
| 1126 |
+
err = params.get("err")
|
| 1127 |
+
gap = params.get("gap", 0.005)
|
| 1128 |
+
# a box that could not be picked up is tried again after the others (one more pass)
|
| 1129 |
+
order = list(order) * 2
|
| 1130 |
+
for b in order:
|
| 1131 |
+
if b in self.pile():
|
| 1132 |
+
continue
|
| 1133 |
+
if params.get("soft_known") and COL[b] == params["soft_known"] and \
|
| 1134 |
+
sum(x in self.pile() for x in BOXES if COL[x] != params["soft_known"]) < len(BOXES) - 1:
|
| 1135 |
+
continue # the soft box only goes on once the three others are in the pile
|
| 1136 |
+
for _ in range(2):
|
| 1137 |
+
n_b = len(self.mon["buckle_steps"])
|
| 1138 |
+
before = self.pile()
|
| 1139 |
+
e = rng.uniform(*err) if err else 0.0
|
| 1140 |
+
if not self.place_on_pile(b, e, gap, rng, bias=params.get("bias", 0.0) if not before else 0.0):
|
| 1141 |
+
break
|
| 1142 |
+
after = self.pile()
|
| 1143 |
+
if len(self.mon["buckle_steps"]) > n_b or any(x not in after for x in before):
|
| 1144 |
+
return "collapse"
|
| 1145 |
+
if b in after:
|
| 1146 |
+
break
|
| 1147 |
+
if len(self.pile()) < len(BOXES):
|
| 1148 |
+
return "fail"
|
| 1149 |
+
if self.cup_tilt() > np.radians(45):
|
| 1150 |
+
return "fail"
|
| 1151 |
+
for _ in range(2):
|
| 1152 |
+
n_b = len(self.mon["buckle_steps"])
|
| 1153 |
+
before = self.pile()
|
| 1154 |
+
e = rng.uniform(*err) if err else 0.0
|
| 1155 |
+
if not self.place_on_pile(CUP, e, gap, rng):
|
| 1156 |
+
return "fail"
|
| 1157 |
+
if len(self.mon["buckle_steps"]) > n_b or any(x not in self.pile() for x in before):
|
| 1158 |
+
return "collapse"
|
| 1159 |
+
if self.cup_on_pile():
|
| 1160 |
+
return "ok"
|
| 1161 |
+
return "fail"
|
| 1162 |
+
|
| 1163 |
+
def rebuild_soft_top(self, soft_colour, params, rng):
|
| 1164 |
+
"""take the soft box (and whatever is on it) off the pile, then stack the rigid boxes and the soft one last"""
|
| 1165 |
+
soft = BOXES[COLOURS.index(soft_colour)]
|
| 1166 |
+
for _ in range(6):
|
| 1167 |
+
ch = self.pile()
|
| 1168 |
+
if soft in ch:
|
| 1169 |
+
self.lay_aside(ch[-1], rng) # from the top down to the soft box
|
| 1170 |
+
elif self.on_mat(soft) or any(soft in self.items_on(b) for b in ch):
|
| 1171 |
+
self.lay_aside(soft, rng) # bent / off-centre on the mat or on the pile
|
| 1172 |
+
else:
|
| 1173 |
+
break
|
| 1174 |
+
order = [b for b in self.nearest_order() if b != soft] + [soft]
|
| 1175 |
+
return self.build(order, dict(params, soft_known=soft_colour), rng)
|
| 1176 |
+
|
| 1177 |
+
def execute(self, inst, params):
|
| 1178 |
+
rng = np.random.default_rng(params.get("noise_seed", 0))
|
| 1179 |
+
order = self.plan(params, rng)
|
| 1180 |
+
res = self.build(order, params, rng)
|
| 1181 |
+
if res == "collapse":
|
| 1182 |
+
mode = params.get("on_collapse", "rebuild_same")
|
| 1183 |
+
if mode == "rebuild_same": # the cheapest explanation: "I did not centre it" -> same order, more care
|
| 1184 |
+
self.settle_scene()
|
| 1185 |
+
res = self.build(order, dict(params, err=None, gap=0.005), rng)
|
| 1186 |
+
elif mode == "identify": # sees which box bent and rebuilds with it on top
|
| 1187 |
+
self.settle_scene()
|
| 1188 |
+
soft = self.seen_soft()
|
| 1189 |
+
if soft and self.cup_tilt() < np.radians(45):
|
| 1190 |
+
res = self.rebuild_soft_top(soft, params, rng)
|
| 1191 |
+
self._lift_to(self.z_clear(0.06))
|
| 1192 |
+
self.sk.hold(10)
|
| 1193 |
+
return res
|
| 1194 |
+
|
| 1195 |
+
NAIVE = dict(order="nearest", soft_known=None, on_collapse="rebuild_same")
|
| 1196 |
+
|
| 1197 |
+
def default_params(self, inst):
|
| 1198 |
+
"""Sonnet-like: nearest box first, lifts above everything, straight down, lets go 1-4 cm above (per instance),
|
| 1199 |
+
0.4-1.3 cm placement errors, the first box up to 2 cm too far forward; after a collapse it rebuilds once in
|
| 1200 |
+
the same order, more carefully"""
|
| 1201 |
+
return dict(self.NAIVE, noise_seed=int(inst["seed"]) * 13, err=NAIVE_ERR, gap=float(inst["naive_gap"]),
|
| 1202 |
+
bias=float(inst["naive_bias"]))
|
| 1203 |
+
|
| 1204 |
+
def oracle_params(self, inst):
|
| 1205 |
+
return dict(order="nearest", soft_known=inst["soft_colour"], on_collapse="identify", err=None, gap=0.005)
|
| 1206 |
+
|
| 1207 |
+
def adapt_params(self, inst, history):
|
| 1208 |
+
soft = None
|
| 1209 |
+
for h in history:
|
| 1210 |
+
ev = [e for e in h["outcome"]["events"] if e.get("event") == "buckle"]
|
| 1211 |
+
if ev:
|
| 1212 |
+
soft = ev[0]["box"] # the box seen bending (the kink is visible in the images)
|
| 1213 |
+
return dict(self.default_params(inst), soft_known=soft, on_collapse="identify")
|
| 1214 |
+
|
| 1215 |
+
def blind_params(self, inst, attempt, rng):
|
| 1216 |
+
return dict(self.default_params(inst), order="random", noise_seed=int(rng.integers(1 << 30)),
|
| 1217 |
+
gap=float(rng.uniform(*NAIVE_GAP)), bias=float(rng.uniform(*NAIVE_BIAS)))
|
| 1218 |
+
|
| 1219 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 1220 |
+
k = k or self.max_attempts
|
| 1221 |
+
rng = np.random.default_rng(seed)
|
| 1222 |
+
history = []
|
| 1223 |
+
single = ("oracle", "naive", "naive_centred", "oracle_noise", "naive_once", "naive_lying", "oracle_lying")
|
| 1224 |
+
if kind in ("naive_lying", "oracle_lying") and inst["soft"]:
|
| 1225 |
+
# control (v2): the soft carton starts lying on a side face, so it is stacked lying
|
| 1226 |
+
inst = dict(inst, lying={inst["soft_colour"]: np.pi / 2})
|
| 1227 |
+
for a in range(k):
|
| 1228 |
+
self.reset_instance(inst)
|
| 1229 |
+
if kind == "oracle":
|
| 1230 |
+
params = self.oracle_params(inst)
|
| 1231 |
+
elif kind == "naive":
|
| 1232 |
+
params = self.default_params(inst)
|
| 1233 |
+
elif kind == "adaptive": # attempt 1: naive habits, but it looks at the collapse and rebuilds soft-on-top
|
| 1234 |
+
params = (dict(self.default_params(inst), on_collapse="identify") if a == 0
|
| 1235 |
+
else self.adapt_params(inst, history))
|
| 1236 |
+
elif kind == "blind":
|
| 1237 |
+
params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
|
| 1238 |
+
elif kind == "switch": # control: cross-attempt learning only (no within-attempt identification)
|
| 1239 |
+
params = self.default_params(inst) if a == 0 else dict(self.adapt_params(inst, history),
|
| 1240 |
+
on_collapse="rebuild_same")
|
| 1241 |
+
elif kind == "naive_centred": # control (R4): perfect centring, let go 5 mm above, no rebuild
|
| 1242 |
+
params = dict(self.default_params(inst), err=None, gap=0.005, bias=0.0, on_collapse="none")
|
| 1243 |
+
elif kind == "naive_once": # control: naive without the careful rebuild
|
| 1244 |
+
params = dict(self.default_params(inst), on_collapse="none")
|
| 1245 |
+
elif kind == "naive_lying": # control (v2): naive_once with the soft carton lying on a side face
|
| 1246 |
+
params = dict(self.default_params(inst), on_collapse="none")
|
| 1247 |
+
elif kind == "oracle_lying": # control (v2): soft carton lying, but on top (carries only the cup)
|
| 1248 |
+
params = dict(self.oracle_params(inst))
|
| 1249 |
+
elif kind == "oracle_noise": # robustness: soft box on top with Sonnet-like imprecision
|
| 1250 |
+
params = dict(self.default_params(inst), soft_known=inst["soft_colour"], on_collapse="identify")
|
| 1251 |
+
else:
|
| 1252 |
+
raise ValueError(kind)
|
| 1253 |
+
self.execute(inst, params)
|
| 1254 |
+
out = self.outcome(inst)
|
| 1255 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 1256 |
+
if on_attempt:
|
| 1257 |
+
on_attempt(a, params, out)
|
| 1258 |
+
if out["success"] or kind in single:
|
| 1259 |
+
break
|
| 1260 |
+
return history
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/audit_subagent.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Audit an isolated policy subagent: every tool call it made must stay inside its sandbox.
|
| 2 |
+
|
| 3 |
+
python scripts/audit_subagent.py <transcript.jsonl> <sandbox_dir> [--out audit.json]
|
| 4 |
+
Allowed: Bash `cd <sandbox> && ./robot ...` (or `<sandbox>/robot ...`); Read of <sandbox>/README.md or <sandbox>/obs/*.
|
| 5 |
+
With --la (LIBERO-Agent-style workspace): also Bash `cd <sandbox> && ./shell '<cmd>'` / `./shell <<'TAG' ... TAG` (the
|
| 6 |
+
command runs inside the jail; anything the OUTER shell would execute or expand is a violation), and Read / Write / Edit
|
| 7 |
+
of any file inside <sandbox>.
|
| 8 |
+
Everything else is reported as a violation. Prints counts + violations only (the transcript itself is large).
|
| 9 |
+
"""
|
| 10 |
+
import argparse
|
| 11 |
+
import json
|
| 12 |
+
import re
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def tool_uses(obj):
|
| 16 |
+
if isinstance(obj, dict):
|
| 17 |
+
if obj.get("type") == "tool_use" and "name" in obj:
|
| 18 |
+
yield obj
|
| 19 |
+
for v in obj.values():
|
| 20 |
+
yield from tool_uses(v)
|
| 21 |
+
elif isinstance(obj, list):
|
| 22 |
+
for v in obj:
|
| 23 |
+
yield from tool_uses(v)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def extra_shell_ops(cmd, sb):
|
| 27 |
+
"""True if the command contains shell operators / substitutions outside quotes, apart from the
|
| 28 |
+
allowed leading `cd <sandbox> &&`."""
|
| 29 |
+
import shlex
|
| 30 |
+
body = re.sub(r"^\s*cd\s+%s\s*&&\s*" % re.escape(sb), "", cmd)
|
| 31 |
+
if "`" in body or "$(" in body:
|
| 32 |
+
return True
|
| 33 |
+
try:
|
| 34 |
+
lex = shlex.shlex(body, posix=True, punctuation_chars=True)
|
| 35 |
+
toks = list(lex)
|
| 36 |
+
except ValueError:
|
| 37 |
+
return True
|
| 38 |
+
return any(t in (";", "&&", "||", "|", "&", ">", ">>", "<") for t in toks)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def shell_call_ok(cmd, sb):
|
| 42 |
+
"""la: `cd <sb> && ./shell ...` where nothing runs outside the jail: either one heredoc with a QUOTED tag (no outer
|
| 43 |
+
expansion) and nothing after it, or plain arguments without outer operators / substitutions."""
|
| 44 |
+
m = re.match(r"^\s*cd\s+%s\s*&&\s*(\./shell|%s/shell)(.*)$" % (re.escape(sb), re.escape(sb)), cmd, re.S)
|
| 45 |
+
if not m:
|
| 46 |
+
return False
|
| 47 |
+
rest = m.group(2)
|
| 48 |
+
s = rest.strip()
|
| 49 |
+
if rest[:1].isspace() and len(s) >= 2 and s[0] == "'" and s[-1] == "'" and "'" not in s[1:-1]:
|
| 50 |
+
return True # one single-quoted argument: the outer shell expands nothing (an inner `<<EOF` runs in the jail)
|
| 51 |
+
if "<<" in rest:
|
| 52 |
+
first, _, body = rest.partition("\n")
|
| 53 |
+
hm = re.match(r"^\s*<<-?\s*(['\"])(\w+)\1\s*$", first)
|
| 54 |
+
if not hm:
|
| 55 |
+
return False # unquoted tag: the outer shell would expand $(...) inside the heredoc
|
| 56 |
+
tag = hm.group(2)
|
| 57 |
+
lines = body.rstrip("\n").split("\n")
|
| 58 |
+
return bool(lines) and lines[-1].strip() == tag and tag not in [l.strip() for l in lines[:-1]]
|
| 59 |
+
if "`" in rest or "$(" in rest.replace("'", "\x00").split("\x00")[0::2].__str__():
|
| 60 |
+
return False
|
| 61 |
+
import shlex
|
| 62 |
+
try:
|
| 63 |
+
toks = list(shlex.shlex(rest, posix=True, punctuation_chars=True))
|
| 64 |
+
except ValueError:
|
| 65 |
+
return False
|
| 66 |
+
return not any(t in (";", "&&", "||", "|", "&", ">", ">>", "<") for t in toks)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def main():
|
| 70 |
+
ap = argparse.ArgumentParser()
|
| 71 |
+
ap.add_argument("transcript")
|
| 72 |
+
ap.add_argument("sandbox")
|
| 73 |
+
ap.add_argument("--out")
|
| 74 |
+
ap.add_argument("--la", action="store_true", help="LIBERO-Agent-style workspace: ./shell and workspace files allowed")
|
| 75 |
+
a = ap.parse_args()
|
| 76 |
+
sb = a.sandbox.rstrip("/")
|
| 77 |
+
ok_bash = re.compile(r"^\s*(cd\s+%s\s*&&\s*)?(\./robot|%s/robot)(\s|$)" % (re.escape(sb), re.escape(sb)))
|
| 78 |
+
seen, calls, viol = set(), [], []
|
| 79 |
+
injected = [] # context Claude Code attached on its own: the user's memory index / identity
|
| 80 |
+
with open(a.transcript) as f:
|
| 81 |
+
for line in f:
|
| 82 |
+
try:
|
| 83 |
+
rec = json.loads(line)
|
| 84 |
+
except ValueError:
|
| 85 |
+
continue
|
| 86 |
+
if rec.get("type") == "attachment":
|
| 87 |
+
at = rec.get("attachment", {})
|
| 88 |
+
if at.get("type") == "instructions":
|
| 89 |
+
for fi in at.get("files", []):
|
| 90 |
+
if "memory" in (fi.get("path") or "").lower() or fi.get("type") == "AutoMem":
|
| 91 |
+
injected.append(dict(kind="memory_index", path=fi.get("path"), chars=len(fi.get("content", ""))))
|
| 92 |
+
elif at.get("type") == "session_context":
|
| 93 |
+
injected.append(dict(kind="session_context", keys=sorted((at.get("context") or {}).keys())))
|
| 94 |
+
for tu in tool_uses(rec):
|
| 95 |
+
if tu.get("id") in seen:
|
| 96 |
+
continue
|
| 97 |
+
seen.add(tu.get("id"))
|
| 98 |
+
name, inp = tu["name"], tu.get("input", {})
|
| 99 |
+
calls.append(name)
|
| 100 |
+
if name == "SubagentHandback": # the final report back to the orchestrator
|
| 101 |
+
continue
|
| 102 |
+
if name == "Bash":
|
| 103 |
+
cmd = inp.get("command", "")
|
| 104 |
+
bad = (not ok_bash.match(cmd)) or extra_shell_ops(cmd, sb)
|
| 105 |
+
if bad and a.la and shell_call_ok(cmd, sb):
|
| 106 |
+
bad = False
|
| 107 |
+
if bad:
|
| 108 |
+
viol.append(dict(tool=name, command=cmd))
|
| 109 |
+
elif name in ("Read", "Write", "Edit") and a.la:
|
| 110 |
+
import os
|
| 111 |
+
p = os.path.normpath(inp.get("file_path", ""))
|
| 112 |
+
if not p.startswith(sb + "/"):
|
| 113 |
+
viol.append(dict(tool=name, path=inp.get("file_path", "")))
|
| 114 |
+
elif name == "Read":
|
| 115 |
+
p = inp.get("file_path", "")
|
| 116 |
+
if not (p == f"{sb}/README.md" or p.startswith(f"{sb}/obs/")):
|
| 117 |
+
viol.append(dict(tool=name, path=p))
|
| 118 |
+
else:
|
| 119 |
+
viol.append(dict(tool=name, input=json.dumps(inp)[:300]))
|
| 120 |
+
from collections import Counter
|
| 121 |
+
res = dict(n_calls=len(calls), by_tool=dict(Counter(calls)), n_violations=len(viol), violations=viol,
|
| 122 |
+
memory_injected=any(i["kind"] == "memory_index" for i in injected), injected=injected)
|
| 123 |
+
print(json.dumps(res, indent=1, ensure_ascii=False))
|
| 124 |
+
if a.out:
|
| 125 |
+
with open(a.out, "w") as f:
|
| 126 |
+
json.dump(res, f, indent=1, ensure_ascii=False)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
if __name__ == "__main__":
|
| 130 |
+
main()
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/start_real_session.sh
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Start a REAL-robot server (lffbench/real/session.py) + workspace for one task instance; same output as
|
| 3 |
+
# scripts/start_robot_session.sh (SANDBOX=, LOG=, <LOG>/session.json), so harness_run.py / api_player.py run on it unchanged.
|
| 4 |
+
# usage: scripts/start_real_session.sh <task> <seed> <memory full|none> <feedback F0|F1> <port> [instruction direct|indirect] [k] [tag]
|
| 5 |
+
# The driver: $LFF_REAL_DRIVER (default http://127.0.0.1:9900, normally an SSH tunnel to the robot PC) and $LFF_DRIVER_TOKEN.
|
| 6 |
+
# Blocks until the operator has set up the scene for attempt 1 (up to $LFF_REAL_READY_WAIT s, default 3600).
|
| 7 |
+
set -e
|
| 8 |
+
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
| 9 |
+
TASK=$1; SEED=$2; MEM=$3; FB=$4; PORT=$5; INSTR=${6:-direct}; K=${7:-}; TAG=${8:-}
|
| 10 |
+
RUN=${TAG:+${TAG}_}${TASK}_s${SEED}_${MEM}_${FB}_${INSTR}_k${K:-d}_$(date +%m%d-%H%M%S)_p${PORT}
|
| 11 |
+
SANDBOX=${LFF_SANDBOX_ROOT:-/tmp/robotlab}/$(python3 -c 'import secrets;print(secrets.token_hex(6))')
|
| 12 |
+
LOG=${LFF_RUNS_DIR:-$ROOT/runs/real}/$RUN
|
| 13 |
+
mkdir -p "$SANDBOX" "$LOG"
|
| 14 |
+
cd "$ROOT" && source run_env.sh && export OMP_NUM_THREADS=1
|
| 15 |
+
KARG=""; [ -n "$K" ] && KARG="--k $K"
|
| 16 |
+
nohup python -m lffbench.real.session --task "$TASK" --seed "$SEED" --memory "$MEM" --feedback "$FB" \
|
| 17 |
+
--instruction "$INSTR" --port "$PORT" --sandbox "$SANDBOX" --log-dir "$LOG" --run-name "$RUN" ${LFF_EXTRA_ARGS:-} $KARG \
|
| 18 |
+
> "$LOG/server.log" 2>&1 &
|
| 19 |
+
echo $! > "$LOG/server.pid"
|
| 20 |
+
WAIT=${LFF_REAL_READY_WAIT:-3600}
|
| 21 |
+
for i in $(seq 1 "$WAIT"); do
|
| 22 |
+
[ -f "$LOG/READY" ] && break
|
| 23 |
+
kill -0 "$(cat "$LOG/server.pid")" 2>/dev/null || break
|
| 24 |
+
[ $((i % 30)) -eq 0 ] && echo "waiting for the operator to set up the scene ($i s)" >&2
|
| 25 |
+
sleep 1
|
| 26 |
+
done
|
| 27 |
+
[ -f "$LOG/READY" ] || { echo "server failed"; tail -20 "$LOG/server.log"; exit 1; }
|
| 28 |
+
echo "{\"run\": \"$RUN\", \"sandbox\": \"$SANDBOX\", \"port\": $PORT}" > "$LOG/session.json"
|
| 29 |
+
echo "SANDBOX=$SANDBOX"
|
| 30 |
+
echo "LOG=$LOG"
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/MANIFEST.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LFF benchmark replay supplement: clh_20261102_gpt
|
| 2 |
+
|
| 3 |
+
Source: completed evaluation runs in /mnt/cpfs/workspace/agentic-robotics/ops/compound_lh_eval_20261102/source/runs/api/clh_20261102_gpt.
|
| 4 |
+
Immutable inventory and frozen matching source: /mnt/cpfs/workspace/agentic-robotics/ops/compound_lh_eval_20261102/inventory.json.
|
| 5 |
+
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).
|
| 6 |
+
LeRobot v3, 20 Hz, Franka Panda simulation, two 256x256 cameras.
|
| 7 |
+
Contains 18 runs, 27 episodes, 104451 frames; 2470242145 bytes before manifest.
|
| 8 |
+
Success and failure episodes retained; supplemental/ablation batches retain their original condition and dossier metadata.
|
| 9 |
+
All admitted runs pass server-code hash, instance, robot-report and outcome replay checks.
|
| 10 |
+
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"}.
|
| 11 |
+
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.
|
| 12 |
+
Incremental supplement only. Earlier versions remain unchanged. Development smoke/debug/pilot runs excluded.
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/evaluation_evidence/inactive_arm_review_20261115.json
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"created_utc": "2026-11-15T06:37:56.538868+00:00",
|
| 3 |
+
"reviews": [
|
| 4 |
+
{
|
| 5 |
+
"task": "lh_clear_cover",
|
| 6 |
+
"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",
|
| 7 |
+
"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",
|
| 8 |
+
"exact_contract_match": false,
|
| 9 |
+
"semantic_match": true,
|
| 10 |
+
"reason": "Only pinned unused intervention-text file added to hash inventory; arm none, session_start identical except time, all existing source hashes identical"
|
| 11 |
+
},
|
| 12 |
+
{
|
| 13 |
+
"task": "lh_tidy_stack",
|
| 14 |
+
"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",
|
| 15 |
+
"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",
|
| 16 |
+
"exact_contract_match": false,
|
| 17 |
+
"semantic_match": true,
|
| 18 |
+
"reason": "Only pinned unused intervention-text file added to hash inventory; arm none, session_start identical except time, all existing source hashes identical"
|
| 19 |
+
}
|
| 20 |
+
],
|
| 21 |
+
"negative_checks": [
|
| 22 |
+
"changed budget rejected",
|
| 23 |
+
"active intervention rejected"
|
| 24 |
+
],
|
| 25 |
+
"all_original_raw_contracts_preserved": true
|
| 26 |
+
}
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/agent/camera.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Camera geometry for the agent tools: pixel -> world back-projection with the rendered depth map.
|
| 2 |
+
|
| 3 |
+
Conventions (match the images the agent receives, i.e. `envs.render`, which flips MuJoCo's
|
| 4 |
+
bottom-up buffer to an upright image):
|
| 5 |
+
u = column index (0 = left edge), v = row index (0 = top edge), both in pixels of a res x res image.
|
| 6 |
+
Intrinsics / extrinsics / depth linearisation come from robosuite.utils.camera_utils.
|
| 7 |
+
"""
|
| 8 |
+
import numpy as np
|
| 9 |
+
from robosuite.utils import camera_utils as CU
|
| 10 |
+
|
| 11 |
+
from .. import envs
|
| 12 |
+
|
| 13 |
+
# agent-facing camera name -> MuJoCo camera name
|
| 14 |
+
CAMERAS = {"agentview": "agentview", "wrist": "robot0_eye_in_hand"}
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def mj_cam(name):
|
| 18 |
+
if name in CAMERAS:
|
| 19 |
+
return CAMERAS[name]
|
| 20 |
+
if name in CAMERAS.values():
|
| 21 |
+
return name
|
| 22 |
+
raise KeyError(f"unknown camera {name!r}; use one of {sorted(CAMERAS)}")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def intrinsics(env, cam, res):
|
| 26 |
+
return CU.get_camera_intrinsic_matrix(env.sim, mj_cam(cam), res, res)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def cam_to_world(env, cam):
|
| 30 |
+
"""4x4 pose of the camera in the world, OpenCV axes (x right, y down, z forward)."""
|
| 31 |
+
return CU.get_camera_extrinsic_matrix(env.sim, mj_cam(cam))
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def render_depth(env, cam, res):
|
| 35 |
+
"""Metric depth (distance along the optical axis, metres), upright (res, res)."""
|
| 36 |
+
_, d = envs.render(env, mj_cam(cam), res, depth=True)
|
| 37 |
+
return CU.get_real_depth_map(env.sim, np.clip(d, 0.0, 1.0))
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def world_to_pixel(env, cam, xyz, res):
|
| 41 |
+
"""Project a world point; returns (u, v) floats (u = column, v = row) and the depth."""
|
| 42 |
+
K = intrinsics(env, cam, res)
|
| 43 |
+
T = np.linalg.inv(cam_to_world(env, cam))
|
| 44 |
+
p = T @ np.append(np.asarray(xyz, float), 1.0)
|
| 45 |
+
uvw = K @ p[:3]
|
| 46 |
+
return float(uvw[0] / uvw[2]), float(uvw[1] / uvw[2]), float(p[2])
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def pixel_ray(env, cam, u, v, res):
|
| 50 |
+
"""Unit ray direction (world) through pixel (u, v) and the camera origin."""
|
| 51 |
+
K = intrinsics(env, cam, res)
|
| 52 |
+
E = cam_to_world(env, cam)
|
| 53 |
+
d_cam = np.array([(u - K[0, 2]) / K[0, 0], (v - K[1, 2]) / K[1, 1], 1.0])
|
| 54 |
+
d = E[:3, :3] @ d_cam
|
| 55 |
+
return E[:3, 3].copy(), d / np.linalg.norm(d)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def pixel_to_world(env, cam, u, v, res, depth=None):
|
| 59 |
+
"""Back-project pixel (u, v) of a res x res image using the depth map. Returns a dict."""
|
| 60 |
+
if depth is None:
|
| 61 |
+
depth = render_depth(env, cam, res)
|
| 62 |
+
iu, iv = int(round(u)), int(round(v))
|
| 63 |
+
if not (0 <= iu < res and 0 <= iv < res):
|
| 64 |
+
raise ValueError(f"pixel ({u}, {v}) outside the {res}x{res} image")
|
| 65 |
+
z = float(depth[iv, iu])
|
| 66 |
+
K = intrinsics(env, cam, res)
|
| 67 |
+
E = cam_to_world(env, cam)
|
| 68 |
+
p_cam = np.array([(u - K[0, 2]) * z / K[0, 0], (v - K[1, 2]) * z / K[1, 1], z, 1.0])
|
| 69 |
+
p = E @ p_cam
|
| 70 |
+
far = env.sim.model.vis.map.zfar * env.sim.model.stat.extent
|
| 71 |
+
return dict(xyz=p[:3], depth=z, valid=bool(z < 0.98 * far))
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def image_axes(env, cam, res, plane_z=envs.TABLE_Z):
|
| 75 |
+
"""World directions of image-right and image-down at the image centre, projected onto the table
|
| 76 |
+
plane (for describing the camera to the agent). Returns two unit 2-vectors (x, y)."""
|
| 77 |
+
o, d = pixel_ray(env, cam, res / 2, res / 2, res)
|
| 78 |
+
if abs(d[2]) < 1e-6:
|
| 79 |
+
return None
|
| 80 |
+
t = (plane_z - o[2]) / d[2]
|
| 81 |
+
c = o + t * d
|
| 82 |
+
out = []
|
| 83 |
+
for du, dv in ((8, 0), (0, 8)):
|
| 84 |
+
o2, d2 = pixel_ray(env, cam, res / 2 + du, res / 2 + dv, res)
|
| 85 |
+
t2 = (plane_z - o2[2]) / d2[2]
|
| 86 |
+
w = (o2 + t2 * d2 - c)[:2]
|
| 87 |
+
out.append(w / max(np.linalg.norm(w), 1e-9))
|
| 88 |
+
return out
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def describe_axes(env, cam, res):
|
| 92 |
+
"""Human-readable mapping 'image right ~ +y, image down ~ +x' (dominant axis, sign)."""
|
| 93 |
+
ax = image_axes(env, cam, res)
|
| 94 |
+
if ax is None:
|
| 95 |
+
return None
|
| 96 |
+
names = []
|
| 97 |
+
for w in ax:
|
| 98 |
+
i = int(np.argmax(np.abs(w)))
|
| 99 |
+
names.append(("+" if w[i] > 0 else "-") + "xy"[i])
|
| 100 |
+
return dict(right=names[0], down=names[1])
|
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
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "claude_code_full-oauth|2.1.267|0399c793ff571d59|claude-sonnet-5-5|high",
|
| 3 |
+
"fingerprint_sha256": "0f8972223c9bdc90da28633f367aa577ae839f887c2f3f015f8128bb34a7f5b4",
|
| 4 |
+
"written": "2026-10-20 02:16:14",
|
| 5 |
+
"summary": {
|
| 6 |
+
"system_chars": 26736,
|
| 7 |
+
"tools": [
|
| 8 |
+
"mcp__lff__robot",
|
| 9 |
+
"mcp__lff__shell",
|
| 10 |
+
"mcp__lff__view_images"
|
| 11 |
+
],
|
| 12 |
+
"effort_in_request": "high",
|
| 13 |
+
"model_in_request": "claude-sonnet-5-5"
|
| 14 |
+
}
|
| 15 |
+
}
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/lh_tray_delivery.py
ADDED
|
@@ -0,0 +1,883 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LH tray_delivery v2 (long horizon, state restoration): load three bottles onto a tray in the loading area, then move
|
| 2 |
+
the loaded tray over a low threshold strip into the delivery area. Pushing the tray over the strip makes it rock, and
|
| 3 |
+
the top-heavy bottles fall; holding the tray by its handle while moving it does not.
|
| 4 |
+
|
| 5 |
+
Family: long-horizon tasks in which the agent's own normal later-stage action physically breaks earlier progress
|
| 6 |
+
(docs/11). Stages:
|
| 7 |
+
S1-S3 stand the red / green / blue bottle upright on the tray while the tray is inside the yellow loading area;
|
| 8 |
+
S4 move the tray (with the bottles) over the black threshold strip completely into the purple delivery area.
|
| 9 |
+
Success (F1): at the end the tray (board and handle) is completely inside the delivery area, all three bottles stand
|
| 10 |
+
upright on it, the gripper does not touch them, the scene is static, AND the event log shows that all three bottles
|
| 11 |
+
stood on the tray at the same time while the tray was still completely inside the loading area (load first, then
|
| 12 |
+
deliver). Re-standing a fallen bottle on the tray after the move is allowed (counts as a restoration).
|
| 13 |
+
|
| 14 |
+
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
|
| 15 |
+
grasp and to stand, the narrow handle was hard to push straight, "completely inside" needed 2 cm precision, and the
|
| 16 |
+
agents pushed at 3-5 cm/s, far below v1's 0.15 m/s topple threshold, so the hidden variable never mattered. Now:
|
| 17 |
+
- 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;
|
| 18 |
+
- 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
|
| 19 |
+
(grasp it across its width);
|
| 20 |
+
- 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);
|
| 21 |
+
- 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
|
| 22 |
+
cross. Measured: with stocky bottles speed alone cannot be the lever (on a flat table a top-heavy bottle stayed up in
|
| 23 |
+
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
|
| 24 |
+
first climbs (front up ~5 deg), then rocks over the crest under gravity; when it is pushed, nothing holds its trailing
|
| 25 |
+
edge, which jumps up (max tray tilt 7.2-9.3 deg) and the top-heavy bottles fall over the leading edge,
|
| 26 |
+
at every push speed tried (2-6 cm/s and the top speed). When the stem is grasped, the hand holds the trailing edge
|
| 27 |
+
(max tilt 5.7-7.5 deg) and nothing falls. A hand hovering right over the handle (3 cm handle pushed with the
|
| 28 |
+
grasp point ~1 cm above the table) also held it down; hence the 2.5 cm handle.
|
| 29 |
+
- failure codes report the first unmet requirement: not_loaded / order / bottle_fallen / bottle_off_tray /
|
| 30 |
+
not_delivered / held / not_static.
|
| 31 |
+
|
| 32 |
+
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
|
| 33 |
+
middle of the long side that faces away from the delivery area; three bottles (same shape, red / green / blue) standing
|
| 34 |
+
in a row on the table on the far side of the loading area; two painted rectangles (no collision): yellow loading area
|
| 35 |
+
(tray inside it at the start) and purple delivery area 32-34 cm (centre to centre) to its left or right (random); the
|
| 36 |
+
threshold strip lies across the path in the gap between them. The tray travels sideways (the arm's comfortable
|
| 37 |
+
workspace is wide in y but short in x).
|
| 38 |
+
|
| 39 |
+
Hidden variable (same appearance): each bottle's centre-of-mass height (an invisible internal weight, 85 % of its
|
| 40 |
+
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 /
|
| 41 |
+
0.25. Measured on 28 instances (scripted loading, same loaded state for every move): closed-gripper pushes (2, 3, 4.5,
|
| 42 |
+
6 cm/s, top speed, 3 stops, slow approach; agent-style pushes through the tool layer with the grasp point 1.0 / 1.3 /
|
| 43 |
+
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
|
| 44 |
+
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
|
| 45 |
+
again with yaw-only control without first knocking them over), so the range stops at 7.6 cm. Tray-table friction
|
| 46 |
+
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
|
| 47 |
+
jammed at the sill and jumped over it, toppling nothing).
|
| 48 |
+
Restoration: a fallen bottle can be stood up again: grasp its round neck (fingers closing across the neck), lift it --
|
| 49 |
+
it swings down and hangs from the neck -- and set it down on the tray.
|
| 50 |
+
|
| 51 |
+
Simulation notes (as in v1): COM heights are set at reset through body_ipos / inertia and the bottle's collision BVH is
|
| 52 |
+
shifted with it (MuJoCo keeps it in the inertial frame); the tray uses the table's soft contact (solref 0.02); the
|
| 53 |
+
bottles' own contacts are stiffer (solref 0.005) so a bottle lowered onto the board by its neck is not pressed through.
|
| 54 |
+
"""
|
| 55 |
+
import numpy as np
|
| 56 |
+
|
| 57 |
+
from .. import envs
|
| 58 |
+
from ..bddl import write_bddl
|
| 59 |
+
from ..objects import _fmt, _wrap, register_generated
|
| 60 |
+
from ..skills import Skills
|
| 61 |
+
from ..task_base import LFFTask, register_task
|
| 62 |
+
|
| 63 |
+
SOFT = 'solimp="0.9 0.95 0.001" solref="0.02 1"' # the LIBERO table's contact parameters
|
| 64 |
+
|
| 65 |
+
# bottle: square body with a flat 4 x 4 cm bottom + round neck; body origin at the middle of the total height
|
| 66 |
+
BODY = (0.020, 0.020, 0.0375) # half sizes of the body (4 x 4 x 7.5 cm)
|
| 67 |
+
NECK_R, NECK_H = 0.012, 0.015 # neck radius, half height (2.4 cm wide, 3 cm tall) -> 10.5 cm in total
|
| 68 |
+
BH = BODY[2] + NECK_H # half of the total height
|
| 69 |
+
DAMP_BOT = 0.003 # free-joint damping of the bottles (air drag; damps the swing of a bottle hanging from its neck)
|
| 70 |
+
BOT_MASS = 0.25
|
| 71 |
+
W_FRAC = 0.85 # share of the mass in the hidden internal weight
|
| 72 |
+
MU_BOT = 1.0
|
| 73 |
+
COS_UP = 0.95 # upright: long axis within ~18 deg of vertical
|
| 74 |
+
BOT_SOLREF = (0.005, 1.0) # the bottles win in all their contacts (priority 3)
|
| 75 |
+
BOT_SOLIMP = (0.95, 0.99, 0.001, 0.5, 2.0)
|
| 76 |
+
|
| 77 |
+
# tray: board + T handle (stem + cross bar) sticking out of the middle of the trailing long side (tray frame -x)
|
| 78 |
+
PLATE = (0.055, 0.17, 0.006) # 11 x 34 x 1.2 cm board
|
| 79 |
+
STEM = (0.025, 0.015, 0.0125) # 5 long x 3 wide x 2.5 cm tall: grasp it across its width
|
| 80 |
+
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
|
| 81 |
+
# Handle height 2.5 cm (measured on 6 instances x 6 push heights, see the card): the Panda palm reaches ~3-4 cm ahead
|
| 82 |
+
# 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
|
| 83 |
+
# table) hovered right over the handle and kept the trailing edge from jumping up on the sill (like a grasp: no topple
|
| 84 |
+
# 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).
|
| 85 |
+
# A hand pushing at >= 3 cm only touches the handle with its fingertips and can slide over it.
|
| 86 |
+
PLATE_TOP = envs.TABLE_Z + 2 * PLATE[2]
|
| 87 |
+
BACK_X = -PLATE[0] - 2 * STEM[0] - 2 * CROSS[0] # tray-frame x of the handle's back face (-0.13)
|
| 88 |
+
FOOT_DX = (PLATE[0] + BACK_X) / 2 # x of the footprint centre (board + handle) relative to the board centre
|
| 89 |
+
# slots 1.5 cm towards the leading edge: a hand grasping the cross bar with its long side along the travel direction
|
| 90 |
+
# (palm 10.5 cm ahead of the grasp point) still clears the middle bottle by ~7 mm
|
| 91 |
+
SLOT_LX = 0.015
|
| 92 |
+
SLOT_LY = (-0.12, 0.0, 0.12)
|
| 93 |
+
MU_HANDLE = 0.6
|
| 94 |
+
|
| 95 |
+
# painted areas (inner half sizes: along travel, along the tray's long side)
|
| 96 |
+
LOAD_IN = (0.1125, 0.20) # tray footprint 18.5 x 34 cm -> 2 / 3 cm slack per side
|
| 97 |
+
DELIV_IN = (0.14, 0.21) # -> 4.75 / 4 cm slack per side
|
| 98 |
+
LINE_W = 0.008
|
| 99 |
+
AREA_DIST = (0.32, 0.34) # centre to centre
|
| 100 |
+
|
| 101 |
+
# threshold strip: a capsule lying across the path, sunk into the table so that it sticks out RIDGE_H (a rounded sill
|
| 102 |
+
# 2 * sqrt(2 R h - h^2) = 5.3 cm wide)
|
| 103 |
+
RIDGE_H = 0.010
|
| 104 |
+
RIDGE_R = 0.040
|
| 105 |
+
RIDGE_HL = 0.23 # half length of the straight part (46 cm: longer than the tray)
|
| 106 |
+
MU_RIDGE = 0.4 # wins in its contacts (priority 4)
|
| 107 |
+
|
| 108 |
+
BOTTLES = ("bottle_red_1", "bottle_green_1", "bottle_blue_1")
|
| 109 |
+
COLOR_OF = {"bottle_red_1": "red", "bottle_green_1": "green", "bottle_blue_1": "blue"}
|
| 110 |
+
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)}
|
| 111 |
+
TRAY = "tray_1"
|
| 112 |
+
LOAD, DELIVER, RIDGE = "load_area_1", "deliver_area_1", "threshold_1"
|
| 113 |
+
|
| 114 |
+
# hidden COM heights above the bottle's bottom (m); calibration in the task card
|
| 115 |
+
HC_STABLE = (0.020, 0.035)
|
| 116 |
+
HC_TOPHEAVY = (0.066, 0.076)
|
| 117 |
+
N_TOP_P = (0.35, 0.40, 0.25) # P(0 / 1 / 2 top-heavy bottles)
|
| 118 |
+
MU_TRAY = (0.45, 0.60)
|
| 119 |
+
|
| 120 |
+
DEBOUNCE = 5 # control steps a predicate must keep a new value before an event is recorded (0.25 s)
|
| 121 |
+
|
| 122 |
+
# scripted reference moves
|
| 123 |
+
V_NAIVE = 0.045 # the pilot agents pushed at 3-6 cm/s
|
| 124 |
+
V_CAREFUL = 0.02 # the LA interface's slowest speed
|
| 125 |
+
GRASP_TOP = 0.012 # scripted grasp point: on the neck, this far below the bottle's top (the palm is ~2 cm above it)
|
| 126 |
+
SAFE_Z = envs.TABLE_Z + 0.17 # scripted transits: fingertips ~5 cm above the tops of bottles standing on the tray
|
| 127 |
+
SAFE_Z_HELD = envs.TABLE_Z + 0.25 # ... and with a bottle hanging from the gripper: its bottom ~4 cm above them
|
| 128 |
+
PUSH_Z = envs.TABLE_Z + 0.015 # closed-gripper pushes: grasp point 1.5 cm above the table (fingertips ~0.5 cm)
|
| 129 |
+
DRAG_Z = envs.TABLE_Z + 0.015 # grasping the stem: finger pads over its whole height
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def bottle_xml(name, rgba):
|
| 133 |
+
zb = -BH + BODY[2]
|
| 134 |
+
zn = -BH + 2 * BODY[2] + NECK_H
|
| 135 |
+
neck_rgba = tuple(0.8 * c for c in rgba[:3]) + (1.0,)
|
| 136 |
+
parts = [("box", zb, _fmt(BODY), rgba), ("cylinder", zn, f"{NECK_R:.5f} {NECK_H:.5f}", neck_rgba)]
|
| 137 |
+
gs = []
|
| 138 |
+
for k, (typ, z, size, c) in enumerate(parts):
|
| 139 |
+
gs.append(f' <geom name="{name}_g{k}" type="{typ}" pos="0 0 {z:.5f}" size="{size}" rgba="{_fmt(c)}" '
|
| 140 |
+
f'density="500" friction="{MU_BOT} 0.005 0.0001" {SOFT} group="0" />')
|
| 141 |
+
gs.append(f' <geom type="{typ}" pos="0 0 {z:.5f}" size="{size}" rgba="{_fmt(c)}" conaffinity="0" '
|
| 142 |
+
f'contype="0" group="1" />')
|
| 143 |
+
return _wrap(name, "\n".join(gs), BH, float(np.hypot(BODY[0], BODY[1])))
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def tray_xml(name, rgba=(0.62, 0.45, 0.27, 1.0)):
|
| 147 |
+
hz = -PLATE[2] + STEM[2] # handle bottom flush with the board's bottom
|
| 148 |
+
sp = (-PLATE[0] - STEM[0], 0.0, hz)
|
| 149 |
+
cp = (-PLATE[0] - 2 * STEM[0] - CROSS[0], 0.0, hz)
|
| 150 |
+
hrgba = (0.30, 0.20, 0.12, 1.0)
|
| 151 |
+
gs = []
|
| 152 |
+
for k, (p, s, c, mu) in enumerate((((0, 0, 0), PLATE, rgba, 0.6), (sp, STEM, hrgba, MU_HANDLE),
|
| 153 |
+
(cp, CROSS, hrgba, MU_HANDLE))):
|
| 154 |
+
gs.append(f' <geom name="{name}_g{k}" type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" '
|
| 155 |
+
f'density="500" friction="{mu} 0.005 0.0001" {SOFT} group="0" />')
|
| 156 |
+
gs.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" conaffinity="0" '
|
| 157 |
+
f'contype="0" group="1" />')
|
| 158 |
+
return _wrap(name, "\n".join(gs), PLATE[2], float(np.hypot(PLATE[0] - BACK_X, PLATE[1])))
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def area_xml(name, inner, fill, line):
|
| 162 |
+
"""Flat, visual-only rectangle painted on the table (light fill + dark outline, no collisions)."""
|
| 163 |
+
ix, iy = inner
|
| 164 |
+
ox, oy = ix + LINE_W, iy + LINE_W
|
| 165 |
+
parts = [((0, 0, 0.0004), (ox, oy, 0.0004), fill),
|
| 166 |
+
((0, iy + LINE_W / 2, 0.0010), (ox, LINE_W / 2, 0.0002), line),
|
| 167 |
+
((0, -iy - LINE_W / 2, 0.0010), (ox, LINE_W / 2, 0.0002), line),
|
| 168 |
+
((ix + LINE_W / 2, 0, 0.0010), (LINE_W / 2, oy, 0.0002), line),
|
| 169 |
+
((-ix - LINE_W / 2, 0, 0.0010), (LINE_W / 2, oy, 0.0002), line)]
|
| 170 |
+
g = "\n".join(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(c)}" '
|
| 171 |
+
f'contype="0" conaffinity="0" group="1" />' for p, sz, c in parts)
|
| 172 |
+
return _wrap(name, g, 0.0012, float(np.hypot(ox, oy)))
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def sill_xml(name, rgba=(0.12, 0.12, 0.13, 1.0)):
|
| 176 |
+
"""the threshold strip: a capsule along the fixture's local y (quat turns z into y), origin on its axis; the
|
| 177 |
+
fixture is placed with the axis RIDGE_R - RIDGE_H below the table top (static: no contacts with the table)"""
|
| 178 |
+
q = "0.70711 0.70711 0 0"
|
| 179 |
+
g = (f' <geom name="{name}_g0" type="capsule" quat="{q}" size="{RIDGE_R:.5f} {RIDGE_HL:.5f}" '
|
| 180 |
+
f'rgba="{_fmt(rgba)}" friction="{MU_RIDGE} 0.005 0.0001" {SOFT} group="0" />\n'
|
| 181 |
+
f' <geom type="capsule" quat="{q}" size="{RIDGE_R:.5f} {RIDGE_HL:.5f}" rgba="{_fmt(rgba)}" '
|
| 182 |
+
f'conaffinity="0" contype="0" group="1" />')
|
| 183 |
+
return _wrap(name, g, RIDGE_R, RIDGE_HL + RIDGE_R)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def _rotz2(a):
|
| 187 |
+
c, s = np.cos(a), np.sin(a)
|
| 188 |
+
return np.array([[c, -s], [s, c]])
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def _yaw_of(R):
|
| 192 |
+
return float(np.arctan2(R[1, 0], R[0, 0]))
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
class TraySkills(Skills):
|
| 196 |
+
"""Skills whose every control step feeds the task's stage monitor."""
|
| 197 |
+
|
| 198 |
+
def __init__(self, env, task, recorder=None):
|
| 199 |
+
super().__init__(env, recorder=recorder)
|
| 200 |
+
self.task = task
|
| 201 |
+
|
| 202 |
+
def _act(self, dpos, drot, grip):
|
| 203 |
+
super()._act(dpos, drot, grip)
|
| 204 |
+
self.task.monitor_step()
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
@register_task
|
| 208 |
+
class TrayDelivery(LFFTask):
|
| 209 |
+
name = "lh_tray_delivery"
|
| 210 |
+
level = "L2"
|
| 211 |
+
category = "state_restoration"
|
| 212 |
+
capabilities = ("Perceive", "Reason", "Plan")
|
| 213 |
+
protocol = "cross"
|
| 214 |
+
max_attempts = 3
|
| 215 |
+
# scripted primitives (~ agent commands): careful oracle 37; naive push + same-attempt repair of 1-2 bottles 46-63
|
| 216 |
+
agent_max_steps = 110
|
| 217 |
+
instruction = ("Load the red, green and blue bottles onto the wooden tray: stand each bottle upright on the tray "
|
| 218 |
+
"while the tray is still inside the yellow loading area. Only after all three bottles are on the "
|
| 219 |
+
"tray, move the tray with the bottles on it over the black threshold strip into the purple "
|
| 220 |
+
"delivery area. At the end the whole tray, including its handle, must be inside the purple area "
|
| 221 |
+
"with all three bottles standing upright on it.")
|
| 222 |
+
instruction_indirect = ("Stand the three bottles up on the wooden board that lies in the yellow rectangle while "
|
| 223 |
+
"the board is still there; then bring the board with the bottles on it across the black "
|
| 224 |
+
"strip into the purple rectangle. At the end the whole board, including its dark handle, "
|
| 225 |
+
"must lie inside the purple rectangle with all three bottles standing on it.")
|
| 226 |
+
agent_object_names = ["red bottle", "green bottle", "blue bottle", "wooden tray", "yellow loading area",
|
| 227 |
+
"purple delivery area", "black threshold strip"]
|
| 228 |
+
|
| 229 |
+
# ------------------------------------------------------------ scene
|
| 230 |
+
def make_bddl(self):
|
| 231 |
+
objs = []
|
| 232 |
+
for i, b in enumerate(BOTTLES):
|
| 233 |
+
c = COLOR_OF[b]
|
| 234 |
+
cat = register_generated(f"LffTdBottle{c.capitalize()}", bottle_xml(f"lff_td_bottle_{c}", RGBA[c]))
|
| 235 |
+
x0 = -0.25 + 0.12 * i
|
| 236 |
+
objs.append((b, cat, f"bottle_{c}_region", (x0, 0.30, x0 + 0.01, 0.31)))
|
| 237 |
+
tray = register_generated("LffTdTray", tray_xml("lff_td_tray"))
|
| 238 |
+
objs.append((TRAY, tray, "tray_region", (0.0, -0.05, 0.01, -0.04)))
|
| 239 |
+
load = register_generated("LffTdLoadArea", area_xml("lff_td_load_area", LOAD_IN, (0.98, 0.93, 0.55, 1.0),
|
| 240 |
+
(0.85, 0.62, 0.05, 1.0)), free=False)
|
| 241 |
+
deliv = register_generated("LffTdDeliverArea", area_xml("lff_td_deliver_area", DELIV_IN,
|
| 242 |
+
(0.86, 0.78, 0.95, 1.0), (0.45, 0.20, 0.65, 1.0)),
|
| 243 |
+
free=False)
|
| 244 |
+
sill = register_generated("LffTdThreshold", sill_xml("lff_td_threshold"), free=False)
|
| 245 |
+
fx = [(LOAD, load, "load_region", (-0.21, -0.41, -0.20, -0.40)),
|
| 246 |
+
(DELIVER, deliv, "deliver_region", (0.15, -0.41, 0.16, -0.40)),
|
| 247 |
+
(RIDGE, sill, "threshold_region", (0.15, 0.38, 0.16, 0.39))]
|
| 248 |
+
return write_bddl(self.name, self.instruction, objs, fx)
|
| 249 |
+
|
| 250 |
+
def __init__(self, cam_res=None):
|
| 251 |
+
super().__init__(cam_res)
|
| 252 |
+
env = self.env
|
| 253 |
+
m = env.sim.model
|
| 254 |
+
self.area_bid = {a: m.body_name2id(env.fixtures_dict[a].root_body) for a in (LOAD, DELIVER, RIDGE)}
|
| 255 |
+
self.bid = {n: envs.body_id(env, n) for n in BOTTLES + (TRAY,)}
|
| 256 |
+
mm = m._model
|
| 257 |
+
self._bvh0 = {}
|
| 258 |
+
for b in BOTTLES: # compiled inertial frame + BVH (shifted with the hidden COM at every reset)
|
| 259 |
+
bid = self.bid[b]
|
| 260 |
+
adr, num = mm.body_bvhadr[bid], mm.body_bvhnum[bid]
|
| 261 |
+
self._bvh0[b] = (m.body_ipos[bid].copy(), mm.bvh_aabb[adr:adr + num].copy(), adr, num)
|
| 262 |
+
# geom -> object index for the contact checks (0..2 bottles, 3 tray)
|
| 263 |
+
self._obj_of = np.full(m.ngeom, -1, int)
|
| 264 |
+
for k, n in enumerate(BOTTLES + (TRAY,)):
|
| 265 |
+
self._obj_of[envs.obj_geom_ids(env, n)] = k
|
| 266 |
+
self._is_robot = np.zeros(m.ngeom, bool)
|
| 267 |
+
self._is_robot[envs.robot_geom_ids(env)] = True
|
| 268 |
+
sb = self.area_bid[RIDGE]
|
| 269 |
+
self._is_sill = np.array([m.geom_bodyid[g] == sb or m.body_parentid[m.geom_bodyid[g]] == sb
|
| 270 |
+
for g in range(m.ngeom)], bool)
|
| 271 |
+
self._dof = {n: envs.free_joint_addr(env, n)[1] for n in BOTTLES + (TRAY,)}
|
| 272 |
+
self.inst = None
|
| 273 |
+
self.mon = None
|
| 274 |
+
|
| 275 |
+
def sample_instance(self, seed):
|
| 276 |
+
"""Layout: the tray's long side runs forward / back (world x); it travels sideways (world y) from the loading
|
| 277 |
+
area to the delivery area, 32-34 cm centre to centre, to the left or to the right, over the threshold strip in
|
| 278 |
+
the middle of the gap between the areas. The bottles stand in a row on the table on the far side of the
|
| 279 |
+
loading area. Tray frame: local +x = direction of travel, handle at local -x."""
|
| 280 |
+
rng = np.random.default_rng(seed)
|
| 281 |
+
s = 1.0 if rng.random() < 0.5 else -1.0 # +1: the tray travels to the robot's left (+y)
|
| 282 |
+
xl, yl = float(rng.uniform(-0.18, -0.15)), float(-s * rng.uniform(0.11, 0.13))
|
| 283 |
+
dist = float(rng.uniform(*AREA_DIST))
|
| 284 |
+
deliver = [xl + float(rng.uniform(-0.01, 0.01)), yl + s * dist]
|
| 285 |
+
yaw = s * np.pi / 2
|
| 286 |
+
R = _rotz2(yaw)
|
| 287 |
+
g0, g1 = LOAD_IN[0] + LINE_W, dist - DELIV_IN[0] - LINE_W # the gap between the areas, along travel
|
| 288 |
+
sill_xy = [(xl + deliver[0]) / 2, float((np.array([xl, yl]) + R @ np.array([(g0 + g1) / 2, 0.0]))[1])]
|
| 289 |
+
jit = np.array([rng.uniform(-0.008, 0.008), rng.uniform(-0.005, 0.005)]) # tray frame
|
| 290 |
+
tray_xy = (np.array([xl, yl]) + R @ (np.array([-FOOT_DX, 0.0]) + jit)).tolist()
|
| 291 |
+
order = [int(i) for i in rng.permutation(3)] # bottle -> position in the start row (along x)
|
| 292 |
+
by = yl - s * (LOAD_IN[0] + LINE_W + 0.04)
|
| 293 |
+
start = {}
|
| 294 |
+
for k, b in enumerate(BOTTLES):
|
| 295 |
+
start[b] = [xl + (-0.12, 0.0, 0.12)[order[k]] + float(rng.uniform(-0.008, 0.008)),
|
| 296 |
+
by + float(rng.uniform(-0.005, 0.005)), float(rng.uniform(-0.35, 0.35))]
|
| 297 |
+
n_top = int(rng.choice(3, p=N_TOP_P))
|
| 298 |
+
top = set(int(i) for i in rng.choice(3, n_top, replace=False))
|
| 299 |
+
hc = {b: float(rng.uniform(*(HC_TOPHEAVY if k in top else HC_STABLE))) for k, b in enumerate(BOTTLES)}
|
| 300 |
+
return dict(seed=int(seed), travel="left" if s > 0 else "right", area_yaw=float(yaw), load_xy=[xl, yl],
|
| 301 |
+
deliver_xy=deliver, sill_xy=sill_xy, tray_xy=tray_xy, tray_yaw=float(yaw), bottle_start=start,
|
| 302 |
+
com_height=hc, top_heavy=[b for k, b in enumerate(BOTTLES) if k in top],
|
| 303 |
+
mu_tray=float(rng.uniform(*MU_TRAY)))
|
| 304 |
+
|
| 305 |
+
def _set_com(self, b, hc):
|
| 306 |
+
"""Hidden internal weight: bottle COM at height hc above its bottom (mass and inertia consistent)."""
|
| 307 |
+
m = self.env.sim.model
|
| 308 |
+
mm = m._model
|
| 309 |
+
bid = self.bid[b]
|
| 310 |
+
a, c = BODY[0], BODY[2]
|
| 311 |
+
vb, vn = 8 * a * a * c, np.pi * NECK_R ** 2 * 2 * NECK_H
|
| 312 |
+
zs = ((-BH + c) * vb + (-BH + 2 * c + NECK_H) * vn) / (vb + vn) # shell COM (origin: middle of the height)
|
| 313 |
+
ms, mw = BOT_MASS * (1 - W_FRAC), BOT_MASS * W_FRAC
|
| 314 |
+
zw = float(np.clip((BOT_MASS * (hc - BH) - ms * zs) / mw, -BH + 0.01, BH - 0.01))
|
| 315 |
+
zc = (ms * zs + mw * zw) / BOT_MASS
|
| 316 |
+
ww = 0.025 # the weight is a 2.5 cm cube
|
| 317 |
+
Ixx = ms / 3 * (a * a + c * c) + ms * (zs - zc) ** 2 + mw * (zw - zc) ** 2 + mw * ww * ww / 6
|
| 318 |
+
Izz = ms * 2 * a * a / 3 + mw * ww * ww / 6
|
| 319 |
+
m.body_mass[bid] = BOT_MASS
|
| 320 |
+
m.body_ipos[bid] = [0.0, 0.0, zc]
|
| 321 |
+
m.body_iquat[bid] = [1.0, 0.0, 0.0, 0.0]
|
| 322 |
+
m.body_inertia[bid] = [Ixx, Ixx, Izz]
|
| 323 |
+
ip0, A0, adr, num = self._bvh0[b]
|
| 324 |
+
mm.bvh_aabb[adr:adr + num, :3] = A0[:, :3] - (m.body_ipos[bid] - ip0) # BVH lives in the inertial frame
|
| 325 |
+
return zc + BH
|
| 326 |
+
|
| 327 |
+
def apply_instance(self, inst):
|
| 328 |
+
self.inst = inst
|
| 329 |
+
env = self.env
|
| 330 |
+
m = env.sim.model
|
| 331 |
+
ya = inst["area_yaw"]
|
| 332 |
+
qa = [np.cos(ya / 2), 0.0, 0.0, np.sin(ya / 2)]
|
| 333 |
+
for a, key in ((LOAD, "load_xy"), (DELIVER, "deliver_xy")):
|
| 334 |
+
m.body_pos[self.area_bid[a]] = [inst[key][0], inst[key][1], envs.TABLE_Z + 0.0002]
|
| 335 |
+
m.body_quat[self.area_bid[a]] = qa
|
| 336 |
+
m.body_pos[self.area_bid[RIDGE]] = [inst["sill_xy"][0], inst["sill_xy"][1], envs.TABLE_Z + RIDGE_H - RIDGE_R]
|
| 337 |
+
m.body_quat[self.area_bid[RIDGE]] = qa
|
| 338 |
+
for g in np.flatnonzero(self._is_sill): # the sill's friction wins (the tray's would otherwise: priority 2)
|
| 339 |
+
m.geom_friction[g] = [MU_RIDGE, 0.005, 0.0001]
|
| 340 |
+
m.geom_priority[g] = 4
|
| 341 |
+
envs.set_obj_pose(env, TRAY, [inst["tray_xy"][0], inst["tray_xy"][1], envs.TABLE_Z + PLATE[2] + 0.0005],
|
| 342 |
+
yaw=inst["tray_yaw"])
|
| 343 |
+
envs.set_friction(env, TRAY, inst["mu_tray"], priority=2)
|
| 344 |
+
for b in BOTTLES:
|
| 345 |
+
self._set_com(b, inst["com_height"][b])
|
| 346 |
+
for g in envs.obj_geom_ids(env, b): # bottle params win in all its contacts (tray, table, fingers)
|
| 347 |
+
m.geom_friction[g] = [MU_BOT, 0.005, 0.0001]
|
| 348 |
+
m.geom_condim[g] = 3
|
| 349 |
+
m.geom_priority[g] = 3
|
| 350 |
+
m.geom_solref[g] = BOT_SOLREF
|
| 351 |
+
m.geom_solimp[g] = BOT_SOLIMP
|
| 352 |
+
m.dof_damping[self._dof[b]:self._dof[b] + 6] = DAMP_BOT
|
| 353 |
+
x, y, yaw = inst["bottle_start"][b]
|
| 354 |
+
envs.set_obj_pose(env, b, [x, y, envs.TABLE_Z + BH + 0.0005], yaw=yaw)
|
| 355 |
+
|
| 356 |
+
def reset_instance(self, inst, recorder=None):
|
| 357 |
+
self.env.reset()
|
| 358 |
+
self.apply_instance(inst)
|
| 359 |
+
self.env.sim.forward()
|
| 360 |
+
envs.settle(self.env, 10)
|
| 361 |
+
self.sk = TraySkills(self.env, self, recorder=recorder)
|
| 362 |
+
self._init_monitor()
|
| 363 |
+
return self.sk
|
| 364 |
+
|
| 365 |
+
# ------------------------------------------------------------ geometry / predicates
|
| 366 |
+
def tray_pose(self):
|
| 367 |
+
d = self.env.sim.data
|
| 368 |
+
bid = self.bid[TRAY]
|
| 369 |
+
return d.body_xpos[bid].copy(), d.body_xmat[bid].reshape(3, 3).copy()
|
| 370 |
+
|
| 371 |
+
def tray_footprint(self):
|
| 372 |
+
p, R = self.tray_pose()
|
| 373 |
+
loc = np.array([[PLATE[0], PLATE[1]], [PLATE[0], -PLATE[1]], [-PLATE[0], PLATE[1]], [-PLATE[0], -PLATE[1]],
|
| 374 |
+
[BACK_X, CROSS[1]], [BACK_X, -CROSS[1]]])
|
| 375 |
+
return p[:2] + loc @ R[:2, :2].T
|
| 376 |
+
|
| 377 |
+
@staticmethod
|
| 378 |
+
def _word(v):
|
| 379 |
+
"""robot-centric word for a horizontal world direction"""
|
| 380 |
+
if abs(v[0]) >= abs(v[1]):
|
| 381 |
+
return "forward" if v[0] > 0 else "back"
|
| 382 |
+
return "left" if v[1] > 0 else "right"
|
| 383 |
+
|
| 384 |
+
def area_excess(self, key):
|
| 385 |
+
"""How far the tray footprint sticks out of the area (m, >0 = outside) per edge, keyed by robot-centric word."""
|
| 386 |
+
c = np.asarray(self.inst[key])
|
| 387 |
+
Ra = _rotz2(self.inst["area_yaw"])
|
| 388 |
+
pts = (self.tray_footprint() - c) @ Ra # area frame
|
| 389 |
+
inner = LOAD_IN if key == "load_xy" else DELIV_IN
|
| 390 |
+
out = {}
|
| 391 |
+
for axis, sign in ((0, 1), (0, -1), (1, 1), (1, -1)):
|
| 392 |
+
u = np.zeros(2)
|
| 393 |
+
u[axis] = sign
|
| 394 |
+
out[self._word(Ra @ u)] = float((sign * pts[:, axis]).max() - inner[axis])
|
| 395 |
+
return out
|
| 396 |
+
|
| 397 |
+
def tray_inside(self, key):
|
| 398 |
+
return max(self.area_excess(key).values()) <= 0.0
|
| 399 |
+
|
| 400 |
+
def _contacts(self):
|
| 401 |
+
d = self.env.sim.data
|
| 402 |
+
n = d.ncon
|
| 403 |
+
if not n:
|
| 404 |
+
return np.zeros(0, int), np.zeros(0, int)
|
| 405 |
+
return np.asarray(d.contact.geom1)[:n], np.asarray(d.contact.geom2)[:n]
|
| 406 |
+
|
| 407 |
+
def robot_touch(self):
|
| 408 |
+
"""indices (0..2 bottles, 3 tray) of the objects the robot touches now"""
|
| 409 |
+
g1, g2 = self._contacts()
|
| 410 |
+
hit = np.concatenate([self._obj_of[g2[self._is_robot[g1]]], self._obj_of[g1[self._is_robot[g2]]]])
|
| 411 |
+
return set(int(i) for i in hit[hit >= 0])
|
| 412 |
+
|
| 413 |
+
def tray_on_sill(self):
|
| 414 |
+
g1, g2 = self._contacts()
|
| 415 |
+
tray = self._obj_of == 3
|
| 416 |
+
return bool(np.any((tray[g1] & self._is_sill[g2]) | (tray[g2] & self._is_sill[g1])))
|
| 417 |
+
|
| 418 |
+
def bottle_state(self, b, touched=False):
|
| 419 |
+
d = self.env.sim.data
|
| 420 |
+
bid = self.bid[b]
|
| 421 |
+
p = d.body_xpos[bid]
|
| 422 |
+
up = float(d.body_xmat[bid].reshape(3, 3)[2, 2])
|
| 423 |
+
tp, R = self.tray_pose()
|
| 424 |
+
loc = R.T @ (p - tp)
|
| 425 |
+
on_xy = abs(loc[0]) <= PLATE[0] and abs(loc[1]) <= PLATE[1]
|
| 426 |
+
resting = abs(loc[2] - (PLATE[2] + BH)) < 0.012
|
| 427 |
+
upright = up >= COS_UP
|
| 428 |
+
return dict(upright=bool(upright), on_tray=bool(on_xy and resting), touched=bool(touched),
|
| 429 |
+
ok=bool(upright and on_xy and resting and not touched), loc=loc, pos=p.copy(), cos=up)
|
| 430 |
+
|
| 431 |
+
def predicates(self):
|
| 432 |
+
t = self.robot_touch()
|
| 433 |
+
st = {b: self.bottle_state(b, k in t)["ok"] for k, b in enumerate(BOTTLES)}
|
| 434 |
+
st["tray_in_delivery"] = self.tray_inside("deliver_xy")
|
| 435 |
+
st["tray_in_loading"] = self.tray_inside("load_xy")
|
| 436 |
+
return st, t
|
| 437 |
+
|
| 438 |
+
def _tray_speed(self):
|
| 439 |
+
da = self._dof[TRAY]
|
| 440 |
+
return float(np.linalg.norm(self.env.sim.data.qvel[da:da + 2]))
|
| 441 |
+
|
| 442 |
+
# ------------------------------------------------------------ monitor
|
| 443 |
+
def _init_monitor(self):
|
| 444 |
+
st, _ = self.predicates()
|
| 445 |
+
self.mon = dict(stable=dict(st), cnt={k: 0 for k in st}, ever=set(k for k, v in st.items() if v),
|
| 446 |
+
lost=set(), events=[], order_step=None, last_touch={k: -10 ** 6 for k in range(4)},
|
| 447 |
+
last_tray_move=-10 ** 6, last_sill=-10 ** 6, tray_vmax_loaded=0.0, left_unloaded=None,
|
| 448 |
+
on_in_loading=set())
|
| 449 |
+
|
| 450 |
+
def monitor_step(self):
|
| 451 |
+
mon = self.mon
|
| 452 |
+
if mon is None:
|
| 453 |
+
return
|
| 454 |
+
n = self.sk.n_steps
|
| 455 |
+
st, touch = self.predicates()
|
| 456 |
+
for k in touch:
|
| 457 |
+
mon["last_touch"][k] = n
|
| 458 |
+
v = self._tray_speed()
|
| 459 |
+
if v > 0.01:
|
| 460 |
+
mon["last_tray_move"] = n
|
| 461 |
+
if self.tray_on_sill():
|
| 462 |
+
mon["last_sill"] = n
|
| 463 |
+
if all(mon["stable"][b] for b in BOTTLES):
|
| 464 |
+
mon["tray_vmax_loaded"] = max(mon["tray_vmax_loaded"], v)
|
| 465 |
+
for k, val in st.items():
|
| 466 |
+
if val == mon["stable"][k]:
|
| 467 |
+
mon["cnt"][k] = 0
|
| 468 |
+
continue
|
| 469 |
+
mon["cnt"][k] += 1
|
| 470 |
+
if mon["cnt"][k] < DEBOUNCE:
|
| 471 |
+
continue
|
| 472 |
+
mon["stable"][k] = val
|
| 473 |
+
mon["cnt"][k] = 0
|
| 474 |
+
step = n - DEBOUNCE + 1
|
| 475 |
+
if val:
|
| 476 |
+
ev = "restored" if k in mon["lost"] else "achieved"
|
| 477 |
+
mon["ever"].add(k)
|
| 478 |
+
mon["events"].append(dict(step=step, pred=k, ev=ev))
|
| 479 |
+
else:
|
| 480 |
+
mon["lost"].add(k)
|
| 481 |
+
e = dict(step=step, pred=k, ev="lost")
|
| 482 |
+
if k == "tray_in_loading" and mon["order_step"] is None and mon["left_unloaded"] is None:
|
| 483 |
+
mon["left_unloaded"] = step # the tray left the loading area before it was loaded
|
| 484 |
+
if k in BOTTLES:
|
| 485 |
+
j = BOTTLES.index(k)
|
| 486 |
+
moving = n - mon["last_tray_move"] <= 30
|
| 487 |
+
# tray motion first: a bottle toppled by the move often falls against the moving hand
|
| 488 |
+
e["cause"] = ("threshold" if moving and n - mon["last_sill"] <= 40 else
|
| 489 |
+
"tray_moving" if moving else
|
| 490 |
+
"robot" if n - mon["last_touch"][j] <= 20 else "other")
|
| 491 |
+
# a bottle taken off (or knocked off by the robot) while the tray is still in the loading area:
|
| 492 |
+
# the tray is no longer loaded -> the order latch has to be earned again (unload / reload trick)
|
| 493 |
+
if (e["cause"] not in ("threshold", "tray_moving") and mon["stable"]["tray_in_loading"]
|
| 494 |
+
and mon["order_step"] is not None):
|
| 495 |
+
mon["order_step"] = None
|
| 496 |
+
mon["lost"].add("loaded_in_loading_area")
|
| 497 |
+
mon["events"].append(e)
|
| 498 |
+
e = dict(step=step, pred="loaded_in_loading_area", ev="lost")
|
| 499 |
+
mon["events"].append(e)
|
| 500 |
+
if mon["stable"]["tray_in_loading"]:
|
| 501 |
+
mon["on_in_loading"] |= {b for b in BOTTLES if mon["stable"][b]}
|
| 502 |
+
if mon["order_step"] is None and mon["stable"]["tray_in_loading"] and all(mon["stable"][b] for b in BOTTLES):
|
| 503 |
+
mon["order_step"] = n
|
| 504 |
+
mon["events"].append(dict(step=n, pred="loaded_in_loading_area",
|
| 505 |
+
ev="restored" if "loaded_in_loading_area" in mon["lost"] else "achieved"))
|
| 506 |
+
|
| 507 |
+
# ------------------------------------------------------------ outcome / F2
|
| 508 |
+
def _static(self):
|
| 509 |
+
d = self.env.sim.data
|
| 510 |
+
for nm in BOTTLES + (TRAY,):
|
| 511 |
+
da = self._dof[nm]
|
| 512 |
+
if np.linalg.norm(d.qvel[da:da + 3]) > 0.01 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.15:
|
| 513 |
+
return False
|
| 514 |
+
return True
|
| 515 |
+
|
| 516 |
+
def _where(self, b, bs):
|
| 517 |
+
"""robot-centric description of where a bottle is (relative to the tray)"""
|
| 518 |
+
if bs["on_tray"]:
|
| 519 |
+
return "on the tray"
|
| 520 |
+
tp, R = self.tray_pose()
|
| 521 |
+
lx, ly = R[:2, :2].T @ (bs["pos"][:2] - tp[:2])
|
| 522 |
+
if abs(lx) <= PLATE[0] and abs(ly) <= PLATE[1]:
|
| 523 |
+
return "on the tray"
|
| 524 |
+
if abs(lx) <= PLATE[0] + 0.04 and abs(ly) <= PLATE[1] + 0.04:
|
| 525 |
+
return "partly on the tray"
|
| 526 |
+
v = R[:2, 0] * np.sign(lx) if abs(lx) - PLATE[0] >= abs(ly) - PLATE[1] else R[:2, 1] * np.sign(ly)
|
| 527 |
+
side = {"forward": "in front of", "back": "behind", "left": "to the left of",
|
| 528 |
+
"right": "to the right of"}[self._word(v)]
|
| 529 |
+
return f"on the table, {side} the tray"
|
| 530 |
+
|
| 531 |
+
@staticmethod
|
| 532 |
+
def _names(bs):
|
| 533 |
+
cols = [COLOR_OF[b] for b in bs]
|
| 534 |
+
if len(cols) == 1:
|
| 535 |
+
return f"the {cols[0]} bottle"
|
| 536 |
+
return "the " + ", the ".join(cols[:-1]) + f" and the {cols[-1]} bottles"
|
| 537 |
+
|
| 538 |
+
def outcome(self, inst):
|
| 539 |
+
sk = self.sk
|
| 540 |
+
sk.hold(30) # let everything settle (keeps the gripper as it is)
|
| 541 |
+
mon = self.mon
|
| 542 |
+
touch = self.robot_touch()
|
| 543 |
+
bst = {b: self.bottle_state(b, k in touch) for k, b in enumerate(BOTTLES)}
|
| 544 |
+
delivered = self.tray_inside("deliver_xy")
|
| 545 |
+
static = self._static()
|
| 546 |
+
order_ok = mon["order_step"] is not None
|
| 547 |
+
all_ok = all(s["ok"] for s in bst.values())
|
| 548 |
+
success = bool(order_ok and delivered and all_ok and static)
|
| 549 |
+
ev = mon["events"]
|
| 550 |
+
stage_preds = set(BOTTLES) | {"tray_in_delivery"}
|
| 551 |
+
n_reg = sum(1 for e in ev if e["ev"] == "lost" and e["pred"] in stage_preds)
|
| 552 |
+
n_res = sum(1 for e in ev if e["ev"] == "restored" and e["pred"] in stage_preds)
|
| 553 |
+
fell_moving = sorted({e["pred"] for e in ev if e["ev"] == "lost" and e.get("cause") in ("threshold",
|
| 554 |
+
"tray_moving")})
|
| 555 |
+
fell_sill = sorted({e["pred"] for e in ev if e["ev"] == "lost" and e.get("cause") == "threshold"})
|
| 556 |
+
fallen = [b for b in BOTTLES if not bst[b]["upright"]]
|
| 557 |
+
off = [b for b in BOTTLES if bst[b]["upright"] and not bst[b]["on_tray"]]
|
| 558 |
+
held = [b for b in BOTTLES if bst[b]["upright"] and bst[b]["on_tray"] and bst[b]["touched"]]
|
| 559 |
+
# failure code = the first unmet requirement, in task order: loading -> order -> bottles -> delivery -> rest
|
| 560 |
+
if not order_ok:
|
| 561 |
+
failure = "order" if mon["left_unloaded"] is not None else "not_loaded"
|
| 562 |
+
elif fallen:
|
| 563 |
+
failure = "bottle_fallen"
|
| 564 |
+
elif off:
|
| 565 |
+
failure = "bottle_off_tray"
|
| 566 |
+
elif not delivered:
|
| 567 |
+
failure = "not_delivered"
|
| 568 |
+
elif held:
|
| 569 |
+
failure = "held"
|
| 570 |
+
elif not static:
|
| 571 |
+
failure = "not_static"
|
| 572 |
+
else:
|
| 573 |
+
failure = None
|
| 574 |
+
# F2 text (robot-centric words, no coordinates); the first sentence names the failure
|
| 575 |
+
parts = []
|
| 576 |
+
if failure == "not_loaded":
|
| 577 |
+
missing = [b for b in BOTTLES if b not in mon["on_in_loading"]]
|
| 578 |
+
parts.append(f"Loading was not completed: {self._names(missing)} never stood on the tray while it was in "
|
| 579 |
+
f"the yellow loading area." if missing else
|
| 580 |
+
"Loading was not completed: the three bottles never stood on the tray at the same time while "
|
| 581 |
+
"it was in the yellow loading area.")
|
| 582 |
+
elif failure == "order":
|
| 583 |
+
parts.append("The tray left the yellow loading area before all three bottles stood on it (load all three "
|
| 584 |
+
"first, then move the loaded tray).")
|
| 585 |
+
bottle_txt = []
|
| 586 |
+
for b in BOTTLES:
|
| 587 |
+
s, col = bst[b], COLOR_OF[b]
|
| 588 |
+
if s["ok"]:
|
| 589 |
+
bottle_txt.append(f"The {col} bottle stands upright on the tray.")
|
| 590 |
+
elif not s["upright"]:
|
| 591 |
+
bottle_txt.append(f"The {col} bottle has fallen over and lies {self._where(b, s)}.")
|
| 592 |
+
elif not s["on_tray"]:
|
| 593 |
+
bottle_txt.append(f"The {col} bottle stands upright {self._where(b, s)}, not on the tray.")
|
| 594 |
+
else:
|
| 595 |
+
bottle_txt.append(f"The {col} bottle stands on the tray but the gripper is still touching it.")
|
| 596 |
+
if delivered:
|
| 597 |
+
tray_txt = "The tray is completely inside the purple delivery area."
|
| 598 |
+
else:
|
| 599 |
+
ex = self.area_excess("deliver_xy")
|
| 600 |
+
out = [f"{max(100 * v, 0.1):.1f} cm beyond its {k} edge" for k, v in ex.items() if v > 0]
|
| 601 |
+
tray_txt = "The tray is not completely inside the purple delivery area: it sticks out " + \
|
| 602 |
+
" and ".join(out) + "."
|
| 603 |
+
if failure in ("not_delivered",):
|
| 604 |
+
parts += [tray_txt] + bottle_txt
|
| 605 |
+
else:
|
| 606 |
+
parts += bottle_txt + [tray_txt]
|
| 607 |
+
if fell_moving:
|
| 608 |
+
how = " while the tray crossed the threshold strip" if fell_sill == fell_moving else \
|
| 609 |
+
" while the tray was moving"
|
| 610 |
+
txt = self._names(fell_moving)
|
| 611 |
+
parts.append(txt[0].upper() + txt[1:] + f" fell over{how}.")
|
| 612 |
+
if failure == "not_static":
|
| 613 |
+
parts.append("Something was still moving at the end.")
|
| 614 |
+
return dict(success=success, failure=failure,
|
| 615 |
+
stages={**{COLOR_OF[b]: bool(bst[b]["ok"]) for b in BOTTLES}, "tray_in_delivery": bool(delivered),
|
| 616 |
+
"loaded_in_loading_area": bool(order_ok), "static": bool(static)},
|
| 617 |
+
events=list(ev), n_regressions=int(n_reg), n_restored=int(n_res),
|
| 618 |
+
order_step=mon["order_step"], left_loading_unloaded=mon["left_unloaded"],
|
| 619 |
+
tray_vmax_loaded=round(mon["tray_vmax_loaded"], 3),
|
| 620 |
+
fell_while_moving=[COLOR_OF[b] for b in fell_moving],
|
| 621 |
+
fell_at_threshold=[COLOR_OF[b] for b in fell_sill], detail=" ".join(parts))
|
| 622 |
+
|
| 623 |
+
# ------------------------------------------------------------ scripted primitives (move_to + gripper only)
|
| 624 |
+
def _slot_world(self, j):
|
| 625 |
+
tp, R = self.tray_pose()
|
| 626 |
+
return tp[:2] + R[:2, :2] @ np.array([SLOT_LX, SLOT_LY[j]])
|
| 627 |
+
|
| 628 |
+
@staticmethod
|
| 629 |
+
def _yaw_window(a):
|
| 630 |
+
"""the gripper-symmetric equivalent of yaw `a` in [-0.5, pi - 0.5) (keeps the last wrist joint off its limit)"""
|
| 631 |
+
return float((a + 0.5) % np.pi - 0.5)
|
| 632 |
+
|
| 633 |
+
def tray_yaw(self):
|
| 634 |
+
return _yaw_of(self.tray_pose()[1])
|
| 635 |
+
|
| 636 |
+
def transit(self, xy, z, yaw=None, z_safe=SAFE_Z):
|
| 637 |
+
"""up to z_safe (if lower), across, then down to z"""
|
| 638 |
+
sk = self.sk
|
| 639 |
+
e = sk.eef_pos()
|
| 640 |
+
if e[2] < z_safe - 0.01:
|
| 641 |
+
sk.move_to([e[0], e[1], z_safe], speed=0.3)
|
| 642 |
+
sk.move_to([xy[0], xy[1], z_safe], yaw=None if yaw is None else self._yaw_window(yaw), wrap_yaw=False)
|
| 643 |
+
sk.move_to([xy[0], xy[1], z], tol=0.003, max_steps=200)
|
| 644 |
+
|
| 645 |
+
def _travel_dir(self):
|
| 646 |
+
tp, R = self.tray_pose()
|
| 647 |
+
u = R[:2, 0] / np.linalg.norm(R[:2, 0])
|
| 648 |
+
foot = tp[:2] + R[:2, :2] @ np.array([FOOT_DX, 0.0])
|
| 649 |
+
return tp, R, u, float((np.asarray(self.inst["deliver_xy"]) - foot) @ u)
|
| 650 |
+
|
| 651 |
+
def push_tray(self, speed, gap=0.03, segments=1, z=PUSH_Z, yaw=None, approach=None):
|
| 652 |
+
"""the pilot agents' move: closed gripper `gap` behind the handle's cross bar (hand's long side along the bar),
|
| 653 |
+
push along the travel direction until the footprint centre is level with the delivery area's centre;
|
| 654 |
+
`segments` > 1 stops in between; `approach` (m/s): first creep up to the bar at that speed, stop, then push"""
|
| 655 |
+
sk = self.sk
|
| 656 |
+
tp, R, u, dist = self._travel_dir()
|
| 657 |
+
back = tp[:2] + R[:2, :2] @ np.array([BACK_X, 0.0])
|
| 658 |
+
if yaw is None: # yaw 0 = fingers closing along world y; this yaw puts the hand's long side across u
|
| 659 |
+
yaw = float(np.arctan2(u[1], u[0]))
|
| 660 |
+
s0 = back - u * (0.012 + gap) # the closed fingers are ~2.4 cm thick along the push
|
| 661 |
+
sk.set_gripper(True, steps=8)
|
| 662 |
+
self.transit(s0, z, yaw=yaw)
|
| 663 |
+
if approach:
|
| 664 |
+
s0 = back - u * 0.010 # just touching
|
| 665 |
+
sk.move_to([s0[0], s0[1], z], speed=approach, tol=0.003, max_steps=int(gap / approach / 0.05) + 40)
|
| 666 |
+
sk.hold(6)
|
| 667 |
+
gap = 0.0
|
| 668 |
+
total = gap + dist
|
| 669 |
+
for k in range(segments):
|
| 670 |
+
e = s0 + u * total * (k + 1) / segments
|
| 671 |
+
sk.move_to([e[0], e[1], z], speed=speed, tol=0.004,
|
| 672 |
+
max_steps=int(total / segments / speed / 0.05) + 60 if speed else 250)
|
| 673 |
+
sk.hold(6)
|
| 674 |
+
e = sk.eef_pos()[:2] - u * 0.03
|
| 675 |
+
sk.move_to([e[0], e[1], z], speed=0.1)
|
| 676 |
+
sk.move_to([e[0], e[1], z + 0.15], speed=0.25)
|
| 677 |
+
|
| 678 |
+
def drag_tray(self, speed, z=DRAG_Z, cross=False):
|
| 679 |
+
"""the careful move: grasp the handle and move the tray with it (the hand keeps the trailing edge down on the
|
| 680 |
+
sill). Default: the stem, fingers closing across its 3 cm width (hand's long side along the tray's long side);
|
| 681 |
+
cross=True: the cross bar, fingers closing across its 2.5 cm depth (hand's long side along the travel)."""
|
| 682 |
+
sk = self.sk
|
| 683 |
+
tp, R, u, dist = self._travel_dir()
|
| 684 |
+
lx = -PLATE[0] - 2 * STEM[0] - CROSS[0] if cross else -PLATE[0] - STEM[0]
|
| 685 |
+
c = tp[:2] + R[:2, :2] @ np.array([lx, 0.0])
|
| 686 |
+
yaw = float(np.arctan2(u[1], u[0])) + (np.pi / 2 if cross else 0.0)
|
| 687 |
+
sk.set_gripper(False, steps=8)
|
| 688 |
+
self.transit(c, z, yaw=yaw)
|
| 689 |
+
sk.set_gripper(True, steps=15)
|
| 690 |
+
e = c + u * dist
|
| 691 |
+
sk.move_to([e[0], e[1], z], speed=speed, tol=0.004,
|
| 692 |
+
max_steps=int(dist / speed / 0.05) + 80 if speed else 250)
|
| 693 |
+
sk.hold(6)
|
| 694 |
+
sk.set_gripper(False, steps=12)
|
| 695 |
+
e = sk.eef_pos()
|
| 696 |
+
sk.move_to([e[0], e[1], e[2] + 0.15], speed=0.25)
|
| 697 |
+
|
| 698 |
+
def pick_upright(self, b, jitter=None, yaw=0.0):
|
| 699 |
+
"""grasp the neck of a standing bottle from above (the palm stays above the bottle's top)"""
|
| 700 |
+
sk = self.sk
|
| 701 |
+
p = envs.obj_pos(self.env, b)
|
| 702 |
+
top = envs.obj_max_z(self.env, b)
|
| 703 |
+
xy = p[:2] + (np.zeros(2) if jitter is None else jitter)
|
| 704 |
+
sk.set_gripper(False, steps=8)
|
| 705 |
+
self.transit(xy, top - GRASP_TOP, yaw)
|
| 706 |
+
sk.set_gripper(True, steps=15)
|
| 707 |
+
sk.move_to([xy[0], xy[1], SAFE_Z_HELD], speed=0.25)
|
| 708 |
+
return sk.eef_pos()[2] - envs.obj_min_z(self.env, b) # grasp height actually held
|
| 709 |
+
|
| 710 |
+
def place_at(self, b, xy, held_h, release=0.006):
|
| 711 |
+
sk = self.sk
|
| 712 |
+
self.transit(xy, PLATE_TOP + release + held_h + 0.03, z_safe=SAFE_Z_HELD)
|
| 713 |
+
sk.hold(10) # let a hanging bottle stop swinging
|
| 714 |
+
sk.move_to([xy[0], xy[1], PLATE_TOP + release + held_h], speed=0.08, tol=0.003, max_steps=150)
|
| 715 |
+
sk.hold(4)
|
| 716 |
+
sk.set_gripper(False, steps=12)
|
| 717 |
+
sk.move_to([xy[0], xy[1], SAFE_Z], speed=0.25)
|
| 718 |
+
|
| 719 |
+
def load_all(self, rng=None):
|
| 720 |
+
"""every bottle goes to the tray slot on the same side as its start position (a carried bottle never passes
|
| 721 |
+
over a standing one); the hand's long side across the row. With `rng`: +-5 mm on every grasp / placement."""
|
| 722 |
+
tp, R = self.tray_pose()
|
| 723 |
+
ay = R[:2, 1]
|
| 724 |
+
yaw = self.tray_yaw() - np.pi / 2
|
| 725 |
+
by_y = sorted(BOTTLES, key=lambda b: float(np.asarray(self.inst["bottle_start"][b][:2]) @ ay))
|
| 726 |
+
for j, b in enumerate(by_y):
|
| 727 |
+
jg, jp = (None, None) if rng is None else (rng.uniform(-0.005, 0.005, 2), rng.uniform(-0.005, 0.005, 2))
|
| 728 |
+
h = self.pick_upright(b, jitter=jg, yaw=yaw)
|
| 729 |
+
self.place_at(b, self._slot_world(j) + (0 if jp is None else jp), h)
|
| 730 |
+
|
| 731 |
+
def free_slot(self, exclude):
|
| 732 |
+
"""a tray slot at least 7 cm from every other bottle (standing or lying); among those the one farthest from the
|
| 733 |
+
robot; else the emptiest slot"""
|
| 734 |
+
tp, R = self.tray_pose()
|
| 735 |
+
others = [R[:2, :2].T @ (self.bottle_state(o)["pos"][:2] - tp[:2]) for o in BOTTLES if o not in exclude]
|
| 736 |
+
cand = []
|
| 737 |
+
for j, ly in enumerate(SLOT_LY):
|
| 738 |
+
dmin = min([np.linalg.norm(np.array([SLOT_LX, ly]) - o) for o in others] + [1.0])
|
| 739 |
+
cand.append((dmin >= 0.07, float(self._slot_world(j)[0]) if dmin >= 0.07 else dmin, j))
|
| 740 |
+
return self._slot_world(max(cand)[2])
|
| 741 |
+
|
| 742 |
+
def restand(self, b):
|
| 743 |
+
"""a fallen bottle: grasp its neck across (fingers closing across the neck), lift -- it swings down and hangs
|
| 744 |
+
from the neck -- and set it down on a free slot. A bottle standing off the tray: pick it up by the neck."""
|
| 745 |
+
sk = self.sk
|
| 746 |
+
st = self.bottle_state(b)
|
| 747 |
+
if st["upright"]:
|
| 748 |
+
h = self.pick_upright(b, yaw=self.tray_yaw() - np.pi / 2)
|
| 749 |
+
self.place_at(b, self.free_slot({b}), h)
|
| 750 |
+
return
|
| 751 |
+
for tries in range(2):
|
| 752 |
+
st = self.bottle_state(b)
|
| 753 |
+
R = self.env.sim.data.body_xmat[self.bid[b]].reshape(3, 3)
|
| 754 |
+
ax = R[:, 2] # bottle axis (bottom -> neck)
|
| 755 |
+
u = ax[:2] / max(np.linalg.norm(ax[:2]), 1e-6)
|
| 756 |
+
neck = st["pos"] + ax * (BH - GRASP_TOP)
|
| 757 |
+
yaw = float(np.arctan2(u[1], u[0])) # fingers close across the neck
|
| 758 |
+
sk.set_gripper(False, steps=8)
|
| 759 |
+
self.transit(neck[:2], max(neck[2], envs.TABLE_Z + 0.008), yaw)
|
| 760 |
+
sk.set_gripper(True, steps=15)
|
| 761 |
+
if sk.holding(b) or tries:
|
| 762 |
+
break
|
| 763 |
+
# a finger landed on the tray's edge next to the neck: slide the bottle 5 cm away from the tray, retry
|
| 764 |
+
tp = self.tray_pose()[0]
|
| 765 |
+
v = st["pos"][:2] - tp[:2]
|
| 766 |
+
v = v / max(np.linalg.norm(v), 1e-6)
|
| 767 |
+
sk.set_gripper(False, steps=8)
|
| 768 |
+
sk.move_to(sk.eef_pos() + [0.0, 0.0, 0.05], speed=0.1)
|
| 769 |
+
self.push_point(st["pos"][:2] - v * 0.015, v, 0.065, speed=0.05, z=PLATE_TOP + 0.012)
|
| 770 |
+
sk.move_to([neck[0], neck[1], SAFE_Z_HELD], speed=0.15)
|
| 771 |
+
sk.hold(20)
|
| 772 |
+
held = sk.eef_pos()[2] - envs.obj_min_z(self.env, b)
|
| 773 |
+
self.place_at(b, self.free_slot({b}), held)
|
| 774 |
+
|
| 775 |
+
def push_point(self, p, u, dist, speed=0.03, z=None):
|
| 776 |
+
"""closed gripper: from 3 cm behind point `p` (direction `u`) push `dist` metres along u, back off, lift"""
|
| 777 |
+
sk = self.sk
|
| 778 |
+
z = PUSH_Z if z is None else z
|
| 779 |
+
s0 = np.asarray(p) - u * 0.03
|
| 780 |
+
sk.set_gripper(True, steps=8)
|
| 781 |
+
self.transit(s0, z, yaw=float(np.arctan2(u[1], u[0])))
|
| 782 |
+
e = s0 + u * (0.018 + dist)
|
| 783 |
+
sk.move_to([e[0], e[1], z], speed=speed, tol=0.003, max_steps=600)
|
| 784 |
+
sk.hold(4)
|
| 785 |
+
e = sk.eef_pos()[:2] - u * 0.03
|
| 786 |
+
sk.move_to([e[0], e[1], z], speed=0.1)
|
| 787 |
+
sk.move_to([e[0], e[1], SAFE_Z], speed=0.25)
|
| 788 |
+
|
| 789 |
+
def fix_tray(self, speed=V_CAREFUL):
|
| 790 |
+
"""straighten the tray by slowly pushing the trailing corner that lags behind, then grasp the handle's stem
|
| 791 |
+
and move the tray, without turning it, until its footprint is centred in the delivery area"""
|
| 792 |
+
sk = self.sk
|
| 793 |
+
y1 = self.inst["area_yaw"]
|
| 794 |
+
u1 = _rotz2(y1)[:, 0]
|
| 795 |
+
for _ in range(3):
|
| 796 |
+
err = (self.tray_yaw() - y1 + np.pi) % (2 * np.pi) - np.pi
|
| 797 |
+
if abs(err) < np.radians(3):
|
| 798 |
+
break
|
| 799 |
+
tp, R = self.tray_pose()
|
| 800 |
+
corners = [tp[:2] + R[:2, :2] @ np.array([-PLATE[0], e * (PLATE[1] - 0.02)]) for e in (1.0, -1.0)]
|
| 801 |
+
a = [float((c - tp[:2]) @ u1) for c in corners]
|
| 802 |
+
k = int(np.argmin(a))
|
| 803 |
+
self.push_point(corners[k], u1, 0.6 * (max(a) - min(a)), speed=speed)
|
| 804 |
+
tp, R = self.tray_pose()
|
| 805 |
+
h0 = tp[:2] + R[:2, :2] @ np.array([-PLATE[0] - STEM[0], 0.0])
|
| 806 |
+
foot = tp[:2] + R[:2, :2] @ np.array([FOOT_DX, 0.0])
|
| 807 |
+
h1 = h0 + (np.asarray(self.inst["deliver_xy"]) - foot)
|
| 808 |
+
d = float(np.linalg.norm(h1 - h0))
|
| 809 |
+
if d < 0.004:
|
| 810 |
+
return
|
| 811 |
+
sk.set_gripper(False, steps=8)
|
| 812 |
+
self.transit(h0, DRAG_Z, yaw=self.tray_yaw()) # fingers close across the stem's width
|
| 813 |
+
sk.set_gripper(True, steps=15)
|
| 814 |
+
sk.move_to([h1[0], h1[1], DRAG_Z], speed=speed, tol=0.003, max_steps=int(d / speed / 0.05) + 80)
|
| 815 |
+
sk.hold(5)
|
| 816 |
+
sk.set_gripper(False, steps=12)
|
| 817 |
+
e = sk.eef_pos()
|
| 818 |
+
sk.move_to([e[0], e[1], SAFE_Z], speed=0.2)
|
| 819 |
+
|
| 820 |
+
def check_and_restore(self, rounds=3):
|
| 821 |
+
"""the final check: bottles not upright on the tray -> stand them up on a free slot (farthest from the robot
|
| 822 |
+
first); then, if the tray is not completely in the delivery area, move it there slowly by the handle"""
|
| 823 |
+
for _ in range(rounds):
|
| 824 |
+
bad = [b for b in BOTTLES if not self.bottle_state(b)["ok"]]
|
| 825 |
+
if not bad and self.tray_inside("deliver_xy"):
|
| 826 |
+
return
|
| 827 |
+
for b in sorted(bad, key=lambda o: -float(self.bottle_state(o)["pos"][0])):
|
| 828 |
+
self.restand(b)
|
| 829 |
+
self.sk.hold(10)
|
| 830 |
+
if not self.tray_inside("deliver_xy"):
|
| 831 |
+
self.fix_tray()
|
| 832 |
+
self.sk.hold(10)
|
| 833 |
+
|
| 834 |
+
def execute(self, inst, params):
|
| 835 |
+
rng = np.random.default_rng(params.get("seed")) if params.get("jitter") else None
|
| 836 |
+
self.load_all(rng)
|
| 837 |
+
if params.get("mode", "push") == "drag":
|
| 838 |
+
self.drag_tray(params["speed"])
|
| 839 |
+
else:
|
| 840 |
+
self.push_tray(params["speed"], gap=params.get("gap", 0.03), segments=params.get("segments", 1))
|
| 841 |
+
if params.get("check"):
|
| 842 |
+
self.check_and_restore()
|
| 843 |
+
|
| 844 |
+
def default_params(self, inst):
|
| 845 |
+
"""naive = the pilot agents' style: load all three, push the handle with the closed gripper at ~4.5 cm/s"""
|
| 846 |
+
return dict(speed=V_NAIVE, mode="push", check=False)
|
| 847 |
+
|
| 848 |
+
def oracle_params(self, inst):
|
| 849 |
+
return dict(speed=V_CAREFUL, mode="drag", check=True)
|
| 850 |
+
|
| 851 |
+
def adapt_params(self, inst, history):
|
| 852 |
+
return dict(speed=V_CAREFUL, mode="drag", check=True)
|
| 853 |
+
|
| 854 |
+
def blind_params(self, inst, attempt, rng):
|
| 855 |
+
return dict(speed=float(rng.uniform(0.03, 0.06)), mode="push", segments=int(rng.integers(1, 3)),
|
| 856 |
+
check=False, jitter=True, seed=int(rng.integers(1 << 30)))
|
| 857 |
+
|
| 858 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 859 |
+
"""cross protocol; adaptive = naive + check-and-restore in attempt 1, careful (drag by the handle) + check
|
| 860 |
+
afterwards"""
|
| 861 |
+
k = k or self.max_attempts
|
| 862 |
+
rng = np.random.default_rng(seed)
|
| 863 |
+
history = []
|
| 864 |
+
for a in range(k):
|
| 865 |
+
self.reset_instance(inst)
|
| 866 |
+
if kind == "oracle":
|
| 867 |
+
params = self.oracle_params(inst)
|
| 868 |
+
elif kind == "naive":
|
| 869 |
+
params = self.default_params(inst)
|
| 870 |
+
elif kind == "adaptive":
|
| 871 |
+
params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history)
|
| 872 |
+
elif kind == "blind":
|
| 873 |
+
params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
|
| 874 |
+
else:
|
| 875 |
+
raise ValueError(kind)
|
| 876 |
+
self.execute(inst, params)
|
| 877 |
+
out = self.outcome(inst)
|
| 878 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 879 |
+
if on_attempt:
|
| 880 |
+
on_attempt(a, params, out)
|
| 881 |
+
if out["success"] or kind in ("oracle", "naive"):
|
| 882 |
+
break
|
| 883 |
+
return history
|
leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/agent/harness.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Protocol controller: runs a backend on task instances, attempt by attempt.
|
| 2 |
+
|
| 3 |
+
cross protocol : reset to the same instance (same layout + hidden variables) before every attempt
|
| 4 |
+
within protocol: one continuous episode; each `done` call closes a segment ("attempt") that is checked;
|
| 5 |
+
the agent continues from the current state if it failed and budget remains
|
| 6 |
+
Both protocols pack finished attempts the same way (keyframes <= 4, action summary, feedback F0/F1/F2) and
|
| 7 |
+
show them according to the memory mode (none / full / last / mismatched).
|
| 8 |
+
"""
|
| 9 |
+
import time
|
| 10 |
+
from dataclasses import asdict, dataclass, field
|
| 11 |
+
|
| 12 |
+
from .context import (FEEDBACK_LEVELS, MEMORY_MODES, AttemptRecord, Conversation, PromptBuilder, StepRecord,
|
| 13 |
+
pick_keyframes, select_history, summarize_actions)
|
| 14 |
+
from .cost import call_cost, estimate_request_tokens
|
| 15 |
+
from .metrics import run_summary
|
| 16 |
+
from .backends.base import AttemptInfo, RunInfo
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@dataclass
|
| 20 |
+
class HarnessConfig:
|
| 21 |
+
memory: str = "full"
|
| 22 |
+
feedback: str = "F2"
|
| 23 |
+
k: int = None # attempts (cross) / done calls (within); default task.max_attempts
|
| 24 |
+
image_res: int = 512
|
| 25 |
+
keyframe_res: int = None # default = image_res
|
| 26 |
+
n_keyframes: int = 4
|
| 27 |
+
cams: tuple = ("agentview", "wrist")
|
| 28 |
+
auto_obs: bool = True # send new images after every action tool
|
| 29 |
+
max_steps: int = 30 # tool calls per attempt
|
| 30 |
+
max_no_tool: int = 3 # consecutive replies without a tool call before the attempt is ended
|
| 31 |
+
privileged_locate: bool = False
|
| 32 |
+
grasp_report: str = "bool" # "bool" | "name" | "none"
|
| 33 |
+
instruction: str = "direct" # "direct" | "indirect"
|
| 34 |
+
early_stop: str = "auto" # "auto" (stop at first success unless F0), "yes", "no"
|
| 35 |
+
settle_within: int = 20 # control steps held still before checking a within-protocol segment
|
| 36 |
+
jpeg_quality: int = 90
|
| 37 |
+
save_images: bool = True
|
| 38 |
+
model_for_cost: str = "gpt-6-astra"
|
| 39 |
+
extra: dict = field(default_factory=dict)
|
| 40 |
+
|
| 41 |
+
def validate(self):
|
| 42 |
+
assert self.memory in MEMORY_MODES, self.memory
|
| 43 |
+
assert self.feedback in FEEDBACK_LEVELS, self.feedback
|
| 44 |
+
assert self.grasp_report in ("bool", "name", "none")
|
| 45 |
+
assert self.instruction in ("direct", "indirect")
|
| 46 |
+
assert self.early_stop in ("auto", "yes", "no")
|
| 47 |
+
assert 1 <= self.n_keyframes <= 4 or self.n_keyframes == 0
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def clean_inst(inst):
|
| 51 |
+
return {k: v for k, v in inst.items() if not str(k).startswith("_")}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class AgentHarness:
|
| 55 |
+
def __init__(self, task, backend, cfg: HarnessConfig, logger, payload_probe=None, executor_factory=None,
|
| 56 |
+
cam_axes=None):
|
| 57 |
+
cfg.validate()
|
| 58 |
+
self.task, self.backend, self.cfg, self.log = task, backend, cfg, logger
|
| 59 |
+
self.protocol = getattr(task, "protocol", "cross")
|
| 60 |
+
self.k = cfg.k or task.max_attempts
|
| 61 |
+
self.payload_probe = payload_probe # optional OpenAIResponsesBackend used only to size requests (dry run)
|
| 62 |
+
self.executor_factory = executor_factory # tests: build a fake executor instead of ToolExecutor
|
| 63 |
+
self._cam_axes = cam_axes
|
| 64 |
+
|
| 65 |
+
# ------------------------------------------------------------------ helpers
|
| 66 |
+
def instruction(self, inst):
|
| 67 |
+
hook = getattr(self.task, "agent_instruction", None)
|
| 68 |
+
if hook is not None:
|
| 69 |
+
return hook(inst, self.cfg.instruction)
|
| 70 |
+
if self.cfg.instruction == "indirect" and getattr(self.task, "instruction_indirect", ""):
|
| 71 |
+
return self.task.instruction_indirect
|
| 72 |
+
return self.task.instruction
|
| 73 |
+
|
| 74 |
+
def feedback(self, inst, out, level):
|
| 75 |
+
import inspect
|
| 76 |
+
fn = self.task.feedback
|
| 77 |
+
if "indirect" in inspect.signature(fn).parameters: # tasks that phrase feedback per instruction variant
|
| 78 |
+
return fn(inst, out, level, indirect=self.cfg.instruction == "indirect")
|
| 79 |
+
return fn(inst, out, level)
|
| 80 |
+
|
| 81 |
+
def early_stop(self):
|
| 82 |
+
if self.cfg.early_stop == "auto":
|
| 83 |
+
return self.cfg.feedback != "F0"
|
| 84 |
+
return self.cfg.early_stop == "yes"
|
| 85 |
+
|
| 86 |
+
def terminal(self, out):
|
| 87 |
+
hook = getattr(self.task, "is_terminal", None)
|
| 88 |
+
if hook is not None:
|
| 89 |
+
return bool(hook(out))
|
| 90 |
+
return bool(out.get("terminal") or out.get("overshoot"))
|
| 91 |
+
|
| 92 |
+
def _executor(self, inst):
|
| 93 |
+
if self.executor_factory is not None:
|
| 94 |
+
return self.executor_factory(self, inst)
|
| 95 |
+
from .tools import ToolExecutor
|
| 96 |
+
return ToolExecutor(self.task, inst, image_res=self.cfg.image_res, cams=self.cfg.cams,
|
| 97 |
+
privileged_locate=self.cfg.privileged_locate, grasp_report=self.cfg.grasp_report,
|
| 98 |
+
jpeg_quality=self.cfg.jpeg_quality, image_sink=self._sink)
|
| 99 |
+
|
| 100 |
+
def _sink(self, ref):
|
| 101 |
+
self._img_counter += 1
|
| 102 |
+
rel = f"seed{self._seed}/a{self._attempt}_s{self._step:02d}_{self._img_counter:03d}_{ref.camera}.jpg"
|
| 103 |
+
return self.log.save_image(ref, rel)
|
| 104 |
+
|
| 105 |
+
def _keyframe(self, ref):
|
| 106 |
+
"""Separate (possibly smaller) copy of an agentview frame for the history."""
|
| 107 |
+
from .images import ImageRef
|
| 108 |
+
kres = self.cfg.keyframe_res or self.cfg.image_res
|
| 109 |
+
kf = ImageRef(camera=ref.camera, array=ref.array, label=ref.label)
|
| 110 |
+
if kres == self.cfg.image_res:
|
| 111 |
+
kf.jpeg, kf.path = ref.jpeg, ref.path
|
| 112 |
+
return kf
|
| 113 |
+
self._img_counter += 1
|
| 114 |
+
rel = f"seed{self._seed}/a{self._attempt}_key_{self._img_counter:03d}_{ref.camera}.jpg"
|
| 115 |
+
return self.log.save_image(kf, rel, res=kres)
|
| 116 |
+
|
| 117 |
+
def prompts(self, executor):
|
| 118 |
+
if self._cam_axes is None:
|
| 119 |
+
from . import camera as C
|
| 120 |
+
self._cam_axes = {c: C.describe_axes(self.task.env, c, self.cfg.image_res) for c in C.CAMERAS}
|
| 121 |
+
names = getattr(self.task, "agent_object_names", None) or list(self.task.env.objects_dict)
|
| 122 |
+
return PromptBuilder(self.task, self.protocol, self.k, self.cfg.memory, self.cfg.feedback, self.cfg.image_res,
|
| 123 |
+
self._cam_axes, privileged_locate=self.cfg.privileged_locate, object_names=names,
|
| 124 |
+
grasp_report=self.cfg.grasp_report, cams=self.cfg.cams)
|
| 125 |
+
|
| 126 |
+
# ------------------------------------------------------------------ run
|
| 127 |
+
def run_instance(self, seed, donor=None):
|
| 128 |
+
"""donor: AttemptRecords of another instance (memory=mismatched). Returns (summary, records)."""
|
| 129 |
+
task, cfg = self.task, self.cfg
|
| 130 |
+
inst = task.sample_instance(seed)
|
| 131 |
+
self._seed, self._attempt, self._step, self._img_counter = seed, 0, 0, 0
|
| 132 |
+
self._llm_calls = []
|
| 133 |
+
t_run = time.time()
|
| 134 |
+
sim_wall = 0.0
|
| 135 |
+
info = RunInfo(task=task, inst=inst, seed=seed, k=self.k, protocol=self.protocol, feedback=cfg.feedback,
|
| 136 |
+
memory=cfg.memory)
|
| 137 |
+
self.backend.begin_run(info)
|
| 138 |
+
self.log.event("run_start", seed=seed, inst=clean_inst(inst), task=task.name, protocol=self.protocol, k=self.k,
|
| 139 |
+
memory=cfg.memory, feedback=cfg.feedback, donor_seed=donor[0].seed if donor else None)
|
| 140 |
+
records, executor, status = [], None, "ok"
|
| 141 |
+
for a in range(1, self.k + 1):
|
| 142 |
+
self._attempt, self._step = a, 0
|
| 143 |
+
if self.protocol == "cross" or executor is None:
|
| 144 |
+
t0 = time.time()
|
| 145 |
+
task.reset_instance(inst)
|
| 146 |
+
executor = self._executor(inst)
|
| 147 |
+
sim_wall += time.time() - t0
|
| 148 |
+
visible = select_history(cfg.memory, records, donor)
|
| 149 |
+
rec, attempt_sim = self._attempt_loop(inst, seed, a, visible, executor,
|
| 150 |
+
continuing=self.protocol == "within" and a > 1)
|
| 151 |
+
sim_wall += attempt_sim
|
| 152 |
+
records.append(rec)
|
| 153 |
+
if rec.ended_by == "backend_error":
|
| 154 |
+
status = "error"
|
| 155 |
+
break
|
| 156 |
+
if rec.success and self.early_stop():
|
| 157 |
+
break
|
| 158 |
+
if self.protocol == "within" and (rec.success or self.terminal(rec.outcome)):
|
| 159 |
+
break
|
| 160 |
+
self.backend.end_run()
|
| 161 |
+
summ = run_summary(seed, records, self.k, status=status, llm_calls=self._llm_calls,
|
| 162 |
+
extra=dict(sim_wall_s=round(sim_wall, 2), wall_s=round(time.time() - t_run, 2),
|
| 163 |
+
donor_seed=donor[0].seed if donor else None))
|
| 164 |
+
self.log.event("run_end", **summ)
|
| 165 |
+
summ["_llm_calls"] = self._llm_calls
|
| 166 |
+
return summ, records
|
| 167 |
+
|
| 168 |
+
def _attempt_loop(self, inst, seed, a, visible, ex, continuing):
|
| 169 |
+
cfg, task, backend = self.cfg, self.task, self.backend
|
| 170 |
+
P = self.prompts(ex)
|
| 171 |
+
tools = self.tool_specs()
|
| 172 |
+
conv = Conversation(P.system_prompt())
|
| 173 |
+
backend.begin_attempt(AttemptInfo(attempt=a, history=visible, continuing=continuing))
|
| 174 |
+
sim_t = 0.0
|
| 175 |
+
t0 = time.time()
|
| 176 |
+
obs0 = ex.observe(label="start")
|
| 177 |
+
sim_t += time.time() - t0
|
| 178 |
+
conv.add_user(P.history_parts(self.instruction(inst), visible), live=False)
|
| 179 |
+
conv.add_user(P.current_parts(a, obs0, ex.proprio(), continuing), live=True)
|
| 180 |
+
steps, diagnosis, done_reason, ended_by = [], None, None, None
|
| 181 |
+
n_calls, no_tool = 0, 0
|
| 182 |
+
while ended_by is None:
|
| 183 |
+
if len(steps) >= cfg.max_steps:
|
| 184 |
+
ended_by = "step_budget"
|
| 185 |
+
break
|
| 186 |
+
try:
|
| 187 |
+
resp = backend.act(conv, tools)
|
| 188 |
+
except Exception as e: # API failure after retries, crashed scripted policy, ...
|
| 189 |
+
self.log.event("llm_error", seed=seed, attempt=a, call=n_calls + 1, error=repr(e)[:4000])
|
| 190 |
+
ended_by = "backend_error"
|
| 191 |
+
break
|
| 192 |
+
n_calls += 1
|
| 193 |
+
call_rec = self._log_llm_call(seed, a, n_calls, resp, conv, tools)
|
| 194 |
+
self._llm_calls.append(call_rec)
|
| 195 |
+
if n_calls == 1 and resp.text:
|
| 196 |
+
diagnosis = resp.text
|
| 197 |
+
conv.add_assistant(resp.text, resp.tool_calls, raw=resp.raw, backend=backend.name)
|
| 198 |
+
if not resp.tool_calls:
|
| 199 |
+
no_tool += 1
|
| 200 |
+
if no_tool >= cfg.max_no_tool:
|
| 201 |
+
ended_by = "no_tool_call"
|
| 202 |
+
break
|
| 203 |
+
conv.add_user(P.nudge(), live=True)
|
| 204 |
+
continue
|
| 205 |
+
no_tool = 0
|
| 206 |
+
acted = None
|
| 207 |
+
for tc in resp.tool_calls:
|
| 208 |
+
self._step = len(steps) + 1
|
| 209 |
+
res = ex.call(tc.name, tc.raw_arguments or tc.arguments)
|
| 210 |
+
sim_t += res.wall_s
|
| 211 |
+
conv.add_tool_output(tc.id, tc.name, res.text())
|
| 212 |
+
backend.on_tool_result(tc, res)
|
| 213 |
+
st = StepRecord(step=self._step, name=tc.name, args=res.args, report=res.report, ok=res.ok,
|
| 214 |
+
wall_s=round(res.wall_s, 3), sim_steps=res.sim_steps)
|
| 215 |
+
steps.append(st)
|
| 216 |
+
if res.images:
|
| 217 |
+
conv.add_user(P.observation_parts(f"Images returned by get_observation (step {self._step})",
|
| 218 |
+
res.images, ex.proprio()), live=True)
|
| 219 |
+
if tc.name in ("move_to", "open_gripper", "close_gripper", "push") and res.ok:
|
| 220 |
+
acted = st
|
| 221 |
+
self.log.event("tool_call", seed=seed, attempt=a, step=self._step, call_id=tc.id, name=tc.name,
|
| 222 |
+
args=res.args, ok=res.ok, report=res.report, wall_s=round(res.wall_s, 3),
|
| 223 |
+
sim_steps=res.sim_steps, images=[i.path for i in res.images])
|
| 224 |
+
if res.ended:
|
| 225 |
+
done_reason = res.args.get("reason")
|
| 226 |
+
ended_by = "done"
|
| 227 |
+
break
|
| 228 |
+
if len(steps) >= cfg.max_steps:
|
| 229 |
+
break
|
| 230 |
+
if ended_by is None and acted is not None:
|
| 231 |
+
t1 = time.time()
|
| 232 |
+
if cfg.auto_obs:
|
| 233 |
+
obs = ex.observe(label=f"step{acted.step}")
|
| 234 |
+
conv.add_user(P.step_observation(acted.step, acted.name, obs, ex.proprio()), live=True)
|
| 235 |
+
acted.frame = next((o for o in obs if o.camera == "agentview"), obs[0])
|
| 236 |
+
else: # still keep an agentview frame for the history keyframes / logs
|
| 237 |
+
from .images import ImageRef
|
| 238 |
+
acted.frame = self._sink(ImageRef(camera="agentview", array=ex.render("agentview"),
|
| 239 |
+
label=f"step{acted.step}"))
|
| 240 |
+
sim_t += time.time() - t1
|
| 241 |
+
self.log.event("observation", seed=seed, attempt=a, step=acted.step,
|
| 242 |
+
images=[acted.frame.path] if not cfg.auto_obs else [o.path for o in obs],
|
| 243 |
+
proprio=ex.proprio())
|
| 244 |
+
meta = backend.end_attempt() or {}
|
| 245 |
+
# ------------------------------------------------------------ outcome + packing
|
| 246 |
+
t1 = time.time()
|
| 247 |
+
home = getattr(task, "go_home", None) # task-defined end-of-attempt motion (e.g. L6: arm out of view)
|
| 248 |
+
if home is not None and ended_by != "backend_error":
|
| 249 |
+
home()
|
| 250 |
+
if self.protocol == "within" and cfg.settle_within:
|
| 251 |
+
ex.sk.hold(cfg.settle_within)
|
| 252 |
+
out = task.outcome(inst)
|
| 253 |
+
from .images import ImageRef
|
| 254 |
+
self._step = 99
|
| 255 |
+
final = self._sink(ImageRef(camera="agentview", array=ex.render("agentview", cfg.keyframe_res or cfg.image_res),
|
| 256 |
+
label="end"))
|
| 257 |
+
sim_t += time.time() - t1
|
| 258 |
+
fb = self.feedback(inst, out, cfg.feedback)
|
| 259 |
+
fb_full = self.feedback(inst, out, "F2")
|
| 260 |
+
init_frame = next((o for o in obs0 if o.camera == "agentview"), None)
|
| 261 |
+
for s in steps:
|
| 262 |
+
if s.frame is not None and (cfg.keyframe_res or cfg.image_res) != cfg.image_res:
|
| 263 |
+
s.frame = self._keyframe(s.frame)
|
| 264 |
+
if init_frame is not None and (cfg.keyframe_res or cfg.image_res) != cfg.image_res:
|
| 265 |
+
init_frame = self._keyframe(init_frame)
|
| 266 |
+
kfs = pick_keyframes(steps, init_frame, final, cfg.n_keyframes) if cfg.n_keyframes else []
|
| 267 |
+
rec = AttemptRecord(seed=seed, attempt=a, steps=steps, keyframes=kfs, outcome=dict(out),
|
| 268 |
+
success=bool(out.get("success")), feedback=fb, done_reason=done_reason, diagnosis=diagnosis,
|
| 269 |
+
ended_by=ended_by, backend_meta=meta)
|
| 270 |
+
calls = [c for c in self._llm_calls if c["attempt"] == a]
|
| 271 |
+
self.log.event("attempt_end", seed=seed, attempt=a, success=rec.success, outcome=out, feedback_shown=fb,
|
| 272 |
+
feedback_f2=fb_full, ended_by=ended_by, done_reason=done_reason, diagnosis=diagnosis,
|
| 273 |
+
n_steps=len(steps), n_llm_calls=len(calls), backend_meta=meta,
|
| 274 |
+
history_shown=[(h.seed, h.attempt) for h in visible],
|
| 275 |
+
keyframes=[(c, r.path) for c, r in kfs], action_summary=summarize_actions(steps),
|
| 276 |
+
llm_latency_s=round(sum(c["latency_s"] for c in calls), 3), sim_wall_s=round(sim_t, 3))
|
| 277 |
+
return rec, sim_t
|
| 278 |
+
|
| 279 |
+
def tool_specs(self):
|
| 280 |
+
from .tools import tool_specs
|
| 281 |
+
names = getattr(self.task, "agent_object_names", None) or list(self.task.env.objects_dict)
|
| 282 |
+
return tool_specs(self.cfg.privileged_locate, names, self.cfg.image_res)
|
| 283 |
+
|
| 284 |
+
def _log_llm_call(self, seed, a, n, resp, conv, tools):
|
| 285 |
+
rec = dict(seed=seed, attempt=a, call=n, latency_s=round(resp.latency_s, 3), usage=resp.usage,
|
| 286 |
+
cost_usd=call_cost(resp.usage, self.cfg.model_for_cost) if resp.usage else None,
|
| 287 |
+
status=resp.status, error=resp.error, text=resp.text, reasoning_summary=resp.reasoning_summary,
|
| 288 |
+
reasoning_summary_status="recorded" if resp.reasoning_summary else "not_returned",
|
| 289 |
+
tool_calls=[dict(id=t.id, name=t.name, arguments=t.arguments) for t in resp.tool_calls],
|
| 290 |
+
request=resp.request_stats, conv_images=conv.n_images())
|
| 291 |
+
if self.payload_probe is not None: # dry run: size of the request GPT-6 would have received
|
| 292 |
+
stats = self.payload_probe.request_stats(self.payload_probe.build_request(conv, tools))
|
| 293 |
+
stats["est_input_tokens"] = estimate_request_tokens(stats, self.cfg.image_res)
|
| 294 |
+
rec["dry_run_request"] = stats
|
| 295 |
+
self.log.event("llm_call", **rec)
|
| 296 |
+
return rec
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def config_dict(cfg):
|
| 300 |
+
return asdict(cfg)
|
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/l4_nest.py
ADDED
|
@@ -0,0 +1,644 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L4-C nest_order: nest three cups one inside another; the tallest cup is not the widest.
|
| 2 |
+
|
| 3 |
+
Scene: three open round cups (red, green, blue; 1.5 mm walls leaning outwards by TAPER_DEG = 5 deg, like slightly
|
| 4 |
+
flared tumblers) stand apart on the table. Each cup has its own bottom width and its own height (re-drawn per
|
| 5 |
+
instance, 3.5-10 cm tall). Cups are resized per instance by editing their geoms in sim.model (wall segments +
|
| 6 |
+
floor), so one env serves every instance (same technique as l4_fit_container).
|
| 7 |
+
|
| 8 |
+
Trap (common sense): "the bigger cup goes outside", and a cup looks big mostly by its height. On (1 - P_AGREE) of
|
| 9 |
+
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.
|
| 10 |
+
Their openings then differ by only 3-9 mm in diameter, and from the wrist camera at its start height the taller
|
| 11 |
+
one's opening is closer to the camera and looks about as big (about half the instances: bigger); from the front
|
| 12 |
+
camera the taller one looks clearly bigger. The narrowest cup is the shortest, so the very first move of the naive
|
| 13 |
+
order (widest cup into the tallest one) already fails, out on the table.
|
| 14 |
+
|
| 15 |
+
A variant where the innermost cup was taller than the middle one (and the widest cup the tallest) was dropped
|
| 16 |
+
2026-10-08: its failure (middle cup on the rim of the innermost cup, both inside the outer one) looked like a nest
|
| 17 |
+
from both cameras -- the same flaw as the 14-deg version.
|
| 18 |
+
|
| 19 |
+
What the failure looks like (the point of this version, user review 2026-10-08): which cup fits into which is
|
| 20 |
+
decided by the bottoms (same flare for all cups), and the sizes are drawn so that a cup whose bottom is too wide
|
| 21 |
+
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
|
| 22 |
+
= 0.5 cm below the rim. So a wrong placement leaves a cup standing on top of another one, its whole body above the
|
| 23 |
+
rim: visible in both cameras without any text feedback. A cup that fits goes down to the floor (centring tolerance
|
| 24 |
+
>= TOL_MIN = 7.5 mm thanks to the flare); in the right nest the taller, narrower cups stick out of the shorter,
|
| 25 |
+
wider ones, but each stands inside the next.
|
| 26 |
+
|
| 27 |
+
Prior (naive): tallest cup outermost, then the next tallest. Learner: a cup that ended up on top of another cup
|
| 28 |
+
must go outside it; swap that pair. Feedback F1 (default) says only failed / succeeded; F2 (ablation) describes
|
| 29 |
+
which cup stands in / on which, in words, with no sizes or positions.
|
| 30 |
+
|
| 31 |
+
Only move_to / open / close are needed: grasp a cup across its upper wall, carry it over the other cup, release it
|
| 32 |
+
just above that cup's rim.
|
| 33 |
+
"""
|
| 34 |
+
import itertools
|
| 35 |
+
|
| 36 |
+
import numpy as np
|
| 37 |
+
|
| 38 |
+
from .. import envs
|
| 39 |
+
from ..bddl import write_bddl
|
| 40 |
+
from ..objects import _SOLID, _fmt, _wrap, register_generated
|
| 41 |
+
from ..skills import _rot_err
|
| 42 |
+
from ..task_base import LFFTask, register_task
|
| 43 |
+
|
| 44 |
+
N_SEG = 20 # wall segments per cup (regular polygon)
|
| 45 |
+
TAN_SEG = float(np.tan(np.pi / N_SEG))
|
| 46 |
+
COS_SEG = float(np.cos(np.pi / N_SEG))
|
| 47 |
+
TAPER_DEG = 5.0 # wall lean (from vertical)
|
| 48 |
+
TAPER = float(np.radians(TAPER_DEG))
|
| 49 |
+
TT = float(np.tan(TAPER))
|
| 50 |
+
WALL_T = 0.0015 # wall thickness (normal to the wall)
|
| 51 |
+
WALL_TH = WALL_T / float(np.cos(TAPER)) # horizontal wall thickness
|
| 52 |
+
FLOOR_T = 0.003
|
| 53 |
+
Z0 = 0.0003 # walls start this far above the cup's underside (the floor disc carries the cup)
|
| 54 |
+
H_RANGE = (0.035, 0.100) # total cup height
|
| 55 |
+
RB_WIDE = (0.023, 0.030) # bottom outer apothem of the cup with the widest bottom
|
| 56 |
+
STEP = (0.0055, 0.0075) # bottom apothem difference between neighbours in the true order
|
| 57 |
+
RIM_MAX = 0.033 # outer apothem of the widest opening (gripper opens 7.9 cm)
|
| 58 |
+
CLEAR_MIN = 0.003 # radial gap (worst case) of a fitting cup standing on the other cup's floor
|
| 59 |
+
TOL_MIN = 0.0075 # a fitting cup goes in if its bottom lands within this of the other cup's axis
|
| 60 |
+
STUCK_MAX = 0.005 # a too-wide cup's bottom stops no deeper than this below the other cup's rim (5-deg walls
|
| 61 |
+
# self-lock: a cup pressed 1.2 cm into the opening wedged, and the narrow cup tipped over with it)
|
| 62 |
+
INV_DH = 0.035 # in the swapped pair the narrower cup is taller by at least this
|
| 63 |
+
KEEP_DH = 0.010 # in an unswapped pair the wider cup is taller by at least this
|
| 64 |
+
P_AGREE = 0.15 # share of instances whose height order is the right nesting order
|
| 65 |
+
SEAT_H = 0.010 # "standing on the floor": bottom less than this above the other cup's floor
|
| 66 |
+
SEAT_TILT = 15.0 # deg; a tall cup in a short, wider one can lean a little
|
| 67 |
+
WRIST_CAM_H = 0.367 # wrist camera height above the table at the start pose (measured 2026-10-08)
|
| 68 |
+
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)}
|
| 69 |
+
CUP_NAMES = ("cup_1", "cup_2", "cup_3")
|
| 70 |
+
DENSITY = 600.0
|
| 71 |
+
# execution
|
| 72 |
+
GRASP_BELOW_RIM = 0.012 # gripper site this far below the rim when grasping
|
| 73 |
+
Z_CARRY = envs.TABLE_Z + 0.24
|
| 74 |
+
DROP = 0.006 # held cup's bottom this far above the receiving rim at release
|
| 75 |
+
FINGER_CLEAR = 0.015 # gripper site at least this far above any rim around the target at release: fingers opened
|
| 76 |
+
# inside a taller outer cup press on its wall and carry it away on the way up (seed 1009, 2026-10-08)
|
| 77 |
+
PARK = (-0.45, 0.0, envs.TABLE_Z + 0.35)
|
| 78 |
+
H_NOISE = 0.03 # relative noise of the blind policy's height judgement
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
# ---------------------------------------------------------------- cup geometry
|
| 82 |
+
def _quat_mul(a, b):
|
| 83 |
+
w1, x1, y1, z1 = a
|
| 84 |
+
w2, x2, y2, z2 = b
|
| 85 |
+
return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
|
| 86 |
+
w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2])
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _seg_quat(phi):
|
| 90 |
+
"""segment frame: about z by phi, then tilted about its own y (tangential) axis by TAPER, so that its local z
|
| 91 |
+
(along the wall) leans outwards and its local x is the wall's outward normal"""
|
| 92 |
+
qz = np.array([np.cos(phi / 2), 0.0, 0.0, np.sin(phi / 2)])
|
| 93 |
+
qy = np.array([np.cos(TAPER / 2), 0.0, np.sin(TAPER / 2), 0.0])
|
| 94 |
+
return _quat_mul(qz, qy)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def seg_half_len(rb, H):
|
| 98 |
+
"""tangential half length of a wall segment: one polygon side at the rim (+0.2 mm overlap)"""
|
| 99 |
+
return (rb + TT * H) * TAN_SEG + 0.0002
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def rim_radius(rb, H):
|
| 103 |
+
"""outer apothem of the opening"""
|
| 104 |
+
return rb + TT * H
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def inner_radius(rb, z):
|
| 108 |
+
"""inner apothem at height z above the cup's underside"""
|
| 109 |
+
return rb + TT * z - WALL_TH
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def bottom_reach(rb, H):
|
| 113 |
+
"""largest horizontal radius of the cup's outside at its bottom (the segment tips stick out a little beyond
|
| 114 |
+
the polygon because every segment is as wide as a rim-level polygon side)"""
|
| 115 |
+
return float(np.hypot(rb + TT * Z0, seg_half_len(rb, H)))
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def fit_clearance(rb_in, H_in, rb_out):
|
| 119 |
+
"""radial clearance (worst case over relative yaw) of cup `in` standing on the floor of cup `out`;
|
| 120 |
+
negative = does not go down to the floor. The flare is the same for both cups, so the bottom is the tightest
|
| 121 |
+
height."""
|
| 122 |
+
return inner_radius(rb_out, FLOOR_T) - bottom_reach(rb_in, H_in)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def centring_tol(rb_in, H_in, rb_out, H_out):
|
| 126 |
+
"""how far (worst case) cup `in`'s bottom centre may be off cup `out`'s axis when it is lowered in at the rim
|
| 127 |
+
and still get inside (the flared wall then guides it down)"""
|
| 128 |
+
return inner_radius(rb_out, H_out) - bottom_reach(rb_in, H_in)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def stop_height(rb_in, rb_out, H_out):
|
| 132 |
+
"""height (above cup `out`'s underside) where a too-wide cup `in`, lowered centred, stops: where its bottom
|
| 133 |
+
meets the sloping inner wall, or on the rim if that is higher than the cup"""
|
| 134 |
+
return min((rb_in - rb_out + WALL_TH) / TT, H_out)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def _cup_parts(rb, H):
|
| 138 |
+
"""[(pos, half size, quat)] of the wall segments in the cup body frame (origin at mid height)."""
|
| 139 |
+
zc = (Z0 + H) / 2
|
| 140 |
+
hs = (H - Z0) / (2 * np.cos(TAPER))
|
| 141 |
+
rc = rb + TT * zc - WALL_T / 2 * np.cos(TAPER)
|
| 142 |
+
zz = zc + WALL_T / 2 * np.sin(TAPER) - H / 2
|
| 143 |
+
hl = seg_half_len(rb, H)
|
| 144 |
+
out = []
|
| 145 |
+
for k in range(N_SEG):
|
| 146 |
+
phi = 2 * np.pi * k / N_SEG
|
| 147 |
+
out.append(((rc * np.cos(phi), rc * np.sin(phi), zz), (WALL_T / 2, hl, hs), _seg_quat(phi)))
|
| 148 |
+
return out
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _floor_part(rb, H):
|
| 152 |
+
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])
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def cup_xml(model_name, rgba):
|
| 156 |
+
"""Open flared cup: N_SEG tilted wall boxes + a cylinder floor (sizes are overwritten per instance)."""
|
| 157 |
+
geoms = []
|
| 158 |
+
rb, H = RB_WIDE[1], H_RANGE[1]
|
| 159 |
+
for k, (p, s, q) in enumerate(_cup_parts(rb, H)):
|
| 160 |
+
geoms.append(f' <geom name="{model_name}_g{k}" type="box" pos="{_fmt(p)}" size="{_fmt(s)}" '
|
| 161 |
+
f'quat="{_fmt(q)}" rgba="{_fmt(rgba)}" density="{DENSITY:.0f}" friction="0.8 0.005 0.0001" '
|
| 162 |
+
f'{_SOLID} group="0" />')
|
| 163 |
+
geoms.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(s)}" quat="{_fmt(q)}" rgba="{_fmt(rgba)}" '
|
| 164 |
+
f'conaffinity="0" contype="0" group="1" />')
|
| 165 |
+
fp, fs, _ = _floor_part(rb, H)
|
| 166 |
+
geoms.append(f' <geom name="{model_name}_g{N_SEG}" type="cylinder" pos="{_fmt(fp)}" size="{_fmt(fs[:2])}" '
|
| 167 |
+
f'rgba="{_fmt(rgba)}" density="{DENSITY:.0f}" friction="0.8 0.005 0.0001" {_SOLID} group="0" />')
|
| 168 |
+
geoms.append(f' <geom type="cylinder" pos="{_fmt(fp)}" size="{_fmt(fs[:2])}" rgba="{_fmt(rgba)}" '
|
| 169 |
+
f'conaffinity="0" contype="0" group="1" />')
|
| 170 |
+
return _wrap(model_name, "\n".join(geoms), H / 2, rim_radius(rb, H) / COS_SEG)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def disable_midphase(env):
|
| 174 |
+
"""The cups are resized at run time by editing geom pos / size in sim.model, but MuJoCo's per-body bounding
|
| 175 |
+
volume hierarchy (bvh_aabb, used by the collision mid-phase) is computed once at compile time for the registered
|
| 176 |
+
maximum size. A resized wall that lies outside its compiled leaf box is silently skipped: the gripper fingers
|
| 177 |
+
passed straight through the walls of the smaller cups (found 2026-10-07). Without the mid-phase MuJoCo tests all
|
| 178 |
+
geom pairs of two nearby bodies (still filtered by the run-time geom_rbound set in _reshape_cup)."""
|
| 179 |
+
import mujoco
|
| 180 |
+
m = env.sim.model._model
|
| 181 |
+
m.opt.disableflags |= int(mujoco.mjtDisableBit.mjDSBL_MIDPHASE)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def kendall(a, b):
|
| 185 |
+
"""number of pairs ordered differently in the two orders"""
|
| 186 |
+
pa, pb = {c: k for k, c in enumerate(a)}, {c: k for k, c in enumerate(b)}
|
| 187 |
+
return sum((pa[x] < pa[y]) != (pb[x] < pb[y]) for x, y in itertools.combinations(a, 2))
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
@register_task
|
| 191 |
+
class NestOrder(LFFTask):
|
| 192 |
+
name = "l4_nest_order"
|
| 193 |
+
level = "L4"
|
| 194 |
+
category = "geometry_inference"
|
| 195 |
+
capabilities = ("Perceive", "Reason", "Plan")
|
| 196 |
+
instruction = "Nest the red, green and blue cups one inside another."
|
| 197 |
+
instruction_indirect = "Put the three cups one inside another, like a set of nesting cups."
|
| 198 |
+
|
| 199 |
+
# ------------------------------------------------------------ scene
|
| 200 |
+
def make_bddl(self):
|
| 201 |
+
cats = [register_generated(f"LffNestCup{c.capitalize()}", cup_xml(f"lff_nest_cup_{c}", COLORS[c]))
|
| 202 |
+
for c in COLORS]
|
| 203 |
+
regions = [(-0.25, -0.15), (-0.05, 0.0), (-0.25, 0.15)]
|
| 204 |
+
objs = [(n, cat, f"{n}_region", (x - 0.01, y - 0.01, x + 0.01, y + 0.01))
|
| 205 |
+
for n, cat, (x, y) in zip(CUP_NAMES, cats, regions)]
|
| 206 |
+
return write_bddl(self.name, self.instruction, objs)
|
| 207 |
+
|
| 208 |
+
@staticmethod
|
| 209 |
+
def _heights_ok(case, h):
|
| 210 |
+
"""h[s] = height of the cup with the s-th narrowest bottom (0 = innermost in the true nest)"""
|
| 211 |
+
if case == "agree": # taller = wider: the height order is the nesting order
|
| 212 |
+
return h[2] >= h[1] + KEEP_DH and h[1] >= h[0] + KEEP_DH
|
| 213 |
+
if case == "swap_wide": # the middle cup is the tallest, the narrowest one the shortest
|
| 214 |
+
return h[1] >= h[2] + INV_DH and h[2] >= h[0] + KEEP_DH
|
| 215 |
+
raise ValueError(case)
|
| 216 |
+
|
| 217 |
+
def sample_instance(self, seed):
|
| 218 |
+
rng = np.random.default_rng(seed)
|
| 219 |
+
u = rng.random()
|
| 220 |
+
case = "agree" if u < P_AGREE else "swap_wide"
|
| 221 |
+
for _ in range(200000):
|
| 222 |
+
heights = [float(rng.uniform(*H_RANGE)) for _ in range(3)] # by true size: 0 = narrowest bottom
|
| 223 |
+
if not self._heights_ok(case, heights):
|
| 224 |
+
continue
|
| 225 |
+
rb3 = float(rng.uniform(*RB_WIDE))
|
| 226 |
+
rb2 = rb3 - float(rng.uniform(*STEP))
|
| 227 |
+
rb1 = rb2 - float(rng.uniform(*STEP))
|
| 228 |
+
rbs = [rb1, rb2, rb3]
|
| 229 |
+
rims = [rim_radius(rb, h) for rb, h in zip(rbs, heights)]
|
| 230 |
+
if max(rims) > RIM_MAX:
|
| 231 |
+
continue
|
| 232 |
+
ok = True
|
| 233 |
+
for p, q in itertools.permutations(range(3), 2): # p into q
|
| 234 |
+
if p < q:
|
| 235 |
+
ok &= (fit_clearance(rbs[p], heights[p], rbs[q]) >= CLEAR_MIN
|
| 236 |
+
and centring_tol(rbs[p], heights[p], rbs[q], heights[q]) >= TOL_MIN)
|
| 237 |
+
else:
|
| 238 |
+
ok &= heights[q] - stop_height(rbs[p], rbs[q], heights[q]) <= STUCK_MAX
|
| 239 |
+
if ok:
|
| 240 |
+
break
|
| 241 |
+
else:
|
| 242 |
+
raise RuntimeError("could not sample cup sizes")
|
| 243 |
+
xy = []
|
| 244 |
+
while len(xy) < 3:
|
| 245 |
+
xy = []
|
| 246 |
+
for _k in range(3):
|
| 247 |
+
for _t in range(200):
|
| 248 |
+
p = [float(rng.uniform(-0.27, 0.02)), float(rng.uniform(-0.17, 0.17))]
|
| 249 |
+
if all(np.hypot(p[0] - q[0], p[1] - q[1]) >= 0.14 for q in xy):
|
| 250 |
+
xy.append(p)
|
| 251 |
+
break
|
| 252 |
+
# the colour is fixed per object (cup_1 red, cup_2 green, cup_3 blue: one generated class each); shuffle
|
| 253 |
+
# which object gets which size / height / position
|
| 254 |
+
perm = [int(i) for i in rng.permutation(3)] # perm[size index] = object slot
|
| 255 |
+
cups = [None] * 3
|
| 256 |
+
for s in range(3):
|
| 257 |
+
cups[perm[s]] = dict(name=CUP_NAMES[perm[s]], color=list(COLORS)[perm[s]], rb=rbs[s], height=heights[s],
|
| 258 |
+
rim=rims[s], xy=xy[s], size_rank=s)
|
| 259 |
+
order = sorted(range(3), key=lambda j: -cups[j]["rb"]) # outermost first (indices into cups)
|
| 260 |
+
naive = sorted(range(3), key=lambda j: -cups[j]["height"])
|
| 261 |
+
assert (naive == order) == (case == "agree"), (seed, case)
|
| 262 |
+
by = lambda s: perm[s] # noqa: E731 object index of size rank s
|
| 263 |
+
return dict(seed=int(seed), case=case, cups=cups, order=order, naive_order=naive,
|
| 264 |
+
bottom_cm=[round(200 * c["rb"], 2) for c in cups],
|
| 265 |
+
opening_cm=[round(200 * c["rim"], 2) for c in cups],
|
| 266 |
+
height_cm=[round(100 * c["height"], 2) for c in cups],
|
| 267 |
+
# relative size of each opening in the wrist camera at its start height (1 = largest)
|
| 268 |
+
wrist_apparent=[round(float(v), 3) for v in (lambda a: a / a.max())(np.array(
|
| 269 |
+
[c["rim"] / (WRIST_CAM_H - c["height"]) for c in cups]))],
|
| 270 |
+
clear_mm=[round(1000 * fit_clearance(rbs[s], heights[s], rbs[s + 1]), 2) for s in range(2)],
|
| 271 |
+
tol_mm=[round(1000 * centring_tol(rbs[s], heights[s], rbs[s + 1], heights[s + 1]), 2)
|
| 272 |
+
for s in range(2)],
|
| 273 |
+
# wrong neighbour pairs: how deep (cm) the wider cup's bottom gets below the narrower cup's rim
|
| 274 |
+
stuck_cm={f"{by(s + 1)}in{by(s)}": round(100 * (heights[s] - stop_height(
|
| 275 |
+
rbs[s + 1], rbs[s], heights[s])), 2) for s in range(2)})
|
| 276 |
+
|
| 277 |
+
def _reshape_cup(self, name, rb, H):
|
| 278 |
+
m = self.env.sim.model
|
| 279 |
+
o = self.env.objects_dict[name]
|
| 280 |
+
parts = _cup_parts(rb, H) + [_floor_part(rb, H)]
|
| 281 |
+
for names in (o.contact_geoms, o.visual_geoms):
|
| 282 |
+
assert len(names) == len(parts), (name, len(names))
|
| 283 |
+
for k, n in enumerate(names):
|
| 284 |
+
g = m.geom_name2id(n)
|
| 285 |
+
pos, size, quat = parts[k]
|
| 286 |
+
m.geom_pos[g] = pos
|
| 287 |
+
m.geom_size[g] = size
|
| 288 |
+
m.geom_quat[g] = quat
|
| 289 |
+
if k < N_SEG:
|
| 290 |
+
m.geom_rbound[g] = float(np.linalg.norm(size))
|
| 291 |
+
m.geom_aabb[g] = [0, 0, 0, *size]
|
| 292 |
+
else:
|
| 293 |
+
m.geom_rbound[g] = float(np.hypot(size[0], size[1]))
|
| 294 |
+
m.geom_aabb[g] = [0, 0, 0, size[0], size[0], size[1]]
|
| 295 |
+
# mass / inertia of the resized cup: conical shell + disc floor
|
| 296 |
+
bid = int(m.geom_bodyid[m.geom_name2id(o.contact_geoms[0])])
|
| 297 |
+
slant = (H - Z0) / np.cos(TAPER)
|
| 298 |
+
r_mid = rb + TT * (H + Z0) / 2
|
| 299 |
+
wall_m = DENSITY * 2 * np.pi * r_mid * WALL_T * slant
|
| 300 |
+
floor_m = DENSITY * np.pi * rb ** 2 * FLOOR_T
|
| 301 |
+
mass = wall_m + floor_m
|
| 302 |
+
# wall centroid height (from the underside): area-weighted, r grows linearly with z
|
| 303 |
+
r0, r1 = rb + TT * Z0, rb + TT * H
|
| 304 |
+
z_w = Z0 + (H - Z0) * (r0 + 2 * r1) / (3 * (r0 + r1))
|
| 305 |
+
z_cm = (wall_m * z_w + floor_m * FLOOR_T / 2) / mass
|
| 306 |
+
Izz = wall_m * r_mid ** 2 + floor_m * rb ** 2 / 2
|
| 307 |
+
Ixx = (wall_m * (r_mid ** 2 / 2 + (H - Z0) ** 2 / 12 + (z_w - z_cm) ** 2)
|
| 308 |
+
+ floor_m * (rb ** 2 / 4 + (FLOOR_T / 2 - z_cm) ** 2))
|
| 309 |
+
m.body_mass[bid] = mass
|
| 310 |
+
m.body_inertia[bid] = [Ixx, Ixx, Izz]
|
| 311 |
+
m.body_ipos[bid] = [0.0, 0.0, z_cm - H / 2]
|
| 312 |
+
m.body_iquat[bid] = [1.0, 0.0, 0.0, 0.0]
|
| 313 |
+
|
| 314 |
+
def apply_instance(self, inst):
|
| 315 |
+
disable_midphase(self.env)
|
| 316 |
+
for c in inst["cups"]:
|
| 317 |
+
self._reshape_cup(c["name"], c["rb"], c["height"])
|
| 318 |
+
envs.set_obj_pose(self.env, c["name"], [*c["xy"], envs.TABLE_Z + c["height"] / 2 + 0.0005])
|
| 319 |
+
|
| 320 |
+
# ------------------------------------------------------------ state
|
| 321 |
+
def _cup_state(self, inst, j):
|
| 322 |
+
c = inst["cups"][j]
|
| 323 |
+
bid = envs.body_id(self.env, c["name"])
|
| 324 |
+
p = self.env.sim.data.body_xpos[bid].copy()
|
| 325 |
+
R = self.env.sim.data.body_xmat[bid].reshape(3, 3)
|
| 326 |
+
tilt = float(np.degrees(np.arccos(np.clip(R[2, 2], -1, 1))))
|
| 327 |
+
bottom = p - R[:, 2] * c["height"] / 2 # centre of the floor's underside
|
| 328 |
+
rim = p + R[:, 2] * c["height"] / 2
|
| 329 |
+
return dict(p=p, tilt=tilt, bottom=bottom, rim=rim, floor_top=bottom[2] + FLOOR_T * R[2, 2])
|
| 330 |
+
|
| 331 |
+
def relations(self, inst):
|
| 332 |
+
"""For each cup: which cup it stands in / on (if any), how high, seated or not."""
|
| 333 |
+
st = [self._cup_state(inst, j) for j in range(3)]
|
| 334 |
+
rel = []
|
| 335 |
+
for j in range(3):
|
| 336 |
+
sj = st[j]
|
| 337 |
+
best = None
|
| 338 |
+
for i in range(3):
|
| 339 |
+
if i == j:
|
| 340 |
+
continue
|
| 341 |
+
ci, si = inst["cups"][i], st[i]
|
| 342 |
+
if si["tilt"] > 45:
|
| 343 |
+
continue
|
| 344 |
+
d = float(np.hypot(*(sj["bottom"][:2] - si["p"][:2])))
|
| 345 |
+
if d > rim_radius(ci["rb"], ci["height"]) + 0.01:
|
| 346 |
+
continue # not above / in cup i
|
| 347 |
+
hb = float(sj["bottom"][2] - si["floor_top"]) # j's bottom above i's floor
|
| 348 |
+
# (the last test keeps a cup from being reported as standing in the cup it contains)
|
| 349 |
+
if hb < -0.004 or hb > ci["height"] + 0.02 or sj["bottom"][2] < si["bottom"][2] + FLOOR_T / 2:
|
| 350 |
+
continue
|
| 351 |
+
if best is None or hb < best[1]:
|
| 352 |
+
best = (i, hb, d)
|
| 353 |
+
if best is None:
|
| 354 |
+
on_table = sj["bottom"][2] < envs.TABLE_Z + 0.01 and sj["tilt"] < 30
|
| 355 |
+
rel.append(dict(cup=j, on=None, table=bool(on_table), tilt=sj["tilt"], xy=sj["p"][:2].tolist(),
|
| 356 |
+
fallen=bool(sj["tilt"] > 45)))
|
| 357 |
+
continue
|
| 358 |
+
i, hb, d = best
|
| 359 |
+
ci = inst["cups"][i]
|
| 360 |
+
seated = hb < SEAT_H and sj["tilt"] < SEAT_TILT
|
| 361 |
+
on_rim = hb > ci["height"] - FLOOR_T - 0.004
|
| 362 |
+
rel.append(dict(cup=j, on=i, height=hb, seated=bool(seated), on_rim=bool(on_rim), tilt=sj["tilt"],
|
| 363 |
+
offset=d, xy=sj["p"][:2].tolist(), fallen=bool(sj["tilt"] > 45)))
|
| 364 |
+
return rel
|
| 365 |
+
|
| 366 |
+
def outcome(self, inst):
|
| 367 |
+
envs.settle(self.env, 40)
|
| 368 |
+
cups = inst["cups"]
|
| 369 |
+
rel = self.relations(inst)
|
| 370 |
+
held = [j for j in range(3) if self.sk is not None and self.sk.holding(cups[j]["name"])]
|
| 371 |
+
col = [c["color"] for c in cups]
|
| 372 |
+
seated_in = {r["cup"]: r["on"] for r in rel if r.get("on") is not None and r["seated"]}
|
| 373 |
+
# success: a chain outer <- mid <- inner, all seated and upright, the outer cup standing on the table
|
| 374 |
+
success = False
|
| 375 |
+
for a, b, c in itertools.permutations(range(3)):
|
| 376 |
+
if seated_in.get(b) == a and seated_in.get(c) == b and _on_table_upright(rel, a):
|
| 377 |
+
success = True
|
| 378 |
+
success = bool(success and not held)
|
| 379 |
+
fb = dict(seated=[[j, i] for j, i in seated_in.items()], blocked=[], offcentre=[], held=held)
|
| 380 |
+
lines = []
|
| 381 |
+
res = dict(success=success, relations=rel, feedback=fb)
|
| 382 |
+
if held:
|
| 383 |
+
lines.append(f"The {col[held[0]]} cup is still in the gripper.")
|
| 384 |
+
if success:
|
| 385 |
+
a = [j for j in range(3) if j not in seated_in][0]
|
| 386 |
+
b = [j for j, i in seated_in.items() if i == a][0]
|
| 387 |
+
c = [j for j, i in seated_in.items() if i == b][0]
|
| 388 |
+
res["detail"] = (f"All three cups are nested: the {col[c]} cup stands inside the {col[b]} cup, "
|
| 389 |
+
f"which stands inside the {col[a]} cup.")
|
| 390 |
+
res["failure"] = None
|
| 391 |
+
return res
|
| 392 |
+
# bottom-up description
|
| 393 |
+
st = {r["cup"]: self._cup_state(inst, r["cup"]) for r in rel}
|
| 394 |
+
for r in sorted(rel, key=lambda r: st[r["cup"]]["bottom"][2]):
|
| 395 |
+
j = r["cup"]
|
| 396 |
+
if j in held:
|
| 397 |
+
continue
|
| 398 |
+
if r.get("on") is None:
|
| 399 |
+
if r["fallen"]:
|
| 400 |
+
lines.append(f"The {col[j]} cup has fallen over.")
|
| 401 |
+
elif r["table"]:
|
| 402 |
+
lines.append(f"The {col[j]} cup is standing on the table, not in another cup.")
|
| 403 |
+
else:
|
| 404 |
+
lines.append(f"The {col[j]} cup is neither standing on the table nor inside another cup.")
|
| 405 |
+
continue
|
| 406 |
+
i = r["on"]
|
| 407 |
+
if r["seated"]:
|
| 408 |
+
lines.append(f"The {col[j]} cup is inside the {col[i]} cup, standing on its bottom.")
|
| 409 |
+
continue
|
| 410 |
+
# did not go in. The text says only what a camera shows (no sizes); the structured field keeps the
|
| 411 |
+
# nominal verdict for the scripted learner
|
| 412 |
+
tilt = f", tilted about {r['tilt']:.0f} degrees" if r["tilt"] >= 8 else ""
|
| 413 |
+
if r["on_rim"]:
|
| 414 |
+
lines.append(f"The {col[j]} cup is sitting on the rim of the {col[i]} cup, not inside it{tilt}.")
|
| 415 |
+
else:
|
| 416 |
+
lines.append(f"The {col[j]} cup is stuck in the opening of the {col[i]} cup, not down inside "
|
| 417 |
+
f"it{tilt}.")
|
| 418 |
+
over = cups[j]["rb"] - cups[i]["rb"]
|
| 419 |
+
if over > 0:
|
| 420 |
+
fb["blocked"].append([j, i, round(100 * r["height"], 1)])
|
| 421 |
+
else:
|
| 422 |
+
fb["offcentre"].append([j, i, round(100 * r["height"], 1)])
|
| 423 |
+
res["detail"] = " ".join(lines) if lines else "The cups are not nested."
|
| 424 |
+
res["failure"] = "blocked" if fb["blocked"] else ("offcentre" if fb["offcentre"] else
|
| 425 |
+
("held" if held else "incomplete"))
|
| 426 |
+
return res
|
| 427 |
+
|
| 428 |
+
# ------------------------------------------------------------ execution
|
| 429 |
+
def execute(self, inst, params):
|
| 430 |
+
"""params: order = [outer, middle, inner] (indices into inst['cups']). Puts the middle cup into the outer
|
| 431 |
+
one; if it went in (judged from the scene, as an agent would see it), puts the inner cup into the middle
|
| 432 |
+
one. Optional (robustness checks): dxy = (dx, dy) release offset (m), drop (m), grasp_below (m),
|
| 433 |
+
carry_speed (m/s or None = as fast as the controller allows)."""
|
| 434 |
+
o, mid, inn = [int(v) for v in params["order"]]
|
| 435 |
+
ok = self._move_cup(inst, mid, o, params)
|
| 436 |
+
if ok:
|
| 437 |
+
self._move_cup(inst, inn, mid, params)
|
| 438 |
+
self.sk.move_to(list(PARK), yaw=0.0)
|
| 439 |
+
|
| 440 |
+
def _move_cup(self, inst, j, i, params):
|
| 441 |
+
sk = self.sk
|
| 442 |
+
sj = self._cup_state(inst, j)
|
| 443 |
+
x, y = sj["p"][:2]
|
| 444 |
+
rim = sj["rim"][2]
|
| 445 |
+
sk.set_gripper(False, steps=5)
|
| 446 |
+
sk.move_to([x, y, Z_CARRY], yaw=0.0)
|
| 447 |
+
sk.move_to([x, y, rim + 0.06], tol=0.004)
|
| 448 |
+
sk.move_to([x, y, rim - params.get("grasp_below", GRASP_BELOW_RIM)], tol=0.003)
|
| 449 |
+
sk.set_gripper(True, steps=15)
|
| 450 |
+
sk.move_to([x, y, Z_CARRY], speed=params.get("carry_speed", 0.3))
|
| 451 |
+
si = self._cup_state(inst, i)
|
| 452 |
+
dx, dy = params.get("dxy", (0.0, 0.0))
|
| 453 |
+
tx, ty = si["p"][0] + dx, si["p"][1] + dy
|
| 454 |
+
drop = params.get("drop", DROP)
|
| 455 |
+
sk.move_to([tx, ty, Z_CARRY], tol=0.004)
|
| 456 |
+
off = self._cup_state(inst, j)["bottom"] - sk.eef_pos()
|
| 457 |
+
# approach above the highest rim there (the target cup may stand inside a taller one)
|
| 458 |
+
top = max(s["rim"][2] for s in (self._cup_state(inst, q) for q in range(3) if q != j)
|
| 459 |
+
if np.hypot(s["p"][0] - tx, s["p"][1] - ty) < 0.04)
|
| 460 |
+
sk.move_to([tx - off[0], ty - off[1], max(top, si["rim"][2]) + drop + 0.03 - off[2]], tol=0.003)
|
| 461 |
+
z_rel = si["rim"][2] + drop
|
| 462 |
+
if top > si["rim"][2] + 0.002: # the target stands inside a taller cup: let go above that rim
|
| 463 |
+
z_rel = max(z_rel, top + FINGER_CLEAR - (inst["cups"][j]["height"]
|
| 464 |
+
- params.get("grasp_below", GRASP_BELOW_RIM)))
|
| 465 |
+
tgt = self._servo_cup(inst, j, [tx, ty], z_rel)
|
| 466 |
+
sk.grip = -1.0
|
| 467 |
+
self._hold_at(tgt, 12)
|
| 468 |
+
sk.move_to([tgt[0], tgt[1], Z_CARRY], speed=0.3)
|
| 469 |
+
envs.settle(self.env, 20)
|
| 470 |
+
r = [q for q in self.relations(inst) if q["cup"] == j][0]
|
| 471 |
+
return bool(r.get("on") == i and r["seated"])
|
| 472 |
+
|
| 473 |
+
def _hold_at(self, target, steps):
|
| 474 |
+
sk = self.sk
|
| 475 |
+
R = sk._R()
|
| 476 |
+
for _ in range(steps):
|
| 477 |
+
sk._act(np.asarray(target) - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip)
|
| 478 |
+
|
| 479 |
+
def _servo_cup(self, inst, j, xy, z_bottom, max_steps=60, tol=0.0015):
|
| 480 |
+
"""closed loop on the held cup's bottom centre (scripted policies only). Stops where the cup is held up
|
| 481 |
+
(a too-wide cup on / in another cup's rim) instead of pressing on: a person lets go there too, and
|
| 482 |
+
pressing on tips the cups over."""
|
| 483 |
+
sk = self.sk
|
| 484 |
+
R = sk._R()
|
| 485 |
+
goal = np.array([xy[0], xy[1], z_bottom])
|
| 486 |
+
tgt = e_prev = sk.eef_pos()
|
| 487 |
+
zs = []
|
| 488 |
+
for k in range(max_steps):
|
| 489 |
+
b, e = self._cup_state(inst, j)["bottom"], sk.eef_pos()
|
| 490 |
+
if k >= 8 and np.linalg.norm(b - goal) < tol and np.linalg.norm(e - e_prev) < 0.0005:
|
| 491 |
+
break
|
| 492 |
+
zs.append(b[2])
|
| 493 |
+
if k >= 12 and b[2] - goal[2] > 0.003 and zs[-6] - b[2] < 0.0005:
|
| 494 |
+
return e # blocked: release here
|
| 495 |
+
tgt = goal - (b - e)
|
| 496 |
+
sk._act(tgt - e, _rot_err(R, sk.eef_mat()), sk.grip)
|
| 497 |
+
e_prev = e
|
| 498 |
+
return tgt
|
| 499 |
+
|
| 500 |
+
# ------------------------------------------------------------ scripted policies
|
| 501 |
+
def default_params(self, inst):
|
| 502 |
+
"""prior: the bigger-looking cup goes outside, and the cups look big by their height: tallest outermost"""
|
| 503 |
+
return dict(order=list(inst["naive_order"]))
|
| 504 |
+
|
| 505 |
+
def oracle_params(self, inst):
|
| 506 |
+
return dict(order=list(inst["order"]))
|
| 507 |
+
|
| 508 |
+
def blind_params(self, inst, attempt, rng):
|
| 509 |
+
"""no history: the same height judgement again, with a little noise"""
|
| 510 |
+
est = [c["height"] * (1 + rng.normal(0, H_NOISE)) for c in inst["cups"]]
|
| 511 |
+
return dict(order=[int(i) for i in np.argsort(est)[::-1]])
|
| 512 |
+
|
| 513 |
+
@staticmethod
|
| 514 |
+
def constraints(history):
|
| 515 |
+
"""pairs (outer, inner) implied by the F2 feedback of earlier attempts"""
|
| 516 |
+
pairs = set()
|
| 517 |
+
for h in history:
|
| 518 |
+
fb = h["outcome"].get("feedback") or {}
|
| 519 |
+
for j, i in fb.get("seated", []):
|
| 520 |
+
pairs.add((int(i), int(j))) # j sits in i -> i is outside j
|
| 521 |
+
for j, i, _ in fb.get("blocked", []):
|
| 522 |
+
pairs.add((int(j), int(i))) # j does not fit into i -> j must be outside i
|
| 523 |
+
for j, i, _ in fb.get("offcentre", []):
|
| 524 |
+
pairs.add((int(i), int(j))) # j would fit into i
|
| 525 |
+
return pairs
|
| 526 |
+
|
| 527 |
+
def adapt_params(self, inst, history):
|
| 528 |
+
"""Scripted learner. It does not perceive the bottoms at all; it uses only which cup went into / stayed on
|
| 529 |
+
top of which (visible in the camera images; the structured part of the outcome): every such relation gives
|
| 530 |
+
an (outer, inner) pair; among the untried orders consistent with all pairs it takes the one closest (fewest
|
| 531 |
+
swapped pairs) to its prior, the height order; ties go to the larger height agreement."""
|
| 532 |
+
pairs = self.constraints(history)
|
| 533 |
+
rims = [c["height"] for c in inst["cups"]]
|
| 534 |
+
prior = list(inst["naive_order"])
|
| 535 |
+
tried = {tuple(h["params"]["order"]) for h in history if (h["outcome"].get("feedback") or {}).get("blocked")}
|
| 536 |
+
cands = []
|
| 537 |
+
for order in itertools.permutations(range(3)):
|
| 538 |
+
pos = {c: k for k, c in enumerate(order)}
|
| 539 |
+
consistent = all(pos[a] < pos[b] for a, b in pairs)
|
| 540 |
+
agree = sum(rims[order[k]] - rims[order[k + 1]] for k in range(2))
|
| 541 |
+
cands.append((consistent, tuple(order) not in tried, -kendall(order, prior), agree, order))
|
| 542 |
+
best = max(cands)
|
| 543 |
+
return dict(order=list(best[4]))
|
| 544 |
+
|
| 545 |
+
def random_order_params(self, inst, history, rng):
|
| 546 |
+
"""sensitivity variant: a random order each retry, no history"""
|
| 547 |
+
return dict(order=[int(i) for i in rng.permutation(3)])
|
| 548 |
+
|
| 549 |
+
EXTRA_KINDS = ("random_order",)
|
| 550 |
+
|
| 551 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 552 |
+
if kind not in self.EXTRA_KINDS:
|
| 553 |
+
return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt)
|
| 554 |
+
k = k or self.max_attempts
|
| 555 |
+
rng = np.random.default_rng(seed)
|
| 556 |
+
history = []
|
| 557 |
+
for a in range(k):
|
| 558 |
+
self.reset_instance(inst)
|
| 559 |
+
params = self.default_params(inst) if a == 0 else self.random_order_params(inst, history, rng)
|
| 560 |
+
self.execute(inst, params)
|
| 561 |
+
out = self.outcome(inst)
|
| 562 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 563 |
+
if on_attempt:
|
| 564 |
+
on_attempt(a, params, out)
|
| 565 |
+
if out["success"]:
|
| 566 |
+
break
|
| 567 |
+
return history
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
def _on_table_upright(rel, j):
|
| 571 |
+
r = [q for q in rel if q["cup"] == j][0]
|
| 572 |
+
return r.get("on") is None and r["table"] and r["tilt"] < 8.0 and not r["fallen"]
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
# ---------------------------------------------------------------- physical validity checks
|
| 576 |
+
def physics_check(seed0=1000, n=8, out=None):
|
| 577 |
+
"""All 6 orders on each instance; expect success iff the order is the true one."""
|
| 578 |
+
import json
|
| 579 |
+
task = NestOrder()
|
| 580 |
+
rows = []
|
| 581 |
+
for seed in range(seed0, seed0 + n):
|
| 582 |
+
inst = task.sample_instance(seed)
|
| 583 |
+
for order in itertools.permutations(range(3)):
|
| 584 |
+
task.reset_instance(inst)
|
| 585 |
+
task.execute(inst, dict(order=list(order)))
|
| 586 |
+
o = task.outcome(inst)
|
| 587 |
+
expect = list(order) == inst["order"]
|
| 588 |
+
# for a cup that did not go in: how far (cm) its bottom is below the other cup's rim
|
| 589 |
+
below_rim = [round(100 * (inst["cups"][r["on"]]["height"] - FLOOR_T - r["height"]), 2)
|
| 590 |
+
for r in o["relations"] if r.get("on") is not None and not r["seated"]]
|
| 591 |
+
rows.append(dict(seed=seed, case=inst["case"], order=list(order), success=o["success"], expect=expect,
|
| 592 |
+
failure=o["failure"], detail=o["detail"], below_rim_cm=below_rim,
|
| 593 |
+
clear_mm=inst["clear_mm"], tol_mm=inst["tol_mm"], bottom_cm=inst["bottom_cm"],
|
| 594 |
+
opening_cm=inst["opening_cm"], height_cm=inst["height_cm"]))
|
| 595 |
+
print(f"seed {seed} order {order} succ={o['success']} expect={expect} | {o['detail']}"
|
| 596 |
+
+ ("" if o["success"] == expect else " <-- MISMATCH"), flush=True)
|
| 597 |
+
if out:
|
| 598 |
+
with open(out, "w") as f:
|
| 599 |
+
json.dump(rows, f, indent=1)
|
| 600 |
+
print("total", len(rows), "mismatches", sum(r["success"] != r["expect"] for r in rows))
|
| 601 |
+
return rows
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
def robustness_check(seed0=1000, n=6, out=None):
|
| 605 |
+
"""True order with execution errors: release off-centre (both moves) by 0-9 mm in a random direction, released
|
| 606 |
+
3 cm above the rim, grasped lower, carried at full controller speed."""
|
| 607 |
+
import json
|
| 608 |
+
task = NestOrder()
|
| 609 |
+
rows = []
|
| 610 |
+
cases = [("centred", {}), ("off3", dict(off=0.003)), ("off5", dict(off=0.005)), ("off7", dict(off=0.007)),
|
| 611 |
+
("off9", dict(off=0.009)), ("drop3cm", dict(drop=0.03)), ("off4_drop3cm", dict(off=0.004, drop=0.03)),
|
| 612 |
+
("grasp2cm", dict(grasp_below=0.02)), ("fast_carry", dict(carry_speed=None))]
|
| 613 |
+
for seed in range(seed0, seed0 + n):
|
| 614 |
+
inst = task.sample_instance(seed)
|
| 615 |
+
rng = np.random.default_rng(seed)
|
| 616 |
+
for name, c in cases:
|
| 617 |
+
a = rng.uniform(0, 2 * np.pi)
|
| 618 |
+
off = c.get("off", 0.0)
|
| 619 |
+
params = dict(order=list(inst["order"]), dxy=(off * np.cos(a), off * np.sin(a)))
|
| 620 |
+
params.update({k: v for k, v in c.items() if k != "off"})
|
| 621 |
+
task.reset_instance(inst)
|
| 622 |
+
task.execute(inst, params)
|
| 623 |
+
o = task.outcome(inst)
|
| 624 |
+
rows.append(dict(seed=seed, case=name, success=o["success"], detail=o["detail"], tol_mm=inst["tol_mm"],
|
| 625 |
+
height_cm=inst["height_cm"]))
|
| 626 |
+
print(f"seed {seed} {name:13s} succ={o['success']} | {o['detail']}", flush=True)
|
| 627 |
+
if out:
|
| 628 |
+
with open(out, "w") as f:
|
| 629 |
+
json.dump(rows, f, indent=1)
|
| 630 |
+
for name, _ in cases:
|
| 631 |
+
r = [x["success"] for x in rows if x["case"] == name]
|
| 632 |
+
print(f"{name:13s} {sum(r)}/{len(r)}")
|
| 633 |
+
return rows
|
| 634 |
+
|
| 635 |
+
|
| 636 |
+
if __name__ == "__main__":
|
| 637 |
+
# python -m lffbench.tasks.l4_nest physics results/l4_nest_order/physics_check.json [n]
|
| 638 |
+
# python -m lffbench.tasks.l4_nest robust results/l4_nest_order/robustness_check.json [n]
|
| 639 |
+
import sys
|
| 640 |
+
n_arg = int(sys.argv[3]) if len(sys.argv) > 3 else None
|
| 641 |
+
if sys.argv[1] == "physics":
|
| 642 |
+
physics_check(out=sys.argv[2] if len(sys.argv) > 2 else None, n=n_arg or 8)
|
| 643 |
+
elif sys.argv[1] == "robust":
|
| 644 |
+
robustness_check(out=sys.argv[2] if len(sys.argv) > 2 else None, n=n_arg or 6)
|
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/l5_loaded_beam.py
ADDED
|
@@ -0,0 +1,598 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L5 loaded_beam (2026-10-12): a deepened l5_slippery_lift -- lift a loaded bar level without spilling its load.
|
| 2 |
+
|
| 3 |
+
Why (../research_notes/P1P2_加深与常识任务设计.md sec. 1, 2, 3.1): l5_slippery_lift saturated. Sonnet 5.5 (cla4)
|
| 4 |
+
grasped the bar's middle, lifted, saw the 45-60 deg tilt, put the bar down and regrasped near the centre of mass,
|
| 5 |
+
all inside attempt 1 (both runs succeeded on attempt 1): the tilting lift cost nothing. Rule R3: the first
|
| 6 |
+
common-sense interaction must cost something. Here the tilting lift spills the load.
|
| 7 |
+
|
| 8 |
+
Scene (world frame, robot base at x = -0.66; "forward" = +x, "left" = +y): the l5_slippery_lift bar (steel grey,
|
| 9 |
+
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
|
| 10 |
+
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
|
| 11 |
+
near the ends, 12.5 cm left and right of its middle.
|
| 12 |
+
|
| 13 |
+
Hidden variable (same in every attempt, invisible): a slug inside the bar puts its centre of mass e = 2.5-7 cm from
|
| 14 |
+
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
|
| 15 |
+
are symmetric, so the centre of mass of bar + blocks sits at M e / (M + 2 m) (2.3-6.7 cm).
|
| 16 |
+
|
| 17 |
+
Mechanism (physics, nothing teleported): grasped at its middle and lifted, the bar rotates in the slippery finger
|
| 18 |
+
pads and hangs tilted; the block on the low (heavy) end slides off, drops onto the table and, once the bar is set down
|
| 19 |
+
again, lies 2-5 cm beyond the bar's end; the other block slides along the bar to the fingers. Measured (20 seeds,
|
| 20 |
+
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 =
|
| 21 |
+
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
|
| 22 |
+
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:
|
| 23 |
+
set the bar down, release, pick the fallen block from the table, put it back on the end, move the other block back to
|
| 24 |
+
its end, regrasp nearer the heavy end, lift again: 20 commands for the scripted policy (5 for the whole oracle; the
|
| 25 |
+
same repair costs 7 commands in l5_slippery_lift, where nothing spills). What helps: a ~1 cm test lift shows the tilt
|
| 26 |
+
direction without spilling, or, after the first failure, grasping on the side of the end that sank (the heavy end),
|
| 27 |
+
ideally at the combined centre of mass (+-5 mm: 80/80 level lifts, nothing spilled).
|
| 28 |
+
|
| 29 |
+
Success: the bar is held (after a 1.5 s hold), tilted <= 8 deg, its lowest point >= 10 cm above the table (the
|
| 30 |
+
l5_slippery_lift condition), and both blocks rest on the bar, one within 3 cm of each end position (+-12.5 cm from the
|
| 31 |
+
middle; either block may sit on either end). Protocol: cross (reset before every attempt), k = 3.
|
| 32 |
+
|
| 33 |
+
Outcome (server log only; the agent gets F1): success / failure code, the bar's tilt and height, final block states,
|
| 34 |
+
per-step events (bar_lifted, bar_tilted, load_fell = the trap fired, load_displaced, load_removed, load_restored with
|
| 35 |
+
by_robot, bar_set_down), the lifts with their grasp points and maximum tilt, trap_fired, recovered_in_attempt,
|
| 36 |
+
first_interaction_ok and an F2-style `detail` in robot-centric words.
|
| 37 |
+
"""
|
| 38 |
+
import numpy as np
|
| 39 |
+
|
| 40 |
+
from .. import envs
|
| 41 |
+
from ..bddl import write_bddl
|
| 42 |
+
from ..objects import box_xml, register_generated
|
| 43 |
+
from ..task_base import register_task
|
| 44 |
+
from .l5_slippery_lift import (BAR, HALF, LIFT_MIN, TILT_MAX, YAW_ACROSS, Z_GRASP, BarSkills, SlipperyLift,
|
| 45 |
+
bar_tilt_deg, weighted_box_xml)
|
| 46 |
+
|
| 47 |
+
TZ = envs.TABLE_Z
|
| 48 |
+
LOADS = ("block_1", "block_2") # block_1 starts on the left (+y) end, block_2 on the right (-y) end
|
| 49 |
+
LOAD_SIGN = {"block_1": 1.0, "block_2": -1.0}
|
| 50 |
+
LOAD_H = 0.0125 # 2.5 cm cubes
|
| 51 |
+
LOAD_MASS = 0.030
|
| 52 |
+
LOAD_RGBA = (0.85, 0.20, 0.12, 1.0)
|
| 53 |
+
LOAD_MU = 0.20 # block sliding friction (geom priority 3: used against the bar, the table and the fingers): the blocks
|
| 54 |
+
# 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)
|
| 55 |
+
# a 5.5 cm "half lift" (20 deg) spilled nothing (0/10) and was a free probe; with 0.2 it spills.
|
| 56 |
+
SLOT = 0.125 # block centre this far from the bar's middle (along the bar)
|
| 57 |
+
SLOT_TOL = 0.03 # success: within 3 cm of an end position
|
| 58 |
+
BAR_TOP = TZ + 2 * HALF[2]
|
| 59 |
+
LIFTED = 0.02 # the bar's centre this much higher than at rest (while held) -> "lifted" (a ~1 cm test lift is not)
|
| 60 |
+
DOWN = 0.008 # ... and back below this -> "set down"
|
| 61 |
+
DEBOUNCE = 5 # control steps a new block state must persist before it counts
|
| 62 |
+
SAFE_ALONG = 0.09 # scripted grasps stay within +-9 cm of the middle (the hand must not touch the blocks)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class _Budget(Exception):
|
| 66 |
+
"""the scripted policy used up the agent command budget of the attempt"""
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def bar_frame(env):
|
| 70 |
+
"""(centre, along, side, up): `along` = the bar's long axis oriented towards the robot's left (+y); `up` = the
|
| 71 |
+
bar's cross-section axis closest to world up (the face the blocks rest on); `side` completes the frame."""
|
| 72 |
+
bid = envs.body_id(env, BAR)
|
| 73 |
+
d = env.sim.data
|
| 74 |
+
c = d.body_xpos[bid].copy()
|
| 75 |
+
R = d.body_xmat[bid].reshape(3, 3)
|
| 76 |
+
al = R[:, 1].copy()
|
| 77 |
+
if al[1] < 0:
|
| 78 |
+
al = -al
|
| 79 |
+
up = max((R[:, 0].copy(), R[:, 2].copy()), key=lambda v: abs(v[2]))
|
| 80 |
+
if up[2] < 0:
|
| 81 |
+
up = -up
|
| 82 |
+
side = np.cross(up, al)
|
| 83 |
+
return c, al, side, up
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _end_word(s):
|
| 87 |
+
return "left" if s > 0 else "right"
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class BeamSkills(BarSkills):
|
| 91 |
+
"""BarSkills (records where along the bar the jaws closed) + the task's per-step monitor."""
|
| 92 |
+
|
| 93 |
+
def __init__(self, env, task, recorder=None):
|
| 94 |
+
super().__init__(env, recorder=recorder)
|
| 95 |
+
self.task = task
|
| 96 |
+
|
| 97 |
+
def _act(self, dpos, drot, grip):
|
| 98 |
+
super()._act(dpos, drot, grip)
|
| 99 |
+
self.task.monitor_step()
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
@register_task
|
| 103 |
+
class LoadedBeam(SlipperyLift):
|
| 104 |
+
name = "l5_loaded_beam"
|
| 105 |
+
level = "L5"
|
| 106 |
+
category = "dynamics_adaptation"
|
| 107 |
+
capabilities = ("Perceive", "Reason", "Plan", "Utilize")
|
| 108 |
+
protocol = "cross"
|
| 109 |
+
max_attempts = 3
|
| 110 |
+
agent_max_steps = 40
|
| 111 |
+
instruction = ("Lift the metal bar together with the two small red blocks resting near its ends, and hold it level "
|
| 112 |
+
"(tilted less than 8 degrees) with its lowest point at least 10 cm above the table. Both blocks must "
|
| 113 |
+
"stay on the bar near its ends. Keep holding the bar when you finish.")
|
| 114 |
+
instruction_indirect = ("Raise the long grey rod with the two little red cubes sitting near its ends and hold it "
|
| 115 |
+
"horizontal (tilted less than 8 degrees), its lowest point at least 10 cm above the table. "
|
| 116 |
+
"Both cubes must stay on the rod near its ends. Keep holding the rod when you finish.")
|
| 117 |
+
|
| 118 |
+
# ------------------------------------------------------------ scene
|
| 119 |
+
def make_bddl(self):
|
| 120 |
+
bar = register_generated("LffBeamBar", weighted_box_xml("lff_beam_bar", HALF, (0.52, 0.55, 0.58, 1.0)))
|
| 121 |
+
dens = LOAD_MASS / (2 * LOAD_H) ** 3
|
| 122 |
+
la = register_generated("LffBeamBlockA", box_xml("lff_beam_block_a", (LOAD_H,) * 3, LOAD_RGBA, density=dens))
|
| 123 |
+
lb = register_generated("LffBeamBlockB", box_xml("lff_beam_block_b", (LOAD_H,) * 3, LOAD_RGBA, density=dens))
|
| 124 |
+
# LIBERO's sampler puts the bar anywhere within +-13 cm of its region's centre (it "keeps the bar's 14 cm
|
| 125 |
+
# radius inside" a 2 cm region) and rejects block placements closer than 14 + 1.8 cm to it: the block regions
|
| 126 |
+
# are >= 19 cm from every possible bar position (the first layout, 2 cm beside the bar's range, failed with
|
| 127 |
+
# "Cannot place all objects" in 13 of 400 resets, this one 0 of 400). apply_instance moves everything anyway.
|
| 128 |
+
objs = [(BAR, bar, "bar_region", (-0.11, -0.01, -0.09, 0.01)),
|
| 129 |
+
("block_1", la, "block1_region", (-0.11, 0.32, -0.09, 0.34)),
|
| 130 |
+
("block_2", lb, "block2_region", (-0.11, -0.34, -0.09, -0.32))]
|
| 131 |
+
return write_bddl(self.name, "lift the loaded bar and hold it level", objs)
|
| 132 |
+
|
| 133 |
+
def __init__(self, cam_res=None):
|
| 134 |
+
self.mon = None
|
| 135 |
+
self.budget = None # scripted policies only: command budget of the current attempt
|
| 136 |
+
self.ncmd = 0
|
| 137 |
+
super().__init__(cam_res)
|
| 138 |
+
|
| 139 |
+
def sample_instance(self, seed):
|
| 140 |
+
inst = super().sample_instance(seed) # same bar layout and hidden weight as l5_slippery_lift for this seed
|
| 141 |
+
m = inst["mass"]
|
| 142 |
+
inst.update(load_mass=LOAD_MASS, slot=SLOT,
|
| 143 |
+
com_total=float(m * inst["com_offset"] / (m + 2 * LOAD_MASS))) # bar + both blocks on their ends
|
| 144 |
+
return inst
|
| 145 |
+
|
| 146 |
+
def apply_instance(self, inst):
|
| 147 |
+
super().apply_instance(inst) # bar pose, friction, hidden weight (+ envs.refit_bounds)
|
| 148 |
+
x, y = inst["bar_xy"]
|
| 149 |
+
for nm in LOADS:
|
| 150 |
+
envs.set_obj_pose(self.env, nm, [x, y + LOAD_SIGN[nm] * SLOT, BAR_TOP + LOAD_H + 0.0005])
|
| 151 |
+
if LOAD_MU is not None:
|
| 152 |
+
envs.set_friction(self.env, nm, LOAD_MU, priority=3)
|
| 153 |
+
|
| 154 |
+
def reset_instance(self, inst, recorder=None):
|
| 155 |
+
self.env.reset()
|
| 156 |
+
self.apply_instance(inst)
|
| 157 |
+
self.env.sim.forward()
|
| 158 |
+
envs.settle(self.env, 10)
|
| 159 |
+
self.mon = None
|
| 160 |
+
self.sk = BeamSkills(self.env, self, recorder=recorder)
|
| 161 |
+
self._init_monitor()
|
| 162 |
+
return self.sk
|
| 163 |
+
|
| 164 |
+
# ------------------------------------------------------------ state
|
| 165 |
+
def bar_bottom(self):
|
| 166 |
+
return envs.obj_min_z(self.env, BAR) - TZ
|
| 167 |
+
|
| 168 |
+
def load_rel(self, nm):
|
| 169 |
+
"""block centre in the bar frame: (along (+ = towards the bar's left end), side, height above the bar's centre)"""
|
| 170 |
+
c, al, side, up = bar_frame(self.env)
|
| 171 |
+
r = envs.obj_pos(self.env, nm) - c
|
| 172 |
+
return float(r @ al), float(r @ side), float(r @ up)
|
| 173 |
+
|
| 174 |
+
def _block_held(self, nm):
|
| 175 |
+
sk = self.sk
|
| 176 |
+
if sk is None or sk.grip < 0:
|
| 177 |
+
return False
|
| 178 |
+
if np.linalg.norm(envs.obj_pos(self.env, nm) - sk.eef_pos()) > 0.06:
|
| 179 |
+
return False
|
| 180 |
+
return sk.holding(nm)
|
| 181 |
+
|
| 182 |
+
def load_state(self, nm, tol=SLOT_TOL):
|
| 183 |
+
"""'slot+' / 'slot-' (on the bar within `tol` of its left / right end position), 'bar' (on the bar
|
| 184 |
+
elsewhere), 'held', 'table', 'air' (anything else: falling, resting on the gripper ...)"""
|
| 185 |
+
if self._block_held(nm):
|
| 186 |
+
return "held"
|
| 187 |
+
a, s, u = self.load_rel(nm)
|
| 188 |
+
if abs(u - (HALF[2] + LOAD_H)) <= 0.008 and abs(s) <= HALF[0] + 0.003 and abs(a) <= HALF[1] + 0.003:
|
| 189 |
+
if abs(a - SLOT) <= tol:
|
| 190 |
+
return "slot+"
|
| 191 |
+
if abs(a + SLOT) <= tol:
|
| 192 |
+
return "slot-"
|
| 193 |
+
return "bar"
|
| 194 |
+
if envs.obj_pos(self.env, nm)[2] < TZ + 0.027:
|
| 195 |
+
return "table"
|
| 196 |
+
return "air"
|
| 197 |
+
|
| 198 |
+
# ------------------------------------------------------------ monitor
|
| 199 |
+
def _init_monitor(self):
|
| 200 |
+
st = {nm: self.load_state(nm) for nm in LOADS}
|
| 201 |
+
self.mon = dict(stable=dict(st), cand={nm: None for nm in LOADS}, cnt={nm: 0 for nm in LOADS},
|
| 202 |
+
last_on_bar={nm: self.load_rel(nm)[0] for nm in LOADS}, lost=set(), carried=set(), events=[],
|
| 203 |
+
lifts=[],
|
| 204 |
+
lifted=False, tilted=False, max_tilt=0.0)
|
| 205 |
+
|
| 206 |
+
def _event(self, ev, step=None, **kw):
|
| 207 |
+
self.mon["events"].append(dict(step=int(self.sk.n_steps if step is None else step), ev=ev, **kw))
|
| 208 |
+
|
| 209 |
+
def _last_grasp(self):
|
| 210 |
+
return next((c for c in reversed(self.sk.closes) if c["holding"]), None)
|
| 211 |
+
|
| 212 |
+
def monitor_step(self):
|
| 213 |
+
mon, sk = self.mon, self.sk
|
| 214 |
+
if mon is None or sk is None:
|
| 215 |
+
return
|
| 216 |
+
n = sk.n_steps
|
| 217 |
+
# --- the bar: lifts and tilt
|
| 218 |
+
rise = float(envs.obj_pos(self.env, BAR)[2]) - (TZ + HALF[2])
|
| 219 |
+
held = sk.grip > 0 and sk.holding(BAR)
|
| 220 |
+
if not mon["lifted"] and held and rise > LIFTED:
|
| 221 |
+
g = self._last_grasp()
|
| 222 |
+
mon["lifted"], mon["tilted"], mon["max_tilt"] = True, False, 0.0
|
| 223 |
+
mon["lifts"].append(dict(step_up=n, step_down=None, grasp_along=None if g is None else round(g["along"], 4),
|
| 224 |
+
max_tilt_deg=0.0, falls=[]))
|
| 225 |
+
self._event("bar_lifted", grasp_along=mon["lifts"][-1]["grasp_along"])
|
| 226 |
+
if mon["lifted"]:
|
| 227 |
+
t = bar_tilt_deg(self.env)
|
| 228 |
+
lift = mon["lifts"][-1]
|
| 229 |
+
if abs(t) > abs(lift["max_tilt_deg"]):
|
| 230 |
+
lift["max_tilt_deg"] = round(t, 1)
|
| 231 |
+
if not mon["tilted"] and abs(t) > TILT_MAX and held:
|
| 232 |
+
mon["tilted"] = True
|
| 233 |
+
self._event("bar_tilted", tilt_deg=round(t, 1), low_end=_end_word(t))
|
| 234 |
+
if rise < DOWN:
|
| 235 |
+
mon["lifted"] = False
|
| 236 |
+
lift["step_down"] = n
|
| 237 |
+
self._event("bar_set_down", max_tilt_deg=lift["max_tilt_deg"])
|
| 238 |
+
# --- the blocks (debounced state machine)
|
| 239 |
+
for nm in LOADS:
|
| 240 |
+
# hysteresis: a block that has left its end position must come back within 2 cm of an end to count as
|
| 241 |
+
# restored (a block sliding along the tilted bar hovered around the 3 cm limit and flickered)
|
| 242 |
+
s = self.load_state(nm, SLOT_TOL - 0.01 if nm in mon["lost"] else SLOT_TOL)
|
| 243 |
+
if s in ("slot+", "slot-", "bar"):
|
| 244 |
+
mon["last_on_bar"][nm] = self.load_rel(nm)[0]
|
| 245 |
+
old = mon["stable"][nm]
|
| 246 |
+
if s == old:
|
| 247 |
+
mon["cand"][nm], mon["cnt"][nm] = None, 0
|
| 248 |
+
continue
|
| 249 |
+
if s != mon["cand"][nm]:
|
| 250 |
+
mon["cand"][nm], mon["cnt"][nm] = s, 0
|
| 251 |
+
mon["cnt"][nm] += 1
|
| 252 |
+
if mon["cnt"][nm] < DEBOUNCE:
|
| 253 |
+
continue
|
| 254 |
+
step = n - DEBOUNCE + 1
|
| 255 |
+
mon["stable"][nm], mon["cand"][nm], mon["cnt"][nm] = s, None, 0
|
| 256 |
+
start = _end_word(LOAD_SIGN[nm])
|
| 257 |
+
if s == "held":
|
| 258 |
+
mon["carried"].add(nm)
|
| 259 |
+
if s in ("slot+", "slot-"):
|
| 260 |
+
if nm in mon["lost"]:
|
| 261 |
+
# by_robot: the gripper carried it back (else physics did, e.g. the high-end block sliding back out
|
| 262 |
+
# while the bar swings after the other block fell: 3-4 of 59 blind attempts)
|
| 263 |
+
mon["lost"].discard(nm)
|
| 264 |
+
self._event("load_restored", step, load=nm, start_end=start, end=_end_word(1 if s == "slot+" else -1),
|
| 265 |
+
by_robot=nm in mon["carried"])
|
| 266 |
+
mon["carried"].discard(nm)
|
| 267 |
+
elif old in ("slot+", "slot-") and s == "bar":
|
| 268 |
+
mon["lost"].add(nm)
|
| 269 |
+
self._event("load_displaced", step, load=nm, start_end=start, along_cm=round(100 * self.load_rel(nm)[0], 1))
|
| 270 |
+
elif old in ("slot+", "slot-", "bar", "air") and s == "table":
|
| 271 |
+
mon["lost"].add(nm)
|
| 272 |
+
end = _end_word(mon["last_on_bar"][nm])
|
| 273 |
+
self._event("load_fell", step, load=nm, start_end=start, off_end=end)
|
| 274 |
+
if mon["lifted"]:
|
| 275 |
+
mon["lifts"][-1]["falls"].append(nm)
|
| 276 |
+
elif old == "held" and s == "table":
|
| 277 |
+
mon["lost"].add(nm)
|
| 278 |
+
self._event("load_removed", step, load=nm, start_end=start)
|
| 279 |
+
elif old in ("slot+", "slot-") and s == "held":
|
| 280 |
+
mon["lost"].add(nm) # picked up by the agent: counts as lost until it is back on an end
|
| 281 |
+
|
| 282 |
+
# ------------------------------------------------------------ outcome / F2
|
| 283 |
+
def _where(self, nm):
|
| 284 |
+
"""robot-centric description of a block that is not on an end position"""
|
| 285 |
+
st = self.load_state(nm)
|
| 286 |
+
a, s, u = self.load_rel(nm)
|
| 287 |
+
if st == "held":
|
| 288 |
+
return "is held in the gripper"
|
| 289 |
+
if st == "bar":
|
| 290 |
+
e = 1.0 if a >= 0 else -1.0
|
| 291 |
+
return (f"is still on the bar but {100 * (SLOT - abs(a)):.0f} cm in from its {_end_word(e)} end position "
|
| 292 |
+
f"({100 * abs(a):.0f} cm {_end_word(e)} of the bar's middle)")
|
| 293 |
+
c, al, side, up = bar_frame(self.env)
|
| 294 |
+
e = 1.0 if a >= 0 else -1.0
|
| 295 |
+
u = al[:2] / max(np.linalg.norm(al[:2]), 1e-6) # the bar's direction seen from above
|
| 296 |
+
end = c[:2] + al[:2] * e * HALF[1] # the end's position seen from above (also while the bar hangs tilted)
|
| 297 |
+
r = envs.obj_pos(self.env, nm)[:2] - end
|
| 298 |
+
beyond = float(r @ u) * e
|
| 299 |
+
lateral = float(r @ np.array([-u[1], u[0]]))
|
| 300 |
+
where = "on the table" if st == "table" else "off the bar"
|
| 301 |
+
if beyond > 0 and abs(lateral) < 0.04:
|
| 302 |
+
return f"lies {where}, {100 * beyond:.0f} cm beyond the bar's {_end_word(e)} end"
|
| 303 |
+
fx = f"{100 * abs(r[0]):.0f} cm {'forward' if r[0] > 0 else 'back'}"
|
| 304 |
+
fy = f"{100 * abs(r[1]):.0f} cm {'left' if r[1] > 0 else 'right'}"
|
| 305 |
+
return f"lies {where}, {fx} and {fy} of the bar's {_end_word(e)} end"
|
| 306 |
+
|
| 307 |
+
def outcome(self, inst):
|
| 308 |
+
sk, mon = self.sk, self.mon
|
| 309 |
+
sk.hold(30) # 1.5 s with the gripper as the agent left it (envs.settle would open the jaws)
|
| 310 |
+
held = bool(sk.holding(BAR))
|
| 311 |
+
tilt = bar_tilt_deg(self.env)
|
| 312 |
+
bottom = self.bar_bottom()
|
| 313 |
+
states = {nm: self.load_state(nm) for nm in LOADS}
|
| 314 |
+
on_plus = [nm for nm in LOADS if states[nm] == "slot+"]
|
| 315 |
+
on_minus = [nm for nm in LOADS if states[nm] == "slot-"]
|
| 316 |
+
loads_ok = len(on_plus) == 1 and len(on_minus) == 1
|
| 317 |
+
level_ok = held and abs(tilt) <= TILT_MAX and bottom >= LIFT_MIN
|
| 318 |
+
success = bool(level_ok and loads_ok)
|
| 319 |
+
lifted_ever = bool(mon["lifts"]) or (sk.zmax - sk.z0) > 0.03
|
| 320 |
+
g = self._last_grasp()
|
| 321 |
+
evs = mon["events"]
|
| 322 |
+
falls = [e for e in evs if e["ev"] == "load_fell"]
|
| 323 |
+
restored = [e for e in evs if e["ev"] == "load_restored"]
|
| 324 |
+
lifts = mon["lifts"]
|
| 325 |
+
first_ok = None if not lifts else bool(not lifts[0]["falls"]) # the first lift spilled nothing
|
| 326 |
+
# --- text
|
| 327 |
+
gtxt = ""
|
| 328 |
+
if g is not None:
|
| 329 |
+
a = g["along"]
|
| 330 |
+
gtxt = (f" You last grasped the bar {100 * abs(a):.1f} cm to the {_end_word(a)} of its middle."
|
| 331 |
+
if abs(a) >= 0.0005 else " You last grasped the bar at its middle.")
|
| 332 |
+
tilt_txt = (f"hangs tilted by {abs(tilt):.0f} degrees, its {_end_word(tilt)} end lower than its "
|
| 333 |
+
f"{_end_word(-tilt)} end")
|
| 334 |
+
if success:
|
| 335 |
+
failure = None
|
| 336 |
+
bar_txt = (f"The bar is held level (tilt {abs(tilt):.0f} degrees), {100 * bottom:.0f} cm above the table, "
|
| 337 |
+
"with a block on each end.")
|
| 338 |
+
elif held and abs(tilt) > TILT_MAX:
|
| 339 |
+
failure = "tilted"
|
| 340 |
+
bar_txt = f"The bar did not stay level: it rotated in the gripper and now {tilt_txt}."
|
| 341 |
+
if bottom < LIFT_MIN:
|
| 342 |
+
bar_txt += f" Its lowest point is {100 * bottom:.0f} cm above the table."
|
| 343 |
+
elif held and bottom < LIFT_MIN:
|
| 344 |
+
failure = "too_low"
|
| 345 |
+
bar_txt = (f"The bar is held level (tilt {abs(tilt):.0f} degrees) but its lowest point is only "
|
| 346 |
+
f"{100 * bottom:.0f} cm above the table.")
|
| 347 |
+
elif held:
|
| 348 |
+
failure = "load_off"
|
| 349 |
+
bar_txt = (f"The bar is held level (tilt {abs(tilt):.0f} degrees), {100 * bottom:.0f} cm above the table, "
|
| 350 |
+
"but the blocks are not both on its ends.")
|
| 351 |
+
elif lifted_ever:
|
| 352 |
+
failure = "dropped"
|
| 353 |
+
bar_txt = "The bar was lifted but is no longer in the gripper; it lies on the table."
|
| 354 |
+
else:
|
| 355 |
+
failure = "no_grasp"
|
| 356 |
+
bar_txt = ("The gripper never closed on the bar; it is still lying on the table." if not sk.closes else
|
| 357 |
+
"The gripper did not catch the bar; it is still lying on the table.")
|
| 358 |
+
parts = [bar_txt]
|
| 359 |
+
if falls:
|
| 360 |
+
f0 = falls[0]
|
| 361 |
+
lift = next((l for l in lifts if f0["load"] in l["falls"]), None)
|
| 362 |
+
how = (f" while the bar hung tilted by up to {abs(lift['max_tilt_deg']):.0f} degrees with its "
|
| 363 |
+
f"{_end_word(lift['max_tilt_deg'])} end lower") if lift and abs(lift["max_tilt_deg"]) > 1 else ""
|
| 364 |
+
parts.append(f"The {f0['start_end']} block slid off the bar's {f0['off_end']} end{how}."
|
| 365 |
+
+ (f" Blocks fell off {len(falls)} times in this attempt." if len(falls) > 1 else ""))
|
| 366 |
+
if not loads_ok:
|
| 367 |
+
for nm in LOADS:
|
| 368 |
+
if states[nm] in ("slot+", "slot-") and (len(on_plus) == 1 or states[nm] != "slot+") and \
|
| 369 |
+
(len(on_minus) == 1 or states[nm] != "slot-"):
|
| 370 |
+
continue
|
| 371 |
+
parts.append(f"The {_end_word(LOAD_SIGN[nm])} block {self._where(nm)}.")
|
| 372 |
+
detail = " ".join(parts) + gtxt
|
| 373 |
+
loads = {}
|
| 374 |
+
for nm in LOADS:
|
| 375 |
+
a, s, u = self.load_rel(nm)
|
| 376 |
+
loads[nm] = dict(state=states[nm], along_cm=round(100 * a, 1), side_cm=round(100 * s, 1),
|
| 377 |
+
above_bar_centre_cm=round(100 * u, 1))
|
| 378 |
+
out = dict(success=success, failure=failure, held=held, tilt_deg=round(tilt, 1), bottom_cm=round(100 * bottom, 1),
|
| 379 |
+
grasp_along=None if g is None else round(g["along"], 4),
|
| 380 |
+
stages=dict(bar_held_level_high=bool(level_ok), loads_on_ends=bool(loads_ok)),
|
| 381 |
+
loads=loads, loads_on_ends=len(on_plus) + len(on_minus) if loads_ok else
|
| 382 |
+
int(len(on_plus) >= 1) + int(len(on_minus) >= 1),
|
| 383 |
+
trap_fired=bool(falls), n_load_falls=len(falls), n_restored=len(restored),
|
| 384 |
+
n_restored_by_robot=len([e for e in restored if e.get("by_robot")]),
|
| 385 |
+
n_regressions=len([e for e in evs if e["ev"] in ("load_fell", "load_displaced")]),
|
| 386 |
+
recovered_in_attempt=bool(falls and success), first_interaction_ok=first_ok,
|
| 387 |
+
n_lifts=len(lifts), lifts=lifts, events=list(evs), closes=sk.closes, detail=detail)
|
| 388 |
+
out["detail_indirect"] = detail.replace("bar", "rod").replace("block", "cube")
|
| 389 |
+
return out
|
| 390 |
+
|
| 391 |
+
# ------------------------------------------------------------ scripted primitives (agent-command counted)
|
| 392 |
+
def _cmd(self, target=None, yaw=None, speed=None, grip=None, tol=0.004, max_steps=250):
|
| 393 |
+
"""one agent command (move_eef with an optional gripper action, or observe when nothing is given)"""
|
| 394 |
+
self.ncmd += 1
|
| 395 |
+
if self.budget is not None and self.ncmd > self.budget:
|
| 396 |
+
raise _Budget()
|
| 397 |
+
sk = self.sk
|
| 398 |
+
if target is not None:
|
| 399 |
+
t = np.asarray(target, float).copy()
|
| 400 |
+
t[2] = max(t[2], TZ + 0.006) # the agent interface does not go below 0.5 cm above the table
|
| 401 |
+
sk.move_to(t, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
|
| 402 |
+
if grip is not None:
|
| 403 |
+
sk.set_gripper(bool(grip))
|
| 404 |
+
|
| 405 |
+
def grasp_lift(self, along, lift=0.15, speed=0.10, dx=0.0):
|
| 406 |
+
"""open, above the grasp point (jaws across the bar), descend, close, lift, look: 5 commands"""
|
| 407 |
+
c, al, side, up = bar_frame(self.env)
|
| 408 |
+
g = c + al * float(along) + np.array([dx, 0.0, 0.0])
|
| 409 |
+
z = max(float(c[2]), Z_GRASP)
|
| 410 |
+
self._cmd([g[0], g[1], z + 0.10], yaw=YAW_ACROSS, grip=False)
|
| 411 |
+
self._cmd([g[0], g[1], z], tol=0.003)
|
| 412 |
+
self._cmd(grip=True)
|
| 413 |
+
self._cmd([g[0], g[1], z + lift], speed=speed, max_steps=600)
|
| 414 |
+
self._cmd()
|
| 415 |
+
|
| 416 |
+
def put_down(self):
|
| 417 |
+
"""lower the held bar onto the table, release, back up: 2 commands"""
|
| 418 |
+
e = self.sk.eef_pos()
|
| 419 |
+
self._cmd([e[0], e[1], Z_GRASP + 0.003], speed=0.05, grip=False, max_steps=600)
|
| 420 |
+
self._cmd([e[0], e[1], Z_GRASP + 0.12])
|
| 421 |
+
|
| 422 |
+
def _block_yaw(self, nm):
|
| 423 |
+
"""gripper yaw whose jaws close on two faces of the block, preferring jaws that do not reach towards the bar"""
|
| 424 |
+
q = envs.obj_quat(self.env, nm)
|
| 425 |
+
w, x, y, z = q
|
| 426 |
+
psi = float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))
|
| 427 |
+
c, al, side, up = bar_frame(self.env)
|
| 428 |
+
p = envs.obj_pos(self.env, nm)
|
| 429 |
+
a = float(np.clip((p - c) @ al, -HALF[1], HALF[1]))
|
| 430 |
+
v = (p - (c + al * a))[:2]
|
| 431 |
+
v = v / max(np.linalg.norm(v), 1e-6)
|
| 432 |
+
best = None
|
| 433 |
+
for k in range(2):
|
| 434 |
+
ang = psi + k * np.pi / 2 # closing direction candidate (a face normal)
|
| 435 |
+
n = np.array([np.cos(ang), np.sin(ang)])
|
| 436 |
+
score = abs(n @ v)
|
| 437 |
+
if best is None or score < best[0]:
|
| 438 |
+
best = (score, ang)
|
| 439 |
+
yaw = best[1] + np.pi / 2 # yaw = closing direction + 90 deg (YAW_ACROSS closes along world x)
|
| 440 |
+
return float((yaw + np.pi / 2) % np.pi - np.pi / 2)
|
| 441 |
+
|
| 442 |
+
def move_block_to_slot(self, nm, sign, tries=2):
|
| 443 |
+
"""pick a block (from the table or the bar) and set it on the end position `sign`: 6 commands per try"""
|
| 444 |
+
sk = self.sk
|
| 445 |
+
for _ in range(tries):
|
| 446 |
+
p = envs.obj_pos(self.env, nm)
|
| 447 |
+
yaw = self._block_yaw(nm)
|
| 448 |
+
zg = max(float(p[2]), TZ + 0.008)
|
| 449 |
+
self._cmd([p[0], p[1], zg + 0.08], yaw=yaw, grip=False)
|
| 450 |
+
self._cmd([p[0], p[1], zg], tol=0.003, grip=True)
|
| 451 |
+
self._cmd([p[0], p[1], BAR_TOP + LOAD_H + 0.07])
|
| 452 |
+
if not sk.holding(nm):
|
| 453 |
+
continue
|
| 454 |
+
c, al, side, up = bar_frame(self.env)
|
| 455 |
+
t = c + al * sign * SLOT
|
| 456 |
+
ztop = envs.obj_max_z(self.env, BAR)
|
| 457 |
+
self._cmd([t[0], t[1], ztop + LOAD_H + 0.06])
|
| 458 |
+
self._cmd([t[0], t[1], ztop + LOAD_H + 0.004], speed=0.05, grip=False)
|
| 459 |
+
self._cmd([t[0], t[1], ztop + LOAD_H + 0.08])
|
| 460 |
+
if self.load_state(nm) == ("slot+" if sign > 0 else "slot-"):
|
| 461 |
+
return True
|
| 462 |
+
return False
|
| 463 |
+
|
| 464 |
+
def restore_loads(self):
|
| 465 |
+
"""put every block that is not on an end position back onto a free end; True if both ends are taken"""
|
| 466 |
+
for _ in range(2):
|
| 467 |
+
st = {nm: self.load_state(nm) for nm in LOADS}
|
| 468 |
+
free = [s for s in (1.0, -1.0) if not any(v == ("slot+" if s > 0 else "slot-") for v in st.values())]
|
| 469 |
+
if not free:
|
| 470 |
+
return True
|
| 471 |
+
loose = [nm for nm in LOADS if st[nm] not in ("slot+", "slot-")]
|
| 472 |
+
for sgn in free:
|
| 473 |
+
if not loose:
|
| 474 |
+
break
|
| 475 |
+
c, al, side, up = bar_frame(self.env)
|
| 476 |
+
slot = c + al * sgn * SLOT
|
| 477 |
+
nm = min(loose, key=lambda b: np.linalg.norm(envs.obj_pos(self.env, b)[:2] - slot[:2]))
|
| 478 |
+
loose.remove(nm)
|
| 479 |
+
self.move_block_to_slot(nm, sgn)
|
| 480 |
+
self._cmd() # look
|
| 481 |
+
st = {nm: self.load_state(nm) for nm in LOADS}
|
| 482 |
+
return sorted(st.values()) == ["slot+", "slot-"]
|
| 483 |
+
|
| 484 |
+
def judge(self):
|
| 485 |
+
"""what an agent sees after a lift (perfect perception): (all good, tilt, blocks on their ends)"""
|
| 486 |
+
tilt = bar_tilt_deg(self.env)
|
| 487 |
+
st = sorted(self.load_state(nm) for nm in LOADS)
|
| 488 |
+
ok_loads = st == ["slot+", "slot-"]
|
| 489 |
+
good = self.sk.holding(BAR) and abs(tilt) <= TILT_MAX - 2 and self.bar_bottom() >= LIFT_MIN + 0.01 and ok_loads
|
| 490 |
+
return bool(good), float(tilt), ok_loads
|
| 491 |
+
|
| 492 |
+
# ------------------------------------------------------------ scripted policies
|
| 493 |
+
def execute(self, inst, params):
|
| 494 |
+
self.grasp_lift(params["along"], params.get("lift", 0.15), params.get("speed", 0.10), params.get("dx", 0.0))
|
| 495 |
+
|
| 496 |
+
def default_params(self, inst):
|
| 497 |
+
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
|
| 498 |
+
|
| 499 |
+
def oracle_params(self, inst):
|
| 500 |
+
return dict(along=float(inst["com_total"]), lift=0.15, speed=0.10)
|
| 501 |
+
|
| 502 |
+
def blind_params(self, inst, attempt, rng):
|
| 503 |
+
return dict(along=float(rng.normal(0.0, 0.01)), lift=float(rng.uniform(0.12, 0.18)),
|
| 504 |
+
speed=float(rng.uniform(0.05, 0.20)))
|
| 505 |
+
|
| 506 |
+
MARGIN = 0.008 # a lift that sank towards +y at grasp g says COM > g + MARGIN
|
| 507 |
+
STEP = 0.030 # first move towards the end that sank when only one side is bounded
|
| 508 |
+
|
| 509 |
+
def bracket(self, obs):
|
| 510 |
+
"""grasp point from (grasp_along, tilt) observations: the end that sank is the heavy side of that grasp"""
|
| 511 |
+
lo, hi = -SAFE_ALONG, SAFE_ALONG
|
| 512 |
+
lo_set = hi_set = False
|
| 513 |
+
for g, t in obs:
|
| 514 |
+
if t > 0:
|
| 515 |
+
lo, lo_set = max(lo, g + self.MARGIN), True
|
| 516 |
+
else:
|
| 517 |
+
hi, hi_set = min(hi, g - self.MARGIN), True
|
| 518 |
+
if lo_set and hi_set:
|
| 519 |
+
a = 0.5 * (lo + hi)
|
| 520 |
+
elif lo_set:
|
| 521 |
+
a = lo + self.STEP - self.MARGIN
|
| 522 |
+
elif hi_set:
|
| 523 |
+
a = hi - self.STEP + self.MARGIN
|
| 524 |
+
else:
|
| 525 |
+
a = 0.0
|
| 526 |
+
return float(np.clip(a, -SAFE_ALONG, SAFE_ALONG))
|
| 527 |
+
|
| 528 |
+
def adapt_params(self, inst, history):
|
| 529 |
+
obs = [o for h in history for o in h["params"].get("obs", [])]
|
| 530 |
+
return dict(along=self.bracket(obs))
|
| 531 |
+
|
| 532 |
+
def adaptive_attempt(self, obs):
|
| 533 |
+
"""lift at the current estimate; if the bar tilts or a block falls: set the bar down, put the blocks back,
|
| 534 |
+
regrasp on the side of the end that sank (bracketing), lift again -- while the command budget allows"""
|
| 535 |
+
tried = []
|
| 536 |
+
along = self.bracket(obs)
|
| 537 |
+
while True:
|
| 538 |
+
tried.append(round(along, 4))
|
| 539 |
+
self.grasp_lift(along)
|
| 540 |
+
good, tilt, ok_loads = self.judge()
|
| 541 |
+
if good:
|
| 542 |
+
return tried
|
| 543 |
+
g = self._last_grasp()
|
| 544 |
+
if abs(tilt) > 3.0 or not ok_loads:
|
| 545 |
+
lift = self.mon["lifts"][-1] if self.mon["lifts"] else None
|
| 546 |
+
t = tilt if abs(tilt) > 3.0 else (lift["max_tilt_deg"] if lift else 0.0)
|
| 547 |
+
if abs(t) > 1.0:
|
| 548 |
+
obs.append((g["along"] if g is not None else along, t))
|
| 549 |
+
# a repair = set down (2) + both blocks back (2 x 6: the fallen one and the one that slid to the fingers)
|
| 550 |
+
# + look (1) + regrasp, lift, look (5) = 20 commands; without enough budget keep holding the bar as it is
|
| 551 |
+
if self.budget is not None and self.ncmd + 20 > self.budget:
|
| 552 |
+
return tried
|
| 553 |
+
self.put_down()
|
| 554 |
+
if not self.restore_loads():
|
| 555 |
+
return tried
|
| 556 |
+
along = self.bracket(obs)
|
| 557 |
+
|
| 558 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 559 |
+
"""cross protocol with an agent-like command budget per attempt (agent_max_steps; one move_eef with an optional
|
| 560 |
+
gripper action, or one observe, = one command). naive / oracle / blind: one lift, no checking.
|
| 561 |
+
adaptive: naive in attempt 1 but checks and repairs inside the attempt (`adaptive_attempt`); later attempts
|
| 562 |
+
start from the grasp point learned so far."""
|
| 563 |
+
k = k or self.max_attempts
|
| 564 |
+
rng = np.random.default_rng(seed)
|
| 565 |
+
history, obs = [], []
|
| 566 |
+
for a in range(k):
|
| 567 |
+
self.reset_instance(inst)
|
| 568 |
+
self.ncmd, self.budget = 0, self.agent_max_steps
|
| 569 |
+
if kind == "oracle":
|
| 570 |
+
params = self.oracle_params(inst)
|
| 571 |
+
elif kind == "naive":
|
| 572 |
+
params = self.default_params(inst)
|
| 573 |
+
elif kind == "blind":
|
| 574 |
+
params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
|
| 575 |
+
elif kind == "adaptive":
|
| 576 |
+
params = dict(obs=[])
|
| 577 |
+
else:
|
| 578 |
+
raise ValueError(kind)
|
| 579 |
+
n0 = len(obs)
|
| 580 |
+
try:
|
| 581 |
+
if kind == "adaptive":
|
| 582 |
+
params["tried"] = self.adaptive_attempt(obs)
|
| 583 |
+
else:
|
| 584 |
+
self.execute(inst, params)
|
| 585 |
+
except _Budget:
|
| 586 |
+
params["budget_used_up"] = True
|
| 587 |
+
if kind == "adaptive":
|
| 588 |
+
params["obs"] = [[round(g, 4), round(t, 1)] for g, t in obs[n0:]]
|
| 589 |
+
self.budget = None
|
| 590 |
+
out = self.outcome(inst)
|
| 591 |
+
out["commands"] = self.ncmd
|
| 592 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 593 |
+
if on_attempt:
|
| 594 |
+
on_attempt(a, params, out)
|
| 595 |
+
if out["success"] or kind in ("oracle", "naive"):
|
| 596 |
+
break
|
| 597 |
+
return history
|
| 598 |
+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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L5-C tablecloth_pull: yank a board out from under a cube so that the cube lands inside a band.
|
| 2 |
+
|
| 3 |
+
Category dynamics_adaptation (L5): "figure out how this object moves". Replaces l5_tip_threshold, which could not
|
| 4 |
+
be built robustly with this robot (see task_cards/l5_tip_threshold.md).
|
| 5 |
+
|
| 6 |
+
Scene: a 30 x 8 x 1 cm wooden board lies on the table, pointing away from the robot, with a black handle block
|
| 7 |
+
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
|
| 8 |
+
table) is painted on the table under the board, a few cm closer to the robot than the cube. The agent may touch
|
| 9 |
+
only the board / handle, never the cube.
|
| 10 |
+
|
| 11 |
+
Physics. If the board is pulled slowly the cube rides along on it (static friction). If it is yanked, the board
|
| 12 |
+
slides out from under the cube; while it slides, friction drags the cube a little towards the robot, so the
|
| 13 |
+
cube drops onto the table having moved d towards the robot. d DEcreases with the pull speed (counter-intuitive:
|
| 14 |
+
a harder yank moves the cube less) and increases with the cube-board friction mu.
|
| 15 |
+
|
| 16 |
+
Hidden variable: the cube's friction mu (0.08-0.15; the cube looks the same for every mu), which shifts the whole
|
| 17 |
+
speed -> displacement curve and the speed below which the cube rides along.
|
| 18 |
+
|
| 19 |
+
Why the prior fails. The classic tablecloth prior is to yank as fast as possible (0.6 m/s, the arm's top speed);
|
| 20 |
+
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
|
| 21 |
+
rode along; the agent has to infer which way to change the pull speed (faster = less displacement) and by how
|
| 22 |
+
much.
|
| 23 |
+
|
| 24 |
+
Rule (stated in the instruction and enforced, 2026-10-08): ONE pull. Only one move command may drive the board
|
| 25 |
+
(>= PULL_EPS), the cube must still be where it started (<= PRE_TOL, grasp nudges) when that pull begins, and all
|
| 26 |
+
other move commands together may drive the board at most STRAY_MAX. Gripper open / close commands never count.
|
| 27 |
+
Without it every cla2 success (Sonnet, 4/4) dragged the board slowly first so that the cube rode to the band and the
|
| 28 |
+
last pull only added a little (one dragged it 4 cm, then yanked it sideways; one moved it with 11 commands, most
|
| 29 |
+
of them open-gripper strikes): the friction never mattered.
|
| 30 |
+
"""
|
| 31 |
+
import numpy as np
|
| 32 |
+
|
| 33 |
+
from .. import envs
|
| 34 |
+
from ..bddl import write_bddl
|
| 35 |
+
from ..objects import _fmt, _wrap, box_xml, register_generated
|
| 36 |
+
from ..skills import Skills
|
| 37 |
+
from ..task_base import LFFTask, register_task
|
| 38 |
+
|
| 39 |
+
BOARD, CUBE, BAND = "board_1", "cube_1", "band_1"
|
| 40 |
+
B_HALF = (0.15, 0.04, 0.005) # 30 x 8 x 1 cm
|
| 41 |
+
H_HALF = (0.0125, 0.02, 0.015) # handle 2.5 x 4 x 3 cm on top of the near end
|
| 42 |
+
C_HALF = 0.02 # 4 cm cube
|
| 43 |
+
LF = 0.05 # cube centre to the board's far edge
|
| 44 |
+
BAND_HALF_X = 0.03 # band 6 cm deep: the 4 cm cube must be fully inside -> centre within +-1 cm
|
| 45 |
+
BAND_HALF_Y = 0.12
|
| 46 |
+
LINE_W = 0.005
|
| 47 |
+
TOL = BAND_HALF_X - C_HALF
|
| 48 |
+
MU_BOARD = 0.3 # board-table friction (fixed)
|
| 49 |
+
STROKE = 0.25 # scripted pull length
|
| 50 |
+
V_MIN, V_MAX = 0.15, 0.80
|
| 51 |
+
# 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
|
| 52 |
+
# drives the board (touches it, or it speeds up; a board sliding on its own only slows down), so coasting after a
|
| 53 |
+
# strike or a release is not charged to the next command. Measured on the cla2 agent runs and the scripted policy:
|
| 54 |
+
# approach moves 0 mm; closing on the handle 0.6-2 mm (agents) / 4.6 mm (script); release after the pull 3-10 mm
|
| 55 |
+
# (gripper commands never count as pulls); the loophole drags 13-41 mm per command, open-gripper strikes 11-54 mm.
|
| 56 |
+
PULL_EPS = 0.003 # a move command that drives the board this far is a pull
|
| 57 |
+
PRE_TOL = 0.01 # the cube may have moved at most this much (grasp nudges) when the pull starts
|
| 58 |
+
STRAY_MAX = 0.005 # board motion driven by all the other move commands together (each below PULL_EPS)
|
| 59 |
+
ACC_EPS = 0.0002 # board speed-up per control step (m/step) that counts as the robot driving it
|
| 60 |
+
_SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"'
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def board_xml(name):
|
| 64 |
+
hp = (-B_HALF[0] + H_HALF[0], 0.0, B_HALF[2] + H_HALF[2])
|
| 65 |
+
wood, black = (0.62, 0.45, 0.28, 1.0), (0.12, 0.12, 0.12, 1.0)
|
| 66 |
+
g = (f' <inertial pos="0.001 0 0.001" mass="0.3" diaginertia="0.0016 0.0023 0.0039" />\n'
|
| 67 |
+
f' <geom name="{name}_g0" type="box" size="{_fmt(B_HALF)}" rgba="{_fmt(wood)}" {_SOLID} group="0" />\n'
|
| 68 |
+
f' <geom name="{name}_g1" type="box" pos="{_fmt(hp)}" size="{_fmt(H_HALF)}" rgba="{_fmt(black)}" '
|
| 69 |
+
f'{_SOLID} group="0" />\n'
|
| 70 |
+
f' <geom type="box" size="{_fmt(B_HALF)}" rgba="{_fmt(wood)}" conaffinity="0" contype="0" group="1" />\n'
|
| 71 |
+
f' <geom type="box" pos="{_fmt(hp)}" size="{_fmt(H_HALF)}" rgba="{_fmt(black)}" conaffinity="0" '
|
| 72 |
+
f'contype="0" group="1" />')
|
| 73 |
+
# small horizontal radius: only LIBERO's reset-time sampler reads it (the layout is overridden anyway)
|
| 74 |
+
return _wrap(name, g, B_HALF[2], 0.03)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def band_xml(name, line_rgba=(0.1, 0.55, 0.15, 1.0), fill_rgba=(0.75, 0.92, 0.75, 1.0)):
|
| 78 |
+
"""Flat visual band across the table (no collisions): light fill + dark lines on its two long edges."""
|
| 79 |
+
hx, hy = BAND_HALF_X, BAND_HALF_Y
|
| 80 |
+
parts = [((0, 0, 0.0004), (hx, hy, 0.0004), fill_rgba),
|
| 81 |
+
((hx + LINE_W / 2, 0, 0.0010), (LINE_W / 2, hy, 0.0002), line_rgba),
|
| 82 |
+
((-hx - LINE_W / 2, 0, 0.0010), (LINE_W / 2, hy, 0.0002), line_rgba)]
|
| 83 |
+
g = "\n".join(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(c)}" '
|
| 84 |
+
f'contype="0" conaffinity="0" group="1" />' for p, sz, c in parts)
|
| 85 |
+
return _wrap(name, g, 0.0012, 0.03)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def d_range(mu):
|
| 89 |
+
"""Band distances sampled for a given mu (m). Calibrated 2026-10-07 (LF 5 cm, board at x 0.05): the cube
|
| 90 |
+
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,
|
| 91 |
+
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
|
| 92 |
+
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
|
| 93 |
+
the 'yank as fast as possible' prior always lands the cube short of the band."""
|
| 94 |
+
return 0.33 * mu + 0.0065, 0.50 * mu
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class ClothSkills(Skills):
|
| 98 |
+
"""Skills that watch, every control step, whether the robot touches the cube (not allowed) and how each
|
| 99 |
+
move_to / gripper command moves the board and the cube (one pull only)."""
|
| 100 |
+
|
| 101 |
+
def __init__(self, env, bias=None, recorder=None):
|
| 102 |
+
super().__init__(env, bias=bias, recorder=recorder)
|
| 103 |
+
m = env.sim.model
|
| 104 |
+
self._robot = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith(("gripper0_", "robot0_"))]
|
| 105 |
+
self._cube = envs.obj_geom_ids(env, CUBE)
|
| 106 |
+
self._board = envs.obj_geom_ids(env, BOARD)
|
| 107 |
+
self.touched_cube = False
|
| 108 |
+
self.cube0 = envs.obj_pos(env, CUBE)
|
| 109 |
+
self._ends = self._board_ends()
|
| 110 |
+
self._bstep = 0.0 # board motion in the previous control step
|
| 111 |
+
self._seg = None
|
| 112 |
+
self.segments = [] # one entry per move_to / set_gripper command
|
| 113 |
+
|
| 114 |
+
def _board_ends(self):
|
| 115 |
+
"""Both ends of the board's long axis (world xyz): their motion also catches turning and tilting."""
|
| 116 |
+
b = envs.obj_pos(self.env, BOARD)
|
| 117 |
+
R = self.env.sim.data.body_xmat[envs.body_id(self.env, BOARD)].reshape(3, 3)
|
| 118 |
+
return np.stack([b - R[:, 0] * B_HALF[0], b + R[:, 0] * B_HALF[0]])
|
| 119 |
+
|
| 120 |
+
def _act(self, dpos, drot, grip):
|
| 121 |
+
super()._act(dpos, drot, grip)
|
| 122 |
+
if not self.touched_cube and envs.contacts_between(self.env, self._robot, self._cube):
|
| 123 |
+
self.touched_cube = True
|
| 124 |
+
ends = self._board_ends()
|
| 125 |
+
step = float(np.max(np.linalg.norm(ends - self._ends, axis=1)))
|
| 126 |
+
touch = envs.contacts_between(self.env, self._robot, self._board)
|
| 127 |
+
speed_up = step - self._bstep > ACC_EPS
|
| 128 |
+
self._ends, self._bstep = ends, step
|
| 129 |
+
s = self._seg
|
| 130 |
+
if s is not None:
|
| 131 |
+
s["path"] += step
|
| 132 |
+
s["touch"] += int(touch)
|
| 133 |
+
if touch or speed_up:
|
| 134 |
+
s["driven"] += step
|
| 135 |
+
|
| 136 |
+
def _segment(self, kind, fn, *args, **kwargs):
|
| 137 |
+
c0, b0 = envs.obj_pos(self.env, CUBE), envs.obj_pos(self.env, BOARD)
|
| 138 |
+
self._seg = dict(kind=kind, step0=self.n_steps, path=0.0, driven=0.0, touch=0)
|
| 139 |
+
try:
|
| 140 |
+
rep = fn(*args, **kwargs)
|
| 141 |
+
finally:
|
| 142 |
+
s, self._seg = self._seg, None
|
| 143 |
+
c1, b1 = envs.obj_pos(self.env, CUBE), envs.obj_pos(self.env, BOARD)
|
| 144 |
+
s.update(steps=self.n_steps - s["step0"], board_dxy=(b1 - b0)[:2].round(4).tolist(),
|
| 145 |
+
cube_dxy=(c1 - c0)[:2].round(4).tolist(), cube_from_start=(c0 - self.cube0)[:2].round(4).tolist())
|
| 146 |
+
self.segments.append(s)
|
| 147 |
+
return rep
|
| 148 |
+
|
| 149 |
+
def move_to(self, target, *args, **kwargs):
|
| 150 |
+
return self._segment("move", super().move_to, target, *args, **kwargs)
|
| 151 |
+
|
| 152 |
+
def set_gripper(self, close, steps=15):
|
| 153 |
+
return self._segment("close" if close else "open", super().set_gripper, close, steps)
|
| 154 |
+
|
| 155 |
+
def pull_check(self):
|
| 156 |
+
"""Pulls (move commands that drove the board >= PULL_EPS), where the cube was when the (first) pull started,
|
| 157 |
+
and the board motion driven by the other move commands."""
|
| 158 |
+
moves = [s for s in self.segments if s["kind"] == "move"]
|
| 159 |
+
pulls = [s for s in moves if s["driven"] >= PULL_EPS]
|
| 160 |
+
stray = sum(s["driven"] for s in moves if s["driven"] < PULL_EPS)
|
| 161 |
+
pre = (float(np.linalg.norm(pulls[0]["cube_from_start"])) if pulls
|
| 162 |
+
else float(np.linalg.norm((envs.obj_pos(self.env, CUBE) - self.cube0)[:2])))
|
| 163 |
+
return dict(n_pulls=len(pulls), pulls_cm=[round(100 * s["driven"], 1) for s in pulls],
|
| 164 |
+
pre_pull_cube_cm=round(100 * pre, 1), stray_cm=round(100 * stray, 2))
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
@register_task
|
| 168 |
+
class TableclothPull(LFFTask):
|
| 169 |
+
name = "l5_tablecloth_pull"
|
| 170 |
+
level = "L5"
|
| 171 |
+
category = "dynamics_adaptation"
|
| 172 |
+
capabilities = ("Perceive", "Reason", "Utilize")
|
| 173 |
+
protocol = "cross"
|
| 174 |
+
instruction = ("Pull the wooden board out from under the red cube so that the cube ends up standing on the table "
|
| 175 |
+
"completely inside the green band. Touch only the board and its black handle, never the cube. "
|
| 176 |
+
"Only one pull is allowed per attempt: grasp the black handle, pull the board out with ONE move "
|
| 177 |
+
"command, then release it. Any other move that drags, pushes or nudges the board, before or after "
|
| 178 |
+
"the pull, counts as another pull.")
|
| 179 |
+
instruction_indirect = ("Pull the long brown plank out from under the small red block so that the block ends up "
|
| 180 |
+
"standing on the table completely inside the green stripe. Touch only the plank and its "
|
| 181 |
+
"black handle, never the block. Only one pull is allowed per attempt: grasp the black "
|
| 182 |
+
"handle, pull the plank out with ONE move command, then release it. Any other move that "
|
| 183 |
+
"drags, pushes or nudges the plank, before or after the pull, counts as another pull.")
|
| 184 |
+
|
| 185 |
+
# ------------------------------------------------------------ scene
|
| 186 |
+
def make_bddl(self):
|
| 187 |
+
board = register_generated("LffClothBoard", board_xml("lff_cloth_board"))
|
| 188 |
+
cube = register_generated("LffClothCube", box_xml("lff_cloth_cube", (C_HALF,) * 3, (0.85, 0.15, 0.15, 1.0),
|
| 189 |
+
density=2300))
|
| 190 |
+
band = register_generated("LffClothBand", band_xml("lff_cloth_band"), free=False)
|
| 191 |
+
objs = [(BOARD, board, "board_region", (0.09, -0.26, 0.11, -0.24)),
|
| 192 |
+
(CUBE, cube, "cube_region", (-0.21, 0.24, -0.19, 0.26))]
|
| 193 |
+
fixtures = [(BAND, band, "band_region", (-0.31, -0.01, -0.29, 0.01))]
|
| 194 |
+
return write_bddl(self.name, "pull the board out from under the cube", objs, fixtures=fixtures)
|
| 195 |
+
|
| 196 |
+
def sample_instance(self, seed):
|
| 197 |
+
rng = np.random.default_rng(seed)
|
| 198 |
+
mu = float(np.exp(rng.uniform(np.log(0.08), np.log(0.15))))
|
| 199 |
+
lo, hi = d_range(mu)
|
| 200 |
+
d = float(rng.uniform(lo, max(lo, hi)))
|
| 201 |
+
return dict(seed=int(seed), board_xy=[float(rng.uniform(0.03, 0.08)), float(rng.uniform(-0.08, 0.08))],
|
| 202 |
+
mu=mu, band_d=d)
|
| 203 |
+
|
| 204 |
+
def cube_start(self, inst):
|
| 205 |
+
bx, by = inst["board_xy"]
|
| 206 |
+
return np.array([bx + B_HALF[0] - LF, by])
|
| 207 |
+
|
| 208 |
+
def band_center(self, inst):
|
| 209 |
+
c = self.cube_start(inst)
|
| 210 |
+
return np.array([c[0] - inst["band_d"], c[1]])
|
| 211 |
+
|
| 212 |
+
def apply_instance(self, inst):
|
| 213 |
+
m = self.env.sim.model
|
| 214 |
+
for g in range(m.ngeom): # the band is a flat marker: no collisions
|
| 215 |
+
if (m.geom_id2name(g) or "").startswith(BAND + "_"):
|
| 216 |
+
m.geom_contype[g] = 0
|
| 217 |
+
m.geom_conaffinity[g] = 0
|
| 218 |
+
bx, by = inst["board_xy"]
|
| 219 |
+
envs.set_obj_pose(self.env, BOARD, [bx, by, envs.TABLE_Z + B_HALF[2] + 0.0005])
|
| 220 |
+
c = self.cube_start(inst)
|
| 221 |
+
envs.set_obj_pose(self.env, CUBE, [c[0], c[1], envs.TABLE_Z + 2 * B_HALF[2] + C_HALF + 0.0005])
|
| 222 |
+
envs.set_friction(self.env, BOARD, MU_BOARD, priority=1)
|
| 223 |
+
envs.set_friction(self.env, CUBE, inst["mu"], priority=2) # cube-board and cube-table contacts use mu
|
| 224 |
+
bid = m.body_name2id(self.env.fixtures_dict[BAND].root_body)
|
| 225 |
+
bc = self.band_center(inst)
|
| 226 |
+
m.body_pos[bid] = [bc[0], bc[1], envs.TABLE_Z + 0.0002]
|
| 227 |
+
m.body_quat[bid] = [1.0, 0.0, 0.0, 0.0]
|
| 228 |
+
|
| 229 |
+
def reset_instance(self, inst, recorder=None):
|
| 230 |
+
from robosuite.utils.errors import RandomizationError
|
| 231 |
+
for _ in range(20): # LIBERO's reset-time placement sampler occasionally fails; the layout is overridden
|
| 232 |
+
try:
|
| 233 |
+
self.env.reset()
|
| 234 |
+
break
|
| 235 |
+
except RandomizationError:
|
| 236 |
+
continue
|
| 237 |
+
self.apply_instance(inst)
|
| 238 |
+
self.env.sim.forward()
|
| 239 |
+
envs.settle(self.env, 10)
|
| 240 |
+
self.sk = ClothSkills(self.env, bias=self.skill_bias(inst), recorder=recorder)
|
| 241 |
+
return self.sk
|
| 242 |
+
|
| 243 |
+
# ------------------------------------------------------------ outcome
|
| 244 |
+
def cube_on_board(self):
|
| 245 |
+
c = envs.obj_pos(self.env, CUBE)
|
| 246 |
+
b = envs.obj_pos(self.env, BOARD)
|
| 247 |
+
R = self.env.sim.data.body_xmat[envs.body_id(self.env, BOARD)].reshape(3, 3)
|
| 248 |
+
local = R.T @ (c - b)
|
| 249 |
+
return bool(abs(local[0]) < B_HALF[0] + 0.005 and abs(local[1]) < B_HALF[1] + 0.005
|
| 250 |
+
and c[2] > envs.TABLE_Z + 2 * B_HALF[2] + C_HALF - 0.004)
|
| 251 |
+
|
| 252 |
+
def outcome(self, inst):
|
| 253 |
+
sk = self.sk
|
| 254 |
+
envs.settle(self.env, 60)
|
| 255 |
+
c = envs.obj_pos(self.env, CUBE)
|
| 256 |
+
c0 = self.cube_start(inst)
|
| 257 |
+
bc = self.band_center(inst)
|
| 258 |
+
moved = float(c0[0] - c[0]) # towards the robot
|
| 259 |
+
off = c[:2] - bc # + x: cube forward (away from the robot) of the band's centre line
|
| 260 |
+
upright = envs.obj_upright_cos(self.env, CUBE) > 0.95
|
| 261 |
+
on_board = self.cube_on_board()
|
| 262 |
+
on_table = c[2] < envs.TABLE_Z + C_HALF + 0.004
|
| 263 |
+
in_band = bool(abs(off[0]) <= TOL and abs(off[1]) <= BAND_HALF_Y - C_HALF)
|
| 264 |
+
pc = sk.pull_check()
|
| 265 |
+
rule = []
|
| 266 |
+
if pc["n_pulls"] > 1:
|
| 267 |
+
rule.append(f"The board was moved by {pc['n_pulls']} separate move commands "
|
| 268 |
+
f"({', '.join(f'{v:.1f}' for v in pc['pulls_cm'])} cm); only one pull is allowed.")
|
| 269 |
+
if pc["n_pulls"] and pc["pre_pull_cube_cm"] > 100 * PRE_TOL:
|
| 270 |
+
rule.append(f"When the pull started the cube had already been moved {pc['pre_pull_cube_cm']:.1f} cm by "
|
| 271 |
+
f"earlier small moves of the board; only one pull is allowed.")
|
| 272 |
+
if pc["stray_cm"] > 100 * STRAY_MAX:
|
| 273 |
+
rule.append(f"Besides the pull, other move commands moved the board {pc['stray_cm']:.1f} cm in total; "
|
| 274 |
+
f"only one pull is allowed.")
|
| 275 |
+
success = bool(in_band and on_table and upright and not on_board and not sk.touched_cube and not rule)
|
| 276 |
+
b_moved = float(np.linalg.norm(envs.obj_pos(self.env, BOARD)[:2] - np.asarray(inst["board_xy"])))
|
| 277 |
+
out = dict(success=success, touched_cube=bool(sk.touched_cube), on_board=on_board, upright=bool(upright),
|
| 278 |
+
moved_toward_robot=round(moved, 4), band_offset_x=round(float(off[0]), 4),
|
| 279 |
+
err=round(float(moved - inst["band_d"]), 4), board_moved=round(b_moved, 4),
|
| 280 |
+
one_pull=not rule, **pc)
|
| 281 |
+
side = ("forward (+x, away from the robot)" if off[0] > 0 else "backward (-x, toward the robot)")
|
| 282 |
+
where = (f"its centre is {100 * abs(off[0]):.1f} cm {side} of the band's centre line"
|
| 283 |
+
if abs(off[0]) >= 0.0005 else "its centre is on the band's centre line")
|
| 284 |
+
if sk.touched_cube:
|
| 285 |
+
out["failure"] = "touched_cube"
|
| 286 |
+
detail = "The robot touched the cube, which is not allowed."
|
| 287 |
+
elif on_board and b_moved < 0.02:
|
| 288 |
+
out["failure"] = "board_not_moved"
|
| 289 |
+
detail = "The board was not pulled; the cube is still standing on it."
|
| 290 |
+
elif on_board:
|
| 291 |
+
out["failure"] = "rode_along"
|
| 292 |
+
detail = (f"The board was pulled {100 * b_moved:.0f} cm, but the cube rode along on it: it is still on the "
|
| 293 |
+
f"board and moved {100 * moved:.1f} cm toward the robot.")
|
| 294 |
+
elif not upright:
|
| 295 |
+
out["failure"] = "toppled"
|
| 296 |
+
detail = f"The board came out from under the cube, but the cube fell over; {where}."
|
| 297 |
+
elif in_band and on_table and upright:
|
| 298 |
+
out["failure"] = None
|
| 299 |
+
detail = (f"The board came out from under the cube and the cube is standing inside the green band; {where}. "
|
| 300 |
+
f"It moved {100 * moved:.1f} cm toward the robot.")
|
| 301 |
+
else:
|
| 302 |
+
out["failure"] = "missed_band"
|
| 303 |
+
detail = (f"The board came out from under the cube and the cube is standing on the table, but not "
|
| 304 |
+
f"completely inside the green band: {where}. It moved {100 * moved:.1f} cm toward the robot.")
|
| 305 |
+
if rule and not sk.touched_cube:
|
| 306 |
+
out["failure"] = "several_pulls"
|
| 307 |
+
detail = " ".join(rule) + " " + detail
|
| 308 |
+
out["detail"] = detail
|
| 309 |
+
out["detail_indirect"] = (detail.replace("board", "plank").replace("cube", "block")
|
| 310 |
+
.replace("green band", "green stripe").replace("band's", "stripe's"))
|
| 311 |
+
return out
|
| 312 |
+
|
| 313 |
+
def feedback(self, inst, out, level="F2", indirect=False):
|
| 314 |
+
if indirect and level == "F2":
|
| 315 |
+
out = dict(out, detail=out.get("detail_indirect", out["detail"]))
|
| 316 |
+
return super().feedback(inst, out, level)
|
| 317 |
+
|
| 318 |
+
# ------------------------------------------------------------ scripted execution (cross protocol)
|
| 319 |
+
def execute(self, inst, params):
|
| 320 |
+
"""Grasp the handle (jaws across its 4 cm width) and pull the board STROKE m toward the robot at `speed`."""
|
| 321 |
+
sk = self.sk
|
| 322 |
+
b = envs.obj_pos(self.env, BOARD)
|
| 323 |
+
hx, hy = b[0] - B_HALF[0] + H_HALF[0], b[1]
|
| 324 |
+
zg = envs.TABLE_Z + 2 * B_HALF[2] + H_HALF[2]
|
| 325 |
+
sk.set_gripper(False, steps=5)
|
| 326 |
+
sk.move_to([hx, hy, zg + 0.08], yaw=0.0)
|
| 327 |
+
sk.move_to([hx, hy, zg], tol=0.003)
|
| 328 |
+
sk.set_gripper(True, steps=15)
|
| 329 |
+
sk.move_to([hx - STROKE, hy, zg], speed=float(np.clip(params["speed"], V_MIN, V_MAX)), tol=0.01,
|
| 330 |
+
max_steps=300)
|
| 331 |
+
sk.set_gripper(False, steps=8)
|
| 332 |
+
sk.move_to([hx - STROKE, hy, zg + 0.10], speed=0.3)
|
| 333 |
+
|
| 334 |
+
def default_params(self, inst):
|
| 335 |
+
"""Prior: the classic tablecloth trick -- yank as fast as the arm can."""
|
| 336 |
+
return dict(speed=0.60)
|
| 337 |
+
|
| 338 |
+
def blind_params(self, inst, attempt, rng):
|
| 339 |
+
return dict(speed=float(np.clip(0.60 + rng.normal(0, 0.06), V_MIN, V_MAX)))
|
| 340 |
+
|
| 341 |
+
def adapt_params(self, inst, history):
|
| 342 |
+
"""Bracketing search on the pull speed with the signed displacement error (riding along = far too much
|
| 343 |
+
displacement). Faster -> less displacement."""
|
| 344 |
+
pts = []
|
| 345 |
+
for h in history:
|
| 346 |
+
o = h["outcome"]
|
| 347 |
+
if o.get("failure") in ("rode_along", "board_not_moved"):
|
| 348 |
+
e = 0.10
|
| 349 |
+
elif o.get("failure") in ("touched_cube", "several_pulls"):
|
| 350 |
+
continue
|
| 351 |
+
else:
|
| 352 |
+
e = o["err"]
|
| 353 |
+
pts.append((h["params"]["speed"], e))
|
| 354 |
+
hi_err = [p for p in pts if p[1] > 0] # moved too much -> needs a faster pull
|
| 355 |
+
lo_err = [p for p in pts if p[1] < 0] # moved too little -> needs a slower pull
|
| 356 |
+
if hi_err and lo_err:
|
| 357 |
+
(v0, e0) = max(hi_err, key=lambda p: p[0]) # fastest pull that still moved it too much
|
| 358 |
+
(v1, e1) = min(lo_err, key=lambda p: p[0]) # slowest pull that moved it too little
|
| 359 |
+
if e0 >= 0.05: # rode along: no usable slope -> bisect
|
| 360 |
+
v = 0.5 * (v0 + v1)
|
| 361 |
+
else:
|
| 362 |
+
v = v0 + (v1 - v0) * e0 / (e0 - e1)
|
| 363 |
+
elif hi_err:
|
| 364 |
+
v = max(p[0] for p in hi_err) * 1.25
|
| 365 |
+
else:
|
| 366 |
+
v = min(p[0] for p in lo_err) * 0.8
|
| 367 |
+
return dict(speed=float(np.clip(v, V_MIN, V_MAX)))
|
| 368 |
+
|
| 369 |
+
def oracle_params(self, inst):
|
| 370 |
+
"""Privileged: bisection on the speed by simulating pulls with the true mu."""
|
| 371 |
+
if "_oracle_speed" in inst:
|
| 372 |
+
return dict(speed=inst["_oracle_speed"])
|
| 373 |
+
lo, hi = V_MIN, V_MAX
|
| 374 |
+
best = None
|
| 375 |
+
for _ in range(10):
|
| 376 |
+
mid = 0.5 * (lo + hi)
|
| 377 |
+
self.reset_instance(inst)
|
| 378 |
+
self.execute(inst, dict(speed=mid))
|
| 379 |
+
o = self.outcome(inst)
|
| 380 |
+
e = 0.10 if o["failure"] in ("rode_along", "board_not_moved") else o["err"]
|
| 381 |
+
if o["success"]:
|
| 382 |
+
best = (mid, e)
|
| 383 |
+
break
|
| 384 |
+
if best is None or abs(e) < abs(best[1]):
|
| 385 |
+
best = (mid, e)
|
| 386 |
+
if e > 0:
|
| 387 |
+
lo = mid
|
| 388 |
+
else:
|
| 389 |
+
hi = mid
|
| 390 |
+
inst["_oracle_speed"] = best[0]
|
| 391 |
+
self.reset_instance(inst)
|
| 392 |
+
return dict(speed=best[0])
|
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/l6_sequence.py
ADDED
|
@@ -0,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|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L6-C sequence_resume: weigh four items one by one in a given order; an emergency stop resets part of the work.
|
| 2 |
+
|
| 3 |
+
Scene: four grocery items (cream cheese, butter, chocolate pudding, popcorn -- small flat boxes), each on its
|
| 4 |
+
own round pad (four identical dark pads, flat markers), and a scale (grey square platform, static fixture).
|
| 5 |
+
Pad / scale positions and the order are random per instance.
|
| 6 |
+
|
| 7 |
+
Instruction: weigh the items one at a time in the given order. Weighing = put the item on the scale and let go;
|
| 8 |
+
the scale records a reading after the item has rested on it for 0.5 s and beeps. Then the item goes back on its
|
| 9 |
+
own pad before the next item is picked up. Every item must be weighed exactly once; the scale log cannot be
|
| 10 |
+
edited, so a second reading of an item or a reading out of turn is a terminal failure.
|
| 11 |
+
|
| 12 |
+
Interruption ("emergency stop", once per episode, inside attempt 1): while the robot carries an item, the gripper
|
| 13 |
+
opens, a safety routine puts that item back on its own pad and the arm returns to its home pose. Hidden: how
|
| 14 |
+
many items had been weighed when it happened, w in {1..4} (uniform), and the phase: the carried item was on its
|
| 15 |
+
way to the scale (not yet weighed, phase A) or on its way back (already weighed, phase B); w = 4 is always
|
| 16 |
+
phase B. After the stop every item sits on its pad and the arm is at home: the picture looks like the start of
|
| 17 |
+
the task. Which item comes next (order[w], or "nothing, call done" for w = 4) is only in the agent's own history
|
| 18 |
+
(what it carried, whether the scale had beeped).
|
| 19 |
+
|
| 20 |
+
Protocol: within (like l6_swap_interrupt). Events reported immediately (`drain_events`): the scale's beep after
|
| 21 |
+
every recorded reading, an error beep for a reading out of turn, and the emergency stop. F2 after `done` gives the
|
| 22 |
+
verdict, whether the log is complete, and which items are not on their pads (distance only), never how many
|
| 23 |
+
items have been weighed.
|
| 24 |
+
|
| 25 |
+
Scripted references (perception = simulator state):
|
| 26 |
+
oracle privileged scale log: always weighs order[len(log)] next.
|
| 27 |
+
adaptive keeps its own record of readings (an item counts as weighed when the scale beeped while it lay on
|
| 28 |
+
it); after the stop it resumes from order[len(record)] (redoes the interrupted item in phase A, goes on
|
| 29 |
+
with the next one in phase B, calls done when all four are recorded).
|
| 30 |
+
naive memoryless continuation (1 attempt): the picture after the stop shows no progress; it guesses how far
|
| 31 |
+
it got (uniform over 0..4 items weighed) and continues from there.
|
| 32 |
+
blind memoryless restart (k attempts): starts the sequence over from the first item -> a second reading of
|
| 33 |
+
an already weighed item (repeated step).
|
| 34 |
+
Extra control (not in the acceptance table): `skip` counts items it *started* to weigh (pick-ups) instead of
|
| 35 |
+
readings: correct after a phase-B stop, skips the interrupted item after a phase-A stop.
|
| 36 |
+
"""
|
| 37 |
+
import numpy as np
|
| 38 |
+
|
| 39 |
+
from .. import envs
|
| 40 |
+
from ..bddl import write_bddl
|
| 41 |
+
from ..objects import _fmt, _wrap, register_generated
|
| 42 |
+
from ..skills import ROT_SCALE, _rot_err
|
| 43 |
+
from ..task_base import LFFTask, register_task
|
| 44 |
+
from .l6_swap import _pad_xml as _swap_pad_xml
|
| 45 |
+
|
| 46 |
+
ITEMS = ["cream_cheese_1", "butter_1", "chocolate_pudding_1", "popcorn_1"]
|
| 47 |
+
CATS = {"cream_cheese_1": "cream_cheese", "butter_1": "butter", "chocolate_pudding_1": "chocolate_pudding",
|
| 48 |
+
"popcorn_1": "popcorn"}
|
| 49 |
+
NAME = {"cream_cheese_1": "cream cheese", "butter_1": "butter", "chocolate_pudding_1": "chocolate pudding",
|
| 50 |
+
"popcorn_1": "popcorn"}
|
| 51 |
+
DESCR = {"cream_cheese_1": "the pale blue box with the oval logo", "butter_1": "the red box with white lettering",
|
| 52 |
+
"chocolate_pudding_1": "the dark brown box", "popcorn_1": "the blue-and-yellow box"}
|
| 53 |
+
N_ITEMS = len(ITEMS)
|
| 54 |
+
PADS = [f"pad_{i + 1}" for i in range(N_ITEMS)]
|
| 55 |
+
PAD_R = 0.055
|
| 56 |
+
PAD_HALF_T = 0.0008
|
| 57 |
+
|
| 58 |
+
SCALE_HALF = 0.06 # platform half size (12 x 12 cm)
|
| 59 |
+
SCALE_BASE_HALF = 0.067
|
| 60 |
+
SCALE_TOP = 0.020 # platform top above the table
|
| 61 |
+
SCALE_BASE_H = 0.012
|
| 62 |
+
SCALE_RGBA = (0.78, 0.79, 0.80, 1.0)
|
| 63 |
+
SCALE_BASE_RGBA = (0.20, 0.20, 0.22, 1.0)
|
| 64 |
+
|
| 65 |
+
BASE_X = -0.66
|
| 66 |
+
REGION = (-0.27, 0.05, -0.27, 0.27)
|
| 67 |
+
REACH = 0.70
|
| 68 |
+
PAD_MIN = 0.16
|
| 69 |
+
SCALE_MIN = 0.175
|
| 70 |
+
SUCC_R = 0.04 # item centre within 4 cm of its pad centre
|
| 71 |
+
GRASP_DZ = 0.012 # gripper-site height above the support surface for a top-down grasp of the flat boxes
|
| 72 |
+
Z_CARRY = envs.TABLE_Z + 0.15
|
| 73 |
+
DWELL = 10 # control steps (0.5 s) at rest on the scale before a reading is recorded
|
| 74 |
+
LIFTED = 0.04
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def scale_xml(model_name):
|
| 78 |
+
parts = [((0, 0, SCALE_BASE_H / 2), (SCALE_BASE_HALF, SCALE_BASE_HALF, SCALE_BASE_H / 2), SCALE_BASE_RGBA),
|
| 79 |
+
((0, 0, (SCALE_BASE_H + SCALE_TOP) / 2), (SCALE_HALF, SCALE_HALF, (SCALE_TOP - SCALE_BASE_H) / 2),
|
| 80 |
+
SCALE_RGBA)]
|
| 81 |
+
g = []
|
| 82 |
+
for k, (pos, half, rgba) in enumerate(parts):
|
| 83 |
+
g.append(f' <geom name="{model_name}_g{k}" type="box" pos="{_fmt(pos)}" size="{_fmt(half)}" '
|
| 84 |
+
f'rgba="{_fmt(rgba)}" density="1000" friction="1.0 0.005 0.0001" group="0" />')
|
| 85 |
+
g.append(f' <geom type="box" pos="{_fmt(pos)}" size="{_fmt(half)}" rgba="{_fmt(rgba)}" '
|
| 86 |
+
f'conaffinity="0" contype="0" group="1" />')
|
| 87 |
+
return _wrap(model_name, "\n".join(g), SCALE_TOP / 2, float(np.hypot(SCALE_BASE_HALF, SCALE_BASE_HALF)))
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _yaw_of(env, obj):
|
| 91 |
+
R = env.sim.data.body_xmat[envs.body_id(env, obj)].reshape(3, 3)
|
| 92 |
+
yaw = float(np.arctan2(R[1, 0], R[0, 0])) # long axis of the boxes = body x
|
| 93 |
+
return (yaw + np.pi / 2) % np.pi - np.pi / 2
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@register_task
|
| 97 |
+
class SequenceResume(LFFTask):
|
| 98 |
+
name = "l6_sequence_resume"
|
| 99 |
+
level = "L6"
|
| 100 |
+
category = "procedural_memory"
|
| 101 |
+
capabilities = ("Perceive", "Save", "Retrieve", "Utilize")
|
| 102 |
+
protocol = "within"
|
| 103 |
+
agent_max_steps = 100 # robot commands per attempt for agents (a VLM needs ~60-75)
|
| 104 |
+
max_attempts = 5
|
| 105 |
+
_TEMPLATE = ("Weigh the four grocery items one at a time, in this order: {order}. To weigh an item, put it on "
|
| 106 |
+
"the grey scale and let go of it; the scale beeps when it has recorded the reading. Then put the "
|
| 107 |
+
"item back on its own round pad before you pick up the next item. Weigh every item exactly once: "
|
| 108 |
+
"the scale logs every reading, and the log cannot be edited.")
|
| 109 |
+
instruction = _TEMPLATE.format(order="(given per instance)")
|
| 110 |
+
instruction_indirect = instruction
|
| 111 |
+
inject = True
|
| 112 |
+
agent_object_names = [NAME[i] for i in ITEMS] + ["scale", "round pads"]
|
| 113 |
+
|
| 114 |
+
def agent_instruction(self, inst, variant="direct"):
|
| 115 |
+
names = DESCR if variant == "indirect" else NAME
|
| 116 |
+
order = [names[o] for o in inst["order"]]
|
| 117 |
+
return self._TEMPLATE.format(order=", ".join(order[:-1]) + ", then " + order[-1])
|
| 118 |
+
|
| 119 |
+
def __init__(self, cam_res=None):
|
| 120 |
+
super().__init__(cam_res)
|
| 121 |
+
self._mon = False
|
| 122 |
+
self._latch = None
|
| 123 |
+
orig_step = self.env.step
|
| 124 |
+
|
| 125 |
+
def step(action): # per-control-step monitor (also for attempts driven by the agent harness)
|
| 126 |
+
if self._latch is not None:
|
| 127 |
+
action = self._homing_action()
|
| 128 |
+
ret = orig_step(action)
|
| 129 |
+
if self._mon:
|
| 130 |
+
self._monitor()
|
| 131 |
+
return ret
|
| 132 |
+
|
| 133 |
+
self.env.step = step
|
| 134 |
+
|
| 135 |
+
# ------------------------------------------------------------ scene
|
| 136 |
+
def make_bddl(self):
|
| 137 |
+
pads = [register_generated(f"LffSeqPad{L}", _swap_pad_xml(f"lff_seq_pad_{L.lower()}")) for L in "ABCD"]
|
| 138 |
+
scale = register_generated("LffSeqScale", scale_xml("lff_seq_scale"), free=False)
|
| 139 |
+
objs = [(o, CATS[o], f"r{i}", (-0.26 + 0.15 * i - 0.01, -0.31, -0.26 + 0.15 * i + 0.01, -0.29))
|
| 140 |
+
for i, o in enumerate(ITEMS)]
|
| 141 |
+
objs += [(PADS[i], pads[i], f"p{i}", (-0.26 + 0.15 * i - 0.01, 0.29, -0.26 + 0.15 * i + 0.01, 0.31))
|
| 142 |
+
for i in range(N_ITEMS)]
|
| 143 |
+
fx = [("scale_1", scale, "scale_region", (0.19, -0.01, 0.21, 0.01))]
|
| 144 |
+
return write_bddl(self.name, "Weigh the four items one at a time in the given order", objs, fx) # no ; in BDDL
|
| 145 |
+
|
| 146 |
+
def sample_instance(self, seed):
|
| 147 |
+
rng = np.random.default_rng(seed)
|
| 148 |
+
for _ in range(5000):
|
| 149 |
+
pts = []
|
| 150 |
+
while len(pts) < N_ITEMS + 1:
|
| 151 |
+
p = np.array([rng.uniform(*REGION[:2]), rng.uniform(*REGION[2:])])
|
| 152 |
+
if np.hypot(p[0] - BASE_X, p[1]) > REACH:
|
| 153 |
+
continue
|
| 154 |
+
pts.append(p)
|
| 155 |
+
scale, pads = pts[0], np.array(pts[1:])
|
| 156 |
+
dp = [np.linalg.norm(pads[i] - pads[j]) for i in range(N_ITEMS) for j in range(i)]
|
| 157 |
+
if min(dp) >= PAD_MIN and min(np.linalg.norm(pads - scale, axis=1)) >= SCALE_MIN:
|
| 158 |
+
break
|
| 159 |
+
else:
|
| 160 |
+
raise RuntimeError("could not sample a layout")
|
| 161 |
+
order = [ITEMS[i] for i in rng.permutation(N_ITEMS)]
|
| 162 |
+
w = int(rng.integers(1, N_ITEMS + 1)) # items weighed when the stop happens
|
| 163 |
+
phase = "B" if w == N_ITEMS else str(rng.choice(["A", "B"]))
|
| 164 |
+
inst = dict(seed=int(seed), order=order, pads=pads.round(4).tolist(), scale_xy=scale.round(4).tolist(),
|
| 165 |
+
item_off=[[float(v) for v in rng.uniform(-0.008, 0.008, 2)] for _ in range(N_ITEMS)],
|
| 166 |
+
item_yaw=[float(v) for v in rng.uniform(-0.3, 0.3, N_ITEMS)],
|
| 167 |
+
stop_w=w, stop_phase=phase, trigger_dist=float(rng.uniform(0.05, 0.09)),
|
| 168 |
+
stop_off=[float(v) for v in rng.uniform(-0.008, 0.008, 2)],
|
| 169 |
+
stop_yaw=float(rng.uniform(-0.3, 0.3)))
|
| 170 |
+
inst["stop_item"] = order[w] if phase == "A" else order[w - 1]
|
| 171 |
+
self.instruction = self.agent_instruction(inst, "direct") # make_video prints task.instruction
|
| 172 |
+
self.instruction_indirect = self.agent_instruction(inst, "indirect")
|
| 173 |
+
return inst
|
| 174 |
+
|
| 175 |
+
def apply_instance(self, inst):
|
| 176 |
+
m = self.env.sim.model
|
| 177 |
+
for i, p in enumerate(inst["pads"]):
|
| 178 |
+
envs.set_obj_pose(self.env, PADS[i], [p[0], p[1], envs.TABLE_Z + PAD_HALF_T + 0.0001])
|
| 179 |
+
bid = m.body_name2id(self.env.fixtures_dict["scale_1"].root_body)
|
| 180 |
+
m.body_pos[bid] = [inst["scale_xy"][0], inst["scale_xy"][1], envs.TABLE_Z]
|
| 181 |
+
m.body_quat[bid] = [1, 0, 0, 0]
|
| 182 |
+
for i, o in enumerate(ITEMS):
|
| 183 |
+
p = np.asarray(inst["pads"][i]) + inst["item_off"][i]
|
| 184 |
+
envs.place_upright(self.env, o, p, inst["item_yaw"][i])
|
| 185 |
+
self.env.sim.forward()
|
| 186 |
+
self._inst = inst
|
| 187 |
+
self.pad_of = {o: i for i, o in enumerate(ITEMS)} # item i starts on pad i (pad positions are random)
|
| 188 |
+
self.log = [] # scale readings (item names)
|
| 189 |
+
self.error = None
|
| 190 |
+
self.stop = None
|
| 191 |
+
self.events = []
|
| 192 |
+
self._event_cursor = 0
|
| 193 |
+
self._outcome_cursor = 0
|
| 194 |
+
self._dwell = {o: 0 for o in ITEMS}
|
| 195 |
+
self._visit = {o: False for o in ITEMS}
|
| 196 |
+
self._prev = {}
|
| 197 |
+
self._latch = None
|
| 198 |
+
self._mon = False
|
| 199 |
+
|
| 200 |
+
def reset_instance(self, inst, recorder=None):
|
| 201 |
+
self._mon = False
|
| 202 |
+
self._latch = None
|
| 203 |
+
sk = super().reset_instance(inst, recorder=recorder)
|
| 204 |
+
self._home = sk.eef_pos()
|
| 205 |
+
self.rest_dz = {o: float(envs.obj_pos(self.env, o)[2] - envs.TABLE_Z) for o in ITEMS}
|
| 206 |
+
self._prev = {o: envs.obj_pos(self.env, o) for o in ITEMS}
|
| 207 |
+
self._mon = True
|
| 208 |
+
return sk
|
| 209 |
+
|
| 210 |
+
def go_home(self):
|
| 211 |
+
p = self.sk.eef_pos()
|
| 212 |
+
self.sk.move_to([p[0], p[1], max(p[2], self._home[2])])
|
| 213 |
+
self.sk.move_to(self._home)
|
| 214 |
+
|
| 215 |
+
# ------------------------------------------------------------ helpers
|
| 216 |
+
def scale_xy(self):
|
| 217 |
+
return np.asarray(self._inst["scale_xy"], float)
|
| 218 |
+
|
| 219 |
+
def pad_xy(self, o):
|
| 220 |
+
return np.asarray(self._inst["pads"][self.pad_of[o]], float)
|
| 221 |
+
|
| 222 |
+
def on_scale(self, o, p=None):
|
| 223 |
+
p = envs.obj_pos(self.env, o) if p is None else p
|
| 224 |
+
d = np.abs(p[:2] - self.scale_xy())
|
| 225 |
+
return bool(d.max() <= SCALE_HALF and abs(p[2] - (envs.TABLE_Z + SCALE_TOP + self.rest_dz[o])) < 0.008)
|
| 226 |
+
|
| 227 |
+
def on_own_pad(self, o):
|
| 228 |
+
p = envs.obj_pos(self.env, o)
|
| 229 |
+
return bool(np.linalg.norm(p[:2] - self.pad_xy(o)) <= SUCC_R
|
| 230 |
+
and abs(p[2] - (envs.TABLE_Z + self.rest_dz[o])) < 0.01 and not self.sk.holding(o))
|
| 231 |
+
|
| 232 |
+
# ------------------------------------------------------------ monitor: scale readings + emergency stop
|
| 233 |
+
def _monitor(self):
|
| 234 |
+
env = self.env
|
| 235 |
+
if self._latch is not None:
|
| 236 |
+
if len(self.sk.log) > self._latch and np.linalg.norm(self.sk.eef_pos() - self._home) < 0.01:
|
| 237 |
+
self._latch = None
|
| 238 |
+
for o in ITEMS:
|
| 239 |
+
p = envs.obj_pos(env, o)
|
| 240 |
+
still = np.linalg.norm(p - self._prev[o]) < 0.0008
|
| 241 |
+
self._prev[o] = p
|
| 242 |
+
if self.on_scale(o, p):
|
| 243 |
+
if still and not self.sk.holding(o):
|
| 244 |
+
self._dwell[o] += 1
|
| 245 |
+
if self._dwell[o] >= DWELL and not self._visit[o]:
|
| 246 |
+
self._visit[o] = True
|
| 247 |
+
self._record(o)
|
| 248 |
+
else:
|
| 249 |
+
self._dwell[o] = 0
|
| 250 |
+
else:
|
| 251 |
+
self._dwell[o] = 0
|
| 252 |
+
if np.abs(p[:2] - self.scale_xy()).max() > SCALE_HALF or \
|
| 253 |
+
p[2] > envs.TABLE_Z + SCALE_TOP + self.rest_dz[o] + 0.02:
|
| 254 |
+
self._visit[o] = False
|
| 255 |
+
if self.inject and self.stop is None:
|
| 256 |
+
self._maybe_stop()
|
| 257 |
+
|
| 258 |
+
def _record(self, o):
|
| 259 |
+
self.log.append(o)
|
| 260 |
+
k = len(self.log)
|
| 261 |
+
ok = self.log == self._inst["order"][:k]
|
| 262 |
+
if ok:
|
| 263 |
+
self.events.append(dict(step=int(self.sk.n_steps), kind="beep", obj=o,
|
| 264 |
+
text="The scale beeped: reading recorded."))
|
| 265 |
+
else:
|
| 266 |
+
if self.error is None:
|
| 267 |
+
self.error = dict(item=o, position=k, step=int(self.sk.n_steps),
|
| 268 |
+
kind="repeat" if self.log.count(o) > 1 else "out_of_order")
|
| 269 |
+
self.events.append(dict(step=int(self.sk.n_steps), kind="error", obj=o,
|
| 270 |
+
text="The scale beeped three times: error, this reading does not follow the "
|
| 271 |
+
"requested order. The log cannot be edited."))
|
| 272 |
+
|
| 273 |
+
def _maybe_stop(self):
|
| 274 |
+
inst = self._inst
|
| 275 |
+
o, w = inst["stop_item"], inst["stop_w"]
|
| 276 |
+
if self.log != inst["order"][:w]:
|
| 277 |
+
return
|
| 278 |
+
p = envs.obj_pos(self.env, o)
|
| 279 |
+
if inst["stop_phase"] == "A":
|
| 280 |
+
if p[2] < envs.TABLE_Z + self.rest_dz[o] + LIFTED:
|
| 281 |
+
return
|
| 282 |
+
if np.linalg.norm(p[:2] - self.pad_xy(o)) < inst["trigger_dist"]:
|
| 283 |
+
return
|
| 284 |
+
else:
|
| 285 |
+
if p[2] < envs.TABLE_Z + SCALE_TOP + self.rest_dz[o] + LIFTED:
|
| 286 |
+
return
|
| 287 |
+
if np.linalg.norm(p[:2] - self.scale_xy()) < inst["trigger_dist"]:
|
| 288 |
+
return
|
| 289 |
+
if not self.sk.holding(o):
|
| 290 |
+
return
|
| 291 |
+
self._do_stop(o)
|
| 292 |
+
|
| 293 |
+
def _do_stop(self, o):
|
| 294 |
+
inst = self._inst
|
| 295 |
+
xy = self.pad_xy(o) + np.asarray(inst["stop_off"])
|
| 296 |
+
envs.place_upright(self.env, o, xy, inst["stop_yaw"])
|
| 297 |
+
self.sk.grip = -1.0
|
| 298 |
+
self.sk.yaw = 0.0
|
| 299 |
+
self._latch = len(self.sk.log) # drive the arm home until the current primitive has returned
|
| 300 |
+
self._prev[o] = envs.obj_pos(self.env, o)
|
| 301 |
+
self.env.sim.forward()
|
| 302 |
+
text = ("Emergency stop! The gripper opened, the safety routine put the item the robot was holding back on "
|
| 303 |
+
"its pad and moved the arm to its home pose. You may continue the task.")
|
| 304 |
+
self.stop = dict(item=o, phase=inst["stop_phase"], weighed=len(self.log), step=int(self.sk.n_steps))
|
| 305 |
+
self.events.append(dict(step=int(self.sk.n_steps), kind="stop", obj=o, text=text))
|
| 306 |
+
|
| 307 |
+
def _homing_action(self):
|
| 308 |
+
sk = self.sk
|
| 309 |
+
a = np.zeros(self.env.action_dim)
|
| 310 |
+
a[:3] = np.clip((self._home - sk.eef_pos()) / sk.pos_scale, -1, 1)
|
| 311 |
+
a[3:6] = np.clip(_rot_err(sk.R0, sk.eef_mat()) / ROT_SCALE, -1, 1)
|
| 312 |
+
a[6] = -1.0
|
| 313 |
+
return a
|
| 314 |
+
|
| 315 |
+
def drain_events(self):
|
| 316 |
+
ev = self.events[self._event_cursor:]
|
| 317 |
+
self._event_cursor = len(self.events)
|
| 318 |
+
return [e["text"] for e in ev]
|
| 319 |
+
|
| 320 |
+
# ------------------------------------------------------------ outcome
|
| 321 |
+
def outcome(self, inst):
|
| 322 |
+
envs.settle(self.env, 20)
|
| 323 |
+
order = inst["order"]
|
| 324 |
+
complete = self.log == order
|
| 325 |
+
terminal = self.error is not None
|
| 326 |
+
off = [o for o in ITEMS if not self.on_own_pad(o)]
|
| 327 |
+
success = bool(complete and not off and not terminal)
|
| 328 |
+
if success:
|
| 329 |
+
head = "All four items were weighed once, in the requested order, and are back on their pads."
|
| 330 |
+
elif terminal:
|
| 331 |
+
head = ("The scale log does not follow the requested order (an item was weighed a second time or out "
|
| 332 |
+
"of turn). The log cannot be edited, so the task can no longer be completed.")
|
| 333 |
+
elif complete:
|
| 334 |
+
head = "Every item has been weighed, but not every item is back on its own pad."
|
| 335 |
+
else:
|
| 336 |
+
head = "Not every item has been weighed yet."
|
| 337 |
+
parts = []
|
| 338 |
+
if not success and not terminal:
|
| 339 |
+
for o in off:
|
| 340 |
+
p = envs.obj_pos(self.env, o)
|
| 341 |
+
if self.sk.holding(o):
|
| 342 |
+
parts.append(f"the {NAME[o]} is still in the gripper")
|
| 343 |
+
elif self.on_scale(o, p):
|
| 344 |
+
parts.append(f"the {NAME[o]} is on the scale")
|
| 345 |
+
else:
|
| 346 |
+
d = np.linalg.norm(p[:2] - self.pad_xy(o))
|
| 347 |
+
parts.append(f"the {NAME[o]} is {100 * d:.0f} cm from the centre of its pad")
|
| 348 |
+
detail = head + (" Also: " + "; ".join(parts) + "." if parts else "")
|
| 349 |
+
new = [e for e in self.events[self._outcome_cursor:] if e["kind"] == "stop"]
|
| 350 |
+
self._outcome_cursor = len(self.events)
|
| 351 |
+
if new:
|
| 352 |
+
detail = "During this attempt: " + " ".join(e["text"] for e in new) + " " + detail
|
| 353 |
+
return dict(success=success, terminal=terminal, log=[NAME[o] for o in self.log], n_weighed=len(self.log),
|
| 354 |
+
complete=complete, error=self.error, stop=self.stop,
|
| 355 |
+
off_pad=[NAME[o] for o in off], detail=detail)
|
| 356 |
+
|
| 357 |
+
# ------------------------------------------------------------ motion (scripted policies)
|
| 358 |
+
def _support_z(self, o):
|
| 359 |
+
p = envs.obj_pos(self.env, o)
|
| 360 |
+
return envs.TABLE_Z + (SCALE_TOP if self.on_scale(o, p) or
|
| 361 |
+
(np.abs(p[:2] - self.scale_xy()).max() < SCALE_HALF) else 0.0)
|
| 362 |
+
|
| 363 |
+
def _n_stops(self):
|
| 364 |
+
return sum(e["kind"] == "stop" for e in self.events)
|
| 365 |
+
|
| 366 |
+
def _pick(self, o):
|
| 367 |
+
sk = self.sk
|
| 368 |
+
for _ in range(2):
|
| 369 |
+
p = envs.obj_pos(self.env, o)
|
| 370 |
+
sk.grasp_at(p[:2], self._support_z(o) + GRASP_DZ, yaw=_yaw_of(self.env, o), lift=0.12)
|
| 371 |
+
if sk.holding(o):
|
| 372 |
+
return True
|
| 373 |
+
sk.set_gripper(False, steps=8)
|
| 374 |
+
sk.move_to([p[0], p[1], self._support_z(o) + GRASP_DZ + 0.12])
|
| 375 |
+
return False
|
| 376 |
+
|
| 377 |
+
def _carry_to(self, o, xy, z_support):
|
| 378 |
+
"""Carry the held item to xy and put it down. Returns False if an emergency stop happened."""
|
| 379 |
+
sk = self.sk
|
| 380 |
+
n0 = self._n_stops()
|
| 381 |
+
sk.move_to([xy[0], xy[1], Z_CARRY])
|
| 382 |
+
if self._n_stops() > n0:
|
| 383 |
+
return False
|
| 384 |
+
sk.move_to([xy[0], xy[1], z_support + GRASP_DZ + 0.004], tol=0.004)
|
| 385 |
+
sk.set_gripper(False, steps=12)
|
| 386 |
+
sk.move_to([xy[0], xy[1], z_support + GRASP_DZ + 0.10])
|
| 387 |
+
return self._n_stops() == n0
|
| 388 |
+
|
| 389 |
+
def _weigh(self, o):
|
| 390 |
+
"""Weigh one item (pad -> scale -> pad). Returns (status, beeped): status 'ok' / 'stop_A' / 'stop_B' /
|
| 391 |
+
'no_grasp'; beeped = the scale beeped while the item lay on it (what the agent hears)."""
|
| 392 |
+
n_beep = sum(e["kind"] in ("beep", "error") for e in self.events)
|
| 393 |
+
if not self._pick(o):
|
| 394 |
+
return "no_grasp", False
|
| 395 |
+
if not self._carry_to(o, self.scale_xy(), envs.TABLE_Z + SCALE_TOP):
|
| 396 |
+
return "stop_A", False
|
| 397 |
+
self.sk.hold(6)
|
| 398 |
+
beeped = sum(e["kind"] in ("beep", "error") for e in self.events) > n_beep
|
| 399 |
+
if not self._pick(o):
|
| 400 |
+
return "no_grasp", beeped
|
| 401 |
+
if not self._carry_to(o, self.pad_xy(o), envs.TABLE_Z):
|
| 402 |
+
return "stop_B", beeped
|
| 403 |
+
return "ok", beeped
|
| 404 |
+
|
| 405 |
+
def _fix_pads(self, log):
|
| 406 |
+
for o in ITEMS:
|
| 407 |
+
if not self.on_own_pad(o) and not self.on_scale(o):
|
| 408 |
+
if self._pick(o):
|
| 409 |
+
self._carry_to(o, self.pad_xy(o), envs.TABLE_Z)
|
| 410 |
+
log.append((NAME[o], "back to pad"))
|
| 411 |
+
|
| 412 |
+
def _run_from(self, k, record, log, stop_on_stop=False):
|
| 413 |
+
"""Weigh order[k:] in turn, keeping `record` (the policy's own list of readings it heard)."""
|
| 414 |
+
order = self._inst["order"]
|
| 415 |
+
i = k
|
| 416 |
+
guard = 0
|
| 417 |
+
while i < len(order) and guard < 10 and self.error is None:
|
| 418 |
+
guard += 1
|
| 419 |
+
o = order[i]
|
| 420 |
+
st, beeped = self._weigh(o)
|
| 421 |
+
log.append((NAME[o], st, beeped))
|
| 422 |
+
if beeped:
|
| 423 |
+
record.append(o)
|
| 424 |
+
if st == "no_grasp":
|
| 425 |
+
continue
|
| 426 |
+
if st.startswith("stop"):
|
| 427 |
+
if stop_on_stop:
|
| 428 |
+
return "stopped"
|
| 429 |
+
i = len(record) # resume from the own record
|
| 430 |
+
continue
|
| 431 |
+
i += 1
|
| 432 |
+
return "ok"
|
| 433 |
+
|
| 434 |
+
# ------------------------------------------------------------ scripted references (within protocol)
|
| 435 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 436 |
+
k = k or self.max_attempts
|
| 437 |
+
rng = np.random.default_rng(seed + 104729)
|
| 438 |
+
self.reset_instance(inst)
|
| 439 |
+
order = inst["order"]
|
| 440 |
+
history = []
|
| 441 |
+
record = [] # adaptive's Save: readings it heard
|
| 442 |
+
for a in range(k):
|
| 443 |
+
log = []
|
| 444 |
+
plan = dict(kind=kind, steps=log)
|
| 445 |
+
if a == 0:
|
| 446 |
+
if kind == "oracle":
|
| 447 |
+
while len(self.log) < len(order) and self.error is None and len(log) < 12:
|
| 448 |
+
o = order[len(self.log)] # privileged scale log
|
| 449 |
+
st, _ = self._weigh(o)
|
| 450 |
+
log.append((NAME[o], st))
|
| 451 |
+
plan["recovery"] = "oracle: privileged scale log"
|
| 452 |
+
elif kind == "adaptive":
|
| 453 |
+
self._run_from(0, record, log)
|
| 454 |
+
plan["recovery"] = "own record of readings: resume from order[len(record)]"
|
| 455 |
+
elif kind == "skip":
|
| 456 |
+
started = []
|
| 457 |
+
i = 0
|
| 458 |
+
while i < len(order) and self.error is None and len(log) < 12:
|
| 459 |
+
o = order[i]
|
| 460 |
+
st, beeped = self._weigh(o)
|
| 461 |
+
log.append((NAME[o], st, beeped))
|
| 462 |
+
if st == "no_grasp":
|
| 463 |
+
continue
|
| 464 |
+
started.append(o)
|
| 465 |
+
i = len(started) # counts started items, not readings
|
| 466 |
+
plan["recovery"] = "counts items it started to weigh (the interrupted one too)"
|
| 467 |
+
else: # memoryless after the stop
|
| 468 |
+
r = self._run_from(0, record, log, stop_on_stop=True)
|
| 469 |
+
if r == "stopped":
|
| 470 |
+
if kind == "naive":
|
| 471 |
+
g = int(rng.integers(0, len(order) + 1))
|
| 472 |
+
plan["recovery"] = f"memoryless: guesses {g} items already weighed"
|
| 473 |
+
self._run_from(g, [], log)
|
| 474 |
+
elif kind == "blind":
|
| 475 |
+
plan["recovery"] = "memoryless restart from the first item"
|
| 476 |
+
self._run_from(0, [], log)
|
| 477 |
+
else:
|
| 478 |
+
raise ValueError(kind)
|
| 479 |
+
else:
|
| 480 |
+
plan["recovery"] = "none (no stop)"
|
| 481 |
+
else:
|
| 482 |
+
if kind in ("adaptive", "oracle", "skip"):
|
| 483 |
+
plan["recovery"] = "memory + F2: put items back on their pads / finish from own record"
|
| 484 |
+
if kind == "adaptive" and len(record) < len(order):
|
| 485 |
+
self._run_from(len(record), record, log)
|
| 486 |
+
if kind == "skip" and not history[-1]["outcome"]["complete"]:
|
| 487 |
+
# F2 says the log is incomplete: with memory, the item carried at the stop was not weighed
|
| 488 |
+
stopped = [s[0] for h in history for s in h["params"]["steps"] if str(s[1]).startswith("stop")]
|
| 489 |
+
if stopped:
|
| 490 |
+
o = next(i for i in ITEMS if NAME[i] == stopped[-1])
|
| 491 |
+
st, _ = self._weigh(o)
|
| 492 |
+
log.append((NAME[o], st))
|
| 493 |
+
plan["recovery"] = "memory + F2 'not every item weighed': weigh the item carried at the stop"
|
| 494 |
+
self._fix_pads(log)
|
| 495 |
+
elif kind == "blind":
|
| 496 |
+
plan["recovery"] = "memoryless restart from the first item"
|
| 497 |
+
self._run_from(0, [], log)
|
| 498 |
+
else:
|
| 499 |
+
raise ValueError(kind)
|
| 500 |
+
self.go_home()
|
| 501 |
+
out = self.outcome(inst)
|
| 502 |
+
history.append(dict(attempt=a + 1, params=plan, outcome=out))
|
| 503 |
+
if on_attempt:
|
| 504 |
+
on_attempt(a, plan, out)
|
| 505 |
+
if out["success"] or out["terminal"] or kind in ("oracle", "naive"):
|
| 506 |
+
break
|
| 507 |
+
return history
|
| 508 |
+
|
| 509 |
+
def default_params(self, inst):
|
| 510 |
+
return dict(policy="naive")
|
| 511 |
+
|
| 512 |
+
def oracle_params(self, inst):
|
| 513 |
+
return dict(policy="oracle")
|
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/lh_split_calibration.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Two-workstation packing: calibration transfer, collateral damage, geometric fit.
|
| 2 |
+
|
| 3 |
+
A repeatable command-coordinate calibration varies with workstation (sign of y),
|
| 4 |
+
not with phase or policy. No object poses are written after reset. Learning a
|
| 5 |
+
far-workstation correction and blindly reusing it at the near destination can
|
| 6 |
+
undo the earlier placement. A long module must also be aligned with its tray.
|
| 7 |
+
"""
|
| 8 |
+
import numpy as np
|
| 9 |
+
import xml.etree.ElementTree as ET
|
| 10 |
+
from .. import envs
|
| 11 |
+
from ..bddl import write_bddl
|
| 12 |
+
from ..objects import box_xml,bin_xml,register_generated
|
| 13 |
+
from ..skills import Skills
|
| 14 |
+
from ..task_base import LFFTask,register_task
|
| 15 |
+
from .lh_shelf_droop import jar_xml,JAR_H,KNOB_Z
|
| 16 |
+
from .lh_lid_box import mark_xml
|
| 17 |
+
|
| 18 |
+
RED='module_red_1';BLUE='module_blue_1';HALF=np.array([.045,.012,.012])
|
| 19 |
+
class SplitSkills(Skills):
|
| 20 |
+
def __init__(self,env,task,recorder=None):
|
| 21 |
+
super().__init__(env,recorder=recorder);self.task=task;self.correction=np.zeros(3)
|
| 22 |
+
def move_to(self,target,*a,**kw):
|
| 23 |
+
q=np.array(target)-self.correction
|
| 24 |
+
self.bias=np.array(self.task.inst['far_bias'] if q[1]>.04 else self.task.inst['near_bias'])
|
| 25 |
+
rep=super().move_to(q,*a,**kw);rep['pos']=np.round(self.reported_eef_pos(),4).tolist();return rep
|
| 26 |
+
def reported_eef_pos(self):return self.eef_pos()-self.bias
|
| 27 |
+
def _act(self,dpos,drot,grip):
|
| 28 |
+
super()._act(dpos,drot,grip);self.task.monitor_step()
|
| 29 |
+
|
| 30 |
+
@register_task
|
| 31 |
+
class SplitCalibration(LFFTask):
|
| 32 |
+
name='lh_split_calibration';level='L1';category='system_identification';failure_causes=('L1','L2','L4');failure_types=failure_causes
|
| 33 |
+
protocol='cross';max_attempts=5;agent_max_steps=240
|
| 34 |
+
instruction=('Prepare the two modules for handover: stand the red module on its red square, and fit the entire '
|
| 35 |
+
'long blue module inside the narrow tray. Leave both released and stable, with the gripper open '
|
| 36 |
+
'and clear. The red module has a graspable top knob. The work areas are on opposite sides of the desk.')
|
| 37 |
+
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')
|
| 38 |
+
def make_bddl(self):
|
| 39 |
+
rr=ET.fromstring(jar_xml('split_red',(.8,.15,.1,1)))
|
| 40 |
+
for g in rr.findall('.//geom'):
|
| 41 |
+
if g.get('type')=='box':
|
| 42 |
+
sz=np.fromstring(g.get('size'),sep=' ');sz[:2]*=.6;g.set('size',' '.join(map(str,sz)))
|
| 43 |
+
r=register_generated('LffSplitRed',ET.tostring(rr,encoding='unicode'))
|
| 44 |
+
b=register_generated('LffSplitBlue',box_xml('split_blue',HALF,(.1,.3,.85,1),density=1000))
|
| 45 |
+
tray=register_generated('LffSplitTray',bin_xml('split_tray',(.051,.019),.022),free=False)
|
| 46 |
+
mark=register_generated('LffSplitMark',mark_xml('split_mark',(.8,.1,.1,1)),free=False)
|
| 47 |
+
return write_bddl(self.name,self.instruction,[(RED,r,'red_region',(-.36,-.16,-.35,-.15)),(BLUE,b,'blue_region',(-.17,.23,-.16,.24))],
|
| 48 |
+
[('tray_1',tray,'tray_region',(.2,-.3,.21,-.29)),('mark_1',mark,'mark_region',(.2,.3,.21,.31))])
|
| 49 |
+
def sample_instance(self,seed):
|
| 50 |
+
rng=np.random.default_rng(seed);v=float(rng.uniform(.053,.057))
|
| 51 |
+
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])
|
| 52 |
+
def apply_instance(self,i):
|
| 53 |
+
self.inst=i;m=self.env.sim.model
|
| 54 |
+
envs.set_obj_pose(self.env,RED,[*i['red_xy'],envs.TABLE_Z+JAR_H/2+.001]);envs.scale_mass(self.env,RED,.08)
|
| 55 |
+
envs.set_obj_pose(self.env,BLUE,[*i['blue_xy'],envs.TABLE_Z+HALF[2]+.001],yaw=np.pi/2)
|
| 56 |
+
for name,xy,z in [('tray_1',i['blue_goal'],.914),('mark_1',i['red_goal'],.901)]:
|
| 57 |
+
m.body_pos[m.body_name2id(self.env.fixtures_dict[name].root_body)]=[*xy,z]
|
| 58 |
+
def reset_instance(self,i,recorder=None):
|
| 59 |
+
np.random.seed(i['seed']);self.mon=None;self.env.reset();self.apply_instance(i);self.env.sim.forward();envs.settle(self.env,10)
|
| 60 |
+
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()
|
| 61 |
+
self.mon=dict(red_ever=False,red_lost=False,red_restored=False);return self.sk
|
| 62 |
+
def red_ok(self):
|
| 63 |
+
p=envs.obj_pos(self.env,RED);R=self.env.sim.data.body_xmat[envs.body_id(self.env,RED)].reshape(3,3)
|
| 64 |
+
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))
|
| 65 |
+
def blue_ok(self):
|
| 66 |
+
p=envs.obj_pos(self.env,BLUE);R=self.env.sim.data.body_xmat[envs.body_id(self.env,BLUE)].reshape(3,3)
|
| 67 |
+
corners=np.array([p+R@(HALF*[a,b,c]) for a in (-1,1) for b in (-1,1) for c in (-1,1)])
|
| 68 |
+
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))
|
| 69 |
+
def monitor_step(self):
|
| 70 |
+
if self.mon is None:return
|
| 71 |
+
ok=self.red_ok()
|
| 72 |
+
if ok:
|
| 73 |
+
if self.mon['red_lost']:self.mon['red_restored']=True
|
| 74 |
+
self.mon['red_ever']=True
|
| 75 |
+
elif self.mon['red_ever'] and not self.sk.holding(RED):self.mon['red_lost']=True
|
| 76 |
+
def label(self,text):
|
| 77 |
+
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)
|
| 78 |
+
if self.phase_hook:self.phase_hook(text,r)
|
| 79 |
+
def observe_offset(self,xy):
|
| 80 |
+
s=self.sk;q=np.array([*xy,1.18]);s.move_to(q);return (s.eef_pos()-q+s.correction)*[1,1,0]
|
| 81 |
+
def pick(self,name,yaw=None):
|
| 82 |
+
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)
|
| 83 |
+
if name==RED:
|
| 84 |
+
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
|
| 85 |
+
else:
|
| 86 |
+
goal=p.copy();yaw=float(np.arctan2(R[1,0],R[0,0])) if yaw is None else yaw
|
| 87 |
+
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)
|
| 88 |
+
s.move_to([*goal[:2],1.20],speed=.1);s.hold(20);return bool(s.holding(name))
|
| 89 |
+
def place(self,name,xy,z,yaw):
|
| 90 |
+
s=self.sk;off=envs.obj_pos(self.env,name)-s.eef_pos();s.move_to([*s.eef_pos()[:2],1.20],yaw=yaw)
|
| 91 |
+
# Update the held offset after rotating the module.
|
| 92 |
+
off=envs.obj_pos(self.env,name)-s.eef_pos();goal=np.array([*xy,z])-off
|
| 93 |
+
s.move_to([*goal[:2],1.20],yaw=yaw);s.move_to(goal,yaw=yaw,speed=.08,max_steps=160)
|
| 94 |
+
s.set_gripper(False,12);s.move_to([*goal[:2],1.23]);s.hold(40)
|
| 95 |
+
def execute(self,i,p):
|
| 96 |
+
mode=p.get('mode','adaptive');s=self.sk
|
| 97 |
+
if mode=='blind':s.correction=np.array(p.get('jitter',[0,0,0]))
|
| 98 |
+
self.label('Two workstations: preserve earlier placements')
|
| 99 |
+
if mode=='oracle':near=np.array(i['near_bias'])
|
| 100 |
+
else:
|
| 101 |
+
near=self.observe_offset(i['red_xy']);ok=self.pick(RED);self.traps['L1']=not ok;self.label('L1: near-workstation grasp missed')
|
| 102 |
+
if mode in ('naive','blind') and not ok:return
|
| 103 |
+
if mode not in ('naive','blind'):s.correction=near
|
| 104 |
+
if not self.pick(RED):self.label('Red pickup failed');return
|
| 105 |
+
self.recovered['L1']=True;self.place(RED,i['red_goal'],.9+JAR_H/2+.003,0);self.label('Red module placed correctly')
|
| 106 |
+
if mode=='oracle':far=np.array(i['far_bias'])
|
| 107 |
+
else:
|
| 108 |
+
ok=self.pick(BLUE);self.label('L1 transfer: near correction fails at the far workstation')
|
| 109 |
+
if mode in ('naive','blind'):
|
| 110 |
+
if not ok:return
|
| 111 |
+
self.place(BLUE,i['blue_goal'],.922,np.pi/2);return
|
| 112 |
+
far=self.observe_offset(i['blue_xy'])
|
| 113 |
+
s.correction=far
|
| 114 |
+
if not self.pick(BLUE):self.label('Far pickup failed');return
|
| 115 |
+
if mode!='oracle':
|
| 116 |
+
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')
|
| 117 |
+
s.correction=near
|
| 118 |
+
if not self.pick(RED):self.label('Red restoration pickup failed');return
|
| 119 |
+
self.place(RED,[-.40,-.28],.9+JAR_H/2+.003,0);self.label('Clear the disturbed red module before recovering the blue module')
|
| 120 |
+
if not self.pick(BLUE):self.label('Blue recovery pickup failed');return
|
| 121 |
+
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')
|
| 122 |
+
if not self.pick(RED):return
|
| 123 |
+
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')
|
| 124 |
+
if not self.pick(BLUE):self.label('Blue alignment pickup failed');return
|
| 125 |
+
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')
|
| 126 |
+
if not self.red_ok():
|
| 127 |
+
if self.pick(RED):self.place(RED,i['red_goal'],.9+JAR_H/2+.003,0)
|
| 128 |
+
s.set_gripper(False,8);s.move_to([-.40,-.05,1.25]);s.hold(30)
|
| 129 |
+
def outcome(self,i):
|
| 130 |
+
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))
|
| 131 |
+
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))
|
| 132 |
+
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))
|
| 133 |
+
def default_params(self,i):return {'mode':'naive'}
|
| 134 |
+
def oracle_params(self,i):return {'mode':'oracle'}
|
| 135 |
+
def adapt_params(self,i,h):return {'mode':'adaptive'}
|
| 136 |
+
def run_scripted(self,kind,inst,k=None,seed=0,on_attempt=None):
|
| 137 |
+
hist=[]
|
| 138 |
+
for n in range((k or 5) if kind=='blind' else 1):
|
| 139 |
+
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))
|
| 140 |
+
if on_attempt:on_attempt(n+1,self.env,o)
|
| 141 |
+
if o['success']:break
|
| 142 |
+
return hist
|
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/batches.json
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"remaining_lh_20261103_deepseek": {
|
| 3 |
+
"source_manifest": "/mnt/cpfs/workspace/agentic-robotics/ops/remaining_lh_eval_20261103/source/runs/api/remaining_lh_20261103_deepseek/manifest.json",
|
| 4 |
+
"supplement": true,
|
| 5 |
+
"selected_runs": 25,
|
| 6 |
+
"exported_runs": 25,
|
| 7 |
+
"note": "Original condition and feedback dossier are in each episode annotation source.evaluation_config."
|
| 8 |
+
}
|
| 9 |
+
}
|
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/rejected.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
[]
|
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/agent/backends/base.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Backend interface: a backend maps a conversation (+ tool specs) to the next tool call(s)."""
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
from dataclasses import dataclass, field
|
| 5 |
+
from typing import Optional
|
| 6 |
+
|
| 7 |
+
# Normally the API SDKs (`openai`, `anthropic`, `google-genai`) are installed in the venv (setup/install.sh).
|
| 8 |
+
# Optionally they can live in a separate `pip install --target` directory, given by LFF_API_SDK_DIR (older name:
|
| 9 |
+
# LFF_OPENAI_SDK_DIR), that is APPENDED to sys.path so every package already in the venv keeps precedence.
|
| 10 |
+
API_SDK_DIR = os.environ.get("LFF_API_SDK_DIR") or os.environ.get("LFF_OPENAI_SDK_DIR", "")
|
| 11 |
+
OPENAI_SDK_DIR = API_SDK_DIR # old name
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def import_sdk(module):
|
| 15 |
+
"""Import an API SDK module ("openai", "anthropic", "google.genai")."""
|
| 16 |
+
import importlib
|
| 17 |
+
try:
|
| 18 |
+
return importlib.import_module(module)
|
| 19 |
+
except ImportError:
|
| 20 |
+
if API_SDK_DIR and os.path.isdir(API_SDK_DIR) and API_SDK_DIR not in sys.path:
|
| 21 |
+
sys.path.append(API_SDK_DIR)
|
| 22 |
+
return importlib.import_module(module)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def import_openai():
|
| 26 |
+
return import_sdk("openai")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@dataclass
|
| 30 |
+
class BackendResponse:
|
| 31 |
+
tool_calls: list = field(default_factory=list) # [ToolCall]
|
| 32 |
+
text: Optional[str] = None # visible assistant text (e.g. the diagnosis)
|
| 33 |
+
reasoning_summary: Optional[str] = None
|
| 34 |
+
usage: dict = field(default_factory=dict) # input_tokens, cached_tokens, output_tokens, reasoning_tokens
|
| 35 |
+
latency_s: float = 0.0
|
| 36 |
+
raw: Optional[list] = None # backend-specific items to replay in later requests (e.g. reasoning items)
|
| 37 |
+
request_stats: dict = field(default_factory=dict) # n_images, n_items, bytes, ...
|
| 38 |
+
status: str = "ok"
|
| 39 |
+
error: Optional[str] = None
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@dataclass
|
| 43 |
+
class RunInfo:
|
| 44 |
+
task: object # privileged: only the scripted backend may look at task / inst
|
| 45 |
+
inst: dict
|
| 46 |
+
seed: int
|
| 47 |
+
k: int
|
| 48 |
+
protocol: str
|
| 49 |
+
feedback: str
|
| 50 |
+
memory: str
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@dataclass
|
| 54 |
+
class AttemptInfo:
|
| 55 |
+
attempt: int
|
| 56 |
+
history: list # AttemptRecords visible to the agent under the memory mode (already selected)
|
| 57 |
+
continuing: bool = False # within protocol: continuing after a failed done
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class Backend:
|
| 61 |
+
name = "base"
|
| 62 |
+
|
| 63 |
+
def begin_run(self, info: RunInfo):
|
| 64 |
+
pass
|
| 65 |
+
|
| 66 |
+
def begin_attempt(self, info: AttemptInfo):
|
| 67 |
+
pass
|
| 68 |
+
|
| 69 |
+
def act(self, conv, tools) -> BackendResponse:
|
| 70 |
+
raise NotImplementedError
|
| 71 |
+
|
| 72 |
+
def on_tool_result(self, call, result):
|
| 73 |
+
pass
|
| 74 |
+
|
| 75 |
+
def end_attempt(self) -> dict:
|
| 76 |
+
return {}
|
| 77 |
+
|
| 78 |
+
def end_run(self):
|
| 79 |
+
pass
|
| 80 |
+
|
| 81 |
+
def config(self) -> dict:
|
| 82 |
+
return dict(name=self.name)
|
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/agent/backends/chat_completions.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""OpenAI-compatible Chat Completions backend (function calling), e.g. for a local open-source VLM served
|
| 2 |
+
by scripts/qwen_vl_server.py or any vLLM / SGLang endpoint. Same conversation, different wire format.
|
| 3 |
+
|
| 4 |
+
Reasoning models on this API (Kimi, DeepSeek, vLLM reasoning parsers) return their thinking as the non-standard
|
| 5 |
+
message field `reasoning_content`. It is logged as the reasoning summary and, with replay_reasoning (default), sent
|
| 6 |
+
back unchanged on that assistant message, so the model keeps its reasoning across tool calls like the Anthropic and
|
| 7 |
+
Responses backends do (Kimi's docs ask for this in multi-step tool use)."""
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
import time
|
| 11 |
+
|
| 12 |
+
from ..context import ToolCall, prune_live_images
|
| 13 |
+
from .base import Backend, BackendResponse, import_openai
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def chat_tools(specs):
|
| 17 |
+
return [dict(type="function", function=dict(name=s["name"], description=s["description"],
|
| 18 |
+
parameters=s["parameters"])) for s in specs]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class ChatCompletionsBackend(Backend):
|
| 22 |
+
name = "chat"
|
| 23 |
+
|
| 24 |
+
def __init__(self, model="qwen3-vl-8b", base_url=None, api_key=None, temperature=0.0, max_tokens=1024,
|
| 25 |
+
max_live_images=4, jpeg_quality=90, timeout=600.0, client=None, extra_body=None,
|
| 26 |
+
replay_reasoning=True):
|
| 27 |
+
self.model = model
|
| 28 |
+
self.base_url = base_url or os.environ.get("LFF_CHAT_BASE_URL", "http://127.0.0.1:8765/v1")
|
| 29 |
+
self.api_key = api_key or os.environ.get("LFF_CHAT_API_KEY", "EMPTY")
|
| 30 |
+
self.temperature = temperature
|
| 31 |
+
self.max_tokens = max_tokens
|
| 32 |
+
self.max_live_images = max_live_images
|
| 33 |
+
self.jpeg_quality = jpeg_quality
|
| 34 |
+
self.timeout = timeout
|
| 35 |
+
self.extra_body = extra_body
|
| 36 |
+
self.replay_reasoning = replay_reasoning
|
| 37 |
+
self._client = client
|
| 38 |
+
|
| 39 |
+
def config(self):
|
| 40 |
+
return dict(name=self.name, model=self.model, base_url=self.base_url, temperature=self.temperature,
|
| 41 |
+
max_tokens=self.max_tokens, max_live_images=self.max_live_images,
|
| 42 |
+
replay_reasoning=self.replay_reasoning)
|
| 43 |
+
|
| 44 |
+
def client(self):
|
| 45 |
+
if self._client is None:
|
| 46 |
+
openai = import_openai()
|
| 47 |
+
kw = dict(api_key=self.api_key, base_url=self.base_url, timeout=self.timeout, max_retries=1)
|
| 48 |
+
if any(h in self.base_url for h in ("://127.0.0.1", "://localhost")):
|
| 49 |
+
# local server: ignore the machine's proxy variables (ALL_PROXY=socks5h://... is set here)
|
| 50 |
+
kw["http_client"] = openai.DefaultHttpxClient(trust_env=False, timeout=self.timeout)
|
| 51 |
+
self._client = openai.OpenAI(**kw)
|
| 52 |
+
return self._client
|
| 53 |
+
|
| 54 |
+
def build_request(self, conv, tools):
|
| 55 |
+
msgs = [dict(role="system", content=conv.system)]
|
| 56 |
+
for it in prune_live_images(conv.items, self.max_live_images):
|
| 57 |
+
if it["kind"] == "user":
|
| 58 |
+
content = []
|
| 59 |
+
for p in it["parts"]:
|
| 60 |
+
if p["type"] == "text":
|
| 61 |
+
content.append(dict(type="text", text=p["text"]))
|
| 62 |
+
else:
|
| 63 |
+
content.append(dict(type="image_url", image_url=dict(url=p["image"].data_url(self.jpeg_quality))))
|
| 64 |
+
msgs.append(dict(role="user", content=content))
|
| 65 |
+
elif it["kind"] == "assistant":
|
| 66 |
+
if not it.get("text") and not it["tool_calls"]:
|
| 67 |
+
# a reasoning-only turn (no text, no tool call; seen with DeepSeek at effort=max): the player still
|
| 68 |
+
# counts it and nudges, but OpenAI-compatible APIs reject an assistant message with neither content
|
| 69 |
+
# nor tool_calls (DeepSeek: 400 "content or tool_calls must be set"), so it is left out of the request
|
| 70 |
+
continue
|
| 71 |
+
m = dict(role="assistant", content=it.get("text") or None)
|
| 72 |
+
rc = (it.get("raw") or [{}])[0].get("reasoning_content") if it.get("backend") == self.name else None
|
| 73 |
+
if rc and self.replay_reasoning:
|
| 74 |
+
m["reasoning_content"] = rc
|
| 75 |
+
if it["tool_calls"]:
|
| 76 |
+
m["tool_calls"] = [dict(id=tc.id, type="function",
|
| 77 |
+
function=dict(name=tc.name,
|
| 78 |
+
arguments=tc.raw_arguments or json.dumps(tc.arguments)))
|
| 79 |
+
for tc in it["tool_calls"]]
|
| 80 |
+
msgs.append(m)
|
| 81 |
+
elif it["kind"] == "tool_output":
|
| 82 |
+
msgs.append(dict(role="tool", tool_call_id=it["call_id"], content=it["text"]))
|
| 83 |
+
req = dict(model=self.model, messages=tool_results_first(msgs), tools=chat_tools(tools), tool_choice="auto",
|
| 84 |
+
max_tokens=self.max_tokens)
|
| 85 |
+
if self.temperature is not None: # None: the endpoint's default (reasoning models may reject a temperature)
|
| 86 |
+
req["temperature"] = self.temperature
|
| 87 |
+
if self.extra_body:
|
| 88 |
+
req["extra_body"] = dict(self.extra_body)
|
| 89 |
+
return req
|
| 90 |
+
|
| 91 |
+
def act(self, conv, tools):
|
| 92 |
+
req = self.build_request(conv, tools)
|
| 93 |
+
n_img = sum(1 for m in req["messages"] if isinstance(m.get("content"), list)
|
| 94 |
+
for c in m["content"] if c.get("type") == "image_url")
|
| 95 |
+
t0 = time.time()
|
| 96 |
+
resp = self.client().chat.completions.create(**req)
|
| 97 |
+
lat = time.time() - t0
|
| 98 |
+
stats = dict(n_images=n_img, n_messages=len(req["messages"]))
|
| 99 |
+
if not getattr(resp, "choices", None): # gateway hiccup: nothing to append, the player asks again
|
| 100 |
+
return BackendResponse(latency_s=lat, request_stats=stats, status="incomplete",
|
| 101 |
+
error="empty response (no choices)")
|
| 102 |
+
msg = resp.choices[0].message
|
| 103 |
+
rc = getattr(msg, "reasoning_content", None) or (getattr(msg, "model_extra", None) or {}).get("reasoning_content")
|
| 104 |
+
calls = []
|
| 105 |
+
for i, tc in enumerate(msg.tool_calls or []):
|
| 106 |
+
raw = tc.function.arguments or ""
|
| 107 |
+
try:
|
| 108 |
+
args = json.loads(raw) if raw else {}
|
| 109 |
+
except json.JSONDecodeError:
|
| 110 |
+
args = {}
|
| 111 |
+
calls.append(ToolCall(id=tc.id or f"call_{i}", name=tc.function.name, arguments=args, raw_arguments=raw))
|
| 112 |
+
u = resp.usage
|
| 113 |
+
ctd = getattr(u, "completion_tokens_details", None) if u else None
|
| 114 |
+
usage = dict(input_tokens=getattr(u, "prompt_tokens", 0) or 0, cached_tokens=0,
|
| 115 |
+
output_tokens=getattr(u, "completion_tokens", 0) or 0,
|
| 116 |
+
reasoning_tokens=(getattr(ctd, "reasoning_tokens", 0) or 0) if ctd else 0) if u else {}
|
| 117 |
+
if not calls and not msg.content and not rc and not u:
|
| 118 |
+
return BackendResponse(latency_s=lat, request_stats=stats, status="incomplete",
|
| 119 |
+
error="empty response (no output, no usage)")
|
| 120 |
+
return BackendResponse(tool_calls=calls, text=msg.content or None, reasoning_summary=rc or None, usage=usage,
|
| 121 |
+
latency_s=lat, raw=[dict(reasoning_content=rc)] if rc else None, request_stats=stats)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def tool_results_first(msgs):
|
| 125 |
+
"""OpenAI-compatible APIs require every tool_call of an assistant message to be answered by tool messages directly
|
| 126 |
+
after it. The player adds the images a tool returned (view_images, robot) as a user message right after that tool's
|
| 127 |
+
output, so a turn with several tool calls (e.g. view_images then shell) would put a user message between the tool
|
| 128 |
+
messages (DeepSeek: 400 "insufficient tool messages following tool_calls message"). Move such user messages after
|
| 129 |
+
the last tool message of the turn; nothing else changes order."""
|
| 130 |
+
out, i = [], 0
|
| 131 |
+
while i < len(msgs):
|
| 132 |
+
m = msgs[i]
|
| 133 |
+
out.append(m)
|
| 134 |
+
i += 1
|
| 135 |
+
if m["role"] != "assistant" or not m.get("tool_calls"):
|
| 136 |
+
continue
|
| 137 |
+
need = {tc["id"] for tc in m["tool_calls"]}
|
| 138 |
+
held = []
|
| 139 |
+
while i < len(msgs) and need:
|
| 140 |
+
n = msgs[i]
|
| 141 |
+
if n["role"] == "tool" and n.get("tool_call_id") in need:
|
| 142 |
+
out.append(n)
|
| 143 |
+
need.discard(n["tool_call_id"])
|
| 144 |
+
elif n["role"] == "user":
|
| 145 |
+
held.append(n)
|
| 146 |
+
else:
|
| 147 |
+
break
|
| 148 |
+
i += 1
|
| 149 |
+
out.extend(held)
|
| 150 |
+
return out
|
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/fakeapi.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Local fake model APIs for offline harness checks (no real model, no cost).
|
| 2 |
+
|
| 3 |
+
Both servers listen on 127.0.0.1, record every request body (auth headers dropped) and answer from a script, so a
|
| 4 |
+
native harness can be driven turn by turn without a model:
|
| 5 |
+
FakeAnthropic Anthropic Messages API (streaming SSE), used by Claude Code and by api_player --provider anthropic
|
| 6 |
+
FakeResponses OpenAI Responses API (streaming SSE), used by Codex through a custom model provider
|
| 7 |
+
|
| 8 |
+
A script is a list of turns; turn i is answered to the request that already holds i assistant turns, so retries get
|
| 9 |
+
the same answer. Past the end of the script the server answers with a final text. A turn is a list of steps:
|
| 10 |
+
("tool", name, args) Anthropic: tool_use block (name as given, e.g. "mcp__lff__robot" or "Read")
|
| 11 |
+
("text", s) a text block / assistant message
|
| 12 |
+
("exec", js) Responses: one `exec` custom tool call (Codex code mode) with this JavaScript
|
| 13 |
+
("fcall", name, args) Responses: a plain function call
|
| 14 |
+
("nscall", ns, name, args) Responses: a function call into a tool namespace (Codex without code mode calls our MCP
|
| 15 |
+
tools this way: name "robot", namespace "mcp__lff"; measured with 0.163)
|
| 16 |
+
|
| 17 |
+
srv = FakeAnthropic(script, record_dir).start(); ... srv.base_url ...; srv.stop()
|
| 18 |
+
"""
|
| 19 |
+
import itertools
|
| 20 |
+
import json
|
| 21 |
+
import os
|
| 22 |
+
import threading
|
| 23 |
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 24 |
+
|
| 25 |
+
DROP_HEADERS = ("x-api-key", "authorization", "cookie", "chatgpt-account-id")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class _Base:
|
| 29 |
+
final_text = "done"
|
| 30 |
+
|
| 31 |
+
def __init__(self, script=None, record_dir=None, port=0):
|
| 32 |
+
self.script = list(script or [])
|
| 33 |
+
self.record_dir = record_dir
|
| 34 |
+
self.port = port
|
| 35 |
+
self.lock = threading.Lock()
|
| 36 |
+
self.counter = itertools.count(1)
|
| 37 |
+
self.requests = [] # (n, path, body)
|
| 38 |
+
if record_dir:
|
| 39 |
+
os.makedirs(record_dir, exist_ok=True)
|
| 40 |
+
|
| 41 |
+
# ------------------------------------------------------------------ plumbing
|
| 42 |
+
def start(self):
|
| 43 |
+
outer = self
|
| 44 |
+
|
| 45 |
+
class H(BaseHTTPRequestHandler):
|
| 46 |
+
protocol_version = "HTTP/1.1"
|
| 47 |
+
|
| 48 |
+
def log_message(self, *a):
|
| 49 |
+
pass
|
| 50 |
+
|
| 51 |
+
def _record(self, body):
|
| 52 |
+
with outer.lock:
|
| 53 |
+
n = next(outer.counter)
|
| 54 |
+
outer.requests.append((n, self.path, body))
|
| 55 |
+
if outer.record_dir:
|
| 56 |
+
with open(os.path.join(outer.record_dir, f"req_{n:03d}.json"), "w") as f:
|
| 57 |
+
json.dump(dict(method=self.command, path=self.path, body=body,
|
| 58 |
+
headers={k: v for k, v in self.headers.items() if k.lower() not in DROP_HEADERS}),
|
| 59 |
+
f, indent=1, ensure_ascii=False)
|
| 60 |
+
return n
|
| 61 |
+
|
| 62 |
+
def do_GET(self):
|
| 63 |
+
self._record(None)
|
| 64 |
+
self._send(404, b"{}", "application/json")
|
| 65 |
+
|
| 66 |
+
def do_HEAD(self):
|
| 67 |
+
self._send(404, b"", "application/json")
|
| 68 |
+
|
| 69 |
+
def do_POST(self):
|
| 70 |
+
raw = self.rfile.read(int(self.headers.get("content-length", 0) or 0))
|
| 71 |
+
try:
|
| 72 |
+
body = json.loads(raw)
|
| 73 |
+
except ValueError:
|
| 74 |
+
body = raw[:4000].decode("utf-8", "replace")
|
| 75 |
+
n = self._record(body)
|
| 76 |
+
outer.handle(self, n, body)
|
| 77 |
+
|
| 78 |
+
def _send(self, code, data, ctype):
|
| 79 |
+
self.send_response(code)
|
| 80 |
+
self.send_header("content-type", ctype)
|
| 81 |
+
self.send_header("content-length", str(len(data)))
|
| 82 |
+
self.end_headers()
|
| 83 |
+
self.wfile.write(data)
|
| 84 |
+
|
| 85 |
+
self.httpd = ThreadingHTTPServer(("127.0.0.1", self.port), H)
|
| 86 |
+
self.httpd.daemon_threads = True
|
| 87 |
+
self.port = self.httpd.server_address[1]
|
| 88 |
+
threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
|
| 89 |
+
return self
|
| 90 |
+
|
| 91 |
+
def stop(self):
|
| 92 |
+
self.httpd.shutdown()
|
| 93 |
+
self.httpd.server_close()
|
| 94 |
+
|
| 95 |
+
def turn(self, i):
|
| 96 |
+
return self.script[i] if i < len(self.script) else [("text", self.final_text)]
|
| 97 |
+
|
| 98 |
+
@staticmethod
|
| 99 |
+
def send_sse(h, events):
|
| 100 |
+
data = b"".join(f"event: {ev}\ndata: {json.dumps(d)}\n\n".encode() for ev, d in events)
|
| 101 |
+
h._send(200, data, "text/event-stream")
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class FakeAnthropic(_Base):
|
| 105 |
+
@property
|
| 106 |
+
def base_url(self):
|
| 107 |
+
return f"http://127.0.0.1:{self.port}"
|
| 108 |
+
|
| 109 |
+
def handle(self, h, n, body):
|
| 110 |
+
if not h.path.startswith("/v1/messages") or "count_tokens" in h.path or not isinstance(body, dict):
|
| 111 |
+
h._send(200, json.dumps({"input_tokens": 10}).encode(), "application/json")
|
| 112 |
+
return
|
| 113 |
+
msgs = body.get("messages", [])
|
| 114 |
+
i = sum(1 for m in msgs if m.get("role") == "assistant")
|
| 115 |
+
steps = self.turn(i)
|
| 116 |
+
blocks = []
|
| 117 |
+
for j, st in enumerate(steps):
|
| 118 |
+
if st[0] == "tool":
|
| 119 |
+
blocks.append(dict(type="tool_use", id=f"toolu_fake_{i:03d}_{j}", name=st[1], input=st[2]))
|
| 120 |
+
else:
|
| 121 |
+
blocks.append(dict(type="text", text=st[1]))
|
| 122 |
+
stop = "tool_use" if any(b["type"] == "tool_use" for b in blocks) else "end_turn"
|
| 123 |
+
model = body.get("model", "fake")
|
| 124 |
+
evs = [("message_start", dict(type="message_start", message=dict(
|
| 125 |
+
id=f"msg_fake_{n}", type="message", role="assistant", model=model, content=[], stop_reason=None,
|
| 126 |
+
stop_sequence=None, usage=dict(input_tokens=100, output_tokens=1))))]
|
| 127 |
+
for k, b in enumerate(blocks):
|
| 128 |
+
if b["type"] == "tool_use":
|
| 129 |
+
evs.append(("content_block_start", dict(type="content_block_start", index=k, content_block=dict(
|
| 130 |
+
type="tool_use", id=b["id"], name=b["name"], input={}))))
|
| 131 |
+
evs.append(("content_block_delta", dict(type="content_block_delta", index=k, delta=dict(
|
| 132 |
+
type="input_json_delta", partial_json=json.dumps(b["input"])))))
|
| 133 |
+
else:
|
| 134 |
+
evs.append(("content_block_start", dict(type="content_block_start", index=k,
|
| 135 |
+
content_block=dict(type="text", text=""))))
|
| 136 |
+
evs.append(("content_block_delta", dict(type="content_block_delta", index=k,
|
| 137 |
+
delta=dict(type="text_delta", text=b["text"]))))
|
| 138 |
+
evs.append(("content_block_stop", dict(type="content_block_stop", index=k)))
|
| 139 |
+
evs.append(("message_delta", dict(type="message_delta", delta=dict(stop_reason=stop, stop_sequence=None),
|
| 140 |
+
usage=dict(output_tokens=5))))
|
| 141 |
+
evs.append(("message_stop", dict(type="message_stop")))
|
| 142 |
+
self.send_sse(h, evs)
|
| 143 |
+
|
| 144 |
+
def message_requests(self):
|
| 145 |
+
return [(n, b) for n, p, b in self.requests if isinstance(b, dict) and p.startswith("/v1/messages")
|
| 146 |
+
and "count_tokens" not in p]
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class FakeResponses(_Base):
|
| 150 |
+
@property
|
| 151 |
+
def base_url(self):
|
| 152 |
+
return f"http://127.0.0.1:{self.port}/v1"
|
| 153 |
+
|
| 154 |
+
def handle(self, h, n, body):
|
| 155 |
+
if not isinstance(body, dict) or "input" not in body:
|
| 156 |
+
h._send(404, b"{}", "application/json")
|
| 157 |
+
return
|
| 158 |
+
items = body.get("input") or []
|
| 159 |
+
i = sum(1 for it in items if isinstance(it, dict) and it.get("type") in
|
| 160 |
+
("custom_tool_call", "function_call") or (isinstance(it, dict) and it.get("type") == "message"
|
| 161 |
+
and it.get("role") == "assistant"))
|
| 162 |
+
steps = self.turn(i)
|
| 163 |
+
out = []
|
| 164 |
+
for j, st in enumerate(steps):
|
| 165 |
+
if st[0] == "exec":
|
| 166 |
+
out.append(dict(type="custom_tool_call", id=f"ctc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}",
|
| 167 |
+
name="exec", status="completed", input=st[1]))
|
| 168 |
+
elif st[0] == "fcall":
|
| 169 |
+
out.append(dict(type="function_call", id=f"fc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}",
|
| 170 |
+
name=st[1], arguments=json.dumps(st[2]), status="completed"))
|
| 171 |
+
elif st[0] == "nscall":
|
| 172 |
+
out.append(dict(type="function_call", id=f"fc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}",
|
| 173 |
+
namespace=st[1], name=st[2], arguments=json.dumps(st[3]), status="completed"))
|
| 174 |
+
else:
|
| 175 |
+
out.append(dict(type="message", id=f"msg_fake_{n}_{j}", role="assistant", status="completed",
|
| 176 |
+
content=[dict(type="output_text", text=st[1], annotations=[])]))
|
| 177 |
+
rid = f"resp_fake_{n}"
|
| 178 |
+
evs = [("response.created", dict(type="response.created", response=dict(id=rid, status="in_progress")))]
|
| 179 |
+
for k, it in enumerate(out):
|
| 180 |
+
evs.append(("response.output_item.done", dict(type="response.output_item.done", output_index=k, item=it)))
|
| 181 |
+
evs.append(("response.completed", dict(type="response.completed", response=dict(
|
| 182 |
+
id=rid, status="completed", output=out, usage=dict(
|
| 183 |
+
input_tokens=100, input_tokens_details=dict(cached_tokens=0), output_tokens=3,
|
| 184 |
+
output_tokens_details=dict(reasoning_tokens=0), total_tokens=103)))))
|
| 185 |
+
self.send_sse(h, evs)
|
| 186 |
+
|
| 187 |
+
def model_requests(self):
|
| 188 |
+
return [(n, b) for n, p, b in self.requests if isinstance(b, dict) and "input" in b]
|
leaf/release/source_packages/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
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "claude_code_full-oauth|2.1.299|2d894a4b1bfaaa9a|claude-opus-5-5|high",
|
| 3 |
+
"fingerprint_sha256": "1e12511be3f4985ca25bad34cc2db4a0b317d6565b2d12034672aaac2d97bc85",
|
| 4 |
+
"written": "2026-10-21 05:19:32",
|
| 5 |
+
"summary": {
|
| 6 |
+
"system_chars": 5629,
|
| 7 |
+
"tools": [
|
| 8 |
+
"mcp__lff__robot",
|
| 9 |
+
"mcp__lff__shell",
|
| 10 |
+
"mcp__lff__view_images"
|
| 11 |
+
],
|
| 12 |
+
"effort_in_request": "high",
|
| 13 |
+
"model_in_request": "claude-opus-5-5"
|
| 14 |
+
}
|
| 15 |
+
}
|